Merge FFmpeg from upstream for M25.

Merged from d91388367fa64b98a09b45e2b7fb8435a62b7609.

Conflicts:
	configure
	libavcodec/aacdec.c
	libavcodec/ac3tab.h
	libavcodec/dca.h
	libavcodec/dnxhddata.h
	libavcodec/mjpeg.h
	libavcodec/mpeg4audio.h
	libavcodec/mpegaudiodata.h
	libavcodec/raw.h
	libavformat/matroskadec.c
	libavformat/mp3dec.c
	libavutil/aes.h
	libavutil/common.h
	libavutil/intmath.h
	libavutil/md5.h
	libavutil/pixdesc.h
	libavutil/sha.h
	libavutil/tree.h
	library.mak
diff --git a/.gitignore b/.gitignore
index 2046e33..d41ac09 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,10 +3,14 @@
 *.d
 *.def
 *.dll
+*.dylib
 *.exe
+*.exp
 *.h.c
+*.ilk
 *.lib
 *.pc
+*.pdb
 *.so
 *.so.*
 *.ver
@@ -22,6 +26,7 @@
 /config.*
 /version.h
 /doc/*.1
+/doc/*.3
 /doc/*.html
 /doc/*.pod
 /doc/avoptions_codec.texi
@@ -34,8 +39,8 @@
 /doc/examples/muxing
 /doc/examples/scaling_video
 /doc/fate.txt
+/doc/doxy/html/
 /doc/print_options
-/doxy/
 /libavcodec/*_tablegen
 /libavcodec/*_tables.c
 /libavcodec/*_tables.h
@@ -51,6 +56,8 @@
 /tools/ffbisect
 /tools/bisect.need
 /tools/cws2fws
+/tools/fourcc2pixfmt
+/tools/ffescape
 /tools/ffeval
 /tools/graph2dot
 /tools/ismindex
diff --git a/Changelog b/Changelog
index bb62a1b..31981d2 100644
--- a/Changelog
+++ b/Changelog
@@ -1,11 +1,42 @@
 Entries are sorted chronologically from oldest to youngest within each release,
 releases are sorted from youngest to oldest.
 
-version next:
+version <next>:
+
 - stream disposition information printing in ffprobe
+- filter for loudness analysis following EBU R128
+- Opus encoder using libopus
+- ffprobe -select_streams option
+- Pinnacle TARGA CineWave YUV16 decoder
+- TAK demuxer, decoder and parser
+- DTS-HD demuxer
+- remove -same_quant, it hasn't worked for years
+- FFM2 support
+- X-Face image encoder and decoder
+- 24-bit FLAC encoding
+- metadata (INFO tag) support in WAV muxer
+- subtitles raw text decoder
+- support for building DLLs using MSVC
+- LVF demuxer
+- ffescape tool
+- metadata (info chunk) support in CAF muxer
+- field filter ported from libmpcodecs
+- AVR demuxer
+- geq filter ported from libmpcodecs
+- remove ffserver daemon mode
+- AST demuxer
+- new expansion syntax for drawtext
+- BRender PIX image decoder
+- ffprobe -show_entries option
+- ffprobe -sections option
+- ADPCM IMA Dialogic decoder
+- BRSTM demuxer
+- animated GIF decoder and demuxer
+- PVF demuxer
 
 
 version 1.0:
+
 - INI and flat output in ffprobe
 - Scene detection in libavfilter
 - Indeo Audio decoder
@@ -68,6 +99,7 @@
 - WebVTT demuxer and decoder (simple tags supported)
 - RTP packetization of JPEG
 - faststart option in the MOV/MP4 muxer
+- support for building with MSVC
 
 
 version 0.11:
diff --git a/LICENSE b/LICENSE
index b98b5d3..a1204f4 100644
--- a/LICENSE
+++ b/LICENSE
@@ -23,13 +23,18 @@
   libswresample/swresample-test.c
 - the texi2pod.pl tool
 - the following filters in libavfilter:
+    - f_ebur128.c
     - vf_blackframe.c
     - vf_boxblur.c
     - vf_colormatrix.c
     - vf_cropdetect.c
+    - vf_decimate.c
     - vf_delogo.c
+    - vf_geq.c
     - vf_hqdn3d.c
+    - vf_hue.c
     - vf_mp.c
+    - vf_smartblur.c
     - vf_super2xsai.c
     - vf_tinterlace.c
     - vf_yadif.c
diff --git a/MAINTAINERS b/MAINTAINERS
index b361543..724b30c 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -270,7 +270,7 @@
   libdc1394.c                           Roman Shaposhnik
   v4l2.c                                Luca Abeni
   vfwcap.c                              Ramiro Polla
-
+  dshow.c                               Roger Pack
 
 libavfilter
 ===========
@@ -322,7 +322,7 @@
   idroqdec.c                            Mike Melanson
   iff.c                                 Jaikrishnan Menon
   ipmovie.c                             Mike Melanson
-  img2.c                                Michael Niedermayer
+  img2*.c                               Michael Niedermayer
   iss.c                                 Stefan Gehrer
   jacosub*                              Clément Bœsch
   jvdec.c                               Peter Ross
@@ -443,4 +443,4 @@
 Sascha Sommer                 38A0 F88B 868E 9D3A 97D4 D6A0 E823 706F 1E07 0D3C
 Stefano Sabatini              9A43 10F8 D32C D33C 48E7 C52C 5DF2 8E4D B2EE 066B
 Stephan Hilb                  4F38 0B3A 5F39 B99B F505 E562 8D5C 5554 4E17 8863
-Tomas Härdin                  D133 29CA 4EEC 9DB4 7076 F697 B04B 7403 3313 41FD
+Tomas Härdin                  A79D 4E3D F38F 763F 91F5 8B33 A01E 8AE0 41BB 2551
diff --git a/Makefile b/Makefile
index 53db626..fcb7e55 100644
--- a/Makefile
+++ b/Makefile
@@ -17,7 +17,8 @@
 
 PROGS      := $(PROGS-yes:%=%$(PROGSSUF)$(EXESUF))
 INSTPROGS   = $(PROGS-yes:%=%$(PROGSSUF)$(EXESUF))
-OBJS        = cmdutils.o
+
+OBJS        = cmdutils.o $(EXEOBJS)
 OBJS-ffmpeg = ffmpeg_opt.o ffmpeg_filter.o
 TESTTOOLS   = audiogen videogen rotozoom tiny_psnr base64
 HOSTPROGS  := $(TESTTOOLS:%=tests/%) doc/print_options
@@ -41,7 +42,7 @@
 FFLIBS := avutil
 
 DATA_FILES := $(wildcard $(SRC_PATH)/presets/*.ffpreset) $(SRC_PATH)/doc/ffprobe.xsd
-EXAMPLES_FILES := $(wildcard $(SRC_PATH)/doc/examples/*.c) $(SRC_PATH)/doc/examples/Makefile
+EXAMPLES_FILES := $(wildcard $(SRC_PATH)/doc/examples/*.c) $(SRC_PATH)/doc/examples/Makefile $(SRC_PATH)/doc/examples/README
 
 SKIPHEADERS = cmdutils_common_opts.h
 
@@ -56,8 +57,8 @@
 	$(CP) $< $@
 	$(STRIP) $@
 
-$(TOOLS): %$(EXESUF): %.o
-	$(LD) $(LDFLAGS) $(LD_O) $< $(ELIBS)
+$(TOOLS): %$(EXESUF): %.o $(EXEOBJS)
+	$(LD) $(LDFLAGS) $(LD_O) $^ $(ELIBS)
 
 tools/cws2fws$(EXESUF): ELIBS = $(ZLIB)
 
@@ -68,9 +69,9 @@
 	@-tput sgr0 2>/dev/null
 
 SUBDIR_VARS := CLEANFILES EXAMPLES FFLIBS HOSTPROGS TESTPROGS TOOLS      \
-               ARCH_HEADERS BUILT_HEADERS SKIPHEADERS                    \
+               HEADERS ARCH_HEADERS BUILT_HEADERS SKIPHEADERS            \
                ARMV5TE-OBJS ARMV6-OBJS ARMVFP-OBJS NEON-OBJS             \
-               MMI-OBJS ALTIVEC-OBJS VIS-OBJS                            \
+               ALTIVEC-OBJS VIS-OBJS                                     \
                MMX-OBJS YASM-OBJS                                        \
                MIPSFPU-OBJS MIPSDSPR2-OBJS MIPSDSPR1-OBJS MIPS32R2-OBJS  \
                OBJS HOSTOBJS TESTOBJS
@@ -91,8 +92,8 @@
 $(foreach D,$(FFLIBS),$(eval $(call DOSUBDIR,lib$(D))))
 
 define DOPROG
-OBJS-$(1) += $(1).o
-$(1)$(PROGSSUF)_g$(EXESUF): $(OBJS-$(1))
+OBJS-$(1) += $(1).o cmdutils.o $(EXEOBJS)
+$(1)$(PROGSSUF)_g$(EXESUF): $$(OBJS-$(1))
 $$(OBJS-$(1)): CFLAGS  += $(CFLAGS-$(1))
 $(1)$(PROGSSUF)_g$(EXESUF): LDFLAGS += $(LDFLAGS-$(1))
 $(1)$(PROGSSUF)_g$(EXESUF): FF_EXTRALIBS += $(LIBS-$(1))
@@ -101,8 +102,8 @@
 
 $(foreach P,$(PROGS-yes),$(eval $(call DOPROG,$(P))))
 
-%$(PROGSSUF)_g$(EXESUF): %.o cmdutils.o $(FF_DEP_LIBS)
-	$(LD) $(LDFLAGS) $(LD_O) $(OBJS-$*) cmdutils.o $(FF_EXTRALIBS)
+%$(PROGSSUF)_g$(EXESUF): %.o $(FF_DEP_LIBS)
+	$(LD) $(LDFLAGS) $(LD_O) $(OBJS-$*) $(FF_EXTRALIBS)
 
 OBJDIRS += tools
 
diff --git a/OWNERS b/OWNERS
index e5c04a2..7ae97eb 100644
--- a/OWNERS
+++ b/OWNERS
@@ -1,10 +1,6 @@
 acolwell@chromium.org
-annacc@chromium.org
 dalecurtis@chromium.org
 ddorwin@chormium.org
-enal@chromium.org
-fischman@chromium.org
-imasaki@chromium.org
 scherkus@chromium.org
 shadi@chromium.org
-vrk@chromium.org
+xhwang@chromium.org
diff --git a/RELEASE b/RELEASE
index 4402ec2..014ccf1 100644
--- a/RELEASE
+++ b/RELEASE
@@ -1 +1 @@
-1.0.git
+1.0.git
\ No newline at end of file
diff --git a/arch.mak b/arch.mak
index 6ccdfa0..79c9e2b 100644
--- a/arch.mak
+++ b/arch.mak
@@ -3,7 +3,6 @@
 OBJS-$(HAVE_ARMVFP)  += $(ARMVFP-OBJS)  $(ARMVFP-OBJS-yes)
 OBJS-$(HAVE_NEON)    += $(NEON-OBJS)    $(NEON-OBJS-yes)
 
-OBJS-$(HAVE_MMI)     += $(MMI-OBJS)     $(MMI-OBJS-yes)
 OBJS-$(HAVE_MIPSFPU)   += $(MIPSFPU-OBJS)    $(MIPSFPU-OBJS-yes)
 OBJS-$(HAVE_MIPS32R2)  += $(MIPS32R2-OBJS)   $(MIPS32R2-OBJS-yes)
 OBJS-$(HAVE_MIPSDSPR1) += $(MIPSDSPR1-OBJS)  $(MIPSDSPR1-OBJS-yes)
diff --git a/chromium/patches/ugly/08_disable_aac_sample_skipping.patch b/chromium/patches/ugly/08_disable_aac_sample_skipping.patch
deleted file mode 100644
index 252d228..0000000
--- a/chromium/patches/ugly/08_disable_aac_sample_skipping.patch
+++ /dev/null
@@ -1,32 +0,0 @@
-From eeba29fa7321bcec47f4d4ff0d6f32f31bd11e3d Mon Sep 17 00:00:00 2001
-From: Dale Curtis <dalecurtis@chromium.org>
-Date: Tue, 24 Jul 2012 18:11:43 -0700
-Subject: [PATCH] Disable AAC sample skipping.
-
-Currently non-Apple encoders aren't supported and this change chops
-off more samples than necessary for these files.
-
-See http://ffmpeg.org/pipermail/ffmpeg-devel/2012-July/127834.html
-
-BUG=none
-TEST=http://rtoy.github.com/webaudio/codec-tests/plot-audio.html
----
- libavformat/mov.c | 2 +-
- 1 file changed, 1 insertion(+), 1 deletion(-)
-
-diff --git a/libavformat/mov.c b/libavformat/mov.c
-index b4295f8..1795707 100644
---- a/libavformat/mov.c
-+++ b/libavformat/mov.c
-@@ -2979,7 +2979,7 @@ static int mov_read_header(AVFormatContext *s)
-         AVStream *st = s->streams[i];
-         MOVStreamContext *sc = st->priv_data;
-         if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == CODEC_ID_AAC) {
--            sc->start_pad = 2112;
-+            sc->start_pad = 0; // 2112; TODO(dalecurtis): Disabled until non-Apple encoders are supported.
-             st->skip_samples = sc->start_pad;
-         }
-     }
--- 
-1.7.11.2
-
diff --git a/cmdutils.c b/cmdutils.c
index 5639751..fd8ff50 100644
--- a/cmdutils.c
+++ b/cmdutils.c
@@ -41,6 +41,7 @@
 #endif
 #include "libavutil/avassert.h"
 #include "libavutil/avstring.h"
+#include "libavutil/bprint.h"
 #include "libavutil/mathematics.h"
 #include "libavutil/imgutils.h"
 #include "libavutil/parseutils.h"
@@ -54,9 +55,12 @@
 #include "libavformat/network.h"
 #endif
 #if HAVE_SYS_RESOURCE_H
+#include <sys/time.h>
 #include <sys/resource.h>
 #endif
 
+static int init_report(const char *env);
+
 struct SwsContext *sws_opts;
 SwrContext *swr_opts;
 AVDictionary *format_opts, *codec_opts;
@@ -126,7 +130,7 @@
     else
         return d;
     av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
-    exit_program(1);
+    exit(1);
     return 0;
 }
 
@@ -137,7 +141,7 @@
     if (av_parse_time(&us, timestr, is_duration) < 0) {
         av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
                is_duration ? "duration" : "date", context, timestr);
-        exit_program(1);
+        exit(1);
     }
     return us;
 }
@@ -196,7 +200,7 @@
     return po;
 }
 
-#if defined(_WIN32) && !defined(__MINGW32CE__)
+#if HAVE_COMMANDLINETOARGVW
 #include <windows.h>
 #include <shellapi.h>
 /* Will be leaked on exit */
@@ -256,7 +260,7 @@
 {
     /* nothing to do */
 }
-#endif /* WIN32 && !__MINGW32CE__ */
+#endif /* HAVE_COMMANDLINETOARGVW */
 
 int parse_option(void *optctx, const char *opt, const char *arg,
                  const OptionDef *options)
@@ -325,7 +329,7 @@
         }
     }
     if (po->flags & OPT_EXIT)
-        exit_program(0);
+        exit(0);
     return !!(po->flags & HAS_ARG);
 }
 
@@ -351,7 +355,7 @@
             opt++;
 
             if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
-                exit_program(1);
+                exit(1);
             optindex += ret;
         } else {
             if (parse_arg_function)
@@ -380,7 +384,7 @@
              (po->name && !strcmp(optname, po->name)))
             return i;
 
-        if (!po || po->flags & HAS_ARG)
+        if (po->flags & HAS_ARG)
             i++;
     }
     return 0;
@@ -413,13 +417,14 @@
 void parse_loglevel(int argc, char **argv, const OptionDef *options)
 {
     int idx = locate_option(argc, argv, options, "loglevel");
+    const char *env;
     if (!idx)
         idx = locate_option(argc, argv, options, "v");
     if (idx && argv[idx + 1])
         opt_loglevel(NULL, "loglevel", argv[idx + 1]);
     idx = locate_option(argc, argv, options, "report");
-    if (idx || getenv("FFREPORT")) {
-        opt_report("report");
+    if ((env = getenv("FFREPORT")) || idx) {
+        init_report(env);
         if (report_file) {
             int i;
             fprintf(report_file, "Command line:\n");
@@ -436,9 +441,11 @@
 int opt_default(void *optctx, const char *opt, const char *arg)
 {
     const AVOption *o;
+    int consumed = 0;
     char opt_stripped[128];
     const char *p;
-    const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class(), *sc, *swr_class;
+    const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class();
+    const AVClass *sc, *swr_class;
 
     if (!(p = strchr(opt, ':')))
         p = opt + strlen(opt);
@@ -447,36 +454,44 @@
     if ((o = av_opt_find(&cc, opt_stripped, NULL, 0,
                          AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
         ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
-         (o = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ))))
+         (o = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ)))) {
         av_dict_set(&codec_opts, opt, arg, FLAGS);
-    else if ((o = av_opt_find(&fc, opt, NULL, 0,
-                              AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
+        consumed = 1;
+    }
+    if ((o = av_opt_find(&fc, opt, NULL, 0,
+                              AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
         av_dict_set(&format_opts, opt, arg, FLAGS);
+        if(consumed)
+            av_log(NULL, AV_LOG_VERBOSE, "Routing %s to codec and muxer layer\n", opt);
+        consumed = 1;
+    }
 #if CONFIG_SWSCALE
     sc = sws_get_class();
-    if (!o && (o = av_opt_find(&sc, opt, NULL, 0,
-                         AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
+    if (!consumed && av_opt_find(&sc, opt, NULL, 0,
+                         AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) {
         // XXX we only support sws_flags, not arbitrary sws options
         int ret = av_opt_set(sws_opts, opt, arg, 0);
         if (ret < 0) {
             av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
             return ret;
         }
+        consumed = 1;
     }
 #endif
 #if CONFIG_SWRESAMPLE
     swr_class = swr_get_class();
-    if (!o && (o = av_opt_find(&swr_class, opt, NULL, 0,
-                               AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
+    if (!consumed && av_opt_find(&swr_class, opt, NULL, 0,
+                               AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) {
         int ret = av_opt_set(swr_opts, opt, arg, 0);
         if (ret < 0) {
             av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
             return ret;
         }
+        consumed = 1;
     }
 #endif
 
-    if (o)
+    if (consumed)
         return 0;
     av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
     return AVERROR_OPTION_NOT_FOUND;
@@ -511,30 +526,89 @@
                "Possible levels are numbers or:\n", arg);
         for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
             av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
-        exit_program(1);
+        exit(1);
     }
     av_log_set_level(level);
     return 0;
 }
 
-int opt_report(const char *opt)
+static void expand_filename_template(AVBPrint *bp, const char *template,
+                                     struct tm *tm)
 {
-    char filename[64];
+    int c;
+
+    while ((c = *(template++))) {
+        if (c == '%') {
+            if (!(c = *(template++)))
+                break;
+            switch (c) {
+            case 'p':
+                av_bprintf(bp, "%s", program_name);
+                break;
+            case 't':
+                av_bprintf(bp, "%04d%02d%02d-%02d%02d%02d",
+                           tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
+                           tm->tm_hour, tm->tm_min, tm->tm_sec);
+                break;
+            case '%':
+                av_bprint_chars(bp, c, 1);
+                break;
+            }
+        } else {
+            av_bprint_chars(bp, c, 1);
+        }
+    }
+}
+
+static int init_report(const char *env)
+{
+    char *filename_template = NULL;
+    char *key, *val;
+    int ret, count = 0;
     time_t now;
     struct tm *tm;
+    AVBPrint filename;
 
     if (report_file) /* already opened */
         return 0;
     time(&now);
     tm = localtime(&now);
-    snprintf(filename, sizeof(filename), "%s-%04d%02d%02d-%02d%02d%02d.log",
-             program_name,
-             tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
-             tm->tm_hour, tm->tm_min, tm->tm_sec);
-    report_file = fopen(filename, "w");
+
+    while (env && *env) {
+        if ((ret = av_opt_get_key_value(&env, "=", ":", 0, &key, &val)) < 0) {
+            if (count)
+                av_log(NULL, AV_LOG_ERROR,
+                       "Failed to parse FFREPORT environment variable: %s\n",
+                       av_err2str(ret));
+            break;
+        }
+        if (*env)
+            env++;
+        count++;
+        if (!strcmp(key, "file")) {
+            av_free(filename_template);
+            filename_template = val;
+            val = NULL;
+        } else {
+            av_log(NULL, AV_LOG_ERROR, "Unknown key '%s' in FFREPORT\n", key);
+        }
+        av_free(val);
+        av_free(key);
+    }
+
+    av_bprint_init(&filename, 0, 1);
+    expand_filename_template(&filename,
+                             av_x_if_null(filename_template, "%p-%t.log"), tm);
+    av_free(filename_template);
+    if (!av_bprint_is_complete(&filename)) {
+        av_log(NULL, AV_LOG_ERROR, "Out of memory building report file name\n");
+        return AVERROR(ENOMEM);
+    }
+
+    report_file = fopen(filename.str, "w");
     if (!report_file) {
         av_log(NULL, AV_LOG_ERROR, "Failed to open report \"%s\": %s\n",
-               filename, strerror(errno));
+               filename.str, strerror(errno));
         return AVERROR(errno);
     }
     av_log_set_callback(log_callback_report);
@@ -544,11 +618,17 @@
            program_name,
            tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
            tm->tm_hour, tm->tm_min, tm->tm_sec,
-           filename);
+           filename.str);
     av_log_set_level(FFMAX(av_log_get_level(), AV_LOG_VERBOSE));
+    av_bprint_finalize(&filename, NULL);
     return 0;
 }
 
+int opt_report(const char *opt)
+{
+    return init_report(NULL);
+}
+
 int opt_max_alloc(void *optctx, const char *opt, const char *arg)
 {
     char *tail;
@@ -557,7 +637,7 @@
     max = strtol(arg, &tail, 10);
     if (*tail) {
         av_log(NULL, AV_LOG_FATAL, "Invalid max_alloc \"%s\".\n", arg);
-        exit_program(1);
+        exit(1);
     }
     av_max_alloc(max);
     return 0;
@@ -691,12 +771,13 @@
 
 int show_license(void *optctx, const char *opt, const char *arg)
 {
-    printf(
 #if CONFIG_NONFREE
+    printf(
     "This version of %s has nonfree parts compiled in.\n"
     "Therefore it is not legally redistributable.\n",
-    program_name
+    program_name );
 #elif CONFIG_GPLV3
+    printf(
     "%s is free software; you can redistribute it and/or modify\n"
     "it under the terms of the GNU General Public License as published by\n"
     "the Free Software Foundation; either version 3 of the License, or\n"
@@ -709,8 +790,9 @@
     "\n"
     "You should have received a copy of the GNU General Public License\n"
     "along with %s.  If not, see <http://www.gnu.org/licenses/>.\n",
-    program_name, program_name, program_name
+    program_name, program_name, program_name );
 #elif CONFIG_GPL
+    printf(
     "%s is free software; you can redistribute it and/or modify\n"
     "it under the terms of the GNU General Public License as published by\n"
     "the Free Software Foundation; either version 2 of the License, or\n"
@@ -724,8 +806,9 @@
     "You should have received a copy of the GNU General Public License\n"
     "along with %s; if not, write to the Free Software\n"
     "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
-    program_name, program_name, program_name
+    program_name, program_name, program_name );
 #elif CONFIG_LGPLV3
+    printf(
     "%s is free software; you can redistribute it and/or modify\n"
     "it under the terms of the GNU Lesser General Public License as published by\n"
     "the Free Software Foundation; either version 3 of the License, or\n"
@@ -738,8 +821,9 @@
     "\n"
     "You should have received a copy of the GNU Lesser General Public License\n"
     "along with %s.  If not, see <http://www.gnu.org/licenses/>.\n",
-    program_name, program_name, program_name
+    program_name, program_name, program_name );
 #else
+    printf(
     "%s is free software; you can redistribute it and/or\n"
     "modify it under the terms of the GNU Lesser General Public\n"
     "License as published by the Free Software Foundation; either\n"
@@ -753,9 +837,8 @@
     "You should have received a copy of the GNU Lesser General Public\n"
     "License along with %s; if not, write to the Free Software\n"
     "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
-    program_name, program_name, program_name
+    program_name, program_name, program_name );
 #endif
-    );
 
     return 0;
 }
@@ -810,7 +893,7 @@
 
 #define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
     if (codec->field) {                                                      \
-        const type *p = c->field;                                            \
+        const type *p = codec->field;                                        \
                                                                              \
         printf("    Supported " list_name ":");                              \
         while (*p != term) {                                                 \
@@ -851,8 +934,8 @@
         }
         printf("\n");
     }
-    PRINT_CODEC_SUPPORTED(c, pix_fmts, enum PixelFormat, "pixel formats",
-                          PIX_FMT_NONE, GET_PIX_FMT_NAME);
+    PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",
+                          AV_PIX_FMT_NONE, GET_PIX_FMT_NAME);
     PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
                           GET_SAMPLE_RATE_NAME);
     PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
@@ -908,8 +991,8 @@
     while ((desc = avcodec_descriptor_next(desc)))
         nb_codecs++;
     if (!(codecs = av_calloc(nb_codecs, sizeof(*codecs)))) {
-        av_log(0, AV_LOG_ERROR, "Out of memory\n");
-        exit_program(1);
+        av_log(NULL, AV_LOG_ERROR, "Out of memory\n");
+        exit(1);
     }
     desc = NULL;
     while ((desc = avcodec_descriptor_next(desc)))
@@ -1094,7 +1177,7 @@
 
 int show_pix_fmts(void *optctx, const char *opt, const char *arg)
 {
-    enum PixelFormat pix_fmt;
+    const AVPixFmtDescriptor *pix_desc = NULL;
 
     printf("Pixel formats:\n"
            "I.... = Supported Input  format for conversion\n"
@@ -1110,8 +1193,8 @@
 #   define sws_isSupportedOutput(x) 0
 #endif
 
-    for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++) {
-        const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[pix_fmt];
+    while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
+        enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
         if(!pix_desc->name)
             continue;
         printf("%c%c%c%c%c %-16s       %d            %2d\n",
@@ -1303,6 +1386,11 @@
     fseek(f, 0, SEEK_END);
     *size = ftell(f);
     fseek(f, 0, SEEK_SET);
+    if (*size == (size_t)-1) {
+        av_log(NULL, AV_LOG_ERROR, "IO error: %s\n", strerror(errno));
+        fclose(f);
+        return AVERROR(errno);
+    }
     *bufptr = av_malloc(*size + 1);
     if (!*bufptr) {
         av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
@@ -1320,7 +1408,7 @@
             ret = AVERROR_EOF;
     } else {
         ret = 0;
-        (*bufptr)[*size++] = '\0';
+        (*bufptr)[(*size)++] = '\0';
     }
 
     fclose(f);
@@ -1467,13 +1555,13 @@
 {
     if (new_size >= INT_MAX / elem_size) {
         av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
-        exit_program(1);
+        exit(1);
     }
     if (*size < new_size) {
         uint8_t *tmp = av_realloc(array, new_size*elem_size);
         if (!tmp) {
             av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
-            exit_program(1);
+            exit(1);
         }
         memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
         *size = new_size;
@@ -1484,13 +1572,19 @@
 
 static int alloc_buffer(FrameBuffer **pool, AVCodecContext *s, FrameBuffer **pbuf)
 {
-    FrameBuffer  *buf = av_mallocz(sizeof(*buf));
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
+    FrameBuffer *buf;
     int i, ret;
-    const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
+    int pixel_size;
     int h_chroma_shift, v_chroma_shift;
     int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
     int w = s->width, h = s->height;
 
+    if (!desc)
+        return AVERROR(EINVAL);
+    pixel_size = desc->comp[0].step_minus1 + 1;
+
+    buf = av_mallocz(sizeof(*buf));
     if (!buf)
         return AVERROR(ENOMEM);
 
diff --git a/cmdutils.h b/cmdutils.h
index d78eb55..931b634 100644
--- a/cmdutils.h
+++ b/cmdutils.h
@@ -139,7 +139,7 @@
     } u;
 } SpecifierOpt;
 
-typedef struct {
+typedef struct OptionDef {
     const char *name;
     int flags;
 #define HAS_ARG    0x0001
@@ -204,6 +204,8 @@
  * Parse the command line arguments.
  *
  * @param optctx an opaque options context
+ * @param argc   number of command line arguments
+ * @param argv   values of command line arguments
  * @param options Array with the definitions required to interpret every
  * option of the form: -option_name [argument]
  * @param parse_arg_function Name of the function called to process every
@@ -249,6 +251,8 @@
  * Create a new options dictionary containing only the options from
  * opts which apply to the codec with ID codec_id.
  *
+ * @param opts     dictionary to place options in
+ * @param codec_id ID of the codec that should be filtered for
  * @param s Corresponding format context.
  * @param st A stream from s for which the options should be filtered.
  * @param codec The particular codec for which the options should be filtered.
@@ -382,6 +386,7 @@
  * Read the file with name filename, and put its content in a newly
  * allocated 0-terminated buffer.
  *
+ * @param filename file to read from
  * @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
@@ -411,17 +416,13 @@
                       const char *preset_name, int is_path, const char *codec_name);
 
 /**
- * Do all the necessary cleanup and abort.
- * This function is implemented in the avtools, not cmdutils.
- */
-av_noreturn void exit_program(int ret);
-
-/**
  * Realloc array to hold new_size elements of elem_size.
- * Calls exit_program() on failure.
+ * Calls exit() on failure.
  *
+ * @param array array to reallocate
  * @param elem_size size in bytes of each element
  * @param size new element count will be written here
+ * @param new_size number of elements to place in reallocated array
  * @return reallocated array
  */
 void *grow_array(void *array, int elem_size, int *size, int new_size);
@@ -432,7 +433,7 @@
     int  linesize[4];
 
     int h, w;
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
 
     int refcount;
     struct FrameBuffer **pool;  ///< head of the buffer pool
diff --git a/common.mak b/common.mak
index dd5de7a..0c48484 100644
--- a/common.mak
+++ b/common.mak
@@ -30,7 +30,7 @@
 CCFLAGS     = $(CPPFLAGS) $(CFLAGS)
 ASFLAGS    := $(CPPFLAGS) $(ASFLAGS)
 CXXFLAGS   += $(CPPFLAGS) $(CFLAGS)
-YASMFLAGS  += $(IFLAGS:%=%/) -I$(SRC_PATH)/libavutil/x86/ -Pconfig.asm
+YASMFLAGS  += $(IFLAGS:%=%/) -Pconfig.asm
 
 HOSTCCFLAGS = $(IFLAGS) $(HOSTCFLAGS)
 LDFLAGS    := $(ALLFFLIBS:%=$(LD_PATH)lib%) $(LDFLAGS)
@@ -56,6 +56,9 @@
 %.o: %.S
 	$(COMPILE_S)
 
+%.i: %.c
+	$(CC) $(CCFLAGS) $(CC_E) $<
+
 %.h.c:
 	$(Q)echo '#include "$*.h"' >$@
 
@@ -94,6 +97,7 @@
 TOOLS     += $(TOOLS-yes)
 TOOLOBJS  := $(TOOLS:%=tools/%.o)
 TOOLS     := $(TOOLS:%=tools/%$(EXESUF))
+HEADERS   += $(HEADERS-yes)
 
 DEP_LIBS := $(foreach NAME,$(FFLIBS),lib$(NAME)/$($(CONFIG_SHARED:yes=S)LIBNAME))
 
diff --git a/compat/getopt.c b/compat/getopt.c
index 019049f..dd082ea 100644
--- a/compat/getopt.c
+++ b/compat/getopt.c
@@ -46,7 +46,7 @@
     int c;
     char *cp;
 
-    if (sp == 1)
+    if (sp == 1) {
         if (optind >= argc ||
             argv[optind][0] != '-' || argv[optind][1] == '\0')
             return EOF;
@@ -54,6 +54,7 @@
             optind++;
             return EOF;
         }
+    }
     optopt = c = argv[optind][sp];
     if (c == ':' || (cp = strchr(opts, c)) == NULL) {
         fprintf(stderr, ": illegal option -- %c\n", c);
diff --git a/compat/plan9/head b/compat/plan9/head
new file mode 100755
index 0000000..2840b2d
--- /dev/null
+++ b/compat/plan9/head
@@ -0,0 +1,10 @@
+#!/bin/sh
+
+n=10
+
+case "$1" in
+    -n)  n=$2;      shift 2 ;;
+    -n*) n=${1#-n}; shift   ;;
+esac
+
+exec sed ${n}q "$@"
diff --git a/libavutil/symbols.h b/compat/plan9/main.c
similarity index 66%
copy from libavutil/symbols.h
copy to compat/plan9/main.c
index 6011da2..d46f96d 100644
--- a/libavutil/symbols.h
+++ b/compat/plan9/main.c
@@ -1,6 +1,4 @@
 /*
- * Copyright (c) 2012 Ronald S. Bultje <rsbultje@gmail.com>
- *
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
@@ -18,15 +16,19 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#ifndef AVUTIL_SYMBOLS_H
-#define AVUTIL_SYMBOLS_H
+int plan9_main(int argc, char **argv);
 
-#include "libavutil/avconfig.h"
-
-#if AV_HAVE_SHARED_LIBS && defined(_MSC_VER) && !defined(COMPILING_avutil)
-#define AVUTIL_SYMBOL __declspec(dllimport)
-#else
-#define AVUTIL_SYMBOL
+#undef main
+int main(int argc, char **argv)
+{
+    /* The setfcr() function in lib9 is broken, must use asm. */
+#ifdef __i386
+    short fcr;
+    __asm__ volatile ("fstcw        %0 \n"
+                      "or      $63, %0 \n"
+                      "fldcw        %0 \n"
+                      : "=m"(fcr));
 #endif
 
-#endif /* AVUTIL_SYMBOLS_H */
+    return plan9_main(argc, argv);
+}
diff --git a/compat/plan9/printf b/compat/plan9/printf
new file mode 100755
index 0000000..1a70a9e
--- /dev/null
+++ b/compat/plan9/printf
@@ -0,0 +1,2 @@
+#!/bin/sh
+exec awk "BEGIN { for (i = 2; i < ARGC; i++) printf \"$1\", ARGV[i] }" "$@"
diff --git a/compat/tms470/math.h b/compat/tms470/math.h
new file mode 100644
index 0000000..1104d74
--- /dev/null
+++ b/compat/tms470/math.h
@@ -0,0 +1,7 @@
+#include_next <math.h>
+
+#undef INFINITY
+#undef NAN
+
+#define INFINITY (*(const float*)((const unsigned []){ 0x7f800000 }))
+#define NAN      (*(const float*)((const unsigned []){ 0x7fc00000 }))
diff --git a/configure b/configure
index 2828956..588104f 100755
--- a/configure
+++ b/configure
@@ -54,6 +54,8 @@
     exit 1
 fi
 
+test -d /usr/xpg4/bin && PATH=/usr/xpg4/bin:$PATH
+
 show_help(){
     cat <<EOF
 Usage: configure [options]
@@ -76,6 +78,7 @@
 Standard options:
   --logfile=FILE           log tests and output to FILE [config.log]
   --disable-logging        do not log configure debug information
+  --fatal-warnings         fail if any configure warning is generated
   --prefix=PREFIX          install in PREFIX [$prefix]
   --bindir=DIR             install binaries in DIR [PREFIX/bin]
   --datadir=DIR            install data files in DIR [PREFIX/share/ffmpeg]
@@ -99,6 +102,13 @@
   --enable-gray            enable full grayscale support (slower color)
   --disable-swscale-alpha  disable alpha channel support in swscale
 
+Program options:
+  --disable-programs       do not build command line programs
+  --disable-ffmpeg         disable ffmpeg build
+  --disable-ffplay         disable ffplay build
+  --disable-ffprobe        disable ffprobe build
+  --disable-ffserver       disable ffserver build
+
 Documentation options:
   --disable-doc            do not build documentation
   --disable-htmlpages      do not build HTML documentation pages
@@ -107,13 +117,10 @@
   --disable-txtpages       do not build text documentation pages
 
 Component options:
-  --disable-ffmpeg         disable ffmpeg build
-  --disable-ffplay         disable ffplay build
-  --disable-ffprobe        disable ffprobe build
-  --disable-ffserver       disable ffserver build
   --disable-avdevice       disable libavdevice build
   --disable-avcodec        disable libavcodec build
   --disable-avformat       disable libavformat build
+  --disable-avutil         disable libavutil build
   --disable-swresample     disable libswresample build
   --disable-swscale        disable libswscale build
   --disable-postproc       disable libpostproc build
@@ -127,6 +134,7 @@
   --disable-dct            disable DCT code
   --disable-dwt            disable DWT code
   --disable-lsp            disable LSP code
+  --disable-lzo            disable LZO decoder code
   --disable-mdct           disable MDCT code
   --disable-rdft           disable RDFT code
   --disable-fft            disable FFT code
@@ -268,6 +276,7 @@
                            disable buffer boundary checking in bitreaders
                            (faster, but may crash)
   --enable-memalign-hack   emulate memalign, interferes with memory debuggers
+  --enable-lto             use link-time optimization
 
 Optimization options (experts only):
   --disable-asm            disable all assembler optimizations
@@ -288,7 +297,6 @@
   --disable-armv6          disable armv6 optimizations
   --disable-armv6t2        disable armv6t2 optimizations
   --disable-armvfp         disable ARM VFP optimizations
-  --disable-mmi            disable MMI optimizations
   --disable-neon           disable NEON optimizations
   --disable-vis            disable VIS optimizations
   --disable-inline-asm     disable use of inline assembler
@@ -314,6 +322,7 @@
   --valgrind=VALGRIND      run "make fate" tests through valgrind to detect memory
                            leaks and errors, using the specified valgrind binary.
                            Cannot be combined with --target-exec
+  --enable-ftrapv          Trap arithmetic overflows
   --samples=PATH           location of test samples for FATE, if not set use
                            \$FATE_SAMPLES at make invocation time.
   --enable-xmm-clobber-test check XMM registers for clobbering (Win64-only;
@@ -608,39 +617,36 @@
     done
 }
 
-print_config_h(){
-    enabled $1 && v=1 || v=0
-    echo "#define $2 $v"
-}
-
-print_config_mak(){
-    enabled $1 && v= || v=!
-    echo "$v$2=yes"
-}
-
-print_config_asm(){
-    enabled $1 && v=1 || v=0
-    echo "%define $2 $v"
-}
-
 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
+    map 'eval echo "$v \${$v:-no}"' "$@" |
+    awk "BEGIN { split(\"$files\", files) }
+        {
+            c = \"$pfx\" toupper(\$1);
+            v = \$2;
+            sub(/yes/, 1, v);
+            sub(/no/,  0, v);
+            for (f in files) {
+                file = files[f];
+                if (file ~ /\\.h\$/) {
+                    printf(\"#define %s %d\\n\", c, v) >>file;
+                } else if (file ~ /\\.asm\$/) {
+                    printf(\"%%define %s %d\\n\", c, v) >>file;
+                } else if (file ~ /\\.mak\$/) {
+                    n = -v ? \"\" : \"!\";
+                    printf(\"%s%s=yes\\n\", n, c) >>file;
+                }
+            }
+        }"
 }
 
 print_enabled(){
-    test "$1" = -n && end=" " && shift || end="\n"
     suf=$1
     shift
     for v; do
-        enabled $v && printf "%s$end" ${v%$suf};
+        enabled $v && printf "%s\n" ${v%$suf};
     done
 }
 
@@ -688,6 +694,12 @@
     append host_ldflags $($host_ldflags_filter "$@")
 }
 
+add_compat(){
+    append compat_objs $1
+    shift
+    map 'add_cppflags -D$v' "$@"
+}
+
 check_cmd(){
     log "$@"
     "$@" >> $logfile 2>&1
@@ -760,11 +772,8 @@
     log check_ld "$@"
     type=$1
     shift 1
-    flags=''
-    libs=''
-    for f; do
-        test "${f}" = "${f#-l}" && flags="$flags $f" || libs="$libs $f"
-    done
+    flags=$(filter_out '-l*' $@)
+    libs=$(filter '-l*' $@)
     check_$type $($cflags_filter $flags) || return
     flags=$($ldflags_filter $flags)
     libs=$($ldflags_filter $libs)
@@ -845,11 +854,13 @@
 check_mathfunc(){
     log check_mathfunc "$@"
     func=$1
-    shift
+    narg=$2
+    shift 2
+    test $narg = 2 && args="f, g" || args="f"
     disable $func
     check_ld "cc" "$@" <<EOF && enable $func
 #include <math.h>
-float foo(float f) { return $func(f); }
+float foo(float f, float g) { return $func($args); }
 int main(void){ return (int) foo; }
 EOF
 }
@@ -1053,7 +1064,7 @@
 cp_if_changed(){
     cmp -s "$1" "$2" && echo "$2 is unchanged" && return
     mkdir -p "$(dirname $2)"
-    cp -f "$1" "$2"
+    $cp_f "$1" "$2"
 }
 
 # CONFIG_LIST contains configurable options, while HAVE_LIST is for
@@ -1081,6 +1092,17 @@
     txtpages
 "
 
+LIBRARY_LIST="
+    avcodec
+    avdevice
+    avfilter
+    avformat
+    avresample
+    avutil
+    swresample
+    swscale
+"
+
 PROGRAM_LIST="
     ffplay
     ffprobe
@@ -1091,12 +1113,8 @@
 CONFIG_LIST="
     $COMPONENT_LIST
     $DOCUMENT_LIST
+    $LIBRARY_LIST
     $PROGRAM_LIST
-    avcodec
-    avdevice
-    avfilter
-    avformat
-    avresample
     avisynth
     bzlib
     crystalhd
@@ -1107,6 +1125,7 @@
     fft
     fontconfig
     frei0r
+    ftrapv
     gnutls
     gpl
     gray
@@ -1151,6 +1170,7 @@
     libxavs
     libxvid
     lsp
+    lzo
     mdct
     memalign_hack
     memory_poisoning
@@ -1167,8 +1187,6 @@
     small
     sram
     static
-    swresample
-    swscale
     swscale_alpha
     thumb
     vaapi
@@ -1187,6 +1205,7 @@
 '
 
 ARCH_LIST='
+    aarch64
     alpha
     arm
     avr32
@@ -1204,12 +1223,23 @@
     sh4
     sparc
     sparc64
+    tilegx
+    tilepro
     tomi
     x86
     x86_32
     x86_64
 '
 
+ARCH_EXT_LIST_ARM='
+    armv5te
+    armv6
+    armv6t2
+    armvfp
+    neon
+    vfpv3
+'
+
 ARCH_EXT_LIST_X86='
     amd3dnow
     amd3dnowext
@@ -1226,16 +1256,10 @@
 '
 
 ARCH_EXT_LIST="
+    $ARCH_EXT_LIST_ARM
     $ARCH_EXT_LIST_X86
     altivec
-    armv5te
-    armv6
-    armv6t2
-    armvfp
-    mmi
-    neon
     ppc4xx
-    vfpv3
     vis
     mipsfpu
     mips32r2
@@ -1243,18 +1267,54 @@
     mipsdspr2
 "
 
+HAVE_LIST_CMDLINE='
+    inline_asm
+    symver
+    yasm
+'
+
 HAVE_LIST_PUB='
     bigendian
     fast_unaligned
     incompatible_fork_abi
 '
 
+MATH_FUNCS="
+    atanf
+    atan2f
+    cbrtf
+    cosf
+    exp2
+    exp2f
+    expf
+    isinf
+    isnan
+    ldexpf
+    llrint
+    llrintf
+    log2
+    log2f
+    log10f
+    lrint
+    lrintf
+    powf
+    rint
+    round
+    roundf
+    sinf
+    trunc
+    truncf
+"
+
 HAVE_LIST="
     $ARCH_EXT_LIST
     $(add_suffix _external $ARCH_EXT_LIST)
     $(add_suffix _inline   $ARCH_EXT_LIST)
+    $HAVE_LIST_CMDLINE
     $HAVE_LIST_PUB
     $THREADS_LIST
+    $MATH_FUNCS
+    access
     aligned_malloc
     aligned_stack
     alsa_asoundlib_h
@@ -1265,13 +1325,12 @@
     asm_types_h
     attribute_may_alias
     attribute_packed
-    broken_snprintf
-    cbrtf
     clock_gettime
     closesocket
     cmov
-    cpuid
+    CommandLineToArgvW
     cpunop
+    CryptGenRandom
     dcbzl
     dev_bktr_ioctl_bt848_h
     dev_bktr_ioctl_meteor_h
@@ -1285,8 +1344,6 @@
     dxva_h
     ebp_available
     ebx_available
-    exp2
-    exp2f
     fast_64bit
     fast_clz
     fast_cmov
@@ -1300,31 +1357,23 @@
     GetProcessTimes
     GetSystemTimeAsFileTime
     getrusage
+    getservbyport
     gettimeofday
     glob
     gnu_as
     ibm_asm
     inet_aton
-    inline_asm
     io_h
     isatty
-    isinf
-    isnan
     jack_port_get_latency_range
     kbhit
     ldbrx
     libdc1394_1
     libdc1394_2
-    llrint
-    llrintf
     local_aligned_16
     local_aligned_8
     localtime_r
-    log2
-    log2f
     loongson
-    lrint
-    lrintf
     lzo1x_999_compress
     machine_ioctl_bt848_h
     machine_ioctl_meteor_h
@@ -1335,6 +1384,7 @@
     mkstemp
     mm_empty
     mmap
+    mprotect
     msvcrt
     nanosleep
     PeekNamedPipe
@@ -1344,13 +1394,10 @@
     posix_memalign
     pthread_cancel
     rdtsc
-    rint
-    round
-    roundf
-    rweflags
     sched_getaffinity
     sdl
     sdl_video_size
+    SetConsoleTextAttribute
     setmode
     setrlimit
     Sleep
@@ -1369,7 +1416,6 @@
     struct_sockaddr_sa_len
     struct_sockaddr_storage
     struct_v4l2_frmivalenum_discrete
-    symver
     symver_asm_label
     symver_gnu_asm
     sysconf
@@ -1384,8 +1430,6 @@
     termios_h
     texi2html
     threads
-    trunc
-    truncf
     unistd_h
     usleep
     vfp_args
@@ -1393,16 +1437,13 @@
     windows_h
     winsock2_h
     xform_asm
-    xgetbv
     xmm_clobbers
-    yasm
 "
 
 # options emitted with CONFIG_ prefix but not available on command line
 CONFIG_EXTRA="
     aandcttables
     ac3dsp
-    avutil
     error_resilience
     gcrypt
     golomb
@@ -1414,6 +1455,7 @@
     huffman
     lgplv3
     lpc
+    mpegaudio
     mpegaudiodsp
     mpegvideo
     mpegvideoenc
@@ -1427,18 +1469,17 @@
 CMDLINE_SELECT="
     $ARCH_EXT_LIST
     $CONFIG_LIST
+    $HAVE_LIST_CMDLINE
     $THREADS_LIST
     asm
     coverage
     cross_compile
     debug
     extra_warnings
-    inline_asm
     logging
+    lto
     optimizations
     stripping
-    symver
-    yasm
 "
 
 PATHS_LIST='
@@ -1512,7 +1553,6 @@
 mips32r2_deps="mips"
 mipsdspr1_deps="mips"
 mipsdspr2_deps="mips"
-mmi_deps="mips"
 
 altivec_deps="ppc"
 ppc4xx_deps="ppc"
@@ -1561,6 +1601,7 @@
 dct_select="rdft"
 mdct_select="fft"
 rdft_select="fft"
+mpegaudio_select="mpegaudiodsp"
 mpegaudiodsp_select="dct"
 mpegvideoenc_select="mpegvideo"
 
@@ -1580,7 +1621,9 @@
 binkaudio_dct_decoder_select="mdct rdft dct sinewin"
 binkaudio_rdft_decoder_select="mdct rdft sinewin"
 cavs_decoder_select="golomb mpegvideo"
+comfortnoise_encoder_select="lpc"
 cook_decoder_select="mdct sinewin"
+cscd_decoder_select="lzo"
 cscd_decoder_suggest="zlib"
 dca_decoder_select="mdct"
 dirac_decoder_select="dwt golomb"
@@ -1630,16 +1673,16 @@
 mdec_decoder_select="error_resilience mpegvideo"
 mjpeg_encoder_select="aandcttables mpegvideoenc"
 mlp_decoder_select="mlp_parser"
-mp1_decoder_select="mpegaudiodsp"
-mp1float_decoder_select="mpegaudiodsp"
-mp2_decoder_select="mpegaudiodsp"
-mp2float_decoder_select="mpegaudiodsp"
-mp3_decoder_select="mpegaudiodsp"
-mp3adu_decoder_select="mpegaudiodsp"
-mp3adufloat_decoder_select="mpegaudiodsp"
-mp3float_decoder_select="mpegaudiodsp"
-mp3on4_decoder_select="mpegaudiodsp"
-mp3on4float_decoder_select="mpegaudiodsp"
+mp1_decoder_select="mpegaudio"
+mp1float_decoder_select="mpegaudio"
+mp2_decoder_select="mpegaudio"
+mp2float_decoder_select="mpegaudio"
+mp3_decoder_select="mpegaudio"
+mp3adu_decoder_select="mpegaudio"
+mp3adufloat_decoder_select="mpegaudio"
+mp3float_decoder_select="mpegaudio"
+mp3on4_decoder_select="mpegaudio"
+mp3on4float_decoder_select="mpegaudio"
 mpc7_decoder_select="mpegaudiodsp"
 mpc8_decoder_select="mpegaudiodsp"
 mpeg_vdpau_decoder_select="vdpau mpegvideo_decoder"
@@ -1671,6 +1714,7 @@
 mss2_decoder_select="vc1_decoder"
 nellymoser_decoder_select="mdct sinewin"
 nellymoser_encoder_select="mdct sinewin"
+nuv_decoder_select="lzo"
 png_decoder_select="zlib"
 png_encoder_select="zlib"
 qcelp_decoder_select="lsp"
@@ -1768,6 +1812,7 @@
 libopenjpeg_decoder_deps="libopenjpeg"
 libopenjpeg_encoder_deps="libopenjpeg"
 libopus_decoder_deps="libopus"
+libopus_encoder_deps="libopus"
 libschroedinger_decoder_deps="libschroedinger"
 libschroedinger_encoder_deps="libschroedinger"
 libspeex_decoder_deps="libspeex"
@@ -1793,14 +1838,17 @@
 asf_stream_muxer_select="asf_muxer"
 avisynth_demuxer_deps="avisynth"
 dirac_demuxer_select="dirac_parser"
+dts_demuxer_select="dca_parser"
+dtshd_demuxer_select="dca_parser"
 eac3_demuxer_select="ac3_parser"
 f4v_muxer_select="mov_muxer"
 flac_demuxer_select="flac_parser"
 ipod_muxer_select="mov_muxer"
+ismv_muxer_select="mov_muxer"
 libnut_demuxer_deps="libnut"
 libnut_muxer_deps="libnut"
 matroska_audio_muxer_select="matroska_muxer"
-matroska_demuxer_suggest="zlib bzlib"
+matroska_demuxer_suggest="bzlib lzo zlib"
 mov_demuxer_suggest="zlib"
 mp3_demuxer_select="mpegaudio_parser"
 mp4_muxer_select="mov_muxer"
@@ -1819,6 +1867,7 @@
 sdp_demuxer_select="rtpdec"
 smoothstreaming_muxer_select="ismv_muxer"
 spdif_muxer_select="aac_parser"
+tak_demuxer_select="tak_parser"
 tg2_muxer_select="mov_muxer"
 tgp_muxer_select="mov_muxer"
 w64_demuxer_deps="wav_demuxer"
@@ -1901,12 +1950,15 @@
 delogo_filter_deps="gpl"
 deshake_filter_deps="avcodec"
 drawtext_filter_deps="libfreetype"
+ebur128_filter_deps="gpl"
 flite_filter_deps="libflite"
 frei0r_filter_deps="frei0r dlopen"
 frei0r_filter_extralibs='$ldl'
 frei0r_src_filter_deps="frei0r dlopen"
 frei0r_src_filter_extralibs='$ldl'
+geq_filter_deps="gpl"
 hqdn3d_filter_deps="gpl"
+hue_filter_deps="gpl"
 movie_filter_deps="avcodec avformat"
 mp_filter_deps="gpl avcodec swscale postproc inline_asm"
 mptestsrc_filter_deps="gpl"
@@ -1917,7 +1969,7 @@
 removelogo_filter_deps="avcodec avformat swscale"
 scale_filter_deps="swscale"
 smartblur_filter_deps="gpl swscale"
-showspectrum_filter_deps="avcodec"
+showspectrum_filter_deps="avcodec rdft"
 super2xsai_filter_deps="gpl"
 tinterlace_filter_deps="gpl"
 yadif_filter_deps="gpl"
@@ -1926,9 +1978,13 @@
 tinterlace_pad_test_deps="tinterlace_filter"
 
 # libraries
-avdevice_deps="avcodec avformat"
-avformat_deps="avcodec"
+avcodec_deps="avutil"
+avdevice_deps="avutil avcodec avformat"
+avfilter_deps="avutil"
+avformat_deps="avutil avcodec"
+avresample_deps="avutil"
 postproc_deps="gpl"
+swscale_deps="avutil"
 
 # programs
 ffmpeg_deps="avcodec avfilter avformat swscale swresample"
@@ -1947,58 +2003,6 @@
 txtpages_deps="makeinfo"
 doc_deps_any="manpages htmlpages podpages txtpages"
 
-# tests
-colormatrix1_test_deps="colormatrix_filter"
-colormatrix2_test_deps="colormatrix_filter"
-mpg_test_deps="mpeg1system_muxer mpegps_demuxer"
-png_test_deps="zlib"
-pp_test_deps="mp_filter"
-pp2_test_deps="mp_filter"
-pp3_test_deps="mp_filter"
-pp4_test_deps="mp_filter"
-pp5_test_deps="mp_filter"
-pp6_test_deps="mp_filter"
-seek_flashsv_flv_test_deps="zlib"
-seek_lavf_mxf_d10_test_deps="mxf_d10_test"
-
-test_deps(){
-    suf1=$1
-    suf2=$2
-    shift 2
-    for v; do
-        dep=${v%=*}
-        tests=${v#*=}
-        for name in ${tests}; do
-            append ${name}_test_deps ${dep}$suf1 ${dep}$suf2
-        done
-    done
-}
-
-test_deps _muxer _demuxer                                               \
-    aiff                                                                \
-    pcm_alaw=alaw                                                       \
-    asf                                                                 \
-    au                                                                  \
-    avi                                                                 \
-    dv=dv_fmt                                                           \
-    ffm                                                                 \
-    flv=flv_fmt                                                         \
-    gxf                                                                 \
-    matroska=mkv                                                        \
-    mmf                                                                 \
-    mov="mov ismv"                                                      \
-    pcm_mulaw=mulaw                                                     \
-    mxf="mxf mxf_d10"                                                   \
-    nut                                                                 \
-    ogg="ogg ogg_vp3"                                                   \
-    rawvideo=pixfmt                                                     \
-    rm                                                                  \
-    swf                                                                 \
-    mpegts=ts                                                           \
-    voc                                                                 \
-    wav                                                                 \
-    yuv4mpegpipe=yuv4mpeg                                               \
-
 # default parameters
 
 logfile="config.log"
@@ -2018,6 +2022,7 @@
 cc_default="gcc"
 cxx_default="g++"
 host_cc_default="gcc"
+cp_f="cp -f"
 install="install"
 ln_s="ln -sf"
 nm_default="nm -g"
@@ -2046,16 +2051,9 @@
 # configurable options
 enable $PROGRAM_LIST
 enable $DOCUMENT_LIST
-
-enable avcodec
-enable avdevice
-enable avfilter
-enable avformat
-enable avutil
+enable $(filter_out avresample $LIBRARY_LIST)
 enable postproc
 enable stripping
-enable swresample
-enable swscale
 
 enable asm
 enable debug
@@ -2164,24 +2162,13 @@
     $PROTOCOL_LIST
 "
 
-find_tests(){
-    map "echo ${2}\${v}_test" $(ls "$source_path"/tests/ref/$1 | grep -v '[^-a-z0-9_]')
-}
-
-LAVF_FATE_TESTS=$(find_tests lavf-fate)
-LAVF_TESTS=$(find_tests lavf)
-LAVFI_TESTS=$(find_tests lavfi)
-SEEK_TESTS=$(find_tests seek seek_)
-
-ALL_TESTS="$LAVF_FATE_TESTS $LAVF_TESTS $LAVFI_TESTS $SEEK_TESTS"
-
 for n in $COMPONENT_LIST; do
     v=$(toupper ${n%s})_LIST
     eval enable \$$v
     eval ${n}_if_any="\$$v"
 done
 
-enable $ARCH_EXT_LIST $ALL_TESTS
+enable $ARCH_EXT_LIST
 
 die_unknown(){
     echo "Unknown option \"$1\"."
@@ -2220,63 +2207,70 @@
 for opt do
     optval="${opt#*=}"
     case "$opt" in
-    --extra-ldflags=*) add_ldflags $optval
-    ;;
-    --extra-libs=*) add_extralibs $optval
-    ;;
-    --disable-devices) disable $INDEV_LIST $OUTDEV_LIST
-    ;;
-    --enable-debug=*) debuglevel="$optval"
-    ;;
-    --disable-everything)
-    map 'eval unset \${$(toupper ${v%s})_LIST}' $COMPONENT_LIST
-    ;;
-    --enable-random|--disable-random)
-    action=${opt%%-random}
-    do_random ${action#--} $COMPONENT_LIST
-    ;;
-    --enable-random=*|--disable-random=*)
-    action=${opt%%-random=*}
-    do_random ${action#--} $optval
-    ;;
-    --enable-*=*|--disable-*=*)
-    eval $(echo "${opt%%=*}" | sed 's/--/action=/;s/-/ thing=/')
-    is_in "${thing}s" $COMPONENT_LIST || die_unknown "$opt"
-    eval list=\$$(toupper $thing)_LIST
-    name=$(echo "${optval}" | sed "s/,/_${thing}|/g")_${thing}
-    $action $(filter "$name" $list)
-    ;;
-    --enable-?*|--disable-?*)
-    eval $(echo "$opt" | sed 's/--/action=/;s/-/ option=/;s/-/_/g')
-    if is_in $option $COMPONENT_LIST; then
-        test $action = disable && action=unset
-        eval $action \$$(toupper ${option%s})_LIST
-    elif is_in $option $CMDLINE_SELECT; then
-        $action $option
-    else
-        die_unknown $opt
-    fi
-    ;;
-    --list-*)
-        NAME="${opt#--list-}"
-        is_in $NAME $COMPONENT_LIST || die_unknown $opt
-        NAME=${NAME%s}
-        eval show_list $NAME \$$(toupper $NAME)_LIST
-    ;;
-    --help|-h) show_help
-    ;;
-    *)
-    optname="${opt%%=*}"
-    optname="${optname#--}"
-    optname=$(echo "$optname" | sed 's/-/_/g')
-    if is_in $optname $CMDLINE_SET; then
-        eval $optname='$optval'
-    elif is_in $optname $CMDLINE_APPEND; then
-        append $optname "$optval"
-    else
-         die_unknown $opt
-    fi
-    ;;
+        --extra-ldflags=*) add_ldflags $optval
+        ;;
+        --extra-libs=*) add_extralibs $optval
+        ;;
+        --disable-devices) disable $INDEV_LIST $OUTDEV_LIST
+        ;;
+        --enable-debug=*) debuglevel="$optval"
+        ;;
+        --disable-programs)
+            disable $PROGRAM_LIST
+        ;;
+        --disable-everything)
+            map 'eval unset \${$(toupper ${v%s})_LIST}' $COMPONENT_LIST
+        ;;
+        --enable-random|--disable-random)
+            action=${opt%%-random}
+            do_random ${action#--} $COMPONENT_LIST
+        ;;
+        --enable-random=*|--disable-random=*)
+            action=${opt%%-random=*}
+            do_random ${action#--} $optval
+        ;;
+        --enable-*=*|--disable-*=*)
+            eval $(echo "${opt%%=*}" | sed 's/--/action=/;s/-/ thing=/')
+            is_in "${thing}s" $COMPONENT_LIST || die_unknown "$opt"
+            eval list=\$$(toupper $thing)_LIST
+            name=$(echo "${optval}" | sed "s/,/_${thing}|/g")_${thing}
+            list=$(filter "$name" $list)
+            [ "$list" = "" ] && warn "Option $opt did not match anything"
+            $action $list
+        ;;
+        --enable-?*|--disable-?*)
+            eval $(echo "$opt" | sed 's/--/action=/;s/-/ option=/;s/-/_/g')
+            if is_in $option $COMPONENT_LIST; then
+                test $action = disable && action=unset
+                eval $action \$$(toupper ${option%s})_LIST
+            elif is_in $option $CMDLINE_SELECT; then
+                $action $option
+            else
+                die_unknown $opt
+            fi
+        ;;
+        --list-*)
+            NAME="${opt#--list-}"
+            is_in $NAME $COMPONENT_LIST || die_unknown $opt
+            NAME=${NAME%s}
+            eval show_list $NAME \$$(toupper $NAME)_LIST
+        ;;
+        --help|-h) show_help
+        ;;
+        --fatal-warnings) enable fatal_warnings
+        ;;
+        *)
+            optname="${opt%%=*}"
+            optname="${optname#--}"
+            optname=$(echo "$optname" | sed 's/-/_/g')
+            if is_in $optname $CMDLINE_SET; then
+                eval $optname='$optval'
+            elif is_in $optname $CMDLINE_APPEND; then
+                append $optname "$optval"
+            else
+                die_unknown $opt
+            fi
+        ;;
     esac
 done
 
@@ -2292,7 +2286,7 @@
         die "Must specify target arch and OS when cross-compiling"
 fi
 
-set_default arch target_os postproc_version
+set_default postproc_version
 
 # Check if we should build alternative libpostproc version instead of current
 if   test "$postproc_version" = $ALT_PP_VER; then
@@ -2315,18 +2309,29 @@
 sysinclude_default="${sysroot}/usr/include"
 
 case "$toolchain" in
+    clang-asan)
+        cc_default="clang"
+        add_cflags  -faddress-sanitizer
+        add_ldflags -faddress-sanitizer
+    ;;
+    clang-tsan)
+        cc_default="clang"
+        add_cflags  -fthread-sanitizer
+        add_ldflags -fthread-sanitizer
+    ;;
     msvc)
         cc_default="c99wrap cl"
         ld_default="c99wrap link"
         nm_default="dumpbin -symbols"
         ar_default="lib"
+        target_os_default="win32"
     ;;
     ?*)
         die "Unknown toolchain $toolchain"
     ;;
 esac
 
-set_default cc cxx pkg_config strip sysinclude yasmexe
+set_default arch cc cxx pkg_config strip sysinclude target_os yasmexe
 enabled cross_compile || host_cc_default=$cc
 set_default host_cc
 
@@ -2337,7 +2342,7 @@
 
 exesuf() {
     case $1 in
-        mingw32*|cygwin*|*-dos|freedos|opendos|os/2*|symbian) echo .exe ;;
+        mingw32*|win32|win64|cygwin*|*-dos|freedos|opendos|os/2*|symbian) echo .exe ;;
     esac
 }
 
@@ -2394,6 +2399,24 @@
     die "Sanity test failed."
 fi
 
+ccc_flags(){
+    for flag; do
+        case $flag in
+            -std=c99)           echo -c99                       ;;
+            -mcpu=*)            echo -arch ${flag#*=}           ;;
+            -mieee)             echo -ieee                      ;;
+            -O*|-fast)          echo $flag                      ;;
+            -fno-math-errno)    echo -assume nomath_errno       ;;
+            -g)                 echo -g3                        ;;
+            -Wall)              echo -msg_enable level2         ;;
+            -Wno-pointer-sign)  echo -msg_disable ptrmismatch1  ;;
+            -Wl,*)              echo $flag                      ;;
+            -f*|-W*)                                            ;;
+            *)                  echo $flag                      ;;
+        esac
+   done
+}
+
 msvc_flags(){
     for flag; do
         case $flag in
@@ -2402,12 +2425,15 @@
             -Wall)                echo -W4 -wd4244 -wd4127 -wd4018 -wd4389 \
                                        -wd4146 -wd4057 -wd4204 -wd4706 -wd4305 \
                                        -wd4152 -wd4324 -we4013 -wd4100 -wd4214 \
-                                       -wd4996 -wd4554 ;;
+                                       -wd4554 \
+                                       -wd4996 -wd4273 ;;
             -std=c99)             ;;
             -fno-math-errno)      ;;
             -fno-common)          ;;
             -fno-signed-zeros)    ;;
             -lz)                  echo zlib.lib ;;
+            -lavifil32)           echo vfw32.lib ;;
+            -lavicap32)           echo vfw32.lib user32.lib ;;
             -l*)                  echo ${flag#-l}.lib ;;
             *)                    echo $flag ;;
         esac
@@ -2417,6 +2443,7 @@
 pgi_flags(){
     for flag; do
         case $flag in
+            -flto)                echo -Mipa=fast,libopt,libinline,vestigial ;;
             -fomit-frame-pointer) echo -Mnoframe ;;
             -g)                   echo -gopt ;;
             *)                    echo $flag ;;
@@ -2441,6 +2468,8 @@
                     prescott|nocona)    echo -xarch=sse3 -xchip=pentium4 ;;
                     *-sse3)             echo -xarch=sse3                 ;;
                     core2)              echo -xarch=ssse3 -xchip=core2   ;;
+                    corei7)           echo -xarch=sse4_2 -xchip=nehalem  ;;
+                    corei7-avx)       echo -xarch=avx -xchip=sandybridge ;;
                     amdfam10|barcelona|bdver*) echo -xarch=sse4_1        ;;
                     athlon-4|athlon-[mx]p)    echo -xarch=ssea           ;;
                     k8|opteron|athlon64|athlon-fx)
@@ -2475,6 +2504,7 @@
             -mfpu=neon)     echo --float_support=vfpv3 --neon ;;
             -mfpu=vfp)      echo --float_support=vfpv2        ;;
             -mfpu=vfpv3)    echo --float_support=vfpv3        ;;
+            -mfpu=vfpv3-d16) echo --float_support=vfpv3d16    ;;
             -msoft-float)   echo --float_support=vfplib       ;;
             -O[0-3]|-mf=*)  echo $flag                        ;;
             -g)             echo -g -mn                       ;;
@@ -2530,10 +2560,9 @@
         _type=ccc
         _ident=$($_cc -V | head -n1 | cut -d' ' -f1-3)
         _DEPFLAGS='-M'
-        debuglevel=3
-        _ldflags='-Wl,-z,now' # calls to libots crash without this
         _cflags_speed='-fast'
         _cflags_size='-O1'
+        _flags_filter=ccc_flags
     elif $_cc --vsn 2>/dev/null | grep -q "ARM C/C++ Compiler"; then
         test -d "$sysroot" || die "No valid sysroot specified."
         _type=armcc
@@ -2554,11 +2583,8 @@
         _type=tms470
         _ident=$($_cc -version | head -n1 | tr -s ' ')
         _flags='--gcc --abi=eabi -me'
-        _cflags='-D__gnuc_va_list=va_list -D__USER_LABEL_PREFIX__='
         _cc_e='-ppl -fe=$@'
         _cc_o='-fe=$@'
-        as_default="${cross_prefix}gcc"
-        ld_default="${cross_prefix}gcc"
         _depflags='-ppa -ppd=$(@:.o=.d)'
         _cflags_speed='-O3 -mf=5'
         _cflags_size='-O3 -mf=2'
@@ -2595,7 +2621,7 @@
     elif $_cc -V 2>&1 | grep -q Portland; then
         _type=pgi
         _ident="PGI $($_cc -V 2>&1 | awk '/^pgcc/ { print $2; exit }')"
-        opt_common='-alias=ansi -Mlre -Mpre'
+        opt_common='-alias=ansi -Mdse -Mlre -Mpre'
         _cflags_speed="-O3 -Mautoinline -Munroll=c:4 $opt_common"
         _cflags_size="-O2 -Munroll=c:1 $opt_common"
         _cflags_noopt="-O1"
@@ -2616,7 +2642,7 @@
         _cc_o='-Fo $@'
         _cc_e='-P -Fi $@'
         _flags_filter=msvc_flags
-        _ld_lib='%.lib'
+        _ld_lib='lib%.a'
         _ld_path='-libpath:'
         _flags='-nologo'
         _cflags='-D_USE_MATH_DEFINES -Dinline=__inline -FIstdlib.h -Dstrtoll=_strtoi64'
@@ -2742,24 +2768,19 @@
 
 # Deal with common $arch aliases
 case "$arch" in
+    aarch64|arm64)
+        arch="aarch64"
+    ;;
     arm*|iPad*)
         arch="arm"
     ;;
-    mips|mipsel|IP*)
+    mips*|IP*)
         arch="mips"
     ;;
-    mips64*)
-        arch="mips"
-        subarch="mips64"
-    ;;
-    parisc|hppa)
+    parisc*|hppa*)
         arch="parisc"
     ;;
-    parisc64|hppa64)
-        arch="parisc"
-        subarch="parisc64"
-    ;;
-    "Power Macintosh"|ppc|powerpc|ppc64|powerpc64)
+    "Power Macintosh"|ppc*|powerpc*)
         arch="ppc"
     ;;
     s390|s390x)
@@ -2768,9 +2789,11 @@
     sh4|sh)
         arch="sh4"
     ;;
-    sun4u|sparc64)
+    sun4u|sparc*)
         arch="sparc"
-        subarch="sparc64"
+    ;;
+    tilegx|tile-gx)
+        arch="tilegx"
     ;;
     i[3-6]86|i86pc|BePC|x86pc|x86_64|x86_32|amd64)
         arch="x86"
@@ -2783,93 +2806,22 @@
 # Add processor-specific flags
 if test "$cpu" = generic; then
     : do nothing
-elif enabled ppc; then
 
-    case $(tolower $cpu) in
-        601|ppc601|powerpc601)
-            cpuflags="-mcpu=601"
-            disable altivec
-        ;;
-        603*|ppc603*|powerpc603*)
-            cpuflags="-mcpu=603"
-            disable altivec
-        ;;
-        604*|ppc604*|powerpc604*)
-            cpuflags="-mcpu=604"
-            disable altivec
-        ;;
-        g3|75*|ppc75*|powerpc75*)
-            cpuflags="-mcpu=750 -mpowerpc-gfxopt"
-            disable altivec
-        ;;
-        g4|745*|ppc745*|powerpc745*)
-            cpuflags="-mcpu=7450 -mpowerpc-gfxopt"
-        ;;
-        74*|ppc74*|powerpc74*)
-            cpuflags="-mcpu=7400 -mpowerpc-gfxopt"
-        ;;
-        g5|970|ppc970|powerpc970)
-            cpuflags="-mcpu=970 -mpowerpc-gfxopt -mpowerpc64"
-        ;;
-        power[3-7]*)
-            cpuflags="-mcpu=$cpu -mpowerpc-gfxopt -mpowerpc64"
-        ;;
-        cell)
-            cpuflags="-mcpu=cell"
-            enable ldbrx
-        ;;
-        e500mc)
-            cpuflags="-mcpu=e500mc"
-            disable altivec
-        ;;
-        e500v2)
-            cpuflags="-mcpu=8548 -mhard-float -mfloat-gprs=double"
-            disable altivec
-        ;;
-        e500)
-            cpuflags="-mcpu=8540 -mhard-float"
-            disable altivec
-        ;;
-    esac
-
-elif enabled x86; then
+elif enabled aarch64; then
 
     case $cpu in
-        i[345]86|pentium)
+        armv*)
             cpuflags="-march=$cpu"
-            disable mmx
         ;;
-        # targets that do NOT support conditional mov (cmov)
-        pentium-mmx|k6|k6-[23]|winchip-c6|winchip2|c3)
-            cpuflags="-march=$cpu"
-            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|barcelona|atom|bdver*)
-            cpuflags="-march=$cpu"
-            enable cmov
-            enable fast_cmov
-        ;;
-        # targets that do support conditional mov but on which it's slow
-        pentium4|pentium4m|prescott|nocona)
-            cpuflags="-march=$cpu"
-            enable cmov
-            disable fast_cmov
-        ;;
-    esac
-
-elif enabled sparc; then
-
-    case $cpu in
-        niagara)
+        *)
             cpuflags="-mcpu=$cpu"
-            disable vis
-        ;;
-        sparc64)
-            cpuflags="-mcpu=v9"
         ;;
     esac
 
+elif enabled alpha; then
+
+    cpuflags="-mcpu=$cpu"
+
 elif enabled arm; then
 
     case $cpu in
@@ -2890,9 +2842,26 @@
         ;;
     esac
 
-elif enabled alpha; then
+elif enabled avr32; then
 
-    enabled ccc && cpuflags="-arch $cpu" || cpuflags="-mcpu=$cpu"
+    case $cpu in
+        ap7[02]0[0-2])
+            subarch="avr32_ap"
+            cpuflags="-mpart=$cpu"
+        ;;
+        ap)
+            subarch="avr32_ap"
+            cpuflags="-march=$cpu"
+        ;;
+        uc3[ab]*)
+            subarch="avr32_uc"
+            cpuflags="-mcpu=$cpu"
+        ;;
+        uc)
+            subarch="avr32_uc"
+            cpuflags="-march=$cpu"
+        ;;
+    esac
 
 elif enabled bfin; then
 
@@ -2924,24 +2893,90 @@
         ;;
     esac
 
-elif enabled avr32; then
+elif enabled ppc; then
 
-    case $cpu in
-        ap7[02]0[0-2])
-            subarch="avr32_ap"
-            cpuflags="-mpart=$cpu"
+    case $(tolower $cpu) in
+        601|ppc601|powerpc601)
+            cpuflags="-mcpu=601"
+            disable altivec
         ;;
-        ap)
-            subarch="avr32_ap"
-            cpuflags="-march=$cpu"
+        603*|ppc603*|powerpc603*)
+            cpuflags="-mcpu=603"
+            disable altivec
         ;;
-        uc3[ab]*)
-            subarch="avr32_uc"
+        604*|ppc604*|powerpc604*)
+            cpuflags="-mcpu=604"
+            disable altivec
+        ;;
+        g3|75*|ppc75*|powerpc75*)
+            cpuflags="-mcpu=750"
+            disable altivec
+        ;;
+        g4|745*|ppc745*|powerpc745*)
+            cpuflags="-mcpu=7450"
+        ;;
+        74*|ppc74*|powerpc74*)
+            cpuflags="-mcpu=7400"
+        ;;
+        g5|970|ppc970|powerpc970)
+            cpuflags="-mcpu=970"
+        ;;
+        power[3-7]*)
             cpuflags="-mcpu=$cpu"
         ;;
-        uc)
-            subarch="avr32_uc"
+        cell)
+            cpuflags="-mcpu=cell"
+            enable ldbrx
+        ;;
+        e500mc)
+            cpuflags="-mcpu=e500mc"
+            disable altivec
+        ;;
+        e500v2)
+            cpuflags="-mcpu=8548 -mhard-float -mfloat-gprs=double"
+            disable altivec
+        ;;
+        e500)
+            cpuflags="-mcpu=8540 -mhard-float"
+            disable altivec
+        ;;
+    esac
+
+elif enabled sparc; then
+
+    case $cpu in
+        cypress|f93[04]|tsc701|sparcl*|supersparc|hypersparc|niagara|v[789])
+            cpuflags="-mcpu=$cpu"
+            disable vis
+        ;;
+        ultrasparc*|niagara[234])
+            cpuflags="-mcpu=$cpu"
+        ;;
+    esac
+
+elif enabled x86; then
+
+    case $cpu in
+        i[345]86|pentium)
             cpuflags="-march=$cpu"
+            disable mmx
+        ;;
+        # targets that do NOT support conditional mov (cmov)
+        pentium-mmx|k6|k6-[23]|winchip-c6|winchip2|c3)
+            cpuflags="-march=$cpu"
+            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|corei7*|amdfam10|barcelona|atom|bdver*)
+            cpuflags="-march=$cpu"
+            enable cmov
+            enable fast_cmov
+        ;;
+        # targets that do support conditional mov but on which it's slow
+        pentium4|pentium4m|prescott|nocona)
+            cpuflags="-march=$cpu"
+            enable cmov
+            disable fast_cmov
         ;;
     esac
 
@@ -2976,13 +3011,35 @@
 check_host_cflags -std=c99
 check_host_cflags -Wall
 
+check_64bit(){
+    arch32=$1
+    arch64=$2
+    expr=$3
+    check_code cc "" "int test[2*($expr) - 1]" &&
+        subarch=$arch64 || subarch=$arch32
+}
+
 case "$arch" in
-    alpha|ia64|mips|parisc|sparc)
+    alpha|ia64)
+        spic=$shared
+    ;;
+    mips)
+        check_64bit mips mips64 '_MIPS_SIM > 1'
+        spic=$shared
+    ;;
+    parisc)
+        check_64bit parisc parisc64 'sizeof(void *) > 4'
+        spic=$shared
+    ;;
+    ppc)
+        check_64bit ppc ppc64 'sizeof(void *) > 4'
+    ;;
+    sparc)
+        check_64bit sparc sparc64 'sizeof(void *) > 4'
         spic=$shared
     ;;
     x86)
-        subarch="x86_32"
-        check_code cc "" "int test[(int)sizeof(char*) - 7]" && subarch="x86_64"
+        check_64bit x86_32 x86_64 'sizeof(void *) > 4'
         if test "$subarch" = "x86_64"; then
             spic=$shared
         fi
@@ -3078,30 +3135,51 @@
         shlibdir_default="$bindir_default"
         SLIBPREF=""
         SLIBSUF=".dll"
-		LIBPREF=""
-		LIBSUF=".lib"
         SLIBNAME_WITH_VERSION='$(SLIBPREF)$(FULLNAME)-$(LIBVERSION)$(SLIBSUF)'
         SLIBNAME_WITH_MAJOR='$(SLIBPREF)$(FULLNAME)-$(LIBMAJOR)$(SLIBSUF)'
         dlltool="${cross_prefix}dlltool"
         if check_cmd lib.exe -list; then
-            SLIB_EXTRA_CMD='-lib.exe -machine:$(LIBTARGET) -def:$$(@:$(SLIBSUF)=.def) -out:$(SUBDIR)$(SLIBNAME:$(SLIBSUF)=.lib)'
+            SLIB_EXTRA_CMD=-'sed -e "s/ @[^ ]*//" $$(@:$(SLIBSUF)=.orig.def) > $$(@:$(SLIBSUF)=.def); lib.exe /machine:$(LIBTARGET) /def:$$(@:$(SLIBSUF)=.def) /out:$(SUBDIR)$(SLIBNAME:$(SLIBSUF)=.lib)'
             if enabled x86_64; then
                 LIBTARGET=x64
             fi
         elif check_cmd $dlltool --version; then
-            SLIB_EXTRA_CMD=-'$(DLLTOOL) -m $(LIBTARGET) -d $$(@:$(SLIBSUF)=.def) -l $(SUBDIR)$(SLIBNAME:$(SLIBSUF)=.lib) -D $(SLIBNAME_WITH_MAJOR)'
+            SLIB_EXTRA_CMD=-'sed -e "s/ @[^ ]*//" $$(@:$(SLIBSUF)=.orig.def) > $$(@:$(SLIBSUF)=.def); $(DLLTOOL) -m $(LIBTARGET) -d $$(@:$(SLIBSUF)=.def) -l $(SUBDIR)$(SLIBNAME:$(SLIBSUF)=.lib) -D $(SLIBNAME_WITH_MAJOR)'
         fi
         SLIB_INSTALL_NAME='$(SLIBNAME_WITH_MAJOR)'
         SLIB_INSTALL_LINKS=
         SLIB_INSTALL_EXTRA_SHLIB='$(SLIBNAME:$(SLIBSUF)=.lib)'
-        SLIB_INSTALL_EXTRA_LIB='lib$(SLIBNAME:$(SLIBSUF)=.dll) $(SLIBNAME_WITH_MAJOR:$(SLIBSUF)=.def)'
-        SHFLAGS='-dll -def:$$(@:$(SLIBSUF)=.def) -implib:$(SUBDIR)lib$(SLIBNAME:$(SLIBSUF)=.dll.a)'
+        SLIB_INSTALL_EXTRA_LIB='lib$(SLIBNAME:$(SLIBSUF)=.dll.a) $(SLIBNAME_WITH_MAJOR:$(SLIBSUF)=.def)'
+        SHFLAGS='-shared -Wl,--output-def,$$(@:$(SLIBSUF)=.orig.def) -Wl,--out-implib,$(SUBDIR)lib$(SLIBNAME:$(SLIBSUF)=.dll.a) -Wl,--enable-runtime-pseudo-reloc -Wl,--enable-auto-image-base'
         objformat="win32"
         ranlib=:
         enable dos_paths
-        check_cflags -fno-common
         add_cppflags -U__STRICT_ANSI__
         ;;
+    win32|win64)
+        if enabled shared; then
+            # Link to the import library instead of the normal static library
+            # for shared libs.
+            LD_LIB='%.lib'
+            # Cannot build shared and static libraries at the same time with
+            # MSVC.
+            disable static
+        fi
+        shlibdir_default="$bindir_default"
+        SLIBPREF=""
+        SLIBSUF=".dll"
+        SLIBNAME_WITH_VERSION='$(SLIBPREF)$(FULLNAME)-$(LIBVERSION)$(SLIBSUF)'
+        SLIBNAME_WITH_MAJOR='$(SLIBPREF)$(FULLNAME)-$(LIBMAJOR)$(SLIBSUF)'
+        SLIB_CREATE_DEF_CMD='makedef $(SUBDIR)lib$(NAME).ver $(OBJS) > $$(@:$(SLIBSUF)=.def)'
+        SLIB_INSTALL_NAME='$(SLIBNAME_WITH_MAJOR)'
+        SLIB_INSTALL_LINKS=
+        SLIB_INSTALL_EXTRA_SHLIB='$(SLIBNAME:$(SLIBSUF)=.lib)'
+        SLIB_INSTALL_EXTRA_LIB='$(SLIBNAME_WITH_MAJOR:$(SLIBSUF)=.def)'
+        SHFLAGS='-dll -def:$$(@:$(SLIBSUF)=.def) -implib:$(SUBDIR)$(SLIBNAME:$(SLIBSUF)=.lib)'
+        objformat="win32"
+        ranlib=:
+        enable dos_paths
+        ;;
     cygwin*)
         target_os=cygwin
         shlibdir_default="$bindir_default"
@@ -3115,8 +3193,6 @@
         SHFLAGS='-shared -Wl,--out-implib,$(SUBDIR)lib$(FULLNAME).dll.a'
         objformat="win32"
         enable dos_paths
-        check_cflags -fno-common
-        add_cppflags -U__STRICT_ANSI__
         ;;
     *-dos|freedos|opendos)
         network_extralibs="-lsocket"
@@ -3125,7 +3201,6 @@
         add_cppflags -U__STRICT_ANSI__
         ;;
     linux)
-        add_cppflags -D_POSIX_C_SOURCE=200112 -D_XOPEN_SOURCE=600
         enable dv1394
         ;;
     irix*)
@@ -3158,10 +3233,9 @@
         enable_weak os2threads
         ;;
     gnu/kfreebsd)
-        add_cppflags -D_POSIX_C_SOURCE=200112 -D_XOPEN_SOURCE=600 -D_BSD_SOURCE
+        add_cppflags -D_BSD_SOURCE
         ;;
     gnu)
-        add_cppflags -D_POSIX_C_SOURCE=200112 -D_XOPEN_SOURCE=600
         ;;
     qnx)
         add_cppflags -D_QNX_SOURCE
@@ -3179,6 +3253,25 @@
                       -l:drtaeabi.dso -l:scppnwdl.dso -lsupc++ -lgcc \
                       -l:libc.dso -l:libm.dso -l:euser.dso -l:libcrt0.lib
         ;;
+    osf1)
+        add_cppflags -D_OSF_SOURCE -D_POSIX_PII -D_REENTRANT
+        FFSERVERLDFLAGS=
+        ;;
+    minix)
+        ;;
+    plan9)
+        add_cppflags -D_C99_SNPRINTF_EXTENSION  \
+                     -D_REENTRANT_SOURCE        \
+                     -D_RESEARCH_SOURCE         \
+                     -DFD_SETSIZE=96            \
+                     -DHAVE_SOCK_OPTS
+        add_compat strtod.o strtod=avpriv_strtod
+        network_extralibs='-lbsd'
+        exeobjs=compat/plan9/main.o
+        disable ffserver
+        ln_s='ln -s -f'
+        cp_f='cp'
+        ;;
     none)
         ;;
     *)
@@ -3190,8 +3283,10 @@
 
 if check_cpp_condition features.h "defined __UCLIBC__"; then
     libc_type=uclibc
+    add_cppflags -D_POSIX_C_SOURCE=200112 -D_XOPEN_SOURCE=600
 elif check_cpp_condition features.h "defined __GLIBC__"; then
     libc_type=glibc
+    add_cppflags -D_POSIX_C_SOURCE=200112 -D_XOPEN_SOURCE=600
 elif check_header _mingw.h; then
     libc_type=mingw
     check_cpp_condition _mingw.h \
@@ -3200,24 +3295,38 @@
         die "ERROR: MinGW runtime version must be >= 3.15."
     if check_cpp_condition _mingw.h "defined(__MINGW64_VERSION_MAJOR) && \
             __MINGW64_VERSION_MAJOR < 3"; then
-        enable broken_snprintf
+        add_compat msvcrt/snprintf.o
         add_cflags "-include $source_path/compat/msvcrt/snprintf.h"
     fi
 elif check_cpp_condition newlib.h "defined _NEWLIB_VERSION"; then
     libc_type=newlib
+    add_cppflags -U__STRICT_ANSI__
 elif check_func_headers stdlib.h _get_doserrno; then
     libc_type=msvcrt
-    enable broken_snprintf
-    add_cflags -Dstrtod=avpriv_strtod
-    add_cflags -Dsnprintf=avpriv_snprintf   \
-               -D_snprintf=avpriv_snprintf  \
-               -Dvsnprintf=avpriv_vsnprintf
+    add_compat strtod.o strtod=avpriv_strtod
+    add_compat msvcrt/snprintf.o snprintf=avpriv_snprintf   \
+                                 _snprintf=avpriv_snprintf  \
+                                 vsnprintf=avpriv_vsnprintf
 elif check_cpp_condition stddef.h "defined __KLIBC__"; then
     libc_type=klibc
 fi
 
 test -n "$libc_type" && enable $libc_type
 
+# hacks for compiler/libc/os combinations
+
+if enabled_all tms470 glibc; then
+    CPPFLAGS="-I${source_path}/compat/tms470 ${CPPFLAGS}"
+    add_cppflags -D__USER_LABEL_PREFIX__=
+    add_cppflags -D__builtin_memset=memset
+    add_cppflags -D__gnuc_va_list=va_list -D_VA_LIST_DEFINED
+    add_cflags   -pds=48    # incompatible redefinition of macro
+fi
+
+if enabled_all ccc glibc; then
+    add_ldflags -Wl,-z,now  # calls to libots crash without this
+fi
+
 esc(){
     echo "$*" | sed 's/%/%25/g;s/:/%3a/g'
 }
@@ -3314,6 +3423,7 @@
 
 elif enabled arm; then
 
+    check_cpp_condition stddef.h "defined __thumb__" && enable_weak thumb
     enabled thumb && check_cflags -mthumb || check_cflags -marm
     nogas=die
 
@@ -3345,7 +3455,6 @@
 elif enabled mips; then
 
     check_inline_asm loongson '"dmult.g $1, $2, $3"'
-    enabled mmi && check_inline_asm mmi '"lq $2, 0($2)"'
     enabled mips32r2  && add_cflags "-mips32r2" && add_asflags "-mips32r2" &&
      check_inline_asm mips32r2  '"rotr $t0, $t1, 1"'
     enabled mipsdspr1 && add_cflags "-mdsp" && add_asflags "-mdsp" &&
@@ -3355,6 +3464,14 @@
     enabled mipsfpu   && add_cflags "-mhard-float" && add_asflags "-mhard-float" &&
      check_inline_asm mipsfpu   '"madd.d $f0, $f2, $f4, $f6"'
 
+elif enabled parisc; then
+
+    if enabled gcc; then
+        case $($cc -dumpversion) in
+            4.[3-8].*) check_cflags -fno-optimize-sibling-calls ;;
+        esac
+    fi
+
 elif enabled ppc; then
 
     enable local_aligned_8 local_aligned_16
@@ -3387,16 +3504,11 @@
 
 elif enabled sparc; then
 
-    enabled vis &&
-        check_inline_asm vis '"pdist %f0, %f0, %f0"' -mcpu=ultrasparc &&
-            add_cflags -mcpu=ultrasparc -mtune=ultrasparc
+    enabled vis && check_inline_asm vis '"pdist %f0, %f0, %f0"'
 
 elif enabled x86; then
 
-    check_code ld immintrin.h "return __xgetbv(0)" "cc" && enable xgetbv
-    check_code ld intrin.h "int info[4]; __cpuid(info, 0)" "cc" && enable cpuid
     check_code ld intrin.h "__rdtsc()" "cc" && enable rdtsc
-    check_code ld intrin.h "unsigned int x = __readeflags()" "cc" && enable rweflags
 
     check_code ld mmintrin.h "_mm_empty()" "cc" && enable mm_empty
 
@@ -3481,6 +3593,7 @@
     check_struct "sys/types.h sys/socket.h" "struct sockaddr" sa_len
     check_type netinet/sctp.h "struct sctp_event_subscribe"
     check_func getaddrinfo $network_extralibs
+    check_func getservbyport $network_extralibs
     # Prefer arpa/inet.h over winsock2
     if check_header arpa/inet.h ; then
         check_func closesocket
@@ -3507,6 +3620,7 @@
 # Solaris has nanosleep in -lrt, OpenSolaris no longer needs that
 check_func nanosleep || { check_func nanosleep -lrt && add_extralibs -lrt; }
 
+check_func  access
 check_func  clock_gettime || { check_func clock_gettime -lrt && add_extralibs -lrt; }
 check_func  fcntl
 check_func  fork
@@ -3521,6 +3635,7 @@
 check_func  ${malloc_prefix}memalign            && enable memalign
 check_func  mkstemp
 check_func  mmap
+check_func  mprotect
 check_func  ${malloc_prefix}posix_memalign      && enable posix_memalign
 check_func_headers malloc.h _aligned_malloc     && enable aligned_malloc
 check_func  setrlimit
@@ -3534,11 +3649,13 @@
 check_func_headers io.h setmode
 check_func_headers lzo/lzo1x.h lzo1x_999_compress
 check_lib2 "windows.h shellapi.h" CommandLineToArgvW -lshell32
+check_lib2 "windows.h wincrypt.h" CryptGenRandom -ladvapi32
 check_lib2 "windows.h psapi.h" GetProcessMemoryInfo -lpsapi
 check_func_headers windows.h GetProcessAffinityMask
 check_func_headers windows.h GetProcessTimes
 check_func_headers windows.h GetSystemTimeAsFileTime
 check_func_headers windows.h MapViewOfFile
+check_func_headers windows.h SetConsoleTextAttribute
 check_func_headers windows.h Sleep
 check_func_headers windows.h VirtualAlloc
 check_func_headers glob.h glob
@@ -3576,7 +3693,7 @@
 fi
 
 if ! disabled w32threads && ! enabled pthreads; then
-    check_func _beginthreadex && enable w32threads
+    check_func_headers "windows.h process.h" _beginthreadex && enable w32threads
 fi
 
 # check for some common methods of building with pthread support
@@ -3614,22 +3731,13 @@
 disabled crystalhd || check_lib libcrystalhd/libcrystalhd_if.h DtsCrystalHDVersion -lcrystalhd || disable crystalhd
 enabled vaapi && require vaapi va/va.h vaInitialize -lva
 
-check_mathfunc cbrtf
-check_mathfunc exp2
-check_mathfunc exp2f
-check_mathfunc isinf
-check_mathfunc isnan
-check_mathfunc llrint
-check_mathfunc llrintf
-check_mathfunc log2
-check_mathfunc log2f
-check_mathfunc lrint
-check_mathfunc lrintf
-check_mathfunc rint
-check_mathfunc round
-check_mathfunc roundf
-check_mathfunc trunc
-check_mathfunc truncf
+atan2f_args=2
+ldexpf_args=2
+powf_args=2
+
+for func in $MATH_FUNCS; do
+    eval check_mathfunc $func \${${func}_args:-1}
+done
 
 # these are off by default, so fail if requested and not available
 enabled avisynth   && require2 vfw32 "windows.h vfw.h" AVIFileInit -lavifil32
@@ -3640,6 +3748,7 @@
 enabled libaacplus && require  "libaacplus >= 2.0.0" aacplus.h aacplusEncOpen -laacplus
 enabled libass     && require_pkg_config libass ass/ass.h ass_library_init
 enabled libbluray  && require libbluray libbluray/bluray.h bd_open -lbluray
+enabled libcdio    && require2 libcdio "cdio/cdda.h cdio/paranoia.h" cdio_cddap_open -lcdio_paranoia -lcdio_cdda -lcdio
 enabled libcelt    && require libcelt celt/celt.h celt_decode -lcelt0 &&
                       { check_lib celt/celt.h celt_decoder_create_custom -lcelt0 ||
                         die "ERROR: libcelt must be installed and version must be >= 0.11.0."; }
@@ -3772,8 +3881,6 @@
 
 enabled_any sndio_indev sndio_outdev && check_lib2 sndio.h sio_open -lsndio
 
-enabled libcdio &&
-    check_lib2 "cdio/cdda.h cdio/paranoia.h" cdio_cddap_open "-lcdio_paranoia -lcdio_cdda -lcdio"
 
 enabled x11grab                                           &&
 require X11 X11/Xlib.h XOpenDisplay -lX11                 &&
@@ -3843,17 +3950,34 @@
 EOF
 fi
 
-if [ -n "$optflags" ]; then
-    add_cflags $optflags
-elif enabled small; then
-    add_cflags $cflags_size
-elif enabled optimizations; then
-    add_cflags $cflags_speed
-else
-    add_cflags $cflags_noopt
+if [ -z "$optflags" ]; then
+    if enabled small; then
+        optflags=$cflags_size
+    elif enabled optimizations; then
+        optflags=$cflags_speed
+    else
+        optflags=$cflags_noopt
+    fi
 fi
-check_cflags -fno-math-errno
-check_cflags -fno-signed-zeros
+
+check_optflags(){
+    check_cflags "$@"
+    enabled lto && check_ldflags "$@"
+}
+
+
+if enabled lto; then
+    test "$cc_type" != "$ld_type" && die "LTO requires same compiler and linker"
+    check_cflags  -flto
+    check_ldflags -flto $cpuflags
+fi
+
+check_optflags $optflags
+check_optflags -fno-math-errno
+check_optflags -fno-signed-zeros
+
+enabled ftrapv && check_cflags -ftrapv
+
 check_cc -mno-red-zone <<EOF && noredzone_flags="-mno-red-zone"
 int x;
 EOF
@@ -3885,21 +4009,22 @@
     fi
 elif enabled ccc; then
     # disable some annoying warnings
-    add_cflags -msg_disable cvtu32to64
-    add_cflags -msg_disable embedcomment
-    add_cflags -msg_disable needconstext
-    add_cflags -msg_disable nomainieee
-    add_cflags -msg_disable ptrmismatch1
-    add_cflags -msg_disable unreachcode
+    add_cflags -msg_disable bitnotint
+    add_cflags -msg_disable mixfuncvoid
+    add_cflags -msg_disable nonstandcast
+    add_cflags -msg_disable unsupieee
 elif enabled gcc; then
-    check_cflags -fno-tree-vectorize
+    check_optflags -fno-tree-vectorize
     check_cflags -Werror=implicit-function-declaration
     check_cflags -Werror=missing-prototypes
+    check_cflags -Werror=vla
 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
+    check_cflags -Werror=implicit-function-declaration
+    check_cflags -Werror=missing-prototypes
 elif enabled armcc; then
     # 2523: use of inline assembler is deprecated
     add_cflags -W${armcc_opt},--diag_suppress=2523
@@ -3916,6 +4041,15 @@
     enabled x86_32 && disable aligned_stack
 fi
 
+case $target_os in
+    osf1)
+        enabled ccc && add_ldflags '-Wl,-expect_unresolved,*'
+    ;;
+    plan9)
+        add_cppflags -Dmain=plan9_main
+    ;;
+esac
+
 enabled_any $THREADS_LIST      && enable threads
 
 enabled asm || { arch=c; disable $ARCH_LIST $ARCH_EXT_LIST; }
@@ -3924,7 +4058,6 @@
            $CONFIG_EXTRA      \
            $HAVE_LIST         \
            $ALL_COMPONENTS    \
-           $ALL_TESTS         \
 
 
 if test $target_os = "haiku"; then
@@ -4000,7 +4133,6 @@
     echo "NEON enabled              ${neon-no}"
 fi
 if enabled mips; then
-    echo "MMI enabled               ${mmi-no}"
     echo "MIPS FPU enabled          ${mipsfpu-no}"
     echo "MIPS32R2 enabled          ${mips32r2-no}"
     echo "MIPS DSP R1 enabled       ${mipsdspr1-no}"
@@ -4149,6 +4281,7 @@
 AS_C=$AS_C
 AS_O=$AS_O
 CC_C=$CC_C
+CC_E=$CC_E
 CC_O=$CC_O
 CXX_C=$CXX_C
 CXX_O=$CXX_O
@@ -4198,6 +4331,8 @@
 ZLIB=$($ldflags_filter -lz)
 LIB_INSTALL_EXTRA_CMD=$LIB_INSTALL_EXTRA_CMD
 EXTRALIBS=$extralibs
+COMPAT_OBJS=$compat_objs
+EXEOBJS=$exeobjs
 INSTALL=$install
 LIBTARGET=${LIBTARGET}
 SLIBNAME=${SLIBNAME}
@@ -4214,10 +4349,10 @@
 EOF
 
 get_version(){
-    lcname=$1
+    lcname=lib${1}
     name=$(toupper $lcname)
     file=$source_path/$lcname/version.h
-    eval $(grep "#define ${name}_VERSION_M" "$file" | awk '{ print $2"="$3 }')
+    eval $(awk "/#define ${name}_VERSION_M/ { print \$2 \"=\" \$3 }" "$file")
     eval ${name}_VERSION=\$${name}_VERSION_MAJOR.\$${name}_VERSION_MINOR.\$${name}_VERSION_MICRO
     eval echo "${lcname}_VERSION=\$${name}_VERSION" >> config.mak
     eval echo "${lcname}_VERSION_MAJOR=\$${name}_VERSION_MAJOR" >> config.mak
@@ -4238,14 +4373,7 @@
 
 get_version_old LIBPOSTPROC libpostproc/version.h
 
-get_version libavcodec
-get_version libavdevice
-get_version libavfilter
-get_version libavformat
-get_version libavresample
-get_version libavutil
-get_version libswresample
-get_version libswscale
+map 'get_version $v' $LIBRARY_LIST
 
 cat > $TMPH <<EOF
 /* Automatically generated by configure - do not modify! */
@@ -4280,13 +4408,6 @@
                                      $CONFIG_EXTRA      \
                                      $ALL_COMPONENTS    \
 
-cat >>config.mak <<EOF
-LAVF_FATE_TESTS=$(print_enabled -n _test $LAVF_FATE_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 /* FFMPEG_CONFIG_H */" >> $TMPH
 echo "endif # FFMPEG_CONFIG_MAK" >> config.mak
 
@@ -4314,7 +4435,10 @@
 
 cp_if_changed $TMPH libavutil/avconfig.h
 
-test -n "$WARNINGS" && printf "\n$WARNINGS"
+if test -n "$WARNINGS"; then
+    printf "\n$WARNINGS"
+    enabled fatal_warnings && exit 1
+fi
 
 # build pkg-config files
 
@@ -4363,9 +4487,10 @@
 EOF
 }
 
-libavfilter_pc_deps=""
+libavfilter_pc_deps="libavutil = $LIBAVUTIL_VERSION"
 enabled libavfilter_deps_avcodec    && prepend libavfilter_pc_deps "libavcodec = $LIBAVCODEC_VERSION,"
 enabled libavfilter_deps_avformat   && prepend libavfilter_pc_deps "libavformat = $LIBAVFORMAT_VERSION,"
+enabled libavfilter_deps_avresample && prepend libavfilter_pc_deps "libavresample = $LIBAVRESAMPLE_VERSION,"
 enabled libavfilter_deps_swscale    && prepend libavfilter_pc_deps "libswscale = $LIBSWSCALE_VERSION,"
 enabled libavfilter_deps_swresample && prepend libavfilter_pc_deps "libswresample = $LIBSWRESAMPLE_VERSION,"
 enabled libavfilter_deps_postproc   && prepend libavfilter_pc_deps "libpostproc = $LIBPOSTPROC_VERSION,"
@@ -4380,9 +4505,9 @@
 pkgconfig_generate libavdevice "FFmpeg device handling library" "$LIBAVDEVICE_VERSION" "$extralibs" "$libavdevice_pc_deps"
 pkgconfig_generate libavfilter "FFmpeg video filtering library" "$LIBAVFILTER_VERSION" "$extralibs" "$libavfilter_pc_deps"
 pkgconfig_generate libpostproc "FFmpeg postprocessing library" "$LIBPOSTPROC_VERSION" "" "libavutil = $LIBAVUTIL_VERSION"
-pkgconfig_generate libavresample "Libav audio resampling library" "$LIBAVRESAMPLE_VERSION" "$extralibs"
+pkgconfig_generate libavresample "Libav audio resampling library" "$LIBAVRESAMPLE_VERSION" "$extralibs" "libavutil = $LIBAVUTIL_VERSION"
 pkgconfig_generate libswscale "FFmpeg image rescaling library" "$LIBSWSCALE_VERSION" "$LIBM" "libavutil = $LIBAVUTIL_VERSION"
-pkgconfig_generate libswresample "FFmpeg audio rescaling library" "$LIBSWRESAMPLE_VERSION" "$LIBM" "libavutil = $LIBAVUTIL_VERSION"
+pkgconfig_generate libswresample "FFmpeg audio resampling library" "$LIBSWRESAMPLE_VERSION" "$LIBM" "libavutil = $LIBAVUTIL_VERSION"
 
 fix_ffmpeg_remote(){
     git_remote_from=$1
diff --git a/doc/APIchanges b/doc/APIchanges
index b941c64..5707d13 100644
--- a/doc/APIchanges
+++ b/doc/APIchanges
@@ -1,20 +1,48 @@
 Never assume the API of libav* to be stable unless at least 1 month has passed
-since the last major version increase.
+since the last major version increase or the API was added.
 
 The last version increases were:
 libavcodec:    2012-01-27
 libavdevice:   2011-04-18
 libavfilter:   2012-06-22
 libavformat:   2012-01-27
-libavresample: 2012-04-24
+libavresample: 2012-10-05
 libpostproc:   2011-04-18
 libswresample: 2011-09-19
 libswscale:    2011-06-20
-libavutil:     2011-04-18
+libavutil:     2012-10-22
 
 
 API changes, most recent first:
 
+2012-11-25 - xxxxxxx - lavu 52.9.100 - opt.h
+  Add the following convenience functions to opt.h:
+   av_opt_get_image_size
+   av_opt_get_pixel_fmt
+   av_opt_get_sample_fmt
+   av_opt_set_image_size
+   av_opt_set_pixel_fmt
+   av_opt_set_sample_fmt
+
+2012-11-17 - xxxxxxx - lavu 52.8.100 - bprint.h
+  Add av_bprint_strftime().
+
+2012-11-15 - xxxxxxx - lavu 52.7.100 - opt.h
+  Add av_opt_get_key_value().
+
+2012-11-13 - xxxxxxx - lavfi 3.23.100 - avfilter.h
+  Add channels field to AVFilterBufferRefAudioProps.
+
+2012-11-03 - xxxxxxx - lavu 52.3.100 - opt.h
+  Add AV_OPT_TYPE_SAMPLE_FMT value to AVOptionType enum.
+
+2012-10-21 - xxxxxxx - lavc  54.68.100 - avcodec.h
+                       lavfi  3.20.100 - avfilter.h
+  Add AV_PKT_DATA_STRINGS_METADATA side data type, used to transmit key/value
+  strings between AVPacket and AVFrame, and add metadata field to
+  AVCodecContext (which shall not be accessed by users; see AVFrame metadata
+  instead).
+
 2012-09-27 - a70b493 - lavd 54.3.100 - version.h
   Add LIBAVDEVICE_IDENT symbol.
 
@@ -97,7 +125,40 @@
 2012-03-26 - a67d9cf - lavfi 2.66.100
   Add avfilter_fill_frame_from_{audio_,}buffer_ref() functions.
 
-2012-09-23 - a42aada - lavc 54.28.0 - avcodec.h
+2012-xx-xx - xxxxxxx - lavu 52.2.0 - audioconvert.h
+  Rename audioconvert.h to channel_layout.h. audioconvert.h is now deprecated.
+
+2012-xx-xx - xxxxxxx - lavu 52.1.0 - intmath.h
+  Add av_ctz() for trailing zero bit count
+
+2012-10-18 - xxxxxxx - lavu 51.45.0 - error.h
+  Add AVERROR_EXPERIMENTAL
+
+2012-10-12 - xxxxxxx - lavu 51.44.0 - pixdesc.h
+  Add functions for accessing pixel format descriptors.
+  Accessing the av_pix_fmt_descriptors array directly is now
+  deprecated.
+
+2012-10-xx - xxxxxxx - lavu 51.43.0 - aes.h, md5.h, sha.h, tree.h
+  Add functions for allocating the opaque contexts for the algorithms,
+
+2012-10-xx - xxxxxxx - lavf 54.18.0 - avio.h
+  Add avio_closep to complement avio_close.
+
+2012-10-xx - xxxxxxx - lavu 51.42.0 - pixfmt.h
+  Rename PixelFormat to AVPixelFormat and all PIX_FMT_* to AV_PIX_FMT_*.
+  To provide backwards compatibility, PixelFormat is now #defined as
+  AVPixelFormat.
+  Note that this can break user code that includes pixfmt.h and uses the
+  'PixelFormat' identifier. Such code should either #undef PixelFormat
+  or stop using the PixelFormat name.
+
+2012-10-05 - e7ba5b1 - lavr 1.0.0 - avresample.h
+  Data planes parameters to avresample_convert() and
+  avresample_read() are now uint8_t** instead of void**.
+  Libavresample is now stable.
+
+2012-09-24 - a42aada - lavc 54.28.0 - avcodec.h
   Add avcodec_free_frame(). This function must now
   be used for freeing an AVFrame.
 
@@ -242,6 +303,10 @@
 2012-01-24 - 0c3577b - lavfi 2.60.100
   Add avfilter_graph_dump.
 
+2012-03-20 - 3c90cc2 - lavfo 54.2.0
+  Deprecate av_read_packet(), use av_read_frame() with
+  AVFMT_FLAG_NOPARSE | AVFMT_FLAG_NOFILLIN in AVFormatContext.flags
+
 2012-03-05 - lavc 54.8.0
   6699d07 Add av_get_exact_bits_per_sample()
   9524cf7 Add av_get_audio_frame_duration()
diff --git a/Doxyfile b/doc/Doxyfile
similarity index 97%
rename from Doxyfile
rename to doc/Doxyfile
index b91f351..9e12ab0 100644
--- a/Doxyfile
+++ b/doc/Doxyfile
@@ -44,7 +44,7 @@
 # If a relative path is entered, it will be relative to the location
 # where doxygen was started. If left blank the current directory will be used.
 
-OUTPUT_DIRECTORY       = doxy
+OUTPUT_DIRECTORY       = doc/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
@@ -489,12 +489,6 @@
 
 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.
@@ -645,15 +639,14 @@
 # directories that contain example code fragments that are included (see
 # the \include command).
 
-EXAMPLE_PATH           = libavcodec/ \
-                         libavformat/
+EXAMPLE_PATH           = doc/examples/
 
 # If the value of the EXAMPLE_PATH tag contains directories, you can use the
 # EXAMPLE_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 all files are included.
 
-EXAMPLE_PATTERNS       = *-example.c
+EXAMPLE_PATTERNS       = *.c
 
 # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
 # searched for input files to be used with the \include or \dontinclude
@@ -800,13 +793,13 @@
 # each generated HTML page. If it is left blank doxygen will generate a
 # standard header.
 
-HTML_HEADER            = doc/doxy/header.html
+#HTML_HEADER            = doc/doxy/header.html
 
 # The HTML_FOOTER tag can be used to specify a personal HTML footer for
 # each generated HTML page. If it is left blank doxygen will generate a
 # standard footer.
 
-HTML_FOOTER            = doc/doxy/footer.html
+#HTML_FOOTER            = doc/doxy/footer.html
 
 # 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
@@ -815,7 +808,7 @@
 # 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        = doc/doxy/doxy_stylesheet.css
+#HTML_STYLESHEET        = doc/doxy/doxy_stylesheet.css
 
 # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output.
 # Doxygen will adjust the colors in the stylesheet and background images
@@ -825,7 +818,7 @@
 # 180 is cyan, 240 is blue, 300 purple, and 360 is red again.
 # The allowed range is 0 to 359.
 
-HTML_COLORSTYLE_HUE    = 120
+#HTML_COLORSTYLE_HUE    = 120
 
 # The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of
 # the colors in the HTML output. For a value of 0 the output will use
@@ -848,12 +841,6 @@
 
 HTML_TIMESTAMP         = YES
 
-# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes,
-# files or namespaces will be aligned in HTML using tables. If set to
-# NO a bullet list will be used.
-
-HTML_ALIGN_MEMBERS     = YES
-
 # 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
@@ -1034,11 +1021,6 @@
 
 GENERATE_TREEVIEW      = NO
 
-# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories,
-# and Class Hierarchy pages using a tree view instead of an ordered list.
-
-USE_INLINE_TREES       = NO
-
 # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be
 # used to set the initial width (in pixels) of the frame in which the tree
 # is shown.
@@ -1374,14 +1356,9 @@
 # instead of the = operator.
 
 PREDEFINED             = "__attribute__(x)=" \
-                         "RENAME(x)=x ## _TMPL" \
-                         "DEF(x)=x ## _TMPL" \
-                         HAVE_AV_CONFIG_H \
-                         HAVE_MMX \
-                         HAVE_MMXEXT \
-                         HAVE_AMD3DNOW \
                          "DECLARE_ALIGNED(a,t,n)=t n" \
-                         "offsetof(x,y)=0x42"
+                         "offsetof(x,y)=0x42" \
+                         av_alloc_size \
 
 # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
 # this tag can be used to specify a list of macro names that should be expanded.
diff --git a/doc/Makefile b/doc/Makefile
index e594c44..e85e53b 100644
--- a/doc/Makefile
+++ b/doc/Makefile
@@ -1,11 +1,29 @@
-MANPAGES    = $(PROGS-yes:%=doc/%.1)
-PODPAGES    = $(PROGS-yes:%=doc/%.pod)
-HTMLPAGES   = $(PROGS-yes:%=doc/%.html)                                 \
+LIBRARIES-$(CONFIG_AVUTIL)     += libavutil
+LIBRARIES-$(CONFIG_SWSCALE)    += libswscale
+LIBRARIES-$(CONFIG_SWRESAMPLE) += libswresample
+LIBRARIES-$(CONFIG_AVCODEC)    += libavcodec
+LIBRARIES-$(CONFIG_AVFORMAT)   += libavformat
+LIBRARIES-$(CONFIG_AVDEVICE)   += libavdevice
+LIBRARIES-$(CONFIG_AVFILTER)   += libavfilter
+
+COMPONENTS-yes = $(PROGS-yes)
+COMPONENTS-$(CONFIG_AVUTIL)     += ffmpeg-utils
+COMPONENTS-$(CONFIG_SWSCALE)    += ffmpeg-scaler
+COMPONENTS-$(CONFIG_SWRESAMPLE) += ffmpeg-resampler
+COMPONENTS-$(CONFIG_AVCODEC)    += ffmpeg-codecs ffmpeg-bitstream-filters
+COMPONENTS-$(CONFIG_AVFORMAT)   += ffmpeg-formats ffmpeg-protocols
+COMPONENTS-$(CONFIG_AVDEVICE)   += ffmpeg-devices
+COMPONENTS-$(CONFIG_AVFILTER)   += ffmpeg-filters
+
+MANPAGES    = $(COMPONENTS-yes:%=doc/%.1)    $(LIBRARIES-yes:%=doc/%.3)
+PODPAGES    = $(COMPONENTS-yes:%=doc/%.pod)  $(LIBRARIES-yes:%=doc/%.pod)
+HTMLPAGES   = $(COMPONENTS-yes:%=doc/%.html) $(LIBRARIES-yes:%=doc/%.html)     \
               doc/developer.html                                        \
               doc/faq.html                                              \
               doc/fate.html                                             \
               doc/general.html                                          \
               doc/git-howto.html                                        \
+              doc/nut.html                                              \
               doc/platform.html                                         \
               doc/syntax.html                                           \
 
@@ -22,6 +40,7 @@
 
 doc: documentation
 
+apidoc: doc/doxy/html
 documentation: $(DOCS)
 
 TEXIDEP = awk '/^@(verbatim)?include/ { printf "$@: $(@D)/%s\n", $$2 }' <$< >$(@:%=%.d)
@@ -48,11 +67,16 @@
 	$(Q)$(TEXIDEP)
 	$(M)perl $(SRC_PATH)/doc/texi2pod.pl -Idoc $< $@
 
-doc/%.1: TAG = MAN
+doc/%.1 doc/%.3: TAG = MAN
 doc/%.1: doc/%.pod $(GENTEXI)
 	$(M)pod2man --section=1 --center=" " --release=" " $< > $@
+doc/%.3: doc/%.pod $(GENTEXI)
+	$(M)pod2man --section=3 --center=" " --release=" " $< > $@
 
-$(DOCS): | doc/
+$(DOCS) doc/doxy/html: | doc/
+
+doc/doxy/html: $(SRC_PATH)/doc/Doxyfile $(INSTHEADERS)
+	$(M)$(SRC_PATH)/doc/doxy-wrapper.sh $(SRC_PATH) $^
 
 install-man:
 
@@ -70,8 +94,9 @@
 	$(RM) $(addprefix "$(MANDIR)/man1/",$(ALLMANPAGES))
 
 clean::
-	$(RM) $(TXTPAGES) doc/*.html doc/*.pod doc/*.1 $(CLEANSUFFIXES:%=doc/%) doc/avoptions_*.texi
+	$(RM) $(TXTPAGES) doc/*.html doc/*.pod doc/*.1 doc/*.3 $(CLEANSUFFIXES:%=doc/%) doc/avoptions_*.texi
+	$(RM) -r doc/doxy/html
 
 -include $(wildcard $(DOCS:%=%.d))
 
-.PHONY: doc documentation
+.PHONY: apidoc doc documentation
diff --git a/doc/avtools-common-opts.texi b/doc/avtools-common-opts.texi
index 1fc12aa..bce5220 100644
--- a/doc/avtools-common-opts.texi
+++ b/doc/avtools-common-opts.texi
@@ -1,10 +1,11 @@
 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.
+SI unit prefixes, for example 'K', 'M', 'G'.
+If 'i' is appended after the prefix, binary prefixes are used,
+which are based on powers of 1024 instead of powers of 1000.
+The 'B' postfix multiplies the value by 8, and can be
+appended after a unit prefix or used alone. This allows using for
+example 'KB', 'MiB', 'G' and 'B' as number 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
@@ -151,8 +152,20 @@
 This file can be useful for bug reports.
 It also implies @code{-loglevel verbose}.
 
-Note: setting the environment variable @code{FFREPORT} to any value has the
-same effect.
+Setting the environment variable @code{FFREPORT} to any value has the same
+effect. If the value is a ':'-separated key=value sequence, these options
+will affect the report; options values must be
+@ref{quoting_and_escaping, escaped} if they contain special characters or
+the options delimiter ':'. The following option is recognized:
+@table @option
+@item file
+set the file name to use for the report; @code{%p} is expanded to the name
+of the program, @code{%t} is expanded to a timestamp, @code{%%} is expanded
+to a plain @code{%}
+@end table
+
+Errors in parsing the environment variable are not fatal, and will not
+appear in the report.
 
 @item -cpuflags flags (@emph{global})
 Allows setting and clearing cpu flags. This option is intended
diff --git a/doc/developer.texi b/doc/developer.texi
index cd635a8..b0e5216 100644
--- a/doc/developer.texi
+++ b/doc/developer.texi
@@ -317,7 +317,8 @@
     (e.g. addition of a function to the public API or extension of an
     existing data structure).
     Incrementing the third component means a noteworthy binary compatible
-    change (e.g. encoder bug fix that matters for the decoder).
+    change (e.g. encoder bug fix that matters for the decoder). The third
+    component always starts at 100 to distinguish FFmpeg from Libav.
 @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
@@ -429,7 +430,7 @@
     Was the patch generated with git format-patch or send-email?
 @item
     Did you sign off your patch? (git commit -s)
-    See @url{http://kerneltrap.org/files/Jeremy/DCO.txt} for the meaning
+    See @url{http://git.kernel.org/?p=linux/kernel/git/torvalds/linux.git;a=blob_plain;f=Documentation/SubmittingPatches} for the meaning
     of sign off.
 @item
     Did you provide a clear git commit log message?
diff --git a/doc/doxy-wrapper.sh b/doc/doxy-wrapper.sh
new file mode 100755
index 0000000..6650e38
--- /dev/null
+++ b/doc/doxy-wrapper.sh
@@ -0,0 +1,14 @@
+#!/bin/sh
+
+SRC_PATH="${1}"
+DOXYFILE="${2}"
+
+shift 2
+
+doxygen - <<EOF
+@INCLUDE        = ${DOXYFILE}
+INPUT           = $@
+HTML_HEADER     = ${SRC_PATH}/doc/doxy/header.html
+HTML_FOOTER     = ${SRC_PATH}/doc/doxy/footer.html
+HTML_STYLESHEET = ${SRC_PATH}/doc/doxy/doxy_stylesheet.css
+EOF
diff --git a/doc/doxy/doxy_stylesheet.css b/doc/doxy/doxy_stylesheet.css
index ff1e214..63238a2 100644
--- a/doc/doxy/doxy_stylesheet.css
+++ b/doc/doxy/doxy_stylesheet.css
@@ -1,32 +1,1138 @@
+/*!
+ * Bootstrap v2.1.1
+ *
+ * Copyright 2012 Twitter, Inc
+ * Licensed under the Apache License v2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Designed and built with all the love in the world @twitter by @mdo and @fat.
+ */
+
+html {
+  font-size: 100%;
+  -webkit-text-size-adjust: 100%;
+  -ms-text-size-adjust: 100%;
+}
+a:focus {
+  outline: thin dotted #333;
+  outline: 5px auto -webkit-focus-ring-color;
+  outline-offset: -2px;
+}
+a:hover,
+a:current {
+  outline: 0;
+}
+img {
+  /* Responsive images (ensure images don't scale beyond their parents) */
+
+  max-width: 100%;
+  /* Part 1: Set a maxium relative to the parent */
+
+  width: auto\9;
+  /* IE7-8 need help adjusting responsive images */
+
+  height: auto;
+  /* Part 2: Scale the height according to the width, otherwise you get stretching */
+
+  vertical-align: middle;
+  border: 0;
+  -ms-interpolation-mode: bicubic;
+}
+body {
+  margin: 0;
+  font-family: sans-serif;
+  font-size: 14px;
+  line-height: 20px;
+  color: #333333;
+  background-color: #ffffff;
+}
+a {
+  color: #0088cc;
+  text-decoration: none;
+}
+a:hover {
+  color: #005580;
+  text-decoration: underline;
+}
+.container {
+  width: 940px;
+}
+
+.container {
+  margin-right: auto;
+  margin-left: auto;
+  *zoom: 1;
+}
+
+.container:before,
+.container:after {
+  display: table;
+  content: "";
+  line-height: 0;
+}
+.container:after {
+  clear: both;
+}
+.container-fluid {
+  padding-right: 20px;
+  padding-left: 20px;
+  *zoom: 1;
+}
+small {
+  font-size: 85%;
+}
+strong {
+  font-weight: bold;
+}
+em {
+  font-style: italic;
+}
+cite {
+  font-style: normal;
+}
+.text-warning {
+  color: #c09853;
+}
+.text-error {
+  color: #b94a48;
+}
+.text-info {
+  color: #3a87ad;
+}
+.text-success {
+  color: #468847;
+}
+h1,
+h2,
+h3,
+h4,
+h5,
+h6 {
+  margin: 10px 0;
+  font-family: inherit;
+  font-weight: bold;
+  line-height: 1;
+  color: inherit;
+  text-rendering: optimizelegibility;
+}
+h1 small,
+h2 small,
+h3 small,
+h4 small,
+h5 small,
+h6 small {
+  font-weight: normal;
+  line-height: 1;
+  color: #999999;
+}
+h1 {
+  font-size: 30px;
+  line-height: 40px;
+}
+h2 {
+  font-size: 20px;
+  line-height: 40px;
+}
+h3 {
+  font-size: 18px;
+  line-height: 40px;
+}
+h4 {
+  font-size: 18px;
+  line-height: 20px;
+}
+h5 {
+  font-size: 14px;
+  line-height: 20px;
+}
+h6 {
+  font-size: 12px;
+  line-height: 20px;
+}
+ul,
+ol {
+  padding: 0;
+  margin: 0 0 10px 25px;
+}
+ul ul,
+ul ol,
+ol ol,
+ol ul {
+  margin-bottom: 0;
+}
+li {
+  line-height: 20px;
+}
+ul.unstyled,
+ol.unstyled {
+  margin-left: 0;
+  list-style: none;
+}
+dl {
+  margin-bottom: 20px;
+}
+dt,
+dd {
+  line-height: 20px;
+}
+dt {
+  font-weight: bold;
+}
+dd {
+  margin-left: 10px;
+}
+blockquote {
+  padding: 0 0 0 15px;
+  margin: 0 0 20px;
+  border-left: 5px solid #eeeeee;
+}
+blockquote p {
+  margin-bottom: 0;
+  font-size: 16px;
+  font-weight: 300;
+  line-height: 25px;
+}
+blockquote:before,
+blockquote:after {
+  content: "";
+}
+.fragment,
+code,
+pre {
+  padding: 0 3px 2px;
+  font-family: monospace;
+  font-size: 12px;
+  color: #333333;
+  -webkit-border-radius: 3px;
+  -moz-border-radius: 3px;
+  border-radius: 3px;
+}
+.fragment,
+code {
+  padding: 2px 4px;
+  color: #d14;
+  background-color: #f7f7f9;
+  border: 1px solid #e1e1e8;
+}
+pre {
+  display: block;
+  padding: 9.5px;
+  margin: 0 0 10px;
+  font-size: 13px;
+  line-height: 20px;
+  word-break: break-all;
+  word-wrap: break-word;
+  white-space: pre;
+  white-space: pre-wrap;
+  background-color: #f5f5f5;
+  border: 1px solid #ccc;
+  border: 1px solid rgba(0, 0, 0, 0.15);
+  -webkit-border-radius: 4px;
+  -moz-border-radius: 4px;
+  border-radius: 4px;
+}
+pre code {
+  padding: 0;
+  color: inherit;
+  background-color: transparent;
+  border: 0;
+}
+.label,
+.badge {
+  font-size: 11.844px;
+  font-weight: bold;
+  line-height: 14px;
+  color: #ffffff;
+  vertical-align: baseline;
+  white-space: nowrap;
+  text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
+  background-color: #999999;
+}
+.label {
+  padding: 1px 4px 2px;
+  -webkit-border-radius: 3px;
+  -moz-border-radius: 3px;
+  border-radius: 3px;
+}
+.badge {
+  padding: 1px 9px 2px;
+  -webkit-border-radius: 9px;
+  -moz-border-radius: 9px;
+  border-radius: 9px;
+}
+a.label:hover,
+a.badge:hover {
+  color: #ffffff;
+  text-decoration: none;
+  cursor: pointer;
+}
+.label-important,
+.badge-important {
+  background-color: #b94a48;
+}
+.label-important[href],
+.badge-important[href] {
+  background-color: #953b39;
+}
+.label-warning,
+.badge-warning {
+  background-color: #f89406;
+}
+.label-warning[href],
+.badge-warning[href] {
+  background-color: #c67605;
+}
+.label-success,
+.badge-success {
+  background-color: #468847;
+}
+.label-success[href],
+.badge-success[href] {
+  background-color: #356635;
+}
+.label-info,
+.badge-info {
+  background-color: #3a87ad;
+}
+.label-info[href],
+.badge-info[href] {
+  background-color: #2d6987;
+}
+.label-inverse,
+.badge-inverse {
+  background-color: #333333;
+}
+.label-inverse[href],
+.badge-inverse[href] {
+  background-color: #1a1a1a;
+}
+table {
+  max-width: 100%;
+  background-color: transparent;
+  border-collapse: collapse;
+  border-spacing: 0;
+}
+
+table [class*=span],
+.row-fluid table [class*=span] {
+  display: table-cell;
+  float: none;
+  margin-left: 0;
+}
+fieldset {
+  padding: 0;
+  margin: 0;
+  border: 0;
+}
+legend {
+  display: block;
+  width: 100%;
+  padding: 0;
+  margin-bottom: 20px;
+  font-size: 21px;
+  line-height: 40px;
+  color: #333333;
+  border: 0;
+  border-bottom: 1px solid #e5e5e5;
+}
+legend small {
+  font-size: 15px;
+  color: #999999;
+}
+label,
+input,
+button,
+select,
+textarea {
+  font-size: 14px;
+  font-weight: normal;
+  line-height: 20px;
+}
+input,
+button,
+select,
+textarea {
+  font-family: sans-serif;
+}
+label {
+  display: block;
+  margin-bottom: 5px;
+}
+
+.tablist {
+  margin-left: 0;
+  margin-bottom: 20px;
+  list-style: none;
+}
+.tablist > li > a {
+  display: block;
+}
+.tablist > li > a:hover {
+  text-decoration: none;
+  background-color: #eeeeee;
+}
+.tablist > .pull-right {
+  float: right;
+}
+.tablist-header {
+  display: block;
+  padding: 3px 15px;
+  font-size: 11px;
+  font-weight: bold;
+  line-height: 20px;
+  color: #999999;
+  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
+  text-transform: uppercase;
+}
+.tablist li + .tablist-header {
+  margin-top: 9px;
+}
+.tablist-list {
+  padding-left: 15px;
+  padding-right: 15px;
+  margin-bottom: 0;
+}
+.tablist-list > li > a,
+.tablist-list .tablist-header {
+  margin-left: -15px;
+  margin-right: -15px;
+  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
+}
+.tablist-list > li > a {
+  padding: 3px 15px;
+}
+.tablist-list > .current > a,
+.tablist-list > .current > a:hover {
+  color: #ffffff;
+  text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.2);
+  background-color: #0088cc;
+}
+.tablist-list [class^="icon-"] {
+  margin-right: 2px;
+}
+.tablist-list .divider {
+  *width: 100%;
+  height: 1px;
+  margin: 9px 1px;
+  *margin: -5px 0 5px;
+  overflow: hidden;
+  background-color: #e5e5e5;
+  border-bottom: 1px solid #ffffff;
+}
+.tablist-tabs,
+.tablist {
+  *zoom: 1;
+}
+.tablist-tabs:before,
+.tablist:before,
+.tablist-tabs:after,
+.tablist:after {
+  display: table;
+  content: "";
+  line-height: 0;
+}
+.tablist-tabs:after,
+.tablist:after {
+  clear: both;
+}
+.tablist-tabs > li,
+.tablist > li {
+  float: left;
+}
+.tablist-tabs > li > a,
+.tablist > li > a {
+  padding-right: 12px;
+  padding-left: 12px;
+  margin-right: 2px;
+  line-height: 14px;
+}
+.tablist-tabs {
+  border-bottom: 1px solid #ddd;
+}
+.tablist-tabs > li {
+  margin-bottom: -1px;
+}
+.tablist-tabs > li > a {
+  padding-top: 8px;
+  padding-bottom: 8px;
+  line-height: 20px;
+  border: 1px solid transparent;
+  -webkit-border-radius: 4px 4px 0 0;
+  -moz-border-radius: 4px 4px 0 0;
+  border-radius: 4px 4px 0 0;
+}
+.tablist-tabs > li > a:hover {
+  border-color: #eeeeee #eeeeee #dddddd;
+}
+.tablist-tabs > .current > a,
+.tablist-tabs > .current > a:hover {
+  color: #555555;
+  background-color: #ffffff;
+  border: 1px solid #ddd;
+  border-bottom-color: transparent;
+  cursor: default;
+}
+.tablist > li > a {
+  padding-top: 8px;
+  padding-bottom: 8px;
+  margin-top: 2px;
+  margin-bottom: 2px;
+  -webkit-border-radius: 5px;
+  -moz-border-radius: 5px;
+  border-radius: 5px;
+}
+.tablist > .current > a,
+.tablist > .current > a:hover {
+  color: #ffffff;
+  background-color: #0088cc;
+}
+.tablist-stacked > li {
+  float: none;
+}
+.tablist-stacked > li > a {
+  margin-right: 0;
+}
+.tablist-tabs.tablist-stacked {
+  border-bottom: 0;
+}
+.tablist-tabs.tablist-stacked > li > a {
+  border: 1px solid #ddd;
+  -webkit-border-radius: 0;
+  -moz-border-radius: 0;
+  border-radius: 0;
+}
+.tablist-tabs.tablist-stacked > li:first-child > a {
+  -webkit-border-top-right-radius: 4px;
+  -moz-border-radius-topright: 4px;
+  border-top-right-radius: 4px;
+  -webkit-border-top-left-radius: 4px;
+  -moz-border-radius-topleft: 4px;
+  border-top-left-radius: 4px;
+}
+.tablist-tabs.tablist-stacked > li:last-child > a {
+  -webkit-border-bottom-right-radius: 4px;
+  -moz-border-radius-bottomright: 4px;
+  border-bottom-right-radius: 4px;
+  -webkit-border-bottom-left-radius: 4px;
+  -moz-border-radius-bottomleft: 4px;
+  border-bottom-left-radius: 4px;
+}
+.tablist-tabs.tablist-stacked > li > a:hover {
+  border-color: #ddd;
+  z-index: 2;
+}
+.tablist.tablist-stacked > li > a {
+  margin-bottom: 3px;
+}
+.tablist.tablist-stacked > li:last-child > a {
+  margin-bottom: 1px;
+}
+.tablist-tabs .dropdown-menu {
+  -webkit-border-radius: 0 0 6px 6px;
+  -moz-border-radius: 0 0 6px 6px;
+  border-radius: 0 0 6px 6px;
+}
+.tablist .dropdown-menu {
+  -webkit-border-radius: 6px;
+  -moz-border-radius: 6px;
+  border-radius: 6px;
+}
+.tablist .dropdown-toggle .caret {
+  border-top-color: #0088cc;
+  border-bottom-color: #0088cc;
+  margin-top: 6px;
+}
+.tablist .dropdown-toggle:hover .caret {
+  border-top-color: #005580;
+  border-bottom-color: #005580;
+}
+/* move down carets for tabs */
+.tablist-tabs .dropdown-toggle .caret {
+  margin-top: 8px;
+}
+.tablist .current .dropdown-toggle .caret {
+  border-top-color: #fff;
+  border-bottom-color: #fff;
+}
+.tablist-tabs .current .dropdown-toggle .caret {
+  border-top-color: #555555;
+  border-bottom-color: #555555;
+}
+.tablist > .dropdown.current > a:hover {
+  cursor: pointer;
+}
+.tablist-tabs .open .dropdown-toggle,
+.tablist .open .dropdown-toggle,
+.tablist > li.dropdown.open.current > a:hover {
+  color: #ffffff;
+  background-color: #999999;
+  border-color: #999999;
+}
+.tablist li.dropdown.open .caret,
+.tablist li.dropdown.open.current .caret,
+.tablist li.dropdown.open a:hover .caret {
+  border-top-color: #ffffff;
+  border-bottom-color: #ffffff;
+  opacity: 1;
+  filter: alpha(opacity=100);
+}
+.tabs-stacked .open > a:hover {
+  border-color: #999999;
+}
+.tab-content > .tab-pane,
+.pill-content > .pill-pane {
+  display: none;
+}
+.tab-content > .current,
+.pill-content > .current {
+  display: block;
+}
+.tabs-below > .tablist-tabs {
+  border-top: 1px solid #ddd;
+}
+.tabs-below > .tablist-tabs > li {
+  margin-top: -1px;
+  margin-bottom: 0;
+}
+.tabs-below > .tablist-tabs > li > a {
+  -webkit-border-radius: 0 0 4px 4px;
+  -moz-border-radius: 0 0 4px 4px;
+  border-radius: 0 0 4px 4px;
+}
+.tabs-below > .tablist-tabs > li > a:hover {
+  border-bottom-color: transparent;
+  border-top-color: #ddd;
+}
+.tabs-below > .tablist-tabs > .current > a,
+.tabs-below > .tablist-tabs > .current > a:hover {
+  border-color: transparent #ddd #ddd #ddd;
+}
+.tabs-left > .tablist-tabs > li,
+.tabs-right > .tablist-tabs > li {
+  float: none;
+}
+.tabs-left > .tablist-tabs > li > a,
+.tabs-right > .tablist-tabs > li > a {
+  min-width: 74px;
+  margin-right: 0;
+  margin-bottom: 3px;
+}
+.tabs-left > .tablist-tabs {
+  float: left;
+  margin-right: 19px;
+  border-right: 1px solid #ddd;
+}
+.tabs-left > .tablist-tabs > li > a {
+  margin-right: -1px;
+  -webkit-border-radius: 4px 0 0 4px;
+  -moz-border-radius: 4px 0 0 4px;
+  border-radius: 4px 0 0 4px;
+}
+.tabs-left > .tablist-tabs > li > a:hover {
+  border-color: #eeeeee #dddddd #eeeeee #eeeeee;
+}
+.tabs-left > .tablist-tabs .current > a,
+.tabs-left > .tablist-tabs .current > a:hover {
+  border-color: #ddd transparent #ddd #ddd;
+  *border-right-color: #ffffff;
+}
+.tabs-right > .tablist-tabs {
+  float: right;
+  margin-left: 19px;
+  border-left: 1px solid #ddd;
+}
+.tabs-right > .tablist-tabs > li > a {
+  margin-left: -1px;
+  -webkit-border-radius: 0 4px 4px 0;
+  -moz-border-radius: 0 4px 4px 0;
+  border-radius: 0 4px 4px 0;
+}
+.tabs-right > .tablist-tabs > li > a:hover {
+  border-color: #eeeeee #eeeeee #eeeeee #dddddd;
+}
+.tabs-right > .tablist-tabs .current > a,
+.tabs-right > .tablist-tabs .current > a:hover {
+  border-color: #ddd #ddd #ddd transparent;
+  *border-left-color: #ffffff;
+}
+.tablist > .disabled > a {
+  color: #999999;
+}
+.tablist > .disabled > a:hover {
+  text-decoration: none;
+  background-color: transparent;
+  cursor: default;
+}
+.tablistbar {
+  overflow: visible;
+  margin-bottom: 20px;
+  color: #ffffff;
+  *position: relative;
+  *z-index: 2;
+}
+.tablistbar-inner {
+  min-height: 40px;
+  padding-left: 20px;
+  padding-right: 20px;
+  background-color: #034c03;
+  background-image: -moz-linear-gradient(top, #024002, #045f04);
+  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#024002), to(#045f04));
+  background-image: -webkit-linear-gradient(top, #024002, #045f04);
+  background-image: -o-linear-gradient(top, #024002, #045f04);
+  background-image: linear-gradient(to bottom, #024002, #045f04);
+  background-repeat: repeat-x;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff024002', endColorstr='#ff045f04', GradientType=0);
+  border: 1px solid #022402;
+  -webkit-border-radius: 4px;
+  -moz-border-radius: 4px;
+  border-radius: 4px;
+  -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065);
+  -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065);
+  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065);
+  *zoom: 1;
+}
+.tablistbar-inner:before,
+.tablistbar-inner:after {
+  display: table;
+  content: "";
+  line-height: 0;
+}
+.tablistbar-inner:after {
+  clear: both;
+}
+.tablistbar .container {
+  width: auto;
+}
+.tablist-collapse.collapse {
+  height: auto;
+}
+.tablistbar .brand {
+  float: left;
+  display: block;
+  padding: 10px 20px 10px;
+  margin-left: -20px;
+  font-size: 20px;
+  font-weight: 200;
+  color: #ffffff;
+  text-shadow: 0 1px 0 #024002;
+}
+.tablistbar .brand:hover {
+  text-decoration: none;
+}
+.tablistbar-text {
+  margin-bottom: 0;
+  line-height: 40px;
+}
+.tablistbar-link {
+  color: #ffffff;
+}
+.tablistbar-link:hover {
+  color: #333333;
+}
+.tablistbar .tablist {
+  position: relative;
+  left: 0;
+  display: block;
+  float: left;
+  margin: 0 10px 0 0;
+}
+.tablistbar .tablist.pull-right {
+  float: right;
+  margin-right: 0;
+}
+.tablistbar .tablist > li {
+  float: left;
+}
+.tablistbar .tablist > li > a {
+  float: none;
+  padding: 10px 15px 10px;
+  color: #ffffff;
+  text-decoration: none;
+  text-shadow: 0 1px 0 #024002;
+}
+.tablistbar .tablist .dropdown-toggle .caret {
+  margin-top: 8px;
+}
+.tablistbar .tablist > li > a:focus,
+.tablistbar .tablist > li > a:hover {
+  background-color: transparent;
+  color: white;
+  text-decoration: none;
+}
+.tablistbar .tablist > .current > a,
+.tablistbar .tablist > .current > a:hover,
+.tablistbar .tablist > .current > a:focus {
+  color: #555555;
+  text-decoration: none;
+  background-color: #034703;
+  -webkit-box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125);
+  -moz-box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125);
+  box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125);
+}
+.tablistbar .btn-navbar {
+  display: none;
+  float: right;
+  padding: 7px 10px;
+  margin-left: 5px;
+  margin-right: 5px;
+  color: #ffffff;
+  text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
+  background-color: #023402;
+  background-image: -moz-linear-gradient(top, #012701, #034703);
+  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#012701), to(#034703));
+  background-image: -webkit-linear-gradient(top, #012701, #034703);
+  background-image: -o-linear-gradient(top, #012701, #034703);
+  background-image: linear-gradient(to bottom, #012701, #034703);
+  background-repeat: repeat-x;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff012701', endColorstr='#ff034703', GradientType=0);
+  border-color: #034703 #034703 #000000;
+  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
+  *background-color: #034703;
+  /* Darken IE7 buttons by default so they stand out more given they won't have borders */
+
+  filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
+  -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075);
+  -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075);
+  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075);
+}
+.tablistbar .tablist > li > .dropdown-menu:before {
+  content: '';
+  display: inline-block;
+  border-left: 7px solid transparent;
+  border-right: 7px solid transparent;
+  border-bottom: 7px solid #ccc;
+  border-bottom-color: rgba(0, 0, 0, 0.2);
+  position: absolute;
+  top: -7px;
+  left: 9px;
+}
+.tablistbar .tablist > li > .dropdown-menu:after {
+  content: '';
+  display: inline-block;
+  border-left: 6px solid transparent;
+  border-right: 6px solid transparent;
+  border-bottom: 6px solid #ffffff;
+  position: absolute;
+  top: -6px;
+  left: 10px;
+}
+.tablistbar .tablist li.dropdown.open > .dropdown-toggle,
+.tablistbar .tablist li.dropdown.current > .dropdown-toggle,
+.tablistbar .tablist li.dropdown.open.current > .dropdown-toggle {
+  background-color: #034703;
+  color: #555555;
+}
+.tablistbar .tablist li.dropdown > .dropdown-toggle .caret {
+  border-top-color: #ffffff;
+  border-bottom-color: #ffffff;
+}
+.tablistbar .tablist li.dropdown.open > .dropdown-toggle .caret,
+.tablistbar .tablist li.dropdown.current > .dropdown-toggle .caret,
+.tablistbar .tablist li.dropdown.open.current > .dropdown-toggle .caret {
+  border-top-color: #555555;
+  border-bottom-color: #555555;
+}
+.tablistbar .pull-right > li > .dropdown-menu,
+.tablistbar .tablist > li > .dropdown-menu.pull-right {
+  left: auto;
+  right: 0;
+}
+.tablistbar .pull-right > li > .dropdown-menu:before,
+.tablistbar .tablist > li > .dropdown-menu.pull-right:before {
+  left: auto;
+  right: 12px;
+}
+.tablistbar .pull-right > li > .dropdown-menu:after,
+.tablistbar .tablist > li > .dropdown-menu.pull-right:after {
+  left: auto;
+  right: 13px;
+}
+.tablistbar .pull-right > li > .dropdown-menu .dropdown-menu,
+.tablistbar .tablist > li > .dropdown-menu.pull-right .dropdown-menu {
+  left: auto;
+  right: 100%;
+  margin-left: 0;
+  margin-right: -1px;
+  -webkit-border-radius: 6px 0 6px 6px;
+  -moz-border-radius: 6px 0 6px 6px;
+  border-radius: 6px 0 6px 6px;
+}
+.breadcrumb {
+  padding: 8px 15px;
+  margin: 0 0 20px;
+  list-style: none;
+  background-color: #f5f5f5;
+  -webkit-border-radius: 4px;
+  -moz-border-radius: 4px;
+  border-radius: 4px;
+}
+.breadcrumb li {
+  display: inline-block;
+  *display: inline;
+  /* IE7 inline-block hack */
+
+  *zoom: 1;
+  text-shadow: 0 1px 0 #ffffff;
+}
+.breadcrumb .divider {
+  padding: 0 5px;
+  color: #ccc;
+}
+.breadcrumb .current {
+  color: #999999;
+}
+.pagination-right {
+  text-align: right;
+}
+.fade {
+  opacity: 0;
+  -webkit-transition: opacity 0.15s linear;
+  -moz-transition: opacity 0.15s linear;
+  -o-transition: opacity 0.15s linear;
+  transition: opacity 0.15s linear;
+}
+.fade.in {
+  opacity: 1;
+}
+.collapse {
+  position: relative;
+  height: 0;
+  overflow: hidden;
+  -webkit-transition: height 0.35s ease;
+  -moz-transition: height 0.35s ease;
+  -o-transition: height 0.35s ease;
+  transition: height 0.35s ease;
+}
+.collapse.in {
+  height: auto;
+}
+.hidden {
+  display: none;
+  visibility: hidden;
+}
+.visible-phone {
+  display: none !important;
+}
+.visible-tablet {
+  display: none !important;
+}
+.hidden-desktop {
+  display: none !important;
+}
+.visible-desktop {
+  display: inherit !important;
+}
+@media (min-width: 768px) and (max-width: 979px) {
+  .hidden-desktop {
+    display: inherit !important;
+  }
+  .visible-desktop {
+    display: none !important ;
+  }
+  .visible-tablet {
+    display: inherit !important;
+  }
+  .hidden-tablet {
+    display: none !important;
+  }
+}
+@media (max-width: 767px) {
+  .hidden-desktop {
+    display: inherit !important;
+  }
+  .visible-desktop {
+    display: none !important;
+  }
+  .visible-phone {
+    display: inherit !important;
+  }
+  .hidden-phone {
+    display: none !important;
+  }
+}
+@media (max-width: 767px) {
+  body {
+    padding-left: 20px;
+    padding-right: 20px;
+  }
+  .container {
+    width: auto;
+  }
+  .row,
+  .thumbnails {
+    margin-left: 0;
+  }
+}
+@media (max-width: 480px) {
+  .tablist-collapse {
+    -webkit-transform: translate3d(0, 0, 0);
+  }
+  .page-header h1 small {
+    display: block;
+    line-height: 20px;
+  }
+}
+@media (min-width: 768px) and (max-width: 979px) {
+  .row {
+    margin-left: -20px;
+    *zoom: 1;
+  }
+  .row:before,
+  .row:after {
+    display: table;
+    content: "";
+    line-height: 0;
+  }
+  .row:after {
+    clear: both;
+  }
+  [class*="span"] {
+    float: left;
+    min-height: 1px;
+    margin-left: 20px;
+  }
+  .container {
+    width: 724px;
+  }
+}
+@media (min-width: 1200px) {
+  .row {
+    margin-left: -30px;
+    *zoom: 1;
+  }
+  .row:before,
+  .row:after {
+    display: table;
+    content: "";
+    line-height: 0;
+  }
+  .row:after {
+    clear: both;
+  }
+  [class*="span"] {
+    float: left;
+    min-height: 1px;
+    margin-left: 30px;
+  }
+  .container {
+    width: 1070px;
+  }
+}
+@media (max-width: 979px) {
+  body {
+    padding-top: 0;
+  }
+}
+@media (min-width: 980px) {
+  .tablist-collapse.collapse {
+    height: auto !important;
+    overflow: visible !important;
+  }
+}
+.tablistbar .brand {
+  padding: 5px;
+  margin-left: 0;
+}
+.tablistbar .brand img {
+  width: 30px;
+  vertical-align: middle;
+}
+
+h1 small {
+  font-size: 18px;
+}
+
+h1 small,
+h2 small,
+h3 small,
+h4 small,
+h5 small,
+h6 small,
+.page-header small {
+  line-height: 0.8;
+  font-weight: normal;
+  color: #999999;
+  display:block;
+  vertical-align: middle;
+}
+
+.page-header h1, h1:first-child {
+  font-size: 40px;
+  padding-bottom: 5px;
+}
+
+.page-header h1 {
+  border-bottom: 1px solid #999999;
+  padding-bottom: 9px;
+}
+
+.page-header img {
+  height: 80px;
+  padding-bottom: 5px;
+}
+
+.page-header small {
+  line-height: 1.1;
+  font-size: 18px;
+}
+
+h2,
+h3,
+h4,
+div.ah,
+.title {
+  border-color: #D6E9C6;
+  color: #468847;
+  border-style: solid;
+  border-width: 0 0 1px;
+  padding-left: 0.5em;
+}
+
+
+.google {
+  color: white;
+}
+
+.breadcrumb {
+  font-size: 11px;
+  padding-top: 2px;
+  padding-bottom: 2px;
+}
+
+h1 a,
+h2 a,
+h3 a,
+h4 a {
+  color: inherit;
+}
+
+.tablistbar-inner a {
+  font-weight: bold;
+}
+
+.list-2panes:before,
+.list-2panes:after {
+  display: table;
+  content: "";
+  line-height: 0;
+}
+
+.list-2panes:after {
+  clear:both;
+}
+
+.list-2panes li {
+  width: 470px;
+  width: 470px;
+  float: left;
+  margin-left: 30px;
+  min-height: 1px;
+}
 /* The standard CSS for doxygen */
 
 /* @group Heading Levels */
 
 
-h1 {
-    font-size: 150%;
-}
-
-.title {
-    font-weight: bold;
-    margin: 10px 2px;
-    background-color: #7BB37B;
-    border: 1px solid #6A996A;
-    color: #151515;
-    font-size: 1.2em;
-    padding-bottom: 0.2em;
-    padding-left: 0.4em;
-    padding-top: 0.2em;
-}
-
-h2 {
-    font-size: 120%;
-}
-
-h3 {
-    font-size: 100%;
-}
-
 dt {
     font-weight: bold;
 }
@@ -70,18 +1176,18 @@
         text-align: center;
 }
 
-div.qindex, div.navtab{
+div.qindex, div.tablisttab{
     background-color: #EBF6EB;
     border: 1px solid #A3D7A3;
     text-align: center;
 }
 
-div.qindex, div.navpath {
+div.qindex, div.tablistpath {
     width: 100%;
     line-height: 140%;
 }
 
-div.navtab {
+div.tablisttab {
     margin-right: 15px;
 }
 
@@ -153,24 +1259,6 @@
     line-height: 125%;
 }
 
-div.ah {
-    background-color: black;
-    font-weight: bold;
-    color: #ffffff;
-    margin-bottom: 3px;
-    margin-top: 3px;
-    padding: 0.2em;
-    border: solid thin #333;
-    border-radius: 0.5em;
-    -webkit-border-radius: .5em;
-    -moz-border-radius: .5em;
-    box-shadow: 2px 2px 3px #999;
-    -webkit-box-shadow: 2px 2px 3px #999;
-    -moz-box-shadow: rgba(0, 0, 0, 0.15) 2px 2px 2px;
-    background-image: -webkit-gradient(linear, left top, left bottom, from(#eee), to(#000),color-stop(0.3, #444));
-    background-image: -moz-linear-gradient(center top, #eee 0%, #444 40%, #000);
-}
-
 div.groupHeader {
     margin-left: 16px;
     margin-top: 12px;
@@ -189,21 +1277,10 @@
 }
 
 td.indexkey {
-    background-color: #EBF6EB;
-    font-weight: bold;
-    border: 1px solid #C4E5C4;
-    margin: 2px 0px 2px 0;
-    padding: 2px 10px;
-        white-space: nowrap;
-        vertical-align: top;
+    white-space: nowrap;
+    vertical-align: top;
 }
 
-td.indexvalue {
-    background-color: #EBF6EB;
-    border: 1px solid #C4E5C4;
-    padding: 2px 10px;
-    margin: 2px 0px;
-}
 
 tr.memlist {
     background-color: #EEF7EE;
@@ -696,7 +1773,7 @@
     font-size: 13px;
 }
 
-.navpath ul
+.tablistpath ul
 {
     font-size: 11px;
     background-image:url('tab_b.png');
@@ -710,7 +1787,7 @@
     padding:0px;
 }
 
-.navpath li
+.tablistpath li
 {
     list-style-type:none;
     float:left;
@@ -722,7 +1799,7 @@
     color:#367C36;
 }
 
-.navpath li.navelem a
+.tablistpath li.tablistelem a
 {
     height:32px;
     display:block;
@@ -730,12 +1807,12 @@
     outline: none;
 }
 
-.navpath li.navelem a:hover
+.tablistpath li.tablistelem a:hover
 {
     color:#68BD68;
 }
 
-.navpath li.footer
+.tablistpath li.footer
 {
         list-style-type:none;
         float:right;
@@ -937,161 +2014,6 @@
   }
 }
 
-/* tabs */
-
-.tabs, .tabs2, .tabs3 {
-    z-index: 101;
-}
-
-.tablist {
-    margin: auto;
-    display: table;
-}
-
-.tablist li {
-    float: left;
-    display: table-cell;
-    list-style: none;
-    margin:0 4px;
-}
-
-.tablist a {
-    display: block;
-    padding: 0 0.3em;
-    color: #285D28;
-    text-decoration: none;
-    outline: none;
-}
-
-.tabs3 .tablist a {
-    padding-left: 10px;
-}
-
-
-/* libav.org stylesheet */
-
-a {
-    color: #2D6198;
-}
-
-a:visited {
-    color: #884488;
-}
-
-h1 a, h2 a, h3 a {
-    text-decoration: inherit;
-    color: inherit;
-}
-
-#body {
-    margin: 0 1em;
-}
-
-body {
-    background-color: #313131;
-    margin: 0;
-}
-
-.center {
-    margin-left: auto;
-    margin-right: auto;
-    text-align: center;
-}
-
-#container {
-    background-color: white;
-    color: #202020;
-    margin-left: 1em;
-    margin-right: 1em;
-}
-
-h1 {
-    background-color: #7BB37B;
-    border: 1px solid #6A996A;
-    color: #151515;
-    font-size: 1.2em;
-    padding-bottom: 0.2em;
-    padding-left: 0.4em;
-    padding-top: 0.2em;
-}
-
-h2 {
-    color: #313131;
-    font-size: 1.2em;
-}
-
-h3 {
-    color: #313131;
-    font-size: 0.8em;
-    margin-bottom: -8px;
-}
-
-img {
-    border: 0;
-}
-
-.tabs {
-    margin-top: 12px;
-    border-top: 1px solid #5C665C;
-}
-
-.tabs, .tabs2, .tabs3, .tabs4 {
-    background-color: #738073;
-    border-bottom: 1px solid #5C665C;
-    border-left: 1px solid #5C665C;
-    border-right: 1px solid #5C665C;
-    position: relative;
-    text-align: center;
-}
-
-.tabs a,
-.tabs2 a,
-.tabs3 a,
-.tabs4 a {
-    color: white;
-    padding: 0.3em;
-    text-decoration: none;
-}
-
-
-.tabs ul,
-.tabs2 ul,
-.tabs3 ul,
-.tabs4 ul {
-    padding: 0;
-}
-
-.tabs li.current a,
-.tabs2 li.current a,
-.tabs3 li.current a,
-.tabs4 li.current a {
-    background-color: #414141;
-    color: white;
-    text-decoration: none;
-}
-
-.tabs a:hover,
-.tabs2 a:hover,
-.tabs3 a:hover,
-.tabs4 a:hover {
-    background-color: #313131 !important;
-    color: white;
-    text-decoration: none;
-}
-
-p {
-    margin-left: 1em;
-    margin-right: 1em;
-}
-
-table {
-    margin-left: 2em;
-}
-
-pre {
-    margin-left: 2em;
-}
-
 #proj_desc {
     font-size: 1.2em;
 }
diff --git a/doc/doxy/footer.html b/doc/doxy/footer.html
index 7217351..101e6fe 100644
--- a/doc/doxy/footer.html
+++ b/doc/doxy/footer.html
@@ -1,10 +1,9 @@
- </div>
 
- <div id="footer">
-   Generated on $datetime for $projectname by&#160;<a href="http://www.doxygen.org/index.html">doxygen</a> $doxygenversion
- </div>
-
+ <footer class="footer pagination-right">
+   <span class="label label-info">
+    Generated on $datetime for $projectname by&#160;<a href="http://www.doxygen.org/index.html">doxygen</a> $doxygenversion
+   </span>
+ </footer>
 </div>
-
 </body>
 </html>
diff --git a/doc/doxy/header.html b/doc/doxy/header.html
index 9e57c98..312990c 100644
--- a/doc/doxy/header.html
+++ b/doc/doxy/header.html
@@ -1,14 +1,16 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
+<!DOCTYPE html>
+<html>
 <head>
-<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
 <meta http-equiv="X-UA-Compatible" content="IE=9"/>
 <!--BEGIN PROJECT_NAME--><title>$projectname: $title</title><!--END PROJECT_NAME-->
 <!--BEGIN !PROJECT_NAME--><title>$title</title><!--END !PROJECT_NAME-->
 <link href="$relpath$doxy_stylesheet.css" rel="stylesheet" type="text/css" />
+<!--Header replace -->
+
 </head>
 
-<div id="container">
+<div class="container">
 
-<div id="body">
- <div>
+<!--Header replace -->
+<div class="menu">
diff --git a/doc/encoders.texi b/doc/encoders.texi
index a7a2761..da44c17 100644
--- a/doc/encoders.texi
+++ b/doc/encoders.texi
@@ -420,6 +420,45 @@
 A description of some of the currently available video encoders
 follows.
 
+@section libtheora
+
+Theora format supported through libtheora.
+
+Requires the presence of the libtheora headers and library during
+configuration. You need to explicitly configure the build with
+@code{--enable-libtheora}.
+
+@subsection Options
+
+The following global options are mapped to internal libtheora options
+which affect the quality and the bitrate of the encoded stream.
+
+@table @option
+@item b
+Set the video bitrate, only works if the @code{qscale} flag in
+@option{flags} is not enabled.
+
+@item flags
+Used to enable constant quality mode encoding through the
+@option{qscale} flag, and to enable the @code{pass1} and @code{pass2}
+modes.
+
+@item g
+Set the GOP size.
+
+@item global_quality
+Set the global quality in lambda units, only works if the
+@code{qscale} flag in @option{flags} is enabled. The value is clipped
+in the [0 - 10*@code{FF_QP2LAMBDA}] range, and then multiplied for 6.3
+to get a value in the native libtheora range [0-63].
+
+For example, to set maximum constant quality encoding with
+@command{ffmpeg}:
+@example
+ffmpeg -i INPUT -flags:v qscale -global_quality:v "10*QP2LAMBDA" -codec:v libtheora OUTPUT.ogg
+@end example
+@end table
+
 @section libvpx
 
 VP8 format supported through libvpx.
@@ -580,7 +619,9 @@
 Allow to set any x264 option, see x264 --fullhelp for a list.
 
 @var{options} is a list of @var{key}=@var{value} couples separated by
-":".
+":". In @var{filter} and @var{psy-rd} options that use ":" as a separator
+themselves, use "," instead. They accept it as well since long ago but this
+is kept undocumented for some reason.
 @end table
 
 For example to specify libx264 encoding options with @command{ffmpeg}:
diff --git a/doc/examples/README b/doc/examples/README
new file mode 100644
index 0000000..a461813
--- /dev/null
+++ b/doc/examples/README
@@ -0,0 +1,18 @@
+FFmpeg examples README
+----------------------
+
+Both following use cases rely on pkg-config and make, thus make sure
+that you have them installed and working on your system.
+
+
+1) Build the installed examples in a generic read/write user directory
+
+Copy to a read/write user directory and just use "make", it will link
+to the libraries on your system, assuming the PKG_CONFIG_PATH is
+correctly configured.
+
+2) Build the examples in-tree
+
+Assuming you are in the source FFmpeg checkout directory, you need to build
+FFmpeg (no need to make install in any prefix). Then you can go into the
+doc/examples and run a command such as PKG_CONFIG_PATH=pc-uninstalled make.
diff --git a/doc/examples/decoding_encoding.c b/doc/examples/decoding_encoding.c
index fcd7dfb..ae1057c 100644
--- a/doc/examples/decoding_encoding.c
+++ b/doc/examples/decoding_encoding.c
@@ -27,13 +27,14 @@
  * Note that libavcodec only handles codecs (mpeg, mpeg4, etc...),
  * not file formats (avi, vob, mp4, mov, mkv, mxf, flv, mpegts, mpegps, etc...). See library 'libavformat' for the
  * format handling
+ * @example doc/examples/decoding_encoding.c
  */
 
 #include <math.h>
 
 #include <libavutil/opt.h>
 #include <libavcodec/avcodec.h>
-#include <libavutil/audioconvert.h>
+#include <libavutil/channel_layout.h>
 #include <libavutil/common.h>
 #include <libavutil/imgutils.h>
 #include <libavutil/mathematics.h>
@@ -121,6 +122,10 @@
     }
 
     c = avcodec_alloc_context3(codec);
+    if (!c) {
+        fprintf(stderr, "Could not allocate audio codec context\n");
+        exit(1);
+    }
 
     /* put sample parameters */
     c->bit_rate = 64000;
@@ -252,6 +257,10 @@
     }
 
     c = avcodec_alloc_context3(codec);
+    if (!c) {
+        fprintf(stderr, "Could not allocate audio codec context\n");
+        exit(1);
+    }
 
     /* open it */
     if (avcodec_open2(c, codec, NULL) < 0) {
@@ -346,6 +355,10 @@
     }
 
     c = avcodec_alloc_context3(codec);
+    if (!c) {
+        fprintf(stderr, "Could not allocate video codec context\n");
+        exit(1);
+    }
 
     /* put sample parameters */
     c->bit_rate = 400000;
@@ -356,7 +369,7 @@
     c->time_base= (AVRational){1,25};
     c->gop_size = 10; /* emit one intra frame every ten frames */
     c->max_b_frames=1;
-    c->pix_fmt = PIX_FMT_YUV420P;
+    c->pix_fmt = AV_PIX_FMT_YUV420P;
 
     if(codec_id == AV_CODEC_ID_H264)
         av_opt_set(c->priv_data, "preset", "slow", 0);
@@ -475,15 +488,42 @@
     fclose(f);
 }
 
+static int decode_write_frame(const char *outfilename, AVCodecContext *avctx,
+                              AVFrame *frame, int *frame_count, AVPacket *pkt, int last)
+{
+    int len, got_frame;
+    char buf[1024];
+
+    len = avcodec_decode_video2(avctx, frame, &got_frame, pkt);
+    if (len < 0) {
+        fprintf(stderr, "Error while decoding frame %d\n", *frame_count);
+        return len;
+    }
+    if (got_frame) {
+        printf("Saving %sframe %3d\n", last ? "last " : "", *frame_count);
+        fflush(stdout);
+
+        /* the picture is allocated by the decoder, no need to free it */
+        snprintf(buf, sizeof(buf), outfilename, *frame_count);
+        pgm_save(frame->data[0], frame->linesize[0],
+                 avctx->width, avctx->height, buf);
+        (*frame_count)++;
+    }
+    if (pkt->data) {
+        pkt->size -= len;
+        pkt->data += len;
+    }
+    return 0;
+}
+
 static void video_decode_example(const char *outfilename, const char *filename)
 {
     AVCodec *codec;
     AVCodecContext *c= NULL;
-    int frame, got_picture, len;
+    int frame_count;
     FILE *f;
-    AVFrame *picture;
+    AVFrame *frame;
     uint8_t inbuf[INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
-    char buf[1024];
     AVPacket avpkt;
 
     av_init_packet(&avpkt);
@@ -501,6 +541,11 @@
     }
 
     c = avcodec_alloc_context3(codec);
+    if (!c) {
+        fprintf(stderr, "Could not allocate video codec context\n");
+        exit(1);
+    }
+
     if(codec->capabilities&CODEC_CAP_TRUNCATED)
         c->flags|= CODEC_FLAG_TRUNCATED; /* we do not send complete frames */
 
@@ -514,21 +559,19 @@
         exit(1);
     }
 
-    /* the codec gives us the frame size, in samples */
-
     f = fopen(filename, "rb");
     if (!f) {
         fprintf(stderr, "Could not open %s\n", filename);
         exit(1);
     }
 
-    picture = avcodec_alloc_frame();
-    if (!picture) {
+    frame = avcodec_alloc_frame();
+    if (!frame) {
         fprintf(stderr, "Could not allocate video frame\n");
         exit(1);
     }
 
-    frame = 0;
+    frame_count = 0;
     for(;;) {
         avpkt.size = fread(inbuf, 1, INBUF_SIZE, f);
         if (avpkt.size == 0)
@@ -550,26 +593,9 @@
         /* here, we use a stream based decoder (mpeg1video), so we
            feed decoder and see if it could decode a frame */
         avpkt.data = inbuf;
-        while (avpkt.size > 0) {
-            len = avcodec_decode_video2(c, picture, &got_picture, &avpkt);
-            if (len < 0) {
-                fprintf(stderr, "Error while decoding frame %d\n", frame);
+        while (avpkt.size > 0)
+            if (decode_write_frame(outfilename, c, frame, &frame_count, &avpkt, 0) < 0)
                 exit(1);
-            }
-            if (got_picture) {
-                printf("Saving frame %3d\n", frame);
-                fflush(stdout);
-
-                /* the picture is allocated by the decoder. no need to
-                   free it */
-                snprintf(buf, sizeof(buf), outfilename, frame);
-                pgm_save(picture->data[0], picture->linesize[0],
-                         c->width, c->height, buf);
-                frame++;
-            }
-            avpkt.size -= len;
-            avpkt.data += len;
-        }
     }
 
     /* some codecs, such as MPEG, transmit the I and P frame with a
@@ -577,24 +603,13 @@
        chance to get the last frame of the video */
     avpkt.data = NULL;
     avpkt.size = 0;
-    len = avcodec_decode_video2(c, picture, &got_picture, &avpkt);
-    if (got_picture) {
-        printf("Saving last frame %3d\n", frame);
-        fflush(stdout);
-
-        /* the picture is allocated by the decoder. no need to
-           free it */
-        snprintf(buf, sizeof(buf), outfilename, frame);
-        pgm_save(picture->data[0], picture->linesize[0],
-                 c->width, c->height, buf);
-        frame++;
-    }
+    decode_write_frame(outfilename, c, frame, &frame_count, &avpkt, 1);
 
     fclose(f);
 
     avcodec_close(c);
     av_free(c);
-    avcodec_free_frame(&picture);
+    avcodec_free_frame(&frame);
     printf("\n");
 }
 
@@ -610,8 +625,8 @@
                "API example program to decode/encode a media stream with libavcodec.\n"
                "This program generates a synthetic stream and encodes it to a file\n"
                "named test.h264, test.mp2 or test.mpg depending on output_type.\n"
-               "The encoded stream is then decoded and written to a raw data output\n."
-               "output_type must be choosen between 'h264', 'mp2', 'mpg'\n",
+               "The encoded stream is then decoded and written to a raw data output.\n"
+               "output_type must be choosen between 'h264', 'mp2', 'mpg'.\n",
                argv[0]);
         return 1;
     }
diff --git a/doc/examples/demuxing.c b/doc/examples/demuxing.c
index 0e0015e..3c9d4a1 100644
--- a/doc/examples/demuxing.c
+++ b/doc/examples/demuxing.c
@@ -26,6 +26,7 @@
  *
  * Show how to use the libavformat and libavcodec API to demux and
  * decode audio and video data.
+ * @example doc/examples/demuxing.c
  */
 
 #include <libavutil/imgutils.h>
@@ -208,7 +209,7 @@
     /* register all formats and codecs */
     av_register_all();
 
-    /* open input file, and allocated format context */
+    /* open input file, and allocate format context */
     if (avformat_open_input(&fmt_ctx, src_filename, NULL, NULL) < 0) {
         fprintf(stderr, "Could not open source file %s\n", src_filename);
         exit(1);
@@ -242,9 +243,6 @@
         video_dst_bufsize = ret;
     }
 
-    /* dump input information to stderr */
-    av_dump_format(fmt_ctx, 0, src_filename, 0);
-
     if (open_codec_context(&audio_stream_idx, fmt_ctx, AVMEDIA_TYPE_AUDIO) >= 0) {
         int nb_planes;
 
@@ -267,6 +265,9 @@
         }
     }
 
+    /* dump input information to stderr */
+    av_dump_format(fmt_ctx, 0, src_filename, 0);
+
     if (!audio_stream && !video_stream) {
         fprintf(stderr, "Could not find audio or video stream in the input, aborting\n");
         ret = 1;
@@ -288,7 +289,7 @@
     if (video_stream)
         printf("Demuxing video from file '%s' into '%s'\n", src_filename, video_dst_filename);
     if (audio_stream)
-        printf("Demuxing video from file '%s' into '%s'\n", src_filename, audio_dst_filename);
+        printf("Demuxing audio from file '%s' into '%s'\n", src_filename, audio_dst_filename);
 
     /* read frames from the file */
     while (av_read_frame(fmt_ctx, &pkt) >= 0)
diff --git a/doc/examples/filtering_audio.c b/doc/examples/filtering_audio.c
index 39f4450..b28e02b 100644
--- a/doc/examples/filtering_audio.c
+++ b/doc/examples/filtering_audio.c
@@ -25,6 +25,7 @@
 /**
  * @file
  * API example for audio decoding and filtering
+ * @example doc/examples/filtering_audio.c
  */
 
 #include <unistd.h>
diff --git a/doc/examples/filtering_video.c b/doc/examples/filtering_video.c
index ee5073a..90babb6 100644
--- a/doc/examples/filtering_video.c
+++ b/doc/examples/filtering_video.c
@@ -24,6 +24,7 @@
 /**
  * @file
  * API example for decoding and filtering
+ * @example doc/examples/filtering_video.c
  */
 
 #define _XOPEN_SOURCE 600 /* for usleep */
@@ -87,7 +88,7 @@
     AVFilter *buffersink = avfilter_get_by_name("ffbuffersink");
     AVFilterInOut *outputs = avfilter_inout_alloc();
     AVFilterInOut *inputs  = avfilter_inout_alloc();
-    enum PixelFormat pix_fmts[] = { PIX_FMT_GRAY8, PIX_FMT_NONE };
+    enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE };
     AVBufferSinkParams *buffersink_params;
 
     filter_graph = avfilter_graph_alloc();
diff --git a/doc/examples/metadata.c b/doc/examples/metadata.c
index 9f35912..9c1bcd7 100644
--- a/doc/examples/metadata.c
+++ b/doc/examples/metadata.c
@@ -23,6 +23,7 @@
 /**
  * @file
  * Shows how the metadata API can be used in application programs.
+ * @example doc/examples/metadata.c
  */
 
 #include <stdio.h>
diff --git a/doc/examples/muxing.c b/doc/examples/muxing.c
index f43a85e..f8b2f7c 100644
--- a/doc/examples/muxing.c
+++ b/doc/examples/muxing.c
@@ -26,6 +26,7 @@
  *
  * Output a media file in any supported libavformat format.
  * The default codecs are used.
+ * @example doc/examples/muxing.c
  */
 
 #include <stdlib.h>
@@ -41,7 +42,7 @@
 #define STREAM_DURATION   200.0
 #define STREAM_FRAME_RATE 25 /* 25 images/s */
 #define STREAM_NB_FRAMES  ((int)(STREAM_DURATION * STREAM_FRAME_RATE))
-#define STREAM_PIX_FMT    PIX_FMT_YUV420P /* default pix_fmt */
+#define STREAM_PIX_FMT    AV_PIX_FMT_YUV420P /* default pix_fmt */
 
 static int sws_flags = SWS_BICUBIC;
 
@@ -52,16 +53,14 @@
 static int16_t *samples;
 static int audio_input_frame_size;
 
-/*
- * add an audio output stream
- */
-static AVStream *add_audio_stream(AVFormatContext *oc, AVCodec **codec,
-                                  enum AVCodecID codec_id)
+/* Add an output stream. */
+static AVStream *add_stream(AVFormatContext *oc, AVCodec **codec,
+                            enum AVCodecID codec_id)
 {
     AVCodecContext *c;
     AVStream *st;
 
-    /* find the audio encoder */
+    /* find the encoder */
     *codec = avcodec_find_encoder(codec_id);
     if (!(*codec)) {
         fprintf(stderr, "Could not find codec\n");
@@ -73,23 +72,64 @@
         fprintf(stderr, "Could not allocate stream\n");
         exit(1);
     }
-    st->id = 1;
-
+    st->id = oc->nb_streams-1;
     c = st->codec;
 
-    /* put sample parameters */
-    c->sample_fmt  = AV_SAMPLE_FMT_S16;
-    c->bit_rate    = 64000;
-    c->sample_rate = 44100;
-    c->channels    = 2;
+    switch ((*codec)->type) {
+    case AVMEDIA_TYPE_AUDIO:
+        st->id = 1;
+        c->sample_fmt  = AV_SAMPLE_FMT_S16;
+        c->bit_rate    = 64000;
+        c->sample_rate = 44100;
+        c->channels    = 2;
+        break;
 
-    // some formats want stream headers to be separate
+    case AVMEDIA_TYPE_VIDEO:
+        avcodec_get_context_defaults3(c, *codec);
+        c->codec_id = codec_id;
+
+        c->bit_rate = 400000;
+        /* Resolution must be a multiple of two. */
+        c->width    = 352;
+        c->height   = 288;
+        /* timebase: This is the fundamental unit of time (in seconds) in terms
+         * of which frame timestamps are represented. For fixed-fps content,
+         * timebase should be 1/framerate and timestamp increments should be
+         * identical to 1. */
+        c->time_base.den = STREAM_FRAME_RATE;
+        c->time_base.num = 1;
+        c->gop_size      = 12; /* emit one intra frame every twelve frames at most */
+        c->pix_fmt       = STREAM_PIX_FMT;
+        if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
+            /* just for testing, we also add B frames */
+            c->max_b_frames = 2;
+        }
+        if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
+            /* Needed to avoid using macroblocks in which some coeffs overflow.
+             * This does not happen with normal video, it just happens here as
+             * the motion of the chroma plane does not match the luma plane. */
+            c->mb_decision = 2;
+        }
+    break;
+
+    default:
+        break;
+    }
+
+    /* Some formats want stream headers to be separate. */
     if (oc->oformat->flags & AVFMT_GLOBALHEADER)
         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
 
     return st;
 }
 
+/**************************************************************/
+/* audio output */
+
+static float t, tincr, tincr2;
+static int16_t *samples;
+static int audio_input_frame_size;
+
 static void open_audio(AVFormatContext *oc, AVCodec *codec, AVStream *st)
 {
     AVCodecContext *c;
@@ -98,7 +138,7 @@
 
     /* open it */
     if (avcodec_open2(c, codec, NULL) < 0) {
-        fprintf(stderr, "could not open codec\n");
+        fprintf(stderr, "Could not open audio codec\n");
         exit(1);
     }
 
@@ -115,6 +155,10 @@
     samples = av_malloc(audio_input_frame_size *
                         av_get_bytes_per_sample(c->sample_fmt) *
                         c->channels);
+    if (!samples) {
+        fprintf(stderr, "Could not allocate audio samples buffer\n");
+        exit(1);
+    }
 }
 
 /* Prepare a 16 bit dummy audio frame of 'frame_size' samples and
@@ -139,7 +183,7 @@
     AVCodecContext *c;
     AVPacket pkt = { 0 }; // data and size must be 0;
     AVFrame *frame = avcodec_alloc_frame();
-    int got_packet;
+    int got_packet, ret;
 
     av_init_packet(&pkt);
     c = st->codec;
@@ -152,7 +196,12 @@
                              av_get_bytes_per_sample(c->sample_fmt) *
                              c->channels, 1);
 
-    avcodec_encode_audio2(c, &pkt, frame, &got_packet);
+    ret = avcodec_encode_audio2(c, &pkt, frame, &got_packet);
+    if (ret < 0) {
+        fprintf(stderr, "Error encoding audio frame\n");
+        exit(1);
+    }
+
     if (!got_packet)
         return;
 
@@ -178,64 +227,7 @@
 
 static AVFrame *frame;
 static AVPicture src_picture, dst_picture;
-static uint8_t *video_outbuf;
-static int frame_count, video_outbuf_size;
-
-/* Add a video output stream. */
-static AVStream *add_video_stream(AVFormatContext *oc, AVCodec **codec,
-                                  enum AVCodecID codec_id)
-{
-    AVCodecContext *c;
-    AVStream *st;
-
-    /* find the video encoder */
-    *codec = avcodec_find_encoder(codec_id);
-    if (!(*codec)) {
-        fprintf(stderr, "codec not found\n");
-        exit(1);
-    }
-
-    st = avformat_new_stream(oc, *codec);
-    if (!st) {
-        fprintf(stderr, "Could not alloc stream\n");
-        exit(1);
-    }
-
-    c = st->codec;
-
-    avcodec_get_context_defaults3(c, *codec);
-
-    c->codec_id = codec_id;
-
-    /* Put sample parameters. */
-    c->bit_rate = 400000;
-    /* Resolution must be a multiple of two. */
-    c->width    = 352;
-    c->height   = 288;
-    /* timebase: This is the fundamental unit of time (in seconds) in terms
-     * of which frame timestamps are represented. For fixed-fps content,
-     * timebase should be 1/framerate and timestamp increments should be
-     * identical to 1. */
-    c->time_base.den = STREAM_FRAME_RATE;
-    c->time_base.num = 1;
-    c->gop_size      = 12; /* emit one intra frame every twelve frames at most */
-    c->pix_fmt       = STREAM_PIX_FMT;
-    if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
-        /* just for testing, we also add B frames */
-        c->max_b_frames = 2;
-    }
-    if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
-        /* Needed to avoid using macroblocks in which some coeffs overflow.
-         * This does not happen with normal video, it just happens here as
-         * the motion of the chroma plane does not match the luma plane. */
-        c->mb_decision = 2;
-    }
-    /* Some formats want stream headers to be separate. */
-    if (oc->oformat->flags & AVFMT_GLOBALHEADER)
-        c->flags |= CODEC_FLAG_GLOBAL_HEADER;
-
-    return st;
-}
+static int frame_count;
 
 static void open_video(AVFormatContext *oc, AVCodec *codec, AVStream *st)
 {
@@ -244,22 +236,10 @@
 
     /* open the codec */
     if (avcodec_open2(c, codec, NULL) < 0) {
-        fprintf(stderr, "Could not open codec\n");
+        fprintf(stderr, "Could not open video codec\n");
         exit(1);
     }
 
-    video_outbuf = NULL;
-    if (!(oc->oformat->flags & AVFMT_RAWPICTURE)) {
-        /* Allocate output buffer. */
-        /* XXX: API change will be done. */
-        /* Buffers passed into lav* 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). */
-        video_outbuf_size = 200000;
-        video_outbuf      = av_malloc(video_outbuf_size);
-    }
-
     /* allocate and init a re-usable frame */
     frame = avcodec_alloc_frame();
     if (!frame) {
@@ -277,8 +257,8 @@
     /* If the output format is not YUV420P, then a temporary YUV420P
      * picture is needed too. It is then converted to the required
      * output format. */
-    if (c->pix_fmt != PIX_FMT_YUV420P) {
-        ret = avpicture_alloc(&src_picture, PIX_FMT_YUV420P, c->width, c->height);
+    if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
+        ret = avpicture_alloc(&src_picture, AV_PIX_FMT_YUV420P, c->width, c->height);
         if (ret < 0) {
             fprintf(stderr, "Could not allocate temporary picture\n");
             exit(1);
@@ -322,11 +302,11 @@
          * frames if using B-frames, so we get the last frames by
          * passing the same picture again. */
     } else {
-        if (c->pix_fmt != PIX_FMT_YUV420P) {
+        if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
             /* as we only generate a YUV420P picture, we must convert it
              * to the codec pixel format if needed */
             if (!sws_ctx) {
-                sws_ctx = sws_getContext(c->width, c->height, PIX_FMT_YUV420P,
+                sws_ctx = sws_getContext(c->width, c->height, AV_PIX_FMT_YUV420P,
                                          c->width, c->height, c->pix_fmt,
                                          sws_flags, NULL, NULL, NULL);
                 if (!sws_ctx) {
@@ -345,8 +325,7 @@
     }
 
     if (oc->oformat->flags & AVFMT_RAWPICTURE) {
-        /* Raw video case - the API will change slightly in the near
-         * future for that. */
+        /* Raw video case - directly store the picture in the packet */
         AVPacket pkt;
         av_init_packet(&pkt);
 
@@ -373,9 +352,6 @@
 
         /* If size is zero, it means the image was buffered. */
         if (got_output) {
-            if (c->coded_frame->pts != AV_NOPTS_VALUE)
-                pkt.pts = av_rescale_q(c->coded_frame->pts,
-                                       c->time_base, st->time_base);
             if (c->coded_frame->key_frame)
                 pkt.flags |= AV_PKT_FLAG_KEY;
 
@@ -400,7 +376,6 @@
     av_free(src_picture.data[0]);
     av_free(dst_picture.data[0]);
     av_free(frame);
-    av_free(video_outbuf);
 }
 
 /**************************************************************/
@@ -422,8 +397,10 @@
     if (argc != 2) {
         printf("usage: %s output_file\n"
                "API example program to output a media file with libavformat.\n"
+               "This program generates a synthetic audio and video stream, encodes and\n"
+               "muxes them into a file named output_file.\n"
                "The output format is automatically guessed according to the file extension.\n"
-               "Raw images can also be output by using '%%d' in the filename\n"
+               "Raw images can also be output by using '%%d' in the filename.\n"
                "\n", argv[0]);
         return 1;
     }
@@ -445,11 +422,12 @@
      * and initialize the codecs. */
     video_st = NULL;
     audio_st = NULL;
+
     if (fmt->video_codec != AV_CODEC_ID_NONE) {
-        video_st = add_video_stream(oc, &video_codec, fmt->video_codec);
+        video_st = add_stream(oc, &video_codec, fmt->video_codec);
     }
     if (fmt->audio_codec != AV_CODEC_ID_NONE) {
-        audio_st = add_audio_stream(oc, &audio_codec, fmt->audio_codec);
+        audio_st = add_stream(oc, &audio_codec, fmt->audio_codec);
     }
 
     /* Now that all the parameters are set, we can open the audio and
@@ -475,7 +453,8 @@
         return 1;
     }
 
-    frame->pts = 0;
+    if (frame)
+        frame->pts = 0;
     for (;;) {
         /* Compute current audio and video time. */
         if (audio_st)
@@ -498,7 +477,7 @@
             write_audio_frame(oc, audio_st);
         } else {
             write_video_frame(oc, video_st);
-            frame->pts++;
+            frame->pts += av_rescale_q(1, video_st->codec->time_base, video_st->time_base);
         }
     }
 
diff --git a/doc/examples/scaling_video.c b/doc/examples/scaling_video.c
index 686af0c..320f4a0 100644
--- a/doc/examples/scaling_video.c
+++ b/doc/examples/scaling_video.c
@@ -23,6 +23,7 @@
 /**
  * @file
  * libswscale API use example.
+ * @example doc/examples/scaling_video.c
  */
 
 #include <libavutil/imgutils.h>
@@ -32,20 +33,18 @@
 static void fill_yuv_image(uint8_t *data[4], int linesize[4],
                            int width, int height, int frame_index)
 {
-    int x, y, i;
-
-    i = frame_index;
+    int x, y;
 
     /* Y */
     for (y = 0; y < height; y++)
         for (x = 0; x < width; x++)
-            data[0][y * linesize[0] + x] = x + y + i * 3;
+            data[0][y * linesize[0] + x] = x + y + frame_index * 3;
 
     /* Cb and Cr */
     for (y = 0; y < height / 2; y++) {
         for (x = 0; x < width / 2; x++) {
-            data[1][y * linesize[1] + x] = 128 + y + i * 2;
-            data[2][y * linesize[2] + x] = 64 + x + i * 5;
+            data[1][y * linesize[1] + x] = 128 + y + frame_index * 2;
+            data[2][y * linesize[2] + x] = 64 + x + frame_index * 5;
         }
     }
 }
@@ -55,7 +54,7 @@
     uint8_t *src_data[4], *dst_data[4];
     int src_linesize[4], dst_linesize[4];
     int src_w = 320, src_h = 240, dst_w, dst_h;
-    enum PixelFormat src_pix_fmt = PIX_FMT_YUV420P, dst_pix_fmt = PIX_FMT_RGB24;
+    enum AVPixelFormat src_pix_fmt = AV_PIX_FMT_YUV420P, dst_pix_fmt = AV_PIX_FMT_RGB24;
     const char *dst_size = NULL;
     const char *dst_filename = NULL;
     FILE *dst_file;
diff --git a/doc/faq.texi b/doc/faq.texi
index 30259dd..a7b34b1 100644
--- a/doc/faq.texi
+++ b/doc/faq.texi
@@ -79,6 +79,17 @@
 Then again, some of them do not know the difference between an undecidable
 problem and an NP-hard problem...
 
+@section I have installed this library with my distro's package manager. Why does @command{configure} not see it?
+
+Distributions usually split libraries in several packages. The main package
+contains the files necessary to run programs using the library. The
+development package contains the files necessary to build programs using the
+library. Sometimes, docs and/or data are in a separate package too.
+
+To build FFmpeg, you need to install the development package. It is usually
+called @file{libfoo-dev} or @file{libfoo-devel}. You can remove it after the
+build is finished, but be sure to keep the main package.
+
 @chapter Usage
 
 @section ffmpeg does not work; what is wrong?
@@ -297,7 +308,7 @@
 ffmpeg -i input1.avi -qscale:v 1 -y intermediate1.mpg < /dev/null &
 ffmpeg -i input2.avi -qscale:v 1 -y intermediate2.mpg < /dev/null &
 cat intermediate1.mpg intermediate2.mpg |\
-ffmpeg -f mpeg -i - -qscale:v 2 -c:v mpeg4 -acodec libmp3lame -q:a 4 output.avi
+ffmpeg -f mpeg -i - -c:v mpeg4 -acodec libmp3lame output.avi
 @end example
 
 @subsection Concatenating using raw audio and video
@@ -327,7 +338,7 @@
 cat temp1.v temp2.v > all.v &
 ffmpeg -f u16le -acodec pcm_s16le -ac 2 -ar 44100 -i all.a \
        -f yuv4mpegpipe -i all.v \
-       -qscale:v 2 -y output.flv
+       -y output.flv
 rm temp[12].[av] all.[av]
 @end example
 
@@ -385,6 +396,20 @@
 (default ~5 Mo) and @code{analyzeduration} (default 5,000,000 µs = 5 s). For
 the subtitle stream to be detected, both values must be large enough.
 
+@section Why was the @command{ffmpeg} @option{-sameq} option removed? What to use instead?
+
+The @option{-sameq} option meant "same quantizer", and made sense only in a
+very limited set of cases. Unfortunately, a lot of people mistook it for
+"same quality" and used it in places where it did not make sense: it had
+roughly the expected visible effect, but achieved it in a very inefficient
+way.
+
+Each encoder has its own set of options to set the quality-vs-size balance,
+use the options for the encoder you are using to set the quality level to a
+point acceptable for your tastes. The most common options to do that are
+@option{-qscale} and @option{-qmax}, but you should peruse the documentation
+of the encoder you chose.
+
 @chapter Development
 
 @section Are there examples illustrating how to use the FFmpeg libraries, particularly libavcodec and libavformat?
@@ -467,8 +492,8 @@
 
 @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 @file{libavformat/file.c} in
-FFmpeg and @file{libmpdemux/demux_lavf.c} in MPlayer sources.
+You have to create a custom AVIOContext using @code{avio_alloc_context},
+see @file{libavformat/aviobuf.c} in FFmpeg and @file{libmpdemux/demux_lavf.c} in MPlayer or MPlayer2 sources.
 
 @section Where can I find libav* headers for Pascal/Delphi?
 
diff --git a/doc/ffmpeg-bitstream-filters.texi b/doc/ffmpeg-bitstream-filters.texi
new file mode 100644
index 0000000..b1fdac2
--- /dev/null
+++ b/doc/ffmpeg-bitstream-filters.texi
@@ -0,0 +1,40 @@
+\input texinfo @c -*- texinfo -*-
+
+@settitle FFmpeg Bitstream Filters Documentation
+@titlepage
+@center @titlefont{FFmpeg Bitstream Filters Documentation}
+@end titlepage
+
+@top
+
+@contents
+
+@chapter Description
+@c man begin DESCRIPTION
+
+This document describes the bitstream filters provided by the
+libavcodec library.
+
+A bitstream filter operates on the encoded stream data, and performs
+bitstream level modifications without performing decoding.
+
+@c man end DESCRIPTION
+
+@include bitstream_filters.texi
+
+@ignore
+
+@setfilename ffmpeg-bitstream-filters
+@settitle FFmpeg bistream filters
+
+@c man begin SEEALSO
+ffmpeg(1), ffplay(1), ffprobe(1), ffserver(1), libavcodec(3)
+@c man end
+
+@c man begin AUTHORS
+See Git history (git://source.ffmpeg.org/ffmpeg)
+@c man end
+
+@end ignore
+
+@bye
diff --git a/doc/ffmpeg-codecs.texi b/doc/ffmpeg-codecs.texi
new file mode 100644
index 0000000..ba31a21
--- /dev/null
+++ b/doc/ffmpeg-codecs.texi
@@ -0,0 +1,1123 @@
+\input texinfo @c -*- texinfo -*-
+
+@settitle FFmpeg Codecs Documentation
+@titlepage
+@center @titlefont{FFmpeg Codecs Documentation}
+@end titlepage
+
+@top
+
+@contents
+
+@chapter Description
+@c man begin DESCRIPTION
+
+This document describes the codecs (decoders and encoders) provided by
+the libavcodec library.
+
+@c man end DESCRIPTION
+
+@chapter Codec Options
+@c man begin CODEC OPTIONS
+
+libavcodec provides some generic global options, which can be set on
+all the encoders and decoders. In addition each codec may support
+so-called private options, which are specific for a given codec.
+
+Sometimes, a global option may only affect a specific kind of codec,
+and may be unsensical or ignored by another, so you need to be aware
+of the meaning of the specified options. Also some options are
+meant only for decoding or encoding.
+
+Options may be set by specifying -@var{option} @var{value} in the
+FFmpeg tools, or by setting the value explicitly in the
+@code{AVCodecContext} options or using the @file{libavutil/opt.h} API
+for programmatic use.
+
+The list of supported options follow:
+
+@table @option
+@item b @var{integer} (@emph{encoding,audio,video})
+Set bitrate in bits/s. Default value is 200K.
+
+@item ab @var{integer} (@emph{encoding,audio})
+Set audio bitrate (in bits/s). Default value is 128K.
+
+@item bt @var{integer} (@emph{encoding,video})
+Set video bitrate tolerance (in bits/s). 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.
+
+@item flags @var{flags} (@emph{decoding/encoding,audio,video,subtitles})
+Set generic flags.
+
+Possible values:
+@table @samp
+@item mv4
+Use four motion vector by macroblock (mpeg4).
+@item qpel
+Use 1/4 pel motion compensation.
+@item loop
+Use loop filter.
+@item qscale
+Use fixed qscale.
+@item gmc
+Use gmc.
+@item mv0
+Always try a mb with mv=<0,0>.
+@item input_preserved
+
+@item pass1
+Use internal 2pass ratecontrol in first pass mode.
+@item pass2
+Use internal 2pass ratecontrol in second pass mode.
+@item gray
+Only decode/encode grayscale.
+@item emu_edge
+Do not draw edges.
+@item psnr
+Set error[?] variables during encoding.
+@item truncated
+
+@item naq
+Normalize adaptive quantization.
+@item ildct
+Use interlaced DCT.
+@item low_delay
+Force low delay.
+@item global_header
+Place global headers in extradata instead of every keyframe.
+@item bitexact
+Use only bitexact stuff (except (I)DCT).
+@item aic
+Apply H263 advanced intra coding / mpeg4 ac prediction.
+@item cbp
+Deprecated, use mpegvideo private options instead.
+@item qprd
+Deprecated, use mpegvideo private options instead.
+@item ilme
+Apply interlaced motion estimation.
+@item cgop
+Use closed gop.
+@end table
+
+@item sub_id @var{integer}
+Deprecated, currently unused.
+
+@item me_method @var{integer} (@emph{encoding,video})
+Set motion estimation method.
+
+Possible values:
+@table @samp
+@item zero
+zero motion estimation (fastest)
+@item full
+full motion estimation (slowest)
+@item epzs
+EPZS motion estimation (default)
+@item esa
+esa motion estimation (alias for full)
+@item tesa
+tesa motion estimation
+@item dia
+dia motion estimation (alias for epzs)
+@item log
+log motion estimation
+@item phods
+phods motion estimation
+@item x1
+X1 motion estimation
+@item hex
+hex motion estimation
+@item umh
+umh motion estimation
+@item iter
+iter motion estimation
+@end table
+
+@item extradata_size @var{integer}
+Set extradata size.
+
+@item time_base @var{rational number}
+Set codec time base.
+
+It is the fundamental unit of time (in seconds) in terms of which
+frame timestamps are represented. For fixed-fps content, timebase
+should be 1/framerate and timestamp increments should be identically
+1.
+
+@item g @var{integer} (@emph{encoding,video})
+Set the group of picture size. Default value is 12.
+
+@item ar @var{integer} (@emph{decoding/encoding,audio})
+Set audio sampling rate (in Hz).
+
+@item ac @var{integer} (@emph{decoding/encoding,audio})
+Set number of audio channels.
+
+@item cutoff @var{integer} (@emph{encoding,audio})
+Set cutoff bandwidth.
+
+@item frame_size @var{integer} (@emph{encoding,audio})
+Set audio frame size.
+
+Each submitted frame except the last must contain exactly frame_size
+samples per channel. May be 0 when the codec has
+CODEC_CAP_VARIABLE_FRAME_SIZE set, in that case the frame size is not
+restricted. It is set by some decoders to indicate constant frame
+size.
+
+@item frame_number @var{integer}
+Set the frame number.
+
+@item delay @var{integer}
+
+@item qcomp @var{float} (@emph{encoding,video})
+Set video quantizer scale compression (VBR). It is used as a constant
+in the ratecontrol equation. Recommended range for default rc_eq:
+0.0-1.0.
+
+@item qblur @var{float} (@emph{encoding,video})
+Set video quantizer scale blur (VBR).
+
+@item qmin @var{integer} (@emph{encoding,video})
+Set min video quantizer scale (VBR). Must be included between -1 and
+69, default value is 2.
+
+@item qmax @var{integer} (@emph{encoding,video})
+Set max video quantizer scale (VBR). Must be included between -1 and
+1024, default value is 31.
+
+@item qdiff @var{integer} (@emph{encoding,video})
+Set max difference between the quantizer scale (VBR).
+
+@item bf @var{integer} (@emph{encoding,video})
+Set max number of B frames.
+
+@item b_qfactor @var{float} (@emph{encoding,video})
+Set qp factor between P and B frames.
+
+@item rc_strategy @var{integer} (@emph{encoding,video})
+Set ratecontrol method.
+
+@item b_strategy @var{integer} (@emph{encoding,video})
+Set strategy to choose between I/P/B-frames.
+
+@item ps @var{integer} (@emph{encoding,video})
+Set RTP payload size in bytes.
+
+@item mv_bits @var{integer}
+@item header_bits @var{integer}
+@item i_tex_bits @var{integer}
+@item p_tex_bits @var{integer}
+@item i_count @var{integer}
+@item p_count @var{integer}
+@item skip_count @var{integer}
+@item misc_bits @var{integer}
+@item frame_bits @var{integer}
+@item codec_tag @var{integer}
+@item bug @var{flags} (@emph{decoding,video})
+Workaround not auto detected encoder bugs.
+
+Possible values:
+@table @samp
+@item autodetect
+
+@item old_msmpeg4
+some old lavc generated msmpeg4v3 files (no autodetection)
+@item xvid_ilace
+Xvid interlacing bug (autodetected if fourcc==XVIX)
+@item ump4
+(autodetected if fourcc==UMP4)
+@item no_padding
+padding bug (autodetected)
+@item amv
+
+@item ac_vlc
+illegal vlc bug (autodetected per fourcc)
+@item qpel_chroma
+
+@item std_qpel
+old standard qpel (autodetected per fourcc/version)
+@item qpel_chroma2
+
+@item direct_blocksize
+direct-qpel-blocksize bug (autodetected per fourcc/version)
+@item edge
+edge padding bug (autodetected per fourcc/version)
+@item hpel_chroma
+
+@item dc_clip
+
+@item ms
+Workaround various bugs in microsoft broken decoders.
+@item trunc
+trancated frames
+@end table
+
+@item lelim @var{integer} (@emph{encoding,video})
+Set single coefficient elimination threshold for luminance (negative
+values also consider DC coefficient).
+
+@item celim @var{integer} (@emph{encoding,video})
+Set single coefficient elimination threshold for chrominance (negative
+values also consider dc coefficient)
+
+@item strict @var{integer} (@emph{decoding/encoding,audio,video})
+Specify how strictly to follow the standards.
+
+Possible values:
+@table @samp
+@item very
+strictly conform to a older more strict version of the spec or reference software
+@item strict
+strictly conform to all the things in the spec no matter what consequences
+@item normal
+
+@item unofficial
+allow unofficial extensions
+@item experimental
+allow non standardized experimental things
+@end table
+
+@item b_qoffset @var{float} (@emph{encoding,video})
+Set QP offset between P and B frames.
+
+@item err_detect @var{flags} (@emph{decoding,audio,video})
+Set error detection flags.
+
+Possible values:
+@table @samp
+@item crccheck
+verify embedded CRCs
+@item bitstream
+detect bitstream specification deviations
+@item buffer
+detect improper bitstream length
+@item explode
+abort decoding on minor error detection
+@item careful
+consider things that violate the spec and have not been seen in the wild as errors
+@item compliant
+consider all spec non compliancies as errors
+@item aggressive
+consider things that a sane encoder should not do as an error
+@end table
+
+@item has_b_frames @var{integer}
+
+@item block_align @var{integer}
+
+@item mpeg_quant @var{integer} (@emph{encoding,video})
+Use MPEG quantizers instead of H.263.
+
+@item qsquish @var{float} (@emph{encoding,video})
+How to keep quantizer between qmin and qmax (0 = clip, 1 = use
+differentiable function).
+
+@item rc_qmod_amp @var{float} (@emph{encoding,video})
+Set experimental quantizer modulation.
+
+@item rc_qmod_freq @var{integer} (@emph{encoding,video})
+Set experimental quantizer modulation.
+
+@item rc_override_count @var{integer}
+
+@item rc_eq @var{string} (@emph{encoding,video})
+Set rate control equation. When computing the expression, besides the
+standard functions defined in the section 'Expression Evaluation', the
+following functions are available: bits2qp(bits), qp2bits(qp). Also
+the following constants are available: iTex pTex tex mv fCode iCount
+mcVar var isI isP isB avgQP qComp avgIITex avgPITex avgPPTex avgBPTex
+avgTex.
+
+@item maxrate @var{integer} (@emph{encoding,audio,video})
+Set max bitrate tolerance (in bits/s). Requires bufsize to be set.
+
+@item minrate @var{integer} (@emph{encoding,audio,video})
+Set min bitrate tolerance (in bits/s). Most useful in setting up a CBR
+encode. It is of little use elsewise.
+
+@item bufsize @var{integer} (@emph{encoding,audio,video})
+Set ratecontrol buffer size (in bits).
+
+@item rc_buf_aggressivity @var{float} (@emph{encoding,video})
+Currently useless.
+
+@item i_qfactor @var{float} (@emph{encoding,video})
+Set QP factor between P and I frames.
+
+@item i_qoffset @var{float} (@emph{encoding,video})
+Set QP offset between P and I frames.
+
+@item rc_init_cplx @var{float} (@emph{encoding,video})
+Set initial complexity for 1-pass encoding.
+
+@item dct @var{integer} (@emph{encoding,video})
+Set DCT algorithm.
+
+Possible values:
+@table @samp
+@item auto
+autoselect a good one (default)
+@item fastint
+fast integer
+@item int
+accurate integer
+@item mmx
+
+@item altivec
+
+@item faan
+floating point AAN DCT
+@end table
+
+@item lumi_mask @var{float} (@emph{encoding,video})
+Compress bright areas stronger than medium ones.
+
+@item tcplx_mask @var{float} (@emph{encoding,video})
+Set temporal complexity masking.
+
+@item scplx_mask @var{float} (@emph{encoding,video})
+Set spatial complexity masking.
+
+@item p_mask @var{float} (@emph{encoding,video})
+Set inter masking.
+
+@item dark_mask @var{float} (@emph{encoding,video})
+Compress dark areas stronger than medium ones.
+
+@item idct @var{integer} (@emph{decoding/encoding,video})
+Select IDCT implementation.
+
+Possible values:
+@table @samp
+@item auto
+
+@item int
+
+@item simple
+
+@item simplemmx
+
+@item libmpeg2mmx
+
+@item mmi
+
+@item arm
+
+@item altivec
+
+@item sh4
+
+@item simplearm
+
+@item simplearmv5te
+
+@item simplearmv6
+
+@item simpleneon
+
+@item simplealpha
+
+@item h264
+
+@item vp3
+
+@item ipp
+
+@item xvidmmx
+
+@item faani
+floating point AAN IDCT
+@end table
+
+@item slice_count @var{integer}
+
+@item ec @var{flags} (@emph{decoding,video})
+Set error concealment strategy.
+
+Possible values:
+@table @samp
+@item guess_mvs
+iterative motion vector (MV) search (slow)
+@item deblock
+use strong deblock filter for damaged MBs
+@end table
+
+@item bits_per_coded_sample @var{integer}
+
+@item pred @var{integer} (@emph{encoding,video})
+Set prediction method.
+
+Possible values:
+@table @samp
+@item left
+
+@item plane
+
+@item median
+
+@end table
+
+@item aspect @var{rational number} (@emph{encoding,video})
+Set sample aspect ratio.
+
+@item debug @var{flags} (@emph{decoding/encoding,audio,video,subtitles})
+Print specific debug info.
+
+Possible values:
+@table @samp
+@item pict
+picture info
+@item rc
+rate control
+@item bitstream
+
+@item mb_type
+macroblock (MB) type
+@item qp
+per-block quantization parameter (QP)
+@item mv
+motion vector
+@item dct_coeff
+
+@item skip
+
+@item startcode
+
+@item pts
+
+@item er
+error recognition
+@item mmco
+memory management control operations (H.264)
+@item bugs
+
+@item vis_qp
+visualize quantization parameter (QP), lower QP are tinted greener
+@item vis_mb_type
+visualize block types
+@item buffers
+picture buffer allocations
+@item thread_ops
+threading operations
+@end table
+
+@item vismv @var{integer} (@emph{decoding,video})
+Visualize motion vectors (MVs).
+
+Possible values:
+@table @samp
+@item pf
+forward predicted MVs of P-frames
+@item bf
+forward predicted MVs of B-frames
+@item bb
+backward predicted MVs of B-frames
+@end table
+
+@item cmp @var{integer} (@emph{encoding,video})
+Set full pel me compare function.
+
+Possible values:
+@table @samp
+@item sad
+sum of absolute differences, fast (default)
+@item sse
+sum of squared errors
+@item satd
+sum of absolute Hadamard transformed differences
+@item dct
+sum of absolute DCT transformed differences
+@item psnr
+sum of squared quantization errors (avoid, low quality)
+@item bit
+number of bits needed for the block
+@item rd
+rate distortion optimal, slow
+@item zero
+0
+@item vsad
+sum of absolute vertical differences
+@item vsse
+sum of squared vertical differences
+@item nsse
+noise preserving sum of squared differences
+@item w53
+5/3 wavelet, only used in snow
+@item w97
+9/7 wavelet, only used in snow
+@item dctmax
+
+@item chroma
+
+@end table
+
+@item subcmp @var{integer} (@emph{encoding,video})
+Set sub pel me compare function.
+
+Possible values:
+@table @samp
+@item sad
+sum of absolute differences, fast (default)
+@item sse
+sum of squared errors
+@item satd
+sum of absolute Hadamard transformed differences
+@item dct
+sum of absolute DCT transformed differences
+@item psnr
+sum of squared quantization errors (avoid, low quality)
+@item bit
+number of bits needed for the block
+@item rd
+rate distortion optimal, slow
+@item zero
+0
+@item vsad
+sum of absolute vertical differences
+@item vsse
+sum of squared vertical differences
+@item nsse
+noise preserving sum of squared differences
+@item w53
+5/3 wavelet, only used in snow
+@item w97
+9/7 wavelet, only used in snow
+@item dctmax
+
+@item chroma
+
+@end table
+
+@item mbcmp @var{integer} (@emph{encoding,video})
+Set macroblock compare function.
+
+Possible values:
+@table @samp
+@item sad
+sum of absolute differences, fast (default)
+@item sse
+sum of squared errors
+@item satd
+sum of absolute Hadamard transformed differences
+@item dct
+sum of absolute DCT transformed differences
+@item psnr
+sum of squared quantization errors (avoid, low quality)
+@item bit
+number of bits needed for the block
+@item rd
+rate distortion optimal, slow
+@item zero
+0
+@item vsad
+sum of absolute vertical differences
+@item vsse
+sum of squared vertical differences
+@item nsse
+noise preserving sum of squared differences
+@item w53
+5/3 wavelet, only used in snow
+@item w97
+9/7 wavelet, only used in snow
+@item dctmax
+
+@item chroma
+
+@end table
+
+@item ildctcmp @var{integer} (@emph{encoding,video})
+Set interlaced dct compare function.
+
+Possible values:
+@table @samp
+@item sad
+sum of absolute differences, fast (default)
+@item sse
+sum of squared errors
+@item satd
+sum of absolute Hadamard transformed differences
+@item dct
+sum of absolute DCT transformed differences
+@item psnr
+sum of squared quantization errors (avoid, low quality)
+@item bit
+number of bits needed for the block
+@item rd
+rate distortion optimal, slow
+@item zero
+0
+@item vsad
+sum of absolute vertical differences
+@item vsse
+sum of squared vertical differences
+@item nsse
+noise preserving sum of squared differences
+@item w53
+5/3 wavelet, only used in snow
+@item w97
+9/7 wavelet, only used in snow
+@item dctmax
+
+@item chroma
+
+@end table
+
+@item dia_size @var{integer} (@emph{encoding,video})
+Set diamond type & size for motion estimation.
+
+@item last_pred @var{integer} (@emph{encoding,video})
+Set amount of motion predictors from the previous frame.
+
+@item preme @var{integer} (@emph{encoding,video})
+Set pre motion estimation.
+
+@item precmp @var{integer} (@emph{encoding,video})
+Set pre motion estimation compare function.
+
+Possible values:
+@table @samp
+@item sad
+sum of absolute differences, fast (default)
+@item sse
+sum of squared errors
+@item satd
+sum of absolute Hadamard transformed differences
+@item dct
+sum of absolute DCT transformed differences
+@item psnr
+sum of squared quantization errors (avoid, low quality)
+@item bit
+number of bits needed for the block
+@item rd
+rate distortion optimal, slow
+@item zero
+0
+@item vsad
+sum of absolute vertical differences
+@item vsse
+sum of squared vertical differences
+@item nsse
+noise preserving sum of squared differences
+@item w53
+5/3 wavelet, only used in snow
+@item w97
+9/7 wavelet, only used in snow
+@item dctmax
+
+@item chroma
+
+@end table
+
+@item pre_dia_size @var{integer} (@emph{encoding,video})
+Set diamond type & size for motion estimation pre-pass.
+
+@item subq @var{integer} (@emph{encoding,video})
+Set sub pel motion estimation quality.
+
+@item dtg_active_format @var{integer}
+
+@item me_range @var{integer} (@emph{encoding,video})
+Set limit motion vectors range (1023 for DivX player).
+
+@item ibias @var{integer} (@emph{encoding,video})
+Set intra quant bias.
+
+@item pbias @var{integer} (@emph{encoding,video})
+Set inter quant bias.
+
+@item color_table_id @var{integer}
+
+@item global_quality @var{integer} (@emph{encoding,audio,video})
+
+@item coder @var{integer} (@emph{encoding,video})
+
+Possible values:
+@table @samp
+@item vlc
+variable length coder / huffman coder
+@item ac
+arithmetic coder
+@item raw
+raw (no encoding)
+@item rle
+run-length coder
+@item deflate
+deflate-based coder
+@end table
+
+@item context @var{integer} (@emph{encoding,video})
+Set context model.
+
+@item slice_flags @var{integer}
+
+@item xvmc_acceleration @var{integer}
+
+@item mbd @var{integer} (@emph{encoding,video})
+Set macroblock decision algorithm (high quality mode).
+
+Possible values:
+@table @samp
+@item simple
+use mbcmp (default)
+@item bits
+use fewest bits
+@item rd
+use best rate distortion
+@end table
+
+@item stream_codec_tag @var{integer}
+
+@item sc_threshold @var{integer} (@emph{encoding,video})
+Set scene change threshold.
+
+@item lmin @var{integer} (@emph{encoding,video})
+Set min lagrange factor (VBR).
+
+@item lmax @var{integer} (@emph{encoding,video})
+Set max lagrange factor (VBR).
+
+@item nr @var{integer} (@emph{encoding,video})
+Set noise reduction.
+
+@item rc_init_occupancy @var{integer} (@emph{encoding,video})
+Set number of bits which should be loaded into the rc buffer before
+decoding starts.
+
+@item inter_threshold @var{integer} (@emph{encoding,video})
+
+@item flags2 @var{flags} (@emph{decoding/encoding,audio,video})
+
+Possible values:
+@table @samp
+@item fast
+allow non spec compliant speedup tricks
+@item sgop
+Deprecated, use mpegvideo private options instead
+@item noout
+skip bitstream encoding
+@item local_header
+place global headers at every keyframe instead of in extradata
+@item chunks
+Frame data might be split into multiple chunks
+@item showall
+Show all frames before the first keyframe
+@item skiprd
+Deprecated, use mpegvideo private options instead
+@end table
+
+@item error @var{integer} (@emph{encoding,video})
+
+@item qns @var{integer} (@emph{encoding,video})
+Deprecated, use mpegvideo private options instead.
+
+@item threads @var{integer} (@emph{decoding/encoding,video})
+
+Possible values:
+@table @samp
+@item auto
+detect a good number of threads
+@end table
+
+@item me_threshold @var{integer} (@emph{encoding,video})
+Set motion estimaton threshold.
+
+@item mb_threshold @var{integer} (@emph{encoding,video})
+Set macroblock threshold.
+
+@item dc @var{integer} (@emph{encoding,video})
+Set intra_dc_precision.
+
+@item nssew @var{integer} (@emph{encoding,video})
+Set nsse weight.
+
+@item skip_top @var{integer} (@emph{decoding,video})
+Set number of macroblock rows at the top which are skipped.
+
+@item skip_bottom @var{integer} (@emph{decoding,video})
+Set number of macroblock rows at the bottom which are skipped.
+
+@item profile @var{integer} (@emph{encoding,audio,video})
+
+Possible values:
+@table @samp
+@item unknown
+
+@item aac_main
+
+@item aac_low
+
+@item aac_ssr
+
+@item aac_ltp
+
+@item aac_he
+
+@item aac_he_v2
+
+@item aac_ld
+
+@item aac_eld
+
+@item dts
+
+@item dts_es
+
+@item dts_96_24
+
+@item dts_hd_hra
+
+@item dts_hd_ma
+
+@end table
+
+@item level @var{integer} (@emph{encoding,audio,video})
+
+Possible values:
+@table @samp
+@item unknown
+
+@end table
+
+@item lowres @var{integer} (@emph{decoding,audio,video})
+Decode at 1= 1/2, 2=1/4, 3=1/8 resolutions.
+
+@item skip_threshold @var{integer} (@emph{encoding,video})
+Set frame skip threshold.
+
+@item skip_factor @var{integer} (@emph{encoding,video})
+Set frame skip factor.
+
+@item skip_exp @var{integer} (@emph{encoding,video})
+Set frame skip exponent.
+
+@item skipcmp @var{integer} (@emph{encoding,video})
+Set frame skip compare function.
+
+Possible values:
+@table @samp
+@item sad
+sum of absolute differences, fast (default)
+@item sse
+sum of squared errors
+@item satd
+sum of absolute Hadamard transformed differences
+@item dct
+sum of absolute DCT transformed differences
+@item psnr
+sum of squared quantization errors (avoid, low quality)
+@item bit
+number of bits needed for the block
+@item rd
+rate distortion optimal, slow
+@item zero
+0
+@item vsad
+sum of absolute vertical differences
+@item vsse
+sum of squared vertical differences
+@item nsse
+noise preserving sum of squared differences
+@item w53
+5/3 wavelet, only used in snow
+@item w97
+9/7 wavelet, only used in snow
+@item dctmax
+
+@item chroma
+
+@end table
+
+@item border_mask @var{float} (@emph{encoding,video})
+Increase the quantizer for macroblocks close to borders.
+
+@item mblmin @var{integer} (@emph{encoding,video})
+Set min macroblock lagrange factor (VBR).
+
+@item mblmax @var{integer} (@emph{encoding,video})
+Set max macroblock lagrange factor (VBR).
+
+@item mepc @var{integer} (@emph{encoding,video})
+Set motion estimation bitrate penalty compensation (1.0 = 256).
+
+@item skip_loop_filter @var{integer} (@emph{decoding,video})
+
+Possible values:
+@table @samp
+@item none
+
+@item default
+
+@item noref
+
+@item bidir
+
+@item nokey
+
+@item all
+
+@end table
+
+@item skip_idct @var{integer} (@emph{decoding,video})
+
+Possible values:
+@table @samp
+@item none
+
+@item default
+
+@item noref
+
+@item bidir
+
+@item nokey
+
+@item all
+
+@end table
+
+@item skip_frame @var{integer} (@emph{decoding,video})
+
+Possible values:
+@table @samp
+@item none
+
+@item default
+
+@item noref
+
+@item bidir
+
+@item nokey
+
+@item all
+
+@end table
+
+@item bidir_refine @var{integer} (@emph{encoding,video})
+Refine the two motion vectors used in bidirectional macroblocks.
+
+@item brd_scale @var{integer} (@emph{encoding,video})
+Downscale frames for dynamic B-frame decision.
+
+@item keyint_min @var{integer} (@emph{encoding,video})
+Set minimum interval between IDR-frames.
+
+@item refs @var{integer} (@emph{encoding,video})
+Set reference frames to consider for motion compensation.
+
+@item chromaoffset @var{integer} (@emph{encoding,video})
+Set chroma qp offset from luma.
+
+@item trellis @var{integer} (@emph{encoding,audio,video})
+Set rate-distortion optimal quantization.
+
+@item sc_factor @var{integer} (@emph{encoding,video})
+Set value multiplied by qscale for each frame and added to
+scene_change_score.
+
+@item mv0_threshold @var{integer} (@emph{encoding,video})
+@item b_sensitivity @var{integer} (@emph{encoding,video})
+Adjust sensitivity of b_frame_strategy 1.
+
+@item compression_level @var{integer} (@emph{encoding,audio,video})
+@item min_prediction_order @var{integer} (@emph{encoding,audio})
+@item max_prediction_order @var{integer} (@emph{encoding,audio})
+@item timecode_frame_start @var{integer} (@emph{encoding,video})
+Set GOP timecode frame start number, in non drop frame format.
+
+@item request_channels @var{integer} (@emph{decoding,audio})
+Set desired number of audio channels.
+
+@item bits_per_raw_sample @var{integer}
+@item channel_layout @var{integer} (@emph{decoding/encoding,audio})
+
+Possible values:
+@table @samp
+@end table
+@item request_channel_layout @var{integer} (@emph{decoding,audio})
+
+Possible values:
+@table @samp
+@end table
+@item rc_max_vbv_use @var{float} (@emph{encoding,video})
+@item rc_min_vbv_use @var{float} (@emph{encoding,video})
+@item ticks_per_frame @var{integer} (@emph{decoding/encoding,audio,video})
+@item color_primaries @var{integer} (@emph{decoding/encoding,video})
+@item color_trc @var{integer} (@emph{decoding/encoding,video})
+@item colorspace @var{integer} (@emph{decoding/encoding,video})
+@item color_range @var{integer} (@emph{decoding/encoding,video})
+@item chroma_sample_location @var{integer} (@emph{decoding/encoding,video})
+
+@item log_level_offset @var{integer}
+Set the log level offset.
+
+@item slices @var{integer} (@emph{encoding,video})
+Number of slices, used in parallelized encoding.
+
+@item thread_type @var{flags} (@emph{decoding/encoding,video})
+Select multithreading type.
+
+Possible values:
+@table @samp
+@item slice
+
+@item frame
+
+@end table
+@item audio_service_type @var{integer} (@emph{encoding,audio})
+Set audio service type.
+
+Possible values:
+@table @samp
+@item ma
+Main Audio Service
+@item ef
+Effects
+@item vi
+Visually Impaired
+@item hi
+Hearing Impaired
+@item di
+Dialogue
+@item co
+Commentary
+@item em
+Emergency
+@item vo
+Voice Over
+@item ka
+Karaoke
+@end table
+
+@item request_sample_fmt @var{sample_fmt} (@emph{decoding,audio})
+Set sample format audio decoders should prefer. Default value is
+@code{none}.
+
+@item pkt_timebase @var{rational number}
+@end table
+
+@c man end CODEC OPTIONS
+
+@include decoders.texi
+@include encoders.texi
+
+@ignore
+
+@setfilename ffmpeg-codecs
+@settitle FFmpeg codecs
+
+@c man begin SEEALSO
+ffmpeg(1), ffplay(1), ffprobe(1), ffserver(1), libavcodec(3)
+@c man end
+
+@c man begin AUTHORS
+See Git history (git://source.ffmpeg.org/ffmpeg)
+@c man end
+
+@end ignore
+
+@bye
diff --git a/doc/ffmpeg-devices.texi b/doc/ffmpeg-devices.texi
new file mode 100644
index 0000000..542dae8
--- /dev/null
+++ b/doc/ffmpeg-devices.texi
@@ -0,0 +1,57 @@
+\input texinfo @c -*- texinfo -*-
+
+@settitle FFmpeg Devices Documentation
+@titlepage
+@center @titlefont{FFmpeg Devices Documentation}
+@end titlepage
+
+@top
+
+@contents
+
+@chapter Description
+@c man begin DESCRIPTION
+
+This document describes the input and output devices provided by the
+libavdevice library.
+
+@c man end DESCRIPTION
+
+@chapter Device Options
+@c man begin DEVICE OPTIONS
+
+The libavdevice library provides the same interface as
+libavformat. Namely, an input device is considered like a demuxer, and
+an output device like a muxer, and the interface and generic device
+options are the same provided by libavformat (see the @ref{FFmpeg
+formats} manual page).
+
+In addition each input or output device may support so-called private
+options, which are specific for that component.
+
+Options may be set by specifying -@var{option} @var{value} in the
+FFmpeg tools, or by setting the value explicitly in the device
+@code{AVFormatContext} options or using the @file{libavutil/opt.h} API
+for programmatic use.
+
+@c man end DEVICE OPTIONS
+
+@include indevs.texi
+@include outdevs.texi
+
+@ignore
+
+@setfilename ffmpeg-devices
+@settitle FFmpeg devices
+
+@c man begin SEEALSO
+ffmpeg(1), ffplay(1), ffprobe(1), ffserver(1), libavformat(3), libavdevice(3)
+@c man end
+
+@c man begin AUTHORS
+See Git history (git://source.ffmpeg.org/ffmpeg)
+@c man end
+
+@end ignore
+
+@bye
diff --git a/doc/ffmpeg-filters.texi b/doc/ffmpeg-filters.texi
new file mode 100644
index 0000000..f272bb4
--- /dev/null
+++ b/doc/ffmpeg-filters.texi
@@ -0,0 +1,37 @@
+\input texinfo @c -*- texinfo -*-
+
+@settitle FFmpeg Filters Documentation
+@titlepage
+@center @titlefont{FFmpeg Filters Documentation}
+@end titlepage
+
+@top
+
+@contents
+
+@chapter Description
+@c man begin DESCRIPTION
+
+This document describes filters, sources, and sinks provided by the
+libavfilter library.
+
+@c man end DESCRIPTION
+
+@include filters.texi
+
+@ignore
+
+@setfilename ffmpeg-filters
+@settitle FFmpeg filters
+
+@c man begin SEEALSO
+ffmpeg(1), ffplay(1), ffprobe(1), ffserver(1), libavfilter(3)
+@c man end
+
+@c man begin AUTHORS
+See Git history (git://source.ffmpeg.org/ffmpeg)
+@c man end
+
+@end ignore
+
+@bye
diff --git a/doc/ffmpeg-formats.texi b/doc/ffmpeg-formats.texi
new file mode 100644
index 0000000..d7f0192
--- /dev/null
+++ b/doc/ffmpeg-formats.texi
@@ -0,0 +1,161 @@
+\input texinfo @c -*- texinfo -*-
+
+@settitle FFmpeg Formats Documentation
+@titlepage
+@center @titlefont{FFmpeg Formats Documentation}
+@end titlepage
+
+@top
+
+@contents
+
+@chapter Description
+@c man begin DESCRIPTION
+
+This document describes the supported formats (muxers and demuxers)
+provided by the libavformat library.
+
+@c man end DESCRIPTION
+
+@chapter Format Options
+@c man begin FORMAT OPTIONS
+
+The libavformat library provides some generic global options, which
+can be set on all the muxers and demuxers. In addition each muxer or
+demuxer may support so-called private options, which are specific for
+that component.
+
+Options may be set by specifying -@var{option} @var{value} in the
+FFmpeg tools, or by setting the value explicitly in the
+@code{AVFormatContext} options or using the @file{libavutil/opt.h} API
+for programmatic use.
+
+The list of supported options follows:
+
+@table @option
+@item avioflags @var{flags} (@emph{input/output})
+Possible values:
+@table @samp
+@item direct
+Reduce buffering.
+@end table
+
+@item probesize @var{integer} (@emph{input})
+Set probing size.
+
+@item packetsize @var{integer} (@emph{output})
+Set packet size.
+
+@item fflags @var{flags} (@emph{input/output})
+Set format flags.
+
+Possible values:
+@table @samp
+@item ignidx
+Ignore index.
+@item genpts
+Generate PTS.
+@item nofillin
+Do not fill in missing values that can be exactly calculated.
+@item noparse
+Disable AVParsers, this needs @code{+nofillin} too.
+@item igndts
+Ignore DTS.
+@item discardcorrupt
+Discard corrupted frames.
+@item sortdts
+Try to interleave output packets by DTS.
+@item keepside
+Do not merge side data.
+@item latm
+Enable RTP MP4A-LATM payload.
+@item nobuffer
+Reduce the latency introduced by optional buffering
+@end table
+
+@item analyzeduration @var{integer} (@emph{input})
+Specify how many microseconds are analyzed to estimate duration.
+
+@item cryptokey @var{hexadecimal string} (@emph{input})
+Set decryption key.
+
+@item indexmem @var{integer} (@emph{input})
+Set max memory used for timestamp index (per stream).
+
+@item rtbufsize @var{integer} (@emph{input})
+Set max memory used for buffering real-time frames.
+
+@item fdebug @var{flags} (@emph{input/output})
+Print specific debug info.
+
+Possible values:
+@table @samp
+@item ts
+@end table
+
+@item max_delay @var{integer} (@emph{input/output})
+Set maximum muxing or demuxing delay in microseconds.
+
+@item fpsprobesize @var{integer} (@emph{input})
+Set number of frames used to probe fps.
+
+@item audio_preload @var{integer} (@emph{output})
+Set microseconds by which audio packets should be interleaved earlier.
+
+@item chunk_duration @var{integer} (@emph{output})
+Set microseconds for each chunk.
+
+@item chunk_size @var{integer} (@emph{output})
+Set size in bytes for each chunk.
+
+@item err_detect, f_err_detect @var{flags} (@emph{input})
+Set error detection flags. @code{f_err_detect} is deprecated and
+should be used only via the @command{ffmpeg} tool.
+
+Possible values:
+@table @samp
+@item crccheck
+Verify embedded CRCs.
+@item bitstream
+Detect bitstream specification deviations.
+@item buffer
+Detect improper bitstream length.
+@item explode
+Abort decoding on minor error detection.
+@item careful
+Consider things that violate the spec and have not been seen in the
+wild as errors.
+@item compliant
+Consider all spec non compliancies as errors.
+@item aggressive
+Consider things that a sane encoder should not do as an error.
+@end table
+
+@item use_wallclock_as_timestamps @var{integer} (@emph{input})
+Use wallclock as timestamps.
+
+@item avoid_negative_ts @var{integer} (@emph{output})
+Avoid negative timestamps.
+@end table
+
+@c man end FORMAT OPTIONS
+
+@include demuxers.texi
+@include muxers.texi
+
+@ignore
+
+@setfilename ffmpeg-formats
+@settitle FFmpeg formats
+
+@c man begin SEEALSO
+ffmpeg(1), ffplay(1), ffprobe(1), ffserver(1), libavformat(3)
+@c man end
+
+@c man begin AUTHORS
+See Git history (git://source.ffmpeg.org/ffmpeg)
+@c man end
+
+@end ignore
+
+@bye
diff --git a/doc/ffmpeg-protocols.texi b/doc/ffmpeg-protocols.texi
new file mode 100644
index 0000000..0bb89a0
--- /dev/null
+++ b/doc/ffmpeg-protocols.texi
@@ -0,0 +1,37 @@
+\input texinfo @c -*- texinfo -*-
+
+@settitle FFmpeg Protocols Documentation
+@titlepage
+@center @titlefont{FFmpeg Protocols Documentation}
+@end titlepage
+
+@top
+
+@contents
+
+@chapter Description
+@c man begin DESCRIPTION
+
+This document describes the input and output protocols provided by the
+libavformat library.
+
+@c man end DESCRIPTION
+
+@include protocols.texi
+
+@ignore
+
+@setfilename ffmpeg-protocols
+@settitle FFmpeg protocols
+
+@c man begin SEEALSO
+ffmpeg(1), ffplay(1), ffprobe(1), ffserver(1), libavformat(3)
+@c man end
+
+@c man begin AUTHORS
+See Git history (git://source.ffmpeg.org/ffmpeg)
+@c man end
+
+@end ignore
+
+@bye
diff --git a/doc/ffmpeg-resampler.texi b/doc/ffmpeg-resampler.texi
new file mode 100644
index 0000000..3558772
--- /dev/null
+++ b/doc/ffmpeg-resampler.texi
@@ -0,0 +1,192 @@
+\input texinfo @c -*- texinfo -*-
+
+@settitle FFmpeg Resampler Documentation
+@titlepage
+@center @titlefont{FFmpeg Resampler Documentation}
+@end titlepage
+
+@top
+
+@contents
+
+@chapter Description
+@c man begin DESCRIPTION
+
+The FFmpeg resampler provides an high-level interface to the
+libswresample library audio resampling utilities. In particular it
+allows to perform audio resampling, audio channel layout rematrixing,
+and convert audio format and packing layout.
+
+@c man end DESCRIPTION
+
+@chapter Resampler Options
+@c man begin RESAMPLER OPTIONS
+
+The audio resampler supports the following named options.
+
+Options may be set by specifying -@var{option} @var{value} in the
+FFmpeg tools, or by setting the value explicitly in the
+@code{SwrContext} options or using the @file{libavutil/opt.h} API for
+programmatic use.
+
+@table @option
+
+@item ich, in_channel_count
+Set the number of input channels. Default value is 0. Setting this
+value is not mandatory if the corresponding channel layout
+@option{in_channel_layout} is set.
+
+@item och, out_channel_count
+Set the number of output channels. Default value is 0. Setting this
+value is not mandatory if the corresponding channel layout
+@option{out_channel_layout} is set.
+
+@item uch, used_channel_count
+Set the number of used channels. Default value is 0. This option is
+only used for special remapping.
+
+@item isr, in_sample_rate
+Set the input sample rate. Default value is 0.
+
+@item osr, out_sample_rate
+Set the output sample rate. Default value is 0.
+
+@item isf, in_sample_fmt
+Specify the input sample format. It is set by default to @code{none}.
+
+@item osf, out_sample_fmt
+Specify the output sample format. It is set by default to @code{none}.
+
+@item tsf, internal_sample_fmt
+Set the internal sample format. Default value is @code{none}.
+
+@item icl, in_channel_layout
+Set the input channel layout.
+
+@item ocl, out_channel_layout
+Set the output channel layout.
+
+@item clev, center_mix_level
+Set center mix level. It is a value expressed in deciBel, and must be
+inclusively included between -32 and +32.
+
+@item slev, surround_mix_level
+Set surround mix level. It is a value expressed in deciBel, and must
+be inclusively included between -32 and +32.
+
+@item lfe_mix_evel
+Set LFE mix level.
+
+@item rmvol, rematrix_volume
+Set rematrix volume. Default value is 1.0.
+
+@item flags, swr_flags
+Set flags used by the converter. Default value is 0.
+
+It supports the following individual flags:
+@table @option
+@item res
+force resampling
+@end table
+
+@item dither_scale
+Set the dither scale. Default value is 1.
+
+@item dither_method
+Set dither method. Default value is 0.
+
+Supported values:
+@table @samp
+@item rectangular
+select rectangular dither
+@item triangular
+select triangular dither
+@item triangular_hp
+select triangular dither with high pass
+@end table
+
+@item filter_size
+Set resampling filter size, default value is 16.
+
+@item phase_shift
+Set resampling phase shift, default value is 10, must be included
+between 0 and 30.
+
+@item linear_interp
+Use Linear Interpolation if set to 1, default value is 0.
+
+@item cutoff
+Set cutoff frequency ratio. Must be a float value between 0 and 1,
+default value is 0.8.
+
+@item min_comp
+Set minimum difference between timestamps and audio data (in seconds)
+below which no timestamp compensation of either kind is applied.
+Default value is @code{FLT_MAX}.
+
+@item min_hard_comp
+Set minimum difference between timestamps and audio data (in seconds)
+to trigger padding/trimming the data. Must be a non-negative double,
+default value is 0.1.
+
+@item comp_duration
+Set duration (in seconds) over which data is stretched/squeezed to
+make it match the timestamps. Must be a non-negative double float
+value, default value is 1.0.
+
+@item max_soft_comp
+Set maximum factor by which data is stretched/squeezed to make it
+match the timestamps. Must be a non-negative double float value,
+default value is 0.
+
+@item matrix_encoding
+Select matrixed stereo encoding.
+
+It accepts the following values:
+@table @samp
+@item none
+select none
+@item dolby
+select Dolby
+@item dplii
+select Dolby Pro Logic II
+@end table
+
+Default value is @code{none}.
+
+@item filter_type
+Select resampling filter type. This only affects resampling
+operations.
+
+It accepts the following values:
+@table @samp
+@item cubic
+select cubic
+@item blackman_nuttall
+select Blackman Nuttall Windowed Sinc
+@item kaiser
+select Kaiser Windowed Sinc
+@end table
+
+@item kaiser_beta
+Set Kaiser Window Beta value. Must be an integer included between 2
+and 16, default value is 9.
+
+@end table
+
+@c man end RESAMPLER OPTIONS
+
+@ignore
+
+@setfilename ffmpeg-resampler
+@settitle FFmpeg Resampler
+
+@c man begin SEEALSO
+ffmpeg(1), ffplay(1), ffprobe(1), ffserver(1), libswresample(3)
+@c man end
+
+@c man begin AUTHORS
+See Git history (git://source.ffmpeg.org/ffmpeg)
+@c man end
+
+@end ignore
diff --git a/doc/ffmpeg-scaler.texi b/doc/ffmpeg-scaler.texi
new file mode 100644
index 0000000..2d1bc95
--- /dev/null
+++ b/doc/ffmpeg-scaler.texi
@@ -0,0 +1,136 @@
+\input texinfo @c -*- texinfo -*-
+
+@settitle FFmpeg Scaler Documentation
+@titlepage
+@center @titlefont{FFmpeg Scaler Documentation}
+@end titlepage
+
+@top
+
+@contents
+
+@chapter Description
+@c man begin DESCRIPTION
+
+The FFmpeg rescaler provides an high-level interface to the libswscale
+library image conversion utilities. In particular it allows to perform
+image rescaling and pixel format conversion.
+
+@c man end DESCRIPTION
+
+@chapter Scaler Options
+@c man begin SCALER OPTIONS
+
+The video scaler supports the following named options.
+
+Options may be set by specifying -@var{option} @var{value} in the
+FFmpeg tools. For programmatic use, they can be set explicitly in the
+@code{SwsContext} options or through the @file{libavutil/opt.h} API.
+
+@table @option
+
+@item sws_flags
+Set the scaler flags. This is also used to set the scaling
+algorithm. Only a single algorithm should be selected.
+
+It accepts the following values:
+@table @samp
+@item fast_bilinear
+Select fast bilinear scaling algorithm.
+
+@item bilinear
+Select bilinear scaling algorithm.
+
+@item bicubic
+Select bicubic scaling algorithm.
+
+@item experimental
+Select experimental scaling algorithm.
+
+@item neighbor
+Select nearest neighbor rescaling algorithm.
+
+@item area
+Select averaging area rescaling algorithm.
+
+@item bicubiclin
+Select bicubic scaling algorithm for the luma component, bilinear for
+chroma components.
+
+@item gauss
+Select Gaussian rescaling algorithm.
+
+@item sinc
+Select sinc rescaling algorithm.
+
+@item lanczos
+Select lanczos rescaling algorithm.
+
+@item spline
+Select natural bicubic spline rescaling algorithm.
+
+@item print_info
+Enable printing/debug logging.
+
+@item accurate_rnd
+Enable accurate rounding.
+
+@item full_chroma_int
+Enable full chroma interpolation.
+
+@item full_chroma_inp
+Select full chroma input.
+
+@item bitexact
+Enable bitexact output.
+@end table
+
+@item srcw
+Set source width.
+
+@item srch
+Set source height.
+
+@item dstw
+Set destination width.
+
+@item dsth
+Set destination height.
+
+@item src_format
+Set source pixel format (must be expressed as an integer).
+
+@item dst_format
+Set destination pixel format (must be expressed as an integer).
+
+@item src_range
+Select source range.
+
+@item dst_range
+Select destination range.
+
+@item param0, param1
+Set scaling algorithm parameters. The specified values are specific of
+some scaling algorithms and ignored by others. The specified values
+are floating point number values.
+
+@end table
+
+@c man end SCALER OPTIONS
+
+@ignore
+
+@setfilename ffmpeg-scaler
+@settitle FFmpeg video scaling and pixel format converter
+
+@c man begin SEEALSO
+ffmpeg(1), ffplay(1), ffprobe(1), ffserver(1), libswscale(3)
+@c man end
+
+@c man begin AUTHORS
+See Git history (git://source.ffmpeg.org/ffmpeg)
+@c man end
+
+@end ignore
+
+@bye
diff --git a/doc/ffmpeg-utils.texi b/doc/ffmpeg-utils.texi
new file mode 100644
index 0000000..5d51fc8
--- /dev/null
+++ b/doc/ffmpeg-utils.texi
@@ -0,0 +1,38 @@
+\input texinfo @c -*- texinfo -*-
+
+@settitle FFmpeg Utilities Documentation
+@titlepage
+@center @titlefont{FFmpeg Utilities Documentation}
+@end titlepage
+
+@top
+
+@contents
+
+@chapter Description
+@c man begin DESCRIPTION
+
+This document describes some generic features and utilities provided
+by the libavutil library.
+
+@c man end DESCRIPTION
+
+@include syntax.texi
+@include eval.texi
+
+@ignore
+
+@setfilename ffmpeg-utils
+@settitle FFmpeg utilities
+
+@c man begin SEEALSO
+ffmpeg(1), ffplay(1), ffprobe(1), ffserver(1), libavutil(3)
+@c man end
+
+@c man begin AUTHORS
+See Git history (git://source.ffmpeg.org/ffmpeg)
+@c man end
+
+@end ignore
+
+@bye
diff --git a/doc/ffmpeg.texi b/doc/ffmpeg.texi
index 121fbc1..d39ad22 100644
--- a/doc/ffmpeg.texi
+++ b/doc/ffmpeg.texi
@@ -58,7 +58,7 @@
 @item
 To set the video bitrate of the output file to 64kbit/s:
 @example
-ffmpeg -i input.avi -b:v 64k output.avi
+ffmpeg -i input.avi -b:v 64k -bufsize 64k output.avi
 @end example
 
 @item
@@ -470,11 +470,6 @@
 
 @item -vcodec @var{codec} (@emph{output})
 Set the video codec. This is an alias for @code{-codec:v}.
-@item -same_quant
-Use same quantizer as source (implies VBR).
-
-Note that this is NOT SAME QUALITY. Do not use this option unless you know you
-need it.
 
 @item -pass[:@var{stream_specifier}] @var{n} (@emph{output,per-stream})
 Select the pass number (1 or 2). It is used to do two-pass
@@ -801,39 +796,7 @@
 output file. If no chapter mapping is specified, then chapters are copied from
 the first input file with at least one chapter. Use a negative file index to
 disable any chapter copying.
-@item -debug @var{category}
-Print specific debug info.
-@var{category} is a number or a string containing one of the following values:
-@table @samp
-@item bitstream
-@item buffers
-picture buffer allocations
-@item bugs
-@item dct_coeff
-@item er
-error recognition
-@item mb_type
-macroblock (MB) type
-@item mmco
-memory management control operations (H.264)
-@item mv
-motion vector
-@item pict
-picture info
-@item pts
-@item qp
-per-block quantization parameter (QP)
-@item rc
-rate control
-@item skip
-@item startcode
-@item thread_ops
-threading operations
-@item vis_mb_type
-visualize block types
-@item vis_qp
-visualize quantization parameter (QP), lower QP are tinted greener
-@end table
+
 @item -benchmark (@emph{global})
 Show benchmarking information at the end of an encode.
 Shows CPU time used and maximum memory consumption.
diff --git a/doc/ffprobe.texi b/doc/ffprobe.texi
index 58ea383..08aef13 100644
--- a/doc/ffprobe.texi
+++ b/doc/ffprobe.texi
@@ -45,6 +45,10 @@
 and consists of one or more sections of a form defined by the selected
 writer, which is specified by the @option{print_format} option.
 
+Sections may contain other nested sections, and are identified by a
+name (which may be shared by other sections), and an unique
+name. See the output of @option{sections}.
+
 Metadata tags stored in the container or in the streams are recognized
 and printed in the corresponding "FORMAT" or "STREAM" section.
 
@@ -94,6 +98,25 @@
 For more details on the available output printing formats, see the
 Writers section below.
 
+@item -sections
+Print sections structure and section information, and exit. The output
+is not meant to be parsed by a machine.
+
+@item -select_streams @var{stream_specifier}
+Select only the streams specified by @var{stream_specifier}. This
+option affects only the options related to streams
+(e.g. @code{show_streams}, @code{show_packets}, etc.).
+
+For example to show only audio streams, you can use the command:
+@example
+ffprobe -show_streams -select_streams a INPUT
+@end example
+
+To show only video packets belonging to the video stream with index 1:
+@example
+ffprobe -show_packets -select_streams v:1 INPUT
+@end example
+
 @item -show_data
 Show payload data, as an hexadecimal and ASCII dump. Coupled with
 @option{-show_packets}, it will dump the packets' data. Coupled with
@@ -118,6 +141,59 @@
 container format information, rather than all. This option may be given more
 than once, then all specified entries will be shown.
 
+This option is deprecated, use @code{show_entries} instead.
+
+@item -show_entries @var{section_entries}
+Set list of entries to show.
+
+Entries are specified according to the following
+syntax. @var{section_entries} contains a list of section entries
+separated by @code{:}. Each section entry is composed by a section
+name (or unique name), optionally followed by a list of entries local
+to that section, separated by @code{,}.
+
+If section name is specified but is followed by no @code{=}, all
+entries are printed to output, together with all the contained
+sections. Otherwise only the entries specified in the local section
+entries list are printed. In particular, if @code{=} is specified but
+the list of local entries is empty, then no entries will be shown for
+that section.
+
+Note that the order of specification of the local section entries is
+not honored in the output, and the usual display order will be
+retained.
+
+The formal syntax is given by:
+@example
+@var{LOCAL_SECTION_ENTRIES} ::= @var{SECTION_ENTRY_NAME}[,@var{LOCAL_SECTION_ENTRIES}]
+@var{SECTION_ENTRY}         ::= @var{SECTION_NAME}[=[@var{LOCAL_SECTION_ENTRIES}]]
+@var{SECTION_ENTRIES}       ::= @var{SECTION_ENTRY}[:@var{SECTION_ENTRIES}]
+@end example
+
+For example, to show only the index and type of each stream, and the PTS
+time, duration time, and stream index of the packets, you can specify
+the argument:
+@example
+packet=pts_time,duration_time,stream_index : stream=index,codec_type
+@end example
+
+To show all the entries in the section "format", but only the codec
+type in the section "stream", specify the argument:
+@example
+format : stream=codec_type
+@end example
+
+To show all the tags in the stream and format sections:
+@example
+format_tags : format_tags
+@end example
+
+To show only the @code{title} tag (if available) in the stream
+sections:
+@example
+stream_tags=title
+@end example
+
 @item -show_packets
 Show information about each packet contained in the input multimedia
 stream.
@@ -186,8 +262,9 @@
 A writer defines the output format adopted by @command{ffprobe}, and will be
 used for printing all the parts of the output.
 
-A writer may accept one or more arguments, which specify the options to
-adopt.
+A writer may accept one or more arguments, which specify the options
+to adopt. The options are specified as a list of @var{key}=@var{value}
+pairs, separated by ":".
 
 A description of the currently available writers follows.
 
@@ -206,9 +283,6 @@
 Metadata tags are printed as a line in the corresponding FORMAT or
 STREAM section, and are prefixed by the string "TAG:".
 
-This writer accepts options as a list of @var{key}=@var{value} pairs,
-separated by ":".
-
 A description of the accepted options follows.
 
 @table @option
@@ -238,9 +312,6 @@
 section. A metadata tag key, if printed, is prefixed by the string
 "tag:".
 
-This writer accepts options as a list of @var{key}=@var{value} pairs,
-separated by ":".
-
 The description of the accepted options follows.
 
 @table @option
@@ -292,9 +363,6 @@
 directly embedded in sh scripts as long as the separator character is an
 alphanumeric character or an underscore (see @var{sep_char} option).
 
-This writer accepts options as a list of @var{key}=@var{value} pairs,
-separated by ":".
-
 The description of the accepted options follows.
 
 @table @option
@@ -357,9 +425,6 @@
 
 Each section is printed using JSON notation.
 
-This writer accepts options as a list of @var{key}=@var{value} pairs,
-separated by ":".
-
 The description of the accepted options follows.
 
 @table @option
@@ -386,9 +451,6 @@
 (@option{unit}, @option{prefix}, @option{byte_binary_prefix},
 @option{sexagesimal} etc.) are specified.
 
-This writer accepts options as a list of @var{key}=@var{value} pairs,
-separated by ":".
-
 The description of the accepted options follows.
 
 @table @option
diff --git a/doc/ffserver.conf b/doc/ffserver.conf
index d10ac5b..0f5922c 100644
--- a/doc/ffserver.conf
+++ b/doc/ffserver.conf
@@ -25,10 +25,6 @@
 # '-' is the standard output.
 CustomLog -
 
-# Suppress that if you want to launch ffserver as a daemon.
-NoDaemon
-
-
 ##################################################################
 # Definition of the live feeds. Each live feed contains one video
 # and/or audio sequence coming from an ffmpeg encoder or another
diff --git a/doc/ffserver.texi b/doc/ffserver.texi
index 074c075..dbfffd2 100644
--- a/doc/ffserver.texi
+++ b/doc/ffserver.texi
@@ -28,11 +28,6 @@
 (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.html} for more
@@ -238,6 +233,19 @@
 For example:   @samp{http://localhost:8080/test.asf?date=2002-07-26T23:05:00}.
 @c man end
 
+@section What is FFM, FFM2
+
+FFM and FFM2 are formats used by ffserver. They allow storing a wide varity of
+video and audio streams and encoding options, and can store a moving time segment
+of an infinite movie or a whole movie.
+
+FFM is version specific, and there is limited compatibility of FFM files
+generated by one version of ffmpeg/ffserver and another version of
+ffmpeg/ffserver. It may work but its not guaranteed to work.
+
+FFM2 is extensible while maintaining compatibility and should work between
+differing versions of tools. FFM2 is the default.
+
 @chapter Options
 @c man begin OPTIONS
 
@@ -254,8 +262,7 @@
 any ffmpeg instances, you will have to launch them manually.
 @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.
+messages to stdout.
 @end table
 @c man end
 
diff --git a/doc/filter_design.txt b/doc/filter_design.txt
index 11bcc72..362fce4 100644
--- a/doc/filter_design.txt
+++ b/doc/filter_design.txt
@@ -52,7 +52,7 @@
     point to only a part of a video buffer.
 
     A reference is usually obtained as input to the start_frame or
-    filter_samples method or requested using the ff_get_video_buffer or
+    filter_frame method or requested using the ff_get_video_buffer or
     ff_get_audio_buffer functions. A new reference on an existing buffer can
     be created with the avfilter_ref_buffer. A reference is destroyed using
     the avfilter_unref_bufferp function.
@@ -68,14 +68,14 @@
 
     Here are the (fairly obvious) rules for reference ownership:
 
-    * A reference received by the start_frame or filter_samples method
+    * A reference received by the start_frame or filter_frame method
       belong to the corresponding filter.
 
       Special exception: for video references: the reference may be used
       internally for automatic copying and must not be destroyed before
       end_frame; it can be given away to ff_start_frame.
 
-    * A reference passed to ff_start_frame or ff_filter_samples is given
+    * A reference passed to ff_start_frame or ff_filter_frame is given
       away and must no longer be used.
 
     * A reference created with avfilter_ref_buffer belongs to the code that
@@ -93,16 +93,16 @@
     The AVFilterLink structure has a few AVFilterBufferRef fields. Here are
     the rules to handle them:
 
-    * cur_buf is set before the start_frame and filter_samples methods to
+    * cur_buf is set before the start_frame and filter_frame methods to
       the same reference given as argument to the methods and belongs to the
       destination filter of the link. If it has not been cleared after
-      end_frame or filter_samples, libavfilter will automatically destroy
+      end_frame or filter_frame, libavfilter will automatically destroy
       the reference; therefore, any filter that needs to keep the reference
       for longer must set cur_buf to NULL.
 
     * out_buf belongs to the source filter of the link and can be used to
       store a reference to the buffer that has been sent to the destination.
-      If it is not NULL after end_frame or filter_samples, libavfilter will
+      If it is not NULL after end_frame or filter_frame, libavfilter will
       automatically destroy the reference.
 
       If a video input pad does not have a start_frame method, the default
@@ -179,7 +179,7 @@
       with the WRITE permission.
 
     * Filters that intend to keep a reference after the filtering process
-      is finished (after end_frame or filter_samples returns) must have the
+      is finished (after end_frame or filter_frame returns) must have the
       PRESERVE permission on it and remove the WRITE permission if they
       create a new reference to give it away.
 
@@ -198,7 +198,7 @@
   Simple filters that output one frame for each input frame should not have
   to worry about it.
 
-  start_frame / filter_samples
+  start_frame / filter_frame
   ----------------------------
 
     These methods are called when a frame is pushed to the filter's input.
@@ -233,7 +233,7 @@
 
     This method is called when a frame is wanted on an output.
 
-    For an input, it should directly call start_frame or filter_samples on
+    For an input, it should directly call start_frame or filter_frame on
     the corresponding output.
 
     For a filter, if there are queued frames already ready, one of these
@@ -266,4 +266,4 @@
 
     Note that, except for filters that can have queued frames, request_frame
     does not push frames: it requests them to its input, and as a reaction,
-    the start_frame / filter_samples method will be called and do the work.
+    the start_frame / filter_frame method will be called and do the work.
diff --git a/doc/filters.texi b/doc/filters.texi
index 916aa6f..e25f548 100644
--- a/doc/filters.texi
+++ b/doc/filters.texi
@@ -191,6 +191,59 @@
 @var{FILTERGRAPH}      ::= [sws_flags=@var{flags};] @var{FILTERCHAIN} [;@var{FILTERGRAPH}]
 @end example
 
+@section Notes on filtergraph escaping
+
+Some filter arguments require the use of special characters, typically
+@code{:} to separate key=value pairs in a named options list. In this
+case the user should perform a first level escaping when specifying
+the filter arguments. For example, consider the following literal
+string to be embedded in the @ref{drawtext} filter arguments:
+@example
+this is a 'string': may contain one, or more, special characters
+@end example
+
+Since @code{:} is special for the filter arguments syntax, it needs to
+be escaped, so you get:
+@example
+text=this is a \'string\'\: may contain one, or more, special characters
+@end example
+
+A second level of escaping is required when embedding the filter
+arguments in a filtergraph description, in order to escape all the
+filtergraph special characters. Thus the example above becomes:
+@example
+drawtext=text=this is a \\\'string\\\'\\: may contain one\, or more\, special characters
+@end example
+
+Finally an additional level of escaping may be needed when writing the
+filtergraph description in a shell command, which depends on the
+escaping rules of the adopted shell. For example, assuming that
+@code{\} is special and needs to be escaped with another @code{\}, the
+previous string will finally result in:
+@example
+-vf "drawtext=text=this is a \\\\\\'string\\\\\\'\\\\: may contain one\\, or more\\, special characters"
+@end example
+
+Sometimes, it might be more convenient to employ quoting in place of
+escaping. For example the string:
+@example
+Caesar: tu quoque, Brute, fili mi
+@end example
+
+Can be quoted in the filter arguments as:
+@example
+text='Caesar: tu quoque, Brute, fili mi'
+@end example
+
+And finally inserted in a filtergraph like:
+@example
+drawtext=text=\'Caesar: tu quoque\, Brute\, fili mi\'
+@end example
+
+See the @ref{quoting_and_escaping, Quoting and escaping} section for
+more information about the escaping and quoting rules adopted by
+FFmpeg.
+
 @c man end FILTERGRAPH DESCRIPTION
 
 @chapter Audio Filters
@@ -215,7 +268,7 @@
 suffix for a planar sample format.
 
 @var{channel_layout} specifies the channel layout, and can be a string
-or the corresponding number value defined in @file{libavutil/audioconvert.h}.
+or the corresponding number value defined in @file{libavutil/channel_layout.h}.
 
 The special parameter "auto", signifies that the filter will
 automatically select the output format depending on the output filter.
@@ -414,37 +467,34 @@
 sequential number of the input frame, starting from 0
 
 @item pts
-presentation TimeStamp of the input frame, expressed as a number of
-time base units. The time base unit depends on the filter input pad, and
-is usually 1/@var{sample_rate}.
+Presentation timestamp of the input frame, in time base units; the time base
+depends on the filter input pad, and is usually 1/@var{sample_rate}.
 
 @item pts_time
-presentation TimeStamp of the input frame, expressed as a number of
-seconds
+presentation timestamp of the input frame in seconds
 
 @item pos
 position of the frame in the input stream, -1 if this information in
 unavailable and/or meaningless (for example in case of synthetic audio)
 
 @item fmt
-sample format name
+sample format
 
 @item chlayout
-channel layout description
-
-@item nb_samples
-number of samples (per each channel) contained in the filtered frame
+channel layout
 
 @item rate
 sample rate for the audio frame
 
-@item checksum
-Adler-32 checksum (printed in hexadecimal) of all the planes of the input frame
+@item nb_samples
+number of samples (per channel) in the frame
 
-@item plane_checksum
-Adler-32 checksum (printed in hexadecimal) for each input frame plane,
-expressed in the form "[@var{c0} @var{c1} @var{c2} @var{c3} @var{c4} @var{c5}
-@var{c6} @var{c7}]"
+@item checksum
+Adler-32 checksum (printed in hexadecimal) of the audio data. For planar audio
+the data is treated as if all the planes were concatenated.
+
+@item plane_checksums
+A list of Adler-32 checksums for each data plane.
 @end table
 
 @section asplit
@@ -899,8 +949,8 @@
 @item channel_layout
 The channel layout of the incoming audio buffers.
 Either a channel layout name from channel_layout_map in
-@file{libavutil/audioconvert.c} or its corresponding integer representation
-from the AV_CH_LAYOUT_* macros in @file{libavutil/audioconvert.h}
+@file{libavutil/channel_layout.c} or its corresponding integer representation
+from the AV_CH_LAYOUT_* macros in @file{libavutil/channel_layout.h}
 
 @end table
 
@@ -1043,7 +1093,7 @@
 is "stereo".
 
 Check the channel_layout_map definition in
-@file{libavcodec/audioconvert.c} for the mapping between strings and
+@file{libavutil/channel_layout.c} for the mapping between strings and
 channel layout values.
 
 @item nb_samples, n
@@ -1138,10 +1188,16 @@
 @end example
 
 @item
-Make @file{ffplay} speech the specified text, using @code{flite} and
+Input text to ffmpeg:
+@example
+ffmpeg -f lavfi -i flite=text='So fare thee well, poor devil of a Sub-Sub, whose commentator I am':voice=slt
+@end example
+
+@item
+Make @file{ffplay} speak the specified text, using @code{flite} and
 the @code{lavfi} device:
 @example
-ffplay -f lavfi flite='No more be grieved for which that thou hast done.'
+ffplay -f lavfi flite=text='No more be grieved for which that thou hast done.'
 @end example
 @end itemize
 
@@ -1224,26 +1280,33 @@
 To enable compilation of this filter you need to configure FFmpeg with
 @code{--enable-libass}.
 
-This filter accepts the syntax: @var{ass_filename}[:@var{options}],
-where @var{ass_filename} is the filename of the ASS file to read, and
-@var{options} is an optional sequence of @var{key}=@var{value} pairs,
-separated by ":".
-
-A description of the accepted options follows.
+This filter accepts the following named options, expressed as a
+sequence of @var{key}=@var{value} pairs, separated by ":".
 
 @table @option
+@item filename, f
+Set the filename of the ASS file to read. It must be specified.
+
 @item original_size
-Specifies the size of the original video, the video for which the ASS file
+Specify the size of the original video, the video for which the ASS file
 was composed. Due to a misdesign in ASS aspect ratio arithmetic, this is
 necessary to correctly scale the fonts if the aspect ratio has been changed.
 @end table
 
+If the first key is not specified, it is assumed that the first value
+specifies the @option{filename}.
+
 For example, to render the file @file{sub.ass} on top of the input
 video, use the command:
 @example
 ass=sub.ass
 @end example
 
+which is equivalent to:
+@example
+ass=filename=sub.ass
+@end example
+
 @section bbox
 
 Compute the bounding box for the non-black pixels in the input frame
@@ -1716,34 +1779,63 @@
 
 Draw a colored box on the input image.
 
-It accepts the syntax:
-@example
-drawbox=@var{x}:@var{y}:@var{width}:@var{height}:@var{color}
-@end example
+The filter accepts parameters as a list of @var{key}=@var{value} pairs,
+separated by ":".
+
+The description of the accepted parameters follows.
 
 @table @option
-
 @item x, y
 Specify the top left corner coordinates of the box. Default to 0.
 
-@item width, height
+@item width, w
+@item height, h
 Specify the width and height of the box, if 0 they are interpreted as
 the input width and height. Default to 0.
 
-@item color
+@item color, c
 Specify the color of the box to write, it can be the name of a color
-(case insensitive match) or a 0xRRGGBB[AA] sequence.
+(case insensitive match) or a 0xRRGGBB[AA] sequence. If the special
+value @code{invert} is used, the box edge color is the same as the
+video with inverted luma.
+
+@item thickness, t
+Set the thickness of the box edge. Default value is @code{4}.
 @end table
 
-Follow some examples:
+If the key of the first options is omitted, the arguments are
+interpreted according to the following syntax:
 @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"
+drawbox=@var{x}:@var{y}:@var{width}:@var{height}:@var{color}:@var{thickness}
 @end example
 
+Some examples follow:
+@itemize
+@item
+Draw a black box around the edge of the input image:
+@example
+drawbox
+@end example
+
+@item
+Draw a box with color red and an opacity of 50%:
+@example
+drawbox=10:20:200:60:red@@0.5
+@end example
+
+The previous example can be specified as:
+@example
+drawbox=x=10:y=20:w=200:h=60:color=red@@0.5
+@end example
+
+@item
+Fill the box with pink color:
+@example
+drawbox=x=10:y=10:w=100:h=100:color=pink@@0.5:t=max
+@end example
+@end itemize
+
+@anchor{drawtext}
 @section drawtext
 
 Draw text string or text from specified file on top of video using the
@@ -1752,8 +1844,7 @@
 To enable compilation of this filter you need to configure FFmpeg with
 @code{--enable-libfreetype}.
 
-The filter also recognizes strftime() sequences in the provided text
-and expands them accordingly. Check the documentation of strftime().
+@subsection Syntax
 
 The filter accepts parameters as a list of @var{key}=@var{value} pairs,
 separated by ":".
@@ -1783,6 +1874,12 @@
 
 See below for the list of accepted constants and functions.
 
+@item expansion
+Select how the @var{text} is expanded. Can be either @code{none},
+@code{strftime} (default for compatibity reasons but deprecated) or
+@code{normal}. See the @ref{drawtext_expansion, Text expansion} section
+below for details.
+
 @item fix_bounds
 If true, check and fix text coords to avoid clipping.
 
@@ -1947,6 +2044,65 @@
 If libavfilter was built with @code{--enable-fontconfig}, then
 @option{fontfile} can be a fontconfig pattern or omitted.
 
+@anchor{drawtext_expansion}
+@subsection Text expansion
+
+If @option{expansion} is set to @code{strftime} (which is the default for
+now), the filter recognizes strftime() sequences in the provided text and
+expands them accordingly. Check the documentation of strftime(). This
+feature is deprecated.
+
+If @option{expansion} is set to @code{none}, the text is printed verbatim.
+
+If @option{expansion} is set to @code{normal} (which will be the default),
+the following expansion mechanism is used.
+
+The backslash character '\', followed by any character, always expands to
+the second character.
+
+Sequence of the form @code{%@{...@}} are expanded. The text between the
+braces is a function name, possibly followed by arguments separated by ':'.
+If the arguments contain special characters or delimiters (':' or '@}'),
+they should be escaped.
+
+Note that they probably must also be escaped as the value for the
+@option{text} option in the filter argument string and as the filter
+argument in the filter graph description, and possibly also for the shell,
+that makes up to four levels of escaping; using a text file avoids these
+problems.
+
+The following functions are available:
+
+@table @command
+
+@item expr, e
+The expression evaluation result.
+
+It must take one argument specifying the expression to be evaluated,
+which accepts the same constants and functions as the @var{x} and
+@var{y} values. Note that not all constants should be used, for
+example the text size is not known when evaluating the expression, so
+the constants @var{text_w} and @var{text_h} will have an undefined
+value.
+
+@item gmtime
+The time at which the filter is running, expressed in UTC.
+It can accept an argument: a strftime() format string.
+
+@item localtime
+The time at which the filter is running, expressed in the local time zone.
+It can accept an argument: a strftime() format string.
+
+@item n, frame_num
+The frame number, starting from 0.
+
+@item pts
+The timestamp of the current frame, in seconds, with microsecond accuracy.
+
+@end table
+
+@subsection Examples
+
 Some examples follow.
 
 @itemize
@@ -2003,13 +2159,19 @@
 @item
 Show text for 1 second every 3 seconds:
 @example
-drawtext="fontfile=FreeSerif.ttf:fontcolor=white:x=100:y=x/dar:draw=lt(mod(t\\,3)\\,1):text='blink'"
+drawtext="fontfile=FreeSerif.ttf:fontcolor=white:x=100:y=x/dar:draw=lt(mod(t\,3)\,1):text='blink'"
 @end example
 
 @item
 Use fontconfig to set the font. Note that the colons need to be escaped.
 @example
-drawtext='fontfile=Linux Libertine O-40\\:style=Semibold:text=FFmpeg'
+drawtext='fontfile=Linux Libertine O-40\:style=Semibold:text=FFmpeg'
+@end example
+
+@item
+Print the date of a real-time encoding (see strftime(3)):
+@example
+drawtext='fontfile=FreeSans.ttf:expansion=normal:text=%@{localtime:%a %b %d %Y@}'
 @end example
 
 @end itemize
@@ -2102,6 +2264,31 @@
 fade=in:0:25:alpha=1
 @end example
 
+@section field
+
+Extract a single field from an interlaced image using stride
+arithmetic to avoid wasting CPU time. The output frames are marked as
+non-interlaced.
+
+This filter accepts the following named options:
+@table @option
+@item type
+Specify whether to extract the top (if the value is @code{0} or
+@code{top}) or the bottom field (if the value is @code{1} or
+@code{bottom}).
+@end table
+
+If the option key is not specified, the first value sets the @var{type}
+option. For example:
+@example
+field=bottom
+@end example
+
+is equivalent to:
+@example
+field=type=bottom
+@end example
+
 @section fieldorder
 
 Transform the field order of the input video.
@@ -2173,6 +2360,9 @@
 @item fps
 Desired output framerate.
 
+@item round
+Rounding method. The default is @code{near}.
+
 @end table
 
 @section framestep
@@ -2195,12 +2385,13 @@
 @var{filter_name}[@{:|=@}@var{param1}:@var{param2}:...:@var{paramN}]
 @end example
 
-@var{filter_name} is the name to the frei0r effect to load. If the
+@var{filter_name} is the name of 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/},
-@file{/usr/local/lib/frei0r-1/}, @file{/usr/lib/frei0r-1/}.
+is searched in each one of the directories specified by the colon (or
+semicolon on Windows platforms) separated list in @env{FREIOR_PATH},
+otherwise in the standard frei0r paths, which are in this order:
+@file{HOME/.frei0r-1/lib/}, @file{/usr/local/lib/frei0r-1/},
+@file{/usr/lib/frei0r-1/}.
 
 @var{param1}, @var{param2}, ... , @var{paramN} specify the parameters
 for the frei0r effect.
@@ -2225,7 +2416,7 @@
 @end example
 
 @item
-Apply the colordistance effect, takes a color as first parameter:
+Apply the colordistance effect, take a color as first parameter:
 @example
 frei0r=colordistance:0.2/0.3/0.4
 frei0r=colordistance:violet
@@ -2243,6 +2434,91 @@
 For more information see:
 @url{http://frei0r.dyne.org}
 
+@section geq
+
+The filter takes one, two or three equations as parameter, separated by ':'.
+The first equation is mandatory and applies to the luma plane. The two
+following are respectively for chroma blue and chroma red planes.
+
+The filter syntax allows named parameters:
+
+@table @option
+@item lum_expr
+the luminance expression
+@item cb_expr
+the chrominance blue expression
+@item cr_expr
+the chrominance red expression
+@end table
+
+If one of the chrominance expression is not defined, it falls back on the other
+one. If none of them are specified, they will evaluate the luminance
+expression.
+
+The expressions can use the following variables and functions:
+
+@table @option
+@item N
+The sequential number of the filtered frame, starting from @code{0}.
+
+@item X, Y
+The coordinates of the current sample.
+
+@item W, H
+The width and height of the image.
+
+@item SW, SH
+Width and height scale depending on the currently filtered plane. It is the
+ratio between the corresponding luma plane number of pixels and the current
+plane ones. E.g. for YUV4:2:0 the values are @code{1,1} for the luma plane, and
+@code{0.5,0.5} for chroma planes.
+
+@item T
+Time of the current frame, expressed in seconds.
+
+@item p(x, y)
+Return the value of the pixel at location (@var{x},@var{y}) of the current
+plane.
+
+@item lum(x, y)
+Return the value of the pixel at location (@var{x},@var{y}) of the luminance
+plane.
+
+@item cb(x, y)
+Return the value of the pixel at location (@var{x},@var{y}) of the
+blue-difference chroma plane.
+
+@item cr(x, y)
+Return the value of the pixel at location (@var{x},@var{y}) of the
+red-difference chroma plane.
+@end table
+
+For functions, if @var{x} and @var{y} are outside the area, the value will be
+automatically clipped to the closer edge.
+
+Some examples follow:
+
+@itemize
+@item
+Flip the image horizontally:
+@example
+geq=p(W-X\,Y)
+@end example
+
+@item
+Generate a bidimensional sine wave, with angle @code{PI/3} and a
+wavelength of 100 pixels:
+@example
+geq=128 + 100*sin(2*(PI/100)*(cos(PI/3)*(X-50*T) + sin(PI/3)*Y)):128:128
+@end example
+
+@item
+Generate a fancy enigmatic moving light:
+@example
+nullsrc=s=256x256,geq=random(1)/hypot(X-cos(N*0.07)*W/2-W/2\,Y-sin(N*0.09)*H/2-H/2)^2*1000000*sin(N*0.02):128:128
+@end example
+@end itemize
+
 @section gradfun
 
 Fix the banding artifacts that are sometimes introduced into nearly flat
@@ -2446,14 +2722,10 @@
 The @var{lut} filter requires either YUV or RGB pixel formats in
 input, and accepts the options:
 @table @option
-@item c0
-first  pixel component
-@item c1
-second pixel component
-@item c2
-third  pixel component
-@item c3
-fourth pixel component, corresponds to the alpha component
+@item @var{c0} (first  pixel component)
+@item @var{c1} (second pixel component)
+@item @var{c2} (third  pixel component)
+@item @var{c3} (fourth pixel component, corresponds to the alpha component)
 @end table
 
 The exact component associated to each option depends on the format in
@@ -2462,27 +2734,19 @@
 The @var{lutrgb} filter requires RGB pixel formats in input, and
 accepts the options:
 @table @option
-@item r
-red component
-@item g
-green component
-@item b
-blue component
-@item a
-alpha component
+@item @var{r} (red component)
+@item @var{g} (green component)
+@item @var{b} (blue component)
+@item @var{a} (alpha component)
 @end table
 
 The @var{lutyuv} filter requires YUV pixel formats in input, and
 accepts the options:
 @table @option
-@item y
-Y/luminance component
-@item u
-U/Cb component
-@item v
-V/Cr component
-@item a
-alpha component
+@item @var{y} (Y/luminance component)
+@item @var{u} (U/Cb component)
+@item @var{v} (V/Cr component)
+@item @var{a} (alpha component)
 @end table
 
 The expressions can contain the following constants and functions:
@@ -2580,13 +2844,9 @@
 @item dsize
 @item eq2
 @item eq
-@item field
 @item fil
-@item fixpts
 @item fspp
-@item geq
 @item harddup
-@item hqdn3d
 @item il
 @item ilpack
 @item ivtc
@@ -2594,24 +2854,19 @@
 @item mcdeint
 @item noise
 @item ow
-@item palette
 @item perspective
 @item phase
 @item pp7
 @item pullup
 @item qp
-@item rectangle
 @item sab
 @item softpulldown
 @item softskip
 @item spp
 @item telecine
-@item tile
 @item tinterlace
 @item unsharp
 @item uspp
-@item yuvcsp
-@item yvu9
 @end table
 
 The parameter syntax and behavior for the listed filters are the same
@@ -2822,7 +3077,7 @@
 
 # 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@.3:WxH [over]; [in][over] overlay [out]
+color=red@@.3:WxH [over]; [in][over] overlay [out]
 
 # play an original video and a filtered version (here with the deshake filter)
 # side by side
@@ -2911,7 +3166,7 @@
 
 @end table
 
-@section Examples
+@subsection Examples
 
 @itemize
 @item
@@ -3005,13 +3260,57 @@
 
 @section scale
 
-Scale the input video to @var{width}:@var{height}[:@var{interl}=@{1|-1@}] and/or convert the image format.
+Scale (resize) the input video, using the libswscale library.
 
 The scale filter forces the output display aspect ratio to be the same
 of the input, by changing the output sample aspect ratio.
 
-The parameters @var{width} and @var{height} are expressions containing
-the following constants:
+This filter accepts a list of named options in the form of
+@var{key}=@var{value} pairs separated by ":". If the key for the first
+two options is not specified, the assumed keys for the first two
+values are @code{w} and @code{h}. If the first option has no key and
+can be interpreted like a video size specification, it will be used
+to set the video size.
+
+A description of the accepted options follows.
+
+@table @option
+@item width, w
+Set the video width expression, default value is @code{iw}. See below
+for the list of accepted constants.
+
+@item height, h
+Set the video heiht expression, default value is @code{ih}.
+See below for the list of accepted constants.
+
+@item interl
+Set the interlacing. It accepts the following values:
+
+@table @option
+@item 1
+force interlaced aware scaling
+
+@item 0
+do not apply interlaced scaling
+
+@item -1
+select interlaced aware scaling depending on whether the source frames
+are flagged as interlaced or not
+@end table
+
+Default value is @code{0}.
+
+@item flags
+Set libswscale scaling flags. If not explictly specified the filter
+applies a bilinear scaling algorithm.
+
+@item size, s
+Set the video size, the value must be a valid abbreviation or in the
+form @var{width}x@var{height}.
+@end table
+
+The values of the @var{w} and @var{h} options are expressions
+containing the following constants:
 
 @table @option
 @item in_w, in_h
@@ -3051,53 +3350,92 @@
 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.
+@subsection Examples
 
-Valid values for the optional parameter @var{interl} are:
-
-@table @option
-@item 1
-force interlaced aware scaling
-
-@item -1
-select interlaced aware scaling depending on whether the source frames
-are flagged as interlaced or not
-@end table
-
-Unless @var{interl} is set to one of the above options, interlaced scaling will not be used.
-
-Some examples follow:
+@itemize
+@item
+Scale the input video to a size of 200x100:
 @example
-# scale the input video to a size of 200x100.
 scale=200:100
+@end example
 
-# scale the input to 2x
+This is equivalent to:
+@example
+scale=w=200:h=100
+@end example
+
+or:
+@example
+scale=200x100
+@end example
+
+@item
+Specify a size abbreviation for the output size:
+@example
+scale=qcif
+@end example
+
+which can also be written as:
+@example
+scale=size=qcif
+@end example
+
+@item
+Scale the input to 2x:
+@example
 scale=2*iw:2*ih
-# the above is the same as
+@end example
+
+@item
+The above is the same as:
+@example
 scale=2*in_w:2*in_h
+@end example
 
-# scale the input to 2x with forced interlaced scaling
+@item
+Scale the input to 2x with forced interlaced scaling:
+@example
 scale=2*iw:2*ih:interl=1
+@end example
 
-# scale the input to half size
+@item
+Scale the input to half size:
+@example
 scale=iw/2:ih/2
+@end example
 
-# increase the width, and set the height to the same size
+@item
+Increase the width, and set the height to the same size:
+@example
 scale=3/2*iw:ow
+@end example
 
-# seek for Greek harmony
+@item
+Seek for Greek harmony:
+@example
 scale=iw:1/PHI*iw
 scale=ih*PHI:ih
+@end example
 
-# increase the height, and set the width to 3/2 of the height
+@item
+Increase the height, and set the width to 3/2 of the height:
+@example
 scale=3/2*oh:3/5*ih
+@end example
 
-# increase the size, but make the size a multiple of the chroma
+@item
+Increase the size, but make the size a multiple of the chroma:
+@example
 scale="trunc(3/2*iw/hsub)*hsub:trunc(3/2*ih/vsub)*vsub"
+@end example
 
-# increase the width to a maximum of 500 pixels, keep the same input aspect ratio
+@item
+Increase the width to a maximum of 500 pixels, keep the same input
+aspect ratio:
+@example
 scale='min(500\, iw*3/2):-1'
 @end example
+@end itemize
 
 @section select
 Select frames to pass in output.
@@ -3249,16 +3587,34 @@
 filter may be changed by later filters in the filterchain, e.g. if
 another "setsar" or a "setdar" filter is applied.
 
-The @code{setdar} and @code{setsar} filters accept a parameter string
-which represents the wanted aspect ratio.  The parameter can
-be a floating point number string, an expression, or a string 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".
+The @code{setdar} and @code{setsar} filters accept a string in the
+form @var{num}:@var{den} expressing an aspect ratio, or the following
+named options, expressed as a sequence of @var{key}=@var{value} pairs,
+separated by ":".
+
+@table @option
+@item max
+Set the maximum integer value to use for expressing numerator and
+denominator when reducing the expressed aspect ratio to a rational.
+Default value is @code{100}.
+
+@item r, ratio:
+Set the aspect ratio used by the filter.
+
+The parameter can be a floating point number string, an expression, or
+a string 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".
+In case the form "@var{num}:@var{den}" the @code{:} character should
+be escaped.
+@end table
+
+If the keys are omitted in the named options list, the specifed values
+are assumed to be @var{ratio} and @var{max} in that order.
 
 For example to change the display aspect ratio to 16:9, specify:
 @example
-setdar=16:9
+setdar='16:9'
 @end example
 
 The example above is equivalent to:
@@ -3268,7 +3624,13 @@
 
 To change the sample aspect ratio to 10:11, specify:
 @example
-setsar=10:11
+setsar='10:11'
+@end example
+
+To set a display aspect ratio of 16:9, and specify a maximum integer value of
+1000 in the aspect ratio reduction, use the command:
+@example
+setdar=ratio='16:9':max=1000
 @end example
 
 @section setfield
@@ -3354,21 +3716,6 @@
 expressed in the form "[@var{c0} @var{c1} @var{c2} @var{c3}]"
 @end table
 
-@section slicify
-
-Pass the images of input video on to next video filter as multiple
-slices.
-
-@example
-ffmpeg -i in.avi -vf "slicify=32" out.avi
-@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.
-
 @section smartblur
 
 Blur the input video without impacting the outlines.
@@ -3455,8 +3802,33 @@
 
 Tile several successive frames together.
 
-It accepts as argument the tile size (i.e. the number of lines and columns)
-in the form "@var{w}x@var{h}".
+It accepts a list of options in the form of @var{key}=@var{value} pairs
+separated by ":". A description of the accepted options follows.
+
+@table @option
+
+@item layout
+Set the grid size (i.e. the number of lines and columns) in the form
+"@var{w}x@var{h}".
+
+@item margin
+Set the outer border margin in pixels.
+
+@item padding
+Set the inner border thickness (i.e. the number of pixels between frames). For
+more advanced padding options (such as having different values for the edges),
+refer to the pad video filter.
+
+@item nb_frames
+Set the maximum number of frames to render in the given area. It must be less
+than or equal to @var{w}x@var{h}. The default value is @code{0}, meaning all
+the area will be used.
+
+@end table
+
+Alternatively, the options can be specified as a flat string:
+
+@var{layout}[:@var{nb_frames}[:@var{margin}[:@var{padding}]]]
 
 For example, produce 8×8 PNG tiles of all keyframes (@option{-skip_frame
 nokey}) in a movie:
@@ -3467,6 +3839,13 @@
 duplicating each output frame to accomodate the originally detected frame
 rate.
 
+Another example to display @code{5} pictures in an area of @code{3x2} frames,
+with @code{7} pixels between them, and @code{2} pixels of initial margin, using
+mixed flat and named options:
+@example
+tile=3x2:nb_frames=5:padding=7:margin=2
+@end example
+
 @section tinterlace
 
 Perform various types of temporal field interlacing.
@@ -3519,8 +3898,11 @@
 
 Transpose rows with columns in the input video and optionally flip it.
 
-It accepts a parameter representing an integer, which can assume the
-values:
+This filter accepts the following named parameters:
+
+@table @option
+@item dir
+Specify the transposition direction. Can assume the following values:
 
 @table @samp
 @item 0, 4
@@ -3556,8 +3938,24 @@
 @end example
 @end table
 
-For values between 4-7 transposition is only done if the input video
-geometry is portrait and not landscape.
+For values between 4-7, the transposition is only done if the input
+video geometry is portrait and not landscape. These values are
+deprecated, the @code{passthrough} option should be used instead.
+
+@item passthrough
+Do not apply the transposition if the input geometry matches the one
+specified by the specified value. It accepts the following values:
+@table @samp
+@item none
+Always apply transposition.
+@item portrait
+Preserve portrait geometry (when @var{height} >= @var{width}).
+@item landscape
+Preserve landscape geometry (when @var{width} >= @var{height}).
+@end table
+
+Default value is @code{none}.
+@end table
 
 @section unsharp
 
@@ -3683,7 +4081,7 @@
 through the interface defined in @file{libavfilter/vsrc_buffer.h}.
 
 It accepts a list of options in the form of @var{key}=@var{value} pairs
-separated by ":". A descroption of the accepted options follows.
+separated by ":". A description of the accepted options follows.
 
 @table @option
 
@@ -3719,7 +4117,7 @@
 with format "yuv410p", assuming 1/24 as the timestamps timebase and
 square pixels (1:1 sample aspect ratio).
 Since the pixel format with name "yuv410p" corresponds to the number 6
-(check the enum PixelFormat definition in @file{libavutil/pixfmt.h}),
+(check the enum AVPixelFormat definition in @file{libavutil/pixfmt.h}),
 this example corresponds to:
 @example
 buffer=size=320x240:pixfmt=6:time_base=1/24:pixel_aspect=1/1
@@ -4210,9 +4608,9 @@
 
 If the input content is to be ignored, @code{nullsrc} can be used. The
 following command generates noise in the luminance plane by employing
-the @code{mp=geq} filter:
+the @code{geq} filter:
 @example
-nullsrc=s=256x256, mp=geq=random(1)*255:128:128
+nullsrc=s=256x256, geq=random(1)*255:128:128
 @end example
 
 @c man end VIDEO SOURCES
@@ -4480,6 +4878,53 @@
 @end example
 @end itemize
 
+@section ebur128
+
+EBU R128 scanner filter. This filter takes an audio stream as input and outputs
+it unchanged. By default, it logs a message at a frequency of 10Hz with the
+Momentary loudness (identified by @code{M}), Short-term loudness (@code{S}),
+Integrated loudness (@code{I}) and Loudness Range (@code{LRA}).
+
+The filter also has a video output (see the @var{video} option) with a real
+time graph to observe the loudness evolution. The graphic contains the logged
+message mentioned above, so it is not printed anymore when this option is set,
+unless the verbose logging is set. The main graphing area contains the
+short-term loudness (3 seconds of analysis), and the gauge on the right is for
+the momentary loudness (400 milliseconds).
+
+More information about the Loudness Recommendation EBU R128 on
+@url{http://tech.ebu.ch/loudness}.
+
+The filter accepts the following named parameters:
+
+@table @option
+
+@item video
+Activate the video output. The audio stream is passed unchanged whether this
+option is set or no. The video stream will be the first output stream if
+activated. Default is @code{0}.
+
+@item size
+Set the video size. This option is for video only. Default and minimum
+resolution is @code{640x480}.
+
+@item meter
+Set the EBU scale meter. Default is @code{9}. Common values are @code{9} and
+@code{18}, respectively for EBU scale meter +9 and EBU scale meter +18. Any
+other integer value between this range is allowed.
+
+@end table
+
+Example of real-time graph using @command{ffplay}, with a EBU scale meter +18:
+@example
+ffplay -f lavfi -i "amovie=input.mp3,ebur128=video=1:meter=18 [out0][out1]"
+@end example
+
+Run an analysis with @command{ffmpeg}:
+@example
+ffmpeg -nostats -i input.mp3 -filter_complex ebur128 -f null -
+@end example
+
 @section settb, asettb
 
 Set the timebase to use for the output frames timestamps.
@@ -4549,6 +4994,9 @@
 Set the number of output audio streams, that is also the number of video
 streams in each segment. Default is 0.
 
+@item unsafe
+Activate unsafe mode: do not fail if segments have a different format.
+
 @end table
 
 The filter has @var{v}+@var{a} outputs: first @var{v} video outputs, then
@@ -4610,6 +5058,9 @@
 @table @option
 @item size, s
 Specify the video size for the output. Default value is @code{640x480}.
+@item slide
+Specify if the spectrum should slide along the window. Default value is
+@code{0}.
 @end table
 
 The usage is very similar to the showwaves filter; see the examples in that
diff --git a/doc/general.texi b/doc/general.texi
index b5f4c99..5698106 100644
--- a/doc/general.texi
+++ b/doc/general.texi
@@ -147,9 +147,15 @@
     @tab Multimedia format used in game Heart Of Darkness.
 @item Apple HTTP Live Streaming @tab   @tab X
 @item Artworx Data Format       @tab   @tab X
+@item AFC                       @tab   @tab X
+    @tab Audio format used on the Nintendo Gamecube.
 @item ASF                       @tab X @tab X
+@item AST                       @tab   @tab X
+    @tab Audio format used on the Nintendo Wii.
 @item AVI                       @tab X @tab X
 @item AVISynth                  @tab   @tab X
+@item AVR                       @tab   @tab X
+    @tab Audio format used on Mac.
 @item AVS                       @tab   @tab X
     @tab Multimedia format used by the Creature Shock game.
 @item Beam Software SIFF        @tab   @tab X
@@ -163,6 +169,8 @@
     @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 BRSTM                     @tab   @tab X
+    @tab Audio format used on the Nintendo Wii.
 @item BWF                       @tab X @tab X
 @item CRI ADX                   @tab X @tab X
     @tab Audio-only format used in console video games.
@@ -207,7 +215,7 @@
 @item G.723.1                   @tab X @tab X
 @item G.729 BIT                 @tab X @tab X
 @item G.729 raw                 @tab   @tab X
-@item GIF Animation             @tab X @tab
+@item GIF Animation             @tab X @tab X
 @item GXF                       @tab X @tab X
     @tab General eXchange Format SMPTE 360M, used by Thomson Grass Valley
          playout servers.
@@ -232,6 +240,7 @@
     @tab Used by Linux Media Labs MPEG-4 PCI boards
 @item LOAS                      @tab   @tab X
     @tab contains LATM multiplexed AAC audio
+@item LVF                       @tab   @tab X
 @item LXF                       @tab   @tab X
     @tab VR native stream format, used by Leitch/Harris' video servers.
 @item Matroska                  @tab X @tab X
@@ -277,6 +286,7 @@
     @tab NUT Open Container Format
 @item Ogg                       @tab X @tab X
 @item Playstation Portable PMP  @tab   @tab X
+@item Portable Voice Format     @tab   @tab X
 @item TechnoTrend PVA           @tab   @tab X
     @tab Used by TechnoTrend DVB PCI boards.
 @item QCP                       @tab   @tab X
@@ -287,6 +297,7 @@
 @item raw Dirac                 @tab X @tab X
 @item raw DNxHD                 @tab X @tab X
 @item raw DTS                   @tab X @tab X
+@item raw DTS-HD                @tab   @tab X
 @item raw E-AC-3                @tab X @tab X
 @item raw FLAC                  @tab X @tab X
 @item raw GSM                   @tab   @tab X
@@ -304,6 +315,7 @@
 @item raw video                 @tab X @tab X
 @item raw id RoQ                @tab X @tab
 @item raw Shorten               @tab   @tab X
+@item raw TAK                   @tab   @tab X
 @item raw TrueHD                @tab X @tab X
 @item raw VC-1                  @tab   @tab X
 @item raw PCM A-law             @tab X @tab X
@@ -368,6 +380,7 @@
     @tab Tiertex .seq files used in the DOS CD-ROM version of the game Flashback.
 @item True Audio                @tab   @tab X
 @item VC-1 test bitstream       @tab X @tab X
+@item Vivo                      @tab   @tab X
 @item WAV                       @tab X @tab X
 @item WavPack                   @tab X @tab X
 @item WebM                      @tab X @tab X
@@ -402,6 +415,8 @@
     @tab Only uncompressed GIFs are generated.
 @item BMP          @tab X @tab X
     @tab Microsoft BMP image
+@item PIX          @tab   @tab X
+    @tab PIX is an image format used in the Argonaut BRender engine.
 @item DPX          @tab X @tab X
     @tab Digital Picture Exchange
 @item EXR          @tab   @tab X
@@ -439,6 +454,8 @@
     @tab Targa (.TGA) image format
 @item XBM  @tab X @tab X
     @tab X BitMap image format
+@item XFace @tab X @tab X
+    @tab X-Face image format
 @item XWD  @tab X @tab X
     @tab X Window Dump image format
 @end multitable
@@ -454,8 +471,6 @@
 @item 4X Movie               @tab     @tab  X
     @tab Used in certain computer games.
 @item 8088flex TMV           @tab     @tab  X
-@item 8SVX exponential       @tab     @tab  X
-@item 8SVX fibonacci         @tab     @tab  X
 @item A64 multicolor         @tab  X  @tab
     @tab Creates video suitable to be played on a commodore 64 (multicolor mode).
 @item Amazing Studio PAF Video @tab     @tab  X
@@ -622,6 +637,8 @@
     @tab fourcc: VP60,VP61,VP62
 @item VP8                    @tab  E  @tab  X
     @tab fourcc: VP80, encoding supported through external library libvpx
+@item Pinnacle TARGA CineWave YUV16 @tab     @tab  X
+    @tab fourcc: Y216
 @item Prores                 @tab     @tab  X
     @tab fourcc: apch,apcn,apcs,apco
 @item Q-team QPEG            @tab     @tab  X
@@ -706,7 +723,8 @@
 
 @multitable @columnfractions .4 .1 .1 .4
 @item Name @tab Encoding @tab Decoding @tab Comments
-@item 8SVX audio             @tab     @tab  X
+@item 8SVX exponential       @tab     @tab  X
+@item 8SVX fibonacci         @tab     @tab  X
 @item AAC+                   @tab  E  @tab  X
     @tab encoding supported through external library libaacplus
 @item AAC                    @tab  E  @tab  X
@@ -737,19 +755,19 @@
 @item ADPCM IMA Westwood     @tab     @tab  X
 @item ADPCM ISS IMA          @tab     @tab  X
     @tab Used in FunCom games.
+@item ADPCM IMA Dialogic     @tab     @tab  X
 @item ADPCM IMA Duck DK3     @tab     @tab  X
     @tab Used in some Sega Saturn console games.
 @item ADPCM IMA Duck DK4     @tab     @tab  X
     @tab Used in some Sega Saturn console games.
 @item ADPCM Microsoft        @tab  X  @tab  X
 @item ADPCM MS IMA           @tab  X  @tab  X
+@item ADPCM Nintendo Gamecube AFC  @tab     @tab  X
 @item ADPCM Nintendo Gamecube THP  @tab     @tab  X
 @item ADPCM QT IMA           @tab  X  @tab  X
 @item ADPCM SEGA CRI ADX     @tab  X  @tab  X
     @tab Used in Sega Dreamcast games.
 @item ADPCM Shockwave Flash  @tab  X  @tab  X
-@item ADPCM SMJPEG IMA       @tab     @tab  X
-    @tab Used in certain Loki game ports.
 @item ADPCM Sound Blaster Pro 2-bit  @tab     @tab  X
 @item ADPCM Sound Blaster Pro 2.6-bit  @tab     @tab  X
 @item ADPCM Sound Blaster Pro 4-bit  @tab     @tab  X
@@ -813,11 +831,15 @@
 @item Musepack SV7           @tab     @tab  X
 @item Musepack SV8           @tab     @tab  X
 @item Nellymoser Asao        @tab  X  @tab  X
-@item Opus                   @tab     @tab  E
+@item Opus                   @tab  E  @tab  E
     @tab supported through external library libopus
 @item PCM A-law              @tab  X  @tab  X
 @item PCM mu-law             @tab  X  @tab  X
-@item PCM 16-bit little-endian planar  @tab     @tab  X
+@item PCM signed 8-bit planar  @tab  X  @tab  X
+@item PCM signed 16-bit big-endian planar  @tab  X  @tab  X
+@item PCM signed 16-bit little-endian planar  @tab  X  @tab  X
+@item PCM signed 24-bit little-endian planar  @tab  X  @tab  X
+@item PCM signed 32-bit little-endian planar  @tab  X  @tab  X
 @item PCM 32-bit floating point big-endian  @tab  X  @tab  X
 @item PCM 32-bit floating point little-endian  @tab  X  @tab  X
 @item PCM 64-bit floating point big-endian  @tab  X  @tab  X
@@ -861,6 +883,7 @@
     @tab experimental codec
 @item Speex                  @tab  E  @tab  E
     @tab supported through external library libspeex
+@item TAK (Tom's lossless Audio Kompressor)  @tab     @tab  X
 @item True Audio (TTA)       @tab     @tab  X
 @item TrueHD                 @tab     @tab  X
     @tab Used in HD-DVD and Blu-Ray discs.
diff --git a/doc/indevs.texi b/doc/indevs.texi
index a5a91fa..6ccd12c 100644
--- a/doc/indevs.texi
+++ b/doc/indevs.texi
@@ -224,6 +224,13 @@
 is an exact value. For HDV, it is not frame exact, since HDV does
 not have a fixed frame size.
 
+@item dvguid
+Select the capture device by specifying it's GUID. Capturing will only
+be performed from the specified device and fails if no device with the
+given GUID is found. This is useful to select the input if multiple
+devices are connected at the same time.
+Look at /sys/bus/firewire/devices to find out the GUIDs.
+
 @end table
 
 @subsection Examples
@@ -320,6 +327,12 @@
 
 If not specified defaults to the filename specified for the input
 device.
+
+@item graph_file
+Set the filename of the filtergraph to be read and sent to the other
+filters. Syntax of the filtergraph is the same as the one specified by
+the option @var{graph}.
+
 @end table
 
 @subsection Examples
diff --git a/doc/libavcodec.texi b/doc/libavcodec.texi
new file mode 100644
index 0000000..1fd1cf8
--- /dev/null
+++ b/doc/libavcodec.texi
@@ -0,0 +1,39 @@
+\input texinfo @c -*- texinfo -*-
+
+@settitle Libavcodec Documentation
+@titlepage
+@center @titlefont{Libavcodec Documentation}
+@end titlepage
+
+@top
+
+@contents
+
+@chapter Description
+@c man begin DESCRIPTION
+
+The libavcodec library provides a generic encoding/decoding framework
+and contains multiple decoders and encoders for audio, video and
+subtitle streams, and several bitstream filters.
+
+The shared architecture provides various services ranging from bit
+stream I/O to DSP optimizations, and makes it suitable for
+implementing robust and fast codecs as well as for experimentation.
+
+@ignore
+
+@setfilename libavcodec
+@settitle media streams decoding and encoding library
+
+@c man begin SEEALSO
+ffmpeg(1), ffplay(1), ffprobe(1), ffserver(1), ffmpeg-codecs(1),
+ffmpeg-bistream-filters(1), libavutil(3)
+@c man end
+
+@c man begin AUTHORS
+See Git history (git://source.ffmpeg.org/ffmpeg)
+@c man end
+
+@end ignore
+
+@bye
diff --git a/doc/libavdevice.texi b/doc/libavdevice.texi
new file mode 100644
index 0000000..d6e17ae
--- /dev/null
+++ b/doc/libavdevice.texi
@@ -0,0 +1,38 @@
+\input texinfo @c -*- texinfo -*-
+
+@settitle Libavdevice Documentation
+@titlepage
+@center @titlefont{Libavdevice Documentation}
+@end titlepage
+
+@top
+
+@contents
+
+@chapter Description
+@c man begin DESCRIPTION
+
+The libavdevice library provides a generic framework for grabbing from
+and rendering to many common multimedia input/output devices, and
+supports several input and output devices, including Video4Linux2,
+VfW, DShow, and ALSA.
+
+@c man end DESCRIPTION
+
+@ignore
+
+@setfilename libavdevice
+@settitle multimedia device handling library
+
+@c man begin SEEALSO
+ffmpeg(1), ffplay(1), ffprobe(1), ffserver(1), libavutil(3),
+libavcodec(3), libavformat(3), ffmpeg-devices(1)
+@c man end
+
+@c man begin AUTHORS
+See Git history (git://source.ffmpeg.org/ffmpeg)
+@c man end
+
+@end ignore
+
+@bye
diff --git a/doc/libavfilter.texi b/doc/libavfilter.texi
new file mode 100644
index 0000000..5d0e82a
--- /dev/null
+++ b/doc/libavfilter.texi
@@ -0,0 +1,35 @@
+\input texinfo @c -*- texinfo -*-
+
+@settitle Libavfilter Documentation
+@titlepage
+@center @titlefont{Libavfilter Documentation}
+@end titlepage
+
+@top
+
+@contents
+
+@chapter Description
+@c man begin DESCRIPTION
+
+The libavfilter library provides a generic audio/video filtering
+framework containing several filters, sources and sinks.
+
+@c man end DESCRIPTION
+
+@ignore
+
+@setfilename libavfilter
+@settitle multimedia filtering library
+
+@c man begin SEEALSO
+ffmpeg(1), ffplay(1), ffprobe(1), ffserver(1), ffmpeg-filters(1)
+@c man end
+
+@c man begin AUTHORS
+See Git history (git://source.ffmpeg.org/ffmpeg)
+@c man end
+
+@end ignore
+
+@bye
diff --git a/doc/libavformat.texi b/doc/libavformat.texi
new file mode 100644
index 0000000..1e85f65
--- /dev/null
+++ b/doc/libavformat.texi
@@ -0,0 +1,40 @@
+\input texinfo @c -*- texinfo -*-
+
+@settitle Libavformat Documentation
+@titlepage
+@center @titlefont{Libavformat Documentation}
+@end titlepage
+
+@top
+
+@contents
+
+@chapter Description
+@c man begin DESCRIPTION
+
+The libavformat library provides a generic framework for multiplexing
+and demultiplexing (muxing and demuxing) audio, video and subtitle
+streams. It encompasses multiple muxers and demuxers for multimedia
+container formats.
+
+It also supports several input and output protocols to access a media
+resource.
+
+@c man end DESCRIPTION
+
+@ignore
+
+@setfilename libavformat
+@settitle multimedia muxing and demuxing library
+
+@c man begin SEEALSO
+ffmpeg(1), ffplay(1), ffprobe(1), ffserver(1), libavutil(3), libavcodec(3), ffmpeg-formats(1), ffmpeg-protocols(1)
+@c man end
+
+@c man begin AUTHORS
+See Git history (git://source.ffmpeg.org/ffmpeg)
+@c man end
+
+@end ignore
+
+@bye
diff --git a/doc/libavutil.texi b/doc/libavutil.texi
new file mode 100644
index 0000000..c12d7ff
--- /dev/null
+++ b/doc/libavutil.texi
@@ -0,0 +1,38 @@
+\input texinfo @c -*- texinfo -*-
+
+@settitle Libavutil Documentation
+@titlepage
+@center @titlefont{Libavutil Documentation}
+@end titlepage
+
+@top
+
+@contents
+
+@chapter Description
+@c man begin DESCRIPTION
+
+The libavutil library is a utility library to aid portable
+multimedia programming. It contains safe portable string functions,
+random number generators, data structures, additional mathematics
+functions, cryptography and multimedia related functionality (like
+enumerations for pixel and sample formats).
+
+@c man end DESCRIPTION
+
+@ignore
+
+@setfilename libavutil
+@settitle multimedia-biased utility library
+
+@c man begin SEEALSO
+ffmpeg(1), ffplay(1), ffprobe(1), ffserver(1), ffmpeg-utils(1)
+@c man end
+
+@c man begin AUTHORS
+See Git history (git://source.ffmpeg.org/ffmpeg)
+@c man end
+
+@end ignore
+
+@bye
diff --git a/doc/libswresample.texi b/doc/libswresample.texi
new file mode 100644
index 0000000..e1c0e2f
--- /dev/null
+++ b/doc/libswresample.texi
@@ -0,0 +1,62 @@
+\input texinfo @c -*- texinfo -*-
+
+@settitle Libswresample Documentation
+@titlepage
+@center @titlefont{Libswresample Documentation}
+@end titlepage
+
+@top
+
+@contents
+
+@chapter Description
+@c man begin DESCRIPTION
+
+The libswresample library performs highly optimized audio resampling,
+rematrixing and sample format conversion operations.
+
+Specifically, this library performs the following conversions:
+
+@itemize
+@item
+@emph{Resampling}: is the process of changing the audio rate, for
+example from an high sample rate of 44100Hz to 8000Hz. Audio
+conversion from high to low sample rate is a lossy process. Several
+resampling options and algorithms are available.
+
+@item
+@emph{Format conversion}: is the process of converting the type of
+samples, for example from 16-bit signed samples to unsigned 8-bit or
+float samples. It also handles packing conversion, when passing from
+packed layout (all samples belonging to distinct channels interleaved
+in the same buffer), to planar layout (all samples belonging to the
+same channel stored in a dedicated buffer or "plane").
+
+@item
+@emph{Rematrixing}: is the process of changing the channel layout, for
+example from stereo to mono. When the input channels cannot be mapped
+to the output streams, the process is lossy, since it involves
+different gain factors and mixing.
+@end itemize
+
+Various other audio conversions (e.g. stretching and padding) are
+enabled through dedicated options.
+
+@c man end DESCRIPTION
+
+@ignore
+
+@setfilename libswresample
+@settitle audio resampling library
+
+@c man begin SEEALSO
+ffmpeg(1), ffplay(1), ffprobe(1), ffserver(1), ffmpeg-resampler(1), libavutil(3)
+@c man end
+
+@c man begin AUTHORS
+See Git history (git://source.ffmpeg.org/ffmpeg)
+@c man end
+
+@end ignore
+
+@bye
diff --git a/doc/libswscale.texi b/doc/libswscale.texi
new file mode 100644
index 0000000..a8c08e6
--- /dev/null
+++ b/doc/libswscale.texi
@@ -0,0 +1,55 @@
+\input texinfo @c -*- texinfo -*-
+
+@settitle Libswscale Documentation
+@titlepage
+@center @titlefont{Libswscale Documentation}
+@end titlepage
+
+@top
+
+@contents
+
+@chapter Description
+@c man begin DESCRIPTION
+
+The libswscale library performs highly optimized image scaling and
+colorspace and pixel format conversion operations.
+
+Specifically, this library performs the following conversions:
+
+@itemize
+@item
+@emph{Rescaling}: is the process of changing the video size. Several
+rescaling options and algorithms are available. This is usually a
+lossy process.
+
+@item
+@emph{Pixel format conversion}: is the process of converting the image
+format and colorspace of the image, for example from planar YUV420P to
+RGB24 packed. It also handles packing conversion, that is converts
+from packed layout (all pixels belonging to distinct planes
+interleaved in the same buffer), to planar layout (all samples
+belonging to the same plane stored in a dedicated buffer or "plane").
+
+This is usually a lossy process in case the source and destination
+colorspaces differ.
+@end itemize
+
+@c man end DESCRIPTION
+
+@ignore
+
+@setfilename libswscale
+@settitle video scaling and pixel format conversion library
+
+@c man begin SEEALSO
+ffmpeg(1), ffplay(1), ffprobe(1), ffserver(1), ffmpeg-scaler(1), libavutil(3)
+@c man end
+
+@c man begin AUTHORS
+See Git history (git://source.ffmpeg.org/ffmpeg)
+@c man end
+
+@end ignore
+
+@bye
diff --git a/doc/mips.txt b/doc/mips.txt
index 6fa6fb4..aabdef0 100644
--- a/doc/mips.txt
+++ b/doc/mips.txt
@@ -45,8 +45,10 @@
 Files that have MIPS copyright notice in them:
 ===============================================
 * libavutil/mips/
+      float_dsp_mips.c
       libm_mips.h
 * libavcodec/mips/
+      ac3dsp_mips.c
       acelp_filters_mips.c
       acelp_vectors_mips.c
       amrwbdec_mips.c
diff --git a/doc/muxers.texi b/doc/muxers.texi
index 83c21db..1c8f93b 100644
--- a/doc/muxers.texi
+++ b/doc/muxers.texi
@@ -129,6 +129,27 @@
 
 See also the @ref{md5} muxer.
 
+@anchor{hls}
+@section hls
+
+Apple HTTP Live Streaming muxer that segments MPEG-TS according to
+the HTTP Live Streaming specification.
+
+It creates a playlist file and numbered segment files. The output
+filename specifies the playlist filename; the segment filenames
+receive the same basename as the playlist, a sequential number and
+a .ts extension.
+
+@example
+ffmpeg -i in.nut out.m3u8
+@end example
+
+@table @option
+@item -hls_time segment length in seconds
+@item -hls_list_size maximum number of playlist entries
+@item -hls_wrap number after which index wraps
+@end table
+
 @anchor{ico}
 @section ico
 
@@ -252,7 +273,8 @@
 The mov/mp4/ismv muxer supports fragmentation. Normally, a MOV/MP4
 file has all the metadata about all packets stored in one location
 (written at the end of the file, it can be moved to the start for
-better playback using the @command{qt-faststart} tool). A fragmented
+better playback by adding @var{faststart} to the @var{movflags}, or
+using the @command{qt-faststart} tool). A fragmented
 file consists of a number of fragments, where packets and metadata
 about these packets are stored together. Writing a fragmented
 file has the advantage that the file is decodable even if the
@@ -310,6 +332,10 @@
 pair for each track, making it easier to separate tracks.
 
 This option is implicitly set when writing ismv (Smooth Streaming) files.
+@item -movflags faststart
+Run a second pass moving the moov atom on top of the file. This
+operation can take a while, and will not work in various situations such
+as fragmented output, thus it is not enabled by default.
 @end table
 
 Smooth Streaming content can be pushed in real time to a publishing
diff --git a/doc/nut.texi b/doc/nut.texi
new file mode 100644
index 0000000..0026a12
--- /dev/null
+++ b/doc/nut.texi
@@ -0,0 +1,138 @@
+\input texinfo @c -*- texinfo -*-
+
+@settitle NUT
+
+@titlepage
+@center @titlefont{NUT}
+@end titlepage
+
+@top
+
+@contents
+
+@chapter Description
+NUT is a low overhead generic container format. It stores audio, video,
+subtitle and user-defined streams in a simple, yet efficient, way.
+
+It was created by a group of FFmpeg and MPlayer developers in 2003
+and was finalized in 2008.
+
+The official nut specification is at svn://svn.mplayerhq.hu/nut
+In case of any differences between this text and the official specification,
+the official specification shall prevail.
+
+@chapter Container-specific codec tags
+
+@section Generic raw YUVA formats
+
+Since many exotic planar YUVA pixel formats are not considered by
+the AVI/QuickTime FourCC lists, the following scheme is adopted for
+representing them.
+
+The first two bytes can contain the values:
+Y1 = only Y
+Y2 = Y+A
+Y3 = YUV
+Y4 = YUVA
+
+The third byte represents the width and height chroma subsampling
+values for the UV planes, that is the amount to shift the luma
+width/height right to find the chroma width/height.
+
+The fourth byte is the number of bits used (8, 16, ...).
+
+If the order of bytes is inverted, that means that each component has
+to be read big-endian.
+
+@section Raw Audio
+
+@multitable @columnfractions .4 .4
+@item ALAW  @tab A-LAW
+@item ULAW  @tab MU-LAW
+@item P<type><interleaving><bits> @tab little-endian PCM
+@item <bits><interleaving><type>P @tab big-endian PCM
+@end multitable
+
+<type> is S for signed integer, U for unsigned integer, F for IEEE float
+<interleaving> is D for default, P is for planar.
+<bits> is 8/16/24/32
+
+@example
+PFD[32]   would for example be signed 32 bit little-endian IEEE float
+@end example
+
+@section Subtitles
+
+@multitable @columnfractions .4 .4
+@item UTF8   @tab Raw UTF-8
+@item SSA[0] @tab SubStation Alpha
+@item DVDS   @tab DVD subtitles
+@item DVBS   @tab DVB subtitles
+@end multitable
+
+@section Raw Data
+
+@multitable @columnfractions .4 .4
+@item UTF8   @tab Raw UTF-8
+@end multitable
+
+@section Codecs
+
+@multitable @columnfractions .4 .4
+@item 3IV1 @tab non-compliant MPEG-4 generated by old 3ivx
+@item ASV1 @tab Asus Video
+@item ASV2 @tab Asus Video 2
+@item CVID @tab Cinepak
+@item CYUV @tab Creative YUV
+@item DIVX @tab non-compliant MPEG-4 generated by old DivX
+@item DUCK @tab Truemotion 1
+@item FFV1 @tab FFmpeg video 1
+@item FFVH @tab FFmpeg Huffyuv
+@item H261 @tab ITU H.261
+@item H262 @tab ITU H.262
+@item H263 @tab ITU H.263
+@item H264 @tab ITU H.264
+@item HFYU @tab Huffyuv
+@item I263 @tab Intel H.263
+@item IV31 @tab Indeo 3.1
+@item IV32 @tab Indeo 3.2
+@item IV50 @tab Indeo 5.0
+@item LJPG @tab ITU JPEG (lossless)
+@item MJLS @tab ITU JPEG-LS
+@item MJPG @tab ITU JPEG
+@item MPG4 @tab MS MPEG-4v1 (not ISO MPEG-4)
+@item MP42 @tab MS MPEG-4v2
+@item MP43 @tab MS MPEG-4v3
+@item MP4V @tab ISO MPEG-4 Part 2 Video (from old encoders)
+@item mpg1 @tab ISO MPEG-1 Video
+@item mpg2 @tab ISO MPEG-2 Video
+@item MRLE @tab MS RLE
+@item MSVC @tab MS Video 1
+@item RT21 @tab Indeo 2.1
+@item RV10 @tab RealVideo 1.0
+@item RV20 @tab RealVideo 2.0
+@item RV30 @tab RealVideo 3.0
+@item RV40 @tab RealVideo 4.0
+@item SNOW @tab FFmpeg Snow
+@item SVQ1 @tab Sorenson Video 1
+@item SVQ3 @tab Sorenson Video 3
+@item theo @tab Xiph Theora
+@item TM20 @tab Truemotion 2.0
+@item UMP4 @tab non-compliant MPEG-4 generated by UB Video MPEG-4
+@item VCR1 @tab ATI VCR1
+@item VP30 @tab VP 3.0
+@item VP31 @tab VP 3.1
+@item VP50 @tab VP 5.0
+@item VP60 @tab VP 6.0
+@item VP61 @tab VP 6.1
+@item VP62 @tab VP 6.2
+@item VP70 @tab VP 7.0
+@item WMV1 @tab MS WMV7
+@item WMV2 @tab MS WMV8
+@item WMV3 @tab MS WMV9
+@item WV1F @tab non-compliant MPEG-4 generated by ?
+@item WVC1 @tab VC-1
+@item XVID @tab non-compliant MPEG-4 generated by old Xvid
+@item XVIX @tab non-compliant MPEG-4 generated by old Xvid with interlacing bug
+@end multitable
+
diff --git a/doc/optimization.txt b/doc/optimization.txt
index b027efe..e3fd324 100644
--- a/doc/optimization.txt
+++ b/doc/optimization.txt
@@ -253,7 +253,7 @@
 http://infocenter.arm.com/help/topic/com.arm.doc.ddi0211j/DDI0211J_arm1136_r1p5_trm.pdf
 Optimization guide for Intel XScale (used in Sharp Zaurus PDA):
 http://download.intel.com/design/intelxscale/27347302.pdf
-Intel Wireless MMX2 Coprocessor: Programmers Reference Manual
+Intel Wireless MMX 2 Coprocessor: Programmers Reference Manual
 http://download.intel.com/design/intelxscale/31451001.pdf
 
 PowerPC-specific:
diff --git a/doc/platform.texi b/doc/platform.texi
index 6047e71..dcdfff2 100644
--- a/doc/platform.texi
+++ b/doc/platform.texi
@@ -1,8 +1,8 @@
 \input texinfo @c -*- texinfo -*-
 
-@settitle Platform Specific information
+@settitle Platform Specific Information
 @titlepage
-@center @titlefont{Platform Specific information}
+@center @titlefont{Platform Specific Information}
 @end titlepage
 
 @top
@@ -77,8 +77,7 @@
 @chapter Windows
 
 To get help and instructions for building FFmpeg under Windows, check out
-the FFmpeg Windows Help Forum at
-@url{http://ffmpeg.arrozcru.org/}.
+the FFmpeg Windows Help Forum at @url{http://ffmpeg.zeranoe.com/forum/}.
 
 @section Native Windows compilation using MinGW or MinGW-w64
 
@@ -110,12 +109,12 @@
 @section Microsoft Visual C++
 
 FFmpeg can be built with MSVC using a C99-to-C89 conversion utility and
-wrapper. At this time, only static builds are supported.
+wrapper.
 
 You will need the following prerequisites:
 
 @itemize
-@item @uref{https://github.com/rbultje/c99-to-c89/, C99-to-C89 Converter & Wrapper}
+@item @uref{https://github.com/libav/c99-to-c89/, C99-to-C89 Converter & Wrapper}
 @item @uref{http://code.google.com/p/msinttypes/, msinttypes}
 @item @uref{http://www.mingw.org/, MSYS}
 @item @uref{http://yasm.tortall.net/, YASM}
@@ -126,13 +125,8 @@
 To set up a proper MSVC environment in MSYS, you simply need to run
 @code{msys.bat} from the Visual Studio command prompt.
 
-Caveat: Run @code{which link} to see which link you are using. If it is located
-at @code{/bin/link.exe}, then you have the wrong link in your @code{PATH}.
-Either move/remove that copy, or make sure MSVC's link.exe is higher up in your
-@code{PATH} than coreutils'.
-
-Place @code{c99wrap.exe}, @code{c99conv.exe}, and @code{yasm.exe} somewhere
-in your @code{PATH}.
+Place @code{makedef}, @code{c99wrap.exe}, @code{c99conv.exe}, and @code{yasm.exe}
+somewhere in your @code{PATH}.
 
 Next, make sure @code{inttypes.h} and any other headers and libs you want to use
 are located in a spot that MSVC can see. Do so by modifying the @code{LIB} and
@@ -148,10 +142,21 @@
 make install
 @end example
 
+If you wish to compile shared libraries, add @code{--enable-shared} to your
+configure options. Note that due to the way MSVC handles DLL imports and
+exports, you cannot compile static and shared libraries at the same time, and
+enabling shared libraries will automatically disable the static ones.
+
 Notes:
 
 @itemize
 
+@item It is possible that coreutils' @code{link.exe} conflicts with MSVC's linker.
+You can find out by running @code{which link} to see which @code{link.exe} you
+are using. If it is located at @code{/bin/link.exe}, then you have the wrong one
+in your @code{PATH}. Either move or remove that copy, or make sure MSVC's
+@code{link.exe} takes precedence in your @code{PATH} over coreutils'.
+
 @item If you wish to build with zlib support, you will have to grab a compatible
 zlib binary from somewhere, with an MSVC import lib, or if you wish to link
 statically, you can follow the instructions below to build a compatible
@@ -298,4 +303,67 @@
 ./configure --target-os=mingw32 --enable-shared --disable-static --extra-cflags=-mno-cygwin --extra-libs=-mno-cygwin
 @end example
 
+@chapter Plan 9
+
+The native @uref{http://plan9.bell-labs.com/plan9/, Plan 9} compiler
+does not implement all the C99 features needed by FFmpeg so the gcc
+port must be used.  Furthermore, a few items missing from the C
+library and shell environment need to be fixed.
+
+@itemize
+
+@item GNU awk, grep, make, and sed
+
+Working packages of these tools can be found at
+@uref{http://code.google.com/p/ports2plan9/downloads/list, ports2plan9}.
+They can be installed with @uref{http://9front.org/, 9front's} @code{pkg}
+utility by setting @code{pkgpath} to
+@code{http://ports2plan9.googlecode.com/files/}.
+
+@item Missing/broken @code{head} and @code{printf} commands
+
+Replacements adequate for building FFmpeg can be found in the
+@code{compat/plan9} directory.  Place these somewhere they will be
+found by the shell.  These are not full implementations of the
+commands and are @emph{not} suitable for general use.
+
+@item Missing C99 @code{stdint.h} and @code{inttypes.h}
+
+Replacement headers are available from
+@url{http://code.google.com/p/plan9front/issues/detail?id=152}.
+
+@item Missing or non-standard library functions
+
+Some functions in the C library are missing or incomplete.  The
+@code{@uref{http://ports2plan9.googlecode.com/files/gcc-apelibs-1207.tbz,
+gcc-apelibs-1207}} package from
+@uref{http://code.google.com/p/ports2plan9/downloads/list, ports2plan9}
+includes an updated C library, but installing the full package gives
+unusable executables.  Instead, keep the files from @code{gccbin.tgz}
+under @code{/386/lib/gnu}.  From the @code{libc.a} archive in the
+@code{gcc-apelibs-1207} package, extract the following object files and
+turn them into a library:
+
+@itemize
+@item @code{strerror.o}
+@item @code{strtoll.o}
+@item @code{snprintf.o}
+@item @code{vsnprintf.o}
+@item @code{vfprintf.o}
+@item @code{_IO_getc.o}
+@item @code{_IO_putc.o}
+@end itemize
+
+Use the @code{--extra-libs} option of @code{configure} to inform the
+build system of this library.
+
+@item FPU exceptions enabled by default
+
+Unlike most other systems, Plan 9 enables FPU exceptions by default.
+These must be disabled before calling any FFmpeg functions.  While the
+included tools will do this automatically, other users of the
+libraries must do it themselves.
+
+@end itemize
+
 @bye
diff --git a/doc/swresample.txt b/doc/swresample.txt
index c0f86a2..7904147 100644
--- a/doc/swresample.txt
+++ b/doc/swresample.txt
@@ -31,7 +31,7 @@
                           v
                         Output
 
-Planar/Packed convertion is done when needed during sample format convertion
+Planar/Packed conversion is done when needed during sample format conversion.
 Every step can be skipped without memcpy when its not needed.
 Either Resampling and Rematrixing can be performed first depending on which
 way its faster.
@@ -39,8 +39,8 @@
 requires future and past data, it thus also introduces inevitably a delay when
 used.
 Internally 32bit float and 16bit int is supported currently, other formats can
-easily be added
+easily be added.
 Externally all sample formats in packed and planar configuration are supported
-Its also trivial to add special converters for common cases
-If only sample format and or packed/planar convertion is needed it
+It's also trivial to add special converters for common cases.
+If only sample format and/or packed/planar conversion is needed, it
 is performed from input to output directly in a single pass with no intermediates.
diff --git a/doc/swscale.txt b/doc/swscale.txt
index 0dc4b8a..2066009 100644
--- a/doc/swscale.txt
+++ b/doc/swscale.txt
@@ -58,7 +58,7 @@
 
 Horizontal scaler
     There are several horizontal scalers. A special case worth mentioning is
-    the fast bilinear scaler that is made of runtime-generated MMX2 code
+    the fast bilinear scaler that is made of runtime-generated MMXEXT code
     using specially tuned pshufw instructions.
     The remaining scalers are specially-tuned for various filter lengths.
     They scale 8-bit unsigned planar data to 16-bit signed planar data.
diff --git a/doc/syntax.texi b/doc/syntax.texi
index 169fa78..a3aabce 100644
--- a/doc/syntax.texi
+++ b/doc/syntax.texi
@@ -1,9 +1,81 @@
 @chapter Syntax
 @c man begin SYNTAX
 
-When evaluating specific formats, FFmpeg uses internal library parsing
-functions, shared by the tools. This section documents the syntax of
-some of these formats.
+This section documents the syntax and formats employed by the FFmpeg
+libraries and tools.
+
+@anchor{quoting_and_escaping}
+@section Quoting and escaping
+
+FFmpeg adopts the following quoting and escaping mechanism, unless
+explicitly specified. The following rules are applied:
+
+@itemize
+@item
+@code{'} and @code{\} are special characters (respectively used for
+quoting and escaping). In addition to them, there might be other
+special characters depending on the specific syntax where the escaping
+and quoting are employed.
+
+@item
+A special character is escaped by prefixing it with a '\'.
+
+@item
+All characters enclosed between '' are included literally in the
+parsed string. The quote character @code{'} itself cannot be quoted,
+so you may need to close the quote and escape it.
+
+@item
+Leading and trailing whitespaces, unless escaped or quoted, are
+removed from the parsed string.
+@end itemize
+
+Note that you may need to add a second level of escaping when using
+the command line or a script, which depends on the syntax of the
+adopted shell language.
+
+The function @code{av_get_token} defined in
+@file{libavutil/avstring.h} can be used to parse a token quoted or
+escaped according to the rules defined above.
+
+The tool @file{tools/ffescape} in the FFmpeg source tree can be used
+to automatically quote or escape a string in a script.
+
+@subsection Examples
+
+@itemize
+@item
+Escape the string @code{Crime d'Amour} containing the @code{'} special
+character:
+@example
+Crime d\'Amour
+@end example
+
+@item
+The string above contains a quote, so the @code{'} needs to be escaped
+when quoting it:
+@example
+'Crime d'\''Amour'
+@end example
+
+@item
+Include leading or trailing whitespaces using quoting:
+@example
+'  this string starts and ends with whitespaces  '
+@end example
+
+@item
+Escaping and quoting can be mixed together:
+@example
+' The string '\'string\'' is a string '
+@end example
+
+@item
+To include a literal @code{\} you can use either escaping or quoting:
+@example
+'c:\foo' can be written as c:\\foo
+@end example
+@end itemize
 
 @anchor{date syntax}
 @section Date
diff --git a/doc/t2h.init b/doc/t2h.init
index 1eb6658..ec7d2a0 100644
--- a/doc/t2h.init
+++ b/doc/t2h.init
@@ -6,73 +6,135 @@
 
 $EXTRA_HEAD =
 '<link rel="icon" href="favicon.png" type="image/png" />
-<link rel="stylesheet" type="text/css" href="default.css" />
 ';
 
-$CSS_LINES = <<EOT;
+$CSS_LINES = $ENV{"FFMPEG_CSS"} || <<EOT;
 <style type="text/css">
 <!--
-a.summary-letter { text-decoration: none }
-a { color: #2D6198; }
-a:visited { color: #884488; }
-h1 a, h2 a, h3 a { text-decoration: inherit; color: inherit; }
-p { margin-left: 1em; margin-right: 1em; }
-table { margin-left: 2em; }
-pre { margin-left: 2em; }
-#footer { text-align: center; }
-#body { margin-left: 1em; margin-right: 1em; }
-body { background-color: #313131; margin: 0; }
-
-#container {
-    background-color: white;
-    color: #202020;
-    margin-left: 1em;
-    margin-right: 1em;
+.container {
+  margin-right: auto;
+  margin-left: auto;
+  width: 1070px;
+}
+body {
+  font-size: 14px;
+  line-height: 20px;
+  color: #333333;
+  background-color: #ffffff;
+}
+a {
+  color: #0088cc;
+  text-decoration: none;
+}
+a:hover {
+  color: #005580;
+  text-decoration: underline;
+}
+p {
+  margin: 0 0 10px;
+}
+h2,
+h3,
+h4 {
+  margin: 10px 0;
+  font-family: inherit;
+  font-weight: bold;
+  line-height: 1;
+  border-color: #D6E9C6;
+  color: #468847;
+  border-style: solid;
+  border-width: 0 0 1px;
+  padding-left: 0.5em;
 }
 
+h1 a,
+h2 a,
+h3 a,
+h4 a {
+  color: inherit;
+}
 h1 {
-    background-color: #7BB37B;
-    border: 1px solid #6A996A;
-    color: #151515;
-    font-size: 1.2em;
-    padding-bottom: 0.2em;
-    padding-left: 0.4em;
-    padding-top: 0.2em;
+  font-size: 30px;
+  line-height: 40px;
 }
-
 h2 {
-    color: #313131;
-    font-size: 1.2em;
+  font-size: 20px;
+  line-height: 40px;
 }
-
 h3 {
-    color: #313131;
-    font-size: 0.8em;
-    margin-bottom: -8px;
+  font-size: 18px;
+  line-height: 40px;
+}
+code,
+pre {
+  padding: 0 3px 2px;
+  font-family: monospace;
+  font-size: 12px;
+  color: #333333;
+  border-radius: 3px;
+}
+pre {
+  display: block;
+  padding: 9.5px;
+  margin: 0 0 10px;
+  font-size: 13px;
+  line-height: 20px;
+  word-break: break-all;
+  word-wrap: break-word;
+  white-space: pre;
+  white-space: pre-wrap;
+  background-color: #f5f5f5;
+  border: 1px solid #ccc;
+  border-radius: 4px;
 }
 
-.note {
-    margin: 1em;
-    border: 1px solid #bbc9d8;
-    background-color: #dde1e1;
+code {
+  padding: 2px 4px;
+  color: #d14;
+  background-color: #f7f7f9;
+  border: 1px solid #e1e1e8;
+}
+pre code {
+  padding: 0;
+  color: inherit;
+  background-color: transparent;
+  border: 0;
+}
+.alert {
+  padding: 8px 35px 8px 14px;
+  margin-bottom: 20px;
+  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
+  background-color: #fcf8e3;
+  border: 1px solid #fbeed5;
+  border-radius: 4px;
+  color: #c09853;
 }
 
-.important {
-    margin: 1em;
-    border: 1px solid #d26767;
-    background-color: #f8e1e1;
+.alert-danger,
+.alert-error {
+  background-color: #f2dede;
+  border-color: #eed3d7;
+  color: #b94a48;
+}
+.alert-info {
+  background-color: #d9edf7;
+  border-color: #bce8f1;
+  color: #3a87ad;
 }
 
+ul.toc {
+  list-style-type: none;
+}
 -->
 </style>
 EOT
 
-my $FFMPEG_NAVBAR = $ENV{"FFMPEG_NAVBAR"} || '';
-
-$AFTER_BODY_OPEN =
-'<div id="container">' .
-"\n$FFMPEG_NAVBAR\n" .
-'<div id="body">';
+my $TEMPLATE_HEADER = $ENV{"FFMPEG_HEADER"} || <<EOT;
+<link rel="icon" href="favicon.png" type="image/png" />
+</head>
+<body>
+<div class="container">
+EOT
 
 $PRE_BODY_CLOSE = '</div></div>';
 
@@ -83,9 +145,11 @@
 sub FFmpeg_print_page_foot($$)
 {
     my $fh = shift;
-    print $fh '<div id="footer">' . "\n";
-    T2H_DEFAULT_print_page_foot($fh);
-    print $fh "</div>\n";
+    my $program_string = defined &T2H_DEFAULT_program_string ?
+        T2H_DEFAULT_program_string() : program_string();
+    print $fh '<footer class="footer pagination-right">' . "\n";
+    print $fh '<span class="label label-info">' . $program_string;
+    print $fh "</span></footer></div>\n";
 }
 
 $float = \&FFmpeg_float;
@@ -107,11 +171,11 @@
 
     if ($caption =~ /NOTE/)
     {
-        $class = "note";
+        $class = "alert alert-info";
     }
     elsif ($caption =~ /IMPORTANT/)
     {
-        $class = "important";
+        $class = "alert alert-warning";
     }
 
     return '<div class="float ' . $class . '">' . "$label\n" . $text . '</div>';
@@ -134,7 +198,7 @@
     $longtitle = "FFmpeg documentation : " . $longtitle;
 
     print $fh <<EOT;
-$DOCTYPE
+<!DOCTYPE html>
 <html>
 $Texi2HTML::THISDOC{'copying'}<!-- Created on $Texi2HTML::THISDOC{today} by $Texi2HTML::THISDOC{program} -->
 <!--
@@ -150,11 +214,7 @@
 <meta name="Generator" content="$Texi2HTML::THISDOC{program}">
 $encoding
 $CSS_LINES
-$EXTRA_HEAD
-</head>
-
-<body $BODYTEXT>
-$AFTER_BODY_OPEN
+$TEMPLATE_HEADER
 EOT
 }
 
diff --git a/doc/texi2pod.pl b/doc/texi2pod.pl
index 5e8814f..d20fac6 100755
--- a/doc/texi2pod.pl
+++ b/doc/texi2pod.pl
@@ -211,7 +211,6 @@
     s/\@TeX\{\}/TeX/g;
     s/\@pounds\{\}/\#/g;
     s/\@minus(?:\{\})?/-/g;
-    s/\\,/,/g;
 
     # Now the ones that have to be replaced by special escapes
     # (which will be turned back into text by unmunge())
@@ -269,7 +268,7 @@
         push @icstack, $ic;
         $endw = $1;
         $ic = $2;
-        $ic =~ s/\@(?:samp|strong|key|gcctabopt|option|env)/B/;
+        $ic =~ s/\@(?:samp|strong|key|gcctabopt|option|env|command)/B/;
         $ic =~ s/\@(?:code|kbd)/C/;
         $ic =~ s/\@(?:dfn|var|emph|cite|i)/I/;
         $ic =~ s/\@(?:file)/F/;
diff --git a/ffmpeg.c b/ffmpeg.c
index 8a74ad1..55b5f86 100644
--- a/ffmpeg.c
+++ b/ffmpeg.c
@@ -43,7 +43,7 @@
 #include "libswscale/swscale.h"
 #include "libswresample/swresample.h"
 #include "libavutil/opt.h"
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/parseutils.h"
 #include "libavutil/samplefmt.h"
 #include "libavutil/colorspace.h"
@@ -69,6 +69,7 @@
 # include "libavfilter/buffersink.h"
 
 #if HAVE_SYS_RESOURCE_H
+#include <sys/time.h>
 #include <sys/types.h>
 #include <sys/resource.h>
 #elif HAVE_GETPROCESSTIMES
@@ -108,7 +109,7 @@
 
 static FILE *vstats_file;
 
-static void do_video_stats(AVFormatContext *os, OutputStream *ost, int frame_size);
+static void do_video_stats(OutputStream *ost, int frame_size);
 static int64_t getutime(void);
 
 static int run_as_daemon  = 0;
@@ -378,7 +379,7 @@
 
 const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
 
-void av_noreturn exit_program(int ret)
+static void exit_program(void)
 {
     int i, j;
 
@@ -456,8 +457,6 @@
                (int) received_sigterm);
         exit (255);
     }
-
-    exit(ret);
 }
 
 void assert_avoptions(AVDictionary *m)
@@ -465,25 +464,13 @@
     AVDictionaryEntry *t;
     if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
         av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
-        exit_program(1);
+        exit(1);
     }
 }
 
-static void assert_codec_experimental(AVCodecContext *c, int encoder)
+static void abort_codec_experimental(AVCodec *c, int encoder)
 {
-    const char *codec_string = encoder ? "encoder" : "decoder";
-    AVCodec *codec;
-    if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
-        c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
-        av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
-                "results.\nAdd '-strict experimental' if you want to use it.\n",
-                codec_string, c->codec->name);
-        codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
-        if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
-            av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
-                   codec_string, codec->name);
-        exit_program(1);
-    }
+    exit(1);
 }
 
 static void update_benchmark(const char *fmt, ...)
@@ -564,7 +551,7 @@
                    avctx->codec ? avctx->codec->name : "copy");
             print_error("", a);
             if (exit_on_error)
-                exit_program(1);
+                exit(1);
         }
         *pkt = new_pkt;
 
@@ -575,17 +562,18 @@
 
     if (debug_ts) {
         av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
-                "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
+                "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
                 av_get_media_type_string(ost->st->codec->codec_type),
                 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
-                av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base)
+                av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
+                pkt->size
               );
     }
 
     ret = av_interleaved_write_frame(s, pkt);
     if (ret < 0) {
         print_error("av_interleaved_write_frame()", ret);
-        exit_program(1);
+        exit(1);
     }
 }
 
@@ -636,7 +624,7 @@
     update_benchmark(NULL);
     if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
         av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
-        exit_program(1);
+        exit(1);
     }
     update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
 
@@ -677,6 +665,8 @@
 
         /* create temporary picture */
         size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
+        if (size < 0)
+            return;
         buf  = av_malloc(size);
         if (!buf)
             return;
@@ -715,7 +705,7 @@
     if (sub->pts == AV_NOPTS_VALUE) {
         av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
         if (exit_on_error)
-            exit_program(1);
+            exit(1);
         return;
     }
 
@@ -751,7 +741,7 @@
                                                     subtitle_out_max_size, sub);
         if (subtitle_out_size < 0) {
             av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
-            exit_program(1);
+            exit(1);
         }
 
         av_init_packet(&pkt);
@@ -774,8 +764,7 @@
 
 static void do_video_out(AVFormatContext *s,
                          OutputStream *ost,
-                         AVFrame *in_picture,
-                         float quality)
+                         AVFrame *in_picture)
 {
     int ret, format_video_sync;
     AVPacket pkt;
@@ -857,6 +846,10 @@
            method. */
         enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
         enc->coded_frame->top_field_first  = in_picture->top_field_first;
+        if (enc->coded_frame->interlaced_frame)
+            enc->field_order = enc->coded_frame->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
+        else
+            enc->field_order = AV_FIELD_PROGRESSIVE;
         pkt.data   = (uint8_t *)in_picture;
         pkt.size   =  sizeof(AVPicture);
         pkt.pts    = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
@@ -879,9 +872,15 @@
                 big_picture.top_field_first = !!ost->top_field_first;
         }
 
-        /* handles same_quant here. This is not correct because it may
-           not be a global option */
-        big_picture.quality = quality;
+        if (big_picture.interlaced_frame) {
+            if (enc->codec->id == AV_CODEC_ID_MJPEG)
+                enc->field_order = big_picture.top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
+            else
+                enc->field_order = big_picture.top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
+        } else
+            enc->field_order = AV_FIELD_PROGRESSIVE;
+
+        big_picture.quality = ost->st->codec->global_quality;
         if (!enc->me_threshold)
             big_picture.pict_type = 0;
         if (ost->forced_kf_index < ost->forced_kf_count &&
@@ -894,7 +893,7 @@
         update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
         if (ret < 0) {
             av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
-            exit_program(1);
+            exit(1);
         }
 
         if (got_packet) {
@@ -934,7 +933,7 @@
   }
 
     if (vstats_filename && frame_size)
-        do_video_stats(output_files[ost->file_index]->ctx, ost, frame_size);
+        do_video_stats(ost, frame_size);
 }
 
 static double psnr(double d)
@@ -942,8 +941,7 @@
     return -10.0 * log(d) / log(10.0);
 }
 
-static void do_video_stats(AVFormatContext *os, OutputStream *ost,
-                           int frame_size)
+static void do_video_stats(OutputStream *ost, int frame_size)
 {
     AVCodecContext *enc;
     int frame_number;
@@ -954,7 +952,7 @@
         vstats_file = fopen(vstats_filename, "w");
         if (!vstats_file) {
             perror("fopen");
-            exit_program(1);
+            exit(1);
         }
     }
 
@@ -1044,9 +1042,7 @@
                 if (!ost->frame_aspect_ratio)
                     ost->st->codec->sample_aspect_ratio = picref->video->sample_aspect_ratio;
 
-                do_video_out(of->ctx, ost, filtered_frame,
-                             same_quant ? ost->last_quality :
-                                          ost->st->codec->global_quality);
+                do_video_out(of->ctx, ost, filtered_frame);
                 break;
             case AVMEDIA_TYPE_AUDIO:
                 avfilter_copy_buf_props(filtered_frame, picref);
@@ -1097,10 +1093,14 @@
     oc = output_files[0]->ctx;
 
     total_size = avio_size(oc->pb);
-    if (total_size < 0) { // FIXME improve avio_size() so it works with non seekable output too
+    if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
         total_size = avio_tell(oc->pb);
-        if (total_size < 0)
-            total_size = 0;
+    if (total_size < 0) {
+        char errbuf[128];
+        av_strerror(total_size, errbuf, sizeof(errbuf));
+        av_log(NULL, AV_LOG_VERBOSE, "Bitrate not available, "
+               "avio_tell() failed: %s\n", errbuf);
+        total_size = 0;
     }
 
     buf[0] = '\0';
@@ -1138,7 +1138,7 @@
                 for (j = 0; j < 32; j++)
                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
             }
-            if (enc->flags&CODEC_FLAG_PSNR) {
+            if ((enc->flags&CODEC_FLAG_PSNR) && (enc->coded_frame || is_last_report)) {
                 int j;
                 double error, error_sum = 0;
                 double scale, scale_sum = 0;
@@ -1287,7 +1287,7 @@
                 update_benchmark("flush %s %d.%d", desc, ost->file_index, ost->index);
                 if (ret < 0) {
                     av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
-                    exit_program(1);
+                    exit(1);
                 }
                 *size += pkt.size;
                 if (ost->logfile && enc->stats_out) {
@@ -1301,6 +1301,8 @@
                     pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
                 if (pkt.dts != AV_NOPTS_VALUE)
                     pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
+                if (pkt.duration > 0)
+                    pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
                 write_frame(os, &pkt, ost);
             }
 
@@ -1371,6 +1373,15 @@
         opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
     opkt.dts -= ost_tb_start_time;
 
+    if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
+        int duration = av_get_audio_frame_duration(ist->st->codec, pkt->size);
+        if(!duration)
+            duration = ist->st->codec->frame_size;
+        opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
+                                               (AVRational){1, ist->st->codec->sample_rate}, duration, &ist->filter_in_rescale_delta_last,
+                                               ost->st->time_base) - ost_tb_start_time;
+    }
+
     opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
     opkt.flags    = pkt->flags;
 
@@ -1397,7 +1408,6 @@
 
     write_frame(of->ctx, &opkt, ost);
     ost->st->codec->frame_number++;
-    av_free_packet(&opkt);
 }
 
 static void rate_emu_sleep(InputStream *ist)
@@ -1437,8 +1447,6 @@
 
     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
         return AVERROR(ENOMEM);
-    else
-        avcodec_get_frame_defaults(ist->decoded_frame);
     decoded_frame = ist->decoded_frame;
 
     update_benchmark(NULL);
@@ -1480,7 +1488,7 @@
             av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
                    "layout for Input Stream #%d.%d\n", ist->file_index,
                    ist->st->index);
-            exit_program(1);
+            exit(1);
         }
         decoded_frame->channel_layout = avctx->channel_layout;
 
@@ -1508,7 +1516,7 @@
                 int j;
                 if (configure_filtergraph(fg) < 0) {
                     av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
-                    exit_program(1);
+                    exit(1);
                 }
                 for (j = 0; j < fg->nb_outputs; j++) {
                     OutputStream *ost = fg->outputs[j]->ost;
@@ -1538,9 +1546,9 @@
         decoded_frame_tb   = AV_TIME_BASE_Q;
     }
     if (decoded_frame->pts != AV_NOPTS_VALUE)
-        decoded_frame->pts = av_rescale_q(decoded_frame->pts,
-                                          decoded_frame_tb,
-                                          (AVRational){1, ist->st->codec->sample_rate});
+        decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
+                                              (AVRational){1, ist->st->codec->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
+                                              (AVRational){1, ist->st->codec->sample_rate});
     for (i = 0; i < ist->nb_filters; i++)
         av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame,
                                AV_BUFFERSRC_FLAG_PUSH);
@@ -1557,12 +1565,9 @@
     int i, ret = 0, resample_changed;
     int64_t best_effort_timestamp;
     AVRational *frame_sample_aspect;
-    float quality;
 
     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
         return AVERROR(ENOMEM);
-    else
-        avcodec_get_frame_defaults(ist->decoded_frame);
     decoded_frame = ist->decoded_frame;
     pkt->dts  = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
 
@@ -1578,8 +1583,6 @@
         return ret;
     }
 
-    quality = same_quant ? decoded_frame->quality : 0;
-
     if(ist->top_field_first>=0)
         decoded_frame->top_field_first = ist->top_field_first;
 
@@ -1619,12 +1622,13 @@
         ist->resample_height  = decoded_frame->height;
         ist->resample_pix_fmt = decoded_frame->format;
 
-        for (i = 0; i < nb_filtergraphs; i++)
-            if (ist_in_filtergraph(filtergraphs[i], ist) &&
+        for (i = 0; i < nb_filtergraphs; i++) {
+            if (ist_in_filtergraph(filtergraphs[i], ist) && ist->reinit_filters &&
                 configure_filtergraph(filtergraphs[i]) < 0) {
                 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
-                exit_program(1);
+                exit(1);
             }
+        }
     }
 
     frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
@@ -1632,9 +1636,6 @@
         int changed =      ist->st->codec->width   != ist->filters[i]->filter->outputs[0]->w
                         || ist->st->codec->height  != ist->filters[i]->filter->outputs[0]->h
                         || ist->st->codec->pix_fmt != ist->filters[i]->filter->outputs[0]->format;
-        // XXX what an ugly hack
-        if (ist->filters[i]->graph->nb_outputs == 1)
-            ist->filters[i]->graph->outputs[0]->ost->last_quality = quality;
 
         if (!frame_sample_aspect->num)
             *frame_sample_aspect = ist->st->sample_aspect_ratio;
@@ -1659,7 +1660,7 @@
         } else
         if(av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame, AV_BUFFERSRC_FLAG_PUSH)<0) {
             av_log(NULL, AV_LOG_FATAL, "Failed to inject frame into filter network\n");
-            exit_program(1);
+            exit(1);
         }
 
     }
@@ -1750,7 +1751,7 @@
     if (pkt->dts != AV_NOPTS_VALUE) {
         ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
         if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
-            ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
+            ist->next_pts = ist->pts = ist->dts;
     }
 
     // while we have more to decode or while the decoder did output something on EOF
@@ -1858,7 +1859,7 @@
     AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
 
     if (!avc)
-        exit_program(1);
+        exit(1);
     for (i = 0; i < nb_output_files; i++)
         avc[i] = output_files[i]->ctx;
 
@@ -1870,6 +1871,7 @@
 
 static int init_input_stream(int ist_index, char *error, int error_len)
 {
+    int ret;
     InputStream *ist = input_streams[ist_index];
 
     if (ist->decoding_needed) {
@@ -1889,12 +1891,13 @@
 
         if (!av_dict_get(ist->opts, "threads", NULL, 0))
             av_dict_set(&ist->opts, "threads", "auto", 0);
-        if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
+        if ((ret = avcodec_open2(ist->st->codec, codec, &ist->opts)) < 0) {
+            if (ret == AVERROR_EXPERIMENTAL)
+                abort_codec_experimental(codec, 0);
             snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
                     ist->file_index, ist->st->index);
-            return AVERROR(EINVAL);
+            return ret;
         }
-        assert_codec_experimental(ist->st->codec, 0);
         assert_avoptions(ist->opts);
     }
 
@@ -1926,7 +1929,7 @@
     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");
-        exit_program(1);
+        exit(1);
     }
 
     p = kf;
@@ -2092,7 +2095,7 @@
             case AVMEDIA_TYPE_AUDIO:
                 if (audio_volume != 256) {
                     av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
-                    exit_program(1);
+                    exit(1);
                 }
                 codec->channel_layout     = icodec->channel_layout;
                 codec->sample_rate        = icodec->sample_rate;
@@ -2239,7 +2242,7 @@
                         if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
                             av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
                                    logfilename);
-                            exit_program(1);
+                            exit(1);
                         }
                         codec->stats_in = logbuffer;
                     }
@@ -2248,7 +2251,7 @@
                         if (!f) {
                             av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
                                 logfilename, strerror(errno));
-                            exit_program(1);
+                            exit(1);
                         }
                         ost->logfile = f;
                     }
@@ -2278,17 +2281,17 @@
             }
             if (!av_dict_get(ost->opts, "threads", NULL, 0))
                 av_dict_set(&ost->opts, "threads", "auto", 0);
-            if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
+            if ((ret = avcodec_open2(ost->st->codec, codec, &ost->opts)) < 0) {
+                if (ret == AVERROR_EXPERIMENTAL)
+                    abort_codec_experimental(codec, 1);
                 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);
-                ret = AVERROR(EINVAL);
                 goto dump_format;
             }
             if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
                 !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
                 av_buffersink_set_frame_size(ost->filter->filter,
                                              ost->st->codec->frame_size);
-            assert_codec_experimental(ost->st->codec, 1);
             assert_avoptions(ost->opts);
             if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
                 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
@@ -2415,10 +2418,7 @@
     return 0;
 }
 
-/**
- * @return 1 if there are still streams where more output is wanted,
- *         0 otherwise
- */
+/* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
 static int need_output(void)
 {
     int i;
@@ -2697,8 +2697,8 @@
         output_streams[i]->unavailable = 0;
 }
 
-/**
- * @return
+/*
+ * Return
  * - 0 -- one packet was read and processed
  * - AVERROR(EAGAIN) -- no packets were available for selected file,
  *   this function should be called again
@@ -2723,7 +2723,7 @@
         if (ret != AVERROR_EOF) {
             print_error(is->filename, ret);
             if (exit_on_error)
-                exit_program(1);
+                exit(1);
         }
         ifile->eof_reached = 1;
 
@@ -2762,9 +2762,41 @@
     if (ist->discard)
         goto discard_packet;
 
-    if(!ist->wrap_correction_done && input_files[file_index]->ctx->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
-        int64_t stime = av_rescale_q(input_files[file_index]->ctx->start_time, AV_TIME_BASE_Q, ist->st->time_base);
-        int64_t stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
+    if (debug_ts) {
+        av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
+               "next_dts:%s next_dts_time:%s next_pts:%s next_pts_time:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",
+               ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
+               av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
+               av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
+               av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
+               av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
+               av_ts2str(input_files[ist->file_index]->ts_offset),
+               av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
+    }
+
+    if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
+        int64_t stime, stime2;
+        // Correcting starttime based on the enabled streams
+        // FIXME this ideally should be done before the first use of starttime but we do not know which are the enabled streams at that point.
+        //       so we instead do it here as part of discontinuity handling
+        if (   ist->next_dts == AV_NOPTS_VALUE
+            && ifile->ts_offset == -is->start_time
+            && (is->iformat->flags & AVFMT_TS_DISCONT)) {
+            int64_t new_start_time = INT64_MAX;
+            for (i=0; i<is->nb_streams; i++) {
+                AVStream *st = is->streams[i];
+                if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
+                    continue;
+                new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
+            }
+            if (new_start_time > is->start_time) {
+                av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
+                ifile->ts_offset = -new_start_time;
+            }
+        }
+
+        stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
+        stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
         ist->wrap_correction_done = 1;
 
         if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
@@ -2787,17 +2819,6 @@
     if (pkt.dts != AV_NOPTS_VALUE)
         pkt.dts *= ist->ts_scale;
 
-    if (debug_ts) {
-        av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
-                "next_dts:%s next_dts_time:%s next_pts:%s next_pts_time:%s  pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%"PRId64"\n",
-                ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
-                av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
-                av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
-                av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
-                av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
-                input_files[ist->file_index]->ts_offset);
-    }
-
     if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
         !copy_ts) {
         int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
@@ -2835,6 +2856,15 @@
         }
     }
 
+    if (debug_ts) {
+        av_log(NULL, AV_LOG_INFO, "demuxer+ffmpeg -> ist_index:%d type:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",
+               ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
+               av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
+               av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
+               av_ts2str(input_files[ist->file_index]->ts_offset),
+               av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
+    }
+
     sub2video_heartbeat(ist, pkt.pts);
 
     ret = output_packet(ist, &pkt);
@@ -2844,7 +2874,7 @@
         av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
                 ist->file_index, ist->st->index, buf);
         if (exit_on_error)
-            exit_program(1);
+            exit(1);
     }
 
 discard_packet:
@@ -3118,6 +3148,8 @@
     OptionsContext o = { 0 };
     int64_t ti;
 
+    atexit(exit_program);
+
     reset_options(&o, 0);
 
     setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
@@ -3152,29 +3184,29 @@
     if (nb_output_files <= 0 && nb_input_files == 0) {
         show_usage();
         av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
-        exit_program(1);
+        exit(1);
     }
 
     /* file converter / grab */
     if (nb_output_files <= 0) {
         av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
-        exit_program(1);
+        exit(1);
     }
 
 //     if (nb_input_files == 0) {
 //         av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
-//         exit_program(1);
+//         exit(1);
 //     }
 
     current_time = ti = getutime();
     if (transcode() < 0)
-        exit_program(1);
+        exit(1);
     ti = getutime() - ti;
     if (do_benchmark) {
         int maxrss = getmaxrss() / 1024;
         printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
     }
 
-    exit_program(0);
+    exit(0);
     return 0;
 }
diff --git a/ffmpeg.h b/ffmpeg.h
index 56f8dfc..d260222 100644
--- a/ffmpeg.h
+++ b/ffmpeg.h
@@ -57,12 +57,12 @@
 
 /* select an input stream for an output stream */
 typedef struct StreamMap {
-    int disabled;           /** 1 is this mapping is disabled by a negative map */
+    int disabled;           /* 1 is this mapping is disabled by a negative map */
     int file_index;
     int stream_index;
     int sync_file_index;
     int sync_stream_index;
-    char *linklabel;       /** name of an output link, for mapping lavfi outputs */
+    char *linklabel;       /* name of an output link, for mapping lavfi outputs */
 } StreamMap;
 
 typedef struct {
@@ -161,6 +161,8 @@
     int        nb_copy_prior_start;
     SpecifierOpt *filters;
     int        nb_filters;
+    SpecifierOpt *reinit_filters;
+    int        nb_reinit_filters;
     SpecifierOpt *fix_sub_duration;
     int        nb_fix_sub_duration;
     SpecifierOpt *pass;
@@ -215,6 +217,9 @@
     int64_t       next_pts;  ///< synthetic pts for the next decode frame (in AV_TIME_BASE units)
     int64_t       pts;       ///< current pts of the decoded frame  (in AV_TIME_BASE units)
     int           wrap_correction_done;
+
+    int64_t filter_in_rescale_delta_last;
+
     double ts_scale;
     int is_start;            /* is 1 at the start and after a discontinuity */
     int saw_first_ts;
@@ -253,6 +258,8 @@
      * currently video and audio only */
     InputFilter **filters;
     int        nb_filters;
+
+    int reinit_filters;
 } InputStream;
 
 typedef struct InputFile {
@@ -301,7 +308,6 @@
     int top_field_first;
 
     float frame_aspect_ratio;
-    float last_quality;
 
     /* forced key frames */
     int64_t *forced_kf_pts;
@@ -320,6 +326,7 @@
     char *avfilter;
 
     int64_t sws_flags;
+    int64_t swr_filter_type;
     int64_t swr_dither_method;
     double swr_dither_scale;
     AVDictionary *opts;
@@ -377,7 +384,6 @@
 extern int exit_on_error;
 extern int print_stats;
 extern int qp_hist;
-extern int same_quant;
 extern int stdin_interaction;
 extern int frame_bits_per_raw_sample;
 extern AVIOContext *progress_avio;
@@ -398,7 +404,7 @@
 
 int guess_input_channel_layout(InputStream *ist);
 
-enum PixelFormat choose_pixel_fmt(AVStream *st, AVCodec *codec, enum PixelFormat target);
+enum AVPixelFormat choose_pixel_fmt(AVStream *st, AVCodec *codec, enum AVPixelFormat target);
 void choose_sample_fmt(AVStream *st, AVCodec *codec);
 
 int configure_filtergraph(FilterGraph *fg);
diff --git a/ffmpeg_filter.c b/ffmpeg_filter.c
index 8478edf..5e37128 100644
--- a/ffmpeg_filter.c
+++ b/ffmpeg_filter.c
@@ -24,41 +24,43 @@
 #include "libavfilter/avfiltergraph.h"
 #include "libavfilter/buffersink.h"
 
-#include "libavutil/audioconvert.h"
 #include "libavutil/avassert.h"
 #include "libavutil/avstring.h"
 #include "libavutil/bprint.h"
+#include "libavutil/channel_layout.h"
+#include "libavutil/opt.h"
 #include "libavutil/pixdesc.h"
 #include "libavutil/pixfmt.h"
 #include "libavutil/imgutils.h"
 #include "libavutil/samplefmt.h"
 
-enum PixelFormat choose_pixel_fmt(AVStream *st, AVCodec *codec, enum PixelFormat target)
+enum AVPixelFormat choose_pixel_fmt(AVStream *st, AVCodec *codec, enum AVPixelFormat target)
 {
     if (codec && codec->pix_fmts) {
-        const enum PixelFormat *p = codec->pix_fmts;
-        int has_alpha= av_pix_fmt_descriptors[target].nb_components % 2 == 0;
-        enum PixelFormat best= PIX_FMT_NONE;
+        const enum AVPixelFormat *p = codec->pix_fmts;
+        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(target);
+        int has_alpha = desc ? desc->nb_components % 2 == 0 : 0;
+        enum AVPixelFormat best= AV_PIX_FMT_NONE;
         if (st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
             if (st->codec->codec_id == AV_CODEC_ID_MJPEG) {
-                p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
+                p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_NONE };
             } else if (st->codec->codec_id == AV_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 };
+                p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUV420P,
+                                                 AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE };
             }
         }
-        for (; *p != PIX_FMT_NONE; p++) {
+        for (; *p != AV_PIX_FMT_NONE; p++) {
             best= avcodec_find_best_pix_fmt_of_2(best, *p, target, has_alpha, NULL);
             if (*p == target)
                 break;
         }
-        if (*p == PIX_FMT_NONE) {
-            if (target != PIX_FMT_NONE)
+        if (*p == AV_PIX_FMT_NONE) {
+            if (target != AV_PIX_FMT_NONE)
                 av_log(NULL, AV_LOG_WARNING,
                        "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
-                       av_pix_fmt_descriptors[target].name,
+                       av_get_pix_fmt_name(target),
                        codec->name,
-                       av_pix_fmt_descriptors[best].name);
+                       av_get_pix_fmt_name(best));
             return best;
         }
     }
@@ -93,32 +95,32 @@
         if (ost->filter)
             avfilter_graph_set_auto_convert(ost->filter->graph->graph,
                                             AVFILTER_AUTO_CONVERT_NONE);
-        if (ost->st->codec->pix_fmt == PIX_FMT_NONE)
+        if (ost->st->codec->pix_fmt == AV_PIX_FMT_NONE)
             return NULL;
         return av_strdup(av_get_pix_fmt_name(ost->st->codec->pix_fmt));
     }
-    if (ost->st->codec->pix_fmt != PIX_FMT_NONE) {
+    if (ost->st->codec->pix_fmt != AV_PIX_FMT_NONE) {
         return av_strdup(av_get_pix_fmt_name(choose_pixel_fmt(ost->st, ost->enc, ost->st->codec->pix_fmt)));
     } else if (ost->enc && ost->enc->pix_fmts) {
-        const enum PixelFormat *p;
+        const enum AVPixelFormat *p;
         AVIOContext *s = NULL;
         uint8_t *ret;
         int len;
 
         if (avio_open_dyn_buf(&s) < 0)
-            exit_program(1);
+            exit(1);
 
         p = ost->enc->pix_fmts;
         if (ost->st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
             if (ost->st->codec->codec_id == AV_CODEC_ID_MJPEG) {
-                p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
+                p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_NONE };
             } else if (ost->st->codec->codec_id == AV_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 };
+                p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUV420P,
+                                                    AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE };
             }
         }
 
-        for (; *p != PIX_FMT_NONE; p++) {
+        for (; *p != AV_PIX_FMT_NONE; p++) {
             const char *name = av_get_pix_fmt_name(*p);
             avio_printf(s, "%s:", name);
         }
@@ -129,10 +131,8 @@
         return NULL;
 }
 
-/**
- * Define a function for building a string containing a list of
- * allowed formats,
- */
+/* Define a function for building a string containing a list of
+ * allowed formats. */
 #define DEF_CHOOSE_FORMAT(type, var, supported_list, none, get_name, separator)\
 static char *choose_ ## var ## s(OutputStream *ost)                            \
 {                                                                              \
@@ -146,7 +146,7 @@
         int len;                                                               \
                                                                                \
         if (avio_open_dyn_buf(&s) < 0)                                         \
-            exit_program(1);                                                   \
+            exit(1);                                                           \
                                                                                \
         for (p = ost->enc->supported_list; *p != none; p++) {                  \
             get_name(*p);                                                      \
@@ -159,7 +159,7 @@
         return NULL;                                                           \
 }
 
-// DEF_CHOOSE_FORMAT(enum PixelFormat, pix_fmt, pix_fmts, PIX_FMT_NONE,
+// DEF_CHOOSE_FORMAT(enum AVPixelFormat, pix_fmt, pix_fmts, AV_PIX_FMT_NONE,
 //                   GET_PIX_FMT_NAME, ":")
 
 DEF_CHOOSE_FORMAT(enum AVSampleFormat, sample_fmt, sample_fmts,
@@ -176,13 +176,13 @@
     FilterGraph *fg = av_mallocz(sizeof(*fg));
 
     if (!fg)
-        exit_program(1);
+        exit(1);
     fg->index = nb_filtergraphs;
 
     fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs), &fg->nb_outputs,
                              fg->nb_outputs + 1);
     if (!(fg->outputs[0] = av_mallocz(sizeof(*fg->outputs[0]))))
-        exit_program(1);
+        exit(1);
     fg->outputs[0]->ost   = ost;
     fg->outputs[0]->graph = fg;
 
@@ -191,7 +191,7 @@
     fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs), &fg->nb_inputs,
                             fg->nb_inputs + 1);
     if (!(fg->inputs[0] = av_mallocz(sizeof(*fg->inputs[0]))))
-        exit_program(1);
+        exit(1);
     fg->inputs[0]->ist   = ist;
     fg->inputs[0]->graph = fg;
 
@@ -216,7 +216,7 @@
     if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {
         av_log(NULL, AV_LOG_FATAL, "Only video and audio filters supported "
                "currently.\n");
-        exit_program(1);
+        exit(1);
     }
 
     if (in->name) {
@@ -228,7 +228,7 @@
         if (file_idx < 0 || file_idx >= nb_input_files) {
             av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtergraph description %s.\n",
                    file_idx, fg->graph_desc);
-            exit_program(1);
+            exit(1);
         }
         s = input_files[file_idx]->ctx;
 
@@ -246,7 +246,7 @@
         if (!st) {
             av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
                    "matches no streams.\n", p, fg->graph_desc);
-            exit_program(1);
+            exit(1);
         }
         ist = input_streams[input_files[file_idx]->ist_index + st->index];
     } else {
@@ -260,7 +260,7 @@
             av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
                    "unlabeled input pad %d on filter %s\n", in->pad_idx,
                    in->filter_ctx->name);
-            exit_program(1);
+            exit(1);
         }
     }
     av_assert0(ist);
@@ -272,7 +272,7 @@
     fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs),
                             &fg->nb_inputs, fg->nb_inputs + 1);
     if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))
-        exit_program(1);
+        exit(1);
     fg->inputs[fg->nb_inputs - 1]->ist   = ist;
     fg->inputs[fg->nb_inputs - 1]->graph = fg;
 
@@ -477,7 +477,7 @@
     AVIOContext *pb;                                               \
                                                                    \
     if (avio_open_dyn_buf(&pb) < 0)                                \
-        exit_program(1);                                           \
+        exit(1);                                                   \
                                                                    \
     avio_printf(pb, "%s", ctx->filter->name);                      \
     if (nb_pads > 1)                                               \
@@ -526,17 +526,17 @@
     ist->sub2video.w = ist->st->codec->width  = w;
     ist->sub2video.h = ist->st->codec->height = h;
 
-    /* rectangles are PIX_FMT_PAL8, but we have no guarantee that the
+    /* rectangles are AV_PIX_FMT_PAL8, but we have no guarantee that the
        palettes for all rectangles are identical or compatible */
-    ist->st->codec->pix_fmt = PIX_FMT_RGB32;
+    ist->st->codec->pix_fmt = AV_PIX_FMT_RGB32;
 
-    ret = av_image_alloc(image, linesize, w, h, PIX_FMT_RGB32, 32);
+    ret = av_image_alloc(image, linesize, w, h, AV_PIX_FMT_RGB32, 32);
     if (ret < 0)
         return ret;
     memset(image[0], 0, h * linesize[0]);
     ist->sub2video.ref = avfilter_get_video_buffer_ref_from_arrays(
             image, linesize, AV_PERM_READ | AV_PERM_PRESERVE,
-            w, h, PIX_FMT_RGB32);
+            w, h, AV_PIX_FMT_RGB32);
     if (!ist->sub2video.ref) {
         av_free(image[0]);
         return AVERROR(ENOMEM);
@@ -560,6 +560,13 @@
     int pad_idx = in->pad_idx;
     int ret;
 
+    if (!ist->framerate.num && ist->st->codec->ticks_per_frame>1) {
+        AVRational codec_fr = av_inv_q(ist->st->codec->time_base);
+        codec_fr.den *= ist->st->codec->ticks_per_frame;
+        if(codec_fr.num>0 && codec_fr.den>0 && av_q2d(codec_fr) < av_q2d(fr)*0.7)
+            fr = codec_fr;
+    }
+
     if (ist->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
         ret = sub2video_prepare(ist);
         if (ret < 0)
@@ -718,6 +725,17 @@
         char args[255];
         snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
         fg->graph->scale_sws_opts = av_strdup(args);
+
+        args[0] = 0;
+        if (ost->swr_filter_type != SWR_FILTER_TYPE_KAISER)
+            av_strlcatf(args, sizeof(args), "filter_type=%d:", (int)ost->swr_filter_type);
+        if (ost->swr_dither_method)
+            av_strlcatf(args, sizeof(args), "dither_method=%d:", (int)ost->swr_dither_method);
+        if (ost->swr_dither_scale != 1.0)
+            av_strlcatf(args, sizeof(args), "dither_scale=%f:", ost->swr_dither_scale);
+        if (strlen(args))
+            args[strlen(args)-1] = 0;
+        av_opt_set(fg->graph, "aresample_swr_opts", args, 0);
     }
 
     if ((ret = avfilter_graph_parse2(fg->graph, graph_desc, &inputs, &outputs)) < 0)
@@ -752,7 +770,7 @@
             fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs),
                                      &fg->nb_outputs, fg->nb_outputs + 1);
             if (!(fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]))))
-                exit_program(1);
+                exit(1);
             fg->outputs[fg->nb_outputs - 1]->graph   = fg;
             fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
             cur = cur->next;
diff --git a/ffmpeg_opt.c b/ffmpeg_opt.c
index 2c5fbfb..c846a10 100644
--- a/ffmpeg_opt.c
+++ b/ffmpeg_opt.c
@@ -30,10 +30,10 @@
 #include "libavfilter/avfilter.h"
 #include "libavfilter/avfiltergraph.h"
 
-#include "libavutil/audioconvert.h"
 #include "libavutil/avassert.h"
 #include "libavutil/avstring.h"
 #include "libavutil/avutil.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "libavutil/fifo.h"
 #include "libavutil/mathematics.h"
@@ -50,7 +50,7 @@
         if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
             outvar = o->name[i].u.type;\
         else if (ret < 0)\
-            exit_program(1);\
+            exit(1);\
     }\
 }
 
@@ -83,7 +83,6 @@
 int exit_on_error     = 0;
 int print_stats       = 1;
 int qp_hist           = 0;
-int same_quant        = 0;
 int stdin_interaction = 1;
 int frame_bits_per_raw_sample = 0;
 
@@ -158,11 +157,20 @@
     return -1;
 }
 
+static int opt_sameq(void *optctx, const char *opt, const char *arg)
+{
+    av_log(NULL, AV_LOG_ERROR, "Option '%s' was removed. "
+           "If you are looking for an option to preserve the quality (which is not "
+           "what -%s was for), use -qscale 0 or an equivalent quality factor option.\n",
+           opt, opt);
+    return AVERROR(EINVAL);
+}
+
 static int opt_video_channel(void *optctx, const char *opt, const char *arg)
 {
     av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -channel.\n");
     return opt_default(optctx, "channel", arg);
-    }
+}
 
 static int opt_video_standard(void *optctx, const char *opt, const char *arg)
 {
@@ -215,7 +223,7 @@
         sync_file_idx = strtol(sync + 1, &sync, 0);
         if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
             av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
-            exit_program(1);
+            exit(1);
         }
         if (*sync)
             sync++;
@@ -228,7 +236,7 @@
         if (i == input_files[sync_file_idx]->nb_streams) {
             av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
                                        "match any streams.\n", arg);
-            exit_program(1);
+            exit(1);
         }
     }
 
@@ -242,13 +250,13 @@
         m->linklabel = av_get_token(&c, "]");
         if (!m->linklabel) {
             av_log(NULL, AV_LOG_ERROR, "Invalid output link label: %s.\n", map);
-            exit_program(1);
+            exit(1);
         }
     } else {
         file_idx = strtol(map, &p, 0);
         if (file_idx >= nb_input_files || file_idx < 0) {
             av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
-            exit_program(1);
+            exit(1);
         }
         if (negative)
             /* disable some already defined maps */
@@ -284,7 +292,7 @@
 
     if (!m) {
         av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
-        exit_program(1);
+        exit(1);
     }
 
     av_freep(&map);
@@ -329,7 +337,7 @@
     if (n != 3 && n != 5) {
         av_log(NULL, AV_LOG_FATAL, "Syntax error, mapchan usage: "
                "[file.stream.channel|-1][:syncfile:syncstream]\n");
-        exit_program(1);
+        exit(1);
     }
 
     if (n != 5) // only file.stream.channel specified
@@ -339,30 +347,31 @@
     if (m->file_idx < 0 || m->file_idx >= nb_input_files) {
         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file index: %d\n",
                m->file_idx);
-        exit_program(1);
+        exit(1);
     }
     if (m->stream_idx < 0 ||
         m->stream_idx >= input_files[m->file_idx]->nb_streams) {
         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file stream index #%d.%d\n",
                m->file_idx, m->stream_idx);
-        exit_program(1);
+        exit(1);
     }
     st = input_files[m->file_idx]->ctx->streams[m->stream_idx];
     if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
         av_log(NULL, AV_LOG_FATAL, "mapchan: stream #%d.%d is not an audio stream.\n",
                m->file_idx, m->stream_idx);
-        exit_program(1);
+        exit(1);
     }
     if (m->channel_idx < 0 || m->channel_idx >= st->codec->channels) {
         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid audio channel #%d.%d.%d\n",
                m->file_idx, m->stream_idx, m->channel_idx);
-        exit_program(1);
+        exit(1);
     }
     return 0;
 }
 
 /**
- * Parse a metadata specifier in arg.
+ * Parse a metadata specifier passed as 'arg' parameter.
+ * @param arg  metadata string to parse
  * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
  * @param index for type c/p, chapter/program index is written here
  * @param stream_spec for type s, the stream specifier is written here
@@ -377,7 +386,7 @@
         case 's':
             if (*(++arg) && *arg != ':') {
                 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
-                exit_program(1);
+                exit(1);
             }
             *stream_spec = *arg == ':' ? arg + 1 : "";
             break;
@@ -388,7 +397,7 @@
             break;
         default:
             av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
-            exit_program(1);
+            exit(1);
         }
     } else
         *type = 'g';
@@ -423,11 +432,15 @@
     if (type_in == 'c' || type_out == 'c')
         o->metadata_chapters_manual = 1;
 
+    /* ic is NULL when just disabling automatic mappings */
+    if (!ic)
+        return 0;
+
 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
     if ((index) < 0 || (index) >= (nb_elems)) {\
         av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
                 (desc), (index));\
-        exit_program(1);\
+        exit(1);\
     }
 
 #define SET_DICT(type, meta, context, index)\
@@ -443,9 +456,9 @@
             METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
             meta = &context->programs[index]->metadata;\
             break;\
-        default: av_assert0(0);\
         case 's':\
-            break;\
+            break; /* handled separately below */ \
+        default: av_assert0(0);\
         }\
 
     SET_DICT(type_in, meta_in, ic, idx_in);
@@ -458,11 +471,11 @@
                 meta_in = &ic->streams[i]->metadata;
                 break;
             } else if (ret < 0)
-                exit_program(1);
+                exit(1);
         }
         if (!meta_in) {
             av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match  any streams.\n", istream_spec);
-            exit_program(1);
+            exit(1);
         }
     }
 
@@ -472,7 +485,7 @@
                 meta_out = &oc->streams[i]->metadata;
                 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
             } else if (ret < 0)
-                exit_program(1);
+                exit(1);
         }
     } else
         av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
@@ -514,11 +527,11 @@
 
     if (!codec) {
         av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
-        exit_program(1);
+        exit(1);
     }
     if (codec->type != type) {
         av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
-        exit_program(1);
+        exit(1);
     }
     return codec;
 }
@@ -536,10 +549,8 @@
         return avcodec_find_decoder(st->codec->codec_id);
 }
 
-/**
- * Add all the streams from the given input file to the global
- * list of input streams.
- */
+/* Add all the streams from the given input file to the global
+ * list of input streams. */
 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
 {
     int i;
@@ -552,7 +563,7 @@
         char *framerate = NULL;
 
         if (!ist)
-            exit_program(1);
+            exit(1);
 
         input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
         input_streams[nb_input_streams - 1] = ist;
@@ -576,6 +587,11 @@
 
         ist->dec = choose_decoder(o, ic, st);
 
+        ist->reinit_filters = -1;
+        MATCH_PER_STREAM_OPT(reinit_filters, i, ist->reinit_filters, ic, st);
+
+        ist->filter_in_rescale_delta_last = AV_NOPTS_VALUE;
+
         switch (dec->codec_type) {
         case AVMEDIA_TYPE_VIDEO:
             if(!ist->dec)
@@ -593,7 +609,7 @@
                                                  framerate) < 0) {
                 av_log(NULL, AV_LOG_ERROR, "Error parsing framerate %s.\n",
                        framerate);
-                exit_program(1);
+                exit(1);
             }
 
             ist->top_field_first = -1;
@@ -637,13 +653,13 @@
                 signal(SIGINT, SIG_DFL);
                 if (!read_yesno()) {
                     av_log(NULL, AV_LOG_FATAL, "Not overwriting - exiting\n");
-                    exit_program(1);
+                    exit(1);
                 }
                 term_init();
             }
             else {
                 av_log(NULL, AV_LOG_FATAL, "File '%s' already exists. Exiting.\n", filename);
-                exit_program(1);
+                exit(1);
             }
         }
     }
@@ -665,7 +681,7 @@
     if (!*filename) {
         av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
                "in stream #%d:%d.\n", nb_input_files - 1, st->index);
-        exit_program(1);
+        exit(1);
     }
 
     assert_file_overwrite(filename);
@@ -673,7 +689,7 @@
     if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
         av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
                filename);
-        exit_program(1);
+        exit(1);
     }
 
     avio_write(out, st->codec->extradata, st->codec->extradata_size);
@@ -698,7 +714,7 @@
     if (o->format) {
         if (!(file_iformat = av_find_input_format(o->format))) {
             av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
-            exit_program(1);
+            exit(1);
         }
     }
 
@@ -712,7 +728,7 @@
     ic = avformat_alloc_context();
     if (!ic) {
         print_error(filename, AVERROR(ENOMEM));
-        exit_program(1);
+        exit(1);
     }
     if (o->nb_audio_sample_rate) {
         snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
@@ -763,7 +779,7 @@
     err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
     if (err < 0) {
         print_error(filename, err);
-        exit_program(1);
+        exit(1);
     }
     assert_avoptions(format_opts);
 
@@ -781,7 +797,7 @@
     if (ret < 0) {
         av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
         avformat_close_input(&ic);
-        exit_program(1);
+        exit(1);
     }
 
     timestamp = o->start_time;
@@ -791,7 +807,7 @@
 
     /* if seeking requested, we execute it */
     if (o->start_time != 0) {
-        ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
+        ret = avformat_seek_file(ic, -1, INT64_MIN, timestamp, timestamp, 0);
         if (ret < 0) {
             av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
                    filename, (double)timestamp / AV_TIME_BASE);
@@ -806,7 +822,7 @@
 
     input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
     if (!(input_files[nb_input_files - 1] = av_mallocz(sizeof(*input_files[0]))))
-        exit_program(1);
+        exit(1);
 
     input_files[nb_input_files - 1]->ctx        = ic;
     input_files[nb_input_files - 1]->ist_index  = nb_input_streams - ic->nb_streams;
@@ -841,7 +857,7 @@
 
     if (avio_open_dyn_buf(&line) < 0) {
         av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
-        exit_program(1);
+        exit(1);
     }
 
     while ((c = avio_r8(s)) && c != '\n')
@@ -903,12 +919,10 @@
     char *bsf = NULL, *next, *codec_tag = NULL;
     AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
     double qscale = -1;
-    char *buf = NULL, *arg = NULL, *preset = NULL;
-    AVIOContext *s = NULL;
 
     if (!st) {
         av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
-        exit_program(1);
+        exit(1);
     }
 
     if (oc->nb_streams - 1 < o->nb_streamid_map)
@@ -917,7 +931,7 @@
     output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
                                 nb_output_streams + 1);
     if (!(ost = av_mallocz(sizeof(*ost))))
-        exit_program(1);
+        exit(1);
     output_streams[nb_output_streams - 1] = ost;
 
     ost->file_index = nb_output_files;
@@ -926,37 +940,40 @@
     st->codec->codec_type = type;
     choose_encoder(o, oc, ost);
     if (ost->enc) {
+        AVIOContext *s = NULL;
+        char *buf = NULL, *arg = NULL, *preset = NULL;
+
         ost->opts  = filter_codec_opts(codec_opts, ost->enc->id, oc, st, ost->enc);
+
+        MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
+        if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
+            do  {
+                buf = get_line(s);
+                if (!buf[0] || buf[0] == '#') {
+                    av_free(buf);
+                    continue;
+                }
+                if (!(arg = strchr(buf, '='))) {
+                    av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
+                    exit(1);
+                }
+                *arg++ = 0;
+                av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
+                av_free(buf);
+            } while (!s->eof_reached);
+            avio_close(s);
+        }
+        if (ret) {
+            av_log(NULL, AV_LOG_FATAL,
+                   "Preset %s specified for stream %d:%d, but could not be opened.\n",
+                   preset, ost->file_index, ost->index);
+            exit(1);
+        }
     }
 
     avcodec_get_context_defaults3(st->codec, ost->enc);
     st->codec->codec_type = type; // XXX hack, avcodec_get_context_defaults2() sets type to unknown for stream copy
 
-    MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
-    if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
-        do  {
-            buf = get_line(s);
-            if (!buf[0] || buf[0] == '#') {
-                av_free(buf);
-                continue;
-            }
-            if (!(arg = strchr(buf, '='))) {
-                av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
-                exit_program(1);
-            }
-            *arg++ = 0;
-            av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
-            av_free(buf);
-        } while (!s->eof_reached);
-        avio_close(s);
-    }
-    if (ret) {
-        av_log(NULL, AV_LOG_FATAL,
-               "Preset %s specified for stream %d:%d, but could not be opened.\n",
-               preset, ost->file_index, ost->index);
-        exit_program(1);
-    }
-
     ost->max_frames = INT64_MAX;
     MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
 
@@ -969,7 +986,7 @@
             *next++ = 0;
         if (!(bsfc = av_bitstream_filter_init(bsf))) {
             av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);
-            exit_program(1);
+            exit(1);
         }
         if (bsfc_prev)
             bsfc_prev->next = bsfc;
@@ -989,7 +1006,7 @@
     }
 
     MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
-    if (qscale >= 0 || same_quant) {
+    if (qscale >= 0) {
         st->codec->flags |= CODEC_FLAG_QSCALE;
         st->codec->global_quality = FF_QP2LAMBDA * qscale;
     }
@@ -998,6 +1015,7 @@
         st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
 
     av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
+    av_opt_get_int   (swr_opts, "filter_type"  , 0, &ost->swr_filter_type);
     av_opt_get_int   (swr_opts, "dither_method", 0, &ost->swr_dither_method);
     av_opt_get_double(swr_opts, "dither_scale" , 0, &ost->swr_dither_scale);
 
@@ -1022,7 +1040,7 @@
         p = strchr(p, ',');
         if (!p) {
             av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
-            exit_program(1);
+            exit(1);
         }
         p++;
     }
@@ -1042,7 +1060,7 @@
     MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
     if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
         av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
-        exit_program(1);
+        exit(1);
     }
 
     if (!ost->stream_copy) {
@@ -1057,7 +1075,7 @@
         MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
         if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
             av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
-            exit_program(1);
+            exit(1);
         }
 
         MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
@@ -1066,7 +1084,7 @@
             if (av_parse_ratio(&q, frame_aspect_ratio, 255, 0, NULL) < 0 ||
                 q.num <= 0 || q.den <= 0) {
                 av_log(NULL, AV_LOG_FATAL, "Invalid aspect ratio: %s\n", frame_aspect_ratio);
-                exit_program(1);
+                exit(1);
             }
             ost->frame_aspect_ratio = av_q2d(q);
         }
@@ -1078,9 +1096,9 @@
             if (!*++frame_pix_fmt)
                 frame_pix_fmt = NULL;
         }
-        if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
+        if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == AV_PIX_FMT_NONE) {
             av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
-            exit_program(1);
+            exit(1);
         }
         st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
 
@@ -1090,7 +1108,7 @@
         if (intra_matrix) {
             if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
                 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
-                exit_program(1);
+                exit(1);
             }
             parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
         }
@@ -1098,7 +1116,7 @@
         if (inter_matrix) {
             if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
                 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
-                exit_program(1);
+                exit(1);
             }
             parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
         }
@@ -1109,7 +1127,7 @@
             int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
             if (e != 3) {
                 av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
-                exit_program(1);
+                exit(1);
             }
             /* FIXME realloc failure */
             video_enc->rc_override =
@@ -1150,7 +1168,7 @@
         MATCH_PER_STREAM_OPT(passlogfiles, str, ost->logfile_prefix, oc, st);
         if (ost->logfile_prefix &&
             !(ost->logfile_prefix = av_strdup(ost->logfile_prefix)))
-            exit_program(1);
+            exit(1);
 
         MATCH_PER_STREAM_OPT(forced_key_frames, str, ost->forced_keyframes, oc, st);
         if (ost->forced_keyframes)
@@ -1193,7 +1211,7 @@
         if (sample_fmt &&
             (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
             av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
-            exit_program(1);
+            exit(1);
         }
 
         MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
@@ -1229,7 +1247,7 @@
     ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA, source_index);
     if (!ost->stream_copy) {
         av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
-        exit_program(1);
+        exit(1);
     }
 
     return ost;
@@ -1262,7 +1280,7 @@
         MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
         if (frame_size && av_parse_video_size(&subtitle_enc->width, &subtitle_enc->height, frame_size) < 0) {
             av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
-            exit_program(1);
+            exit(1);
         }
     }
 
@@ -1283,7 +1301,7 @@
         av_log(NULL, AV_LOG_FATAL,
                "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
                arg, opt);
-        exit_program(1);
+        exit(1);
     }
     *p++ = '\0';
     idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
@@ -1296,8 +1314,14 @@
 {
     AVFormatContext *is = ifile->ctx;
     AVFormatContext *os = ofile->ctx;
+    AVChapter **tmp;
     int i;
 
+    tmp = av_realloc_f(os->chapters, is->nb_chapters + os->nb_chapters, sizeof(*os->chapters));
+    if (!tmp)
+        return AVERROR(ENOMEM);
+    os->chapters = tmp;
+
     for (i = 0; i < is->nb_chapters; i++) {
         AVChapter *in_ch = is->chapters[i], *out_ch;
         int64_t ts_off   = av_rescale_q(ofile->start_time - ifile->ts_offset,
@@ -1323,11 +1347,7 @@
         if (copy_metadata)
             av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
 
-        os->nb_chapters++;
-        os->chapters = av_realloc_f(os->chapters, os->nb_chapters, sizeof(AVChapter));
-        if (!os->chapters)
-            return AVERROR(ENOMEM);
-        os->chapters[os->nb_chapters - 1] = out_ch;
+        os->chapters[os->nb_chapters++] = out_ch;
     }
     return 0;
 }
@@ -1368,8 +1388,11 @@
             choose_pixel_fmt(st, codec, st->codec->pix_fmt);
     }
 
+    /* ffserver seeking with date=... needs a date reference */
+    err = parse_option(o, "metadata", "creation_time=now", options);
+
     avformat_close_input(&ic);
-    return 0;
+    return err;
 }
 
 static void init_output_filter(OutputFilter *ofilter, OptionsContext *o,
@@ -1384,7 +1407,7 @@
     default:
         av_log(NULL, AV_LOG_FATAL, "Only video and audio filters are supported "
                "currently.\n");
-        exit_program(1);
+        exit(1);
     }
 
     ost->source_index = -1;
@@ -1396,12 +1419,12 @@
         av_log(NULL, AV_LOG_ERROR, "Streamcopy requested for output stream %d:%d, "
                "which is fed from a complex filtergraph. Filtering and streamcopy "
                "cannot be used together.\n", ost->file_index, ost->index);
-        exit_program(1);
+        exit(1);
     }
 
     if (configure_output_filter(ofilter->graph, ofilter, ofilter->out_tmp) < 0) {
         av_log(NULL, AV_LOG_FATAL, "Error configuring filter.\n");
-        exit_program(1);
+        exit(1);
     }
     avfilter_inout_free(&ofilter->out_tmp);
 }
@@ -1428,7 +1451,7 @@
 
     if (configure_complex_filters() < 0) {
         av_log(NULL, AV_LOG_FATAL, "Error configuring filters.\n");
-        exit_program(1);
+        exit(1);
     }
 
     if (!strcmp(filename, "-"))
@@ -1437,7 +1460,7 @@
     err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
     if (!oc) {
         print_error(filename, err);
-        exit_program(1);
+        exit(1);
     }
     file_oformat= oc->oformat;
     oc->interrupt_callback = int_cb;
@@ -1469,7 +1492,7 @@
         int err = read_ffserver_streams(o, oc, filename);
         if (err < 0) {
             print_error(filename, err);
-            exit_program(1);
+            exit(1);
         }
         for(j = nb_output_streams - oc->nb_streams; j < nb_output_streams; j++) {
             ost = output_streams[j];
@@ -1487,7 +1510,7 @@
             }
             if(!ost->sync_ist){
                 av_log(NULL, AV_LOG_FATAL, "Missing %s stream which is required by this ffm\n", av_get_media_type_string(ost->st->codec->codec_type));
-                exit_program(1);
+                exit(1);
             }
         }
     } else if (!o->nb_stream_maps) {
@@ -1568,7 +1591,7 @@
                 if (!ofilter) {
                     av_log(NULL, AV_LOG_FATAL, "Output with label '%s' does not exist "
                            "in any defined filter graph.\n", map->linklabel);
-                    exit_program(1);
+                    exit(1);
                 }
                 init_output_filter(ofilter, o, oc);
             } else {
@@ -1591,7 +1614,7 @@
                 default:
                     av_log(NULL, AV_LOG_FATAL, "Cannot map stream #%d:%d - unsupported type.\n",
                            map->file_index, map->stream_index);
-                    exit_program(1);
+                    exit(1);
                 }
             }
         }
@@ -1606,7 +1629,7 @@
             && (e = av_dict_get(codec_opts, "flags", NULL, AV_DICT_IGNORE_SUFFIX))
             && (!e->key[5] || check_stream_specifier(oc, ost->st, e->key+6)))
             if (av_opt_set(ost->st->codec, "flags", e->value, 0) < 0)
-                exit_program(1);
+                exit(1);
     }
 
     /* handle attached files */
@@ -1619,17 +1642,17 @@
         if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
             av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
                    o->attachments[i]);
-            exit_program(1);
+            exit(1);
         }
         if ((len = avio_size(pb)) <= 0) {
             av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
                    o->attachments[i]);
-            exit_program(1);
+            exit(1);
         }
         if (!(attachment = av_malloc(len))) {
             av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",
                    o->attachments[i]);
-            exit_program(1);
+            exit(1);
         }
         avio_read(pb, attachment, len);
 
@@ -1646,7 +1669,7 @@
 
     output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);
     if (!(output_files[nb_output_files - 1] = av_mallocz(sizeof(*output_files[0]))))
-        exit_program(1);
+        exit(1);
 
     output_files[nb_output_files - 1]->ctx            = oc;
     output_files[nb_output_files - 1]->ost_index      = nb_output_streams - oc->nb_streams;
@@ -1662,7 +1685,7 @@
     if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
         if (!av_filename_number_test(oc->filename)) {
             print_error(oc->filename, AVERROR(EINVAL));
-            exit_program(1);
+            exit(1);
         }
     }
 
@@ -1675,7 +1698,7 @@
                               &oc->interrupt_callback,
                               &output_files[nb_output_files - 1]->opts)) < 0) {
             print_error(filename, err);
-            exit_program(1);
+            exit(1);
         }
     }
 
@@ -1693,9 +1716,11 @@
 
         if (in_file_index >= nb_input_files) {
             av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);
-            exit_program(1);
+            exit(1);
         }
-        copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc, in_file_index >= 0 ? input_files[in_file_index]->ctx : NULL, o);
+        copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc,
+                      in_file_index >= 0 ?
+                      input_files[in_file_index]->ctx : NULL, o);
     }
 
     /* copy chapters */
@@ -1711,7 +1736,7 @@
         } else {
             av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
                    o->chapters_input_file);
-            exit_program(1);
+            exit(1);
         }
     }
     if (o->chapters_input_file >= 0)
@@ -1746,7 +1771,7 @@
         if (!val) {
             av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
                    o->metadata[i].u.str);
-            exit_program(1);
+            exit(1);
         }
         *val++ = 0;
 
@@ -1756,7 +1781,7 @@
                 if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
                     av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
                 } else if (ret < 0)
-                    exit_program(1);
+                    exit(1);
             }
         }
         else {
@@ -1767,13 +1792,13 @@
             case 'c':
                 if (index < 0 || index >= oc->nb_chapters) {
                     av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
-                    exit_program(1);
+                    exit(1);
                 }
                 m = &oc->chapters[index]->metadata;
                 break;
             default:
                 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
-                exit_program(1);
+                exit(1);
             }
             av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
         }
@@ -1827,7 +1852,7 @@
         av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
         av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
         av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
-        exit_program(1);
+        exit(1);
     }
 
     if (!strcmp(arg, "vcd")) {
@@ -1972,7 +1997,7 @@
             av_log(NULL, AV_LOG_FATAL, "Please use -preset <speed> -qp 0\n");
         }else
             av_log(NULL, AV_LOG_FATAL, "File for preset '%s' not found\n", arg);
-        exit_program(1);
+        exit(1);
 }
 
     while (fgets(line, sizeof(line), f)) {
@@ -1984,7 +2009,7 @@
         if (!av_strtok(key,   "=",    &value) ||
             !av_strtok(value, "\r\n", &endptr)) {
             av_log(NULL, AV_LOG_FATAL, "%s: Invalid syntax: '%s'\n", filename, line);
-            exit_program(1);
+            exit(1);
         }
         av_log(NULL, AV_LOG_DEBUG, "ffpreset[%s]: set '%s' = '%s'\n", filename, key, value);
 
@@ -1995,7 +2020,7 @@
         else if (opt_default(NULL, key, value) < 0) {
             av_log(NULL, AV_LOG_FATAL, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n",
                    filename, line, key, value);
-            exit_program(1);
+            exit(1);
         }
     }
 
@@ -2150,7 +2175,7 @@
     const int per_file = OPT_SPEC | OPT_OFFSET | OPT_PERFILE;
     int show_advanced = 0, show_avoptions = 0;
 
-    if (opt) {
+    if (opt && *opt) {
         if (!strcmp(opt, "long"))
             show_advanced = 1;
         else if (!strcmp(opt, "full"))
@@ -2227,7 +2252,7 @@
         arg = "pipe:";
     ret = avio_open2(&avio, arg, AVIO_FLAG_WRITE, &int_cb, NULL);
     if (ret < 0) {
-        av_log(0, AV_LOG_ERROR, "Failed to open progress URL \"%s\": %s\n",
+        av_log(NULL, AV_LOG_ERROR, "Failed to open progress URL \"%s\": %s\n",
                arg, av_err2str(ret));
         return ret;
     }
@@ -2333,6 +2358,8 @@
         "set profile", "profile" },
     { "filter",         HAS_ARG | OPT_STRING | OPT_SPEC,             { .off = OFFSET(filters) },
         "set stream filterchain", "filter_list" },
+    { "reinit_filter",  HAS_ARG | OPT_INT | OPT_SPEC,                { .off = OFFSET(reinit_filters) },
+        "reinit filtergraph on input parameter changes", "" },
     { "filter_complex", HAS_ARG | OPT_EXPERT,                        { .func_arg = opt_filter_complex },
         "create a complex filtergraph", "graph_description" },
     { "stats",          OPT_BOOL,                                    { &print_stats },
@@ -2385,10 +2412,10 @@
         "rate control override for specific intervals", "override" },
     { "vcodec",       OPT_VIDEO | HAS_ARG  | OPT_PERFILE,                        { .func_arg = opt_video_codec },
         "force video codec ('copy' to copy stream)", "codec" },
-    { "sameq",        OPT_VIDEO | OPT_BOOL | OPT_EXPERT ,                        { &same_quant },
-        "use same quantizer as source (implies VBR)" },
-    { "same_quant",   OPT_VIDEO | OPT_BOOL | OPT_EXPERT,                         { &same_quant },
-        "use same quantizer as source (implies VBR)" },
+    { "sameq",        OPT_VIDEO | OPT_EXPERT ,                                   { .func_arg = opt_sameq },
+        "Removed" },
+    { "same_quant",   OPT_VIDEO | OPT_EXPERT ,                                   { .func_arg = opt_sameq },
+        "Removed" },
     { "timecode",     OPT_VIDEO | HAS_ARG | OPT_PERFILE,                         { .func_arg = opt_timecode },
         "set initial TimeCode value.", "hh:mm:ss[:;.]ff" },
     { "pass",         OPT_VIDEO | HAS_ARG | OPT_SPEC | OPT_INT,                  { .off = OFFSET(pass) },
diff --git a/ffplay.c b/ffplay.c
index 2337fe0..d6b17c2 100644
--- a/ffplay.c
+++ b/ffplay.c
@@ -78,6 +78,11 @@
 /* maximum audio speed change to get correct sync */
 #define SAMPLE_CORRECTION_PERCENT_MAX 10
 
+/* external clock speed adjustment constants for realtime sources based on buffer fullness */
+#define EXTERNAL_CLOCK_SPEED_MIN  0.900
+#define EXTERNAL_CLOCK_SPEED_MAX  1.010
+#define EXTERNAL_CLOCK_SPEED_STEP 0.001
+
 /* we use about AUDIO_DIFF_AVG_NB A-V differences to make the average */
 #define AUDIO_DIFF_AVG_NB   20
 
@@ -85,13 +90,20 @@
 /* TODO: We assume that a decoded and resampled frame fits into this buffer */
 #define SAMPLE_ARRAY_SIZE (8 * 65536)
 
-static int sws_flags = SWS_BICUBIC;
+static int64_t sws_flags = SWS_BICUBIC;
+
+typedef struct MyAVPacketList {
+    AVPacket pkt;
+    struct MyAVPacketList *next;
+    int serial;
+} MyAVPacketList;
 
 typedef struct PacketQueue {
-    AVPacketList *first_pkt, *last_pkt;
+    MyAVPacketList *first_pkt, *last_pkt;
     int nb_packets;
     int size;
     int abort_request;
+    int serial;
     SDL_mutex *mutex;
     SDL_cond *cond;
 } PacketQueue;
@@ -100,14 +112,15 @@
 #define SUBPICTURE_QUEUE_SIZE 4
 
 typedef struct VideoPicture {
-    double pts;                                  ///< presentation time stamp for this picture
-    int64_t pos;                                 ///< byte position in file
+    double pts;             // presentation timestamp for this picture
+    int64_t pos;            // byte position in file
     int skip;
     SDL_Overlay *bmp;
     int width, height; /* source height & width */
     AVRational sample_aspect_ratio;
     int allocated;
     int reallocate;
+    int serial;
 
 #if CONFIG_AVFILTER
     AVFilterBufferRef *picref;
@@ -149,12 +162,15 @@
     int64_t seek_rel;
     int read_pause_return;
     AVFormatContext *ic;
+    int realtime;
 
     int audio_stream;
 
     int av_sync_type;
-    double external_clock; /* external clock base */
-    int64_t external_clock_time;
+    double external_clock;                   ///< external clock base
+    double external_clock_drift;             ///< external clock base - time (av_gettime) at which we updated external_clock
+    int64_t external_clock_time;             ///< last reference time
+    double external_clock_speed;             ///< speed of the external clock
 
     double audio_clock;
     double audio_diff_cum; /* used for AV difference average computation */
@@ -173,6 +189,7 @@
     int audio_write_buf_size;
     AVPacket audio_pkt_temp;
     AVPacket audio_pkt;
+    int audio_pkt_temp_serial;
     struct AudioParams audio_src;
     struct AudioParams audio_tgt;
     struct SwrContext *swr_ctx;
@@ -210,13 +227,14 @@
     double frame_last_returned_time;
     double frame_last_filter_delay;
     int64_t frame_last_dropped_pos;
-    double video_clock;                          ///< pts of last decoded frame / predicted pts of next decoded frame
+    double video_clock;             // pts of last decoded frame / predicted pts of next decoded frame
     int video_stream;
     AVStream *video_st;
     PacketQueue videoq;
-    double video_current_pts;                    ///< current displayed pts (different from video_clock if frame fifos are used)
-    double video_current_pts_drift;              ///< video_current_pts - time (av_gettime) at which we updated video_current_pts - used to have running video pts
-    int64_t video_current_pos;                   ///< current displayed file pos
+    double video_current_pts;       // current displayed pts (different from video_clock if frame fifos are used)
+    double video_current_pts_drift; // video_current_pts - time (av_gettime) at which we updated video_current_pts - used to have running video pts
+    int64_t video_current_pos;      // current displayed file pos
+    double max_frame_duration;      // maximum duration of a frame - above this, we consider the jump a timestamp discontinuity
     VideoPicture pictq[VIDEO_PICTURE_QUEUE_SIZE];
     int pictq_size, pictq_rindex, pictq_windex;
     SDL_mutex *pictq_mutex;
@@ -224,14 +242,15 @@
 #if !CONFIG_AVFILTER
     struct SwsContext *img_convert_ctx;
 #endif
+    SDL_Rect last_display_rect;
 
     char filename[1024];
     int width, height, xleft, ytop;
     int step;
 
 #if CONFIG_AVFILTER
-    AVFilterContext *in_video_filter;           ///< the first filter in the video chain
-    AVFilterContext *out_video_filter;          ///< the last filter in the video chain
+    AVFilterContext *in_video_filter;   // the first filter in the video chain
+    AVFilterContext *out_video_filter;  // the last filter in the video chain
     int use_dr1;
     FrameBuffer *buffer_pool;
 #endif
@@ -278,7 +297,7 @@
 static int exit_on_mousedown;
 static int loop = 1;
 static int framedrop = -1;
-static int infinite_buffer = 0;
+static int infinite_buffer = -1;
 static enum ShowMode show_mode = SHOW_MODE_NONE;
 static const char *audio_codec_name;
 static const char *subtitle_codec_name;
@@ -300,23 +319,23 @@
 
 static SDL_Surface *screen;
 
-void av_noreturn exit_program(int ret)
-{
-    exit(ret);
-}
+static int packet_queue_put(PacketQueue *q, AVPacket *pkt);
 
 static int packet_queue_put_private(PacketQueue *q, AVPacket *pkt)
 {
-    AVPacketList *pkt1;
+    MyAVPacketList *pkt1;
 
     if (q->abort_request)
        return -1;
 
-    pkt1 = av_malloc(sizeof(AVPacketList));
+    pkt1 = av_malloc(sizeof(MyAVPacketList));
     if (!pkt1)
         return -1;
     pkt1->pkt = *pkt;
     pkt1->next = NULL;
+    if (pkt == &flush_pkt)
+        q->serial++;
+    pkt1->serial = q->serial;
 
     if (!q->last_pkt)
         q->first_pkt = pkt1;
@@ -359,7 +378,7 @@
 
 static void packet_queue_flush(PacketQueue *q)
 {
-    AVPacketList *pkt, *pkt1;
+    MyAVPacketList *pkt, *pkt1;
 
     SDL_LockMutex(q->mutex);
     for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
@@ -401,9 +420,9 @@
 }
 
 /* return < 0 if aborted, 0 if no packet and > 0 if packet.  */
-static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block)
+static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block, int *serial)
 {
-    AVPacketList *pkt1;
+    MyAVPacketList *pkt1;
     int ret;
 
     SDL_LockMutex(q->mutex);
@@ -422,6 +441,8 @@
             q->nb_packets--;
             q->size -= pkt1->pkt.size + sizeof(*pkt1);
             *pkt = pkt1->pkt;
+            if (serial)
+                *serial = pkt1->serial;
             av_free(pkt1);
             ret = 1;
             break;
@@ -437,7 +458,7 @@
 }
 
 static inline void fill_rectangle(SDL_Surface *screen,
-                                  int x, int y, int w, int h, int color)
+                                  int x, int y, int w, int h, int color, int update)
 {
     SDL_Rect rect;
     rect.x = x;
@@ -445,6 +466,44 @@
     rect.w = w;
     rect.h = h;
     SDL_FillRect(screen, &rect, color);
+    if (update && w > 0 && h > 0)
+        SDL_UpdateRect(screen, x, y, w, h);
+}
+
+/* draw only the border of a rectangle */
+static void fill_border(int xleft, int ytop, int width, int height, int x, int y, int w, int h, int color, int update)
+{
+    int w1, w2, h1, h2;
+
+    /* fill the background */
+    w1 = x;
+    if (w1 < 0)
+        w1 = 0;
+    w2 = width - (x + w);
+    if (w2 < 0)
+        w2 = 0;
+    h1 = y;
+    if (h1 < 0)
+        h1 = 0;
+    h2 = height - (y + h);
+    if (h2 < 0)
+        h2 = 0;
+    fill_rectangle(screen,
+                   xleft, ytop,
+                   w1, height,
+                   color, update);
+    fill_rectangle(screen,
+                   xleft + width - w2, ytop,
+                   w2, height,
+                   color, update);
+    fill_rectangle(screen,
+                   xleft + w1, ytop,
+                   width - w1 - w2, h1,
+                   color, update);
+    fill_rectangle(screen,
+                   xleft + w1, ytop + height - h2,
+                   width - w1 - w2, h2,
+                   color, update);
 }
 
 #define ALPHA_BLEND(a, oldp, newp, s)\
@@ -747,6 +806,12 @@
         calculate_display_rect(&rect, is->xleft, is->ytop, is->width, is->height, vp);
 
         SDL_DisplayYUVOverlay(vp->bmp, &rect);
+
+        if (rect.x != is->last_display_rect.x || rect.y != is->last_display_rect.y || rect.w != is->last_display_rect.w || rect.h != is->last_display_rect.h || is->force_refresh) {
+            int bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
+            fill_border(is->xleft, is->ytop, is->width, is->height, rect.x, rect.y, rect.w, rect.h, bgcolor, 1);
+            is->last_display_rect = rect;
+        }
     }
 }
 
@@ -812,7 +877,7 @@
     if (s->show_mode == SHOW_MODE_WAVES) {
         fill_rectangle(screen,
                        s->xleft, s->ytop, s->width, s->height,
-                       bgcolor);
+                       bgcolor, 0);
 
         fgcolor = SDL_MapRGB(screen->format, 0xff, 0xff, 0xff);
 
@@ -833,7 +898,7 @@
                 }
                 fill_rectangle(screen,
                                s->xleft + x, ys, 1, y,
-                               fgcolor);
+                               fgcolor, 0);
                 i += channels;
                 if (i >= SAMPLE_ARRAY_SIZE)
                     i -= SAMPLE_ARRAY_SIZE;
@@ -846,7 +911,7 @@
             y = s->ytop + ch * h;
             fill_rectangle(screen,
                            s->xleft, y, s->width, 1,
-                           fgcolor);
+                           fgcolor, 0);
         }
         SDL_UpdateRect(screen, s->xleft, s->ytop, s->width, s->height);
     } else {
@@ -884,7 +949,7 @@
 
                 fill_rectangle(screen,
                             s->xpos, s->height-y, 1, 1,
-                            fgcolor);
+                            fgcolor, 0);
             }
         }
         SDL_UpdateRect(screen, s->xpos, s->ytop, 1, s->height);
@@ -1047,9 +1112,28 @@
 /* get the current external clock value */
 static double get_external_clock(VideoState *is)
 {
-    int64_t ti;
-    ti = av_gettime();
-    return is->external_clock + ((ti - is->external_clock_time) * 1e-6);
+    if (is->paused) {
+        return is->external_clock;
+    } else {
+        double time = av_gettime() / 1000000.0;
+        return is->external_clock_drift + time - (time - is->external_clock_time / 1000000.0) * (1.0 - is->external_clock_speed);
+    }
+}
+
+static int get_master_sync_type(VideoState *is) {
+    if (is->av_sync_type == AV_SYNC_VIDEO_MASTER) {
+        if (is->video_st)
+            return AV_SYNC_VIDEO_MASTER;
+        else
+            return AV_SYNC_AUDIO_MASTER;
+    } else if (is->av_sync_type == AV_SYNC_AUDIO_MASTER) {
+        if (is->audio_st)
+            return AV_SYNC_AUDIO_MASTER;
+        else
+            return AV_SYNC_EXTERNAL_CLOCK;
+    } else {
+        return AV_SYNC_EXTERNAL_CLOCK;
+    }
 }
 
 /* get the current master clock value */
@@ -1057,22 +1141,52 @@
 {
     double val;
 
-    if (is->av_sync_type == AV_SYNC_VIDEO_MASTER) {
-        if (is->video_st)
+    switch (get_master_sync_type(is)) {
+        case AV_SYNC_VIDEO_MASTER:
             val = get_video_clock(is);
-        else
+            break;
+        case AV_SYNC_AUDIO_MASTER:
             val = get_audio_clock(is);
-    } else if (is->av_sync_type == AV_SYNC_AUDIO_MASTER) {
-        if (is->audio_st)
-            val = get_audio_clock(is);
-        else
-            val = get_video_clock(is);
-    } else {
-        val = get_external_clock(is);
+            break;
+        default:
+            val = get_external_clock(is);
+            break;
     }
     return val;
 }
 
+static void update_external_clock_pts(VideoState *is, double pts)
+{
+   is->external_clock_time = av_gettime();
+   is->external_clock = pts;
+   is->external_clock_drift = pts - is->external_clock_time / 1000000.0;
+}
+
+static void check_external_clock_sync(VideoState *is, double pts) {
+    if (fabs(get_external_clock(is) - pts) > AV_NOSYNC_THRESHOLD) {
+        update_external_clock_pts(is, pts);
+    }
+}
+
+static void update_external_clock_speed(VideoState *is, double speed) {
+    update_external_clock_pts(is, get_external_clock(is));
+    is->external_clock_speed = speed;
+}
+
+static void check_external_clock_speed(VideoState *is) {
+   if (is->video_stream >= 0 && is->videoq.nb_packets <= MIN_FRAMES / 2 ||
+       is->audio_stream >= 0 && is->audioq.nb_packets <= MIN_FRAMES / 2) {
+       update_external_clock_speed(is, FFMAX(EXTERNAL_CLOCK_SPEED_MIN, is->external_clock_speed - EXTERNAL_CLOCK_SPEED_STEP));
+   } else if ((is->video_stream < 0 || is->videoq.nb_packets > MIN_FRAMES * 2) &&
+              (is->audio_stream < 0 || is->audioq.nb_packets > MIN_FRAMES * 2)) {
+       update_external_clock_speed(is, FFMIN(EXTERNAL_CLOCK_SPEED_MAX, is->external_clock_speed + EXTERNAL_CLOCK_SPEED_STEP));
+   } else {
+       double speed = is->external_clock_speed;
+       if (speed != 1.0)
+           update_external_clock_speed(is, speed + EXTERNAL_CLOCK_SPEED_STEP * (1.0 - speed) / fabs(1.0 - speed));
+   }
+}
+
 /* seek in the stream */
 static void stream_seek(VideoState *is, int64_t pos, int64_t rel, int seek_by_bytes)
 {
@@ -1096,6 +1210,7 @@
         }
         is->video_current_pts_drift = is->video_current_pts - av_gettime() / 1000000.0;
     }
+    update_external_clock_pts(is, get_external_clock(is));
     is->paused = !is->paused;
 }
 
@@ -1104,8 +1219,7 @@
     double sync_threshold, diff;
 
     /* update delay to follow master synchronisation source */
-    if (((is->av_sync_type == AV_SYNC_AUDIO_MASTER && is->audio_st) ||
-         is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK)) {
+    if (get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER) {
         /* if video is slave, we try to correct big delays by
            duplicating or deleting a frame */
         diff = get_video_clock(is) - get_master_clock(is);
@@ -1155,13 +1269,15 @@
     }
 }
 
-static void update_video_pts(VideoState *is, double pts, int64_t pos) {
+static void update_video_pts(VideoState *is, double pts, int64_t pos, int serial) {
     double time = av_gettime() / 1000000.0;
     /* update current video pts */
     is->video_current_pts = pts;
     is->video_current_pts_drift = is->video_current_pts - time;
     is->video_current_pos = pos;
     is->frame_last_pts = pts;
+    if (is->videoq.serial == serial)
+        check_external_clock_sync(is, is->video_current_pts);
 }
 
 /* called to display each frame */
@@ -1173,6 +1289,9 @@
 
     SubPicture *sp, *sp2;
 
+    if (!is->paused && get_master_sync_type(is) == AV_SYNC_EXTERNAL_CLOCK && is->realtime)
+        check_external_clock_speed(is);
+
     if (is->video_st) {
         if (is->force_refresh)
             pictq_prev_picture(is);
@@ -1180,7 +1299,7 @@
         if (is->pictq_size == 0) {
             SDL_LockMutex(is->pictq_mutex);
             if (is->frame_last_dropped_pts != AV_NOPTS_VALUE && is->frame_last_dropped_pts > is->frame_last_pts) {
-                update_video_pts(is, is->frame_last_dropped_pts, is->frame_last_dropped_pos);
+                update_video_pts(is, is->frame_last_dropped_pts, is->frame_last_dropped_pos, 0);
                 is->frame_last_dropped_pts = AV_NOPTS_VALUE;
             }
             SDL_UnlockMutex(is->pictq_mutex);
@@ -1200,7 +1319,7 @@
 
             /* compute nominal last_duration */
             last_duration = vp->pts - is->frame_last_pts;
-            if (last_duration > 0 && last_duration < 10.0) {
+            if (last_duration > 0 && last_duration < is->max_frame_duration) {
                 /* if duration of the last frame was sane, update last_duration in video state */
                 is->frame_last_duration = last_duration;
             }
@@ -1214,13 +1333,13 @@
                 is->frame_timer += delay * FFMAX(1, floor((time-is->frame_timer) / delay));
 
             SDL_LockMutex(is->pictq_mutex);
-            update_video_pts(is, vp->pts, vp->pos);
+            update_video_pts(is, vp->pts, vp->pos, vp->serial);
             SDL_UnlockMutex(is->pictq_mutex);
 
             if (is->pictq_size > 1) {
                 VideoPicture *nextvp = &is->pictq[(is->pictq_rindex + 1) % VIDEO_PICTURE_QUEUE_SIZE];
                 duration = nextvp->pts - vp->pts;
-                if((framedrop>0 || (framedrop && is->audio_st)) && time > is->frame_timer + duration){
+                if((framedrop>0 || (framedrop && get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER)) && time > is->frame_timer + duration){
                     is->frame_drops_late++;
                     pictq_next_picture(is);
                     goto retry;
@@ -1359,7 +1478,7 @@
     SDL_UnlockMutex(is->pictq_mutex);
 }
 
-static int queue_picture(VideoState *is, AVFrame *src_frame, double pts1, int64_t pos)
+static int queue_picture(VideoState *is, AVFrame *src_frame, double pts1, int64_t pos, int serial)
 {
     VideoPicture *vp;
     double frame_delay, pts = pts1;
@@ -1463,10 +1582,10 @@
         av_picture_copy(&pict, (AVPicture *)src_frame,
                         src_frame->format, vp->width, vp->height);
 #else
-        sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
+        av_opt_get_int(sws_opts, "sws_flags", 0, &sws_flags);
         is->img_convert_ctx = sws_getCachedContext(is->img_convert_ctx,
             vp->width, vp->height, src_frame->format, vp->width, vp->height,
-            PIX_FMT_YUV420P, sws_flags, NULL, NULL, NULL);
+            AV_PIX_FMT_YUV420P, sws_flags, NULL, NULL, NULL);
         if (is->img_convert_ctx == NULL) {
             fprintf(stderr, "Cannot initialize the conversion context\n");
             exit(1);
@@ -1480,6 +1599,7 @@
         vp->pts = pts;
         vp->pos = pos;
         vp->skip = 0;
+        vp->serial = serial;
 
         /* now we can update the picture count */
         if (++is->pictq_windex == VIDEO_PICTURE_QUEUE_SIZE)
@@ -1491,11 +1611,11 @@
     return 0;
 }
 
-static int get_video_frame(VideoState *is, AVFrame *frame, int64_t *pts, AVPacket *pkt)
+static int get_video_frame(VideoState *is, AVFrame *frame, int64_t *pts, AVPacket *pkt, int *serial)
 {
     int got_picture, i;
 
-    if (packet_queue_get(&is->videoq, pkt, 1) < 0)
+    if (packet_queue_get(&is->videoq, pkt, 1, serial) < 0)
         return -1;
 
     if (pkt->data == flush_pkt.data) {
@@ -1537,8 +1657,7 @@
             *pts = 0;
         }
 
-        if (((is->av_sync_type == AV_SYNC_AUDIO_MASTER && is->audio_st) || is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK) &&
-             (framedrop>0 || (framedrop && is->audio_st))) {
+        if (framedrop>0 || (framedrop && get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER)) {
             SDL_LockMutex(is->pictq_mutex);
             if (is->frame_last_pts != AV_NOPTS_VALUE && *pts) {
                 double clockdiff = get_video_clock(is) - get_master_clock(is);
@@ -1593,7 +1712,7 @@
             goto fail;
     }
 
-    return avfilter_graph_config(graph, NULL);
+    ret = avfilter_graph_config(graph, NULL);
 fail:
     avfilter_inout_free(&outputs);
     avfilter_inout_free(&inputs);
@@ -1602,58 +1721,56 @@
 
 static int configure_video_filters(AVFilterGraph *graph, VideoState *is, const char *vfilters)
 {
-    static const enum PixelFormat pix_fmts[] = { PIX_FMT_YUV420P, PIX_FMT_NONE };
+    static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE };
     char sws_flags_str[128];
     char buffersrc_args[256];
     int ret;
     AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
-    AVFilterContext *filt_src = NULL, *filt_out = NULL, *filt_format, *filt_crop;
+    AVFilterContext *filt_src = NULL, *filt_out = NULL, *filt_crop;
     AVCodecContext *codec = is->video_st->codec;
 
-    snprintf(sws_flags_str, sizeof(sws_flags_str), "flags=%d", sws_flags);
+    if (!buffersink_params)
+        return AVERROR(ENOMEM);
+
+    snprintf(sws_flags_str, sizeof(sws_flags_str), "flags=%"PRId64, sws_flags);
     graph->scale_sws_opts = av_strdup(sws_flags_str);
 
     snprintf(buffersrc_args, sizeof(buffersrc_args),
              "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
              codec->width, codec->height, codec->pix_fmt,
              is->video_st->time_base.num, is->video_st->time_base.den,
-             codec->sample_aspect_ratio.num, codec->sample_aspect_ratio.den);
+             codec->sample_aspect_ratio.num, FFMAX(codec->sample_aspect_ratio.den, 1));
 
     if ((ret = avfilter_graph_create_filter(&filt_src,
                                             avfilter_get_by_name("buffer"),
                                             "ffplay_buffer", buffersrc_args, NULL,
                                             graph)) < 0)
-        return ret;
+        goto fail;
 
     buffersink_params->pixel_fmts = pix_fmts;
     ret = avfilter_graph_create_filter(&filt_out,
                                        avfilter_get_by_name("ffbuffersink"),
                                        "ffplay_buffersink", NULL, buffersink_params, graph);
-    av_freep(&buffersink_params);
     if (ret < 0)
-        return ret;
+        goto fail;
 
     /* SDL YUV code is not handling odd width/height for some driver
      * combinations, therefore we crop the picture to an even width/height. */
     if ((ret = avfilter_graph_create_filter(&filt_crop,
                                             avfilter_get_by_name("crop"),
                                             "ffplay_crop", "floor(in_w/2)*2:floor(in_h/2)*2", NULL, graph)) < 0)
-        return ret;
-    if ((ret = avfilter_graph_create_filter(&filt_format,
-                                            avfilter_get_by_name("format"),
-                                            "format", "yuv420p", NULL, graph)) < 0)
-        return ret;
-    if ((ret = avfilter_link(filt_crop, 0, filt_format, 0)) < 0)
-        return ret;
-    if ((ret = avfilter_link(filt_format, 0, filt_out, 0)) < 0)
-        return ret;
+        goto fail;
+    if ((ret = avfilter_link(filt_crop, 0, filt_out, 0)) < 0)
+        goto fail;
 
     if ((ret = configure_filtergraph(graph, vfilters, filt_src, filt_crop)) < 0)
-        return ret;
+        goto fail;
 
     is->in_video_filter  = filt_src;
     is->out_video_filter = filt_out;
 
+fail:
+    av_freep(&buffersink_params);
     return ret;
 }
 
@@ -1667,6 +1784,7 @@
     int64_t pts_int = AV_NOPTS_VALUE, pos = -1;
     double pts;
     int ret;
+    int serial = 0;
 
 #if CONFIG_AVFILTER
     AVCodecContext *codec = is->video_st->codec;
@@ -1674,7 +1792,7 @@
     AVFilterContext *filt_out = NULL, *filt_in = NULL;
     int last_w = 0;
     int last_h = 0;
-    enum PixelFormat last_format = -2;
+    enum AVPixelFormat last_format = -2;
 
     if (codec->codec->capabilities & CODEC_CAP_DR1) {
         is->use_dr1 = 1;
@@ -1695,7 +1813,7 @@
         avcodec_get_frame_defaults(frame);
         av_free_packet(&pkt);
 
-        ret = get_video_frame(is, frame, &pts_int, &pkt);
+        ret = get_video_frame(is, frame, &pts_int, &pkt, &serial);
         if (ret < 0)
             goto the_end;
 
@@ -1776,11 +1894,11 @@
                         is->video_st->time_base.num, is->video_st->time_base.den, pts_int);
             }
             pts = pts_int * av_q2d(is->video_st->time_base);
-            ret = queue_picture(is, frame, pts, pos);
+            ret = queue_picture(is, frame, pts, pos, serial);
         }
 #else
         pts = pts_int * av_q2d(is->video_st->time_base);
-        ret = queue_picture(is, frame, pts, pkt.pos);
+        ret = queue_picture(is, frame, pts, pkt.pos, serial);
 #endif
 
         if (ret < 0)
@@ -1813,7 +1931,7 @@
         while (is->paused && !is->subtitleq.abort_request) {
             SDL_Delay(10);
         }
-        if (packet_queue_get(&is->subtitleq, pkt, 1) < 0)
+        if (packet_queue_get(&is->subtitleq, pkt, 1, NULL) < 0)
             break;
 
         if (pkt->data == flush_pkt.data) {
@@ -1895,14 +2013,13 @@
     int wanted_nb_samples = nb_samples;
 
     /* if not master, then we try to remove or add samples to correct the clock */
-    if (((is->av_sync_type == AV_SYNC_VIDEO_MASTER && is->video_st) ||
-         is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK)) {
+    if (get_master_sync_type(is) != AV_SYNC_AUDIO_MASTER) {
         double diff, avg_diff;
         int min_nb_samples, max_nb_samples;
 
         diff = get_audio_clock(is) - get_master_clock(is);
 
-        if (diff < AV_NOSYNC_THRESHOLD) {
+        if (fabs(diff) < AV_NOSYNC_THRESHOLD) {
             is->audio_diff_cum = diff + is->audio_diff_avg_coef * is->audio_diff_cum;
             if (is->audio_diff_avg_count < AUDIO_DIFF_AVG_NB) {
                 /* not enough measures to have a correct estimate */
@@ -1977,34 +2094,34 @@
                     flush_complete = 1;
                 continue;
             }
-            data_size = av_samples_get_buffer_size(NULL, dec->channels,
+            data_size = av_samples_get_buffer_size(NULL, is->frame->channels,
                                                    is->frame->nb_samples,
-                                                   dec->sample_fmt, 1);
+                                                   is->frame->format, 1);
 
             dec_channel_layout =
-                (dec->channel_layout && dec->channels == av_get_channel_layout_nb_channels(dec->channel_layout)) ?
-                dec->channel_layout : av_get_default_channel_layout(dec->channels);
+                (is->frame->channel_layout && is->frame->channels == av_get_channel_layout_nb_channels(is->frame->channel_layout)) ?
+                is->frame->channel_layout : av_get_default_channel_layout(is->frame->channels);
             wanted_nb_samples = synchronize_audio(is, is->frame->nb_samples);
 
-            if (dec->sample_fmt    != is->audio_src.fmt            ||
-                dec_channel_layout != is->audio_src.channel_layout ||
-                dec->sample_rate   != is->audio_src.freq           ||
-                (wanted_nb_samples != is->frame->nb_samples && !is->swr_ctx)) {
+            if (is->frame->format        != is->audio_src.fmt            ||
+                dec_channel_layout       != is->audio_src.channel_layout ||
+                is->frame->sample_rate   != is->audio_src.freq           ||
+                (wanted_nb_samples       != is->frame->nb_samples && !is->swr_ctx)) {
                 swr_free(&is->swr_ctx);
                 is->swr_ctx = swr_alloc_set_opts(NULL,
                                                  is->audio_tgt.channel_layout, is->audio_tgt.fmt, is->audio_tgt.freq,
-                                                 dec_channel_layout,           dec->sample_fmt,   dec->sample_rate,
+                                                 dec_channel_layout,           is->frame->format, is->frame->sample_rate,
                                                  0, NULL);
                 if (!is->swr_ctx || swr_init(is->swr_ctx) < 0) {
                     fprintf(stderr, "Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!\n",
-                        dec->sample_rate,   av_get_sample_fmt_name(dec->sample_fmt),   dec->channels,
+                        is->frame->sample_rate,   av_get_sample_fmt_name(is->frame->format), (int)is->frame->channels,
                         is->audio_tgt.freq, av_get_sample_fmt_name(is->audio_tgt.fmt), is->audio_tgt.channels);
                     break;
                 }
                 is->audio_src.channel_layout = dec_channel_layout;
-                is->audio_src.channels = dec->channels;
-                is->audio_src.freq = dec->sample_rate;
-                is->audio_src.fmt = dec->sample_fmt;
+                is->audio_src.channels = is->frame->channels;
+                is->audio_src.freq = is->frame->sample_rate;
+                is->audio_src.fmt = is->frame->format;
             }
 
             if (is->swr_ctx) {
@@ -2012,8 +2129,8 @@
                 uint8_t *out[] = {is->audio_buf2};
                 int out_count = sizeof(is->audio_buf2) / is->audio_tgt.channels / av_get_bytes_per_sample(is->audio_tgt.fmt);
                 if (wanted_nb_samples != is->frame->nb_samples) {
-                    if (swr_set_compensation(is->swr_ctx, (wanted_nb_samples - is->frame->nb_samples) * is->audio_tgt.freq / dec->sample_rate,
-                                                wanted_nb_samples * is->audio_tgt.freq / dec->sample_rate) < 0) {
+                    if (swr_set_compensation(is->swr_ctx, (wanted_nb_samples - is->frame->nb_samples) * is->audio_tgt.freq / is->frame->sample_rate,
+                                                wanted_nb_samples * is->audio_tgt.freq / is->frame->sample_rate) < 0) {
                         fprintf(stderr, "swr_set_compensation() failed\n");
                         break;
                     }
@@ -2038,7 +2155,7 @@
             pts = is->audio_clock;
             *pts_ptr = pts;
             is->audio_clock += (double)data_size /
-                (dec->channels * dec->sample_rate * av_get_bytes_per_sample(dec->sample_fmt));
+                (is->frame->channels * is->frame->sample_rate * av_get_bytes_per_sample(is->frame->format));
 #ifdef DEBUG
             {
                 static double last_clock;
@@ -2064,7 +2181,7 @@
             SDL_CondSignal(is->continue_read_thread);
 
         /* read next packet */
-        if ((new_packet = packet_queue_get(&is->audioq, pkt, 1)) < 0)
+        if ((new_packet = packet_queue_get(&is->audioq, pkt, 1, &is->audio_pkt_temp_serial)) < 0)
             return -1;
 
         if (pkt->data == flush_pkt.data) {
@@ -2119,6 +2236,8 @@
     /* Let's assume the audio driver that is used by SDL has two periods. */
     is->audio_current_pts = is->audio_clock - (double)(2 * is->audio_hw_buf_size + is->audio_write_buf_size) / bytes_per_sec;
     is->audio_current_pts_drift = is->audio_current_pts - audio_callback_time / 1000000.0;
+    if (is->audioq.serial == is->audio_pkt_temp_serial)
+        check_external_clock_sync(is, is->audio_current_pts);
 }
 
 static int audio_open(void *opaque, int64_t wanted_channel_layout, int wanted_nb_channels, int wanted_sample_rate, struct AudioParams *audio_hw_params)
@@ -2189,7 +2308,6 @@
     avctx = ic->streams[stream_index]->codec;
 
     codec = avcodec_find_decoder(avctx->codec_id);
-    opts = filter_codec_opts(codec_opts, avctx->codec_id, ic, ic->streams[stream_index], codec);
 
     switch(avctx->codec_type){
         case AVMEDIA_TYPE_AUDIO   : is->last_audio_stream    = stream_index; if(audio_codec_name   ) codec= avcodec_find_decoder_by_name(   audio_codec_name); break;
@@ -2217,10 +2335,10 @@
     if(codec->capabilities & CODEC_CAP_DR1)
         avctx->flags |= CODEC_FLAG_EMU_EDGE;
 
+    opts = filter_codec_opts(codec_opts, avctx->codec_id, ic, ic->streams[stream_index], codec);
     if (!av_dict_get(opts, "threads", NULL, 0))
         av_dict_set(&opts, "threads", "auto", 0);
-    if (!codec ||
-        avcodec_open2(avctx, codec, &opts) < 0)
+    if (avcodec_open2(avctx, codec, &opts) < 0)
         return -1;
     if ((t = av_dict_get(opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
@@ -2366,6 +2484,22 @@
     return is->abort_request;
 }
 
+static int is_realtime(AVFormatContext *s)
+{
+    if(   !strcmp(s->iformat->name, "rtp")
+       || !strcmp(s->iformat->name, "rtsp")
+       || !strcmp(s->iformat->name, "sdp")
+    )
+        return 1;
+
+    if(s->pb && (   !strncmp(s->filename, "rtp:", 4)
+                 || !strncmp(s->filename, "udp:", 4)
+                )
+    )
+        return 1;
+    return 0;
+}
+
 /* this thread gets the stream from the disk or the network */
 static int read_thread(void *arg)
 {
@@ -2424,6 +2558,8 @@
     if (seek_by_bytes < 0)
         seek_by_bytes = !!(ic->iformat->flags & AVFMT_TS_DISCONT);
 
+    is->max_frame_duration = (ic->iformat->flags & AVFMT_TS_DISCONT) ? 10.0 : 3600.0;
+
     /* if seeking requested, we execute it */
     if (start_time != AV_NOPTS_VALUE) {
         int64_t timestamp;
@@ -2439,6 +2575,8 @@
         }
     }
 
+    is->realtime = is_realtime(ic);
+
     for (i = 0; i < ic->nb_streams; i++)
         ic->streams[i]->discard = AVDISCARD_ALL;
     if (!video_disable)
@@ -2488,6 +2626,9 @@
         goto fail;
     }
 
+    if (infinite_buffer < 0 && is->realtime)
+        infinite_buffer = 1;
+
     for (;;) {
         if (is->abort_request)
             break;
@@ -2531,6 +2672,12 @@
                     packet_queue_flush(&is->videoq);
                     packet_queue_put(&is->videoq, &flush_pkt);
                 }
+                if (is->seek_flags & AVSEEK_FLAG_BYTE) {
+                   //FIXME: use a cleaner way to signal obsolete external clock...
+                   update_external_clock_pts(is, (double)AV_NOPTS_VALUE);
+                } else {
+                   update_external_clock_pts(is, seek_target / (double)AV_TIME_BASE);
+                }
             }
             is->seek_req = 0;
             eof = 0;
@@ -2541,7 +2688,7 @@
         }
 
         /* if the queue are full, no need to read more */
-        if (!infinite_buffer &&
+        if (infinite_buffer<1 &&
               (is->audioq.size + is->videoq.size + is->subtitleq.size > MAX_QUEUE_SIZE
             || (   (is->audioq   .nb_packets > MIN_FRAMES || is->audio_stream < 0 || is->audioq.abort_request)
                 && (is->videoq   .nb_packets > MIN_FRAMES || is->video_stream < 0 || is->videoq.abort_request)
@@ -2661,6 +2808,10 @@
 
     is->continue_read_thread = SDL_CreateCond();
 
+    update_external_clock_pts(is, 0.0);
+    update_external_clock_speed(is, 1.0);
+    is->audio_current_pts_drift = -av_gettime() / 1000000.0;
+    is->video_current_pts_drift = is->audio_current_pts_drift;
     is->av_sync_type = av_sync_type;
     is->read_tid     = SDL_CreateThread(read_thread, is);
     if (!is->read_tid) {
@@ -2760,8 +2911,7 @@
     is->show_mode = (is->show_mode + 1) % SHOW_MODE_NB;
     fill_rectangle(screen,
                 is->xleft, is->ytop, is->width, is->height,
-                bgcolor);
-    SDL_UpdateRect(screen, is->xleft, is->ytop, is->width, is->height);
+                bgcolor, 1);
 }
 
 /* handle an event sent by the GUI */
@@ -2842,6 +2992,8 @@
                     } else {
                         pos = get_master_clock(cur_stream);
                         pos += incr;
+                        if (cur_stream->ic->start_time != AV_NOPTS_VALUE && pos < cur_stream->ic->start_time / (double)AV_TIME_BASE)
+                            pos = cur_stream->ic->start_time / (double)AV_TIME_BASE;
                         stream_seek(cur_stream, (int64_t)(pos * AV_TIME_BASE), (int64_t)(incr * AV_TIME_BASE), 0);
                     }
                 break;
@@ -2988,7 +3140,7 @@
     if (input_filename) {
         fprintf(stderr, "Argument '%s' provided as input filename, but '%s' was already specified.\n",
                 filename, input_filename);
-        exit_program(1);
+        exit(1);
     }
     if (!strcmp(filename, "-"))
         filename = "pipe:";
diff --git a/ffprobe.c b/ffprobe.c
index 9e5cd04..84dfa19 100644
--- a/ffprobe.c
+++ b/ffprobe.c
@@ -55,9 +55,9 @@
 static int do_show_error   = 0;
 static int do_show_format  = 0;
 static int do_show_frames  = 0;
-static AVDictionary *fmt_entries_to_show = NULL;
 static int do_show_packets = 0;
 static int do_show_streams = 0;
+static int do_show_stream_disposition = 0;
 static int do_show_data    = 0;
 static int do_show_program_version  = 0;
 static int do_show_library_versions = 0;
@@ -69,11 +69,14 @@
 static int show_private_data            = 1;
 
 static char *print_format;
+static char *stream_specifier;
 
 /* section structure definition */
 
+#define SECTION_MAX_NB_CHILDREN 10
+
 struct section {
-    int id;             ///< unique id indentifying a section
+    int id;             ///< unique id identifying a section
     const char *name;
 
 #define SECTION_FLAG_IS_WRAPPER      1 ///< the section only contains other sections, but has no data at its own level
@@ -81,7 +84,11 @@
 #define SECTION_FLAG_HAS_VARIABLE_FIELDS 4 ///< the section may contain a variable number of fields with variable keys.
                                            ///  For these sections the element_name field is mandatory.
     int flags;
+    int children_ids[SECTION_MAX_NB_CHILDREN+1]; ///< list of children section IDS, terminated by -1
     const char *element_name; ///< name of the contained element, if provided
+    const char *unique_name;  ///< unique section name, in case the name is ambiguous
+    AVDictionary *entries_to_show;
+    int show_all_entries;
 };
 
 typedef enum {
@@ -102,27 +109,29 @@
     SECTION_ID_STREAM,
     SECTION_ID_STREAM_DISPOSITION,
     SECTION_ID_STREAMS,
-    SECTION_ID_STREAM_TAGS
+    SECTION_ID_STREAM_TAGS,
 } SectionID;
 
-static const struct section sections[] = {
-    [SECTION_ID_ERROR] =              { SECTION_ID_ERROR,              "error" },
-    [SECTION_ID_FORMAT] =             { SECTION_ID_FORMAT,             "format" },
-    [SECTION_ID_FORMAT_TAGS] =        { SECTION_ID_FORMAT_TAGS,        "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, .element_name = "tag" },
-    [SECTION_ID_FRAME] =              { SECTION_ID_FRAME,              "frame" },
-    [SECTION_ID_FRAMES] =             { SECTION_ID_FRAMES,             "frames", SECTION_FLAG_IS_ARRAY },
-    [SECTION_ID_FRAME_TAGS] =         { SECTION_ID_FRAME_TAGS,         "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, .element_name = "tag" },
-    [SECTION_ID_LIBRARY_VERSION] =    { SECTION_ID_LIBRARY_VERSION,    "library_version" },
-    [SECTION_ID_LIBRARY_VERSIONS] =   { SECTION_ID_LIBRARY_VERSIONS,   "library_versions", SECTION_FLAG_IS_ARRAY },
-    [SECTION_ID_PACKET] =             { SECTION_ID_PACKET,             "packet" },
-    [SECTION_ID_PACKETS] =            { SECTION_ID_PACKETS,            "packets", SECTION_FLAG_IS_ARRAY },
-    [SECTION_ID_PACKETS_AND_FRAMES] = { SECTION_ID_PACKETS_AND_FRAMES, "packets_and_frames", SECTION_FLAG_IS_ARRAY },
-    [SECTION_ID_PROGRAM_VERSION] =    { SECTION_ID_PROGRAM_VERSION,    "program_version" },
-    [SECTION_ID_ROOT] =               { SECTION_ID_ROOT,               "root", SECTION_FLAG_IS_WRAPPER },
-    [SECTION_ID_STREAM] =             { SECTION_ID_STREAM,             "stream" },
-    [SECTION_ID_STREAM_DISPOSITION] = { SECTION_ID_STREAM_DISPOSITION, "disposition" },
-    [SECTION_ID_STREAMS] =            { SECTION_ID_STREAMS,            "streams", SECTION_FLAG_IS_ARRAY },
-    [SECTION_ID_STREAM_TAGS] =        { SECTION_ID_STREAM_TAGS,        "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, .element_name = "tag" },
+static struct section sections[] = {
+    [SECTION_ID_ERROR] =              { SECTION_ID_ERROR, "error", 0, { -1 } },
+    [SECTION_ID_FORMAT] =             { SECTION_ID_FORMAT, "format", 0, { SECTION_ID_FORMAT_TAGS, -1 } },
+    [SECTION_ID_FORMAT_TAGS] =        { SECTION_ID_FORMAT_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "format_tags" },
+    [SECTION_ID_FRAMES] =             { SECTION_ID_FRAMES, "frames", SECTION_FLAG_IS_ARRAY, { SECTION_ID_FRAME, -1 } },
+    [SECTION_ID_FRAME] =              { SECTION_ID_FRAME, "frame", 0, { SECTION_ID_FRAME_TAGS, -1 } },
+    [SECTION_ID_FRAME_TAGS] =         { SECTION_ID_FRAME_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "frame_tags" },
+    [SECTION_ID_LIBRARY_VERSIONS] =   { SECTION_ID_LIBRARY_VERSIONS, "library_versions", SECTION_FLAG_IS_ARRAY, { SECTION_ID_LIBRARY_VERSION, -1 } },
+    [SECTION_ID_LIBRARY_VERSION] =    { SECTION_ID_LIBRARY_VERSION, "library_version", 0, { -1 } },
+    [SECTION_ID_PACKETS] =            { SECTION_ID_PACKETS, "packets", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PACKET, -1} },
+    [SECTION_ID_PACKETS_AND_FRAMES] = { SECTION_ID_PACKETS_AND_FRAMES, "packets_and_frames", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PACKET, -1} },
+    [SECTION_ID_PACKET] =             { SECTION_ID_PACKET, "packet", 0, { -1 } },
+    [SECTION_ID_PROGRAM_VERSION] =    { SECTION_ID_PROGRAM_VERSION, "program_version", 0, { -1 } },
+    [SECTION_ID_ROOT] =               { SECTION_ID_ROOT, "root", SECTION_FLAG_IS_WRAPPER,
+                                        { SECTION_ID_FORMAT, SECTION_ID_FRAMES, SECTION_ID_STREAMS, SECTION_ID_PACKETS,
+                                          SECTION_ID_ERROR, SECTION_ID_PROGRAM_VERSION, SECTION_ID_LIBRARY_VERSIONS, -1} },
+    [SECTION_ID_STREAMS] =            { SECTION_ID_STREAMS, "streams", SECTION_FLAG_IS_ARRAY, { SECTION_ID_STREAM, -1 } },
+    [SECTION_ID_STREAM] =             { SECTION_ID_STREAM, "stream", 0, { SECTION_ID_STREAM_DISPOSITION, SECTION_ID_STREAM_TAGS, -1 } },
+    [SECTION_ID_STREAM_DISPOSITION] = { SECTION_ID_STREAM_DISPOSITION, "disposition", 0, { -1 }, .unique_name = "stream_disposition" },
+    [SECTION_ID_STREAM_TAGS] =        { SECTION_ID_STREAM_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "stream_tags" },
 };
 
 static const OptionDef *options;
@@ -138,13 +147,16 @@
 static const char unit_hertz_str[]          = "Hz"   ;
 static const char unit_byte_str[]           = "byte" ;
 static const char unit_bit_per_second_str[] = "bit/s";
+
 static uint64_t *nb_streams_packets;
 static uint64_t *nb_streams_frames;
+static int *selected_streams;
 
-void av_noreturn exit_program(int ret)
+static void exit_program(void)
 {
-    av_dict_free(&fmt_entries_to_show);
-    exit(ret);
+    int i;
+    for (i = 0; i < FF_ARRAY_ELEMS(sections); i++)
+        av_dict_free(&(sections[i].entries_to_show));
 }
 
 struct unit_value {
@@ -245,6 +257,8 @@
 
     /** section per each level */
     const struct section *section[SECTION_MAX_NB_LEVELS];
+    AVBPrint section_pbuf[SECTION_MAX_NB_LEVELS]; ///< generic print buffer dedicated to each section,
+                                                  ///  used by various writers
 
     unsigned int nb_section_packet; ///< number of the packet section in case we are in "packets_and_frames" section
     unsigned int nb_section_frame;  ///< number of the frame  section in case we are in "packets_and_frames" section
@@ -266,11 +280,15 @@
 
 static void writer_close(WriterContext **wctx)
 {
+    int i;
+
     if (!*wctx)
         return;
 
     if ((*wctx)->writer->uninit)
         (*wctx)->writer->uninit(*wctx);
+    for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
+        av_bprint_finalize(&(*wctx)->section_pbuf[i], NULL);
     if ((*wctx)->writer->priv_class)
         av_opt_free((*wctx)->priv);
     av_freep(&((*wctx)->priv));
@@ -280,7 +298,7 @@
 static int writer_open(WriterContext **wctx, const Writer *writer, const char *args,
                        const struct section *sections, int nb_sections)
 {
-    int ret = 0;
+    int i, ret = 0;
 
     if (!(*wctx = av_malloc(sizeof(WriterContext)))) {
         ret = AVERROR(ENOMEM);
@@ -307,6 +325,10 @@
             (ret = av_set_options_string(priv_ctx, args, "=", ":")) < 0)
             goto fail;
     }
+
+    for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
+        av_bprint_init(&(*wctx)->section_pbuf[i], 1, AV_BPRINT_SIZE_UNLIMITED);
+
     if ((*wctx)->writer->init)
         ret = (*wctx)->writer->init(*wctx);
     if (ret < 0)
@@ -363,9 +385,9 @@
 static inline void writer_print_integer(WriterContext *wctx,
                                         const char *key, long long int val)
 {
-    if ((wctx->section[wctx->level]->id != SECTION_ID_FORMAT
-         && wctx->section[wctx->level]->id != SECTION_ID_FORMAT_TAGS) ||
-        !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
+    const struct section *section = wctx->section[wctx->level];
+
+    if (section->show_all_entries || av_dict_get(section->entries_to_show, key, NULL, 0)) {
         wctx->writer->print_integer(wctx, key, val);
         wctx->nb_item[wctx->level]++;
     }
@@ -374,11 +396,12 @@
 static inline void writer_print_string(WriterContext *wctx,
                                        const char *key, const char *val, int opt)
 {
+    const struct section *section = wctx->section[wctx->level];
+
     if (opt && !(wctx->writer->flags & WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS))
         return;
-    if ((wctx->section[wctx->level]->id != SECTION_ID_FORMAT
-         && wctx->section[wctx->level]->id != SECTION_ID_FORMAT_TAGS) ||
-        !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
+
+    if (section->show_all_entries || av_dict_get(section->entries_to_show, key, NULL, 0)) {
         wctx->writer->print_string(wctx, key, val);
         wctx->nb_item[wctx->level]++;
     }
@@ -494,7 +517,6 @@
     int nokey;
     int noprint_wrappers;
     int nested_section[SECTION_MAX_NB_LEVELS];
-    AVBPrint prefix[SECTION_MAX_NB_LEVELS];
 } DefaultContext;
 
 #define OFFSET(x) offsetof(DefaultContext, x)
@@ -519,25 +541,6 @@
     return dst;
 }
 
-static int default_init(WriterContext *wctx)
-{
-    DefaultContext *def = wctx->priv;
-    int i;
-
-    for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
-        av_bprint_init(&def->prefix[i], 1, AV_BPRINT_SIZE_UNLIMITED);
-    return 0;
-}
-
-static void default_uninit(WriterContext *wctx)
-{
-    DefaultContext *def = wctx->priv;
-    int i;
-
-    for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
-        av_bprint_finalize(&def->prefix[i], NULL);
-}
-
 static void default_print_section_header(WriterContext *wctx)
 {
     DefaultContext *def = wctx->priv;
@@ -546,11 +549,12 @@
     const struct section *parent_section = wctx->level ?
         wctx->section[wctx->level-1] : NULL;
 
-    av_bprint_clear(&def->prefix[wctx->level]);
+    av_bprint_clear(&wctx->section_pbuf[wctx->level]);
     if (parent_section &&
         !(parent_section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY))) {
         def->nested_section[wctx->level] = 1;
-        av_bprintf(&def->prefix[wctx->level], "%s%s:", def->prefix[wctx->level-1].str,
+        av_bprintf(&wctx->section_pbuf[wctx->level], "%s%s:",
+                   wctx->section_pbuf[wctx->level-1].str,
                    upcase_string(buf, sizeof(buf),
                                  av_x_if_null(section->element_name, section->name)));
     }
@@ -580,7 +584,7 @@
     DefaultContext *def = wctx->priv;
 
     if (!def->nokey)
-        printf("%s%s=", def->prefix[wctx->level].str, key);
+        printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
     printf("%s\n", value);
 }
 
@@ -589,15 +593,13 @@
     DefaultContext *def = wctx->priv;
 
     if (!def->nokey)
-        printf("%s%s=", def->prefix[wctx->level].str, key);
+        printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
     printf("%lld\n", value);
 }
 
 static const Writer default_writer = {
     .name                  = "default",
     .priv_size             = sizeof(DefaultContext),
-    .init                  = default_init,
-    .uninit                = default_uninit,
     .print_section_header  = default_print_section_header,
     .print_section_footer  = default_print_section_footer,
     .print_integer         = default_print_int,
@@ -666,7 +668,6 @@
     char *escape_mode_str;
     const char * (*escape_str)(AVBPrint *dst, const char *src, const char sep, void *log_ctx);
     int nested_section[SECTION_MAX_NB_LEVELS];
-    AVBPrint prefix[SECTION_MAX_NB_LEVELS];
 } CompactContext;
 
 #undef OFFSET
@@ -689,7 +690,6 @@
 static av_cold int compact_init(WriterContext *wctx)
 {
     CompactContext *compact = wctx->priv;
-    int i;
 
     if (strlen(compact->item_sep_str) != 1) {
         av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
@@ -706,20 +706,9 @@
         return AVERROR(EINVAL);
     }
 
-    for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
-        av_bprint_init(&compact->prefix[i], 1, AV_BPRINT_SIZE_UNLIMITED);
     return 0;
 }
 
-static void compact_uninit(WriterContext *wctx)
-{
-    CompactContext *compact = wctx->priv;
-    int i;
-
-    for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
-        av_bprint_finalize(&compact->prefix[i], NULL);
-}
-
 static void compact_print_section_header(WriterContext *wctx)
 {
     CompactContext *compact = wctx->priv;
@@ -727,12 +716,12 @@
     const struct section *parent_section = wctx->level ?
         wctx->section[wctx->level-1] : NULL;
 
-    av_bprint_clear(&compact->prefix[wctx->level]);
+    av_bprint_clear(&wctx->section_pbuf[wctx->level]);
     if (parent_section &&
         !(parent_section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY))) {
         compact->nested_section[wctx->level] = 1;
-        av_bprintf(&compact->prefix[wctx->level], "%s%s:",
-                   compact->prefix[wctx->level-1].str,
+        av_bprintf(&wctx->section_pbuf[wctx->level], "%s%s:",
+                   wctx->section_pbuf[wctx->level-1].str,
                    (char *)av_x_if_null(section->element_name, section->name));
         wctx->nb_item[wctx->level] = wctx->nb_item[wctx->level-1];
     } else if (compact->print_section &&
@@ -756,7 +745,7 @@
 
     if (wctx->nb_item[wctx->level]) printf("%c", compact->item_sep);
     if (!compact->nokey)
-        printf("%s%s=", compact->prefix[wctx->level].str, key);
+        printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
     printf("%s", compact->escape_str(&buf, value, compact->item_sep, wctx));
     av_bprint_finalize(&buf, NULL);
@@ -768,7 +757,7 @@
 
     if (wctx->nb_item[wctx->level]) printf("%c", compact->item_sep);
     if (!compact->nokey)
-        printf("%s%s=", compact->prefix[wctx->level].str, key);
+        printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
     printf("%lld", value);
 }
 
@@ -776,7 +765,6 @@
     .name                 = "compact",
     .priv_size            = sizeof(CompactContext),
     .init                 = compact_init,
-    .uninit               = compact_uninit,
     .print_section_header = compact_print_section_header,
     .print_section_footer = compact_print_section_footer,
     .print_integer        = compact_print_int,
@@ -820,7 +808,6 @@
 
 typedef struct FlatContext {
     const AVClass *class;
-    AVBPrint section_header[SECTION_MAX_NB_LEVELS];
     const char *sep_str;
     char sep;
     int hierarchical;
@@ -842,7 +829,6 @@
 static av_cold int flat_init(WriterContext *wctx)
 {
     FlatContext *flat = wctx->priv;
-    int i;
 
     if (strlen(flat->sep_str) != 1) {
         av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
@@ -851,20 +837,9 @@
     }
     flat->sep = flat->sep_str[0];
 
-    for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
-        av_bprint_init(&flat->section_header[i], 1, AV_BPRINT_SIZE_UNLIMITED);
     return 0;
 }
 
-static void flat_uninit(WriterContext *wctx)
-{
-    FlatContext *flat = wctx->priv;
-    int i;
-
-    for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
-        av_bprint_finalize(&flat->section_header[i], NULL);
-}
-
 static const char *flat_escape_key_str(AVBPrint *dst, const char *src, const char sep)
 {
     const char *p;
@@ -901,7 +876,7 @@
 static void flat_print_section_header(WriterContext *wctx)
 {
     FlatContext *flat = wctx->priv;
-    AVBPrint *buf = &flat->section_header[wctx->level];
+    AVBPrint *buf = &wctx->section_pbuf[wctx->level];
     const struct section *section = wctx->section[wctx->level];
     const struct section *parent_section = wctx->level ?
         wctx->section[wctx->level-1] : NULL;
@@ -910,7 +885,7 @@
     av_bprint_clear(buf);
     if (!parent_section)
         return;
-    av_bprintf(buf, "%s", flat->section_header[wctx->level-1].str);
+    av_bprintf(buf, "%s", wctx->section_pbuf[wctx->level-1].str);
 
     if (flat->hierarchical ||
         !(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER))) {
@@ -926,8 +901,7 @@
 
 static void flat_print_int(WriterContext *wctx, const char *key, long long int value)
 {
-    FlatContext *flat = wctx->priv;
-    printf("%s%s=%lld\n", flat->section_header[wctx->level].str, key, value);
+    printf("%s%s=%lld\n", wctx->section_pbuf[wctx->level].str, key, value);
 }
 
 static void flat_print_str(WriterContext *wctx, const char *key, const char *value)
@@ -935,7 +909,7 @@
     FlatContext *flat = wctx->priv;
     AVBPrint buf;
 
-    printf("%s", flat->section_header[wctx->level].str);
+    printf("%s", wctx->section_pbuf[wctx->level].str);
     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
     printf("%s=", flat_escape_key_str(&buf, key, flat->sep));
     av_bprint_clear(&buf);
@@ -947,7 +921,6 @@
     .name                  = "flat",
     .priv_size             = sizeof(FlatContext),
     .init                  = flat_init,
-    .uninit                = flat_uninit,
     .print_section_header  = flat_print_section_header,
     .print_integer         = flat_print_int,
     .print_string          = flat_print_str,
@@ -960,7 +933,6 @@
 typedef struct {
     const AVClass *class;
     int hierarchical;
-    AVBPrint section_header[SECTION_MAX_NB_LEVELS];
 } INIContext;
 
 #undef OFFSET
@@ -974,25 +946,6 @@
 
 DEFINE_WRITER_CLASS(ini);
 
-static int ini_init(WriterContext *wctx)
-{
-    INIContext *ini = wctx->priv;
-    int i;
-
-    for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
-        av_bprint_init(&ini->section_header[i], 1, AV_BPRINT_SIZE_UNLIMITED);
-    return 0;
-}
-
-static void ini_uninit(WriterContext *wctx)
-{
-    INIContext *ini = wctx->priv;
-    int i;
-
-    for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
-        av_bprint_finalize(&ini->section_header[i], NULL);
-}
-
 static char *ini_escape_str(AVBPrint *dst, const char *src)
 {
     int i = 0;
@@ -1023,7 +976,7 @@
 static void ini_print_section_header(WriterContext *wctx)
 {
     INIContext *ini = wctx->priv;
-    AVBPrint *buf = &ini->section_header[wctx->level];
+    AVBPrint *buf = &wctx->section_pbuf[wctx->level];
     const struct section *section = wctx->section[wctx->level];
     const struct section *parent_section = wctx->level ?
         wctx->section[wctx->level-1] : NULL;
@@ -1037,7 +990,7 @@
     if (wctx->nb_item[wctx->level-1])
         printf("\n");
 
-    av_bprintf(buf, "%s", ini->section_header[wctx->level-1].str);
+    av_bprintf(buf, "%s", wctx->section_pbuf[wctx->level-1].str);
     if (ini->hierarchical ||
         !(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER))) {
         av_bprintf(buf, "%s%s", buf->str[0] ? "." : "", wctx->section[wctx->level]->name);
@@ -1072,8 +1025,6 @@
 static const Writer ini_writer = {
     .name                  = "ini",
     .priv_size             = sizeof(INIContext),
-    .init                  = ini_init,
-    .uninit                = ini_uninit,
     .print_section_header  = ini_print_section_header,
     .print_integer         = ini_print_int,
     .print_string          = ini_print_str,
@@ -1155,13 +1106,13 @@
         json->indent_level++;
         if (section->flags & SECTION_FLAG_IS_ARRAY) {
             printf("\"%s\": [\n", buf.str);
-        } else if (!(parent_section->flags & SECTION_FLAG_IS_ARRAY)) {
+        } else if (parent_section && !(parent_section->flags & SECTION_FLAG_IS_ARRAY)) {
             printf("\"%s\": {%s", buf.str, json->item_start_end);
         } else {
             printf("{%s", json->item_start_end);
 
             /* this is required so the parser can distinguish between packets and frames */
-            if (parent_section->id == SECTION_ID_PACKETS_AND_FRAMES) {
+            if (parent_section && parent_section->id == SECTION_ID_PACKETS_AND_FRAMES) {
                 if (!json->compact)
                     JSON_INDENT();
                 printf("\"type\": \"%s\"%s", section->name, json->item_sep);
@@ -1615,14 +1566,16 @@
     av_init_packet(&pkt);
 
     while (!av_read_frame(fmt_ctx, &pkt)) {
-        if (do_read_packets) {
-            if (do_show_packets)
-                show_packet(w, fmt_ctx, &pkt, i++);
-            nb_streams_packets[pkt.stream_index]++;
-        }
-        if (do_read_frames) {
-            pkt1 = pkt;
-            while (pkt1.size && process_frame(w, fmt_ctx, &frame, &pkt1) > 0);
+        if (selected_streams[pkt.stream_index]) {
+            if (do_read_packets) {
+                if (do_show_packets)
+                    show_packet(w, fmt_ctx, &pkt, i++);
+                nb_streams_packets[pkt.stream_index]++;
+            }
+            if (do_read_frames) {
+                pkt1 = pkt;
+                while (pkt1.size && process_frame(w, fmt_ctx, &frame, &pkt1) > 0);
+            }
         }
         av_free_packet(&pkt);
     }
@@ -1764,6 +1717,7 @@
         print_int(name, !!(stream->disposition & AV_DISPOSITION_##flagname)); \
     } while (0)
 
+    if (do_show_stream_disposition) {
     writer_print_section_header(w, SECTION_ID_STREAM_DISPOSITION);
     PRINT_DISPOSITION(DEFAULT,          "default");
     PRINT_DISPOSITION(DUB,              "dub");
@@ -1777,6 +1731,7 @@
     PRINT_DISPOSITION(CLEAN_EFFECTS,    "clean_effects");
     PRINT_DISPOSITION(ATTACHED_PIC,     "attached_pic");
     writer_print_section_footer(w);
+    }
 
     show_tags(w, stream->metadata, SECTION_ID_STREAM_TAGS);
 
@@ -1790,7 +1745,8 @@
     int i;
     writer_print_section_header(w, SECTION_ID_STREAMS);
     for (i = 0; i < fmt_ctx->nb_streams; i++)
-        show_stream(w, fmt_ctx, i);
+        if (selected_streams[i])
+            show_stream(w, fmt_ctx, i);
     writer_print_section_footer(w);
 }
 
@@ -1897,7 +1853,7 @@
 static int probe_file(WriterContext *wctx, const char *filename)
 {
     AVFormatContext *fmt_ctx;
-    int ret;
+    int ret, i;
     int section_id;
 
     do_read_frames = do_show_frames || do_count_frames;
@@ -1907,6 +1863,22 @@
     if (ret >= 0) {
         nb_streams_frames  = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_frames));
         nb_streams_packets = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_packets));
+        selected_streams   = av_calloc(fmt_ctx->nb_streams, sizeof(*selected_streams));
+
+        for (i = 0; i < fmt_ctx->nb_streams; i++) {
+            if (stream_specifier) {
+                ret = avformat_match_stream_specifier(fmt_ctx,
+                                                      fmt_ctx->streams[i],
+                                                      stream_specifier);
+                if (ret < 0)
+                    goto end;
+                else
+                    selected_streams[i] = ret;
+            } else {
+                selected_streams[i] = 1;
+            }
+        }
+
         if (do_read_frames || do_read_packets) {
             if (do_show_frames && do_show_packets &&
                 wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
@@ -1926,9 +1898,11 @@
         if (do_show_format)
             show_format(wctx, fmt_ctx);
 
+    end:
         close_input_file(&fmt_ctx);
         av_freep(&nb_streams_frames);
         av_freep(&nb_streams_packets);
+        av_freep(&selected_streams);
     }
     return ret;
 }
@@ -1997,11 +1971,101 @@
     return 0;
 }
 
+static inline void mark_section_show_entries(SectionID section_id,
+                                             int show_all_entries, AVDictionary *entries)
+{
+    struct section *section = &sections[section_id];
+
+    section->show_all_entries = show_all_entries;
+    if (show_all_entries) {
+        SectionID *id;
+        for (id = section->children_ids; *id != -1; id++)
+            mark_section_show_entries(*id, show_all_entries, entries);
+    } else {
+        av_dict_copy(&section->entries_to_show, entries, 0);
+    }
+}
+
+static int match_section(const char *section_name,
+                         int show_all_entries, AVDictionary *entries)
+{
+    int i, ret = 0;
+
+    for (i = 0; i < FF_ARRAY_ELEMS(sections); i++) {
+        const struct section *section = &sections[i];
+        if (!strcmp(section_name, section->name) ||
+            (section->unique_name && !strcmp(section_name, section->unique_name))) {
+            av_log(NULL, AV_LOG_DEBUG,
+                   "'%s' matches section with unique name '%s'\n", section_name,
+                   (char *)av_x_if_null(section->unique_name, section->name));
+            ret++;
+            mark_section_show_entries(section->id, show_all_entries, entries);
+        }
+    }
+    return ret;
+}
+
+static int opt_show_entries(void *optctx, const char *opt, const char *arg)
+{
+    const char *p = arg;
+    int ret = 0;
+
+    while (*p) {
+        AVDictionary *entries = NULL;
+        char *section_name = av_get_token(&p, "=:");
+        int show_all_entries = 0;
+
+        if (!section_name) {
+            av_log(NULL, AV_LOG_ERROR,
+                   "Missing section name for option '%s'\n", opt);
+            return AVERROR(EINVAL);
+        }
+
+        if (*p == '=') {
+            p++;
+            while (*p && *p != ':') {
+                char *entry = av_get_token(&p, ",:");
+                if (!entry)
+                    break;
+                av_log(NULL, AV_LOG_VERBOSE,
+                       "Adding '%s' to the entries to show in section '%s'\n",
+                       entry, section_name);
+                av_dict_set(&entries, entry, "", AV_DICT_DONT_STRDUP_KEY);
+                if (*p == ',')
+                    p++;
+            }
+        } else {
+            show_all_entries = 1;
+        }
+
+        ret = match_section(section_name, show_all_entries, entries);
+        if (ret == 0) {
+            av_log(NULL, AV_LOG_ERROR, "No match for section '%s'\n", section_name);
+            ret = AVERROR(EINVAL);
+        }
+        av_dict_free(&entries);
+        av_free(section_name);
+
+        if (ret <= 0)
+            break;
+        if (*p)
+            p++;
+    }
+
+    return ret;
+}
+
 static int opt_show_format_entry(void *optctx, const char *opt, const char *arg)
 {
-    do_show_format = 1;
-    av_dict_set(&fmt_entries_to_show, arg, "", 0);
-    return 0;
+    char *buf = av_asprintf("format=%s", arg);
+    int ret;
+
+    av_log(NULL, AV_LOG_WARNING,
+           "Option '%s' is deprecated, use '-show_entries format=%s' instead\n",
+           opt, arg);
+    ret = opt_show_entries(optctx, opt, buf);
+    av_free(buf);
+    return ret;
 }
 
 static void opt_input_file(void *optctx, const char *arg)
@@ -2042,13 +2106,57 @@
     return 0;
 }
 
-static int opt_show_versions(const char *opt, const char *arg)
+static void print_section(SectionID id, int level)
 {
-    do_show_program_version  = 1;
-    do_show_library_versions = 1;
+    const SectionID *pid;
+    const struct section *section = &sections[id];
+    printf("%c%c%c",
+           section->flags & SECTION_FLAG_IS_WRAPPER           ? 'W' : '.',
+           section->flags & SECTION_FLAG_IS_ARRAY             ? 'A' : '.',
+           section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS  ? 'V' : '.');
+    printf("%*c  %s", level * 4, ' ', section->name);
+    if (section->unique_name)
+        printf("/%s", section->unique_name);
+    printf("\n");
+
+    for (pid = section->children_ids; *pid != -1; pid++)
+        print_section(*pid, level+1);
+}
+
+static int opt_sections(void *optctx, const char *opt, const char *arg)
+{
+    printf("Sections:\n"
+           "W.. = Section is a wrapper (contains other sections, no local entries)\n"
+           ".A. = Section contains an array of elements of the same type\n"
+           "..V = Section may contain a variable number of fields with variable keys\n"
+           "FLAGS NAME/UNIQUE_NAME\n"
+           "---\n");
+    print_section(SECTION_ID_ROOT, 0);
     return 0;
 }
 
+static int opt_show_versions(const char *opt, const char *arg)
+{
+    mark_section_show_entries(SECTION_ID_PROGRAM_VERSION, 1, NULL);
+    mark_section_show_entries(SECTION_ID_LIBRARY_VERSION, 1, NULL);
+    return 0;
+}
+
+#define DEFINE_OPT_SHOW_SECTION(section, target_section_id)             \
+    static int opt_show_##section(const char *opt, const char *arg)     \
+    {                                                                   \
+        mark_section_show_entries(SECTION_ID_##target_section_id, 1, NULL); \
+        return 0;                                                       \
+    }
+
+DEFINE_OPT_SHOW_SECTION(error,            ERROR);
+DEFINE_OPT_SHOW_SECTION(format,           FORMAT);
+DEFINE_OPT_SHOW_SECTION(frames,           FRAMES);
+DEFINE_OPT_SHOW_SECTION(library_versions, LIBRARY_VERSIONS);
+DEFINE_OPT_SHOW_SECTION(packets,          PACKETS);
+DEFINE_OPT_SHOW_SECTION(program_version,  PROGRAM_VERSION);
+DEFINE_OPT_SHOW_SECTION(streams,          STREAMS);
+
 static const OptionDef real_options[] = {
 #include "cmdutils_common_opts.h"
     { "f", HAS_ARG, {.func_arg = opt_format}, "force format", "format" },
@@ -2063,18 +2171,22 @@
     { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
       "set the output printing format (available formats are: default, compact, csv, flat, ini, json, xml)", "format" },
     { "of", OPT_STRING | HAS_ARG, {(void*)&print_format}, "alias for -print_format", "format" },
+    { "select_streams", OPT_STRING | HAS_ARG, {(void*)&stream_specifier}, "select the specified streams", "stream_specifier" },
+    { "sections", OPT_EXIT, {.func_arg = opt_sections}, "print sections structure and section information, and exit" },
     { "show_data",    OPT_BOOL, {(void*)&do_show_data}, "show packets data" },
-    { "show_error",   OPT_BOOL, {(void*)&do_show_error} ,  "show probing error" },
-    { "show_format",  OPT_BOOL, {&do_show_format} , "show format/container info" },
-    { "show_frames",  OPT_BOOL, {(void*)&do_show_frames} , "show frames info" },
+    { "show_error",   0, {(void*)&opt_show_error},  "show probing error" },
+    { "show_format",  0, {(void*)&opt_show_format}, "show format/container info" },
+    { "show_frames",  0, {(void*)&opt_show_frames}, "show frames info" },
     { "show_format_entry", HAS_ARG, {.func_arg = opt_show_format_entry},
       "show a particular entry from the format/container info", "entry" },
-    { "show_packets", OPT_BOOL, {&do_show_packets}, "show packets info" },
-    { "show_streams", OPT_BOOL, {&do_show_streams}, "show streams info" },
+    { "show_entries", HAS_ARG, {.func_arg = opt_show_entries},
+      "show a set of specified entries", "entry_list" },
+    { "show_packets", 0, {(void*)&opt_show_packets}, "show packets info" },
+    { "show_streams", 0, {(void*)&opt_show_streams}, "show streams info" },
     { "count_frames", OPT_BOOL, {(void*)&do_count_frames}, "count the number of frames per stream" },
     { "count_packets", OPT_BOOL, {(void*)&do_count_packets}, "count the number of packets per stream" },
-    { "show_program_version",  OPT_BOOL, {(void*)&do_show_program_version},  "show ffprobe version" },
-    { "show_library_versions", OPT_BOOL, {(void*)&do_show_library_versions}, "show library versions" },
+    { "show_program_version",  0, {(void*)&opt_show_program_version},  "show ffprobe version" },
+    { "show_library_versions", 0, {(void*)&opt_show_library_versions}, "show library versions" },
     { "show_versions",         0, {(void*)&opt_show_versions}, "show program and library versions" },
     { "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
     { "private",           OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
@@ -2084,15 +2196,34 @@
     { NULL, },
 };
 
+static inline int check_section_show_entries(int section_id)
+{
+    int *id;
+    struct section *section = &sections[section_id];
+    if (sections[section_id].show_all_entries || sections[section_id].entries_to_show)
+        return 1;
+    for (id = section->children_ids; *id != -1; id++)
+        if (check_section_show_entries(*id))
+            return 1;
+    return 0;
+}
+
+#define SET_DO_SHOW(id, varname) do {                                   \
+        if (check_section_show_entries(SECTION_ID_##id))                \
+            do_show_##varname = 1;                                      \
+    } while (0)
+
 int main(int argc, char **argv)
 {
     const Writer *w;
     WriterContext *wctx;
     char *buf;
     char *w_name = NULL, *w_args = NULL;
-    int ret;
+    int ret, i;
 
     av_log_set_flags(AV_LOG_SKIP_REPEATED);
+    atexit(exit_program);
+
     options = real_options;
     parse_loglevel(argc, argv, options);
     av_register_all();
@@ -2105,6 +2236,16 @@
     show_banner(argc, argv, options);
     parse_options(NULL, argc, argv, options, opt_input_file);
 
+    /* mark things to show, based on -show_entries */
+    SET_DO_SHOW(ERROR, error);
+    SET_DO_SHOW(FORMAT, format);
+    SET_DO_SHOW(FRAMES, frames);
+    SET_DO_SHOW(LIBRARY_VERSIONS, library_versions);
+    SET_DO_SHOW(PACKETS, packets);
+    SET_DO_SHOW(PROGRAM_VERSION, program_version);
+    SET_DO_SHOW(STREAMS, streams);
+    SET_DO_SHOW(STREAM_DISPOSITION, stream_disposition);
+
     if (do_bitexact && (do_show_program_version || do_show_library_versions)) {
         av_log(NULL, AV_LOG_ERROR,
                "-bitexact and -show_program_version or -show_library_versions "
@@ -2117,6 +2258,10 @@
 
     if (!print_format)
         print_format = av_strdup("default");
+    if (!print_format) {
+        ret = AVERROR(ENOMEM);
+        goto end;
+    }
     w_name = av_strtok(print_format, "=", &buf);
     w_args = buf;
 
@@ -2157,7 +2302,8 @@
     av_freep(&print_format);
 
     uninit_opts();
-    av_dict_free(&fmt_entries_to_show);
+    for (i = 0; i < FF_ARRAY_ELEMS(sections); i++)
+        av_dict_free(&(sections[i].entries_to_show));
 
     avformat_network_deinit();
 
diff --git a/ffserver.c b/ffserver.c
index 480e6fc..3af481d 100644
--- a/ffserver.c
+++ b/ffserver.c
@@ -29,6 +29,7 @@
 #endif
 #include <string.h>
 #include <stdlib.h>
+#include <stdio.h>
 #include "libavformat/avformat.h"
 // FIXME those are internal headers, ffserver _really_ shouldn't use them
 #include "libavformat/ffm.h"
@@ -44,6 +45,7 @@
 #include "libavutil/avstring.h"
 #include "libavutil/lfg.h"
 #include "libavutil/dict.h"
+#include "libavutil/intreadwrite.h"
 #include "libavutil/mathematics.h"
 #include "libavutil/random_seed.h"
 #include "libavutil/parseutils.h"
@@ -305,12 +307,10 @@
                              HTTPContext *rtsp_c);
 
 static const char *my_program_name;
-static const char *my_program_dir;
 
 static const char *config_filename = "/etc/ffserver.conf";
 
 static int ffserver_debug;
-static int ffserver_daemon;
 static int no_launch;
 static int need_to_start_children;
 
@@ -328,12 +328,40 @@
 
 static FILE *logfile = NULL;
 
-/* FIXME: make ffserver work with IPv6 */
-void av_noreturn exit_program(int ret)
+static int64_t ffm_read_write_index(int fd)
 {
-    exit(ret);
+    uint8_t buf[8];
+
+    if (lseek(fd, 8, SEEK_SET) < 0)
+        return AVERROR(EIO);
+    if (read(fd, buf, 8) != 8)
+        return AVERROR(EIO);
+    return AV_RB64(buf);
 }
 
+static int ffm_write_write_index(int fd, int64_t pos)
+{
+    uint8_t buf[8];
+    int i;
+
+    for(i=0;i<8;i++)
+        buf[i] = (pos >> (56 - i * 8)) & 0xff;
+    if (lseek(fd, 8, SEEK_SET) < 0)
+        return AVERROR(EIO);
+    if (write(fd, buf, 8) != 8)
+        return AVERROR(EIO);
+    return 8;
+}
+
+static void ffm_set_write_index(AVFormatContext *s, int64_t pos,
+                                int64_t file_size)
+{
+    FFMContext *ffm = s->priv_data;
+    ffm->write_index = pos;
+    ffm->file_size = file_size;
+}
+
+/* FIXME: make ffserver work with IPv6 */
 /* resolve host with also IP address parsing */
 static int resolve_host(struct in_addr *sin_addr, const char *hostname)
 {
@@ -493,19 +521,12 @@
                     close(i);
 
                 if (!ffserver_debug) {
-                    i = open("/dev/null", O_RDWR);
-                    if (i != -1) {
-                        dup2(i, 0);
-                        dup2(i, 1);
-                        dup2(i, 2);
-                        close(i);
-                    }
-                }
-
-                /* This is needed to make relative pathnames work */
-                if (chdir(my_program_dir) < 0) {
-                    http_log("chdir failed\n");
-                    exit(1);
+                    if (!freopen("/dev/null", "r", stdin))
+                        http_log("failed to redirect STDIN to /dev/null\n;");
+                    if (!freopen("/dev/null", "w", stdout))
+                        http_log("failed to redirect STDOUT to /dev/null\n;");
+                    if (!freopen("/dev/null", "w", stderr))
+                        http_log("failed to redirect STDERR to /dev/null\n;");
                 }
 
                 signal(SIGPIPE, SIG_DFL);
@@ -557,7 +578,7 @@
     FFStream *stream;
     char session_id[32];
     HTTPContext *rtp_c;
-    struct sockaddr_in dest_addr;
+    struct sockaddr_in dest_addr = {0};
     int default_port, stream_index;
 
     default_port = 6000;
@@ -772,7 +793,7 @@
                        "\r\n"
                        "<html><head><title>Too busy</title></head><body>\r\n"
                        "<p>The server is too busy to serve your request at this time.</p>\r\n"
-                       "<p>The number of current connections is %d, and this exceeds the limit of %d.</p>\r\n"
+                       "<p>The number of current connections is %u, and this exceeds the limit of %u.</p>\r\n"
                        "</body></html>\r\n",
                        nb_connections, nb_max_connections);
     av_assert0(len < sizeof(buffer));
@@ -783,7 +804,8 @@
 static void new_connection(int server_fd, int is_rtsp)
 {
     struct sockaddr_in from_addr;
-    int fd, len;
+    socklen_t len;
+    int fd;
     HTTPContext *c = NULL;
 
     len = sizeof(from_addr);
@@ -899,6 +921,8 @@
 
     for(i=0; i<ctx->nb_streams; i++)
         av_free(ctx->streams[i]);
+    av_freep(&ctx->streams);
+    av_freep(&ctx->priv_data);
 
     if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
         current_bandwidth -= c->stream->bandwidth;
@@ -1466,7 +1490,8 @@
 /* parse http request and prepare header */
 static int http_parse_request(HTTPContext *c)
 {
-    char *p;
+    const char *p;
+    char *p1;
     enum RedirType redir_type;
     char cmd[32];
     char info[1024], filename[1024];
@@ -1477,10 +1502,10 @@
     FFStream *stream;
     int i;
     char ratebuf[32];
-    char *useragent = 0;
+    const char *useragent = 0;
 
     p = c->buffer;
-    get_word(cmd, sizeof(cmd), (const char **)&p);
+    get_word(cmd, sizeof(cmd), &p);
     av_strlcpy(c->method, cmd, sizeof(c->method));
 
     if (!strcmp(cmd, "GET"))
@@ -1490,7 +1515,7 @@
     else
         return -1;
 
-    get_word(url, sizeof(url), (const char **)&p);
+    get_word(url, sizeof(url), &p);
     av_strlcpy(c->url, url, sizeof(c->url));
 
     get_word(protocol, sizeof(protocol), (const char **)&p);
@@ -1503,10 +1528,10 @@
         http_log("%s - - New connection: %s %s\n", inet_ntoa(c->from_addr.sin_addr), cmd, url);
 
     /* find the filename and the optional info string in the request */
-    p = strchr(url, '?');
-    if (p) {
-        av_strlcpy(info, p, sizeof(info));
-        *p = '\0';
+    p1 = strchr(url, '?');
+    if (p1) {
+        av_strlcpy(info, p1, sizeof(info));
+        *p1 = '\0';
     } else
         info[0] = '\0';
 
@@ -1625,7 +1650,7 @@
     }
 
     if (redir_type != REDIR_NONE) {
-        char *hostinfo = 0;
+        const char *hostinfo = 0;
 
         for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
             if (av_strncasecmp(p, "Host:", 5) == 0) {
@@ -1707,7 +1732,8 @@
                     case REDIR_SDP:
                         {
                             uint8_t *sdp_data;
-                            int sdp_data_size, len;
+                            int sdp_data_size;
+                            socklen_t len;
                             struct sockaddr_in my_addr;
 
                             snprintf(q, c->buffer_size,
@@ -1758,7 +1784,7 @@
         if (!stream->is_feed) {
             /* However it might be a status report from WMP! Let us log the
              * data as it might come in handy one day. */
-            char *logline = 0;
+            const char *logline = 0;
             int client_id = 0;
 
             for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
@@ -2019,7 +2045,7 @@
             if (stream->pid) {
                 avio_printf(pb, "Running as pid %d.\n", stream->pid);
 
-#if defined(linux) && !defined(CONFIG_NOCUTILS)
+#if defined(linux)
                 {
                     FILE *pid_stat;
                     char ps_cmd[64];
@@ -2034,7 +2060,7 @@
                         char cpuperc[10];
                         char cpuused[64];
 
-                        if (fscanf(pid_stat, "%10s %64s", cpuperc,
+                        if (fscanf(pid_stat, "%9s %63s", cpuperc,
                                    cpuused) == 2) {
                             avio_printf(pb, "Currently using %s%% of the cpu. Total time used %s.\n",
                                          cpuperc, cpuused);
@@ -2990,7 +3016,8 @@
     char path1[1024];
     const char *path;
     uint8_t *content;
-    int content_length, len;
+    int content_length;
+    socklen_t len;
     struct sockaddr_in my_addr;
 
     /* find which url is asked */
@@ -3479,6 +3506,9 @@
 {
     AVStream *fst;
 
+    if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))
+        return NULL;
+
     fst = av_mallocz(sizeof(AVStream));
     if (!fst)
         return NULL;
@@ -3565,6 +3595,8 @@
     AVStream *st;
     const uint8_t *p;
 
+    infile->flags |= AVFMT_FLAG_NOFILLIN | AVFMT_FLAG_NOPARSE;
+
     mpeg4_count = 0;
     for(i=0;i<infile->nb_streams;i++) {
         st = infile->streams[i];
@@ -3578,7 +3610,7 @@
 
     printf("MPEG4 without extra data: trying to find header in %s\n", infile->filename);
     while (mpeg4_count > 0) {
-        if (av_read_packet(infile, &pkt) < 0)
+        if (av_read_frame(infile, &pkt) < 0)
             break;
         st = infile->streams[pkt.stream_index];
         if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
@@ -3826,6 +3858,9 @@
 {
     AVStream *st;
 
+    if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))
+        return;
+
     /* compute default parameters */
     switch(av->codec_type) {
     case AVMEDIA_TYPE_AUDIO:
@@ -4083,7 +4118,7 @@
                 ERROR("%s:%d: Invalid host/IP address: %s\n", arg);
             }
         } else if (!av_strcasecmp(cmd, "NoDaemon")) {
-            ffserver_daemon = 0;
+            // do nothing here, its the default now
         } else if (!av_strcasecmp(cmd, "RTSPPort")) {
             get_arg(arg, sizeof(arg), &p);
             val = atoi(arg);
@@ -4170,10 +4205,7 @@
                     feed->child_argv[i] = av_strdup(arg);
                 }
 
-                feed->child_argv[i] = av_malloc(30 + strlen(feed->filename));
-
-                snprintf(feed->child_argv[i], 30+strlen(feed->filename),
-                    "http://%s:%d/%s",
+                feed->child_argv[i] = av_asprintf("http://%s:%d/%s",
                         (my_http_addr.sin_addr.s_addr == INADDR_ANY) ? "127.0.0.1" :
                     inet_ntoa(my_http_addr.sin_addr),
                     ntohs(my_http_addr.sin_port), feed->filename);
@@ -4235,7 +4267,7 @@
                 stream = av_mallocz(sizeof(FFStream));
                 get_arg(stream->filename, sizeof(stream->filename), &p);
                 q = strrchr(stream->filename, '>');
-                if (*q)
+                if (q)
                     *q = '\0';
 
                 for (s = first_stream; s; s = s->next) {
@@ -4657,7 +4689,6 @@
 static void opt_debug(void)
 {
     ffserver_debug = 1;
-    ffserver_daemon = 0;
     logfilename[0] = '-';
 }
 
@@ -4688,8 +4719,6 @@
     show_banner(argc, argv, options);
 
     my_program_name = argv[0];
-    my_program_dir = getcwd(0, 0);
-    ffserver_daemon = 1;
 
     parse_options(NULL, argc, argv, options, NULL);
 
@@ -4721,37 +4750,9 @@
 
     compute_bandwidth();
 
-    /* put the process in background and detach it from its TTY */
-    if (ffserver_daemon) {
-        int pid;
-
-        pid = fork();
-        if (pid < 0) {
-            perror("fork");
-            exit(1);
-        } else if (pid > 0) {
-            /* parent : exit */
-            exit(0);
-        } else {
-            /* child */
-            setsid();
-            close(0);
-            open("/dev/null", O_RDWR);
-            if (strcmp(logfilename, "-") != 0) {
-                close(1);
-                dup(0);
-            }
-            close(2);
-            dup(0);
-        }
-    }
-
     /* signal init */
     signal(SIGPIPE, SIG_IGN);
 
-    if (ffserver_daemon)
-        chdir("/");
-
     if (http_server() < 0) {
         http_log("Could not start server\n");
         exit(1);
diff --git a/libavcodec/4xm.c b/libavcodec/4xm.c
index 1eaae48..85795f9 100644
--- a/libavcodec/4xm.c
+++ b/libavcodec/4xm.c
@@ -428,7 +428,7 @@
         bytestream_size = FFMAX(length - bitstream_size - wordstream_size, 0);
     }
 
-    if (bitstream_size > length ||
+    if (bitstream_size > length || bitstream_size >= INT_MAX/8 ||
         bytestream_size > length - bitstream_size ||
         wordstream_size > length - bytestream_size - bitstream_size ||
         extra > length - bytestream_size - bitstream_size - wordstream_size) {
@@ -811,6 +811,11 @@
             return AVERROR_INVALIDDATA;
         }
 
+        if (f->version <= 1) {
+            av_log(f->avctx, AV_LOG_ERROR, "cfrm in version %d\n", f->version);
+            return AVERROR_INVALIDDATA;
+        }
+
         for (i = 0; i < CFRAME_BUFFER_COUNT; i++)
             if (f->cfrm[i].id && f->cfrm[i].id < avctx->frame_number)
                 av_log(f->avctx, AV_LOG_ERROR, "lost c frame %d\n",
@@ -936,7 +941,7 @@
 
     if (avctx->extradata_size != 4 || !avctx->extradata) {
         av_log(avctx, AV_LOG_ERROR, "extradata wrong or missing\n");
-        return 1;
+        return AVERROR_INVALIDDATA;
     }
     if((avctx->width % 16) || (avctx->height % 16)) {
         av_log(avctx, AV_LOG_ERROR, "unsupported width/height\n");
@@ -950,9 +955,9 @@
     init_vlcs(f);
 
     if (f->version > 2)
-        avctx->pix_fmt = PIX_FMT_RGB565;
+        avctx->pix_fmt = AV_PIX_FMT_RGB565;
     else
-        avctx->pix_fmt = PIX_FMT_BGR555;
+        avctx->pix_fmt = AV_PIX_FMT_BGR555;
 
     return 0;
 }
diff --git a/libavcodec/8bps.c b/libavcodec/8bps.c
index af07c6a..f895ed3 100644
--- a/libavcodec/8bps.c
+++ b/libavcodec/8bps.c
@@ -40,8 +40,8 @@
 #include "avcodec.h"
 
 
-static const enum PixelFormat pixfmt_rgb24[] = {
-    PIX_FMT_BGR24, PIX_FMT_RGB32, PIX_FMT_NONE };
+static const enum AVPixelFormat pixfmt_rgb24[] = {
+    AV_PIX_FMT_BGR24, AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE };
 
 /*
  * Decoder context
@@ -98,6 +98,8 @@
         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];
+            if(lp - encoded + row*2 + 1 >= buf_size)
+                return -1;
             dlen = av_be2ne16(*(const unsigned short *)(lp + row * 2));
             /* Decode a row of this plane */
             while (dlen > 0) {
@@ -164,7 +166,7 @@
     avcodec_get_frame_defaults(&c->pic);
     switch (avctx->bits_per_coded_sample) {
     case 8:
-        avctx->pix_fmt = PIX_FMT_PAL8;
+        avctx->pix_fmt = AV_PIX_FMT_PAL8;
         c->planes      = 1;
         c->planemap[0] = 0; // 1st plane is palette indexes
         break;
@@ -176,7 +178,7 @@
         c->planemap[2] = 0; // 3rd plane is blue
         break;
     case 32:
-        avctx->pix_fmt = PIX_FMT_RGB32;
+        avctx->pix_fmt = AV_PIX_FMT_RGB32;
         c->planes      = 4;
 #if HAVE_BIGENDIAN
         c->planemap[0] = 1; // 1st plane is red
diff --git a/libavcodec/8svx.c b/libavcodec/8svx.c
index f41b19f..618ae87 100644
--- a/libavcodec/8svx.c
+++ b/libavcodec/8svx.c
@@ -44,13 +44,14 @@
 /** decoder context */
 typedef struct EightSvxContext {
     AVFrame frame;
+    uint8_t fib_acc[2];
     const int8_t *table;
 
-    /* buffer used to store the whole audio decoded/interleaved chunk,
-     * which is sent with the first packet */
-    uint8_t *samples;
-    int64_t samples_size;
-    int samples_idx;
+    /* buffer used to store the whole first packet.
+       data is only sent as one large packet */
+    uint8_t *data[2];
+    int data_size;
+    int data_idx;
 } EightSvxContext;
 
 static const int8_t fibonacci[16]   = { -34,  -21, -13,  -8, -5, -3, -2, -1, 0, 1, 2, 3, 5, 8,  13, 21 };
@@ -59,47 +60,26 @@
 #define MAX_FRAME_SIZE 2048
 
 /**
- * Interleave samples in buffer containing all left channel samples
- * at the beginning, and right channel samples at the end.
- * Each sample is assumed to be in signed 8-bit format.
- *
- * @param size the size in bytes of the dst and src buffer
- */
-static void interleave_stereo(uint8_t *dst, const uint8_t *src, int size)
-{
-    uint8_t *dst_end = dst + size;
-    size = size>>1;
-
-    while (dst < dst_end) {
-        *dst++ = *src;
-        *dst++ = *(src+size);
-        src++;
-    }
-}
-
-/**
  * Delta decode the compressed values in src, and put the resulting
- * decoded n samples in dst.
+ * decoded samples in dst.
  *
- * @param val starting value assumed by the delta sequence
+ * @param[in,out] state starting value. it is saved for use in the next call.
  * @param table delta sequence table
- * @return size in bytes of the decoded data, must be src_size*2
  */
-static int delta_decode(int8_t *dst, const uint8_t *src, int src_size,
-                        int8_t val, const int8_t *table)
+static void delta_decode(uint8_t *dst, const uint8_t *src, int src_size,
+                         uint8_t *state, const int8_t *table)
 {
-    int n = src_size;
-    int8_t *dst0 = dst;
+    uint8_t val = *state;
 
-    while (n--) {
+    while (src_size--) {
         uint8_t d = *src++;
-        val = av_clip(val + table[d & 0x0f], -127, 128);
+        val = av_clip_uint8(val + table[d & 0xF]);
         *dst++ = val;
-        val = av_clip(val + table[d >> 4]  , -127, 128);
+        val = av_clip_uint8(val + table[d >> 4]);
         *dst++ = val;
     }
 
-    return dst-dst0;
+    *state = val;
 }
 
 /** decode a frame */
@@ -107,79 +87,70 @@
                                  int *got_frame_ptr, AVPacket *avpkt)
 {
     EightSvxContext *esc = avctx->priv_data;
-    int n, out_data_size, ret;
-    uint8_t *src, *dst;
+    int buf_size;
+    int ch, ret;
+    int hdr_size = 2;
 
     /* decode and interleave the first packet */
-    if (!esc->samples && avpkt) {
-        uint8_t *deinterleaved_samples, *p = NULL;
-        int packet_size = avpkt->size;
+    if (!esc->data[0] && avpkt) {
+        int chan_size = avpkt->size / avctx->channels - hdr_size;
 
-        if (packet_size % avctx->channels) {
+        if (avpkt->size % avctx->channels) {
             av_log(avctx, AV_LOG_WARNING, "Packet with odd size, ignoring last byte\n");
-            if (packet_size < avctx->channels)
-                return packet_size;
-            packet_size -= packet_size % avctx->channels;
         }
-        esc->samples_size = !esc->table ?
-            packet_size : avctx->channels + (packet_size-avctx->channels) * 2;
-        if (!(esc->samples = av_malloc(esc->samples_size)))
-            return AVERROR(ENOMEM);
-
-        /* decompress */
-        if (esc->table) {
-            const uint8_t *buf = avpkt->data;
-            uint8_t *dst;
-            int buf_size = avpkt->size;
-            int i, n = esc->samples_size;
-
-            if (buf_size < 2) {
-                av_log(avctx, AV_LOG_ERROR, "packet size is too small\n");
-                return AVERROR(EINVAL);
-            }
-            if (!(deinterleaved_samples = av_mallocz(n)))
-                return AVERROR(ENOMEM);
-            dst = p = deinterleaved_samples;
-
-            /* the uncompressed starting value is contained in the first byte */
-            dst = deinterleaved_samples;
-            for (i = 0; i < avctx->channels; i++) {
-                delta_decode(dst, buf + 1, buf_size / avctx->channels - 1, buf[0], esc->table);
-                buf += buf_size / avctx->channels;
-                dst += n / avctx->channels - 1;
-            }
-        } else {
-            deinterleaved_samples = avpkt->data;
+        if (avpkt->size < (hdr_size + 1) * avctx->channels) {
+            av_log(avctx, AV_LOG_ERROR, "packet size is too small\n");
+            return AVERROR(EINVAL);
         }
 
+        esc->fib_acc[0] = avpkt->data[1] + 128;
         if (avctx->channels == 2)
-            interleave_stereo(esc->samples, deinterleaved_samples, esc->samples_size);
-        else
-            memcpy(esc->samples, deinterleaved_samples, esc->samples_size);
-        av_freep(&p);
+            esc->fib_acc[1] = avpkt->data[2+chan_size+1] + 128;
+
+        esc->data_idx  = 0;
+        esc->data_size = chan_size;
+        if (!(esc->data[0] = av_malloc(chan_size)))
+            return AVERROR(ENOMEM);
+        if (avctx->channels == 2) {
+            if (!(esc->data[1] = av_malloc(chan_size))) {
+                av_freep(&esc->data[0]);
+                return AVERROR(ENOMEM);
+            }
+        }
+        memcpy(esc->data[0], &avpkt->data[hdr_size], chan_size);
+        if (avctx->channels == 2)
+            memcpy(esc->data[1], &avpkt->data[2*hdr_size+chan_size], chan_size);
+    }
+    if (!esc->data[0]) {
+        av_log(avctx, AV_LOG_ERROR, "unexpected empty packet\n");
+        return AVERROR(EINVAL);
+    }
+
+    /* decode next piece of data from the buffer */
+    buf_size = FFMIN(MAX_FRAME_SIZE, esc->data_size - esc->data_idx);
+    if (buf_size <= 0) {
+        *got_frame_ptr = 0;
+        return avpkt->size;
     }
 
     /* get output buffer */
-    av_assert1(!(esc->samples_size % avctx->channels || esc->samples_idx % avctx->channels));
-    esc->frame.nb_samples = FFMIN(MAX_FRAME_SIZE, esc->samples_size - esc->samples_idx)  / avctx->channels;
+    esc->frame.nb_samples = buf_size * 2;
     if ((ret = avctx->get_buffer(avctx, &esc->frame)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         return ret;
     }
 
+    for (ch = 0; ch < avctx->channels; ch++) {
+        delta_decode(esc->frame.data[ch], &esc->data[ch][esc->data_idx],
+                     buf_size, &esc->fib_acc[ch], esc->table);
+    }
+
+    esc->data_idx += buf_size;
+
     *got_frame_ptr   = 1;
     *(AVFrame *)data = esc->frame;
 
-    dst = esc->frame.data[0];
-    src = esc->samples + esc->samples_idx;
-    out_data_size = esc->frame.nb_samples * avctx->channels;
-    for (n = out_data_size; n > 0; n--)
-        *dst++ = *src++ + 128;
-    esc->samples_idx += out_data_size;
-
-    return esc->table ?
-        (avctx->frame_number == 0)*2 + out_data_size / 2 :
-        out_data_size;
+    return ((avctx->frame_number == 0)*hdr_size + buf_size)*avctx->channels;
 }
 
 static av_cold int eightsvx_decode_init(AVCodecContext *avctx)
@@ -194,13 +165,11 @@
     switch (avctx->codec->id) {
     case AV_CODEC_ID_8SVX_FIB: esc->table = fibonacci;    break;
     case AV_CODEC_ID_8SVX_EXP: esc->table = exponential;  break;
-    case AV_CODEC_ID_PCM_S8_PLANAR:
-    case AV_CODEC_ID_8SVX_RAW: esc->table = NULL;         break;
     default:
         av_log(avctx, AV_LOG_ERROR, "Invalid codec id %d.\n", avctx->codec->id);
         return AVERROR_INVALIDDATA;
     }
-    avctx->sample_fmt = AV_SAMPLE_FMT_U8;
+    avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
 
     avcodec_get_frame_defaults(&esc->frame);
     avctx->coded_frame = &esc->frame;
@@ -212,9 +181,10 @@
 {
     EightSvxContext *esc = avctx->priv_data;
 
-    av_freep(&esc->samples);
-    esc->samples_size = 0;
-    esc->samples_idx = 0;
+    av_freep(&esc->data[0]);
+    av_freep(&esc->data[1]);
+    esc->data_size = 0;
+    esc->data_idx = 0;
 
     return 0;
 }
@@ -230,6 +200,8 @@
   .close          = eightsvx_decode_close,
   .capabilities   = CODEC_CAP_DR1,
   .long_name      = NULL_IF_CONFIG_SMALL("8SVX fibonacci"),
+  .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
+                                                    AV_SAMPLE_FMT_NONE },
 };
 #endif
 #if CONFIG_EIGHTSVX_EXP_DECODER
@@ -243,18 +215,7 @@
   .close          = eightsvx_decode_close,
   .capabilities   = CODEC_CAP_DR1,
   .long_name      = NULL_IF_CONFIG_SMALL("8SVX exponential"),
-};
-#endif
-#if CONFIG_PCM_S8_PLANAR_DECODER
-AVCodec ff_pcm_s8_planar_decoder = {
-    .name           = "pcm_s8_planar",
-    .type           = AVMEDIA_TYPE_AUDIO,
-    .id             = AV_CODEC_ID_PCM_S8_PLANAR,
-    .priv_data_size = sizeof(EightSvxContext),
-    .init           = eightsvx_decode_init,
-    .close          = eightsvx_decode_close,
-    .decode         = eightsvx_decode_frame,
-    .capabilities   = CODEC_CAP_DR1,
-    .long_name      = NULL_IF_CONFIG_SMALL("PCM signed 8-bit planar"),
+  .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
+                                                    AV_SAMPLE_FMT_NONE },
 };
 #endif
diff --git a/libavcodec/Makefile b/libavcodec/Makefile
index 34737f2..1d4cb59 100644
--- a/libavcodec/Makefile
+++ b/libavcodec/Makefile
@@ -16,6 +16,7 @@
 OBJS = allcodecs.o                                                      \
        audioconvert.o                                                   \
        avpacket.o                                                       \
+       avpicture.o                                                      \
        bitstream.o                                                      \
        bitstream_filter.o                                               \
        codec_desc.o                                                     \
@@ -24,6 +25,8 @@
        fmtconvert.o                                                     \
        imgconvert.o                                                     \
        jrevdct.o                                                        \
+       log2_tab.o                                                       \
+       mathtables.o                                                     \
        options.o                                                        \
        parser.o                                                         \
        raw.o                                                            \
@@ -53,6 +56,8 @@
 OBJS-$(CONFIG_LPC)                     += lpc.o
 OBJS-$(CONFIG_LSP)                     += lsp.o
 OBJS-$(CONFIG_MDCT)                    += mdct_fixed.o mdct_float.o
+OBJS-$(CONFIG_MPEGAUDIO)               += mpegaudio.o mpegaudiodata.o   \
+                                          mpegaudiodecheader.o
 OBJS-$(CONFIG_MPEGAUDIODSP)            += mpegaudiodsp.o                \
                                           mpegaudiodsp_data.o           \
                                           mpegaudiodsp_fixed.o          \
@@ -105,10 +110,10 @@
 OBJS-$(CONFIG_APE_DECODER)             += apedec.o
 OBJS-$(CONFIG_ASS_DECODER)             += assdec.o ass.o ass_split.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
-OBJS-$(CONFIG_ASV2_ENCODER)            += asv1.o mpeg12data.o
+OBJS-$(CONFIG_ASV1_DECODER)            += asvdec.o asv.o mpeg12data.o
+OBJS-$(CONFIG_ASV1_ENCODER)            += asvenc.o asv.o mpeg12data.o
+OBJS-$(CONFIG_ASV2_DECODER)            += asvdec.o asv.o mpeg12data.o
+OBJS-$(CONFIG_ASV2_ENCODER)            += asvenc.o asv.o mpeg12data.o
 OBJS-$(CONFIG_ATRAC1_DECODER)          += atrac1.o atrac.o
 OBJS-$(CONFIG_ATRAC3_DECODER)          += atrac3.o atrac.o
 OBJS-$(CONFIG_AURA_DECODER)            += cyuv.o
@@ -131,6 +136,7 @@
 OBJS-$(CONFIG_BMP_ENCODER)             += bmpenc.o
 OBJS-$(CONFIG_BMV_VIDEO_DECODER)       += bmv.o
 OBJS-$(CONFIG_BMV_AUDIO_DECODER)       += bmv.o
+OBJS-$(CONFIG_BRENDER_PIX_DECODER)     += brender_pix.o
 OBJS-$(CONFIG_C93_DECODER)             += c93.o
 OBJS-$(CONFIG_CAVS_DECODER)            += cavs.o cavsdec.o cavsdsp.o \
                                           cavsdata.o mpeg12data.o
@@ -141,6 +147,8 @@
 OBJS-$(CONFIG_CLJR_ENCODER)            += cljr.o
 OBJS-$(CONFIG_CLLC_DECODER)            += cllc.o
 OBJS-$(CONFIG_COOK_DECODER)            += cook.o
+OBJS-$(CONFIG_COMFORTNOISE_DECODER)    += cngdec.o celp_filters.o
+OBJS-$(CONFIG_COMFORTNOISE_ENCODER)    += cngenc.o
 OBJS-$(CONFIG_CPIA_DECODER)            += cpia.o
 OBJS-$(CONFIG_CSCD_DECODER)            += cscd.o
 OBJS-$(CONFIG_CYUV_DECODER)            += cyuv.o
@@ -179,13 +187,13 @@
 OBJS-$(CONFIG_ESCAPE124_DECODER)       += escape124.o
 OBJS-$(CONFIG_ESCAPE130_DECODER)       += escape130.o
 OBJS-$(CONFIG_EXR_DECODER)             += exr.o
-OBJS-$(CONFIG_FFV1_DECODER)            += ffv1.o
-OBJS-$(CONFIG_FFV1_ENCODER)            += ffv1.o
+OBJS-$(CONFIG_FFV1_DECODER)            += ffv1dec.o ffv1.o
+OBJS-$(CONFIG_FFV1_ENCODER)            += ffv1enc.o ffv1.o
 OBJS-$(CONFIG_FFVHUFF_DECODER)         += huffyuv.o
 OBJS-$(CONFIG_FFVHUFF_ENCODER)         += huffyuv.o
 OBJS-$(CONFIG_FFWAVESYNTH_DECODER)     += ffwavesynth.o
 OBJS-$(CONFIG_FLAC_DECODER)            += flacdec.o flacdata.o flac.o flacdsp.o
-OBJS-$(CONFIG_FLAC_ENCODER)            += flacenc.o flacdata.o flac.o vorbis_data.o
+OBJS-$(CONFIG_FLAC_ENCODER)            += flacenc.o flacdata.o flac.o flacdsp.o vorbis_data.o
 OBJS-$(CONFIG_FLASHSV_DECODER)         += flashsv.o
 OBJS-$(CONFIG_FLASHSV_ENCODER)         += flashsvenc.o
 OBJS-$(CONFIG_FLASHSV2_ENCODER)        += flashsv2enc.o
@@ -257,30 +265,18 @@
 OBJS-$(CONFIG_MOTIONPIXELS_DECODER)    += motionpixels.o
 OBJS-$(CONFIG_MOVTEXT_DECODER)         += movtextdec.o ass.o
 OBJS-$(CONFIG_MOVTEXT_ENCODER)         += movtextenc.o ass_split.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_MP1_DECODER)             += mpegaudiodec.o
+OBJS-$(CONFIG_MP1FLOAT_DECODER)        += mpegaudiodec_float.o
+OBJS-$(CONFIG_MP2_DECODER)             += mpegaudiodec.o
 OBJS-$(CONFIG_MP2_ENCODER)             += mpegaudioenc.o mpegaudio.o \
                                           mpegaudiodata.o mpegaudiodsp_data.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_MP2FLOAT_DECODER)        += mpegaudiodec_float.o
+OBJS-$(CONFIG_MP3_DECODER)             += mpegaudiodec.o
+OBJS-$(CONFIG_MP3ADU_DECODER)          += mpegaudiodec.o
+OBJS-$(CONFIG_MP3ADUFLOAT_DECODER)     += mpegaudiodec_float.o
+OBJS-$(CONFIG_MP3FLOAT_DECODER)        += mpegaudiodec_float.o
+OBJS-$(CONFIG_MP3ON4_DECODER)          += mpegaudiodec.o mpeg4audio.o
+OBJS-$(CONFIG_MP3ON4FLOAT_DECODER)     += mpegaudiodec_float.o mpeg4audio.o
 OBJS-$(CONFIG_MPC7_DECODER)            += mpc7.o mpc.o
 OBJS-$(CONFIG_MPC8_DECODER)            += mpc8.o mpc.o
 OBJS-$(CONFIG_MPEGVIDEO_DECODER)       += mpeg12.o mpeg12data.o \
@@ -410,8 +406,11 @@
                                           h264_loopfilter.o h264_direct.o     \
                                           h264_sei.o h264_ps.o h264_refs.o    \
                                           h264_cavlc.o h264_cabac.o cabac.o
+OBJS-$(CONFIG_TEXT_DECODER)            += textdec.o ass.o
+OBJS-$(CONFIG_TAK_DECODER)             += takdec.o tak.o
 OBJS-$(CONFIG_TARGA_DECODER)           += targa.o
 OBJS-$(CONFIG_TARGA_ENCODER)           += targaenc.o rle.o
+OBJS-$(CONFIG_TARGA_Y216_DECODER)      += targa_y216dec.o
 OBJS-$(CONFIG_THEORA_DECODER)          += xiph.o
 OBJS-$(CONFIG_THP_DECODER)             += mjpegdec.o mjpeg.o
 OBJS-$(CONFIG_TIERTEXSEQVIDEO_DECODER) += tiertexseqv.o
@@ -488,6 +487,8 @@
 OBJS-$(CONFIG_XBIN_DECODER)            += bintext.o cga_data.o
 OBJS-$(CONFIG_XBM_DECODER)             += xbmdec.o
 OBJS-$(CONFIG_XBM_ENCODER)             += xbmenc.o
+OBJS-$(CONFIG_XFACE_DECODER)           += xfacedec.o xface.o
+OBJS-$(CONFIG_XFACE_ENCODER)           += xfaceenc.o xface.o
 OBJS-$(CONFIG_XL_DECODER)              += xl.o
 OBJS-$(CONFIG_XSUB_DECODER)            += xsubdec.o
 OBJS-$(CONFIG_XSUB_ENCODER)            += xsubenc.o
@@ -509,7 +510,6 @@
 OBJS-$(CONFIG_PCM_ALAW_ENCODER)           += pcm.o
 OBJS-$(CONFIG_PCM_BLURAY_DECODER)         += pcm-mpeg.o
 OBJS-$(CONFIG_PCM_DVD_DECODER)            += pcm.o
-OBJS-$(CONFIG_PCM_DVD_ENCODER)            += pcm.o
 OBJS-$(CONFIG_PCM_F32BE_DECODER)          += pcm.o
 OBJS-$(CONFIG_PCM_F32BE_ENCODER)          += pcm.o
 OBJS-$(CONFIG_PCM_F32LE_DECODER)          += pcm.o
@@ -523,22 +523,30 @@
 OBJS-$(CONFIG_PCM_MULAW_ENCODER)          += pcm.o
 OBJS-$(CONFIG_PCM_S8_DECODER)             += pcm.o
 OBJS-$(CONFIG_PCM_S8_ENCODER)             += pcm.o
-OBJS-$(CONFIG_PCM_S8_PLANAR_DECODER)      += 8svx.o
+OBJS-$(CONFIG_PCM_S8_PLANAR_DECODER)      += pcm.o
+OBJS-$(CONFIG_PCM_S8_PLANAR_ENCODER)      += pcm.o
 OBJS-$(CONFIG_PCM_S16BE_DECODER)          += pcm.o
 OBJS-$(CONFIG_PCM_S16BE_ENCODER)          += pcm.o
+OBJS-$(CONFIG_PCM_S16BE_PLANAR_DECODER)   += pcm.o
+OBJS-$(CONFIG_PCM_S16BE_PLANAR_ENCODER)   += pcm.o
 OBJS-$(CONFIG_PCM_S16LE_DECODER)          += pcm.o
 OBJS-$(CONFIG_PCM_S16LE_ENCODER)          += pcm.o
 OBJS-$(CONFIG_PCM_S16LE_PLANAR_DECODER)   += pcm.o
+OBJS-$(CONFIG_PCM_S16LE_PLANAR_ENCODER)   += pcm.o
 OBJS-$(CONFIG_PCM_S24BE_DECODER)          += pcm.o
 OBJS-$(CONFIG_PCM_S24BE_ENCODER)          += pcm.o
 OBJS-$(CONFIG_PCM_S24DAUD_DECODER)        += pcm.o
 OBJS-$(CONFIG_PCM_S24DAUD_ENCODER)        += pcm.o
 OBJS-$(CONFIG_PCM_S24LE_DECODER)          += pcm.o
 OBJS-$(CONFIG_PCM_S24LE_ENCODER)          += pcm.o
+OBJS-$(CONFIG_PCM_S24LE_PLANAR_DECODER)   += pcm.o
+OBJS-$(CONFIG_PCM_S24LE_PLANAR_ENCODER)   += pcm.o
 OBJS-$(CONFIG_PCM_S32BE_DECODER)          += pcm.o
 OBJS-$(CONFIG_PCM_S32BE_ENCODER)          += pcm.o
 OBJS-$(CONFIG_PCM_S32LE_DECODER)          += pcm.o
 OBJS-$(CONFIG_PCM_S32LE_ENCODER)          += pcm.o
+OBJS-$(CONFIG_PCM_S32LE_PLANAR_DECODER)   += pcm.o
+OBJS-$(CONFIG_PCM_S32LE_PLANAR_ENCODER)   += pcm.o
 OBJS-$(CONFIG_PCM_U8_DECODER)             += pcm.o
 OBJS-$(CONFIG_PCM_U8_ENCODER)             += pcm.o
 OBJS-$(CONFIG_PCM_U16BE_DECODER)          += pcm.o
@@ -558,6 +566,7 @@
 OBJS-$(CONFIG_ADPCM_4XM_DECODER)          += adpcm.o adpcm_data.o
 OBJS-$(CONFIG_ADPCM_ADX_DECODER)          += adxdec.o adx.o
 OBJS-$(CONFIG_ADPCM_ADX_ENCODER)          += adxenc.o adx.o
+OBJS-$(CONFIG_ADPCM_AFC_DECODER)          += adpcm.o adpcm_data.o
 OBJS-$(CONFIG_ADPCM_CT_DECODER)           += adpcm.o adpcm_data.o
 OBJS-$(CONFIG_ADPCM_EA_DECODER)           += adpcm.o adpcm_data.o
 OBJS-$(CONFIG_ADPCM_EA_MAXIS_XA_DECODER)  += adpcm.o adpcm_data.o
@@ -576,6 +585,7 @@
 OBJS-$(CONFIG_ADPCM_IMA_EA_EACS_DECODER)  += adpcm.o adpcm_data.o
 OBJS-$(CONFIG_ADPCM_IMA_EA_SEAD_DECODER)  += adpcm.o adpcm_data.o
 OBJS-$(CONFIG_ADPCM_IMA_ISS_DECODER)      += adpcm.o adpcm_data.o
+OBJS-$(CONFIG_ADPCM_IMA_OKI_DECODER)      += adpcm.o adpcm_data.o
 OBJS-$(CONFIG_ADPCM_IMA_QT_DECODER)       += adpcm.o adpcm_data.o
 OBJS-$(CONFIG_ADPCM_IMA_QT_ENCODER)       += adpcmenc.o adpcm_data.o
 OBJS-$(CONFIG_ADPCM_IMA_SMJPEG_DECODER)   += adpcm.o adpcm_data.o
@@ -657,7 +667,10 @@
 OBJS-$(CONFIG_LIBOPENCORE_AMRWB_DECODER)  += libopencore-amr.o
 OBJS-$(CONFIG_LIBOPENJPEG_DECODER)        += libopenjpegdec.o
 OBJS-$(CONFIG_LIBOPENJPEG_ENCODER)        += libopenjpegenc.o
-OBJS-$(CONFIG_LIBOPUS_DECODER)            += libopusdec.o vorbis_data.o
+OBJS-$(CONFIG_LIBOPUS_DECODER)            += libopusdec.o libopus.o     \
+                                             vorbis_data.o
+OBJS-$(CONFIG_LIBOPUS_ENCODER)            += libopusenc.o libopus.o     \
+                                             vorbis_data.o audio_frame_queue.o
 OBJS-$(CONFIG_LIBSCHROEDINGER_DECODER)    += libschroedingerdec.o \
                                              libschroedinger.o
 OBJS-$(CONFIG_LIBSCHROEDINGER_ENCODER)    += libschroedingerenc.o \
@@ -719,6 +732,7 @@
 OBJS-$(CONFIG_PNM_PARSER)              += pnm_parser.o pnm.o
 OBJS-$(CONFIG_RV30_PARSER)             += rv34_parser.o
 OBJS-$(CONFIG_RV40_PARSER)             += rv34_parser.o
+OBJS-$(CONFIG_TAK_PARSER)              += tak_parser.o tak.o
 OBJS-$(CONFIG_VC1_PARSER)              += vc1_parser.o vc1.o vc1data.o \
                                           msmpeg4.o msmpeg4data.o mpeg4video.o \
                                           h263.o
@@ -748,12 +762,6 @@
 OBJS-$(HAVE_W32THREADS)                += pthread.o frame_thread_encoder.o
 OBJS-$(HAVE_OS2THREADS)                += pthread.o frame_thread_encoder.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
-
 SKIPHEADERS                            += %_tablegen.h                  \
                                           %_tables.h                    \
                                           aac_tablegen_decl.h           \
@@ -778,6 +786,7 @@
             fft-fixed                                                   \
             golomb                                                      \
             iirfilter                                                   \
+            imgconvert                                                  \
             rangecoder                                                  \
             snowenc                                                     \
 
diff --git a/libavcodec/a64enc.h b/libavcodec/a64enc.h
index 4868461..2895995 100644
--- a/libavcodec/a64enc.h
+++ b/libavcodec/a64enc.h
@@ -41,7 +41,7 @@
     AVLFG randctx;
     int mc_lifetime;
     int mc_use_5col;
-    int mc_frame_counter;
+    unsigned mc_frame_counter;
     int *mc_meta_charset;
     int *mc_charmap;
     int *mc_best_cb;
diff --git a/libavcodec/a64multienc.c b/libavcodec/a64multienc.c
index 658a8ab..0f6cc76 100644
--- a/libavcodec/a64multienc.c
+++ b/libavcodec/a64multienc.c
@@ -378,7 +378,7 @@
     .init           = a64multi_init_encoder,
     .encode2        = a64multi_encode_frame,
     .close          = a64multi_close_encoder,
-    .pix_fmts       = (const enum PixelFormat[]) {PIX_FMT_GRAY8, PIX_FMT_NONE},
+    .pix_fmts       = (const enum AVPixelFormat[]) {AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE},
     .long_name      = NULL_IF_CONFIG_SMALL("Multicolor charset for Commodore 64"),
     .capabilities   = CODEC_CAP_DELAY,
 };
@@ -392,7 +392,7 @@
     .init           = a64multi_init_encoder,
     .encode2        = a64multi_encode_frame,
     .close          = a64multi_close_encoder,
-    .pix_fmts       = (const enum PixelFormat[]) {PIX_FMT_GRAY8, PIX_FMT_NONE},
+    .pix_fmts       = (const enum AVPixelFormat[]) {AV_PIX_FMT_GRAY8, AV_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/aac.h b/libavcodec/aac.h
index a1e91b0..9ceccf8 100644
--- a/libavcodec/aac.h
+++ b/libavcodec/aac.h
@@ -113,7 +113,7 @@
     OC_LOCKED,      ///< Output configuration locked in place
 };
 
-typedef struct {
+typedef struct OutputConfiguration {
     MPEG4AudioConfig m4ac;
     uint8_t layout_map[MAX_ELEM_ID*4][3];
     int layout_map_tags;
@@ -125,7 +125,7 @@
 /**
  * Predictor State
  */
-typedef struct {
+typedef struct PredictorState {
     float cor0;
     float cor1;
     float var0;
@@ -141,12 +141,11 @@
 #define SCALE_MAX_POS   255    ///< scalefactor index maximum value
 #define SCALE_MAX_DIFF   60    ///< maximum scalefactor difference allowed by standard
 #define SCALE_DIFF_ZERO  60    ///< codebook index corresponding to zero scalefactor indices difference
-#define POW_SF2_ZERO    200    ///< ff_aac_pow2sf_tab index corresponding to pow(2, 0);
 
 /**
  * Long Term Prediction
  */
-typedef struct {
+typedef struct LongTermPrediction {
     int8_t present;
     int16_t lag;
     float coef;
@@ -156,7 +155,7 @@
 /**
  * Individual Channel Stream
  */
-typedef struct {
+typedef struct IndividualChannelStream {
     uint8_t max_sfb;            ///< number of scalefactor bands per group
     enum WindowSequence window_sequence[2];
     uint8_t use_kb_window[2];   ///< If set, use Kaiser-Bessel window, otherwise use a sinus window.
@@ -177,7 +176,7 @@
 /**
  * Temporal Noise Shaping
  */
-typedef struct {
+typedef struct TemporalNoiseShaping {
     int present;
     int n_filt[8];
     int length[8][4];
@@ -189,7 +188,7 @@
 /**
  * Dynamic Range Control - decoded from the bitstream but not processed further.
  */
-typedef struct {
+typedef struct DynamicRangeControl {
     int pce_instance_tag;                           ///< Indicates with which program the DRC info is associated.
     int dyn_rng_sgn[17];                            ///< DRC sign information; 0 - positive, 1 - negative
     int dyn_rng_ctl[17];                            ///< DRC magnitude information
@@ -202,7 +201,7 @@
                                                      */
 } DynamicRangeControl;
 
-typedef struct {
+typedef struct Pulse {
     int num_pulse;
     int start;
     int pos[4];
@@ -212,7 +211,7 @@
 /**
  * coupling parameters
  */
-typedef struct {
+typedef struct ChannelCoupling {
     enum CouplingPoint coupling_point;  ///< The point during decoding at which coupling is applied.
     int num_coupled;       ///< number of target elements
     enum RawDataBlockType type[8];   ///< Type of channel element to be coupled - SCE or CPE.
@@ -226,7 +225,7 @@
 /**
  * Single Channel Element - used for both SCE and LFE elements.
  */
-typedef struct {
+typedef struct SingleChannelElement {
     IndividualChannelStream ics;
     TemporalNoiseShaping tns;
     Pulse pulse;
@@ -237,15 +236,16 @@
     uint8_t zeroes[128];                            ///< band is not coded (used by encoder)
     DECLARE_ALIGNED(32, float,   coeffs)[1024];     ///< coefficients for IMDCT
     DECLARE_ALIGNED(32, float,   saved)[1024];      ///< overlap
-    DECLARE_ALIGNED(32, float,   ret)[2048];        ///< PCM output
+    DECLARE_ALIGNED(32, float,   ret_buf)[2048];    ///< PCM output buffer
     DECLARE_ALIGNED(16, float,   ltp_state)[3072];  ///< time signal for LTP
     PredictorState predictor_state[MAX_PREDICTORS];
+    float *ret;                                     ///< PCM output
 } SingleChannelElement;
 
 /**
  * channel element - generic struct for SCE/CPE/CCE/LFE
  */
-typedef struct {
+typedef struct ChannelElement {
     // CPE specific
     int common_window;        ///< Set if channels share a common 'IndividualChannelStream' in bitstream.
     int     ms_mode;          ///< Signals mid/side stereo flags coding mode (used by encoder)
@@ -260,7 +260,7 @@
 /**
  * main AAC context
  */
-typedef struct {
+typedef struct AACContext {
     AVCodecContext *avctx;
     AVFrame frame;
 
@@ -298,10 +298,10 @@
     /** @} */
 
     /**
-     * @name Members used for output interleaving
+     * @name Members used for output
      * @{
      */
-    float *output_data[MAX_CHANNELS];                 ///< Points to each element's 'ret' buffer (PCM output).
+    SingleChannelElement *output_element[MAX_CHANNELS]; ///< Points to each SingleChannelElement
     /** @} */
 
 
diff --git a/libavcodec/aac_adtstoasc_bsf.c b/libavcodec/aac_adtstoasc_bsf.c
index 3cb065e..e6b32ce 100644
--- a/libavcodec/aac_adtstoasc_bsf.c
+++ b/libavcodec/aac_adtstoasc_bsf.c
@@ -61,8 +61,8 @@
     }
 
     if (!hdr.crc_absent && hdr.num_aac_frames > 1) {
-        av_log_missing_feature(avctx, "Multiple RDBs per frame with CRC is", 0);
-        return -1;
+        av_log_missing_feature(avctx, "Multiple RDBs per frame with CRC", 0);
+        return AVERROR_PATCHWELCOME;
     }
 
     buf      += AAC_ADTS_HEADER_SIZE + 2*!hdr.crc_absent;
@@ -74,8 +74,8 @@
         if (!hdr.chan_config) {
             init_get_bits(&gb, buf, buf_size * 8);
             if (get_bits(&gb, 3) != 5) {
-                av_log_missing_feature(avctx, "PCE based channel configuration, where the PCE is not the first syntax element is", 0);
-                return -1;
+                av_log_missing_feature(avctx, "PCE based channel configuration, where the PCE is not the first syntax element", 0);
+                return AVERROR_PATCHWELCOME;
             }
             init_put_bits(&pb, pce_data, MAX_PCE_SIZE);
             pce_size = avpriv_copy_pce_data(&pb, &gb)/8;
diff --git a/libavcodec/aac_tablegen.h b/libavcodec/aac_tablegen.h
index 7afa466..2b080ba 100644
--- a/libavcodec/aac_tablegen.h
+++ b/libavcodec/aac_tablegen.h
@@ -29,7 +29,6 @@
 #include "libavcodec/aac_tables.h"
 #else
 #include "libavutil/mathematics.h"
-#include "aac.h"
 float ff_aac_pow2sf_tab[428];
 
 void ff_aac_tableinit(void)
diff --git a/libavcodec/aac_tablegen_decl.h b/libavcodec/aac_tablegen_decl.h
index 0d86e80..5105dae 100644
--- a/libavcodec/aac_tablegen_decl.h
+++ b/libavcodec/aac_tablegen_decl.h
@@ -23,6 +23,8 @@
 #ifndef AVCODEC_AAC_TABLEGEN_DECL_H
 #define AVCODEC_AAC_TABLEGEN_DECL_H
 
+#define POW_SF2_ZERO    200    ///< ff_aac_pow2sf_tab index corresponding to pow(2, 0);
+
 #if CONFIG_HARDCODED_TABLES
 #define ff_aac_tableinit()
 extern const float ff_aac_pow2sf_tab[428];
diff --git a/libavcodec/aacadtsdec.h b/libavcodec/aacadtsdec.h
index fb2cbd9..d0584ef 100644
--- a/libavcodec/aacadtsdec.h
+++ b/libavcodec/aacadtsdec.h
@@ -28,7 +28,7 @@
 
 #define AAC_ADTS_HEADER_SIZE 7
 
-typedef struct {
+typedef struct AACADTSHeaderInfo {
     uint32_t sample_rate;
     uint32_t samples;
     uint32_t bit_rate;
diff --git a/libavcodec/aacdec.c b/libavcodec/aacdec.c
index 600af79..719426c 100644
--- a/libavcodec/aacdec.c
+++ b/libavcodec/aacdec.c
@@ -153,10 +153,10 @@
                 av_log(ac->avctx, AV_LOG_ERROR, "Too many channels\n");
                 return AVERROR_INVALIDDATA;
             }
-            ac->output_data[(*channels)++] = ac->che[type][id]->ch[0].ret;
+            ac->output_element[(*channels)++] = &ac->che[type][id]->ch[0];
             if (type == TYPE_CPE ||
                 (type == TYPE_SCE && ac->oc[1].m4ac.ps == 1)) {
-                ac->output_data[(*channels)++] = ac->che[type][id]->ch[1].ret;
+                ac->output_element[(*channels)++] = &ac->che[type][id]->ch[1];
             }
         }
     } else {
@@ -167,6 +167,38 @@
     return 0;
 }
 
+static int frame_configure_elements(AVCodecContext *avctx)
+{
+    AACContext *ac = avctx->priv_data;
+    int type, id, ch, ret;
+
+    /* set channel pointers to internal buffers by default */
+    for (type = 0; type < 4; type++) {
+        for (id = 0; id < MAX_ELEM_ID; id++) {
+            ChannelElement *che = ac->che[type][id];
+            if (che) {
+                che->ch[0].ret = che->ch[0].ret_buf;
+                che->ch[1].ret = che->ch[1].ret_buf;
+            }
+        }
+    }
+
+    /* get output buffer */
+    ac->frame.nb_samples = 2048;
+    if ((ret = avctx->get_buffer(avctx, &ac->frame)) < 0) {
+        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+        return ret;
+    }
+
+    /* map output channel pointers to AVFrame data */
+    for (ch = 0; ch < avctx->channels; ch++) {
+        if (ac->output_element[ch])
+            ac->output_element[ch]->ret = (float *)ac->frame.extended_data[ch];
+    }
+
+    return 0;
+}
+
 struct elem_to_channel {
     uint64_t av_position;
     uint8_t syn_ele;
@@ -175,7 +207,7 @@
 };
 
 static int assign_pair(struct elem_to_channel e2c_vec[MAX_ELEM_ID],
-    uint8_t (*layout_map)[3], int offset, int tags, uint64_t left,
+                       uint8_t (*layout_map)[3], int offset, uint64_t left,
     uint64_t right, int pos)
 {
     if (layout_map[offset][0] == TYPE_CPE) {
@@ -257,21 +289,21 @@
         num_front_channels--;
     }
     if (num_front_channels >= 4) {
-        i += assign_pair(e2c_vec, layout_map, i, tags,
+        i += assign_pair(e2c_vec, layout_map, i,
                          AV_CH_FRONT_LEFT_OF_CENTER,
                          AV_CH_FRONT_RIGHT_OF_CENTER,
                          AAC_CHANNEL_FRONT);
         num_front_channels -= 2;
     }
     if (num_front_channels >= 2) {
-        i += assign_pair(e2c_vec, layout_map, i, tags,
+        i += assign_pair(e2c_vec, layout_map, i,
                          AV_CH_FRONT_LEFT,
                          AV_CH_FRONT_RIGHT,
                          AAC_CHANNEL_FRONT);
         num_front_channels -= 2;
     }
     while (num_front_channels >= 2) {
-        i += assign_pair(e2c_vec, layout_map, i, tags,
+        i += assign_pair(e2c_vec, layout_map, i,
                          UINT64_MAX,
                          UINT64_MAX,
                          AAC_CHANNEL_FRONT);
@@ -279,14 +311,14 @@
     }
 
     if (num_side_channels >= 2) {
-        i += assign_pair(e2c_vec, layout_map, i, tags,
+        i += assign_pair(e2c_vec, layout_map, i,
                          AV_CH_SIDE_LEFT,
                          AV_CH_SIDE_RIGHT,
                          AAC_CHANNEL_FRONT);
         num_side_channels -= 2;
     }
     while (num_side_channels >= 2) {
-        i += assign_pair(e2c_vec, layout_map, i, tags,
+        i += assign_pair(e2c_vec, layout_map, i,
                          UINT64_MAX,
                          UINT64_MAX,
                          AAC_CHANNEL_SIDE);
@@ -294,14 +326,14 @@
     }
 
     while (num_back_channels >= 4) {
-        i += assign_pair(e2c_vec, layout_map, i, tags,
+        i += assign_pair(e2c_vec, layout_map, i,
                          UINT64_MAX,
                          UINT64_MAX,
                          AAC_CHANNEL_BACK);
         num_back_channels -= 2;
     }
     if (num_back_channels >= 2) {
-        i += assign_pair(e2c_vec, layout_map, i, tags,
+        i += assign_pair(e2c_vec, layout_map, i,
                          AV_CH_BACK_LEFT,
                          AV_CH_BACK_RIGHT,
                          AAC_CHANNEL_BACK);
@@ -382,8 +414,8 @@
  * @return  Returns error status. 0 - OK, !0 - error
  */
 static int output_configure(AACContext *ac,
-                                    uint8_t layout_map[MAX_ELEM_ID*4][3], int tags,
-                                    int channel_config, enum OCStatus oc_type)
+                            uint8_t layout_map[MAX_ELEM_ID*4][3], int tags,
+                            enum OCStatus oc_type, int get_new_frame)
 {
     AVCodecContext *avctx = ac->avctx;
     int i, channels = 0, ret;
@@ -422,6 +454,11 @@
     avctx->channels = ac->oc[1].channels = channels;
     ac->oc[1].status = oc_type;
 
+    if (get_new_frame) {
+        if ((ret = frame_configure_elements(ac->avctx)) < 0)
+            return ret;
+    }
+
     return 0;
 }
 
@@ -481,7 +518,7 @@
                                        2) < 0)
             return NULL;
         if (output_configure(ac, layout_map, layout_map_tags,
-                             2, OC_TRIAL_FRAME) < 0)
+                             OC_TRIAL_FRAME, 1) < 0)
             return NULL;
 
         ac->oc[1].m4ac.chan_config = 2;
@@ -499,7 +536,7 @@
                                        1) < 0)
             return NULL;
         if (output_configure(ac, layout_map, layout_map_tags,
-                             1, OC_TRIAL_FRAME) < 0)
+                             OC_TRIAL_FRAME, 1) < 0)
             return NULL;
 
         ac->oc[1].m4ac.chan_config = 1;
@@ -665,8 +702,8 @@
     int tags = 0;
 
     if (get_bits1(gb)) { // frameLengthFlag
-        av_log_missing_feature(avctx, "960/120 MDCT window is", 1);
-        return -1;
+        av_log_missing_feature(avctx, "960/120 MDCT window", 1);
+        return AVERROR_PATCHWELCOME;
     }
 
     if (get_bits1(gb))       // dependsOnCoreCoder
@@ -692,8 +729,7 @@
     } else if (m4ac->sbr == 1 && m4ac->ps == -1)
         m4ac->ps = 1;
 
-    if (ac && (ret = output_configure(ac, layout_map, tags,
-                                      channel_config, OC_GLOBAL_HDR)))
+    if (ac && (ret = output_configure(ac, layout_map, tags, OC_GLOBAL_HDR, 0)))
         return ret;
 
     if (extension_flag) {
@@ -783,7 +819,8 @@
  */
 static av_always_inline int lcg_random(unsigned previous_val)
 {
-    return previous_val * 1664525 + 1013904223;
+    union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
+    return v.s;
 }
 
 static av_always_inline void reset_predict_state(PredictorState *ps)
@@ -835,18 +872,11 @@
 static av_cold int aac_decode_init(AVCodecContext *avctx)
 {
     AACContext *ac = avctx->priv_data;
-    float output_scale_factor;
 
     ac->avctx = avctx;
     ac->oc[1].m4ac.sample_rate = avctx->sample_rate;
 
-    if (avctx->request_sample_fmt == AV_SAMPLE_FMT_FLT) {
-        avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
-        output_scale_factor = 1.0 / 32768.0;
-    } else {
-        avctx->sample_fmt = AV_SAMPLE_FMT_S16;
-        output_scale_factor = 1.0;
-    }
+    avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
 
     if (avctx->extradata_size > 0) {
         if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
@@ -877,7 +907,7 @@
                 &layout_map_tags, ac->oc[1].m4ac.chan_config);
             if (!ret)
                 output_configure(ac, layout_map, layout_map_tags,
-                                 ac->oc[1].m4ac.chan_config, OC_GLOBAL_HDR);
+                                 OC_GLOBAL_HDR, 0);
             else if (avctx->err_recognition & AV_EF_EXPLODE)
                 return AVERROR_INVALIDDATA;
         }
@@ -910,9 +940,9 @@
                     ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
                     352);
 
-    ff_mdct_init(&ac->mdct,       11, 1, output_scale_factor/1024.0);
-    ff_mdct_init(&ac->mdct_small,  8, 1, output_scale_factor/128.0);
-    ff_mdct_init(&ac->mdct_ltp,   11, 0, -2.0/output_scale_factor);
+    ff_mdct_init(&ac->mdct,       11, 1, 1.0 / (32768.0 * 1024.0));
+    ff_mdct_init(&ac->mdct_small,  8, 1, 1.0 / (32768.0 * 128.0));
+    ff_mdct_init(&ac->mdct_ltp,   11, 0, -2.0 * 32768.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);
@@ -967,7 +997,7 @@
 /**
  * Decode Long Term Prediction data; reference: table 4.xx.
  */
-static void decode_ltp(AACContext *ac, LongTermPrediction *ltp,
+static void decode_ltp(LongTermPrediction *ltp,
                        GetBitContext *gb, uint8_t max_sfb)
 {
     int sfb;
@@ -1028,7 +1058,7 @@
                 goto fail;
             } else {
                 if ((ics->ltp.present = get_bits(gb, 1)))
-                    decode_ltp(ac, &ics->ltp, gb, ics->max_sfb);
+                    decode_ltp(&ics->ltp, gb, ics->max_sfb);
             }
         }
     }
@@ -1242,7 +1272,7 @@
         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]));
+        memset(cpe->ms_mask, 1,  sizeof(cpe->ms_mask[0]) * cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb);
     }
 }
 
@@ -1365,7 +1395,7 @@
 
                     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);
+                    ac->fdsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
                 }
             } else {
                 const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
@@ -1511,7 +1541,7 @@
                             }
                         } while (len -= 2);
 
-                        ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
+                        ac->fdsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
                     }
                 }
 
@@ -1670,7 +1700,7 @@
             return -1;
         if (get_bits1(gb)) {
             av_log_missing_feature(ac->avctx, "SSR", 1);
-            return -1;
+            return AVERROR_PATCHWELCOME;
         }
     }
 
@@ -1735,10 +1765,10 @@
                         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]);
+                        ac->fdsp.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];
@@ -1769,7 +1799,7 @@
         cpe->ch[1].ics.use_kb_window[1] = i;
         if (cpe->ch[1].ics.predictor_present && (ac->oc[1].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);
+                decode_ltp(&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");
@@ -1896,12 +1926,10 @@
 /**
  * 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)
+                                GetBitContext *gb)
 {
     int n             = 1;
     int drc_num_bands = 1;
@@ -2004,14 +2032,14 @@
             ac->oc[1].m4ac.sbr = 1;
             ac->oc[1].m4ac.ps = 1;
             output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
-                             ac->oc[1].m4ac.chan_config, ac->oc[1].status);
+                             ac->oc[1].status, 1);
         } else {
             ac->oc[1].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);
+        res = decode_dynamic_range(&ac->che_drc, gb);
         break;
     case EXT_FILL:
         decode_fill(ac, gb, 8 * cnt - 4);
@@ -2038,7 +2066,7 @@
     int w, filt, m, i;
     int bottom, top, order, start, end, size, inc;
     float lpc[TNS_MAX_ORDER];
-    float tmp[TNS_MAX_ORDER + 1];
+    float tmp[TNS_MAX_ORDER+1];
 
     for (w = 0; w < ics->num_windows; w++) {
         bottom = ics->num_swb;
@@ -2388,7 +2416,7 @@
         if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
             // This is 2 for "VLB " audio in NSV files.
             // See samples/nsv/vlb_audio.
-            av_log_missing_feature(ac->avctx, "More than one AAC RDB per ADTS frame is", 0);
+            av_log_missing_feature(ac->avctx, "More than one AAC RDB per ADTS frame", 0);
             ac->warned_num_aac_frames = 1;
         }
         push_output_configuration(ac);
@@ -2398,8 +2426,7 @@
                     &layout_map_tags, hdr_info.chan_config))
                 return -7;
             if (output_configure(ac, layout_map, layout_map_tags,
-                                 hdr_info.chan_config,
-                                 FFMAX(ac->oc[1].status, OC_TRIAL_FRAME)))
+                                 FFMAX(ac->oc[1].status, OC_TRIAL_FRAME), 0))
                 return -7;
         } else {
             ac->oc[1].m4ac.chan_config = 0;
@@ -2408,6 +2435,7 @@
              * WITHOUT specifying PCE.
              *  thus, set dual mono as default.
              */
+#if 0
             if (ac->enable_jp_dmono && ac->oc[0].status == OC_NONE) {
                 layout_map_tags = 2;
                 layout_map[0][0] = layout_map[1][0] = TYPE_SCE;
@@ -2415,9 +2443,10 @@
                 layout_map[0][1] = 0;
                 layout_map[1][1] = 1;
                 if (output_configure(ac, layout_map, layout_map_tags,
-                                     0, OC_TRIAL_FRAME))
+                                     OC_TRIAL_FRAME))
                     return -7;
             }
+#endif
         }
         ac->oc[1].m4ac.sample_rate     = hdr_info.sample_rate;
         ac->oc[1].m4ac.sampling_index  = hdr_info.sampling_index;
@@ -2458,6 +2487,11 @@
         }
     }
 
+    if (frame_configure_elements(avctx) < 0) {
+        err = -1;
+        goto fail;
+    }
+
     ac->tags_mapped = 0;
     // parse
     while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
@@ -2513,7 +2547,7 @@
                        "Not evaluating a further program_config_element as this construct is dubious at best.\n");
                 pop_output_configuration(ac);
             } else {
-                err = output_configure(ac, layout_map, tags, 0, OC_TRIAL_PCE);
+                err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
                 if (!err)
                     ac->oc[1].m4ac.chan_config = 0;
                 pce_found = 1;
@@ -2556,7 +2590,7 @@
 
     multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
     samples <<= multiplier;
-
+#if 0
     /* for dual-mono audio (SCE + SCE) */
     is_dmono = ac->enable_jp_dmono && sce_count == 2 &&
                ac->oc[1].channel_layout == (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT);
@@ -2570,36 +2604,20 @@
             ac->output_data[0] = ac->output_data[1];
         }
     }
-
+#endif
     if (samples) {
-        /* get output buffer */
         ac->frame.nb_samples = samples;
-        if ((err = avctx->get_buffer(avctx, &ac->frame)) < 0) {
-            av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-            err = -1;
-            goto fail;
-        }
-
-        if (avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
-            ac->fmt_conv.float_interleave((float *)ac->frame.data[0],
-                                          (const float **)ac->output_data,
-                                          samples, avctx->channels);
-        else
-            ac->fmt_conv.float_to_int16_interleave((int16_t *)ac->frame.data[0],
-                                                   (const float **)ac->output_data,
-                                                   samples, avctx->channels);
-
         *(AVFrame *)data = ac->frame;
     }
     *got_frame_ptr = !!samples;
-
+#if 0
     if (is_dmono) {
         if (ac->dmono_mode == 0)
             ac->output_data[1] = tmp;
         else if (ac->dmono_mode == 1)
             ac->output_data[0] = tmp;
     }
-
+#endif
     if (ac->oc[1].status && audio_found) {
         avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
         avctx->frame_size = samples;
@@ -2728,9 +2746,9 @@
         asclen         = get_bits_left(gb);
 
     if (config_start_bit % 8) {
-        av_log_missing_feature(latmctx->aac_ctx.avctx, "audio specific "
-                               "config not byte aligned.\n", 1);
-        return AVERROR_INVALIDDATA;
+        av_log_missing_feature(latmctx->aac_ctx.avctx,
+                               "Non-byte-aligned audio-specific config", 1);
+        return AVERROR_PATCHWELCOME;
     }
     if (asclen <= 0)
         return AVERROR_INVALIDDATA;
@@ -2789,7 +2807,7 @@
         // numPrograms
         if (get_bits(gb, 4)) {                  // numPrograms
             av_log_missing_feature(latmctx->aac_ctx.avctx,
-                                   "multiple programs are not supported\n", 1);
+                                   "Multiple programs", 1);
             return AVERROR_PATCHWELCOME;
         }
 
@@ -2798,7 +2816,7 @@
         // for each layer (which there is only one in DVB)
         if (get_bits(gb, 3)) {                   // numLayer
             av_log_missing_feature(latmctx->aac_ctx.avctx,
-                                   "multiple layers are not supported\n", 1);
+                                   "Multiple layers", 1);
             return AVERROR_PATCHWELCOME;
         }
 
@@ -2974,7 +2992,7 @@
     .decode          = aac_decode_frame,
     .long_name       = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
     .sample_fmts     = (const enum AVSampleFormat[]) {
-        AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
+        AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
     },
     .capabilities    = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
     .channel_layouts = aac_channel_layout,
@@ -2996,7 +3014,7 @@
     .decode          = latm_decode_frame,
     .long_name       = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Coding LATM syntax)"),
     .sample_fmts     = (const enum AVSampleFormat[]) {
-        AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
+        AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
     },
     .capabilities    = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
     .channel_layouts = aac_channel_layout,
diff --git a/libavcodec/aacdectab.h b/libavcodec/aacdectab.h
index 0083260..4a12b4f 100644
--- a/libavcodec/aacdectab.h
+++ b/libavcodec/aacdectab.h
@@ -30,7 +30,7 @@
 #ifndef AVCODEC_AACDECTAB_H
 #define AVCODEC_AACDECTAB_H
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "aac.h"
 
 #include <stdint.h>
diff --git a/libavcodec/aacenc.c b/libavcodec/aacenc.c
index 9b2b2bb..2c40ec9 100644
--- a/libavcodec/aacenc.c
+++ b/libavcodec/aacenc.c
@@ -191,7 +191,7 @@
 {
     const float *lwindow = sce->ics.use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
     const float *pwindow = sce->ics.use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
-    float *out = sce->ret;
+    float *out = sce->ret_buf;
 
     fdsp->vector_fmul       (out,        audio,        lwindow, 1024);
     dsp->vector_fmul_reverse(out + 1024, audio + 1024, pwindow, 1024);
@@ -201,7 +201,7 @@
 {
     const float *lwindow = sce->ics.use_kb_window[1] ? 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;
-    float *out = sce->ret;
+    float *out = sce->ret_buf;
 
     fdsp->vector_fmul(out, audio, lwindow, 1024);
     memcpy(out + 1024, audio + 1024, sizeof(out[0]) * 448);
@@ -213,7 +213,7 @@
 {
     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[1] ? ff_aac_kbd_short_128 : ff_sine_128;
-    float *out = sce->ret;
+    float *out = sce->ret_buf;
 
     memset(out, 0, sizeof(out[0]) * 448);
     fdsp->vector_fmul(out + 448, audio + 448, swindow, 128);
@@ -226,7 +226,7 @@
     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;
     const float *in = audio + 448;
-    float *out = sce->ret;
+    float *out = sce->ret_buf;
     int w;
 
     for (w = 0; w < 8; w++) {
@@ -251,7 +251,7 @@
                                   float *audio)
 {
     int i;
-    float *output = sce->ret;
+    float *output = sce->ret_buf;
 
     apply_window[sce->ics.window_sequence[0]](&s->dsp, &s->fdsp, sce, audio);
 
@@ -302,7 +302,7 @@
 /**
  * Produce integer coefficients from scalefactors provided by the model.
  */
-static void adjust_frame_information(AACEncContext *apc, ChannelElement *cpe, int chans)
+static void adjust_frame_information(ChannelElement *cpe, int chans)
 {
     int i, w, w2, g, ch;
     int start, maxsfb, cmaxsfb;
@@ -385,8 +385,7 @@
         for (i = 0; i < sce->ics.max_sfb; i++) {
             if (!sce->zeroes[w*16 + i]) {
                 diff = sce->sf_idx[w*16 + i] - off + SCALE_DIFF_ZERO;
-                if (diff < 0 || diff > 120)
-                    av_log(avctx, AV_LOG_ERROR, "Scalefactor difference is too big to be coded\n");
+                av_assert0(diff >= 0 && diff <= 120);
                 off = sce->sf_idx[w*16 + i];
                 put_bits(&s->pb, ff_aac_scalefactor_bits[diff], ff_aac_scalefactor_code[diff]);
             }
@@ -460,8 +459,7 @@
 /**
  * Write some auxiliary information about the created AAC file.
  */
-static void put_bitstream_info(AVCodecContext *avctx, AACEncContext *s,
-                               const char *name)
+static void put_bitstream_info(AACEncContext *s, const char *name)
 {
     int i, namelen, padbits;
 
@@ -479,31 +477,28 @@
 }
 
 /*
- * Deinterleave input samples.
+ * Copy input samples.
  * Channels are reordered from libavcodec's default order to AAC order.
  */
-static void deinterleave_input_samples(AACEncContext *s, const AVFrame *frame)
+static void copy_input_samples(AACEncContext *s, const AVFrame *frame)
 {
-    int ch, i;
-    const int sinc = s->channels;
-    const uint8_t *channel_map = aac_chan_maps[sinc - 1];
+    int ch;
+    int end = 2048 + (frame ? frame->nb_samples : 0);
+    const uint8_t *channel_map = aac_chan_maps[s->channels - 1];
 
-    /* deinterleave and remap input samples */
-    for (ch = 0; ch < sinc; ch++) {
+    /* copy and remap input samples */
+    for (ch = 0; ch < s->channels; ch++) {
         /* copy last 1024 samples of previous frame to the start of the current frame */
         memcpy(&s->planar_samples[ch][1024], &s->planar_samples[ch][2048], 1024 * sizeof(s->planar_samples[0][0]));
 
-        /* deinterleave */
-        i = 2048;
+        /* copy new samples and zero any remaining samples */
         if (frame) {
-            const float *sptr = ((const float *)frame->data[0]) + channel_map[ch];
-            for (; i < 2048 + frame->nb_samples; i++) {
-                s->planar_samples[ch][i] = *sptr;
-                sptr += sinc;
-            }
+            memcpy(&s->planar_samples[ch][2048],
+                   frame->extended_data[channel_map[ch]],
+                   frame->nb_samples * sizeof(s->planar_samples[0][0]));
         }
-        memset(&s->planar_samples[ch][i], 0,
-               (3072 - i) * sizeof(s->planar_samples[0][0]));
+        memset(&s->planar_samples[ch][end], 0,
+               (3072 - end) * sizeof(s->planar_samples[0][0]));
     }
 }
 
@@ -526,7 +521,7 @@
             return ret;
     }
 
-    deinterleave_input_samples(s, frame);
+    copy_input_samples(s, frame);
     if (s->psypp)
         ff_psy_preprocess(s->psypp, s->planar_samples, s->channels);
 
@@ -576,7 +571,7 @@
         }
         start_ch += chans;
     }
-    if ((ret = ff_alloc_packet2(avctx, avpkt, 768 * s->channels))) {
+    if ((ret = ff_alloc_packet2(avctx, avpkt, 8192 * s->channels))) {
         av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
         return ret;
     }
@@ -586,7 +581,7 @@
         init_put_bits(&s->pb, avpkt->data, avpkt->size);
 
         if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & CODEC_FLAG_BITEXACT))
-            put_bitstream_info(avctx, s, LIBAVCODEC_IDENT);
+            put_bitstream_info(s, LIBAVCODEC_IDENT);
         start_ch = 0;
         memset(chan_el_counter, 0, sizeof(chan_el_counter));
         for (i = 0; i < s->chan_map[0]; i++) {
@@ -628,7 +623,7 @@
                     s->coder->search_for_ms(s, cpe, s->lambda);
                 }
             }
-            adjust_frame_information(s, cpe, chans);
+            adjust_frame_information(cpe, chans);
             if (chans == 2) {
                 put_bits(&s->pb, 1, cpe->common_window);
                 if (cpe->common_window) {
@@ -816,6 +811,13 @@
     LIBAVUTIL_VERSION_INT,
 };
 
+/* duplicated from avpriv_mpeg4audio_sample_rates to avoid shared build
+ * failures */
+static const int mpeg4audio_sample_rates[16] = {
+    96000, 88200, 64000, 48000, 44100, 32000,
+    24000, 22050, 16000, 12000, 11025, 8000, 7350
+};
+
 AVCodec ff_aac_encoder = {
     .name           = "aac",
     .type           = AVMEDIA_TYPE_AUDIO,
@@ -824,10 +826,10 @@
     .init           = aac_encode_init,
     .encode2        = aac_encode_frame,
     .close          = aac_encode_end,
-    .supported_samplerates = avpriv_mpeg4audio_sample_rates,
+    .supported_samplerates = mpeg4audio_sample_rates,
     .capabilities   = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY |
                       CODEC_CAP_EXPERIMENTAL,
-    .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLT,
+    .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLTP,
                                                      AV_SAMPLE_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
     .priv_class     = &aacenc_class,
diff --git a/libavcodec/aacps.c b/libavcodec/aacps.c
index 569b44e..25ed1d0 100644
--- a/libavcodec/aacps.c
+++ b/libavcodec/aacps.c
@@ -139,7 +139,7 @@
     return get_bits_count(gb) - count;
 }
 
-static void ipdopd_reset(int8_t *opd_hist, int8_t *ipd_hist)
+static void ipdopd_reset(int8_t *ipd_hist, int8_t *opd_hist)
 {
     int i;
     for (i = 0; i < PS_MAX_NR_IPDOPD; i++) {
@@ -236,6 +236,7 @@
     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;
+        int b;
         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]));
@@ -248,6 +249,22 @@
                 memcpy(ps->opd_par+ps->num_env, ps->opd_par+source, sizeof(ps->opd_par[0]));
             }
         }
+        if (ps->enable_iid){
+            for (b = 0; b < ps->nr_iid_par; b++) {
+                if (FFABS(ps->iid_par[ps->num_env][b]) > 7 + 8 * ps->iid_quant) {
+                    av_log(avctx, AV_LOG_ERROR, "iid_par invalid\n");
+                    goto err;
+                }
+            }
+        }
+        if (ps->enable_icc){
+            for (b = 0; b < ps->nr_iid_par; b++) {
+                if (ps->icc_par[ps->num_env][b] > 7U) {
+                    av_log(avctx, AV_LOG_ERROR, "icc_par invalid\n");
+                    goto err;
+                }
+            }
+        }
         ps->num_env++;
         ps->border_position[ps->num_env] = numQMFSlots - 1;
     }
@@ -603,7 +620,6 @@
     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)
diff --git a/libavcodec/aacps.h b/libavcodec/aacps.h
index d310c91..29323ff 100644
--- a/libavcodec/aacps.h
+++ b/libavcodec/aacps.h
@@ -38,7 +38,7 @@
 #define PS_AP_LINKS 3
 #define PS_MAX_AP_DELAY 5
 
-typedef struct {
+typedef struct PSContext {
     int    start;
     int    enable_iid;
     int    iid_quant;
diff --git a/libavcodec/aacps_tablegen.h b/libavcodec/aacps_tablegen.h
index a8c4021..1f9c326 100644
--- a/libavcodec/aacps_tablegen.h
+++ b/libavcodec/aacps_tablegen.h
@@ -31,6 +31,7 @@
 #include "libavcodec/aacps_tables.h"
 #else
 #include "libavutil/common.h"
+#include "libavutil/libm.h"
 #include "libavutil/mathematics.h"
 #include "libavutil/mem.h"
 #define NR_ALLPASS_BANDS20 30
diff --git a/libavcodec/aacsbr.c b/libavcodec/aacsbr.c
index b4fc761..e46b4a4 100644
--- a/libavcodec/aacsbr.c
+++ b/libavcodec/aacsbr.c
@@ -142,7 +142,6 @@
 
 av_cold void ff_aac_sbr_ctx_init(AACContext *ac, SpectralBandReplication *sbr)
 {
-    float mdct_scale;
     if(sbr->mdct.mdct_bits)
         return;
     sbr->kx[0] = sbr->kx[1];
@@ -152,9 +151,8 @@
     /* SBR requires samples to be scaled to +/-32768.0 to work correctly.
      * mdct scale factors are adjusted to scale up from +/-1.0 at analysis
      * and scale back down at synthesis. */
-    mdct_scale = ac->avctx->sample_fmt == AV_SAMPLE_FMT_FLT ? 32768.0f : 1.0f;
-    ff_mdct_init(&sbr->mdct,     7, 1, 1.0 / (64 * mdct_scale));
-    ff_mdct_init(&sbr->mdct_ana, 7, 1, -2.0 * mdct_scale);
+    ff_mdct_init(&sbr->mdct,     7, 1, 1.0 / (64 * 32768.0));
+    ff_mdct_init(&sbr->mdct_ana, 7, 1, -2.0 * 32768.0);
     ff_ps_ctx_init(&sbr->ps);
     ff_sbrdsp_init(&sbr->dsp);
 }
@@ -340,9 +338,6 @@
     } else
         temp = 5000;
 
-    start_min = ((temp << 7) + (sbr->sample_rate >> 1)) / sbr->sample_rate;
-    stop_min  = ((temp << 8) + (sbr->sample_rate >> 1)) / sbr->sample_rate;
-
     switch (sbr->sample_rate) {
     case 16000:
         sbr_offset_ptr = sbr_offset[0];
@@ -368,6 +363,9 @@
         return -1;
     }
 
+    start_min = ((temp << 7) + (sbr->sample_rate >> 1)) / sbr->sample_rate;
+    stop_min  = ((temp << 8) + (sbr->sample_rate >> 1)) / sbr->sample_rate;
+
     sbr->k[0] = start_min + sbr_offset_ptr[spectrum->bs_start_freq];
 
     if (spectrum->bs_stop_freq < 14) {
@@ -555,7 +553,7 @@
             k = sbr->n_master;
     } while (sb != sbr->kx[1] + sbr->m[1]);
 
-    if (sbr->patch_num_subbands[sbr->num_patches-1] < 3 && sbr->num_patches > 1)
+    if (sbr->num_patches > 1 && sbr->patch_num_subbands[sbr->num_patches-1] < 3)
         sbr->num_patches--;
 
     return 0;
@@ -749,7 +747,7 @@
         if (ch_data->bs_frame_class == FIXFIX) {
             idx = ch_data->bs_num_env >> 1;
         } else if (ch_data->bs_frame_class & 1) { // FIXVAR or VARVAR
-            idx = ch_data->bs_num_env - FFMAX(bs_pointer - 1, 1);
+            idx = ch_data->bs_num_env - FFMAX((int)bs_pointer - 1, 1);
         } else { // VARFIX
             if (!bs_pointer)
                 idx = 1;
@@ -926,7 +924,7 @@
 #if 1
             *num_bits_left -= ff_ps_read_data(ac->avctx, gb, &sbr->ps, *num_bits_left);
 #else
-            av_log_missing_feature(ac->avctx, "Parametric Stereo is", 0);
+            av_log_missing_feature(ac->avctx, "Parametric Stereo", 0);
             skip_bits_long(gb, *num_bits_left); // bs_fill_bits
             *num_bits_left = 0;
 #endif
@@ -935,7 +933,7 @@
     default:
         // some files contain 0-padding
         if (bs_extension_id || *num_bits_left > 16 || show_bits(gb, *num_bits_left))
-            av_log_missing_feature(ac->avctx, "Reserved SBR extensions are", 1);
+            av_log_missing_feature(ac->avctx, "Reserved SBR extensions", 1);
         skip_bits_long(gb, *num_bits_left); // bs_fill_bits
         *num_bits_left = 0;
         break;
@@ -1161,10 +1159,9 @@
  */
 static void sbr_qmf_analysis(DSPContext *dsp, FFTContext *mdct,
                              SBRDSPContext *sbrdsp, const float *in, float *x,
-                             float z[320], float W[2][32][32][2])
+                             float z[320], float W[2][32][32][2], int buf_idx)
 {
     int i;
-    memcpy(W[0], W[1], sizeof(W[0]));
     memcpy(x    , x+1024, (320-32)*sizeof(x[0]));
     memcpy(x+288, in,         1024*sizeof(x[0]));
     for (i = 0; i < 32; i++) { // numTimeSlots*RATE = 16*2 as 960 sample frames
@@ -1173,7 +1170,7 @@
         sbrdsp->sum64x5(z);
         sbrdsp->qmf_pre_shuffle(z);
         mdct->imdct_half(mdct, z, z+64);
-        sbrdsp->qmf_post_shuffle(W[1][i], z);
+        sbrdsp->qmf_post_shuffle(W[buf_idx][i], z);
         x += 32;
     }
 }
@@ -1309,7 +1306,8 @@
 
 /// Generate the subband filtered lowband
 static int sbr_lf_gen(AACContext *ac, SpectralBandReplication *sbr,
-                      float X_low[32][40][2], const float W[2][32][32][2])
+                      float X_low[32][40][2], const float W[2][32][32][2],
+                      int buf_idx)
 {
     int i, k;
     const int t_HFGen = 8;
@@ -1317,14 +1315,15 @@
     memset(X_low, 0, 32*sizeof(*X_low));
     for (k = 0; k < sbr->kx[1]; k++) {
         for (i = t_HFGen; i < i_f + t_HFGen; i++) {
-            X_low[k][i][0] = W[1][i - t_HFGen][k][0];
-            X_low[k][i][1] = W[1][i - t_HFGen][k][1];
+            X_low[k][i][0] = W[buf_idx][i - t_HFGen][k][0];
+            X_low[k][i][1] = W[buf_idx][i - t_HFGen][k][1];
         }
     }
+    buf_idx = 1-buf_idx;
     for (k = 0; k < sbr->kx[0]; k++) {
         for (i = 0; i < t_HFGen; i++) {
-            X_low[k][i][0] = W[0][i + i_f - t_HFGen][k][0];
-            X_low[k][i][1] = W[0][i + i_f - t_HFGen][k][1];
+            X_low[k][i][0] = W[buf_idx][i + i_f - t_HFGen][k][0];
+            X_low[k][i][1] = W[buf_idx][i + i_f - t_HFGen][k][1];
         }
     }
     return 0;
@@ -1672,8 +1671,8 @@
         /* decode channel */
         sbr_qmf_analysis(&ac->dsp, &sbr->mdct_ana, &sbr->dsp, ch ? R : L, sbr->data[ch].analysis_filterbank_samples,
                          (float*)sbr->qmf_filter_scratch,
-                         sbr->data[ch].W);
-        sbr_lf_gen(ac, sbr, sbr->X_low, sbr->data[ch].W);
+                         sbr->data[ch].W, sbr->data[ch].Ypos);
+        sbr_lf_gen(ac, sbr, sbr->X_low, sbr->data[ch].W, sbr->data[ch].Ypos);
         sbr->data[ch].Ypos ^= 1;
         if (sbr->start) {
             sbr_hf_inverse_filter(&sbr->dsp, sbr->alpha0, sbr->alpha1, sbr->X_low, sbr->k[0]);
diff --git a/libavcodec/aasc.c b/libavcodec/aasc.c
index 7b48557..6c9fd4e 100644
--- a/libavcodec/aasc.c
+++ b/libavcodec/aasc.c
@@ -50,7 +50,7 @@
     s->avctx = avctx;
     switch (avctx->bits_per_coded_sample) {
     case 8:
-        avctx->pix_fmt = PIX_FMT_PAL8;
+        avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
         ptr = avctx->extradata;
         s->palette_size = FFMIN(avctx->extradata_size, AVPALETTE_SIZE);
@@ -60,10 +60,10 @@
         }
         break;
     case 16:
-        avctx->pix_fmt = PIX_FMT_RGB555;
+        avctx->pix_fmt = AV_PIX_FMT_RGB555;
         break;
     case 24:
-        avctx->pix_fmt = PIX_FMT_BGR24;
+        avctx->pix_fmt = AV_PIX_FMT_BGR24;
         break;
     default:
         av_log(avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n", avctx->bits_per_coded_sample);
@@ -83,6 +83,11 @@
     AascContext *s = avctx->priv_data;
     int compr, i, stride, psize;
 
+    if (buf_size < 4) {
+        av_log(avctx, AV_LOG_ERROR, "frame too short\n");
+        return AVERROR_INVALIDDATA;
+    }
+
     s->frame.reference = 3;
     s->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;
     if (avctx->reget_buffer(avctx, &s->frame)) {
@@ -127,7 +132,7 @@
         return -1;
     }
 
-    if (avctx->pix_fmt == PIX_FMT_PAL8)
+    if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
         memcpy(s->frame.data[1], s->palette, s->palette_size);
 
     *data_size = sizeof(AVFrame);
diff --git a/libavcodec/ac3.h b/libavcodec/ac3.h
index b9f34b9..e609bb5 100644
--- a/libavcodec/ac3.h
+++ b/libavcodec/ac3.h
@@ -93,7 +93,7 @@
  * @struct AC3HeaderInfo
  * Coded AC-3 header values up to the lfeon element, plus derived values.
  */
-typedef struct {
+typedef struct AC3HeaderInfo {
     /** @name Coded elements
      * @{
      */
diff --git a/libavcodec/ac3_parser.c b/libavcodec/ac3_parser.c
index 8250a67..8dc4c0d 100644
--- a/libavcodec/ac3_parser.c
+++ b/libavcodec/ac3_parser.c
@@ -20,11 +20,11 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "parser.h"
 #include "ac3_parser.h"
 #include "aac_ac3_parser.h"
 #include "get_bits.h"
-#include "libavutil/audioconvert.h"
 
 
 #define AC3_HEADER_SIZE 7
diff --git a/libavcodec/ac3dec.c b/libavcodec/ac3dec.c
index 674de7a..7fb380c 100644
--- a/libavcodec/ac3dec.c
+++ b/libavcodec/ac3dec.c
@@ -876,7 +876,7 @@
             if (s->eac3 && get_bits1(gbc)) {
                 /* TODO: parse enhanced coupling strategy info */
                 av_log_missing_feature(s->avctx, "Enhanced coupling", 1);
-                return -1;
+                return AVERROR_PATCHWELCOME;
             }
 
             /* determine which channels are coupled */
diff --git a/libavcodec/ac3dec.h b/libavcodec/ac3dec.h
index e0f3dc7..c3a43bf 100644
--- a/libavcodec/ac3dec.h
+++ b/libavcodec/ac3dec.h
@@ -65,7 +65,7 @@
 /** Large enough for maximum possible frame size when the specification limit is ignored */
 #define AC3_FRAME_BUFFER_SIZE 32768
 
-typedef struct {
+typedef struct AC3DecodeContext {
     AVClass        *class;                  ///< class for AVOptions
     AVCodecContext *avctx;                  ///< parent context
     AVFrame frame;                          ///< AVFrame for decoded output
diff --git a/libavcodec/ac3dsp.c b/libavcodec/ac3dsp.c
index 4e1e4bd..9277411 100644
--- a/libavcodec/ac3dsp.c
+++ b/libavcodec/ac3dsp.c
@@ -256,6 +256,8 @@
 
     if (ARCH_ARM)
         ff_ac3dsp_init_arm(c, bit_exact);
-    if (HAVE_MMX)
+    if (ARCH_X86)
         ff_ac3dsp_init_x86(c, bit_exact);
+    if (ARCH_MIPS)
+        ff_ac3dsp_init_mips(c, bit_exact);
 }
diff --git a/libavcodec/ac3dsp.h b/libavcodec/ac3dsp.h
index fbc63f6..7269c57 100644
--- a/libavcodec/ac3dsp.h
+++ b/libavcodec/ac3dsp.h
@@ -139,5 +139,6 @@
 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);
+void ff_ac3dsp_init_mips(AC3DSPContext *c, int bit_exact);
 
 #endif /* AVCODEC_AC3DSP_H */
diff --git a/libavcodec/ac3enc.c b/libavcodec/ac3enc.c
index e5dea46..22b6857 100644
--- a/libavcodec/ac3enc.c
+++ b/libavcodec/ac3enc.c
@@ -30,9 +30,9 @@
 
 #include <stdint.h>
 
-#include "libavutil/audioconvert.h"
 #include "libavutil/avassert.h"
 #include "libavutil/avstring.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/crc.h"
 #include "libavutil/opt.h"
 #include "avcodec.h"
@@ -40,7 +40,6 @@
 #include "dsputil.h"
 #include "ac3dsp.h"
 #include "ac3.h"
-#include "audioconvert.h"
 #include "fft.h"
 #include "ac3enc.h"
 #include "eac3enc.h"
@@ -273,7 +272,7 @@
     int nb_coefs;
     int blk, bnd, i;
     int start, end;
-    uint8_t *flags;
+    uint8_t *flags = NULL;
 
     if (!s->rematrixing_enabled)
         return;
diff --git a/libavcodec/ac3enc_fixed.c b/libavcodec/ac3enc_fixed.c
index fa109f9..5d8dd5c 100644
--- a/libavcodec/ac3enc_fixed.c
+++ b/libavcodec/ac3enc_fixed.c
@@ -160,7 +160,7 @@
     .init            = ac3_fixed_encode_init,
     .encode2         = ff_ac3_fixed_encode_frame,
     .close           = ff_ac3_encode_close,
-    .sample_fmts     = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
+    .sample_fmts     = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16P,
                                                       AV_SAMPLE_FMT_NONE },
     .long_name       = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
     .priv_class      = &ac3enc_class,
diff --git a/libavcodec/ac3enc_float.c b/libavcodec/ac3enc_float.c
index 5afe0fe..7864f41 100644
--- a/libavcodec/ac3enc_float.c
+++ b/libavcodec/ac3enc_float.c
@@ -158,7 +158,7 @@
     .init            = ff_ac3_encode_init,
     .encode2         = ff_ac3_float_encode_frame,
     .close           = ff_ac3_encode_close,
-    .sample_fmts     = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLT,
+    .sample_fmts     = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLTP,
                                                       AV_SAMPLE_FMT_NONE },
     .long_name       = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
     .priv_class      = &ac3enc_class,
diff --git a/libavcodec/ac3enc_template.c b/libavcodec/ac3enc_template.c
index e81bfce..904e0bb 100644
--- a/libavcodec/ac3enc_template.c
+++ b/libavcodec/ac3enc_template.c
@@ -4,20 +4,20 @@
  * Copyright (c) 2006-2011 Justin Ruggles <justin.ruggles@gmail.com>
  * Copyright (c) 2006-2010 Prakash Punnoor <prakash@punnoor.de>
  *
- * This file is part of Libav.
+ * This file is part of FFmpeg.
  *
- * Libav is free software; you can redistribute it and/or
+ * 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.
  *
- * Libav is distributed in the hope that it will be useful,
+ * 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 Libav; if not, write to the Free Software
+ * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -68,30 +68,23 @@
 
 
 /*
- * Deinterleave input samples.
+ * Copy input samples.
  * Channels are reordered from FFmpeg's default order to AC-3 order.
  */
-static void deinterleave_input_samples(AC3EncodeContext *s,
-                                       const SampleType *samples)
+static void copy_input_samples(AC3EncodeContext *s, SampleType **samples)
 {
-    int ch, i;
+    int ch;
 
-    /* deinterleave and remap input samples */
+    /* copy 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_BLOCK_SIZE * s->num_blocks],
                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_BLOCK_SIZE * (s->num_blocks + 1); i++) {
-            s->planar_samples[ch][i] = *sptr;
-            sptr += sinc;
-        }
+        /* copy new samples for current frame */
+        memcpy(&s->planar_samples[ch][AC3_BLOCK_SIZE],
+               samples[s->channel_map[ch]],
+               AC3_BLOCK_SIZE * s->num_blocks * sizeof(s->planar_samples[0][0]));
     }
 }
 
@@ -395,7 +388,6 @@
                            const AVFrame *frame, int *got_packet_ptr)
 {
     AC3EncodeContext *s = avctx->priv_data;
-    const SampleType *samples = (const SampleType *)frame->data[0];
     int ret;
 
     if (s->options.allow_per_frame_metadata) {
@@ -407,7 +399,7 @@
     if (s->bit_alloc.sr_code == 1 || s->eac3)
         ff_ac3_adjust_frame_size(s);
 
-    deinterleave_input_samples(s, samples);
+    copy_input_samples(s, (SampleType **)frame->extended_data);
 
     apply_mdct(s);
 
diff --git a/libavcodec/ac3tab.c b/libavcodec/ac3tab.c
index ccf04ec..9d20d90 100644
--- a/libavcodec/ac3tab.c
+++ b/libavcodec/ac3tab.c
@@ -24,7 +24,7 @@
  * tables taken directly from the AC-3 spec.
  */
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "avcodec.h"
 #include "ac3tab.h"
 
diff --git a/libavcodec/ac3tab.h b/libavcodec/ac3tab.h
index 0063c8d..c41a93e 100644
--- a/libavcodec/ac3tab.h
+++ b/libavcodec/ac3tab.h
@@ -24,7 +24,6 @@
 
 #include "libavutil/common.h"
 #include "ac3.h"
-#include "symbols.h"
 
 #if CONFIG_HARDCODED_TABLES
 #   define HCONST const
@@ -34,7 +33,7 @@
 
 extern const uint16_t ff_ac3_frame_size_tab[38][3];
 extern const uint8_t  ff_ac3_channels_tab[8];
-extern AVCODEC_SYMBOL const uint16_t avpriv_ac3_channel_layout_tab[8];
+extern av_export const uint16_t avpriv_ac3_channel_layout_tab[8];
 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];
diff --git a/libavcodec/acelp_pitch_delay.c b/libavcodec/acelp_pitch_delay.c
index e488cc8..95bcce7 100644
--- a/libavcodec/acelp_pitch_delay.c
+++ b/libavcodec/acelp_pitch_delay.c
@@ -87,7 +87,7 @@
     if(erasure)
         quant_energy[0] = FFMAX(avg_gain >> log2_ma_pred_order, -10240) - 4096; // -10 and -4 in (5.10)
     else
-        quant_energy[0] = (6165 * ((ff_log2(gain_corr_factor) >> 2) - (13 << 13))) >> 13;
+        quant_energy[0] = (6165 * ((ff_log2_q15(gain_corr_factor) >> 2) - (13 << 13))) >> 13;
 }
 
 int16_t ff_acelp_decode_gain_code(
diff --git a/libavcodec/acelp_vectors.h b/libavcodec/acelp_vectors.h
index d92f288..fae834d 100644
--- a/libavcodec/acelp_vectors.h
+++ b/libavcodec/acelp_vectors.h
@@ -50,7 +50,7 @@
 void ff_acelp_vectors_init_mips(ACELPVContext *c);
 
 /** Sparse representation for the algebraic codebook (fixed) vector */
-typedef struct {
+typedef struct AMRFixed {
     int      n;
     int      x[10];
     float    y[10];
diff --git a/libavcodec/adpcm.c b/libavcodec/adpcm.c
index 8525496..fd308a9 100644
--- a/libavcodec/adpcm.c
+++ b/libavcodec/adpcm.c
@@ -99,10 +99,12 @@
     case AV_CODEC_ID_ADPCM_EA:
         min_channels = 2;
         break;
+    case AV_CODEC_ID_ADPCM_AFC:
     case AV_CODEC_ID_ADPCM_EA_R1:
     case AV_CODEC_ID_ADPCM_EA_R2:
     case AV_CODEC_ID_ADPCM_EA_R3:
     case AV_CODEC_ID_ADPCM_EA_XAS:
+    case AV_CODEC_ID_ADPCM_THP:
         max_channels = 6;
         break;
     }
@@ -134,7 +136,27 @@
     default:
         break;
     }
-    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+
+    switch(avctx->codec->id) {
+        case AV_CODEC_ID_ADPCM_IMA_QT:
+        case AV_CODEC_ID_ADPCM_IMA_WAV:
+        case AV_CODEC_ID_ADPCM_4XM:
+        case AV_CODEC_ID_ADPCM_XA:
+        case AV_CODEC_ID_ADPCM_EA_R1:
+        case AV_CODEC_ID_ADPCM_EA_R2:
+        case AV_CODEC_ID_ADPCM_EA_R3:
+        case AV_CODEC_ID_ADPCM_EA_XAS:
+        case AV_CODEC_ID_ADPCM_THP:
+        case AV_CODEC_ID_ADPCM_AFC:
+            avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
+            break;
+        case AV_CODEC_ID_ADPCM_IMA_WS:
+            avctx->sample_fmt = c->vqa_version == 3 ? AV_SAMPLE_FMT_S16P :
+                                                      AV_SAMPLE_FMT_S16;
+            break;
+        default:
+            avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    }
 
     avcodec_get_frame_defaults(&c->frame);
     avctx->coded_frame = &c->frame;
@@ -209,6 +231,27 @@
     return c->sample1;
 }
 
+static inline short adpcm_ima_oki_expand_nibble(ADPCMChannelStatus *c, int nibble)
+{
+    int step_index, predictor, sign, delta, diff, step;
+
+    step = ff_adpcm_oki_step_table[c->step_index];
+    step_index = c->step_index + ff_adpcm_index_table[(unsigned)nibble];
+    step_index = av_clip(step_index, 0, 48);
+
+    sign = nibble & 8;
+    delta = nibble & 7;
+    diff = ((2 * delta + 1) * step) >> 3;
+    predictor = c->predictor;
+    if (sign) predictor -= diff;
+    else predictor += diff;
+
+    c->predictor = av_clip(predictor, -2048, 2047);
+    c->step_index = step_index;
+
+    return c->predictor << 4;
+}
+
 static inline short adpcm_ct_expand_nibble(ADPCMChannelStatus *c, char nibble)
 {
     int sign, delta, diff;
@@ -264,17 +307,22 @@
     return c->predictor;
 }
 
-static int xa_decode(AVCodecContext *avctx,
-                     short *out, const unsigned char *in,
-                     ADPCMChannelStatus *left, ADPCMChannelStatus *right, int inc)
+static int xa_decode(AVCodecContext *avctx, int16_t *out0, int16_t *out1,
+                     const uint8_t *in, ADPCMChannelStatus *left,
+                     ADPCMChannelStatus *right, int channels, int sample_offset)
 {
     int i, j;
     int shift,filter,f0,f1;
     int s_1,s_2;
     int d,s,t;
 
-    for(i=0;i<4;i++) {
+    out0 += sample_offset;
+    if (channels == 1)
+        out1 = out0 + 28;
+    else
+        out1 += sample_offset;
 
+    for(i=0;i<4;i++) {
         shift  = 12 - (in[4+i*2] & 15);
         filter = in[4+i*2] >> 4;
         if (filter >= FF_ARRAY_ELEMS(xa_adpcm_table)) {
@@ -294,16 +342,14 @@
             s = ( t<<shift ) + ((s_1*f0 + s_2*f1+32)>>6);
             s_2 = s_1;
             s_1 = av_clip_int16(s);
-            *out = s_1;
-            out += inc;
+            out0[j] = s_1;
         }
 
-        if (inc==2) { /* stereo */
+        if (channels == 2) {
             left->sample1 = s_1;
             left->sample2 = s_2;
             s_1 = right->sample1;
             s_2 = right->sample2;
-            out = out + 1 - 28*2;
         }
 
         shift  = 12 - (in[5+i*2] & 15);
@@ -323,18 +369,19 @@
             s = ( t<<shift ) + ((s_1*f0 + s_2*f1+32)>>6);
             s_2 = s_1;
             s_1 = av_clip_int16(s);
-            *out = s_1;
-            out += inc;
+            out1[j] = s_1;
         }
 
-        if (inc==2) { /* stereo */
+        if (channels == 2) {
             right->sample1 = s_1;
             right->sample2 = s_2;
-            out -= 1;
         } else {
             left->sample1 = s_1;
             left->sample2 = s_2;
         }
+
+        out0 += 28 * (3 - channels);
+        out1 += 28 * (3 - channels);
     }
 
     return 0;
@@ -436,6 +483,7 @@
     case AV_CODEC_ID_ADPCM_CT:
     case AV_CODEC_ID_ADPCM_IMA_APC:
     case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
+    case AV_CODEC_ID_ADPCM_IMA_OKI:
     case AV_CODEC_ID_ADPCM_IMA_WS:
     case AV_CODEC_ID_ADPCM_YAMAHA:
         nb_samples = buf_size * 2 / ch;
@@ -450,7 +498,7 @@
         case AV_CODEC_ID_ADPCM_4XM:
         case AV_CODEC_ID_ADPCM_IMA_ISS:     header_size = 4 * ch;      break;
         case AV_CODEC_ID_ADPCM_IMA_AMV:     header_size = 8;           break;
-        case AV_CODEC_ID_ADPCM_IMA_SMJPEG:  header_size = 4;           break;
+        case AV_CODEC_ID_ADPCM_IMA_SMJPEG:  header_size = 4 * ch;      break;
     }
     if (header_size > 0)
         return (buf_size - header_size) * 2 / ch;
@@ -550,7 +598,10 @@
         bytestream2_skip(gb, 4); // channel size
         *coded_samples  = bytestream2_get_be32(gb);
         *coded_samples -= *coded_samples % 14;
-        nb_samples      = (buf_size - 80) / (8 * ch) * 14;
+        nb_samples      = (buf_size - (8 + 36 * ch)) / (8 * ch) * 14;
+        break;
+    case AV_CODEC_ID_ADPCM_AFC:
+        nb_samples = buf_size / (9 * ch) * 16;
         break;
     case AV_CODEC_ID_ADPCM_XA:
         nb_samples = (buf_size / 128) * 224 / ch;
@@ -573,6 +624,7 @@
     ADPCMChannelStatus *cs;
     int n, m, channel, i;
     short *samples;
+    int16_t **samples_p;
     int st; /* stereo */
     int count1, count2;
     int nb_samples, coded_samples, ret;
@@ -592,6 +644,7 @@
         return ret;
     }
     samples = (short *)c->frame.data[0];
+    samples_p = (int16_t **)c->frame.extended_data;
 
     /* use coded_samples when applicable */
     /* it is always <= nb_samples, so the output buffer will be large enough */
@@ -636,21 +689,19 @@
                 return AVERROR_INVALIDDATA;
             }
 
-            samples = (short *)c->frame.data[0] + channel;
+            samples = samples_p[channel];
 
-            for (m = 0; m < 32; m++) {
+            for (m = 0; m < 64; m += 2) {
                 int byte = bytestream2_get_byteu(&gb);
-                *samples = adpcm_ima_qt_expand_nibble(cs, byte & 0x0F, 3);
-                samples += avctx->channels;
-                *samples = adpcm_ima_qt_expand_nibble(cs, byte >> 4  , 3);
-                samples += avctx->channels;
+                samples[m    ] = adpcm_ima_qt_expand_nibble(cs, byte & 0x0F, 3);
+                samples[m + 1] = adpcm_ima_qt_expand_nibble(cs, byte >> 4  , 3);
             }
         }
         break;
     case AV_CODEC_ID_ADPCM_IMA_WAV:
         for(i=0; i<avctx->channels; i++){
             cs = &(c->status[i]);
-            cs->predictor = *samples++ = sign_extend(bytestream2_get_le16u(&gb), 16);
+            cs->predictor = samples_p[i][0] = sign_extend(bytestream2_get_le16u(&gb), 16);
 
             cs->step_index = sign_extend(bytestream2_get_le16u(&gb), 16);
             if (cs->step_index > 88u){
@@ -660,19 +711,16 @@
             }
         }
 
-        for (n = (nb_samples - 1) / 8; n > 0; n--) {
+        for (n = 0; n < (nb_samples - 1) / 8; n++) {
             for (i = 0; i < avctx->channels; i++) {
                 cs = &c->status[i];
-                for (m = 0; m < 4; m++) {
+                samples = &samples_p[i][1 + n * 8];
+                for (m = 0; m < 8; m += 2) {
                     int v = bytestream2_get_byteu(&gb);
-                    *samples = adpcm_ima_expand_nibble(cs, v & 0x0F, 3);
-                    samples += avctx->channels;
-                    *samples = adpcm_ima_expand_nibble(cs, v >> 4  , 3);
-                    samples += avctx->channels;
+                    samples[m    ] = adpcm_ima_expand_nibble(cs, v & 0x0F, 3);
+                    samples[m + 1] = adpcm_ima_expand_nibble(cs, v >> 4  , 3);
                 }
-                samples -= 8 * avctx->channels - 1;
             }
-            samples += 7 * avctx->channels;
         }
         break;
     case AV_CODEC_ID_ADPCM_4XM:
@@ -689,14 +737,12 @@
         }
 
         for (i = 0; i < avctx->channels; i++) {
-            samples = (short *)c->frame.data[0] + i;
+            samples = (int16_t *)c->frame.data[i];
             cs = &c->status[i];
             for (n = nb_samples >> 1; n > 0; n--) {
                 int v = bytestream2_get_byteu(&gb);
-                *samples = adpcm_ima_expand_nibble(cs, v & 0x0F, 4);
-                samples += avctx->channels;
-                *samples = adpcm_ima_expand_nibble(cs, v >> 4  , 4);
-                samples += avctx->channels;
+                *samples++ = adpcm_ima_expand_nibble(cs, v & 0x0F, 4);
+                *samples++ = adpcm_ima_expand_nibble(cs, v >> 4  , 4);
             }
         }
         break;
@@ -855,17 +901,22 @@
             *samples++ = adpcm_ima_expand_nibble(&c->status[st], v & 0x0F, 3);
         }
         break;
+    case AV_CODEC_ID_ADPCM_IMA_OKI:
+        while (bytestream2_get_bytes_left(&gb) > 0) {
+            int v = bytestream2_get_byteu(&gb);
+            *samples++ = adpcm_ima_oki_expand_nibble(&c->status[0],  v >> 4  );
+            *samples++ = adpcm_ima_oki_expand_nibble(&c->status[st], v & 0x0F);
+        }
+        break;
     case AV_CODEC_ID_ADPCM_IMA_WS:
         if (c->vqa_version == 3) {
             for (channel = 0; channel < avctx->channels; channel++) {
-                int16_t *smp = samples + channel;
+                int16_t *smp = samples_p[channel];
 
                 for (n = nb_samples / 2; n > 0; n--) {
                     int v = bytestream2_get_byteu(&gb);
-                    *smp = adpcm_ima_expand_nibble(&c->status[channel], v >> 4  , 3);
-                    smp += avctx->channels;
-                    *smp = adpcm_ima_expand_nibble(&c->status[channel], v & 0x0F, 3);
-                    smp += avctx->channels;
+                    *smp++ = adpcm_ima_expand_nibble(&c->status[channel], v >> 4  , 3);
+                    *smp++ = adpcm_ima_expand_nibble(&c->status[channel], v & 0x0F, 3);
                 }
             }
         } else {
@@ -881,14 +932,21 @@
         bytestream2_seek(&gb, 0, SEEK_END);
         break;
     case AV_CODEC_ID_ADPCM_XA:
+    {
+        int16_t *out0 = samples_p[0];
+        int16_t *out1 = samples_p[1];
+        int samples_per_block = 28 * (3 - avctx->channels) * 4;
+        int sample_offset = 0;
         while (bytestream2_get_bytes_left(&gb) >= 128) {
-            if ((ret = xa_decode(avctx, samples, buf + bytestream2_tell(&gb), &c->status[0],
-                                 &c->status[1], avctx->channels)) < 0)
+            if ((ret = xa_decode(avctx, out0, out1, buf + bytestream2_tell(&gb),
+                                 &c->status[0], &c->status[1],
+                                 avctx->channels, sample_offset)) < 0)
                 return ret;
             bytestream2_skipu(&gb, 128);
-            samples += 28 * 8;
+            sample_offset += samples_per_block;
         }
         break;
+    }
     case AV_CODEC_ID_ADPCM_IMA_EA_EACS:
         for (i=0; i<=st; i++) {
             c->status[i].step_index = bytestream2_get_le32u(&gb);
@@ -1022,7 +1080,7 @@
 
         for (channel=0; channel<avctx->channels; channel++) {
             bytestream2_seek(&gb, offsets[channel], SEEK_SET);
-            samplesC = samples + channel;
+            samplesC = samples_p[channel];
 
             if (avctx->codec->id == AV_CODEC_ID_ADPCM_EA_R1) {
                 current_sample  = sign_extend(bytestream2_get_le16(&gb), 16);
@@ -1038,10 +1096,8 @@
                     current_sample  = sign_extend(bytestream2_get_be16(&gb), 16);
                     previous_sample = sign_extend(bytestream2_get_be16(&gb), 16);
 
-                    for (count2=0; count2<28; count2++) {
-                        *samplesC = sign_extend(bytestream2_get_be16(&gb), 16);
-                        samplesC += avctx->channels;
-                    }
+                    for (count2=0; count2<28; count2++)
+                        *samplesC++ = sign_extend(bytestream2_get_be16(&gb), 16);
                 } else {
                     coeff1 = ea_adpcm_table[ byte >> 4     ];
                     coeff2 = ea_adpcm_table[(byte >> 4) + 4];
@@ -1061,8 +1117,7 @@
 
                         previous_sample = current_sample;
                         current_sample  = next_sample;
-                        *samplesC = current_sample;
-                        samplesC += avctx->channels;
+                        *samplesC++ = current_sample;
                     }
                 }
             }
@@ -1086,8 +1141,8 @@
     case AV_CODEC_ID_ADPCM_EA_XAS:
         for (channel=0; channel<avctx->channels; channel++) {
             int coeff[2][4], shift[4];
-            short *s2, *s = &samples[channel];
-            for (n=0; n<4; n++, s+=32*avctx->channels) {
+            int16_t *s = samples_p[channel];
+            for (n = 0; n < 4; n++, s += 32) {
                 int val = sign_extend(bytestream2_get_le16u(&gb), 16);
                 for (i=0; i<2; i++)
                     coeff[i][n] = ea_adpcm_table[(val&0x0F)+4*i];
@@ -1095,34 +1150,30 @@
 
                 val = sign_extend(bytestream2_get_le16u(&gb), 16);
                 shift[n] = 20 - (val & 0x0F);
-                s[avctx->channels] = val & ~0x0F;
+                s[1] = val & ~0x0F;
             }
 
             for (m=2; m<32; m+=2) {
-                s = &samples[m*avctx->channels + channel];
-                for (n=0; n<4; n++, s+=32*avctx->channels) {
+                s = &samples_p[channel][m];
+                for (n = 0; n < 4; n++, s += 32) {
+                    int level, pred;
                     int byte = bytestream2_get_byteu(&gb);
-                    for (s2=s, i=0; i<8; i+=4, s2+=avctx->channels) {
-                        int level = sign_extend(byte >> (4 - i), 4) << shift[n];
-                        int pred  = s2[-1*avctx->channels] * coeff[0][n]
-                                  + s2[-2*avctx->channels] * coeff[1][n];
-                        s2[0] = av_clip_int16((level + pred + 0x80) >> 8);
-                    }
+
+                    level = sign_extend(byte >> 4, 4) << shift[n];
+                    pred  = s[-1] * coeff[0][n] + s[-2] * coeff[1][n];
+                    s[0]  = av_clip_int16((level + pred + 0x80) >> 8);
+
+                    level = sign_extend(byte, 4) << shift[n];
+                    pred  = s[0] * coeff[0][n] + s[-1] * coeff[1][n];
+                    s[1]  = av_clip_int16((level + pred + 0x80) >> 8);
                 }
             }
         }
         break;
     case AV_CODEC_ID_ADPCM_IMA_AMV:
-    case AV_CODEC_ID_ADPCM_IMA_SMJPEG:
-        if (avctx->codec->id == AV_CODEC_ID_ADPCM_IMA_AMV) {
-            c->status[0].predictor = sign_extend(bytestream2_get_le16u(&gb), 16);
-            c->status[0].step_index = bytestream2_get_le16u(&gb);
-            bytestream2_skipu(&gb, 4);
-        } else {
-            c->status[0].predictor = sign_extend(bytestream2_get_be16u(&gb), 16);
-            c->status[0].step_index = bytestream2_get_byteu(&gb);
-            bytestream2_skipu(&gb, 1);
-        }
+        c->status[0].predictor = sign_extend(bytestream2_get_le16u(&gb), 16);
+        c->status[0].step_index = bytestream2_get_le16u(&gb);
+        bytestream2_skipu(&gb, 4);
         if (c->status[0].step_index > 88u) {
             av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n",
                    c->status[0].step_index);
@@ -1130,18 +1181,29 @@
         }
 
         for (n = nb_samples >> (1 - st); n > 0; n--) {
-            int hi, lo, v = bytestream2_get_byteu(&gb);
+            int v = bytestream2_get_byteu(&gb);
 
-            if (avctx->codec->id == AV_CODEC_ID_ADPCM_IMA_AMV) {
-                hi = v & 0x0F;
-                lo = v >> 4;
-            } else {
-                lo = v & 0x0F;
-                hi = v >> 4;
+            *samples++ = adpcm_ima_expand_nibble(&c->status[0], v >> 4, 3);
+            *samples++ = adpcm_ima_expand_nibble(&c->status[0], v & 0xf, 3);
+        }
+        break;
+    case AV_CODEC_ID_ADPCM_IMA_SMJPEG:
+        for (i = 0; i < avctx->channels; i++) {
+            c->status[i].predictor = sign_extend(bytestream2_get_be16u(&gb), 16);
+            c->status[i].step_index = bytestream2_get_byteu(&gb);
+            bytestream2_skipu(&gb, 1);
+            if (c->status[i].step_index > 88u) {
+                av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n",
+                       c->status[i].step_index);
+                return AVERROR_INVALIDDATA;
             }
+        }
 
-            *samples++ = adpcm_ima_expand_nibble(&c->status[0], lo, 3);
-            *samples++ = adpcm_ima_expand_nibble(&c->status[0], hi, 3);
+        for (n = nb_samples >> (1 - st); n > 0; n--) {
+            int v = bytestream2_get_byteu(&gb);
+
+            *samples++ = adpcm_ima_qt_expand_nibble(&c->status[0 ], v >> 4, 3);
+            *samples++ = adpcm_ima_qt_expand_nibble(&c->status[st], v & 0xf, 3);
         }
         break;
     case AV_CODEC_ID_ADPCM_CT:
@@ -1205,23 +1267,76 @@
             *samples++ = adpcm_yamaha_expand_nibble(&c->status[st], v >> 4  );
         }
         break;
+    case AV_CODEC_ID_ADPCM_AFC:
+    {
+        int samples_per_block;
+        int blocks;
+
+        if (avctx->extradata && avctx->extradata_size == 1 && avctx->extradata[0]) {
+            samples_per_block = avctx->extradata[0] / 16;
+            blocks = nb_samples / avctx->extradata[0];
+        } else {
+            samples_per_block = nb_samples / 16;
+            blocks = 1;
+        }
+
+        for (m = 0; m < blocks; m++) {
+        for (channel = 0; channel < avctx->channels; channel++) {
+            int prev1 = c->status[channel].sample1;
+            int prev2 = c->status[channel].sample2;
+
+            samples = samples_p[channel] + m * 16;
+            /* Read in every sample for this channel.  */
+            for (i = 0; i < samples_per_block; i++) {
+                int byte = bytestream2_get_byteu(&gb);
+                int scale = 1 << (byte >> 4);
+                int index = byte & 0xf;
+                int factor1 = ff_adpcm_afc_coeffs[0][index];
+                int factor2 = ff_adpcm_afc_coeffs[1][index];
+
+                /* Decode 16 samples.  */
+                for (n = 0; n < 16; n++) {
+                    int32_t sampledat;
+
+                    if (n & 1) {
+                        sampledat = sign_extend(byte, 4);
+                    } else {
+                        byte = bytestream2_get_byteu(&gb);
+                        sampledat = sign_extend(byte >> 4, 4);
+                    }
+
+                    sampledat = ((prev1 * factor1 + prev2 * factor2) +
+                                 ((sampledat * scale) << 11)) >> 11;
+                    *samples = av_clip_int16(sampledat);
+                    prev2 = prev1;
+                    prev1 = *samples++;
+                }
+            }
+
+            c->status[channel].sample1 = prev1;
+            c->status[channel].sample2 = prev2;
+        }
+        }
+        bytestream2_seek(&gb, 0, SEEK_END);
+        break;
+    }
     case AV_CODEC_ID_ADPCM_THP:
     {
-        int table[2][16];
-        int prev[2][2];
+        int table[6][16];
         int ch;
 
-        for (i = 0; i < 2; i++)
+        for (i = 0; i < avctx->channels; i++)
             for (n = 0; n < 16; n++)
                 table[i][n] = sign_extend(bytestream2_get_be16u(&gb), 16);
 
         /* Initialize the previous sample.  */
-        for (i = 0; i < 2; i++)
-            for (n = 0; n < 2; n++)
-                prev[i][n] = sign_extend(bytestream2_get_be16u(&gb), 16);
+        for (i = 0; i < avctx->channels; i++) {
+            c->status[i].sample1 = sign_extend(bytestream2_get_be16u(&gb), 16);
+            c->status[i].sample2 = sign_extend(bytestream2_get_be16u(&gb), 16);
+        }
 
-        for (ch = 0; ch <= st; ch++) {
-            samples = (short *)c->frame.data[0] + ch;
+        for (ch = 0; ch < avctx->channels; ch++) {
+            samples = samples_p[ch];
 
             /* Read in every sample for this channel.  */
             for (i = 0; i < nb_samples / 14; i++) {
@@ -1242,15 +1357,11 @@
                         sampledat = sign_extend(byte >> 4, 4);
                     }
 
-                    sampledat = ((prev[ch][0]*factor1
-                                + prev[ch][1]*factor2) >> 11) + (sampledat << exp);
+                    sampledat = ((c->status[ch].sample1 * factor1
+                                + c->status[ch].sample2 * factor2) >> 11) + (sampledat << exp);
                     *samples = av_clip_int16(sampledat);
-                    prev[ch][1] = prev[ch][0];
-                    prev[ch][0] = *samples++;
-
-                    /* In case of stereo, skip one sample, this sample
-                       is for the other channel.  */
-                    samples += st;
+                    c->status[ch].sample2 = c->status[ch].sample1;
+                    c->status[ch].sample1 = *samples++;
                 }
             }
         }
@@ -1261,6 +1372,11 @@
         return -1;
     }
 
+    if (avpkt->size && bytestream2_tell(&gb) == 0) {
+        av_log(avctx, AV_LOG_ERROR, "Nothing consumed\n");
+        return AVERROR_INVALIDDATA;
+    }
+
     *got_frame_ptr   = 1;
     *(AVFrame *)data = c->frame;
 
@@ -1268,7 +1384,15 @@
 }
 
 
-#define ADPCM_DECODER(id_, name_, long_name_)               \
+static const enum AVSampleFormat sample_fmts_s16[]  = { AV_SAMPLE_FMT_S16,
+                                                        AV_SAMPLE_FMT_NONE };
+static const enum AVSampleFormat sample_fmts_s16p[] = { AV_SAMPLE_FMT_S16,
+                                                        AV_SAMPLE_FMT_NONE };
+static const enum AVSampleFormat sample_fmts_both[] = { AV_SAMPLE_FMT_S16,
+                                                        AV_SAMPLE_FMT_S16P,
+                                                        AV_SAMPLE_FMT_NONE };
+
+#define ADPCM_DECODER(id_, sample_fmts_, name_, long_name_) \
 AVCodec ff_ ## name_ ## _decoder = {                        \
     .name           = #name_,                               \
     .type           = AVMEDIA_TYPE_AUDIO,                   \
@@ -1278,33 +1402,36 @@
     .decode         = adpcm_decode_frame,                   \
     .capabilities   = CODEC_CAP_DR1,                        \
     .long_name      = NULL_IF_CONFIG_SMALL(long_name_),     \
+    .sample_fmts    = sample_fmts_,                         \
 }
 
 /* Note: Do not forget to add new entries to the Makefile as well. */
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_4XM, adpcm_4xm, "ADPCM 4X Movie");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_CT, adpcm_ct, "ADPCM Creative Technology");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_EA, adpcm_ea, "ADPCM Electronic Arts");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_EA_MAXIS_XA, adpcm_ea_maxis_xa, "ADPCM Electronic Arts Maxis CDROM XA");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_EA_R1, adpcm_ea_r1, "ADPCM Electronic Arts R1");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_EA_R2, adpcm_ea_r2, "ADPCM Electronic Arts R2");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_EA_R3, adpcm_ea_r3, "ADPCM Electronic Arts R3");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_EA_XAS, adpcm_ea_xas, "ADPCM Electronic Arts XAS");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_AMV, adpcm_ima_amv, "ADPCM IMA AMV");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_APC, adpcm_ima_apc, "ADPCM IMA CRYO APC");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_DK3, adpcm_ima_dk3, "ADPCM IMA Duck DK3");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_DK4, adpcm_ima_dk4, "ADPCM IMA Duck DK4");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_EA_EACS, adpcm_ima_ea_eacs, "ADPCM IMA Electronic Arts EACS");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_EA_SEAD, adpcm_ima_ea_sead, "ADPCM IMA Electronic Arts SEAD");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_ISS, adpcm_ima_iss, "ADPCM IMA Funcom ISS");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_QT, adpcm_ima_qt, "ADPCM IMA QuickTime");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_SMJPEG, adpcm_ima_smjpeg, "ADPCM IMA Loki SDL MJPEG");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_WAV, adpcm_ima_wav, "ADPCM IMA WAV");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_WS, adpcm_ima_ws, "ADPCM IMA Westwood");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_MS, adpcm_ms, "ADPCM Microsoft");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_SBPRO_2, adpcm_sbpro_2, "ADPCM Sound Blaster Pro 2-bit");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_SBPRO_3, adpcm_sbpro_3, "ADPCM Sound Blaster Pro 2.6-bit");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_SBPRO_4, adpcm_sbpro_4, "ADPCM Sound Blaster Pro 4-bit");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_SWF, adpcm_swf, "ADPCM Shockwave Flash");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_THP, adpcm_thp, "ADPCM Nintendo Gamecube THP");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_XA, adpcm_xa, "ADPCM CDROM XA");
-ADPCM_DECODER(AV_CODEC_ID_ADPCM_YAMAHA, adpcm_yamaha, "ADPCM Yamaha");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_4XM,         sample_fmts_s16p, adpcm_4xm,         "ADPCM 4X Movie");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_AFC,         sample_fmts_s16p, adpcm_afc,         "ADPCM Nintendo Gamecube AFC");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_CT,          sample_fmts_s16,  adpcm_ct,          "ADPCM Creative Technology");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_EA,          sample_fmts_s16,  adpcm_ea,          "ADPCM Electronic Arts");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_EA_MAXIS_XA, sample_fmts_s16,  adpcm_ea_maxis_xa, "ADPCM Electronic Arts Maxis CDROM XA");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_EA_R1,       sample_fmts_s16p, adpcm_ea_r1,       "ADPCM Electronic Arts R1");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_EA_R2,       sample_fmts_s16p, adpcm_ea_r2,       "ADPCM Electronic Arts R2");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_EA_R3,       sample_fmts_s16p, adpcm_ea_r3,       "ADPCM Electronic Arts R3");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_EA_XAS,      sample_fmts_s16p, adpcm_ea_xas,      "ADPCM Electronic Arts XAS");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_AMV,     sample_fmts_s16,  adpcm_ima_amv,     "ADPCM IMA AMV");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_APC,     sample_fmts_s16,  adpcm_ima_apc,     "ADPCM IMA CRYO APC");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_DK3,     sample_fmts_s16,  adpcm_ima_dk3,     "ADPCM IMA Duck DK3");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_DK4,     sample_fmts_s16,  adpcm_ima_dk4,     "ADPCM IMA Duck DK4");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_EA_EACS, sample_fmts_s16,  adpcm_ima_ea_eacs, "ADPCM IMA Electronic Arts EACS");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_EA_SEAD, sample_fmts_s16,  adpcm_ima_ea_sead, "ADPCM IMA Electronic Arts SEAD");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_ISS,     sample_fmts_s16,  adpcm_ima_iss,     "ADPCM IMA Funcom ISS");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_OKI,     sample_fmts_s16,  adpcm_ima_oki,     "ADPCM IMA Dialogic OKI");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_QT,      sample_fmts_s16p, adpcm_ima_qt,      "ADPCM IMA QuickTime");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_SMJPEG,  sample_fmts_s16,  adpcm_ima_smjpeg,  "ADPCM IMA Loki SDL MJPEG");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_WAV,     sample_fmts_s16p, adpcm_ima_wav,     "ADPCM IMA WAV");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_WS,      sample_fmts_both, adpcm_ima_ws,      "ADPCM IMA Westwood");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_MS,          sample_fmts_s16,  adpcm_ms,          "ADPCM Microsoft");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_SBPRO_2,     sample_fmts_s16,  adpcm_sbpro_2,     "ADPCM Sound Blaster Pro 2-bit");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_SBPRO_3,     sample_fmts_s16,  adpcm_sbpro_3,     "ADPCM Sound Blaster Pro 2.6-bit");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_SBPRO_4,     sample_fmts_s16,  adpcm_sbpro_4,     "ADPCM Sound Blaster Pro 4-bit");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_SWF,         sample_fmts_s16,  adpcm_swf,         "ADPCM Shockwave Flash");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_THP,         sample_fmts_s16p, adpcm_thp,         "ADPCM Nintendo Gamecube THP");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_XA,          sample_fmts_s16p, adpcm_xa,          "ADPCM CDROM XA");
+ADPCM_DECODER(AV_CODEC_ID_ADPCM_YAMAHA,      sample_fmts_s16,  adpcm_yamaha,      "ADPCM Yamaha");
diff --git a/libavcodec/adpcm_data.c b/libavcodec/adpcm_data.c
index f19d622..0625fc9 100644
--- a/libavcodec/adpcm_data.c
+++ b/libavcodec/adpcm_data.c
@@ -49,6 +49,14 @@
     15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
 };
 
+const int16_t ff_adpcm_oki_step_table[49] = {
+     16,  17,  19,  21,   23,   25,   28,   31,   34,  37,
+     41,  45,  50,  55,   60,   66,   73,   80,   88,  97,
+    107, 118, 130, 143,  157,  173,  190,  209,  230, 253,
+    279, 307, 337, 371,  408,  449,  494,  544,  598, 658,
+    724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552
+};
+
 /* These are for MS-ADPCM */
 /* ff_adpcm_AdaptationTable[], ff_adpcm_AdaptCoeff1[], and
    ff_adpcm_AdaptCoeff2[] are from libsndfile */
@@ -76,3 +84,8 @@
      1,  3,  5,  7,  9,  11,  13,  15,
     -1, -3, -5, -7, -9, -11, -13, -15
 };
+
+const int16_t ff_adpcm_afc_coeffs[2][16] = {
+    { 0, 2048, 0, 1024, 4096, 3584, 3072, 4608, 4200, 4800, 5120, 2048, 1024, 64512, 64512, 63488 },
+    { 0, 0, 2048, 1024, 63488, 64000, 64512, 62976, 63288, 63236, 62464, 63488, 64512, 1024, 0, 0 }
+};
diff --git a/libavcodec/adpcm_data.h b/libavcodec/adpcm_data.h
index 97ab66c..0ebb7c3 100644
--- a/libavcodec/adpcm_data.h
+++ b/libavcodec/adpcm_data.h
@@ -30,10 +30,12 @@
 
 extern const int8_t  ff_adpcm_index_table[16];
 extern const int16_t ff_adpcm_step_table[89];
+extern const int16_t ff_adpcm_oki_step_table[49];
 extern const int16_t ff_adpcm_AdaptationTable[];
 extern const uint8_t ff_adpcm_AdaptCoeff1[];
 extern const int8_t  ff_adpcm_AdaptCoeff2[];
 extern const int16_t ff_adpcm_yamaha_indexscale[];
 extern const int8_t  ff_adpcm_yamaha_difflookup[];
+extern const int16_t ff_adpcm_afc_coeffs[2][16];
 
 #endif /* AVCODEC_ADPCM_DATA_H */
diff --git a/libavcodec/adpcmenc.c b/libavcodec/adpcmenc.c
index a3194ab..217d165 100644
--- a/libavcodec/adpcmenc.c
+++ b/libavcodec/adpcmenc.c
@@ -274,12 +274,11 @@
 
 static void adpcm_compress_trellis(AVCodecContext *avctx,
                                    const int16_t *samples, uint8_t *dst,
-                                   ADPCMChannelStatus *c, int n)
+                                   ADPCMChannelStatus *c, int n, int stride)
 {
     //FIXME 6% faster if frontier is a compile-time constant
     ADPCMEncodeContext *s = avctx->priv_data;
     const int frontier = 1 << avctx->trellis;
-    const int stride   = avctx->channels;
     const int version  = avctx->codec->id;
     TrellisPath *paths       = s->paths, *p;
     TrellisNode *node_buf    = s->node_buf;
@@ -377,7 +376,7 @@
                     *h = generation;\
                     u  = nodes_next[pos];\
                     if (!u) {\
-                        assert(pathn < FREEZE_INTERVAL << avctx->trellis);\
+                        av_assert1(pathn < FREEZE_INTERVAL << avctx->trellis);\
                         u = t++;\
                         nodes_next[pos] = u;\
                         u->path = pathn++;\
@@ -481,13 +480,15 @@
 static int adpcm_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
                               const AVFrame *frame, int *got_packet_ptr)
 {
-    int n, i, st, pkt_size, ret;
+    int n, i, ch, st, pkt_size, ret;
     const int16_t *samples;
+    int16_t **samples_p;
     uint8_t *dst;
     ADPCMEncodeContext *c = avctx->priv_data;
     uint8_t *buf;
 
     samples = (const int16_t *)frame->data[0];
+    samples_p = (int16_t **)frame->extended_data;
     st = avctx->channels == 2;
 
     if (avctx->codec_id == AV_CODEC_ID_ADPCM_SWF)
@@ -500,91 +501,72 @@
 
     switch(avctx->codec->id) {
     case AV_CODEC_ID_ADPCM_IMA_WAV:
-        n = frame->nb_samples / 8;
-        c->status[0].prev_sample = samples[0];
-        /* c->status[0].step_index = 0;
-        XXX: not sure how to init the state machine */
-        bytestream_put_le16(&dst, c->status[0].prev_sample);
-        *dst++ = c->status[0].step_index;
-        *dst++ = 0; /* unknown */
-        samples++;
-        if (avctx->channels == 2) {
-            c->status[1].prev_sample = samples[0];
-            /* c->status[1].step_index = 0; */
-            bytestream_put_le16(&dst, c->status[1].prev_sample);
-            *dst++ = c->status[1].step_index;
-            *dst++ = 0;
-            samples++;
+    {
+        int blocks, j;
+
+        blocks = (frame->nb_samples - 1) / 8;
+
+        for (ch = 0; ch < avctx->channels; ch++) {
+            ADPCMChannelStatus *status = &c->status[ch];
+            status->prev_sample = samples_p[ch][0];
+            /* status->step_index = 0;
+               XXX: not sure how to init the state machine */
+            bytestream_put_le16(&dst, status->prev_sample);
+            *dst++ = status->step_index;
+            *dst++ = 0; /* unknown */
         }
 
-        /* stereo: 4 bytes (8 samples) for left,
-            4 bytes for right, 4 bytes left, ... */
+        /* stereo: 4 bytes (8 samples) for left, 4 bytes for right */
         if (avctx->trellis > 0) {
-            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 + n * 8,
-                                       &c->status[1], n * 8);
-            for (i = 0; i < n; i++) {
-                *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) {
-                    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);
+            FF_ALLOC_OR_GOTO(avctx, buf, avctx->channels * blocks * 8, error);
+            for (ch = 0; ch < avctx->channels; ch++) {
+                adpcm_compress_trellis(avctx, &samples_p[ch][1],
+                                       buf + ch * blocks * 8, &c->status[ch],
+                                       blocks * 8, 1);
+            }
+            for (i = 0; i < blocks; i++) {
+                for (ch = 0; ch < avctx->channels; ch++) {
+                    uint8_t *buf1 = buf + ch * blocks * 8 + i * 8;
+                    for (j = 0; j < 8; j += 2)
+                        *dst++ = buf1[j] | (buf1[j + 1] << 4);
                 }
             }
             av_free(buf);
         } else {
-            for (; n > 0; n--) {
-                *dst    = adpcm_ima_compress_sample(&c->status[0], samples[0]);
-                *dst++ |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels    ]) << 4;
-                *dst    = adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 2]);
-                *dst++ |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 3]) << 4;
-                *dst    = adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 4]);
-                *dst++ |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 5]) << 4;
-                *dst    = adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 6]);
-                *dst++ |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 7]) << 4;
-                /* right channel */
-                if (avctx->channels == 2) {
-                    *dst    = adpcm_ima_compress_sample(&c->status[1], samples[1 ]);
-                    *dst++ |= adpcm_ima_compress_sample(&c->status[1], samples[3 ]) << 4;
-                    *dst    = adpcm_ima_compress_sample(&c->status[1], samples[5 ]);
-                    *dst++ |= adpcm_ima_compress_sample(&c->status[1], samples[7 ]) << 4;
-                    *dst    = adpcm_ima_compress_sample(&c->status[1], samples[9 ]);
-                    *dst++ |= adpcm_ima_compress_sample(&c->status[1], samples[11]) << 4;
-                    *dst    = adpcm_ima_compress_sample(&c->status[1], samples[13]);
-                    *dst++ |= adpcm_ima_compress_sample(&c->status[1], samples[15]) << 4;
+            for (i = 0; i < blocks; i++) {
+                for (ch = 0; ch < avctx->channels; ch++) {
+                    ADPCMChannelStatus *status = &c->status[ch];
+                    const int16_t *smp = &samples_p[ch][1 + i * 8];
+                    for (j = 0; j < 8; j += 2) {
+                        uint8_t v = adpcm_ima_compress_sample(status, smp[j    ]);
+                        v        |= adpcm_ima_compress_sample(status, smp[j + 1]) << 4;
+                        *dst++ = v;
+                    }
                 }
-                samples += 8 * avctx->channels;
             }
         }
         break;
+    }
     case AV_CODEC_ID_ADPCM_IMA_QT:
     {
-        int ch, i;
         PutBitContext pb;
         init_put_bits(&pb, dst, pkt_size * 8);
 
         for (ch = 0; ch < avctx->channels; ch++) {
-            put_bits(&pb, 9, (c->status[ch].prev_sample & 0xFFFF) >> 7);
-            put_bits(&pb, 7,  c->status[ch].step_index);
+            ADPCMChannelStatus *status = &c->status[ch];
+            put_bits(&pb, 9, (status->prev_sample & 0xFFFF) >> 7);
+            put_bits(&pb, 7,  status->step_index);
             if (avctx->trellis > 0) {
                 uint8_t buf[64];
-                adpcm_compress_trellis(avctx, samples+ch, buf, &c->status[ch], 64);
+                adpcm_compress_trellis(avctx, &samples_p[ch][1], buf, status,
+                                       64, 1);
                 for (i = 0; i < 64; i++)
                     put_bits(&pb, 4, buf[i ^ 1]);
             } else {
                 for (i = 0; i < 64; i += 2) {
                     int t1, t2;
-                    t1 = adpcm_ima_qt_compress_sample(&c->status[ch],
-                                                      samples[avctx->channels * (i + 0) + ch]);
-                    t2 = adpcm_ima_qt_compress_sample(&c->status[ch],
-                                                      samples[avctx->channels * (i + 1) + ch]);
+                    t1 = adpcm_ima_qt_compress_sample(status, samples_p[ch][i    ]);
+                    t2 = adpcm_ima_qt_compress_sample(status, samples_p[ch][i + 1]);
                     put_bits(&pb, 4, t2);
                     put_bits(&pb, 4, t1);
                 }
@@ -596,7 +578,6 @@
     }
     case AV_CODEC_ID_ADPCM_SWF:
     {
-        int i;
         PutBitContext pb;
         init_put_bits(&pb, dst, pkt_size * 8);
 
@@ -617,10 +598,11 @@
         if (avctx->trellis > 0) {
             FF_ALLOC_OR_GOTO(avctx, buf, 2 * n, error);
             adpcm_compress_trellis(avctx, samples + avctx->channels, buf,
-                                   &c->status[0], n);
+                                   &c->status[0], n, avctx->channels);
             if (avctx->channels == 2)
                 adpcm_compress_trellis(avctx, samples + avctx->channels + 1,
-                                       buf + n, &c->status[1], n);
+                                       buf + n, &c->status[1], n,
+                                       avctx->channels);
             for (i = 0; i < n; i++) {
                 put_bits(&pb, 4, buf[i]);
                 if (avctx->channels == 2)
@@ -661,15 +643,18 @@
             bytestream_put_le16(&dst, c->status[i].sample2);
 
         if (avctx->trellis > 0) {
-            int n = avctx->block_align - 7 * avctx->channels;
+            n = avctx->block_align - 7 * avctx->channels;
             FF_ALLOC_OR_GOTO(avctx, buf, 2 * n, error);
             if (avctx->channels == 1) {
-                adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n);
+                adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n,
+                                       avctx->channels);
                 for (i = 0; i < n; i += 2)
                     *dst++ = (buf[i] << 4) | buf[i + 1];
             } else {
-                adpcm_compress_trellis(avctx, samples,     buf,     &c->status[0], n);
-                adpcm_compress_trellis(avctx, samples + 1, buf + n, &c->status[1], n);
+                adpcm_compress_trellis(avctx, samples,     buf,
+                                       &c->status[0], n, avctx->channels);
+                adpcm_compress_trellis(avctx, samples + 1, buf + n,
+                                       &c->status[1], n, avctx->channels);
                 for (i = 0; i < n; i++)
                     *dst++ = (buf[i] << 4) | buf[n + i];
             }
@@ -689,12 +674,15 @@
             FF_ALLOC_OR_GOTO(avctx, buf, 2 * n * 2, error);
             n *= 2;
             if (avctx->channels == 1) {
-                adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n);
+                adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n,
+                                       avctx->channels);
                 for (i = 0; i < n; i += 2)
                     *dst++ = buf[i] | (buf[i + 1] << 4);
             } else {
-                adpcm_compress_trellis(avctx, samples,     buf,     &c->status[0], n);
-                adpcm_compress_trellis(avctx, samples + 1, buf + n, &c->status[1], n);
+                adpcm_compress_trellis(avctx, samples,     buf,
+                                       &c->status[0], n, avctx->channels);
+                adpcm_compress_trellis(avctx, samples + 1, buf + n,
+                                       &c->status[1], n, avctx->channels);
                 for (i = 0; i < n; i++)
                     *dst++ = buf[i] | (buf[n + i] << 4);
             }
@@ -722,7 +710,11 @@
     AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
 };
 
-#define ADPCM_ENCODER(id_, name_, long_name_)               \
+static const enum AVSampleFormat sample_fmts_p[] = {
+    AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_NONE
+};
+
+#define ADPCM_ENCODER(id_, name_, sample_fmts_, long_name_) \
 AVCodec ff_ ## name_ ## _encoder = {                        \
     .name           = #name_,                               \
     .type           = AVMEDIA_TYPE_AUDIO,                   \
@@ -731,12 +723,12 @@
     .init           = adpcm_encode_init,                    \
     .encode2        = adpcm_encode_frame,                   \
     .close          = adpcm_encode_close,                   \
-    .sample_fmts    = sample_fmts,                          \
+    .sample_fmts    = sample_fmts_,                         \
     .long_name      = NULL_IF_CONFIG_SMALL(long_name_),     \
 }
 
-ADPCM_ENCODER(AV_CODEC_ID_ADPCM_IMA_QT, adpcm_ima_qt,   "ADPCM IMA QuickTime");
-ADPCM_ENCODER(AV_CODEC_ID_ADPCM_IMA_WAV, adpcm_ima_wav, "ADPCM IMA WAV");
-ADPCM_ENCODER(AV_CODEC_ID_ADPCM_MS, adpcm_ms,           "ADPCM Microsoft");
-ADPCM_ENCODER(AV_CODEC_ID_ADPCM_SWF, adpcm_swf,         "ADPCM Shockwave Flash");
-ADPCM_ENCODER(AV_CODEC_ID_ADPCM_YAMAHA, adpcm_yamaha,   "ADPCM Yamaha");
+ADPCM_ENCODER(AV_CODEC_ID_ADPCM_IMA_QT,  adpcm_ima_qt,  sample_fmts_p, "ADPCM IMA QuickTime");
+ADPCM_ENCODER(AV_CODEC_ID_ADPCM_IMA_WAV, adpcm_ima_wav, sample_fmts_p, "ADPCM IMA WAV");
+ADPCM_ENCODER(AV_CODEC_ID_ADPCM_MS,      adpcm_ms,      sample_fmts,   "ADPCM Microsoft");
+ADPCM_ENCODER(AV_CODEC_ID_ADPCM_SWF,     adpcm_swf,     sample_fmts,   "ADPCM Shockwave Flash");
+ADPCM_ENCODER(AV_CODEC_ID_ADPCM_YAMAHA,  adpcm_yamaha,  sample_fmts,   "ADPCM Yamaha");
diff --git a/libavcodec/adx.c b/libavcodec/adx.c
index 870216c..7da696d 100644
--- a/libavcodec/adx.c
+++ b/libavcodec/adx.c
@@ -47,6 +47,11 @@
         return AVERROR_INVALIDDATA;
     offset = AV_RB16(buf + 2) + 4;
 
+    if (offset < 6) {
+        av_log(avctx, AV_LOG_ERROR, "offset is prior data\n");
+        return AVERROR_INVALIDDATA;
+    }
+
     /* if copyright string is within the provided data, validate it */
     if (bufsize >= offset && memcmp(buf + offset - 6, "(c)CRI", 6))
         return AVERROR_INVALIDDATA;
diff --git a/libavcodec/adx.h b/libavcodec/adx.h
index a14ddce..85b35d1 100644
--- a/libavcodec/adx.h
+++ b/libavcodec/adx.h
@@ -35,11 +35,11 @@
 
 #include "avcodec.h"
 
-typedef struct {
+typedef struct ADXChannelState {
     int s1,s2;
 } ADXChannelState;
 
-typedef struct {
+typedef struct ADXContext {
     AVFrame frame;
     int channels;
     ADXChannelState prev[2];
diff --git a/libavcodec/adxdec.c b/libavcodec/adxdec.c
index 0ac9bce..901d717 100644
--- a/libavcodec/adxdec.c
+++ b/libavcodec/adxdec.c
@@ -49,7 +49,7 @@
         c->header_parsed = 1;
     }
 
-    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
 
     avcodec_get_frame_defaults(&c->frame);
     avctx->coded_frame = &c->frame;
@@ -64,7 +64,8 @@
  * 2nd-order LPC filter applied to it to form the output signal for a single
  * channel.
  */
-static int adx_decode(ADXContext *c, int16_t *out, const uint8_t *in, int ch)
+static int adx_decode(ADXContext *c, int16_t *out, int offset,
+                      const uint8_t *in, int ch)
 {
     ADXChannelState *prev = &c->prev[ch];
     GetBitContext gb;
@@ -77,6 +78,7 @@
         return -1;
 
     init_get_bits(&gb, in + 2, (BLOCK_SIZE - 2) * 8);
+    out += offset;
     s1 = prev->s1;
     s2 = prev->s2;
     for (i = 0; i < BLOCK_SAMPLES; i++) {
@@ -84,8 +86,7 @@
         s0 = ((d << COEFF_BITS) * scale + c->coeff[0] * s1 + c->coeff[1] * s2) >> COEFF_BITS;
         s2 = s1;
         s1 = av_clip_int16(s0);
-        *out = s1;
-        out += c->channels;
+        *out++ = s1;
     }
     prev->s1 = s1;
     prev->s2 = s2;
@@ -98,7 +99,8 @@
 {
     int buf_size        = avpkt->size;
     ADXContext *c       = avctx->priv_data;
-    int16_t *samples;
+    int16_t **samples;
+    int samples_offset;
     const uint8_t *buf  = avpkt->data;
     const uint8_t *buf_end = buf + avpkt->size;
     int num_blocks, ch, ret;
@@ -145,11 +147,12 @@
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         return ret;
     }
-    samples = (int16_t *)c->frame.data[0];
+    samples = (int16_t **)c->frame.extended_data;
+    samples_offset = 0;
 
     while (num_blocks--) {
         for (ch = 0; ch < c->channels; ch++) {
-            if (buf_end - buf < BLOCK_SIZE || adx_decode(c, samples + ch, buf, ch)) {
+            if (buf_end - buf < BLOCK_SIZE || adx_decode(c, samples[ch], samples_offset, buf, ch)) {
                 c->eof = 1;
                 buf = avpkt->data + avpkt->size;
                 break;
@@ -157,7 +160,7 @@
             buf_size -= BLOCK_SIZE;
             buf      += BLOCK_SIZE;
         }
-        samples += BLOCK_SAMPLES * c->channels;
+        samples_offset += BLOCK_SAMPLES;
     }
 
     *got_frame_ptr   = 1;
@@ -183,4 +186,6 @@
     .flush          = adx_decode_flush,
     .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("SEGA CRI ADX ADPCM"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
+                                                      AV_SAMPLE_FMT_NONE },
 };
diff --git a/libavcodec/alac.c b/libavcodec/alac.c
index 9cd1737..49ccaac 100644
--- a/libavcodec/alac.c
+++ b/libavcodec/alac.c
@@ -45,7 +45,7 @@
  * 32bit  samplerate
  */
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "avcodec.h"
 #include "get_bits.h"
 #include "bytestream.h"
@@ -224,7 +224,7 @@
     }
 
     /* read warm-up samples */
-    for (i = 1; i <= lpc_order; i++)
+    for (i = 1; i <= lpc_order && i < nb_samples; i++)
         buffer_out[i] = sign_extend(buffer_out[i - 1] + error_buffer[i], bps);
 
     /* NOTE: 4 and 8 are very common cases that could be optimized. */
@@ -303,7 +303,7 @@
 
     alac->extra_bits = get_bits(&alac->gb, 2) << 3;
     bps = alac->sample_size - alac->extra_bits + channels - 1;
-    if (bps > 32) {
+    if (bps > 32U) {
         av_log(avctx, AV_LOG_ERROR, "bps is unsupported: %d\n", bps);
         return AVERROR_PATCHWELCOME;
     }
@@ -495,7 +495,9 @@
         }
 
         channels = (element == TYPE_CPE) ? 2 : 1;
-        if (ch + channels > alac->channels) {
+        if (   ch + channels > alac->channels
+            || alac_channel_layout_offsets[alac->channels - 1][ch] + channels > alac->channels
+        ) {
             av_log(avctx, AV_LOG_ERROR, "invalid element channel count\n");
             return AVERROR_INVALIDDATA;
         }
@@ -542,7 +544,11 @@
 static int allocate_buffers(ALACContext *alac)
 {
     int ch;
-    int buf_size = alac->max_samples_per_frame * sizeof(int32_t);
+    int buf_size;
+
+    if (alac->max_samples_per_frame > INT_MAX / sizeof(int32_t))
+        goto buf_alloc_fail;
+    buf_size = alac->max_samples_per_frame * sizeof(int32_t);
 
     for (ch = 0; ch < FFMIN(alac->channels, 2); ch++) {
         FF_ALLOC_OR_GOTO(alac->avctx, alac->predict_error_buffer[ch],
@@ -621,6 +627,7 @@
                                    alac->sample_size);
              return AVERROR_PATCHWELCOME;
     }
+    avctx->bits_per_raw_sample = alac->sample_size;
 
     if (alac->channels < 1) {
         av_log(avctx, AV_LOG_WARNING, "Invalid channel count\n");
@@ -631,7 +638,7 @@
         else
             avctx->channels = alac->channels;
     }
-    if (avctx->channels > MAX_CHANNELS) {
+    if (avctx->channels > MAX_CHANNELS || avctx->channels <= 0 ) {
         av_log(avctx, AV_LOG_ERROR, "Unsupported channel count: %d\n",
                avctx->channels);
         return AVERROR_PATCHWELCOME;
diff --git a/libavcodec/alacenc.c b/libavcodec/alacenc.c
index 79b6ba8..706810f 100644
--- a/libavcodec/alacenc.c
+++ b/libavcodec/alacenc.c
@@ -27,7 +27,6 @@
 #include "mathops.h"
 
 #define DEFAULT_FRAME_SIZE        4096
-#define DEFAULT_SAMPLE_SIZE       16
 #define MAX_CHANNELS              8
 #define ALAC_EXTRADATA_SIZE       36
 #define ALAC_FRAME_HEADER_SIZE    55
@@ -66,6 +65,7 @@
     int max_prediction_order;
     int max_coded_frame_size;
     int write_sample_size;
+    int extra_bits;
     int32_t sample_buf[MAX_CHANNELS][DEFAULT_FRAME_SIZE];
     int32_t predictor_buf[DEFAULT_FRAME_SIZE];
     int interlacing_shift;
@@ -78,16 +78,26 @@
 } AlacEncodeContext;
 
 
-static void init_sample_buffers(AlacEncodeContext *s, int16_t **input_samples)
+static void init_sample_buffers(AlacEncodeContext *s,
+                                uint8_t * const *samples)
 {
     int ch, i;
+    int shift = av_get_bytes_per_sample(s->avctx->sample_fmt) * 8 -
+                s->avctx->bits_per_raw_sample;
 
-    for (ch = 0; ch < s->avctx->channels; ch++) {
-        int32_t       *bptr = s->sample_buf[ch];
-        const int16_t *sptr = input_samples[ch];
-        for (i = 0; i < s->frame_size; i++)
-            bptr[i] = sptr[i];
-    }
+#define COPY_SAMPLES(type) do {                             \
+        for (ch = 0; ch < s->avctx->channels; ch++) {       \
+            int32_t       *bptr = s->sample_buf[ch];        \
+            const type *sptr = (const type *)samples[ch];   \
+            for (i = 0; i < s->frame_size; i++)             \
+                bptr[i] = sptr[i] >> shift;                 \
+        }                                                   \
+    } while (0)
+
+    if (s->avctx->sample_fmt == AV_SAMPLE_FMT_S32P)
+        COPY_SAMPLES(int32_t);
+    else
+        COPY_SAMPLES(int16_t);
 }
 
 static void encode_scalar(AlacEncodeContext *s, int x,
@@ -128,7 +138,7 @@
     put_bits(&s->pbctx, 3,  s->avctx->channels-1);  // No. of channels -1
     put_bits(&s->pbctx, 16, 0);                     // Seems to be zero
     put_bits(&s->pbctx, 1,  encode_fs);             // Sample count is in the header
-    put_bits(&s->pbctx, 2,  0);                     // FIXME: Wasted bytes field
+    put_bits(&s->pbctx, 2,  s->extra_bits >> 3);    // Extra bytes (for 24-bit)
     put_bits(&s->pbctx, 1,  s->verbatim);           // Audio block is verbatim
     if (encode_fs)
         put_bits32(&s->pbctx, s->frame_size);       // No. of samples in the frame
@@ -345,7 +355,8 @@
     }
 }
 
-static int write_frame(AlacEncodeContext *s, AVPacket *avpkt, int16_t **samples)
+static int write_frame(AlacEncodeContext *s, AVPacket *avpkt,
+                       uint8_t * const *samples)
 {
     int i, j;
     int prediction_type = 0;
@@ -356,9 +367,20 @@
     if (s->verbatim) {
         write_frame_header(s);
         /* samples are channel-interleaved in verbatim mode */
-        for (i = 0; i < s->frame_size; i++)
-            for (j = 0; j < s->avctx->channels; j++)
-                put_sbits(pb, 16, samples[j][i]);
+        if (s->avctx->sample_fmt == AV_SAMPLE_FMT_S32P) {
+            int shift = 32 - s->avctx->bits_per_raw_sample;
+            int32_t * const *samples_s32 = (int32_t * const *)samples;
+            for (i = 0; i < s->frame_size; i++)
+                for (j = 0; j < s->avctx->channels; j++)
+                    put_sbits(pb, s->avctx->bits_per_raw_sample,
+                              samples_s32[j][i] >> shift);
+        } else {
+            int16_t * const *samples_s16 = (int16_t * const *)samples;
+            for (i = 0; i < s->frame_size; i++)
+                for (j = 0; j < s->avctx->channels; j++)
+                    put_sbits(pb, s->avctx->bits_per_raw_sample,
+                              samples_s16[j][i]);
+        }
     } else {
         init_sample_buffers(s, samples);
         write_frame_header(s);
@@ -381,6 +403,17 @@
                 put_sbits(pb, 16, s->lpc[i].lpc_coeff[j]);
         }
 
+        // write extra bits if needed
+        if (s->extra_bits) {
+            uint32_t mask = (1 << s->extra_bits) - 1;
+            for (i = 0; i < s->frame_size; i++) {
+                for (j = 0; j < s->avctx->channels; j++) {
+                    put_bits(pb, s->extra_bits, s->sample_buf[j][i] & mask);
+                    s->sample_buf[j][i] >>= s->extra_bits;
+                }
+            }
+        }
+
         // apply lpc and entropy coding to audio samples
 
         for (i = 0; i < s->avctx->channels; i++) {
@@ -433,6 +466,15 @@
         return AVERROR_PATCHWELCOME;
     }
 
+    if (avctx->sample_fmt == AV_SAMPLE_FMT_S32P) {
+        if (avctx->bits_per_raw_sample != 24)
+            av_log(avctx, AV_LOG_WARNING, "encoding as 24 bits-per-sample\n");
+        avctx->bits_per_raw_sample = 24;
+    } else {
+        avctx->bits_per_raw_sample = 16;
+        s->extra_bits              = 0;
+    }
+
     // Set default compression level
     if (avctx->compression_level == FF_COMPRESSION_DEFAULT)
         s->compression_level = 2;
@@ -447,10 +489,7 @@
 
     s->max_coded_frame_size = get_max_frame_size(avctx->frame_size,
                                                  avctx->channels,
-                                                 DEFAULT_SAMPLE_SIZE);
-
-    // FIXME: consider wasted_bytes
-    s->write_sample_size  = DEFAULT_SAMPLE_SIZE + avctx->channels - 1;
+                                                 avctx->bits_per_raw_sample);
 
     avctx->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);
     if (!avctx->extradata) {
@@ -463,11 +502,11 @@
     AV_WB32(alac_extradata,    ALAC_EXTRADATA_SIZE);
     AV_WB32(alac_extradata+4,  MKBETAG('a','l','a','c'));
     AV_WB32(alac_extradata+12, avctx->frame_size);
-    AV_WB8 (alac_extradata+17, DEFAULT_SAMPLE_SIZE);
+    AV_WB8 (alac_extradata+17, avctx->bits_per_raw_sample);
     AV_WB8 (alac_extradata+21, avctx->channels);
     AV_WB32(alac_extradata+24, s->max_coded_frame_size);
     AV_WB32(alac_extradata+28,
-            avctx->sample_rate * avctx->channels * DEFAULT_SAMPLE_SIZE); // average bitrate
+            avctx->sample_rate * avctx->channels * avctx->bits_per_raw_sample); // average bitrate
     AV_WB32(alac_extradata+32, avctx->sample_rate);
 
     // Set relevant extradata fields
@@ -536,13 +575,12 @@
 {
     AlacEncodeContext *s = avctx->priv_data;
     int out_bytes, max_frame_size, ret;
-    int16_t **samples = (int16_t **)frame->extended_data;
 
     s->frame_size = frame->nb_samples;
 
     if (frame->nb_samples < DEFAULT_FRAME_SIZE)
         max_frame_size = get_max_frame_size(s->frame_size, avctx->channels,
-                                            DEFAULT_SAMPLE_SIZE);
+                                            avctx->bits_per_raw_sample);
     else
         max_frame_size = s->max_coded_frame_size;
 
@@ -550,14 +588,24 @@
         return ret;
 
     /* use verbatim mode for compression_level 0 */
-    s->verbatim = !s->compression_level;
+    if (s->compression_level) {
+        s->verbatim   = 0;
+        s->extra_bits = avctx->bits_per_raw_sample - 16;
+    } else {
+        s->verbatim   = 1;
+        s->extra_bits = 0;
+    }
+    s->write_sample_size = avctx->bits_per_raw_sample - s->extra_bits +
+                           avctx->channels - 1;
 
-    out_bytes = write_frame(s, avpkt, samples);
+    out_bytes = write_frame(s, avpkt, frame->extended_data);
 
     if (out_bytes > max_frame_size) {
         /* frame too large. use verbatim mode */
         s->verbatim = 1;
-        out_bytes = write_frame(s, avpkt, samples);
+        s->extra_bits = 0;
+        s->write_sample_size = avctx->bits_per_raw_sample + avctx->channels - 1;
+        out_bytes = write_frame(s, avpkt, frame->extended_data);
     }
 
     avpkt->size = out_bytes;
@@ -574,7 +622,8 @@
     .encode2        = alac_encode_frame,
     .close          = alac_encode_close,
     .capabilities   = CODEC_CAP_SMALL_LAST_FRAME,
-    .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16P,
+    .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S32P,
+                                                     AV_SAMPLE_FMT_S16P,
                                                      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 cba953f..4743bb1 100644
--- a/libavcodec/allcodecs.c
+++ b/libavcodec/allcodecs.c
@@ -90,6 +90,7 @@
     REGISTER_DECODER (BINK, bink);
     REGISTER_ENCDEC  (BMP, bmp);
     REGISTER_DECODER (BMV_VIDEO, bmv_video);
+    REGISTER_DECODER (BRENDER_PIX, brender_pix);
     REGISTER_DECODER (C93, c93);
     REGISTER_DECODER (CAVS, cavs);
     REGISTER_DECODER (CDGRAPHICS, cdgraphics);
@@ -97,6 +98,7 @@
     REGISTER_DECODER (CINEPAK, cinepak);
     REGISTER_ENCDEC  (CLJR, cljr);
     REGISTER_DECODER (CLLC, cllc);
+    REGISTER_ENCDEC  (COMFORTNOISE, comfortnoise);
     REGISTER_DECODER (CPIA, cpia);
     REGISTER_DECODER (CSCD, cscd);
     REGISTER_DECODER (CYUV, cyuv);
@@ -221,6 +223,7 @@
     REGISTER_ENCDEC  (SVQ1, svq1);
     REGISTER_DECODER (SVQ3, svq3);
     REGISTER_ENCDEC  (TARGA, targa);
+    REGISTER_DECODER (TARGA_Y216, targa_y216);
     REGISTER_DECODER (THEORA, theora);
     REGISTER_DECODER (THP, thp);
     REGISTER_DECODER (TIERTEXSEQVIDEO, tiertexseqvideo);
@@ -264,6 +267,7 @@
     REGISTER_DECODER (XAN_WC3, xan_wc3);
     REGISTER_DECODER (XAN_WC4, xan_wc4);
     REGISTER_ENCDEC  (XBM, xbm);
+    REGISTER_ENCDEC  (XFACE, xface);
     REGISTER_DECODER (XL, xl);
     REGISTER_ENCDEC  (XWD, xwd);
     REGISTER_ENCDEC  (Y41P, y41p);
@@ -327,6 +331,7 @@
     REGISTER_DECODER (SMACKAUD, smackaud);
     REGISTER_ENCDEC  (SONIC, sonic);
     REGISTER_ENCODER (SONIC_LS, sonic_ls);
+    REGISTER_DECODER (TAK, tak);
     REGISTER_DECODER (TRUEHD, truehd);
     REGISTER_DECODER (TRUESPEECH, truespeech);
     REGISTER_DECODER (TTA, tta);
@@ -352,15 +357,18 @@
     REGISTER_DECODER (PCM_LXF, pcm_lxf);
     REGISTER_ENCDEC  (PCM_MULAW, pcm_mulaw);
     REGISTER_ENCDEC  (PCM_S8, pcm_s8);
-    REGISTER_DECODER (PCM_S8_PLANAR, pcm_s8_planar);
+    REGISTER_ENCDEC  (PCM_S8_PLANAR, pcm_s8_planar);
     REGISTER_ENCDEC  (PCM_S16BE, pcm_s16be);
+    REGISTER_ENCDEC  (PCM_S16BE_PLANAR, pcm_s16be_planar);
     REGISTER_ENCDEC  (PCM_S16LE, pcm_s16le);
-    REGISTER_DECODER (PCM_S16LE_PLANAR, pcm_s16le_planar);
+    REGISTER_ENCDEC  (PCM_S16LE_PLANAR, pcm_s16le_planar);
     REGISTER_ENCDEC  (PCM_S24BE, pcm_s24be);
     REGISTER_ENCDEC  (PCM_S24DAUD, pcm_s24daud);
     REGISTER_ENCDEC  (PCM_S24LE, pcm_s24le);
+    REGISTER_ENCDEC  (PCM_S24LE_PLANAR, pcm_s24le_planar);
     REGISTER_ENCDEC  (PCM_S32BE, pcm_s32be);
     REGISTER_ENCDEC  (PCM_S32LE, pcm_s32le);
+    REGISTER_ENCDEC  (PCM_S32LE_PLANAR, pcm_s32le_planar);
     REGISTER_ENCDEC  (PCM_U8, pcm_u8);
     REGISTER_ENCDEC  (PCM_U16BE, pcm_u16be);
     REGISTER_ENCDEC  (PCM_U16LE, pcm_u16le);
@@ -379,6 +387,7 @@
     /* ADPCM codecs */
     REGISTER_DECODER (ADPCM_4XM, adpcm_4xm);
     REGISTER_ENCDEC  (ADPCM_ADX, adpcm_adx);
+    REGISTER_DECODER (ADPCM_AFC, adpcm_afc);
     REGISTER_DECODER (ADPCM_CT, adpcm_ct);
     REGISTER_DECODER (ADPCM_EA, adpcm_ea);
     REGISTER_DECODER (ADPCM_EA_MAXIS_XA, adpcm_ea_maxis_xa);
@@ -395,6 +404,7 @@
     REGISTER_DECODER (ADPCM_IMA_EA_EACS, adpcm_ima_ea_eacs);
     REGISTER_DECODER (ADPCM_IMA_EA_SEAD, adpcm_ima_ea_sead);
     REGISTER_DECODER (ADPCM_IMA_ISS, adpcm_ima_iss);
+    REGISTER_DECODER (ADPCM_IMA_OKI, adpcm_ima_oki);
     REGISTER_ENCDEC  (ADPCM_IMA_QT, adpcm_ima_qt);
     REGISTER_DECODER (ADPCM_IMA_SMJPEG, adpcm_ima_smjpeg);
     REGISTER_ENCDEC  (ADPCM_IMA_WAV, adpcm_ima_wav);
@@ -422,6 +432,7 @@
     REGISTER_ENCDEC  (SRT, srt);
     REGISTER_ENCDEC  (SUBRIP, subrip);
     REGISTER_DECODER (SUBVIEWER, subviewer);
+    REGISTER_DECODER (TEXT, text);
     REGISTER_DECODER (WEBVTT, webvtt);
     REGISTER_ENCDEC  (XSUB, xsub);
 
@@ -436,7 +447,7 @@
     REGISTER_ENCDEC  (LIBOPENCORE_AMRNB, libopencore_amrnb);
     REGISTER_DECODER (LIBOPENCORE_AMRWB, libopencore_amrwb);
     REGISTER_ENCDEC  (LIBOPENJPEG, libopenjpeg);
-    REGISTER_DECODER (LIBOPUS, libopus);
+    REGISTER_ENCDEC  (LIBOPUS, libopus);
     REGISTER_ENCDEC  (LIBSCHROEDINGER, libschroedinger);
     REGISTER_ENCDEC  (LIBSPEEX, libspeex);
     REGISTER_DECODER (LIBSTAGEFRIGHT_H264, libstagefright_h264);
@@ -485,6 +496,7 @@
     REGISTER_PARSER  (PNM, pnm);
     REGISTER_PARSER  (RV30, rv30);
     REGISTER_PARSER  (RV40, rv40);
+    REGISTER_PARSER  (TAK, tak);
     REGISTER_PARSER  (VC1, vc1);
     REGISTER_PARSER  (VORBIS, vorbis);
     REGISTER_PARSER  (VP3, vp3);
diff --git a/libavcodec/alpha/Makefile b/libavcodec/alpha/Makefile
index e55fe49..e28200d 100644
--- a/libavcodec/alpha/Makefile
+++ b/libavcodec/alpha/Makefile
@@ -2,5 +2,6 @@
         alpha/dsputil_alpha_asm.o                                       \
         alpha/motion_est_alpha.o                                        \
         alpha/motion_est_mvi_asm.o                                      \
-        alpha/mpegvideo_alpha.o                                         \
         alpha/simple_idct_alpha.o                                       \
+
+OBJS-$(CONFIG_MPEGVIDEO)                += alpha/mpegvideo_alpha.o
diff --git a/libavcodec/alsdec.c b/libavcodec/alsdec.c
index 46dd0b4..69e66d6 100644
--- a/libavcodec/alsdec.c
+++ b/libavcodec/alsdec.c
@@ -427,9 +427,9 @@
         }                                               \
     }
 
-    MISSING_ERR(sconf->floating,             "Floating point decoding",     -1);
-    MISSING_ERR(sconf->rlslms,               "Adaptive RLS-LMS prediction", -1);
-    MISSING_ERR(sconf->chan_sort,            "Channel sorting",              0);
+    MISSING_ERR(sconf->floating,  "Floating point decoding",     AVERROR_PATCHWELCOME);
+    MISSING_ERR(sconf->rlslms,    "Adaptive RLS-LMS prediction", AVERROR_PATCHWELCOME);
+    MISSING_ERR(sconf->chan_sort, "Channel sorting",             0);
 
     return error;
 }
@@ -1175,14 +1175,14 @@
 
         if (current->master_channel != c) {
             current->time_diff_flag = get_bits1(gb);
-            current->weighting[0]   = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 32)];
-            current->weighting[1]   = mcc_weightings[av_clip(decode_rice(gb, 2) + 14, 0, 32)];
-            current->weighting[2]   = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 32)];
+            current->weighting[0]   = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 31)];
+            current->weighting[1]   = mcc_weightings[av_clip(decode_rice(gb, 2) + 14, 0, 31)];
+            current->weighting[2]   = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 31)];
 
             if (current->time_diff_flag) {
-                current->weighting[3] = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 32)];
-                current->weighting[4] = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 32)];
-                current->weighting[5] = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 32)];
+                current->weighting[3] = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 31)];
+                current->weighting[4] = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 31)];
+                current->weighting[5] = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 31)];
 
                 current->time_diff_sign  = get_bits1(gb);
                 current->time_diff_index = get_bits(gb, ctx->ltp_lag_length - 3) + 3;
diff --git a/libavcodec/amrnbdata.h b/libavcodec/amrnbdata.h
index 6e555bf..435fd99 100644
--- a/libavcodec/amrnbdata.h
+++ b/libavcodec/amrnbdata.h
@@ -55,7 +55,7 @@
 /**
  * AMRNB unpacked data subframe
  */
-typedef struct {
+typedef struct AMRNBSubframe {
     uint16_t p_lag;      ///< index to decode the pitch lag
     uint16_t p_gain;     ///< index to decode the pitch gain
     uint16_t fixed_gain; ///< index to decode the fixed gain factor, for MODE_12k2 and MODE_7k95
@@ -65,7 +65,7 @@
 /**
  * AMRNB unpacked data frame
  */
-typedef struct {
+typedef struct AMRNBFrame {
     uint16_t lsf[5];           ///< lsf parameters: 5 parameters for MODE_12k2, only 3 for other modes
     AMRNBSubframe subframe[4]; ///< unpacked data for each subframe
 } AMRNBFrame;
diff --git a/libavcodec/amrnbdec.c b/libavcodec/amrnbdec.c
index 32b754f..0057959 100644
--- a/libavcodec/amrnbdec.c
+++ b/libavcodec/amrnbdec.c
@@ -43,6 +43,7 @@
 #include <string.h>
 #include <math.h>
 
+#include "libavutil/channel_layout.h"
 #include "avcodec.h"
 #include "dsputil.h"
 #include "libavutil/common.h"
@@ -161,7 +162,16 @@
     AMRContext *p = avctx->priv_data;
     int i;
 
-    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
+    if (avctx->channels > 1) {
+        av_log_missing_feature(avctx, "multi-channel AMR", 0);
+        return AVERROR_PATCHWELCOME;
+    }
+
+    avctx->channels       = 1;
+    avctx->channel_layout = AV_CH_LAYOUT_MONO;
+    if (!avctx->sample_rate)
+        avctx->sample_rate = 8000;
+    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];
@@ -969,7 +979,7 @@
     if (p->cur_frame_mode == MODE_DTX) {
         av_log_missing_feature(avctx, "dtx mode", 0);
         av_log(avctx, AV_LOG_INFO, "Note: libopencore_amrnb supports dtx\n");
-        return -1;
+        return AVERROR_PATCHWELCOME;
     }
 
     if (p->cur_frame_mode == MODE_12k2) {
diff --git a/libavcodec/amrwbdata.h b/libavcodec/amrwbdata.h
index 83390fc..8390582 100644
--- a/libavcodec/amrwbdata.h
+++ b/libavcodec/amrwbdata.h
@@ -66,7 +66,7 @@
 
 /* All decoded parameters in these structs must be 2 bytes long
  * because of the direct indexing at the frame parsing */
-typedef struct {
+typedef struct AMRWBSubFrame {
     uint16_t adap;                         ///< adaptive codebook index
     uint16_t ltp;                          ///< ltp-filtering flag
     uint16_t vq_gain;                      ///< VQ adaptive and innovative gains
@@ -75,7 +75,7 @@
     uint16_t pul_il[4];                    ///< LSBs part of codebook index
 } AMRWBSubFrame;
 
-typedef struct {
+typedef struct AMRWBFrame {
     uint16_t vad;                          ///< voice activity detection flag
     uint16_t isp_id[7];                    ///< index of ISP subvectors
     AMRWBSubFrame subframe[4];             ///< data for subframes
diff --git a/libavcodec/amrwbdec.c b/libavcodec/amrwbdec.c
index 738dd98..468ffa0 100644
--- a/libavcodec/amrwbdec.c
+++ b/libavcodec/amrwbdec.c
@@ -24,6 +24,7 @@
  * AMR wideband decoder
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
 #include "libavutil/lfg.h"
 
@@ -97,7 +98,16 @@
     AMRWBContext *ctx = avctx->priv_data;
     int i;
 
-    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
+    if (avctx->channels > 1) {
+        av_log_missing_feature(avctx, "multi-channel AMR", 0);
+        return AVERROR_PATCHWELCOME;
+    }
+
+    avctx->channels       = 1;
+    avctx->channel_layout = AV_CH_LAYOUT_MONO;
+    if (!avctx->sample_rate)
+        avctx->sample_rate = 16000;
+    avctx->sample_fmt     = AV_SAMPLE_FMT_FLT;
 
     av_lfg_init(&ctx->prng, 1);
 
@@ -918,10 +928,9 @@
 static void extrapolate_isf(float isf[LP_ORDER_16k])
 {
     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;
+    int i, j, i_max_corr;
 
     isf[LP_ORDER_16k - 1] = isf[LP_ORDER - 1];
 
@@ -952,20 +961,20 @@
     scale = 0.5 * (FFMIN(est, 7600) - isf[LP_ORDER - 2]) /
             (isf[LP_ORDER_16k - 2] - isf[LP_ORDER - 2]);
 
-    for (i = LP_ORDER - 1; i < LP_ORDER_16k - 1; i++)
-        diff_hi[i] = scale * (isf[i] - isf[i - 1]);
+    for (i = LP_ORDER - 1, j = 0; i < LP_ORDER_16k - 1; i++, j++)
+        diff_isf[j] = scale * (isf[i] - isf[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];
+    for (i = 1; i < LP_ORDER_16k - LP_ORDER; i++)
+        if (diff_isf[i] + diff_isf[i - 1] < 5.0) {
+            if (diff_isf[i] > diff_isf[i - 1]) {
+                diff_isf[i - 1] = 5.0 - diff_isf[i];
             } else
-                diff_hi[i] = 5.0 - diff_hi[i - 1];
+                diff_isf[i] = 5.0 - diff_isf[i - 1];
         }
 
-    for (i = LP_ORDER - 1; i < LP_ORDER_16k - 1; i++)
-        isf[i] = isf[i - 1] + diff_hi[i] * (1.0f / (1 << 15));
+    for (i = LP_ORDER - 1, j = 0; i < LP_ORDER_16k - 1; i++, j++)
+        isf[i] = isf[i - 1] + diff_isf[j] * (1.0f / (1 << 15));
 
     /* Scale the ISF vector for 16000 Hz */
     for (i = 0; i < LP_ORDER_16k - 1; i++)
@@ -1130,7 +1139,7 @@
 
     if (ctx->fr_cur_mode == MODE_SID) { /* Comfort noise frame */
         av_log_missing_feature(avctx, "SID mode", 1);
-        return -1;
+        return AVERROR_PATCHWELCOME;
     }
 
     ff_amr_bit_reorder((uint16_t *) &ctx->frame, sizeof(AMRWBFrame),
diff --git a/libavcodec/anm.c b/libavcodec/anm.c
index a077367..7cac095 100644
--- a/libavcodec/anm.c
+++ b/libavcodec/anm.c
@@ -39,13 +39,13 @@
     AnmContext *s = avctx->priv_data;
     int i;
 
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     avcodec_get_frame_defaults(&s->frame);
     s->frame.reference = 3;
     bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
     if (bytestream2_get_bytes_left(&s->gb) < 16 * 8 + 4 * 256)
-        return -1;
+        return AVERROR_INVALIDDATA;
 
     bytestream2_skipu(&s->gb, 16 * 8);
     for (i = 0; i < 256; i++)
@@ -112,11 +112,11 @@
     AnmContext *s = avctx->priv_data;
     const int buf_size = avpkt->size;
     uint8_t *dst, *dst_end;
-    int count;
+    int count, ret;
 
-    if(avctx->reget_buffer(avctx, &s->frame) < 0){
+    if ((ret = avctx->reget_buffer(avctx, &s->frame)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
+        return ret;
     }
     dst     = s->frame.data[0];
     dst_end = s->frame.data[0] + s->frame.linesize[0]*avctx->height;
@@ -125,11 +125,11 @@
 
     if (bytestream2_get_byte(&s->gb) != 0x42) {
         av_log_ask_for_sample(avctx, "unknown record type\n");
-        return buf_size;
+        return AVERROR_INVALIDDATA;
     }
     if (bytestream2_get_byte(&s->gb)) {
         av_log_ask_for_sample(avctx, "padding bytes not supported\n");
-        return buf_size;
+        return AVERROR_PATCHWELCOME;
     }
     bytestream2_skip(&s->gb, 2);
 
diff --git a/libavcodec/ansi.c b/libavcodec/ansi.c
index 3572500..d84b395 100644
--- a/libavcodec/ansi.c
+++ b/libavcodec/ansi.c
@@ -26,6 +26,7 @@
 
 #include "libavutil/common.h"
 #include "libavutil/lfg.h"
+#include "libavutil/xga_font_data.h"
 #include "avcodec.h"
 #include "cga_data.h"
 
@@ -75,10 +76,10 @@
 static av_cold int decode_init(AVCodecContext *avctx)
 {
     AnsiContext *s = avctx->priv_data;
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     /* defaults */
-    s->font        = ff_vga16_font;
+    s->font        = avpriv_vga16_font;
     s->font_height = 16;
     s->fg          = DEFAULT_FG_COLOR;
     s->bg          = DEFAULT_BG_COLOR;
@@ -203,19 +204,19 @@
         height = avctx->height;
         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 = avpriv_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 = avpriv_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 = avpriv_cga_font;
             s->font_height = 8;
             width  = 80<<3;
             height = 25<<3;
@@ -223,13 +224,13 @@
         case 7: //set line wrapping
             break;
         case 15: case 16: //640x350 (43 rows)
-            s->font = ff_cga_font;
+            s->font = avpriv_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 = avpriv_cga_font;
             s->font_height = 8;
             width  = 80<<3;
             height = 60<<4;
@@ -298,7 +299,7 @@
                 s->attributes |= 1 << (m - 1);
             } else if (m >= 30 && m <= 37) {
                 s->fg = ansi_to_cga[m - 30];
-            } else if (m == 38 && i + 2 < s->nb_args && s->args[i + 1] == 5 && s->args[i + 2] < 256) {
+            } else if (m == 38 && i + 2 < FFMIN(s->nb_args, MAX_NB_ARGS) && s->args[i + 1] == 5 && s->args[i + 2] < 256) {
                 int index = s->args[i + 2];
                 s->fg = index < 16 ? ansi_to_cga[index] : index;
                 i += 2;
@@ -306,7 +307,7 @@
                 s->fg = ansi_to_cga[DEFAULT_FG_COLOR];
             } else if (m >= 40 && m <= 47) {
                 s->bg = ansi_to_cga[m - 40];
-            } else if (m == 48 && i + 2 < s->nb_args && s->args[i + 1] == 5 && s->args[i + 2] < 256) {
+            } else if (m == 48 && i + 2 < FFMIN(s->nb_args, MAX_NB_ARGS) && s->args[i + 1] == 5 && s->args[i + 2] < 256) {
                 int index = s->args[i + 2];
                 s->bg = index < 16 ? ansi_to_cga[index] : index;
                 i += 2;
diff --git a/libavcodec/apedec.c b/libavcodec/apedec.c
index 2108090..a85d355 100644
--- a/libavcodec/apedec.c
+++ b/libavcodec/apedec.c
@@ -20,12 +20,12 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/avassert.h"
+#include "libavutil/channel_layout.h"
+#include "libavutil/opt.h"
 #include "avcodec.h"
 #include "dsputil.h"
 #include "bytestream.h"
-#include "libavutil/audioconvert.h"
-#include "libavutil/avassert.h"
-#include "libavutil/opt.h"
 
 /**
  * @file
@@ -196,13 +196,13 @@
     s->bps = avctx->bits_per_coded_sample;
     switch (s->bps) {
     case 8:
-        avctx->sample_fmt = AV_SAMPLE_FMT_U8;
+        avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
         break;
     case 16:
-        avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+        avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
         break;
     case 24:
-        avctx->sample_fmt = AV_SAMPLE_FMT_S32;
+        avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
         break;
     default:
         av_log_ask_for_sample(avctx, "Unsupported bits per coded sample %d\n",
@@ -830,9 +830,8 @@
     uint8_t *sample8;
     int16_t *sample16;
     int32_t *sample24;
-    int i, ret;
+    int i, ch, ret;
     int blockstodecode;
-    int bytes_used = 0;
 
     /* this should never be negative, but bad things will happen if it is, so
        check it just to make sure. */
@@ -887,8 +886,6 @@
             av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
             return AVERROR_INVALIDDATA;
         }
-
-        bytes_used = avpkt->size;
     }
 
     if (!s->data) {
@@ -930,27 +927,24 @@
 
     switch (s->bps) {
     case 8:
-        sample8 = (uint8_t *)s->frame.data[0];
-        for (i = 0; i < blockstodecode; i++) {
-            *sample8++ = (s->decoded[0][i] + 0x80) & 0xff;
-            if (s->channels == 2)
-                *sample8++ = (s->decoded[1][i] + 0x80) & 0xff;
+        for (ch = 0; ch < s->channels; ch++) {
+            sample8 = (uint8_t *)s->frame.data[ch];
+            for (i = 0; i < blockstodecode; i++)
+                *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
         }
         break;
     case 16:
-        sample16 = (int16_t *)s->frame.data[0];
-        for (i = 0; i < blockstodecode; i++) {
-            *sample16++ = s->decoded[0][i];
-            if (s->channels == 2)
-                *sample16++ = s->decoded[1][i];
+        for (ch = 0; ch < s->channels; ch++) {
+            sample16 = (int16_t *)s->frame.data[ch];
+            for (i = 0; i < blockstodecode; i++)
+                *sample16++ = s->decoded[ch][i];
         }
         break;
     case 24:
-        sample24 = (int32_t *)s->frame.data[0];
-        for (i = 0; i < blockstodecode; i++) {
-            *sample24++ = s->decoded[0][i] << 8;
-            if (s->channels == 2)
-                *sample24++ = s->decoded[1][i] << 8;
+        for (ch = 0; ch < s->channels; ch++) {
+            sample24 = (int32_t *)s->frame.data[ch];
+            for (i = 0; i < blockstodecode; i++)
+                *sample24++ = s->decoded[ch][i] << 8;
         }
         break;
     }
@@ -960,7 +954,7 @@
     *got_frame_ptr   = 1;
     *(AVFrame *)data = s->frame;
 
-    return bytes_used;
+    return !s->samples ? avpkt->size : 0;
 }
 
 static void ape_flush(AVCodecContext *avctx)
@@ -995,5 +989,9 @@
     .capabilities   = CODEC_CAP_SUBFRAMES | CODEC_CAP_DELAY | CODEC_CAP_DR1,
     .flush          = ape_flush,
     .long_name      = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
+                                                      AV_SAMPLE_FMT_S16P,
+                                                      AV_SAMPLE_FMT_S32P,
+                                                      AV_SAMPLE_FMT_NONE },
     .priv_class     = &ape_decoder_class,
 };
diff --git a/libavcodec/arm/Makefile b/libavcodec/arm/Makefile
index 745a5bd..acfd626 100644
--- a/libavcodec/arm/Makefile
+++ b/libavcodec/arm/Makefile
@@ -14,6 +14,7 @@
 OBJS-$(CONFIG_MPEGAUDIODSP)            += arm/mpegaudiodsp_init_arm.o
 ARMV6-OBJS-$(CONFIG_MPEGAUDIODSP)      += arm/mpegaudiodsp_fixed_armv6.o
 
+OBJS-$(CONFIG_MPEGVIDEO)               += arm/mpegvideo_arm.o
 OBJS-$(CONFIG_VP3DSP)                  += arm/vp3dsp_init_arm.o
 OBJS-$(CONFIG_VP5_DECODER)             += arm/vp56dsp_init_arm.o
 OBJS-$(CONFIG_VP6_DECODER)             += arm/vp56dsp_init_arm.o
@@ -25,18 +26,22 @@
 OBJS-$(CONFIG_H264DSP)                 += arm/h264dsp_init_arm.o
 OBJS-$(CONFIG_H264PRED)                += arm/h264pred_init_arm.o
 
+OBJS-$(CONFIG_RV30_DECODER)            += arm/rv34dsp_init_arm.o
+OBJS-$(CONFIG_RV40_DECODER)            += arm/rv34dsp_init_arm.o        \
+                                          arm/rv40dsp_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         \
 
-ARMV5TE-OBJS                           += arm/dsputil_init_armv5te.o    \
-                                          arm/mpegvideo_armv5te.o       \
+ARMV5TE-OBJS-$(CONFIG_MPEGVIDEO)       += arm/mpegvideo_armv5te.o       \
                                           arm/mpegvideo_armv5te_s.o     \
+
+ARMV5TE-OBJS                           += arm/dsputil_init_armv5te.o    \
                                           arm/simple_idct_armv5te.o     \
 
 ARMV6-OBJS                             += arm/dsputil_init_armv6.o      \
@@ -70,12 +75,9 @@
 NEON-OBJS-$(CONFIG_DCA_DECODER)        += arm/dcadsp_neon.o             \
                                           arm/synth_filter_neon.o       \
 
-NEON-OBJS-$(CONFIG_RV30_DECODER)       += arm/rv34dsp_init_neon.o       \
-                                          arm/rv34dsp_neon.o            \
-
-NEON-OBJS-$(CONFIG_RV40_DECODER)       += arm/rv34dsp_init_neon.o       \
-                                          arm/rv34dsp_neon.o            \
-                                          arm/rv40dsp_init_neon.o       \
+NEON-OBJS-$(CONFIG_MPEGVIDEO)          += arm/mpegvideo_neon.o
+NEON-OBJS-$(CONFIG_RV30_DECODER)       += arm/rv34dsp_neon.o
+NEON-OBJS-$(CONFIG_RV40_DECODER)       += arm/rv34dsp_neon.o            \
                                           arm/rv40dsp_neon.o            \
                                           arm/h264cmc_neon.o            \
 
@@ -92,5 +94,4 @@
                                           arm/dsputil_neon.o            \
                                           arm/fmtconvert_neon.o         \
                                           arm/int_neon.o                \
-                                          arm/mpegvideo_neon.o          \
                                           arm/simple_idct_neon.o        \
diff --git a/libavcodec/arm/dsputil_arm.S b/libavcodec/arm/dsputil_arm.S
index 92a3757..d665ab3 100644
--- a/libavcodec/arm/dsputil_arm.S
+++ b/libavcodec/arm/dsputil_arm.S
@@ -22,8 +22,6 @@
 #include "config.h"
 #include "libavutil/arm/asm.S"
 
-        preserve8
-
 #if HAVE_ARMV5TE
 function ff_prefetch_arm, export=1
         subs            r2,  r2,  #1
diff --git a/libavcodec/arm/dsputil_armv6.S b/libavcodec/arm/dsputil_armv6.S
index fac431d..0c54b52 100644
--- a/libavcodec/arm/dsputil_armv6.S
+++ b/libavcodec/arm/dsputil_armv6.S
@@ -20,8 +20,6 @@
 
 #include "libavutil/arm/asm.S"
 
-        preserve8
-
 .macro  call_2x_pixels  type, subp
 function ff_\type\()_pixels16\subp\()_armv6, export=1
         push            {r0-r3, lr}
diff --git a/libavcodec/arm/dsputil_init_neon.c b/libavcodec/arm/dsputil_init_neon.c
index 5533a28..ff1178d 100644
--- a/libavcodec/arm/dsputil_init_neon.c
+++ b/libavcodec/arm/dsputil_init_neon.c
@@ -144,8 +144,6 @@
 
 void ff_vector_fmul_window_neon(float *dst, const float *src0,
                                 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_butterflies_float_neon(float *v1, float *v2, int len);
 float ff_scalarproduct_float_neon(const float *v1, const float *v2, int len);
 void ff_vector_fmul_reverse_neon(float *dst, const float *src0,
@@ -305,7 +303,6 @@
     }
 
     c->vector_fmul_window         = ff_vector_fmul_window_neon;
-    c->vector_fmul_scalar         = ff_vector_fmul_scalar_neon;
     c->butterflies_float          = ff_butterflies_float_neon;
     c->scalarproduct_float        = ff_scalarproduct_float_neon;
     c->vector_fmul_reverse        = ff_vector_fmul_reverse_neon;
diff --git a/libavcodec/arm/dsputil_neon.S b/libavcodec/arm/dsputil_neon.S
index 66b3f17..610a2bb 100644
--- a/libavcodec/arm/dsputil_neon.S
+++ b/libavcodec/arm/dsputil_neon.S
@@ -22,8 +22,6 @@
 #include "config.h"
 #include "libavutil/arm/asm.S"
 
-        preserve8
-
 function ff_clear_block_neon, export=1
         vmov.i16        q0,  #0
         .rept           8
@@ -644,44 +642,6 @@
 endfunc
 #endif
 
-function ff_vector_fmul_scalar_neon, export=1
-VFP     len .req r2
-NOVFP   len .req r3
-VFP     vdup.32         q8,  d0[0]
-NOVFP   vdup.32         q8,  r2
-        bics            r12, len, #15
-        beq             3f
-        vld1.32         {q0},[r1,:128]!
-        vld1.32         {q1},[r1,:128]!
-1:      vmul.f32        q0,  q0,  q8
-        vld1.32         {q2},[r1,:128]!
-        vmul.f32        q1,  q1,  q8
-        vld1.32         {q3},[r1,:128]!
-        vmul.f32        q2,  q2,  q8
-        vst1.32         {q0},[r0,:128]!
-        vmul.f32        q3,  q3,  q8
-        vst1.32         {q1},[r0,:128]!
-        subs            r12, r12, #16
-        beq             2f
-        vld1.32         {q0},[r1,:128]!
-        vst1.32         {q2},[r0,:128]!
-        vld1.32         {q1},[r1,:128]!
-        vst1.32         {q3},[r0,:128]!
-        b               1b
-2:      vst1.32         {q2},[r0,:128]!
-        vst1.32         {q3},[r0,:128]!
-        ands            len, len, #15
-        it              eq
-        bxeq            lr
-3:      vld1.32         {q0},[r1,:128]!
-        vmul.f32        q0,  q0,  q8
-        vst1.32         {q0},[r0,:128]!
-        subs            len, len, #4
-        bgt             3b
-        bx              lr
-        .unreq          len
-endfunc
-
 function ff_butterflies_float_neon, export=1
 1:      vld1.32         {q0},[r0,:128]
         vld1.32         {q1},[r1,:128]
diff --git a/libavcodec/arm/fmtconvert_neon.S b/libavcodec/arm/fmtconvert_neon.S
index 83fc124..55d070e 100644
--- a/libavcodec/arm/fmtconvert_neon.S
+++ b/libavcodec/arm/fmtconvert_neon.S
@@ -22,8 +22,6 @@
 #include "config.h"
 #include "libavutil/arm/asm.S"
 
-        preserve8
-
 function ff_float_to_int16_neon, export=1
         subs            r2,  r2,  #8
         vld1.64         {d0-d1},  [r1,:128]!
diff --git a/libavcodec/arm/h264cmc_neon.S b/libavcodec/arm/h264cmc_neon.S
index c7e5460..3427e36 100644
--- a/libavcodec/arm/h264cmc_neon.S
+++ b/libavcodec/arm/h264cmc_neon.S
@@ -51,24 +51,20 @@
 
         beq             2f
 
-        add             r5,  r1,  r2
-
         vdup.8          d0,  r4
-        lsl             r4,  r2,  #1
         vdup.8          d1,  r12
-        vld1.8          {d4, d5}, [r1], r4
+        vld1.8          {d4, d5}, [r1], r2
         vdup.8          d2,  r6
-        vld1.8          {d6, d7}, [r5], r4
         vdup.8          d3,  r7
-
         vext.8          d5,  d4,  d5,  #1
-        vext.8          d7,  d6,  d7,  #1
 
-1:      pld             [r5]
+1:      vld1.8          {d6, d7}, [r1], r2
         vmull.u8        q8,  d4,  d0
         vmlal.u8        q8,  d5,  d1
-        vld1.8          {d4, d5}, [r1], r4
+        vext.8          d7,  d6,  d7,  #1
+        vld1.8          {d4, d5}, [r1], r2
         vmlal.u8        q8,  d6,  d2
+        pld             [r1]
         vext.8          d5,  d4,  d5,  #1
         vmlal.u8        q8,  d7,  d3
         vmull.u8        q9,  d6,  d0
@@ -76,8 +72,7 @@
         vmlal.u8        q9,  d7,  d1
         vmlal.u8        q9,  d4,  d2
         vmlal.u8        q9,  d5,  d3
-        vld1.8          {d6, d7}, [r5], r4
-        pld             [r1]
+        pld             [r1, r2]
   .ifc \codec,h264
         vrshrn.u16      d16, q8,  #6
         vrshrn.u16      d17, q9,  #6
@@ -92,7 +87,6 @@
         vld1.8          {d21}, [lr,:64], r2
         vrhadd.u8       q8,  q8,  q10
   .endif
-        vext.8          d7,  d6,  d7,  #1
         vst1.8          {d16}, [r0,:64], r2
         vst1.8          {d17}, [r0,:64], r2
         bgt             1b
@@ -106,18 +100,15 @@
 
         beq             4f
 
-        add             r5,  r1,  r2
-        lsl             r4,  r2,  #1
-        vld1.8          {d4}, [r1], r4
-        vld1.8          {d6}, [r5], r4
+        vld1.8          {d4}, [r1], r2
 
-3:      pld             [r5]
+3:      vld1.8          {d6}, [r1], r2
         vmull.u8        q8,  d4,  d0
         vmlal.u8        q8,  d6,  d1
-        vld1.8          {d4}, [r1], r4
+        vld1.8          {d4}, [r1], r2
         vmull.u8        q9,  d6,  d0
         vmlal.u8        q9,  d4,  d1
-        vld1.8          {d6}, [r5], r4
+        pld             [r1]
   .ifc \codec,h264
         vrshrn.u16      d16, q8,  #6
         vrshrn.u16      d17, q9,  #6
@@ -127,13 +118,13 @@
         vshrn.u16       d16, q8,  #6
         vshrn.u16       d17, q9,  #6
   .endif
+        pld             [r1, r2]
   .ifc \type,avg
         vld1.8          {d20}, [lr,:64], r2
         vld1.8          {d21}, [lr,:64], r2
         vrhadd.u8       q8,  q8,  q10
   .endif
         subs            r3,  r3,  #2
-        pld             [r1]
         vst1.8          {d16}, [r0,:64], r2
         vst1.8          {d17}, [r0,:64], r2
         bgt             3b
@@ -144,16 +135,13 @@
         vld1.8          {d6, d7}, [r1], r2
         vext.8          d5,  d4,  d5,  #1
         vext.8          d7,  d6,  d7,  #1
-
-5:      pld             [r1]
+        pld             [r1]
         subs            r3,  r3,  #2
         vmull.u8        q8,  d4,  d0
         vmlal.u8        q8,  d5,  d1
-        vld1.8          {d4, d5}, [r1], r2
         vmull.u8        q9,  d6,  d0
         vmlal.u8        q9,  d7,  d1
-        pld             [r1]
-        vext.8          d5,  d4,  d5,  #1
+        pld             [r1, r2]
   .ifc \codec,h264
         vrshrn.u16      d16, q8,  #6
         vrshrn.u16      d17, q9,  #6
@@ -168,11 +156,9 @@
         vld1.8          {d21}, [lr,:64], r2
         vrhadd.u8       q8,  q8,  q10
   .endif
-        vld1.8          {d6, d7}, [r1], r2
-        vext.8          d7,  d6,  d7,  #1
         vst1.8          {d16}, [r0,:64], r2
         vst1.8          {d17}, [r0,:64], r2
-        bgt             5b
+        bgt             4b
 
         pop             {r4-r7, pc}
 endfunc
@@ -209,33 +195,29 @@
 
         beq             2f
 
-        add             r5,  r1,  r2
-
         vdup.8          d0,  r4
-        lsl             r4,  r2,  #1
         vdup.8          d1,  r12
-        vld1.8          {d4},     [r1], r4
+        vld1.8          {d4},     [r1], r2
         vdup.8          d2,  r6
-        vld1.8          {d6},     [r5], r4
         vdup.8          d3,  r7
 
         vext.8          d5,  d4,  d5,  #1
-        vext.8          d7,  d6,  d7,  #1
         vtrn.32         d4,  d5
-        vtrn.32         d6,  d7
 
         vtrn.32         d0,  d1
         vtrn.32         d2,  d3
 
-1:      pld             [r5]
+1:      vld1.8          {d6},     [r1], r2
+        vext.8          d7,  d6,  d7,  #1
+        vtrn.32         d6,  d7
         vmull.u8        q8,  d4,  d0
         vmlal.u8        q8,  d6,  d2
-        vld1.8          {d4},     [r1], r4
+        vld1.8          {d4},     [r1], r2
         vext.8          d5,  d4,  d5,  #1
         vtrn.32         d4,  d5
+        pld             [r1]
         vmull.u8        q9,  d6,  d0
         vmlal.u8        q9,  d4,  d2
-        vld1.8          {d6},     [r5], r4
         vadd.i16        d16, d16, d17
         vadd.i16        d17, d18, d19
   .ifc \codec,h264
@@ -245,14 +227,12 @@
         vshrn.u16       d16, q8,  #6
   .endif
         subs            r3,  r3,  #2
-        pld             [r1]
+        pld             [r1, r2]
   .ifc \type,avg
         vld1.32         {d20[0]}, [lr,:32], r2
         vld1.32         {d20[1]}, [lr,:32], r2
         vrhadd.u8       d16, d16, d20
   .endif
-        vext.8          d7,  d6,  d7,  #1
-        vtrn.32         d6,  d7
         vst1.32         {d16[0]}, [r0,:32], r2
         vst1.32         {d16[1]}, [r0,:32], r2
         bgt             1b
@@ -268,18 +248,15 @@
         beq             4f
 
         vext.32         d1,  d0,  d1,  #1
-        add             r5,  r1,  r2
-        lsl             r4,  r2,  #1
-        vld1.32         {d4[0]},  [r1], r4
-        vld1.32         {d4[1]},  [r5], r4
+        vld1.32         {d4[0]},  [r1], r2
 
-3:      pld             [r5]
+3:      vld1.32         {d4[1]},  [r1], r2
         vmull.u8        q8,  d4,  d0
-        vld1.32         {d4[0]},  [r1], r4
+        vld1.32         {d4[0]},  [r1], r2
         vmull.u8        q9,  d4,  d1
-        vld1.32         {d4[1]},  [r5], r4
         vadd.i16        d16, d16, d17
         vadd.i16        d17, d18, d19
+        pld             [r1]
   .ifc \codec,h264
         vrshrn.u16      d16, q8,  #6
   .else
@@ -292,7 +269,7 @@
         vrhadd.u8       d16, d16, d20
   .endif
         subs            r3,  r3,  #2
-        pld             [r1]
+        pld             [r1, r2]
         vst1.32         {d16[0]}, [r0,:32], r2
         vst1.32         {d16[1]}, [r0,:32], r2
         bgt             3b
@@ -305,13 +282,9 @@
         vext.8          d7,  d6,  d7,  #1
         vtrn.32         d4,  d5
         vtrn.32         d6,  d7
-
-5:      vmull.u8        q8,  d4,  d0
+        vmull.u8        q8,  d4,  d0
         vmull.u8        q9,  d6,  d0
         subs            r3,  r3,  #2
-        vld1.8          {d4},     [r1], r2
-        vext.8          d5,  d4,  d5,  #1
-        vtrn.32         d4,  d5
         vadd.i16        d16, d16, d17
         vadd.i16        d17, d18, d19
         pld             [r1]
@@ -326,13 +299,10 @@
         vld1.32         {d20[1]}, [lr,:32], r2
         vrhadd.u8       d16, d16, d20
   .endif
-        vld1.8          {d6},     [r1], r2
-        vext.8          d7,  d6,  d7,  #1
-        vtrn.32         d6,  d7
         pld             [r1]
         vst1.32         {d16[0]}, [r0,:32], r2
         vst1.32         {d16[1]}, [r0,:32], r2
-        bgt             5b
+        bgt             4b
 
         pop             {r4-r7, pc}
 endfunc
diff --git a/libavcodec/arm/h264idct_neon.S b/libavcodec/arm/h264idct_neon.S
index 612aec3..1b349ce 100644
--- a/libavcodec/arm/h264idct_neon.S
+++ b/libavcodec/arm/h264idct_neon.S
@@ -20,8 +20,6 @@
 
 #include "libavutil/arm/asm.S"
 
-        preserve8
-
 function ff_h264_idct_add_neon, export=1
         vld1.64         {d0-d3},  [r1,:128]
 
diff --git a/libavcodec/arm/h264pred_init_arm.c b/libavcodec/arm/h264pred_init_arm.c
index bd2ed0a..31714d7 100644
--- a/libavcodec/arm/h264pred_init_arm.c
+++ b/libavcodec/arm/h264pred_init_arm.c
@@ -23,25 +23,25 @@
 #include "libavutil/arm/cpu.h"
 #include "libavcodec/h264pred.h"
 
-void ff_pred16x16_vert_neon(uint8_t *src, int stride);
-void ff_pred16x16_hor_neon(uint8_t *src, int stride);
-void ff_pred16x16_plane_neon(uint8_t *src, int stride);
-void ff_pred16x16_dc_neon(uint8_t *src, int stride);
-void ff_pred16x16_128_dc_neon(uint8_t *src, int stride);
-void ff_pred16x16_left_dc_neon(uint8_t *src, int stride);
-void ff_pred16x16_top_dc_neon(uint8_t *src, int stride);
+void ff_pred16x16_vert_neon(uint8_t *src, ptrdiff_t stride);
+void ff_pred16x16_hor_neon(uint8_t *src, ptrdiff_t stride);
+void ff_pred16x16_plane_neon(uint8_t *src, ptrdiff_t stride);
+void ff_pred16x16_dc_neon(uint8_t *src, ptrdiff_t stride);
+void ff_pred16x16_128_dc_neon(uint8_t *src, ptrdiff_t stride);
+void ff_pred16x16_left_dc_neon(uint8_t *src, ptrdiff_t stride);
+void ff_pred16x16_top_dc_neon(uint8_t *src, ptrdiff_t stride);
 
-void ff_pred8x8_vert_neon(uint8_t *src, int stride);
-void ff_pred8x8_hor_neon(uint8_t *src, int stride);
-void ff_pred8x8_plane_neon(uint8_t *src, int stride);
-void ff_pred8x8_dc_neon(uint8_t *src, int stride);
-void ff_pred8x8_128_dc_neon(uint8_t *src, int stride);
-void ff_pred8x8_left_dc_neon(uint8_t *src, int stride);
-void ff_pred8x8_top_dc_neon(uint8_t *src, int stride);
-void ff_pred8x8_l0t_dc_neon(uint8_t *src, int stride);
-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);
+void ff_pred8x8_vert_neon(uint8_t *src, ptrdiff_t stride);
+void ff_pred8x8_hor_neon(uint8_t *src, ptrdiff_t stride);
+void ff_pred8x8_plane_neon(uint8_t *src, ptrdiff_t stride);
+void ff_pred8x8_dc_neon(uint8_t *src, ptrdiff_t stride);
+void ff_pred8x8_128_dc_neon(uint8_t *src, ptrdiff_t stride);
+void ff_pred8x8_left_dc_neon(uint8_t *src, ptrdiff_t stride);
+void ff_pred8x8_top_dc_neon(uint8_t *src, ptrdiff_t stride);
+void ff_pred8x8_l0t_dc_neon(uint8_t *src, ptrdiff_t stride);
+void ff_pred8x8_0lt_dc_neon(uint8_t *src, ptrdiff_t stride);
+void ff_pred8x8_l00_dc_neon(uint8_t *src, ptrdiff_t stride);
+void ff_pred8x8_0l0_dc_neon(uint8_t *src, ptrdiff_t stride);
 
 static void ff_h264_pred_init_neon(H264PredContext *h, int codec_id, const int bit_depth, const int chroma_format_idc)
 {
diff --git a/libavcodec/arm/int_neon.S b/libavcodec/arm/int_neon.S
index bce8451..6b28a97 100644
--- a/libavcodec/arm/int_neon.S
+++ b/libavcodec/arm/int_neon.S
@@ -21,7 +21,6 @@
 
 #include "libavutil/arm/asm.S"
 
-        preserve8
         .fpu neon
 
 function ff_scalarproduct_int16_neon, export=1
diff --git a/libavcodec/arm/mathops.h b/libavcodec/arm/mathops.h
index d67714c..9313d6b 100644
--- a/libavcodec/arm/mathops.h
+++ b/libavcodec/arm/mathops.h
@@ -36,6 +36,30 @@
     __asm__ ("smmul %0, %1, %2" : "=r"(r) : "r"(a), "r"(b));
     return r;
 }
+
+#define FASTDIV FASTDIV
+static av_always_inline av_const int FASTDIV(int a, int b)
+{
+    int r;
+    __asm__ ("cmp     %2, #2               \n\t"
+             "ldr     %0, [%3, %2, lsl #2] \n\t"
+             "ite     le                   \n\t"
+             "lsrle   %0, %1, #1           \n\t"
+             "smmulgt %0, %0, %1           \n\t"
+             : "=&r"(r) : "r"(a), "r"(b), "r"(ff_inverse) : "cc");
+    return r;
+}
+
+#else /* HAVE_ARMV6 */
+
+#define FASTDIV FASTDIV
+static av_always_inline av_const int FASTDIV(int a, int b)
+{
+    int r, t;
+    __asm__ ("umull %1, %0, %2, %3"
+             : "=&r"(r), "=&r"(t) : "r"(a), "r"(ff_inverse[b]));
+    return r;
+}
 #endif
 
 #define MLS64(d, a, b) MAC64(d, -(a), b)
diff --git a/libavcodec/arm/mdct_fixed_neon.S b/libavcodec/arm/mdct_fixed_neon.S
index 08a3887..c77be59 100644
--- a/libavcodec/arm/mdct_fixed_neon.S
+++ b/libavcodec/arm/mdct_fixed_neon.S
@@ -20,8 +20,6 @@
 
 #include "libavutil/arm/asm.S"
 
-        preserve8
-
 .macro  prerot          dst, rt
         lsr             r3,  r6,  #2            @ n4
         add             \rt, r4,  r6,  lsr #1   @ revtab + n4
diff --git a/libavcodec/arm/mdct_neon.S b/libavcodec/arm/mdct_neon.S
index a8f376d..e481cd1 100644
--- a/libavcodec/arm/mdct_neon.S
+++ b/libavcodec/arm/mdct_neon.S
@@ -21,8 +21,6 @@
 
 #include "libavutil/arm/asm.S"
 
-        preserve8
-
 #define ff_fft_calc_neon X(ff_fft_calc_neon)
 
 function ff_imdct_half_neon, export=1
diff --git a/libavcodec/arm/mpegvideo_armv5te.c b/libavcodec/arm/mpegvideo_armv5te.c
index dcde466..842620b 100644
--- a/libavcodec/arm/mpegvideo_armv5te.c
+++ b/libavcodec/arm/mpegvideo_armv5te.c
@@ -19,6 +19,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/avassert.h"
 #include "libavcodec/avcodec.h"
 #include "libavcodec/dsputil.h"
 #include "libavcodec/mpegvideo.h"
@@ -55,7 +56,7 @@
     int level, qmul, qadd;
     int nCoeffs;
 
-    assert(s->block_last_index[n]>=0);
+    av_assert2(s->block_last_index[n]>=0);
 
     qmul = qscale << 1;
 
@@ -84,7 +85,7 @@
     int qmul, qadd;
     int nCoeffs;
 
-    assert(s->block_last_index[n]>=0);
+    av_assert2(s->block_last_index[n]>=0);
 
     qadd = (qscale - 1) | 1;
     qmul = qscale << 1;
diff --git a/libavcodec/arm/rdft_neon.S b/libavcodec/arm/rdft_neon.S
index dcd3eee..781d976 100644
--- a/libavcodec/arm/rdft_neon.S
+++ b/libavcodec/arm/rdft_neon.S
@@ -21,8 +21,6 @@
 
 #include "libavutil/arm/asm.S"
 
-        preserve8
-
 function ff_rdft_calc_neon, export=1
         push            {r4-r8,lr}
 
diff --git a/libavcodec/arm/rv34dsp_init_neon.c b/libavcodec/arm/rv34dsp_init_arm.c
similarity index 60%
rename from libavcodec/arm/rv34dsp_init_neon.c
rename to libavcodec/arm/rv34dsp_init_arm.c
index b4a2f01..60ab82e 100644
--- a/libavcodec/arm/rv34dsp_init_neon.c
+++ b/libavcodec/arm/rv34dsp_init_arm.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2011 Janne Grunau <janne-libav@jannau.net>
  *
- * This file is part of Libav.
+ * This file is part of FFmpeg.
  *
- * Libav is free software; you can redistribute it and/or
+ * 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.
  *
- * Libav is distributed in the hope that it will be useful,
+ * 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 Libav; if not, write to the Free Software
+ * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -22,6 +22,7 @@
 
 #include "libavcodec/avcodec.h"
 #include "libavcodec/rv34dsp.h"
+#include "libavutil/arm/cpu.h"
 
 void ff_rv34_inv_transform_noround_neon(DCTELEM *block);
 
@@ -30,11 +31,15 @@
 void ff_rv34_idct_add_neon(uint8_t *dst, ptrdiff_t stride, DCTELEM *block);
 void ff_rv34_idct_dc_add_neon(uint8_t *dst, ptrdiff_t stride, int dc);
 
-void ff_rv34dsp_init_neon(RV34DSPContext *c, DSPContext* dsp)
+void ff_rv34dsp_init_arm(RV34DSPContext *c, DSPContext* dsp)
 {
-    c->rv34_inv_transform    = ff_rv34_inv_transform_noround_neon;
-    c->rv34_inv_transform_dc = ff_rv34_inv_transform_noround_dc_neon;
+    int cpu_flags = av_get_cpu_flags();
 
-    c->rv34_idct_add    = ff_rv34_idct_add_neon;
-    c->rv34_idct_dc_add = ff_rv34_idct_dc_add_neon;
+    if (have_neon(cpu_flags)) {
+        c->rv34_inv_transform    = ff_rv34_inv_transform_noround_neon;
+        c->rv34_inv_transform_dc = ff_rv34_inv_transform_noround_dc_neon;
+
+        c->rv34_idct_add    = ff_rv34_idct_add_neon;
+        c->rv34_idct_dc_add = ff_rv34_idct_dc_add_neon;
+    }
 }
diff --git a/libavcodec/arm/rv40dsp_init_neon.c b/libavcodec/arm/rv40dsp_init_arm.c
similarity index 92%
rename from libavcodec/arm/rv40dsp_init_neon.c
rename to libavcodec/arm/rv40dsp_init_arm.c
index 2ce50a2..1f9364a 100644
--- a/libavcodec/arm/rv40dsp_init_neon.c
+++ b/libavcodec/arm/rv40dsp_init_arm.c
@@ -1,20 +1,20 @@
 /*
  * Copyright (c) 2011 Janne Grunau <janne-libav@jannau.net>
  *
- * This file is part of Libav.
+ * This file is part of FFmpeg.
  *
- * Libav is free software; you can redistribute it and/or
+ * 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.
  *
- * Libav is distributed in the hope that it will be useful,
+ * 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 Libav; if not, write to the Free Software
+ * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -22,6 +22,7 @@
 
 #include "libavcodec/avcodec.h"
 #include "libavcodec/rv34dsp.h"
+#include "libavutil/arm/cpu.h"
 
 #define DECL_QPEL3(type, w, pos) \
     void ff_##type##_rv40_qpel##w##_mc##pos##_neon(uint8_t *dst, uint8_t *src,\
@@ -68,7 +69,7 @@
                                      int filter_q1, int alpha, int beta,
                                      int lim_p0q0, int lim_q1, int lim_p1);
 
-void ff_rv40dsp_init_neon(RV34DSPContext *c, DSPContext* dsp)
+static void ff_rv40dsp_init_neon(RV34DSPContext *c)
 {
     c->put_pixels_tab[0][ 1] = ff_put_rv40_qpel16_mc10_neon;
     c->put_pixels_tab[0][ 3] = ff_put_rv40_qpel16_mc30_neon;
@@ -136,3 +137,11 @@
     c->rv40_weak_loop_filter[0]     = ff_rv40_h_weak_loop_filter_neon;
     c->rv40_weak_loop_filter[1]     = ff_rv40_v_weak_loop_filter_neon;
 }
+
+void ff_rv40dsp_init_arm(RV34DSPContext *c, DSPContext* dsp)
+{
+    int cpu_flags = av_get_cpu_flags();
+
+    if (have_neon(cpu_flags))
+        ff_rv40dsp_init_neon(c);
+}
diff --git a/libavcodec/arm/synth_filter_neon.S b/libavcodec/arm/synth_filter_neon.S
index 0e38ffc..5417be7 100644
--- a/libavcodec/arm/synth_filter_neon.S
+++ b/libavcodec/arm/synth_filter_neon.S
@@ -20,8 +20,6 @@
 
 #include "libavutil/arm/asm.S"
 
-        preserve8
-
 function ff_synth_filter_float_neon, export=1
         push            {r3-r11,lr}
 
diff --git a/libavcodec/asv.c b/libavcodec/asv.c
new file mode 100644
index 0000000..34622b4
--- /dev/null
+++ b/libavcodec/asv.c
@@ -0,0 +1,95 @@
+/*
+ * 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
+ */
+
+/**
+ * @file
+ * ASUS V1/V2 encoder/decoder common data
+ */
+
+#include <stdint.h>
+
+#include "asv.h"
+#include "avcodec.h"
+#include "dsputil.h"
+
+const uint8_t ff_asv_scantab[64] = {
+    0x00,0x08,0x01,0x09,0x10,0x18,0x11,0x19,
+    0x02,0x0A,0x03,0x0B,0x12,0x1A,0x13,0x1B,
+    0x04,0x0C,0x05,0x0D,0x20,0x28,0x21,0x29,
+    0x06,0x0E,0x07,0x0F,0x14,0x1C,0x15,0x1D,
+    0x22,0x2A,0x23,0x2B,0x30,0x38,0x31,0x39,
+    0x16,0x1E,0x17,0x1F,0x24,0x2C,0x25,0x2D,
+    0x32,0x3A,0x33,0x3B,0x26,0x2E,0x27,0x2F,
+    0x34,0x3C,0x35,0x3D,0x36,0x3E,0x37,0x3F,
+};
+
+const uint8_t ff_asv_ccp_tab[17][2] = {
+    {0x2,2}, {0x7,5}, {0xB,5}, {0x3,5},
+    {0xD,5}, {0x5,5}, {0x9,5}, {0x1,5},
+    {0xE,5}, {0x6,5}, {0xA,5}, {0x2,5},
+    {0xC,5}, {0x4,5}, {0x8,5}, {0x3,2},
+    {0xF,5}, //EOB
+};
+
+const uint8_t ff_asv_level_tab[7][2] = {
+    {3,4}, {3,3}, {3,2}, {0,3}, {2,2}, {2,3}, {2,4}
+};
+
+const uint8_t ff_asv_dc_ccp_tab[8][2] = {
+    {0x1,2}, {0xD,4}, {0xF,4}, {0xC,4},
+    {0x5,3}, {0xE,4}, {0x4,3}, {0x0,2},
+};
+
+const uint8_t ff_asv_ac_ccp_tab[16][2] = {
+    {0x00,2}, {0x3B,6}, {0x0A,4}, {0x3A,6},
+    {0x02,3}, {0x39,6}, {0x3C,6}, {0x38,6},
+    {0x03,3}, {0x3D,6}, {0x08,4}, {0x1F,5},
+    {0x09,4}, {0x0B,4}, {0x0D,4}, {0x0C,4},
+};
+
+const uint8_t ff_asv2_level_tab[63][2] = {
+    {0x3F,10},{0x2F,10},{0x37,10},{0x27,10},{0x3B,10},{0x2B,10},{0x33,10},{0x23,10},
+    {0x3D,10},{0x2D,10},{0x35,10},{0x25,10},{0x39,10},{0x29,10},{0x31,10},{0x21,10},
+    {0x1F, 8},{0x17, 8},{0x1B, 8},{0x13, 8},{0x1D, 8},{0x15, 8},{0x19, 8},{0x11, 8},
+    {0x0F, 6},{0x0B, 6},{0x0D, 6},{0x09, 6},
+    {0x07, 4},{0x05, 4},
+    {0x03, 2},
+    {0x00, 5},
+    {0x02, 2},
+    {0x04, 4},{0x06, 4},
+    {0x08, 6},{0x0C, 6},{0x0A, 6},{0x0E, 6},
+    {0x10, 8},{0x18, 8},{0x14, 8},{0x1C, 8},{0x12, 8},{0x1A, 8},{0x16, 8},{0x1E, 8},
+    {0x20,10},{0x30,10},{0x28,10},{0x38,10},{0x24,10},{0x34,10},{0x2C,10},{0x3C,10},
+    {0x22,10},{0x32,10},{0x2A,10},{0x3A,10},{0x26,10},{0x36,10},{0x2E,10},{0x3E,10},
+};
+
+av_cold void ff_asv_common_init(AVCodecContext *avctx) {
+    ASV1Context * const a = avctx->priv_data;
+
+    ff_dsputil_init(&a->dsp, avctx);
+
+    a->mb_width   = (avctx->width  + 15) / 16;
+    a->mb_height  = (avctx->height + 15) / 16;
+    a->mb_width2  = (avctx->width  + 0) / 16;
+    a->mb_height2 = (avctx->height + 0) / 16;
+
+    avctx->coded_frame= &a->picture;
+    a->avctx= avctx;
+}
diff --git a/libavcodec/asv.h b/libavcodec/asv.h
new file mode 100644
index 0000000..4a6c799
--- /dev/null
+++ b/libavcodec/asv.h
@@ -0,0 +1,67 @@
+/*
+ * 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
+ */
+
+/**
+ * @file
+ * ASUS V1/V2 encoder/decoder common data.
+ */
+
+#ifndef AVCODEC_ASV_H
+#define AVCODEC_ASV_H
+
+#include <stdint.h>
+
+#include "libavutil/attributes.h"
+#include "libavutil/mem.h"
+
+#include "avcodec.h"
+#include "dsputil.h"
+#include "get_bits.h"
+#include "put_bits.h"
+
+typedef struct ASV1Context{
+    AVCodecContext *avctx;
+    DSPContext dsp;
+    AVFrame picture;
+    PutBitContext pb;
+    GetBitContext gb;
+    ScanTable scantable;
+    int inv_qscale;
+    int mb_width;
+    int mb_height;
+    int mb_width2;
+    int mb_height2;
+    DECLARE_ALIGNED(16, DCTELEM, block)[6][64];
+    uint16_t intra_matrix[64];
+    int q_intra_matrix[64];
+    uint8_t *bitstream_buffer;
+    unsigned int bitstream_buffer_size;
+} ASV1Context;
+
+extern const uint8_t ff_asv_scantab[64];
+extern const uint8_t ff_asv_ccp_tab[17][2];
+extern const uint8_t ff_asv_level_tab[7][2];
+extern const uint8_t ff_asv_dc_ccp_tab[8][2];
+extern const uint8_t ff_asv_ac_ccp_tab[16][2];
+extern const uint8_t ff_asv2_level_tab[63][2];
+
+av_cold void ff_asv_common_init(AVCodecContext *avctx);
+
+#endif /* AVCODEC_ASV_H */
diff --git a/libavcodec/asv1.c b/libavcodec/asv1.c
deleted file mode 100644
index 51b924a..0000000
--- a/libavcodec/asv1.c
+++ /dev/null
@@ -1,666 +0,0 @@
-/*
- * ASUS V1/V2 codec
- * 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
- */
-
-/**
- * @file
- * ASUS V1/V2 codec.
- */
-
-#include "avcodec.h"
-#include "internal.h"
-#include "libavutil/common.h"
-#include "put_bits.h"
-#include "dsputil.h"
-#include "mpeg12data.h"
-
-#define VLC_BITS 6
-#define ASV2_LEVEL_VLC_BITS 10
-
-typedef struct ASV1Context{
-    AVCodecContext *avctx;
-    DSPContext dsp;
-    AVFrame picture;
-    PutBitContext pb;
-    GetBitContext gb;
-    ScanTable scantable;
-    int inv_qscale;
-    int mb_width;
-    int mb_height;
-    int mb_width2;
-    int mb_height2;
-    DECLARE_ALIGNED(16, DCTELEM, block)[6][64];
-    uint16_t intra_matrix[64];
-    int q_intra_matrix[64];
-    uint8_t *bitstream_buffer;
-    unsigned int bitstream_buffer_size;
-} ASV1Context;
-
-static const uint8_t scantab[64]={
-    0x00,0x08,0x01,0x09,0x10,0x18,0x11,0x19,
-    0x02,0x0A,0x03,0x0B,0x12,0x1A,0x13,0x1B,
-    0x04,0x0C,0x05,0x0D,0x20,0x28,0x21,0x29,
-    0x06,0x0E,0x07,0x0F,0x14,0x1C,0x15,0x1D,
-    0x22,0x2A,0x23,0x2B,0x30,0x38,0x31,0x39,
-    0x16,0x1E,0x17,0x1F,0x24,0x2C,0x25,0x2D,
-    0x32,0x3A,0x33,0x3B,0x26,0x2E,0x27,0x2F,
-    0x34,0x3C,0x35,0x3D,0x36,0x3E,0x37,0x3F,
-};
-
-
-static const uint8_t ccp_tab[17][2]={
-    {0x2,2}, {0x7,5}, {0xB,5}, {0x3,5},
-    {0xD,5}, {0x5,5}, {0x9,5}, {0x1,5},
-    {0xE,5}, {0x6,5}, {0xA,5}, {0x2,5},
-    {0xC,5}, {0x4,5}, {0x8,5}, {0x3,2},
-    {0xF,5}, //EOB
-};
-
-static const uint8_t level_tab[7][2]={
-    {3,4}, {3,3}, {3,2}, {0,3}, {2,2}, {2,3}, {2,4}
-};
-
-static const uint8_t dc_ccp_tab[8][2]={
-    {0x1,2}, {0xD,4}, {0xF,4}, {0xC,4},
-    {0x5,3}, {0xE,4}, {0x4,3}, {0x0,2},
-};
-
-static const uint8_t ac_ccp_tab[16][2]={
-    {0x00,2}, {0x3B,6}, {0x0A,4}, {0x3A,6},
-    {0x02,3}, {0x39,6}, {0x3C,6}, {0x38,6},
-    {0x03,3}, {0x3D,6}, {0x08,4}, {0x1F,5},
-    {0x09,4}, {0x0B,4}, {0x0D,4}, {0x0C,4},
-};
-
-static const uint8_t asv2_level_tab[63][2]={
-    {0x3F,10},{0x2F,10},{0x37,10},{0x27,10},{0x3B,10},{0x2B,10},{0x33,10},{0x23,10},
-    {0x3D,10},{0x2D,10},{0x35,10},{0x25,10},{0x39,10},{0x29,10},{0x31,10},{0x21,10},
-    {0x1F, 8},{0x17, 8},{0x1B, 8},{0x13, 8},{0x1D, 8},{0x15, 8},{0x19, 8},{0x11, 8},
-    {0x0F, 6},{0x0B, 6},{0x0D, 6},{0x09, 6},
-    {0x07, 4},{0x05, 4},
-    {0x03, 2},
-    {0x00, 5},
-    {0x02, 2},
-    {0x04, 4},{0x06, 4},
-    {0x08, 6},{0x0C, 6},{0x0A, 6},{0x0E, 6},
-    {0x10, 8},{0x18, 8},{0x14, 8},{0x1C, 8},{0x12, 8},{0x1A, 8},{0x16, 8},{0x1E, 8},
-    {0x20,10},{0x30,10},{0x28,10},{0x38,10},{0x24,10},{0x34,10},{0x2C,10},{0x3C,10},
-    {0x22,10},{0x32,10},{0x2A,10},{0x3A,10},{0x26,10},{0x36,10},{0x2E,10},{0x3E,10},
-};
-
-
-static VLC ccp_vlc;
-static VLC level_vlc;
-static VLC dc_ccp_vlc;
-static VLC ac_ccp_vlc;
-static VLC asv2_level_vlc;
-
-static av_cold void init_vlcs(ASV1Context *a){
-    static int done = 0;
-
-    if (!done) {
-        done = 1;
-
-        INIT_VLC_STATIC(&ccp_vlc, VLC_BITS, 17,
-                 &ccp_tab[0][1], 2, 1,
-                 &ccp_tab[0][0], 2, 1, 64);
-        INIT_VLC_STATIC(&dc_ccp_vlc, VLC_BITS, 8,
-                 &dc_ccp_tab[0][1], 2, 1,
-                 &dc_ccp_tab[0][0], 2, 1, 64);
-        INIT_VLC_STATIC(&ac_ccp_vlc, VLC_BITS, 16,
-                 &ac_ccp_tab[0][1], 2, 1,
-                 &ac_ccp_tab[0][0], 2, 1, 64);
-        INIT_VLC_STATIC(&level_vlc,  VLC_BITS, 7,
-                 &level_tab[0][1], 2, 1,
-                 &level_tab[0][0], 2, 1, 64);
-        INIT_VLC_STATIC(&asv2_level_vlc, ASV2_LEVEL_VLC_BITS, 63,
-                 &asv2_level_tab[0][1], 2, 1,
-                 &asv2_level_tab[0][0], 2, 1, 1024);
-    }
-}
-
-//FIXME write a reversed bitstream reader to avoid the double reverse
-static inline int asv2_get_bits(GetBitContext *gb, int n){
-    return av_reverse[ get_bits(gb, n) << (8-n) ];
-}
-
-static inline void asv2_put_bits(PutBitContext *pb, int n, int v){
-    put_bits(pb, n, av_reverse[ v << (8-n) ]);
-}
-
-static inline int asv1_get_level(GetBitContext *gb){
-    int code= get_vlc2(gb, level_vlc.table, VLC_BITS, 1);
-
-    if(code==3) return get_sbits(gb, 8);
-    else        return code - 3;
-}
-
-static inline int asv2_get_level(GetBitContext *gb){
-    int code= get_vlc2(gb, asv2_level_vlc.table, ASV2_LEVEL_VLC_BITS, 1);
-
-    if(code==31) return (int8_t)asv2_get_bits(gb, 8);
-    else         return code - 31;
-}
-
-static inline void asv1_put_level(PutBitContext *pb, int level){
-    unsigned int index= level + 3;
-
-    if(index <= 6) put_bits(pb, level_tab[index][1], level_tab[index][0]);
-    else{
-        put_bits(pb, level_tab[3][1], level_tab[3][0]);
-        put_sbits(pb, 8, level);
-    }
-}
-
-static inline void asv2_put_level(PutBitContext *pb, int level){
-    unsigned int index= level + 31;
-
-    if(index <= 62) put_bits(pb, asv2_level_tab[index][1], asv2_level_tab[index][0]);
-    else{
-        put_bits(pb, asv2_level_tab[31][1], asv2_level_tab[31][0]);
-        asv2_put_bits(pb, 8, level&0xFF);
-    }
-}
-
-static inline int asv1_decode_block(ASV1Context *a, DCTELEM block[64]){
-    int i;
-
-    block[0]= 8*get_bits(&a->gb, 8);
-
-    for(i=0; i<11; i++){
-        const int ccp= get_vlc2(&a->gb, ccp_vlc.table, VLC_BITS, 1);
-
-        if(ccp){
-            if(ccp == 16) break;
-            if(ccp < 0 || i>=10){
-                av_log(a->avctx, AV_LOG_ERROR, "coded coeff pattern damaged\n");
-                return -1;
-            }
-
-            if(ccp&8) block[a->scantable.permutated[4*i+0]]= (asv1_get_level(&a->gb) * a->intra_matrix[4*i+0])>>4;
-            if(ccp&4) block[a->scantable.permutated[4*i+1]]= (asv1_get_level(&a->gb) * a->intra_matrix[4*i+1])>>4;
-            if(ccp&2) block[a->scantable.permutated[4*i+2]]= (asv1_get_level(&a->gb) * a->intra_matrix[4*i+2])>>4;
-            if(ccp&1) block[a->scantable.permutated[4*i+3]]= (asv1_get_level(&a->gb) * a->intra_matrix[4*i+3])>>4;
-        }
-    }
-
-    return 0;
-}
-
-static inline int asv2_decode_block(ASV1Context *a, DCTELEM block[64]){
-    int i, count, ccp;
-
-    count= asv2_get_bits(&a->gb, 4);
-
-    block[0]= 8*asv2_get_bits(&a->gb, 8);
-
-    ccp= get_vlc2(&a->gb, dc_ccp_vlc.table, VLC_BITS, 1);
-    if(ccp){
-        if(ccp&4) block[a->scantable.permutated[1]]= (asv2_get_level(&a->gb) * a->intra_matrix[1])>>4;
-        if(ccp&2) block[a->scantable.permutated[2]]= (asv2_get_level(&a->gb) * a->intra_matrix[2])>>4;
-        if(ccp&1) block[a->scantable.permutated[3]]= (asv2_get_level(&a->gb) * a->intra_matrix[3])>>4;
-    }
-
-    for(i=1; i<count+1; i++){
-        const int ccp= get_vlc2(&a->gb, ac_ccp_vlc.table, VLC_BITS, 1);
-
-        if(ccp){
-            if(ccp&8) block[a->scantable.permutated[4*i+0]]= (asv2_get_level(&a->gb) * a->intra_matrix[4*i+0])>>4;
-            if(ccp&4) block[a->scantable.permutated[4*i+1]]= (asv2_get_level(&a->gb) * a->intra_matrix[4*i+1])>>4;
-            if(ccp&2) block[a->scantable.permutated[4*i+2]]= (asv2_get_level(&a->gb) * a->intra_matrix[4*i+2])>>4;
-            if(ccp&1) block[a->scantable.permutated[4*i+3]]= (asv2_get_level(&a->gb) * a->intra_matrix[4*i+3])>>4;
-        }
-    }
-
-    return 0;
-}
-
-static inline void asv1_encode_block(ASV1Context *a, DCTELEM block[64]){
-    int i;
-    int nc_count=0;
-
-    put_bits(&a->pb, 8, (block[0] + 32)>>6);
-    block[0]= 0;
-
-    for(i=0; i<10; i++){
-        const int index= scantab[4*i];
-        int ccp=0;
-
-        if( (block[index + 0] = (block[index + 0]*a->q_intra_matrix[index + 0] + (1<<15))>>16) ) ccp |= 8;
-        if( (block[index + 8] = (block[index + 8]*a->q_intra_matrix[index + 8] + (1<<15))>>16) ) ccp |= 4;
-        if( (block[index + 1] = (block[index + 1]*a->q_intra_matrix[index + 1] + (1<<15))>>16) ) ccp |= 2;
-        if( (block[index + 9] = (block[index + 9]*a->q_intra_matrix[index + 9] + (1<<15))>>16) ) ccp |= 1;
-
-        if(ccp){
-            for(;nc_count; nc_count--)
-                put_bits(&a->pb, ccp_tab[0][1], ccp_tab[0][0]);
-
-            put_bits(&a->pb, ccp_tab[ccp][1], ccp_tab[ccp][0]);
-
-            if(ccp&8) asv1_put_level(&a->pb, block[index + 0]);
-            if(ccp&4) asv1_put_level(&a->pb, block[index + 8]);
-            if(ccp&2) asv1_put_level(&a->pb, block[index + 1]);
-            if(ccp&1) asv1_put_level(&a->pb, block[index + 9]);
-        }else{
-            nc_count++;
-        }
-    }
-    put_bits(&a->pb, ccp_tab[16][1], ccp_tab[16][0]);
-}
-
-static inline void asv2_encode_block(ASV1Context *a, DCTELEM block[64]){
-    int i;
-    int count=0;
-
-    for(count=63; count>3; count--){
-        const int index= scantab[count];
-
-        if( (block[index]*a->q_intra_matrix[index] + (1<<15))>>16 )
-            break;
-    }
-
-    count >>= 2;
-
-    asv2_put_bits(&a->pb, 4, count);
-    asv2_put_bits(&a->pb, 8, (block[0] + 32)>>6);
-    block[0]= 0;
-
-    for(i=0; i<=count; i++){
-        const int index= scantab[4*i];
-        int ccp=0;
-
-        if( (block[index + 0] = (block[index + 0]*a->q_intra_matrix[index + 0] + (1<<15))>>16) ) ccp |= 8;
-        if( (block[index + 8] = (block[index + 8]*a->q_intra_matrix[index + 8] + (1<<15))>>16) ) ccp |= 4;
-        if( (block[index + 1] = (block[index + 1]*a->q_intra_matrix[index + 1] + (1<<15))>>16) ) ccp |= 2;
-        if( (block[index + 9] = (block[index + 9]*a->q_intra_matrix[index + 9] + (1<<15))>>16) ) ccp |= 1;
-
-        av_assert2(i || ccp<8);
-        if(i) put_bits(&a->pb, ac_ccp_tab[ccp][1], ac_ccp_tab[ccp][0]);
-        else  put_bits(&a->pb, dc_ccp_tab[ccp][1], dc_ccp_tab[ccp][0]);
-
-        if(ccp){
-            if(ccp&8) asv2_put_level(&a->pb, block[index + 0]);
-            if(ccp&4) asv2_put_level(&a->pb, block[index + 8]);
-            if(ccp&2) asv2_put_level(&a->pb, block[index + 1]);
-            if(ccp&1) asv2_put_level(&a->pb, block[index + 9]);
-        }
-    }
-}
-
-static inline int decode_mb(ASV1Context *a, DCTELEM block[6][64]){
-    int i;
-
-    a->dsp.clear_blocks(block[0]);
-
-    if(a->avctx->codec_id == AV_CODEC_ID_ASV1){
-        for(i=0; i<6; i++){
-            if( asv1_decode_block(a, block[i]) < 0)
-                return -1;
-        }
-    }else{
-        for(i=0; i<6; i++){
-            if( asv2_decode_block(a, block[i]) < 0)
-                return -1;
-        }
-    }
-    return 0;
-}
-
-#define MAX_MB_SIZE (30*16*16*3/2/8)
-
-static inline int encode_mb(ASV1Context *a, DCTELEM block[6][64]){
-    int i;
-
-    if (a->pb.buf_end - a->pb.buf - (put_bits_count(&a->pb)>>3) < MAX_MB_SIZE) {
-        av_log(a->avctx, AV_LOG_ERROR, "encoded frame too large\n");
-        return -1;
-    }
-
-    if(a->avctx->codec_id == AV_CODEC_ID_ASV1){
-        for(i=0; i<6; i++)
-            asv1_encode_block(a, block[i]);
-    }else{
-        for(i=0; i<6; i++)
-            asv2_encode_block(a, block[i]);
-    }
-    return 0;
-}
-
-static inline void idct_put(ASV1Context *a, int mb_x, int mb_y){
-    DCTELEM (*block)[64]= a->block;
-    int linesize= a->picture.linesize[0];
-
-    uint8_t *dest_y  = a->picture.data[0] + (mb_y * 16* linesize              ) + mb_x * 16;
-    uint8_t *dest_cb = a->picture.data[1] + (mb_y * 8 * a->picture.linesize[1]) + mb_x * 8;
-    uint8_t *dest_cr = a->picture.data[2] + (mb_y * 8 * a->picture.linesize[2]) + mb_x * 8;
-
-    a->dsp.idct_put(dest_y                 , linesize, block[0]);
-    a->dsp.idct_put(dest_y              + 8, linesize, block[1]);
-    a->dsp.idct_put(dest_y + 8*linesize    , linesize, block[2]);
-    a->dsp.idct_put(dest_y + 8*linesize + 8, linesize, block[3]);
-
-    if(!(a->avctx->flags&CODEC_FLAG_GRAY)){
-        a->dsp.idct_put(dest_cb, a->picture.linesize[1], block[4]);
-        a->dsp.idct_put(dest_cr, a->picture.linesize[2], block[5]);
-    }
-}
-
-static inline void dct_get(ASV1Context *a, int mb_x, int mb_y){
-    DCTELEM (*block)[64]= a->block;
-    int linesize= a->picture.linesize[0];
-    int i;
-
-    uint8_t *ptr_y  = a->picture.data[0] + (mb_y * 16* linesize              ) + mb_x * 16;
-    uint8_t *ptr_cb = a->picture.data[1] + (mb_y * 8 * a->picture.linesize[1]) + mb_x * 8;
-    uint8_t *ptr_cr = a->picture.data[2] + (mb_y * 8 * a->picture.linesize[2]) + mb_x * 8;
-
-    a->dsp.get_pixels(block[0], ptr_y                 , linesize);
-    a->dsp.get_pixels(block[1], ptr_y              + 8, linesize);
-    a->dsp.get_pixels(block[2], ptr_y + 8*linesize    , linesize);
-    a->dsp.get_pixels(block[3], ptr_y + 8*linesize + 8, linesize);
-    for(i=0; i<4; i++)
-        a->dsp.fdct(block[i]);
-
-    if(!(a->avctx->flags&CODEC_FLAG_GRAY)){
-        a->dsp.get_pixels(block[4], ptr_cb, a->picture.linesize[1]);
-        a->dsp.get_pixels(block[5], ptr_cr, a->picture.linesize[2]);
-        for(i=4; i<6; i++)
-            a->dsp.fdct(block[i]);
-    }
-}
-
-static int decode_frame(AVCodecContext *avctx,
-                        void *data, int *data_size,
-                        AVPacket *avpkt)
-{
-    const uint8_t *buf = avpkt->data;
-    int buf_size = avpkt->size;
-    ASV1Context * const a = avctx->priv_data;
-    AVFrame *picture = data;
-    AVFrame * const p= &a->picture;
-    int mb_x, mb_y;
-
-    if(p->data[0])
-        avctx->release_buffer(avctx, p);
-
-    p->reference= 0;
-    if(avctx->get_buffer(avctx, p) < 0){
-        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
-    }
-    p->pict_type= AV_PICTURE_TYPE_I;
-    p->key_frame= 1;
-
-    av_fast_padded_malloc(&a->bitstream_buffer, &a->bitstream_buffer_size,
-                          buf_size);
-    if (!a->bitstream_buffer)
-        return AVERROR(ENOMEM);
-
-    if(avctx->codec_id == AV_CODEC_ID_ASV1)
-        a->dsp.bswap_buf((uint32_t*)a->bitstream_buffer, (const uint32_t*)buf, buf_size/4);
-    else{
-        int i;
-        for(i=0; i<buf_size; i++)
-            a->bitstream_buffer[i]= av_reverse[ buf[i] ];
-    }
-
-    init_get_bits(&a->gb, a->bitstream_buffer, buf_size*8);
-
-    for(mb_y=0; mb_y<a->mb_height2; mb_y++){
-        for(mb_x=0; mb_x<a->mb_width2; mb_x++){
-            if( decode_mb(a, a->block) <0)
-                return -1;
-
-            idct_put(a, mb_x, mb_y);
-        }
-    }
-
-    if(a->mb_width2 != a->mb_width){
-        mb_x= a->mb_width2;
-        for(mb_y=0; mb_y<a->mb_height2; mb_y++){
-            if( decode_mb(a, a->block) <0)
-                return -1;
-
-            idct_put(a, mb_x, mb_y);
-        }
-    }
-
-    if(a->mb_height2 != a->mb_height){
-        mb_y= a->mb_height2;
-        for(mb_x=0; mb_x<a->mb_width; mb_x++){
-            if( decode_mb(a, a->block) <0)
-                return -1;
-
-            idct_put(a, mb_x, mb_y);
-        }
-    }
-
-    *picture   = a->picture;
-    *data_size = sizeof(AVPicture);
-
-    emms_c();
-
-    return (get_bits_count(&a->gb)+31)/32*4;
-}
-
-#if CONFIG_ASV1_ENCODER || CONFIG_ASV2_ENCODER
-static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
-                        const AVFrame *pict, int *got_packet)
-{
-    ASV1Context * const a = avctx->priv_data;
-    AVFrame * const p= &a->picture;
-    int size, ret;
-    int mb_x, mb_y;
-
-    if ((ret = ff_alloc_packet2(avctx, pkt, a->mb_height*a->mb_width*MAX_MB_SIZE +
-                                  FF_MIN_BUFFER_SIZE)) < 0)
-        return ret;
-
-    init_put_bits(&a->pb, pkt->data, pkt->size);
-
-    *p = *pict;
-    p->pict_type= AV_PICTURE_TYPE_I;
-    p->key_frame= 1;
-
-    for(mb_y=0; mb_y<a->mb_height2; mb_y++){
-        for(mb_x=0; mb_x<a->mb_width2; mb_x++){
-            dct_get(a, mb_x, mb_y);
-            encode_mb(a, a->block);
-        }
-    }
-
-    if(a->mb_width2 != a->mb_width){
-        mb_x= a->mb_width2;
-        for(mb_y=0; mb_y<a->mb_height2; mb_y++){
-            dct_get(a, mb_x, mb_y);
-            encode_mb(a, a->block);
-        }
-    }
-
-    if(a->mb_height2 != a->mb_height){
-        mb_y= a->mb_height2;
-        for(mb_x=0; mb_x<a->mb_width; mb_x++){
-            dct_get(a, mb_x, mb_y);
-            encode_mb(a, a->block);
-        }
-    }
-    emms_c();
-
-    avpriv_align_put_bits(&a->pb);
-    while(put_bits_count(&a->pb)&31)
-        put_bits(&a->pb, 8, 0);
-
-    size= put_bits_count(&a->pb)/32;
-
-    if(avctx->codec_id == AV_CODEC_ID_ASV1)
-        a->dsp.bswap_buf((uint32_t*)pkt->data, (uint32_t*)pkt->data, size);
-    else{
-        int i;
-        for(i=0; i<4*size; i++)
-            pkt->data[i] = av_reverse[pkt->data[i]];
-    }
-
-    pkt->size   = size*4;
-    pkt->flags |= AV_PKT_FLAG_KEY;
-    *got_packet = 1;
-
-    return 0;
-}
-#endif /* CONFIG_ASV1_ENCODER || CONFIG_ASV2_ENCODER */
-
-static av_cold void common_init(AVCodecContext *avctx){
-    ASV1Context * const a = avctx->priv_data;
-
-    ff_dsputil_init(&a->dsp, avctx);
-
-    a->mb_width   = (avctx->width  + 15) / 16;
-    a->mb_height  = (avctx->height + 15) / 16;
-    a->mb_width2  = (avctx->width  + 0) / 16;
-    a->mb_height2 = (avctx->height + 0) / 16;
-
-    avctx->coded_frame= &a->picture;
-    a->avctx= avctx;
-}
-
-static av_cold int decode_init(AVCodecContext *avctx){
-    ASV1Context * const a = avctx->priv_data;
-    AVFrame *p= &a->picture;
-    int i;
-    const int scale= avctx->codec_id == AV_CODEC_ID_ASV1 ? 1 : 2;
-
-    common_init(avctx);
-    init_vlcs(a);
-    ff_init_scantable(a->dsp.idct_permutation, &a->scantable, scantab);
-    avctx->pix_fmt= PIX_FMT_YUV420P;
-
-    if(avctx->extradata_size < 1 || (a->inv_qscale= avctx->extradata[0]) == 0){
-        av_log(avctx, AV_LOG_ERROR, "illegal qscale 0\n");
-        if(avctx->codec_id == AV_CODEC_ID_ASV1)
-            a->inv_qscale= 6;
-        else
-            a->inv_qscale= 10;
-    }
-
-    for(i=0; i<64; i++){
-        int index= scantab[i];
-
-        a->intra_matrix[i]= 64*scale*ff_mpeg1_default_intra_matrix[index] / a->inv_qscale;
-    }
-
-    p->qstride= a->mb_width;
-    p->qscale_table= av_malloc( p->qstride * a->mb_height);
-    p->quality= (32*scale + a->inv_qscale/2)/a->inv_qscale;
-    memset(p->qscale_table, p->quality, p->qstride*a->mb_height);
-
-    return 0;
-}
-
-#if CONFIG_ASV1_ENCODER || CONFIG_ASV2_ENCODER
-static av_cold int encode_init(AVCodecContext *avctx){
-    ASV1Context * const a = avctx->priv_data;
-    int i;
-    const int scale= avctx->codec_id == AV_CODEC_ID_ASV1 ? 1 : 2;
-
-    common_init(avctx);
-
-    if(avctx->global_quality == 0) avctx->global_quality= 4*FF_QUALITY_SCALE;
-
-    a->inv_qscale= (32*scale*FF_QUALITY_SCALE +  avctx->global_quality/2) / avctx->global_quality;
-
-    avctx->extradata= av_mallocz(8);
-    avctx->extradata_size=8;
-    ((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];
-        a->q_intra_matrix[i]= ((a->inv_qscale<<16) + q/2) / q;
-    }
-
-    return 0;
-}
-#endif /* CONFIG_ASV1_ENCODER || CONFIG_ASV2_ENCODER */
-
-static av_cold int decode_end(AVCodecContext *avctx){
-    ASV1Context * const a = avctx->priv_data;
-
-    av_freep(&a->bitstream_buffer);
-    av_freep(&a->picture.qscale_table);
-    a->bitstream_buffer_size=0;
-
-    if(a->picture.data[0])
-        avctx->release_buffer(avctx, &a->picture);
-
-    return 0;
-}
-
-#if CONFIG_ASV1_DECODER
-AVCodec ff_asv1_decoder = {
-    .name           = "asv1",
-    .type           = AVMEDIA_TYPE_VIDEO,
-    .id             = AV_CODEC_ID_ASV1,
-    .priv_data_size = sizeof(ASV1Context),
-    .init           = decode_init,
-    .close          = decode_end,
-    .decode         = decode_frame,
-    .capabilities   = CODEC_CAP_DR1,
-    .long_name      = NULL_IF_CONFIG_SMALL("ASUS V1"),
-};
-#endif
-
-#if CONFIG_ASV2_DECODER
-AVCodec ff_asv2_decoder = {
-    .name           = "asv2",
-    .type           = AVMEDIA_TYPE_VIDEO,
-    .id             = AV_CODEC_ID_ASV2,
-    .priv_data_size = sizeof(ASV1Context),
-    .init           = decode_init,
-    .close          = decode_end,
-    .decode         = decode_frame,
-    .capabilities   = CODEC_CAP_DR1,
-    .long_name      = NULL_IF_CONFIG_SMALL("ASUS V2"),
-};
-#endif
-
-#if CONFIG_ASV1_ENCODER
-AVCodec ff_asv1_encoder = {
-    .name           = "asv1",
-    .type           = AVMEDIA_TYPE_VIDEO,
-    .id             = AV_CODEC_ID_ASV1,
-    .priv_data_size = sizeof(ASV1Context),
-    .init           = encode_init,
-    .encode2        = encode_frame,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUV420P, PIX_FMT_NONE },
-    .long_name      = NULL_IF_CONFIG_SMALL("ASUS V1"),
-};
-#endif
-
-#if CONFIG_ASV2_ENCODER
-AVCodec ff_asv2_encoder = {
-    .name           = "asv2",
-    .type           = AVMEDIA_TYPE_VIDEO,
-    .id             = AV_CODEC_ID_ASV2,
-    .priv_data_size = sizeof(ASV1Context),
-    .init           = encode_init,
-    .encode2        = encode_frame,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUV420P, PIX_FMT_NONE },
-    .long_name      = NULL_IF_CONFIG_SMALL("ASUS V2"),
-};
-#endif
diff --git a/libavcodec/asvdec.c b/libavcodec/asvdec.c
new file mode 100644
index 0000000..b9686a2
--- /dev/null
+++ b/libavcodec/asvdec.c
@@ -0,0 +1,326 @@
+/*
+ * 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
+ */
+
+/**
+ * @file
+ * ASUS V1/V2 decoder.
+ */
+
+#include "libavutil/attributes.h"
+#include "libavutil/mem.h"
+
+#include "asv.h"
+#include "avcodec.h"
+#include "put_bits.h"
+#include "dsputil.h"
+#include "mathops.h"
+#include "mpeg12data.h"
+
+#define VLC_BITS 6
+#define ASV2_LEVEL_VLC_BITS 10
+
+static VLC ccp_vlc;
+static VLC level_vlc;
+static VLC dc_ccp_vlc;
+static VLC ac_ccp_vlc;
+static VLC asv2_level_vlc;
+
+static av_cold void init_vlcs(ASV1Context *a){
+    static int done = 0;
+
+    if (!done) {
+        done = 1;
+
+        INIT_VLC_STATIC(&ccp_vlc, VLC_BITS, 17,
+                 &ff_asv_ccp_tab[0][1], 2, 1,
+                 &ff_asv_ccp_tab[0][0], 2, 1, 64);
+        INIT_VLC_STATIC(&dc_ccp_vlc, VLC_BITS, 8,
+                 &ff_asv_dc_ccp_tab[0][1], 2, 1,
+                 &ff_asv_dc_ccp_tab[0][0], 2, 1, 64);
+        INIT_VLC_STATIC(&ac_ccp_vlc, VLC_BITS, 16,
+                 &ff_asv_ac_ccp_tab[0][1], 2, 1,
+                 &ff_asv_ac_ccp_tab[0][0], 2, 1, 64);
+        INIT_VLC_STATIC(&level_vlc,  VLC_BITS, 7,
+                 &ff_asv_level_tab[0][1], 2, 1,
+                 &ff_asv_level_tab[0][0], 2, 1, 64);
+        INIT_VLC_STATIC(&asv2_level_vlc, ASV2_LEVEL_VLC_BITS, 63,
+                 &ff_asv2_level_tab[0][1], 2, 1,
+                 &ff_asv2_level_tab[0][0], 2, 1, 1024);
+    }
+}
+
+//FIXME write a reversed bitstream reader to avoid the double reverse
+static inline int asv2_get_bits(GetBitContext *gb, int n){
+    return ff_reverse[ get_bits(gb, n) << (8-n) ];
+}
+
+static inline int asv1_get_level(GetBitContext *gb){
+    int code= get_vlc2(gb, level_vlc.table, VLC_BITS, 1);
+
+    if(code==3) return get_sbits(gb, 8);
+    else        return code - 3;
+}
+
+static inline int asv2_get_level(GetBitContext *gb){
+    int code= get_vlc2(gb, asv2_level_vlc.table, ASV2_LEVEL_VLC_BITS, 1);
+
+    if(code==31) return (int8_t)asv2_get_bits(gb, 8);
+    else         return code - 31;
+}
+
+static inline int asv1_decode_block(ASV1Context *a, DCTELEM block[64]){
+    int i;
+
+    block[0]= 8*get_bits(&a->gb, 8);
+
+    for(i=0; i<11; i++){
+        const int ccp= get_vlc2(&a->gb, ccp_vlc.table, VLC_BITS, 1);
+
+        if(ccp){
+            if(ccp == 16) break;
+            if(ccp < 0 || i>=10){
+                av_log(a->avctx, AV_LOG_ERROR, "coded coeff pattern damaged\n");
+                return -1;
+            }
+
+            if(ccp&8) block[a->scantable.permutated[4*i+0]]= (asv1_get_level(&a->gb) * a->intra_matrix[4*i+0])>>4;
+            if(ccp&4) block[a->scantable.permutated[4*i+1]]= (asv1_get_level(&a->gb) * a->intra_matrix[4*i+1])>>4;
+            if(ccp&2) block[a->scantable.permutated[4*i+2]]= (asv1_get_level(&a->gb) * a->intra_matrix[4*i+2])>>4;
+            if(ccp&1) block[a->scantable.permutated[4*i+3]]= (asv1_get_level(&a->gb) * a->intra_matrix[4*i+3])>>4;
+        }
+    }
+
+    return 0;
+}
+
+static inline int asv2_decode_block(ASV1Context *a, DCTELEM block[64]){
+    int i, count, ccp;
+
+    count= asv2_get_bits(&a->gb, 4);
+
+    block[0]= 8*asv2_get_bits(&a->gb, 8);
+
+    ccp= get_vlc2(&a->gb, dc_ccp_vlc.table, VLC_BITS, 1);
+    if(ccp){
+        if(ccp&4) block[a->scantable.permutated[1]]= (asv2_get_level(&a->gb) * a->intra_matrix[1])>>4;
+        if(ccp&2) block[a->scantable.permutated[2]]= (asv2_get_level(&a->gb) * a->intra_matrix[2])>>4;
+        if(ccp&1) block[a->scantable.permutated[3]]= (asv2_get_level(&a->gb) * a->intra_matrix[3])>>4;
+    }
+
+    for(i=1; i<count+1; i++){
+        const int ccp= get_vlc2(&a->gb, ac_ccp_vlc.table, VLC_BITS, 1);
+
+        if(ccp){
+            if(ccp&8) block[a->scantable.permutated[4*i+0]]= (asv2_get_level(&a->gb) * a->intra_matrix[4*i+0])>>4;
+            if(ccp&4) block[a->scantable.permutated[4*i+1]]= (asv2_get_level(&a->gb) * a->intra_matrix[4*i+1])>>4;
+            if(ccp&2) block[a->scantable.permutated[4*i+2]]= (asv2_get_level(&a->gb) * a->intra_matrix[4*i+2])>>4;
+            if(ccp&1) block[a->scantable.permutated[4*i+3]]= (asv2_get_level(&a->gb) * a->intra_matrix[4*i+3])>>4;
+        }
+    }
+
+    return 0;
+}
+
+static inline int decode_mb(ASV1Context *a, DCTELEM block[6][64]){
+    int i;
+
+    a->dsp.clear_blocks(block[0]);
+
+    if(a->avctx->codec_id == AV_CODEC_ID_ASV1){
+        for(i=0; i<6; i++){
+            if( asv1_decode_block(a, block[i]) < 0)
+                return -1;
+        }
+    }else{
+        for(i=0; i<6; i++){
+            if( asv2_decode_block(a, block[i]) < 0)
+                return -1;
+        }
+    }
+    return 0;
+}
+
+static inline void idct_put(ASV1Context *a, int mb_x, int mb_y){
+    DCTELEM (*block)[64]= a->block;
+    int linesize= a->picture.linesize[0];
+
+    uint8_t *dest_y  = a->picture.data[0] + (mb_y * 16* linesize              ) + mb_x * 16;
+    uint8_t *dest_cb = a->picture.data[1] + (mb_y * 8 * a->picture.linesize[1]) + mb_x * 8;
+    uint8_t *dest_cr = a->picture.data[2] + (mb_y * 8 * a->picture.linesize[2]) + mb_x * 8;
+
+    a->dsp.idct_put(dest_y                 , linesize, block[0]);
+    a->dsp.idct_put(dest_y              + 8, linesize, block[1]);
+    a->dsp.idct_put(dest_y + 8*linesize    , linesize, block[2]);
+    a->dsp.idct_put(dest_y + 8*linesize + 8, linesize, block[3]);
+
+    if(!(a->avctx->flags&CODEC_FLAG_GRAY)){
+        a->dsp.idct_put(dest_cb, a->picture.linesize[1], block[4]);
+        a->dsp.idct_put(dest_cr, a->picture.linesize[2], block[5]);
+    }
+}
+
+static int decode_frame(AVCodecContext *avctx,
+                        void *data, int *data_size,
+                        AVPacket *avpkt)
+{
+    const uint8_t *buf = avpkt->data;
+    int buf_size = avpkt->size;
+    ASV1Context * const a = avctx->priv_data;
+    AVFrame *picture = data;
+    AVFrame * const p= &a->picture;
+    int mb_x, mb_y;
+
+    if(p->data[0])
+        avctx->release_buffer(avctx, p);
+
+    p->reference= 0;
+    if(avctx->get_buffer(avctx, p) < 0){
+        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+        return -1;
+    }
+    p->pict_type= AV_PICTURE_TYPE_I;
+    p->key_frame= 1;
+
+    av_fast_padded_malloc(&a->bitstream_buffer, &a->bitstream_buffer_size,
+                          buf_size);
+    if (!a->bitstream_buffer)
+        return AVERROR(ENOMEM);
+
+    if(avctx->codec_id == AV_CODEC_ID_ASV1)
+        a->dsp.bswap_buf((uint32_t*)a->bitstream_buffer, (const uint32_t*)buf, buf_size/4);
+    else{
+        int i;
+        for(i=0; i<buf_size; i++)
+            a->bitstream_buffer[i]= ff_reverse[ buf[i] ];
+    }
+
+    init_get_bits(&a->gb, a->bitstream_buffer, buf_size*8);
+
+    for(mb_y=0; mb_y<a->mb_height2; mb_y++){
+        for(mb_x=0; mb_x<a->mb_width2; mb_x++){
+            if( decode_mb(a, a->block) <0)
+                return -1;
+
+            idct_put(a, mb_x, mb_y);
+        }
+    }
+
+    if(a->mb_width2 != a->mb_width){
+        mb_x= a->mb_width2;
+        for(mb_y=0; mb_y<a->mb_height2; mb_y++){
+            if( decode_mb(a, a->block) <0)
+                return -1;
+
+            idct_put(a, mb_x, mb_y);
+        }
+    }
+
+    if(a->mb_height2 != a->mb_height){
+        mb_y= a->mb_height2;
+        for(mb_x=0; mb_x<a->mb_width; mb_x++){
+            if( decode_mb(a, a->block) <0)
+                return -1;
+
+            idct_put(a, mb_x, mb_y);
+        }
+    }
+
+    *picture   = a->picture;
+    *data_size = sizeof(AVPicture);
+
+    emms_c();
+
+    return (get_bits_count(&a->gb)+31)/32*4;
+}
+
+static av_cold int decode_init(AVCodecContext *avctx){
+    ASV1Context * const a = avctx->priv_data;
+    AVFrame *p= &a->picture;
+    int i;
+    const int scale= avctx->codec_id == AV_CODEC_ID_ASV1 ? 1 : 2;
+
+    ff_asv_common_init(avctx);
+    init_vlcs(a);
+    ff_init_scantable(a->dsp.idct_permutation, &a->scantable, ff_asv_scantab);
+    avctx->pix_fmt= AV_PIX_FMT_YUV420P;
+
+    if(avctx->extradata_size < 1 || (a->inv_qscale= avctx->extradata[0]) == 0){
+        av_log(avctx, AV_LOG_ERROR, "illegal qscale 0\n");
+        if(avctx->codec_id == AV_CODEC_ID_ASV1)
+            a->inv_qscale= 6;
+        else
+            a->inv_qscale= 10;
+    }
+
+    for(i=0; i<64; i++){
+        int index = ff_asv_scantab[i];
+
+        a->intra_matrix[i]= 64*scale*ff_mpeg1_default_intra_matrix[index] / a->inv_qscale;
+    }
+
+    p->qstride= a->mb_width;
+    p->qscale_table= av_malloc( p->qstride * a->mb_height);
+    p->quality= (32*scale + a->inv_qscale/2)/a->inv_qscale;
+    memset(p->qscale_table, p->quality, p->qstride*a->mb_height);
+
+    return 0;
+}
+
+static av_cold int decode_end(AVCodecContext *avctx){
+    ASV1Context * const a = avctx->priv_data;
+
+    av_freep(&a->bitstream_buffer);
+    av_freep(&a->picture.qscale_table);
+    a->bitstream_buffer_size=0;
+
+    if(a->picture.data[0])
+        avctx->release_buffer(avctx, &a->picture);
+
+    return 0;
+}
+
+#if CONFIG_ASV1_DECODER
+AVCodec ff_asv1_decoder = {
+    .name           = "asv1",
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = AV_CODEC_ID_ASV1,
+    .priv_data_size = sizeof(ASV1Context),
+    .init           = decode_init,
+    .close          = decode_end,
+    .decode         = decode_frame,
+    .capabilities   = CODEC_CAP_DR1,
+    .long_name      = NULL_IF_CONFIG_SMALL("ASUS V1"),
+};
+#endif
+
+#if CONFIG_ASV2_DECODER
+AVCodec ff_asv2_decoder = {
+    .name           = "asv2",
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = AV_CODEC_ID_ASV2,
+    .priv_data_size = sizeof(ASV1Context),
+    .init           = decode_init,
+    .close          = decode_end,
+    .decode         = decode_frame,
+    .capabilities   = CODEC_CAP_DR1,
+    .long_name      = NULL_IF_CONFIG_SMALL("ASUS V2"),
+};
+#endif
+
diff --git a/libavcodec/asvenc.c b/libavcodec/asvenc.c
new file mode 100644
index 0000000..259cd68
--- /dev/null
+++ b/libavcodec/asvenc.c
@@ -0,0 +1,286 @@
+/*
+ * 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
+ */
+
+/**
+ * @file
+ * ASUS V1/V2 encoder.
+ */
+
+#include "libavutil/attributes.h"
+#include "libavutil/mem.h"
+
+#include "asv.h"
+#include "avcodec.h"
+#include "internal.h"
+#include "mathops.h"
+#include "mpeg12data.h"
+
+static inline void asv2_put_bits(PutBitContext *pb, int n, int v){
+    put_bits(pb, n, ff_reverse[ v << (8-n) ]);
+}
+
+static inline void asv1_put_level(PutBitContext *pb, int level){
+    unsigned int index= level + 3;
+
+    if(index <= 6) put_bits(pb, ff_asv_level_tab[index][1], ff_asv_level_tab[index][0]);
+    else{
+        put_bits(pb, ff_asv_level_tab[3][1], ff_asv_level_tab[3][0]);
+        put_sbits(pb, 8, level);
+    }
+}
+
+static inline void asv2_put_level(PutBitContext *pb, int level){
+    unsigned int index= level + 31;
+
+    if(index <= 62) put_bits(pb, ff_asv2_level_tab[index][1], ff_asv2_level_tab[index][0]);
+    else{
+        put_bits(pb, ff_asv2_level_tab[31][1], ff_asv2_level_tab[31][0]);
+        asv2_put_bits(pb, 8, level&0xFF);
+    }
+}
+
+static inline void asv1_encode_block(ASV1Context *a, DCTELEM block[64]){
+    int i;
+    int nc_count=0;
+
+    put_bits(&a->pb, 8, (block[0] + 32)>>6);
+    block[0]= 0;
+
+    for(i=0; i<10; i++){
+        const int index = ff_asv_scantab[4*i];
+        int ccp=0;
+
+        if( (block[index + 0] = (block[index + 0]*a->q_intra_matrix[index + 0] + (1<<15))>>16) ) ccp |= 8;
+        if( (block[index + 8] = (block[index + 8]*a->q_intra_matrix[index + 8] + (1<<15))>>16) ) ccp |= 4;
+        if( (block[index + 1] = (block[index + 1]*a->q_intra_matrix[index + 1] + (1<<15))>>16) ) ccp |= 2;
+        if( (block[index + 9] = (block[index + 9]*a->q_intra_matrix[index + 9] + (1<<15))>>16) ) ccp |= 1;
+
+        if(ccp){
+            for(;nc_count; nc_count--)
+                put_bits(&a->pb, ff_asv_ccp_tab[0][1], ff_asv_ccp_tab[0][0]);
+
+            put_bits(&a->pb, ff_asv_ccp_tab[ccp][1], ff_asv_ccp_tab[ccp][0]);
+
+            if(ccp&8) asv1_put_level(&a->pb, block[index + 0]);
+            if(ccp&4) asv1_put_level(&a->pb, block[index + 8]);
+            if(ccp&2) asv1_put_level(&a->pb, block[index + 1]);
+            if(ccp&1) asv1_put_level(&a->pb, block[index + 9]);
+        }else{
+            nc_count++;
+        }
+    }
+    put_bits(&a->pb, ff_asv_ccp_tab[16][1], ff_asv_ccp_tab[16][0]);
+}
+
+static inline void asv2_encode_block(ASV1Context *a, DCTELEM block[64]){
+    int i;
+    int count=0;
+
+    for(count=63; count>3; count--){
+        const int index = ff_asv_scantab[count];
+
+        if( (block[index]*a->q_intra_matrix[index] + (1<<15))>>16 )
+            break;
+    }
+
+    count >>= 2;
+
+    asv2_put_bits(&a->pb, 4, count);
+    asv2_put_bits(&a->pb, 8, (block[0] + 32)>>6);
+    block[0]= 0;
+
+    for(i=0; i<=count; i++){
+        const int index = ff_asv_scantab[4*i];
+        int ccp=0;
+
+        if( (block[index + 0] = (block[index + 0]*a->q_intra_matrix[index + 0] + (1<<15))>>16) ) ccp |= 8;
+        if( (block[index + 8] = (block[index + 8]*a->q_intra_matrix[index + 8] + (1<<15))>>16) ) ccp |= 4;
+        if( (block[index + 1] = (block[index + 1]*a->q_intra_matrix[index + 1] + (1<<15))>>16) ) ccp |= 2;
+        if( (block[index + 9] = (block[index + 9]*a->q_intra_matrix[index + 9] + (1<<15))>>16) ) ccp |= 1;
+
+        av_assert2(i || ccp<8);
+        if(i) put_bits(&a->pb, ff_asv_ac_ccp_tab[ccp][1], ff_asv_ac_ccp_tab[ccp][0]);
+        else  put_bits(&a->pb, ff_asv_dc_ccp_tab[ccp][1], ff_asv_dc_ccp_tab[ccp][0]);
+
+        if(ccp){
+            if(ccp&8) asv2_put_level(&a->pb, block[index + 0]);
+            if(ccp&4) asv2_put_level(&a->pb, block[index + 8]);
+            if(ccp&2) asv2_put_level(&a->pb, block[index + 1]);
+            if(ccp&1) asv2_put_level(&a->pb, block[index + 9]);
+        }
+    }
+}
+
+#define MAX_MB_SIZE (30*16*16*3/2/8)
+
+static inline int encode_mb(ASV1Context *a, DCTELEM block[6][64]){
+    int i;
+
+    if (a->pb.buf_end - a->pb.buf - (put_bits_count(&a->pb)>>3) < MAX_MB_SIZE) {
+        av_log(a->avctx, AV_LOG_ERROR, "encoded frame too large\n");
+        return -1;
+    }
+
+    if(a->avctx->codec_id == AV_CODEC_ID_ASV1){
+        for(i=0; i<6; i++)
+            asv1_encode_block(a, block[i]);
+    }else{
+        for(i=0; i<6; i++)
+            asv2_encode_block(a, block[i]);
+    }
+    return 0;
+}
+
+static inline void dct_get(ASV1Context *a, int mb_x, int mb_y){
+    DCTELEM (*block)[64]= a->block;
+    int linesize= a->picture.linesize[0];
+    int i;
+
+    uint8_t *ptr_y  = a->picture.data[0] + (mb_y * 16* linesize              ) + mb_x * 16;
+    uint8_t *ptr_cb = a->picture.data[1] + (mb_y * 8 * a->picture.linesize[1]) + mb_x * 8;
+    uint8_t *ptr_cr = a->picture.data[2] + (mb_y * 8 * a->picture.linesize[2]) + mb_x * 8;
+
+    a->dsp.get_pixels(block[0], ptr_y                 , linesize);
+    a->dsp.get_pixels(block[1], ptr_y              + 8, linesize);
+    a->dsp.get_pixels(block[2], ptr_y + 8*linesize    , linesize);
+    a->dsp.get_pixels(block[3], ptr_y + 8*linesize + 8, linesize);
+    for(i=0; i<4; i++)
+        a->dsp.fdct(block[i]);
+
+    if(!(a->avctx->flags&CODEC_FLAG_GRAY)){
+        a->dsp.get_pixels(block[4], ptr_cb, a->picture.linesize[1]);
+        a->dsp.get_pixels(block[5], ptr_cr, a->picture.linesize[2]);
+        for(i=4; i<6; i++)
+            a->dsp.fdct(block[i]);
+    }
+}
+
+static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
+                        const AVFrame *pict, int *got_packet)
+{
+    ASV1Context * const a = avctx->priv_data;
+    AVFrame * const p= &a->picture;
+    int size, ret;
+    int mb_x, mb_y;
+
+    if ((ret = ff_alloc_packet2(avctx, pkt, a->mb_height*a->mb_width*MAX_MB_SIZE +
+                                  FF_MIN_BUFFER_SIZE)) < 0)
+        return ret;
+
+    init_put_bits(&a->pb, pkt->data, pkt->size);
+
+    *p = *pict;
+    p->pict_type= AV_PICTURE_TYPE_I;
+    p->key_frame= 1;
+
+    for(mb_y=0; mb_y<a->mb_height2; mb_y++){
+        for(mb_x=0; mb_x<a->mb_width2; mb_x++){
+            dct_get(a, mb_x, mb_y);
+            encode_mb(a, a->block);
+        }
+    }
+
+    if(a->mb_width2 != a->mb_width){
+        mb_x= a->mb_width2;
+        for(mb_y=0; mb_y<a->mb_height2; mb_y++){
+            dct_get(a, mb_x, mb_y);
+            encode_mb(a, a->block);
+        }
+    }
+
+    if(a->mb_height2 != a->mb_height){
+        mb_y= a->mb_height2;
+        for(mb_x=0; mb_x<a->mb_width; mb_x++){
+            dct_get(a, mb_x, mb_y);
+            encode_mb(a, a->block);
+        }
+    }
+    emms_c();
+
+    avpriv_align_put_bits(&a->pb);
+    while(put_bits_count(&a->pb)&31)
+        put_bits(&a->pb, 8, 0);
+
+    size= put_bits_count(&a->pb)/32;
+
+    if(avctx->codec_id == AV_CODEC_ID_ASV1)
+        a->dsp.bswap_buf((uint32_t*)pkt->data, (uint32_t*)pkt->data, size);
+    else{
+        int i;
+        for(i=0; i<4*size; i++)
+            pkt->data[i] = ff_reverse[pkt->data[i]];
+    }
+
+    pkt->size   = size*4;
+    pkt->flags |= AV_PKT_FLAG_KEY;
+    *got_packet = 1;
+
+    return 0;
+}
+
+static av_cold int encode_init(AVCodecContext *avctx){
+    ASV1Context * const a = avctx->priv_data;
+    int i;
+    const int scale= avctx->codec_id == AV_CODEC_ID_ASV1 ? 1 : 2;
+
+    ff_asv_common_init(avctx);
+
+    if(avctx->global_quality == 0) avctx->global_quality= 4*FF_QUALITY_SCALE;
+
+    a->inv_qscale= (32*scale*FF_QUALITY_SCALE +  avctx->global_quality/2) / avctx->global_quality;
+
+    avctx->extradata= av_mallocz(8);
+    avctx->extradata_size=8;
+    ((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];
+        a->q_intra_matrix[i]= ((a->inv_qscale<<16) + q/2) / q;
+    }
+
+    return 0;
+}
+
+#if CONFIG_ASV1_ENCODER
+AVCodec ff_asv1_encoder = {
+    .name           = "asv1",
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = AV_CODEC_ID_ASV1,
+    .priv_data_size = sizeof(ASV1Context),
+    .init           = encode_init,
+    .encode2        = encode_frame,
+    .pix_fmts       = (const enum PixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
+    .long_name      = NULL_IF_CONFIG_SMALL("ASUS V1"),
+};
+#endif
+
+#if CONFIG_ASV2_ENCODER
+AVCodec ff_asv2_encoder = {
+    .name           = "asv2",
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = AV_CODEC_ID_ASV2,
+    .priv_data_size = sizeof(ASV1Context),
+    .init           = encode_init,
+    .encode2        = encode_frame,
+    .pix_fmts       = (const enum PixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
+    .long_name      = NULL_IF_CONFIG_SMALL("ASUS V2"),
+};
+#endif
diff --git a/libavcodec/atrac1.c b/libavcodec/atrac1.c
index 669035d..1ba5593 100644
--- a/libavcodec/atrac1.c
+++ b/libavcodec/atrac1.c
@@ -36,7 +36,6 @@
 #include "get_bits.h"
 #include "dsputil.h"
 #include "fft.h"
-#include "fmtconvert.h"
 #include "sinewin.h"
 
 #include "atrac.h"
@@ -80,11 +79,8 @@
     DECLARE_ALIGNED(32, float,  mid)[256];
     DECLARE_ALIGNED(32, float, high)[512];
     float*              bands[3];
-    float              *out_samples[AT1_MAX_CHANNELS];
     FFTContext          mdct_ctx[3];
-    int                 channels;
     DSPContext          dsp;
-    FmtConvertContext   fmt_conv;
 } AT1Ctx;
 
 /** size of the transform in samples in the long mode for each QMF band */
@@ -281,10 +277,9 @@
     AT1Ctx *q          = avctx->priv_data;
     int ch, ret;
     GetBitContext gb;
-    float *samples;
 
 
-    if (buf_size < 212 * q->channels) {
+    if (buf_size < 212 * avctx->channels) {
         av_log(avctx, AV_LOG_ERROR, "Not enough data to decode!\n");
         return AVERROR_INVALIDDATA;
     }
@@ -295,9 +290,8 @@
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         return ret;
     }
-    samples = (float *)q->frame.data[0];
 
-    for (ch = 0; ch < q->channels; ch++) {
+    for (ch = 0; ch < avctx->channels; ch++) {
         AT1SUCtx* su = &q->SUs[ch];
 
         init_get_bits(&gb, &buf[212 * ch], 212 * 8);
@@ -314,13 +308,7 @@
         ret = at1_imdct_block(su, q);
         if (ret < 0)
             return ret;
-        at1_subband_synthesis(q, su, q->channels == 1 ? samples : q->out_samples[ch]);
-    }
-
-    /* interleave */
-    if (q->channels == 2) {
-        q->fmt_conv.float_interleave(samples, (const float **)q->out_samples,
-                                     AT1_SU_SAMPLES, 2);
+        at1_subband_synthesis(q, su, (float *)q->frame.extended_data[ch]);
     }
 
     *got_frame_ptr   = 1;
@@ -334,8 +322,6 @@
 {
     AT1Ctx *q = avctx->priv_data;
 
-    av_freep(&q->out_samples[0]);
-
     ff_mdct_end(&q->mdct_ctx[0]);
     ff_mdct_end(&q->mdct_ctx[1]);
     ff_mdct_end(&q->mdct_ctx[2]);
@@ -349,22 +335,17 @@
     AT1Ctx *q = avctx->priv_data;
     int ret;
 
-    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
+    avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
 
     if (avctx->channels < 1 || avctx->channels > AT1_MAX_CHANNELS) {
         av_log(avctx, AV_LOG_ERROR, "Unsupported number of channels: %d\n",
                avctx->channels);
         return AVERROR(EINVAL);
     }
-    q->channels = avctx->channels;
 
-    if (avctx->channels == 2) {
-        q->out_samples[0] = av_malloc(2 * AT1_SU_SAMPLES * sizeof(*q->out_samples[0]));
-        q->out_samples[1] = q->out_samples[0] + AT1_SU_SAMPLES;
-        if (!q->out_samples[0]) {
-            av_freep(&q->out_samples[0]);
-            return AVERROR(ENOMEM);
-        }
+    if (avctx->block_align <= 0) {
+        av_log_ask_for_sample(avctx, "unsupported block align\n");
+        return AVERROR_PATCHWELCOME;
     }
 
     /* Init the mdct transforms */
@@ -381,7 +362,6 @@
     ff_atrac_generate_tables();
 
     ff_dsputil_init(&q->dsp, avctx);
-    ff_fmt_convert_init(&q->fmt_conv, avctx);
 
     q->bands[0] = q->low;
     q->bands[1] = q->mid;
@@ -410,4 +390,6 @@
     .decode         = atrac1_decode_frame,
     .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("Atrac 1 (Adaptive TRansform Acoustic Coding)"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
+                                                      AV_SAMPLE_FMT_NONE },
 };
diff --git a/libavcodec/atrac3.c b/libavcodec/atrac3.c
index 7d076be..052bef0 100644
--- a/libavcodec/atrac3.c
+++ b/libavcodec/atrac3.c
@@ -39,10 +39,10 @@
 #include "libavutil/float_dsp.h"
 #include "libavutil/libm.h"
 #include "avcodec.h"
-#include "get_bits.h"
 #include "bytestream.h"
 #include "fft.h"
 #include "fmtconvert.h"
+#include "get_bits.h"
 
 #include "atrac.h"
 #include "atrac3data.h"
@@ -53,143 +53,121 @@
 #define SAMPLES_PER_FRAME 1024
 #define MDCT_SIZE          512
 
-/* These structures are needed to store the parsed gain control data. */
-typedef struct {
-    int   num_gain_data;
-    int   levcode[8];
-    int   loccode[8];
-} gain_info;
+typedef struct GainInfo {
+    int num_gain_data;
+    int lev_code[8];
+    int loc_code[8];
+} GainInfo;
 
-typedef struct {
-    gain_info   gBlock[4];
-} gain_block;
+typedef struct GainBlock {
+    GainInfo g_block[4];
+} GainBlock;
 
-typedef struct {
-    int     pos;
-    int     numCoefs;
-    float   coef[8];
-} tonal_component;
+typedef struct TonalComponent {
+    int pos;
+    int num_coefs;
+    float coef[8];
+} TonalComponent;
 
-typedef struct {
-    int               bandsCoded;
-    int               numComponents;
-    tonal_component   components[64];
-    float             prevFrame[SAMPLES_PER_FRAME];
-    int               gcBlkSwitch;
-    gain_block        gainBlock[2];
+typedef struct ChannelUnit {
+    int            bands_coded;
+    int            num_components;
+    float          prev_frame[SAMPLES_PER_FRAME];
+    int            gc_blk_switch;
+    TonalComponent components[64];
+    GainBlock      gain_block[2];
 
     DECLARE_ALIGNED(32, float, spectrum)[SAMPLES_PER_FRAME];
-    DECLARE_ALIGNED(32, float, IMDCT_buf)[SAMPLES_PER_FRAME];
+    DECLARE_ALIGNED(32, float, imdct_buf)[SAMPLES_PER_FRAME];
 
-    float             delayBuf1[46]; ///<qmf delay buffers
-    float             delayBuf2[46];
-    float             delayBuf3[46];
-} channel_unit;
+    float          delay_buf1[46]; ///<qmf delay buffers
+    float          delay_buf2[46];
+    float          delay_buf3[46];
+} ChannelUnit;
 
-typedef struct {
-    AVFrame             frame;
-    GetBitContext       gb;
+typedef struct ATRAC3Context {
+    AVFrame frame;
+    GetBitContext gb;
     //@{
     /** stream data */
-    int                 channels;
-    int                 codingMode;
-    int                 bit_rate;
-    int                 sample_rate;
-    int                 samples_per_channel;
-    int                 samples_per_frame;
+    int coding_mode;
 
-    int                 bits_per_frame;
-    int                 bytes_per_frame;
-    int                 pBs;
-    channel_unit*       pUnits;
+    ChannelUnit *units;
     //@}
     //@{
     /** joint-stereo related variables */
-    int                 matrix_coeff_index_prev[4];
-    int                 matrix_coeff_index_now[4];
-    int                 matrix_coeff_index_next[4];
-    int                 weighting_delay[6];
+    int matrix_coeff_index_prev[4];
+    int matrix_coeff_index_now[4];
+    int matrix_coeff_index_next[4];
+    int weighting_delay[6];
     //@}
     //@{
     /** data buffers */
-    float              *outSamples[2];
-    uint8_t*            decoded_bytes_buffer;
-    float               tempBuf[1070];
+    uint8_t *decoded_bytes_buffer;
+    float temp_buf[1070];
     //@}
     //@{
     /** extradata */
-    int                 atrac3version;
-    int                 delay;
-    int                 scrambled_stream;
-    int                 frame_factor;
+    int scrambled_stream;
     //@}
 
-    FFTContext          mdct_ctx;
-    FmtConvertContext   fmt_conv;
-    AVFloatDSPContext   fdsp;
+    FFTContext mdct_ctx;
+    FmtConvertContext fmt_conv;
+    AVFloatDSPContext fdsp;
 } ATRAC3Context;
 
 static DECLARE_ALIGNED(32, float, mdct_window)[MDCT_SIZE];
-static VLC              spectral_coeff_tab[7];
-static float            gain_tab1[16];
-static float            gain_tab2[31];
+static VLC_TYPE atrac3_vlc_table[4096][2];
+static VLC   spectral_coeff_tab[7];
+static float gain_tab1[16];
+static float gain_tab2[31];
 
 
 /**
- * Regular 512 points IMDCT without overlapping, with the exception of the swapping of odd bands
- * caused by the reverse spectra of the QMF.
+ * Regular 512 points IMDCT without overlapping, with the exception of the
+ * swapping of odd bands caused by the reverse spectra of the QMF.
  *
- * @param pInput    float input
- * @param pOutput   float output
  * @param odd_band  1 if the band is an odd band
  */
-
-static void IMLT(ATRAC3Context *q, float *pInput, float *pOutput, int odd_band)
+static void imlt(ATRAC3Context *q, float *input, float *output, int odd_band)
 {
-    int     i;
+    int i;
 
     if (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 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.
-        */
-
-        for (i=0; i<128; i++)
-            FFSWAP(float, pInput[i], pInput[255-i]);
+         * 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 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.
+         */
+        for (i = 0; i < 128; i++)
+            FFSWAP(float, input[i], input[255 - i]);
     }
 
-    q->mdct_ctx.imdct_calc(&q->mdct_ctx,pOutput,pInput);
+    q->mdct_ctx.imdct_calc(&q->mdct_ctx, output, input);
 
     /* Perform windowing on the output. */
-    q->fdsp.vector_fmul(pOutput, pOutput, mdct_window, MDCT_SIZE);
-
+    q->fdsp.vector_fmul(output, output, mdct_window, MDCT_SIZE);
 }
 
-
-/**
- * Atrac 3 indata descrambling, only used for data coming from the rm container
- *
- * @param inbuffer  pointer to 8 bit array of indata
- * @param out       pointer to 8 bit array of outdata
- * @param bytes     amount of bytes
+/*
+ * indata descrambling, only used for data coming from the rm container
  */
-
-static int decode_bytes(const uint8_t* inbuffer, uint8_t* out, int bytes){
+static int decode_bytes(const uint8_t *input, uint8_t *out, int bytes)
+{
     int i, off;
     uint32_t c;
-    const uint32_t* buf;
-    uint32_t* obuf = (uint32_t*) out;
+    const uint32_t *buf;
+    uint32_t *output = (uint32_t *)out;
 
-    off = (intptr_t)inbuffer & 3;
-    buf = (const uint32_t*) (inbuffer - off);
-    c = av_be2ne32((0x537F6103 >> (off*8)) | (0x537F6103 << (32-(off*8))));
+    off = (intptr_t)input & 3;
+    buf = (const uint32_t *)(input - off);
+    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];
+    for (i = 0; i < bytes / 4; i++)
+        output[i] = c ^ buf[i];
 
     if (off)
         av_log_ask_for_sample(NULL, "Offset of %d not handled.\n", off);
@@ -197,37 +175,27 @@
     return off;
 }
 
+static av_cold void init_atrac3_window(void)
+{
+    int i, j;
 
-static av_cold int init_atrac3_transforms(ATRAC3Context *q, int is_float) {
-    float enc_window[256];
-    int i;
-
-    /* Generate the mdct window, for details see
+    /* generate the mdct window, for details see
      * http://wiki.multimedia.cx/index.php?title=RealAudio_atrc#Windows */
-    for (i=0 ; i<256; i++)
-        enc_window[i] = (sin(((i + 0.5) / 256.0 - 0.5) * M_PI) + 1.0) * 0.5;
-
-    if (!mdct_window[0])
-        for (i=0 ; i<256; i++) {
-            mdct_window[i] = enc_window[i]/(enc_window[i]*enc_window[i] + enc_window[255-i]*enc_window[255-i]);
-            mdct_window[511-i] = mdct_window[i];
-        }
-
-    /* Initialize the MDCT transform. */
-    return ff_mdct_init(&q->mdct_ctx, 9, 1, is_float ? 1.0 / 32768 : 1.0);
+    for (i = 0, j = 255; i < 128; i++, j--) {
+        float wi = sin(((i + 0.5) / 256.0 - 0.5) * M_PI) + 1.0;
+        float wj = sin(((j + 0.5) / 256.0 - 0.5) * M_PI) + 1.0;
+        float w  = 0.5 * (wi * wi + wj * wj);
+        mdct_window[i] = mdct_window[511 - i] = wi / w;
+        mdct_window[j] = mdct_window[511 - j] = wj / w;
+    }
 }
 
-/**
- * Atrac3 uninit, free all allocated memory
- */
-
 static av_cold int atrac3_decode_close(AVCodecContext *avctx)
 {
     ATRAC3Context *q = avctx->priv_data;
 
-    av_free(q->pUnits);
+    av_free(q->units);
     av_free(q->decoded_bytes_buffer);
-    av_freep(&q->outSamples[0]);
 
     ff_mdct_end(&q->mdct_ctx);
 
@@ -235,60 +203,62 @@
 }
 
 /**
-/ * Mantissa decoding
+ * Mantissa decoding
  *
- * @param gb            the GetBit context
- * @param selector      what table is the output values coded with
- * @param codingFlag    constant length coding or variable length coding
- * @param mantissas     mantissa output table
- * @param numCodes      amount of values to get
+ * @param selector     which table the output values are coded with
+ * @param coding_flag  constant length coding or variable length coding
+ * @param mantissas    mantissa output table
+ * @param num_codes    number of values to get
  */
-
-static void readQuantSpectralCoeffs (GetBitContext *gb, int selector, int codingFlag, int* mantissas, int numCodes)
+static void read_quant_spectral_coeffs(GetBitContext *gb, int selector,
+                                       int coding_flag, int *mantissas,
+                                       int num_codes)
 {
-    int   numBits, cnt, code, huffSymb;
+    int i, code, huff_symb;
 
     if (selector == 1)
-        numCodes /= 2;
+        num_codes /= 2;
 
-    if (codingFlag != 0) {
+    if (coding_flag != 0) {
         /* constant length coding (CLC) */
-        numBits = CLCLengthTab[selector];
+        int num_bits = clc_length_tab[selector];
 
         if (selector > 1) {
-            for (cnt = 0; cnt < numCodes; cnt++) {
-                if (numBits)
-                    code = get_sbits(gb, numBits);
+            for (i = 0; i < num_codes; i++) {
+                if (num_bits)
+                    code = get_sbits(gb, num_bits);
                 else
                     code = 0;
-                mantissas[cnt] = code;
+                mantissas[i] = code;
             }
         } else {
-            for (cnt = 0; cnt < numCodes; cnt++) {
-                if (numBits)
-                    code = get_bits(gb, numBits); //numBits is always 4 in this case
+            for (i = 0; i < num_codes; i++) {
+                if (num_bits)
+                    code = get_bits(gb, num_bits); // num_bits is always 4 in this case
                 else
                     code = 0;
-                mantissas[cnt*2] = seTab_0[code >> 2];
-                mantissas[cnt*2+1] = seTab_0[code & 3];
+                mantissas[i * 2    ] = mantissa_clc_tab[code >> 2];
+                mantissas[i * 2 + 1] = mantissa_clc_tab[code &  3];
             }
         }
     } else {
         /* variable length coding (VLC) */
         if (selector != 1) {
-            for (cnt = 0; cnt < numCodes; cnt++) {
-                huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3);
-                huffSymb += 1;
-                code = huffSymb >> 1;
-                if (huffSymb & 1)
+            for (i = 0; i < num_codes; i++) {
+                huff_symb = get_vlc2(gb, spectral_coeff_tab[selector-1].table,
+                                     spectral_coeff_tab[selector-1].bits, 3);
+                huff_symb += 1;
+                code = huff_symb >> 1;
+                if (huff_symb & 1)
                     code = -code;
-                mantissas[cnt] = code;
+                mantissas[i] = code;
             }
         } else {
-            for (cnt = 0; cnt < numCodes; cnt++) {
-                huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3);
-                mantissas[cnt*2] = decTable1[huffSymb*2];
-                mantissas[cnt*2+1] = decTable1[huffSymb*2+1];
+            for (i = 0; i < num_codes; i++) {
+                huff_symb = get_vlc2(gb, spectral_coeff_tab[selector - 1].table,
+                                     spectral_coeff_tab[selector - 1].bits, 3);
+                mantissas[i * 2    ] = mantissa_vlc_tab[huff_symb * 2    ];
+                mantissas[i * 2 + 1] = mantissa_vlc_tab[huff_symb * 2 + 1];
             }
         }
     }
@@ -297,129 +267,135 @@
 /**
  * Restore the quantized band spectrum coefficients
  *
- * @param gb            the GetBit context
- * @param pOut          decoded band spectrum
- * @return outSubbands   subband counter, fix for broken specification/files
+ * @return subband count, fix for broken specification/files
  */
-
-static int decodeSpectrum (GetBitContext *gb, float *pOut)
+static int decode_spectrum(GetBitContext *gb, float *output)
 {
-    int   numSubbands, codingMode, cnt, first, last, subbWidth, *pIn;
-    int   subband_vlc_index[32], SF_idxs[32];
-    int   mantissas[128];
-    float SF;
+    int num_subbands, coding_mode, i, j, first, last, subband_size;
+    int subband_vlc_index[32], sf_index[32];
+    int mantissas[128];
+    float scale_factor;
 
-    numSubbands = get_bits(gb, 5); // number of coded subbands
-    codingMode = get_bits1(gb); // coding Mode: 0 - VLC/ 1-CLC
+    num_subbands = get_bits(gb, 5);  // number of coded subbands
+    coding_mode  = get_bits1(gb);    // coding Mode: 0 - VLC/ 1-CLC
 
-    /* Get the VLC selector table for the subbands, 0 means not coded. */
-    for (cnt = 0; cnt <= numSubbands; cnt++)
-        subband_vlc_index[cnt] = get_bits(gb, 3);
+    /* get the VLC selector table for the subbands, 0 means not coded */
+    for (i = 0; i <= num_subbands; i++)
+        subband_vlc_index[i] = get_bits(gb, 3);
 
-    /* Read the scale factor indexes from the stream. */
-    for (cnt = 0; cnt <= numSubbands; cnt++) {
-        if (subband_vlc_index[cnt] != 0)
-            SF_idxs[cnt] = get_bits(gb, 6);
+    /* read the scale factor indexes from the stream */
+    for (i = 0; i <= num_subbands; i++) {
+        if (subband_vlc_index[i] != 0)
+            sf_index[i] = get_bits(gb, 6);
     }
 
-    for (cnt = 0; cnt <= numSubbands; cnt++) {
-        first = subbandTab[cnt];
-        last = subbandTab[cnt+1];
+    for (i = 0; i <= num_subbands; i++) {
+        first = subband_tab[i    ];
+        last  = subband_tab[i + 1];
 
-        subbWidth = last - first;
+        subband_size = last - first;
 
-        if (subband_vlc_index[cnt] != 0) {
-            /* Decode spectral coefficients for this subband. */
+        if (subband_vlc_index[i] != 0) {
+            /* decode spectral coefficients for this subband */
             /* TODO: This can be done faster is several blocks share the
              * same VLC selector (subband_vlc_index) */
-            readQuantSpectralCoeffs (gb, subband_vlc_index[cnt], codingMode, mantissas, subbWidth);
+            read_quant_spectral_coeffs(gb, subband_vlc_index[i], coding_mode,
+                                       mantissas, subband_size);
 
-            /* Decode the scale factor for this subband. */
-            SF = ff_atrac_sf_table[SF_idxs[cnt]] * iMaxQuant[subband_vlc_index[cnt]];
+            /* decode the scale factor for this subband */
+            scale_factor = ff_atrac_sf_table[sf_index[i]] *
+                           inv_max_quant[subband_vlc_index[i]];
 
-            /* Inverse quantize the coefficients. */
-            for (pIn=mantissas ; first<last; first++, pIn++)
-                pOut[first] = *pIn * SF;
+            /* inverse quantize the coefficients */
+            for (j = 0; first < last; first++, j++)
+                output[first] = mantissas[j] * scale_factor;
         } else {
-            /* This subband was not coded, so zero the entire subband. */
-            memset(pOut+first, 0, subbWidth*sizeof(float));
+            /* this subband was not coded, so zero the entire subband */
+            memset(output + first, 0, subband_size * sizeof(*output));
         }
     }
 
-    /* Clear the subbands that were not coded. */
-    first = subbandTab[cnt];
-    memset(pOut+first, 0, (SAMPLES_PER_FRAME - first) * sizeof(float));
-    return numSubbands;
+    /* clear the subbands that were not coded */
+    first = subband_tab[i];
+    memset(output + first, 0, (SAMPLES_PER_FRAME - first) * sizeof(*output));
+    return num_subbands;
 }
 
 /**
  * Restore the quantized tonal components
  *
- * @param gb            the GetBit context
- * @param pComponent    tone component
- * @param numBands      amount of coded bands
+ * @param components tonal components
+ * @param num_bands  number of coded bands
  */
-
-static int decodeTonalComponents (GetBitContext *gb, tonal_component *pComponent, int numBands)
+static int decode_tonal_components(GetBitContext *gb,
+                                   TonalComponent *components, int num_bands)
 {
-    int i,j,k,cnt;
-    int   components, coding_mode_selector, coding_mode, coded_values_per_component;
-    int   sfIndx, coded_values, max_coded_values, quant_step_index, coded_components;
-    int   band_flags[4], mantissa[8];
-    float  *pCoef;
-    float  scalefactor;
-    int   component_count = 0;
+    int i, b, c, m;
+    int nb_components, coding_mode_selector, coding_mode;
+    int band_flags[4], mantissa[8];
+    int component_count = 0;
 
-    components = get_bits(gb,5);
+    nb_components = get_bits(gb, 5);
 
     /* no tonal components */
-    if (components == 0)
+    if (nb_components == 0)
         return 0;
 
-    coding_mode_selector = get_bits(gb,2);
+    coding_mode_selector = get_bits(gb, 2);
     if (coding_mode_selector == 2)
         return AVERROR_INVALIDDATA;
 
     coding_mode = coding_mode_selector & 1;
 
-    for (i = 0; i < components; i++) {
-        for (cnt = 0; cnt <= numBands; cnt++)
-            band_flags[cnt] = get_bits1(gb);
+    for (i = 0; i < nb_components; i++) {
+        int coded_values_per_component, quant_step_index;
 
-        coded_values_per_component = get_bits(gb,3);
+        for (b = 0; b <= num_bands; b++)
+            band_flags[b] = get_bits1(gb);
 
-        quant_step_index = get_bits(gb,3);
+        coded_values_per_component = get_bits(gb, 3);
+
+        quant_step_index = get_bits(gb, 3);
         if (quant_step_index <= 1)
             return AVERROR_INVALIDDATA;
 
         if (coding_mode_selector == 3)
             coding_mode = get_bits1(gb);
 
-        for (j = 0; j < (numBands + 1) * 4; j++) {
-            if (band_flags[j >> 2] == 0)
+        for (b = 0; b < (num_bands + 1) * 4; b++) {
+            int coded_components;
+
+            if (band_flags[b >> 2] == 0)
                 continue;
 
-            coded_components = get_bits(gb,3);
+            coded_components = get_bits(gb, 3);
 
-            for (k=0; k<coded_components; k++) {
-                sfIndx = get_bits(gb,6);
+            for (c = 0; c < coded_components; c++) {
+                TonalComponent *cmp = &components[component_count];
+                int sf_index, coded_values, max_coded_values;
+                float scale_factor;
+
+                sf_index = get_bits(gb, 6);
                 if (component_count >= 64)
                     return AVERROR_INVALIDDATA;
-                pComponent[component_count].pos = j * 64 + (get_bits(gb,6));
-                max_coded_values = SAMPLES_PER_FRAME - pComponent[component_count].pos;
-                coded_values = coded_values_per_component + 1;
-                coded_values = FFMIN(max_coded_values,coded_values);
 
-                scalefactor = ff_atrac_sf_table[sfIndx] * iMaxQuant[quant_step_index];
+                cmp->pos = b * 64 + get_bits(gb, 6);
 
-                readQuantSpectralCoeffs(gb, quant_step_index, coding_mode, mantissa, coded_values);
+                max_coded_values = SAMPLES_PER_FRAME - cmp->pos;
+                coded_values     = coded_values_per_component + 1;
+                coded_values     = FFMIN(max_coded_values, coded_values);
 
-                pComponent[component_count].numCoefs = coded_values;
+                scale_factor = ff_atrac_sf_table[sf_index] *
+                               inv_max_quant[quant_step_index];
+
+                read_quant_spectral_coeffs(gb, quant_step_index, coding_mode,
+                                           mantissa, coded_values);
+
+                cmp->num_coefs = coded_values;
 
                 /* inverse quant */
-                pCoef = pComponent[component_count].coef;
-                for (cnt = 0; cnt < coded_values; cnt++)
-                    pCoef[cnt] = mantissa[cnt] * scalefactor;
+                for (m = 0; m < coded_values; m++)
+                    cmp->coef[m] = mantissa[m] * scale_factor;
 
                 component_count++;
             }
@@ -432,36 +408,34 @@
 /**
  * Decode gain parameters for the coded bands
  *
- * @param gb            the GetBit context
- * @param pGb           the gainblock for the current band
- * @param numBands      amount of coded bands
+ * @param block      the gainblock for the current band
+ * @param num_bands  amount of coded bands
  */
-
-static int decodeGainControl (GetBitContext *gb, gain_block *pGb, int numBands)
+static int decode_gain_control(GetBitContext *gb, GainBlock *block,
+                               int num_bands)
 {
-    int   i, cf, numData;
-    int   *pLevel, *pLoc;
+    int i, cf, num_data;
+    int *level, *loc;
 
-    gain_info   *pGain = pGb->gBlock;
+    GainInfo *gain = block->g_block;
 
-    for (i=0 ; i<=numBands; i++)
-    {
-        numData = get_bits(gb,3);
-        pGain[i].num_gain_data = numData;
-        pLevel = pGain[i].levcode;
-        pLoc = pGain[i].loccode;
+    for (i = 0; i <= num_bands; i++) {
+        num_data              = get_bits(gb, 3);
+        gain[i].num_gain_data = num_data;
+        level                 = gain[i].lev_code;
+        loc                   = gain[i].loc_code;
 
-        for (cf = 0; cf < numData; cf++){
-            pLevel[cf]= get_bits(gb,4);
-            pLoc  [cf]= get_bits(gb,5);
-            if(cf && pLoc[cf] <= pLoc[cf-1])
+        for (cf = 0; cf < gain[i].num_gain_data; cf++) {
+            level[cf] = get_bits(gb, 4);
+            loc  [cf] = get_bits(gb, 5);
+            if (cf && loc[cf] <= loc[cf - 1])
                 return AVERROR_INVALIDDATA;
         }
     }
 
     /* Clear the unused blocks. */
-    for (; i<4 ; i++)
-        pGain[i].num_gain_data = 0;
+    for (; i < 4 ; i++)
+        gain[i].num_gain_data = 0;
 
     return 0;
 }
@@ -469,377 +443,366 @@
 /**
  * Apply gain parameters and perform the MDCT overlapping part
  *
- * @param pIn           input float buffer
- * @param pPrev         previous float buffer to perform overlap against
- * @param pOut          output float buffer
- * @param pGain1        current band gain info
- * @param pGain2        next band gain info
+ * @param input   input buffer
+ * @param prev    previous buffer to perform overlap against
+ * @param output  output buffer
+ * @param gain1   current band gain info
+ * @param gain2   next band gain info
  */
-
-static void gainCompensateAndOverlap (float *pIn, float *pPrev, float *pOut, gain_info *pGain1, gain_info *pGain2)
+static void gain_compensate_and_overlap(float *input, float *prev,
+                                        float *output, GainInfo *gain1,
+                                        GainInfo *gain2)
 {
-    /* gain compensation function */
-    float  gain1, gain2, gain_inc;
-    int   cnt, numdata, nsample, startLoc, endLoc;
+    float g1, g2, gain_inc;
+    int i, j, num_data, start_loc, end_loc;
 
 
-    if (pGain2->num_gain_data == 0)
-        gain1 = 1.0;
+    if (gain2->num_gain_data == 0)
+        g1 = 1.0;
     else
-        gain1 = gain_tab1[pGain2->levcode[0]];
+        g1 = gain_tab1[gain2->lev_code[0]];
 
-    if (pGain1->num_gain_data == 0) {
-        for (cnt = 0; cnt < 256; cnt++)
-            pOut[cnt] = pIn[cnt] * gain1 + pPrev[cnt];
+    if (gain1->num_gain_data == 0) {
+        for (i = 0; i < 256; i++)
+            output[i] = input[i] * g1 + prev[i];
     } else {
-        numdata = pGain1->num_gain_data;
-        pGain1->loccode[numdata] = 32;
-        pGain1->levcode[numdata] = 4;
+        num_data = gain1->num_gain_data;
+        gain1->loc_code[num_data] = 32;
+        gain1->lev_code[num_data] = 4;
 
-        nsample = 0; // current sample = 0
+        for (i = 0, j = 0; i < num_data; i++) {
+            start_loc = gain1->loc_code[i] * 8;
+            end_loc   = start_loc + 8;
 
-        for (cnt = 0; cnt < numdata; cnt++) {
-            startLoc = pGain1->loccode[cnt] * 8;
-            endLoc = startLoc + 8;
-
-            gain2 = gain_tab1[pGain1->levcode[cnt]];
-            gain_inc = gain_tab2[(pGain1->levcode[cnt+1] - pGain1->levcode[cnt])+15];
+            g2       = gain_tab1[gain1->lev_code[i]];
+            gain_inc = gain_tab2[gain1->lev_code[i + 1] -
+                                 gain1->lev_code[i    ] + 15];
 
             /* interpolate */
-            for (; nsample < startLoc; nsample++)
-                pOut[nsample] = (pIn[nsample] * gain1 + pPrev[nsample]) * gain2;
+            for (; j < start_loc; j++)
+                output[j] = (input[j] * g1 + prev[j]) * g2;
 
             /* interpolation is done over eight samples */
-            for (; nsample < endLoc; nsample++) {
-                pOut[nsample] = (pIn[nsample] * gain1 + pPrev[nsample]) * gain2;
-                gain2 *= gain_inc;
+            for (; j < end_loc; j++) {
+                output[j] = (input[j] * g1 + prev[j]) * g2;
+                g2 *= gain_inc;
             }
         }
 
-        for (; nsample < 256; nsample++)
-            pOut[nsample] = (pIn[nsample] * gain1) + pPrev[nsample];
+        for (; j < 256; j++)
+            output[j] = input[j] * g1 + prev[j];
     }
 
     /* Delay for the overlapping part. */
-    memcpy(pPrev, &pIn[256], 256*sizeof(float));
+    memcpy(prev, &input[256], 256 * sizeof(*prev));
 }
 
 /**
  * Combine the tonal band spectrum and regular band spectrum
- * Return position of the last tonal coefficient
  *
- * @param pSpectrum     output spectrum buffer
- * @param numComponents amount of tonal components
- * @param pComponent    tonal components for this band
+ * @param spectrum        output spectrum buffer
+ * @param num_components  number of tonal components
+ * @param components      tonal components for this band
+ * @return                position of the last tonal coefficient
  */
-
-static int addTonalComponents (float *pSpectrum, int numComponents, tonal_component *pComponent)
+static int add_tonal_components(float *spectrum, int num_components,
+                                TonalComponent *components)
 {
-    int   cnt, i, lastPos = -1;
-    float   *pIn, *pOut;
+    int i, j, last_pos = -1;
+    float *input, *output;
 
-    for (cnt = 0; cnt < numComponents; cnt++){
-        lastPos = FFMAX(pComponent[cnt].pos + pComponent[cnt].numCoefs, lastPos);
-        pIn = pComponent[cnt].coef;
-        pOut = &(pSpectrum[pComponent[cnt].pos]);
+    for (i = 0; i < num_components; i++) {
+        last_pos = FFMAX(components[i].pos + components[i].num_coefs, last_pos);
+        input    = components[i].coef;
+        output   = &spectrum[components[i].pos];
 
-        for (i=0 ; i<pComponent[cnt].numCoefs ; i++)
-            pOut[i] += pIn[i];
+        for (j = 0; j < components[i].num_coefs; j++)
+            output[i] += input[i];
     }
 
-    return lastPos;
+    return last_pos;
 }
 
+#define INTERPOLATE(old, new, nsample) \
+    ((old) + (nsample) * 0.125 * ((new) - (old)))
 
-#define INTERPOLATE(old,new,nsample) ((old) + (nsample)*0.125*((new)-(old)))
-
-static void reverseMatrixing(float *su1, float *su2, int *pPrevCode, int *pCurrCode)
+static void reverse_matrixing(float *su1, float *su2, int *prev_code,
+                              int *curr_code)
 {
-    int    i, band, nsample, s1, s2;
-    float    c1, c2;
-    float    mc1_l, mc1_r, mc2_l, mc2_r;
+    int i, nsample, band;
+    float mc1_l, mc1_r, mc2_l, mc2_r;
 
-    for (i=0,band = 0; band < 4*256; band+=256,i++) {
-        s1 = pPrevCode[i];
-        s2 = pCurrCode[i];
-        nsample = 0;
+    for (i = 0, band = 0; band < 4 * 256; band += 256, i++) {
+        int s1 = prev_code[i];
+        int s2 = curr_code[i];
+        nsample = band;
 
         if (s1 != s2) {
             /* Selector value changed, interpolation needed. */
-            mc1_l = matrixCoeffs[s1*2];
-            mc1_r = matrixCoeffs[s1*2+1];
-            mc2_l = matrixCoeffs[s2*2];
-            mc2_r = matrixCoeffs[s2*2+1];
+            mc1_l = matrix_coeffs[s1 * 2    ];
+            mc1_r = matrix_coeffs[s1 * 2 + 1];
+            mc2_l = matrix_coeffs[s2 * 2    ];
+            mc2_r = matrix_coeffs[s2 * 2 + 1];
 
             /* Interpolation is done over the first eight samples. */
-            for(; nsample < 8; nsample++) {
-                c1 = su1[band+nsample];
-                c2 = su2[band+nsample];
-                c2 = c1 * INTERPOLATE(mc1_l,mc2_l,nsample) + c2 * INTERPOLATE(mc1_r,mc2_r,nsample);
-                su1[band+nsample] = c2;
-                su2[band+nsample] = c1 * 2.0 - c2;
+            for (; nsample < band + 8; nsample++) {
+                float c1 = su1[nsample];
+                float c2 = su2[nsample];
+                c2 = c1 * INTERPOLATE(mc1_l, mc2_l, nsample - band) +
+                     c2 * INTERPOLATE(mc1_r, mc2_r, nsample - band);
+                su1[nsample] = c2;
+                su2[nsample] = c1 * 2.0 - c2;
             }
         }
 
         /* Apply the matrix without interpolation. */
         switch (s2) {
-            case 0:     /* M/S decoding */
-                for (; nsample < 256; nsample++) {
-                    c1 = su1[band+nsample];
-                    c2 = su2[band+nsample];
-                    su1[band+nsample] = c2 * 2.0;
-                    su2[band+nsample] = (c1 - c2) * 2.0;
-                }
-                break;
-
-            case 1:
-                for (; nsample < 256; nsample++) {
-                    c1 = su1[band+nsample];
-                    c2 = su2[band+nsample];
-                    su1[band+nsample] = (c1 + c2) * 2.0;
-                    su2[band+nsample] = c2 * -2.0;
-                }
-                break;
-            case 2:
-            case 3:
-                for (; nsample < 256; nsample++) {
-                    c1 = su1[band+nsample];
-                    c2 = su2[band+nsample];
-                    su1[band+nsample] = c1 + c2;
-                    su2[band+nsample] = c1 - c2;
-                }
-                break;
-            default:
-                av_assert1(0);
+        case 0:     /* M/S decoding */
+            for (; nsample < band + 256; nsample++) {
+                float c1 = su1[nsample];
+                float c2 = su2[nsample];
+                su1[nsample] =  c2       * 2.0;
+                su2[nsample] = (c1 - c2) * 2.0;
+            }
+            break;
+        case 1:
+            for (; nsample < band + 256; nsample++) {
+                float c1 = su1[nsample];
+                float c2 = su2[nsample];
+                su1[nsample] = (c1 + c2) *  2.0;
+                su2[nsample] =  c2       * -2.0;
+            }
+            break;
+        case 2:
+        case 3:
+            for (; nsample < band + 256; nsample++) {
+                float c1 = su1[nsample];
+                float c2 = su2[nsample];
+                su1[nsample] = c1 + c2;
+                su2[nsample] = c1 - c2;
+            }
+            break;
+        default:
+            av_assert1(0);
         }
     }
 }
 
-static void getChannelWeights (int indx, int flag, float ch[2]){
-
-    if (indx == 7) {
+static void get_channel_weights(int index, int flag, float ch[2])
+{
+    if (index == 7) {
         ch[0] = 1.0;
         ch[1] = 1.0;
     } else {
-        ch[0] = (float)(indx & 7) / 7.0;
-        ch[1] = sqrt(2 - ch[0]*ch[0]);
-        if(flag)
+        ch[0] = (index & 7) / 7.0;
+        ch[1] = sqrt(2 - ch[0] * ch[0]);
+        if (flag)
             FFSWAP(float, ch[0], ch[1]);
     }
 }
 
-static void channelWeighting (float *su1, float *su2, int *p3)
+static void channel_weighting(float *su1, float *su2, int *p3)
 {
-    int   band, nsample;
+    int band, nsample;
     /* w[x][y] y=0 is left y=1 is right */
     float w[2][2];
 
-    if (p3[1] != 7 || p3[3] != 7){
-        getChannelWeights(p3[1], p3[0], w[0]);
-        getChannelWeights(p3[3], p3[2], w[1]);
+    if (p3[1] != 7 || p3[3] != 7) {
+        get_channel_weights(p3[1], p3[0], w[0]);
+        get_channel_weights(p3[3], p3[2], w[1]);
 
-        for(band = 1; band < 4; band++) {
-            /* scale the channels by the weights */
-            for(nsample = 0; nsample < 8; nsample++) {
-                su1[band*256+nsample] *= INTERPOLATE(w[0][0], w[0][1], nsample);
-                su2[band*256+nsample] *= INTERPOLATE(w[1][0], w[1][1], nsample);
+        for (band = 256; band < 4 * 256; band += 256) {
+            for (nsample = band; nsample < band + 8; nsample++) {
+                su1[nsample] *= INTERPOLATE(w[0][0], w[0][1], nsample - band);
+                su2[nsample] *= INTERPOLATE(w[1][0], w[1][1], nsample - band);
             }
-
-            for(; nsample < 256; nsample++) {
-                su1[band*256+nsample] *= w[1][0];
-                su2[band*256+nsample] *= w[1][1];
+            for(; nsample < band + 256; nsample++) {
+                su1[nsample] *= w[1][0];
+                su2[nsample] *= w[1][1];
             }
         }
     }
 }
 
-
 /**
  * Decode a Sound Unit
  *
- * @param gb            the GetBit context
- * @param pSnd          the channel unit to be used
- * @param pOut          the decoded samples before IQMF in float representation
- * @param channelNum    channel number
- * @param codingMode    the coding mode (JOINT_STEREO or regular stereo/mono)
+ * @param snd           the channel unit to be used
+ * @param output        the decoded samples before IQMF in float representation
+ * @param channel_num   channel number
+ * @param coding_mode   the coding mode (JOINT_STEREO or regular stereo/mono)
  */
-
-
-static int decodeChannelSoundUnit (ATRAC3Context *q, GetBitContext *gb, channel_unit *pSnd, float *pOut, int channelNum, int codingMode)
+static int decode_channel_sound_unit(ATRAC3Context *q, GetBitContext *gb,
+                                     ChannelUnit *snd, float *output,
+                                     int channel_num, int coding_mode)
 {
-    int   band, result=0, numSubbands, lastTonal, numBands;
+    int band, ret, num_subbands, last_tonal, num_bands;
+    GainBlock *gain1 = &snd->gain_block[    snd->gc_blk_switch];
+    GainBlock *gain2 = &snd->gain_block[1 - snd->gc_blk_switch];
 
-    if (codingMode == JOINT_STEREO && channelNum == 1) {
-        if (get_bits(gb,2) != 3) {
+    if (coding_mode == JOINT_STEREO && channel_num == 1) {
+        if (get_bits(gb, 2) != 3) {
             av_log(NULL,AV_LOG_ERROR,"JS mono Sound Unit id != 3.\n");
             return AVERROR_INVALIDDATA;
         }
     } else {
-        if (get_bits(gb,6) != 0x28) {
+        if (get_bits(gb, 6) != 0x28) {
             av_log(NULL,AV_LOG_ERROR,"Sound Unit id != 0x28.\n");
             return AVERROR_INVALIDDATA;
         }
     }
 
     /* number of coded QMF bands */
-    pSnd->bandsCoded = get_bits(gb,2);
+    snd->bands_coded = get_bits(gb, 2);
 
-    result = decodeGainControl (gb, &(pSnd->gainBlock[pSnd->gcBlkSwitch]), pSnd->bandsCoded);
-    if (result) return result;
+    ret = decode_gain_control(gb, gain2, snd->bands_coded);
+    if (ret)
+        return ret;
 
-    pSnd->numComponents = decodeTonalComponents (gb, pSnd->components, pSnd->bandsCoded);
-    if (pSnd->numComponents == -1) return -1;
+    snd->num_components = decode_tonal_components(gb, snd->components,
+                                                  snd->bands_coded);
+    if (snd->num_components == -1)
+        return -1;
 
-    numSubbands = decodeSpectrum (gb, pSnd->spectrum);
+    num_subbands = decode_spectrum(gb, snd->spectrum);
 
     /* Merge the decoded spectrum and tonal components. */
-    lastTonal = addTonalComponents (pSnd->spectrum, pSnd->numComponents, pSnd->components);
+    last_tonal = add_tonal_components(snd->spectrum, snd->num_components,
+                                      snd->components);
 
 
-    /* calculate number of used MLT/QMF bands according to the amount of coded spectral lines */
-    numBands = (subbandTab[numSubbands] - 1) >> 8;
-    if (lastTonal >= 0)
-        numBands = FFMAX((lastTonal + 256) >> 8, numBands);
+    /* calculate number of used MLT/QMF bands according to the amount of coded
+       spectral lines */
+    num_bands = (subband_tab[num_subbands] - 1) >> 8;
+    if (last_tonal >= 0)
+        num_bands = FFMAX((last_tonal + 256) >> 8, num_bands);
 
 
     /* Reconstruct time domain samples. */
-    for (band=0; band<4; band++) {
+    for (band = 0; band < 4; band++) {
         /* Perform the IMDCT step without overlapping. */
-        if (band <= numBands) {
-            IMLT(q, &(pSnd->spectrum[band*256]), pSnd->IMDCT_buf, band&1);
-        } else
-            memset(pSnd->IMDCT_buf, 0, 512 * sizeof(float));
+        if (band <= num_bands)
+            imlt(q, &snd->spectrum[band * 256], snd->imdct_buf, band & 1);
+        else
+            memset(snd->imdct_buf, 0, 512 * sizeof(*snd->imdct_buf));
 
         /* gain compensation and overlapping */
-        gainCompensateAndOverlap(pSnd->IMDCT_buf, &pSnd->prevFrame[band * 256],
-                                 &pOut[band * 256],
-                                 &pSnd->gainBlock[1 - pSnd->gcBlkSwitch].gBlock[band],
-                                 &pSnd->gainBlock[    pSnd->gcBlkSwitch].gBlock[band]);
+        gain_compensate_and_overlap(snd->imdct_buf,
+                                    &snd->prev_frame[band * 256],
+                                    &output[band * 256],
+                                    &gain1->g_block[band],
+                                    &gain2->g_block[band]);
     }
 
     /* Swap the gain control buffers for the next frame. */
-    pSnd->gcBlkSwitch ^= 1;
+    snd->gc_blk_switch ^= 1;
 
     return 0;
 }
 
-/**
- * Frame handling
- *
- * @param q             Atrac3 private context
- * @param databuf       the input data
- */
-
-static int decodeFrame(ATRAC3Context *q, const uint8_t* databuf,
-                       float **out_samples)
+static int decode_frame(AVCodecContext *avctx, const uint8_t *databuf,
+                        float **out_samples)
 {
-    int   result, i;
-    float   *p1, *p2, *p3, *p4;
+    ATRAC3Context *q = avctx->priv_data;
+    int ret, i;
     uint8_t *ptr1;
 
-    if (q->codingMode == JOINT_STEREO) {
-
+    if (q->coding_mode == JOINT_STEREO) {
         /* channel coupling mode */
         /* decode Sound Unit 1 */
-        init_get_bits(&q->gb,databuf,q->bits_per_frame);
+        init_get_bits(&q->gb, databuf, avctx->block_align * 8);
 
-        result = decodeChannelSoundUnit(q,&q->gb, q->pUnits, out_samples[0], 0, JOINT_STEREO);
-        if (result != 0)
-            return result;
+        ret = decode_channel_sound_unit(q, &q->gb, q->units, out_samples[0], 0,
+                                        JOINT_STEREO);
+        if (ret != 0)
+            return ret;
 
         /* Framedata of the su2 in the joint-stereo mode is encoded in
          * reverse byte order so we need to swap it first. */
         if (databuf == q->decoded_bytes_buffer) {
-            uint8_t *ptr2 = q->decoded_bytes_buffer+q->bytes_per_frame-1;
-            ptr1 = q->decoded_bytes_buffer;
-            for (i = 0; i < (q->bytes_per_frame/2); i++, ptr1++, ptr2--) {
-                FFSWAP(uint8_t,*ptr1,*ptr2);
-            }
+            uint8_t *ptr2 = q->decoded_bytes_buffer + avctx->block_align - 1;
+            ptr1          = q->decoded_bytes_buffer;
+            for (i = 0; i < avctx->block_align / 2; i++, ptr1++, ptr2--)
+                FFSWAP(uint8_t, *ptr1, *ptr2);
         } else {
-            const uint8_t *ptr2 = databuf+q->bytes_per_frame-1;
-            for (i = 0; i < q->bytes_per_frame; i++)
+            const uint8_t *ptr2 = databuf + avctx->block_align - 1;
+            for (i = 0; i < avctx->block_align; i++)
                 q->decoded_bytes_buffer[i] = *ptr2--;
         }
 
         /* Skip the sync codes (0xF8). */
         ptr1 = q->decoded_bytes_buffer;
         for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {
-            if (i >= q->bytes_per_frame)
+            if (i >= avctx->block_align)
                 return AVERROR_INVALIDDATA;
         }
 
 
         /* set the bitstream reader at the start of the second Sound Unit*/
-        init_get_bits(&q->gb,ptr1,q->bits_per_frame);
+        init_get_bits(&q->gb, ptr1, avctx->block_align * 8);
 
         /* Fill the Weighting coeffs delay buffer */
-        memmove(q->weighting_delay,&(q->weighting_delay[2]),4*sizeof(int));
+        memmove(q->weighting_delay, &q->weighting_delay[2],
+                4 * sizeof(*q->weighting_delay));
         q->weighting_delay[4] = get_bits1(&q->gb);
-        q->weighting_delay[5] = get_bits(&q->gb,3);
+        q->weighting_delay[5] = get_bits(&q->gb, 3);
 
         for (i = 0; i < 4; i++) {
             q->matrix_coeff_index_prev[i] = q->matrix_coeff_index_now[i];
-            q->matrix_coeff_index_now[i] = q->matrix_coeff_index_next[i];
-            q->matrix_coeff_index_next[i] = get_bits(&q->gb,2);
+            q->matrix_coeff_index_now[i]  = q->matrix_coeff_index_next[i];
+            q->matrix_coeff_index_next[i] = get_bits(&q->gb, 2);
         }
 
         /* Decode Sound Unit 2. */
-        result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[1], out_samples[1], 1, JOINT_STEREO);
-        if (result != 0)
-            return result;
+        ret = decode_channel_sound_unit(q, &q->gb, &q->units[1],
+                                        out_samples[1], 1, JOINT_STEREO);
+        if (ret != 0)
+            return ret;
 
         /* Reconstruct the channel coefficients. */
-        reverseMatrixing(out_samples[0], out_samples[1], q->matrix_coeff_index_prev, q->matrix_coeff_index_now);
+        reverse_matrixing(out_samples[0], out_samples[1],
+                          q->matrix_coeff_index_prev,
+                          q->matrix_coeff_index_now);
 
-        channelWeighting(out_samples[0], out_samples[1], q->weighting_delay);
-
+        channel_weighting(out_samples[0], out_samples[1], q->weighting_delay);
     } else {
         /* normal stereo mode or mono */
         /* Decode the channel sound units. */
-        for (i=0 ; i<q->channels ; i++) {
-
+        for (i = 0; i < avctx->channels; i++) {
             /* Set the bitstream reader at the start of a channel sound unit. */
             init_get_bits(&q->gb,
-                          databuf + i * q->bytes_per_frame / q->channels,
-                          q->bits_per_frame / q->channels);
+                          databuf + i * avctx->block_align / avctx->channels,
+                          avctx->block_align * 8 / avctx->channels);
 
-            result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[i], out_samples[i], i, q->codingMode);
-            if (result != 0)
-                return result;
+            ret = decode_channel_sound_unit(q, &q->gb, &q->units[i],
+                                            out_samples[i], i, q->coding_mode);
+            if (ret != 0)
+                return ret;
         }
     }
 
     /* Apply the iQMF synthesis filter. */
-    for (i=0 ; i<q->channels ; i++) {
-        p1 = out_samples[i];
-        p2= p1+256;
-        p3= p2+256;
-        p4= p3+256;
-        ff_atrac_iqmf (p1, p2, 256, p1, q->pUnits[i].delayBuf1, q->tempBuf);
-        ff_atrac_iqmf (p4, p3, 256, p3, q->pUnits[i].delayBuf2, q->tempBuf);
-        ff_atrac_iqmf (p1, p3, 512, p1, q->pUnits[i].delayBuf3, q->tempBuf);
+    for (i = 0; i < avctx->channels; i++) {
+        float *p1 = out_samples[i];
+        float *p2 = p1 + 256;
+        float *p3 = p2 + 256;
+        float *p4 = p3 + 256;
+        ff_atrac_iqmf(p1, p2, 256, p1, q->units[i].delay_buf1, q->temp_buf);
+        ff_atrac_iqmf(p4, p3, 256, p3, q->units[i].delay_buf2, q->temp_buf);
+        ff_atrac_iqmf(p1, p3, 512, p1, q->units[i].delay_buf3, q->temp_buf);
     }
 
     return 0;
 }
 
-
-/**
- * Atrac frame decoding
- *
- * @param avctx     pointer to the AVCodecContext
- */
-
 static int atrac3_decode_frame(AVCodecContext *avctx, void *data,
                                int *got_frame_ptr, AVPacket *avpkt)
 {
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
     ATRAC3Context *q = avctx->priv_data;
-    int result;
-    const uint8_t* databuf;
-    float   *samples_flt;
-    int16_t *samples_s16;
+    int ret;
+    const uint8_t *databuf;
 
     if (buf_size < avctx->block_align) {
         av_log(avctx, AV_LOG_ERROR,
@@ -849,12 +812,10 @@
 
     /* get output buffer */
     q->frame.nb_samples = SAMPLES_PER_FRAME;
-    if ((result = avctx->get_buffer(avctx, &q->frame)) < 0) {
+    if ((ret = avctx->get_buffer(avctx, &q->frame)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return result;
+        return ret;
     }
-    samples_flt = (float   *)q->frame.data[0];
-    samples_s16 = (int16_t *)q->frame.data[0];
 
     /* Check if we need to descramble and what buffer to pass on. */
     if (q->scrambled_stream) {
@@ -864,25 +825,10 @@
         databuf = buf;
     }
 
-    if (q->channels == 1 && avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
-        result = decodeFrame(q, databuf, &samples_flt);
-    else
-        result = decodeFrame(q, databuf, q->outSamples);
-
-    if (result != 0) {
-        av_log(NULL,AV_LOG_ERROR,"Frame decoding error!\n");
-        return result;
-    }
-
-    /* interleave */
-    if (q->channels == 2 && avctx->sample_fmt == AV_SAMPLE_FMT_FLT) {
-        q->fmt_conv.float_interleave(samples_flt,
-                                     (const float **)q->outSamples,
-                                     SAMPLES_PER_FRAME, 2);
-    } else if (avctx->sample_fmt == AV_SAMPLE_FMT_S16) {
-        q->fmt_conv.float_to_int16_interleave(samples_s16,
-                                              (const float **)q->outSamples,
-                                              SAMPLES_PER_FRAME, q->channels);
+    ret = decode_frame(avctx, databuf, (float **)q->frame.extended_data);
+    if (ret) {
+        av_log(NULL, AV_LOG_ERROR, "Frame decoding error!\n");
+        return ret;
     }
 
     *got_frame_ptr   = 1;
@@ -891,141 +837,142 @@
     return avctx->block_align;
 }
 
+static void atrac3_init_static_data(void)
+{
+    int i;
 
-/**
- * Atrac3 initialization
- *
- * @param avctx     pointer to the AVCodecContext
- */
+    init_atrac3_window();
+    ff_atrac_generate_tables();
+
+    /* Initialize the VLC tables. */
+    for (i = 0; i < 7; i++) {
+        spectral_coeff_tab[i].table = &atrac3_vlc_table[atrac3_vlc_offs[i]];
+        spectral_coeff_tab[i].table_allocated = atrac3_vlc_offs[i + 1] -
+                                                atrac3_vlc_offs[i    ];
+        init_vlc(&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
+                 huff_bits[i],  1, 1,
+                 huff_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);
+    }
+
+    /* Generate gain tables */
+    for (i = 0; i < 16; i++)
+        gain_tab1[i] = exp2f (4 - i);
+
+    for (i = -15; i < 16; i++)
+        gain_tab2[i + 15] = exp2f (i * -0.125);
+}
 
 static av_cold int atrac3_decode_init(AVCodecContext *avctx)
 {
+    static int static_init_done;
     int i, ret;
+    int version, delay, samples_per_frame, frame_factor;
     const uint8_t *edata_ptr = avctx->extradata;
     ATRAC3Context *q = avctx->priv_data;
-    static VLC_TYPE atrac3_vlc_table[4096][2];
-    static int vlcs_initialized = 0;
 
-    /* Take data from the AVCodecContext (RM container). */
-    q->sample_rate = avctx->sample_rate;
-    q->channels = avctx->channels;
-    q->bit_rate = avctx->bit_rate;
-    q->bits_per_frame = avctx->block_align * 8;
-    q->bytes_per_frame = avctx->block_align;
+    if (avctx->channels <= 0 || avctx->channels > 2) {
+        av_log(avctx, AV_LOG_ERROR, "Channel configuration error!\n");
+        return AVERROR(EINVAL);
+    }
+
+    if (!static_init_done)
+        atrac3_init_static_data();
+    static_init_done = 1;
 
     /* Take care of the codec-specific extradata. */
     if (avctx->extradata_size == 14) {
         /* Parse the extradata, WAV format */
-        av_log(avctx,AV_LOG_DEBUG,"[0-1] %d\n",bytestream_get_le16(&edata_ptr));  //Unknown value always 1
-        q->samples_per_channel = bytestream_get_le32(&edata_ptr);
-        q->codingMode = bytestream_get_le16(&edata_ptr);
-        av_log(avctx,AV_LOG_DEBUG,"[8-9] %d\n",bytestream_get_le16(&edata_ptr));  //Dupe of coding mode
-        q->frame_factor = bytestream_get_le16(&edata_ptr);  //Unknown always 1
-        av_log(avctx,AV_LOG_DEBUG,"[12-13] %d\n",bytestream_get_le16(&edata_ptr));  //Unknown always 0
+        av_log(avctx, AV_LOG_DEBUG, "[0-1] %d\n",
+               bytestream_get_le16(&edata_ptr));  // Unknown value always 1
+        edata_ptr += 4;                             // samples per channel
+        q->coding_mode = bytestream_get_le16(&edata_ptr);
+        av_log(avctx, AV_LOG_DEBUG,"[8-9] %d\n",
+               bytestream_get_le16(&edata_ptr));  //Dupe of coding mode
+        frame_factor = bytestream_get_le16(&edata_ptr);  // Unknown always 1
+        av_log(avctx, AV_LOG_DEBUG,"[12-13] %d\n",
+               bytestream_get_le16(&edata_ptr));  // Unknown always 0
 
         /* setup */
-        q->samples_per_frame = SAMPLES_PER_FRAME * q->channels;
-        q->atrac3version = 4;
-        q->delay = 0x88E;
-        if (q->codingMode)
-            q->codingMode = JOINT_STEREO;
-        else
-            q->codingMode = STEREO;
+        samples_per_frame    = SAMPLES_PER_FRAME * avctx->channels;
+        version              = 4;
+        delay                = 0x88E;
+        q->coding_mode       = q->coding_mode ? JOINT_STEREO : STEREO;
+        q->scrambled_stream  = 0;
 
-        q->scrambled_stream = 0;
-
-        if ((q->bytes_per_frame == 96*q->channels*q->frame_factor) || (q->bytes_per_frame == 152*q->channels*q->frame_factor) || (q->bytes_per_frame == 192*q->channels*q->frame_factor)) {
-        } else {
-            av_log(avctx,AV_LOG_ERROR,"Unknown frame/channel/frame_factor configuration %d/%d/%d\n", q->bytes_per_frame, q->channels, q->frame_factor);
+        if (avctx->block_align !=  96 * avctx->channels * frame_factor &&
+            avctx->block_align != 152 * avctx->channels * frame_factor &&
+            avctx->block_align != 192 * avctx->channels * frame_factor) {
+            av_log(avctx, AV_LOG_ERROR, "Unknown frame/channel/frame_factor "
+                   "configuration %d/%d/%d\n", avctx->block_align,
+                   avctx->channels, frame_factor);
             return AVERROR_INVALIDDATA;
         }
-
     } else if (avctx->extradata_size == 10) {
         /* Parse the extradata, RM format. */
-        q->atrac3version = bytestream_get_be32(&edata_ptr);
-        q->samples_per_frame = bytestream_get_be16(&edata_ptr);
-        q->delay = bytestream_get_be16(&edata_ptr);
-        q->codingMode = bytestream_get_be16(&edata_ptr);
-
-        q->samples_per_channel = q->samples_per_frame / q->channels;
-        q->scrambled_stream = 1;
+        version                = bytestream_get_be32(&edata_ptr);
+        samples_per_frame      = bytestream_get_be16(&edata_ptr);
+        delay                  = bytestream_get_be16(&edata_ptr);
+        q->coding_mode         = bytestream_get_be16(&edata_ptr);
+        q->scrambled_stream    = 1;
 
     } else {
-        av_log(NULL,AV_LOG_ERROR,"Unknown extradata size %d.\n",avctx->extradata_size);
-    }
-    /* Check the extradata. */
-
-    if (q->atrac3version != 4) {
-        av_log(avctx,AV_LOG_ERROR,"Version %d != 4.\n",q->atrac3version);
-        return AVERROR_INVALIDDATA;
-    }
-
-    if (q->samples_per_frame != SAMPLES_PER_FRAME && q->samples_per_frame != SAMPLES_PER_FRAME*2) {
-        av_log(avctx,AV_LOG_ERROR,"Unknown amount of samples per frame %d.\n",q->samples_per_frame);
-        return AVERROR_INVALIDDATA;
-    }
-
-    if (q->delay != 0x88E) {
-        av_log(avctx,AV_LOG_ERROR,"Unknown amount of delay %x != 0x88E.\n",q->delay);
-        return AVERROR_INVALIDDATA;
-    }
-
-    if (q->codingMode == STEREO) {
-        av_log(avctx,AV_LOG_DEBUG,"Normal stereo detected.\n");
-    } else if (q->codingMode == JOINT_STEREO) {
-        av_log(avctx,AV_LOG_DEBUG,"Joint stereo detected.\n");
-    } else {
-        av_log(avctx,AV_LOG_ERROR,"Unknown channel coding mode %x!\n",q->codingMode);
-        return AVERROR_INVALIDDATA;
-    }
-
-    if (avctx->channels <= 0 || avctx->channels > 2 /*|| ((avctx->channels * 1024) != q->samples_per_frame)*/) {
-        av_log(avctx,AV_LOG_ERROR,"Channel configuration error!\n");
+        av_log(NULL, AV_LOG_ERROR, "Unknown extradata size %d.\n",
+               avctx->extradata_size);
         return AVERROR(EINVAL);
     }
 
+    if (q->coding_mode == JOINT_STEREO && avctx->channels < 2) {
+        av_log(avctx, AV_LOG_ERROR, "Invalid coding mode\n");
+        return AVERROR_INVALIDDATA;
+    }
 
-    if(avctx->block_align >= UINT_MAX/2)
+    /* Check the extradata */
+
+    if (version != 4) {
+        av_log(avctx, AV_LOG_ERROR, "Version %d != 4.\n", version);
+        return AVERROR_INVALIDDATA;
+    }
+
+    if (samples_per_frame != SAMPLES_PER_FRAME &&
+        samples_per_frame != SAMPLES_PER_FRAME * 2) {
+        av_log(avctx, AV_LOG_ERROR, "Unknown amount of samples per frame %d.\n",
+               samples_per_frame);
+        return AVERROR_INVALIDDATA;
+    }
+
+    if (delay != 0x88E) {
+        av_log(avctx, AV_LOG_ERROR, "Unknown amount of delay %x != 0x88E.\n",
+               delay);
+        return AVERROR_INVALIDDATA;
+    }
+
+    if (q->coding_mode == STEREO)
+        av_log(avctx, AV_LOG_DEBUG, "Normal stereo detected.\n");
+    else if (q->coding_mode == JOINT_STEREO)
+        av_log(avctx, AV_LOG_DEBUG, "Joint stereo detected.\n");
+    else {
+        av_log(avctx, AV_LOG_ERROR, "Unknown channel coding mode %x!\n",
+               q->coding_mode);
+        return AVERROR_INVALIDDATA;
+    }
+
+    if (avctx->block_align >= UINT_MAX / 2)
         return AVERROR(EINVAL);
 
-    /* Pad the data buffer with FF_INPUT_BUFFER_PADDING_SIZE,
-     * this is for the bitstream reader. */
-    if ((q->decoded_bytes_buffer = av_mallocz((avctx->block_align+(4-avctx->block_align%4) + FF_INPUT_BUFFER_PADDING_SIZE)))  == NULL)
+    q->decoded_bytes_buffer = av_mallocz(FFALIGN(avctx->block_align, 4) +
+                                         FF_INPUT_BUFFER_PADDING_SIZE);
+    if (q->decoded_bytes_buffer == NULL)
         return AVERROR(ENOMEM);
 
+    avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
 
-    /* Initialize the VLC tables. */
-    if (!vlcs_initialized) {
-        for (i=0 ; i<7 ; i++) {
-            spectral_coeff_tab[i].table = &atrac3_vlc_table[atrac3_vlc_offs[i]];
-            spectral_coeff_tab[i].table_allocated = atrac3_vlc_offs[i + 1] - atrac3_vlc_offs[i];
-            init_vlc (&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
-                huff_bits[i], 1, 1,
-                huff_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);
-        }
-        vlcs_initialized = 1;
-    }
-
-    if (avctx->request_sample_fmt == AV_SAMPLE_FMT_FLT)
-        avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
-    else
-        avctx->sample_fmt = AV_SAMPLE_FMT_S16;
-
-    if ((ret = init_atrac3_transforms(q, avctx->sample_fmt == AV_SAMPLE_FMT_FLT))) {
+    /* initialize the MDCT transform */
+    if ((ret = ff_mdct_init(&q->mdct_ctx, 9, 1, 1.0 / 32768)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "Error initializing MDCT\n");
         av_freep(&q->decoded_bytes_buffer);
         return ret;
     }
 
-    ff_atrac_generate_tables();
-
-    /* Generate gain tables. */
-    for (i=0 ; i<16 ; i++)
-        gain_tab1[i] = exp2f (4 - i);
-
-    for (i=-15 ; i<16 ; i++)
-        gain_tab2[i+15] = exp2f (i * -0.125);
-
     /* init the joint-stereo decoding data */
     q->weighting_delay[0] = 0;
     q->weighting_delay[1] = 7;
@@ -1034,46 +981,37 @@
     q->weighting_delay[4] = 0;
     q->weighting_delay[5] = 7;
 
-    for (i=0; i<4; i++) {
+    for (i = 0; i < 4; i++) {
         q->matrix_coeff_index_prev[i] = 3;
-        q->matrix_coeff_index_now[i] = 3;
+        q->matrix_coeff_index_now[i]  = 3;
         q->matrix_coeff_index_next[i] = 3;
     }
 
     avpriv_float_dsp_init(&q->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
     ff_fmt_convert_init(&q->fmt_conv, avctx);
 
-    q->pUnits = av_mallocz(sizeof(channel_unit)*q->channels);
-    if (!q->pUnits) {
+    q->units = av_mallocz(sizeof(*q->units) * avctx->channels);
+    if (!q->units) {
         atrac3_decode_close(avctx);
         return AVERROR(ENOMEM);
     }
 
-    if (avctx->channels > 1 || avctx->sample_fmt == AV_SAMPLE_FMT_S16) {
-        q->outSamples[0] = av_mallocz(SAMPLES_PER_FRAME * avctx->channels * sizeof(*q->outSamples[0]));
-        q->outSamples[1] = q->outSamples[0] + SAMPLES_PER_FRAME;
-        if (!q->outSamples[0]) {
-            atrac3_decode_close(avctx);
-            return AVERROR(ENOMEM);
-        }
-    }
-
     avcodec_get_frame_defaults(&q->frame);
     avctx->coded_frame = &q->frame;
 
     return 0;
 }
 
-
-AVCodec ff_atrac3_decoder =
-{
-    .name           = "atrac3",
-    .type           = AVMEDIA_TYPE_AUDIO,
-    .id             = AV_CODEC_ID_ATRAC3,
-    .priv_data_size = sizeof(ATRAC3Context),
-    .init           = atrac3_decode_init,
-    .close          = atrac3_decode_close,
-    .decode         = atrac3_decode_frame,
-    .capabilities   = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1,
-    .long_name      = NULL_IF_CONFIG_SMALL("Atrac 3 (Adaptive TRansform Acoustic Coding 3)"),
+AVCodec ff_atrac3_decoder = {
+    .name             = "atrac3",
+    .type             = AVMEDIA_TYPE_AUDIO,
+    .id               = AV_CODEC_ID_ATRAC3,
+    .priv_data_size   = sizeof(ATRAC3Context),
+    .init             = atrac3_decode_init,
+    .close            = atrac3_decode_close,
+    .decode           = atrac3_decode_frame,
+    .capabilities     = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1,
+    .long_name        = NULL_IF_CONFIG_SMALL("Atrac 3 (Adaptive TRansform Acoustic Coding 3)"),
+    .sample_fmts      = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
+                                                        AV_SAMPLE_FMT_NONE },
 };
diff --git a/libavcodec/atrac3data.h b/libavcodec/atrac3data.h
index b5aa71f..9963d4e 100644
--- a/libavcodec/atrac3data.h
+++ b/libavcodec/atrac3data.h
@@ -33,101 +33,109 @@
 /* VLC tables */
 
 static const uint8_t huffcode1[9] = {
-  0x0,0x4,0x5,0xC,0xD,0x1C,0x1D,0x1E,0x1F,
+    0x0, 0x4, 0x5, 0xC, 0xD, 0x1C, 0x1D, 0x1E, 0x1F
 };
 
-static const uint8_t huffbits1[9] = {
-  1,3,3,4,4,5,5,5,5,
-};
+static const uint8_t huffbits1[9] = { 1, 3, 3, 4, 4, 5, 5, 5, 5 };
 
-static const uint8_t huffcode2[5] = {
-  0x0,0x4,0x5,0x6,0x7,
-};
+static const uint8_t huffcode2[5] = { 0x0, 0x4, 0x5, 0x6, 0x7 };
 
-static const uint8_t huffbits2[5] = {
-  1,3,3,3,3,
-};
+static const uint8_t huffbits2[5] = { 1, 3, 3, 3, 3 };
 
-static const uint8_t huffcode3[7] = {
-0x0,0x4,0x5,0xC,0xD,0xE,0xF,
-};
+static const uint8_t huffcode3[7] = { 0x0, 0x4, 0x5, 0xC, 0xD, 0xE, 0xF };
 
-static const uint8_t huffbits3[7] = {
-  1,3,3,4,4,4,4,
-};
+static const uint8_t huffbits3[7] = { 1, 3, 3, 4, 4, 4, 4 };
 
 static const uint8_t huffcode4[9] = {
-  0x0,0x4,0x5,0xC,0xD,0x1C,0x1D,0x1E,0x1F,
+    0x0, 0x4, 0x5, 0xC, 0xD, 0x1C, 0x1D, 0x1E, 0x1F
 };
 
-static const uint8_t huffbits4[9] = {
-  1,3,3,4,4,5,5,5,5,
-};
+static const uint8_t huffbits4[9] = { 1, 3, 3, 4, 4, 5, 5, 5, 5 };
 
 static const uint8_t huffcode5[15] = {
-  0x0,0x2,0x3,0x8,0x9,0xA,0xB,0x1C,0x1D,0x3C,0x3D,0x3E,0x3F,0xC,0xD,
+    0x00, 0x02, 0x03, 0x08, 0x09, 0x0A, 0x0B, 0x1C,
+    0x1D, 0x3C, 0x3D, 0x3E, 0x3F, 0x0C, 0x0D
 };
 
 static const uint8_t huffbits5[15] = {
-  2,3,3,4,4,4,4,5,5,6,6,6,6,4,4
+    2, 3, 3, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 4, 4
 };
 
 static const uint8_t huffcode6[31] = {
-  0x0,0x2,0x3,0x4,0x5,0x6,0x7,0x14,0x15,0x16,0x17,0x18,0x19,0x34,0x35,
-  0x36,0x37,0x38,0x39,0x3A,0x3B,0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x7F,0x8,0x9,
+    0x00, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x14,
+    0x15, 0x16, 0x17, 0x18, 0x19, 0x34, 0x35, 0x36,
+    0x37, 0x38, 0x39, 0x3A, 0x3B, 0x78, 0x79, 0x7A,
+    0x7B, 0x7C, 0x7D, 0x7E, 0x7F, 0x08, 0x09
 };
 
 static const uint8_t huffbits6[31] = {
-  3,4,4,4,4,4,4,5,5,5,5,5,5,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,4,4
+    3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6,
+    6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 4, 4
 };
 
 static const uint8_t huffcode7[63] = {
-  0x0,0x8,0x9,0xA,0xB,0xC,0xD,0xE,0xF,0x10,0x11,0x24,0x25,0x26,0x27,0x28,
-  0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F,0x30,0x31,0x32,0x33,0x68,0x69,0x6A,0x6B,0x6C,
-  0x6D,0x6E,0x6F,0x70,0x71,0x72,0x73,0x74,0x75,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,
-  0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF,0x2,0x3,
+    0x00, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
+    0x0F, 0x10, 0x11, 0x24, 0x25, 0x26, 0x27, 0x28,
+    0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30,
+    0x31, 0x32, 0x33, 0x68, 0x69, 0x6A, 0x6B, 0x6C,
+    0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74,
+    0x75, 0xEC, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF2,
+    0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA,
+    0xFB, 0xFC, 0xFD, 0xFE, 0xFF, 0x02, 0x03
 };
 
 static const uint8_t huffbits7[63] = {
-  3,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,7,7,7,7,7,
-  7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,4,4
+    3, 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, 7, 7, 7, 7, 7,
+    7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
+    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 4
 };
 
 static const uint8_t huff_tab_sizes[7] = {
-  9, 5, 7, 9, 15, 31, 63,
+    9, 5, 7, 9, 15, 31, 63,
 };
 
 static const uint8_t* const huff_codes[7] = {
-  huffcode1,huffcode2,huffcode3,huffcode4,huffcode5,huffcode6,huffcode7,
+    huffcode1, huffcode2, huffcode3, huffcode4, huffcode5, huffcode6, huffcode7
 };
 
 static const uint8_t* const huff_bits[7] = {
-  huffbits1,huffbits2,huffbits3,huffbits4,huffbits5,huffbits6,huffbits7,
+    huffbits1, huffbits2, huffbits3, huffbits4, huffbits5, huffbits6, huffbits7,
 };
 
-static const uint16_t atrac3_vlc_offs[] = {
-    0,512,1024,1536,2048,2560,3072,3584,4096
+static const uint16_t atrac3_vlc_offs[9] = {
+    0, 512, 1024, 1536, 2048, 2560, 3072, 3584, 4096
 };
 
 /* selector tables */
 
-static const uint8_t CLCLengthTab[8] = {0, 4, 3, 3, 4, 4, 5, 6};
-static const int8_t seTab_0[4] = {0, 1, -2, -1};
-static const int8_t decTable1[18] = {0,0, 0,1, 0,-1, 1,0, -1,0, 1,1, 1,-1, -1,1, -1,-1};
+static const uint8_t clc_length_tab[8] = { 0, 4, 3, 3, 4, 4, 5, 6 };
+
+static const int8_t mantissa_clc_tab[4] = { 0, 1, -2, -1 };
+
+static const int8_t mantissa_vlc_tab[18] = {
+    0, 0,  0, 1,  0, -1,  1, 0,  -1, 0,  1, 1,  1, -1,  -1, 1,  -1, -1
+};
 
 
 /* tables for the scalefactor decoding */
 
-static const float iMaxQuant[8] = {
-  0.0, 1.0/1.5, 1.0/2.5, 1.0/3.5, 1.0/4.5, 1.0/7.5, 1.0/15.5, 1.0/31.5
+static const float inv_max_quant[8] = {
+      0.0,       1.0 / 1.5, 1.0 /  2.5, 1.0 /  3.5,
+      1.0 / 4.5, 1.0 / 7.5, 1.0 / 15.5, 1.0 / 31.5
 };
 
-static const uint16_t subbandTab[33] = {
-  0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224,
-  256, 288, 320, 352, 384, 416, 448, 480, 512, 576, 640, 704, 768, 896, 1024
+static const uint16_t subband_tab[33] = {
+      0,   8,  16,  24,  32,  40,  48,  56,
+     64,  80,  96, 112, 128, 144, 160, 176,
+    192, 224, 256, 288, 320, 352, 384, 416,
+    448, 480, 512, 576, 640, 704, 768, 896,
+    1024
 };
 
 /* joint stereo related tables */
-static const float matrixCoeffs[8] = {0.0, 2.0, 2.0, 2.0, 0.0, 0.0, 1.0, 1.0};
+static const float matrix_coeffs[8] = {
+    0.0, 2.0, 2.0, 2.0, 0.0, 0.0, 1.0, 1.0
+};
 
 #endif /* AVCODEC_ATRAC3DATA_H */
diff --git a/libavcodec/audio_frame_queue.c b/libavcodec/audio_frame_queue.c
index cc1fd13..7db0091 100644
--- a/libavcodec/audio_frame_queue.c
+++ b/libavcodec/audio_frame_queue.c
@@ -95,12 +95,14 @@
         if(afq->frames[i].pts != AV_NOPTS_VALUE)
             afq->frames[i].pts      += n;
     }
+    afq->remaining_samples -= removed_samples;
     i -= i && afq->frames[i-1].duration;
     memmove(afq->frames, afq->frames + i, sizeof(*afq->frames) * (afq->frame_count - i));
     afq->frame_count -= i;
 
     if(nb_samples){
         av_assert0(!afq->frame_count);
+        av_assert0(afq->remaining_samples == afq->remaining_delay);
         if(afq->frames && afq->frames[0].pts != AV_NOPTS_VALUE)
             afq->frames[0].pts += nb_samples;
         av_log(afq->avctx, AV_LOG_DEBUG, "Trying to remove %d more samples than are in the que\n", nb_samples);
diff --git a/libavcodec/audioconvert.h b/libavcodec/audioconvert.h
index 03b196b..61124b3 100644
--- a/libavcodec/audioconvert.h
+++ b/libavcodec/audioconvert.h
@@ -31,7 +31,7 @@
 
 #include "libavutil/cpu.h"
 #include "avcodec.h"
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 
 struct AVAudioConvert;
 typedef struct AVAudioConvert AVAudioConvert;
diff --git a/libavcodec/aura.c b/libavcodec/aura.c
index d79daba..669ef48 100644
--- a/libavcodec/aura.c
+++ b/libavcodec/aura.c
@@ -39,7 +39,7 @@
     /* width needs to be divisible by 4 for this codec to work */
     if (avctx->width & 0x3)
         return -1;
-    avctx->pix_fmt = PIX_FMT_YUV422P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV422P;
     avcodec_get_frame_defaults(&s->frame);
 
     return 0;
diff --git a/libavcodec/avcodec.h b/libavcodec/avcodec.h
index 2c18b42..b6a4b0e 100644
--- a/libavcodec/avcodec.h
+++ b/libavcodec/avcodec.h
@@ -30,11 +30,11 @@
 #include "libavutil/samplefmt.h"
 #include "libavutil/avutil.h"
 #include "libavutil/cpu.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/dict.h"
 #include "libavutil/log.h"
 #include "libavutil/pixfmt.h"
 #include "libavutil/rational.h"
-#include "libavutil/audioconvert.h"
 
 #include "libavcodec/version.h"
 /**
@@ -267,6 +267,7 @@
     AV_CODEC_ID_MTS2,
     AV_CODEC_ID_CLLC,
     AV_CODEC_ID_MSS2,
+    AV_CODEC_ID_BRENDER_PIX= MKBETAG('B','P','I','X'),
     AV_CODEC_ID_Y41P       = MKBETAG('Y','4','1','P'),
     AV_CODEC_ID_ESCAPE130  = MKBETAG('E','1','3','0'),
     AV_CODEC_ID_EXR        = MKBETAG('0','E','X','R'),
@@ -275,6 +276,7 @@
     AV_CODEC_ID_G2M        = MKBETAG( 0 ,'G','2','M'),
     AV_CODEC_ID_AVUI       = MKBETAG('A','V','U','I'),
     AV_CODEC_ID_AYUV       = MKBETAG('A','Y','U','V'),
+    AV_CODEC_ID_TARGA_Y216 = MKBETAG('T','2','1','6'),
     AV_CODEC_ID_V308       = MKBETAG('V','3','0','8'),
     AV_CODEC_ID_V408       = MKBETAG('V','4','0','8'),
     AV_CODEC_ID_YUV4       = MKBETAG('Y','U','V','4'),
@@ -282,6 +284,7 @@
     AV_CODEC_ID_PAF_VIDEO  = MKBETAG('P','A','F','V'),
     AV_CODEC_ID_AVRN       = MKBETAG('A','V','R','n'),
     AV_CODEC_ID_CPIA       = MKBETAG('C','P','I','A'),
+    AV_CODEC_ID_XFACE      = MKBETAG('X','F','A','C'),
 
     /* various PCM "codecs" */
     AV_CODEC_ID_FIRST_AUDIO = 0x10000,     ///< A dummy id pointing at the start of audio codecs
@@ -313,6 +316,9 @@
     AV_CODEC_ID_PCM_LXF,
     AV_CODEC_ID_S302M,
     AV_CODEC_ID_PCM_S8_PLANAR,
+    AV_CODEC_ID_PCM_S24LE_PLANAR = MKBETAG(24,'P','S','P'),
+    AV_CODEC_ID_PCM_S32LE_PLANAR = MKBETAG(32,'P','S','P'),
+    AV_CODEC_ID_PCM_S16BE_PLANAR = MKBETAG('P','S','P',16),
 
     /* various ADPCM codecs */
     AV_CODEC_ID_ADPCM_IMA_QT = 0x11000,
@@ -346,6 +352,8 @@
     AV_CODEC_ID_ADPCM_G722,
     AV_CODEC_ID_ADPCM_IMA_APC,
     AV_CODEC_ID_VIMA       = MKBETAG('V','I','M','A'),
+    AV_CODEC_ID_ADPCM_AFC  = MKBETAG('A','F','C',' '),
+    AV_CODEC_ID_ADPCM_IMA_OKI = MKBETAG('O','K','I',' '),
 
     /* AMR */
     AV_CODEC_ID_AMR_NB = 0x12000,
@@ -424,12 +432,14 @@
     AV_CODEC_ID_IAC,
     AV_CODEC_ID_ILBC,
     AV_CODEC_ID_OPUS_DEPRECATED,
+    AV_CODEC_ID_COMFORT_NOISE,
     AV_CODEC_ID_FFWAVESYNTH = MKBETAG('F','F','W','S'),
     AV_CODEC_ID_8SVX_RAW    = MKBETAG('8','S','V','X'),
     AV_CODEC_ID_SONIC       = MKBETAG('S','O','N','C'),
     AV_CODEC_ID_SONIC_LS    = MKBETAG('S','O','N','L'),
     AV_CODEC_ID_PAF_AUDIO   = MKBETAG('P','A','F','A'),
     AV_CODEC_ID_OPUS        = MKBETAG('O','P','U','S'),
+    AV_CODEC_ID_TAK         = MKBETAG('t','B','a','K'),
 
     /* subtitle codecs */
     AV_CODEC_ID_FIRST_SUBTITLE = 0x17000,          ///< A dummy ID pointing at the start of subtitle codecs.
@@ -939,8 +949,47 @@
      * @endcode
      */
     AV_PKT_DATA_JP_DUALMONO,
+
+    /**
+     * A list of zero terminated key/value strings. There is no end marker for
+     * the list, so it is required to rely on the side data size to stop.
+     */
+    AV_PKT_DATA_STRINGS_METADATA,
+
+    /**
+     * Subtitle event position
+     * @code
+     * u32le x1
+     * u32le y1
+     * u32le x2
+     * u32le y2
+     * @endcode
+     */
+    AV_PKT_DATA_SUBTITLE_POSITION,
 };
 
+/**
+ * This structure stores compressed data. It is typically exported by demuxers
+ * and then passed as input to decoders, or received as output from encoders and
+ * then passed to muxers.
+ *
+ * For video, it should typically contain one compressed frame. For audio it may
+ * contain several compressed frames.
+ *
+ * AVPacket is one of the few structs in FFmpeg, whose size is a part of public
+ * ABI. Thus it may be allocated on stack and no new fields can be added to it
+ * without libavcodec and libavformat major bump.
+ *
+ * The semantics of data ownership depends on the destruct field.
+ * If it is set, the packet data is dynamically allocated and is valid
+ * indefinitely until av_free_packet() is called (which in turn calls the
+ * destruct callback to free the data). If destruct is not set, the packet data
+ * is typically backed by some static buffer somewhere and is only valid for a
+ * limited time (e.g. until the next read call when demuxing).
+ *
+ * The side data is always allocated with av_malloc() and is freed in
+ * av_free_packet().
+ */
 typedef struct AVPacket {
     /**
      * Presentation timestamp in AVStream->time_base units; the time at which
@@ -1063,7 +1112,7 @@
      * extended_data must be used by the decoder in order to access all
      * channels.
      *
-     * encoding: unused
+     * encoding: set by user
      * decoding: set by AVCodecContext.get_buffer()
      */
     uint8_t **extended_data;
@@ -1084,7 +1133,7 @@
 
     /**
      * format of the frame, -1 if unknown or unset
-     * Values correspond to enum PixelFormat for video frames,
+     * Values correspond to enum AVPixelFormat for video frames,
      * enum AVSampleFormat for audio)
      * - encoding: unused
      * - decoding: Read by user.
@@ -1598,6 +1647,8 @@
     int ticks_per_frame;
 
     /**
+     * Codec delay.
+     *
      * Encoding: Number of frames delay there will be from the encoder input to
      *           the decoder output. (we assume the decoder matches the spec)
      * Decoding: Number of frames delay in addition to what a standard decoder
@@ -1651,13 +1702,13 @@
     int gop_size;
 
     /**
-     * Pixel format, see PIX_FMT_xxx.
+     * Pixel format, see AV_PIX_FMT_xxx.
      * May be set by the demuxer if known from headers.
      * May be overridden by the decoder if it knows better.
      * - encoding: Set by user.
      * - decoding: Set by user if known, overridden by libavcodec if known
      */
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
 
     /**
      * Motion estimation algorithm used for video coding.
@@ -1704,7 +1755,7 @@
      * - encoding: unused
      * - decoding: Set by user, if not set the native format will be chosen.
      */
-    enum PixelFormat (*get_format)(struct AVCodecContext *s, const enum PixelFormat * fmt);
+    enum AVPixelFormat (*get_format)(struct AVCodecContext *s, const enum AVPixelFormat * fmt);
 
     /**
      * maximum number of B-frames between non-B-frames
@@ -2223,7 +2274,7 @@
 
     /** Field order
      * - encoding: set by libavcodec
-     * - decoding: Set by libavcodec
+     * - decoding: Set by user.
      */
     enum AVFieldOrder field_order;
 
@@ -2240,7 +2291,13 @@
 
     /* The following data should not be initialized. */
     /**
-     * Samples per packet, initialized when calling 'init'.
+     * Number of samples per channel in an audio frame.
+     *
+     * - encoding: set by libavcodec in avcodec_open2(). Each submitted frame
+     *   except the last must contain exactly frame_size samples per channel.
+     *   May be 0 when the codec has CODEC_CAP_VARIABLE_FRAME_SIZE set, then the
+     *   frame size is not restricted.
+     * - decoding: may be set by some decoders to indicate constant frame size
      */
     int frame_size;
 
@@ -2349,7 +2406,12 @@
      *
      * Decoders cannot use the buffer after returning from
      * avcodec_decode_audio4(), so they will not call release_buffer(), as it
-     * is assumed to be released immediately upon return.
+     * is assumed to be released immediately upon return. In some rare cases,
+     * a decoder may need to call get_buffer() more than once in a single
+     * call to avcodec_decode_audio4(). In that case, when get_buffer() is
+     * called again after it has already been called once, the previously
+     * acquired buffer is assumed to be released at that time and may not be
+     * reused by the decoder.
      *
      * As a convenience, av_samples_get_buffer_size() and
      * av_samples_fill_arrays() in libavutil may be used by custom get_buffer()
@@ -2786,7 +2848,9 @@
 #define FF_IDCT_SIMPLE        2
 #define FF_IDCT_SIMPLEMMX     3
 #define FF_IDCT_LIBMPEG2MMX   4
+#if FF_API_MMI
 #define FF_IDCT_MMI           5
+#endif
 #define FF_IDCT_ARM           7
 #define FF_IDCT_ALTIVEC       8
 #define FF_IDCT_SH4           9
@@ -3086,6 +3150,13 @@
     int64_t pts_correction_num_faulty_dts; /// Number of incorrect DTS values so far
     int64_t pts_correction_last_pts;       /// PTS of the last frame
     int64_t pts_correction_last_dts;       /// DTS of the last frame
+
+    /**
+     * Current frame metadata.
+     * - decoding: maintained and used by libavcodec, not intended to be used by user apps
+     * - encoding: unused
+     */
+    AVDictionary *metadata;
 } AVCodecContext;
 
 AVRational av_codec_get_pkt_timebase         (const AVCodecContext *avctx);
@@ -3130,7 +3201,7 @@
      */
     int capabilities;
     const AVRational *supported_framerates; ///< array of supported framerates, or NULL if any, array is terminated by {0,0}
-    const enum PixelFormat *pix_fmts;       ///< array of supported pixel formats, or NULL if unknown, array is terminated by -1
+    const enum AVPixelFormat *pix_fmts;     ///< array of supported pixel formats, or NULL if unknown, array is terminated by -1
     const int *supported_samplerates;       ///< array of supported audio samplerates, or NULL if unknown, array is terminated by 0
     const enum AVSampleFormat *sample_fmts; ///< array of supported sample formats, or NULL if unknown, array is terminated by -1
     const uint64_t *channel_layouts;         ///< array of support channel layouts, or NULL if unknown. array is terminated by 0
@@ -3231,7 +3302,7 @@
      *
      * Only hardware accelerated formats are supported here.
      */
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
 
     /**
      * Hardware accelerated codec capabilities.
@@ -3329,6 +3400,8 @@
     SUBTITLE_ASS,
 };
 
+#define AV_SUBTITLE_FLAG_FORCED 0x00000001
+
 typedef struct AVSubtitleRect {
     int x;         ///< top left corner  of pict, undefined when pict is not set
     int y;         ///< top left corner  of pict, undefined when pict is not set
@@ -3352,11 +3425,7 @@
      */
     char *ass;
 
-    /**
-     * 1 indicates this subtitle is a forced subtitle.
-     * A forced subtitle should be displayed even when subtitles are hidden.
-     */
-    int forced;
+    int flags;
 } AVSubtitleRect;
 
 typedef struct AVSubtitle {
@@ -4153,6 +4222,10 @@
                      int64_t pts, int64_t dts,
                      int64_t pos);
 
+/**
+ * @return 0 if the output buffer is a subset of the input, 1 if it is allocated and must be freed
+ * @deprecated use AVBitstreamFilter
+ */
 int av_parser_change(AVCodecParserContext *s,
                      AVCodecContext *avctx,
                      uint8_t **poutbuf, int *poutbuf_size,
@@ -4322,9 +4395,11 @@
  * @}
  */
 
+#if FF_API_AVCODEC_RESAMPLE
 /**
  * @defgroup lavc_resample Audio resampling
  * @ingroup libavc
+ * @deprecated use libswresample instead
  *
  * @{
  */
@@ -4349,6 +4424,7 @@
  * @param cutoff           cutoff frequency, 1.0 corresponds to half the output sampling rate
  * @return allocated ReSampleContext, NULL if error occurred
  */
+attribute_deprecated
 ReSampleContext *av_audio_resample_init(int output_channels, int input_channels,
                                         int output_rate, int input_rate,
                                         enum AVSampleFormat sample_fmt_out,
@@ -4356,6 +4432,7 @@
                                         int filter_length, int log2_phase_count,
                                         int linear, double cutoff);
 
+attribute_deprecated
 int audio_resample(ReSampleContext *s, short *output, short *input, int nb_samples);
 
 /**
@@ -4364,6 +4441,7 @@
  * @param s a non-NULL pointer to a resample context previously
  *          created with av_audio_resample_init()
  */
+attribute_deprecated
 void audio_resample_close(ReSampleContext *s);
 
 
@@ -4376,6 +4454,7 @@
                  between the 2 closest, if 0 the closest will be used
  * @param cutoff cutoff frequency, 1.0 corresponds to half the output sampling rate
  */
+attribute_deprecated
 struct AVResampleContext *av_resample_init(int out_rate, int in_rate, int filter_length, int log2_phase_count, int linear, double cutoff);
 
 /**
@@ -4387,6 +4466,7 @@
  * @param update_ctx If this is 0 then the context will not be modified, that way several channels can be resampled with the same context.
  * @return the number of samples written in dst or -1 if an error occurred
  */
+attribute_deprecated
 int av_resample(struct AVResampleContext *c, short *dst, short *src, int *consumed, int src_size, int dst_size, int update_ctx);
 
 
@@ -4402,12 +4482,15 @@
  * note, due to rounding the actual compensation might be slightly different,
  * especially if the compensation_distance is large and the in_rate used during init is small
  */
+attribute_deprecated
 void av_resample_compensate(struct AVResampleContext *c, int sample_delta, int compensation_distance);
+attribute_deprecated
 void av_resample_close(struct AVResampleContext *c);
 
 /**
  * @}
  */
+#endif
 
 /**
  * @addtogroup lavc_picture
@@ -4425,7 +4508,7 @@
  * @param height the height of the picture
  * @return zero if successful, a negative value if not
  */
-int avpicture_alloc(AVPicture *picture, enum PixelFormat pix_fmt, int width, int height);
+int avpicture_alloc(AVPicture *picture, enum AVPixelFormat pix_fmt, int width, int height);
 
 /**
  * Free a picture previously allocated by avpicture_alloc().
@@ -4442,8 +4525,8 @@
  *
  * @see av_image_fill_arrays()
  */
-int avpicture_fill(AVPicture *picture, uint8_t *ptr,
-                   enum PixelFormat pix_fmt, int width, int height);
+int avpicture_fill(AVPicture *picture, const uint8_t *ptr,
+                   enum AVPixelFormat pix_fmt, int width, int height);
 
 /**
  * Copy pixel data from an AVPicture into a buffer, always assume a
@@ -4451,7 +4534,8 @@
  *
  * @see av_image_copy_to_buffer()
  */
-int avpicture_layout(const AVPicture* src, enum PixelFormat pix_fmt, int width, int height,
+int avpicture_layout(const AVPicture* src, enum AVPixelFormat pix_fmt,
+                     int width, int height,
                      unsigned char *dest, int dest_size);
 
 /**
@@ -4461,29 +4545,29 @@
  *
  * @see av_image_get_buffer_size().
  */
-int avpicture_get_size(enum PixelFormat pix_fmt, int width, int height);
+int avpicture_get_size(enum AVPixelFormat pix_fmt, int width, int height);
 
 /**
  *  deinterlace - if not supported return -1
  */
 int avpicture_deinterlace(AVPicture *dst, const AVPicture *src,
-                          enum PixelFormat pix_fmt, int width, int height);
+                          enum AVPixelFormat pix_fmt, int width, int height);
 /**
  * Copy image src to dst. Wraps av_image_copy().
  */
 void av_picture_copy(AVPicture *dst, const AVPicture *src,
-                     enum PixelFormat pix_fmt, int width, int height);
+                     enum AVPixelFormat pix_fmt, int width, int height);
 
 /**
  * Crop image top and left side.
  */
 int av_picture_crop(AVPicture *dst, const AVPicture *src,
-                    enum PixelFormat pix_fmt, int top_band, int left_band);
+                    enum AVPixelFormat pix_fmt, int top_band, int left_band);
 
 /**
  * Pad image.
  */
-int av_picture_pad(AVPicture *dst, const AVPicture *src, int height, int width, enum PixelFormat pix_fmt,
+int av_picture_pad(AVPicture *dst, const AVPicture *src, int height, int width, enum AVPixelFormat pix_fmt,
             int padtop, int padbottom, int padleft, int padright, int *color);
 
 /**
@@ -4506,14 +4590,29 @@
  * @{
  */
 
-void avcodec_get_chroma_sub_sample(enum PixelFormat pix_fmt, int *h_shift, int *v_shift);
+/**
+ * Utility function to access log2_chroma_w log2_chroma_h from
+ * the pixel format AVPixFmtDescriptor.
+ *
+ * This function asserts that pix_fmt is valid. See av_pix_fmt_get_chroma_sub_sample
+ * for one that returns a failure code and continues in case of invalid
+ * pix_fmts.
+ *
+ * @param[in]  pix_fmt the pixel format
+ * @param[out] h_shift store log2_chroma_h
+ * @param[out] v_shift store log2_chroma_w
+ *
+ * @see av_pix_fmt_get_chroma_sub_sample
+ */
+
+void avcodec_get_chroma_sub_sample(enum AVPixelFormat pix_fmt, int *h_shift, int *v_shift);
 
 /**
  * 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);
+unsigned int avcodec_pix_fmt_to_codec_tag(enum AVPixelFormat pix_fmt);
 
 #define FF_LOSS_RESOLUTION  0x0001 /**< loss due to resolution change */
 #define FF_LOSS_DEPTH       0x0002 /**< loss due to color depth change */
@@ -4540,7 +4639,7 @@
  * @return Combination of flags informing you what kind of losses will occur
  * (maximum loss for an invalid dst_pix_fmt).
  */
-int avcodec_get_pix_fmt_loss(enum PixelFormat dst_pix_fmt, enum PixelFormat src_pix_fmt,
+int avcodec_get_pix_fmt_loss(enum AVPixelFormat dst_pix_fmt, enum AVPixelFormat src_pix_fmt,
                              int has_alpha);
 
 #if FF_API_FIND_BEST_PIX_FMT
@@ -4559,8 +4658,8 @@
  * Note, only the first 64 pixel formats will fit in pix_fmt_mask.
  *
  * @code
- * src_pix_fmt = PIX_FMT_YUV420P;
- * pix_fmt_mask = (1 << PIX_FMT_YUV422P) | (1 << PIX_FMT_RGB24);
+ * src_pix_fmt = AV_PIX_FMT_YUV420P;
+ * pix_fmt_mask = (1 << AV_PIX_FMT_YUV422P) | (1 << AV_PIX_FMT_RGB24);
  * dst_pix_fmt = avcodec_find_best_pix_fmt(pix_fmt_mask, src_pix_fmt, alpha, &loss);
  * @endcode
  *
@@ -4571,7 +4670,7 @@
  * @return The best pixel format to convert to or -1 if none was found.
  */
 attribute_deprecated
-enum PixelFormat avcodec_find_best_pix_fmt(int64_t pix_fmt_mask, enum PixelFormat src_pix_fmt,
+enum AVPixelFormat avcodec_find_best_pix_fmt(int64_t pix_fmt_mask, enum AVPixelFormat src_pix_fmt,
                               int has_alpha, int *loss_ptr);
 #endif /* FF_API_FIND_BEST_PIX_FMT */
 
@@ -4586,14 +4685,14 @@
  * pix_fmt_list parameter.
  *
  *
- * @param[in] pix_fmt_list PIX_FMT_NONE terminated array of pixel formats to choose from
+ * @param[in] pix_fmt_list AV_PIX_FMT_NONE terminated array of pixel formats to choose from
  * @param[in] src_pix_fmt source pixel format
  * @param[in] has_alpha Whether the source pixel format alpha channel is used.
  * @param[out] loss_ptr Combination of flags informing you what kind of losses will occur.
  * @return The best pixel format to convert to or -1 if none was found.
  */
-enum PixelFormat avcodec_find_best_pix_fmt_of_list(enum PixelFormat *pix_fmt_list,
-                                            enum PixelFormat src_pix_fmt,
+enum AVPixelFormat avcodec_find_best_pix_fmt_of_list(enum AVPixelFormat *pix_fmt_list,
+                                            enum AVPixelFormat src_pix_fmt,
                                             int has_alpha, int *loss_ptr);
 
 /**
@@ -4604,14 +4703,14 @@
  * converting from some formats to other formats. avcodec_find_best_pix_fmt_of_2() selects which of
  * the given pixel formats should be used to suffer the least amount of loss.
  *
- * If one of the destination formats is PIX_FMT_NONE the other pixel format (if valid) will be
+ * If one of the destination formats is AV_PIX_FMT_NONE the other pixel format (if valid) will be
  * returned.
  *
  * @code
- * src_pix_fmt = PIX_FMT_YUV420P;
- * dst_pix_fmt1= PIX_FMT_RGB24;
- * dst_pix_fmt2= PIX_FMT_GRAY8;
- * dst_pix_fmt3= PIX_FMT_RGB8;
+ * src_pix_fmt = AV_PIX_FMT_YUV420P;
+ * dst_pix_fmt1= AV_PIX_FMT_RGB24;
+ * dst_pix_fmt2= AV_PIX_FMT_GRAY8;
+ * dst_pix_fmt3= AV_PIX_FMT_RGB8;
  * loss= FF_LOSS_CHROMA; // don't care about chroma loss, so chroma loss will be ignored.
  * dst_pix_fmt = avcodec_find_best_pix_fmt_of_2(dst_pix_fmt1, dst_pix_fmt2, src_pix_fmt, alpha, &loss);
  * dst_pix_fmt = avcodec_find_best_pix_fmt_of_2(dst_pix_fmt, dst_pix_fmt3, src_pix_fmt, alpha, &loss);
@@ -4626,21 +4725,21 @@
  *                               that occurs when converting from src to selected dst pixel format.
  * @return The best pixel format to convert to or -1 if none was found.
  */
-enum PixelFormat avcodec_find_best_pix_fmt_of_2(enum PixelFormat dst_pix_fmt1, enum PixelFormat dst_pix_fmt2,
-                                            enum PixelFormat src_pix_fmt, int has_alpha, int *loss_ptr);
+enum AVPixelFormat avcodec_find_best_pix_fmt_of_2(enum AVPixelFormat dst_pix_fmt1, enum AVPixelFormat dst_pix_fmt2,
+                                            enum AVPixelFormat src_pix_fmt, int has_alpha, int *loss_ptr);
 
 attribute_deprecated
 #if AV_HAVE_INCOMPATIBLE_FORK_ABI
-enum PixelFormat avcodec_find_best_pix_fmt2(enum PixelFormat *pix_fmt_list,
-                                            enum PixelFormat src_pix_fmt,
-                                            int has_alpha, int *loss_ptr);
+enum AVPixelFormat avcodec_find_best_pix_fmt2(enum AVPixelFormat *pix_fmt_list,
+                                              enum AVPixelFormat src_pix_fmt,
+                                              int has_alpha, int *loss_ptr);
 #else
-enum PixelFormat avcodec_find_best_pix_fmt2(enum PixelFormat dst_pix_fmt1, enum PixelFormat dst_pix_fmt2,
-                                            enum PixelFormat src_pix_fmt, int has_alpha, int *loss_ptr);
+enum AVPixelFormat avcodec_find_best_pix_fmt2(enum AVPixelFormat dst_pix_fmt1, enum AVPixelFormat dst_pix_fmt2,
+                                            enum AVPixelFormat src_pix_fmt, int has_alpha, int *loss_ptr);
 #endif
 
 
-enum PixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum PixelFormat * fmt);
+enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat * fmt);
 
 /**
  * @}
@@ -4686,7 +4785,9 @@
  * @param buf         buffer to use for frame data
  * @param buf_size    size of buffer
  * @param align       plane size sample alignment (0 = default)
- * @return            0 on success, negative error code on failure
+ * @return            >=0 on success, negative error code on failure
+ * @todo return the size of the allocated frame size in case of
+ * success, at the next libavutil bump
  */
 int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels,
                              enum AVSampleFormat sample_fmt, const uint8_t *buf,
diff --git a/libavcodec/avpicture.c b/libavcodec/avpicture.c
new file mode 100644
index 0000000..a6f89ef
--- /dev/null
+++ b/libavcodec/avpicture.c
@@ -0,0 +1,78 @@
+/*
+ * AVPicture management routines
+ * 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
+ * AVPicture management routines
+ */
+
+#include "avcodec.h"
+#include "internal.h"
+#include "libavutil/common.h"
+#include "libavutil/pixdesc.h"
+#include "libavutil/imgutils.h"
+#include "libavutil/colorspace.h"
+
+int avpicture_fill(AVPicture *picture, const uint8_t *ptr,
+                   enum AVPixelFormat pix_fmt, int width, int height)
+{
+    return av_image_fill_arrays(picture->data, picture->linesize,
+                                ptr, pix_fmt, width, height, 1);
+}
+
+int avpicture_layout(const AVPicture* src, enum AVPixelFormat pix_fmt, int width, int height,
+                     unsigned char *dest, int dest_size)
+{
+    return av_image_copy_to_buffer(dest, dest_size,
+                                   (const uint8_t * const*)src->data, src->linesize,
+                                   pix_fmt, width, height, 1);
+}
+
+int avpicture_get_size(enum AVPixelFormat pix_fmt, int width, int height)
+{
+    return av_image_get_buffer_size(pix_fmt, width, height, 1);
+}
+
+int avpicture_alloc(AVPicture *picture,
+                    enum AVPixelFormat pix_fmt, int width, int height)
+{
+    int ret = av_image_alloc(picture->data, picture->linesize,
+                             width, height, pix_fmt, 1);
+    if (ret < 0) {
+        memset(picture, 0, sizeof(AVPicture));
+        return ret;
+    }
+
+    return 0;
+}
+
+void avpicture_free(AVPicture *picture)
+{
+    av_free(picture->data[0]);
+}
+
+void av_picture_copy(AVPicture *dst, const AVPicture *src,
+                     enum AVPixelFormat pix_fmt, int width, int height)
+{
+    av_image_copy(dst->data, dst->linesize, (const uint8_t **)src->data,
+                  src->linesize, pix_fmt, width, height);
+}
+
diff --git a/libavcodec/avrndec.c b/libavcodec/avrndec.c
index cda360d..2205a42 100644
--- a/libavcodec/avrndec.c
+++ b/libavcodec/avrndec.c
@@ -22,6 +22,7 @@
 #include "avcodec.h"
 #include "mjpeg.h"
 #include "mjpegdec.h"
+#include "libavutil/imgutils.h"
 
 typedef struct {
     MJpegDecodeContext mjpeg_ctx;
@@ -34,18 +35,24 @@
 static av_cold int init(AVCodecContext *avctx)
 {
     AVRnContext *a = avctx->priv_data;
+    int ret;
 
     // Support "Resolution 1:1" for Avid AVI Codec
     a->is_mjpeg = avctx->extradata_size < 31 || memcmp(&avctx->extradata[28], "1:1", 3);
 
+    if(!a->is_mjpeg && avctx->lowres) {
+        av_log(avctx, AV_LOG_ERROR, "lowres is not possible with rawvideo\n");
+        return AVERROR(EINVAL);
+    }
+
     if(a->is_mjpeg)
         return ff_mjpeg_decode_init(avctx);
 
-    if(avctx->width <= 0 || avctx->height <= 0)
-        return -1;
+    if ((ret = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0)
+        return ret;
 
     avcodec_get_frame_defaults(&a->frame);
-    avctx->pix_fmt = PIX_FMT_UYVY422;
+    avctx->pix_fmt = AV_PIX_FMT_UYVY422;
 
     if(avctx->extradata_size >= 9 && avctx->extradata[4]+28 < avctx->extradata_size) {
         int ndx = avctx->extradata[4] + 4;
@@ -78,12 +85,12 @@
     AVFrame *p = &a->frame;
     const uint8_t *buf = avpkt->data;
     int buf_size       = avpkt->size;
-    int true_height    = buf_size / (2*avctx->width);
-    int y;
+    int y, ret, true_height;
 
     if(a->is_mjpeg)
         return ff_mjpeg_decode_frame(avctx, data, data_size, avpkt);
 
+    true_height    = buf_size / (2*avctx->width);
     if(p->data[0])
         avctx->release_buffer(avctx, p);
 
@@ -92,9 +99,9 @@
         return AVERROR_INVALIDDATA;
     }
 
-    if(avctx->get_buffer(avctx, p) < 0){
+    if((ret = avctx->get_buffer(avctx, p)) < 0){
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
+        return ret;
     }
     p->pict_type= AV_PICTURE_TYPE_I;
     p->key_frame= 1;
@@ -129,5 +136,6 @@
     .decode         = decode_frame,
     .long_name      = NULL_IF_CONFIG_SMALL("Avid AVI Codec"),
     .capabilities   = CODEC_CAP_DR1,
+    .max_lowres     = 3,
 };
 
diff --git a/libavcodec/avs.c b/libavcodec/avs.c
index 76e8a9a..4b05bf9 100644
--- a/libavcodec/avs.c
+++ b/libavcodec/avs.c
@@ -87,7 +87,7 @@
         buf += 4;
         for (i=first; i<last; i++, buf+=3) {
             pal[i] = (buf[0] << 18) | (buf[1] << 10) | (buf[2] << 2);
-            pal[i] |= 0xFF << 24 | (pal[i] >> 6) & 0x30303;
+            pal[i] |= 0xFFU << 24 | (pal[i] >> 6) & 0x30303;
         }
 
         sub_type = buf[0];
@@ -160,7 +160,7 @@
 static av_cold int avs_decode_init(AVCodecContext * avctx)
 {
     AvsContext *const avs = avctx->priv_data;
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
     avcodec_get_frame_defaults(&avs->picture);
     avcodec_set_dimensions(avctx, 318, 198);
     return 0;
diff --git a/libavcodec/avuidec.c b/libavcodec/avuidec.c
index ba07a58..52d8090 100644
--- a/libavcodec/avuidec.c
+++ b/libavcodec/avuidec.c
@@ -25,7 +25,7 @@
 
 static av_cold int avui_decode_init(AVCodecContext *avctx)
 {
-    avctx->pix_fmt = PIX_FMT_YUVA422P;
+    avctx->pix_fmt = AV_PIX_FMT_YUVA422P;
 
     avctx->coded_frame = avcodec_alloc_frame();
 
@@ -151,5 +151,5 @@
     .decode       = avui_decode_frame,
     .close        = avui_decode_close,
     .capabilities = CODEC_CAP_DR1,
-    .long_name    = NULL_IF_CONFIG_SMALL("AVID Meridien"),
+    .long_name    = NULL_IF_CONFIG_SMALL("Avid Meridien Uncompressed"),
 };
diff --git a/libavcodec/avuienc.c b/libavcodec/avuienc.c
index 686e52c..4428232 100644
--- a/libavcodec/avuienc.c
+++ b/libavcodec/avuienc.c
@@ -108,6 +108,6 @@
     .encode2      = avui_encode_frame,
     .close        = avui_encode_close,
     .capabilities = CODEC_CAP_EXPERIMENTAL,
-    .pix_fmts     = (const enum PixelFormat[]){ PIX_FMT_UYVY422, PIX_FMT_NONE },
+    .pix_fmts     = (const enum AVPixelFormat[]){ AV_PIX_FMT_UYVY422, AV_PIX_FMT_NONE },
     .long_name    = NULL_IF_CONFIG_SMALL("Avid Meridien Uncompressed"),
 };
diff --git a/libavcodec/bethsoftvideo.c b/libavcodec/bethsoftvideo.c
index 39a0047..8eec5b7 100644
--- a/libavcodec/bethsoftvideo.c
+++ b/libavcodec/bethsoftvideo.c
@@ -44,7 +44,7 @@
     vid->frame.reference = 3;
     vid->frame.buffer_hints = FF_BUFFER_HINTS_VALID |
         FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
     return 0;
 }
 
@@ -77,9 +77,9 @@
     int code, ret;
     int yoffset;
 
-    if (avctx->reget_buffer(avctx, &vid->frame)) {
+    if ((ret = avctx->reget_buffer(avctx, &vid->frame)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
-        return -1;
+        return ret;
     }
     wrap_to_next_line = vid->frame.linesize[0] - avctx->width;
 
@@ -107,7 +107,7 @@
         case VIDEO_YOFF_P_FRAME:
             yoffset = bytestream2_get_le16(&vid->g);
             if(yoffset >= avctx->height)
-                return -1;
+                return AVERROR_INVALIDDATA;
             dst += vid->frame.linesize[0] * yoffset;
     }
 
diff --git a/libavcodec/bfi.c b/libavcodec/bfi.c
index fc5523e..f7df68e 100644
--- a/libavcodec/bfi.c
+++ b/libavcodec/bfi.c
@@ -40,7 +40,7 @@
 static av_cold int bfi_decode_init(AVCodecContext *avctx)
 {
     BFIContext *bfi = avctx->priv_data;
-    avctx->pix_fmt  = PIX_FMT_PAL8;
+    avctx->pix_fmt  = AV_PIX_FMT_PAL8;
     avcodec_get_frame_defaults(&bfi->frame);
     bfi->dst        = av_mallocz(avctx->width * avctx->height);
     return 0;
@@ -82,7 +82,7 @@
         pal = (uint32_t *)bfi->frame.data[1];
         for (i = 0; i < avctx->extradata_size / 3; i++) {
             int shift = 16;
-            *pal = 0xFF << 24;
+            *pal = 0xFFU << 24;
             for (j = 0; j < 3; j++, shift -= 8)
                 *pal += ((avctx->extradata[i * 3 + j] << 2) |
                          (avctx->extradata[i * 3 + j] >> 4)) << shift;
diff --git a/libavcodec/bfin/Makefile b/libavcodec/bfin/Makefile
index 6b3e7cf..be81e6c 100644
--- a/libavcodec/bfin/Makefile
+++ b/libavcodec/bfin/Makefile
@@ -1,7 +1,8 @@
 OBJS += bfin/dsputil_bfin.o                                             \
         bfin/fdct_bfin.o                                                \
         bfin/idct_bfin.o                                                \
-        bfin/mpegvideo_bfin.o                                           \
         bfin/pixels_bfin.o                                              \
         bfin/vp3_bfin.o                                                 \
         bfin/vp3_idct_bfin.o                                            \
+
+OBJS-$(CONFIG_MPEGVIDEOENC)             += bfin/mpegvideo_bfin.o
diff --git a/libavcodec/bfin/pixels_bfin.S b/libavcodec/bfin/pixels_bfin.S
index 3b987ae..995d7b8 100644
--- a/libavcodec/bfin/pixels_bfin.S
+++ b/libavcodec/bfin/pixels_bfin.S
@@ -84,7 +84,7 @@
 DEFUN_END(add_pixels_clamped)
 
 
-/*
+/**
   motion compensation
   primitives
 
diff --git a/libavcodec/bgmc.c b/libavcodec/bgmc.c
index e4f937c..f48ac2e 100644
--- a/libavcodec/bgmc.c
+++ b/libavcodec/bgmc.c
@@ -458,16 +458,16 @@
 /** Initialize the lookup table arrays */
 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);
+    *cf_lut        = av_malloc(sizeof(**cf_lut)        * LUT_BUFF * 16 * LUT_SIZE);
+    *cf_lut_status = av_malloc(sizeof(**cf_lut_status) * LUT_BUFF);
 
-    if (!cf_lut || !cf_lut_status) {
+    if (!*cf_lut || !*cf_lut_status) {
         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);
+        memset(*cf_lut_status, -1, sizeof(**cf_lut_status) * LUT_BUFF);
     }
 
     return 0;
diff --git a/libavcodec/bink.c b/libavcodec/bink.c
index 024d289..bb202ca 100644
--- a/libavcodec/bink.c
+++ b/libavcodec/bink.c
@@ -674,6 +674,10 @@
         quant_idx = get_bits(gb, 4);
     } else {
         quant_idx = q;
+        if (quant_idx > 15U) {
+            av_log(NULL, AV_LOG_ERROR, "quant_index %d out of range\n", quant_idx);
+            return AVERROR_INVALIDDATA;
+        }
     }
 
     quant = quant_matrices[quant_idx];
@@ -1288,7 +1292,7 @@
         return 1;
     }
 
-    avctx->pix_fmt = c->has_alpha ? PIX_FMT_YUVA420P : PIX_FMT_YUV420P;
+    avctx->pix_fmt = c->has_alpha ? AV_PIX_FMT_YUVA420P : AV_PIX_FMT_YUV420P;
 
     avctx->idct_algo = FF_IDCT_BINK;
     ff_dsputil_init(&c->dsp, avctx);
@@ -1328,4 +1332,5 @@
     .close          = decode_end,
     .decode         = decode_frame,
     .long_name      = NULL_IF_CONFIG_SMALL("Bink video"),
+    .capabilities   = CODEC_CAP_DR1,
 };
diff --git a/libavcodec/binkaudio.c b/libavcodec/binkaudio.c
index 000895b..a1a91eb 100644
--- a/libavcodec/binkaudio.c
+++ b/libavcodec/binkaudio.c
@@ -28,6 +28,7 @@
  *  http://wiki.multimedia.cx/index.php?title=Bink_Audio
  */
 
+#include "libavutil/channel_layout.h"
 #include "avcodec.h"
 #define BITSTREAM_READER_LE
 #include "get_bits.h"
@@ -87,6 +88,8 @@
         av_log(avctx, AV_LOG_ERROR, "invalid number of channels: %d\n", avctx->channels);
         return AVERROR_INVALIDDATA;
     }
+    avctx->channel_layout = avctx->channels == 1 ? AV_CH_LAYOUT_MONO :
+                                                   AV_CH_LAYOUT_STEREO;
 
     s->version_b = avctx->extradata_size >= 4 && avctx->extradata[3] == 'b';
 
diff --git a/libavcodec/bintext.c b/libavcodec/bintext.c
index 8c12c59..9c36b6b 100644
--- a/libavcodec/bintext.c
+++ b/libavcodec/bintext.c
@@ -29,6 +29,7 @@
  */
 
 #include "libavutil/intreadwrite.h"
+#include "libavutil/xga_font_data.h"
 #include "avcodec.h"
 #include "cga_data.h"
 #include "bintext.h"
@@ -48,7 +49,7 @@
     uint8_t *p;
     int i;
 
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
     p = avctx->extradata;
     if (p) {
         s->font_height = p[0];
@@ -82,10 +83,10 @@
             av_log(avctx, AV_LOG_WARNING, "font height %i not supported\n", s->font_height);
             s->font_height = 8;
         case 8:
-            s->font = ff_cga_font;
+            s->font = avpriv_cga_font;
             break;
         case 16:
-            s->font = ff_vga16_font;
+            s->font = avpriv_vga16_font;
             break;
         }
     }
diff --git a/libavcodec/bitstream.c b/libavcodec/bitstream.c
index ce20f56..ce83ee0 100644
--- a/libavcodec/bitstream.c
+++ b/libavcodec/bitstream.c
@@ -30,6 +30,7 @@
 
 #include "libavutil/avassert.h"
 #include "avcodec.h"
+#include "mathops.h"
 #include "get_bits.h"
 #include "put_bits.h"
 
@@ -115,10 +116,10 @@
 }
 
 static av_always_inline uint32_t bitswap_32(uint32_t x) {
-    return (uint32_t)av_reverse[x&0xFF]<<24
-         | (uint32_t)av_reverse[(x>>8)&0xFF]<<16
-         | (uint32_t)av_reverse[(x>>16)&0xFF]<<8
-         | (uint32_t)av_reverse[x>>24];
+    return (uint32_t)ff_reverse[x&0xFF]<<24
+         | (uint32_t)ff_reverse[(x>>8)&0xFF]<<16
+         | (uint32_t)ff_reverse[(x>>16)&0xFF]<<8
+         | (uint32_t)ff_reverse[x>>24];
 }
 
 typedef struct {
diff --git a/libavcodec/bmp.c b/libavcodec/bmp.c
index 7e160ae..9aee375 100644
--- a/libavcodec/bmp.c
+++ b/libavcodec/bmp.c
@@ -118,7 +118,7 @@
 
     depth = bytestream_get_le16(&buf);
 
-    if(ihsize == 40 || ihsize == 64 || ihsize == 56)
+    if (ihsize >= 40)
         comp = bytestream_get_le32(&buf);
     else
         comp = BMP_RGB;
@@ -133,47 +133,46 @@
         rgb[0] = bytestream_get_le32(&buf);
         rgb[1] = bytestream_get_le32(&buf);
         rgb[2] = bytestream_get_le32(&buf);
-        if (ihsize >= 108)
-            alpha = bytestream_get_le32(&buf);
+        alpha = bytestream_get_le32(&buf);
     }
 
     avctx->width = width;
     avctx->height = height > 0? height: -height;
 
-    avctx->pix_fmt = PIX_FMT_NONE;
+    avctx->pix_fmt = AV_PIX_FMT_NONE;
 
     switch(depth){
     case 32:
         if(comp == BMP_BITFIELDS){
             if (rgb[0] == 0xFF000000 && rgb[1] == 0x00FF0000 && rgb[2] == 0x0000FF00)
-                avctx->pix_fmt = alpha ? PIX_FMT_ABGR : PIX_FMT_0BGR;
+                avctx->pix_fmt = alpha ? AV_PIX_FMT_ABGR : AV_PIX_FMT_0BGR;
             else if (rgb[0] == 0x00FF0000 && rgb[1] == 0x0000FF00 && rgb[2] == 0x000000FF)
-                avctx->pix_fmt = alpha ? PIX_FMT_BGRA : PIX_FMT_BGR0;
+                avctx->pix_fmt = alpha ? AV_PIX_FMT_BGRA : AV_PIX_FMT_BGR0;
             else if (rgb[0] == 0x0000FF00 && rgb[1] == 0x00FF0000 && rgb[2] == 0xFF000000)
-                avctx->pix_fmt = alpha ? PIX_FMT_ARGB : PIX_FMT_0RGB;
+                avctx->pix_fmt = alpha ? AV_PIX_FMT_ARGB : AV_PIX_FMT_0RGB;
             else if (rgb[0] == 0x000000FF && rgb[1] == 0x0000FF00 && rgb[2] == 0x00FF0000)
-                avctx->pix_fmt = alpha ? PIX_FMT_RGBA : PIX_FMT_RGB0;
+                avctx->pix_fmt = alpha ? AV_PIX_FMT_RGBA : AV_PIX_FMT_RGB0;
             else {
                 av_log(avctx, AV_LOG_ERROR, "Unknown bitfields %0X %0X %0X\n", rgb[0], rgb[1], rgb[2]);
                 return AVERROR(EINVAL);
             }
         } else {
-            avctx->pix_fmt = PIX_FMT_BGRA;
+            avctx->pix_fmt = AV_PIX_FMT_BGRA;
         }
         break;
     case 24:
-        avctx->pix_fmt = PIX_FMT_BGR24;
+        avctx->pix_fmt = AV_PIX_FMT_BGR24;
         break;
     case 16:
         if(comp == BMP_RGB)
-            avctx->pix_fmt = PIX_FMT_RGB555;
+            avctx->pix_fmt = AV_PIX_FMT_RGB555;
         else if (comp == BMP_BITFIELDS) {
             if (rgb[0] == 0xF800 && rgb[1] == 0x07E0 && rgb[2] == 0x001F)
-               avctx->pix_fmt = PIX_FMT_RGB565;
+               avctx->pix_fmt = AV_PIX_FMT_RGB565;
             else if (rgb[0] == 0x7C00 && rgb[1] == 0x03E0 && rgb[2] == 0x001F)
-               avctx->pix_fmt = PIX_FMT_RGB555;
+               avctx->pix_fmt = AV_PIX_FMT_RGB555;
             else if (rgb[0] == 0x0F00 && rgb[1] == 0x00F0 && rgb[2] == 0x000F)
-               avctx->pix_fmt = PIX_FMT_RGB444;
+               avctx->pix_fmt = AV_PIX_FMT_RGB444;
             else {
                av_log(avctx, AV_LOG_ERROR, "Unknown bitfields %0X %0X %0X\n", rgb[0], rgb[1], rgb[2]);
                return AVERROR(EINVAL);
@@ -182,14 +181,14 @@
         break;
     case 8:
         if(hsize - ihsize - 14 > 0)
-            avctx->pix_fmt = PIX_FMT_PAL8;
+            avctx->pix_fmt = AV_PIX_FMT_PAL8;
         else
-            avctx->pix_fmt = PIX_FMT_GRAY8;
+            avctx->pix_fmt = AV_PIX_FMT_GRAY8;
         break;
     case 1:
     case 4:
         if(hsize - ihsize - 14 > 0){
-            avctx->pix_fmt = PIX_FMT_PAL8;
+            avctx->pix_fmt = AV_PIX_FMT_PAL8;
         }else{
             av_log(avctx, AV_LOG_ERROR, "Unknown palette for %d-colour BMP\n", 1<<depth);
             return -1;
@@ -200,7 +199,7 @@
         return -1;
     }
 
-    if(avctx->pix_fmt == PIX_FMT_NONE){
+    if(avctx->pix_fmt == AV_PIX_FMT_NONE){
         av_log(avctx, AV_LOG_ERROR, "unsupported pixel format\n");
         return -1;
     }
@@ -240,7 +239,7 @@
         linesize = p->linesize[0];
     }
 
-    if(avctx->pix_fmt == PIX_FMT_PAL8){
+    if(avctx->pix_fmt == AV_PIX_FMT_PAL8){
         int colors = 1 << depth;
 
         memset(p->data[1], 0, 1024);
@@ -258,7 +257,7 @@
         buf = buf0 + 14 + ihsize; //palette location
         if((hsize-ihsize-14) < (colors << 2)){ // OS/2 bitmap, 3 bytes per palette entry
             for(i = 0; i < colors; i++)
-                ((uint32_t*)p->data[1])[i] = (0xff<<24) | bytestream_get_le24(&buf);
+                ((uint32_t*)p->data[1])[i] = (0xFFU<<24) | bytestream_get_le24(&buf);
         }else{
             for(i = 0; i < colors; i++)
                 ((uint32_t*)p->data[1])[i] = 0xFFU << 24 | bytestream_get_le32(&buf);
diff --git a/libavcodec/bmpenc.c b/libavcodec/bmpenc.c
index 3d329d1..bda6799 100644
--- a/libavcodec/bmpenc.c
+++ b/libavcodec/bmpenc.c
@@ -38,26 +38,26 @@
     avctx->coded_frame = &s->picture;
 
     switch (avctx->pix_fmt) {
-    case PIX_FMT_BGRA:
+    case AV_PIX_FMT_BGRA:
         avctx->bits_per_coded_sample = 32;
         break;
-    case PIX_FMT_BGR24:
+    case AV_PIX_FMT_BGR24:
         avctx->bits_per_coded_sample = 24;
         break;
-    case PIX_FMT_RGB555:
-    case PIX_FMT_RGB565:
-    case PIX_FMT_RGB444:
+    case AV_PIX_FMT_RGB555:
+    case AV_PIX_FMT_RGB565:
+    case AV_PIX_FMT_RGB444:
         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:
+    case AV_PIX_FMT_RGB8:
+    case AV_PIX_FMT_BGR8:
+    case AV_PIX_FMT_RGB4_BYTE:
+    case AV_PIX_FMT_BGR4_BYTE:
+    case AV_PIX_FMT_GRAY8:
+    case AV_PIX_FMT_PAL8:
         avctx->bits_per_coded_sample = 8;
         break;
-    case PIX_FMT_MONOBLACK:
+    case AV_PIX_FMT_MONOBLACK:
         avctx->bits_per_coded_sample = 1;
         break;
     default:
@@ -83,29 +83,29 @@
     p->pict_type= AV_PICTURE_TYPE_I;
     p->key_frame= 1;
     switch (avctx->pix_fmt) {
-    case PIX_FMT_RGB444:
+    case AV_PIX_FMT_RGB444:
         compression = BMP_BITFIELDS;
         pal = rgb444_masks; // abuse pal to hold color masks
         pal_entries = 3;
         break;
-    case PIX_FMT_RGB565:
+    case AV_PIX_FMT_RGB565:
         compression = BMP_BITFIELDS;
         pal = rgb565_masks; // abuse pal to hold color masks
         pal_entries = 3;
         break;
-    case PIX_FMT_RGB8:
-    case PIX_FMT_BGR8:
-    case PIX_FMT_RGB4_BYTE:
-    case PIX_FMT_BGR4_BYTE:
-    case PIX_FMT_GRAY8:
+    case AV_PIX_FMT_RGB8:
+    case AV_PIX_FMT_BGR8:
+    case AV_PIX_FMT_RGB4_BYTE:
+    case AV_PIX_FMT_BGR4_BYTE:
+    case AV_PIX_FMT_GRAY8:
         av_assert1(bit_count == 8);
-        ff_set_systematic_pal2(palette256, avctx->pix_fmt);
+        avpriv_set_systematic_pal2(palette256, avctx->pix_fmt);
         pal = palette256;
         break;
-    case PIX_FMT_PAL8:
+    case AV_PIX_FMT_PAL8:
         pal = (uint32_t *)p->data[1];
         break;
-    case PIX_FMT_MONOBLACK:
+    case AV_PIX_FMT_MONOBLACK:
         pal = monoblack_pal;
         break;
     }
@@ -172,12 +172,12 @@
     .priv_data_size = sizeof(BMPContext),
     .init           = bmp_encode_init,
     .encode2        = bmp_encode_frame,
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_BGRA, PIX_FMT_BGR24,
-        PIX_FMT_RGB565, PIX_FMT_RGB555, PIX_FMT_RGB444,
-        PIX_FMT_RGB8, PIX_FMT_BGR8, PIX_FMT_RGB4_BYTE, PIX_FMT_BGR4_BYTE, PIX_FMT_GRAY8, PIX_FMT_PAL8,
-        PIX_FMT_MONOBLACK,
-        PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_BGRA, AV_PIX_FMT_BGR24,
+        AV_PIX_FMT_RGB565, AV_PIX_FMT_RGB555, AV_PIX_FMT_RGB444,
+        AV_PIX_FMT_RGB8, AV_PIX_FMT_BGR8, AV_PIX_FMT_RGB4_BYTE, AV_PIX_FMT_BGR4_BYTE, AV_PIX_FMT_GRAY8, AV_PIX_FMT_PAL8,
+        AV_PIX_FMT_MONOBLACK,
+        AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("BMP (Windows and OS/2 bitmap)"),
 };
diff --git a/libavcodec/bmv.c b/libavcodec/bmv.c
index 5d33b91..fa44c6c 100644
--- a/libavcodec/bmv.c
+++ b/libavcodec/bmv.c
@@ -19,6 +19,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "avcodec.h"
 #include "bytestream.h"
 #include "libavutil/avassert.h"
@@ -187,8 +188,6 @@
                 memset(dst, val, len);
             }
             break;
-        default:
-            break;
         }
         if (dst == dst_end)
             return 0;
@@ -200,7 +199,7 @@
 {
     BMVDecContext * const c = avctx->priv_data;
     int type, scr_off;
-    int i;
+    int i, ret;
     uint8_t *srcptr, *outptr;
 
     c->stream = pkt->data;
@@ -227,7 +226,7 @@
             return AVERROR_INVALIDDATA;
         }
         for (i = 0; i < 256; i++)
-            c->pal[i] = 0xFF << 24 | bytestream_get_be24(&c->stream);
+            c->pal[i] = 0xFFU << 24 | bytestream_get_be24(&c->stream);
     }
     if (type & BMV_SCROLL) {
         if (c->stream - pkt->data > pkt->size - 2) {
@@ -241,6 +240,15 @@
         scr_off = 0;
     }
 
+    if (c->pic.data[0])
+        avctx->release_buffer(avctx, &c->pic);
+
+    c->pic.reference = 3;
+    if ((ret = avctx->get_buffer(avctx, &c->pic)) < 0) {
+        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+        return ret;
+    }
+
     if (decode_bmv_frame(c->stream, pkt->size - (c->stream - pkt->data), c->frame, scr_off)) {
         av_log(avctx, AV_LOG_ERROR, "Error decoding frame data\n");
         return AVERROR_INVALIDDATA;
@@ -270,19 +278,13 @@
     BMVDecContext * const c = avctx->priv_data;
 
     c->avctx = avctx;
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     if (avctx->width != SCREEN_WIDE || avctx->height != SCREEN_HIGH) {
         av_log(avctx, AV_LOG_ERROR, "Invalid dimension %dx%d\n", avctx->width, avctx->height);
         return AVERROR_INVALIDDATA;
     }
 
-    c->pic.reference = 1;
-    if (avctx->get_buffer(avctx, &c->pic) < 0) {
-        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
-    }
-
     c->frame = c->frame_base + 640;
 
     return 0;
@@ -310,12 +312,9 @@
 {
     BMVAudioDecContext *c = avctx->priv_data;
 
-    if (avctx->channels != 2) {
-        av_log(avctx, AV_LOG_INFO, "invalid number of channels\n");
-        return AVERROR(EINVAL);
-    }
-
-    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    avctx->channels       = 2;
+    avctx->channel_layout = AV_CH_LAYOUT_STEREO;
+    avctx->sample_fmt     = AV_SAMPLE_FMT_S16;
 
     avcodec_get_frame_defaults(&c->frame);
     avctx->coded_frame = &c->frame;
diff --git a/libavcodec/brender_pix.c b/libavcodec/brender_pix.c
new file mode 100644
index 0000000..886e8fb
--- /dev/null
+++ b/libavcodec/brender_pix.c
@@ -0,0 +1,244 @@
+/*
+ * BRender PIX (.pix) image decoder
+ * Copyright (c) 2012 Aleksi Nurmi
+ *
+ * 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
+ */
+
+/*
+ * Tested against samples from I-War / Independence War and Defiance.
+ * If the PIX file does not contain a palette, the
+ * palette_has_changed property of the AVFrame is set to 0.
+ */
+
+#include "libavutil/imgutils.h"
+#include "avcodec.h"
+#include "bytestream.h"
+
+typedef struct BRPixContext {
+    AVFrame frame;
+} BRPixContext;
+
+typedef struct BRPixHeader {
+    int format;
+    unsigned int width, height;
+} BRPixHeader;
+
+static av_cold int brpix_init(AVCodecContext *avctx)
+{
+    BRPixContext *s = avctx->priv_data;
+
+    avcodec_get_frame_defaults(&s->frame);
+    avctx->coded_frame = &s->frame;
+
+    return 0;
+}
+
+static int brpix_decode_header(BRPixHeader *out, GetByteContext *pgb)
+{
+    unsigned int header_len = bytestream2_get_be32(pgb);
+
+    out->format = bytestream2_get_byte(pgb);
+    bytestream2_skip(pgb, 2);
+    out->width = bytestream2_get_be16(pgb);
+    out->height = bytestream2_get_be16(pgb);
+
+    // the header is at least 11 bytes long; we read the first 7
+    if (header_len < 11) {
+        return 0;
+    }
+
+    // skip the rest of the header
+    bytestream2_skip(pgb, header_len-7);
+
+    return 1;
+}
+
+static int brpix_decode_frame(AVCodecContext *avctx,
+                              void *data, int *data_size_out,
+                              AVPacket *avpkt)
+{
+    BRPixContext *s = avctx->priv_data;
+    AVFrame *frame_out = data;
+
+    int ret;
+    GetByteContext gb;
+
+    unsigned int bytes_pp;
+
+    unsigned int magic[4];
+    unsigned int chunk_type;
+    unsigned int data_len;
+    BRPixHeader hdr;
+
+    bytestream2_init(&gb, avpkt->data, avpkt->size);
+
+    magic[0] = bytestream2_get_be32(&gb);
+    magic[1] = bytestream2_get_be32(&gb);
+    magic[2] = bytestream2_get_be32(&gb);
+    magic[3] = bytestream2_get_be32(&gb);
+
+    if (magic[0] != 0x12 ||
+        magic[1] != 0x8 ||
+        magic[2] != 0x2 ||
+        magic[3] != 0x2) {
+        av_log(avctx, AV_LOG_ERROR, "Not a BRender PIX file\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    chunk_type = bytestream2_get_be32(&gb);
+    if (chunk_type != 0x3 && chunk_type != 0x3d) {
+        av_log(avctx, AV_LOG_ERROR, "Invalid chunk type %d\n", chunk_type);
+        return AVERROR_INVALIDDATA;
+    }
+
+    ret = brpix_decode_header(&hdr, &gb);
+    if (!ret) {
+        av_log(avctx, AV_LOG_ERROR, "Invalid header length\n");
+        return AVERROR_INVALIDDATA;
+    }
+    switch (hdr.format) {
+    case 3:
+        avctx->pix_fmt = AV_PIX_FMT_PAL8;
+        bytes_pp = 1;
+        break;
+    case 4:
+        avctx->pix_fmt = AV_PIX_FMT_RGB555BE;
+        bytes_pp = 2;
+        break;
+    case 5:
+        avctx->pix_fmt = AV_PIX_FMT_RGB565BE;
+        bytes_pp = 2;
+        break;
+    case 6:
+        avctx->pix_fmt = AV_PIX_FMT_RGB24;
+        bytes_pp = 3;
+        break;
+    case 7:
+        avctx->pix_fmt = AV_PIX_FMT_0RGB;
+        bytes_pp = 4;
+        break;
+    case 18:
+        avctx->pix_fmt = AV_PIX_FMT_GRAY8A;
+        bytes_pp = 2;
+        break;
+    default:
+        av_log(avctx, AV_LOG_ERROR, "Format %d is not supported\n",
+                                    hdr.format);
+        return AVERROR_PATCHWELCOME;
+    }
+
+    if (s->frame.data[0])
+        avctx->release_buffer(avctx, &s->frame);
+
+    if (av_image_check_size(hdr.width, hdr.height, 0, avctx) < 0)
+        return AVERROR_INVALIDDATA;
+
+    if (hdr.width != avctx->width || hdr.height != avctx->height)
+        avcodec_set_dimensions(avctx, hdr.width, hdr.height);
+
+    if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
+        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+        return ret;
+    }
+
+    chunk_type = bytestream2_get_be32(&gb);
+
+    if (avctx->pix_fmt == AV_PIX_FMT_PAL8 &&
+        (chunk_type == 0x3 || chunk_type == 0x3d)) {
+        BRPixHeader palhdr;
+        uint32_t *pal_out = (uint32_t *)s->frame.data[1];
+        int i;
+
+        ret = brpix_decode_header(&palhdr, &gb);
+        if (!ret) {
+            av_log(avctx, AV_LOG_ERROR, "Invalid palette header length\n");
+            return AVERROR_INVALIDDATA;
+        }
+        if (palhdr.format != 7) {
+            av_log(avctx, AV_LOG_ERROR, "Palette is not in 0RGB format\n");
+            return AVERROR_INVALIDDATA;
+        }
+
+        chunk_type = bytestream2_get_be32(&gb);
+        data_len = bytestream2_get_be32(&gb);
+        bytestream2_skip(&gb, 8);
+        if (chunk_type != 0x21 || data_len != 1032 ||
+            bytestream2_get_bytes_left(&gb) < 1032) {
+            av_log(avctx, AV_LOG_ERROR, "Invalid palette data\n");
+            return AVERROR_INVALIDDATA;
+        }
+        // convert 0RGB to machine endian format (ARGB32)
+        for (i = 0; i < 256; ++i) {
+            bytestream2_skipu(&gb, 1);
+            *pal_out++ = (0xFFU << 24) | bytestream2_get_be24u(&gb);
+        }
+        bytestream2_skip(&gb, 8);
+
+        s->frame.palette_has_changed = 1;
+
+        chunk_type = bytestream2_get_be32(&gb);
+    }
+
+    data_len = bytestream2_get_be32(&gb);
+    bytestream2_skip(&gb, 8);
+
+    // read the image data to the buffer
+    {
+        unsigned int bytes_per_scanline = bytes_pp * hdr.width;
+        unsigned int bytes_left = bytestream2_get_bytes_left(&gb);
+
+        if (chunk_type != 0x21 || data_len != bytes_left ||
+            bytes_left / bytes_per_scanline < hdr.height)
+        {
+            av_log(avctx, AV_LOG_ERROR, "Invalid image data\n");
+            return AVERROR_INVALIDDATA;
+        }
+
+        av_image_copy_plane(s->frame.data[0], s->frame.linesize[0],
+                            avpkt->data + bytestream2_tell(&gb),
+                            bytes_per_scanline,
+                            bytes_per_scanline, hdr.height);
+    }
+
+    *frame_out = s->frame;
+    *data_size_out = sizeof(AVFrame);
+
+    return avpkt->size;
+}
+
+static av_cold int brpix_end(AVCodecContext *avctx)
+{
+    BRPixContext *s = avctx->priv_data;
+
+    if(s->frame.data[0])
+        avctx->release_buffer(avctx, &s->frame);
+
+    return 0;
+}
+
+AVCodec ff_brender_pix_decoder = {
+    .name           = "brender_pix",
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = AV_CODEC_ID_BRENDER_PIX,
+    .priv_data_size = sizeof(BRPixContext),
+    .init           = brpix_init,
+    .close          = brpix_end,
+    .decode         = brpix_decode_frame,
+    .capabilities   = CODEC_CAP_DR1,
+    .long_name      = NULL_IF_CONFIG_SMALL("BRender PIX image"),
+};
diff --git a/libavcodec/bytestream.h b/libavcodec/bytestream.h
index 39a1e28..af7f75b 100644
--- a/libavcodec/bytestream.h
+++ b/libavcodec/bytestream.h
@@ -29,11 +29,11 @@
 #include "libavutil/common.h"
 #include "libavutil/intreadwrite.h"
 
-typedef struct {
+typedef struct GetByteContext {
     const uint8_t *buffer, *buffer_end, *buffer_start;
 } GetByteContext;
 
-typedef struct {
+typedef struct PutByteContext {
     uint8_t *buffer, *buffer_end, *buffer_start;
     int eof;
 } PutByteContext;
diff --git a/libavcodec/c93.c b/libavcodec/c93.c
index 89f5933..b53ee1b 100644
--- a/libavcodec/c93.c
+++ b/libavcodec/c93.c
@@ -51,7 +51,7 @@
 
     avcodec_get_frame_defaults(&c93->pictures[0]);
     avcodec_get_frame_defaults(&c93->pictures[1]);
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
     return 0;
 }
 
@@ -83,7 +83,7 @@
     if (from_y + height > HEIGHT) {
         av_log(avctx, AV_LOG_ERROR, "invalid offset %d during C93 decoding\n",
                offset);
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     if (overflow > 0) {
@@ -127,16 +127,16 @@
     AVFrame *picture = data;
     GetByteContext gb;
     uint8_t *out;
-    int stride, i, x, y, b, bt = 0;
+    int stride, ret, i, x, y, b, bt = 0;
 
     c93->currentpic ^= 1;
 
     newpic->reference = 3;
     newpic->buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE |
                          FF_BUFFER_HINTS_REUSABLE | FF_BUFFER_HINTS_READABLE;
-    if (avctx->reget_buffer(avctx, newpic)) {
+    if ((ret = avctx->reget_buffer(avctx, newpic))) {
         av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
-        return -1;
+        return ret;
     }
 
     stride = newpic->linesize[0];
@@ -167,7 +167,7 @@
             case C93_8X8_FROM_PREV:
                 offset = bytestream2_get_le16(&gb);
                 if (copy_block(avctx, out, copy_from, offset, 8, stride))
-                    return -1;
+                    return AVERROR_INVALIDDATA;
                 break;
 
             case C93_4X4_FROM_CURR:
@@ -178,7 +178,7 @@
                         offset = bytestream2_get_le16(&gb);
                         if (copy_block(avctx, &out[j*stride+i],
                                            copy_from, offset, 4, stride))
-                            return -1;
+                            return AVERROR_INVALIDDATA;
                     }
                 }
                 break;
@@ -225,7 +225,7 @@
             default:
                 av_log(avctx, AV_LOG_ERROR, "unexpected type %x at %dx%d\n",
                        block_type, x, y);
-                return -1;
+                return AVERROR_INVALIDDATA;
             }
             bt >>= 4;
             out += 8;
diff --git a/libavcodec/cavs.c b/libavcodec/cavs.c
index 9e47163..65e12dd 100644
--- a/libavcodec/cavs.c
+++ b/libavcodec/cavs.c
@@ -712,7 +712,7 @@
     ff_cavsdsp_init(&h->cdsp, avctx);
     s->avctx = avctx;
 
-    avctx->pix_fmt= PIX_FMT_YUV420P;
+    avctx->pix_fmt= AV_PIX_FMT_YUV420P;
 
     h->luma_scan[0] = 0;
     h->luma_scan[1] = 8;
diff --git a/libavcodec/cavs.h b/libavcodec/cavs.h
index 461d7c8..039053d 100644
--- a/libavcodec/cavs.h
+++ b/libavcodec/cavs.h
@@ -152,7 +152,7 @@
   int8_t max_run;
 };
 
-typedef struct {
+typedef struct AVSContext {
     MpegEncContext s;
     CAVSDSPContext cdsp;
     Picture picture; ///< currently decoded frame
diff --git a/libavcodec/cavsdec.c b/libavcodec/cavsdec.c
index 4119303..02d0d81 100644
--- a/libavcodec/cavsdec.c
+++ b/libavcodec/cavsdec.c
@@ -1077,7 +1077,7 @@
     width  = get_bits(&s->gb, 14);
     height = get_bits(&s->gb, 14);
     if ((s->width || s->height) && (s->width != width || s->height != height)) {
-        av_log_missing_feature(s, "Width/height changing in CAVS is", 0);
+        av_log_missing_feature(s, "Width/height changing in CAVS", 0);
         return AVERROR_PATCHWELCOME;
     }
     if (width <= 0 || height <= 0) {
@@ -1097,8 +1097,8 @@
     s->low_delay =       get_bits1(&s->gb);
     h->mb_width  = (s->width  + 15) >> 4;
     h->mb_height = (s->height + 15) >> 4;
-    h->s.avctx->time_base.den = avpriv_frame_rate_tab[frame_rate_code].num;
-    h->s.avctx->time_base.num = avpriv_frame_rate_tab[frame_rate_code].den;
+    h->s.avctx->time_base.den = ff_mpeg12_frame_rate_tab[frame_rate_code].num;
+    h->s.avctx->time_base.num = ff_mpeg12_frame_rate_tab[frame_rate_code].den;
     h->s.avctx->width  = s->width;
     h->s.avctx->height = s->height;
     if(!h->top_qp)
diff --git a/libavcodec/cavsdsp.c b/libavcodec/cavsdsp.c
index 7eb8eca..a9b136e 100644
--- a/libavcodec/cavsdsp.c
+++ b/libavcodec/cavsdsp.c
@@ -546,5 +546,6 @@
     c->cavs_idct8_add = cavs_idct8_add_c;
     c->idct_perm = FF_NO_IDCT_PERM;
 
-    if (HAVE_MMX) ff_cavsdsp_init_mmx(c, avctx);
+    if (ARCH_X86)
+        ff_cavsdsp_init_x86(c, avctx);
 }
diff --git a/libavcodec/cavsdsp.h b/libavcodec/cavsdsp.h
index b281133..f6e3e18 100644
--- a/libavcodec/cavsdsp.h
+++ b/libavcodec/cavsdsp.h
@@ -37,6 +37,6 @@
 } CAVSDSPContext;
 
 void ff_cavsdsp_init(CAVSDSPContext* c, AVCodecContext *avctx);
-void ff_cavsdsp_init_mmx(CAVSDSPContext* c, AVCodecContext *avctx);
+void ff_cavsdsp_init_x86(CAVSDSPContext* c, AVCodecContext *avctx);
 
 #endif /* AVCODEC_CAVSDSP_H */
diff --git a/libavcodec/cdgraphics.c b/libavcodec/cdgraphics.c
index 8638dca..eb31532 100644
--- a/libavcodec/cdgraphics.c
+++ b/libavcodec/cdgraphics.c
@@ -86,7 +86,7 @@
 
     avctx->width   = CDG_FULL_WIDTH;
     avctx->height  = CDG_FULL_HEIGHT;
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     return 0;
 }
@@ -126,7 +126,7 @@
         r = ((color >> 8) & 0x000F) * 17;
         g = ((color >> 4) & 0x000F) * 17;
         b = ((color     ) & 0x000F) * 17;
-        palette[i + array_offset] = 0xFF << 24 | r << 16 | g << 8 | b;
+        palette[i + array_offset] = 0xFFU << 24 | r << 16 | g << 8 | b;
     }
     cc->frame.palette_has_changed = 1;
 }
@@ -218,7 +218,7 @@
     vscmd = (data[2] & 0x30) >> 4;
 
     h_off =  FFMIN(data[1] & 0x07, CDG_BORDER_WIDTH  - 1);
-    v_off =  FFMIN(data[2] & 0x07, CDG_BORDER_HEIGHT - 1);
+    v_off =  FFMIN(data[2] & 0x0F, CDG_BORDER_HEIGHT - 1);
 
     /// find the difference and save the offset for cdg_tile_block usage
     hinc = h_off - cc->hscroll;
diff --git a/libavcodec/cdxl.c b/libavcodec/cdxl.c
index ad830ce..abcd073 100644
--- a/libavcodec/cdxl.c
+++ b/libavcodec/cdxl.c
@@ -19,8 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#define UNCHECKED_BITSTREAM_READER 1
-
 #include "libavutil/intreadwrite.h"
 #include "libavutil/imgutils.h"
 #include "avcodec.h"
@@ -249,11 +247,11 @@
     if (c->video_size < aligned_width * avctx->height * c->bpp / 8)
         return AVERROR_INVALIDDATA;
     if (!encoding && c->palette_size && c->bpp <= 8) {
-        avctx->pix_fmt = PIX_FMT_PAL8;
+        avctx->pix_fmt = AV_PIX_FMT_PAL8;
     } else if (encoding == 1 && (c->bpp == 6 || c->bpp == 8)) {
         if (c->palette_size != (1 << (c->bpp - 1)))
             return AVERROR_INVALIDDATA;
-        avctx->pix_fmt = PIX_FMT_BGR24;
+        avctx->pix_fmt = AV_PIX_FMT_BGR24;
     } else {
         av_log_ask_for_sample(avctx, "unsupported encoding %d and bpp %d\n",
                               encoding, c->bpp);
diff --git a/libavcodec/celp_filters.c b/libavcodec/celp_filters.c
index 9dac77e..a81fd88 100644
--- a/libavcodec/celp_filters.c
+++ b/libavcodec/celp_filters.c
@@ -24,6 +24,7 @@
 
 #include "avcodec.h"
 #include "celp_filters.h"
+#include "libavutil/avassert.h"
 #include "libavutil/common.h"
 
 void ff_celp_convolve_circ(int16_t* fc_out, const int16_t* fc_in,
@@ -104,6 +105,8 @@
     c -= filter_coeffs[1] * filter_coeffs[0];
     c -= filter_coeffs[0] * b;
 
+    av_assert2((filter_length&1)==0 && filter_length>=4);
+
     old_out0 = out[-4];
     old_out1 = out[-3];
     old_out2 = out[-2];
@@ -133,7 +136,7 @@
         out2 -= val * old_out2;
         out3 -= val * old_out3;
 
-        for (i = 5; i <= filter_length; i += 2) {
+        for (i = 5; i < filter_length; i += 2) {
             old_out3 = out[-i];
             val = filter_coeffs[i-1];
 
diff --git a/libavcodec/celp_math.c b/libavcodec/celp_math.c
index 56dc863..a96b1ae 100644
--- a/libavcodec/celp_math.c
+++ b/libavcodec/celp_math.c
@@ -75,7 +75,7 @@
 #endif
 };
 
-int ff_log2(uint32_t value)
+int ff_log2_q15(uint32_t value)
 {
     uint8_t  power_int;
     uint8_t  frac_x0;
diff --git a/libavcodec/celp_math.h b/libavcodec/celp_math.h
index f12f678..18d3ad9 100644
--- a/libavcodec/celp_math.h
+++ b/libavcodec/celp_math.h
@@ -59,7 +59,7 @@
  *
  * @return value of (1<<15) * log2(value)
  */
-int ff_log2(uint32_t value);
+int ff_log2_q15(uint32_t value);
 
 /**
  * Shift value left or right depending on sign of offset parameter.
diff --git a/libavcodec/cga_data.c b/libavcodec/cga_data.c
index 46097bb..023a86b 100644
--- a/libavcodec/cga_data.c
+++ b/libavcodec/cga_data.c
@@ -21,401 +21,12 @@
 /**
  * @file
  * CGA/EGA/VGA ROM data
+ * @note fonts are in libavutil/xga_font_data.[ch]
  */
 
 #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,
- 0x7e, 0xff, 0xdb, 0xff, 0xc3, 0xe7, 0xff, 0x7e, 0x6c, 0xfe, 0xfe, 0xfe, 0x7c, 0x38, 0x10, 0x00,
- 0x10, 0x38, 0x7c, 0xfe, 0x7c, 0x38, 0x10, 0x00, 0x38, 0x7c, 0x38, 0xfe, 0xfe, 0x7c, 0x38, 0x7c,
- 0x10, 0x10, 0x38, 0x7c, 0xfe, 0x7c, 0x38, 0x7c, 0x00, 0x00, 0x18, 0x3c, 0x3c, 0x18, 0x00, 0x00,
- 0xff, 0xff, 0xe7, 0xc3, 0xc3, 0xe7, 0xff, 0xff, 0x00, 0x3c, 0x66, 0x42, 0x42, 0x66, 0x3c, 0x00,
- 0xff, 0xc3, 0x99, 0xbd, 0xbd, 0x99, 0xc3, 0xff, 0x0f, 0x07, 0x0f, 0x7d, 0xcc, 0xcc, 0xcc, 0x78,
- 0x3c, 0x66, 0x66, 0x66, 0x3c, 0x18, 0x7e, 0x18, 0x3f, 0x33, 0x3f, 0x30, 0x30, 0x70, 0xf0, 0xe0,
- 0x7f, 0x63, 0x7f, 0x63, 0x63, 0x67, 0xe6, 0xc0, 0x99, 0x5a, 0x3c, 0xe7, 0xe7, 0x3c, 0x5a, 0x99,
- 0x80, 0xe0, 0xf8, 0xfe, 0xf8, 0xe0, 0x80, 0x00, 0x02, 0x0e, 0x3e, 0xfe, 0x3e, 0x0e, 0x02, 0x00,
- 0x18, 0x3c, 0x7e, 0x18, 0x18, 0x7e, 0x3c, 0x18, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x66, 0x00,
- 0x7f, 0xdb, 0xdb, 0x7b, 0x1b, 0x1b, 0x1b, 0x00, 0x3e, 0x63, 0x38, 0x6c, 0x6c, 0x38, 0xcc, 0x78,
- 0x00, 0x00, 0x00, 0x00, 0x7e, 0x7e, 0x7e, 0x00, 0x18, 0x3c, 0x7e, 0x18, 0x7e, 0x3c, 0x18, 0xff,
- 0x18, 0x3c, 0x7e, 0x18, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x18, 0x7e, 0x3c, 0x18, 0x00,
- 0x00, 0x18, 0x0c, 0xfe, 0x0c, 0x18, 0x00, 0x00, 0x00, 0x30, 0x60, 0xfe, 0x60, 0x30, 0x00, 0x00,
- 0x00, 0x00, 0xc0, 0xc0, 0xc0, 0xfe, 0x00, 0x00, 0x00, 0x24, 0x66, 0xff, 0x66, 0x24, 0x00, 0x00,
- 0x00, 0x18, 0x3c, 0x7e, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0x7e, 0x3c, 0x18, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x78, 0x78, 0x30, 0x30, 0x00, 0x30, 0x00,
- 0x6c, 0x6c, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6c, 0x6c, 0xfe, 0x6c, 0xfe, 0x6c, 0x6c, 0x00,
- 0x30, 0x7c, 0xc0, 0x78, 0x0c, 0xf8, 0x30, 0x00, 0x00, 0xc6, 0xcc, 0x18, 0x30, 0x66, 0xc6, 0x00,
- 0x38, 0x6c, 0x38, 0x76, 0xdc, 0xcc, 0x76, 0x00, 0x60, 0x60, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x18, 0x30, 0x60, 0x60, 0x60, 0x30, 0x18, 0x00, 0x60, 0x30, 0x18, 0x18, 0x18, 0x30, 0x60, 0x00,
- 0x00, 0x66, 0x3c, 0xff, 0x3c, 0x66, 0x00, 0x00, 0x00, 0x30, 0x30, 0xfc, 0x30, 0x30, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x30, 0x60, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x30, 0x00, 0x06, 0x0c, 0x18, 0x30, 0x60, 0xc0, 0x80, 0x00,
- 0x7c, 0xc6, 0xce, 0xde, 0xf6, 0xe6, 0x7c, 0x00, 0x30, 0x70, 0x30, 0x30, 0x30, 0x30, 0xfc, 0x00,
- 0x78, 0xcc, 0x0c, 0x38, 0x60, 0xcc, 0xfc, 0x00, 0x78, 0xcc, 0x0c, 0x38, 0x0c, 0xcc, 0x78, 0x00,
- 0x1c, 0x3c, 0x6c, 0xcc, 0xfe, 0x0c, 0x1e, 0x00, 0xfc, 0xc0, 0xf8, 0x0c, 0x0c, 0xcc, 0x78, 0x00,
- 0x38, 0x60, 0xc0, 0xf8, 0xcc, 0xcc, 0x78, 0x00, 0xfc, 0xcc, 0x0c, 0x18, 0x30, 0x30, 0x30, 0x00,
- 0x78, 0xcc, 0xcc, 0x78, 0xcc, 0xcc, 0x78, 0x00, 0x78, 0xcc, 0xcc, 0x7c, 0x0c, 0x18, 0x70, 0x00,
- 0x00, 0x30, 0x30, 0x00, 0x00, 0x30, 0x30, 0x00, 0x00, 0x30, 0x30, 0x00, 0x00, 0x30, 0x30, 0x60,
- 0x18, 0x30, 0x60, 0xc0, 0x60, 0x30, 0x18, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0xfc, 0x00, 0x00,
- 0x60, 0x30, 0x18, 0x0c, 0x18, 0x30, 0x60, 0x00, 0x78, 0xcc, 0x0c, 0x18, 0x30, 0x00, 0x30, 0x00,
- 0x7c, 0xc6, 0xde, 0xde, 0xde, 0xc0, 0x78, 0x00, 0x30, 0x78, 0xcc, 0xcc, 0xfc, 0xcc, 0xcc, 0x00,
- 0xfc, 0x66, 0x66, 0x7c, 0x66, 0x66, 0xfc, 0x00, 0x3c, 0x66, 0xc0, 0xc0, 0xc0, 0x66, 0x3c, 0x00,
- 0xf8, 0x6c, 0x66, 0x66, 0x66, 0x6c, 0xf8, 0x00, 0xfe, 0x62, 0x68, 0x78, 0x68, 0x62, 0xfe, 0x00,
- 0xfe, 0x62, 0x68, 0x78, 0x68, 0x60, 0xf0, 0x00, 0x3c, 0x66, 0xc0, 0xc0, 0xce, 0x66, 0x3e, 0x00,
- 0xcc, 0xcc, 0xcc, 0xfc, 0xcc, 0xcc, 0xcc, 0x00, 0x78, 0x30, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00,
- 0x1e, 0x0c, 0x0c, 0x0c, 0xcc, 0xcc, 0x78, 0x00, 0xe6, 0x66, 0x6c, 0x78, 0x6c, 0x66, 0xe6, 0x00,
- 0xf0, 0x60, 0x60, 0x60, 0x62, 0x66, 0xfe, 0x00, 0xc6, 0xee, 0xfe, 0xfe, 0xd6, 0xc6, 0xc6, 0x00,
- 0xc6, 0xe6, 0xf6, 0xde, 0xce, 0xc6, 0xc6, 0x00, 0x38, 0x6c, 0xc6, 0xc6, 0xc6, 0x6c, 0x38, 0x00,
- 0xfc, 0x66, 0x66, 0x7c, 0x60, 0x60, 0xf0, 0x00, 0x78, 0xcc, 0xcc, 0xcc, 0xdc, 0x78, 0x1c, 0x00,
- 0xfc, 0x66, 0x66, 0x7c, 0x6c, 0x66, 0xe6, 0x00, 0x78, 0xcc, 0xe0, 0x70, 0x1c, 0xcc, 0x78, 0x00,
- 0xfc, 0xb4, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xfc, 0x00,
- 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x78, 0x30, 0x00, 0xc6, 0xc6, 0xc6, 0xd6, 0xfe, 0xee, 0xc6, 0x00,
- 0xc6, 0xc6, 0x6c, 0x38, 0x38, 0x6c, 0xc6, 0x00, 0xcc, 0xcc, 0xcc, 0x78, 0x30, 0x30, 0x78, 0x00,
- 0xfe, 0xc6, 0x8c, 0x18, 0x32, 0x66, 0xfe, 0x00, 0x78, 0x60, 0x60, 0x60, 0x60, 0x60, 0x78, 0x00,
- 0xc0, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x02, 0x00, 0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x78, 0x00,
- 0x10, 0x38, 0x6c, 0xc6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff,
- 0x30, 0x30, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0x76, 0x00,
- 0xe0, 0x60, 0x60, 0x7c, 0x66, 0x66, 0xdc, 0x00, 0x00, 0x00, 0x78, 0xcc, 0xc0, 0xcc, 0x78, 0x00,
- 0x1c, 0x0c, 0x0c, 0x7c, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x78, 0x00,
- 0x38, 0x6c, 0x60, 0xf0, 0x60, 0x60, 0xf0, 0x00, 0x00, 0x00, 0x76, 0xcc, 0xcc, 0x7c, 0x0c, 0xf8,
- 0xe0, 0x60, 0x6c, 0x76, 0x66, 0x66, 0xe6, 0x00, 0x30, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
- 0x0c, 0x00, 0x0c, 0x0c, 0x0c, 0xcc, 0xcc, 0x78, 0xe0, 0x60, 0x66, 0x6c, 0x78, 0x6c, 0xe6, 0x00,
- 0x70, 0x30, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00, 0x00, 0x00, 0xcc, 0xfe, 0xfe, 0xd6, 0xc6, 0x00,
- 0x00, 0x00, 0xf8, 0xcc, 0xcc, 0xcc, 0xcc, 0x00, 0x00, 0x00, 0x78, 0xcc, 0xcc, 0xcc, 0x78, 0x00,
- 0x00, 0x00, 0xdc, 0x66, 0x66, 0x7c, 0x60, 0xf0, 0x00, 0x00, 0x76, 0xcc, 0xcc, 0x7c, 0x0c, 0x1e,
- 0x00, 0x00, 0xdc, 0x76, 0x66, 0x60, 0xf0, 0x00, 0x00, 0x00, 0x7c, 0xc0, 0x78, 0x0c, 0xf8, 0x00,
- 0x10, 0x30, 0x7c, 0x30, 0x30, 0x34, 0x18, 0x00, 0x00, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00,
- 0x00, 0x00, 0xcc, 0xcc, 0xcc, 0x78, 0x30, 0x00, 0x00, 0x00, 0xc6, 0xd6, 0xfe, 0xfe, 0x6c, 0x00,
- 0x00, 0x00, 0xc6, 0x6c, 0x38, 0x6c, 0xc6, 0x00, 0x00, 0x00, 0xcc, 0xcc, 0xcc, 0x7c, 0x0c, 0xf8,
- 0x00, 0x00, 0xfc, 0x98, 0x30, 0x64, 0xfc, 0x00, 0x1c, 0x30, 0x30, 0xe0, 0x30, 0x30, 0x1c, 0x00,
- 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00, 0xe0, 0x30, 0x30, 0x1c, 0x30, 0x30, 0xe0, 0x00,
- 0x76, 0xdc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6c, 0xc6, 0xc6, 0xfe, 0x00,
- 0x78, 0xcc, 0xc0, 0xcc, 0x78, 0x18, 0x0c, 0x78, 0x00, 0xcc, 0x00, 0xcc, 0xcc, 0xcc, 0x7e, 0x00,
- 0x1c, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x78, 0x00, 0x7e, 0xc3, 0x3c, 0x06, 0x3e, 0x66, 0x3f, 0x00,
- 0xcc, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0x7e, 0x00, 0xe0, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0x7e, 0x00,
- 0x30, 0x30, 0x78, 0x0c, 0x7c, 0xcc, 0x7e, 0x00, 0x00, 0x00, 0x78, 0xc0, 0xc0, 0x78, 0x0c, 0x38,
- 0x7e, 0xc3, 0x3c, 0x66, 0x7e, 0x60, 0x3c, 0x00, 0xcc, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x78, 0x00,
- 0xe0, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x78, 0x00, 0xcc, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
- 0x7c, 0xc6, 0x38, 0x18, 0x18, 0x18, 0x3c, 0x00, 0xe0, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
- 0xc6, 0x38, 0x6c, 0xc6, 0xfe, 0xc6, 0xc6, 0x00, 0x30, 0x30, 0x00, 0x78, 0xcc, 0xfc, 0xcc, 0x00,
- 0x1c, 0x00, 0xfc, 0x60, 0x78, 0x60, 0xfc, 0x00, 0x00, 0x00, 0x7f, 0x0c, 0x7f, 0xcc, 0x7f, 0x00,
- 0x3e, 0x6c, 0xcc, 0xfe, 0xcc, 0xcc, 0xce, 0x00, 0x78, 0xcc, 0x00, 0x78, 0xcc, 0xcc, 0x78, 0x00,
- 0x00, 0xcc, 0x00, 0x78, 0xcc, 0xcc, 0x78, 0x00, 0x00, 0xe0, 0x00, 0x78, 0xcc, 0xcc, 0x78, 0x00,
- 0x78, 0xcc, 0x00, 0xcc, 0xcc, 0xcc, 0x7e, 0x00, 0x00, 0xe0, 0x00, 0xcc, 0xcc, 0xcc, 0x7e, 0x00,
- 0x00, 0xcc, 0x00, 0xcc, 0xcc, 0x7c, 0x0c, 0xf8, 0xc3, 0x18, 0x3c, 0x66, 0x66, 0x3c, 0x18, 0x00,
- 0xcc, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0x78, 0x00, 0x18, 0x18, 0x7e, 0xc0, 0xc0, 0x7e, 0x18, 0x18,
- 0x38, 0x6c, 0x64, 0xf0, 0x60, 0xe6, 0xfc, 0x00, 0xcc, 0xcc, 0x78, 0xfc, 0x30, 0xfc, 0x30, 0x30,
- 0xf8, 0xcc, 0xcc, 0xfa, 0xc6, 0xcf, 0xc6, 0xc7, 0x0e, 0x1b, 0x18, 0x3c, 0x18, 0x18, 0xd8, 0x70,
- 0x1c, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0x7e, 0x00, 0x38, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
- 0x00, 0x1c, 0x00, 0x78, 0xcc, 0xcc, 0x78, 0x00, 0x00, 0x1c, 0x00, 0xcc, 0xcc, 0xcc, 0x7e, 0x00,
- 0x00, 0xf8, 0x00, 0xf8, 0xcc, 0xcc, 0xcc, 0x00, 0xfc, 0x00, 0xcc, 0xec, 0xfc, 0xdc, 0xcc, 0x00,
- 0x3c, 0x6c, 0x6c, 0x3e, 0x00, 0x7e, 0x00, 0x00, 0x38, 0x6c, 0x6c, 0x38, 0x00, 0x7c, 0x00, 0x00,
- 0x30, 0x00, 0x30, 0x60, 0xc0, 0xcc, 0x78, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xc0, 0xc0, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0xfc, 0x0c, 0x0c, 0x00, 0x00, 0xc3, 0xc6, 0xcc, 0xde, 0x33, 0x66, 0xcc, 0x0f,
- 0xc3, 0xc6, 0xcc, 0xdb, 0x37, 0x6f, 0xcf, 0x03, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x18, 0x00,
- 0x00, 0x33, 0x66, 0xcc, 0x66, 0x33, 0x00, 0x00, 0x00, 0xcc, 0x66, 0x33, 0x66, 0xcc, 0x00, 0x00,
- 0x22, 0x88, 0x22, 0x88, 0x22, 0x88, 0x22, 0x88, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa,
- 0xdb, 0x77, 0xdb, 0xee, 0xdb, 0x77, 0xdb, 0xee, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
- 0x18, 0x18, 0x18, 0x18, 0xf8, 0x18, 0x18, 0x18, 0x18, 0x18, 0xf8, 0x18, 0xf8, 0x18, 0x18, 0x18,
- 0x36, 0x36, 0x36, 0x36, 0xf6, 0x36, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x36, 0x36, 0x36,
- 0x00, 0x00, 0xf8, 0x18, 0xf8, 0x18, 0x18, 0x18, 0x36, 0x36, 0xf6, 0x06, 0xf6, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x00, 0x00, 0xfe, 0x06, 0xf6, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0xf6, 0x06, 0xfe, 0x00, 0x00, 0x00, 0x36, 0x36, 0x36, 0x36, 0xfe, 0x00, 0x00, 0x00,
- 0x18, 0x18, 0xf8, 0x18, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x18, 0x18, 0x18,
- 0x18, 0x18, 0x18, 0x18, 0x1f, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0xff, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0xff, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1f, 0x18, 0x18, 0x18,
- 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0xff, 0x18, 0x18, 0x18,
- 0x18, 0x18, 0x1f, 0x18, 0x1f, 0x18, 0x18, 0x18, 0x36, 0x36, 0x36, 0x36, 0x37, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x37, 0x30, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x30, 0x37, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0xf7, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xf7, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x37, 0x30, 0x37, 0x36, 0x36, 0x36, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00,
- 0x36, 0x36, 0xf7, 0x00, 0xf7, 0x36, 0x36, 0x36, 0x18, 0x18, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00,
- 0x36, 0x36, 0x36, 0x36, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0x18, 0x18, 0x18,
- 0x00, 0x00, 0x00, 0x00, 0xff, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x3f, 0x00, 0x00, 0x00,
- 0x18, 0x18, 0x1f, 0x18, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x18, 0x1f, 0x18, 0x18, 0x18,
- 0x00, 0x00, 0x00, 0x00, 0x3f, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xff, 0x36, 0x36, 0x36,
- 0x18, 0x18, 0xff, 0x18, 0xff, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xf8, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x1f, 0x18, 0x18, 0x18, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
- 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0,
- 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x76, 0xdc, 0xc8, 0xdc, 0x76, 0x00, 0x00, 0x78, 0xcc, 0xf8, 0xcc, 0xf8, 0xc0, 0xc0,
- 0x00, 0xfc, 0xcc, 0xc0, 0xc0, 0xc0, 0xc0, 0x00, 0x00, 0xfe, 0x6c, 0x6c, 0x6c, 0x6c, 0x6c, 0x00,
- 0xfc, 0xcc, 0x60, 0x30, 0x60, 0xcc, 0xfc, 0x00, 0x00, 0x00, 0x7e, 0xd8, 0xd8, 0xd8, 0x70, 0x00,
- 0x00, 0x66, 0x66, 0x66, 0x66, 0x7c, 0x60, 0xc0, 0x00, 0x76, 0xdc, 0x18, 0x18, 0x18, 0x18, 0x00,
- 0xfc, 0x30, 0x78, 0xcc, 0xcc, 0x78, 0x30, 0xfc, 0x38, 0x6c, 0xc6, 0xfe, 0xc6, 0x6c, 0x38, 0x00,
- 0x38, 0x6c, 0xc6, 0xc6, 0x6c, 0x6c, 0xee, 0x00, 0x1c, 0x30, 0x18, 0x7c, 0xcc, 0xcc, 0x78, 0x00,
- 0x00, 0x00, 0x7e, 0xdb, 0xdb, 0x7e, 0x00, 0x00, 0x06, 0x0c, 0x7e, 0xdb, 0xdb, 0x7e, 0x60, 0xc0,
- 0x38, 0x60, 0xc0, 0xf8, 0xc0, 0x60, 0x38, 0x00, 0x78, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x00,
- 0x00, 0xfc, 0x00, 0xfc, 0x00, 0xfc, 0x00, 0x00, 0x30, 0x30, 0xfc, 0x30, 0x30, 0x00, 0xfc, 0x00,
- 0x60, 0x30, 0x18, 0x30, 0x60, 0x00, 0xfc, 0x00, 0x18, 0x30, 0x60, 0x30, 0x18, 0x00, 0xfc, 0x00,
- 0x0e, 0x1b, 0x1b, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xd8, 0xd8, 0x70,
- 0x30, 0x30, 0x00, 0xfc, 0x00, 0x30, 0x30, 0x00, 0x00, 0x76, 0xdc, 0x00, 0x76, 0xdc, 0x00, 0x00,
- 0x38, 0x6c, 0x6c, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x0f, 0x0c, 0x0c, 0x0c, 0xec, 0x6c, 0x3c, 0x1c,
- 0x78, 0x6c, 0x6c, 0x6c, 0x6c, 0x00, 0x00, 0x00, 0x70, 0x18, 0x30, 0x60, 0x78, 0x00, 0x00, 0x00,
- 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] = {
     0xFF000000, 0xFF0000AA, 0xFF00AA00, 0xFF00AAAA, 0xFFAA0000, 0xFFAA00AA, 0xFFAA5500, 0xFFAAAAAA,
     0xFF555555, 0xFF5555FF, 0xFF55FF55, 0xFF55FFFF, 0xFFFF5555, 0xFFFF55FF, 0xFFFFFF55, 0xFFFFFFFF,
diff --git a/libavcodec/cga_data.h b/libavcodec/cga_data.h
index 998dcca..3f5281a 100644
--- a/libavcodec/cga_data.h
+++ b/libavcodec/cga_data.h
@@ -21,6 +21,7 @@
 /**
  * @file
  * CGA/EGA/VGA ROM data
+ * @note fonts are in libavutil/xga_font_data.[ch]
  */
 
 #ifndef AVCODEC_CGA_DATA_H
@@ -28,8 +29,6 @@
 
 #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];
 
diff --git a/libavcodec/cinepak.c b/libavcodec/cinepak.c
index 391e787..9ae63b7 100644
--- a/libavcodec/cinepak.c
+++ b/libavcodec/cinepak.c
@@ -412,10 +412,10 @@
     // check for paletted data
     if (avctx->bits_per_coded_sample != 8) {
         s->palette_video = 0;
-        avctx->pix_fmt = PIX_FMT_YUV420P;
+        avctx->pix_fmt = AV_PIX_FMT_YUV420P;
     } else {
         s->palette_video = 1;
-        avctx->pix_fmt = PIX_FMT_PAL8;
+        avctx->pix_fmt = AV_PIX_FMT_PAL8;
     }
 
     avcodec_get_frame_defaults(&s->frame);
diff --git a/libavcodec/cljr.c b/libavcodec/cljr.c
index 7f31aa5..87c8fc2 100644
--- a/libavcodec/cljr.c
+++ b/libavcodec/cljr.c
@@ -57,7 +57,7 @@
     GetBitContext gb;
     AVFrame *picture = data;
     AVFrame * const p = &a->picture;
-    int x, y;
+    int x, y, ret;
 
     if (p->data[0])
         avctx->release_buffer(avctx, p);
@@ -74,9 +74,9 @@
     }
 
     p->reference = 0;
-    if (avctx->get_buffer(avctx, p) < 0) {
+    if ((ret = avctx->get_buffer(avctx, p)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
+        return ret;
     }
     p->pict_type = AV_PICTURE_TYPE_I;
     p->key_frame = 1;
@@ -106,7 +106,7 @@
 
 static av_cold int decode_init(AVCodecContext *avctx)
 {
-    avctx->pix_fmt = PIX_FMT_YUV411P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV411P;
     return common_init(avctx);
 }
 
@@ -203,8 +203,8 @@
     .priv_data_size = sizeof(CLJRContext),
     .init           = common_init,
     .encode2        = encode_frame,
-    .pix_fmts       = (const enum PixelFormat[]) { PIX_FMT_YUV411P,
-                                                   PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV411P,
+                                                   AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("Cirrus Logic AccuPak"),
     .priv_class     = &class,
 };
diff --git a/libavcodec/cllc.c b/libavcodec/cllc.c
index 9cb8dfa..b588331 100644
--- a/libavcodec/cllc.c
+++ b/libavcodec/cllc.c
@@ -330,7 +330,7 @@
     switch (coding_type) {
     case 1:
     case 2:
-        avctx->pix_fmt             = PIX_FMT_RGB24;
+        avctx->pix_fmt             = AV_PIX_FMT_RGB24;
         avctx->bits_per_raw_sample = 8;
 
         ret = avctx->get_buffer(avctx, pic);
@@ -345,7 +345,7 @@
 
         break;
     case 3:
-        avctx->pix_fmt             = PIX_FMT_ARGB;
+        avctx->pix_fmt             = AV_PIX_FMT_ARGB;
         avctx->bits_per_raw_sample = 8;
 
         ret = avctx->get_buffer(avctx, pic);
diff --git a/libavcodec/cngdec.c b/libavcodec/cngdec.c
new file mode 100644
index 0000000..9b6dfef
--- /dev/null
+++ b/libavcodec/cngdec.c
@@ -0,0 +1,176 @@
+/*
+ * RFC 3389 comfort noise generator
+ * Copyright (c) 2012 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
+ */
+
+#include <math.h>
+
+#include "libavutil/common.h"
+#include "avcodec.h"
+#include "celp_filters.h"
+#include "libavutil/lfg.h"
+
+typedef struct CNGContext {
+    AVFrame avframe;
+    float *refl_coef, *target_refl_coef;
+    float *lpc_coef;
+    int order;
+    int energy, target_energy;
+    int inited;
+    float *filter_out;
+    float *excitation;
+    AVLFG lfg;
+} CNGContext;
+
+static av_cold int cng_decode_close(AVCodecContext *avctx)
+{
+    CNGContext *p = avctx->priv_data;
+    av_free(p->refl_coef);
+    av_free(p->target_refl_coef);
+    av_free(p->lpc_coef);
+    av_free(p->filter_out);
+    av_free(p->excitation);
+    return 0;
+}
+
+static av_cold int cng_decode_init(AVCodecContext *avctx)
+{
+    CNGContext *p = avctx->priv_data;
+
+    avctx->sample_fmt  = AV_SAMPLE_FMT_S16;
+    avctx->channels    = 1;
+    avctx->sample_rate = 8000;
+
+    avcodec_get_frame_defaults(&p->avframe);
+    avctx->coded_frame  = &p->avframe;
+    p->order            = 12;
+    avctx->frame_size   = 640;
+    p->refl_coef        = av_mallocz(p->order * sizeof(*p->refl_coef));
+    p->target_refl_coef = av_mallocz(p->order * sizeof(*p->target_refl_coef));
+    p->lpc_coef         = av_mallocz(p->order * sizeof(*p->lpc_coef));
+    p->filter_out       = av_mallocz((avctx->frame_size + p->order) *
+                                     sizeof(*p->filter_out));
+    p->excitation       = av_mallocz(avctx->frame_size * sizeof(*p->excitation));
+    if (!p->refl_coef || !p->target_refl_coef || !p->lpc_coef ||
+        !p->filter_out || !p->excitation) {
+        cng_decode_close(avctx);
+        return AVERROR(ENOMEM);
+    }
+
+    av_lfg_init(&p->lfg, 0);
+
+    return 0;
+}
+
+static void make_lpc_coefs(float *lpc, const float *refl, int order)
+{
+    float buf[100];
+    float *next, *cur;
+    int m, i;
+    next = buf;
+    cur  = lpc;
+    for (m = 0; m < order; m++) {
+        next[m] = refl[m];
+        for (i = 0; i < m; i++)
+            next[i] = cur[i] + refl[m] * cur[m - i - 1];
+        FFSWAP(float*, next, cur);
+    }
+    if (cur != lpc)
+        memcpy(lpc, cur, sizeof(*lpc) * order);
+}
+
+static void cng_decode_flush(AVCodecContext *avctx)
+{
+    CNGContext *p = avctx->priv_data;
+    p->inited = 0;
+}
+
+static int cng_decode_frame(AVCodecContext *avctx, void *data,
+                            int *got_frame_ptr, AVPacket *avpkt)
+{
+
+    CNGContext *p = avctx->priv_data;
+    int buf_size  = avpkt->size;
+    int ret, i;
+    int16_t *buf_out;
+    float e = 1.0;
+    float scaling;
+
+    if (avpkt->size) {
+        int dbov = -avpkt->data[0];
+        p->target_energy = 1081109975 * pow(10, dbov / 10.0) * 0.75;
+        memset(p->target_refl_coef, 0, p->order * sizeof(*p->target_refl_coef));
+        for (i = 0; i < FFMIN(avpkt->size - 1, p->order); i++) {
+            p->target_refl_coef[i] = (avpkt->data[1 + i] - 127) / 128.0;
+        }
+    }
+
+    if (p->inited) {
+        p->energy = p->energy / 2 + p->target_energy / 2;
+        for (i = 0; i < p->order; i++)
+            p->refl_coef[i] = 0.6 *p->refl_coef[i] + 0.4 * p->target_refl_coef[i];
+    } else {
+        p->energy = p->target_energy;
+        memcpy(p->refl_coef, p->target_refl_coef, p->order * sizeof(*p->refl_coef));
+        p->inited = 1;
+    }
+    make_lpc_coefs(p->lpc_coef, p->refl_coef, p->order);
+
+    for (i = 0; i < p->order; i++)
+        e *= 1.0 - p->refl_coef[i]*p->refl_coef[i];
+
+    scaling = sqrt(e * p->energy / 1081109975);
+    for (i = 0; i < avctx->frame_size; i++) {
+        int r = (av_lfg_get(&p->lfg) & 0xffff) - 0x8000;
+        p->excitation[i] = scaling * r;
+    }
+    ff_celp_lp_synthesis_filterf(p->filter_out + p->order, p->lpc_coef,
+                                 p->excitation, avctx->frame_size, p->order);
+
+    p->avframe.nb_samples = avctx->frame_size;
+    if ((ret = avctx->get_buffer(avctx, &p->avframe)) < 0) {
+        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+        return ret;
+    }
+    buf_out = (int16_t *)p->avframe.data[0];
+    for (i = 0; i < avctx->frame_size; i++)
+        buf_out[i] = p->filter_out[i + p->order];
+    memcpy(p->filter_out, p->filter_out + avctx->frame_size,
+           p->order * sizeof(*p->filter_out));
+
+    *got_frame_ptr   = 1;
+    *(AVFrame *)data = p->avframe;
+
+    return buf_size;
+}
+
+AVCodec ff_comfortnoise_decoder = {
+    .name           = "comfortnoise",
+    .type           = AVMEDIA_TYPE_AUDIO,
+    .id             = AV_CODEC_ID_COMFORT_NOISE,
+    .priv_data_size = sizeof(CNGContext),
+    .init           = cng_decode_init,
+    .decode         = cng_decode_frame,
+    .flush          = cng_decode_flush,
+    .close          = cng_decode_close,
+    .long_name      = NULL_IF_CONFIG_SMALL("RFC 3389 comfort noise generator"),
+    .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
+                                                     AV_SAMPLE_FMT_NONE },
+    .capabilities   = CODEC_CAP_DELAY | CODEC_CAP_DR1,
+};
diff --git a/libavcodec/cngenc.c b/libavcodec/cngenc.c
new file mode 100644
index 0000000..4ab3019
--- /dev/null
+++ b/libavcodec/cngenc.c
@@ -0,0 +1,116 @@
+/*
+ * RFC 3389 comfort noise generator
+ * Copyright (c) 2012 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
+ */
+
+#include <math.h>
+
+#include "libavutil/common.h"
+#include "avcodec.h"
+#include "internal.h"
+#include "lpc.h"
+
+typedef struct CNGContext {
+    LPCContext lpc;
+    int order;
+    int32_t *samples32;
+    double *ref_coef;
+} CNGContext;
+
+static av_cold int cng_encode_close(AVCodecContext *avctx)
+{
+    CNGContext *p = avctx->priv_data;
+    ff_lpc_end(&p->lpc);
+    av_free(p->samples32);
+    av_free(p->ref_coef);
+    return 0;
+}
+
+static av_cold int cng_encode_init(AVCodecContext *avctx)
+{
+    CNGContext *p = avctx->priv_data;
+    int ret;
+
+    if (avctx->channels != 1) {
+        av_log(avctx, AV_LOG_ERROR, "Only mono supported\n");
+        return AVERROR(EINVAL);
+    }
+
+    avctx->frame_size = 640;
+    p->order = 10;
+    if ((ret = ff_lpc_init(&p->lpc, avctx->frame_size, p->order, FF_LPC_TYPE_LEVINSON)) < 0)
+        return ret;
+    p->samples32 = av_malloc(avctx->frame_size * sizeof(*p->samples32));
+    p->ref_coef = av_malloc(p->order * sizeof(*p->ref_coef));
+    if (!p->samples32 || !p->ref_coef) {
+        cng_encode_close(avctx);
+        return AVERROR(ENOMEM);
+    }
+
+    return 0;
+}
+
+static int cng_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
+                            const AVFrame *frame, int *got_packet_ptr)
+{
+    CNGContext *p = avctx->priv_data;
+    int ret, i;
+    double energy = 0;
+    int qdbov;
+    int16_t *samples = (int16_t*) frame->data[0];
+
+    if ((ret = ff_alloc_packet(avpkt, 1 + p->order))) {
+        av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
+        return ret;
+    }
+
+    for (i = 0; i < frame->nb_samples; i++) {
+        p->samples32[i] = samples[i];
+        energy += samples[i] * samples[i];
+    }
+    energy /= frame->nb_samples;
+    if (energy > 0) {
+        double dbov = 10 * log10(energy / 1081109975);
+        qdbov = av_clip(-floor(dbov), 0, 127);
+    } else {
+        qdbov = 127;
+    }
+    ret = ff_lpc_calc_ref_coefs(&p->lpc, p->samples32, p->order, p->ref_coef);
+    avpkt->data[0] = qdbov;
+    for (i = 0; i < p->order; i++)
+        avpkt->data[1 + i] = p->ref_coef[i] * 127 + 127;
+
+    *got_packet_ptr = 1;
+    avpkt->size = 1 + p->order;
+
+    return 0;
+}
+
+AVCodec ff_comfortnoise_encoder = {
+    .name           = "comfortnoise",
+    .type           = AVMEDIA_TYPE_AUDIO,
+    .id             = AV_CODEC_ID_COMFORT_NOISE,
+    .priv_data_size = sizeof(CNGContext),
+    .init           = cng_encode_init,
+    .encode2        = cng_encode_frame,
+    .close          = cng_encode_close,
+    .long_name      = NULL_IF_CONFIG_SMALL("RFC 3389 comfort noise generator"),
+    .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
+                                                     AV_SAMPLE_FMT_NONE },
+};
diff --git a/libavcodec/codec_desc.c b/libavcodec/codec_desc.c
index 2f9e348..5e4f357 100644
--- a/libavcodec/codec_desc.c
+++ b/libavcodec/codec_desc.c
@@ -39,7 +39,7 @@
         .id        = AV_CODEC_ID_MPEG2VIDEO,
         .type      = AVMEDIA_TYPE_VIDEO,
         .name      = "mpeg2video",
-        .long_name = NULL_IF_CONFIG_SMALL("MPEG-1 video"),
+        .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 video"),
         .props     = AV_CODEC_PROP_LOSSY,
     },
     {
@@ -1154,7 +1154,7 @@
         .type      = AVMEDIA_TYPE_VIDEO,
         .name      = "cdxl",
         .long_name = NULL_IF_CONFIG_SMALL("Commodore CDXL video"),
-        .props     = AV_CODEC_PROP_LOSSY,
+        .props     = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSY,
     },
     {
         .id        = AV_CODEC_ID_XBM,
@@ -1224,13 +1224,15 @@
         .type      = AVMEDIA_TYPE_VIDEO,
         .name      = "escape130",
         .long_name = NULL_IF_CONFIG_SMALL("Escape 130"),
+        .props     = AV_CODEC_PROP_LOSSY,
     },
     {
         .id        = AV_CODEC_ID_EXR,
         .type      = AVMEDIA_TYPE_VIDEO,
         .name      = "exr",
         .long_name = NULL_IF_CONFIG_SMALL("OpenEXR image"),
-        .props     = AV_CODEC_PROP_INTRA_ONLY,
+        .props     = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSY |
+                     AV_CODEC_PROP_LOSSLESS,
     },
     {
         .id        = AV_CODEC_ID_AVRP,
@@ -1249,7 +1251,7 @@
         .id        = AV_CODEC_ID_AVUI,
         .type      = AVMEDIA_TYPE_VIDEO,
         .name      = "avui",
-        .long_name = NULL_IF_CONFIG_SMALL("AVID Meridien"),
+        .long_name = NULL_IF_CONFIG_SMALL("Avid Meridien Uncompressed"),
         .props     = AV_CODEC_PROP_INTRA_ONLY,
     },
     {
@@ -1260,6 +1262,13 @@
         .props     = AV_CODEC_PROP_INTRA_ONLY,
     },
     {
+        .id        = AV_CODEC_ID_TARGA_Y216,
+        .type      = AVMEDIA_TYPE_VIDEO,
+        .name      = "targa_y216",
+        .long_name = NULL_IF_CONFIG_SMALL("Pinnacle TARGA CineWave YUV16"),
+        .props     = AV_CODEC_PROP_INTRA_ONLY,
+    },
+    {
         .id        = AV_CODEC_ID_V308,
         .type      = AVMEDIA_TYPE_VIDEO,
         .name      = "v308",
@@ -1285,12 +1294,14 @@
         .type      = AVMEDIA_TYPE_VIDEO,
         .name      = "sanm",
         .long_name = NULL_IF_CONFIG_SMALL("LucasArts SMUSH video"),
+        .props     = AV_CODEC_PROP_LOSSY,
     },
     {
         .id        = AV_CODEC_ID_PAF_VIDEO,
         .type      = AVMEDIA_TYPE_VIDEO,
         .name      = "paf_video",
         .long_name = NULL_IF_CONFIG_SMALL("Amazing Studio Packed Animation File Video"),
+        .props     = AV_CODEC_PROP_LOSSY,
     },
     {
         .id        = AV_CODEC_ID_AVRN,
@@ -1304,6 +1315,18 @@
         .name      = "cpia",
         .long_name = NULL_IF_CONFIG_SMALL("CPiA video format"),
     },
+    {
+        .id        = AV_CODEC_ID_XFACE,
+        .type      = AVMEDIA_TYPE_VIDEO,
+        .name      = "xface",
+        .long_name = NULL_IF_CONFIG_SMALL("X-face image"),
+    },
+    {
+        .id        = AV_CODEC_ID_BRENDER_PIX,
+        .type      = AVMEDIA_TYPE_VIDEO,
+        .name      = "brender_pix",
+        .long_name = NULL_IF_CONFIG_SMALL("BRender PIX image"),
+    },
 
     /* various PCM "codecs" */
     {
@@ -1352,13 +1375,15 @@
         .id        = AV_CODEC_ID_PCM_MULAW,
         .type      = AVMEDIA_TYPE_AUDIO,
         .name      = "pcm_mulaw",
-        .long_name = NULL_IF_CONFIG_SMALL("PCM mu-law"),
+        .long_name = NULL_IF_CONFIG_SMALL("PCM mu-law / G.711 mu-law"),
+        .props     = AV_CODEC_PROP_LOSSY,
     },
     {
         .id        = AV_CODEC_ID_PCM_ALAW,
         .type      = AVMEDIA_TYPE_AUDIO,
         .name      = "pcm_alaw",
-        .long_name = NULL_IF_CONFIG_SMALL("PCM A-law"),
+        .long_name = NULL_IF_CONFIG_SMALL("PCM A-law / G.711 A-law"),
+        .props     = AV_CODEC_PROP_LOSSY,
     },
     {
         .id        = AV_CODEC_ID_PCM_S32LE,
@@ -1431,10 +1456,31 @@
         .props     = AV_CODEC_PROP_LOSSY,
     },
     {
+        .id        = AV_CODEC_ID_PCM_S16BE_PLANAR,
+        .type      = AVMEDIA_TYPE_AUDIO,
+        .name      = "pcm_s16be_planar",
+        .long_name = NULL_IF_CONFIG_SMALL("PCM signed 16-bit big-endian planar"),
+        .props     = AV_CODEC_PROP_LOSSLESS,
+    },
+    {
         .id        = AV_CODEC_ID_PCM_S16LE_PLANAR,
         .type      = AVMEDIA_TYPE_AUDIO,
         .name      = "pcm_s16le_planar",
-        .long_name = NULL_IF_CONFIG_SMALL("PCM 16-bit little-endian planar"),
+        .long_name = NULL_IF_CONFIG_SMALL("PCM signed 16-bit little-endian planar"),
+        .props     = AV_CODEC_PROP_LOSSLESS,
+    },
+    {
+        .id        = AV_CODEC_ID_PCM_S24LE_PLANAR,
+        .type      = AVMEDIA_TYPE_AUDIO,
+        .name      = "pcm_s24le_planar",
+        .long_name = NULL_IF_CONFIG_SMALL("PCM signed 24-bit little-endian planar"),
+        .props     = AV_CODEC_PROP_LOSSLESS,
+    },
+    {
+        .id        = AV_CODEC_ID_PCM_S32LE_PLANAR,
+        .type      = AVMEDIA_TYPE_AUDIO,
+        .name      = "pcm_s32le_planar",
+        .long_name = NULL_IF_CONFIG_SMALL("PCM signed 32-bit little-endian planar"),
         .props     = AV_CODEC_PROP_LOSSLESS,
     },
     {
@@ -1712,6 +1758,20 @@
         .long_name = NULL_IF_CONFIG_SMALL("ADPCM IMA CRYO APC"),
         .props     = AV_CODEC_PROP_LOSSY,
     },
+    {
+        .id        = AV_CODEC_ID_ADPCM_AFC,
+        .type      = AVMEDIA_TYPE_AUDIO,
+        .name      = "adpcm_afc",
+        .long_name = NULL_IF_CONFIG_SMALL("ADPCM Nintendo Gamecube AFC"),
+        .props     = AV_CODEC_PROP_LOSSY,
+    },
+    {
+        .id        = AV_CODEC_ID_ADPCM_IMA_OKI,
+        .type      = AVMEDIA_TYPE_AUDIO,
+        .name      = "adpcm_ima_oki",
+        .long_name = NULL_IF_CONFIG_SMALL("ADPCM IMA Dialogic OKI"),
+        .props     = AV_CODEC_PROP_LOSSY,
+    },
 
     /* AMR */
     {
@@ -2207,6 +2267,7 @@
         .type      = AVMEDIA_TYPE_AUDIO,
         .name      = "vima",
         .long_name = NULL_IF_CONFIG_SMALL("LucasArts VIMA audio"),
+        .props     = AV_CODEC_PROP_LOSSY,
     },
     {
         .id        = AV_CODEC_ID_FFWAVESYNTH,
@@ -2237,6 +2298,7 @@
         .type      = AVMEDIA_TYPE_AUDIO,
         .name      = "paf_audio",
         .long_name = NULL_IF_CONFIG_SMALL("Amazing Studio Packed Animation File Audio"),
+        .props     = AV_CODEC_PROP_LOSSY,
     },
     {
         .id        = AV_CODEC_ID_OPUS,
@@ -2245,6 +2307,20 @@
         .long_name = NULL_IF_CONFIG_SMALL("Opus (Opus Interactive Audio Codec)"),
         .props     = AV_CODEC_PROP_LOSSY,
     },
+    {
+        .id        = AV_CODEC_ID_COMFORT_NOISE,
+        .type      = AVMEDIA_TYPE_AUDIO,
+        .name      = "comfortnoise",
+        .long_name = NULL_IF_CONFIG_SMALL("RFC 3389 Comfort Noise"),
+        .props     = AV_CODEC_PROP_LOSSY,
+    },
+    {
+        .id        = AV_CODEC_ID_TAK,
+        .type      = AVMEDIA_TYPE_AUDIO,
+        .name      = "tak",
+        .long_name = NULL_IF_CONFIG_SMALL("TAK (Tom's lossless Audio Kompressor)"),
+        .props     = AV_CODEC_PROP_LOSSLESS,
+    },
 
     /* subtitle codecs */
     {
diff --git a/libavcodec/cook.c b/libavcodec/cook.c
index cca97e3..63f6be2 100644
--- a/libavcodec/cook.c
+++ b/libavcodec/cook.c
@@ -42,13 +42,13 @@
  * available.
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/lfg.h"
 #include "avcodec.h"
 #include "get_bits.h"
 #include "dsputil.h"
 #include "bytestream.h"
 #include "fft.h"
-#include "libavutil/audioconvert.h"
 #include "sinewin.h"
 
 #include "cookdata.h"
@@ -72,23 +72,22 @@
     int                 size;
     int                 num_channels;
     int                 cookversion;
-    int                 samples_per_frame;
     int                 subbands;
     int                 js_subband_start;
     int                 js_vlc_bits;
     int                 samples_per_channel;
     int                 log2_numvector_size;
     unsigned int        channel_mask;
-    VLC                 ccpl;                 ///< channel coupling
+    VLC                 channel_coupling;
     int                 joint_stereo;
     int                 bits_per_subpacket;
     int                 bits_per_subpdiv;
     int                 total_subbands;
-    int                 numvector_size;       ///< 1 << log2_numvector_size;
+    int                 numvector_size;       // 1 << log2_numvector_size;
 
     float               mono_previous_buffer1[1024];
     float               mono_previous_buffer2[1024];
-    /** gain buffers */
+
     cook_gains          gains1;
     cook_gains          gains2;
     int                 gain_1[9];
@@ -119,15 +118,13 @@
     void (*interpolate)(struct cook *q, float *buffer,
                         int gain_index, int gain_index_next);
 
-    void (*saturate_output)(struct cook *q, int chan, float *out);
+    void (*saturate_output)(struct cook *q, float *out);
 
     AVCodecContext*     avctx;
+    DSPContext          dsp;
     AVFrame             frame;
     GetBitContext       gb;
     /* stream data */
-    int                 nb_channels;
-    int                 bit_rate;
-    int                 sample_rate;
     int                 num_vectors;
     int                 samples_per_channel;
     /* states */
@@ -204,7 +201,8 @@
 
     for (i = 0; i < q->num_subpackets; i++) {
         if (q->subpacket[i].joint_stereo == 1) {
-            result |= init_vlc(&q->subpacket[i].ccpl, 6, (1 << q->subpacket[i].js_vlc_bits) - 1,
+            result |= init_vlc(&q->subpacket[i].channel_coupling, 6,
+                               (1 << q->subpacket[i].js_vlc_bits) - 1,
                                ccpl_huffbits[q->subpacket[i].js_vlc_bits - 2], 1, 1,
                                ccpl_huffcodes[q->subpacket[i].js_vlc_bits - 2], 2, 2, 0);
             av_log(q->avctx, AV_LOG_DEBUG, "subpacket %i Joint-stereo VLC used.\n", i);
@@ -239,17 +237,11 @@
     return 0;
 }
 
-static const float *maybe_reformat_buffer32(COOKContext *q, const float *ptr, int n)
-{
-    if (1)
-        return ptr;
-}
-
 static av_cold void init_cplscales_table(COOKContext *q)
 {
     int i;
     for (i = 0; i < 5; i++)
-        q->cplscales[i] = maybe_reformat_buffer32(q, cplscales[i], (1 << (i + 2)) - 1);
+        q->cplscales[i] = cplscales[i];
 }
 
 /*************** init functions end ***********/
@@ -303,9 +295,6 @@
     return off;
 }
 
-/**
- * Cook uninit
- */
 static av_cold int cook_decode_close(AVCodecContext *avctx)
 {
     int i;
@@ -325,7 +314,7 @@
     for (i = 0; i < 7; i++)
         ff_free_vlc(&q->sqvh[i]);
     for (i = 0; i < q->num_subpackets; i++)
-        ff_free_vlc(&q->subpacket[i].ccpl);
+        ff_free_vlc(&q->subpacket[i].channel_coupling);
 
     av_log(avctx, AV_LOG_DEBUG, "Memory deallocated.\n");
 
@@ -635,12 +624,6 @@
 }
 
 
-/**
- * function for decoding mono data
- *
- * @param q                 pointer to the COOKContext
- * @param mlt_buffer        pointer to mlt coefficients
- */
 static int mono_decode(COOKContext *q, COOKSubpacket *p, float *mlt_buffer)
 {
     int category_index[128] = { 0 };
@@ -755,7 +738,6 @@
  *
  * @param q                 pointer to the COOKContext
  * @param decouple_tab      decoupling array
- *
  */
 static int decouple_info(COOKContext *q, COOKSubpacket *p, int *decouple_tab)
 {
@@ -770,7 +752,9 @@
 
     if (vlc)
         for (i = 0; i < length; i++)
-            decouple_tab[start + i] = get_vlc2(&q->gb, p->ccpl.table, p->ccpl.bits, 2);
+            decouple_tab[start + i] = get_vlc2(&q->gb,
+                                               p->channel_coupling.table,
+                                               p->channel_coupling.bits, 2);
     else
         for (i = 0; i < length; i++) {
             int v = get_bits(&q->gb, p->js_vlc_bits);
@@ -783,7 +767,7 @@
     return 0;
 }
 
-/*
+/**
  * function decouples a pair of signals from a single signal via multiplication.
  *
  * @param q                 pointer to the COOKContext
@@ -816,8 +800,8 @@
  * @param mlt_buffer1       pointer to left channel mlt coefficients
  * @param mlt_buffer2       pointer to right channel mlt coefficients
  */
-static int joint_decode(COOKContext *q, COOKSubpacket *p, float *mlt_buffer1,
-                        float *mlt_buffer2)
+static int joint_decode(COOKContext *q, COOKSubpacket *p,
+                        float *mlt_buffer_left, float *mlt_buffer_right)
 {
     int i, j, res;
     int decouple_tab[SUBBAND_SIZE] = { 0 };
@@ -829,8 +813,8 @@
     memset(decode_buffer, 0, sizeof(q->decode_buffer_0));
 
     /* Make sure the buffers are zeroed out. */
-    memset(mlt_buffer1, 0, 1024 * sizeof(*mlt_buffer1));
-    memset(mlt_buffer2, 0, 1024 * sizeof(*mlt_buffer2));
+    memset(mlt_buffer_left,  0, 1024 * sizeof(*mlt_buffer_left));
+    memset(mlt_buffer_right, 0, 1024 * sizeof(*mlt_buffer_right));
     if ((res = decouple_info(q, p, decouple_tab)) < 0)
         return res;
     if ((res = mono_decode(q, p, decode_buffer)) < 0)
@@ -838,8 +822,8 @@
     /* The two channels are stored interleaved in decode_buffer. */
     for (i = 0; i < p->js_subband_start; i++) {
         for (j = 0; j < SUBBAND_SIZE; j++) {
-            mlt_buffer1[i * 20 + j] = decode_buffer[i * 40 + j];
-            mlt_buffer2[i * 20 + j] = decode_buffer[i * 40 + 20 + j];
+            mlt_buffer_left[i  * 20 + j] = decode_buffer[i * 40 + j];
+            mlt_buffer_right[i * 20 + j] = decode_buffer[i * 40 + 20 + j];
         }
     }
 
@@ -852,7 +836,8 @@
         cplscale = q->cplscales[p->js_vlc_bits - 2];  // choose decoupler table
         f1 = cplscale[decouple_tab[cpl_tmp] + 1];
         f2 = cplscale[idx];
-        q->decouple(q, p, i, f1, f2, decode_buffer, mlt_buffer1, mlt_buffer2);
+        q->decouple(q, p, i, f1, f2, decode_buffer,
+                    mlt_buffer_left, mlt_buffer_right);
         idx = (1 << p->js_vlc_bits) - 1;
     }
 
@@ -887,18 +872,15 @@
  * Saturate the output signal and interleave.
  *
  * @param q                 pointer to the COOKContext
- * @param chan              channel to saturate
  * @param out               pointer to the output vector
  */
-static void saturate_output_float(COOKContext *q, int chan, float *out)
+static void saturate_output_float(COOKContext *q, float *out)
 {
-    int j;
-    float *output = q->mono_mdct_output + q->samples_per_channel;
-    for (j = 0; j < q->samples_per_channel; j++) {
-        out[chan + q->nb_channels * j] = av_clipf(output[j], -1.0, 1.0);
-    }
+    q->dsp.vector_clipf(out, q->mono_mdct_output + q->samples_per_channel,
+                        -1.0f, 1.0f, FFALIGN(q->samples_per_channel, 8));
 }
 
+
 /**
  * Final part of subpacket decoding:
  *  Apply modulated lapped transform, gain compensation,
@@ -909,15 +891,14 @@
  * @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
  */
 static inline void mlt_compensate_output(COOKContext *q, float *decode_buffer,
                                          cook_gains *gains_ptr, float *previous_buffer,
-                                         float *out, int chan)
+                                         float *out)
 {
     imlt_gain(q, decode_buffer, gains_ptr, previous_buffer);
     if (out)
-        q->saturate_output(q, chan, out);
+        q->saturate_output(q, out);
 }
 
 
@@ -930,7 +911,7 @@
  * @param outbuffer         pointer to the outbuffer
  */
 static int decode_subpacket(COOKContext *q, COOKSubpacket *p,
-                            const uint8_t *inbuffer, float *outbuffer)
+                            const uint8_t *inbuffer, float **outbuffer)
 {
     int sub_packet_size = p->size;
     int res;
@@ -953,32 +934,31 @@
     }
 
     mlt_compensate_output(q, q->decode_buffer_1, &p->gains1,
-                          p->mono_previous_buffer1, outbuffer, p->ch_idx);
+                          p->mono_previous_buffer1,
+                          outbuffer ? outbuffer[p->ch_idx] : NULL);
 
-    if (p->num_channels == 2)
+    if (p->num_channels == 2) {
         if (p->joint_stereo)
             mlt_compensate_output(q, q->decode_buffer_2, &p->gains1,
-                                  p->mono_previous_buffer2, outbuffer, p->ch_idx + 1);
+                                  p->mono_previous_buffer2,
+                                  outbuffer ? outbuffer[p->ch_idx + 1] : NULL);
         else
             mlt_compensate_output(q, q->decode_buffer_2, &p->gains2,
-                                  p->mono_previous_buffer2, outbuffer, p->ch_idx + 1);
+                                  p->mono_previous_buffer2,
+                                  outbuffer ? outbuffer[p->ch_idx + 1] : NULL);
+    }
 
     return 0;
 }
 
 
-/**
- * Cook frame decoding
- *
- * @param avctx     pointer to the AVCodecContext
- */
 static int cook_decode_frame(AVCodecContext *avctx, void *data,
                              int *got_frame_ptr, AVPacket *avpkt)
 {
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
     COOKContext *q = avctx->priv_data;
-    float *samples = NULL;
+    float **samples = NULL;
     int i, ret;
     int offset = 0;
     int chidx = 0;
@@ -993,7 +973,7 @@
             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
             return ret;
         }
-        samples = (float *) q->frame.data[0];
+        samples = (float **)q->frame.extended_data;
     }
 
     /* estimate subpacket sizes */
@@ -1044,19 +1024,18 @@
 static void dump_cook_context(COOKContext *q)
 {
     //int i=0;
-#define PRINT(a, b) av_log(q->avctx, AV_LOG_ERROR, " %s = %d\n", a, b);
-    av_log(q->avctx, AV_LOG_ERROR, "COOKextradata\n");
-    av_log(q->avctx, AV_LOG_ERROR, "cookversion=%x\n", q->subpacket[0].cookversion);
+#define PRINT(a, b) av_dlog(q->avctx, " %s = %d\n", a, b);
+    av_dlog(q->avctx, "COOKextradata\n");
+    av_dlog(q->avctx, "cookversion=%x\n", q->subpacket[0].cookversion);
     if (q->subpacket[0].cookversion > STEREO) {
         PRINT("js_subband_start", q->subpacket[0].js_subband_start);
         PRINT("js_vlc_bits", q->subpacket[0].js_vlc_bits);
     }
-    av_log(q->avctx, AV_LOG_ERROR, "COOKContext\n");
-    PRINT("nb_channels", q->nb_channels);
-    PRINT("bit_rate", q->bit_rate);
-    PRINT("sample_rate", q->sample_rate);
+    av_dlog(q->avctx, "COOKContext\n");
+    PRINT("nb_channels", q->avctx->channels);
+    PRINT("bit_rate", q->avctx->bit_rate);
+    PRINT("sample_rate", q->avctx->sample_rate);
     PRINT("samples_per_channel", q->subpacket[0].samples_per_channel);
-    PRINT("samples_per_frame", q->subpacket[0].samples_per_frame);
     PRINT("subbands", q->subpacket[0].subbands);
     PRINT("js_subband_start", q->subpacket[0].js_subband_start);
     PRINT("log2_numvector_size", q->subpacket[0].log2_numvector_size);
@@ -1065,16 +1044,6 @@
 }
 #endif
 
-static av_cold int cook_count_channels(unsigned int mask)
-{
-    int i;
-    int channels = 0;
-    for (i = 0; i < 32; i++)
-        if (mask & (1 << i))
-            ++channels;
-    return channels;
-}
-
 /**
  * Cook initialization
  *
@@ -1088,6 +1057,7 @@
     int extradata_size = avctx->extradata_size;
     int s = 0;
     unsigned int channel_mask = 0;
+    int samples_per_frame = 0;
     int ret;
     q->avctx = avctx;
 
@@ -1099,10 +1069,7 @@
     av_log(avctx, AV_LOG_DEBUG, "codecdata_length=%d\n", avctx->extradata_size);
 
     /* Take data from the AVCodecContext (RM container). */
-    q->sample_rate = avctx->sample_rate;
-    q->nb_channels = avctx->channels;
-    q->bit_rate = avctx->bit_rate;
-    if (!q->nb_channels) {
+    if (!avctx->channels) {
         av_log(avctx, AV_LOG_ERROR, "Invalid number of channels\n");
         return AVERROR_INVALIDDATA;
     }
@@ -1110,12 +1077,14 @@
     /* Initialize RNG. */
     av_lfg_init(&q->random_state, 0);
 
+    ff_dsputil_init(&q->dsp, avctx);
+
     while (edata_ptr < edata_ptr_end) {
         /* 8 for mono, 16 for stereo, ? for multichannel
            Swap to right endianness so we don't need to care later on. */
         if (extradata_size >= 8) {
             q->subpacket[s].cookversion = bytestream_get_be32(&edata_ptr);
-            q->subpacket[s].samples_per_frame = bytestream_get_be16(&edata_ptr);
+            samples_per_frame           = bytestream_get_be16(&edata_ptr);
             q->subpacket[s].subbands = bytestream_get_be16(&edata_ptr);
             extradata_size -= 8;
         }
@@ -1127,7 +1096,7 @@
         }
 
         /* Initialize extradata related variables. */
-        q->subpacket[s].samples_per_channel = q->subpacket[s].samples_per_frame / q->nb_channels;
+        q->subpacket[s].samples_per_channel = samples_per_frame / avctx->channels;
         q->subpacket[s].bits_per_subpacket = avctx->block_align * 8;
 
         /* Initialize default data states. */
@@ -1142,21 +1111,21 @@
         q->subpacket[s].joint_stereo = 0;
         switch (q->subpacket[s].cookversion) {
         case MONO:
-            if (q->nb_channels != 1) {
+            if (avctx->channels != 1) {
                 av_log_ask_for_sample(avctx, "Container channels != 1.\n");
                 return AVERROR_PATCHWELCOME;
             }
             av_log(avctx, AV_LOG_DEBUG, "MONO\n");
             break;
         case STEREO:
-            if (q->nb_channels != 1) {
+            if (avctx->channels != 1) {
                 q->subpacket[s].bits_per_subpdiv = 1;
                 q->subpacket[s].num_channels = 2;
             }
             av_log(avctx, AV_LOG_DEBUG, "STEREO\n");
             break;
         case JOINT_STEREO:
-            if (q->nb_channels != 2) {
+            if (avctx->channels != 2) {
                 av_log_ask_for_sample(avctx, "Container channels != 2.\n");
                 return AVERROR_PATCHWELCOME;
             }
@@ -1179,12 +1148,12 @@
             if (extradata_size >= 4)
                 channel_mask |= q->subpacket[s].channel_mask = bytestream_get_be32(&edata_ptr);
 
-            if (cook_count_channels(q->subpacket[s].channel_mask) > 1) {
+            if (av_get_channel_layout_nb_channels(q->subpacket[s].channel_mask) > 1) {
                 q->subpacket[s].total_subbands = q->subpacket[s].subbands +
                                                  q->subpacket[s].js_subband_start;
                 q->subpacket[s].joint_stereo = 1;
                 q->subpacket[s].num_channels = 2;
-                q->subpacket[s].samples_per_channel = q->subpacket[s].samples_per_frame >> 1;
+                q->subpacket[s].samples_per_channel = samples_per_frame >> 1;
 
                 if (q->subpacket[s].samples_per_channel > 256) {
                     q->subpacket[s].log2_numvector_size = 6;
@@ -1193,7 +1162,7 @@
                     q->subpacket[s].log2_numvector_size = 7;
                 }
             } else
-                q->subpacket[s].samples_per_channel = q->subpacket[s].samples_per_frame;
+                q->subpacket[s].samples_per_channel = samples_per_frame;
 
             break;
         default:
@@ -1228,13 +1197,17 @@
             av_log_ask_for_sample(avctx, "subbands > 50\n");
             return AVERROR_PATCHWELCOME;
         }
+        if (q->subpacket[s].subbands == 0) {
+            av_log_ask_for_sample(avctx, "subbands is 0\n");
+            return AVERROR_PATCHWELCOME;
+        }
         q->subpacket[s].gains1.now      = q->subpacket[s].gain_1;
         q->subpacket[s].gains1.previous = q->subpacket[s].gain_2;
         q->subpacket[s].gains2.now      = q->subpacket[s].gain_3;
         q->subpacket[s].gains2.previous = q->subpacket[s].gain_4;
 
-        if (q->num_subpackets + q->subpacket[s].num_channels > q->nb_channels) {
-            av_log(avctx, AV_LOG_ERROR, "Too many subpackets %d for channels %d\n", q->num_subpackets, q->nb_channels);
+        if (q->num_subpackets + q->subpacket[s].num_channels > q->avctx->channels) {
+            av_log(avctx, AV_LOG_ERROR, "Too many subpackets %d for channels %d\n", q->num_subpackets, q->avctx->channels);
             return AVERROR_INVALIDDATA;
         }
 
@@ -1281,16 +1254,15 @@
     }
 
     /* Try to catch some obviously faulty streams, othervise it might be exploitable */
-    if ((q->samples_per_channel == 256) || (q->samples_per_channel == 512)
-                || (q->samples_per_channel == 1024)) {
-    } else {
+    if (q->samples_per_channel != 256 && q->samples_per_channel != 512 &&
+        q->samples_per_channel != 1024) {
         av_log_ask_for_sample(avctx,
                               "unknown amount of samples_per_channel = %d\n",
                               q->samples_per_channel);
         return AVERROR_PATCHWELCOME;
     }
 
-    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
+    avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
     if (channel_mask)
         avctx->channel_layout = channel_mask;
     else
@@ -1315,4 +1287,6 @@
     .decode         = cook_decode_frame,
     .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("Cook / Cooker / Gecko (RealAudio G2)"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
+                                                      AV_SAMPLE_FMT_NONE },
 };
diff --git a/libavcodec/cpia.c b/libavcodec/cpia.c
index a631a05..26e067a 100644
--- a/libavcodec/cpia.c
+++ b/libavcodec/cpia.c
@@ -192,7 +192,7 @@
 static av_cold int cpia_decode_init(AVCodecContext *avctx)
 {
     // output pixel format
-    avctx->pix_fmt = PIX_FMT_YUV420P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV420P;
 
     /* The default timebase set by the v4l2 demuxer leads to probing which is buggy.
      * Set some reasonable time_base to skip this.
diff --git a/libavcodec/crystalhd.c b/libavcodec/crystalhd.c
index 503baaa..bf846d3 100644
--- a/libavcodec/crystalhd.c
+++ b/libavcodec/crystalhd.c
@@ -153,7 +153,7 @@
     { "crystalhd_downscale_width",
       "Turn on downscaling to the specified width",
       offsetof(CHDContext, sWidth),
-      AV_OPT_TYPE_INT, 0, 0, UINT32_MAX,
+      AV_OPT_TYPE_INT, {.i64 = 0}, 0, UINT32_MAX,
       AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM, },
     { NULL, },
 };
@@ -402,7 +402,7 @@
     av_log(avctx, AV_LOG_VERBOSE, "CrystalHD Init for %s\n",
            avctx->codec->name);
 
-    avctx->pix_fmt = PIX_FMT_YUYV422;
+    avctx->pix_fmt = AV_PIX_FMT_YUYV422;
 
     /* Initialize the library */
     priv               = avctx->priv_data;
@@ -1099,7 +1099,7 @@
     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
     .flush          = flush,
     .long_name      = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (CrystalHD acceleration)"),
-    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
+    .pix_fmts       = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
     .priv_class     = &h264_class,
 };
 #endif
@@ -1123,7 +1123,7 @@
     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
     .flush          = flush,
     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-2 Video (CrystalHD acceleration)"),
-    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
+    .pix_fmts       = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
     .priv_class     = &mpeg2_class,
 };
 #endif
@@ -1147,7 +1147,7 @@
     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
     .flush          = flush,
     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 (CrystalHD acceleration)"),
-    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
+    .pix_fmts       = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
     .priv_class     = &mpeg4_class,
 };
 #endif
@@ -1171,7 +1171,7 @@
     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
     .flush          = flush,
     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 Microsoft variant version 3 (CrystalHD acceleration)"),
-    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
+    .pix_fmts       = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
     .priv_class     = &msmpeg4_class,
 };
 #endif
@@ -1195,7 +1195,7 @@
     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
     .flush          = flush,
     .long_name      = NULL_IF_CONFIG_SMALL("SMPTE VC-1 (CrystalHD acceleration)"),
-    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
+    .pix_fmts       = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
     .priv_class     = &vc1_class,
 };
 #endif
@@ -1219,7 +1219,7 @@
     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
     .flush          = flush,
     .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Video 9 (CrystalHD acceleration)"),
-    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
+    .pix_fmts       = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
     .priv_class     = &wmv3_class,
 };
 #endif
diff --git a/libavcodec/cscd.c b/libavcodec/cscd.c
index bdcfdcc..8ba5de3 100644
--- a/libavcodec/cscd.c
+++ b/libavcodec/cscd.c
@@ -127,9 +127,9 @@
     CamStudioContext *c = avctx->priv_data;
     int stride;
     switch (avctx->bits_per_coded_sample) {
-        case 16: avctx->pix_fmt = PIX_FMT_RGB555LE; break;
-        case 24: avctx->pix_fmt = PIX_FMT_BGR24; break;
-        case 32: avctx->pix_fmt = PIX_FMT_BGRA; break;
+        case 16: avctx->pix_fmt = AV_PIX_FMT_RGB555LE; break;
+        case 24: avctx->pix_fmt = AV_PIX_FMT_BGR24; break;
+        case 32: avctx->pix_fmt = AV_PIX_FMT_BGRA; break;
         default:
             av_log(avctx, AV_LOG_ERROR,
                    "CamStudio codec error: invalid depth %i bpp\n",
diff --git a/libavcodec/cyuv.c b/libavcodec/cyuv.c
index df0a2d2..74c1077 100644
--- a/libavcodec/cyuv.c
+++ b/libavcodec/cyuv.c
@@ -93,9 +93,9 @@
      * of 4 pixels. Thus, the total size of the buffer ought to be:
      *    (3 * 16) + height * (width * 3 / 4) */
     if (buf_size == 48 + s->height * (s->width * 3 / 4)) {
-        avctx->pix_fmt = PIX_FMT_YUV411P;
+        avctx->pix_fmt = AV_PIX_FMT_YUV411P;
     } else if(buf_size == rawsize ) {
-        avctx->pix_fmt = PIX_FMT_UYVY422;
+        avctx->pix_fmt = AV_PIX_FMT_UYVY422;
     } else {
         av_log(avctx, AV_LOG_ERROR, "got a buffer with %d bytes when %d were expected\n",
                buf_size, 48 + s->height * (s->width * 3 / 4));
diff --git a/libavcodec/dca.h b/libavcodec/dca.h
index e754056..3da93aa 100644
--- a/libavcodec/dca.h
+++ b/libavcodec/dca.h
@@ -26,7 +26,7 @@
 #define AVCODEC_DCA_H
 
 #include <stdint.h>
-#include "symbols.h"
+#include "libavutil/internal.h"
 
 /** DCA syncwords, also used for bitstream type detection */
 #define DCA_MARKER_RAW_BE 0x7FFE8001
@@ -37,6 +37,6 @@
 /** DCA-HD specific block starts with this marker. */
 #define DCA_HD_MARKER     0x64582025
 
-extern AVCODEC_SYMBOL const uint32_t avpriv_dca_sample_rates[16];
+extern av_export const uint32_t avpriv_dca_sample_rates[16];
 
 #endif /* AVCODEC_DCA_H */
diff --git a/libavcodec/dca_parser.c b/libavcodec/dca_parser.c
index 5ccaacc..266520f 100644
--- a/libavcodec/dca_parser.c
+++ b/libavcodec/dca_parser.c
@@ -190,8 +190,7 @@
     /* read the duration and sample rate from the frame header */
     if (!dca_parse_params(buf, buf_size, &duration, &sample_rate)) {
         s->duration = duration;
-        if (!avctx->sample_rate)
-            avctx->sample_rate = sample_rate;
+        avctx->sample_rate = sample_rate;
     } else
         s->duration = 0;
 
diff --git a/libavcodec/dcadec.c b/libavcodec/dcadec.c
index 4e9f957..acbabd6 100644
--- a/libavcodec/dcadec.c
+++ b/libavcodec/dcadec.c
@@ -26,12 +26,13 @@
 #include <stddef.h>
 #include <stdio.h>
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
 #include "libavutil/float_dsp.h"
 #include "libavutil/intmath.h"
 #include "libavutil/intreadwrite.h"
 #include "libavutil/mathematics.h"
-#include "libavutil/audioconvert.h"
+#include "libavutil/samplefmt.h"
 #include "avcodec.h"
 #include "dsputil.h"
 #include "fft.h"
@@ -417,11 +418,12 @@
     DECLARE_ALIGNED(32, float, raXin)[32];
 
     int output;                 ///< type of output
-    float scale_bias;           ///< output scale
 
     DECLARE_ALIGNED(32, float, subband_samples)[DCA_BLOCKS_MAX][DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][8];
-    DECLARE_ALIGNED(32, float, samples)[(DCA_PRIM_CHANNELS_MAX + 1) * 256];
-    const float *samples_chanptr[DCA_PRIM_CHANNELS_MAX + 1];
+    float *samples_chanptr[DCA_PRIM_CHANNELS_MAX + 1];
+    float *extra_channels[DCA_PRIM_CHANNELS_MAX + 1];
+    uint8_t *extra_channels_buffer;
+    unsigned int extra_channels_buffer_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
@@ -446,7 +448,6 @@
     int xxch_chset_nch[4];
     float xxch_dmix_sf[DCA_CHSETS_MAX];
 
-    uint32_t xxch_downmix;        /* downmix enabled per channel set */
     uint32_t xxch_dmix_embedded;  /* lower layer has mix pre-embedded, per chset */
     float xxch_dmix_coeff[DCA_PRIM_CHANNELS_MAX][32]; /* worst case sizing */
 
@@ -595,7 +596,6 @@
             s->xxch_dmix_sf[s->xxch_chset] = scale_factor;
 
             for (i = base_channel; i < s->prim_channels; i++) {
-                s->xxch_downmix |= (1 << i);
                 mask[i] = get_bits(&s->gb, s->xxch_nbits_spk_mask);
             }
 
@@ -737,6 +737,12 @@
     s->lfe               = get_bits(&s->gb, 2);
     s->predictor_history = get_bits(&s->gb, 1);
 
+    if (s->lfe == 3) {
+        s->lfe = 0;
+        av_log_ask_for_sample(s->avctx, "LFE is 3\n");
+        return AVERROR_PATCHWELCOME;
+    }
+
     /* TODO: check CRC */
     if (s->crc_present)
         s->header_crc    = get_bits(&s->gb, 16);
@@ -1169,20 +1175,20 @@
 }
 
 /* downmixing routines */
-#define MIX_REAR1(samples, si1, rs, coef)           \
-    samples[i]     += samples[si1] * coef[rs][0];   \
-    samples[i+256] += samples[si1] * coef[rs][1];
+#define MIX_REAR1(samples, s1, rs, coef)            \
+    samples[0][i] += samples[s1][i] * coef[rs][0];  \
+    samples[1][i] += samples[s1][i] * coef[rs][1];
 
-#define MIX_REAR2(samples, si1, si2, rs, coef)                                     \
-    samples[i]     += samples[si1] * coef[rs][0] + samples[si2] * coef[rs + 1][0]; \
-    samples[i+256] += samples[si1] * coef[rs][1] + samples[si2] * coef[rs + 1][1];
+#define MIX_REAR2(samples, s1, s2, rs, coef)                                          \
+    samples[0][i] += samples[s1][i] * coef[rs][0] + samples[s2][i] * coef[rs + 1][0]; \
+    samples[1][i] += samples[s1][i] * coef[rs][1] + samples[s2][i] * coef[rs + 1][1];
 
 #define MIX_FRONT3(samples, coef)                                      \
-    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];
+    t = samples[c][i];                                                 \
+    u = samples[l][i];                                                 \
+    v = samples[r][i];                                                 \
+    samples[0][i] = t * coef[0][0] + u * coef[1][0] + v * coef[2][0];  \
+    samples[1][i] = t * coef[0][1] + u * coef[1][1] + v * coef[2][1];
 
 #define DOWNMIX_TO_STEREO(op1, op2)             \
     for (i = 0; i < 256; i++) {                 \
@@ -1190,7 +1196,7 @@
         op2                                     \
     }
 
-static void dca_downmix(float *samples, int srcfmt,
+static void dca_downmix(float **samples, int srcfmt,
                         int downmix_coef[DCA_PRIM_CHANNELS_MAX][2],
                         const int8_t *channel_mapping)
 {
@@ -1210,41 +1216,41 @@
     case DCA_STEREO_TOTAL:
     case DCA_STEREO_SUMDIFF:
     case DCA_4F2R:
-        av_log(NULL, 0, "Not implemented!\n");
+        av_log(NULL, AV_LOG_ERROR, "Not implemented!\n");
         break;
     case DCA_STEREO:
         break;
     case DCA_3F:
-        c = channel_mapping[0] * 256;
-        l = channel_mapping[1] * 256;
-        r = channel_mapping[2] * 256;
+        c = channel_mapping[0];
+        l = channel_mapping[1];
+        r = channel_mapping[2];
         DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef), );
         break;
     case DCA_2F1R:
-        s = channel_mapping[2] * 256;
-        DOWNMIX_TO_STEREO(MIX_REAR1(samples, i + s, 2, coef), );
+        s = channel_mapping[2];
+        DOWNMIX_TO_STEREO(MIX_REAR1(samples, 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;
+        c = channel_mapping[0];
+        l = channel_mapping[1];
+        r = channel_mapping[2];
+        s = channel_mapping[3];
         DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
-                          MIX_REAR1(samples, i + s, 3, coef));
+                          MIX_REAR1(samples, s, 3, coef));
         break;
     case DCA_2F2R:
-        sl = channel_mapping[2] * 256;
-        sr = channel_mapping[3] * 256;
-        DOWNMIX_TO_STEREO(MIX_REAR2(samples, i + sl, i + sr, 2, coef), );
+        sl = channel_mapping[2];
+        sr = channel_mapping[3];
+        DOWNMIX_TO_STEREO(MIX_REAR2(samples, sl, 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;
+        c  = channel_mapping[0];
+        l  = channel_mapping[1];
+        r  = channel_mapping[2];
+        sl = channel_mapping[3];
+        sr = channel_mapping[4];
         DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
-                          MIX_REAR2(samples, i + sl, i + sr, 3, coef));
+                          MIX_REAR2(samples, sl, sr, 3, coef));
         break;
     }
 }
@@ -1440,22 +1446,23 @@
     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] */);
+        if (s->channel_order_tab[k] >= 0)
+            qmf_32_subbands(s, k, subband_samples[k],
+                            s->samples_chanptr[s->channel_order_tab[k]],
+                            M_SQRT1_2 / 32768.0 /* pcm_to_double[s->source_pcm_res] */);
     }
 
     /* Down mixing */
     if (s->avctx->request_channels == 2 && s->prim_channels > 2) {
-        dca_downmix(s->samples, s->amode, s->downmix_coef, s->channel_order_tab);
+        dca_downmix(s->samples_chanptr, s->amode, s->downmix_coef, s->channel_order_tab);
     }
 
     /* Generate LFE samples for this subsubframe FIXME!!! */
     if (s->output & DCA_LFE) {
         lfe_interpolation_fir(s, s->lfe, 2 * s->lfe,
                               s->lfe_data + 2 * s->lfe * (block_index + 4),
-                              &s->samples[256 * s->lfe_index],
-                              (1.0 / 256.0) * s->scale_bias);
+                              s->samples_chanptr[s->lfe_index],
+                              1.0 / (256.0 * 32768.0));
         /* Outputs 20bits pcm samples */
     }
 
@@ -1902,7 +1909,6 @@
     core_spk               = get_bits(&s->gb, spkmsk_bits);
     s->xxch_core_spkmask   = core_spk;
     s->xxch_nbits_spk_mask = spkmsk_bits;
-    s->xxch_downmix        = 0;
     s->xxch_dmix_embedded  = 0;
 
     /* skip to the end of the header */
@@ -2067,13 +2073,12 @@
     int lfe_samples;
     int num_core_channels = 0;
     int i, ret;
-    float *samples_flt;
+    float **samples_flt;
     float *src_chan;
     float *dst_chan;
-    int16_t *samples_s16;
     DCAContext *s = avctx->priv_data;
     int core_ss_end;
-    int channels;
+    int channels, full_channels;
     float scale;
     int achan;
     int chset;
@@ -2081,7 +2086,6 @@
     int lavc;
     int posn;
     int j, k;
-    int ch;
     int endch;
 
     s->xch_present = 0;
@@ -2160,6 +2164,11 @@
                     continue;
                 }
 
+                if (s->xch_base_channel < 2) {
+                    av_log_ask_for_sample(avctx, "XCh with fewer than 2 base channels is not supported\n");
+                    continue;
+                }
+
                 /* much like core primary audio coding header */
                 dca_parse_audio_coding_header(s, s->xch_base_channel, 0);
 
@@ -2215,7 +2224,7 @@
 
     avctx->profile = s->profile;
 
-    channels = s->prim_channels + !!s->lfe;
+    full_channels = channels = s->prim_channels + !!s->lfe;
 
     /* If we have XXCH then the channel layout is managed differently */
     /* note that XLL will also have another way to do things */
@@ -2251,6 +2260,11 @@
                 s->channel_order_tab[channels - 1 - !!s->lfe] < 0)
                 return AVERROR_INVALIDDATA;
 
+            if (av_get_channel_layout_nb_channels(avctx->channel_layout) != channels) {
+                av_log(avctx, AV_LOG_ERROR, "Number of channels %d mismatches layout %d\n", channels, av_get_channel_layout_nb_channels(avctx->channel_layout));
+                return AVERROR_INVALIDDATA;
+            }
+
             if (avctx->request_channels == 2 && s->prim_channels > 2) {
                 channels = 2;
                 s->output = DCA_STEREO;
@@ -2267,7 +2281,7 @@
             return AVERROR_INVALIDDATA;
         }
 
-        s->xxch_downmix = 0;
+        s->xxch_dmix_embedded = 0;
     } else {
         /* we only get here if an XXCH channel set can be added to the mix */
         channel_mask = s->xxch_core_spkmask;
@@ -2342,19 +2356,46 @@
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         return ret;
     }
-    samples_flt = (float *)   s->frame.data[0];
-    samples_s16 = (int16_t *) s->frame.data[0];
+    samples_flt = (float  **) s->frame.extended_data;
+
+    /* allocate buffer for extra channels if downmixing */
+    if (avctx->channels < full_channels) {
+        ret = av_samples_get_buffer_size(NULL, full_channels - channels,
+                                         s->frame.nb_samples,
+                                         avctx->sample_fmt, 0);
+        if (ret < 0)
+            return ret;
+
+        av_fast_malloc(&s->extra_channels_buffer,
+                       &s->extra_channels_buffer_size, ret);
+        if (!s->extra_channels_buffer)
+            return AVERROR(ENOMEM);
+
+        ret = av_samples_fill_arrays((uint8_t **)s->extra_channels, NULL,
+                                     s->extra_channels_buffer,
+                                     full_channels - channels,
+                                     s->frame.nb_samples, avctx->sample_fmt, 0);
+        if (ret < 0)
+            return ret;
+    }
 
     /* filter to get final output */
     for (i = 0; i < (s->sample_blocks / 8); i++) {
+        int ch;
+
+        for (ch = 0; ch < channels; ch++)
+            s->samples_chanptr[ch] = samples_flt[ch] + i * 256;
+        for (; ch < full_channels; ch++)
+            s->samples_chanptr[ch] = s->extra_channels[ch - channels] + i * 256;
+
         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;
+            float *back_chan = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel]];
+            float *lt_chan   = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel - 2]];
+            float *rt_chan   = s->samples_chanptr[s->channel_order_tab[s->xch_base_channel - 1]];
             s->fdsp.vector_fmac_scalar(lt_chan, back_chan, -M_SQRT1_2, 256);
             s->fdsp.vector_fmac_scalar(rt_chan, back_chan, -M_SQRT1_2, 256);
         }
@@ -2370,12 +2411,12 @@
                 /* undo downmix */
                 for (j = ch; j < endch; j++) {
                     if (mask & (1 << j)) { /* this channel has been mixed-out */
-                        src_chan = s->samples + s->channel_order_tab[j] * 256;
+                        src_chan = s->samples_chanptr[s->channel_order_tab[j]];
                         for (k = 0; k < endch; k++) {
                             achan = s->channel_order_tab[k];
                             scale = s->xxch_dmix_coeff[j][k];
                             if (scale != 0.0) {
-                                dst_chan = s->samples + achan * 256;
+                                dst_chan = s->samples_chanptr[achan];
                                 s->fdsp.vector_fmac_scalar(dst_chan, src_chan,
                                                            -scale, 256);
                             }
@@ -2388,14 +2429,14 @@
                     scale = s->xxch_dmix_sf[chset];
 
                     for (j = 0; j < ch; j++) {
-                        src_chan = s->samples + s->channel_order_tab[j] * 256;
+                        src_chan = s->samples_chanptr[s->channel_order_tab[j]];
                         for (k = 0; k < 256; k++)
                             src_chan[k] *= scale;
                     }
 
                     /* LFE channel is always part of core, scale if it exists */
                     if (s->lfe) {
-                        src_chan = s->samples + s->lfe_index * 256;
+                        src_chan = s->samples_chanptr[s->lfe_index];
                         for (k = 0; k < 256; k++)
                             src_chan[k] *= scale;
                     }
@@ -2405,17 +2446,6 @@
             }
 
         }
-
-        if (avctx->sample_fmt == AV_SAMPLE_FMT_FLT) {
-            s->fmt_conv.float_interleave(samples_flt, s->samples_chanptr, 256,
-                                         channels);
-            samples_flt += 256 * channels;
-        } else {
-            s->fmt_conv.float_to_int16_interleave(samples_s16,
-                                                  s->samples_chanptr, 256,
-                                                  channels);
-            samples_s16 += 256 * channels;
-        }
     }
 
     /* update lfe history */
@@ -2440,7 +2470,6 @@
 static av_cold int dca_decode_init(AVCodecContext *avctx)
 {
     DCAContext *s = avctx->priv_data;
-    int i;
 
     s->avctx = avctx;
     dca_init_vlcs();
@@ -2451,16 +2480,7 @@
     ff_dcadsp_init(&s->dcadsp);
     ff_fmt_convert_init(&s->fmt_conv, avctx);
 
-    for (i = 0; i < DCA_PRIM_CHANNELS_MAX + 1; i++)
-        s->samples_chanptr[i] = s->samples + i * 256;
-
-    if (avctx->request_sample_fmt == AV_SAMPLE_FMT_FLT) {
-        avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
-        s->scale_bias     = 1.0 / 32768.0;
-    } else {
-        avctx->sample_fmt = AV_SAMPLE_FMT_S16;
-        s->scale_bias     = 1.0;
-    }
+    avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
 
     /* allow downmixing to stereo */
     if (avctx->channels > 0 && avctx->request_channels < avctx->channels &&
@@ -2478,6 +2498,7 @@
 {
     DCAContext *s = avctx->priv_data;
     ff_mdct_end(&s->imdct);
+    av_freep(&s->extra_channels_buffer);
     return 0;
 }
 
@@ -2500,8 +2521,7 @@
     .close           = dca_decode_end,
     .long_name       = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
     .capabilities    = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
-    .sample_fmts     = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLT,
-                                                       AV_SAMPLE_FMT_S16,
+    .sample_fmts     = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
                                                        AV_SAMPLE_FMT_NONE },
     .profiles        = NULL_IF_CONFIG_SMALL(profiles),
 };
diff --git a/libavcodec/dcaenc.c b/libavcodec/dcaenc.c
index 104fd87..7d55bb5 100644
--- a/libavcodec/dcaenc.c
+++ b/libavcodec/dcaenc.c
@@ -21,9 +21,9 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
 #include "libavutil/avassert.h"
-#include "libavutil/audioconvert.h"
 #include "avcodec.h"
 #include "get_bits.h"
 #include "internal.h"
diff --git a/libavcodec/dct-test.c b/libavcodec/dct-test.c
index 6cefd9d..7727f0b 100644
--- a/libavcodec/dct-test.c
+++ b/libavcodec/dct-test.c
@@ -86,7 +86,7 @@
 
 #if HAVE_MMX_INLINE
     { "MMX",            ff_fdct_mmx,           NO_PERM,   AV_CPU_FLAG_MMX     },
-    { "MMXEXT",         ff_fdct_mmx2,          NO_PERM,   AV_CPU_FLAG_MMXEXT  },
+    { "MMXEXT",         ff_fdct_mmxext,        NO_PERM,   AV_CPU_FLAG_MMXEXT  },
     { "SSE2",           ff_fdct_sse2,          NO_PERM,   AV_CPU_FLAG_SSE2    },
 #endif
 
@@ -131,7 +131,7 @@
 #endif
     { "SIMPLE-MMX",     ff_simple_idct_mmx,  MMX_SIMPLE_PERM, AV_CPU_FLAG_MMX },
     { "XVID-MMX",       ff_idct_xvid_mmx,      NO_PERM,   AV_CPU_FLAG_MMX,  1 },
-    { "XVID-MMXEXT",    ff_idct_xvid_mmx2,     NO_PERM,   AV_CPU_FLAG_MMXEXT, 1 },
+    { "XVID-MMXEXT",    ff_idct_xvid_mmxext,   NO_PERM,   AV_CPU_FLAG_MMXEXT, 1 },
     { "XVID-SSE2",      ff_idct_xvid_sse2,     SSE2_PERM, AV_CPU_FLAG_SSE2, 1 },
 #if ARCH_X86_64 && HAVE_YASM
     { "PR-SSE2",        ff_prores_idct_put_10_sse2_wrap,     TRANSPOSE_PERM, AV_CPU_FLAG_SSE2, 1 },
diff --git a/libavcodec/dct.c b/libavcodec/dct.c
index 2782bd9..e2ac0a8 100644
--- a/libavcodec/dct.c
+++ b/libavcodec/dct.c
@@ -209,8 +209,8 @@
     }
 
     s->dct32 = ff_dct32_float;
-    if (HAVE_MMX)
-        ff_dct_init_mmx(s);
+    if (ARCH_X86)
+        ff_dct_init_x86(s);
 
     return 0;
 }
diff --git a/libavcodec/dct.h b/libavcodec/dct.h
index bb17d75..8995f10 100644
--- a/libavcodec/dct.h
+++ b/libavcodec/dct.h
@@ -47,6 +47,6 @@
 int  ff_dct_init(DCTContext *s, int nbits, enum DCTTransformType type);
 void ff_dct_end (DCTContext *s);
 
-void ff_dct_init_mmx(DCTContext *s);
+void ff_dct_init_x86(DCTContext *s);
 
 #endif /* AVCODEC_DCT_H */
diff --git a/libavcodec/dfa.c b/libavcodec/dfa.c
index 1159731..548a649 100644
--- a/libavcodec/dfa.c
+++ b/libavcodec/dfa.c
@@ -25,7 +25,7 @@
 #include "bytestream.h"
 
 #include "libavutil/imgutils.h"
-#include "libavutil/lzo.h" // for av_memcpy_backptr
+#include "libavutil/mem.h"
 
 typedef struct DfaContext {
     AVFrame pic;
@@ -38,14 +38,14 @@
 {
     DfaContext *s = avctx->priv_data;
 
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     if (!avctx->width || !avctx->height)
         return AVERROR_INVALIDDATA;
 
     av_assert0(av_image_check_size(avctx->width, avctx->height, 0, avctx) >= 0);
 
-    s->frame_buf = av_mallocz(avctx->width * avctx->height + AV_LZO_OUTPUT_PADDING);
+    s->frame_buf = av_mallocz(avctx->width * avctx->height);
     if (!s->frame_buf)
         return AVERROR(ENOMEM);
 
@@ -126,9 +126,7 @@
             count = ((v >> 13) + 2) << 1;
             if (frame - frame_start < offset || frame_end - frame < count)
                 return AVERROR_INVALIDDATA;
-            // can't use av_memcpy_backptr() since it can overwrite following pixels
-            for (v = 0; v < count; v++)
-                frame[v] = frame[v - offset];
+            av_memcpy_backptr(frame, offset, count);
             frame += count;
         } else if (bitbuf & (mask << 1)) {
             frame += bytestream2_get_le16(gb);
@@ -345,7 +343,7 @@
             pal_elems = FFMIN(chunk_size / 3, 256);
             for (i = 0; i < pal_elems; i++) {
                 s->pal[i] = bytestream2_get_be24(&gb) << 2;
-                s->pal[i] |= 0xFF << 24 | (s->pal[i] >> 6) & 0x30303;
+                s->pal[i] |= 0xFFU << 24 | (s->pal[i] >> 6) & 0x30303;
             }
             s->pic.palette_has_changed = 1;
         } else if (chunk_type <= 9) {
diff --git a/libavcodec/dirac.c b/libavcodec/dirac.c
index b26fff7..4fcb3a2 100644
--- a/libavcodec/dirac.c
+++ b/libavcodec/dirac.c
@@ -106,9 +106,9 @@
 };
 
 /* [DIRAC_STD] Table 10.2 Supported chroma sampling formats + luma Offset */
-static const enum PixelFormat dirac_pix_fmt[2][3] = {
-    { PIX_FMT_YUV444P,  PIX_FMT_YUV422P,  PIX_FMT_YUV420P  },
-    { PIX_FMT_YUVJ444P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ420P },
+static const enum AVPixelFormat dirac_pix_fmt[2][3] = {
+    { AV_PIX_FMT_YUV444P,  AV_PIX_FMT_YUV422P,  AV_PIX_FMT_YUV420P  },
+    { AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ420P },
 };
 
 /* [DIRAC_STD] 10.3 Parse Source Parameters.
@@ -164,7 +164,7 @@
     /* [DIRAC_STD] preset_frame_rate(video_params, index) */
     if (source->frame_rate_index > 0) {
         if (source->frame_rate_index <= 8)
-            frame_rate = avpriv_frame_rate_tab[source->frame_rate_index];  /* [DIRAC_STD] Table 10.3 values 1-8  */
+            frame_rate = ff_mpeg12_frame_rate_tab[source->frame_rate_index];
         else
              /* [DIRAC_STD] Table 10.3 values 9-10 */
             frame_rate = dirac_frame_rate[source->frame_rate_index-9];
diff --git a/libavcodec/dirac.h b/libavcodec/dirac.h
index 542d491..b0f955b 100644
--- a/libavcodec/dirac.h
+++ b/libavcodec/dirac.h
@@ -34,7 +34,7 @@
 #include "avcodec.h"
 #include "get_bits.h"
 
-typedef struct {
+typedef struct dirac_source_params {
     unsigned width;
     unsigned height;
     uint8_t chroma_format;          ///< 0: 444  1: 422  2: 420
diff --git a/libavcodec/diracdec.c b/libavcodec/diracdec.c
index 13d9e47..6e81491 100644
--- a/libavcodec/diracdec.c
+++ b/libavcodec/diracdec.c
@@ -346,7 +346,7 @@
 
     /* fixme: allocate using real stride here */
     s->sbsplit  = av_malloc(sbwidth * sbheight);
-    s->blmotion = av_malloc(sbwidth * sbheight * 4 * sizeof(*s->blmotion));
+    s->blmotion = av_malloc(sbwidth * sbheight * 16 * sizeof(*s->blmotion));
     s->edge_emu_buffer_base = av_malloc((w+64)*MAX_BLOCKSIZE);
 
     s->mctmp     = av_malloc((w+64+MAX_BLOCKSIZE) * (h*MAX_BLOCKSIZE) * sizeof(*s->mctmp));
@@ -996,6 +996,10 @@
                 s->lowdelay.quant[level][3] = svq3_get_ue_golomb(gb);
             }
         } else {
+            if (s->wavelet_depth > 4) {
+                av_log(s->avctx,AV_LOG_ERROR,"Mandatory custom low delay matrix missing for depth %d\n", s->wavelet_depth);
+                return AVERROR_INVALIDDATA;
+            }
             /* default quantization matrix */
             for (level = 0; level < s->wavelet_depth; level++)
                 for (i = 0; i < 4; i++) {
@@ -1404,8 +1408,8 @@
     }
 
     /* fixme: v/h _edge_pos */
-    if ((unsigned)x > p->width +EDGE_WIDTH/2 - p->xblen ||
-        (unsigned)y > p->height+EDGE_WIDTH/2 - p->yblen) {
+    if ((unsigned)x > FFMAX(p->width +EDGE_WIDTH/2 - p->xblen, 0) ||
+        (unsigned)y > FFMAX(p->height+EDGE_WIDTH/2 - p->yblen, 0)) {
         for (i = 0; i < nplanes; i++) {
             ff_emulated_edge_mc(s->edge_emu_buffer[i], src[i], p->stride,
                                 p->xblen, p->yblen, x, y,
@@ -1665,6 +1669,7 @@
                 if (!s->all_frames[j].avframe.data[0]) {
                     s->ref_pics[i] = &s->all_frames[j];
                     s->avctx->get_buffer(s->avctx, &s->ref_pics[i]->avframe);
+                    break;
                 }
     }
 
diff --git a/libavcodec/dnxhddata.c b/libavcodec/dnxhddata.c
index c3d2204..9e2e014 100644
--- a/libavcodec/dnxhddata.c
+++ b/libavcodec/dnxhddata.c
@@ -1038,7 +1038,7 @@
         if (cid->width == avctx->width && cid->height == avctx->height &&
             cid->interlaced == !!(avctx->flags & CODEC_FLAG_INTERLACED_DCT) &&
             cid->bit_depth == bit_depth) {
-            for (j = 0; j < sizeof(cid->bit_rates); j++) {
+            for (j = 0; j < FF_ARRAY_ELEMS(cid->bit_rates); j++) {
                 if (cid->bit_rates[j] == mbs)
                     return cid->cid;
             }
diff --git a/libavcodec/dnxhddata.h b/libavcodec/dnxhddata.h
index 8572d91..01c3f58 100644
--- a/libavcodec/dnxhddata.h
+++ b/libavcodec/dnxhddata.h
@@ -24,9 +24,9 @@
 
 #include <stdint.h>
 #include "avcodec.h"
-#include "symbols.h"
+#include "libavutil/internal.h"
 
-typedef struct {
+typedef struct CIDEntry {
     int cid;
     unsigned int width, height;
     int interlaced;
@@ -45,7 +45,7 @@
     int bit_rates[5]; ///< Helpher to choose variants, rounded to nearest 5Mb/s
 } CIDEntry;
 
-extern AVCODEC_SYMBOL const CIDEntry ff_dnxhd_cid_table[];
+extern av_export const CIDEntry ff_dnxhd_cid_table[];
 
 int ff_dnxhd_get_cid_table(int cid);
 int ff_dnxhd_find_cid(AVCodecContext *avctx, int bit_depth);
diff --git a/libavcodec/dnxhddec.c b/libavcodec/dnxhddec.c
index bbf89bf..4f3968a 100644
--- a/libavcodec/dnxhddec.c
+++ b/libavcodec/dnxhddec.c
@@ -133,7 +133,7 @@
     av_dlog(ctx->avctx, "width %d, height %d\n", ctx->width, ctx->height);
 
     if (buf[0x21] & 0x40) {
-        ctx->avctx->pix_fmt = PIX_FMT_YUV422P10;
+        ctx->avctx->pix_fmt = AV_PIX_FMT_YUV422P10;
         ctx->avctx->bits_per_raw_sample = 10;
         if (ctx->bit_depth != 10) {
             ff_dsputil_init(&ctx->dsp, ctx->avctx);
@@ -141,7 +141,7 @@
             ctx->decode_dct_block = dnxhd_decode_dct_block_10;
         }
     } else {
-        ctx->avctx->pix_fmt = PIX_FMT_YUV422P;
+        ctx->avctx->pix_fmt = AV_PIX_FMT_YUV422P;
         ctx->avctx->bits_per_raw_sample = 8;
         if (ctx->bit_depth != 8) {
             ff_dsputil_init(&ctx->dsp, ctx->avctx);
diff --git a/libavcodec/dnxhdenc.c b/libavcodec/dnxhdenc.c
index c8b031e..690e64f 100644
--- a/libavcodec/dnxhdenc.c
+++ b/libavcodec/dnxhdenc.c
@@ -253,10 +253,10 @@
     int i, index, bit_depth;
 
     switch (avctx->pix_fmt) {
-    case PIX_FMT_YUV422P:
+    case AV_PIX_FMT_YUV422P:
         bit_depth = 8;
         break;
-    case PIX_FMT_YUV422P10:
+    case AV_PIX_FMT_YUV422P10:
         bit_depth = 10;
         break;
     default:
@@ -272,6 +272,7 @@
     av_log(avctx, AV_LOG_DEBUG, "cid %d\n", ctx->cid);
 
     index = ff_dnxhd_get_cid_table(ctx->cid);
+    av_assert0(index >= 0);
     ctx->cid_table = &ff_dnxhd_cid_table[index];
 
     ctx->m.avctx = avctx;
@@ -1021,9 +1022,9 @@
     .encode2        = dnxhd_encode_picture,
     .close          = dnxhd_encode_end,
     .capabilities   = CODEC_CAP_SLICE_THREADS,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUV422P,
-                                                  PIX_FMT_YUV422P10,
-                                                  PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV422P,
+                                                  AV_PIX_FMT_YUV422P10,
+                                                  AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("VC3/DNxHD"),
     .priv_class     = &class,
     .defaults       = dnxhd_defaults,
diff --git a/libavcodec/dnxhdenc.h b/libavcodec/dnxhdenc.h
index e57047d..36a42fb 100644
--- a/libavcodec/dnxhdenc.h
+++ b/libavcodec/dnxhdenc.h
@@ -29,12 +29,12 @@
 #include "mpegvideo.h"
 #include "dnxhddata.h"
 
-typedef struct {
+typedef struct RCCMPEntry {
     uint16_t mb;
     int value;
 } RCCMPEntry;
 
-typedef struct {
+typedef struct RCEntry {
     int ssd;
     int bits;
 } RCEntry;
diff --git a/libavcodec/dpcm.c b/libavcodec/dpcm.c
index a7c9bb1..c9c45c6 100644
--- a/libavcodec/dpcm.c
+++ b/libavcodec/dpcm.c
@@ -44,7 +44,6 @@
 
 typedef struct DPCMContext {
     AVFrame frame;
-    int channels;
     int16_t roq_square_array[256];
     int sample[2];                  ///< previous sample (for SOL_DPCM)
     const int8_t *sol_table;        ///< delta table for SOL_DPCM
@@ -119,11 +118,10 @@
     int i;
 
     if (avctx->channels < 1 || avctx->channels > 2) {
-        av_log(avctx, AV_LOG_INFO, "invalid number of channels\n");
+        av_log(avctx, AV_LOG_ERROR, "invalid number of channels\n");
         return AVERROR(EINVAL);
     }
 
-    s->channels = avctx->channels;
     s->sample[0] = s->sample[1] = 0;
 
     switch(avctx->codec->id) {
@@ -179,7 +177,7 @@
     int out = 0, ret;
     int predictor[2];
     int ch = 0;
-    int stereo = s->channels - 1;
+    int stereo = avctx->channels - 1;
     int16_t *output_samples, *samples_end;
     GetByteContext gb;
 
@@ -193,10 +191,10 @@
         out = buf_size - 8;
         break;
     case AV_CODEC_ID_INTERPLAY_DPCM:
-        out = buf_size - 6 - s->channels;
+        out = buf_size - 6 - avctx->channels;
         break;
     case AV_CODEC_ID_XAN_DPCM:
-        out = buf_size - 2 * s->channels;
+        out = buf_size - 2 * avctx->channels;
         break;
     case AV_CODEC_ID_SOL_DPCM:
         if (avctx->codec_tag != 3)
@@ -209,12 +207,12 @@
         av_log(avctx, AV_LOG_ERROR, "packet is too small\n");
         return AVERROR(EINVAL);
     }
-    if (out % s->channels) {
+    if (out % avctx->channels) {
         av_log(avctx, AV_LOG_WARNING, "channels have differing number of samples\n");
     }
 
     /* get output buffer */
-    s->frame.nb_samples = (out + s->channels - 1) / s->channels;
+    s->frame.nb_samples = (out + avctx->channels - 1) / avctx->channels;
     if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         return ret;
@@ -248,7 +246,7 @@
     case AV_CODEC_ID_INTERPLAY_DPCM:
         bytestream2_skipu(&gb, 6);  /* skip over the stream mask and stream length */
 
-        for (ch = 0; ch < s->channels; ch++) {
+        for (ch = 0; ch < avctx->channels; ch++) {
             predictor[ch] = sign_extend(bytestream2_get_le16u(&gb), 16);
             *output_samples++ = predictor[ch];
         }
@@ -268,7 +266,7 @@
     {
         int shift[2] = { 4, 4 };
 
-        for (ch = 0; ch < s->channels; ch++)
+        for (ch = 0; ch < avctx->channels; ch++)
             predictor[ch] = sign_extend(bytestream2_get_le16u(&gb), 16);
 
         ch = 0;
diff --git a/libavcodec/dpx.c b/libavcodec/dpx.c
index 71cf439..4d09efe 100644
--- a/libavcodec/dpx.c
+++ b/libavcodec/dpx.c
@@ -41,13 +41,27 @@
     return temp;
 }
 
+static uint16_t read10in32(const uint8_t **ptr, uint32_t * lbuf,
+                                  int * n_datum, int is_big)
+{
+    if (*n_datum)
+        (*n_datum)--;
+    else {
+        *lbuf = read32(ptr, is_big);
+        *n_datum = 2;
+    }
+
+    *lbuf = (*lbuf << 10) | (*lbuf >> 22);
+
+    return *lbuf & 0x3FF;
+}
+
 static int decode_frame(AVCodecContext *avctx,
                         void *data,
                         int *data_size,
                         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;
@@ -57,10 +71,10 @@
     unsigned int offset;
     int magic_num, endian;
     int x, y, i;
-    int w, h, stride, bits_per_color, descriptor, elements, target_packet_size, source_packet_size;
-    int planar;
+    int w, h, bits_per_color, descriptor, elements, packing, total_size;
 
-    unsigned int rgbBuffer;
+    unsigned int rgbBuffer = 0;
+    int n_datum = 0;
 
     if (avpkt->size <= 1634) {
         av_log(avctx, AV_LOG_ERROR, "Packet too small for DPX header\n");
@@ -90,6 +104,11 @@
     buf = avpkt->data + 0x304;
     w = read32(&buf, endian);
     h = read32(&buf, endian);
+    if (av_image_check_size(w, h, 0, avctx))
+        return AVERROR(EINVAL);
+
+    if (w != avctx->width || h != avctx->height)
+        avcodec_set_dimensions(avctx, w, h);
 
     // Need to end in 0x320 to read the descriptor
     buf += 20;
@@ -99,8 +118,10 @@
     buf += 3;
     avctx->bits_per_raw_sample =
     bits_per_color = buf[0];
+    buf++;
+    packing = *((uint16_t*)buf);
 
-    buf += 825;
+    buf += 824;
     avctx->sample_aspect_ratio.num = read32(&buf, endian);
     avctx->sample_aspect_ratio.den = read32(&buf, endian);
     if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0)
@@ -125,39 +146,39 @@
     switch (bits_per_color) {
         case 8:
             if (elements == 4) {
-                avctx->pix_fmt = PIX_FMT_RGBA;
+                avctx->pix_fmt = AV_PIX_FMT_RGBA;
             } else {
-                avctx->pix_fmt = PIX_FMT_RGB24;
+                avctx->pix_fmt = AV_PIX_FMT_RGB24;
             }
-            source_packet_size = elements;
-            target_packet_size = elements;
-            planar = 0;
+            total_size = avctx->width * avctx->height * elements;
             break;
         case 10:
-            avctx->pix_fmt = PIX_FMT_GBRP10;
-            target_packet_size = 6;
-            source_packet_size = 4;
-            planar = 1;
+            if (!packing) {
+                av_log(avctx, AV_LOG_ERROR, "Packing to 32bit required\n");
+                return -1;
+            }
+            avctx->pix_fmt = AV_PIX_FMT_GBRP10;
+            total_size = (4 * avctx->width * avctx->height * elements) / 3;
             break;
         case 12:
-            if (endian) {
-                avctx->pix_fmt = elements == 4 ? PIX_FMT_GBRP12BE : PIX_FMT_GBRP12BE;
-            } else {
-                avctx->pix_fmt = elements == 4 ? PIX_FMT_GBRP12LE : PIX_FMT_GBRP12LE;
+            if (!packing) {
+                av_log(avctx, AV_LOG_ERROR, "Packing to 16bit required\n");
+                return -1;
             }
-            target_packet_size = 6;
-            source_packet_size = 6;
-            planar = 1;
+            if (endian) {
+                avctx->pix_fmt = AV_PIX_FMT_GBRP12BE;
+            } else {
+                avctx->pix_fmt = AV_PIX_FMT_GBRP12LE;
+            }
+            total_size = 2 * avctx->width * avctx->height * elements;
             break;
         case 16:
             if (endian) {
-                avctx->pix_fmt = elements == 4 ? PIX_FMT_RGBA64BE : PIX_FMT_RGB48BE;
+                avctx->pix_fmt = elements == 4 ? AV_PIX_FMT_RGBA64BE : AV_PIX_FMT_RGB48BE;
             } else {
-                avctx->pix_fmt = elements == 4 ? PIX_FMT_RGBA64LE : PIX_FMT_RGB48LE;
+                avctx->pix_fmt = elements == 4 ? AV_PIX_FMT_RGBA64LE : AV_PIX_FMT_RGB48LE;
             }
-            target_packet_size =
-            source_packet_size = elements * 2;
-            planar = 0;
+            total_size = 2 * avctx->width * avctx->height * elements;
             break;
         default:
             av_log(avctx, AV_LOG_ERROR, "Unsupported color depth : %d\n", bits_per_color);
@@ -166,10 +187,6 @@
 
     if (s->picture.data[0])
         avctx->release_buffer(avctx, &s->picture);
-    if (av_image_check_size(w, h, 0, avctx))
-        return -1;
-    if (w != avctx->width || h != avctx->height)
-        avcodec_set_dimensions(avctx, w, h);
     if (avctx->get_buffer(avctx, p) < 0) {
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         return -1;
@@ -180,68 +197,68 @@
 
     for (i=0; i<AV_NUM_DATA_POINTERS; i++)
         ptr[i] = p->data[i];
-    stride = p->linesize[0];
 
-    if (source_packet_size*avctx->width*avctx->height > buf_end - buf) {
+    if (total_size > avpkt->size) {
         av_log(avctx, AV_LOG_ERROR, "Overread buffer. Invalid header?\n");
         return -1;
     }
     switch (bits_per_color) {
-        case 10:
-            for (x = 0; x < avctx->height; x++) {
-                uint16_t *dst[3] = {(uint16_t*)ptr[0],
-                                    (uint16_t*)ptr[1],
-                                    (uint16_t*)ptr[2]};
-               for (y = 0; y < avctx->width; y++) {
-                   rgbBuffer = read32(&buf, endian);
-                   *dst[0]++ = (rgbBuffer >> 12) & 0x3FF;
-                   *dst[1]++ = (rgbBuffer >> 2)  & 0x3FF;
-                   *dst[2]++ = (rgbBuffer >> 22) & 0x3FF;
-               }
-               for (i=0; i<3; i++)
-                   ptr[i] += p->linesize[i];
+    case 10:
+        for (x = 0; x < avctx->height; x++) {
+            uint16_t *dst[3] = {(uint16_t*)ptr[0],
+                                (uint16_t*)ptr[1],
+                                (uint16_t*)ptr[2]};
+            for (y = 0; y < avctx->width; y++) {
+                *dst[2]++ = read10in32(&buf, &rgbBuffer,
+                                       &n_datum, endian);
+                *dst[0]++ = read10in32(&buf, &rgbBuffer,
+                                       &n_datum, endian);
+                *dst[1]++ = read10in32(&buf, &rgbBuffer,
+                                       &n_datum, endian);
+                // For 10 bit, ignore alpha
+                if (elements == 4)
+                    read10in32(&buf, &rgbBuffer,
+                               &n_datum, endian);
             }
-            break;
-        case 8:
-        case 12:
-        case 16:
-            if (planar) {
-                int source_bpc = target_packet_size / elements;
-                int target_bpc = target_packet_size / elements;
-                for (x = 0; x < avctx->height; x++) {
-                    uint8_t *dst[AV_NUM_DATA_POINTERS];
-                    for (i=0; i<elements; i++)
-                        dst[i] = ptr[i];
-                    for (y = 0; y < avctx->width; y++) {
-                        for (i=0; i<3; i++) {
-                            memcpy(dst[i], buf, FFMIN(source_bpc, target_bpc));
-                            dst[i] += target_bpc;
-                            buf += source_bpc;
-                        }
-                    }
-                    for (i=0; i<elements; i++)
-                        ptr[i] += p->linesize[i];
-                }
-            } else {
-                if (source_packet_size == target_packet_size) {
-                    for (x = 0; x < avctx->height; x++) {
-                        memcpy(ptr[0], buf, target_packet_size*avctx->width);
-                        ptr[0] += stride;
-                        buf += source_packet_size*avctx->width;
-                    }
-                } else {
-                    for (x = 0; x < avctx->height; x++) {
-                        uint8_t *dst = ptr[0];
-                        for (y = 0; y < avctx->width; y++) {
-                            memcpy(dst, buf, target_packet_size);
-                            dst += target_packet_size;
-                            buf += source_packet_size;
-                        }
-                        ptr[0] += stride;
-                    }
-                }
+            for (i = 0; i < 3; i++)
+                ptr[i] += p->linesize[i];
+        }
+        break;
+    case 12:
+        for (x = 0; x < avctx->height; x++) {
+            uint16_t *dst[3] = {(uint16_t*)ptr[0],
+                                (uint16_t*)ptr[1],
+                                (uint16_t*)ptr[2]};
+            for (y = 0; y < avctx->width; y++) {
+                *dst[2] = *((uint16_t*)buf);
+                *dst[2] = (*dst[2] >> 4) | (*dst[2] << 12);
+                dst[2]++;
+                buf += 2;
+                *dst[0] = *((uint16_t*)buf);
+                *dst[0] = (*dst[0] >> 4) | (*dst[0] << 12);
+                dst[0]++;
+                buf += 2;
+                *dst[1] = *((uint16_t*)buf);
+                *dst[1] = (*dst[1] >> 4) | (*dst[1] << 12);
+                dst[1]++;
+                buf += 2;
+                // For 12 bit, ignore alpha
+                if (elements == 4)
+                    buf += 2;
             }
-            break;
+            for (i = 0; i < 3; i++)
+                ptr[i] += p->linesize[i];
+        }
+        break;
+    case 16:
+        elements *= 2;
+    case 8:
+        for (x = 0; x < avctx->height; x++) {
+            memcpy(ptr[0], buf, elements*avctx->width);
+            ptr[0] += p->linesize[0];
+            buf += elements*avctx->width;
+        }
+        break;
     }
 
     *picture   = s->picture;
@@ -275,6 +292,6 @@
     .init           = decode_init,
     .close          = decode_end,
     .decode         = decode_frame,
-    .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("DPX image"),
+    .capabilities   = CODEC_CAP_DR1,
 };
diff --git a/libavcodec/dpxenc.c b/libavcodec/dpxenc.c
index 451b7b9..bd44b16 100644
--- a/libavcodec/dpxenc.c
+++ b/libavcodec/dpxenc.c
@@ -47,31 +47,31 @@
     s->planar             = 0;
 
     switch (avctx->pix_fmt) {
-    case PIX_FMT_RGB24:
+    case AV_PIX_FMT_RGB24:
         break;
-    case PIX_FMT_RGBA:
+    case AV_PIX_FMT_RGBA:
         s->descriptor = 51; /* RGBA */
         break;
-    case PIX_FMT_RGB48LE:
+    case AV_PIX_FMT_RGB48LE:
         s->big_endian = 0;
-    case PIX_FMT_RGB48BE:
+    case AV_PIX_FMT_RGB48BE:
         s->bits_per_component = avctx->bits_per_raw_sample ? avctx->bits_per_raw_sample : 16;
         break;
-    case PIX_FMT_RGBA64LE:
+    case AV_PIX_FMT_RGBA64LE:
         s->big_endian = 0;
-    case PIX_FMT_RGBA64BE:
+    case AV_PIX_FMT_RGBA64BE:
         s->descriptor = 51;
         s->bits_per_component = 16;
         break;
-    case PIX_FMT_GBRP10LE:
+    case AV_PIX_FMT_GBRP10LE:
         s->big_endian = 0;
-    case PIX_FMT_GBRP10BE:
+    case AV_PIX_FMT_GBRP10BE:
         s->bits_per_component = 10;
         s->planar = 1;
         break;
-    case PIX_FMT_GBRP12LE:
+    case AV_PIX_FMT_GBRP12LE:
         s->big_endian = 0;
-    case PIX_FMT_GBRP12BE:
+    case AV_PIX_FMT_GBRP12BE:
         s->bits_per_component = 12;
         s->planar = 1;
         break;
@@ -104,14 +104,14 @@
     for (y = 0; y < avctx->height; y++) {
         for (x = 0; x < avctx->width; x++) {
             int value;
-            if ((avctx->pix_fmt & 1)) {
-                value = ((AV_RB16(src + 6*x + 4) & 0xFFC0) >> 4)
-                      | ((AV_RB16(src + 6*x + 2) & 0xFFC0) << 6)
-                      | ((AV_RB16(src + 6*x + 0) & 0xFFC0) << 16);
+            if (s->big_endian) {
+                value = ((AV_RB16(src + 6*x + 4) & 0xFFC0U) >> 4)
+                      | ((AV_RB16(src + 6*x + 2) & 0xFFC0U) << 6)
+                      | ((AV_RB16(src + 6*x + 0) & 0xFFC0U) << 16);
             } else {
-                value = ((AV_RL16(src + 6*x + 4) & 0xFFC0) >> 4)
-                      | ((AV_RL16(src + 6*x + 2) & 0xFFC0) << 6)
-                      | ((AV_RL16(src + 6*x + 0) & 0xFFC0) << 16);
+                value = ((AV_RL16(src + 6*x + 4) & 0xFFC0U) >> 4)
+                      | ((AV_RL16(src + 6*x + 2) & 0xFFC0U) << 6)
+                      | ((AV_RL16(src + 6*x + 0) & 0xFFC0U) << 16);
             }
             write32(dst, value);
             dst += 4;
@@ -129,7 +129,7 @@
     for (y = 0; y < avctx->height; y++) {
         for (x = 0; x < avctx->width; x++) {
             int value;
-            if ((avctx->pix_fmt & 1)) {
+            if (s->big_endian) {
                 value = (AV_RB16(src[0] + 2*x) << 12)
                       | (AV_RB16(src[1] + 2*x) << 2)
                       | (AV_RB16(src[2] + 2*x) << 22);
@@ -148,14 +148,25 @@
 
 static void encode_gbrp12(AVCodecContext *avctx, const AVPicture *pic, uint16_t *dst)
 {
+    DPXContext *s = avctx->priv_data;
     const uint16_t *src[3] = {(uint16_t*)pic->data[0],
                               (uint16_t*)pic->data[1],
                               (uint16_t*)pic->data[2]};
     int x, y, i;
     for (y = 0; y < avctx->height; y++) {
         for (x = 0; x < avctx->width; x++) {
+            uint16_t value[3];
+            if (s->big_endian) {
+                value[1] = AV_RB16(src[0] + x) << 4;
+                value[2] = AV_RB16(src[1] + x) << 4;
+                value[0] = AV_RB16(src[2] + x) << 4;
+            } else {
+                value[1] = AV_RL16(src[0] + x) << 4;
+                value[2] = AV_RL16(src[1] + x) << 4;
+                value[0] = AV_RL16(src[2] + x) << 4;
+            }
             for (i = 0; i < 3; i++)
-                *dst++ = *(src[i] + x);
+                write16(dst++, value[i]);
         }
         for (i = 0; i < 3; i++)
             src[i] += pic->linesize[i]/2;
@@ -246,17 +257,17 @@
     .priv_data_size = sizeof(DPXContext),
     .init   = encode_init,
     .encode2 = encode_frame,
-    .pix_fmts = (const enum PixelFormat[]){
-        PIX_FMT_RGB24,
-        PIX_FMT_RGBA,
-        PIX_FMT_RGB48LE,
-        PIX_FMT_RGB48BE,
-        PIX_FMT_RGBA64LE,
-        PIX_FMT_RGBA64BE,
-        PIX_FMT_GBRP10LE,
-        PIX_FMT_GBRP10BE,
-        PIX_FMT_GBRP12LE,
-        PIX_FMT_GBRP12BE,
-        PIX_FMT_NONE},
+    .pix_fmts = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_RGB24,
+        AV_PIX_FMT_RGBA,
+        AV_PIX_FMT_RGB48LE,
+        AV_PIX_FMT_RGB48BE,
+        AV_PIX_FMT_RGBA64LE,
+        AV_PIX_FMT_RGBA64BE,
+        AV_PIX_FMT_GBRP10LE,
+        AV_PIX_FMT_GBRP10BE,
+        AV_PIX_FMT_GBRP12LE,
+        AV_PIX_FMT_GBRP12BE,
+        AV_PIX_FMT_NONE},
     .long_name = NULL_IF_CONFIG_SMALL("DPX image"),
 };
diff --git a/libavcodec/dsicinav.c b/libavcodec/dsicinav.c
index 1679bfe..0290f5a 100644
--- a/libavcodec/dsicinav.c
+++ b/libavcodec/dsicinav.c
@@ -24,6 +24,7 @@
  * Delphine Software International CIN audio/video decoders
  */
 
+#include "libavutil/channel_layout.h"
 #include "avcodec.h"
 #include "bytestream.h"
 #include "mathops.h"
@@ -86,24 +87,42 @@
          0,      0,      0,      0,      0,      0,      0,      0
 };
 
+static av_cold void destroy_buffers(CinVideoContext *cin)
+{
+    int i;
+
+    for (i = 0; i < 3; ++i)
+        av_freep(&cin->bitmap_table[i]);
+}
+
+static av_cold int allocate_buffers(CinVideoContext *cin)
+{
+    int i;
+
+    for (i = 0; i < 3; ++i) {
+        cin->bitmap_table[i] = av_mallocz(cin->bitmap_size);
+        if (!cin->bitmap_table[i]) {
+            av_log(cin->avctx, AV_LOG_ERROR, "Can't allocate bitmap buffers.\n");
+            destroy_buffers(cin);
+            return AVERROR(ENOMEM);
+        }
+    }
+
+    return 0;
+}
 
 static av_cold int cinvideo_decode_init(AVCodecContext *avctx)
 {
     CinVideoContext *cin = avctx->priv_data;
-    unsigned int i;
 
     cin->avctx = avctx;
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     avcodec_get_frame_defaults(&cin->frame);
-    cin->frame.data[0] = NULL;
 
     cin->bitmap_size = avctx->width * avctx->height;
-    for (i = 0; i < 3; ++i) {
-        cin->bitmap_table[i] = av_mallocz(cin->bitmap_size);
-        if (!cin->bitmap_table[i])
-            av_log(avctx, AV_LOG_ERROR, "Can't allocate bitmap buffers.\n");
-    }
+    if (allocate_buffers(cin))
+        return AVERROR(ENOMEM);
 
     return 0;
 }
@@ -193,7 +212,7 @@
         } else {
             len = code + 1;
             if (len > src_end-src) {
-                av_log(0, AV_LOG_ERROR, "RLE overread\n");
+                av_log(NULL, AV_LOG_ERROR, "RLE overread\n");
                 return AVERROR_INVALIDDATA;
             }
             memcpy(dst, src, FFMIN(len, dst_end - dst));
@@ -251,7 +270,7 @@
           cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size);
         break;
     case 35:
-        cin_decode_huffman(buf, bitmap_frame_size,
+        bitmap_frame_size = cin_decode_huffman(buf, bitmap_frame_size,
           cin->bitmap_table[CIN_INT_BMP], cin->bitmap_size);
         cin_decode_rle(cin->bitmap_table[CIN_INT_BMP], bitmap_frame_size,
           cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size);
@@ -287,9 +306,9 @@
     }
 
     cin->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;
-    if (avctx->reget_buffer(avctx, &cin->frame)) {
-        av_log(cin->avctx, AV_LOG_ERROR, "delphinecinvideo: reget_buffer() failed to allocate a frame\n");
-        return -1;
+    if ((res = avctx->reget_buffer(avctx, &cin->frame))) {
+        av_log(cin->avctx, AV_LOG_ERROR, "failed to allocate a frame\n");
+        return res;
     }
 
     memcpy(cin->frame.data[1], cin->palette, sizeof(cin->palette));
@@ -310,13 +329,11 @@
 static av_cold int cinvideo_decode_end(AVCodecContext *avctx)
 {
     CinVideoContext *cin = avctx->priv_data;
-    int i;
 
     if (cin->frame.data[0])
         avctx->release_buffer(avctx, &cin->frame);
 
-    for (i = 0; i < 3; ++i)
-        av_free(cin->bitmap_table[i]);
+    destroy_buffers(cin);
 
     return 0;
 }
@@ -325,14 +342,11 @@
 {
     CinAudioContext *cin = avctx->priv_data;
 
-    if (avctx->channels != 1) {
-        av_log_ask_for_sample(avctx, "Number of channels is not supported\n");
-        return AVERROR_PATCHWELCOME;
-    }
-
     cin->initial_decode_frame = 1;
-    cin->delta = 0;
-    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    cin->delta                = 0;
+    avctx->sample_fmt         = AV_SAMPLE_FMT_S16;
+    avctx->channels           = 1;
+    avctx->channel_layout     = AV_CH_LAYOUT_MONO;
 
     avcodec_get_frame_defaults(&cin->frame);
     avctx->coded_frame = &cin->frame;
diff --git a/libavcodec/dsputil.c b/libavcodec/dsputil.c
index af939b1..7997885 100644
--- a/libavcodec/dsputil.c
+++ b/libavcodec/dsputil.c
@@ -1812,7 +1812,7 @@
         int b= rem[i] + ((basis[i]*scale + (1<<(BASIS_SHIFT - RECON_SHIFT-1)))>>(BASIS_SHIFT - RECON_SHIFT));
         int w= weight[i];
         b>>= RECON_SHIFT;
-        assert(-512<b && b<512);
+        av_assert2(-512<b && b<512);
 
         sum += (w*b)*(w*b)>>4;
     }
@@ -2315,7 +2315,7 @@
 
         level= temp[i] + 64;
 
-        assert(level - 64);
+        av_assert2(level - 64);
 
         if((level&(~127)) == 0){
             bits+= last_length[UNI_AC_ENC_INDEX(run, level)];
@@ -2386,7 +2386,7 @@
 
         level= temp[i] + 64;
 
-        assert(level - 64);
+        av_assert2(level - 64);
 
         if((level&(~127)) == 0){
             bits+= last_length[UNI_AC_ENC_INDEX(run, level)];
@@ -2514,14 +2514,6 @@
     }
 }
 
-static void vector_fmul_scalar_c(float *dst, const float *src, float mul,
-                                 int len)
-{
-    int i;
-    for (i = 0; i < len; i++)
-        dst[i] = src[i] * mul;
-}
-
 static void butterflies_float_c(float *av_restrict v1, float *av_restrict v2,
                                 int len)
 {
@@ -2963,10 +2955,6 @@
 
 #undef dspfunc
 
-#if CONFIG_MLP_DECODER || CONFIG_TRUEHD_DECODER
-    ff_mlp_init(c, avctx);
-#endif
-
     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;
@@ -3043,7 +3031,6 @@
     c->scalarproduct_float = ff_scalarproduct_float_c;
     c->butterflies_float = butterflies_float_c;
     c->butterflies_float_interleave = butterflies_float_interleave_c;
-    c->vector_fmul_scalar = vector_fmul_scalar_c;
 
     c->shrink[0]= av_image_copy_plane;
     c->shrink[1]= ff_shrink22;
@@ -3166,7 +3153,6 @@
     if (HAVE_VIS)        ff_dsputil_init_vis   (c, avctx);
     if (ARCH_ALPHA)      ff_dsputil_init_alpha (c, avctx);
     if (ARCH_PPC)        ff_dsputil_init_ppc   (c, avctx);
-    if (HAVE_MMI)        ff_dsputil_init_mmi   (c, avctx);
     if (ARCH_SH4)        ff_dsputil_init_sh4   (c, avctx);
     if (ARCH_BFIN)       ff_dsputil_init_bfin  (c, avctx);
     if (HAVE_MIPSFPU)    ff_dsputil_init_mips  (c, avctx);
diff --git a/libavcodec/dsputil.h b/libavcodec/dsputil.h
index 2173508..1fef07e 100644
--- a/libavcodec/dsputil.h
+++ b/libavcodec/dsputil.h
@@ -52,7 +52,7 @@
 void ff_wmv2_idct_c(DCTELEM *data);
 
 void ff_fdct_mmx(DCTELEM *block);
-void ff_fdct_mmx2(DCTELEM *block);
+void ff_fdct_mmxext(DCTELEM *block);
 void ff_fdct_sse2(DCTELEM *block);
 
 #define H264_IDCT(depth) \
@@ -393,16 +393,6 @@
     /* assume len is a multiple of 8, and arrays are 16-byte aligned */
     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
-     * destination vectors must overlap exactly or not at all.
-     * @param dst result vector, 16-byte aligned
-     * @param src input vector, 16-byte aligned
-     * @param mul scalar value
-     * @param len length of vector, multiple of 4
-     */
-    void (*vector_fmul_scalar)(float *dst, const float *src, float mul,
-                               int len);
-    /**
      * Calculate the scalar product of two vectors of floats.
      * @param v1  first vector, 16-byte aligned
      * @param v2  second vector, 16-byte aligned
@@ -489,12 +479,6 @@
 
     void (*shrink[4])(uint8_t *dst, int dst_wrap, const uint8_t *src, int src_wrap, int width, int height);
 
-    /* mlp/truehd functions */
-    void (*mlp_filter_channel)(int32_t *state, const int32_t *coeff,
-                               int firorder, int iirorder,
-                               unsigned int filter_shift, int32_t mask, int blocksize,
-                               int32_t *sample_buffer);
-
     /**
      * Calculate scalar product of two vectors.
      * @param len length of vectors, should be multiple of 16
@@ -616,7 +600,6 @@
 void ff_dsputil_init_alpha(DSPContext* c, AVCodecContext *avctx);
 void ff_dsputil_init_arm(DSPContext* c, AVCodecContext *avctx);
 void ff_dsputil_init_bfin(DSPContext* c, AVCodecContext *avctx);
-void ff_dsputil_init_mmi(DSPContext* c, AVCodecContext *avctx);
 void ff_dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx);
 void ff_dsputil_init_ppc(DSPContext* c, AVCodecContext *avctx);
 void ff_dsputil_init_sh4(DSPContext* c, AVCodecContext *avctx);
@@ -624,10 +607,8 @@
 void ff_dsputil_init_mips(DSPContext* c, AVCodecContext *avctx);
 
 void ff_dsputil_init_dwt(DSPContext *c);
-void ff_mlp_init(DSPContext* c, AVCodecContext *avctx);
-void ff_mlp_init_x86(DSPContext* c, AVCodecContext *avctx);
 
-#if (ARCH_ARM && HAVE_NEON) || ARCH_PPC || HAVE_MMI || HAVE_MMX
+#if (ARCH_ARM && HAVE_NEON) || ARCH_PPC || HAVE_MMX
 #   define STRIDE_ALIGN 16
 #else
 #   define STRIDE_ALIGN 8
@@ -683,7 +664,7 @@
     int i;
     for(i=0; i<h; i++)
     {
-        AV_WN16(dst   , AV_RN16(src   ));
+        AV_COPY16U(dst, src);
         dst+=dstStride;
         src+=srcStride;
     }
@@ -694,7 +675,7 @@
     int i;
     for(i=0; i<h; i++)
     {
-        AV_WN32(dst   , AV_RN32(src   ));
+        AV_COPY32U(dst, src);
         dst+=dstStride;
         src+=srcStride;
     }
@@ -705,8 +686,7 @@
     int i;
     for(i=0; i<h; i++)
     {
-        AV_WN32(dst   , AV_RN32(src   ));
-        AV_WN32(dst+4 , AV_RN32(src+4 ));
+        AV_COPY64U(dst, src);
         dst+=dstStride;
         src+=srcStride;
     }
@@ -717,8 +697,7 @@
     int i;
     for(i=0; i<h; i++)
     {
-        AV_WN32(dst   , AV_RN32(src   ));
-        AV_WN32(dst+4 , AV_RN32(src+4 ));
+        AV_COPY64U(dst, src);
         dst[8]= src[8];
         dst+=dstStride;
         src+=srcStride;
@@ -730,10 +709,7 @@
     int i;
     for(i=0; i<h; i++)
     {
-        AV_WN32(dst   , AV_RN32(src   ));
-        AV_WN32(dst+4 , AV_RN32(src+4 ));
-        AV_WN32(dst+8 , AV_RN32(src+8 ));
-        AV_WN32(dst+12, AV_RN32(src+12));
+        AV_COPY128U(dst, src);
         dst+=dstStride;
         src+=srcStride;
     }
@@ -744,10 +720,7 @@
     int i;
     for(i=0; i<h; i++)
     {
-        AV_WN32(dst   , AV_RN32(src   ));
-        AV_WN32(dst+4 , AV_RN32(src+4 ));
-        AV_WN32(dst+8 , AV_RN32(src+8 ));
-        AV_WN32(dst+12, AV_RN32(src+12));
+        AV_COPY128U(dst, src);
         dst[16]= src[16];
         dst+=dstStride;
         src+=srcStride;
diff --git a/libavcodec/dsputil_template.c b/libavcodec/dsputil_template.c
index 7286726..eacf59b 100644
--- a/libavcodec/dsputil_template.c
+++ b/libavcodec/dsputil_template.c
@@ -131,10 +131,12 @@
     int start_y, start_x, end_y, end_x;
 
     if(src_y>= h){
-        src+= (h-1-src_y)*linesize;
+        src-= src_y*linesize;
+        src+= (h-1)*linesize;
         src_y=h-1;
     }else if(src_y<=-block_h){
-        src+= (1-block_h-src_y)*linesize;
+        src-= src_y*linesize;
+        src+= (1-block_h)*linesize;
         src_y=1-block_h;
     }
     if(src_x>= w){
@@ -680,7 +682,7 @@
     int i;\
     stride >>= sizeof(pixel)-1;\
     \
-    assert(x<8 && y<8 && x>=0 && y>=0);\
+    av_assert2(x<8 && y<8 && x>=0 && y>=0);\
 \
     if(D){\
         for(i=0; i<h; i++){\
diff --git a/libavcodec/dv.c b/libavcodec/dv.c
index 13af692..18c90c2 100644
--- a/libavcodec/dv.c
+++ b/libavcodec/dv.c
@@ -137,19 +137,19 @@
               break;
         case 720:
               switch (d->pix_fmt) {
-              case PIX_FMT_YUV422P:
+              case AV_PIX_FMT_YUV422P:
                    x = shuf3[m] + slot/3;
                    y = serpent1[slot] +
                        ((((seq + off[m]) % d->difseg_size)<<1) + chan)*3;
                    tbl[m] = (x<<1)|(y<<8);
                    break;
-              case PIX_FMT_YUV420P:
+              case AV_PIX_FMT_YUV420P:
                    x = shuf3[m] + slot/3;
                    y = serpent1[slot] +
                        ((seq + off[m]) % d->difseg_size)*3;
                    tbl[m] = (x<<1)|(y<<9);
                    break;
-              case PIX_FMT_YUV411P:
+              case AV_PIX_FMT_YUV411P:
                    i = (seq + off[m]) % d->difseg_size;
                    k = slot + ((m==1||m==2)?3:0);
 
@@ -275,7 +275,7 @@
            to accelerate the parsing of partial codes */
         init_vlc(&dv_vlc, TEX_VLC_BITS, j,
                  new_dv_vlc_len, 1, 1, new_dv_vlc_bits, 2, 2, 0);
-        assert(dv_vlc.table_size == 1184);
+        av_assert1(dv_vlc.table_size == 1184);
 
         for (i = 0; i < dv_vlc.table_size; i++){
             int code = dv_vlc.table[i][0];
@@ -297,6 +297,7 @@
     }
 
     /* Generic DSP setup */
+    memset(&dsp,0, sizeof(dsp));
     ff_dsputil_init(&dsp, avctx);
     ff_set_cmp(&dsp, dsp.ildct_cmp, avctx->ildct_cmp);
     s->get_pixels = dsp.get_pixels;
@@ -525,7 +526,7 @@
     int max  = classes[0];
     int prev = 0;
 
-    assert((((int)blk) & 15) == 0);
+    av_assert2((((int)blk) & 15) == 0);
 
     bi->area_q[0] = bi->area_q[1] = bi->area_q[2] = bi->area_q[3] = 0;
     bi->partial_bit_count = 0;
@@ -616,7 +617,7 @@
                     b->bit_size[a] = 1; // 4 areas 4 bits for EOB :)
                     b->area_q[a]++;
                     prev = b->prev[a];
-                    assert(b->next[prev] >= mb_area_start[a+1] || b->mb[prev]);
+                    av_assert2(b->next[prev] >= mb_area_start[a+1] || b->mb[prev]);
                     for (k = b->next[prev] ; k < mb_area_start[a+1]; k = b->next[k]) {
                        b->mb[k] >>= 1;
                        if (b->mb[k]) {
@@ -626,11 +627,11 @@
                            if (b->next[k] >= mb_area_start[a+1] && b->next[k]<64){
                                 for (a2 = a + 1; b->next[k] >= mb_area_start[a2+1]; a2++)
                                     b->prev[a2] = prev;
-                                assert(a2 < 4);
-                                assert(b->mb[b->next[k]]);
+                                av_assert2(a2 < 4);
+                                av_assert2(b->mb[b->next[k]]);
                                 b->bit_size[a2] += dv_rl2vlc_size(b->next[k] - prev - 1, b->mb[b->next[k]])
                                                   -dv_rl2vlc_size(b->next[k] -    k - 1, b->mb[b->next[k]]);
-                                assert(b->prev[a2] == k && (a2 + 1 >= 4 || b->prev[a2+1] != k));
+                                av_assert2(b->prev[a2] == k && (a2 + 1 >= 4 || b->prev[a2+1] != k));
                                 b->prev[a2] = prev;
                            }
                            b->next[prev] = b->next[k];
@@ -687,8 +688,8 @@
         dv_calculate_mb_xy(s, work_chunk, mb_index, &mb_x, &mb_y);
 
         /* initializing luminance blocks */
-        if ((s->sys->pix_fmt == PIX_FMT_YUV420P) ||
-            (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x >= (704 / 8)) ||
+        if ((s->sys->pix_fmt == AV_PIX_FMT_YUV420P) ||
+            (s->sys->pix_fmt == AV_PIX_FMT_YUV411P && mb_x >= (704 / 8)) ||
             (s->sys->height >= 720 && mb_y != 134)) {
             y_stride = s->picture.linesize[0] << 3;
         } else {
@@ -713,13 +714,13 @@
         enc_blk += 4;
 
         /* initializing chrominance blocks */
-        c_offset = (((mb_y >>  (s->sys->pix_fmt == PIX_FMT_YUV420P)) * s->picture.linesize[1] +
-                     (mb_x >> ((s->sys->pix_fmt == PIX_FMT_YUV411P) ? 2 : 1))) << 3);
+        c_offset = (((mb_y >>  (s->sys->pix_fmt == AV_PIX_FMT_YUV420P)) * s->picture.linesize[1] +
+                     (mb_x >> ((s->sys->pix_fmt == AV_PIX_FMT_YUV411P) ? 2 : 1))) << 3);
         for (j = 2; j; j--) {
             uint8_t *c_ptr = s->picture.data[j] + c_offset;
             linesize = s->picture.linesize[j];
             y_stride = (mb_y == 134) ? 8 : (s->picture.linesize[j] << 3);
-            if (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x >= (704 / 8)) {
+            if (s->sys->pix_fmt == AV_PIX_FMT_YUV411P && mb_x >= (704 / 8)) {
                 uint8_t* d;
                 uint8_t* b = scratch;
                 for (i = 0; i < 8; i++) {
@@ -816,7 +817,8 @@
      *   2. It is not at all clear what STYPE is used for 4:2:0 PAL
      *      compression scheme (if any).
      */
-    int apt   = (c->sys->pix_fmt == PIX_FMT_YUV420P ? 0 : 1);
+    int apt   = (c->sys->pix_fmt == AV_PIX_FMT_YUV420P ? 0 : 1);
+    int fs    = c->picture.top_field_first ? 0x00 : 0x40;
 
     uint8_t aspect = 0;
     if ((int)(av_q2d(c->avctx->sample_aspect_ratio) * c->avctx->width / c->avctx->height * 10) >= 17) /* 16:9 */
@@ -855,7 +857,7 @@
           buf[2] = 0xc8 |     /* reserved -- always b11001xxx */
                    aspect;
           buf[3] = (1 << 7) | /* frame/field flag 1 -- frame, 0 -- field */
-                   (1 << 6) | /* first/second field flag 0 -- field 2, 1 -- field 1 */
+                   fs       | /* first/second field flag 0 -- field 2, 1 -- field 1 */
                    (1 << 5) | /* frame change flag 0 -- same picture as before, 1 -- different */
                    (1 << 4) | /* 1 - interlaced, 0 - noninterlaced */
                    0xc;       /* reserved -- always b1100 */
@@ -992,8 +994,8 @@
     .init           = dvvideo_init_encoder,
     .encode2        = dvvideo_encode_frame,
     .capabilities   = CODEC_CAP_SLICE_THREADS,
-    .pix_fmts       = (const enum PixelFormat[]) {
-        PIX_FMT_YUV411P, PIX_FMT_YUV422P, PIX_FMT_YUV420P, PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]) {
+        AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("DV (Digital Video)"),
 };
diff --git a/libavcodec/dv_profile.c b/libavcodec/dv_profile.c
index cd06b28..05d4aba 100644
--- a/libavcodec/dv_profile.c
+++ b/libavcodec/dv_profile.c
@@ -91,7 +91,7 @@
       .sar = {{8, 9}, {32, 27}},
       .work_chunks = &work_chunks_dv25ntsc[0],
       .idct_factor = &dv_idct_factor_sd[0],
-      .pix_fmt = PIX_FMT_YUV411P,
+      .pix_fmt = AV_PIX_FMT_YUV411P,
       .bpm = 6,
       .block_sizes = block_sizes_dv2550,
       .audio_stride = 90,
@@ -111,7 +111,7 @@
       .sar = {{16, 15}, {64, 45}},
       .work_chunks = &work_chunks_dv25pal[0],
       .idct_factor = &dv_idct_factor_sd[0],
-      .pix_fmt = PIX_FMT_YUV420P,
+      .pix_fmt = AV_PIX_FMT_YUV420P,
       .bpm = 6,
       .block_sizes = block_sizes_dv2550,
       .audio_stride = 108,
@@ -131,7 +131,7 @@
       .sar = {{16, 15}, {64, 45}},
       .work_chunks = &work_chunks_dv25pal411[0],
       .idct_factor = &dv_idct_factor_sd[0],
-      .pix_fmt = PIX_FMT_YUV411P,
+      .pix_fmt = AV_PIX_FMT_YUV411P,
       .bpm = 6,
       .block_sizes = block_sizes_dv2550,
       .audio_stride = 108,
@@ -151,7 +151,7 @@
       .sar = {{8, 9}, {32, 27}},
       .work_chunks = &work_chunks_dv50ntsc[0],
       .idct_factor = &dv_idct_factor_sd[0],
-      .pix_fmt = PIX_FMT_YUV422P,
+      .pix_fmt = AV_PIX_FMT_YUV422P,
       .bpm = 6,
       .block_sizes = block_sizes_dv2550,
       .audio_stride = 90,
@@ -171,7 +171,7 @@
       .sar = {{16, 15}, {64, 45}},
       .work_chunks = &work_chunks_dv50pal[0],
       .idct_factor = &dv_idct_factor_sd[0],
-      .pix_fmt = PIX_FMT_YUV422P,
+      .pix_fmt = AV_PIX_FMT_YUV422P,
       .bpm = 6,
       .block_sizes = block_sizes_dv2550,
       .audio_stride = 108,
@@ -191,7 +191,7 @@
       .sar = {{1, 1}, {3, 2}},
       .work_chunks = &work_chunks_dv100ntsci[0],
       .idct_factor = &dv_idct_factor_hd1080[0],
-      .pix_fmt = PIX_FMT_YUV422P,
+      .pix_fmt = AV_PIX_FMT_YUV422P,
       .bpm = 8,
       .block_sizes = block_sizes_dv100,
       .audio_stride = 90,
@@ -211,7 +211,7 @@
       .sar = {{1, 1}, {4, 3}},
       .work_chunks = &work_chunks_dv100pali[0],
       .idct_factor = &dv_idct_factor_hd1080[0],
-      .pix_fmt = PIX_FMT_YUV422P,
+      .pix_fmt = AV_PIX_FMT_YUV422P,
       .bpm = 8,
       .block_sizes = block_sizes_dv100,
       .audio_stride = 108,
@@ -231,7 +231,7 @@
       .sar = {{1, 1}, {4, 3}},
       .work_chunks = &work_chunks_dv100ntscp[0],
       .idct_factor = &dv_idct_factor_hd720[0],
-      .pix_fmt = PIX_FMT_YUV422P,
+      .pix_fmt = AV_PIX_FMT_YUV422P,
       .bpm = 8,
       .block_sizes = block_sizes_dv100,
       .audio_stride = 90,
@@ -251,7 +251,7 @@
       .sar = {{1, 1}, {4, 3}},
       .work_chunks = &work_chunks_dv100palp[0],
       .idct_factor = &dv_idct_factor_hd720[0],
-      .pix_fmt = PIX_FMT_YUV422P,
+      .pix_fmt = AV_PIX_FMT_YUV422P,
       .bpm = 8,
       .block_sizes = block_sizes_dv100,
       .audio_stride = 90,
@@ -271,7 +271,7 @@
       .sar = {{16, 15}, {64, 45}},
       .work_chunks = &work_chunks_dv25pal[0],
       .idct_factor = &dv_idct_factor_sd[0],
-      .pix_fmt = PIX_FMT_YUV420P,
+      .pix_fmt = AV_PIX_FMT_YUV420P,
       .bpm = 6,
       .block_sizes = block_sizes_dv2550,
       .audio_stride = 108,
diff --git a/libavcodec/dv_profile.h b/libavcodec/dv_profile.h
index 1a2a60f..97edce9 100644
--- a/libavcodec/dv_profile.h
+++ b/libavcodec/dv_profile.h
@@ -53,7 +53,7 @@
     AVRational       sar[2];                /* sample aspect ratios for 4:3 and 16:9 */
     DVwork_chunk    *work_chunks;           /* each thread gets its own chunk of frame to work on */
     uint32_t        *idct_factor;           /* set of iDCT factor tables */
-    enum PixelFormat pix_fmt;               /* picture pixel format */
+    enum AVPixelFormat pix_fmt;             /* picture pixel format */
     int              bpm;                   /* blocks per macroblock */
     const uint8_t   *block_sizes;           /* AC block sizes, in bits */
     int              audio_stride;          /* size of audio_shuffle table */
diff --git a/libavcodec/dvdec.c b/libavcodec/dvdec.c
index 6a74244..d3a1234 100644
--- a/libavcodec/dvdec.c
+++ b/libavcodec/dvdec.c
@@ -254,8 +254,8 @@
         dv_calculate_mb_xy(s, work_chunk, mb_index, &mb_x, &mb_y);
 
         /* idct_put'ting luminance */
-        if ((s->sys->pix_fmt == PIX_FMT_YUV420P) ||
-            (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x >= (704 / 8)) ||
+        if ((s->sys->pix_fmt == AV_PIX_FMT_YUV420P) ||
+            (s->sys->pix_fmt == AV_PIX_FMT_YUV411P && mb_x >= (704 / 8)) ||
             (s->sys->height >= 720 && mb_y != 134)) {
             y_stride = (s->picture.linesize[0] << ((!is_field_mode[mb_index]) * log2_blocksize));
         } else {
@@ -275,11 +275,11 @@
         block += 4*64;
 
         /* idct_put'ting chrominance */
-        c_offset = (((mb_y >>  (s->sys->pix_fmt == PIX_FMT_YUV420P)) * s->picture.linesize[1] +
-                     (mb_x >> ((s->sys->pix_fmt == PIX_FMT_YUV411P) ? 2 : 1))) << log2_blocksize);
+        c_offset = (((mb_y >>  (s->sys->pix_fmt == AV_PIX_FMT_YUV420P)) * s->picture.linesize[1] +
+                     (mb_x >> ((s->sys->pix_fmt == AV_PIX_FMT_YUV411P) ? 2 : 1))) << log2_blocksize);
         for (j = 2; j; j--) {
             uint8_t *c_ptr = s->picture.data[j] + c_offset;
-            if (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x >= (704 / 8)) {
+            if (s->sys->pix_fmt == AV_PIX_FMT_YUV411P && mb_x >= (704 / 8)) {
                   uint64_t aligned_pixels[64/8];
                   uint8_t *pixels = (uint8_t*)aligned_pixels;
                   uint8_t *c_ptr1, *ptr1;
@@ -343,6 +343,15 @@
     s->picture.interlaced_frame = 1;
     s->picture.top_field_first  = 0;
 
+    /* Determine the codec's sample_aspect ratio and field order from the packet */
+    vsc_pack = buf + 80*5 + 48 + 5;
+    if ( *vsc_pack == dv_video_control ) {
+        apt = buf[4] & 0x07;
+        is16_9 = (vsc_pack[2] & 0x07) == 0x02 || (!apt && (vsc_pack[2] & 0x07) == 0x07);
+        avctx->sample_aspect_ratio = s->sys->sar[is16_9];
+        s->picture.top_field_first = !(vsc_pack[3] & 0x40);
+    }
+
     s->buf = buf;
     avctx->execute(avctx, dv_decode_video_segment, s->sys->work_chunks, NULL,
                    dv_work_pool_size(s->sys), sizeof(DVwork_chunk));
@@ -353,14 +362,6 @@
     *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[2] & 0x07) == 0x02 || (!apt && (vsc_pack[2] & 0x07) == 0x07);
-        avctx->sample_aspect_ratio = s->sys->sar[is16_9];
-    }
-
     return s->sys->frame_size;
 }
 
diff --git a/libavcodec/dvdsubdec.c b/libavcodec/dvdsubdec.c
index 90593d0..9c2dd8c 100644
--- a/libavcodec/dvdsubdec.c
+++ b/libavcodec/dvdsubdec.c
@@ -357,7 +357,7 @@
                 sub_header->rects[0]->h = h;
                 sub_header->rects[0]->type = SUBTITLE_BITMAP;
                 sub_header->rects[0]->pict.linesize[0] = w;
-                sub_header->rects[0]->forced = is_menu;
+                sub_header->rects[0]->flags = is_menu ? AV_SUBTITLE_FLAG_FORCED : 0;
             }
         }
         if (next_cmd_pos < cmd_pos) {
diff --git a/libavcodec/dwt.h b/libavcodec/dwt.h
index 6df32f3..d82e510 100644
--- a/libavcodec/dwt.h
+++ b/libavcodec/dwt.h
@@ -29,7 +29,7 @@
 #define MAX_DWT_SUPPORT 8
 #define MAX_DECOMPOSITIONS 8
 
-typedef struct {
+typedef struct DWTCompose {
     IDWTELEM *b[MAX_DWT_SUPPORT];
 
     IDWTELEM *b0;
diff --git a/libavcodec/dxa.c b/libavcodec/dxa.c
index 389705e..cf8ce0c 100644
--- a/libavcodec/dxa.c
+++ b/libavcodec/dxa.c
@@ -209,7 +209,7 @@
             r = *buf++;
             g = *buf++;
             b = *buf++;
-            c->pal[i] = 0xFF << 24 | r << 16 | g << 8 | b;
+            c->pal[i] = 0xFFU << 24 | r << 16 | g << 8 | b;
         }
         pc = 1;
         buf_size -= 768+4;
@@ -256,7 +256,7 @@
         c->pic.key_frame = !(compr & 1);
         c->pic.pict_type = (compr & 1) ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_I;
         for(j = 0; j < avctx->height; j++){
-            if(compr & 1){
+            if((compr & 1) && tmpptr){
                 for(i = 0; i < avctx->width; i++)
                     outptr[i] = srcptr[i] ^ tmpptr[i];
                 tmpptr += stride;
@@ -270,6 +270,10 @@
     case 13:
         c->pic.key_frame = 0;
         c->pic.pict_type = AV_PICTURE_TYPE_P;
+        if (!c->prev.data[0]) {
+            av_log(avctx, AV_LOG_ERROR, "Missing reference frame\n");
+            return AVERROR_INVALIDDATA;
+        }
         decode_13(avctx, c, c->pic.data[0], srcptr, c->prev.data[0]);
         break;
     default:
@@ -292,7 +296,7 @@
 {
     DxaDecContext * const c = avctx->priv_data;
 
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     avcodec_get_frame_defaults(&c->pic);
     avcodec_get_frame_defaults(&c->prev);
diff --git a/libavcodec/dxtory.c b/libavcodec/dxtory.c
index 83abc72..da43c47 100644
--- a/libavcodec/dxtory.c
+++ b/libavcodec/dxtory.c
@@ -26,7 +26,7 @@
 
 static av_cold int decode_init(AVCodecContext *avctx)
 {
-    avctx->pix_fmt     = PIX_FMT_YUV420P;
+    avctx->pix_fmt     = AV_PIX_FMT_YUV420P;
     avctx->coded_frame = avcodec_alloc_frame();
     if (!avctx->coded_frame)
         return AVERROR(ENOMEM);
@@ -70,8 +70,8 @@
     V  = pic->data[2];
     for (h = 0; h < avctx->height; h += 2) {
         for (w = 0; w < avctx->width; w += 2) {
-            AV_WN16A(Y1 + w, AV_RN16A(src));
-            AV_WN16A(Y2 + w, AV_RN16A(src + 2));
+            AV_COPY16(Y1 + w, src);
+            AV_COPY16(Y2 + w, src + 2);
             U[w >> 1] = src[4] + 0x80;
             V[w >> 1] = src[5] + 0x80;
             src += 6;
diff --git a/libavcodec/dxva2_h264.c b/libavcodec/dxva2_h264.c
index fdd8980..f7d4e5d 100644
--- a/libavcodec/dxva2_h264.c
+++ b/libavcodec/dxva2_h264.c
@@ -443,7 +443,7 @@
     .name           = "h264_dxva2",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = AV_CODEC_ID_H264,
-    .pix_fmt        = PIX_FMT_DXVA2_VLD,
+    .pix_fmt        = AV_PIX_FMT_DXVA2_VLD,
     .start_frame    = start_frame,
     .decode_slice   = decode_slice,
     .end_frame      = end_frame,
diff --git a/libavcodec/dxva2_mpeg2.c b/libavcodec/dxva2_mpeg2.c
index dc9b103..f050ed9 100644
--- a/libavcodec/dxva2_mpeg2.c
+++ b/libavcodec/dxva2_mpeg2.c
@@ -264,7 +264,7 @@
     .name           = "mpeg2_dxva2",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = AV_CODEC_ID_MPEG2VIDEO,
-    .pix_fmt        = PIX_FMT_DXVA2_VLD,
+    .pix_fmt        = AV_PIX_FMT_DXVA2_VLD,
     .start_frame    = start_frame,
     .decode_slice   = decode_slice,
     .end_frame      = end_frame,
diff --git a/libavcodec/dxva2_vc1.c b/libavcodec/dxva2_vc1.c
index a6891d3..ed4836d 100644
--- a/libavcodec/dxva2_vc1.c
+++ b/libavcodec/dxva2_vc1.c
@@ -68,7 +68,7 @@
         pp->bPicStructure      |= 0x01;
     if (s->picture_structure & PICT_BOTTOM_FIELD)
         pp->bPicStructure      |= 0x02;
-    pp->bSecondField            = v->interlace && v->fcm != ILACE_FIELD && !s->first_field;
+    pp->bSecondField            = v->interlace && v->fcm == ILACE_FIELD && v->second_field;
     pp->bPicIntra               = s->pict_type == AV_PICTURE_TYPE_I || v->bi_type;
     pp->bPicBackwardPrediction  = s->pict_type == AV_PICTURE_TYPE_B && !v->bi_type;
     pp->bBidirectionalAveragingMode = (1                                           << 7) |
@@ -183,8 +183,11 @@
 
     result = data_size <= dxva_size ? 0 : -1;
     if (!result) {
-        if (start_code_size > 0)
+        if (start_code_size > 0) {
             memcpy(dxva_data, start_code, start_code_size);
+            if (v->second_field)
+                dxva_data[3] = 0x0c;
+        }
         memcpy(dxva_data + start_code_size,
                ctx_pic->bitstream + slice->dwSliceDataLocation, slice_size);
         if (padding > 0)
@@ -269,7 +272,7 @@
     .name           = "wmv3_dxva2",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = AV_CODEC_ID_WMV3,
-    .pix_fmt        = PIX_FMT_DXVA2_VLD,
+    .pix_fmt        = AV_PIX_FMT_DXVA2_VLD,
     .start_frame    = start_frame,
     .decode_slice   = decode_slice,
     .end_frame      = end_frame,
@@ -281,7 +284,7 @@
     .name           = "vc1_dxva2",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = AV_CODEC_ID_VC1,
-    .pix_fmt        = PIX_FMT_DXVA2_VLD,
+    .pix_fmt        = AV_PIX_FMT_DXVA2_VLD,
     .start_frame    = start_frame,
     .decode_slice   = decode_slice,
     .end_frame      = end_frame,
diff --git a/libavcodec/eac3dec.c b/libavcodec/eac3dec.c
index 91e35ad..922bf7a 100644
--- a/libavcodec/eac3dec.c
+++ b/libavcodec/eac3dec.c
@@ -321,8 +321,8 @@
            rates in bit allocation.  The best assumption would be that it is
            handled like AC-3 DolbyNet, but we cannot be sure until we have a
            sample which utilizes this feature. */
-        av_log_missing_feature(s->avctx, "Reduced sampling rates", 1);
-        return -1;
+        av_log_missing_feature(s->avctx, "Reduced sampling rate", 1);
+        return AVERROR_PATCHWELCOME;
     }
     skip_bits(gbc, 5); // skip bitstream id
 
diff --git a/libavcodec/eac3enc.c b/libavcodec/eac3enc.c
index c5ac6d1..bb9ef4f 100644
--- a/libavcodec/eac3enc.c
+++ b/libavcodec/eac3enc.c
@@ -258,7 +258,7 @@
     .init            = ff_ac3_encode_init,
     .encode2         = ff_ac3_float_encode_frame,
     .close           = ff_ac3_encode_close,
-    .sample_fmts     = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLT,
+    .sample_fmts     = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLTP,
                                                       AV_SAMPLE_FMT_NONE },
     .long_name       = NULL_IF_CONFIG_SMALL("ATSC A/52 E-AC-3"),
     .priv_class      = &eac3enc_class,
diff --git a/libavcodec/eacmv.c b/libavcodec/eacmv.c
index 6b23758..d3de7ca 100644
--- a/libavcodec/eacmv.c
+++ b/libavcodec/eacmv.c
@@ -49,7 +49,7 @@
     avcodec_get_frame_defaults(&s->last2_frame);
 
     s->avctx = avctx;
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
     return 0;
 }
 
@@ -142,7 +142,7 @@
 
     buf += 16;
     for (i=pal_start; i<pal_start+pal_count && i<AVPALETTE_COUNT && buf_end - buf >= 3; i++) {
-        s->palette[i] = 0xFF << 24 | AV_RB24(buf);
+        s->palette[i] = 0xFFU << 24 | AV_RB24(buf);
         buf += 3;
     }
 }
diff --git a/libavcodec/eamad.c b/libavcodec/eamad.c
index b338240..0dad58b 100644
--- a/libavcodec/eamad.c
+++ b/libavcodec/eamad.c
@@ -61,7 +61,7 @@
 {
     MadContext *s = avctx->priv_data;
     s->avctx = avctx;
-    avctx->pix_fmt = PIX_FMT_YUV420P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV420P;
     ff_dsputil_init(&s->dsp, avctx);
     ff_init_scantable_permutation(s->dsp.idct_permutation, FF_NO_IDCT_PERM);
     ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
@@ -233,14 +233,14 @@
     int buf_size       = avpkt->size;
     const uint8_t *buf_end = buf+buf_size;
     MadContext *s     = avctx->priv_data;
-    int width, height;
+    int width, height, ret;
     int chunk_type;
     int inter;
 
-    if (buf_size < 17) {
+    if (buf_size < 26) {
         av_log(avctx, AV_LOG_ERROR, "Input buffer too small\n");
         *data_size = 0;
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     chunk_type = AV_RL32(&buf[0]);
@@ -257,9 +257,9 @@
 
     if (avctx->width != width || avctx->height != height) {
         if((width * height)/2048*7 > buf_end-buf)
-            return -1;
-        if (av_image_check_size(width, height, 0, avctx) < 0)
-            return -1;
+            return AVERROR_INVALIDDATA;
+        if ((ret = av_image_check_size(width, height, 0, avctx)) < 0)
+            return ret;
         avcodec_set_dimensions(avctx, width, height);
         if (s->frame.data[0])
             avctx->release_buffer(avctx, &s->frame);
@@ -269,9 +269,9 @@
 
     s->frame.reference = 3;
     if (!s->frame.data[0]) {
-        if (avctx->get_buffer(avctx, &s->frame) < 0) {
+        if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-            return -1;
+            return ret;
         }
     }
 
@@ -285,7 +285,7 @@
     for (s->mb_y=0; s->mb_y < (avctx->height+15)/16; s->mb_y++)
         for (s->mb_x=0; s->mb_x < (avctx->width +15)/16; s->mb_x++)
             if(decode_mb(s, inter) < 0)
-                return -1;
+                return AVERROR_INVALIDDATA;
 
     *data_size = sizeof(AVFrame);
     *(AVFrame*)data = s->frame;
diff --git a/libavcodec/eatgq.c b/libavcodec/eatgq.c
index ab2a398..f8d9010 100644
--- a/libavcodec/eatgq.c
+++ b/libavcodec/eatgq.c
@@ -53,7 +53,7 @@
     ff_init_scantable_permutation(idct_permutation, FF_NO_IDCT_PERM);
     ff_init_scantable(idct_permutation, &s->scantable, ff_zigzag_direct);
     avctx->time_base = (AVRational){1, 15};
-    avctx->pix_fmt = PIX_FMT_YUV420P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV420P;
     return 0;
 }
 
@@ -141,7 +141,10 @@
     }
 }
 
-static void tgq_decode_mb(TgqContext *s, int mb_y, int mb_x){
+/**
+ * @return <0 on error
+ */
+static int tgq_decode_mb(TgqContext *s, int mb_y, int mb_x){
     int mode;
     int i;
     int8_t dc[6];
@@ -168,9 +171,11 @@
             }
         }else{
             av_log(s->avctx, AV_LOG_ERROR, "unsupported mb mode %i\n", mode);
+            return -1;
         }
         tgq_idct_put_mb_dconly(s, mb_x, mb_y, dc);
     }
+    return 0;
 }
 
 static void tgq_calculate_qtable(TgqContext *s, int quant){
@@ -189,12 +194,13 @@
     int buf_size = avpkt->size;
     TgqContext *s = avctx->priv_data;
     int x,y;
-    int big_endian = AV_RL32(&buf[4]) > 0x000FFFFF;
+    int big_endian;
 
     if (buf_size < 16) {
         av_log(avctx, AV_LOG_WARNING, "truncated header\n");
         return -1;
     }
+    big_endian = AV_RL32(&buf[4]) > 0x000FFFFF;
     bytestream2_init(&s->gb, buf + 8, buf_size - 8);
     if (big_endian) {
         s->width  = bytestream2_get_be16u(&s->gb);
@@ -224,7 +230,8 @@
 
     for (y = 0; y < FFALIGN(avctx->height, 16) >> 4; y++)
         for (x = 0; x < FFALIGN(avctx->width, 16) >> 4; x++)
-            tgq_decode_mb(s, y, x);
+            if (tgq_decode_mb(s, y, x) < 0)
+                return AVERROR_INVALIDDATA;
 
     *data_size = sizeof(AVFrame);
     *(AVFrame*)data = s->frame;
diff --git a/libavcodec/eatgv.c b/libavcodec/eatgv.c
index 5ca8cf5..caee311 100644
--- a/libavcodec/eatgv.c
+++ b/libavcodec/eatgv.c
@@ -31,8 +31,8 @@
 #include "avcodec.h"
 #define BITSTREAM_READER_LE
 #include "get_bits.h"
-#include "libavutil/lzo.h"
 #include "libavutil/imgutils.h"
+#include "libavutil/mem.h"
 
 #define EA_PREAMBLE_SIZE    8
 #define kVGT_TAG MKTAG('k', 'V', 'G', 'T')
@@ -54,7 +54,7 @@
     TgvContext *s = avctx->priv_data;
     s->avctx = avctx;
     avctx->time_base = (AVRational){1, 15};
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
     avcodec_get_frame_defaults(&s->frame);
     avcodec_get_frame_defaults(&s->last_frame);
     return 0;
@@ -286,7 +286,7 @@
         pal_count = AV_RL16(&buf[6]);
         buf += 12;
         for(i=0; i<pal_count && i<AVPALETTE_COUNT && buf_end - buf >= 3; i++) {
-            s->palette[i] = 0xFF << 24 | AV_RB24(buf);
+            s->palette[i] = 0xFFU << 24 | AV_RB24(buf);
             buf += 3;
         }
     }
@@ -301,8 +301,7 @@
         s->frame.buffer_hints = FF_BUFFER_HINTS_VALID;
         s->frame.linesize[0] = s->width;
 
-        /* allocate additional 12 bytes to accommodate av_memcpy_backptr() OUTBUF_PADDED optimisation */
-        s->frame.data[0] = av_malloc(s->width*s->height + 12);
+        s->frame.data[0] = av_malloc(s->width * s->height);
         if (!s->frame.data[0])
             return AVERROR(ENOMEM);
         s->frame.data[1] = av_malloc(AVPALETTE_SIZE);
diff --git a/libavcodec/eatqi.c b/libavcodec/eatqi.c
index 7610acd..62833d5 100644
--- a/libavcodec/eatqi.c
+++ b/libavcodec/eatqi.c
@@ -52,7 +52,7 @@
     ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
     s->qscale = 1;
     avctx->time_base = (AVRational){1, 15};
-    avctx->pix_fmt = PIX_FMT_YUV420P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV420P;
     ff_mpeg12_init_vlcs();
     return 0;
 }
diff --git a/libavcodec/error_resilience.c b/libavcodec/error_resilience.c
index 7ddc5ac..01f7424 100644
--- a/libavcodec/error_resilience.c
+++ b/libavcodec/error_resilience.c
@@ -66,6 +66,10 @@
             av_log(s->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
             ref = 0;
         }
+        if ((h->ref_list[0][ref].f.reference&3) != 3) {
+            av_log(s->avctx, AV_LOG_DEBUG, "Reference invalid\n");
+            return;
+        }
         fill_rectangle(&s->current_picture.f.ref_index[0][4 * h->mb_xy],
                        2, 2, 2, ref, 1);
         fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
diff --git a/libavcodec/escape124.c b/libavcodec/escape124.c
index e4cc497..94eadce 100644
--- a/libavcodec/escape124.c
+++ b/libavcodec/escape124.c
@@ -62,7 +62,7 @@
     Escape124Context *s = avctx->priv_data;
 
     avcodec_get_frame_defaults(&s->frame);
-    avctx->pix_fmt = PIX_FMT_RGB555;
+    avctx->pix_fmt = AV_PIX_FMT_RGB555;
 
     s->num_superblocks = ((unsigned)avctx->width / 8) *
                          ((unsigned)avctx->height / 8);
diff --git a/libavcodec/escape130.c b/libavcodec/escape130.c
index 47e7f11..97547bb 100644
--- a/libavcodec/escape130.c
+++ b/libavcodec/escape130.c
@@ -37,7 +37,7 @@
 static av_cold int escape130_decode_init(AVCodecContext *avctx)
 {
     Escape130Context *s = avctx->priv_data;
-    avctx->pix_fmt = PIX_FMT_YUV420P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV420P;
 
     if((avctx->width&1) || (avctx->height&1)){
         av_log(avctx, AV_LOG_ERROR, "Dimensions are not a multiple of the block size\n");
diff --git a/libavcodec/exr.c b/libavcodec/exr.c
index 7caacd9..6773d88 100644
--- a/libavcodec/exr.c
+++ b/libavcodec/exr.c
@@ -230,6 +230,7 @@
     unsigned int   buf_size = avpkt->size;
     const uint8_t *buf_end  = buf + buf_size;
 
+    const AVPixFmtDescriptor *desc;
     EXRContext *const s = avctx->priv_data;
     AVFrame *picture  = data;
     AVFrame *const p = &s->picture;
@@ -452,9 +453,9 @@
     case 2: // 32-bit
     case 1: // 16-bit
         if (s->channel_offsets[3] >= 0)
-            avctx->pix_fmt = PIX_FMT_RGBA64;
+            avctx->pix_fmt = AV_PIX_FMT_RGBA64;
         else
-            avctx->pix_fmt = PIX_FMT_RGB48;
+            avctx->pix_fmt = AV_PIX_FMT_RGB48;
         break;
     // 8-bit
     case 0:
@@ -494,9 +495,10 @@
         avcodec_set_dimensions(avctx, w, h);
     }
 
-    bxmin = xmin * 2 * av_pix_fmt_descriptors[avctx->pix_fmt].nb_components;
-    axmax = (avctx->width - (xmax + 1)) * 2 * av_pix_fmt_descriptors[avctx->pix_fmt].nb_components;
-    out_line_size = avctx->width * 2 * av_pix_fmt_descriptors[avctx->pix_fmt].nb_components;
+    desc = av_pix_fmt_desc_get(avctx->pix_fmt);
+    bxmin = xmin * 2 * desc->nb_components;
+    axmax = (avctx->width - (xmax + 1)) * 2 * desc->nb_components;
+    out_line_size = avctx->width * 2 * desc->nb_components;
     scan_line_size = xdelta * current_channel_offset;
     uncompressed_size = scan_line_size * scan_lines_per_block;
 
@@ -590,7 +592,7 @@
 
                     // Zero out the start if xmin is not 0
                     memset(ptr_x, 0, bxmin);
-                    ptr_x += xmin * av_pix_fmt_descriptors[avctx->pix_fmt].nb_components;
+                    ptr_x += xmin * desc->nb_components;
                     if (s->bits_per_color_id == 2) {
                         // 32-bit
                         for (x = 0; x < xdelta; x++) {
diff --git a/libavcodec/fft.c b/libavcodec/fft.c
index e5bdcbd..00c434a 100644
--- a/libavcodec/fft.c
+++ b/libavcodec/fft.c
@@ -160,7 +160,7 @@
 #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 (ARCH_X86)     ff_fft_init_x86(s);
     if (CONFIG_MDCT)  s->mdct_calcw = s->mdct_calc;
     if (HAVE_MIPSFPU) ff_fft_init_mips(s);
 #else
diff --git a/libavcodec/fft.h b/libavcodec/fft.h
index 15e5a12..9d92b2c 100644
--- a/libavcodec/fft.h
+++ b/libavcodec/fft.h
@@ -135,7 +135,7 @@
 
 #if CONFIG_FFT_FLOAT
 void ff_fft_init_altivec(FFTContext *s);
-void ff_fft_init_mmx(FFTContext *s);
+void ff_fft_init_x86(FFTContext *s);
 void ff_fft_init_arm(FFTContext *s);
 void ff_fft_init_mips(FFTContext *s);
 #else
diff --git a/libavcodec/ffv1.c b/libavcodec/ffv1.c
index 7c68b2f..074be4c 100644
--- a/libavcodec/ffv1.c
+++ b/libavcodec/ffv1.c
@@ -25,1385 +25,166 @@
  * FF Video Codec 1 (a lossless codec)
  */
 
-#include "avcodec.h"
-#include "internal.h"
-#include "get_bits.h"
-#include "put_bits.h"
-#include "dsputil.h"
-#include "rangecoder.h"
-#include "golomb.h"
-#include "mathops.h"
-#include "libavutil/pixdesc.h"
 #include "libavutil/avassert.h"
 #include "libavutil/crc.h"
 #include "libavutil/opt.h"
 #include "libavutil/imgutils.h"
+#include "libavutil/pixdesc.h"
 #include "libavutil/timer.h"
+#include "avcodec.h"
+#include "internal.h"
+#include "dsputil.h"
+#include "rangecoder.h"
+#include "golomb.h"
+#include "mathops.h"
+#include "ffv1.h"
 
-#ifdef __INTEL_COMPILER
-#undef av_flatten
-#define av_flatten
-#endif
-
-#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[41];
-
-static const int8_t quant5_10bit[256]={
- 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, 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, 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, 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,-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,-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,-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,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,
-};
-
-static const int8_t quant5[256]={
- 0, 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, 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, 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, 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, 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,-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,-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,-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,-2,-1,-1,-1,
-};
-
-static const int8_t quant9_10bit[256]={
- 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 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, 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
--4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,
--4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,
--4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,
--4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,
--4,-4,-4,-4,-4,-4,-4,-4,-4,-3,-3,-3,-3,-3,-3,-3,
--3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-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,-1,-1,-1,-1,-1,-1,-1,-1,-0,-0,-0,-0,
-};
-
-static const int8_t quant11[256]={
- 0, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4,
- 4, 4, 4, 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, 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, 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,-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,-4,-4,
--4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,
--4,-4,-4,-4,-4,-3,-3,-3,-3,-3,-3,-3,-2,-2,-2,-1,
-};
-
-static const uint8_t ver2_state[256]= {
-   0,  10,  10,  10,  10,  16,  16,  16,  28,  16,  16,  29,  42,  49,  20,  49,
-  59,  25,  26,  26,  27,  31,  33,  33,  33,  34,  34,  37,  67,  38,  39,  39,
-  40,  40,  41,  79,  43,  44,  45,  45,  48,  48,  64,  50,  51,  52,  88,  52,
-  53,  74,  55,  57,  58,  58,  74,  60, 101,  61,  62,  84,  66,  66,  68,  69,
-  87,  82,  71,  97,  73,  73,  82,  75, 111,  77,  94,  78,  87,  81,  83,  97,
-  85,  83,  94,  86,  99,  89,  90,  99, 111,  92,  93, 134,  95,  98, 105,  98,
- 105, 110, 102, 108, 102, 118, 103, 106, 106, 113, 109, 112, 114, 112, 116, 125,
- 115, 116, 117, 117, 126, 119, 125, 121, 121, 123, 145, 124, 126, 131, 127, 129,
- 165, 130, 132, 138, 133, 135, 145, 136, 137, 139, 146, 141, 143, 142, 144, 148,
- 147, 155, 151, 149, 151, 150, 152, 157, 153, 154, 156, 168, 158, 162, 161, 160,
- 172, 163, 169, 164, 166, 184, 167, 170, 177, 174, 171, 173, 182, 176, 180, 178,
- 175, 189, 179, 181, 186, 183, 192, 185, 200, 187, 191, 188, 190, 197, 193, 196,
- 197, 194, 195, 196, 198, 202, 199, 201, 210, 203, 207, 204, 205, 206, 208, 214,
- 209, 211, 221, 212, 213, 215, 224, 216, 217, 218, 219, 220, 222, 228, 223, 225,
- 226, 224, 227, 229, 240, 230, 231, 232, 233, 234, 235, 236, 238, 239, 237, 242,
- 241, 243, 242, 244, 245, 246, 247, 248, 249, 250, 251, 252, 252, 253, 254, 255,
-};
-
-typedef struct VlcState{
-    int16_t drift;
-    uint16_t error_sum;
-    int8_t bias;
-    uint8_t count;
-} 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{
-    AVClass *class;
-    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 minor_version;
-    int width, height;
-    int chroma_h_shift, chroma_v_shift;
-    int chroma_planes;
-    int transparency;
-    int flags;
-    int picture_number;
-    AVFrame picture;
-    AVFrame last_picture;
-    int plane_count;
-    int ac;                              ///< 1=range coder <-> 0=golomb rice
-    int ac_byte_count;                   ///< number of bytes used for AC coding
-    PlaneContext plane[MAX_PLANES];
-    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;
-    int16_t *sample_buffer;
-    int gob_count;
-    int packed_at_lsb;
-    int ec;
-    int slice_damaged;
-    int key_frame_ok;
-
-    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;
-    int bits_per_raw_sample;
-}FFV1Context;
-
-static av_always_inline int fold(int diff, int bits){
-    if(bits==8)
-        diff= (int8_t)diff;
-    else{
-        diff+= 1<<(bits-1);
-        diff&=(1<<bits)-1;
-        diff-= 1<<(bits-1);
-    }
-
-    return diff;
-}
-
-static inline int predict(int16_t *src, int16_t *last)
+av_cold int ffv1_common_init(AVCodecContext *avctx)
 {
-    const int LT= last[-1];
-    const int  T= last[ 0];
-    const int L =  src[-1];
-
-    return mid_pred(L, L + T - LT, T);
-}
-
-static inline int get_context(PlaneContext *p, int16_t *src,
-                              int16_t *last, int16_t *last2)
-{
-    const int LT= last[-1];
-    const int  T= last[ 0];
-    const int RT= last[ 1];
-    const int L =  src[-1];
-
-    if(p->quant_table[3][127]){
-        const int TT= last2[0];
-        const int LL=  src[-2];
-        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 p->quant_table[0][(L-LT) & 0xFF] + p->quant_table[1][(LT-T) & 0xFF] + p->quant_table[2][(T-RT) & 0xFF];
-}
-
-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);
-        put_rac(c, state+0, 0);
-        if(e<=9){
-            for(i=0; i<e; i++){
-                put_rac(c, state+1+i, 1);  //1..10
-            }
-            put_rac(c, state+1+i, 0);
-
-            for(i=e-1; i>=0; i--){
-                put_rac(c, state+22+i, (a>>i)&1); //22..31
-            }
-
-            if(is_signed)
-                put_rac(c, state+11 + e, v < 0); //11..21
-        }else{
-            for(i=0; i<e; i++){
-                put_rac(c, state+1+FFMIN(i,9), 1);  //1..10
-            }
-            put_rac(c, state+1+9, 0);
-
-            for(i=e-1; i>=0; i--){
-                put_rac(c, state+22+FFMIN(i,9), (a>>i)&1); //22..31
-            }
-
-            if(is_signed)
-                put_rac(c, state+11 + 10, v < 0); //11..21
-        }
-    }else{
-        put_rac(c, state+0, 1);
-    }
-#undef put_rac
-}
-
-static av_noinline void put_symbol(RangeCoder *c, uint8_t *state, int v, int 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){
-    if(get_rac(c, state+0))
-        return 0;
-    else{
-        int i, e, a;
-        e= 0;
-        while(get_rac(c, state+1 + FFMIN(e,9))){ //1..10
-            e++;
-        }
-
-        a= 1;
-        for(i=e-1; i>=0; i--){
-            a += a + get_rac(c, state+22 + FFMIN(i,9)); //22..31
-        }
-
-        e= -(is_signed && get_rac(c, state+11 + FFMIN(e, 10))); //11..21
-        return (a^e)-e;
-    }
-}
-
-static av_noinline int get_symbol(RangeCoder *c, uint8_t *state, int is_signed){
-    return get_symbol_inline(c, state, is_signed);
-}
-
-static inline void update_vlc_state(VlcState * const state, const int v){
-    int drift= state->drift;
-    int count= state->count;
-    state->error_sum += FFABS(v);
-    drift += v;
-
-    if(count == 128){ //FIXME variable
-        count >>= 1;
-        drift >>= 1;
-        state->error_sum >>= 1;
-    }
-    count++;
-
-    if(drift <= -count){
-        if(state->bias > -128) state->bias--;
-
-        drift += count;
-        if(drift <= -count)
-            drift= -count + 1;
-    }else if(drift > 0){
-        if(state->bias <  127) state->bias++;
-
-        drift -= count;
-        if(drift > 0)
-            drift= 0;
-    }
-
-    state->drift= drift;
-    state->count= count;
-}
-
-static inline void put_vlc_symbol(PutBitContext *pb, VlcState * const state, int v, int bits){
-    int i, k, code;
-    v = fold(v - state->bias, bits);
-
-    i= state->count;
-    k=0;
-    while(i < state->error_sum){ //FIXME optimize
-        k++;
-        i += i;
-    }
-
-    assert(k<=8);
-
-#if 0 // JPEG LS
-    if(k==0 && 2*state->drift <= - state->count) code= v ^ (-1);
-    else                                         code= v;
-#else
-     code= v ^ ((2*state->drift + state->count)>>31);
-#endif
-
-     av_dlog(NULL, "v:%d/%d bias:%d error:%d drift:%d count:%d k:%d\n", v, code,
-             state->bias, state->error_sum, state->drift, state->count, k);
-    set_sr_golomb(pb, code, k, 12, bits);
-
-    update_vlc_state(state, v);
-}
-
-static inline int get_vlc_symbol(GetBitContext *gb, VlcState * const state, int bits){
-    int k, i, v, ret;
-
-    i= state->count;
-    k=0;
-    while(i < state->error_sum){ //FIXME optimize
-        k++;
-        i += i;
-    }
-
-    assert(k<=8);
-
-    v= get_sr_golomb(gb, k, 12, bits);
-    av_dlog(NULL, "v:%d bias:%d error:%d drift:%d count:%d k:%d",
-            v, state->bias, state->error_sum, state->drift, state->count, k);
-
-#if 0 // JPEG LS
-    if(k==0 && 2*state->drift <= - state->count) v ^= (-1);
-#else
-     v ^= ((2*state->drift + state->count)>>31);
-#endif
-
-    ret= fold(v + state->bias, bits);
-
-    update_vlc_state(state, v);
-
-    return ret;
-}
-
-#if CONFIG_FFV1_ENCODER
-static av_always_inline int encode_line(FFV1Context *s, int w,
-                                        int16_t *sample[3],
-                                        int plane_index, int bits)
-{
-    PlaneContext * const p= &s->plane[plane_index];
-    RangeCoder * const c= &s->c;
-    int x;
-    int run_index= s->run_index;
-    int run_count=0;
-    int run_mode=0;
-
-    if(s->ac){
-        if(c->bytestream_end - c->bytestream < w*20){
-            av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
-            return -1;
-        }
-    }else{
-        if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < w*4){
-            av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
-            return -1;
-        }
-    }
-
-    for(x=0; x<w; x++){
-        int diff, context;
-
-        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){
-            context = -context;
-            diff= -diff;
-        }
-
-        diff= fold(diff, bits);
-
-        if(s->ac){
-            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;
-
-            if(run_mode){
-
-                if(diff){
-                    while(run_count >= 1<<ff_log2_run[run_index]){
-                        run_count -= 1<<ff_log2_run[run_index];
-                        run_index++;
-                        put_bits(&s->pb, 1, 1);
-                    }
-
-                    put_bits(&s->pb, 1 + ff_log2_run[run_index], run_count);
-                    if(run_index) run_index--;
-                    run_count=0;
-                    run_mode=0;
-                    if(diff>0) diff--;
-                }else{
-                    run_count++;
-                }
-            }
-
-            av_dlog(s->avctx, "count:%d index:%d, mode:%d, x:%d pos:%d\n",
-                    run_count, run_index, run_mode, x,
-                    (int)put_bits_count(&s->pb));
-
-            if(run_mode == 0)
-                put_vlc_symbol(&s->pb, &p->vlc_state[context], diff, bits);
-        }
-    }
-    if(run_mode){
-        while(run_count >= 1<<ff_log2_run[run_index]){
-            run_count -= 1<<ff_log2_run[run_index];
-            run_index++;
-            put_bits(&s->pb, 1, 1);
-        }
-
-        if(run_count)
-            put_bits(&s->pb, 1, 1);
-    }
-    s->run_index= run_index;
-
-    return 0;
-}
-
-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;
-    int16_t *sample[3];
-    s->run_index=0;
-
-    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]= s->sample_buffer + (w+6)*((h+i-y)%ring_size) + 3;
-
-        sample[0][-1]= sample[1][0  ];
-        sample[1][ w]= sample[1][w-1];
-//{START_TIMER
-        if(s->bits_per_raw_sample<=8){
-            for(x=0; x<w; x++){
-                sample[0][x]= src[x + stride*y];
-            }
-            encode_line(s, w, sample, plane_index, 8);
-        }else{
-            if(s->packed_at_lsb){
-                for(x=0; x<w; x++){
-                    sample[0][x]= ((uint16_t*)(src + stride*y))[x];
-                }
-            }else{
-                for(x=0; x<w; x++){
-                    sample[0][x]= ((uint16_t*)(src + stride*y))[x] >> (16 - s->bits_per_raw_sample);
-                }
-            }
-            encode_line(s, w, sample, plane_index, s->bits_per_raw_sample);
-        }
-//STOP_TIMER("encode line")}
-    }
-}
-
-static void encode_rgb_frame(FFV1Context *s, uint8_t *src[3], int w, int h, int stride[3]){
-    int x, y, p, i;
-    const int ring_size= s->avctx->context_model ? 3 : 2;
-    int16_t *sample[4][3];
-    int lbd=  s->avctx->bits_per_raw_sample <= 8;
-    int bits= s->avctx->bits_per_raw_sample > 0 ? s->avctx->bits_per_raw_sample : 8;
-    int offset= 1 << bits;
-    s->run_index=0;
-
-    memset(s->sample_buffer, 0, ring_size*4*(w+6)*sizeof(*s->sample_buffer));
-
-    for(y=0; y<h; y++){
-        for(i=0; i<ring_size; i++)
-            for(p=0; p<4; p++)
-                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 b,g,r,av_uninit(a);
-            if(lbd){
-                unsigned v= *((uint32_t*)(src[0] + x*4 + stride[0]*y));
-                b= v&0xFF;
-                g= (v>>8)&0xFF;
-                r= (v>>16)&0xFF;
-                a=  v>>24;
-            }else{
-                b= *((uint16_t*)(src[0] + x*2 + stride[0]*y));
-                g= *((uint16_t*)(src[1] + x*2 + stride[1]*y));
-                r= *((uint16_t*)(src[2] + x*2 + stride[2]*y));
-            }
-
-            b -= g;
-            r -= g;
-            g += (b + r)>>2;
-            b += offset;
-            r += offset;
-
-//            assert(g>=0 && b>=0 && r>=0);
-//            assert(g<256 && b<512 && r<512);
-            sample[0][0][x]= g;
-            sample[1][0][x]= b;
-            sample[2][0][x]= r;
-            sample[3][0][x]= a;
-        }
-        for(p=0; p<3 + s->transparency; p++){
-            sample[p][0][-1]= sample[p][1][0  ];
-            sample[p][1][ w]= sample[p][1][w-1];
-            if (lbd)
-                encode_line(s, w, sample[p], (p+1)/2, 9);
-            else
-                encode_line(s, w, sample[p], (p+1)/2, bits+1);
-        }
-    }
-}
-
-static void write_quant_table(RangeCoder *c, int16_t *quant_table){
-    int last=0;
-    int i;
-    uint8_t state[CONTEXT_SIZE];
-    memset(state, 128, sizeof(state));
-
-    for(i=1; i<128 ; i++){
-        if(quant_table[i] != quant_table[i-1]){
-            put_symbol(c, state, i-last-1, 0);
-            last= i;
-        }
-    }
-    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, j;
-    RangeCoder * const c= &f->slice_context[0]->c;
-
-    memset(state, 128, sizeof(state));
-
-    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->bits_per_raw_sample, 0);
-        put_rac(c, state, f->chroma_planes);
-        put_symbol(c, state, f->chroma_h_shift, 0);
-        put_symbol(c, state, f->chroma_v_shift, 0);
-        put_rac(c, state, f->transparency);
-
-        write_quant_tables(c, f->quant_table);
-    }else if(f->version < 3){
-        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);
-            }
-        }
-    }
-}
-#endif /* CONFIG_FFV1_ENCODER */
-
-static av_cold int common_init(AVCodecContext *avctx){
     FFV1Context *s = avctx->priv_data;
 
-    s->avctx= avctx;
-    s->flags= avctx->flags;
+    if (!avctx->width || !avctx->height)
+        return AVERROR_INVALIDDATA;
+
+    s->avctx = avctx;
+    s->flags = avctx->flags;
 
     avcodec_get_frame_defaults(&s->picture);
 
     ff_dsputil_init(&s->dsp, avctx);
 
-    s->width = avctx->width;
-    s->height= avctx->height;
+    s->width  = avctx->width;
+    s->height = avctx->height;
 
-    assert(s->width && s->height);
-    //defaults
-    s->num_h_slices=1;
-    s->num_v_slices=1;
-
+    // defaults
+    s->num_h_slices = 1;
+    s->num_v_slices = 1;
 
     return 0;
 }
 
-static int init_slice_state(FFV1Context *f, FFV1Context *fs){
+int ffv1_init_slice_state(FFV1Context *f, FFV1Context *fs)
+{
     int j;
 
-        fs->plane_count= f->plane_count;
-        fs->transparency= f->transparency;
-        for(j=0; j<f->plane_count; j++){
-            PlaneContext * const p= &fs->plane[j];
+    fs->plane_count  = f->plane_count;
+    fs->transparency = f->transparency;
+    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) {
+            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]= f->state_transition[j];
-                fs->c.zero_state[256-j]= 256-fs->c.one_state [j];
-            }
+    if (fs->ac > 1) {
+        //FIXME only redo if state_transition changed
+        for (j = 1; j < 256; j++) {
+            fs->c. one_state[      j] = f->state_transition[j];
+            fs->c.zero_state[256 - j] = 256 - fs->c.one_state[j];
         }
+    }
 
     return 0;
 }
 
-static int init_slices_state(FFV1Context *f){
-    int i;
-    for(i=0; i<f->slice_count; i++){
-        FFV1Context *fs= f->slice_context[i];
-        if(init_slice_state(f, fs) < 0)
-            return -1;
+int ffv1_init_slices_state(FFV1Context *f)
+{
+    int i, ret;
+    for (i = 0; i < f->slice_count; i++) {
+        FFV1Context *fs = f->slice_context[i];
+        if ((ret = ffv1_init_slice_state(f, fs)) < 0)
+            return AVERROR(ENOMEM);
     }
     return 0;
 }
 
-static av_cold int init_slice_contexts(FFV1Context *f){
+av_cold int ffv1_init_slice_contexts(FFV1Context *f)
+{
     int i;
 
-    f->slice_count= f->num_h_slices * f->num_v_slices;
+    f->slice_count = f->num_h_slices * f->num_v_slices;
+    av_assert0(f->slice_count > 0);
 
-    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;
+    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->slice_width  = sxe - sxs;
+        fs->slice_height = sye - sys;
+        fs->slice_x      = sxs;
+        fs->slice_y      = sys;
 
-        fs->sample_buffer = av_malloc(3*4 * (fs->width+6) * sizeof(*fs->sample_buffer));
+        fs->sample_buffer = av_malloc(3 * MAX_PLANES * (fs->width + 6) *
+                                      sizeof(*fs->sample_buffer));
         if (!fs->sample_buffer)
             return AVERROR(ENOMEM);
     }
     return 0;
 }
 
-static int allocate_initial_states(FFV1Context *f){
+int ffv1_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])
+    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]));
+        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];
-    unsigned v;
-
-    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);
-    if(f->version > 2) {
-        if(f->version == 3)
-            f->minor_version = 2;
-        put_symbol(c, state, f->minor_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->bits_per_raw_sample, 0);
-    put_rac(c, state, f->chroma_planes);
-    put_symbol(c, state, f->chroma_h_shift, 0);
-    put_symbol(c, state, f->chroma_v_shift, 0);
-    put_rac(c, state, f->transparency);
-    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);
-        }
-    }
-
-    if(f->version > 2){
-        put_symbol(c, state, f->ec, 0);
-    }
-
-    f->avctx->extradata_size= ff_rac_terminate(c);
-    v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, f->avctx->extradata, f->avctx->extradata_size);
-    AV_WL32(f->avctx->extradata + f->avctx->extradata_size, v);
-    f->avctx->extradata_size += 4;
-
-    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)
+void ffv1_clear_slice_state(FFV1Context *f, FFV1Context *fs)
 {
-    FFV1Context *s = avctx->priv_data;
-    int i, j, k, m;
-
-    common_init(avctx);
-
-    s->version=0;
-
-    if((avctx->flags & (CODEC_FLAG_PASS1|CODEC_FLAG_PASS2)) || avctx->slices>1)
-        s->version = FFMAX(s->version, 2);
-
-    if(avctx->level == 3){
-        s->version = 3;
-    }
-
-    if(s->ec < 0){
-        s->ec = (s->version >= 3);
-    }
-
-    if(s->version >= 2 && avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
-        av_log(avctx, AV_LOG_ERROR, "Version 2 needed for requested features but version 2 is experimental and not enabled\n");
-        return AVERROR_INVALIDDATA;
-    }
-
-    s->ac= avctx->coder_type > 0 ? 2 : 0;
-
-    s->plane_count=3;
-    switch(avctx->pix_fmt){
-    case PIX_FMT_YUV444P9:
-    case PIX_FMT_YUV422P9:
-    case PIX_FMT_YUV420P9:
-        if (!avctx->bits_per_raw_sample)
-            s->bits_per_raw_sample = 9;
-    case PIX_FMT_YUV444P10:
-    case PIX_FMT_YUV420P10:
-    case PIX_FMT_YUV422P10:
-        s->packed_at_lsb = 1;
-        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
-            s->bits_per_raw_sample = 10;
-    case PIX_FMT_GRAY16:
-    case PIX_FMT_YUV444P16:
-    case PIX_FMT_YUV422P16:
-    case PIX_FMT_YUV420P16:
-        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample) {
-            s->bits_per_raw_sample = 16;
-        } else if (!s->bits_per_raw_sample){
-            s->bits_per_raw_sample = avctx->bits_per_raw_sample;
-        }
-        if(s->bits_per_raw_sample <=8){
-            av_log(avctx, AV_LOG_ERROR, "bits_per_raw_sample invalid\n");
-            return AVERROR_INVALIDDATA;
-        }
-        if(!s->ac && avctx->coder_type == -1) {
-            av_log(avctx, AV_LOG_INFO, "bits_per_raw_sample > 8, forcing coder 1\n");
-            s->ac = 2;
-        }
-        if(!s->ac){
-            av_log(avctx, AV_LOG_ERROR, "bits_per_raw_sample of more than 8 needs -coder 1 currently\n");
-            return AVERROR_INVALIDDATA;
-        }
-        s->version= FFMAX(s->version, 1);
-    case PIX_FMT_GRAY8:
-    case PIX_FMT_YUV444P:
-    case PIX_FMT_YUV440P:
-    case PIX_FMT_YUV422P:
-    case PIX_FMT_YUV420P:
-    case PIX_FMT_YUV411P:
-    case PIX_FMT_YUV410P:
-        s->chroma_planes= av_pix_fmt_descriptors[avctx->pix_fmt].nb_components < 3 ? 0 : 1;
-        s->colorspace= 0;
-        break;
-    case PIX_FMT_YUVA444P:
-    case PIX_FMT_YUVA422P:
-    case PIX_FMT_YUVA420P:
-        s->chroma_planes= 1;
-        s->colorspace= 0;
-        s->transparency= 1;
-        break;
-    case PIX_FMT_RGB32:
-        s->colorspace= 1;
-        s->transparency= 1;
-        break;
-    case PIX_FMT_0RGB32:
-        s->colorspace= 1;
-        break;
-    case PIX_FMT_GBRP9:
-        if (!avctx->bits_per_raw_sample)
-            s->bits_per_raw_sample = 9;
-    case PIX_FMT_GBRP10:
-        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
-            s->bits_per_raw_sample = 10;
-    case PIX_FMT_GBRP12:
-        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
-            s->bits_per_raw_sample = 12;
-    case PIX_FMT_GBRP14:
-        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
-            s->bits_per_raw_sample = 14;
-        else if (!s->bits_per_raw_sample)
-            s->bits_per_raw_sample = avctx->bits_per_raw_sample;
-        s->colorspace= 1;
-        s->chroma_planes= 1;
-        s->version= FFMAX(s->version, 1);
-        break;
-    default:
-        av_log(avctx, AV_LOG_ERROR, "format not supported\n");
-        return AVERROR_INVALIDDATA;
-    }
-    if (s->transparency) {
-        av_log(avctx, AV_LOG_WARNING, "Storing alpha plane, this will require a recent FFV1 decoder to playback!\n");
-    }
-    if (avctx->context_model > 1U) {
-        av_log(avctx, AV_LOG_ERROR, "Invalid context model %d, valid values are 0 and 1\n", avctx->context_model);
-        return AVERROR(EINVAL);
-    }
-
-    if(s->ac>1)
-        for(i=1; i<256; i++)
-            s->state_transition[i]=ver2_state[i];
-
-    for(i=0; i<256; i++){
-        s->quant_table_count=2;
-        if(s->bits_per_raw_sample <=8){
-            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_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];
-
-        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;
-    if(!s->transparency)
-        s->plane_count= 2;
-    avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_h_shift, &s->chroma_v_shift);
-
-    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 AVERROR_INVALIDDATA;
-                            }
-                            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 AVERROR_INVALIDDATA;
-            }
-            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){
-        for(s->num_v_slices=2; s->num_v_slices<9; s->num_v_slices++){
-            for(s->num_h_slices=s->num_v_slices; s->num_h_slices<2*s->num_v_slices; s->num_h_slices++){
-                if(avctx->slices == s->num_h_slices * s->num_v_slices && avctx->slices <= 64 || !avctx->slices)
-                    goto slices_ok;
-            }
-        }
-        av_log(avctx, AV_LOG_ERROR, "Unsupported number %d of slices requested, please specify a supported number with -slices (ex:4,6,9,12,16, ...)\n", avctx->slices);
-        return -1;
-        slices_ok:
-        write_extra_header(s);
-    }
-
-    if(init_slice_contexts(s) < 0)
-        return -1;
-    if(init_slices_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_slice_state(FFV1Context *f, FFV1Context *fs){
     int i, j;
 
-        for(i=0; i<f->plane_count; i++){
-            PlaneContext *p= &fs->plane[i];
+    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;
 
-            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{
-                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 (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 {
+            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 void encode_slice_header(FFV1Context *f, FFV1Context *fs){
-    RangeCoder *c = &fs->c;
-    uint8_t state[CONTEXT_SIZE];
-    int j;
-    memset(state, 128, sizeof(state));
-
-    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);
-    }
-    if(!f->picture.interlaced_frame) put_symbol(c, state, 3, 0);
-    else                             put_symbol(c, state, 1 + !f->picture.top_field_first, 0);
-    put_symbol(c, state, f->picture.sample_aspect_ratio.num, 0);
-    put_symbol(c, state, f->picture.sample_aspect_ratio.den, 0);
-}
-
-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;
-    const int ps= (f->bits_per_raw_sample>8)+1;
-
-    if(p->key_frame)
-        clear_slice_state(f, fs);
-    if(f->version > 2){
-        encode_slice_header(f, fs);
-    }
-    if(!fs->ac){
-        if(f->version > 2)
-            put_rac(&fs->c, (int[]){129}, 0);
-        fs->ac_byte_count = f->version > 2 || (!x&&!y) ? ff_rac_terminate(&fs->c) : 0;
-        init_put_bits(&fs->pb, fs->c.bytestream_start + fs->ac_byte_count, fs->c.bytestream_end - fs->c.bytestream_start - fs->ac_byte_count);
-    }
-
-    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] + ps*x + y*p->linesize[0], width, height, p->linesize[0], 0);
-
-        if (f->chroma_planes){
-            encode_plane(fs, p->data[1] + ps*cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);
-            encode_plane(fs, p->data[2] + ps*cx+cy*p->linesize[2], chroma_width, chroma_height, p->linesize[2], 1);
-        }
-        if (fs->transparency)
-            encode_plane(fs, p->data[3] + ps*x + y*p->linesize[3], width, height, p->linesize[3], 2);
-    }else{
-        uint8_t *planes[3] = {p->data[0] + ps*x + y*p->linesize[0],
-                              p->data[1] + ps*x + y*p->linesize[1],
-                              p->data[2] + ps*x + y*p->linesize[2]};
-        encode_rgb_frame(fs, planes, width, height, p->linesize);
-    }
-    emms_c();
-
-    return 0;
-}
-
-static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
-                        const AVFrame *pict, int *got_packet)
+av_cold int ffv1_close(AVCodecContext *avctx)
 {
-    FFV1Context *f = avctx->priv_data;
-    RangeCoder * const c= &f->slice_context[0]->c;
-    AVFrame * const p= &f->picture;
-    int used_count= 0;
-    uint8_t keystate=128;
-    uint8_t *buf_p;
-    int i, ret;
-
-    if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*((8*2+1+1)*4)/8
-                                  + FF_MIN_BUFFER_SIZE)) < 0)
-        return ret;
-
-    ff_init_range_encoder(c, pkt->data, pkt->size);
-    ff_build_rac_states(c, 0.05*(1LL<<32), 256-8);
-
-    *p = *pict;
-    p->pict_type= AV_PICTURE_TYPE_I;
-
-    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);
-    }else{
-        put_rac(c, &keystate, 0);
-        p->key_frame= 0;
-    }
-
-    if (f->ac>1){
-        int i;
-        for(i=1; i<256; i++){
-            c->one_state[i]= f->state_transition[i];
-            c->zero_state[256-i]= 256-c->one_state[i];
-        }
-    }
-
-    for(i=1; i<f->slice_count; i++){
-        FFV1Context *fs= f->slice_context[i];
-        uint8_t *start = pkt->data + (pkt->size-used_count)*(int64_t)i/f->slice_count;
-        int len = pkt->size/f->slice_count;
-        ff_init_range_encoder(&fs->c, start, len);
-    }
-    avctx->execute(avctx, encode_slice, &f->slice_context[0], NULL, f->slice_count, sizeof(void*));
-
-    buf_p = pkt->data;
-    for(i=0; i<f->slice_count; i++){
-        FFV1Context *fs= f->slice_context[i];
-        int bytes;
-
-        if(fs->ac){
-            uint8_t state=129;
-            put_rac(&fs->c, &state, 0);
-            bytes= ff_rac_terminate(&fs->c);
-        }else{
-            flush_put_bits(&fs->pb); //nicer padding FIXME
-            bytes= fs->ac_byte_count + (put_bits_count(&fs->pb)+7)/8;
-        }
-        if(i>0 || f->version>2){
-            av_assert0(bytes < pkt->size/f->slice_count);
-            memmove(buf_p, fs->c.bytestream_start, bytes);
-            av_assert0(bytes < (1<<24));
-            AV_WB24(buf_p+bytes, bytes);
-            bytes+=3;
-        }
-        if(f->ec){
-            unsigned v;
-            buf_p[bytes++] = 0;
-            v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, buf_p, bytes);
-            AV_WL32(buf_p + bytes, v); bytes += 4;
-        }
-        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++;
-    pkt->size   = buf_p - pkt->data;
-    pkt->flags |= AV_PKT_FLAG_KEY*p->key_frame;
-    *got_packet = 1;
-
-    return 0;
-}
-#endif /* CONFIG_FFV1_ENCODER */
-
-static av_cold int common_end(AVCodecContext *avctx){
     FFV1Context *s = avctx->priv_data;
     int i, j;
 
@@ -1412,10 +193,10 @@
     if (avctx->codec->decode && s->last_picture.data[0])
         avctx->release_buffer(avctx, &s->last_picture);
 
-    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];
+    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);
@@ -1424,788 +205,17 @@
     }
 
     av_freep(&avctx->stats_out);
-    for(j=0; j<s->quant_table_count; j++){
+    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];
+        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++){
+    for (i = 0; i < s->slice_count; i++)
         av_freep(&s->slice_context[i]);
-    }
 
     return 0;
 }
-
-static av_always_inline void decode_line(FFV1Context *s, int w,
-                                         int16_t *sample[2],
-                                         int plane_index, int bits)
-{
-    PlaneContext * const p= &s->plane[plane_index];
-    RangeCoder * const c= &s->c;
-    int x;
-    int run_count=0;
-    int run_mode=0;
-    int run_index= s->run_index;
-
-    for(x=0; x<w; x++){
-        int diff, context, sign;
-
-        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);
-        }else{
-            if(context == 0 && run_mode==0) run_mode=1;
-
-            if(run_mode){
-                if(run_count==0 && run_mode==1){
-                    if(get_bits1(&s->gb)){
-                        run_count = 1<<ff_log2_run[run_index];
-                        if(x + run_count <= w) run_index++;
-                    }else{
-                        if(ff_log2_run[run_index]) run_count = get_bits(&s->gb, ff_log2_run[run_index]);
-                        else run_count=0;
-                        if(run_index) run_index--;
-                        run_mode=2;
-                    }
-                }
-                run_count--;
-                if(run_count < 0){
-                    run_mode=0;
-                    run_count=0;
-                    diff= get_vlc_symbol(&s->gb, &p->vlc_state[context], bits);
-                    if(diff>=0) diff++;
-                }else
-                    diff=0;
-            }else
-                diff= get_vlc_symbol(&s->gb, &p->vlc_state[context], bits);
-
-            av_dlog(s->avctx, "count:%d index:%d, mode:%d, x:%d pos:%d\n",
-                    run_count, run_index, run_mode, x, get_bits_count(&s->gb));
-        }
-
-        if(sign) diff= -diff;
-
-        sample[1][x]= (predict(sample[1] + x, sample[0] + x) + diff) & ((1<<bits)-1);
-    }
-    s->run_index= run_index;
-}
-
-static void decode_plane(FFV1Context *s, uint8_t *src, int w, int h, int stride, int plane_index){
-    int x, y;
-    int16_t *sample[2];
-    sample[0]=s->sample_buffer    +3;
-    sample[1]=s->sample_buffer+w+6+3;
-
-    s->run_index=0;
-
-    memset(s->sample_buffer, 0, 2*(w+6)*sizeof(*s->sample_buffer));
-
-    for(y=0; y<h; y++){
-        int16_t *temp = sample[0]; //FIXME try a normal buffer
-
-        sample[0]= sample[1];
-        sample[1]= temp;
-
-        sample[1][-1]= sample[0][0  ];
-        sample[0][ w]= sample[0][w-1];
-
-//{START_TIMER
-        if(s->avctx->bits_per_raw_sample <= 8){
-            decode_line(s, w, sample, plane_index, 8);
-            for(x=0; x<w; x++){
-                src[x + stride*y]= sample[1][x];
-            }
-        }else{
-            decode_line(s, w, sample, plane_index, s->avctx->bits_per_raw_sample);
-            if(s->packed_at_lsb){
-                for(x=0; x<w; x++){
-                    ((uint16_t*)(src + stride*y))[x]= sample[1][x];
-                }
-            }else{
-                for(x=0; x<w; x++){
-                    ((uint16_t*)(src + stride*y))[x]= sample[1][x] << (16 - s->avctx->bits_per_raw_sample);
-                }
-            }
-        }
-//STOP_TIMER("decode-line")}
-    }
-}
-
-static void decode_rgb_frame(FFV1Context *s, uint8_t *src[3], int w, int h, int stride[3]){
-    int x, y, p;
-    int16_t *sample[4][2];
-    int lbd=  s->avctx->bits_per_raw_sample <= 8;
-    int bits= s->avctx->bits_per_raw_sample > 0 ? s->avctx->bits_per_raw_sample : 8;
-    int offset= 1 << bits;
-    for(x=0; x<4; x++){
-        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(s->sample_buffer, 0, 8*(w+6)*sizeof(*s->sample_buffer));
-
-    for(y=0; y<h; y++){
-        for(p=0; p<3 + s->transparency; p++){
-            int16_t *temp = sample[p][0]; //FIXME try a normal buffer
-
-            sample[p][0]= sample[p][1];
-            sample[p][1]= temp;
-
-            sample[p][1][-1]= sample[p][0][0  ];
-            sample[p][0][ w]= sample[p][0][w-1];
-            if (lbd)
-                decode_line(s, w, sample[p], (p+1)/2, 9);
-            else
-                decode_line(s, w, sample[p], (p+1)/2, bits+1);
-        }
-        for(x=0; x<w; x++){
-            int g= sample[0][1][x];
-            int b= sample[1][1][x];
-            int r= sample[2][1][x];
-            int a= sample[3][1][x];
-
-//            assert(g>=0 && b>=0 && r>=0);
-//            assert(g<256 && b<512 && r<512);
-
-            b -= offset;
-            r -= offset;
-            g -= (b + r)>>2;
-            b += g;
-            r += g;
-
-            if(lbd)
-                *((uint32_t*)(src[0] + x*4 + stride[0]*y))= b + (g<<8) + (r<<16) + (a<<24);
-            else{
-                *((uint16_t*)(src[0] + x*2 + stride[0]*y)) = b;
-                *((uint16_t*)(src[1] + x*2 + stride[1]*y)) = g;
-                *((uint16_t*)(src[2] + x*2 + stride[2]*y)) = r;
-            }
-        }
-    }
-}
-
-static int decode_slice_header(FFV1Context *f, FFV1Context *fs){
-    RangeCoder *c = &fs->c;
-    uint8_t state[CONTEXT_SIZE];
-    unsigned ps, i, context_count;
-    memset(state, 128, sizeof(state));
-
-    av_assert0(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;
-
-    for(i=0; i<f->plane_count; i++){
-        PlaneContext * const p= &fs->plane[i];
-        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];
-
-        if(p->context_count < context_count){
-            av_freep(&p->state);
-            av_freep(&p->vlc_state);
-        }
-        p->context_count= context_count;
-    }
-
-    ps = get_symbol(c, state, 0);
-    if(ps==1){
-        f->picture.interlaced_frame = 1;
-        f->picture.top_field_first  = 1;
-    } else if(ps==2){
-        f->picture.interlaced_frame = 1;
-        f->picture.top_field_first  = 0;
-    } else if(ps==3){
-        f->picture.interlaced_frame = 0;
-    }
-    f->picture.sample_aspect_ratio.num = get_symbol(c, state, 0);
-    f->picture.sample_aspect_ratio.den = get_symbol(c, state, 0);
-
-    return 0;
-}
-
-static int decode_slice(AVCodecContext *c, void *arg){
-    FFV1Context *fs= *(void**)arg;
-    FFV1Context *f= fs->avctx->priv_data;
-    int width, height, x, y;
-    const int ps= (c->bits_per_raw_sample>8)+1;
-    AVFrame * const p= &f->picture;
-
-    if(f->version > 2){
-        if(init_slice_state(f, fs) < 0)
-            return AVERROR(ENOMEM);
-        if(decode_slice_header(f, fs) < 0) {
-            fs->slice_damaged = 1;
-            return AVERROR_INVALIDDATA;
-        }
-    }
-    if(init_slice_state(f, fs) < 0)
-        return AVERROR(ENOMEM);
-    if(f->picture.key_frame)
-        clear_slice_state(f, fs);
-    width = fs->slice_width;
-    height= fs->slice_height;
-    x= fs->slice_x;
-    y= fs->slice_y;
-
-    if(!fs->ac){
-        if (f->version == 3 && f->minor_version > 1 || f->version > 3)
-            get_rac(&fs->c, (int[]){129});
-        fs->ac_byte_count = f->version > 2 || (!x&&!y) ? fs->c.bytestream - fs->c.bytestream_start - 1 : 0;
-        init_get_bits(&fs->gb,
-                      fs->c.bytestream_start + fs->ac_byte_count,
-                      (fs->c.bytestream_end - fs->c.bytestream_start - fs->ac_byte_count) * 8);
-    }
-
-    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] + ps*x + y*p->linesize[0], width, height, p->linesize[0], 0);
-
-        if (f->chroma_planes){
-            decode_plane(fs, p->data[1] + ps*cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);
-            decode_plane(fs, p->data[2] + ps*cx+cy*p->linesize[2], chroma_width, chroma_height, p->linesize[2], 1);
-        }
-        if (fs->transparency)
-            decode_plane(fs, p->data[3] + ps*x + y*p->linesize[3], width, height, p->linesize[3], 2);
-    }else{
-        uint8_t *planes[3] = {p->data[0] + ps*x + y*p->linesize[0],
-                              p->data[1] + ps*x + y*p->linesize[1],
-                              p->data[2] + ps*x + y*p->linesize[2]};
-        decode_rgb_frame(fs, planes, width, height, p->linesize);
-    }
-    if(fs->ac && f->version > 2) {
-        int v;
-        get_rac(&fs->c, (int[]){129});
-        v = fs->c.bytestream_end - fs->c.bytestream - 2 - 5*f->ec;
-        if(v) {
-            av_log(f->avctx, AV_LOG_ERROR, "bytestream end mismatching by %d\n", v);
-            fs->slice_damaged = 1;
-        }
-    }
-
-    emms_c();
-
-    return 0;
-}
-
-static int read_quant_table(RangeCoder *c, int16_t *quant_table, int scale){
-    int v;
-    int i=0;
-    uint8_t state[CONTEXT_SIZE];
-
-    memset(state, 128, sizeof(state));
-
-    for(v=0; i<128 ; v++){
-        unsigned len= get_symbol(c, state, 0) + 1;
-
-        if(len > 128 - i) return -1;
-
-        while(len--){
-            quant_table[i] = scale*v;
-            i++;
-        }
-    }
-
-    for(i=1; i<128; i++){
-        quant_table[256-i]= -quant_table[i];
-    }
-    quant_table[128]= -quant_table[127];
-
-    return 2*v - 1;
-}
-
-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);
-    if(f->version > 2) {
-        c->bytestream_end -= 4;
-        f->minor_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
-    f->avctx->bits_per_raw_sample= get_symbol(c, state, 0);
-    f->chroma_planes= get_rac(c, state);
-    f->chroma_h_shift= get_symbol(c, state, 0);
-    f->chroma_v_shift= get_symbol(c, state, 0);
-    f->transparency= get_rac(c, state);
-    f->plane_count= 2 + f->transparency;
-    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;
-                }
-            }
-        }
-    }
-
-    if(f->version > 2){
-        f->ec = get_symbol(c, state, 0);
-    }
-
-    if(f->version > 2){
-        unsigned v;
-        v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, f->avctx->extradata, f->avctx->extradata_size);
-        if(v){
-            av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!\n", v);
-            return AVERROR_INVALIDDATA;
-        }
-    }
-
-    return 0;
-}
-
-static int read_header(FFV1Context *f){
-    uint8_t state[CONTEXT_SIZE];
-    int i, j, context_count = -1; //-1 to avoid warning
-    RangeCoder * const c= &f->slice_context[0]->c;
-
-    memset(state, 128, sizeof(state));
-
-    if(f->version < 2){
-        unsigned v= get_symbol(c, state, 0);
-        if(v >= 2){
-            av_log(f->avctx, AV_LOG_ERROR, "invalid version %d in ver01 header\n", v);
-            return AVERROR_INVALIDDATA;
-        }
-        f->version = v;
-        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);
-        f->chroma_planes= get_rac(c, state);
-        f->chroma_h_shift= get_symbol(c, state, 0);
-        f->chroma_v_shift= get_symbol(c, state, 0);
-        f->transparency= get_rac(c, state);
-        f->plane_count= 2 + f->transparency;
-    }
-
-    if(f->colorspace==0){
-        if(!f->transparency && !f->chroma_planes){
-            if (f->avctx->bits_per_raw_sample<=8)
-                f->avctx->pix_fmt= PIX_FMT_GRAY8;
-            else
-                f->avctx->pix_fmt= PIX_FMT_GRAY16;
-        }else if(f->avctx->bits_per_raw_sample<=8 && !f->transparency){
-            switch(16*f->chroma_h_shift + f->chroma_v_shift){
-            case 0x00: f->avctx->pix_fmt= PIX_FMT_YUV444P; break;
-            case 0x01: f->avctx->pix_fmt= PIX_FMT_YUV440P; break;
-            case 0x10: f->avctx->pix_fmt= PIX_FMT_YUV422P; break;
-            case 0x11: f->avctx->pix_fmt= PIX_FMT_YUV420P; break;
-            case 0x20: f->avctx->pix_fmt= PIX_FMT_YUV411P; break;
-            case 0x22: f->avctx->pix_fmt= PIX_FMT_YUV410P; break;
-            default:
-                av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
-                return -1;
-            }
-        }else if(f->avctx->bits_per_raw_sample<=8 && f->transparency){
-            switch(16*f->chroma_h_shift + f->chroma_v_shift){
-            case 0x00: f->avctx->pix_fmt= PIX_FMT_YUVA444P; break;
-            case 0x10: f->avctx->pix_fmt= PIX_FMT_YUVA422P; break;
-            case 0x11: f->avctx->pix_fmt= PIX_FMT_YUVA420P; break;
-            default:
-                av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
-                return -1;
-            }
-        }else if(f->avctx->bits_per_raw_sample==9) {
-            f->packed_at_lsb=1;
-            switch(16*f->chroma_h_shift + f->chroma_v_shift){
-            case 0x00: f->avctx->pix_fmt= PIX_FMT_YUV444P9; break;
-            case 0x10: f->avctx->pix_fmt= PIX_FMT_YUV422P9; break;
-            case 0x11: f->avctx->pix_fmt= PIX_FMT_YUV420P9; break;
-            default:
-                av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
-                return -1;
-            }
-        }else if(f->avctx->bits_per_raw_sample==10) {
-            f->packed_at_lsb=1;
-            switch(16*f->chroma_h_shift + f->chroma_v_shift){
-            case 0x00: f->avctx->pix_fmt= PIX_FMT_YUV444P10; break;
-            case 0x10: f->avctx->pix_fmt= PIX_FMT_YUV422P10; break;
-            case 0x11: f->avctx->pix_fmt= PIX_FMT_YUV420P10; break;
-            default:
-                av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
-                return -1;
-            }
-        }else {
-            switch(16*f->chroma_h_shift + f->chroma_v_shift){
-            case 0x00: f->avctx->pix_fmt= PIX_FMT_YUV444P16; break;
-            case 0x10: f->avctx->pix_fmt= PIX_FMT_YUV422P16; break;
-            case 0x11: f->avctx->pix_fmt= PIX_FMT_YUV420P16; break;
-            default:
-                av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
-                return -1;
-            }
-        }
-    }else if(f->colorspace==1){
-        if(f->chroma_h_shift || f->chroma_v_shift){
-            av_log(f->avctx, AV_LOG_ERROR, "chroma subsampling not supported in this colorspace\n");
-            return -1;
-        }
-        if(f->avctx->bits_per_raw_sample==9)
-            f->avctx->pix_fmt= PIX_FMT_GBRP9;
-        else if(f->avctx->bits_per_raw_sample==10)
-            f->avctx->pix_fmt= PIX_FMT_GBRP10;
-        else if(f->avctx->bits_per_raw_sample==12)
-            f->avctx->pix_fmt= PIX_FMT_GBRP12;
-        else if(f->avctx->bits_per_raw_sample==14)
-            f->avctx->pix_fmt= PIX_FMT_GBRP14;
-        else
-        if(f->transparency) f->avctx->pix_fmt= PIX_FMT_RGB32;
-        else                f->avctx->pix_fmt= PIX_FMT_0RGB32;
-    }else{
-        av_log(f->avctx, AV_LOG_ERROR, "colorspace not supported\n");
-        return -1;
-    }
-
-    av_dlog(f->avctx, "%d %d %d\n",
-            f->chroma_h_shift, f->chroma_v_shift, f->avctx->pix_fmt);
-    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 if(f->version < 3){
-        f->slice_count= get_symbol(c, state, 0);
-    }else{
-        const uint8_t *p= c->bytestream_end;
-        for(f->slice_count = 0; f->slice_count < MAX_SLICES && 3 < p - c->bytestream_start; f->slice_count++){
-            int trailer = 3 + 5*!!f->ec;
-            int size = AV_RB24(p-trailer);
-            if(size + trailer > p - c->bytestream_start)
-                break;
-            p -= size + trailer;
-        }
-    }
-    if(f->slice_count > (unsigned)MAX_SLICES || f->slice_count <= 0){
-        av_log(f->avctx, AV_LOG_ERROR, "slice count %d is invalid\n", f->slice_count);
-        return -1;
-    }
-
-    for(j=0; j<f->slice_count; j++){
-        FFV1Context *fs= f->slice_context[j];
-        fs->ac= f->ac;
-        fs->packed_at_lsb= f->packed_at_lsb;
-
-        fs->slice_damaged = 0;
-
-        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;
-        }
-
-        for(i=0; i<f->plane_count; i++){
-            PlaneContext * const p= &fs->plane[i];
-
-            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(f->version <= 2){
-                av_assert0(context_count>=0);
-                if(p->context_count < context_count){
-                    av_freep(&p->state);
-                    av_freep(&p->vlc_state);
-                }
-                p->context_count= context_count;
-            }
-        }
-    }
-    return 0;
-}
-
-static av_cold int decode_init(AVCodecContext *avctx)
-{
-    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;
-}
-
-static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt){
-    const uint8_t *buf = avpkt->data;
-    int buf_size = avpkt->size;
-    FFV1Context *f = avctx->priv_data;
-    RangeCoder * const c= &f->slice_context[0]->c;
-    AVFrame * const p= &f->picture;
-    int 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);
-
-
-    p->pict_type= AV_PICTURE_TYPE_I; //FIXME I vs. P
-    if(get_rac(c, &keystate)){
-        p->key_frame= 1;
-        f->key_frame_ok = 0;
-        if(read_header(f) < 0)
-            return -1;
-        f->key_frame_ok = 1;
-    }else{
-        if (!f->key_frame_ok) {
-            av_log(avctx, AV_LOG_ERROR, "Cant decode non keyframe without valid keyframe\n");
-            return AVERROR_INVALIDDATA;
-        }
-        p->key_frame= 0;
-    }
-
-    p->reference= 3; //for error concealment
-    if(avctx->get_buffer(avctx, p) < 0){
-        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
-    }
-
-    if(avctx->debug&FF_DEBUG_PICT_INFO)
-        av_log(avctx, AV_LOG_DEBUG, "ver:%d keyframe:%d coder:%d ec:%d slices:%d\n",
-               f->version, p->key_frame, f->ac, f->ec, f->slice_count);
-
-    buf_p= buf + buf_size;
-    for(i=f->slice_count-1; i>=0; i--){
-        FFV1Context *fs= f->slice_context[i];
-        int trailer = 3 + 5*!!f->ec;
-        int v;
-
-        if(i || f->version>2) v = AV_RB24(buf_p-trailer)+trailer;
-        else                  v = buf_p - c->bytestream_start;
-        if(buf_p - c->bytestream_start < v){
-            av_log(avctx, AV_LOG_ERROR, "Slice pointer chain broken\n");
-            return -1;
-        }
-        buf_p -= v;
-
-        if(f->ec){
-            unsigned crc = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, buf_p, v);
-            if(crc){
-                int64_t ts = avpkt->pts != AV_NOPTS_VALUE ? avpkt->pts : avpkt->dts;
-                av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!", crc);
-                if(ts != AV_NOPTS_VALUE && avctx->pkt_timebase.num) {
-                    av_log(f->avctx, AV_LOG_ERROR, "at %f seconds\n",ts*av_q2d(avctx->pkt_timebase));
-                } else if(ts != AV_NOPTS_VALUE) {
-                    av_log(f->avctx, AV_LOG_ERROR, "at %"PRId64"\n", ts);
-                } else {
-                    av_log(f->avctx, AV_LOG_ERROR, "\n");
-                }
-                fs->slice_damaged = 1;
-            }
-        }
-
-        if(i){
-            ff_init_range_decoder(&fs->c, buf_p, v);
-        }else
-            fs->c.bytestream_end = (uint8_t *)(buf_p + v);
-    }
-
-    avctx->execute(avctx, decode_slice, &f->slice_context[0], NULL, f->slice_count, sizeof(void*));
-
-    for(i=f->slice_count-1; i>=0; i--){
-        FFV1Context *fs= f->slice_context[i];
-        int j;
-        if(fs->slice_damaged && f->last_picture.data[0]){
-            uint8_t *dst[4], *src[4];
-            for(j=0; j<4; j++){
-                int sh = (j==1 || j==2) ? f->chroma_h_shift : 0;
-                int sv = (j==1 || j==2) ? f->chroma_v_shift : 0;
-                dst[j] = f->picture     .data[j] + f->picture     .linesize[j]*
-                         (fs->slice_y>>sv) + (fs->slice_x>>sh);
-                src[j] = f->last_picture.data[j] + f->last_picture.linesize[j]*
-                         (fs->slice_y>>sv) + (fs->slice_x>>sh);
-            }
-            av_image_copy(dst, f->picture.linesize, (const uint8_t **)src, f->last_picture.linesize,
-                          avctx->pix_fmt, fs->slice_width, fs->slice_height);
-        }
-    }
-
-    f->picture_number++;
-
-    *picture= *p;
-    *data_size = sizeof(AVFrame);
-
-    FFSWAP(AVFrame, f->picture, f->last_picture);
-
-    return buf_size;
-}
-
-AVCodec ff_ffv1_decoder = {
-    .name           = "ffv1",
-    .type           = AVMEDIA_TYPE_VIDEO,
-    .id             = AV_CODEC_ID_FFV1,
-    .priv_data_size = sizeof(FFV1Context),
-    .init           = decode_init,
-    .close          = common_end,
-    .decode         = decode_frame,
-    .capabilities   = CODEC_CAP_DR1 /*| CODEC_CAP_DRAW_HORIZ_BAND*/ |
-                      CODEC_CAP_SLICE_THREADS,
-    .long_name      = NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"),
-};
-
-#if CONFIG_FFV1_ENCODER
-
-#define OFFSET(x) offsetof(FFV1Context, x)
-#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
-static const AVOption options[] = {
-    { "slicecrc",        "Protect slices with CRCs",               OFFSET(ec),              AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
-{NULL}
-};
-
-static const AVClass class = {
-    .class_name = "ffv1 encoder",
-    .item_name  = av_default_item_name,
-    .option     = options,
-    .version    = LIBAVUTIL_VERSION_INT,
-};
-
-static const AVCodecDefault ffv1_defaults[] = {
-    { "coder",                "-1" },
-    { NULL },
-};
-
-AVCodec ff_ffv1_encoder = {
-    .name           = "ffv1",
-    .type           = AVMEDIA_TYPE_VIDEO,
-    .id             = AV_CODEC_ID_FFV1,
-    .priv_data_size = sizeof(FFV1Context),
-    .init           = encode_init,
-    .encode2        = encode_frame,
-    .close          = common_end,
-    .capabilities   = CODEC_CAP_SLICE_THREADS,
-    .defaults       = ffv1_defaults,
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_YUV420P, PIX_FMT_YUVA420P, PIX_FMT_YUVA422P, PIX_FMT_YUV444P,
-        PIX_FMT_YUVA444P, PIX_FMT_YUV440P, PIX_FMT_YUV422P, PIX_FMT_YUV411P,
-        PIX_FMT_YUV410P, PIX_FMT_0RGB32, PIX_FMT_RGB32, PIX_FMT_YUV420P16,
-        PIX_FMT_YUV422P16, PIX_FMT_YUV444P16, PIX_FMT_YUV444P9, PIX_FMT_YUV422P9,
-        PIX_FMT_YUV420P9, PIX_FMT_YUV420P10, PIX_FMT_YUV422P10, PIX_FMT_YUV444P10,
-        PIX_FMT_GRAY16, PIX_FMT_GRAY8, PIX_FMT_GBRP9, PIX_FMT_GBRP10,
-        PIX_FMT_GBRP12, PIX_FMT_GBRP14,
-        PIX_FMT_NONE
-    },
-    .long_name      = NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"),
-    .priv_class     = &class,
-};
-#endif
diff --git a/libavcodec/ffv1.h b/libavcodec/ffv1.h
new file mode 100644
index 0000000..02c3afa
--- /dev/null
+++ b/libavcodec/ffv1.h
@@ -0,0 +1,215 @@
+/*
+ * FFV1 codec for libavcodec
+ *
+ * Copyright (c) 2003-2012 Michael Niedermayer <michaelni@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
+ */
+
+#ifndef AVCODEC_FFV1_H
+#define AVCODEC_FFV1_H
+
+/**
+ * @file
+ * FF Video Codec 1 (a lossless codec)
+ */
+
+#include "libavutil/avassert.h"
+#include "libavutil/crc.h"
+#include "libavutil/opt.h"
+#include "libavutil/imgutils.h"
+#include "libavutil/pixdesc.h"
+#include "libavutil/timer.h"
+#include "avcodec.h"
+#include "dsputil.h"
+#include "get_bits.h"
+#include "internal.h"
+#include "mathops.h"
+#include "put_bits.h"
+#include "rangecoder.h"
+
+#ifdef __INTEL_COMPILER
+#undef av_flatten
+#define av_flatten
+#endif
+
+#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[41];
+
+typedef struct VlcState {
+    int16_t drift;
+    uint16_t error_sum;
+    int8_t bias;
+    uint8_t count;
+} 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 {
+    AVClass *class;
+    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 minor_version;
+    int width, height;
+    int chroma_planes;
+    int chroma_h_shift, chroma_v_shift;
+    int transparency;
+    int flags;
+    int picture_number;
+    AVFrame picture;
+    AVFrame last_picture;
+    int plane_count;
+    int ac;                              ///< 1=range coder <-> 0=golomb rice
+    int ac_byte_count;                   ///< number of bytes used for AC coding
+    PlaneContext plane[MAX_PLANES];
+    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;
+    int16_t *sample_buffer;
+
+    int ec;
+    int slice_damaged;
+    int key_frame_ok;
+
+    int bits_per_raw_sample;
+    int packed_at_lsb;
+
+    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;
+
+int ffv1_common_init(AVCodecContext *avctx);
+int ffv1_init_slice_state(FFV1Context *f, FFV1Context *fs);
+int ffv1_init_slices_state(FFV1Context *f);
+int ffv1_init_slice_contexts(FFV1Context *f);
+int ffv1_allocate_initial_states(FFV1Context *f);
+void ffv1_clear_slice_state(FFV1Context *f, FFV1Context *fs);
+int ffv1_close(AVCodecContext *avctx);
+
+static av_always_inline int fold(int diff, int bits)
+{
+    if (bits == 8)
+        diff = (int8_t)diff;
+    else {
+        diff +=  1 << (bits  - 1);
+        diff &= (1 <<  bits) - 1;
+        diff -=  1 << (bits  - 1);
+    }
+
+    return diff;
+}
+
+static inline int predict(int16_t *src, int16_t *last)
+{
+    const int LT = last[-1];
+    const int T  = last[0];
+    const int L  = src[-1];
+
+    return mid_pred(L, L + T - LT, T);
+}
+
+static inline int get_context(PlaneContext *p, int16_t *src,
+                              int16_t *last, int16_t *last2)
+{
+    const int LT = last[-1];
+    const int T  = last[0];
+    const int RT = last[1];
+    const int L  = src[-1];
+
+    if (p->quant_table[3][127]) {
+        const int TT = last2[0];
+        const int LL = src[-2];
+        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 p->quant_table[0][(L - LT) & 0xFF] +
+               p->quant_table[1][(LT - T) & 0xFF] +
+               p->quant_table[2][(T - RT) & 0xFF];
+}
+
+static inline void update_vlc_state(VlcState *const state, const int v)
+{
+    int drift = state->drift;
+    int count = state->count;
+    state->error_sum += FFABS(v);
+    drift            += v;
+
+    if (count == 128) { // FIXME: variable
+        count            >>= 1;
+        drift            >>= 1;
+        state->error_sum >>= 1;
+    }
+    count++;
+
+    if (drift <= -count) {
+        if (state->bias > -128)
+            state->bias--;
+
+        drift += count;
+        if (drift <= -count)
+            drift = -count + 1;
+    } else if (drift > 0) {
+        if (state->bias < 127)
+            state->bias++;
+
+        drift -= count;
+        if (drift > 0)
+            drift = 0;
+    }
+
+    state->drift = drift;
+    state->count = count;
+}
+
+#endif /* AVCODEC_FFV1_H */
diff --git a/libavcodec/ffv1dec.c b/libavcodec/ffv1dec.c
new file mode 100644
index 0000000..da44b94
--- /dev/null
+++ b/libavcodec/ffv1dec.c
@@ -0,0 +1,864 @@
+/*
+ * FFV1 decoder
+ *
+ * Copyright (c) 2003-2012 Michael Niedermayer <michaelni@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
+ * FF Video Codec 1 (a lossless codec) decoder
+ */
+
+#include "libavutil/avassert.h"
+#include "libavutil/crc.h"
+#include "libavutil/opt.h"
+#include "libavutil/imgutils.h"
+#include "libavutil/pixdesc.h"
+#include "libavutil/timer.h"
+#include "avcodec.h"
+#include "internal.h"
+#include "get_bits.h"
+#include "put_bits.h"
+#include "dsputil.h"
+#include "rangecoder.h"
+#include "golomb.h"
+#include "mathops.h"
+#include "ffv1.h"
+
+static inline av_flatten int get_symbol_inline(RangeCoder *c, uint8_t *state,
+                                               int is_signed)
+{
+    if (get_rac(c, state + 0))
+        return 0;
+    else {
+        int i, e, a;
+        e = 0;
+        while (get_rac(c, state + 1 + FFMIN(e, 9))) // 1..10
+            e++;
+
+        a = 1;
+        for (i = e - 1; i >= 0; i--)
+            a += a + get_rac(c, state + 22 + FFMIN(i, 9));  // 22..31
+
+        e = -(is_signed && get_rac(c, state + 11 + FFMIN(e, 10))); // 11..21
+        return (a ^ e) - e;
+    }
+}
+
+static av_noinline int get_symbol(RangeCoder *c, uint8_t *state, int is_signed)
+{
+    return get_symbol_inline(c, state, is_signed);
+}
+
+static inline int get_vlc_symbol(GetBitContext *gb, VlcState *const state,
+                                 int bits)
+{
+    int k, i, v, ret;
+
+    i = state->count;
+    k = 0;
+    while (i < state->error_sum) { // FIXME: optimize
+        k++;
+        i += i;
+    }
+
+    v = get_sr_golomb(gb, k, 12, bits);
+    av_dlog(NULL, "v:%d bias:%d error:%d drift:%d count:%d k:%d",
+            v, state->bias, state->error_sum, state->drift, state->count, k);
+
+#if 0 // JPEG LS
+    if (k == 0 && 2 * state->drift <= -state->count)
+        v ^= (-1);
+#else
+    v ^= ((2 * state->drift + state->count) >> 31);
+#endif
+
+    ret = fold(v + state->bias, bits);
+
+    update_vlc_state(state, v);
+
+    return ret;
+}
+
+static av_always_inline void decode_line(FFV1Context *s, int w,
+                                         int16_t *sample[2],
+                                         int plane_index, int bits)
+{
+    PlaneContext *const p = &s->plane[plane_index];
+    RangeCoder *const c   = &s->c;
+    int x;
+    int run_count = 0;
+    int run_mode  = 0;
+    int run_index = s->run_index;
+
+    for (x = 0; x < w; x++) {
+        int diff, context, sign;
+
+        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);
+        } else {
+            if (context == 0 && run_mode == 0)
+                run_mode = 1;
+
+            if (run_mode) {
+                if (run_count == 0 && run_mode == 1) {
+                    if (get_bits1(&s->gb)) {
+                        run_count = 1 << ff_log2_run[run_index];
+                        if (x + run_count <= w)
+                            run_index++;
+                    } else {
+                        if (ff_log2_run[run_index])
+                            run_count = get_bits(&s->gb, ff_log2_run[run_index]);
+                        else
+                            run_count = 0;
+                        if (run_index)
+                            run_index--;
+                        run_mode = 2;
+                    }
+                }
+                run_count--;
+                if (run_count < 0) {
+                    run_mode  = 0;
+                    run_count = 0;
+                    diff      = get_vlc_symbol(&s->gb, &p->vlc_state[context],
+                                               bits);
+                    if (diff >= 0)
+                        diff++;
+                } else
+                    diff = 0;
+            } else
+                diff = get_vlc_symbol(&s->gb, &p->vlc_state[context], bits);
+
+            av_dlog(s->avctx, "count:%d index:%d, mode:%d, x:%d pos:%d\n",
+                    run_count, run_index, run_mode, x, get_bits_count(&s->gb));
+        }
+
+        if (sign)
+            diff = -diff;
+
+        sample[1][x] = (predict(sample[1] + x, sample[0] + x) + diff) &
+                       ((1 << bits) - 1);
+    }
+    s->run_index = run_index;
+}
+
+static void decode_plane(FFV1Context *s, uint8_t *src,
+                         int w, int h, int stride, int plane_index)
+{
+    int x, y;
+    int16_t *sample[2];
+    sample[0] = s->sample_buffer + 3;
+    sample[1] = s->sample_buffer + w + 6 + 3;
+
+    s->run_index = 0;
+
+    memset(s->sample_buffer, 0, 2 * (w + 6) * sizeof(*s->sample_buffer));
+
+    for (y = 0; y < h; y++) {
+        int16_t *temp = sample[0]; // FIXME: try a normal buffer
+
+        sample[0] = sample[1];
+        sample[1] = temp;
+
+        sample[1][-1] = sample[0][0];
+        sample[0][w]  = sample[0][w - 1];
+
+// { START_TIMER
+        if (s->avctx->bits_per_raw_sample <= 8) {
+            decode_line(s, w, sample, plane_index, 8);
+            for (x = 0; x < w; x++)
+                src[x + stride * y] = sample[1][x];
+        } else {
+            decode_line(s, w, sample, plane_index, s->avctx->bits_per_raw_sample);
+            if (s->packed_at_lsb) {
+                for (x = 0; x < w; x++) {
+                    ((uint16_t*)(src + stride*y))[x] = sample[1][x];
+                }
+            } else {
+                for (x = 0; x < w; x++) {
+                    ((uint16_t*)(src + stride*y))[x] = sample[1][x] << (16 - s->avctx->bits_per_raw_sample);
+                }
+            }
+        }
+// STOP_TIMER("decode-line") }
+    }
+}
+
+static void decode_rgb_frame(FFV1Context *s, uint8_t *src[3], int w, int h, int stride[3])
+{
+    int x, y, p;
+    int16_t *sample[4][2];
+    int lbd    = s->avctx->bits_per_raw_sample <= 8;
+    int bits   = s->avctx->bits_per_raw_sample > 0 ? s->avctx->bits_per_raw_sample : 8;
+    int offset = 1 << bits;
+
+    for (x = 0; x < 4; x++) {
+        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(s->sample_buffer, 0, 8 * (w + 6) * sizeof(*s->sample_buffer));
+
+    for (y = 0; y < h; y++) {
+        for (p = 0; p < 3 + s->transparency; p++) {
+            int16_t *temp = sample[p][0]; // FIXME: try a normal buffer
+
+            sample[p][0] = sample[p][1];
+            sample[p][1] = temp;
+
+            sample[p][1][-1]= sample[p][0][0  ];
+            sample[p][0][ w]= sample[p][0][w-1];
+            if (lbd)
+                decode_line(s, w, sample[p], (p + 1)/2, 9);
+            else
+                decode_line(s, w, sample[p], (p + 1)/2, bits + 1);
+        }
+        for (x = 0; x < w; x++) {
+            int g = sample[0][1][x];
+            int b = sample[1][1][x];
+            int r = sample[2][1][x];
+            int a = sample[3][1][x];
+
+            b -= offset;
+            r -= offset;
+            g -= (b + r) >> 2;
+            b += g;
+            r += g;
+
+            if (lbd)
+                *((uint32_t*)(src[0] + x*4 + stride[0]*y)) = b + (g<<8) + (r<<16) + (a<<24);
+            else {
+                *((uint16_t*)(src[0] + x*2 + stride[0]*y)) = b;
+                *((uint16_t*)(src[1] + x*2 + stride[1]*y)) = g;
+                *((uint16_t*)(src[2] + x*2 + stride[2]*y)) = r;
+            }
+        }
+    }
+}
+
+static int decode_slice_header(FFV1Context *f, FFV1Context *fs)
+{
+    RangeCoder *c = &fs->c;
+    uint8_t state[CONTEXT_SIZE];
+    unsigned ps, i, context_count;
+    memset(state, 128, sizeof(state));
+
+    av_assert0(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;
+
+    for (i = 0; i < f->plane_count; i++) {
+        PlaneContext * const p = &fs->plane[i];
+        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];
+
+        if (p->context_count < context_count) {
+            av_freep(&p->state);
+            av_freep(&p->vlc_state);
+        }
+        p->context_count = context_count;
+    }
+
+    ps = get_symbol(c, state, 0);
+    if (ps == 1) {
+        f->picture.interlaced_frame = 1;
+        f->picture.top_field_first  = 1;
+    } else if (ps == 2) {
+        f->picture.interlaced_frame = 1;
+        f->picture.top_field_first  = 0;
+    } else if (ps == 3) {
+        f->picture.interlaced_frame = 0;
+    }
+    f->picture.sample_aspect_ratio.num = get_symbol(c, state, 0);
+    f->picture.sample_aspect_ratio.den = get_symbol(c, state, 0);
+
+    return 0;
+}
+
+static int decode_slice(AVCodecContext *c, void *arg)
+{
+    FFV1Context *fs   = *(void **)arg;
+    FFV1Context *f    = fs->avctx->priv_data;
+    int width, height, x, y, ret;
+    const int ps      = av_pix_fmt_desc_get(c->pix_fmt)->comp[0].step_minus1 + 1;
+    AVFrame * const p = &f->picture;
+
+    if (f->version > 2) {
+        if (ffv1_init_slice_state(f, fs) < 0)
+            return AVERROR(ENOMEM);
+        if (decode_slice_header(f, fs) < 0) {
+            fs->slice_damaged = 1;
+            return AVERROR_INVALIDDATA;
+        }
+    }
+    if ((ret = ffv1_init_slice_state(f, fs)) < 0)
+        return ret;
+    if (f->picture.key_frame)
+        ffv1_clear_slice_state(f, fs);
+
+    width  = fs->slice_width;
+    height = fs->slice_height;
+    x      = fs->slice_x;
+    y      = fs->slice_y;
+
+    if (!fs->ac) {
+        if (f->version == 3 && f->minor_version > 1 || f->version > 3)
+            get_rac(&fs->c, (uint8_t[]) { 129 });
+        fs->ac_byte_count = f->version > 2 || (!x && !y) ? fs->c.bytestream - fs->c.bytestream_start - 1 : 0;
+        init_get_bits(&fs->gb,
+                      fs->c.bytestream_start + fs->ac_byte_count,
+                      (fs->c.bytestream_end - fs->c.bytestream_start - fs->ac_byte_count) * 8);
+    }
+
+    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] + ps*x + y*p->linesize[0], width, height, p->linesize[0], 0);
+
+        if (f->chroma_planes) {
+            decode_plane(fs, p->data[1] + ps*cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);
+            decode_plane(fs, p->data[2] + ps*cx+cy*p->linesize[2], chroma_width, chroma_height, p->linesize[2], 1);
+        }
+        if (fs->transparency)
+            decode_plane(fs, p->data[3] + ps*x + y*p->linesize[3], width, height, p->linesize[3], 2);
+    } else {
+        uint8_t *planes[3] = { p->data[0] + ps * x + y * p->linesize[0],
+                               p->data[1] + ps * x + y * p->linesize[1],
+                               p->data[2] + ps * x + y * p->linesize[2] };
+        decode_rgb_frame(fs, planes, width, height, p->linesize);
+    }
+    if (fs->ac && f->version > 2) {
+        int v;
+        get_rac(&fs->c, (uint8_t[]) { 129 });
+        v = fs->c.bytestream_end - fs->c.bytestream - 2 - 5*f->ec;
+        if (v) {
+            av_log(f->avctx, AV_LOG_ERROR, "bytestream end mismatching by %d\n", v);
+            fs->slice_damaged = 1;
+        }
+    }
+
+    emms_c();
+
+    return 0;
+}
+
+static int read_quant_table(RangeCoder *c, int16_t *quant_table, int scale)
+{
+    int v;
+    int i = 0;
+    uint8_t state[CONTEXT_SIZE];
+
+    memset(state, 128, sizeof(state));
+
+    for (v = 0; i < 128; v++) {
+        unsigned len = get_symbol(c, state, 0) + 1;
+
+        if (len > 128 - i)
+            return AVERROR_INVALIDDATA;
+
+        while (len--) {
+            quant_table[i] = scale * v;
+            i++;
+        }
+    }
+
+    for (i = 1; i < 128; i++)
+        quant_table[256 - i] = -quant_table[i];
+    quant_table[128] = -quant_table[127];
+
+    return 2 * v - 1;
+}
+
+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 AVERROR_INVALIDDATA;
+        }
+    }
+    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, ret;
+    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);
+    if (f->version > 2) {
+        c->bytestream_end -= 4;
+        f->minor_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
+    f->avctx->bits_per_raw_sample = get_symbol(c, state, 0);
+    f->chroma_planes              = get_rac(c, state);
+    f->chroma_h_shift             = get_symbol(c, state, 0);
+    f->chroma_v_shift             = get_symbol(c, state, 0);
+    f->transparency               = get_rac(c, state);
+    f->plane_count                = 2 + f->transparency;
+    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_h_slices ||
+        f->num_v_slices > (unsigned)f->height || !f->num_v_slices
+       ) {
+        av_log(f->avctx, AV_LOG_ERROR, "slice count invalid\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    f->quant_table_count = get_symbol(c, state, 0);
+    if (f->quant_table_count > (unsigned)MAX_QUANT_TABLES)
+        return AVERROR_INVALIDDATA;
+
+    for (i = 0; i < f->quant_table_count; i++) {
+        f->context_count[i] = read_quant_tables(c, f->quant_tables[i]);
+        if (f->context_count[i] < 0) {
+            av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
+            return AVERROR_INVALIDDATA;
+        }
+    }
+    if ((ret = ffv1_allocate_initial_states(f)) < 0)
+        return ret;
+
+    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;
+                }
+        }
+
+    if (f->version > 2) {
+        f->ec = get_symbol(c, state, 0);
+    }
+
+    if (f->version > 2) {
+        unsigned v;
+        v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0,
+                   f->avctx->extradata, f->avctx->extradata_size);
+        if (v) {
+            av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!\n", v);
+            return AVERROR_INVALIDDATA;
+        }
+    }
+
+    return 0;
+}
+
+static int read_header(FFV1Context *f)
+{
+    uint8_t state[CONTEXT_SIZE];
+    int i, j, context_count = -1; //-1 to avoid warning
+    RangeCoder *const c = &f->slice_context[0]->c;
+
+    memset(state, 128, sizeof(state));
+
+    if (f->version < 2) {
+        unsigned v= get_symbol(c, state, 0);
+        if (v >= 2) {
+            av_log(f->avctx, AV_LOG_ERROR, "invalid version %d in ver01 header\n", v);
+            return AVERROR_INVALIDDATA;
+        }
+        f->version = v;
+        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);
+
+        f->chroma_planes  = get_rac(c, state);
+        f->chroma_h_shift = get_symbol(c, state, 0);
+        f->chroma_v_shift = get_symbol(c, state, 0);
+        f->transparency   = get_rac(c, state);
+        f->plane_count    = 2 + f->transparency;
+    }
+
+    if (f->colorspace == 0) {
+        if (!f->transparency && !f->chroma_planes) {
+            if (f->avctx->bits_per_raw_sample <= 8)
+                f->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
+            else
+                f->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
+        } else if (f->avctx->bits_per_raw_sample<=8 && !f->transparency) {
+            switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
+            case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P; break;
+            case 0x01: f->avctx->pix_fmt = AV_PIX_FMT_YUV440P; break;
+            case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P; break;
+            case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P; break;
+            case 0x20: f->avctx->pix_fmt = AV_PIX_FMT_YUV411P; break;
+            case 0x22: f->avctx->pix_fmt = AV_PIX_FMT_YUV410P; break;
+            default:
+                av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
+                return AVERROR(ENOSYS);
+            }
+        } else if (f->avctx->bits_per_raw_sample <= 8 && f->transparency) {
+            switch(16*f->chroma_h_shift + f->chroma_v_shift) {
+            case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUVA444P; break;
+            case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUVA422P; break;
+            case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUVA420P; break;
+            default:
+                av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
+                return AVERROR(ENOSYS);
+            }
+        } else if (f->avctx->bits_per_raw_sample == 9) {
+            f->packed_at_lsb = 1;
+            switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
+            case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P9; break;
+            case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P9; break;
+            case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P9; break;
+            default:
+                av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
+                return AVERROR(ENOSYS);
+            }
+        } else if (f->avctx->bits_per_raw_sample == 10) {
+            f->packed_at_lsb = 1;
+            switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
+            case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P10; break;
+            case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P10; break;
+            case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P10; break;
+            default:
+                av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
+                return AVERROR(ENOSYS);
+            }
+        } else {
+            switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
+            case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P16; break;
+            case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P16; break;
+            case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P16; break;
+            default:
+                av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
+                return AVERROR(ENOSYS);
+            }
+        }
+    } else if (f->colorspace == 1) {
+        if (f->chroma_h_shift || f->chroma_v_shift) {
+            av_log(f->avctx, AV_LOG_ERROR,
+                   "chroma subsampling not supported in this colorspace\n");
+            return AVERROR(ENOSYS);
+        }
+        if (     f->avctx->bits_per_raw_sample ==  9)
+            f->avctx->pix_fmt = AV_PIX_FMT_GBRP9;
+        else if (f->avctx->bits_per_raw_sample == 10)
+            f->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
+        else if (f->avctx->bits_per_raw_sample == 12)
+            f->avctx->pix_fmt = AV_PIX_FMT_GBRP12;
+        else if (f->avctx->bits_per_raw_sample == 14)
+            f->avctx->pix_fmt = AV_PIX_FMT_GBRP14;
+        else
+        if (f->transparency) f->avctx->pix_fmt = AV_PIX_FMT_RGB32;
+        else                 f->avctx->pix_fmt = AV_PIX_FMT_0RGB32;
+    } else {
+        av_log(f->avctx, AV_LOG_ERROR, "colorspace not supported\n");
+        return AVERROR(ENOSYS);
+    }
+
+    av_dlog(f->avctx, "%d %d %d\n",
+            f->chroma_h_shift, f->chroma_v_shift, f->avctx->pix_fmt);
+    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 AVERROR_INVALIDDATA;
+        }
+    } else if (f->version < 3) {
+        f->slice_count = get_symbol(c, state, 0);
+    } else {
+        const uint8_t *p = c->bytestream_end;
+        for (f->slice_count = 0;
+             f->slice_count < MAX_SLICES && 3 < p - c->bytestream_start;
+             f->slice_count++) {
+            int trailer = 3 + 5*!!f->ec;
+            int size = AV_RB24(p-trailer);
+            if (size + trailer > p - c->bytestream_start)
+                break;
+            p -= size + trailer;
+        }
+    }
+    if (f->slice_count > (unsigned)MAX_SLICES || f->slice_count <= 0) {
+        av_log(f->avctx, AV_LOG_ERROR, "slice count %d is invalid\n", f->slice_count);
+        return AVERROR_INVALIDDATA;
+    }
+
+    for (j = 0; j < f->slice_count; j++) {
+        FFV1Context *fs = f->slice_context[j];
+        fs->ac            = f->ac;
+        fs->packed_at_lsb = f->packed_at_lsb;
+
+        fs->slice_damaged = 0;
+
+        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 AVERROR_INVALIDDATA;
+            if (   (unsigned)fs->slice_x + (uint64_t)fs->slice_width  > f->width
+                || (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
+                return AVERROR_INVALIDDATA;
+        }
+
+        for (i = 0; i < f->plane_count; i++) {
+            PlaneContext *const p = &fs->plane[i];
+
+            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 AVERROR_INVALIDDATA;
+                }
+                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 (f->version <= 2) {
+                av_assert0(context_count >= 0);
+                if (p->context_count < context_count) {
+                    av_freep(&p->state);
+                    av_freep(&p->vlc_state);
+                }
+                p->context_count = context_count;
+            }
+        }
+    }
+    return 0;
+}
+
+static av_cold int decode_init(AVCodecContext *avctx)
+{
+    FFV1Context *f = avctx->priv_data;
+    int ret;
+
+    if ((ret = ffv1_common_init(avctx)) < 0)
+        return ret;
+
+    if (avctx->extradata && (ret = read_extra_header(f)) < 0)
+        return ret;
+
+    if ((ret = ffv1_init_slice_contexts(f)) < 0)
+        return ret;
+
+    return 0;
+}
+
+static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
+{
+    const uint8_t *buf  = avpkt->data;
+    int buf_size        = avpkt->size;
+    FFV1Context *f      = avctx->priv_data;
+    RangeCoder *const c = &f->slice_context[0]->c;
+    AVFrame *const p    = &f->picture;
+    int i, ret;
+    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);
+
+    p->pict_type = AV_PICTURE_TYPE_I; //FIXME I vs. P
+    if (get_rac(c, &keystate)) {
+        p->key_frame    = 1;
+        f->key_frame_ok = 0;
+        if ((ret = read_header(f)) < 0)
+            return ret;
+        f->key_frame_ok = 1;
+    } else {
+        if (!f->key_frame_ok) {
+            av_log(avctx, AV_LOG_ERROR,
+                   "Cant decode non keyframe without valid keyframe\n");
+            return AVERROR_INVALIDDATA;
+        }
+        p->key_frame = 0;
+    }
+
+    p->reference = 3; //for error concealment
+    if ((ret = avctx->get_buffer(avctx, p)) < 0) {
+        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+        return ret;
+    }
+
+    if (avctx->debug & FF_DEBUG_PICT_INFO)
+        av_log(avctx, AV_LOG_DEBUG, "ver:%d keyframe:%d coder:%d ec:%d slices:%d bps:%d\n",
+               f->version, p->key_frame, f->ac, f->ec, f->slice_count, f->avctx->bits_per_raw_sample);
+
+    buf_p = buf + buf_size;
+    for (i = f->slice_count - 1; i >= 0; i--) {
+        FFV1Context *fs = f->slice_context[i];
+        int trailer = 3 + 5*!!f->ec;
+        int v;
+
+        if (i || f->version > 2) v = AV_RB24(buf_p-trailer) + trailer;
+        else                     v = buf_p - c->bytestream_start;
+        if (buf_p - c->bytestream_start < v) {
+            av_log(avctx, AV_LOG_ERROR, "Slice pointer chain broken\n");
+            return AVERROR_INVALIDDATA;
+        }
+        buf_p -= v;
+
+        if (f->ec) {
+            unsigned crc = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, buf_p, v);
+            if (crc) {
+                int64_t ts = avpkt->pts != AV_NOPTS_VALUE ? avpkt->pts : avpkt->dts;
+                av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!", crc);
+                if (ts != AV_NOPTS_VALUE && avctx->pkt_timebase.num) {
+                    av_log(f->avctx, AV_LOG_ERROR, "at %f seconds\n", ts*av_q2d(avctx->pkt_timebase));
+                } else if (ts != AV_NOPTS_VALUE) {
+                    av_log(f->avctx, AV_LOG_ERROR, "at %"PRId64"\n", ts);
+                } else {
+                    av_log(f->avctx, AV_LOG_ERROR, "\n");
+                }
+                fs->slice_damaged = 1;
+            }
+        }
+
+        if (i) {
+            ff_init_range_decoder(&fs->c, buf_p, v);
+        } else
+            fs->c.bytestream_end = (uint8_t *)(buf_p + v);
+    }
+
+    avctx->execute(avctx,
+                   decode_slice,
+                   &f->slice_context[0],
+                   NULL,
+                   f->slice_count,
+                   sizeof(void*));
+
+    for (i = f->slice_count - 1; i >= 0; i--) {
+        FFV1Context *fs = f->slice_context[i];
+        int j;
+        if (fs->slice_damaged && f->last_picture.data[0]) {
+            const uint8_t *src[4];
+            uint8_t *dst[4];
+            for (j = 0; j < 4; j++) {
+                int sh = (j==1 || j==2) ? f->chroma_h_shift : 0;
+                int sv = (j==1 || j==2) ? f->chroma_v_shift : 0;
+                dst[j] = f->picture     .data[j] + f->picture     .linesize[j]*
+                         (fs->slice_y>>sv) + (fs->slice_x>>sh);
+                src[j] = f->last_picture.data[j] + f->last_picture.linesize[j]*
+                         (fs->slice_y>>sv) + (fs->slice_x>>sh);
+            }
+            av_image_copy(dst,
+                          f->picture.linesize,
+                          (const uint8_t **)src,
+                          f->last_picture.linesize,
+                          avctx->pix_fmt,
+                          fs->slice_width,
+                          fs->slice_height);
+        }
+    }
+
+    f->picture_number++;
+
+    *picture   = *p;
+    *data_size = sizeof(AVFrame);
+
+    FFSWAP(AVFrame, f->picture, f->last_picture);
+
+    return buf_size;
+}
+
+AVCodec ff_ffv1_decoder = {
+    .name           = "ffv1",
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = AV_CODEC_ID_FFV1,
+    .priv_data_size = sizeof(FFV1Context),
+    .init           = decode_init,
+    .close          = ffv1_close,
+    .decode         = decode_frame,
+    .capabilities   = CODEC_CAP_DR1 /*| CODEC_CAP_DRAW_HORIZ_BAND*/ |
+                      CODEC_CAP_SLICE_THREADS,
+    .long_name      = NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"),
+};
diff --git a/libavcodec/ffv1enc.c b/libavcodec/ffv1enc.c
new file mode 100644
index 0000000..b3879fc
--- /dev/null
+++ b/libavcodec/ffv1enc.c
@@ -0,0 +1,1156 @@
+/*
+ * FFV1 encoder
+ *
+ * Copyright (c) 2003-2012 Michael Niedermayer <michaelni@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
+ * FF Video Codec 1 (a lossless codec) encoder
+ */
+
+#include "libavutil/avassert.h"
+#include "libavutil/crc.h"
+#include "libavutil/opt.h"
+#include "libavutil/imgutils.h"
+#include "libavutil/pixdesc.h"
+#include "libavutil/timer.h"
+#include "avcodec.h"
+#include "internal.h"
+#include "get_bits.h"
+#include "dsputil.h"
+#include "rangecoder.h"
+#include "golomb.h"
+#include "mathops.h"
+#include "ffv1.h"
+
+static const int8_t quant5_10bit[256] = {
+     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,  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,  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,  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, -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, -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, -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, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0,
+};
+
+static const int8_t quant5[256] = {
+     0,  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,  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,  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,  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,  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, -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, -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, -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, -2, -1, -1, -1,
+};
+
+static const int8_t quant9_10bit[256] = {
+     0,  0,  0,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  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,  4,  4,  4,  4,  4,  4,  4,  4,
+     4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,
+     4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,
+     4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,
+     4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,
+    -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4,
+    -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4,
+    -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4,
+    -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4,
+    -4, -4, -4, -4, -4, -4, -4, -4, -4, -3, -3, -3, -3, -3, -3, -3,
+    -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -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, -1, -1, -1, -1, -1, -1, -1, -1, -0, -0, -0, -0,
+};
+
+static const int8_t quant11[256] = {
+     0,  1,  2,  2,  2,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,  4,
+     4,  4,  4,  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,  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,  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, -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, -4, -4,
+    -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4,
+    -4, -4, -4, -4, -4, -3, -3, -3, -3, -3, -3, -3, -2, -2, -2, -1,
+};
+
+static const uint8_t ver2_state[256] = {
+      0,  10,  10,  10,  10,  16,  16,  16, 28,   16,  16,  29,  42,  49,  20,  49,
+     59,  25,  26,  26,  27,  31,  33,  33, 33,   34,  34,  37,  67,  38,  39,  39,
+     40,  40,  41,  79,  43,  44,  45,  45, 48,   48,  64,  50,  51,  52,  88,  52,
+     53,  74,  55,  57,  58,  58,  74,  60, 101,  61,  62,  84,  66,  66,  68,  69,
+     87,  82,  71,  97,  73,  73,  82,  75, 111,  77,  94,  78,  87,  81,  83,  97,
+     85,  83,  94,  86,  99,  89,  90,  99, 111,  92,  93,  134, 95,  98,  105, 98,
+    105, 110, 102, 108, 102, 118, 103, 106, 106, 113, 109, 112, 114, 112, 116, 125,
+    115, 116, 117, 117, 126, 119, 125, 121, 121, 123, 145, 124, 126, 131, 127, 129,
+    165, 130, 132, 138, 133, 135, 145, 136, 137, 139, 146, 141, 143, 142, 144, 148,
+    147, 155, 151, 149, 151, 150, 152, 157, 153, 154, 156, 168, 158, 162, 161, 160,
+    172, 163, 169, 164, 166, 184, 167, 170, 177, 174, 171, 173, 182, 176, 180, 178,
+    175, 189, 179, 181, 186, 183, 192, 185, 200, 187, 191, 188, 190, 197, 193, 196,
+    197, 194, 195, 196, 198, 202, 199, 201, 210, 203, 207, 204, 205, 206, 208, 214,
+    209, 211, 221, 212, 213, 215, 224, 216, 217, 218, 219, 220, 222, 228, 223, 225,
+    226, 224, 227, 229, 240, 230, 231, 232, 233, 234, 235, 236, 238, 239, 237, 242,
+    241, 243, 242, 244, 245, 246, 247, 248, 249, 250, 251, 252, 252, 253, 254, 255,
+};
+
+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 = 1; 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);
+        put_rac(c, state + 0, 0);
+        if (e <= 9) {
+            for (i = 0; i < e; i++)
+                put_rac(c, state + 1 + i, 1);  // 1..10
+            put_rac(c, state + 1 + i, 0);
+
+            for (i = e - 1; i >= 0; i--)
+                put_rac(c, state + 22 + i, (a >> i) & 1);  // 22..31
+
+            if (is_signed)
+                put_rac(c, state + 11 + e, v < 0);  // 11..21
+        } else {
+            for (i = 0; i < e; i++)
+                put_rac(c, state + 1 + FFMIN(i, 9), 1);  // 1..10
+            put_rac(c, state + 1 + 9, 0);
+
+            for (i = e - 1; i >= 0; i--)
+                put_rac(c, state + 22 + FFMIN(i, 9), (a >> i) & 1);  // 22..31
+
+            if (is_signed)
+                put_rac(c, state + 11 + 10, v < 0);  // 11..21
+        }
+    } else {
+        put_rac(c, state + 0, 1);
+    }
+#undef put_rac
+}
+
+static av_noinline void put_symbol(RangeCoder *c, uint8_t *state,
+                                   int v, int is_signed)
+{
+    put_symbol_inline(c, state, v, is_signed, NULL, NULL);
+}
+
+
+static inline void put_vlc_symbol(PutBitContext *pb, VlcState *const state,
+                                  int v, int bits)
+{
+    int i, k, code;
+    v = fold(v - state->bias, bits);
+
+    i = state->count;
+    k = 0;
+    while (i < state->error_sum) { // FIXME: optimize
+        k++;
+        i += i;
+    }
+
+    av_assert2(k <= 13);
+
+#if 0 // JPEG LS
+    if (k == 0 && 2 * state->drift <= -state->count)
+        code = v ^ (-1);
+    else
+        code = v;
+#else
+    code = v ^ ((2 * state->drift + state->count) >> 31);
+#endif
+
+    av_dlog(NULL, "v:%d/%d bias:%d error:%d drift:%d count:%d k:%d\n", v, code,
+            state->bias, state->error_sum, state->drift, state->count, k);
+    set_sr_golomb(pb, code, k, 12, bits);
+
+    update_vlc_state(state, v);
+}
+
+static av_always_inline int encode_line(FFV1Context *s, int w,
+                                        int16_t *sample[3],
+                                        int plane_index, int bits)
+{
+    PlaneContext *const p = &s->plane[plane_index];
+    RangeCoder *const c   = &s->c;
+    int x;
+    int run_index = s->run_index;
+    int run_count = 0;
+    int run_mode  = 0;
+
+    if (s->ac) {
+        if (c->bytestream_end - c->bytestream < w * 20) {
+            av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
+            return AVERROR_INVALIDDATA;
+        }
+    } else {
+        if (s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb) >> 3) < w * 4) {
+            av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
+            return AVERROR_INVALIDDATA;
+        }
+    }
+
+    for (x = 0; x < w; x++) {
+        int diff, context;
+
+        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) {
+            context = -context;
+            diff    = -diff;
+        }
+
+        diff = fold(diff, bits);
+
+        if (s->ac) {
+            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;
+
+            if (run_mode) {
+                if (diff) {
+                    while (run_count >= 1 << ff_log2_run[run_index]) {
+                        run_count -= 1 << ff_log2_run[run_index];
+                        run_index++;
+                        put_bits(&s->pb, 1, 1);
+                    }
+
+                    put_bits(&s->pb, 1 + ff_log2_run[run_index], run_count);
+                    if (run_index)
+                        run_index--;
+                    run_count = 0;
+                    run_mode  = 0;
+                    if (diff > 0)
+                        diff--;
+                } else {
+                    run_count++;
+                }
+            }
+
+            av_dlog(s->avctx, "count:%d index:%d, mode:%d, x:%d pos:%d\n",
+                    run_count, run_index, run_mode, x,
+                    (int)put_bits_count(&s->pb));
+
+            if (run_mode == 0)
+                put_vlc_symbol(&s->pb, &p->vlc_state[context], diff, bits);
+        }
+    }
+    if (run_mode) {
+        while (run_count >= 1 << ff_log2_run[run_index]) {
+            run_count -= 1 << ff_log2_run[run_index];
+            run_index++;
+            put_bits(&s->pb, 1, 1);
+        }
+
+        if (run_count)
+            put_bits(&s->pb, 1, 1);
+    }
+    s->run_index = run_index;
+
+    return 0;
+}
+
+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;
+    int16_t *sample[3];
+    s->run_index = 0;
+
+    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] = s->sample_buffer + (w + 6) * ((h + i - y) % ring_size) + 3;
+
+        sample[0][-1]= sample[1][0  ];
+        sample[1][ w]= sample[1][w-1];
+// { START_TIMER
+        if (s->bits_per_raw_sample <= 8) {
+            for (x = 0; x < w; x++)
+                sample[0][x] = src[x + stride * y];
+            encode_line(s, w, sample, plane_index, 8);
+        } else {
+            if (s->packed_at_lsb) {
+                for (x = 0; x < w; x++) {
+                    sample[0][x] = ((uint16_t*)(src + stride*y))[x];
+                }
+            } else {
+                for (x = 0; x < w; x++) {
+                    sample[0][x] = ((uint16_t*)(src + stride*y))[x] >> (16 - s->bits_per_raw_sample);
+                }
+            }
+            encode_line(s, w, sample, plane_index, s->bits_per_raw_sample);
+        }
+// STOP_TIMER("encode line") }
+    }
+}
+
+static void encode_rgb_frame(FFV1Context *s, uint8_t *src[3], int w, int h, int stride[3])
+{
+    int x, y, p, i;
+    const int ring_size = s->avctx->context_model ? 3 : 2;
+    int16_t *sample[4][3];
+    int lbd    = s->avctx->bits_per_raw_sample <= 8;
+    int bits   = s->avctx->bits_per_raw_sample > 0 ? s->avctx->bits_per_raw_sample : 8;
+    int offset = 1 << bits;
+
+    s->run_index = 0;
+
+    memset(s->sample_buffer, 0, ring_size * MAX_PLANES *
+                                (w + 6) * sizeof(*s->sample_buffer));
+
+    for (y = 0; y < h; y++) {
+        for (i = 0; i < ring_size; i++)
+            for (p = 0; p < MAX_PLANES; p++)
+                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 b, g, r, av_uninit(a);
+            if (lbd) {
+                unsigned v = *((uint32_t*)(src[0] + x*4 + stride[0]*y));
+                b =  v        & 0xFF;
+                g = (v >>  8) & 0xFF;
+                r = (v >> 16) & 0xFF;
+                a =  v >> 24;
+            } else {
+                b = *((uint16_t*)(src[0] + x*2 + stride[0]*y));
+                g = *((uint16_t*)(src[1] + x*2 + stride[1]*y));
+                r = *((uint16_t*)(src[2] + x*2 + stride[2]*y));
+            }
+
+            b -= g;
+            r -= g;
+            g += (b + r) >> 2;
+            b += offset;
+            r += offset;
+
+            sample[0][0][x] = g;
+            sample[1][0][x] = b;
+            sample[2][0][x] = r;
+            sample[3][0][x] = a;
+        }
+        for (p = 0; p < 3 + s->transparency; p++) {
+            sample[p][0][-1] = sample[p][1][0  ];
+            sample[p][1][ w] = sample[p][1][w-1];
+            if (lbd)
+                encode_line(s, w, sample[p], (p + 1) / 2, 9);
+            else
+                encode_line(s, w, sample[p], (p + 1) / 2, bits + 1);
+        }
+    }
+}
+
+static void write_quant_table(RangeCoder *c, int16_t *quant_table)
+{
+    int last = 0;
+    int i;
+    uint8_t state[CONTEXT_SIZE];
+    memset(state, 128, sizeof(state));
+
+    for (i = 1; i < 128; i++)
+        if (quant_table[i] != quant_table[i - 1]) {
+            put_symbol(c, state, i - last - 1, 0);
+            last = i;
+        }
+    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, j;
+    RangeCoder *const c = &f->slice_context[0]->c;
+
+    memset(state, 128, sizeof(state));
+
+    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->bits_per_raw_sample, 0);
+        put_rac(c, state, f->chroma_planes);
+        put_symbol(c, state, f->chroma_h_shift, 0);
+        put_symbol(c, state, f->chroma_v_shift, 0);
+        put_rac(c, state, f->transparency);
+
+        write_quant_tables(c, f->quant_table);
+    } else if (f->version < 3) {
+        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);
+            }
+        }
+    }
+}
+
+static int write_extradata(FFV1Context *f)
+{
+    RangeCoder *const c = &f->c;
+    uint8_t state[CONTEXT_SIZE];
+    int i, j, k;
+    uint8_t state2[32][CONTEXT_SIZE];
+    unsigned v;
+
+    memset(state2, 128, sizeof(state2));
+    memset(state, 128, sizeof(state));
+
+    f->avctx->extradata_size = 10000 + 4 +
+                                    (11 * 11 * 5 * 5 * 5 + 11 * 11 * 11) * 32;
+    f->avctx->extradata = av_malloc(f->avctx->extradata_size);
+    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);
+    if (f->version > 2) {
+        if (f->version == 3)
+            f->minor_version = 2;
+        put_symbol(c, state, f->minor_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->bits_per_raw_sample, 0);
+    put_rac(c, state, f->chroma_planes);
+    put_symbol(c, state, f->chroma_h_shift, 0);
+    put_symbol(c, state, f->chroma_v_shift, 0);
+    put_rac(c, state, f->transparency);
+    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);
+        }
+    }
+
+    if (f->version > 2) {
+        put_symbol(c, state, f->ec, 0);
+    }
+
+    f->avctx->extradata_size = ff_rac_terminate(c);
+    v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, f->avctx->extradata, f->avctx->extradata_size);
+    AV_WL32(f->avctx->extradata + f->avctx->extradata_size, v);
+    f->avctx->extradata_size += 4;
+
+    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 (size0 - sizeX > size0*(1e-14) && 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;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
+    int i, j, k, m, ret;
+
+    ffv1_common_init(avctx);
+
+    s->version = 0;
+
+    if ((avctx->flags & (CODEC_FLAG_PASS1|CODEC_FLAG_PASS2)) || avctx->slices>1)
+        s->version = FFMAX(s->version, 2);
+
+    if (avctx->level == 3) {
+        s->version = 3;
+    }
+
+    if (s->ec < 0) {
+        s->ec = (s->version >= 3);
+    }
+
+    if (s->version >= 2 && avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
+        av_log(avctx, AV_LOG_ERROR, "Version 2 needed for requested features but version 2 is experimental and not enabled\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    s->ac = avctx->coder_type > 0 ? 2 : 0;
+
+    s->plane_count = 3;
+    switch(avctx->pix_fmt) {
+    case AV_PIX_FMT_YUV444P9:
+    case AV_PIX_FMT_YUV422P9:
+    case AV_PIX_FMT_YUV420P9:
+        if (!avctx->bits_per_raw_sample)
+            s->bits_per_raw_sample = 9;
+    case AV_PIX_FMT_YUV444P10:
+    case AV_PIX_FMT_YUV420P10:
+    case AV_PIX_FMT_YUV422P10:
+        s->packed_at_lsb = 1;
+        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
+            s->bits_per_raw_sample = 10;
+    case AV_PIX_FMT_GRAY16:
+    case AV_PIX_FMT_YUV444P16:
+    case AV_PIX_FMT_YUV422P16:
+    case AV_PIX_FMT_YUV420P16:
+        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample) {
+            s->bits_per_raw_sample = 16;
+        } else if (!s->bits_per_raw_sample) {
+            s->bits_per_raw_sample = avctx->bits_per_raw_sample;
+        }
+        if (s->bits_per_raw_sample <= 8) {
+            av_log(avctx, AV_LOG_ERROR, "bits_per_raw_sample invalid\n");
+            return AVERROR_INVALIDDATA;
+        }
+        if (!s->ac && avctx->coder_type == -1) {
+            av_log(avctx, AV_LOG_INFO, "bits_per_raw_sample > 8, forcing coder 1\n");
+            s->ac = 2;
+        }
+        if (!s->ac) {
+            av_log(avctx, AV_LOG_ERROR, "bits_per_raw_sample of more than 8 needs -coder 1 currently\n");
+            return AVERROR(ENOSYS);
+        }
+        s->version = FFMAX(s->version, 1);
+    case AV_PIX_FMT_GRAY8:
+    case AV_PIX_FMT_YUV444P:
+    case AV_PIX_FMT_YUV440P:
+    case AV_PIX_FMT_YUV422P:
+    case AV_PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUV411P:
+    case AV_PIX_FMT_YUV410P:
+        s->chroma_planes = desc->nb_components < 3 ? 0 : 1;
+        s->colorspace = 0;
+        break;
+    case AV_PIX_FMT_YUVA444P:
+    case AV_PIX_FMT_YUVA422P:
+    case AV_PIX_FMT_YUVA420P:
+        s->chroma_planes = 1;
+        s->colorspace = 0;
+        s->transparency = 1;
+        break;
+    case AV_PIX_FMT_RGB32:
+        s->colorspace = 1;
+        s->transparency = 1;
+        break;
+    case AV_PIX_FMT_0RGB32:
+        s->colorspace = 1;
+        break;
+    case AV_PIX_FMT_GBRP9:
+        if (!avctx->bits_per_raw_sample)
+            s->bits_per_raw_sample = 9;
+    case AV_PIX_FMT_GBRP10:
+        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
+            s->bits_per_raw_sample = 10;
+    case AV_PIX_FMT_GBRP12:
+        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
+            s->bits_per_raw_sample = 12;
+    case AV_PIX_FMT_GBRP14:
+        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
+            s->bits_per_raw_sample = 14;
+        else if (!s->bits_per_raw_sample)
+            s->bits_per_raw_sample = avctx->bits_per_raw_sample;
+        s->colorspace = 1;
+        s->chroma_planes = 1;
+        s->version = FFMAX(s->version, 1);
+        break;
+    default:
+        av_log(avctx, AV_LOG_ERROR, "format not supported\n");
+        return AVERROR(ENOSYS);
+    }
+    if (s->transparency) {
+        av_log(avctx, AV_LOG_WARNING, "Storing alpha plane, this will require a recent FFV1 decoder to playback!\n");
+    }
+    if (avctx->context_model > 1U) {
+        av_log(avctx, AV_LOG_ERROR, "Invalid context model %d, valid values are 0 and 1\n", avctx->context_model);
+        return AVERROR(EINVAL);
+    }
+
+    if (s->ac > 1)
+        for (i = 1; i < 256; i++)
+            s->state_transition[i] = ver2_state[i];
+
+    for (i = 0; i < 256; i++) {
+        s->quant_table_count = 2;
+        if (s->bits_per_raw_sample <= 8) {
+            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_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];
+
+        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 ((ret = ffv1_allocate_initial_states(s)) < 0)
+        return ret;
+
+    avctx->coded_frame = &s->picture;
+    if (!s->transparency)
+        s->plane_count = 2;
+    avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_h_shift, &s->chroma_v_shift);
+    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 AVERROR_INVALIDDATA;
+                    }
+                    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 AVERROR_INVALIDDATA;
+                            }
+                            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 AVERROR_INVALIDDATA;
+            }
+            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) {
+        for (s->num_v_slices = 2; s->num_v_slices < 9; s->num_v_slices++) {
+            for (s->num_h_slices = s->num_v_slices; s->num_h_slices < 2*s->num_v_slices; s->num_h_slices++) {
+                if (avctx->slices == s->num_h_slices * s->num_v_slices && avctx->slices <= 64 || !avctx->slices)
+                    goto slices_ok;
+            }
+        }
+        av_log(avctx, AV_LOG_ERROR,
+               "Unsupported number %d of slices requested, please specify a "
+               "supported number with -slices (ex:4,6,9,12,16, ...)\n",
+               avctx->slices);
+        return AVERROR(ENOSYS);
+slices_ok:
+        write_extradata(s);
+    }
+
+    if ((ret = ffv1_init_slice_contexts(s)) < 0)
+        return ret;
+    if ((ret = ffv1_init_slices_state(s)) < 0)
+        return ret;
+
+#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;
+}
+
+static void encode_slice_header(FFV1Context *f, FFV1Context *fs)
+{
+    RangeCoder *c = &fs->c;
+    uint8_t state[CONTEXT_SIZE];
+    int j;
+    memset(state, 128, sizeof(state));
+
+    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);
+    }
+    if (!f->picture.interlaced_frame)
+        put_symbol(c, state, 3, 0);
+    else
+        put_symbol(c, state, 1 + !f->picture.top_field_first, 0);
+    put_symbol(c, state, f->picture.sample_aspect_ratio.num, 0);
+    put_symbol(c, state, f->picture.sample_aspect_ratio.den, 0);
+}
+
+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;
+    const int ps     = av_pix_fmt_desc_get(c->pix_fmt)->comp[0].step_minus1 + 1;
+
+    if (p->key_frame)
+        ffv1_clear_slice_state(f, fs);
+    if (f->version > 2) {
+        encode_slice_header(f, fs);
+    }
+    if (!fs->ac) {
+        if (f->version > 2)
+            put_rac(&fs->c, (uint8_t[]) { 129 }, 0);
+        fs->ac_byte_count = f->version > 2 || (!x && !y) ? ff_rac_terminate(&fs->c) : 0;
+        init_put_bits(&fs->pb,
+                      fs->c.bytestream_start + fs->ac_byte_count,
+                      fs->c.bytestream_end - fs->c.bytestream_start - fs->ac_byte_count);
+    }
+
+    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] + ps*x + y*p->linesize[0], width, height, p->linesize[0], 0);
+
+        if (f->chroma_planes) {
+            encode_plane(fs, p->data[1] + ps*cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);
+            encode_plane(fs, p->data[2] + ps*cx+cy*p->linesize[2], chroma_width, chroma_height, p->linesize[2], 1);
+        }
+        if (fs->transparency)
+            encode_plane(fs, p->data[3] + ps*x + y*p->linesize[3], width, height, p->linesize[3], 2);
+    } else {
+        uint8_t *planes[3] = {p->data[0] + ps*x + y*p->linesize[0],
+                              p->data[1] + ps*x + y*p->linesize[1],
+                              p->data[2] + ps*x + y*p->linesize[2]};
+        encode_rgb_frame(fs, planes, width, height, p->linesize);
+    }
+    emms_c();
+
+    return 0;
+}
+
+static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
+                        const AVFrame *pict, int *got_packet)
+{
+    FFV1Context *f      = avctx->priv_data;
+    RangeCoder *const c = &f->slice_context[0]->c;
+    AVFrame *const p    = &f->picture;
+    int used_count      = 0;
+    uint8_t keystate    = 128;
+    uint8_t *buf_p;
+    int i, ret;
+
+    if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*((8*2+1+1)*4)/8
+                                            + FF_MIN_BUFFER_SIZE)) < 0)
+        return ret;
+
+    ff_init_range_encoder(c, pkt->data, pkt->size);
+    ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
+
+    *p           = *pict;
+    p->pict_type = AV_PICTURE_TYPE_I;
+
+    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);
+    } else {
+        put_rac(c, &keystate, 0);
+        p->key_frame = 0;
+    }
+
+    if (f->ac > 1) {
+        int i;
+        for (i = 1; i < 256; i++) {
+            c->one_state[i]        = f->state_transition[i];
+            c->zero_state[256 - i] = 256 - c->one_state[i];
+        }
+    }
+
+    for (i = 1; i < f->slice_count; i++) {
+        FFV1Context *fs = f->slice_context[i];
+        uint8_t *start  = pkt->data + (pkt->size - used_count) * (int64_t)i / f->slice_count;
+        int len         = pkt->size / f->slice_count;
+        ff_init_range_encoder(&fs->c, start, len);
+    }
+    avctx->execute(avctx, encode_slice, &f->slice_context[0], NULL,
+                   f->slice_count, sizeof(void *));
+
+    buf_p = pkt->data;
+    for (i = 0; i < f->slice_count; i++) {
+        FFV1Context *fs = f->slice_context[i];
+        int bytes;
+
+        if (fs->ac) {
+            uint8_t state = 129;
+            put_rac(&fs->c, &state, 0);
+            bytes = ff_rac_terminate(&fs->c);
+        } else {
+            flush_put_bits(&fs->pb); // FIXME: nicer padding
+            bytes = fs->ac_byte_count + (put_bits_count(&fs->pb) + 7) / 8;
+        }
+        if (i > 0 || f->version > 2) {
+            av_assert0(bytes < pkt->size / f->slice_count);
+            memmove(buf_p, fs->c.bytestream_start, bytes);
+            av_assert0(bytes < (1 << 24));
+            AV_WB24(buf_p + bytes, bytes);
+            bytes += 3;
+        }
+        if (f->ec) {
+            unsigned v;
+            buf_p[bytes++] = 0;
+            v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, buf_p, bytes);
+            AV_WL32(buf_p + bytes, v);
+            bytes += 4;
+        }
+        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++;
+    pkt->size   = buf_p - pkt->data;
+    pkt->flags |= AV_PKT_FLAG_KEY * p->key_frame;
+    *got_packet = 1;
+
+    return 0;
+}
+
+#define OFFSET(x) offsetof(FFV1Context, x)
+#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
+static const AVOption options[] = {
+    { "slicecrc", "Protect slices with CRCs", OFFSET(ec), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE },
+    { NULL }
+};
+
+static const AVClass class = {
+    .class_name = "ffv1 encoder",
+    .item_name  = av_default_item_name,
+    .option     = options,
+    .version    = LIBAVUTIL_VERSION_INT,
+};
+
+static const AVCodecDefault ffv1_defaults[] = {
+    { "coder", "-1" },
+    { NULL },
+};
+
+AVCodec ff_ffv1_encoder = {
+    .name           = "ffv1",
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = AV_CODEC_ID_FFV1,
+    .priv_data_size = sizeof(FFV1Context),
+    .init           = encode_init,
+    .encode2        = encode_frame,
+    .close          = ffv1_close,
+    .capabilities   = CODEC_CAP_SLICE_THREADS,
+    .pix_fmts       = (const enum AVPixelFormat[]) {
+        AV_PIX_FMT_YUV420P,   AV_PIX_FMT_YUVA420P,  AV_PIX_FMT_YUVA422P,  AV_PIX_FMT_YUV444P,
+        AV_PIX_FMT_YUVA444P,  AV_PIX_FMT_YUV440P,   AV_PIX_FMT_YUV422P,   AV_PIX_FMT_YUV411P,
+        AV_PIX_FMT_YUV410P,   AV_PIX_FMT_0RGB32,    AV_PIX_FMT_RGB32,     AV_PIX_FMT_YUV420P16,
+        AV_PIX_FMT_YUV422P16, AV_PIX_FMT_YUV444P16, AV_PIX_FMT_YUV444P9,  AV_PIX_FMT_YUV422P9,
+        AV_PIX_FMT_YUV420P9,  AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV444P10,
+        AV_PIX_FMT_GRAY16,    AV_PIX_FMT_GRAY8,     AV_PIX_FMT_GBRP9,     AV_PIX_FMT_GBRP10,
+        AV_PIX_FMT_GBRP12,    AV_PIX_FMT_GBRP14,
+        AV_PIX_FMT_NONE
+
+    },
+    .long_name      = NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"),
+    .defaults       = ffv1_defaults,
+    .priv_class     = &class,
+};
diff --git a/libavcodec/flac.c b/libavcodec/flac.c
index b07e4f8..3b803fe 100644
--- a/libavcodec/flac.c
+++ b/libavcodec/flac.c
@@ -19,6 +19,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/crc.h"
 #include "libavutil/log.h"
 #include "bytestream.h"
@@ -28,6 +29,15 @@
 
 static const int8_t sample_size_table[] = { 0, 8, 12, 0, 16, 20, 24, 0 };
 
+static const int64_t flac_channel_layouts[6] = {
+    AV_CH_LAYOUT_MONO,
+    AV_CH_LAYOUT_STEREO,
+    AV_CH_LAYOUT_SURROUND,
+    AV_CH_LAYOUT_QUAD,
+    AV_CH_LAYOUT_5POINT0,
+    AV_CH_LAYOUT_5POINT1
+};
+
 static int64_t get_utf8(GetBitContext *gb)
 {
     int64_t val;
@@ -181,6 +191,14 @@
     return 1;
 }
 
+void ff_flac_set_channel_layout(AVCodecContext *avctx)
+{
+    if (avctx->channels <= FF_ARRAY_ELEMS(flac_channel_layouts))
+        avctx->channel_layout = flac_channel_layouts[avctx->channels - 1];
+    else
+        avctx->channel_layout = 0;
+}
+
 void avpriv_flac_parse_streaminfo(AVCodecContext *avctx, struct FLACStreaminfo *s,
                               const uint8_t *buffer)
 {
@@ -205,6 +223,7 @@
     avctx->channels = s->channels;
     avctx->sample_rate = s->samplerate;
     avctx->bits_per_raw_sample = s->bps;
+    ff_flac_set_channel_layout(avctx);
 
     s->samples = get_bits_longlong(&gb, 36);
 
diff --git a/libavcodec/flac.h b/libavcodec/flac.h
index 94444f8..13e863b 100644
--- a/libavcodec/flac.h
+++ b/libavcodec/flac.h
@@ -137,4 +137,7 @@
  */
 int ff_flac_decode_frame_header(AVCodecContext *avctx, GetBitContext *gb,
                                 FLACFrameInfo *fi, int log_level_offset);
+
+void ff_flac_set_channel_layout(AVCodecContext *avctx);
+
 #endif /* AVCODEC_FLAC_H */
diff --git a/libavcodec/flac_parser.c b/libavcodec/flac_parser.c
index e37ca64..7d3c5c4 100644
--- a/libavcodec/flac_parser.c
+++ b/libavcodec/flac_parser.c
@@ -459,6 +459,7 @@
 
     fpc->avctx->sample_rate = header->fi.samplerate;
     fpc->avctx->channels    = header->fi.channels;
+    ff_flac_set_channel_layout(fpc->avctx);
     fpc->pc->duration       = header->fi.blocksize;
     *poutbuf = flac_fifo_read_wrap(fpc, header->offset, *poutbuf_size,
                                         &fpc->wrap_buf,
@@ -541,14 +542,18 @@
         av_freep(&fpc->best_header);
     }
 
-    /* Find and score new headers. */
-    while ((buf && read_end < buf + buf_size &&
+    /* Find and score new headers.                                     */
+    /* buf_size is to zero when padding, so check for this since we do */
+    /* not want to try to read more input once we have found the end.  */
+    /* Note that as (non-modified) parameters, buf can be non-NULL,    */
+    /* while buf_size is 0.                                            */
+    while ((buf && buf_size && read_end < buf + buf_size &&
             fpc->nb_headers_buffered < FLAC_MIN_HEADERS)
-           || (!buf && !fpc->end_padded)) {
+           || ((!buf || !buf_size) && !fpc->end_padded)) {
         int start_offset;
 
         /* Pad the end once if EOF, to check the final region for headers. */
-        if (!buf) {
+        if (!buf || !buf_size) {
             fpc->end_padded      = 1;
             buf_size = MAX_FRAME_HEADER_SIZE;
             read_end = read_start + MAX_FRAME_HEADER_SIZE;
@@ -569,7 +574,7 @@
             goto handle_error;
         }
 
-        if (buf) {
+        if (buf && buf_size) {
             av_fifo_generic_write(fpc->fifo_buf, (void*) read_start,
                                   read_end - read_start, NULL);
         } else {
diff --git a/libavcodec/flacdec.c b/libavcodec/flacdec.c
index 61c30e8..317d7fa 100644
--- a/libavcodec/flacdec.c
+++ b/libavcodec/flacdec.c
@@ -33,8 +33,8 @@
 
 #include <limits.h>
 
-#include "libavutil/audioconvert.h"
 #include "libavutil/avassert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/crc.h"
 #include "avcodec.h"
 #include "internal.h"
@@ -58,20 +58,13 @@
     int got_streaminfo;                     ///< indicates if the STREAMINFO has been read
 
     int32_t *decoded[FLAC_MAX_CHANNELS];    ///< decoded samples
+    uint8_t *decoded_buffer;
+    unsigned int decoded_buffer_size;
 
     FLACDSPContext dsp;
 } FLACContext;
 
-static const int64_t flac_channel_layouts[6] = {
-    AV_CH_LAYOUT_MONO,
-    AV_CH_LAYOUT_STEREO,
-    AV_CH_LAYOUT_SURROUND,
-    AV_CH_LAYOUT_QUAD,
-    AV_CH_LAYOUT_5POINT0,
-    AV_CH_LAYOUT_5POINT1
-};
-
-static void allocate_buffers(FLACContext *s);
+static int allocate_buffers(FLACContext *s);
 
 static void flac_set_bps(FLACContext *s)
 {
@@ -99,6 +92,7 @@
 {
     enum FLACExtradataFormat format;
     uint8_t *streaminfo;
+    int ret;
     FLACContext *s = avctx->priv_data;
     s->avctx = avctx;
 
@@ -112,7 +106,9 @@
 
     /* initialize based on the demuxer-supplied streamdata header */
     avpriv_flac_parse_streaminfo(avctx, (FLACStreaminfo *)s, streaminfo);
-    allocate_buffers(s);
+    ret = allocate_buffers(s);
+    if (ret < 0)
+        return ret;
     flac_set_bps(s);
     ff_flacdsp_init(&s->dsp, avctx->sample_fmt, s->bps);
     s->got_streaminfo = 1;
@@ -120,9 +116,6 @@
     avcodec_get_frame_defaults(&s->frame);
     avctx->coded_frame = &s->frame;
 
-    if (avctx->channels <= FF_ARRAY_ELEMS(flac_channel_layouts))
-        avctx->channel_layout = flac_channel_layouts[avctx->channels - 1];
-
     return 0;
 }
 
@@ -135,15 +128,24 @@
     av_log(avctx, AV_LOG_DEBUG, "  Bits: %d\n", s->bps);
 }
 
-static void allocate_buffers(FLACContext *s)
+static int allocate_buffers(FLACContext *s)
 {
-    int i;
+    int buf_size;
 
     av_assert0(s->max_blocksize);
 
-    for (i = 0; i < s->channels; i++) {
-        s->decoded[i] = av_malloc(sizeof(int32_t)*s->max_blocksize);
-    }
+    buf_size = av_samples_get_buffer_size(NULL, s->channels, s->max_blocksize,
+                                          AV_SAMPLE_FMT_S32P, 0);
+    if (buf_size < 0)
+        return buf_size;
+
+    av_fast_malloc(&s->decoded_buffer, &s->decoded_buffer_size, buf_size);
+    if (!s->decoded_buffer)
+        return AVERROR(ENOMEM);
+
+    return av_samples_fill_arrays((uint8_t **)s->decoded, NULL,
+                                  s->decoded_buffer, s->channels,
+                                  s->max_blocksize, AV_SAMPLE_FMT_S32P, 0);
 }
 
 /**
@@ -155,7 +157,7 @@
  */
 static int parse_streaminfo(FLACContext *s, const uint8_t *buf, int buf_size)
 {
-    int metadata_type, metadata_size;
+    int metadata_type, metadata_size, ret;
 
     if (buf_size < FLAC_STREAMINFO_SIZE+8) {
         /* need more data */
@@ -167,7 +169,9 @@
         return AVERROR_INVALIDDATA;
     }
     avpriv_flac_parse_streaminfo(s->avctx, (FLACStreaminfo *)s, &buf[8]);
-    allocate_buffers(s);
+    ret = allocate_buffers(s);
+    if (ret < 0)
+        return ret;
     flac_set_bps(s);
     ff_flacdsp_init(&s->dsp, s->avctx->sample_fmt, s->bps);
     s->got_streaminfo = 1;
@@ -369,8 +373,8 @@
         bps -= wasted;
     }
     if (bps > 32) {
-        av_log_missing_feature(s->avctx, "decorrelated bit depth > 32", 0);
-        return -1;
+        av_log_missing_feature(s->avctx, "Decorrelated bit depth > 32", 0);
+        return AVERROR_PATCHWELCOME;
     }
 
 //FIXME use av_log2 for types
@@ -403,7 +407,7 @@
 
 static int decode_frame(FLACContext *s)
 {
-    int i;
+    int i, ret;
     GetBitContext *gb = &s->gb;
     FLACFrameInfo fi;
 
@@ -412,12 +416,15 @@
         return -1;
     }
 
-    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;
+    if (s->channels && fi.channels != s->channels && s->got_streaminfo) {
+        s->channels = s->avctx->channels = fi.channels;
+        ff_flac_set_channel_layout(s->avctx);
+        ret = allocate_buffers(s);
+        if (ret < 0)
+            return ret;
     }
     s->channels = s->avctx->channels = fi.channels;
+    ff_flac_set_channel_layout(s->avctx);
     s->ch_mode = fi.ch_mode;
 
     if (!s->bps && !fi.bps) {
@@ -451,16 +458,14 @@
                                         " or frame header\n");
         return -1;
     }
-    if (fi.samplerate == 0) {
+    if (fi.samplerate == 0)
         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);
+        ret = allocate_buffers(s);
+        if (ret < 0)
+            return ret;
         ff_flacdsp_init(&s->dsp, s->avctx->sample_fmt, s->bps);
         s->got_streaminfo = 1;
         dump_headers(s->avctx, (FLACStreaminfo *)s);
@@ -550,11 +555,8 @@
 static av_cold int flac_decode_close(AVCodecContext *avctx)
 {
     FLACContext *s = avctx->priv_data;
-    int i;
 
-    for (i = 0; i < s->channels; i++) {
-        av_freep(&s->decoded[i]);
-    }
+    av_freep(&s->decoded_buffer);
 
     return 0;
 }
@@ -573,5 +575,5 @@
                                                       AV_SAMPLE_FMT_S16P,
                                                       AV_SAMPLE_FMT_S32,
                                                       AV_SAMPLE_FMT_S32P,
-                                                      -1 },
+                                                      AV_SAMPLE_FMT_NONE },
 };
diff --git a/libavcodec/flacdsp.c b/libavcodec/flacdsp.c
index e51a91a..02eba3e 100644
--- a/libavcodec/flacdsp.c
+++ b/libavcodec/flacdsp.c
@@ -26,6 +26,7 @@
 #define SAMPLE_SIZE 16
 #define PLANAR 0
 #include "flacdsp_template.c"
+#include "flacdsp_lpc_template.c"
 
 #undef  PLANAR
 #define PLANAR 1
@@ -36,6 +37,7 @@
 #define SAMPLE_SIZE 32
 #define PLANAR 0
 #include "flacdsp_template.c"
+#include "flacdsp_lpc_template.c"
 
 #undef  PLANAR
 #define PLANAR 1
@@ -86,10 +88,13 @@
 av_cold void ff_flacdsp_init(FLACDSPContext *c, enum AVSampleFormat fmt,
                              int bps)
 {
-    if (bps > 16)
+    if (bps > 16) {
         c->lpc            = flac_lpc_32_c;
-    else
+        c->lpc_encode     = flac_lpc_encode_c_32;
+    } else {
         c->lpc            = flac_lpc_16_c;
+        c->lpc_encode     = flac_lpc_encode_c_16;
+    }
 
     switch (fmt) {
     case AV_SAMPLE_FMT_S32:
diff --git a/libavcodec/flacdsp.h b/libavcodec/flacdsp.h
index 00be265..5e66dc2 100644
--- a/libavcodec/flacdsp.h
+++ b/libavcodec/flacdsp.h
@@ -27,6 +27,8 @@
                            int len, int shift);
     void (*lpc)(int32_t *samples, const int coeffs[32], int order,
                 int qlevel, int len);
+    void (*lpc_encode)(int32_t *res, const int32_t *smp, int len, int order,
+                       const int32_t *coefs, int shift);
 } FLACDSPContext;
 
 void ff_flacdsp_init(FLACDSPContext *c, enum AVSampleFormat fmt, int bps);
diff --git a/libavcodec/flacdsp_lpc_template.c b/libavcodec/flacdsp_lpc_template.c
new file mode 100644
index 0000000..0c453ae
--- /dev/null
+++ b/libavcodec/flacdsp_lpc_template.c
@@ -0,0 +1,141 @@
+/*
+ * 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 <stdint.h>
+#include "libavutil/avutil.h"
+#include "mathops.h"
+
+#undef FUNC
+#undef sum_type
+#undef MUL
+#undef CLIP
+#undef FSUF
+
+#define FUNC(n) AV_JOIN(n ## _, SAMPLE_SIZE)
+
+#if SAMPLE_SIZE == 32
+#   define sum_type  int64_t
+#   define MUL(a, b) MUL64(a, b)
+#   define CLIP(x) av_clipl_int32(x)
+#else
+#   define sum_type  int32_t
+#   define MUL(a, b) ((a) * (b))
+#   define CLIP(x) (x)
+#endif
+
+#define LPC1(x) {           \
+    int c = coefs[(x)-1];   \
+    p0   += MUL(c, s);      \
+    s     = smp[i-(x)+1];   \
+    p1   += MUL(c, s);      \
+}
+
+static av_always_inline void FUNC(lpc_encode_unrolled)(int32_t *res,
+                                  const int32_t *smp, int len, int order,
+                                  const int32_t *coefs, int shift, int big)
+{
+    int i;
+    for (i = order; i < len; i += 2) {
+        int s  = smp[i-order];
+        sum_type 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)
+            }
+        } 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)
+            }
+        }
+        res[i  ] = smp[i  ] - CLIP(p0 >> shift);
+        res[i+1] = smp[i+1] - CLIP(p1 >> shift);
+    }
+}
+
+static void FUNC(flac_lpc_encode_c)(int32_t *res, const int32_t *smp, int len,
+                                    int order, const int32_t *coefs, int shift)
+{
+    int i;
+    for (i = 0; i < order; i++)
+        res[i] = smp[i];
+#if CONFIG_SMALL
+    for (i = order; i < len; i += 2) {
+        int j;
+        int s  = smp[i];
+        sum_type p0 = 0, p1 = 0;
+        for (j = 0; j < order; j++) {
+            int c = coefs[j];
+            p1   += MUL(c, s);
+            s     = smp[i-j-1];
+            p0   += MUL(c, s);
+        }
+        res[i  ] = smp[i  ] - CLIP(p0 >> shift);
+        res[i+1] = smp[i+1] - CLIP(p1 >> shift);
+    }
+#else
+    switch (order) {
+    case  1: FUNC(lpc_encode_unrolled)(res, smp, len,     1, coefs, shift, 0); break;
+    case  2: FUNC(lpc_encode_unrolled)(res, smp, len,     2, coefs, shift, 0); break;
+    case  3: FUNC(lpc_encode_unrolled)(res, smp, len,     3, coefs, shift, 0); break;
+    case  4: FUNC(lpc_encode_unrolled)(res, smp, len,     4, coefs, shift, 0); break;
+    case  5: FUNC(lpc_encode_unrolled)(res, smp, len,     5, coefs, shift, 0); break;
+    case  6: FUNC(lpc_encode_unrolled)(res, smp, len,     6, coefs, shift, 0); break;
+    case  7: FUNC(lpc_encode_unrolled)(res, smp, len,     7, coefs, shift, 0); break;
+    case  8: FUNC(lpc_encode_unrolled)(res, smp, len,     8, coefs, shift, 0); break;
+    default: FUNC(lpc_encode_unrolled)(res, smp, len, order, coefs, shift, 1); break;
+    }
+#endif
+}
diff --git a/libavcodec/flacenc.c b/libavcodec/flacenc.c
index 070fb4d..a3c4e64 100644
--- a/libavcodec/flacenc.c
+++ b/libavcodec/flacenc.c
@@ -21,15 +21,18 @@
 
 #include "libavutil/avassert.h"
 #include "libavutil/crc.h"
+#include "libavutil/intmath.h"
 #include "libavutil/md5.h"
 #include "libavutil/opt.h"
 #include "avcodec.h"
+#include "dsputil.h"
 #include "get_bits.h"
 #include "golomb.h"
 #include "internal.h"
 #include "lpc.h"
 #include "flac.h"
 #include "flacdata.h"
+#include "flacdsp.h"
 
 #define FLAC_SUBFRAME_CONSTANT  0
 #define FLAC_SUBFRAME_VERBATIM  1
@@ -41,7 +44,11 @@
 #define MAX_PARTITIONS     (1 << MAX_PARTITION_ORDER)
 #define MAX_LPC_PRECISION  15
 #define MAX_LPC_SHIFT      15
-#define MAX_RICE_PARAM     14
+
+enum CodingMode {
+    CODING_MODE_RICE  = 4,
+    CODING_MODE_RICE2 = 5,
+};
 
 typedef struct CompressionOptions {
     int compression_level;
@@ -58,6 +65,7 @@
 } CompressionOptions;
 
 typedef struct RiceContext {
+    enum CodingMode coding_mode;
     int porder;
     int params[MAX_PARTITIONS];
 } RiceContext;
@@ -66,6 +74,7 @@
     int type;
     int type_code;
     int obits;
+    int wasted;
     int order;
     int32_t coefs[MAX_LPC_ORDER];
     int shift;
@@ -89,6 +98,7 @@
     int channels;
     int samplerate;
     int sr_code[2];
+    int bps_code;
     int max_blocksize;
     int min_framesize;
     int max_framesize;
@@ -101,6 +111,10 @@
     AVCodecContext *avctx;
     LPCContext lpc_ctx;
     struct AVMD5 *md5ctx;
+    uint8_t *md5_buffer;
+    unsigned int md5_buffer_size;
+    DSPContext dsp;
+    FLACDSPContext flac_dsp;
 } FlacEncodeContext;
 
 
@@ -121,7 +135,7 @@
     put_bits(&pb, 24, s->max_framesize);
     put_bits(&pb, 20, s->samplerate);
     put_bits(&pb, 3, s->channels-1);
-    put_bits(&pb, 5, 15);       /* bits per sample - 1 */
+    put_bits(&pb,  5, s->avctx->bits_per_raw_sample - 1);
     /* write 36-bit sample count in 2 put_bits() calls */
     put_bits(&pb, 24, (s->sample_count & 0xFFFFFF000LL) >> 12);
     put_bits(&pb, 12,  s->sample_count & 0x000000FFFLL);
@@ -221,8 +235,18 @@
 
     s->avctx = avctx;
 
-    if (avctx->sample_fmt != AV_SAMPLE_FMT_S16)
-        return -1;
+    switch (avctx->sample_fmt) {
+    case AV_SAMPLE_FMT_S16:
+        avctx->bits_per_raw_sample = 16;
+        s->bps_code                = 4;
+        break;
+    case AV_SAMPLE_FMT_S32:
+        if (avctx->bits_per_raw_sample != 24)
+            av_log(avctx, AV_LOG_WARNING, "encoding as 24 bits-per-sample\n");
+        avctx->bits_per_raw_sample = 24;
+        s->bps_code                = 6;
+        break;
+    }
 
     if (channels < 1 || channels > FLAC_MAX_CHANNELS)
         return -1;
@@ -352,10 +376,11 @@
 
     /* set maximum encoded frame size in verbatim mode */
     s->max_framesize = ff_flac_get_max_frame_size(s->avctx->frame_size,
-                                                  s->channels, 16);
+                                                  s->channels,
+                                                  s->avctx->bits_per_raw_sample);
 
     /* initialize MD5 context */
-    s->md5ctx = av_malloc(av_md5_size);
+    s->md5ctx = av_md5_alloc();
     if (!s->md5ctx)
         return AVERROR(ENOMEM);
     av_md5_init(s->md5ctx);
@@ -401,6 +426,10 @@
     ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
                       s->options.max_prediction_order, FF_LPC_TYPE_LEVINSON);
 
+    ff_dsputil_init(&s->dsp, avctx);
+    ff_flacdsp_init(&s->flac_dsp, avctx->sample_fmt,
+                    avctx->bits_per_raw_sample);
+
     dprint_compression_options(s);
 
     return ret;
@@ -433,8 +462,17 @@
         }
     }
 
-    for (ch = 0; ch < s->channels; ch++)
-        frame->subframes[ch].obits = 16;
+    for (ch = 0; ch < s->channels; ch++) {
+        FlacSubframe *sub = &frame->subframes[ch];
+
+        sub->wasted = 0;
+        sub->obits  = s->avctx->bits_per_raw_sample;
+
+        if (sub->obits > 16)
+            sub->rc.coding_mode = CODING_MODE_RICE2;
+        else
+            sub->rc.coding_mode = CODING_MODE_RICE;
+    }
 
     frame->verbatim_only = 0;
 }
@@ -443,22 +481,32 @@
 /**
  * Copy channel-interleaved input samples into separate subframes.
  */
-static void copy_samples(FlacEncodeContext *s, const int16_t *samples)
+static void copy_samples(FlacEncodeContext *s, const void *samples)
 {
     int i, j, ch;
     FlacFrame *frame;
+    int shift = av_get_bytes_per_sample(s->avctx->sample_fmt) * 8 -
+                s->avctx->bits_per_raw_sample;
 
-    frame = &s->frame;
-    for (i = 0, j = 0; i < frame->blocksize; i++)
-        for (ch = 0; ch < s->channels; ch++, j++)
-            frame->subframes[ch].samples[i] = samples[j];
+#define COPY_SAMPLES(bits) do {                                     \
+    const int ## bits ## _t *samples0 = samples;                    \
+    frame = &s->frame;                                              \
+    for (i = 0, j = 0; i < frame->blocksize; i++)                   \
+        for (ch = 0; ch < s->channels; ch++, j++)                   \
+            frame->subframes[ch].samples[i] = samples0[j] >> shift; \
+} while (0)
+
+    if (s->avctx->sample_fmt == AV_SAMPLE_FMT_S16)
+        COPY_SAMPLES(16);
+    else
+        COPY_SAMPLES(32);
 }
 
 
-static int rice_count_exact(int32_t *res, int n, int k)
+static uint64_t rice_count_exact(int32_t *res, int n, int k)
 {
     int i;
-    int count = 0;
+    uint64_t count = 0;
 
     for (i = 0; i < n; i++) {
         int32_t v = -2 * res[i] - 1;
@@ -469,12 +517,12 @@
 }
 
 
-static int subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub,
-                                int pred_order)
+static uint64_t subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub,
+                                     int pred_order)
 {
     int p, porder, psize;
     int i, part_end;
-    int count = 0;
+    uint64_t count = 0;
 
     /* subframe header */
     count += 8;
@@ -505,7 +553,7 @@
         part_end = psize;
         for (p = 0; p < 1 << porder; p++) {
             int k = sub->rc.params[p];
-            count += 4;
+            count += sub->rc.coding_mode;
             count += rice_count_exact(&sub->residual[i], part_end - i, k);
             i = part_end;
             part_end = FFMIN(s->frame.blocksize, part_end + psize);
@@ -521,32 +569,34 @@
 /**
  * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0.
  */
-static int find_optimal_param(uint32_t sum, int n)
+static int find_optimal_param(uint64_t sum, int n, int max_param)
 {
     int k;
-    uint32_t sum2;
+    uint64_t sum2;
 
     if (sum <= n >> 1)
         return 0;
     sum2 = sum - (n >> 1);
-    k    = av_log2(n < 256 ? FASTDIV(sum2, n) : sum2 / n);
-    return FFMIN(k, MAX_RICE_PARAM);
+    k    = av_log2(av_clipl_int32(sum2 / n));
+    return FFMIN(k, max_param);
 }
 
 
-static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
-                                         uint32_t *sums, int n, int pred_order)
+static uint64_t calc_optimal_rice_params(RiceContext *rc, int porder,
+                                         uint64_t *sums, int n, int pred_order)
 {
     int i;
-    int k, cnt, part;
-    uint32_t all_bits;
+    int k, cnt, part, max_param;
+    uint64_t all_bits;
+
+    max_param = (1 << rc->coding_mode) - 2;
 
     part     = (1 << porder);
     all_bits = 4 * part;
 
     cnt = (n >> porder) - pred_order;
     for (i = 0; i < part; i++) {
-        k = find_optimal_param(sums[i], cnt);
+        k = find_optimal_param(sums[i], cnt, max_param);
         rc->params[i] = k;
         all_bits += rice_encode_count(sums[i], cnt, k);
         cnt = n >> porder;
@@ -559,7 +609,7 @@
 
 
 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
-                      uint32_t sums[][MAX_PARTITIONS])
+                      uint64_t sums[][MAX_PARTITIONS])
 {
     int i, j;
     int parts;
@@ -570,7 +620,7 @@
     res     = &data[pred_order];
     res_end = &data[n >> pmax];
     for (i = 0; i < parts; i++) {
-        uint32_t sum = 0;
+        uint64_t sum = 0;
         while (res < res_end)
             sum += *(res++);
         sums[pmax][i] = sum;
@@ -585,20 +635,22 @@
 }
 
 
-static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
+static uint64_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
                                  int32_t *data, int n, int pred_order)
 {
     int i;
-    uint32_t bits[MAX_PARTITION_ORDER+1];
+    uint64_t bits[MAX_PARTITION_ORDER+1];
     int opt_porder;
     RiceContext tmp_rc;
     uint32_t *udata;
-    uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
+    uint64_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
 
     av_assert1(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
     av_assert1(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
     av_assert1(pmin <= pmax);
 
+    tmp_rc.coding_mode = rc->coding_mode;
+
     udata = av_malloc(n * sizeof(uint32_t));
     for (i = 0; i < n; i++)
         udata[i] = (2*data[i]) ^ (data[i]>>31);
@@ -629,7 +681,7 @@
 }
 
 
-static uint32_t find_subframe_rice_params(FlacEncodeContext *s,
+static uint64_t find_subframe_rice_params(FlacEncodeContext *s,
                                           FlacSubframe *sub, int pred_order)
 {
     int pmin = get_max_p_order(s->options.min_partition_order,
@@ -637,7 +689,7 @@
     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;
+    uint64_t bits = 8 + pred_order * sub->obits + 2 + sub->rc.coding_mode;
     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,
@@ -697,110 +749,6 @@
 }
 
 
-#define LPC1(x) {\
-    int c = coefs[(x)-1];\
-    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)
-{
-    int i;
-    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)
-            }
-        } 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)
-            }
-        }
-        res[i  ] = smp[i  ] - (p0 >> shift);
-        res[i+1] = smp[i+1] - (p1 >> shift);
-    }
-}
-
-
-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++)
-        res[i] = smp[i];
-#if CONFIG_SMALL
-    for (i = order; i < n; i += 2) {
-        int j;
-        int s  = smp[i];
-        int p0 = 0, p1 = 0;
-        for (j = 0; j < order; j++) {
-            int c = coefs[j];
-            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;
-    }
-#endif
-}
-
-
 static int encode_residual_ch(FlacEncodeContext *s, int ch)
 {
     int i, n;
@@ -842,7 +790,7 @@
     sub->type = FLAC_SUBFRAME_FIXED;
     if (s->options.lpc_type == FF_LPC_TYPE_NONE  ||
         s->options.lpc_type == FF_LPC_TYPE_FIXED || n <= max_order) {
-        uint32_t bits[MAX_FIXED_ORDER+1];
+        uint64_t bits[MAX_FIXED_ORDER+1];
         if (max_order > MAX_FIXED_ORDER)
             max_order = MAX_FIXED_ORDER;
         opt_order = 0;
@@ -873,16 +821,19 @@
         omethod == ORDER_METHOD_4LEVEL ||
         omethod == ORDER_METHOD_8LEVEL) {
         int levels = 1 << omethod;
-        uint32_t bits[1 << ORDER_METHOD_8LEVEL];
-        int order;
+        uint64_t bits[1 << ORDER_METHOD_8LEVEL];
+        int order       = -1;
         int opt_index   = levels-1;
         opt_order       = max_order-1;
         bits[opt_index] = UINT32_MAX;
         for (i = levels-1; i >= 0; i--) {
+            int last_order = order;
             order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
-            if (order < 0)
-                order = 0;
-            encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
+            order = av_clip(order, min_order - 1, max_order - 1);
+            if (order == last_order)
+                continue;
+            s->flac_dsp.lpc_encode(res, smp, n, order+1, coefs[order],
+                                   shift[order]);
             bits[i] = find_subframe_rice_params(s, sub, order+1);
             if (bits[i] < bits[opt_index]) {
                 opt_index = i;
@@ -892,18 +843,18 @@
         opt_order++;
     } else if (omethod == ORDER_METHOD_SEARCH) {
         // brute-force optimal order search
-        uint32_t bits[MAX_LPC_ORDER];
+        uint64_t bits[MAX_LPC_ORDER];
         opt_order = 0;
         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]);
+            s->flac_dsp.lpc_encode(res, smp, n, i+1, coefs[i], shift[i]);
             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) {
-        uint32_t bits[MAX_LPC_ORDER];
+        uint64_t bits[MAX_LPC_ORDER];
         int step;
 
         opt_order = min_order - 1 + (max_order-min_order)/3;
@@ -914,7 +865,7 @@
             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]);
+                s->flac_dsp.lpc_encode(res, smp, n, i+1, coefs[i], shift[i]);
                 bits[i] = find_subframe_rice_params(s, sub, i+1);
                 if (bits[i] < bits[opt_order])
                     opt_order = i;
@@ -929,7 +880,7 @@
     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);
+    s->flac_dsp.lpc_encode(res, smp, n, sub->order, sub->coefs, sub->shift);
 
     find_subframe_rice_params(s, sub, sub->order);
 
@@ -975,7 +926,8 @@
 
 static int encode_frame(FlacEncodeContext *s)
 {
-    int ch, count;
+    int ch;
+    uint64_t count;
 
     count = count_frame_header(s);
 
@@ -985,11 +937,47 @@
     count += (8 - (count & 7)) & 7; // byte alignment
     count += 16;                    // CRC-16
 
-    return count >> 3;
+    count >>= 3;
+    if (count > INT_MAX)
+        return AVERROR_BUG;
+    return count;
 }
 
 
-static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
+static void remove_wasted_bits(FlacEncodeContext *s)
+{
+    int ch, i;
+
+    for (ch = 0; ch < s->channels; ch++) {
+        FlacSubframe *sub = &s->frame.subframes[ch];
+        int32_t v         = 0;
+
+        for (i = 0; i < s->frame.blocksize; i++) {
+            v |= sub->samples[i];
+            if (v & 1)
+                break;
+        }
+
+        if (v && !(v & 1)) {
+            v = av_ctz(v);
+
+            for (i = 0; i < s->frame.blocksize; i++)
+                sub->samples[i] >>= v;
+
+            sub->wasted = v;
+            sub->obits -= v;
+
+            /* for 24-bit, check if removing wasted bits makes the range better
+               suited for using RICE instead of RICE2 for entropy coding */
+            if (sub->obits <= 17)
+                sub->rc.coding_mode = CODING_MODE_RICE;
+        }
+    }
+}
+
+
+static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n,
+                                int max_rice_param)
 {
     int i, best;
     int32_t lt, rt;
@@ -1009,7 +997,7 @@
     }
     /* estimate bit counts */
     for (i = 0; i < 4; i++) {
-        k      = find_optimal_param(2 * sum[i], n);
+        k      = find_optimal_param(2 * sum[i], n, max_rice_param);
         sum[i] = rice_encode_count( 2 * sum[i], n, k);
     }
 
@@ -1048,9 +1036,10 @@
         return;
     }
 
-    if (s->options.ch_mode < 0)
-        frame->ch_mode = estimate_stereo_mode(left, right, n);
-    else
+    if (s->options.ch_mode < 0) {
+        int max_rice_param = (1 << frame->subframes[0].rc.coding_mode) - 2;
+        frame->ch_mode = estimate_stereo_mode(left, right, n, max_rice_param);
+    } else
         frame->ch_mode = s->options.ch_mode;
 
     /* perform decorrelation and adjust bits-per-sample */
@@ -1099,7 +1088,7 @@
     else
         put_bits(&s->pb, 4, frame->ch_mode + FLAC_MAX_CHANNELS - 1);
 
-    put_bits(&s->pb, 3, 4); /* bits-per-sample code */
+    put_bits(&s->pb, 3, s->bps_code);
     put_bits(&s->pb, 1, 0);
     write_utf8(&s->pb, s->frame_count);
 
@@ -1134,7 +1123,9 @@
         /* subframe header */
         put_bits(&s->pb, 1, 0);
         put_bits(&s->pb, 6, sub->type_code);
-        put_bits(&s->pb, 1, 0); /* no wasted bits */
+        put_bits(&s->pb, 1, !!sub->wasted);
+        if (sub->wasted)
+            put_bits(&s->pb, sub->wasted, 1);
 
         /* subframe */
         if (sub->type == FLAC_SUBFRAME_CONSTANT) {
@@ -1157,7 +1148,7 @@
             }
 
             /* rice-encoded block */
-            put_bits(&s->pb, 2, 0);
+            put_bits(&s->pb, 2, sub->rc.coding_mode - 4);
 
             /* partition order */
             porder  = sub->rc.porder;
@@ -1168,7 +1159,7 @@
             part_end  = &sub->residual[psize];
             for (p = 0; p < 1 << porder; p++) {
                 int k = sub->rc.params[p];
-                put_bits(&s->pb, 4, k);
+                put_bits(&s->pb, sub->rc.coding_mode, k);
                 while (res < part_end)
                     set_sr_golomb_flac(&s->pb, *res++, k, INT32_MAX, 0);
                 part_end = FFMIN(frame_end, part_end + psize);
@@ -1199,17 +1190,41 @@
 }
 
 
-static void update_md5_sum(FlacEncodeContext *s, const int16_t *samples)
+static int update_md5_sum(FlacEncodeContext *s, const void *samples)
 {
-#if HAVE_BIGENDIAN
-    int 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);
+    const uint8_t *buf;
+    int buf_size = s->frame.blocksize * s->channels *
+                   ((s->avctx->bits_per_raw_sample + 7) / 8);
+
+    if (s->avctx->bits_per_raw_sample > 16 || HAVE_BIGENDIAN) {
+        av_fast_malloc(&s->md5_buffer, &s->md5_buffer_size, buf_size);
+        if (!s->md5_buffer)
+            return AVERROR(ENOMEM);
     }
-#else
-    av_md5_update(s->md5ctx, (const uint8_t *)samples, s->frame.blocksize*s->channels*2);
+
+    if (s->avctx->bits_per_raw_sample <= 16) {
+        buf = (const uint8_t *)samples;
+#if HAVE_BIGENDIAN
+        s->dsp.bswap16_buf((uint16_t *)s->md5_buffer,
+                           (const uint16_t *)samples, buf_size / 2);
+        buf = s->md5_buffer;
 #endif
+    } else {
+        int i;
+        const int32_t *samples0 = samples;
+        uint8_t *tmp            = s->md5_buffer;
+
+        for (i = 0; i < s->frame.blocksize * s->channels; i++) {
+            int32_t v = samples0[i] >> 8;
+            *tmp++    = (v      ) & 0xFF;
+            *tmp++    = (v >>  8) & 0xFF;
+            *tmp++    = (v >> 16) & 0xFF;
+        }
+        buf = s->md5_buffer;
+    }
+    av_md5_update(s->md5ctx, buf, buf_size);
+
+    return 0;
 }
 
 
@@ -1217,7 +1232,6 @@
                              const AVFrame *frame, int *got_packet_ptr)
 {
     FlacEncodeContext *s;
-    const int16_t *samples;
     int frame_bytes, out_bytes, ret;
 
     s = avctx->priv_data;
@@ -1229,27 +1243,33 @@
         write_streaminfo(s, avctx->extradata);
         return 0;
     }
-    samples = (const int16_t *)frame->data[0];
 
     /* change max_framesize for small final frame */
     if (frame->nb_samples < s->frame.blocksize) {
         s->max_framesize = ff_flac_get_max_frame_size(frame->nb_samples,
-                                                      s->channels, 16);
+                                                      s->channels,
+                                                      avctx->bits_per_raw_sample);
     }
 
     init_frame(s, frame->nb_samples);
 
-    copy_samples(s, samples);
+    copy_samples(s, frame->data[0]);
 
     channel_decorrelation(s);
 
+    remove_wasted_bits(s);
+
     frame_bytes = encode_frame(s);
 
     /* fallback to verbatim mode if the compressed frame is larger than it
        would be if encoded uncompressed. */
-    if (frame_bytes > s->max_framesize) {
+    if (frame_bytes < 0 || frame_bytes > s->max_framesize) {
         s->frame.verbatim_only = 1;
         frame_bytes = encode_frame(s);
+        if (frame_bytes < 0) {
+            av_log(avctx, AV_LOG_ERROR, "Bad frame count\n");
+            return frame_bytes;
+        }
     }
 
     if ((ret = ff_alloc_packet2(avctx, avpkt, frame_bytes)))
@@ -1259,7 +1279,10 @@
 
     s->frame_count++;
     s->sample_count += frame->nb_samples;
-    update_md5_sum(s, samples);
+    if ((ret = update_md5_sum(s, frame->data[0])) < 0) {
+        av_log(avctx, AV_LOG_ERROR, "Error updating MD5 checksum\n");
+        return ret;
+    }
     if (out_bytes > s->max_encoded_framesize)
         s->max_encoded_framesize = out_bytes;
     if (out_bytes < s->min_framesize)
@@ -1278,6 +1301,7 @@
     if (avctx->priv_data) {
         FlacEncodeContext *s = avctx->priv_data;
         av_freep(&s->md5ctx);
+        av_freep(&s->md5_buffer);
         ff_lpc_end(&s->lpc_ctx);
     }
     av_freep(&avctx->extradata);
@@ -1332,6 +1356,7 @@
     .close          = flac_encode_close,
     .capabilities   = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY | CODEC_CAP_LOSSLESS,
     .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
+                                                     AV_SAMPLE_FMT_S32,
                                                      AV_SAMPLE_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
     .priv_class     = &flac_encoder_class,
diff --git a/libavcodec/flashsv.c b/libavcodec/flashsv.c
index 1d94efd..533e9f0 100644
--- a/libavcodec/flashsv.c
+++ b/libavcodec/flashsv.c
@@ -45,7 +45,6 @@
 typedef struct BlockInfo {
     uint8_t *pos;
     int      size;
-    int      unp_size;
 } BlockInfo;
 
 typedef struct FlashSVContext {
@@ -114,7 +113,7 @@
         av_log(avctx, AV_LOG_ERROR, "Inflate init error: %d\n", zret);
         return 1;
     }
-    avctx->pix_fmt = PIX_FMT_BGR24;
+    avctx->pix_fmt = AV_PIX_FMT_BGR24;
     avcodec_get_frame_defaults(&s->frame);
     s->frame.data[0] = NULL;
 
@@ -122,10 +121,10 @@
 }
 
 
-static void flashsv2_prime(FlashSVContext *s, uint8_t *src,
-                           int size, int unp_size)
+static int flashsv2_prime(FlashSVContext *s, uint8_t *src, int size)
 {
     z_stream zs;
+    int zret; // Zlib return code
 
     zs.zalloc = NULL;
     zs.zfree  = NULL;
@@ -137,7 +136,8 @@
     s->zstream.avail_out = s->block_size * 3;
     inflate(&s->zstream, Z_SYNC_FLUSH);
 
-    deflateInit(&zs, 0);
+    if (deflateInit(&zs, 0) != Z_OK)
+        return -1;
     zs.next_in   = s->tmpblock;
     zs.avail_in  = s->block_size * 3 - s->zstream.avail_out;
     zs.next_out  = s->deflate_block;
@@ -145,13 +145,18 @@
     deflate(&zs, Z_SYNC_FLUSH);
     deflateEnd(&zs);
 
-    inflateReset(&s->zstream);
+    if ((zret = inflateReset(&s->zstream)) != Z_OK) {
+        av_log(s->avctx, AV_LOG_ERROR, "Inflate reset error: %d\n", zret);
+        return AVERROR_UNKNOWN;
+    }
 
     s->zstream.next_in   = s->deflate_block;
     s->zstream.avail_in  = s->deflate_block_size - zs.avail_out;
     s->zstream.next_out  = s->tmpblock;
     s->zstream.avail_out = s->block_size * 3;
     inflate(&s->zstream, Z_SYNC_FLUSH);
+
+    return 0;
 }
 
 static int flashsv_decode_block(AVCodecContext *avctx, AVPacket *avpkt,
@@ -164,11 +169,15 @@
     int k;
     int ret = inflateReset(&s->zstream);
     if (ret != Z_OK) {
-        //return -1;
+        av_log(avctx, AV_LOG_ERROR, "Inflate reset error: %d\n", ret);
+        return AVERROR_UNKNOWN;
     }
     if (s->zlibprime_curr || s->zlibprime_prev) {
-        flashsv2_prime(s, s->blocks[blk_idx].pos, s->blocks[blk_idx].size,
-                       s->blocks[blk_idx].unp_size);
+        ret = flashsv2_prime(s,
+                             s->blocks[blk_idx].pos,
+                             s->blocks[blk_idx].size);
+        if (ret < 0)
+            return ret;
     }
     s->zstream.next_in   = avpkt->data + get_bits_count(gb) / 8;
     s->zstream.avail_in  = block_size;
@@ -188,7 +197,6 @@
     if (s->is_keyframe) {
         s->blocks[blk_idx].pos      = s->keyframedata + (get_bits_count(gb) / 8);
         s->blocks[blk_idx].size     = block_size;
-        s->blocks[blk_idx].unp_size = s->block_size * 3 - s->zstream.avail_out;
     }
     if (!s->color_depth) {
         /* Flash Screen Video stores the image upside down, so copy
@@ -256,7 +264,7 @@
             return AVERROR_PATCHWELCOME;
         }
         if (get_bits1(&gb)) {
-            av_log_missing_feature(avctx, "custom palette", 1);
+            av_log_missing_feature(avctx, "Custom palette", 1);
             return AVERROR_PATCHWELCOME;
         }
     }
@@ -294,8 +302,7 @@
 
     /* initialize the image size once */
     if (avctx->width == 0 && avctx->height == 0) {
-        avctx->width  = s->image_width;
-        avctx->height = s->image_height;
+        avcodec_set_dimensions(avctx, s->image_width, s->image_height);
     }
 
     /* check for changes of image width and image height */
@@ -312,10 +319,11 @@
     if (s->is_keyframe) {
         s->keyframedata = av_realloc(s->keyframedata, avpkt->size);
         memcpy(s->keyframedata, avpkt->data, avpkt->size);
-        s->blocks = av_realloc(s->blocks,
-                               (v_blocks + !!v_part) * (h_blocks + !!h_part)
-                               * sizeof(s->blocks[0]));
     }
+    if(s->ver == 2)
+        s->blocks = av_realloc(s->blocks,
+                                (v_blocks + !!v_part) * (h_blocks + !!h_part)
+                                * sizeof(s->blocks[0]));
 
     av_dlog(avctx, "image: %dx%d block: %dx%d num: %dx%d part: %dx%d\n",
             s->image_width, s->image_height, s->block_width, s->block_height,
@@ -371,6 +379,11 @@
                 }
 
                 if (has_diff) {
+                    if (!s->keyframe) {
+                        av_log(avctx, AV_LOG_ERROR,
+                               "inter frame without keyframe\n");
+                        return AVERROR_INVALIDDATA;
+                    }
                     s->diff_start  = get_bits(&gb, 8);
                     s->diff_height = get_bits(&gb, 8);
                     av_log(avctx, AV_LOG_DEBUG,
@@ -390,6 +403,11 @@
                     av_log_missing_feature(avctx, "zlibprime_curr", 1);
                     return AVERROR_PATCHWELCOME;
                 }
+                if (!s->blocks && (s->zlibprime_curr || s->zlibprime_prev)) {
+                    av_log(avctx, AV_LOG_ERROR, "no data available for zlib "
+                           "priming\n");
+                    return AVERROR_INVALIDDATA;
+                }
                 size--; // account for flags byte
             }
 
@@ -462,7 +480,7 @@
     .close          = flashsv_decode_end,
     .decode         = flashsv_decode_frame,
     .capabilities   = CODEC_CAP_DR1,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_BGR24, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_BGR24, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("Flash Screen Video v1"),
 };
 #endif /* CONFIG_FLASHSV_DECODER */
@@ -525,7 +543,7 @@
     .close          = flashsv2_decode_end,
     .decode         = flashsv_decode_frame,
     .capabilities   = CODEC_CAP_DR1,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_BGR24, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_BGR24, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("Flash Screen Video v2"),
 };
 #endif /* CONFIG_FLASHSV2_DECODER */
diff --git a/libavcodec/flashsv2enc.c b/libavcodec/flashsv2enc.c
index a33c9bb..1d0d196 100644
--- a/libavcodec/flashsv2enc.c
+++ b/libavcodec/flashsv2enc.c
@@ -926,6 +926,6 @@
     .init           = flashsv2_encode_init,
     .encode2        = flashsv2_encode_frame,
     .close          = flashsv2_encode_end,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_BGR24, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_BGR24, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("Flash Screen Video Version 2"),
 };
diff --git a/libavcodec/flashsvenc.c b/libavcodec/flashsvenc.c
index 867c65e..e6b181f 100644
--- a/libavcodec/flashsvenc.c
+++ b/libavcodec/flashsvenc.c
@@ -283,6 +283,6 @@
     .init           = flashsv_encode_init,
     .encode2        = flashsv_encode_frame,
     .close          = flashsv_encode_end,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_BGR24, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_BGR24, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("Flash Screen Video"),
 };
diff --git a/libavcodec/flicvideo.c b/libavcodec/flicvideo.c
index 6a11122..7bba299 100644
--- a/libavcodec/flicvideo.c
+++ b/libavcodec/flicvideo.c
@@ -129,15 +129,15 @@
     }
 
     switch (depth) {
-        case 8  : avctx->pix_fmt = PIX_FMT_PAL8; break;
-        case 15 : avctx->pix_fmt = PIX_FMT_RGB555; break;
-        case 16 : avctx->pix_fmt = PIX_FMT_RGB565; break;
-        case 24 : avctx->pix_fmt = PIX_FMT_BGR24; /* Supposedly BGR, but havent any files to test with */
+        case 8  : avctx->pix_fmt = AV_PIX_FMT_PAL8; break;
+        case 15 : avctx->pix_fmt = AV_PIX_FMT_RGB555; break;
+        case 16 : avctx->pix_fmt = AV_PIX_FMT_RGB565; break;
+        case 24 : avctx->pix_fmt = AV_PIX_FMT_BGR24; /* Supposedly BGR, but havent any files to test with */
                   av_log(avctx, AV_LOG_ERROR, "24Bpp FLC/FLX is unsupported due to no test files.\n");
-                  return -1;
+                  return AVERROR_PATCHWELCOME;
         default :
                   av_log(avctx, AV_LOG_ERROR, "Unknown FLC/FLX depth of %d Bpp is unsupported.\n",depth);
-                  return -1;
+                  return AVERROR_INVALIDDATA;
     }
 
     avcodec_get_frame_defaults(&s->frame);
@@ -165,7 +165,7 @@
     unsigned int chunk_size;
     int chunk_type;
 
-    int i, j;
+    int i, j, ret;
 
     int color_packets;
     int color_changes;
@@ -187,9 +187,9 @@
 
     s->frame.reference = 3;
     s->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;
-    if (avctx->reget_buffer(avctx, &s->frame) < 0) {
+    if ((ret = avctx->reget_buffer(avctx, &s->frame)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
-        return -1;
+        return ret;
     }
 
     pixels = s->frame.data[0];
@@ -256,7 +256,7 @@
                     r = bytestream2_get_byte(&g2) << color_shift;
                     g = bytestream2_get_byte(&g2) << color_shift;
                     b = bytestream2_get_byte(&g2) << color_shift;
-                    entry = 0xFF << 24 | r << 16 | g << 8 | b;
+                    entry = 0xFFU << 24 | r << 16 | g << 8 | b;
                     if (color_shift == 2)
                         entry |= entry >> 6 & 0x30303;
                     if (s->palette[palette_ptr] != entry)
@@ -485,7 +485,7 @@
     unsigned int chunk_size;
     int chunk_type;
 
-    int i, j;
+    int i, j, ret;
 
     int lines;
     int compressed_lines;
@@ -502,9 +502,9 @@
 
     s->frame.reference = 3;
     s->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;
-    if (avctx->reget_buffer(avctx, &s->frame) < 0) {
+    if ((ret = avctx->reget_buffer(avctx, &s->frame)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
-        return -1;
+        return ret;
     }
 
     pixels = s->frame.data[0];
@@ -759,7 +759,7 @@
                                    const uint8_t *buf, int buf_size)
 {
   av_log(avctx, AV_LOG_ERROR, "24Bpp FLC Unsupported due to lack of test files.\n");
-  return -1;
+  return AVERROR_PATCHWELCOME;
 }
 
 static int flic_decode_frame(AVCodecContext *avctx,
@@ -768,16 +768,16 @@
 {
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
-    if (avctx->pix_fmt == PIX_FMT_PAL8) {
+    if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
       return flic_decode_frame_8BPP(avctx, data, data_size,
                                     buf, buf_size);
     }
-    else if ((avctx->pix_fmt == PIX_FMT_RGB555) ||
-             (avctx->pix_fmt == PIX_FMT_RGB565)) {
+    else if ((avctx->pix_fmt == AV_PIX_FMT_RGB555) ||
+             (avctx->pix_fmt == AV_PIX_FMT_RGB565)) {
       return flic_decode_frame_15_16BPP(avctx, data, data_size,
                                         buf, buf_size);
     }
-    else if (avctx->pix_fmt == PIX_FMT_BGR24) {
+    else if (avctx->pix_fmt == AV_PIX_FMT_BGR24) {
       return flic_decode_frame_24BPP(avctx, data, data_size,
                                      buf, buf_size);
     }
@@ -787,7 +787,7 @@
     /* the finite set of possibilites allowable by here. */
     /* But in case we do, just error out. */
     av_log(avctx, AV_LOG_ERROR, "Unknown FLC format, my science cannot explain how this happened.\n");
-    return -1;
+    return AVERROR_INVALIDDATA;
 }
 
 
diff --git a/libavcodec/flvenc.c b/libavcodec/flvenc.c
index acd81b3..a68a6fa 100644
--- a/libavcodec/flvenc.c
+++ b/libavcodec/flvenc.c
@@ -94,7 +94,7 @@
     .init           = ff_MPV_encode_init,
     .encode2        = ff_MPV_encode_picture,
     .close          = ff_MPV_encode_end,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUV420P, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("FLV / Sorenson Spark / Sorenson H.263 (Flash Video)"),
     .priv_class     = &flv_class,
 };
diff --git a/libavcodec/fmtconvert.c b/libavcodec/fmtconvert.c
index 372f2a3..79e9645 100644
--- a/libavcodec/fmtconvert.c
+++ b/libavcodec/fmtconvert.c
@@ -85,7 +85,7 @@
 
     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);
+    if (ARCH_X86) ff_fmt_convert_init_x86(c, avctx);
     if (HAVE_MIPSFPU) ff_fmt_convert_init_mips(c);
 }
 
diff --git a/libavcodec/frame_thread_encoder.c b/libavcodec/frame_thread_encoder.c
index 26a41af..ab095dc 100644
--- a/libavcodec/frame_thread_encoder.c
+++ b/libavcodec/frame_thread_encoder.c
@@ -95,9 +95,12 @@
         c->parent_avctx->release_buffer(c->parent_avctx, frame);
         pthread_mutex_unlock(&c->buffer_mutex);
         av_freep(&frame);
-        if(!got_packet)
-            continue;
-        av_dup_packet(pkt);
+        if(got_packet) {
+            av_dup_packet(pkt);
+        } else {
+            pkt->data = NULL;
+            pkt->size = 0;
+        }
         pthread_mutex_lock(&c->finished_task_mutex);
         c->finished_tasks[task.index].outdata = pkt; pkt = NULL;
         c->finished_tasks[task.index].return_code = ret;
@@ -152,16 +155,14 @@
 
     for(i=0; i<avctx->thread_count ; i++){
         AVDictionary *tmp = NULL;
+        void *tmpv;
         AVCodecContext *thread_avctx = avcodec_alloc_context3(avctx->codec);
         if(!thread_avctx)
             goto fail;
+        tmpv = thread_avctx->priv_data;
         *thread_avctx = *avctx;
+        thread_avctx->priv_data = tmpv;
         thread_avctx->internal = NULL;
-        thread_avctx->priv_data = av_malloc(avctx->codec->priv_data_size);
-        if(!thread_avctx->priv_data) {
-            av_freep(&thread_avctx);
-            goto fail;
-        }
         memcpy(thread_avctx->priv_data, avctx->priv_data, avctx->codec->priv_data_size);
         thread_avctx->thread_count = 1;
         thread_avctx->active_thread_type &= ~FF_THREAD_FRAME;
@@ -259,11 +260,11 @@
     }
     task = c->finished_tasks[c->finished_task_index];
     *pkt = *(AVPacket*)(task.outdata);
-    c->finished_tasks[c->finished_task_index].outdata= NULL;
+    if(pkt->data)
+        *got_packet_ptr = 1;
+    av_freep(&c->finished_tasks[c->finished_task_index].outdata);
     c->finished_task_index = (c->finished_task_index+1) % BUFFER_SIZE;
     pthread_mutex_unlock(&c->finished_task_mutex);
 
-    *got_packet_ptr = 1;
-
     return task.return_code;
 }
diff --git a/libavcodec/fraps.c b/libavcodec/fraps.c
index af4e321..b624e4b 100644
--- a/libavcodec/fraps.c
+++ b/libavcodec/fraps.c
@@ -142,7 +142,8 @@
     int i, j, is_chroma;
     const int planes = 3;
     uint8_t *out;
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
+    int ret;
 
     header = AV_RL32(buf);
     version = header & 0xff;
@@ -152,7 +153,7 @@
         av_log(avctx, AV_LOG_ERROR,
                "This file is encoded with Fraps version %d. " \
                "This codec can only decode versions <= 5.\n", version);
-        return -1;
+        return AVERROR_PATCHWELCOME;
     }
 
     buf += header_size;
@@ -170,7 +171,7 @@
             av_log(avctx, AV_LOG_ERROR,
                    "Invalid frame length %d (should be %d)\n",
                    buf_size, needed_size);
-            return -1;
+            return AVERROR_INVALIDDATA;
         }
     } else {
         /* skip frame */
@@ -180,13 +181,13 @@
         }
         if (AV_RL32(buf) != FPS_TAG || buf_size < planes*1024 + 24) {
             av_log(avctx, AV_LOG_ERROR, "Fraps: error in data stream\n");
-            return -1;
+            return AVERROR_INVALIDDATA;
         }
         for(i = 0; i < planes; i++) {
             offs[i] = AV_RL32(buf + 4 + i * 4);
             if(offs[i] >= buf_size - header_size || (i && offs[i] <= offs[i - 1] + 1024)) {
                 av_log(avctx, AV_LOG_ERROR, "Fraps: plane %i offset is out of bounds\n", i);
-                return -1;
+                return AVERROR_INVALIDDATA;
             }
         }
         offs[planes] = buf_size - header_size;
@@ -204,15 +205,15 @@
     f->reference = 0;
     f->buffer_hints = FF_BUFFER_HINTS_VALID;
 
-    pix_fmt = version & 1 ? PIX_FMT_BGR24 : PIX_FMT_YUVJ420P;
+    pix_fmt = version & 1 ? AV_PIX_FMT_BGR24 : AV_PIX_FMT_YUVJ420P;
     if (avctx->pix_fmt != pix_fmt && f->data[0]) {
         avctx->release_buffer(avctx, f);
     }
     avctx->pix_fmt = pix_fmt;
 
-    if (ff_thread_get_buffer(avctx, f)) {
+    if ((ret = ff_thread_get_buffer(avctx, f))) {
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
+        return ret;
     }
 
     switch(version) {
@@ -222,7 +223,7 @@
         if ( (avctx->width % 8) != 0 || (avctx->height % 2) != 0 ) {
             av_log(avctx, AV_LOG_ERROR, "Invalid frame size %dx%d\n",
                    avctx->width, avctx->height);
-            return -1;
+            return AVERROR_INVALIDDATA;
         }
 
         buf32=(const uint32_t*)buf;
@@ -261,7 +262,7 @@
             if(fraps2_decode_plane(s, f->data[i], f->linesize[i], avctx->width >> is_chroma,
                     avctx->height >> is_chroma, buf + offs[i], offs[i + 1] - offs[i], is_chroma, 1) < 0) {
                 av_log(avctx, AV_LOG_ERROR, "Error decoding plane %i\n", i);
-                return -1;
+                return AVERROR_INVALIDDATA;
             }
         }
         break;
@@ -272,7 +273,7 @@
             if(fraps2_decode_plane(s, f->data[0] + i + (f->linesize[0] * (avctx->height - 1)), -f->linesize[0],
                     avctx->width, avctx->height, buf + offs[i], offs[i + 1] - offs[i], 0, 3) < 0) {
                 av_log(avctx, AV_LOG_ERROR, "Error decoding plane %i\n", i);
-                return -1;
+                return AVERROR_INVALIDDATA;
             }
         }
         out = f->data[0];
diff --git a/libavcodec/frwu.c b/libavcodec/frwu.c
index 10b80f7..a0484d3 100644
--- a/libavcodec/frwu.c
+++ b/libavcodec/frwu.c
@@ -22,6 +22,12 @@
 
 #include "avcodec.h"
 #include "bytestream.h"
+#include "libavutil/opt.h"
+
+typedef struct {
+    AVClass *av_class;
+    int change_field_order;
+} FRWUContext;
 
 static av_cold int decode_init(AVCodecContext *avctx)
 {
@@ -29,7 +35,7 @@
         av_log(avctx, AV_LOG_ERROR, "frwu needs even width\n");
         return AVERROR(EINVAL);
     }
-    avctx->pix_fmt = PIX_FMT_UYVY422;
+    avctx->pix_fmt = AV_PIX_FMT_UYVY422;
 
     avctx->coded_frame = avcodec_alloc_frame();
     if (!avctx->coded_frame)
@@ -41,6 +47,7 @@
 static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
                         AVPacket *avpkt)
 {
+    FRWUContext *s = avctx->priv_data;
     int field, ret;
     AVFrame *pic = avctx->coded_frame;
     const uint8_t *buf = avpkt->data;
@@ -66,8 +73,6 @@
 
     pic->pict_type = AV_PICTURE_TYPE_I;
     pic->key_frame = 1;
-    pic->interlaced_frame = 1;
-    pic->top_field_first = 1;
 
     for (field = 0; field < 2; field++) {
         int i;
@@ -86,9 +91,14 @@
             av_log(avctx, AV_LOG_ERROR, "Packet is too small, need %i, have %i\n", field_size, (int)(buf_end - buf));
             return AVERROR_INVALIDDATA;
         }
-        if (field)
+        if (field ^ s->change_field_order) {
             dst += pic->linesize[0];
+        } else if (s->change_field_order) {
+            dst += 2 * pic->linesize[0];
+        }
         for (i = 0; i < field_h; i++) {
+            if (s->change_field_order && field && i == field_h - 1)
+                dst = pic->data[0];
             memcpy(dst, buf, avctx->width * 2);
             buf += avctx->width * 2;
             dst += pic->linesize[0] << 1;
@@ -112,13 +122,28 @@
     return 0;
 }
 
+static const AVOption frwu_options[] = {
+    {"change_field_order", "Change field order", offsetof(FRWUContext, change_field_order), FF_OPT_TYPE_INT,
+     {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_VIDEO_PARAM},
+    {NULL}
+};
+
+static const AVClass frwu_class = {
+    .class_name = "frwu Decoder",
+    .item_name  = av_default_item_name,
+    .option     = frwu_options,
+    .version    = LIBAVUTIL_VERSION_INT,
+};
+
 AVCodec ff_frwu_decoder = {
     .name           = "frwu",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = AV_CODEC_ID_FRWU,
+    .priv_data_size = sizeof(FRWUContext),
     .init           = decode_init,
     .close          = decode_close,
     .decode         = decode_frame,
     .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("Forward Uncompressed"),
+    .priv_class     = &frwu_class,
 };
diff --git a/libavcodec/g722.h b/libavcodec/g722.h
index eb3b9b8..bab1da4 100644
--- a/libavcodec/g722.h
+++ b/libavcodec/g722.h
@@ -30,7 +30,7 @@
 
 #define PREV_SAMPLES_BUF_SIZE 1024
 
-typedef struct {
+typedef struct G722Context {
     const AVClass *class;
     AVFrame frame;
     int     bits_per_codeword;
diff --git a/libavcodec/g722dec.c b/libavcodec/g722dec.c
index ea06ce0..f28c86b 100644
--- a/libavcodec/g722dec.c
+++ b/libavcodec/g722dec.c
@@ -5,20 +5,20 @@
  * Copyright (c) 2009 Kenan Gillet
  * Copyright (c) 2010 Martin Storsjo
  *
- * This file is part of Libav.
+ * This file is part of FFmpeg.
  *
- * Libav is free software; you can redistribute it and/or
+ * 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.
  *
- * Libav is distributed in the hope that it will be useful,
+ * 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 Libav; if not, write to the Free Software
+ * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
@@ -34,10 +34,11 @@
  *       respectively of each byte are ignored.
  */
 
+#include "libavutil/channel_layout.h"
+#include "libavutil/opt.h"
 #include "avcodec.h"
 #include "get_bits.h"
 #include "g722.h"
-#include "libavutil/opt.h"
 
 #define OFFSET(x) offsetof(G722Context, x)
 #define AD AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM
@@ -57,11 +58,9 @@
 {
     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;
+    avctx->channels       = 1;
+    avctx->channel_layout = AV_CH_LAYOUT_MONO;
+    avctx->sample_fmt     = AV_SAMPLE_FMT_S16;
 
     c->band[0].scale_factor = 8;
     c->band[1].scale_factor = 2;
diff --git a/libavcodec/g722enc.c b/libavcodec/g722enc.c
index d3c7298..39f83dc 100644
--- a/libavcodec/g722enc.c
+++ b/libavcodec/g722enc.c
@@ -197,7 +197,7 @@
     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));
+        memset(c->nodep_buf[i], 0, 2 * frontier * sizeof(*c->nodep_buf[i]));
         nodes[i][0] = c->node_buf[i] + frontier;
         nodes[i][0]->ssd = 0;
         nodes[i][0]->path = 0;
diff --git a/libavcodec/g723_1.c b/libavcodec/g723_1.c
index 29eb4fa..fd6b558 100644
--- a/libavcodec/g723_1.c
+++ b/libavcodec/g723_1.c
@@ -26,8 +26,8 @@
  */
 
 #define BITSTREAM_READER_LE
-#include "libavutil/audioconvert.h"
-#include "libavutil/lzo.h"
+#include "libavutil/channel_layout.h"
+#include "libavutil/mem.h"
 #include "libavutil/opt.h"
 #include "avcodec.h"
 #include "internal.h"
@@ -226,8 +226,10 @@
 /**
  * Bitexact implementation of sqrt(val/2).
  */
-static int16_t square_root(int val)
+static int16_t square_root(unsigned val)
 {
+    av_assert2(!(val & 0x80000000));
+
     return (ff_sqrt(val << 1) >> 1) & (~1);
 }
 
@@ -357,7 +359,7 @@
 
     /* Calculate negative cosine */
     for (j = 0; j < LPC_ORDER; j++) {
-        int index     = lpc[j] >> 7;
+        int index     = (lpc[j] >> 7) & 0x1FF;
         int offset    = lpc[j] & 0x7f;
         int temp1     = cos_tab[index] << 16;
         int temp2     = (cos_tab[index + 1] - cos_tab[index]) *
@@ -711,7 +713,7 @@
 
     scale = normalize_bits(temp1, 31);
     for (i = 0; i < 5; i++)
-        energy[i] = av_clipl_int32(energy[i] << scale) >> 16;
+        energy[i] = (energy[i] << scale) >> 16;
 
     if (fwd_lag && !back_lag) {  /* Case 1 */
         comp_ppf_gains(fwd_lag,  ppf, cur_rate, energy[0], energy[1],
diff --git a/libavcodec/g723_1_data.h b/libavcodec/g723_1_data.h
index 8ee4a91..38a6c59 100644
--- a/libavcodec/g723_1_data.h
+++ b/libavcodec/g723_1_data.h
@@ -128,7 +128,7 @@
 /**
  * Cosine table scaled by 2^14
  */
-static const int16_t cos_tab[COS_TBL_SIZE] = {
+static const int16_t cos_tab[COS_TBL_SIZE+1] = {
     16384,  16383,  16379,  16373,  16364,  16353,  16340,  16324,
     16305,  16284,  16261,  16235,  16207,  16176,  16143,  16107,
     16069,  16029,  15986,  15941,  15893,  15843,  15791,  15736,
@@ -193,6 +193,7 @@
     15679,  15736,  15791,  15843,  15893,  15941,  15986,  16029,
     16069,  16107,  16143,  16176,  16207,  16235,  16261,  16284,
     16305,  16324,  16340,  16353,  16364,  16373,  16379,  16383,
+    16384
 };
 
 /**
diff --git a/libavcodec/g726.c b/libavcodec/g726.c
index b2f21fd..e505d5d 100644
--- a/libavcodec/g726.c
+++ b/libavcodec/g726.c
@@ -22,7 +22,9 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include <limits.h>
+
 #include "libavutil/avassert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/opt.h"
 #include "avcodec.h"
 #include "internal.h"
@@ -418,18 +420,8 @@
 {
     G726Context* c = avctx->priv_data;
 
-    if (avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
-        avctx->sample_rate != 8000) {
-        av_log(avctx, AV_LOG_ERROR, "Only 8kHz sample rate is allowed when "
-               "the compliance level is strict. Reduce the compliance level "
-               "if you wish to decode the stream anyway.\n");
-        return AVERROR(EINVAL);
-    }
-
-    if(avctx->channels != 1){
-        av_log(avctx, AV_LOG_ERROR, "Only mono is supported\n");
-        return AVERROR(EINVAL);
-    }
+    avctx->channels       = 1;
+    avctx->channel_layout = AV_CH_LAYOUT_MONO;
 
     c->code_size = avctx->bits_per_coded_sample;
     if (c->code_size < 2 || c->code_size > 5) {
diff --git a/libavcodec/g729dec.c b/libavcodec/g729dec.c
index 7c12b0e..036614d 100644
--- a/libavcodec/g729dec.c
+++ b/libavcodec/g729dec.c
@@ -187,10 +187,10 @@
    return (0x6996966996696996ULL >> (value >> 2)) & 1;
 }
 
-/*
+/**
  * Decodes LSF (Line Spectral Frequencies) from L0-L3 (3.2.4).
- * @param lsfq [out] (2.13) quantized LSF coefficients
- * @param past_quantizer_outputs [in/out] (2.13) quantizer outputs from previous frames
+ * @param[out] lsfq (2.13) quantized LSF coefficients
+ * @param[in,out] past_quantizer_outputs (2.13) quantizer outputs from previous frames
  * @param ma_predictor switched MA predictor of LSP quantizer
  * @param vq_1st first stage vector of quantizer
  * @param vq_2nd_low second stage lower vector of LSP quantizer
@@ -232,8 +232,8 @@
 
 /**
  * Restores past LSP quantizer output using LSF from previous frame
- * @param lsfq [in/out] (2.13) quantized LSF coefficients
- * @param past_quantizer_outputs [in/out] (2.13) quantizer outputs from previous frames
+ * @param[in,out] lsfq (2.13) quantized LSF coefficients
+ * @param[in,out] past_quantizer_outputs (2.13) quantizer outputs from previous frames
  * @param ma_predictor_prev MA predictor from previous frame
  * @param lsfq_prev (2.13) quantized LSF coefficients from previous frame
  */
@@ -256,7 +256,7 @@
 
 /**
  * Constructs new excitation signal and applies phase filter to it
- * @param out[out] constructed speech signal
+ * @param[out] out constructed speech signal
  * @param in original excitation signal
  * @param fc_cur (2.13) original fixed-codebook vector
  * @param gain_code (14.1) gain code
diff --git a/libavcodec/get_bits.h b/libavcodec/get_bits.h
index 05ac8f7..a1a48ab 100644
--- a/libavcodec/get_bits.h
+++ b/libavcodec/get_bits.h
@@ -302,7 +302,9 @@
  */
 static inline unsigned int get_bits_long(GetBitContext *s, int n)
 {
-    if (n <= MIN_CACHE_BITS)
+    if (!n) {
+        return 0;
+    } else if (n <= MIN_CACHE_BITS)
         return get_bits(s, n);
     else {
 #ifdef BITSTREAM_READER_LE
diff --git a/libavcodec/gif.c b/libavcodec/gif.c
index 8576002..1ae4661 100644
--- a/libavcodec/gif.c
+++ b/libavcodec/gif.c
@@ -204,9 +204,9 @@
     .init           = gif_encode_init,
     .encode2        = gif_encode_frame,
     .close          = gif_encode_close,
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_RGB8, PIX_FMT_BGR8, PIX_FMT_RGB4_BYTE, PIX_FMT_BGR4_BYTE,
-        PIX_FMT_GRAY8, PIX_FMT_PAL8, PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_RGB8, AV_PIX_FMT_BGR8, AV_PIX_FMT_RGB4_BYTE, AV_PIX_FMT_BGR4_BYTE,
+        AV_PIX_FMT_GRAY8, AV_PIX_FMT_PAL8, AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("GIF (Graphics Interchange Format)"),
 };
diff --git a/libavcodec/gif.h b/libavcodec/gif.h
new file mode 100644
index 0000000..b557534
--- /dev/null
+++ b/libavcodec/gif.h
@@ -0,0 +1,47 @@
+/*
+ * GIF format definitions
+ * Copyright (c) 2003 Fabrice Bellard
+ * Copyright (c) 2006 Baptiste Coudurier
+ * Copyright (c) 2012 Vitaliy E Sugrobov
+ *
+ * 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
+ * GIF format definitions.
+ */
+
+#ifndef AVCODEC_GIFDEFS_H
+#define AVCODEC_GIFDEFS_H
+
+#include <stdint.h>
+
+static const uint8_t gif87a_sig[6] = "GIF87a";
+static const uint8_t gif89a_sig[6] = "GIF89a";
+
+#define GCE_DISPOSAL_NONE       0
+#define GCE_DISPOSAL_INPLACE    1
+#define GCE_DISPOSAL_BACKGROUND 2
+#define GCE_DISPOSAL_RESTORE    3
+
+#define GIF_TRAILER                 0x3b
+#define GIF_EXTENSION_INTRODUCER    0x21
+#define GIF_IMAGE_SEPARATOR         0x2c
+#define GIF_GCE_EXT_LABEL           0xf9
+
+#endif /* AVCODEC_GIFDEFS_H */
diff --git a/libavcodec/gifdec.c b/libavcodec/gifdec.c
index 40a4c9b..3e3c9a5 100644
--- a/libavcodec/gifdec.c
+++ b/libavcodec/gifdec.c
@@ -2,6 +2,7 @@
  * GIF decoder
  * Copyright (c) 2003 Fabrice Bellard
  * Copyright (c) 2006 Baptiste Coudurier
+ * Copyright (c) 2012 Vitaliy E Sugrobov
  *
  * This file is part of FFmpeg.
  *
@@ -23,29 +24,45 @@
 //#define DEBUG
 
 #include "libavutil/imgutils.h"
+#include "libavutil/opt.h"
 #include "avcodec.h"
 #include "bytestream.h"
 #include "lzw.h"
+#include "gif.h"
 
-#define GCE_DISPOSAL_NONE       0
-#define GCE_DISPOSAL_INPLACE    1
-#define GCE_DISPOSAL_BACKGROUND 2
-#define GCE_DISPOSAL_RESTORE    3
+/* This value is intentionally set to "transparent white" color.
+ * It is much better to have white background instead of black
+ * when gif image converted to format which not support transparency.
+ */
+#define GIF_TRANSPARENT_COLOR    0x00ffffff
 
 typedef struct GifState {
+    const AVClass *class;
     AVFrame picture;
     int screen_width;
     int screen_height;
+    int has_global_palette;
     int bits_per_pixel;
+    uint32_t bg_color;
     int background_color_index;
     int transparent_color_index;
     int color_resolution;
-    uint32_t *image_palette;
+    /* intermediate buffer for storing color indices
+     * obtained from lzw-encoded data stream */
+    uint8_t *idx_line;
+    int idx_line_size;
 
     /* after the frame is displayed, the disposal method is used */
+    int gce_prev_disposal;
     int gce_disposal;
-    /* delay during which the frame is shown */
-    int gce_delay;
+    /* rectangle describing area that must be disposed */
+    int gce_l, gce_t, gce_w, gce_h;
+    /* depending on disposal method we store either part of the image
+     * drawn on the canvas or background color that
+     * should be used upon disposal */
+    uint32_t * stored_img;
+    int stored_img_size;
+    int stored_bg_color;
 
     /* LZW compatible decoder */
     const uint8_t *bytestream;
@@ -53,20 +70,78 @@
     LZWState *lzw;
 
     /* aux buffers */
-    uint8_t global_palette[256 * 3];
-    uint8_t local_palette[256 * 3];
+    uint32_t global_palette[256];
+    uint32_t local_palette[256];
 
     AVCodecContext *avctx;
+    int keyframe;
+    int trans_color;    /**< color value that is used instead of transparent color */
 } GifState;
 
-static const uint8_t gif87a_sig[6] = "GIF87a";
-static const uint8_t gif89a_sig[6] = "GIF89a";
+static void gif_read_palette(const uint8_t **buf, uint32_t *pal, int nb)
+{
+    const uint8_t *pal_end = *buf + nb * 3;
+
+    for (; *buf < pal_end; *buf += 3, pal++)
+        *pal = (0xffu << 24) | AV_RB24(*buf);
+}
+
+static void gif_fill(AVFrame *picture, uint32_t color)
+{
+    uint32_t *p = (uint32_t *)picture->data[0];
+    uint32_t *p_end = p + (picture->linesize[0] / sizeof(uint32_t)) * picture->height;
+
+    for (; p < p_end; p++)
+        *p = color;
+}
+
+static void gif_fill_rect(AVFrame *picture, uint32_t color, int l, int t, int w, int h)
+{
+    const int linesize = picture->linesize[0] / sizeof(uint32_t);
+    const uint32_t *py = (uint32_t *)picture->data[0] + t * linesize;
+    const uint32_t *pr, *pb = py + (t + h) * linesize;
+    uint32_t *px;
+
+    for (; py < pb; py += linesize) {
+        px = (uint32_t *)py + l;
+        pr = px + w;
+
+        for (; px < pr; px++)
+            *px = color;
+    }
+}
+
+static void gif_copy_img_rect(const uint32_t *src, uint32_t *dst,
+                              int linesize, int l, int t, int w, int h)
+{
+    const int y_start = t * linesize;
+    const uint32_t *src_px, *src_pr,
+                   *src_py = src + y_start,
+                   *dst_py = dst + y_start;
+    const uint32_t *src_pb = src_py + (t + h) * linesize;
+    uint32_t *dst_px;
+
+    for (; src_py < src_pb; src_py += linesize, dst_py += linesize) {
+        src_px = src_py + l;
+        dst_px = (uint32_t *)dst_py + l;
+        src_pr = src_px + w;
+
+        for (; src_px < src_pr; src_px++, dst_px++)
+            *dst_px = *src_px;
+    }
+}
 
 static int gif_read_image(GifState *s)
 {
     int left, top, width, height, bits_per_pixel, code_size, flags;
-    int is_interleaved, has_local_palette, y, pass, y1, linesize, n, i;
-    uint8_t *ptr, *spal, *palette, *ptr1;
+    int is_interleaved, has_local_palette, y, pass, y1, linesize, pal_size;
+    uint32_t *ptr, *pal, *px, *pr, *ptr1;
+    int ret;
+    uint8_t *idx;
+
+    /* At least 9 bytes of Image Descriptor. */
+    if (s->bytestream_end < s->bytestream + 9)
+        return AVERROR_INVALIDDATA;
 
     left = bytestream_get_le16(&s->bytestream);
     top = bytestream_get_le16(&s->bytestream);
@@ -80,11 +155,31 @@
     av_dlog(s->avctx, "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));
-        palette = s->local_palette;
+        pal_size = 1 << bits_per_pixel;
+
+        if (s->bytestream_end < s->bytestream + pal_size * 3)
+            return AVERROR_INVALIDDATA;
+
+        gif_read_palette(&s->bytestream, s->local_palette, pal_size);
+        pal = s->local_palette;
     } else {
-        palette = s->global_palette;
-        bits_per_pixel = s->bits_per_pixel;
+        if (!s->has_global_palette) {
+            av_log(s->avctx, AV_LOG_FATAL, "picture doesn't have either global or local palette.\n");
+            return AVERROR_INVALIDDATA;
+        }
+
+        pal = s->global_palette;
+    }
+
+    if (s->keyframe) {
+        if (s->transparent_color_index == -1 && s->has_global_palette) {
+            /* transparency wasn't set before the first frame, fill with background color */
+            gif_fill(&s->picture, s->bg_color);
+        } else {
+            /* otherwise fill with transparent color.
+             * this is necessary since by default picture filled with 0x80808080. */
+            gif_fill(&s->picture, s->trans_color);
+        }
     }
 
     /* verify that all the image is inside the screen dimensions */
@@ -92,32 +187,64 @@
         top + height > s->screen_height)
         return AVERROR(EINVAL);
 
-    /* build the palette */
-    n = (1 << bits_per_pixel);
-    spal = palette;
-    for(i = 0; i < n; i++) {
-        s->image_palette[i] = (0xffu << 24) | AV_RB24(spal);
-        spal += 3;
+    /* process disposal method */
+    if (s->gce_prev_disposal == GCE_DISPOSAL_BACKGROUND) {
+        gif_fill_rect(&s->picture, s->stored_bg_color, s->gce_l, s->gce_t, s->gce_w, s->gce_h);
+    } else if (s->gce_prev_disposal == GCE_DISPOSAL_RESTORE) {
+        gif_copy_img_rect(s->stored_img, (uint32_t *)s->picture.data[0],
+            s->picture.linesize[0] / sizeof(uint32_t), s->gce_l, s->gce_t, s->gce_w, s->gce_h);
     }
-    for(; i < 256; i++)
-        s->image_palette[i] = (0xffu << 24);
-    /* handle transparency */
-    if (s->transparent_color_index >= 0)
-        s->image_palette[s->transparent_color_index] = 0;
+
+    s->gce_prev_disposal = s->gce_disposal;
+
+    if (s->gce_disposal != GCE_DISPOSAL_NONE) {
+        s->gce_l = left;  s->gce_t = top;
+        s->gce_w = width; s->gce_h = height;
+
+        if (s->gce_disposal == GCE_DISPOSAL_BACKGROUND) {
+            if (s->background_color_index == s->transparent_color_index)
+                s->stored_bg_color = s->trans_color;
+            else
+                s->stored_bg_color = s->bg_color;
+        } else if (s->gce_disposal == GCE_DISPOSAL_RESTORE) {
+            av_fast_malloc(&s->stored_img, &s->stored_img_size, s->picture.linesize[0] * s->picture.height);
+            if (!s->stored_img)
+                return AVERROR(ENOMEM);
+
+            gif_copy_img_rect((uint32_t *)s->picture.data[0], s->stored_img,
+                s->picture.linesize[0] / sizeof(uint32_t), left, top, width, height);
+        }
+    }
+
+    /* Expect at least 2 bytes: 1 for lzw code size and 1 for block size. */
+    if (s->bytestream_end < s->bytestream + 2)
+        return AVERROR_INVALIDDATA;
 
     /* now get the image data */
     code_size = bytestream_get_byte(&s->bytestream);
-    ff_lzw_decode_init(s->lzw, code_size, s->bytestream,
-                       s->bytestream_end - s->bytestream, FF_LZW_GIF);
+    if ((ret = ff_lzw_decode_init(s->lzw, code_size, s->bytestream,
+                       s->bytestream_end - s->bytestream, FF_LZW_GIF)) < 0) {
+        av_log(s->avctx, AV_LOG_ERROR, "LZW init failed\n");
+        return ret;
+    }
 
     /* read all the image */
-    linesize = s->picture.linesize[0];
-    ptr1 = s->picture.data[0] + top * linesize + left;
+    linesize = s->picture.linesize[0] / sizeof(uint32_t);
+    ptr1 = (uint32_t *)s->picture.data[0] + top * linesize + left;
     ptr = ptr1;
     pass = 0;
     y1 = 0;
     for (y = 0; y < height; y++) {
-        ff_lzw_decode(s->lzw, ptr, width);
+        if (ff_lzw_decode(s->lzw, s->idx_line, width) == 0)
+            goto decode_tail;
+
+        pr = ptr + width;
+
+        for (px = ptr, idx = s->idx_line; px < pr; px++, idx++) {
+            if (*idx != s->transparent_color_index)
+                *px = pal[*idx];
+        }
+
         if (is_interleaved) {
             switch(pass) {
             default:
@@ -149,9 +276,17 @@
             ptr += linesize;
         }
     }
+
+ decode_tail:
     /* read the garbage data until end marker is found */
     ff_lzw_decode_tail(s->lzw);
     s->bytestream = ff_lzw_cur_ptr(s->lzw);
+
+    /* Graphic Control Extension's scope is single frame.
+     * Remove its influence. */
+    s->transparent_color_index = -1;
+    s->gce_disposal = GCE_DISPOSAL_NONE;
+
     return 0;
 }
 
@@ -159,19 +294,29 @@
 {
     int ext_code, ext_len, i, gce_flags, gce_transparent_index;
 
-    /* extension */
+    /* There must be at least 2 bytes:
+     * 1 for extension label and 1 for extension length. */
+    if (s->bytestream_end < s->bytestream + 2)
+        return AVERROR_INVALIDDATA;
+
     ext_code = bytestream_get_byte(&s->bytestream);
     ext_len = bytestream_get_byte(&s->bytestream);
 
     av_dlog(s->avctx, "ext_code=0x%x len=%d\n", ext_code, ext_len);
 
     switch(ext_code) {
-    case 0xf9:
+    case GIF_GCE_EXT_LABEL:
         if (ext_len != 4)
             goto discard_ext;
+
+        /* We need at least 5 bytes more: 4 is for extension body
+         * and 1 for next block size. */
+        if (s->bytestream_end < s->bytestream + 5)
+            return AVERROR_INVALIDDATA;
+
         s->transparent_color_index = -1;
         gce_flags = bytestream_get_byte(&s->bytestream);
-        s->gce_delay = bytestream_get_le16(&s->bytestream);
+        bytestream_get_le16(&s->bytestream);    // delay during which the frame is shown
         gce_transparent_index = bytestream_get_byte(&s->bytestream);
         if (gce_flags & 0x01)
             s->transparent_color_index = gce_transparent_index;
@@ -179,10 +324,15 @@
             s->transparent_color_index = -1;
         s->gce_disposal = (gce_flags >> 2) & 0x7;
 
-        av_dlog(s->avctx, "gce_flags=%x delay=%d tcolor=%d disposal=%d\n",
-               gce_flags, s->gce_delay,
+        av_dlog(s->avctx, "gce_flags=%x tcolor=%d disposal=%d\n",
+               gce_flags,
                s->transparent_color_index, s->gce_disposal);
 
+        if (s->gce_disposal > 3) {
+            s->gce_disposal = GCE_DISPOSAL_NONE;
+            av_dlog(s->avctx, "invalid value in gce_disposal (%d). Using default value of 0.\n", ext_len);
+        }
+
         ext_len = bytestream_get_byte(&s->bytestream);
         break;
     }
@@ -190,6 +340,10 @@
     /* NOTE: many extension blocks can come after */
  discard_ext:
     while (ext_len != 0) {
+        /* There must be at least ext_len bytes and 1 for next block size byte. */
+        if (s->bytestream_end < s->bytestream + ext_len + 1)
+            return AVERROR_INVALIDDATA;
+
         for (i = 0; i < ext_len; i++)
             bytestream_get_byte(&s->bytestream);
         ext_len = bytestream_get_byte(&s->bytestream);
@@ -203,7 +357,7 @@
 {
     uint8_t sig[6];
     int v, n;
-    int has_global_palette;
+    int background_color_index;
 
     if (s->bytestream_end < s->bytestream + 13)
         return AVERROR_INVALIDDATA;
@@ -224,48 +378,65 @@
         return AVERROR_INVALIDDATA;
     }
 
+    av_fast_malloc(&s->idx_line, &s->idx_line_size, s->screen_width);
+    if (!s->idx_line)
+        return AVERROR(ENOMEM);
+
     v = bytestream_get_byte(&s->bytestream);
     s->color_resolution = ((v & 0x70) >> 4) + 1;
-    has_global_palette = (v & 0x80);
+    s->has_global_palette = (v & 0x80);
     s->bits_per_pixel = (v & 0x07) + 1;
-    s->background_color_index = bytestream_get_byte(&s->bytestream);
-    bytestream_get_byte(&s->bytestream);                /* ignored */
+    background_color_index = bytestream_get_byte(&s->bytestream);
+    n = bytestream_get_byte(&s->bytestream);
+    if (n) {
+        s->avctx->sample_aspect_ratio.num = n + 15;
+        s->avctx->sample_aspect_ratio.den = 64;
+    }
 
     av_dlog(s->avctx, "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);
+           s->has_global_palette);
 
-    if (has_global_palette) {
+    if (s->has_global_palette) {
+        s->background_color_index = background_color_index;
         n = 1 << s->bits_per_pixel;
         if (s->bytestream_end < s->bytestream + n * 3)
             return AVERROR_INVALIDDATA;
-        bytestream_get_buffer(&s->bytestream, s->global_palette, n * 3);
-    }
+
+        gif_read_palette(&s->bytestream, s->global_palette, n);
+        s->bg_color = s->global_palette[s->background_color_index];
+    } else
+        s->background_color_index = -1;
+
     return 0;
 }
 
-static int gif_parse_next_image(GifState *s)
+static int gif_parse_next_image(GifState *s, int *got_picture)
 {
+    int ret;
+    *got_picture = sizeof(AVPicture);
     while (s->bytestream < s->bytestream_end) {
         int code = bytestream_get_byte(&s->bytestream);
 
         av_dlog(s->avctx, "code=%02x '%c'\n", code, code);
 
         switch (code) {
-        case ',':
+        case GIF_IMAGE_SEPARATOR:
             return gif_read_image(s);
-        case '!':
-            if (gif_read_extension(s) < 0)
-                return -1;
+        case GIF_EXTENSION_INTRODUCER:
+            if ((ret = gif_read_extension(s)) < 0)
+                return ret;
             break;
-        case ';':
+        case GIF_TRAILER:
             /* end of image */
+            *got_picture = 0;
+            return 0;
         default:
-            /* error or erroneous EOF */
-            return -1;
+            /* erroneous block label */
+            return AVERROR_INVALIDDATA;
         }
     }
-    return -1;
+    return AVERROR_EOF;
 }
 
 static av_cold int gif_decode_init(AVCodecContext *avctx)
@@ -274,6 +445,7 @@
 
     s->avctx = avctx;
 
+    avctx->pix_fmt = AV_PIX_FMT_RGB32;
     avcodec_get_frame_defaults(&s->picture);
     avctx->coded_frame= &s->picture;
     s->picture.data[0] = NULL;
@@ -281,7 +453,7 @@
     return 0;
 }
 
-static int gif_decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
+static int gif_decode_frame(AVCodecContext *avctx, void *data, int *got_picture, AVPacket *avpkt)
 {
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
@@ -289,29 +461,55 @@
     AVFrame *picture = data;
     int ret;
 
+    s->picture.pts          = avpkt->pts;
+    s->picture.pkt_pts      = avpkt->pts;
+    s->picture.pkt_dts      = avpkt->dts;
+    s->picture.pkt_duration = avpkt->duration;
+
     s->bytestream = buf;
     s->bytestream_end = buf + buf_size;
-    if ((ret = gif_read_header1(s)) < 0)
-        return ret;
 
-    avctx->pix_fmt = PIX_FMT_PAL8;
-    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);
-
-    if (s->picture.data[0])
-        avctx->release_buffer(avctx, &s->picture);
-    if ((ret = avctx->get_buffer(avctx, &s->picture)) < 0) {
-        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return ret;
+    if (buf_size >= 6) {
+        s->keyframe = memcmp(s->bytestream, gif87a_sig, 6) == 0 ||
+                      memcmp(s->bytestream, gif89a_sig, 6) == 0;
+    } else {
+        s->keyframe = 0;
     }
-    s->image_palette = (uint32_t *)s->picture.data[1];
-    ret = gif_parse_next_image(s);
+
+    if (s->keyframe) {
+        if ((ret = gif_read_header1(s)) < 0)
+            return ret;
+
+        if ((ret = av_image_check_size(s->screen_width, s->screen_height, 0, avctx)) < 0)
+            return ret;
+        avcodec_set_dimensions(avctx, s->screen_width, s->screen_height);
+
+        if (s->picture.data[0])
+            avctx->release_buffer(avctx, &s->picture);
+
+        if ((ret = avctx->get_buffer(avctx, &s->picture)) < 0) {
+            av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+            return ret;
+        }
+
+        s->picture.pict_type = AV_PICTURE_TYPE_I;
+        s->picture.key_frame = 1;
+    } else {
+        if ((ret = avctx->reget_buffer(avctx, &s->picture)) < 0) {
+            av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
+            return ret;
+        }
+
+        s->picture.pict_type = AV_PICTURE_TYPE_P;
+        s->picture.key_frame = 0;
+    }
+
+    ret = gif_parse_next_image(s, got_picture);
     if (ret < 0)
         return ret;
+    else if (*got_picture)
+        *picture = s->picture;
 
-    *picture = s->picture;
-    *data_size = sizeof(AVPicture);
     return s->bytestream - buf;
 }
 
@@ -322,9 +520,29 @@
     ff_lzw_decode_close(&s->lzw);
     if(s->picture.data[0])
         avctx->release_buffer(avctx, &s->picture);
+
+    av_freep(&s->idx_line);
+    av_freep(&s->stored_img);
+
     return 0;
 }
 
+static const AVOption options[] = {
+    { "trans_color", "color value (ARGB) that is used instead of transparent color",
+      offsetof(GifState, trans_color), AV_OPT_TYPE_INT,
+      {.i64 = GIF_TRANSPARENT_COLOR}, 0, 0xffffffff,
+      AV_OPT_FLAG_DECODING_PARAM|AV_OPT_FLAG_VIDEO_PARAM },
+    { NULL },
+};
+
+static const AVClass decoder_class = {
+    .class_name = "gif decoder",
+    .item_name  = av_default_item_name,
+    .option     = options,
+    .version    = LIBAVUTIL_VERSION_INT,
+    .category   = AV_CLASS_CATEGORY_DECODER,
+};
+
 AVCodec ff_gif_decoder = {
     .name           = "gif",
     .type           = AVMEDIA_TYPE_VIDEO,
@@ -335,4 +553,5 @@
     .decode         = gif_decode_frame,
     .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("GIF (Graphics Interchange Format)"),
+    .priv_class     = &decoder_class,
 };
diff --git a/libavcodec/gsm_parser.c b/libavcodec/gsm_parser.c
index 1d381fc..dd26f7d 100644
--- a/libavcodec/gsm_parser.c
+++ b/libavcodec/gsm_parser.c
@@ -54,7 +54,10 @@
             s->duration   = GSM_FRAME_SIZE * 2;
             break;
         default:
-            return AVERROR(EINVAL);
+            *poutbuf      = buf;
+            *poutbuf_size = buf_size;
+            av_log(avctx, AV_LOG_ERROR, "Invalid codec_id\n");
+            return buf_size;
         }
     }
 
diff --git a/libavcodec/gsmdec.c b/libavcodec/gsmdec.c
index fc042fb..f6f99bd 100644
--- a/libavcodec/gsmdec.c
+++ b/libavcodec/gsmdec.c
@@ -24,6 +24,7 @@
  * GSM decoder
  */
 
+#include "libavutil/channel_layout.h"
 #include "avcodec.h"
 #include "get_bits.h"
 #include "msgsmdec.h"
@@ -34,10 +35,11 @@
 {
     GSMContext *s = avctx->priv_data;
 
-    avctx->channels = 1;
+    avctx->channels       = 1;
+    avctx->channel_layout = AV_CH_LAYOUT_MONO;
     if (!avctx->sample_rate)
         avctx->sample_rate = 8000;
-    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    avctx->sample_fmt     = AV_SAMPLE_FMT_S16;
 
     switch (avctx->codec_id) {
     case AV_CODEC_ID_GSM:
diff --git a/libavcodec/gsmdec_data.h b/libavcodec/gsmdec_data.h
index 3eb30b8..6abe2b4 100644
--- a/libavcodec/gsmdec_data.h
+++ b/libavcodec/gsmdec_data.h
@@ -25,7 +25,7 @@
 #include <stdint.h>
 #include "avcodec.h"
 
-typedef struct {
+typedef struct GSMContext {
     AVFrame frame;
     // Contains first 120 elements from the previous frame
     // (used by long_term_synth according to the "lag"),
diff --git a/libavcodec/h261dec.c b/libavcodec/h261dec.c
index 6be02ae..9bd6b20 100644
--- a/libavcodec/h261dec.c
+++ b/libavcodec/h261dec.c
@@ -86,7 +86,7 @@
 
     s->out_format = FMT_H261;
     s->low_delay= 1;
-    avctx->pix_fmt= PIX_FMT_YUV420P;
+    avctx->pix_fmt= AV_PIX_FMT_YUV420P;
 
     s->codec_id= avctx->codec->id;
 
diff --git a/libavcodec/h261enc.c b/libavcodec/h261enc.c
index a14da0d..29bee5d 100644
--- a/libavcodec/h261enc.c
+++ b/libavcodec/h261enc.c
@@ -332,7 +332,7 @@
     .init           = ff_MPV_encode_init,
     .encode2        = ff_MPV_encode_picture,
     .close          = ff_MPV_encode_end,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUV420P, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("H.261"),
     .priv_class     = &h261_class,
 };
diff --git a/libavcodec/h263.h b/libavcodec/h263.h
index 91dd548..a8d266d 100644
--- a/libavcodec/h263.h
+++ b/libavcodec/h263.h
@@ -110,7 +110,7 @@
 
 void ff_clean_h263_qscales(MpegEncContext *s);
 int ff_h263_resync(MpegEncContext *s);
-const uint8_t *ff_h263_find_resync_marker(const uint8_t *p, const uint8_t *end);
+const uint8_t *ff_h263_find_resync_marker(MpegEncContext *s, const uint8_t *p, const uint8_t *end);
 int ff_h263_get_gob_height(MpegEncContext *s);
 void ff_h263_encode_motion(MpegEncContext * s, int val, int f_code);
 
diff --git a/libavcodec/h263dec.c b/libavcodec/h263dec.c
index e4328cd..3fff1d6 100644
--- a/libavcodec/h263dec.c
+++ b/libavcodec/h263dec.c
@@ -60,7 +60,7 @@
     s->decode_mb= ff_h263_decode_mb;
     s->low_delay= 1;
     if (avctx->codec->id == AV_CODEC_ID_MSS2)
-        avctx->pix_fmt = PIX_FMT_YUV420P;
+        avctx->pix_fmt = AV_PIX_FMT_YUV420P;
     else
         avctx->pix_fmt = avctx->get_format(avctx, avctx->codec->pix_fmts);
     s->unrestricted_mv= 1;
@@ -168,7 +168,7 @@
 
     if (s->avctx->hwaccel) {
         const uint8_t *start= s->gb.buffer + get_bits_count(&s->gb)/8;
-        const uint8_t *end  = ff_h263_find_resync_marker(start + 1, s->gb.buffer_end);
+        const uint8_t *end  = ff_h263_find_resync_marker(s, start + 1, s->gb.buffer_end);
         skip_bits_long(&s->gb, 8*(end - start));
         return s->avctx->hwaccel->decode_slice(s->avctx, start, end - start);
     }
@@ -266,7 +266,7 @@
         s->mb_x= 0;
     }
 
-    assert(s->mb_x==0 && s->mb_y==s->mb_height);
+    av_assert1(s->mb_x==0 && s->mb_y==s->mb_height);
 
     if(s->codec_id==AV_CODEC_ID_MPEG4
        && (s->workaround_bugs&FF_BUG_AUTODETECT)
@@ -703,7 +703,7 @@
             s->error_status_table[s->mb_num-1]= ER_MB_ERROR;
         }
 
-    assert(s->bitstream_buffer_size==0);
+    av_assert1(s->bitstream_buffer_size==0);
 frame_end:
     /* divx 5.01+ bistream reorder stuff */
     if(s->codec_id==AV_CODEC_ID_MPEG4 && s->divx_packed){
diff --git a/libavcodec/h264.c b/libavcodec/h264.c
index 9c79f35..f9b8fc1 100644
--- a/libavcodec/h264.c
+++ b/libavcodec/h264.c
@@ -25,8 +25,6 @@
  * @author Michael Niedermayer <michaelni@gmx.at>
  */
 
-#define UNCHECKED_BITSTREAM_READER 1
-
 #include "libavutil/imgutils.h"
 #include "libavutil/opt.h"
 #include "internal.h"
@@ -66,12 +64,12 @@
    14,14,14,14,
 };
 
-static const enum PixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
-    PIX_FMT_DXVA2_VLD,
-    PIX_FMT_VAAPI_VLD,
-    PIX_FMT_VDA_VLD,
-    PIX_FMT_YUVJ420P,
-    PIX_FMT_NONE
+static const enum AVPixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
+    AV_PIX_FMT_DXVA2_VLD,
+    AV_PIX_FMT_VAAPI_VLD,
+    AV_PIX_FMT_VDA_VLD,
+    AV_PIX_FMT_YUVJ420P,
+    AV_PIX_FMT_NONE
 };
 
 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
@@ -388,7 +386,7 @@
     } else {
         int i;
 
-        assert(IS_8X8(mb_type));
+        av_assert2(IS_8X8(mb_type));
 
         for (i = 0; i < 4; i++) {
             const int sub_mb_type = h->sub_mb_type[i];
@@ -420,7 +418,7 @@
                                   nrefs);
             } else {
                 int j;
-                assert(IS_SUB_4X4(sub_mb_type));
+                av_assert2(IS_SUB_4X4(sub_mb_type));
                 for (j = 0; j < 4; j++) {
                     int sub_y_offset = y_offset + 2 * (j & 2);
                     get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
@@ -1002,7 +1000,7 @@
     memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
 }
 
-int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
+static int ff_h264_decode_extradata_internal(H264Context *h, const uint8_t *buf, int size)
 {
     AVCodecContext *avctx = h->s.avctx;
 
@@ -1059,6 +1057,15 @@
     return size;
 }
 
+int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
+{
+    int ret;
+    h->decoding_extradata = 1;
+    ret = ff_h264_decode_extradata_internal(h, buf, size);
+    h->decoding_extradata = 0;
+    return ret;
+}
+
 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
 {
     H264Context *h = avctx->priv_data;
@@ -1095,8 +1102,12 @@
     h->x264_build   = -1;
     ff_h264_reset_sei(h);
     if (avctx->codec_id == AV_CODEC_ID_H264) {
-        if (avctx->ticks_per_frame == 1)
-            s->avctx->time_base.den *= 2;
+        if (avctx->ticks_per_frame == 1) {
+            if(s->avctx->time_base.den < INT_MAX/2) {
+                s->avctx->time_base.den *= 2;
+            } else
+                s->avctx->time_base.num /= 2;
+        }
         avctx->ticks_per_frame = 2;
     }
 
@@ -1112,6 +1123,8 @@
         s->low_delay           = 0;
     }
 
+    ff_init_cabac_states();
+
     return 0;
 }
 
@@ -1787,7 +1800,7 @@
                         uint64_t tr_high;
                         if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
                             const int topright_avail = (h->topright_samples_available << i) & 0x8000;
-                            assert(s->mb_y || linesize <= block_offset[i]);
+                            av_assert2(s->mb_y || linesize <= block_offset[i]);
                             if (!topright_avail) {
                                 if (pixel_shift) {
                                     tr_high  = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
@@ -2395,7 +2408,7 @@
     if (slice_type > 9) {
         av_log(h->s.avctx, AV_LOG_ERROR,
                "slice type too large (%d) at %d %d\n",
-               h->slice_type, s->mb_x, s->mb_y);
+               slice_type, s->mb_x, s->mb_y);
         return -1;
     }
     if (slice_type > 4) {
@@ -2449,7 +2462,7 @@
 
     if(must_reinit && (h != h0 || (s->avctx->active_thread_type & FF_THREAD_FRAME))) {
         av_log_missing_feature(s->avctx,
-                                "Width/height/bit depth/chroma idc changing with threads is", 0);
+                                "Width/height/bit depth/chroma idc changing with threads", 0);
         return AVERROR_PATCHWELCOME;   // width / height changed during parallelized decoding
     }
 
@@ -2542,60 +2555,60 @@
         case 9:
             if (CHROMA444) {
                 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
-                    s->avctx->pix_fmt = PIX_FMT_GBRP9;
+                    s->avctx->pix_fmt = AV_PIX_FMT_GBRP9;
                 } else
-                    s->avctx->pix_fmt = PIX_FMT_YUV444P9;
+                    s->avctx->pix_fmt = AV_PIX_FMT_YUV444P9;
             } else if (CHROMA422)
-                s->avctx->pix_fmt = PIX_FMT_YUV422P9;
+                s->avctx->pix_fmt = AV_PIX_FMT_YUV422P9;
             else
-                s->avctx->pix_fmt = PIX_FMT_YUV420P9;
+                s->avctx->pix_fmt = AV_PIX_FMT_YUV420P9;
             break;
         case 10:
             if (CHROMA444) {
                 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
-                    s->avctx->pix_fmt = PIX_FMT_GBRP10;
+                    s->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
                 } else
-                    s->avctx->pix_fmt = PIX_FMT_YUV444P10;
+                    s->avctx->pix_fmt = AV_PIX_FMT_YUV444P10;
             } else if (CHROMA422)
-                s->avctx->pix_fmt = PIX_FMT_YUV422P10;
+                s->avctx->pix_fmt = AV_PIX_FMT_YUV422P10;
             else
-                s->avctx->pix_fmt = PIX_FMT_YUV420P10;
+                s->avctx->pix_fmt = AV_PIX_FMT_YUV420P10;
             break;
         case 12:
             if (CHROMA444) {
                 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
-                    s->avctx->pix_fmt = PIX_FMT_GBRP12;
+                    s->avctx->pix_fmt = AV_PIX_FMT_GBRP12;
                 } else
-                    s->avctx->pix_fmt = PIX_FMT_YUV444P12;
+                    s->avctx->pix_fmt = AV_PIX_FMT_YUV444P12;
             } else if (CHROMA422)
-                s->avctx->pix_fmt = PIX_FMT_YUV422P12;
+                s->avctx->pix_fmt = AV_PIX_FMT_YUV422P12;
             else
-                s->avctx->pix_fmt = PIX_FMT_YUV420P12;
+                s->avctx->pix_fmt = AV_PIX_FMT_YUV420P12;
             break;
         case 14:
             if (CHROMA444) {
                 if (s->avctx->colorspace == AVCOL_SPC_RGB) {
-                    s->avctx->pix_fmt = PIX_FMT_GBRP14;
+                    s->avctx->pix_fmt = AV_PIX_FMT_GBRP14;
                 } else
-                    s->avctx->pix_fmt = PIX_FMT_YUV444P14;
+                    s->avctx->pix_fmt = AV_PIX_FMT_YUV444P14;
             } else if (CHROMA422)
-                s->avctx->pix_fmt = PIX_FMT_YUV422P14;
+                s->avctx->pix_fmt = AV_PIX_FMT_YUV422P14;
             else
-                s->avctx->pix_fmt = PIX_FMT_YUV420P14;
+                s->avctx->pix_fmt = AV_PIX_FMT_YUV420P14;
             break;
         case 8:
             if (CHROMA444) {
-                    s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ444P
-                                                                                  : PIX_FMT_YUV444P;
+                    s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
+                                                                                  : AV_PIX_FMT_YUV444P;
                     if (s->avctx->colorspace == AVCOL_SPC_RGB) {
-                        s->avctx->pix_fmt = PIX_FMT_GBR24P;
+                        s->avctx->pix_fmt = AV_PIX_FMT_GBR24P;
                         av_log(h->s.avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
                     } else if (s->avctx->colorspace == AVCOL_SPC_YCGCO) {
                         av_log(h->s.avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
                     }
             } else if (CHROMA422) {
-                s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ422P
-                                                                              : PIX_FMT_YUV422P;
+                s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
+                                                                              : AV_PIX_FMT_YUV422P;
             } else {
                 s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
                                                          s->avctx->codec->pix_fmts ?
@@ -2694,6 +2707,11 @@
             s->picture_structure = last_pic_structure;
             s->dropable          = last_pic_dropable;
             return AVERROR_INVALIDDATA;
+        } else if (!s->current_picture_ptr) {
+            av_log(s->avctx, AV_LOG_ERROR,
+                   "unset current_picture_ptr on %d. slice\n",
+                   h0->current_slice + 1);
+            return AVERROR_INVALIDDATA;
         }
     } else {
         /* Shorten frame num gaps so we don't have to allocate reference
@@ -2860,7 +2878,7 @@
 
     s->current_picture_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
 
-    assert(s->mb_num == s->mb_width * s->mb_height);
+    av_assert1(s->mb_num == s->mb_width * s->mb_height);
     if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
         first_mb_in_slice >= s->mb_num) {
         av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
@@ -2870,7 +2888,7 @@
     s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
     if (s->picture_structure == PICT_BOTTOM_FIELD)
         s->resync_mb_y = s->mb_y = s->mb_y + 1;
-    assert(s->mb_y < s->mb_height);
+    av_assert1(s->mb_y < s->mb_height);
 
     if (s->picture_structure == PICT_FRAME) {
         h->curr_pic_num = h->frame_num;
@@ -2916,11 +2934,11 @@
 
         if (num_ref_idx_active_override_flag) {
             h->ref_count[0] = get_ue_golomb(&s->gb) + 1;
-            if (h->slice_type_nos == AV_PICTURE_TYPE_B)
+            if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
                 h->ref_count[1] = get_ue_golomb(&s->gb) + 1;
-            else
+            } else
                 // full range is spec-ok in this case, even for frames
-                max[1] = 31;
+                h->ref_count[1] = 1;
         }
 
         if (h->ref_count[0]-1 > max[0] || h->ref_count[1]-1 > max[1]){
@@ -2947,10 +2965,12 @@
 
     if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
         s->last_picture_ptr = &h->ref_list[0][0];
+        s->last_picture_ptr->owner2 = s;
         ff_copy_picture(&s->last_picture, s->last_picture_ptr);
     }
     if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
         s->next_picture_ptr = &h->ref_list[1][0];
+        s->next_picture_ptr->owner2 = s;
         ff_copy_picture(&s->next_picture, s->next_picture_ptr);
     }
 
@@ -3533,7 +3553,6 @@
         align_get_bits(&s->gb);
 
         /* init cabac */
-        ff_init_cabac_states();
         ff_init_cabac_decoder(&h->cabac,
                               s->gb.buffer + get_bits_count(&s->gb) / 8,
                               (get_bits_left(&s->gb) + 7) / 8);
@@ -3747,6 +3766,13 @@
         ff_h264_reset_sei(h);
     }
 
+    if (h->nal_length_size == 4) {
+        if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
+            h->is_avc = 0;
+        }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
+            h->is_avc = 1;
+    }
+
     for (; pass <= 1; pass++) {
         buf_index     = 0;
         context_count = 0;
@@ -3848,6 +3874,20 @@
 
 again:
             err = 0;
+
+            if (h->decoding_extradata) {
+                switch (hx->nal_unit_type) {
+                case NAL_IDR_SLICE:
+                case NAL_SLICE:
+                case NAL_DPA:
+                case NAL_DPB:
+                case NAL_DPC:
+                case NAL_AUXILIARY_SLICE:
+                    av_log(h->s.avctx, AV_LOG_WARNING, "Ignoring NAL %d in global header\n", hx->nal_unit_type);
+                    hx->nal_unit_type = NAL_FILLER_DATA;
+                }
+            }
+
             switch (hx->nal_unit_type) {
             case NAL_IDR_SLICE:
                 if (h->nal_unit_type != NAL_IDR_SLICE) {
@@ -3947,11 +3987,12 @@
                 hx->inter_gb_ptr = &hx->inter_gb;
 
                 av_log(h->s.avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
-                return AVERROR_PATCHWELCOME;
+                break;
 
                 if (hx->redundant_pic_count == 0 &&
                     hx->intra_gb_ptr &&
                     hx->s.data_partitioning &&
+                    s->current_picture_ptr &&
                     s->context_initialized &&
                     (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
                     (avctx->skip_frame < AVDISCARD_BIDIR  ||
@@ -3972,6 +4013,8 @@
                            "SPS decoding failure, trying again with the complete NAL\n");
                     if (h->is_avc)
                         av_assert0(next_avc - buf_index + consumed == nalsize);
+                    if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
+                        break;
                     init_get_bits(&s->gb, &buf[buf_index + 1 - consumed],
                                   8*(next_avc - buf_index + consumed - 1));
                     ff_h264_decode_seq_parameter_set(h);
@@ -3979,8 +4022,15 @@
 
                 if (s->flags & CODEC_FLAG_LOW_DELAY ||
                     (h->sps.bitstream_restriction_flag &&
-                     !h->sps.num_reorder_frames))
-                    s->low_delay = 1;
+                     !h->sps.num_reorder_frames)) {
+                    if (s->avctx->has_b_frames > 1 || h->delayed_pic[0])
+                        av_log(avctx, AV_LOG_WARNING, "Delayed frames seen "
+                               "reenabling low delay requires a codec "
+                               "flush.\n");
+                        else
+                            s->low_delay = 1;
+                }
+
                 if (avctx->has_b_frames < 2)
                     avctx->has_b_frames = !s->low_delay;
                 break;
@@ -4197,23 +4247,23 @@
 };
 
 static const AVOption h264_options[] = {
-    {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 1, 0},
-    {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 4, 0},
+    {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
+    {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
     {NULL}
 };
 
 static const AVClass h264_class = {
-    "H264 Decoder",
-    av_default_item_name,
-    h264_options,
-    LIBAVUTIL_VERSION_INT,
+    .class_name = "H264 Decoder",
+    .item_name  = av_default_item_name,
+    .option     = h264_options,
+    .version    = LIBAVUTIL_VERSION_INT,
 };
 
 static const AVClass h264_vdpau_class = {
-    "H264 VDPAU Decoder",
-    av_default_item_name,
-    h264_options,
-    LIBAVUTIL_VERSION_INT,
+    .class_name = "H264 VDPAU Decoder",
+    .item_name  = av_default_item_name,
+    .option     = h264_options,
+    .version    = LIBAVUTIL_VERSION_INT,
 };
 
 AVCodec ff_h264_decoder = {
@@ -4247,8 +4297,8 @@
     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
     .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},
+    .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
+                                                   AV_PIX_FMT_NONE},
     .profiles       = NULL_IF_CONFIG_SMALL(profiles),
     .priv_class     = &h264_vdpau_class,
 };
diff --git a/libavcodec/h264.h b/libavcodec/h264.h
index 4d07a8a..00a1fc3 100644
--- a/libavcodec/h264.h
+++ b/libavcodec/h264.h
@@ -130,6 +130,7 @@
 typedef enum {
     SEI_BUFFERING_PERIOD            = 0,   ///< buffering period (H.264, D.1.1)
     SEI_TYPE_PIC_TIMING             = 1,   ///< picture timing
+    SEI_TYPE_USER_DATA_ITU_T_T35    = 4,   ///< user data registered by ITU-T Recommendation T.35
     SEI_TYPE_USER_DATA_UNREGISTERED = 5,   ///< unregistered user data
     SEI_TYPE_RECOVERY_POINT         = 6    ///< recovery point (frame # to decoder sync)
 } SEI_Type;
@@ -446,6 +447,7 @@
     int nal_unit_type;
     uint8_t *rbsp_buffer[2];
     unsigned int rbsp_buffer_size[2];
+    int decoding_extradata;
 
     /**
      * Used to parse AVC variant of h264
diff --git a/libavcodec/h264_cabac.c b/libavcodec/h264_cabac.c
index 7e8947b..015b02e 100644
--- a/libavcodec/h264_cabac.c
+++ b/libavcodec/h264_cabac.c
@@ -1863,6 +1863,7 @@
     int dct8x8_allowed= h->pps.transform_8x8_mode;
     int decode_chroma = h->sps.chroma_format_idc == 1 || h->sps.chroma_format_idc == 2;
     const int pixel_shift = h->pixel_shift;
+    unsigned local_ref_count[2];
 
     mb_xy = h->mb_xy = s->mb_x + s->mb_y*s->mb_stride;
 
@@ -2003,10 +2004,8 @@
         return 0;
     }
 
-    if(MB_MBAFF){
-        h->ref_count[0] <<= 1;
-        h->ref_count[1] <<= 1;
-    }
+    local_ref_count[0] = h->ref_count[0] << MB_MBAFF;
+    local_ref_count[1] = h->ref_count[1] << MB_MBAFF;
 
     fill_decode_caches(h, mb_type);
 
@@ -2076,10 +2075,10 @@
                 for( i = 0; i < 4; i++ ) {
                     if(IS_DIRECT(h->sub_mb_type[i])) continue;
                     if(IS_DIR(h->sub_mb_type[i], 0, list)){
-                        if( h->ref_count[list] > 1 ){
+                        if (local_ref_count[list] > 1) {
                             ref[list][i] = decode_cabac_mb_ref( h, list, 4*i );
-                            if(ref[list][i] >= (unsigned)h->ref_count[list]){
-                                av_log(s->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref[list][i], h->ref_count[list]);
+                            if (ref[list][i] >= (unsigned)local_ref_count[list]) {
+                                av_log(s->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref[list][i], local_ref_count[list]);
                                 return -1;
                             }
                         }else
@@ -2162,10 +2161,10 @@
             for(list=0; list<h->list_count; list++){
                 if(IS_DIR(mb_type, 0, list)){
                     int ref;
-                    if(h->ref_count[list] > 1){
+                    if (local_ref_count[list] > 1) {
                         ref= decode_cabac_mb_ref(h, list, 0);
-                        if(ref >= (unsigned)h->ref_count[list]){
-                            av_log(s->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref, h->ref_count[list]);
+                        if (ref >= (unsigned)local_ref_count[list]) {
+                            av_log(s->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref, local_ref_count[list]);
                             return -1;
                         }
                     }else
@@ -2190,10 +2189,10 @@
                     for(i=0; i<2; i++){
                         if(IS_DIR(mb_type, i, list)){
                             int ref;
-                            if(h->ref_count[list] > 1){
+                            if (local_ref_count[list] > 1) {
                                 ref= decode_cabac_mb_ref( h, list, 8*i );
-                                if(ref >= (unsigned)h->ref_count[list]){
-                                    av_log(s->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref, h->ref_count[list]);
+                                if (ref >= (unsigned)local_ref_count[list]) {
+                                    av_log(s->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref, local_ref_count[list]);
                                     return -1;
                                 }
                             }else
@@ -2225,10 +2224,10 @@
                     for(i=0; i<2; i++){
                         if(IS_DIR(mb_type, i, list)){ //FIXME optimize
                             int ref;
-                            if(h->ref_count[list] > 1){
+                            if (local_ref_count[list] > 1) {
                                 ref= decode_cabac_mb_ref( h, list, 4*i );
-                                if(ref >= (unsigned)h->ref_count[list]){
-                                    av_log(s->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref, h->ref_count[list]);
+                                if (ref >= (unsigned)local_ref_count[list]) {
+                                    av_log(s->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref, local_ref_count[list]);
                                     return -1;
                                 }
                             }else
@@ -2266,6 +2265,11 @@
         cbp  = decode_cabac_mb_cbp_luma( h );
         if(decode_chroma)
             cbp |= decode_cabac_mb_cbp_chroma( h ) << 4;
+    } else {
+        if (!decode_chroma && cbp>15) {
+            av_log(s->avctx, AV_LOG_ERROR, "gray chroma\n");
+            return AVERROR_INVALIDDATA;
+        }
     }
 
     h->cbp_table[mb_xy] = h->cbp = cbp;
@@ -2401,10 +2405,5 @@
     s->current_picture.f.qscale_table[mb_xy] = s->qscale;
     write_back_non_zero_count(h);
 
-    if(MB_MBAFF){
-        h->ref_count[0] >>= 1;
-        h->ref_count[1] >>= 1;
-    }
-
     return 0;
 }
diff --git a/libavcodec/h264_cavlc.c b/libavcodec/h264_cavlc.c
index 06e1ba7..cfad27c 100644
--- a/libavcodec/h264_cavlc.c
+++ b/libavcodec/h264_cavlc.c
@@ -699,6 +699,7 @@
     int dct8x8_allowed= h->pps.transform_8x8_mode;
     int decode_chroma = h->sps.chroma_format_idc == 1 || h->sps.chroma_format_idc == 2;
     const int pixel_shift = h->pixel_shift;
+    unsigned local_ref_count[2];
 
     mb_xy = h->mb_xy = s->mb_x + s->mb_y*s->mb_stride;
 
@@ -784,10 +785,8 @@
         return 0;
     }
 
-    if(MB_MBAFF){
-        h->ref_count[0] <<= 1;
-        h->ref_count[1] <<= 1;
-    }
+    local_ref_count[0] = h->ref_count[0] << MB_MBAFF;
+    local_ref_count[1] = h->ref_count[1] << MB_MBAFF;
 
     fill_decode_neighbors(h, mb_type);
     fill_decode_caches(h, mb_type);
@@ -868,7 +867,7 @@
         }
 
         for(list=0; list<h->list_count; list++){
-            int ref_count= IS_REF0(mb_type) ? 1 : h->ref_count[list];
+            int ref_count= IS_REF0(mb_type) ? 1 : local_ref_count[list];
             for(i=0; i<4; i++){
                 if(IS_DIRECT(h->sub_mb_type[i])) continue;
                 if(IS_DIR(h->sub_mb_type[i], 0, list)){
@@ -948,13 +947,13 @@
             for(list=0; list<h->list_count; list++){
                     unsigned int val;
                     if(IS_DIR(mb_type, 0, list)){
-                        if(h->ref_count[list]==1){
+                        if(local_ref_count[list]==1){
                             val= 0;
-                        }else if(h->ref_count[list]==2){
+                        }else if(local_ref_count[list]==2){
                             val= get_bits1(&s->gb)^1;
                         }else{
                             val= get_ue_golomb_31(&s->gb);
-                            if(val >= h->ref_count[list]){
+                            if(val >= local_ref_count[list]){
                                 av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
                                 return -1;
                             }
@@ -978,13 +977,13 @@
                     for(i=0; i<2; i++){
                         unsigned int val;
                         if(IS_DIR(mb_type, i, list)){
-                            if(h->ref_count[list] == 1){
+                            if(local_ref_count[list] == 1){
                                 val= 0;
-                            }else if(h->ref_count[list] == 2){
+                            }else if(local_ref_count[list] == 2){
                                 val= get_bits1(&s->gb)^1;
                             }else{
                                 val= get_ue_golomb_31(&s->gb);
-                                if(val >= h->ref_count[list]){
+                                if(val >= local_ref_count[list]){
                                     av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
                                     return -1;
                                 }
@@ -1015,13 +1014,13 @@
                     for(i=0; i<2; i++){
                         unsigned int val;
                         if(IS_DIR(mb_type, i, list)){ //FIXME optimize
-                            if(h->ref_count[list]==1){
+                            if(local_ref_count[list]==1){
                                 val= 0;
-                            }else if(h->ref_count[list]==2){
+                            }else if(local_ref_count[list]==2){
                                 val= get_bits1(&s->gb)^1;
                             }else{
                                 val= get_ue_golomb_31(&s->gb);
-                                if(val >= h->ref_count[list]){
+                                if(val >= local_ref_count[list]){
                                     av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
                                     return -1;
                                 }
@@ -1070,6 +1069,11 @@
             if(IS_INTRA4x4(mb_type)) cbp= golomb_to_intra4x4_cbp_gray[cbp];
             else                     cbp= golomb_to_inter_cbp_gray[cbp];
         }
+    } else {
+        if (!decode_chroma && cbp>15) {
+            av_log(s->avctx, AV_LOG_ERROR, "gray chroma\n");
+            return AVERROR_INVALIDDATA;
+        }
     }
 
     if(dct8x8_allowed && (cbp&15) && !IS_INTRA(mb_type)){
@@ -1161,10 +1165,5 @@
     s->current_picture.f.qscale_table[mb_xy] = s->qscale;
     write_back_non_zero_count(h);
 
-    if(MB_MBAFF){
-        h->ref_count[0] >>= 1;
-        h->ref_count[1] >>= 1;
-    }
-
     return 0;
 }
diff --git a/libavcodec/h264_direct.c b/libavcodec/h264_direct.c
index ce395a3..9ef5862 100644
--- a/libavcodec/h264_direct.c
+++ b/libavcodec/h264_direct.c
@@ -131,7 +131,7 @@
         h->col_fieldoff = 2 * h->ref_list[1][0].f.reference - 3;
     }
 
-    if (cur->f.pict_type != AV_PICTURE_TYPE_B || h->direct_spatial_mv_pred)
+    if (h->slice_type_nos != AV_PICTURE_TYPE_B || h->direct_spatial_mv_pred)
         return;
 
     for(list=0; list<2; list++){
diff --git a/libavcodec/h264_ps.c b/libavcodec/h264_ps.c
index cdc6b07..28d3cbc 100644
--- a/libavcodec/h264_ps.c
+++ b/libavcodec/h264_ps.c
@@ -367,7 +367,7 @@
     if(sps->profile_idc == 100 || sps->profile_idc == 110 ||
        sps->profile_idc == 122 || sps->profile_idc == 244 || sps->profile_idc ==  44 ||
        sps->profile_idc ==  83 || sps->profile_idc ==  86 || sps->profile_idc == 118 ||
-       sps->profile_idc == 128 ) {
+       sps->profile_idc == 128 || sps->profile_idc == 144) {
         sps->chroma_format_idc= get_ue_golomb_31(&s->gb);
         if (sps->chroma_format_idc > 3U) {
             av_log(h->s.avctx, AV_LOG_ERROR, "chroma_format_idc %d is illegal\n", sps->chroma_format_idc);
@@ -429,6 +429,8 @@
     }
 
     sps->ref_frame_count= get_ue_golomb_31(&s->gb);
+    if (h->s.avctx->codec_tag == MKTAG('S', 'M', 'V', '2'))
+        sps->ref_frame_count= FFMAX(2, sps->ref_frame_count);
     if(sps->ref_frame_count > MAX_PICTURE_COUNT-2 || sps->ref_frame_count > 16U){
         av_log(h->s.avctx, AV_LOG_ERROR, "too many reference frames\n");
         goto fail;
diff --git a/libavcodec/h264_refs.c b/libavcodec/h264_refs.c
index c15e928..812913a 100644
--- a/libavcodec/h264_refs.c
+++ b/libavcodec/h264_refs.c
@@ -123,10 +123,10 @@
         for(list= 0; list<2; list++){
             len= add_sorted(sorted    , h->short_ref, h->short_ref_count, cur_poc, 1^list);
             len+=add_sorted(sorted+len, h->short_ref, h->short_ref_count, cur_poc, 0^list);
-            assert(len<=32);
+            av_assert0(len<=32);
             len= build_def_list(h->default_ref_list[list]    , sorted     , len, 0, s->picture_structure);
             len+=build_def_list(h->default_ref_list[list]+len, h->long_ref, 16 , 1, s->picture_structure);
-            assert(len<=32);
+            av_assert0(len<=32);
 
             if(len < h->ref_count[list])
                 memset(&h->default_ref_list[list][len], 0, sizeof(Picture)*(h->ref_count[list] - len));
@@ -141,7 +141,7 @@
     }else{
         len = build_def_list(h->default_ref_list[0]    , h->short_ref, h->short_ref_count, 0, s->picture_structure);
         len+= build_def_list(h->default_ref_list[0]+len, h-> long_ref, 16                , 1, s->picture_structure);
-        assert(len <= 32);
+        av_assert0(len<=32);
         if(len < h->ref_count[0])
             memset(&h->default_ref_list[0][len], 0, sizeof(Picture)*(h->ref_count[0] - len));
     }
@@ -287,7 +287,7 @@
     for(list=0; list<h->list_count; list++){
         for(index= 0; index < h->ref_count[list]; index++){
             if (!h->ref_list[list][index].f.data[0]) {
-                av_log(h->s.avctx, AV_LOG_ERROR, "Missing reference picture\n");
+                av_log(h->s.avctx, AV_LOG_ERROR, "Missing reference picture, default is %d\n", h->default_ref_list[list][0].poc);
                 if (h->default_ref_list[list][0].f.data[0])
                     h->ref_list[list][index]= h->default_ref_list[list][0];
                 else
diff --git a/libavcodec/h264_sei.c b/libavcodec/h264_sei.c
index 81edeb2..62320e2 100644
--- a/libavcodec/h264_sei.c
+++ b/libavcodec/h264_sei.c
@@ -95,6 +95,43 @@
     return 0;
 }
 
+static int decode_user_data_itu_t_t35(H264Context *h, int size) {
+    MpegEncContext * const s = &h->s;
+    uint32_t user_identifier;
+    int dtg_active_format;
+
+    if (size < 7)
+        return -1;
+    size -= 7;
+
+    skip_bits(&s->gb, 8);   // country_code
+    skip_bits(&s->gb, 16);  // provider_code
+    user_identifier = get_bits_long(&s->gb, 32);
+
+    switch (user_identifier) {
+        case 0x44544731:    // "DTG1" - AFD_data
+            if (size < 1)
+                return -1;
+            skip_bits(&s->gb, 1);
+            if (get_bits(&s->gb, 1)) {
+                skip_bits(&s->gb, 6);
+                if (size < 2)
+                    return -1;
+                skip_bits(&s->gb, 4);
+                dtg_active_format = get_bits(&s->gb, 4);
+                s->avctx->dtg_active_format = dtg_active_format;
+            } else {
+                skip_bits(&s->gb, 6);
+            }
+            break;
+        default:
+            skip_bits(&s->gb, size * 8);
+            break;
+    }
+
+    return 0;
+}
+
 static int decode_unregistered_user_data(H264Context *h, int size){
     MpegEncContext * const s = &h->s;
     uint8_t user_data[16+256];
@@ -191,6 +228,10 @@
             if(decode_picture_timing(h) < 0)
                 return -1;
             break;
+        case SEI_TYPE_USER_DATA_ITU_T_T35:
+            if(decode_user_data_itu_t_t35(h, size) < 0)
+                return -1;
+            break;
         case SEI_TYPE_USER_DATA_UNREGISTERED:
             if(decode_unregistered_user_data(h, size) < 0)
                 return -1;
diff --git a/libavcodec/h264dsp.c b/libavcodec/h264dsp.c
index ce6545b..69d0536 100644
--- a/libavcodec/h264dsp.c
+++ b/libavcodec/h264dsp.c
@@ -130,5 +130,5 @@
 
     if (ARCH_ARM) ff_h264dsp_init_arm(c, bit_depth, chroma_format_idc);
     if (HAVE_ALTIVEC) ff_h264dsp_init_ppc(c, bit_depth, chroma_format_idc);
-    if (HAVE_MMX) ff_h264dsp_init_x86(c, bit_depth, chroma_format_idc);
+    if (ARCH_X86) ff_h264dsp_init_x86(c, bit_depth, chroma_format_idc);
 }
diff --git a/libavcodec/h264pred.c b/libavcodec/h264pred.c
index 2d8b9a4..f83924d 100644
--- a/libavcodec/h264pred.c
+++ b/libavcodec/h264pred.c
@@ -48,7 +48,9 @@
 #include "h264pred_template.c"
 #undef BIT_DEPTH
 
-static void pred4x4_vertical_vp8_c(uint8_t *src, const uint8_t *topright, int stride){
+static void pred4x4_vertical_vp8_c(uint8_t *src, const uint8_t *topright,
+                                   ptrdiff_t stride)
+{
     const unsigned lt = src[-1-1*stride];
     LOAD_TOP_EDGE
     LOAD_TOP_RIGHT_EDGE
@@ -63,7 +65,9 @@
     AV_WN32A(src+3*stride, v);
 }
 
-static void pred4x4_horizontal_vp8_c(uint8_t *src, const uint8_t *topright, int stride){
+static void pred4x4_horizontal_vp8_c(uint8_t *src, const uint8_t *topright,
+                                     ptrdiff_t stride)
+{
     const unsigned lt = src[-1-1*stride];
     LOAD_LEFT_EDGE
 
@@ -73,7 +77,9 @@
     AV_WN32A(src+3*stride, ((l2 + 2*l3 + l3 + 2) >> 2)*0x01010101);
 }
 
-static void pred4x4_down_left_svq3_c(uint8_t *src, const uint8_t *topright, int stride){
+static void pred4x4_down_left_svq3_c(uint8_t *src, const uint8_t *topright,
+                                     ptrdiff_t stride)
+{
     LOAD_TOP_EDGE
     LOAD_LEFT_EDGE
 
@@ -95,7 +101,9 @@
     src[3+3*stride]=(l3 + t3)>>1;
 }
 
-static void pred4x4_down_left_rv40_c(uint8_t *src, const uint8_t *topright, int stride){
+static void pred4x4_down_left_rv40_c(uint8_t *src, const uint8_t *topright,
+                                     ptrdiff_t stride)
+{
     LOAD_TOP_EDGE
     LOAD_TOP_RIGHT_EDGE
     LOAD_LEFT_EDGE
@@ -119,7 +127,10 @@
     src[3+3*stride]=(t6 + t7 + 1 + l6 + l7 + 1)>>2;
 }
 
-static void pred4x4_down_left_rv40_nodown_c(uint8_t *src, const uint8_t *topright, int stride){
+static void pred4x4_down_left_rv40_nodown_c(uint8_t *src,
+                                            const uint8_t *topright,
+                                            ptrdiff_t stride)
+{
     LOAD_TOP_EDGE
     LOAD_TOP_RIGHT_EDGE
     LOAD_LEFT_EDGE
@@ -142,8 +153,11 @@
     src[3+3*stride]=(t6 + t7 + 1 + 2*l3 + 1)>>2;
 }
 
-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){
+static void pred4x4_vertical_left_rv40(uint8_t *src, const uint8_t *topright,
+                                       ptrdiff_t stride,
+                                       const int l0, const int l1, const int l2,
+                                       const int l3, const int l4)
+{
     LOAD_TOP_EDGE
     LOAD_TOP_RIGHT_EDGE
 
@@ -165,20 +179,27 @@
     src[3+3*stride]=(t4 + 2*t5 + t6 + 2)>>2;
 }
 
-static void pred4x4_vertical_left_rv40_c(uint8_t *src, const uint8_t *topright, int stride){
+static void pred4x4_vertical_left_rv40_c(uint8_t *src, const uint8_t *topright,
+                                         ptrdiff_t 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, const uint8_t *topright, int stride){
+static void pred4x4_vertical_left_rv40_nodown_c(uint8_t *src,
+                                                const uint8_t *topright,
+                                                ptrdiff_t stride)
+{
     LOAD_LEFT_EDGE
 
     pred4x4_vertical_left_rv40(src, topright, stride, l0, l1, l2, l3, l3);
 }
 
-static void pred4x4_vertical_left_vp8_c(uint8_t *src, const uint8_t *topright, int stride){
+static void pred4x4_vertical_left_vp8_c(uint8_t *src, const uint8_t *topright,
+                                        ptrdiff_t stride)
+{
     LOAD_TOP_EDGE
     LOAD_TOP_RIGHT_EDGE
 
@@ -200,7 +221,9 @@
     src[3+3*stride]=(t5 + 2*t6 + t7 + 2)>>2;
 }
 
-static void pred4x4_horizontal_up_rv40_c(uint8_t *src, const uint8_t *topright, int stride){
+static void pred4x4_horizontal_up_rv40_c(uint8_t *src, const uint8_t *topright,
+                                         ptrdiff_t stride)
+{
     LOAD_LEFT_EDGE
     LOAD_DOWN_LEFT_EDGE
     LOAD_TOP_EDGE
@@ -224,7 +247,10 @@
     src[3+3*stride]=(l4 + 2*l5 + l6 + 2)>>2;
 }
 
-static void pred4x4_horizontal_up_rv40_nodown_c(uint8_t *src, const uint8_t *topright, int stride){
+static void pred4x4_horizontal_up_rv40_nodown_c(uint8_t *src,
+                                                const uint8_t *topright,
+                                                ptrdiff_t stride)
+{
     LOAD_LEFT_EDGE
     LOAD_TOP_EDGE
     LOAD_TOP_RIGHT_EDGE
@@ -247,7 +273,9 @@
     src[3+3*stride]=l3;
 }
 
-static void pred4x4_tm_vp8_c(uint8_t *src, const uint8_t *topright, int stride){
+static void pred4x4_tm_vp8_c(uint8_t *src, const uint8_t *topright,
+                             ptrdiff_t stride)
+{
     uint8_t *cm = ff_cropTbl + MAX_NEG_CROP - src[-1-stride];
     uint8_t *top = src-stride;
     int y;
@@ -262,15 +290,18 @@
     }
 }
 
-static void pred16x16_plane_svq3_c(uint8_t *src, int stride){
+static void pred16x16_plane_svq3_c(uint8_t *src, ptrdiff_t stride)
+{
     pred16x16_plane_compat_8_c(src, stride, 1, 0);
 }
 
-static void pred16x16_plane_rv40_c(uint8_t *src, int stride){
+static void pred16x16_plane_rv40_c(uint8_t *src, ptrdiff_t stride)
+{
     pred16x16_plane_compat_8_c(src, stride, 0, 1);
 }
 
-static void pred16x16_tm_vp8_c(uint8_t *src, int stride){
+static void pred16x16_tm_vp8_c(uint8_t *src, ptrdiff_t stride)
+{
     uint8_t *cm = ff_cropTbl + MAX_NEG_CROP - src[-1-stride];
     uint8_t *top = src-stride;
     int y;
@@ -297,7 +328,8 @@
     }
 }
 
-static void pred8x8_left_dc_rv40_c(uint8_t *src, int stride){
+static void pred8x8_left_dc_rv40_c(uint8_t *src, ptrdiff_t stride)
+{
     int i;
     unsigned dc0;
 
@@ -312,7 +344,8 @@
     }
 }
 
-static void pred8x8_top_dc_rv40_c(uint8_t *src, int stride){
+static void pred8x8_top_dc_rv40_c(uint8_t *src, ptrdiff_t stride)
+{
     int i;
     unsigned dc0;
 
@@ -327,7 +360,8 @@
     }
 }
 
-static void pred8x8_dc_rv40_c(uint8_t *src, int stride){
+static void pred8x8_dc_rv40_c(uint8_t *src, ptrdiff_t stride)
+{
     int i;
     unsigned dc0 = 0;
 
@@ -348,7 +382,8 @@
     }
 }
 
-static void pred8x8_tm_vp8_c(uint8_t *src, int stride){
+static void pred8x8_tm_vp8_c(uint8_t *src, ptrdiff_t stride)
+{
     uint8_t *cm = ff_cropTbl + MAX_NEG_CROP - src[-1-stride];
     uint8_t *top = src-stride;
     int y;
@@ -370,7 +405,9 @@
 /**
  * Set the intra prediction function pointers.
  */
-void ff_h264_pred_init(H264PredContext *h, int codec_id, const int bit_depth, const int chroma_format_idc){
+void ff_h264_pred_init(H264PredContext *h, int codec_id, const int bit_depth,
+                       const int chroma_format_idc)
+{
 //    MpegEncContext * const s = &h->s;
 
 #undef FUNC
@@ -549,5 +586,5 @@
     }
 
     if (ARCH_ARM) ff_h264_pred_init_arm(h, codec_id, bit_depth, chroma_format_idc);
-    if (HAVE_MMX) ff_h264_pred_init_x86(h, codec_id, bit_depth, chroma_format_idc);
+    if (ARCH_X86) ff_h264_pred_init_x86(h, codec_id, bit_depth, chroma_format_idc);
 }
diff --git a/libavcodec/h264pred.h b/libavcodec/h264pred.h
index d68f39b..33f3944 100644
--- a/libavcodec/h264pred.h
+++ b/libavcodec/h264pred.h
@@ -90,21 +90,23 @@
  * Context for storing H.264 prediction functions
  */
 typedef struct H264PredContext {
-    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 + 2])(uint8_t *src, int stride);
+    void(*pred4x4[9 + 3 + 3])(uint8_t *src, const uint8_t *topright,
+                              ptrdiff_t stride);
+    void(*pred8x8l[9 + 3])(uint8_t *src, int topleft, int topright,
+                           ptrdiff_t stride);
+    void(*pred8x8[4 + 3 + 4])(uint8_t *src, ptrdiff_t stride);
+    void(*pred16x16[4 + 3 + 2])(uint8_t *src, ptrdiff_t stride);
 
     void(*pred4x4_add[2])(uint8_t *pix /*align  4*/,
-                          const DCTELEM *block /*align 16*/, int stride);
+                          const DCTELEM *block /*align 16*/, ptrdiff_t stride);
     void(*pred8x8l_add[2])(uint8_t *pix /*align  8*/,
-                           const DCTELEM *block /*align 16*/, int stride);
+                           const DCTELEM *block /*align 16*/, ptrdiff_t stride);
     void(*pred8x8_add[3])(uint8_t *pix /*align  8*/,
                           const int *block_offset,
-                          const DCTELEM *block /*align 16*/, int stride);
+                          const DCTELEM *block /*align 16*/, ptrdiff_t stride);
     void(*pred16x16_add[3])(uint8_t *pix /*align 16*/,
                             const int *block_offset,
-                            const DCTELEM *block /*align 16*/, int stride);
+                            const DCTELEM *block /*align 16*/, ptrdiff_t stride);
 } H264PredContext;
 
 void ff_h264_pred_init(H264PredContext *h, int codec_id,
diff --git a/libavcodec/h264pred_template.c b/libavcodec/h264pred_template.c
index 3a1b1cf..f08fdf4 100644
--- a/libavcodec/h264pred_template.c
+++ b/libavcodec/h264pred_template.c
@@ -29,7 +29,9 @@
 
 #include "bit_depth_template.c"
 
-static void FUNCC(pred4x4_vertical)(uint8_t *_src, const uint8_t *topright, int _stride){
+static void FUNCC(pred4x4_vertical)(uint8_t *_src, const uint8_t *topright,
+                                    ptrdiff_t _stride)
+{
     pixel *src = (pixel*)_src;
     int stride = _stride>>(sizeof(pixel)-1);
     const pixel4 a= AV_RN4PA(src-stride);
@@ -40,7 +42,9 @@
     AV_WN4PA(src+3*stride, a);
 }
 
-static void FUNCC(pred4x4_horizontal)(uint8_t *_src, const uint8_t *topright, int _stride){
+static void FUNCC(pred4x4_horizontal)(uint8_t *_src, const uint8_t *topright,
+                                      ptrdiff_t _stride)
+{
     pixel *src = (pixel*)_src;
     int stride = _stride>>(sizeof(pixel)-1);
     AV_WN4PA(src+0*stride, PIXEL_SPLAT_X4(src[-1+0*stride]));
@@ -49,7 +53,9 @@
     AV_WN4PA(src+3*stride, PIXEL_SPLAT_X4(src[-1+3*stride]));
 }
 
-static void FUNCC(pred4x4_dc)(uint8_t *_src, const uint8_t *topright, int _stride){
+static void FUNCC(pred4x4_dc)(uint8_t *_src, const uint8_t *topright,
+                              ptrdiff_t _stride)
+{
     pixel *src = (pixel*)_src;
     int stride = _stride>>(sizeof(pixel)-1);
     const int dc= (  src[-stride] + src[1-stride] + src[2-stride] + src[3-stride]
@@ -62,7 +68,9 @@
     AV_WN4PA(src+3*stride, a);
 }
 
-static void FUNCC(pred4x4_left_dc)(uint8_t *_src, const uint8_t *topright, int _stride){
+static void FUNCC(pred4x4_left_dc)(uint8_t *_src, const uint8_t *topright,
+                                   ptrdiff_t _stride)
+{
     pixel *src = (pixel*)_src;
     int stride = _stride>>(sizeof(pixel)-1);
     const int dc= (  src[-1+0*stride] + src[-1+1*stride] + src[-1+2*stride] + src[-1+3*stride] + 2) >>2;
@@ -74,7 +82,9 @@
     AV_WN4PA(src+3*stride, a);
 }
 
-static void FUNCC(pred4x4_top_dc)(uint8_t *_src, const uint8_t *topright, int _stride){
+static void FUNCC(pred4x4_top_dc)(uint8_t *_src, const uint8_t *topright,
+                                  ptrdiff_t _stride)
+{
     pixel *src = (pixel*)_src;
     int stride = _stride>>(sizeof(pixel)-1);
     const int dc= (  src[-stride] + src[1-stride] + src[2-stride] + src[3-stride] + 2) >>2;
@@ -86,7 +96,9 @@
     AV_WN4PA(src+3*stride, a);
 }
 
-static void FUNCC(pred4x4_128_dc)(uint8_t *_src, const uint8_t *topright, int _stride){
+static void FUNCC(pred4x4_128_dc)(uint8_t *_src, const uint8_t *topright,
+                                  ptrdiff_t _stride)
+{
     pixel *src = (pixel*)_src;
     int stride = _stride>>(sizeof(pixel)-1);
     const pixel4 a = PIXEL_SPLAT_X4(1<<(BIT_DEPTH-1));
@@ -97,7 +109,9 @@
     AV_WN4PA(src+3*stride, a);
 }
 
-static void FUNCC(pred4x4_127_dc)(uint8_t *_src, const uint8_t *topright, int _stride){
+static void FUNCC(pred4x4_127_dc)(uint8_t *_src, const uint8_t *topright,
+                                  ptrdiff_t _stride)
+{
     pixel *src = (pixel*)_src;
     int stride = _stride>>(sizeof(pixel)-1);
     const pixel4 a = PIXEL_SPLAT_X4((1<<(BIT_DEPTH-1))-1);
@@ -108,7 +122,9 @@
     AV_WN4PA(src+3*stride, a);
 }
 
-static void FUNCC(pred4x4_129_dc)(uint8_t *_src, const uint8_t *topright, int _stride){
+static void FUNCC(pred4x4_129_dc)(uint8_t *_src, const uint8_t *topright,
+                                  ptrdiff_t _stride)
+{
     pixel *src = (pixel*)_src;
     int stride = _stride>>(sizeof(pixel)-1);
     const pixel4 a = PIXEL_SPLAT_X4((1<<(BIT_DEPTH-1))+1);
@@ -144,7 +160,9 @@
     const unsigned av_unused t2 = src[ 2-1*stride];\
     const unsigned av_unused t3 = src[ 3-1*stride];\
 
-static void FUNCC(pred4x4_down_right)(uint8_t *_src, const uint8_t *topright, int _stride){
+static void FUNCC(pred4x4_down_right)(uint8_t *_src, const uint8_t *topright,
+                                      ptrdiff_t _stride)
+{
     pixel *src = (pixel*)_src;
     int stride = _stride>>(sizeof(pixel)-1);
     const int lt= src[-1-1*stride];
@@ -169,7 +187,9 @@
     src[3+0*stride]=(t1 + 2*t2 + t3 + 2)>>2;
 }
 
-static void FUNCC(pred4x4_down_left)(uint8_t *_src, const uint8_t *_topright, int _stride){
+static void FUNCC(pred4x4_down_left)(uint8_t *_src, const uint8_t *_topright,
+                                     ptrdiff_t _stride)
+{
     pixel *src = (pixel*)_src;
     const pixel *topright = (const pixel*)_topright;
     int stride = _stride>>(sizeof(pixel)-1);
@@ -195,7 +215,10 @@
     src[3+3*stride]=(t6 + 3*t7 + 2)>>2;
 }
 
-static void FUNCC(pred4x4_vertical_right)(uint8_t *_src, const uint8_t *topright, int _stride){
+static void FUNCC(pred4x4_vertical_right)(uint8_t *_src,
+                                          const uint8_t *topright,
+                                          ptrdiff_t _stride)
+{
     pixel *src = (pixel*)_src;
     int stride = _stride>>(sizeof(pixel)-1);
     const int lt= src[-1-1*stride];
@@ -220,7 +243,10 @@
     src[0+3*stride]=(l0 + 2*l1 + l2 + 2)>>2;
 }
 
-static void FUNCC(pred4x4_vertical_left)(uint8_t *_src, const uint8_t *_topright, int _stride){
+static void FUNCC(pred4x4_vertical_left)(uint8_t *_src,
+                                         const uint8_t *_topright,
+                                         ptrdiff_t _stride)
+{
     pixel *src = (pixel*)_src;
     const pixel *topright = (const pixel*)_topright;
     int stride = _stride>>(sizeof(pixel)-1);
@@ -245,7 +271,9 @@
     src[3+3*stride]=(t4 + 2*t5 + t6 + 2)>>2;
 }
 
-static void FUNCC(pred4x4_horizontal_up)(uint8_t *_src, const uint8_t *topright, int _stride){
+static void FUNCC(pred4x4_horizontal_up)(uint8_t *_src, const uint8_t *topright,
+                                         ptrdiff_t _stride)
+{
     pixel *src = (pixel*)_src;
     int stride = _stride>>(sizeof(pixel)-1);
     LOAD_LEFT_EDGE
@@ -268,7 +296,10 @@
     src[3+3*stride]=l3;
 }
 
-static void FUNCC(pred4x4_horizontal_down)(uint8_t *_src, const uint8_t *topright, int _stride){
+static void FUNCC(pred4x4_horizontal_down)(uint8_t *_src,
+                                           const uint8_t *topright,
+                                           ptrdiff_t _stride)
+{
     pixel *src = (pixel*)_src;
     int stride = _stride>>(sizeof(pixel)-1);
     const int lt= src[-1-1*stride];
@@ -293,7 +324,8 @@
     src[1+3*stride]=(l1 + 2*l2 + l3 + 2)>>2;
 }
 
-static void FUNCC(pred16x16_vertical)(uint8_t *_src, int _stride){
+static void FUNCC(pred16x16_vertical)(uint8_t *_src, ptrdiff_t _stride)
+{
     int i;
     pixel *src = (pixel*)_src;
     int stride = _stride>>(sizeof(pixel)-1);
@@ -310,7 +342,8 @@
     }
 }
 
-static void FUNCC(pred16x16_horizontal)(uint8_t *_src, int stride){
+static void FUNCC(pred16x16_horizontal)(uint8_t *_src, ptrdiff_t stride)
+{
     int i;
     pixel *src = (pixel*)_src;
     stride >>= sizeof(pixel)-1;
@@ -334,7 +367,8 @@
         src += stride;\
     }
 
-static void FUNCC(pred16x16_dc)(uint8_t *_src, int stride){
+static void FUNCC(pred16x16_dc)(uint8_t *_src, ptrdiff_t stride)
+{
     int i, dc=0;
     pixel *src = (pixel*)_src;
     pixel4 dcsplat;
@@ -352,7 +386,8 @@
     PREDICT_16x16_DC(dcsplat);
 }
 
-static void FUNCC(pred16x16_left_dc)(uint8_t *_src, int stride){
+static void FUNCC(pred16x16_left_dc)(uint8_t *_src, ptrdiff_t stride)
+{
     int i, dc=0;
     pixel *src = (pixel*)_src;
     pixel4 dcsplat;
@@ -366,7 +401,8 @@
     PREDICT_16x16_DC(dcsplat);
 }
 
-static void FUNCC(pred16x16_top_dc)(uint8_t *_src, int stride){
+static void FUNCC(pred16x16_top_dc)(uint8_t *_src, ptrdiff_t stride)
+{
     int i, dc=0;
     pixel *src = (pixel*)_src;
     pixel4 dcsplat;
@@ -381,7 +417,8 @@
 }
 
 #define PRED16x16_X(n, v) \
-static void FUNCC(pred16x16_##n##_dc)(uint8_t *_src, int stride){\
+static void FUNCC(pred16x16_##n##_dc)(uint8_t *_src, ptrdiff_t stride)\
+{\
     int i;\
     pixel *src = (pixel*)_src;\
     stride >>= sizeof(pixel)-1;\
@@ -392,12 +429,16 @@
 PRED16x16_X(128, (1<<(BIT_DEPTH-1))+0)
 PRED16x16_X(129, (1<<(BIT_DEPTH-1))+1)
 
-static inline void FUNCC(pred16x16_plane_compat)(uint8_t *p_src, int p_stride, const int svq3, const int rv40){
+static inline void FUNCC(pred16x16_plane_compat)(uint8_t *_src,
+                                                 ptrdiff_t _stride,
+                                                 const int svq3,
+                                                 const int rv40)
+{
   int i, j, k;
   int a;
   INIT_CLIP
-  pixel *src = (pixel*)p_src;
-  int stride = p_stride>>(sizeof(pixel)-1);
+  pixel *src = (pixel*)_src;
+  int stride = _stride>>(sizeof(pixel)-1);
   const pixel * const src0 = src +7-stride;
   const pixel *       src1 = src +8*stride-1;
   const pixel *       src2 = src1-2*stride;    // == src+6*stride-1;
@@ -437,11 +478,13 @@
   }
 }
 
-static void FUNCC(pred16x16_plane)(uint8_t *src, int stride){
+static void FUNCC(pred16x16_plane)(uint8_t *src, ptrdiff_t stride)
+{
     FUNCC(pred16x16_plane_compat)(src, stride, 0, 0);
 }
 
-static void FUNCC(pred8x8_vertical)(uint8_t *_src, int _stride){
+static void FUNCC(pred8x8_vertical)(uint8_t *_src, ptrdiff_t _stride)
+{
     int i;
     pixel *src = (pixel*)_src;
     int stride = _stride>>(sizeof(pixel)-1);
@@ -454,7 +497,8 @@
     }
 }
 
-static void FUNCC(pred8x16_vertical)(uint8_t *_src, int _stride){
+static void FUNCC(pred8x16_vertical)(uint8_t *_src, ptrdiff_t _stride)
+{
     int i;
     pixel *src = (pixel*)_src;
     int stride = _stride>>(sizeof(pixel)-1);
@@ -467,7 +511,8 @@
     }
 }
 
-static void FUNCC(pred8x8_horizontal)(uint8_t *_src, int stride){
+static void FUNCC(pred8x8_horizontal)(uint8_t *_src, ptrdiff_t stride)
+{
     int i;
     pixel *src = (pixel*)_src;
     stride >>= sizeof(pixel)-1;
@@ -479,7 +524,8 @@
     }
 }
 
-static void FUNCC(pred8x16_horizontal)(uint8_t *_src, int stride){
+static void FUNCC(pred8x16_horizontal)(uint8_t *_src, ptrdiff_t stride)
+{
     int i;
     pixel *src = (pixel*)_src;
     stride >>= sizeof(pixel)-1;
@@ -491,7 +537,8 @@
 }
 
 #define PRED8x8_X(n, v)\
-static void FUNCC(pred8x8_##n##_dc)(uint8_t *_src, int stride){\
+static void FUNCC(pred8x8_##n##_dc)(uint8_t *_src, ptrdiff_t stride)\
+{\
     int i;\
     const pixel4 a = PIXEL_SPLAT_X4(v);\
     pixel *src = (pixel*)_src;\
@@ -506,12 +553,14 @@
 PRED8x8_X(128, (1<<(BIT_DEPTH-1))+0)
 PRED8x8_X(129, (1<<(BIT_DEPTH-1))+1)
 
-static void FUNCC(pred8x16_128_dc)(uint8_t *_src, int stride){
+static void FUNCC(pred8x16_128_dc)(uint8_t *_src, ptrdiff_t stride)
+{
     FUNCC(pred8x8_128_dc)(_src, stride);
     FUNCC(pred8x8_128_dc)(_src+8*stride, stride);
 }
 
-static void FUNCC(pred8x8_left_dc)(uint8_t *_src, int stride){
+static void FUNCC(pred8x8_left_dc)(uint8_t *_src, ptrdiff_t stride)
+{
     int i;
     int dc0, dc2;
     pixel4 dc0splat, dc2splat;
@@ -536,12 +585,14 @@
     }
 }
 
-static void FUNCC(pred8x16_left_dc)(uint8_t *_src, int stride){
+static void FUNCC(pred8x16_left_dc)(uint8_t *_src, ptrdiff_t stride)
+{
     FUNCC(pred8x8_left_dc)(_src, stride);
     FUNCC(pred8x8_left_dc)(_src+8*stride, stride);
 }
 
-static void FUNCC(pred8x8_top_dc)(uint8_t *_src, int stride){
+static void FUNCC(pred8x8_top_dc)(uint8_t *_src, ptrdiff_t stride)
+{
     int i;
     int dc0, dc1;
     pixel4 dc0splat, dc1splat;
@@ -566,7 +617,8 @@
     }
 }
 
-static void FUNCC(pred8x16_top_dc)(uint8_t *_src, int stride){
+static void FUNCC(pred8x16_top_dc)(uint8_t *_src, ptrdiff_t stride)
+{
     int i;
     int dc0, dc1;
     pixel4 dc0splat, dc1splat;
@@ -587,7 +639,8 @@
     }
 }
 
-static void FUNCC(pred8x8_dc)(uint8_t *_src, int stride){
+static void FUNCC(pred8x8_dc)(uint8_t *_src, ptrdiff_t stride)
+{
     int i;
     int dc0, dc1, dc2;
     pixel4 dc0splat, dc1splat, dc2splat, dc3splat;
@@ -615,7 +668,8 @@
     }
 }
 
-static void FUNCC(pred8x16_dc)(uint8_t *_src, int stride){
+static void FUNCC(pred8x16_dc)(uint8_t *_src, ptrdiff_t stride)
+{
     int i;
     int dc0, dc1, dc2, dc3, dc4;
     pixel4 dc0splat, dc1splat, dc2splat, dc3splat, dc4splat, dc5splat, dc6splat, dc7splat;
@@ -658,51 +712,60 @@
 }
 
 //the following 4 function should not be optimized!
-static void FUNC(pred8x8_mad_cow_dc_l0t)(uint8_t *src, int stride){
+static void FUNC(pred8x8_mad_cow_dc_l0t)(uint8_t *src, ptrdiff_t stride)
+{
     FUNCC(pred8x8_top_dc)(src, stride);
     FUNCC(pred4x4_dc)(src, NULL, stride);
 }
 
-static void FUNC(pred8x16_mad_cow_dc_l0t)(uint8_t *src, int stride){
+static void FUNC(pred8x16_mad_cow_dc_l0t)(uint8_t *src, ptrdiff_t stride)
+{
     FUNCC(pred8x16_top_dc)(src, stride);
     FUNCC(pred4x4_dc)(src, NULL, stride);
 }
 
-static void FUNC(pred8x8_mad_cow_dc_0lt)(uint8_t *src, int stride){
+static void FUNC(pred8x8_mad_cow_dc_0lt)(uint8_t *src, ptrdiff_t stride)
+{
     FUNCC(pred8x8_dc)(src, stride);
     FUNCC(pred4x4_top_dc)(src, NULL, stride);
 }
 
-static void FUNC(pred8x16_mad_cow_dc_0lt)(uint8_t *src, int stride){
+static void FUNC(pred8x16_mad_cow_dc_0lt)(uint8_t *src, ptrdiff_t stride)
+{
     FUNCC(pred8x16_dc)(src, stride);
     FUNCC(pred4x4_top_dc)(src, NULL, stride);
 }
 
-static void FUNC(pred8x8_mad_cow_dc_l00)(uint8_t *src, int stride){
+static void FUNC(pred8x8_mad_cow_dc_l00)(uint8_t *src, ptrdiff_t stride)
+{
     FUNCC(pred8x8_left_dc)(src, stride);
     FUNCC(pred4x4_128_dc)(src + 4*stride                  , NULL, stride);
     FUNCC(pred4x4_128_dc)(src + 4*stride + 4*sizeof(pixel), NULL, stride);
 }
 
-static void FUNC(pred8x16_mad_cow_dc_l00)(uint8_t *src, int stride){
+static void FUNC(pred8x16_mad_cow_dc_l00)(uint8_t *src, ptrdiff_t stride)
+{
     FUNCC(pred8x16_left_dc)(src, stride);
     FUNCC(pred4x4_128_dc)(src + 4*stride                  , NULL, stride);
     FUNCC(pred4x4_128_dc)(src + 4*stride + 4*sizeof(pixel), NULL, stride);
 }
 
-static void FUNC(pred8x8_mad_cow_dc_0l0)(uint8_t *src, int stride){
+static void FUNC(pred8x8_mad_cow_dc_0l0)(uint8_t *src, ptrdiff_t stride)
+{
     FUNCC(pred8x8_left_dc)(src, stride);
     FUNCC(pred4x4_128_dc)(src                  , NULL, stride);
     FUNCC(pred4x4_128_dc)(src + 4*sizeof(pixel), NULL, stride);
 }
 
-static void FUNC(pred8x16_mad_cow_dc_0l0)(uint8_t *src, int stride){
+static void FUNC(pred8x16_mad_cow_dc_0l0)(uint8_t *src, ptrdiff_t stride)
+{
     FUNCC(pred8x16_left_dc)(src, stride);
     FUNCC(pred4x4_128_dc)(src                  , NULL, stride);
     FUNCC(pred4x4_128_dc)(src + 4*sizeof(pixel), NULL, stride);
 }
 
-static void FUNCC(pred8x8_plane)(uint8_t *_src, int _stride){
+static void FUNCC(pred8x8_plane)(uint8_t *_src, ptrdiff_t _stride)
+{
   int j, k;
   int a;
   INIT_CLIP
@@ -737,7 +800,8 @@
   }
 }
 
-static void FUNCC(pred8x16_plane)(uint8_t *_src, int _stride){
+static void FUNCC(pred8x16_plane)(uint8_t *_src, ptrdiff_t _stride)
+{
   int j, k;
   int a;
   INIT_CLIP
@@ -816,14 +880,16 @@
         src += stride; \
     }
 
-static void FUNCC(pred8x8l_128_dc)(uint8_t *_src, int has_topleft, int has_topright, int _stride)
+static void FUNCC(pred8x8l_128_dc)(uint8_t *_src, int has_topleft,
+                                   int has_topright, ptrdiff_t _stride)
 {
     pixel *src = (pixel*)_src;
     int stride = _stride>>(sizeof(pixel)-1);
 
     PREDICT_8x8_DC(PIXEL_SPLAT_X4(1<<(BIT_DEPTH-1)));
 }
-static void FUNCC(pred8x8l_left_dc)(uint8_t *_src, int has_topleft, int has_topright, int _stride)
+static void FUNCC(pred8x8l_left_dc)(uint8_t *_src, int has_topleft,
+                                    int has_topright, ptrdiff_t _stride)
 {
     pixel *src = (pixel*)_src;
     int stride = _stride>>(sizeof(pixel)-1);
@@ -832,19 +898,21 @@
     const pixel4 dc = PIXEL_SPLAT_X4((l0+l1+l2+l3+l4+l5+l6+l7+4) >> 3);
     PREDICT_8x8_DC(dc);
 }
-static void FUNCC(pred8x8l_top_dc)(uint8_t *p_src, int has_topleft, int has_topright, int p_stride)
+static void FUNCC(pred8x8l_top_dc)(uint8_t *_src, int has_topleft,
+                                   int has_topright, ptrdiff_t _stride)
 {
-    pixel *src = (pixel*)p_src;
-    int stride = p_stride>>(sizeof(pixel)-1);
+    pixel *src = (pixel*)_src;
+    int stride = _stride>>(sizeof(pixel)-1);
 
     PREDICT_8x8_LOAD_TOP;
     const pixel4 dc = PIXEL_SPLAT_X4((t0+t1+t2+t3+t4+t5+t6+t7+4) >> 3);
     PREDICT_8x8_DC(dc);
 }
-static void FUNCC(pred8x8l_dc)(uint8_t *p_src, int has_topleft, int has_topright, int p_stride)
+static void FUNCC(pred8x8l_dc)(uint8_t *_src, int has_topleft,
+                               int has_topright, ptrdiff_t _stride)
 {
-    pixel *src = (pixel*)p_src;
-    int stride = p_stride>>(sizeof(pixel)-1);
+    pixel *src = (pixel*)_src;
+    int stride = _stride>>(sizeof(pixel)-1);
 
     PREDICT_8x8_LOAD_LEFT;
     PREDICT_8x8_LOAD_TOP;
@@ -852,10 +920,11 @@
                                      +t0+t1+t2+t3+t4+t5+t6+t7+8) >> 4);
     PREDICT_8x8_DC(dc);
 }
-static void FUNCC(pred8x8l_horizontal)(uint8_t *p_src, int has_topleft, int has_topright, int p_stride)
+static void FUNCC(pred8x8l_horizontal)(uint8_t *_src, int has_topleft,
+                                       int has_topright, ptrdiff_t _stride)
 {
-    pixel *src = (pixel*)p_src;
-    int stride = p_stride>>(sizeof(pixel)-1);
+    pixel *src = (pixel*)_src;
+    int stride = _stride>>(sizeof(pixel)-1);
     pixel4 a;
 
     PREDICT_8x8_LOAD_LEFT;
@@ -865,7 +934,8 @@
     ROW(0); ROW(1); ROW(2); ROW(3); ROW(4); ROW(5); ROW(6); ROW(7);
 #undef ROW
 }
-static void FUNCC(pred8x8l_vertical)(uint8_t *_src, int has_topleft, int has_topright, int _stride)
+static void FUNCC(pred8x8l_vertical)(uint8_t *_src, int has_topleft,
+                                     int has_topright, ptrdiff_t _stride)
 {
     int y;
     pixel *src = (pixel*)_src;
@@ -888,10 +958,11 @@
         AV_WN4PA(((pixel4*)(src+y*stride))+1, b);
     }
 }
-static void FUNCC(pred8x8l_down_left)(uint8_t *p_src, int has_topleft, int has_topright, int p_stride)
+static void FUNCC(pred8x8l_down_left)(uint8_t *_src, int has_topleft,
+                                      int has_topright, ptrdiff_t _stride)
 {
-    pixel *src = (pixel*)p_src;
-    int stride = p_stride>>(sizeof(pixel)-1);
+    pixel *src = (pixel*)_src;
+    int stride = _stride>>(sizeof(pixel)-1);
     PREDICT_8x8_LOAD_TOP;
     PREDICT_8x8_LOAD_TOPRIGHT;
     SRC(0,0)= (t0 + 2*t1 + t2 + 2) >> 2;
@@ -910,10 +981,11 @@
     SRC(6,7)=SRC(7,6)= (t13 + 2*t14 + t15 + 2) >> 2;
     SRC(7,7)= (t14 + 3*t15 + 2) >> 2;
 }
-static void FUNCC(pred8x8l_down_right)(uint8_t *p_src, int has_topleft, int has_topright, int p_stride)
+static void FUNCC(pred8x8l_down_right)(uint8_t *_src, int has_topleft,
+                                       int has_topright, ptrdiff_t _stride)
 {
-    pixel *src = (pixel*)p_src;
-    int stride = p_stride>>(sizeof(pixel)-1);
+    pixel *src = (pixel*)_src;
+    int stride = _stride>>(sizeof(pixel)-1);
     PREDICT_8x8_LOAD_TOP;
     PREDICT_8x8_LOAD_LEFT;
     PREDICT_8x8_LOAD_TOPLEFT;
@@ -933,10 +1005,11 @@
     SRC(6,0)=SRC(7,1)= (t4 + 2*t5 + t6 + 2) >> 2;
     SRC(7,0)= (t5 + 2*t6 + t7 + 2) >> 2;
 }
-static void FUNCC(pred8x8l_vertical_right)(uint8_t *p_src, int has_topleft, int has_topright, int p_stride)
+static void FUNCC(pred8x8l_vertical_right)(uint8_t *_src, int has_topleft,
+                                           int has_topright, ptrdiff_t _stride)
 {
-    pixel *src = (pixel*)p_src;
-    int stride = p_stride>>(sizeof(pixel)-1);
+    pixel *src = (pixel*)_src;
+    int stride = _stride>>(sizeof(pixel)-1);
     PREDICT_8x8_LOAD_TOP;
     PREDICT_8x8_LOAD_LEFT;
     PREDICT_8x8_LOAD_TOPLEFT;
@@ -963,10 +1036,11 @@
     SRC(7,1)= (t5 + 2*t6 + t7 + 2) >> 2;
     SRC(7,0)= (t6 + t7 + 1) >> 1;
 }
-static void FUNCC(pred8x8l_horizontal_down)(uint8_t *p_src, int has_topleft, int has_topright, int p_stride)
+static void FUNCC(pred8x8l_horizontal_down)(uint8_t *_src, int has_topleft,
+                                            int has_topright, ptrdiff_t _stride)
 {
-    pixel *src = (pixel*)p_src;
-    int stride = p_stride>>(sizeof(pixel)-1);
+    pixel *src = (pixel*)_src;
+    int stride = _stride>>(sizeof(pixel)-1);
     PREDICT_8x8_LOAD_TOP;
     PREDICT_8x8_LOAD_LEFT;
     PREDICT_8x8_LOAD_TOPLEFT;
@@ -993,10 +1067,11 @@
     SRC(6,0)= (t5 + 2*t4 + t3 + 2) >> 2;
     SRC(7,0)= (t6 + 2*t5 + t4 + 2) >> 2;
 }
-static void FUNCC(pred8x8l_vertical_left)(uint8_t *p_src, int has_topleft, int has_topright, int p_stride)
+static void FUNCC(pred8x8l_vertical_left)(uint8_t *_src, int has_topleft,
+                                          int has_topright, ptrdiff_t _stride)
 {
-    pixel *src = (pixel*)p_src;
-    int stride = p_stride>>(sizeof(pixel)-1);
+    pixel *src = (pixel*)_src;
+    int stride = _stride>>(sizeof(pixel)-1);
     PREDICT_8x8_LOAD_TOP;
     PREDICT_8x8_LOAD_TOPRIGHT;
     SRC(0,0)= (t0 + t1 + 1) >> 1;
@@ -1022,10 +1097,11 @@
     SRC(7,6)= (t10 + t11 + 1) >> 1;
     SRC(7,7)= (t10 + 2*t11 + t12 + 2) >> 2;
 }
-static void FUNCC(pred8x8l_horizontal_up)(uint8_t *p_src, int has_topleft, int has_topright, int p_stride)
+static void FUNCC(pred8x8l_horizontal_up)(uint8_t *_src, int has_topleft,
+                                          int has_topright, ptrdiff_t _stride)
 {
-    pixel *src = (pixel*)p_src;
-    int stride = p_stride>>(sizeof(pixel)-1);
+    pixel *src = (pixel*)_src;
+    int stride = _stride>>(sizeof(pixel)-1);
     PREDICT_8x8_LOAD_LEFT;
     SRC(0,0)= (l0 + l1 + 1) >> 1;
     SRC(1,0)= (l0 + 2*l1 + l2 + 2) >> 2;
@@ -1056,10 +1132,12 @@
 #undef PL
 #undef SRC
 
-static void FUNCC(pred4x4_vertical_add)(uint8_t *p_pix, const DCTELEM *p_block, int stride){
+static void FUNCC(pred4x4_vertical_add)(uint8_t *_pix, const DCTELEM *_block,
+                                        ptrdiff_t stride)
+{
     int i;
-    pixel *pix = (pixel*)p_pix;
-    const dctcoef *block = (const dctcoef*)p_block;
+    pixel *pix = (pixel*)_pix;
+    const dctcoef *block = (const dctcoef*)_block;
     stride >>= sizeof(pixel)-1;
     pix -= stride;
     for(i=0; i<4; i++){
@@ -1073,10 +1151,12 @@
     }
 }
 
-static void FUNCC(pred4x4_horizontal_add)(uint8_t *p_pix, const DCTELEM *p_block, int stride){
+static void FUNCC(pred4x4_horizontal_add)(uint8_t *_pix, const DCTELEM *_block,
+                                          ptrdiff_t stride)
+{
     int i;
-    pixel *pix = (pixel*)p_pix;
-    const dctcoef *block = (const dctcoef*)p_block;
+    pixel *pix = (pixel*)_pix;
+    const dctcoef *block = (const dctcoef*)_block;
     stride >>= sizeof(pixel)-1;
     for(i=0; i<4; i++){
         pixel v = pix[-1];
@@ -1089,10 +1169,12 @@
     }
 }
 
-static void FUNCC(pred8x8l_vertical_add)(uint8_t *p_pix, const DCTELEM *p_block, int stride){
+static void FUNCC(pred8x8l_vertical_add)(uint8_t *_pix, const DCTELEM *_block,
+                                         ptrdiff_t stride)
+{
     int i;
-    pixel *pix = (pixel*)p_pix;
-    const dctcoef *block = (const dctcoef*)p_block;
+    pixel *pix = (pixel*)_pix;
+    const dctcoef *block = (const dctcoef*)_block;
     stride >>= sizeof(pixel)-1;
     pix -= stride;
     for(i=0; i<8; i++){
@@ -1110,10 +1192,12 @@
     }
 }
 
-static void FUNCC(pred8x8l_horizontal_add)(uint8_t *p_pix, const DCTELEM *p_block, int stride){
+static void FUNCC(pred8x8l_horizontal_add)(uint8_t *_pix, const DCTELEM *_block,
+                                           ptrdiff_t stride)
+{
     int i;
-    pixel *pix = (pixel*)p_pix;
-    const dctcoef *block = (const dctcoef*)p_block;
+    pixel *pix = (pixel*)_pix;
+    const dctcoef *block = (const dctcoef*)_block;
     stride >>= sizeof(pixel)-1;
     for(i=0; i<8; i++){
         pixel v = pix[-1];
@@ -1130,25 +1214,36 @@
     }
 }
 
-static void FUNCC(pred16x16_vertical_add)(uint8_t *pix, const int *block_offset, const DCTELEM *block, int stride){
+static void FUNCC(pred16x16_vertical_add)(uint8_t *pix, const int *block_offset,
+                                          const DCTELEM *block,
+                                          ptrdiff_t stride)
+{
     int i;
     for(i=0; i<16; i++)
         FUNCC(pred4x4_vertical_add)(pix + block_offset[i], block + i*16*sizeof(pixel), stride);
 }
 
-static void FUNCC(pred16x16_horizontal_add)(uint8_t *pix, const int *block_offset, const DCTELEM *block, int stride){
+static void FUNCC(pred16x16_horizontal_add)(uint8_t *pix,
+                                            const int *block_offset,
+                                            const DCTELEM *block,
+                                            ptrdiff_t stride)
+{
     int i;
     for(i=0; i<16; i++)
         FUNCC(pred4x4_horizontal_add)(pix + block_offset[i], block + i*16*sizeof(pixel), stride);
 }
 
-static void FUNCC(pred8x8_vertical_add)(uint8_t *pix, const int *block_offset, const DCTELEM *block, int stride){
+static void FUNCC(pred8x8_vertical_add)(uint8_t *pix, const int *block_offset,
+                                        const DCTELEM *block, ptrdiff_t stride)
+{
     int i;
     for(i=0; i<4; i++)
         FUNCC(pred4x4_vertical_add)(pix + block_offset[i], block + i*16*sizeof(pixel), stride);
 }
 
-static void FUNCC(pred8x16_vertical_add)(uint8_t *pix, const int *block_offset, const DCTELEM *block, int stride){
+static void FUNCC(pred8x16_vertical_add)(uint8_t *pix, const int *block_offset,
+                                         const DCTELEM *block, ptrdiff_t stride)
+{
     int i;
     for(i=0; i<4; i++)
         FUNCC(pred4x4_vertical_add)(pix + block_offset[i], block + i*16*sizeof(pixel), stride);
@@ -1156,13 +1251,19 @@
         FUNCC(pred4x4_vertical_add)(pix + block_offset[i+4], block + i*16*sizeof(pixel), stride);
 }
 
-static void FUNCC(pred8x8_horizontal_add)(uint8_t *pix, const int *block_offset, const DCTELEM *block, int stride){
+static void FUNCC(pred8x8_horizontal_add)(uint8_t *pix, const int *block_offset,
+                                          const DCTELEM *block,
+                                          ptrdiff_t stride)
+{
     int i;
     for(i=0; i<4; i++)
         FUNCC(pred4x4_horizontal_add)(pix + block_offset[i], block + i*16*sizeof(pixel), stride);
 }
 
-static void FUNCC(pred8x16_horizontal_add)(uint8_t *pix, const int *block_offset, const DCTELEM *block, int stride){
+static void FUNCC(pred8x16_horizontal_add)(uint8_t *pix,
+                                           const int *block_offset,
+                                           const DCTELEM *block, ptrdiff_t stride)
+{
     int i;
     for(i=0; i<4; i++)
         FUNCC(pred4x4_horizontal_add)(pix + block_offset[i], block + i*16*sizeof(pixel), stride);
diff --git a/libavcodec/huffman.h b/libavcodec/huffman.h
index 2fdf88d..4f9ccba 100644
--- a/libavcodec/huffman.h
+++ b/libavcodec/huffman.h
@@ -29,7 +29,7 @@
 #include "avcodec.h"
 #include "get_bits.h"
 
-typedef struct {
+typedef struct Node {
     int16_t  sym;
     int16_t  n0;
     uint32_t count;
diff --git a/libavcodec/huffyuv.c b/libavcodec/huffyuv.c
index 2a9ebe1..ca5bcd8 100644
--- a/libavcodec/huffyuv.c
+++ b/libavcodec/huffyuv.c
@@ -489,32 +489,35 @@
 
     switch (s->bitstream_bpp) {
     case 12:
-        avctx->pix_fmt = PIX_FMT_YUV420P;
+        avctx->pix_fmt = AV_PIX_FMT_YUV420P;
         break;
     case 16:
         if (s->yuy2) {
-            avctx->pix_fmt = PIX_FMT_YUYV422;
+            avctx->pix_fmt = AV_PIX_FMT_YUYV422;
         } else {
-            avctx->pix_fmt = PIX_FMT_YUV422P;
+            avctx->pix_fmt = AV_PIX_FMT_YUV422P;
         }
         break;
     case 24:
     case 32:
         if (s->bgr32) {
-            avctx->pix_fmt = PIX_FMT_RGB32;
+            avctx->pix_fmt = AV_PIX_FMT_RGB32;
         } else {
-            avctx->pix_fmt = PIX_FMT_BGR24;
+            avctx->pix_fmt = AV_PIX_FMT_BGR24;
         }
         break;
     default:
         return AVERROR_INVALIDDATA;
     }
 
-    if ((avctx->pix_fmt == PIX_FMT_YUV422P || avctx->pix_fmt == PIX_FMT_YUV420P) && avctx->width & 1) {
+    if ((avctx->pix_fmt == AV_PIX_FMT_YUV422P || avctx->pix_fmt == AV_PIX_FMT_YUV420P) && avctx->width & 1) {
         av_log(avctx, AV_LOG_ERROR, "width must be even for this colorspace\n");
         return AVERROR_INVALIDDATA;
     }
-
+    if (s->predictor == MEDIAN && avctx->pix_fmt == AV_PIX_FMT_YUV422P && avctx->width%4) {
+        av_log(avctx, AV_LOG_ERROR, "width must be a multiple of 4 this colorspace and predictor\n");
+        return AVERROR_INVALIDDATA;
+    }
     alloc_temp(s);
 
     return 0;
@@ -583,18 +586,18 @@
     avctx->coded_frame = &s->picture;
 
     switch (avctx->pix_fmt) {
-    case PIX_FMT_YUV420P:
-    case PIX_FMT_YUV422P:
+    case AV_PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUV422P:
         if (s->width & 1) {
             av_log(avctx, AV_LOG_ERROR, "width must be even for this colorspace\n");
             return AVERROR(EINVAL);
         }
-        s->bitstream_bpp = avctx->pix_fmt == PIX_FMT_YUV420P ? 12 : 16;
+        s->bitstream_bpp = avctx->pix_fmt == AV_PIX_FMT_YUV420P ? 12 : 16;
         break;
-    case PIX_FMT_RGB32:
+    case AV_PIX_FMT_RGB32:
         s->bitstream_bpp = 32;
         break;
-    case PIX_FMT_RGB24:
+    case AV_PIX_FMT_RGB24:
         s->bitstream_bpp = 24;
         break;
     default:
@@ -616,7 +619,7 @@
     }else s->context= 0;
 
     if (avctx->codec->id == AV_CODEC_ID_HUFFYUV) {
-        if (avctx->pix_fmt == PIX_FMT_YUV420P) {
+        if (avctx->pix_fmt == AV_PIX_FMT_YUV420P) {
             av_log(avctx, AV_LOG_ERROR,
                    "Error: YV12 is not supported by huffyuv; use "
                    "vcodec=ffvhuff or format=422p\n");
@@ -1299,8 +1302,8 @@
 
     init_put_bits(&s->pb, pkt->data + size, pkt->size - size);
 
-    if (avctx->pix_fmt == PIX_FMT_YUV422P ||
-        avctx->pix_fmt == PIX_FMT_YUV420P) {
+    if (avctx->pix_fmt == AV_PIX_FMT_YUV422P ||
+        avctx->pix_fmt == AV_PIX_FMT_YUV420P) {
         int lefty, leftu, leftv, y, cy;
 
         put_bits(&s->pb, 8, leftv = p->data[2][0]);
@@ -1404,7 +1407,7 @@
                 encode_422_bitstream(s, 0, width);
             }
         }
-    } else if(avctx->pix_fmt == PIX_FMT_RGB32) {
+    } else if(avctx->pix_fmt == AV_PIX_FMT_RGB32) {
         uint8_t *data = p->data[0] + (height - 1) * p->linesize[0];
         const int stride = -p->linesize[0];
         const int fake_stride = -fake_ystride;
@@ -1429,7 +1432,7 @@
             }
             encode_bgra_bitstream(s, width, 4);
         }
-    }else if(avctx->pix_fmt == PIX_FMT_RGB24){
+    }else if(avctx->pix_fmt == AV_PIX_FMT_RGB24){
         uint8_t *data = p->data[0] + (height-1)*p->linesize[0];
         const int stride = -p->linesize[0];
         const int fake_stride = -fake_ystride;
@@ -1547,8 +1550,8 @@
     .init           = encode_init,
     .encode2        = encode_frame,
     .close          = encode_end,
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_YUV422P, PIX_FMT_RGB24, PIX_FMT_RGB32, PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_YUV422P, AV_PIX_FMT_RGB24, AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("Huffyuv / HuffYUV"),
 };
@@ -1563,8 +1566,8 @@
     .init           = encode_init,
     .encode2        = encode_frame,
     .close          = encode_end,
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_RGB24, PIX_FMT_RGB32, PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_RGB24, AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("Huffyuv FFmpeg variant"),
 };
diff --git a/libavcodec/idcinvideo.c b/libavcodec/idcinvideo.c
index 26d408f..a517d9d 100644
--- a/libavcodec/idcinvideo.c
+++ b/libavcodec/idcinvideo.c
@@ -76,7 +76,7 @@
     uint32_t pal[256];
 } IdcinContext;
 
-/*
+/**
  * Find the lowest probability node in a Huffman table, and mark it as
  * being assigned to a higher probability.
  * @return the node index of the lowest unused node, or -1 if all nodes
@@ -151,7 +151,7 @@
     unsigned char *histograms;
 
     s->avctx = avctx;
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     /* make sure the Huffman tables make it */
     if (s->avctx->extradata_size != HUFFMAN_TABLE_SIZE) {
@@ -173,7 +173,7 @@
     return 0;
 }
 
-static void idcin_decode_vlcs(IdcinContext *s)
+static int idcin_decode_vlcs(IdcinContext *s)
 {
     hnode *hnodes;
     long x, y;
@@ -192,7 +192,7 @@
                 if(!bit_pos) {
                     if(dat_pos >= s->size) {
                         av_log(s->avctx, AV_LOG_ERROR, "Huffman decode error.\n");
-                        return;
+                        return -1;
                     }
                     bit_pos = 8;
                     v = s->buf[dat_pos++];
@@ -207,6 +207,8 @@
             prev = node_num;
         }
     }
+
+    return 0;
 }
 
 static int idcin_decode_frame(AVCodecContext *avctx,
@@ -217,6 +219,7 @@
     int buf_size = avpkt->size;
     IdcinContext *s = avctx->priv_data;
     const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);
+    int ret;
 
     s->buf = buf;
     s->size = buf_size;
@@ -224,12 +227,13 @@
     if (s->frame.data[0])
         avctx->release_buffer(avctx, &s->frame);
 
-    if (avctx->get_buffer(avctx, &s->frame)) {
-        av_log(avctx, AV_LOG_ERROR, "  id CIN Video: get_buffer() failed\n");
-        return -1;
+    if ((ret = avctx->get_buffer(avctx, &s->frame))) {
+        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+        return ret;
     }
 
-    idcin_decode_vlcs(s);
+    if (idcin_decode_vlcs(s))
+        return AVERROR_INVALIDDATA;
 
     if (pal) {
         s->frame.palette_has_changed = 1;
diff --git a/libavcodec/iff.c b/libavcodec/iff.c
index 2c4ea8f..04c359e 100644
--- a/libavcodec/iff.c
+++ b/libavcodec/iff.c
@@ -1,5 +1,5 @@
 /*
- * IFF PBM/ILBM bitmap decoder
+ * IFF ACBM/DEEP/ILBM/PBM bitmap decoder
  * Copyright (c) 2010 Peter Ross <pross@xvid.org>
  * Copyright (c) 2010 Sebastian Vater <cdgs.basty@googlemail.com>
  *
@@ -22,7 +22,7 @@
 
 /**
  * @file
- * IFF PBM/ILBM bitmap decoder
+ * IFF ACBM/DEEP/ILBM/PBM bitmap decoder
  */
 
 #include "libavutil/imgutils.h"
@@ -231,8 +231,8 @@
         s->transparency = bytestream_get_be16(&buf);
         s->masking      = bytestream_get_byte(&buf);
         if (s->masking == MASK_HAS_MASK) {
-            if (s->bpp >= 8) {
-                avctx->pix_fmt = PIX_FMT_RGB32;
+            if (s->bpp >= 8 && !s->ham) {
+                avctx->pix_fmt = AV_PIX_FMT_RGB32;
                 av_freep(&s->mask_buf);
                 av_freep(&s->mask_palbuf);
                 s->mask_buf = av_malloc((s->planesize * 32) + FF_INPUT_BUFFER_PADDING_SIZE);
@@ -328,10 +328,18 @@
         else
             palette_size = 0;
         avctx->pix_fmt = (avctx->bits_per_coded_sample < 8) ||
-                         (avctx->extradata_size >= 2 && palette_size) ? PIX_FMT_PAL8 : PIX_FMT_GRAY8;
+                         (avctx->extradata_size >= 2 && palette_size) ? AV_PIX_FMT_PAL8 : AV_PIX_FMT_GRAY8;
     } else if (avctx->bits_per_coded_sample <= 32) {
-        if (avctx->codec_tag != MKTAG('D','E','E','P'))
-            avctx->pix_fmt = PIX_FMT_BGR32;
+        if (avctx->codec_tag != MKTAG('D','E','E','P')) {
+            if (avctx->bits_per_coded_sample == 24) {
+                avctx->pix_fmt = AV_PIX_FMT_RGB0;
+            } else if (avctx->bits_per_coded_sample == 32) {
+                avctx->pix_fmt = AV_PIX_FMT_BGR32;
+            } else {
+                av_log_ask_for_sample(avctx, "unknown bits_per_coded_sample\n");
+                return AVERROR_PATCHWELCOME;
+            }
+        }
     } else {
         return AVERROR_INVALIDDATA;
     }
@@ -363,6 +371,10 @@
 static void decodeplane8(uint8_t *dst, const uint8_t *buf, int buf_size, int plane)
 {
     const uint64_t *lut = plane8_lut[plane];
+    if (plane >= 8) {
+        av_log(NULL, AV_LOG_WARNING, "Ignoring extra planes beyond 8\n");
+        return;
+    }
     do {
         uint64_t v = AV_RN64A(dst) | lut[*buf++];
         AV_WN64A(dst, v);
@@ -416,7 +428,7 @@
 static void decode_ham_plane32(uint32_t *dst, const uint8_t  *buf,
                                const uint32_t *const pal, unsigned buf_size)
 {
-    uint32_t delta = 0;
+    uint32_t delta = pal[1]; /* first palette entry */
     do {
         uint32_t first, second;
         DECODE_HAM_PLANE32(0);
@@ -467,125 +479,63 @@
     return buf - buf_start;
 }
 
-static int decode_frame_ilbm(AVCodecContext *avctx,
-                            void *data, int *data_size,
-                            AVPacket *avpkt)
+/**
+ * Decode DEEP RLE 32-bit buffer
+ * @param[out] dst Destination buffer
+ * @param[in] src Source buffer
+ * @param src_size Source buffer size (bytes)
+ * @param width Width of destination buffer (pixels)
+ * @param height Height of destination buffer (pixels)
+ * @param linesize Line size of destination buffer (bytes)
+ */
+static void decode_deep_rle32(uint8_t *dst, const uint8_t *src, int src_size, int width, int height, int linesize)
 {
-    IffContext *s = avctx->priv_data;
-    const uint8_t *buf = avpkt->size >= 2 ? avpkt->data + AV_RB16(avpkt->data) : NULL;
-    const int buf_size = avpkt->size >= 2 ? avpkt->size - AV_RB16(avpkt->data) : 0;
-    const uint8_t *buf_end = buf+buf_size;
-    int y, plane, res;
-
-    if ((res = extract_header(avctx, avpkt)) < 0)
-        return res;
-
-    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 res;
-    } else if (avctx->bits_per_coded_sample <= 8 && avctx->pix_fmt == PIX_FMT_PAL8) {
-        if ((res = ff_cmap_read_palette(avctx, (uint32_t*)s->frame.data[1])) < 0)
-            return res;
-    }
-    s->init = 1;
-
-    if (avctx->codec_tag == MKTAG('A','C','B','M')) {
-        if (avctx->pix_fmt == PIX_FMT_PAL8 || avctx->pix_fmt == PIX_FMT_GRAY8) {
-            memset(s->frame.data[0], 0, avctx->height * s->frame.linesize[0]);
-            for (plane = 0; plane < s->bpp; plane++) {
-                for(y = 0; y < avctx->height && buf < buf_end; y++ ) {
-                    uint8_t *row = &s->frame.data[0][ y*s->frame.linesize[0] ];
-                    decodeplane8(row, buf, FFMIN(s->planesize, buf_end - buf), plane);
-                    buf += s->planesize;
+    const uint8_t *src_end = src + src_size;
+    int x = 0, y = 0, i;
+    while (src + 5 <= src_end) {
+        int opcode;
+        opcode = *(int8_t *)src++;
+        if (opcode >= 0) {
+            int size = opcode + 1;
+            for (i = 0; i < size; i++) {
+                int length = FFMIN(size - i, width);
+                memcpy(dst + y*linesize + x * 4, src, length * 4);
+                src += length * 4;
+                x += length;
+                i += length;
+                if (x >= width) {
+                    x = 0;
+                    y += 1;
+                    if (y >= height)
+                        return;
                 }
             }
-        } else if (s->ham) { // HAM to PIX_FMT_BGR32
-            memset(s->frame.data[0], 0, avctx->height * s->frame.linesize[0]);
-            for(y = 0; y < avctx->height; y++) {
-                uint8_t *row = &s->frame.data[0][y * s->frame.linesize[0]];
-                memset(s->ham_buf, 0, s->planesize * 8);
-                for (plane = 0; plane < s->bpp; plane++) {
-                    const uint8_t * start = buf + (plane * avctx->height + y) * s->planesize;
-                    if (start >= buf_end)
-                        break;
-                    decodeplane8(s->ham_buf, start, FFMIN(s->planesize, buf_end - start), plane);
-                }
-                decode_ham_plane32((uint32_t *) row, s->ham_buf, s->ham_palbuf, s->planesize);
-            }
-        }
-    } else if (avctx->codec_tag == MKTAG('D','E','E','P')) {
-        int raw_width = avctx->width * (av_get_bits_per_pixel(&av_pix_fmt_descriptors[avctx->pix_fmt]) >> 3);
-        int x;
-        for(y = 0; y < avctx->height && buf < buf_end; y++ ) {
-            uint8_t *row = &s->frame.data[0][y * s->frame.linesize[0]];
-            memcpy(row, buf, FFMIN(raw_width, buf_end - buf));
-            buf += raw_width;
-            if (avctx->pix_fmt == PIX_FMT_BGR32) {
-                for(x = 0; x < avctx->width; x++)
-                    row[4 * x + 3] = row[4 * x + 3] & 0xF0 | (row[4 * x + 3] >> 4);
-            }
-        }
-    } else 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 < s->bpp && buf < buf_end; plane++) {
-                    decodeplane8(row, buf, FFMIN(s->planesize, buf_end - buf), plane);
-                    buf += s->planesize;
-                }
-            }
-        } else if (s->ham) { // HAM to PIX_FMT_BGR32
-            for (y = 0; y < avctx->height; y++) {
-                uint8_t *row = &s->frame.data[0][ y*s->frame.linesize[0] ];
-                memset(s->ham_buf, 0, s->planesize * 8);
-                for (plane = 0; plane < s->bpp && buf < buf_end; plane++) {
-                    decodeplane8(s->ham_buf, buf, FFMIN(s->planesize, buf_end - buf), plane);
-                    buf += s->planesize;
-                }
-                decode_ham_plane32((uint32_t *) row, s->ham_buf, s->ham_palbuf, 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 < s->bpp && buf < buf_end; plane++) {
-                    decodeplane32((uint32_t *) row, buf, FFMIN(s->planesize, buf_end - buf), plane);
-                    buf += s->planesize;
-                }
-            }
-        }
-    } else if (avctx->codec_tag == MKTAG('P','B','M',' ')) { // IFF-PBM
-        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]];
-                memcpy(row, buf, FFMIN(avctx->width, buf_end - buf));
-                buf += avctx->width + (avctx->width % 2); // padding if odd
-            }
-        } else if (s->ham) { // IFF-PBM: HAM to PIX_FMT_BGR32
-            for (y = 0; y < avctx->height; y++) {
-                uint8_t *row = &s->frame.data[0][ y*s->frame.linesize[0] ];
-                memcpy(s->ham_buf, buf, FFMIN(avctx->width, buf_end - buf));
-                buf += avctx->width + (avctx->width & 1); // padding if odd
-                decode_ham_plane32((uint32_t *) row, s->ham_buf, s->ham_palbuf, s->planesize);
-            }
         } else {
-            av_log_ask_for_sample(avctx, "unsupported bpp\n");
-            return AVERROR_INVALIDDATA;
+            int size = -opcode + 1;
+            uint32_t pixel = AV_RL32(src);
+            for (i = 0; i < size; i++) {
+                *(uint32_t *)(dst + y*linesize + x * 4) = pixel;
+                x += 1;
+                if (x >= width) {
+                    x = 0;
+                    y += 1;
+                    if (y >= height)
+                        return;
+                }
+            }
+            src += 4;
         }
     }
-
-    *data_size = sizeof(AVFrame);
-    *(AVFrame*)data = s->frame;
-    return buf_size;
 }
 
-static int decode_frame_byterun1(AVCodecContext *avctx,
+static int unsupported(AVCodecContext *avctx)
+{
+    IffContext *s = avctx->priv_data;
+    av_log_ask_for_sample(avctx, "unsupported bitmap (compression %i, bpp %i, ham %i)\n", s->compression, s->bpp, s->ham);
+    return AVERROR_INVALIDDATA;
+}
+
+static int decode_frame(AVCodecContext *avctx,
                             void *data, int *data_size,
                             AVPacket *avpkt)
 {
@@ -605,71 +555,168 @@
     } else if ((res = avctx->get_buffer(avctx, &s->frame)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         return res;
-    } else if (avctx->pix_fmt == PIX_FMT_PAL8) {
+    } else if (avctx->bits_per_coded_sample <= 8 && avctx->pix_fmt == AV_PIX_FMT_PAL8) {
         if ((res = ff_cmap_read_palette(avctx, (uint32_t*)s->frame.data[1])) < 0)
             return res;
-    } else if (avctx->pix_fmt == PIX_FMT_RGB32 && avctx->bits_per_coded_sample <= 8) {
+    } else if (avctx->pix_fmt == AV_PIX_FMT_RGB32 && avctx->bits_per_coded_sample <= 8) {
         if ((res = ff_cmap_read_palette(avctx, s->mask_palbuf)) < 0)
             return res;
     }
     s->init = 1;
 
-    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);
+    switch (s->compression) {
+    case 0:
+        if (avctx->codec_tag == MKTAG('A','C','B','M')) {
+            if (avctx->pix_fmt == AV_PIX_FMT_PAL8 || avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
+                memset(s->frame.data[0], 0, avctx->height * s->frame.linesize[0]);
                 for (plane = 0; plane < s->bpp; plane++) {
-                    buf += decode_byterun(s->planebuf, s->planesize, buf, buf_end);
-                    decodeplane8(row, s->planebuf, s->planesize, plane);
+                    for(y = 0; y < avctx->height && buf < buf_end; y++ ) {
+                        uint8_t *row = &s->frame.data[0][ y*s->frame.linesize[0] ];
+                        decodeplane8(row, buf, FFMIN(s->planesize, buf_end - buf), plane);
+                        buf += s->planesize;
+                    }
+                }
+            } else if (s->ham) { // HAM to AV_PIX_FMT_BGR32
+                memset(s->frame.data[0], 0, avctx->height * s->frame.linesize[0]);
+                for(y = 0; y < avctx->height; y++) {
+                    uint8_t *row = &s->frame.data[0][y * s->frame.linesize[0]];
+                    memset(s->ham_buf, 0, s->planesize * 8);
+                    for (plane = 0; plane < s->bpp; plane++) {
+                        const uint8_t * start = buf + (plane * avctx->height + y) * s->planesize;
+                        if (start >= buf_end)
+                            break;
+                        decodeplane8(s->ham_buf, start, FFMIN(s->planesize, buf_end - start), plane);
+                    }
+                    decode_ham_plane32((uint32_t *) row, s->ham_buf, s->ham_palbuf, s->planesize);
+                }
+            } else
+                return unsupported(avctx);
+        } else if (avctx->codec_tag == MKTAG('D','E','E','P')) {
+            const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
+            int raw_width = avctx->width * (av_get_bits_per_pixel(desc) >> 3);
+            int x;
+            for(y = 0; y < avctx->height && buf < buf_end; y++ ) {
+                uint8_t *row = &s->frame.data[0][y * s->frame.linesize[0]];
+                memcpy(row, buf, FFMIN(raw_width, buf_end - buf));
+                buf += raw_width;
+                if (avctx->pix_fmt == AV_PIX_FMT_BGR32) {
+                    for(x = 0; x < avctx->width; x++)
+                        row[4 * x + 3] = row[4 * x + 3] & 0xF0 | (row[4 * x + 3] >> 4);
                 }
             }
-        } else if (avctx->bits_per_coded_sample <= 8) { //8-bit (+ mask) to PIX_FMT_BGR32
-            for (y = 0; y < avctx->height ; y++ ) {
-                uint8_t *row = &s->frame.data[0][y*s->frame.linesize[0]];
-                memset(s->mask_buf, 0, avctx->width * sizeof(uint32_t));
-                for (plane = 0; plane < s->bpp; plane++) {
-                    buf += decode_byterun(s->planebuf, s->planesize, buf, buf_end);
-                    decodeplane32(s->mask_buf, s->planebuf, s->planesize, plane);
+        } else if (avctx->codec_tag == MKTAG('I','L','B','M')) { // interleaved
+            if (avctx->pix_fmt == AV_PIX_FMT_PAL8 || avctx->pix_fmt == AV_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 < s->bpp && buf < buf_end; plane++) {
+                        decodeplane8(row, buf, FFMIN(s->planesize, buf_end - buf), plane);
+                        buf += s->planesize;
+                    }
                 }
-                lookup_pal_indicies((uint32_t *) row, s->mask_buf, s->mask_palbuf, avctx->width);
-            }
-        } else if (s->ham) { // HAM to PIX_FMT_BGR32
-            for (y = 0; y < avctx->height ; y++) {
-                uint8_t *row = &s->frame.data[0][y*s->frame.linesize[0]];
-                memset(s->ham_buf, 0, s->planesize * 8);
-                for (plane = 0; plane < s->bpp; plane++) {
-                    buf += decode_byterun(s->planebuf, s->planesize, buf, buf_end);
-                    decodeplane8(s->ham_buf, s->planebuf, s->planesize, plane);
+            } else if (s->ham) { // HAM to AV_PIX_FMT_BGR32
+                for (y = 0; y < avctx->height; y++) {
+                    uint8_t *row = &s->frame.data[0][ y*s->frame.linesize[0] ];
+                    memset(s->ham_buf, 0, s->planesize * 8);
+                    for (plane = 0; plane < s->bpp && buf < buf_end; plane++) {
+                        decodeplane8(s->ham_buf, buf, FFMIN(s->planesize, buf_end - buf), plane);
+                        buf += s->planesize;
+                    }
+                    decode_ham_plane32((uint32_t *) row, s->ham_buf, s->ham_palbuf, s->planesize);
                 }
-                decode_ham_plane32((uint32_t *) row, s->ham_buf, s->ham_palbuf, 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 < s->bpp; plane++) {
-                    buf += decode_byterun(s->planebuf, s->planesize, buf, buf_end);
-                    decodeplane32((uint32_t *) row, s->planebuf, s->planesize, plane);
+            } else { // AV_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 < s->bpp && buf < buf_end; plane++) {
+                        decodeplane32((uint32_t *) row, buf, FFMIN(s->planesize, buf_end - buf), plane);
+                        buf += s->planesize;
+                    }
                 }
             }
+        } else if (avctx->codec_tag == MKTAG('P','B','M',' ')) { // IFF-PBM
+            if (avctx->pix_fmt == AV_PIX_FMT_PAL8 || avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
+                for(y = 0; y < avctx->height && buf_end > buf; y++ ) {
+                    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
+                }
+            } else if (s->ham) { // IFF-PBM: HAM to AV_PIX_FMT_BGR32
+                for (y = 0; y < avctx->height && buf_end > buf; y++) {
+                    uint8_t *row = &s->frame.data[0][ y*s->frame.linesize[0] ];
+                    memcpy(s->ham_buf, buf, FFMIN(avctx->width, buf_end - buf));
+                    buf += avctx->width + (avctx->width & 1); // padding if odd
+                    decode_ham_plane32((uint32_t *) row, s->ham_buf, s->ham_palbuf, s->planesize);
+                }
+            } else
+                return unsupported(avctx);
         }
-    } else if (avctx->codec_tag == MKTAG('P','B','M',' ')) { // IFF-PBM
-        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]];
-                buf += decode_byterun(row, avctx->width, buf, buf_end);
+        break;
+    case 1:
+        if (avctx->codec_tag == MKTAG('I','L','B','M')) { //interleaved
+            if (avctx->pix_fmt == AV_PIX_FMT_PAL8 || avctx->pix_fmt == AV_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 < s->bpp; plane++) {
+                        buf += decode_byterun(s->planebuf, s->planesize, buf, buf_end);
+                        decodeplane8(row, s->planebuf, s->planesize, plane);
+                    }
+                }
+            } else if (avctx->bits_per_coded_sample <= 8) { //8-bit (+ mask) to AV_PIX_FMT_BGR32
+                for (y = 0; y < avctx->height ; y++ ) {
+                    uint8_t *row = &s->frame.data[0][y*s->frame.linesize[0]];
+                    memset(s->mask_buf, 0, avctx->width * sizeof(uint32_t));
+                    for (plane = 0; plane < s->bpp; plane++) {
+                        buf += decode_byterun(s->planebuf, s->planesize, buf, buf_end);
+                        decodeplane32(s->mask_buf, s->planebuf, s->planesize, plane);
+                    }
+                    lookup_pal_indicies((uint32_t *) row, s->mask_buf, s->mask_palbuf, avctx->width);
+                }
+            } else if (s->ham) { // HAM to AV_PIX_FMT_BGR32
+                for (y = 0; y < avctx->height ; y++) {
+                    uint8_t *row = &s->frame.data[0][y*s->frame.linesize[0]];
+                    memset(s->ham_buf, 0, s->planesize * 8);
+                    for (plane = 0; plane < s->bpp; plane++) {
+                        buf += decode_byterun(s->planebuf, s->planesize, buf, buf_end);
+                        decodeplane8(s->ham_buf, s->planebuf, s->planesize, plane);
+                    }
+                    decode_ham_plane32((uint32_t *) row, s->ham_buf, s->ham_palbuf, s->planesize);
+                }
+            } else { //AV_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 < s->bpp; plane++) {
+                        buf += decode_byterun(s->planebuf, s->planesize, buf, buf_end);
+                        decodeplane32((uint32_t *) row, s->planebuf, s->planesize, plane);
+                    }
+                }
             }
-        } else if (s->ham) { // IFF-PBM: HAM to PIX_FMT_BGR32
-            for (y = 0; y < avctx->height ; y++) {
-                uint8_t *row = &s->frame.data[0][y*s->frame.linesize[0]];
-                buf += decode_byterun(s->ham_buf, avctx->width, buf, buf_end);
-                decode_ham_plane32((uint32_t *) row, s->ham_buf, s->ham_palbuf, s->planesize);
-            }
-        } else {
-            av_log_ask_for_sample(avctx, "unsupported bpp\n");
-            return AVERROR_INVALIDDATA;
+        } else if (avctx->codec_tag == MKTAG('P','B','M',' ')) { // IFF-PBM
+            if (avctx->pix_fmt == AV_PIX_FMT_PAL8 || avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
+                for(y = 0; y < avctx->height ; y++ ) {
+                    uint8_t *row = &s->frame.data[0][y*s->frame.linesize[0]];
+                    buf += decode_byterun(row, avctx->width, buf, buf_end);
+                }
+            } else if (s->ham) { // IFF-PBM: HAM to AV_PIX_FMT_BGR32
+                for (y = 0; y < avctx->height ; y++) {
+                    uint8_t *row = &s->frame.data[0][y*s->frame.linesize[0]];
+                    buf += decode_byterun(s->ham_buf, avctx->width, buf, buf_end);
+                    decode_ham_plane32((uint32_t *) row, s->ham_buf, s->ham_palbuf, s->planesize);
+                }
+            } else
+                return unsupported(avctx);
+        } else if (avctx->codec_tag == MKTAG('D','E','E','P')) { // IFF-DEEP
+            const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
+            if (av_get_bits_per_pixel(desc) == 32)
+                decode_deep_rle32(s->frame.data[0], buf, buf_size, avctx->width, avctx->height, s->frame.linesize[0]);
+            else
+                return unsupported(avctx);
         }
+        break;
+    default:
+        return unsupported(avctx);
     }
 
     *data_size = sizeof(AVFrame);
@@ -690,27 +737,27 @@
 
 #if CONFIG_IFF_ILBM_DECODER
 AVCodec ff_iff_ilbm_decoder = {
-    .name           = "iff_ilbm",
+    .name           = "iff",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = AV_CODEC_ID_IFF_ILBM,
     .priv_data_size = sizeof(IffContext),
     .init           = decode_init,
     .close          = decode_end,
-    .decode         = decode_frame_ilbm,
+    .decode         = decode_frame,
     .capabilities   = CODEC_CAP_DR1,
-    .long_name      = NULL_IF_CONFIG_SMALL("IFF ILBM"),
+    .long_name      = NULL_IF_CONFIG_SMALL("IFF"),
 };
 #endif
 #if CONFIG_IFF_BYTERUN1_DECODER
 AVCodec ff_iff_byterun1_decoder = {
-    .name           = "iff_byterun1",
+    .name           = "iff",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = AV_CODEC_ID_IFF_BYTERUN1,
     .priv_data_size = sizeof(IffContext),
     .init           = decode_init,
     .close          = decode_end,
-    .decode         = decode_frame_byterun1,
+    .decode         = decode_frame,
     .capabilities   = CODEC_CAP_DR1,
-    .long_name      = NULL_IF_CONFIG_SMALL("IFF ByteRun1"),
+    .long_name      = NULL_IF_CONFIG_SMALL("IFF"),
 };
 #endif
diff --git a/libavcodec/imc.c b/libavcodec/imc.c
index d12c755..feca07c 100644
--- a/libavcodec/imc.c
+++ b/libavcodec/imc.c
@@ -35,12 +35,12 @@
 #include <stddef.h>
 #include <stdio.h>
 
+#include "libavutil/channel_layout.h"
+#include "libavutil/libm.h"
 #include "avcodec.h"
 #include "get_bits.h"
 #include "dsputil.h"
 #include "fft.h"
-#include "libavutil/audioconvert.h"
-#include "libavutil/libm.h"
 #include "sinewin.h"
 
 #include "imcdata.h"
@@ -176,8 +176,10 @@
     IMCContext *q = avctx->priv_data;
     double r1, r2;
 
-    if ((avctx->codec_id == AV_CODEC_ID_IMC && avctx->channels != 1)
-        || (avctx->codec_id == AV_CODEC_ID_IAC && avctx->channels > 2)) {
+    if (avctx->codec_id == AV_CODEC_ID_IMC)
+        avctx->channels = 1;
+
+    if (avctx->channels > 2) {
         av_log_ask_for_sample(avctx, "Number of channels is not supported\n");
         return AVERROR_PATCHWELCOME;
     }
@@ -242,7 +244,7 @@
         return ret;
     }
     ff_dsputil_init(&q->dsp, avctx);
-    avctx->sample_fmt     = AV_SAMPLE_FMT_FLT;
+    avctx->sample_fmt     = AV_SAMPLE_FMT_FLTP;
     avctx->channel_layout = avctx->channels == 1 ? AV_CH_LAYOUT_MONO
                                                  : AV_CH_LAYOUT_STEREO;
 
@@ -662,7 +664,7 @@
     int i;
     float re, im;
     float *dst1 = q->out_samples;
-    float *dst2 = q->out_samples + (COEFFS - 1) * channels;
+    float *dst2 = q->out_samples + (COEFFS - 1);
 
     /* prerotation */
     for (i = 0; i < COEFFS / 2; i++) {
@@ -684,8 +686,8 @@
                + (q->mdct_sine_window[i * 2] * re);
         *dst2 =  (q->mdct_sine_window[i * 2] * chctx->last_fft_im[i])
                - (q->mdct_sine_window[COEFFS - 1 - i * 2] * re);
-        dst1 += channels * 2;
-        dst2 -= channels * 2;
+        dst1 += 2;
+        dst2 -= 2;
         chctx->last_fft_im[i] = im;
     }
 }
@@ -786,7 +788,6 @@
         chctx->decoder_reset = 1;
 
     if (chctx->decoder_reset) {
-        memset(q->out_samples, 0, COEFFS * sizeof(*q->out_samples));
         for (i = 0; i < BANDS; i++)
             chctx->old_floor[i] = 1.0;
         for (i = 0; i < COEFFS; i++)
@@ -804,6 +805,13 @@
         imc_decode_level_coefficients2(q, chctx->levlCoeffBuf, chctx->old_floor,
                                        chctx->flcoeffs1, chctx->flcoeffs2);
 
+    for(i=0; i<BANDS; i++) {
+        if(chctx->flcoeffs1[i] > INT_MAX) {
+            av_log(avctx, AV_LOG_ERROR, "scalefactor out of range\n");
+            return AVERROR_INVALIDDATA;
+        }
+    }
+
     memcpy(chctx->old_floor, chctx->flcoeffs1, 32 * sizeof(float));
 
     counter = 0;
@@ -945,7 +953,7 @@
     }
 
     for (i = 0; i < avctx->channels; i++) {
-        q->out_samples = (float*)q->frame.data[0] + i;
+        q->out_samples = (float *)q->frame.extended_data[i];
 
         q->dsp.bswap16_buf(buf16, (const uint16_t*)buf, IMC_BLOCK_SIZE / 2);
 
@@ -958,15 +966,8 @@
     }
 
     if (avctx->channels == 2) {
-        float *src = (float*)q->frame.data[0], t1, t2;
-
-        for (i = 0; i < COEFFS; i++) {
-            t1     = src[0];
-            t2     = src[1];
-            src[0] = t1 + t2;
-            src[1] = t1 - t2;
-            src   += 2;
-        }
+        q->dsp.butterflies_float((float *)q->frame.extended_data[0],
+                                 (float *)q->frame.extended_data[1], COEFFS);
     }
 
     *got_frame_ptr   = 1;
@@ -985,6 +986,14 @@
     return 0;
 }
 
+static av_cold void flush(AVCodecContext *avctx)
+{
+    IMCContext *q = avctx->priv_data;
+
+    q->chctx[0].decoder_reset =
+    q->chctx[1].decoder_reset = 1;
+}
+
 #if CONFIG_IMC_DECODER
 AVCodec ff_imc_decoder = {
     .name           = "imc",
@@ -994,8 +1003,11 @@
     .init           = imc_decode_init,
     .close          = imc_decode_close,
     .decode         = imc_decode_frame,
+    .flush          = flush,
     .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("IMC (Intel Music Coder)"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
+                                                      AV_SAMPLE_FMT_NONE },
 };
 #endif
 #if CONFIG_IAC_DECODER
@@ -1007,7 +1019,10 @@
     .init           = imc_decode_init,
     .close          = imc_decode_close,
     .decode         = imc_decode_frame,
+    .flush          = flush,
     .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("IAC (Indeo Audio Coder)"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
+                                                      AV_SAMPLE_FMT_NONE },
 };
 #endif
diff --git a/libavcodec/imgconvert.c b/libavcodec/imgconvert.c
index 61ca6a9..030810c 100644
--- a/libavcodec/imgconvert.c
+++ b/libavcodec/imgconvert.c
@@ -33,6 +33,7 @@
 #include "avcodec.h"
 #include "dsputil.h"
 #include "internal.h"
+#include "libavutil/avassert.h"
 #include "libavutil/colorspace.h"
 #include "libavutil/common.h"
 #include "libavutil/pixdesc.h"
@@ -42,6 +43,7 @@
 #include "x86/dsputil_mmx.h"
 #endif
 
+#define FF_COLOR_NA      -1
 #define FF_COLOR_RGB      0 /**< RGB color space */
 #define FF_COLOR_GRAY     1 /**< gray color space */
 #define FF_COLOR_YUV      2 /**< YUV color space. 16 <= Y <= 235, 16 <= U, V <= 240 */
@@ -58,373 +60,37 @@
 #define pixdesc_has_alpha(pixdesc) \
     ((pixdesc)->nb_components == 2 || (pixdesc)->nb_components == 4 || (pixdesc)->flags & PIX_FMT_PAL)
 
-typedef struct PixFmtInfo {
-    uint8_t color_type;      /**< color type (see FF_COLOR_xxx constants) */
-    uint8_t padded_size;     /**< padded size in bits if different from the non-padded size */
-} PixFmtInfo;
 
-/* this table gives more information about formats */
-static const PixFmtInfo pix_fmt_info[PIX_FMT_NB] = {
-    /* YUV formats */
-    [PIX_FMT_YUV420P] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV422P] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV444P] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUYV422] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_UYVY422] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV410P] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV411P] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV440P] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV420P9LE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV422P9LE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV444P9LE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV420P9BE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV422P9BE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV444P9BE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV420P10LE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV422P10LE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV444P10LE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV420P10BE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV422P10BE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV444P10BE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV420P12LE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV422P12LE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV444P12LE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV420P12BE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV422P12BE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV444P12BE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV420P14LE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV422P14LE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV444P14LE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV420P14BE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV422P14BE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV444P14BE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV420P16LE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV422P16LE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV444P16LE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV420P16BE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV422P16BE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_YUV444P16BE] = {
-        .color_type = FF_COLOR_YUV,
-    },
-
-    /* YUV formats with alpha plane */
-    [PIX_FMT_YUVA420P] = {
-        .color_type = FF_COLOR_YUV,
-    },
-
-    [PIX_FMT_YUVA422P] = {
-        .color_type = FF_COLOR_YUV,
-    },
-
-    [PIX_FMT_YUVA444P] = {
-        .color_type = FF_COLOR_YUV,
-    },
-
-    /* JPEG YUV */
-    [PIX_FMT_YUVJ420P] = {
-        .color_type = FF_COLOR_YUV_JPEG,
-    },
-    [PIX_FMT_YUVJ422P] = {
-        .color_type = FF_COLOR_YUV_JPEG,
-    },
-    [PIX_FMT_YUVJ444P] = {
-        .color_type = FF_COLOR_YUV_JPEG,
-    },
-    [PIX_FMT_YUVJ440P] = {
-        .color_type = FF_COLOR_YUV_JPEG,
-    },
-
-    /* RGB formats */
-    [PIX_FMT_RGB24] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_BGR24] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_ARGB] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_RGB48BE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_RGB48LE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_RGBA64BE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_RGBA64LE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_RGB565BE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_RGB565LE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_RGB555BE] = {
-        .color_type = FF_COLOR_RGB,
-        .padded_size = 16,
-    },
-    [PIX_FMT_RGB555LE] = {
-        .color_type = FF_COLOR_RGB,
-        .padded_size = 16,
-    },
-    [PIX_FMT_RGB444BE] = {
-        .color_type = FF_COLOR_RGB,
-        .padded_size = 16,
-    },
-    [PIX_FMT_RGB444LE] = {
-        .color_type = FF_COLOR_RGB,
-        .padded_size = 16,
-    },
-
-    /* gray / mono formats */
-    [PIX_FMT_GRAY16BE] = {
-        .color_type = FF_COLOR_GRAY,
-    },
-    [PIX_FMT_GRAY16LE] = {
-        .color_type = FF_COLOR_GRAY,
-    },
-    [PIX_FMT_GRAY8] = {
-        .color_type = FF_COLOR_GRAY,
-    },
-    [PIX_FMT_GRAY8A] = {
-        .color_type = FF_COLOR_GRAY,
-    },
-    [PIX_FMT_MONOWHITE] = {
-        .color_type = FF_COLOR_GRAY,
-    },
-    [PIX_FMT_MONOBLACK] = {
-        .color_type = FF_COLOR_GRAY,
-    },
-
-    /* paletted formats */
-    [PIX_FMT_PAL8] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_UYYVYY411] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_ABGR] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_BGR48BE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_BGR48LE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_BGRA64BE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_BGRA64LE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_BGR565BE] = {
-        .color_type = FF_COLOR_RGB,
-        .padded_size = 16,
-    },
-    [PIX_FMT_BGR565LE] = {
-        .color_type = FF_COLOR_RGB,
-        .padded_size = 16,
-    },
-    [PIX_FMT_BGR555BE] = {
-        .color_type = FF_COLOR_RGB,
-        .padded_size = 16,
-    },
-    [PIX_FMT_BGR555LE] = {
-        .color_type = FF_COLOR_RGB,
-        .padded_size = 16,
-    },
-    [PIX_FMT_BGR444BE] = {
-        .color_type = FF_COLOR_RGB,
-        .padded_size = 16,
-    },
-    [PIX_FMT_BGR444LE] = {
-        .color_type = FF_COLOR_RGB,
-        .padded_size = 16,
-    },
-    [PIX_FMT_RGB8] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_RGB4] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_RGB4_BYTE] = {
-        .color_type = FF_COLOR_RGB,
-        .padded_size = 8,
-    },
-    [PIX_FMT_BGR8] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_BGR4] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_BGR4_BYTE] = {
-        .color_type = FF_COLOR_RGB,
-        .padded_size = 8,
-    },
-    [PIX_FMT_NV12] = {
-        .color_type = FF_COLOR_YUV,
-    },
-    [PIX_FMT_NV21] = {
-        .color_type = FF_COLOR_YUV,
-    },
-
-    [PIX_FMT_BGRA] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_RGBA] = {
-        .color_type = FF_COLOR_RGB,
-    },
-
-    [PIX_FMT_GBRP] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_GBRP9BE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_GBRP9LE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_GBRP10BE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_GBRP10LE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_GBRP12BE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_GBRP12LE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_GBRP14BE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_GBRP14LE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_GBRP16BE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-    [PIX_FMT_GBRP16LE] = {
-        .color_type = FF_COLOR_RGB,
-    },
-};
-
-void avcodec_get_chroma_sub_sample(enum PixelFormat pix_fmt, int *h_shift, int *v_shift)
+void avcodec_get_chroma_sub_sample(enum AVPixelFormat pix_fmt, int *h_shift, int *v_shift)
 {
-    *h_shift = av_pix_fmt_descriptors[pix_fmt].log2_chroma_w;
-    *v_shift = av_pix_fmt_descriptors[pix_fmt].log2_chroma_h;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
+    av_assert0(desc);
+    *h_shift = desc->log2_chroma_w;
+    *v_shift = desc->log2_chroma_h;
 }
 
-int ff_is_hwaccel_pix_fmt(enum PixelFormat pix_fmt)
-{
-    return av_pix_fmt_descriptors[pix_fmt].flags & PIX_FMT_HWACCEL;
+static get_color_type(AVPixFmtDescriptor *desc) {
+    if(desc->nb_components == 1 || desc->nb_components == 2)
+        return FF_COLOR_GRAY;
+
+    if(desc->name && !strncmp(desc->name, "yuvj", 4))
+        return FF_COLOR_YUV_JPEG;
+
+    if(desc->flags & PIX_FMT_RGB)
+        return  FF_COLOR_RGB;
+
+    if(desc->nb_components == 0)
+        return FF_COLOR_NA;
+
+    return FF_COLOR_YUV;
 }
 
-int avpicture_fill(AVPicture *picture, uint8_t *ptr,
-                   enum PixelFormat pix_fmt, int width, int height)
+static int get_pix_fmt_depth(int *min, int *max, enum AVPixelFormat pix_fmt)
 {
-    return av_image_fill_arrays(picture->data, picture->linesize,
-                                ptr, pix_fmt, width, height, 1);
-}
-
-int avpicture_layout(const AVPicture* src, enum PixelFormat pix_fmt, int width, int height,
-                     unsigned char *dest, int dest_size)
-{
-    return av_image_copy_to_buffer(dest, dest_size,
-                                   (const uint8_t * const*)src->data, src->linesize,
-                                   pix_fmt, width, height, 1);
-}
-
-int avpicture_get_size(enum PixelFormat pix_fmt, int width, int height)
-{
-    return av_image_get_buffer_size(pix_fmt, width, height, 1);
-}
-
-static int get_pix_fmt_depth(int *min, int *max, enum PixelFormat pix_fmt)
-{
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
     int i;
 
-    if (!desc->nb_components) {
+    if (!desc || !desc->nb_components) {
         *min = *max = 0;
         return AVERROR(EINVAL);
     }
@@ -437,96 +103,92 @@
     return 0;
 }
 
-int avcodec_get_pix_fmt_loss(enum PixelFormat dst_pix_fmt, enum PixelFormat src_pix_fmt,
+int avcodec_get_pix_fmt_loss(enum AVPixelFormat dst_pix_fmt,
+                             enum AVPixelFormat src_pix_fmt,
                              int has_alpha)
 {
-    const PixFmtInfo *pf, *ps;
-    const AVPixFmtDescriptor *src_desc;
-    const AVPixFmtDescriptor *dst_desc;
+    const AVPixFmtDescriptor *src_desc = av_pix_fmt_desc_get(src_pix_fmt);
+    const AVPixFmtDescriptor *dst_desc = av_pix_fmt_desc_get(dst_pix_fmt);
+    int src_color, dst_color;
     int src_min_depth, src_max_depth, dst_min_depth, dst_max_depth;
-    int ret, loss;
+    int ret, loss, i, nb_components;
 
-    if (dst_pix_fmt >= PIX_FMT_NB || dst_pix_fmt <= PIX_FMT_NONE)
+    if (dst_pix_fmt >= AV_PIX_FMT_NB || dst_pix_fmt <= AV_PIX_FMT_NONE)
         return ~0;
 
-    src_desc = &av_pix_fmt_descriptors[src_pix_fmt];
-    dst_desc = &av_pix_fmt_descriptors[dst_pix_fmt];
-    ps = &pix_fmt_info[src_pix_fmt];
-
     /* compute loss */
     loss = 0;
 
+    if (dst_pix_fmt == src_pix_fmt)
+        return 0;
+
     if ((ret = get_pix_fmt_depth(&src_min_depth, &src_max_depth, src_pix_fmt)) < 0)
         return ret;
     if ((ret = get_pix_fmt_depth(&dst_min_depth, &dst_max_depth, dst_pix_fmt)) < 0)
         return ret;
-    if (dst_min_depth < src_min_depth ||
-        dst_max_depth < src_max_depth)
-        loss |= FF_LOSS_DEPTH;
+
+    src_color = get_color_type(src_desc);
+    dst_color = get_color_type(dst_desc);
+    nb_components = FFMIN(src_desc->nb_components, dst_desc->nb_components);
+
+    for (i = 0; i < nb_components; i++)
+        if (src_desc->comp[i].depth_minus1 > dst_desc->comp[i].depth_minus1)
+            loss |= FF_LOSS_DEPTH;
+
     if (dst_desc->log2_chroma_w > src_desc->log2_chroma_w ||
         dst_desc->log2_chroma_h > src_desc->log2_chroma_h)
         loss |= FF_LOSS_RESOLUTION;
 
-    pf = &pix_fmt_info[dst_pix_fmt];
-    switch(pf->color_type) {
+    switch(dst_color) {
     case FF_COLOR_RGB:
-        if (ps->color_type != FF_COLOR_RGB &&
-            ps->color_type != FF_COLOR_GRAY)
+        if (src_color != FF_COLOR_RGB &&
+            src_color != FF_COLOR_GRAY)
             loss |= FF_LOSS_COLORSPACE;
         break;
     case FF_COLOR_GRAY:
-        if (ps->color_type != FF_COLOR_GRAY)
+        if (src_color != FF_COLOR_GRAY)
             loss |= FF_LOSS_COLORSPACE;
         break;
     case FF_COLOR_YUV:
-        if (ps->color_type != FF_COLOR_YUV)
+        if (src_color != FF_COLOR_YUV)
             loss |= FF_LOSS_COLORSPACE;
         break;
     case FF_COLOR_YUV_JPEG:
-        if (ps->color_type != FF_COLOR_YUV_JPEG &&
-            ps->color_type != FF_COLOR_YUV &&
-            ps->color_type != FF_COLOR_GRAY)
+        if (src_color != FF_COLOR_YUV_JPEG &&
+            src_color != FF_COLOR_YUV &&
+            src_color != FF_COLOR_GRAY)
             loss |= FF_LOSS_COLORSPACE;
         break;
     default:
         /* fail safe test */
-        if (ps->color_type != pf->color_type)
+        if (src_color != dst_color)
             loss |= FF_LOSS_COLORSPACE;
         break;
     }
-    if (pf->color_type == FF_COLOR_GRAY &&
-        ps->color_type != FF_COLOR_GRAY)
+    if (dst_color == FF_COLOR_GRAY &&
+        src_color != FF_COLOR_GRAY)
         loss |= FF_LOSS_CHROMA;
     if (!pixdesc_has_alpha(dst_desc) && (pixdesc_has_alpha(src_desc) && has_alpha))
         loss |= FF_LOSS_ALPHA;
-    if (dst_pix_fmt == PIX_FMT_PAL8 &&
-        (src_pix_fmt != PIX_FMT_PAL8 && (ps->color_type != FF_COLOR_GRAY || (pixdesc_has_alpha(src_desc) && has_alpha))))
+    if (dst_pix_fmt == AV_PIX_FMT_PAL8 &&
+        (src_pix_fmt != AV_PIX_FMT_PAL8 && (src_color != FF_COLOR_GRAY || (pixdesc_has_alpha(src_desc) && has_alpha))))
         loss |= FF_LOSS_COLORQUANT;
 
     return loss;
 }
 
-static int avg_bits_per_pixel(enum PixelFormat pix_fmt)
-{
-    const PixFmtInfo *info = &pix_fmt_info[pix_fmt];
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];
-
-    return info->padded_size ?
-        info->padded_size : av_get_bits_per_pixel(desc);
-}
-
 #if FF_API_FIND_BEST_PIX_FMT
-enum PixelFormat avcodec_find_best_pix_fmt(int64_t pix_fmt_mask, enum PixelFormat src_pix_fmt,
+enum AVPixelFormat avcodec_find_best_pix_fmt(int64_t pix_fmt_mask, enum AVPixelFormat src_pix_fmt,
                                             int has_alpha, int *loss_ptr)
 {
-    enum PixelFormat dst_pix_fmt;
+    enum AVPixelFormat dst_pix_fmt;
     int i;
 
     if (loss_ptr) /* all losses count (for backward compatibility) */
         *loss_ptr = 0;
 
-    dst_pix_fmt = PIX_FMT_NONE; /* so first iteration doesn't have to be treated special */
-    for(i = 0; i< FFMIN(PIX_FMT_NB, 64); i++){
+    dst_pix_fmt = AV_PIX_FMT_NONE; /* so first iteration doesn't have to be treated special */
+    for(i = 0; i< FFMIN(AV_PIX_FMT_NB, 64); i++){
         if (pix_fmt_mask & (1ULL << i))
             dst_pix_fmt = avcodec_find_best_pix_fmt_of_2(dst_pix_fmt, i, src_pix_fmt, has_alpha, loss_ptr);
     }
@@ -534,11 +196,13 @@
 }
 #endif /* FF_API_FIND_BEST_PIX_FMT */
 
-enum PixelFormat avcodec_find_best_pix_fmt_of_2(enum PixelFormat dst_pix_fmt1, enum PixelFormat dst_pix_fmt2,
-                                            enum PixelFormat src_pix_fmt, int has_alpha, int *loss_ptr)
+enum AVPixelFormat avcodec_find_best_pix_fmt_of_2(enum AVPixelFormat dst_pix_fmt1, enum AVPixelFormat dst_pix_fmt2,
+                                            enum AVPixelFormat src_pix_fmt, int has_alpha, int *loss_ptr)
 {
-    enum PixelFormat dst_pix_fmt;
+    enum AVPixelFormat dst_pix_fmt;
     int loss1, loss2, loss_order1, loss_order2, i, loss_mask;
+    const AVPixFmtDescriptor *desc1 = av_pix_fmt_desc_get(dst_pix_fmt1);
+    const AVPixFmtDescriptor *desc2 = av_pix_fmt_desc_get(dst_pix_fmt2);
     static const int loss_mask_order[] = {
         ~0, /* no loss first */
         ~FF_LOSS_ALPHA,
@@ -555,17 +219,21 @@
     };
 
     loss_mask= loss_ptr?~*loss_ptr:~0; /* use loss mask if provided */
-    dst_pix_fmt = PIX_FMT_NONE;
+    dst_pix_fmt = AV_PIX_FMT_NONE;
     loss1 = avcodec_get_pix_fmt_loss(dst_pix_fmt1, src_pix_fmt, has_alpha) & loss_mask;
     loss2 = avcodec_get_pix_fmt_loss(dst_pix_fmt2, src_pix_fmt, has_alpha) & loss_mask;
 
     /* try with successive loss */
-    for(i = 0;loss_mask_order[i] != 0 && dst_pix_fmt == PIX_FMT_NONE;i++) {
+    for(i = 0;loss_mask_order[i] != 0 && dst_pix_fmt == AV_PIX_FMT_NONE;i++) {
         loss_order1 = loss1 & loss_mask_order[i];
         loss_order2 = loss2 & loss_mask_order[i];
 
-        if (loss_order1 == 0 && loss_order2 == 0){ /* use format with smallest depth */
-            dst_pix_fmt = avg_bits_per_pixel(dst_pix_fmt2) < avg_bits_per_pixel(dst_pix_fmt1) ? dst_pix_fmt2 : dst_pix_fmt1;
+        if (loss_order1 == 0 && loss_order2 == 0 && dst_pix_fmt2 != AV_PIX_FMT_NONE && dst_pix_fmt1 != AV_PIX_FMT_NONE){ /* use format with smallest depth */
+            if(av_get_padded_bits_per_pixel(desc2) != av_get_padded_bits_per_pixel(desc1)) {
+                dst_pix_fmt = av_get_padded_bits_per_pixel(desc2) < av_get_padded_bits_per_pixel(desc1) ? dst_pix_fmt2 : dst_pix_fmt1;
+            } else {
+                dst_pix_fmt = desc2->nb_components < desc1->nb_components ? dst_pix_fmt2 : dst_pix_fmt1;
+            }
         } else if (loss_order1 == 0 || loss_order2 == 0) { /* use format with no loss */
             dst_pix_fmt = loss_order2 ? dst_pix_fmt1 : dst_pix_fmt2;
         }
@@ -577,39 +245,32 @@
 }
 
 #if AV_HAVE_INCOMPATIBLE_FORK_ABI
-enum PixelFormat avcodec_find_best_pix_fmt2(enum PixelFormat *pix_fmt_list,
-                                            enum PixelFormat src_pix_fmt,
+enum AVPixelFormat avcodec_find_best_pix_fmt2(enum AVPixelFormat *pix_fmt_list,
+                                            enum AVPixelFormat src_pix_fmt,
                                             int has_alpha, int *loss_ptr){
     return avcodec_find_best_pix_fmt_of_list(pix_fmt_list, src_pix_fmt, has_alpha, loss_ptr);
 }
 #else
-enum PixelFormat avcodec_find_best_pix_fmt2(enum PixelFormat dst_pix_fmt1, enum PixelFormat dst_pix_fmt2,
-                                            enum PixelFormat src_pix_fmt, int has_alpha, int *loss_ptr)
+enum AVPixelFormat avcodec_find_best_pix_fmt2(enum AVPixelFormat dst_pix_fmt1, enum AVPixelFormat dst_pix_fmt2,
+                                            enum AVPixelFormat src_pix_fmt, int has_alpha, int *loss_ptr)
 {
     return avcodec_find_best_pix_fmt_of_2(dst_pix_fmt1, dst_pix_fmt2, src_pix_fmt, has_alpha, loss_ptr);
 }
 #endif
 
-enum PixelFormat avcodec_find_best_pix_fmt_of_list(enum PixelFormat *pix_fmt_list,
-                                            enum PixelFormat src_pix_fmt,
+enum AVPixelFormat avcodec_find_best_pix_fmt_of_list(enum AVPixelFormat *pix_fmt_list,
+                                            enum AVPixelFormat src_pix_fmt,
                                             int has_alpha, int *loss_ptr){
     int i;
 
-    enum PixelFormat best = PIX_FMT_NONE;
+    enum AVPixelFormat best = AV_PIX_FMT_NONE;
 
-    for(i=0; pix_fmt_list[i] != PIX_FMT_NONE; i++)
+    for(i=0; pix_fmt_list[i] != AV_PIX_FMT_NONE; i++)
         best = avcodec_find_best_pix_fmt_of_2(best, pix_fmt_list[i], src_pix_fmt, has_alpha, loss_ptr);
 
     return best;
 }
 
-void av_picture_copy(AVPicture *dst, const AVPicture *src,
-                     enum PixelFormat pix_fmt, int width, int height)
-{
-    av_image_copy(dst->data, dst->linesize, (const uint8_t **)src->data,
-                  src->linesize, pix_fmt, width, height);
-}
-
 /* 2x2 -> 1x1 */
 void ff_shrink22(uint8_t *dst, int dst_wrap,
                      const uint8_t *src, int src_wrap,
@@ -696,35 +357,14 @@
     }
 }
 
-
-int avpicture_alloc(AVPicture *picture,
-                    enum PixelFormat pix_fmt, int width, int height)
-{
-    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;
-}
-
-void avpicture_free(AVPicture *picture)
-{
-    av_free(picture->data[0]);
-}
-
 /* return true if yuv planar */
-static inline int is_yuv_planar(enum PixelFormat fmt)
+static inline int is_yuv_planar(const AVPixFmtDescriptor *desc)
 {
-    const PixFmtInfo         *info = &pix_fmt_info[fmt];
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[fmt];
     int i;
     int planes[4] = { 0 };
 
-    if (info->color_type != FF_COLOR_YUV &&
-        info->color_type != FF_COLOR_YUV_JPEG)
+    if (     desc->flags & PIX_FMT_RGB
+        || !(desc->flags & PIX_FMT_PLANAR))
         return 0;
 
     /* set the used planes */
@@ -739,18 +379,19 @@
 }
 
 int av_picture_crop(AVPicture *dst, const AVPicture *src,
-                    enum PixelFormat pix_fmt, int top_band, int left_band)
+                    enum AVPixelFormat pix_fmt, int top_band, int left_band)
 {
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
     int y_shift;
     int x_shift;
 
-    if (pix_fmt < 0 || pix_fmt >= PIX_FMT_NB)
+    if (pix_fmt < 0 || pix_fmt >= AV_PIX_FMT_NB)
         return -1;
 
-    y_shift = av_pix_fmt_descriptors[pix_fmt].log2_chroma_h;
-    x_shift = av_pix_fmt_descriptors[pix_fmt].log2_chroma_w;
+    y_shift = desc->log2_chroma_h;
+    x_shift = desc->log2_chroma_w;
 
-    if (is_yuv_planar(pix_fmt)) {
+    if (is_yuv_planar(desc)) {
     dst->data[0] = src->data[0] + (top_band * src->linesize[0]) + left_band;
     dst->data[1] = src->data[1] + ((top_band >> y_shift) * src->linesize[1]) + (left_band >> x_shift);
     dst->data[2] = src->data[2] + ((top_band >> y_shift) * src->linesize[2]) + (left_band >> x_shift);
@@ -769,21 +410,22 @@
 }
 
 int av_picture_pad(AVPicture *dst, const AVPicture *src, int height, int width,
-                   enum PixelFormat pix_fmt, int padtop, int padbottom, int padleft, int padright,
+                   enum AVPixelFormat pix_fmt, int padtop, int padbottom, int padleft, int padright,
             int *color)
 {
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
     uint8_t *optr;
     int y_shift;
     int x_shift;
     int yheight;
     int i, y;
 
-    if (pix_fmt < 0 || pix_fmt >= PIX_FMT_NB ||
-        !is_yuv_planar(pix_fmt)) return -1;
+    if (pix_fmt < 0 || pix_fmt >= AV_PIX_FMT_NB ||
+        !is_yuv_planar(desc)) return -1;
 
     for (i = 0; i < 3; i++) {
-        x_shift = i ? av_pix_fmt_descriptors[pix_fmt].log2_chroma_w : 0;
-        y_shift = i ? av_pix_fmt_descriptors[pix_fmt].log2_chroma_h : 0;
+        x_shift = i ? desc->log2_chroma_w : 0;
+        y_shift = i ? desc->log2_chroma_h : 0;
 
         if (padtop || padleft) {
             memset(dst->data[i], color[i],
@@ -937,17 +579,17 @@
 }
 
 int avpicture_deinterlace(AVPicture *dst, const AVPicture *src,
-                          enum PixelFormat pix_fmt, int width, int height)
+                          enum AVPixelFormat pix_fmt, int width, int height)
 {
     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)
+    if (pix_fmt != AV_PIX_FMT_YUV420P &&
+        pix_fmt != AV_PIX_FMT_YUVJ420P &&
+        pix_fmt != AV_PIX_FMT_YUV422P &&
+        pix_fmt != AV_PIX_FMT_YUVJ422P &&
+        pix_fmt != AV_PIX_FMT_YUV444P &&
+        pix_fmt != AV_PIX_FMT_YUV411P &&
+        pix_fmt != AV_PIX_FMT_GRAY8)
         return -1;
     if ((width & 3) != 0 || (height & 3) != 0)
         return -1;
@@ -955,22 +597,22 @@
     for(i=0;i<3;i++) {
         if (i == 1) {
             switch(pix_fmt) {
-            case PIX_FMT_YUVJ420P:
-            case PIX_FMT_YUV420P:
+            case AV_PIX_FMT_YUVJ420P:
+            case AV_PIX_FMT_YUV420P:
                 width >>= 1;
                 height >>= 1;
                 break;
-            case PIX_FMT_YUV422P:
-            case PIX_FMT_YUVJ422P:
+            case AV_PIX_FMT_YUV422P:
+            case AV_PIX_FMT_YUVJ422P:
                 width >>= 1;
                 break;
-            case PIX_FMT_YUV411P:
+            case AV_PIX_FMT_YUV411P:
                 width >>= 2;
                 break;
             default:
                 break;
             }
-            if (pix_fmt == PIX_FMT_GRAY8) {
+            if (pix_fmt == AV_PIX_FMT_GRAY8) {
                 break;
             }
         }
@@ -986,3 +628,31 @@
     emms_c();
     return 0;
 }
+
+#ifdef TEST
+
+int main(void){
+    int i;
+    int err=0;
+    int skip = 0;
+
+    for (i=0; i<AV_PIX_FMT_NB*2; i++) {
+        AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(i);
+        if(!desc || !desc->name) {
+            skip ++;
+            continue;
+        }
+        if (skip) {
+            av_log(NULL, AV_LOG_INFO, "%3d unused pixel format values\n", skip);
+            skip = 0;
+        }
+        av_log(NULL, AV_LOG_INFO, "pix fmt %s yuv_plan:%d avg_bpp:%d colortype:%d\n", desc->name, is_yuv_planar(desc), av_get_padded_bits_per_pixel(desc), get_color_type(desc));
+        if ((!(desc->flags & PIX_FMT_ALPHA)) != (desc->nb_components != 2 && desc->nb_components != 4)) {
+            av_log(NULL, AV_LOG_ERROR, "Alpha flag mismatch\n");
+            err = 1;
+        }
+    }
+    return err;
+}
+
+#endif
diff --git a/libavcodec/indeo2.c b/libavcodec/indeo2.c
index 3f8ed42..74a9800 100644
--- a/libavcodec/indeo2.c
+++ b/libavcodec/indeo2.c
@@ -23,11 +23,13 @@
  * @file
  * Intel Indeo 2 decoder.
  */
+
 #define BITSTREAM_READER_LE
+#include "libavutil/attributes.h"
 #include "avcodec.h"
 #include "get_bits.h"
 #include "indeo2data.h"
-#include "libavutil/common.h"
+#include "mathops.h"
 
 typedef struct Ir2Context{
     AVCodecContext *avctx;
@@ -165,7 +167,7 @@
     /* decide whether frame uses deltas or not */
 #ifndef BITSTREAM_READER_LE
     for (i = 0; i < buf_size; i++)
-        buf[i] = av_reverse[buf[i]];
+        buf[i] = ff_reverse[buf[i]];
 #endif
 
     init_get_bits(&s->gb, buf + start, (buf_size - start) * 8);
@@ -201,7 +203,7 @@
     avcodec_get_frame_defaults(&ic->picture);
     ic->avctx = avctx;
 
-    avctx->pix_fmt= PIX_FMT_YUV410P;
+    avctx->pix_fmt= AV_PIX_FMT_YUV410P;
 
     ir2_vlc.table = vlc_tables;
     ir2_vlc.table_allocated = 1 << CODE_VLC_BITS;
diff --git a/libavcodec/indeo3.c b/libavcodec/indeo3.c
index d19c604..013d610 100644
--- a/libavcodec/indeo3.c
+++ b/libavcodec/indeo3.c
@@ -1010,14 +1010,17 @@
  *  @param[in]  buf_sel      indicates which frame buffer the input data stored in
  *  @param[out] dst          pointer to the buffer receiving converted pixels
  *  @param[in]  dst_pitch    pitch for moving to the next y line
+ *  @param[in]  dst_height   output plane height
  */
-static void output_plane(const Plane *plane, int buf_sel, uint8_t *dst, int dst_pitch)
+static void output_plane(const Plane *plane, int buf_sel, uint8_t *dst,
+                         int dst_pitch, int dst_height)
 {
     int             x,y;
     const uint8_t   *src  = plane->pixels[buf_sel];
     uint32_t        pitch = plane->pitch;
 
-    for (y = 0; y < plane->height; y++) {
+    dst_height = FFMIN(dst_height, plane->height);
+    for (y = 0; y < dst_height; y++) {
         /* convert four pixels at once using SWAR */
         for (x = 0; x < plane->width >> 2; x++) {
             AV_WN32A(dst, (AV_RN32A(src) & 0x7F7F7F7F) << 1);
@@ -1039,7 +1042,7 @@
     Indeo3DecodeContext *ctx = avctx->priv_data;
 
     ctx->avctx     = avctx;
-    avctx->pix_fmt = PIX_FMT_YUV410P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV410P;
     avcodec_get_frame_defaults(&ctx->frame);
 
     build_requant_tab();
@@ -1081,6 +1084,15 @@
     /* use BS_BUFFER flag for buffer switching */
     ctx->buf_sel = (ctx->frame_flags >> BS_BUFFER) & 1;
 
+    if (ctx->frame.data[0])
+        avctx->release_buffer(avctx, &ctx->frame);
+
+    ctx->frame.reference = 0;
+    if ((res = avctx->get_buffer(avctx, &ctx->frame)) < 0) {
+        av_log(ctx->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+        return res;
+    }
+
     /* decode luma plane */
     if ((res = decode_plane(ctx, avctx, ctx->planes, ctx->y_data_ptr, ctx->y_data_size, 40)))
         return res;
@@ -1092,18 +1104,15 @@
     if ((res = decode_plane(ctx, avctx, &ctx->planes[2], ctx->v_data_ptr, ctx->v_data_size, 10)))
         return res;
 
-    if (ctx->frame.data[0])
-        avctx->release_buffer(avctx, &ctx->frame);
-
-    ctx->frame.reference = 0;
-    if ((res = avctx->get_buffer(avctx, &ctx->frame)) < 0) {
-        av_log(ctx->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return res;
-    }
-
-    output_plane(&ctx->planes[0], ctx->buf_sel, ctx->frame.data[0], ctx->frame.linesize[0]);
-    output_plane(&ctx->planes[1], ctx->buf_sel, ctx->frame.data[1], ctx->frame.linesize[1]);
-    output_plane(&ctx->planes[2], ctx->buf_sel, ctx->frame.data[2], ctx->frame.linesize[2]);
+    output_plane(&ctx->planes[0], ctx->buf_sel,
+                 ctx->frame.data[0], ctx->frame.linesize[0],
+                 avctx->height);
+    output_plane(&ctx->planes[1], ctx->buf_sel,
+                 ctx->frame.data[1], ctx->frame.linesize[1],
+                 (avctx->height + 3) >> 2);
+    output_plane(&ctx->planes[2], ctx->buf_sel,
+                 ctx->frame.data[2], ctx->frame.linesize[2],
+                 (avctx->height + 3) >> 2);
 
     *data_size      = sizeof(AVFrame);
     *(AVFrame*)data = ctx->frame;
@@ -1133,4 +1142,5 @@
     .close          = decode_close,
     .decode         = decode_frame,
     .long_name      = NULL_IF_CONFIG_SMALL("Intel Indeo 3"),
+    .capabilities   = CODEC_CAP_DR1,
 };
diff --git a/libavcodec/indeo3data.h b/libavcodec/indeo3data.h
index e6f370c..0b5648e 100644
--- a/libavcodec/indeo3data.h
+++ b/libavcodec/indeo3data.h
@@ -320,7 +320,7 @@
 static const int32_t delta_tab_3_5_m10[79]  = { TAB_3_5 };
 
 
-typedef struct {
+typedef struct vqEntry {
     const int16_t  *deltas;     ///< delta tables for 4x4 block modes
     const int32_t  *deltas_m10; ///< delta tables for 8x8 block modes
     uint8_t        num_dyads;   ///< number of two-pixel deltas
diff --git a/libavcodec/indeo4.c b/libavcodec/indeo4.c
index d1f62b7..0766ed4 100644
--- a/libavcodec/indeo4.c
+++ b/libavcodec/indeo4.c
@@ -197,6 +197,7 @@
 
     /* decode subdivision of the planes */
     pic_conf.luma_bands = decode_plane_subdivision(&ctx->gb);
+    pic_conf.chroma_bands = 0;
     if (pic_conf.luma_bands)
         pic_conf.chroma_bands = decode_plane_subdivision(&ctx->gb);
     ctx->is_scalable = pic_conf.luma_bands != 1 || pic_conf.chroma_bands != 1;
@@ -364,6 +365,7 @@
                 return AVERROR_INVALIDDATA;
             }
             band->scan = scan_index_to_tab[scan_indx];
+            band->scan_size = band->blk_size;
 
             quant_mat = get_bits(&ctx->gb, 5);
             if (quant_mat == 31) {
@@ -381,6 +383,11 @@
             band->quant_mat = 0;
             return AVERROR_INVALIDDATA;
         }
+        if (band->scan_size != band->blk_size) {
+            av_log(avctx, AV_LOG_ERROR, "mismatching scan table!\n");
+            return AVERROR_INVALIDDATA;
+        }
+
         /* decode block huffman codebook */
         if (ff_ivi_dec_huff_desc(&ctx->gb, get_bits1(&ctx->gb), IVI_BLK_HUFF,
                                  &band->blk_vlc, avctx))
@@ -624,7 +631,7 @@
     ctx->pic_conf.pic_width  = 0;
     ctx->pic_conf.pic_height = 0;
 
-    avctx->pix_fmt = PIX_FMT_YUV410P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV410P;
 
     ctx->decode_pic_hdr   = decode_pic_hdr;
     ctx->decode_band_hdr  = decode_band_hdr;
@@ -645,4 +652,5 @@
     .close          = ff_ivi_decode_close,
     .decode         = ff_ivi_decode_frame,
     .long_name      = NULL_IF_CONFIG_SMALL("Intel Indeo Video Interactive 4"),
+    .capabilities   = CODEC_CAP_DR1,
 };
diff --git a/libavcodec/indeo5.c b/libavcodec/indeo5.c
index fd43e33..52dddd2 100644
--- a/libavcodec/indeo5.c
+++ b/libavcodec/indeo5.c
@@ -660,7 +660,7 @@
     ctx->switch_buffers   = switch_buffers;
     ctx->is_nonnull_frame = is_nonnull_frame;
 
-    avctx->pix_fmt = PIX_FMT_YUV410P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV410P;
 
     return 0;
 }
@@ -674,4 +674,5 @@
     .close          = ff_ivi_decode_close,
     .decode         = ff_ivi_decode_frame,
     .long_name      = NULL_IF_CONFIG_SMALL("Intel Indeo Video Interactive 5"),
+    .capabilities   = CODEC_CAP_DR1,
 };
diff --git a/libavcodec/internal.h b/libavcodec/internal.h
index f0114dc..17ca8bb 100644
--- a/libavcodec/internal.h
+++ b/libavcodec/internal.h
@@ -30,13 +30,15 @@
 #include "libavutil/pixfmt.h"
 #include "avcodec.h"
 
+#define FF_SANE_NB_CHANNELS 128U
+
 typedef struct InternalBuffer {
     uint8_t *base[AV_NUM_DATA_POINTERS];
     uint8_t *data[AV_NUM_DATA_POINTERS];
     int linesize[AV_NUM_DATA_POINTERS];
     int width;
     int height;
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
     uint8_t **extended_data;
     int audio_data_size;
     int nb_channels;
@@ -97,11 +99,6 @@
 };
 
 /**
- * Determine whether pix_fmt is a hardware accelerated format.
- */
-int ff_is_hwaccel_pix_fmt(enum PixelFormat pix_fmt);
-
-/**
  * Return the hardware accelerated codec for codec codec_id and
  * pixel format pix_fmt.
  *
@@ -109,7 +106,7 @@
  * @param pix_fmt the pixel format to match
  * @return the hardware accelerated codec, or NULL if none was found.
  */
-AVHWAccel *ff_find_hwaccel(enum AVCodecID codec_id, enum PixelFormat pix_fmt);
+AVHWAccel *ff_find_hwaccel(enum AVCodecID codec_id, enum AVPixelFormat pix_fmt);
 
 /**
  * Return the index into tab at which {a,b} match elements {[0],[1]} of tab.
@@ -178,4 +175,16 @@
 
 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx);
 
+/**
+ * Call avcodec_open2 recursively by decrementing counter, unlocking mutex,
+ * calling the function and then restoring again. Assumes the mutex is
+ * already locked
+ */
+int ff_codec_open2_recursive(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options);
+
+/**
+ * Call avcodec_close recursively, counterpart to avcodec_open2_recursive.
+ */
+int ff_codec_close_recursive(AVCodecContext *avctx);
+
 #endif /* AVCODEC_INTERNAL_H */
diff --git a/libavcodec/interplayvideo.c b/libavcodec/interplayvideo.c
index 3063b8e..6892936 100644
--- a/libavcodec/interplayvideo.c
+++ b/libavcodec/interplayvideo.c
@@ -941,7 +941,7 @@
     s->avctx = avctx;
 
     s->is_16bpp = avctx->bits_per_coded_sample == 16;
-    avctx->pix_fmt = s->is_16bpp ? PIX_FMT_RGB555 : PIX_FMT_PAL8;
+    avctx->pix_fmt = s->is_16bpp ? AV_PIX_FMT_RGB555 : AV_PIX_FMT_PAL8;
 
     ff_dsputil_init(&s->dsp, avctx);
 
diff --git a/libavcodec/intrax8.h b/libavcodec/intrax8.h
index dd2dc7d..40d689a 100644
--- a/libavcodec/intrax8.h
+++ b/libavcodec/intrax8.h
@@ -23,7 +23,7 @@
 #include "mpegvideo.h"
 #include "intrax8dsp.h"
 
-typedef struct{
+typedef struct IntraX8Context {
     VLC * j_ac_vlc[4];//they point to the static j_mb_vlc
     VLC * j_orient_vlc;
     VLC * j_dc_vlc[3];
diff --git a/libavcodec/inverse.c b/libavcodec/inverse.c
deleted file mode 100644
index 04681d2..0000000
--- a/libavcodec/inverse.c
+++ /dev/null
@@ -1 +0,0 @@
-#include "libavutil/inverse.c"
diff --git a/libavcodec/ituh263dec.c b/libavcodec/ituh263dec.c
index cd5d456..461af3a 100644
--- a/libavcodec/ituh263dec.c
+++ b/libavcodec/ituh263dec.c
@@ -100,11 +100,9 @@
 /* XXX: find a better solution to handle static init */
 void ff_h263_decode_init_vlc(MpegEncContext *s)
 {
-    static int done = 0;
+    static volatile int done = 0;
 
     if (!done) {
-        done = 1;
-
         INIT_VLC_STATIC(&ff_h263_intra_MCBPC_vlc, INTRA_MCBPC_VLC_BITS, 9,
                  ff_h263_intra_MCBPC_bits, 1, 1,
                  ff_h263_intra_MCBPC_code, 1, 1, 72);
@@ -127,6 +125,7 @@
         INIT_VLC_STATIC(&cbpc_b_vlc, CBPC_B_VLC_BITS, 4,
                  &ff_cbpc_b_tab[0][1], 2, 1,
                  &ff_cbpc_b_tab[0][0], 2, 1, 8);
+        done = 1;
     }
 }
 
@@ -205,16 +204,19 @@
  * @param end pointer to the end of the buffer
  * @return pointer to the next resync_marker, or end if none was found
  */
-const uint8_t *ff_h263_find_resync_marker(const uint8_t *av_restrict p, const uint8_t *av_restrict end)
+const uint8_t *ff_h263_find_resync_marker(MpegEncContext *s, const uint8_t *av_restrict p, const uint8_t *av_restrict end)
 {
     av_assert2(p < end);
 
     end-=2;
     p++;
-    for(;p<end; p+=2){
-        if(!*p){
-            if     (!p[-1] && p[1]) return p - 1;
-            else if(!p[ 1] && p[2]) return p;
+    if(s->resync_marker){
+        int prefix_len = ff_mpeg4_get_video_packet_prefix_length(s);
+        for(;p<end; p+=2){
+            if(!*p){
+                if      (!p[-1] && ((p[1] >> (23-prefix_len)) == 1)) return p - 1;
+                else if (!p[ 1] && ((p[2] >> (23-prefix_len)) == 1)) return p;
+            }
         }
     }
     return end+2;
@@ -1071,6 +1073,10 @@
         s->qscale = get_bits(&s->gb, 5);
     }
 
+    if (s->width == 0 || s->height == 0) {
+        av_log(s->avctx, AV_LOG_ERROR, "dimensions 0\n");
+        return -1;
+    }
     s->mb_width = (s->width  + 15) / 16;
     s->mb_height = (s->height  + 15) / 16;
     s->mb_num = s->mb_width * s->mb_height;
diff --git a/libavcodec/ivi_common.c b/libavcodec/ivi_common.c
index 9ecf9cd..c20ce77 100644
--- a/libavcodec/ivi_common.c
+++ b/libavcodec/ivi_common.c
@@ -27,10 +27,11 @@
  */
 
 #define BITSTREAM_READER_LE
+#include "libavutil/attributes.h"
 #include "avcodec.h"
 #include "get_bits.h"
+#include "mathops.h"
 #include "ivi_common.h"
-#include "libavutil/common.h"
 #include "ivi_dsp.h"
 
 extern const IVIHuffDesc ff_ivi_mb_huff_desc[8];  ///< static macroblock huffman tables
@@ -48,9 +49,9 @@
     uint16_t res;
 
     if (nbits <= 8) {
-        res = av_reverse[val] >> (8-nbits);
+        res = ff_reverse[val] >> (8-nbits);
     } else
-        res = ((av_reverse[val & 0xFF] << 8) + (av_reverse[val >> 8])) >> (16-nbits);
+        res = ((ff_reverse[val & 0xFF] << 8) + (ff_reverse[val >> 8])) >> (16-nbits);
 
     return res;
 }
@@ -238,6 +239,7 @@
     int p, b, t;
 
     for (p = 0; p < 3; p++) {
+        if (planes[p].bands)
         for (b = 0; b < planes[p].num_bands; b++) {
             av_freep(&planes[p].bands[b].bufs[0]);
             av_freep(&planes[p].bands[b].bufs[1]);
@@ -306,7 +308,10 @@
 
                     tile->ref_mbs = 0;
                     if (p || b) {
-                        tile->ref_mbs = ref_tile->mbs;
+                        if (tile->num_MBs <= ref_tile->num_MBs) {
+                            tile->ref_mbs = ref_tile->mbs;
+                        }else
+                            av_log(NULL, AV_LOG_DEBUG, "Cannot use ref_tile, too few mbs\n");
                         ref_tile++;
                     }
 
@@ -461,7 +466,7 @@
                     col_flags[0] |= !!prev_dc;
                 }
                 if(band->transform_size > band->blk_size){
-                    av_log(0, AV_LOG_ERROR, "Too large transform\n");
+                    av_log(NULL, AV_LOG_ERROR, "Too large transform\n");
                     return AVERROR_INVALIDDATA;
                 }
                 /* apply inverse transform */
@@ -477,7 +482,7 @@
                 /* block not coded */
                 /* for intra blocks apply the dc slant transform */
                 /* for inter - perform the motion compensation without delta */
-                if (is_intra && band->dc_transform) {
+                if (is_intra) {
                     band->dc_transform(&prev_dc, band->buf + buf_offs,
                                        band->pitch, blk_size);
                 } else
@@ -558,6 +563,22 @@
                     mb->mv_y = ref_mb->mv_y;
                 }
                 need_mc |= mb->mv_x || mb->mv_y; /* tracking non-zero motion vectors */
+                {
+                    int dmv_x, dmv_y, cx, cy;
+
+                    dmv_x = mb->mv_x >> band->is_halfpel;
+                    dmv_y = mb->mv_y >> band->is_halfpel;
+                    cx    = mb->mv_x &  band->is_halfpel;
+                    cy    = mb->mv_y &  band->is_halfpel;
+
+                    if (   mb->xpos + dmv_x < 0
+                        || mb->xpos + dmv_x + band->mb_size + cx > band->pitch
+                        || mb->ypos + dmv_y < 0
+                        || mb->ypos + dmv_y + band->mb_size + cy > band->aheight) {
+                        av_log(avctx, AV_LOG_ERROR, "MV out of bounds\n");
+                        return AVERROR_INVALIDDATA;
+                    }
+                }
             }
 
             mb++;
@@ -649,7 +670,7 @@
  *  @param[in]      avctx  ptr to the AVCodecContext
  *  @return         result code: 0 = OK, -1 = error
  */
-static int decode_band(IVI45DecContext *ctx, int plane_num,
+static int decode_band(IVI45DecContext *ctx,
                        IVIBandDesc *band, AVCodecContext *avctx)
 {
     int         result, i, t, idx1, idx2, pos;
@@ -790,7 +811,7 @@
         ctx->buf_invalid[ctx->dst_buf] = 1;
         for (p = 0; p < 3; p++) {
             for (b = 0; b < ctx->planes[p].num_bands; b++) {
-                result = decode_band(ctx, p, &ctx->planes[p].bands[b], avctx);
+                result = decode_band(ctx, &ctx->planes[p].bands[b], avctx);
                 if (result) {
                     av_log(avctx, AV_LOG_ERROR,
                            "Error while decoding band: %d, plane: %d\n", b, p);
@@ -830,9 +851,9 @@
 
     if (ctx->is_scalable) {
         if (avctx->codec_id == AV_CODEC_ID_INDEO4)
-            ff_ivi_recompose_haar(&ctx->planes[0], ctx->frame.data[0], ctx->frame.linesize[0], 4);
+            ff_ivi_recompose_haar(&ctx->planes[0], ctx->frame.data[0], ctx->frame.linesize[0]);
         else
-            ff_ivi_recompose53   (&ctx->planes[0], ctx->frame.data[0], ctx->frame.linesize[0], 4);
+            ff_ivi_recompose53   (&ctx->planes[0], ctx->frame.data[0], ctx->frame.linesize[0]);
     } else {
         ff_ivi_output_plane(&ctx->planes[0], ctx->frame.data[0], ctx->frame.linesize[0]);
     }
diff --git a/libavcodec/ivi_common.h b/libavcodec/ivi_common.h
index 4636f6c..e3afe43 100644
--- a/libavcodec/ivi_common.h
+++ b/libavcodec/ivi_common.h
@@ -40,7 +40,7 @@
 /**
  *  huffman codebook descriptor
  */
-typedef struct {
+typedef struct IVIHuffDesc {
     int32_t     num_rows;
     uint8_t     xbits[16];
 } IVIHuffDesc;
@@ -48,7 +48,7 @@
 /**
  *  macroblock/block huffman table descriptor
  */
-typedef struct {
+typedef struct IVIHuffTab {
     int32_t     tab_sel;    /// index of one of the predefined tables
                             /// or "7" for custom one
     VLC         *tab;       /// pointer to the table associated with tab_sel
@@ -85,7 +85,7 @@
 /**
  *  run-value (RLE) table descriptor
  */
-typedef struct {
+typedef struct RVMapDesc {
     uint8_t     eob_sym; ///< end of block symbol
     uint8_t     esc_sym; ///< escape symbol
     uint8_t     runtab[256];
@@ -98,7 +98,7 @@
 /**
  *  information for Indeo macroblock (16x16, 8x8 or 4x4)
  */
-typedef struct {
+typedef struct IVIMbInfo {
     int16_t     xpos;
     int16_t     ypos;
     uint32_t    buf_offs; ///< address in the output buffer for this mb
@@ -113,7 +113,7 @@
 /**
  *  information for Indeo tile
  */
-typedef struct {
+typedef struct IVITile {
     int         xpos;
     int         ypos;
     int         width;
@@ -130,7 +130,7 @@
 /**
  *  information for Indeo wavelet band
  */
-typedef struct {
+typedef struct IVIBandDesc {
     int             plane;          ///< plane number this band belongs to
     int             band_num;       ///< band number
     int             width;
@@ -152,6 +152,7 @@
     int             quant_mat;      ///< dequant matrix index
     int             glob_quant;     ///< quant base for this band
     const uint8_t   *scan;          ///< ptr to the scan pattern
+    int             scan_size;      ///< size of the scantable
 
     IVIHuffTab      blk_vlc;        ///< vlc table for decoding block data
 
@@ -178,7 +179,7 @@
 /**
  *  color plane (luma or chroma) information
  */
-typedef struct {
+typedef struct IVIPlaneDesc {
     uint16_t    width;
     uint16_t    height;
     uint8_t     num_bands;  ///< number of bands this plane subdivided into
@@ -186,7 +187,7 @@
 } IVIPlaneDesc;
 
 
-typedef struct {
+typedef struct IVIPicConfig {
     uint16_t    pic_width;
     uint16_t    pic_height;
     uint16_t    chroma_width;
diff --git a/libavcodec/ivi_dsp.c b/libavcodec/ivi_dsp.c
index bedd5dc..52cd402 100644
--- a/libavcodec/ivi_dsp.c
+++ b/libavcodec/ivi_dsp.c
@@ -33,7 +33,7 @@
 #include "ivi_dsp.h"
 
 void ff_ivi_recompose53(const IVIPlaneDesc *plane, uint8_t *dst,
-                        const int dst_pitch, const int num_bands)
+                        const int dst_pitch)
 {
     int             x, y, indx;
     int32_t         p0, p1, p2, p3, tmp0, tmp1, tmp2;
@@ -41,6 +41,7 @@
     int32_t         b3_1, b3_2, b3_3, b3_4, b3_5, b3_6, b3_7, b3_8, b3_9;
     int32_t         pitch, back_pitch;
     const IDWTELEM *b0_ptr, *b1_ptr, *b2_ptr, *b3_ptr;
+    const int       num_bands = 4;
 
     /* all bands should have the same pitch */
     pitch = plane->bands[0].pitch;
@@ -189,7 +190,7 @@
 }
 
 void ff_ivi_recompose_haar(const IVIPlaneDesc *plane, uint8_t *dst,
-                           const int dst_pitch, const int num_bands)
+                           const int dst_pitch)
 {
     int             x, y, indx, b0, b1, b2, b3, p0, p1, p2, p3;
     const IDWTELEM *b0_ptr, *b1_ptr, *b2_ptr, *b3_ptr;
diff --git a/libavcodec/ivi_dsp.h b/libavcodec/ivi_dsp.h
index 5a34417..e95bb11 100644
--- a/libavcodec/ivi_dsp.h
+++ b/libavcodec/ivi_dsp.h
@@ -38,10 +38,9 @@
  *  @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);
+                        const int dst_pitch);
 
 /**
  *  Haar wavelet recomposition filter for Indeo 4
@@ -49,10 +48,9 @@
  *  @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_recompose_haar(const IVIPlaneDesc *plane, uint8_t *dst,
-                           const int dst_pitch, const int num_bands);
+                           const int dst_pitch);
 
 /**
  *  two-dimensional inverse Haar 8x8 transform for Indeo 4
diff --git a/libavcodec/j2k.c b/libavcodec/j2k.c
index 606a3d8..f5b40b1 100644
--- a/libavcodec/j2k.c
+++ b/libavcodec/j2k.c
@@ -285,10 +285,10 @@
             band->cblknx = ff_j2k_ceildiv(band->cblknx, dx);
             band->cblkny = ff_j2k_ceildiv(band->cblkny, dy);
 
-            band->cblk = av_malloc(band->cblknx * band->cblkny * sizeof(J2kCblk));
+            band->cblk = av_malloc(sizeof(J2kCblk) * band->cblknx * band->cblkny);
             if (!band->cblk)
                 return AVERROR(ENOMEM);
-            band->prec = av_malloc(reslevel->num_precincts_x * reslevel->num_precincts_y * sizeof(J2kPrec));
+            band->prec = av_malloc(sizeof(J2kCblk) * reslevel->num_precincts_x * reslevel->num_precincts_y);
             if (!band->prec)
                 return AVERROR(ENOMEM);
 
diff --git a/libavcodec/j2kdec.c b/libavcodec/j2kdec.c
index b3ba8fc..de94f51 100644
--- a/libavcodec/j2kdec.c
+++ b/libavcodec/j2kdec.c
@@ -69,7 +69,7 @@
 
     int bit_index;
 
-    int16_t curtileno;
+    int curtileno;
 
     J2kTile *tile;
 } J2kDecoderContext;
@@ -167,6 +167,9 @@
     J2kTgtNode *stack[30];
     int sp = -1, curval = 0;
 
+    if(!node)
+        return AVERROR(EINVAL);
+
     while(node && !node->vis){
         stack[++sp] = node;
         node = node->parent;
@@ -260,20 +263,20 @@
     switch(s->ncomponents){
     case 1:
         if (s->precision > 8) {
-            s->avctx->pix_fmt = PIX_FMT_GRAY16;
+            s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
         } else {
-            s->avctx->pix_fmt = PIX_FMT_GRAY8;
+            s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
         }
         break;
     case 3:
         if (s->precision > 8) {
-            s->avctx->pix_fmt = PIX_FMT_RGB48;
+            s->avctx->pix_fmt = AV_PIX_FMT_RGB48;
         } else {
-            s->avctx->pix_fmt = PIX_FMT_RGB24;
+            s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
         }
         break;
     case 4:
-        s->avctx->pix_fmt = PIX_FMT_RGBA;
+        s->avctx->pix_fmt = AV_PIX_FMT_RGBA;
         break;
     }
 
@@ -833,7 +836,7 @@
                                 int *ptr = t1.data[y-yy0];
                                 for (x = xx0; x < xx1; x+=s->cdx[compno]){
                                     int tmp = ((int64_t)*ptr++) * ((int64_t)band->stepsize) >> 13, tmp2;
-                                    tmp2 = FFABS(tmp>>1) + FFABS(tmp&1);
+                                    tmp2 = FFABS(tmp>>1) + (tmp&1);
                                     comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] = tmp < 0 ? -tmp2 : tmp2;
                                 }
                             }
diff --git a/libavcodec/j2kenc.c b/libavcodec/j2kenc.c
index 6e4ae16..c1a4981 100644
--- a/libavcodec/j2kenc.c
+++ b/libavcodec/j2kenc.c
@@ -286,7 +286,7 @@
     // SGcod
     bytestream_put_byte(&s->buf, 0); // progression level
     bytestream_put_be16(&s->buf, 1); // num of layers
-    if(s->avctx->pix_fmt == PIX_FMT_YUV444P){
+    if(s->avctx->pix_fmt == AV_PIX_FMT_YUV444P){
         bytestream_put_byte(&s->buf, 2); // ICT
     }else{
         bytestream_put_byte(&s->buf, 0); // unspecified
@@ -871,7 +871,7 @@
                                 for (x = xx0; x < xx1; x++){
                                     *ptr = (comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x]);
                                     *ptr = (int64_t)*ptr * (int64_t)(8192 * 8192 / band->stepsize) >> 13 - NMSEDEC_FRACBITS;
-                                    *ptr++;
+                                    ptr++;
                                 }
                             }
                         }
@@ -1010,9 +1010,9 @@
     for (i = 0; i < 3; i++)
         s->cbps[i] = 8;
 
-    if (avctx->pix_fmt == PIX_FMT_RGB24){
+    if (avctx->pix_fmt == AV_PIX_FMT_RGB24){
         s->ncomponents = 3;
-    } else if (avctx->pix_fmt == PIX_FMT_GRAY8){
+    } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY8){
         s->ncomponents = 1;
     } else{ // planar YUV
         s->planar = 1;
@@ -1052,11 +1052,11 @@
     .close          = j2kenc_destroy,
     .capabilities   = CODEC_CAP_EXPERIMENTAL,
     .long_name      = NULL_IF_CONFIG_SMALL("JPEG 2000"),
-    .pix_fmts       = (const enum PixelFormat[]) {
-        PIX_FMT_RGB24, PIX_FMT_YUV444P, PIX_FMT_GRAY8,
-/*      PIX_FMT_YUV420P,
-        PIX_FMT_YUV422P, PIX_FMT_YUV444P,
-        PIX_FMT_YUV410P, PIX_FMT_YUV411P,*/
-        PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]) {
+        AV_PIX_FMT_RGB24, AV_PIX_FMT_YUV444P, AV_PIX_FMT_GRAY8,
+/*      AV_PIX_FMT_YUV420P,
+        AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P,
+        AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,*/
+        AV_PIX_FMT_NONE
     }
 };
diff --git a/libavcodec/jpegls.h b/libavcodec/jpegls.h
index 88e65c9..0a6ead3 100644
--- a/libavcodec/jpegls.h
+++ b/libavcodec/jpegls.h
@@ -41,7 +41,7 @@
     int A[367], B[367], C[365], N[367];
     int limit, reset, bpp, qbpp, maxval, range;
     int near, twonear;
-    int run_index[3];
+    int run_index[4];
 }JLSState;
 
 extern const uint8_t ff_log2_run[32];
diff --git a/libavcodec/jpeglsdec.c b/libavcodec/jpeglsdec.c
index db230cf..516a82f 100644
--- a/libavcodec/jpeglsdec.c
+++ b/libavcodec/jpeglsdec.c
@@ -295,7 +295,7 @@
     }
     if(ilv == 0) { /* separate planes */
         stride = (s->nb_components > 1) ? 3 : 1;
-        off = av_clip(s->cur_scan - 1, 0, stride);
+        off = av_clip(s->cur_scan - 1, 0, stride - 1);
         width = s->width * stride;
         cur += off;
         for(i = 0; i < s->height; i++) {
diff --git a/libavcodec/jpeglsenc.c b/libavcodec/jpeglsenc.c
index 938ce88..e51e47a 100644
--- a/libavcodec/jpeglsenc.c
+++ b/libavcodec/jpeglsenc.c
@@ -244,7 +244,7 @@
     p->pict_type= AV_PICTURE_TYPE_I;
     p->key_frame= 1;
 
-    if(avctx->pix_fmt == PIX_FMT_GRAY8 || avctx->pix_fmt == PIX_FMT_GRAY16)
+    if(avctx->pix_fmt == AV_PIX_FMT_GRAY8 || avctx->pix_fmt == AV_PIX_FMT_GRAY16)
         comps = 1;
     else
         comps = 3;
@@ -262,7 +262,7 @@
     put_marker(&pb, SOI);
     put_marker(&pb, SOF48);
     put_bits(&pb, 16, 8 + comps * 3); // header size depends on components
-    put_bits(&pb,  8, (avctx->pix_fmt == PIX_FMT_GRAY16) ? 16 : 8); // bpp
+    put_bits(&pb,  8, (avctx->pix_fmt == AV_PIX_FMT_GRAY16) ? 16 : 8); // bpp
     put_bits(&pb, 16, avctx->height);
     put_bits(&pb, 16, avctx->width);
     put_bits(&pb,  8, comps);         // components
@@ -286,18 +286,20 @@
     state = av_mallocz(sizeof(JLSState));
     /* initialize JPEG-LS state from JPEG parameters */
     state->near = near;
-    state->bpp = (avctx->pix_fmt == PIX_FMT_GRAY16) ? 16 : 8;
+    state->bpp = (avctx->pix_fmt == AV_PIX_FMT_GRAY16) ? 16 : 8;
     ff_jpegls_reset_coding_parameters(state, 0);
     ff_jpegls_init_state(state);
 
     ls_store_lse(state, &pb);
 
     zero = av_mallocz(FFABS(p->linesize[0]));
-    if (!zero)
+    if (!zero) {
+        av_free(state);
         return AVERROR(ENOMEM);
+    }
     last = zero;
     cur = p->data[0];
-    if(avctx->pix_fmt == PIX_FMT_GRAY8){
+    if(avctx->pix_fmt == AV_PIX_FMT_GRAY8){
         int t = 0;
 
         for(i = 0; i < avctx->height; i++) {
@@ -306,7 +308,7 @@
             last = cur;
             cur += p->linesize[0];
         }
-    }else if(avctx->pix_fmt == PIX_FMT_GRAY16){
+    }else if(avctx->pix_fmt == AV_PIX_FMT_GRAY16){
         int t = 0;
 
         for(i = 0; i < avctx->height; i++) {
@@ -315,7 +317,7 @@
             last = cur;
             cur += p->linesize[0];
         }
-    }else if(avctx->pix_fmt == PIX_FMT_RGB24){
+    }else if(avctx->pix_fmt == AV_PIX_FMT_RGB24){
         int j, width;
         int Rc[3] = {0, 0, 0};
 
@@ -328,7 +330,7 @@
             last = cur;
             cur += s->picture.linesize[0];
         }
-    }else if(avctx->pix_fmt == PIX_FMT_BGR24){
+    }else if(avctx->pix_fmt == AV_PIX_FMT_BGR24){
         int j, width;
         int Rc[3] = {0, 0, 0};
 
@@ -343,8 +345,8 @@
         }
     }
 
-    av_free(zero);
-    av_free(state);
+    av_freep(&zero);
+    av_freep(&state);
 
     // the specification says that after doing 0xff escaping unused bits in the
     // last byte must be set to 0, so just append 7 "optional" zero-bits to
@@ -385,7 +387,7 @@
     c->avctx = ctx;
     ctx->coded_frame = &c->picture;
 
-    if(ctx->pix_fmt != PIX_FMT_GRAY8 && ctx->pix_fmt != PIX_FMT_GRAY16 && ctx->pix_fmt != PIX_FMT_RGB24 && ctx->pix_fmt != PIX_FMT_BGR24){
+    if(ctx->pix_fmt != AV_PIX_FMT_GRAY8 && ctx->pix_fmt != AV_PIX_FMT_GRAY16 && ctx->pix_fmt != AV_PIX_FMT_RGB24 && ctx->pix_fmt != AV_PIX_FMT_BGR24){
         av_log(ctx, AV_LOG_ERROR, "Only grayscale and RGB24/BGR24 images are supported\n");
         return -1;
     }
@@ -399,9 +401,9 @@
     .priv_data_size = sizeof(JpeglsContext),
     .init           = encode_init_ls,
     .encode2        = encode_picture_ls,
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_BGR24, PIX_FMT_RGB24, PIX_FMT_GRAY8, PIX_FMT_GRAY16,
-        PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_BGR24, AV_PIX_FMT_RGB24, AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY16,
+        AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("JPEG-LS"),
 };
diff --git a/libavcodec/jvdec.c b/libavcodec/jvdec.c
index 81345f2..5e54a16 100644
--- a/libavcodec/jvdec.c
+++ b/libavcodec/jvdec.c
@@ -40,7 +40,7 @@
 static av_cold int decode_init(AVCodecContext *avctx)
 {
     JvContext *s = avctx->priv_data;
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
     ff_dsputil_init(&s->dsp, avctx);
     return 0;
 }
@@ -135,7 +135,7 @@
     JvContext *s           = avctx->priv_data;
     const uint8_t *buf     = avpkt->data;
     const uint8_t *buf_end = buf + avpkt->size;
-    int video_size, video_type, i, j;
+    int video_size, video_type, ret, i, j;
 
     if (avpkt->size < 6)
         return AVERROR_INVALIDDATA;
@@ -149,9 +149,9 @@
             av_log(avctx, AV_LOG_ERROR, "video size %d invalid\n", video_size);
             return AVERROR_INVALIDDATA;
         }
-        if (avctx->reget_buffer(avctx, &s->frame) < 0) {
+        if ((ret = avctx->reget_buffer(avctx, &s->frame)) < 0) {
             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-            return -1;
+            return ret;
         }
 
         if (video_type == 0 || video_type == 1) {
@@ -177,7 +177,7 @@
     if (buf_end - buf >= AVPALETTE_COUNT * 3) {
         for (i = 0; i < AVPALETTE_COUNT; i++) {
             uint32_t pal = AV_RB24(buf);
-            s->palette[i] = 0xFF << 24 | pal << 2 | ((pal >> 4) & 0x30303);
+            s->palette[i] = 0xFFU << 24 | pal << 2 | ((pal >> 4) & 0x30303);
             buf += 3;
         }
         s->palette_has_changed = 1;
diff --git a/libavcodec/kgv1dec.c b/libavcodec/kgv1dec.c
index d416661..6c1daa9 100644
--- a/libavcodec/kgv1dec.c
+++ b/libavcodec/kgv1dec.c
@@ -83,7 +83,7 @@
     for (i = 0; i < 8; i++)
         offsets[i] = -1;
 
-    while (outcnt < maxcnt && buf_end - 2 > buf) {
+    while (outcnt < maxcnt && buf_end - 2 >= buf) {
         int code = AV_RL16(buf);
         buf += 2;
 
@@ -169,7 +169,7 @@
     KgvContext * const c = avctx->priv_data;
 
     c->avctx = avctx;
-    avctx->pix_fmt = PIX_FMT_RGB555;
+    avctx->pix_fmt = AV_PIX_FMT_RGB555;
     avctx->flags  |= CODEC_FLAG_EMU_EDGE;
 
     return 0;
@@ -191,4 +191,5 @@
     .decode         = decode_frame,
     .flush          = decode_flush,
     .long_name      = NULL_IF_CONFIG_SMALL("Kega Game Video"),
+    .capabilities   = CODEC_CAP_DR1,
 };
diff --git a/libavcodec/kmvc.c b/libavcodec/kmvc.c
index cde410e..2046d28 100644
--- a/libavcodec/kmvc.c
+++ b/libavcodec/kmvc.c
@@ -266,6 +266,7 @@
     int header;
     int blocksize;
     const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);
+    int ret;
 
     bytestream2_init(&ctx->g, avpkt->data, avpkt->size);
     if (ctx->pic.data[0])
@@ -273,9 +274,9 @@
 
     ctx->pic.reference = 3;
     ctx->pic.buffer_hints = FF_BUFFER_HINTS_VALID;
-    if (avctx->get_buffer(avctx, &ctx->pic) < 0) {
+    if ((ret = avctx->get_buffer(avctx, &ctx->pic)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
+        return ret;
     }
 
     header = bytestream2_get_byte(&ctx->g);
@@ -323,7 +324,7 @@
 
     if (blocksize != 8 && blocksize != 127) {
         av_log(avctx, AV_LOG_ERROR, "Block size = %i\n", blocksize);
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
     memset(ctx->cur, 0, 320 * 200);
     switch (header & KMVC_METHOD) {
@@ -339,7 +340,7 @@
         break;
     default:
         av_log(avctx, AV_LOG_ERROR, "Unknown compression method %i\n", header & KMVC_METHOD);
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     out = ctx->pic.data[0];
@@ -380,7 +381,7 @@
 
     if (avctx->width > 320 || avctx->height > 200) {
         av_log(avctx, AV_LOG_ERROR, "KMVC supports frames <= 320x200\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     c->frm0 = av_mallocz(320 * 200);
@@ -389,7 +390,7 @@
     c->prev = c->frm1;
 
     for (i = 0; i < 256; i++) {
-        c->pal[i] = 0xFF << 24 | i * 0x10101;
+        c->pal[i] = 0xFFU << 24 | i * 0x10101;
     }
 
     if (avctx->extradata_size < 12) {
@@ -415,7 +416,7 @@
     }
 
     avcodec_get_frame_defaults(&c->pic);
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     return 0;
 }
diff --git a/libavcodec/lagarith.c b/libavcodec/lagarith.c
index 261e39c..d0a5049 100644
--- a/libavcodec/lagarith.c
+++ b/libavcodec/lagarith.c
@@ -158,8 +158,8 @@
                 av_log(rac->avctx, AV_LOG_ERROR, "Invalid probability run encountered.\n");
                 return -1;
             }
-            if (prob > 257 - i)
-                prob = 257 - i;
+            if (prob > 256 - i)
+                prob = 256 - i;
             for (j = 0; j < prob; j++)
                 rac->prob[++i] = 0;
         }
@@ -259,7 +259,7 @@
         if (line == 1) {
             /* Second line, left predict first pixel, the rest of the line is median predicted
              * NOTE: In the case of RGB this pixel is top predicted */
-            TL = l->avctx->pix_fmt == PIX_FMT_YUV420P ? buf[-stride] : L;
+            TL = l->avctx->pix_fmt == AV_PIX_FMT_YUV420P ? buf[-stride] : L;
         } else {
             /* Top left is 2 rows back, last pixel */
             TL = buf[width - (2 * stride) - 1];
@@ -482,7 +482,7 @@
         return -1;
     }
 
-    if (l->avctx->pix_fmt != PIX_FMT_YUV422P) {
+    if (l->avctx->pix_fmt != AV_PIX_FMT_YUV422P) {
         for (i = 0; i < height; i++) {
             lag_pred_line(l, dst, width, stride, i);
             dst += stride;
@@ -534,7 +534,7 @@
 
     switch (frametype) {
     case FRAME_SOLID_RGBA:
-        avctx->pix_fmt = PIX_FMT_RGB32;
+        avctx->pix_fmt = AV_PIX_FMT_RGB32;
 
         if (ff_thread_get_buffer(avctx, p) < 0) {
             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
@@ -549,14 +549,14 @@
         }
         break;
     case FRAME_ARITH_RGBA:
-        avctx->pix_fmt = PIX_FMT_RGB32;
+        avctx->pix_fmt = AV_PIX_FMT_RGB32;
         planes = 4;
         offset_ry += 4;
         offs[3] = AV_RL32(buf + 9);
     case FRAME_ARITH_RGB24:
     case FRAME_U_RGB24:
         if (frametype == FRAME_ARITH_RGB24 || frametype == FRAME_U_RGB24)
-            avctx->pix_fmt = PIX_FMT_RGB24;
+            avctx->pix_fmt = AV_PIX_FMT_RGB24;
 
         if (ff_thread_get_buffer(avctx, p) < 0) {
             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
@@ -569,7 +569,7 @@
 
         if (!l->rgb_planes) {
             l->rgb_stride = FFALIGN(avctx->width, 16);
-            l->rgb_planes = av_malloc(l->rgb_stride * avctx->height * planes + 16);
+            l->rgb_planes = av_malloc(l->rgb_stride * avctx->height * 4 + 16);
             if (!l->rgb_planes) {
                 av_log(avctx, AV_LOG_ERROR, "cannot allocate temporary buffer\n");
                 return AVERROR(ENOMEM);
@@ -615,7 +615,7 @@
         }
         break;
     case FRAME_ARITH_YUY2:
-        avctx->pix_fmt = PIX_FMT_YUV422P;
+        avctx->pix_fmt = AV_PIX_FMT_YUV422P;
 
         if (ff_thread_get_buffer(avctx, p) < 0) {
             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
@@ -641,7 +641,7 @@
                                buf + offset_bv, buf_size - offset_bv);
         break;
     case FRAME_ARITH_YV12:
-        avctx->pix_fmt = PIX_FMT_YUV420P;
+        avctx->pix_fmt = AV_PIX_FMT_YUV420P;
 
         if (ff_thread_get_buffer(avctx, p) < 0) {
             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
diff --git a/libavcodec/lcldec.c b/libavcodec/lcldec.c
index f180373..66db7c7 100644
--- a/libavcodec/lcldec.c
+++ b/libavcodec/lcldec.c
@@ -41,10 +41,10 @@
 #include <stdio.h>
 #include <stdlib.h>
 
+#include "libavutil/mem.h"
 #include "avcodec.h"
 #include "bytestream.h"
 #include "lcl.h"
-#include "libavutil/lzo.h"
 
 #if CONFIG_ZLIB_DECODER
 #include <zlib.h>
@@ -198,7 +198,9 @@
     case AV_CODEC_ID_MSZH:
         switch (c->compression) {
         case COMP_MSZH:
-            if (c->flags & FLAG_MULTITHREAD) {
+            if (c->imgtype == IMGTYPE_RGB24 && len == width * height * 3) {
+                ;
+            } else if (c->flags & FLAG_MULTITHREAD) {
                 mthread_inlen = AV_RL32(encoded);
                 mthread_inlen = FFMIN(mthread_inlen, len - 8);
                 mthread_outlen = AV_RL32(encoded+4);
@@ -482,7 +484,8 @@
 {
     LclDecContext * const c = avctx->priv_data;
     unsigned int basesize = avctx->width * avctx->height;
-    unsigned int max_basesize = FFALIGN(avctx->width, 4) * FFALIGN(avctx->height, 4) + AV_LZO_OUTPUT_PADDING;
+    unsigned int max_basesize = FFALIGN(avctx->width,  4) *
+                                FFALIGN(avctx->height, 4);
     unsigned int max_decomp_size;
 
     avcodec_get_frame_defaults(&c->pic);
@@ -502,37 +505,37 @@
     case IMGTYPE_YUV111:
         c->decomp_size = basesize * 3;
         max_decomp_size = max_basesize * 3;
-        avctx->pix_fmt = PIX_FMT_YUV444P;
+        avctx->pix_fmt = AV_PIX_FMT_YUV444P;
         av_log(avctx, AV_LOG_DEBUG, "Image type is YUV 1:1:1.\n");
         break;
     case IMGTYPE_YUV422:
         c->decomp_size = basesize * 2;
         max_decomp_size = max_basesize * 2;
-        avctx->pix_fmt = PIX_FMT_YUV422P;
+        avctx->pix_fmt = AV_PIX_FMT_YUV422P;
         av_log(avctx, AV_LOG_DEBUG, "Image type is YUV 4:2:2.\n");
         break;
     case IMGTYPE_RGB24:
         c->decomp_size = basesize * 3;
         max_decomp_size = max_basesize * 3;
-        avctx->pix_fmt = PIX_FMT_BGR24;
+        avctx->pix_fmt = AV_PIX_FMT_BGR24;
         av_log(avctx, AV_LOG_DEBUG, "Image type is RGB 24.\n");
         break;
     case IMGTYPE_YUV411:
         c->decomp_size = basesize / 2 * 3;
         max_decomp_size = max_basesize / 2 * 3;
-        avctx->pix_fmt = PIX_FMT_YUV411P;
+        avctx->pix_fmt = AV_PIX_FMT_YUV411P;
         av_log(avctx, AV_LOG_DEBUG, "Image type is YUV 4:1:1.\n");
         break;
     case IMGTYPE_YUV211:
         c->decomp_size = basesize * 2;
         max_decomp_size = max_basesize * 2;
-        avctx->pix_fmt = PIX_FMT_YUV422P;
+        avctx->pix_fmt = AV_PIX_FMT_YUV422P;
         av_log(avctx, AV_LOG_DEBUG, "Image type is YUV 2:1:1.\n");
         break;
     case IMGTYPE_YUV420:
         c->decomp_size = basesize / 2 * 3;
         max_decomp_size = max_basesize / 2 * 3;
-        avctx->pix_fmt = PIX_FMT_YUV420P;
+        avctx->pix_fmt = AV_PIX_FMT_YUV420P;
         av_log(avctx, AV_LOG_DEBUG, "Image type is YUV 4:2:0.\n");
         break;
     default:
diff --git a/libavcodec/lclenc.c b/libavcodec/lclenc.c
index af5d6de..09beb98 100644
--- a/libavcodec/lclenc.c
+++ b/libavcodec/lclenc.c
@@ -88,7 +88,7 @@
     p->pict_type= AV_PICTURE_TYPE_I;
     p->key_frame= 1;
 
-    if(avctx->pix_fmt != PIX_FMT_BGR24){
+    if(avctx->pix_fmt != AV_PIX_FMT_BGR24){
         av_log(avctx, AV_LOG_ERROR, "Format not supported!\n");
         return -1;
     }
@@ -140,8 +140,9 @@
     avctx->extradata= av_mallocz(8);
     avctx->coded_frame= &c->pic;
 
-    // Will be user settable someday
-    c->compression = 6;
+    c->compression = avctx->compression_level == FF_COMPRESSION_DEFAULT ?
+                            COMP_ZLIB_NORMAL :
+                            av_clip(avctx->compression_level, 0, 9);
     c->flags = 0;
     c->imgtype = IMGTYPE_RGB24;
     avctx->bits_per_coded_sample= 24;
@@ -191,6 +192,6 @@
     .init           = encode_init,
     .encode2        = encode_frame,
     .close          = encode_end,
-    .pix_fmts       = (const enum PixelFormat[]) { PIX_FMT_BGR24, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_BGR24, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("LCL (LossLess Codec Library) ZLIB"),
 };
diff --git a/libavcodec/libfaac.c b/libavcodec/libfaac.c
index 0bfed1e..a7bf503 100644
--- a/libavcodec/libfaac.c
+++ b/libavcodec/libfaac.c
@@ -26,11 +26,11 @@
 
 #include <faac.h>
 
+#include "libavutil/channel_layout.h"
+#include "libavutil/common.h"
 #include "avcodec.h"
 #include "audio_frame_queue.h"
 #include "internal.h"
-#include "libavutil/audioconvert.h"
-#include "libavutil/common.h"
 
 
 /* libfaac has an encoder delay of 1024 samples */
diff --git a/libavcodec/libfdk-aacenc.c b/libavcodec/libfdk-aacenc.c
index 2874e37..c2d8a2b 100644
--- a/libavcodec/libfdk-aacenc.c
+++ b/libavcodec/libfdk-aacenc.c
@@ -21,12 +21,12 @@
 
 #include <fdk-aac/aacenc_lib.h>
 
+#include "libavutil/channel_layout.h"
+#include "libavutil/common.h"
+#include "libavutil/opt.h"
 #include "avcodec.h"
 #include "audio_frame_queue.h"
 #include "internal.h"
-#include "libavutil/audioconvert.h"
-#include "libavutil/common.h"
-#include "libavutil/opt.h"
 
 typedef struct AACContext {
     const AVClass *class;
diff --git a/libavcodec/libgsm.c b/libavcodec/libgsm.c
index 97f8abe..8915ef5 100644
--- a/libavcodec/libgsm.c
+++ b/libavcodec/libgsm.c
@@ -29,10 +29,11 @@
 
 #include <gsm/gsm.h>
 
+#include "libavutil/channel_layout.h"
+#include "libavutil/common.h"
 #include "avcodec.h"
 #include "internal.h"
 #include "gsm.h"
-#include "libavutil/common.h"
 
 static av_cold int libgsm_encode_close(AVCodecContext *avctx) {
 #if FF_API_OLD_ENCODE_AUDIO
@@ -153,19 +154,11 @@
 static av_cold int libgsm_decode_init(AVCodecContext *avctx) {
     LibGSMDecodeContext *s = avctx->priv_data;
 
-    if (avctx->channels > 1) {
-        av_log(avctx, AV_LOG_ERROR, "Mono required for GSM, got %d channels\n",
-               avctx->channels);
-        return -1;
-    }
-
-    if (!avctx->channels)
-        avctx->channels = 1;
-
+    avctx->channels       = 1;
+    avctx->channel_layout = AV_CH_LAYOUT_MONO;
     if (!avctx->sample_rate)
         avctx->sample_rate = 8000;
-
-    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    avctx->sample_fmt     = AV_SAMPLE_FMT_S16;
 
     s->state = gsm_create();
 
diff --git a/libavcodec/libilbc.c b/libavcodec/libilbc.c
index fe1fa39..bcc01ed 100644
--- a/libavcodec/libilbc.c
+++ b/libavcodec/libilbc.c
@@ -21,9 +21,10 @@
 
 #include <ilbc.h>
 
-#include "avcodec.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
 #include "libavutil/opt.h"
+#include "avcodec.h"
 #include "internal.h"
 
 static int get_mode(AVCodecContext *avctx)
@@ -71,9 +72,10 @@
     avcodec_get_frame_defaults(&s->frame);
     avctx->coded_frame = &s->frame;
 
-    avctx->channels = 1;
-    avctx->sample_rate = 8000;
-    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    avctx->channels       = 1;
+    avctx->channel_layout = AV_CH_LAYOUT_MONO;
+    avctx->sample_rate    = 8000;
+    avctx->sample_fmt     = AV_SAMPLE_FMT_S16;
 
     return 0;
 }
diff --git a/libavcodec/libmp3lame.c b/libavcodec/libmp3lame.c
index 427cacd..1447d6a 100644
--- a/libavcodec/libmp3lame.c
+++ b/libavcodec/libmp3lame.c
@@ -26,8 +26,9 @@
 
 #include <lame/lame.h>
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
+#include "libavutil/float_dsp.h"
 #include "libavutil/intreadwrite.h"
 #include "libavutil/log.h"
 #include "libavutil/opt.h"
@@ -43,14 +44,36 @@
     AVClass *class;
     AVCodecContext *avctx;
     lame_global_flags *gfp;
-    uint8_t buffer[BUFFER_SIZE];
+    uint8_t *buffer;
     int buffer_index;
+    int buffer_size;
     int reservoir;
-    void *planar_samples[2];
+    float *samples_flt[2];
     AudioFrameQueue afq;
+    AVFloatDSPContext fdsp;
 } LAMEContext;
 
 
+static int realloc_buffer(LAMEContext *s)
+{
+    if (!s->buffer || s->buffer_size - s->buffer_index < BUFFER_SIZE) {
+        uint8_t *tmp;
+        int new_size = s->buffer_index + 2 * BUFFER_SIZE;
+
+        av_dlog(s->avctx, "resizing output buffer: %d -> %d\n", s->buffer_size,
+                new_size);
+        tmp = av_realloc(s->buffer, new_size);
+        if (!tmp) {
+            av_freep(&s->buffer);
+            s->buffer_size = s->buffer_index = 0;
+            return AVERROR(ENOMEM);
+        }
+        s->buffer      = tmp;
+        s->buffer_size = new_size;
+    }
+    return 0;
+}
+
 static av_cold int mp3lame_encode_close(AVCodecContext *avctx)
 {
     LAMEContext *s = avctx->priv_data;
@@ -58,8 +81,9 @@
 #if FF_API_OLD_ENCODE_AUDIO
     av_freep(&avctx->coded_frame);
 #endif
-    av_freep(&s->planar_samples[0]);
-    av_freep(&s->planar_samples[1]);
+    av_freep(&s->samples_flt[0]);
+    av_freep(&s->samples_flt[1]);
+    av_freep(&s->buffer);
 
     ff_af_queue_close(&s->afq);
 
@@ -127,93 +151,67 @@
     }
 #endif
 
-    /* sample format */
-    if (avctx->sample_fmt == AV_SAMPLE_FMT_S32 ||
-        avctx->sample_fmt == AV_SAMPLE_FMT_FLT) {
+    /* allocate float sample buffers */
+    if (avctx->sample_fmt == AV_SAMPLE_FMT_FLTP) {
         int ch;
         for (ch = 0; ch < avctx->channels; ch++) {
-            s->planar_samples[ch] = av_malloc(avctx->frame_size *
-                                              av_get_bytes_per_sample(avctx->sample_fmt));
-            if (!s->planar_samples[ch]) {
+            s->samples_flt[ch] = av_malloc(avctx->frame_size *
+                                           sizeof(*s->samples_flt[ch]));
+            if (!s->samples_flt[ch]) {
                 ret = AVERROR(ENOMEM);
                 goto error;
             }
         }
     }
 
+    ret = realloc_buffer(s);
+    if (ret < 0)
+        goto error;
+
+    avpriv_float_dsp_init(&s->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
+
     return 0;
 error:
     mp3lame_encode_close(avctx);
     return ret;
 }
 
-#define DEINTERLEAVE(type, scale) do {                  \
-    int ch, i;                                          \
-    for (ch = 0; ch < s->avctx->channels; ch++) {       \
-        const type *input = samples;                    \
-        type      *output = s->planar_samples[ch];      \
-        input += ch;                                    \
-        for (i = 0; i < nb_samples; i++) {              \
-            output[i] = *input * scale;                 \
-            input += s->avctx->channels;                \
-        }                                               \
-    }                                                   \
+#define ENCODE_BUFFER(func, buf_type, buf_name) do {                        \
+    lame_result = func(s->gfp,                                              \
+                       (const buf_type *)buf_name[0],                       \
+                       (const buf_type *)buf_name[1], frame->nb_samples,    \
+                       s->buffer + s->buffer_index,                         \
+                       s->buffer_size - s->buffer_index);                   \
 } while (0)
 
-static int encode_frame_int16(LAMEContext *s, void *samples, int nb_samples)
-{
-    if (s->avctx->channels > 1) {
-        return lame_encode_buffer_interleaved(s->gfp, samples,
-                                              nb_samples,
-                                              s->buffer + s->buffer_index,
-                                              BUFFER_SIZE - s->buffer_index);
-    } else {
-        return lame_encode_buffer(s->gfp, samples, NULL, nb_samples,
-                                  s->buffer + s->buffer_index,
-                                  BUFFER_SIZE - s->buffer_index);
-    }
-}
-
-static int encode_frame_int32(LAMEContext *s, void *samples, int nb_samples)
-{
-    DEINTERLEAVE(int32_t, 1);
-
-    return lame_encode_buffer_int(s->gfp,
-                                  s->planar_samples[0], s->planar_samples[1],
-                                  nb_samples,
-                                  s->buffer + s->buffer_index,
-                                  BUFFER_SIZE - s->buffer_index);
-}
-
-static int encode_frame_float(LAMEContext *s, void *samples, int nb_samples)
-{
-    DEINTERLEAVE(float, 32768.0f);
-
-    return lame_encode_buffer_float(s->gfp,
-                                    s->planar_samples[0], s->planar_samples[1],
-                                    nb_samples,
-                                    s->buffer + s->buffer_index,
-                                    BUFFER_SIZE - s->buffer_index);
-}
-
 static int mp3lame_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
                                 const AVFrame *frame, int *got_packet_ptr)
 {
     LAMEContext *s = avctx->priv_data;
     MPADecodeHeader hdr;
-    int len, ret;
+    int len, ret, ch;
     int lame_result;
 
     if (frame) {
         switch (avctx->sample_fmt) {
-        case AV_SAMPLE_FMT_S16:
-            lame_result = encode_frame_int16(s, frame->data[0], frame->nb_samples);
+        case AV_SAMPLE_FMT_S16P:
+            ENCODE_BUFFER(lame_encode_buffer, int16_t, frame->data);
             break;
-        case AV_SAMPLE_FMT_S32:
-            lame_result = encode_frame_int32(s, frame->data[0], frame->nb_samples);
+        case AV_SAMPLE_FMT_S32P:
+            ENCODE_BUFFER(lame_encode_buffer_int, int32_t, frame->data);
             break;
-        case AV_SAMPLE_FMT_FLT:
-            lame_result = encode_frame_float(s, frame->data[0], frame->nb_samples);
+        case AV_SAMPLE_FMT_FLTP:
+            if (frame->linesize[0] < 4 * FFALIGN(frame->nb_samples, 8)) {
+                av_log(avctx, AV_LOG_ERROR, "inadequate AVFrame plane padding\n");
+                return AVERROR(EINVAL);
+            }
+            for (ch = 0; ch < avctx->channels; ch++) {
+                s->fdsp.vector_fmul_scalar(s->samples_flt[ch],
+                                           (const float *)frame->data[ch],
+                                           32768.0f,
+                                           FFALIGN(frame->nb_samples, 8));
+            }
+            ENCODE_BUFFER(lame_encode_buffer_float, float, s->samples_flt);
             break;
         default:
             return AVERROR_BUG;
@@ -226,11 +224,16 @@
         if (lame_result == -1) {
             av_log(avctx, AV_LOG_ERROR,
                    "lame: output buffer too small (buffer index: %d, free bytes: %d)\n",
-                   s->buffer_index, BUFFER_SIZE - s->buffer_index);
+                   s->buffer_index, s->buffer_size - s->buffer_index);
         }
         return -1;
     }
     s->buffer_index += lame_result;
+    ret = realloc_buffer(s);
+    if (ret < 0) {
+        av_log(avctx, AV_LOG_ERROR, "error reallocating output buffer\n");
+        return ret;
+    }
 
     /* add current frame to the queue */
     if (frame) {
@@ -299,9 +302,9 @@
     .encode2               = mp3lame_encode_frame,
     .close                 = mp3lame_encode_close,
     .capabilities          = CODEC_CAP_DELAY | CODEC_CAP_SMALL_LAST_FRAME,
-    .sample_fmts           = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S32,
-                                                             AV_SAMPLE_FMT_FLT,
-                                                             AV_SAMPLE_FMT_S16,
+    .sample_fmts           = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S32P,
+                                                             AV_SAMPLE_FMT_FLTP,
+                                                             AV_SAMPLE_FMT_S16P,
                                                              AV_SAMPLE_FMT_NONE },
     .supported_samplerates = libmp3lame_sample_rates,
     .channel_layouts       = (const uint64_t[]) { AV_CH_LAYOUT_MONO,
diff --git a/libavcodec/libopencore-amr.c b/libavcodec/libopencore-amr.c
index aa6dfa6..f0207ae 100644
--- a/libavcodec/libopencore-amr.c
+++ b/libavcodec/libopencore-amr.c
@@ -19,24 +19,30 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#include "avcodec.h"
 #include "libavutil/avstring.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
 #include "libavutil/opt.h"
+#include "avcodec.h"
 #include "audio_frame_queue.h"
 #include "internal.h"
 
-static void amr_decode_fix_avctx(AVCodecContext *avctx)
+static int amr_decode_fix_avctx(AVCodecContext *avctx)
 {
     const int is_amr_wb = 1 + (avctx->codec_id == AV_CODEC_ID_AMR_WB);
 
     if (!avctx->sample_rate)
         avctx->sample_rate = 8000 * is_amr_wb;
 
-    if (!avctx->channels)
-        avctx->channels = 1;
+    if (avctx->channels > 1) {
+        av_log_missing_feature(avctx, "multi-channel AMR", 0);
+        return AVERROR_PATCHWELCOME;
+    }
 
-    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    avctx->channels       = 1;
+    avctx->channel_layout = AV_CH_LAYOUT_MONO;
+    avctx->sample_fmt     = AV_SAMPLE_FMT_S16;
+    return 0;
 }
 
 #if CONFIG_LIBOPENCORE_AMRNB
@@ -103,6 +109,10 @@
 static av_cold int amr_nb_decode_init(AVCodecContext *avctx)
 {
     AMRContext *s  = avctx->priv_data;
+    int ret;
+
+    if ((ret = amr_decode_fix_avctx(avctx)) < 0)
+        return ret;
 
     s->dec_state   = Decoder_Interface_init();
     if (!s->dec_state) {
@@ -110,13 +120,6 @@
         return -1;
     }
 
-    amr_decode_fix_avctx(avctx);
-
-    if (avctx->channels > 1) {
-        av_log(avctx, AV_LOG_ERROR, "amr_nb: multichannel decoding not supported\n");
-        return AVERROR(ENOSYS);
-    }
-
     avcodec_get_frame_defaults(&s->frame);
     avctx->coded_frame = &s->frame;
 
@@ -188,7 +191,7 @@
 {
     AMRContext *s = avctx->priv_data;
 
-    if (avctx->sample_rate != 8000) {
+    if (avctx->sample_rate != 8000 && avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL) {
         av_log(avctx, AV_LOG_ERROR, "Only 8000Hz sample rate supported\n");
         return AVERROR(ENOSYS);
     }
@@ -275,7 +278,7 @@
     written = Encoder_Interface_Encode(s->enc_state, s->enc_mode, samples,
                                        avpkt->data, 0);
     av_dlog(avctx, "amr_nb_encode_frame encoded %u bytes, bitrate %u, first byte was %#02x\n",
-            written, s->enc_mode, frame[0]);
+            written, s->enc_mode, avpkt->data[0]);
 
     /* Get the next frame pts/duration */
     ff_af_queue_remove(&s->afq, avctx->frame_size, &avpkt->pts,
@@ -318,16 +321,13 @@
 static av_cold int amr_wb_decode_init(AVCodecContext *avctx)
 {
     AMRWBContext *s = avctx->priv_data;
+    int ret;
+
+    if ((ret = amr_decode_fix_avctx(avctx)) < 0)
+        return ret;
 
     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 AVERROR(ENOSYS);
-    }
-
     avcodec_get_frame_defaults(&s->frame);
     avctx->coded_frame = &s->frame;
 
@@ -359,6 +359,10 @@
                buf_size, packet_size + 1);
         return AVERROR_INVALIDDATA;
     }
+    if (!packet_size) {
+        av_log(avctx, AV_LOG_ERROR, "amr packet_size invalid\n");
+        return AVERROR_INVALIDDATA;
+    }
 
     D_IF_decode(s->state, buf, (short *)s->frame.data[0], _good_frame);
 
diff --git a/libavcodec/libopenjpegdec.c b/libavcodec/libopenjpegdec.c
index 9f01afd..5f3c36b 100644
--- a/libavcodec/libopenjpegdec.c
+++ b/libavcodec/libopenjpegdec.c
@@ -40,21 +40,24 @@
 
 // pix_fmts with lower bpp have to be listed before
 // similar pix_fmts with higher bpp.
-#define RGB_PIXEL_FORMATS   PIX_FMT_RGB24,PIX_FMT_RGBA,PIX_FMT_RGB48,PIX_FMT_RGBA64
-#define GRAY_PIXEL_FORMATS  PIX_FMT_GRAY8,PIX_FMT_GRAY8A,PIX_FMT_GRAY16
-#define YUV_PIXEL_FORMATS   PIX_FMT_YUV410P,PIX_FMT_YUV411P,PIX_FMT_YUVA420P, \
-                            PIX_FMT_YUV420P,PIX_FMT_YUV422P,PIX_FMT_YUVA422P, \
-                            PIX_FMT_YUV440P,PIX_FMT_YUV444P,PIX_FMT_YUVA444P, \
-                            PIX_FMT_YUV420P9,PIX_FMT_YUV422P9,PIX_FMT_YUV444P9, \
-                            PIX_FMT_YUV420P10,PIX_FMT_YUV422P10,PIX_FMT_YUV444P10, \
-                            PIX_FMT_YUV420P12,PIX_FMT_YUV422P12,PIX_FMT_YUV444P12, \
-                            PIX_FMT_YUV420P14,PIX_FMT_YUV422P14,PIX_FMT_YUV444P14, \
-                            PIX_FMT_YUV420P16,PIX_FMT_YUV422P16,PIX_FMT_YUV444P16
+#define RGB_PIXEL_FORMATS   AV_PIX_FMT_RGB24,AV_PIX_FMT_RGBA,AV_PIX_FMT_RGB48,AV_PIX_FMT_RGBA64
+#define GRAY_PIXEL_FORMATS  AV_PIX_FMT_GRAY8,AV_PIX_FMT_GRAY8A,AV_PIX_FMT_GRAY16
+#define YUV_PIXEL_FORMATS   AV_PIX_FMT_YUV410P,AV_PIX_FMT_YUV411P,AV_PIX_FMT_YUVA420P, \
+                            AV_PIX_FMT_YUV420P,AV_PIX_FMT_YUV422P,AV_PIX_FMT_YUVA422P, \
+                            AV_PIX_FMT_YUV440P,AV_PIX_FMT_YUV444P,AV_PIX_FMT_YUVA444P, \
+                            AV_PIX_FMT_YUV420P9,AV_PIX_FMT_YUV422P9,AV_PIX_FMT_YUV444P9, \
+                            AV_PIX_FMT_YUVA420P9,AV_PIX_FMT_YUVA422P9,AV_PIX_FMT_YUVA444P9, \
+                            AV_PIX_FMT_YUV420P10,AV_PIX_FMT_YUV422P10,AV_PIX_FMT_YUV444P10, \
+                            AV_PIX_FMT_YUVA420P10,AV_PIX_FMT_YUVA422P10,AV_PIX_FMT_YUVA444P10, \
+                            AV_PIX_FMT_YUV420P12,AV_PIX_FMT_YUV422P12,AV_PIX_FMT_YUV444P12, \
+                            AV_PIX_FMT_YUV420P14,AV_PIX_FMT_YUV422P14,AV_PIX_FMT_YUV444P14, \
+                            AV_PIX_FMT_YUV420P16,AV_PIX_FMT_YUV422P16,AV_PIX_FMT_YUV444P16, \
+                            AV_PIX_FMT_YUVA420P16,AV_PIX_FMT_YUVA422P16,AV_PIX_FMT_YUVA444P16
 
-static const enum PixelFormat libopenjpeg_rgb_pix_fmts[]  = {RGB_PIXEL_FORMATS};
-static const enum PixelFormat libopenjpeg_gray_pix_fmts[] = {GRAY_PIXEL_FORMATS};
-static const enum PixelFormat libopenjpeg_yuv_pix_fmts[]  = {YUV_PIXEL_FORMATS};
-static const enum PixelFormat libopenjpeg_all_pix_fmts[]  = {RGB_PIXEL_FORMATS,GRAY_PIXEL_FORMATS,YUV_PIXEL_FORMATS};
+static const enum AVPixelFormat libopenjpeg_rgb_pix_fmts[]  = {RGB_PIXEL_FORMATS};
+static const enum AVPixelFormat libopenjpeg_gray_pix_fmts[] = {GRAY_PIXEL_FORMATS};
+static const enum AVPixelFormat libopenjpeg_yuv_pix_fmts[]  = {YUV_PIXEL_FORMATS};
+static const enum AVPixelFormat libopenjpeg_all_pix_fmts[]  = {RGB_PIXEL_FORMATS,GRAY_PIXEL_FORMATS,YUV_PIXEL_FORMATS};
 
 typedef struct {
     AVClass *class;
@@ -63,26 +66,26 @@
     int lowqual;
 } LibOpenJPEGContext;
 
-static inline int libopenjpeg_matches_pix_fmt(const opj_image_t *image, enum PixelFormat pix_fmt)
+static inline int libopenjpeg_matches_pix_fmt(const opj_image_t *image, enum AVPixelFormat pix_fmt)
 {
-    AVPixFmtDescriptor descriptor = av_pix_fmt_descriptors[pix_fmt];
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
     int match = 1;
 
-    if (descriptor.nb_components != image->numcomps) {
+    if (desc->nb_components != image->numcomps) {
         return 0;
     }
 
-    switch (descriptor.nb_components) {
-    case 4: match = match && descriptor.comp[3].depth_minus1 + 1 >= image->comps[3].prec &&
+    switch (desc->nb_components) {
+    case 4: match = match && desc->comp[3].depth_minus1 + 1 >= image->comps[3].prec &&
                              1 == image->comps[3].dx &&
                              1 == image->comps[3].dy;
-    case 3: match = match && descriptor.comp[2].depth_minus1 + 1 >= image->comps[2].prec &&
-                             1 << descriptor.log2_chroma_w == image->comps[2].dx &&
-                             1 << descriptor.log2_chroma_h == image->comps[2].dy;
-    case 2: match = match && descriptor.comp[1].depth_minus1 + 1 >= image->comps[1].prec &&
-                             1 << descriptor.log2_chroma_w == image->comps[1].dx &&
-                             1 << descriptor.log2_chroma_h == image->comps[1].dy;
-    case 1: match = match && descriptor.comp[0].depth_minus1 + 1 >= image->comps[0].prec &&
+    case 3: match = match && desc->comp[2].depth_minus1 + 1 >= image->comps[2].prec &&
+                             1 << desc->log2_chroma_w == image->comps[2].dx &&
+                             1 << desc->log2_chroma_h == image->comps[2].dy;
+    case 2: match = match && desc->comp[1].depth_minus1 + 1 >= image->comps[1].prec &&
+                             1 << desc->log2_chroma_w == image->comps[1].dx &&
+                             1 << desc->log2_chroma_h == image->comps[1].dy;
+    case 1: match = match && desc->comp[0].depth_minus1 + 1 >= image->comps[0].prec &&
                              1 == image->comps[0].dx &&
                              1 == image->comps[0].dy;
     default:
@@ -92,9 +95,9 @@
     return match;
 }
 
-static inline enum PixelFormat libopenjpeg_guess_pix_fmt(const opj_image_t *image) {
+static inline enum AVPixelFormat libopenjpeg_guess_pix_fmt(const opj_image_t *image) {
     int index;
-    const enum PixelFormat *possible_fmts = NULL;
+    const enum AVPixelFormat *possible_fmts = NULL;
     int possible_fmts_nb = 0;
 
     switch (image->color_space) {
@@ -122,18 +125,20 @@
         }
     }
 
-    return PIX_FMT_NONE;
+    return AV_PIX_FMT_NONE;
 }
 
-static inline int libopenjpeg_ispacked(enum PixelFormat pix_fmt) {
+static inline int libopenjpeg_ispacked(enum AVPixelFormat pix_fmt)
+{
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
     int i, component_plane;
 
-    if (pix_fmt == PIX_FMT_GRAY16)
+    if (pix_fmt == AV_PIX_FMT_GRAY16)
         return 0;
 
-    component_plane = av_pix_fmt_descriptors[pix_fmt].comp[0].plane;
-    for (i = 1; i < av_pix_fmt_descriptors[pix_fmt].nb_components; i++) {
-        if (component_plane != av_pix_fmt_descriptors[pix_fmt].comp[i].plane)
+    component_plane = desc->comp[0].plane;
+    for (i = 1; i < desc->nb_components; i++) {
+        if (component_plane != desc->comp[i].plane)
             return 0;
     }
     return 1;
@@ -232,6 +237,7 @@
     int buf_size = avpkt->size;
     LibOpenJPEGContext *ctx = avctx->priv_data;
     AVFrame *picture = &ctx->image, *output = data;
+    const AVPixFmtDescriptor *desc;
     opj_dinfo_t *dec;
     opj_cio_t *stream;
     opj_image_t *image;
@@ -294,14 +300,14 @@
 
     avcodec_set_dimensions(avctx, width, height);
 
-    if (avctx->pix_fmt != PIX_FMT_NONE)
+    if (avctx->pix_fmt != AV_PIX_FMT_NONE)
         if (!libopenjpeg_matches_pix_fmt(image, avctx->pix_fmt))
-            avctx->pix_fmt = PIX_FMT_NONE;
+            avctx->pix_fmt = AV_PIX_FMT_NONE;
 
-    if (avctx->pix_fmt == PIX_FMT_NONE)
+    if (avctx->pix_fmt == AV_PIX_FMT_NONE)
         avctx->pix_fmt = libopenjpeg_guess_pix_fmt(image);
 
-    if (avctx->pix_fmt == PIX_FMT_NONE) {
+    if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
         av_log(avctx, AV_LOG_ERROR, "Unable to determine pixel format\n");
         goto done;
     }
@@ -338,7 +344,8 @@
         goto done;
     }
 
-    pixel_size = av_pix_fmt_descriptors[avctx->pix_fmt].comp[0].step_minus1 + 1;
+    desc = av_pix_fmt_desc_get(avctx->pix_fmt);
+    pixel_size = desc->comp[0].step_minus1 + 1;
     ispacked = libopenjpeg_ispacked(avctx->pix_fmt);
 
     switch (pixel_size) {
diff --git a/libavcodec/libopenjpegenc.c b/libavcodec/libopenjpegenc.c
index e97dd2b..b87d4d4 100644
--- a/libavcodec/libopenjpegenc.c
+++ b/libavcodec/libopenjpegenc.c
@@ -1,6 +1,6 @@
 /*
  * JPEG 2000 encoding support via OpenJPEG
- * Copyright (c) 2011 Michael Bradshaw <mbradshaw@sorensonmedia.com>
+ * Copyright (c) 2011 Michael Bradshaw <mjbshaw gmail com>
  *
  * This file is part of FFmpeg.
  *
@@ -69,6 +69,7 @@
 
 static opj_image_t *mj2_create_image(AVCodecContext *avctx, opj_cparameters_t *parameters)
 {
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
     opj_image_cmptparm_t *cmptparm;
     opj_image_t *img;
     int i;
@@ -79,47 +80,56 @@
 
     sub_dx[0] = sub_dx[3] = 1;
     sub_dy[0] = sub_dy[3] = 1;
-    sub_dx[1] = sub_dx[2] = 1<<av_pix_fmt_descriptors[avctx->pix_fmt].log2_chroma_w;
-    sub_dy[1] = sub_dy[2] = 1<<av_pix_fmt_descriptors[avctx->pix_fmt].log2_chroma_h;
+    sub_dx[1] = sub_dx[2] = 1 << desc->log2_chroma_w;
+    sub_dy[1] = sub_dy[2] = 1 << desc->log2_chroma_h;
 
-    numcomps = av_pix_fmt_descriptors[avctx->pix_fmt].nb_components;
+    numcomps = desc->nb_components;
 
     switch (avctx->pix_fmt) {
-    case PIX_FMT_GRAY8:
-    case PIX_FMT_GRAY8A:
-    case PIX_FMT_GRAY16:
+    case AV_PIX_FMT_GRAY8:
+    case AV_PIX_FMT_GRAY8A:
+    case AV_PIX_FMT_GRAY16:
         color_space = CLRSPC_GRAY;
         break;
-    case PIX_FMT_RGB24:
-    case PIX_FMT_RGBA:
-    case PIX_FMT_RGB48:
-    case PIX_FMT_RGBA64:
+    case AV_PIX_FMT_RGB24:
+    case AV_PIX_FMT_RGBA:
+    case AV_PIX_FMT_RGB48:
+    case AV_PIX_FMT_RGBA64:
         color_space = CLRSPC_SRGB;
         break;
-    case PIX_FMT_YUV410P:
-    case PIX_FMT_YUV411P:
-    case PIX_FMT_YUV420P:
-    case PIX_FMT_YUV422P:
-    case PIX_FMT_YUV440P:
-    case PIX_FMT_YUV444P:
-    case PIX_FMT_YUVA420P:
-    case PIX_FMT_YUVA422P:
-    case PIX_FMT_YUVA444P:
-    case PIX_FMT_YUV420P9:
-    case PIX_FMT_YUV422P9:
-    case PIX_FMT_YUV444P9:
-    case PIX_FMT_YUV420P10:
-    case PIX_FMT_YUV422P10:
-    case PIX_FMT_YUV444P10:
-    case PIX_FMT_YUV420P12:
-    case PIX_FMT_YUV422P12:
-    case PIX_FMT_YUV444P12:
-    case PIX_FMT_YUV420P14:
-    case PIX_FMT_YUV422P14:
-    case PIX_FMT_YUV444P14:
-    case PIX_FMT_YUV420P16:
-    case PIX_FMT_YUV422P16:
-    case PIX_FMT_YUV444P16:
+    case AV_PIX_FMT_YUV410P:
+    case AV_PIX_FMT_YUV411P:
+    case AV_PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUV422P:
+    case AV_PIX_FMT_YUV440P:
+    case AV_PIX_FMT_YUV444P:
+    case AV_PIX_FMT_YUVA420P:
+    case AV_PIX_FMT_YUVA422P:
+    case AV_PIX_FMT_YUVA444P:
+    case AV_PIX_FMT_YUV420P9:
+    case AV_PIX_FMT_YUV422P9:
+    case AV_PIX_FMT_YUV444P9:
+    case AV_PIX_FMT_YUVA420P9:
+    case AV_PIX_FMT_YUVA422P9:
+    case AV_PIX_FMT_YUVA444P9:
+    case AV_PIX_FMT_YUV420P10:
+    case AV_PIX_FMT_YUV422P10:
+    case AV_PIX_FMT_YUV444P10:
+    case AV_PIX_FMT_YUVA420P10:
+    case AV_PIX_FMT_YUVA422P10:
+    case AV_PIX_FMT_YUVA444P10:
+    case AV_PIX_FMT_YUV420P12:
+    case AV_PIX_FMT_YUV422P12:
+    case AV_PIX_FMT_YUV444P12:
+    case AV_PIX_FMT_YUV420P14:
+    case AV_PIX_FMT_YUV422P14:
+    case AV_PIX_FMT_YUV444P14:
+    case AV_PIX_FMT_YUV420P16:
+    case AV_PIX_FMT_YUV422P16:
+    case AV_PIX_FMT_YUV444P16:
+    case AV_PIX_FMT_YUVA420P16:
+    case AV_PIX_FMT_YUVA422P16:
+    case AV_PIX_FMT_YUVA444P16:
         color_space = CLRSPC_SYCC;
         break;
     default:
@@ -135,8 +145,8 @@
         return NULL;
     }
     for (i = 0; i < numcomps; i++) {
-        cmptparm[i].prec = av_pix_fmt_descriptors[avctx->pix_fmt].comp[i].depth_minus1 + 1;
-        cmptparm[i].bpp = av_pix_fmt_descriptors[avctx->pix_fmt].comp[i].depth_minus1 + 1;
+        cmptparm[i].prec = desc->comp[i].depth_minus1 + 1;
+        cmptparm[i].bpp  = desc->comp[i].depth_minus1 + 1;
         cmptparm[i].sgnd = 0;
         cmptparm[i].dx = sub_dx[i];
         cmptparm[i].dy = sub_dy[i];
@@ -345,43 +355,52 @@
     image->y1 = (avctx->height - 1) * ctx->enc_params.subsampling_dy + 1;
 
     switch (avctx->pix_fmt) {
-    case PIX_FMT_RGB24:
-    case PIX_FMT_RGBA:
-    case PIX_FMT_GRAY8A:
+    case AV_PIX_FMT_RGB24:
+    case AV_PIX_FMT_RGBA:
+    case AV_PIX_FMT_GRAY8A:
         cpyresult = libopenjpeg_copy_packed8(avctx, frame, image);
         break;
-    case PIX_FMT_RGB48:
-    case PIX_FMT_RGBA64:
+    case AV_PIX_FMT_RGB48:
+    case AV_PIX_FMT_RGBA64:
         cpyresult = libopenjpeg_copy_packed16(avctx, frame, image);
         break;
-    case PIX_FMT_GRAY8:
-    case PIX_FMT_YUV410P:
-    case PIX_FMT_YUV411P:
-    case PIX_FMT_YUV420P:
-    case PIX_FMT_YUV422P:
-    case PIX_FMT_YUV440P:
-    case PIX_FMT_YUV444P:
-    case PIX_FMT_YUVA420P:
-    case PIX_FMT_YUVA422P:
-    case PIX_FMT_YUVA444P:
+    case AV_PIX_FMT_GRAY8:
+    case AV_PIX_FMT_YUV410P:
+    case AV_PIX_FMT_YUV411P:
+    case AV_PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUV422P:
+    case AV_PIX_FMT_YUV440P:
+    case AV_PIX_FMT_YUV444P:
+    case AV_PIX_FMT_YUVA420P:
+    case AV_PIX_FMT_YUVA422P:
+    case AV_PIX_FMT_YUVA444P:
         cpyresult = libopenjpeg_copy_unpacked8(avctx, frame, image);
         break;
-    case PIX_FMT_GRAY16:
-    case PIX_FMT_YUV420P9:
-    case PIX_FMT_YUV422P9:
-    case PIX_FMT_YUV444P9:
-    case PIX_FMT_YUV444P10:
-    case PIX_FMT_YUV422P10:
-    case PIX_FMT_YUV420P10:
-    case PIX_FMT_YUV420P12:
-    case PIX_FMT_YUV422P12:
-    case PIX_FMT_YUV444P12:
-    case PIX_FMT_YUV420P14:
-    case PIX_FMT_YUV422P14:
-    case PIX_FMT_YUV444P14:
-    case PIX_FMT_YUV444P16:
-    case PIX_FMT_YUV422P16:
-    case PIX_FMT_YUV420P16:
+    case AV_PIX_FMT_GRAY16:
+    case AV_PIX_FMT_YUV420P9:
+    case AV_PIX_FMT_YUV422P9:
+    case AV_PIX_FMT_YUV444P9:
+    case AV_PIX_FMT_YUVA420P9:
+    case AV_PIX_FMT_YUVA422P9:
+    case AV_PIX_FMT_YUVA444P9:
+    case AV_PIX_FMT_YUV444P10:
+    case AV_PIX_FMT_YUV422P10:
+    case AV_PIX_FMT_YUV420P10:
+    case AV_PIX_FMT_YUVA444P10:
+    case AV_PIX_FMT_YUVA422P10:
+    case AV_PIX_FMT_YUVA420P10:
+    case AV_PIX_FMT_YUV420P12:
+    case AV_PIX_FMT_YUV422P12:
+    case AV_PIX_FMT_YUV444P12:
+    case AV_PIX_FMT_YUV420P14:
+    case AV_PIX_FMT_YUV422P14:
+    case AV_PIX_FMT_YUV444P14:
+    case AV_PIX_FMT_YUV444P16:
+    case AV_PIX_FMT_YUV422P16:
+    case AV_PIX_FMT_YUV420P16:
+    case AV_PIX_FMT_YUVA444P16:
+    case AV_PIX_FMT_YUVA422P16:
+    case AV_PIX_FMT_YUVA420P16:
         cpyresult = libopenjpeg_copy_unpacked16(avctx, frame, image);
         break;
     default:
@@ -479,18 +498,21 @@
     .encode2        = libopenjpeg_encode_frame,
     .close          = libopenjpeg_encode_close,
     .capabilities   = 0,
-    .pix_fmts       = (const enum PixelFormat[]) {
-        PIX_FMT_RGB24, PIX_FMT_RGBA, PIX_FMT_RGB48, PIX_FMT_RGBA64,
-        PIX_FMT_GRAY8, PIX_FMT_GRAY8A, PIX_FMT_GRAY16,
-        PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUVA420P,
-        PIX_FMT_YUV440P, PIX_FMT_YUV444P, PIX_FMT_YUVA422P,
-        PIX_FMT_YUV411P, PIX_FMT_YUV410P, PIX_FMT_YUVA444P,
-        PIX_FMT_YUV420P9, PIX_FMT_YUV422P9, PIX_FMT_YUV444P9,
-        PIX_FMT_YUV420P10, PIX_FMT_YUV422P10, PIX_FMT_YUV444P10,
-        PIX_FMT_YUV420P12, PIX_FMT_YUV422P12, PIX_FMT_YUV444P12,
-        PIX_FMT_YUV420P14, PIX_FMT_YUV422P14, PIX_FMT_YUV444P14,
-        PIX_FMT_YUV420P16, PIX_FMT_YUV422P16, PIX_FMT_YUV444P16,
-        PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]) {
+        AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA, AV_PIX_FMT_RGB48, AV_PIX_FMT_RGBA64,
+        AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY8A, AV_PIX_FMT_GRAY16,
+        AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUVA420P,
+        AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUVA422P,
+        AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUVA444P,
+        AV_PIX_FMT_YUV420P9, AV_PIX_FMT_YUV422P9, AV_PIX_FMT_YUV444P9,
+        AV_PIX_FMT_YUVA420P9, AV_PIX_FMT_YUVA422P9, AV_PIX_FMT_YUVA444P9,
+        AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV444P10,
+        AV_PIX_FMT_YUVA420P10, AV_PIX_FMT_YUVA422P10, AV_PIX_FMT_YUVA444P10,
+        AV_PIX_FMT_YUV420P12, AV_PIX_FMT_YUV422P12, AV_PIX_FMT_YUV444P12,
+        AV_PIX_FMT_YUV420P14, AV_PIX_FMT_YUV422P14, AV_PIX_FMT_YUV444P14,
+        AV_PIX_FMT_YUV420P16, AV_PIX_FMT_YUV422P16, AV_PIX_FMT_YUV444P16,
+        AV_PIX_FMT_YUVA420P16, AV_PIX_FMT_YUVA422P16, AV_PIX_FMT_YUVA444P16,
+        AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("OpenJPEG JPEG 2000"),
     .priv_class     = &class,
diff --git a/libavcodec/libopus.c b/libavcodec/libopus.c
new file mode 100644
index 0000000..16395c7
--- /dev/null
+++ b/libavcodec/libopus.c
@@ -0,0 +1,48 @@
+/*
+ * libopus encoder/decoder common code
+ * Copyright (c) 2012 Nicolas George
+ *
+ * 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 <opus_defines.h>
+
+#include "libavutil/common.h"
+#include "libavutil/error.h"
+#include "libopus.h"
+
+int ff_opus_error_to_averror(int err)
+{
+    switch (err) {
+    case OPUS_BAD_ARG:
+        return AVERROR(EINVAL);
+    case OPUS_BUFFER_TOO_SMALL:
+        return AVERROR_UNKNOWN;
+    case OPUS_INTERNAL_ERROR:
+        return AVERROR(EFAULT);
+    case OPUS_INVALID_PACKET:
+        return AVERROR_INVALIDDATA;
+    case OPUS_UNIMPLEMENTED:
+        return AVERROR(ENOSYS);
+    case OPUS_INVALID_STATE:
+        return AVERROR_UNKNOWN;
+    case OPUS_ALLOC_FAIL:
+        return AVERROR(ENOMEM);
+    default:
+        return AVERROR(EINVAL);
+    }
+}
diff --git a/libavutil/symbols.h b/libavcodec/libopus.h
similarity index 69%
copy from libavutil/symbols.h
copy to libavcodec/libopus.h
index 6011da2..a8223d1 100644
--- a/libavutil/symbols.h
+++ b/libavcodec/libopus.h
@@ -1,5 +1,6 @@
 /*
- * Copyright (c) 2012 Ronald S. Bultje <rsbultje@gmail.com>
+ * libopus encoder/decoder common code
+ * Copyright (c) 2012 Nicolas George
  *
  * This file is part of FFmpeg.
  *
@@ -18,15 +19,9 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#ifndef AVUTIL_SYMBOLS_H
-#define AVUTIL_SYMBOLS_H
+#ifndef AVCODEC_LIBOPUS_H
+#define AVCODEC_LIBOPUS_H
 
-#include "libavutil/avconfig.h"
+int ff_opus_error_to_averror(int err);
 
-#if AV_HAVE_SHARED_LIBS && defined(_MSC_VER) && !defined(COMPILING_avutil)
-#define AVUTIL_SYMBOL __declspec(dllimport)
-#else
-#define AVUTIL_SYMBOL
-#endif
-
-#endif /* AVUTIL_SYMBOLS_H */
+#endif /* AVCODEC_LIBOPUS_H */
diff --git a/libavcodec/libopusdec.c b/libavcodec/libopusdec.c
index 24488fe..f3cad25 100644
--- a/libavcodec/libopusdec.c
+++ b/libavcodec/libopusdec.c
@@ -22,13 +22,13 @@
 #include <opus.h>
 #include <opus_multistream.h>
 
-#include "libavutil/common.h"
 #include "libavutil/avassert.h"
 #include "libavutil/intreadwrite.h"
 #include "avcodec.h"
 #include "internal.h"
 #include "vorbis.h"
 #include "mathops.h"
+#include "libopus.h"
 
 struct libopus_context {
     OpusMSDecoder *dec;
@@ -39,20 +39,6 @@
 #endif
 };
 
-static int opus_error_to_averror(int err)
-{
-    switch (err) {
-        case OPUS_BAD_ARG:          return AVERROR(EINVAL);
-        case OPUS_BUFFER_TOO_SMALL: return AVERROR_BUFFER_TOO_SMALL;
-        case OPUS_INTERNAL_ERROR:   return AVERROR(EFAULT);
-        case OPUS_INVALID_PACKET:   return AVERROR_INVALIDDATA;
-        case OPUS_UNIMPLEMENTED:    return AVERROR(ENOSYS);
-        case OPUS_INVALID_STATE:    return AVERROR_EXTERNAL;
-        case OPUS_ALLOC_FAIL:       return AVERROR(ENOMEM);
-        default:                    return AVERROR(EINVAL);
-    }
-}
-
 #define OPUS_HEAD_SIZE 19
 
 static av_cold int libopus_decode_init(AVCodecContext *avc)
@@ -105,7 +91,7 @@
     if (!opus->dec) {
         av_log(avc, AV_LOG_ERROR, "Unable to create decoder: %s\n",
                opus_strerror(ret));
-        return opus_error_to_averror(ret);
+        return ff_opus_error_to_averror(ret);
     }
 
 #ifdef OPUS_SET_GAIN
@@ -165,7 +151,7 @@
     if (nb_samples < 0) {
         av_log(avc, AV_LOG_ERROR, "Decoding error: %s\n",
                opus_strerror(nb_samples));
-        return opus_error_to_averror(nb_samples);
+        return ff_opus_error_to_averror(nb_samples);
     }
 
 #ifndef OPUS_SET_GAIN
diff --git a/libavcodec/libopusenc.c b/libavcodec/libopusenc.c
new file mode 100644
index 0000000..d198798
--- /dev/null
+++ b/libavcodec/libopusenc.c
@@ -0,0 +1,421 @@
+/*
+ * Opus encoder using libopus
+ * Copyright (c) 2012 Nathan Caldwell
+ *
+ * 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 <opus.h>
+#include <opus_multistream.h>
+
+#include "libavutil/opt.h"
+#include "avcodec.h"
+#include "bytestream.h"
+#include "internal.h"
+#include "libopus.h"
+#include "vorbis.h"
+#include "audio_frame_queue.h"
+
+typedef struct LibopusEncOpts {
+    int vbr;
+    int application;
+    int packet_loss;
+    int complexity;
+    float frame_duration;
+    int packet_size;
+    int max_bandwidth;
+} LibopusEncOpts;
+
+typedef struct LibopusEncContext {
+    AVClass *class;
+    OpusMSEncoder *enc;
+    int stream_count;
+    uint8_t *samples;
+    LibopusEncOpts opts;
+    AudioFrameQueue afq;
+} LibopusEncContext;
+
+static const uint8_t opus_coupled_streams[8] = {
+    0, 1, 1, 2, 2, 2, 2, 3
+};
+
+/* Opus internal to Vorbis channel order mapping written in the header */
+static const uint8_t opus_vorbis_channel_map[8][8] = {
+    { 0 },
+    { 0, 1 },
+    { 0, 2, 1 },
+    { 0, 1, 2, 3 },
+    { 0, 4, 1, 2, 3 },
+    { 0, 4, 1, 2, 3, 5 },
+    { 0, 4, 1, 2, 3, 5, 6 },
+    { 0, 6, 1, 2, 3, 4, 5, 7 },
+};
+
+/* libavcodec to libopus channel order mapping, passed to libopus */
+static const uint8_t libavcodec_libopus_channel_map[8][8] = {
+    { 0 },
+    { 0, 1 },
+    { 0, 1, 2 },
+    { 0, 1, 2, 3 },
+    { 0, 1, 3, 4, 2 },
+    { 0, 1, 4, 5, 2, 3 },
+    { 0, 1, 5, 6, 2, 4, 3 },
+    { 0, 1, 6, 7, 4, 5, 2, 3 },
+};
+
+static void libopus_write_header(AVCodecContext *avctx, int stream_count,
+                                 int coupled_stream_count,
+                                 const uint8_t *channel_mapping)
+{
+    uint8_t *p   = avctx->extradata;
+    int channels = avctx->channels;
+
+    bytestream_put_buffer(&p, "OpusHead", 8);
+    bytestream_put_byte(&p, 1); /* Version */
+    bytestream_put_byte(&p, channels);
+    bytestream_put_le16(&p, avctx->delay); /* Lookahead samples at 48kHz */
+    bytestream_put_le32(&p, avctx->sample_rate); /* Original sample rate */
+    bytestream_put_le16(&p, 0); /* Gain of 0dB is recommended. */
+
+    /* Channel mapping */
+    if (channels > 2) {
+        bytestream_put_byte(&p, channels <= 8 ? 1 : 255);
+        bytestream_put_byte(&p, stream_count);
+        bytestream_put_byte(&p, coupled_stream_count);
+        bytestream_put_buffer(&p, channel_mapping, channels);
+    } else {
+        bytestream_put_byte(&p, 0);
+    }
+}
+
+static int libopus_configure_encoder(AVCodecContext *avctx, OpusMSEncoder *enc,
+                                     LibopusEncOpts *opts)
+{
+    int ret;
+
+    ret = opus_multistream_encoder_ctl(enc, OPUS_SET_BITRATE(avctx->bit_rate));
+    if (ret != OPUS_OK) {
+        av_log(avctx, AV_LOG_ERROR,
+               "Failed to set bitrate: %s\n", opus_strerror(ret));
+        return ret;
+    }
+
+    ret = opus_multistream_encoder_ctl(enc,
+                                       OPUS_SET_COMPLEXITY(opts->complexity));
+    if (ret != OPUS_OK)
+        av_log(avctx, AV_LOG_WARNING,
+               "Unable to set complexity: %s\n", opus_strerror(ret));
+
+    ret = opus_multistream_encoder_ctl(enc, OPUS_SET_VBR(!!opts->vbr));
+    if (ret != OPUS_OK)
+        av_log(avctx, AV_LOG_WARNING,
+               "Unable to set VBR: %s\n", opus_strerror(ret));
+
+    ret = opus_multistream_encoder_ctl(enc,
+                                       OPUS_SET_VBR_CONSTRAINT(opts->vbr == 2));
+    if (ret != OPUS_OK)
+        av_log(avctx, AV_LOG_WARNING,
+               "Unable to set constrained VBR: %s\n", opus_strerror(ret));
+
+    ret = opus_multistream_encoder_ctl(enc,
+                                       OPUS_SET_PACKET_LOSS_PERC(opts->packet_loss));
+    if (ret != OPUS_OK)
+        av_log(avctx, AV_LOG_WARNING,
+               "Unable to set expected packet loss percentage: %s\n",
+               opus_strerror(ret));
+
+    if (avctx->cutoff) {
+        ret = opus_multistream_encoder_ctl(enc,
+                                           OPUS_SET_MAX_BANDWIDTH(opts->max_bandwidth));
+        if (ret != OPUS_OK)
+            av_log(avctx, AV_LOG_WARNING,
+                   "Unable to set maximum bandwidth: %s\n", opus_strerror(ret));
+    }
+
+    return OPUS_OK;
+}
+
+static int av_cold libopus_encode_init(AVCodecContext *avctx)
+{
+    LibopusEncContext *opus = avctx->priv_data;
+    const uint8_t *channel_mapping;
+    OpusMSEncoder *enc;
+    int ret = OPUS_OK;
+    int coupled_stream_count, header_size, frame_size;
+
+    coupled_stream_count = opus_coupled_streams[avctx->channels - 1];
+    opus->stream_count   = avctx->channels - coupled_stream_count;
+    channel_mapping      = libavcodec_libopus_channel_map[avctx->channels - 1];
+
+    /* FIXME: Opus can handle up to 255 channels. However, the mapping for
+     * anything greater than 8 is undefined. */
+    if (avctx->channels > 8)
+        av_log(avctx, AV_LOG_WARNING,
+               "Channel layout undefined for %d channels.\n", avctx->channels);
+
+    if (!avctx->bit_rate) {
+        /* Sane default copied from opusenc */
+        avctx->bit_rate = 64000 * opus->stream_count +
+                          32000 * coupled_stream_count;
+        av_log(avctx, AV_LOG_WARNING,
+               "No bit rate set. Defaulting to %d bps.\n", avctx->bit_rate);
+    }
+
+    if (avctx->bit_rate < 500 || avctx->bit_rate > 256000 * avctx->channels) {
+        av_log(avctx, AV_LOG_ERROR, "The bit rate %d bps is unsupported. "
+               "Please choose a value between 500 and %d.\n", avctx->bit_rate,
+               256000 * avctx->channels);
+        return AVERROR(EINVAL);
+    }
+
+    frame_size = opus->opts.frame_duration * 48000 / 1000;
+    switch (frame_size) {
+    case 120:
+    case 240:
+        if (opus->opts.application != OPUS_APPLICATION_RESTRICTED_LOWDELAY)
+            av_log(avctx, AV_LOG_WARNING,
+                   "LPC mode cannot be used with a frame duration of less "
+                   "than 10ms. Enabling restricted low-delay mode.\n"
+                   "Use a longer frame duration if this is not what you want.\n");
+        /* Frame sizes less than 10 ms can only use MDCT mode, so switching to
+         * RESTRICTED_LOWDELAY avoids an unnecessary extra 2.5ms lookahead. */
+        opus->opts.application = OPUS_APPLICATION_RESTRICTED_LOWDELAY;
+    case 480:
+    case 960:
+    case 1920:
+    case 2880:
+        opus->opts.packet_size =
+        avctx->frame_size      = frame_size * avctx->sample_rate / 48000;
+        break;
+    default:
+        av_log(avctx, AV_LOG_ERROR, "Invalid frame duration: %g.\n"
+               "Frame duration must be exactly one of: 2.5, 5, 10, 20, 40 or 60.\n",
+               opus->opts.frame_duration);
+        return AVERROR(EINVAL);
+    }
+
+    if (avctx->compression_level < 0 || avctx->compression_level > 10) {
+        av_log(avctx, AV_LOG_WARNING,
+               "Compression level must be in the range 0 to 10. "
+               "Defaulting to 10.\n");
+        opus->opts.complexity = 10;
+    } else {
+        opus->opts.complexity = avctx->compression_level;
+    }
+
+    if (avctx->cutoff) {
+        switch (avctx->cutoff) {
+        case  4000:
+            opus->opts.max_bandwidth = OPUS_BANDWIDTH_NARROWBAND;
+            break;
+        case  6000:
+            opus->opts.max_bandwidth = OPUS_BANDWIDTH_MEDIUMBAND;
+            break;
+        case  8000:
+            opus->opts.max_bandwidth = OPUS_BANDWIDTH_WIDEBAND;
+            break;
+        case 12000:
+            opus->opts.max_bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND;
+            break;
+        case 20000:
+            opus->opts.max_bandwidth = OPUS_BANDWIDTH_FULLBAND;
+            break;
+        default:
+            av_log(avctx, AV_LOG_WARNING,
+                   "Invalid frequency cutoff: %d. Using default maximum bandwidth.\n"
+                   "Cutoff frequency must be exactly one of: 4000, 6000, 8000, 12000 or 20000.\n",
+                   avctx->cutoff);
+            avctx->cutoff = 0;
+        }
+    }
+
+    enc = opus_multistream_encoder_create(avctx->sample_rate, avctx->channels,
+                                          opus->stream_count,
+                                          coupled_stream_count,
+                                          channel_mapping,
+                                          opus->opts.application, &ret);
+    if (ret != OPUS_OK) {
+        av_log(avctx, AV_LOG_ERROR,
+               "Failed to create encoder: %s\n", opus_strerror(ret));
+        return ff_opus_error_to_averror(ret);
+    }
+
+    ret = libopus_configure_encoder(avctx, enc, &opus->opts);
+    if (ret != OPUS_OK) {
+        ret = ff_opus_error_to_averror(ret);
+        goto fail;
+    }
+
+    header_size = 19 + (avctx->channels > 2 ? 2 + avctx->channels : 0);
+    avctx->extradata = av_malloc(header_size + FF_INPUT_BUFFER_PADDING_SIZE);
+    if (!avctx->extradata) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to allocate extradata.\n");
+        ret = AVERROR(ENOMEM);
+        goto fail;
+    }
+    avctx->extradata_size = header_size;
+
+    opus->samples = av_mallocz(frame_size * avctx->channels *
+                               av_get_bytes_per_sample(avctx->sample_fmt));
+    if (!opus->samples) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to allocate samples buffer.\n");
+        ret = AVERROR(ENOMEM);
+        goto fail;
+    }
+
+    ret = opus_multistream_encoder_ctl(enc, OPUS_GET_LOOKAHEAD(&avctx->delay));
+    if (ret != OPUS_OK)
+        av_log(avctx, AV_LOG_WARNING,
+               "Unable to get number of lookahead samples: %s\n",
+               opus_strerror(ret));
+
+    libopus_write_header(avctx, opus->stream_count, coupled_stream_count,
+                         opus_vorbis_channel_map[avctx->channels - 1]);
+
+    ff_af_queue_init(avctx, &opus->afq);
+
+    opus->enc = enc;
+
+    return 0;
+
+fail:
+    opus_multistream_encoder_destroy(enc);
+    av_freep(&avctx->extradata);
+    return ret;
+}
+
+static int libopus_encode(AVCodecContext *avctx, AVPacket *avpkt,
+                          const AVFrame *frame, int *got_packet_ptr)
+{
+    LibopusEncContext *opus = avctx->priv_data;
+    const int sample_size   = avctx->channels *
+                              av_get_bytes_per_sample(avctx->sample_fmt);
+    uint8_t *audio;
+    int ret;
+
+    if (frame) {
+        ff_af_queue_add(&opus->afq, frame);
+        if (frame->nb_samples < opus->opts.packet_size) {
+            audio = opus->samples;
+            memcpy(audio, frame->data[0], frame->nb_samples * sample_size);
+        } else
+            audio = frame->data[0];
+    } else {
+        if (!opus->afq.remaining_samples)
+            return 0;
+        audio = opus->samples;
+        memset(audio, 0, opus->opts.packet_size * sample_size);
+    }
+
+    /* Maximum packet size taken from opusenc in opus-tools. 60ms packets
+     * consist of 3 frames in one packet. The maximum frame size is 1275
+     * bytes along with the largest possible packet header of 7 bytes. */
+    if (ret = ff_alloc_packet(avpkt, (1275 * 3 + 7) * opus->stream_count)) {
+        av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
+        return ret;
+    }
+
+    if (avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
+        ret = opus_multistream_encode_float(opus->enc, (float *)audio,
+                                            opus->opts.packet_size,
+                                            avpkt->data, avpkt->size);
+    else
+        ret = opus_multistream_encode(opus->enc, (opus_int16 *)audio,
+                                      opus->opts.packet_size,
+                                      avpkt->data, avpkt->size);
+
+    if (ret < 0) {
+        av_log(avctx, AV_LOG_ERROR,
+               "Error encoding frame: %s\n", opus_strerror(ret));
+        return ff_opus_error_to_averror(ret);
+    }
+
+    av_shrink_packet(avpkt, ret);
+
+    ff_af_queue_remove(&opus->afq, opus->opts.packet_size,
+                       &avpkt->pts, &avpkt->duration);
+
+    *got_packet_ptr = 1;
+
+    return 0;
+}
+
+static int av_cold libopus_encode_close(AVCodecContext *avctx)
+{
+    LibopusEncContext *opus = avctx->priv_data;
+
+    opus_multistream_encoder_destroy(opus->enc);
+
+    ff_af_queue_close(&opus->afq);
+
+    av_freep(&opus->samples);
+    av_freep(&avctx->extradata);
+
+    return 0;
+}
+
+#define OFFSET(x) offsetof(LibopusEncContext, opts.x)
+#define FLAGS AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
+static const AVOption libopus_options[] = {
+    { "application",    "Intended application type",           OFFSET(application),    AV_OPT_TYPE_INT,   { .i64 = OPUS_APPLICATION_AUDIO }, OPUS_APPLICATION_VOIP, OPUS_APPLICATION_RESTRICTED_LOWDELAY, FLAGS, "application" },
+        { "voip",           "Favor improved speech intelligibility",   0, AV_OPT_TYPE_CONST, { .i64 = OPUS_APPLICATION_VOIP },                0, 0, FLAGS, "application" },
+        { "audio",          "Favor faithfulness to the input",         0, AV_OPT_TYPE_CONST, { .i64 = OPUS_APPLICATION_AUDIO },               0, 0, FLAGS, "application" },
+        { "lowdelay",       "Restrict to only the lowest delay modes", 0, AV_OPT_TYPE_CONST, { .i64 = OPUS_APPLICATION_RESTRICTED_LOWDELAY }, 0, 0, FLAGS, "application" },
+    { "frame_duration", "Duration of a frame in milliseconds", OFFSET(frame_duration), AV_OPT_TYPE_FLOAT, { .dbl = 10.0 }, 2.5, 60.0, FLAGS },
+    { "packet_loss",    "Expected packet loss percentage",     OFFSET(packet_loss),    AV_OPT_TYPE_INT,   { .i64 = 0 },    0,   100,  FLAGS },
+    { "vbr",            "Variable bit rate mode",              OFFSET(vbr),            AV_OPT_TYPE_INT,   { .i64 = 1 },    0,   2,    FLAGS, "vbr" },
+        { "off",            "Use constant bit rate", 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, 0, 0, FLAGS, "vbr" },
+        { "on",             "Use variable bit rate", 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, 0, 0, FLAGS, "vbr" },
+        { "constrained",    "Use constrained VBR",   0, AV_OPT_TYPE_CONST, { .i64 = 2 }, 0, 0, FLAGS, "vbr" },
+    { NULL },
+};
+
+static const AVClass libopus_class = {
+    .class_name = "libopus",
+    .item_name  = av_default_item_name,
+    .option     = libopus_options,
+    .version    = LIBAVUTIL_VERSION_INT,
+};
+
+static const AVCodecDefault libopus_defaults[] = {
+    { "b",                 "0" },
+    { "compression_level", "10" },
+    { NULL },
+};
+
+static const int libopus_sample_rates[] = {
+    48000, 24000, 16000, 12000, 8000, 0,
+};
+
+AVCodec ff_libopus_encoder = {
+    .name            = "libopus",
+    .type            = AVMEDIA_TYPE_AUDIO,
+    .id              = AV_CODEC_ID_OPUS,
+    .priv_data_size  = sizeof(LibopusEncContext),
+    .init            = libopus_encode_init,
+    .encode2         = libopus_encode,
+    .close           = libopus_encode_close,
+    .capabilities    = CODEC_CAP_DELAY | CODEC_CAP_SMALL_LAST_FRAME,
+    .sample_fmts     = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
+                                                      AV_SAMPLE_FMT_FLT,
+                                                      AV_SAMPLE_FMT_NONE },
+    .channel_layouts = ff_vorbis_channel_layouts,
+    .supported_samplerates = libopus_sample_rates,
+    .long_name       = NULL_IF_CONFIG_SMALL("libopus Opus"),
+    .priv_class      = &libopus_class,
+    .defaults        = libopus_defaults,
+};
diff --git a/libavcodec/libschroedinger.h b/libavcodec/libschroedinger.h
index bacc0da..f2e513b 100644
--- a/libavcodec/libschroedinger.h
+++ b/libavcodec/libschroedinger.h
@@ -31,7 +31,7 @@
 
 #include "avcodec.h"
 
-typedef struct {
+typedef struct SchroVideoFormatInfo {
     uint16_t width;
     uint16_t height;
     uint16_t frame_rate_num;
@@ -101,13 +101,13 @@
 void ff_schro_queue_free(FFSchroQueue *queue, void (*free_func)(void *));
 
 static const struct {
-    enum PixelFormat  ff_pix_fmt;
+    enum AVPixelFormat  ff_pix_fmt;
     SchroChromaFormat schro_pix_fmt;
     SchroFrameFormat  schro_frame_fmt;
 } schro_pixel_format_map[] = {
-    { PIX_FMT_YUV420P, SCHRO_CHROMA_420, SCHRO_FRAME_FORMAT_U8_420 },
-    { PIX_FMT_YUV422P, SCHRO_CHROMA_422, SCHRO_FRAME_FORMAT_U8_422 },
-    { PIX_FMT_YUV444P, SCHRO_CHROMA_444, SCHRO_FRAME_FORMAT_U8_444 },
+    { AV_PIX_FMT_YUV420P, SCHRO_CHROMA_420, SCHRO_FRAME_FORMAT_U8_420 },
+    { AV_PIX_FMT_YUV422P, SCHRO_CHROMA_422, SCHRO_FRAME_FORMAT_U8_422 },
+    { AV_PIX_FMT_YUV444P, SCHRO_CHROMA_444, SCHRO_FRAME_FORMAT_U8_444 },
 };
 
 /**
diff --git a/libavcodec/libschroedingerdec.c b/libavcodec/libschroedingerdec.c
index 61e7dcb..4e523dc 100644
--- a/libavcodec/libschroedingerdec.c
+++ b/libavcodec/libschroedingerdec.c
@@ -134,7 +134,7 @@
 /**
 * Returns FFmpeg chroma format.
 */
-static enum PixelFormat get_chroma_format(SchroChromaFormat schro_pix_fmt)
+static enum AVPixelFormat get_chroma_format(SchroChromaFormat schro_pix_fmt)
 {
     int num_formats = sizeof(schro_pixel_format_map) /
                       sizeof(schro_pixel_format_map[0]);
@@ -143,7 +143,7 @@
     for (idx = 0; idx < num_formats; ++idx)
         if (schro_pixel_format_map[idx].schro_pix_fmt == schro_pix_fmt)
             return schro_pixel_format_map[idx].ff_pix_fmt;
-    return PIX_FMT_NONE;
+    return AV_PIX_FMT_NONE;
 }
 
 static av_cold int libschroedinger_decode_init(AVCodecContext *avccontext)
diff --git a/libavcodec/libschroedingerenc.c b/libavcodec/libschroedingerenc.c
index 447661c..aed7818 100644
--- a/libavcodec/libschroedingerenc.c
+++ b/libavcodec/libschroedingerenc.c
@@ -443,8 +443,8 @@
     .encode2        = libschroedinger_encode_frame,
     .close          = libschroedinger_encode_close,
     .capabilities   = CODEC_CAP_DELAY,
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("libschroedinger Dirac 2.2"),
 };
diff --git a/libavcodec/libspeexdec.c b/libavcodec/libspeexdec.c
index 60859b7..935bebb 100644
--- a/libavcodec/libspeexdec.c
+++ b/libavcodec/libspeexdec.c
@@ -22,15 +22,16 @@
 #include <speex/speex_header.h>
 #include <speex/speex_stereo.h>
 #include <speex/speex_callbacks.h>
-#include "avcodec.h"
+
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
+#include "avcodec.h"
 
 typedef struct {
     AVFrame frame;
     SpeexBits bits;
     SpeexStereoState stereo;
     void *dec_state;
-    SpeexHeader *header;
     int frame_size;
 } LibSpeexContext;
 
@@ -39,36 +40,52 @@
 {
     LibSpeexContext *s = avctx->priv_data;
     const SpeexMode *mode;
-
-    // defaults in the case of a missing header
-    if (avctx->sample_rate <= 8000)
-        mode = &speex_nb_mode;
-    else if (avctx->sample_rate <= 16000)
-        mode = &speex_wb_mode;
-    else
-        mode = &speex_uwb_mode;
-
-    if (avctx->extradata_size >= 80)
-        s->header = speex_packet_to_header(avctx->extradata, avctx->extradata_size);
+    SpeexHeader *header = NULL;
+    int spx_mode;
 
     avctx->sample_fmt = AV_SAMPLE_FMT_S16;
-    if (s->header) {
-        avctx->sample_rate = s->header->rate;
-        avctx->channels    = s->header->nb_channels;
-        s->frame_size      = s->header->frame_size;
-
-        mode = speex_lib_get_mode(s->header->mode);
-        if (!mode) {
-            av_log(avctx, AV_LOG_ERROR, "Unknown Speex mode %d\n", s->header->mode);
-            return AVERROR_INVALIDDATA;
-        }
-    } else
-        av_log(avctx, AV_LOG_INFO, "Missing Speex header, assuming defaults.\n");
-
-    if (avctx->channels > 2) {
-        av_log(avctx, AV_LOG_ERROR, "Only stereo and mono are supported.\n");
-        return AVERROR(EINVAL);
+    if (avctx->extradata && avctx->extradata_size >= 80) {
+        header = speex_packet_to_header(avctx->extradata,
+                                        avctx->extradata_size);
+        if (!header)
+            av_log(avctx, AV_LOG_WARNING, "Invalid Speex header\n");
     }
+    if (header) {
+        avctx->sample_rate = header->rate;
+        avctx->channels    = header->nb_channels;
+        spx_mode           = header->mode;
+        speex_header_free(header);
+    } else {
+        switch (avctx->sample_rate) {
+        case 8000:  spx_mode = 0; break;
+        case 16000: spx_mode = 1; break;
+        case 32000: spx_mode = 2; break;
+        default:
+            /* libspeex can handle any mode if initialized as ultra-wideband */
+            av_log(avctx, AV_LOG_WARNING, "Invalid sample rate: %d\n"
+                                          "Decoding as 32kHz ultra-wideband\n",
+                                          avctx->sample_rate);
+            spx_mode = 2;
+        }
+    }
+
+    mode = speex_lib_get_mode(spx_mode);
+    if (!mode) {
+        av_log(avctx, AV_LOG_ERROR, "Unknown Speex mode %d", spx_mode);
+        return AVERROR_INVALIDDATA;
+    }
+    s->frame_size      =  160 << spx_mode;
+    if (!avctx->sample_rate)
+        avctx->sample_rate = 8000 << spx_mode;
+
+    if (avctx->channels < 1 || avctx->channels > 2) {
+        /* libspeex can handle mono or stereo if initialized as stereo */
+        av_log(avctx, AV_LOG_ERROR, "Invalid channel count: %d.\n"
+                                    "Decoding as stereo.\n", avctx->channels);
+        avctx->channels = 2;
+    }
+    avctx->channel_layout = avctx->channels == 2 ? AV_CH_LAYOUT_STEREO :
+                                                   AV_CH_LAYOUT_MONO;
 
     speex_bits_init(&s->bits);
     s->dec_state = speex_decoder_init(mode);
@@ -77,10 +94,6 @@
         return -1;
     }
 
-    if (!s->header) {
-        speex_decoder_ctl(s->dec_state, SPEEX_GET_FRAME_SIZE, &s->frame_size);
-    }
-
     if (avctx->channels == 2) {
         SpeexCallback callback;
         callback.callback_id = SPEEX_INBAND_STEREO;
@@ -113,10 +126,12 @@
     }
     output = (int16_t *)s->frame.data[0];
 
-    /* if there is not enough data left for the smallest possible frame,
-       reset the libspeex buffer using the current packet, otherwise ignore
-       the current packet and keep decoding frames from the libspeex buffer. */
-    if (speex_bits_remaining(&s->bits) < 43) {
+    /* if there is not enough data left for the smallest possible frame or the
+       next 5 bits are a terminator code, reset the libspeex buffer using the
+       current packet, otherwise ignore the current packet and keep decoding
+       frames from the libspeex buffer. */
+    if (speex_bits_remaining(&s->bits) < 5 ||
+        speex_bits_peek_unsigned(&s->bits, 5) == 0x1F) {
         /* check for flush packet */
         if (!buf || !buf_size) {
             *got_frame_ptr = 0;
@@ -146,7 +161,6 @@
 {
     LibSpeexContext *s = avctx->priv_data;
 
-    speex_header_free(s->header);
     speex_bits_destroy(&s->bits);
     speex_decoder_destroy(s->dec_state);
 
diff --git a/libavcodec/libspeexenc.c b/libavcodec/libspeexenc.c
index cd32630..7dfc6d3 100644
--- a/libavcodec/libspeexenc.c
+++ b/libavcodec/libspeexenc.c
@@ -62,19 +62,37 @@
  *     sometimes desirable to use multiple frames-per-packet to reduce the
  *     amount of container overhead.  This can be done by setting the
  *     'frames_per_packet' option to a value 1 to 8.
+ *
+ *
+ * Optional features
+ * Speex encoder supports several optional features, which can be useful
+ * for some conditions.
+ *
+ * Voice Activity Detection
+ *     When enabled, voice activity detection detects whether the audio
+ *     being encoded is speech or silence/background noise. VAD is always
+ *     implicitly activated when encoding in VBR, so the option is only useful
+ *     in non-VBR operation. In this case, Speex detects non-speech periods and
+ *     encodes them with just enough bits to reproduce the background noise.
+ *
+ * Discontinuous Transmission (DTX)
+ *     DTX is an addition to VAD/VBR operation, that allows to stop transmitting
+ *     completely when the background noise is stationary.
+ *     In file-based operation only 5 bits are used for such frames.
  */
 
 #include <speex/speex.h>
 #include <speex/speex_header.h>
 #include <speex/speex_stereo.h>
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
 #include "libavutil/opt.h"
 #include "avcodec.h"
 #include "internal.h"
 #include "audio_frame_queue.h"
 
+/* TODO: Think about converting abr, vad, dtx and such flags to a bit field */
 typedef struct {
     AVClass *class;             ///< AVClass for private options
     SpeexBits bits;             ///< libspeex bitwriter context
@@ -84,6 +102,8 @@
     float vbr_quality;          ///< VBR quality 0.0 to 10.0
     int cbr_quality;            ///< CBR quality 0 to 10
     int abr;                    ///< flag to enable ABR
+    int vad;                    ///< flag to enable VAD
+    int dtx;                    ///< flag to enable DTX
     int pkt_frame_count;        ///< frame count for the current packet
     AudioFrameQueue afq;        ///< frame queue
 } LibSpeexEncContext;
@@ -118,6 +138,8 @@
            s->frames_per_packet);
     av_log(avctx, AV_LOG_DEBUG, "packet size: %d\n",
            avctx->frame_size * s->frames_per_packet);
+    av_log(avctx, AV_LOG_DEBUG, "voice activity detection: %d\n", s->vad);
+    av_log(avctx, AV_LOG_DEBUG, "discontinuous transmission: %d\n", s->dtx);
 }
 
 static av_cold int encode_init(AVCodecContext *avctx)
@@ -158,6 +180,7 @@
     if (avctx->flags & CODEC_FLAG_QSCALE) {
         /* VBR */
         s->header.vbr = 1;
+        s->vad = 1; /* VAD is always implicitly activated for VBR */
         speex_encoder_ctl(s->enc_state, SPEEX_SET_VBR, &s->header.vbr);
         s->vbr_quality = av_clipf(avctx->global_quality / (float)FF_QP2LAMBDA,
                                   0.0f, 10.0f);
@@ -189,6 +212,17 @@
         avctx->bit_rate = s->header.bitrate + (avctx->channels == 2 ? 800 : 0);
     }
 
+    /* VAD is activated with VBR or can be turned on by itself */
+    if (s->vad)
+        speex_encoder_ctl(s->enc_state, SPEEX_SET_VAD, &s->vad);
+
+    /* Activiting Discontinuous Transmission */
+    if (s->dtx) {
+        speex_encoder_ctl(s->enc_state, SPEEX_SET_DTX, &s->dtx);
+        if (!(s->abr || s->vad || s->header.vbr))
+            av_log(avctx, AV_LOG_WARNING, "DTX is not much of use without ABR, VAD or VBR\n");
+    }
+
     /* set encoding complexity */
     if (avctx->compression_level > FF_COMPRESSION_DEFAULT) {
         complexity = av_clip(avctx->compression_level, 0, 10);
@@ -308,6 +342,8 @@
     { "abr",               "Use average bit rate",                      OFFSET(abr),               AV_OPT_TYPE_INT, { .i64 = 0 }, 0,   1, AE },
     { "cbr_quality",       "Set quality value (0 to 10) for CBR",       OFFSET(cbr_quality),       AV_OPT_TYPE_INT, { .i64 = 8 }, 0,  10, AE },
     { "frames_per_packet", "Number of frames to encode in each packet", OFFSET(frames_per_packet), AV_OPT_TYPE_INT, { .i64 = 1 }, 1,   8, AE },
+    { "vad",               "Voice Activity Detection",                  OFFSET(vad),               AV_OPT_TYPE_INT, { .i64 = 0 }, 0,   1, AE },
+    { "dtx",               "Discontinuous Transmission",                OFFSET(dtx),               AV_OPT_TYPE_INT, { .i64 = 0 }, 0,   1, AE },
     { NULL },
 };
 
diff --git a/libavcodec/libstagefright.cpp b/libavcodec/libstagefright.cpp
index cdea8e4..f741df9 100644
--- a/libavcodec/libstagefright.cpp
+++ b/libavcodec/libstagefright.cpp
@@ -153,7 +153,7 @@
 {
     AVCodecContext *avctx = (AVCodecContext*)arg;
     StagefrightContext *s = (StagefrightContext*)avctx->priv_data;
-    const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[avctx->pix_fmt];
+    const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(avctx->pix_fmt);
     Frame* frame;
     MediaBuffer *buffer;
     int32_t w, h;
@@ -325,13 +325,13 @@
     outFormat->findInt32(kKeyColorFormat, &colorFormat);
     if (colorFormat == OMX_QCOM_COLOR_FormatYVU420SemiPlanar ||
         colorFormat == OMX_COLOR_FormatYUV420SemiPlanar)
-        avctx->pix_fmt = PIX_FMT_NV21;
+        avctx->pix_fmt = AV_PIX_FMT_NV21;
     else if (colorFormat == OMX_COLOR_FormatYCbYCr)
-        avctx->pix_fmt = PIX_FMT_YUYV422;
+        avctx->pix_fmt = AV_PIX_FMT_YUYV422;
     else if (colorFormat == OMX_COLOR_FormatCbYCrY)
-        avctx->pix_fmt = PIX_FMT_UYVY422;
+        avctx->pix_fmt = AV_PIX_FMT_UYVY422;
     else
-        avctx->pix_fmt = PIX_FMT_YUV420P;
+        avctx->pix_fmt = AV_PIX_FMT_YUV420P;
 
     outFormat->findCString(kKeyDecoderComponent, &s->decoder_component);
     if (s->decoder_component)
diff --git a/libavcodec/libtheoraenc.c b/libavcodec/libtheoraenc.c
index 2d4ec6e..5a86674 100644
--- a/libavcodec/libtheoraenc.c
+++ b/libavcodec/libtheoraenc.c
@@ -33,6 +33,7 @@
 /* FFmpeg includes */
 #include "libavutil/common.h"
 #include "libavutil/intreadwrite.h"
+#include "libavutil/pixdesc.h"
 #include "libavutil/log.h"
 #include "libavutil/base64.h"
 #include "avcodec.h"
@@ -59,21 +60,26 @@
     const char* message = NULL;
     uint8_t* newdata    = NULL;
     int newsize = avc_context->extradata_size + 2 + packet->bytes;
+    int ret;
 
     if (packet->bytes < 0) {
         message = "ogg_packet has negative size";
+        ret = AVERROR_INVALIDDATA;
     } else if (packet->bytes > 0xffff) {
         message = "ogg_packet is larger than 65535 bytes";
+        ret = AVERROR_INVALIDDATA;
     } else if (newsize < avc_context->extradata_size) {
         message = "extradata_size would overflow";
+        ret = AVERROR_INVALIDDATA;
     } else {
         newdata = av_realloc(avc_context->extradata, newsize);
         if (!newdata)
             message = "av_realloc failed";
+        ret = AVERROR(ENOMEM);
     }
     if (message) {
         av_log(avc_context, AV_LOG_ERROR, "concatenate_packet failed: %s\n", message);
-        return -1;
+        return ret;
     }
 
     avc_context->extradata      = newdata;
@@ -95,7 +101,7 @@
     bytes = th_encode_ctl(h->t_state, TH_ENCCTL_2PASS_OUT, &buf, sizeof(buf));
     if (bytes < 0) {
         av_log(avctx, AV_LOG_ERROR, "Error getting first pass stats\n");
-        return -1;
+        return AVERROR_EXTERNAL;
     }
     if (!eos) {
         h->stats = av_fast_realloc(h->stats, &h->stats_size,
@@ -112,7 +118,7 @@
     return 0;
 #else
     av_log(avctx, AV_LOG_ERROR, "libtheora too old to support 2pass\n");
-    return -1;
+    return AVERROR(ENOSUP);
 #endif
 }
 
@@ -126,7 +132,7 @@
     if (!h->stats) {
         if (!avctx->stats_in) {
             av_log(avctx, AV_LOG_ERROR, "No statsfile for second pass\n");
-            return -1;
+            return AVERROR(EINVAL);
         }
         h->stats_size = strlen(avctx->stats_in) * 3/4;
         h->stats      = av_malloc(h->stats_size);
@@ -138,7 +144,7 @@
                               h->stats_size - h->stats_offset);
         if (bytes < 0) {
             av_log(avctx, AV_LOG_ERROR, "Error submitting stats\n");
-            return -1;
+            return AVERROR_EXTERNAL;
         }
         if (!bytes)
             return 0;
@@ -147,7 +153,7 @@
     return 0;
 #else
     av_log(avctx, AV_LOG_ERROR, "libtheora too old to support 2pass\n");
-    return -1;
+    return AVERROR(ENOSUP);
 #endif
 }
 
@@ -159,6 +165,7 @@
     unsigned int offset;
     TheoraContext *h = avc_context->priv_data;
     uint32_t gop_size = avc_context->gop_size;
+    int ret;
 
     /* Set up the theora_info struct */
     th_info_init(&t_info);
@@ -187,15 +194,15 @@
     else
         t_info.colorspace = TH_CS_UNSPECIFIED;
 
-    if (avc_context->pix_fmt == PIX_FMT_YUV420P)
+    if (avc_context->pix_fmt == AV_PIX_FMT_YUV420P)
         t_info.pixel_fmt = TH_PF_420;
-    else if (avc_context->pix_fmt == PIX_FMT_YUV422P)
+    else if (avc_context->pix_fmt == AV_PIX_FMT_YUV422P)
         t_info.pixel_fmt = TH_PF_422;
-    else if (avc_context->pix_fmt == PIX_FMT_YUV444P)
+    else if (avc_context->pix_fmt == AV_PIX_FMT_YUV444P)
         t_info.pixel_fmt = TH_PF_444;
     else {
         av_log(avc_context, AV_LOG_ERROR, "Unsupported pix_fmt\n");
-        return -1;
+        return AVERROR(EINVAL);
     }
     avcodec_get_chroma_sub_sample(avc_context->pix_fmt, &h->uv_hshift, &h->uv_vshift);
 
@@ -216,7 +223,7 @@
     h->t_state = th_encode_alloc(&t_info);
     if (!h->t_state) {
         av_log(avc_context, AV_LOG_ERROR, "theora_encode_init failed\n");
-        return -1;
+        return AVERROR_EXTERNAL;
     }
 
     h->keyframe_mask = (1 << t_info.keyframe_granule_shift) - 1;
@@ -226,16 +233,16 @@
     if (th_encode_ctl(h->t_state, TH_ENCCTL_SET_KEYFRAME_FREQUENCY_FORCE,
                       &gop_size, sizeof(gop_size))) {
         av_log(avc_context, AV_LOG_ERROR, "Error setting GOP size\n");
-        return -1;
+        return AVERROR_EXTERNAL;
     }
 
     // need to enable 2 pass (via TH_ENCCTL_2PASS_) before encoding headers
     if (avc_context->flags & CODEC_FLAG_PASS1) {
-        if (get_stats(avc_context, 0))
-            return -1;
+        if ((ret = get_stats(avc_context, 0)) < 0)
+            return ret;
     } else if (avc_context->flags & CODEC_FLAG_PASS2) {
-        if (submit_stats(avc_context))
-            return -1;
+        if ((ret = submit_stats(avc_context)) < 0)
+            return ret;
     }
 
     /*
@@ -251,8 +258,8 @@
     th_comment_init(&t_comment);
 
     while (th_encode_flushheader(h->t_state, &t_comment, &o_packet))
-        if (concatenate_packet(&offset, avc_context, &o_packet))
-            return -1;
+        if ((ret = concatenate_packet(&offset, avc_context, &o_packet)) < 0)
+            return ret;
 
     th_comment_clear(&t_comment);
 
@@ -274,8 +281,8 @@
     if (!frame) {
         th_encode_packetout(h->t_state, 1, &o_packet);
         if (avc_context->flags & CODEC_FLAG_PASS1)
-            if (get_stats(avc_context, 1))
-                return -1;
+            if ((ret = get_stats(avc_context, 1)) < 0)
+                return ret;
         return 0;
     }
 
@@ -288,8 +295,8 @@
     }
 
     if (avc_context->flags & CODEC_FLAG_PASS2)
-        if (submit_stats(avc_context))
-            return -1;
+        if ((ret = submit_stats(avc_context)) < 0)
+            return ret;
 
     /* Now call into theora_encode_YUVin */
     result = th_encode_ycbcr_in(h->t_state, t_yuv_buffer);
@@ -307,12 +314,12 @@
             break;
         }
         av_log(avc_context, AV_LOG_ERROR, "theora_encode_YUVin failed (%s) [%d]\n", message, result);
-        return -1;
+        return AVERROR_EXTERNAL;
     }
 
     if (avc_context->flags & CODEC_FLAG_PASS1)
-        if (get_stats(avc_context, 0))
-            return -1;
+        if ((ret = get_stats(avc_context, 0)) < 0)
+            return ret;
 
     /* Pick up returned ogg_packet */
     result = th_encode_packetout(h->t_state, 0, &o_packet);
@@ -325,7 +332,7 @@
         break;
     default:
         av_log(avc_context, AV_LOG_ERROR, "theora_encode_packetout failed [%d]\n", result);
-        return -1;
+        return AVERROR_EXTERNAL;
     }
 
     /* Copy ogg_packet content out to buffer */
@@ -368,8 +375,8 @@
     .close          = encode_close,
     .encode2        = encode_frame,
     .capabilities   = CODEC_CAP_DELAY, // needed to get the statsfile summary
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("libtheora Theora"),
 };
diff --git a/libavcodec/libutvideodec.cpp b/libavcodec/libutvideodec.cpp
index 4f5b91f..f4ba8b3 100644
--- a/libavcodec/libutvideodec.cpp
+++ b/libavcodec/libutvideodec.cpp
@@ -52,19 +52,19 @@
     /* Pick format based on FOURCC */
     switch (avctx->codec_tag) {
     case MKTAG('U', 'L', 'Y', '0'):
-        avctx->pix_fmt = PIX_FMT_YUV420P;
+        avctx->pix_fmt = AV_PIX_FMT_YUV420P;
         format = UTVF_YV12;
         break;
     case MKTAG('U', 'L', 'Y', '2'):
-        avctx->pix_fmt = PIX_FMT_YUYV422;
+        avctx->pix_fmt = AV_PIX_FMT_YUYV422;
         format = UTVF_YUY2;
         break;
     case MKTAG('U', 'L', 'R', 'G'):
-        avctx->pix_fmt = PIX_FMT_BGR24;
+        avctx->pix_fmt = AV_PIX_FMT_BGR24;
         format = UTVF_RGB24_WIN;
         break;
     case MKTAG('U', 'L', 'R', 'A'):
-        avctx->pix_fmt = PIX_FMT_RGB32;
+        avctx->pix_fmt = AV_PIX_FMT_RGB32;
         format = UTVF_RGB32_WIN;
         break;
     default:
@@ -131,21 +131,21 @@
 
     /* Set the output data depending on the colorspace */
     switch (avctx->pix_fmt) {
-    case PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUV420P:
         pic->linesize[0] = w;
         pic->linesize[1] = pic->linesize[2] = w / 2;
         pic->data[0] = utv->buffer;
         pic->data[2] = utv->buffer + (w * h);
         pic->data[1] = pic->data[2] + (w * h / 4);
         break;
-    case PIX_FMT_YUYV422:
+    case AV_PIX_FMT_YUYV422:
         pic->linesize[0] = w * 2;
         pic->data[0] = utv->buffer;
         break;
-    case PIX_FMT_BGR24:
-    case PIX_FMT_RGB32:
+    case AV_PIX_FMT_BGR24:
+    case AV_PIX_FMT_RGB32:
         /* Make the linesize negative, since Ut Video uses bottom-up BGR */
-        pic->linesize[0] = -1 * w * (avctx->pix_fmt == PIX_FMT_BGR24 ? 3 : 4);
+        pic->linesize[0] = -1 * w * (avctx->pix_fmt == AV_PIX_FMT_BGR24 ? 3 : 4);
         pic->data[0] = utv->buffer + utv->buf_size + pic->linesize[0];
         break;
     }
diff --git a/libavcodec/libutvideoenc.cpp b/libavcodec/libutvideoenc.cpp
index 989339a..e9af7df 100644
--- a/libavcodec/libutvideoenc.cpp
+++ b/libavcodec/libutvideoenc.cpp
@@ -40,22 +40,22 @@
     uint32_t flags, in_format;
 
     switch (avctx->pix_fmt) {
-    case PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUV420P:
         in_format = UTVF_YV12;
         avctx->bits_per_coded_sample = 12;
         avctx->codec_tag = MKTAG('U', 'L', 'Y', '0');
         break;
-    case PIX_FMT_YUYV422:
+    case AV_PIX_FMT_YUYV422:
         in_format = UTVF_YUYV;
         avctx->bits_per_coded_sample = 16;
         avctx->codec_tag = MKTAG('U', 'L', 'Y', '2');
         break;
-    case PIX_FMT_BGR24:
+    case AV_PIX_FMT_BGR24:
         in_format = UTVF_RGB24_WIN;
         avctx->bits_per_coded_sample = 24;
         avctx->codec_tag = MKTAG('U', 'L', 'R', 'G');
         break;
-    case PIX_FMT_RGB32:
+    case AV_PIX_FMT_RGB32:
         in_format = UTVF_RGB32_WIN;
         avctx->bits_per_coded_sample = 32;
         avctx->codec_tag = MKTAG('U', 'L', 'R', 'A');
@@ -137,7 +137,7 @@
 
     /* Move input if needed data into Ut Video friendly buffer */
     switch (avctx->pix_fmt) {
-    case PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUV420P:
         y = utv->buffer;
         u = y + w * h;
         v = u + w * h / 4;
@@ -152,15 +152,15 @@
             v += w >> 1;
         }
         break;
-    case PIX_FMT_YUYV422:
+    case AV_PIX_FMT_YUYV422:
         for (i = 0; i < h; i++)
             memcpy(utv->buffer + i * (w << 1),
                    pic->data[0] + i * pic->linesize[0], w << 1);
         break;
-    case PIX_FMT_BGR24:
-    case PIX_FMT_RGB32:
+    case AV_PIX_FMT_BGR24:
+    case AV_PIX_FMT_RGB32:
         /* Ut Video takes bottom-up BGR */
-        rgb_size = avctx->pix_fmt == PIX_FMT_BGR24 ? 3 : 4;
+        rgb_size = avctx->pix_fmt == AV_PIX_FMT_BGR24 ? 3 : 4;
         for (i = 0; i < h; i++)
             memcpy(utv->buffer + (h - i - 1) * w * rgb_size,
                    pic->data[0] + i * pic->linesize[0],
@@ -214,9 +214,9 @@
     AV_CODEC_ID_UTVIDEO,
     CODEC_CAP_AUTO_THREADS | CODEC_CAP_LOSSLESS,
     NULL, /* supported_framerates */
-    (const enum PixelFormat[]) {
-        PIX_FMT_YUV420P, PIX_FMT_YUYV422, PIX_FMT_BGR24,
-        PIX_FMT_RGB32, PIX_FMT_NONE
+    (const enum AVPixelFormat[]) {
+        AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUYV422, AV_PIX_FMT_BGR24,
+        AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE
     },
     NULL, /* supported_samplerates */
     NULL, /* sample_fmts */
diff --git a/libavcodec/libvo-aacenc.c b/libavcodec/libvo-aacenc.c
index 3b7aca7..a09c74c 100644
--- a/libavcodec/libvo-aacenc.c
+++ b/libavcodec/libvo-aacenc.c
@@ -185,6 +185,13 @@
     return 0;
 }
 
+/* duplicated from avpriv_mpeg4audio_sample_rates to avoid shared build
+ * failures */
+static const int mpeg4audio_sample_rates[16] = {
+    96000, 88200, 64000, 48000, 44100, 32000,
+    24000, 22050, 16000, 12000, 11025, 8000, 7350
+};
+
 AVCodec ff_libvo_aacenc_encoder = {
     .name           = "libvo_aacenc",
     .type           = AVMEDIA_TYPE_AUDIO,
@@ -193,7 +200,7 @@
     .init           = aac_encode_init,
     .encode2        = aac_encode_frame,
     .close          = aac_encode_close,
-    .supported_samplerates = avpriv_mpeg4audio_sample_rates,
+    .supported_samplerates = mpeg4audio_sample_rates,
     .capabilities   = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY,
     .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
                                                      AV_SAMPLE_FMT_NONE },
diff --git a/libavcodec/libvo-amrwbenc.c b/libavcodec/libvo-amrwbenc.c
index c463994..eaf632d 100644
--- a/libavcodec/libvo-amrwbenc.c
+++ b/libavcodec/libvo-amrwbenc.c
@@ -79,7 +79,7 @@
 {
     AMRWBContext *s = avctx->priv_data;
 
-    if (avctx->sample_rate != 16000) {
+    if (avctx->sample_rate != 16000 && avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL) {
         av_log(avctx, AV_LOG_ERROR, "Only 16000Hz sample rate supported\n");
         return AVERROR(ENOSYS);
     }
diff --git a/libavcodec/libvorbisenc.c b/libavcodec/libvorbisenc.c
index 76a912d..c81375c 100644
--- a/libavcodec/libvorbisenc.c
+++ b/libavcodec/libvorbisenc.c
@@ -290,18 +290,16 @@
 
     /* send samples to libvorbis */
     if (frame) {
-        const float *audio = (const float *)frame->data[0];
         const int samples = frame->nb_samples;
         float **buffer;
         int c, channels = s->vi.channels;
 
         buffer = vorbis_analysis_buffer(&s->vd, samples);
         for (c = 0; c < channels; c++) {
-            int i;
             int co = (channels > 8) ? c :
                      ff_vorbis_encoding_channel_layout_offsets[channels - 1][c];
-            for (i = 0; i < samples; i++)
-                buffer[c][i] = audio[i * channels + co];
+            memcpy(buffer[c], frame->extended_data[co],
+                   samples * sizeof(*buffer[c]));
         }
         if ((ret = vorbis_analysis_wrote(&s->vd, samples)) < 0) {
             av_log(avctx, AV_LOG_ERROR, "error in vorbis_analysis_wrote()\n");
@@ -360,9 +358,11 @@
     if (duration > 0) {
         /* we do not know encoder delay until we get the first packet from
          * libvorbis, so we have to update the AudioFrameQueue counts */
-        if (!avctx->delay) {
+        if (!avctx->delay && s->afq.frames) {
             avctx->delay              = duration;
-            s->afq.remaining_delay   += duration;
+            av_assert0(!s->afq.remaining_delay);
+            s->afq.frames->duration  += duration;
+            s->afq.frames->pts       -= duration;
             s->afq.remaining_samples += duration;
         }
         ff_af_queue_remove(&s->afq, duration, &avpkt->pts, &avpkt->duration);
@@ -381,7 +381,7 @@
     .encode2        = oggvorbis_encode_frame,
     .close          = oggvorbis_encode_close,
     .capabilities   = CODEC_CAP_DELAY,
-    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLT,
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
                                                       AV_SAMPLE_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("libvorbis"),
     .priv_class     = &class,
diff --git a/libavcodec/libvpxdec.c b/libavcodec/libvpxdec.c
index c0f9f36..61dbaa7 100644
--- a/libavcodec/libvpxdec.c
+++ b/libavcodec/libvpxdec.c
@@ -54,7 +54,7 @@
         return AVERROR(EINVAL);
     }
 
-    avctx->pix_fmt = PIX_FMT_YUV420P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV420P;
     return 0;
 }
 
diff --git a/libavcodec/libvpxenc.c b/libavcodec/libvpxenc.c
index 5449a88..320f5f8 100644
--- a/libavcodec/libvpxenc.c
+++ b/libavcodec/libvpxenc.c
@@ -491,6 +491,7 @@
                     av_log(avctx, AV_LOG_ERROR,
                            "Data buffer alloc (%zu bytes) failed\n",
                            cx_frame->sz);
+                    av_free(cx_frame);
                     return AVERROR(ENOMEM);
                 }
                 memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
@@ -595,15 +596,15 @@
 #endif
 {"speed", "", offsetof(VP8Context, cpu_used), AV_OPT_TYPE_INT, {.i64 = 3}, -16, 16, VE},
 {"quality", "", offsetof(VP8Context, deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"},
-{"vp8flags", "", offsetof(VP8Context, flags), FF_OPT_TYPE_FLAGS, {.dbl = 0}, 0, UINT_MAX, VE, "flags"},
+{"vp8flags", "", offsetof(VP8Context, flags), FF_OPT_TYPE_FLAGS, {.i64 = 0}, 0, UINT_MAX, VE, "flags"},
 {"error_resilient", "enable error resilience", 0, FF_OPT_TYPE_CONST, {.dbl = VP8F_ERROR_RESILIENT}, INT_MIN, INT_MAX, VE, "flags"},
 {"altref", "enable use of alternate reference frames (VP8/2-pass only)", 0, FF_OPT_TYPE_CONST, {.dbl = VP8F_AUTO_ALT_REF}, INT_MIN, INT_MAX, VE, "flags"},
 {"arnr_max_frames", "altref noise reduction max frame count", offsetof(VP8Context, arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 15, VE},
 {"arnr_strength", "altref noise reduction filter strength", offsetof(VP8Context, arnr_strength), AV_OPT_TYPE_INT, {.i64 = 3}, 0, 6, VE},
 {"arnr_type", "altref noise reduction filter type", offsetof(VP8Context, arnr_type), AV_OPT_TYPE_INT, {.i64 = 3}, 1, 3, VE},
 {"rc_lookahead", "Number of frames to look ahead for alternate reference frame selection", offsetof(VP8Context, lag_in_frames), AV_OPT_TYPE_INT, {.i64 = 25}, 0, 25, VE},
-{"crf", "Select the quality for constant quality mode", offsetof(VP8Context, crf), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 63, VE},
-{NULL}
+    { "crf",              "Select the quality for constant quality mode", offsetof(VP8Context, crf), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 63, VE },
+    { NULL }
 };
 
 static const AVClass class = {
@@ -630,7 +631,7 @@
     .encode2        = vp8_encode,
     .close          = vp8_free,
     .capabilities   = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUV420P, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("libvpx VP8"),
     .priv_class     = &class,
     .defaults       = defaults,
diff --git a/libavcodec/libx264.c b/libavcodec/libx264.c
index a2d64d1..8765e56 100644
--- a/libavcodec/libx264.c
+++ b/libavcodec/libx264.c
@@ -132,15 +132,15 @@
 static int avfmt2_num_planes(int avfmt)
 {
     switch (avfmt) {
-    case PIX_FMT_YUV420P:
-    case PIX_FMT_YUVJ420P:
-    case PIX_FMT_YUV420P9:
-    case PIX_FMT_YUV420P10:
-    case PIX_FMT_YUV444P:
+    case AV_PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUVJ420P:
+    case AV_PIX_FMT_YUV420P9:
+    case AV_PIX_FMT_YUV420P10:
+    case AV_PIX_FMT_YUV444P:
         return 3;
 
-    case PIX_FMT_BGR24:
-    case PIX_FMT_RGB24:
+    case AV_PIX_FMT_BGR24:
+    case AV_PIX_FMT_RGB24:
         return 1;
 
     default:
@@ -247,23 +247,23 @@
         }                                                                     \
     } while (0)
 
-static int convert_pix_fmt(enum PixelFormat pix_fmt)
+static int convert_pix_fmt(enum AVPixelFormat pix_fmt)
 {
     switch (pix_fmt) {
-    case PIX_FMT_YUV420P:
-    case PIX_FMT_YUVJ420P:
-    case PIX_FMT_YUV420P9:
-    case PIX_FMT_YUV420P10: return X264_CSP_I420;
-    case PIX_FMT_YUV422P:
-    case PIX_FMT_YUV422P10: return X264_CSP_I422;
-    case PIX_FMT_YUV444P:
-    case PIX_FMT_YUV444P9:
-    case PIX_FMT_YUV444P10: return X264_CSP_I444;
+    case AV_PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUVJ420P:
+    case AV_PIX_FMT_YUV420P9:
+    case AV_PIX_FMT_YUV420P10: return X264_CSP_I420;
+    case AV_PIX_FMT_YUV422P:
+    case AV_PIX_FMT_YUV422P10: return X264_CSP_I422;
+    case AV_PIX_FMT_YUV444P:
+    case AV_PIX_FMT_YUV444P9:
+    case AV_PIX_FMT_YUV444P10: return X264_CSP_I444;
 #ifdef X264_CSP_BGR
-    case PIX_FMT_BGR24:
+    case AV_PIX_FMT_BGR24:
         return X264_CSP_BGR;
 
-    case PIX_FMT_RGB24:
+    case AV_PIX_FMT_RGB24:
         return X264_CSP_RGB;
 #endif
     };
@@ -517,7 +517,7 @@
 
     x4->params.i_slice_count  = avctx->slices;
 
-    x4->params.vui.b_fullrange = avctx->pix_fmt == PIX_FMT_YUVJ420P;
+    x4->params.vui.b_fullrange = avctx->pix_fmt == AV_PIX_FMT_YUVJ420P;
 
     if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER)
         x4->params.b_repeat_headers = 0;
@@ -562,30 +562,30 @@
     return 0;
 }
 
-static const enum PixelFormat pix_fmts_8bit[] = {
-    PIX_FMT_YUV420P,
-    PIX_FMT_YUVJ420P,
-    PIX_FMT_YUV422P,
-    PIX_FMT_YUV444P,
-    PIX_FMT_NONE
+static const enum AVPixelFormat pix_fmts_8bit[] = {
+    AV_PIX_FMT_YUV420P,
+    AV_PIX_FMT_YUVJ420P,
+    AV_PIX_FMT_YUV422P,
+    AV_PIX_FMT_YUV444P,
+    AV_PIX_FMT_NONE
 };
-static const enum PixelFormat pix_fmts_9bit[] = {
-    PIX_FMT_YUV420P9,
-    PIX_FMT_YUV444P9,
-    PIX_FMT_NONE
+static const enum AVPixelFormat pix_fmts_9bit[] = {
+    AV_PIX_FMT_YUV420P9,
+    AV_PIX_FMT_YUV444P9,
+    AV_PIX_FMT_NONE
 };
-static const enum PixelFormat pix_fmts_10bit[] = {
-    PIX_FMT_YUV420P10,
-    PIX_FMT_YUV422P10,
-    PIX_FMT_YUV444P10,
-    PIX_FMT_NONE
+static const enum AVPixelFormat pix_fmts_10bit[] = {
+    AV_PIX_FMT_YUV420P10,
+    AV_PIX_FMT_YUV422P10,
+    AV_PIX_FMT_YUV444P10,
+    AV_PIX_FMT_NONE
 };
-static const enum PixelFormat pix_fmts_8bit_rgb[] = {
+static const enum AVPixelFormat pix_fmts_8bit_rgb[] = {
 #ifdef X264_CSP_BGR
-    PIX_FMT_BGR24,
-    PIX_FMT_RGB24,
+    AV_PIX_FMT_BGR24,
+    AV_PIX_FMT_RGB24,
 #endif
-    PIX_FMT_NONE
+    AV_PIX_FMT_NONE
 };
 
 static av_cold void X264_init_static(AVCodec *codec)
diff --git a/libavcodec/libxavs.c b/libavcodec/libxavs.c
index 4d51c8e..442fc0ee 100644
--- a/libavcodec/libxavs.c
+++ b/libavcodec/libxavs.c
@@ -425,7 +425,7 @@
     .encode2        = XAVS_frame,
     .close          = XAVS_close,
     .capabilities   = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
-    .pix_fmts       = (const enum PixelFormat[]) { PIX_FMT_YUV420P, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("libxavs Chinese AVS (Audio Video Standard)"),
     .priv_class     = &class,
     .defaults       = xavs_defaults,
diff --git a/libavcodec/libxvid.c b/libavcodec/libxvid.c
index a76dfc1..dae8ac8 100644
--- a/libavcodec/libxvid.c
+++ b/libavcodec/libxvid.c
@@ -342,14 +342,6 @@
     }
 }
 
-/**
- * Create the private context for the encoder.
- * All buffers are allocated, settings are loaded from the user,
- * and the encoder context created.
- *
- * @param avctx AVCodecContext pointer to context
- * @return Returns 0 on success, -1 on failure
- */
 static av_cold int xvid_encode_init(AVCodecContext *avctx)  {
     int xerr, i;
     int xvid_flags = avctx->flags;
@@ -621,15 +613,6 @@
     return 0;
 }
 
-/**
- * Encode a single frame.
- *
- * @param avctx AVCodecContext pointer to context
- * @param frame Pointer to encoded frame buffer
- * @param buf_size Size of encoded frame buffer
- * @param data Pointer to AVFrame of unencoded frame
- * @return Returns 0 on success, -1 on failure
- */
 static int xvid_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
                              const AVFrame *picture, int *got_packet)
 {
@@ -656,7 +639,7 @@
     xvid_enc_frame.length    = pkt->size;
 
     /* Initialize input image fields */
-    if( avctx->pix_fmt != PIX_FMT_YUV420P ) {
+    if( avctx->pix_fmt != AV_PIX_FMT_YUV420P ) {
         av_log(avctx, AV_LOG_ERROR, "Xvid: Color spaces other than 420p not supported\n");
         return -1;
     }
@@ -747,13 +730,6 @@
     }
 }
 
-/**
- * Destroy the private context for the encoder.
- * All buffers are freed, and the Xvid encoder context is destroyed.
- *
- * @param avctx AVCodecContext pointer to context
- * @return Returns 0, success guaranteed
- */
 static av_cold int xvid_encode_close(AVCodecContext *avctx) {
     struct xvid_context *x = avctx->priv_data;
 
@@ -772,9 +748,6 @@
     return 0;
 }
 
-/**
- * Xvid codec definition for libavcodec.
- */
 AVCodec ff_libxvid_encoder = {
     .name           = "libxvid",
     .type           = AVMEDIA_TYPE_VIDEO,
@@ -783,6 +756,6 @@
     .init           = xvid_encode_init,
     .encode2        = xvid_encode_frame,
     .close          = xvid_encode_close,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUV420P, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("libxvidcore MPEG-4 part 2"),
 };
diff --git a/libavcodec/libxvid_rc.c b/libavcodec/libxvid_rc.c
index 0f9e50e..93aeb71 100644
--- a/libavcodec/libxvid_rc.c
+++ b/libavcodec/libxvid_rc.c
@@ -57,6 +57,8 @@
 
         if (write(fd, tmp, strlen(tmp)) < 0) {
             av_log(NULL, AV_LOG_ERROR, "Error %s writing 2pass logfile\n", strerror(errno));
+            av_free(tmp_name);
+            close(fd);
             return AVERROR(errno);
         }
     }
diff --git a/libavcodec/ljpegenc.c b/libavcodec/ljpegenc.c
index 8703a6e..d3c2921 100644
--- a/libavcodec/ljpegenc.c
+++ b/libavcodec/ljpegenc.c
@@ -51,7 +51,7 @@
     const int mb_height = (height + s->mjpeg_vsample[0] - 1) / s->mjpeg_vsample[0];
     int ret, max_pkt_size = FF_MIN_BUFFER_SIZE;
 
-    if (avctx->pix_fmt == PIX_FMT_BGRA)
+    if (avctx->pix_fmt == AV_PIX_FMT_BGRA)
         max_pkt_size += width * height * 3 * 4;
     else {
         max_pkt_size += mb_width * mb_height * 3 * 4
@@ -70,9 +70,9 @@
 
     s->header_bits= put_bits_count(&s->pb);
 
-    if(avctx->pix_fmt == PIX_FMT_BGR0
-        || avctx->pix_fmt == PIX_FMT_BGRA
-        || avctx->pix_fmt == PIX_FMT_BGR24){
+    if(avctx->pix_fmt == AV_PIX_FMT_BGR0
+        || avctx->pix_fmt == AV_PIX_FMT_BGRA
+        || avctx->pix_fmt == AV_PIX_FMT_BGR24){
         int x, y, i;
         const int linesize= p->linesize[0];
         uint16_t (*buffer)[4]= (void *) s->rd_scratchpad;
@@ -95,7 +95,7 @@
                 top[i]= left[i]= topleft[i]= buffer[0][i];
             }
             for(x = 0; x < width; x++) {
-                if(avctx->pix_fmt == PIX_FMT_BGR24){
+                if(avctx->pix_fmt == AV_PIX_FMT_BGR24){
                     buffer[x][1] = ptr[3*x+0] - ptr[3*x+1] + 0x100;
                     buffer[x][2] = ptr[3*x+2] - ptr[3*x+1] + 0x100;
                     buffer[x][0] = (ptr[3*x+0] + 2*ptr[3*x+1] + ptr[3*x+2])>>2;
@@ -218,10 +218,10 @@
     .init           = ff_MPV_encode_init,
     .encode2        = encode_picture_lossless,
     .close          = ff_MPV_encode_end,
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_BGR24, PIX_FMT_BGRA, PIX_FMT_BGR0,
-        PIX_FMT_YUVJ420P, PIX_FMT_YUVJ444P, PIX_FMT_YUVJ422P,
-        PIX_FMT_YUV420P, PIX_FMT_YUV444P, PIX_FMT_YUV422P,
-        PIX_FMT_NONE},
+    .pix_fmts       = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_BGR24, AV_PIX_FMT_BGRA, AV_PIX_FMT_BGR0,
+        AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ422P,
+        AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV422P,
+        AV_PIX_FMT_NONE},
     .long_name      = NULL_IF_CONFIG_SMALL("Lossless JPEG"),
 };
diff --git a/libavcodec/loco.c b/libavcodec/loco.c
index 3b22b66..53bdb58 100644
--- a/libavcodec/loco.c
+++ b/libavcodec/loco.c
@@ -262,16 +262,16 @@
     l->mode = AV_RL32(avctx->extradata + 4);
     switch(l->mode) {
     case LOCO_CYUY2: case LOCO_YUY2: case LOCO_UYVY:
-        avctx->pix_fmt = PIX_FMT_YUV422P;
+        avctx->pix_fmt = AV_PIX_FMT_YUV422P;
         break;
     case LOCO_CRGB: case LOCO_RGB:
-        avctx->pix_fmt = PIX_FMT_BGR24;
+        avctx->pix_fmt = AV_PIX_FMT_BGR24;
         break;
     case LOCO_CYV12: case LOCO_YV12:
-        avctx->pix_fmt = PIX_FMT_YUV420P;
+        avctx->pix_fmt = AV_PIX_FMT_YUV420P;
         break;
     case LOCO_CRGBA: case LOCO_RGBA:
-        avctx->pix_fmt = PIX_FMT_RGB32;
+        avctx->pix_fmt = AV_PIX_FMT_RGB32;
         break;
     default:
         av_log(avctx, AV_LOG_INFO, "Unknown colorspace, index = %i\n", l->mode);
diff --git a/libavcodec/log2_tab.c b/libavcodec/log2_tab.c
new file mode 100644
index 0000000..47a1df0
--- /dev/null
+++ b/libavcodec/log2_tab.c
@@ -0,0 +1 @@
+#include "libavutil/log2_tab.c"
diff --git a/libavcodec/lpc.c b/libavcodec/lpc.c
index ac8984a..019689a 100644
--- a/libavcodec/lpc.c
+++ b/libavcodec/lpc.c
@@ -149,6 +149,18 @@
     return est;
 }
 
+int ff_lpc_calc_ref_coefs(LPCContext *s,
+                          const int32_t *samples, int order, double *ref)
+{
+    double autoc[MAX_LPC_ORDER + 1];
+
+    s->lpc_apply_welch_window(samples, s->blocksize, s->windowed_samples);
+    s->lpc_compute_autocorr(s->windowed_samples, s->blocksize, order, autoc);
+    compute_ref_coefs(autoc, order, ref, NULL);
+
+    return order;
+}
+
 /**
  * Calculate LPC coefficients for multiple orders
  *
@@ -226,7 +238,8 @@
         }
         for(i=max_order-1; i>0; i--)
             ref[i] = ref[i-1] - ref[i];
-    }
+    } else
+        av_assert0(0);
     opt_order = max_order;
 
     if(omethod == ORDER_METHOD_EST) {
@@ -262,7 +275,7 @@
     s->lpc_apply_welch_window = lpc_apply_welch_window_c;
     s->lpc_compute_autocorr   = lpc_compute_autocorr_c;
 
-    if (HAVE_MMX)
+    if (ARCH_X86)
         ff_lpc_init_x86(s);
 
     return 0;
diff --git a/libavcodec/lpc.h b/libavcodec/lpc.h
index 680e102..24f776a 100644
--- a/libavcodec/lpc.h
+++ b/libavcodec/lpc.h
@@ -23,6 +23,7 @@
 #define AVCODEC_LPC_H
 
 #include <stdint.h>
+#include "libavutil/avassert.h"
 #include "dsputil.h"
 
 #define ORDER_METHOD_EST     0
@@ -92,6 +93,9 @@
                       enum FFLPCType lpc_type, int lpc_passes,
                       int omethod, int max_shift, int zero_shift);
 
+int ff_lpc_calc_ref_coefs(LPCContext *s,
+                          const int32_t *samples, int order, double *ref);
+
 /**
  * Initialize LPCContext.
  */
@@ -111,6 +115,37 @@
 #endif
 
 /**
+ * Schur recursion.
+ * Produces reflection coefficients from autocorrelation data.
+ */
+static inline void compute_ref_coefs(const LPC_TYPE *autoc, int max_order,
+                                     LPC_TYPE *ref, LPC_TYPE *error)
+{
+    int i, j;
+    LPC_TYPE err;
+    LPC_TYPE gen0[MAX_LPC_ORDER], gen1[MAX_LPC_ORDER];
+
+    for (i = 0; i < max_order; i++)
+        gen0[i] = gen1[i] = autoc[i + 1];
+
+    err    = autoc[0];
+    ref[0] = -gen1[0] / err;
+    err   +=  gen1[0] * ref[0];
+    if (error)
+        error[0] = err;
+    for (i = 1; i < max_order; i++) {
+        for (j = 0; j < max_order - i; j++) {
+            gen1[j] = gen1[j + 1] + ref[i - 1] * gen0[j];
+            gen0[j] = gen1[j + 1] * ref[i - 1] + gen0[j];
+        }
+        ref[i] = -gen1[0] / err;
+        err   +=  gen1[0] * ref[i];
+        if (error)
+            error[i] = err;
+    }
+}
+
+/**
  * Levinson-Durbin recursion.
  * Produce LPC coefficients from autocorrelation data.
  */
@@ -122,6 +157,8 @@
     LPC_TYPE err;
     LPC_TYPE *lpc_last = lpc;
 
+    av_assert2(normalize || !fail);
+
     if (normalize)
         err = *autoc++;
 
diff --git a/libavcodec/lzw.c b/libavcodec/lzw.c
index d06e3a0..97f6e6a 100644
--- a/libavcodec/lzw.c
+++ b/libavcodec/lzw.c
@@ -192,7 +192,7 @@
                 goto the_end;
         }
         if (s->ebuf < s->pbuf) {
-            av_log(0, AV_LOG_ERROR, "lzw overread\n");
+            av_log(NULL, AV_LOG_ERROR, "lzw overread\n");
             goto the_end;
         }
         c = lzw_get_code(s);
diff --git a/libavcodec/lzwenc.c b/libavcodec/lzwenc.c
index 0757d02..7e30765 100644
--- a/libavcodec/lzwenc.c
+++ b/libavcodec/lzwenc.c
@@ -76,7 +76,7 @@
     head ^= (add << LZW_HASH_SHIFT);
     if (head >= LZW_HASH_SIZE)
         head -= LZW_HASH_SIZE;
-    assert(head >= 0 && head < LZW_HASH_SIZE);
+    av_assert2(head >= 0 && head < LZW_HASH_SIZE);
     return head;
 }
 
diff --git a/libavcodec/mace.c b/libavcodec/mace.c
index 4c70979..c76f486 100644
--- a/libavcodec/mace.c
+++ b/libavcodec/mace.c
@@ -187,9 +187,7 @@
     return current;
 }
 
-static void chomp3(ChannelData *chd, int16_t *output, uint8_t val,
-                   int tab_idx,
-                   uint32_t numChannels)
+static void chomp3(ChannelData *chd, int16_t *output, uint8_t val, int tab_idx)
 {
 
     int16_t current = read_table(chd, val, tab_idx);
@@ -200,9 +198,7 @@
     *output = QT_8S_2_16S(current);
 }
 
-static void chomp6(ChannelData *chd, int16_t *output, uint8_t val,
-                   int tab_idx,
-                   uint32_t numChannels)
+static void chomp6(ChannelData *chd, int16_t *output, uint8_t val, int tab_idx)
 {
     int16_t current = read_table(chd, val, tab_idx);
 
@@ -222,8 +218,8 @@
 
     output[0] = QT_8S_2_16S(chd->previous + chd->prev2 -
                             ((chd->prev2-current) >> 2));
-    output[numChannels] = QT_8S_2_16S(chd->previous + current +
-                                      ((chd->prev2-current) >> 2));
+    output[1] = QT_8S_2_16S(chd->previous + current +
+                            ((chd->prev2-current) >> 2));
     chd->prev2 = chd->previous;
     chd->previous = current;
 }
@@ -234,7 +230,7 @@
 
     if (avctx->channels > 2 || avctx->channels <= 0)
         return -1;
-    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
 
     avcodec_get_frame_defaults(&ctx->frame);
     avctx->coded_frame = &ctx->frame;
@@ -247,7 +243,7 @@
 {
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
-    int16_t *samples;
+    int16_t **samples;
     MACEContext *ctx = avctx->priv_data;
     int i, j, k, l, ret;
     int is_mace3 = (avctx->codec_id == AV_CODEC_ID_MACE3);
@@ -258,10 +254,10 @@
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         return ret;
     }
-    samples = (int16_t *)ctx->frame.data[0];
+    samples = (int16_t **)ctx->frame.extended_data;
 
     for(i = 0; i < avctx->channels; i++) {
-        int16_t *output = samples + i;
+        int16_t *output = samples[i];
 
         for (j=0; j < buf_size / (avctx->channels << is_mace3); j++)
             for (k=0; k < (1 << is_mace3); k++) {
@@ -273,13 +269,11 @@
 
                 for (l=0; l < 3; l++) {
                     if (is_mace3)
-                        chomp3(&ctx->chd[i], output, val[1][l], l,
-                               avctx->channels);
+                        chomp3(&ctx->chd[i], output, val[1][l], l);
                     else
-                        chomp6(&ctx->chd[i], output, val[0][l], l,
-                               avctx->channels);
+                        chomp6(&ctx->chd[i], output, val[0][l], l);
 
-                    output += avctx->channels << (1-is_mace3);
+                    output += 1 << (1-is_mace3);
                 }
             }
     }
@@ -299,6 +293,8 @@
     .decode         = mace_decode_frame,
     .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("MACE (Macintosh Audio Compression/Expansion) 3:1"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
+                                                      AV_SAMPLE_FMT_NONE },
 };
 
 AVCodec ff_mace6_decoder = {
@@ -310,4 +306,6 @@
     .decode         = mace_decode_frame,
     .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("MACE (Macintosh Audio Compression/Expansion) 6:1"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
+                                                      AV_SAMPLE_FMT_NONE },
 };
diff --git a/libavcodec/mathops.h b/libavcodec/mathops.h
index 2840735..592f5a5 100644
--- a/libavcodec/mathops.h
+++ b/libavcodec/mathops.h
@@ -22,9 +22,15 @@
 #ifndef AVCODEC_MATHOPS_H
 #define AVCODEC_MATHOPS_H
 
+#include <stdint.h>
+
 #include "libavutil/common.h"
 #include "config.h"
 
+extern const uint32_t ff_inverse[257];
+extern const uint8_t  ff_reverse[256];
+extern const uint8_t ff_sqrt_tab[256];
+
 #if   ARCH_ARM
 #   include "arm/mathops.h"
 #elif ARCH_AVR32
@@ -185,4 +191,28 @@
 #   define PACK_2S16(a,b)    PACK_2U16((a)&0xffff, (b)&0xffff)
 #endif
 
+#ifndef FASTDIV
+#   define FASTDIV(a,b) ((uint32_t)((((uint64_t)a) * ff_inverse[b]) >> 32))
+#endif /* FASTDIV */
+
+static inline av_const unsigned int ff_sqrt(unsigned int a)
+{
+    unsigned int b;
+
+    if (a < 255) return (ff_sqrt_tab[a + 1] - 1) >> 4;
+    else if (a < (1 << 12)) b = ff_sqrt_tab[a >> 4] >> 2;
+#if !CONFIG_SMALL
+    else if (a < (1 << 14)) b = ff_sqrt_tab[a >> 6] >> 1;
+    else if (a < (1 << 16)) b = ff_sqrt_tab[a >> 8]   ;
+#endif
+    else {
+        int s = av_log2_16bit(a >> 16) >> 1;
+        unsigned int c = a >> (s + 2);
+        b = ff_sqrt_tab[c >> (s + 8)];
+        b = FASTDIV(c,b) + (b << s);
+    }
+
+    return b - (a < b * b);
+}
+
 #endif /* AVCODEC_MATHOPS_H */
diff --git a/libavutil/inverse.c b/libavcodec/mathtables.c
similarity index 62%
rename from libavutil/inverse.c
rename to libavcodec/mathtables.c
index 74c7a93..037b135 100644
--- a/libavutil/inverse.c
+++ b/libavcodec/mathtables.c
@@ -1,5 +1,4 @@
 /*
- * Inverse table
  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
  *
  * This file is part of FFmpeg.
@@ -58,3 +57,33 @@
   17318417,   17248865,   17179870,   17111424,   17043522,   16976156,   16909321,   16843010,
   16777216
 };
+
+const uint8_t ff_sqrt_tab[256]={
+  0, 16, 23, 28, 32, 36, 40, 43, 46, 48, 51, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 77, 79, 80, 82, 84, 85, 87, 88, 90,
+ 91, 92, 94, 95, 96, 98, 99,100,102,103,104,105,107,108,109,110,111,112,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
+128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,144,145,146,147,148,149,150,151,151,152,153,154,155,156,156,
+157,158,159,160,160,161,162,163,164,164,165,166,167,168,168,169,170,171,171,172,173,174,174,175,176,176,177,178,179,179,180,181,
+182,182,183,184,184,185,186,186,187,188,188,189,190,190,191,192,192,193,194,194,195,196,196,197,198,198,199,200,200,201,202,202,
+203,204,204,205,205,206,207,207,208,208,209,210,210,211,212,212,213,213,214,215,215,216,216,217,218,218,219,219,220,220,221,222,
+222,223,223,224,224,225,226,226,227,227,228,228,229,230,230,231,231,232,232,233,233,234,235,235,236,236,237,237,238,238,239,239,
+240,240,241,242,242,243,243,244,244,245,245,246,246,247,247,248,248,249,249,250,250,251,251,252,252,253,253,254,254,255,255,255
+};
+
+const uint8_t ff_reverse[256] = {
+0x00,0x80,0x40,0xC0,0x20,0xA0,0x60,0xE0,0x10,0x90,0x50,0xD0,0x30,0xB0,0x70,0xF0,
+0x08,0x88,0x48,0xC8,0x28,0xA8,0x68,0xE8,0x18,0x98,0x58,0xD8,0x38,0xB8,0x78,0xF8,
+0x04,0x84,0x44,0xC4,0x24,0xA4,0x64,0xE4,0x14,0x94,0x54,0xD4,0x34,0xB4,0x74,0xF4,
+0x0C,0x8C,0x4C,0xCC,0x2C,0xAC,0x6C,0xEC,0x1C,0x9C,0x5C,0xDC,0x3C,0xBC,0x7C,0xFC,
+0x02,0x82,0x42,0xC2,0x22,0xA2,0x62,0xE2,0x12,0x92,0x52,0xD2,0x32,0xB2,0x72,0xF2,
+0x0A,0x8A,0x4A,0xCA,0x2A,0xAA,0x6A,0xEA,0x1A,0x9A,0x5A,0xDA,0x3A,0xBA,0x7A,0xFA,
+0x06,0x86,0x46,0xC6,0x26,0xA6,0x66,0xE6,0x16,0x96,0x56,0xD6,0x36,0xB6,0x76,0xF6,
+0x0E,0x8E,0x4E,0xCE,0x2E,0xAE,0x6E,0xEE,0x1E,0x9E,0x5E,0xDE,0x3E,0xBE,0x7E,0xFE,
+0x01,0x81,0x41,0xC1,0x21,0xA1,0x61,0xE1,0x11,0x91,0x51,0xD1,0x31,0xB1,0x71,0xF1,
+0x09,0x89,0x49,0xC9,0x29,0xA9,0x69,0xE9,0x19,0x99,0x59,0xD9,0x39,0xB9,0x79,0xF9,
+0x05,0x85,0x45,0xC5,0x25,0xA5,0x65,0xE5,0x15,0x95,0x55,0xD5,0x35,0xB5,0x75,0xF5,
+0x0D,0x8D,0x4D,0xCD,0x2D,0xAD,0x6D,0xED,0x1D,0x9D,0x5D,0xDD,0x3D,0xBD,0x7D,0xFD,
+0x03,0x83,0x43,0xC3,0x23,0xA3,0x63,0xE3,0x13,0x93,0x53,0xD3,0x33,0xB3,0x73,0xF3,
+0x0B,0x8B,0x4B,0xCB,0x2B,0xAB,0x6B,0xEB,0x1B,0x9B,0x5B,0xDB,0x3B,0xBB,0x7B,0xFB,
+0x07,0x87,0x47,0xC7,0x27,0xA7,0x67,0xE7,0x17,0x97,0x57,0xD7,0x37,0xB7,0x77,0xF7,
+0x0F,0x8F,0x4F,0xCF,0x2F,0xAF,0x6F,0xEF,0x1F,0x9F,0x5F,0xDF,0x3F,0xBF,0x7F,0xFF,
+};
diff --git a/libavcodec/mdec.c b/libavcodec/mdec.c
index 4d9ee4d..52b9040 100644
--- a/libavcodec/mdec.c
+++ b/libavcodec/mdec.c
@@ -236,7 +236,7 @@
         avctx->idct_algo = FF_IDCT_SIMPLE;
     p->qstride= 0;
     p->qscale_table= av_mallocz(a->mb_width);
-    avctx->pix_fmt= PIX_FMT_YUVJ420P;
+    avctx->pix_fmt= AV_PIX_FMT_YUVJ420P;
 
     return 0;
 }
diff --git a/libavcodec/mimic.c b/libavcodec/mimic.c
index 93d0bbc..25db9ca 100644
--- a/libavcodec/mimic.c
+++ b/libavcodec/mimic.c
@@ -340,7 +340,7 @@
         ctx->avctx     = avctx;
         avctx->width   = width;
         avctx->height  = height;
-        avctx->pix_fmt = PIX_FMT_YUV420P;
+        avctx->pix_fmt = AV_PIX_FMT_YUV420P;
         for(i = 0; i < 3; i++) {
             ctx->num_vblocks[i] = -((-height) >> (3 + !!i));
             ctx->num_hblocks[i] =     width   >> (3 + !!i) ;
diff --git a/libavcodec/mips/Makefile b/libavcodec/mips/Makefile
index ff46768..feeec99 100644
--- a/libavcodec/mips/Makefile
+++ b/libavcodec/mips/Makefile
@@ -1,7 +1,3 @@
-MMI-OBJS += mips/dsputil_mmi.o                                          \
-            mips/idct_mmi.o                                             \
-            mips/mpegvideo_mmi.o
-
 MIPSFPU-OBJS-$(CONFIG_AMRNB_DECODER)      += mips/acelp_filters_mips.o     \
                                              mips/celp_filters_mips.o      \
                                              mips/celp_math_mips.o         \
@@ -15,5 +11,6 @@
 MIPSDSPR1-OBJS-$(CONFIG_MPEGAUDIODSP)     += mips/mpegaudiodsp_mips_fixed.o
 OBJS-$(CONFIG_FFT)                        += mips/fft_init_table.o
 MIPSFPU-OBJS-$(CONFIG_FFT)                += mips/fft_mips.o
-MIPSFPU-OBJS-$(HAVE_INLINE_ASM)           += mips/fmtconvert_mips.o
-MIPSFPU-OBJS-$(HAVE_INLINE_ASM)           += mips/dsputil_mips.o
+MIPSFPU-OBJS                              += mips/dsputil_mips.o           \
+                                             mips/fmtconvert_mips.o
+OBJS-$(CONFIG_AC3DSP)                     += mips/ac3dsp_mips.o
diff --git a/libavcodec/mips/ac3dsp_mips.c b/libavcodec/mips/ac3dsp_mips.c
new file mode 100644
index 0000000..e503645
--- /dev/null
+++ b/libavcodec/mips/ac3dsp_mips.c
@@ -0,0 +1,372 @@
+/*
+ * Copyright (c) 2012
+ *      MIPS Technologies, Inc., California.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the MIPS Technologies, Inc., nor the names of its
+ *    contributors may be used to endorse or promote products derived from
+ *    this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE MIPS TECHNOLOGIES, INC. ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE MIPS TECHNOLOGIES, INC. BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * Author:  Branimir Vasic (bvasic@mips.com)
+ *
+ * Various AC-3 DSP Utils optimized for MIPS
+ *
+ * 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
+ * Reference: libavcodec/ac3dsp.c
+ */
+
+#include "config.h"
+#include "libavcodec/ac3dsp.h"
+#include "libavcodec/ac3.h"
+
+
+#if HAVE_INLINE_ASM
+#if HAVE_MIPSDSPR1
+static void ac3_bit_alloc_calc_bap_mips(int16_t *mask, int16_t *psd,
+                                        int start, int end,
+                                        int snr_offset, int floor,
+                                        const uint8_t *bap_tab, uint8_t *bap)
+{
+    int band, band_end, cond;
+    int m, address1, address2;
+    int16_t *psd1, *psd_end;
+    uint8_t *bap1;
+
+    if (snr_offset == -960) {
+        memset(bap, 0, AC3_MAX_COEFS);
+        return;
+    }
+
+    psd1 = &psd[start];
+    bap1 = &bap[start];
+    band = ff_ac3_bin_to_band_tab[start];
+
+    do {
+        m = (FFMAX(mask[band] - snr_offset - floor, 0) & 0x1FE0) + floor;
+        band_end = ff_ac3_band_start_tab[++band];
+        band_end = FFMIN(band_end, end);
+        psd_end = psd + band_end - 1;
+
+        __asm__ volatile (
+            "slt        %[cond],        %[psd1],        %[psd_end]  \n\t"
+            "beqz       %[cond],        1f                          \n\t"
+            "2:                                                     \n\t"
+            "lh         %[address1],    0(%[psd1])                  \n\t"
+            "lh         %[address2],    2(%[psd1])                  \n\t"
+            "addiu      %[psd1],        %[psd1],        4           \n\t"
+            "subu       %[address1],    %[address1],    %[m]        \n\t"
+            "sra        %[address1],    %[address1],    5           \n\t"
+            "addiu      %[address1],    %[address1],    -32         \n\t"
+            "shll_s.w   %[address1],    %[address1],    26          \n\t"
+            "subu       %[address2],    %[address2],    %[m]        \n\t"
+            "sra        %[address2],    %[address2],    5           \n\t"
+            "sra        %[address1],    %[address1],    26          \n\t"
+            "addiu      %[address1],    %[address1],    32          \n\t"
+            "lbux       %[address1],    %[address1](%[bap_tab])     \n\t"
+            "addiu      %[address2],    %[address2],    -32         \n\t"
+            "shll_s.w   %[address2],    %[address2],    26          \n\t"
+            "sb         %[address1],    0(%[bap1])                  \n\t"
+            "slt        %[cond],        %[psd1],        %[psd_end]  \n\t"
+            "sra        %[address2],    %[address2],    26          \n\t"
+            "addiu      %[address2],    %[address2],    32          \n\t"
+            "lbux       %[address2],    %[address2](%[bap_tab])     \n\t"
+            "sb         %[address2],    1(%[bap1])                  \n\t"
+            "addiu      %[bap1],        %[bap1],        2           \n\t"
+            "bnez       %[cond],        2b                          \n\t"
+            "addiu      %[psd_end],     %[psd_end],     2           \n\t"
+            "slt        %[cond],        %[psd1],        %[psd_end]  \n\t"
+            "beqz       %[cond],        3f                          \n\t"
+            "1:                                                     \n\t"
+            "lh         %[address1],    0(%[psd1])                  \n\t"
+            "addiu      %[psd1],        %[psd1],        2           \n\t"
+            "subu       %[address1],    %[address1],    %[m]        \n\t"
+            "sra        %[address1],    %[address1],    5           \n\t"
+            "addiu      %[address1],    %[address1],    -32         \n\t"
+            "shll_s.w   %[address1],    %[address1],    26          \n\t"
+            "sra        %[address1],    %[address1],    26          \n\t"
+            "addiu      %[address1],    %[address1],    32          \n\t"
+            "lbux       %[address1],    %[address1](%[bap_tab])     \n\t"
+            "sb         %[address1],    0(%[bap1])                  \n\t"
+            "addiu      %[bap1],        %[bap1],        1           \n\t"
+            "3:                                                     \n\t"
+
+            : [address1]"=&r"(address1), [address2]"=&r"(address2),
+              [cond]"=&r"(cond), [bap1]"+r"(bap1),
+              [psd1]"+r"(psd1), [psd_end]"+r"(psd_end)
+            : [m]"r"(m), [bap_tab]"r"(bap_tab)
+            : "memory"
+        );
+    } while (end > band_end);
+}
+
+static void ac3_update_bap_counts_mips(uint16_t mant_cnt[16], uint8_t *bap,
+                                       int len)
+{
+    int temp0, temp1, temp2, temp3, temp4, temp5, temp6, temp7;
+
+    __asm__ volatile (
+        "andi   %[temp3],   %[len],         3               \n\t"
+        "addu   %[temp2],   %[bap],         %[len]          \n\t"
+        "addu   %[temp4],   %[bap],         %[temp3]        \n\t"
+        "beq    %[temp2],   %[temp4],       4f              \n\t"
+        "1:                                                 \n\t"
+        "lbu    %[temp0],   -1(%[temp2])                    \n\t"
+        "lbu    %[temp5],   -2(%[temp2])                    \n\t"
+        "lbu    %[temp6],   -3(%[temp2])                    \n\t"
+        "sll    %[temp0],   %[temp0],       1               \n\t"
+        "addu   %[temp0],   %[mant_cnt],    %[temp0]        \n\t"
+        "sll    %[temp5],   %[temp5],       1               \n\t"
+        "addu   %[temp5],   %[mant_cnt],    %[temp5]        \n\t"
+        "lhu    %[temp1],   0(%[temp0])                     \n\t"
+        "sll    %[temp6],   %[temp6],       1               \n\t"
+        "addu   %[temp6],   %[mant_cnt],    %[temp6]        \n\t"
+        "addiu  %[temp1],   %[temp1],       1               \n\t"
+        "sh     %[temp1],   0(%[temp0])                     \n\t"
+        "lhu    %[temp1],   0(%[temp5])                     \n\t"
+        "lbu    %[temp7],   -4(%[temp2])                    \n\t"
+        "addiu  %[temp2],   %[temp2],       -4              \n\t"
+        "addiu  %[temp1],   %[temp1],       1               \n\t"
+        "sh     %[temp1],   0(%[temp5])                     \n\t"
+        "lhu    %[temp1],   0(%[temp6])                     \n\t"
+        "sll    %[temp7],   %[temp7],       1               \n\t"
+        "addu   %[temp7],   %[mant_cnt],    %[temp7]        \n\t"
+        "addiu  %[temp1],   %[temp1],1                      \n\t"
+        "sh     %[temp1],   0(%[temp6])                     \n\t"
+        "lhu    %[temp1],   0(%[temp7])                     \n\t"
+        "addiu  %[temp1],   %[temp1],       1               \n\t"
+        "sh     %[temp1],   0(%[temp7])                     \n\t"
+        "bne    %[temp2],   %[temp4],       1b              \n\t"
+        "4:                                                 \n\t"
+        "beqz   %[temp3],   2f                              \n\t"
+        "3:                                                 \n\t"
+        "addiu  %[temp3],   %[temp3],       -1              \n\t"
+        "lbu    %[temp0],   -1(%[temp2])                    \n\t"
+        "addiu  %[temp2],   %[temp2],       -1              \n\t"
+        "sll    %[temp0],   %[temp0],       1               \n\t"
+        "addu   %[temp0],   %[mant_cnt],    %[temp0]        \n\t"
+        "lhu    %[temp1],   0(%[temp0])                     \n\t"
+        "addiu  %[temp1],   %[temp1],       1               \n\t"
+        "sh     %[temp1],   0(%[temp0])                     \n\t"
+        "bgtz   %[temp3],   3b                              \n\t"
+        "2:                                                 \n\t"
+
+        : [temp0] "=&r" (temp0), [temp1] "=&r" (temp1),
+          [temp2] "=&r" (temp2), [temp3] "=&r" (temp3),
+          [temp4] "=&r" (temp4), [temp5] "=&r" (temp5),
+          [temp6] "=&r" (temp6), [temp7] "=&r" (temp7)
+        : [len] "r" (len), [bap] "r" (bap),
+          [mant_cnt] "r" (mant_cnt)
+        : "memory"
+    );
+}
+#endif
+
+#if HAVE_MIPSFPU
+static void float_to_fixed24_mips(int32_t *dst, const float *src, unsigned int len)
+{
+    const float scale = 1 << 24;
+    float src0, src1, src2, src3, src4, src5, src6, src7;
+    int temp0, temp1, temp2, temp3, temp4, temp5, temp6, temp7;
+
+    do {
+        __asm__ volatile (
+            "lwc1       %[src0],    0(%[src])               \n\t"
+            "lwc1       %[src1],    4(%[src])               \n\t"
+            "lwc1       %[src2],    8(%[src])               \n\t"
+            "lwc1       %[src3],    12(%[src])              \n\t"
+            "lwc1       %[src4],    16(%[src])              \n\t"
+            "lwc1       %[src5],    20(%[src])              \n\t"
+            "lwc1       %[src6],    24(%[src])              \n\t"
+            "lwc1       %[src7],    28(%[src])              \n\t"
+            "mul.s      %[src0],    %[src0],    %[scale]    \n\t"
+            "mul.s      %[src1],    %[src1],    %[scale]    \n\t"
+            "mul.s      %[src2],    %[src2],    %[scale]    \n\t"
+            "mul.s      %[src3],    %[src3],    %[scale]    \n\t"
+            "mul.s      %[src4],    %[src4],    %[scale]    \n\t"
+            "mul.s      %[src5],    %[src5],    %[scale]    \n\t"
+            "mul.s      %[src6],    %[src6],    %[scale]    \n\t"
+            "mul.s      %[src7],    %[src7],    %[scale]    \n\t"
+            "cvt.w.s    %[src0],    %[src0]                 \n\t"
+            "cvt.w.s    %[src1],    %[src1]                 \n\t"
+            "cvt.w.s    %[src2],    %[src2]                 \n\t"
+            "cvt.w.s    %[src3],    %[src3]                 \n\t"
+            "cvt.w.s    %[src4],    %[src4]                 \n\t"
+            "cvt.w.s    %[src5],    %[src5]                 \n\t"
+            "cvt.w.s    %[src6],    %[src6]                 \n\t"
+            "cvt.w.s    %[src7],    %[src7]                 \n\t"
+            "mfc1       %[temp0],   %[src0]                 \n\t"
+            "mfc1       %[temp1],   %[src1]                 \n\t"
+            "mfc1       %[temp2],   %[src2]                 \n\t"
+            "mfc1       %[temp3],   %[src3]                 \n\t"
+            "mfc1       %[temp4],   %[src4]                 \n\t"
+            "mfc1       %[temp5],   %[src5]                 \n\t"
+            "mfc1       %[temp6],   %[src6]                 \n\t"
+            "mfc1       %[temp7],   %[src7]                 \n\t"
+            "sw         %[temp0],   0(%[dst])               \n\t"
+            "sw         %[temp1],   4(%[dst])               \n\t"
+            "sw         %[temp2],   8(%[dst])               \n\t"
+            "sw         %[temp3],   12(%[dst])              \n\t"
+            "sw         %[temp4],   16(%[dst])              \n\t"
+            "sw         %[temp5],   20(%[dst])              \n\t"
+            "sw         %[temp6],   24(%[dst])              \n\t"
+            "sw         %[temp7],   28(%[dst])              \n\t"
+
+            : [dst] "+r" (dst), [src] "+r" (src),
+              [src0] "=&f" (src0), [src1] "=&f" (src1),
+              [src2] "=&f" (src2), [src3] "=&f" (src3),
+              [src4] "=&f" (src4), [src5] "=&f" (src5),
+              [src6] "=&f" (src6), [src7] "=&f" (src7),
+              [temp0] "=r" (temp0), [temp1] "=r" (temp1),
+              [temp2] "=r" (temp2), [temp3] "=r" (temp3),
+              [temp4] "=r" (temp4), [temp5] "=r" (temp5),
+              [temp6] "=r" (temp6), [temp7] "=r" (temp7)
+            : [scale] "f" (scale)
+            : "memory"
+        );
+        src = src + 8;
+        dst = dst + 8;
+        len -= 8;
+    } while (len > 0);
+}
+
+static void ac3_downmix_mips(float (*samples)[256], float (*matrix)[2], int out_ch, int in_ch, int len)
+{
+    int i, j;
+    float v0, v1, v2, v3;
+    float v4, v5, v6, v7;
+    float samples0, samples1, samples2, samples3, matrix_j, matrix_j2;
+    float *samples_p,*matrix_p;
+    if (out_ch == 2) {
+        for (i = 0; i < len; i += 4) {
+            v0 = v1 = v2 = v3 = 0.0f;
+            v4 = v5 = v6 = v7 = 0.0f;
+            samples_p = &samples[0][i];
+            matrix_p = &matrix[0][0];
+            __asm__ volatile (
+                "move   %[j],           $zero                               \n\t"
+                "1:                                                         \n\t"
+                "lwc1   %[matrix_j],    0(%[matrix_p])                      \n\t"
+                "lwc1   %[matrix_j2],   4(%[matrix_p])                      \n\t"
+                "lwc1   %[samples0],    0(%[samples_p])                     \n\t"
+                "lwc1   %[samples1],    4(%[samples_p])                     \n\t"
+                "lwc1   %[samples2],    8(%[samples_p])                     \n\t"
+                "lwc1   %[samples3],    12(%[samples_p])                    \n\t"
+                "addiu  %[matrix_p],    8                                   \n\t"
+                "madd.s %[v0],          %[v0],  %[samples0],    %[matrix_j] \n\t"
+                "madd.s %[v1],          %[v1],  %[samples1],    %[matrix_j] \n\t"
+                "madd.s %[v2],          %[v2],  %[samples2],    %[matrix_j] \n\t"
+                "madd.s %[v3],          %[v3],  %[samples3],    %[matrix_j] \n\t"
+                "madd.s %[v4],          %[v4],  %[samples0],    %[matrix_j2]\n\t"
+                "madd.s %[v5],          %[v5],  %[samples1],    %[matrix_j2]\n\t"
+                "madd.s %[v6],          %[v6],  %[samples2],    %[matrix_j2]\n\t"
+                "madd.s %[v7],          %[v7],  %[samples3],    %[matrix_j2]\n\t"
+                "addiu  %[j],           1                                   \n\t"
+                "addiu  %[samples_p],   1024                                \n\t"
+                "bne    %[j],           %[in_ch],   1b                      \n\t"
+                :[samples0]"=&f"(samples0), [samples1]"=&f"(samples1),
+                 [samples2]"=&f"(samples2), [samples3]"=&f"(samples3),
+                 [samples_p]"+r"(samples_p), [matrix_j]"=&f"(matrix_j),
+                 [matrix_p]"+r"(matrix_p), [v0]"+f"(v0), [v1]"+f"(v1),
+                 [v2]"+f"(v2), [v3]"+f"(v3), [v4]"+f"(v4), [v5]"+f"(v5),
+                 [v6]"+f"(v6), [v7]"+f"(v7),[j]"=&r"(j), [matrix_j2]"=&f"(matrix_j2)
+                :[in_ch]"r"(in_ch)
+                :"memory"
+            );
+            samples[0][i  ] = v0;
+            samples[0][i+1] = v1;
+            samples[0][i+2] = v2;
+            samples[0][i+3] = v3;
+            samples[1][i  ] = v4;
+            samples[1][i+1] = v5;
+            samples[1][i+2] = v6;
+            samples[1][i+3] = v7;
+        }
+    } else if (out_ch == 1) {
+        for (i = 0; i < len; i += 4) {
+            v0 = v1 = v2 = v3 = 0.0f;
+            samples_p = &samples[0][i];
+            matrix_p = &matrix[0][0];
+            __asm__ volatile (
+                "move   %[j],           $zero                               \n\t"
+                "1:                                                         \n\t"
+                "lwc1   %[matrix_j],    0(%[matrix_p])                      \n\t"
+                "lwc1   %[samples0],    0(%[samples_p])                     \n\t"
+                "lwc1   %[samples1],    4(%[samples_p])                     \n\t"
+                "lwc1   %[samples2],    8(%[samples_p])                     \n\t"
+                "lwc1   %[samples3],    12(%[samples_p])                    \n\t"
+                "addiu  %[matrix_p],    8                                   \n\t"
+                "madd.s %[v0],          %[v0],  %[samples0],    %[matrix_j] \n\t"
+                "madd.s %[v1],          %[v1],  %[samples1],    %[matrix_j] \n\t"
+                "madd.s %[v2],          %[v2],  %[samples2],    %[matrix_j] \n\t"
+                "madd.s %[v3],          %[v3],  %[samples3],    %[matrix_j] \n\t"
+                "addiu  %[j],           1                                   \n\t"
+                "addiu  %[samples_p],   1024                                \n\t"
+                "bne    %[j],           %[in_ch],   1b                      \n\t"
+                :[samples0]"=&f"(samples0), [samples1]"=&f"(samples1),
+                 [samples2]"=&f"(samples2), [samples3]"=&f"(samples3),
+                 [samples_p]"+r"(samples_p), [matrix_j]"=&f"(matrix_j),
+                 [matrix_p]"+r"(matrix_p), [v0]"+f"(v0), [v1]"+f"(v1),
+                 [v2]"+f"(v2), [v3]"+f"(v3), [j]"=&r"(j)
+                :[in_ch]"r"(in_ch)
+                :"memory"
+            );
+            samples[0][i  ] = v0;
+            samples[0][i+1] = v1;
+            samples[0][i+2] = v2;
+            samples[0][i+3] = v3;
+        }
+    }
+}
+#endif
+#endif /* HAVE_INLINE_ASM */
+
+void ff_ac3dsp_init_mips(AC3DSPContext *c, int bit_exact) {
+#if HAVE_INLINE_ASM
+#if HAVE_MIPSDSPR1
+    c->bit_alloc_calc_bap = ac3_bit_alloc_calc_bap_mips;
+    c->update_bap_counts  = ac3_update_bap_counts_mips;
+#endif
+#if HAVE_MIPSFPU
+    c->float_to_fixed24 = float_to_fixed24_mips;
+    c->downmix          = ac3_downmix_mips;
+#endif
+#endif
+
+}
diff --git a/libavcodec/mips/acelp_filters_mips.c b/libavcodec/mips/acelp_filters_mips.c
index 498660b..1e0845c 100644
--- a/libavcodec/mips/acelp_filters_mips.c
+++ b/libavcodec/mips/acelp_filters_mips.c
@@ -51,9 +51,11 @@
  * @file
  * Reference: libavcodec/acelp_filters.c
  */
+#include "config.h"
 #include "libavutil/attributes.h"
 #include "libavcodec/acelp_filters.h"
 
+#if HAVE_INLINE_ASM
 static void ff_acelp_interpolatef_mips(float *out, const float *in,
                            const float *filter_coeffs, int precision,
                            int frac_pos, int filter_length, int length)
@@ -202,9 +204,12 @@
            "$f12", "$f13", "$f14", "$f15", "$f16"
     );
 }
+#endif /* HAVE_INLINE_ASM */
 
 void ff_acelp_filter_init_mips(ACELPFContext *c)
 {
+#if HAVE_INLINE_ASM
     c->acelp_interpolatef                      = ff_acelp_interpolatef_mips;
     c->acelp_apply_order_2_transfer_function   = ff_acelp_apply_order_2_transfer_function_mips;
+#endif
 }
diff --git a/libavcodec/mips/acelp_vectors_mips.c b/libavcodec/mips/acelp_vectors_mips.c
index 6f9390f..e00b34e 100644
--- a/libavcodec/mips/acelp_vectors_mips.c
+++ b/libavcodec/mips/acelp_vectors_mips.c
@@ -52,8 +52,10 @@
  * @file
  * Reference: libavcodec/acelp_vectors.c
  */
+#include "config.h"
 #include "libavcodec/acelp_vectors.h"
 
+#if HAVE_INLINE_ASM
 static void ff_weighted_vector_sumf_mips(
                   float *out, const float *in_a, const float *in_b,
                   float weight_coeff_a, float weight_coeff_b, int length)
@@ -89,8 +91,11 @@
         : "$f0", "$f1", "$f2", "$f3", "$f4", "$f5"
     );
 }
+#endif /* HAVE_INLINE_ASM */
 
 void ff_acelp_vectors_init_mips(ACELPVContext *c)
 {
+#if HAVE_INLINE_ASM
     c->weighted_vector_sumf = ff_weighted_vector_sumf_mips;
+#endif
 }
diff --git a/libavcodec/mips/amrwbdec_mips.c b/libavcodec/mips/amrwbdec_mips.c
index 4bfbb8c..77fae6c 100644
--- a/libavcodec/mips/amrwbdec_mips.c
+++ b/libavcodec/mips/amrwbdec_mips.c
@@ -53,6 +53,7 @@
 #include "libavcodec/amrwbdata.h"
 #include "amrwbdec_mips.h"
 
+#if HAVE_INLINE_ASM
 void hb_fir_filter_mips(float *out, const float fir_coef[HB_FIR_SIZE + 1],
                           float mem[HB_FIR_SIZE], const float *in)
 {
@@ -183,3 +184,4 @@
     }
     memcpy(mem, data + AMRWB_SFR_SIZE_16k, HB_FIR_SIZE * sizeof(float));
 }
+#endif /* HAVE_INLINE_ASM */
diff --git a/libavcodec/mips/celp_filters_mips.c b/libavcodec/mips/celp_filters_mips.c
index 06e0127..5ecde00 100644
--- a/libavcodec/mips/celp_filters_mips.c
+++ b/libavcodec/mips/celp_filters_mips.c
@@ -51,10 +51,12 @@
  * @file
  * Reference: libavcodec/celp_filters.c
  */
+#include "config.h"
 #include "libavutil/attributes.h"
 #include "libavutil/common.h"
 #include "libavcodec/celp_filters.h"
 
+#if HAVE_INLINE_ASM
 static void ff_celp_lp_synthesis_filterf_mips(float *out,
                                   const float *filter_coeffs,
                                   const float* in, int buffer_length,
@@ -273,9 +275,12 @@
         out[n] = sum_out1;
     }
 }
+#endif /* HAVE_INLINE_ASM */
 
 void ff_celp_filter_init_mips(CELPFContext *c)
 {
+#if HAVE_INLINE_ASM
     c->celp_lp_synthesis_filterf        = ff_celp_lp_synthesis_filterf_mips;
     c->celp_lp_zero_synthesis_filterf   = ff_celp_lp_zero_synthesis_filterf_mips;
+#endif
 }
diff --git a/libavcodec/mips/celp_math_mips.c b/libavcodec/mips/celp_math_mips.c
index 6ab1823..f0335c9 100644
--- a/libavcodec/mips/celp_math_mips.c
+++ b/libavcodec/mips/celp_math_mips.c
@@ -51,8 +51,10 @@
  * @file
  * Reference: libavcodec/celp_math.c
  */
+#include "config.h"
 #include "libavcodec/celp_math.h"
 
+#if HAVE_INLINE_ASM
 static float ff_dot_productf_mips(const float* a, const float* b,
                                               int length)
 {
@@ -77,8 +79,11 @@
     );
     return sum;
 }
+#endif /* HAVE_INLINE_ASM */
 
 void ff_celp_math_init_mips(CELPMContext *c)
 {
+#if HAVE_INLINE_ASM
     c->dot_productf = ff_dot_productf_mips;
+#endif
 }
diff --git a/libavcodec/mips/compute_antialias_fixed.h b/libavcodec/mips/compute_antialias_fixed.h
index 528411f..13684f6 100644
--- a/libavcodec/mips/compute_antialias_fixed.h
+++ b/libavcodec/mips/compute_antialias_fixed.h
@@ -55,6 +55,7 @@
 #ifndef AVCODEC_MIPS_COMPUTE_ANTIALIAS_FIXED_H
 #define AVCODEC_MIPS_COMPUTE_ANTIALIAS_FIXED_H
 
+#if HAVE_INLINE_ASM
 static void compute_antialias_mips_fixed(MPADecodeContext *s,
                                         GranuleDef *g)
 {
@@ -242,5 +243,6 @@
     }
 }
 #define compute_antialias compute_antialias_mips_fixed
+#endif /* HAVE_INLINE_ASM */
 
 #endif /* AVCODEC_MIPS_COMPUTE_ANTIALIAS_FIXED_H */
diff --git a/libavcodec/mips/compute_antialias_float.h b/libavcodec/mips/compute_antialias_float.h
index 3a3f5d6..289150d 100644
--- a/libavcodec/mips/compute_antialias_float.h
+++ b/libavcodec/mips/compute_antialias_float.h
@@ -55,6 +55,7 @@
 #ifndef AVCODEC_MIPS_COMPUTE_ANTIALIAS_FLOAT_H
 #define AVCODEC_MIPS_COMPUTE_ANTIALIAS_FLOAT_H
 
+#if HAVE_INLINE_ASM
 static void compute_antialias_mips_float(MPADecodeContext *s,
                                         GranuleDef *g)
 {
@@ -178,5 +179,6 @@
     );
 }
 #define compute_antialias compute_antialias_mips_float
+#endif /* HAVE_INLINE_ASM */
 
 #endif /* AVCODEC_MIPS_COMPUTE_ANTIALIAS_FLOAT_H */
diff --git a/libavcodec/mips/dsputil_mips.c b/libavcodec/mips/dsputil_mips.c
index e46a0a9..76dc664 100644
--- a/libavcodec/mips/dsputil_mips.c
+++ b/libavcodec/mips/dsputil_mips.c
@@ -47,6 +47,7 @@
 #include "config.h"
 #include "libavcodec/dsputil.h"
 
+#if HAVE_INLINE_ASM
 static void vector_fmul_window_mips(float *dst, const float *src0,
         const float *src1, const float *win, int len)
 {
@@ -157,8 +158,11 @@
         );
     }
 }
+#endif /* HAVE_INLINE_ASM */
 
 av_cold void ff_dsputil_init_mips( DSPContext* c, AVCodecContext *avctx )
 {
+#if HAVE_INLINE_ASM
     c->vector_fmul_window = vector_fmul_window_mips;
+#endif
 }
diff --git a/libavcodec/mips/dsputil_mmi.c b/libavcodec/mips/dsputil_mmi.c
deleted file mode 100644
index a1e1f6b..0000000
--- a/libavcodec/mips/dsputil_mmi.c
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * MMI optimized DSP utils
- * Copyright (c) 2000, 2001 Fabrice Bellard
- *
- * MMI optimization by Leon van Stuivenberg
- * clear_blocks_mmi() by BroadQ
- *
- * 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 "libavcodec/dsputil.h"
-#include "mmi.h"
-
-static void clear_blocks_mmi(DCTELEM * blocks)
-{
-        __asm__ volatile(
-        ".set noreorder    \n"
-        "addiu $9, %0, 768 \n"
-        "nop               \n"
-        "1:                \n"
-        "sq $0, 0(%0)      \n"
-        "move $8, %0       \n"
-        "addi %0, %0, 64   \n"
-        "sq $0, 16($8)     \n"
-        "slt $10, %0, $9   \n"
-        "sq $0, 32($8)     \n"
-        "bnez $10, 1b      \n"
-        "sq $0, 48($8)     \n"
-        ".set reorder      \n"
-        : "+r" (blocks) ::  "$8", "$9", "memory" );
-}
-
-
-static void get_pixels_mmi(DCTELEM *block, const uint8_t *pixels, int line_size)
-{
-        __asm__ volatile(
-        ".set   push            \n\t"
-        ".set   mips3           \n\t"
-        "ld     $8, 0(%0)       \n\t"
-        "add    %0, %0, %2      \n\t"
-        "ld     $9, 0(%0)       \n\t"
-        "add    %0, %0, %2      \n\t"
-        "ld     $10, 0(%0)      \n\t"
-        "pextlb $8, $0, $8      \n\t"
-        "sq     $8, 0(%1)       \n\t"
-        "add    %0, %0, %2      \n\t"
-        "ld     $8, 0(%0)       \n\t"
-        "pextlb $9, $0, $9      \n\t"
-        "sq     $9, 16(%1)      \n\t"
-        "add    %0, %0, %2      \n\t"
-        "ld     $9, 0(%0)       \n\t"
-        "pextlb $10, $0, $10    \n\t"
-        "sq     $10, 32(%1)     \n\t"
-        "add    %0, %0, %2      \n\t"
-        "ld     $10, 0(%0)      \n\t"
-        "pextlb $8, $0, $8      \n\t"
-        "sq     $8, 48(%1)      \n\t"
-        "add    %0, %0, %2      \n\t"
-        "ld     $8, 0(%0)       \n\t"
-        "pextlb $9, $0, $9      \n\t"
-        "sq     $9, 64(%1)      \n\t"
-        "add    %0, %0, %2      \n\t"
-        "ld     $9, 0(%0)       \n\t"
-        "pextlb $10, $0, $10    \n\t"
-        "sq     $10, 80(%1)     \n\t"
-        "pextlb $8, $0, $8      \n\t"
-        "sq     $8, 96(%1)      \n\t"
-        "pextlb $9, $0, $9      \n\t"
-        "sq     $9, 112(%1)     \n\t"
-        ".set   pop             \n\t"
-        : "+r" (pixels) : "r" (block), "r" (line_size) : "$8", "$9", "$10", "memory" );
-}
-
-
-static void put_pixels8_mmi(uint8_t *block, const uint8_t *pixels, int line_size, int h)
-{
-        __asm__ volatile(
-        ".set   push            \n\t"
-        ".set   mips3           \n\t"
-        "1:                     \n\t"
-        "ldr    $8, 0(%1)       \n\t"
-        "addiu  %2, %2, -1      \n\t"
-        "ldl    $8, 7(%1)       \n\t"
-        "add    %1, %1, %3      \n\t"
-        "sd     $8, 0(%0)       \n\t"
-        "add    %0, %0, %3      \n\t"
-        "bgtz   %2, 1b          \n\t"
-        ".set   pop             \n\t"
-        : "+r" (block), "+r" (pixels), "+r" (h) : "r" (line_size)
-        : "$8", "memory" );
-}
-
-
-static void put_pixels16_mmi(uint8_t *block, const uint8_t *pixels, int line_size, int h)
-{
-        __asm__ volatile (
-        ".set   push            \n\t"
-        ".set   mips3           \n\t"
-        "1:                     \n\t"
-        "ldr    $8, 0(%1)       \n\t"
-        "add    $11, %1, %3     \n\t"
-        "ldl    $8, 7(%1)       \n\t"
-        "add    $10, %0, %3     \n\t"
-        "ldr    $9, 8(%1)       \n\t"
-        "ldl    $9, 15(%1)      \n\t"
-        "ldr    $12, 0($11)     \n\t"
-        "add    %1, $11, %3     \n\t"
-        "ldl    $12, 7($11)     \n\t"
-        "pcpyld $8, $9, $8      \n\t"
-        "sq     $8, 0(%0)       \n\t"
-        "ldr    $13, 8($11)     \n\t"
-        "addiu  %2, %2, -2      \n\t"
-        "ldl    $13, 15($11)    \n\t"
-        "add    %0, $10, %3     \n\t"
-        "pcpyld $12, $13, $12   \n\t"
-        "sq     $12, 0($10)     \n\t"
-        "bgtz   %2, 1b          \n\t"
-        ".set   pop             \n\t"
-        : "+r" (block), "+r" (pixels), "+r" (h) : "r" (line_size)
-        : "$8", "$9", "$10", "$11", "$12", "$13", "memory" );
-}
-
-
-void ff_dsputil_init_mmi(DSPContext* c, AVCodecContext *avctx)
-{
-    const int idct_algo= avctx->idct_algo;
-    const int high_bit_depth = avctx->bits_per_raw_sample > 8;
-
-    if (!high_bit_depth) {
-    c->clear_blocks = clear_blocks_mmi;
-
-    c->put_pixels_tab[1][0] = put_pixels8_mmi;
-    c->put_no_rnd_pixels_tab[1][0] = put_pixels8_mmi;
-
-    c->put_pixels_tab[0][0] = put_pixels16_mmi;
-    c->put_no_rnd_pixels_tab[0][0] = put_pixels16_mmi;
-
-    c->get_pixels = get_pixels_mmi;
-    }
-
-    if (avctx->bits_per_raw_sample <= 8 &&
-        (idct_algo == FF_IDCT_AUTO || idct_algo == FF_IDCT_MMI)) {
-        c->idct_put= ff_mmi_idct_put;
-        c->idct_add= ff_mmi_idct_add;
-        c->idct    = ff_mmi_idct;
-        c->idct_permutation_type= FF_LIBMPEG2_IDCT_PERM;
-    }
-}
diff --git a/libavcodec/mips/fft_mips.c b/libavcodec/mips/fft_mips.c
index 2b1c508..8a2d86e 100644
--- a/libavcodec/mips/fft_mips.c
+++ b/libavcodec/mips/fft_mips.c
@@ -485,7 +485,6 @@
         z2[1].im = temp12;
     }
 }
-#endif /* HAVE_INLINE_ASM */
 
 /**
  * Compute inverse MDCT of size N = 2^nbits
@@ -513,6 +512,7 @@
         output[n-k-4] = output[n2+k+3];
     }
 }
+#endif /* HAVE_INLINE_ASM */
 
 av_cold void ff_fft_init_mips(FFTContext *s)
 {
@@ -522,9 +522,9 @@
 
 #if HAVE_INLINE_ASM
     s->fft_calc     = ff_fft_calc_mips;
-#endif
 #if CONFIG_MDCT
     s->imdct_calc   = ff_imdct_calc_mips;
     s->imdct_half   = ff_imdct_half_mips;
 #endif
+#endif
 }
diff --git a/libavcodec/mips/fmtconvert_mips.c b/libavcodec/mips/fmtconvert_mips.c
index f89d3b6..8a0265f 100644
--- a/libavcodec/mips/fmtconvert_mips.c
+++ b/libavcodec/mips/fmtconvert_mips.c
@@ -51,6 +51,7 @@
 #include "libavcodec/avcodec.h"
 #include "libavcodec/fmtconvert.h"
 
+#if HAVE_INLINE_ASM
 #if HAVE_MIPSDSPR1
 static void float_to_int16_mips(int16_t *dst, const float *src, long len)
 {
@@ -327,12 +328,15 @@
         : "memory"
     );
 }
+#endif /* HAVE_INLINE_ASM */
 
 av_cold void ff_fmt_convert_init_mips(FmtConvertContext *c)
 {
+#if HAVE_INLINE_ASM
 #if HAVE_MIPSDSPR1
     c->float_to_int16_interleave = float_to_int16_interleave_mips;
     c->float_to_int16 = float_to_int16_mips;
 #endif
     c->int32_to_float_fmul_scalar = int32_to_float_fmul_scalar_mips;
+#endif
 }
diff --git a/libavcodec/mips/idct_mmi.c b/libavcodec/mips/idct_mmi.c
deleted file mode 100644
index 5a3af17..0000000
--- a/libavcodec/mips/idct_mmi.c
+++ /dev/null
@@ -1,361 +0,0 @@
-/*
- * Originally provided by Intel at Application Note AP-922.
- *
- * Column code adapted from Peter Gubanov.
- * Copyright (c) 2000-2001 Peter Gubanov <peter@elecard.net.ru>
- * http://www.elecard.com/peter/idct.shtml
- * rounding trick copyright (c) 2000 Michel Lespinasse <walken@zoy.org>
- *
- * MMI port and (c) 2002 by Leon van Stuivenberg
- *
- * 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 "libavcodec/dsputil.h"
-#include "mmi.h"
-
-#define BITS_INV_ACC    5       // 4 or 5 for IEEE
-#define SHIFT_INV_ROW   (16 - BITS_INV_ACC)
-#define SHIFT_INV_COL   (1 + BITS_INV_ACC)
-
-#define TG1             6518
-#define TG2             13573
-#define TG3             21895
-#define CS4             23170
-
-#define ROUNDER_0       0
-#define ROUNDER_1       16
-
-#define TAB_i_04        (32+0)
-#define TAB_i_17        (32+64)
-#define TAB_i_26        (32+128)
-#define TAB_i_35        (32+192)
-
-#define TG_1_16         (32+256+0)
-#define TG_2_16         (32+256+16)
-#define TG_3_16         (32+256+32)
-#define COS_4_16        (32+256+48)
-
-#define CLIPMAX         (32+256+64+0)
-
-static short consttable[] align16 = {
-/* rounder 0*/  // assume SHIFT_INV_ROW == 11
- 0x3ff, 1, 0x3ff, 1, 0x3ff, 1, 0x3ff, 1,
-/* rounder 1*/
- 0x3ff, 0, 0x3ff, 0, 0x3ff, 0, 0x3ff, 0,
-/* row 0/4*/
- 16384,  21407, -16384, -21407,  22725,  19266, -22725, -12873,
-  8867,  16384,   8867,  16384,   4520,  12873,  -4520,  19266,
- 16384,  -8867,  16384,  -8867,  12873, -22725,  19266, -22725,
- 21407, -16384, -21407,  16384,  19266,   4520, -12873,   4520,
-/* row 1/7*/
- 22725,  29692, -22725, -29692,  31521,  26722, -31521, -17855,
- 12299,  22725,  12299,  22725,   6270,  17855,  -6270,  26722,
- 22725, -12299,  22725, -12299,  17855, -31521,  26722, -31521,
- 29692, -22725, -29692,  22725,  26722,   6270, -17855,   6270,
-/* row 2/6*/
- 21407,  27969, -21407, -27969,  29692,  25172, -29692, -16819,
- 11585,  21407,  11585,  21407,   5906,  16819,  -5906,  25172,
- 21407, -11585,  21407, -11585,  16819, -29692,  25172, -29692,
- 27969, -21407, -27969,  21407,  25172,   5906, -16819,   5906,
-/*row 3/5*/
- 19266,  25172, -19266, -25172,  26722,  22654, -26722, -15137,
- 10426,  19266,  10426,  19266,   5315,  15137,  -5315,  22654,
- 19266, -10426,  19266, -10426,  15137, -26722,  22654, -26722,
- 25172, -19266, -25172,  19266,  22654,   5315, -15137,   5315,
-/*column constants*/
- TG1, TG1, TG1, TG1, TG1, TG1, TG1, TG1,
- TG2, TG2, TG2, TG2, TG2, TG2, TG2, TG2,
- TG3, TG3, TG3, TG3, TG3, TG3, TG3, TG3,
- CS4, CS4, CS4, CS4, CS4, CS4, CS4, CS4,
-/* clamp */
- 255, 255, 255, 255, 255, 255, 255, 255
-};
-
-
-#define DCT_8_INV_ROW1(blk, rowoff, taboff, rnd, outreg) { \
-        lq(blk, rowoff, $16);   /* r16 = x7  x5  x3  x1  x6  x4  x2  x0 */ \
-        /*slot*/ \
-        lq($24, 0+taboff, $17); /* r17 = w */ \
-        /*delay slot $16*/ \
-        lq($24, 16+taboff, $18);/* r18 = w */ \
-        prevh($16, $2);         /* r2  = x1  x3  x5  x7  x0  x2  x4  x6 */ \
-        lq($24, 32+taboff, $19);/* r19 = w */ \
-        phmadh($17, $16, $17);  /* r17 = b1"b0'a1"a0' */ \
-        lq($24, 48+taboff, $20);/* r20 = w */ \
-        phmadh($18, $2, $18);   /* r18 = b1'b0"a1'a0" */ \
-        phmadh($19, $16, $19);  /* r19 = b3"b2'a3"a2' */ \
-        phmadh($20, $2, $20);   /* r20 = b3'b2"a3'a2" */ \
-        paddw($17, $18, $17);   /* r17 = (b1)(b0)(a1)(a0) */ \
-        paddw($19, $20, $19);   /* r19 = (b3)(b2)(a3)(a2) */ \
-        pcpyld($19, $17, $18);  /* r18 = (a3)(a2)(a1)(a0) */ \
-        pcpyud($17, $19, $20);  /* r20 = (b3)(b2)(b1)(b0) */ \
-        paddw($18, rnd, $18);   /* r18 = (a3)(a2)(a1)(a0) */\
-        paddw($18, $20, $17);   /* r17 = ()()()(a0+b0) */ \
-        psubw($18, $20, $20);   /* r20 = ()()()(a0-b0) */ \
-        psraw($17, SHIFT_INV_ROW, $17); /* r17 = (y3 y2 y1 y0) */ \
-        psraw($20, SHIFT_INV_ROW, $20); /* r20 = (y4 y5 y6 y7) */ \
-        ppach($20, $17, outreg);/* out = y4 y5 y6 y7 y3 y2 y1 y0  Note order */ \
-\
-        prevh(outreg, $2);        \
-        pcpyud($2, $2, $2);        \
-        pcpyld($2, outreg, outreg);        \
-}
-
-
-#define DCT_8_INV_COL8() \
-\
-        lq($24, TG_3_16, $2);   /* r2  = tn3 */         \
-\
-        pmulth($11, $2, $17);   /* r17 = x3 * tn3 (6420) */ \
-        psraw($17, 15, $17);    \
-        pmfhl_uw($3);           /* r3  = 7531 */        \
-        psraw($3, 15, $3);      \
-        pinteh($3, $17, $17);   /* r17 = x3 * tn3 */    \
-        psubh($17, $13, $17);   /* r17 = tm35 */        \
-\
-        pmulth($13, $2, $18);   /* r18 = x5 * tn3 (6420) */ \
-        psraw($18, 15, $18);    \
-        pmfhl_uw($3);           /* r3  = 7531 */        \
-        psraw($3, 15, $3);      \
-        pinteh($3, $18, $18);   /* r18 = x5 * tn3 */    \
-        paddh($18, $11, $18);   /* r18 = tp35 */        \
-\
-        lq($24, TG_1_16, $2);   /* r2  = tn1 */         \
-\
-        pmulth($15, $2, $19);   /* r19 = x7 * tn1 (6420) */ \
-        psraw($19, 15, $19);    \
-        pmfhl_uw($3);           /* r3  = 7531 */        \
-        psraw($3, 15, $3);      \
-        pinteh($3, $19, $19);   /* r19 = x7 * tn1 */    \
-        paddh($19, $9, $19);    /* r19 = tp17 */        \
-\
-        pmulth($9, $2, $20);    /* r20 = x1 * tn1 (6420) */ \
-        psraw($20, 15, $20);    \
-        pmfhl_uw($3);           /* r3  = 7531 */        \
-        psraw($3, 15, $3);      \
-        pinteh($3, $20, $20);   /* r20 = x1 * tn1 */    \
-        psubh($20, $15, $20);   /* r20 = tm17 */        \
-\
-        psubh($19, $18, $3);    /* r3  = t1 */          \
-        paddh($20, $17, $16);   /* r16 = t2 */          \
-        psubh($20, $17, $23);   /* r23 = b3 */          \
-        paddh($19, $18, $20);   /* r20 = b0 */          \
-\
-        lq($24, COS_4_16, $2);  /* r2  = cs4 */         \
-\
-        paddh($3, $16, $21);    /* r21 = t1+t2 */       \
-        psubh($3, $16, $22);    /* r22 = t1-t2 */       \
-\
-        pmulth($21, $2, $21);   /* r21 = cs4 * (t1+t2) 6420 */ \
-        psraw($21, 15, $21);    \
-        pmfhl_uw($3);           /* r3  = 7531 */        \
-        psraw($3, 15, $3);      \
-        pinteh($3, $21, $21);   /* r21 = b1 */          \
-\
-        pmulth($22, $2, $22);   /* r22 = cs4 * (t1-t2) 6420 */ \
-        psraw($22, 15, $22);    \
-        pmfhl_uw($3);           /* r3  = 7531 */        \
-        psraw($3, 15, $3);      \
-        pinteh($3, $22, $22);   /* r22 = b2 */          \
-\
-        lq($24, TG_2_16, $2);   /* r2  = tn2 */         \
-\
-        pmulth($10, $2, $17);   /* r17 = x2 * tn2 (6420) */ \
-        psraw($17, 15, $17);    \
-        pmfhl_uw($3);           /* r3  = 7531 */        \
-        psraw($3, 15, $3);      \
-        pinteh($3, $17, $17);   /* r17 = x3 * tn3 */    \
-        psubh($17, $14, $17);   /* r17 = tm26 */        \
-\
-        pmulth($14, $2, $18);   /* r18 = x6 * tn2 (6420) */ \
-        psraw($18, 15, $18);    \
-        pmfhl_uw($3);           /* r3  = 7531 */        \
-        psraw($3, 15, $3);      \
-        pinteh($3, $18, $18);   /* r18 = x6 * tn2 */    \
-        paddh($18, $10, $18);   /* r18 = tp26 */        \
-\
-        paddh($8, $12, $2);     /* r2  = tp04 */        \
-        psubh($8, $12, $3);     /* r3  = tm04 */        \
-\
-        paddh($2, $18, $16);    /* r16 = a0 */          \
-        psubh($2, $18, $19);    /* r19 = a3 */          \
-        psubh($3, $17, $18);    /* r18 = a2 */          \
-        paddh($3, $17, $17);    /* r17 = a1 */
-
-
-#define DCT_8_INV_COL8_STORE(blk) \
-\
-        paddh($16, $20, $2);    /* y0  a0+b0 */ \
-        psubh($16, $20, $16);   /* y7  a0-b0 */ \
-        psrah($2, SHIFT_INV_COL, $2);           \
-        psrah($16, SHIFT_INV_COL, $16);         \
-        sq($2, 0, blk);                         \
-        sq($16, 112, blk);                      \
-\
-        paddh($17, $21, $3);    /* y1  a1+b1 */ \
-        psubh($17, $21, $17);   /* y6  a1-b1 */ \
-        psrah($3, SHIFT_INV_COL, $3);           \
-        psrah($17, SHIFT_INV_COL, $17);         \
-        sq($3, 16, blk);                        \
-        sq($17, 96, blk);                       \
-\
-        paddh($18, $22, $2);    /* y2  a2+b2 */ \
-        psubh($18, $22, $18);   /* y5  a2-b2 */ \
-        psrah($2, SHIFT_INV_COL, $2);           \
-        psrah($18, SHIFT_INV_COL, $18);         \
-        sq($2, 32, blk);                        \
-        sq($18, 80, blk);                       \
-\
-        paddh($19, $23, $3);    /* y3  a3+b3 */ \
-        psubh($19, $23, $19);   /* y4  a3-b3 */ \
-        psrah($3, SHIFT_INV_COL, $3);           \
-        psrah($19, SHIFT_INV_COL, $19);         \
-        sq($3, 48, blk);                        \
-        sq($19, 64, blk);
-
-
-
-#define DCT_8_INV_COL8_PMS() \
-        paddh($16, $20, $2);    /* y0  a0+b0 */ \
-        psubh($16, $20, $20);   /* y7  a0-b0 */ \
-        psrah($2, SHIFT_INV_COL, $16);          \
-        psrah($20, SHIFT_INV_COL, $20);         \
-\
-        paddh($17, $21, $3);    /* y1  a1+b1 */ \
-        psubh($17, $21, $21);   /* y6  a1-b1 */ \
-        psrah($3, SHIFT_INV_COL, $17);          \
-        psrah($21, SHIFT_INV_COL, $21);         \
-\
-        paddh($18, $22, $2);    /* y2  a2+b2 */ \
-        psubh($18, $22, $22);   /* y5  a2-b2 */ \
-        psrah($2, SHIFT_INV_COL, $18);          \
-        psrah($22, SHIFT_INV_COL, $22);         \
-\
-        paddh($19, $23, $3);    /* y3  a3+b3 */ \
-        psubh($19, $23, $23);   /* y4  a3-b3 */ \
-        psrah($3, SHIFT_INV_COL, $19);          \
-        psrah($23, SHIFT_INV_COL, $23);
-
-#define PUT(rs)                 \
-        pminh(rs, $11, $2);     \
-        pmaxh($2, $0, $2);      \
-        ppacb($0, $2, $2);      \
-        sd3(2, 0, 4);           \
-        __asm__ volatile ("add $4, $5, $4");
-
-#define DCT_8_INV_COL8_PUT() \
-        PUT($16);        \
-        PUT($17);        \
-        PUT($18);        \
-        PUT($19);        \
-        PUT($23);        \
-        PUT($22);        \
-        PUT($21);        \
-        PUT($20);
-
-#define ADD(rs)          \
-        ld3(4, 0, 2);        \
-        pextlb($0, $2, $2);  \
-        paddh($2, rs, $2);   \
-        pminh($2, $11, $2);  \
-        pmaxh($2, $0, $2);   \
-        ppacb($0, $2, $2);   \
-        sd3(2, 0, 4); \
-        __asm__ volatile ("add $4, $5, $4");
-
-/*fixme: schedule*/
-#define DCT_8_INV_COL8_ADD() \
-        ADD($16);        \
-        ADD($17);        \
-        ADD($18);        \
-        ADD($19);        \
-        ADD($23);        \
-        ADD($22);        \
-        ADD($21);        \
-        ADD($20);
-
-
-void ff_mmi_idct(int16_t * block)
-{
-        /* $4 = block */
-        __asm__ volatile("la $24, %0"::"m"(consttable[0]));
-        lq($24, ROUNDER_0, $8);
-        lq($24, ROUNDER_1, $7);
-        DCT_8_INV_ROW1($4, 0, TAB_i_04, $8, $8);
-        DCT_8_INV_ROW1($4, 16, TAB_i_17, $7, $9);
-        DCT_8_INV_ROW1($4, 32, TAB_i_26, $7, $10);
-        DCT_8_INV_ROW1($4, 48, TAB_i_35, $7, $11);
-        DCT_8_INV_ROW1($4, 64, TAB_i_04, $7, $12);
-        DCT_8_INV_ROW1($4, 80, TAB_i_35, $7, $13);
-        DCT_8_INV_ROW1($4, 96, TAB_i_26, $7, $14);
-        DCT_8_INV_ROW1($4, 112, TAB_i_17, $7, $15);
-        DCT_8_INV_COL8();
-        DCT_8_INV_COL8_STORE($4);
-
-        //let savedtemp regs be saved
-        __asm__ volatile(" ":::"$16", "$17", "$18", "$19", "$20", "$21", "$22", "$23");
-}
-
-
-void ff_mmi_idct_put(uint8_t *dest, int line_size, DCTELEM *block)
-{
-        /* $4 = dest, $5 = line_size, $6 = block */
-        __asm__ volatile("la $24, %0"::"m"(consttable[0]));
-        lq($24, ROUNDER_0, $8);
-        lq($24, ROUNDER_1, $7);
-        DCT_8_INV_ROW1($6, 0, TAB_i_04, $8, $8);
-        DCT_8_INV_ROW1($6, 16, TAB_i_17, $7, $9);
-        DCT_8_INV_ROW1($6, 32, TAB_i_26, $7, $10);
-        DCT_8_INV_ROW1($6, 48, TAB_i_35, $7, $11);
-        DCT_8_INV_ROW1($6, 64, TAB_i_04, $7, $12);
-        DCT_8_INV_ROW1($6, 80, TAB_i_35, $7, $13);
-        DCT_8_INV_ROW1($6, 96, TAB_i_26, $7, $14);
-        DCT_8_INV_ROW1($6, 112, TAB_i_17, $7, $15);
-        DCT_8_INV_COL8();
-        lq($24, CLIPMAX, $11);
-        DCT_8_INV_COL8_PMS();
-        DCT_8_INV_COL8_PUT();
-
-        //let savedtemp regs be saved
-        __asm__ volatile(" ":::"$16", "$17", "$18", "$19", "$20", "$21", "$22", "$23");
-}
-
-
-void ff_mmi_idct_add(uint8_t *dest, int line_size, DCTELEM *block)
-{
-        /* $4 = dest, $5 = line_size, $6 = block */
-        __asm__ volatile("la $24, %0"::"m"(consttable[0]));
-        lq($24, ROUNDER_0, $8);
-        lq($24, ROUNDER_1, $7);
-        DCT_8_INV_ROW1($6, 0, TAB_i_04, $8, $8);
-        DCT_8_INV_ROW1($6, 16, TAB_i_17, $7, $9);
-        DCT_8_INV_ROW1($6, 32, TAB_i_26, $7, $10);
-        DCT_8_INV_ROW1($6, 48, TAB_i_35, $7, $11);
-        DCT_8_INV_ROW1($6, 64, TAB_i_04, $7, $12);
-        DCT_8_INV_ROW1($6, 80, TAB_i_35, $7, $13);
-        DCT_8_INV_ROW1($6, 96, TAB_i_26, $7, $14);
-        DCT_8_INV_ROW1($6, 112, TAB_i_17, $7, $15);
-        DCT_8_INV_COL8();
-        lq($24, CLIPMAX, $11);
-        DCT_8_INV_COL8_PMS();
-        DCT_8_INV_COL8_ADD();
-
-        //let savedtemp regs be saved
-        __asm__ volatile(" ":::"$16", "$17", "$18", "$19", "$20", "$21", "$22", "$23");
-}
diff --git a/libavcodec/mips/mathops.h b/libavcodec/mips/mathops.h
index b58361f..368290a 100644
--- a/libavcodec/mips/mathops.h
+++ b/libavcodec/mips/mathops.h
@@ -57,7 +57,8 @@
     __asm__ ("dmult %2, %3     \n\t"
              "mflo  %1         \n\t"
              "daddu %0, %0, %1 \n\t"
-             : "+r"(d), "=&r"(m) : "r"(a), "r"(b));
+             : "+r"(d), "=&r"(m) : "r"(a), "r"(b)
+             : "hi", "lo");
     return d;
 }
 #define MAC64(d, a, b) ((d) = MAC64(d, a, b))
@@ -68,7 +69,8 @@
     __asm__ ("dmult %2, %3     \n\t"
              "mflo  %1         \n\t"
              "dsubu %0, %0, %1 \n\t"
-             : "+r"(d), "=&r"(m) : "r"(a), "r"(b));
+             : "+r"(d), "=&r"(m) : "r"(a), "r"(b)
+             : "hi", "lo");
     return d;
 }
 #define MLS64(d, a, b) ((d) = MLS64(d, a, b))
diff --git a/libavcodec/mips/mmi.h b/libavcodec/mips/mmi.h
deleted file mode 100644
index 5ff0033..0000000
--- a/libavcodec/mips/mmi.h
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * copyright (c) 2002 Leon van Stuivenberg
- *
- * 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_MIPS_MMI_H
-#define AVCODEC_MIPS_MMI_H
-
-#include <stdint.h>
-
-#include "libavcodec/dsputil.h"
-
-void ff_mmi_idct_put(uint8_t *dest, int line_size, DCTELEM *block);
-void ff_mmi_idct_add(uint8_t *dest, int line_size, DCTELEM *block);
-void ff_mmi_idct(DCTELEM *block);
-
-#define align16 __attribute__ ((aligned (16)))
-
-/*
-#define r0 $zero
-#define r1 $at          //assembler!
-#define r2 $v0          //return
-#define r3 $v1          //return
-#define r4 $a0          //arg
-#define r5 $a1          //arg
-#define r6 $a2          //arg
-#define r7 $a3          //arg
-#define r8 $t0          //temp
-#define r9 $t1          //temp
-#define r10 $t2         //temp
-#define r11 $t3         //temp
-#define r12 $t4         //temp
-#define r13 $t5         //temp
-#define r14 $t6         //temp
-#define r15 $t7         //temp
-#define r16 $s0         //saved temp
-#define r17 $s1         //saved temp
-#define r18 $s2         //saved temp
-#define r19 $s3         //saved temp
-#define r20 $s4         //saved temp
-#define r21 $s5         //saved temp
-#define r22 $s6         //saved temp
-#define r23 $s7         //saved temp
-#define r24 $t8         //temp
-#define r25 $t9         //temp
-#define r26 $k0         //kernel
-#define r27 $k1         //kernel
-#define r28 $gp         //global ptr
-#define r29 $sp         //stack ptr
-#define r30 $fp         //frame ptr
-#define r31 $ra         //return addr
-*/
-
-
-#define         lq(base, off, reg)        \
-        __asm__ volatile ("lq " #reg ", %0("#base ")" : : "i" (off) )
-
-#define         lq2(mem, reg)        \
-        __asm__ volatile ("lq " #reg ", %0" : : "r" (mem))
-
-#define         sq(reg, off, base)        \
-        __asm__ volatile ("sq " #reg ", %0("#base ")" : : "i" (off) )
-
-/*
-#define         ld(base, off, reg)        \
-        __asm__ volatile ("ld " #reg ", " #off "("#base ")")
-*/
-
-#define         ld3(base, off, reg)        \
-        __asm__ volatile (".word %0" : : "i" ( 0xdc000000 | (base<<21) | (reg<<16) | (off)))
-
-#define         ldr3(base, off, reg)        \
-        __asm__ volatile (".word %0" : : "i" ( 0x6c000000 | (base<<21) | (reg<<16) | (off)))
-
-#define         ldl3(base, off, reg)        \
-        __asm__ volatile (".word %0" : : "i" ( 0x68000000 | (base<<21) | (reg<<16) | (off)))
-
-/*
-#define         sd(reg, off, base)        \
-        __asm__ volatile ("sd " #reg ", " #off "("#base ")")
-*/
-//seems assembler has bug encoding mnemonic 'sd', so DIY
-#define         sd3(reg, off, base)        \
-        __asm__ volatile (".word %0" : : "i" ( 0xfc000000 | (base<<21) | (reg<<16) | (off)))
-
-#define         sw(reg, off, base)        \
-        __asm__ volatile ("sw " #reg ", " #off "("#base ")")
-
-#define         sq2(reg, mem)        \
-        __asm__ volatile ("sq " #reg ", %0" : : "m" (*(mem)))
-
-#define         pinth(rs, rt, rd) \
-        __asm__ volatile ("pinth  " #rd ", " #rs ", " #rt )
-
-#define         phmadh(rs, rt, rd) \
-        __asm__ volatile ("phmadh " #rd ", " #rs ", " #rt )
-
-#define         pcpyud(rs, rt, rd) \
-        __asm__ volatile ("pcpyud " #rd ", " #rs ", " #rt )
-
-#define         pcpyld(rs, rt, rd) \
-        __asm__ volatile ("pcpyld " #rd ", " #rs ", " #rt )
-
-#define         pcpyh(rt, rd) \
-        __asm__ volatile ("pcpyh  " #rd ", " #rt )
-
-#define         paddw(rs, rt, rd) \
-        __asm__ volatile ("paddw  " #rd ", " #rs ", " #rt )
-
-#define         pextlw(rs, rt, rd) \
-        __asm__ volatile ("pextlw " #rd ", " #rs ", " #rt )
-
-#define         pextuw(rs, rt, rd) \
-        __asm__ volatile ("pextuw " #rd ", " #rs ", " #rt )
-
-#define         pextlh(rs, rt, rd) \
-        __asm__ volatile ("pextlh " #rd ", " #rs ", " #rt )
-
-#define         pextuh(rs, rt, rd) \
-        __asm__ volatile ("pextuh " #rd ", " #rs ", " #rt )
-
-#define         psubw(rs, rt, rd) \
-        __asm__ volatile ("psubw  " #rd ", " #rs ", " #rt )
-
-#define         psraw(rt, sa, rd) \
-        __asm__ volatile ("psraw  " #rd ", " #rt ", %0" : : "i"(sa) )
-
-#define         ppach(rs, rt, rd) \
-        __asm__ volatile ("ppach  " #rd ", " #rs ", " #rt )
-
-#define         ppacb(rs, rt, rd) \
-        __asm__ volatile ("ppacb  " #rd ", " #rs ", " #rt )
-
-#define         prevh(rt, rd) \
-        __asm__ volatile ("prevh  " #rd ", " #rt )
-
-#define         pmulth(rs, rt, rd) \
-        __asm__ volatile ("pmulth " #rd ", " #rs ", " #rt )
-
-#define         pmaxh(rs, rt, rd) \
-        __asm__ volatile ("pmaxh " #rd ", " #rs ", " #rt )
-
-#define         pminh(rs, rt, rd) \
-        __asm__ volatile ("pminh " #rd ", " #rs ", " #rt )
-
-#define         pinteh(rs, rt, rd) \
-        __asm__ volatile ("pinteh  " #rd ", " #rs ", " #rt )
-
-#define         paddh(rs, rt, rd) \
-        __asm__ volatile ("paddh  " #rd ", " #rs ", " #rt )
-
-#define         psubh(rs, rt, rd) \
-        __asm__ volatile ("psubh  " #rd ", " #rs ", " #rt )
-
-#define         psrah(rt, sa, rd) \
-        __asm__ volatile ("psrah  " #rd ", " #rt ", %0" : : "i"(sa) )
-
-#define         pmfhl_uw(rd) \
-        __asm__ volatile ("pmfhl.uw  " #rd)
-
-#define         pextlb(rs, rt, rd) \
-        __asm__ volatile ("pextlb  " #rd ", " #rs ", " #rt )
-
-#endif /* AVCODEC_MIPS_MMI_H */
diff --git a/libavcodec/mips/mpegvideo_mmi.c b/libavcodec/mips/mpegvideo_mmi.c
deleted file mode 100644
index 2870892..0000000
--- a/libavcodec/mips/mpegvideo_mmi.c
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (c) 2000,2001 Fabrice Bellard
- *
- * MMI optimization by Leon van Stuivenberg
- *
- * 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 "libavcodec/avcodec.h"
-#include "libavcodec/dsputil.h"
-#include "libavcodec/mpegvideo.h"
-
-static void dct_unquantize_h263_mmi(MpegEncContext *s,
-                                  DCTELEM *block, int n, int qscale)
-{
-    int level=0, qmul, qadd;
-    int nCoeffs;
-
-    assert(s->block_last_index[n]>=0);
-
-    qadd = (qscale - 1) | 1;
-    qmul = qscale << 1;
-
-    if (s->mb_intra) {
-        if (!s->h263_aic) {
-            if (n < 4)
-                level = block[0] * s->y_dc_scale;
-            else
-                level = block[0] * s->c_dc_scale;
-        }else {
-            qadd = 0;
-            level = block[0];
-        }
-        nCoeffs= 63; //does not always use zigzag table
-    } else {
-        nCoeffs= s->intra_scantable.raster_end[ s->block_last_index[n] ];
-    }
-
-    __asm__ volatile(
-        "add    $14, $0, %3     \n\t"
-        "pcpyld $8, %0, %0      \n\t"
-        "pcpyh  $8, $8          \n\t"   //r8 = qmul
-        "pcpyld $9, %1, %1      \n\t"
-        "pcpyh  $9, $9          \n\t"   //r9 = qadd
-        ".p2align 2             \n\t"
-        "1:                     \n\t"
-        "lq     $10, 0($14)     \n\t"   //r10 = level
-        "addi   $14, $14, 16    \n\t"   //block+=8
-        "addi   %2, %2, -8      \n\t"
-        "pcgth  $11, $0, $10    \n\t"   //r11 = level < 0 ? -1 : 0
-        "pcgth  $12, $10, $0    \n\t"   //r12 = level > 0 ? -1 : 0
-        "por    $12, $11, $12   \n\t"
-        "pmulth $10, $10, $8    \n\t"
-        "paddh  $13, $9, $11    \n\t"
-        "pxor   $13, $13, $11   \n\t"   //r13 = level < 0 ? -qadd : qadd
-        "pmfhl.uw $11           \n\t"
-        "pinteh $10, $11, $10   \n\t"   //r10 = level * qmul
-        "paddh  $10, $10, $13   \n\t"
-        "pand   $10, $10, $12   \n\t"
-        "sq     $10, -16($14)   \n\t"
-        "bgez   %2, 1b          \n\t"
-        :: "r"(qmul), "r" (qadd), "r" (nCoeffs), "r" (block) : "$8", "$9", "$10", "$11", "$12", "$13", "$14", "memory" );
-
-    if(s->mb_intra)
-        block[0]= level;
-}
-
-
-void ff_MPV_common_init_mmi(MpegEncContext *s)
-{
-    s->dct_unquantize_h263_intra =
-    s->dct_unquantize_h263_inter = dct_unquantize_h263_mmi;
-}
diff --git a/libavcodec/mjpeg.h b/libavcodec/mjpeg.h
index d9cff5b..96e1854 100644
--- a/libavcodec/mjpeg.h
+++ b/libavcodec/mjpeg.h
@@ -35,7 +35,7 @@
 
 #include "avcodec.h"
 #include "put_bits.h"
-#include "symbols.h"
+
 
 /* JPEG marker codes */
 typedef enum {
@@ -138,16 +138,16 @@
         case 7: ret= (left + top)>>1; break;\
     }
 
-extern AVCODEC_SYMBOL const uint8_t avpriv_mjpeg_bits_dc_luminance[];
-extern AVCODEC_SYMBOL const uint8_t avpriv_mjpeg_val_dc[];
+extern av_export const uint8_t avpriv_mjpeg_bits_dc_luminance[];
+extern av_export const uint8_t avpriv_mjpeg_val_dc[];
 
-extern AVCODEC_SYMBOL const uint8_t avpriv_mjpeg_bits_dc_chrominance[];
+extern av_export const uint8_t avpriv_mjpeg_bits_dc_chrominance[];
 
-extern AVCODEC_SYMBOL const uint8_t avpriv_mjpeg_bits_ac_luminance[];
-extern AVCODEC_SYMBOL const uint8_t avpriv_mjpeg_val_ac_luminance[];
+extern av_export const uint8_t avpriv_mjpeg_bits_ac_luminance[];
+extern av_export const uint8_t avpriv_mjpeg_val_ac_luminance[];
 
-extern AVCODEC_SYMBOL const uint8_t avpriv_mjpeg_bits_ac_chrominance[];
-extern AVCODEC_SYMBOL const uint8_t avpriv_mjpeg_val_ac_chrominance[];
+extern av_export const uint8_t avpriv_mjpeg_bits_ac_chrominance[];
+extern av_export const uint8_t avpriv_mjpeg_val_ac_chrominance[];
 
 void ff_mjpeg_build_huffman_codes(uint8_t *huff_size, uint16_t *huff_code,
                                   const uint8_t *bits_table,
diff --git a/libavcodec/mjpegbdec.c b/libavcodec/mjpegbdec.c
index 77f23f2..796ef84 100644
--- a/libavcodec/mjpegbdec.c
+++ b/libavcodec/mjpegbdec.c
@@ -136,6 +136,11 @@
 
     //XXX FIXME factorize, this looks very similar to the EOI code
 
+    if(!s->got_picture) {
+        av_log(avctx, AV_LOG_WARNING, "no picture\n");
+        return buf_size;
+    }
+
     *picture= *s->picture_ptr;
     *data_size = sizeof(AVFrame);
 
diff --git a/libavcodec/mjpegdec.c b/libavcodec/mjpegdec.c
index 677dfb2..c47093b 100644
--- a/libavcodec/mjpegdec.c
+++ b/libavcodec/mjpegdec.c
@@ -94,6 +94,7 @@
     s->buffer        = NULL;
     s->start_code    = -1;
     s->first_picture = 1;
+    s->got_picture   = 0;
     s->org_height    = avctx->coded_height;
     avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
 
@@ -210,6 +211,8 @@
 int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
 {
     int len, nb_components, i, width, height, pix_fmt_id;
+    int h_count[MAX_COMPONENTS];
+    int v_count[MAX_COMPONENTS];
 
     s->cur_scan = 0;
     s->upscale_h = s->upscale_v = 0;
@@ -256,38 +259,41 @@
     }
     if (s->ls && !(s->bits <= 8 || nb_components == 1)) {
         av_log_missing_feature(s->avctx,
-                               "only <= 8 bits/component or "
-                               "16-bit gray accepted for JPEG-LS\n", 0);
+                               "For JPEG-LS anything except <= 8 bits/component"
+                               " or 16-bit gray", 0);
         return AVERROR_PATCHWELCOME;
     }
     s->nb_components = nb_components;
     s->h_max         = 1;
     s->v_max         = 1;
+    memset(h_count, 0, sizeof(h_count));
+    memset(v_count, 0, sizeof(v_count));
     for (i = 0; i < nb_components; i++) {
         /* component id */
         s->component_id[i] = get_bits(&s->gb, 8) - 1;
-        s->h_count[i]      = get_bits(&s->gb, 4);
-        s->v_count[i]      = get_bits(&s->gb, 4);
+        h_count[i]         = get_bits(&s->gb, 4);
+        v_count[i]         = get_bits(&s->gb, 4);
         /* compute hmax and vmax (only used in interleaved case) */
-        if (s->h_count[i] > s->h_max)
-            s->h_max = s->h_count[i];
-        if (s->v_count[i] > s->v_max)
-            s->v_max = s->v_count[i];
-        if (!s->h_count[i] || !s->v_count[i]) {
+        if (h_count[i] > s->h_max)
+            s->h_max = h_count[i];
+        if (v_count[i] > s->v_max)
+            s->v_max = v_count[i];
+        if (!h_count[i] || !v_count[i]) {
             av_log(s->avctx, AV_LOG_ERROR, "h/v_count is 0\n");
             return -1;
         }
         s->quant_index[i] = get_bits(&s->gb, 8);
-        if (s->quant_index[i] >= 4)
+        if (s->quant_index[i] >= 4) {
+            av_log(s->avctx, AV_LOG_ERROR, "quant_index is invalid\n");
             return AVERROR_INVALIDDATA;
+        }
         av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n",
-               i, s->h_count[i], s->v_count[i],
+               i, h_count[i], v_count[i],
                s->component_id[i], s->quant_index[i]);
     }
 
     if (s->ls && (s->h_max > 1 || s->v_max > 1)) {
-        av_log_missing_feature(s->avctx,
-                               "Subsampling in JPEG-LS is not supported.\n", 0);
+        av_log_missing_feature(s->avctx, "Subsampling in JPEG-LS", 0);
         return AVERROR_PATCHWELCOME;
     }
 
@@ -295,13 +301,17 @@
         s->rgb = 1;
 
     /* if different size, realloc/alloc picture */
-    /* XXX: also check h_count and v_count */
-    if (width != s->width || height != s->height) {
+    if (   width != s->width || height != s->height
+        || memcmp(s->h_count, h_count, sizeof(h_count[0])*nb_components)
+        || memcmp(s->v_count, v_count, sizeof(v_count[0])*nb_components)) {
         av_freep(&s->qscale_table);
 
         s->width      = width;
         s->height     = height;
+        memcpy(s->h_count, h_count, sizeof(h_count));
+        memcpy(s->v_count, v_count, sizeof(v_count));
         s->interlaced = 0;
+        s->got_picture = 0;
 
         /* test interlaced mode */
         if (s->first_picture   &&
@@ -342,12 +352,12 @@
     switch (pix_fmt_id) {
     case 0x11111100:
         if (s->rgb)
-            s->avctx->pix_fmt = PIX_FMT_BGR24;
+            s->avctx->pix_fmt = AV_PIX_FMT_BGR24;
         else {
             if (s->component_id[0] == 'Q' && s->component_id[1] == 'F' && s->component_id[2] == 'A') {
-                s->avctx->pix_fmt = PIX_FMT_GBR24P;
+                s->avctx->pix_fmt = AV_PIX_FMT_GBR24P;
             } else {
-            s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV444P : PIX_FMT_YUVJ444P;
+            s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
             s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
             }
         }
@@ -355,7 +365,7 @@
         break;
     case 0x12121100:
     case 0x22122100:
-        s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV444P : PIX_FMT_YUVJ444P;
+        s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
         s->upscale_v = 2;
         s->upscale_h = (pix_fmt_id == 0x22122100);
@@ -363,14 +373,14 @@
         break;
     case 0x21211100:
     case 0x22211200:
-        s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV444P : PIX_FMT_YUVJ444P;
+        s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
         s->upscale_v = (pix_fmt_id == 0x22211200);
         s->upscale_h = 2;
         s->chroma_height = s->height;
         break;
     case 0x22221100:
-        s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV444P : PIX_FMT_YUVJ444P;
+        s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
         s->upscale_v = 2;
         s->upscale_h = 2;
@@ -378,30 +388,30 @@
         break;
     case 0x11000000:
         if(s->bits <= 8)
-            s->avctx->pix_fmt = PIX_FMT_GRAY8;
+            s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
         else
-            s->avctx->pix_fmt = PIX_FMT_GRAY16;
+            s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
         break;
     case 0x12111100:
     case 0x22211100:
     case 0x22112100:
-        s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV440P : PIX_FMT_YUVJ440P;
+        s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV440P : AV_PIX_FMT_YUVJ440P;
         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
         s->upscale_h = (pix_fmt_id == 0x22211100) * 2 + (pix_fmt_id == 0x22112100);
         s->chroma_height = s->height / 2;
         break;
     case 0x21111100:
-        s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV422P : PIX_FMT_YUVJ422P;
+        s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
         break;
     case 0x22121100:
     case 0x22111200:
-        s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV422P : PIX_FMT_YUVJ422P;
+        s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
         s->upscale_v = (pix_fmt_id == 0x22121100) + 1;
         break;
     case 0x22111100:
-        s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV420P : PIX_FMT_YUVJ420P;
+        s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV420P : AV_PIX_FMT_YUVJ420P;
         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
         break;
     default:
@@ -415,11 +425,11 @@
     if (s->ls) {
         s->upscale_h = s->upscale_v = 0;
         if (s->nb_components > 1)
-            s->avctx->pix_fmt = PIX_FMT_RGB24;
+            s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
         else if (s->bits <= 8)
-            s->avctx->pix_fmt = PIX_FMT_GRAY8;
+            s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
         else
-            s->avctx->pix_fmt = PIX_FMT_GRAY16;
+            s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
     }
 
     if (s->picture_ptr->data[0])
@@ -1096,6 +1106,11 @@
     int last_scan = 0;
     int16_t *quant_matrix = s->quant_matrixes[s->quant_index[c]];
 
+    if (se > 63) {
+        av_log(s->avctx, AV_LOG_ERROR, "SE %d is too large\n", se);
+        return AVERROR_INVALIDDATA;
+    }
+
     if (!Al) {
         s->coefs_finished[c] |= (1LL << (se + 1)) - (1LL << ss);
         last_scan = !~s->coefs_finished[c];
@@ -1176,9 +1191,9 @@
             && nb_components == 3 && s->nb_components == 3 && i)
             index = 3 - i;
 
-        if(nb_components == 3 && s->nb_components == 3 && s->avctx->pix_fmt == PIX_FMT_GBR24P)
+        if(nb_components == 3 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
             index = (i+2)%3;
-        if(nb_components == 1 && s->nb_components == 3 && s->avctx->pix_fmt == PIX_FMT_GBR24P)
+        if(nb_components == 1 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
             index = (index+2)%3;
 
         s->comp_index[i] = index;
@@ -1596,7 +1611,6 @@
     int ret = 0;
     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) {
@@ -1607,7 +1621,7 @@
         /* EOF */
         if (start_code < 0) {
             goto the_end;
-        } else if (unescaped_buf_size > (1U<<29)) {
+        } else if (unescaped_buf_size > (1U<<28)) {
             av_log(avctx, AV_LOG_ERROR, "MJPEG packet 0x%x too big (0x%x/0x%x), corrupt data?\n",
                    start_code, unescaped_buf_size, buf_size);
             return AVERROR_INVALIDDATA;
@@ -1632,6 +1646,7 @@
             else if (start_code == COM)
                 mjpeg_decode_com(s);
 
+            ret = -1;
             switch (start_code) {
             case SOI:
                 s->restart_interval = 0;
@@ -1644,7 +1659,7 @@
             case DHT:
                 if ((ret = ff_mjpeg_decode_dht(s)) < 0) {
                     av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
-                    return ret;
+                    goto fail;
                 }
                 break;
             case SOF0:
@@ -1653,33 +1668,33 @@
                 s->ls          = 0;
                 s->progressive = 0;
                 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
-                    return ret;
+                    goto fail;
                 break;
             case SOF2:
                 s->lossless    = 0;
                 s->ls          = 0;
                 s->progressive = 1;
                 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
-                    return ret;
+                    goto fail;
                 break;
             case SOF3:
                 s->lossless    = 1;
                 s->ls          = 0;
                 s->progressive = 0;
                 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
-                    return ret;
+                    goto fail;
                 break;
             case SOF48:
                 s->lossless    = 1;
                 s->ls          = 1;
                 s->progressive = 0;
                 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
-                    return ret;
+                    goto fail;
                 break;
             case LSE:
                 if (!CONFIG_JPEGLS_DECODER ||
                     (ret = ff_jpegls_decode_lse(s)) < 0)
-                    return ret;
+                    goto fail;
                 break;
             case EOI:
 eoi_parser:
@@ -1697,6 +1712,7 @@
                 }
                     *picture   = *s->picture_ptr;
                     *data_size = sizeof(AVFrame);
+                    s->got_picture = 0;
 
                     if (!s->lossless) {
                         picture->quality      = FFMAX3(s->qscale[0],
@@ -1716,7 +1732,7 @@
             case SOS:
                 if ((ret = ff_mjpeg_decode_sos(s, NULL, NULL)) < 0 &&
                     (avctx->err_recognition & AV_EF_EXPLODE))
-                    return ret;
+                    goto fail;
                 break;
             case DRI:
                 mjpeg_decode_dri(s);
@@ -1749,13 +1765,16 @@
     }
     av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
     return AVERROR_INVALIDDATA;
+fail:
+    s->got_picture = 0;
+    return ret;
 the_end:
     if (s->upscale_h) {
         uint8_t *line = s->picture_ptr->data[s->upscale_h];
-        av_assert0(avctx->pix_fmt == PIX_FMT_YUVJ444P ||
-                   avctx->pix_fmt == PIX_FMT_YUV444P  ||
-                   avctx->pix_fmt == PIX_FMT_YUVJ440P ||
-                   avctx->pix_fmt == PIX_FMT_YUV440P);
+        av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
+                   avctx->pix_fmt == AV_PIX_FMT_YUV444P  ||
+                   avctx->pix_fmt == AV_PIX_FMT_YUVJ440P ||
+                   avctx->pix_fmt == AV_PIX_FMT_YUV440P);
         for (i = 0; i < s->chroma_height; i++) {
             for (index = s->width - 1; index; index--)
                 line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;
@@ -1764,10 +1783,10 @@
     }
     if (s->upscale_v) {
         uint8_t *dst = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(s->height - 1) * s->linesize[s->upscale_v]];
-        av_assert0(avctx->pix_fmt == PIX_FMT_YUVJ444P ||
-                   avctx->pix_fmt == PIX_FMT_YUV444P  ||
-                   avctx->pix_fmt == PIX_FMT_YUVJ422P ||
-                   avctx->pix_fmt == PIX_FMT_YUV422P);
+        av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
+                   avctx->pix_fmt == AV_PIX_FMT_YUV444P  ||
+                   avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||
+                   avctx->pix_fmt == AV_PIX_FMT_YUV422P);
         for (i = s->height - 1; i; i--) {
             uint8_t *src1 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[i / 2 * s->linesize[s->upscale_v]];
             uint8_t *src2 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(i + 1) / 2 * s->linesize[s->upscale_v]];
@@ -1833,6 +1852,12 @@
     return 0;
 }
 
+static void decode_flush(AVCodecContext *avctx)
+{
+    MJpegDecodeContext *s = avctx->priv_data;
+    s->got_picture = 0;
+}
+
 #if CONFIG_MJPEG_DECODER
 #define OFFSET(x) offsetof(MJpegDecodeContext, x)
 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
@@ -1857,6 +1882,7 @@
     .init           = ff_mjpeg_decode_init,
     .close          = ff_mjpeg_decode_end,
     .decode         = ff_mjpeg_decode_frame,
+    .flush          = decode_flush,
     .capabilities   = CODEC_CAP_DR1,
     .max_lowres     = 3,
     .long_name      = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
@@ -1872,6 +1898,7 @@
     .init           = ff_mjpeg_decode_init,
     .close          = ff_mjpeg_decode_end,
     .decode         = ff_mjpeg_decode_frame,
+    .flush          = decode_flush,
     .capabilities   = CODEC_CAP_DR1,
     .max_lowres     = 3,
     .long_name      = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
diff --git a/libavcodec/mjpegenc.c b/libavcodec/mjpegenc.c
index b3ead99..381f0fb 100644
--- a/libavcodec/mjpegenc.c
+++ b/libavcodec/mjpegenc.c
@@ -189,9 +189,9 @@
         AV_WB16(ptr, size);
     }
 
-    if(  s->avctx->pix_fmt == PIX_FMT_YUV420P
-       ||s->avctx->pix_fmt == PIX_FMT_YUV422P
-       ||s->avctx->pix_fmt == PIX_FMT_YUV444P){
+    if(  s->avctx->pix_fmt == AV_PIX_FMT_YUV420P
+       ||s->avctx->pix_fmt == AV_PIX_FMT_YUV422P
+       ||s->avctx->pix_fmt == AV_PIX_FMT_YUV444P){
         put_marker(p, COM);
         flush_put_bits(p);
         ptr = put_bits_ptr(p);
@@ -223,9 +223,9 @@
     }
 
     put_bits(&s->pb, 16, 17);
-    if(lossless && (s->avctx->pix_fmt == PIX_FMT_BGR0
-                    || s->avctx->pix_fmt == PIX_FMT_BGRA
-                    || s->avctx->pix_fmt == PIX_FMT_BGR24))
+    if(lossless && (s->avctx->pix_fmt == AV_PIX_FMT_BGR0
+                    || s->avctx->pix_fmt == AV_PIX_FMT_BGRA
+                    || s->avctx->pix_fmt == AV_PIX_FMT_BGR24))
         put_bits(&s->pb, 8, 9); /* 9 bits/component RCT */
     else
         put_bits(&s->pb, 8, 8); /* 8 bits/component */
@@ -463,10 +463,18 @@
     }
     if (s->chroma_format == CHROMA_420) {
         encode_block(s, block[5], 5);
-    } else {
+    } else if (s->chroma_format == CHROMA_422) {
         encode_block(s, block[6], 6);
         encode_block(s, block[5], 5);
         encode_block(s, block[7], 7);
+    } else {
+        encode_block(s, block[6], 6);
+        encode_block(s, block[8], 8);
+        encode_block(s, block[10], 10);
+        encode_block(s, block[5], 5);
+        encode_block(s, block[7], 7);
+        encode_block(s, block[9], 9);
+        encode_block(s, block[11], 11);
     }
 
     s->i_tex_bits += get_bits_diff(s);
@@ -504,8 +512,8 @@
     .encode2        = ff_MPV_encode_picture,
     .close          = ff_MPV_encode_end,
     .capabilities   = CODEC_CAP_SLICE_THREADS | CODEC_CAP_FRAME_THREADS | CODEC_CAP_INTRA_ONLY,
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
 };
@@ -519,8 +527,8 @@
     .init           = ff_MPV_encode_init,
     .encode2        = amv_encode_picture,
     .close          = ff_MPV_encode_end,
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("AMV Video"),
 };
diff --git a/libavcodec/mlp.h b/libavcodec/mlp.h
index 628b58d..d8d1292 100644
--- a/libavcodec/mlp.h
+++ b/libavcodec/mlp.h
@@ -71,7 +71,7 @@
 #define IIR 1
 
 /** filter data */
-typedef struct {
+typedef struct FilterParams {
     uint8_t     order; ///< number of taps in filter
     uint8_t     shift; ///< Right shift to apply to output of filter.
 
@@ -79,7 +79,7 @@
 } FilterParams;
 
 /** sample data coding information */
-typedef struct {
+typedef struct ChannelParams {
     FilterParams filter_params[NUM_FILTERS];
     int32_t     coeff[NUM_FILTERS][MAX_FIR_ORDER];
 
diff --git a/libavcodec/mlp_parser.c b/libavcodec/mlp_parser.c
index 5fb1424..f1c0a0d 100644
--- a/libavcodec/mlp_parser.c
+++ b/libavcodec/mlp_parser.c
@@ -26,8 +26,8 @@
 
 #include <stdint.h>
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/crc.h"
-#include "libavutil/audioconvert.h"
 #include "get_bits.h"
 #include "parser.h"
 #include "mlp_parser.h"
@@ -239,7 +239,8 @@
         }
 
         if (!mp->in_sync) {
-            ff_combine_frame(&mp->pc, END_NOT_FOUND, &buf, &buf_size);
+            if (ff_combine_frame(&mp->pc, END_NOT_FOUND, &buf, &buf_size) != -1)
+                av_log(avctx, AV_LOG_WARNING, "ff_combine_frame failed\n");
             return buf_size;
         }
 
@@ -257,7 +258,8 @@
         }
 
         if (mp->pc.index + buf_size < 2) {
-            ff_combine_frame(&mp->pc, END_NOT_FOUND, &buf, &buf_size);
+            if (ff_combine_frame(&mp->pc, END_NOT_FOUND, &buf, &buf_size) != -1)
+                av_log(avctx, AV_LOG_WARNING, "ff_combine_frame failed\n");
             return buf_size;
         }
 
diff --git a/libavcodec/mlpdec.c b/libavcodec/mlpdec.c
index ccd09b6..d587982 100644
--- a/libavcodec/mlpdec.c
+++ b/libavcodec/mlpdec.c
@@ -27,12 +27,12 @@
 #include <stdint.h>
 
 #include "avcodec.h"
-#include "dsputil.h"
 #include "libavutil/intreadwrite.h"
 #include "get_bits.h"
 #include "libavutil/crc.h"
 #include "parser.h"
 #include "mlp_parser.h"
+#include "mlpdsp.h"
 #include "mlp.h"
 
 /** number of bits used for VLC lookup - longest Huffman code is 9 */
@@ -145,7 +145,7 @@
     int8_t      bypassed_lsbs[MAX_BLOCKSIZE][MAX_CHANNELS];
     int32_t     sample_buffer[MAX_BLOCKSIZE][MAX_CHANNELS];
 
-    DSPContext  dsp;
+    MLPDSPContext dsp;
 } MLPDecodeContext;
 
 static VLC huff_vlc[3];
@@ -235,7 +235,7 @@
     m->avctx = avctx;
     for (substr = 0; substr < MAX_SUBSTREAMS; substr++)
         m->substream[substr].lossless_check_data = 0xffffffff;
-    ff_dsputil_init(&m->dsp, avctx);
+    ff_mlpdsp_init(&m->dsp);
 
     avcodec_get_frame_defaults(&m->frame);
     avctx->coded_frame = &m->frame;
diff --git a/libavcodec/mlpdsp.c b/libavcodec/mlpdsp.c
index 7ec8dd2..9a376e2 100644
--- a/libavcodec/mlpdsp.c
+++ b/libavcodec/mlpdsp.c
@@ -19,7 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#include "dsputil.h"
+#include "config.h"
+#include "mlpdsp.h"
 #include "mlp.h"
 
 static void ff_mlp_filter_channel(int32_t *state, const int32_t *coeff,
@@ -55,9 +56,9 @@
     }
 }
 
-void ff_mlp_init(DSPContext* c, AVCodecContext *avctx)
+void ff_mlpdsp_init(MLPDSPContext *c)
 {
     c->mlp_filter_channel = ff_mlp_filter_channel;
     if (ARCH_X86)
-        ff_mlp_init_x86(c, avctx);
+        ff_mlpdsp_init_x86(c);
 }
diff --git a/libavcodec/mlpdsp.h b/libavcodec/mlpdsp.h
new file mode 100644
index 0000000..84a8aa3
--- /dev/null
+++ b/libavcodec/mlpdsp.h
@@ -0,0 +1,37 @@
+/*
+ * MLP codec common header file
+ * Copyright (c) 2007-2008 Ian Caulfield
+ *
+ * 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_MLPDSP_H
+#define AVCODEC_MLPDSP_H
+
+#include <stdint.h>
+
+typedef struct MLPDSPContext {
+    void (*mlp_filter_channel)(int32_t *state, const int32_t *coeff,
+                               int firorder, int iirorder,
+                               unsigned int filter_shift, int32_t mask,
+                               int blocksize, int32_t *sample_buffer);
+} MLPDSPContext;
+
+void ff_mlpdsp_init(MLPDSPContext *c);
+void ff_mlpdsp_init_x86(MLPDSPContext *c);
+
+#endif /* AVCODEC_MLPDSP_H */
diff --git a/libavcodec/mmvideo.c b/libavcodec/mmvideo.c
index ff8908a..0120e9f 100644
--- a/libavcodec/mmvideo.c
+++ b/libavcodec/mmvideo.c
@@ -58,7 +58,7 @@
 
     s->avctx = avctx;
 
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     avcodec_get_frame_defaults(&s->frame);
     s->frame.reference = 3;
@@ -72,7 +72,7 @@
 
     bytestream2_skip(&s->gb, 4);
     for (i = 0; i < 128; i++) {
-        s->palette[i] = 0xFF << 24 | bytestream2_get_be24(&s->gb);
+        s->palette[i] = 0xFFU << 24 | bytestream2_get_be24(&s->gb);
         s->palette[i+128] = s->palette[i]<<2;
     }
 
@@ -120,7 +120,7 @@
     return 0;
 }
 
-/*
+/**
  * @param half_horiz Half horizontal resolution (0 or 1)
  * @param half_vert Half vertical resolution (0 or 1)
  */
diff --git a/libavcodec/motion-test.c b/libavcodec/motion-test.c
index 3504ccf..2cdb1c0 100644
--- a/libavcodec/motion-test.c
+++ b/libavcodec/motion-test.c
@@ -80,8 +80,8 @@
         for(y=0;y<HEIGHT-17;y++) {
             for(x=0;x<WIDTH-17;x++) {
                 ptr = img2 + y * WIDTH + x;
-                d1 = test_func(NULL, img1, ptr, WIDTH, 1);
-                d2 = ref_func(NULL, img1, ptr, WIDTH, 1);
+                d1 = test_func(NULL, img1, ptr, WIDTH, 8);
+                d2 = ref_func(NULL, img1, ptr, WIDTH, 8);
                 if (d1 != d2) {
                     printf("error: mmx=%d c=%d\n", d1, d2);
                 }
@@ -97,7 +97,7 @@
         for(y=0;y<HEIGHT-17;y++) {
             for(x=0;x<WIDTH-17;x++) {
                 ptr = img2 + y * WIDTH + x;
-                d1 += test_func(NULL, img1, ptr, WIDTH, 1);
+                d1 += test_func(NULL, img1, ptr, WIDTH, 8);
             }
         }
     }
@@ -128,10 +128,12 @@
 
     ctx = avcodec_alloc_context3(NULL);
     ctx->dsp_mask = AV_CPU_FLAG_FORCE;
+    memset(&cctx, 0, sizeof(cctx));
     ff_dsputil_init(&cctx, ctx);
     for (c = 0; c < flags_size; c++) {
         int x;
         ctx->dsp_mask = AV_CPU_FLAG_FORCE | flags[c];
+        memset(&mmxctx, 0, sizeof(mmxctx));
         ff_dsputil_init(&mmxctx, ctx);
 
         for (x = 0; x < 2; x++) {
diff --git a/libavcodec/motion_est.c b/libavcodec/motion_est.c
index 1e4aa84..a303d37 100644
--- a/libavcodec/motion_est.c
+++ b/libavcodec/motion_est.c
@@ -30,7 +30,7 @@
 #include <stdlib.h>
 #include <stdio.h>
 #include <limits.h>
-#include "libavutil/intmath.h"
+
 #include "avcodec.h"
 #include "dsputil.h"
 #include "mathops.h"
@@ -113,7 +113,7 @@
     uint8_t * const * const src= c->src[src_index];
     int d;
     //FIXME check chroma 4mv, (no crashes ...)
-        assert(x >= c->xmin && hx <= c->xmax<<(qpel+1) && y >= c->ymin && hy <= c->ymax<<(qpel+1));
+        av_assert2(x >= c->xmin && hx <= c->xmax<<(qpel+1) && y >= c->ymin && hy <= c->ymax<<(qpel+1));
         if(x >= c->xmin && hx <= c->xmax<<(qpel+1) && y >= c->ymin && hy <= c->ymax<<(qpel+1)){
             const int time_pp= s->pp_time;
             const int time_pb= s->pb_time;
@@ -155,14 +155,14 @@
                     c->qpel_avg[1][bxy](c->temp     + 8*stride, ref[8] + (bx>>2) + (by>>2)*stride     + 8*stride, stride);
                     c->qpel_avg[1][bxy](c->temp + 8 + 8*stride, ref[8] + (bx>>2) + (by>>2)*stride + 8 + 8*stride, stride);
                 }else{
-                    assert((fx>>1) + 16*s->mb_x >= -16);
-                    assert((fy>>1) + 16*s->mb_y >= -16);
-                    assert((fx>>1) + 16*s->mb_x <= s->width);
-                    assert((fy>>1) + 16*s->mb_y <= s->height);
-                    assert((bx>>1) + 16*s->mb_x >= -16);
-                    assert((by>>1) + 16*s->mb_y >= -16);
-                    assert((bx>>1) + 16*s->mb_x <= s->width);
-                    assert((by>>1) + 16*s->mb_y <= s->height);
+                    av_assert2((fx>>1) + 16*s->mb_x >= -16);
+                    av_assert2((fy>>1) + 16*s->mb_y >= -16);
+                    av_assert2((fx>>1) + 16*s->mb_x <= s->width);
+                    av_assert2((fy>>1) + 16*s->mb_y <= s->height);
+                    av_assert2((bx>>1) + 16*s->mb_x >= -16);
+                    av_assert2((by>>1) + 16*s->mb_y >= -16);
+                    av_assert2((bx>>1) + 16*s->mb_x <= s->width);
+                    av_assert2((by>>1) + 16*s->mb_y <= s->height);
 
                     c->hpel_put[0][fxy](c->temp, ref[0] + (fx>>1) + (fy>>1)*stride, stride, 16);
                     c->hpel_avg[0][bxy](c->temp, ref[8] + (bx>>1) + (by>>1)*stride, stride, 16);
@@ -298,7 +298,7 @@
     int cache_size= FFMIN(ME_MAP_SIZE>>ME_MAP_SHIFT, 1<<ME_MAP_SHIFT);
     int dia_size= FFMAX(FFABS(s->avctx->dia_size)&255, FFABS(s->avctx->pre_dia_size)&255);
 
-    if(FFMIN(s->avctx->dia_size, s->avctx->pre_dia_size) < -ME_MAP_SIZE){
+    if(FFMIN(s->avctx->dia_size, s->avctx->pre_dia_size) < -FFMIN(ME_MAP_SIZE, MAX_SAB_SIZE)){
         av_log(s->avctx, AV_LOG_ERROR, "ME_MAP size is too small for SAB diamond\n");
         return -1;
     }
@@ -392,7 +392,7 @@
     const int flags= c->sub_flags;
     LOAD_COMMON
 
-    assert(flags == 0);
+    av_assert2(flags == 0);
 
     if(c->skip){
         *mx_ptr = 0;
@@ -747,8 +747,8 @@
             int16_t (*mv_table)[2]= mv_tables[block][field_select];
 
             if(user_field_select){
-                assert(field_select==0 || field_select==1);
-                assert(field_select_tables[block][xy]==0 || field_select_tables[block][xy]==1);
+                av_assert1(field_select==0 || field_select==1);
+                av_assert1(field_select_tables[block][xy]==0 || field_select_tables[block][xy]==1);
                 if(field_select_tables[block][xy] != field_select)
                     continue;
             }
@@ -866,7 +866,7 @@
         av_log(c->avctx, AV_LOG_ERROR, "backward motion vector in P frame\n");
         return INT_MAX/2;
     }
-    assert(IS_INTRA(mb_type) || USES_LIST(mb_type,0) || USES_LIST(mb_type,1));
+    av_assert0(IS_INTRA(mb_type) || USES_LIST(mb_type,0) || USES_LIST(mb_type,1));
 
     for(i=0; i<4; i++){
         int xy= s->block_index[i];
@@ -888,8 +888,8 @@
         if(USES_LIST(mb_type, 0)){
             int field_select0= p->f.ref_index[0][4*mb_xy  ];
             int field_select1= p->f.ref_index[0][4*mb_xy+2];
-            assert(field_select0==0 ||field_select0==1);
-            assert(field_select1==0 ||field_select1==1);
+            av_assert0(field_select0==0 ||field_select0==1);
+            av_assert0(field_select1==0 ||field_select1==1);
             init_interlaced_ref(s, 0);
 
             if(p_type){
@@ -916,8 +916,8 @@
         if(USES_LIST(mb_type, 1)){
             int field_select0 = p->f.ref_index[1][4 * mb_xy    ];
             int field_select1 = p->f.ref_index[1][4 * mb_xy + 2];
-            assert(field_select0==0 ||field_select0==1);
-            assert(field_select1==0 ||field_select1==1);
+            av_assert0(field_select0==0 ||field_select0==1);
+            av_assert0(field_select1==0 ||field_select1==1);
             init_interlaced_ref(s, 2);
 
             s->b_field_select_table[1][0][mb_xy]= field_select0;
@@ -999,9 +999,9 @@
 
     init_ref(c, s->new_picture.f.data, s->last_picture.f.data, NULL, 16*mb_x, 16*mb_y, 0);
 
-    assert(s->quarter_sample==0 || s->quarter_sample==1);
-    assert(s->linesize == c->stride);
-    assert(s->uvlinesize == c->uvstride);
+    av_assert0(s->quarter_sample==0 || s->quarter_sample==1);
+    av_assert0(s->linesize == c->stride);
+    av_assert0(s->uvlinesize == c->uvstride);
 
     c->penalty_factor    = get_penalty_factor(s->lambda, s->lambda2, c->avctx->me_cmp);
     c->sub_penalty_factor= get_penalty_factor(s->lambda, s->lambda2, c->avctx->me_sub_cmp);
@@ -1215,7 +1215,7 @@
     const int xy= mb_x + mb_y*s->mb_stride;
     init_ref(c, s->new_picture.f.data, s->last_picture.f.data, NULL, 16*mb_x, 16*mb_y, 0);
 
-    assert(s->quarter_sample==0 || s->quarter_sample==1);
+    av_assert0(s->quarter_sample==0 || s->quarter_sample==1);
 
     c->pre_penalty_factor    = get_penalty_factor(s->lambda, s->lambda2, c->avctx->me_pre_cmp);
     c->current_mv_penalty= c->mv_penalty[s->f_code] + MAX_MV;
@@ -1593,7 +1593,7 @@
         if(s->mv_type == MV_TYPE_16X16) break;
     }
 
-    assert(xmax <= 15 && ymax <= 15 && xmin >= -16 && ymin >= -16);
+    av_assert2(xmax <= 15 && ymax <= 15 && xmin >= -16 && ymin >= -16);
 
     if(xmax < 0 || xmin >0 || ymax < 0 || ymin > 0){
         s->b_direct_mv_table[mot_xy][0]= 0;
diff --git a/libavcodec/motion_est_template.c b/libavcodec/motion_est_template.c
index 07bfc00..2b1c6e1 100644
--- a/libavcodec/motion_est_template.c
+++ b/libavcodec/motion_est_template.c
@@ -688,6 +688,8 @@
     LOAD_COMMON2
     unsigned map_generation = c->map_generation;
 
+    av_assert1(minima_count <= MAX_SAB_SIZE);
+
     cmpf= s->dsp.me_cmp[size];
     chroma_cmpf= s->dsp.me_cmp[size+1];
 
diff --git a/libavcodec/motionpixels.c b/libavcodec/motionpixels.c
index 7b6853e..8d457e0 100644
--- a/libavcodec/motionpixels.c
+++ b/libavcodec/motionpixels.c
@@ -67,7 +67,7 @@
     mp->offset_bits_len = av_log2(avctx->width * avctx->height) + 1;
     mp->vpt = av_mallocz(avctx->height * sizeof(YuvPixel));
     mp->hpt = av_mallocz(h4 * w4 / 16 * sizeof(YuvPixel));
-    avctx->pix_fmt = PIX_FMT_RGB555;
+    avctx->pix_fmt = AV_PIX_FMT_RGB555;
     avcodec_get_frame_defaults(&mp->frame);
     return 0;
 }
@@ -220,6 +220,8 @@
     YuvPixel p;
     int y, y0;
 
+    av_assert1(mp->changes_map[0]);
+
     for (y = 0; y < mp->avctx->height; ++y) {
         if (mp->changes_map[y * mp->avctx->width] != 0) {
             memset(mp->gradient_scale, 1, sizeof(mp->gradient_scale));
@@ -250,13 +252,13 @@
     int buf_size = avpkt->size;
     MotionPixelsContext *mp = avctx->priv_data;
     GetBitContext gb;
-    int i, count1, count2, sz;
+    int i, count1, count2, sz, ret;
 
     mp->frame.reference = 3;
     mp->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;
-    if (avctx->reget_buffer(avctx, &mp->frame)) {
+    if ((ret = avctx->reget_buffer(avctx, &mp->frame)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
-        return -1;
+        return ret;
     }
 
     /* le32 bitstream msb first */
diff --git a/libavcodec/mpc.c b/libavcodec/mpc.c
index 7ef437c..d064924 100644
--- a/libavcodec/mpc.c
+++ b/libavcodec/mpc.c
@@ -43,28 +43,24 @@
 /**
  * Process decoded Musepack data and produce PCM
  */
-static void mpc_synth(MPCContext *c, int16_t *out, int channels)
+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 < channels; ch++){
-        samples_ptr = samples + ch;
         for(i = 0; i < SAMPLES_PER_BAND; i++) {
             ff_mpa_synth_filter_fixed(&c->mpadsp,
                                 c->synth_buf[ch], &(c->synth_buf_offset[ch]),
                                 ff_mpa_synth_window_fixed, &dither_state,
-                                samples_ptr, channels,
+                                out[ch] + 32 * i, 1,
                                 c->sb_samples[ch][i]);
-            samples_ptr += 32 * channels;
         }
     }
-    for(i = 0; i < MPC_FRAME_SIZE*channels; i++)
-        *out++=samples[i];
 }
 
-void ff_mpc_dequantize_and_synth(MPCContext * c, int maxband, void *data, int channels)
+void ff_mpc_dequantize_and_synth(MPCContext * c, int maxband, int16_t **out,
+                                 int channels)
 {
     int i, j, ch;
     Band *bands = c->bands;
@@ -100,5 +96,5 @@
         }
     }
 
-    mpc_synth(c, data, channels);
+    mpc_synth(c, out, channels);
 }
diff --git a/libavcodec/mpc.h b/libavcodec/mpc.h
index 8b4deef..7ee402b 100644
--- a/libavcodec/mpc.h
+++ b/libavcodec/mpc.h
@@ -41,7 +41,7 @@
 #define MPC_FRAME_SIZE   (BANDS * SAMPLES_PER_BAND)
 
 /** Subband structure - hold all variables for each subband */
-typedef struct {
+typedef struct Band {
     int msf; ///< mid-stereo flag
     int res[2];
     int scfi[2];
@@ -49,7 +49,7 @@
     int Q[2];
 }Band;
 
-typedef struct {
+typedef struct MPCContext {
     AVFrame frame;
     DSPContext dsp;
     MPADSPContext mpadsp;
@@ -73,6 +73,6 @@
 } MPCContext;
 
 void ff_mpc_init(void);
-void ff_mpc_dequantize_and_synth(MPCContext *c, int maxband, void *dst, int channels);
+void ff_mpc_dequantize_and_synth(MPCContext *c, int maxband, int16_t **out, int channels);
 
 #endif /* AVCODEC_MPC_H */
diff --git a/libavcodec/mpc7.c b/libavcodec/mpc7.c
index cab4eee..bacb78e 100644
--- a/libavcodec/mpc7.c
+++ b/libavcodec/mpc7.c
@@ -25,12 +25,12 @@
  * divided into 32 subbands.
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/lfg.h"
 #include "avcodec.h"
 #include "get_bits.h"
 #include "dsputil.h"
 #include "mpegaudiodsp.h"
-#include "libavutil/audioconvert.h"
 
 #include "mpc.h"
 #include "mpc7data.h"
@@ -90,7 +90,7 @@
             c->IS, c->MSS, c->gapless, c->lastframelen, c->maxbands);
     c->frames_to_skip = 0;
 
-    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
     avctx->channel_layout = AV_CH_LAYOUT_STEREO;
 
     avcodec_get_frame_defaults(&c->frame);
@@ -293,7 +293,7 @@
         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, c->frame.data[0], 2);
+    ff_mpc_dequantize_and_synth(c, mb, (int16_t **)c->frame.extended_data, 2);
     if(last_frame)
         c->frame.nb_samples = c->lastframelen;
 
@@ -342,4 +342,6 @@
     .flush          = mpc7_decode_flush,
     .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("Musepack SV7"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
+                                                      AV_SAMPLE_FMT_NONE },
 };
diff --git a/libavcodec/mpc8.c b/libavcodec/mpc8.c
index cb30b2c..1af417a 100644
--- a/libavcodec/mpc8.c
+++ b/libavcodec/mpc8.c
@@ -25,12 +25,12 @@
  * divided into 32 subbands.
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/lfg.h"
 #include "avcodec.h"
 #include "get_bits.h"
 #include "dsputil.h"
 #include "mpegaudiodsp.h"
-#include "libavutil/audioconvert.h"
 
 #include "mpc.h"
 #include "mpc8data.h"
@@ -134,12 +134,12 @@
     channels = get_bits(&gb, 4) + 1;
     if (channels > 2) {
         av_log_missing_feature(avctx, "Multichannel MPC SV8", 1);
-        return -1;
+        return AVERROR_PATCHWELCOME;
     }
     c->MSS = get_bits1(&gb);
     c->frames = 1 << (get_bits(&gb, 3) * 2);
 
-    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
     avctx->channel_layout = (channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
     avctx->channels = channels;
 
@@ -413,7 +413,8 @@
         }
     }
 
-    ff_mpc_dequantize_and_synth(c, maxband - 1, c->frame.data[0],
+    ff_mpc_dequantize_and_synth(c, maxband - 1,
+                                (int16_t **)c->frame.extended_data,
                                 avctx->channels);
 
     c->cur_frame++;
@@ -446,4 +447,6 @@
     .flush          = mpc8_decode_flush,
     .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("Musepack SV8"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
+                                                      AV_SAMPLE_FMT_NONE },
 };
diff --git a/libavcodec/mpeg12.c b/libavcodec/mpeg12.c
index cd57121..7115a99 100644
--- a/libavcodec/mpeg12.c
+++ b/libavcodec/mpeg12.c
@@ -1190,61 +1190,61 @@
     }
 }
 
-static const enum PixelFormat mpeg1_hwaccel_pixfmt_list_420[] = {
+static const enum AVPixelFormat mpeg1_hwaccel_pixfmt_list_420[] = {
 #if CONFIG_MPEG_XVMC_DECODER
-    PIX_FMT_XVMC_MPEG2_IDCT,
-    PIX_FMT_XVMC_MPEG2_MC,
+    AV_PIX_FMT_XVMC_MPEG2_IDCT,
+    AV_PIX_FMT_XVMC_MPEG2_MC,
 #endif
 #if CONFIG_MPEG1_VDPAU_HWACCEL
-    PIX_FMT_VDPAU_MPEG1,
+    AV_PIX_FMT_VDPAU_MPEG1,
 #endif
-    PIX_FMT_YUV420P,
-    PIX_FMT_NONE
+    AV_PIX_FMT_YUV420P,
+    AV_PIX_FMT_NONE
 };
 
-static const enum PixelFormat mpeg2_hwaccel_pixfmt_list_420[] = {
+static const enum AVPixelFormat mpeg2_hwaccel_pixfmt_list_420[] = {
 #if CONFIG_MPEG_XVMC_DECODER
-    PIX_FMT_XVMC_MPEG2_IDCT,
-    PIX_FMT_XVMC_MPEG2_MC,
+    AV_PIX_FMT_XVMC_MPEG2_IDCT,
+    AV_PIX_FMT_XVMC_MPEG2_MC,
 #endif
 #if CONFIG_MPEG2_VDPAU_HWACCEL
-    PIX_FMT_VDPAU_MPEG2,
+    AV_PIX_FMT_VDPAU_MPEG2,
 #endif
 #if CONFIG_MPEG2_DXVA2_HWACCEL
-    PIX_FMT_DXVA2_VLD,
+    AV_PIX_FMT_DXVA2_VLD,
 #endif
 #if CONFIG_MPEG2_VAAPI_HWACCEL
-    PIX_FMT_VAAPI_VLD,
+    AV_PIX_FMT_VAAPI_VLD,
 #endif
-    PIX_FMT_YUV420P,
-    PIX_FMT_NONE
+    AV_PIX_FMT_YUV420P,
+    AV_PIX_FMT_NONE
 };
 
 static inline int uses_vdpau(AVCodecContext *avctx) {
-    return avctx->pix_fmt == PIX_FMT_VDPAU_MPEG1 || avctx->pix_fmt == PIX_FMT_VDPAU_MPEG2;
+    return avctx->pix_fmt == AV_PIX_FMT_VDPAU_MPEG1 || avctx->pix_fmt == AV_PIX_FMT_VDPAU_MPEG2;
 }
 
-static enum PixelFormat mpeg_get_pixelformat(AVCodecContext *avctx)
+static enum AVPixelFormat mpeg_get_pixelformat(AVCodecContext *avctx)
 {
     Mpeg1Context *s1 = avctx->priv_data;
     MpegEncContext *s = &s1->mpeg_enc_ctx;
 
     if(s->chroma_format < 2) {
-        enum PixelFormat res;
+        enum AVPixelFormat res;
         res = avctx->get_format(avctx,
                                 avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO ?
                                 mpeg1_hwaccel_pixfmt_list_420 :
                                 mpeg2_hwaccel_pixfmt_list_420);
-        if (res != PIX_FMT_XVMC_MPEG2_IDCT && res != PIX_FMT_XVMC_MPEG2_MC) {
+        if (res != AV_PIX_FMT_XVMC_MPEG2_IDCT && res != AV_PIX_FMT_XVMC_MPEG2_MC) {
             avctx->xvmc_acceleration = 0;
         } else if (!avctx->xvmc_acceleration) {
             avctx->xvmc_acceleration = 2;
         }
         return res;
     } else if(s->chroma_format == 2)
-        return PIX_FMT_YUV422P;
+        return AV_PIX_FMT_YUV422P;
     else
-        return PIX_FMT_YUV444P;
+        return AV_PIX_FMT_YUV444P;
 }
 
 /* Call this function when we know all parameters.
@@ -1276,7 +1276,12 @@
             return -2;
 
         avcodec_set_dimensions(avctx, s->width, s->height);
-        avctx->bit_rate          = s->bit_rate;
+        if (avctx->codec_id == AV_CODEC_ID_MPEG2VIDEO && s->bit_rate) {
+            avctx->rc_max_rate = s->bit_rate;
+        } else if (avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO && s->bit_rate &&
+                   (s->bit_rate != 0x3FFFF*400 || s->vbv_delay != 0xFFFF)) {
+            avctx->bit_rate = s->bit_rate;
+        }
         s1->save_aspect_info     = s->aspect_ratio_info;
         s1->save_width           = s->width;
         s1->save_height          = s->height;
@@ -1288,8 +1293,8 @@
 
         if (avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
             //MPEG-1 fps
-            avctx->time_base.den = avpriv_frame_rate_tab[s->frame_rate_index].num;
-            avctx->time_base.num = avpriv_frame_rate_tab[s->frame_rate_index].den;
+            avctx->time_base.den = ff_mpeg12_frame_rate_tab[s->frame_rate_index].num;
+            avctx->time_base.num = ff_mpeg12_frame_rate_tab[s->frame_rate_index].den;
             //MPEG-1 aspect
             avctx->sample_aspect_ratio = av_d2q(1.0/ff_mpeg1_aspect[s->aspect_ratio_info], 255);
             avctx->ticks_per_frame=1;
@@ -1297,8 +1302,8 @@
         //MPEG-2 fps
             av_reduce(&s->avctx->time_base.den,
                       &s->avctx->time_base.num,
-                      avpriv_frame_rate_tab[s->frame_rate_index].num * s1->frame_rate_ext.num*2,
-                      avpriv_frame_rate_tab[s->frame_rate_index].den * s1->frame_rate_ext.den,
+                      ff_mpeg12_frame_rate_tab[s->frame_rate_index].num * s1->frame_rate_ext.num*2,
+                      ff_mpeg12_frame_rate_tab[s->frame_rate_index].den * s1->frame_rate_ext.den,
                       1 << 30);
             avctx->ticks_per_frame = 2;
             //MPEG-2 aspect
@@ -1338,7 +1343,7 @@
         avctx->pix_fmt = mpeg_get_pixelformat(avctx);
         avctx->hwaccel = ff_find_hwaccel(avctx->codec->id, avctx->pix_fmt);
         // until then pix_fmt may be changed right after codec init
-        if (avctx->pix_fmt == PIX_FMT_XVMC_MPEG2_IDCT ||
+        if (avctx->pix_fmt == AV_PIX_FMT_XVMC_MPEG2_IDCT ||
             avctx->hwaccel )
             if (avctx->idct_algo == FF_IDCT_AUTO)
                 avctx->idct_algo = FF_IDCT_SIMPLE;
@@ -1375,6 +1380,7 @@
         return -1;
 
     vbv_delay = get_bits(&s->gb, 16);
+    s->vbv_delay = vbv_delay;
     if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type == AV_PICTURE_TYPE_B) {
         s->full_pel[0] = get_bits1(&s->gb);
         f_code = get_bits(&s->gb, 3);
@@ -2076,7 +2082,7 @@
     avctx->pix_fmt = mpeg_get_pixelformat(avctx);
     avctx->hwaccel = ff_find_hwaccel(avctx->codec->id, avctx->pix_fmt);
 
-    if( avctx->pix_fmt == PIX_FMT_XVMC_MPEG2_IDCT || avctx->hwaccel )
+    if( avctx->pix_fmt == AV_PIX_FMT_XVMC_MPEG2_IDCT || avctx->hwaccel )
         if (avctx->idct_algo == FF_IDCT_AUTO)
             avctx->idct_algo = FF_IDCT_SIMPLE;
 
@@ -2129,9 +2135,9 @@
             }
 
 /*        for(i=0; !(!p[i-2] && !p[i-1] && p[i]==1) && i<buf_size; i++){
-            av_log(0,0, "%c", p[i]);
+            av_log(avctx, AV_LOG_ERROR, "%c", p[i]);
         }
-            av_log(0,0, "\n");*/
+            av_log(avctx, AV_LOG_ERROR, "\n");*/
     }
 
     /* we parse the DTG active format information */
@@ -2520,6 +2526,8 @@
     MpegEncContext *s2 = &s->mpeg_enc_ctx;
     av_dlog(avctx, "fill_buffer\n");
 
+    s2->current_picture_ptr = NULL;
+
     if (buf_size == 0 || (buf_size == 4 && AV_RB32(buf) == SEQ_END_CODE)) {
         /* special case for last picture */
         if (s2->low_delay == 0 && s2->next_picture_ptr) {
@@ -2653,7 +2661,7 @@
     }
     mpeg_decode_init(avctx);
 
-    avctx->pix_fmt           = PIX_FMT_XVMC_MPEG2_IDCT;
+    avctx->pix_fmt           = AV_PIX_FMT_XVMC_MPEG2_IDCT;
     avctx->xvmc_acceleration = 2; // 2 - the blocks are packed!
 
     return 0;
diff --git a/libavcodec/mpeg12data.c b/libavcodec/mpeg12data.c
index 309ec4e..e8c4a5d 100644
--- a/libavcodec/mpeg12data.c
+++ b/libavcodec/mpeg12data.c
@@ -27,7 +27,7 @@
 
 #include "mpeg12data.h"
 
-const uint16_t ff_mpeg1_default_intra_matrix[64] = {
+const uint16_t ff_mpeg1_default_intra_matrix[256] = {
         8, 16, 19, 22, 26, 27, 29, 34,
         16, 16, 22, 24, 27, 29, 34, 37,
         19, 22, 26, 27, 29, 34, 34, 38,
@@ -305,7 +305,7 @@
 { 0xc, 10 },
 };
 
-const AVRational avpriv_frame_rate_tab[16] = {
+const AVRational ff_mpeg12_frame_rate_tab[16] = {
     {    0,    0},
     {24000, 1001},
     {   24,    1},
@@ -325,6 +325,72 @@
     {    0,    0},
 };
 
+const AVRational ff_mpeg2_frame_rate_tab[] = {
+    {      1,     1},
+    {      2,     1},
+    {      3,     1},
+    {      4,     1},
+    {      5,     1},
+    {      6,     1},
+    {      8,     1},
+    {      9,     1},
+    {     10,     1},
+    {     12,     1},
+    {     15,     1},
+    {     16,     1},
+    {     18,     1},
+    {     20,     1},
+    {     24,     1},
+    {     25,     1},
+    {     30,     1},
+    {     32,     1},
+    {     36,     1},
+    {     40,     1},
+    {     45,     1},
+    {     48,     1},
+    {     50,     1},
+    {     60,     1},
+    {     72,     1},
+    {     75,     1},
+    {     80,     1},
+    {     90,     1},
+    {     96,     1},
+    {    100,     1},
+    {    120,     1},
+    {    150,     1},
+    {    180,     1},
+    {    200,     1},
+    {    240,     1},
+    {    750,  1001},
+    {    800,  1001},
+    {    960,  1001},
+    {   1000,  1001},
+    {   1200,  1001},
+    {   1250,  1001},
+    {   1500,  1001},
+    {   1600,  1001},
+    {   1875,  1001},
+    {   2000,  1001},
+    {   2400,  1001},
+    {   2500,  1001},
+    {   3000,  1001},
+    {   3750,  1001},
+    {   4000,  1001},
+    {   4800,  1001},
+    {   5000,  1001},
+    {   6000,  1001},
+    {   7500,  1001},
+    {   8000,  1001},
+    {  10000,  1001},
+    {  12000,  1001},
+    {  15000,  1001},
+    {  20000,  1001},
+    {  24000,  1001},
+    {  30000,  1001},
+    {  60000,  1001},
+    {      0,     0},
+};
+
 const float ff_mpeg1_aspect[16]={
     0.0000,
     1.0000,
diff --git a/libavcodec/mpeg12data.h b/libavcodec/mpeg12data.h
index d4ef11e..65b9485 100644
--- a/libavcodec/mpeg12data.h
+++ b/libavcodec/mpeg12data.h
@@ -32,7 +32,7 @@
 #include "libavutil/rational.h"
 #include "rl.h"
 
-extern const uint16_t ff_mpeg1_default_intra_matrix[64];
+extern const uint16_t ff_mpeg1_default_intra_matrix[];
 extern const uint16_t ff_mpeg1_default_non_intra_matrix[64];
 
 extern const uint16_t ff_mpeg12_vlc_dc_lum_code[12];
@@ -48,7 +48,8 @@
 
 extern const uint8_t ff_mpeg12_mbMotionVectorTable[17][2];
 
-extern const AVRational avpriv_frame_rate_tab[];
+extern const AVRational ff_mpeg12_frame_rate_tab[];
+extern const AVRational ff_mpeg2_frame_rate_tab[];
 
 extern const float ff_mpeg1_aspect[16];
 extern const AVRational ff_mpeg2_aspect[16];
diff --git a/libavcodec/mpeg12enc.c b/libavcodec/mpeg12enc.c
index 5afa944..c615417 100644
--- a/libavcodec/mpeg12enc.c
+++ b/libavcodec/mpeg12enc.c
@@ -108,21 +108,34 @@
 
 static int find_frame_rate_index(MpegEncContext *s){
     int i;
-    int64_t dmin= INT64_MAX;
-    int64_t d;
+    AVRational bestq= (AVRational){0, 0};
+    AVRational ext;
+    AVRational target = av_inv_q(s->avctx->time_base);
 
     for(i=1;i<14;i++) {
-        int64_t n0= 1001LL/avpriv_frame_rate_tab[i].den*avpriv_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_UNOFFICIAL && i>=9) break;
 
-        d = FFABS(n0 - n1);
-        if(d < dmin){
-            dmin=d;
-            s->frame_rate_index= i;
+        for (ext.num=1; ext.num <= 4; ext.num++) {
+            for (ext.den=1; ext.den <= 32; ext.den++) {
+                AVRational q = av_mul_q(ext, ff_mpeg12_frame_rate_tab[i]);
+
+                if(s->codec_id != AV_CODEC_ID_MPEG2VIDEO && (ext.den!=1 || ext.num!=1))
+                    continue;
+                if(av_gcd(ext.den, ext.num) != 1)
+                    continue;
+
+                if(    bestq.num==0
+                    || av_nearer_q(target, bestq, q) < 0
+                    || ext.num==1 && ext.den==1 && av_nearer_q(target, bestq, q) == 0){
+                    bestq = q;
+                    s->frame_rate_index= i;
+                    s->mpeg2_frame_rate_ext.num = ext.num;
+                    s->mpeg2_frame_rate_ext.den = ext.den;
+                }
+            }
         }
     }
-    if(dmin)
+    if(av_cmp_q(target, bestq))
         return -1;
     else
         return 0;
@@ -176,7 +189,7 @@
     }
 
     if (s->tc_opt_str) {
-        AVRational rate = avpriv_frame_rate_tab[s->frame_rate_index];
+        AVRational rate = ff_mpeg12_frame_rate_tab[s->frame_rate_index];
         int ret = av_timecode_init_from_string(&s->tc, rate, s->tc_opt_str, s);
         if (ret < 0)
             return ret;
@@ -209,7 +222,7 @@
         if(aspect_ratio==0.0) aspect_ratio= 1.0; //pixel aspect 1:1 (VGA)
 
         if (s->current_picture.f.key_frame) {
-            AVRational framerate= avpriv_frame_rate_tab[s->frame_rate_index];
+            AVRational framerate = ff_mpeg12_frame_rate_tab[s->frame_rate_index];
 
             /* mpeg1 header repeated every gop */
             put_header(s, SEQ_START_CODE);
@@ -286,8 +299,8 @@
                 put_bits(&s->pb, 1, 1); //marker
                 put_bits(&s->pb, 8, vbv_buffer_size >>10); //vbv buffer ext
                 put_bits(&s->pb, 1, s->low_delay);
-                put_bits(&s->pb, 2, 0); // frame_rate_ext_n
-                put_bits(&s->pb, 5, 0); // frame_rate_ext_d
+                put_bits(&s->pb, 2, s->mpeg2_frame_rate_ext.num-1); // frame_rate_ext_n
+                put_bits(&s->pb, 5, s->mpeg2_frame_rate_ext.den-1); // frame_rate_ext_d
             }
 
             put_header(s, GOP_START_CODE);
@@ -969,9 +982,9 @@
     .init                 = encode_init,
     .encode2              = ff_MPV_encode_picture,
     .close                = ff_MPV_encode_end,
-    .supported_framerates = avpriv_frame_rate_tab+1,
-    .pix_fmts             = (const enum PixelFormat[]){ PIX_FMT_YUV420P,
-                                                        PIX_FMT_NONE },
+    .supported_framerates = ff_mpeg12_frame_rate_tab + 1,
+    .pix_fmts             = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P,
+                                                        AV_PIX_FMT_NONE },
     .capabilities         = CODEC_CAP_DELAY,
     .long_name            = NULL_IF_CONFIG_SMALL("MPEG-1 video"),
     .priv_class           = &mpeg1_class,
@@ -985,9 +998,9 @@
     .init                 = encode_init,
     .encode2              = ff_MPV_encode_picture,
     .close                = ff_MPV_encode_end,
-    .supported_framerates = avpriv_frame_rate_tab + 1,
-    .pix_fmts             = (const enum PixelFormat[]){
-        PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE
+    .supported_framerates = ff_mpeg2_frame_rate_tab,
+    .pix_fmts             = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_NONE
     },
     .capabilities         = CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS,
     .long_name            = NULL_IF_CONFIG_SMALL("MPEG-2 video"),
diff --git a/libavcodec/mpeg4audio.c b/libavcodec/mpeg4audio.c
index 3066954..8aa3219 100644
--- a/libavcodec/mpeg4audio.c
+++ b/libavcodec/mpeg4audio.c
@@ -52,6 +52,8 @@
     return 0;
 }
 
+/* XXX: make sure to update the copies in the different encoders if you change
+ * this table */
 const int avpriv_mpeg4audio_sample_rates[16] = {
     96000, 88200, 64000, 48000, 44100, 32000,
     24000, 22050, 16000, 12000, 11025, 8000, 7350
diff --git a/libavcodec/mpeg4audio.h b/libavcodec/mpeg4audio.h
index 69ddc2e..0f41045 100644
--- a/libavcodec/mpeg4audio.h
+++ b/libavcodec/mpeg4audio.h
@@ -25,9 +25,8 @@
 #include <stdint.h>
 #include "get_bits.h"
 #include "put_bits.h"
-#include "symbols.h"
 
-typedef struct {
+typedef struct MPEG4AudioConfig {
     int object_type;
     int sampling_index;
     int sample_rate;
@@ -41,7 +40,7 @@
     int ps;  ///< -1 implicit, 1 presence
 } MPEG4AudioConfig;
 
-extern AVCODEC_SYMBOL const int avpriv_mpeg4audio_sample_rates[16];
+extern av_export const int avpriv_mpeg4audio_sample_rates[16];
 extern const uint8_t ff_mpeg4audio_channels[8];
 
 /**
diff --git a/libavcodec/mpeg4video.h b/libavcodec/mpeg4video.h
index 95e6e9e..97c39b6 100644
--- a/libavcodec/mpeg4video.h
+++ b/libavcodec/mpeg4video.h
@@ -101,6 +101,7 @@
 int ff_mpeg4_get_video_packet_prefix_length(MpegEncContext *s);
 int ff_mpeg4_decode_video_packet_header(MpegEncContext *s);
 void ff_mpeg4_init_direct_mv(MpegEncContext *s);
+void ff_mpeg4videodec_static_init(void);
 
 /**
  *
diff --git a/libavcodec/mpeg4video_parser.c b/libavcodec/mpeg4video_parser.c
index 2e1257d..e085669 100644
--- a/libavcodec/mpeg4video_parser.c
+++ b/libavcodec/mpeg4video_parser.c
@@ -107,6 +107,8 @@
 {
     struct Mp4vParseContext *pc = s->priv_data;
 
+    ff_mpeg4videodec_static_init();
+
     pc->first_picture = 1;
     pc->enc.quant_precision=5;
     pc->enc.slice_context_count = 1;
diff --git a/libavcodec/mpeg4videodec.c b/libavcodec/mpeg4videodec.c
index a34581f..00de316 100644
--- a/libavcodec/mpeg4videodec.c
+++ b/libavcodec/mpeg4videodec.c
@@ -1961,6 +1961,9 @@
         }
 
         av_log(s->avctx, AV_LOG_ERROR, "my guess is %d bits ;)\n",s->time_increment_bits);
+        if (s->avctx->time_base.den && 4*s->avctx->time_base.den < 1<<s->time_increment_bits) {
+            s->avctx->time_base.den = 1<<s->time_increment_bits;
+        }
     }
 
     if(IS_3IV1) time_increment= get_bits1(gb); //FIXME investigate further
@@ -2002,7 +2005,7 @@
     }
 
     if(s->avctx->time_base.num)
-        s->current_picture_ptr->f.pts = (s->time + s->avctx->time_base.num / 2) / s->avctx->time_base.num;
+        s->current_picture_ptr->f.pts = ROUNDED_DIV(s->time, s->avctx->time_base.num);
     else
         s->current_picture_ptr->f.pts = AV_NOPTS_VALUE;
     if(s->avctx->debug&FF_DEBUG_PTS)
@@ -2250,23 +2253,10 @@
     return decode_vop_header(s, gb);
 }
 
-static av_cold int decode_init(AVCodecContext *avctx)
-{
-    MpegEncContext *s = avctx->priv_data;
-    int ret;
+av_cold void ff_mpeg4videodec_static_init(void) {
     static int done = 0;
 
-    s->divx_version=
-    s->divx_build=
-    s->xvid_build=
-    s->lavc_build= -1;
-
-    if((ret=ff_h263_decode_init(avctx)) < 0)
-        return ret;
-
     if (!done) {
-        done = 1;
-
         ff_init_rl(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
         ff_init_rl(&ff_rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]);
         ff_init_rl(&ff_rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]);
@@ -2285,7 +2275,24 @@
         INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
                  &ff_mb_type_b_tab[0][1], 2, 1,
                  &ff_mb_type_b_tab[0][0], 2, 1, 16);
+        done = 1;
     }
+}
+
+static av_cold int decode_init(AVCodecContext *avctx)
+{
+    MpegEncContext *s = avctx->priv_data;
+    int ret;
+
+    s->divx_version=
+    s->divx_build=
+    s->xvid_build=
+    s->lavc_build= -1;
+
+    if((ret=ff_h263_decode_init(avctx)) < 0)
+        return ret;
+
+    ff_mpeg4videodec_static_init();
 
     s->h263_pred = 1;
     s->low_delay = 0; //default, might be overridden in the vol header during header parsing
@@ -2317,8 +2324,8 @@
 };
 
 static const AVOption mpeg4_options[] = {
-    {"quarter_sample", "1/4 subpel MC", offsetof(MpegEncContext, quarter_sample), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 1, 0},
-    {"divx_packed", "divx style packed b frames", offsetof(MpegEncContext, divx_packed), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 1, 0},
+    {"quarter_sample", "1/4 subpel MC", offsetof(MpegEncContext, quarter_sample), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
+    {"divx_packed", "divx style packed b frames", offsetof(MpegEncContext, divx_packed), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
     {NULL}
 };
 
@@ -2369,8 +2376,8 @@
     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY |
                       CODEC_CAP_HWACCEL_VDPAU,
     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 part 2 (VDPAU)"),
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_VDPAU_MPEG4,
-                                                  PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_VDPAU_MPEG4,
+                                                  AV_PIX_FMT_NONE },
     .priv_class     = &mpeg4_vdpau_class,
 };
 #endif
diff --git a/libavcodec/mpeg4videoenc.c b/libavcodec/mpeg4videoenc.c
index 97a4cd1..3311506 100644
--- a/libavcodec/mpeg4videoenc.c
+++ b/libavcodec/mpeg4videoenc.c
@@ -1351,7 +1351,7 @@
     .init           = encode_init,
     .encode2        = ff_MPV_encode_picture,
     .close          = ff_MPV_encode_end,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUV420P, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
     .capabilities   = CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS,
     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
     .priv_class     = &mpeg4enc_class,
diff --git a/libavcodec/mpegaudiodata.h b/libavcodec/mpegaudiodata.h
index f4d86d8..29a2658 100644
--- a/libavcodec/mpegaudiodata.h
+++ b/libavcodec/mpegaudiodata.h
@@ -29,13 +29,13 @@
 
 #include <stdint.h>
 
-#include "symbols.h"
+#include "libavutil/internal.h"
 
 #define MODE_EXT_MS_STEREO 2
 #define MODE_EXT_I_STEREO  1
 
-extern AVCODEC_SYMBOL const uint16_t avpriv_mpa_bitrate_tab[2][3][15];
-extern AVCODEC_SYMBOL const uint16_t avpriv_mpa_freq_tab[3];
+extern av_export const uint16_t avpriv_mpa_bitrate_tab[2][3][15];
+extern av_export const uint16_t avpriv_mpa_freq_tab[3];
 extern const int ff_mpa_sblimit_table[5];
 extern const int ff_mpa_quant_steps[17];
 extern const int ff_mpa_quant_bits[17];
diff --git a/libavcodec/mpegaudiodec.c b/libavcodec/mpegaudiodec.c
index 5a39bdc..e33c643 100644
--- a/libavcodec/mpegaudiodec.c
+++ b/libavcodec/mpegaudiodec.c
@@ -24,8 +24,8 @@
  * MPEG Audio decoder
  */
 
-#include "libavutil/audioconvert.h"
 #include "libavutil/avassert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/libm.h"
 #include "avcodec.h"
 #include "get_bits.h"
@@ -95,7 +95,8 @@
 #   define MULH3(x, y, s) ((s)*(y)*(x))
 #   define MULLx(x, y, s) ((y)*(x))
 #   define RENAME(a) a ## _float
-#   define OUT_FMT AV_SAMPLE_FMT_FLT
+#   define OUT_FMT   AV_SAMPLE_FMT_FLT
+#   define OUT_FMT_P AV_SAMPLE_FMT_FLTP
 #else
 #   define SHR(a,b)       ((a)>>(b))
 /* WARNING: only correct for positive numbers */
@@ -105,7 +106,8 @@
 #   define MULH3(x, y, s) MULH((s)*(x), y)
 #   define MULLx(x, y, s) MULL(x,y,s)
 #   define RENAME(a)      a ## _fixed
-#   define OUT_FMT AV_SAMPLE_FMT_S16
+#   define OUT_FMT   AV_SAMPLE_FMT_S16
+#   define OUT_FMT_P AV_SAMPLE_FMT_S16P
 #endif
 
 /****************/
@@ -268,7 +270,7 @@
     e -= exponent >> 2;
 #ifdef DEBUG
     if(e < 1)
-        av_log(0, AV_LOG_WARNING, "l3_unscale: e is %d\n", e);
+        av_log(NULL, AV_LOG_WARNING, "l3_unscale: e is %d\n", e);
 #endif
     if (e > 31)
         return 0;
@@ -441,7 +443,11 @@
     ff_mpadsp_init(&s->mpadsp);
     ff_dsputil_init(&s->dsp, avctx);
 
-    avctx->sample_fmt= OUT_FMT;
+    if (avctx->request_sample_fmt == OUT_FMT &&
+        avctx->codec_id != AV_CODEC_ID_MP3ON4)
+        avctx->sample_fmt = OUT_FMT;
+    else
+        avctx->sample_fmt = OUT_FMT_P;
     s->err_recognition = avctx->err_recognition;
 
     if (avctx->codec_id == AV_CODEC_ID_MP3ADU)
@@ -1564,7 +1570,7 @@
     return nb_granules * 18;
 }
 
-static int mp_decode_frame(MPADecodeContext *s, OUT_INT *samples,
+static int mp_decode_frame(MPADecodeContext *s, OUT_INT **samples,
                            const uint8_t *buf, int buf_size)
 {
     int i, nb_frames, ch, ret;
@@ -1627,20 +1633,26 @@
             av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
             return ret;
         }
-        samples = (OUT_INT *)s->frame.data[0];
+        samples = (OUT_INT **)s->frame.extended_data;
     }
 
     /* apply the synthesis filter */
     for (ch = 0; ch < s->nb_channels; ch++) {
-        samples_ptr = samples + ch;
+        int sample_stride;
+        if (s->avctx->sample_fmt == OUT_FMT_P) {
+            samples_ptr   = samples[ch];
+            sample_stride = 1;
+        } else {
+            samples_ptr   = samples[0] + ch;
+            sample_stride = s->nb_channels;
+        }
         for (i = 0; i < nb_frames; i++) {
-            RENAME(ff_mpa_synth_filter)(
-                         &s->mpadsp,
-                         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;
+            RENAME(ff_mpa_synth_filter)(&s->mpadsp, s->synth_buf[ch],
+                                        &(s->synth_buf_offset[ch]),
+                                        RENAME(ff_mpa_synth_window),
+                                        &s->dither_state, samples_ptr,
+                                        sample_stride, s->sb_samples[ch][i]);
+            samples_ptr += 32 * sample_stride;
         }
     }
 
@@ -1654,7 +1666,7 @@
     int buf_size        = avpkt->size;
     MPADecodeContext *s = avctx->priv_data;
     uint32_t header;
-    int out_size;
+    int ret;
 
     while(buf_size && !*buf){
         buf++;
@@ -1693,31 +1705,36 @@
         buf_size= s->frame_size;
     }
 
-    out_size = mp_decode_frame(s, NULL, buf, buf_size);
-    if (out_size >= 0) {
+    ret = mp_decode_frame(s, NULL, buf, buf_size);
+    if (ret >= 0) {
         *got_frame_ptr   = 1;
         *(AVFrame *)data = s->frame;
         avctx->sample_rate = s->sample_rate;
         //FIXME maybe move the other codec info stuff from above here too
     } else {
         av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
-        /* Only return an error if the bad frame makes up the whole packet.
-           If there is more data in the packet, just consume the bad frame
-           instead of returning an error, which would discard the whole
-           packet. */
+        /* Only return an error if the bad frame makes up the whole packet or
+         * the error is related to buffer management.
+         * If there is more data in the packet, just consume the bad frame
+         * instead of returning an error, which would discard the whole
+         * packet. */
         *got_frame_ptr = 0;
-        if (buf_size == avpkt->size)
-            return out_size;
+        if (buf_size == avpkt->size || ret != AVERROR_INVALIDDATA)
+            return ret;
     }
     s->frame_size = 0;
     return buf_size;
 }
 
+static void mp_flush(MPADecodeContext *ctx)
+{
+    memset(ctx->synth_buf, 0, sizeof(ctx->synth_buf));
+    ctx->last_buf_size = 0;
+}
+
 static void flush(AVCodecContext *avctx)
 {
-    MPADecodeContext *s = avctx->priv_data;
-    memset(s->synth_buf, 0, sizeof(s->synth_buf));
-    s->last_buf_size = 0;
+    mp_flush(avctx->priv_data);
 }
 
 #if CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER
@@ -1728,7 +1745,7 @@
     int buf_size        = avpkt->size;
     MPADecodeContext *s = avctx->priv_data;
     uint32_t header;
-    int len;
+    int len, ret;
     int av_unused out_size;
 
     len = buf_size;
@@ -1760,10 +1777,10 @@
 
     s->frame_size = len;
 
-    out_size = mp_decode_frame(s, NULL, buf, buf_size);
-    if (out_size < 0) {
+    ret = mp_decode_frame(s, NULL, buf, buf_size);
+    if (ret < 0) {
         av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
-        return AVERROR_INVALIDDATA;
+        return ret;
     }
 
     *got_frame_ptr   = 1;
@@ -1784,7 +1801,6 @@
     int syncword;                   ///< syncword patch
     const uint8_t *coff;            ///< channel offsets in output buffer
     MPADecodeContext *mp3decctx[5]; ///< MPADecodeContext for every decoder instance
-    OUT_INT *decoded_buf;           ///< output buffer for decoded samples
 } MP3On4DecodeContext;
 
 #include "mpeg4audio.h"
@@ -1826,8 +1842,6 @@
     for (i = 0; i < s->frames; i++)
         av_free(s->mp3decctx[i]);
 
-    av_freep(&s->decoded_buf);
-
     return 0;
 }
 
@@ -1888,14 +1902,6 @@
         s->mp3decctx[i]->mpadsp = s->mp3decctx[0]->mpadsp;
     }
 
-    /* Allocate buffer for multi-channel output if needed */
-    if (s->frames > 1) {
-        s->decoded_buf = av_malloc(MPA_FRAME_SIZE * MPA_MAX_CHANNELS *
-                                   sizeof(*s->decoded_buf));
-        if (!s->decoded_buf)
-            goto alloc_fail;
-    }
-
     return 0;
 alloc_fail:
     decode_close_mp3on4(avctx);
@@ -1908,11 +1914,8 @@
     int i;
     MP3On4DecodeContext *s = avctx->priv_data;
 
-    for (i = 0; i < s->frames; i++) {
-        MPADecodeContext *m = s->mp3decctx[i];
-        memset(m->synth_buf, 0, sizeof(m->synth_buf));
-        m->last_buf_size = 0;
-    }
+    for (i = 0; i < s->frames; i++)
+        mp_flush(s->mp3decctx[i]);
 }
 
 
@@ -1925,9 +1928,9 @@
     MPADecodeContext *m;
     int fsize, len = buf_size, out_size = 0;
     uint32_t header;
-    OUT_INT *out_samples;
-    OUT_INT *outptr, *bp;
-    int fr, j, n, ch, ret;
+    OUT_INT **out_samples;
+    OUT_INT *outptr[2];
+    int fr, ch, ret;
 
     /* get output buffer */
     s->frame->nb_samples = s->frames * MPA_FRAME_SIZE;
@@ -1935,15 +1938,12 @@
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         return ret;
     }
-    out_samples = (OUT_INT *)s->frame->data[0];
+    out_samples = (OUT_INT **)s->frame->extended_data;
 
     // Discard too short frames
     if (buf_size < HEADER_SIZE)
         return AVERROR_INVALIDDATA;
 
-    // If only one decoder interleave is not needed
-    outptr = s->frames == 1 ? out_samples : s->decoded_buf;
-
     avctx->bit_rate = 0;
 
     ch = 0;
@@ -1971,27 +1971,17 @@
         }
         ch += m->nb_channels;
 
-        out_size += mp_decode_frame(m, outptr, buf, fsize);
+        outptr[0] = out_samples[s->coff[fr]];
+        if (m->nb_channels > 1)
+            outptr[1] = out_samples[s->coff[fr] + 1];
+
+        if ((ret = mp_decode_frame(m, outptr, buf, fsize)) < 0)
+            return ret;
+
+        out_size += ret;
         buf      += fsize;
         len      -= fsize;
 
-        if (s->frames > 1) {
-            n = m->avctx->frame_size*m->nb_channels;
-            /* interleave output data */
-            bp = out_samples + s->coff[fr];
-            if (m->nb_channels == 1) {
-                for (j = 0; j < n; j++) {
-                    *bp = s->decoded_buf[j];
-                    bp += avctx->channels;
-                }
-            } else {
-                for (j = 0; j < n; j++) {
-                    bp[0] = s->decoded_buf[j++];
-                    bp[1] = s->decoded_buf[j];
-                    bp   += avctx->channels;
-                }
-            }
-        }
         avctx->bit_rate += m->bit_rate;
     }
 
@@ -2018,6 +2008,9 @@
     .capabilities   = CODEC_CAP_DR1,
     .flush          = flush,
     .long_name      = NULL_IF_CONFIG_SMALL("MP1 (MPEG audio layer 1)"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
+                                                      AV_SAMPLE_FMT_S16,
+                                                      AV_SAMPLE_FMT_NONE },
 };
 #endif
 #if CONFIG_MP2_DECODER
@@ -2031,6 +2024,9 @@
     .capabilities   = CODEC_CAP_DR1,
     .flush          = flush,
     .long_name      = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
+                                                      AV_SAMPLE_FMT_S16,
+                                                      AV_SAMPLE_FMT_NONE },
 };
 #endif
 #if CONFIG_MP3_DECODER
@@ -2044,6 +2040,9 @@
     .capabilities   = CODEC_CAP_DR1,
     .flush          = flush,
     .long_name      = NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
+                                                      AV_SAMPLE_FMT_S16,
+                                                      AV_SAMPLE_FMT_NONE },
 };
 #endif
 #if CONFIG_MP3ADU_DECODER
@@ -2057,6 +2056,9 @@
     .capabilities   = CODEC_CAP_DR1,
     .flush          = flush,
     .long_name      = NULL_IF_CONFIG_SMALL("ADU (Application Data Unit) MP3 (MPEG audio layer 3)"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
+                                                      AV_SAMPLE_FMT_S16,
+                                                      AV_SAMPLE_FMT_NONE },
 };
 #endif
 #if CONFIG_MP3ON4_DECODER
@@ -2071,6 +2073,8 @@
     .capabilities   = CODEC_CAP_DR1,
     .flush          = flush_mp3on4,
     .long_name      = NULL_IF_CONFIG_SMALL("MP3onMP4"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
+                                                      AV_SAMPLE_FMT_NONE },
 };
 #endif
 #endif
diff --git a/libavcodec/mpegaudiodec_float.c b/libavcodec/mpegaudiodec_float.c
index e26a0a9..17a7757 100644
--- a/libavcodec/mpegaudiodec_float.c
+++ b/libavcodec/mpegaudiodec_float.c
@@ -33,6 +33,9 @@
     .capabilities   = CODEC_CAP_DR1,
     .flush          = flush,
     .long_name      = NULL_IF_CONFIG_SMALL("MP1 (MPEG audio layer 1)"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
+                                                      AV_SAMPLE_FMT_FLT,
+                                                      AV_SAMPLE_FMT_NONE },
 };
 #endif
 #if CONFIG_MP2FLOAT_DECODER
@@ -46,6 +49,9 @@
     .capabilities   = CODEC_CAP_DR1,
     .flush          = flush,
     .long_name      = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
+                                                      AV_SAMPLE_FMT_FLT,
+                                                      AV_SAMPLE_FMT_NONE },
 };
 #endif
 #if CONFIG_MP3FLOAT_DECODER
@@ -59,6 +65,9 @@
     .capabilities   = CODEC_CAP_DR1,
     .flush          = flush,
     .long_name      = NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
+                                                      AV_SAMPLE_FMT_FLT,
+                                                      AV_SAMPLE_FMT_NONE },
 };
 #endif
 #if CONFIG_MP3ADUFLOAT_DECODER
@@ -72,6 +81,9 @@
     .capabilities   = CODEC_CAP_DR1,
     .flush          = flush,
     .long_name      = NULL_IF_CONFIG_SMALL("ADU (Application Data Unit) MP3 (MPEG audio layer 3)"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
+                                                      AV_SAMPLE_FMT_FLT,
+                                                      AV_SAMPLE_FMT_NONE },
 };
 #endif
 #if CONFIG_MP3ON4FLOAT_DECODER
@@ -86,5 +98,7 @@
     .capabilities   = CODEC_CAP_DR1,
     .flush          = flush_mp3on4,
     .long_name      = NULL_IF_CONFIG_SMALL("MP3onMP4"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
+                                                      AV_SAMPLE_FMT_NONE },
 };
 #endif
diff --git a/libavcodec/mpegaudiodsp.c b/libavcodec/mpegaudiodsp.c
index 82a3652..aadc747 100644
--- a/libavcodec/mpegaudiodsp.c
+++ b/libavcodec/mpegaudiodsp.c
@@ -41,7 +41,7 @@
     s->imdct36_blocks_fixed = ff_imdct36_blocks_fixed;
 
     if (ARCH_ARM)     ff_mpadsp_init_arm(s);
-    if (HAVE_MMX)     ff_mpadsp_init_mmx(s);
+    if (ARCH_X86)     ff_mpadsp_init_x86(s);
     if (HAVE_ALTIVEC) ff_mpadsp_init_altivec(s);
     if (HAVE_MIPSFPU)   ff_mpadsp_init_mipsfpu(s);
     if (HAVE_MIPSDSPR1) ff_mpadsp_init_mipsdspr1(s);
diff --git a/libavcodec/mpegaudiodsp.h b/libavcodec/mpegaudiodsp.h
index aae8ac0..623d2df 100644
--- a/libavcodec/mpegaudiodsp.h
+++ b/libavcodec/mpegaudiodsp.h
@@ -56,7 +56,7 @@
                                float *sb_samples);
 
 void ff_mpadsp_init_arm(MPADSPContext *s);
-void ff_mpadsp_init_mmx(MPADSPContext *s);
+void ff_mpadsp_init_x86(MPADSPContext *s);
 void ff_mpadsp_init_altivec(MPADSPContext *s);
 void ff_mpadsp_init_mipsfpu(MPADSPContext *s);
 void ff_mpadsp_init_mipsdspr1(MPADSPContext *s);
diff --git a/libavcodec/mpegaudioenc.c b/libavcodec/mpegaudioenc.c
index 806cb21..75436f8 100644
--- a/libavcodec/mpegaudioenc.c
+++ b/libavcodec/mpegaudioenc.c
@@ -24,7 +24,7 @@
  * The simplest mpeg audio layer 2 encoder.
  */
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 
 #include "avcodec.h"
 #include "internal.h"
diff --git a/libavcodec/mpegvideo.c b/libavcodec/mpegvideo.c
index 461ecaf..8a308be 100644
--- a/libavcodec/mpegvideo.c
+++ b/libavcodec/mpegvideo.c
@@ -27,11 +27,11 @@
  * The simplest mpeg encoder (well, it was the simplest!).
  */
 
-#include "libavutil/intmath.h"
 #include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "dsputil.h"
 #include "internal.h"
+#include "mathops.h"
 #include "mpegvideo.h"
 #include "mjpegenc.h"
 #include "msmpeg4.h"
@@ -125,17 +125,17 @@
     mpeg2_dc_scale_table3,
 };
 
-const enum PixelFormat ff_pixfmt_list_420[] = {
-    PIX_FMT_YUV420P,
-    PIX_FMT_NONE
+const enum AVPixelFormat ff_pixfmt_list_420[] = {
+    AV_PIX_FMT_YUV420P,
+    AV_PIX_FMT_NONE
 };
 
-const enum PixelFormat ff_hwaccel_pixfmt_list_420[] = {
-    PIX_FMT_DXVA2_VLD,
-    PIX_FMT_VAAPI_VLD,
-    PIX_FMT_VDA_VLD,
-    PIX_FMT_YUV420P,
-    PIX_FMT_NONE
+const enum AVPixelFormat ff_hwaccel_pixfmt_list_420[] = {
+    AV_PIX_FMT_DXVA2_VLD,
+    AV_PIX_FMT_VAAPI_VLD,
+    AV_PIX_FMT_VDA_VLD,
+    AV_PIX_FMT_YUV420P,
+    AV_PIX_FMT_NONE
 };
 
 const uint8_t *avpriv_mpv_find_start_code(const uint8_t *av_restrict p,
@@ -189,8 +189,6 @@
     ff_MPV_common_init_x86(s);
 #elif ARCH_ALPHA
     ff_MPV_common_init_axp(s);
-#elif HAVE_MMI
-    ff_MPV_common_init_mmi(s);
 #elif ARCH_ARM
     ff_MPV_common_init_arm(s);
 #elif HAVE_ALTIVEC
@@ -531,11 +529,15 @@
 int ff_mpeg_update_thread_context(AVCodecContext *dst,
                                   const AVCodecContext *src)
 {
+    int i;
+    int err;
     MpegEncContext *s = dst->priv_data, *s1 = src->priv_data;
 
     if (dst == src)
         return 0;
 
+    av_assert0(s != s1);
+
     // FIXME can parameters change on I-frames?
     // in that case dst may need a reinit
     if (!s->context_initialized) {
@@ -548,12 +550,12 @@
         if (s1->context_initialized){
             s->picture_range_start  += MAX_PICTURE_COUNT;
             s->picture_range_end    += MAX_PICTURE_COUNT;
-            ff_MPV_common_init(s);
+            if((err = ff_MPV_common_init(s)) < 0)
+                return err;
         }
     }
 
     if (s->height != s1->height || s->width != s1->width || s->context_reinit) {
-        int err;
         s->context_reinit = 0;
         s->height = s1->height;
         s->width  = s1->width;
@@ -570,10 +572,15 @@
     s->picture_number       = s1->picture_number;
     s->input_picture_number = s1->input_picture_number;
 
+    av_assert0(!s->picture || s->picture != s1->picture);
     memcpy(s->picture, s1->picture, s1->picture_count * sizeof(Picture));
     memcpy(&s->last_picture, &s1->last_picture,
            (char *) &s1->last_picture_ptr - (char *) &s1->last_picture);
 
+    // reset s->picture[].f.extended_data to s->picture[].f.data
+    for (i = 0; i < s->picture_count; i++)
+        s->picture[i].f.extended_data = s->picture[i].f.data;
+
     s->last_picture_ptr    = REBASE_PICTURE(s1->last_picture_ptr,    s, s1);
     s->current_picture_ptr = REBASE_PICTURE(s1->current_picture_ptr, s, s1);
     s->next_picture_ptr    = REBASE_PICTURE(s1->next_picture_ptr,    s, s1);
@@ -796,7 +803,7 @@
  */
 av_cold int ff_MPV_common_init(MpegEncContext *s)
 {
-    int i, err;
+    int i;
     int nb_slices = (HAVE_THREADS &&
                      s->avctx->active_thread_type & FF_THREAD_SLICE) ?
                     s->avctx->thread_count : 1;
@@ -809,9 +816,9 @@
     else if (s->codec_id != AV_CODEC_ID_H264)
         s->mb_height = (s->height + 15) / 16;
 
-    if (s->avctx->pix_fmt == PIX_FMT_NONE) {
+    if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) {
         av_log(s->avctx, AV_LOG_ERROR,
-               "decoding to PIX_FMT_NONE is not supported.\n");
+               "decoding to AV_PIX_FMT_NONE is not supported.\n");
         return -1;
     }
 
@@ -835,9 +842,8 @@
     s->flags  = s->avctx->flags;
     s->flags2 = s->avctx->flags2;
 
-        /* set chroma shifts */
-        avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &s->chroma_x_shift,
-                                      &s->chroma_y_shift);
+    /* set chroma shifts */
+    avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
 
     /* convert fourcc to upper case */
     s->codec_tag        = avpriv_toupper4(s->avctx->codec_tag);
@@ -874,7 +880,7 @@
         avcodec_get_frame_defaults(&s->picture[i].f);
     }
 
-        if ((err = init_context_frame(s)))
+        if (init_context_frame(s))
             goto fail;
 
         s->parse_context.state = -1;
@@ -1450,8 +1456,7 @@
     if (s->next_picture_ptr)
         ff_copy_picture(&s->next_picture, s->next_picture_ptr);
 
-    if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_FRAME) &&
-        (s->out_format != FMT_H264 || s->codec_id == AV_CODEC_ID_SVQ3)) {
+    if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_FRAME)) {
         if (s->next_picture_ptr)
             s->next_picture_ptr->owner2 = s;
         if (s->last_picture_ptr)
@@ -1519,8 +1524,9 @@
               !(s->flags & CODEC_FLAG_EMU_EDGE) &&
               !s->avctx->lowres
             ) {
-        int hshift = av_pix_fmt_descriptors[s->avctx->pix_fmt].log2_chroma_w;
-        int vshift = av_pix_fmt_descriptors[s->avctx->pix_fmt].log2_chroma_h;
+        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->avctx->pix_fmt);
+        int hshift = desc->log2_chroma_w;
+        int vshift = desc->log2_chroma_h;
         s->dsp.draw_edges(s->current_picture.f.data[0], s->current_picture.f.linesize[0],
                           s->h_edge_pos, s->v_edge_pos,
                           EDGE_WIDTH, EDGE_WIDTH,
@@ -1757,8 +1763,8 @@
                                    (s->codec_id == AV_CODEC_ID_H264 ? 0 : 1);
         s->low_delay = 0; // needed to see the vectors without trashing the buffers
 
-        avcodec_get_chroma_sub_sample(s->avctx->pix_fmt,
-                                      &h_chroma_shift, &v_chroma_shift);
+        avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
+
         for (i = 0; i < 3; i++) {
             size_t size= (i == 0) ? pict->linesize[i] * FFALIGN(height, 16):
                          pict->linesize[i] * FFALIGN(height, 16) >> v_chroma_shift;
@@ -1775,7 +1781,7 @@
             int mb_x;
             for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
                 const int mb_index = mb_x + mb_y * s->mb_stride;
-                if ((s->avctx->debug_mv) && pict->motion_val) {
+                if ((s->avctx->debug_mv) && pict->motion_val[0]) {
                     int type;
                     for (type = 0; type < 3; type++) {
                         int direction = 0;
@@ -1854,7 +1860,7 @@
                         }
                     }
                 }
-                if ((s->avctx->debug & FF_DEBUG_VIS_QP) && pict->motion_val) {
+                if ((s->avctx->debug & FF_DEBUG_VIS_QP)) {
                     uint64_t c = (pict->qscale_table[mb_index] * 128 / 31) *
                                  0x0101010101010101ULL;
                     int y;
@@ -1868,7 +1874,7 @@
                     }
                 }
                 if ((s->avctx->debug & FF_DEBUG_VIS_MB_TYPE) &&
-                    pict->motion_val) {
+                    pict->motion_val[0]) {
                     int mb_type = pict->mb_type[mb_index];
                     uint64_t u,v;
                     int y;
@@ -2087,17 +2093,17 @@
     if ((unsigned) src_x > FFMAX( h_edge_pos - (!!sx) - 2 * block_s,       0) ||
         (unsigned) src_y > FFMAX((v_edge_pos >> field_based) - (!!sy) - h, 0)) {
         s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr_y,
-                                s->linesize, 17, 17 + field_based,
+                                linesize >> field_based, 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;
-            s->dsp.emulated_edge_mc(uvbuf , ptr_cb, s->uvlinesize, 9,
+            s->dsp.emulated_edge_mc(uvbuf , ptr_cb, uvlinesize >> field_based, 9,
                                     9 + field_based,
                                     uvsrc_x, uvsrc_y << field_based,
                                     h_edge_pos >> 1, v_edge_pos >> 1);
-            s->dsp.emulated_edge_mc(uvbuf + 16, ptr_cr, s->uvlinesize, 9,
+            s->dsp.emulated_edge_mc(uvbuf + 16, ptr_cr, uvlinesize >> field_based, 9,
                                     9 + field_based,
                                     uvsrc_x, uvsrc_y << field_based,
                                     h_edge_pos >> 1, v_edge_pos >> 1);
@@ -2338,7 +2344,8 @@
     int my_max = INT_MIN, my_min = INT_MAX, qpel_shift = !s->quarter_sample;
     int my, off, i, mvs;
 
-    if (s->picture_structure != PICT_FRAME) goto unhandled;
+    if (s->picture_structure != PICT_FRAME || s->mcsel)
+        goto unhandled;
 
     switch (s->mv_type) {
         case MV_TYPE_16X16:
@@ -2708,9 +2715,10 @@
        && s->current_picture.f.reference
        && !s->intra_only
        && !(s->flags&CODEC_FLAG_EMU_EDGE)) {
+        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->avctx->pix_fmt);
         int sides = 0, edge_h;
-        int hshift = av_pix_fmt_descriptors[s->avctx->pix_fmt].log2_chroma_w;
-        int vshift = av_pix_fmt_descriptors[s->avctx->pix_fmt].log2_chroma_h;
+        int hshift = desc->log2_chroma_w;
+        int vshift = desc->log2_chroma_h;
         if (y==0) sides |= EDGE_TOP;
         if (y + h >= s->v_edge_pos) sides |= EDGE_BOTTOM;
 
diff --git a/libavcodec/mpegvideo.h b/libavcodec/mpegvideo.h
index 560ad02..b366899 100644
--- a/libavcodec/mpegvideo.h
+++ b/libavcodec/mpegvideo.h
@@ -60,7 +60,7 @@
 
 #define MAX_THREADS 32
 
-#define MAX_PICTURE_COUNT 32
+#define MAX_PICTURE_COUNT 34
 
 #define ME_MAP_SIZE 64
 #define ME_MAP_SHIFT 3
@@ -343,10 +343,12 @@
     int dquant;                 ///< qscale difference to prev qscale
     int closed_gop;             ///< MPEG1/2 GOP is closed
     int pict_type;              ///< AV_PICTURE_TYPE_I, AV_PICTURE_TYPE_P, AV_PICTURE_TYPE_B, ...
+    int vbv_delay;
     int last_pict_type; //FIXME removes
     int last_non_b_pict_type;   ///< used for mpeg4 gmc b-frames & ratecontrol
     int dropable;
     int frame_rate_index;
+    AVRational mpeg2_frame_rate_ext;
     int last_lambda_for[5];     ///< last lambda for a specific pict type
     int skipdct;                ///< skip dct and code zero residual
 
@@ -449,7 +451,7 @@
     uint8_t *luma_dc_vlc_length;
 #define UNI_AC_ENC_INDEX(run,level) ((run)*128 + (level))
 
-    int coded_score[8];
+    int coded_score[12];
 
     /** precomputed matrix (combine qscale and DCT renorm) */
     int (*q_intra_matrix)[64];
@@ -674,7 +676,7 @@
     DCTELEM (*pblocks[12])[64];
 
     DCTELEM (*block)[64]; ///< points to one of the following blocks
-    DCTELEM (*blocks)[8][64]; // for HQ mode we need to keep the best block
+    DCTELEM (*blocks)[12][64]; // for HQ mode we need to keep the best block
     int (*decode_mb)(struct MpegEncContext *s, DCTELEM block[6][64]); // used by some codecs to avoid a switch()
 #define SLICE_OK         0
 #define SLICE_ERROR     -1
@@ -775,7 +777,6 @@
 void ff_dct_encode_init_x86(MpegEncContext *s);
 void ff_MPV_common_init_x86(MpegEncContext *s);
 void ff_MPV_common_init_axp(MpegEncContext *s);
-void ff_MPV_common_init_mmi(MpegEncContext *s);
 void ff_MPV_common_init_arm(MpegEncContext *s);
 void ff_MPV_common_init_altivec(MpegEncContext *s);
 void ff_MPV_common_init_bfin(MpegEncContext *s);
@@ -820,8 +821,8 @@
  */
 int ff_alloc_picture(MpegEncContext *s, Picture *pic, int shared);
 
-extern const enum PixelFormat ff_pixfmt_list_420[];
-extern const enum PixelFormat ff_hwaccel_pixfmt_list_420[];
+extern const enum AVPixelFormat ff_pixfmt_list_420[];
+extern const enum AVPixelFormat ff_hwaccel_pixfmt_list_420[];
 
 static inline void ff_update_block_index(MpegEncContext *s){
     const int block_size= 8 >> s->avctx->lowres;
diff --git a/libavcodec/mpegvideo_enc.c b/libavcodec/mpegvideo_enc.c
index d7aad62..d942fdd 100644
--- a/libavcodec/mpegvideo_enc.c
+++ b/libavcodec/mpegvideo_enc.c
@@ -29,11 +29,13 @@
 
 #include "libavutil/intmath.h"
 #include "libavutil/mathematics.h"
+#include "libavutil/pixdesc.h"
 #include "libavutil/opt.h"
 #include "avcodec.h"
 #include "dsputil.h"
 #include "mpegvideo.h"
 #include "h263.h"
+#include "mathops.h"
 #include "mjpegenc.h"
 #include "msmpeg4.h"
 #include "faandct.h"
@@ -102,7 +104,7 @@
                  *           3444240 >= (1 << 36) / (x) >= 275 */
 
                 qmat[qscale][i] = (int)((UINT64_C(1) << (QMAT_SHIFT + 14)) /
-                                        (ff_aanscales[i] * qscale * quant_matrix[j]));
+                                        (ff_aanscales[i] * (int64_t)qscale * quant_matrix[j]));
             }
         } else {
             for (i = 0; i < 64; i++) {
@@ -293,23 +295,23 @@
 
     switch (avctx->codec_id) {
     case AV_CODEC_ID_MPEG2VIDEO:
-        if (avctx->pix_fmt != PIX_FMT_YUV420P &&
-            avctx->pix_fmt != PIX_FMT_YUV422P) {
+        if (avctx->pix_fmt != AV_PIX_FMT_YUV420P &&
+            avctx->pix_fmt != AV_PIX_FMT_YUV422P) {
             av_log(avctx, AV_LOG_ERROR,
                    "only YUV420 and YUV422 are supported\n");
             return -1;
         }
         break;
     case AV_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_BGR0     &&
-            avctx->pix_fmt != PIX_FMT_BGRA     &&
-            avctx->pix_fmt != PIX_FMT_BGR24    &&
-            ((avctx->pix_fmt != PIX_FMT_YUV420P &&
-              avctx->pix_fmt != PIX_FMT_YUV422P &&
-              avctx->pix_fmt != PIX_FMT_YUV444P) ||
+        if (avctx->pix_fmt != AV_PIX_FMT_YUVJ420P &&
+            avctx->pix_fmt != AV_PIX_FMT_YUVJ422P &&
+            avctx->pix_fmt != AV_PIX_FMT_YUVJ444P &&
+            avctx->pix_fmt != AV_PIX_FMT_BGR0     &&
+            avctx->pix_fmt != AV_PIX_FMT_BGRA     &&
+            avctx->pix_fmt != AV_PIX_FMT_BGR24    &&
+            ((avctx->pix_fmt != AV_PIX_FMT_YUV420P &&
+              avctx->pix_fmt != AV_PIX_FMT_YUV422P &&
+              avctx->pix_fmt != AV_PIX_FMT_YUV444P) ||
              avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL)) {
             av_log(avctx, AV_LOG_ERROR, "colorspace not supported in LJPEG\n");
             return -1;
@@ -317,29 +319,35 @@
         break;
     case AV_CODEC_ID_MJPEG:
     case AV_CODEC_ID_AMV:
-        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) ||
+        if (avctx->pix_fmt != AV_PIX_FMT_YUVJ420P &&
+            avctx->pix_fmt != AV_PIX_FMT_YUVJ422P &&
+            avctx->pix_fmt != AV_PIX_FMT_YUVJ444P &&
+            ((avctx->pix_fmt != AV_PIX_FMT_YUV420P &&
+              avctx->pix_fmt != AV_PIX_FMT_YUV422P &&
+              avctx->pix_fmt != AV_PIX_FMT_YUV444P) ||
              avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL)) {
             av_log(avctx, AV_LOG_ERROR, "colorspace not supported in jpeg\n");
             return -1;
         }
         break;
     default:
-        if (avctx->pix_fmt != PIX_FMT_YUV420P) {
+        if (avctx->pix_fmt != AV_PIX_FMT_YUV420P) {
             av_log(avctx, AV_LOG_ERROR, "only YUV420 is supported\n");
             return -1;
         }
     }
 
     switch (avctx->pix_fmt) {
-    case PIX_FMT_YUVJ422P:
-    case PIX_FMT_YUV422P:
+    case AV_PIX_FMT_YUVJ444P:
+    case AV_PIX_FMT_YUV444P:
+        s->chroma_format = CHROMA_444;
+        break;
+    case AV_PIX_FMT_YUVJ422P:
+    case AV_PIX_FMT_YUV422P:
         s->chroma_format = CHROMA_422;
         break;
-    case PIX_FMT_YUVJ420P:
-    case PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUVJ420P:
+    case AV_PIX_FMT_YUV420P:
     default:
         s->chroma_format = CHROMA_420;
         break;
@@ -402,6 +410,32 @@
 
     s->loop_filter      = !!(s->flags & CODEC_FLAG_LOOP_FILTER);
 
+    if (avctx->rc_max_rate && !avctx->rc_buffer_size) {
+        switch(avctx->codec_id) {
+        case AV_CODEC_ID_MPEG1VIDEO:
+        case AV_CODEC_ID_MPEG2VIDEO:
+            avctx->rc_buffer_size = FFMAX(avctx->rc_max_rate, 15000000) * 112L / 15000000 * 16384;
+            break;
+        case AV_CODEC_ID_MPEG4:
+        case AV_CODEC_ID_MSMPEG4V1:
+        case AV_CODEC_ID_MSMPEG4V2:
+        case AV_CODEC_ID_MSMPEG4V3:
+            if       (avctx->rc_max_rate >= 15000000) {
+                avctx->rc_buffer_size = 320 + (avctx->rc_max_rate - 15000000L) * (760-320) / (38400000 - 15000000);
+            } else if(avctx->rc_max_rate >=  2000000) {
+                avctx->rc_buffer_size =  80 + (avctx->rc_max_rate -  2000000L) * (320- 80) / (15000000 -  2000000);
+            } else if(avctx->rc_max_rate >=   384000) {
+                avctx->rc_buffer_size =  40 + (avctx->rc_max_rate -   384000L) * ( 80- 40) / ( 2000000 -   384000);
+            } else
+                avctx->rc_buffer_size = 40;
+            avctx->rc_buffer_size *= 16384;
+            break;
+        }
+        if (avctx->rc_buffer_size) {
+            av_log(avctx, AV_LOG_INFO, "Automatically choosing VBV buffer size of %d kbyte\n", avctx->rc_buffer_size/8192);
+        }
+    }
+
     if ((!avctx->rc_max_rate) != (!avctx->rc_buffer_size)) {
         av_log(avctx, AV_LOG_ERROR, "Either both buffer size and max rate or neither must be specified\n");
         if (avctx->rc_max_rate && !avctx->rc_buffer_size)
@@ -660,8 +694,7 @@
 
     av_log(avctx, AV_LOG_DEBUG, "intra_quant_bias = %d inter_quant_bias = %d\n",s->intra_quant_bias,s->inter_quant_bias);
 
-    avcodec_get_chroma_sub_sample(avctx->pix_fmt, &chroma_h_shift,
-                                  &chroma_v_shift);
+    avcodec_get_chroma_sub_sample(avctx->pix_fmt, &chroma_h_shift, &chroma_v_shift);
 
     if (avctx->codec_id == AV_CODEC_ID_MPEG4 &&
         s->avctx->time_base.den > (1 << 16) - 1) {
@@ -701,9 +734,9 @@
         s->out_format = FMT_MJPEG;
         s->intra_only = 1; /* force intra only for jpeg */
         if (avctx->codec->id == AV_CODEC_ID_LJPEG &&
-            (avctx->pix_fmt == PIX_FMT_BGR0
-             || s->avctx->pix_fmt == PIX_FMT_BGRA
-             || s->avctx->pix_fmt == PIX_FMT_BGR24)) {
+            (avctx->pix_fmt == AV_PIX_FMT_BGR0
+             || s->avctx->pix_fmt == AV_PIX_FMT_BGRA
+             || s->avctx->pix_fmt == AV_PIX_FMT_BGR24)) {
             s->mjpeg_vsample[0] = s->mjpeg_hsample[0] =
             s->mjpeg_vsample[1] = s->mjpeg_hsample[1] =
             s->mjpeg_vsample[2] = s->mjpeg_hsample[2] = 1;
@@ -1047,8 +1080,7 @@
             // empty
         } else {
             int h_chroma_shift, v_chroma_shift;
-            avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift,
-                                          &v_chroma_shift);
+            avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
 
             for (i = 0; i < 3; i++) {
                 int src_stride = pic_arg->linesize[i];
@@ -1175,7 +1207,7 @@
     c->me_cmp       = s->avctx->me_cmp;
     c->mb_cmp       = s->avctx->mb_cmp;
     c->me_sub_cmp   = s->avctx->me_sub_cmp;
-    c->pix_fmt      = PIX_FMT_YUV420P;
+    c->pix_fmt      = AV_PIX_FMT_YUV420P;
     c->time_base    = s->avctx->time_base;
     c->max_b_frames = s->max_b_frames;
 
@@ -1500,7 +1532,8 @@
 
         s->pict_type = s->new_picture.f.pict_type;
         //emms_c();
-        ff_MPV_frame_start(s, avctx);
+        if (ff_MPV_frame_start(s, avctx) < 0)
+            return -1;
 vbv_retry:
         if (encode_picture(s, s->picture_number) < 0)
             return -1;
@@ -1781,15 +1814,17 @@
 static av_always_inline void encode_mb_internal(MpegEncContext *s,
                                                 int motion_x, int motion_y,
                                                 int mb_block_height,
+                                                int mb_block_width,
                                                 int mb_block_count)
 {
-    int16_t weight[8][64];
-    DCTELEM orig[8][64];
+    int16_t weight[12][64];
+    DCTELEM orig[12][64];
     const int mb_x = s->mb_x;
     const int mb_y = s->mb_y;
     int i;
-    int skip_dct[8];
+    int skip_dct[12];
     int dct_offset = s->linesize * 8; // default for progressive frames
+    int uv_dct_offset = s->uvlinesize * 8;
     uint8_t *ptr_y, *ptr_cb, *ptr_cr;
     int wrap_y, wrap_c;
 
@@ -1831,20 +1866,20 @@
     ptr_y  = s->new_picture.f.data[0] +
              (mb_y * 16 * wrap_y)              + mb_x * 16;
     ptr_cb = s->new_picture.f.data[1] +
-             (mb_y * mb_block_height * wrap_c) + mb_x * 8;
+             (mb_y * mb_block_height * wrap_c) + mb_x * mb_block_width;
     ptr_cr = s->new_picture.f.data[2] +
-             (mb_y * mb_block_height * wrap_c) + mb_x * 8;
+             (mb_y * mb_block_height * wrap_c) + mb_x * mb_block_width;
 
     if((mb_x*16+16 > s->width || mb_y*16+16 > s->height) && s->codec_id != AV_CODEC_ID_AMV){
         uint8_t *ebuf = s->edge_emu_buffer + 32;
         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;
-        s->dsp.emulated_edge_mc(ebuf + 18 * wrap_y, ptr_cb, wrap_c, 8,
+        s->dsp.emulated_edge_mc(ebuf + 18 * wrap_y, ptr_cb, wrap_c, mb_block_width,
                                 mb_block_height, mb_x * 8, mb_y * 8,
                                 (s->width+1) >> 1, (s->height+1) >> 1);
         ptr_cb = ebuf + 18 * wrap_y;
-        s->dsp.emulated_edge_mc(ebuf + 18 * wrap_y + 8, ptr_cr, wrap_c, 8,
+        s->dsp.emulated_edge_mc(ebuf + 18 * wrap_y + 8, ptr_cr, wrap_c, mb_block_width,
                                 mb_block_height, mb_x * 8, mb_y * 8,
                                 (s->width+1) >> 1, (s->height+1) >> 1);
         ptr_cr = ebuf + 18 * wrap_y + 8;
@@ -1869,8 +1904,10 @@
                     s->interlaced_dct = 1;
 
                     dct_offset = wrap_y;
+                    uv_dct_offset = wrap_c;
                     wrap_y <<= 1;
-                    if (s->chroma_format == CHROMA_422)
+                    if (s->chroma_format == CHROMA_422 ||
+                        s->chroma_format == CHROMA_444)
                         wrap_c <<= 1;
                 }
             }
@@ -1887,11 +1924,16 @@
         } else {
             s->dsp.get_pixels(s->block[4], ptr_cb, wrap_c);
             s->dsp.get_pixels(s->block[5], ptr_cr, wrap_c);
-            if (!s->chroma_y_shift) { /* 422 */
-                s->dsp.get_pixels(s->block[6],
-                                  ptr_cb + (dct_offset >> 1), wrap_c);
-                s->dsp.get_pixels(s->block[7],
-                                  ptr_cr + (dct_offset >> 1), wrap_c);
+            if (!s->chroma_y_shift && s->chroma_x_shift) { /* 422 */
+                s->dsp.get_pixels(s->block[6], ptr_cb + uv_dct_offset, wrap_c);
+                s->dsp.get_pixels(s->block[7], ptr_cr + uv_dct_offset, wrap_c);
+            } else if (!s->chroma_y_shift && !s->chroma_x_shift) { /* 444 */
+                s->dsp.get_pixels(s->block[6], ptr_cb + 8, wrap_c);
+                s->dsp.get_pixels(s->block[7], ptr_cr + 8, wrap_c);
+                s->dsp.get_pixels(s->block[8], ptr_cb + uv_dct_offset, wrap_c);
+                s->dsp.get_pixels(s->block[9], ptr_cr + uv_dct_offset, wrap_c);
+                s->dsp.get_pixels(s->block[10], ptr_cb + uv_dct_offset + 8, wrap_c);
+                s->dsp.get_pixels(s->block[11], ptr_cr + uv_dct_offset + 8, wrap_c);
             }
         }
     } else {
@@ -1950,6 +1992,7 @@
                     s->interlaced_dct = 1;
 
                     dct_offset = wrap_y;
+                    uv_dct_offset = wrap_c;
                     wrap_y <<= 1;
                     if (s->chroma_format == CHROMA_422)
                         wrap_c <<= 1;
@@ -1971,10 +2014,10 @@
             s->dsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
             s->dsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
             if (!s->chroma_y_shift) { /* 422 */
-                s->dsp.diff_pixels(s->block[6], ptr_cb + (dct_offset >> 1),
-                                   dest_cb + (dct_offset >> 1), wrap_c);
-                s->dsp.diff_pixels(s->block[7], ptr_cr + (dct_offset >> 1),
-                                   dest_cr + (dct_offset >> 1), wrap_c);
+                s->dsp.diff_pixels(s->block[6], ptr_cb + uv_dct_offset,
+                                   dest_cb + uv_dct_offset, wrap_c);
+                s->dsp.diff_pixels(s->block[7], ptr_cr + uv_dct_offset,
+                                   dest_cr + uv_dct_offset, wrap_c);
             }
         }
         /* pre quantization */
@@ -2001,12 +2044,12 @@
                               wrap_c, 8) < 20 * s->qscale)
                 skip_dct[5] = 1;
             if (!s->chroma_y_shift) { /* 422 */
-                if (s->dsp.sad[1](NULL, ptr_cb + (dct_offset >> 1),
-                                  dest_cb + (dct_offset >> 1),
+                if (s->dsp.sad[1](NULL, ptr_cb + uv_dct_offset,
+                                  dest_cb + uv_dct_offset,
                                   wrap_c, 8) < 20 * s->qscale)
                     skip_dct[6] = 1;
-                if (s->dsp.sad[1](NULL, ptr_cr + (dct_offset >> 1),
-                                  dest_cr + (dct_offset >> 1),
+                if (s->dsp.sad[1](NULL, ptr_cr + uv_dct_offset,
+                                  dest_cr + uv_dct_offset,
                                   wrap_c, 8) < 20 * s->qscale)
                     skip_dct[7] = 1;
             }
@@ -2028,10 +2071,10 @@
             get_visual_weight(weight[5], ptr_cr                , wrap_c);
         if (!s->chroma_y_shift) { /* 422 */
             if (!skip_dct[6])
-                get_visual_weight(weight[6], ptr_cb + (dct_offset >> 1),
+                get_visual_weight(weight[6], ptr_cb + uv_dct_offset,
                                   wrap_c);
             if (!skip_dct[7])
-                get_visual_weight(weight[7], ptr_cr + (dct_offset >> 1),
+                get_visual_weight(weight[7], ptr_cr + uv_dct_offset,
                                   wrap_c);
         }
         memcpy(orig[0], s->block[0], sizeof(DCTELEM) * 64 * mb_block_count);
@@ -2145,8 +2188,9 @@
 
 static av_always_inline void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
 {
-    if (s->chroma_format == CHROMA_420) encode_mb_internal(s, motion_x, motion_y,  8, 6);
-    else                                encode_mb_internal(s, motion_x, motion_y, 16, 8);
+    if (s->chroma_format == CHROMA_420) encode_mb_internal(s, motion_x, motion_y,  8, 8, 6);
+    else if (s->chroma_format == CHROMA_422) encode_mb_internal(s, motion_x, motion_y, 16, 8, 8);
+    else encode_mb_internal(s, motion_x, motion_y, 16, 16, 12);
 }
 
 static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
@@ -4233,7 +4277,7 @@
     .init           = ff_MPV_encode_init,
     .encode2        = ff_MPV_encode_picture,
     .close          = ff_MPV_encode_end,
-    .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
+    .pix_fmts= (const enum AVPixelFormat[]){AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE},
     .long_name= NULL_IF_CONFIG_SMALL("H.263 / H.263-1996"),
     .priv_class     = &h263_class,
 };
@@ -4262,7 +4306,7 @@
     .encode2        = ff_MPV_encode_picture,
     .close          = ff_MPV_encode_end,
     .capabilities   = CODEC_CAP_SLICE_THREADS,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUV420P, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("H.263+ / H.263-1998 / H.263 version 2"),
     .priv_class     = &h263p_class,
 };
@@ -4277,7 +4321,7 @@
     .init           = ff_MPV_encode_init,
     .encode2        = ff_MPV_encode_picture,
     .close          = ff_MPV_encode_end,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUV420P, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 2"),
     .priv_class     = &msmpeg4v2_class,
 };
@@ -4292,7 +4336,7 @@
     .init           = ff_MPV_encode_init,
     .encode2        = ff_MPV_encode_picture,
     .close          = ff_MPV_encode_end,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUV420P, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 3"),
     .priv_class     = &msmpeg4v3_class,
 };
@@ -4307,7 +4351,7 @@
     .init           = ff_MPV_encode_init,
     .encode2        = ff_MPV_encode_picture,
     .close          = ff_MPV_encode_end,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUV420P, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Video 7"),
     .priv_class     = &wmv1_class,
 };
diff --git a/libavcodec/mpegvideo_motion.c b/libavcodec/mpegvideo_motion.c
index 2e5f7e6..18e6428 100644
--- a/libavcodec/mpegvideo_motion.c
+++ b/libavcodec/mpegvideo_motion.c
@@ -178,20 +178,19 @@
                                   op_pixels_func *pix_op,
                                   int motion_x, int motion_y)
 {
-    int dxy;
+    int dxy = 0;
     int emu=0;
 
-    dxy = ((motion_y & 1) << 1) | (motion_x & 1);
     src_x += motion_x >> 1;
     src_y += motion_y >> 1;
 
     /* WARNING: do no forget half pels */
     src_x = av_clip(src_x, -16, s->width); //FIXME unneeded for emu?
-    if (src_x == s->width)
-        dxy &= ~1;
+    if (src_x != s->width)
+        dxy |= motion_x & 1;
     src_y = av_clip(src_y, -16, s->height);
-    if (src_y == s->height)
-        dxy &= ~2;
+    if (src_y != s->height)
+        dxy |= (motion_y & 1) << 1;
     src += src_y * s->linesize + src_x;
 
     if(s->unrestricted_mv && (s->flags&CODEC_FLAG_EMU_EDGE)){
@@ -639,37 +638,45 @@
     prefetch_motion(s, ref_picture, dir);
 
     if(!is_mpeg12 && s->obmc && s->pict_type != AV_PICTURE_TYPE_B){
-        int16_t mv_cache[4][4][2];
+        LOCAL_ALIGNED_8(int16_t, mv_cache, [4], [4][2]);
+        AVFrame *cur_frame = &s->current_picture.f;
         const int xy= s->mb_x + s->mb_y*s->mb_stride;
         const int mot_stride= s->b8_stride;
         const int mot_xy= mb_x*2 + mb_y*2*mot_stride;
 
         av_assert2(!s->mb_skipped);
 
-        memcpy(mv_cache[1][1], s->current_picture.f.motion_val[0][mot_xy             ], sizeof(int16_t) * 4);
-        memcpy(mv_cache[2][1], s->current_picture.f.motion_val[0][mot_xy + mot_stride], sizeof(int16_t) * 4);
-        memcpy(mv_cache[3][1], s->current_picture.f.motion_val[0][mot_xy + mot_stride], sizeof(int16_t) * 4);
+        AV_COPY32(mv_cache[1][1], cur_frame->motion_val[0][mot_xy    ]);
+        AV_COPY32(mv_cache[1][2], cur_frame->motion_val[0][mot_xy + 1]);
 
-        if (mb_y == 0 || IS_INTRA(s->current_picture.f.mb_type[xy - s->mb_stride])) {
-            memcpy(mv_cache[0][1], mv_cache[1][1], sizeof(int16_t)*4);
+        AV_COPY32(mv_cache[2][1], cur_frame->motion_val[0][mot_xy + mot_stride    ]);
+        AV_COPY32(mv_cache[2][2], cur_frame->motion_val[0][mot_xy + mot_stride + 1]);
+
+        AV_COPY32(mv_cache[3][1], cur_frame->motion_val[0][mot_xy + mot_stride    ]);
+        AV_COPY32(mv_cache[3][2], cur_frame->motion_val[0][mot_xy + mot_stride + 1]);
+
+        if (mb_y == 0 || IS_INTRA(cur_frame->mb_type[xy - s->mb_stride])) {
+            AV_COPY32(mv_cache[0][1], mv_cache[1][1]);
+            AV_COPY32(mv_cache[0][2], mv_cache[1][2]);
         }else{
-            memcpy(mv_cache[0][1], s->current_picture.f.motion_val[0][mot_xy - mot_stride], sizeof(int16_t) * 4);
+            AV_COPY32(mv_cache[0][1], cur_frame->motion_val[0][mot_xy - mot_stride    ]);
+            AV_COPY32(mv_cache[0][2], cur_frame->motion_val[0][mot_xy - mot_stride + 1]);
         }
 
-        if (mb_x == 0 || IS_INTRA(s->current_picture.f.mb_type[xy - 1])) {
+        if (mb_x == 0 || IS_INTRA(cur_frame->mb_type[xy - 1])) {
             AV_COPY32(mv_cache[1][0], mv_cache[1][1]);
             AV_COPY32(mv_cache[2][0], mv_cache[2][1]);
         }else{
-            AV_COPY32(mv_cache[1][0], s->current_picture.f.motion_val[0][mot_xy - 1]);
-            AV_COPY32(mv_cache[2][0], s->current_picture.f.motion_val[0][mot_xy - 1 + mot_stride]);
+            AV_COPY32(mv_cache[1][0], cur_frame->motion_val[0][mot_xy - 1]);
+            AV_COPY32(mv_cache[2][0], cur_frame->motion_val[0][mot_xy - 1 + mot_stride]);
         }
 
-        if (mb_x + 1 >= s->mb_width || IS_INTRA(s->current_picture.f.mb_type[xy + 1])) {
+        if (mb_x + 1 >= s->mb_width || IS_INTRA(cur_frame->mb_type[xy + 1])) {
             AV_COPY32(mv_cache[1][3], mv_cache[1][2]);
             AV_COPY32(mv_cache[2][3], mv_cache[2][2]);
         }else{
-            AV_COPY32(mv_cache[1][3], s->current_picture.f.motion_val[0][mot_xy + 2]);
-            AV_COPY32(mv_cache[2][3], s->current_picture.f.motion_val[0][mot_xy + 2 + mot_stride]);
+            AV_COPY32(mv_cache[1][3], cur_frame->motion_val[0][mot_xy + 2]);
+            AV_COPY32(mv_cache[2][3], cur_frame->motion_val[0][mot_xy + 2 + mot_stride]);
         }
 
         mx = 0;
diff --git a/libavcodec/mpegvideo_parser.c b/libavcodec/mpegvideo_parser.c
index a9ed81b..c112a94 100644
--- a/libavcodec/mpegvideo_parser.c
+++ b/libavcodec/mpegvideo_parser.c
@@ -43,6 +43,8 @@
     int top_field_first, repeat_first_field, progressive_frame;
     int horiz_size_ext, vert_size_ext, bit_rate_ext;
     int did_set_size=0;
+    int bit_rate = 0;
+    int vbv_delay = 0;
 //FIXME replace the crap with get_bits()
     s->repeat_pict = 0;
 
@@ -54,6 +56,7 @@
         case PICTURE_START_CODE:
             if (bytes_left >= 2) {
                 s->pict_type = (buf[1] >> 3) & 7;
+                vbv_delay = ((buf[1] & 0x07) << 13) | (buf[2] << 5) | (buf[3]  >> 3);
             }
             break;
         case SEQ_START_CODE:
@@ -65,9 +68,9 @@
                     did_set_size=1;
                 }
                 frame_rate_index = buf[3] & 0xf;
-                pc->frame_rate.den = avctx->time_base.den = avpriv_frame_rate_tab[frame_rate_index].num;
-                pc->frame_rate.num = avctx->time_base.num = avpriv_frame_rate_tab[frame_rate_index].den;
-                avctx->bit_rate = ((buf[4]<<10) | (buf[5]<<2) | (buf[6]>>6))*400;
+                pc->frame_rate.den = avctx->time_base.den = ff_mpeg12_frame_rate_tab[frame_rate_index].num;
+                pc->frame_rate.num = avctx->time_base.num = ff_mpeg12_frame_rate_tab[frame_rate_index].den;
+                bit_rate = (buf[4]<<10) | (buf[5]<<2) | (buf[6]>>6);
                 avctx->codec_id = AV_CODEC_ID_MPEG1VIDEO;
             }
             break;
@@ -87,7 +90,7 @@
 
                         pc->width  |=(horiz_size_ext << 12);
                         pc->height |=( vert_size_ext << 12);
-                        avctx->bit_rate += (bit_rate_ext << 18) * 400;
+                        bit_rate = (bit_rate&0x3FFFF) | (bit_rate_ext << 18);
                         if(did_set_size)
                             avcodec_set_dimensions(avctx, pc->width, pc->height);
                         avctx->time_base.den = pc->frame_rate.den * (frame_rate_ext_n + 1) * 2;
@@ -130,6 +133,12 @@
         }
     }
  the_end: ;
+    if (avctx->codec_id == AV_CODEC_ID_MPEG2VIDEO && bit_rate) {
+        avctx->rc_max_rate = 400*bit_rate;
+    } else if (avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO && bit_rate &&
+               (bit_rate != 0x3FFFF || vbv_delay != 0xFFFF)) {
+        avctx->bit_rate = 400*bit_rate;
+    }
 }
 
 static int mpegvideo_parse(AVCodecParserContext *s,
diff --git a/libavcodec/msmpeg4.c b/libavcodec/msmpeg4.c
index 0f8b57e..e80db6d 100644
--- a/libavcodec/msmpeg4.c
+++ b/libavcodec/msmpeg4.c
@@ -36,6 +36,7 @@
 #include "mpeg4video.h"
 #include "msmpeg4data.h"
 #include "vc1data.h"
+#include "libavutil/imgutils.h"
 
 /*
  * You can also call this codec : MPEG4 with a twist !
@@ -61,6 +62,9 @@
 {
         int level, uni_code, uni_len;
 
+        if(ff_v2_dc_chroma_table[255 + 256][1])
+            return;
+
         for(level=-256; level<256; level++){
             int size, v, l;
             /* find number of bits */
@@ -113,8 +117,6 @@
 
 av_cold void ff_msmpeg4_common_init(MpegEncContext *s)
 {
-    static int initialized=0;
-
     switch(s->msmpeg4_version){
     case 1:
     case 2:
@@ -153,11 +155,7 @@
     }
     //Note the default tables are set in common_init in mpegvideo.c
 
-    if(!initialized){
-        initialized=1;
-
-        init_h263_dc_for_msmpeg4();
-    }
+    init_h263_dc_for_msmpeg4();
 }
 
 /* predict coded block */
@@ -592,18 +590,19 @@
 av_cold int ff_msmpeg4_decode_init(AVCodecContext *avctx)
 {
     MpegEncContext *s = avctx->priv_data;
-    static int done = 0;
-    int i;
+    static volatile int done = 0;
+    int i, ret;
     MVTable *mv;
 
+    if ((ret = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0)
+        return ret;
+
     if (ff_h263_decode_init(avctx) < 0)
         return -1;
 
     ff_msmpeg4_common_init(s);
 
     if (!done) {
-        done = 1;
-
         for(i=0;i<NB_RL_TABLES;i++) {
             ff_init_rl(&ff_rl_table[i], ff_static_rl_table_store[i]);
         }
@@ -673,6 +672,7 @@
         INIT_VLC_STATIC(&ff_inter_intra_vlc, INTER_INTRA_VLC_BITS, 4,
                  &ff_table_inter_intra[0][1], 2, 1,
                  &ff_table_inter_intra[0][0], 2, 1, 8);
+        done = 1;
     }
 
     switch(s->msmpeg4_version){
diff --git a/libavcodec/msrle.c b/libavcodec/msrle.c
index 7c965d2..2792f8b 100644
--- a/libavcodec/msrle.c
+++ b/libavcodec/msrle.c
@@ -56,14 +56,14 @@
 
     switch (avctx->bits_per_coded_sample) {
     case 1:
-        avctx->pix_fmt = PIX_FMT_MONOWHITE;
+        avctx->pix_fmt = AV_PIX_FMT_MONOWHITE;
         break;
     case 4:
     case 8:
-        avctx->pix_fmt = PIX_FMT_PAL8;
+        avctx->pix_fmt = AV_PIX_FMT_PAL8;
         break;
     case 24:
-        avctx->pix_fmt = PIX_FMT_BGR24;
+        avctx->pix_fmt = AV_PIX_FMT_BGR24;
         break;
     default:
         av_log(avctx, AV_LOG_ERROR, "unsupported bits per sample\n");
@@ -75,7 +75,7 @@
 
     if (avctx->extradata_size >= AVPALETTE_SIZE)
         for (i = 0; i < AVPALETTE_SIZE/4; i++)
-            s->pal[i] = 0xFF<<24 | AV_RL32(avctx->extradata+4*i);
+            s->pal[i] = 0xFFU<<24 | AV_RL32(avctx->extradata+4*i);
 
     return 0;
 }
diff --git a/libavcodec/mss1.c b/libavcodec/mss1.c
index c90485b..6a55b4f 100644
--- a/libavcodec/mss1.c
+++ b/libavcodec/mss1.c
@@ -129,7 +129,7 @@
         r = arith_get_bits(acoder, 8);
         g = arith_get_bits(acoder, 8);
         b = arith_get_bits(acoder, 8);
-        *pal++ = (0xFF << 24) | (r << 16) | (g << 8) | b;
+        *pal++ = (0xFFU << 24) | (r << 16) | (g << 8) | b;
     }
 
     return !!ncol;
@@ -197,7 +197,7 @@
 
     ret = ff_mss12_decode_init(&c->ctx, 0, &c->sc, NULL);
 
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     return ret;
 }
diff --git a/libavcodec/mss12.c b/libavcodec/mss12.c
index b8df225..59294b8 100644
--- a/libavcodec/mss12.c
+++ b/libavcodec/mss12.c
@@ -645,7 +645,7 @@
     }
 
     for (i = 0; i < 256; i++)
-        c->pal[i] = 0xFF << 24 | AV_RB24(avctx->extradata + 52 +
+        c->pal[i] = 0xFFU << 24 | AV_RB24(avctx->extradata + 52 +
                             (version ? 8 : 0) + i * 3);
 
     c->mask_stride = FFALIGN(avctx->width, 16);
diff --git a/libavcodec/mss2.c b/libavcodec/mss2.c
index ceb0a45..caeb800 100644
--- a/libavcodec/mss2.c
+++ b/libavcodec/mss2.c
@@ -396,11 +396,11 @@
         return AVERROR_INVALIDDATA;
     }
 
-    avctx->pix_fmt = PIX_FMT_YUV420P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV420P;
 
     if (ff_MPV_frame_start(s, avctx) < 0) {
         av_log(v->s.avctx, AV_LOG_ERROR, "ff_MPV_frame_start error\n");
-        avctx->pix_fmt = PIX_FMT_RGB24;
+        avctx->pix_fmt = AV_PIX_FMT_RGB24;
         return -1;
     }
 
@@ -448,7 +448,7 @@
                                 f->data[1], f->data[2], f->linesize[1],
                                 w, h);
 
-    avctx->pix_fmt = PIX_FMT_RGB24;
+    avctx->pix_fmt = AV_PIX_FMT_RGB24;
 
     return 0;
 }
@@ -474,7 +474,7 @@
     int keyframe, has_wmv9, has_mv, is_rle, is_555, ret;
 
     Rectangle wmv9rects[MAX_WMV9_RECTANGLES], *r;
-    int used_rects = 0, i, implicit_rect, av_uninit(wmv9_mask);
+    int used_rects = 0, i, implicit_rect = 0, av_uninit(wmv9_mask);
 
     av_assert0(FF_INPUT_BUFFER_PADDING_SIZE >=
                ARITH2_PADDING + (MIN_CACHE_BITS + 7) / 8);
@@ -519,7 +519,7 @@
     if (is_555 && (has_wmv9 || has_mv || c->slice_split && ctx->split_position))
         return AVERROR_INVALIDDATA;
 
-    avctx->pix_fmt = is_555 ? PIX_FMT_RGB555 : PIX_FMT_RGB24;
+    avctx->pix_fmt = is_555 ? AV_PIX_FMT_RGB555 : AV_PIX_FMT_RGB24;
     if (ctx->pic.data[0] && ctx->pic.format != avctx->pix_fmt)
         avctx->release_buffer(avctx, &ctx->pic);
 
@@ -650,25 +650,6 @@
             return AVERROR_INVALIDDATA;
 
         buf_size -= bytestream2_tell(&gB);
-    } else if (is_rle) {
-        init_get_bits(&gb, buf, buf_size * 8);
-        if (ret = decode_rle(&gb, c->pal_pic, c->pal_stride,
-                             c->rgb_pic, c->rgb_stride, c->pal, keyframe,
-                             ctx->split_position, 0,
-                             avctx->width, avctx->height))
-            return ret;
-        align_get_bits(&gb);
-
-        if (c->slice_split)
-            if (ret = decode_rle(&gb, c->pal_pic, c->pal_stride,
-                                 c->rgb_pic, c->rgb_stride, c->pal, keyframe,
-                                 ctx->split_position, 1,
-                                 avctx->width, avctx->height))
-                return ret;
-
-        align_get_bits(&gb);
-        buf      += get_bits_count(&gb) >> 3;
-        buf_size -= get_bits_count(&gb) >> 3;
     } else {
         if (keyframe) {
             c->corrupted = 0;
@@ -676,32 +657,54 @@
             if (c->slice_split)
                 ff_mss12_slicecontext_reset(&ctx->sc[1]);
         }
-        else if (c->corrupted)
-            return AVERROR_INVALIDDATA;
-        bytestream2_init(&gB, buf, buf_size + ARITH2_PADDING);
-        arith2_init(&acoder, &gB);
-        c->keyframe = keyframe;
-        if (c->corrupted = ff_mss12_decode_rect(&ctx->sc[0], &acoder, 0, 0,
-                                                avctx->width,
-                                                ctx->split_position))
-            return AVERROR_INVALIDDATA;
+        if (is_rle) {
+            init_get_bits(&gb, buf, buf_size * 8);
+            if (ret = decode_rle(&gb, c->pal_pic, c->pal_stride,
+                                 c->rgb_pic, c->rgb_stride, c->pal, keyframe,
+                                 ctx->split_position, 0,
+                                 avctx->width, avctx->height))
+                return ret;
+            align_get_bits(&gb);
 
-        buf      += arith2_get_consumed_bytes(&acoder);
-        buf_size -= arith2_get_consumed_bytes(&acoder);
-        if (c->slice_split) {
-            if (buf_size < 1)
+            if (c->slice_split)
+                if (ret = decode_rle(&gb, c->pal_pic, c->pal_stride,
+                                     c->rgb_pic, c->rgb_stride, c->pal, keyframe,
+                                     ctx->split_position, 1,
+                                     avctx->width, avctx->height))
+                    return ret;
+
+            align_get_bits(&gb);
+            buf      += get_bits_count(&gb) >> 3;
+            buf_size -= get_bits_count(&gb) >> 3;
+        } else if (!implicit_rect || wmv9_mask != -1) {
+            if (c->corrupted)
                 return AVERROR_INVALIDDATA;
             bytestream2_init(&gB, buf, buf_size + ARITH2_PADDING);
             arith2_init(&acoder, &gB);
-            if (c->corrupted = ff_mss12_decode_rect(&ctx->sc[1], &acoder, 0,
-                                                    ctx->split_position,
+            c->keyframe = keyframe;
+            if (c->corrupted = ff_mss12_decode_rect(&ctx->sc[0], &acoder, 0, 0,
                                                     avctx->width,
-                                                    avctx->height - ctx->split_position))
+                                                    ctx->split_position))
                 return AVERROR_INVALIDDATA;
 
             buf      += arith2_get_consumed_bytes(&acoder);
             buf_size -= arith2_get_consumed_bytes(&acoder);
-        }
+            if (c->slice_split) {
+                if (buf_size < 1)
+                    return AVERROR_INVALIDDATA;
+                bytestream2_init(&gB, buf, buf_size + ARITH2_PADDING);
+                arith2_init(&acoder, &gB);
+                if (c->corrupted = ff_mss12_decode_rect(&ctx->sc[1], &acoder, 0,
+                                                        ctx->split_position,
+                                                        avctx->width,
+                                                        avctx->height - ctx->split_position))
+                    return AVERROR_INVALIDDATA;
+
+                buf      += arith2_get_consumed_bytes(&acoder);
+                buf_size -= arith2_get_consumed_bytes(&acoder);
+            }
+        } else
+            memset(c->pal_pic, 0, c->pal_stride * avctx->height);
     }
 
     if (has_wmv9) {
@@ -836,8 +839,8 @@
     if (ret = ff_mss12_decode_init(c, 1, &ctx->sc[0], &ctx->sc[1]))
         return ret;
     c->pal_stride   = c->mask_stride;
-    c->pal_pic      = av_malloc(c->pal_stride * avctx->height);
-    c->last_pal_pic = av_malloc(c->pal_stride * avctx->height);
+    c->pal_pic      = av_mallocz(c->pal_stride * avctx->height);
+    c->last_pal_pic = av_mallocz(c->pal_stride * avctx->height);
     if (!c->pal_pic || !c->last_pal_pic) {
         mss2_decode_end(avctx);
         return AVERROR(ENOMEM);
@@ -848,8 +851,8 @@
     }
     ff_mss2dsp_init(&ctx->dsp);
 
-    avctx->pix_fmt = c->free_colours == 127 ? PIX_FMT_RGB555
-                                            : PIX_FMT_RGB24;
+    avctx->pix_fmt = c->free_colours == 127 ? AV_PIX_FMT_RGB555
+                                            : AV_PIX_FMT_RGB24;
 
     return 0;
 }
diff --git a/libavcodec/mss3.c b/libavcodec/mss3.c
index 1795773..91aceb2 100644
--- a/libavcodec/mss3.c
+++ b/libavcodec/mss3.c
@@ -835,7 +835,7 @@
         }
     }
 
-    avctx->pix_fmt     = PIX_FMT_YUV420P;
+    avctx->pix_fmt     = AV_PIX_FMT_YUV420P;
     avctx->coded_frame = &c->pic;
 
     init_coders(c);
diff --git a/libavcodec/mss4.c b/libavcodec/mss4.c
index bee9764..51db721 100644
--- a/libavcodec/mss4.c
+++ b/libavcodec/mss4.c
@@ -649,7 +649,7 @@
         }
     }
 
-    avctx->pix_fmt     = PIX_FMT_YUV444P;
+    avctx->pix_fmt     = AV_PIX_FMT_YUV444P;
     avctx->coded_frame = &c->pic;
 
     return 0;
diff --git a/libavcodec/msvideo1.c b/libavcodec/msvideo1.c
index 21ba7d7..8d1164b 100644
--- a/libavcodec/msvideo1.c
+++ b/libavcodec/msvideo1.c
@@ -65,10 +65,10 @@
     /* figure out the colorspace based on the presence of a palette */
     if (s->avctx->bits_per_coded_sample == 8) {
         s->mode_8bit = 1;
-        avctx->pix_fmt = PIX_FMT_PAL8;
+        avctx->pix_fmt = AV_PIX_FMT_PAL8;
     } else {
         s->mode_8bit = 0;
-        avctx->pix_fmt = PIX_FMT_RGB555;
+        avctx->pix_fmt = AV_PIX_FMT_RGB555;
     }
 
     avcodec_get_frame_defaults(&s->frame);
@@ -173,7 +173,7 @@
     }
 
     /* make the palette available on the way out */
-    if (s->avctx->pix_fmt == PIX_FMT_PAL8)
+    if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
         memcpy(s->frame.data[1], s->pal, AVPALETTE_SIZE);
 }
 
diff --git a/libavcodec/msvideo1enc.c b/libavcodec/msvideo1enc.c
index 852939b..e0efb48 100644
--- a/libavcodec/msvideo1enc.c
+++ b/libavcodec/msvideo1enc.c
@@ -71,7 +71,7 @@
     uint16_t *src;
     uint8_t *prevptr;
     uint8_t *dst, *buf;
-    int keyframe = 1;
+    int keyframe = 0;
     int no_skips = 1;
     int i, j, k, x, y, ret;
     int skips = 0;
@@ -110,7 +110,7 @@
                 bestscore = 0;
                 for(j = 0; j < 4; j++){
                     for(i = 0; i < 4*3; i++){
-                        int t = prevptr[x*3 + i + j*p->linesize[0]] - c->block[i + j*4*3];
+                        int t = prevptr[x*3 + i - j*3*avctx->width] - c->block[i + j*4*3];
                         bestscore += t*t;
                     }
                 }
@@ -204,14 +204,14 @@
                 for(j = 0; j < 4; j++)
                     for(i = 0; i < 4; i++)
                         for(k = 0; k < 3; k++)
-                            prevptr[i*3 + k - j*3*avctx->width] = c->avg[k];
+                            prevptr[x*3 + i*3 + k - j*3*avctx->width] = c->avg[k];
                 break;
             case MODE_2COL:
                 for(j = 0; j < 4; j++){
                     for(i = 0; i < 4; i++){
                         flags |= (c->output[i + j*4]^1) << (i + j*4);
                         for(k = 0; k < 3; k++)
-                            prevptr[i*3 + k - j*3*avctx->width] = c->codebook[c->output[i + j*4]*3 + k];
+                            prevptr[x*3 + i*3 + k - j*3*avctx->width] = c->codebook[c->output[i + j*4]*3 + k];
                     }
                 }
                 bytestream_put_le16(&dst, flags);
@@ -223,7 +223,7 @@
                     for(i = 0; i < 4; i++){
                         flags |= (c->output2[remap[i + j*4]]^1) << (i + j*4);
                         for(k = 0; k < 3; k++)
-                            prevptr[i*3 + k - j*3*avctx->width] = c->codebook2[(c->output2[remap[i+j*4]] + (i&2) + (j&2)*2)*3 + k];
+                            prevptr[x*3 + i*3 + k - j*3*avctx->width] = c->codebook2[(c->output2[remap[i+j*4]] + (i&2) + (j&2)*2)*3 + k];
                     }
                 }
                 bytestream_put_le16(&dst, flags);
@@ -306,6 +306,6 @@
     .init           = encode_init,
     .encode2        = encode_frame,
     .close          = encode_end,
-    .pix_fmts = (const enum PixelFormat[]){PIX_FMT_RGB555, PIX_FMT_NONE},
+    .pix_fmts = (const enum AVPixelFormat[]){AV_PIX_FMT_RGB555, AV_PIX_FMT_NONE},
     .long_name = NULL_IF_CONFIG_SMALL("Microsoft Video-1"),
 };
diff --git a/libavcodec/nellymoserdec.c b/libavcodec/nellymoserdec.c
index ae98bf5..b4823a8 100644
--- a/libavcodec/nellymoserdec.c
+++ b/libavcodec/nellymoserdec.c
@@ -31,14 +31,14 @@
  * implementors. The original code is available from http://code.google.com/p/nelly2pcm/
  */
 
-#include "nellymoser.h"
+#include "libavutil/channel_layout.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 "nellymoser.h"
 #include "sinewin.h"
 
 #define BITSTREAM_READER_LE
@@ -129,6 +129,7 @@
     if (!ff_sine_128[127])
         ff_init_ff_sine_windows(7);
 
+    avctx->channels       = 1;
     avctx->channel_layout = AV_CH_LAYOUT_MONO;
 
     avcodec_get_frame_defaults(&s->frame);
diff --git a/libavcodec/nellymoserenc.c b/libavcodec/nellymoserenc.c
index 2b96d47..4317e32 100644
--- a/libavcodec/nellymoserenc.c
+++ b/libavcodec/nellymoserenc.c
@@ -62,8 +62,8 @@
     DECLARE_ALIGNED(32, float, mdct_out)[NELLY_SAMPLES];
     DECLARE_ALIGNED(32, float, in_buff)[NELLY_SAMPLES];
     DECLARE_ALIGNED(32, float, buf)[3 * NELLY_BUF_LEN];     ///< sample buffer
-    float           (*opt )[NELLY_BANDS];
-    uint8_t         (*path)[NELLY_BANDS];
+    float           (*opt )[OPT_SIZE];
+    uint8_t         (*path)[OPT_SIZE];
 } NellyMoserEncodeContext;
 
 static float pow_table[POW_TABLE_SIZE];     ///< -pow(2, -i / 2048.0 - 3.0);
@@ -240,8 +240,8 @@
     int i, j, band, best_idx;
     float power_candidate, best_val;
 
-    float  (*opt )[NELLY_BANDS] = s->opt ;
-    uint8_t(*path)[NELLY_BANDS] = s->path;
+    float  (*opt )[OPT_SIZE] = s->opt ;
+    uint8_t(*path)[OPT_SIZE] = s->path;
 
     for (i = 0; i < NELLY_BANDS * OPT_SIZE; i++) {
         opt[0][i] = INFINITY;
diff --git a/libavcodec/noise_bsf.c b/libavcodec/noise_bsf.c
index 1cab3e1..763af79 100644
--- a/libavcodec/noise_bsf.c
+++ b/libavcodec/noise_bsf.c
@@ -32,6 +32,9 @@
     int amount= args ? atoi(args) : (*state % 10001+1);
     int i;
 
+    if(amount <= 0)
+        return AVERROR(EINVAL);
+
     *poutbuf= av_malloc(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
 
     memcpy(*poutbuf, buf, buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
diff --git a/libavcodec/nuv.c b/libavcodec/nuv.c
index c30ba50..09868e8 100644
--- a/libavcodec/nuv.c
+++ b/libavcodec/nuv.c
@@ -75,8 +75,8 @@
 static void copy_frame(AVFrame *f, const uint8_t *src, int width, int height)
 {
     AVPicture pic;
-    avpicture_fill(&pic, src, PIX_FMT_YUV420P, width, height);
-    av_picture_copy((AVPicture *)f, &pic, PIX_FMT_YUV420P, width, height);
+    avpicture_fill(&pic, src, AV_PIX_FMT_YUV420P, width, height);
+    av_picture_copy((AVPicture *)f, &pic, AV_PIX_FMT_YUV420P, width, height);
 }
 
 /**
@@ -290,7 +290,7 @@
 static av_cold int decode_init(AVCodecContext *avctx)
 {
     NuvContext *c  = avctx->priv_data;
-    avctx->pix_fmt = PIX_FMT_YUV420P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV420P;
     c->pic.data[0] = NULL;
     c->decomp_buf  = NULL;
     c->quality     = -1;
diff --git a/libavcodec/options.c b/libavcodec/options.c
index 7b627c9..0da0db4 100644
--- a/libavcodec/options.c
+++ b/libavcodec/options.c
@@ -117,7 +117,7 @@
     s->execute             = avcodec_default_execute;
     s->execute2            = avcodec_default_execute2;
     s->sample_aspect_ratio = (AVRational){0,1};
-    s->pix_fmt             = PIX_FMT_NONE;
+    s->pix_fmt             = AV_PIX_FMT_NONE;
     s->sample_fmt          = AV_SAMPLE_FMT_NONE;
     s->timecode_frame_start = -1;
 
@@ -277,7 +277,8 @@
 {"w", "", SROFFSET(w), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, 0},
 {"h", "", SROFFSET(h), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, 0},
 {"type", "", SROFFSET(type), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, 0},
-{"forced", "", SROFFSET(forced), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
+{"flags", "", SROFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, 0, 1, 0, "flags"},
+{"forced", "", SROFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, 0, 1, 0},
 {NULL},
 };
 
diff --git a/libavcodec/options_table.h b/libavcodec/options_table.h
index e4397d0..1ae93c1 100644
--- a/libavcodec/options_table.h
+++ b/libavcodec/options_table.h
@@ -27,6 +27,7 @@
 
 #include "libavutil/opt.h"
 #include "avcodec.h"
+#include "version.h"
 #include "config.h"
 
 #define OFFSET(x) offsetof(AVCodecContext,x)
@@ -41,8 +42,8 @@
 #define AV_CODEC_DEFAULT_BITRATE 200*1000
 
 static const AVOption options[]={
-{"b", "set bitrate (in bits/s)", OFFSET(bit_rate), AV_OPT_TYPE_INT, {.i64 = AV_CODEC_DEFAULT_BITRATE }, INT_MIN, INT_MAX, A|V|E},
-{"ab", "set bitrate (in bits/s)", OFFSET(bit_rate), AV_OPT_TYPE_INT, {.i64 = 128*1000 }, INT_MIN, INT_MAX, A|E},
+{"b", "set bitrate (in bits/s)", OFFSET(bit_rate), AV_OPT_TYPE_INT, {.i64 = AV_CODEC_DEFAULT_BITRATE }, 0, INT_MAX, A|V|E},
+{"ab", "set bitrate (in bits/s)", OFFSET(bit_rate), AV_OPT_TYPE_INT, {.i64 = 128*1000 }, 0, INT_MAX, A|E},
 {"bt", "Set video bitrate tolerance (in bits/s). 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.",
@@ -167,7 +168,6 @@
 {"has_b_frames", NULL, OFFSET(has_b_frames), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
 {"block_align", NULL, OFFSET(block_align), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
 {"mpeg_quant", "use MPEG quantizers instead of H.263", OFFSET(mpeg_quant), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
-{"stats_out", NULL, OFFSET(stats_out), AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX},
 {"qsquish", "how to keep quantizer between qmin and qmax (0 = clip, 1 = use differentiable function)", OFFSET(rc_qsquish), AV_OPT_TYPE_FLOAT, {.dbl = DEFAULT }, 0, 99, V|E},
 {"rc_qmod_amp", "experimental quantizer modulation", OFFSET(rc_qmod_amp), AV_OPT_TYPE_FLOAT, {.dbl = DEFAULT }, -FLT_MAX, FLT_MAX, V|E},
 {"rc_qmod_freq", "experimental quantizer modulation", OFFSET(rc_qmod_freq), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
@@ -203,7 +203,9 @@
 {"simple", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_SIMPLE }, INT_MIN, INT_MAX, V|E|D, "idct"},
 {"simplemmx", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_SIMPLEMMX }, INT_MIN, INT_MAX, V|E|D, "idct"},
 {"libmpeg2mmx", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_LIBMPEG2MMX }, INT_MIN, INT_MAX, V|E|D, "idct"},
+#if FF_API_MMI
 {"mmi", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_MMI }, INT_MIN, INT_MAX, V|E|D, "idct"},
+#endif
 {"arm", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_ARM }, INT_MIN, INT_MAX, V|E|D, "idct"},
 {"altivec", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_ALTIVEC }, INT_MIN, INT_MAX, V|E|D, "idct"},
 {"sh4", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_SH4 }, INT_MIN, INT_MAX, V|E|D, "idct"},
@@ -399,17 +401,7 @@
 {"em", "Emergency",          0, AV_OPT_TYPE_CONST, {.i64 = AV_AUDIO_SERVICE_TYPE_EMERGENCY },         INT_MIN, INT_MAX, A|E, "audio_service_type"},
 {"vo", "Voice Over",         0, AV_OPT_TYPE_CONST, {.i64 = AV_AUDIO_SERVICE_TYPE_VOICE_OVER },        INT_MIN, INT_MAX, A|E, "audio_service_type"},
 {"ka", "Karaoke",            0, AV_OPT_TYPE_CONST, {.i64 = AV_AUDIO_SERVICE_TYPE_KARAOKE },           INT_MIN, INT_MAX, A|E, "audio_service_type"},
-{"request_sample_fmt", "sample format audio decoders should prefer", OFFSET(request_sample_fmt), AV_OPT_TYPE_INT, {.i64 = AV_SAMPLE_FMT_NONE }, AV_SAMPLE_FMT_NONE, AV_SAMPLE_FMT_NB-1, A|D, "request_sample_fmt"},
-{"u8" , "8-bit unsigned integer", 0, AV_OPT_TYPE_CONST, {.i64 = AV_SAMPLE_FMT_U8  }, INT_MIN, INT_MAX, A|D, "request_sample_fmt"},
-{"s16", "16-bit signed integer",  0, AV_OPT_TYPE_CONST, {.i64 = AV_SAMPLE_FMT_S16 }, INT_MIN, INT_MAX, A|D, "request_sample_fmt"},
-{"s32", "32-bit signed integer",  0, AV_OPT_TYPE_CONST, {.i64 = AV_SAMPLE_FMT_S32 }, INT_MIN, INT_MAX, A|D, "request_sample_fmt"},
-{"flt", "32-bit float",           0, AV_OPT_TYPE_CONST, {.i64 = AV_SAMPLE_FMT_FLT }, INT_MIN, INT_MAX, A|D, "request_sample_fmt"},
-{"dbl", "64-bit double",          0, AV_OPT_TYPE_CONST, {.i64 = AV_SAMPLE_FMT_DBL }, INT_MIN, INT_MAX, A|D, "request_sample_fmt"},
-{"u8p" , "8-bit unsigned integer planar", 0, AV_OPT_TYPE_CONST, {.i64 = AV_SAMPLE_FMT_U8P  }, INT_MIN, INT_MAX, A|D, "request_sample_fmt"},
-{"s16p", "16-bit signed integer planar",  0, AV_OPT_TYPE_CONST, {.i64 = AV_SAMPLE_FMT_S16P }, INT_MIN, INT_MAX, A|D, "request_sample_fmt"},
-{"s32p", "32-bit signed integer planar",  0, AV_OPT_TYPE_CONST, {.i64 = AV_SAMPLE_FMT_S32P }, INT_MIN, INT_MAX, A|D, "request_sample_fmt"},
-{"fltp", "32-bit float planar",           0, AV_OPT_TYPE_CONST, {.i64 = AV_SAMPLE_FMT_FLTP }, INT_MIN, INT_MAX, A|D, "request_sample_fmt"},
-{"dblp", "64-bit double planar",          0, AV_OPT_TYPE_CONST, {.i64 = AV_SAMPLE_FMT_DBLP }, INT_MIN, INT_MAX, A|D, "request_sample_fmt"},
+{"request_sample_fmt", "sample format audio decoders should prefer", OFFSET(request_sample_fmt), AV_OPT_TYPE_SAMPLE_FMT, {.i64=AV_SAMPLE_FMT_NONE}, -1, AV_SAMPLE_FMT_NB-1, A|D, "request_sample_fmt"},
 {"pkt_timebase", NULL, OFFSET(pkt_timebase), AV_OPT_TYPE_RATIONAL, {.dbl = 0 }, 0, INT_MAX, 0},
 {NULL},
 };
diff --git a/libavcodec/paf.c b/libavcodec/paf.c
index bd7298a..877b170 100644
--- a/libavcodec/paf.c
+++ b/libavcodec/paf.c
@@ -67,7 +67,7 @@
         return AVERROR_INVALIDDATA;
     }
 
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     avcodec_get_frame_defaults(&c->pic);
     c->frame_size = FFALIGN(avctx->height, 256) * avctx->width;
diff --git a/libavcodec/pamenc.c b/libavcodec/pamenc.c
index a43aa55..3e47278 100644
--- a/libavcodec/pamenc.c
+++ b/libavcodec/pamenc.c
@@ -36,49 +36,49 @@
     h = avctx->height;
     w = avctx->width;
     switch (avctx->pix_fmt) {
-    case PIX_FMT_MONOBLACK:
+    case AV_PIX_FMT_MONOBLACK:
         n          = w;
         depth      = 1;
         maxval     = 1;
         tuple_type = "BLACKANDWHITE";
         break;
-    case PIX_FMT_GRAY8:
+    case AV_PIX_FMT_GRAY8:
         n          = w;
         depth      = 1;
         maxval     = 255;
         tuple_type = "GRAYSCALE";
         break;
-    case PIX_FMT_GRAY16BE:
+    case AV_PIX_FMT_GRAY16BE:
         n          = w * 2;
         depth      = 1;
         maxval     = 0xFFFF;
         tuple_type = "GRAYSCALE";
         break;
-    case PIX_FMT_GRAY8A:
+    case AV_PIX_FMT_GRAY8A:
         n          = w * 2;
         depth      = 2;
         maxval     = 255;
         tuple_type = "GRAYSCALE_ALPHA";
         break;
-    case PIX_FMT_RGB24:
+    case AV_PIX_FMT_RGB24:
         n          = w * 3;
         depth      = 3;
         maxval     = 255;
         tuple_type = "RGB";
         break;
-    case PIX_FMT_RGBA:
+    case AV_PIX_FMT_RGBA:
         n          = w * 4;
         depth      = 4;
         maxval     = 255;
         tuple_type = "RGB_ALPHA";
         break;
-    case PIX_FMT_RGB48BE:
+    case AV_PIX_FMT_RGB48BE:
         n          = w * 6;
         depth      = 3;
         maxval     = 0xFFFF;
         tuple_type = "RGB";
         break;
-    case PIX_FMT_RGBA64BE:
+    case AV_PIX_FMT_RGBA64BE:
         n          = w * 8;
         depth      = 4;
         maxval     = 0xFFFF;
@@ -107,7 +107,7 @@
     ptr      = p->data[0];
     linesize = p->linesize[0];
 
-    if (avctx->pix_fmt == PIX_FMT_MONOBLACK){
+    if (avctx->pix_fmt == AV_PIX_FMT_MONOBLACK){
         int j;
         for (i = 0; i < h; i++) {
             for (j = 0; j < w; j++)
@@ -136,8 +136,8 @@
     .priv_data_size = sizeof(PNMContext),
     .init           = ff_pnm_init,
     .encode2        = pam_encode_frame,
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_RGB24, PIX_FMT_RGBA, PIX_FMT_RGB48BE, PIX_FMT_RGBA64BE, PIX_FMT_GRAY8, PIX_FMT_GRAY8A, PIX_FMT_GRAY16BE, PIX_FMT_MONOBLACK, PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA, AV_PIX_FMT_RGB48BE, AV_PIX_FMT_RGBA64BE, AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY8A, AV_PIX_FMT_GRAY16BE, AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("PAM (Portable AnyMap) image"),
 };
diff --git a/libavcodec/parser.c b/libavcodec/parser.c
index a85db1a..2e204e2 100644
--- a/libavcodec/parser.c
+++ b/libavcodec/parser.c
@@ -40,7 +40,7 @@
 
 AVCodecParserContext *av_parser_init(int codec_id)
 {
-    AVCodecParserContext *s;
+    AVCodecParserContext *s = NULL;
     AVCodecParser *parser;
     int ret;
 
@@ -59,22 +59,17 @@
  found:
     s = av_mallocz(sizeof(AVCodecParserContext));
     if (!s)
-        return NULL;
+        goto err_out;
     s->parser = parser;
     s->priv_data = av_mallocz(parser->priv_data_size);
-    if (!s->priv_data) {
-        av_free(s);
-        return NULL;
-    }
+    if (!s->priv_data)
+        goto err_out;
     s->fetch_timestamp=1;
     s->pict_type = AV_PICTURE_TYPE_I;
     if (parser->parser_init) {
         ret = parser->parser_init(s);
-        if (ret != 0) {
-            av_free(s->priv_data);
-            av_free(s);
-            return NULL;
-        }
+        if (ret != 0)
+            goto err_out;
     }
     s->key_frame = -1;
     s->convergence_duration = 0;
@@ -82,6 +77,12 @@
     s->dts_ref_dts_delta    = INT_MIN;
     s->pts_dts_delta        = INT_MIN;
     return s;
+
+err_out:
+    if (s)
+        av_freep(&s->priv_data);
+    av_free(s);
+    return NULL;
 }
 
 void ff_fetch_timestamp(AVCodecParserContext *s, int off, int remove){
@@ -165,11 +166,6 @@
     return index;
 }
 
-/**
- *
- * @return 0 if the output buffer is a subset of the input, 1 if it is allocated and must be freed
- * @deprecated use AVBitstreamFilter
- */
 int av_parser_change(AVCodecParserContext *s,
                      AVCodecContext *avctx,
                      uint8_t **poutbuf, int *poutbuf_size,
@@ -215,10 +211,6 @@
 
 /*****************************************************/
 
-/**
- * Combine the (truncated) bitstream to a complete frame.
- * @return -1 if no complete frame could be created, AVERROR(ENOMEM) if there was a memory allocation error
- */
 int ff_combine_frame(ParseContext *pc, int next, const uint8_t **buf, int *buf_size)
 {
     if(pc->overread){
@@ -261,6 +253,7 @@
         if(!new_buffer)
             return AVERROR(ENOMEM);
         pc->buffer = new_buffer;
+        if(FF_INPUT_BUFFER_PADDING_SIZE > -next)
         memcpy(&pc->buffer[pc->index], *buf, next + FF_INPUT_BUFFER_PADDING_SIZE );
         pc->index = 0;
         *buf= pc->buffer;
diff --git a/libavcodec/parser.h b/libavcodec/parser.h
index 69f1064..7fe0e11 100644
--- a/libavcodec/parser.h
+++ b/libavcodec/parser.h
@@ -39,6 +39,11 @@
 
 #define END_NOT_FOUND (-100)
 
+/**
+ * Combine the (truncated) bitstream to a complete frame.
+ * @return -1 if no complete frame could be created,
+ *         AVERROR(ENOMEM) if there was a memory allocation error
+ */
 int ff_combine_frame(ParseContext *pc, int next, const uint8_t **buf, int *buf_size);
 int ff_mpeg4video_split(AVCodecContext *avctx, const uint8_t *buf,
                         int buf_size);
diff --git a/libavcodec/pcm-mpeg.c b/libavcodec/pcm-mpeg.c
index 032bdae..01a61c8 100644
--- a/libavcodec/pcm-mpeg.c
+++ b/libavcodec/pcm-mpeg.c
@@ -24,7 +24,7 @@
  * PCM codecs for encodings found in MPEG streams (DVD/Blu-ray)
  */
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "avcodec.h"
 #include "bytestream.h"
 
@@ -110,12 +110,12 @@
         return -1;
     }
 
-    avctx->bit_rate = avctx->channels * avctx->sample_rate *
+    avctx->bit_rate = FFALIGN(avctx->channels, 2) * avctx->sample_rate *
                       avctx->bits_per_coded_sample;
 
     if (avctx->debug & FF_DEBUG_PICT_INFO)
         av_dlog(avctx,
-                "pcm_bluray_parse_header: %d channels, %d bits per sample, %d kHz, %d kbit\n",
+                "pcm_bluray_parse_header: %d channels, %d bits per sample, %d Hz, %d bit/s\n",
                 avctx->channels, avctx->bits_per_coded_sample,
                 avctx->sample_rate, avctx->bit_rate);
     return 0;
diff --git a/libavcodec/pcm.c b/libavcodec/pcm.c
index cc94a5e..d769fb1 100644
--- a/libavcodec/pcm.c
+++ b/libavcodec/pcm.c
@@ -24,14 +24,13 @@
  * PCM codecs
  */
 
-#include "libavutil/common.h" /* for av_reverse */
+#include "libavutil/attributes.h"
 #include "avcodec.h"
 #include "bytestream.h"
 #include "internal.h"
+#include "mathops.h"
 #include "pcm_tablegen.h"
 
-#define MAX_CHANNELS 64
-
 static av_cold int pcm_encode_init(AVCodecContext *avctx)
 {
     avctx->frame_size = 0;
@@ -80,13 +79,24 @@
         bytestream_put_ ## endian(&dst, v);                             \
     }
 
+#define ENCODE_PLANAR(type, endian, dst, n, shift, offset)              \
+    n /= avctx->channels;                                               \
+    for (c = 0; c < avctx->channels; c++) {                             \
+        int i;                                                          \
+        samples_ ## type = (const type *) frame->extended_data[c];      \
+        for (i = n; i > 0; i--) {                                       \
+            register type v = (*samples_ ## type++ >> shift) + offset;  \
+            bytestream_put_ ## endian(&dst, v);                         \
+        }                                                               \
+    }
+
 static int pcm_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
                             const AVFrame *frame, int *got_packet_ptr)
 {
-    int n, sample_size, v, ret;
+    int n, c, sample_size, v, ret;
     const short *samples;
     unsigned char *dst;
-    const uint8_t *srcu8;
+    const uint8_t *samples_uint8_t;
     const int16_t *samples_int16_t;
     const int32_t *samples_int32_t;
     const int64_t *samples_int64_t;
@@ -111,6 +121,9 @@
     case AV_CODEC_ID_PCM_S24LE:
         ENCODE(int32_t, le24, samples, dst, n, 8, 0)
         break;
+    case AV_CODEC_ID_PCM_S24LE_PLANAR:
+        ENCODE_PLANAR(int32_t, le24, dst, n, 8, 0)
+        break;
     case AV_CODEC_ID_PCM_S24BE:
         ENCODE(int32_t, be24, samples, dst, n, 8, 0)
         break;
@@ -122,8 +135,8 @@
         break;
     case AV_CODEC_ID_PCM_S24DAUD:
         for (; n > 0; n--) {
-            uint32_t tmp = av_reverse[(*samples >> 8) & 0xff] +
-                           (av_reverse[*samples & 0xff] << 8);
+            uint32_t tmp = ff_reverse[(*samples >> 8) & 0xff] +
+                           (ff_reverse[*samples & 0xff] << 8);
             tmp <<= 4; // sync flags would go here
             bytestream_put_be24(&dst, tmp);
             samples++;
@@ -136,11 +149,10 @@
         ENCODE(uint16_t, be16, samples, dst, n, 0, 0x8000)
         break;
     case AV_CODEC_ID_PCM_S8:
-        srcu8 = frame->data[0];
-        for (; n > 0; n--) {
-            v      = *srcu8++;
-            *dst++ = v - 128;
-        }
+        ENCODE(uint8_t, byte, samples, dst, n, 0, -128)
+        break;
+    case AV_CODEC_ID_PCM_S8_PLANAR:
+        ENCODE_PLANAR(uint8_t, byte, dst, n, 0, -128)
         break;
 #if HAVE_BIGENDIAN
     case AV_CODEC_ID_PCM_F64LE:
@@ -150,9 +162,15 @@
     case AV_CODEC_ID_PCM_F32LE:
         ENCODE(int32_t, le32, samples, dst, n, 0, 0)
         break;
+    case AV_CODEC_ID_PCM_S32LE_PLANAR:
+        ENCODE_PLANAR(int32_t, le32, dst, n, 0, 0)
+        break;
     case AV_CODEC_ID_PCM_S16LE:
         ENCODE(int16_t, le16, samples, dst, n, 0, 0)
         break;
+    case AV_CODEC_ID_PCM_S16LE_PLANAR:
+        ENCODE_PLANAR(int16_t, le16, dst, n, 0, 0)
+        break;
     case AV_CODEC_ID_PCM_F64BE:
     case AV_CODEC_ID_PCM_F32BE:
     case AV_CODEC_ID_PCM_S32BE:
@@ -168,6 +186,9 @@
     case AV_CODEC_ID_PCM_S16BE:
         ENCODE(int16_t, be16, samples, dst, n, 0, 0)
         break;
+    case AV_CODEC_ID_PCM_S16BE_PLANAR:
+        ENCODE_PLANAR(int16_t, be16, dst, n, 0, 0)
+        break;
     case AV_CODEC_ID_PCM_F64LE:
     case AV_CODEC_ID_PCM_F32LE:
     case AV_CODEC_ID_PCM_S32LE:
@@ -175,7 +196,18 @@
 #endif /* HAVE_BIGENDIAN */
     case AV_CODEC_ID_PCM_U8:
         memcpy(dst, samples, n * sample_size);
-        dst += n * sample_size;
+        break;
+#if HAVE_BIGENDIAN
+    case AV_CODEC_ID_PCM_S16BE_PLANAR:
+#else
+    case AV_CODEC_ID_PCM_S16LE_PLANAR:
+    case AV_CODEC_ID_PCM_S32LE_PLANAR:
+#endif /* HAVE_BIGENDIAN */
+        n /= avctx->channels;
+        for (c = 0; c < avctx->channels; c++) {
+            const uint8_t *src = frame->extended_data[c];
+            bytestream_put_buffer(&dst, src, n * sample_size);
+        }
         break;
     case AV_CODEC_ID_PCM_ALAW:
         for (; n > 0; n--) {
@@ -207,12 +239,12 @@
     PCMDecode *s = avctx->priv_data;
     int i;
 
-    if (avctx->channels <= 0 || avctx->channels > MAX_CHANNELS) {
+    if (avctx->channels <= 0) {
         av_log(avctx, AV_LOG_ERROR, "PCM channels out of bounds\n");
         return AVERROR(EINVAL);
     }
 
-    switch (avctx->codec->id) {
+    switch (avctx->codec_id) {
     case AV_CODEC_ID_PCM_ALAW:
         for (i = 0; i < 256; i++)
             s->table[i] = alaw2linear(i);
@@ -228,7 +260,7 @@
     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);
+        avctx->bits_per_raw_sample = av_get_bits_per_sample(avctx->codec_id);
 
     avcodec_get_frame_defaults(&s->frame);
     avctx->coded_frame = &s->frame;
@@ -253,6 +285,18 @@
         dst += size / 8;                                                \
     }
 
+#define DECODE_PLANAR(size, endian, src, dst, n, shift, offset)         \
+    n /= avctx->channels;                                               \
+    for (c = 0; c < avctx->channels; c++) {                             \
+        int i;                                                          \
+        dst = s->frame.extended_data[c];                                \
+        for (i = n; i > 0; i--) {                                       \
+            uint ## size ## _t v = bytestream_get_ ## endian(&src);     \
+            AV_WN ## size ## A(dst, (v - offset) << shift);             \
+            dst += size / 8;                                            \
+        }                                                               \
+    }
+
 static int pcm_decode_frame(AVCodecContext *avctx, void *data,
                             int *got_frame_ptr, AVPacket *avpkt)
 {
@@ -289,6 +333,16 @@
         return AVERROR(EINVAL);
     }
 
+    if (avctx->channels == 0) {
+        av_log(avctx, AV_LOG_ERROR, "Invalid number of channels\n");
+        return AVERROR(EINVAL);
+    }
+
+    if (avctx->codec_id != avctx->codec->id) {
+        av_log(avctx, AV_LOG_ERROR, "codec ids mismatch\n");
+        return AVERROR(EINVAL);
+    }
+
     n = avctx->channels * sample_size;
 
     if (n && buf_size % n) {
@@ -311,7 +365,7 @@
     }
     samples = s->frame.data[0];
 
-    switch (avctx->codec->id) {
+    switch (avctx->codec_id) {
     case AV_CODEC_ID_PCM_U32LE:
         DECODE(32, le32, src, samples, n, 0, 0x80000000)
         break;
@@ -321,6 +375,9 @@
     case AV_CODEC_ID_PCM_S24LE:
         DECODE(32, le24, src, samples, n, 8, 0)
         break;
+    case AV_CODEC_ID_PCM_S24LE_PLANAR:
+        DECODE_PLANAR(32, le24, src, samples, n, 8, 0);
+        break;
     case AV_CODEC_ID_PCM_S24BE:
         DECODE(32, be24, src, samples, n, 8, 0)
         break;
@@ -334,24 +391,11 @@
         for (; n > 0; n--) {
             uint32_t v = bytestream_get_be24(&src);
             v >>= 4; // sync flags are here
-            AV_WN16A(samples, av_reverse[(v >> 8) & 0xff] +
-                             (av_reverse[v        & 0xff] << 8));
+            AV_WN16A(samples, ff_reverse[(v >> 8) & 0xff] +
+                             (ff_reverse[v        & 0xff] << 8));
             samples += 2;
         }
         break;
-    case AV_CODEC_ID_PCM_S16LE_PLANAR:
-    {
-        int i;
-        n /= avctx->channels;
-        for (c = 0; c < avctx->channels; c++) {
-            samples = s->frame.data[c];
-            for (i = n; i > 0; i--) {
-                AV_WN16A(samples, bytestream_get_le16(&src));
-                samples += 2;
-            }
-        }
-        break;
-    }
     case AV_CODEC_ID_PCM_U16LE:
         DECODE(16, le16, src, samples, n, 0, 0x8000)
         break;
@@ -362,6 +406,15 @@
         for (; n > 0; n--)
             *samples++ = *src++ + 128;
         break;
+    case AV_CODEC_ID_PCM_S8_PLANAR:
+        n /= avctx->channels;
+        for (c = 0; c < avctx->channels; c++) {
+            int i;
+            samples = s->frame.extended_data[c];
+            for (i = n; i > 0; i--)
+                *samples++ = *src++ + 128;
+        }
+        break;
 #if HAVE_BIGENDIAN
     case AV_CODEC_ID_PCM_F64LE:
         DECODE(64, le64, src, samples, n, 0, 0)
@@ -370,9 +423,15 @@
     case AV_CODEC_ID_PCM_F32LE:
         DECODE(32, le32, src, samples, n, 0, 0)
         break;
+    case AV_CODEC_ID_PCM_S32LE_PLANAR:
+        DECODE_PLANAR(32, le32, src, samples, n, 0, 0);
+        break;
     case AV_CODEC_ID_PCM_S16LE:
         DECODE(16, le16, src, samples, n, 0, 0)
         break;
+    case AV_CODEC_ID_PCM_S16LE_PLANAR:
+        DECODE_PLANAR(16, le16, src, samples, n, 0, 0);
+        break;
     case AV_CODEC_ID_PCM_F64BE:
     case AV_CODEC_ID_PCM_F32BE:
     case AV_CODEC_ID_PCM_S32BE:
@@ -388,6 +447,9 @@
     case AV_CODEC_ID_PCM_S16BE:
         DECODE(16, be16, src, samples, n, 0, 0)
         break;
+    case AV_CODEC_ID_PCM_S16BE_PLANAR:
+        DECODE_PLANAR(16, be16, src, samples, n, 0, 0);
+        break;
     case AV_CODEC_ID_PCM_F64LE:
     case AV_CODEC_ID_PCM_F32LE:
     case AV_CODEC_ID_PCM_S32LE:
@@ -396,6 +458,18 @@
     case AV_CODEC_ID_PCM_U8:
         memcpy(samples, src, n * sample_size);
         break;
+#if HAVE_BIGENDIAN
+    case AV_CODEC_ID_PCM_S16BE_PLANAR:
+#else
+    case AV_CODEC_ID_PCM_S16LE_PLANAR:
+    case AV_CODEC_ID_PCM_S32LE_PLANAR:
+#endif /* HAVE_BIGENDIAN */
+        n /= avctx->channels;
+        for (c = 0; c < avctx->channels; c++) {
+            samples = s->frame.extended_data[c];
+            bytestream_get_buffer(&src, samples, n * sample_size);
+        }
+        break;
     case AV_CODEC_ID_PCM_ZORK:
         for (; n > 0; n--) {
             int v = *src++;
@@ -446,22 +520,21 @@
     {
         int i;
         n /= avctx->channels;
-        //unpack
         for (c = 0; c < avctx->channels; c++) {
-            dst_int32_t = (int32_t *)s->frame.data[c];
+            dst_int32_t = (int32_t *)s->frame.extended_data[c];
             for (i = 0; i < n; i++) {
-                //extract low 20 bits and expand to 32 bits
-                *dst_int32_t++ = (src[2] << 28) |
-                                 (src[1] << 20) |
-                                 (src[0] << 12) |
-                                 ((src[2] & 0xF) << 8) |
-                                 src[1];
-                //extract high 20 bits and expand to 32 bits
-                *dst_int32_t++ = (src[4] << 24) |
-                                 (src[3] << 16) |
-                                 ((src[2] & 0xF0) << 8) |
-                                 (src[4] << 4) |
-                                 (src[3] >> 4);
+                // extract low 20 bits and expand to 32 bits
+                *dst_int32_t++ =  (src[2]         << 28) |
+                                  (src[1]         << 20) |
+                                  (src[0]         << 12) |
+                                 ((src[2] & 0x0F) <<  8) |
+                                   src[1];
+                // extract high 20 bits and expand to 32 bits
+                *dst_int32_t++ =  (src[4]         << 24) |
+                                  (src[3]         << 16) |
+                                 ((src[2] & 0xF0) <<  8) |
+                                  (src[4]         <<  4) |
+                                  (src[3]         >>  4);
                 src += 5;
             }
         }
@@ -477,12 +550,12 @@
     return buf_size;
 }
 
-#if CONFIG_ENCODERS
-#define PCM_ENCODER(id_, sample_fmt_, name_, long_name_)                    \
+#define PCM_ENCODER_0(id_, sample_fmt_, name_, long_name_)
+#define PCM_ENCODER_1(id_, sample_fmt_, name_, long_name_)                  \
 AVCodec ff_ ## name_ ## _encoder = {                                        \
     .name         = #name_,                                                 \
     .type         = AVMEDIA_TYPE_AUDIO,                                     \
-    .id           = id_,                                                    \
+    .id           = AV_CODEC_ID_ ## id_,                                    \
     .init         = pcm_encode_init,                                        \
     .encode2      = pcm_encode_frame,                                       \
     .close        = pcm_encode_close,                                       \
@@ -491,16 +564,20 @@
                                                    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_)                    \
+#define PCM_ENCODER_2(cf, id, sample_fmt, name, long_name)                  \
+    PCM_ENCODER_ ## cf(id, sample_fmt, name, long_name)
+#define PCM_ENCODER_3(cf, id, sample_fmt, name, long_name)                  \
+    PCM_ENCODER_2(cf, id, sample_fmt, name, long_name)
+#define PCM_ENCODER(id, sample_fmt, name, long_name)                        \
+    PCM_ENCODER_3(CONFIG_ ## id ## _ENCODER, id, sample_fmt, name, long_name)
+
+#define PCM_DECODER_0(id, sample_fmt, name, long_name)
+#define PCM_DECODER_1(id_, sample_fmt_, name_, long_name_)                  \
 AVCodec ff_ ## name_ ## _decoder = {                                        \
     .name           = #name_,                                               \
     .type           = AVMEDIA_TYPE_AUDIO,                                   \
-    .id             = id_,                                                  \
+    .id             = AV_CODEC_ID_ ## id_,                                  \
     .priv_data_size = sizeof(PCMDecode),                                    \
     .init           = pcm_decode_init,                                      \
     .decode         = pcm_decode_frame,                                     \
@@ -509,38 +586,46 @@
                                                      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_DECODER_2(cf, id, sample_fmt, name, long_name)                  \
+    PCM_DECODER_ ## cf(id, sample_fmt, name, long_name)
+#define PCM_DECODER_3(cf, id, sample_fmt, name, long_name)                  \
+    PCM_DECODER_2(cf, id, sample_fmt, name, long_name)
+#define PCM_DECODER(id, sample_fmt, name, long_name)                        \
+    PCM_DECODER_3(CONFIG_ ## id ## _DECODER, id, sample_fmt, name, long_name)
 
 #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_)
 
 /* Note: Do not forget to add new entries to the Makefile as well. */
-PCM_CODEC  (AV_CODEC_ID_PCM_ALAW,         AV_SAMPLE_FMT_S16, pcm_alaw,         "PCM A-law / G.711 A-law");
-PCM_DECODER(AV_CODEC_ID_PCM_DVD,          AV_SAMPLE_FMT_S32, pcm_dvd,          "PCM signed 20|24-bit big-endian");
-PCM_CODEC  (AV_CODEC_ID_PCM_F32BE,        AV_SAMPLE_FMT_FLT, pcm_f32be,        "PCM 32-bit floating point big-endian");
-PCM_CODEC  (AV_CODEC_ID_PCM_F32LE,        AV_SAMPLE_FMT_FLT, pcm_f32le,        "PCM 32-bit floating point little-endian");
-PCM_CODEC  (AV_CODEC_ID_PCM_F64BE,        AV_SAMPLE_FMT_DBL, pcm_f64be,        "PCM 64-bit floating point big-endian");
-PCM_CODEC  (AV_CODEC_ID_PCM_F64LE,        AV_SAMPLE_FMT_DBL, pcm_f64le,        "PCM 64-bit floating point little-endian");
-PCM_DECODER(AV_CODEC_ID_PCM_LXF,          AV_SAMPLE_FMT_S32P,pcm_lxf,          "PCM signed 20-bit little-endian planar");
-PCM_CODEC  (AV_CODEC_ID_PCM_MULAW,        AV_SAMPLE_FMT_S16, pcm_mulaw,        "PCM mu-law / G.711 mu-law");
-PCM_CODEC  (AV_CODEC_ID_PCM_S8,           AV_SAMPLE_FMT_U8,  pcm_s8,           "PCM signed 8-bit");
-PCM_CODEC  (AV_CODEC_ID_PCM_S16BE,        AV_SAMPLE_FMT_S16, pcm_s16be,        "PCM signed 16-bit big-endian");
-PCM_CODEC  (AV_CODEC_ID_PCM_S16LE,        AV_SAMPLE_FMT_S16, pcm_s16le,        "PCM signed 16-bit little-endian");
-PCM_DECODER(AV_CODEC_ID_PCM_S16LE_PLANAR, AV_SAMPLE_FMT_S16P,pcm_s16le_planar, "PCM 16-bit little-endian planar");
-PCM_CODEC  (AV_CODEC_ID_PCM_S24BE,        AV_SAMPLE_FMT_S32, pcm_s24be,        "PCM signed 24-bit big-endian");
-PCM_CODEC  (AV_CODEC_ID_PCM_S24DAUD,      AV_SAMPLE_FMT_S16, pcm_s24daud,      "PCM D-Cinema audio signed 24-bit");
-PCM_CODEC  (AV_CODEC_ID_PCM_S24LE,        AV_SAMPLE_FMT_S32, pcm_s24le,        "PCM signed 24-bit little-endian");
-PCM_CODEC  (AV_CODEC_ID_PCM_S32BE,        AV_SAMPLE_FMT_S32, pcm_s32be,        "PCM signed 32-bit big-endian");
-PCM_CODEC  (AV_CODEC_ID_PCM_S32LE,        AV_SAMPLE_FMT_S32, pcm_s32le,        "PCM signed 32-bit little-endian");
-PCM_CODEC  (AV_CODEC_ID_PCM_U8,           AV_SAMPLE_FMT_U8,  pcm_u8,           "PCM unsigned 8-bit");
-PCM_CODEC  (AV_CODEC_ID_PCM_U16BE,        AV_SAMPLE_FMT_S16, pcm_u16be,        "PCM unsigned 16-bit big-endian");
-PCM_CODEC  (AV_CODEC_ID_PCM_U16LE,        AV_SAMPLE_FMT_S16, pcm_u16le,        "PCM unsigned 16-bit little-endian");
-PCM_CODEC  (AV_CODEC_ID_PCM_U24BE,        AV_SAMPLE_FMT_S32, pcm_u24be,        "PCM unsigned 24-bit big-endian");
-PCM_CODEC  (AV_CODEC_ID_PCM_U24LE,        AV_SAMPLE_FMT_S32, pcm_u24le,        "PCM unsigned 24-bit little-endian");
-PCM_CODEC  (AV_CODEC_ID_PCM_U32BE,        AV_SAMPLE_FMT_S32, pcm_u32be,        "PCM unsigned 32-bit big-endian");
-PCM_CODEC  (AV_CODEC_ID_PCM_U32LE,        AV_SAMPLE_FMT_S32, pcm_u32le,        "PCM unsigned 32-bit little-endian");
-PCM_DECODER(AV_CODEC_ID_PCM_ZORK,         AV_SAMPLE_FMT_U8,  pcm_zork,         "PCM Zork");
+PCM_CODEC  (PCM_ALAW,         AV_SAMPLE_FMT_S16, pcm_alaw,         "PCM A-law / G.711 A-law");
+PCM_DECODER(PCM_DVD,          AV_SAMPLE_FMT_S32, pcm_dvd,          "PCM signed 20|24-bit big-endian");
+PCM_CODEC  (PCM_F32BE,        AV_SAMPLE_FMT_FLT, pcm_f32be,        "PCM 32-bit floating point big-endian");
+PCM_CODEC  (PCM_F32LE,        AV_SAMPLE_FMT_FLT, pcm_f32le,        "PCM 32-bit floating point little-endian");
+PCM_CODEC  (PCM_F64BE,        AV_SAMPLE_FMT_DBL, pcm_f64be,        "PCM 64-bit floating point big-endian");
+PCM_CODEC  (PCM_F64LE,        AV_SAMPLE_FMT_DBL, pcm_f64le,        "PCM 64-bit floating point little-endian");
+PCM_DECODER(PCM_LXF,          AV_SAMPLE_FMT_S32P,pcm_lxf,          "PCM signed 20-bit little-endian planar");
+PCM_CODEC  (PCM_MULAW,        AV_SAMPLE_FMT_S16, pcm_mulaw,        "PCM mu-law / G.711 mu-law");
+PCM_CODEC  (PCM_S8,           AV_SAMPLE_FMT_U8,  pcm_s8,           "PCM signed 8-bit");
+PCM_CODEC  (PCM_S8_PLANAR,    AV_SAMPLE_FMT_U8P, pcm_s8_planar,    "PCM signed 8-bit planar");
+PCM_CODEC  (PCM_S16BE,        AV_SAMPLE_FMT_S16, pcm_s16be,        "PCM signed 16-bit big-endian");
+PCM_CODEC  (PCM_S16BE_PLANAR, AV_SAMPLE_FMT_S16P,pcm_s16be_planar, "PCM signed 16-bit big-endian planar");
+PCM_CODEC  (PCM_S16LE,        AV_SAMPLE_FMT_S16, pcm_s16le,        "PCM signed 16-bit little-endian");
+PCM_CODEC  (PCM_S16LE_PLANAR, AV_SAMPLE_FMT_S16P,pcm_s16le_planar, "PCM signed 16-bit little-endian planar");
+PCM_CODEC  (PCM_S24BE,        AV_SAMPLE_FMT_S32, pcm_s24be,        "PCM signed 24-bit big-endian");
+PCM_CODEC  (PCM_S24DAUD,      AV_SAMPLE_FMT_S16, pcm_s24daud,      "PCM D-Cinema audio signed 24-bit");
+PCM_CODEC  (PCM_S24LE,        AV_SAMPLE_FMT_S32, pcm_s24le,        "PCM signed 24-bit little-endian");
+PCM_CODEC  (PCM_S24LE_PLANAR, AV_SAMPLE_FMT_S32P,pcm_s24le_planar, "PCM signed 24-bit little-endian planar");
+PCM_CODEC  (PCM_S32BE,        AV_SAMPLE_FMT_S32, pcm_s32be,        "PCM signed 32-bit big-endian");
+PCM_CODEC  (PCM_S32LE,        AV_SAMPLE_FMT_S32, pcm_s32le,        "PCM signed 32-bit little-endian");
+PCM_CODEC  (PCM_S32LE_PLANAR, AV_SAMPLE_FMT_S32P,pcm_s32le_planar, "PCM signed 32-bit little-endian planar");
+PCM_CODEC  (PCM_U8,           AV_SAMPLE_FMT_U8,  pcm_u8,           "PCM unsigned 8-bit");
+PCM_CODEC  (PCM_U16BE,        AV_SAMPLE_FMT_S16, pcm_u16be,        "PCM unsigned 16-bit big-endian");
+PCM_CODEC  (PCM_U16LE,        AV_SAMPLE_FMT_S16, pcm_u16le,        "PCM unsigned 16-bit little-endian");
+PCM_CODEC  (PCM_U24BE,        AV_SAMPLE_FMT_S32, pcm_u24be,        "PCM unsigned 24-bit big-endian");
+PCM_CODEC  (PCM_U24LE,        AV_SAMPLE_FMT_S32, pcm_u24le,        "PCM unsigned 24-bit little-endian");
+PCM_CODEC  (PCM_U32BE,        AV_SAMPLE_FMT_S32, pcm_u32be,        "PCM unsigned 32-bit big-endian");
+PCM_CODEC  (PCM_U32LE,        AV_SAMPLE_FMT_S32, pcm_u32le,        "PCM unsigned 32-bit little-endian");
+PCM_DECODER(PCM_ZORK,         AV_SAMPLE_FMT_U8,  pcm_zork,         "PCM Zork");
 
diff --git a/libavcodec/pcx.c b/libavcodec/pcx.c
index 1833f6d..722e89f 100644
--- a/libavcodec/pcx.c
+++ b/libavcodec/pcx.c
@@ -31,7 +31,8 @@
     AVFrame picture;
 } PCXContext;
 
-static av_cold int pcx_init(AVCodecContext *avctx) {
+static av_cold int pcx_init(AVCodecContext *avctx)
+{
     PCXContext *s = avctx->priv_data;
 
     avcodec_get_frame_defaults(&s->picture);
@@ -40,89 +41,91 @@
     return 0;
 }
 
-/**
- * @return advanced src pointer
- */
-static const uint8_t *pcx_rle_decode(const uint8_t *src, uint8_t *dst,
-                            unsigned int bytes_per_scanline, int compressed) {
+static void pcx_rle_decode(GetByteContext *gb, uint8_t *dst,
+                           unsigned int bytes_per_scanline, int compressed)
+{
     unsigned int i = 0;
     unsigned char run, value;
 
     if (compressed) {
         while (i<bytes_per_scanline) {
             run = 1;
-            value = *src++;
+            value = bytestream2_get_byte(gb);
             if (value >= 0xc0) {
                 run = value & 0x3f;
-                value = *src++;
+                value = bytestream2_get_byte(gb);
             }
             while (i<bytes_per_scanline && run--)
                 dst[i++] = value;
         }
     } else {
-        memcpy(dst, src, bytes_per_scanline);
-        src += bytes_per_scanline;
+        bytestream2_get_buffer(gb, dst, bytes_per_scanline);
     }
-
-    return src;
 }
 
-static void pcx_palette(const uint8_t **src, uint32_t *dst, unsigned int pallen) {
-    unsigned int i;
+static void pcx_palette(GetByteContext *gb, uint32_t *dst, int pallen)
+{
+    int i;
 
+    pallen = FFMIN(pallen, bytestream2_get_bytes_left(gb) / 3);
     for (i=0; i<pallen; i++)
-        *dst++ = 0xFF000000 | bytestream_get_be24(src);
+        *dst++ = 0xFF000000 | bytestream2_get_be24u(gb);
     if (pallen < 256)
         memset(dst, 0, (256 - pallen) * sizeof(*dst));
 }
 
 static int pcx_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
-                            AVPacket *avpkt) {
-    const uint8_t *buf = avpkt->data;
-    int buf_size = avpkt->size;
+                            AVPacket *avpkt)
+{
     PCXContext * const s = avctx->priv_data;
     AVFrame *picture = data;
     AVFrame * const p = &s->picture;
-    int compressed, xmin, ymin, xmax, ymax;
+    GetByteContext gb;
+    int compressed, xmin, ymin, xmax, ymax, ret;
     unsigned int w, h, bits_per_pixel, bytes_per_line, nplanes, stride, y, x,
                  bytes_per_scanline;
-    uint8_t *ptr;
-    uint8_t const *bufstart = buf;
-    uint8_t *scanline;
-    int ret = -1;
+    uint8_t *ptr, *scanline;
 
-    if (buf[0] != 0x0a || buf[1] > 5) {
+    if (avpkt->size < 128)
+        return AVERROR_INVALIDDATA;
+
+    bytestream2_init(&gb, avpkt->data, avpkt->size);
+
+    if (bytestream2_get_byteu(&gb) != 0x0a || bytestream2_get_byteu(&gb) > 5) {
         av_log(avctx, AV_LOG_ERROR, "this is not PCX encoded data\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
-    compressed = buf[2];
-    xmin = AV_RL16(buf+ 4);
-    ymin = AV_RL16(buf+ 6);
-    xmax = AV_RL16(buf+ 8);
-    ymax = AV_RL16(buf+10);
+    compressed = bytestream2_get_byteu(&gb);
+    bits_per_pixel = bytestream2_get_byteu(&gb);
+    xmin = bytestream2_get_le16u(&gb);
+    ymin = bytestream2_get_le16u(&gb);
+    xmax = bytestream2_get_le16u(&gb);
+    ymax = bytestream2_get_le16u(&gb);
+    avctx->sample_aspect_ratio.num = bytestream2_get_le16u(&gb);
+    avctx->sample_aspect_ratio.den = bytestream2_get_le16u(&gb);
 
     if (xmax < xmin || ymax < ymin) {
         av_log(avctx, AV_LOG_ERROR, "invalid image dimensions\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     w = xmax - xmin + 1;
     h = ymax - ymin + 1;
 
-    bits_per_pixel     = buf[3];
-    bytes_per_line     = AV_RL16(buf+66);
-    nplanes            = buf[65];
+    bytestream2_skipu(&gb, 49);
+    nplanes            = bytestream2_get_byteu(&gb);
+    bytes_per_line     = bytestream2_get_le16u(&gb);
     bytes_per_scanline = nplanes * bytes_per_line;
 
     if (bytes_per_scanline < w * bits_per_pixel * nplanes / 8) {
         av_log(avctx, AV_LOG_ERROR, "PCX data is corrupted\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     switch ((nplanes<<8) + bits_per_pixel) {
         case 0x0308:
-            avctx->pix_fmt = PIX_FMT_RGB24;
+            avctx->pix_fmt = AV_PIX_FMT_RGB24;
             break;
         case 0x0108:
         case 0x0104:
@@ -131,25 +134,25 @@
         case 0x0401:
         case 0x0301:
         case 0x0201:
-            avctx->pix_fmt = PIX_FMT_PAL8;
+            avctx->pix_fmt = AV_PIX_FMT_PAL8;
             break;
         default:
             av_log(avctx, AV_LOG_ERROR, "invalid PCX file\n");
-            return -1;
+            return AVERROR_INVALIDDATA;
     }
 
-    buf += 128;
+    bytestream2_skipu(&gb, 60);
 
     if (p->data[0])
         avctx->release_buffer(avctx, p);
 
     if (av_image_check_size(w, h, 0, avctx))
-        return -1;
+        return AVERROR_INVALIDDATA;
     if (w != avctx->width || h != avctx->height)
         avcodec_set_dimensions(avctx, w, h);
-    if (avctx->get_buffer(avctx, p) < 0) {
+    if ((ret = avctx->get_buffer(avctx, p)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
+        return ret;
     }
 
     p->pict_type = AV_PICTURE_TYPE_I;
@@ -163,7 +166,7 @@
 
     if (nplanes == 3 && bits_per_pixel == 8) {
         for (y=0; y<h; y++) {
-            buf = pcx_rle_decode(buf, scanline, bytes_per_scanline, compressed);
+            pcx_rle_decode(&gb, scanline, bytes_per_scanline, compressed);
 
             for (x=0; x<w; x++) {
                 ptr[3*x  ] = scanline[x                    ];
@@ -175,19 +178,20 @@
         }
 
     } else if (nplanes == 1 && bits_per_pixel == 8) {
-        const uint8_t *palstart = bufstart + buf_size - 769;
+        int palstart = avpkt->size - 769;
 
         for (y=0; y<h; y++, ptr+=stride) {
-            buf = pcx_rle_decode(buf, scanline, bytes_per_scanline, compressed);
+            pcx_rle_decode(&gb, scanline, bytes_per_scanline, compressed);
             memcpy(ptr, scanline, w);
         }
 
-        if (buf != palstart) {
+        if (bytestream2_tell(&gb) != palstart) {
             av_log(avctx, AV_LOG_WARNING, "image data possibly corrupted\n");
-            buf = palstart;
+            bytestream2_seek(&gb, palstart, SEEK_SET);
         }
-        if (*buf++ != 12) {
+        if (bytestream2_get_byte(&gb) != 12) {
             av_log(avctx, AV_LOG_ERROR, "expected palette after image data\n");
+            ret = AVERROR_INVALIDDATA;
             goto end;
         }
 
@@ -197,7 +201,7 @@
         for (y=0; y<h; y++) {
             init_get_bits(&s, scanline, bytes_per_scanline<<3);
 
-            buf = pcx_rle_decode(buf, scanline, bytes_per_scanline, compressed);
+            pcx_rle_decode(&gb, scanline, bytes_per_scanline, compressed);
 
             for (x=0; x<w; x++)
                 ptr[x] = get_bits(&s, bits_per_pixel);
@@ -208,7 +212,7 @@
         int i;
 
         for (y=0; y<h; y++) {
-            buf = pcx_rle_decode(buf, scanline, bytes_per_scanline, compressed);
+            pcx_rle_decode(&gb, scanline, bytes_per_scanline, compressed);
 
             for (x=0; x<w; x++) {
                 int m = 0x80 >> (x&7), v = 0;
@@ -222,26 +226,28 @@
         }
     }
 
+    ret = bytestream2_tell(&gb);
     if (nplanes == 1 && bits_per_pixel == 8) {
-        pcx_palette(&buf, (uint32_t *) p->data[1], 256);
+        pcx_palette(&gb, (uint32_t *) p->data[1], 256);
+        ret += 256 * 3;
     } else if (bits_per_pixel * nplanes == 1) {
         AV_WN32A(p->data[1]  , 0xFF000000);
         AV_WN32A(p->data[1]+4, 0xFFFFFFFF);
     } else if (bits_per_pixel < 8) {
-        const uint8_t *palette = bufstart+16;
-        pcx_palette(&palette, (uint32_t *) p->data[1], 16);
+        bytestream2_seek(&gb, 16, SEEK_SET);
+        pcx_palette(&gb, (uint32_t *) p->data[1], 16);
     }
 
     *picture = s->picture;
     *data_size = sizeof(AVFrame);
 
-    ret = buf - bufstart;
 end:
     av_free(scanline);
     return ret;
 }
 
-static av_cold int pcx_end(AVCodecContext *avctx) {
+static av_cold int pcx_end(AVCodecContext *avctx)
+{
     PCXContext *s = avctx->priv_data;
 
     if(s->picture.data[0])
diff --git a/libavcodec/pcxenc.c b/libavcodec/pcxenc.c
index 63c7d23..7cb3af3 100644
--- a/libavcodec/pcxenc.c
+++ b/libavcodec/pcxenc.c
@@ -105,7 +105,7 @@
     const uint8_t *buf_end;
     uint8_t *buf;
 
-    int bpp, nplanes, i, y, line_bytes, written, ret, max_pkt_size;
+    int bpp, nplanes, i, y, line_bytes, written, ret, max_pkt_size, sw, sh;
     const uint32_t *pal = NULL;
     uint32_t palette256[256];
     const uint8_t *src;
@@ -120,26 +120,26 @@
     }
 
     switch (avctx->pix_fmt) {
-    case PIX_FMT_RGB24:
+    case AV_PIX_FMT_RGB24:
         bpp = 8;
         nplanes = 3;
         break;
-    case PIX_FMT_RGB8:
-    case PIX_FMT_BGR8:
-    case PIX_FMT_RGB4_BYTE:
-    case PIX_FMT_BGR4_BYTE:
-    case PIX_FMT_GRAY8:
+    case AV_PIX_FMT_RGB8:
+    case AV_PIX_FMT_BGR8:
+    case AV_PIX_FMT_RGB4_BYTE:
+    case AV_PIX_FMT_BGR4_BYTE:
+    case AV_PIX_FMT_GRAY8:
         bpp = 8;
         nplanes = 1;
-        ff_set_systematic_pal2(palette256, avctx->pix_fmt);
+        avpriv_set_systematic_pal2(palette256, avctx->pix_fmt);
         pal = palette256;
         break;
-    case PIX_FMT_PAL8:
+    case AV_PIX_FMT_PAL8:
         bpp = 8;
         nplanes = 1;
         pal = (uint32_t *)pict->data[1];
         break;
-    case PIX_FMT_MONOBLACK:
+    case AV_PIX_FMT_MONOBLACK:
         bpp = 1;
         nplanes = 1;
         pal = monoblack_pal;
@@ -158,6 +158,11 @@
     buf     = pkt->data;
     buf_end = pkt->data + pkt->size;
 
+    sw = avctx->sample_aspect_ratio.num;
+    sh = avctx->sample_aspect_ratio.den;
+    if (sw > 0xFFFFu || sh > 0xFFFFu)
+        av_reduce(&sw, &sh, sw, sh, 0xFFFFu);
+
     bytestream_put_byte(&buf, 10);                  // manufacturer
     bytestream_put_byte(&buf, 5);                   // version
     bytestream_put_byte(&buf, 1);                   // encoding
@@ -166,8 +171,8 @@
     bytestream_put_le16(&buf, 0);                   // y min
     bytestream_put_le16(&buf, avctx->width - 1);    // x max
     bytestream_put_le16(&buf, avctx->height - 1);   // y max
-    bytestream_put_le16(&buf, 0);                   // horizontal DPI
-    bytestream_put_le16(&buf, 0);                   // vertical DPI
+    bytestream_put_le16(&buf, sw);                  // horizontal DPI
+    bytestream_put_le16(&buf, sh);                  // vertical DPI
     for (i = 0; i < 16; i++)
         bytestream_put_be24(&buf, pal ? pal[i] : 0);// palette (<= 16 color only)
     bytestream_put_byte(&buf, 0);                   // reserved
@@ -214,12 +219,12 @@
     .priv_data_size = sizeof(PCXContext),
     .init           = pcx_encode_init,
     .encode2        = pcx_encode_frame,
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_RGB24,
-        PIX_FMT_RGB8, PIX_FMT_BGR8, PIX_FMT_RGB4_BYTE, PIX_FMT_BGR4_BYTE,
-        PIX_FMT_GRAY8, PIX_FMT_PAL8,
-        PIX_FMT_MONOBLACK,
-        PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_RGB24,
+        AV_PIX_FMT_RGB8, AV_PIX_FMT_BGR8, AV_PIX_FMT_RGB4_BYTE, AV_PIX_FMT_BGR4_BYTE,
+        AV_PIX_FMT_GRAY8, AV_PIX_FMT_PAL8,
+        AV_PIX_FMT_MONOBLACK,
+        AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("PC Paintbrush PCX image"),
 };
diff --git a/libavcodec/pgssubdec.c b/libavcodec/pgssubdec.c
index 728f178..d0cff7b 100644
--- a/libavcodec/pgssubdec.c
+++ b/libavcodec/pgssubdec.c
@@ -52,6 +52,7 @@
     int                    id_number;
     int                    object_count;
     PGSSubPictureReference *objects;
+    int64_t pts;
 } PGSSubPresentation;
 
 typedef struct PGSSubPicture {
@@ -67,13 +68,12 @@
     PGSSubPresentation presentation;
     uint32_t           clut[256];
     PGSSubPicture      pictures[UINT16_MAX];
-    int64_t            pts;
     int forced_subs_only;
 } PGSSubContext;
 
 static av_cold int init_decoder(AVCodecContext *avctx)
 {
-    avctx->pix_fmt     = PIX_FMT_PAL8;
+    avctx->pix_fmt     = AV_PIX_FMT_PAL8;
 
     return 0;
 }
@@ -222,6 +222,11 @@
         return -1;
     }
 
+    if (buf_size > rle_bitmap_len) {
+        av_log(avctx, AV_LOG_ERROR, "too much RLE data\n");
+        return AVERROR_INVALIDDATA;
+    }
+
     ctx->pictures[picture_id].w = width;
     ctx->pictures[picture_id].h = height;
 
@@ -290,7 +295,8 @@
  * @todo TODO: Implement cropping
  */
 static void parse_presentation_segment(AVCodecContext *avctx,
-                                       const uint8_t *buf, int buf_size)
+                                       const uint8_t *buf, int buf_size,
+                                       int64_t pts)
 {
     PGSSubContext *ctx = avctx->priv_data;
 
@@ -299,6 +305,8 @@
 
     uint16_t object_index;
 
+    ctx->presentation.pts = pts;
+
     av_dlog(avctx, "Video Dimensions %dx%d\n",
             w, h);
     if (av_image_check_size(w, h, 0, avctx) >= 0)
@@ -389,10 +397,10 @@
      *      not been cleared by a subsequent empty display command.
      */
 
-    pts = ctx->pts != AV_NOPTS_VALUE ? ctx->pts : sub->pts;
+    pts = ctx->presentation.pts != AV_NOPTS_VALUE ? ctx->presentation.pts : sub->pts;
     memset(sub, 0, sizeof(*sub));
     sub->pts = pts;
-    ctx->pts = AV_NOPTS_VALUE;
+    ctx->presentation.pts = AV_NOPTS_VALUE;
 
     // Blank if last object_count was 0.
     if (!ctx->presentation.object_count)
@@ -429,7 +437,7 @@
         sub->rects[rect]->pict.data[1] = av_mallocz(AVPALETTE_SIZE);
 
         /* Copy the forced flag */
-        sub->rects[rect]->forced = (ctx->presentation.objects[rect].composition & 0x40) != 0;
+        sub->rects[rect]->flags = (ctx->presentation.objects[rect].composition & 0x40) != 0 ? AV_SUBTITLE_FLAG_FORCED : 0;
 
         if (!ctx->forced_subs_only || ctx->presentation.objects[rect].composition & 0x40)
         memcpy(sub->rects[rect]->pict.data[1], ctx->clut, sub->rects[rect]->nb_colors * sizeof(uint32_t));
@@ -441,7 +449,6 @@
 static int decode(AVCodecContext *avctx, void *data, int *data_size,
                   AVPacket *avpkt)
 {
-    PGSSubContext *ctx = avctx->priv_data;
     const uint8_t *buf = avpkt->data;
     int buf_size       = avpkt->size;
     AVSubtitle *sub    = data;
@@ -488,8 +495,7 @@
             parse_picture_segment(avctx, buf, segment_length);
             break;
         case PRESENTATION_SEGMENT:
-            parse_presentation_segment(avctx, buf, segment_length);
-            ctx->pts = sub->pts;
+            parse_presentation_segment(avctx, buf, segment_length, sub->pts);
             break;
         case WINDOW_SEGMENT:
             /*
diff --git a/libavcodec/pictordec.c b/libavcodec/pictordec.c
index 5d1e6ee..748d9b3 100644
--- a/libavcodec/pictordec.c
+++ b/libavcodec/pictordec.c
@@ -111,7 +111,7 @@
     PicContext *s = avctx->priv_data;
     uint32_t *palette;
     int bits_per_plane, bpp, etype, esize, npal, pos_after_pal;
-    int i, x, y, plane, tmp;
+    int i, x, y, plane, tmp, val;
 
     bytestream2_init(&s->g, avpkt->data, avpkt->size);
 
@@ -133,7 +133,7 @@
         return AVERROR_INVALIDDATA;
     }
 
-    if (bytestream2_peek_byte(&s->g) == 0xFF || bpp == 8) {
+    if (bytestream2_peek_byte(&s->g) == 0xFF || bpp == 1 || bpp == 4 || bpp == 8) {
         bytestream2_skip(&s->g, 2);
         etype = bytestream2_get_le16(&s->g);
         esize = bytestream2_get_le16(&s->g);
@@ -144,7 +144,7 @@
         esize = 0;
     }
 
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     if (s->width != avctx->width && s->height != avctx->height) {
         if (av_image_check_size(s->width, s->height, 0, avctx) < 0)
@@ -206,6 +206,7 @@
     // skip remaining palette bytes
     bytestream2_seek(&s->g, pos_after_pal, SEEK_SET);
 
+    val = 0;
     y = s->height - 1;
     if (bytestream2_get_le16(&s->g)) {
         x = 0;
@@ -223,7 +224,7 @@
             while (plane < s->nb_planes && y >= 0 &&
                    bytestream2_get_bytes_left(&s->g) > stop_size) {
                 int run = 1;
-                int val = bytestream2_get_byte(&s->g);
+                val = bytestream2_get_byte(&s->g);
                 if (val == marker) {
                     run = bytestream2_get_byte(&s->g);
                     if (run == 0)
@@ -240,6 +241,14 @@
                 }
             }
         }
+
+        if (x < avctx->width && y >= 0) {
+            int run = (y + 1) * avctx->width - x;
+            if (bits_per_plane == 8)
+                picmemset_8bpp(s, val, run, &x, &y);
+            else
+                picmemset(s, val, run / (8 / bits_per_plane), &x, &y, &plane, bits_per_plane);
+        }
     } else {
         while (y >= 0 && bytestream2_get_bytes_left(&s->g) > 0) {
             memcpy(s->frame.data[0] + y * s->frame.linesize[0], s->g.buffer, FFMIN(avctx->width, bytestream2_get_bytes_left(&s->g)));
diff --git a/libavcodec/pngdec.c b/libavcodec/pngdec.c
index a5faeba..c1b8b08 100644
--- a/libavcodec/pngdec.c
+++ b/libavcodec/pngdec.c
@@ -21,6 +21,7 @@
 
 //#define DEBUG
 
+#include "libavutil/bprint.h"
 #include "libavutil/imgutils.h"
 #include "avcodec.h"
 #include "bytestream.h"
@@ -386,6 +387,122 @@
     return 0;
 }
 
+static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
+                       const uint8_t *data_end)
+{
+    z_stream zstream;
+    unsigned char *buf;
+    unsigned buf_size;
+    int ret;
+
+    zstream.zalloc = ff_png_zalloc;
+    zstream.zfree  = ff_png_zfree;
+    zstream.opaque = NULL;
+    if (inflateInit(&zstream) != Z_OK)
+        return AVERROR_EXTERNAL;
+    zstream.next_in  = (unsigned char *)data;
+    zstream.avail_in = data_end - data;
+    av_bprint_init(bp, 0, -1);
+
+    while (zstream.avail_in > 0) {
+        av_bprint_get_buffer(bp, 1, &buf, &buf_size);
+        if (!buf_size) {
+            ret = AVERROR(ENOMEM);
+            goto fail;
+        }
+        zstream.next_out  = buf;
+        zstream.avail_out = buf_size;
+        ret = inflate(&zstream, Z_PARTIAL_FLUSH);
+        if (ret != Z_OK && ret != Z_STREAM_END) {
+            ret = AVERROR_EXTERNAL;
+            goto fail;
+        }
+        bp->len += zstream.next_out - buf;
+        if (ret == Z_STREAM_END)
+            break;
+    }
+    inflateEnd(&zstream);
+    bp->str[bp->len] = 0;
+    return 0;
+
+fail:
+    inflateEnd(&zstream);
+    av_bprint_finalize(bp, NULL);
+    return ret;
+}
+
+static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
+{
+    size_t extra = 0, i;
+    uint8_t *out, *q;
+
+    for (i = 0; i < size_in; i++)
+        extra += in[i] >= 0x80;
+    if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
+        return NULL;
+    q = out = av_malloc(size_in + extra + 1);
+    if (!out)
+        return NULL;
+    for (i = 0; i < size_in; i++) {
+        if (in[i] >= 0x80) {
+            *(q++) = 0xC0 | (in[i] >> 6);
+            *(q++) = 0x80 | (in[i] & 0x3F);
+        } else {
+            *(q++) = in[i];
+        }
+    }
+    *(q++) = 0;
+    return out;
+}
+
+static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed,
+                             AVDictionary **dict)
+{
+    int ret, method;
+    const uint8_t *data        = s->gb.buffer;
+    const uint8_t *data_end    = data + length;
+    const uint8_t *keyword     = data;
+    const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
+    uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
+    unsigned text_len;
+    AVBPrint bp;
+
+    if (!keyword_end)
+        return AVERROR_INVALIDDATA;
+    data = keyword_end + 1;
+
+    if (compressed) {
+        if (data == data_end)
+            return AVERROR_INVALIDDATA;
+        method = *(data++);
+        if (method)
+            return AVERROR_INVALIDDATA;
+        if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
+            return ret;
+        text_len = bp.len;
+        av_bprint_finalize(&bp, (char **)&text);
+        if (!text)
+            return AVERROR(ENOMEM);
+    } else {
+        text = (uint8_t *)data;
+        text_len = data_end - text;
+    }
+
+    kw_utf8  = iso88591_to_utf8(keyword, keyword_end - keyword);
+    txt_utf8 = iso88591_to_utf8(text, text_len);
+    if (text != data)
+        av_free(text);
+    if (!(kw_utf8 && txt_utf8)) {
+        av_free(kw_utf8);
+        av_free(txt_utf8);
+        return AVERROR(ENOMEM);
+    }
+
+    av_dict_set(dict, kw_utf8, txt_utf8,
+                AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
+    return 0;
+}
+
 static int decode_frame(AVCodecContext *avctx,
                         void *data, int *data_size,
                         AVPacket *avpkt)
@@ -395,6 +512,7 @@
     PNGDecContext * const s = avctx->priv_data;
     AVFrame *picture = data;
     AVFrame *p;
+    AVDictionary *metadata = NULL;
     uint8_t *crow_buf_base = NULL;
     uint32_t tag, length;
     int64_t sig;
@@ -467,6 +585,18 @@
                     s->width, s->height, s->bit_depth, s->color_type,
                     s->compression_type, s->filter_type, s->interlace_type);
             break;
+        case MKTAG('p', 'H', 'Y', 's'):
+            if (s->state & PNG_IDAT) {
+                av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
+                goto fail;
+            }
+            avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
+            avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
+            if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
+                avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
+            bytestream2_skip(&s->gb, 1); /* unit specifier */
+            bytestream2_skip(&s->gb, 4); /* crc */
+            break;
         case MKTAG('I', 'D', 'A', 'T'):
             if (!(s->state & PNG_IHDR)) {
                 av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
@@ -484,30 +614,30 @@
 
                 if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
                     s->color_type == PNG_COLOR_TYPE_RGB) {
-                    avctx->pix_fmt = PIX_FMT_RGB24;
+                    avctx->pix_fmt = AV_PIX_FMT_RGB24;
                 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
                            s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
-                    avctx->pix_fmt = PIX_FMT_RGBA;
+                    avctx->pix_fmt = AV_PIX_FMT_RGBA;
                 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
                            s->color_type == PNG_COLOR_TYPE_GRAY) {
-                    avctx->pix_fmt = PIX_FMT_GRAY8;
+                    avctx->pix_fmt = AV_PIX_FMT_GRAY8;
                 } else if (s->bit_depth == 16 &&
                            s->color_type == PNG_COLOR_TYPE_GRAY) {
-                    avctx->pix_fmt = PIX_FMT_GRAY16BE;
+                    avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
                 } else if (s->bit_depth == 16 &&
                            s->color_type == PNG_COLOR_TYPE_RGB) {
-                    avctx->pix_fmt = PIX_FMT_RGB48BE;
+                    avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
                 } else if (s->bit_depth == 16 &&
                            s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
-                    avctx->pix_fmt = PIX_FMT_RGBA64BE;
+                    avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
                 } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
                            s->color_type == PNG_COLOR_TYPE_PALETTE) {
-                    avctx->pix_fmt = PIX_FMT_PAL8;
+                    avctx->pix_fmt = AV_PIX_FMT_PAL8;
                 } else if (s->bit_depth == 1) {
-                    avctx->pix_fmt = PIX_FMT_MONOBLACK;
+                    avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
                 } else if (s->bit_depth == 8 &&
                            s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
-                    avctx->pix_fmt = PIX_FMT_Y400A;
+                    avctx->pix_fmt = AV_PIX_FMT_Y400A;
                 } else {
                     av_log(avctx, AV_LOG_ERROR, "unsupported bit depth %d "
                                                 "and color type %d\n",
@@ -541,7 +671,7 @@
                 s->image_buf = p->data[0];
                 s->image_linesize = p->linesize[0];
                 /* copy the palette if needed */
-                if (avctx->pix_fmt == PIX_FMT_PAL8)
+                if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
                     memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
                 /* empty row is used if differencing to the first row */
                 s->last_row = av_mallocz(s->row_size);
@@ -580,10 +710,10 @@
                     r = bytestream2_get_byte(&s->gb);
                     g = bytestream2_get_byte(&s->gb);
                     b = bytestream2_get_byte(&s->gb);
-                    s->palette[i] = (0xff << 24) | (r << 16) | (g << 8) | b;
+                    s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
                 }
                 for(;i<256;i++) {
-                    s->palette[i] = (0xff << 24);
+                    s->palette[i] = (0xFFU << 24);
                 }
                 s->state |= PNG_PLTE;
                 bytestream2_skip(&s->gb, 4); /* crc */
@@ -605,6 +735,16 @@
                 bytestream2_skip(&s->gb, 4); /* crc */
             }
             break;
+        case MKTAG('t', 'E', 'X', 't'):
+            if (decode_text_chunk(s, length, 0, &metadata) < 0)
+                av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
+            bytestream2_skip(&s->gb, length + 4);
+            break;
+        case MKTAG('z', 'T', 'X', 't'):
+            if (decode_text_chunk(s, length, 1, &metadata) < 0)
+                av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
+            bytestream2_skip(&s->gb, length + 4);
+            break;
         case MKTAG('I', 'E', 'N', 'D'):
             if (!(s->state & PNG_ALLIMAGE))
                 av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
@@ -685,6 +825,7 @@
          if(   !(avpkt->flags & AV_PKT_FLAG_KEY)
             && s->last_picture->width == s->current_picture->width
             && s->last_picture->height== s->current_picture->height
+            && s->last_picture->format== s->current_picture->format
          ) {
             int i, j;
             uint8_t *pd = s->current_picture->data[0];
@@ -700,6 +841,8 @@
         }
     }
 
+    s->current_picture->metadata = metadata;
+    metadata = NULL;
     *picture= *s->current_picture;
     *data_size = sizeof(AVFrame);
 
@@ -712,6 +855,7 @@
     av_freep(&s->tmp_row);
     return ret;
  fail:
+    av_dict_free(&metadata);
     ret = -1;
     goto the_end;
 }
diff --git a/libavcodec/pngdsp.c b/libavcodec/pngdsp.c
index 75ec996..1ee8b57 100644
--- a/libavcodec/pngdsp.c
+++ b/libavcodec/pngdsp.c
@@ -44,5 +44,5 @@
     dsp->add_bytes_l2         = add_bytes_l2_c;
     dsp->add_paeth_prediction = ff_add_png_paeth_prediction;
 
-    if (HAVE_MMX) ff_pngdsp_init_x86(dsp);
+    if (ARCH_X86) ff_pngdsp_init_x86(dsp);
 }
diff --git a/libavcodec/pngenc.c b/libavcodec/pngenc.c
index 0d00a08..c91f289 100644
--- a/libavcodec/pngenc.c
+++ b/libavcodec/pngenc.c
@@ -235,43 +235,43 @@
 
     is_progressive = !!(avctx->flags & CODEC_FLAG_INTERLACED_DCT);
     switch(avctx->pix_fmt) {
-    case PIX_FMT_RGBA64BE:
+    case AV_PIX_FMT_RGBA64BE:
         bit_depth = 16;
         color_type = PNG_COLOR_TYPE_RGB_ALPHA;
         break;
-    case PIX_FMT_RGB48BE:
+    case AV_PIX_FMT_RGB48BE:
         bit_depth = 16;
         color_type = PNG_COLOR_TYPE_RGB;
         break;
-    case PIX_FMT_RGBA:
+    case AV_PIX_FMT_RGBA:
         avctx->bits_per_coded_sample = 32;
         bit_depth = 8;
         color_type = PNG_COLOR_TYPE_RGB_ALPHA;
         break;
-    case PIX_FMT_RGB24:
+    case AV_PIX_FMT_RGB24:
         avctx->bits_per_coded_sample = 24;
         bit_depth = 8;
         color_type = PNG_COLOR_TYPE_RGB;
         break;
-    case PIX_FMT_GRAY16BE:
+    case AV_PIX_FMT_GRAY16BE:
         bit_depth = 16;
         color_type = PNG_COLOR_TYPE_GRAY;
         break;
-    case PIX_FMT_GRAY8:
+    case AV_PIX_FMT_GRAY8:
         avctx->bits_per_coded_sample = 0x28;
         bit_depth = 8;
         color_type = PNG_COLOR_TYPE_GRAY;
         break;
-    case PIX_FMT_GRAY8A:
+    case AV_PIX_FMT_GRAY8A:
         bit_depth = 8;
         color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
         break;
-    case PIX_FMT_MONOBLACK:
+    case AV_PIX_FMT_MONOBLACK:
         avctx->bits_per_coded_sample =
         bit_depth = 1;
         color_type = PNG_COLOR_TYPE_GRAY;
         break;
-    case PIX_FMT_PAL8:
+    case AV_PIX_FMT_PAL8:
         avctx->bits_per_coded_sample =
         bit_depth = 8;
         color_type = PNG_COLOR_TYPE_PALETTE;
@@ -335,6 +335,11 @@
 
     png_write_chunk(&s->bytestream, MKTAG('I', 'H', 'D', 'R'), s->buf, 13);
 
+    AV_WB32(s->buf, avctx->sample_aspect_ratio.num);
+    AV_WB32(s->buf + 4, avctx->sample_aspect_ratio.den);
+    s->buf[8] = 0; /* unit specifier is unknown */
+    png_write_chunk(&s->bytestream, MKTAG('p', 'H', 'Y', 's'), s->buf, 9);
+
     /* put the palette if needed */
     if (color_type == PNG_COLOR_TYPE_PALETTE) {
         int has_alpha, alpha, i;
@@ -437,7 +442,7 @@
     ff_dsputil_init(&s->dsp, avctx);
 
     s->filter_type = av_clip(avctx->prediction_method, PNG_FILTER_VALUE_NONE, PNG_FILTER_VALUE_MIXED);
-    if(avctx->pix_fmt == PIX_FMT_MONOBLACK)
+    if(avctx->pix_fmt == AV_PIX_FMT_MONOBLACK)
         s->filter_type = PNG_FILTER_VALUE_NONE;
 
     return 0;
@@ -451,13 +456,13 @@
     .init           = png_enc_init,
     .encode2        = encode_frame,
     .capabilities   = CODEC_CAP_FRAME_THREADS | CODEC_CAP_INTRA_ONLY,
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_RGB24, PIX_FMT_RGBA,
-        PIX_FMT_RGB48BE, PIX_FMT_RGBA64BE,
-        PIX_FMT_PAL8,
-        PIX_FMT_GRAY8, PIX_FMT_GRAY8A,
-        PIX_FMT_GRAY16BE,
-        PIX_FMT_MONOBLACK, PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA,
+        AV_PIX_FMT_RGB48BE, AV_PIX_FMT_RGBA64BE,
+        AV_PIX_FMT_PAL8,
+        AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY8A,
+        AV_PIX_FMT_GRAY16BE,
+        AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
 };
diff --git a/libavcodec/pnm.c b/libavcodec/pnm.c
index a5cf766..13ecbb0 100644
--- a/libavcodec/pnm.c
+++ b/libavcodec/pnm.c
@@ -68,14 +68,14 @@
         return -1;
 
     if (s->type==1 || s->type==4) {
-        avctx->pix_fmt = PIX_FMT_MONOWHITE;
+        avctx->pix_fmt = AV_PIX_FMT_MONOWHITE;
     } else if (s->type==2 || s->type==5) {
         if (avctx->codec_id == AV_CODEC_ID_PGMYUV)
-            avctx->pix_fmt = PIX_FMT_YUV420P;
+            avctx->pix_fmt = AV_PIX_FMT_YUV420P;
         else
-            avctx->pix_fmt = PIX_FMT_GRAY8;
+            avctx->pix_fmt = AV_PIX_FMT_GRAY8;
     } else if (s->type==3 || s->type==6) {
-        avctx->pix_fmt = PIX_FMT_RGB24;
+        avctx->pix_fmt = AV_PIX_FMT_RGB24;
     } else if (s->type==7) {
         w      = -1;
         h      = -1;
@@ -115,26 +115,26 @@
         s->maxval     = maxval;
         if (depth == 1) {
             if (maxval == 1) {
-                avctx->pix_fmt = PIX_FMT_MONOBLACK;
+                avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
             } else if (maxval == 255) {
-                avctx->pix_fmt = PIX_FMT_GRAY8;
+                avctx->pix_fmt = AV_PIX_FMT_GRAY8;
             } else {
-                avctx->pix_fmt = PIX_FMT_GRAY16BE;
+                avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
             }
         } else if (depth == 2) {
             if (maxval == 255)
-                avctx->pix_fmt = PIX_FMT_GRAY8A;
+                avctx->pix_fmt = AV_PIX_FMT_GRAY8A;
         } else if (depth == 3) {
             if (maxval < 256) {
-            avctx->pix_fmt = PIX_FMT_RGB24;
+                avctx->pix_fmt = AV_PIX_FMT_RGB24;
             } else {
-                avctx->pix_fmt = PIX_FMT_RGB48BE;
+                avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
             }
         } else if (depth == 4) {
             if (maxval < 256) {
-                avctx->pix_fmt = PIX_FMT_RGBA;
+                avctx->pix_fmt = AV_PIX_FMT_RGBA;
             } else {
-                avctx->pix_fmt = PIX_FMT_RGBA64BE;
+                avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
             }
         } else {
             return -1;
@@ -153,7 +153,7 @@
     avctx->width  = w;
     avctx->height = h;
 
-    if (avctx->pix_fmt != PIX_FMT_MONOWHITE && avctx->pix_fmt != PIX_FMT_MONOBLACK) {
+    if (avctx->pix_fmt != AV_PIX_FMT_MONOWHITE && avctx->pix_fmt != AV_PIX_FMT_MONOBLACK) {
         pnm_get(s, buf1, sizeof(buf1));
         s->maxval = atoi(buf1);
         if (s->maxval <= 0) {
@@ -161,23 +161,20 @@
             s->maxval = 255;
         }
         if (s->maxval >= 256) {
-            if (avctx->pix_fmt == PIX_FMT_GRAY8) {
-                avctx->pix_fmt = PIX_FMT_GRAY16BE;
-                if (s->maxval != 65535)
-                    avctx->pix_fmt = PIX_FMT_GRAY16;
-            } else if (avctx->pix_fmt == PIX_FMT_RGB24) {
-                if (s->maxval > 255)
-                    avctx->pix_fmt = PIX_FMT_RGB48BE;
+            if (avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
+                avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
+            } else if (avctx->pix_fmt == AV_PIX_FMT_RGB24) {
+                avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
             } else {
                 av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format\n");
-                avctx->pix_fmt = PIX_FMT_NONE;
+                avctx->pix_fmt = AV_PIX_FMT_NONE;
                 return -1;
             }
         }
     }else
         s->maxval=1;
     /* more check if YUV420 */
-    if (avctx->pix_fmt == PIX_FMT_YUV420P) {
+    if (avctx->pix_fmt == AV_PIX_FMT_YUV420P) {
         if ((avctx->width & 1) != 0)
             return -1;
         h = (avctx->height * 2);
diff --git a/libavcodec/pnmdec.c b/libavcodec/pnmdec.c
index c6dfa2c..66fc9df 100644
--- a/libavcodec/pnmdec.c
+++ b/libavcodec/pnmdec.c
@@ -34,71 +34,71 @@
     AVFrame * const p    = &s->picture;
     int i, j, n, linesize, h, upgrade = 0, is_mono = 0;
     unsigned char *ptr;
-    int components, sample_len;
+    int components, sample_len, ret;
 
     s->bytestream_start =
     s->bytestream       = (uint8_t *)buf;
     s->bytestream_end   = (uint8_t *)buf + buf_size;
 
     if (ff_pnm_decode_header(avctx, s) < 0)
-        return -1;
+        return AVERROR_INVALIDDATA;
 
     if (p->data[0])
         avctx->release_buffer(avctx, p);
 
     p->reference = 0;
-    if (avctx->get_buffer(avctx, p) < 0) {
+    if ((ret = avctx->get_buffer(avctx, p)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
+        return ret;
     }
     p->pict_type = AV_PICTURE_TYPE_I;
     p->key_frame = 1;
 
     switch (avctx->pix_fmt) {
     default:
-        return -1;
-    case PIX_FMT_RGBA64BE:
+        return AVERROR_INVALIDDATA;
+    case AV_PIX_FMT_RGBA64BE:
         n = avctx->width * 8;
         components=4;
         sample_len=16;
         goto do_read;
-    case PIX_FMT_RGB48BE:
+    case AV_PIX_FMT_RGB48BE:
         n = avctx->width * 6;
         components=3;
         sample_len=16;
         goto do_read;
-    case PIX_FMT_RGBA:
+    case AV_PIX_FMT_RGBA:
         n = avctx->width * 4;
         components=4;
         sample_len=8;
         goto do_read;
-    case PIX_FMT_RGB24:
+    case AV_PIX_FMT_RGB24:
         n = avctx->width * 3;
         components=3;
         sample_len=8;
         goto do_read;
-    case PIX_FMT_GRAY8:
+    case AV_PIX_FMT_GRAY8:
         n = avctx->width;
         components=1;
         sample_len=8;
         if (s->maxval < 255)
             upgrade = 1;
         goto do_read;
-    case PIX_FMT_GRAY8A:
+    case AV_PIX_FMT_GRAY8A:
         n = avctx->width * 2;
         components=2;
         sample_len=8;
         goto do_read;
-    case PIX_FMT_GRAY16BE:
-    case PIX_FMT_GRAY16LE:
+    case AV_PIX_FMT_GRAY16BE:
+    case AV_PIX_FMT_GRAY16LE:
         n = avctx->width * 2;
         components=1;
         sample_len=16;
         if (s->maxval < 65535)
             upgrade = 2;
         goto do_read;
-    case PIX_FMT_MONOWHITE:
-    case PIX_FMT_MONOBLACK:
+    case AV_PIX_FMT_MONOWHITE:
+    case AV_PIX_FMT_MONOBLACK:
         n = (avctx->width + 7) >> 3;
         components=1;
         sample_len=1;
@@ -107,7 +107,7 @@
         ptr      = p->data[0];
         linesize = p->linesize[0];
         if (s->bytestream + n * avctx->height > s->bytestream_end)
-            return -1;
+            return AVERROR_INVALIDDATA;
         if(s->type < 4 || (is_mono && s->type==7)){
             for (i=0; i<avctx->height; i++) {
                 PutBitContext pb;
@@ -119,7 +119,7 @@
                     while(s->bytestream < s->bytestream_end && (*s->bytestream < '0' || *s->bytestream > '9' ))
                         s->bytestream++;
                     if(s->bytestream >= s->bytestream_end)
-                        return -1;
+                        return AVERROR_INVALIDDATA;
                     if (is_mono) {
                         /* read a single digit */
                         v = (*s->bytestream++)&1;
@@ -155,7 +155,7 @@
         }
         }
         break;
-    case PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUV420P:
         {
             unsigned char *ptr1, *ptr2;
 
@@ -163,7 +163,7 @@
             ptr      = p->data[0];
             linesize = p->linesize[0];
             if (s->bytestream + n * avctx->height * 3 / 2 > s->bytestream_end)
-                return -1;
+                return AVERROR_INVALIDDATA;
             for (i = 0; i < avctx->height; i++) {
                 memcpy(ptr, s->bytestream, n);
                 s->bytestream += n;
diff --git a/libavcodec/pnmenc.c b/libavcodec/pnmenc.c
index 00d82f5..ab20cf5 100644
--- a/libavcodec/pnmenc.c
+++ b/libavcodec/pnmenc.c
@@ -48,29 +48,29 @@
     h  = avctx->height;
     h1 = h;
     switch (avctx->pix_fmt) {
-    case PIX_FMT_MONOWHITE:
+    case AV_PIX_FMT_MONOWHITE:
         c  = '4';
         n  = (avctx->width + 7) >> 3;
         break;
-    case PIX_FMT_GRAY8:
+    case AV_PIX_FMT_GRAY8:
         c  = '5';
         n  = avctx->width;
         break;
-    case PIX_FMT_GRAY16BE:
+    case AV_PIX_FMT_GRAY16BE:
         c  = '5';
         n  = avctx->width * 2;
         break;
-    case PIX_FMT_RGB24:
+    case AV_PIX_FMT_RGB24:
         c  = '6';
         n  = avctx->width * 3;
         break;
-    case PIX_FMT_RGB48BE:
+    case AV_PIX_FMT_RGB48BE:
         c  = '6';
         n  = avctx->width * 6;
         break;
-    case PIX_FMT_YUV420P:
-        if (avctx->width & 1) {
-            av_log(avctx, AV_LOG_ERROR, "pgmyuv needs even width\n");
+    case AV_PIX_FMT_YUV420P:
+        if (avctx->width & 1 || avctx->height & 1) {
+            av_log(avctx, AV_LOG_ERROR, "pgmyuv needs even width and height\n");
             return AVERROR(EINVAL);
         }
         c  = '5';
@@ -83,9 +83,9 @@
     snprintf(s->bytestream, s->bytestream_end - s->bytestream,
              "P%c\n%d %d\n", c, avctx->width, h1);
     s->bytestream += strlen(s->bytestream);
-    if (avctx->pix_fmt != PIX_FMT_MONOWHITE) {
+    if (avctx->pix_fmt != AV_PIX_FMT_MONOWHITE) {
         snprintf(s->bytestream, s->bytestream_end - s->bytestream,
-                 "%d\n", (avctx->pix_fmt != PIX_FMT_GRAY16BE && avctx->pix_fmt != PIX_FMT_RGB48BE) ? 255 : 65535);
+                 "%d\n", (avctx->pix_fmt != AV_PIX_FMT_GRAY16BE && avctx->pix_fmt != AV_PIX_FMT_RGB48BE) ? 255 : 65535);
         s->bytestream += strlen(s->bytestream);
     }
 
@@ -97,7 +97,7 @@
         ptr           += linesize;
     }
 
-    if (avctx->pix_fmt == PIX_FMT_YUV420P) {
+    if (avctx->pix_fmt == AV_PIX_FMT_YUV420P) {
         h >>= 1;
         n >>= 1;
         ptr1 = p->data[1];
@@ -127,8 +127,8 @@
     .priv_data_size = sizeof(PNMContext),
     .init           = ff_pnm_init,
     .encode2        = pnm_encode_frame,
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_GRAY8, PIX_FMT_GRAY16BE, PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY16BE, AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("PGM (Portable GrayMap) image"),
 };
@@ -142,7 +142,7 @@
     .priv_data_size = sizeof(PNMContext),
     .init           = ff_pnm_init,
     .encode2        = pnm_encode_frame,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUV420P, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("PGMYUV (Portable GrayMap YUV) image"),
 };
 #endif
@@ -155,8 +155,8 @@
     .priv_data_size = sizeof(PNMContext),
     .init           = ff_pnm_init,
     .encode2        = pnm_encode_frame,
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_RGB24, PIX_FMT_RGB48BE, PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_RGB24, AV_PIX_FMT_RGB48BE, AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("PPM (Portable PixelMap) image"),
 };
@@ -170,8 +170,8 @@
     .priv_data_size = sizeof(PNMContext),
     .init           = ff_pnm_init,
     .encode2        = pnm_encode_frame,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_MONOWHITE,
-                                                  PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_MONOWHITE,
+                                                  AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("PBM (Portable BitMap) image"),
 };
 #endif
diff --git a/libavcodec/ppc/Makefile b/libavcodec/ppc/Makefile
index e5d1d39..f7548e3 100644
--- a/libavcodec/ppc/Makefile
+++ b/libavcodec/ppc/Makefile
@@ -7,6 +7,7 @@
                                           $(FFT-OBJS-yes)
 ALTIVEC-OBJS-$(CONFIG_H264DSP)         += ppc/h264_altivec.o
 ALTIVEC-OBJS-$(CONFIG_MPEGAUDIODSP)    += ppc/mpegaudiodec_altivec.o
+ALTIVEC-OBJS-$(CONFIG_MPEGVIDEO)       += ppc/mpegvideo_altivec.o
 ALTIVEC-OBJS-$(CONFIG_VC1_DECODER)     += ppc/vc1dsp_altivec.o
 ALTIVEC-OBJS-$(CONFIG_VP8_DECODER)     += ppc/vp8dsp_altivec.o
 
@@ -17,4 +18,3 @@
                                           ppc/gmc_altivec.o             \
                                           ppc/idct_altivec.o            \
                                           ppc/int_altivec.o             \
-                                          ppc/mpegvideo_altivec.o       \
diff --git a/libavcodec/ppc/fmtconvert_altivec.c b/libavcodec/ppc/fmtconvert_altivec.c
index 3cb1154..d40ce07 100644
--- a/libavcodec/ppc/fmtconvert_altivec.c
+++ b/libavcodec/ppc/fmtconvert_altivec.c
@@ -83,6 +83,31 @@
     }
 }
 
+#define VSTE_INC(dst, v, elem, inc) do {                \
+        vector signed short s = vec_splat(v, elem);     \
+        vec_ste(s, 0, dst);                             \
+        dst += inc;                                     \
+    } while (0)
+
+static void float_to_int16_stride_altivec(int16_t *dst, const float *src,
+                                          long len, int stride)
+{
+    int i;
+    vector signed short d, s;
+
+    for (i = 0; i < len - 7; i += 8) {
+        d = float_to_int16_one_altivec(src + i);
+        VSTE_INC(dst, d, 0, stride);
+        VSTE_INC(dst, d, 1, stride);
+        VSTE_INC(dst, d, 2, stride);
+        VSTE_INC(dst, d, 3, stride);
+        VSTE_INC(dst, d, 4, stride);
+        VSTE_INC(dst, d, 5, stride);
+        VSTE_INC(dst, d, 6, stride);
+        VSTE_INC(dst, d, 7, stride);
+    }
+}
+
 static void float_to_int16_interleave_altivec(int16_t *dst, const float **src,
                                               long len, int channels)
 {
@@ -124,13 +149,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];
-            }
+            for (i = 0; i < channels; i++)
+                float_to_int16_stride_altivec(dst + i, src[i], len, channels);
         }
     }
 }
diff --git a/libavcodec/ppc/h264_altivec.c b/libavcodec/ppc/h264_altivec.c
index 7c89b85..be54b48 100644
--- a/libavcodec/ppc/h264_altivec.c
+++ b/libavcodec/ppc/h264_altivec.c
@@ -19,6 +19,7 @@
  */
 
 #include "libavutil/cpu.h"
+#include "libavutil/intreadwrite.h"
 #include "libavutil/ppc/types_altivec.h"
 #include "libavutil/ppc/util_altivec.h"
 #include "libavcodec/dsputil.h"
@@ -788,7 +789,7 @@
     alphavec = vec_splat(alphavec, 0x0);                                                     \
     mask = h264_deblock_mask(p0, p1, q0, q1, alphavec, betavec); /*if in block */            \
                                                                                              \
-    *((int *)temp) = *((int *)tc0);                                                          \
+    AV_COPY32(temp, tc0);                                                                    \
     tc0vec = vec_ld(0, (signed char*)temp);                                                  \
     tc0vec = vec_mergeh(tc0vec, tc0vec);                                                     \
     tc0vec = vec_mergeh(tc0vec, tc0vec);                                                     \
diff --git a/libavcodec/ppc/h264_altivec_template.c b/libavcodec/ppc/h264_altivec_template.c
index 6121ea1..5a08e0e 100644
--- a/libavcodec/ppc/h264_altivec_template.c
+++ b/libavcodec/ppc/h264_altivec_template.c
@@ -322,7 +322,7 @@
               pp1A, pp1B, pp2A, pp2B, pp3A, pp3B,
               psumA, psumB, sumA, sumB;
 
-    vec_u8 sum, vdst, fsum;
+    vec_u8 sum, fsum;
 
     for (i = 0 ; i < 16 ; i ++) {
         vec_u8 srcR1 = vec_ld(-2, src);
@@ -423,9 +423,8 @@
         sum = vec_packsu(sumA, sumB);
 
         ASSERT_ALIGNED(dst);
-        vdst = vec_ld(0, dst);
 
-        OP_U8_ALTIVEC(fsum, sum, vdst);
+        OP_U8_ALTIVEC(fsum, sum, vec_ld(0, dst));
 
         vec_st(fsum, 0, dst);
 
@@ -486,7 +485,7 @@
               srcP3ssA, srcP3ssB,
               sum1A, sum1B, sum2A, sum2B, sum3A, sum3B;
 
-    vec_u8 sum, vdst, fsum, srcP3a, srcP3b, srcP3;
+    vec_u8 sum, fsum, srcP3a, srcP3b, srcP3;
 
     for (i = 0 ; i < 16 ; i++) {
         srcP3a = vec_ld(0, srcbis += srcStride);
@@ -532,9 +531,8 @@
         sum = vec_packsu(sumA, sumB);
 
         ASSERT_ALIGNED(dst);
-        vdst = vec_ld(0, dst);
 
-        OP_U8_ALTIVEC(fsum, sum, vdst);
+        OP_U8_ALTIVEC(fsum, sum, vec_ld(0, dst));
 
         vec_st(fsum, 0, dst);
 
@@ -582,7 +580,7 @@
               pp3Ae, pp3Ao, pp3Be, pp3Bo, pp1cAe, pp1cAo, pp1cBe, pp1cBo,
               pp32Ae, pp32Ao, pp32Be, pp32Bo, sumAe, sumAo, sumBe, sumBo,
               ssumAe, ssumAo, ssumBe, ssumBo;
-    vec_u8 fsum, sumv, sum, vdst;
+    vec_u8 fsum, sumv, sum;
     vec_s16 ssume, ssumo;
 
     src -= (2 * srcStride);
@@ -766,9 +764,8 @@
         sum = vec_perm(sumv, sumv, mperm);
 
         ASSERT_ALIGNED(dst);
-        vdst = vec_ld(0, dst);
 
-        OP_U8_ALTIVEC(fsum, sum, vdst);
+        OP_U8_ALTIVEC(fsum, sum, vec_ld(0, dst));
 
         vec_st(fsum, 0, dst);
 
diff --git a/libavcodec/proresdec2.c b/libavcodec/proresdec2.c
index cd487b2..e643c87 100644
--- a/libavcodec/proresdec2.c
+++ b/libavcodec/proresdec2.c
@@ -126,13 +126,17 @@
         ctx->frame.top_field_first = ctx->frame_type == 1;
     }
 
-    avctx->pix_fmt = (buf[12] & 0xC0) == 0xC0 ? PIX_FMT_YUV444P10 : PIX_FMT_YUV422P10;
+    avctx->pix_fmt = (buf[12] & 0xC0) == 0xC0 ? AV_PIX_FMT_YUV444P10 : AV_PIX_FMT_YUV422P10;
 
     ptr   = buf + 20;
     flags = buf[19];
     av_dlog(avctx, "flags %x\n", flags);
 
     if (flags & 2) {
+        if(buf + data_size - ptr < 64) {
+            av_log(avctx, AV_LOG_ERROR, "Header truncated\n");
+            return -1;
+        }
         permute(ctx->qmat_luma, ctx->prodsp.idct_permutation, ptr);
         ptr += 64;
     } else {
@@ -140,6 +144,10 @@
     }
 
     if (flags & 1) {
+        if(buf + data_size - ptr < 64) {
+            av_log(avctx, AV_LOG_ERROR, "Header truncated\n");
+            return -1;
+        }
         permute(ctx->qmat_chroma, ctx->prodsp.idct_permutation, ptr);
     } else {
         memset(ctx->qmat_chroma, 4, 64);
@@ -465,7 +473,7 @@
         chroma_stride = pic->linesize[1] << 1;
     }
 
-    if (avctx->pix_fmt == PIX_FMT_YUV444P10) {
+    if (avctx->pix_fmt == AV_PIX_FMT_YUV444P10) {
         mb_x_shift = 5;
         log2_chroma_blocks_per_mb = 2;
     } else {
diff --git a/libavcodec/proresdec_lgpl.c b/libavcodec/proresdec_lgpl.c
index e672ad2..d338649 100644
--- a/libavcodec/proresdec_lgpl.c
+++ b/libavcodec/proresdec_lgpl.c
@@ -139,10 +139,10 @@
     ctx->num_chroma_blocks = (1 << ctx->chroma_factor) >> 1;
     switch (ctx->chroma_factor) {
     case 2:
-        avctx->pix_fmt = PIX_FMT_YUV422P10;
+        avctx->pix_fmt = AV_PIX_FMT_YUV422P10;
         break;
     case 3:
-        avctx->pix_fmt = PIX_FMT_YUV444P10;
+        avctx->pix_fmt = AV_PIX_FMT_YUV444P10;
         break;
     default:
         av_log(avctx, AV_LOG_ERROR,
@@ -171,7 +171,7 @@
 
     ctx->alpha_info = buf[17] & 0xf;
     if (ctx->alpha_info)
-        av_log_missing_feature(avctx, "alpha channel", 0);
+        av_log_missing_feature(avctx, "Alpha channel", 0);
 
     ctx->qmat_changed = 0;
     ptr   = buf + 20;
diff --git a/libavcodec/proresdsp.c b/libavcodec/proresdsp.c
index 867e403..9e063b0 100644
--- a/libavcodec/proresdsp.c
+++ b/libavcodec/proresdsp.c
@@ -75,7 +75,7 @@
     dsp->idct_put = prores_idct_put_c;
     dsp->idct_permutation_type = FF_NO_IDCT_PERM;
 
-    if (HAVE_MMX) ff_proresdsp_x86_init(dsp, avctx);
+    if (ARCH_X86) ff_proresdsp_x86_init(dsp, avctx);
 
     ff_init_scantable_permutation(dsp->idct_permutation,
                                   dsp->idct_permutation_type);
diff --git a/libavcodec/proresdsp.h b/libavcodec/proresdsp.h
index a35e0d6..09541d9 100644
--- a/libavcodec/proresdsp.h
+++ b/libavcodec/proresdsp.h
@@ -27,7 +27,7 @@
 
 #define PRORES_BITS_PER_SAMPLE 10 ///< output precision of prores decoder
 
-typedef struct {
+typedef struct ProresDSPContext {
     int idct_permutation_type;
     uint8_t idct_permutation[64];
     int dct_permutation_type;
diff --git a/libavcodec/proresenc_anatoliy.c b/libavcodec/proresenc_anatoliy.c
index d77d6ee..8c71ca5 100644
--- a/libavcodec/proresenc_anatoliy.c
+++ b/libavcodec/proresenc_anatoliy.c
@@ -540,7 +540,7 @@
     int i;
     ProresContext* ctx = avctx->priv_data;
 
-    if (avctx->pix_fmt != PIX_FMT_YUV422P10) {
+    if (avctx->pix_fmt != AV_PIX_FMT_YUV422P10) {
         av_log(avctx, AV_LOG_ERROR, "need YUV422P10\n");
         return -1;
     }
@@ -604,7 +604,7 @@
     .init           = prores_encode_init,
     .close          = prores_encode_close,
     .encode2        = prores_encode_frame,
-    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUV422P10, PIX_FMT_NONE},
+    .pix_fmts       = (const enum AVPixelFormat[]){AV_PIX_FMT_YUV422P10, AV_PIX_FMT_NONE},
     .long_name      = NULL_IF_CONFIG_SMALL("Apple ProRes"),
     .capabilities   = CODEC_CAP_FRAME_THREADS | CODEC_CAP_INTRA_ONLY,
     .profiles       = profiles
@@ -618,7 +618,7 @@
     .init           = prores_encode_init,
     .close          = prores_encode_close,
     .encode2        = prores_encode_frame,
-    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUV422P10, PIX_FMT_NONE},
+    .pix_fmts       = (const enum AVPixelFormat[]){AV_PIX_FMT_YUV422P10, AV_PIX_FMT_NONE},
     .long_name      = NULL_IF_CONFIG_SMALL("Apple ProRes"),
     .capabilities   = CODEC_CAP_FRAME_THREADS | CODEC_CAP_INTRA_ONLY,
     .profiles       = profiles
diff --git a/libavcodec/proresenc_kostya.c b/libavcodec/proresenc_kostya.c
index 53c74a4..0462c74 100644
--- a/libavcodec/proresenc_kostya.c
+++ b/libavcodec/proresenc_kostya.c
@@ -36,7 +36,7 @@
 
 #define MAX_MBS_PER_SLICE 8
 
-#define MAX_PLANES 3 // should be increased to 4 when there's PIX_FMT_YUV444AP10
+#define MAX_PLANES 3 // should be increased to 4 when there's AV_PIX_FMT_YUV444AP10
 
 enum {
     PRORES_PROFILE_PROXY = 0,
@@ -902,7 +902,7 @@
         return AVERROR(EINVAL);
     }
 
-    ctx->chroma_factor = avctx->pix_fmt == PIX_FMT_YUV422P10
+    ctx->chroma_factor = avctx->pix_fmt == AV_PIX_FMT_YUV422P10
                          ? CFACTOR_Y422
                          : CFACTOR_Y444;
     ctx->profile_info  = prores_profile_info + ctx->profile;
@@ -1069,8 +1069,8 @@
     .encode2        = encode_frame,
     .capabilities   = CODEC_CAP_SLICE_THREADS,
     .long_name      = NULL_IF_CONFIG_SMALL("Apple ProRes (iCodec Pro)"),
-    .pix_fmts       = (const enum PixelFormat[]) {
-                          PIX_FMT_YUV422P10, PIX_FMT_YUV444P10, PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]) {
+                          AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV444P10, AV_PIX_FMT_NONE
                       },
     .priv_class     = &proresenc_class,
 };
diff --git a/libavcodec/pthread.c b/libavcodec/pthread.c
index c0a872e..9a52924 100644
--- a/libavcodec/pthread.c
+++ b/libavcodec/pthread.c
@@ -85,7 +85,7 @@
 } ThreadContext;
 
 /// Max number of frame buffers that can be allocated when using frame threads.
-#define MAX_BUFFERS (32+1)
+#define MAX_BUFFERS (34+1)
 
 /**
  * Context used by codec threads and stored in their AVCodecContext thread_opaque.
diff --git a/libavcodec/ptx.c b/libavcodec/ptx.c
index 0d6762f..c9adb6d 100644
--- a/libavcodec/ptx.c
+++ b/libavcodec/ptx.c
@@ -59,7 +59,7 @@
         return -1;
     }
 
-    avctx->pix_fmt = PIX_FMT_BGR555LE;
+    avctx->pix_fmt = AV_PIX_FMT_BGR555LE;
 
     if (buf_end - buf < offset)
         return AVERROR_INVALIDDATA;
diff --git a/libavcodec/qcelpdata.h b/libavcodec/qcelpdata.h
index 4a7dcdb..d58e9f8 100644
--- a/libavcodec/qcelpdata.h
+++ b/libavcodec/qcelpdata.h
@@ -37,7 +37,7 @@
 /**
  * QCELP unpacked data frame
  */
-typedef struct {
+typedef struct QCELPFrame {
 /// @name QCELP excitation codebook parameters
 /// @{
     uint8_t cbsign[16]; ///< sign of the codebook gain for each codebook subframe
@@ -73,7 +73,7 @@
  */
 static const float qcelp_hammsinc_table[4] = { -0.006822,  0.041249, -0.143459,  0.588863};
 
-typedef struct {
+typedef struct QCELPBitmap {
     uint8_t index;  /**< index into the QCELPContext structure */
     uint8_t bitpos; /**< position of the lowest bit in the value's byte */
     uint8_t bitlen; /**< number of bits to read */
diff --git a/libavcodec/qcelpdec.c b/libavcodec/qcelpdec.c
index 7f27081..e406049 100644
--- a/libavcodec/qcelpdec.c
+++ b/libavcodec/qcelpdec.c
@@ -29,6 +29,7 @@
 
 #include <stddef.h>
 
+#include "libavutil/channel_layout.h"
 #include "avcodec.h"
 #include "internal.h"
 #include "get_bits.h"
@@ -89,7 +90,9 @@
     QCELPContext *q = avctx->priv_data;
     int i;
 
-    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
+    avctx->channels       = 1;
+    avctx->channel_layout = AV_CH_LAYOUT_MONO;
+    avctx->sample_fmt     = AV_SAMPLE_FMT_FLT;
 
     for (i = 0; i < 10; i++)
         q->prev_lspf[i] = (i + 1) / 11.;
diff --git a/libavcodec/qdm2.c b/libavcodec/qdm2.c
index 3a77e7f..1dfb8d5 100644
--- a/libavcodec/qdm2.c
+++ b/libavcodec/qdm2.c
@@ -36,6 +36,7 @@
 #include <stdio.h>
 
 #define BITSTREAM_READER_LE
+#include "libavutil/channel_layout.h"
 #include "avcodec.h"
 #include "get_bits.h"
 #include "dsputil.h"
@@ -346,7 +347,7 @@
         int tmp;
 
         if (value >= 60) {
-            av_log(0, AV_LOG_ERROR, "value %d in qdm2_get_vlc too large\n", value);
+            av_log(NULL, AV_LOG_ERROR, "value %d in qdm2_get_vlc too large\n", value);
             return 0;
         }
 
@@ -550,10 +551,6 @@
     int i, sb, ch, sb_used;
     int tmp, tab;
 
-    // This should never happen
-    if (q->nb_channels <= 0)
-        return;
-
     for (ch = 0; ch < q->nb_channels; ch++)
         for (sb = 0; sb < 30; sb++)
             for (i = 0; i < 8; i++) {
@@ -649,10 +646,6 @@
     int add1, add2, add3, add4;
     int64_t multres;
 
-    // This should never happen
-    if (nb_channels <= 0)
-        return;
-
     if (!superblocktype_2_3) {
         /* This case is untested, no samples available */
         SAMPLES_NEEDED
@@ -802,6 +795,11 @@
                 for (j = 0; j < 16; j++)
                     sign_bits[j] = get_bits1 (gb);
 
+            if (q->coding_method[0][sb][0] <= 0) {
+                av_log(NULL, AV_LOG_ERROR, "coding method invalid\n");
+                return AVERROR_INVALIDDATA;
+            }
+
             for (j = 0; j < 64; j++)
                 if (q->coding_method[1][sb][j] > q->coding_method[0][sb][j])
                     q->coding_method[0][sb][j] = q->coding_method[1][sb][j];
@@ -1167,7 +1165,7 @@
     synthfilt_build_sb_samples(q, &gb, length, 8, QDM2_SB_USED(q->sub_sampling));
 }
 
-/*
+/**
  * Process new subpackets for synthesis filter
  *
  * @param q       context
@@ -1201,7 +1199,7 @@
 }
 
 
-/*
+/**
  * Decode superblock, fill packet lists.
  *
  * @param q    context
@@ -1259,6 +1257,11 @@
     for (i = 0; packet_bytes > 0; i++) {
         int j;
 
+        if (i>=FF_ARRAY_ELEMS(q->sub_packet_list_A)) {
+            SAMPLES_NEEDED_2("too many packet bytes");
+            return;
+        }
+
         q->sub_packet_list_A[i].next = NULL;
 
         if (i > 0) {
@@ -1362,7 +1365,7 @@
             while ((n = qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2)) < 2) {
                 if (get_bits_left(gb)<0) {
                     if(local_int_4 < q->group_size)
-                        av_log(0, AV_LOG_ERROR, "overread in qdm2_fft_decode_tones()\n");
+                        av_log(NULL, AV_LOG_ERROR, "overread in qdm2_fft_decode_tones()\n");
                     return;
                 }
                 offset = 1;
@@ -1792,10 +1795,12 @@
 
     avctx->channels = s->nb_channels = s->channels = AV_RB32(extradata);
     extradata += 4;
-    if (s->channels > MPA_MAX_CHANNELS) {
-        av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
+    if (s->channels <= 0 || s->channels > MPA_MAX_CHANNELS) {
+        av_log(avctx, AV_LOG_ERROR, "Invalid number of channels\n");
         return AVERROR_INVALIDDATA;
     }
+    avctx->channel_layout = avctx->channels == 2 ? AV_CH_LAYOUT_STEREO :
+                                                   AV_CH_LAYOUT_MONO;
 
     avctx->sample_rate = AV_RB32(extradata);
     extradata += 4;
diff --git a/libavcodec/qdrw.c b/libavcodec/qdrw.c
index 6c61b50..ab4c6c1 100644
--- a/libavcodec/qdrw.c
+++ b/libavcodec/qdrw.c
@@ -91,7 +91,7 @@
         buf++;
         b = *buf++;
         buf++;
-        pal[idx] = 0xFF << 24 | r << 16 | g << 8 | b;
+        pal[idx] = 0xFFU << 24 | r << 16 | g << 8 | b;
     }
     p->palette_has_changed = 1;
 
@@ -149,7 +149,7 @@
     QdrawContext * const a = avctx->priv_data;
 
     avcodec_get_frame_defaults(&a->pic);
-    avctx->pix_fmt= PIX_FMT_PAL8;
+    avctx->pix_fmt= AV_PIX_FMT_PAL8;
 
     return 0;
 }
diff --git a/libavcodec/qpeg.c b/libavcodec/qpeg.c
index 751d6ce..0a7c788 100644
--- a/libavcodec/qpeg.c
+++ b/libavcodec/qpeg.c
@@ -301,13 +301,27 @@
     return avpkt->size;
 }
 
+static void decode_flush(AVCodecContext *avctx){
+    QpegContext * const a = avctx->priv_data;
+    int i, pal_size;
+    const uint8_t *pal_src;
+
+    pal_size = FFMIN(1024U, avctx->extradata_size);
+    pal_src = avctx->extradata + avctx->extradata_size - pal_size;
+
+    for (i=0; i<pal_size/4; i++)
+        a->pal[i] = 0xFFU<<24 | AV_RL32(pal_src+4*i);
+}
+
 static av_cold int decode_init(AVCodecContext *avctx){
     QpegContext * const a = avctx->priv_data;
 
     avcodec_get_frame_defaults(&a->pic);
     avcodec_get_frame_defaults(&a->ref);
     a->avctx = avctx;
-    avctx->pix_fmt= PIX_FMT_PAL8;
+    avctx->pix_fmt= AV_PIX_FMT_PAL8;
+
+    decode_flush(avctx);
 
     return 0;
 }
@@ -333,6 +347,7 @@
     .init           = decode_init,
     .close          = decode_end,
     .decode         = decode_frame,
+    .flush          = decode_flush,
     .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("Q-team QPEG"),
 };
diff --git a/libavcodec/qtrle.c b/libavcodec/qtrle.c
index a8fe38a..d02dffa 100644
--- a/libavcodec/qtrle.c
+++ b/libavcodec/qtrle.c
@@ -363,7 +363,7 @@
     switch (avctx->bits_per_coded_sample) {
     case 1:
     case 33:
-        avctx->pix_fmt = PIX_FMT_MONOWHITE;
+        avctx->pix_fmt = AV_PIX_FMT_MONOWHITE;
         break;
 
     case 2:
@@ -372,19 +372,19 @@
     case 34:
     case 36:
     case 40:
-        avctx->pix_fmt = PIX_FMT_PAL8;
+        avctx->pix_fmt = AV_PIX_FMT_PAL8;
         break;
 
     case 16:
-        avctx->pix_fmt = PIX_FMT_RGB555;
+        avctx->pix_fmt = AV_PIX_FMT_RGB555;
         break;
 
     case 24:
-        avctx->pix_fmt = PIX_FMT_RGB24;
+        avctx->pix_fmt = AV_PIX_FMT_RGB24;
         break;
 
     case 32:
-        avctx->pix_fmt = PIX_FMT_RGB32;
+        avctx->pix_fmt = AV_PIX_FMT_RGB32;
         break;
 
     default:
diff --git a/libavcodec/qtrleenc.c b/libavcodec/qtrleenc.c
index 2fb9c1c..e151c9e 100644
--- a/libavcodec/qtrleenc.c
+++ b/libavcodec/qtrleenc.c
@@ -73,24 +73,24 @@
     s->logical_width=avctx->width;
 
     switch (avctx->pix_fmt) {
-    case PIX_FMT_GRAY8:
+    case AV_PIX_FMT_GRAY8:
         s->logical_width = avctx->width / 4;
         s->pixel_size = 4;
         break;
-    case PIX_FMT_RGB555BE:
+    case AV_PIX_FMT_RGB555BE:
         s->pixel_size = 2;
         break;
-    case PIX_FMT_RGB24:
+    case AV_PIX_FMT_RGB24:
         s->pixel_size = 3;
         break;
-    case PIX_FMT_ARGB:
+    case AV_PIX_FMT_ARGB:
         s->pixel_size = 4;
         break;
     default:
         av_log(avctx, AV_LOG_ERROR, "Unsupported colorspace.\n");
         break;
     }
-    avctx->bits_per_coded_sample = avctx->pix_fmt == PIX_FMT_GRAY8 ? 40 : s->pixel_size*8;
+    avctx->bits_per_coded_sample = avctx->pix_fmt == AV_PIX_FMT_GRAY8 ? 40 : s->pixel_size*8;
 
     s->rlecode_table = av_mallocz(s->logical_width);
     s->skip_table    = av_mallocz(s->logical_width);
@@ -232,11 +232,11 @@
         }
         else if (rlecode > 0) {
             /* bulk copy */
-            if (s->avctx->pix_fmt == PIX_FMT_GRAY8) {
+            if (s->avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
                 int j;
                 // QT grayscale colorspace has 0=white and 255=black, we will
                 // ignore the palette that is included in the AVFrame because
-                // PIX_FMT_GRAY8 has defined color mapping
+                // AV_PIX_FMT_GRAY8 has defined color mapping
                 for (j = 0; j < rlecode*s->pixel_size; ++j)
                     bytestream_put_byte(buf, *(this_line + i*s->pixel_size + j) ^ 0xff);
             } else {
@@ -246,7 +246,7 @@
         }
         else {
             /* repeat the bits */
-            if (s->avctx->pix_fmt == PIX_FMT_GRAY8) {
+            if (s->avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
                 int j;
                 // QT grayscale colorspace has 0=white and 255=black, ...
                 for (j = 0; j < s->pixel_size; ++j)
@@ -355,8 +355,8 @@
     .init           = qtrle_encode_init,
     .encode2        = qtrle_encode_frame,
     .close          = qtrle_encode_end,
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_RGB24, PIX_FMT_RGB555BE, PIX_FMT_ARGB, PIX_FMT_GRAY8, PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_RGB24, AV_PIX_FMT_RGB555BE, AV_PIX_FMT_ARGB, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("QuickTime Animation (RLE) video"),
 };
diff --git a/libavcodec/r210dec.c b/libavcodec/r210dec.c
index f8db4a9..4c78b53 100644
--- a/libavcodec/r210dec.c
+++ b/libavcodec/r210dec.c
@@ -26,7 +26,7 @@
 
 static av_cold int decode_init(AVCodecContext *avctx)
 {
-    avctx->pix_fmt             = PIX_FMT_RGB48;
+    avctx->pix_fmt             = AV_PIX_FMT_RGB48;
     avctx->bits_per_raw_sample = 10;
 
     avctx->coded_frame         = avcodec_alloc_frame();
diff --git a/libavcodec/r210enc.c b/libavcodec/r210enc.c
index 9e209fd..39069ab 100644
--- a/libavcodec/r210enc.c
+++ b/libavcodec/r210enc.c
@@ -94,7 +94,7 @@
     .init           = encode_init,
     .encode2        = encode_frame,
     .close          = encode_close,
-    .pix_fmts       = (const enum PixelFormat[]) { PIX_FMT_RGB48, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_RGB48, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("Uncompressed RGB 10-bit"),
 };
 #endif
@@ -106,7 +106,7 @@
     .init           = encode_init,
     .encode2        = encode_frame,
     .close          = encode_close,
-    .pix_fmts       = (const enum PixelFormat[]) { PIX_FMT_RGB48, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_RGB48, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("AJA Kona 10-bit RGB Codec"),
 };
 #endif
@@ -118,7 +118,7 @@
     .init           = encode_init,
     .encode2        = encode_frame,
     .close          = encode_close,
-    .pix_fmts       = (const enum PixelFormat[]) { PIX_FMT_RGB48, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_RGB48, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("Avid 1:1 10-bit RGB Packer"),
 };
 #endif
diff --git a/libavcodec/ra144.c b/libavcodec/ra144.c
index aa68378..1ec1e10 100644
--- a/libavcodec/ra144.c
+++ b/libavcodec/ra144.c
@@ -22,8 +22,8 @@
 #include <stdint.h>
 #include "avcodec.h"
 #include "celp_filters.h"
+#include "mathops.h"
 #include "ra144.h"
-#include "libavutil/common.h"
 
 const int16_t ff_gain_val_tab[256][3] = {
     { 541, 956,  768}, { 877, 581,  568}, { 675,1574,  635}, {1248,1464,  668},
@@ -1567,8 +1567,14 @@
             b = -2;
 
         b = 0x1000000 / b;
-        for (j=0; j <= i; j++)
+        for (j=0; j <= i; j++) {
+#if CONFIG_FTRAPV
+            int a = bp2[j] - ((refl[i+1] * bp2[i-j]) >> 12);
+            if((int)(a*(unsigned)b) != a*(int64_t)b)
+                return 1;
+#endif
             bp1[j] = ((bp2[j] - ((refl[i+1] * bp2[i-j]) >> 12)) * b) >> 12;
+        }
 
         if ((unsigned) bp1[i] + 0x1000 > 0x1fff)
             return 1;
diff --git a/libavcodec/ra144.h b/libavcodec/ra144.h
index 03c4860..331dc35 100644
--- a/libavcodec/ra144.h
+++ b/libavcodec/ra144.h
@@ -33,7 +33,7 @@
 #define FRAMESIZE       20      ///< size of encoded frame
 #define LPC_ORDER       10      ///< order of LPC filter
 
-typedef struct {
+typedef struct RA144Context {
     AVCodecContext *avctx;
     AVFrame frame;
     LPCContext lpc_ctx;
diff --git a/libavcodec/ra144dec.c b/libavcodec/ra144dec.c
index 9d44776..ad9e008 100644
--- a/libavcodec/ra144dec.c
+++ b/libavcodec/ra144dec.c
@@ -22,6 +22,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intmath.h"
 #include "avcodec.h"
 #include "get_bits.h"
@@ -37,7 +38,9 @@
     ractx->lpc_coef[0] = ractx->lpc_tables[0];
     ractx->lpc_coef[1] = ractx->lpc_tables[1];
 
-    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    avctx->channels       = 1;
+    avctx->channel_layout = AV_CH_LAYOUT_MONO;
+    avctx->sample_fmt     = AV_SAMPLE_FMT_S16;
 
     avcodec_get_frame_defaults(&ractx->frame);
     avctx->coded_frame = &ractx->frame;
diff --git a/libavcodec/ra144enc.c b/libavcodec/ra144enc.c
index e0fb827..9a8ac2b 100644
--- a/libavcodec/ra144enc.c
+++ b/libavcodec/ra144enc.c
@@ -564,5 +564,6 @@
     .capabilities   = CODEC_CAP_DELAY | CODEC_CAP_SMALL_LAST_FRAME,
     .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
                                                      AV_SAMPLE_FMT_NONE },
+    .supported_samplerates = (const int[]){ 8000, 0 },
     .long_name      = NULL_IF_CONFIG_SMALL("RealAudio 1.0 (14.4K)"),
 };
diff --git a/libavcodec/ra288.c b/libavcodec/ra288.c
index a8e9eab..cefc99c 100644
--- a/libavcodec/ra288.c
+++ b/libavcodec/ra288.c
@@ -19,6 +19,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/float_dsp.h"
 #include "avcodec.h"
 #define BITSTREAM_READER_LE
@@ -61,7 +62,16 @@
 static av_cold int ra288_decode_init(AVCodecContext *avctx)
 {
     RA288Context *ractx = avctx->priv_data;
-    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
+
+    avctx->channels       = 1;
+    avctx->channel_layout = AV_CH_LAYOUT_MONO;
+    avctx->sample_fmt     = AV_SAMPLE_FMT_FLT;
+
+    if (avctx->block_align <= 0) {
+        av_log_ask_for_sample(avctx, "unsupported block align\n");
+        return AVERROR_PATCHWELCOME;
+    }
+
     avpriv_float_dsp_init(&ractx->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
 
     avcodec_get_frame_defaults(&ractx->frame);
@@ -137,6 +147,8 @@
                                             MAX_BACKWARD_FILTER_LEN   +
                                             MAX_BACKWARD_FILTER_NONREC, 16)]);
 
+    av_assert2(order>=0);
+
     ractx->fdsp.vector_fmul(work, window, hist, FFALIGN(order + n + non_rec, 16));
 
     convolve(buffer1, work + order    , n      , order);
diff --git a/libavcodec/ralf.c b/libavcodec/ralf.c
index 6866f79..c9c8080 100644
--- a/libavcodec/ralf.c
+++ b/libavcodec/ralf.c
@@ -26,11 +26,11 @@
  * Dedicated to the mastermind behind it, Ralph Wiggum.
  */
 
+#include "libavutil/channel_layout.h"
 #include "avcodec.h"
 #include "get_bits.h"
 #include "golomb.h"
 #include "unary.h"
-#include "libavutil/audioconvert.h"
 #include "ralfdata.h"
 
 #define FILTER_NONE 0
@@ -149,7 +149,7 @@
                avctx->sample_rate, avctx->channels);
         return AVERROR_INVALIDDATA;
     }
-    avctx->sample_fmt     = AV_SAMPLE_FMT_S16;
+    avctx->sample_fmt     = AV_SAMPLE_FMT_S16P;
     avctx->channel_layout = (avctx->channels == 2) ? AV_CH_LAYOUT_STEREO
                                                    : AV_CH_LAYOUT_MONO;
 
@@ -338,7 +338,8 @@
     }
 }
 
-static int decode_block(AVCodecContext *avctx, GetBitContext *gb, int16_t *dst)
+static int decode_block(AVCodecContext *avctx, GetBitContext *gb,
+                        int16_t *dst0, int16_t *dst1)
 {
     RALFContext *ctx = avctx->priv_data;
     int len, ch, ret;
@@ -382,35 +383,35 @@
     switch (dmode) {
     case 0:
         for (i = 0; i < len; i++)
-            *dst++ = ch0[i] + ctx->bias[0];
+            dst0[i] = ch0[i] + ctx->bias[0];
         break;
     case 1:
         for (i = 0; i < len; i++) {
-            *dst++ = ch0[i] + ctx->bias[0];
-            *dst++ = ch1[i] + ctx->bias[1];
+            dst0[i] = ch0[i] + ctx->bias[0];
+            dst1[i] = ch1[i] + ctx->bias[1];
         }
         break;
     case 2:
         for (i = 0; i < len; i++) {
             ch0[i] += ctx->bias[0];
-            *dst++ = ch0[i];
-            *dst++ = ch0[i] - (ch1[i] + ctx->bias[1]);
+            dst0[i] = ch0[i];
+            dst1[i] = ch0[i] - (ch1[i] + ctx->bias[1]);
         }
         break;
     case 3:
         for (i = 0; i < len; i++) {
             t  = ch0[i] + ctx->bias[0];
             t2 = ch1[i] + ctx->bias[1];
-            *dst++ = t + t2;
-            *dst++ = t;
+            dst0[i] = t + t2;
+            dst1[i] = t;
         }
         break;
     case 4:
         for (i = 0; i < len; i++) {
             t  =   ch1[i] + ctx->bias[1];
             t2 = ((ch0[i] + ctx->bias[0]) << 1) | (t & 1);
-            *dst++ = (t2 + t) / 2;
-            *dst++ = (t2 - t) / 2;
+            dst0[i] = (t2 + t) / 2;
+            dst1[i] = (t2 - t) / 2;
         }
         break;
     }
@@ -424,7 +425,8 @@
                         AVPacket *avpkt)
 {
     RALFContext *ctx = avctx->priv_data;
-    int16_t *samples;
+    int16_t *samples0;
+    int16_t *samples1;
     int ret;
     GetBitContext gb;
     int table_size, table_bytes, i;
@@ -465,7 +467,8 @@
         av_log(avctx, AV_LOG_ERROR, "Me fail get_buffer()? That's unpossible!\n");
         return ret;
     }
-    samples = (int16_t*)ctx->frame.data[0];
+    samples0 = (int16_t *)ctx->frame.data[0];
+    samples1 = (int16_t *)ctx->frame.data[1];
 
     if (src_size < 5) {
         av_log(avctx, AV_LOG_ERROR, "too short packets are too short!\n");
@@ -498,8 +501,8 @@
             break;
         }
         init_get_bits(&gb, block_pointer, ctx->block_size[i] * 8);
-        if (decode_block(avctx, &gb, samples + ctx->sample_offset
-                                               * avctx->channels) < 0) {
+        if (decode_block(avctx, &gb, samples0 + ctx->sample_offset,
+                                     samples1 + ctx->sample_offset) < 0) {
             av_log(avctx, AV_LOG_ERROR, "Sir, I got carsick in your office. Not decoding the rest of packet.\n");
             break;
         }
@@ -533,4 +536,6 @@
     .flush          = decode_flush,
     .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("RealAudio Lossless"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
+                                                      AV_SAMPLE_FMT_NONE },
 };
diff --git a/libavcodec/rangecoder.c b/libavcodec/rangecoder.c
index 8367a79..7d2d14d 100644
--- a/libavcodec/rangecoder.c
+++ b/libavcodec/rangecoder.c
@@ -38,70 +38,72 @@
 #include "rangecoder.h"
 #include "bytestream.h"
 
-
-void ff_init_range_encoder(RangeCoder *c, uint8_t *buf, int buf_size){
-    c->bytestream_start=
-    c->bytestream= buf;
-    c->bytestream_end= buf + buf_size;
-
-    c->low= 0;
-    c->range= 0xFF00;
-    c->outstanding_count= 0;
-    c->outstanding_byte= -1;
+void ff_init_range_encoder(RangeCoder *c, uint8_t *buf, int buf_size)
+{
+    c->bytestream_start  =
+    c->bytestream        = buf;
+    c->bytestream_end    = buf + buf_size;
+    c->low               = 0;
+    c->range             = 0xFF00;
+    c->outstanding_count = 0;
+    c->outstanding_byte  = -1;
 }
 
-void ff_init_range_decoder(RangeCoder *c, const uint8_t *buf, int buf_size){
+void ff_init_range_decoder(RangeCoder *c, const uint8_t *buf, int buf_size)
+{
     /* cast to avoid compiler warning */
-    ff_init_range_encoder(c, (uint8_t *) buf, buf_size);
+    ff_init_range_encoder(c, (uint8_t *)buf, buf_size);
 
-    c->low = bytestream_get_be16(&c->bytestream);
+    c->low = bytestream_get_be16((const uint8_t **)&c->bytestream);
 }
 
-void ff_build_rac_states(RangeCoder *c, int factor, int max_p){
-    const int64_t one= 1LL<<32;
+void ff_build_rac_states(RangeCoder *c, int factor, int max_p)
+{
+    const int64_t one = 1LL << 32;
     int64_t p;
     int last_p8, p8, i;
 
     memset(c->zero_state, 0, sizeof(c->zero_state));
-    memset(c-> one_state, 0, sizeof(c-> one_state));
+    memset(c->one_state, 0, sizeof(c->one_state));
 
-    last_p8= 0;
-    p= one/2;
-    for(i=0; i<128; i++){
-        p8= (256*p + one/2) >> 32; //FIXME try without the one
-        if(p8 <= last_p8) p8= last_p8+1;
-        if(last_p8 && last_p8<256 && p8<=max_p)
-            c->one_state[last_p8]= p8;
+    last_p8 = 0;
+    p       = one / 2;
+    for (i = 0; i < 128; i++) {
+        p8 = (256 * p + one / 2) >> 32; // FIXME: try without the one
+        if (p8 <= last_p8)
+            p8 = last_p8 + 1;
+        if (last_p8 && last_p8 < 256 && p8 <= max_p)
+            c->one_state[last_p8] = p8;
 
-        p+= ((one-p)*factor + one/2) >> 32;
-        last_p8= p8;
+        p      += ((one - p) * factor + one / 2) >> 32;
+        last_p8 = p8;
     }
 
-    for(i=256-max_p; i<=max_p; i++){
-        if(c->one_state[i])
+    for (i = 256 - max_p; i <= max_p; i++) {
+        if (c->one_state[i])
             continue;
 
-        p= (i*one + 128) >> 8;
-        p+= ((one-p)*factor + one/2) >> 32;
-        p8= (256*p + one/2) >> 32; //FIXME try without the one
-        if(p8 <= i) p8= i+1;
-        if(p8 > max_p) p8= max_p;
-        c->one_state[    i]=     p8;
+        p  = (i * one + 128) >> 8;
+        p += ((one - p) * factor + one / 2) >> 32;
+        p8 = (256 * p + one / 2) >> 32; // FIXME: try without the one
+        if (p8 <= i)
+            p8 = i + 1;
+        if (p8 > max_p)
+            p8 = max_p;
+        c->one_state[i] = p8;
     }
 
-    for(i=1; i<255; i++)
-        c->zero_state[i]= 256-c->one_state[256-i];
+    for (i = 1; i < 255; i++)
+        c->zero_state[i] = 256 - c->one_state[256 - i];
 }
 
-/**
- *
- * @return the number of bytes written
- */
-int ff_rac_terminate(RangeCoder *c){
-    c->range=0xFF;
-    c->low +=0xFF;
+/* Return the number of bytes written. */
+int ff_rac_terminate(RangeCoder *c)
+{
+    c->range = 0xFF;
+    c->low  += 0xFF;
     renorm_encoder(c);
-    c->range=0xFF;
+    c->range = 0xFF;
     renorm_encoder(c);
 
     av_assert1(c->low   == 0);
@@ -114,11 +116,13 @@
 #define SIZE 10240
 
 #include "libavutil/lfg.h"
+#include "libavutil/log.h"
 
-int main(void){
+int main(void)
+{
     RangeCoder c;
-    uint8_t b[9*SIZE];
-    uint8_t r[9*SIZE];
+    uint8_t b[9 * SIZE];
+    uint8_t r[9 * SIZE];
     int i;
     uint8_t state[10];
     AVLFG prng;
@@ -126,19 +130,15 @@
     av_lfg_init(&prng, 1);
 
     ff_init_range_encoder(&c, b, SIZE);
-    ff_build_rac_states(&c, 0.05*(1LL<<32), 128+64+32+16);
+    ff_build_rac_states(&c, 0.05 * (1LL << 32), 128 + 64 + 32 + 16);
 
     memset(state, 128, sizeof(state));
 
-    for(i=0; i<SIZE; i++){
+    for (i = 0; i < SIZE; i++)
         r[i] = av_lfg_get(&prng) % 7;
-    }
 
-    for(i=0; i<SIZE; i++){
-START_TIMER
-        put_rac(&c, state, r[i]&1);
-STOP_TIMER("put_rac")
-    }
+    for (i = 0; i < SIZE; i++)
+        put_rac(&c, state, r[i] & 1);
 
     ff_rac_terminate(&c);
 
@@ -146,12 +146,11 @@
 
     memset(state, 128, sizeof(state));
 
-    for(i=0; i<SIZE; i++){
-START_TIMER
-        if( (r[i]&1) != get_rac(&c, state) )
+    for (i = 0; i < SIZE; i++)
+        if ((r[i] & 1) != get_rac(&c, state)) {
             av_log(NULL, AV_LOG_ERROR, "rac failure at %d\n", i);
-STOP_TIMER("get_rac")
-    }
+            return 1;
+        }
 
     return 0;
 }
diff --git a/libavcodec/rangecoder.h b/libavcodec/rangecoder.h
index f0c86d0..88e555f 100644
--- a/libavcodec/rangecoder.h
+++ b/libavcodec/rangecoder.h
@@ -28,113 +28,119 @@
 #define AVCODEC_RANGECODER_H
 
 #include <stdint.h>
+
 #include "libavutil/common.h"
 #include "libavutil/avassert.h"
 
-typedef struct RangeCoder{
+typedef struct RangeCoder {
     int low;
     int range;
     int outstanding_count;
     int outstanding_byte;
     uint8_t zero_state[256];
-    uint8_t  one_state[256];
+    uint8_t one_state[256];
     uint8_t *bytestream_start;
     uint8_t *bytestream;
     uint8_t *bytestream_end;
-}RangeCoder;
+} RangeCoder;
 
 void ff_init_range_encoder(RangeCoder *c, uint8_t *buf, int buf_size);
 void ff_init_range_decoder(RangeCoder *c, const uint8_t *buf, int buf_size);
 int ff_rac_terminate(RangeCoder *c);
 void ff_build_rac_states(RangeCoder *c, int factor, int max_p);
 
-static inline void renorm_encoder(RangeCoder *c){
-    //FIXME optimize
-    while(c->range < 0x100){
-        if(c->outstanding_byte < 0){
-            c->outstanding_byte= c->low>>8;
-        }else if(c->low <= 0xFF00){
+static inline void renorm_encoder(RangeCoder *c)
+{
+    // FIXME: optimize
+    while (c->range < 0x100) {
+        if (c->outstanding_byte < 0) {
+            c->outstanding_byte = c->low >> 8;
+        } else if (c->low <= 0xFF00) {
             *c->bytestream++ = c->outstanding_byte;
-            for(;c->outstanding_count; c->outstanding_count--)
+            for (; c->outstanding_count; c->outstanding_count--)
                 *c->bytestream++ = 0xFF;
-            c->outstanding_byte= c->low>>8;
-        }else if(c->low >= 0x10000){
+            c->outstanding_byte = c->low >> 8;
+        } else if (c->low >= 0x10000) {
             *c->bytestream++ = c->outstanding_byte + 1;
-            for(;c->outstanding_count; c->outstanding_count--)
+            for (; c->outstanding_count; c->outstanding_count--)
                 *c->bytestream++ = 0x00;
-            c->outstanding_byte= (c->low>>8) & 0xFF;
-        }else{
+            c->outstanding_byte = (c->low >> 8) & 0xFF;
+        } else {
             c->outstanding_count++;
         }
 
-        c->low = (c->low & 0xFF)<<8;
+        c->low     = (c->low & 0xFF) << 8;
         c->range <<= 8;
     }
 }
 
-static inline int get_rac_count(RangeCoder *c){
-    int x= c->bytestream - c->bytestream_start + c->outstanding_count;
-    if(c->outstanding_byte >= 0)
+static inline int get_rac_count(RangeCoder *c)
+{
+    int x = c->bytestream - c->bytestream_start + c->outstanding_count;
+    if (c->outstanding_byte >= 0)
         x++;
-    return 8*x - av_log2(c->range);
+    return 8 * x - av_log2(c->range);
 }
 
-static inline void put_rac(RangeCoder *c, uint8_t * const state, int bit){
-    int range1= (c->range * (*state)) >> 8;
+static inline void put_rac(RangeCoder *c, uint8_t *const state, int bit)
+{
+    int range1 = (c->range * (*state)) >> 8;
 
     av_assert2(*state);
     av_assert2(range1 < c->range);
     av_assert2(range1 > 0);
-    if(!bit){
+    if (!bit) {
         c->range -= range1;
-        *state= c->zero_state[*state];
-    }else{
-        c->low += c->range - range1;
+        *state    = c->zero_state[*state];
+    } else {
+        c->low  += c->range - range1;
         c->range = range1;
-        *state= c->one_state[*state];
+        *state   = c->one_state[*state];
     }
 
     renorm_encoder(c);
 }
 
-static inline void refill(RangeCoder *c){
-    if(c->range < 0x100){
+static inline void refill(RangeCoder *c)
+{
+    if (c->range < 0x100) {
         c->range <<= 8;
-        c->low <<= 8;
-        if(c->bytestream < c->bytestream_end)
-            c->low+= c->bytestream[0];
+        c->low   <<= 8;
+        if (c->bytestream < c->bytestream_end)
+            c->low += c->bytestream[0];
         c->bytestream++;
     }
 }
 
-static inline int get_rac(RangeCoder *c, uint8_t * const state){
-    int range1= (c->range * (*state)) >> 8;
+static inline int get_rac(RangeCoder *c, uint8_t *const state)
+{
+    int range1 = (c->range * (*state)) >> 8;
     int av_unused one_mask;
 
     c->range -= range1;
 #if 1
-    if(c->low < c->range){
-        *state= c->zero_state[*state];
+    if (c->low < c->range) {
+        *state = c->zero_state[*state];
         refill(c);
         return 0;
-    }else{
-        c->low -= c->range;
-        *state= c->one_state[*state];
+    } else {
+        c->low  -= c->range;
+        *state   = c->one_state[*state];
         c->range = range1;
         refill(c);
         return 1;
     }
 #else
-    one_mask= (c->range - c->low-1)>>31;
+    one_mask = (c->range - c->low - 1) >> 31;
 
-    c->low -= c->range & one_mask;
+    c->low   -= c->range & one_mask;
     c->range += (range1 - c->range) & one_mask;
 
-    *state= c->zero_state[(*state) + (256&one_mask)];
+    *state = c->zero_state[(*state) + (256 & one_mask)];
 
     refill(c);
 
-    return one_mask&1;
+    return one_mask & 1;
 #endif
 }
 
diff --git a/libavcodec/ratecontrol.c b/libavcodec/ratecontrol.c
index 8f8647c..59f69a2 100644
--- a/libavcodec/ratecontrol.c
+++ b/libavcodec/ratecontrol.c
@@ -112,7 +112,7 @@
 
     if (!s->avctx->rc_max_available_vbv_use && s->avctx->rc_buffer_size) {
         if (s->avctx->rc_max_rate) {
-            s->avctx->rc_max_available_vbv_use = av_clipf(s->avctx->rc_max_rate/(s->avctx->rc_buffer_size*get_fps(s->avctx)), 1.0/0.3, 1.0);
+            s->avctx->rc_max_available_vbv_use = av_clipf(s->avctx->rc_max_rate/(s->avctx->rc_buffer_size*get_fps(s->avctx)), 1.0/3, 1.0);
         } else
             s->avctx->rc_max_available_vbv_use = 1.0;
     }
@@ -691,7 +691,10 @@
 
     if(s->flags&CODEC_FLAG_PASS2){
         assert(picture_number>=0);
-        assert(picture_number<rcc->num_entries);
+        if(picture_number >= rcc->num_entries) {
+            av_log(s, AV_LOG_ERROR, "Input is longer than 2-pass log file\n");
+            return -1;
+        }
         rce= &rcc->entry[picture_number];
         wanted_bits= rce->expected_bits;
     }else{
diff --git a/libavcodec/raw.c b/libavcodec/raw.c
index 35d98f0..e23dbea 100644
--- a/libavcodec/raw.c
+++ b/libavcodec/raw.c
@@ -29,155 +29,174 @@
 #include "libavutil/common.h"
 
 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') },
-    { PIX_FMT_YUV410P, MKTAG('Y', 'U', 'V', '9') },
-    { PIX_FMT_YUV410P, MKTAG('Y', 'V', 'U', '9') },
-    { 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_YUV422P, MKTAG('Y', 'V', '1', '6') },
+    { AV_PIX_FMT_YUV420P, MKTAG('I', '4', '2', '0') }, /* Planar formats */
+    { AV_PIX_FMT_YUV420P, MKTAG('I', 'Y', 'U', 'V') },
+    { AV_PIX_FMT_YUV420P, MKTAG('Y', 'V', '1', '2') },
+    { AV_PIX_FMT_YUV410P, MKTAG('Y', 'U', 'V', '9') },
+    { AV_PIX_FMT_YUV410P, MKTAG('Y', 'V', 'U', '9') },
+    { AV_PIX_FMT_YUV411P, MKTAG('Y', '4', '1', 'B') },
+    { AV_PIX_FMT_YUV422P, MKTAG('Y', '4', '2', 'B') },
+    { AV_PIX_FMT_YUV422P, MKTAG('P', '4', '2', '2') },
+    { AV_PIX_FMT_YUV422P, MKTAG('Y', 'V', '1', '6') },
     /* 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', ' ', ' ') },
+    { AV_PIX_FMT_YUVJ420P, MKTAG('I', '4', '2', '0') }, /* Planar formats */
+    { AV_PIX_FMT_YUVJ420P, MKTAG('I', 'Y', 'U', 'V') },
+    { AV_PIX_FMT_YUVJ420P, MKTAG('Y', 'V', '1', '2') },
+    { AV_PIX_FMT_YUVJ422P, MKTAG('Y', '4', '2', 'B') },
+    { AV_PIX_FMT_YUVJ422P, MKTAG('P', '4', '2', '2') },
+    { AV_PIX_FMT_GRAY8,    MKTAG('Y', '8', '0', '0') },
+    { AV_PIX_FMT_GRAY8,    MKTAG('Y', '8', ' ', ' ') },
 
-    { PIX_FMT_YUYV422, MKTAG('Y', 'U', 'Y', '2') }, /* Packed formats */
-    { PIX_FMT_YUYV422, MKTAG('Y', '4', '2', '2') },
-    { PIX_FMT_YUYV422, MKTAG('V', '4', '2', '2') },
-    { PIX_FMT_YUYV422, MKTAG('V', 'Y', 'U', 'Y') },
-    { PIX_FMT_YUYV422, MKTAG('Y', 'U', 'N', 'V') },
-    { PIX_FMT_UYVY422, MKTAG('U', 'Y', 'V', 'Y') },
-    { PIX_FMT_UYVY422, MKTAG('H', 'D', 'Y', 'C') },
-    { PIX_FMT_UYVY422, MKTAG('U', 'Y', 'N', 'V') },
-    { PIX_FMT_UYVY422, MKTAG('U', 'Y', 'N', 'Y') },
-    { PIX_FMT_UYVY422, MKTAG('u', 'y', 'v', '1') },
-    { PIX_FMT_UYVY422, MKTAG('2', 'V', 'u', '1') },
-    { PIX_FMT_UYVY422, MKTAG('A', 'V', 'R', 'n') }, /* Avid AVI Codec 1:1 */
-    { 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_UYVY422, MKTAG('a', 'u', 'v', '2') },
-    { PIX_FMT_UYVY422, MKTAG('c', 'y', 'u', 'v') }, /* CYUV is also Creative YUV */
-    { 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') },
+    { AV_PIX_FMT_YUYV422, MKTAG('Y', 'U', 'Y', '2') }, /* Packed formats */
+    { AV_PIX_FMT_YUYV422, MKTAG('Y', '4', '2', '2') },
+    { AV_PIX_FMT_YUYV422, MKTAG('V', '4', '2', '2') },
+    { AV_PIX_FMT_YUYV422, MKTAG('V', 'Y', 'U', 'Y') },
+    { AV_PIX_FMT_YUYV422, MKTAG('Y', 'U', 'N', 'V') },
+    { AV_PIX_FMT_UYVY422, MKTAG('U', 'Y', 'V', 'Y') },
+    { AV_PIX_FMT_UYVY422, MKTAG('H', 'D', 'Y', 'C') },
+    { AV_PIX_FMT_UYVY422, MKTAG('U', 'Y', 'N', 'V') },
+    { AV_PIX_FMT_UYVY422, MKTAG('U', 'Y', 'N', 'Y') },
+    { AV_PIX_FMT_UYVY422, MKTAG('u', 'y', 'v', '1') },
+    { AV_PIX_FMT_UYVY422, MKTAG('2', 'V', 'u', '1') },
+    { AV_PIX_FMT_UYVY422, MKTAG('A', 'V', 'R', 'n') }, /* Avid AVI Codec 1:1 */
+    { AV_PIX_FMT_UYVY422, MKTAG('A', 'V', '1', 'x') }, /* Avid 1:1x */
+    { AV_PIX_FMT_UYVY422, MKTAG('A', 'V', 'u', 'p') },
+    { AV_PIX_FMT_UYVY422, MKTAG('V', 'D', 'T', 'Z') }, /* SoftLab-NSK VideoTizer */
+    { AV_PIX_FMT_UYVY422, MKTAG('a', 'u', 'v', '2') },
+    { AV_PIX_FMT_UYVY422, MKTAG('c', 'y', 'u', 'v') }, /* CYUV is also Creative YUV */
+    { AV_PIX_FMT_UYYVYY411, MKTAG('Y', '4', '1', '1') },
+    { AV_PIX_FMT_GRAY8,   MKTAG('G', 'R', 'E', 'Y') },
+    { AV_PIX_FMT_NV12,    MKTAG('N', 'V', '1', '2') },
+    { AV_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_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_RGBA64LE, MKTAG('R', 'B', 'A', 64 ) },
-    { PIX_FMT_BGRA64LE, MKTAG('B', 'R', 'A', 64 ) },
-    { PIX_FMT_RGBA64BE, MKTAG(64 , 'R', 'B', 'A') },
-    { PIX_FMT_BGRA64BE, MKTAG(64 , 'B', 'R', 'A') },
-    { PIX_FMT_RGBA,     MKTAG('R', 'G', 'B', 'A') },
-    { PIX_FMT_RGB0,     MKTAG('R', 'G', 'B',  0 ) },
-    { PIX_FMT_BGRA,     MKTAG('B', 'G', 'R', 'A') },
-    { PIX_FMT_BGR0,     MKTAG('B', 'G', 'R',  0 ) },
-    { PIX_FMT_ABGR,     MKTAG('A', 'B', 'G', 'R') },
-    { PIX_FMT_0BGR,     MKTAG( 0 , 'B', 'G', 'R') },
-    { PIX_FMT_ARGB,     MKTAG('A', 'R', 'G', 'B') },
-    { PIX_FMT_0RGB,     MKTAG( 0 , '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_BGR48LE,  MKTAG('B', 'G', 'R', 48 ) },
-    { PIX_FMT_BGR48BE,  MKTAG( 48, 'B', 'G', 'R') },
-    { PIX_FMT_GRAY16LE,    MKTAG('Y', '1',  0 , 16 ) },
-    { PIX_FMT_GRAY16BE,    MKTAG(16 ,  0 , '1', 'Y') },
-    { PIX_FMT_YUV420P10LE, MKTAG('Y', '3', 11 , 10 ) },
-    { PIX_FMT_YUV420P10BE, MKTAG(10 , 11 , '3', 'Y') },
-    { PIX_FMT_YUV422P10LE, MKTAG('Y', '3', 10 , 10 ) },
-    { PIX_FMT_YUV422P10BE, MKTAG(10 , 10 , '3', 'Y') },
-    { PIX_FMT_YUV444P10LE, MKTAG('Y', '3',  0 , 10 ) },
-    { PIX_FMT_YUV444P10BE, MKTAG(10 ,  0 , '3', 'Y') },
-    { PIX_FMT_YUV420P12LE, MKTAG('Y', '3', 11 , 12 ) },
-    { PIX_FMT_YUV420P12BE, MKTAG(12 , 11 , '3', 'Y') },
-    { PIX_FMT_YUV422P12LE, MKTAG('Y', '3', 10 , 12 ) },
-    { PIX_FMT_YUV422P12BE, MKTAG(12 , 10 , '3', 'Y') },
-    { PIX_FMT_YUV444P12LE, MKTAG('Y', '3',  0 , 12 ) },
-    { PIX_FMT_YUV444P12BE, MKTAG(12 ,  0 , '3', 'Y') },
-    { PIX_FMT_YUV420P14LE, MKTAG('Y', '3', 11 , 14 ) },
-    { PIX_FMT_YUV420P14BE, MKTAG(14 , 11 , '3', 'Y') },
-    { PIX_FMT_YUV422P14LE, MKTAG('Y', '3', 10 , 14 ) },
-    { PIX_FMT_YUV422P14BE, MKTAG(14 , 10 , '3', 'Y') },
-    { PIX_FMT_YUV444P14LE, MKTAG('Y', '3',  0 , 14 ) },
-    { PIX_FMT_YUV444P14BE, MKTAG(14 ,  0 , '3', '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_YUVA422P,    MKTAG('Y', '4', 10 ,  8 ) },
-    { PIX_FMT_YUVA444P,    MKTAG('Y', '4',  0 ,  8 ) },
-    { PIX_FMT_GRAY8A,      MKTAG('Y', '2',  0 ,  8 ) },
+    { AV_PIX_FMT_RGB555LE, MKTAG('R', 'G', 'B', 15) },
+    { AV_PIX_FMT_BGR555LE, MKTAG('B', 'G', 'R', 15) },
+    { AV_PIX_FMT_RGB565LE, MKTAG('R', 'G', 'B', 16) },
+    { AV_PIX_FMT_BGR565LE, MKTAG('B', 'G', 'R', 16) },
+    { AV_PIX_FMT_RGB555BE, MKTAG(15 , 'B', 'G', 'R') },
+    { AV_PIX_FMT_BGR555BE, MKTAG(15 , 'R', 'G', 'B') },
+    { AV_PIX_FMT_RGB565BE, MKTAG(16 , 'B', 'G', 'R') },
+    { AV_PIX_FMT_BGR565BE, MKTAG(16 , 'R', 'G', 'B') },
+    { AV_PIX_FMT_RGB444LE, MKTAG('R', 'G', 'B', 12) },
+    { AV_PIX_FMT_BGR444LE, MKTAG('B', 'G', 'R', 12) },
+    { AV_PIX_FMT_RGB444BE, MKTAG(12 , 'B', 'G', 'R') },
+    { AV_PIX_FMT_BGR444BE, MKTAG(12 , 'R', 'G', 'B') },
+    { AV_PIX_FMT_RGBA64LE, MKTAG('R', 'B', 'A', 64 ) },
+    { AV_PIX_FMT_BGRA64LE, MKTAG('B', 'R', 'A', 64 ) },
+    { AV_PIX_FMT_RGBA64BE, MKTAG(64 , 'R', 'B', 'A') },
+    { AV_PIX_FMT_BGRA64BE, MKTAG(64 , 'B', 'R', 'A') },
+    { AV_PIX_FMT_RGBA,     MKTAG('R', 'G', 'B', 'A') },
+    { AV_PIX_FMT_RGB0,     MKTAG('R', 'G', 'B',  0 ) },
+    { AV_PIX_FMT_BGRA,     MKTAG('B', 'G', 'R', 'A') },
+    { AV_PIX_FMT_BGR0,     MKTAG('B', 'G', 'R',  0 ) },
+    { AV_PIX_FMT_ABGR,     MKTAG('A', 'B', 'G', 'R') },
+    { AV_PIX_FMT_0BGR,     MKTAG( 0 , 'B', 'G', 'R') },
+    { AV_PIX_FMT_ARGB,     MKTAG('A', 'R', 'G', 'B') },
+    { AV_PIX_FMT_0RGB,     MKTAG( 0 , 'R', 'G', 'B') },
+    { AV_PIX_FMT_RGB24,    MKTAG('R', 'G', 'B', 24 ) },
+    { AV_PIX_FMT_BGR24,    MKTAG('B', 'G', 'R', 24 ) },
+    { AV_PIX_FMT_YUV411P,  MKTAG('4', '1', '1', 'P') },
+    { AV_PIX_FMT_YUV422P,  MKTAG('4', '2', '2', 'P') },
+    { AV_PIX_FMT_YUVJ422P, MKTAG('4', '2', '2', 'P') },
+    { AV_PIX_FMT_YUV440P,  MKTAG('4', '4', '0', 'P') },
+    { AV_PIX_FMT_YUVJ440P, MKTAG('4', '4', '0', 'P') },
+    { AV_PIX_FMT_YUV444P,  MKTAG('4', '4', '4', 'P') },
+    { AV_PIX_FMT_YUVJ444P, MKTAG('4', '4', '4', 'P') },
+    { AV_PIX_FMT_MONOWHITE,MKTAG('B', '1', 'W', '0') },
+    { AV_PIX_FMT_MONOBLACK,MKTAG('B', '0', 'W', '1') },
+    { AV_PIX_FMT_BGR8,     MKTAG('B', 'G', 'R',  8 ) },
+    { AV_PIX_FMT_RGB8,     MKTAG('R', 'G', 'B',  8 ) },
+    { AV_PIX_FMT_BGR4,     MKTAG('B', 'G', 'R',  4 ) },
+    { AV_PIX_FMT_RGB4,     MKTAG('R', 'G', 'B',  4 ) },
+    { AV_PIX_FMT_RGB4_BYTE,MKTAG('B', '4', 'B', 'Y') },
+    { AV_PIX_FMT_BGR4_BYTE,MKTAG('R', '4', 'B', 'Y') },
+    { AV_PIX_FMT_RGB48LE,  MKTAG('R', 'G', 'B', 48 ) },
+    { AV_PIX_FMT_RGB48BE,  MKTAG( 48, 'R', 'G', 'B') },
+    { AV_PIX_FMT_BGR48LE,  MKTAG('B', 'G', 'R', 48 ) },
+    { AV_PIX_FMT_BGR48BE,  MKTAG( 48, 'B', 'G', 'R') },
+    { AV_PIX_FMT_GRAY16LE,    MKTAG('Y', '1',  0 , 16 ) },
+    { AV_PIX_FMT_GRAY16BE,    MKTAG(16 ,  0 , '1', 'Y') },
+    { AV_PIX_FMT_YUV420P10LE, MKTAG('Y', '3', 11 , 10 ) },
+    { AV_PIX_FMT_YUV420P10BE, MKTAG(10 , 11 , '3', 'Y') },
+    { AV_PIX_FMT_YUV422P10LE, MKTAG('Y', '3', 10 , 10 ) },
+    { AV_PIX_FMT_YUV422P10BE, MKTAG(10 , 10 , '3', 'Y') },
+    { AV_PIX_FMT_YUV444P10LE, MKTAG('Y', '3',  0 , 10 ) },
+    { AV_PIX_FMT_YUV444P10BE, MKTAG(10 ,  0 , '3', 'Y') },
+    { AV_PIX_FMT_YUV420P12LE, MKTAG('Y', '3', 11 , 12 ) },
+    { AV_PIX_FMT_YUV420P12BE, MKTAG(12 , 11 , '3', 'Y') },
+    { AV_PIX_FMT_YUV422P12LE, MKTAG('Y', '3', 10 , 12 ) },
+    { AV_PIX_FMT_YUV422P12BE, MKTAG(12 , 10 , '3', 'Y') },
+    { AV_PIX_FMT_YUV444P12LE, MKTAG('Y', '3',  0 , 12 ) },
+    { AV_PIX_FMT_YUV444P12BE, MKTAG(12 ,  0 , '3', 'Y') },
+    { AV_PIX_FMT_YUV420P14LE, MKTAG('Y', '3', 11 , 14 ) },
+    { AV_PIX_FMT_YUV420P14BE, MKTAG(14 , 11 , '3', 'Y') },
+    { AV_PIX_FMT_YUV422P14LE, MKTAG('Y', '3', 10 , 14 ) },
+    { AV_PIX_FMT_YUV422P14BE, MKTAG(14 , 10 , '3', 'Y') },
+    { AV_PIX_FMT_YUV444P14LE, MKTAG('Y', '3',  0 , 14 ) },
+    { AV_PIX_FMT_YUV444P14BE, MKTAG(14 ,  0 , '3', 'Y') },
+    { AV_PIX_FMT_YUV420P16LE, MKTAG('Y', '3', 11 , 16 ) },
+    { AV_PIX_FMT_YUV420P16BE, MKTAG(16 , 11 , '3', 'Y') },
+    { AV_PIX_FMT_YUV422P16LE, MKTAG('Y', '3', 10 , 16 ) },
+    { AV_PIX_FMT_YUV422P16BE, MKTAG(16 , 10 , '3', 'Y') },
+    { AV_PIX_FMT_YUV444P16LE, MKTAG('Y', '3',  0 , 16 ) },
+    { AV_PIX_FMT_YUV444P16BE, MKTAG(16 ,  0 , '3', 'Y') },
+    { AV_PIX_FMT_YUVA420P,    MKTAG('Y', '4', 11 ,  8 ) },
+    { AV_PIX_FMT_YUVA422P,    MKTAG('Y', '4', 10 ,  8 ) },
+    { AV_PIX_FMT_YUVA444P,    MKTAG('Y', '4',  0 ,  8 ) },
+    { AV_PIX_FMT_GRAY8A,      MKTAG('Y', '2',  0 ,  8 ) },
+
+    { AV_PIX_FMT_YUVA420P9LE,  MKTAG('Y', '4', 11 ,  9 ) },
+    { AV_PIX_FMT_YUVA420P9BE,  MKTAG( 9 , 11 , '4', 'Y') },
+    { AV_PIX_FMT_YUVA422P9LE,  MKTAG('Y', '4', 10 ,  9 ) },
+    { AV_PIX_FMT_YUVA422P9BE,  MKTAG( 9 , 10 , '4', 'Y') },
+    { AV_PIX_FMT_YUVA444P9LE,  MKTAG('Y', '4',  0 ,  9 ) },
+    { AV_PIX_FMT_YUVA444P9BE,  MKTAG( 9 ,  0 , '4', 'Y') },
+    { AV_PIX_FMT_YUVA420P10LE, MKTAG('Y', '4', 11 , 10 ) },
+    { AV_PIX_FMT_YUVA420P10BE, MKTAG(10 , 11 , '4', 'Y') },
+    { AV_PIX_FMT_YUVA422P10LE, MKTAG('Y', '4', 10 , 10 ) },
+    { AV_PIX_FMT_YUVA422P10BE, MKTAG(10 , 10 , '4', 'Y') },
+    { AV_PIX_FMT_YUVA444P10LE, MKTAG('Y', '4',  0 , 10 ) },
+    { AV_PIX_FMT_YUVA444P10BE, MKTAG(10 ,  0 , '4', 'Y') },
+    { AV_PIX_FMT_YUVA420P16LE, MKTAG('Y', '4', 11 , 16 ) },
+    { AV_PIX_FMT_YUVA420P16BE, MKTAG(16 , 11 , '4', 'Y') },
+    { AV_PIX_FMT_YUVA422P16LE, MKTAG('Y', '4', 10 , 16 ) },
+    { AV_PIX_FMT_YUVA422P16BE, MKTAG(16 , 10 , '4', 'Y') },
+    { AV_PIX_FMT_YUVA444P16LE, MKTAG('Y', '4',  0 , 16 ) },
+    { AV_PIX_FMT_YUVA444P16BE, MKTAG(16 ,  0 , '4', 'Y') },
 
     /* quicktime */
-    { PIX_FMT_YUV420P, MKTAG('R', '4', '2', '0') }, /* Radius DV YUV PAL */
-    { PIX_FMT_YUV411P, MKTAG('R', '4', '1', '1') }, /* Radius DV YUV NTSC */
-    { PIX_FMT_UYVY422, MKTAG('2', 'v', 'u', 'y') },
-    { PIX_FMT_UYVY422, MKTAG('2', 'V', 'u', 'y') },
-    { PIX_FMT_UYVY422, MKTAG('A', 'V', 'U', 'I') }, /* FIXME merge both fields */
-    { PIX_FMT_UYVY422, MKTAG('b', 'x', 'y', 'v') },
-    { PIX_FMT_YUYV422, MKTAG('y', 'u', 'v', '2') },
-    { PIX_FMT_YUYV422, MKTAG('y', 'u', 'v', 's') },
-    { PIX_FMT_YUYV422, MKTAG('D', 'V', 'O', 'O') }, /* Digital Voodoo SD 8 Bit */
-    { 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_BGR24,   MKTAG('b', 'x', 'b', 'g') },
-    { PIX_FMT_BGRA,    MKTAG('B', 'G', 'R', 'A') },
-    { PIX_FMT_RGBA,    MKTAG('R', 'G', 'B', 'A') },
-    { PIX_FMT_RGB24,   MKTAG('b', 'x', 'r', 'g') },
-    { PIX_FMT_ABGR,    MKTAG('A', 'B', 'G', 'R') },
-    { PIX_FMT_GRAY16BE,MKTAG('b', '1', '6', 'g') },
-    { PIX_FMT_RGB48BE, MKTAG('b', '4', '8', 'r') },
+    { AV_PIX_FMT_YUV420P, MKTAG('R', '4', '2', '0') }, /* Radius DV YUV PAL */
+    { AV_PIX_FMT_YUV411P, MKTAG('R', '4', '1', '1') }, /* Radius DV YUV NTSC */
+    { AV_PIX_FMT_UYVY422, MKTAG('2', 'v', 'u', 'y') },
+    { AV_PIX_FMT_UYVY422, MKTAG('2', 'V', 'u', 'y') },
+    { AV_PIX_FMT_UYVY422, MKTAG('A', 'V', 'U', 'I') }, /* FIXME merge both fields */
+    { AV_PIX_FMT_UYVY422, MKTAG('b', 'x', 'y', 'v') },
+    { AV_PIX_FMT_YUYV422, MKTAG('y', 'u', 'v', '2') },
+    { AV_PIX_FMT_YUYV422, MKTAG('y', 'u', 'v', 's') },
+    { AV_PIX_FMT_YUYV422, MKTAG('D', 'V', 'O', 'O') }, /* Digital Voodoo SD 8 Bit */
+    { AV_PIX_FMT_RGB555LE,MKTAG('L', '5', '5', '5') },
+    { AV_PIX_FMT_RGB565LE,MKTAG('L', '5', '6', '5') },
+    { AV_PIX_FMT_RGB565BE,MKTAG('B', '5', '6', '5') },
+    { AV_PIX_FMT_BGR24,   MKTAG('2', '4', 'B', 'G') },
+    { AV_PIX_FMT_BGR24,   MKTAG('b', 'x', 'b', 'g') },
+    { AV_PIX_FMT_BGRA,    MKTAG('B', 'G', 'R', 'A') },
+    { AV_PIX_FMT_RGBA,    MKTAG('R', 'G', 'B', 'A') },
+    { AV_PIX_FMT_RGB24,   MKTAG('b', 'x', 'r', 'g') },
+    { AV_PIX_FMT_ABGR,    MKTAG('A', 'B', 'G', 'R') },
+    { AV_PIX_FMT_GRAY16BE,MKTAG('b', '1', '6', 'g') },
+    { AV_PIX_FMT_RGB48BE, MKTAG('b', '4', '8', 'r') },
 
     /* special */
-    { PIX_FMT_RGB565LE,MKTAG( 3 ,  0 ,  0 ,  0 ) }, /* flipped RGB565LE */
-    { PIX_FMT_YUV444P, MKTAG('Y', 'V', '2', '4') }, /* YUV444P, swapped UV */
-    { PIX_FMT_YUYV422, MKTAG('Y', 'V', 'Y', 'U') }, /* YUYV, swapped UV */
+    { AV_PIX_FMT_RGB565LE,MKTAG( 3 ,  0 ,  0 ,  0 ) }, /* flipped RGB565LE */
+    { AV_PIX_FMT_YUV444P, MKTAG('Y', 'V', '2', '4') }, /* YUV444P, swapped UV */
+    { AV_PIX_FMT_YUYV422, MKTAG('Y', 'V', 'Y', 'U') }, /* YUYV, swapped UV */
 
-    { PIX_FMT_NONE, 0 },
+    { AV_PIX_FMT_NONE, 0 },
 };
 
-unsigned int avcodec_pix_fmt_to_codec_tag(enum PixelFormat fmt)
+unsigned int avcodec_pix_fmt_to_codec_tag(enum AVPixelFormat fmt)
 {
     const PixelFormatTag *tags = ff_raw_pix_fmt_tags;
     while (tags->pix_fmt >= 0) {
diff --git a/libavcodec/raw.h b/libavcodec/raw.h
index f5dd067..87b6c90 100644
--- a/libavcodec/raw.h
+++ b/libavcodec/raw.h
@@ -28,14 +28,14 @@
 #define AVCODEC_RAW_H
 
 #include "avcodec.h"
-#include "symbols.h"
+#include "libavutil/internal.h"
 
 typedef struct PixelFormatTag {
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
     unsigned int fourcc;
 } PixelFormatTag;
 
-extern AVCODEC_SYMBOL const PixelFormatTag ff_raw_pix_fmt_tags[];
-enum PixelFormat ff_find_pix_fmt(const PixelFormatTag *tags, unsigned int fourcc);
+extern av_export const PixelFormatTag ff_raw_pix_fmt_tags[];
+enum AVPixelFormat ff_find_pix_fmt(const PixelFormatTag *tags, unsigned int fourcc);
 
 #endif /* AVCODEC_RAW_H */
diff --git a/libavcodec/rawdec.c b/libavcodec/rawdec.c
index 8eb0fae..f60f5e4 100644
--- a/libavcodec/rawdec.c
+++ b/libavcodec/rawdec.c
@@ -54,40 +54,40 @@
 };
 
 static const PixelFormatTag pix_fmt_bps_avi[] = {
-    { PIX_FMT_MONOWHITE, 1 },
-    { PIX_FMT_PAL8,    2 },
-    { PIX_FMT_PAL8,    4 },
-    { PIX_FMT_PAL8,    8 },
-    { PIX_FMT_RGB444, 12 },
-    { PIX_FMT_RGB555, 15 },
-    { PIX_FMT_RGB555, 16 },
-    { PIX_FMT_BGR24,  24 },
-    { PIX_FMT_BGRA,   32 },
-    { PIX_FMT_NONE, 0 },
+    { AV_PIX_FMT_MONOWHITE, 1 },
+    { AV_PIX_FMT_PAL8,    2 },
+    { AV_PIX_FMT_PAL8,    4 },
+    { AV_PIX_FMT_PAL8,    8 },
+    { AV_PIX_FMT_RGB444, 12 },
+    { AV_PIX_FMT_RGB555, 15 },
+    { AV_PIX_FMT_RGB555, 16 },
+    { AV_PIX_FMT_BGR24,  24 },
+    { AV_PIX_FMT_BGRA,   32 },
+    { AV_PIX_FMT_NONE, 0 },
 };
 
 static const PixelFormatTag pix_fmt_bps_mov[] = {
-    { PIX_FMT_MONOWHITE, 1 },
-    { PIX_FMT_PAL8,      2 },
-    { PIX_FMT_PAL8,      4 },
-    { PIX_FMT_PAL8,      8 },
+    { AV_PIX_FMT_MONOWHITE, 1 },
+    { AV_PIX_FMT_PAL8,      2 },
+    { AV_PIX_FMT_PAL8,      4 },
+    { AV_PIX_FMT_PAL8,      8 },
     // FIXME swscale does not support 16 bit in .mov, sample 16bit.mov
     // http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap3/qtff3.html
-    { PIX_FMT_RGB555BE, 16 },
-    { PIX_FMT_RGB24,    24 },
-    { PIX_FMT_ARGB,     32 },
-    { PIX_FMT_MONOWHITE,33 },
-    { PIX_FMT_NONE, 0 },
+    { AV_PIX_FMT_RGB555BE, 16 },
+    { AV_PIX_FMT_RGB24,    24 },
+    { AV_PIX_FMT_ARGB,     32 },
+    { AV_PIX_FMT_MONOWHITE,33 },
+    { AV_PIX_FMT_NONE, 0 },
 };
 
-enum PixelFormat ff_find_pix_fmt(const PixelFormatTag *tags, unsigned int fourcc)
+enum AVPixelFormat ff_find_pix_fmt(const PixelFormatTag *tags, unsigned int fourcc)
 {
     while (tags->pix_fmt >= 0) {
         if (tags->fourcc == fourcc)
             return tags->pix_fmt;
         tags++;
     }
-    return PIX_FMT_YUV420P;
+    return AV_PIX_FMT_YUV420P;
 }
 
 static av_cold int raw_init_decoder(AVCodecContext *avctx)
@@ -100,24 +100,28 @@
         avctx->pix_fmt = ff_find_pix_fmt(pix_fmt_bps_avi, avctx->bits_per_coded_sample);
     else if (avctx->codec_tag)
         avctx->pix_fmt = ff_find_pix_fmt(ff_raw_pix_fmt_tags, avctx->codec_tag);
-    else if (avctx->pix_fmt == PIX_FMT_NONE && avctx->bits_per_coded_sample)
+    else if (avctx->pix_fmt == AV_PIX_FMT_NONE && avctx->bits_per_coded_sample)
         avctx->pix_fmt = ff_find_pix_fmt(pix_fmt_bps_avi, avctx->bits_per_coded_sample);
 
-    if (avctx->pix_fmt == PIX_FMT_NONE) {
+    if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
         av_log(avctx, AV_LOG_ERROR, "Pixel format was not specified and cannot be detected\n");
         return AVERROR(EINVAL);
     }
 
-    ff_set_systematic_pal2(context->palette, avctx->pix_fmt);
+    avpriv_set_systematic_pal2(context->palette, avctx->pix_fmt);
     if((avctx->bits_per_coded_sample == 4 || avctx->bits_per_coded_sample == 2) &&
-       avctx->pix_fmt==PIX_FMT_PAL8 &&
+       avctx->pix_fmt==AV_PIX_FMT_PAL8 &&
        (!avctx->codec_tag || avctx->codec_tag == MKTAG('r','a','w',' '))){
         context->length = avpicture_get_size(avctx->pix_fmt, FFALIGN(avctx->width, 16), avctx->height);
+        if (context->length < 0)
+            return context->length;
         context->buffer = av_malloc(context->length);
         if (!context->buffer)
             return AVERROR(ENOMEM);
     } else {
         context->length = avpicture_get_size(avctx->pix_fmt, avctx->width, avctx->height);
+        if (context->length < 0)
+            return context->length;
     }
     context->pic.pict_type = AV_PICTURE_TYPE_I;
     context->pic.key_frame = 1;
@@ -129,6 +133,13 @@
         avctx->codec_tag == MKTAG(3, 0, 0, 0) || avctx->codec_tag == MKTAG('W','R','A','W'))
         context->flip=1;
 
+    if (avctx->field_order > AV_FIELD_PROGRESSIVE) { /*we have interlaced material flagged in container */
+        avctx->coded_frame->interlaced_frame = 1;
+        if (avctx->field_order == AV_FIELD_TT  || avctx->field_order == AV_FIELD_TB)
+            avctx->coded_frame->top_field_first = 1;
+    }
+
+
     return 0;
 }
 
@@ -145,6 +156,7 @@
     int buf_size = avpkt->size;
     int linesize_align = 4;
     RawVideoContext *context = avctx->priv_data;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
     int res, len;
 
     AVFrame   *frame   = data;
@@ -163,10 +175,8 @@
         frame->top_field_first  = context->tff;
     }
 
-    if (avctx->width <= 0 || avctx->height <= 0) {
-        av_log(avctx, AV_LOG_ERROR, "w/h is invalid\n");
-        return AVERROR(EINVAL);
-    }
+    if ((res = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0)
+        return res;
 
     //2bpp and 4bpp raw in avi and mov (yes this is ugly ...)
     if (context->buffer) {
@@ -196,7 +206,7 @@
        avctx->codec_tag == MKTAG('A', 'V', 'u', 'p'))
         buf += buf_size - context->length;
 
-    len = context->length - (avctx->pix_fmt==PIX_FMT_PAL8 ? AVPALETTE_SIZE : 0);
+    len = context->length - (avctx->pix_fmt==AV_PIX_FMT_PAL8 ? AVPALETTE_SIZE : 0);
     if (buf_size < len) {
         av_log(avctx, AV_LOG_ERROR, "Invalid buffer size, packet size %d < expected length %d\n", buf_size, len);
         return AVERROR(EINVAL);
@@ -205,11 +215,11 @@
     if ((res = avpicture_fill(picture, buf, avctx->pix_fmt,
                               avctx->width, avctx->height)) < 0)
         return res;
-    if((avctx->pix_fmt==PIX_FMT_PAL8 && buf_size < context->length) ||
-       (av_pix_fmt_descriptors[avctx->pix_fmt].flags & PIX_FMT_PSEUDOPAL)) {
+    if((avctx->pix_fmt==AV_PIX_FMT_PAL8 && buf_size < context->length) ||
+       (desc->flags & PIX_FMT_PSEUDOPAL)) {
         frame->data[1]= (uint8_t*)context->palette;
     }
-    if (avctx->pix_fmt == PIX_FMT_PAL8) {
+    if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
         const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);
 
         if (pal) {
@@ -217,13 +227,13 @@
             frame->palette_has_changed = 1;
         }
     }
-    if((avctx->pix_fmt==PIX_FMT_BGR24    ||
-        avctx->pix_fmt==PIX_FMT_GRAY8    ||
-        avctx->pix_fmt==PIX_FMT_RGB555LE ||
-        avctx->pix_fmt==PIX_FMT_RGB555BE ||
-        avctx->pix_fmt==PIX_FMT_RGB565LE ||
-        avctx->pix_fmt==PIX_FMT_MONOWHITE ||
-        avctx->pix_fmt==PIX_FMT_PAL8) &&
+    if((avctx->pix_fmt==AV_PIX_FMT_BGR24    ||
+        avctx->pix_fmt==AV_PIX_FMT_GRAY8    ||
+        avctx->pix_fmt==AV_PIX_FMT_RGB555LE ||
+        avctx->pix_fmt==AV_PIX_FMT_RGB555BE ||
+        avctx->pix_fmt==AV_PIX_FMT_RGB565LE ||
+        avctx->pix_fmt==AV_PIX_FMT_MONOWHITE ||
+        avctx->pix_fmt==AV_PIX_FMT_PAL8) &&
         FFALIGN(frame->linesize[0], linesize_align)*avctx->height <= buf_size)
         frame->linesize[0] = FFALIGN(frame->linesize[0], linesize_align);
 
@@ -237,7 +247,7 @@
         FFSWAP(uint8_t *, picture->data[1], picture->data[2]);
 
     if(avctx->codec_tag == AV_RL32("yuv2") &&
-       avctx->pix_fmt   == PIX_FMT_YUYV422) {
+       avctx->pix_fmt   == AV_PIX_FMT_YUYV422) {
         int x, y;
         uint8_t *line = picture->data[0];
         for(y = 0; y < avctx->height; y++) {
@@ -247,7 +257,7 @@
         }
     }
     if(avctx->codec_tag == AV_RL32("YVYU") &&
-       avctx->pix_fmt   == PIX_FMT_YUYV422) {
+       avctx->pix_fmt   == AV_PIX_FMT_YUYV422) {
         int x, y;
         uint8_t *line = picture->data[0];
         for(y = 0; y < avctx->height; y++) {
diff --git a/libavcodec/rawenc.c b/libavcodec/rawenc.c
index 9d61e81..c6da6b8 100644
--- a/libavcodec/rawenc.c
+++ b/libavcodec/rawenc.c
@@ -33,10 +33,12 @@
 
 static av_cold int raw_init_encoder(AVCodecContext *avctx)
 {
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
+
     avctx->coded_frame            = avctx->priv_data;
     avcodec_get_frame_defaults(avctx->coded_frame);
     avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
-    avctx->bits_per_coded_sample = av_get_bits_per_pixel(&av_pix_fmt_descriptors[avctx->pix_fmt]);
+    avctx->bits_per_coded_sample = av_get_bits_per_pixel(desc);
     if(!avctx->codec_tag)
         avctx->codec_tag = avcodec_pix_fmt_to_codec_tag(avctx->pix_fmt);
     return 0;
@@ -57,7 +59,7 @@
         return ret;
 
     if(avctx->codec_tag == AV_RL32("yuv2") && ret > 0 &&
-       avctx->pix_fmt   == PIX_FMT_YUYV422) {
+       avctx->pix_fmt   == AV_PIX_FMT_YUYV422) {
         int x;
         for(x = 1; x < avctx->height*avctx->width*2; x += 2)
             pkt->data[x] ^= 0x80;
diff --git a/libavcodec/resample.c b/libavcodec/resample.c
index 04e5aab..dfaad66 100644
--- a/libavcodec/resample.c
+++ b/libavcodec/resample.c
@@ -32,6 +32,8 @@
 #include "libavutil/mem.h"
 #include "libavutil/samplefmt.h"
 
+#if FF_API_AVCODEC_RESAMPLE
+
 #define MAX_CHANNELS 8
 
 struct AVResampleContext;
@@ -429,3 +431,5 @@
     av_audio_convert_free(s->convert_ctx[1]);
     av_free(s);
 }
+
+#endif
diff --git a/libavcodec/resample2.c b/libavcodec/resample2.c
index 3818612..3a3cd13 100644
--- a/libavcodec/resample2.c
+++ b/libavcodec/resample2.c
@@ -30,6 +30,8 @@
 #include "dsputil.h"
 #include "libavutil/common.h"
 
+#if FF_API_AVCODEC_RESAMPLE
+
 #ifndef CONFIG_RESAMPLE_HP
 #define FILTER_SHIFT 15
 
@@ -321,3 +323,5 @@
 
     return dst_index;
 }
+
+#endif
diff --git a/libavcodec/rl2.c b/libavcodec/rl2.c
index 151b884..c51fbd5 100644
--- a/libavcodec/rl2.c
+++ b/libavcodec/rl2.c
@@ -134,13 +134,13 @@
     int back_size;
     int i;
     s->avctx = avctx;
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
     avcodec_get_frame_defaults(&s->frame);
 
     /** parse extra data */
     if(!avctx->extradata || avctx->extradata_size < EXTRADATA1_SIZE){
         av_log(avctx, AV_LOG_ERROR, "invalid extradata size\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     /** get frame_offset */
@@ -149,12 +149,12 @@
 
     if(s->video_base >= avctx->width * avctx->height){
         av_log(avctx, AV_LOG_ERROR, "invalid video_base\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     /** initialize palette */
     for(i=0;i<AVPALETTE_COUNT;i++)
-        s->palette[i] = 0xFF << 24 | AV_RB24(&avctx->extradata[6 + i * 3]);
+        s->palette[i] = 0xFFU << 24 | AV_RB24(&avctx->extradata[6 + i * 3]);
 
     /** decode background frame if present */
     back_size = avctx->extradata_size - EXTRADATA1_SIZE;
@@ -162,7 +162,7 @@
     if(back_size > 0){
         unsigned char* back_frame = av_mallocz(avctx->width*avctx->height);
         if(!back_frame)
-            return -1;
+            return AVERROR(ENOMEM);
         rl2_rle_decode(s,avctx->extradata + EXTRADATA1_SIZE,back_size,
                            back_frame,avctx->width,0);
         s->back_frame = back_frame;
@@ -178,15 +178,16 @@
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
     Rl2Context *s = avctx->priv_data;
+    int ret;
 
     if(s->frame.data[0])
         avctx->release_buffer(avctx, &s->frame);
 
     /** get buffer */
     s->frame.reference= 0;
-    if(avctx->get_buffer(avctx, &s->frame)) {
+    if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
         av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
+        return ret;
     }
 
     /** run length decode */
diff --git a/libavcodec/roqaudioenc.c b/libavcodec/roqaudioenc.c
index 0129051..ed5481f 100644
--- a/libavcodec/roqaudioenc.c
+++ b/libavcodec/roqaudioenc.c
@@ -21,10 +21,10 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#include "libavutil/intmath.h"
 #include "avcodec.h"
 #include "bytestream.h"
 #include "internal.h"
+#include "mathops.h"
 
 #define ROQ_FRAME_SIZE           735
 #define ROQ_HEADER_SIZE   8
@@ -158,6 +158,8 @@
             context->input_frames++;
             return 0;
         }
+    }
+    if (context->input_frames < 8) {
         in = context->frame_buffer;
     }
 
@@ -166,7 +168,7 @@
         context->lastSample[1] &= 0xFF00;
     }
 
-    if (context->input_frames == 7 || !in)
+    if (context->input_frames == 7)
         data_size = avctx->channels * context->buffered_samples;
     else
         data_size = avctx->channels * avctx->frame_size;
diff --git a/libavcodec/roqvideo.h b/libavcodec/roqvideo.h
index 6fc7161..2f9493d 100644
--- a/libavcodec/roqvideo.h
+++ b/libavcodec/roqvideo.h
@@ -27,16 +27,16 @@
 #include "bytestream.h"
 #include "dsputil.h"
 
-typedef struct {
+typedef struct roq_cell {
     unsigned char y[4];
     unsigned char u, v;
 } roq_cell;
 
-typedef struct {
+typedef struct roq_qcell {
     int idx[4];
 } roq_qcell;
 
-typedef struct {
+typedef struct motion_vect {
     int d[2];
 } motion_vect;
 
diff --git a/libavcodec/roqvideodec.c b/libavcodec/roqvideodec.c
index b4cf454..3a8e904 100644
--- a/libavcodec/roqvideodec.c
+++ b/libavcodec/roqvideodec.c
@@ -25,6 +25,7 @@
  *   http://www.csse.monash.edu.au/~timf/
  */
 
+#include "libavutil/avassert.h"
 #include "avcodec.h"
 #include "bytestream.h"
 #include "roqvideo.h"
@@ -149,7 +150,7 @@
                     }
                     break;
                 default:
-                    av_log(ri->avctx, AV_LOG_ERROR, "Unknown vq code: %d\n", vqid);
+                    av_assert2(0);
             }
         }
 
@@ -169,13 +170,19 @@
     RoqContext *s = avctx->priv_data;
 
     s->avctx = avctx;
+
+    if (avctx->width%16 || avctx->height%16) {
+         av_log_ask_for_sample(avctx, "dimensions not being a multiple of 16 are unsupported\n");
+         return AVERROR_PATCHWELCOME;
+    }
+
     s->width = avctx->width;
     s->height = avctx->height;
     avcodec_get_frame_defaults(&s->frames[0]);
     avcodec_get_frame_defaults(&s->frames[1]);
     s->last_frame    = &s->frames[0];
     s->current_frame = &s->frames[1];
-    avctx->pix_fmt = PIX_FMT_YUV444P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV444P;
 
     return 0;
 }
diff --git a/libavcodec/roqvideoenc.c b/libavcodec/roqvideoenc.c
index eee0046..b38ecab 100644
--- a/libavcodec/roqvideoenc.c
+++ b/libavcodec/roqvideoenc.c
@@ -1079,7 +1079,7 @@
     .encode2              = roq_encode_frame,
     .close                = roq_encode_end,
     .supported_framerates = (const AVRational[]){ {30,1}, {0,0} },
-    .pix_fmts             = (const enum PixelFormat[]){ PIX_FMT_YUV444P,
-                                                        PIX_FMT_NONE },
+    .pix_fmts             = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV444P,
+                                                        AV_PIX_FMT_NONE },
     .long_name            = NULL_IF_CONFIG_SMALL("id RoQ video"),
 };
diff --git a/libavcodec/rpza.c b/libavcodec/rpza.c
index b12bf04..498c36e 100644
--- a/libavcodec/rpza.c
+++ b/libavcodec/rpza.c
@@ -236,7 +236,7 @@
     RpzaContext *s = avctx->priv_data;
 
     s->avctx = avctx;
-    avctx->pix_fmt = PIX_FMT_RGB555;
+    avctx->pix_fmt = AV_PIX_FMT_RGB555;
 
     avcodec_get_frame_defaults(&s->frame);
     s->frame.data[0] = NULL;
diff --git a/libavcodec/rtjpeg.h b/libavcodec/rtjpeg.h
index 5b359db..0fd24a3 100644
--- a/libavcodec/rtjpeg.h
+++ b/libavcodec/rtjpeg.h
@@ -29,7 +29,7 @@
 #define RTJPEG_FILE_VERSION 0
 #define RTJPEG_HEADER_SIZE 12
 
-typedef struct {
+typedef struct RTJpegContext {
     int w, h;
     DSPContext *dsp;
     uint8_t scan[64];
diff --git a/libavcodec/rv10.c b/libavcodec/rv10.c
index 49072de..d06a2fe 100644
--- a/libavcodec/rv10.c
+++ b/libavcodec/rv10.c
@@ -332,6 +332,10 @@
         return -1;
     }
 
+    if(s->low_delay && s->pict_type==AV_PICTURE_TYPE_B){
+        av_log(s->avctx, AV_LOG_ERROR, "low delay B\n");
+        return -1;
+    }
     if(s->last_picture_ptr==NULL && s->pict_type==AV_PICTURE_TYPE_B){
         av_log(s->avctx, AV_LOG_ERROR, "early B pix\n");
         return -1;
@@ -394,7 +398,8 @@
         if(s->avctx->debug & FF_DEBUG_PICT_INFO){
             av_log(s->avctx, AV_LOG_DEBUG, "F %d/%d\n", f, rpr_bits);
         }
-    } else if (av_image_check_size(s->width, s->height, 0, s->avctx) < 0)
+    }
+    if (av_image_check_size(s->width, s->height, 0, s->avctx) < 0)
         return AVERROR_INVALIDDATA;
 
     mb_pos = ff_h263_decode_mba(s);
@@ -493,7 +498,7 @@
         av_log(avctx, AV_LOG_DEBUG, "ver:%X ver0:%X\n", rv->sub_id, avctx->extradata_size >= 4 ? ((uint32_t*)avctx->extradata)[0] : -1);
     }
 
-    avctx->pix_fmt = PIX_FMT_YUV420P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV420P;
 
     if (ff_MPV_common_init(s) < 0)
         return -1;
diff --git a/libavcodec/rv10enc.c b/libavcodec/rv10enc.c
index 7a2045a..c4c5c53 100644
--- a/libavcodec/rv10enc.c
+++ b/libavcodec/rv10enc.c
@@ -66,7 +66,7 @@
     .init           = ff_MPV_encode_init,
     .encode2        = ff_MPV_encode_picture,
     .close          = ff_MPV_encode_end,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUV420P, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("RealVideo 1.0"),
     .priv_class     = &rv10_class,
 };
diff --git a/libavcodec/rv20enc.c b/libavcodec/rv20enc.c
index 2d21818..295699a 100644
--- a/libavcodec/rv20enc.c
+++ b/libavcodec/rv20enc.c
@@ -67,7 +67,7 @@
     .init           = ff_MPV_encode_init,
     .encode2        = ff_MPV_encode_picture,
     .close          = ff_MPV_encode_end,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUV420P, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("RealVideo 2.0"),
     .priv_class     = &rv20_class,
 };
diff --git a/libavcodec/rv30.c b/libavcodec/rv30.c
index b033d1c..df2160a 100644
--- a/libavcodec/rv30.c
+++ b/libavcodec/rv30.c
@@ -79,7 +79,7 @@
     for(i = 0; i < 4; i++, dst += r->intra_types_stride - 4){
         for(j = 0; j < 4; j+= 2){
             int code = svq3_get_ue_golomb(gb) << 1;
-            if(code >= 81U*2U){
+            if(code > 80U*2U){
                 av_log(r->s.avctx, AV_LOG_ERROR, "Incorrect intra prediction code\n");
                 return -1;
             }
diff --git a/libavcodec/rv34.c b/libavcodec/rv34.c
index 4ca134e..6527252 100644
--- a/libavcodec/rv34.c
+++ b/libavcodec/rv34.c
@@ -24,6 +24,7 @@
  * RV30/40 decoder common data
  */
 
+#include "libavutil/imgutils.h"
 #include "libavutil/internal.h"
 
 #include "avcodec.h"
@@ -1483,7 +1484,7 @@
     r->s.avctx = avctx;
     avctx->flags |= CODEC_FLAG_EMU_EDGE;
     r->s.flags |= CODEC_FLAG_EMU_EDGE;
-    avctx->pix_fmt = PIX_FMT_YUV420P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV420P;
     avctx->has_b_frames = 1;
     s->low_delay = 0;
 
@@ -1661,6 +1662,9 @@
             av_log(s->avctx, AV_LOG_WARNING, "Changing dimensions to %dx%d\n",
                    si.width, si.height);
 
+            if (av_image_check_size(si.width, si.height, 0, s->avctx))
+                return AVERROR_INVALIDDATA;
+
             s->width  = si.width;
             s->height = si.height;
             avcodec_set_dimensions(s->avctx, s->width, s->height);
diff --git a/libavcodec/rv34dsp.c b/libavcodec/rv34dsp.c
index ac14ed9..86a2ffd 100644
--- a/libavcodec/rv34dsp.c
+++ b/libavcodec/rv34dsp.c
@@ -135,8 +135,8 @@
     c->rv34_idct_add    = rv34_idct_add_c;
     c->rv34_idct_dc_add = rv34_idct_dc_add_c;
 
-    if (HAVE_NEON)
-        ff_rv34dsp_init_neon(c, dsp);
-    if (HAVE_MMX)
+    if (ARCH_ARM)
+        ff_rv34dsp_init_arm(c, dsp);
+    if (ARCH_X86)
         ff_rv34dsp_init_x86(c, dsp);
 }
diff --git a/libavcodec/rv34dsp.h b/libavcodec/rv34dsp.h
index 58da59f..f0263b1 100644
--- a/libavcodec/rv34dsp.h
+++ b/libavcodec/rv34dsp.h
@@ -77,10 +77,10 @@
 void ff_rv34dsp_init(RV34DSPContext *c, DSPContext* dsp);
 void ff_rv40dsp_init(RV34DSPContext *c, DSPContext* dsp);
 
-void ff_rv34dsp_init_neon(RV34DSPContext *c, DSPContext *dsp);
+void ff_rv34dsp_init_arm(RV34DSPContext *c, DSPContext *dsp);
 void ff_rv34dsp_init_x86(RV34DSPContext *c, DSPContext *dsp);
 
 void ff_rv40dsp_init_x86(RV34DSPContext *c, DSPContext *dsp);
-void ff_rv40dsp_init_neon(RV34DSPContext *c, DSPContext *dsp);
+void ff_rv40dsp_init_arm(RV34DSPContext *c, DSPContext *dsp);
 
 #endif /* AVCODEC_RV34DSP_H */
diff --git a/libavcodec/rv40dsp.c b/libavcodec/rv40dsp.c
index 66f5326..944a628 100644
--- a/libavcodec/rv40dsp.c
+++ b/libavcodec/rv40dsp.c
@@ -604,8 +604,8 @@
     c->rv40_loop_filter_strength[0] = rv40_h_loop_filter_strength;
     c->rv40_loop_filter_strength[1] = rv40_v_loop_filter_strength;
 
-    if (HAVE_MMX)
+    if (ARCH_X86)
         ff_rv40dsp_init_x86(c, dsp);
-    if (HAVE_NEON)
-        ff_rv40dsp_init_neon(c, dsp);
+    if (ARCH_ARM)
+        ff_rv40dsp_init_arm(c, dsp);
 }
diff --git a/libavcodec/s302m.c b/libavcodec/s302m.c
index 90406a9..5058ba0 100644
--- a/libavcodec/s302m.c
+++ b/libavcodec/s302m.c
@@ -20,9 +20,10 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#include "libavutil/common.h"
 #include "libavutil/intreadwrite.h"
+#include "libavutil/log.h"
 #include "avcodec.h"
+#include "mathops.h"
 
 #define AES3_HEADER_LEN 4
 
@@ -118,34 +119,34 @@
     if (avctx->bits_per_coded_sample == 24) {
         uint32_t *o = (uint32_t *)s->frame.data[0];
         for (; buf_size > 6; buf_size -= 7) {
-            *o++ = (av_reverse[buf[2]]        << 24) |
-                   (av_reverse[buf[1]]        << 16) |
-                   (av_reverse[buf[0]]        <<  8);
-            *o++ = (av_reverse[buf[6] & 0xf0] << 28) |
-                   (av_reverse[buf[5]]        << 20) |
-                   (av_reverse[buf[4]]        << 12) |
-                   (av_reverse[buf[3] & 0x0f] <<  4);
+            *o++ = (ff_reverse[buf[2]]        << 24) |
+                   (ff_reverse[buf[1]]        << 16) |
+                   (ff_reverse[buf[0]]        <<  8);
+            *o++ = (ff_reverse[buf[6] & 0xf0] << 28) |
+                   (ff_reverse[buf[5]]        << 20) |
+                   (ff_reverse[buf[4]]        << 12) |
+                   (ff_reverse[buf[3] & 0x0f] <<  4);
             buf += 7;
         }
     } else if (avctx->bits_per_coded_sample == 20) {
         uint32_t *o = (uint32_t *)s->frame.data[0];
         for (; buf_size > 5; buf_size -= 6) {
-            *o++ = (av_reverse[buf[2] & 0xf0] << 28) |
-                   (av_reverse[buf[1]]        << 20) |
-                   (av_reverse[buf[0]]        << 12);
-            *o++ = (av_reverse[buf[5] & 0xf0] << 28) |
-                   (av_reverse[buf[4]]        << 20) |
-                   (av_reverse[buf[3]]        << 12);
+            *o++ = (ff_reverse[buf[2] & 0xf0] << 28) |
+                   (ff_reverse[buf[1]]        << 20) |
+                   (ff_reverse[buf[0]]        << 12);
+            *o++ = (ff_reverse[buf[5] & 0xf0] << 28) |
+                   (ff_reverse[buf[4]]        << 20) |
+                   (ff_reverse[buf[3]]        << 12);
             buf += 6;
         }
     } else {
         uint16_t *o = (uint16_t *)s->frame.data[0];
         for (; buf_size > 4; buf_size -= 5) {
-            *o++ = (av_reverse[buf[1]]        <<  8) |
-                    av_reverse[buf[0]];
-            *o++ = (av_reverse[buf[4] & 0xf0] << 12) |
-                   (av_reverse[buf[3]]        <<  4) |
-                   (av_reverse[buf[2]]        >>  4);
+            *o++ = (ff_reverse[buf[1]]        <<  8) |
+                    ff_reverse[buf[0]];
+            *o++ = (ff_reverse[buf[4] & 0xf0] << 12) |
+                   (ff_reverse[buf[3]]        <<  4) |
+                   (ff_reverse[buf[2]]        >>  4);
             buf += 5;
         }
     }
diff --git a/libavcodec/sanm.c b/libavcodec/sanm.c
index 3736bd7..766ac68 100644
--- a/libavcodec/sanm.c
+++ b/libavcodec/sanm.c
@@ -261,7 +261,7 @@
     ctx->avctx     = avctx;
     ctx->version   = !avctx->extradata_size;
 
-    avctx->pix_fmt = ctx->version ? PIX_FMT_RGB565 : PIX_FMT_PAL8;
+    avctx->pix_fmt = ctx->version ? AV_PIX_FMT_RGB565 : AV_PIX_FMT_PAL8;
 
     init_sizes(ctx, avctx->width, avctx->height);
     if (init_buffers(ctx)) {
@@ -284,7 +284,7 @@
 
         ctx->subversion = AV_RL16(avctx->extradata);
         for (i = 0; i < 256; i++)
-            ctx->pal[i] = 0xFF << 24 | AV_RL32(avctx->extradata + 2 + i * 4);
+            ctx->pal[i] = 0xFFU << 24 | AV_RL32(avctx->extradata + 2 + i * 4);
     }
 
     return 0;
@@ -802,7 +802,7 @@
     uint16_t colors[2] = { fg_color, bg_color };
     int x, y;
 
-    if (index > NGLYPHS) {
+    if (index >= NGLYPHS) {
         av_log(ctx->avctx, AV_LOG_ERROR, "ignoring nonexistent glyph #%u\n", index);
         return AVERROR_INVALIDDATA;
     }
@@ -1172,7 +1172,7 @@
                     return AVERROR_INVALIDDATA;
                 }
                 for (i = 0; i < 256; i++)
-                    ctx->pal[i] = 0xFF << 24 | bytestream2_get_be24u(&ctx->gb);
+                    ctx->pal[i] = 0xFFU << 24 | bytestream2_get_be24u(&ctx->gb);
                 break;
             case MKBETAG('F', 'O', 'B', 'J'):
                 if (size < 16)
@@ -1190,7 +1190,7 @@
                             int t = (ctx->pal[i] >> (16 - j * 8)) & 0xFF;
                             tmp[j] = av_clip_uint8((t * 129 + ctx->delta_pal[i * 3 + j]) >> 7);
                         }
-                        ctx->pal[i] = 0xFF << 24 | AV_RB24(tmp);
+                        ctx->pal[i] = 0xFFU << 24 | AV_RB24(tmp);
                     }
                 } else {
                     if (size < 768 * 2 + 4) {
@@ -1203,7 +1203,7 @@
                         ctx->delta_pal[i] = bytestream2_get_le16u(&ctx->gb);
                     if (size >= 768 * 5 + 4) {
                         for (i = 0; i < 256; i++)
-                            ctx->pal[i] = 0xFF << 24 | bytestream2_get_be24u(&ctx->gb);
+                            ctx->pal[i] = 0xFFU << 24 | bytestream2_get_be24u(&ctx->gb);
                     } else {
                         memset(ctx->pal, 0, sizeof(ctx->pal));
                     }
diff --git a/libavcodec/sbr.h b/libavcodec/sbr.h
index e68b3cf..1e41396 100644
--- a/libavcodec/sbr.h
+++ b/libavcodec/sbr.h
@@ -37,7 +37,7 @@
 /**
  * Spectral Band Replication header - spectrum parameters that invoke a reset if they differ from the previous header.
  */
-typedef struct {
+typedef struct SpectrumParameters {
     uint8_t bs_start_freq;
     uint8_t bs_stop_freq;
     uint8_t bs_xover_band;
@@ -57,7 +57,7 @@
 /**
  * Spectral Band Replication per channel data
  */
-typedef struct {
+typedef struct SBRData {
     /**
      * @name Main bitstream data variables
      * @{
@@ -111,7 +111,7 @@
 /**
  * Spectral Band Replication
  */
-typedef struct {
+typedef struct SpectralBandReplication {
     int                sample_rate;
     int                start;
     int                reset;
@@ -153,7 +153,7 @@
     ///Frequency borders for noise floors
     uint16_t           f_tablenoise[6];
     ///Frequency borders for the limiter
-    uint16_t           f_tablelim[29];
+    uint16_t           f_tablelim[30];
     unsigned           num_patches;
     uint8_t            patch_num_subbands[6];
     uint8_t            patch_start_subband[6];
diff --git a/libavcodec/sbrdsp.c b/libavcodec/sbrdsp.c
index 8c88fb3..781ec83 100644
--- a/libavcodec/sbrdsp.c
+++ b/libavcodec/sbrdsp.c
@@ -243,6 +243,6 @@
 
     if (ARCH_ARM)
         ff_sbrdsp_init_arm(s);
-    if (HAVE_MMX)
+    if (ARCH_X86)
         ff_sbrdsp_init_x86(s);
 }
diff --git a/libavcodec/sgidec.c b/libavcodec/sgidec.c
index 370473a..bf6e572 100644
--- a/libavcodec/sgidec.c
+++ b/libavcodec/sgidec.c
@@ -192,11 +192,11 @@
     }
 
     if (s->depth == SGI_GRAYSCALE) {
-        avctx->pix_fmt = s->bytes_per_channel == 2 ? PIX_FMT_GRAY16BE : PIX_FMT_GRAY8;
+        avctx->pix_fmt = s->bytes_per_channel == 2 ? AV_PIX_FMT_GRAY16BE : AV_PIX_FMT_GRAY8;
     } else if (s->depth == SGI_RGB) {
-        avctx->pix_fmt = s->bytes_per_channel == 2 ? PIX_FMT_RGB48BE : PIX_FMT_RGB24;
+        avctx->pix_fmt = s->bytes_per_channel == 2 ? AV_PIX_FMT_RGB48BE : AV_PIX_FMT_RGB24;
     } else if (s->depth == SGI_RGBA) {
-        avctx->pix_fmt = s->bytes_per_channel == 2 ? PIX_FMT_RGBA64BE : PIX_FMT_RGBA;
+        avctx->pix_fmt = s->bytes_per_channel == 2 ? AV_PIX_FMT_RGBA64BE : AV_PIX_FMT_RGBA;
     } else {
         av_log(avctx, AV_LOG_ERROR, "wrong picture format\n");
         return -1;
@@ -267,6 +267,6 @@
     .init           = sgi_init,
     .close          = sgi_end,
     .decode         = decode_frame,
-    .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("SGI image"),
+    .capabilities   = CODEC_CAP_DR1,
 };
diff --git a/libavcodec/sgienc.c b/libavcodec/sgienc.c
index 77b471b..d03ef52 100644
--- a/libavcodec/sgienc.c
+++ b/libavcodec/sgienc.c
@@ -68,39 +68,39 @@
     put_be = HAVE_BIGENDIAN;
 
     switch (avctx->pix_fmt) {
-    case PIX_FMT_GRAY8:
+    case AV_PIX_FMT_GRAY8:
         dimension = SGI_SINGLE_CHAN;
         depth     = SGI_GRAYSCALE;
         break;
-    case PIX_FMT_RGB24:
+    case AV_PIX_FMT_RGB24:
         dimension = SGI_MULTI_CHAN;
         depth     = SGI_RGB;
         break;
-    case PIX_FMT_RGBA:
+    case AV_PIX_FMT_RGBA:
         dimension = SGI_MULTI_CHAN;
         depth     = SGI_RGBA;
         break;
-    case PIX_FMT_GRAY16LE:
+    case AV_PIX_FMT_GRAY16LE:
         put_be = !HAVE_BIGENDIAN;
-    case PIX_FMT_GRAY16BE:
+    case AV_PIX_FMT_GRAY16BE:
         avctx->coder_type = FF_CODER_TYPE_RAW;
         bytes_per_channel = 2;
         pixmax = 0xFFFF;
         dimension = SGI_SINGLE_CHAN;
         depth     = SGI_GRAYSCALE;
         break;
-    case PIX_FMT_RGB48LE:
+    case AV_PIX_FMT_RGB48LE:
         put_be = !HAVE_BIGENDIAN;
-    case PIX_FMT_RGB48BE:
+    case AV_PIX_FMT_RGB48BE:
         avctx->coder_type = FF_CODER_TYPE_RAW;
         bytes_per_channel = 2;
         pixmax = 0xFFFF;
         dimension = SGI_MULTI_CHAN;
         depth     = SGI_RGB;
         break;
-    case PIX_FMT_RGBA64LE:
+    case AV_PIX_FMT_RGBA64LE:
         put_be = !HAVE_BIGENDIAN;
-    case PIX_FMT_RGBA64BE:
+    case AV_PIX_FMT_RGBA64BE:
         avctx->coder_type = FF_CODER_TYPE_RAW;
         bytes_per_channel = 2;
         pixmax = 0xFFFF;
@@ -217,12 +217,12 @@
     .priv_data_size = sizeof(SgiContext),
     .init           = encode_init,
     .encode2        = encode_frame,
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_RGB24, PIX_FMT_RGBA,
-        PIX_FMT_RGB48LE, PIX_FMT_RGB48BE,
-        PIX_FMT_RGBA64LE, PIX_FMT_RGBA64BE,
-        PIX_FMT_GRAY16LE, PIX_FMT_GRAY16BE,
-        PIX_FMT_GRAY8, PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA,
+        AV_PIX_FMT_RGB48LE, AV_PIX_FMT_RGB48BE,
+        AV_PIX_FMT_RGBA64LE, AV_PIX_FMT_RGBA64BE,
+        AV_PIX_FMT_GRAY16LE, AV_PIX_FMT_GRAY16BE,
+        AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("SGI image"),
 };
diff --git a/libavcodec/sh4/qpel.c b/libavcodec/sh4/qpel.c
index 2e30ae1..5ad0290 100644
--- a/libavcodec/sh4/qpel.c
+++ b/libavcodec/sh4/qpel.c
@@ -21,6 +21,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/common.h"
+
 #define PIXOP2(OPNAME, OP) \
 \
 static inline void OPNAME ## _pixels4_l2_aligned(uint8_t *dst, const uint8_t *src1, const uint8_t *src2, int dst_stride, int src_stride1, int src_stride2, int h) \
diff --git a/libavcodec/shorten.c b/libavcodec/shorten.c
index d04011e..da5a2b4 100644
--- a/libavcodec/shorten.c
+++ b/libavcodec/shorten.c
@@ -132,11 +132,11 @@
     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");
-            return -1;
+            return AVERROR_INVALIDDATA;
         }
         if(s->blocksize + s->nwrap >= UINT_MAX/sizeof(int32_t) || s->blocksize + s->nwrap <= (unsigned)s->nwrap){
             av_log(s->avctx, AV_LOG_ERROR, "s->blocksize + s->nwrap too large\n");
-            return -1;
+            return AVERROR_INVALIDDATA;
         }
 
         tmp_ptr = av_realloc(s->offset[chan], sizeof(int32_t)*FFMAX(1, s->nmean));
@@ -190,16 +190,16 @@
     switch (s->internal_ftype)
     {
         case TYPE_U8:
-            s->avctx->sample_fmt = AV_SAMPLE_FMT_U8;
+            s->avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
             mean = 0x80;
             break;
         case TYPE_S16HL:
         case TYPE_S16LH:
-            s->avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+            s->avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
             break;
         default:
             av_log(s->avctx, AV_LOG_ERROR, "unknown audio type\n");
-            return AVERROR_INVALIDDATA;
+            return AVERROR_PATCHWELCOME;
     }
 
     for (chan = 0; chan < s->channels; chan++)
@@ -217,14 +217,14 @@
 
     if (bytestream_get_le32(&header) != MKTAG('R','I','F','F')) {
         av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     header += 4; /* chunk size */;
 
     if (bytestream_get_le32(&header) != MKTAG('W','A','V','E')) {
         av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     while (bytestream_get_le32(&header) != MKTAG('f','m','t',' ')) {
@@ -237,7 +237,7 @@
 
     if (len < 16) {
         av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     wave_format = bytestream_get_le16(&header);
@@ -247,7 +247,7 @@
             break;
         default:
             av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
-            return -1;
+            return AVERROR_PATCHWELCOME;
     }
 
     header += 2;        // skip channels    (already got from shorten header)
@@ -259,7 +259,7 @@
 
     if (bps != 16 && bps != 8) {
         av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample: %d\n", bps);
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     len -= 16;
@@ -330,7 +330,7 @@
     /* shorten signature */
     if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
         av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     s->lpcqoffset = 0;
@@ -340,9 +340,9 @@
     s->internal_ftype = get_uint(s, TYPESIZE);
 
     s->channels = get_uint(s, CHANSIZE);
-    if (s->channels > MAX_CHANNELS) {
+    if (s->channels <= 0 || s->channels > MAX_CHANNELS) {
         av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
     s->avctx->channels = s->channels;
 
@@ -379,20 +379,20 @@
 
     if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
         av_log(s->avctx, AV_LOG_ERROR, "missing verbatim section at beginning of stream\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
     if (s->header_size >= OUT_BUFFER_SIZE || s->header_size < CANONICAL_HEADER_SIZE) {
         av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n", s->header_size);
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     for (i=0; i<s->header_size; i++)
         s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
 
-    if (decode_wave_header(s->avctx, s->header, s->header_size) < 0)
-        return -1;
+    if ((ret = decode_wave_header(s->avctx, s->header, s->header_size)) < 0)
+        return ret;
 
     s->cur_chan = 0;
     s->bitshift = 0;
@@ -587,11 +587,11 @@
                     av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
                     return ret;
                 }
-                samples_u8  = (uint8_t *)s->frame.data[0];
-                samples_s16 = (int16_t *)s->frame.data[0];
-                /* interleave output */
-                for (i = 0; i < s->blocksize; i++) {
-                    for (chan = 0; chan < s->channels; chan++) {
+
+                for (chan = 0; chan < s->channels; chan++) {
+                    samples_u8  = ((uint8_t **)s->frame.extended_data)[chan];
+                    samples_s16 = ((int16_t **)s->frame.extended_data)[chan];
+                    for (i = 0; i < s->blocksize; i++) {
                         switch (s->internal_ftype) {
                         case TYPE_U8:
                             *samples_u8++ = av_clip_uint8(s->decoded[chan][i]);
@@ -604,6 +604,7 @@
                     }
                 }
 
+
                 *got_frame_ptr   = 1;
                 *(AVFrame *)data = s->frame;
             }
@@ -619,7 +620,7 @@
         av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
         s->bitstream_size=0;
         s->bitstream_index=0;
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
     if (s->bitstream_size) {
         s->bitstream_index += i;
@@ -655,4 +656,7 @@
     .decode         = shorten_decode_frame,
     .capabilities   = CODEC_CAP_DELAY | CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("Shorten"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
+                                                      AV_SAMPLE_FMT_U8P,
+                                                      AV_SAMPLE_FMT_NONE },
 };
diff --git a/libavcodec/sipr.c b/libavcodec/sipr.c
index fc03259..d8bfdd2 100644
--- a/libavcodec/sipr.c
+++ b/libavcodec/sipr.c
@@ -25,6 +25,7 @@
 #include <stdint.h>
 #include <string.h>
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/mathematics.h"
 #include "avcodec.h"
 #define BITSTREAM_READER_LE
@@ -509,7 +510,9 @@
     for (i = 0; i < 4; i++)
         ctx->energy_history[i] = -14;
 
-    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
+    avctx->channels       = 1;
+    avctx->channel_layout = AV_CH_LAYOUT_MONO;
+    avctx->sample_fmt     = AV_SAMPLE_FMT_FLT;
 
     avcodec_get_frame_defaults(&ctx->frame);
     avctx->coded_frame = &ctx->frame;
diff --git a/libavcodec/smacker.c b/libavcodec/smacker.c
index e02c76c..e1e67da 100644
--- a/libavcodec/smacker.c
+++ b/libavcodec/smacker.c
@@ -31,8 +31,8 @@
 #include <stdio.h>
 #include <stdlib.h>
 
+#include "libavutil/channel_layout.h"
 #include "avcodec.h"
-#include "libavutil/audioconvert.h"
 #include "mathops.h"
 
 #define BITSTREAM_READER_LE
@@ -96,14 +96,14 @@
  */
 static int smacker_decode_tree(GetBitContext *gb, HuffContext *hc, uint32_t prefix, int length)
 {
-    if(length > 32) {
+    if(length > 32 || length > 3*SMKTREE_BITS) {
         av_log(NULL, AV_LOG_ERROR, "length too long\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
     if(!get_bits1(gb)){ //Leaf
         if(hc->current >= 256){
             av_log(NULL, AV_LOG_ERROR, "Tree size exceeded!\n");
-            return -1;
+            return AVERROR_INVALIDDATA;
         }
         if(length){
             hc->bits[hc->current] = prefix;
@@ -134,14 +134,14 @@
 {
     if (hc->current + 1 >= hc->length) {
         av_log(NULL, AV_LOG_ERROR, "Tree size exceeded!\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
     if(!get_bits1(gb)){ //Leaf
         int val, i1, i2;
         i1 = ctx->v1->table ? get_vlc2(gb, ctx->v1->table, SMKTREE_BITS, 3) : 0;
         i2 = ctx->v2->table ? get_vlc2(gb, ctx->v2->table, SMKTREE_BITS, 3) : 0;
         if (i1 < 0 || i2 < 0)
-            return -1;
+            return AVERROR_INVALIDDATA;
         val = ctx->recode1[i1] | (ctx->recode2[i2] << 8);
         if(val == ctx->escapes[0]) {
             ctx->last[0] = hc->current;
@@ -187,7 +187,7 @@
 
     if(size >= UINT_MAX>>4){ // (((size + 3) >> 2) + 3) << 2 must not overflow
         av_log(smk->avctx, AV_LOG_ERROR, "size too large\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     tmp1.length = 256;
@@ -205,29 +205,39 @@
     tmp2.values = av_mallocz(256 * sizeof(int));
 
     if(get_bits1(gb)) {
-        smacker_decode_tree(gb, &tmp1, 0, 0);
+        res = smacker_decode_tree(gb, &tmp1, 0, 0);
+        if (res < 0)
+            return res;
         skip_bits1(gb);
-        res = init_vlc(&vlc[0], SMKTREE_BITS, tmp1.length,
-                    tmp1.lengths, sizeof(int), sizeof(int),
-                    tmp1.bits, sizeof(uint32_t), sizeof(uint32_t), INIT_VLC_LE);
-        if(res < 0) {
-            av_log(smk->avctx, AV_LOG_ERROR, "Cannot build VLC table\n");
-            return -1;
+        if(tmp1.current > 1) {
+            res = init_vlc(&vlc[0], SMKTREE_BITS, tmp1.length,
+                        tmp1.lengths, sizeof(int), sizeof(int),
+                        tmp1.bits, sizeof(uint32_t), sizeof(uint32_t), INIT_VLC_LE);
+            if(res < 0) {
+                av_log(smk->avctx, AV_LOG_ERROR, "Cannot build VLC table\n");
+                return AVERROR_INVALIDDATA;
+            }
         }
-    } else {
+    }
+    if (!vlc[0].table) {
         av_log(smk->avctx, AV_LOG_ERROR, "Skipping low bytes tree\n");
     }
     if(get_bits1(gb)){
-        smacker_decode_tree(gb, &tmp2, 0, 0);
+        res = smacker_decode_tree(gb, &tmp2, 0, 0);
+        if (res < 0)
+            return res;
         skip_bits1(gb);
-        res = init_vlc(&vlc[1], SMKTREE_BITS, tmp2.length,
-                    tmp2.lengths, sizeof(int), sizeof(int),
-                    tmp2.bits, sizeof(uint32_t), sizeof(uint32_t), INIT_VLC_LE);
-        if(res < 0) {
-            av_log(smk->avctx, AV_LOG_ERROR, "Cannot build VLC table\n");
-            return -1;
+        if(tmp2.current > 1) {
+            res = init_vlc(&vlc[1], SMKTREE_BITS, tmp2.length,
+                        tmp2.lengths, sizeof(int), sizeof(int),
+                        tmp2.bits, sizeof(uint32_t), sizeof(uint32_t), INIT_VLC_LE);
+            if(res < 0) {
+                av_log(smk->avctx, AV_LOG_ERROR, "Cannot build VLC table\n");
+                return AVERROR_INVALIDDATA;
+            }
         }
-    } else {
+    }
+    if (!vlc[1].table) {
         av_log(smk->avctx, AV_LOG_ERROR, "Skipping high bytes tree\n");
     }
 
@@ -260,7 +270,7 @@
     if(huff.current > huff.length){
         ctx.last[0] = ctx.last[1] = ctx.last[2] = 1;
         av_log(smk->avctx, AV_LOG_ERROR, "bigtree damaged\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     *recodes = huff.values;
@@ -297,7 +307,7 @@
         smk->mmap_last[0] = smk->mmap_last[1] = smk->mmap_last[2] = 1;
     } else {
         if (smacker_decode_header_tree(smk, &gb, &smk->mmap_tbl, smk->mmap_last, mmap_size))
-            return -1;
+            return AVERROR_INVALIDDATA;
     }
     if(!get_bits1(&gb)) {
         av_log(smk->avctx, AV_LOG_INFO, "Skipping MCLR tree\n");
@@ -306,7 +316,7 @@
         smk->mclr_last[0] = smk->mclr_last[1] = smk->mclr_last[2] = 1;
     } else {
         if (smacker_decode_header_tree(smk, &gb, &smk->mclr_tbl, smk->mclr_last, mclr_size))
-            return -1;
+            return AVERROR_INVALIDDATA;
     }
     if(!get_bits1(&gb)) {
         av_log(smk->avctx, AV_LOG_INFO, "Skipping FULL tree\n");
@@ -315,7 +325,7 @@
         smk->full_last[0] = smk->full_last[1] = smk->full_last[2] = 1;
     } else {
         if (smacker_decode_header_tree(smk, &gb, &smk->full_tbl, smk->full_last, full_size))
-            return -1;
+            return AVERROR_INVALIDDATA;
     }
     if(!get_bits1(&gb)) {
         av_log(smk->avctx, AV_LOG_INFO, "Skipping TYPE tree\n");
@@ -324,7 +334,7 @@
         smk->type_last[0] = smk->type_last[1] = smk->type_last[2] = 1;
     } else {
         if (smacker_decode_header_tree(smk, &gb, &smk->type_tbl, smk->type_last, type_size))
-            return -1;
+            return AVERROR_INVALIDDATA;
     }
 
     return 0;
@@ -362,18 +372,18 @@
     GetByteContext gb2;
     GetBitContext gb;
     int blocks, blk, bw, bh;
-    int i;
+    int i, ret;
     int stride;
     int flags;
 
     if (avpkt->size <= 769)
-        return 0;
+        return AVERROR_INVALIDDATA;
 
     smk->pic.reference = 3;
     smk->pic.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;
-    if(avctx->reget_buffer(avctx, &smk->pic) < 0){
+    if((ret = avctx->reget_buffer(avctx, &smk->pic)) < 0){
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
+        return ret;
     }
 
     /* make the palette available on the way out */
@@ -388,7 +398,7 @@
         smk->pic.pict_type = AV_PICTURE_TYPE_P;
 
     for(i = 0; i < 256; i++)
-        *pal++ = 0xFF << 24 | bytestream2_get_be24u(&gb2);
+        *pal++ = 0xFFU << 24 | bytestream2_get_be24u(&gb2);
 
     last_reset(smk->mmap_tbl, smk->mmap_last);
     last_reset(smk->mclr_tbl, smk->mclr_last);
@@ -521,18 +531,18 @@
 
     c->avctx = avctx;
 
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     avcodec_get_frame_defaults(&c->pic);
 
     /* decode huffman trees from extradata */
     if(avctx->extradata_size < 16){
         av_log(avctx, AV_LOG_ERROR, "Extradata missing!\n");
-        return -1;
+        return AVERROR(EINVAL);
     }
 
     if (decode_header_trees(c))
-        return -1;
+        return AVERROR_INVALIDDATA;
 
     return 0;
 }
@@ -608,6 +618,11 @@
 
     unp_size = AV_RL32(buf);
 
+    if (unp_size > (1U<<24)) {
+        av_log(avctx, AV_LOG_ERROR, "packet is too big\n");
+        return AVERROR_INVALIDDATA;
+    }
+
     init_get_bits(&gb, buf + 4, (buf_size - 4) * 8);
 
     if(!get_bits1(&gb)){
@@ -644,7 +659,9 @@
         h[i].lengths = av_mallocz(256 * sizeof(int));
         h[i].values = av_mallocz(256 * sizeof(int));
         skip_bits1(&gb);
-        smacker_decode_tree(&gb, &h[i], 0, 0);
+        res = smacker_decode_tree(&gb, &h[i], 0, 0);
+        if (res < 0)
+            return res;
         skip_bits1(&gb);
         if(h[i].current > 1) {
             res = init_vlc(&vlc[i], SMKTREE_BITS, h[i].length,
@@ -652,7 +669,7 @@
                     h[i].bits, sizeof(uint32_t), sizeof(uint32_t), INIT_VLC_LE);
             if(res < 0) {
                 av_log(avctx, AV_LOG_ERROR, "Cannot build VLC table\n");
-                return -1;
+                return AVERROR_INVALIDDATA;
             }
         }
     }
@@ -663,7 +680,7 @@
             *samples++ = pred[i];
         for(; i < unp_size / 2; i++) {
             if(get_bits_left(&gb)<0)
-                return -1;
+                return AVERROR_INVALIDDATA;
             if(i & stereo) {
                 if(vlc[2].table)
                     res = get_vlc2(&gb, vlc[2].table, SMKTREE_BITS, 3);
@@ -715,7 +732,7 @@
             *samples8++ = pred[i];
         for(; i < unp_size; i++) {
             if(get_bits_left(&gb)<0)
-                return -1;
+                return AVERROR_INVALIDDATA;
             if(i & stereo){
                 if(vlc[1].table)
                     res = get_vlc2(&gb, vlc[1].table, SMKTREE_BITS, 3);
diff --git a/libavcodec/smc.c b/libavcodec/smc.c
index 37b7409..402c804 100644
--- a/libavcodec/smc.c
+++ b/libavcodec/smc.c
@@ -414,7 +414,7 @@
     SmcContext *s = avctx->priv_data;
 
     s->avctx = avctx;
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     avcodec_get_frame_defaults(&s->frame);
     s->frame.data[0] = NULL;
diff --git a/libavcodec/snow.c b/libavcodec/snow.c
index a4fe8b6..2f3ddbe 100644
--- a/libavcodec/snow.c
+++ b/libavcodec/snow.c
@@ -343,8 +343,8 @@
         sx += (mx>>4) - (HTAPS_MAX/2-1);
         sy += (my>>4) - (HTAPS_MAX/2-1);
         src += sx + sy*stride;
-        if(   (unsigned)sx >= w - b_w - (HTAPS_MAX-2)
-           || (unsigned)sy >= h - b_h - (HTAPS_MAX-2)){
+        if(   (unsigned)sx >= FFMAX(w - b_w - (HTAPS_MAX-2), 0)
+           || (unsigned)sy >= FFMAX(h - b_h - (HTAPS_MAX-2), 0)){
             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;
         }
diff --git a/libavcodec/snowdec.c b/libavcodec/snowdec.c
index 22d4f92..f377409 100644
--- a/libavcodec/snowdec.c
+++ b/libavcodec/snowdec.c
@@ -292,15 +292,15 @@
         s->chroma_v_shift= get_symbol(&s->c, s->header_state, 0);
 
         if(s->chroma_h_shift == 1 && s->chroma_v_shift==1){
-            s->avctx->pix_fmt= PIX_FMT_YUV420P;
+            s->avctx->pix_fmt= AV_PIX_FMT_YUV420P;
         }else if(s->chroma_h_shift == 0 && s->chroma_v_shift==0){
-            s->avctx->pix_fmt= PIX_FMT_YUV444P;
+            s->avctx->pix_fmt= AV_PIX_FMT_YUV444P;
         }else if(s->chroma_h_shift == 2 && s->chroma_v_shift==2){
-            s->avctx->pix_fmt= PIX_FMT_YUV410P;
+            s->avctx->pix_fmt= AV_PIX_FMT_YUV410P;
         } else {
             av_log(s, AV_LOG_ERROR, "unsupported color subsample mode %d %d\n", s->chroma_h_shift, s->chroma_v_shift);
             s->chroma_h_shift = s->chroma_v_shift = 1;
-            s->avctx->pix_fmt= PIX_FMT_YUV420P;
+            s->avctx->pix_fmt= AV_PIX_FMT_YUV420P;
             return AVERROR_INVALIDDATA;
         }
 
diff --git a/libavcodec/snowenc.c b/libavcodec/snowenc.c
index b1377ca..23d8d81 100644
--- a/libavcodec/snowenc.c
+++ b/libavcodec/snowenc.c
@@ -218,15 +218,15 @@
 
     avctx->coded_frame= &s->current_picture;
     switch(avctx->pix_fmt){
-    case PIX_FMT_YUV444P:
-//    case PIX_FMT_YUV422P:
-    case PIX_FMT_YUV420P:
-//     case PIX_FMT_GRAY8:
-//    case PIX_FMT_YUV411P:
-    case PIX_FMT_YUV410P:
+    case AV_PIX_FMT_YUV444P:
+//    case AV_PIX_FMT_YUV422P:
+    case AV_PIX_FMT_YUV420P:
+//     case AV_PIX_FMT_GRAY8:
+//    case AV_PIX_FMT_YUV411P:
+    case AV_PIX_FMT_YUV410P:
         s->colorspace_type= 0;
         break;
-/*    case PIX_FMT_RGB32:
+/*    case AV_PIX_FMT_RGB32:
         s->colorspace= 1;
         break;*/
     default:
@@ -626,7 +626,7 @@
     }
     *b= backup;
 
-    return av_clip(((ab<<LOG2_OBMC_MAX) + aa/2)/aa, 0, 255); //FIXME we should not need clipping
+    return av_clip( ROUNDED_DIV(ab<<LOG2_OBMC_MAX, aa), 0, 255); //FIXME we should not need clipping
 }
 
 static inline int get_block_bits(SnowContext *s, int x, int y, int w){
@@ -1946,9 +1946,9 @@
     .init           = encode_init,
     .encode2        = encode_frame,
     .close          = encode_end,
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_YUV420P, PIX_FMT_YUV410P, PIX_FMT_YUV444P,
-        PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV444P,
+        AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("Snow"),
     .priv_class     = &snowenc_class,
@@ -1964,8 +1964,8 @@
 #include "libavutil/mathematics.h"
 
 int main(void){
-    int width=256;
-    int height=256;
+#define width  256
+#define height 256
     int buffer[2][width*height];
     SnowContext s;
     int i;
diff --git a/libavcodec/srtdec.c b/libavcodec/srtdec.c
index 5824091..ddeabd2 100644
--- a/libavcodec/srtdec.c
+++ b/libavcodec/srtdec.c
@@ -21,6 +21,7 @@
 
 #include "libavutil/avstring.h"
 #include "libavutil/common.h"
+#include "libavutil/intreadwrite.h"
 #include "libavutil/parseutils.h"
 #include "avcodec.h"
 #include "ass.h"
@@ -219,6 +220,15 @@
     char buffer[2048];
     const char *ptr = avpkt->data;
     const char *end = avpkt->data + avpkt->size;
+    int size;
+    const uint8_t *p = av_packet_get_side_data(avpkt, AV_PKT_DATA_SUBTITLE_POSITION, &size);
+
+    if (p && size == 16) {
+        x1 = AV_RL32(p     );
+        y1 = AV_RL32(p +  4);
+        x2 = AV_RL32(p +  8);
+        y2 = AV_RL32(p + 12);
+    }
 
     if (avpkt->size <= 0)
         return avpkt->size;
@@ -247,6 +257,7 @@
 }
 
 #if CONFIG_SRT_DECODER
+/* deprecated decoder */
 AVCodec ff_srt_decoder = {
     .name         = "srt",
     .long_name    = NULL_IF_CONFIG_SMALL("SubRip subtitle with embedded timing"),
diff --git a/libavcodec/srtenc.c b/libavcodec/srtenc.c
index 473c88f..56f29e9 100644
--- a/libavcodec/srtenc.c
+++ b/libavcodec/srtenc.c
@@ -203,6 +203,8 @@
                         int t1, int t2)
 {
     SRTContext *s = priv;
+
+    if (s->avctx->codec->id == CODEC_ID_SRT) {
     char buffer[32];
     int len = snprintf(buffer, sizeof(buffer),
                        "  X1:%03u X2:%03u Y1:%03u Y2:%03u", x1, x2, y1, y2);
@@ -211,6 +213,7 @@
         memcpy(s->dialog_start, buffer, len);
         s->ptr += len;
     }
+    }
 }
 
 static void srt_end_cb(void *priv)
@@ -262,9 +265,9 @@
                 es = ec/   1000;  ec -=    1000*es;
                 srt_print(s,"%d\r\n%02d:%02d:%02d,%03d --> %02d:%02d:%02d,%03d\r\n",
                           ++s->count, sh, sm, ss, sc, eh, em, es, ec);
+                s->dialog_start = s->ptr - 2;
             }
             s->alignment_applied = 0;
-            s->dialog_start = s->ptr - 2;
             srt_style_apply(s, dialog->style);
             ff_ass_split_override_codes(&srt_callbacks, s, dialog->text);
         }
diff --git a/libavcodec/sunrast.c b/libavcodec/sunrast.c
index 7724f0f..eb245da 100644
--- a/libavcodec/sunrast.c
+++ b/libavcodec/sunrast.c
@@ -94,19 +94,19 @@
 
     switch (depth) {
         case 1:
-            avctx->pix_fmt = maplength ? PIX_FMT_PAL8 : PIX_FMT_MONOWHITE;
+            avctx->pix_fmt = maplength ? AV_PIX_FMT_PAL8 : AV_PIX_FMT_MONOWHITE;
             break;
         case 4:
-            avctx->pix_fmt = maplength ? PIX_FMT_PAL8 : PIX_FMT_NONE;
+            avctx->pix_fmt = maplength ? AV_PIX_FMT_PAL8 : AV_PIX_FMT_NONE;
             break;
         case 8:
-            avctx->pix_fmt = maplength ? PIX_FMT_PAL8 : PIX_FMT_GRAY8;
+            avctx->pix_fmt = maplength ? AV_PIX_FMT_PAL8 : AV_PIX_FMT_GRAY8;
             break;
         case 24:
-            avctx->pix_fmt = (type == RT_FORMAT_RGB) ? PIX_FMT_RGB24 : PIX_FMT_BGR24;
+            avctx->pix_fmt = (type == RT_FORMAT_RGB) ? AV_PIX_FMT_RGB24 : AV_PIX_FMT_BGR24;
             break;
         case 32:
-            avctx->pix_fmt = (type == RT_FORMAT_RGB) ? PIX_FMT_0RGB : PIX_FMT_0BGR;
+            avctx->pix_fmt = (type == RT_FORMAT_RGB) ? AV_PIX_FMT_0RGB : AV_PIX_FMT_0BGR;
             break;
         default:
             av_log(avctx, AV_LOG_ERROR, "invalid depth\n");
@@ -141,7 +141,7 @@
 
         ptr = p->data[1];
         for (x = 0; x < len; x++, ptr += 4)
-            *(uint32_t *)ptr = (0xFF<<24) + (buf[x]<<16) + (buf[len+x]<<8) + buf[len+len+x];
+            *(uint32_t *)ptr = (0xFFU<<24) + (buf[x]<<16) + (buf[len+x]<<8) + buf[len+len+x];
     }
 
     buf += maplength;
@@ -195,7 +195,7 @@
             buf += alen;
         }
     }
-    if (avctx->pix_fmt == PIX_FMT_PAL8 && depth < 8) {
+    if (avctx->pix_fmt == AV_PIX_FMT_PAL8 && depth < 8) {
         uint8_t *ptr_free = ptr2;
         ptr = p->data[0];
         for (y=0; y<h; y++) {
diff --git a/libavcodec/sunrastenc.c b/libavcodec/sunrastenc.c
index e8caa25..2c7e72f 100644
--- a/libavcodec/sunrastenc.c
+++ b/libavcodec/sunrastenc.c
@@ -156,16 +156,16 @@
     s->maplength                  = 0;
 
     switch (avctx->pix_fmt) {
-    case PIX_FMT_MONOWHITE:
+    case AV_PIX_FMT_MONOWHITE:
         s->depth = 1;
         break;
-    case PIX_FMT_PAL8 :
+    case AV_PIX_FMT_PAL8 :
         s->maptype   = RMT_EQUAL_RGB;
         s->maplength = 3 * 256;
-    case PIX_FMT_GRAY8:
+    case AV_PIX_FMT_GRAY8:
         s->depth = 8;
         break;
-    case PIX_FMT_BGR24:
+    case AV_PIX_FMT_BGR24:
         s->depth = 24;
         break;
     default:
@@ -215,10 +215,10 @@
     .init           = sunrast_encode_init,
     .encode2        = sunrast_encode_frame,
     .defaults       = sunrast_defaults,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_BGR24,
-                                                  PIX_FMT_PAL8,
-                                                  PIX_FMT_GRAY8,
-                                                  PIX_FMT_MONOWHITE,
-                                                  PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_BGR24,
+                                                  AV_PIX_FMT_PAL8,
+                                                  AV_PIX_FMT_GRAY8,
+                                                  AV_PIX_FMT_MONOWHITE,
+                                                  AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("Sun Rasterfile image"),
 };
diff --git a/libavcodec/svq1.c b/libavcodec/svq1.c
index d0e1132..0c19a6d 100644
--- a/libavcodec/svq1.c
+++ b/libavcodec/svq1.c
@@ -38,6 +38,6 @@
 
 /* standard video sizes */
 const struct svq1_frame_size ff_svq1_frame_size_table[7] = {
-  { 160, 120 }, { 128,  96 }, { 176, 144 }, { 352, 288 },
-  { 704, 576 }, { 240, 180 }, { 320, 240 }
+    { 160, 120 }, { 128,  96 }, { 176, 144 }, { 352, 288 },
+    { 704, 576 }, { 240, 180 }, { 320, 240 }
 };
diff --git a/libavcodec/svq1.h b/libavcodec/svq1.h
index 3ade05d..9b132e2 100644
--- a/libavcodec/svq1.h
+++ b/libavcodec/svq1.h
@@ -47,11 +47,11 @@
     uint16_t height;
 };
 
-uint16_t ff_svq1_packet_checksum (const uint8_t *data, const int length,
-                                  int value);
+uint16_t ff_svq1_packet_checksum(const uint8_t *data,
+                                 const int length, int value);
 
-extern const int8_t* const ff_svq1_inter_codebooks[6];
-extern const int8_t* const ff_svq1_intra_codebooks[6];
+extern const int8_t *const ff_svq1_inter_codebooks[6];
+extern const int8_t *const ff_svq1_intra_codebooks[6];
 
 extern const uint8_t ff_svq1_block_type_vlc[4][2];
 extern const uint8_t ff_svq1_intra_multistage_vlc[6][8][2];
diff --git a/libavcodec/svq13.c b/libavcodec/svq13.c
index 65a7902..b821a44 100644
--- a/libavcodec/svq13.c
+++ b/libavcodec/svq13.c
@@ -23,46 +23,47 @@
 #include "svq1.h"
 
 static const uint16_t checksum_table[256] = {
-  0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
-  0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
-  0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
-  0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
-  0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
-  0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
-  0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
-  0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
-  0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
-  0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
-  0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
-  0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
-  0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
-  0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
-  0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
-  0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
-  0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
-  0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
-  0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
-  0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
-  0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
-  0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
-  0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
-  0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
-  0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
-  0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
-  0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
-  0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
-  0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
-  0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
-  0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
-  0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0
+    0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
+    0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
+    0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
+    0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
+    0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
+    0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
+    0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
+    0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
+    0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
+    0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
+    0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
+    0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
+    0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
+    0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
+    0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
+    0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
+    0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
+    0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
+    0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
+    0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
+    0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
+    0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
+    0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
+    0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
+    0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
+    0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
+    0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
+    0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
+    0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
+    0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
+    0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
+    0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0
 };
 
-uint16_t ff_svq1_packet_checksum (const uint8_t *data, const int length, int value) {
-  int i;
+uint16_t ff_svq1_packet_checksum (const uint8_t *data,
+                                  const int length, int value)
+{
+    int i;
 
-  for (i=0; i < length; i++) {
-    value = checksum_table[data[i] ^ (value >> 8)] ^ ((value & 0xFF) << 8);
-  }
+    for (i = 0; i < length; i++)
+        value = checksum_table[data[i] ^ (value >> 8)] ^ ((value & 0xFF) << 8);
 
-  return value;
+    return value;
 }
diff --git a/libavcodec/svq1_vlc.h b/libavcodec/svq1_vlc.h
index 272597e..e56d894 100644
--- a/libavcodec/svq1_vlc.h
+++ b/libavcodec/svq1_vlc.h
@@ -25,131 +25,116 @@
 
 /* values in this table range from 0..3; adjust retrieved value by +0 */
 const uint8_t ff_svq1_block_type_vlc[4][2] = {
- /* { code, length } */
+    /* { code, length } */
     { 0x1, 1 },  { 0x1, 2 },  { 0x1, 3 },  { 0x0, 3 }
-
 };
 
 /* values in this table range from -1..6; adjust retrieved value by -1 */
 const uint8_t ff_svq1_intra_multistage_vlc[6][8][2] = {
- /* { code, length } */
-{
-    { 0x1, 5 },  { 0x1, 1 },  { 0x3, 3 },  { 0x2, 3 },
-    { 0x3, 4 },  { 0x2, 4 },  { 0x0, 5 },  { 0x1, 4 }
-},{
-    { 0x1, 4 },  { 0x3, 2 },  { 0x5, 3 },  { 0x4, 3 },
-    { 0x3, 3 },  { 0x2, 3 },  { 0x0, 4 },  { 0x1, 3 }
-},{
-    { 0x1, 5 },  { 0x1, 1 },  { 0x3, 3 },  { 0x0, 5 },
-    { 0x3, 4 },  { 0x2, 3 },  { 0x2, 4 },  { 0x1, 4 }
-},{
-    { 0x1, 6 },  { 0x1, 1 },  { 0x1, 2 },  { 0x0, 6 },
-    { 0x3, 4 },  { 0x2, 4 },  { 0x1, 5 },  { 0x1, 4 }
-},{
-    { 0x1, 6 },  { 0x1, 1 },  { 0x1, 2 },  { 0x3, 5 },
-    { 0x2, 5 },  { 0x0, 6 },  { 0x1, 5 },  { 0x1, 3 }
-},{
-    { 0x1, 7 },  { 0x1, 1 },  { 0x1, 2 },  { 0x1, 3 },
-    { 0x1, 4 },  { 0x1, 6 },  { 0x0, 7 },  { 0x1, 5 }
-}
+    /* { code, length } */
+    { { 0x1, 5 },  { 0x1, 1 },  { 0x3, 3 },  { 0x2, 3 },
+      { 0x3, 4 },  { 0x2, 4 },  { 0x0, 5 },  { 0x1, 4 } },
+    { { 0x1, 4 },  { 0x3, 2 },  { 0x5, 3 },  { 0x4, 3 },
+      { 0x3, 3 },  { 0x2, 3 },  { 0x0, 4 },  { 0x1, 3 } },
+    { { 0x1, 5 },  { 0x1, 1 },  { 0x3, 3 },  { 0x0, 5 },
+      { 0x3, 4 },  { 0x2, 3 },  { 0x2, 4 },  { 0x1, 4 } },
+    { { 0x1, 6 },  { 0x1, 1 },  { 0x1, 2 },  { 0x0, 6 },
+      { 0x3, 4 },  { 0x2, 4 },  { 0x1, 5 },  { 0x1, 4 } },
+    { { 0x1, 6 },  { 0x1, 1 },  { 0x1, 2 },  { 0x3, 5 },
+      { 0x2, 5 },  { 0x0, 6 },  { 0x1, 5 },  { 0x1, 3 } },
+    { { 0x1, 7 },  { 0x1, 1 },  { 0x1, 2 },  { 0x1, 3 },
+      { 0x1, 4 },  { 0x1, 6 },  { 0x0, 7 },  { 0x1, 5 } }
 };
 
 /* values in this table range from -1..6; adjust retrieved value by -1 */
 const uint8_t ff_svq1_inter_multistage_vlc[6][8][2] = {
- /* { code, length } */
-{
-    { 0x3, 2 },  { 0x5, 3 },  { 0x4, 3 },  { 0x3, 3 },
-    { 0x2, 3 },  { 0x1, 3 },  { 0x1, 4 },  { 0x0, 4 }
-},{
-    { 0x3, 2 },  { 0x5, 3 },  { 0x4, 3 },  { 0x3, 3 },
-    { 0x2, 3 },  { 0x1, 3 },  { 0x1, 4 },  { 0x0, 4 }
-},{
-    { 0x1, 1 },  { 0x3, 3 },  { 0x2, 3 },  { 0x3, 4 },
-    { 0x2, 4 },  { 0x1, 4 },  { 0x1, 5 },  { 0x0, 5 }
-},{
-    { 0x1, 1 },  { 0x3, 3 },  { 0x2, 3 },  { 0x3, 4 },
-    { 0x2, 4 },  { 0x1, 4 },  { 0x1, 5 },  { 0x0, 5 }
-},{
-    { 0x1, 1 },  { 0x3, 3 },  { 0x2, 3 },  { 0x3, 4 },
-    { 0x2, 4 },  { 0x1, 4 },  { 0x1, 5 },  { 0x0, 5 }
-},{
-    { 0x1, 1 },  { 0x1, 2 },  { 0x1, 3 },  { 0x3, 5 },
-    { 0x2, 5 },  { 0x1, 5 },  { 0x1, 6 },  { 0x0, 6 }
-}
+    /* { code, length } */
+    { { 0x3, 2 },  { 0x5, 3 },  { 0x4, 3 },  { 0x3, 3 },
+      { 0x2, 3 },  { 0x1, 3 },  { 0x1, 4 },  { 0x0, 4 } },
+    { { 0x3, 2 },  { 0x5, 3 },  { 0x4, 3 },  { 0x3, 3 },
+      { 0x2, 3 },  { 0x1, 3 },  { 0x1, 4 },  { 0x0, 4 } },
+    { { 0x1, 1 },  { 0x3, 3 },  { 0x2, 3 },  { 0x3, 4 },
+      { 0x2, 4 },  { 0x1, 4 },  { 0x1, 5 },  { 0x0, 5 } },
+    { { 0x1, 1 },  { 0x3, 3 },  { 0x2, 3 },  { 0x3, 4 },
+      { 0x2, 4 },  { 0x1, 4 },  { 0x1, 5 },  { 0x0, 5 } },
+    { { 0x1, 1 },  { 0x3, 3 },  { 0x2, 3 },  { 0x3, 4 },
+      { 0x2, 4 },  { 0x1, 4 },  { 0x1, 5 },  { 0x0, 5 } },
+    { { 0x1, 1 },  { 0x1, 2 },  { 0x1, 3 },  { 0x3, 5 },
+      { 0x2, 5 },  { 0x1, 5 },  { 0x1, 6 },  { 0x0, 6 } }
 };
 
 /* values in this table range from 0..255; adjust retrieved value by +0 */
 const uint16_t ff_svq1_intra_mean_vlc[256][2] = {
- /* { code, length } */
-    { 0x37, 6 },  { 0x56, 7 },  { 0x1, 17 },  { 0x1, 20 },
-    { 0x2, 20 },  { 0x3, 20 },  { 0x0, 20 },  { 0x4, 20 },
-    { 0x5, 20 },  { 0x3, 19 },  { 0x15, 11 },  { 0x42, 9 },
-    { 0x14, 11 },  { 0x3, 14 },  { 0x2, 14 },  { 0x1, 15 },
-    { 0x1, 16 },  { 0x1, 12 },  { 0x2B, 10 },  { 0x18, 11 },
-    { 0xC, 11 },  { 0x41, 9 },  { 0x78, 8 },  { 0x6C, 8 },
-    { 0x55, 7 },  { 0xF, 4 },  { 0xE, 4 },  { 0x34, 6 },
-    { 0x51, 7 },  { 0x72, 8 },  { 0x6E, 8 },  { 0x40, 9 },
-    { 0x3F, 9 },  { 0x3E, 9 },  { 0x3D, 9 },  { 0x3C, 9 },
-    { 0x3B, 9 },  { 0x3A, 9 },  { 0x39, 9 },  { 0x38, 9 },
-    { 0x37, 9 },  { 0x43, 9 },  { 0x46, 9 },  { 0x47, 9 },
-    { 0x45, 9 },  { 0x44, 9 },  { 0x49, 9 },  { 0x48, 9 },
-    { 0x4A, 8 },  { 0x79, 8 },  { 0x76, 8 },  { 0x77, 8 },
-    { 0x71, 8 },  { 0x75, 8 },  { 0x74, 8 },  { 0x73, 8 },
-    { 0x6A, 8 },  { 0x55, 8 },  { 0x70, 8 },  { 0x6F, 8 },
-    { 0x52, 8 },  { 0x6D, 8 },  { 0x4C, 8 },  { 0x6B, 8 },
-    { 0x40, 7 },  { 0x69, 8 },  { 0x68, 8 },  { 0x67, 8 },
-    { 0x66, 8 },  { 0x65, 8 },  { 0x64, 8 },  { 0x63, 8 },
-    { 0x62, 8 },  { 0x61, 8 },  { 0x60, 8 },  { 0x5F, 8 },
-    { 0x5E, 8 },  { 0x5D, 8 },  { 0x5C, 8 },  { 0x5B, 8 },
-    { 0x5A, 8 },  { 0x59, 8 },  { 0x58, 8 },  { 0x57, 8 },
-    { 0x56, 8 },  { 0x3D, 7 },  { 0x54, 8 },  { 0x53, 8 },
-    { 0x3F, 7 },  { 0x51, 8 },  { 0x50, 8 },  { 0x4F, 8 },
-    { 0x4E, 8 },  { 0x4D, 8 },  { 0x41, 7 },  { 0x4B, 8 },
-    { 0x53, 7 },  { 0x3E, 7 },  { 0x48, 8 },  { 0x4F, 7 },
-    { 0x52, 7 },  { 0x45, 8 },  { 0x50, 7 },  { 0x43, 8 },
-    { 0x42, 8 },  { 0x41, 8 },  { 0x42, 7 },  { 0x43, 7 },
-    { 0x3E, 8 },  { 0x44, 7 },  { 0x3C, 8 },  { 0x45, 7 },
-    { 0x46, 7 },  { 0x47, 7 },  { 0x48, 7 },  { 0x49, 7 },
-    { 0x4A, 7 },  { 0x4B, 7 },  { 0x4C, 7 },  { 0x4D, 7 },
-    { 0x4E, 7 },  { 0x58, 7 },  { 0x59, 7 },  { 0x5A, 7 },
-    { 0x5B, 7 },  { 0x5C, 7 },  { 0x5D, 7 },  { 0x44, 8 },
-    { 0x49, 8 },  { 0x29, 8 },  { 0x3F, 8 },  { 0x3D, 8 },
-    { 0x3B, 8 },  { 0x2C, 8 },  { 0x28, 8 },  { 0x25, 8 },
-    { 0x26, 8 },  { 0x5E, 7 },  { 0x57, 7 },  { 0x54, 7 },
-    { 0x5F, 7 },  { 0x62, 7 },  { 0x63, 7 },  { 0x64, 7 },
-    { 0x61, 7 },  { 0x65, 7 },  { 0x67, 7 },  { 0x66, 7 },
-    { 0x35, 6 },  { 0x36, 6 },  { 0x60, 7 },  { 0x39, 8 },
-    { 0x3A, 8 },  { 0x38, 8 },  { 0x37, 8 },  { 0x36, 8 },
-    { 0x35, 8 },  { 0x34, 8 },  { 0x33, 8 },  { 0x32, 8 },
-    { 0x31, 8 },  { 0x30, 8 },  { 0x2D, 8 },  { 0x2B, 8 },
-    { 0x2A, 8 },  { 0x27, 8 },  { 0x40, 8 },  { 0x46, 8 },
-    { 0x47, 8 },  { 0x26, 9 },  { 0x25, 9 },  { 0x24, 9 },
-    { 0x23, 9 },  { 0x22, 9 },  { 0x2E, 8 },  { 0x2F, 8 },
-    { 0x1F, 9 },  { 0x36, 9 },  { 0x1D, 9 },  { 0x21, 9 },
-    { 0x1B, 9 },  { 0x1C, 9 },  { 0x19, 9 },  { 0x1A, 9 },
-    { 0x18, 9 },  { 0x17, 9 },  { 0x16, 9 },  { 0x1E, 9 },
-    { 0x20, 9 },  { 0x27, 9 },  { 0x28, 9 },  { 0x29, 9 },
-    { 0x2A, 9 },  { 0x2B, 9 },  { 0x2C, 9 },  { 0x2D, 9 },
-    { 0x2E, 9 },  { 0x2F, 9 },  { 0x30, 9 },  { 0x35, 9 },
-    { 0x31, 9 },  { 0x32, 9 },  { 0x33, 9 },  { 0x34, 9 },
+    /* { code, length } */
+    { 0x37,  6 },  { 0x56,  7 },  { 0x01, 17 },  { 0x01, 20 },
+    { 0x02, 20 },  { 0x03, 20 },  { 0x00, 20 },  { 0x04, 20 },
+    { 0x05, 20 },  { 0x03, 19 },  { 0x15, 11 },  { 0x42,  9 },
+    { 0x14, 11 },  { 0x03, 14 },  { 0x02, 14 },  { 0x01, 15 },
+    { 0x01, 16 },  { 0x01, 12 },  { 0x2B, 10 },  { 0x18, 11 },
+    { 0x0C, 11 },  { 0x41,  9 },  { 0x78,  8 },  { 0x6C,  8 },
+    { 0x55,  7 },  { 0x0F,  4 },  { 0x0E,  4 },  { 0x34,  6 },
+    { 0x51,  7 },  { 0x72,  8 },  { 0x6E,  8 },  { 0x40,  9 },
+    { 0x3F,  9 },  { 0x3E,  9 },  { 0x3D,  9 },  { 0x3C,  9 },
+    { 0x3B,  9 },  { 0x3A,  9 },  { 0x39,  9 },  { 0x38,  9 },
+    { 0x37,  9 },  { 0x43,  9 },  { 0x46,  9 },  { 0x47,  9 },
+    { 0x45,  9 },  { 0x44,  9 },  { 0x49,  9 },  { 0x48,  9 },
+    { 0x4A,  8 },  { 0x79,  8 },  { 0x76,  8 },  { 0x77,  8 },
+    { 0x71,  8 },  { 0x75,  8 },  { 0x74,  8 },  { 0x73,  8 },
+    { 0x6A,  8 },  { 0x55,  8 },  { 0x70,  8 },  { 0x6F,  8 },
+    { 0x52,  8 },  { 0x6D,  8 },  { 0x4C,  8 },  { 0x6B,  8 },
+    { 0x40,  7 },  { 0x69,  8 },  { 0x68,  8 },  { 0x67,  8 },
+    { 0x66,  8 },  { 0x65,  8 },  { 0x64,  8 },  { 0x63,  8 },
+    { 0x62,  8 },  { 0x61,  8 },  { 0x60,  8 },  { 0x5F,  8 },
+    { 0x5E,  8 },  { 0x5D,  8 },  { 0x5C,  8 },  { 0x5B,  8 },
+    { 0x5A,  8 },  { 0x59,  8 },  { 0x58,  8 },  { 0x57,  8 },
+    { 0x56,  8 },  { 0x3D,  7 },  { 0x54,  8 },  { 0x53,  8 },
+    { 0x3F,  7 },  { 0x51,  8 },  { 0x50,  8 },  { 0x4F,  8 },
+    { 0x4E,  8 },  { 0x4D,  8 },  { 0x41,  7 },  { 0x4B,  8 },
+    { 0x53,  7 },  { 0x3E,  7 },  { 0x48,  8 },  { 0x4F,  7 },
+    { 0x52,  7 },  { 0x45,  8 },  { 0x50,  7 },  { 0x43,  8 },
+    { 0x42,  8 },  { 0x41,  8 },  { 0x42,  7 },  { 0x43,  7 },
+    { 0x3E,  8 },  { 0x44,  7 },  { 0x3C,  8 },  { 0x45,  7 },
+    { 0x46,  7 },  { 0x47,  7 },  { 0x48,  7 },  { 0x49,  7 },
+    { 0x4A,  7 },  { 0x4B,  7 },  { 0x4C,  7 },  { 0x4D,  7 },
+    { 0x4E,  7 },  { 0x58,  7 },  { 0x59,  7 },  { 0x5A,  7 },
+    { 0x5B,  7 },  { 0x5C,  7 },  { 0x5D,  7 },  { 0x44,  8 },
+    { 0x49,  8 },  { 0x29,  8 },  { 0x3F,  8 },  { 0x3D,  8 },
+    { 0x3B,  8 },  { 0x2C,  8 },  { 0x28,  8 },  { 0x25,  8 },
+    { 0x26,  8 },  { 0x5E,  7 },  { 0x57,  7 },  { 0x54,  7 },
+    { 0x5F,  7 },  { 0x62,  7 },  { 0x63,  7 },  { 0x64,  7 },
+    { 0x61,  7 },  { 0x65,  7 },  { 0x67,  7 },  { 0x66,  7 },
+    { 0x35,  6 },  { 0x36,  6 },  { 0x60,  7 },  { 0x39,  8 },
+    { 0x3A,  8 },  { 0x38,  8 },  { 0x37,  8 },  { 0x36,  8 },
+    { 0x35,  8 },  { 0x34,  8 },  { 0x33,  8 },  { 0x32,  8 },
+    { 0x31,  8 },  { 0x30,  8 },  { 0x2D,  8 },  { 0x2B,  8 },
+    { 0x2A,  8 },  { 0x27,  8 },  { 0x40,  8 },  { 0x46,  8 },
+    { 0x47,  8 },  { 0x26,  9 },  { 0x25,  9 },  { 0x24,  9 },
+    { 0x23,  9 },  { 0x22,  9 },  { 0x2E,  8 },  { 0x2F,  8 },
+    { 0x1F,  9 },  { 0x36,  9 },  { 0x1D,  9 },  { 0x21,  9 },
+    { 0x1B,  9 },  { 0x1C,  9 },  { 0x19,  9 },  { 0x1A,  9 },
+    { 0x18,  9 },  { 0x17,  9 },  { 0x16,  9 },  { 0x1E,  9 },
+    { 0x20,  9 },  { 0x27,  9 },  { 0x28,  9 },  { 0x29,  9 },
+    { 0x2A,  9 },  { 0x2B,  9 },  { 0x2C,  9 },  { 0x2D,  9 },
+    { 0x2E,  9 },  { 0x2F,  9 },  { 0x30,  9 },  { 0x35,  9 },
+    { 0x31,  9 },  { 0x32,  9 },  { 0x33,  9 },  { 0x34,  9 },
     { 0x19, 10 },  { 0x2A, 10 },  { 0x17, 10 },  { 0x16, 10 },
     { 0x15, 10 },  { 0x28, 10 },  { 0x26, 10 },  { 0x25, 10 },
     { 0x22, 10 },  { 0x21, 10 },  { 0x18, 10 },  { 0x14, 10 },
-    { 0x29, 10 },  { 0x12, 10 },  { 0xD, 10 },  { 0xE, 10 },
-    { 0xF, 10 },  { 0x10, 10 },  { 0x11, 10 },  { 0x1A, 10 },
+    { 0x29, 10 },  { 0x12, 10 },  { 0x0D, 10 },  { 0x0E, 10 },
+    { 0x0F, 10 },  { 0x10, 10 },  { 0x11, 10 },  { 0x1A, 10 },
     { 0x1B, 10 },  { 0x1C, 10 },  { 0x1D, 10 },  { 0x1E, 10 },
     { 0x1F, 10 },  { 0x20, 10 },  { 0x13, 10 },  { 0x23, 10 },
-    { 0x24, 10 },  { 0x9, 11 },  { 0x8, 11 },  { 0x7, 11 },
-    { 0x27, 10 },  { 0x5, 11 },  { 0xB, 11 },  { 0x6, 11 },
-    { 0x4, 11 },  { 0x3, 11 },  { 0x2, 11 },  { 0x1, 11 },
-    { 0xA, 11 },  { 0x16, 11 },  { 0x19, 11 },  { 0x17, 11 },
-    { 0xD, 11 },  { 0xE, 11 },  { 0xF, 11 },  { 0x10, 11 },
-    { 0x11, 11 },  { 0x12, 11 },  { 0x13, 11 },  { 0x1, 14 }
+    { 0x24, 10 },  { 0x09, 11 },  { 0x08, 11 },  { 0x07, 11 },
+    { 0x27, 10 },  { 0x05, 11 },  { 0x0B, 11 },  { 0x06, 11 },
+    { 0x04, 11 },  { 0x03, 11 },  { 0x02, 11 },  { 0x01, 11 },
+    { 0x0A, 11 },  { 0x16, 11 },  { 0x19, 11 },  { 0x17, 11 },
+    { 0x0D, 11 },  { 0x0E, 11 },  { 0x0F, 11 },  { 0x10, 11 },
+    { 0x11, 11 },  { 0x12, 11 },  { 0x13, 11 },  { 0x01, 14 }
 };
 
 /* values in this table range from -256..255; adjust retrieved value by -256 */
 const uint16_t ff_svq1_inter_mean_vlc[512][2] = {
- /* { code, length } */
+    /* { code, length } */
     { 0x5A, 22 },  { 0xD4, 22 },  { 0xD5, 22 },  { 0xD6, 22 },
     { 0xD7, 22 },  { 0xD8, 22 },  { 0xD9, 22 },  { 0xDA, 22 },
     { 0xDB, 22 },  { 0xDC, 22 },  { 0xDD, 22 },  { 0xDE, 22 },
@@ -159,12 +144,12 @@
     { 0xE7, 22 },  { 0xEC, 22 },  { 0xED, 22 },  { 0xEE, 22 },
     { 0xEF, 22 },  { 0xF0, 22 },  { 0xF1, 22 },  { 0xF2, 22 },
     { 0xF3, 22 },  { 0xF4, 22 },  { 0xF5, 22 },  { 0xF6, 22 },
-    { 0xF7, 22 },  { 0xF8, 22 },  { 0x102, 22 },  { 0xEB, 22 },
+    { 0xF7, 22 },  { 0xF8, 22 },  { 0x102,22 },  { 0xEB, 22 },
     { 0xF9, 22 },  { 0xFC, 22 },  { 0xFD, 22 },  { 0xFE, 22 },
-    { 0x100, 22 },  { 0x5C, 22 },  { 0x60, 22 },  { 0x101, 22 },
-    { 0x71, 22 },  { 0x104, 22 },  { 0x105, 22 },  { 0xFB, 22 },
+    { 0x100,22 },  { 0x5C, 22 },  { 0x60, 22 },  { 0x101,22 },
+    { 0x71, 22 },  { 0x104,22 },  { 0x105,22 },  { 0xFB, 22 },
     { 0xFF, 22 },  { 0x86, 21 },  { 0xFA, 22 },  { 0x7C, 22 },
-    { 0x75, 22 },  { 0x103, 22 },  { 0x78, 22 },  { 0xD3, 22 },
+    { 0x75, 22 },  { 0x103,22 },  { 0x78, 22 },  { 0xD3, 22 },
     { 0x7B, 22 },  { 0x82, 22 },  { 0xD2, 22 },  { 0xD1, 22 },
     { 0xD0, 22 },  { 0xCF, 22 },  { 0xCE, 22 },  { 0xCD, 22 },
     { 0xCC, 22 },  { 0xC3, 22 },  { 0xCA, 22 },  { 0xC9, 22 },
@@ -206,19 +191,19 @@
     { 0x21, 14 },  { 0x13, 13 },  { 0x14, 13 },  { 0x15, 13 },
     { 0x16, 13 },  { 0x17, 13 },  { 0x18, 13 },  { 0x19, 13 },
     { 0x1A, 13 },  { 0x18, 12 },  { 0x17, 12 },  { 0x15, 12 },
-    { 0x14, 12 },  { 0x13, 12 },  { 0x12, 12 },  { 0xF, 11 },
+    { 0x14, 12 },  { 0x13, 12 },  { 0x12, 12 },  { 0x0F, 11 },
     { 0x10, 11 },  { 0x12, 11 },  { 0x13, 11 },  { 0x1B, 11 },
-    { 0x1A, 11 },  { 0xE, 10 },  { 0x13, 10 },  { 0xF, 10 },
-    { 0x10, 10 },  { 0x11, 10 },  { 0x12, 10 },  { 0xD, 9 },
-    { 0x14, 9 },  { 0x15, 9 },  { 0xC, 9 },  { 0x13, 9 },
-    { 0xF, 8 },  { 0xE, 8 },  { 0x10, 8 },  { 0x11, 8 },
-    { 0xC, 7 },  { 0x9, 7 },  { 0xA, 7 },  { 0x8, 6 },
-    { 0x9, 6 },  { 0x9, 5 },  { 0x8, 5 },  { 0x5, 4 },
-    { 0x1, 1 },  { 0x3, 3 },  { 0x7, 5 },  { 0x6, 5 },
-    { 0xB, 6 },  { 0xA, 6 },  { 0xE, 7 },  { 0xF, 7 },
-    { 0xB, 7 },  { 0xD, 7 },  { 0xB, 8 },  { 0xD, 8 },
-    { 0xC, 8 },  { 0xF, 9 },  { 0x10, 9 },  { 0x11, 9 },
-    { 0xE, 9 },  { 0x12, 9 },  { 0x17, 10 },  { 0x14, 10 },
+    { 0x1A, 11 },  { 0x0E, 10 },  { 0x13, 10 },  { 0x0F, 10 },
+    { 0x10, 10 },  { 0x11, 10 },  { 0x12, 10 },  { 0x0D,  9 },
+    { 0x14,  9 },  { 0x15,  9 },  { 0x0C,  9 },  { 0x13,  9 },
+    { 0x0F,  8 },  { 0x0E,  8 },  { 0x10,  8 },  { 0x11,  8 },
+    { 0x0C,  7 },  { 0x09,  7 },  { 0x0A,  7 },  { 0x08,  6 },
+    { 0x09,  6 },  { 0x09,  5 },  { 0x08,  5 },  { 0x05,  4 },
+    { 0x01,  1 },  { 0x03,  3 },  { 0x07,  5 },  { 0x06,  5 },
+    { 0x0B,  6 },  { 0x0A,  6 },  { 0x0E,  7 },  { 0x0F,  7 },
+    { 0x0B,  7 },  { 0x0D,  7 },  { 0x0B,  8 },  { 0x0D,  8 },
+    { 0x0C,  8 },  { 0x0F,  9 },  { 0x10,  9 },  { 0x11,  9 },
+    { 0x0E,  9 },  { 0x12,  9 },  { 0x17, 10 },  { 0x14, 10 },
     { 0x16, 10 },  { 0x15, 10 },  { 0x19, 11 },  { 0x18, 11 },
     { 0x17, 11 },  { 0x16, 11 },  { 0x15, 11 },  { 0x14, 11 },
     { 0x11, 11 },  { 0x19, 12 },  { 0x1A, 12 },  { 0x16, 12 },
@@ -274,10 +259,10 @@
     { 0x1B, 22 },  { 0x1A, 22 },  { 0x19, 22 },  { 0x18, 22 },
     { 0x17, 22 },  { 0x16, 22 },  { 0x15, 22 },  { 0x14, 22 },
     { 0x13, 22 },  { 0x12, 22 },  { 0x11, 22 },  { 0x10, 22 },
-    { 0xF, 22 },  { 0xE, 22 },  { 0xD, 22 },  { 0xC, 22 },
-    { 0xB, 22 },  { 0xA, 22 },  { 0x9, 22 },  { 0x8, 22 },
-    { 0x7, 22 },  { 0x6, 22 },  { 0x5, 22 },  { 0x4, 22 },
-    { 0x3, 22 },  { 0x2, 22 },  { 0x1, 22 },  { 0x0, 22 }
+    { 0x0F, 22 },  { 0x0E, 22 },  { 0x0D, 22 },  { 0x0C, 22 },
+    { 0x0B, 22 },  { 0x0A, 22 },  { 0x09, 22 },  { 0x08, 22 },
+    { 0x07, 22 },  { 0x06, 22 },  { 0x05, 22 },  { 0x04, 22 },
+    { 0x03, 22 },  { 0x02, 22 },  { 0x01, 22 },  { 0x00, 22 }
 };
 
 #endif /* AVCODEC_SVQ1_VLC_H */
diff --git a/libavcodec/svq1dec.c b/libavcodec/svq1dec.c
index 2e5600a..27e9606 100644
--- a/libavcodec/svq1dec.c
+++ b/libavcodec/svq1dec.c
@@ -32,12 +32,10 @@
  *   http://www.pcisys.net/~melanson/codecs/
  */
 
-
 #include "avcodec.h"
 #include "dsputil.h"
 #include "mpegvideo.h"
 #include "mathops.h"
-
 #include "svq1.h"
 
 #undef NDEBUG
@@ -54,655 +52,667 @@
 
 /* motion vector (prediction) */
 typedef struct svq1_pmv_s {
-  int           x;
-  int           y;
+    int x;
+    int y;
 } svq1_pmv;
 
 static const uint8_t string_table[256] = {
-  0x00, 0xD5, 0x7F, 0xAA, 0xFE, 0x2B, 0x81, 0x54,
-  0x29, 0xFC, 0x56, 0x83, 0xD7, 0x02, 0xA8, 0x7D,
-  0x52, 0x87, 0x2D, 0xF8, 0xAC, 0x79, 0xD3, 0x06,
-  0x7B, 0xAE, 0x04, 0xD1, 0x85, 0x50, 0xFA, 0x2F,
-  0xA4, 0x71, 0xDB, 0x0E, 0x5A, 0x8F, 0x25, 0xF0,
-  0x8D, 0x58, 0xF2, 0x27, 0x73, 0xA6, 0x0C, 0xD9,
-  0xF6, 0x23, 0x89, 0x5C, 0x08, 0xDD, 0x77, 0xA2,
-  0xDF, 0x0A, 0xA0, 0x75, 0x21, 0xF4, 0x5E, 0x8B,
-  0x9D, 0x48, 0xE2, 0x37, 0x63, 0xB6, 0x1C, 0xC9,
-  0xB4, 0x61, 0xCB, 0x1E, 0x4A, 0x9F, 0x35, 0xE0,
-  0xCF, 0x1A, 0xB0, 0x65, 0x31, 0xE4, 0x4E, 0x9B,
-  0xE6, 0x33, 0x99, 0x4C, 0x18, 0xCD, 0x67, 0xB2,
-  0x39, 0xEC, 0x46, 0x93, 0xC7, 0x12, 0xB8, 0x6D,
-  0x10, 0xC5, 0x6F, 0xBA, 0xEE, 0x3B, 0x91, 0x44,
-  0x6B, 0xBE, 0x14, 0xC1, 0x95, 0x40, 0xEA, 0x3F,
-  0x42, 0x97, 0x3D, 0xE8, 0xBC, 0x69, 0xC3, 0x16,
-  0xEF, 0x3A, 0x90, 0x45, 0x11, 0xC4, 0x6E, 0xBB,
-  0xC6, 0x13, 0xB9, 0x6C, 0x38, 0xED, 0x47, 0x92,
-  0xBD, 0x68, 0xC2, 0x17, 0x43, 0x96, 0x3C, 0xE9,
-  0x94, 0x41, 0xEB, 0x3E, 0x6A, 0xBF, 0x15, 0xC0,
-  0x4B, 0x9E, 0x34, 0xE1, 0xB5, 0x60, 0xCA, 0x1F,
-  0x62, 0xB7, 0x1D, 0xC8, 0x9C, 0x49, 0xE3, 0x36,
-  0x19, 0xCC, 0x66, 0xB3, 0xE7, 0x32, 0x98, 0x4D,
-  0x30, 0xE5, 0x4F, 0x9A, 0xCE, 0x1B, 0xB1, 0x64,
-  0x72, 0xA7, 0x0D, 0xD8, 0x8C, 0x59, 0xF3, 0x26,
-  0x5B, 0x8E, 0x24, 0xF1, 0xA5, 0x70, 0xDA, 0x0F,
-  0x20, 0xF5, 0x5F, 0x8A, 0xDE, 0x0B, 0xA1, 0x74,
-  0x09, 0xDC, 0x76, 0xA3, 0xF7, 0x22, 0x88, 0x5D,
-  0xD6, 0x03, 0xA9, 0x7C, 0x28, 0xFD, 0x57, 0x82,
-  0xFF, 0x2A, 0x80, 0x55, 0x01, 0xD4, 0x7E, 0xAB,
-  0x84, 0x51, 0xFB, 0x2E, 0x7A, 0xAF, 0x05, 0xD0,
-  0xAD, 0x78, 0xD2, 0x07, 0x53, 0x86, 0x2C, 0xF9
+    0x00, 0xD5, 0x7F, 0xAA, 0xFE, 0x2B, 0x81, 0x54,
+    0x29, 0xFC, 0x56, 0x83, 0xD7, 0x02, 0xA8, 0x7D,
+    0x52, 0x87, 0x2D, 0xF8, 0xAC, 0x79, 0xD3, 0x06,
+    0x7B, 0xAE, 0x04, 0xD1, 0x85, 0x50, 0xFA, 0x2F,
+    0xA4, 0x71, 0xDB, 0x0E, 0x5A, 0x8F, 0x25, 0xF0,
+    0x8D, 0x58, 0xF2, 0x27, 0x73, 0xA6, 0x0C, 0xD9,
+    0xF6, 0x23, 0x89, 0x5C, 0x08, 0xDD, 0x77, 0xA2,
+    0xDF, 0x0A, 0xA0, 0x75, 0x21, 0xF4, 0x5E, 0x8B,
+    0x9D, 0x48, 0xE2, 0x37, 0x63, 0xB6, 0x1C, 0xC9,
+    0xB4, 0x61, 0xCB, 0x1E, 0x4A, 0x9F, 0x35, 0xE0,
+    0xCF, 0x1A, 0xB0, 0x65, 0x31, 0xE4, 0x4E, 0x9B,
+    0xE6, 0x33, 0x99, 0x4C, 0x18, 0xCD, 0x67, 0xB2,
+    0x39, 0xEC, 0x46, 0x93, 0xC7, 0x12, 0xB8, 0x6D,
+    0x10, 0xC5, 0x6F, 0xBA, 0xEE, 0x3B, 0x91, 0x44,
+    0x6B, 0xBE, 0x14, 0xC1, 0x95, 0x40, 0xEA, 0x3F,
+    0x42, 0x97, 0x3D, 0xE8, 0xBC, 0x69, 0xC3, 0x16,
+    0xEF, 0x3A, 0x90, 0x45, 0x11, 0xC4, 0x6E, 0xBB,
+    0xC6, 0x13, 0xB9, 0x6C, 0x38, 0xED, 0x47, 0x92,
+    0xBD, 0x68, 0xC2, 0x17, 0x43, 0x96, 0x3C, 0xE9,
+    0x94, 0x41, 0xEB, 0x3E, 0x6A, 0xBF, 0x15, 0xC0,
+    0x4B, 0x9E, 0x34, 0xE1, 0xB5, 0x60, 0xCA, 0x1F,
+    0x62, 0xB7, 0x1D, 0xC8, 0x9C, 0x49, 0xE3, 0x36,
+    0x19, 0xCC, 0x66, 0xB3, 0xE7, 0x32, 0x98, 0x4D,
+    0x30, 0xE5, 0x4F, 0x9A, 0xCE, 0x1B, 0xB1, 0x64,
+    0x72, 0xA7, 0x0D, 0xD8, 0x8C, 0x59, 0xF3, 0x26,
+    0x5B, 0x8E, 0x24, 0xF1, 0xA5, 0x70, 0xDA, 0x0F,
+    0x20, 0xF5, 0x5F, 0x8A, 0xDE, 0x0B, 0xA1, 0x74,
+    0x09, 0xDC, 0x76, 0xA3, 0xF7, 0x22, 0x88, 0x5D,
+    0xD6, 0x03, 0xA9, 0x7C, 0x28, 0xFD, 0x57, 0x82,
+    0xFF, 0x2A, 0x80, 0x55, 0x01, 0xD4, 0x7E, 0xAB,
+    0x84, 0x51, 0xFB, 0x2E, 0x7A, 0xAF, 0x05, 0xD0,
+    0xAD, 0x78, 0xD2, 0x07, 0x53, 0x86, 0x2C, 0xF9
 };
 
-#define SVQ1_PROCESS_VECTOR()\
-    for (; level > 0; i++) {\
-      /* process next depth */\
-      if (i == m) {\
-        m = n;\
-        if (--level == 0)\
-          break;\
-      }\
-      /* divide block if next bit set */\
-      if (get_bits1 (bitbuf) == 0)\
-        break;\
-      /* add child nodes */\
-      list[n++] = list[i];\
-      list[n++] = list[i] + (((level & 1) ? pitch : 1) << ((level >> 1) + 1));\
+#define SVQ1_PROCESS_VECTOR()                                           \
+    for (; level > 0; i++) {                                            \
+        /* process next depth */                                        \
+        if (i == m) {                                                   \
+            m = n;                                                      \
+            if (--level == 0)                                           \
+                break;                                                  \
+        }                                                               \
+        /* divide block if next bit set */                              \
+        if (!get_bits1(bitbuf))                                         \
+            break;                                                      \
+        /* add child nodes */                                           \
+        list[n++] = list[i];                                            \
+        list[n++] = list[i] + (((level & 1) ? pitch : 1) << ((level >> 1) + 1));\
     }
 
-#define SVQ1_ADD_CODEBOOK()\
-          /* add codebook entries to vector */\
-          for (j=0; j < stages; j++) {\
-            n3  = codebook[entries[j]] ^ 0x80808080;\
-            n1 += ((n3 & 0xFF00FF00) >> 8);\
-            n2 +=  (n3 & 0x00FF00FF);\
-          }\
-\
-          /* clip to [0..255] */\
-          if (n1 & 0xFF00FF00) {\
-            n3  = ((( n1 >> 15) & 0x00010001) | 0x01000100) - 0x00010001;\
-            n1 += 0x7F007F00;\
-            n1 |= (((~n1 >> 15) & 0x00010001) | 0x01000100) - 0x00010001;\
-            n1 &= (n3 & 0x00FF00FF);\
-          }\
-\
-          if (n2 & 0xFF00FF00) {\
-            n3  = ((( n2 >> 15) & 0x00010001) | 0x01000100) - 0x00010001;\
-            n2 += 0x7F007F00;\
-            n2 |= (((~n2 >> 15) & 0x00010001) | 0x01000100) - 0x00010001;\
-            n2 &= (n3 & 0x00FF00FF);\
-          }
+#define SVQ1_ADD_CODEBOOK()                                             \
+    /* add codebook entries to vector */                                \
+    for (j = 0; j < stages; j++) {                                      \
+        n3  = codebook[entries[j]] ^ 0x80808080;                        \
+        n1 += (n3 & 0xFF00FF00) >> 8;                                   \
+        n2 +=  n3 & 0x00FF00FF;                                         \
+    }                                                                   \
+                                                                        \
+    /* clip to [0..255] */                                              \
+    if (n1 & 0xFF00FF00) {                                              \
+        n3  = (n1 >> 15  & 0x00010001 | 0x01000100) - 0x00010001;       \
+        n1 += 0x7F007F00;                                               \
+        n1 |= (~n1 >> 15 & 0x00010001 | 0x01000100) - 0x00010001;       \
+        n1 &= n3 & 0x00FF00FF;                                          \
+    }                                                                   \
+                                                                        \
+    if (n2 & 0xFF00FF00) {                                              \
+        n3  = (n2 >> 15  & 0x00010001 | 0x01000100) - 0x00010001;       \
+        n2 += 0x7F007F00;                                               \
+        n2 |= (~n2 >> 15 & 0x00010001 | 0x01000100) - 0x00010001;       \
+        n2 &= n3 & 0x00FF00FF;                                          \
+    }
 
-#define SVQ1_DO_CODEBOOK_INTRA()\
-      for (y=0; y < height; y++) {\
-        for (x=0; x < (width / 4); x++, codebook++) {\
-        n1 = n4;\
-        n2 = n4;\
-        SVQ1_ADD_CODEBOOK()\
-        /* store result */\
-        dst[x] = (n1 << 8) | n2;\
-        }\
-        dst += (pitch / 4);\
-      }
+#define SVQ1_DO_CODEBOOK_INTRA()                                        \
+    for (y = 0; y < height; y++) {                                      \
+        for (x = 0; x < width / 4; x++, codebook++) {                   \
+            n1 = n4;                                                    \
+            n2 = n4;                                                    \
+            SVQ1_ADD_CODEBOOK()                                         \
+            /* store result */                                          \
+            dst[x] = n1 << 8 | n2;                                      \
+        }                                                               \
+        dst += pitch / 4;                                               \
+    }
 
-#define SVQ1_DO_CODEBOOK_NONINTRA()\
-      for (y=0; y < height; y++) {\
-        for (x=0; x < (width / 4); x++, codebook++) {\
-        n3 = dst[x];\
-        /* add mean value to vector */\
-        n1 = ((n3 & 0xFF00FF00) >> 8) + n4;\
-        n2 =  (n3 & 0x00FF00FF)          + n4;\
-        SVQ1_ADD_CODEBOOK()\
-        /* store result */\
-        dst[x] = (n1 << 8) | n2;\
-        }\
-        dst += (pitch / 4);\
-      }
+#define SVQ1_DO_CODEBOOK_NONINTRA()                                     \
+    for (y = 0; y < height; y++) {                                      \
+        for (x = 0; x < width / 4; x++, codebook++) {                   \
+            n3 = dst[x];                                                \
+            /* add mean value to vector */                              \
+            n1 = n4 + ((n3 & 0xFF00FF00) >> 8);                         \
+            n2 = n4 +  (n3 & 0x00FF00FF);                               \
+            SVQ1_ADD_CODEBOOK()                                         \
+            /* store result */                                          \
+            dst[x] = n1 << 8 | n2;                                      \
+        }                                                               \
+        dst += pitch / 4;                                               \
+    }
 
-#define SVQ1_CALC_CODEBOOK_ENTRIES(cbook)\
-      codebook = (const uint32_t *) cbook[level];\
-      if (stages > 0)\
-        bit_cache = get_bits (bitbuf, 4*stages);\
-      /* calculate codebook entries for this vector */\
-      for (j=0; j < stages; j++) {\
-        entries[j] = (((bit_cache >> (4*(stages - j - 1))) & 0xF) + 16*j) << (level + 1);\
-      }\
-      mean -= (stages * 128);\
-      n4    = (mean << 16) + mean;
+#define SVQ1_CALC_CODEBOOK_ENTRIES(cbook)                               \
+    codebook = (const uint32_t *)cbook[level];                          \
+    if (stages > 0)                                                     \
+        bit_cache = get_bits(bitbuf, 4 * stages);                       \
+    /* calculate codebook entries for this vector */                    \
+    for (j = 0; j < stages; j++) {                                      \
+        entries[j] = (((bit_cache >> (4 * (stages - j - 1))) & 0xF) +   \
+                      16 * j) << (level + 1);                           \
+    }                                                                   \
+    mean -= stages * 128;                                               \
+    n4    = (mean << 16) + mean;
 
-static int svq1_decode_block_intra (GetBitContext *bitbuf, uint8_t *pixels, int pitch ) {
-  uint32_t    bit_cache;
-  uint8_t    *list[63];
-  uint32_t   *dst;
-  const uint32_t *codebook;
-  int         entries[6];
-  int         i, j, m, n;
-  int         mean, stages;
-  unsigned    x, y, width, height, level;
-  uint32_t    n1, n2, n3, n4;
+static int svq1_decode_block_intra(GetBitContext *bitbuf, uint8_t *pixels,
+                                   int pitch)
+{
+    uint32_t bit_cache;
+    uint8_t *list[63];
+    uint32_t *dst;
+    const uint32_t *codebook;
+    int entries[6];
+    int i, j, m, n;
+    int mean, stages;
+    unsigned x, y, width, height, level;
+    uint32_t n1, n2, n3, n4;
 
-  /* initialize list for breadth first processing of vectors */
-  list[0] = pixels;
+    /* initialize list for breadth first processing of vectors */
+    list[0] = pixels;
 
-  /* recursively process vector */
-  for (i=0, m=1, n=1, level=5; i < n; i++) {
-    SVQ1_PROCESS_VECTOR();
+    /* recursively process vector */
+    for (i = 0, m = 1, n = 1, level = 5; i < n; i++) {
+        SVQ1_PROCESS_VECTOR();
 
-    /* destination address and vector size */
-    dst = (uint32_t *) list[i];
-    width = 1 << ((4 + level) /2);
-    height = 1 << ((3 + level) /2);
+        /* destination address and vector size */
+        dst    = (uint32_t *)list[i];
+        width  = 1 << ((4 + level) / 2);
+        height = 1 << ((3 + level) / 2);
 
-    /* get number of stages (-1 skips vector, 0 for mean only) */
-    stages = get_vlc2(bitbuf, svq1_intra_multistage[level].table, 3, 3) - 1;
+        /* get number of stages (-1 skips vector, 0 for mean only) */
+        stages = get_vlc2(bitbuf, svq1_intra_multistage[level].table, 3, 3) - 1;
 
-    if (stages == -1) {
-        for (y=0; y < height; y++) {
-          memset (&dst[y*(pitch / 4)], 0, width);
+        if (stages == -1) {
+            for (y = 0; y < height; y++)
+                memset(&dst[y * (pitch / 4)], 0, width);
+            continue;   /* skip vector */
         }
-      continue;                 /* skip vector */
+
+        if (stages > 0 && level >= 4) {
+            av_dlog(NULL,
+                    "Error (svq1_decode_block_intra): invalid vector: stages=%i level=%i\n",
+                    stages, level);
+            return AVERROR_INVALIDDATA;  /* invalid vector */
+        }
+
+        mean = get_vlc2(bitbuf, svq1_intra_mean.table, 8, 3);
+
+        if (stages == 0) {
+            for (y = 0; y < height; y++)
+                memset(&dst[y * (pitch / 4)], mean, width);
+        } else {
+            SVQ1_CALC_CODEBOOK_ENTRIES(ff_svq1_intra_codebooks);
+            SVQ1_DO_CODEBOOK_INTRA()
+        }
     }
 
-    if ((stages > 0) && (level >= 4)) {
-      av_dlog(NULL,
-              "Error (svq1_decode_block_intra): invalid vector: stages=%i level=%i\n",
-              stages, level);
-      return -1;        /* invalid vector */
+    return 0;
+}
+
+static int svq1_decode_block_non_intra(GetBitContext *bitbuf, uint8_t *pixels,
+                                       int pitch)
+{
+    uint32_t bit_cache;
+    uint8_t *list[63];
+    uint32_t *dst;
+    const uint32_t *codebook;
+    int entries[6];
+    int i, j, m, n;
+    int mean, stages;
+    int x, y, width, height, level;
+    uint32_t n1, n2, n3, n4;
+
+    /* initialize list for breadth first processing of vectors */
+    list[0] = pixels;
+
+    /* recursively process vector */
+    for (i = 0, m = 1, n = 1, level = 5; i < n; i++) {
+        SVQ1_PROCESS_VECTOR();
+
+        /* destination address and vector size */
+        dst    = (uint32_t *)list[i];
+        width  = 1 << ((4 + level) / 2);
+        height = 1 << ((3 + level) / 2);
+
+        /* get number of stages (-1 skips vector, 0 for mean only) */
+        stages = get_vlc2(bitbuf, svq1_inter_multistage[level].table, 3, 2) - 1;
+
+        if (stages == -1)
+            continue;           /* skip vector */
+
+        if ((stages > 0) && (level >= 4)) {
+            av_dlog(NULL,
+                    "Error (svq1_decode_block_non_intra): invalid vector: stages=%i level=%i\n",
+                    stages, level);
+            return AVERROR_INVALIDDATA;  /* invalid vector */
+        }
+
+        mean = get_vlc2(bitbuf, svq1_inter_mean.table, 9, 3) - 256;
+
+        SVQ1_CALC_CODEBOOK_ENTRIES(ff_svq1_inter_codebooks);
+        SVQ1_DO_CODEBOOK_NONINTRA()
+    }
+    return 0;
+}
+
+static int svq1_decode_motion_vector(GetBitContext *bitbuf, svq1_pmv *mv,
+                                     svq1_pmv **pmv)
+{
+    int diff;
+    int i;
+
+    for (i = 0; i < 2; i++) {
+        /* get motion code */
+        diff = get_vlc2(bitbuf, svq1_motion_component.table, 7, 2);
+        if (diff < 0)
+            return AVERROR_INVALIDDATA;
+        else if (diff) {
+            if (get_bits1(bitbuf))
+                diff = -diff;
+        }
+
+        /* add median of motion vector predictors and clip result */
+        if (i == 1)
+            mv->y = sign_extend(diff + mid_pred(pmv[0]->y, pmv[1]->y, pmv[2]->y), 6);
+        else
+            mv->x = sign_extend(diff + mid_pred(pmv[0]->x, pmv[1]->x, pmv[2]->x), 6);
     }
 
-    mean = get_vlc2(bitbuf, svq1_intra_mean.table, 8, 3);
-
-    if (stages == 0) {
-      for (y=0; y < height; y++) {
-        memset (&dst[y*(pitch / 4)], mean, width);
-      }
-    } else {
-      SVQ1_CALC_CODEBOOK_ENTRIES(ff_svq1_intra_codebooks);
-      SVQ1_DO_CODEBOOK_INTRA()
-    }
-  }
-
-  return 0;
+    return 0;
 }
 
-static int svq1_decode_block_non_intra (GetBitContext *bitbuf, uint8_t *pixels, int pitch ) {
-  uint32_t    bit_cache;
-  uint8_t    *list[63];
-  uint32_t   *dst;
-  const uint32_t *codebook;
-  int         entries[6];
-  int         i, j, m, n;
-  int         mean, stages;
-  int         x, y, width, height, level;
-  uint32_t    n1, n2, n3, n4;
+static void svq1_skip_block(uint8_t *current, uint8_t *previous,
+                            int pitch, int x, int y)
+{
+    uint8_t *src;
+    uint8_t *dst;
+    int i;
 
-  /* initialize list for breadth first processing of vectors */
-  list[0] = pixels;
-
-  /* recursively process vector */
-  for (i=0, m=1, n=1, level=5; i < n; i++) {
-    SVQ1_PROCESS_VECTOR();
-
-    /* destination address and vector size */
-    dst = (uint32_t *) list[i];
-    width = 1 << ((4 + level) /2);
-    height = 1 << ((3 + level) /2);
-
-    /* get number of stages (-1 skips vector, 0 for mean only) */
-    stages = get_vlc2(bitbuf, svq1_inter_multistage[level].table, 3, 2) - 1;
-
-    if (stages == -1) continue; /* skip vector */
-
-    if ((stages > 0) && (level >= 4)) {
-      av_dlog(NULL,
-              "Error (svq1_decode_block_non_intra): invalid vector: stages=%i level=%i\n",
-              stages, level);
-      return -1;        /* invalid vector */
-    }
-
-    mean = get_vlc2(bitbuf, svq1_inter_mean.table, 9, 3) - 256;
-
-    SVQ1_CALC_CODEBOOK_ENTRIES(ff_svq1_inter_codebooks);
-    SVQ1_DO_CODEBOOK_NONINTRA()
-  }
-  return 0;
-}
-
-static int svq1_decode_motion_vector (GetBitContext *bitbuf, svq1_pmv *mv, svq1_pmv **pmv) {
-  int        diff;
-  int        i;
-
-  for (i=0; i < 2; i++) {
-
-    /* get motion code */
-    diff = get_vlc2(bitbuf, svq1_motion_component.table, 7, 2);
-    if(diff<0)
-        return -1;
-    else if(diff){
-        if(get_bits1(bitbuf)) diff= -diff;
-    }
-
-    /* add median of motion vector predictors and clip result */
-    if (i == 1)
-      mv->y = sign_extend(diff + mid_pred(pmv[0]->y, pmv[1]->y, pmv[2]->y), 6);
-    else
-      mv->x = sign_extend(diff + mid_pred(pmv[0]->x, pmv[1]->x, pmv[2]->x), 6);
-  }
-
-  return 0;
-}
-
-static void svq1_skip_block (uint8_t *current, uint8_t *previous, int pitch, int x, int y) {
-  uint8_t *src;
-  uint8_t *dst;
-  int      i;
-
-  src = &previous[x + y*pitch];
-  dst = current;
-
-  for (i=0; i < 16; i++) {
-    memcpy (dst, src, 16);
-    src += pitch;
-    dst += pitch;
-  }
-}
-
-static int svq1_motion_inter_block (MpegEncContext *s, GetBitContext *bitbuf,
-                               uint8_t *current, uint8_t *previous, int pitch,
-                               svq1_pmv *motion, int x, int y) {
-  uint8_t    *src;
-  uint8_t    *dst;
-  svq1_pmv    mv;
-  svq1_pmv   *pmv[3];
-  int         result;
-
-  /* predict and decode motion vector */
-  pmv[0] = &motion[0];
-  if (y == 0) {
-    pmv[1] =
-    pmv[2] = pmv[0];
-  }
-  else {
-    pmv[1] = &motion[(x / 8) + 2];
-    pmv[2] = &motion[(x / 8) + 4];
-  }
-
-  result = svq1_decode_motion_vector (bitbuf, &mv, pmv);
-
-  if (result != 0)
-    return result;
-
-  motion[0].x                =
-  motion[(x / 8) + 2].x      =
-  motion[(x / 8) + 3].x      = mv.x;
-  motion[0].y                =
-  motion[(x / 8) + 2].y      =
-  motion[(x / 8) + 3].y      = mv.y;
-
-  if(y + (mv.y >> 1)<0)
-     mv.y= 0;
-  if(x + (mv.x >> 1)<0)
-     mv.x= 0;
-
-  src = &previous[(x + (mv.x >> 1)) + (y + (mv.y >> 1))*pitch];
-  dst = current;
-
-  s->dsp.put_pixels_tab[0][((mv.y & 1) << 1) | (mv.x & 1)](dst,src,pitch,16);
-
-  return 0;
-}
-
-static int svq1_motion_inter_4v_block (MpegEncContext *s, GetBitContext *bitbuf,
-                                  uint8_t *current, uint8_t *previous, int pitch,
-                                  svq1_pmv *motion,int x, int y) {
-  uint8_t    *src;
-  uint8_t    *dst;
-  svq1_pmv    mv;
-  svq1_pmv   *pmv[4];
-  int         i, result;
-
-  /* predict and decode motion vector (0) */
-  pmv[0] = &motion[0];
-  if (y == 0) {
-    pmv[1] =
-    pmv[2] = pmv[0];
-  }
-  else {
-    pmv[1] = &motion[(x / 8) + 2];
-    pmv[2] = &motion[(x / 8) + 4];
-  }
-
-  result = svq1_decode_motion_vector (bitbuf, &mv, pmv);
-
-  if (result != 0)
-    return result;
-
-  /* predict and decode motion vector (1) */
-  pmv[0] = &mv;
-  if (y == 0) {
-    pmv[1] =
-    pmv[2] = pmv[0];
-  }
-  else {
-    pmv[1] = &motion[(x / 8) + 3];
-  }
-  result = svq1_decode_motion_vector (bitbuf, &motion[0], pmv);
-
-  if (result != 0)
-    return result;
-
-  /* predict and decode motion vector (2) */
-  pmv[1] = &motion[0];
-  pmv[2] = &motion[(x / 8) + 1];
-
-  result = svq1_decode_motion_vector (bitbuf, &motion[(x / 8) + 2], pmv);
-
-  if (result != 0)
-    return result;
-
-  /* predict and decode motion vector (3) */
-  pmv[2] = &motion[(x / 8) + 2];
-  pmv[3] = &motion[(x / 8) + 3];
-
-  result = svq1_decode_motion_vector (bitbuf, pmv[3], pmv);
-
-  if (result != 0)
-    return result;
-
-  /* form predictions */
-  for (i=0; i < 4; i++) {
-    int mvx= pmv[i]->x + (i&1)*16;
-    int mvy= pmv[i]->y + (i>>1)*16;
-
-    ///XXX /FIXME clipping or padding?
-    if(y + (mvy >> 1)<0)
-       mvy= 0;
-    if(x + (mvx >> 1)<0)
-       mvx= 0;
-
-    src = &previous[(x + (mvx >> 1)) + (y + (mvy >> 1))*pitch];
+    src = &previous[x + y * pitch];
     dst = current;
 
-    s->dsp.put_pixels_tab[1][((mvy & 1) << 1) | (mvx & 1)](dst,src,pitch,8);
-
-    /* select next block */
-    if (i & 1) {
-      current  += 8*(pitch - 1);
-    } else {
-      current  += 8;
+    for (i = 0; i < 16; i++) {
+        memcpy(dst, src, 16);
+        src += pitch;
+        dst += pitch;
     }
-  }
-
-  return 0;
 }
 
-static int svq1_decode_delta_block (MpegEncContext *s, GetBitContext *bitbuf,
-                        uint8_t *current, uint8_t *previous, int pitch,
-                        svq1_pmv *motion, int x, int y) {
-  uint32_t block_type;
-  int      result = 0;
-
-  /* get block type */
-  block_type = get_vlc2(bitbuf, svq1_block_type.table, 2, 2);
-
-  /* reset motion vectors */
-  if (block_type == SVQ1_BLOCK_SKIP || block_type == SVQ1_BLOCK_INTRA) {
-    motion[0].x                 =
-    motion[0].y                 =
-    motion[(x / 8) + 2].x =
-    motion[(x / 8) + 2].y =
-    motion[(x / 8) + 3].x =
-    motion[(x / 8) + 3].y = 0;
-  }
-
-  switch (block_type) {
-  case SVQ1_BLOCK_SKIP:
-    svq1_skip_block (current, previous, pitch, x, y);
-    break;
-
-  case SVQ1_BLOCK_INTER:
-    result = svq1_motion_inter_block (s, bitbuf, current, previous, pitch, motion, x, y);
-
-    if (result != 0)
-    {
-      av_dlog(s->avctx, "Error in svq1_motion_inter_block %i\n", result);
-      break;
-    }
-    result = svq1_decode_block_non_intra (bitbuf, current, pitch);
-    break;
-
-  case SVQ1_BLOCK_INTER_4V:
-    result = svq1_motion_inter_4v_block (s, bitbuf, current, previous, pitch, motion, x, y);
-
-    if (result != 0)
-    {
-      av_dlog(s->avctx, "Error in svq1_motion_inter_4v_block %i\n", result);
-      break;
-    }
-    result = svq1_decode_block_non_intra (bitbuf, current, pitch);
-    break;
-
-  case SVQ1_BLOCK_INTRA:
-    result = svq1_decode_block_intra (bitbuf, current, pitch);
-    break;
-  }
-
-  return result;
-}
-
-static void svq1_parse_string (GetBitContext *bitbuf, uint8_t *out) {
-  uint8_t seed;
-  int     i;
-
-  out[0] = get_bits (bitbuf, 8);
-
-  seed = string_table[out[0]];
-
-  for (i=1; i <= out[0]; i++) {
-    out[i] = get_bits (bitbuf, 8) ^ seed;
-    seed   = string_table[out[i] ^ seed];
-  }
-}
-
-static int svq1_decode_frame_header (GetBitContext *bitbuf,MpegEncContext *s) {
-  int frame_size_code;
-
-  skip_bits(bitbuf, 8); /* temporal_reference */
-
-  /* frame type */
-  s->pict_type= get_bits (bitbuf, 2)+1;
-  if(s->pict_type==4)
-      return -1;
-
-  if (s->pict_type == AV_PICTURE_TYPE_I) {
-
-    /* unknown fields */
-    if (s->f_code == 0x50 || s->f_code == 0x60) {
-      int csum = get_bits (bitbuf, 16);
-
-      csum = ff_svq1_packet_checksum (bitbuf->buffer, bitbuf->size_in_bits>>3, csum);
-
-      av_dlog(s->avctx, "%s checksum (%02x) for packet data\n",
-              (csum == 0) ? "correct" : "incorrect", csum);
-    }
-
-    if ((s->f_code ^ 0x10) >= 0x50) {
-      uint8_t msg[256];
-
-      svq1_parse_string (bitbuf, msg);
-
-      av_log(s->avctx, AV_LOG_INFO, "embedded message: \"%s\"\n", (char *) msg);
-    }
-
-    skip_bits (bitbuf, 2);
-    skip_bits (bitbuf, 2);
-    skip_bits1 (bitbuf);
-
-    /* load frame size */
-    frame_size_code = get_bits (bitbuf, 3);
-
-    if (frame_size_code == 7) {
-      /* load width, height (12 bits each) */
-      s->width = get_bits (bitbuf, 12);
-      s->height = get_bits (bitbuf, 12);
-
-      if (!s->width || !s->height)
-        return -1;
-    } else {
-      /* get width, height from table */
-      s->width = ff_svq1_frame_size_table[frame_size_code].width;
-      s->height = ff_svq1_frame_size_table[frame_size_code].height;
-    }
-  }
-
-  /* unknown fields */
-  if (get_bits1 (bitbuf) == 1) {
-    skip_bits1 (bitbuf);       /* use packet checksum if (1) */
-    skip_bits1 (bitbuf);       /* component checksums after image data if (1) */
-
-    if (get_bits (bitbuf, 2) != 0)
-      return -1;
-  }
-
-  if (get_bits1 (bitbuf) == 1) {
-    skip_bits1 (bitbuf);
-    skip_bits (bitbuf, 4);
-    skip_bits1 (bitbuf);
-    skip_bits (bitbuf, 2);
-
-    while (get_bits1 (bitbuf) == 1) {
-      skip_bits (bitbuf, 8);
-    }
-  }
-
-  return 0;
-}
-
-static int svq1_decode_frame(AVCodecContext *avctx,
-                             void *data, int *data_size,
-                             AVPacket *avpkt)
+static int svq1_motion_inter_block(MpegEncContext *s, GetBitContext *bitbuf,
+                                   uint8_t *current, uint8_t *previous,
+                                   int pitch, svq1_pmv *motion, int x, int y)
 {
-  const uint8_t *buf = avpkt->data;
-  int buf_size = avpkt->size;
-  MpegEncContext *s=avctx->priv_data;
-  uint8_t        *current, *previous;
-  int             result, i, x, y, width, height;
-  AVFrame *pict = data;
-  svq1_pmv *pmv;
+    uint8_t *src;
+    uint8_t *dst;
+    svq1_pmv mv;
+    svq1_pmv *pmv[3];
+    int result;
 
-  /* initialize bit buffer */
-  init_get_bits(&s->gb,buf,buf_size*8);
+    /* predict and decode motion vector */
+    pmv[0] = &motion[0];
+    if (y == 0) {
+        pmv[1] =
+        pmv[2] = pmv[0];
+    } else {
+        pmv[1] = &motion[x / 8 + 2];
+        pmv[2] = &motion[x / 8 + 4];
+    }
 
-  /* decode frame header */
-  s->f_code = get_bits (&s->gb, 22);
+    result = svq1_decode_motion_vector(bitbuf, &mv, pmv);
+    if (result)
+        return result;
 
-  if ((s->f_code & ~0x70) || !(s->f_code & 0x60))
-    return -1;
+    motion[0].x         =
+    motion[x / 8 + 2].x =
+    motion[x / 8 + 3].x = mv.x;
+    motion[0].y         =
+    motion[x / 8 + 2].y =
+    motion[x / 8 + 3].y = mv.y;
 
-  /* swap some header bytes (why?) */
-  if (s->f_code != 0x20) {
-    uint32_t *src = (uint32_t *) (buf + 4);
+    if (y + (mv.y >> 1) < 0)
+        mv.y = 0;
+    if (x + (mv.x >> 1) < 0)
+        mv.x = 0;
 
-    if (buf_size < 36)
+    src = &previous[(x + (mv.x >> 1)) + (y + (mv.y >> 1)) * pitch];
+    dst = current;
+
+    s->dsp.put_pixels_tab[0][(mv.y & 1) << 1 | (mv.x & 1)](dst, src, pitch, 16);
+
+    return 0;
+}
+
+static int svq1_motion_inter_4v_block(MpegEncContext *s, GetBitContext *bitbuf,
+                                      uint8_t *current, uint8_t *previous,
+                                      int pitch, svq1_pmv *motion, int x, int y)
+{
+    uint8_t *src;
+    uint8_t *dst;
+    svq1_pmv mv;
+    svq1_pmv *pmv[4];
+    int i, result;
+
+    /* predict and decode motion vector (0) */
+    pmv[0] = &motion[0];
+    if (y == 0) {
+        pmv[1] =
+        pmv[2] = pmv[0];
+    } else {
+        pmv[1] = &motion[(x / 8) + 2];
+        pmv[2] = &motion[(x / 8) + 4];
+    }
+
+    result = svq1_decode_motion_vector(bitbuf, &mv, pmv);
+    if (result)
+        return result;
+
+    /* predict and decode motion vector (1) */
+    pmv[0] = &mv;
+    if (y == 0) {
+        pmv[1] =
+        pmv[2] = pmv[0];
+    } else {
+        pmv[1] = &motion[(x / 8) + 3];
+    }
+    result = svq1_decode_motion_vector(bitbuf, &motion[0], pmv);
+    if (result)
+        return result;
+
+    /* predict and decode motion vector (2) */
+    pmv[1] = &motion[0];
+    pmv[2] = &motion[(x / 8) + 1];
+
+    result = svq1_decode_motion_vector(bitbuf, &motion[(x / 8) + 2], pmv);
+    if (result)
+        return result;
+
+    /* predict and decode motion vector (3) */
+    pmv[2] = &motion[(x / 8) + 2];
+    pmv[3] = &motion[(x / 8) + 3];
+
+    result = svq1_decode_motion_vector(bitbuf, pmv[3], pmv);
+    if (result)
+        return result;
+
+    /* form predictions */
+    for (i = 0; i < 4; i++) {
+        int mvx = pmv[i]->x + (i  & 1) * 16;
+        int mvy = pmv[i]->y + (i >> 1) * 16;
+
+        // FIXME: clipping or padding?
+        if (y + (mvy >> 1) < 0)
+            mvy = 0;
+        if (x + (mvx >> 1) < 0)
+            mvx = 0;
+
+        src = &previous[(x + (mvx >> 1)) + (y + (mvy >> 1)) * pitch];
+        dst = current;
+
+        s->dsp.put_pixels_tab[1][((mvy & 1) << 1) | (mvx & 1)](dst, src, pitch, 8);
+
+        /* select next block */
+        if (i & 1)
+            current += 8 * (pitch - 1);
+        else
+            current += 8;
+    }
+
+    return 0;
+}
+
+static int svq1_decode_delta_block(MpegEncContext *s, GetBitContext *bitbuf,
+                                   uint8_t *current, uint8_t *previous,
+                                   int pitch, svq1_pmv *motion, int x, int y)
+{
+    uint32_t block_type;
+    int result = 0;
+
+    /* get block type */
+    block_type = get_vlc2(bitbuf, svq1_block_type.table, 2, 2);
+
+    /* reset motion vectors */
+    if (block_type == SVQ1_BLOCK_SKIP || block_type == SVQ1_BLOCK_INTRA) {
+        motion[0].x         =
+        motion[0].y         =
+        motion[x / 8 + 2].x =
+        motion[x / 8 + 2].y =
+        motion[x / 8 + 3].x =
+        motion[x / 8 + 3].y = 0;
+    }
+
+    switch (block_type) {
+    case SVQ1_BLOCK_SKIP:
+        svq1_skip_block(current, previous, pitch, x, y);
+        break;
+
+    case SVQ1_BLOCK_INTER:
+        result = svq1_motion_inter_block(s, bitbuf, current, previous,
+                                         pitch, motion, x, y);
+        if (result) {
+            av_dlog(s->avctx, "Error in svq1_motion_inter_block %i\n", result);
+            break;
+        }
+        result = svq1_decode_block_non_intra(bitbuf, current, pitch);
+        break;
+
+    case SVQ1_BLOCK_INTER_4V:
+        result = svq1_motion_inter_4v_block(s, bitbuf, current, previous,
+                                            pitch, motion, x, y);
+        if (result) {
+            av_dlog(s->avctx,
+                    "Error in svq1_motion_inter_4v_block %i\n", result);
+            break;
+        }
+        result = svq1_decode_block_non_intra(bitbuf, current, pitch);
+        break;
+
+    case SVQ1_BLOCK_INTRA:
+        result = svq1_decode_block_intra(bitbuf, current, pitch);
+        break;
+    }
+
+    return result;
+}
+
+static void svq1_parse_string(GetBitContext *bitbuf, uint8_t *out)
+{
+    uint8_t seed;
+    int i;
+
+    out[0] = get_bits(bitbuf, 8);
+    seed   = string_table[out[0]];
+
+    for (i = 1; i <= out[0]; i++) {
+        out[i] = get_bits(bitbuf, 8) ^ seed;
+        seed   = string_table[out[i] ^ seed];
+    }
+}
+
+static int svq1_decode_frame_header(GetBitContext *bitbuf, MpegEncContext *s)
+{
+    int frame_size_code;
+    int width  = s->width;
+    int height = s->height;
+
+    skip_bits(bitbuf, 8); /* temporal_reference */
+
+    /* frame type */
+    s->pict_type = get_bits(bitbuf, 2) + 1;
+    if (s->pict_type == 4)
         return AVERROR_INVALIDDATA;
 
-    for (i=0; i < 4; i++) {
-      src[i] = ((src[i] << 16) | (src[i] >> 16)) ^ src[7 - i];
-    }
-  }
-
-  result = svq1_decode_frame_header (&s->gb, s);
-
-  if (result != 0)
-  {
-    av_dlog(s->avctx, "Error in svq1_decode_frame_header %i\n",result);
-    return result;
-  }
-  avcodec_set_dimensions(avctx, s->width, s->height);
-
-  //FIXME this avoids some confusion for "B frames" without 2 references
-  //this should be removed after libavcodec can handle more flexible picture types & ordering
-  if(s->pict_type==AV_PICTURE_TYPE_B && s->last_picture_ptr==NULL) return buf_size;
-
-  if(  (avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type==AV_PICTURE_TYPE_B)
-     ||(avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type!=AV_PICTURE_TYPE_I)
-     || avctx->skip_frame >= AVDISCARD_ALL)
-      return buf_size;
-
-  if(ff_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;
-    if (i == 0) {
-      width  = FFALIGN(s->width, 16);
-      height = FFALIGN(s->height, 16);
-      linesize= s->linesize;
-    } else {
-      if(s->flags&CODEC_FLAG_GRAY) break;
-      width  = FFALIGN(s->width/4, 16);
-      height = FFALIGN(s->height/4, 16);
-      linesize= s->uvlinesize;
-    }
-
-    current = s->current_picture.f.data[i];
-
-    if(s->pict_type==AV_PICTURE_TYPE_B){
-        previous = s->next_picture.f.data[i];
-    }else{
-        previous = s->last_picture.f.data[i];
-    }
-
     if (s->pict_type == AV_PICTURE_TYPE_I) {
-      /* keyframe */
-      for (y=0; y < height; y+=16) {
-        for (x=0; x < width; x+=16) {
-          result = svq1_decode_block_intra (&s->gb, &current[x], linesize);
-          if (result != 0)
-          {
-            av_log(s->avctx, AV_LOG_ERROR, "Error in svq1_decode_block %i (keyframe)\n",result);
-            goto err;
-          }
-        }
-        current += 16*linesize;
-      }
-    } else {
-      /* delta frame */
-      memset (pmv, 0, ((width / 8) + 3) * sizeof(svq1_pmv));
+        /* unknown fields */
+        if (s->f_code == 0x50 || s->f_code == 0x60) {
+            int csum = get_bits(bitbuf, 16);
 
-      for (y=0; y < height; y+=16) {
-        for (x=0; x < width; x+=16) {
-          result = svq1_decode_delta_block (s, &s->gb, &current[x], previous,
-                                            linesize, pmv, x, y);
-          if (result != 0)
-          {
-            av_dlog(s->avctx, "Error in svq1_decode_delta_block %i\n",result);
-            goto err;
-          }
+            csum = ff_svq1_packet_checksum(bitbuf->buffer,
+                                           bitbuf->size_in_bits >> 3,
+                                           csum);
+
+            av_dlog(s->avctx, "%s checksum (%02x) for packet data\n",
+                    (csum == 0) ? "correct" : "incorrect", csum);
         }
 
-        pmv[0].x =
-        pmv[0].y = 0;
+        if ((s->f_code ^ 0x10) >= 0x50) {
+            uint8_t msg[256];
 
-        current += 16*linesize;
-      }
+            svq1_parse_string(bitbuf, msg);
+
+            av_log(s->avctx, AV_LOG_INFO,
+                   "embedded message: \"%s\"\n", (char *)msg);
+        }
+
+        skip_bits(bitbuf, 2);
+        skip_bits(bitbuf, 2);
+        skip_bits1(bitbuf);
+
+        /* load frame size */
+        frame_size_code = get_bits(bitbuf, 3);
+
+        if (frame_size_code == 7) {
+            /* load width, height (12 bits each) */
+            width  = get_bits(bitbuf, 12);
+            height = get_bits(bitbuf, 12);
+
+            if (!width || !height)
+                return AVERROR_INVALIDDATA;
+        } else {
+            /* get width, height from table */
+            width  = ff_svq1_frame_size_table[frame_size_code].width;
+            height = ff_svq1_frame_size_table[frame_size_code].height;
+        }
     }
-  }
 
-  *pict = s->current_picture.f;
+    /* unknown fields */
+    if (get_bits1(bitbuf)) {
+        skip_bits1(bitbuf);    /* use packet checksum if (1) */
+        skip_bits1(bitbuf);    /* component checksums after image data if (1) */
 
+        if (get_bits(bitbuf, 2) != 0)
+            return AVERROR_INVALIDDATA;
+    }
 
-  ff_MPV_frame_end(s);
+    if (get_bits1(bitbuf)) {
+        skip_bits1(bitbuf);
+        skip_bits(bitbuf, 4);
+        skip_bits1(bitbuf);
+        skip_bits(bitbuf, 2);
 
-  *data_size=sizeof(AVFrame);
-  result = buf_size;
+        while (get_bits1(bitbuf))
+            skip_bits(bitbuf, 8);
+    }
+
+    s->width  = width;
+    s->height = height;
+    return 0;
+}
+
+static int svq1_decode_frame(AVCodecContext *avctx, void *data,
+                             int *data_size, AVPacket *avpkt)
+{
+    const uint8_t *buf = avpkt->data;
+    int buf_size       = avpkt->size;
+    MpegEncContext *s  = avctx->priv_data;
+    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);
+
+    /* decode frame header */
+    s->f_code = get_bits(&s->gb, 22);
+
+    if ((s->f_code & ~0x70) || !(s->f_code & 0x60))
+        return AVERROR_INVALIDDATA;
+
+    /* swap some header bytes (why?) */
+    if (s->f_code != 0x20) {
+        uint32_t *src = (uint32_t *)(buf + 4);
+
+        if (buf_size < 36)
+            return AVERROR_INVALIDDATA;
+
+        for (i = 0; i < 4; i++)
+            src[i] = ((src[i] << 16) | (src[i] >> 16)) ^ src[7 - i];
+    }
+
+    result = svq1_decode_frame_header(&s->gb, s);
+    if (result) {
+        av_dlog(s->avctx, "Error in svq1_decode_frame_header %i\n", result);
+        return result;
+    }
+    avcodec_set_dimensions(avctx, s->width, s->height);
+
+    /* FIXME: This avoids some confusion for "B frames" without 2 references.
+     * This should be removed after libavcodec can handle more flexible
+     * picture types & ordering */
+    if (s->pict_type == AV_PICTURE_TYPE_B && s->last_picture_ptr == NULL)
+        return buf_size;
+
+    if ((avctx->skip_frame >= AVDISCARD_NONREF &&
+         s->pict_type == AV_PICTURE_TYPE_B)    ||
+        (avctx->skip_frame >= AVDISCARD_NONKEY &&
+         s->pict_type != AV_PICTURE_TYPE_I)    ||
+        avctx->skip_frame >= AVDISCARD_ALL)
+        return buf_size;
+
+    if ((result = ff_MPV_frame_start(s, avctx)) < 0)
+        return result;
+
+    pmv = av_malloc((FFALIGN(s->width, 16) / 8 + 3) * sizeof(*pmv));
+    if (!pmv)
+        return AVERROR(ENOMEM);
+
+    /* decode y, u and v components */
+    for (i = 0; i < 3; i++) {
+        int linesize;
+        if (i == 0) {
+            width    = FFALIGN(s->width,  16);
+            height   = FFALIGN(s->height, 16);
+            linesize = s->linesize;
+        } else {
+            if (s->flags & CODEC_FLAG_GRAY)
+                break;
+            width    = FFALIGN(s->width  / 4, 16);
+            height   = FFALIGN(s->height / 4, 16);
+            linesize = s->uvlinesize;
+        }
+
+        current = s->current_picture.f.data[i];
+
+        if (s->pict_type == AV_PICTURE_TYPE_B)
+            previous = s->next_picture.f.data[i];
+        else
+            previous = s->last_picture.f.data[i];
+
+        if (s->pict_type == AV_PICTURE_TYPE_I) {
+            /* keyframe */
+            for (y = 0; y < height; y += 16) {
+                for (x = 0; x < width; x += 16) {
+                    result = svq1_decode_block_intra(&s->gb, &current[x],
+                                                     linesize);
+                    if (result) {
+                        av_log(s->avctx, AV_LOG_ERROR,
+                               "Error in svq1_decode_block %i (keyframe)\n",
+                               result);
+                        goto err;
+                    }
+                }
+                current += 16 * linesize;
+            }
+        } else {
+            /* delta frame */
+            memset(pmv, 0, ((width / 8) + 3) * sizeof(svq1_pmv));
+
+            for (y = 0; y < height; y += 16) {
+                for (x = 0; x < width; x += 16) {
+                    result = svq1_decode_delta_block(s, &s->gb, &current[x],
+                                                     previous, linesize,
+                                                     pmv, x, y);
+                    if (result) {
+                        av_dlog(s->avctx,
+                                "Error in svq1_decode_delta_block %i\n",
+                                result);
+                        goto err;
+                    }
+                }
+
+                pmv[0].x     =
+                    pmv[0].y = 0;
+
+                current += 16 * linesize;
+            }
+        }
+    }
+
+    *pict = s->current_picture.f;
+    pict->qscale_table = NULL;
+
+    ff_MPV_frame_end(s);
+
+    *data_size = sizeof(AVFrame);
+    result     = buf_size;
+
 err:
-  av_free(pmv);
-  return result;
+    av_free(pmv);
+    return result;
 }
 
 static av_cold int svq1_decode_init(AVCodecContext *avctx)
@@ -713,47 +723,52 @@
 
     ff_MPV_decode_defaults(s);
 
-    s->avctx = avctx;
-    s->width = (avctx->width+3)&~3;
-    s->height = (avctx->height+3)&~3;
-    s->codec_id= avctx->codec->id;
-    avctx->pix_fmt = PIX_FMT_YUV410P;
-    avctx->has_b_frames= 1; // not true, but DP frames and these behave like unidirectional b frames
-    s->flags= avctx->flags;
-    if (ff_MPV_common_init(s) < 0) return -1;
+    s->avctx            = avctx;
+    s->width            = avctx->width  + 3 & ~3;
+    s->height           = avctx->height + 3 & ~3;
+    s->codec_id         = avctx->codec->id;
+    avctx->pix_fmt      = AV_PIX_FMT_YUV410P;
+    /* Not true, but DP frames and these behave like unidirectional B-frames. */
+    avctx->has_b_frames = 1;
+    s->flags            = avctx->flags;
+    if (ff_MPV_common_init(s) < 0)
+        return -1;
 
     INIT_VLC_STATIC(&svq1_block_type, 2, 4,
-        &ff_svq1_block_type_vlc[0][1], 2, 1,
-        &ff_svq1_block_type_vlc[0][0], 2, 1, 6);
+                    &ff_svq1_block_type_vlc[0][1], 2, 1,
+                    &ff_svq1_block_type_vlc[0][0], 2, 1, 6);
 
     INIT_VLC_STATIC(&svq1_motion_component, 7, 33,
-        &ff_mvtab[0][1], 2, 1,
-        &ff_mvtab[0][0], 2, 1, 176);
+                    &ff_mvtab[0][1], 2, 1,
+                    &ff_mvtab[0][0], 2, 1, 176);
 
     for (i = 0; i < 6; i++) {
-        static const uint8_t sizes[2][6] = {{14, 10, 14, 18, 16, 18}, {10, 10, 14, 14, 14, 16}};
+        static const uint8_t sizes[2][6] = { { 14, 10, 14, 18, 16, 18 },
+                                             { 10, 10, 14, 14, 14, 16 } };
         static VLC_TYPE table[168][2];
-        svq1_intra_multistage[i].table = &table[offset];
+        svq1_intra_multistage[i].table           = &table[offset];
         svq1_intra_multistage[i].table_allocated = sizes[0][i];
-        offset += sizes[0][i];
+        offset                                  += sizes[0][i];
         init_vlc(&svq1_intra_multistage[i], 3, 8,
-            &ff_svq1_intra_multistage_vlc[i][0][1], 2, 1,
-            &ff_svq1_intra_multistage_vlc[i][0][0], 2, 1, INIT_VLC_USE_NEW_STATIC);
-        svq1_inter_multistage[i].table = &table[offset];
+                 &ff_svq1_intra_multistage_vlc[i][0][1], 2, 1,
+                 &ff_svq1_intra_multistage_vlc[i][0][0], 2, 1,
+                 INIT_VLC_USE_NEW_STATIC);
+        svq1_inter_multistage[i].table           = &table[offset];
         svq1_inter_multistage[i].table_allocated = sizes[1][i];
-        offset += sizes[1][i];
+        offset                                  += sizes[1][i];
         init_vlc(&svq1_inter_multistage[i], 3, 8,
-            &ff_svq1_inter_multistage_vlc[i][0][1], 2, 1,
-            &ff_svq1_inter_multistage_vlc[i][0][0], 2, 1, INIT_VLC_USE_NEW_STATIC);
+                 &ff_svq1_inter_multistage_vlc[i][0][1], 2, 1,
+                 &ff_svq1_inter_multistage_vlc[i][0][0], 2, 1,
+                 INIT_VLC_USE_NEW_STATIC);
     }
 
     INIT_VLC_STATIC(&svq1_intra_mean, 8, 256,
-        &ff_svq1_intra_mean_vlc[0][1], 4, 2,
-        &ff_svq1_intra_mean_vlc[0][0], 4, 2, 632);
+                    &ff_svq1_intra_mean_vlc[0][1], 4, 2,
+                    &ff_svq1_intra_mean_vlc[0][0], 4, 2, 632);
 
     INIT_VLC_STATIC(&svq1_inter_mean, 9, 512,
-        &ff_svq1_inter_mean_vlc[0][1], 4, 2,
-        &ff_svq1_inter_mean_vlc[0][0], 4, 2, 1434);
+                    &ff_svq1_inter_mean_vlc[0][1], 4, 2,
+                    &ff_svq1_inter_mean_vlc[0][0], 4, 2, 1434);
 
     return 0;
 }
@@ -766,7 +781,6 @@
     return 0;
 }
 
-
 AVCodec ff_svq1_decoder = {
     .name           = "svq1",
     .type           = AVMEDIA_TYPE_VIDEO,
@@ -777,6 +791,7 @@
     .decode         = svq1_decode_frame,
     .capabilities   = CODEC_CAP_DR1,
     .flush          = ff_mpeg_flush,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUV410P, PIX_FMT_NONE },
+    .pix_fmts       = (const enum PixelFormat[]) { AV_PIX_FMT_YUV410P,
+                                                   AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("Sorenson Vector Quantizer 1 / Sorenson Video 1 / SVQ1"),
 };
diff --git a/libavcodec/svq1enc.c b/libavcodec/svq1enc.c
index edd3507..0877795 100644
--- a/libavcodec/svq1enc.c
+++ b/libavcodec/svq1enc.c
@@ -26,21 +26,21 @@
  *   http://www.pcisys.net/~melanson/codecs/
  */
 
-
 #include "avcodec.h"
 #include "dsputil.h"
 #include "mpegvideo.h"
 #include "h263.h"
 #include "internal.h"
 #include "libavutil/avassert.h"
-
 #include "svq1.h"
 #include "svq1enc_cb.h"
 
 
-
 typedef struct SVQ1Context {
-    MpegEncContext m; // needed for motion estimation, should not be used for anything else, the idea is to make the motion estimation eventually independent of MpegEncContext, so this will be removed then (FIXME/XXX)
+    /* FIXME: Needed for motion estimation, should not be used for anything
+     * else, the idea is to make the motion estimation eventually independent
+     * of MpegEncContext, so this will be removed then. */
+    MpegEncContext m;
     AVCodecContext *avctx;
     DSPContext dsp;
     AVFrame picture;
@@ -49,7 +49,9 @@
     PutBitContext pb;
     GetBitContext gb;
 
-    PutBitContext reorder_pb[6]; //why ooh why this sick breadth first order, everything is slower and more complex
+    /* why ooh why this sick breadth first order,
+     * everything is slower and more complex */
+    PutBitContext reorder_pb[6];
 
     int frame_width;
     int frame_height;
@@ -86,21 +88,19 @@
     put_bits(&s->pb, 2, frame_type - 1);
 
     if (frame_type == AV_PICTURE_TYPE_I) {
-
         /* no checksum since frame code is 0x20 */
-
         /* no embedded string either */
-
         /* output 5 unknown bits (2 + 2 + 1) */
         put_bits(&s->pb, 5, 2); /* 2 needed by quicktime decoder */
 
-        i= ff_match_2uint16((void*)ff_svq1_frame_size_table, FF_ARRAY_ELEMS(ff_svq1_frame_size_table), s->frame_width, s->frame_height);
+        i = ff_match_2uint16((void*)ff_svq1_frame_size_table,
+                             FF_ARRAY_ELEMS(ff_svq1_frame_size_table),
+                             s->frame_width, s->frame_height);
         put_bits(&s->pb, 3, i);
 
-        if (i == 7)
-        {
-                put_bits(&s->pb, 12, s->frame_width);
-                put_bits(&s->pb, 12, s->frame_height);
+        if (i == 7) {
+            put_bits(&s->pb, 12, s->frame_width);
+            put_bits(&s->pb, 12, s->frame_height);
         }
     }
 
@@ -108,391 +108,423 @@
     put_bits(&s->pb, 2, 0);
 }
 
-
-#define QUALITY_THRESHOLD 100
+#define QUALITY_THRESHOLD    100
 #define THRESHOLD_MULTIPLIER 0.6
 
-static int encode_block(SVQ1Context *s, uint8_t *src, uint8_t *ref, uint8_t *decoded, int stride, int level, int threshold, int lambda, int intra){
+static int encode_block(SVQ1Context *s, uint8_t *src, uint8_t *ref,
+                        uint8_t *decoded, int stride, int level,
+                        int threshold, int lambda, int intra)
+{
     int count, y, x, i, j, split, best_mean, best_score, best_count;
     int best_vector[6];
-    int block_sum[7]= {0, 0, 0, 0, 0, 0};
-    int w= 2<<((level+2)>>1);
-    int h= 2<<((level+1)>>1);
-    int size=w*h;
+    int block_sum[7] = { 0, 0, 0, 0, 0, 0 };
+    int w            = 2 << (level + 2 >> 1);
+    int h            = 2 << (level + 1 >> 1);
+    int size         = w * h;
     int16_t block[7][256];
     const int8_t *codebook_sum, *codebook;
-    const uint16_t (*mean_vlc)[2];
-    const uint8_t (*multistage_vlc)[2];
+    const uint16_t(*mean_vlc)[2];
+    const uint8_t(*multistage_vlc)[2];
 
-    best_score=0;
-    //FIXME optimize, this doenst need to be done multiple times
-    if(intra){
-        codebook_sum= svq1_intra_codebook_sum[level];
-        codebook= ff_svq1_intra_codebooks[level];
-        mean_vlc= ff_svq1_intra_mean_vlc;
-        multistage_vlc= ff_svq1_intra_multistage_vlc[level];
-        for(y=0; y<h; y++){
-            for(x=0; x<w; x++){
-                int v= src[x + y*stride];
-                block[0][x + w*y]= v;
-                best_score += v*v;
-                block_sum[0] += v;
+    best_score = 0;
+    // FIXME: Optimize, this does not need to be done multiple times.
+    if (intra) {
+        codebook_sum   = svq1_intra_codebook_sum[level];
+        codebook       = ff_svq1_intra_codebooks[level];
+        mean_vlc       = ff_svq1_intra_mean_vlc;
+        multistage_vlc = ff_svq1_intra_multistage_vlc[level];
+        for (y = 0; y < h; y++) {
+            for (x = 0; x < w; x++) {
+                int v = src[x + y * stride];
+                block[0][x + w * y] = v;
+                best_score         += v * v;
+                block_sum[0]       += v;
             }
         }
-    }else{
-        codebook_sum= svq1_inter_codebook_sum[level];
-        codebook= ff_svq1_inter_codebooks[level];
-        mean_vlc= ff_svq1_inter_mean_vlc + 256;
-        multistage_vlc= ff_svq1_inter_multistage_vlc[level];
-        for(y=0; y<h; y++){
-            for(x=0; x<w; x++){
-                int v= src[x + y*stride] - ref[x + y*stride];
-                block[0][x + w*y]= v;
-                best_score += v*v;
-                block_sum[0] += v;
+    } else {
+        codebook_sum   = svq1_inter_codebook_sum[level];
+        codebook       = ff_svq1_inter_codebooks[level];
+        mean_vlc       = ff_svq1_inter_mean_vlc + 256;
+        multistage_vlc = ff_svq1_inter_multistage_vlc[level];
+        for (y = 0; y < h; y++) {
+            for (x = 0; x < w; x++) {
+                int v = src[x + y * stride] - ref[x + y * stride];
+                block[0][x + w * y] = v;
+                best_score         += v * v;
+                block_sum[0]       += v;
             }
         }
     }
 
-    best_count=0;
-    best_score -= (int)(((unsigned)block_sum[0]*block_sum[0])>>(level+3));
-    best_mean= (block_sum[0] + (size>>1)) >> (level+3);
+    best_count  = 0;
+    best_score -= (int)((unsigned)block_sum[0] * block_sum[0] >> (level + 3));
+    best_mean   = block_sum[0] + (size >> 1) >> (level + 3);
 
-    if(level<4){
-        for(count=1; count<7; count++){
-            int best_vector_score= INT_MAX;
-            int best_vector_sum=-999, best_vector_mean=-999;
-            const int stage= count-1;
+    if (level < 4) {
+        for (count = 1; count < 7; count++) {
+            int best_vector_score = INT_MAX;
+            int best_vector_sum   = -999, best_vector_mean = -999;
+            const int stage       = count - 1;
             const int8_t *vector;
 
-            for(i=0; i<16; i++){
-                int sum= codebook_sum[stage*16 + i];
+            for (i = 0; i < 16; i++) {
+                int sum = codebook_sum[stage * 16 + i];
                 int sqr, diff, score;
 
-                vector = codebook + stage*size*16 + i*size;
-                sqr = s->dsp.ssd_int8_vs_int16(vector, block[stage], size);
-                diff= block_sum[stage] - sum;
-                score= sqr - ((diff*(int64_t)diff)>>(level+3)); //FIXME 64bit slooow
-                if(score < best_vector_score){
-                    int mean= (diff + (size>>1)) >> (level+3);
-                    av_assert2(mean >-300 && mean<300);
-                    mean= av_clip(mean, intra?0:-256, 255);
-                    best_vector_score= score;
-                    best_vector[stage]= i;
-                    best_vector_sum= sum;
-                    best_vector_mean= mean;
+                vector = codebook + stage * size * 16 + i * size;
+                sqr    = s->dsp.ssd_int8_vs_int16(vector, block[stage], size);
+                diff   = block_sum[stage] - sum;
+                score  = sqr - (diff * (int64_t)diff >> (level + 3)); // FIXME: 64bit slooow
+                if (score < best_vector_score) {
+                    int mean = diff + (size >> 1) >> (level + 3);
+                    av_assert2(mean > -300 && mean < 300);
+                    mean               = av_clip(mean, intra ? 0 : -256, 255);
+                    best_vector_score  = score;
+                    best_vector[stage] = i;
+                    best_vector_sum    = sum;
+                    best_vector_mean   = mean;
                 }
             }
             av_assert0(best_vector_mean != -999);
-            vector= codebook + stage*size*16 + best_vector[stage]*size;
-            for(j=0; j<size; j++){
-                block[stage+1][j] = block[stage][j] - vector[j];
-            }
-            block_sum[stage+1]= block_sum[stage] - best_vector_sum;
-            best_vector_score +=
-                lambda*(+ 1 + 4*count
-                        + multistage_vlc[1+count][1]
-                        + mean_vlc[best_vector_mean][1]);
+            vector = codebook + stage * size * 16 + best_vector[stage] * size;
+            for (j = 0; j < size; j++)
+                block[stage + 1][j] = block[stage][j] - vector[j];
+            block_sum[stage + 1] = block_sum[stage] - best_vector_sum;
+            best_vector_score   += lambda *
+                                   (+1 + 4 * count +
+                                    multistage_vlc[1 + count][1]
+                                    + mean_vlc[best_vector_mean][1]);
 
-            if(best_vector_score < best_score){
-                best_score= best_vector_score;
-                best_count= count;
-                best_mean= best_vector_mean;
+            if (best_vector_score < best_score) {
+                best_score = best_vector_score;
+                best_count = count;
+                best_mean  = best_vector_mean;
             }
         }
     }
 
-    split=0;
-    if(best_score > threshold && level){
-        int score=0;
-        int offset= (level&1) ? stride*h/2 : w/2;
+    split = 0;
+    if (best_score > threshold && level) {
+        int score  = 0;
+        int offset = level & 1 ? stride * h / 2 : w / 2;
         PutBitContext backup[6];
 
-        for(i=level-1; i>=0; i--){
-            backup[i]= s->reorder_pb[i];
-        }
-        score += encode_block(s, src         , ref         , decoded         , stride, level-1, threshold>>1, lambda, intra);
-        score += encode_block(s, src + offset, ref + offset, decoded + offset, stride, level-1, threshold>>1, lambda, intra);
+        for (i = level - 1; i >= 0; i--)
+            backup[i] = s->reorder_pb[i];
+        score += encode_block(s, src, ref, decoded, stride, level - 1,
+                              threshold >> 1, lambda, intra);
+        score += encode_block(s, src + offset, ref + offset, decoded + offset,
+                              stride, level - 1, threshold >> 1, lambda, intra);
         score += lambda;
 
-        if(score < best_score){
-            best_score= score;
-            split=1;
-        }else{
-            for(i=level-1; i>=0; i--){
-                s->reorder_pb[i]= backup[i];
-            }
+        if (score < best_score) {
+            best_score = score;
+            split      = 1;
+        } else {
+            for (i = level - 1; i >= 0; i--)
+                s->reorder_pb[i] = backup[i];
         }
     }
     if (level > 0)
         put_bits(&s->reorder_pb[level], 1, split);
 
-    if(!split){
-        av_assert1((best_mean >= 0 && best_mean<256) || !intra);
-        av_assert1(best_mean >= -256 && best_mean<256);
-        av_assert1(best_count >=0 && best_count<7);
-        av_assert1(level<4 || best_count==0);
+    if (!split) {
+        av_assert1(best_mean >= 0 && best_mean < 256 || !intra);
+        av_assert1(best_mean >= -256 && best_mean < 256);
+        av_assert1(best_count >= 0 && best_count < 7);
+        av_assert1(level < 4 || best_count == 0);
 
         /* output the encoding */
         put_bits(&s->reorder_pb[level],
-            multistage_vlc[1 + best_count][1],
-            multistage_vlc[1 + best_count][0]);
+                 multistage_vlc[1 + best_count][1],
+                 multistage_vlc[1 + best_count][0]);
         put_bits(&s->reorder_pb[level], mean_vlc[best_mean][1],
-            mean_vlc[best_mean][0]);
+                 mean_vlc[best_mean][0]);
 
-        for (i = 0; i < best_count; i++){
-            av_assert2(best_vector[i]>=0 && best_vector[i]<16);
+        for (i = 0; i < best_count; i++) {
+            av_assert2(best_vector[i] >= 0 && best_vector[i] < 16);
             put_bits(&s->reorder_pb[level], 4, best_vector[i]);
         }
 
-        for(y=0; y<h; y++){
-            for(x=0; x<w; x++){
-                decoded[x + y*stride]= src[x + y*stride] - block[best_count][x + w*y] + best_mean;
-            }
-        }
+        for (y = 0; y < h; y++)
+            for (x = 0; x < w; x++)
+                decoded[x + y * stride] = src[x + y * stride] -
+                                          block[best_count][x + w * y] +
+                                          best_mean;
     }
 
     return best_score;
 }
 
-
-static int svq1_encode_plane(SVQ1Context *s, int plane, unsigned char *src_plane, unsigned char *ref_plane, unsigned char *decoded_plane,
-    int width, int height, int src_stride, int stride)
+static int svq1_encode_plane(SVQ1Context *s, int plane,
+                             unsigned char *src_plane,
+                             unsigned char *ref_plane,
+                             unsigned char *decoded_plane,
+                             int width, int height, int src_stride, int stride)
 {
     int x, y;
     int i;
     int block_width, block_height;
     int level;
     int threshold[6];
-    uint8_t *src = s->scratchbuf + stride * 16;
-    const int lambda= (s->picture.quality*s->picture.quality) >> (2*FF_LAMBDA_SHIFT);
+    uint8_t *src     = s->scratchbuf + stride * 16;
+    const int lambda = (s->picture.quality * s->picture.quality) >>
+                       (2 * FF_LAMBDA_SHIFT);
 
     /* figure out the acceptable level thresholds in advance */
     threshold[5] = QUALITY_THRESHOLD;
     for (level = 4; level >= 0; level--)
         threshold[level] = threshold[level + 1] * THRESHOLD_MULTIPLIER;
 
-    block_width = (width + 15) / 16;
+    block_width  = (width  + 15) / 16;
     block_height = (height + 15) / 16;
 
-    if(s->picture.pict_type == AV_PICTURE_TYPE_P){
-        s->m.avctx= s->avctx;
-        s->m.current_picture_ptr= &s->m.current_picture;
-        s->m.last_picture_ptr   = &s->m.last_picture;
-        s->m.last_picture.f.data[0] = ref_plane;
-        s->m.linesize=
-        s->m.last_picture.f.linesize[0] =
-        s->m.new_picture.f.linesize[0] =
+    if (s->picture.pict_type == AV_PICTURE_TYPE_P) {
+        s->m.avctx                         = s->avctx;
+        s->m.current_picture_ptr           = &s->m.current_picture;
+        s->m.last_picture_ptr              = &s->m.last_picture;
+        s->m.last_picture.f.data[0]        = ref_plane;
+        s->m.linesize                      =
+        s->m.last_picture.f.linesize[0]    =
+        s->m.new_picture.f.linesize[0]     =
         s->m.current_picture.f.linesize[0] = stride;
-        s->m.width= width;
-        s->m.height= height;
-        s->m.mb_width= block_width;
-        s->m.mb_height= block_height;
-        s->m.mb_stride= s->m.mb_width+1;
-        s->m.b8_stride= 2*s->m.mb_width+1;
-        s->m.f_code=1;
-        s->m.pict_type= s->picture.pict_type;
-        s->m.me_method= s->avctx->me_method;
-        s->m.me.scene_change_score=0;
-        s->m.flags= s->avctx->flags;
-//        s->m.out_format = FMT_H263;
-//        s->m.unrestricted_mv= 1;
+        s->m.width                         = width;
+        s->m.height                        = height;
+        s->m.mb_width                      = block_width;
+        s->m.mb_height                     = block_height;
+        s->m.mb_stride                     = s->m.mb_width + 1;
+        s->m.b8_stride                     = 2 * s->m.mb_width + 1;
+        s->m.f_code                        = 1;
+        s->m.pict_type                     = s->picture.pict_type;
+        s->m.me_method                     = s->avctx->me_method;
+        s->m.me.scene_change_score         = 0;
+        s->m.flags                         = s->avctx->flags;
+        // s->m.out_format                    = FMT_H263;
+        // s->m.unrestricted_mv               = 1;
+        s->m.lambda                        = s->picture.quality;
+        s->m.qscale                        = s->m.lambda * 139 +
+                                             FF_LAMBDA_SCALE * 64 >>
+                                             FF_LAMBDA_SHIFT + 7;
+        s->m.lambda2                       = s->m.lambda * s->m.lambda +
+                                             FF_LAMBDA_SCALE / 2 >>
+                                             FF_LAMBDA_SHIFT;
 
-        s->m.lambda= s->picture.quality;
-        s->m.qscale= (s->m.lambda*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);
-        s->m.lambda2= (s->m.lambda*s->m.lambda + FF_LAMBDA_SCALE/2) >> FF_LAMBDA_SHIFT;
-
-        if(!s->motion_val8[plane]){
-            s->motion_val8 [plane]= av_mallocz((s->m.b8_stride*block_height*2 + 2)*2*sizeof(int16_t));
-            s->motion_val16[plane]= av_mallocz((s->m.mb_stride*(block_height + 2) + 1)*2*sizeof(int16_t));
+        if (!s->motion_val8[plane]) {
+            s->motion_val8[plane]  = av_mallocz((s->m.b8_stride *
+                                                 block_height * 2 + 2) *
+                                                2 * sizeof(int16_t));
+            s->motion_val16[plane] = av_mallocz((s->m.mb_stride *
+                                                 (block_height + 2) + 1) *
+                                                2 * sizeof(int16_t));
         }
 
-        s->m.mb_type= s->mb_type;
+        s->m.mb_type = s->mb_type;
 
-        //dummies, to avoid segfaults
-        s->m.current_picture.mb_mean=   (uint8_t *)s->dummy;
-        s->m.current_picture.mb_var=    (uint16_t*)s->dummy;
-        s->m.current_picture.mc_mb_var= (uint16_t*)s->dummy;
+        // dummies, to avoid segfaults
+        s->m.current_picture.mb_mean   = (uint8_t *)s->dummy;
+        s->m.current_picture.mb_var    = (uint16_t *)s->dummy;
+        s->m.current_picture.mc_mb_var = (uint16_t *)s->dummy;
         s->m.current_picture.f.mb_type = s->dummy;
 
         s->m.current_picture.f.motion_val[0] = s->motion_val8[plane] + 2;
-        s->m.p_mv_table= s->motion_val16[plane] + s->m.mb_stride + 1;
-        s->m.dsp= s->dsp; //move
+        s->m.p_mv_table                      = s->motion_val16[plane] +
+                                               s->m.mb_stride + 1;
+        s->m.dsp                             = s->dsp; // move
         ff_init_me(&s->m);
 
-        s->m.me.dia_size= s->avctx->dia_size;
-        s->m.first_slice_line=1;
+        s->m.me.dia_size      = s->avctx->dia_size;
+        s->m.first_slice_line = 1;
         for (y = 0; y < block_height; y++) {
-            s->m.new_picture.f.data[0] = src - y*16*stride; //ugly
-            s->m.mb_y= y;
+            s->m.new_picture.f.data[0] = src - y * 16 * stride; // ugly
+            s->m.mb_y                  = y;
 
-            for(i=0; i<16 && i + 16*y<height; i++){
-                memcpy(&src[i*stride], &src_plane[(i+16*y)*src_stride], width);
-                for(x=width; x<16*block_width; x++)
-                    src[i*stride+x]= src[i*stride+x-1];
+            for (i = 0; i < 16 && i + 16 * y < height; i++) {
+                memcpy(&src[i * stride], &src_plane[(i + 16 * y) * src_stride],
+                       width);
+                for (x = width; x < 16 * block_width; x++)
+                    src[i * stride + x] = src[i * stride + x - 1];
             }
-            for(; i<16 && i + 16*y<16*block_height; i++)
-                memcpy(&src[i*stride], &src[(i-1)*stride], 16*block_width);
+            for (; i < 16 && i + 16 * y < 16 * block_height; i++)
+                memcpy(&src[i * stride], &src[(i - 1) * stride],
+                       16 * block_width);
 
             for (x = 0; x < block_width; x++) {
-                s->m.mb_x= x;
+                s->m.mb_x = x;
                 ff_init_block_index(&s->m);
                 ff_update_block_index(&s->m);
 
                 ff_estimate_p_frame_motion(&s->m, x, y);
             }
-            s->m.first_slice_line=0;
+            s->m.first_slice_line = 0;
         }
 
         ff_fix_long_p_mvs(&s->m);
-        ff_fix_long_mvs(&s->m, NULL, 0, s->m.p_mv_table, s->m.f_code, CANDIDATE_MB_TYPE_INTER, 0);
+        ff_fix_long_mvs(&s->m, NULL, 0, s->m.p_mv_table, s->m.f_code,
+                        CANDIDATE_MB_TYPE_INTER, 0);
     }
 
-    s->m.first_slice_line=1;
+    s->m.first_slice_line = 1;
     for (y = 0; y < block_height; y++) {
-        for(i=0; i<16 && i + 16*y<height; i++){
-            memcpy(&src[i*stride], &src_plane[(i+16*y)*src_stride], width);
-            for(x=width; x<16*block_width; x++)
-                src[i*stride+x]= src[i*stride+x-1];
+        for (i = 0; i < 16 && i + 16 * y < height; i++) {
+            memcpy(&src[i * stride], &src_plane[(i + 16 * y) * src_stride],
+                   width);
+            for (x = width; x < 16 * block_width; x++)
+                src[i * stride + x] = src[i * stride + x - 1];
         }
-        for(; i<16 && i + 16*y<16*block_height; i++)
-            memcpy(&src[i*stride], &src[(i-1)*stride], 16*block_width);
+        for (; i < 16 && i + 16 * y < 16 * block_height; i++)
+            memcpy(&src[i * stride], &src[(i - 1) * stride], 16 * block_width);
 
-        s->m.mb_y= y;
+        s->m.mb_y = y;
         for (x = 0; x < block_width; x++) {
-            uint8_t reorder_buffer[3][6][7*32];
+            uint8_t reorder_buffer[3][6][7 * 32];
             int count[3][6];
-            int offset = y * 16 * stride + x * 16;
-            uint8_t *decoded= decoded_plane + offset;
-            uint8_t *ref= ref_plane + offset;
-            int score[4]={0,0,0,0}, best;
-            uint8_t *temp = s->scratchbuf;
+            int offset       = y * 16 * stride + x * 16;
+            uint8_t *decoded = decoded_plane + offset;
+            uint8_t *ref     = ref_plane + offset;
+            int score[4]     = { 0, 0, 0, 0 }, best;
+            uint8_t *temp    = s->scratchbuf;
 
-            if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < 3000){ //FIXME check size
+            if (s->pb.buf_end - s->pb.buf -
+                (put_bits_count(&s->pb) >> 3) < 3000) { // FIXME: check size
                 av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
                 return -1;
             }
 
-            s->m.mb_x= x;
+            s->m.mb_x = x;
             ff_init_block_index(&s->m);
             ff_update_block_index(&s->m);
 
-            if(s->picture.pict_type == AV_PICTURE_TYPE_I || (s->m.mb_type[x + y*s->m.mb_stride]&CANDIDATE_MB_TYPE_INTRA)){
-                for(i=0; i<6; i++){
-                    init_put_bits(&s->reorder_pb[i], reorder_buffer[0][i], 7*32);
-                }
-                if(s->picture.pict_type == AV_PICTURE_TYPE_P){
-                    const uint8_t *vlc= ff_svq1_block_type_vlc[SVQ1_BLOCK_INTRA];
+            if (s->picture.pict_type == AV_PICTURE_TYPE_I ||
+                (s->m.mb_type[x + y * s->m.mb_stride] &
+                 CANDIDATE_MB_TYPE_INTRA)) {
+                for (i = 0; i < 6; i++)
+                    init_put_bits(&s->reorder_pb[i], reorder_buffer[0][i],
+                                  7 * 32);
+                if (s->picture.pict_type == AV_PICTURE_TYPE_P) {
+                    const uint8_t *vlc = ff_svq1_block_type_vlc[SVQ1_BLOCK_INTRA];
                     put_bits(&s->reorder_pb[5], vlc[1], vlc[0]);
-                    score[0]= vlc[1]*lambda;
+                    score[0] = vlc[1] * lambda;
                 }
-                score[0]+= encode_block(s, src+16*x, NULL, temp, stride, 5, 64, lambda, 1);
-                for(i=0; i<6; i++){
-                    count[0][i]= put_bits_count(&s->reorder_pb[i]);
+                score[0] += encode_block(s, src + 16 * x, NULL, temp, stride,
+                                         5, 64, lambda, 1);
+                for (i = 0; i < 6; i++) {
+                    count[0][i] = put_bits_count(&s->reorder_pb[i]);
                     flush_put_bits(&s->reorder_pb[i]);
                 }
-            }else
-                score[0]= INT_MAX;
+            } else
+                score[0] = INT_MAX;
 
-            best=0;
+            best = 0;
 
-            if(s->picture.pict_type == AV_PICTURE_TYPE_P){
-                const uint8_t *vlc= ff_svq1_block_type_vlc[SVQ1_BLOCK_INTER];
+            if (s->picture.pict_type == AV_PICTURE_TYPE_P) {
+                const uint8_t *vlc = ff_svq1_block_type_vlc[SVQ1_BLOCK_INTER];
                 int mx, my, pred_x, pred_y, dxy;
                 int16_t *motion_ptr;
 
-                motion_ptr= ff_h263_pred_motion(&s->m, 0, 0, &pred_x, &pred_y);
-                if(s->m.mb_type[x + y*s->m.mb_stride]&CANDIDATE_MB_TYPE_INTER){
-                    for(i=0; i<6; i++)
-                        init_put_bits(&s->reorder_pb[i], reorder_buffer[1][i], 7*32);
+                motion_ptr = ff_h263_pred_motion(&s->m, 0, 0, &pred_x, &pred_y);
+                if (s->m.mb_type[x + y * s->m.mb_stride] &
+                    CANDIDATE_MB_TYPE_INTER) {
+                    for (i = 0; i < 6; i++)
+                        init_put_bits(&s->reorder_pb[i], reorder_buffer[1][i],
+                                      7 * 32);
 
                     put_bits(&s->reorder_pb[5], vlc[1], vlc[0]);
 
-                    s->m.pb= s->reorder_pb[5];
-                    mx= motion_ptr[0];
-                    my= motion_ptr[1];
-                    av_assert1(mx>=-32 && mx<=31);
-                    av_assert1(my>=-32 && my<=31);
-                    av_assert1(pred_x>=-32 && pred_x<=31);
-                    av_assert1(pred_y>=-32 && pred_y<=31);
+                    s->m.pb = s->reorder_pb[5];
+                    mx      = motion_ptr[0];
+                    my      = motion_ptr[1];
+                    av_assert1(mx     >= -32 && mx     <= 31);
+                    av_assert1(my     >= -32 && my     <= 31);
+                    av_assert1(pred_x >= -32 && pred_x <= 31);
+                    av_assert1(pred_y >= -32 && pred_y <= 31);
                     ff_h263_encode_motion(&s->m, mx - pred_x, 1);
                     ff_h263_encode_motion(&s->m, my - pred_y, 1);
-                    s->reorder_pb[5]= s->m.pb;
-                    score[1] += lambda*put_bits_count(&s->reorder_pb[5]);
+                    s->reorder_pb[5] = s->m.pb;
+                    score[1]        += lambda * put_bits_count(&s->reorder_pb[5]);
 
-                    dxy= (mx&1) + 2*(my&1);
+                    dxy = (mx & 1) + 2 * (my & 1);
 
-                    s->dsp.put_pixels_tab[0][dxy](temp+16, ref + (mx>>1) + stride*(my>>1), stride, 16);
+                    s->dsp.put_pixels_tab[0][dxy](temp + 16,
+                                                  ref + (mx >> 1) +
+                                                  stride * (my >> 1),
+                                                  stride, 16);
 
-                    score[1]+= encode_block(s, src+16*x, temp+16, decoded, stride, 5, 64, lambda, 0);
-                    best= score[1] <= score[0];
+                    score[1] += encode_block(s, src + 16 * x, temp + 16,
+                                             decoded, stride, 5, 64, lambda, 0);
+                    best      = score[1] <= score[0];
 
-                    vlc= ff_svq1_block_type_vlc[SVQ1_BLOCK_SKIP];
-                    score[2]= s->dsp.sse[0](NULL, src+16*x, ref, stride, 16);
-                    score[2]+= vlc[1]*lambda;
-                    if(score[2] < score[best] && mx==0 && my==0){
-                        best=2;
+                    vlc       = ff_svq1_block_type_vlc[SVQ1_BLOCK_SKIP];
+                    score[2]  = s->dsp.sse[0](NULL, src + 16 * x, ref,
+                                              stride, 16);
+                    score[2] += vlc[1] * lambda;
+                    if (score[2] < score[best] && mx == 0 && my == 0) {
+                        best = 2;
                         s->dsp.put_pixels_tab[0][0](decoded, ref, stride, 16);
-                        for(i=0; i<6; i++){
-                            count[2][i]=0;
-                        }
+                        for (i = 0; i < 6; i++)
+                            count[2][i] = 0;
                         put_bits(&s->pb, vlc[1], vlc[0]);
                     }
                 }
 
-                if(best==1){
-                    for(i=0; i<6; i++){
-                        count[1][i]= put_bits_count(&s->reorder_pb[i]);
+                if (best == 1) {
+                    for (i = 0; i < 6; i++) {
+                        count[1][i] = put_bits_count(&s->reorder_pb[i]);
                         flush_put_bits(&s->reorder_pb[i]);
                     }
-                }else{
-                    motion_ptr[0                 ] = motion_ptr[1                 ]=
-                    motion_ptr[2                 ] = motion_ptr[3                 ]=
-                    motion_ptr[0+2*s->m.b8_stride] = motion_ptr[1+2*s->m.b8_stride]=
-                    motion_ptr[2+2*s->m.b8_stride] = motion_ptr[3+2*s->m.b8_stride]=0;
+                } else {
+                    motion_ptr[0]                      =
+                    motion_ptr[1]                      =
+                    motion_ptr[2]                      =
+                    motion_ptr[3]                      =
+                    motion_ptr[0 + 2 * s->m.b8_stride] =
+                    motion_ptr[1 + 2 * s->m.b8_stride] =
+                    motion_ptr[2 + 2 * s->m.b8_stride] =
+                    motion_ptr[3 + 2 * s->m.b8_stride] = 0;
                 }
             }
 
             s->rd_total += score[best];
 
-            for(i=5; i>=0; i--){
-                avpriv_copy_bits(&s->pb, reorder_buffer[best][i], count[best][i]);
-            }
-            if(best==0){
+            for (i = 5; i >= 0; i--)
+                avpriv_copy_bits(&s->pb, reorder_buffer[best][i],
+                                 count[best][i]);
+            if (best == 0)
                 s->dsp.put_pixels_tab[0][0](decoded, temp, stride, 16);
-            }
         }
-        s->m.first_slice_line=0;
+        s->m.first_slice_line = 0;
     }
     return 0;
 }
 
 static av_cold int svq1_encode_init(AVCodecContext *avctx)
 {
-    SVQ1Context * const s = avctx->priv_data;
+    SVQ1Context *const s = avctx->priv_data;
 
     ff_dsputil_init(&s->dsp, avctx);
     avctx->coded_frame = &s->picture;
 
-    s->frame_width = avctx->width;
+    s->frame_width  = avctx->width;
     s->frame_height = avctx->height;
 
-    s->y_block_width = (s->frame_width + 15) / 16;
+    s->y_block_width  = (s->frame_width  + 15) / 16;
     s->y_block_height = (s->frame_height + 15) / 16;
 
-    s->c_block_width = (s->frame_width / 4 + 15) / 16;
+    s->c_block_width  = (s->frame_width  / 4 + 15) / 16;
     s->c_block_height = (s->frame_height / 4 + 15) / 16;
 
-    s->avctx= avctx;
-    s->m.avctx= avctx;
+    s->avctx               = avctx;
+    s->m.avctx             = avctx;
     s->m.picture_structure = PICT_FRAME;
-    s->m.me.temp      =
-    s->m.me.scratchpad= av_mallocz((avctx->width+64)*2*16*2*sizeof(uint8_t));
-    s->m.me.map       = av_mallocz(ME_MAP_SIZE*sizeof(uint32_t));
-    s->m.me.score_map = av_mallocz(ME_MAP_SIZE*sizeof(uint32_t));
-    s->mb_type        = av_mallocz((s->y_block_width+1)*s->y_block_height*sizeof(int16_t));
-    s->dummy          = av_mallocz((s->y_block_width+1)*s->y_block_height*sizeof(int32_t));
-    ff_h263_encode_init(&s->m); //mv_penalty
+    s->m.me.temp           =
+    s->m.me.scratchpad     = av_mallocz((avctx->width + 64) *
+                                        2 * 16 * 2 * sizeof(uint8_t));
+    s->m.me.map            = av_mallocz(ME_MAP_SIZE * sizeof(uint32_t));
+    s->m.me.score_map      = av_mallocz(ME_MAP_SIZE * sizeof(uint32_t));
+    s->mb_type             = av_mallocz((s->y_block_width + 1) *
+                                        s->y_block_height * sizeof(int16_t));
+    s->dummy               = av_mallocz((s->y_block_width + 1) *
+                                        s->y_block_height * sizeof(int32_t));
+    ff_h263_encode_init(&s->m); // mv_penalty
 
     return 0;
 }
@@ -500,46 +532,51 @@
 static int svq1_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
                              const AVFrame *pict, int *got_packet)
 {
-    SVQ1Context * const s = avctx->priv_data;
-    AVFrame * const p = &s->picture;
+    SVQ1Context *const s = avctx->priv_data;
+    AVFrame *const p     = &s->picture;
     AVFrame temp;
     int i, ret;
 
-    if ((ret = ff_alloc_packet2(avctx, pkt, s->y_block_width*s->y_block_height*MAX_MB_BYTES*3 + FF_MIN_BUFFER_SIZE) < 0))
+    if ((ret = ff_alloc_packet2(avctx, pkt, s->y_block_width * s->y_block_height *
+                             MAX_MB_BYTES*3 + FF_MIN_BUFFER_SIZE) < 0))
         return ret;
 
-    if(avctx->pix_fmt != PIX_FMT_YUV410P){
+    if (avctx->pix_fmt != AV_PIX_FMT_YUV410P) {
         av_log(avctx, AV_LOG_ERROR, "unsupported pixel format\n");
         return -1;
     }
 
-    if(!s->current_picture.data[0]){
+    if (!s->current_picture.data[0]) {
         avctx->get_buffer(avctx, &s->current_picture);
         avctx->get_buffer(avctx, &s->last_picture);
         s->scratchbuf = av_malloc(s->current_picture.linesize[0] * 16 * 2);
     }
 
-    temp= s->current_picture;
-    s->current_picture= s->last_picture;
-    s->last_picture= temp;
+    temp               = s->current_picture;
+    s->current_picture = s->last_picture;
+    s->last_picture    = temp;
 
     init_put_bits(&s->pb, pkt->data, pkt->size);
 
-    *p = *pict;
-    p->pict_type = avctx->gop_size && avctx->frame_number % avctx->gop_size ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_I;
+    *p           = *pict;
+    p->pict_type = avctx->gop_size && avctx->frame_number % avctx->gop_size ?
+                   AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_I;
     p->key_frame = p->pict_type == AV_PICTURE_TYPE_I;
 
     svq1_write_header(s, p->pict_type);
-    for(i=0; i<3; i++){
-        if(svq1_encode_plane(s, i,
-            s->picture.data[i], s->last_picture.data[i], s->current_picture.data[i],
-            s->frame_width / (i?4:1), s->frame_height / (i?4:1),
-            s->picture.linesize[i], s->current_picture.linesize[i]) < 0)
-                return -1;
-    }
+    for (i = 0; i < 3; i++)
+        if (svq1_encode_plane(s, i,
+                              s->picture.data[i],
+                              s->last_picture.data[i],
+                              s->current_picture.data[i],
+                              s->frame_width  / (i ? 4 : 1),
+                              s->frame_height / (i ? 4 : 1),
+                              s->picture.linesize[i],
+                              s->current_picture.linesize[i]) < 0)
+            return -1;
 
-//    avpriv_align_put_bits(&s->pb);
-    while(put_bits_count(&s->pb) & 31)
+    // avpriv_align_put_bits(&s->pb);
+    while (put_bits_count(&s->pb) & 31)
         put_bits(&s->pb, 1, 0);
 
     flush_put_bits(&s->pb);
@@ -554,10 +591,12 @@
 
 static av_cold int svq1_encode_end(AVCodecContext *avctx)
 {
-    SVQ1Context * const s = avctx->priv_data;
+    SVQ1Context *const s = avctx->priv_data;
     int i;
 
-    av_log(avctx, AV_LOG_DEBUG, "RD: %f\n", s->rd_total/(double)(avctx->width*avctx->height*avctx->frame_number));
+    av_log(avctx, AV_LOG_DEBUG, "RD: %f\n",
+           s->rd_total / (double)(avctx->width * avctx->height *
+                                  avctx->frame_number));
 
     av_freep(&s->m.me.scratchpad);
     av_freep(&s->m.me.map);
@@ -566,7 +605,7 @@
     av_freep(&s->dummy);
     av_freep(&s->scratchbuf);
 
-    for(i=0; i<3; i++){
+    for (i = 0; i < 3; i++) {
         av_freep(&s->motion_val8[i]);
         av_freep(&s->motion_val16[i]);
     }
@@ -578,7 +617,6 @@
     return 0;
 }
 
-
 AVCodec ff_svq1_encoder = {
     .name           = "svq1",
     .type           = AVMEDIA_TYPE_VIDEO,
@@ -587,6 +625,7 @@
     .init           = svq1_encode_init,
     .encode2        = svq1_encode_frame,
     .close          = svq1_encode_end,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUV410P, PIX_FMT_NONE },
+    .pix_fmts       = (const enum PixelFormat[]) { AV_PIX_FMT_YUV410P,
+                                                   AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("Sorenson Vector Quantizer 1 / Sorenson Video 1 / SVQ1"),
 };
diff --git a/libavcodec/svq1enc_cb.h b/libavcodec/svq1enc_cb.h
index 7eff82e..1edb4ec 100644
--- a/libavcodec/svq1enc_cb.h
+++ b/libavcodec/svq1enc_cb.h
@@ -30,67 +30,57 @@
 #include <stdint.h>
 
 static const int8_t svq1_inter_codebook_sum[4][16*6] = {
- {
- -1,  1, -2,  0,  1, -1, -1, -1, -2, -1,  1, -1, -1,  0, -1, -1,
-  0, -1, -1, -1, -1,  0, -1,  0,  0,  0, -3,  1, -1,  0,  1, -1,
-  1, -1,  2,  2,  1,  1,  2,  0,  0,  0, -1,  1,  1,  0,  0,  0,
-  1, -1,  0,  1, -1,  1,  1,  0,  1,  0, -1,  1,  1,  0,  0,  0,
- -2,  0,  0, -2,  0,  0, -2,  0, -2, -1, -2, -1,  0,  0, -1,  0,
-  1,  0,  1, -1,  2,  2,  1,  2,  2,  1,  0,  1,  1,  0,  1,  1,
- },{
- -2,  1, -1, -1,  1,  0,  1, -1, -1, -1,  1, -1,  0, -1,  0, -1,
-  0,  0,  0, -2,  0,  1,  0, -1, -1,  0,  2, -3,  1, -2,  3, -1,
-  2,  0,  2,  1,  1, -1,  1,  1,  0,  0,  1,  1,  2, -2,  1,  0,
- -2, -1,  2, -2, -2,  0, -3,  0, -1,  0, -1,  0, -1,  0, -2, -3,
-  1, -2, -2, -1,  1, -1, -1,  1, -1,  1,  1,  0, -2,  0,  1,  1,
-  1,  1,  2,  1,  0,  0, -1,  0,  0,  1,  0,  1, -1,  1,  0,  2,
- },{
-  0,  0,  0, -3,  1,  1,  1, -3,  0, -1,  0, -3,  1, -3,  0, -2,
-  1,  2, -1, -3,  0, -3,  1, -1,  0, -1,  0,  0,  1,  2,  1,  1,
- -1,  2, -3,  3,  1,  0, -5,  1,  0, -1, -3,  1,  0,  2,  0, -3,
-  4,  2,  0, -2,  1, -2,  3, -2,  1,  1,  0, -1,  2,  5,  3,  1,
- -1,  0,  2, -3, -2,  0,  0, -2,  2, -3, -1, -1,  2,  1,  0, -2,
-  3, -1,  1, -1,  2,  4,  0,  1,  0,  1,  0, -1, -3, -2, -1,  0,
- },{
-  0,  2, -1, -1,  2, -4, -2,  3,  0, -1, -5,  1,  0,  1,  0,  6,
- -2,  2,  0,  1,  1, -1, -1, -2,  1, -2, -1,  0,  2, -2, -2, -1,
- -4,  2, -1, -3, -1, -2,  2, -1,  2, -1,  2,  0,  3, -3, -3,  0,
- -3,  0,  0, -2,  4, -4,  0, -1,  4,  0, -2, -2,  3, -2,  0,  4,
-  5,  0,  1,  0, -3,  3,  3,  2,  0,  0,  1,  2, -5, -2, -3,  0,
- -3,  2, -2,  2, -2,  4,  7, -3,  4,  2,  3,  2, -1,  0, -3,  1,
- }
+    { -1,  1, -2,  0,  1, -1, -1, -1, -2, -1,  1, -1, -1,  0, -1, -1,
+       0, -1, -1, -1, -1,  0, -1,  0,  0,  0, -3,  1, -1,  0,  1, -1,
+       1, -1,  2,  2,  1,  1,  2,  0,  0,  0, -1,  1,  1,  0,  0,  0,
+       1, -1,  0,  1, -1,  1,  1,  0,  1,  0, -1,  1,  1,  0,  0,  0,
+      -2,  0,  0, -2,  0,  0, -2,  0, -2, -1, -2, -1,  0,  0, -1,  0,
+       1,  0,  1, -1,  2,  2,  1,  2,  2,  1,  0,  1,  1,  0,  1,  1, },
+    { -2,  1, -1, -1,  1,  0,  1, -1, -1, -1,  1, -1,  0, -1,  0, -1,
+       0,  0,  0, -2,  0,  1,  0, -1, -1,  0,  2, -3,  1, -2,  3, -1,
+       2,  0,  2,  1,  1, -1,  1,  1,  0,  0,  1,  1,  2, -2,  1,  0,
+      -2, -1,  2, -2, -2,  0, -3,  0, -1,  0, -1,  0, -1,  0, -2, -3,
+       1, -2, -2, -1,  1, -1, -1,  1, -1,  1,  1,  0, -2,  0,  1,  1,
+       1,  1,  2,  1,  0,  0, -1,  0,  0,  1,  0,  1, -1,  1,  0,  2, },
+    {  0,  0,  0, -3,  1,  1,  1, -3,  0, -1,  0, -3,  1, -3,  0, -2,
+       1,  2, -1, -3,  0, -3,  1, -1,  0, -1,  0,  0,  1,  2,  1,  1,
+      -1,  2, -3,  3,  1,  0, -5,  1,  0, -1, -3,  1,  0,  2,  0, -3,
+       4,  2,  0, -2,  1, -2,  3, -2,  1,  1,  0, -1,  2,  5,  3,  1,
+      -1,  0,  2, -3, -2,  0,  0, -2,  2, -3, -1, -1,  2,  1,  0, -2,
+       3, -1,  1, -1,  2,  4,  0,  1,  0,  1,  0, -1, -3, -2, -1,  0, },
+    {  0,  2, -1, -1,  2, -4, -2,  3,  0, -1, -5,  1,  0,  1,  0,  6,
+      -2,  2,  0,  1,  1, -1, -1, -2,  1, -2, -1,  0,  2, -2, -2, -1,
+      -4,  2, -1, -3, -1, -2,  2, -1,  2, -1,  2,  0,  3, -3, -3,  0,
+      -3,  0,  0, -2,  4, -4,  0, -1,  4,  0, -2, -2,  3, -2,  0,  4,
+       5,  0,  1,  0, -3,  3,  3,  2,  0,  0,  1,  2, -5, -2, -3,  0,
+      -3,  2, -2,  2, -2,  4,  7, -3,  4,  2,  3,  2, -1,  0, -3,  1, }
 };
 
 static const int8_t svq1_intra_codebook_sum[4][16*6] = {
- {
-  0,  0,  0, -1, -1, -1, -1, -2,  0, -1, -1,  0, -1,  0,  1,  0,
-  1,  0, -1,  1,  0,  0, -1,  1, -1,  0,  0,  0, -1,  1,  0,  0,
- -1,  0,  0,  1, -1,  1,  0, -1, -1,  0,  1,  1,  0,  0, -1,  1,
-  0,  1,  0,  0,  1, -1,  0,  0,  0, -1,  1,  0,  1,  0, -2,  1,
-  0, -1,  1,  0,  0,  0,  1,  0, -1,  0,  0,  0, -1,  0,  0,  0,
-  0,  1,  1,  0,  0, -1,  0,  1,  0,  0,  0,  0, -1,  1,  1, -1,
- },{
- -1, -2,  0, -1,  1,  0, -1,  0, -1, -4, -1, -2, -1, -2,  1, -2,
-  0,  0,  4, -2, -1,  1,  1,  0,  2,  1,  1,  0,  2,  0,  0,  0,
-  1,  1,  0, -1, -1, -1,  1,  0, -1, -3, -3,  1, -1,  1, -2, -1,
-  1, -1,  0,  1,  2,  1, -1, -1,  1,  1,  1,  2,  1,  0,  1, -2,
- -2,  0, -1, -2, -2,  0, -1, -1, -1,  0,  1,  0, -1, -1,  0, -1,
-  0,  2,  1,  2,  2,  1, -1,  1,  0,  2,  0, -1,  1,  0,  0,  0,
- },{
- -2,  0, -1, -1,  1,  1, -2,  0, -2,  0,  1, -2, -2,  1, -1, -1,
-  3, -2,  0, -3, -4, -3,  2,  1,  0,  3, -2,  2,  3,  2,  2, -1,
- -3,  1,  0,  1,  0,  0,  0,  1, -2,  1, -2, -2, -1, -2, -2,  2,
-  0, -4,  0,  2, -1,  0,  2,  2,  2,  1,  0, -1, -1,  1, -3,  2,
-  2,  1,  0,  3,  1, -1,  1,  3,  1,  0,  1,  1,  2, -1,  1, -1,
- -2, -1,  0, -1,  1, -1,  1, -2, -2, -1, -1, -3,  1, -4, -3,  1,
- },{
- -2,  0, -2,  3, -1, -1,  0,  2,  2, -1, -3,  2,  1,  0, -2, -1,
- -3, -2, -2,  1,  2, -3,  0,  1, -5, -2, -3,  0, -2, -1,  2,  0,
- -1, -1,  0, -2,  1,  3, -7, -2, -2, -1,  2, -1,  0,  3,  1,  3,
-  1,  0,  0,  1,  2,  3,  1,  2,  0, -2, -2,  1,  1,  2,  2,  3,
-  4,  1, -1,  2, -2,  4,  0,  0,  0,  4,  2,  0, -2, -2,  2, -4,
- -1,  5, -2, -2, -3,  2, -3, -1,  3, -3,  0,  4,  3,  0,  1, -2,
- }
+    {  0,  0,  0, -1, -1, -1, -1, -2,  0, -1, -1,  0, -1,  0,  1,  0,
+       1,  0, -1,  1,  0,  0, -1,  1, -1,  0,  0,  0, -1,  1,  0,  0,
+      -1,  0,  0,  1, -1,  1,  0, -1, -1,  0,  1,  1,  0,  0, -1,  1,
+       0,  1,  0,  0,  1, -1,  0,  0,  0, -1,  1,  0,  1,  0, -2,  1,
+       0, -1,  1,  0,  0,  0,  1,  0, -1,  0,  0,  0, -1,  0,  0,  0,
+       0,  1,  1,  0,  0, -1,  0,  1,  0,  0,  0,  0, -1,  1,  1, -1, },
+    { -1, -2,  0, -1,  1,  0, -1,  0, -1, -4, -1, -2, -1, -2,  1, -2,
+       0,  0,  4, -2, -1,  1,  1,  0,  2,  1,  1,  0,  2,  0,  0,  0,
+       1,  1,  0, -1, -1, -1,  1,  0, -1, -3, -3,  1, -1,  1, -2, -1,
+       1, -1,  0,  1,  2,  1, -1, -1,  1,  1,  1,  2,  1,  0,  1, -2,
+      -2,  0, -1, -2, -2,  0, -1, -1, -1,  0,  1,  0, -1, -1,  0, -1,
+       0,  2,  1,  2,  2,  1, -1,  1,  0,  2,  0, -1,  1,  0,  0,  0, },
+    { -2,  0, -1, -1,  1,  1, -2,  0, -2,  0,  1, -2, -2,  1, -1, -1,
+       3, -2,  0, -3, -4, -3,  2,  1,  0,  3, -2,  2,  3,  2,  2, -1,
+      -3,  1,  0,  1,  0,  0,  0,  1, -2,  1, -2, -2, -1, -2, -2,  2,
+       0, -4,  0,  2, -1,  0,  2,  2,  2,  1,  0, -1, -1,  1, -3,  2,
+       2,  1,  0,  3,  1, -1,  1,  3,  1,  0,  1,  1,  2, -1,  1, -1,
+      -2, -1,  0, -1,  1, -1,  1, -2, -2, -1, -1, -3,  1, -4, -3,  1, },
+    { -2,  0, -2,  3, -1, -1,  0,  2,  2, -1, -3,  2,  1,  0, -2, -1,
+      -3, -2, -2,  1,  2, -3,  0,  1, -5, -2, -3,  0, -2, -1,  2,  0,
+      -1, -1,  0, -2,  1,  3, -7, -2, -2, -1,  2, -1,  0,  3,  1,  3,
+       1,  0,  0,  1,  2,  3,  1,  2,  0, -2, -2,  1,  1,  2,  2,  3,
+       4,  1, -1,  2, -2,  4,  0,  0,  0,  4,  2,  0, -2, -2,  2, -4,
+      -1,  5, -2, -2, -3,  2, -3, -1,  3, -3,  0,  4,  3,  0,  1, -2, }
 };
 
 #endif /* AVCODEC_SVQ1ENC_CB_H */
diff --git a/libavcodec/svq3.c b/libavcodec/svq3.c
index 9342935..e195422 100644
--- a/libavcodec/svq3.c
+++ b/libavcodec/svq3.c
@@ -45,7 +45,7 @@
 #include "mpegvideo.h"
 #include "h264.h"
 
-#include "h264data.h" //FIXME FIXME FIXME
+#include "h264data.h" // FIXME FIXME FIXME
 
 #include "h264_mvpred.h"
 #include "golomb.h"
@@ -80,19 +80,19 @@
 #define PREDICT_MODE  4
 
 /* dual scan (from some older h264 draft)
- o-->o-->o   o
-         |  /|
- o   o   o / o
- | / |   |/  |
- o   o   o   o
-   /
- o-->o-->o-->o
-*/
+ * o-->o-->o   o
+ *         |  /|
+ * o   o   o / o
+ * | / |   |/  |
+ * o   o   o   o
+ *   /
+ * o-->o-->o-->o
+ */
 static const uint8_t svq3_scan[16] = {
-    0+0*4, 1+0*4, 2+0*4, 2+1*4,
-    2+2*4, 3+0*4, 3+1*4, 3+2*4,
-    0+1*4, 0+2*4, 1+1*4, 1+2*4,
-    0+3*4, 1+3*4, 2+3*4, 3+3*4,
+    0 + 0 * 4, 1 + 0 * 4, 2 + 0 * 4, 2 + 1 * 4,
+    2 + 2 * 4, 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4,
+    0 + 1 * 4, 0 + 2 * 4, 1 + 1 * 4, 1 + 2 * 4,
+    0 + 3 * 4, 1 + 3 * 4, 2 + 3 * 4, 3 + 3 * 4,
 };
 
 static const uint8_t svq3_pred_0[25][2] = {
@@ -108,21 +108,24 @@
 };
 
 static const int8_t svq3_pred_1[6][6][5] = {
-    { { 2,-1,-1,-1,-1 }, { 2, 1,-1,-1,-1 }, { 1, 2,-1,-1,-1 },
-      { 2, 1,-1,-1,-1 }, { 1, 2,-1,-1,-1 }, { 1, 2,-1,-1,-1 } },
-    { { 0, 2,-1,-1,-1 }, { 0, 2, 1, 4, 3 }, { 0, 1, 2, 4, 3 },
-      { 0, 2, 1, 4, 3 }, { 2, 0, 1, 3, 4 }, { 0, 4, 2, 1, 3 } },
-    { { 2, 0,-1,-1,-1 }, { 2, 1, 0, 4, 3 }, { 1, 2, 4, 0, 3 },
-      { 2, 1, 0, 4, 3 }, { 2, 1, 4, 3, 0 }, { 1, 2, 4, 0, 3 } },
-    { { 2, 0,-1,-1,-1 }, { 2, 0, 1, 4, 3 }, { 1, 2, 0, 4, 3 },
-      { 2, 1, 0, 4, 3 }, { 2, 1, 3, 4, 0 }, { 2, 4, 1, 0, 3 } },
-    { { 0, 2,-1,-1,-1 }, { 0, 2, 1, 3, 4 }, { 1, 2, 3, 0, 4 },
-      { 2, 0, 1, 3, 4 }, { 2, 1, 3, 0, 4 }, { 2, 0, 4, 3, 1 } },
-    { { 0, 2,-1,-1,-1 }, { 0, 2, 4, 1, 3 }, { 1, 4, 2, 0, 3 },
-      { 4, 2, 0, 1, 3 }, { 2, 0, 1, 4, 3 }, { 4, 2, 1, 0, 3 } },
+    { { 2, -1, -1, -1, -1 }, { 2, 1, -1, -1, -1 }, { 1, 2, -1, -1, -1 },
+      { 2,  1, -1, -1, -1 }, { 1, 2, -1, -1, -1 }, { 1, 2, -1, -1, -1 } },
+    { { 0,  2, -1, -1, -1 }, { 0, 2,  1,  4,  3 }, { 0, 1,  2,  4,  3 },
+      { 0,  2,  1,  4,  3 }, { 2, 0,  1,  3,  4 }, { 0, 4,  2,  1,  3 } },
+    { { 2,  0, -1, -1, -1 }, { 2, 1,  0,  4,  3 }, { 1, 2,  4,  0,  3 },
+      { 2,  1,  0,  4,  3 }, { 2, 1,  4,  3,  0 }, { 1, 2,  4,  0,  3 } },
+    { { 2,  0, -1, -1, -1 }, { 2, 0,  1,  4,  3 }, { 1, 2,  0,  4,  3 },
+      { 2,  1,  0,  4,  3 }, { 2, 1,  3,  4,  0 }, { 2, 4,  1,  0,  3 } },
+    { { 0,  2, -1, -1, -1 }, { 0, 2,  1,  3,  4 }, { 1, 2,  3,  0,  4 },
+      { 2,  0,  1,  3,  4 }, { 2, 1,  3,  0,  4 }, { 2, 0,  4,  3,  1 } },
+    { { 0,  2, -1, -1, -1 }, { 0, 2,  4,  1,  3 }, { 1, 4,  2,  0,  3 },
+      { 4,  2,  0,  1,  3 }, { 2, 0,  1,  4,  3 }, { 4, 2,  1,  0,  3 } },
 };
 
-static const struct { uint8_t run; uint8_t level; } svq3_dct_tables[2][16] = {
+static const struct {
+    uint8_t run;
+    uint8_t level;
+} svq3_dct_tables[2][16] = {
     { { 0, 0 }, { 0, 1 }, { 1, 1 }, { 2, 1 }, { 0, 2 }, { 3, 1 }, { 4, 1 }, { 5, 1 },
       { 0, 3 }, { 1, 2 }, { 2, 2 }, { 6, 1 }, { 7, 1 }, { 8, 1 }, { 9, 1 }, { 0, 4 } },
     { { 0, 0 }, { 0, 1 }, { 1, 1 }, { 0, 2 }, { 2, 1 }, { 0, 3 }, { 0, 4 }, { 0, 5 },
@@ -130,80 +133,82 @@
 };
 
 static const uint32_t svq3_dequant_coeff[32] = {
-     3881,  4351,  4890,  5481,  6154,  6914,  7761,  8718,
-     9781, 10987, 12339, 13828, 15523, 17435, 19561, 21873,
-    24552, 27656, 30847, 34870, 38807, 43747, 49103, 54683,
-    61694, 68745, 77615, 89113,100253,109366,126635,141533
+     3881,  4351,  4890,  5481,   6154,   6914,   7761,   8718,
+     9781, 10987, 12339, 13828,  15523,  17435,  19561,  21873,
+    24552, 27656, 30847, 34870,  38807,  43747,  49103,  54683,
+    61694, 68745, 77615, 89113, 100253, 109366, 126635, 141533
 };
 
-void ff_svq3_luma_dc_dequant_idct_c(DCTELEM *output, DCTELEM *input, 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 uint8_t x_offset[4]={0, 1*stride, 4*stride, 5*stride};
+    static const uint8_t x_offset[4] = { 0, 1 * stride, 4 * stride, 5 * stride };
 
-    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];
+    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;
-        temp[4*i+2] = z1-z2;
-        temp[4*i+3] = z0-z3;
+        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= 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];
+    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;
+        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
 
-void ff_svq3_add_idct_c(uint8_t *dst, DCTELEM *block, int stride, int qp,
-                            int dc)
+void ff_svq3_add_idct_c(uint8_t *dst, DCTELEM *block,
+                        int stride, int qp, int dc)
 {
     const int qmul = svq3_dequant_coeff[qp];
     int i;
 
     if (dc) {
-        dc = 13*13*((dc == 1) ? 1538*block[0] : ((qmul*(block[0] >> 3)) / 2));
+        dc       = 13 * 13 * (dc == 1 ? 1538 * block[0]
+                                      : qmul * (block[0] >> 3) / 2);
         block[0] = 0;
     }
 
     for (i = 0; i < 4; i++) {
-        const int z0 = 13*(block[0 + 4*i] +    block[2 + 4*i]);
-        const int z1 = 13*(block[0 + 4*i] -    block[2 + 4*i]);
-        const int z2 =  7* block[1 + 4*i] - 17*block[3 + 4*i];
-        const int z3 = 17* block[1 + 4*i] +  7*block[3 + 4*i];
+        const int z0 = 13 * (block[0 + 4 * i] +      block[2 + 4 * i]);
+        const int z1 = 13 * (block[0 + 4 * i] -      block[2 + 4 * i]);
+        const int z2 =  7 *  block[1 + 4 * i] - 17 * block[3 + 4 * i];
+        const int z3 = 17 *  block[1 + 4 * i] +  7 * block[3 + 4 * i];
 
-        block[0 + 4*i] = z0 + z3;
-        block[1 + 4*i] = z1 + z2;
-        block[2 + 4*i] = z1 - z2;
-        block[3 + 4*i] = z0 - z3;
+        block[0 + 4 * i] = z0 + z3;
+        block[1 + 4 * i] = z1 + z2;
+        block[2 + 4 * i] = z1 - z2;
+        block[3 + 4 * i] = z0 - z3;
     }
 
     for (i = 0; i < 4; i++) {
-        const int z0 = 13*(block[i + 4*0] +    block[i + 4*2]);
-        const int z1 = 13*(block[i + 4*0] -    block[i + 4*2]);
-        const int z2 =  7* block[i + 4*1] - 17*block[i + 4*3];
-        const int z3 = 17* block[i + 4*1] +  7*block[i + 4*3];
+        const int z0 = 13 * (block[i + 4 * 0] +      block[i + 4 * 2]);
+        const int z1 = 13 * (block[i + 4 * 0] -      block[i + 4 * 2]);
+        const int z2 =  7 *  block[i + 4 * 1] - 17 * block[i + 4 * 3];
+        const int z3 = 17 *  block[i + 4 * 1] +  7 * block[i + 4 * 3];
         const int rr = (dc + 0x80000);
 
-        dst[i + stride*0] = av_clip_uint8( dst[i + stride*0] + (((z0 + z3)*qmul + rr) >> 20) );
-        dst[i + stride*1] = av_clip_uint8( dst[i + stride*1] + (((z1 + z2)*qmul + rr) >> 20) );
-        dst[i + stride*2] = av_clip_uint8( dst[i + stride*2] + (((z1 - z2)*qmul + rr) >> 20) );
-        dst[i + stride*3] = av_clip_uint8( dst[i + stride*3] + (((z0 - z3)*qmul + rr) >> 20) );
+        dst[i + stride * 0] = av_clip_uint8(dst[i + stride * 0] + ((z0 + z3) * qmul + rr >> 20));
+        dst[i + stride * 1] = av_clip_uint8(dst[i + stride * 1] + ((z1 + z2) * qmul + rr >> 20));
+        dst[i + stride * 2] = av_clip_uint8(dst[i + stride * 2] + ((z1 - z2) * qmul + rr >> 20));
+        dst[i + stride * 3] = av_clip_uint8(dst[i + stride * 3] + ((z0 - z3) * qmul + rr >> 20));
     }
 }
 
@@ -214,46 +219,46 @@
     { luma_dc_zigzag_scan, zigzag_scan, svq3_scan, chroma_dc_scan };
 
     int run, level, sign, vlc, limit;
-    const int intra = (3 * type) >> 2;
+    const int intra           = 3 * type >> 2;
     const uint8_t *const scan = scan_patterns[type];
 
     for (limit = (16 >> intra); index < 16; index = limit, limit += 8) {
         for (; (vlc = svq3_get_ue_golomb(gb)) != 0; index++) {
+            if (vlc < 0)
+                return -1;
 
-          if (vlc < 0)
-              return -1;
+            sign = (vlc & 0x1) - 1;
+            vlc  = vlc + 1 >> 1;
 
-          sign = (vlc & 0x1) - 1;
-          vlc  = (vlc + 1) >> 1;
+            if (type == 3) {
+                if (vlc < 3) {
+                    run   = 0;
+                    level = vlc;
+                } else if (vlc < 4) {
+                    run   = 1;
+                    level = 1;
+                } else {
+                    run   = vlc & 0x3;
+                    level = (vlc + 9 >> 2) - run;
+                }
+            } else {
+                if (vlc < 16U) {
+                    run   = svq3_dct_tables[intra][vlc].run;
+                    level = svq3_dct_tables[intra][vlc].level;
+                } else if (intra) {
+                    run   = vlc & 0x7;
+                    level = (vlc >> 3) + ((run == 0) ? 8 : ((run < 2) ? 2 : ((run < 5) ? 0 : -1)));
+                } else {
+                    run   = vlc & 0xF;
+                    level = (vlc >> 4) + ((run == 0) ? 4 : ((run < 3) ? 2 : ((run < 10) ? 1 : 0)));
+                }
+            }
 
-          if (type == 3) {
-              if (vlc < 3) {
-                  run   = 0;
-                  level = vlc;
-              } else if (vlc < 4) {
-                  run   = 1;
-                  level = 1;
-              } else {
-                  run   = (vlc & 0x3);
-                  level = ((vlc + 9) >> 2) - run;
-              }
-          } else {
-              if (vlc < 16U) {
-                  run   = svq3_dct_tables[intra][vlc].run;
-                  level = svq3_dct_tables[intra][vlc].level;
-              } else if (intra) {
-                  run   = (vlc & 0x7);
-                  level = (vlc >> 3) + ((run == 0) ? 8 : ((run < 2) ? 2 : ((run < 5) ? 0 : -1)));
-              } else {
-                  run   = (vlc & 0xF);
-                  level = (vlc >> 4) + ((run == 0) ? 4 : ((run < 3) ? 2 : ((run < 10) ? 1 : 0)));
-              }
-          }
 
-          if ((index += run) >= limit)
-              return -1;
+            if ((index += run) >= limit)
+                return -1;
 
-          block[scan[index]] = (level ^ sign) - sign;
+            block[scan[index]] = (level ^ sign) - sign;
         }
 
         if (type != 2) {
@@ -272,41 +277,44 @@
     const Picture *pic = (dir == 0) ? &s->last_picture : &s->next_picture;
     uint8_t *src, *dest;
     int i, emu = 0;
-    int blocksize = 2 - (width>>3); //16->0, 8->1, 4->2
+    int blocksize = 2 - (width >> 3); // 16->0, 8->1, 4->2
 
     mx += x;
     my += y;
 
-    if (mx < 0 || mx >= (s->h_edge_pos - width  - 1) ||
-        my < 0 || my >= (s->v_edge_pos - height - 1)) {
-
-        if ((s->flags & CODEC_FLAG_EMU_EDGE)) {
+    if (mx < 0 || mx >= s->h_edge_pos - width  - 1 ||
+        my < 0 || my >= s->v_edge_pos - height - 1) {
+        if ((s->flags & CODEC_FLAG_EMU_EDGE))
             emu = 1;
-        }
 
-        mx = av_clip (mx, -16, (s->h_edge_pos - width  + 15));
-        my = av_clip (my, -16, (s->v_edge_pos - height + 15));
+        mx = av_clip(mx, -16, s->h_edge_pos - width  + 15);
+        my = av_clip(my, -16, s->v_edge_pos - height + 15);
     }
 
     /* form component predictions */
-    dest = s->current_picture.f.data[0] + x + y*s->linesize;
-    src  = pic->f.data[0] + mx + my*s->linesize;
+    dest = s->current_picture.f.data[0] + x + y * s->linesize;
+    src  = pic->f.data[0] + mx + my * s->linesize;
 
     if (emu) {
-        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);
+        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;
     }
     if (thirdpel)
-        (avg ? s->dsp.avg_tpel_pixels_tab : s->dsp.put_tpel_pixels_tab)[dxy](dest, src, s->linesize, width, height);
+        (avg ? s->dsp.avg_tpel_pixels_tab
+             : s->dsp.put_tpel_pixels_tab)[dxy](dest, src, s->linesize,
+                                                width, height);
     else
-        (avg ? s->dsp.avg_pixels_tab : s->dsp.put_pixels_tab)[blocksize][dxy](dest, src, s->linesize, height);
+        (avg ? s->dsp.avg_pixels_tab
+             : s->dsp.put_pixels_tab)[blocksize][dxy](dest, src, s->linesize,
+                                                      height);
 
     if (!(s->flags & CODEC_FLAG_GRAY)) {
-        mx     = (mx + (mx < (int) x)) >> 1;
-        my     = (my + (my < (int) y)) >> 1;
-        width  = (width  >> 1);
-        height = (height >> 1);
+        mx     = mx + (mx < (int) x) >> 1;
+        my     = my + (my < (int) y) >> 1;
+        width  = width  >> 1;
+        height = height >> 1;
         blocksize++;
 
         for (i = 1; i < 3; i++) {
@@ -314,55 +322,69 @@
             src  = pic->f.data[i] + mx + my * s->uvlinesize;
 
             if (emu) {
-                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));
+                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;
             }
             if (thirdpel)
-                (avg ? s->dsp.avg_tpel_pixels_tab : s->dsp.put_tpel_pixels_tab)[dxy](dest, src, s->uvlinesize, width, height);
+                (avg ? s->dsp.avg_tpel_pixels_tab
+                     : s->dsp.put_tpel_pixels_tab)[dxy](dest, src,
+                                                        s->uvlinesize,
+                                                        width, height);
             else
-                (avg ? s->dsp.avg_pixels_tab : s->dsp.put_pixels_tab)[blocksize][dxy](dest, src, s->uvlinesize, height);
+                (avg ? s->dsp.avg_pixels_tab
+                     : s->dsp.put_pixels_tab)[blocksize][dxy](dest, src,
+                                                              s->uvlinesize,
+                                                              height);
         }
     }
 }
 
-static inline int svq3_mc_dir(H264Context *h, int size, int mode, int dir,
-                              int avg)
+static inline int svq3_mc_dir(H264Context *h, int size, int mode,
+                              int dir, int avg)
 {
     int i, j, k, mx, my, dx, dy, x, y;
-    MpegEncContext *const s = (MpegEncContext *) h;
-    const int part_width  = ((size & 5) == 4) ? 4 : 16 >> (size & 1);
-    const int part_height = 16 >> ((unsigned) (size + 1) / 3);
-    const int extra_width = (mode == PREDICT_MODE) ? -16*6 : 0;
-    const int h_edge_pos  = 6*(s->h_edge_pos - part_width ) - extra_width;
-    const int v_edge_pos  = 6*(s->v_edge_pos - part_height) - extra_width;
+    MpegEncContext *const s = (MpegEncContext *)h;
+    const int part_width    = ((size & 5) == 4) ? 4 : 16 >> (size & 1);
+    const int part_height   = 16 >> ((unsigned)(size + 1) / 3);
+    const int extra_width   = (mode == PREDICT_MODE) ? -16 * 6 : 0;
+    const int h_edge_pos    = 6 * (s->h_edge_pos - part_width)  - extra_width;
+    const int v_edge_pos    = 6 * (s->v_edge_pos - part_height) - extra_width;
 
-    for (i = 0; i < 16; i += part_height) {
+    for (i = 0; i < 16; i += part_height)
         for (j = 0; j < 16; j += part_width) {
-            const int b_xy = (4*s->mb_x + (j >> 2)) + (4*s->mb_y + (i >> 2))*h->b_stride;
+            const int b_xy = (4 * s->mb_x + (j >> 2)) +
+                             (4 * s->mb_y + (i >> 2)) * h->b_stride;
             int dxy;
-            x = 16*s->mb_x + j;
-            y = 16*s->mb_y + i;
-            k = ((j >> 2) & 1) + ((i >> 1) & 2) + ((j >> 1) & 4) + (i & 8);
+            x = 16 * s->mb_x + j;
+            y = 16 * s->mb_y + i;
+            k = (j >> 2 & 1) + (i >> 1 & 2) +
+                (j >> 1 & 4) + (i      & 8);
 
             if (mode != PREDICT_MODE) {
-                pred_motion(h, k, (part_width >> 2), dir, 1, &mx, &my);
+                pred_motion(h, k, part_width >> 2, dir, 1, &mx, &my);
             } else {
                 mx = s->next_picture.f.motion_val[0][b_xy][0] << 1;
                 my = s->next_picture.f.motion_val[0][b_xy][1] << 1;
 
                 if (dir == 0) {
-                    mx = ((mx * h->frame_num_offset) / h->prev_frame_num_offset + 1) >> 1;
-                    my = ((my * h->frame_num_offset) / h->prev_frame_num_offset + 1) >> 1;
+                    mx = mx * h->frame_num_offset /
+                         h->prev_frame_num_offset + 1 >> 1;
+                    my = my * h->frame_num_offset /
+                         h->prev_frame_num_offset + 1 >> 1;
                 } else {
-                    mx = ((mx * (h->frame_num_offset - h->prev_frame_num_offset)) / h->prev_frame_num_offset + 1) >> 1;
-                    my = ((my * (h->frame_num_offset - h->prev_frame_num_offset)) / h->prev_frame_num_offset + 1) >> 1;
+                    mx = mx * (h->frame_num_offset - h->prev_frame_num_offset) /
+                         h->prev_frame_num_offset + 1 >> 1;
+                    my = my * (h->frame_num_offset - h->prev_frame_num_offset) /
+                         h->prev_frame_num_offset + 1 >> 1;
                 }
             }
 
             /* clip motion vector prediction to frame border */
-            mx = av_clip(mx, extra_width - 6*x, h_edge_pos - 6*x);
-            my = av_clip(my, extra_width - 6*y, v_edge_pos - 6*y);
+            mx = av_clip(mx, extra_width - 6 * x, h_edge_pos - 6 * x);
+            my = av_clip(my, extra_width - 6 * y, v_edge_pos - 6 * y);
 
             /* get (optional) motion vector differential */
             if (mode == PREDICT_MODE) {
@@ -380,49 +402,49 @@
             /* compute motion vector */
             if (mode == THIRDPEL_MODE) {
                 int fx, fy;
-                mx  = ((mx + 1)>>1) + dx;
-                my  = ((my + 1)>>1) + dy;
-                fx  = ((unsigned)(mx + 0x3000))/3 - 0x1000;
-                fy  = ((unsigned)(my + 0x3000))/3 - 0x1000;
-                dxy = (mx - 3*fx) + 4*(my - 3*fy);
+                mx  = (mx + 1 >> 1) + dx;
+                my  = (my + 1 >> 1) + dy;
+                fx  = (unsigned)(mx + 0x3000) / 3 - 0x1000;
+                fy  = (unsigned)(my + 0x3000) / 3 - 0x1000;
+                dxy = (mx - 3 * fx) + 4 * (my - 3 * fy);
 
-                svq3_mc_dir_part(s, x, y, part_width, part_height, fx, fy, dxy, 1, dir, avg);
+                svq3_mc_dir_part(s, x, y, part_width, part_height,
+                                 fx, fy, dxy, 1, dir, avg);
                 mx += mx;
                 my += my;
             } else if (mode == HALFPEL_MODE || mode == PREDICT_MODE) {
-                mx  = ((unsigned)(mx + 1 + 0x3000))/3 + dx - 0x1000;
-                my  = ((unsigned)(my + 1 + 0x3000))/3 + dy - 0x1000;
-                dxy = (mx&1) + 2*(my&1);
+                mx  = (unsigned)(mx + 1 + 0x3000) / 3 + dx - 0x1000;
+                my  = (unsigned)(my + 1 + 0x3000) / 3 + dy - 0x1000;
+                dxy = (mx & 1) + 2 * (my & 1);
 
-                svq3_mc_dir_part(s, x, y, part_width, part_height, mx>>1, my>>1, dxy, 0, dir, avg);
+                svq3_mc_dir_part(s, x, y, part_width, part_height,
+                                 mx >> 1, my >> 1, dxy, 0, dir, avg);
                 mx *= 3;
                 my *= 3;
             } else {
-                mx = ((unsigned)(mx + 3 + 0x6000))/6 + dx - 0x1000;
-                my = ((unsigned)(my + 3 + 0x6000))/6 + dy - 0x1000;
+                mx = (unsigned)(mx + 3 + 0x6000) / 6 + dx - 0x1000;
+                my = (unsigned)(my + 3 + 0x6000) / 6 + dy - 0x1000;
 
-                svq3_mc_dir_part(s, x, y, part_width, part_height, mx, my, 0, 0, dir, avg);
+                svq3_mc_dir_part(s, x, y, part_width, part_height,
+                                 mx, my, 0, 0, dir, avg);
                 mx *= 6;
                 my *= 6;
             }
 
             /* update mv_cache */
             if (mode != PREDICT_MODE) {
-                int32_t mv = pack16to32(mx,my);
+                int32_t mv = pack16to32(mx, my);
 
                 if (part_height == 8 && i < 8) {
-                    *(int32_t *) h->mv_cache[dir][scan8[k] + 1*8] = mv;
+                    AV_WN32A(h->mv_cache[dir][scan8[k] + 1 * 8], mv);
 
-                    if (part_width == 8 && j < 8) {
-                        *(int32_t *) h->mv_cache[dir][scan8[k] + 1 + 1*8] = mv;
-                    }
+                    if (part_width == 8 && j < 8)
+                        AV_WN32A(h->mv_cache[dir][scan8[k] + 1 + 1 * 8], mv);
                 }
-                if (part_width == 8 && j < 8) {
-                    *(int32_t *) h->mv_cache[dir][scan8[k] + 1] = mv;
-                }
-                if (part_width == 4 || part_height == 4) {
-                    *(int32_t *) h->mv_cache[dir][scan8[k]] = mv;
-                }
+                if (part_width == 8 && j < 8)
+                    AV_WN32A(h->mv_cache[dir][scan8[k] + 1], mv);
+                if (part_width == 4 || part_height == 4)
+                    AV_WN32A(h->mv_cache[dir][scan8[k]], mv);
             }
 
             /* write back motion vectors */
@@ -430,7 +452,6 @@
                            part_width >> 2, part_height >> 2, h->b_stride,
                            pack16to32(mx, my), 4);
         }
-    }
 
     return 0;
 }
@@ -442,21 +463,23 @@
     int cbp = 0;
     uint32_t vlc;
     int8_t *top, *left;
-    MpegEncContext *const s = (MpegEncContext *) h;
-    const int mb_xy = h->mb_xy;
-    const int b_xy  = 4*s->mb_x + 4*s->mb_y*h->b_stride;
+    MpegEncContext *const s = (MpegEncContext *)h;
+    const int mb_xy         = h->mb_xy;
+    const int b_xy          = 4 * s->mb_x + 4 * s->mb_y * h->b_stride;
 
     h->top_samples_available      = (s->mb_y == 0) ? 0x33FF : 0xFFFF;
     h->left_samples_available     = (s->mb_x == 0) ? 0x5F5F : 0xFFFF;
     h->topright_samples_available = 0xFFFF;
 
     if (mb_type == 0) {           /* SKIP */
-        if (s->pict_type == AV_PICTURE_TYPE_P || s->next_picture.f.mb_type[mb_xy] == -1) {
-            svq3_mc_dir_part(s, 16*s->mb_x, 16*s->mb_y, 16, 16, 0, 0, 0, 0, 0, 0);
+        if (s->pict_type == AV_PICTURE_TYPE_P ||
+            s->next_picture.f.mb_type[mb_xy] == -1) {
+            svq3_mc_dir_part(s, 16 * s->mb_x, 16 * s->mb_y, 16, 16,
+                             0, 0, 0, 0, 0, 0);
 
-            if (s->pict_type == AV_PICTURE_TYPE_B) {
-                svq3_mc_dir_part(s, 16*s->mb_x, 16*s->mb_y, 16, 16, 0, 0, 0, 0, 1, 1);
-            }
+            if (s->pict_type == AV_PICTURE_TYPE_B)
+                svq3_mc_dir_part(s, 16 * s->mb_x, 16 * s->mb_y, 16, 16,
+                                 0, 0, 0, 0, 1, 1);
 
             mb_type = MB_TYPE_SKIP;
         } else {
@@ -469,51 +492,57 @@
             mb_type = MB_TYPE_16x16;
         }
     } else if (mb_type < 8) {     /* INTER */
-        if (svq3->thirdpel_flag && svq3->halfpel_flag == !get_bits1 (&s->gb)) {
+        if (svq3->thirdpel_flag && svq3->halfpel_flag == !get_bits1(&s->gb))
             mode = THIRDPEL_MODE;
-        } else if (svq3->halfpel_flag && svq3->thirdpel_flag == !get_bits1 (&s->gb)) {
+        else if (svq3->halfpel_flag &&
+                 svq3->thirdpel_flag == !get_bits1(&s->gb))
             mode = HALFPEL_MODE;
-        } else {
+        else
             mode = FULLPEL_MODE;
-        }
 
         /* fill caches */
         /* note ref_cache should contain here:
-            ????????
-            ???11111
-            N??11111
-            N??11111
-            N??11111
-        */
+         *  ????????
+         *  ???11111
+         *  N??11111
+         *  N??11111
+         *  N??11111
+         */
 
         for (m = 0; m < 2; m++) {
-            if (s->mb_x > 0 && h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - 1]+6] != -1) {
-                for (i = 0; i < 4; i++) {
-                    *(uint32_t *) h->mv_cache[m][scan8[0] - 1 + i*8] = *(uint32_t *) s->current_picture.f.motion_val[m][b_xy - 1 + i*h->b_stride];
-                }
+            if (s->mb_x > 0 && h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - 1] + 6] != -1) {
+                for (i = 0; i < 4; i++)
+                    AV_COPY32(h->mv_cache[m][scan8[0] - 1 + i * 8],
+                              s->current_picture.f.motion_val[m][b_xy - 1 + i * h->b_stride]);
             } else {
-                for (i = 0; i < 4; i++) {
-                    *(uint32_t *) h->mv_cache[m][scan8[0] - 1 + i*8] = 0;
-                }
+                for (i = 0; i < 4; i++)
+                    AV_ZERO32(h->mv_cache[m][scan8[0] - 1 + i * 8]);
             }
             if (s->mb_y > 0) {
-                memcpy(h->mv_cache[m][scan8[0] - 1*8], s->current_picture.f.motion_val[m][b_xy - h->b_stride], 4*2*sizeof(int16_t));
-                memset(&h->ref_cache[m][scan8[0] - 1*8], (h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride]] == -1) ? PART_NOT_AVAILABLE : 1, 4);
+                memcpy(h->mv_cache[m][scan8[0] - 1 * 8],
+                       s->current_picture.f.motion_val[m][b_xy - h->b_stride],
+                       4 * 2 * sizeof(int16_t));
+                memset(&h->ref_cache[m][scan8[0] - 1 * 8],
+                       (h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride]] == -1) ? PART_NOT_AVAILABLE : 1, 4);
 
-                if (s->mb_x < (s->mb_width - 1)) {
-                    *(uint32_t *) h->mv_cache[m][scan8[0] + 4 - 1*8] = *(uint32_t *) s->current_picture.f.motion_val[m][b_xy - h->b_stride + 4];
-                    h->ref_cache[m][scan8[0] + 4 - 1*8] =
-                        (h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride + 1]+6] == -1 ||
-                         h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride    ]  ] == -1) ? PART_NOT_AVAILABLE : 1;
-                }else
-                    h->ref_cache[m][scan8[0] + 4 - 1*8] = PART_NOT_AVAILABLE;
+                if (s->mb_x < s->mb_width - 1) {
+                    AV_COPY32(h->mv_cache[m][scan8[0] + 4 - 1 * 8],
+                              s->current_picture.f.motion_val[m][b_xy - h->b_stride + 4]);
+                    h->ref_cache[m][scan8[0] + 4 - 1 * 8] =
+                        (h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride + 1] + 6] == -1 ||
+                         h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride]] == -1) ? PART_NOT_AVAILABLE : 1;
+                } else
+                    h->ref_cache[m][scan8[0] + 4 - 1 * 8] = PART_NOT_AVAILABLE;
                 if (s->mb_x > 0) {
-                    *(uint32_t *) h->mv_cache[m][scan8[0] - 1 - 1*8] = *(uint32_t *) s->current_picture.f.motion_val[m][b_xy - h->b_stride - 1];
-                    h->ref_cache[m][scan8[0] - 1 - 1*8] = (h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride - 1]+3] == -1) ? PART_NOT_AVAILABLE : 1;
-                }else
-                    h->ref_cache[m][scan8[0] - 1 - 1*8] = PART_NOT_AVAILABLE;
-            }else
-                memset(&h->ref_cache[m][scan8[0] - 1*8 - 1], PART_NOT_AVAILABLE, 8);
+                    AV_COPY32(h->mv_cache[m][scan8[0] - 1 - 1 * 8],
+                              s->current_picture.f.motion_val[m][b_xy - h->b_stride - 1]);
+                    h->ref_cache[m][scan8[0] - 1 - 1 * 8] =
+                        (h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride - 1] + 3] == -1) ? PART_NOT_AVAILABLE : 1;
+                } else
+                    h->ref_cache[m][scan8[0] - 1 - 1 * 8] = PART_NOT_AVAILABLE;
+            } else
+                memset(&h->ref_cache[m][scan8[0] - 1 * 8 - 1],
+                       PART_NOT_AVAILABLE, 8);
 
             if (s->pict_type != AV_PICTURE_TYPE_B)
                 break;
@@ -521,75 +550,71 @@
 
         /* decode motion vector(s) and form prediction(s) */
         if (s->pict_type == AV_PICTURE_TYPE_P) {
-            if (svq3_mc_dir(h, (mb_type - 1), mode, 0, 0) < 0)
+            if (svq3_mc_dir(h, mb_type - 1, mode, 0, 0) < 0)
                 return -1;
         } else {        /* AV_PICTURE_TYPE_B */
             if (mb_type != 2) {
                 if (svq3_mc_dir(h, 0, mode, 0, 0) < 0)
                     return -1;
             } else {
-                for (i = 0; i < 4; i++) {
-                    memset(s->current_picture.f.motion_val[0][b_xy + i*h->b_stride], 0, 4*2*sizeof(int16_t));
-                }
+                for (i = 0; i < 4; i++)
+                    memset(s->current_picture.f.motion_val[0][b_xy + i * h->b_stride],
+                           0, 4 * 2 * sizeof(int16_t));
             }
             if (mb_type != 1) {
-                if (svq3_mc_dir(h, 0, mode, 1, (mb_type == 3)) < 0)
+                if (svq3_mc_dir(h, 0, mode, 1, mb_type == 3) < 0)
                     return -1;
             } else {
-                for (i = 0; i < 4; i++) {
-                    memset(s->current_picture.f.motion_val[1][b_xy + i*h->b_stride], 0, 4*2*sizeof(int16_t));
-                }
+                for (i = 0; i < 4; i++)
+                    memset(s->current_picture.f.motion_val[1][b_xy + i * h->b_stride],
+                           0, 4 * 2 * sizeof(int16_t));
             }
         }
 
         mb_type = MB_TYPE_16x16;
     } else if (mb_type == 8 || mb_type == 33) {   /* INTRA4x4 */
-        memset(h->intra4x4_pred_mode_cache, -1, 8*5*sizeof(int8_t));
+        memset(h->intra4x4_pred_mode_cache, -1, 8 * 5 * sizeof(int8_t));
 
         if (mb_type == 8) {
             if (s->mb_x > 0) {
-                for (i = 0; i < 4; i++) {
-                    h->intra4x4_pred_mode_cache[scan8[0] - 1 + i*8] = h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - 1]+6-i];
-                }
-                if (h->intra4x4_pred_mode_cache[scan8[0] - 1] == -1) {
+                for (i = 0; i < 4; i++)
+                    h->intra4x4_pred_mode_cache[scan8[0] - 1 + i * 8] = h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - 1] + 6 - i];
+                if (h->intra4x4_pred_mode_cache[scan8[0] - 1] == -1)
                     h->left_samples_available = 0x5F5F;
-                }
             }
             if (s->mb_y > 0) {
-                h->intra4x4_pred_mode_cache[4+8*0] = h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride]+0];
-                h->intra4x4_pred_mode_cache[5+8*0] = h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride]+1];
-                h->intra4x4_pred_mode_cache[6+8*0] = h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride]+2];
-                h->intra4x4_pred_mode_cache[7+8*0] = h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride]+3];
+                h->intra4x4_pred_mode_cache[4 + 8 * 0] = h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride] + 0];
+                h->intra4x4_pred_mode_cache[5 + 8 * 0] = h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride] + 1];
+                h->intra4x4_pred_mode_cache[6 + 8 * 0] = h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride] + 2];
+                h->intra4x4_pred_mode_cache[7 + 8 * 0] = h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride] + 3];
 
-                if (h->intra4x4_pred_mode_cache[4+8*0] == -1) {
+                if (h->intra4x4_pred_mode_cache[4 + 8 * 0] == -1)
                     h->top_samples_available = 0x33FF;
-                }
             }
 
             /* decode prediction codes for luma blocks */
-            for (i = 0; i < 16; i+=2) {
+            for (i = 0; i < 16; i += 2) {
                 vlc = svq3_get_ue_golomb(&s->gb);
 
-                if (vlc >= 25U){
+                if (vlc >= 25U) {
                     av_log(h->s.avctx, AV_LOG_ERROR, "luma prediction:%d\n", vlc);
                     return -1;
                 }
 
-                left    = &h->intra4x4_pred_mode_cache[scan8[i] - 1];
-                top     = &h->intra4x4_pred_mode_cache[scan8[i] - 8];
+                left = &h->intra4x4_pred_mode_cache[scan8[i] - 1];
+                top  = &h->intra4x4_pred_mode_cache[scan8[i] - 8];
 
                 left[1] = svq3_pred_1[top[0] + 1][left[0] + 1][svq3_pred_0[vlc][0]];
                 left[2] = svq3_pred_1[top[1] + 1][left[1] + 1][svq3_pred_0[vlc][1]];
 
-                if (left[1] == -1 || left[2] == -1){
+                if (left[1] == -1 || left[2] == -1) {
                     av_log(h->s.avctx, AV_LOG_ERROR, "weird prediction\n");
                     return -1;
                 }
             }
         } else {    /* mb_type == 33, DC_128_PRED block type */
-            for (i = 0; i < 4; i++) {
-                memset(&h->intra4x4_pred_mode_cache[scan8[0] + 8*i], DC_PRED, 4);
-            }
+            for (i = 0; i < 4; i++)
+                memset(&h->intra4x4_pred_mode_cache[scan8[0] + 8 * i], DC_PRED, 4);
         }
 
         write_back_intra_pred_mode(h);
@@ -600,9 +625,8 @@
             h->top_samples_available  = (s->mb_y == 0) ? 0x33FF : 0xFFFF;
             h->left_samples_available = (s->mb_x == 0) ? 0x5F5F : 0xFFFF;
         } else {
-            for (i = 0; i < 4; i++) {
-                memset(&h->intra4x4_pred_mode_cache[scan8[0] + 8*i], DC_128_PRED, 4);
-            }
+            for (i = 0; i < 4; i++)
+                memset(&h->intra4x4_pred_mode_cache[scan8[0] + 8 * i], DC_128_PRED, 4);
 
             h->top_samples_available  = 0x33FF;
             h->left_samples_available = 0x5F5F;
@@ -611,95 +635,102 @@
         mb_type = MB_TYPE_INTRA4x4;
     } else {                      /* INTRA16x16 */
         dir = i_mb_type_info[mb_type - 8].pred_mode;
-        dir = (dir >> 1) ^ 3*(dir & 1) ^ 1;
+        dir = (dir >> 1) ^ 3 * (dir & 1) ^ 1;
 
-        if ((h->intra16x16_pred_mode = ff_h264_check_intra_pred_mode(h, dir, 0)) == -1){
+        if ((h->intra16x16_pred_mode = ff_h264_check_intra_pred_mode(h, dir, 0)) == -1) {
             av_log(h->s.avctx, AV_LOG_ERROR, "check_intra_pred_mode = -1\n");
             return -1;
         }
 
-        cbp = i_mb_type_info[mb_type - 8].cbp;
+        cbp     = i_mb_type_info[mb_type - 8].cbp;
         mb_type = MB_TYPE_INTRA16x16;
     }
 
     if (!IS_INTER(mb_type) && s->pict_type != AV_PICTURE_TYPE_I) {
-        for (i = 0; i < 4; i++) {
-            memset(s->current_picture.f.motion_val[0][b_xy + i*h->b_stride], 0, 4*2*sizeof(int16_t));
-        }
+        for (i = 0; i < 4; i++)
+            memset(s->current_picture.f.motion_val[0][b_xy + i * h->b_stride],
+                   0, 4 * 2 * sizeof(int16_t));
         if (s->pict_type == AV_PICTURE_TYPE_B) {
-            for (i = 0; i < 4; i++) {
-                memset(s->current_picture.f.motion_val[1][b_xy + i*h->b_stride], 0, 4*2*sizeof(int16_t));
-            }
+            for (i = 0; i < 4; i++)
+                memset(s->current_picture.f.motion_val[1][b_xy + i * h->b_stride],
+                       0, 4 * 2 * sizeof(int16_t));
         }
     }
     if (!IS_INTRA4x4(mb_type)) {
-        memset(h->intra4x4_pred_mode+h->mb2br_xy[mb_xy], DC_PRED, 8);
+        memset(h->intra4x4_pred_mode + h->mb2br_xy[mb_xy], DC_PRED, 8);
     }
     if (!IS_SKIP(mb_type) || s->pict_type == AV_PICTURE_TYPE_B) {
-        memset(h->non_zero_count_cache + 8, 0, 14*8*sizeof(uint8_t));
-        s->dsp.clear_blocks(h->mb+  0);
-        s->dsp.clear_blocks(h->mb+384);
+        memset(h->non_zero_count_cache + 8, 0, 14 * 8 * sizeof(uint8_t));
+        s->dsp.clear_blocks(h->mb +   0);
+        s->dsp.clear_blocks(h->mb + 384);
     }
 
-    if (!IS_INTRA16x16(mb_type) && (!IS_SKIP(mb_type) || s->pict_type == AV_PICTURE_TYPE_B)) {
+    if (!IS_INTRA16x16(mb_type) &&
+        (!IS_SKIP(mb_type) || s->pict_type == AV_PICTURE_TYPE_B)) {
         if ((vlc = svq3_get_ue_golomb(&s->gb)) >= 48U){
             av_log(h->s.avctx, AV_LOG_ERROR, "cbp_vlc=%d\n", vlc);
             return -1;
         }
 
-        cbp = IS_INTRA(mb_type) ? golomb_to_intra4x4_cbp[vlc] : golomb_to_inter_cbp[vlc];
+        cbp = IS_INTRA(mb_type) ? golomb_to_intra4x4_cbp[vlc]
+                                : golomb_to_inter_cbp[vlc];
     }
-    if (IS_INTRA16x16(mb_type) || (s->pict_type != AV_PICTURE_TYPE_I && s->adaptive_quant && cbp)) {
+    if (IS_INTRA16x16(mb_type) ||
+        (s->pict_type != AV_PICTURE_TYPE_I && s->adaptive_quant && cbp)) {
         s->qscale += svq3_get_se_golomb(&s->gb);
 
-        if (s->qscale > 31U){
+        if (s->qscale > 31u) {
             av_log(h->s.avctx, AV_LOG_ERROR, "qscale:%d\n", s->qscale);
             return -1;
         }
     }
     if (IS_INTRA16x16(mb_type)) {
-        AV_ZERO128(h->mb_luma_dc[0]+0);
-        AV_ZERO128(h->mb_luma_dc[0]+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");
+        AV_ZERO128(h->mb_luma_dc[0] + 0);
+        AV_ZERO128(h->mb_luma_dc[0] + 8);
+        if (svq3_decode_block(&s->gb, h->mb_luma_dc[0], 0, 1)) {
+            av_log(h->s.avctx, AV_LOG_ERROR,
+                   "error while decoding intra luma dc\n");
             return -1;
         }
     }
 
     if (cbp) {
         const int index = IS_INTRA16x16(mb_type) ? 1 : 0;
-        const int type = ((s->qscale < 24 && IS_INTRA4x4(mb_type)) ? 2 : 1);
+        const int type  = ((s->qscale < 24 && IS_INTRA4x4(mb_type)) ? 2 : 1);
 
-        for (i = 0; i < 4; i++) {
+        for (i = 0; i < 4; i++)
             if ((cbp & (1 << i))) {
                 for (j = 0; j < 4; j++) {
-                    k = index ? ((j&1) + 2*(i&1) + 2*(j&2) + 4*(i&2)) : (4*i + j);
-                    h->non_zero_count_cache[ scan8[k] ] = 1;
+                    k = index ? (1 * (j & 1) + 2 * (i & 1) +
+                                 2 * (j & 2) + 4 * (i & 2))
+                              : (4 * i + j);
+                    h->non_zero_count_cache[scan8[k]] = 1;
 
-                    if (svq3_decode_block(&s->gb, &h->mb[16*k], index, type)){
-                        av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding block\n");
+                    if (svq3_decode_block(&s->gb, &h->mb[16 * k], index, type)) {
+                        av_log(h->s.avctx, AV_LOG_ERROR,
+                               "error while decoding block\n");
                         return -1;
                     }
                 }
             }
-        }
 
         if ((cbp & 0x30)) {
-            for (i = 1; i < 3; ++i) {
-              if (svq3_decode_block(&s->gb, &h->mb[16*16*i], 0, 3)){
-                av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding chroma dc block\n");
-                return -1;
-              }
-            }
+            for (i = 1; i < 3; ++i)
+                if (svq3_decode_block(&s->gb, &h->mb[16 * 16 * i], 0, 3)) {
+                    av_log(h->s.avctx, AV_LOG_ERROR,
+                           "error while decoding chroma dc block\n");
+                    return -1;
+                }
 
             if ((cbp & 0x20)) {
                 for (i = 1; i < 3; i++) {
                     for (j = 0; j < 4; j++) {
-                        k = 16*i + j;
-                        h->non_zero_count_cache[ scan8[k] ] = 1;
+                        k                                 = 16 * i + j;
+                        h->non_zero_count_cache[scan8[k]] = 1;
 
-                        if (svq3_decode_block(&s->gb, &h->mb[16*k], 1, 1)){
-                            av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding chroma ac block\n");
+                        if (svq3_decode_block(&s->gb, &h->mb[16 * k], 1, 1)) {
+                            av_log(h->s.avctx, AV_LOG_ERROR,
+                                   "error while decoding chroma ac block\n");
                             return -1;
                         }
                     }
@@ -708,12 +739,11 @@
         }
     }
 
-    h->cbp= cbp;
+    h->cbp                              = cbp;
     s->current_picture.f.mb_type[mb_xy] = mb_type;
 
-    if (IS_INTRA(mb_type)) {
+    if (IS_INTRA(mb_type))
         h->chroma_pred_mode = ff_h264_check_intra_pred_mode(h, DC_PRED8x8, 1);
-    }
 
     return 0;
 }
@@ -721,9 +751,9 @@
 static int svq3_decode_slice_header(AVCodecContext *avctx)
 {
     SVQ3Context *svq3 = avctx->priv_data;
-    H264Context *h = &svq3->h;
+    H264Context *h    = &svq3->h;
     MpegEncContext *s = &h->s;
-    const int mb_xy = h->mb_xy;
+    const int mb_xy   = h->mb_xy;
     int i, header;
 
     header = get_bits(&s->gb, 8);
@@ -733,30 +763,33 @@
         av_log(avctx, AV_LOG_ERROR, "unsupported slice header (%02X)\n", header);
         return -1;
     } else {
-        int length = (header >> 5) & 3;
+        int length = header >> 5 & 3;
 
-        svq3->next_slice_index = get_bits_count(&s->gb) + 8*show_bits(&s->gb, 8*length) + 8*length;
+        svq3->next_slice_index = get_bits_count(&s->gb) +
+                                 8 * show_bits(&s->gb, 8 * length) +
+                                 8 * length;
 
         if (svq3->next_slice_index > s->gb.size_in_bits) {
             av_log(avctx, AV_LOG_ERROR, "slice after bitstream end\n");
             return -1;
-    }
+        }
 
-        s->gb.size_in_bits = svq3->next_slice_index - 8*(length - 1);
+        s->gb.size_in_bits = svq3->next_slice_index - 8 * (length - 1);
         skip_bits(&s->gb, 8);
 
         if (svq3->watermark_key) {
-            uint32_t header = AV_RL32(&s->gb.buffer[(get_bits_count(&s->gb)>>3)+1]);
-            AV_WL32(&s->gb.buffer[(get_bits_count(&s->gb)>>3)+1], header ^ svq3->watermark_key);
+            uint32_t header = AV_RL32(&s->gb.buffer[(get_bits_count(&s->gb) >> 3) + 1]);
+            AV_WL32(&s->gb.buffer[(get_bits_count(&s->gb) >> 3) + 1],
+                    header ^ svq3->watermark_key);
         }
         if (length > 0) {
             memcpy((uint8_t *) &s->gb.buffer[get_bits_count(&s->gb) >> 3],
-                   &s->gb.buffer[s->gb.size_in_bits >> 3], (length - 1));
+                   &s->gb.buffer[s->gb.size_in_bits >> 3], length - 1);
         }
         skip_bits_long(&s->gb, 0);
     }
 
-    if ((i = svq3_get_ue_golomb(&s->gb)) >= 3U){
+    if ((i = svq3_get_ue_golomb(&s->gb)) >= 3U) {
         av_log(h->s.avctx, AV_LOG_ERROR, "illegal slice type %d \n", i);
         return -1;
     }
@@ -764,42 +797,43 @@
     h->slice_type = golomb_to_pict_type[i];
 
     if ((header & 0x9F) == 2) {
-        i = (s->mb_num < 64) ? 6 : (1 + av_log2 (s->mb_num - 1));
-        s->mb_skip_run = get_bits(&s->gb, i) - (s->mb_x + (s->mb_y * s->mb_width));
+        i              = (s->mb_num < 64) ? 6 : (1 + av_log2(s->mb_num - 1));
+        s->mb_skip_run = get_bits(&s->gb, i) -
+                         (s->mb_y * s->mb_width + s->mb_x);
     } else {
         skip_bits1(&s->gb);
         s->mb_skip_run = 0;
     }
 
-    h->slice_num = get_bits(&s->gb, 8);
-    s->qscale = get_bits(&s->gb, 5);
+    h->slice_num      = get_bits(&s->gb, 8);
+    s->qscale         = get_bits(&s->gb, 5);
     s->adaptive_quant = get_bits1(&s->gb);
 
     /* unknown fields */
     skip_bits1(&s->gb);
 
-    if (svq3->unknown_flag) {
+    if (svq3->unknown_flag)
         skip_bits1(&s->gb);
-    }
 
     skip_bits1(&s->gb);
     skip_bits(&s->gb, 2);
 
-    while (get_bits1(&s->gb)) {
+    while (get_bits1(&s->gb))
         skip_bits(&s->gb, 8);
-    }
 
     /* reset intra predictors and invalidate motion vector references */
     if (s->mb_x > 0) {
-        memset(h->intra4x4_pred_mode+h->mb2br_xy[mb_xy - 1      ]+3, -1, 4*sizeof(int8_t));
-        memset(h->intra4x4_pred_mode+h->mb2br_xy[mb_xy - s->mb_x]  , -1, 8*sizeof(int8_t)*s->mb_x);
+        memset(h->intra4x4_pred_mode + h->mb2br_xy[mb_xy - 1] + 3,
+               -1, 4 * sizeof(int8_t));
+        memset(h->intra4x4_pred_mode + h->mb2br_xy[mb_xy - s->mb_x],
+               -1, 8 * sizeof(int8_t) * s->mb_x);
     }
     if (s->mb_y > 0) {
-        memset(h->intra4x4_pred_mode+h->mb2br_xy[mb_xy - s->mb_stride], -1, 8*sizeof(int8_t)*(s->mb_width - s->mb_x));
+        memset(h->intra4x4_pred_mode + h->mb2br_xy[mb_xy - s->mb_stride],
+               -1, 8 * sizeof(int8_t) * (s->mb_width - s->mb_x));
 
-        if (s->mb_x > 0) {
-            h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride - 1]+3] = -1;
-        }
+        if (s->mb_x > 0)
+            h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride - 1] + 3] = -1;
     }
 
     return 0;
@@ -808,7 +842,7 @@
 static av_cold int svq3_decode_init(AVCodecContext *avctx)
 {
     SVQ3Context *svq3 = avctx->priv_data;
-    H264Context *h = &svq3->h;
+    H264Context *h    = &svq3->h;
     MpegEncContext *s = &h->s;
     int m;
     unsigned char *extradata;
@@ -819,12 +853,12 @@
     if (ff_h264_decode_init(avctx) < 0)
         return -1;
 
-    s->flags  = avctx->flags;
-    s->flags2 = avctx->flags2;
+    s->flags           = avctx->flags;
+    s->flags2          = avctx->flags2;
     s->unrestricted_mv = 1;
-    h->is_complex=1;
+    h->is_complex      = 1;
     h->sps.chroma_format_idc = 1;
-    avctx->pix_fmt = avctx->codec->pix_fmts[0];
+    avctx->pix_fmt     = avctx->codec->pix_fmts[0];
 
     if (!s->context_initialized) {
         h->chroma_qp[0] = h->chroma_qp[1] = 4;
@@ -835,7 +869,7 @@
 
 
         /* prowl for the "SEQH" marker in the extradata */
-        extradata = (unsigned char *)avctx->extradata;
+        extradata     = (unsigned char *)avctx->extradata;
         extradata_end = avctx->extradata + avctx->extradata_size;
         if (extradata) {
             for (m = 0; m + 8 < avctx->extradata_size; m++) {
@@ -849,29 +883,49 @@
 
         /* if a match was found, parse the extra data */
         if (marker_found) {
-
             GetBitContext gb;
             int frame_size_code;
 
             size = AV_RB32(&extradata[4]);
             if (size > extradata_end - extradata - 8)
                 return AVERROR_INVALIDDATA;
-            init_get_bits(&gb, extradata + 8, size*8);
+            init_get_bits(&gb, extradata + 8, size * 8);
 
             /* 'frame size code' and optional 'width, height' */
             frame_size_code = get_bits(&gb, 3);
             switch (frame_size_code) {
-                case 0: avctx->width = 160; avctx->height = 120; break;
-                case 1: avctx->width = 128; avctx->height =  96; break;
-                case 2: avctx->width = 176; avctx->height = 144; break;
-                case 3: avctx->width = 352; avctx->height = 288; break;
-                case 4: avctx->width = 704; avctx->height = 576; break;
-                case 5: avctx->width = 240; avctx->height = 180; break;
-                case 6: avctx->width = 320; avctx->height = 240; break;
-                case 7:
-                    avctx->width  = get_bits(&gb, 12);
-                    avctx->height = get_bits(&gb, 12);
-                    break;
+            case 0:
+                avctx->width  = 160;
+                avctx->height = 120;
+                break;
+            case 1:
+                avctx->width  = 128;
+                avctx->height =  96;
+                break;
+            case 2:
+                avctx->width  = 176;
+                avctx->height = 144;
+                break;
+            case 3:
+                avctx->width  = 352;
+                avctx->height = 288;
+                break;
+            case 4:
+                avctx->width  = 704;
+                avctx->height = 576;
+                break;
+            case 5:
+                avctx->width  = 240;
+                avctx->height = 180;
+                break;
+            case 6:
+                avctx->width  = 320;
+                avctx->height = 240;
+                break;
+            case 7:
+                avctx->width  = get_bits(&gb, 12);
+                avctx->height = get_bits(&gb, 12);
+                break;
             }
 
             svq3->halfpel_flag  = get_bits1(&gb);
@@ -888,41 +942,49 @@
             /* unknown field */
             skip_bits1(&gb);
 
-            while (get_bits1(&gb)) {
+            while (get_bits1(&gb))
                 skip_bits(&gb, 8);
-            }
 
-            svq3->unknown_flag = get_bits1(&gb);
+            svq3->unknown_flag  = get_bits1(&gb);
             avctx->has_b_frames = !s->low_delay;
             if (svq3->unknown_flag) {
 #if CONFIG_ZLIB
                 unsigned watermark_width  = svq3_get_ue_golomb(&gb);
                 unsigned watermark_height = svq3_get_ue_golomb(&gb);
-                int u1 = svq3_get_ue_golomb(&gb);
-                int u2 = get_bits(&gb, 8);
-                int u3 = get_bits(&gb, 2);
-                int u4 = svq3_get_ue_golomb(&gb);
-                unsigned long buf_len = watermark_width*watermark_height*4;
-                int offset = (get_bits_count(&gb)+7)>>3;
+                int u1                    = svq3_get_ue_golomb(&gb);
+                int u2                    = get_bits(&gb, 8);
+                int u3                    = get_bits(&gb, 2);
+                int u4                    = svq3_get_ue_golomb(&gb);
+                unsigned long buf_len     = watermark_width *
+                                            watermark_height * 4;
+                int offset                = get_bits_count(&gb) + 7 >> 3;
                 uint8_t *buf;
 
-                if (watermark_height<=0 || (uint64_t)watermark_width*4 > UINT_MAX/watermark_height)
+                if (watermark_height <= 0 || (uint64_t)watermark_width*4 > UINT_MAX/watermark_height)
                     return -1;
 
                 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, &buf_len, extradata + 8 + offset, size - offset) != Z_OK) {
-                    av_log(avctx, AV_LOG_ERROR, "could not uncompress watermark logo\n");
+                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, &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;
                 }
                 svq3->watermark_key = ff_svq1_packet_checksum(buf, buf_len, 0);
-                svq3->watermark_key = svq3->watermark_key << 16 | svq3->watermark_key;
-                av_log(avctx, AV_LOG_DEBUG, "watermark key %#x\n", svq3->watermark_key);
+                svq3->watermark_key = svq3->watermark_key << 16 |
+                                      svq3->watermark_key;
+                av_log(avctx, AV_LOG_DEBUG,
+                       "watermark key %#x\n", svq3->watermark_key);
                 av_free(buf);
 #else
-                av_log(avctx, AV_LOG_ERROR, "this svq3 file contains watermark which need zlib support compiled in\n");
+                av_log(avctx, AV_LOG_ERROR,
+                       "this svq3 file contains watermark which need zlib support compiled in\n");
                 return -1;
 #endif
             }
@@ -934,7 +996,7 @@
         if (ff_MPV_common_init(s) < 0)
             return -1;
 
-        h->b_stride = 4*s->mb_width;
+        h->b_stride = 4 * s->mb_width;
 
         if (ff_h264_alloc_tables(h) < 0) {
             av_log(avctx, AV_LOG_ERROR, "svq3 memory allocation failed\n");
@@ -945,14 +1007,13 @@
     return 0;
 }
 
-static int svq3_decode_frame(AVCodecContext *avctx,
-                             void *data, int *data_size,
-                             AVPacket *avpkt)
+static int svq3_decode_frame(AVCodecContext *avctx, void *data,
+                             int *data_size, AVPacket *avpkt)
 {
-    SVQ3Context *svq3 = avctx->priv_data;
-    H264Context *h = &svq3->h;
-    MpegEncContext *s = &h->s;
-    int buf_size = avpkt->size;
+    SVQ3Context *svq3  = avctx->priv_data;
+    H264Context *h     = &svq3->h;
+    MpegEncContext *s  = &h->s;
+    int buf_size       = avpkt->size;
     int m, mb_type, left;
     uint8_t *buf;
 
@@ -961,7 +1022,7 @@
         if (s->next_picture_ptr && !s->low_delay) {
             *(AVFrame *) data   = s->next_picture.f;
             s->next_picture_ptr = NULL;
-            *data_size = sizeof(AVFrame);
+            *data_size          = sizeof(AVFrame);
         }
         return 0;
     }
@@ -979,19 +1040,20 @@
         buf = avpkt->data;
     }
 
-    init_get_bits(&s->gb, buf, 8*buf_size);
+    init_get_bits(&s->gb, buf, 8 * buf_size);
 
     if (svq3_decode_slice_header(avctx))
         return -1;
 
-    s->pict_type = h->slice_type;
+    s->pict_type      = h->slice_type;
     s->picture_number = h->slice_num;
 
-    if (avctx->debug&FF_DEBUG_PICT_INFO){
-        av_log(h->s.avctx, AV_LOG_DEBUG, "%c hpel:%d, tpel:%d aqp:%d qp:%d, slice_num:%02X\n",
-               av_get_picture_type_char(s->pict_type), svq3->halfpel_flag, svq3->thirdpel_flag,
+    if (avctx->debug & FF_DEBUG_PICT_INFO)
+        av_log(h->s.avctx, AV_LOG_DEBUG,
+               "%c hpel:%d, tpel:%d aqp:%d qp:%d, slice_num:%02X\n",
+               av_get_picture_type_char(s->pict_type),
+               svq3->halfpel_flag, svq3->thirdpel_flag,
                s->adaptive_quant, s->qscale, h->slice_num);
-    }
 
     /* for skipping the frame */
     s->current_picture.f.pict_type = s->pict_type;
@@ -1000,9 +1062,9 @@
     /* Skip B-frames if we do not have reference frames. */
     if (s->last_picture_ptr == NULL && s->pict_type == AV_PICTURE_TYPE_B)
         return 0;
-    if (  (avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type == AV_PICTURE_TYPE_B)
-        ||(avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type != AV_PICTURE_TYPE_I)
-        || avctx->skip_frame >= AVDISCARD_ALL)
+    if (avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type == AV_PICTURE_TYPE_B ||
+        avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type != AV_PICTURE_TYPE_I ||
+        avctx->skip_frame >= AVDISCARD_ALL)
         return 0;
 
     if (s->next_p_frame_damaged) {
@@ -1016,45 +1078,44 @@
         return -1;
 
     if (s->pict_type == AV_PICTURE_TYPE_B) {
-        h->frame_num_offset = (h->slice_num - h->prev_frame_num);
+        h->frame_num_offset = h->slice_num - h->prev_frame_num;
 
-        if (h->frame_num_offset < 0) {
+        if (h->frame_num_offset < 0)
             h->frame_num_offset += 256;
-        }
-        if (h->frame_num_offset == 0 || h->frame_num_offset >= h->prev_frame_num_offset) {
+        if (h->frame_num_offset == 0 ||
+            h->frame_num_offset >= h->prev_frame_num_offset) {
             av_log(h->s.avctx, AV_LOG_ERROR, "error in B-frame picture id\n");
             return -1;
         }
     } else {
-        h->prev_frame_num = h->frame_num;
-        h->frame_num = h->slice_num;
-        h->prev_frame_num_offset = (h->frame_num - h->prev_frame_num);
+        h->prev_frame_num        = h->frame_num;
+        h->frame_num             = h->slice_num;
+        h->prev_frame_num_offset = h->frame_num - h->prev_frame_num;
 
-        if (h->prev_frame_num_offset < 0) {
+        if (h->prev_frame_num_offset < 0)
             h->prev_frame_num_offset += 256;
-        }
     }
 
-    for (m = 0; m < 2; m++){
+    for (m = 0; m < 2; m++) {
         int i;
-        for (i = 0; i < 4; i++){
+        for (i = 0; i < 4; i++) {
             int j;
             for (j = -1; j < 4; j++)
-                h->ref_cache[m][scan8[0] + 8*i + j]= 1;
+                h->ref_cache[m][scan8[0] + 8 * i + j] = 1;
             if (i < 3)
-                h->ref_cache[m][scan8[0] + 8*i + j]= PART_NOT_AVAILABLE;
+                h->ref_cache[m][scan8[0] + 8 * i + j] = PART_NOT_AVAILABLE;
         }
     }
 
     for (s->mb_y = 0; s->mb_y < s->mb_height; s->mb_y++) {
         for (s->mb_x = 0; s->mb_x < s->mb_width; s->mb_x++) {
-            h->mb_xy = s->mb_x + s->mb_y*s->mb_stride;
+            h->mb_xy = s->mb_x + s->mb_y * s->mb_stride;
 
-            if ( (get_bits_count(&s->gb) + 7) >= s->gb.size_in_bits &&
-                ((get_bits_count(&s->gb) & 7) == 0 || show_bits(&s->gb, (-get_bits_count(&s->gb) & 7)) == 0)) {
-
+            if ((get_bits_count(&s->gb) + 7) >= s->gb.size_in_bits &&
+                ((get_bits_count(&s->gb) & 7) == 0 ||
+                 show_bits(&s->gb, -get_bits_count(&s->gb) & 7) == 0)) {
                 skip_bits(&s->gb, svq3->next_slice_index - get_bits_count(&s->gb));
-                s->gb.size_in_bits = 8*buf_size;
+                s->gb.size_in_bits = 8 * buf_size;
 
                 if (svq3_decode_slice_header(avctx))
                     return -1;
@@ -1064,27 +1125,25 @@
 
             mb_type = svq3_get_ue_golomb(&s->gb);
 
-            if (s->pict_type == AV_PICTURE_TYPE_I) {
+            if (s->pict_type == AV_PICTURE_TYPE_I)
                 mb_type += 8;
-            } else if (s->pict_type == AV_PICTURE_TYPE_B && mb_type >= 4) {
+            else if (s->pict_type == AV_PICTURE_TYPE_B && mb_type >= 4)
                 mb_type += 4;
-            }
             if ((unsigned)mb_type > 33 || svq3_decode_mb(svq3, mb_type)) {
-                av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
+                av_log(h->s.avctx, AV_LOG_ERROR,
+                       "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
                 return -1;
             }
 
-            if (mb_type != 0) {
-                ff_h264_hl_decode_mb (h);
-            }
+            if (mb_type != 0)
+                ff_h264_hl_decode_mb(h);
 
-            if (s->pict_type != AV_PICTURE_TYPE_B && !s->low_delay) {
+            if (s->pict_type != AV_PICTURE_TYPE_B && !s->low_delay)
                 s->current_picture.f.mb_type[s->mb_x + s->mb_y * s->mb_stride] =
                     (s->pict_type == AV_PICTURE_TYPE_P && mb_type < 8) ? (mb_type - 1) : -1;
-            }
         }
 
-        ff_draw_horiz_band(s, 16*s->mb_y, 16);
+        ff_draw_horiz_band(s, 16 * s->mb_y, 16);
     }
 
     left = buf_size*8 - get_bits_count(&s->gb);
@@ -1101,16 +1160,14 @@
 
     ff_MPV_frame_end(s);
 
-    if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {
-        *(AVFrame *) data = s->current_picture.f;
-    } else {
-        *(AVFrame *) data = s->last_picture.f;
-    }
+    if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay)
+        *(AVFrame *)data = s->current_picture.f;
+    else
+        *(AVFrame *)data = s->last_picture.f;
 
     /* Do not output the last pic after seeking. */
-    if (s->last_picture_ptr || s->low_delay) {
+    if (s->last_picture_ptr || s->low_delay)
         *data_size = sizeof(AVFrame);
-    }
 
     return buf_size;
 }
@@ -1118,7 +1175,7 @@
 static int svq3_decode_end(AVCodecContext *avctx)
 {
     SVQ3Context *svq3 = avctx->priv_data;
-    H264Context *h = &svq3->h;
+    H264Context *h    = &svq3->h;
     MpegEncContext *s = &h->s;
 
     ff_h264_free_context(h);
@@ -1139,8 +1196,10 @@
     .init           = svq3_decode_init,
     .close          = svq3_decode_end,
     .decode         = svq3_decode_frame,
-    .capabilities   = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
+    .capabilities   = CODEC_CAP_DRAW_HORIZ_BAND |
+                      CODEC_CAP_DR1             |
                       CODEC_CAP_DELAY,
     .long_name      = NULL_IF_CONFIG_SMALL("Sorenson Vector Quantizer 3 / Sorenson Video 3 / SVQ3"),
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUVJ420P, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P,
+                                                     AV_PIX_FMT_NONE},
 };
diff --git a/libavcodec/symbols.h b/libavcodec/symbols.h
deleted file mode 100644
index ca4a89d..0000000
--- a/libavcodec/symbols.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2012 Ronald S. Bultje <rsbultje@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_SYMBOLS_H
-#define AVCODEC_SYMBOLS_H
-
-#include "libavutil/avconfig.h"
-
-#if AV_HAVE_SHARED_LIBS && defined(_MSC_VER) && !defined(COMPILING_avcodec)
-#define AVCODEC_SYMBOL __declspec(dllimport)
-#else
-#define AVCODEC_SYMBOL
-#endif
-
-#endif /* AVCODEC_SYMBOLS_H */
diff --git a/libavcodec/tak.c b/libavcodec/tak.c
new file mode 100644
index 0000000..7e1a047
--- /dev/null
+++ b/libavcodec/tak.c
@@ -0,0 +1,177 @@
+/*
+ * TAK common code
+ * Copyright (c) 2012 Paul B Mahol
+ *
+ * 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 "tak.h"
+#include "libavutil/crc.h"
+#include "libavutil/intreadwrite.h"
+#include "libavutil/bswap.h"
+
+static const int64_t tak_channel_layouts[] = {
+    0,
+    AV_CH_FRONT_LEFT,
+    AV_CH_FRONT_RIGHT,
+    AV_CH_FRONT_CENTER,
+    AV_CH_LOW_FREQUENCY,
+    AV_CH_BACK_LEFT,
+    AV_CH_BACK_RIGHT,
+    AV_CH_FRONT_LEFT_OF_CENTER,
+    AV_CH_FRONT_RIGHT_OF_CENTER,
+    AV_CH_BACK_CENTER,
+    AV_CH_SIDE_LEFT,
+    AV_CH_SIDE_RIGHT,
+    AV_CH_TOP_CENTER,
+    AV_CH_TOP_FRONT_LEFT,
+    AV_CH_TOP_FRONT_CENTER,
+    AV_CH_TOP_FRONT_RIGHT,
+    AV_CH_TOP_BACK_LEFT,
+    AV_CH_TOP_BACK_CENTER,
+    AV_CH_TOP_BACK_RIGHT,
+};
+
+static const uint16_t frame_duration_type_quants[] = {
+    3, 4, 6, 8, 4096, 8192, 16384, 512, 1024, 2048,
+};
+
+static int tak_get_nb_samples(int sample_rate, enum TAKFrameSizeType type)
+{
+    int nb_samples, max_nb_samples;
+
+    if (type <= TAK_FST_250ms) {
+        nb_samples     = sample_rate * frame_duration_type_quants[type] >>
+                                       TAK_FRAME_DURATION_QUANT_SHIFT;
+        max_nb_samples = 16384;
+    } else if (type < FF_ARRAY_ELEMS(frame_duration_type_quants)) {
+        nb_samples     = frame_duration_type_quants[type];
+        max_nb_samples = sample_rate * frame_duration_type_quants[TAK_FST_250ms] >>
+                                       TAK_FRAME_DURATION_QUANT_SHIFT;
+    } else {
+        return AVERROR_INVALIDDATA;
+    }
+
+    if (nb_samples <= 0 || nb_samples > max_nb_samples)
+        return AVERROR_INVALIDDATA;
+
+    return nb_samples;
+}
+
+static int crc_init = 0;
+#if CONFIG_SMALL
+#define CRC_TABLE_SIZE 257
+#else
+#define CRC_TABLE_SIZE 1024
+#endif
+static AVCRC crc_24[CRC_TABLE_SIZE];
+
+av_cold void ff_tak_init_crc(void)
+{
+    if (!crc_init) {
+        av_crc_init(crc_24, 0, 24, 0x864CFBU, sizeof(crc_24));
+        crc_init = 1;
+    }
+}
+
+int ff_tak_check_crc(const uint8_t *buf, unsigned int buf_size)
+{
+    uint32_t crc, CRC;
+
+    if (buf_size < 4)
+        return AVERROR_INVALIDDATA;
+    buf_size -= 3;
+
+    CRC = av_bswap32(AV_RL24(buf + buf_size)) >> 8;
+    crc = av_crc(crc_24, 0xCE04B7U, buf, buf_size);
+    if (CRC != crc)
+        return AVERROR_INVALIDDATA;
+
+    return 0;
+}
+
+void avpriv_tak_parse_streaminfo(GetBitContext *gb, TAKStreamInfo *s)
+{
+    uint64_t channel_mask = 0;
+    int frame_type, i;
+
+    s->codec = get_bits(gb, TAK_ENCODER_CODEC_BITS);
+    skip_bits(gb, TAK_ENCODER_PROFILE_BITS);
+
+    frame_type = get_bits(gb, TAK_SIZE_FRAME_DURATION_BITS);
+    s->samples = get_bits_longlong(gb, TAK_SIZE_SAMPLES_NUM_BITS);
+
+    s->data_type   = get_bits(gb, TAK_FORMAT_DATA_TYPE_BITS);
+    s->sample_rate = get_bits(gb, TAK_FORMAT_SAMPLE_RATE_BITS) + TAK_SAMPLE_RATE_MIN;
+    s->bps         = get_bits(gb, TAK_FORMAT_BPS_BITS) + TAK_BPS_MIN;
+    s->channels    = get_bits(gb, TAK_FORMAT_CHANNEL_BITS) + TAK_CHANNELS_MIN;
+
+    if (get_bits1(gb)) {
+        skip_bits(gb, TAK_FORMAT_VALID_BITS);
+        if (get_bits1(gb)) {
+            for (i = 0; i < s->channels; i++) {
+                int value = get_bits(gb, TAK_FORMAT_CH_LAYOUT_BITS);
+
+                if (value < FF_ARRAY_ELEMS(tak_channel_layouts))
+                    channel_mask |= tak_channel_layouts[value];
+            }
+        }
+    }
+
+    s->ch_layout     = channel_mask;
+    s->frame_samples = tak_get_nb_samples(s->sample_rate, frame_type);
+}
+
+#define FRAME_IS_LAST       1
+#define FRAME_HAVE_INFO     2
+#define FRAME_HAVE_METADATA 4
+
+int ff_tak_decode_frame_header(AVCodecContext *avctx, GetBitContext *gb,
+                               TAKStreamInfo *ti, int log_level_offset)
+{
+    int flags;
+
+    if (get_bits(gb, TAK_FRAME_HEADER_SYNC_ID_BITS) != TAK_FRAME_HEADER_SYNC_ID) {
+        av_log(avctx, AV_LOG_ERROR + log_level_offset, "missing sync id\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    flags = get_bits(gb, TAK_FRAME_HEADER_FLAGS_BITS);
+    ti->frame_num = get_bits(gb, TAK_FRAME_HEADER_NO_BITS);
+
+    if (flags & FRAME_IS_LAST) {
+        ti->last_frame_samples = get_bits(gb, TAK_FRAME_HEADER_SAMPLE_COUNT_BITS) + 1;
+        skip_bits(gb, 2);
+    } else {
+        ti->last_frame_samples = 0;
+    }
+
+    if (flags & FRAME_HAVE_INFO) {
+        avpriv_tak_parse_streaminfo(gb, ti);
+
+        if (get_bits(gb, 6))
+            skip_bits(gb, 25);
+        align_get_bits(gb);
+    }
+
+    if (flags & FRAME_HAVE_METADATA)
+        return AVERROR_INVALIDDATA;
+
+    skip_bits(gb, 24);
+
+    return 0;
+}
diff --git a/libavcodec/tak.h b/libavcodec/tak.h
new file mode 100644
index 0000000..cfa074d
--- /dev/null
+++ b/libavcodec/tak.h
@@ -0,0 +1,151 @@
+/*
+ * TAK decoder/demuxer common code
+ * Copyright (c) 2012 Paul B Mahol
+ *
+ * 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
+ * TAK (Tom's lossless Audio Kompressor) decoder/demuxer common functions
+ */
+
+#ifndef AVCODEC_TAK_H
+#define AVCODEC_TAK_H
+
+#define BITSTREAM_READER_LE
+#include "get_bits.h"
+#include "avcodec.h"
+
+#define TAK_FORMAT_DATA_TYPE_BITS    3
+#define TAK_FORMAT_SAMPLE_RATE_BITS  18
+#define TAK_FORMAT_BPS_BITS          5
+#define TAK_FORMAT_CHANNEL_BITS      4
+#define TAK_FORMAT_VALID_BITS        5
+#define TAK_FORMAT_CH_LAYOUT_BITS    6
+#define TAK_SIZE_FRAME_DURATION_BITS 4
+#define TAK_SIZE_SAMPLES_NUM_BITS    35
+#define TAK_LAST_FRAME_POS_BITS      40
+#define TAK_LAST_FRAME_SIZE_BITS     24
+#define TAK_ENCODER_CODEC_BITS       6
+#define TAK_ENCODER_PROFILE_BITS     4
+#define TAK_ENCODER_VERSION_BITS     24
+#define TAK_SAMPLE_RATE_MIN          6000
+#define TAK_CHANNELS_MIN             1
+#define TAK_BPS_MIN                  8
+#define TAK_FRAME_HEADER_FLAGS_BITS         3
+#define TAK_FRAME_HEADER_SYNC_ID            0xA0FF
+#define TAK_FRAME_HEADER_SYNC_ID_BITS       16
+#define TAK_FRAME_HEADER_SAMPLE_COUNT_BITS  14
+#define TAK_FRAME_HEADER_NO_BITS            21
+#define TAK_FRAME_DURATION_QUANT_SHIFT      5
+#define TAK_CRC24_BITS                      24
+
+#define TAK_MAX_CHANNELS                  ( 1 << TAK_FORMAT_CHANNEL_BITS )
+
+#define TAK_MIN_FRAME_HEADER_BITS         ( TAK_FRAME_HEADER_SYNC_ID_BITS + \
+                                            TAK_FRAME_HEADER_FLAGS_BITS   + \
+                                            TAK_FRAME_HEADER_NO_BITS      + \
+                                            TAK_CRC24_BITS )
+
+#define TAK_MIN_FRAME_HEADER_LAST_BITS    ( TAK_MIN_FRAME_HEADER_BITS + 2 + \
+                                            TAK_FRAME_HEADER_SAMPLE_COUNT_BITS )
+
+#define TAK_ENCODER_BITS         ( TAK_ENCODER_CODEC_BITS        + \
+                                   TAK_ENCODER_PROFILE_BITS )
+
+#define TAK_SIZE_BITS            ( TAK_SIZE_SAMPLES_NUM_BITS     + \
+                                   TAK_SIZE_FRAME_DURATION_BITS )
+
+#define TAK_FORMAT_BITS          ( TAK_FORMAT_DATA_TYPE_BITS     + \
+                                   TAK_FORMAT_SAMPLE_RATE_BITS   + \
+                                   TAK_FORMAT_BPS_BITS           + \
+                                   TAK_FORMAT_CHANNEL_BITS + 1   + \
+                                   TAK_FORMAT_VALID_BITS   + 1   + \
+                                   TAK_FORMAT_CH_LAYOUT_BITS     * \
+                                   TAK_MAX_CHANNELS )
+
+#define TAK_STREAMINFO_BITS      ( TAK_ENCODER_BITS              + \
+                                   TAK_SIZE_BITS                 + \
+                                   TAK_FORMAT_BITS )
+
+#define TAK_MAX_FRAME_HEADER_BITS  ( TAK_MIN_FRAME_HEADER_LAST_BITS + \
+                                     TAK_STREAMINFO_BITS + 31 )
+
+#define TAK_STREAMINFO_BYTES        (( TAK_STREAMINFO_BITS + 7 ) / 8)
+#define TAK_MAX_FRAME_HEADER_BYTES  (( TAK_MAX_FRAME_HEADER_BITS + 7 ) / 8)
+#define TAK_MIN_FRAME_HEADER_BYTES  (( TAK_MIN_FRAME_HEADER_BITS + 7 ) / 8)
+
+enum TAKMetaDataType {
+    TAK_METADATA_END = 0,
+    TAK_METADATA_STREAMINFO,
+    TAK_METADATA_SEEKTABLE,
+    TAK_METADATA_SIMPLE_WAVE_DATA,
+    TAK_METADATA_ENCODER,
+    TAK_METADATA_PADDING,
+    TAK_METADATA_MD5,
+    TAK_METADATA_LAST_FRAME,
+};
+
+enum TAKFrameSizeType {
+    TAK_FST_94ms = 0,
+    TAK_FST_125ms,
+    TAK_FST_188ms,
+    TAK_FST_250ms,
+    TAK_FST_4096,
+    TAK_FST_8192,
+    TAK_FST_16384,
+    TAK_FST_512,
+    TAK_FST_1024,
+    TAK_FST_2048,
+};
+
+typedef struct TAKStreamInfo {
+    int      codec;
+    int      data_type;
+    int      sample_rate;
+    int      channels;
+    int      bps;
+    int      frame_num;
+    int      frame_samples;
+    int      last_frame_samples;
+    uint64_t ch_layout;
+    int64_t  samples;
+} TAKStreamInfo;
+
+void ff_tak_init_crc(void);
+
+int ff_tak_check_crc(const uint8_t *buf, unsigned int buf_size);
+
+/**
+ * Parse the Streaminfo metadata block
+ * @param[in]  gb      pointer to GetBitContext
+ * @param[out] s       where parsed information is stored
+ */
+void avpriv_tak_parse_streaminfo(GetBitContext *gb, TAKStreamInfo *s);
+
+/**
+ * Validate and decode a frame header.
+ * @param      avctx AVCodecContext to use as av_log() context
+ * @param[in]  gb    GetBitContext from which to read frame header
+ * @param[out] s     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_tak_decode_frame_header(AVCodecContext *avctx, GetBitContext *gb,
+                               TAKStreamInfo *s, int log_level_offset);
+#endif /* AVCODEC_TAK_H */
diff --git a/libavcodec/tak_parser.c b/libavcodec/tak_parser.c
new file mode 100644
index 0000000..55766a4
--- /dev/null
+++ b/libavcodec/tak_parser.c
@@ -0,0 +1,127 @@
+/*
+ * TAK parser
+ * Copyright (c) 2012 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
+ */
+
+/**
+ * @file
+ * TAK parser
+ **/
+
+#include "parser.h"
+#include "tak.h"
+
+typedef struct TAKParseContext {
+    ParseContext  pc;
+    TAKStreamInfo ti;
+    int index;
+} TAKParseContext;
+
+static av_cold int tak_init(AVCodecParserContext *s)
+{
+    ff_tak_init_crc();
+    return 0;
+}
+
+static int tak_parse(AVCodecParserContext *s, AVCodecContext *avctx,
+                     const uint8_t **poutbuf, int *poutbuf_size,
+                     const uint8_t *buf, int buf_size)
+{
+    TAKParseContext *t = s->priv_data;
+    ParseContext *pc = &t->pc;
+    int next = END_NOT_FOUND;
+    GetBitContext gb;
+    int consumed = 0;
+    int needed = buf_size ? TAK_MAX_FRAME_HEADER_BYTES : 8;
+
+    if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
+        TAKStreamInfo ti;
+        init_get_bits(&gb, buf, buf_size);
+        if (!ff_tak_decode_frame_header(avctx, &gb, &ti, 127))
+            s->duration = t->ti.last_frame_samples ? t->ti.last_frame_samples :
+                                                     t->ti.frame_samples;
+        *poutbuf      = buf;
+        *poutbuf_size = buf_size;
+        return buf_size;
+    }
+
+    while (buf_size || t->index + needed <= pc->index) {
+        if (buf_size && t->index + TAK_MAX_FRAME_HEADER_BYTES > pc->index) {
+            int tmp_buf_size = FFMIN(2 * TAK_MAX_FRAME_HEADER_BYTES, buf_size);
+            const uint8_t *tmp_buf = buf;
+
+            if (ff_combine_frame(pc, END_NOT_FOUND, &tmp_buf, &tmp_buf_size) != -1)
+                return AVERROR(ENOMEM);
+            consumed += tmp_buf_size;
+            buf      += tmp_buf_size;
+            buf_size -= tmp_buf_size;
+        }
+
+        for (; t->index + needed <= pc->index; t->index++) {
+            if (pc->buffer[ t->index     ] == 0xFF &&
+                pc->buffer[ t->index + 1 ] == 0xA0) {
+                TAKStreamInfo ti;
+
+                init_get_bits(&gb, pc->buffer + t->index,
+                              8 * (pc->index - t->index));
+                if (!ff_tak_decode_frame_header(avctx, &gb,
+                        pc->frame_start_found ? &ti : &t->ti, 127) &&
+                    !ff_tak_check_crc(pc->buffer + t->index,
+                                      get_bits_count(&gb) / 8)) {
+                    if (!pc->frame_start_found) {
+                        pc->frame_start_found = 1;
+                        s->duration = t->ti.last_frame_samples ?
+                                      t->ti.last_frame_samples :
+                                      t->ti.frame_samples;
+                    } else {
+                        pc->frame_start_found = 0;
+                        next = t->index - pc->index;
+                        t->index = 0;
+                        goto found;
+                    }
+                }
+            }
+        }
+    }
+found:
+
+    if (consumed && !buf_size && next == END_NOT_FOUND ||
+        ff_combine_frame(pc, next, &buf, &buf_size) < 0) {
+        *poutbuf      = NULL;
+        *poutbuf_size = 0;
+        return buf_size + consumed;
+    }
+
+    if (next != END_NOT_FOUND) {
+        next += consumed;
+        pc->overread = FFMAX(0, -next);
+    }
+
+    *poutbuf      = buf;
+    *poutbuf_size = buf_size;
+    return next;
+}
+
+AVCodecParser ff_tak_parser = {
+    .codec_ids      = { AV_CODEC_ID_TAK },
+    .priv_data_size = sizeof(TAKParseContext),
+    .parser_init    = tak_init,
+    .parser_parse   = tak_parse,
+    .parser_close   = ff_parse_close,
+};
diff --git a/libavcodec/takdec.c b/libavcodec/takdec.c
new file mode 100644
index 0000000..1120296
--- /dev/null
+++ b/libavcodec/takdec.c
@@ -0,0 +1,984 @@
+/*
+ * TAK decoder
+ * Copyright (c) 2012 Paul B Mahol
+ *
+ * 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
+ * TAK (Tom's lossless Audio Kompressor) decoder
+ * @author Paul B Mahol
+ */
+
+#include "tak.h"
+#include "avcodec.h"
+#include "unary.h"
+#include "dsputil.h"
+
+#define MAX_SUBFRAMES   8                       ///< max number of subframes per channel
+#define MAX_PREDICTORS  256
+
+typedef struct MCDParam {
+    int8_t     present;                         ///< is decorrelation parameters available for this channel
+    int8_t     index;                           ///< index into array of decorrelation types
+    int8_t     chan1;
+    int8_t     chan2;
+} MCDParam;
+
+typedef struct TAKDecContext {
+    AVCodecContext *avctx;                      ///< parent AVCodecContext
+    AVFrame        frame;                       ///< AVFrame for decoded output
+    DSPContext     dsp;
+    TAKStreamInfo  ti;
+    GetBitContext  gb;                          ///< bitstream reader initialized to start at the current frame
+
+    int            nb_samples;                  ///< number of samples in the current frame
+    int32_t        *decode_buffer;
+    int            decode_buffer_size;
+    int32_t        *decoded[TAK_MAX_CHANNELS];  ///< decoded samples for each channel
+
+    int8_t         lpc_mode[TAK_MAX_CHANNELS];
+    int8_t         sample_shift[TAK_MAX_CHANNELS];  ///< shift applied to every sample in the channel
+    int32_t        xred;
+    int            size;
+    int            ared;
+    int            filter_order;
+    int16_t        predictors[MAX_PREDICTORS];
+    int            nb_subframes;                ///< number of subframes in the current frame
+    int16_t        subframe_len[MAX_SUBFRAMES]; ///< subframe length in samples
+    int            subframe_scale;
+
+    int8_t         dmode;                       ///< channel decorrelation type in the current frame
+    int8_t         dshift;
+    int16_t        dfactor;
+    int8_t         dval1;
+    int8_t         dval2;
+
+    MCDParam       mcdparams[TAK_MAX_CHANNELS]; ///< multichannel decorrelation parameters
+
+    int            wlength;
+    int            uval;
+    int            rval;
+    int8_t         coding_mode[128];
+    DECLARE_ALIGNED(16, int16_t, filter)[MAX_PREDICTORS];
+    DECLARE_ALIGNED(16, int16_t, residues)[544];
+} TAKDecContext;
+
+static const int8_t mc_dmodes[] = {
+    1, 3, 4, 6,
+};
+
+static const uint16_t predictor_sizes[] = {
+    4, 8, 12, 16, 24, 32, 48, 64, 80, 96, 128, 160, 192, 224, 256, 0,
+};
+
+static const struct CParam {
+    int        init;
+    int        escape;
+    int        scale;
+    int        aescape;
+    int        bias;
+} xcodes[50] = {
+    { 0x01, 0x0000001, 0x0000001, 0x0000003, 0x0000008 },
+    { 0x02, 0x0000003, 0x0000001, 0x0000007, 0x0000006 },
+    { 0x03, 0x0000005, 0x0000002, 0x000000E, 0x000000D },
+    { 0x03, 0x0000003, 0x0000003, 0x000000D, 0x0000018 },
+    { 0x04, 0x000000B, 0x0000004, 0x000001C, 0x0000019 },
+    { 0x04, 0x0000006, 0x0000006, 0x000001A, 0x0000030 },
+    { 0x05, 0x0000016, 0x0000008, 0x0000038, 0x0000032 },
+    { 0x05, 0x000000C, 0x000000C, 0x0000034, 0x0000060 },
+    { 0x06, 0x000002C, 0x0000010, 0x0000070, 0x0000064 },
+    { 0x06, 0x0000018, 0x0000018, 0x0000068, 0x00000C0 },
+    { 0x07, 0x0000058, 0x0000020, 0x00000E0, 0x00000C8 },
+    { 0x07, 0x0000030, 0x0000030, 0x00000D0, 0x0000180 },
+    { 0x08, 0x00000B0, 0x0000040, 0x00001C0, 0x0000190 },
+    { 0x08, 0x0000060, 0x0000060, 0x00001A0, 0x0000300 },
+    { 0x09, 0x0000160, 0x0000080, 0x0000380, 0x0000320 },
+    { 0x09, 0x00000C0, 0x00000C0, 0x0000340, 0x0000600 },
+    { 0x0A, 0x00002C0, 0x0000100, 0x0000700, 0x0000640 },
+    { 0x0A, 0x0000180, 0x0000180, 0x0000680, 0x0000C00 },
+    { 0x0B, 0x0000580, 0x0000200, 0x0000E00, 0x0000C80 },
+    { 0x0B, 0x0000300, 0x0000300, 0x0000D00, 0x0001800 },
+    { 0x0C, 0x0000B00, 0x0000400, 0x0001C00, 0x0001900 },
+    { 0x0C, 0x0000600, 0x0000600, 0x0001A00, 0x0003000 },
+    { 0x0D, 0x0001600, 0x0000800, 0x0003800, 0x0003200 },
+    { 0x0D, 0x0000C00, 0x0000C00, 0x0003400, 0x0006000 },
+    { 0x0E, 0x0002C00, 0x0001000, 0x0007000, 0x0006400 },
+    { 0x0E, 0x0001800, 0x0001800, 0x0006800, 0x000C000 },
+    { 0x0F, 0x0005800, 0x0002000, 0x000E000, 0x000C800 },
+    { 0x0F, 0x0003000, 0x0003000, 0x000D000, 0x0018000 },
+    { 0x10, 0x000B000, 0x0004000, 0x001C000, 0x0019000 },
+    { 0x10, 0x0006000, 0x0006000, 0x001A000, 0x0030000 },
+    { 0x11, 0x0016000, 0x0008000, 0x0038000, 0x0032000 },
+    { 0x11, 0x000C000, 0x000C000, 0x0034000, 0x0060000 },
+    { 0x12, 0x002C000, 0x0010000, 0x0070000, 0x0064000 },
+    { 0x12, 0x0018000, 0x0018000, 0x0068000, 0x00C0000 },
+    { 0x13, 0x0058000, 0x0020000, 0x00E0000, 0x00C8000 },
+    { 0x13, 0x0030000, 0x0030000, 0x00D0000, 0x0180000 },
+    { 0x14, 0x00B0000, 0x0040000, 0x01C0000, 0x0190000 },
+    { 0x14, 0x0060000, 0x0060000, 0x01A0000, 0x0300000 },
+    { 0x15, 0x0160000, 0x0080000, 0x0380000, 0x0320000 },
+    { 0x15, 0x00C0000, 0x00C0000, 0x0340000, 0x0600000 },
+    { 0x16, 0x02C0000, 0x0100000, 0x0700000, 0x0640000 },
+    { 0x16, 0x0180000, 0x0180000, 0x0680000, 0x0C00000 },
+    { 0x17, 0x0580000, 0x0200000, 0x0E00000, 0x0C80000 },
+    { 0x17, 0x0300000, 0x0300000, 0x0D00000, 0x1800000 },
+    { 0x18, 0x0B00000, 0x0400000, 0x1C00000, 0x1900000 },
+    { 0x18, 0x0600000, 0x0600000, 0x1A00000, 0x3000000 },
+    { 0x19, 0x1600000, 0x0800000, 0x3800000, 0x3200000 },
+    { 0x19, 0x0C00000, 0x0C00000, 0x3400000, 0x6000000 },
+    { 0x1A, 0x2C00000, 0x1000000, 0x7000000, 0x6400000 },
+    { 0x1A, 0x1800000, 0x1800000, 0x6800000, 0xC000000 },
+};
+
+static int tak_set_bps(AVCodecContext *avctx, int bps)
+{
+    switch (bps) {
+    case 8:
+        avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
+        break;
+    case 16:
+        avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
+        break;
+    case 24:
+        avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
+        break;
+    default:
+        av_log(avctx, AV_LOG_ERROR, "invalid/unsupported bits per sample\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    return 0;
+}
+
+static int get_shift(int sample_rate)
+{
+    int shift;
+
+    if (sample_rate < 11025)
+        shift = 3;
+    else if (sample_rate < 22050)
+        shift = 2;
+    else if (sample_rate < 44100)
+        shift = 1;
+    else
+        shift = 0;
+
+    return shift;
+}
+
+static int get_scale(int sample_rate, int shift)
+{
+    return FFALIGN(sample_rate + 511 >> 9, 4) << shift;
+}
+
+static av_cold int tak_decode_init(AVCodecContext *avctx)
+{
+    TAKDecContext *s = avctx->priv_data;
+    int ret;
+
+    ff_tak_init_crc();
+    ff_dsputil_init(&s->dsp, avctx);
+
+    s->avctx = avctx;
+    avcodec_get_frame_defaults(&s->frame);
+    avctx->coded_frame = &s->frame;
+
+    s->uval = get_scale(avctx->sample_rate, get_shift(avctx->sample_rate));
+    s->subframe_scale = get_scale(avctx->sample_rate, 1);
+
+    if ((ret = tak_set_bps(avctx, avctx->bits_per_coded_sample)) < 0)
+        return ret;
+
+    return 0;
+}
+
+static int get_code(GetBitContext *gb, int nbits)
+{
+    if (nbits == 1) {
+        skip_bits1(gb);
+        return 0;
+    } else {
+        return get_sbits(gb, nbits);
+    }
+}
+
+static void decode_lpc(int32_t *coeffs, int mode, int length)
+{
+    int i, a1, a2, a3, a4, a5;
+
+    if (length < 2)
+        return;
+
+    if (mode == 1) {
+        a1 = *coeffs++;
+        for (i = 0; i < (length - 1 >> 1); i++) {
+            *coeffs   += a1;
+            coeffs[1] += *coeffs;
+            a1      = coeffs[1];
+            coeffs    += 2;
+        }
+        if ((length - 1) & 1)
+            *coeffs += a1;
+    } else if (mode == 2) {
+        a1     = coeffs[1];
+        a2     = a1 + *coeffs;
+        coeffs[1] = a2;
+        if (length > 2) {
+            coeffs += 2;
+            for (i = 0; i < (length - 2 >> 1); i++) {
+                a3     = *coeffs + a1;
+                a4     = a3 + a2;
+                *coeffs   = a4;
+                a1     = coeffs[1] + a3;
+                a2     = a1 + a4;
+                coeffs[1] = a2;
+                coeffs   += 2;
+            }
+            if (length & 1)
+                *coeffs  += a1 + a2;
+        }
+    } else if (mode == 3) {
+        a1     = coeffs[1];
+        a2     = a1 + *coeffs;
+        coeffs[1] = a2;
+        if (length > 2) {
+            a3   = coeffs[2];
+            a4   = a3 + a1;
+            a5   = a4 + a2;
+            coeffs += 3;
+            for (i = 0; i < length - 3; i++) {
+                a3  += *coeffs;
+                a4  += a3;
+                a5  += a4;
+                *coeffs = a5;
+                coeffs++;
+            }
+        }
+    }
+}
+
+static int decode_segment(TAKDecContext *s, int8_t value, int32_t *dst, int len)
+{
+    GetBitContext *gb = &s->gb;
+
+    if (!value) {
+        memset(dst, 0, len * 4);
+    } else {
+        int x, y, z, i = 0;
+
+        value--;
+        do {
+            while (1) {
+                x = get_bits_long(gb, xcodes[value].init);
+                if (x >= xcodes[value].escape)
+                    break;
+                dst[i++] = (x >> 1) ^ -(x & 1);
+                if (i >= len)
+                    return 0;
+            }
+
+            y = get_bits1(gb);
+            x = (y << xcodes[value].init) | x;
+            if (x >= xcodes[value].aescape) {
+                int c = get_unary(gb, 1, 9);
+
+                if (c == 9) {
+                    int d;
+
+                    z = x + xcodes[value].bias;
+                    d = get_bits(gb, 3);
+                    if (d == 7) {
+                        d = get_bits(gb, 5) + 7;
+                        if (d > 29)
+                            return AVERROR_INVALIDDATA;
+                    }
+                    if (d)
+                        z += xcodes[value].scale * (get_bits_long(gb, d) + 1);
+                } else {
+                    z = xcodes[value].scale * c + x - xcodes[value].escape;
+                }
+            } else {
+                z = x - (xcodes[value].escape & -y);
+            }
+            dst[i++] = (z >> 1) ^ -(z & 1);
+        } while (i < len);
+    }
+
+    return 0;
+}
+
+static int xget(TAKDecContext *s, int d, int q)
+{
+    int x;
+
+    x = d / q;
+
+    s->rval = d - (x * q);
+
+    if (s->rval < q / 2) {
+        s->rval += q;
+    } else {
+        x++;
+    }
+
+    if (x <= 1 || x > 128)
+        return -1;
+
+    return x;
+}
+
+static int get_len(TAKDecContext *s, int b)
+{
+    if (b >= s->wlength - 1)
+        return s->rval;
+    else
+        return s->uval;
+}
+
+static int decode_coeffs(TAKDecContext *s, int32_t *dst, int length)
+{
+    GetBitContext *gb = &s->gb;
+    int i, v, ret;
+
+    if (length > s->nb_samples)
+        return AVERROR_INVALIDDATA;
+
+    if (get_bits1(gb)) {
+        if ((s->wlength = xget(s, length, s->uval)) < 0)
+            return AVERROR_INVALIDDATA;
+
+        s->coding_mode[0] = v = get_bits(gb, 6);
+        if (s->coding_mode[0] > FF_ARRAY_ELEMS(xcodes))
+            return AVERROR_INVALIDDATA;
+
+        for (i = 1; i < s->wlength; i++) {
+            int c = get_unary(gb, 1, 6);
+
+            if (c > 5) {
+                v = get_bits(gb, 6);
+            } else if (c > 2) {
+                int t = get_bits1(gb);
+
+                v += (-t ^ (c - 1)) + t;
+            } else {
+                v += (-(c & 1) ^ (((c & 1) + c) >> 1)) + (c & 1);
+            }
+
+            if (v > FF_ARRAY_ELEMS(xcodes))
+                return AVERROR_INVALIDDATA;
+            s->coding_mode[i] = v;
+        }
+
+        i = 0;
+        while (i < s->wlength) {
+            int len = 0;
+
+            v = s->coding_mode[i];
+            do {
+                len += get_len(s, i);
+                i++;
+
+                if (i == s->wlength)
+                    break;
+            } while (v == s->coding_mode[i]);
+
+            if ((ret = decode_segment(s, v, dst, len)) < 0)
+                return ret;
+            dst += len;
+        }
+    } else {
+        v = get_bits(gb, 6);
+        if (v > FF_ARRAY_ELEMS(xcodes))
+            return AVERROR_INVALIDDATA;
+        if ((ret = decode_segment(s, v, dst, length)) < 0)
+            return ret;
+    }
+
+    return 0;
+}
+
+static int get_b(GetBitContext *gb)
+{
+    if (get_bits1(gb))
+        return get_bits(gb, 4) + 1;
+    else
+        return 0;
+}
+
+static int decode_subframe(TAKDecContext *s, int32_t *ptr, int subframe_size,
+                           int prev_subframe_size)
+{
+    GetBitContext  *gb = &s->gb;
+    int tmp, x, y, i, j, ret = 0;
+    int tfilter[MAX_PREDICTORS];
+
+    if (get_bits1(gb)) {
+        s->filter_order = predictor_sizes[get_bits(gb, 4)];
+
+        if (prev_subframe_size > 0 && get_bits1(gb)) {
+            if (s->filter_order > prev_subframe_size)
+                return AVERROR_INVALIDDATA;
+
+            ptr           -= s->filter_order;
+            subframe_size += s->filter_order;
+
+            if (s->filter_order > subframe_size)
+                return AVERROR_INVALIDDATA;
+        } else {
+            int lpc;
+
+            if (s->filter_order > subframe_size)
+                return AVERROR_INVALIDDATA;
+
+            lpc = get_bits(gb, 2);
+            if (lpc > 2)
+                return AVERROR_INVALIDDATA;
+
+            if ((ret = decode_coeffs(s, ptr, s->filter_order)) < 0)
+                return ret;
+
+            decode_lpc(ptr, lpc, s->filter_order);
+        }
+
+        s->xred = get_b(gb);
+        s->size = get_bits1(gb) + 5;
+
+        if (get_bits1(gb)) {
+            s->ared = get_bits(gb, 3) + 1;
+            if (s->ared > 7)
+                return AVERROR_INVALIDDATA;
+        } else {
+            s->ared = 0;
+        }
+        s->predictors[0] = get_code(gb, 10);
+        s->predictors[1] = get_code(gb, 10);
+        s->predictors[2] = get_code(gb, s->size + 1) << (9 - s->size);
+        s->predictors[3] = get_code(gb, s->size + 1) << (9 - s->size);
+        if (s->filter_order > 4) {
+            tmp = s->size + 1 - get_bits1(gb);
+
+            for (i = 4; i < s->filter_order; i++) {
+                if (!(i & 3))
+                    x = tmp - get_bits(gb, 2);
+                s->predictors[i] = get_code(gb, x) << (9 - s->size);
+            }
+        }
+
+        tfilter[0] = s->predictors[0] << 6;
+        for (i = 1; i < s->filter_order; i++) {
+            int32_t *p1 = &tfilter[0];
+            int32_t *p2 = &tfilter[i - 1];
+
+            for (j = 0; j < (i + 1) / 2; j++) {
+                x     = *p1 + (s->predictors[i] * *p2 + 256 >> 9);
+                *p2  += s->predictors[i] * *p1 + 256 >> 9;
+                *p1++ = x;
+                p2--;
+            }
+
+            tfilter[i] = s->predictors[i] << 6;
+        }
+
+        x = -1 << (32 - (s->ared + 5));
+        y =  1 << ((s->ared + 5) - 1);
+        for (i = 0, j = s->filter_order - 1; i < s->filter_order / 2; i++, j--) {
+            tmp = y + tfilter[j];
+            s->filter[j] = -(x & -(y + tfilter[i] >> 31) |
+                            (y + tfilter[i]) >> (s->ared + 5));
+            s->filter[i] = -(x & -(tmp >> 31) | (tmp >> s->ared + 5));
+        }
+
+        if ((ret = decode_coeffs(s, &ptr[s->filter_order],
+                                 subframe_size - s->filter_order)) < 0)
+            return ret;
+
+        for (i = 0; i < s->filter_order; i++)
+            s->residues[i] = *ptr++ >> s->xred;
+
+        y    = FF_ARRAY_ELEMS(s->residues) - s->filter_order;
+        x    = subframe_size - s->filter_order;
+        while (x > 0) {
+            tmp = FFMIN(y, x);
+
+            for (i = 0; i < tmp; i++) {
+                int v, w, m;
+
+                v = 1 << (10 - s->ared - 1);
+                if (!(s->filter_order & 15)) {
+                    v += s->dsp.scalarproduct_int16(&s->residues[i], s->filter,
+                                                    s->filter_order);
+                } else if (s->filter_order & 4) {
+                    for (j = 0; j < s->filter_order; j += 4) {
+                        v += s->residues[i + j + 3] * s->filter[j + 3] +
+                             s->residues[i + j + 2] * s->filter[j + 2] +
+                             s->residues[i + j + 1] * s->filter[j + 1] +
+                             s->residues[i + j    ] * s->filter[j    ];
+                    }
+                } else {
+                    for (j = 0; j < s->filter_order; j += 8) {
+                        v += s->residues[i + j + 7] * s->filter[j + 7] +
+                             s->residues[i + j + 6] * s->filter[j + 6] +
+                             s->residues[i + j + 5] * s->filter[j + 5] +
+                             s->residues[i + j + 4] * s->filter[j + 4] +
+                             s->residues[i + j + 3] * s->filter[j + 3] +
+                             s->residues[i + j + 2] * s->filter[j + 2] +
+                             s->residues[i + j + 1] * s->filter[j + 1] +
+                             s->residues[i + j    ] * s->filter[j    ];
+                    }
+                }
+                m = (-1 << (32 - (10 - s->ared))) & -(v >> 31) | (v >> 10 - s->ared);
+                m = av_clip(m, -8192, 8191);
+                w = (m << s->xred) - *ptr;
+                *ptr++ = w;
+                s->residues[s->filter_order + i] = w >> s->xred;
+            }
+
+            x -= tmp;
+            if (x > 0)
+                memcpy(s->residues, &s->residues[y], 2 * s->filter_order);
+        }
+
+        emms_c();
+    } else {
+        ret = decode_coeffs(s, ptr, subframe_size);
+    }
+
+    return ret;
+}
+
+static int decode_channel(TAKDecContext *s, int chan)
+{
+    AVCodecContext *avctx = s->avctx;
+    GetBitContext  *gb = &s->gb;
+    int32_t *dst = s->decoded[chan];
+    int i = 0, ret, prev = 0;
+    int left = s->nb_samples - 1;
+
+    s->sample_shift[chan] = get_b(gb);
+    if (s->sample_shift[chan] >= avctx->bits_per_raw_sample)
+        return AVERROR_INVALIDDATA;
+
+    *dst++ = get_code(gb, avctx->bits_per_raw_sample - s->sample_shift[chan]);
+    s->lpc_mode[chan] = get_bits(gb, 2);
+    s->nb_subframes   = get_bits(gb, 3) + 1;
+
+    if (s->nb_subframes > 1) {
+        if (get_bits_left(gb) < (s->nb_subframes - 1) * 6)
+            return AVERROR_INVALIDDATA;
+
+        for (; i < s->nb_subframes - 1; i++) {
+            int v = get_bits(gb, 6);
+
+            s->subframe_len[i] = (v - prev) * s->subframe_scale;
+            if (s->subframe_len[i] <= 0)
+                return AVERROR_INVALIDDATA;
+
+            left -= s->subframe_len[i];
+            prev  = v;
+        }
+
+        if (left <= 0)
+            return AVERROR_INVALIDDATA;
+    }
+
+    s->subframe_len[i] = left;
+    prev = 0;
+    for (i = 0; i < s->nb_subframes; i++) {
+        if ((ret = decode_subframe(s, dst, s->subframe_len[i], prev)) < 0)
+            return ret;
+        dst += s->subframe_len[i];
+        prev = s->subframe_len[i];
+    }
+
+    return 0;
+}
+
+static int decorrelate(TAKDecContext *s, int c1, int c2, int length)
+{
+    GetBitContext  *gb = &s->gb;
+    uint32_t *p1 = s->decoded[c1] + 1;
+    uint32_t *p2 = s->decoded[c2] + 1;
+    int a, b, i, x, tmp;
+
+    if (s->dmode > 3) {
+        s->dshift = get_b(gb);
+        if (s->dmode > 5) {
+            if (get_bits1(gb))
+                s->filter_order = 16;
+            else
+                s->filter_order = 8;
+
+            s->dval1 = get_bits1(gb);
+            s->dval2 = get_bits1(gb);
+
+            for (i = 0; i < s->filter_order; i++) {
+                if (!(i & 3))
+                    x = 14 - get_bits(gb, 3);
+                s->filter[i] = get_code(gb, x);
+            }
+        } else {
+            s->dfactor = get_code(gb, 10);
+        }
+    }
+
+    switch (s->dmode) {
+    case 1:
+        for (i = 0; i < length; i++, p1++, p2++)
+            *p2 += *p1;
+        break;
+    case 2:
+        for (i = 0; i < length; i++, p1++, p2++)
+            *p1 = *p2 - *p1;
+        break;
+    case 3:
+        for (i = 0; i < length; i++, p1++, p2++) {
+            x   = (*p2 & 1) + 2 * *p1;
+            a   = -*p2 + x;
+            b   =  *p2 + x;
+            *p1 = a & 0x80000000 | (a >> 1);
+            *p2 = b & 0x80000000 | (b >> 1);
+        }
+        break;
+    case 4:
+        FFSWAP(uint32_t *, p1, p2);
+    case 5:
+        if (s->dshift)
+            tmp = -1 << (32 - s->dshift);
+        else
+            tmp = 0;
+
+        for (i = 0; i < length; i++, p1++, p2++) {
+            x   = s->dfactor * (tmp & -(*p2 >> 31) | (*p2 >> s->dshift)) + 128;
+            *p1 = ((-(x >> 31) & 0xFF000000 | (x >> 8)) << s->dshift) - *p1;
+        }
+        break;
+    case 6:
+        FFSWAP(uint32_t *, p1, p2);
+    case 7:
+        if (length < 256)
+            return AVERROR_INVALIDDATA;
+
+        a = s->filter_order / 2;
+        b = length - (s->filter_order - 1);
+
+        if (s->dval1) {
+            for (i = 0; i < a; i++)
+                p1[i] += p2[i];
+        }
+
+        if (s->dval2) {
+            x = a + b;
+            for (i = 0; i < length - x; i++)
+                p1[x + i] += p2[x + i];
+        }
+
+        for (i = 0; i < s->filter_order; i++)
+            s->residues[i] = *p2++ >> s->dshift;
+
+        p1 += a;
+        x = FF_ARRAY_ELEMS(s->residues) - s->filter_order;
+        for (; b > 0; b -= tmp) {
+            tmp = FFMIN(b, x);
+
+            for (i = 0; i < tmp; i++)
+                s->residues[s->filter_order + i] = *p2++ >> s->dshift;
+
+            for (i = 0; i < tmp; i++) {
+                int v, w, m;
+
+                v = 1 << 9;
+
+                if (s->filter_order == 16) {
+                    v += s->dsp.scalarproduct_int16(&s->residues[i], s->filter,
+                                                    s->filter_order);
+                } else {
+                    v += s->residues[i + 7] * s->filter[7] +
+                         s->residues[i + 6] * s->filter[6] +
+                         s->residues[i + 5] * s->filter[5] +
+                         s->residues[i + 4] * s->filter[4] +
+                         s->residues[i + 3] * s->filter[3] +
+                         s->residues[i + 2] * s->filter[2] +
+                         s->residues[i + 1] * s->filter[1] +
+                         s->residues[i    ] * s->filter[0];
+                }
+
+                m = (-1 << 22) & -(v >> 31) | (v >> 10);
+                m = av_clip(m, -8192, 8191);
+                w = (m << s->dshift) - *p1;
+                *p1++ = w;
+            }
+
+            memcpy(s->residues, &s->residues[tmp], 2 * s->filter_order);
+        }
+
+        emms_c();
+        break;
+    }
+
+    return 0;
+}
+
+static int tak_decode_frame(AVCodecContext *avctx, void *data,
+                            int *got_frame_ptr, AVPacket *pkt)
+{
+    TAKDecContext  *s = avctx->priv_data;
+    GetBitContext *gb = &s->gb;
+    int chan, i, ret, hsize;
+    int32_t *p;
+
+    if (pkt->size < TAK_MIN_FRAME_HEADER_BYTES)
+        return AVERROR_INVALIDDATA;
+
+    init_get_bits(gb, pkt->data, pkt->size * 8);
+
+    if ((ret = ff_tak_decode_frame_header(avctx, gb, &s->ti, 0)) < 0)
+        return ret;
+
+    if (avctx->err_recognition & AV_EF_CRCCHECK) {
+        hsize = get_bits_count(gb) / 8;
+        if (ff_tak_check_crc(pkt->data, hsize)) {
+            av_log(avctx, AV_LOG_ERROR, "CRC error\n");
+            return AVERROR_INVALIDDATA;
+        }
+    }
+
+    if (s->ti.codec != 2 && s->ti.codec != 4) {
+        av_log(avctx, AV_LOG_ERROR, "unsupported codec: %d\n", s->ti.codec);
+        return AVERROR_PATCHWELCOME;
+    }
+    if (s->ti.data_type) {
+        av_log(avctx, AV_LOG_ERROR, "unsupported data type: %d\n", s->ti.data_type);
+        return AVERROR_INVALIDDATA;
+    }
+    if (s->ti.codec == 2 && s->ti.channels > 2) {
+        av_log(avctx, AV_LOG_ERROR, "invalid number of channels: %d\n", s->ti.channels);
+        return AVERROR_INVALIDDATA;
+    }
+    if (s->ti.channels > 6) {
+        av_log(avctx, AV_LOG_ERROR, "unsupported number of channels: %d\n", s->ti.channels);
+        return AVERROR_INVALIDDATA;
+    }
+
+    if (s->ti.frame_samples <= 0) {
+        av_log(avctx, AV_LOG_ERROR, "unsupported/invalid number of samples\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    if (s->ti.bps != avctx->bits_per_raw_sample) {
+        avctx->bits_per_raw_sample = s->ti.bps;
+        if ((ret = tak_set_bps(avctx, avctx->bits_per_raw_sample)) < 0)
+            return ret;
+    }
+    if (s->ti.sample_rate != avctx->sample_rate) {
+        avctx->sample_rate = s->ti.sample_rate;
+        s->uval = get_scale(avctx->sample_rate, get_shift(avctx->sample_rate));
+        s->subframe_scale = get_scale(avctx->sample_rate, 1);
+    }
+    if (s->ti.ch_layout)
+        avctx->channel_layout = s->ti.ch_layout;
+    avctx->channels = s->ti.channels;
+
+    s->nb_samples = s->ti.last_frame_samples ? s->ti.last_frame_samples :
+                                               s->ti.frame_samples;
+
+    s->frame.nb_samples = s->nb_samples;
+    if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0)
+        return ret;
+
+    if (avctx->bits_per_raw_sample <= 16) {
+        av_fast_malloc(&s->decode_buffer, &s->decode_buffer_size,
+                       sizeof(*s->decode_buffer) * FFALIGN(s->nb_samples, 8) *
+                       avctx->channels + FF_INPUT_BUFFER_PADDING_SIZE);
+        if (!s->decode_buffer)
+            return AVERROR(ENOMEM);
+        for (chan = 0; chan < avctx->channels; chan++)
+            s->decoded[chan] = s->decode_buffer +
+                               chan * FFALIGN(s->nb_samples, 8);
+    } else {
+        for (chan = 0; chan < avctx->channels; chan++)
+            s->decoded[chan] = (int32_t *)s->frame.data[chan];
+    }
+
+    if (s->nb_samples < 16) {
+        for (chan = 0; chan < avctx->channels; chan++) {
+            p = s->decoded[chan];
+            for (i = 0; i < s->nb_samples; i++)
+                *p++ = get_code(gb, avctx->bits_per_raw_sample);
+        }
+    } else {
+        if (s->ti.codec == 2) {
+            for (chan = 0; chan < avctx->channels; chan++) {
+                if (ret = decode_channel(s, chan))
+                    return ret;
+            }
+
+            if (avctx->channels == 2) {
+                s->nb_subframes = get_bits(gb, 1) + 1;
+                if (s->nb_subframes > 1)
+                    s->subframe_len[1] = get_bits(gb, 6);
+
+                s->dmode = get_bits(gb, 3);
+                if (ret = decorrelate(s, 0, 1, s->nb_samples - 1))
+                    return ret;
+            }
+        } else if (s->ti.codec == 4) {
+            if (get_bits1(gb)) {
+                int ch_mask = 0;
+
+                chan = get_bits(gb, 4) + 1;
+                if (chan > avctx->channels)
+                    return AVERROR_INVALIDDATA;
+
+                for (i = 0; i < chan; i++) {
+                    int nbit = get_bits(gb, 4);
+
+                    if (nbit >= avctx->channels)
+                        return AVERROR_INVALIDDATA;
+
+                    if (ch_mask & 1 << nbit)
+                        return AVERROR_INVALIDDATA;
+
+                    s->mcdparams[i].present = get_bits1(gb);
+                    if (s->mcdparams[i].present) {
+                        s->mcdparams[i].index = get_bits(gb, 2);
+                        s->mcdparams[i].chan2 = get_bits(gb, 4);
+                        if (s->mcdparams[i].index == 1) {
+                            if ((nbit == s->mcdparams[i].chan2) ||
+                                (ch_mask & 1 << s->mcdparams[i].chan2))
+                                return AVERROR_INVALIDDATA;
+
+                            ch_mask |= 1 << s->mcdparams[i].chan2;
+                        } else if (!(ch_mask & 1 << s->mcdparams[i].chan2)) {
+                            return AVERROR_INVALIDDATA;
+                        }
+                    }
+                    s->mcdparams[i].chan1 = nbit;
+
+                    ch_mask |= 1 << nbit;
+                }
+            } else {
+                chan = avctx->channels;
+                for (i = 0; i < chan; i++) {
+                    s->mcdparams[i].present = 0;
+                    s->mcdparams[i].chan1   = i;
+                }
+            }
+
+            for (i = 0; i < chan; i++) {
+                if (s->mcdparams[i].present && s->mcdparams[i].index == 1) {
+                    if (ret = decode_channel(s, s->mcdparams[i].chan2))
+                        return ret;
+                }
+
+                if (ret = decode_channel(s, s->mcdparams[i].chan1))
+                    return ret;
+
+                if (s->mcdparams[i].present) {
+                    s->dmode = mc_dmodes[s->mcdparams[i].index];
+                    if (ret = decorrelate(s, s->mcdparams[i].chan2,
+                                             s->mcdparams[i].chan1,
+                                             s->nb_samples - 1))
+                        return ret;
+                }
+            }
+        }
+
+        for (chan = 0; chan < avctx->channels; chan++) {
+            p = s->decoded[chan];
+            decode_lpc(p, s->lpc_mode[chan], s->nb_samples);
+
+            if (s->sample_shift[chan] > 0) {
+                for (i = 0; i < s->nb_samples; i++)
+                    *p++ <<= s->sample_shift[chan];
+            }
+        }
+    }
+
+    align_get_bits(gb);
+    skip_bits(gb, 24);
+    if (get_bits_left(gb) < 0)
+        av_log(avctx, AV_LOG_DEBUG, "overread\n");
+    else if (get_bits_left(gb) > 0)
+        av_log(avctx, AV_LOG_DEBUG, "underread\n");
+
+    if (avctx->err_recognition & AV_EF_CRCCHECK) {
+        if (ff_tak_check_crc(pkt->data + hsize,
+                             get_bits_count(gb) / 8 - hsize)) {
+            av_log(avctx, AV_LOG_ERROR, "CRC error\n");
+            return AVERROR_INVALIDDATA;
+        }
+    }
+
+    // convert to output buffer
+    switch (avctx->bits_per_raw_sample) {
+    case 8:
+        for (chan = 0; chan < avctx->channels; chan++) {
+            uint8_t *samples = (uint8_t *)s->frame.data[chan];
+            p = s->decoded[chan];
+            for (i = 0; i < s->nb_samples; i++, p++)
+                *samples++ = *p + 0x80;
+        }
+        break;
+    case 16:
+        for (chan = 0; chan < avctx->channels; chan++) {
+            int16_t *samples = (int16_t *)s->frame.data[chan];
+            p = s->decoded[chan];
+            for (i = 0; i < s->nb_samples; i++, p++)
+                *samples++ = *p;
+        }
+        break;
+    case 24:
+        for (chan = 0; chan < avctx->channels; chan++) {
+            int32_t *samples = (int32_t *)s->frame.data[chan];
+            for (i = 0; i < s->nb_samples; i++)
+                *samples++ <<= 8;
+        }
+        break;
+    }
+
+    *got_frame_ptr   = 1;
+    *(AVFrame *)data = s->frame;
+
+    return pkt->size;
+}
+
+static av_cold int tak_decode_close(AVCodecContext *avctx)
+{
+    TAKDecContext *s = avctx->priv_data;
+
+    av_freep(&s->decode_buffer);
+
+    return 0;
+}
+
+AVCodec ff_tak_decoder = {
+    .name           = "tak",
+    .type           = AVMEDIA_TYPE_AUDIO,
+    .id             = AV_CODEC_ID_TAK,
+    .priv_data_size = sizeof(TAKDecContext),
+    .init           = tak_decode_init,
+    .close          = tak_decode_close,
+    .decode         = tak_decode_frame,
+    .capabilities   = CODEC_CAP_DR1,
+    .long_name      = NULL_IF_CONFIG_SMALL("TAK (Tom's lossless Audio Kompressor)"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
+                                                      AV_SAMPLE_FMT_S16P,
+                                                      AV_SAMPLE_FMT_S32P,
+                                                      AV_SAMPLE_FMT_NONE },
+};
diff --git a/libavcodec/targa.c b/libavcodec/targa.c
index 339d7c4..d761078 100644
--- a/libavcodec/targa.c
+++ b/libavcodec/targa.c
@@ -28,22 +28,37 @@
 typedef struct TargaContext {
     AVFrame picture;
     GetByteContext gb;
-
-    int color_type;
-    int compression_type;
 } TargaContext;
 
+static uint8_t *advance_line(uint8_t *start, uint8_t *line,
+                             int stride, int *y, int h, int interleave)
+{
+    *y += interleave;
+
+    if (*y < h) {
+        return line + interleave * stride;
+    } else {
+        *y = (*y + 1) & (interleave - 1);
+        if (*y) {
+            return start + *y * stride;
+        } else {
+            return NULL;
+        }
+    }
+}
+
 static int targa_decode_rle(AVCodecContext *avctx, TargaContext *s,
-                            uint8_t *dst, int w, int h, int stride, int bpp)
+                            uint8_t *start, int w, int h, int stride,
+                            int bpp, int interleave)
 {
     int x, y;
     int depth = (bpp + 1) >> 3;
     int type, count;
-    int diff;
+    uint8_t *line = start;
+    uint8_t *dst  = line;
 
-    diff = stride - w * depth;
-    x = y = 0;
-    while (y < h) {
+    x = y = count = 0;
+    while (dst) {
         if (bytestream2_get_bytes_left(&s->gb) <= 0) {
             av_log(avctx, AV_LOG_ERROR,
                    "Ran ouf of data before end-of-image\n");
@@ -52,12 +67,6 @@
         type  = bytestream2_get_byteu(&s->gb);
         count = (type & 0x7F) + 1;
         type &= 0x80;
-        if(x + count > (h - y) * w){
-            av_log(avctx, AV_LOG_ERROR,
-                   "Packet went out of bounds: position (%i,%i) size %i\n",
-                   x, y, count);
-            return AVERROR_INVALIDDATA;
-        }
         if (!type) {
             do {
                 int n  = FFMIN(count, w - x);
@@ -67,10 +76,9 @@
                 x     += n;
                 if (x == w) {
                     x    = 0;
-                    y++;
-                    dst += diff;
+                    dst = line = advance_line(start, line, stride, &y, h, interleave);
                 }
-            } while (count > 0);
+            } while (dst && count > 0);
         } else {
             uint8_t tmp[4];
             bytestream2_get_buffer(&s->gb, tmp, depth);
@@ -84,12 +92,17 @@
                 } while (--n);
                 if (x == w) {
                     x    = 0;
-                    y++;
-                    dst += diff;
+                    dst = line = advance_line(start, line, stride, &y, h, interleave);
                 }
-            } while (count > 0);
+            } while (dst && count > 0);
         }
     }
+
+    if (count) {
+        av_log(avctx, AV_LOG_ERROR, "Packet went out of bounds\n");
+        return AVERROR_INVALIDDATA;
+    }
+
     return 0;
 }
 
@@ -102,8 +115,9 @@
     AVFrame * const p = &s->picture;
     uint8_t *dst;
     int stride;
-    int idlen, pal, compr, y, w, h, bpp, flags;
+    int idlen, pal, compr, y, w, h, bpp, flags, ret;
     int first_clr, colors, csize;
+    int interleave;
 
     bytestream2_init(&s->gb, avpkt->data, avpkt->size);
 
@@ -136,62 +150,68 @@
     // skip identifier if any
     bytestream2_skip(&s->gb, idlen);
 
-    switch(bpp){
+    switch (bpp) {
     case 8:
-        avctx->pix_fmt = ((compr & (~TGA_RLE)) == TGA_BW) ? PIX_FMT_GRAY8 : PIX_FMT_PAL8;
+        avctx->pix_fmt = ((compr & (~TGA_RLE)) == TGA_BW) ? AV_PIX_FMT_GRAY8 : AV_PIX_FMT_PAL8;
         break;
     case 15:
     case 16:
-        avctx->pix_fmt = PIX_FMT_RGB555LE;
+        avctx->pix_fmt = AV_PIX_FMT_RGB555LE;
         break;
     case 24:
-        avctx->pix_fmt = PIX_FMT_BGR24;
+        avctx->pix_fmt = AV_PIX_FMT_BGR24;
         break;
     case 32:
-        avctx->pix_fmt = PIX_FMT_BGRA;
+        avctx->pix_fmt = AV_PIX_FMT_BGRA;
         break;
     default:
         av_log(avctx, AV_LOG_ERROR, "Bit depth %i is not supported\n", bpp);
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
-    if(s->picture.data[0])
+    if (s->picture.data[0])
         avctx->release_buffer(avctx, &s->picture);
 
-    if(av_image_check_size(w, h, 0, avctx))
-        return -1;
-    if(w != avctx->width || h != avctx->height)
-        avcodec_set_dimensions(avctx, w, h);
-    if(avctx->get_buffer(avctx, p) < 0){
-        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
+    if (colors && (colors + first_clr) > 256) {
+        av_log(avctx, AV_LOG_ERROR, "Incorrect palette: %i colors with offset %i\n", colors, first_clr);
+        return AVERROR_INVALIDDATA;
     }
-    if(flags & 0x20){
+
+    if ((ret = av_image_check_size(w, h, 0, avctx)))
+        return ret;
+    if (w != avctx->width || h != avctx->height)
+        avcodec_set_dimensions(avctx, w, h);
+    if ((ret = avctx->get_buffer(avctx, p)) < 0) {
+        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+        return ret;
+    }
+
+    if (flags & TGA_TOPTOBOTTOM) {
         dst = p->data[0];
         stride = p->linesize[0];
-    }else{ //image is upside-down
+    } else { //image is upside-down
         dst = p->data[0] + p->linesize[0] * (h - 1);
         stride = -p->linesize[0];
     }
 
-    if(colors){
+    interleave = flags & TGA_INTERLEAVE2 ? 2 :
+                 flags & TGA_INTERLEAVE4 ? 4 : 1;
+
+    if (colors) {
         int pal_size, pal_sample_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;
-        }
         switch (csize) {
+        case 32: pal_sample_size = 4; break;
         case 24: pal_sample_size = 3; break;
         case 16:
         case 15: pal_sample_size = 2; break;
         default:
             av_log(avctx, AV_LOG_ERROR, "Palette entry size %i bits is not supported\n", csize);
-            return -1;
+            return AVERROR_INVALIDDATA;
         }
         pal_size = colors * pal_sample_size;
-        if(avctx->pix_fmt != PIX_FMT_PAL8)//should not occur but skip palette anyway
+        if (avctx->pix_fmt != AV_PIX_FMT_PAL8) //should not occur but skip palette anyway
             bytestream2_skip(&s->gb, pal_size);
-        else{
+        else {
             int t;
             uint32_t *pal = ((uint32_t *)p->data[1]) + first_clr;
 
@@ -201,6 +221,10 @@
                 return AVERROR_INVALIDDATA;
             }
             switch (pal_sample_size) {
+            case 4:
+                for (t = 0; t < colors; t++)
+                    *pal++ = bytestream2_get_le32u(&s->gb);
+                break;
             case 3:
                 /* RGB24 */
                 for (t = 0; t < colors; t++)
@@ -222,32 +246,38 @@
             p->palette_has_changed = 1;
         }
     }
+
     if ((compr & (~TGA_RLE)) == TGA_NODATA) {
         memset(p->data[0], 0, p->linesize[0] * h);
     } else {
-        if(compr & TGA_RLE){
-            int res = targa_decode_rle(avctx, s, dst, w, h, stride, bpp);
+        if (compr & TGA_RLE) {
+            int res = targa_decode_rle(avctx, s, dst, w, h, stride, bpp, interleave);
             if (res < 0)
                 return res;
         } else {
             size_t img_size = w * ((bpp + 1) >> 3);
+            uint8_t *line;
             if (bytestream2_get_bytes_left(&s->gb) < img_size * h) {
                 av_log(avctx, AV_LOG_ERROR,
                        "Not enough data available for image\n");
                 return AVERROR_INVALIDDATA;
             }
-            for (y = 0; y < h; y++) {
-                bytestream2_get_bufferu(&s->gb, dst, img_size);
-                dst += stride;
-            }
+
+            line = dst;
+            y = 0;
+            do {
+                bytestream2_get_bufferu(&s->gb, line, img_size);
+                line = advance_line(dst, line, stride, &y, h, interleave);
+            } while (line);
         }
     }
-    if(flags & 0x10){ // right-to-left, needs horizontal flip
+
+    if (flags & TGA_RIGHTTOLEFT) { // right-to-left, needs horizontal flip
         int x;
-        for(y = 0; y < h; y++){
+        for (y = 0; y < h; y++) {
             void *line = &p->data[0][y * p->linesize[0]];
-            for(x = 0; x < w >> 1; x++){
-                switch(bpp){
+            for (x = 0; x < w >> 1; x++) {
+                switch (bpp) {
                 case 32:
                     FFSWAP(uint32_t, ((uint32_t *)line)[x], ((uint32_t *)line)[w - x - 1]);
                     break;
@@ -272,7 +302,8 @@
     return avpkt->size;
 }
 
-static av_cold int targa_init(AVCodecContext *avctx){
+static av_cold int targa_init(AVCodecContext *avctx)
+{
     TargaContext *s = avctx->priv_data;
 
     avcodec_get_frame_defaults(&s->picture);
@@ -281,10 +312,11 @@
     return 0;
 }
 
-static av_cold int targa_end(AVCodecContext *avctx){
+static av_cold int targa_end(AVCodecContext *avctx)
+{
     TargaContext *s = avctx->priv_data;
 
-    if(s->picture.data[0])
+    if (s->picture.data[0])
         avctx->release_buffer(avctx, &s->picture);
 
     return 0;
diff --git a/libavcodec/targa.h b/libavcodec/targa.h
index 158a5ea..c2f5224 100644
--- a/libavcodec/targa.h
+++ b/libavcodec/targa.h
@@ -38,4 +38,11 @@
     TGA_RLE    = 8, // flag pointing that data is RLE-coded
 };
 
+enum TargaFlags {
+    TGA_RIGHTTOLEFT = 0x10, // right-to-left (flipped horizontally)
+    TGA_TOPTOBOTTOM = 0x20, // top-to-bottom (NOT flipped vertically)
+    TGA_INTERLEAVE2 = 0x40, // 2-way interleave, odd then even lines
+    TGA_INTERLEAVE4 = 0x80, // 4-way interleave
+};
+
 #endif /* AVCODEC_TARGA_H */
diff --git a/libavcodec/targa_y216dec.c b/libavcodec/targa_y216dec.c
new file mode 100644
index 0000000..bac5aee
--- /dev/null
+++ b/libavcodec/targa_y216dec.c
@@ -0,0 +1,108 @@
+/*
+ * Pinnacle TARGA CineWave YUV16 decoder
+ * Copyright (c) 2012 Carl Eugen Hoyos
+ *
+ * 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"
+
+static av_cold int y216_decode_init(AVCodecContext *avctx)
+{
+    avctx->pix_fmt             = AV_PIX_FMT_YUV422P16;
+    avctx->bits_per_raw_sample = 14;
+
+    avctx->coded_frame = avcodec_alloc_frame();
+
+    if (!avctx->coded_frame) {
+        av_log(avctx, AV_LOG_ERROR, "Could not allocate frame.\n");
+        return AVERROR(ENOMEM);
+    }
+
+    return 0;
+}
+
+static int y216_decode_frame(AVCodecContext *avctx, void *data,
+                             int *data_size, AVPacket *avpkt)
+{
+    AVFrame *pic = avctx->coded_frame;
+    const uint16_t *src = (uint16_t *)avpkt->data;
+    uint16_t *y, *u, *v, aligned_width = FFALIGN(avctx->width, 4);
+    int i, j;
+
+    if (pic->data[0])
+        avctx->release_buffer(avctx, pic);
+
+    if (avpkt->size < 4 * avctx->height * aligned_width) {
+        av_log(avctx, AV_LOG_ERROR, "Insufficient input data.\n");
+        return AVERROR(EINVAL);
+    }
+
+    pic->reference = 0;
+
+    if (avctx->get_buffer(avctx, pic) < 0) {
+        av_log(avctx, AV_LOG_ERROR, "Could not allocate buffer.\n");
+        return AVERROR(ENOMEM);
+    }
+
+    pic->key_frame = 1;
+    pic->pict_type = AV_PICTURE_TYPE_I;
+
+    y = (uint16_t *)pic->data[0];
+    u = (uint16_t *)pic->data[1];
+    v = (uint16_t *)pic->data[2];
+
+    for (i = 0; i < avctx->height; i++) {
+        for (j = 0; j < avctx->width >> 1; j++) {
+            u[    j    ] = src[4 * j    ] << 2 | src[4 * j    ] >> 14;
+            y[2 * j    ] = src[4 * j + 1] << 2 | src[4 * j + 1] >> 14;
+            v[    j    ] = src[4 * j + 2] << 2 | src[4 * j + 2] >> 14;
+            y[2 * j + 1] = src[4 * j + 3] << 2 | src[4 * j + 3] >> 14;
+        }
+
+        y += pic->linesize[0] >> 1;
+        u += pic->linesize[1] >> 1;
+        v += pic->linesize[2] >> 1;
+        src += aligned_width << 1;
+    }
+
+    *data_size = sizeof(AVFrame);
+    *(AVFrame *)data = *pic;
+
+    return avpkt->size;
+}
+
+static av_cold int y216_decode_close(AVCodecContext *avctx)
+{
+    if (avctx->coded_frame->data[0])
+        avctx->release_buffer(avctx, avctx->coded_frame);
+
+    av_freep(&avctx->coded_frame);
+
+    return 0;
+}
+
+AVCodec ff_targa_y216_decoder = {
+    .name         = "targa_y216",
+    .type         = AVMEDIA_TYPE_VIDEO,
+    .id           = AV_CODEC_ID_TARGA_Y216,
+    .init         = y216_decode_init,
+    .decode       = y216_decode_frame,
+    .close        = y216_decode_close,
+    .capabilities = CODEC_CAP_DR1,
+    .long_name    = NULL_IF_CONFIG_SMALL("Pinnacle TARGA CineWave YUV16"),
+};
diff --git a/libavcodec/targaenc.c b/libavcodec/targaenc.c
index 2f22e94..b2c679d 100644
--- a/libavcodec/targaenc.c
+++ b/libavcodec/targaenc.c
@@ -97,37 +97,48 @@
     AV_WL16(pkt->data+12, avctx->width);
     AV_WL16(pkt->data+14, avctx->height);
     /* image descriptor byte: origin is always top-left, bits 0-3 specify alpha */
-    pkt->data[17] = 0x20 | (avctx->pix_fmt == PIX_FMT_BGRA ? 8 : 0);
+    pkt->data[17] = 0x20 | (avctx->pix_fmt == AV_PIX_FMT_BGRA ? 8 : 0);
 
     out = pkt->data + 18;  /* skip past the header we write */
 
-    avctx->bits_per_coded_sample = av_get_bits_per_pixel(&av_pix_fmt_descriptors[avctx->pix_fmt]);
+    avctx->bits_per_coded_sample = av_get_bits_per_pixel(av_pix_fmt_desc_get(avctx->pix_fmt));
     switch(avctx->pix_fmt) {
-    case PIX_FMT_PAL8:
+    case AV_PIX_FMT_PAL8: {
+        int pal_bpp = 24; /* Only write 32bit palette if there is transparency information */
+        for (i = 0; i < 256; i++)
+            if (AV_RN32(p->data[1] + 4 * i) >> 24 != 0xFF) {
+                pal_bpp = 32;
+                break;
+            }
         pkt->data[1]  = 1;          /* palette present */
         pkt->data[2]  = TGA_PAL;    /* uncompressed palettised image */
         pkt->data[6]  = 1;          /* palette contains 256 entries */
-        pkt->data[7]  = 24;         /* palette contains 24 bit entries */
+        pkt->data[7]  = pal_bpp;    /* palette contains pal_bpp bit entries */
         pkt->data[16] = 8;          /* bpp */
         for (i = 0; i < 256; i++)
+            if (pal_bpp == 32) {
+                AV_WL32(pkt->data + 18 + 4 * i, *(uint32_t *)(p->data[1] + i * 4));
+            } else {
             AV_WL24(pkt->data + 18 + 3 * i, *(uint32_t *)(p->data[1] + i * 4));
-        out += 256 * 3;             /* skip past the palette we just output */
+            }
+        out += 32 * pal_bpp;        /* skip past the palette we just output */
         break;
-    case PIX_FMT_GRAY8:
+        }
+    case AV_PIX_FMT_GRAY8:
         pkt->data[2]  = TGA_BW;     /* uncompressed grayscale image */
         avctx->bits_per_coded_sample = 0x28;
         pkt->data[16] = 8;          /* bpp */
         break;
-    case PIX_FMT_RGB555LE:
+    case AV_PIX_FMT_RGB555LE:
         pkt->data[2]  = TGA_RGB;    /* uncompressed true-color image */
         avctx->bits_per_coded_sample =
         pkt->data[16] = 16;         /* bpp */
         break;
-    case PIX_FMT_BGR24:
+    case AV_PIX_FMT_BGR24:
         pkt->data[2]  = TGA_RGB;    /* uncompressed true-color image */
         pkt->data[16] = 24;         /* bpp */
         break;
-    case PIX_FMT_BGRA:
+    case AV_PIX_FMT_BGRA:
         pkt->data[2]  = TGA_RGB;    /* uncompressed true-color image */
         pkt->data[16] = 32;         /* bpp */
         break;
@@ -182,9 +193,9 @@
     .priv_data_size = sizeof(TargaContext),
     .init           = targa_encode_init,
     .encode2        = targa_encode_frame,
-    .pix_fmts       = (const enum PixelFormat[]){
-        PIX_FMT_BGR24, PIX_FMT_BGRA, PIX_FMT_RGB555LE, PIX_FMT_GRAY8, PIX_FMT_PAL8,
-        PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]){
+        AV_PIX_FMT_BGR24, AV_PIX_FMT_BGRA, AV_PIX_FMT_RGB555LE, AV_PIX_FMT_GRAY8, AV_PIX_FMT_PAL8,
+        AV_PIX_FMT_NONE
     },
     .long_name= NULL_IF_CONFIG_SMALL("Truevision Targa image"),
 };
diff --git a/libavcodec/textdec.c b/libavcodec/textdec.c
new file mode 100644
index 0000000..4b3a4ad
--- /dev/null
+++ b/libavcodec/textdec.c
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) 2012 Clément Bœsch
+ *
+ * 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
+ * Raw subtitles decoder
+ */
+
+#include "avcodec.h"
+#include "ass.h"
+#include "libavutil/bprint.h"
+#include "libavutil/opt.h"
+
+typedef struct {
+    AVClass *class;
+    char *linebreaks;
+    int keep_ass_markup;
+} TextContext;
+
+#define OFFSET(x) offsetof(TextContext, x)
+#define SD AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_DECODING_PARAM
+static const AVOption options[] = {
+    { "linebreaks",      "Extra line breaks characters",    OFFSET(linebreaks),      AV_OPT_TYPE_STRING, {.str=NULL},    .flags=SD },
+    { "keep_ass_markup", "Set if ASS tags must be escaped", OFFSET(keep_ass_markup), AV_OPT_TYPE_INT,    {.i64=0}, 0, 1, .flags=SD },
+    { NULL }
+};
+
+static const AVClass text_decoder_class = {
+    .class_name = "text decoder",
+    .item_name  = av_default_item_name,
+    .option     = options,
+    .version    = LIBAVUTIL_VERSION_INT,
+};
+
+static int text_event_to_ass(const AVCodecContext *avctx, AVBPrint *buf,
+                             const char *p, const char *p_end)
+{
+    const TextContext *text = avctx->priv_data;
+
+    for (; p < p_end && *p; p++) {
+
+        /* forced custom line breaks, not accounted as "normal" EOL */
+        if (text->linebreaks && strchr(text->linebreaks, *p)) {
+            av_bprintf(buf, "\\N");
+
+        /* standard ASS escaping so random characters don't get mis-interpreted
+         * as ASS */
+        } else if (!text->keep_ass_markup && strchr("{}\\", *p)) {
+            av_bprintf(buf, "\\%c", *p);
+
+        /* some packets might end abruptly (no \0 at the end, like for example
+         * in some cases of demuxing from a classic video container), some
+         * might be terminated with \n or \r\n which we have to remove (for
+         * consistency with those who haven't), and we also have to deal with
+         * evil cases such as \r at the end of the buffer (and no \0 terminated
+         * character) */
+        } else if (p[0] == '\n') {
+            /* some stuff left so we can insert a line break */
+            if (p < p_end - 1)
+                av_bprintf(buf, "\\N");
+        } else if (p[0] == '\r' && p < p_end - 1 && p[1] == '\n') {
+            /* \r followed by a \n, we can skip it. We don't insert the \N yet
+             * because we don't know if it is followed by more text */
+            continue;
+
+        /* finally, a sane character */
+        } else {
+            av_bprint_chars(buf, *p, 1);
+        }
+    }
+    av_bprintf(buf, "\r\n");
+    return 0;
+}
+
+static int text_decode_frame(AVCodecContext *avctx, void *data,
+                             int *got_sub_ptr, AVPacket *avpkt)
+{
+    AVBPrint buf;
+    AVSubtitle *sub = data;
+    const char *ptr = avpkt->data;
+    const int ts_start     = av_rescale_q(avpkt->pts,      avctx->time_base, (AVRational){1,100});
+    const int ts_duration  = avpkt->duration != -1 ?
+                             av_rescale_q(avpkt->duration, avctx->time_base, (AVRational){1,100}) : -1;
+
+    av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
+    if (ptr && avpkt->size > 0 && *ptr &&
+        !text_event_to_ass(avctx, &buf, ptr, ptr + avpkt->size)) {
+        if (!av_bprint_is_complete(&buf)) {
+            av_bprint_finalize(&buf, NULL);
+            return AVERROR(ENOMEM);
+        }
+        ff_ass_add_rect(sub, buf.str, ts_start, ts_duration, 0);
+    }
+    *got_sub_ptr = sub->num_rects > 0;
+    av_bprint_finalize(&buf, NULL);
+    return avpkt->size;
+}
+
+AVCodec ff_text_decoder = {
+    .name           = "text",
+    .priv_data_size = sizeof(TextContext),
+    .long_name      = NULL_IF_CONFIG_SMALL("Raw text subtitle"),
+    .type           = AVMEDIA_TYPE_SUBTITLE,
+    .id             = AV_CODEC_ID_TEXT,
+    .decode         = text_decode_frame,
+    .init           = ff_ass_subtitle_header_default,
+    .priv_class     = &text_decoder_class,
+};
diff --git a/libavcodec/tiertexseqv.c b/libavcodec/tiertexseqv.c
index 75a985d..62b7eeb 100644
--- a/libavcodec/tiertexseqv.c
+++ b/libavcodec/tiertexseqv.c
@@ -178,7 +178,7 @@
         for (i = 0; i < 256; i++) {
             for (j = 0; j < 3; j++, data++)
                 c[j] = (*data << 2) | (*data >> 4);
-            palette[i] = 0xFF << 24 | AV_RB24(c);
+            palette[i] = 0xFFU << 24 | AV_RB24(c);
         }
         seq->frame.palette_has_changed = 1;
     }
@@ -214,7 +214,7 @@
     SeqVideoContext *seq = avctx->priv_data;
 
     seq->avctx = avctx;
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     avcodec_get_frame_defaults(&seq->frame);
     seq->frame.data[0] = NULL;
diff --git a/libavcodec/tiff.c b/libavcodec/tiff.c
index 579bd0d..34fb109 100644
--- a/libavcodec/tiff.c
+++ b/libavcodec/tiff.c
@@ -34,7 +34,8 @@
 #include "tiff.h"
 #include "tiff_data.h"
 #include "faxcompr.h"
-#include "libavutil/common.h"
+#include "mathops.h"
+#include "libavutil/attributes.h"
 #include "libavutil/intreadwrite.h"
 #include "libavutil/imgutils.h"
 #include "libavutil/avstring.h"
@@ -66,26 +67,26 @@
 
 static unsigned tget_short(GetByteContext *gb, int le)
 {
-    unsigned v = le ? bytestream2_get_le16u(gb) : bytestream2_get_be16u(gb);
+    unsigned v = le ? bytestream2_get_le16(gb) : bytestream2_get_be16(gb);
     return v;
 }
 
 static unsigned tget_long(GetByteContext *gb, int le)
 {
-    unsigned v = le ? bytestream2_get_le32u(gb) : bytestream2_get_be32u(gb);
+    unsigned v = le ? bytestream2_get_le32(gb) : bytestream2_get_be32(gb);
     return v;
 }
 
 static double tget_double(GetByteContext *gb, int le)
 {
-    av_alias64 i = { .u64 = le ? bytestream2_get_le64u(gb) : bytestream2_get_be64u(gb)};
+    av_alias64 i = { .u64 = le ? bytestream2_get_le64(gb) : bytestream2_get_be64(gb)};
     return i.f64;
 }
 
 static unsigned tget(GetByteContext *gb, int type, int le)
 {
     switch (type) {
-    case TIFF_BYTE : return bytestream2_get_byteu(gb);
+    case TIFF_BYTE : return bytestream2_get_byte(gb);
     case TIFF_SHORT: return tget_short(gb, le);
     case TIFF_LONG : return tget_long(gb, le);
     default        : return UINT_MAX;
@@ -207,8 +208,9 @@
 {
     int i;
     char *ap, *ap0;
-    int component_len = 15 + strlen(sep);
+    int component_len;
     if (!sep) sep = ", ";
+    component_len = 15 + strlen(sep);
     ap = av_malloc(component_len * count);
     if (!ap)
         return NULL;
@@ -216,8 +218,10 @@
     ap[0] = '\0';
     for (i = 0; i < count; i++) {
         unsigned l = snprintf(ap, component_len, "%f%s", dp[i], sep);
-        if(l >= component_len)
+        if(l >= component_len) {
+            av_free(ap0);
             return NULL;
+        }
         ap += l;
     }
     ap0[strlen(ap0) - strlen(sep)] = '\0';
@@ -250,7 +254,7 @@
     int i;
     double *dp;
 
-    if (count >= INT_MAX / sizeof(int64_t))
+    if (count >= INT_MAX / sizeof(int64_t) || count <= 0)
         return AVERROR_INVALIDDATA;
     if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int64_t))
         return AVERROR_INVALIDDATA;
@@ -276,7 +280,7 @@
     int i;
     int16_t *sp;
 
-    if (count >= INT_MAX / sizeof(int16_t))
+    if (count >= INT_MAX / sizeof(int16_t) || count <= 0)
         return AVERROR_INVALIDDATA;
     if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int16_t))
         return AVERROR_INVALIDDATA;
@@ -332,7 +336,7 @@
     z_stream zstream = { 0 };
     int zret;
 
-    zstream.next_in = src;
+    zstream.next_in = (uint8_t *)src;
     zstream.avail_in = size;
     zstream.next_out = dst;
     zstream.avail_out = *len;
@@ -417,7 +421,7 @@
         }
         src = zbuf;
         for (line = 0; line < lines; line++) {
-            if(s->bpp < 8 && s->avctx->pix_fmt == PIX_FMT_PAL8){
+            if(s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8){
                 horizontal_fill(s->bpp, dst, 1, src, 0, width, 0);
             }else{
                 memcpy(dst, src, width);
@@ -456,7 +460,7 @@
             memcpy(src2, src, size);
         } else {
             for (i = 0; i < size; i++)
-                src2[i] = av_reverse[src[i]];
+                src2[i] = ff_reverse[src[i]];
         }
         memset(src2 + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
         switch (s->compr) {
@@ -467,7 +471,7 @@
                                   s->compr, s->fax_opts);
             break;
         }
-        if (s->bpp < 8 && s->avctx->pix_fmt == PIX_FMT_PAL8)
+        if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
             for (line = 0; line < lines; line++) {
                 horizontal_fill(s->bpp, dst, 1, dst, 0, width, 0);
                 dst += stride;
@@ -485,12 +489,12 @@
             if (ssrc + size - src < width)
                 return AVERROR_INVALIDDATA;
             if (!s->fill_order) {
-                horizontal_fill(s->bpp * (s->avctx->pix_fmt == PIX_FMT_PAL8),
+                horizontal_fill(s->bpp * (s->avctx->pix_fmt == AV_PIX_FMT_PAL8),
                                 dst, 1, src, 0, width, 0);
             } else {
                 int i;
                 for (i = 0; i < width; i++)
-                    dst[i] = av_reverse[src[i]];
+                    dst[i] = ff_reverse[src[i]];
             }
             src += width;
             break;
@@ -512,7 +516,7 @@
                         av_log(s->avctx, AV_LOG_ERROR, "Read went out of bounds\n");
                         return AVERROR_INVALIDDATA;
                     }
-                    horizontal_fill(s->bpp * (s->avctx->pix_fmt == PIX_FMT_PAL8),
+                    horizontal_fill(s->bpp * (s->avctx->pix_fmt == AV_PIX_FMT_PAL8),
                                     dst, 1, src, 0, code, pixels);
                     src += code;
                     pixels += code;
@@ -524,7 +528,7 @@
                         return -1;
                     }
                     c = *src++;
-                    horizontal_fill(s->bpp * (s->avctx->pix_fmt == PIX_FMT_PAL8),
+                    horizontal_fill(s->bpp * (s->avctx->pix_fmt == AV_PIX_FMT_PAL8),
                                     dst, 0, NULL, c, code, pixels);
                     pixels += code;
                 }
@@ -537,7 +541,7 @@
                        pixels, width);
                 return -1;
             }
-            if (s->bpp < 8 && s->avctx->pix_fmt == PIX_FMT_PAL8)
+            if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
                 horizontal_fill(s->bpp, dst, 1, dst, 0, width, 0);
             break;
         }
@@ -554,31 +558,31 @@
     switch (s->bpp * 10 + s->bppcount) {
     case 11:
         if (!s->palette_is_set) {
-            s->avctx->pix_fmt = PIX_FMT_MONOBLACK;
+            s->avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
             break;
         }
     case 21:
     case 41:
     case 81:
-        s->avctx->pix_fmt = PIX_FMT_PAL8;
+        s->avctx->pix_fmt = AV_PIX_FMT_PAL8;
         break;
     case 243:
-        s->avctx->pix_fmt = PIX_FMT_RGB24;
+        s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
         break;
     case 161:
-        s->avctx->pix_fmt = s->le ? PIX_FMT_GRAY16LE : PIX_FMT_GRAY16BE;
+        s->avctx->pix_fmt = s->le ? AV_PIX_FMT_GRAY16LE : AV_PIX_FMT_GRAY16BE;
         break;
     case 162:
-        s->avctx->pix_fmt = PIX_FMT_GRAY8A;
+        s->avctx->pix_fmt = AV_PIX_FMT_GRAY8A;
         break;
     case 324:
-        s->avctx->pix_fmt = PIX_FMT_RGBA;
+        s->avctx->pix_fmt = AV_PIX_FMT_RGBA;
         break;
     case 483:
-        s->avctx->pix_fmt = s->le ? PIX_FMT_RGB48LE : PIX_FMT_RGB48BE;
+        s->avctx->pix_fmt = s->le ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB48BE;
         break;
     case 644:
-        s->avctx->pix_fmt = s->le ? PIX_FMT_RGBA64LE : PIX_FMT_RGBA64BE;
+        s->avctx->pix_fmt = s->le ? AV_PIX_FMT_RGBA64LE : AV_PIX_FMT_RGBA64BE;
         break;
     default:
         av_log(s->avctx, AV_LOG_ERROR,
@@ -597,14 +601,14 @@
         av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         return ret;
     }
-    if (s->avctx->pix_fmt == PIX_FMT_PAL8) {
+    if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8) {
         if (s->palette_is_set) {
             memcpy(s->picture.data[1], s->palette, sizeof(s->palette));
         } else {
             /* make default grayscale pal */
             pal = (uint32_t *) s->picture.data[1];
             for (i = 0; i < 1<<s->bpp; i++)
-                pal[i] = 0xFF << 24 | i * 255 / ((1<<s->bpp) - 1) * 0x010101;
+                pal[i] = 0xFFU << 24 | i * 255 / ((1<<s->bpp) - 1) * 0x010101;
         }
     }
     return 0;
@@ -821,7 +825,7 @@
         for (k = 2; k >= 0; k--) {
             for (i = 0; i < count / 3; i++) {
                 if (k == 2)
-                    pal[i] = 0xff << 24;
+                    pal[i] = 0xFFU << 24;
                 j =  (tget(&s->gb, type, s->le) >> off) << (k * 8);
                 pal[i] |= j;
             }
@@ -1014,8 +1018,9 @@
     s->compr = TIFF_RAW;
     s->fill_order = 0;
     free_geotags(s);
-    /* free existing metadata */
-    av_dict_free(&s->picture.metadata);
+    /* metadata has been destroyed from lavc internals, that pointer is not
+     * valid anymore */
+    s->picture.metadata = NULL;
 
     // As TIFF 6.0 specification puts it "An arbitrary but carefully chosen number
     // that further identifies the file as a TIFF file"
@@ -1074,16 +1079,21 @@
     dst = p->data[0];
 
     if (s->stripsizesoff) {
-        if (s->stripsizesoff >= avpkt->size)
+        if (s->stripsizesoff >= (unsigned)avpkt->size)
             return AVERROR_INVALIDDATA;
         bytestream2_init(&stripsizes, avpkt->data + s->stripsizesoff, avpkt->size - s->stripsizesoff);
     }
     if (s->strippos) {
-        if (s->strippos >= avpkt->size)
+        if (s->strippos >= (unsigned)avpkt->size)
             return AVERROR_INVALIDDATA;
         bytestream2_init(&stripdata, avpkt->data + s->strippos, avpkt->size - s->strippos);
     }
 
+    if (s->rps <= 0) {
+        av_log(avctx, AV_LOG_ERROR, "rps %d invalid\n", s->rps);
+        return AVERROR_INVALIDDATA;
+    }
+
     for (i = 0; i < s->height; i += s->rps) {
         if (s->stripsizesoff)
             ssize = tget(&stripsizes, s->sstype, s->le);
@@ -1108,15 +1118,15 @@
         dst = p->data[0];
         soff = s->bpp >> 3;
         ssize = s->width * soff;
-        if (s->avctx->pix_fmt == PIX_FMT_RGB48LE ||
-            s->avctx->pix_fmt == PIX_FMT_RGBA64LE) {
+        if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48LE ||
+            s->avctx->pix_fmt == AV_PIX_FMT_RGBA64LE) {
             for (i = 0; i < s->height; i++) {
                 for (j = soff; j < ssize; j += 2)
                     AV_WL16(dst + j, AV_RL16(dst + j) + AV_RL16(dst + j - soff));
                 dst += stride;
             }
-        } else if (s->avctx->pix_fmt == PIX_FMT_RGB48BE ||
-                   s->avctx->pix_fmt == PIX_FMT_RGBA64BE) {
+        } else if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
+                   s->avctx->pix_fmt == AV_PIX_FMT_RGBA64BE) {
             for (i = 0; i < s->height; i++) {
                 for (j = soff; j < ssize; j += 2)
                     AV_WB16(dst + j, AV_RB16(dst + j) + AV_RB16(dst + j - soff));
@@ -1135,7 +1145,7 @@
         dst = s->picture.data[0];
         for (i = 0; i < s->height; i++) {
             for (j = 0; j < s->picture.linesize[0]; j++)
-                dst[j] = (s->avctx->pix_fmt == PIX_FMT_PAL8 ? (1<<s->bpp) - 1 : 255) - dst[j];
+                dst[j] = (s->avctx->pix_fmt == AV_PIX_FMT_PAL8 ? (1<<s->bpp) - 1 : 255) - dst[j];
             dst += s->picture.linesize[0];
         }
     }
@@ -1165,8 +1175,6 @@
     TiffContext *const s = avctx->priv_data;
 
     free_geotags(s);
-    if (avctx->coded_frame && avctx->coded_frame->metadata)
-        av_dict_free(&avctx->coded_frame->metadata);
 
     ff_lzw_decode_close(&s->lzw);
     if (s->picture.data[0])
diff --git a/libavcodec/tiffenc.c b/libavcodec/tiffenc.c
index 7d97523..61294b9 100644
--- a/libavcodec/tiffenc.c
+++ b/libavcodec/tiffenc.c
@@ -28,6 +28,7 @@
 #include "libavutil/imgutils.h"
 #include "libavutil/log.h"
 #include "libavutil/opt.h"
+#include "libavutil/pixdesc.h"
 
 #include "avcodec.h"
 #include "config.h"
@@ -136,11 +137,11 @@
     bytestream_put_le16(&entries_ptr, type);
     bytestream_put_le32(&entries_ptr, count);
 
-    if (type_sizes[type] * count <= 4) {
+    if (type_sizes[type] * (int64_t)count <= 4) {
         tnput(&entries_ptr, count, ptr_val, type, 0);
     } else {
         bytestream_put_le32(&entries_ptr, *s->buf - s->buf_start);
-        check_size(s, count * type_sizes2[type]);
+        check_size(s, count * (int64_t)type_sizes2[type]);
         tnput(s->buf, count, ptr_val, type, 0);
     }
 
@@ -238,6 +239,7 @@
 static int encode_frame(AVCodecContext * avctx, AVPacket *pkt,
                         const AVFrame *pict, int *got_packet)
 {
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
     TiffEncoderContext *s = avctx->priv_data;
     AVFrame *const p = &s->picture;
     int i;
@@ -259,39 +261,39 @@
     s->subsampling[1] = 1;
 
     avctx->bits_per_coded_sample =
-    s->bpp = av_get_bits_per_pixel(&av_pix_fmt_descriptors[avctx->pix_fmt]);
+    s->bpp = av_get_bits_per_pixel(desc);
+    s->bpp_tab_size = desc->nb_components;
 
     switch (avctx->pix_fmt) {
-    case PIX_FMT_RGBA64LE:
-    case PIX_FMT_RGBA:
+    case AV_PIX_FMT_RGBA64LE:
+    case AV_PIX_FMT_RGBA:
         alpha = 1;
-    case PIX_FMT_RGB48LE:
-    case PIX_FMT_RGB24:
+    case AV_PIX_FMT_RGB48LE:
+    case AV_PIX_FMT_RGB24:
         s->photometric_interpretation = 2;
         break;
-    case PIX_FMT_GRAY8:
+    case AV_PIX_FMT_GRAY8:
         avctx->bits_per_coded_sample = 0x28;
-    case PIX_FMT_GRAY8A:
-        alpha = avctx->pix_fmt == PIX_FMT_GRAY8A;
-    case PIX_FMT_GRAY16LE:
-    case PIX_FMT_MONOBLACK:
+    case AV_PIX_FMT_GRAY8A:
+        alpha = avctx->pix_fmt == AV_PIX_FMT_GRAY8A;
+    case AV_PIX_FMT_GRAY16LE:
+    case AV_PIX_FMT_MONOBLACK:
         s->photometric_interpretation = 1;
         break;
-    case PIX_FMT_PAL8:
+    case AV_PIX_FMT_PAL8:
         s->photometric_interpretation = 3;
         break;
-    case PIX_FMT_MONOWHITE:
+    case AV_PIX_FMT_MONOWHITE:
         s->photometric_interpretation = 0;
         break;
-    case PIX_FMT_YUV420P:
-    case PIX_FMT_YUV422P:
-    case PIX_FMT_YUV440P:
-    case PIX_FMT_YUV444P:
-    case PIX_FMT_YUV410P:
-    case PIX_FMT_YUV411P:
+    case AV_PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUV422P:
+    case AV_PIX_FMT_YUV440P:
+    case AV_PIX_FMT_YUV444P:
+    case AV_PIX_FMT_YUV410P:
+    case AV_PIX_FMT_YUV411P:
         s->photometric_interpretation = 6;
-        avcodec_get_chroma_sub_sample(avctx->pix_fmt,
-                &shift_h, &shift_v);
+        avcodec_get_chroma_sub_sample(avctx->pix_fmt, &shift_h, &shift_v);
         s->subsampling[0] = 1 << shift_h;
         s->subsampling[1] = 1 << shift_v;
         is_yuv = 1;
@@ -302,9 +304,8 @@
         return -1;
     }
 
-    s->bpp_tab_size = av_pix_fmt_descriptors[avctx->pix_fmt].nb_components;
     for (i = 0; i < s->bpp_tab_size; i++)
-        bpp_tab[i] = av_pix_fmt_descriptors[avctx->pix_fmt].comp[i].depth_minus1 + 1;
+        bpp_tab[i] = desc->comp[i].depth_minus1 + 1;
 
     if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE || s->compr == TIFF_LZW)
         //best choose for DEFLATE
@@ -346,6 +347,7 @@
     if (is_yuv){
         av_fast_padded_malloc(&s->yuv_line, &s->yuv_line_size, bytes_per_row);
         if (s->yuv_line == NULL){
+            av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n");
             ret = AVERROR(ENOMEM);
             goto fail;
         }
@@ -359,6 +361,10 @@
 
         zlen = bytes_per_row * s->rps;
         zbuf = av_malloc(zlen);
+        if (!zbuf) {
+            ret = AVERROR(ENOMEM);
+            goto fail;
+        }
         s->strip_offsets[0] = ptr - pkt->data;
         zn = 0;
         for (j = 0; j < s->rps; j++) {
@@ -383,8 +389,13 @@
     } else
 #endif
     {
-        if(s->compr == TIFF_LZW)
+        if (s->compr == TIFF_LZW) {
             s->lzws = av_malloc(ff_lzw_encode_state_size);
+            if (!s->lzws) {
+                ret = AVERROR(ENOMEM);
+                goto fail;
+            }
+        }
         for (i = 0; i < s->height; i++) {
             if (s->strip_sizes[i / s->rps] == 0) {
                 if(s->compr == TIFF_LZW){
@@ -443,7 +454,7 @@
     add_entry(s, TIFF_SOFTWARE_NAME,     TIFF_STRING,
               strlen(LIBAVCODEC_IDENT) + 1, LIBAVCODEC_IDENT);
 
-    if (avctx->pix_fmt == PIX_FMT_PAL8) {
+    if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
         uint16_t pal[256 * 3];
         for (i = 0; i < 256; i++) {
             uint32_t rgb = *(uint32_t *) (p->data[1] + i * 4);
@@ -459,6 +470,8 @@
         /** according to CCIR Recommendation 601.1 */
         uint32_t refbw[12] = {15, 1, 235, 1, 128, 1, 240, 1, 128, 1, 240, 1};
         add_entry(s, TIFF_YCBCR_SUBSAMPLING, TIFF_SHORT,    2, s->subsampling);
+        if (avctx->chroma_sample_location == AVCHROMA_LOC_TOPLEFT)
+            add_entry1(s, TIFF_YCBCR_POSITIONING, TIFF_SHORT, 2);
         add_entry(s, TIFF_REFERENCE_BW,      TIFF_RATIONAL, 6, refbw);
     }
     bytestream_put_le32(&offset, ptr - pkt->data);    // write offset to dir
@@ -519,14 +532,14 @@
     .init           = encode_init,
     .encode2        = encode_frame,
     .close          = encode_close,
-    .pix_fmts       = (const enum PixelFormat[]) {
-        PIX_FMT_RGB24, PIX_FMT_PAL8, PIX_FMT_GRAY8,
-        PIX_FMT_GRAY8A, PIX_FMT_GRAY16LE,
-        PIX_FMT_MONOBLACK, PIX_FMT_MONOWHITE,
-        PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV440P, PIX_FMT_YUV444P,
-        PIX_FMT_YUV410P, PIX_FMT_YUV411P, PIX_FMT_RGB48LE,
-        PIX_FMT_RGBA, PIX_FMT_RGBA64LE,
-        PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]) {
+        AV_PIX_FMT_RGB24, AV_PIX_FMT_PAL8, AV_PIX_FMT_GRAY8,
+        AV_PIX_FMT_GRAY8A, AV_PIX_FMT_GRAY16LE,
+        AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_MONOWHITE,
+        AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P,
+        AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_RGB48LE,
+        AV_PIX_FMT_RGBA, AV_PIX_FMT_RGBA64LE,
+        AV_PIX_FMT_NONE
     },
     .long_name      = NULL_IF_CONFIG_SMALL("TIFF image"),
     .priv_class     = &tiffenc_class,
diff --git a/libavcodec/tmv.c b/libavcodec/tmv.c
index e2397ce..a0b3f36 100644
--- a/libavcodec/tmv.c
+++ b/libavcodec/tmv.c
@@ -30,6 +30,7 @@
 
 #include "avcodec.h"
 #include "libavutil/internal.h"
+#include "libavutil/xga_font_data.h"
 
 #include "cga_data.h"
 
@@ -75,7 +76,7 @@
             bg = *src  >> 4;
             fg = *src++ & 0xF;
             ff_draw_pc_font(dst + x * 8, tmv->pic.linesize[0],
-                            ff_cga_font, 8, c, fg, bg);
+                            avpriv_cga_font, 8, c, fg, bg);
         }
         dst += tmv->pic.linesize[0] * 8;
     }
@@ -88,7 +89,7 @@
 static av_cold int tmv_decode_init(AVCodecContext *avctx)
 {
     TMVContext *tmv = avctx->priv_data;
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
     avcodec_get_frame_defaults(&tmv->pic);
     return 0;
 }
diff --git a/libavcodec/truemotion1.c b/libavcodec/truemotion1.c
index fd4a355..b46366b 100644
--- a/libavcodec/truemotion1.c
+++ b/libavcodec/truemotion1.c
@@ -390,10 +390,10 @@
     }
 
     if (compression_types[header.compression].algorithm == ALGO_RGB24H) {
-        new_pix_fmt = PIX_FMT_RGB32;
+        new_pix_fmt = AV_PIX_FMT_RGB32;
         width_shift = 1;
     } else
-        new_pix_fmt = PIX_FMT_RGB555; // RGB565 is supported as well
+        new_pix_fmt = AV_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)
@@ -419,7 +419,7 @@
         if (compression_types[header.compression].algorithm == ALGO_RGB24H)
             gen_vector_table24(s, sel_vector_table);
         else
-        if (s->avctx->pix_fmt == PIX_FMT_RGB555)
+        if (s->avctx->pix_fmt == AV_PIX_FMT_RGB555)
             gen_vector_table15(s, sel_vector_table);
         else
             gen_vector_table16(s, sel_vector_table);
@@ -464,9 +464,9 @@
 
     // FIXME: it may change ?
 //    if (avctx->bits_per_sample == 24)
-//        avctx->pix_fmt = PIX_FMT_RGB24;
+//        avctx->pix_fmt = AV_PIX_FMT_RGB24;
 //    else
-//        avctx->pix_fmt = PIX_FMT_RGB555;
+//        avctx->pix_fmt = AV_PIX_FMT_RGB555;
 
     avcodec_get_frame_defaults(&s->frame);
     s->frame.data[0] = NULL;
diff --git a/libavcodec/truemotion2.c b/libavcodec/truemotion2.c
index e9fcf4d..f1e24b7 100644
--- a/libavcodec/truemotion2.c
+++ b/libavcodec/truemotion2.c
@@ -200,15 +200,14 @@
 {
     int val;
     val = get_vlc2(gb, code->vlc.table, code->bits, 1);
+    if(val<0)
+        return -1;
     return code->recode[val];
 }
 
 static inline int tm2_read_header(TM2Context *ctx, const uint8_t *buf)
 {
     uint32_t magic;
-    const uint8_t *obuf;
-
-    obuf = buf;
 
     magic = AV_RL32(buf);
     buf += 4;
@@ -222,8 +221,6 @@
         av_log (ctx->avctx, AV_LOG_ERROR, "Not a TM2 header: 0x%08X\n", magic);
         return -1;
     }
-
-    return buf - obuf;
 }
 
 static int tm2_read_deltas(TM2Context *ctx, int stream_id) {
@@ -273,8 +270,8 @@
         return 4;
 
     if (len >= INT_MAX/4-1 || len < 0 || skip > buf_size) {
-        av_log(ctx->avctx, AV_LOG_ERROR, "Error, invalid stream size.\n");
-        return -1;
+        av_log(ctx->avctx, AV_LOG_ERROR, "invalid stream size\n");
+        return AVERROR_INVALIDDATA;
     }
 
     toks = bytestream2_get_be32(&gb);
@@ -286,10 +283,10 @@
         if(len > 0) {
             pos = bytestream2_tell(&gb);
             if (skip <= pos)
-                return -1;
+                return AVERROR_INVALIDDATA;
             init_get_bits(&ctx->gb, buf + pos, (skip - pos) * 8);
             if(tm2_read_deltas(ctx, stream_id) == -1)
-                return -1;
+                return AVERROR_INVALIDDATA;
             bytestream2_skip(&gb, ((get_bits_count(&ctx->gb) + 31) >> 5) << 2);
         }
     }
@@ -303,10 +300,10 @@
 
     pos = bytestream2_tell(&gb);
     if (skip <= pos)
-        return -1;
+        return AVERROR_INVALIDDATA;
     init_get_bits(&ctx->gb, buf + pos, (skip - pos) * 8);
     if(tm2_build_huff_table(ctx, &codes) == -1)
-        return -1;
+        return AVERROR_INVALIDDATA;
     bytestream2_skip(&gb, ((get_bits_count(&ctx->gb) + 31) >> 5) << 2);
 
     toks >>= 1;
@@ -314,7 +311,7 @@
     if((toks < 0) || (toks > 0xFFFFFF)){
         av_log(ctx->avctx, AV_LOG_ERROR, "Incorrect number of tokens: %i\n", toks);
         tm2_free_codes(&codes);
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
     ctx->tokens[stream_id] = av_realloc(ctx->tokens[stream_id], toks * sizeof(int));
     ctx->tok_lens[stream_id] = toks;
@@ -322,15 +319,15 @@
     if(len > 0) {
         pos = bytestream2_tell(&gb);
         if (skip <= pos)
-            return -1;
+            return AVERROR_INVALIDDATA;
         init_get_bits(&ctx->gb, buf + pos, (skip - pos) * 8);
         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;
+                return AVERROR_INVALIDDATA;
             }
             ctx->tokens[stream_id][i] = tm2_get_token(&ctx->gb, &codes);
-            if (stream_id <= TM2_MOT && ctx->tokens[stream_id][i] >= TM2_DELTAS) {
+            if (stream_id <= TM2_MOT && ctx->tokens[stream_id][i] >= TM2_DELTAS || ctx->tokens[stream_id][i]<0) {
                 av_log(ctx->avctx, AV_LOG_ERROR, "Invalid delta token index %d for type %d, n=%d\n",
                        ctx->tokens[stream_id][i], stream_id, i);
                 return AVERROR_INVALIDDATA;
@@ -668,7 +665,7 @@
     my = av_clip(my, -(by * 4 + 4), ctx->avctx->height - by * 4);
 
     if (4*bx+mx<0 || 4*by+my<0 || 4*bx+mx+4 > ctx->avctx->width || 4*by+my+4 > ctx->avctx->height) {
-        av_log(0,0, "MV out of picture\n");
+        av_log(ctx->avctx, AV_LOG_ERROR, "MV out of picture\n");
         return;
     }
 
@@ -836,25 +833,25 @@
     int buf_size = avpkt->size & ~3;
     TM2Context * const l = avctx->priv_data;
     AVFrame * const p = &l->pic;
-    int i, skip, t;
+    int i, ret, skip, t;
 
     av_fast_padded_malloc(&l->buffer, &l->buffer_size, buf_size);
     if(!l->buffer){
         av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer\n");
-        return -1;
+        return AVERROR(ENOMEM);
     }
     p->reference = 3;
     p->buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;
-    if(avctx->reget_buffer(avctx, p) < 0){
+    if((ret = avctx->reget_buffer(avctx, p)) < 0){
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
+        return ret;
     }
 
     l->dsp.bswap_buf((uint32_t*)l->buffer, (const uint32_t*)buf, buf_size >> 2);
     skip = tm2_read_header(l, l->buffer);
 
     if(skip == -1){
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     for(i = 0; i < TM2_NUM_STREAMS; i++){
@@ -888,12 +885,12 @@
 
     if((avctx->width & 3) || (avctx->height & 3)){
         av_log(avctx, AV_LOG_ERROR, "Width and height must be multiple of 4\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     l->avctx = avctx;
     l->pic.data[0]=NULL;
-    avctx->pix_fmt = PIX_FMT_BGR24;
+    avctx->pix_fmt = AV_PIX_FMT_BGR24;
     avcodec_get_frame_defaults(&l->pic);
 
     ff_dsputil_init(&l->dsp, avctx);
diff --git a/libavcodec/truespeech.c b/libavcodec/truespeech.c
index 6a1e439..d523bdd 100644
--- a/libavcodec/truespeech.c
+++ b/libavcodec/truespeech.c
@@ -19,6 +19,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "avcodec.h"
 #include "dsputil.h"
@@ -66,7 +67,8 @@
         return AVERROR(EINVAL);
     }
 
-    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    avctx->channel_layout = AV_CH_LAYOUT_MONO;
+    avctx->sample_fmt     = AV_SAMPLE_FMT_S16;
 
     ff_dsputil_init(&c->dsp, avctx);
 
diff --git a/libavcodec/tscc.c b/libavcodec/tscc.c
index 954e372..1ba3bb9 100644
--- a/libavcodec/tscc.c
+++ b/libavcodec/tscc.c
@@ -91,7 +91,7 @@
         av_log(avctx, AV_LOG_ERROR, "Inflate reset error: %d\n", zret);
         return AVERROR(EINVAL);
     }
-    c->zstream.next_in = encoded;
+    c->zstream.next_in = (uint8_t*)encoded;
     c->zstream.avail_in = len;
     c->zstream.next_out = c->decomp_buf;
     c->zstream.avail_out = c->decomp_size;
@@ -110,7 +110,7 @@
     }
 
     /* make the palette available on the way out */
-    if (c->avctx->pix_fmt == PIX_FMT_PAL8) {
+    if (c->avctx->pix_fmt == AV_PIX_FMT_PAL8) {
         const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);
 
         if (pal) {
@@ -147,12 +147,12 @@
     // Needed if zlib unused or init aborted before inflateInit
     memset(&c->zstream, 0, sizeof(z_stream));
     switch(avctx->bits_per_coded_sample){
-    case  8: avctx->pix_fmt = PIX_FMT_PAL8; break;
-    case 16: avctx->pix_fmt = PIX_FMT_RGB555; break;
+    case  8: avctx->pix_fmt = AV_PIX_FMT_PAL8; break;
+    case 16: avctx->pix_fmt = AV_PIX_FMT_RGB555; break;
     case 24:
-             avctx->pix_fmt = PIX_FMT_BGR24;
+             avctx->pix_fmt = AV_PIX_FMT_BGR24;
              break;
-    case 32: avctx->pix_fmt = PIX_FMT_RGB32; break;
+    case 32: avctx->pix_fmt = AV_PIX_FMT_RGB32; break;
     default: av_log(avctx, AV_LOG_ERROR, "Camtasia error: unknown depth %i bpp\n", avctx->bits_per_coded_sample);
              return AVERROR_PATCHWELCOME;
     }
diff --git a/libavcodec/tscc2.c b/libavcodec/tscc2.c
index d1dd8fd..8692819 100644
--- a/libavcodec/tscc2.c
+++ b/libavcodec/tscc2.c
@@ -173,7 +173,7 @@
                 if (ac == 0x1000)
                     ac = get_bits(gb, 12);
                 bpos += ac & 0xF;
-                if (bpos >= 64)
+                if (bpos >= 16)
                     return AVERROR_INVALIDDATA;
                 val = sign_extend(ac >> 4, 8);
                 c->block[tscc2_zigzag[bpos++]] = val;
@@ -336,7 +336,7 @@
 
     c->avctx = avctx;
 
-    avctx->pix_fmt = PIX_FMT_YUV444P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV444P;
 
     if ((ret = init_vlcs(c)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "Cannot initialise VLCs\n");
diff --git a/libavcodec/tta.c b/libavcodec/tta.c
index ce41cb3..b0e538f 100644
--- a/libavcodec/tta.c
+++ b/libavcodec/tta.c
@@ -180,7 +180,7 @@
 
     // 30bytes includes a seektable with one frame
     if (avctx->extradata_size < 30)
-        return -1;
+        return AVERROR_INVALIDDATA;
 
     init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8);
     if (show_bits_long(&s->gb, 32) == AV_RL32("TTA1"))
@@ -196,17 +196,17 @@
         s->format = get_bits(&s->gb, 16);
         if (s->format > 2) {
             av_log(s->avctx, AV_LOG_ERROR, "Invalid format\n");
-            return -1;
+            return AVERROR_INVALIDDATA;
         }
         if (s->format == FORMAT_ENCRYPTED) {
             av_log_missing_feature(s->avctx, "Encrypted TTA", 0);
-            return AVERROR(EINVAL);
+            return AVERROR_PATCHWELCOME;
         }
         avctx->channels = s->channels = get_bits(&s->gb, 16);
         if (s->channels > 1 && s->channels < 9)
             avctx->channel_layout = tta_channel_layouts[s->channels-2];
-        avctx->bits_per_coded_sample = get_bits(&s->gb, 16);
-        s->bps = (avctx->bits_per_coded_sample + 7) / 8;
+        avctx->bits_per_raw_sample = get_bits(&s->gb, 16);
+        s->bps = (avctx->bits_per_raw_sample + 7) / 8;
         avctx->sample_rate = get_bits_long(&s->gb, 32);
         s->data_length = get_bits_long(&s->gb, 32);
         skip_bits_long(&s->gb, 32); // CRC32 of header
@@ -223,11 +223,9 @@
         case 1: avctx->sample_fmt = AV_SAMPLE_FMT_U8; break;
         case 2:
             avctx->sample_fmt = AV_SAMPLE_FMT_S16;
-            avctx->bits_per_raw_sample = 16;
             break;
         case 3:
             avctx->sample_fmt = AV_SAMPLE_FMT_S32;
-            avctx->bits_per_raw_sample = 24;
             break;
         //case 4: avctx->sample_fmt = AV_SAMPLE_FMT_S32; break;
         default:
@@ -268,7 +266,7 @@
 
         if(s->frame_length >= UINT_MAX / (s->channels * sizeof(int32_t))){
             av_log(avctx, AV_LOG_ERROR, "frame_length too large\n");
-            return -1;
+            return AVERROR_INVALIDDATA;
         }
 
         if (s->bps < 3) {
@@ -284,7 +282,7 @@
         }
     } else {
         av_log(avctx, AV_LOG_ERROR, "Wrong extradata present\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     avcodec_get_frame_defaults(&s->frame);
diff --git a/libavcodec/twinvq.c b/libavcodec/twinvq.c
index 070f498..d7a3726 100644
--- a/libavcodec/twinvq.c
+++ b/libavcodec/twinvq.c
@@ -19,6 +19,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/float_dsp.h"
 #include "avcodec.h"
 #include "get_bits.h"
@@ -666,7 +667,7 @@
 }
 
 static void imdct_output(TwinContext *tctx, enum FrameType ftype, int wtype,
-                         float *out)
+                         float **out)
 {
     const ModeTab *mtab = tctx->mtab;
     int size1, size2;
@@ -685,24 +686,15 @@
 
     size2 = tctx->last_block_pos[0];
     size1 = mtab->size - size2;
+
+    memcpy(&out[0][0    ], prev_buf,         size1 * sizeof(out[0][0]));
+    memcpy(&out[0][size1], tctx->curr_frame, size2 * sizeof(out[0][0]));
+
     if (tctx->avctx->channels == 2) {
-        tctx->dsp.butterflies_float_interleave(out, prev_buf,
-                                               &prev_buf[2*mtab->size],
-                                               size1);
-
-        out += 2 * size1;
-
-        tctx->dsp.butterflies_float_interleave(out, tctx->curr_frame,
-                                               &tctx->curr_frame[2*mtab->size],
-                                               size2);
-    } else {
-        memcpy(out, prev_buf, size1 * sizeof(*out));
-
-        out += size1;
-
-        memcpy(out, tctx->curr_frame, size2 * sizeof(*out));
+        memcpy(&out[1][0],     &prev_buf[2*mtab->size],         size1 * sizeof(out[1][0]));
+        memcpy(&out[1][size1], &tctx->curr_frame[2*mtab->size], size2 * sizeof(out[1][0]));
+        tctx->dsp.butterflies_float(out[0], out[1], mtab->size);
     }
-
 }
 
 static void dec_bark_env(TwinContext *tctx, const uint8_t *in, int use_hist,
@@ -825,7 +817,7 @@
     TwinContext *tctx = avctx->priv_data;
     GetBitContext gb;
     const ModeTab *mtab = tctx->mtab;
-    float *out = NULL;
+    float **out = NULL;
     enum FrameType ftype;
     int window_type, ret;
     static const enum FrameType wtype_to_ftype_table[] = {
@@ -846,7 +838,7 @@
             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
             return ret;
         }
-        out = (float *)tctx->frame.data[0];
+        out = (float **)tctx->frame.extended_data;
     }
 
     init_get_bits(&gb, buf, buf_size * 8);
@@ -1119,7 +1111,7 @@
     int isampf, ibps;
 
     tctx->avctx       = avctx;
-    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
+    avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
 
     if (!avctx->extradata || avctx->extradata_size < 12) {
         av_log(avctx, AV_LOG_ERROR, "Missing or incomplete extradata\n");
@@ -1128,6 +1120,11 @@
     avctx->channels = AV_RB32(avctx->extradata    ) + 1;
     avctx->bit_rate = AV_RB32(avctx->extradata + 4) * 1000;
     isampf          = AV_RB32(avctx->extradata + 8);
+
+    if (isampf < 8 || isampf > 44) {
+        av_log(avctx, AV_LOG_ERROR, "Unsupported sample rate\n");
+        return AVERROR_INVALIDDATA;
+    }
     switch (isampf) {
     case 44: avctx->sample_rate = 44100;         break;
     case 22: avctx->sample_rate = 22050;         break;
@@ -1135,13 +1132,21 @@
     default: avctx->sample_rate = isampf * 1000; break;
     }
 
-    if (avctx->channels > CHANNELS_MAX) {
+    if (avctx->channels <= 0 || avctx->channels > CHANNELS_MAX) {
         av_log(avctx, AV_LOG_ERROR, "Unsupported number of channels: %i\n",
                avctx->channels);
         return -1;
     }
+    avctx->channel_layout = avctx->channels == 1 ? AV_CH_LAYOUT_MONO :
+                                                   AV_CH_LAYOUT_STEREO;
+
     ibps = avctx->bit_rate / (1000 * avctx->channels);
 
+    if (ibps > 255U) {
+        av_log(avctx, AV_LOG_ERROR, "unsupported per channel bitrate %dkbps\n", ibps);
+        return AVERROR_INVALIDDATA;
+    }
+
     switch ((isampf << 8) +  ibps) {
     case (8 <<8) +  8: tctx->mtab = &mode_08_08; break;
     case (11<<8) +  8: tctx->mtab = &mode_11_08; break;
@@ -1184,4 +1189,6 @@
     .decode         = twin_decode_frame,
     .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("VQF TwinVQ"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
+                                                      AV_SAMPLE_FMT_NONE },
 };
diff --git a/libavcodec/txd.c b/libavcodec/txd.c
index 523e1e6..a526035 100644
--- a/libavcodec/txd.c
+++ b/libavcodec/txd.c
@@ -25,7 +25,6 @@
 #include "libavutil/imgutils.h"
 #include "bytestream.h"
 #include "avcodec.h"
-#include "bytestream.h"
 #include "s3tc.h"
 
 typedef struct TXDContext {
@@ -69,9 +68,9 @@
     }
 
     if (depth == 8) {
-        avctx->pix_fmt = PIX_FMT_PAL8;
+        avctx->pix_fmt = AV_PIX_FMT_PAL8;
     } else if (depth == 16 || depth == 32) {
-        avctx->pix_fmt = PIX_FMT_RGB32;
+        avctx->pix_fmt = AV_PIX_FMT_RGB32;
     } else {
         av_log(avctx, AV_LOG_ERROR, "depth of %i is unsupported\n", depth);
         return -1;
diff --git a/libavcodec/ulti.c b/libavcodec/ulti.c
index 6e2da8b..f6d6418 100644
--- a/libavcodec/ulti.c
+++ b/libavcodec/ulti.c
@@ -49,7 +49,7 @@
     s->width = avctx->width;
     s->height = avctx->height;
     s->blocks = (s->width / 8) * (s->height / 8);
-    avctx->pix_fmt = PIX_FMT_YUV410P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV410P;
     avctx->coded_frame = &s->frame;
     avctx->coded_frame = (AVFrame*) &s->frame;
     s->ulti_codebook = ulti_codebook;
diff --git a/libavcodec/utils.c b/libavcodec/utils.c
index 1617edd..48ef679 100644
--- a/libavcodec/utils.c
+++ b/libavcodec/utils.c
@@ -27,10 +27,10 @@
 
 #include "libavutil/avassert.h"
 #include "libavutil/avstring.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/crc.h"
 #include "libavutil/mathematics.h"
 #include "libavutil/pixdesc.h"
-#include "libavutil/audioconvert.h"
 #include "libavutil/imgutils.h"
 #include "libavutil/samplefmt.h"
 #include "libavutil/dict.h"
@@ -40,7 +40,6 @@
 #include "libavutil/opt.h"
 #include "thread.h"
 #include "frame_thread_encoder.h"
-#include "audioconvert.h"
 #include "internal.h"
 #include "bytestream.h"
 #include <stdlib.h>
@@ -49,7 +48,7 @@
 #include <float.h>
 
 static int volatile entangled_thread_counter = 0;
-static int (*ff_lockmgr_cb)(void **mutex, enum AVLockOp op) = NULL;
+static int (*ff_lockmgr_cb)(void **mutex, enum AVLockOp op);
 static void *codec_mutex;
 static void *avformat_mutex;
 
@@ -184,82 +183,84 @@
     int h_align = 1;
 
     switch (s->pix_fmt) {
-    case PIX_FMT_YUV420P:
-    case PIX_FMT_YUYV422:
-    case PIX_FMT_UYVY422:
-    case PIX_FMT_YUV422P:
-    case PIX_FMT_YUV440P:
-    case PIX_FMT_YUV444P:
-    case PIX_FMT_GBRP:
-    case PIX_FMT_GRAY8:
-    case PIX_FMT_GRAY16BE:
-    case PIX_FMT_GRAY16LE:
-    case PIX_FMT_YUVJ420P:
-    case PIX_FMT_YUVJ422P:
-    case PIX_FMT_YUVJ440P:
-    case PIX_FMT_YUVJ444P:
-    case PIX_FMT_YUVA420P:
-    case PIX_FMT_YUVA422P:
-    case PIX_FMT_YUVA444P:
-    case PIX_FMT_YUV420P9LE:
-    case PIX_FMT_YUV420P9BE:
-    case PIX_FMT_YUV420P10LE:
-    case PIX_FMT_YUV420P10BE:
-    case PIX_FMT_YUV420P12LE:
-    case PIX_FMT_YUV420P12BE:
-    case PIX_FMT_YUV420P14LE:
-    case PIX_FMT_YUV420P14BE:
-    case PIX_FMT_YUV422P9LE:
-    case PIX_FMT_YUV422P9BE:
-    case PIX_FMT_YUV422P10LE:
-    case PIX_FMT_YUV422P10BE:
-    case PIX_FMT_YUV422P12LE:
-    case PIX_FMT_YUV422P12BE:
-    case PIX_FMT_YUV422P14LE:
-    case PIX_FMT_YUV422P14BE:
-    case PIX_FMT_YUV444P9LE:
-    case PIX_FMT_YUV444P9BE:
-    case PIX_FMT_YUV444P10LE:
-    case PIX_FMT_YUV444P10BE:
-    case PIX_FMT_YUV444P12LE:
-    case PIX_FMT_YUV444P12BE:
-    case PIX_FMT_YUV444P14LE:
-    case PIX_FMT_YUV444P14BE:
-    case PIX_FMT_GBRP9LE:
-    case PIX_FMT_GBRP9BE:
-    case PIX_FMT_GBRP10LE:
-    case PIX_FMT_GBRP10BE:
-    case PIX_FMT_GBRP12LE:
-    case PIX_FMT_GBRP12BE:
-    case PIX_FMT_GBRP14LE:
-    case PIX_FMT_GBRP14BE:
+    case AV_PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUYV422:
+    case AV_PIX_FMT_UYVY422:
+    case AV_PIX_FMT_YUV422P:
+    case AV_PIX_FMT_YUV440P:
+    case AV_PIX_FMT_YUV444P:
+    case AV_PIX_FMT_GBRP:
+    case AV_PIX_FMT_GRAY8:
+    case AV_PIX_FMT_GRAY16BE:
+    case AV_PIX_FMT_GRAY16LE:
+    case AV_PIX_FMT_YUVJ420P:
+    case AV_PIX_FMT_YUVJ422P:
+    case AV_PIX_FMT_YUVJ440P:
+    case AV_PIX_FMT_YUVJ444P:
+    case AV_PIX_FMT_YUVA420P:
+    case AV_PIX_FMT_YUVA422P:
+    case AV_PIX_FMT_YUVA444P:
+    case AV_PIX_FMT_YUV420P9LE:
+    case AV_PIX_FMT_YUV420P9BE:
+    case AV_PIX_FMT_YUV420P10LE:
+    case AV_PIX_FMT_YUV420P10BE:
+    case AV_PIX_FMT_YUV420P12LE:
+    case AV_PIX_FMT_YUV420P12BE:
+    case AV_PIX_FMT_YUV420P14LE:
+    case AV_PIX_FMT_YUV420P14BE:
+    case AV_PIX_FMT_YUV422P9LE:
+    case AV_PIX_FMT_YUV422P9BE:
+    case AV_PIX_FMT_YUV422P10LE:
+    case AV_PIX_FMT_YUV422P10BE:
+    case AV_PIX_FMT_YUV422P12LE:
+    case AV_PIX_FMT_YUV422P12BE:
+    case AV_PIX_FMT_YUV422P14LE:
+    case AV_PIX_FMT_YUV422P14BE:
+    case AV_PIX_FMT_YUV444P9LE:
+    case AV_PIX_FMT_YUV444P9BE:
+    case AV_PIX_FMT_YUV444P10LE:
+    case AV_PIX_FMT_YUV444P10BE:
+    case AV_PIX_FMT_YUV444P12LE:
+    case AV_PIX_FMT_YUV444P12BE:
+    case AV_PIX_FMT_YUV444P14LE:
+    case AV_PIX_FMT_YUV444P14BE:
+    case AV_PIX_FMT_GBRP9LE:
+    case AV_PIX_FMT_GBRP9BE:
+    case AV_PIX_FMT_GBRP10LE:
+    case AV_PIX_FMT_GBRP10BE:
+    case AV_PIX_FMT_GBRP12LE:
+    case AV_PIX_FMT_GBRP12BE:
+    case AV_PIX_FMT_GBRP14LE:
+    case AV_PIX_FMT_GBRP14BE:
         w_align = 16; //FIXME assume 16 pixel per macroblock
         h_align = 16 * 2; // interlaced needs 2 macroblocks height
         break;
-    case PIX_FMT_YUV411P:
-    case PIX_FMT_UYYVYY411:
+    case AV_PIX_FMT_YUV411P:
+    case AV_PIX_FMT_UYYVYY411:
         w_align = 32;
         h_align = 8;
         break;
-    case PIX_FMT_YUV410P:
+    case AV_PIX_FMT_YUV410P:
         if (s->codec_id == AV_CODEC_ID_SVQ1) {
             w_align = 64;
             h_align = 64;
         }
-    case PIX_FMT_RGB555:
+        break;
+    case AV_PIX_FMT_RGB555:
         if (s->codec_id == AV_CODEC_ID_RPZA) {
             w_align = 4;
             h_align = 4;
         }
-    case PIX_FMT_PAL8:
-    case PIX_FMT_BGR8:
-    case PIX_FMT_RGB8:
+        break;
+    case AV_PIX_FMT_PAL8:
+    case AV_PIX_FMT_BGR8:
+    case AV_PIX_FMT_RGB8:
         if (s->codec_id == AV_CODEC_ID_SMC) {
             w_align = 4;
             h_align = 4;
         }
         break;
-    case PIX_FMT_BGR24:
+    case AV_PIX_FMT_BGR24:
         if ((s->codec_id == AV_CODEC_ID_MSZH) ||
             (s->codec_id == AV_CODEC_ID_ZLIB)) {
             w_align = 4;
@@ -289,7 +290,8 @@
 
 void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height)
 {
-    int chroma_shift = av_pix_fmt_descriptors[s->pix_fmt].log2_chroma_w;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
+    int chroma_shift = desc->log2_chroma_w;
     int linesize_align[AV_NUM_DATA_POINTERS];
     int align;
 
@@ -393,7 +395,7 @@
         if (buf->extended_data[0] && buf_size > buf->audio_data_size) {
             av_free(buf->extended_data[0]);
             if (buf->extended_data != buf->data)
-                av_freep(&buf->extended_data);
+                av_free(buf->extended_data);
             buf->extended_data = NULL;
             buf->data[0]       = NULL;
         }
@@ -416,7 +418,7 @@
         }
         if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
                                             avctx->sample_fmt, buf->data[0],
-                                            buf->audio_data_size, 0)))
+                                            buf->audio_data_size, 0)) < 0)
             return ret;
 
         if (frame->extended_data == frame->data)
@@ -486,9 +488,11 @@
         int unaligned;
         AVPicture picture;
         int stride_align[AV_NUM_DATA_POINTERS];
-        const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1 + 1;
+        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
+        const int pixel_size = desc->comp[0].step_minus1 + 1;
 
-        avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
+        av_pix_fmt_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift,
+                                         &v_chroma_shift);
 
         avcodec_align_dimensions2(s, &w, &h, stride_align);
 
@@ -542,7 +546,7 @@
             buf->linesize[i] = 0;
         }
         if (size[1] && !size[2])
-            ff_set_systematic_pal2((uint32_t *)buf->data[1], s->pix_fmt);
+            avpriv_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;
@@ -619,7 +623,7 @@
 int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic)
 {
     AVFrame temp_pic;
-    int i;
+    int i, ret;
 
     av_assert0(s->codec_type == AVMEDIA_TYPE_VIDEO);
 
@@ -653,8 +657,8 @@
         pic->data[i] = pic->base[i] = NULL;
     pic->opaque = NULL;
     /* Allocate new frame */
-    if (s->get_buffer(s, pic))
-        return -1;
+    if ((ret = s->get_buffer(s, pic)))
+        return ret;
     /* Copy image data from old buffer to new buffer */
     av_picture_copy((AVPicture *)pic, (AVPicture *)&temp_pic, s->pix_fmt, s->width,
                     s->height);
@@ -686,9 +690,15 @@
     return 0;
 }
 
-enum PixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum PixelFormat *fmt)
+static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
 {
-    while (*fmt != PIX_FMT_NONE && ff_is_hwaccel_pix_fmt(*fmt))
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
+    return desc->flags & PIX_FMT_HWACCEL;
+}
+
+enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
+{
+    while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
         ++fmt;
     return fmt[0];
 }
@@ -796,6 +806,27 @@
 }
 #endif
 
+int attribute_align_arg ff_codec_open2_recursive(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
+{
+    int ret = 0;
+
+    entangled_thread_counter--;
+    /* Release any user-supplied mutex. */
+    if (ff_lockmgr_cb) {
+        (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
+    }
+
+    ret = avcodec_open2(avctx, codec, options);
+
+    /* If there is a user-supplied mutex locking routine, call it. */
+    if (ff_lockmgr_cb) {
+        if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
+            return -1;
+    }
+    entangled_thread_counter++;
+    return ret;
+}
+
 int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
 {
     int ret = 0;
@@ -805,12 +836,12 @@
         return 0;
 
     if ((!codec && !avctx->codec)) {
-        av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2().\n");
+        av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2()\n");
         return AVERROR(EINVAL);
     }
     if ((codec && avctx->codec && codec != avctx->codec)) {
         av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
-                                    "but %s passed to avcodec_open2().\n", avctx->codec->name, codec->name);
+                                    "but %s passed to avcodec_open2()\n", avctx->codec->name, codec->name);
         return AVERROR(EINVAL);
     }
     if (!codec)
@@ -824,14 +855,14 @@
 
     /* If there is a user-supplied mutex locking routine, call it. */
     if (ff_lockmgr_cb) {
-        if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
-            return -1;
+        if ((ret = (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN)) < 0)
+            return ret;
     }
 
     entangled_thread_counter++;
     if (entangled_thread_counter != 1) {
-        av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
-        ret = -1;
+        av_log(avctx, AV_LOG_ERROR, "Insufficient thread locking around avcodec_open/close()\n");
+        ret = AVERROR(EINVAL);
         goto end;
     }
 
@@ -861,13 +892,6 @@
     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
         goto free_and_end;
 
-    if (codec->capabilities & CODEC_CAP_EXPERIMENTAL)
-        if (avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
-            av_log(avctx, AV_LOG_ERROR, "Codec is experimental but experimental codecs are not enabled, try -strict -2\n");
-            ret = -1;
-            goto free_and_end;
-        }
-
     //We only call avcodec_set_dimensions() for non h264 codecs so as not to overwrite previously setup dimensions
     if (!( avctx->coded_width && avctx->coded_height && avctx->width && avctx->height && avctx->codec_id == AV_CODEC_ID_H264)){
 
@@ -880,7 +904,7 @@
     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");
+        av_log(avctx, AV_LOG_WARNING, "Ignoring invalid width/height values\n");
         avcodec_set_dimensions(avctx, 0, 0);
     }
 
@@ -889,8 +913,7 @@
     if (av_codec_is_decoder(codec))
         av_freep(&avctx->subtitle_header);
 
-#define SANE_NB_CHANNELS 128U
-    if (avctx->channels > SANE_NB_CHANNELS) {
+    if (avctx->channels > FF_SANE_NB_CHANNELS) {
         ret = AVERROR(EINVAL);
         goto free_and_end;
     }
@@ -903,13 +926,29 @@
     }
     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");
+        av_log(avctx, AV_LOG_ERROR, "Codec type or id mismatches\n");
         ret = AVERROR(EINVAL);
         goto free_and_end;
     }
     avctx->frame_number = 0;
     avctx->codec_descriptor = avcodec_descriptor_get(avctx->codec_id);
 
+    if (avctx->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
+        avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
+        const char *codec_string = av_codec_is_encoder(codec) ? "encoder" : "decoder";
+        AVCodec *codec2;
+        av_log(NULL, AV_LOG_ERROR,
+               "The %s '%s' is experimental but experimental codecs are not enabled, "
+               "add '-strict %d' if you want to use it.\n",
+               codec_string, codec->name, FF_COMPLIANCE_EXPERIMENTAL);
+        codec2 = av_codec_is_encoder(codec) ? avcodec_find_encoder(codec->id) : avcodec_find_decoder(codec->id);
+        if (!(codec2->capabilities & CODEC_CAP_EXPERIMENTAL))
+            av_log(NULL, AV_LOG_ERROR, "Alternatively use the non experimental %s '%s'.\n",
+                codec_string, codec2->name);
+        ret = AVERROR_EXPERIMENTAL;
+        goto free_and_end;
+    }
+
     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
         (!avctx->time_base.num || !avctx->time_base.den)) {
         avctx->time_base.num = 1;
@@ -947,23 +986,36 @@
     if (av_codec_is_encoder(avctx->codec)) {
         int i;
         if (avctx->codec->sample_fmts) {
-            for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; 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->channels == 1 &&
+                    av_get_planar_sample_fmt(avctx->sample_fmt) ==
+                    av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {
+                    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");
+                char buf[128];
+                snprintf(buf, sizeof(buf), "%d", avctx->sample_fmt);
+                av_log(avctx, AV_LOG_ERROR, "Specified sample format %s is invalid or not supported\n",
+                       (char *)av_x_if_null(av_get_sample_fmt_name(avctx->sample_fmt), buf));
                 ret = AVERROR(EINVAL);
                 goto free_and_end;
             }
         }
         if (avctx->codec->pix_fmts) {
-            for (i = 0; avctx->codec->pix_fmts[i] != PIX_FMT_NONE; i++)
+            for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)
                 if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
                     break;
-            if (avctx->codec->pix_fmts[i] == PIX_FMT_NONE
+            if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE
                 && !((avctx->codec_id == AV_CODEC_ID_MJPEG || avctx->codec_id == AV_CODEC_ID_LJPEG)
                      && avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) {
-                av_log(avctx, AV_LOG_ERROR, "Specified pix_fmt is not supported\n");
+                char buf[128];
+                snprintf(buf, sizeof(buf), "%d", avctx->pix_fmt);
+                av_log(avctx, AV_LOG_ERROR, "Specified pixel format %s is invalid or not supported\n",
+                       (char *)av_x_if_null(av_get_pix_fmt_name(avctx->pix_fmt), buf));
                 ret = AVERROR(EINVAL);
                 goto free_and_end;
             }
@@ -973,28 +1025,36 @@
                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
                     break;
             if (avctx->codec->supported_samplerates[i] == 0) {
-                av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");
+                av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n",
+                       avctx->sample_rate);
                 ret = AVERROR(EINVAL);
                 goto free_and_end;
             }
         }
         if (avctx->codec->channel_layouts) {
             if (!avctx->channel_layout) {
-                av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");
+                av_log(avctx, AV_LOG_WARNING, "Channel layout not specified\n");
             } else {
                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
                         break;
                 if (avctx->codec->channel_layouts[i] == 0) {
-                    av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");
+                    char buf[512];
+                    av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
+                    av_log(avctx, AV_LOG_ERROR, "Specified channel layout '%s' is not supported\n", buf);
                     ret = AVERROR(EINVAL);
                     goto free_and_end;
                 }
             }
         }
         if (avctx->channel_layout && avctx->channels) {
-            if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
-                av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");
+            int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
+            if (channels != avctx->channels) {
+                char buf[512];
+                av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
+                av_log(avctx, AV_LOG_ERROR,
+                       "Channel layout '%s' with %d channels does not match number of specified channels %d\n",
+                       buf, channels, avctx->channels);
                 ret = AVERROR(EINVAL);
                 goto free_and_end;
             }
@@ -1027,11 +1087,20 @@
             if (!avctx->channels)
                 avctx->channels = channels;
             else if (channels != avctx->channels) {
+                char buf[512];
+                av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
                 av_log(avctx, AV_LOG_WARNING,
-                       "channel layout does not match number of channels\n");
+                       "Channel layout '%s' with %d channels does not match specified number of channels %d: "
+                       "ignoring specified channel layout\n",
+                       buf, channels, avctx->channels);
                 avctx->channel_layout = 0;
             }
         }
+        if (avctx->channels && avctx->channels < 0 ||
+            avctx->channels > FF_SANE_NB_CHANNELS) {
+            ret = AVERROR(EINVAL);
+            goto free_and_end;
+        }
     }
 end:
     entangled_thread_counter--;
@@ -1269,13 +1338,13 @@
     return ret;
 }
 
-#if FF_API_OLD_DECODE_AUDIO
+#if FF_API_OLD_ENCODE_AUDIO
 int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx,
                                              uint8_t *buf, int buf_size,
                                              const short *samples)
 {
     AVPacket pkt;
-    AVFrame frame0;
+    AVFrame frame0 = { 0 };
     AVFrame *frame;
     int ret, samples_size, got_packet;
 
@@ -1314,7 +1383,7 @@
         if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
                                             avctx->sample_fmt,
                                             (const uint8_t *)samples,
-                                            samples_size, 1)))
+                                            samples_size, 1)) < 0)
             return ret;
 
         /* fabricate frame pts from sample count.
@@ -1397,6 +1466,9 @@
     if(HAVE_THREADS && avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))
         return ff_thread_video_encode_frame(avctx, avpkt, frame, got_packet_ptr);
 
+    if ((avctx->flags&CODEC_FLAG_PASS1) && avctx->stats_out)
+        avctx->stats_out[0] = '\0';
+
     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
         av_free_packet(avpkt);
         av_init_packet(avpkt);
@@ -1542,6 +1614,31 @@
     }
 }
 
+static int add_metadata_from_side_data(AVCodecContext *avctx, AVFrame *frame)
+{
+    int size, ret = 0;
+    const uint8_t *side_metadata;
+    const uint8_t *end;
+
+    av_dict_free(&avctx->metadata);
+    side_metadata = av_packet_get_side_data(avctx->pkt,
+                                            AV_PKT_DATA_STRINGS_METADATA, &size);
+    if (!side_metadata)
+        goto end;
+    end = side_metadata + size;
+    while (side_metadata < end) {
+        const uint8_t *key = side_metadata;
+        const uint8_t *val = side_metadata + strlen(key) + 1;
+        int ret = av_dict_set(&frame->metadata, key, val, 0);
+        if (ret < 0)
+            break;
+        side_metadata = val + strlen(val) + 1;
+    }
+end:
+    avctx->metadata = frame->metadata;
+    return ret;
+}
+
 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
                                               int *got_picture_ptr,
                                               const AVPacket *avpkt)
@@ -1559,6 +1656,8 @@
     if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
         return AVERROR(EINVAL);
 
+    avcodec_get_frame_defaults(picture);
+
     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
         int did_split = av_packet_split_side_data(&tmp);
         apply_param_change(avctx, &tmp);
@@ -1578,8 +1677,9 @@
             if (!picture->sample_aspect_ratio.num) picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
             if (!picture->width)                   picture->width               = avctx->width;
             if (!picture->height)                  picture->height              = avctx->height;
-            if (picture->format == PIX_FMT_NONE)   picture->format              = avctx->pix_fmt;
+            if (picture->format == AV_PIX_FMT_NONE)   picture->format              = avctx->pix_fmt;
         }
+        add_metadata_from_side_data(avctx, picture);
 
         emms_c(); //needed to avoid an emms_c() call before every return;
 
@@ -1611,7 +1711,7 @@
                                               int *frame_size_ptr,
                                               AVPacket *avpkt)
 {
-    AVFrame frame;
+    AVFrame frame = {0};
     int ret, got_frame = 0;
 
     if (avctx->get_buffer != avcodec_default_get_buffer) {
@@ -1674,6 +1774,8 @@
         return AVERROR(EINVAL);
     }
 
+    avcodec_get_frame_defaults(frame);
+
     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
         uint8_t *side;
         int side_size;
@@ -1699,6 +1801,7 @@
             if (!frame->sample_rate)
                 frame->sample_rate = avctx->sample_rate;
         }
+        add_metadata_from_side_data(avctx, frame);
 
         side= av_packet_get_side_data(avctx->pkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
         if(side && side_size>=10) {
@@ -1746,10 +1849,14 @@
     /* many decoders assign whole AVFrames, thus overwriting extended_data;
      * make sure it's set correctly; assume decoders that actually use
      * extended_data are doing it correctly */
-    planar   = av_sample_fmt_is_planar(frame->format);
-    channels = av_get_channel_layout_nb_channels(frame->channel_layout);
-    if (!(planar && channels > AV_NUM_DATA_POINTERS))
-        frame->extended_data = frame->data;
+    if (*got_frame_ptr) {
+        planar   = av_sample_fmt_is_planar(frame->format);
+        channels = av_get_channel_layout_nb_channels(frame->channel_layout);
+        if (!(planar && channels > AV_NUM_DATA_POINTERS))
+            frame->extended_data = frame->data;
+    } else {
+        frame->extended_data = NULL;
+    }
 
     return ret;
 }
@@ -1758,22 +1865,39 @@
                              int *got_sub_ptr,
                              AVPacket *avpkt)
 {
-    int ret;
+    int ret = 0;
 
     if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
         av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
         return AVERROR(EINVAL);
     }
 
-    avctx->pkt = avpkt;
     *got_sub_ptr = 0;
     avcodec_get_subtitle_defaults(sub);
+
+    if (avpkt->size) {
+        AVPacket tmp = *avpkt;
+        int did_split = av_packet_split_side_data(&tmp);
+        //apply_param_change(avctx, &tmp);
+
+        avctx->pkt = &tmp;
+
     if (avctx->pkt_timebase.den && avpkt->pts != AV_NOPTS_VALUE)
         sub->pts = av_rescale_q(avpkt->pts,
                                 avctx->pkt_timebase, AV_TIME_BASE_Q);
-    ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
+        ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &tmp);
+
+        avctx->pkt = NULL;
+        if (did_split) {
+            ff_packet_free_side_data(&tmp);
+            if(ret == tmp.size)
+                ret = avpkt->size;
+        }
+
     if (*got_sub_ptr)
         avctx->frame_number++;
+    }
+
     return ret;
 }
 
@@ -1796,6 +1920,27 @@
     memset(sub, 0, sizeof(AVSubtitle));
 }
 
+av_cold int ff_codec_close_recursive(AVCodecContext *avctx)
+{
+    int ret = 0;
+
+    entangled_thread_counter--;
+    /* Release any user-supplied mutex. */
+    if (ff_lockmgr_cb) {
+        (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
+    }
+
+    ret = avcodec_close(avctx);
+
+    /* If there is a user-supplied mutex locking routine, call it. */
+    if (ff_lockmgr_cb) {
+        if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
+            return -1;
+    }
+    entangled_thread_counter++;
+    return ret;
+}
+
 av_cold int avcodec_close(AVCodecContext *avctx)
 {
     /* If there is a user-supplied mutex locking routine, call it. */
@@ -1826,6 +1971,7 @@
         avctx->internal->byte_buffer_size = 0;
         av_freep(&avctx->internal->byte_buffer);
         av_freep(&avctx->internal);
+        av_dict_free(&avctx->metadata);
     }
 
     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
@@ -1856,13 +2002,14 @@
     }
 }
 
-AVCodec *avcodec_find_encoder(enum AVCodecID id)
+static AVCodec *find_encdec(enum AVCodecID id, int encoder)
 {
     AVCodec *p, *experimental = NULL;
     p = first_avcodec;
     id= remap_deprecated_codec_id(id);
     while (p) {
-        if (av_codec_is_encoder(p) && p->id == id) {
+        if ((encoder ? av_codec_is_encoder(p) : av_codec_is_decoder(p)) &&
+            p->id == id) {
             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
                 experimental = p;
             } else
@@ -1873,6 +2020,11 @@
     return experimental;
 }
 
+AVCodec *avcodec_find_encoder(enum AVCodecID id)
+{
+    return find_encdec(id, 1);
+}
+
 AVCodec *avcodec_find_encoder_by_name(const char *name)
 {
     AVCodec *p;
@@ -1889,19 +2041,7 @@
 
 AVCodec *avcodec_find_decoder(enum AVCodecID id)
 {
-    AVCodec *p, *experimental=NULL;
-    p = first_avcodec;
-    id= remap_deprecated_codec_id(id);
-    while (p) {
-        if (av_codec_is_decoder(p) && p->id == id) {
-            if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
-                experimental = p;
-            } else
-                return p;
-        }
-        p = p->next;
-    }
-    return experimental;
+    return find_encdec(id, 0);
 }
 
 AVCodec *avcodec_find_decoder_by_name(const char *name)
@@ -1995,7 +2135,7 @@
 
     switch (enc->codec_type) {
     case AVMEDIA_TYPE_VIDEO:
-        if (enc->pix_fmt != PIX_FMT_NONE) {
+        if (enc->pix_fmt != AV_PIX_FMT_NONE) {
             snprintf(buf + strlen(buf), buf_size - strlen(buf),
                      ", %s",
                      av_get_pix_fmt_name(enc->pix_fmt));
@@ -2160,9 +2300,12 @@
 int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
 {
     switch (codec_id) {
+    case AV_CODEC_ID_8SVX_EXP:
+    case AV_CODEC_ID_8SVX_FIB:
     case AV_CODEC_ID_ADPCM_CT:
     case AV_CODEC_ID_ADPCM_IMA_APC:
     case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
+    case AV_CODEC_ID_ADPCM_IMA_OKI:
     case AV_CODEC_ID_ADPCM_IMA_WS:
     case AV_CODEC_ID_ADPCM_G722:
     case AV_CODEC_ID_ADPCM_YAMAHA:
@@ -2170,10 +2313,12 @@
     case AV_CODEC_ID_PCM_ALAW:
     case AV_CODEC_ID_PCM_MULAW:
     case AV_CODEC_ID_PCM_S8:
+    case AV_CODEC_ID_PCM_S8_PLANAR:
     case AV_CODEC_ID_PCM_U8:
     case AV_CODEC_ID_PCM_ZORK:
         return 8;
     case AV_CODEC_ID_PCM_S16BE:
+    case AV_CODEC_ID_PCM_S16BE_PLANAR:
     case AV_CODEC_ID_PCM_S16LE:
     case AV_CODEC_ID_PCM_S16LE_PLANAR:
     case AV_CODEC_ID_PCM_U16BE:
@@ -2182,11 +2327,13 @@
     case AV_CODEC_ID_PCM_S24DAUD:
     case AV_CODEC_ID_PCM_S24BE:
     case AV_CODEC_ID_PCM_S24LE:
+    case AV_CODEC_ID_PCM_S24LE_PLANAR:
     case AV_CODEC_ID_PCM_U24BE:
     case AV_CODEC_ID_PCM_U24LE:
         return 24;
     case AV_CODEC_ID_PCM_S32BE:
     case AV_CODEC_ID_PCM_S32LE:
+    case AV_CODEC_ID_PCM_S32LE_PLANAR:
     case AV_CODEC_ID_PCM_U32BE:
     case AV_CODEC_ID_PCM_U32LE:
     case AV_CODEC_ID_PCM_F32BE:
@@ -2264,7 +2411,6 @@
     case AV_CODEC_ID_GSM:
     case AV_CODEC_ID_QCELP:
     case AV_CODEC_ID_RA_288:       return  160;
-    case AV_CODEC_ID_IMC:          return  256;
     case AV_CODEC_ID_AMR_WB:
     case AV_CODEC_ID_GSM_MS:       return  320;
     case AV_CODEC_ID_MP1:          return  384;
@@ -2312,6 +2458,8 @@
             return 256 * (frame_bytes / 64);
         if (id == AV_CODEC_ID_RA_144)
             return 160 * (frame_bytes / 20);
+        if (id == AV_CODEC_ID_G723_1)
+            return 240 * (frame_bytes / 24);
 
         if (bps > 0) {
             /* calc from frame_bytes and bits_per_coded_sample */
@@ -2322,6 +2470,8 @@
         if (ch > 0) {
             /* calc from frame_bytes and channels */
             switch (id) {
+            case AV_CODEC_ID_ADPCM_AFC:
+                return frame_bytes / (9 * ch) * 16;
             case AV_CODEC_ID_ADPCM_4XM:
             case AV_CODEC_ID_ADPCM_IMA_ISS:
                 return (frame_bytes - 4 * ch) * 2 / ch;
@@ -2343,6 +2493,9 @@
                 return 6 * frame_bytes / ch;
             case AV_CODEC_ID_PCM_LXF:
                 return 2 * (frame_bytes / (5 * ch));
+            case AV_CODEC_ID_IAC:
+            case AV_CODEC_ID_IMC:
+                return 4 * frame_bytes / ch;
             }
 
             if (tag) {
@@ -2422,7 +2575,7 @@
 
 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 "
+    av_log(avc, AV_LOG_WARNING, "%s is not implemented. Update your FFmpeg "
             "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.\n", feature);
@@ -2461,7 +2614,7 @@
     return hwaccel ? hwaccel->next : first_hwaccel;
 }
 
-AVHWAccel *ff_find_hwaccel(enum AVCodecID codec_id, enum PixelFormat pix_fmt)
+AVHWAccel *ff_find_hwaccel(enum AVCodecID codec_id, enum AVPixelFormat pix_fmt)
 {
     AVHWAccel *hwaccel = NULL;
 
diff --git a/libavcodec/utvideodec.c b/libavcodec/utvideodec.c
index d08d6e8..cfeb46b 100644
--- a/libavcodec/utvideodec.c
+++ b/libavcodec/utvideodec.c
@@ -86,7 +86,7 @@
     VLC vlc;
     GetBitContext gb;
     int prev, fsym;
-    const int cmask = ~(!plane_no && c->avctx->pix_fmt == PIX_FMT_YUV420P);
+    const int cmask = ~(!plane_no && c->avctx->pix_fmt == AV_PIX_FMT_YUV420P);
 
     if (build_huff(src, &vlc, &fsym)) {
         av_log(c->avctx, AV_LOG_ERROR, "Cannot build Huffman codes\n");
@@ -391,8 +391,8 @@
     }
 
     switch (c->avctx->pix_fmt) {
-    case PIX_FMT_RGB24:
-    case PIX_FMT_RGBA:
+    case AV_PIX_FMT_RGB24:
+    case AV_PIX_FMT_RGBA:
         for (i = 0; i < c->planes; i++) {
             ret = decode_plane(c, i, c->pic.data[0] + ff_ut_rgb_order[i],
                                c->planes, c->pic.linesize[0], avctx->width,
@@ -416,7 +416,7 @@
         restore_rgb_planes(c->pic.data[0], c->planes, c->pic.linesize[0],
                            avctx->width, avctx->height);
         break;
-    case PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUV420P:
         for (i = 0; i < 3; i++) {
             ret = decode_plane(c, i, c->pic.data[i], 1, c->pic.linesize[i],
                                avctx->width >> !!i, avctx->height >> !!i,
@@ -437,7 +437,7 @@
             }
         }
         break;
-    case PIX_FMT_YUV422P:
+    case AV_PIX_FMT_YUV422P:
         for (i = 0; i < 3; i++) {
             ret = decode_plane(c, i, c->pic.data[i], 1, c->pic.linesize[i],
                                avctx->width >> !!i, avctx->height,
@@ -505,19 +505,19 @@
     switch (avctx->codec_tag) {
     case MKTAG('U', 'L', 'R', 'G'):
         c->planes      = 3;
-        avctx->pix_fmt = PIX_FMT_RGB24;
+        avctx->pix_fmt = AV_PIX_FMT_RGB24;
         break;
     case MKTAG('U', 'L', 'R', 'A'):
         c->planes      = 4;
-        avctx->pix_fmt = PIX_FMT_RGBA;
+        avctx->pix_fmt = AV_PIX_FMT_RGBA;
         break;
     case MKTAG('U', 'L', 'Y', '0'):
         c->planes      = 3;
-        avctx->pix_fmt = PIX_FMT_YUV420P;
+        avctx->pix_fmt = AV_PIX_FMT_YUV420P;
         break;
     case MKTAG('U', 'L', 'Y', '2'):
         c->planes      = 3;
-        avctx->pix_fmt = PIX_FMT_YUV422P;
+        avctx->pix_fmt = AV_PIX_FMT_YUV422P;
         break;
     default:
         av_log(avctx, AV_LOG_ERROR, "Unknown Ut Video FOURCC provided (%08X)\n",
diff --git a/libavcodec/utvideoenc.c b/libavcodec/utvideoenc.c
index fe5636f..7167278 100644
--- a/libavcodec/utvideoenc.c
+++ b/libavcodec/utvideoenc.c
@@ -65,17 +65,17 @@
     c->slice_stride    = FFALIGN(avctx->width, 32);
 
     switch (avctx->pix_fmt) {
-    case PIX_FMT_RGB24:
+    case AV_PIX_FMT_RGB24:
         c->planes        = 3;
         avctx->codec_tag = MKTAG('U', 'L', 'R', 'G');
         original_format  = UTVIDEO_RGB;
         break;
-    case PIX_FMT_RGBA:
+    case AV_PIX_FMT_RGBA:
         c->planes        = 4;
         avctx->codec_tag = MKTAG('U', 'L', 'R', 'A');
         original_format  = UTVIDEO_RGBA;
         break;
-    case PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUV420P:
         if (avctx->width & 1 || avctx->height & 1) {
             av_log(avctx, AV_LOG_ERROR,
                    "4:2:0 video requires even width and height.\n");
@@ -85,7 +85,7 @@
         avctx->codec_tag = MKTAG('U', 'L', 'Y', '0');
         original_format  = UTVIDEO_420;
         break;
-    case PIX_FMT_YUV422P:
+    case AV_PIX_FMT_YUV422P:
         if (avctx->width & 1) {
             av_log(avctx, AV_LOG_ERROR,
                    "4:2:2 video requires even width.\n");
@@ -417,7 +417,7 @@
         /* If non-zero count is found, see if it matches width * height */
         if (counts[symbol]) {
             /* Special case if only one symbol was used */
-            if (counts[symbol] == width * height) {
+            if (counts[symbol] == width * (int64_t)height) {
                 /*
                  * Write a zero for the single symbol
                  * used in the plane, else 0xFF.
@@ -534,14 +534,14 @@
     }
 
     /* In case of RGB, mangle the planes to Ut Video's format */
-    if (avctx->pix_fmt == PIX_FMT_RGBA || avctx->pix_fmt == PIX_FMT_RGB24)
+    if (avctx->pix_fmt == AV_PIX_FMT_RGBA || avctx->pix_fmt == AV_PIX_FMT_RGB24)
         mangle_rgb_planes(c->slice_buffer, c->slice_stride, pic->data[0],
                           c->planes, pic->linesize[0], width, height);
 
     /* Deal with the planes */
     switch (avctx->pix_fmt) {
-    case PIX_FMT_RGB24:
-    case PIX_FMT_RGBA:
+    case AV_PIX_FMT_RGB24:
+    case AV_PIX_FMT_RGBA:
         for (i = 0; i < c->planes; i++) {
             ret = encode_plane(avctx, c->slice_buffer[i] + 2 * c->slice_stride,
                                c->slice_buffer[i], c->slice_stride,
@@ -553,7 +553,7 @@
             }
         }
         break;
-    case PIX_FMT_YUV422P:
+    case AV_PIX_FMT_YUV422P:
         for (i = 0; i < c->planes; i++) {
             ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
                                pic->linesize[i], width >> !!i, height, &pb);
@@ -564,7 +564,7 @@
             }
         }
         break;
-    case PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUV420P:
         for (i = 0; i < c->planes; i++) {
             ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
                                pic->linesize[i], width >> !!i, height >> !!i,
@@ -615,9 +615,9 @@
     .init           = utvideo_encode_init,
     .encode2        = utvideo_encode_frame,
     .close          = utvideo_encode_close,
-    .pix_fmts       = (const enum PixelFormat[]) {
-                          PIX_FMT_RGB24, PIX_FMT_RGBA, PIX_FMT_YUV422P,
-                          PIX_FMT_YUV420P, PIX_FMT_NONE
+    .pix_fmts       = (const enum AVPixelFormat[]) {
+                          AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA, AV_PIX_FMT_YUV422P,
+                          AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE
                       },
     .long_name      = NULL_IF_CONFIG_SMALL("Ut Video"),
 };
diff --git a/libavcodec/v210dec.c b/libavcodec/v210dec.c
index ccac0ac..d508ce8 100644
--- a/libavcodec/v210dec.c
+++ b/libavcodec/v210dec.c
@@ -56,7 +56,7 @@
         av_log(avctx, AV_LOG_ERROR, "v210 needs even width\n");
         return -1;
     }
-    avctx->pix_fmt             = PIX_FMT_YUV422P10;
+    avctx->pix_fmt             = AV_PIX_FMT_YUV422P10;
     avctx->bits_per_raw_sample = 10;
 
     avctx->coded_frame         = avcodec_alloc_frame();
@@ -172,7 +172,7 @@
 #define V210DEC_FLAGS AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_VIDEO_PARAM
 static const AVOption v210dec_options[] = {
     {"custom_stride", "Custom V210 stride", offsetof(V210DecContext, custom_stride), FF_OPT_TYPE_INT,
-     {.dbl = 0}, INT_MIN, INT_MAX, V210DEC_FLAGS},
+     {.i64 = 0}, INT_MIN, INT_MAX, V210DEC_FLAGS},
     {NULL}
 };
 
diff --git a/libavcodec/v210enc.c b/libavcodec/v210enc.c
index 34b772f..5527686 100644
--- a/libavcodec/v210enc.c
+++ b/libavcodec/v210enc.c
@@ -121,6 +121,6 @@
     .init           = encode_init,
     .encode2        = encode_frame,
     .close          = encode_close,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUV422P10, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV422P10, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("Uncompressed 4:2:2 10-bit"),
 };
diff --git a/libavcodec/v210x.c b/libavcodec/v210x.c
index ca847b7..376588c 100644
--- a/libavcodec/v210x.c
+++ b/libavcodec/v210x.c
@@ -29,7 +29,7 @@
         av_log(avctx, AV_LOG_ERROR, "v210x needs even width\n");
         return -1;
     }
-    avctx->pix_fmt = PIX_FMT_YUV422P16;
+    avctx->pix_fmt = AV_PIX_FMT_YUV422P16;
     avctx->bits_per_raw_sample= 10;
 
     avctx->coded_frame= avcodec_alloc_frame();
diff --git a/libavcodec/v308dec.c b/libavcodec/v308dec.c
index 796518f..fd742ca 100644
--- a/libavcodec/v308dec.c
+++ b/libavcodec/v308dec.c
@@ -23,7 +23,7 @@
 
 static av_cold int v308_decode_init(AVCodecContext *avctx)
 {
-    avctx->pix_fmt = PIX_FMT_YUV444P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV444P;
 
     if (avctx->width & 1)
         av_log(avctx, AV_LOG_WARNING, "v308 requires width to be even.\n");
diff --git a/libavcodec/v308enc.c b/libavcodec/v308enc.c
index 3c98da7..7a0ca40 100644
--- a/libavcodec/v308enc.c
+++ b/libavcodec/v308enc.c
@@ -90,6 +90,6 @@
     .init         = v308_encode_init,
     .encode2      = v308_encode_frame,
     .close        = v308_encode_close,
-    .pix_fmts     = (const enum PixelFormat[]){ PIX_FMT_YUV444P, PIX_FMT_NONE },
+    .pix_fmts     = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV444P, AV_PIX_FMT_NONE },
     .long_name    = NULL_IF_CONFIG_SMALL("Uncompressed packed 4:4:4"),
 };
diff --git a/libavcodec/v408dec.c b/libavcodec/v408dec.c
index 01a5064..8820fc4c 100644
--- a/libavcodec/v408dec.c
+++ b/libavcodec/v408dec.c
@@ -23,7 +23,7 @@
 
 static av_cold int v408_decode_init(AVCodecContext *avctx)
 {
-    avctx->pix_fmt = PIX_FMT_YUVA444P;
+    avctx->pix_fmt = AV_PIX_FMT_YUVA444P;
 
     avctx->coded_frame = avcodec_alloc_frame();
 
diff --git a/libavcodec/v408enc.c b/libavcodec/v408enc.c
index 27944bc..9b0ebce 100644
--- a/libavcodec/v408enc.c
+++ b/libavcodec/v408enc.c
@@ -96,7 +96,7 @@
     .init         = v408_encode_init,
     .encode2      = v408_encode_frame,
     .close        = v408_encode_close,
-    .pix_fmts     = (const enum PixelFormat[]){ PIX_FMT_YUVA444P, PIX_FMT_NONE },
+    .pix_fmts     = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUVA444P, AV_PIX_FMT_NONE },
     .long_name    = NULL_IF_CONFIG_SMALL("Uncompressed packed MS 4:4:4:4"),
 };
 #endif
@@ -108,7 +108,7 @@
     .init         = v408_encode_init,
     .encode2      = v408_encode_frame,
     .close        = v408_encode_close,
-    .pix_fmts     = (const enum PixelFormat[]){ PIX_FMT_YUVA444P, PIX_FMT_NONE },
+    .pix_fmts     = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUVA444P, AV_PIX_FMT_NONE },
     .long_name    = NULL_IF_CONFIG_SMALL("Uncompressed packed QT 4:4:4:4"),
 };
 #endif
diff --git a/libavcodec/v410dec.c b/libavcodec/v410dec.c
index 180fcc0..4d4d625 100644
--- a/libavcodec/v410dec.c
+++ b/libavcodec/v410dec.c
@@ -26,7 +26,7 @@
 
 static av_cold int v410_decode_init(AVCodecContext *avctx)
 {
-    avctx->pix_fmt             = PIX_FMT_YUV444P10;
+    avctx->pix_fmt             = AV_PIX_FMT_YUV444P10;
     avctx->bits_per_raw_sample = 10;
 
     if (avctx->width & 1) {
diff --git a/libavcodec/v410enc.c b/libavcodec/v410enc.c
index b697b44..67d8fc9 100644
--- a/libavcodec/v410enc.c
+++ b/libavcodec/v410enc.c
@@ -94,6 +94,6 @@
     .init         = v410_encode_init,
     .encode2      = v410_encode_frame,
     .close        = v410_encode_close,
-    .pix_fmts     = (const enum PixelFormat[]){ PIX_FMT_YUV444P10, PIX_FMT_NONE },
+    .pix_fmts     = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV444P10, AV_PIX_FMT_NONE },
     .long_name    = NULL_IF_CONFIG_SMALL("Uncompressed 4:4:4 10-bit"),
 };
diff --git a/libavcodec/vaapi_h264.c b/libavcodec/vaapi_h264.c
index 38fc0da..9be51bf 100644
--- a/libavcodec/vaapi_h264.c
+++ b/libavcodec/vaapi_h264.c
@@ -341,7 +341,7 @@
     .name           = "h264_vaapi",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = AV_CODEC_ID_H264,
-    .pix_fmt        = PIX_FMT_VAAPI_VLD,
+    .pix_fmt        = AV_PIX_FMT_VAAPI_VLD,
     .start_frame    = start_frame,
     .end_frame      = end_frame,
     .decode_slice   = decode_slice,
diff --git a/libavcodec/vaapi_mpeg2.c b/libavcodec/vaapi_mpeg2.c
index 455f68e..50ba06d 100644
--- a/libavcodec/vaapi_mpeg2.c
+++ b/libavcodec/vaapi_mpeg2.c
@@ -142,7 +142,7 @@
     .name           = "mpeg2_vaapi",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = AV_CODEC_ID_MPEG2VIDEO,
-    .pix_fmt        = PIX_FMT_VAAPI_VLD,
+    .pix_fmt        = AV_PIX_FMT_VAAPI_VLD,
     .start_frame    = vaapi_mpeg2_start_frame,
     .end_frame      = vaapi_mpeg2_end_frame,
     .decode_slice   = vaapi_mpeg2_decode_slice,
diff --git a/libavcodec/vaapi_mpeg4.c b/libavcodec/vaapi_mpeg4.c
index f019661..3178740 100644
--- a/libavcodec/vaapi_mpeg4.c
+++ b/libavcodec/vaapi_mpeg4.c
@@ -154,7 +154,7 @@
     .name           = "mpeg4_vaapi",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = AV_CODEC_ID_MPEG4,
-    .pix_fmt        = PIX_FMT_VAAPI_VLD,
+    .pix_fmt        = AV_PIX_FMT_VAAPI_VLD,
     .start_frame    = vaapi_mpeg4_start_frame,
     .end_frame      = vaapi_mpeg4_end_frame,
     .decode_slice   = vaapi_mpeg4_decode_slice,
@@ -166,7 +166,7 @@
     .name           = "h263_vaapi",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = AV_CODEC_ID_H263,
-    .pix_fmt        = PIX_FMT_VAAPI_VLD,
+    .pix_fmt        = AV_PIX_FMT_VAAPI_VLD,
     .start_frame    = vaapi_mpeg4_start_frame,
     .end_frame      = vaapi_mpeg4_end_frame,
     .decode_slice   = vaapi_mpeg4_decode_slice,
diff --git a/libavcodec/vaapi_vc1.c b/libavcodec/vaapi_vc1.c
index e5d5626..af01e51 100644
--- a/libavcodec/vaapi_vc1.c
+++ b/libavcodec/vaapi_vc1.c
@@ -345,7 +345,7 @@
     .name           = "wmv3_vaapi",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = AV_CODEC_ID_WMV3,
-    .pix_fmt        = PIX_FMT_VAAPI_VLD,
+    .pix_fmt        = AV_PIX_FMT_VAAPI_VLD,
     .start_frame    = vaapi_vc1_start_frame,
     .end_frame      = vaapi_vc1_end_frame,
     .decode_slice   = vaapi_vc1_decode_slice,
@@ -356,7 +356,7 @@
     .name           = "vc1_vaapi",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = AV_CODEC_ID_VC1,
-    .pix_fmt        = PIX_FMT_VAAPI_VLD,
+    .pix_fmt        = AV_PIX_FMT_VAAPI_VLD,
     .start_frame    = vaapi_vc1_start_frame,
     .end_frame      = vaapi_vc1_end_frame,
     .decode_slice   = vaapi_vc1_decode_slice,
diff --git a/libavcodec/vb.c b/libavcodec/vb.c
index a71741d..5129458 100644
--- a/libavcodec/vb.c
+++ b/libavcodec/vb.c
@@ -250,7 +250,7 @@
     VBDecContext * const c = avctx->priv_data;
 
     c->avctx = avctx;
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
     avcodec_get_frame_defaults(&c->pic);
 
     c->frame      = av_mallocz(avctx->width * avctx->height);
@@ -280,4 +280,5 @@
     .close          = decode_end,
     .decode         = decode_frame,
     .long_name      = NULL_IF_CONFIG_SMALL("Beam Software VB"),
+    .capabilities   = CODEC_CAP_DR1,
 };
diff --git a/libavcodec/vble.c b/libavcodec/vble.c
index 63a08d7..2c68178 100644
--- a/libavcodec/vble.c
+++ b/libavcodec/vble.c
@@ -29,6 +29,7 @@
 #include "avcodec.h"
 #include "dsputil.h"
 #include "get_bits.h"
+#include "mathops.h"
 
 typedef struct {
     AVCodecContext *avctx;
@@ -126,6 +127,11 @@
     if (pic->data[0])
         avctx->release_buffer(avctx, pic);
 
+    if (avpkt->size < 4 || avpkt->size - 4 > INT_MAX/8) {
+        av_log(avctx, AV_LOG_ERROR, "Invalid packet size\n");
+        return AVERROR_INVALIDDATA;
+    }
+
     /* Allocate buffer */
     if (avctx->get_buffer(avctx, pic) < 0) {
         av_log(avctx, AV_LOG_ERROR, "Could not allocate buffer.\n");
@@ -139,10 +145,8 @@
     /* Version should always be 1 */
     version = AV_RL32(src);
 
-    if (version != 1) {
-        av_log(avctx, AV_LOG_ERROR, "Unsupported VBLE Version: %d\n", version);
-        return AVERROR_INVALIDDATA;
-    }
+    if (version != 1)
+        av_log(avctx, AV_LOG_WARNING, "Unsupported VBLE Version: %d\n", version);
 
     init_get_bits(&gb, src + 4, (avpkt->size - 4) * 8);
 
@@ -192,7 +196,7 @@
     ctx->avctx = avctx;
     ff_dsputil_init(&ctx->dsp, avctx);
 
-    avctx->pix_fmt = PIX_FMT_YUV420P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV420P;
     avctx->bits_per_raw_sample = 8;
     avctx->coded_frame = avcodec_alloc_frame();
 
diff --git a/libavcodec/vc1.c b/libavcodec/vc1.c
index 56c5bf9..fa0b916 100644
--- a/libavcodec/vc1.c
+++ b/libavcodec/vc1.c
@@ -585,7 +585,7 @@
         v->interpfrm = get_bits1(gb);
     if (!v->s.avctx->codec)
         return -1;
-    if (v->s.avctx->codec->id == AV_CODEC_ID_MSS2)
+    if (v->s.avctx->codec_id == AV_CODEC_ID_MSS2)
         v->respic   =
         v->rangered =
         v->multires = get_bits(gb, 2) == 1;
@@ -834,6 +834,7 @@
     int status;
     int mbmodetab, imvtab, icbptab, twomvbptab, fourmvbptab; /* useful only for debugging */
     int scale, shift, i; /* for initializing LUT for intensity compensation */
+    int field_mode, fcm;
 
     v->numref=0;
     v->p_frame_skipped = 0;
@@ -848,19 +849,23 @@
             goto parse_common_info;
     }
 
-    v->field_mode = 0;
+    field_mode = 0;
     if (v->interlace) {
-        v->fcm = decode012(gb);
-        if (v->fcm) {
-            if (v->fcm == ILACE_FIELD)
-                v->field_mode = 1;
+        fcm = decode012(gb);
+        if (fcm) {
+            if (fcm == ILACE_FIELD)
+                field_mode = 1;
             if (!v->warn_interlaced++)
                 av_log(v->s.avctx, AV_LOG_ERROR,
                        "Interlaced frames/fields support is incomplete\n");
         }
     } else {
-        v->fcm = PROGRESSIVE;
+        fcm = PROGRESSIVE;
     }
+    if (!v->first_pic_header_flag && v->field_mode != field_mode)
+        return -1;
+    v->field_mode = field_mode;
+    v->fcm = fcm;
 
     if (v->field_mode) {
         v->fptype = get_bits(gb, 3);
@@ -1158,7 +1163,6 @@
             if (v->bfraction == 0) {
                 return -1;
             }
-            return -1; // This codepath is still incomplete thus it is disabled
         }
         if (v->extended_mv)
             v->mvrange = get_unary(gb, 0, 3);
@@ -1274,6 +1278,11 @@
         break;
     }
 
+    if (v->fcm != PROGRESSIVE && !v->s.quarter_sample) {
+        v->range_x <<= 1;
+        v->range_y <<= 1;
+    }
+
     /* AC Syntax */
     v->c_ac_table_index = decode012(gb);
     if (v->s.pict_type == AV_PICTURE_TYPE_I || v->s.pict_type == AV_PICTURE_TYPE_BI) {
diff --git a/libavcodec/vc1.h b/libavcodec/vc1.h
index 6263d1d..4ed8923 100644
--- a/libavcodec/vc1.h
+++ b/libavcodec/vc1.h
@@ -368,6 +368,7 @@
     int qs_last;            ///< if qpel has been used in the previous (tr.) picture
     int bmvtype;
     int frfd, brfd;         ///< reference frame distance (forward or backward)
+    int first_pic_header_flag;
     int pic_header_flag;
 
     /** Frame decoding info for sprite modes */
diff --git a/libavcodec/vc1dec.c b/libavcodec/vc1dec.c
index cbf9562..f5c5329 100644
--- a/libavcodec/vc1dec.c
+++ b/libavcodec/vc1dec.c
@@ -395,6 +395,9 @@
         }
     }
 
+    if(!srcY)
+        return;
+
     src_x   = s->mb_x * 16 + (mx   >> 2);
     src_y   = s->mb_y * 16 + (my   >> 2);
     uvsrc_x = s->mb_x *  8 + (uvmx >> 2);
@@ -431,7 +434,7 @@
     if (v->rangeredfrm || (v->mv_mode == MV_PMODE_INTENSITY_COMP)
         || s->h_edge_pos < 22 || v_edge_pos < 22
         || (unsigned)(src_x - s->mspel) > s->h_edge_pos - (mx&3) - 16 - s->mspel * 3
-        || (unsigned)(src_y - s->mspel) > v_edge_pos    - (my&3) - 16 - s->mspel * 3) {
+        || (unsigned)(src_y - 1)        > v_edge_pos    - (my&3) - 16 - 3) {
         uint8_t *uvbuf = s->edge_emu_buffer + 19 * s->linesize;
 
         srcY -= s->mspel * (1 + s->linesize);
@@ -570,6 +573,9 @@
     } else
         srcY = s->next_picture.f.data[0];
 
+    if(!srcY)
+        return;
+
     if (v->field_mode) {
         if (v->cur_field_type != v->ref_field_type[dir])
             my = my - 2 + 4 * v->cur_field_type;
@@ -602,6 +608,8 @@
             tx = (chosen_mv[f][0][0] + chosen_mv[f][1][0]) / 2;
             ty = (chosen_mv[f][0][1] + chosen_mv[f][1][1]) / 2;
             break;
+        default:
+            av_assert2(0);
         }
         s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][0] = tx;
         s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][1] = ty;
@@ -795,6 +803,7 @@
     /* calculate chroma MV vector from four luma MVs */
     if (!v->field_mode || (v->field_mode && !v->numref)) {
         valid_count = get_chroma_mv(mvx, mvy, intra, 0, &tx, &ty);
+        chroma_ref_type = v->reffield;
         if (!valid_count) {
             s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][0] = 0;
             s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][1] = 0;
@@ -841,21 +850,27 @@
     if (!dir) {
         if (v->field_mode) {
             if ((v->cur_field_type != chroma_ref_type) && v->cur_field_type) {
-                srcU = s->current_picture.f.data[1] + uvsrc_y * s->uvlinesize + uvsrc_x;
-                srcV = s->current_picture.f.data[2] + uvsrc_y * s->uvlinesize + uvsrc_x;
+                srcU = s->current_picture.f.data[1];
+                srcV = s->current_picture.f.data[2];
             } else {
-                srcU = s->last_picture.f.data[1] + uvsrc_y * s->uvlinesize + uvsrc_x;
-                srcV = s->last_picture.f.data[2] + uvsrc_y * s->uvlinesize + uvsrc_x;
+                srcU = s->last_picture.f.data[1];
+                srcV = s->last_picture.f.data[2];
             }
         } else {
-            srcU = s->last_picture.f.data[1] + uvsrc_y * s->uvlinesize + uvsrc_x;
-            srcV = s->last_picture.f.data[2] + uvsrc_y * s->uvlinesize + uvsrc_x;
+            srcU = s->last_picture.f.data[1];
+            srcV = s->last_picture.f.data[2];
         }
     } else {
-        srcU = s->next_picture.f.data[1] + uvsrc_y * s->uvlinesize + uvsrc_x;
-        srcV = s->next_picture.f.data[2] + uvsrc_y * s->uvlinesize + uvsrc_x;
+        srcU = s->next_picture.f.data[1];
+        srcV = s->next_picture.f.data[2];
     }
 
+    if(!srcU)
+        return;
+
+    srcU += uvsrc_y * s->uvlinesize + uvsrc_x;
+    srcV += uvsrc_y * s->uvlinesize + uvsrc_x;
+
     if (v->field_mode) {
         if (chroma_ref_type) {
             srcU += s->current_picture_ptr->f.linesize[1];
@@ -1351,7 +1366,7 @@
     int px, py;
     int sum;
     int mixedmv_pic, num_samefield = 0, num_oppfield = 0;
-    int opposit, a_f, b_f, c_f;
+    int opposite, a_f, b_f, c_f;
     int16_t field_predA[2];
     int16_t field_predB[2];
     int16_t field_predC[2];
@@ -1459,13 +1474,19 @@
     }
 
     if (v->field_mode) {
-        if (num_samefield <= num_oppfield)
-            opposit = 1 - pred_flag;
-        else
-            opposit = pred_flag;
+        if (!v->numref)
+            // REFFIELD determines if the last field or the second-last field is
+            // to be used as reference
+            opposite = 1 - v->reffield;
+        else {
+            if (num_samefield <= num_oppfield)
+                opposite = 1 - pred_flag;
+            else
+                opposite = pred_flag;
+        }
     } else
-        opposit = 0;
-    if (opposit) {
+        opposite = 0;
+    if (opposite) {
         if (a_valid && !a_f) {
             field_predA[0] = scaleforopp(v, field_predA[0], 0, dir);
             field_predA[1] = scaleforopp(v, field_predA[1], 1, dir);
@@ -1568,10 +1589,6 @@
         }
     }
 
-    if (v->field_mode && !s->quarter_sample) {
-        r_x <<= 1;
-        r_y <<= 1;
-    }
     if (v->field_mode && v->numref)
         r_y >>= 1;
     if (v->field_mode && v->cur_field_type && v->ref_field_type[dir] == 0)
@@ -5151,7 +5168,7 @@
     if (!(avctx->flags & CODEC_FLAG_GRAY))
         avctx->pix_fmt = avctx->get_format(avctx, avctx->codec->pix_fmts);
     else
-        avctx->pix_fmt = PIX_FMT_GRAY8;
+        avctx->pix_fmt = AV_PIX_FMT_GRAY8;
     avctx->hwaccel = ff_find_hwaccel(avctx->codec->id, avctx->pix_fmt);
     v->s.avctx = avctx;
     avctx->flags |= CODEC_FLAG_EMU_EDGE;
@@ -5163,6 +5180,15 @@
 
     if (ff_vc1_init_common(v) < 0)
         return -1;
+    // ensure static VLC tables are initialized
+    if (ff_msmpeg4_decode_init(avctx) < 0)
+        return -1;
+    if (ff_vc1_decode_init_alloc_tables(v) < 0)
+        return -1;
+    // Hack to ensure the above functions will be called
+    // again once we know all necessary settings.
+    // That this is necessary might indicate a bug.
+    ff_vc1_decode_end(avctx);
     ff_vc1dsp_init(&v->vc1dsp);
 
     if (avctx->codec_id == AV_CODEC_ID_WMV3 || avctx->codec_id == AV_CODEC_ID_WMV3IMAGE) {
@@ -5315,7 +5341,7 @@
     MpegEncContext *s = &v->s;
     AVFrame *pict = data;
     uint8_t *buf2 = NULL;
-    const uint8_t *buf_start = buf;
+    const uint8_t *buf_start = buf, *buf_start_second_field = NULL;
     int mb_height, n_slices1=-1;
     struct {
         uint8_t *buf;
@@ -5323,6 +5349,8 @@
         int mby_start;
     } *slices = NULL, *tmp;
 
+    v->second_field = 0;
+
     if(s->flags & CODEC_FLAG_LOW_DELAY)
         s->low_delay = 1;
 
@@ -5341,9 +5369,9 @@
 
     if (s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU) {
         if (v->profile < PROFILE_ADVANCED)
-            avctx->pix_fmt = PIX_FMT_VDPAU_WMV3;
+            avctx->pix_fmt = AV_PIX_FMT_VDPAU_WMV3;
         else
-            avctx->pix_fmt = PIX_FMT_VDPAU_VC1;
+            avctx->pix_fmt = AV_PIX_FMT_VDPAU_VC1;
     }
 
     //for advanced profile we may need to parse and unescape data
@@ -5369,9 +5397,13 @@
                     break;
                 case VC1_CODE_FIELD: {
                     int buf_size3;
-                    slices = av_realloc(slices, sizeof(*slices) * (n_slices+1));
-                    if (!slices)
+                    if (avctx->hwaccel ||
+                        s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
+                        buf_start_second_field = start;
+                    tmp = av_realloc(slices, sizeof(*slices) * (n_slices+1));
+                    if (!tmp)
                         goto err;
+                    slices = tmp;
                     slices[n_slices].buf = av_mallocz(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
                     if (!slices[n_slices].buf)
                         goto err;
@@ -5393,9 +5425,10 @@
                     break;
                 case VC1_CODE_SLICE: {
                     int buf_size3;
-                    slices = av_realloc(slices, sizeof(*slices) * (n_slices+1));
-                    if (!slices)
+                    tmp = av_realloc(slices, sizeof(*slices) * (n_slices+1));
+                    if (!tmp)
                         goto err;
+                    slices = tmp;
                     slices[n_slices].buf = av_mallocz(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
                     if (!slices[n_slices].buf)
                         goto err;
@@ -5418,6 +5451,9 @@
                 av_log(avctx, AV_LOG_ERROR, "Error in WVC1 interlaced frame\n");
                 goto err;
             } else { // found field marker, unescape second field
+                if (avctx->hwaccel ||
+                    s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
+                    buf_start_second_field = divider;
                 tmp = av_realloc(slices, sizeof(*slices) * (n_slices+1));
                 if (!tmp)
                     goto err;
@@ -5466,11 +5502,13 @@
 
     if (!s->context_initialized) {
         if (ff_msmpeg4_decode_init(avctx) < 0 || ff_vc1_decode_init_alloc_tables(v) < 0)
-            return -1;
+            goto err;
 
         s->low_delay = !avctx->has_b_frames || v->res_sprite;
 
         if (v->profile == PROFILE_ADVANCED) {
+            if(avctx->coded_width<=1 || avctx->coded_height<=1)
+                goto err;
             s->h_edge_pos = avctx->coded_width;
             s->v_edge_pos = avctx->coded_height;
         }
@@ -5487,6 +5525,7 @@
 
     // do parse frame header
     v->pic_header_flag = 0;
+    v->first_pic_header_flag = 1;
     if (v->profile < PROFILE_ADVANCED) {
         if (ff_vc1_parse_frame_header(v, &s->gb) < 0) {
             goto err;
@@ -5496,6 +5535,7 @@
             goto err;
         }
     }
+    v->first_pic_header_flag = 0;
 
     if (avctx->debug & FF_DEBUG_PICT_INFO)
         av_log(v->s.avctx, AV_LOG_DEBUG, "pict_type: %c\n", av_get_picture_type_char(s->pict_type));
@@ -5506,6 +5546,11 @@
         goto err;
     }
 
+    if ((s->mb_height >> v->field_mode) == 0) {
+        av_log(v->s.avctx, AV_LOG_ERROR, "image too short\n");
+        goto err;
+    }
+
     // process pulldown flags
     s->current_picture_ptr->f.repeat_pict = 0;
     // Pulldown flags are only valid when 'broadcast' has been set.
@@ -5553,13 +5598,46 @@
         &&s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
         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)
-            goto err;
-        if (avctx->hwaccel->decode_slice(avctx, buf_start, (buf + buf_size) - buf_start) < 0)
-            goto err;
-        if (avctx->hwaccel->end_frame(avctx) < 0)
-            goto err;
+        if (v->field_mode && buf_start_second_field) {
+            // decode first field
+            s->picture_structure = PICT_BOTTOM_FIELD - v->tff;
+            if (avctx->hwaccel->start_frame(avctx, buf_start, buf_start_second_field - buf_start) < 0)
+                goto err;
+            if (avctx->hwaccel->decode_slice(avctx, buf_start, buf_start_second_field - buf_start) < 0)
+                goto err;
+            if (avctx->hwaccel->end_frame(avctx) < 0)
+                goto err;
+
+            // decode second field
+            s->gb = slices[n_slices1 + 1].gb;
+            s->picture_structure = PICT_TOP_FIELD + v->tff;
+            v->second_field = 1;
+            v->pic_header_flag = 0;
+            if (ff_vc1_parse_frame_header_adv(v, &s->gb) < 0) {
+                av_log(avctx, AV_LOG_ERROR, "parsing header for second field failed");
+                goto err;
+            }
+            v->s.current_picture_ptr->f.pict_type = v->s.pict_type;
+
+            if (avctx->hwaccel->start_frame(avctx, buf_start_second_field, (buf + buf_size) - buf_start_second_field) < 0)
+                goto err;
+            if (avctx->hwaccel->decode_slice(avctx, buf_start_second_field, (buf + buf_size) - buf_start_second_field) < 0)
+                goto err;
+            if (avctx->hwaccel->end_frame(avctx) < 0)
+                goto err;
+        } else {
+            s->picture_structure = PICT_FRAME;
+            if (avctx->hwaccel->start_frame(avctx, buf_start, (buf + buf_size) - buf_start) < 0)
+                goto err;
+            if (avctx->hwaccel->decode_slice(avctx, buf_start, (buf + buf_size) - buf_start) < 0)
+                goto err;
+            if (avctx->hwaccel->end_frame(avctx) < 0)
+                goto err;
+        }
     } else {
+        if (v->fcm == ILACE_FRAME && s->pict_type == AV_PICTURE_TYPE_B)
+            goto err; // This codepath is still incomplete thus it is disabled
+
         ff_er_frame_start(s);
 
         v->bits = buf_size * 8;
@@ -5615,8 +5693,13 @@
             s->start_mb_y = (i == 0) ? 0 : FFMAX(0, slices[i-1].mby_start % mb_height);
             if (!v->field_mode || v->second_field)
                 s->end_mb_y = (i == n_slices     ) ? mb_height : FFMIN(mb_height, slices[i].mby_start % mb_height);
-            else
+            else {
+                if (i >= n_slices) {
+                    av_log(v->s.avctx, AV_LOG_ERROR, "first field slice count too large\n");
+                    continue;
+                }
                 s->end_mb_y = (i <= n_slices1 + 1) ? mb_height : FFMIN(mb_height, slices[i].mby_start % mb_height);
+            }
             if (s->end_mb_y <= s->start_mb_y) {
                 av_log(v->s.avctx, AV_LOG_ERROR, "end mb y %d %d invalid\n", s->end_mb_y, s->start_mb_y);
                 continue;
@@ -5740,7 +5823,7 @@
     .decode         = vc1_decode_frame,
     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
     .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 AVPixelFormat[]){ AV_PIX_FMT_VDPAU_WMV3, AV_PIX_FMT_NONE },
     .profiles       = NULL_IF_CONFIG_SMALL(profiles)
 };
 #endif
@@ -5756,7 +5839,7 @@
     .decode         = vc1_decode_frame,
     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
     .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 AVPixelFormat[]){ AV_PIX_FMT_VDPAU_VC1, AV_PIX_FMT_NONE },
     .profiles       = NULL_IF_CONFIG_SMALL(profiles)
 };
 #endif
diff --git a/libavcodec/vc1dsp.c b/libavcodec/vc1dsp.c
index c2b7eff..a874509 100644
--- a/libavcodec/vc1dsp.c
+++ b/libavcodec/vc1dsp.c
@@ -850,6 +850,6 @@
 
     if (HAVE_ALTIVEC)
         ff_vc1dsp_init_altivec(dsp);
-    if (HAVE_MMX)
-        ff_vc1dsp_init_mmx(dsp);
+    if (ARCH_X86)
+        ff_vc1dsp_init_x86(dsp);
 }
diff --git a/libavcodec/vc1dsp.h b/libavcodec/vc1dsp.h
index d96853a..8775818 100644
--- a/libavcodec/vc1dsp.h
+++ b/libavcodec/vc1dsp.h
@@ -74,6 +74,6 @@
 
 void ff_vc1dsp_init(VC1DSPContext* c);
 void ff_vc1dsp_init_altivec(VC1DSPContext* c);
-void ff_vc1dsp_init_mmx(VC1DSPContext* dsp);
+void ff_vc1dsp_init_x86(VC1DSPContext* dsp);
 
 #endif /* AVCODEC_VC1DSP_H */
diff --git a/libavcodec/vcr1.c b/libavcodec/vcr1.c
index cbbec53..acac925 100644
--- a/libavcodec/vcr1.c
+++ b/libavcodec/vcr1.c
@@ -48,8 +48,12 @@
 {
     vcr1_common_init(avctx);
 
-    avctx->pix_fmt = PIX_FMT_YUV410P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV410P;
 
+    if (avctx->width % 8 || avctx->height%4) {
+        av_log_ask_for_sample(avctx, "odd dimensions are not supported\n");
+        return AVERROR_PATCHWELCOME;
+    }
     return 0;
 }
 
diff --git a/libavcodec/vda.h b/libavcodec/vda.h
index ccbf375..de7070e 100644
--- a/libavcodec/vda.h
+++ b/libavcodec/vda.h
@@ -29,12 +29,6 @@
  * Public libavcodec VDA header.
  */
 
-#include "libavcodec/version.h"
-
-#if FF_API_VDA_ASYNC
-#include <pthread.h>
-#endif
-
 #include <stdint.h>
 
 // emmintrin.h is unable to compile with -std=c99 -Werror=missing-prototypes
@@ -45,6 +39,12 @@
 #include <VideoDecodeAcceleration/VDADecoder.h>
 #undef Picture
 
+#include "libavcodec/version.h"
+
+#if FF_API_VDA_ASYNC
+#include <pthread.h>
+#endif
+
 /**
  * @defgroup lavc_codec_hwaccel_vda VDA
  * @ingroup lavc_codec_hwaccel
diff --git a/libavcodec/vda_h264.c b/libavcodec/vda_h264.c
index 4b8c754..89960d7 100644
--- a/libavcodec/vda_h264.c
+++ b/libavcodec/vda_h264.c
@@ -375,7 +375,7 @@
     .name           = "h264_vda",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = AV_CODEC_ID_H264,
-    .pix_fmt        = PIX_FMT_VDA_VLD,
+    .pix_fmt        = AV_PIX_FMT_VDA_VLD,
     .start_frame    = start_frame,
     .decode_slice   = decode_slice,
     .end_frame      = end_frame,
diff --git a/libavcodec/vda_h264_dec.c b/libavcodec/vda_h264_dec.c
index 36453c5..3cb13e3 100644
--- a/libavcodec/vda_h264_dec.c
+++ b/libavcodec/vda_h264_dec.c
@@ -37,31 +37,31 @@
 
 extern AVCodec ff_h264_decoder, ff_h264_vda_decoder;
 
-static const enum PixelFormat vda_pixfmts_prior_10_7[] = {
-    PIX_FMT_UYVY422,
-    PIX_FMT_YUV420P,
-    PIX_FMT_NONE
+static const enum AVPixelFormat vda_pixfmts_prior_10_7[] = {
+    AV_PIX_FMT_UYVY422,
+    AV_PIX_FMT_YUV420P,
+    AV_PIX_FMT_NONE
 };
 
-static const enum PixelFormat vda_pixfmts[] = {
-    PIX_FMT_UYVY422,
-    PIX_FMT_YUYV422,
-    PIX_FMT_NV12,
-    PIX_FMT_YUV420P,
-    PIX_FMT_NONE
+static const enum AVPixelFormat vda_pixfmts[] = {
+    AV_PIX_FMT_UYVY422,
+    AV_PIX_FMT_YUYV422,
+    AV_PIX_FMT_NV12,
+    AV_PIX_FMT_YUV420P,
+    AV_PIX_FMT_NONE
 };
 
 typedef struct {
     H264Context h264ctx;
     int h264_initialized;
     struct vda_context vda_ctx;
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
 } VDADecoderContext;
 
-static enum PixelFormat get_format(struct AVCodecContext *avctx,
-        const enum PixelFormat *fmt)
+static enum AVPixelFormat get_format(struct AVCodecContext *avctx,
+        const enum AVPixelFormat *fmt)
 {
-    return PIX_FMT_VDA_VLD;
+    return AV_PIX_FMT_VDA_VLD;
 }
 
 static int get_buffer(AVCodecContext *avctx, AVFrame *pic)
@@ -194,16 +194,16 @@
     vda_ctx->use_sync_decoding = 1;
     ctx->pix_fmt = avctx->get_format(avctx, avctx->codec->pix_fmts);
     switch (ctx->pix_fmt) {
-    case PIX_FMT_UYVY422:
+    case AV_PIX_FMT_UYVY422:
         vda_ctx->cv_pix_fmt_type = '2vuy';
         break;
-    case PIX_FMT_YUYV422:
+    case AV_PIX_FMT_YUYV422:
         vda_ctx->cv_pix_fmt_type = 'yuvs';
         break;
-    case PIX_FMT_NV12:
+    case AV_PIX_FMT_NV12:
         vda_ctx->cv_pix_fmt_type = '420v';
         break;
-    case PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUV420P:
         vda_ctx->cv_pix_fmt_type = 'y420';
         break;
     default:
diff --git a/libavcodec/vdpau.c b/libavcodec/vdpau.c
index da9ae9d..6ac195e 100644
--- a/libavcodec/vdpau.c
+++ b/libavcodec/vdpau.c
@@ -390,7 +390,7 @@
     .name           = "mpeg1_vdpau",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = AV_CODEC_ID_MPEG1VIDEO,
-    .pix_fmt        = PIX_FMT_VDPAU_MPEG1,
+    .pix_fmt        = AV_PIX_FMT_VDPAU_MPEG1,
     .start_frame    = vdpau_mpeg2_start_frame,
     .end_frame      = vdpau_mpeg2_end_frame,
     .decode_slice   = vdpau_mpeg2_decode_slice,
@@ -400,7 +400,7 @@
     .name           = "mpeg2_vdpau",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = AV_CODEC_ID_MPEG2VIDEO,
-    .pix_fmt        = PIX_FMT_VDPAU_MPEG2,
+    .pix_fmt        = AV_PIX_FMT_VDPAU_MPEG2,
     .start_frame    = vdpau_mpeg2_start_frame,
     .end_frame      = vdpau_mpeg2_end_frame,
     .decode_slice   = vdpau_mpeg2_decode_slice,
diff --git a/libavcodec/version.h b/libavcodec/version.h
index c1f80b6..a56e415 100644
--- a/libavcodec/version.h
+++ b/libavcodec/version.h
@@ -29,8 +29,8 @@
 #include "libavutil/avutil.h"
 
 #define LIBAVCODEC_VERSION_MAJOR 54
-#define LIBAVCODEC_VERSION_MINOR 61
-#define LIBAVCODEC_VERSION_MICRO 100
+#define LIBAVCODEC_VERSION_MINOR 78
+#define LIBAVCODEC_VERSION_MICRO 101
 
 #define LIBAVCODEC_VERSION_INT  AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \
                                                LIBAVCODEC_VERSION_MINOR, \
@@ -94,5 +94,14 @@
 #ifndef FF_API_VDA_ASYNC
 #define FF_API_VDA_ASYNC         (LIBAVCODEC_VERSION_MAJOR < 55)
 #endif
+#ifndef FF_API_AVCODEC_RESAMPLE
+#define FF_API_AVCODEC_RESAMPLE  (LIBAVCODEC_VERSION_MAJOR < 55)
+#endif
+#ifndef FF_API_LIBMPEG2
+#define FF_API_LIBMPEG2          (LIBAVCODEC_VERSION_MAJOR < 55)
+#endif
+#ifndef FF_API_MMI
+#define FF_API_MMI               (LIBAVCODEC_VERSION_MAJOR < 55)
+#endif
 
 #endif /* AVCODEC_VERSION_H */
diff --git a/libavcodec/vima.c b/libavcodec/vima.c
index 648ae55..35e2a3c 100644
--- a/libavcodec/vima.c
+++ b/libavcodec/vima.c
@@ -19,7 +19,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "avcodec.h"
 #include "get_bits.h"
 #include "adpcm_data.h"
diff --git a/libavcodec/vmdav.c b/libavcodec/vmdav.c
index 3834416..6e92e18 100644
--- a/libavcodec/vmdav.c
+++ b/libavcodec/vmdav.c
@@ -43,6 +43,7 @@
 #include <stdlib.h>
 #include <string.h>
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
 #include "libavutil/intreadwrite.h"
 #include "avcodec.h"
@@ -265,7 +266,7 @@
             r = *p++ * 4;
             g = *p++ * 4;
             b = *p++ * 4;
-            palette32[i] = 0xFF << 24 | r << 16 | g << 8 | b;
+            palette32[i] = 0xFFU << 24 | r << 16 | g << 8 | b;
             palette32[i] |= palette32[i] >> 6 & 0x30303;
         }
     }
@@ -378,7 +379,7 @@
     unsigned char *raw_palette;
 
     s->avctx = avctx;
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     /* make sure the VMD header made it */
     if (s->avctx->extradata_size != VMD_HEADER_SIZE) {
@@ -496,11 +497,14 @@
         av_log(avctx, AV_LOG_ERROR, "invalid number of channels\n");
         return AVERROR(EINVAL);
     }
-    if (avctx->block_align < 1) {
+    if (avctx->block_align < 1 || avctx->block_align % avctx->channels) {
         av_log(avctx, AV_LOG_ERROR, "invalid block align\n");
         return AVERROR(EINVAL);
     }
 
+    avctx->channel_layout = avctx->channels == 1 ? AV_CH_LAYOUT_MONO :
+                                                   AV_CH_LAYOUT_STEREO;
+
     if (avctx->bits_per_coded_sample == 16)
         avctx->sample_fmt = AV_SAMPLE_FMT_S16;
     else
diff --git a/libavcodec/vmnc.c b/libavcodec/vmnc.c
index 6d091c1..d465f30 100644
--- a/libavcodec/vmnc.c
+++ b/libavcodec/vmnc.c
@@ -332,6 +332,10 @@
     src += 2;
     chunks = AV_RB16(src); src += 2;
     while(chunks--) {
+        if(buf_size - (src - buf) < 12) {
+            av_log(avctx, AV_LOG_ERROR, "Premature end of data!\n");
+            return -1;
+        }
         dx = AV_RB16(src); src += 2;
         dy = AV_RB16(src); src += 2;
         w  = AV_RB16(src); src += 2;
@@ -341,6 +345,10 @@
         size_left = buf_size - (src - buf);
         switch(enc) {
         case MAGIC_WMVd: // cursor
+            if (w*(int64_t)h*c->bpp2 > INT_MAX/2 - 2) {
+                av_log(avctx, AV_LOG_ERROR, "dimensions too large\n");
+                return AVERROR_INVALIDDATA;
+            }
             if(size_left < 2 + w * h * c->bpp2 * 2) {
                 av_log(avctx, AV_LOG_ERROR, "Premature end of data! (need %i got %i)\n", 2 + w * h * c->bpp2 * 2, size_left);
                 return -1;
@@ -475,13 +483,13 @@
 
     switch(c->bpp){
     case 8:
-        avctx->pix_fmt = PIX_FMT_PAL8;
+        avctx->pix_fmt = AV_PIX_FMT_PAL8;
         break;
     case 16:
-        avctx->pix_fmt = PIX_FMT_RGB555;
+        avctx->pix_fmt = AV_PIX_FMT_RGB555;
         break;
     case 32:
-        avctx->pix_fmt = PIX_FMT_RGB32;
+        avctx->pix_fmt = AV_PIX_FMT_RGB32;
         break;
     default:
         av_log(avctx, AV_LOG_ERROR, "Unsupported bitdepth %i\n", c->bpp);
diff --git a/libavcodec/vorbis.h b/libavcodec/vorbis.h
index 14045ec..0bab0b9 100644
--- a/libavcodec/vorbis.h
+++ b/libavcodec/vorbis.h
@@ -29,7 +29,7 @@
 extern const uint8_t ff_vorbis_encoding_channel_layout_offsets[8][8];
 extern const uint64_t ff_vorbis_channel_layouts[9];
 
-typedef struct {
+typedef struct vorbis_floor1_entry {
     uint16_t x;
     uint16_t sort;
     uint16_t low;
diff --git a/libavcodec/vorbis_data.c b/libavcodec/vorbis_data.c
index f4b25fb..8aa8015 100644
--- a/libavcodec/vorbis_data.c
+++ b/libavcodec/vorbis_data.c
@@ -18,10 +18,10 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
+#include "libavutil/mem.h"
 #include "dsputil.h"
 #include "vorbis.h"
-#include "libavutil/audioconvert.h"
-#include "libavutil/mem.h"
 
 const uint8_t ff_vorbis_channel_layout_offsets[8][8] = {
     { 0 },
diff --git a/libavcodec/vorbisdec.c b/libavcodec/vorbisdec.c
index 8ce0fc7..0e018f1 100644
--- a/libavcodec/vorbisdec.c
+++ b/libavcodec/vorbisdec.c
@@ -153,9 +153,7 @@
     uint8_t       mode_number; // mode number for the current packet
     uint8_t       previous_window;
     float        *channel_residues;
-    float        *channel_floors;
     float        *saved;
-    float         scale_bias; // for float->int conversion
 } vorbis_context;
 
 /* Helper functions */
@@ -194,7 +192,6 @@
     int i;
 
     av_freep(&vc->channel_residues);
-    av_freep(&vc->channel_floors);
     av_freep(&vc->saved);
 
     for (i = 0; i < vc->residue_count; i++)
@@ -953,12 +950,11 @@
     }
 
     vc->channel_residues =  av_malloc((vc->blocksize[1]  / 2) * vc->audio_channels * sizeof(*vc->channel_residues));
-    vc->channel_floors   =  av_malloc((vc->blocksize[1]  / 2) * vc->audio_channels * sizeof(*vc->channel_floors));
     vc->saved            =  av_mallocz((vc->blocksize[1] / 4) * vc->audio_channels * sizeof(*vc->saved));
     vc->previous_window  = 0;
 
-    ff_mdct_init(&vc->mdct[0], bl0, 1, -vc->scale_bias);
-    ff_mdct_init(&vc->mdct[1], bl1, 1, -vc->scale_bias);
+    ff_mdct_init(&vc->mdct[0], bl0, 1, -1.0);
+    ff_mdct_init(&vc->mdct[1], bl1, 1, -1.0);
 
     av_dlog(NULL, " 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]);
@@ -990,13 +986,7 @@
     avpriv_float_dsp_init(&vc->fdsp, avccontext->flags & CODEC_FLAG_BITEXACT);
     ff_fmt_convert_init(&vc->fmt_conv, avccontext);
 
-    if (avccontext->request_sample_fmt == AV_SAMPLE_FMT_FLT) {
-        avccontext->sample_fmt = AV_SAMPLE_FMT_FLT;
-        vc->scale_bias = 1.0f;
-    } else {
-        avccontext->sample_fmt = AV_SAMPLE_FMT_S16;
-        vc->scale_bias = 32768.0f;
-    }
+    avccontext->sample_fmt = AV_SAMPLE_FMT_FLTP;
 
     if (!headers_len) {
         av_log(avccontext, AV_LOG_ERROR, "Extradata missing.\n");
@@ -1487,7 +1477,7 @@
 
 // Decode the audio packet using the functions above
 
-static int vorbis_parse_audio_packet(vorbis_context *vc)
+static int vorbis_parse_audio_packet(vorbis_context *vc, float **floor_ptr)
 {
     GetBitContext *gb = &vc->gb;
     FFTContext *mdct;
@@ -1498,7 +1488,6 @@
     uint8_t do_not_decode[255];
     vorbis_mapping *mapping;
     float *ch_res_ptr   = vc->channel_residues;
-    float *ch_floor_ptr = vc->channel_floors;
     uint8_t res_chan[255];
     unsigned res_num = 0;
     int retlen  = 0;
@@ -1530,7 +1519,8 @@
     }
 
     memset(ch_res_ptr,   0, sizeof(float) * vc->audio_channels * vlen); //FIXME can this be removed ?
-    memset(ch_floor_ptr, 0, sizeof(float) * vc->audio_channels * vlen); //FIXME can this be removed ?
+    for (i = 0; i < vc->audio_channels; ++i)
+        memset(floor_ptr[i], 0, vlen * sizeof(floor_ptr[0][0])); //FIXME can this be removed ?
 
 // Decode floor
 
@@ -1543,14 +1533,13 @@
             floor = &vc->floors[mapping->submap_floor[0]];
         }
 
-        ret = floor->decode(vc, &floor->data, ch_floor_ptr);
+        ret = floor->decode(vc, &floor->data, floor_ptr[i]);
 
         if (ret < 0) {
             av_log(vc->avccontext, AV_LOG_ERROR, "Invalid codebook in vorbis_floor_decode.\n");
             return AVERROR_INVALIDDATA;
         }
         no_residue[i] = ret;
-        ch_floor_ptr += vlen;
     }
 
 // Nonzero vector propagate
@@ -1614,10 +1603,9 @@
     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->fdsp.vector_fmul(ch_floor_ptr, ch_floor_ptr, ch_res_ptr, blocksize / 2);
-        mdct->imdct_half(mdct, ch_res_ptr, ch_floor_ptr);
+        vc->fdsp.vector_fmul(floor_ptr[j], floor_ptr[j], ch_res_ptr, blocksize / 2);
+        mdct->imdct_half(mdct, ch_res_ptr, floor_ptr[j]);
     }
 
 // Overlap/add, save data for next overlapping
@@ -1628,7 +1616,7 @@
         unsigned bs1 = vc->blocksize[1];
         float *residue    = vc->channel_residues + res_chan[j] * blocksize / 2;
         float *saved      = vc->saved + j * bs1 / 4;
-        float *ret        = vc->channel_floors + j * retlen;
+        float *ret        = floor_ptr[j];
         float *buf        = residue;
         const float *win  = vc->win[blockflag & previous_window];
 
@@ -1657,14 +1645,31 @@
     int buf_size       = avpkt->size;
     vorbis_context *vc = avccontext->priv_data;
     GetBitContext *gb = &vc->gb;
-    const float *channel_ptrs[255];
+    float *channel_ptrs[255];
     int i, len, ret;
 
     av_dlog(NULL, "packet length %d \n", buf_size);
 
+    /* get output buffer */
+    vc->frame.nb_samples = vc->blocksize[1] / 2;
+    if ((ret = avccontext->get_buffer(avccontext, &vc->frame)) < 0) {
+        av_log(avccontext, AV_LOG_ERROR, "get_buffer() failed\n");
+        return ret;
+    }
+
+    if (vc->audio_channels > 8) {
+        for (i = 0; i < vc->audio_channels; i++)
+            channel_ptrs[i] = (float *)vc->frame.extended_data[i];
+    } else {
+        for (i = 0; i < vc->audio_channels; i++) {
+            int ch = ff_vorbis_channel_layout_offsets[vc->audio_channels - 1][i];
+            channel_ptrs[ch] = (float *)vc->frame.extended_data[i];
+        }
+    }
+
     init_get_bits(gb, buf, buf_size*8);
 
-    if ((len = vorbis_parse_audio_packet(vc)) <= 0)
+    if ((len = vorbis_parse_audio_packet(vc, channel_ptrs)) <= 0)
         return len;
 
     if (!vc->first_frame) {
@@ -1676,30 +1681,7 @@
     av_dlog(NULL, "parsed %d bytes %d bits, returned %d samples (*ch*bits) \n",
             get_bits_count(gb) / 8, get_bits_count(gb) % 8, len);
 
-    /* get output buffer */
     vc->frame.nb_samples = len;
-    if ((ret = avccontext->get_buffer(avccontext, &vc->frame)) < 0) {
-        av_log(avccontext, AV_LOG_ERROR, "get_buffer() failed\n");
-        return ret;
-    }
-
-    if (vc->audio_channels > 8) {
-        for (i = 0; i < vc->audio_channels; i++)
-            channel_ptrs[i] = vc->channel_floors + i * len;
-    } else {
-        for (i = 0; i < vc->audio_channels; i++)
-            channel_ptrs[i] = vc->channel_floors +
-                              len * ff_vorbis_channel_layout_offsets[vc->audio_channels - 1][i];
-    }
-
-    if (avccontext->sample_fmt == AV_SAMPLE_FMT_FLT)
-        vc->fmt_conv.float_interleave((float *)vc->frame.data[0], channel_ptrs,
-                                      len, vc->audio_channels);
-    else
-        vc->fmt_conv.float_to_int16_interleave((int16_t *)vc->frame.data[0],
-                                               channel_ptrs, len,
-                                               vc->audio_channels);
-
     *got_frame_ptr   = 1;
     *(AVFrame *)data = vc->frame;
 
@@ -1740,7 +1722,6 @@
     .capabilities    = CODEC_CAP_DR1,
     .long_name       = NULL_IF_CONFIG_SMALL("Vorbis"),
     .channel_layouts = ff_vorbis_channel_layouts,
-    .sample_fmts     = (const enum AVSampleFormat[]) {
-        AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
-    },
+    .sample_fmts     = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
+                                                       AV_SAMPLE_FMT_NONE },
 };
diff --git a/libavcodec/vorbisenc.c b/libavcodec/vorbisenc.c
index b88791f..33b2577 100644
--- a/libavcodec/vorbisenc.c
+++ b/libavcodec/vorbisenc.c
@@ -963,10 +963,10 @@
     return 0;
 }
 
-static int apply_window_and_mdct(vorbis_enc_context *venc, const signed short *audio,
-                                 int samples)
+static int apply_window_and_mdct(vorbis_enc_context *venc,
+                                 float **audio, int samples)
 {
-    int i, j, channel;
+    int i, channel;
     const float * win = venc->win[0];
     int window_len = 1 << (venc->log2_blocksize[0] - 1);
     float n = (float)(1 << venc->log2_blocksize[0]) / 4.;
@@ -988,9 +988,8 @@
     if (samples) {
         for (channel = 0; channel < venc->channels; channel++) {
             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];
+            for (i = 0; i < samples; i++)
+                offset[i] = audio[channel][i] / n * win[window_len - i - 1];
         }
     } else {
         for (channel = 0; channel < venc->channels; channel++)
@@ -1005,9 +1004,8 @@
     if (samples) {
         for (channel = 0; channel < venc->channels; channel++) {
             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];
+            for (i = 0; i < samples; i++)
+                offset[i] = audio[channel][i] / n * win[i];
         }
         venc->have_saved = 1;
     } else {
@@ -1020,7 +1018,7 @@
                                const AVFrame *frame, int *got_packet_ptr)
 {
     vorbis_enc_context *venc = avccontext->priv_data;
-    const int16_t *audio = frame ? (const int16_t *)frame->data[0] : NULL;
+    float **audio = frame ? (float **)frame->extended_data : NULL;
     int samples = frame ? frame->nb_samples : 0;
     vorbis_enc_mode *mode;
     vorbis_enc_mapping *mapping;
@@ -1089,10 +1087,10 @@
     avpkt->size = put_bits_count(&pb) >> 3;
 
     avpkt->duration = ff_samples_to_time_base(avccontext, avccontext->frame_size);
-    if (frame)
+    if (frame) {
         if (frame->pts != AV_NOPTS_VALUE)
             avpkt->pts = ff_samples_to_time_base(avccontext, frame->pts);
-    else
+    } else
         avpkt->pts = venc->next_pts;
     if (avpkt->pts != AV_NOPTS_VALUE)
         venc->next_pts = avpkt->pts + avpkt->duration;
@@ -1213,7 +1211,7 @@
     .encode2        = vorbis_encode_frame,
     .close          = vorbis_encode_close,
     .capabilities   = CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
-    .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
+    .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLTP,
                                                      AV_SAMPLE_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("Vorbis"),
 };
diff --git a/libavcodec/vp3.c b/libavcodec/vp3.c
index 1094562..cc6fb3a 100644
--- a/libavcodec/vp3.c
+++ b/libavcodec/vp3.c
@@ -312,7 +312,7 @@
     return 0;
 }
 
-/*
+/**
  * This function sets up all of the various blocks mappings:
  * superblocks <-> fragments, macroblocks <-> fragments,
  * superblocks <-> macroblocks
@@ -1668,7 +1668,7 @@
     s->width = FFALIGN(avctx->width, 16);
     s->height = FFALIGN(avctx->height, 16);
     if (avctx->codec_id != AV_CODEC_ID_THEORA)
-        avctx->pix_fmt = PIX_FMT_YUV420P;
+        avctx->pix_fmt = AV_PIX_FMT_YUV420P;
     avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
     ff_dsputil_init(&s->dsp, avctx);
     ff_vp3dsp_init(&s->vp3dsp, avctx->flags);
@@ -2110,8 +2110,8 @@
 }
 
 #if CONFIG_THEORA_DECODER
-static const enum PixelFormat theora_pix_fmts[4] = {
-    PIX_FMT_YUV420P, PIX_FMT_NONE, PIX_FMT_YUV422P, PIX_FMT_YUV444P
+static const enum AVPixelFormat theora_pix_fmts[4] = {
+    AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P
 };
 
 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
@@ -2175,6 +2175,10 @@
     {
         skip_bits(gb, 5); /* keyframe frequency force */
         avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
+        if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
+            av_log(avctx, AV_LOG_ERROR, "Invalid pixel format\n");
+            return AVERROR_INVALIDDATA;
+        }
         skip_bits(gb, 3); /* reserved */
     }
 
@@ -2316,7 +2320,7 @@
     int header_len[3];
     int i;
 
-    avctx->pix_fmt = PIX_FMT_YUV420P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV420P;
 
     s->theora = 1;
 
@@ -2349,7 +2353,8 @@
     switch(ptype)
     {
         case 0x80:
-            theora_decode_header(avctx, &gb);
+            if (theora_decode_header(avctx, &gb) < 0)
+                return -1;
                 break;
         case 0x81:
 // FIXME: is this needed? it breaks sometimes
diff --git a/libavcodec/vp56.c b/libavcodec/vp56.c
index 2ae5f9c..ae7a117 100644
--- a/libavcodec/vp56.c
+++ b/libavcodec/vp56.c
@@ -547,11 +547,22 @@
     }
 
     if (s->has_alpha) {
+        int bak_w = avctx->width;
+        int bak_h = avctx->height;
+        int bak_cw = avctx->coded_width;
+        int bak_ch = avctx->coded_height;
         buf += alpha_offset;
         remaining_buf_size -= alpha_offset;
 
         res = s->alpha_context->parse_header(s->alpha_context, buf, remaining_buf_size);
         if (res != 1) {
+            if(res==2) {
+                av_log(avctx, AV_LOG_ERROR, "Alpha reconfiguration\n");
+                avctx->width  = bak_w;
+                avctx->height = bak_h;
+                avctx->coded_width  = bak_cw;
+                avctx->coded_height = bak_ch;
+            }
             avctx->release_buffer(avctx, p);
             return -1;
         }
@@ -688,7 +699,7 @@
     int i;
 
     s->avctx = avctx;
-    avctx->pix_fmt = has_alpha ? PIX_FMT_YUVA420P : PIX_FMT_YUV420P;
+    avctx->pix_fmt = has_alpha ? AV_PIX_FMT_YUVA420P : AV_PIX_FMT_YUV420P;
 
     ff_dsputil_init(&s->dsp, avctx);
     ff_vp3dsp_init(&s->vp3dsp, avctx->flags);
diff --git a/libavcodec/vp56.h b/libavcodec/vp56.h
index 44bd229..65245a2 100644
--- a/libavcodec/vp56.h
+++ b/libavcodec/vp56.h
@@ -35,7 +35,7 @@
 
 typedef struct vp56_context VP56Context;
 
-typedef struct {
+typedef struct VP56mv {
     DECLARE_ALIGNED(4, int16_t, x);
     int16_t y;
 } VP56mv;
@@ -52,7 +52,7 @@
 typedef int  (*VP56ParseHeader)(VP56Context *s, const uint8_t *buf,
                                 int buf_size);
 
-typedef struct {
+typedef struct VP56RangeCoder {
     int high;
     int bits; /* stored negated (i.e. negative "bits" is a positive number of
                  bits left) in order to eliminate a negate in cache refilling */
@@ -61,18 +61,18 @@
     unsigned int code_word;
 } VP56RangeCoder;
 
-typedef struct {
+typedef struct VP56RefDc {
     uint8_t not_null_dc;
     VP56Frame ref_frame;
     DCTELEM dc_coeff;
 } VP56RefDc;
 
-typedef struct {
+typedef struct VP56Macroblock {
     uint8_t type;
     VP56mv mv;
 } VP56Macroblock;
 
-typedef struct {
+typedef struct VP56Model {
     uint8_t coeff_reorder[64];       /* used in vp6 only */
     uint8_t coeff_index_to_pos[64];  /* used in vp6 only */
     uint8_t vector_sig[2];           /* delta sign */
diff --git a/libavcodec/vp56data.h b/libavcodec/vp56data.h
index d48a89c..f30732e 100644
--- a/libavcodec/vp56data.h
+++ b/libavcodec/vp56data.h
@@ -51,7 +51,7 @@
     VP56_MB_INTER_V2_GF    = 9,  /**< Inter MB, second vector, from golden frame */
 } VP56mb;
 
-typedef struct {
+typedef struct VP56Tree {
   int8_t val;
   int8_t prob_idx;
 } VP56Tree;
diff --git a/libavcodec/vp56dsp.c b/libavcodec/vp56dsp.c
index 339c3d2..a72c48e 100644
--- a/libavcodec/vp56dsp.c
+++ b/libavcodec/vp56dsp.c
@@ -90,5 +90,5 @@
     }
 
     if (ARCH_ARM) ff_vp56dsp_init_arm(s, codec);
-    if (HAVE_MMX) ff_vp56dsp_init_x86(s, codec);
+    if (ARCH_X86) ff_vp56dsp_init_x86(s, codec);
 }
diff --git a/libavcodec/vp8.c b/libavcodec/vp8.c
index 510b59d..9424c45 100644
--- a/libavcodec/vp8.c
+++ b/libavcodec/vp8.c
@@ -1965,7 +1965,8 @@
     // 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);
+        s->top_border[0][31] = 127;
+        memset(s->top_border[1], 127, s->mb_width*sizeof(*s->top_border));
     }
     memset(s->ref_count, 0, sizeof(s->ref_count));
 
@@ -2018,7 +2019,7 @@
     VP8Context *s = avctx->priv_data;
 
     s->avctx = avctx;
-    avctx->pix_fmt = PIX_FMT_YUV420P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV420P;
 
     ff_dsputil_init(&s->dsp, avctx);
     ff_h264_pred_init(&s->hpc, AV_CODEC_ID_VP8, 8, 1);
diff --git a/libavcodec/vp8.h b/libavcodec/vp8.h
index 4f026df..2193487 100644
--- a/libavcodec/vp8.h
+++ b/libavcodec/vp8.h
@@ -34,6 +34,8 @@
 #include <pthread.h>
 #elif HAVE_W32THREADS
 #include "w32pthreads.h"
+#elif HAVE_OS2THREADS
+#include "os2threads.h"
 #endif
 
 #define VP8_MAX_QUANT 127
@@ -72,13 +74,13 @@
     VP8_SPLITMVMODE_NONE,        ///< (only used in prediction) no split MVs
 };
 
-typedef struct {
+typedef struct VP8FilterStrength {
     uint8_t filter_level;
     uint8_t inner_limit;
     uint8_t inner_filter;
 } VP8FilterStrength;
 
-typedef struct {
+typedef struct VP8Macroblock {
     uint8_t skip;
     // todo: make it possible to check for at least (i4x4 or split_mv)
     // in one op. are others needed?
@@ -93,7 +95,7 @@
     VP56mv bmv[16];
 } VP8Macroblock;
 
-typedef struct {
+typedef struct VP8ThreadData {
     DECLARE_ALIGNED(16, DCTELEM, block)[6][4][16];
     DECLARE_ALIGNED(16, DCTELEM, block_dc)[16];
     /**
@@ -123,7 +125,7 @@
 } VP8ThreadData;
 
 #define MAX_THREADS 8
-typedef struct {
+typedef struct VP8Context {
     VP8ThreadData *thread_data;
     AVCodecContext *avctx;
     AVFrame *framep[4];
diff --git a/libavcodec/vp8dsp.c b/libavcodec/vp8dsp.c
index bacd10e..a53643c 100644
--- a/libavcodec/vp8dsp.c
+++ b/libavcodec/vp8dsp.c
@@ -521,7 +521,7 @@
     VP8_BILINEAR_MC_FUNC(1, 8);
     VP8_BILINEAR_MC_FUNC(2, 4);
 
-    if (HAVE_MMX)
+    if (ARCH_X86)
         ff_vp8dsp_init_x86(dsp);
     if (HAVE_ALTIVEC)
         ff_vp8dsp_init_altivec(dsp);
diff --git a/libavcodec/vqavideo.c b/libavcodec/vqavideo.c
index e4bad00..2980f94 100644
--- a/libavcodec/vqavideo.c
+++ b/libavcodec/vqavideo.c
@@ -124,25 +124,25 @@
     int i, j, codebook_index;
 
     s->avctx = avctx;
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     /* make sure the extradata made it */
     if (s->avctx->extradata_size != VQA_HEADER_SIZE) {
         av_log(s->avctx, AV_LOG_ERROR, "expected extradata size of %d\n", VQA_HEADER_SIZE);
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     /* load up the VQA parameters from the header */
     s->vqa_version = s->avctx->extradata[0];
     if (s->vqa_version < 1 || s->vqa_version > 3) {
         av_log(s->avctx, AV_LOG_ERROR, "unsupported version %d\n", s->vqa_version);
-        return -1;
+        return AVERROR_PATCHWELCOME;
     }
     s->width = AV_RL16(&s->avctx->extradata[6]);
     s->height = AV_RL16(&s->avctx->extradata[8]);
     if(av_image_check_size(s->width, s->height, 0, avctx)){
         s->width= s->height= 0;
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
     s->vector_width = s->avctx->extradata[10];
     s->vector_height = s->avctx->extradata[11];
@@ -152,7 +152,7 @@
     if ((s->vector_width != 4) ||
         ((s->vector_height != 2) && (s->vector_height != 4))) {
         /* return without further initialization */
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     if (s->width % s->vector_width || s->height % s->vector_height) {
@@ -416,7 +416,7 @@
             r = bytestream2_get_byteu(&s->gb) * 4;
             g = bytestream2_get_byteu(&s->gb) * 4;
             b = bytestream2_get_byteu(&s->gb) * 4;
-            s->palette[i] = 0xFF << 24 | r << 16 | g << 8 | b;
+            s->palette[i] = 0xFFU << 24 | r << 16 | g << 8 | b;
             s->palette[i] |= s->palette[i] >> 6 & 0x30303;
         }
     }
@@ -566,9 +566,7 @@
 
         s->partial_countdown--;
         if (s->partial_countdown <= 0) {
-            GetByteContext gb;
-
-            bytestream2_init(&gb, s->next_codebook_buffer, s->next_codebook_buffer_index);
+            bytestream2_init(&s->gb, s->next_codebook_buffer, s->next_codebook_buffer_index);
             /* decompress codebook */
             if ((res = decode_format80(s, s->next_codebook_buffer_index,
                                        s->codebook, s->codebook_size, 0)) < 0)
@@ -593,9 +591,9 @@
     if (s->frame.data[0])
         avctx->release_buffer(avctx, &s->frame);
 
-    if (avctx->get_buffer(avctx, &s->frame)) {
+    if ((res = avctx->get_buffer(avctx, &s->frame))) {
         av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
+        return res;
     }
 
     bytestream2_init(&s->gb, avpkt->data, avpkt->size);
diff --git a/libavcodec/w32pthreads.h b/libavcodec/w32pthreads.h
index c4bbb9a..29185c7 100644
--- a/libavcodec/w32pthreads.h
+++ b/libavcodec/w32pthreads.h
@@ -43,7 +43,7 @@
 #include "libavutil/internal.h"
 #include "libavutil/mem.h"
 
-typedef struct {
+typedef struct pthread_t {
     void *handle;
     void *(*func)(void* arg);
     void *arg;
@@ -57,7 +57,7 @@
 /* This is the CONDITIONAL_VARIABLE typedef for using Window's native
  * conditional variables on kernels 6.0+.
  * MinGW does not currently have this typedef. */
-typedef struct {
+typedef struct pthread_cond_t {
     void *ptr;
 } pthread_cond_t;
 
@@ -118,7 +118,7 @@
 
 /* for pre-Windows 6.0 platforms we need to define and use our own condition
  * variable and api */
-typedef struct {
+typedef struct  win32_cond_t {
     pthread_mutex_t mtx_broadcast;
     pthread_mutex_t mtx_waiter_count;
     volatile int waiter_count;
diff --git a/libavcodec/wavpack.c b/libavcodec/wavpack.c
index ef4fc4f..bc038a9 100644
--- a/libavcodec/wavpack.c
+++ b/libavcodec/wavpack.c
@@ -21,7 +21,7 @@
 
 #define BITSTREAM_READER_LE
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "avcodec.h"
 #include "get_bits.h"
 #include "unary.h"
@@ -46,6 +46,8 @@
 #define WV_FLT_ZERO_SENT  0x08
 #define WV_FLT_ZERO_SIGN  0x10
 
+#define WV_MAX_SAMPLES    131072
+
 enum WP_ID_Flags {
     WP_IDF_MASK   = 0x1F,
     WP_IDF_IGNORE = 0x20,
@@ -787,6 +789,11 @@
         return -1;
     }
 
+    if (wc->ch_offset >= avctx->channels) {
+        av_log(avctx, AV_LOG_ERROR, "too many channels\n");
+        return -1;
+    }
+
     memset(s->decorr, 0, MAX_TERMS * sizeof(Decorr));
     memset(s->ch, 0, sizeof(s->ch));
     s->extra_bits = 0;
@@ -799,6 +806,10 @@
             *got_frame_ptr = 0;
             return 0;
         }
+        if (s->samples > wc->samples) {
+            av_log(avctx, AV_LOG_ERROR, "too many samples in block");
+            return -1;
+        }
     } else {
         s->samples = wc->samples;
     }
@@ -1190,7 +1201,7 @@
             frame_flags = AV_RL32(buf + 4);
         }
     }
-    if (s->samples <= 0) {
+    if (s->samples <= 0 || s->samples > WV_MAX_SAMPLES) {
         av_log(avctx, AV_LOG_ERROR, "Invalid number of samples: %d\n",
                s->samples);
         return AVERROR(EINVAL);
@@ -1206,11 +1217,12 @@
     }
 
     /* get output buffer */
-    s->frame.nb_samples = s->samples;
+    s->frame.nb_samples = s->samples + 1;
     if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         return ret;
     }
+    s->frame.nb_samples = s->samples;
 
     while (buf_size > 0) {
         if (!s->multichannel) {
@@ -1228,13 +1240,13 @@
             av_log(avctx, AV_LOG_ERROR, "Block %d has invalid size (size %d "
                    "vs. %d bytes left)\n", s->block, frame_size, buf_size);
             wavpack_decode_flush(avctx);
-            return -1;
+            return AVERROR_INVALIDDATA;
         }
         if ((samplecount = wavpack_decode_block(avctx, s->block,
                                                 s->frame.data[0], got_frame_ptr,
                                                 buf, frame_size)) < 0) {
             wavpack_decode_flush(avctx);
-            return -1;
+            return AVERROR_INVALIDDATA;
         }
         s->block++;
         buf += frame_size; buf_size -= frame_size;
diff --git a/libavcodec/wma.c b/libavcodec/wma.c
index d5e66e2..d0c0b34 100644
--- a/libavcodec/wma.c
+++ b/libavcodec/wma.c
@@ -82,13 +82,9 @@
         || avctx->bit_rate    <= 0)
         return -1;
 
-    s->sample_rate = avctx->sample_rate;
-    s->nb_channels = avctx->channels;
-    s->bit_rate    = avctx->bit_rate;
-    s->block_align = avctx->block_align;
-
     ff_dsputil_init(&s->dsp, avctx);
     ff_fmt_convert_init(&s->fmt_conv, avctx);
+    avpriv_float_dsp_init(&s->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
 
     if (avctx->codec->id == AV_CODEC_ID_WMAV1) {
         s->version = 1;
@@ -97,7 +93,8 @@
     }
 
     /* compute MDCT block size */
-    s->frame_len_bits = ff_wma_get_frame_len_bits(s->sample_rate, s->version, 0);
+    s->frame_len_bits = ff_wma_get_frame_len_bits(avctx->sample_rate,
+                                                  s->version, 0);
     s->next_block_len_bits = s->frame_len_bits;
     s->prev_block_len_bits = s->frame_len_bits;
     s->block_len_bits      = s->frame_len_bits;
@@ -106,7 +103,7 @@
     if (s->use_variable_block_len) {
         int nb_max, nb;
         nb = ((flags2 >> 3) & 3) + 1;
-        if ((s->bit_rate / s->nb_channels) >= 32000)
+        if ((avctx->bit_rate / avctx->channels) >= 32000)
             nb += 2;
         nb_max = s->frame_len_bits - BLOCK_MIN_BITS;
         if (nb > nb_max)
@@ -118,10 +115,10 @@
 
     /* init rate dependent parameters */
     s->use_noise_coding = 1;
-    high_freq = s->sample_rate * 0.5;
+    high_freq = avctx->sample_rate * 0.5;
 
     /* if version 2, then the rates are normalized */
-    sample_rate1 = s->sample_rate;
+    sample_rate1 = avctx->sample_rate;
     if (s->version == 2) {
         if (sample_rate1 >= 44100) {
             sample_rate1 = 44100;
@@ -136,13 +133,13 @@
         }
     }
 
-    bps = (float)s->bit_rate / (float)(s->nb_channels * s->sample_rate);
+    bps = (float)avctx->bit_rate / (float)(avctx->channels * avctx->sample_rate);
     s->byte_offset_bits = av_log2((int)(bps * s->frame_len / 8.0 + 0.5)) + 2;
 
     /* compute high frequency value and choose if noise coding should
        be activated */
     bps1 = bps;
-    if (s->nb_channels == 2)
+    if (avctx->channels == 2)
         bps1 = bps * 1.6;
     if (sample_rate1 == 44100) {
         if (bps1 >= 0.61) {
@@ -185,8 +182,8 @@
     }
     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);
+            s->version, avctx->channels, avctx->sample_rate, avctx->bit_rate,
+            avctx->block_align);
     av_dlog(s->avctx, "bps=%f bps1=%f high_freq=%f bitoffset=%d\n",
             bps, bps1, high_freq, s->byte_offset_bits);
     av_dlog(s->avctx, "use_noise_coding=%d use_exp_vlc=%d nb_block_sizes=%d\n",
@@ -209,7 +206,7 @@
                 lpos = 0;
                 for (i = 0; i < 25; i++) {
                     a = ff_wma_critical_freqs[i];
-                    b = s->sample_rate;
+                    b = avctx->sample_rate;
                     pos = ((block_len * 2 * a) + (b >> 1)) / b;
                     if (pos > block_len)
                         pos = block_len;
@@ -226,11 +223,11 @@
                 table = NULL;
                 a = s->frame_len_bits - BLOCK_MIN_BITS - k;
                 if (a < 3) {
-                    if (s->sample_rate >= 44100) {
+                    if (avctx->sample_rate >= 44100) {
                         table = exponent_band_44100[a];
-                    } else if (s->sample_rate >= 32000) {
+                    } else if (avctx->sample_rate >= 32000) {
                         table = exponent_band_32000[a];
-                    } else if (s->sample_rate >= 22050) {
+                    } else if (avctx->sample_rate >= 22050) {
                         table = exponent_band_22050[a];
                     }
                 }
@@ -244,7 +241,7 @@
                     lpos = 0;
                     for (i = 0; i < 25; i++) {
                         a = ff_wma_critical_freqs[i];
-                        b = s->sample_rate;
+                        b = avctx->sample_rate;
                         pos = ((block_len * 2 * a) + (b << 1)) / (4 * b);
                         pos <<= 2;
                         if (pos > block_len)
@@ -263,7 +260,7 @@
             s->coefs_end[k] = (s->frame_len - ((s->frame_len * 9) / 100)) >> k;
             /* high freq computation */
             s->high_band_start[k] = (int)((block_len * 2 * high_freq) /
-                                          s->sample_rate + 0.5);
+                                          avctx->sample_rate + 0.5);
             n = s->exponent_sizes[k];
             j = 0;
             pos = 0;
@@ -343,7 +340,7 @@
 
     /* choose the VLC tables for the coefficients */
     coef_vlc_table = 2;
-    if (s->sample_rate >= 32000) {
+    if (avctx->sample_rate >= 32000) {
         if (bps1 < 0.72) {
             coef_vlc_table = 0;
         } else if (bps1 < 1.16) {
diff --git a/libavcodec/wma.h b/libavcodec/wma.h
index 73734eb..4db4faa 100644
--- a/libavcodec/wma.h
+++ b/libavcodec/wma.h
@@ -22,6 +22,7 @@
 #ifndef AVCODEC_WMA_H
 #define AVCODEC_WMA_H
 
+#include "libavutil/float_dsp.h"
 #include "get_bits.h"
 #include "put_bits.h"
 #include "dsputil.h"
@@ -68,11 +69,7 @@
     AVFrame frame;
     GetBitContext gb;
     PutBitContext pb;
-    int sample_rate;
-    int nb_channels;
-    int bit_rate;
     int version;                            ///< 1 = 0x160 (WMAV1), 2 = 0x161 (WMAV2)
-    int block_align;
     int use_bit_reservoir;
     int use_variable_block_len;
     int use_exp_vlc;                        ///< exponent coding: 0 = lsp, 1 = vlc + delta
@@ -137,6 +134,7 @@
     float lsp_pow_m_table2[(1 << LSP_POW_BITS)];
     DSPContext dsp;
     FmtConvertContext fmt_conv;
+    AVFloatDSPContext fdsp;
 
 #ifdef TRACE
     int frame_count;
diff --git a/libavcodec/wmadec.c b/libavcodec/wmadec.c
index 6bd1a82..f3ce474 100644
--- a/libavcodec/wmadec.c
+++ b/libavcodec/wmadec.c
@@ -48,20 +48,6 @@
 static void wma_lsp_to_curve_init(WMACodecContext *s, int frame_len);
 
 #ifdef TRACE
-static void dump_shorts(WMACodecContext *s, const char *name, const short *tab, int n)
-{
-    int i;
-
-    tprintf(s->avctx, "%s[%d]:\n", name, n);
-    for(i=0;i<n;i++) {
-        if ((i & 7) == 0)
-            tprintf(s->avctx, "%4d: ", i);
-        tprintf(s->avctx, " %5d.0", tab[i]);
-        if ((i & 7) == 7)
-            tprintf(s->avctx, "\n");
-    }
-}
-
 static void dump_floats(WMACodecContext *s, const char *name, int prec, const float *tab, int n)
 {
     int i;
@@ -112,7 +98,7 @@
 
     /* init MDCT */
     for(i = 0; i < s->nb_block_sizes; i++)
-        ff_mdct_init(&s->mdct_ctx[i], s->frame_len_bits - i + 1, 1, 1.0);
+        ff_mdct_init(&s->mdct_ctx[i], s->frame_len_bits - i + 1, 1, 1.0 / 32768.0);
 
     if (s->use_noise_coding) {
         init_vlc(&s->hgain_vlc, HGAINVLCBITS, sizeof(ff_wma_hgain_huffbits),
@@ -128,7 +114,7 @@
         wma_lsp_to_curve_init(s, s->frame_len);
     }
 
-    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
 
     avcodec_get_frame_defaults(&s->frame);
     avctx->coded_frame = &s->frame;
@@ -501,11 +487,11 @@
         return -1;
     }
 
-    if (s->nb_channels == 2) {
+    if (s->avctx->channels == 2) {
         s->ms_stereo = get_bits1(&s->gb);
     }
     v = 0;
-    for(ch = 0; ch < s->nb_channels; ch++) {
+    for(ch = 0; ch < s->avctx->channels; ch++) {
         a = get_bits1(&s->gb);
         s->channel_coded[ch] = a;
         v |= a;
@@ -532,13 +518,13 @@
 
     /* compute number of coefficients */
     n = s->coefs_end[bsize] - s->coefs_start;
-    for(ch = 0; ch < s->nb_channels; ch++)
+    for(ch = 0; ch < s->avctx->channels; ch++)
         nb_coefs[ch] = n;
 
     /* complex coding */
     if (s->use_noise_coding) {
 
-        for(ch = 0; ch < s->nb_channels; ch++) {
+        for(ch = 0; ch < s->avctx->channels; ch++) {
             if (s->channel_coded[ch]) {
                 int i, n, a;
                 n = s->exponent_high_sizes[bsize];
@@ -551,7 +537,7 @@
                 }
             }
         }
-        for(ch = 0; ch < s->nb_channels; ch++) {
+        for(ch = 0; ch < s->avctx->channels; ch++) {
             if (s->channel_coded[ch]) {
                 int i, n, val, code;
 
@@ -579,7 +565,7 @@
     /* exponents can be reused in short blocks. */
     if ((s->block_len_bits == s->frame_len_bits) ||
         get_bits1(&s->gb)) {
-        for(ch = 0; ch < s->nb_channels; ch++) {
+        for(ch = 0; ch < s->avctx->channels; ch++) {
             if (s->channel_coded[ch]) {
                 if (s->use_exp_vlc) {
                     if (decode_exp_vlc(s, ch) < 0)
@@ -593,7 +579,7 @@
     }
 
     /* parse spectral coefficients : just RLE encoding */
-    for(ch = 0; ch < s->nb_channels; ch++) {
+    for (ch = 0; ch < s->avctx->channels; ch++) {
         if (s->channel_coded[ch]) {
             int tindex;
             WMACoef* ptr = &s->coefs1[ch][0];
@@ -607,7 +593,7 @@
                   0, ptr, 0, nb_coefs[ch],
                   s->block_len, s->frame_len_bits, coef_nb_bits);
         }
-        if (s->version == 1 && s->nb_channels >= 2) {
+        if (s->version == 1 && s->avctx->channels >= 2) {
             align_get_bits(&s->gb);
         }
     }
@@ -622,7 +608,7 @@
     }
 
     /* finally compute the MDCT coefficients */
-    for(ch = 0; ch < s->nb_channels; ch++) {
+    for (ch = 0; ch < s->avctx->channels; ch++) {
         if (s->channel_coded[ch]) {
             WMACoef *coefs1;
             float *coefs, *exponents, mult, mult1, noise;
@@ -726,7 +712,7 @@
     }
 
 #ifdef TRACE
-    for(ch = 0; ch < s->nb_channels; ch++) {
+    for (ch = 0; ch < s->avctx->channels; ch++) {
         if (s->channel_coded[ch]) {
             dump_floats(s, "exponents", 3, s->exponents[ch], s->block_len);
             dump_floats(s, "coefs", 1, s->coefs[ch], s->block_len);
@@ -750,7 +736,7 @@
 next:
     mdct = &s->mdct_ctx[bsize];
 
-    for(ch = 0; ch < s->nb_channels; ch++) {
+    for (ch = 0; ch < s->avctx->channels; ch++) {
         int n4, index;
 
         n4 = s->block_len / 2;
@@ -774,10 +760,10 @@
 }
 
 /* decode a frame of frame_len samples */
-static int wma_decode_frame(WMACodecContext *s, int16_t *samples)
+static int wma_decode_frame(WMACodecContext *s, float **samples,
+                            int samples_offset)
 {
-    int ret, n, ch, incr;
-    const float *output[MAX_CHANNELS];
+    int ret, ch;
 
 #ifdef TRACE
     tprintf(s->avctx, "***decode_frame: %d size=%d\n", s->frame_count++, s->frame_len);
@@ -794,20 +780,19 @@
             break;
     }
 
-    /* convert frame to integer */
-    n = s->frame_len;
-    incr = s->nb_channels;
-    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++) {
+    for (ch = 0; ch < s->avctx->channels; ch++) {
+        /* copy current block to output */
+        memcpy(samples[ch] + samples_offset, s->frame_out[ch],
+               s->frame_len * sizeof(*s->frame_out[ch]));
         /* prepare for next block */
-        memmove(&s->frame_out[ch][0], &s->frame_out[ch][n], n * sizeof(float));
-    }
+        memmove(&s->frame_out[ch][0], &s->frame_out[ch][s->frame_len],
+                s->frame_len * sizeof(*s->frame_out[ch]));
 
 #ifdef TRACE
-    dump_shorts(s, "samples", samples, n * s->nb_channels);
+        dump_floats(s, "samples", 6, samples[ch] + samples_offset, s->frame_len);
 #endif
+    }
+
     return 0;
 }
 
@@ -819,7 +804,8 @@
     WMACodecContext *s = avctx->priv_data;
     int nb_frames, bit_offset, i, pos, len, ret;
     uint8_t *q;
-    int16_t *samples;
+    float **samples;
+    int samples_offset;
 
     tprintf(avctx, "***decode_superframe:\n");
 
@@ -827,14 +813,14 @@
         s->last_superframe_len = 0;
         return 0;
     }
-    if (buf_size < s->block_align) {
+    if (buf_size < avctx->block_align) {
         av_log(avctx, AV_LOG_ERROR,
                "Input packet size too small (%d < %d)\n",
-               buf_size, s->block_align);
+               buf_size, avctx->block_align);
         return AVERROR_INVALIDDATA;
     }
-    if(s->block_align)
-        buf_size = s->block_align;
+    if(avctx->block_align)
+        buf_size = avctx->block_align;
 
     init_get_bits(&s->gb, buf, buf_size*8);
 
@@ -852,7 +838,8 @@
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         return ret;
     }
-    samples = (int16_t *)s->frame.data[0];
+    samples = (float **)s->frame.extended_data;
+    samples_offset = 0;
 
     if (s->use_bit_reservoir) {
         bit_offset = get_bits(&s->gb, s->byte_offset_bits + 3);
@@ -886,9 +873,9 @@
                 skip_bits(&s->gb, s->last_bitoffset);
             /* this frame is stored in the last superframe and in the
                current one */
-            if (wma_decode_frame(s, samples) < 0)
+            if (wma_decode_frame(s, samples, samples_offset) < 0)
                 goto fail;
-            samples += s->nb_channels * s->frame_len;
+            samples_offset += s->frame_len;
             nb_frames--;
         }
 
@@ -903,9 +890,9 @@
 
         s->reset_block_lengths = 1;
         for(i=0;i<nb_frames;i++) {
-            if (wma_decode_frame(s, samples) < 0)
+            if (wma_decode_frame(s, samples, samples_offset) < 0)
                 goto fail;
-            samples += s->nb_channels * s->frame_len;
+            samples_offset += s->frame_len;
         }
 
         /* we copy the end of the frame in the last frame buffer */
@@ -921,14 +908,14 @@
         memcpy(s->last_superframe, buf + pos, len);
     } else {
         /* single frame decode */
-        if (wma_decode_frame(s, samples) < 0)
+        if (wma_decode_frame(s, samples, samples_offset) < 0)
             goto fail;
-        samples += s->nb_channels * s->frame_len;
+        samples_offset += s->frame_len;
     }
 
-    av_dlog(s->avctx, "%d %d %d %d outbytes:%d eaten:%d\n",
+    av_dlog(s->avctx, "%d %d %d %d outbytes:%td eaten:%d\n",
             s->frame_len_bits, s->block_len_bits, s->frame_len, s->block_len,
-            (int8_t *)samples - (int8_t *)data, s->block_align);
+            (int8_t *)samples - (int8_t *)data, avctx->block_align);
 
     *got_frame_ptr   = 1;
     *(AVFrame *)data = s->frame;
@@ -960,6 +947,8 @@
     .flush          = flush,
     .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Audio 1"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
+                                                      AV_SAMPLE_FMT_NONE },
 };
 #endif
 #if CONFIG_WMAV2_DECODER
@@ -974,5 +963,7 @@
     .flush          = flush,
     .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Audio 2"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
+                                                      AV_SAMPLE_FMT_NONE },
 };
 #endif
diff --git a/libavcodec/wmaenc.c b/libavcodec/wmaenc.c
index 835bc39..969ffc5 100644
--- a/libavcodec/wmaenc.c
+++ b/libavcodec/wmaenc.c
@@ -27,7 +27,7 @@
 
 static int encode_init(AVCodecContext * avctx){
     WMACodecContext *s = avctx->priv_data;
-    int i, flags1, flags2;
+    int i, flags1, flags2, block_align;
     uint8_t *extradata;
 
     s->avctx = avctx;
@@ -78,10 +78,11 @@
     for(i = 0; i < s->nb_block_sizes; i++)
         ff_mdct_init(&s->mdct_ctx[i], s->frame_len_bits - i + 1, 0, 1.0);
 
-    s->block_align     = avctx->bit_rate * (int64_t)s->frame_len /
+    block_align        = avctx->bit_rate * (int64_t)s->frame_len /
                          (avctx->sample_rate * 8);
-    s->block_align     = FFMIN(s->block_align, MAX_CODED_SUPERFRAME_SIZE);
-    avctx->block_align = s->block_align;
+    block_align        = FFMIN(block_align, MAX_CODED_SUPERFRAME_SIZE);
+    avctx->block_align = block_align;
+
     avctx->frame_size = avctx->delay = s->frame_len;
 
 #if FF_API_OLD_ENCODE_AUDIO
@@ -93,23 +94,24 @@
 }
 
 
-static void apply_window_and_mdct(AVCodecContext * avctx, const signed short * audio, int len) {
+static void apply_window_and_mdct(AVCodecContext * avctx, const AVFrame *frame)
+{
     WMACodecContext *s = avctx->priv_data;
+    float **audio      = (float **)frame->extended_data;
+    int len            = frame->nb_samples;
     int window_index= s->frame_len_bits - s->block_len_bits;
     FFTContext *mdct = &s->mdct_ctx[window_index];
-    int i, j, channel;
+    int ch;
     const float * win = s->windows[window_index];
     int window_len = 1 << s->block_len_bits;
-    float n = window_len/2;
+    float n = 2.0 * 32768.0 / window_len;
 
-    for (channel = 0; channel < avctx->channels; channel++) {
-        memcpy(s->output, s->frame_out[channel], sizeof(float)*window_len);
-        j = channel;
-        for (i = 0; i < len; i++, j += avctx->channels){
-            s->output[i+window_len]  = audio[j] / n * win[window_len - i - 1];
-            s->frame_out[channel][i] = audio[j] / n * win[i];
-        }
-        mdct->mdct_calc(mdct, s->coefs[channel], s->output);
+    for (ch = 0; ch < avctx->channels; ch++) {
+        memcpy(s->output, s->frame_out[ch], window_len * sizeof(*s->output));
+        s->fdsp.vector_fmul_scalar(s->frame_out[ch], audio[ch], n, len);
+        s->dsp.vector_fmul_reverse(&s->output[window_len], s->frame_out[ch], win, len);
+        s->fdsp.vector_fmul(s->frame_out[ch], s->frame_out[ch], win, len);
+        mdct->mdct_calc(mdct, s->coefs[ch], s->output);
     }
 }
 
@@ -183,7 +185,7 @@
 
     //FIXME factor
     v = s->coefs_end[bsize] - s->coefs_start;
-    for(ch = 0; ch < s->nb_channels; ch++)
+    for (ch = 0; ch < s->avctx->channels; ch++)
         nb_coefs[ch] = v;
     {
         int n4 = s->block_len / 2;
@@ -193,18 +195,18 @@
         }
     }
 
-    if (s->nb_channels == 2) {
+    if (s->avctx->channels == 2) {
         put_bits(&s->pb, 1, !!s->ms_stereo);
     }
 
-    for(ch = 0; ch < s->nb_channels; ch++) {
+    for (ch = 0; ch < s->avctx->channels; ch++) {
         s->channel_coded[ch] = 1; //FIXME only set channel_coded when needed, instead of always
         if (s->channel_coded[ch]) {
             init_exp(s, ch, fixed_exp);
         }
     }
 
-    for(ch = 0; ch < s->nb_channels; ch++) {
+    for (ch = 0; ch < s->avctx->channels; ch++) {
         if (s->channel_coded[ch]) {
             WMACoef *coefs1;
             float *coefs, *exponents, mult;
@@ -232,7 +234,7 @@
     }
 
     v = 0;
-    for(ch = 0; ch < s->nb_channels; ch++) {
+    for (ch = 0; ch < s->avctx->channels; ch++) {
         int a = s->channel_coded[ch];
         put_bits(&s->pb, 1, a);
         v |= a;
@@ -248,7 +250,7 @@
     coef_nb_bits= ff_wma_total_gain_to_bits(total_gain);
 
     if (s->use_noise_coding) {
-        for(ch = 0; ch < s->nb_channels; ch++) {
+        for (ch = 0; ch < s->avctx->channels; ch++) {
             if (s->channel_coded[ch]) {
                 int i, n;
                 n = s->exponent_high_sizes[bsize];
@@ -267,7 +269,7 @@
     }
 
     if (parse_exponents) {
-        for(ch = 0; ch < s->nb_channels; ch++) {
+        for (ch = 0; ch < s->avctx->channels; ch++) {
             if (s->channel_coded[ch]) {
                 if (s->use_exp_vlc) {
                     encode_exp_vlc(s, ch, fixed_exp);
@@ -281,7 +283,7 @@
         av_assert0(0); //FIXME not implemented
     }
 
-    for(ch = 0; ch < s->nb_channels; ch++) {
+    for (ch = 0; ch < s->avctx->channels; ch++) {
         if (s->channel_coded[ch]) {
             int run, tindex;
             WMACoef *ptr, *eptr;
@@ -319,7 +321,7 @@
             if(run)
                 put_bits(&s->pb, s->coef_vlcs[tindex]->huffbits[1], s->coef_vlcs[tindex]->huffcodes[1]);
         }
-        if (s->version == 1 && s->nb_channels >= 2) {
+        if (s->version == 1 && s->avctx->channels >= 2) {
             avpriv_align_put_bits(&s->pb);
         }
     }
@@ -338,20 +340,19 @@
 
     avpriv_align_put_bits(&s->pb);
 
-    return put_bits_count(&s->pb)/8 - s->block_align;
+    return put_bits_count(&s->pb) / 8 - s->avctx->block_align;
 }
 
 static int encode_superframe(AVCodecContext *avctx, AVPacket *avpkt,
                              const AVFrame *frame, int *got_packet_ptr)
 {
     WMACodecContext *s = avctx->priv_data;
-    const int16_t *samples = (const int16_t *)frame->data[0];
     int i, total_gain, ret, error;
 
     s->block_len_bits= s->frame_len_bits; //required by non variable block len
     s->block_len = 1 << s->block_len_bits;
 
-    apply_window_and_mdct(avctx, samples, frame->nb_samples);
+    apply_window_and_mdct(avctx, frame);
 
     if (s->ms_stereo) {
         float a, b;
@@ -379,18 +380,18 @@
     while(total_gain <= 128 && error > 0)
         error = encode_frame(s, s->coefs, avpkt->data, avpkt->size, total_gain++);
     av_assert0((put_bits_count(&s->pb) & 7) == 0);
-    i= s->block_align - (put_bits_count(&s->pb)+7)/8;
+    i= avctx->block_align - (put_bits_count(&s->pb)+7)/8;
     av_assert0(i>=0);
     while(i--)
         put_bits(&s->pb, 8, 'N');
 
     flush_put_bits(&s->pb);
-    av_assert0(put_bits_ptr(&s->pb) - s->pb.buf == s->block_align);
+    av_assert0(put_bits_ptr(&s->pb) - s->pb.buf == avctx->block_align);
 
     if (frame->pts != AV_NOPTS_VALUE)
         avpkt->pts = frame->pts - ff_samples_to_time_base(avctx, avctx->delay);
 
-    avpkt->size = s->block_align;
+    avpkt->size = avctx->block_align;
     *got_packet_ptr = 1;
     return 0;
 }
@@ -404,7 +405,7 @@
     .init           = encode_init,
     .encode2        = encode_superframe,
     .close          = ff_wma_end,
-    .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
+    .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLTP,
                                                      AV_SAMPLE_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Audio 1"),
 };
@@ -418,7 +419,7 @@
     .init           = encode_init,
     .encode2        = encode_superframe,
     .close          = ff_wma_end,
-    .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
+    .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLTP,
                                                      AV_SAMPLE_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Audio 2"),
 };
diff --git a/libavcodec/wmalosslessdec.c b/libavcodec/wmalosslessdec.c
index 6e5dcb8..749e41f 100644
--- a/libavcodec/wmalosslessdec.c
+++ b/libavcodec/wmalosslessdec.c
@@ -176,7 +176,7 @@
     WmallDecodeCtx *s  = avctx->priv_data;
     uint8_t *edata_ptr = avctx->extradata;
     unsigned int channel_mask;
-    int i, bits, log2_max_num_subframes;
+    int i, log2_max_num_subframes;
 
     s->avctx = avctx;
     init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
@@ -186,10 +186,10 @@
         channel_mask       = AV_RL32(edata_ptr +  2);
         s->bits_per_sample = AV_RL16(edata_ptr);
         if (s->bits_per_sample == 16)
-            avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+            avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
         else if (s->bits_per_sample == 24) {
-            avctx->sample_fmt = AV_SAMPLE_FMT_S32;
-            av_log_missing_feature(avctx, "bit-depth higher than 16", 0);
+            avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
+            av_log_missing_feature(avctx, "Bit-depth higher than 16", 0);
             return AVERROR_PATCHWELCOME;
         } else {
             av_log(avctx, AV_LOG_ERROR, "Unknown bit-depth: %d\n",
@@ -885,7 +885,7 @@
 
         s->do_arith_coding    = get_bits1(&s->gb);
         if (s->do_arith_coding) {
-            av_log_missing_feature(s->avctx, "arithmetic coding", 1);
+            av_log_missing_feature(s->avctx, "Arithmetic coding", 1);
             return AVERROR_PATCHWELCOME;
         }
         s->do_ac_filter       = get_bits1(&s->gb);
@@ -984,11 +984,9 @@
 
         for (j = 0; j < subframe_len; j++) {
             if (s->bits_per_sample == 16) {
-                *s->samples_16[c] = (int16_t) s->channel_residues[c][j] << padding_zeroes;
-                s->samples_16[c] += s->num_channels;
+                *s->samples_16[c]++ = (int16_t) s->channel_residues[c][j] << padding_zeroes;
             } else {
-                *s->samples_32[c] = s->channel_residues[c][j] << padding_zeroes;
-                s->samples_32[c] += s->num_channels;
+                *s->samples_32[c]++ = s->channel_residues[c][j] << padding_zeroes;
             }
         }
     }
@@ -1025,8 +1023,8 @@
         return ret;
     }
     for (i = 0; i < s->num_channels; i++) {
-        s->samples_16[i] = (int16_t *)s->frame.data[0] + i;
-        s->samples_32[i] = (int32_t *)s->frame.data[0] + i;
+        s->samples_16[i] = (int16_t *)s->frame.extended_data[i];
+        s->samples_32[i] = (int32_t *)s->frame.extended_data[i];
     }
 
     /* get frame length */
@@ -1296,4 +1294,7 @@
     .flush          = flush,
     .capabilities   = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1 | CODEC_CAP_DELAY,
     .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Audio Lossless"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
+                                                      AV_SAMPLE_FMT_S32P,
+                                                      AV_SAMPLE_FMT_NONE },
 };
diff --git a/libavcodec/wmaprodec.c b/libavcodec/wmaprodec.c
index b70e1f5..235425e 100644
--- a/libavcodec/wmaprodec.c
+++ b/libavcodec/wmaprodec.c
@@ -86,6 +86,7 @@
  * subframe in order to reconstruct the output samples.
  */
 
+#include "libavutil/float_dsp.h"
 #include "libavutil/intfloat.h"
 #include "libavutil/intreadwrite.h"
 #include "avcodec.h"
@@ -94,7 +95,6 @@
 #include "put_bits.h"
 #include "wmaprodata.h"
 #include "dsputil.h"
-#include "fmtconvert.h"
 #include "sinewin.h"
 #include "wma.h"
 #include "wma_common.h"
@@ -171,7 +171,7 @@
     AVCodecContext*  avctx;                         ///< codec context for av_log
     AVFrame          frame;                         ///< AVFrame for decoded output
     DSPContext       dsp;                           ///< accelerated DSP functions
-    FmtConvertContext fmt_conv;
+    AVFloatDSPContext fdsp;
     uint8_t          frame_data[MAX_FRAMESIZE +
                       FF_INPUT_BUFFER_PADDING_SIZE];///< compressed frame data
     PutBitContext    pb;                            ///< context for filling the frame_data buffer
@@ -186,7 +186,6 @@
     uint8_t          bits_per_sample;               ///< integer audio sample size for the unscaled IMDCT output (used to scale to [-1.0, 1.0])
     uint16_t         samples_per_frame;             ///< number of samples to output
     uint16_t         log2_frame_size;
-    int8_t           num_channels;                  ///< number of channels in the stream (same as AVCodecContext.num_channels)
     int8_t           lfe_channel;                   ///< lfe channel index
     uint8_t          max_num_subframes;
     uint8_t          subframe_len_bits;             ///< number of bits used for the subframe length
@@ -248,7 +247,7 @@
     PRINT("log2 frame size",     s->log2_frame_size);
     PRINT("max num subframes",   s->max_num_subframes);
     PRINT("len prefix",          s->len_prefix);
-    PRINT("num channels",        s->num_channels);
+    PRINT("num channels",        s->avctx->channels);
 }
 
 /**
@@ -283,10 +282,11 @@
 
     s->avctx = avctx;
     ff_dsputil_init(&s->dsp, avctx);
-    ff_fmt_convert_init(&s->fmt_conv, avctx);
+    avpriv_float_dsp_init(&s->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
+
     init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
 
-    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
+    avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
 
     if (avctx->extradata_size >= 18) {
         s->decode_flags    = AV_RL16(edata_ptr+14);
@@ -314,7 +314,7 @@
     bits = ff_wma_get_frame_len_bits(avctx->sample_rate, 3, s->decode_flags);
     if (bits > WMAPRO_BLOCK_MAX_BITS) {
         av_log_missing_feature(avctx, "14-bits block sizes", 1);
-        return AVERROR_INVALIDDATA;
+        return AVERROR_PATCHWELCOME;
     }
     s->samples_per_frame = 1 << bits;
 
@@ -346,18 +346,17 @@
         return AVERROR_INVALIDDATA;
     }
 
-    s->num_channels = avctx->channels;
-
-    if (s->num_channels < 0) {
-        av_log(avctx, AV_LOG_ERROR, "invalid number of channels %d\n", s->num_channels);
+    if (avctx->channels < 0) {
+        av_log(avctx, AV_LOG_ERROR, "invalid number of channels %d\n",
+               avctx->channels);
         return AVERROR_INVALIDDATA;
-    } else if (s->num_channels > WMAPRO_MAX_CHANNELS) {
+    } else if (avctx->channels > WMAPRO_MAX_CHANNELS) {
         av_log_ask_for_sample(avctx, "unsupported number of channels\n");
         return AVERROR_PATCHWELCOME;
     }
 
     /** init previous block len */
-    for (i = 0; i < s->num_channels; i++)
+    for (i = 0; i < avctx->channels; i++)
         s->channel[i].prev_block_len = s->samples_per_frame;
 
     /** extract lfe channel position */
@@ -417,6 +416,10 @@
         }
         s->sfb_offsets[i][band - 1] = subframe_len;
         s->num_sfb[i]               = band - 1;
+        if (s->num_sfb[i] <= 0) {
+            av_log(avctx, AV_LOG_ERROR, "num_sfb invalid\n");
+            return AVERROR_INVALIDDATA;
+        }
     }
 
 
@@ -534,7 +537,7 @@
 {
     uint16_t num_samples[WMAPRO_MAX_CHANNELS] = { 0 };/**< 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 channels_for_cur_subframe = s->avctx->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;
@@ -546,7 +549,7 @@
      */
 
     /** reset tiling information */
-    for (c = 0; c < s->num_channels; c++)
+    for (c = 0; c < s->avctx->channels; c++)
         s->channel[c].num_subframes = 0;
 
     if (s->max_num_subframes == 1 || get_bits1(&s->gb))
@@ -557,7 +560,7 @@
         int subframe_len;
 
         /** check which channels contain the subframe */
-        for (c = 0; c < s->num_channels; c++) {
+        for (c = 0; c < s->avctx->channels; c++) {
             if (num_samples[c] == min_channel_len) {
                 if (fixed_channel_layout || channels_for_cur_subframe == 1 ||
                    (min_channel_len == s->samples_per_frame - s->min_samples_per_subframe))
@@ -574,7 +577,7 @@
 
         /** add subframes to the individual channels and find new min_channel_len */
         min_channel_len += subframe_len;
-        for (c = 0; c < s->num_channels; c++) {
+        for (c = 0; c < s->avctx->channels; c++) {
             WMAProChannelCtx* chan = &s->channel[c];
 
             if (contains_subframe[c]) {
@@ -601,7 +604,7 @@
         }
     } while (min_channel_len < s->samples_per_frame);
 
-    for (c = 0; c < s->num_channels; c++) {
+    for (c = 0; c < s->avctx->channels; c++) {
         int i;
         int offset = 0;
         for (i = 0; i < s->channel[c].num_subframes; i++) {
@@ -627,8 +630,8 @@
     int i;
     int offset = 0;
     int8_t rotation_offset[WMAPRO_MAX_CHANNELS * WMAPRO_MAX_CHANNELS];
-    memset(chgroup->decorrelation_matrix, 0, s->num_channels *
-           s->num_channels * sizeof(*chgroup->decorrelation_matrix));
+    memset(chgroup->decorrelation_matrix, 0, s->avctx->channels *
+           s->avctx->channels * sizeof(*chgroup->decorrelation_matrix));
 
     for (i = 0; i < chgroup->num_channels * (chgroup->num_channels - 1) >> 1; i++)
         rotation_offset[i] = get_bits(&s->gb, 6);
@@ -681,7 +684,7 @@
 
     /** in the one channel case channel transforms are pointless */
     s->num_chgroups = 0;
-    if (s->num_channels > 1) {
+    if (s->avctx->channels > 1) {
         int remaining_channels = s->channels_for_cur_subframe;
 
         if (get_bits1(&s->gb)) {
@@ -727,7 +730,7 @@
                     }
                 } else {
                     chgroup->transform = 1;
-                    if (s->num_channels == 2) {
+                    if (s->avctx->channels == 2) {
                         chgroup->decorrelation_matrix[0] =  1.0;
                         chgroup->decorrelation_matrix[1] = -1.0;
                         chgroup->decorrelation_matrix[2] =  1.0;
@@ -1017,14 +1020,14 @@
                             (*ch)[y] = sum;
                         }
                     }
-                } else if (s->num_channels == 2) {
+                } else if (s->avctx->channels == 2) {
                     int len = FFMIN(sfb[1], s->subframe_len) - sfb[0];
-                    s->dsp.vector_fmul_scalar(ch_data[0] + sfb[0],
-                                              ch_data[0] + sfb[0],
-                                              181.0 / 128, len);
-                    s->dsp.vector_fmul_scalar(ch_data[1] + sfb[0],
-                                              ch_data[1] + sfb[0],
-                                              181.0 / 128, len);
+                    s->fdsp.vector_fmul_scalar(ch_data[0] + sfb[0],
+                                               ch_data[0] + sfb[0],
+                                               181.0 / 128, len);
+                    s->fdsp.vector_fmul_scalar(ch_data[1] + sfb[0],
+                                               ch_data[1] + sfb[0],
+                                               181.0 / 128, len);
                 }
             }
         }
@@ -1070,7 +1073,7 @@
     int offset = s->samples_per_frame;
     int subframe_len = s->samples_per_frame;
     int i;
-    int total_samples   = s->samples_per_frame * s->num_channels;
+    int total_samples   = s->samples_per_frame * s->avctx->channels;
     int transmit_coeffs = 0;
     int cur_subwoofer_cutoff;
 
@@ -1080,7 +1083,7 @@
         == the next block of the channel with the smallest number of
         decoded samples
     */
-    for (i = 0; i < s->num_channels; i++) {
+    for (i = 0; i < s->avctx->channels; i++) {
         s->channel[i].grouped = 0;
         if (offset > s->channel[i].decoded_samples) {
             offset = s->channel[i].decoded_samples;
@@ -1094,7 +1097,7 @@
 
     /** get a list of all channels that contain the estimated block */
     s->channels_for_cur_subframe = 0;
-    for (i = 0; i < s->num_channels; i++) {
+    for (i = 0; i < s->avctx->channels; i++) {
         const int cur_subframe = s->channel[i].cur_subframe;
         /** substract already processed samples */
         total_samples -= s->channel[i].decoded_samples;
@@ -1271,9 +1274,9 @@
                             s->channel[c].scale_factor_step;
                 const float quant = pow(10.0, exp / 20.0);
                 int start = s->cur_sfb_offsets[b];
-                s->dsp.vector_fmul_scalar(s->tmp + start,
-                                          s->channel[c].coeffs + start,
-                                          quant, end - start);
+                s->fdsp.vector_fmul_scalar(s->tmp + start,
+                                           s->channel[c].coeffs + start,
+                                           quant, end - start);
             }
 
             /** apply imdct (imdct_half == DCTIV with reverse) */
@@ -1310,8 +1313,6 @@
     int more_frames = 0;
     int len = 0;
     int i, ret;
-    const float *out_ptr[WMAPRO_MAX_CHANNELS];
-    float *samples;
 
     /** get frame length */
     if (s->len_prefix)
@@ -1326,9 +1327,9 @@
     }
 
     /** read postproc transform */
-    if (s->num_channels > 1 && get_bits1(gb)) {
+    if (s->avctx->channels > 1 && get_bits1(gb)) {
         if (get_bits1(gb)) {
-            for (i = 0; i < s->num_channels * s->num_channels; i++)
+            for (i = 0; i < avctx->channels * avctx->channels; i++)
                 skip_bits(gb, 4);
         }
     }
@@ -1363,7 +1364,7 @@
 
     /** reset subframe states */
     s->parsed_all_subframes = 0;
-    for (i = 0; i < s->num_channels; i++) {
+    for (i = 0; i < avctx->channels; i++) {
         s->channel[i].decoded_samples = 0;
         s->channel[i].cur_subframe    = 0;
         s->channel[i].reuse_sf        = 0;
@@ -1384,15 +1385,13 @@
         s->packet_loss = 1;
         return 0;
     }
-    samples = (float *)s->frame.data[0];
 
-    /** interleave samples and write them to the output buffer */
-    for (i = 0; i < s->num_channels; i++)
-        out_ptr[i] = s->channel[i].out;
-    s->fmt_conv.float_interleave(samples, out_ptr, s->samples_per_frame,
-                                 s->num_channels);
+    /** copy samples to the output buffer */
+    for (i = 0; i < avctx->channels; i++)
+        memcpy(s->frame.extended_data[i], s->channel[i].out,
+               s->samples_per_frame * sizeof(*s->channel[i].out));
 
-    for (i = 0; i < s->num_channels; i++) {
+    for (i = 0; i < avctx->channels; i++) {
         /** reuse second half of the IMDCT output for the next frame */
         memcpy(&s->channel[i].out[0],
                &s->channel[i].out[s->samples_per_frame],
@@ -1622,7 +1621,7 @@
     int i;
     /** reset output buffer as a part of it is used during the windowing of a
         new frame */
-    for (i = 0; i < s->num_channels; i++)
+    for (i = 0; i < avctx->channels; i++)
         memset(s->channel[i].out, 0, s->samples_per_frame *
                sizeof(*s->channel[i].out));
     s->packet_loss = 1;
@@ -1643,4 +1642,6 @@
     .capabilities   = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1,
     .flush          = flush,
     .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Audio 9 Professional"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
+                                                      AV_SAMPLE_FMT_NONE },
 };
diff --git a/libavcodec/wmavoice.c b/libavcodec/wmavoice.c
index ee87141..89b3094 100644
--- a/libavcodec/wmavoice.c
+++ b/libavcodec/wmavoice.c
@@ -27,6 +27,8 @@
 
 #include <math.h>
 
+#include "libavutil/channel_layout.h"
+#include "libavutil/mem.h"
 #include "dsputil.h"
 #include "avcodec.h"
 #include "get_bits.h"
@@ -36,7 +38,6 @@
 #include "acelp_vectors.h"
 #include "acelp_filters.h"
 #include "lsp.h"
-#include "libavutil/lzo.h"
 #include "dct.h"
 #include "rdft.h"
 #include "sinewin.h"
@@ -437,6 +438,8 @@
                                   2 * (s->block_conv_table[1] - 2 * s->min_pitch_val);
     s->block_pitch_nbits        = av_ceil_log2(s->block_pitch_range);
 
+    ctx->channels               = 1;
+    ctx->channel_layout         = AV_CH_LAYOUT_MONO;
     ctx->sample_fmt             = AV_SAMPLE_FMT_FLT;
 
     avcodec_get_frame_defaults(&s->frame);
@@ -1760,8 +1763,8 @@
      * are really WMAPro-in-WMAVoice-superframes. I've never seen those in
      * the wild yet. */
     if (!get_bits1(gb)) {
-        av_log_missing_feature(ctx, "WMAPro-in-WMAVoice support", 1);
-        return -1;
+        av_log_missing_feature(ctx, "WMAPro-in-WMAVoice", 1);
+        return AVERROR_PATCHWELCOME;
     }
 
     /* (optional) nr. of samples in superframe; always <= 480 and >= 0 */
diff --git a/libavcodec/wmv2enc.c b/libavcodec/wmv2enc.c
index e696d69..e6e1e67 100644
--- a/libavcodec/wmv2enc.c
+++ b/libavcodec/wmv2enc.c
@@ -219,6 +219,6 @@
     .init           = wmv2_encode_init,
     .encode2        = ff_MPV_encode_picture,
     .close          = ff_MPV_encode_end,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_YUV420P, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Video 8"),
 };
diff --git a/libavcodec/wnv1.c b/libavcodec/wnv1.c
index e7a8240..494dc98 100644
--- a/libavcodec/wnv1.c
+++ b/libavcodec/wnv1.c
@@ -26,7 +26,7 @@
 
 #include "avcodec.h"
 #include "get_bits.h"
-#include "libavutil/common.h"
+#include "mathops.h"
 
 
 typedef struct WNV1Context{
@@ -52,7 +52,7 @@
     int v = get_vlc2(&w->gb, code_vlc.table, CODE_VLC_BITS, 1);
 
     if(v==15)
-        return av_reverse[ get_bits(&w->gb, 8 - w->shift) ];
+        return ff_reverse[ get_bits(&w->gb, 8 - w->shift) ];
     else
         return base_value + ((v - 7)<<w->shift);
 }
@@ -66,7 +66,7 @@
     WNV1Context * const l = avctx->priv_data;
     AVFrame * const p = &l->pic;
     unsigned char *Y,*U,*V;
-    int i, j;
+    int i, j, ret;
     int prev_y = 0, prev_u = 0, prev_v = 0;
     uint8_t *rbuf;
 
@@ -78,22 +78,22 @@
     rbuf = av_malloc(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
     if(!rbuf){
         av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer\n");
-        return -1;
+        return AVERROR(ENOMEM);
     }
 
     if(p->data[0])
         avctx->release_buffer(avctx, p);
 
     p->reference = 0;
-    if(avctx->get_buffer(avctx, p) < 0){
+    if ((ret = avctx->get_buffer(avctx, p)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         av_free(rbuf);
-        return -1;
+        return ret;
     }
     p->key_frame = 1;
 
     for(i=8; i<buf_size; i++)
-        rbuf[i]= av_reverse[ buf[i] ];
+        rbuf[i]= ff_reverse[ buf[i] ];
     init_get_bits(&l->gb, rbuf+8, (buf_size-8)*8);
 
     if (buf[2] >> 4 == 6)
@@ -140,7 +140,7 @@
     static VLC_TYPE code_table[1 << CODE_VLC_BITS][2];
 
     l->avctx = avctx;
-    avctx->pix_fmt = PIX_FMT_YUV422P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV422P;
     avcodec_get_frame_defaults(&l->pic);
 
     code_vlc.table = code_table;
diff --git a/libavcodec/ws-snd1.c b/libavcodec/ws-snd1.c
index dfa02b6..7cc0678 100644
--- a/libavcodec/ws-snd1.c
+++ b/libavcodec/ws-snd1.c
@@ -20,6 +20,8 @@
  */
 
 #include <stdint.h>
+
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
 #include "libavutil/intreadwrite.h"
 #include "avcodec.h"
@@ -46,12 +48,9 @@
 {
     WSSndContext *s = avctx->priv_data;
 
-    if (avctx->channels != 1) {
-        av_log_ask_for_sample(avctx, "unsupported number of channels\n");
-        return AVERROR(EINVAL);
-    }
-
-    avctx->sample_fmt = AV_SAMPLE_FMT_U8;
+    avctx->channels       = 1;
+    avctx->channel_layout = AV_CH_LAYOUT_MONO;
+    avctx->sample_fmt     = AV_SAMPLE_FMT_U8;
 
     avcodec_get_frame_defaults(&s->frame);
     avctx->coded_frame = &s->frame;
@@ -85,7 +84,7 @@
 
     if (in_size > buf_size) {
         av_log(avctx, AV_LOG_ERROR, "Frame data is larger than input buffer\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     /* get output buffer */
diff --git a/libavcodec/x86/Makefile b/libavcodec/x86/Makefile
index 39d2727..66884a5 100644
--- a/libavcodec/x86/Makefile
+++ b/libavcodec/x86/Makefile
@@ -1,42 +1,43 @@
+OBJS                                   += x86/fmtconvert_init.o
+
+OBJS-$(CONFIG_AAC_DECODER)             += x86/sbrdsp_init.o
+OBJS-$(CONFIG_AC3DSP)                  += x86/ac3dsp_init.o
+OBJS-$(CONFIG_CAVS_DECODER)            += x86/cavsdsp.o
 OBJS-$(CONFIG_DNXHD_ENCODER)           += x86/dnxhdenc.o
+OBJS-$(CONFIG_FFT)                     += x86/fft_init.o
+OBJS-$(CONFIG_GPL)                     += x86/idct_mmx.o
+OBJS-$(CONFIG_H264DSP)                 += x86/h264dsp_init.o
+OBJS-$(CONFIG_H264PRED)                += x86/h264_intrapred_init.o
+OBJS-$(CONFIG_LPC)                     += x86/lpc.o
 OBJS-$(CONFIG_MLP_DECODER)             += x86/mlpdsp.o
+OBJS-$(CONFIG_MPEGAUDIODSP)            += x86/mpegaudiodec.o
 OBJS-$(CONFIG_MPEGVIDEO)               += x86/mpegvideo.o
 OBJS-$(CONFIG_MPEGVIDEOENC)            += x86/mpegvideoenc.o
+OBJS-$(CONFIG_PNG_DECODER)             += x86/pngdsp_init.o
+OBJS-$(CONFIG_PRORES_LGPL_DECODER)     += x86/proresdsp_init.o
+OBJS-$(CONFIG_RV30_DECODER)            += x86/rv34dsp_init.o
+OBJS-$(CONFIG_RV40_DECODER)            += x86/rv34dsp_init.o            \
+                                          x86/rv40dsp_init.o
+OBJS-$(CONFIG_V210_DECODER)            += x86/v210-init.o
 OBJS-$(CONFIG_TRUEHD_DECODER)          += x86/mlpdsp.o
+OBJS-$(CONFIG_VC1_DECODER)             += x86/vc1dsp_init.o
 OBJS-$(CONFIG_VP3DSP)                  += x86/vp3dsp_init.o
+OBJS-$(CONFIG_VP5_DECODER)             += x86/vp56dsp_init.o
+OBJS-$(CONFIG_VP6_DECODER)             += x86/vp56dsp_init.o
+OBJS-$(CONFIG_VP8_DECODER)             += x86/vp8dsp_init.o
 OBJS-$(CONFIG_XMM_CLOBBER_TEST)        += x86/w64xmmtest.o
 
 MMX-OBJS                               += x86/dsputil_mmx.o             \
                                           x86/fdct.o                    \
-                                          x86/fmtconvert_init.o         \
                                           x86/idct_mmx_xvid.o           \
                                           x86/idct_sse2_xvid.o          \
                                           x86/simple_idct.o             \
 
-MMX-OBJS-$(CONFIG_AAC_DECODER)         += x86/sbrdsp_init.o
-MMX-OBJS-$(CONFIG_AC3DSP)              += x86/ac3dsp_init.o
-MMX-OBJS-$(CONFIG_CAVS_DECODER)        += x86/cavsdsp.o
 MMX-OBJS-$(CONFIG_DWT)                 += x86/snowdsp.o \
                                           x86/dwt.o
 MMX-OBJS-$(CONFIG_ENCODERS)            += x86/dsputilenc_mmx.o          \
                                           x86/motion_est.o
-MMX-OBJS-$(CONFIG_FFT)                 += x86/fft_init.o
-MMX-OBJS-$(CONFIG_GPL)                 += x86/idct_mmx.o
-MMX-OBJS-$(CONFIG_H264DSP)             += x86/h264dsp_init.o
-MMX-OBJS-$(CONFIG_H264PRED)            += x86/h264_intrapred_init.o
-MMX-OBJS-$(CONFIG_LPC)                 += x86/lpc.o
-MMX-OBJS-$(CONFIG_MPEGAUDIODSP)        += x86/mpegaudiodec.o
-MMX-OBJS-$(CONFIG_PNG_DECODER)         += x86/pngdsp_init.o
-MMX-OBJS-$(CONFIG_PRORES_DECODER)      += x86/proresdsp_init.o
-MMX-OBJS-$(CONFIG_PRORES_LGPL_DECODER) += x86/proresdsp_init.o
-MMX-OBJS-$(CONFIG_RV30_DECODER)        += x86/rv34dsp_init.o
-MMX-OBJS-$(CONFIG_RV40_DECODER)        += x86/rv34dsp_init.o            \
-                                          x86/rv40dsp_init.o
-MMX-OBJS-$(CONFIG_V210_DECODER)        += x86/v210-init.o
 MMX-OBJS-$(CONFIG_VC1_DECODER)         += x86/vc1dsp_mmx.o
-MMX-OBJS-$(CONFIG_VP5_DECODER)         += x86/vp56dsp_init.o
-MMX-OBJS-$(CONFIG_VP6_DECODER)         += x86/vp56dsp_init.o
-MMX-OBJS-$(CONFIG_VP8_DECODER)         += x86/vp8dsp_init.o
 
 YASM-OBJS-$(CONFIG_AAC_DECODER)        += x86/sbrdsp.o
 YASM-OBJS-$(CONFIG_AC3DSP)             += x86/ac3dsp.o
@@ -55,7 +56,8 @@
                                           x86/h264_weight_10bit.o
 YASM-OBJS-$(CONFIG_H264PRED)           += x86/h264_intrapred.o          \
                                           x86/h264_intrapred_10bit.o
-YASM-OBJS-$(CONFIG_H264QPEL)           += x86/h264_qpel_10bit.o
+YASM-OBJS-$(CONFIG_H264QPEL)           += x86/h264_qpel_8bit.o          \
+                                          x86/h264_qpel_10bit.o
 YASM-OBJS-$(CONFIG_MPEGAUDIODSP)       += x86/imdct36.o
 YASM-OBJS-$(CONFIG_PNG_DECODER)        += x86/pngdsp.o
 YASM-OBJS-$(CONFIG_PRORES_DECODER)     += x86/proresdsp.o
diff --git a/libavcodec/x86/ac3dsp.asm b/libavcodec/x86/ac3dsp.asm
index b085eae..4958a7b 100644
--- a/libavcodec/x86/ac3dsp.asm
+++ b/libavcodec/x86/ac3dsp.asm
@@ -19,7 +19,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
@@ -42,8 +41,8 @@
 ; 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
+%macro AC3_EXPONENT_MIN 0
+cglobal ac3_exponent_min, 3, 4, 2, exp, reuse_blks, expn, offset
     shl  reuse_blksq, 8
     jz .end
     LOOP_ALIGN
@@ -64,20 +63,18 @@
     REP_RET
 %endmacro
 
-%define PMINUB PMINUB_MMX
 %define LOOP_ALIGN
-INIT_MMX
-AC3_EXPONENT_MIN mmx
+INIT_MMX mmx
+AC3_EXPONENT_MIN
 %if HAVE_MMXEXT_EXTERNAL
-%define PMINUB PMINUB_MMXEXT
 %define LOOP_ALIGN ALIGN 16
-AC3_EXPONENT_MIN mmxext
+INIT_MMX mmxext
+AC3_EXPONENT_MIN
 %endif
 %if HAVE_SSE2_EXTERNAL
-INIT_XMM
-AC3_EXPONENT_MIN sse2
+INIT_XMM sse2
+AC3_EXPONENT_MIN
 %endif
-%undef PMINUB
 %undef LOOP_ALIGN
 
 ;-----------------------------------------------------------------------------
@@ -100,7 +97,7 @@
     por         %1, %2
     pshuflw     %2, %1, q0001
     por         %1, %2
-%elif cpuflag(mmx2)
+%elif cpuflag(mmxext)
     pshufw      %2, %1, q0032
     por         %1, %2
     pshufw      %2, %1, q0001
@@ -156,8 +153,8 @@
 INIT_MMX mmx
 %define ABS2 ABS2_MMX
 AC3_MAX_MSB_ABS_INT16 or_abs
-INIT_MMX mmx2
-%define ABS2 ABS2_MMX2
+INIT_MMX mmxext
+%define ABS2 ABS2_MMXEXT
 AC3_MAX_MSB_ABS_INT16 min_max
 INIT_XMM sse2
 AC3_MAX_MSB_ABS_INT16 min_max
@@ -169,8 +166,8 @@
 ; 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
+%macro AC3_SHIFT 3 ; l/r, 16/32, shift instruction, instruction set
+cglobal ac3_%1shift_int%2, 3, 3, 5, src, len, shift
     movd      m0, shiftd
 .loop:
     mova      m1, [srcq         ]
@@ -196,19 +193,19 @@
 ; 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
+INIT_MMX mmx
+AC3_SHIFT l, 16, psllw
+INIT_XMM sse2
+AC3_SHIFT l, 16, psllw
 
 ;-----------------------------------------------------------------------------
 ; 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
+INIT_MMX mmx
+AC3_SHIFT r, 32, psrad
+INIT_XMM sse2
+AC3_SHIFT r, 32, psrad
 
 ;-----------------------------------------------------------------------------
 ; void ff_float_to_fixed24(int32_t *dst, const float *src, unsigned int len)
@@ -216,8 +213,8 @@
 
 ; 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
+INIT_MMX 3dnow
+cglobal float_to_fixed24, 3, 3, 0, dst, src, len
     movq   m0, [pf_1_24]
 .loop:
     movq   m1, [srcq   ]
@@ -243,8 +240,8 @@
     femms
     RET
 
-INIT_XMM
-cglobal float_to_fixed24_sse, 3,3,3, dst, src, len
+INIT_XMM sse
+cglobal float_to_fixed24, 3, 3, 3, dst, src, len
     movaps     m0, [pf_1_24]
 .loop:
     movaps     m1, [srcq   ]
@@ -268,8 +265,8 @@
     emms
     RET
 
-INIT_XMM
-cglobal float_to_fixed24_sse2, 3,3,9, dst, src, len
+INIT_XMM sse2
+cglobal float_to_fixed24, 3, 3, 9, dst, src, len
     movaps     m0, [pf_1_24]
 .loop:
     movaps     m1, [srcq    ]
@@ -333,8 +330,8 @@
     paddd    %1, %2
 %endmacro
 
-INIT_XMM
-cglobal ac3_compute_mantissa_size_sse2, 1,2,4, mant_cnt, sum
+INIT_XMM sse2
+cglobal ac3_compute_mantissa_size, 1, 2, 4, mant_cnt, sum
     movdqa      m0, [mant_cntq      ]
     movdqa      m1, [mant_cntq+ 1*16]
     paddw       m0, [mant_cntq+ 2*16]
@@ -374,20 +371,20 @@
 ; void ff_ac3_extract_exponents(uint8_t *exp, int32_t *coef, int nb_coefs)
 ;------------------------------------------------------------------------------
 
-%macro PABSD_MMX 2 ; src/dst, tmp
+%macro PABSD 1-2 ; src/dst, unused
+%if cpuflag(ssse3)
+    pabsd    %1, %1
+%else ; src/dst, tmp
     pxor     %2, %2
     pcmpgtd  %2, %1
     pxor     %1, %2
     psubd    %1, %2
-%endmacro
-
-%macro PABSD_SSSE3 1-2 ; src/dst, unused
-    pabsd    %1, %1
+%endif
 %endmacro
 
 %if HAVE_AMD3DNOW_EXTERNAL
-INIT_MMX
-cglobal ac3_extract_exponents_3dnow, 3,3,0, exp, coef, len
+INIT_MMX 3dnow
+cglobal ac3_extract_exponents, 3, 3, 0, exp, coef, len
     add      expq, lenq
     lea     coefq, [coefq+4*lenq]
     neg      lenq
@@ -396,8 +393,8 @@
 .loop:
     movq       m0, [coefq+4*lenq  ]
     movq       m1, [coefq+4*lenq+8]
-    PABSD_MMX  m0, m2
-    PABSD_MMX  m1, m2
+    PABSD      m0, m2
+    PABSD      m1, m2
     pslld      m0, 1
     por        m0, m3
     pi2fd      m2, m0
@@ -421,8 +418,8 @@
     REP_RET
 %endif
 
-%macro AC3_EXTRACT_EXPONENTS 1
-cglobal ac3_extract_exponents_%1, 3,3,4, exp, coef, len
+%macro AC3_EXTRACT_EXPONENTS 0
+cglobal ac3_extract_exponents, 3, 3, 4, exp, coef, len
     add     expq, lenq
     lea    coefq, [coefq+4*lenq]
     neg     lenq
@@ -454,11 +451,10 @@
 %endmacro
 
 %if HAVE_SSE2_EXTERNAL
-INIT_XMM
-%define PABSD PABSD_MMX
-AC3_EXTRACT_EXPONENTS sse2
-%if HAVE_SSSE3_EXTERNAL
-%define PABSD PABSD_SSSE3
-AC3_EXTRACT_EXPONENTS ssse3
+INIT_XMM sse2
+AC3_EXTRACT_EXPONENTS
 %endif
+%if HAVE_SSSE3_EXTERNAL
+INIT_XMM ssse3
+AC3_EXTRACT_EXPONENTS
 %endif
diff --git a/libavcodec/x86/ac3dsp_init.c b/libavcodec/x86/ac3dsp_init.c
index b1e8cfb..e95131e 100644
--- a/libavcodec/x86/ac3dsp_init.c
+++ b/libavcodec/x86/ac3dsp_init.c
@@ -31,7 +31,7 @@
 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_mmx2 (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);
 
@@ -182,7 +182,7 @@
     }
     if (EXTERNAL_MMXEXT(mm_flags)) {
         c->ac3_exponent_min = ff_ac3_exponent_min_mmxext;
-        c->ac3_max_msb_abs_int16 = ff_ac3_max_msb_abs_int16_mmx2;
+        c->ac3_max_msb_abs_int16 = ff_ac3_max_msb_abs_int16_mmxext;
     }
     if (EXTERNAL_SSE(mm_flags)) {
         c->float_to_fixed24 = ff_float_to_fixed24_sse;
diff --git a/libavcodec/x86/cavsdsp.c b/libavcodec/x86/cavsdsp.c
index 03a8b87..6a252e0 100644
--- a/libavcodec/x86/cavsdsp.c
+++ b/libavcodec/x86/cavsdsp.c
@@ -25,11 +25,13 @@
 #include "libavutil/common.h"
 #include "libavutil/cpu.h"
 #include "libavutil/x86/asm.h"
+#include "libavutil/x86/cpu.h"
 #include "libavcodec/dsputil.h"
 #include "libavcodec/cavsdsp.h"
 #include "dsputil_mmx.h"
+#include "config.h"
 
-#if HAVE_INLINE_ASM
+#if (HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE)
 
 /* in/out: mma=mma+mmb, mmb=mmb-mma */
 #define SUMSUB_BA( a, b ) \
@@ -428,32 +430,30 @@
 "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) \
+#define AVG_MMXEXT_OP(a, b, temp, size) \
 "mov" #size " " #b ", " #temp "   \n\t"\
 "pavgb " #temp ", " #a "          \n\t"\
 "mov" #size " " #a ", " #b "      \n\t"
 
-QPEL_CAVS(put_,       PUT_OP, 3dnow)
-QPEL_CAVS(avg_, AVG_3DNOW_OP, 3dnow)
-QPEL_CAVS(put_,       PUT_OP, mmx2)
-QPEL_CAVS(avg_,  AVG_MMX2_OP, mmx2)
+#endif /* (HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE) */
 
-CAVS_MC(put_, 8, 3dnow)
-CAVS_MC(put_, 16,3dnow)
-CAVS_MC(avg_, 8, 3dnow)
-CAVS_MC(avg_, 16,3dnow)
-CAVS_MC(put_, 8, mmx2)
-CAVS_MC(put_, 16,mmx2)
-CAVS_MC(avg_, 8, mmx2)
-CAVS_MC(avg_, 16,mmx2)
+#if HAVE_MMXEXT_INLINE
+QPEL_CAVS(put_,        PUT_OP, mmxext)
+QPEL_CAVS(avg_, AVG_MMXEXT_OP, mmxext)
 
-static void ff_cavsdsp_init_mmx2(CAVSDSPContext* c, AVCodecContext *avctx) {
+CAVS_MC(put_,  8, mmxext)
+CAVS_MC(put_, 16, mmxext)
+CAVS_MC(avg_,  8, mmxext)
+CAVS_MC(avg_, 16, mmxext)
+
+static void ff_cavsdsp_init_mmxext(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; \
-    c->PFX ## _pixels_tab[IDX][ 4] = ff_ ## PFX ## NUM ## _mc01_mmx2; \
-    c->PFX ## _pixels_tab[IDX][ 8] = ff_ ## PFX ## NUM ## _mc02_mmx2; \
-    c->PFX ## _pixels_tab[IDX][12] = ff_ ## PFX ## NUM ## _mc03_mmx2; \
+    c->PFX ## _pixels_tab[IDX][ 0] = ff_ ## PFX ## NUM ## _mc00_mmxext; \
+    c->PFX ## _pixels_tab[IDX][ 2] = ff_ ## PFX ## NUM ## _mc20_mmxext; \
+    c->PFX ## _pixels_tab[IDX][ 4] = ff_ ## PFX ## NUM ## _mc01_mmxext; \
+    c->PFX ## _pixels_tab[IDX][ 8] = ff_ ## PFX ## NUM ## _mc02_mmxext; \
+    c->PFX ## _pixels_tab[IDX][12] = ff_ ## PFX ## NUM ## _mc03_mmxext; \
 
     dspfunc(put_cavs_qpel, 0, 16);
     dspfunc(put_cavs_qpel, 1, 8);
@@ -463,10 +463,20 @@
     c->cavs_idct8_add = cavs_idct8_add_mmx;
     c->idct_perm = FF_TRANSPOSE_IDCT_PERM;
 }
+#endif /* HAVE_MMXEXT_INLINE */
+
+#if HAVE_AMD3DNOW_INLINE
+QPEL_CAVS(put_,       PUT_OP, 3dnow)
+QPEL_CAVS(avg_, AVG_3DNOW_OP, 3dnow)
+
+CAVS_MC(put_, 8, 3dnow)
+CAVS_MC(put_, 16,3dnow)
+CAVS_MC(avg_, 8, 3dnow)
+CAVS_MC(avg_, 16,3dnow)
 
 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][ 0] = ff_ ## PFX ## NUM ## _mc00_mmxext; \
     c->PFX ## _pixels_tab[IDX][ 2] = ff_ ## PFX ## NUM ## _mc20_3dnow; \
     c->PFX ## _pixels_tab[IDX][ 4] = ff_ ## PFX ## NUM ## _mc01_3dnow; \
     c->PFX ## _pixels_tab[IDX][ 8] = ff_ ## PFX ## NUM ## _mc02_3dnow; \
@@ -480,15 +490,16 @@
     c->cavs_idct8_add = cavs_idct8_add_mmx;
     c->idct_perm = FF_TRANSPOSE_IDCT_PERM;
 }
+#endif /* HAVE_AMD3DNOW_INLINE */
 
-#endif /* HAVE_INLINE_ASM */
-
-void ff_cavsdsp_init_mmx(CAVSDSPContext *c, AVCodecContext *avctx)
+av_cold void ff_cavsdsp_init_x86(CAVSDSPContext *c, AVCodecContext *avctx)
 {
     int mm_flags = av_get_cpu_flags();
 
-#if HAVE_INLINE_ASM
-    if (mm_flags & AV_CPU_FLAG_MMXEXT) ff_cavsdsp_init_mmx2(c, avctx);
+#if HAVE_MMXEXT_INLINE
+    if (mm_flags & AV_CPU_FLAG_MMXEXT) ff_cavsdsp_init_mmxext(c, avctx);
+#endif /* HAVE_MMXEXT_INLINE */
+#if HAVE_AMD3DNOW_INLINE
     if (mm_flags & AV_CPU_FLAG_3DNOW) ff_cavsdsp_init_3dnow(c, avctx);
-#endif /* HAVE_INLINE_ASM */
+#endif /* HAVE_AMD3DNOW_INLINE */
 }
diff --git a/libavcodec/x86/dct32.asm b/libavcodec/x86/dct32.asm
index 91ea493..6fd5ba3 100644
--- a/libavcodec/x86/dct32.asm
+++ b/libavcodec/x86/dct32.asm
@@ -19,7 +19,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA 32
diff --git a/libavcodec/x86/deinterlace.asm b/libavcodec/x86/deinterlace.asm
index bcc275b..3812dbe 100644
--- a/libavcodec/x86/deinterlace.asm
+++ b/libavcodec/x86/deinterlace.asm
@@ -20,7 +20,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
diff --git a/libavcodec/x86/diracdsp_mmx.c b/libavcodec/x86/diracdsp_mmx.c
index 2a040da..ee89295 100644
--- a/libavcodec/x86/diracdsp_mmx.c
+++ b/libavcodec/x86/diracdsp_mmx.c
@@ -78,7 +78,7 @@
 
 #if HAVE_MMXEXT_INLINE
     if (mm_flags & AV_CPU_FLAG_MMX2) {
-        PIXFUNC(avg, 0, mmx2);
+        PIXFUNC(avg, 0, mmxext);
     }
 #endif
 
diff --git a/libavcodec/x86/diracdsp_mmx.h b/libavcodec/x86/diracdsp_mmx.h
index 3d8e117..8985854 100644
--- a/libavcodec/x86/diracdsp_mmx.h
+++ b/libavcodec/x86/diracdsp_mmx.h
@@ -27,7 +27,7 @@
 
 DECL_DIRAC_PIXOP(put, mmx);
 DECL_DIRAC_PIXOP(avg, mmx);
-DECL_DIRAC_PIXOP(avg, mmx2);
+DECL_DIRAC_PIXOP(avg, mmxext);
 
 void ff_put_dirac_pixels16_sse2(uint8_t *dst, const uint8_t *src[5], int stride, int h);
 void ff_avg_dirac_pixels16_sse2(uint8_t *dst, const uint8_t *src[5], int stride, int h);
diff --git a/libavcodec/x86/diracdsp_yasm.asm b/libavcodec/x86/diracdsp_yasm.asm
index f5f32b3..d12fc64 100644
--- a/libavcodec/x86/diracdsp_yasm.asm
+++ b/libavcodec/x86/diracdsp_yasm.asm
@@ -18,7 +18,7 @@
 ;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "x86inc.asm"
+%include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
 pw_3: times 8 dw 3
diff --git a/libavcodec/x86/dsputil.asm b/libavcodec/x86/dsputil.asm
index af7669a..61b5cf3 100644
--- a/libavcodec/x86/dsputil.asm
+++ b/libavcodec/x86/dsputil.asm
@@ -19,8 +19,7 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
-%include "x86util.asm"
+%include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
 pb_f: times 16 db 15
@@ -34,9 +33,9 @@
 
 SECTION_TEXT
 
-%macro SCALARPRODUCT 1
+%macro SCALARPRODUCT 0
 ; int scalarproduct_int16(int16_t *v1, int16_t *v2, int order)
-cglobal scalarproduct_int16_%1, 3,3,3, v1, v2, order
+cglobal scalarproduct_int16, 3,3,3, v1, v2, order
     shl orderq, 1
     add v1q, orderq
     add v2q, orderq
@@ -63,7 +62,7 @@
     RET
 
 ; int scalarproduct_and_madd_int16(int16_t *v1, int16_t *v2, int16_t *v3, int order, int mul)
-cglobal scalarproduct_and_madd_int16_%1, 4,4,8, v1, v2, v3, order, mul
+cglobal scalarproduct_and_madd_int16, 4,4,8, v1, v2, v3, order, mul
     shl orderq, 1
     movd    m7, mulm
 %if mmsize == 16
@@ -108,10 +107,10 @@
     RET
 %endmacro
 
-INIT_MMX
-SCALARPRODUCT mmx2
-INIT_XMM
-SCALARPRODUCT sse2
+INIT_MMX mmxext
+SCALARPRODUCT
+INIT_XMM sse2
+SCALARPRODUCT
 
 %macro SCALARPRODUCT_LOOP 1
 align 16
@@ -159,7 +158,8 @@
 %endmacro
 
 ; int scalarproduct_and_madd_int16(int16_t *v1, int16_t *v2, int16_t *v3, int order, int mul)
-cglobal scalarproduct_and_madd_int16_ssse3, 4,5,10, v1, v2, v3, order, mul
+INIT_XMM ssse3
+cglobal scalarproduct_and_madd_int16, 4,5,10, v1, v2, v3, order, mul
     shl orderq, 1
     movd    m7, mulm
     pshuflw m7, m7, 0
@@ -208,48 +208,60 @@
 ;                            const int16_t *window, unsigned int len)
 ;-----------------------------------------------------------------------------
 
-%macro REVERSE_WORDS_MMXEXT 1-2
-    pshufw   %1, %1, 0x1B
-%endmacro
-
-%macro REVERSE_WORDS_SSE2 1-2
+%macro REVERSE_WORDS 1-2
+%if cpuflag(ssse3) && notcpuflag(atom)
+    pshufb  %1, %2
+%elif cpuflag(sse2)
     pshuflw  %1, %1, 0x1B
     pshufhw  %1, %1, 0x1B
     pshufd   %1, %1, 0x4E
+%elif cpuflag(mmxext)
+    pshufw   %1, %1, 0x1B
+%endif
 %endmacro
 
-%macro REVERSE_WORDS_SSSE3 2
-    pshufb  %1, %2
-%endmacro
-
+%macro MUL16FIXED 3
+%if cpuflag(ssse3) ; dst, src, unused
+; dst = ((dst * src) + (1<<14)) >> 15
+    pmulhrsw   %1, %2
+%elif cpuflag(mmxext) ; dst, src, temp
 ; 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
+%endif
 %endmacro
 
-; 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
+%macro APPLY_WINDOW_INT16 1 ; %1 bitexact version
+%if %1
+cglobal apply_window_int16, 4,5,6, output, input, window, offset, offset2
+%else
+cglobal apply_window_int16_round, 4,5,6, output, input, window, offset, offset2
+%endif
     lea     offset2q, [offsetq-mmsize]
-%if %2
-    mova          m5, [pd_16384]
-%elifidn %1, ssse3
+%if cpuflag(ssse3) && notcpuflag(atom)
     mova          m5, [pb_revwords]
     ALIGN 16
+%elif %1
+    mova          m5, [pd_16384]
 %endif
 .loop:
-%if %2
+%if cpuflag(ssse3)
+    ; 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
+%elif %1
     ; 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.
@@ -285,16 +297,6 @@
     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
@@ -314,22 +316,24 @@
     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
+INIT_MMX mmxext
+APPLY_WINDOW_INT16 0
+INIT_XMM sse2
+APPLY_WINDOW_INT16 0
+
+INIT_MMX mmxext
+APPLY_WINDOW_INT16 1
+INIT_XMM sse2
+APPLY_WINDOW_INT16 1
+INIT_XMM ssse3
+APPLY_WINDOW_INT16 1
+INIT_XMM ssse3, atom
+APPLY_WINDOW_INT16 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
+; void add_hfyu_median_prediction_mmxext(uint8_t *dst, const uint8_t *top, const uint8_t *diff, int w, int *left, int *left_top)
+INIT_MMX mmxext
+cglobal add_hfyu_median_prediction, 6,6,0, dst, top, diff, w, left, left_top
     movq    mm0, [topq]
     movq    mm2, mm0
     movd    mm4, [left_topq]
@@ -431,8 +435,8 @@
 %endmacro
 
 ; 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
+INIT_MMX ssse3
+cglobal add_hfyu_left_prediction, 3,3,7, dst, src, w, left
 .skip_prologue:
     mova    m5, [pb_7]
     mova    m4, [pb_zzzz3333zzzzbbbb]
@@ -441,8 +445,8 @@
     psllq   m0, 56
     ADD_HFYU_LEFT_LOOP 1, 1
 
-INIT_XMM
-cglobal add_hfyu_left_prediction_sse4, 3,3,7, dst, src, w, left
+INIT_XMM sse4
+cglobal add_hfyu_left_prediction, 3,3,7, dst, src, w, left
     mova    m5, [pb_f]
     mova    m6, [pb_zzzzzzzz77777777]
     mova    m4, [pb_zzzz3333zzzzbbbb]
@@ -461,7 +465,8 @@
 
 
 ; float scalarproduct_float_sse(const float *v1, const float *v2, int len)
-cglobal scalarproduct_float_sse, 3,3,2, v1, v2, offset
+INIT_XMM sse
+cglobal scalarproduct_float, 3,3,2, v1, v2, offset
     neg offsetq
     shl offsetq, 2
     sub v1q, offsetq
@@ -805,7 +810,7 @@
     mov        valh, vall
 %if %1 >= 8
     movd        mm0, vald
-%if cpuflag(mmx2)
+%if cpuflag(mmxext)
     pshufw      mm0, mm0, 0
 %else ; mmx
     punpcklwd   mm0, mm0
@@ -1119,11 +1124,9 @@
 %endmacro
 
 INIT_MMX mmx
-%define SPLATD SPLATD_MMX
 %define CLIPD CLIPD_MMX
 VECTOR_CLIP_INT32 0, 1, 0, 0
 INIT_XMM sse2
-%define SPLATD SPLATD_SSE2
 VECTOR_CLIP_INT32 6, 1, 0, 0, _int
 %define CLIPD CLIPD_SSE2
 VECTOR_CLIP_INT32 6, 2, 0, 1
@@ -1250,15 +1253,20 @@
 BUTTERFLIES_FLOAT_INTERLEAVE
 %endif
 
-INIT_XMM sse2
 ; %1 = aligned/unaligned
-%macro BSWAP_LOOPS_SSE2  1
+%macro BSWAP_LOOPS  1
     mov      r3, r2
     sar      r2, 3
     jz       .left4_%1
 .loop8_%1:
     mov%1    m0, [r1 +  0]
     mov%1    m1, [r1 + 16]
+%if cpuflag(ssse3)
+    pshufb   m0, m2
+    pshufb   m1, m2
+    mova     [r0 +  0], m0
+    mova     [r0 + 16], m1
+%else
     pshuflw  m0, m0, 10110001b
     pshuflw  m1, m1, 10110001b
     pshufhw  m0, m0, 10110001b
@@ -1273,8 +1281,9 @@
     por      m3, m1
     mova     [r0 +  0], m2
     mova     [r0 + 16], m3
-    add      r1, 32
+%endif
     add      r0, 32
+    add      r1, 32
     dec      r2
     jnz      .loop8_%1
 .left4_%1:
@@ -1282,6 +1291,10 @@
     and      r3, 4
     jz       .left
     mov%1    m0, [r1]
+%if cpuflag(ssse3)
+    pshufb   m0, m2
+    mova     [r0], m0
+%else
     pshuflw  m0, m0, 10110001b
     pshufhw  m0, m0, 10110001b
     mova     m2, m0
@@ -1289,72 +1302,29 @@
     psrlw    m2, 8
     por      m2, m0
     mova     [r0], m2
+%endif
     add      r1, 16
     add      r0, 16
 %endmacro
 
 ; void bswap_buf(uint32_t *dst, const uint32_t *src, int w);
-cglobal bswap32_buf, 3,4,5
-    mov      r3, r1
-    and      r3, 15
-    jz       .start_align
-    BSWAP_LOOPS_SSE2  u
-    jmp      .left
-.start_align:
-    BSWAP_LOOPS_SSE2  a
-.left:
-    and      r2, 3
-    jz       .end
-.loop2:
-    mov      r3d, [r1]
-    bswap    r3d
-    mov      [r0], r3d
-    add      r1, 4
-    add      r0, 4
-    dec      r2
-    jnz      .loop2
-.end:
-    RET
-
-; %1 = aligned/unaligned
-%macro BSWAP_LOOPS_SSSE3  1
-    mov      r3, r2
-    sar      r2, 3
-    jz       .left4_%1
-.loop8_%1:
-    mov%1    m0, [r1 +  0]
-    mov%1    m1, [r1 + 16]
-    pshufb   m0, m2
-    pshufb   m1, m2
-    mova     [r0 +  0], m0
-    mova     [r0 + 16], m1
-    add      r0, 32
-    add      r1, 32
-    dec      r2
-    jnz      .loop8_%1
-.left4_%1:
-    mov      r2, r3
-    and      r3, 4
-    jz       .left2
-    mov%1    m0, [r1]
-    pshufb   m0, m2
-    mova     [r0], m0
-    add      r1, 16
-    add      r0, 16
-%endmacro
-
-INIT_XMM ssse3
-; void bswap_buf(uint32_t *dst, const uint32_t *src, int w);
+%macro BSWAP32_BUF 0
+%if cpuflag(ssse3)
 cglobal bswap32_buf, 3,4,3
     mov      r3, r1
     mova     m2, [pb_bswap32]
+%else
+cglobal bswap32_buf, 3,4,5
+    mov      r3, r1
+%endif
     and      r3, 15
     jz       .start_align
-    BSWAP_LOOPS_SSSE3  u
-    jmp      .left2
+    BSWAP_LOOPS  u
+    jmp      .left
 .start_align:
-    BSWAP_LOOPS_SSSE3  a
-.left2:
+    BSWAP_LOOPS  a
+.left:
+%if cpuflag(ssse3)
     mov      r3, r2
     and      r2, 2
     jz       .left1
@@ -1369,6 +1339,255 @@
     mov      r2d, [r1]
     bswap    r2d
     mov      [r0], r2d
+%else
+    and      r2, 3
+    jz       .end
+.loop2:
+    mov      r3d, [r1]
+    bswap    r3d
+    mov      [r0], r3d
+    add      r1, 4
+    add      r0, 4
+    dec      r2
+    jnz      .loop2
+%endif
 .end:
     RET
+%endmacro
 
+INIT_XMM sse2
+BSWAP32_BUF
+
+INIT_XMM ssse3
+BSWAP32_BUF
+
+%macro op_avgh 3
+    movh   %3, %2
+    pavgb  %1, %3
+    movh   %2, %1
+%endmacro
+
+%macro op_avg 2
+    pavgb  %1, %2
+    mova   %2, %1
+%endmacro
+
+%macro op_puth 2-3
+    movh   %2, %1
+%endmacro
+
+%macro op_put 2
+    mova   %2, %1
+%endmacro
+
+; void pixels4_l2_mmxext(uint8_t *dst, uint8_t *src1, uint8_t *src2, int dstStride, int src1Stride, int h)
+%macro PIXELS4_L2 1
+%define OP op_%1h
+cglobal %1_pixels4_l2, 6,6
+    movsxdifnidn r3, r3d
+    movsxdifnidn r4, r4d
+    test        r5d, 1
+    je        .loop
+    movd         m0, [r1]
+    movd         m1, [r2]
+    add          r1, r4
+    add          r2, 4
+    pavgb        m0, m1
+    OP           m0, [r0], m3
+    add          r0, r3
+    dec         r5d
+.loop:
+    mova         m0, [r1]
+    mova         m1, [r1+r4]
+    lea          r1, [r1+2*r4]
+    pavgb        m0, [r2]
+    pavgb        m1, [r2+4]
+    OP           m0, [r0], m3
+    OP           m1, [r0+r3], m3
+    lea          r0, [r0+2*r3]
+    mova         m0, [r1]
+    mova         m1, [r1+r4]
+    lea          r1, [r1+2*r4]
+    pavgb        m0, [r2+8]
+    pavgb        m1, [r2+12]
+    OP           m0, [r0], m3
+    OP           m1, [r0+r3], m3
+    lea          r0, [r0+2*r3]
+    add          r2, 16
+    sub         r5d, 4
+    jne       .loop
+    REP_RET
+%endmacro
+
+INIT_MMX mmxext
+PIXELS4_L2 put
+PIXELS4_L2 avg
+
+; void pixels8_l2_mmxext(uint8_t *dst, uint8_t *src1, uint8_t *src2, int dstStride, int src1Stride, int h)
+%macro PIXELS8_L2 1
+%define OP op_%1
+cglobal %1_pixels8_l2, 6,6
+    movsxdifnidn r3, r3d
+    movsxdifnidn r4, r4d
+    test        r5d, 1
+    je        .loop
+    mova         m0, [r1]
+    mova         m1, [r2]
+    add          r1, r4
+    add          r2, 8
+    pavgb        m0, m1
+    OP           m0, [r0]
+    add          r0, r3
+    dec         r5d
+.loop:
+    mova         m0, [r1]
+    mova         m1, [r1+r4]
+    lea          r1, [r1+2*r4]
+    pavgb        m0, [r2]
+    pavgb        m1, [r2+8]
+    OP           m0, [r0]
+    OP           m1, [r0+r3]
+    lea          r0, [r0+2*r3]
+    mova         m0, [r1]
+    mova         m1, [r1+r4]
+    lea          r1, [r1+2*r4]
+    pavgb        m0, [r2+16]
+    pavgb        m1, [r2+24]
+    OP           m0, [r0]
+    OP           m1, [r0+r3]
+    lea          r0, [r0+2*r3]
+    add          r2, 32
+    sub         r5d, 4
+    jne       .loop
+    REP_RET
+%endmacro
+
+INIT_MMX mmxext
+PIXELS8_L2 put
+PIXELS8_L2 avg
+
+; void pixels16_l2_mmxext(uint8_t *dst, uint8_t *src1, uint8_t *src2, int dstStride, int src1Stride, int h)
+%macro PIXELS16_L2 1
+%define OP op_%1
+cglobal %1_pixels16_l2, 6,6
+    movsxdifnidn r3, r3d
+    movsxdifnidn r4, r4d
+    test        r5d, 1
+    je        .loop
+    mova         m0, [r1]
+    mova         m1, [r1+8]
+    pavgb        m0, [r2]
+    pavgb        m1, [r2+8]
+    add          r1, r4
+    add          r2, 16
+    OP           m0, [r0]
+    OP           m1, [r0+8]
+    add          r0, r3
+    dec         r5d
+.loop:
+    mova         m0, [r1]
+    mova         m1, [r1+8]
+    add          r1, r4
+    pavgb        m0, [r2]
+    pavgb        m1, [r2+8]
+    OP           m0, [r0]
+    OP           m1, [r0+8]
+    add          r0, r3
+    mova         m0, [r1]
+    mova         m1, [r1+8]
+    add          r1, r4
+    pavgb        m0, [r2+16]
+    pavgb        m1, [r2+24]
+    OP           m0, [r0]
+    OP           m1, [r0+8]
+    add          r0, r3
+    add          r2, 32
+    sub         r5d, 2
+    jne       .loop
+    REP_RET
+%endmacro
+
+INIT_MMX mmxext
+PIXELS16_L2 put
+PIXELS16_L2 avg
+
+INIT_MMX mmxext
+; void pixels(uint8_t *block, const uint8_t *pixels, int line_size, int h)
+%macro PIXELS48 2
+%if %2 == 4
+%define OP movh
+%else
+%define OP mova
+%endif
+cglobal %1_pixels%2, 4,5
+    movsxdifnidn r2, r2d
+    lea          r4, [r2*3]
+.loop:
+    OP           m0, [r1]
+    OP           m1, [r1+r2]
+    OP           m2, [r1+r2*2]
+    OP           m3, [r1+r4]
+    lea          r1, [r1+r2*4]
+%ifidn %1, avg
+    pavgb        m0, [r0]
+    pavgb        m1, [r0+r2]
+    pavgb        m2, [r0+r2*2]
+    pavgb        m3, [r0+r4]
+%endif
+    OP         [r0], m0
+    OP      [r0+r2], m1
+    OP    [r0+r2*2], m2
+    OP      [r0+r4], m3
+    sub         r3d, 4
+    lea          r0, [r0+r2*4]
+    jne       .loop
+    RET
+%endmacro
+
+PIXELS48 put, 4
+PIXELS48 avg, 4
+PIXELS48 put, 8
+PIXELS48 avg, 8
+
+INIT_XMM sse2
+; void put_pixels16_sse2(uint8_t *block, const uint8_t *pixels, int line_size, int h)
+cglobal put_pixels16, 4,5,4
+    movsxdifnidn r2, r2d
+    lea          r4, [r2*3]
+.loop:
+    movu         m0, [r1]
+    movu         m1, [r1+r2]
+    movu         m2, [r1+r2*2]
+    movu         m3, [r1+r4]
+    lea          r1, [r1+r2*4]
+    mova       [r0], m0
+    mova    [r0+r2], m1
+    mova  [r0+r2*2], m2
+    mova    [r0+r4], m3
+    sub         r3d, 4
+    lea          r0, [r0+r2*4]
+    jnz       .loop
+    REP_RET
+
+; void avg_pixels16_sse2(uint8_t *block, const uint8_t *pixels, int line_size, int h)
+cglobal avg_pixels16, 4,5,4
+    movsxdifnidn r2, r2d
+    lea          r4, [r2*3]
+.loop:
+    movu         m0, [r1]
+    movu         m1, [r1+r2]
+    movu         m2, [r1+r2*2]
+    movu         m3, [r1+r4]
+    lea          r1, [r1+r2*4]
+    pavgb        m0, [r0]
+    pavgb        m1, [r0+r2]
+    pavgb        m2, [r0+r2*2]
+    pavgb        m3, [r0+r4]
+    mova       [r0], m0
+    mova    [r0+r2], m1
+    mova  [r0+r2*2], m2
+    mova    [r0+r4], m3
+    sub         r3d, 4
+    lea          r0, [r0+r2*4]
+    jnz       .loop
+    REP_RET
diff --git a/libavcodec/x86/dsputil_avg_template.c b/libavcodec/x86/dsputil_avg_template.c
index 6f76859..17f8955 100644
--- a/libavcodec/x86/dsputil_avg_template.c
+++ b/libavcodec/x86/dsputil_avg_template.c
@@ -1,5 +1,5 @@
 /*
- * DSP utils : average functions are compiled twice for 3dnow/mmx2
+ * DSP utils : average functions are compiled twice for 3dnow/mmxext
  * Copyright (c) 2000, 2001 Fabrice Bellard
  * Copyright (c) 2002-2004 Michael Niedermayer
  *
@@ -55,57 +55,7 @@
         :"%"REG_a, "memory");
 }
 
-static void DEF(put_pixels4_l2)(uint8_t *dst, uint8_t *src1, uint8_t *src2, int dstStride, int src1Stride, int h)
-{
-    __asm__ volatile(
-        "testl $1, %0                   \n\t"
-            " jz 1f                     \n\t"
-        "movd   (%1), %%mm0             \n\t"
-        "movd   (%2), %%mm1             \n\t"
-        "add    %4, %1                  \n\t"
-        "add    $4, %2                  \n\t"
-        PAVGB" %%mm1, %%mm0             \n\t"
-        "movd   %%mm0, (%3)             \n\t"
-        "add    %5, %3                  \n\t"
-        "decl   %0                      \n\t"
-        "1:                             \n\t"
-        "movd   (%1), %%mm0             \n\t"
-        "add    %4, %1                  \n\t"
-        "movd   (%1), %%mm1             \n\t"
-        "movd   (%2), %%mm2             \n\t"
-        "movd   4(%2), %%mm3            \n\t"
-        "add    %4, %1                  \n\t"
-        PAVGB" %%mm2, %%mm0             \n\t"
-        PAVGB" %%mm3, %%mm1             \n\t"
-        "movd   %%mm0, (%3)             \n\t"
-        "add    %5, %3                  \n\t"
-        "movd   %%mm1, (%3)             \n\t"
-        "add    %5, %3                  \n\t"
-        "movd   (%1), %%mm0             \n\t"
-        "add    %4, %1                  \n\t"
-        "movd   (%1), %%mm1             \n\t"
-        "movd   8(%2), %%mm2            \n\t"
-        "movd   12(%2), %%mm3           \n\t"
-        "add    %4, %1                  \n\t"
-        PAVGB" %%mm2, %%mm0             \n\t"
-        PAVGB" %%mm3, %%mm1             \n\t"
-        "movd   %%mm0, (%3)             \n\t"
-        "add    %5, %3                  \n\t"
-        "movd   %%mm1, (%3)             \n\t"
-        "add    %5, %3                  \n\t"
-        "add    $16, %2                 \n\t"
-        "subl   $4, %0                  \n\t"
-        "jnz    1b                      \n\t"
-#if !HAVE_EBX_AVAILABLE //Note "+bm" and "+mb" are buggy too (with gcc 3.2.2 at least) and cannot be used
-        :"+m"(h), "+a"(src1), "+c"(src2), "+d"(dst)
-#else
-        :"+b"(h), "+a"(src1), "+c"(src2), "+d"(dst)
-#endif
-        :"S"((x86_reg)src1Stride), "D"((x86_reg)dstStride)
-        :"memory");
-}
-
-
+#ifndef SKIP_FOR_3DNOW
 static void DEF(put_pixels8_l2)(uint8_t *dst, uint8_t *src1, uint8_t *src2, int dstStride, int src1Stride, int h)
 {
     __asm__ volatile(
@@ -226,58 +176,6 @@
         :"memory");*/
 }
 
-static void DEF(avg_pixels4_l2)(uint8_t *dst, uint8_t *src1, uint8_t *src2, int dstStride, int src1Stride, int h)
-{
-    __asm__ volatile(
-        "testl $1, %0                   \n\t"
-            " jz 1f                     \n\t"
-        "movd   (%1), %%mm0             \n\t"
-        "movd   (%2), %%mm1             \n\t"
-        "add    %4, %1                  \n\t"
-        "add    $4, %2                  \n\t"
-        PAVGB" %%mm1, %%mm0             \n\t"
-        PAVGB" (%3), %%mm0              \n\t"
-        "movd   %%mm0, (%3)             \n\t"
-        "add    %5, %3                  \n\t"
-        "decl   %0                      \n\t"
-        "1:                             \n\t"
-        "movd   (%1), %%mm0             \n\t"
-        "add    %4, %1                  \n\t"
-        "movd   (%1), %%mm1             \n\t"
-        "add    %4, %1                  \n\t"
-        PAVGB" (%2), %%mm0              \n\t"
-        PAVGB" 4(%2), %%mm1             \n\t"
-        PAVGB" (%3), %%mm0              \n\t"
-        "movd   %%mm0, (%3)             \n\t"
-        "add    %5, %3                  \n\t"
-        PAVGB" (%3), %%mm1              \n\t"
-        "movd   %%mm1, (%3)             \n\t"
-        "add    %5, %3                  \n\t"
-        "movd   (%1), %%mm0             \n\t"
-        "add    %4, %1                  \n\t"
-        "movd   (%1), %%mm1             \n\t"
-        "add    %4, %1                  \n\t"
-        PAVGB" 8(%2), %%mm0             \n\t"
-        PAVGB" 12(%2), %%mm1            \n\t"
-        PAVGB" (%3), %%mm0              \n\t"
-        "movd   %%mm0, (%3)             \n\t"
-        "add    %5, %3                  \n\t"
-        PAVGB" (%3), %%mm1              \n\t"
-        "movd   %%mm1, (%3)             \n\t"
-        "add    %5, %3                  \n\t"
-        "add    $16, %2                 \n\t"
-        "subl   $4, %0                  \n\t"
-        "jnz    1b                      \n\t"
-#if !HAVE_EBX_AVAILABLE //Note "+bm" and "+mb" are buggy too (with gcc 3.2.2 at least) and cannot be used
-        :"+m"(h), "+a"(src1), "+c"(src2), "+d"(dst)
-#else
-        :"+b"(h), "+a"(src1), "+c"(src2), "+d"(dst)
-#endif
-        :"S"((x86_reg)src1Stride), "D"((x86_reg)dstStride)
-        :"memory");
-}
-
-
 static void DEF(avg_pixels8_l2)(uint8_t *dst, uint8_t *src1, uint8_t *src2, int dstStride, int src1Stride, int h)
 {
     __asm__ volatile(
@@ -332,6 +230,7 @@
         :"r"(src1Stride), "r"(dstStride)
         :"memory");*/
 }
+#endif /* SKIP_FOR_3DNOW */
 
 static void DEF(put_pixels16_x2)(uint8_t *block, const uint8_t *pixels, int line_size, int h)
 {
@@ -373,6 +272,7 @@
         :"%"REG_a, "memory");
 }
 
+#ifndef SKIP_FOR_3DNOW
 static void DEF(put_pixels16_l2)(uint8_t *dst, uint8_t *src1, uint8_t *src2, int dstStride, int src1Stride, int h)
 {
     __asm__ volatile(
@@ -547,6 +447,7 @@
         :"r"(src1Stride), "r"(dstStride)
         :"memory");*/
 }
+#endif /* SKIP_FOR_3DNOW */
 
 /* GL: this function does incorrect rounding if overflow */
 static void DEF(put_no_rnd_pixels8_x2)(uint8_t *block, const uint8_t *pixels, int line_size, int h)
@@ -872,31 +773,6 @@
         :"%"REG_a,  "memory");
 }
 
-static void DEF(avg_pixels4)(uint8_t *block, const uint8_t *pixels, int line_size, int h)
-{
-    do {
-        __asm__ volatile(
-            "movd (%1), %%mm0               \n\t"
-            "movd (%1, %2), %%mm1           \n\t"
-            "movd (%1, %2, 2), %%mm2        \n\t"
-            "movd (%1, %3), %%mm3           \n\t"
-            PAVGB" (%0), %%mm0              \n\t"
-            PAVGB" (%0, %2), %%mm1          \n\t"
-            PAVGB" (%0, %2, 2), %%mm2       \n\t"
-            PAVGB" (%0, %3), %%mm3          \n\t"
-            "movd %%mm0, (%1)               \n\t"
-            "movd %%mm1, (%1, %2)           \n\t"
-            "movd %%mm2, (%1, %2, 2)        \n\t"
-            "movd %%mm3, (%1, %3)           \n\t"
-            ::"S"(pixels), "D"(block),
-             "r" ((x86_reg)line_size), "r"((x86_reg)3L*line_size)
-            :"memory");
-        block += 4*line_size;
-        pixels += 4*line_size;
-        h -= 4;
-    } while(h > 0);
-}
-
 //FIXME the following could be optimized too ...
 static void DEF(put_no_rnd_pixels16_x2)(uint8_t *block, const uint8_t *pixels, int line_size, int h){
     DEF(put_no_rnd_pixels8_x2)(block  , pixels  , line_size, h);
@@ -968,6 +844,7 @@
     );\
 }
 
+#ifndef SKIP_FOR_3DNOW
 #define STORE_OP(a,b) PAVGB" "#a","#b" \n\t"
 QPEL_2TAP_L3(avg_)
 #undef STORE_OP
@@ -975,3 +852,4 @@
 QPEL_2TAP_L3(put_)
 #undef STORE_OP
 #undef QPEL_2TAP_L3
+#endif /* SKIP_FOR_3DNOW */
diff --git a/libavcodec/x86/dsputil_mmx.c b/libavcodec/x86/dsputil_mmx.c
index c36a027..3fb9d21 100644
--- a/libavcodec/x86/dsputil_mmx.c
+++ b/libavcodec/x86/dsputil_mmx.c
@@ -198,19 +198,21 @@
 #define DEF(x) x ## _3dnow
 #define PAVGB "pavgusb"
 #define OP_AVG PAVGB
+#define SKIP_FOR_3DNOW
 
 #include "dsputil_avg_template.c"
 
 #undef DEF
 #undef PAVGB
 #undef OP_AVG
+#undef SKIP_FOR_3DNOW
 
 /***********************************/
-/* MMX2 specific */
+/* MMXEXT specific */
 
-#define DEF(x) x ## _mmx2
+#define DEF(x) x ## _mmxext
 
-/* Introduced only in MMX2 set */
+/* Introduced only in MMXEXT set */
 #define PAVGB "pavgb"
 #define OP_AVG PAVGB
 
@@ -222,16 +224,11 @@
 
 #define put_no_rnd_pixels16_mmx put_pixels16_mmx
 #define put_no_rnd_pixels8_mmx put_pixels8_mmx
-#define put_pixels16_mmx2 put_pixels16_mmx
-#define put_pixels8_mmx2 put_pixels8_mmx
-#define put_pixels4_mmx2 put_pixels4_mmx
-#define put_no_rnd_pixels16_mmx2 put_no_rnd_pixels16_mmx
-#define put_no_rnd_pixels8_mmx2 put_no_rnd_pixels8_mmx
-#define put_pixels16_3dnow put_pixels16_mmx
-#define put_pixels8_3dnow put_pixels8_mmx
-#define put_pixels4_3dnow put_pixels4_mmx
-#define put_no_rnd_pixels16_3dnow put_no_rnd_pixels16_mmx
-#define put_no_rnd_pixels8_3dnow put_no_rnd_pixels8_mmx
+#define put_pixels16_mmxext put_pixels16_mmx
+#define put_pixels8_mmxext put_pixels8_mmx
+#define put_pixels4_mmxext put_pixels4_mmx
+#define put_no_rnd_pixels16_mmxext put_no_rnd_pixels16_mmx
+#define put_no_rnd_pixels8_mmxext put_no_rnd_pixels8_mmx
 
 /***********************************/
 /* standard MMX */
@@ -370,33 +367,6 @@
     } while (--i);
 }
 
-static void put_pixels4_mmx(uint8_t *block, const uint8_t *pixels,
-                            int line_size, int h)
-{
-    __asm__ volatile (
-        "lea   (%3, %3), %%"REG_a"      \n\t"
-        ".p2align     3                 \n\t"
-        "1:                             \n\t"
-        "movd  (%1    ), %%mm0          \n\t"
-        "movd  (%1, %3), %%mm1          \n\t"
-        "movd     %%mm0, (%2)           \n\t"
-        "movd     %%mm1, (%2, %3)       \n\t"
-        "add  %%"REG_a", %1             \n\t"
-        "add  %%"REG_a", %2             \n\t"
-        "movd  (%1    ), %%mm0          \n\t"
-        "movd  (%1, %3), %%mm1          \n\t"
-        "movd     %%mm0, (%2)           \n\t"
-        "movd     %%mm1, (%2, %3)       \n\t"
-        "add  %%"REG_a", %1             \n\t"
-        "add  %%"REG_a", %2             \n\t"
-        "subl        $4, %0             \n\t"
-        "jnz         1b                 \n\t"
-        : "+g"(h), "+r"(pixels),  "+r"(block)
-        : "r"((x86_reg)line_size)
-        : "%"REG_a, "memory"
-        );
-}
-
 static void put_pixels8_mmx(uint8_t *block, const uint8_t *pixels,
                             int line_size, int h)
 {
@@ -459,56 +429,6 @@
         );
 }
 
-static void put_pixels16_sse2(uint8_t *block, const uint8_t *pixels,
-                              int line_size, int h)
-{
-    __asm__ volatile (
-        "1:                              \n\t"
-        "movdqu (%1       ), %%xmm0      \n\t"
-        "movdqu (%1, %3   ), %%xmm1      \n\t"
-        "movdqu (%1, %3, 2), %%xmm2      \n\t"
-        "movdqu (%1, %4   ), %%xmm3      \n\t"
-        "lea    (%1, %3, 4), %1          \n\t"
-        "movdqa      %%xmm0, (%2)        \n\t"
-        "movdqa      %%xmm1, (%2, %3)    \n\t"
-        "movdqa      %%xmm2, (%2, %3, 2) \n\t"
-        "movdqa      %%xmm3, (%2, %4)    \n\t"
-        "subl            $4, %0          \n\t"
-        "lea    (%2, %3, 4), %2          \n\t"
-        "jnz             1b              \n\t"
-        : "+g"(h), "+r"(pixels),  "+r"(block)
-        : "r"((x86_reg)line_size), "r"((x86_reg)3L * line_size)
-        : "memory"
-        );
-}
-
-static void avg_pixels16_sse2(uint8_t *block, const uint8_t *pixels,
-                              int line_size, int h)
-{
-    __asm__ volatile (
-        "1:                                 \n\t"
-        "movdqu (%1       ), %%xmm0         \n\t"
-        "movdqu (%1, %3   ), %%xmm1         \n\t"
-        "movdqu (%1, %3, 2), %%xmm2         \n\t"
-        "movdqu (%1, %4   ), %%xmm3         \n\t"
-        "lea    (%1, %3, 4), %1             \n\t"
-        "pavgb  (%2       ), %%xmm0         \n\t"
-        "pavgb  (%2, %3   ), %%xmm1         \n\t"
-        "pavgb  (%2, %3, 2), %%xmm2         \n\t"
-        "pavgb     (%2, %4), %%xmm3         \n\t"
-        "movdqa      %%xmm0, (%2)           \n\t"
-        "movdqa      %%xmm1, (%2, %3)       \n\t"
-        "movdqa      %%xmm2, (%2, %3, 2)    \n\t"
-        "movdqa      %%xmm3, (%2, %4)       \n\t"
-        "subl            $4, %0             \n\t"
-        "lea    (%2, %3, 4), %2             \n\t"
-        "jnz             1b                 \n\t"
-        : "+g"(h), "+r"(pixels),  "+r"(block)
-        : "r"((x86_reg)line_size), "r"((x86_reg)3L * line_size)
-        : "memory"
-        );
-}
-
 #define CLEAR_BLOCKS(name, n)                           \
 static void name(DCTELEM *blocks)                       \
 {                                                       \
@@ -943,12 +863,12 @@
     "packuswb            %%mm5, %%mm5   \n\t"                             \
     OP(%%mm5, out, %%mm7, d)
 
-#define QPEL_BASE(OPNAME, ROUNDER, RND, OP_MMX2, OP_3DNOW)                \
-static void OPNAME ## mpeg4_qpel16_h_lowpass_mmx2(uint8_t *dst,           \
-                                                  uint8_t *src,           \
-                                                  int dstStride,          \
-                                                  int srcStride,          \
-                                                  int h)                  \
+#define QPEL_BASE(OPNAME, ROUNDER, RND, OP_MMXEXT)                        \
+static void OPNAME ## mpeg4_qpel16_h_lowpass_mmxext(uint8_t *dst,         \
+                                                    uint8_t *src,         \
+                                                    int dstStride,        \
+                                                    int srcStride,        \
+                                                    int h)                \
 {                                                                         \
     uint64_t temp;                                                        \
                                                                           \
@@ -1011,7 +931,7 @@
         "psraw        $5, %%mm3             \n\t"                         \
         "movq         %5, %%mm1             \n\t"                         \
         "packuswb  %%mm3, %%mm1             \n\t"                         \
-        OP_MMX2(%%mm1, (%1), %%mm4, q)                                    \
+        OP_MMXEXT(%%mm1, (%1), %%mm4, q)                                  \
         /* mm0 = GHIJ, mm2 = FGHI, mm5 = HIJK, mm6 = IJKL, mm7 = 0 */     \
                                                                           \
         "movq      9(%0), %%mm1             \n\t" /* JKLMNOPQ */          \
@@ -1058,7 +978,7 @@
         "paddw    %%mm3, %%mm4              \n\t" /* 20a - 6b + 3c - d */ \
         "psraw       $5, %%mm4              \n\t"                         \
         "packuswb %%mm4, %%mm0              \n\t"                         \
-        OP_MMX2(%%mm0, 8(%1), %%mm4, q)                                   \
+        OP_MMXEXT(%%mm0, 8(%1), %%mm4, q)                                 \
                                                                           \
         "add         %3, %0                 \n\t"                         \
         "add         %4, %1                 \n\t"                         \
@@ -1071,79 +991,12 @@
         );                                                                \
 }                                                                         \
                                                                           \
-static void OPNAME ## mpeg4_qpel16_h_lowpass_3dnow(uint8_t *dst,          \
+static void OPNAME ## mpeg4_qpel8_h_lowpass_mmxext(uint8_t *dst,          \
                                                    uint8_t *src,          \
                                                    int dstStride,         \
                                                    int srcStride,         \
                                                    int h)                 \
 {                                                                         \
-    int i;                                                                \
-    int16_t temp[16];                                                     \
-    /* quick HACK, XXX FIXME MUST be optimized */                         \
-    for (i = 0; i < h; i++) {                                             \
-        temp[ 0] = (src[ 0] + src[ 1]) * 20 - (src[ 0] + src[ 2]) * 6 +   \
-                   (src[ 1] + src[ 3]) *  3 - (src[ 2] + src[ 4]);        \
-        temp[ 1] = (src[ 1] + src[ 2]) * 20 - (src[ 0] + src[ 3]) * 6 +   \
-                   (src[ 0] + src[ 4]) *  3 - (src[ 1] + src[ 5]);        \
-        temp[ 2] = (src[ 2] + src[ 3]) * 20 - (src[ 1] + src[ 4]) * 6 +   \
-                   (src[ 0] + src[ 5]) *  3 - (src[ 0] + src[ 6]);        \
-        temp[ 3] = (src[ 3] + src[ 4]) * 20 - (src[ 2] + src[ 5]) * 6 +   \
-                   (src[ 1] + src[ 6]) *  3 - (src[ 0] + src[ 7]);        \
-        temp[ 4] = (src[ 4] + src[ 5]) * 20 - (src[ 3] + src[ 6]) * 6 +   \
-                   (src[ 2] + src[ 7]) *  3 - (src[ 1] + src[ 8]);        \
-        temp[ 5] = (src[ 5] + src[ 6]) * 20 - (src[ 4] + src[ 7]) * 6 +   \
-                   (src[ 3] + src[ 8]) *  3 - (src[ 2] + src[ 9]);        \
-        temp[ 6] = (src[ 6] + src[ 7]) * 20 - (src[ 5] + src[ 8]) * 6 +   \
-                   (src[ 4] + src[ 9]) *  3 - (src[ 3] + src[10]);        \
-        temp[ 7] = (src[ 7] + src[ 8]) * 20 - (src[ 6] + src[ 9]) * 6 +   \
-                   (src[ 5] + src[10]) *  3 - (src[ 4] + src[11]);        \
-        temp[ 8] = (src[ 8] + src[ 9]) * 20 - (src[ 7] + src[10]) * 6 +   \
-                   (src[ 6] + src[11]) *  3 - (src[ 5] + src[12]);        \
-        temp[ 9] = (src[ 9] + src[10]) * 20 - (src[ 8] + src[11]) * 6 +   \
-                   (src[ 7] + src[12]) *  3 - (src[ 6] + src[13]);        \
-        temp[10] = (src[10] + src[11]) * 20 - (src[ 9] + src[12]) * 6 +   \
-                   (src[ 8] + src[13]) *  3 - (src[ 7] + src[14]);        \
-        temp[11] = (src[11] + src[12]) * 20 - (src[10] + src[13]) * 6 +   \
-                   (src[ 9] + src[14]) *  3 - (src[ 8] + src[15]);        \
-        temp[12] = (src[12] + src[13]) * 20 - (src[11] + src[14]) * 6 +   \
-                   (src[10] + src[15]) *  3 - (src[ 9] + src[16]);        \
-        temp[13] = (src[13] + src[14]) * 20 - (src[12] + src[15]) * 6 +   \
-                   (src[11] + src[16]) *  3 - (src[10] + src[16]);        \
-        temp[14] = (src[14] + src[15]) * 20 - (src[13] + src[16]) * 6 +   \
-                   (src[12] + src[16]) *  3 - (src[11] + src[15]);        \
-        temp[15] = (src[15] + src[16]) * 20 - (src[14] + src[16]) * 6 +   \
-                   (src[13] + src[15]) *  3 - (src[12] + src[14]);        \
-        __asm__ volatile (                                                \
-            "movq      (%0), %%mm0          \n\t"                         \
-            "movq     8(%0), %%mm1          \n\t"                         \
-            "paddw       %2, %%mm0          \n\t"                         \
-            "paddw       %2, %%mm1          \n\t"                         \
-            "psraw       $5, %%mm0          \n\t"                         \
-            "psraw       $5, %%mm1          \n\t"                         \
-            "packuswb %%mm1, %%mm0          \n\t"                         \
-            OP_3DNOW(%%mm0, (%1), %%mm1, q)                               \
-            "movq    16(%0), %%mm0          \n\t"                         \
-            "movq    24(%0), %%mm1          \n\t"                         \
-            "paddw       %2, %%mm0          \n\t"                         \
-            "paddw       %2, %%mm1          \n\t"                         \
-            "psraw       $5, %%mm0          \n\t"                         \
-            "psraw       $5, %%mm1          \n\t"                         \
-            "packuswb %%mm1, %%mm0          \n\t"                         \
-            OP_3DNOW(%%mm0, 8(%1), %%mm1, q)                              \
-            :: "r"(temp), "r"(dst), "m"(ROUNDER)                          \
-            : "memory"                                                    \
-            );                                                            \
-        dst += dstStride;                                                 \
-        src += srcStride;                                                 \
-    }                                                                     \
-}                                                                         \
-                                                                          \
-static void OPNAME ## mpeg4_qpel8_h_lowpass_mmx2(uint8_t *dst,            \
-                                                 uint8_t *src,            \
-                                                 int dstStride,           \
-                                                 int srcStride,           \
-                                                 int h)                   \
-{                                                                         \
     __asm__ volatile (                                                    \
         "pxor      %%mm7, %%mm7             \n\t"                         \
         "1:                                 \n\t"                         \
@@ -1195,7 +1048,7 @@
         "paddw     %%mm1, %%mm3             \n\t" /* 20a - 6b + 3c - d */ \
         "psraw        $5, %%mm3             \n\t"                         \
         "packuswb  %%mm3, %%mm0             \n\t"                         \
-        OP_MMX2(%%mm0, (%1), %%mm4, q)                                    \
+        OP_MMXEXT(%%mm0, (%1), %%mm4, q)                                  \
                                                                           \
         "add          %3, %0                \n\t"                         \
         "add          %4, %1                \n\t"                         \
@@ -1206,49 +1059,6 @@
           /* "m"(ff_pw_20), "m"(ff_pw_3), */ "m"(ROUNDER)                 \
         : "memory"                                                        \
         );                                                                \
-}                                                                         \
-                                                                          \
-static void OPNAME ## mpeg4_qpel8_h_lowpass_3dnow(uint8_t *dst,           \
-                                                  uint8_t *src,           \
-                                                  int dstStride,          \
-                                                  int srcStride,          \
-                                                  int h)                  \
-{                                                                         \
-    int i;                                                                \
-    int16_t temp[8];                                                      \
-    /* quick HACK, XXX FIXME MUST be optimized */                         \
-    for (i = 0; i < h; i++) {                                             \
-        temp[0] = (src[0] + src[1]) * 20 - (src[0] + src[2]) * 6 +        \
-                  (src[1] + src[3]) *  3 - (src[2] + src[4]);             \
-        temp[1] = (src[1] + src[2]) * 20 - (src[0] + src[3]) * 6 +        \
-                  (src[0] + src[4]) *  3 - (src[1] + src[5]);             \
-        temp[2] = (src[2] + src[3]) * 20 - (src[1] + src[4]) * 6 +        \
-                  (src[0] + src[5]) *  3 - (src[0] + src[6]);             \
-        temp[3] = (src[3] + src[4]) * 20 - (src[2] + src[5]) * 6 +        \
-                  (src[1] + src[6]) *  3 - (src[0] + src[7]);             \
-        temp[4] = (src[4] + src[5]) * 20 - (src[3] + src[6]) * 6 +        \
-                  (src[2] + src[7]) *  3 - (src[1] + src[8]);             \
-        temp[5] = (src[5] + src[6]) * 20 - (src[4] + src[7]) * 6 +        \
-                  (src[3] + src[8]) *  3 - (src[2] + src[8]);             \
-        temp[6] = (src[6] + src[7]) * 20 - (src[5] + src[8]) * 6 +        \
-                  (src[4] + src[8]) *  3 - (src[3] + src[7]);             \
-        temp[7] = (src[7] + src[8]) * 20 - (src[6] + src[8]) * 6 +        \
-                  (src[5] + src[7]) *  3 - (src[4] + src[6]);             \
-        __asm__ volatile (                                                \
-            "movq      (%0), %%mm0      \n\t"                             \
-            "movq     8(%0), %%mm1      \n\t"                             \
-            "paddw       %2, %%mm0      \n\t"                             \
-            "paddw       %2, %%mm1      \n\t"                             \
-            "psraw       $5, %%mm0      \n\t"                             \
-            "psraw       $5, %%mm1      \n\t"                             \
-            "packuswb %%mm1, %%mm0      \n\t"                             \
-            OP_3DNOW(%%mm0, (%1), %%mm1, q)                               \
-            :: "r"(temp), "r"(dst), "m"(ROUNDER)                          \
-            : "memory"                                                    \
-            );                                                            \
-        dst += dstStride;                                                 \
-        src += srcStride;                                                 \
-    }                                                                     \
 }
 
 #define QPEL_OP(OPNAME, ROUNDER, RND, OP, MMX)                          \
@@ -1759,25 +1569,17 @@
 #define PUT_OP(a, b, temp, size)                \
     "mov"#size"        "#a", "#b"       \n\t"
 
-#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)           \
+#define AVG_MMXEXT_OP(a, b, temp, size)         \
     "mov"#size"        "#b", "#temp"    \n\t"   \
     "pavgb          "#temp", "#a"       \n\t"   \
     "mov"#size"        "#a", "#b"       \n\t"
 
-QPEL_BASE(put_,        ff_pw_16, _,        PUT_OP,       PUT_OP)
-QPEL_BASE(avg_,        ff_pw_16, _,        AVG_MMX2_OP,  AVG_3DNOW_OP)
-QPEL_BASE(put_no_rnd_, ff_pw_15, _no_rnd_, PUT_OP,       PUT_OP)
-QPEL_OP(put_,          ff_pw_16, _,        PUT_OP,       3dnow)
-QPEL_OP(avg_,          ff_pw_16, _,        AVG_3DNOW_OP, 3dnow)
-QPEL_OP(put_no_rnd_,   ff_pw_15, _no_rnd_, PUT_OP,       3dnow)
-QPEL_OP(put_,          ff_pw_16, _,        PUT_OP,       mmx2)
-QPEL_OP(avg_,          ff_pw_16, _,        AVG_MMX2_OP,  mmx2)
-QPEL_OP(put_no_rnd_,   ff_pw_15, _no_rnd_, PUT_OP,       mmx2)
+QPEL_BASE(put_,        ff_pw_16, _,        PUT_OP)
+QPEL_BASE(avg_,        ff_pw_16, _,        AVG_MMXEXT_OP)
+QPEL_BASE(put_no_rnd_, ff_pw_15, _no_rnd_, PUT_OP)
+QPEL_OP(put_,          ff_pw_16, _,        PUT_OP,        mmxext)
+QPEL_OP(avg_,          ff_pw_16, _,        AVG_MMXEXT_OP, mmxext)
+QPEL_OP(put_no_rnd_,   ff_pw_15, _no_rnd_, PUT_OP,        mmxext)
 
 /***********************************/
 /* bilinear qpel: not compliant to any spec, only for -lavdopts fast */
@@ -1831,14 +1633,10 @@
 QPEL_2TAP_L3(OPNAME, SIZE, MMX, 13, stride,     -stride,  1)                \
 QPEL_2TAP_L3(OPNAME, SIZE, MMX, 33, stride + 1, -stride, -1)                \
 
-QPEL_2TAP(put_, 16, mmx2)
-QPEL_2TAP(avg_, 16, mmx2)
-QPEL_2TAP(put_,  8, mmx2)
-QPEL_2TAP(avg_,  8, mmx2)
-QPEL_2TAP(put_, 16, 3dnow)
-QPEL_2TAP(avg_, 16, 3dnow)
-QPEL_2TAP(put_,  8, 3dnow)
-QPEL_2TAP(avg_,  8, 3dnow)
+QPEL_2TAP(put_, 16, mmxext)
+QPEL_2TAP(avg_, 16, mmxext)
+QPEL_2TAP(put_,  8, mmxext)
+QPEL_2TAP(avg_,  8, mmxext)
 
 void ff_put_rv40_qpel8_mc33_mmx(uint8_t *dst, uint8_t *src, int stride)
 {
@@ -1878,10 +1676,12 @@
     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 -= src_y*linesize;
+        src_y_add = h - 1;
         src_y     = h - 1;
     } else if (src_y <= -block_h) {
-        src_y_add = 1 - block_h - src_y;
+        src -= src_y*linesize;
+        src_y_add = 1 - block_h;
         src_y     = 1 - block_h;
     }
     if (src_x >= w) {
@@ -1896,8 +1696,8 @@
     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);
+    av_assert2(start_x < end_x && block_w > 0);
+    av_assert2(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;
@@ -1952,18 +1752,24 @@
     const uint16_t dxy4[4] = { dxys, dxys, dxys, dxys };
     const uint16_t dyy4[4] = { dyys, dyys, dyys, dyys };
     const uint64_t shift2 = 2 * shift;
-    uint8_t edge_buf[(h + 1) * stride];
+#define MAX_STRIDE 4096U
+#define MAX_H 8U
+    uint8_t edge_buf[(MAX_H + 1) * MAX_STRIDE];
     int x, y;
 
     const int dxw = (dxx - (1 << (16 + shift))) * (w - 1);
     const int dyh = (dyy - (1 << (16 + shift))) * (h - 1);
     const int dxh = dxy * (h - 1);
     const int dyw = dyx * (w - 1);
+    int need_emu =  (unsigned)ix >= width  - w ||
+                    (unsigned)iy >= height - h;
+
     if ( // non-constant fullpel offset (3% of blocks)
         ((ox ^ (ox + dxw)) | (ox ^ (ox + dxh)) | (ox ^ (ox + dxw + dxh)) |
          (oy ^ (oy + dyw)) | (oy ^ (oy + dyh)) | (oy ^ (oy + dyw + dyh))) >> (16 + shift)
         // uses more than 16 bits of subpel mv (only at huge resolution)
-        || (dxx | dxy | dyx | dyy) & 15) {
+        || (dxx | dxy | dyx | dyy) & 15
+        || (need_emu && (h > MAX_H || stride > MAX_STRIDE))) {
         // FIXME could still use mmx for some of the rows
         ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy,
                  shift, r, width, height);
@@ -1971,8 +1777,7 @@
     }
 
     src += ix + iy * stride;
-    if ((unsigned)ix >= width  - w ||
-        (unsigned)iy >= height - h) {
+    if (need_emu) {
         emu_edge_fn(edge_buf, src, stride, w + 1, h + 1, ix, iy, width, height);
         src = edge_buf;
     }
@@ -2094,7 +1899,7 @@
     } while (--h);                              \
 }
 
-PREFETCH(prefetch_mmx2,  prefetcht0)
+PREFETCH(prefetch_mmxext, prefetcht0)
 PREFETCH(prefetch_3dnow, prefetch)
 #undef PREFETCH
 
@@ -2102,31 +1907,31 @@
 
 #include "h264_qpel.c"
 
-void ff_put_h264_chroma_mc8_mmx_rnd  (uint8_t *dst, uint8_t *src,
+void ff_put_h264_chroma_mc8_rnd_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_h264_chroma_mc8_3dnow_rnd(uint8_t *dst, uint8_t *src,
+void ff_avg_h264_chroma_mc8_rnd_mmxext(uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_avg_h264_chroma_mc8_rnd_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_avg_h264_chroma_mc4_mmx2     (uint8_t *dst, uint8_t *src,
+void ff_avg_h264_chroma_mc4_mmxext   (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_put_h264_chroma_mc2_mmx2     (uint8_t *dst, uint8_t *src,
+void ff_put_h264_chroma_mc2_mmxext   (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,
+void ff_avg_h264_chroma_mc2_mmxext   (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,
+void ff_put_h264_chroma_mc8_rnd_ssse3(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,
+void ff_avg_h264_chroma_mc8_rnd_ssse3(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);
@@ -2136,10 +1941,10 @@
                                       (uint8_t *dst, uint8_t *src,      \
                                        int stride, int h, int x, int y);
 
-CHROMA_MC(put, 2, 10, mmx2)
-CHROMA_MC(avg, 2, 10, mmx2)
-CHROMA_MC(put, 4, 10, mmx2)
-CHROMA_MC(avg, 4, 10, mmx2)
+CHROMA_MC(put, 2, 10, mmxext)
+CHROMA_MC(avg, 2, 10, mmxext)
+CHROMA_MC(put, 4, 10, mmxext)
+CHROMA_MC(avg, 4, 10, mmxext)
 CHROMA_MC(put, 8, 10, sse2)
 CHROMA_MC(avg, 8, 10, sse2)
 CHROMA_MC(put, 8, 10, avx)
@@ -2148,22 +1953,22 @@
 #if HAVE_INLINE_ASM
 
 /* CAVS-specific */
-void ff_put_cavs_qpel8_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride)
+void ff_put_cavs_qpel8_mc00_mmxext(uint8_t *dst, uint8_t *src, int stride)
 {
     put_pixels8_mmx(dst, src, stride, 8);
 }
 
-void ff_avg_cavs_qpel8_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride)
+void ff_avg_cavs_qpel8_mc00_mmxext(uint8_t *dst, uint8_t *src, int stride)
 {
     avg_pixels8_mmx(dst, src, stride, 8);
 }
 
-void ff_put_cavs_qpel16_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride)
+void ff_put_cavs_qpel16_mc00_mmxext(uint8_t *dst, uint8_t *src, int stride)
 {
     put_pixels16_mmx(dst, src, stride, 16);
 }
 
-void ff_avg_cavs_qpel16_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride)
+void ff_avg_cavs_qpel16_mc00_mmxext(uint8_t *dst, uint8_t *src, int stride)
 {
     avg_pixels16_mmx(dst, src, stride, 16);
 }
@@ -2175,10 +1980,10 @@
     put_pixels8_mmx(dst, src, stride, 8);
 }
 
-void ff_avg_vc1_mspel_mc00_mmx2(uint8_t *dst, const uint8_t *src,
-                                int stride, int rnd)
+void ff_avg_vc1_mspel_mc00_mmxext(uint8_t *dst, const uint8_t *src,
+                                  int stride, int rnd)
 {
-    avg_pixels8_mmx2(dst, src, stride, 8);
+    avg_pixels8_mmxext(dst, src, stride, 8);
 }
 
 /* only used in VP3/5/6 */
@@ -2237,27 +2042,29 @@
 
 DIRAC_PIXOP(put, mmx)
 DIRAC_PIXOP(avg, mmx)
-DIRAC_PIXOP(avg, mmx2)
+DIRAC_PIXOP(avg, mmxext)
 
+#if HAVE_YASM
 void ff_put_dirac_pixels16_sse2(uint8_t *dst, const uint8_t *src[5], int stride, int h)
 {
-    put_pixels16_sse2(dst, src[0], stride, h);
+    ff_put_pixels16_sse2(dst, src[0], stride, h);
 }
 void ff_avg_dirac_pixels16_sse2(uint8_t *dst, const uint8_t *src[5], int stride, int h)
 {
-    avg_pixels16_sse2(dst, src[0], stride, h);
+    ff_avg_pixels16_sse2(dst, src[0], stride, h);
 }
 void ff_put_dirac_pixels32_sse2(uint8_t *dst, const uint8_t *src[5], int stride, int h)
 {
-    put_pixels16_sse2(dst   , src[0]   , stride, h);
-    put_pixels16_sse2(dst+16, src[0]+16, stride, h);
+    ff_put_pixels16_sse2(dst   , src[0]   , stride, h);
+    ff_put_pixels16_sse2(dst+16, src[0]+16, stride, h);
 }
 void ff_avg_dirac_pixels32_sse2(uint8_t *dst, const uint8_t *src[5], int stride, int h)
 {
-    avg_pixels16_sse2(dst   , src[0]   , stride, h);
-    avg_pixels16_sse2(dst+16, src[0]+16, stride, h);
+    ff_avg_pixels16_sse2(dst   , src[0]   , stride, h);
+    ff_avg_pixels16_sse2(dst+16, src[0]+16, stride, h);
 }
 #endif
+#endif
 
 /* XXX: Those functions should be suppressed ASAP when all IDCTs are
  * converted. */
@@ -2452,13 +2259,13 @@
 
 #endif /* HAVE_INLINE_ASM */
 
-int32_t ff_scalarproduct_int16_mmx2(const int16_t *v1, const int16_t *v2,
-                                    int order);
+int32_t ff_scalarproduct_int16_mmxext(const int16_t *v1, const int16_t *v2,
+                                      int order);
 int32_t ff_scalarproduct_int16_sse2(const int16_t *v1, const int16_t *v2,
                                     int order);
-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_mmxext(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);
@@ -2466,25 +2273,25 @@
                                               const int16_t *v3,
                                               int order, int mul);
 
-void ff_apply_window_int16_mmxext    (int16_t *output, const int16_t *input,
+void ff_apply_window_int16_round_mmxext(int16_t *output, const int16_t *input,
+                                        const int16_t *window, unsigned int len);
+void ff_apply_window_int16_round_sse2(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_mmxext(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_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_bswap32_buf_ssse3(uint32_t *dst, const uint32_t *src, int w);
 void ff_bswap32_buf_sse2(uint32_t *dst, const uint32_t *src, int w);
 
-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);
+void ff_add_hfyu_median_prediction_mmxext(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,
@@ -2606,7 +2413,7 @@
 #endif
 
     if (!high_bit_depth && CONFIG_H264CHROMA) {
-        c->put_h264_chroma_pixels_tab[0] = ff_put_h264_chroma_mc8_mmx_rnd;
+        c->put_h264_chroma_pixels_tab[0] = ff_put_h264_chroma_mc8_rnd_mmx;
         c->put_h264_chroma_pixels_tab[1] = ff_put_h264_chroma_mc4_mmx;
     }
 
@@ -2615,71 +2422,72 @@
 
 }
 
-static void dsputil_init_mmx2(DSPContext *c, AVCodecContext *avctx,
-                              int mm_flags)
+static void dsputil_init_mmxext(DSPContext *c, AVCodecContext *avctx,
+                                int mm_flags)
 {
     const int bit_depth      = avctx->bits_per_raw_sample;
     const int high_bit_depth = bit_depth > 8;
 
 #if HAVE_INLINE_ASM
-    c->prefetch = prefetch_mmx2;
+    c->prefetch = prefetch_mmxext;
+
+    SET_QPEL_FUNCS(avg_qpel,        0, 16, mmxext, );
+    SET_QPEL_FUNCS(avg_qpel,        1,  8, mmxext, );
+    SET_QPEL_FUNCS(avg_2tap_qpel,   0, 16, mmxext, );
+    SET_QPEL_FUNCS(avg_2tap_qpel,   1,  8, mmxext, );
+
+    SET_QPEL_FUNCS(put_qpel,        0, 16, mmxext, );
+    SET_QPEL_FUNCS(put_qpel,        1,  8, mmxext, );
+    SET_QPEL_FUNCS(put_2tap_qpel,   0, 16, mmxext, );
+    SET_QPEL_FUNCS(put_2tap_qpel,   1,  8, mmxext, );
+    SET_QPEL_FUNCS(put_no_rnd_qpel, 0, 16, mmxext, );
+    SET_QPEL_FUNCS(put_no_rnd_qpel, 1,  8, mmxext, );
 
     if (!high_bit_depth) {
-        c->put_pixels_tab[0][1] = put_pixels16_x2_mmx2;
-        c->put_pixels_tab[0][2] = put_pixels16_y2_mmx2;
+        c->put_pixels_tab[0][1] = put_pixels16_x2_mmxext;
+        c->put_pixels_tab[0][2] = put_pixels16_y2_mmxext;
 
-        c->avg_pixels_tab[0][0] = avg_pixels16_mmx2;
-        c->avg_pixels_tab[0][1] = avg_pixels16_x2_mmx2;
-        c->avg_pixels_tab[0][2] = avg_pixels16_y2_mmx2;
+        c->avg_pixels_tab[0][0] = avg_pixels16_mmxext;
+        c->avg_pixels_tab[0][1] = avg_pixels16_x2_mmxext;
+        c->avg_pixels_tab[0][2] = avg_pixels16_y2_mmxext;
 
-        c->put_pixels_tab[1][1] = put_pixels8_x2_mmx2;
-        c->put_pixels_tab[1][2] = put_pixels8_y2_mmx2;
+        c->put_pixels_tab[1][1] = put_pixels8_x2_mmxext;
+        c->put_pixels_tab[1][2] = put_pixels8_y2_mmxext;
 
-        c->avg_pixels_tab[1][0] = avg_pixels8_mmx2;
-        c->avg_pixels_tab[1][1] = avg_pixels8_x2_mmx2;
-        c->avg_pixels_tab[1][2] = avg_pixels8_y2_mmx2;
+        c->avg_pixels_tab[1][0] = avg_pixels8_mmxext;
+        c->avg_pixels_tab[1][1] = avg_pixels8_x2_mmxext;
+        c->avg_pixels_tab[1][2] = avg_pixels8_y2_mmxext;
     }
 
     if (!(avctx->flags & CODEC_FLAG_BITEXACT)) {
         if (!high_bit_depth) {
-            c->put_no_rnd_pixels_tab[0][1] = put_no_rnd_pixels16_x2_mmx2;
-            c->put_no_rnd_pixels_tab[0][2] = put_no_rnd_pixels16_y2_mmx2;
-            c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_mmx2;
-            c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_mmx2;
+            c->put_no_rnd_pixels_tab[0][1] = put_no_rnd_pixels16_x2_mmxext;
+            c->put_no_rnd_pixels_tab[0][2] = put_no_rnd_pixels16_y2_mmxext;
+            c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_mmxext;
+            c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_mmxext;
 
-            c->avg_pixels_tab[0][3] = avg_pixels16_xy2_mmx2;
-            c->avg_pixels_tab[1][3] = avg_pixels8_xy2_mmx2;
+            c->avg_pixels_tab[0][3] = avg_pixels16_xy2_mmxext;
+            c->avg_pixels_tab[1][3] = avg_pixels8_xy2_mmxext;
         }
     }
 
     if (CONFIG_VP3_DECODER && (avctx->codec_id == AV_CODEC_ID_VP3 ||
                                avctx->codec_id == AV_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;
+        c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_exact_mmxext;
+        c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_exact_mmxext;
     }
 #endif /* HAVE_INLINE_ASM */
 
+#if HAVE_MMXEXT_EXTERNAL
     if (CONFIG_H264QPEL) {
-#if HAVE_INLINE_ASM
-        SET_QPEL_FUNCS(put_qpel,        0, 16, mmx2, );
-        SET_QPEL_FUNCS(put_qpel,        1,  8, mmx2, );
-        SET_QPEL_FUNCS(put_no_rnd_qpel, 0, 16, mmx2, );
-        SET_QPEL_FUNCS(put_no_rnd_qpel, 1,  8, mmx2, );
-        SET_QPEL_FUNCS(avg_qpel,        0, 16, mmx2, );
-        SET_QPEL_FUNCS(avg_qpel,        1,  8, mmx2, );
-#endif /* HAVE_INLINE_ASM */
-
         if (!high_bit_depth) {
-#if HAVE_INLINE_ASM
-            SET_QPEL_FUNCS(put_h264_qpel, 0, 16, mmx2, );
-            SET_QPEL_FUNCS(put_h264_qpel, 1,  8, mmx2, );
-            SET_QPEL_FUNCS(put_h264_qpel, 2,  4, mmx2, );
-            SET_QPEL_FUNCS(avg_h264_qpel, 0, 16, mmx2, );
-            SET_QPEL_FUNCS(avg_h264_qpel, 1,  8, mmx2, );
-            SET_QPEL_FUNCS(avg_h264_qpel, 2,  4, mmx2, );
-#endif /* HAVE_INLINE_ASM */
+            SET_QPEL_FUNCS(put_h264_qpel, 0, 16, mmxext, );
+            SET_QPEL_FUNCS(put_h264_qpel, 1,  8, mmxext, );
+            SET_QPEL_FUNCS(put_h264_qpel, 2,  4, mmxext, );
+            SET_QPEL_FUNCS(avg_h264_qpel, 0, 16, mmxext, );
+            SET_QPEL_FUNCS(avg_h264_qpel, 1,  8, mmxext, );
+            SET_QPEL_FUNCS(avg_h264_qpel, 2,  4, mmxext, );
         } else if (bit_depth == 10) {
-#if HAVE_YASM
 #if !ARCH_X86_64
             SET_QPEL_FUNCS(avg_h264_qpel, 0, 16, 10_mmxext, ff_);
             SET_QPEL_FUNCS(put_h264_qpel, 0, 16, 10_mmxext, ff_);
@@ -2688,44 +2496,35 @@
 #endif
             SET_QPEL_FUNCS(put_h264_qpel, 2, 4,  10_mmxext, ff_);
             SET_QPEL_FUNCS(avg_h264_qpel, 2, 4,  10_mmxext, ff_);
-#endif /* HAVE_YASM */
         }
-
-#if HAVE_INLINE_ASM
-        SET_QPEL_FUNCS(put_2tap_qpel, 0, 16, mmx2, );
-        SET_QPEL_FUNCS(put_2tap_qpel, 1,  8, mmx2, );
-        SET_QPEL_FUNCS(avg_2tap_qpel, 0, 16, mmx2, );
-        SET_QPEL_FUNCS(avg_2tap_qpel, 1,  8, mmx2, );
-#endif /* HAVE_INLINE_ASM */
     }
 
-#if HAVE_YASM
     if (!high_bit_depth && CONFIG_H264CHROMA) {
-        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;
+        c->avg_h264_chroma_pixels_tab[0] = ff_avg_h264_chroma_mc8_rnd_mmxext;
+        c->avg_h264_chroma_pixels_tab[1] = ff_avg_h264_chroma_mc4_mmxext;
+        c->avg_h264_chroma_pixels_tab[2] = ff_avg_h264_chroma_mc2_mmxext;
+        c->put_h264_chroma_pixels_tab[2] = ff_put_h264_chroma_mc2_mmxext;
     }
     if (bit_depth == 10 && CONFIG_H264CHROMA) {
-        c->put_h264_chroma_pixels_tab[2] = ff_put_h264_chroma_mc2_10_mmx2;
-        c->avg_h264_chroma_pixels_tab[2] = ff_avg_h264_chroma_mc2_10_mmx2;
-        c->put_h264_chroma_pixels_tab[1] = ff_put_h264_chroma_mc4_10_mmx2;
-        c->avg_h264_chroma_pixels_tab[1] = ff_avg_h264_chroma_mc4_10_mmx2;
+        c->put_h264_chroma_pixels_tab[2] = ff_put_h264_chroma_mc2_10_mmxext;
+        c->avg_h264_chroma_pixels_tab[2] = ff_avg_h264_chroma_mc2_10_mmxext;
+        c->put_h264_chroma_pixels_tab[1] = ff_put_h264_chroma_mc4_10_mmxext;
+        c->avg_h264_chroma_pixels_tab[1] = ff_avg_h264_chroma_mc4_10_mmxext;
     }
 
     /* slower than cmov version on AMD */
     if (!(mm_flags & AV_CPU_FLAG_3DNOW))
-        c->add_hfyu_median_prediction = ff_add_hfyu_median_prediction_mmx2;
+        c->add_hfyu_median_prediction = ff_add_hfyu_median_prediction_mmxext;
 
-    c->scalarproduct_int16          = ff_scalarproduct_int16_mmx2;
-    c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_mmx2;
+    c->scalarproduct_int16          = ff_scalarproduct_int16_mmxext;
+    c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_mmxext;
 
     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;
+    } else {
+        c->apply_window_int16 = ff_apply_window_int16_round_mmxext;
     }
-#endif /* HAVE_YASM */
+#endif /* HAVE_MMXEXT_EXTERNAL */
 }
 
 static void dsputil_init_3dnow(DSPContext *c, AVCodecContext *avctx,
@@ -2768,35 +2567,12 @@
         c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_exact_3dnow;
     }
 
-    if (CONFIG_H264QPEL) {
-        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, );
-        SET_QPEL_FUNCS(put_no_rnd_qpel, 1,  8, 3dnow, );
-        SET_QPEL_FUNCS(avg_qpel,        0, 16, 3dnow, );
-        SET_QPEL_FUNCS(avg_qpel,        1,  8, 3dnow, );
-
-        if (!high_bit_depth) {
-            SET_QPEL_FUNCS(put_h264_qpel, 0, 16, 3dnow, );
-            SET_QPEL_FUNCS(put_h264_qpel, 1,  8, 3dnow, );
-            SET_QPEL_FUNCS(put_h264_qpel, 2,  4, 3dnow, );
-            SET_QPEL_FUNCS(avg_h264_qpel, 0, 16, 3dnow, );
-            SET_QPEL_FUNCS(avg_h264_qpel, 1,  8, 3dnow, );
-            SET_QPEL_FUNCS(avg_h264_qpel, 2,  4, 3dnow, );
-        }
-
-        SET_QPEL_FUNCS(put_2tap_qpel, 0, 16, 3dnow, );
-        SET_QPEL_FUNCS(put_2tap_qpel, 1,  8, 3dnow, );
-        SET_QPEL_FUNCS(avg_2tap_qpel, 0, 16, 3dnow, );
-        SET_QPEL_FUNCS(avg_2tap_qpel, 1,  8, 3dnow, );
-    }
-
     c->vorbis_inverse_coupling = vorbis_inverse_coupling_3dnow;
 #endif /* HAVE_INLINE_ASM */
 
 #if HAVE_YASM
     if (!high_bit_depth && CONFIG_H264CHROMA) {
-        c->avg_h264_chroma_pixels_tab[0] = ff_avg_h264_chroma_mc8_3dnow_rnd;
+        c->avg_h264_chroma_pixels_tab[0] = ff_avg_h264_chroma_mc8_rnd_3dnow;
         c->avg_h264_chroma_pixels_tab[1] = ff_avg_h264_chroma_mc4_3dnow;
     }
 #endif /* HAVE_YASM */
@@ -2851,16 +2627,24 @@
                               int mm_flags)
 {
     const int bit_depth      = avctx->bits_per_raw_sample;
-
-#if HAVE_INLINE_ASM
     const int high_bit_depth = bit_depth > 8;
 
+#if HAVE_SSE2_INLINE
+    if (!high_bit_depth && avctx->idct_algo == FF_IDCT_XVIDMMX) {
+        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;
+    }
+#endif /* HAVE_SSE2_INLINE */
+
+#if HAVE_SSE2_EXTERNAL
     if (!(mm_flags & AV_CPU_FLAG_SSE2SLOW)) {
         // these functions are slower than mmx on AMD, but faster on Intel
         if (!high_bit_depth) {
-            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;
+            c->put_pixels_tab[0][0]        = ff_put_pixels16_sse2;
+            c->put_no_rnd_pixels_tab[0][0] = ff_put_pixels16_sse2;
+            c->avg_pixels_tab[0][0]        = ff_avg_pixels16_sse2;
             if (CONFIG_H264QPEL)
                 H264_QPEL_FUNCS(0, 0, sse2);
         }
@@ -2880,9 +2664,7 @@
         H264_QPEL_FUNCS(3, 2, sse2);
         H264_QPEL_FUNCS(3, 3, sse2);
     }
-#endif /* HAVE_INLINE_ASM */
 
-#if HAVE_YASM
     if (bit_depth == 10) {
         if (CONFIG_H264QPEL) {
             SET_QPEL_FUNCS(put_h264_qpel, 0, 16, 10_sse2, ff_);
@@ -2907,21 +2689,21 @@
         c->vector_clip_int32 = ff_vector_clip_int32_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;
+    } else if (!(mm_flags & AV_CPU_FLAG_SSE2SLOW)) {
+        c->apply_window_int16 = ff_apply_window_int16_round_sse2;
     }
     c->bswap_buf = ff_bswap32_buf_sse2;
-#endif /* HAVE_YASM */
+#endif /* HAVE_SSE2_EXTERNAL */
 }
 
 static void dsputil_init_ssse3(DSPContext *c, AVCodecContext *avctx,
                                int mm_flags)
 {
+#if HAVE_SSSE3_EXTERNAL
     const int high_bit_depth = avctx->bits_per_raw_sample > 8;
     const int bit_depth      = avctx->bits_per_raw_sample;
 
-#if HAVE_SSSE3_INLINE
     if (!high_bit_depth && CONFIG_H264QPEL) {
         H264_QPEL_FUNCS(1, 0, ssse3);
         H264_QPEL_FUNCS(1, 1, ssse3);
@@ -2936,17 +2718,14 @@
         H264_QPEL_FUNCS(3, 2, ssse3);
         H264_QPEL_FUNCS(3, 3, ssse3);
     }
-#endif /* HAVE_SSSE3_INLINE */
-
-#if HAVE_SSSE3_EXTERNAL
     if (bit_depth == 10 && CONFIG_H264QPEL) {
         H264_QPEL_FUNCS_10(1, 0, ssse3_cache64);
         H264_QPEL_FUNCS_10(2, 0, ssse3_cache64);
         H264_QPEL_FUNCS_10(3, 0, ssse3_cache64);
     }
     if (!high_bit_depth && CONFIG_H264CHROMA) {
-        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[0] = ff_put_h264_chroma_mc8_rnd_ssse3;
+        c->avg_h264_chroma_pixels_tab[0] = ff_avg_h264_chroma_mc8_rnd_ssse3;
         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;
     }
@@ -3036,9 +2815,9 @@
                     c->idct                  = ff_idct_xvid_sse2;
                     c->idct_permutation_type = FF_SSE2_IDCT_PERM;
                 } else if (mm_flags & AV_CPU_FLAG_MMXEXT) {
-                    c->idct_put              = ff_idct_xvid_mmx2_put;
-                    c->idct_add              = ff_idct_xvid_mmx2_add;
-                    c->idct                  = ff_idct_xvid_mmx2;
+                    c->idct_put              = ff_idct_xvid_mmxext_put;
+                    c->idct_add              = ff_idct_xvid_mmxext_add;
+                    c->idct                  = ff_idct_xvid_mmxext;
                 } else {
                     c->idct_put              = ff_idct_xvid_mmx_put;
                     c->idct_add              = ff_idct_xvid_mmx_add;
@@ -3052,7 +2831,7 @@
     }
 
     if (mm_flags & AV_CPU_FLAG_MMXEXT)
-        dsputil_init_mmx2(c, avctx, mm_flags);
+        dsputil_init_mmxext(c, avctx, mm_flags);
 
     if (mm_flags & AV_CPU_FLAG_3DNOW)
         dsputil_init_3dnow(c, avctx, mm_flags);
diff --git a/libavcodec/x86/dsputil_mmx.h b/libavcodec/x86/dsputil_mmx.h
index 100381c..d07ac9f 100644
--- a/libavcodec/x86/dsputil_mmx.h
+++ b/libavcodec/x86/dsputil_mmx.h
@@ -26,7 +26,7 @@
 #include "libavcodec/dsputil.h"
 #include "libavutil/x86/asm.h"
 
-typedef struct { uint64_t a, b; } xmm_reg;
+typedef struct xmm_reg { uint64_t a, b; } xmm_reg;
 
 extern const uint64_t ff_bone;
 extern const uint64_t ff_wtwo;
@@ -89,13 +89,13 @@
 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_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_put_cavs_qpel8_mc00_mmxext(uint8_t *dst, uint8_t *src, int stride);
+void ff_avg_cavs_qpel8_mc00_mmxext(uint8_t *dst, uint8_t *src, int stride);
+void ff_put_cavs_qpel16_mc00_mmxext(uint8_t *dst, uint8_t *src, int stride);
+void ff_avg_cavs_qpel16_mc00_mmxext(uint8_t *dst, uint8_t *src, int stride);
 
 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_avg_vc1_mspel_mc00_mmxext(uint8_t *dst, const uint8_t *src, int stride, int rnd);
 
 void ff_put_rv40_qpel8_mc33_mmx(uint8_t *block, uint8_t *pixels, int line_size);
 void ff_put_rv40_qpel16_mc33_mmx(uint8_t *block, uint8_t *pixels, int line_size);
diff --git a/libavcodec/x86/dsputilenc.asm b/libavcodec/x86/dsputilenc.asm
index 2d805c7..3e7990d 100644
--- a/libavcodec/x86/dsputilenc.asm
+++ b/libavcodec/x86/dsputilenc.asm
@@ -21,7 +21,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;*****************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 SECTION .text
@@ -100,28 +99,11 @@
     paddusw         m0, m1
 %endmacro
 
-; FIXME: HSUM_* saturates at 64k, while an 8x8 hadamard or dct block can get up to
+; 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
+%macro HSUM 3
+%if cpuflag(sse2)
     movhlps         %2, %1
     paddusw         %1, %2
     pshuflw         %2, %1, 0xE
@@ -129,6 +111,21 @@
     pshuflw         %2, %1, 0x1
     paddusw         %1, %2
     movd            %3, %1
+%elif cpuflag(mmxext)
+    pshufw          %2, %1, 0xE
+    paddusw         %1, %2
+    pshufw          %2, %1, 0x1
+    paddusw         %1, %2
+    movd            %3, %1
+%elif cpuflag(mmx)
+    mova            %2, %1
+    psrlq           %1, 32
+    paddusw         %1, %2
+    mova            %2, %1
+    psrlq           %1, 16
+    paddusw         %1, %2
+    movd            %3, %1
+%endif
 %endmacro
 
 %macro STORE4 5
@@ -145,30 +142,30 @@
     mova            %5, [%1+mmsize*3]
 %endmacro
 
-%macro hadamard8_16_wrapper 3
-cglobal hadamard8_diff_%1, 4, 4, %2
+%macro hadamard8_16_wrapper 2
+cglobal hadamard8_diff, 4, 4, %1
 %ifndef m8
-    %assign pad %3*mmsize-(4+stack_offset&(mmsize-1))
+    %assign pad %2*mmsize-(4+stack_offset&(mmsize-1))
     SUB            rsp, pad
 %endif
-    call hadamard8x8_diff_%1
+    call hadamard8x8_diff %+ SUFFIX
 %ifndef m8
     ADD            rsp, pad
 %endif
     RET
 
-cglobal hadamard8_diff16_%1, 5, 6, %2
+cglobal hadamard8_diff16, 5, 6, %1
 %ifndef m8
-    %assign pad %3*mmsize-(4+stack_offset&(mmsize-1))
+    %assign pad %2*mmsize-(4+stack_offset&(mmsize-1))
     SUB            rsp, pad
 %endif
 
-    call hadamard8x8_diff_%1
+    call hadamard8x8_diff %+ SUFFIX
     mov            r5d, eax
 
     add             r1, 8
     add             r2, 8
-    call hadamard8x8_diff_%1
+    call hadamard8x8_diff %+ SUFFIX
     add            r5d, eax
 
     cmp            r4d, 16
@@ -176,12 +173,12 @@
 
     lea             r1, [r1+r3*8-8]
     lea             r2, [r2+r3*8-8]
-    call hadamard8x8_diff_%1
+    call hadamard8x8_diff %+ SUFFIX
     add            r5d, eax
 
     add             r1, 8
     add             r2, 8
-    call hadamard8x8_diff_%1
+    call hadamard8x8_diff %+ SUFFIX
     add            r5d, eax
 
 .done:
@@ -192,7 +189,25 @@
     RET
 %endmacro
 
-%macro HADAMARD8_DIFF_MMX 1
+%macro HADAMARD8_DIFF 0-1
+%if cpuflag(sse2)
+hadamard8x8_diff %+ SUFFIX:
+    lea                          r0, [r3*3]
+    DIFF_PIXELS_8                r1, r2,  0, r3, r0, rsp+gprsize
+    HADAMARD8
+%if 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                        m0, m1, eax
+    and                         eax, 0xFFFF
+    ret
+
+hadamard8_16_wrapper %1, 3
+%elif cpuflag(mmx)
 ALIGN 16
 ; int hadamard8_diff_##cpu(void *s, uint8_t *src1, uint8_t *src2,
 ;                          int stride, int h)
@@ -200,7 +215,7 @@
 ; 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:
+hadamard8x8_diff %+ SUFFIX:
     lea                          r0, [r3*3]
 
     ; first 4x8 pixels
@@ -237,53 +252,35 @@
     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
-%if 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]
+hadamard8_16_wrapper 0, 14
 %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
+INIT_MMX mmx
 %define ABS1 ABS1_MMX
-%define HSUM HSUM_MMX
-HADAMARD8_DIFF_MMX mmx
+HADAMARD8_DIFF
 
-%define ABS1 ABS1_MMX2
-%define HSUM HSUM_MMX2
-HADAMARD8_DIFF_MMX mmx2
+INIT_MMX mmxext
+%define ABS1 ABS1_MMXEXT
+HADAMARD8_DIFF
 
-INIT_XMM
-%define ABS2 ABS2_MMX2
+INIT_XMM sse2
+%define ABS2 ABS2_MMXEXT
 %if 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
+HADAMARD8_DIFF 10
 
+INIT_XMM ssse3
 %define ABS2        ABS2_SSSE3
 %define ABS_SUM_8x8 ABS_SUM_8x8_64
-HADAMARD8_DIFF_SSE2 ssse3, 9
+HADAMARD8_DIFF 9
 
-INIT_XMM
+INIT_XMM sse2
 ; sse16_sse2(void *v, uint8_t * pix1, uint8_t * pix2, int line_size, int h)
-cglobal sse16_sse2, 5, 5, 8
+cglobal sse16, 5, 5, 8
     shr      r4d, 1
     pxor      m0, m0         ; mm0 = 0
     pxor      m7, m7         ; mm7 holds the sum
diff --git a/libavcodec/x86/dsputilenc_mmx.c b/libavcodec/x86/dsputilenc_mmx.c
index f6eadc1..fb098ad 100644
--- a/libavcodec/x86/dsputilenc_mmx.c
+++ b/libavcodec/x86/dsputilenc_mmx.c
@@ -647,7 +647,9 @@
 }
 #undef SUM
 
-static int vsad_intra16_mmx2(void *v, uint8_t * pix, uint8_t * dummy, int line_size, int h) {
+static int vsad_intra16_mmxext(void *v, uint8_t *pix, uint8_t *dummy,
+                               int line_size, int h)
+{
     int tmp;
 
     assert( (((int)pix) & 7) == 0);
@@ -765,7 +767,9 @@
 }
 #undef SUM
 
-static int vsad16_mmx2(void *v, uint8_t * pix1, uint8_t * pix2, int line_size, int h) {
+static int vsad16_mmxext(void *v, uint8_t *pix1, uint8_t *pix2,
+                         int line_size, int h)
+{
     int tmp;
 
     assert( (((int)pix1) & 7) == 0);
@@ -845,7 +849,10 @@
         dst[i+0] = src1[i+0]-src2[i+0];
 }
 
-static void sub_hfyu_median_prediction_mmx2(uint8_t *dst, const uint8_t *src1, const uint8_t *src2, int w, int *left, int *left_top){
+static void sub_hfyu_median_prediction_mmxext(uint8_t *dst, const uint8_t *src1,
+                                              const uint8_t *src2, int w,
+                                              int *left, int *left_top)
+{
     x86_reg i=0;
     uint8_t l, lt;
 
@@ -889,7 +896,7 @@
     "pxor " #z ", " #a "              \n\t"\
     "psubw " #z ", " #a "             \n\t"
 
-#define MMABS_MMX2(a,z)\
+#define MMABS_MMXEXT(a, z)                 \
     "pxor " #z ", " #z "              \n\t"\
     "psubw " #a ", " #z "             \n\t"\
     "pmaxsw " #z ", " #a "            \n\t"
@@ -913,7 +920,7 @@
     "paddusw "#t", "#a"               \n\t"\
     "movd "#a", "#dst"                \n\t"\
 
-#define HSUM_MMX2(a, t, dst)\
+#define HSUM_MMXEXT(a, t, dst)             \
     "pshufw $0x0E, "#a", "#t"         \n\t"\
     "paddusw "#t", "#a"               \n\t"\
     "pshufw $0x01, "#a", "#t"         \n\t"\
@@ -975,9 +982,9 @@
 #undef MMABS
 #undef HSUM
 
-#define HSUM(a,t,dst) HSUM_MMX2(a,t,dst)
-#define MMABS(a,z)    MMABS_MMX2(a,z)
-DCT_SAD_FUNC(mmx2)
+#define HSUM(a,t,dst) HSUM_MMXEXT(a,t,dst)
+#define MMABS(a,z)    MMABS_MMXEXT(a,z)
+DCT_SAD_FUNC(mmxext)
 #undef HSUM
 #undef DCT_SAD
 
@@ -1098,7 +1105,7 @@
                               int stride, int h);
 
 hadamard_func(mmx)
-hadamard_func(mmx2)
+hadamard_func(mmxext)
 hadamard_func(sse2)
 hadamard_func(ssse3)
 
@@ -1116,7 +1123,7 @@
             if(mm_flags & AV_CPU_FLAG_SSE2){
                 c->fdct = ff_fdct_sse2;
             } else if (mm_flags & AV_CPU_FLAG_MMXEXT) {
-                c->fdct = ff_fdct_mmx2;
+                c->fdct = ff_fdct_mmxext;
             }else{
                 c->fdct = ff_fdct_mmx;
             }
@@ -1149,14 +1156,14 @@
         c->ssd_int8_vs_int16 = ssd_int8_vs_int16_mmx;
 
         if (mm_flags & AV_CPU_FLAG_MMXEXT) {
-            c->sum_abs_dctelem= sum_abs_dctelem_mmx2;
-            c->vsad[4]= vsad_intra16_mmx2;
+            c->sum_abs_dctelem = sum_abs_dctelem_mmxext;
+            c->vsad[4]         = vsad_intra16_mmxext;
 
             if(!(avctx->flags & CODEC_FLAG_BITEXACT)){
-                c->vsad[0] = vsad16_mmx2;
+                c->vsad[0] = vsad16_mmxext;
             }
 
-            c->sub_hfyu_median_prediction= sub_hfyu_median_prediction_mmx2;
+            c->sub_hfyu_median_prediction = sub_hfyu_median_prediction_mmxext;
         }
 
         if(mm_flags & AV_CPU_FLAG_SSE2){
@@ -1189,8 +1196,8 @@
         c->hadamard8_diff[1] = ff_hadamard8_diff_mmx;
 
         if (EXTERNAL_MMXEXT(mm_flags)) {
-            c->hadamard8_diff[0] = ff_hadamard8_diff16_mmx2;
-            c->hadamard8_diff[1] = ff_hadamard8_diff_mmx2;
+            c->hadamard8_diff[0] = ff_hadamard8_diff16_mmxext;
+            c->hadamard8_diff[1] = ff_hadamard8_diff_mmxext;
         }
 
         if (EXTERNAL_SSE2(mm_flags)) {
diff --git a/libavcodec/x86/dwt_yasm.asm b/libavcodec/x86/dwt_yasm.asm
index ac6c505..f6280d1 100644
--- a/libavcodec/x86/dwt_yasm.asm
+++ b/libavcodec/x86/dwt_yasm.asm
@@ -19,7 +19,7 @@
 ;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "x86inc.asm"
+%include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
 pw_1: times 8 dw 1
@@ -65,7 +65,7 @@
 cglobal vertical_compose53iL0_%1, 4,4,1, b0, b1, b2, width
     mova    m2, [pw_2]
 .loop:
-    sub     widthd, mmsize/2
+    sub     widthq, mmsize/2
     mova    m1, [b0q+2*widthq]
     mova    m0, [b1q+2*widthq]
     COMPOSE_53iL0 m0, m1, [b2q+2*widthq], m2
@@ -78,7 +78,7 @@
 cglobal vertical_compose_dirac53iH0_%1, 4,4,1, b0, b1, b2, width
     mova    m1, [pw_1]
 .loop:
-    sub     widthd, mmsize/2
+    sub     widthq, mmsize/2
     mova    m0, [b0q+2*widthq]
     paddw   m0, [b2q+2*widthq]
     paddw   m0, m1
@@ -94,7 +94,7 @@
     mova    m3, [pw_8]
     mova    m4, [pw_1991]
 .loop:
-    sub     widthd, mmsize/2
+    sub     widthq, mmsize/2
     mova    m0, [b0q+2*widthq]
     mova    m1, [b1q+2*widthq]
     COMPOSE_DD97iH0 [b2q+2*widthq], [b3q+2*widthq], [b4q+2*widthq]
@@ -108,7 +108,7 @@
     mova    m3, [pw_16]
     mova    m4, [pw_1991]
 .loop:
-    sub     widthd, mmsize/2
+    sub     widthq, mmsize/2
     mova    m0, [b0q+2*widthq]
     mova    m1, [b1q+2*widthq]
     mova    m5, [b2q+2*widthq]
@@ -132,7 +132,7 @@
 cglobal vertical_compose_haar_%1, 3,4,3, b0, b1, width
     mova    m3, [pw_1]
 .loop:
-    sub     widthd, mmsize/2
+    sub     widthq, mmsize/2
     mova    m1, [b1q+2*widthq]
     mova    m0, [b0q+2*widthq]
     mova    m2, m1
diff --git a/libavcodec/x86/fdct.c b/libavcodec/x86/fdct.c
index 566e0b6..44a3d7c 100644
--- a/libavcodec/x86/fdct.c
+++ b/libavcodec/x86/fdct.c
@@ -440,7 +440,8 @@
     );
 }
 
-static av_always_inline void fdct_row_mmx2(const int16_t *in, int16_t *out, const int16_t *table)
+static av_always_inline void fdct_row_mmxext(const int16_t *in, int16_t *out,
+                                             const int16_t *table)
 {
     __asm__ volatile (
         "pshufw    $0x1B, 8(%0), %%mm5 \n\t"
@@ -555,7 +556,7 @@
     }
 }
 
-void ff_fdct_mmx2(int16_t *block)
+void ff_fdct_mmxext(int16_t *block)
 {
     DECLARE_ALIGNED(8, int64_t, align_tmp)[16];
     int16_t *block1= (int16_t*)align_tmp;
@@ -566,7 +567,7 @@
     fdct_col_mmx(block, block1, 4);
 
     for(i=8;i>0;i--) {
-        fdct_row_mmx2(block1, block, table);
+        fdct_row_mmxext(block1, block, table);
         block1 += 8;
         table += 32;
         block += 8;
diff --git a/libavcodec/x86/fft.asm b/libavcodec/x86/fft.asm
index c2b9cbb..5071741 100644
--- a/libavcodec/x86/fft.asm
+++ b/libavcodec/x86/fft.asm
@@ -28,7 +28,6 @@
 ; in blocks as conventient to the vector size.
 ; i.e. {4x real, 4x imaginary, 4x real, ...} (or 2x respectively)
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 %if ARCH_X86_64
@@ -106,7 +105,8 @@
     pfadd    %5, %4 ; {t6,t5}
     pxor     %3, [ps_m1p1] ; {t8,t7}
     mova     %6, %1
-    PSWAPD   %3, %3
+    movd [r0+12], %3
+    punpckhdq %3, [r0+8]
     pfadd    %1, %5 ; {r0,i0}
     pfsub    %6, %5 ; {r2,i2}
     mova     %4, %2
@@ -500,19 +500,6 @@
 %endmacro
 
 %if ARCH_X86_32
-%macro PSWAPD 2
-%if cpuflag(3dnowext)
-    pswapd %1, %2
-%elifidn %1, %2
-    movd [r0+12], %1
-    punpckhdq %1, [r0+8]
-%else
-    movq  %1, %2
-    psrlq %1, 32
-    punpckldq %1, %2
-%endif
-%endmacro
-
 INIT_MMX 3dnowext
 FFT48_3DNOW
 
diff --git a/libavcodec/x86/fft_init.c b/libavcodec/x86/fft_init.c
index d7a31d4..a9d9579 100644
--- a/libavcodec/x86/fft_init.c
+++ b/libavcodec/x86/fft_init.c
@@ -22,7 +22,7 @@
 #include "libavcodec/dct.h"
 #include "fft.h"
 
-av_cold void ff_fft_init_mmx(FFTContext *s)
+av_cold void ff_fft_init_x86(FFTContext *s)
 {
     int has_vectors = av_get_cpu_flags();
 #if ARCH_X86_32
@@ -56,7 +56,7 @@
 }
 
 #if CONFIG_DCT
-av_cold void ff_dct_init_mmx(DCTContext *s)
+av_cold void ff_dct_init_x86(DCTContext *s)
 {
     int has_vectors = av_get_cpu_flags();
     if (EXTERNAL_SSE(has_vectors))
diff --git a/libavcodec/x86/fmtconvert.asm b/libavcodec/x86/fmtconvert.asm
index 21e0cce..1bd13fc 100644
--- a/libavcodec/x86/fmtconvert.asm
+++ b/libavcodec/x86/fmtconvert.asm
@@ -19,19 +19,26 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 SECTION_TEXT
 
+%macro CVTPS2PI 2
+%if cpuflag(sse)
+    cvtps2pi %1, %2
+%elif cpuflag(3dnow)
+    pf2id %1, %2
+%endif
+%endmacro
+
 ;---------------------------------------------------------------------------------
 ; void int32_to_float_fmul_scalar(float *dst, const int *src, float mul, int len);
 ;---------------------------------------------------------------------------------
-%macro INT32_TO_FLOAT_FMUL_SCALAR 2
+%macro INT32_TO_FLOAT_FMUL_SCALAR 1
 %if UNIX64
-cglobal int32_to_float_fmul_scalar_%1, 3,3,%2, dst, src, len
+cglobal int32_to_float_fmul_scalar, 3, 3, %1, dst, src, len
 %else
-cglobal int32_to_float_fmul_scalar_%1, 4,4,%2, dst, src, mul, len
+cglobal int32_to_float_fmul_scalar, 4, 4, %1, dst, src, mul, len
 %endif
 %if WIN64
     SWAP 0, 2
@@ -44,7 +51,7 @@
     add     dstq, lenq
     neg     lenq
 .loop:
-%ifidn %1, sse2
+%if cpuflag(sse2)
     cvtdq2ps  m1, [srcq+lenq   ]
     cvtdq2ps  m2, [srcq+lenq+16]
 %else
@@ -64,36 +71,32 @@
     REP_RET
 %endmacro
 
-INIT_XMM
-%define SPLATD SPLATD_SSE
-%define movdqa movaps
-INT32_TO_FLOAT_FMUL_SCALAR sse, 5
-%undef movdqa
-%define SPLATD SPLATD_SSE2
-INT32_TO_FLOAT_FMUL_SCALAR sse2, 3
-%undef SPLATD
+INIT_XMM sse
+INT32_TO_FLOAT_FMUL_SCALAR 5
+INIT_XMM sse2
+INT32_TO_FLOAT_FMUL_SCALAR 3
 
 
 ;------------------------------------------------------------------------------
 ; void ff_float_to_int16(int16_t *dst, const float *src, long len);
 ;------------------------------------------------------------------------------
-%macro FLOAT_TO_INT16 2
-cglobal float_to_int16_%1, 3,3,%2, dst, src, len
+%macro FLOAT_TO_INT16 1
+cglobal float_to_int16, 3, 3, %1, dst, src, len
     add       lenq, lenq
     lea       srcq, [srcq+2*lenq]
     add       dstq, lenq
     neg       lenq
 .loop:
-%ifidn %1, sse2
+%if cpuflag(sse2)
     cvtps2dq    m0, [srcq+2*lenq   ]
     cvtps2dq    m1, [srcq+2*lenq+16]
     packssdw    m0, m1
     mova  [dstq+lenq], m0
 %else
-    cvtps2pi    m0, [srcq+2*lenq   ]
-    cvtps2pi    m1, [srcq+2*lenq+ 8]
-    cvtps2pi    m2, [srcq+2*lenq+16]
-    cvtps2pi    m3, [srcq+2*lenq+24]
+    CVTPS2PI    m0, [srcq+2*lenq   ]
+    CVTPS2PI    m1, [srcq+2*lenq+ 8]
+    CVTPS2PI    m2, [srcq+2*lenq+16]
+    CVTPS2PI    m3, [srcq+2*lenq+24]
     packssdw    m0, m1
     packssdw    m2, m3
     mova  [dstq+lenq  ], m0
@@ -101,31 +104,30 @@
 %endif
     add       lenq, 16
     js .loop
-%ifnidn %1, sse2
+%if mmsize == 8
     emms
 %endif
     REP_RET
 %endmacro
 
-INIT_XMM
-FLOAT_TO_INT16 sse2, 2
-INIT_MMX
-FLOAT_TO_INT16 sse, 0
-%define cvtps2pi pf2id
-FLOAT_TO_INT16 3dnow, 0
-%undef cvtps2pi
+INIT_XMM sse2
+FLOAT_TO_INT16 2
+INIT_MMX sse
+FLOAT_TO_INT16 0
+INIT_MMX 3dnow
+FLOAT_TO_INT16 0
 
 ;------------------------------------------------------------------------------
 ; void ff_float_to_int16_step(int16_t *dst, const float *src, long len, long step);
 ;------------------------------------------------------------------------------
-%macro FLOAT_TO_INT16_STEP 2
-cglobal float_to_int16_step_%1, 4,7,%2, dst, src, len, step, step3, v1, v2
+%macro FLOAT_TO_INT16_STEP 1
+cglobal float_to_int16_step, 4, 7, %1, dst, src, len, step, step3, v1, v2
     add       lenq, lenq
     lea       srcq, [srcq+2*lenq]
     lea     step3q, [stepq*3]
     neg       lenq
 .loop:
-%ifidn %1, sse2
+%if cpuflag(sse2)
     cvtps2dq    m0, [srcq+2*lenq   ]
     cvtps2dq    m1, [srcq+2*lenq+16]
     packssdw    m0, m1
@@ -151,10 +153,10 @@
     mov  [dstq+step3q*2], v2w
     lea       dstq, [dstq+stepq*8]
 %else
-    cvtps2pi    m0, [srcq+2*lenq   ]
-    cvtps2pi    m1, [srcq+2*lenq+ 8]
-    cvtps2pi    m2, [srcq+2*lenq+16]
-    cvtps2pi    m3, [srcq+2*lenq+24]
+    CVTPS2PI    m0, [srcq+2*lenq   ]
+    CVTPS2PI    m1, [srcq+2*lenq+ 8]
+    CVTPS2PI    m2, [srcq+2*lenq+16]
+    CVTPS2PI    m3, [srcq+2*lenq+24]
     packssdw    m0, m1
     packssdw    m2, m3
     movd       v1d, m0
@@ -180,25 +182,24 @@
 %endif
     add       lenq, 16
     js .loop
-%ifnidn %1, sse2
+%if mmsize == 8
     emms
 %endif
     REP_RET
 %endmacro
 
-INIT_XMM
-FLOAT_TO_INT16_STEP sse2, 2
-INIT_MMX
-FLOAT_TO_INT16_STEP sse, 0
-%define cvtps2pi pf2id
-FLOAT_TO_INT16_STEP 3dnow, 0
-%undef cvtps2pi
+INIT_XMM sse2
+FLOAT_TO_INT16_STEP 2
+INIT_MMX sse
+FLOAT_TO_INT16_STEP 0
+INIT_MMX 3dnow
+FLOAT_TO_INT16_STEP 0
 
 ;-------------------------------------------------------------------------------
 ; void ff_float_to_int16_interleave2(int16_t *dst, const float **src, long len);
 ;-------------------------------------------------------------------------------
-%macro FLOAT_TO_INT16_INTERLEAVE2 1
-cglobal float_to_int16_interleave2_%1, 3,4,2, dst, src0, src1, len
+%macro FLOAT_TO_INT16_INTERLEAVE2 0
+cglobal float_to_int16_interleave2, 3, 4, 2, dst, src0, src1, len
     lea      lenq, [4*r2q]
     mov     src1q, [src0q+gprsize]
     mov     src0q, [src0q]
@@ -207,7 +208,7 @@
     add     src1q, lenq
     neg      lenq
 .loop:
-%ifidn %1, sse2
+%if cpuflag(sse2)
     cvtps2dq   m0, [src0q+lenq]
     cvtps2dq   m1, [src1q+lenq]
     packssdw   m0, m1
@@ -215,10 +216,10 @@
     punpcklwd  m0, m1
     mova  [dstq+lenq], m0
 %else
-    cvtps2pi   m0, [src0q+lenq  ]
-    cvtps2pi   m1, [src0q+lenq+8]
-    cvtps2pi   m2, [src1q+lenq  ]
-    cvtps2pi   m3, [src1q+lenq+8]
+    CVTPS2PI   m0, [src0q+lenq  ]
+    CVTPS2PI   m1, [src0q+lenq+8]
+    CVTPS2PI   m2, [src1q+lenq  ]
+    CVTPS2PI   m3, [src1q+lenq+8]
     packssdw   m0, m1
     packssdw   m2, m3
     mova       m1, m0
@@ -229,35 +230,22 @@
 %endif
     add      lenq, 16
     js .loop
-%ifnidn %1, sse2
+%if mmsize == 8
     emms
 %endif
     REP_RET
 %endmacro
 
-INIT_MMX
-%define cvtps2pi pf2id
-FLOAT_TO_INT16_INTERLEAVE2 3dnow
-%undef cvtps2pi
-%define movdqa movaps
-FLOAT_TO_INT16_INTERLEAVE2 sse
-%undef movdqa
-INIT_XMM
-FLOAT_TO_INT16_INTERLEAVE2 sse2
+INIT_MMX 3dnow
+FLOAT_TO_INT16_INTERLEAVE2
+INIT_MMX sse
+FLOAT_TO_INT16_INTERLEAVE2
+INIT_XMM sse2
+FLOAT_TO_INT16_INTERLEAVE2
 
-
-%macro PSWAPD_SSE 2
-    pshufw %1, %2, 0x4e
-%endmacro
-%macro PSWAPD_3DNOW 2
-    movq  %1, %2
-    psrlq %1, 32
-    punpckldq %1, %2
-%endmacro
-
-%macro FLOAT_TO_INT16_INTERLEAVE6 1
+%macro FLOAT_TO_INT16_INTERLEAVE6 0
 ; void float_to_int16_interleave6_sse(int16_t *dst, const float **src, int len)
-cglobal float_to_int16_interleave6_%1, 2,8,0, dst, src, src1, src2, src3, src4, src5, len
+cglobal float_to_int16_interleave6, 2, 8, 0, dst, src, src1, src2, src3, src4, src5, len
 %if ARCH_X86_64
     mov     lend, r2d
 %else
@@ -275,20 +263,20 @@
     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]
+    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
+    PSWAPD     mm3, mm0
     punpcklwd  mm0, mm1
     punpckhwd  mm1, mm2
     punpcklwd  mm2, mm3
-    pswapd     mm3, mm0
+    PSWAPD     mm3, mm0
     punpckldq  mm0, mm2
     punpckhdq  mm2, mm1
     punpckldq  mm1, mm3
@@ -303,21 +291,19 @@
     RET
 %endmacro ; FLOAT_TO_INT16_INTERLEAVE6
 
-%define pswapd PSWAPD_SSE
-FLOAT_TO_INT16_INTERLEAVE6 sse
-%define cvtps2pi pf2id
-%define pswapd PSWAPD_3DNOW
-FLOAT_TO_INT16_INTERLEAVE6 3dnow
-%undef pswapd
-FLOAT_TO_INT16_INTERLEAVE6 3dnowext
-%undef cvtps2pi
+INIT_MMX sse
+FLOAT_TO_INT16_INTERLEAVE6
+INIT_MMX 3dnow
+FLOAT_TO_INT16_INTERLEAVE6
+INIT_MMX 3dnowext
+FLOAT_TO_INT16_INTERLEAVE6
 
 ;-----------------------------------------------------------------------------
 ; void ff_float_interleave6(float *dst, const float **src, unsigned int len);
 ;-----------------------------------------------------------------------------
 
-%macro FLOAT_INTERLEAVE6 2
-cglobal float_interleave6_%1, 2,8,%2, dst, src, src1, src2, src3, src4, src5, len
+%macro FLOAT_INTERLEAVE6 1
+cglobal float_interleave6, 2, 8, %1, dst, src, src1, src2, src3, src4, src5, len
 %if ARCH_X86_64
     mov     lend, r2d
 %else
@@ -335,7 +321,7 @@
     sub    src4q, srcq
     sub    src5q, srcq
 .loop:
-%ifidn %1, sse
+%if cpuflag(sse)
     movaps    m0, [srcq]
     movaps    m1, [srcq+src1q]
     movaps    m2, [srcq+src2q]
@@ -384,62 +370,60 @@
     add      dstq, mmsize*6
     sub      lend, mmsize/4
     jg .loop
-%ifidn %1, mmx
+%if mmsize == 8
     emms
 %endif
     REP_RET
 %endmacro
 
-INIT_MMX
-FLOAT_INTERLEAVE6 mmx, 0
-INIT_XMM
-FLOAT_INTERLEAVE6 sse, 7
+INIT_MMX mmx
+FLOAT_INTERLEAVE6 0
+INIT_XMM sse
+FLOAT_INTERLEAVE6 7
 
 ;-----------------------------------------------------------------------------
 ; void ff_float_interleave2(float *dst, const float **src, unsigned int len);
 ;-----------------------------------------------------------------------------
 
-%macro FLOAT_INTERLEAVE2 2
-cglobal float_interleave2_%1, 3,4,%2, dst, src, len, src1
+%macro FLOAT_INTERLEAVE2 1
+cglobal float_interleave2, 3, 4, %1, dst, src, len, src1
     mov     src1q, [srcq+gprsize]
     mov      srcq, [srcq        ]
     sub     src1q, srcq
 .loop:
-    MOVPS      m0, [srcq             ]
-    MOVPS      m1, [srcq+src1q       ]
-    MOVPS      m3, [srcq      +mmsize]
-    MOVPS      m4, [srcq+src1q+mmsize]
+    mova       m0, [srcq             ]
+    mova       m1, [srcq+src1q       ]
+    mova       m3, [srcq      +mmsize]
+    mova       m4, [srcq+src1q+mmsize]
 
-    MOVPS      m2, m0
+    mova       m2, m0
     PUNPCKLDQ  m0, m1
     PUNPCKHDQ  m2, m1
 
-    MOVPS      m1, m3
+    mova       m1, m3
     PUNPCKLDQ  m3, m4
     PUNPCKHDQ  m1, m4
 
-    MOVPS [dstq         ], m0
-    MOVPS [dstq+1*mmsize], m2
-    MOVPS [dstq+2*mmsize], m3
-    MOVPS [dstq+3*mmsize], m1
+    mova  [dstq         ], m0
+    mova  [dstq+1*mmsize], m2
+    mova  [dstq+2*mmsize], m3
+    mova  [dstq+3*mmsize], m1
 
     add      srcq, mmsize*2
     add      dstq, mmsize*4
     sub      lend, mmsize/2
     jg .loop
-%ifidn %1, mmx
+%if mmsize == 8
     emms
 %endif
     REP_RET
 %endmacro
 
-INIT_MMX
-%define MOVPS     movq
+INIT_MMX mmx
 %define PUNPCKLDQ punpckldq
 %define PUNPCKHDQ punpckhdq
-FLOAT_INTERLEAVE2 mmx, 0
-INIT_XMM
-%define MOVPS     movaps
+FLOAT_INTERLEAVE2 0
+INIT_XMM sse
 %define PUNPCKLDQ unpcklps
 %define PUNPCKHDQ unpckhps
-FLOAT_INTERLEAVE2 sse, 5
+FLOAT_INTERLEAVE2 5
diff --git a/libavcodec/x86/h264_chromamc.asm b/libavcodec/x86/h264_chromamc.asm
index bee8330..7f5be75 100644
--- a/libavcodec/x86/h264_chromamc.asm
+++ b/libavcodec/x86/h264_chromamc.asm
@@ -20,7 +20,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
@@ -90,7 +89,7 @@
     jne .next4rows
 %endmacro
 
-%macro chroma_mc8_mmx_func 3
+%macro chroma_mc8_mmx_func 2-3
 %ifidn %2, rv40
 %ifdef PIC
 %define rnd_1d_rv40 r8
@@ -104,9 +103,9 @@
 %else
 %define extra_regs 0
 %endif ; rv40
-; 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 + extra_regs, 0
+; put/avg_h264_chroma_mc8_*(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 + extra_regs, 0
 %if ARCH_X86_64
     movsxd        r2, r2d
 %endif
@@ -283,14 +282,14 @@
     RET
 %endmacro
 
-%macro chroma_mc4_mmx_func 3
+%macro chroma_mc4_mmx_func 2
 %define extra_regs 0
 %ifidn %2, rv40
 %ifdef PIC
 %define extra_regs 1
 %endif ; PIC
 %endif ; rv40
-cglobal %1_%2_chroma_mc4_%3, 6, 6 + extra_regs, 0
+cglobal %1_%2_chroma_mc4, 6, 6 + extra_regs, 0
 %if ARCH_X86_64
     movsxd        r2, r2d
 %endif
@@ -374,8 +373,8 @@
     REP_RET
 %endmacro
 
-%macro chroma_mc2_mmx_func 3
-cglobal %1_%2_chroma_mc2_%3, 6, 7, 0
+%macro chroma_mc2_mmx_func 2
+cglobal %1_%2_chroma_mc2, 6, 7, 0
 %if ARCH_X86_64
     movsxd        r2, r2d
 %endif
@@ -435,35 +434,38 @@
     PAVG          %1, %2
 %endmacro
 
-INIT_MMX
+INIT_MMX 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
+chroma_mc8_mmx_func put, h264, _rnd
+chroma_mc8_mmx_func put, vc1,  _nornd
+chroma_mc8_mmx_func put, rv40
+chroma_mc4_mmx_func put, h264
+chroma_mc4_mmx_func put, rv40
+
+INIT_MMX mmxext
+chroma_mc2_mmx_func put, h264
 
 %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
+chroma_mc8_mmx_func avg, h264, _rnd
+chroma_mc8_mmx_func avg, vc1,  _nornd
+chroma_mc8_mmx_func avg, rv40
+chroma_mc4_mmx_func avg, h264
+chroma_mc4_mmx_func avg, rv40
+chroma_mc2_mmx_func avg, h264
 
 %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
+INIT_MMX 3dnow
+chroma_mc8_mmx_func avg, h264, _rnd
+chroma_mc8_mmx_func avg, vc1,  _nornd
+chroma_mc8_mmx_func avg, rv40
+chroma_mc4_mmx_func avg, h264
+chroma_mc4_mmx_func avg, rv40
 
-%macro chroma_mc8_ssse3_func 3
-cglobal %1_%2_chroma_mc8_%3, 6, 7, 8
+%macro chroma_mc8_ssse3_func 2-3
+cglobal %1_%2_chroma_mc8%3, 6, 7, 8
 %if ARCH_X86_64
     movsxd        r2, r2d
 %endif
@@ -610,8 +612,8 @@
     REP_RET
 %endmacro
 
-%macro chroma_mc4_ssse3_func 3
-cglobal %1_%2_chroma_mc4_%3, 6, 7, 0
+%macro chroma_mc4_ssse3_func 2
+cglobal %1_%2_chroma_mc4, 6, 7, 0
 %if ARCH_X86_64
     movsxd        r2, r2d
 %endif
@@ -664,16 +666,16 @@
 %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
+INIT_XMM ssse3
+chroma_mc8_ssse3_func put, h264, _rnd
+chroma_mc8_ssse3_func put, vc1,  _nornd
+INIT_MMX ssse3
+chroma_mc4_ssse3_func put, h264
 
 %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
+INIT_XMM ssse3
+chroma_mc8_ssse3_func avg, h264, _rnd
+chroma_mc8_ssse3_func avg, vc1,  _nornd
+INIT_MMX ssse3
+chroma_mc4_ssse3_func avg, h264
diff --git a/libavcodec/x86/h264_chromamc_10bit.asm b/libavcodec/x86/h264_chromamc_10bit.asm
index bcdb27c..b850551 100644
--- a/libavcodec/x86/h264_chromamc_10bit.asm
+++ b/libavcodec/x86/h264_chromamc_10bit.asm
@@ -22,8 +22,7 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "x86inc.asm"
-%include "x86util.asm"
+%include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
 
@@ -246,7 +245,7 @@
 %if %0==3
     movq          %2, %3
 %endif
-    PAVG          %1, %2
+    pavgw         %1, %2
 %endmacro
 
 %define CHROMAMC_AVG  NOTHING
@@ -256,18 +255,17 @@
 INIT_XMM avx
 CHROMA_MC8 put
 %endif
-INIT_MMX mmx2
+INIT_MMX mmxext
 CHROMA_MC4 put
 CHROMA_MC2 put
 
 %define CHROMAMC_AVG  AVG
-%define PAVG          pavgw
 INIT_XMM sse2
 CHROMA_MC8 avg
 %if HAVE_AVX_EXTERNAL
 INIT_XMM avx
 CHROMA_MC8 avg
 %endif
-INIT_MMX mmx2
+INIT_MMX mmxext
 CHROMA_MC4 avg
 CHROMA_MC2 avg
diff --git a/libavcodec/x86/h264_deblock.asm b/libavcodec/x86/h264_deblock.asm
index 48f8cef..7343b27 100644
--- a/libavcodec/x86/h264_deblock.asm
+++ b/libavcodec/x86/h264_deblock.asm
@@ -24,7 +24,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
@@ -503,7 +502,7 @@
     RET
 %endmacro ; DEBLOCK_LUMA
 
-INIT_MMX mmx2
+INIT_MMX mmxext
 DEBLOCK_LUMA v8, 8
 INIT_XMM sse2
 DEBLOCK_LUMA v, 16
@@ -777,11 +776,11 @@
 DEBLOCK_LUMA_INTRA v
 %endif
 %if ARCH_X86_64 == 0
-INIT_MMX mmx2
+INIT_MMX mmxext
 DEBLOCK_LUMA_INTRA v8
 %endif
 
-INIT_MMX mmx2
+INIT_MMX mmxext
 
 %macro CHROMA_V_START 0
     dec    r2d      ; alpha-1
@@ -812,7 +811,7 @@
     movq  m1, [t5+r1]
     movq  m2, [r0]
     movq  m3, [r0+r1]
-    call ff_chroma_inter_body_mmx2
+    call ff_chroma_inter_body_mmxext
     movq  [t5+r1], m1
     movq  [r0], m2
     RET
@@ -850,7 +849,7 @@
     RET
 
 ALIGN 16
-ff_chroma_inter_body_mmx2:
+ff_chroma_inter_body_mmxext:
     LOAD_MASK  r2d, r3d
     movd       m6, [r4] ; tc0
     punpcklbw  m6, m6
@@ -883,7 +882,7 @@
     movq  m1, [t5+r1]
     movq  m2, [r0]
     movq  m3, [r0+r1]
-    call ff_chroma_intra_body_mmx2
+    call ff_chroma_intra_body_mmxext
     movq  [t5+r1], m1
     movq  [r0], m2
     RET
@@ -894,12 +893,12 @@
 cglobal deblock_h_chroma_intra_8, 4,6
     CHROMA_H_START
     TRANSPOSE4x8_LOAD  bw, wd, dq, PASS8ROWS(t5, r0, r1, t6)
-    call ff_chroma_intra_body_mmx2
+    call ff_chroma_intra_body_mmxext
     TRANSPOSE8x4B_STORE PASS8ROWS(t5, r0, r1, t6)
     RET
 
 ALIGN 16
-ff_chroma_intra_body_mmx2:
+ff_chroma_intra_body_mmxext:
     LOAD_MASK r2d, r3d
     movq   m5, m1
     movq   m6, m2
@@ -1023,7 +1022,7 @@
     jl %%.b_idx_loop
 %endmacro
 
-INIT_MMX mmx2
+INIT_MMX mmxext
 cglobal h264_loop_filter_strength, 9, 9, 0, bs, nnz, ref, mv, bidir, edges, \
                                             step, mask_mv0, mask_mv1, field
 %define b_idxq bidirq
diff --git a/libavcodec/x86/h264_deblock_10bit.asm b/libavcodec/x86/h264_deblock_10bit.asm
index 0517605..d63ca02 100644
--- a/libavcodec/x86/h264_deblock_10bit.asm
+++ b/libavcodec/x86/h264_deblock_10bit.asm
@@ -24,7 +24,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
@@ -796,7 +795,7 @@
 %endmacro
 
 %if ARCH_X86_64 == 0
-INIT_MMX mmx2
+INIT_MMX mmxext
 DEBLOCK_LUMA
 DEBLOCK_LUMA_INTRA
 INIT_XMM sse2
@@ -913,7 +912,7 @@
 %endmacro
 
 %if ARCH_X86_64 == 0
-INIT_MMX mmx2
+INIT_MMX mmxext
 DEBLOCK_CHROMA
 %endif
 INIT_XMM sse2
diff --git a/libavcodec/x86/h264_idct.asm b/libavcodec/x86/h264_idct.asm
index 7003a14..d0ac0fe 100644
--- a/libavcodec/x86/h264_idct.asm
+++ b/libavcodec/x86/h264_idct.asm
@@ -26,7 +26,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;*****************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
@@ -77,9 +76,9 @@
     STORE_DIFFx2 m2, m3, m4, m5, m7, 6, %1, %3
 %endmacro
 
-INIT_MMX
+INIT_MMX mmx
 ; ff_h264_idct_add_mmx(uint8_t *dst, int16_t *block, int stride)
-cglobal h264_idct_add_8_mmx, 3, 3, 0
+cglobal h264_idct_add_8, 3, 3, 0
     IDCT4_ADD    r0, r1, r2
     RET
 
@@ -181,9 +180,9 @@
     STORE_DIFFx2 m1, m2, m5, m6, m7, 6, %1, %3
 %endmacro
 
-INIT_MMX
+INIT_MMX mmx
 ; ff_h264_idct8_add_mmx(uint8_t *dst, int16_t *block, int stride)
-cglobal h264_idct8_add_8_mmx, 3, 4, 0
+cglobal h264_idct8_add_8, 3, 4, 0
     %assign pad 128+4-(stack_offset&7)
     SUB         rsp, pad
 
@@ -241,13 +240,13 @@
     STORE_DIFF   m1, m6, m7, [%1+%4  ]
 %endmacro
 
-INIT_XMM
+INIT_XMM sse2
 ; ff_h264_idct8_add_sse2(uint8_t *dst, int16_t *block, int stride)
-cglobal h264_idct8_add_8_sse2, 3, 4, 10
+cglobal h264_idct8_add_8, 3, 4, 10
     IDCT8_ADD_SSE r0, r1, r2, r3
     RET
 
-%macro DC_ADD_MMX2_INIT 2-3
+%macro DC_ADD_MMXEXT_INIT 2-3
 %if %0 == 2
     movsx        %1, word [%1]
     add          %1, 32
@@ -267,7 +266,7 @@
     packuswb     m1, m1
 %endmacro
 
-%macro DC_ADD_MMX2_OP 4
+%macro DC_ADD_MMXEXT_OP 4
     %1           m2, [%2     ]
     %1           m3, [%2+%3  ]
     %1           m4, [%2+%3*2]
@@ -286,24 +285,25 @@
     %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_8_mmx2, 3, 3, 0
-    DC_ADD_MMX2_INIT r1, r2
-    DC_ADD_MMX2_OP movh, r0, r2, r1
+INIT_MMX mmxext
+; ff_h264_idct_dc_add_mmxext(uint8_t *dst, int16_t *block, int stride)
+cglobal h264_idct_dc_add_8, 3, 3, 0
+    DC_ADD_MMXEXT_INIT r1, r2
+    DC_ADD_MMXEXT_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_8_mmx2, 3, 3, 0
-    DC_ADD_MMX2_INIT r1, r2
-    DC_ADD_MMX2_OP mova, r0, r2, r1
+; ff_h264_idct8_dc_add_mmxext(uint8_t *dst, int16_t *block, int stride)
+cglobal h264_idct8_dc_add_8, 3, 3, 0
+    DC_ADD_MMXEXT_INIT r1, r2
+    DC_ADD_MMXEXT_OP mova, r0, r2, r1
     lea          r0, [r0+r2*4]
-    DC_ADD_MMX2_OP mova, r0, r2, r1
+    DC_ADD_MMXEXT_OP mova, r0, r2, r1
     RET
 
+INIT_MMX mmx
 ; 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_8_mmx, 5, 7 + npicregs, 0, dst, block_offset, block, stride, nnzc, cntr, coeff, picreg
+cglobal h264_idct_add16_8, 5, 7 + npicregs, 0, dst, block_offset, block, stride, nnzc, cntr, coeff, picreg
     xor          r5, r5
 %ifdef PIC
     lea     picregq, [scan8_mem]
@@ -325,7 +325,7 @@
 
 ; 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_8_mmx, 5, 7 + npicregs, 0, dst, block_offset, block, stride, nnzc, cntr, coeff, picreg
+cglobal h264_idct8_add4_8, 5, 7 + npicregs, 0, dst, block_offset, block, stride, nnzc, cntr, coeff, picreg
     %assign pad 128+4-(stack_offset&7)
     SUB         rsp, pad
 
@@ -355,9 +355,10 @@
     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_8_mmx2, 5, 8 + npicregs, 0, dst1, block_offset, block, stride, nnzc, cntr, coeff, dst2, picreg
+INIT_MMX mmxext
+; ff_h264_idct_add16_mmxext(uint8_t *dst, const int *block_offset,
+;                           DCTELEM *block, int stride, const uint8_t nnzc[6*8])
+cglobal h264_idct_add16_8, 5, 8 + npicregs, 0, dst1, block_offset, block, stride, nnzc, cntr, coeff, dst2, picreg
     xor          r5, r5
 %ifdef PIC
     lea     picregq, [scan8_mem]
@@ -372,14 +373,14 @@
     movsx        r6, word [r2]
     test         r6, r6
     jz .no_dc
-    DC_ADD_MMX2_INIT r2, r3, r6
+    DC_ADD_MMXEXT_INIT r2, r3, r6
 %if ARCH_X86_64 == 0
 %define dst2q r1
 %define dst2d r1d
 %endif
     mov       dst2d, dword [r1+r5*4]
     lea       dst2q, [r0+dst2q]
-    DC_ADD_MMX2_OP movh, dst2q, r3, r6
+    DC_ADD_MMXEXT_OP movh, dst2q, r3, r6
 %if ARCH_X86_64 == 0
     mov          r1, r1m
 %endif
@@ -399,9 +400,10 @@
     jl .nextblock
     REP_RET
 
+INIT_MMX mmx
 ; 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_8_mmx, 5, 7 + npicregs, 0, dst, block_offset, block, stride, nnzc, cntr, coeff, picreg
+cglobal h264_idct_add16intra_8, 5, 7 + npicregs, 0, dst, block_offset, block, stride, nnzc, cntr, coeff, picreg
     xor          r5, r5
 %ifdef PIC
     lea     picregq, [scan8_mem]
@@ -422,9 +424,11 @@
     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_8_mmx2, 5, 8 + npicregs, 0, dst1, block_offset, block, stride, nnzc, cntr, coeff, dst2, picreg
+INIT_MMX mmxext
+; ff_h264_idct_add16intra_mmxext(uint8_t *dst, const int *block_offset,
+;                                DCTELEM *block, int stride,
+;                                const uint8_t nnzc[6*8])
+cglobal h264_idct_add16intra_8, 5, 8 + npicregs, 0, dst1, block_offset, block, stride, nnzc, cntr, coeff, dst2, picreg
     xor          r5, r5
 %ifdef PIC
     lea     picregq, [scan8_mem]
@@ -446,14 +450,14 @@
     movsx        r6, word [r2]
     test         r6, r6
     jz .skipblock
-    DC_ADD_MMX2_INIT r2, r3, r6
+    DC_ADD_MMXEXT_INIT r2, r3, r6
 %if ARCH_X86_64 == 0
 %define dst2q r1
 %define dst2d r1d
 %endif
     mov       dst2d, dword [r1+r5*4]
     add       dst2q, r0
-    DC_ADD_MMX2_OP movh, dst2q, r3, r6
+    DC_ADD_MMXEXT_OP movh, dst2q, r3, r6
 %if ARCH_X86_64 == 0
     mov          r1, r1m
 %endif
@@ -464,9 +468,10 @@
     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_8_mmx2, 5, 8 + npicregs, 0, dst1, block_offset, block, stride, nnzc, cntr, coeff, dst2, picreg
+; ff_h264_idct8_add4_mmxext(uint8_t *dst, const int *block_offset,
+;                           DCTELEM *block, int stride,
+;                           const uint8_t nnzc[6*8])
+cglobal h264_idct8_add4_8, 5, 8 + npicregs, 0, dst1, block_offset, block, stride, nnzc, cntr, coeff, dst2, picreg
     %assign pad 128+4-(stack_offset&7)
     SUB         rsp, pad
 
@@ -484,16 +489,16 @@
     movsx        r6, word [r2]
     test         r6, r6
     jz .no_dc
-    DC_ADD_MMX2_INIT r2, r3, r6
+    DC_ADD_MMXEXT_INIT r2, r3, r6
 %if ARCH_X86_64 == 0
 %define dst2q r1
 %define dst2d r1d
 %endif
     mov       dst2d, dword [r1+r5*4]
     lea       dst2q, [r0+dst2q]
-    DC_ADD_MMX2_OP mova, dst2q, r3, r6
+    DC_ADD_MMXEXT_OP mova, dst2q, r3, r6
     lea       dst2q, [dst2q+r3*4]
-    DC_ADD_MMX2_OP mova, dst2q, r3, r6
+    DC_ADD_MMXEXT_OP mova, dst2q, r3, r6
 %if ARCH_X86_64 == 0
     mov          r1, r1m
 %endif
@@ -523,10 +528,10 @@
     ADD         rsp, pad
     RET
 
-INIT_XMM
+INIT_XMM sse2
 ; 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_8_sse2, 5, 8 + npicregs, 10, dst1, block_offset, block, stride, nnzc, cntr, coeff, dst2, picreg
+cglobal h264_idct8_add4_8, 5, 8 + npicregs, 10, dst1, block_offset, block, stride, nnzc, cntr, coeff, dst2, picreg
     xor          r5, r5
 %ifdef PIC
     lea     picregq, [scan8_mem]
@@ -541,17 +546,17 @@
     movsx        r6, word [r2]
     test         r6, r6
     jz .no_dc
-INIT_MMX
-    DC_ADD_MMX2_INIT r2, r3, r6
+INIT_MMX cpuname
+    DC_ADD_MMXEXT_INIT r2, r3, r6
 %if ARCH_X86_64 == 0
 %define dst2q r1
 %define dst2d r1d
 %endif
     mov       dst2d, dword [r1+r5*4]
     add       dst2q, r0
-    DC_ADD_MMX2_OP mova, dst2q, r3, r6
+    DC_ADD_MMXEXT_OP mova, dst2q, r3, r6
     lea       dst2q, [dst2q+r3*4]
-    DC_ADD_MMX2_OP mova, dst2q, r3, r6
+    DC_ADD_MMXEXT_OP mova, dst2q, r3, r6
 %if ARCH_X86_64 == 0
     mov          r1, r1m
 %endif
@@ -561,7 +566,7 @@
     jl .nextblock
     REP_RET
 .no_dc:
-INIT_XMM
+INIT_XMM cpuname
     mov       dst2d, dword [r1+r5*4]
     add       dst2q, r0
     IDCT8_ADD_SSE dst2q, r2, r3, r6
@@ -575,7 +580,7 @@
     jl .nextblock
     REP_RET
 
-INIT_MMX
+INIT_MMX mmx
 h264_idct_add8_mmx_plane:
 .nextblock:
     movzx        r6, byte [scan8+r5]
@@ -601,7 +606,7 @@
 
 ; 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_8_mmx, 5, 8 + npicregs, 0, dst1, block_offset, block, stride, nnzc, cntr, coeff, dst2, picreg
+cglobal h264_idct_add8_8, 5, 8 + npicregs, 0, dst1, block_offset, block, stride, nnzc, cntr, coeff, dst2, picreg
     mov          r5, 16
     add          r2, 512
 %ifdef PIC
@@ -621,7 +626,7 @@
     call         h264_idct_add8_mmx_plane
     RET
 
-h264_idct_add8_mmx2_plane:
+h264_idct_add8_mmxext_plane:
 .nextblock:
     movzx        r6, byte [scan8+r5]
     movzx        r6, byte [r4+r6]
@@ -645,7 +650,7 @@
     movsx        r6, word [r2]
     test         r6, r6
     jz .skipblock
-    DC_ADD_MMX2_INIT r2, r3, r6
+    DC_ADD_MMXEXT_INIT r2, r3, r6
 %if ARCH_X86_64
     mov         r0d, dword [r1+r5*4]
     add          r0, [dst2q]
@@ -654,7 +659,7 @@
     mov          r0, [r0]
     add          r0, dword [r1+r5*4]
 %endif
-    DC_ADD_MMX2_OP movh, r0, r3, r6
+    DC_ADD_MMXEXT_OP movh, r0, r3, r6
 .skipblock:
     inc          r5
     add          r2, 32
@@ -662,9 +667,10 @@
     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_8_mmx2, 5, 8 + npicregs, 0, dst1, block_offset, block, stride, nnzc, cntr, coeff, dst2, picreg
+INIT_MMX mmxext
+; ff_h264_idct_add8_mmxext(uint8_t **dest, const int *block_offset,
+;                          DCTELEM *block, int stride, const uint8_t nnzc[6*8])
+cglobal h264_idct_add8_8, 5, 8 + npicregs, 0, dst1, block_offset, block, stride, nnzc, cntr, coeff, dst2, picreg
     mov          r5, 16
     add          r2, 512
 %if ARCH_X86_64
@@ -673,7 +679,7 @@
 %ifdef PIC
     lea     picregq, [scan8_mem]
 %endif
-    call h264_idct_add8_mmx2_plane
+    call h264_idct_add8_mmxext_plane
     mov          r5, 32
     add          r2, 384
 %if ARCH_X86_64
@@ -681,12 +687,11 @@
 %else
     add        r0mp, gprsize
 %endif
-    call h264_idct_add8_mmx2_plane
+    call h264_idct_add8_mmxext_plane
     RET
 
-INIT_MMX
 ; r0 = uint8_t *dst, r2 = int16_t *block, r3 = int stride, r6=clobbered
-h264_idct_dc_add8_mmx2:
+h264_idct_dc_add8_mmxext:
     movd         m0, [r2   ]          ;  0 0 X D
     punpcklwd    m0, [r2+32]          ;  x X d D
     paddsw       m0, [pw_32]
@@ -698,11 +703,11 @@
     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
+    DC_ADD_MMXEXT_OP movq, r0, r3, r6
     ret
 
 ALIGN 16
-INIT_XMM
+INIT_XMM sse2
 ; r0 = uint8_t *dst (clobbered), r2 = int16_t *block, r3 = int stride
 h264_add8x4_idct_sse2:
     movq   m0, [r2+ 0]
@@ -742,7 +747,7 @@
 
 ; 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_8_sse2, 5, 5 + ARCH_X86_64, 8
+cglobal h264_idct_add16_8, 5, 5 + ARCH_X86_64, 8
 %if ARCH_X86_64
     mov         r5, r0
 %endif
@@ -780,7 +785,7 @@
 %else
     add         r0, r0m
 %endif
-    call        h264_idct_dc_add8_mmx2
+    call        h264_idct_dc_add8_mmxext
 .cycle%1end:
 %if %1 < 7
     add         r2, 64
@@ -789,7 +794,7 @@
 
 ; 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_8_sse2, 5, 7 + ARCH_X86_64, 8
+cglobal h264_idct_add16intra_8, 5, 7 + ARCH_X86_64, 8
 %if ARCH_X86_64
     mov         r7, r0
 %endif
@@ -829,7 +834,7 @@
     mov         r0, [r0]
     add         r0, dword [r1+(%1&1)*8+64*(1+(%1>>1))]
 %endif
-    call        h264_idct_dc_add8_mmx2
+    call        h264_idct_dc_add8_mmxext
 .cycle%1end:
 %if %1 == 1
     add         r2, 384+64
@@ -840,7 +845,7 @@
 
 ; 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_8_sse2, 5, 7 + ARCH_X86_64, 8
+cglobal h264_idct_add8_8, 5, 7 + ARCH_X86_64, 8
     add          r2, 512
 %if ARCH_X86_64
     mov          r7, r0
@@ -886,29 +891,8 @@
     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
+%macro STORE_WORDS 5-9
+%if cpuflag(sse)
     movd  t0d, %1
     psrldq  %1, 4
     movd  t1d, %1
@@ -928,9 +912,21 @@
     shr   t1d, 16
     mov [t2+%7*32], t0w
     mov [t2+%9*32], t1w
+%else
+    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
+%endif
 %endmacro
 
-%macro DEQUANT_STORE_SSE2 1
+%macro DEQUANT_STORE 1
+%if cpuflag(sse2)
     movd      xmm4, t3d
     movq      xmm5, [pw_1]
     pshufd    xmm4, xmm4, 0
@@ -952,15 +948,24 @@
     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
+    STORE_WORDS xmm0,  0,  1,  4,  5,  2,  3,  6,  7
+    STORE_WORDS xmm2,  8,  9, 12, 13, 10, 11, 14, 15
+%else
+    DEQUANT_MMX m0, m1, %1
+    STORE_WORDS m0,  0,  1,  4,  5
+    STORE_WORDS m1,  2,  3,  6,  7
+
+    DEQUANT_MMX m2, m3, %1
+    STORE_WORDS m2,  8,  9, 12, 13
+    STORE_WORDS m3, 10, 11, 14, 15
+%endif
 %endmacro
 
-%macro IDCT_DC_DEQUANT 2
-cglobal h264_luma_dc_dequant_idct_%1, 3,4,%2
+%macro IDCT_DC_DEQUANT 1
+cglobal h264_luma_dc_dequant_idct, 3, 4, %1
     ; manually spill XMM registers for Win64 because
     ; the code here is initialized with INIT_MMX
-    WIN64_SPILL_XMM %2
+    WIN64_SPILL_XMM %1
     movq        m3, [r1+24]
     movq        m2, [r1+16]
     movq        m1, [r1+ 8]
@@ -983,11 +988,7 @@
     cmp        t3d, 32767
     jg .big_qmul
     add        t3d, 128 << 16
-%ifidn %1,mmx
-    DEQUANT_STORE_MMX 8
-%else
-    DEQUANT_STORE_SSE2 8
-%endif
+    DEQUANT_STORE 8
     RET
 .big_qmul:
     bsr        t0d, t3d
@@ -998,16 +999,17 @@
     inc        t1d
     shr        t3d, t0b
     sub        t1d, t0d
-%ifidn %1,mmx
-    movd        m6, t1d
-    DEQUANT_STORE_MMX m6
-%else
+%if cpuflag(sse2)
     movd      xmm6, t1d
-    DEQUANT_STORE_SSE2 xmm6
+    DEQUANT_STORE xmm6
+%else
+    movd        m6, t1d
+    DEQUANT_STORE m6
 %endif
     RET
 %endmacro
 
-INIT_MMX
-IDCT_DC_DEQUANT mmx, 0
-IDCT_DC_DEQUANT sse2, 7
+INIT_MMX mmx
+IDCT_DC_DEQUANT 0
+INIT_MMX sse2
+IDCT_DC_DEQUANT 7
diff --git a/libavcodec/x86/h264_idct_10bit.asm b/libavcodec/x86/h264_idct_10bit.asm
index 525ce39..eb375f9 100644
--- a/libavcodec/x86/h264_idct_10bit.asm
+++ b/libavcodec/x86/h264_idct_10bit.asm
@@ -22,7 +22,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
@@ -185,7 +184,7 @@
     mova [%1+%3  ], m4
 %endmacro
 
-INIT_MMX mmx2
+INIT_MMX mmxext
 cglobal h264_idct_dc_add_10,3,3
     movd      m0, [r1]
     paddd     m0, [pd_32]
diff --git a/libavcodec/x86/h264_intrapred.asm b/libavcodec/x86/h264_intrapred.asm
index 609cb23..5c0dff4 100644
--- a/libavcodec/x86/h264_intrapred.asm
+++ b/libavcodec/x86/h264_intrapred.asm
@@ -22,7 +22,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
@@ -50,10 +49,11 @@
 cextern pw_32
 
 ;-----------------------------------------------------------------------------
-; void pred16x16_vertical(uint8_t *src, int stride)
+; void pred16x16_vertical_8(uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
 
-cglobal pred16x16_vertical_mmx, 2,3
+INIT_MMX mmx
+cglobal pred16x16_vertical_8, 2,3
     sub   r0, r1
     mov   r2, 8
     movq mm0, [r0+0]
@@ -68,7 +68,8 @@
     jg .loop
     REP_RET
 
-cglobal pred16x16_vertical_sse, 2,3
+INIT_XMM sse
+cglobal pred16x16_vertical_8, 2,3
     sub   r0, r1
     mov   r2, 4
     movaps xmm0, [r0]
@@ -84,11 +85,11 @@
     REP_RET
 
 ;-----------------------------------------------------------------------------
-; void pred16x16_horizontal(uint8_t *src, int stride)
+; void pred16x16_horizontal_8(uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
 
 %macro PRED16x16_H 0
-cglobal pred16x16_horizontal, 2,3
+cglobal pred16x16_horizontal_8, 2,3
     mov       r2, 8
 %if cpuflag(ssse3)
     mova      m2, [pb_3]
@@ -119,18 +120,17 @@
 
 INIT_MMX mmx
 PRED16x16_H
-INIT_MMX mmx2
+INIT_MMX mmxext
 PRED16x16_H
 INIT_XMM ssse3
 PRED16x16_H
-INIT_XMM
 
 ;-----------------------------------------------------------------------------
-; void pred16x16_dc(uint8_t *src, int stride)
+; void pred16x16_dc_8(uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
 
 %macro PRED16x16_DC 0
-cglobal pred16x16_dc, 2,7
+cglobal pred16x16_dc_8, 2,7
     mov       r4, r0
     sub       r0, r1
     pxor      mm0, mm0
@@ -180,20 +180,19 @@
     REP_RET
 %endmacro
 
-INIT_MMX mmx2
+INIT_MMX mmxext
 PRED16x16_DC
 INIT_XMM sse2
 PRED16x16_DC
 INIT_XMM ssse3
 PRED16x16_DC
-INIT_XMM
 
 ;-----------------------------------------------------------------------------
-; void pred16x16_tm_vp8(uint8_t *src, int stride)
+; void pred16x16_tm_vp8_8(uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
 
-%macro PRED16x16_TM_MMX 0
-cglobal pred16x16_tm_vp8, 2,5
+%macro PRED16x16_TM 0
+cglobal pred16x16_tm_vp8_8, 2,5
     sub        r0, r1
     pxor      mm7, mm7
     movq      mm0, [r0+0]
@@ -229,12 +228,12 @@
 %endmacro
 
 INIT_MMX mmx
-PRED16x16_TM_MMX
-INIT_MMX mmx2
-PRED16x16_TM_MMX
-INIT_MMX
+PRED16x16_TM
+INIT_MMX mmxext
+PRED16x16_TM
 
-cglobal pred16x16_tm_vp8_sse2, 2,6,6
+INIT_XMM sse2
+cglobal pred16x16_tm_vp8_8, 2,6,6
     sub          r0, r1
     pxor       xmm2, xmm2
     movdqa     xmm0, [r0]
@@ -270,11 +269,11 @@
     REP_RET
 
 ;-----------------------------------------------------------------------------
-; void pred16x16_plane(uint8_t *src, int stride)
+; void pred16x16_plane_*_8(uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
 
 %macro H264_PRED16x16_PLANE 1
-cglobal pred16x16_plane_%1, 2,9,7
+cglobal pred16x16_plane_%1_8, 2,9,7
     mov          r2, r1           ; +stride
     neg          r1               ; -stride
 
@@ -310,14 +309,14 @@
     movhlps      m1, m0
 %endif
     paddw        m0, m1
-%if cpuflag(mmx2)
+%if cpuflag(mmxext)
     PSHUFLW      m1, m0, 0xE
 %elif cpuflag(mmx)
     mova         m1, m0
     psrlq        m1, 32
 %endif
     paddw        m0, m1
-%if cpuflag(mmx2)
+%if cpuflag(mmxext)
     PSHUFLW      m1, m0, 0x1
 %elif cpuflag(mmx)
     mova         m1, m0
@@ -537,7 +536,7 @@
 H264_PRED16x16_PLANE h264
 H264_PRED16x16_PLANE rv40
 H264_PRED16x16_PLANE svq3
-INIT_MMX mmx2
+INIT_MMX mmxext
 H264_PRED16x16_PLANE h264
 H264_PRED16x16_PLANE rv40
 H264_PRED16x16_PLANE svq3
@@ -549,14 +548,13 @@
 H264_PRED16x16_PLANE h264
 H264_PRED16x16_PLANE rv40
 H264_PRED16x16_PLANE svq3
-INIT_XMM
 
 ;-----------------------------------------------------------------------------
-; void pred8x8_plane(uint8_t *src, int stride)
+; void pred8x8_plane_8(uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
 
 %macro H264_PRED8x8_PLANE 0
-cglobal pred8x8_plane, 2,9,7
+cglobal pred8x8_plane_8, 2,9,7
     mov          r2, r1           ; +stride
     neg          r1               ; -stride
 
@@ -584,7 +582,7 @@
     paddw        m0, m1
 
 %if notcpuflag(ssse3)
-%if cpuflag(mmx2)
+%if cpuflag(mmxext)
     PSHUFLW      m1, m0, 0xE
 %elif cpuflag(mmx)
     mova         m1, m0
@@ -593,7 +591,7 @@
     paddw        m0, m1
 %endif ; !ssse3
 
-%if cpuflag(mmx2)
+%if cpuflag(mmxext)
     PSHUFLW      m1, m0, 0x1
 %elif cpuflag(mmx)
     mova         m1, m0
@@ -718,19 +716,19 @@
 
 INIT_MMX mmx
 H264_PRED8x8_PLANE
-INIT_MMX mmx2
+INIT_MMX mmxext
 H264_PRED8x8_PLANE
 INIT_XMM sse2
 H264_PRED8x8_PLANE
 INIT_XMM ssse3
 H264_PRED8x8_PLANE
-INIT_XMM
 
 ;-----------------------------------------------------------------------------
-; void pred8x8_vertical(uint8_t *src, int stride)
+; void pred8x8_vertical_8(uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
 
-cglobal pred8x8_vertical_mmx, 2,2
+INIT_MMX mmx
+cglobal pred8x8_vertical_8, 2,2
     sub    r0, r1
     movq  mm0, [r0]
 %rep 3
@@ -743,11 +741,11 @@
     RET
 
 ;-----------------------------------------------------------------------------
-; void pred8x8_horizontal(uint8_t *src, int stride)
+; void pred8x8_horizontal_8(uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
 
 %macro PRED8x8_H 0
-cglobal pred8x8_horizontal, 2,3
+cglobal pred8x8_horizontal_8, 2,3
     mov       r2, 4
 %if cpuflag(ssse3)
     mova      m2, [pb_3]
@@ -765,16 +763,16 @@
 
 INIT_MMX mmx
 PRED8x8_H
-INIT_MMX mmx2
+INIT_MMX mmxext
 PRED8x8_H
 INIT_MMX ssse3
 PRED8x8_H
-INIT_MMX
 
 ;-----------------------------------------------------------------------------
-; void pred8x8_top_dc_mmxext(uint8_t *src, int stride)
+; void pred8x8_top_dc_8_mmxext(uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
-cglobal pred8x8_top_dc_mmxext, 2,5
+INIT_MMX mmxext
+cglobal pred8x8_top_dc_8, 2,5
     sub         r0, r1
     movq       mm0, [r0]
     pxor       mm1, mm1
@@ -805,11 +803,11 @@
     RET
 
 ;-----------------------------------------------------------------------------
-; void pred8x8_dc_mmxext(uint8_t *src, int stride)
+; void pred8x8_dc_8_mmxext(uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
 
-INIT_MMX
-cglobal pred8x8_dc_mmxext, 2,5
+INIT_MMX mmxext
+cglobal pred8x8_dc_8, 2,5
     sub       r0, r1
     pxor      m7, m7
     movd      m0, [r0+0]
@@ -866,10 +864,11 @@
     RET
 
 ;-----------------------------------------------------------------------------
-; void pred8x8_dc_rv40(uint8_t *src, int stride)
+; void pred8x8_dc_rv40_8(uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
 
-cglobal pred8x8_dc_rv40_mmxext, 2,7
+INIT_MMX mmxext
+cglobal pred8x8_dc_rv40_8, 2,7
     mov       r4, r0
     sub       r0, r1
     pxor      mm0, mm0
@@ -902,11 +901,11 @@
     REP_RET
 
 ;-----------------------------------------------------------------------------
-; void pred8x8_tm_vp8(uint8_t *src, int stride)
+; void pred8x8_tm_vp8_8(uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
 
-%macro PRED8x8_TM_MMX 0
-cglobal pred8x8_tm_vp8, 2,6
+%macro PRED8x8_TM 0
+cglobal pred8x8_tm_vp8_8, 2,6
     sub        r0, r1
     pxor      mm7, mm7
     movq      mm0, [r0]
@@ -941,12 +940,12 @@
 %endmacro
 
 INIT_MMX mmx
-PRED8x8_TM_MMX
-INIT_MMX mmx2
-PRED8x8_TM_MMX
-INIT_MMX
+PRED8x8_TM
+INIT_MMX mmxext
+PRED8x8_TM
 
-cglobal pred8x8_tm_vp8_sse2, 2,6,4
+INIT_XMM sse2
+cglobal pred8x8_tm_vp8_8, 2,6,4
     sub          r0, r1
     pxor       xmm1, xmm1
     movq       xmm0, [r0]
@@ -974,7 +973,8 @@
     jg .loop
     REP_RET
 
-cglobal pred8x8_tm_vp8_ssse3, 2,3,6
+INIT_XMM ssse3
+cglobal pred8x8_tm_vp8_8, 2,3,6
     sub          r0, r1
     movdqa     xmm4, [tm_shuf]
     pxor       xmm1, xmm1
@@ -1013,10 +1013,10 @@
 %endmacro
 
 ;-----------------------------------------------------------------------------
-; void pred8x8l_top_dc(uint8_t *src, int has_topleft, int has_topright, int stride)
+; void pred8x8l_top_dc_8(uint8_t *src, int has_topleft, int has_topright, int stride)
 ;-----------------------------------------------------------------------------
-%macro PRED8x8L_TOP_DC 1
-cglobal pred8x8l_top_dc_%1, 4,4
+%macro PRED8x8L_TOP_DC 0
+cglobal pred8x8l_top_dc_8, 4,4
     sub          r0, r3
     pxor        mm7, mm7
     movq        mm0, [r0-8]
@@ -1062,18 +1062,17 @@
     RET
 %endmacro
 
-INIT_MMX
-%define PALIGNR PALIGNR_MMX
-PRED8x8L_TOP_DC mmxext
-%define PALIGNR PALIGNR_SSSE3
-PRED8x8L_TOP_DC ssse3
+INIT_MMX mmxext
+PRED8x8L_TOP_DC
+INIT_MMX ssse3
+PRED8x8L_TOP_DC
 
 ;-----------------------------------------------------------------------------
-;void pred8x8l_dc(uint8_t *src, int has_topleft, int has_topright, int stride)
+;void pred8x8l_dc_8(uint8_t *src, int has_topleft, int has_topright, int stride)
 ;-----------------------------------------------------------------------------
 
-%macro PRED8x8L_DC 1
-cglobal pred8x8l_dc_%1, 4,5
+%macro PRED8x8L_DC 0
+cglobal pred8x8l_dc_8, 4,5
     sub          r0, r3
     lea          r4, [r0+r3*2]
     movq        mm0, [r0+r3*1-8]
@@ -1165,18 +1164,18 @@
     movq [r4+r3*2], mm0
     RET
 %endmacro
-INIT_MMX
-%define PALIGNR PALIGNR_MMX
-PRED8x8L_DC mmxext
-%define PALIGNR PALIGNR_SSSE3
-PRED8x8L_DC ssse3
+
+INIT_MMX mmxext
+PRED8x8L_DC
+INIT_MMX ssse3
+PRED8x8L_DC
 
 ;-----------------------------------------------------------------------------
-; void pred8x8l_horizontal(uint8_t *src, int has_topleft, int has_topright, int stride)
+; void pred8x8l_horizontal_8(uint8_t *src, int has_topleft, int has_topright, int stride)
 ;-----------------------------------------------------------------------------
 
-%macro PRED8x8L_HORIZONTAL 1
-cglobal pred8x8l_horizontal_%1, 4,4
+%macro PRED8x8L_HORIZONTAL 0
+cglobal pred8x8l_horizontal_8, 4,4
     sub          r0, r3
     lea          r2, [r0+r3*2]
     movq        mm0, [r0+r3*1-8]
@@ -1237,18 +1236,17 @@
     RET
 %endmacro
 
-INIT_MMX
-%define PALIGNR PALIGNR_MMX
-PRED8x8L_HORIZONTAL mmxext
-%define PALIGNR PALIGNR_SSSE3
-PRED8x8L_HORIZONTAL ssse3
+INIT_MMX mmxext
+PRED8x8L_HORIZONTAL
+INIT_MMX ssse3
+PRED8x8L_HORIZONTAL
 
 ;-----------------------------------------------------------------------------
-; void pred8x8l_vertical(uint8_t *src, int has_topleft, int has_topright, int stride)
+; void pred8x8l_vertical_8(uint8_t *src, int has_topleft, int has_topright, int stride)
 ;-----------------------------------------------------------------------------
 
-%macro PRED8x8L_VERTICAL 1
-cglobal pred8x8l_vertical_%1, 4,4
+%macro PRED8x8L_VERTICAL 0
+cglobal pred8x8l_vertical_8, 4,4
     sub          r0, r3
     movq        mm0, [r0-8]
     movq        mm3, [r0]
@@ -1288,19 +1286,17 @@
     RET
 %endmacro
 
-INIT_MMX
-%define PALIGNR PALIGNR_MMX
-PRED8x8L_VERTICAL mmxext
-%define PALIGNR PALIGNR_SSSE3
-PRED8x8L_VERTICAL ssse3
+INIT_MMX mmxext
+PRED8x8L_VERTICAL
+INIT_MMX ssse3
+PRED8x8L_VERTICAL
 
 ;-----------------------------------------------------------------------------
-;void pred8x8l_down_left(uint8_t *src, int has_topleft, int has_topright, int stride)
+;void pred8x8l_down_left_8(uint8_t *src, int has_topleft, int has_topright, int stride)
 ;-----------------------------------------------------------------------------
 
-INIT_MMX
-%define PALIGNR PALIGNR_MMX
-cglobal pred8x8l_down_left_mmxext, 4,5
+INIT_MMX mmxext
+cglobal pred8x8l_down_left_8, 4,5
     sub          r0, r3
     movq        mm0, [r0-8]
     movq        mm3, [r0]
@@ -1407,8 +1403,8 @@
     movq  [r0+r3*1], mm1
     RET
 
-%macro PRED8x8L_DOWN_LEFT 1
-cglobal pred8x8l_down_left_%1, 4,4
+%macro PRED8x8L_DOWN_LEFT 0
+cglobal pred8x8l_down_left_8, 4,4
     sub          r0, r3
     movq        mm0, [r0-8]
     movq        mm3, [r0]
@@ -1468,7 +1464,7 @@
     lea         r2, [r1+r3*2]
     movdqa    xmm1, xmm3
     pslldq    xmm1, 1
-INIT_XMM
+INIT_XMM cpuname
     PRED4x4_LOWPASS xmm0, xmm1, xmm2, xmm3, xmm4
     psrldq    xmm0, 1
     movq [r0+r3*1], xmm0
@@ -1490,20 +1486,17 @@
     RET
 %endmacro
 
-INIT_MMX
-%define PALIGNR PALIGNR_MMX
-PRED8x8L_DOWN_LEFT sse2
-INIT_MMX
-%define PALIGNR PALIGNR_SSSE3
-PRED8x8L_DOWN_LEFT ssse3
+INIT_MMX sse2
+PRED8x8L_DOWN_LEFT
+INIT_MMX ssse3
+PRED8x8L_DOWN_LEFT
 
 ;-----------------------------------------------------------------------------
-;void pred8x8l_down_right_mmxext(uint8_t *src, int has_topleft, int has_topright, int stride)
+;void pred8x8l_down_right_8_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
+INIT_MMX mmxext
+cglobal pred8x8l_down_right_8, 4,5
     sub          r0, r3
     lea          r4, [r0+r3*2]
     movq        mm0, [r0+r3*1-8]
@@ -1634,8 +1627,8 @@
     movq [r0+r3*1], mm0
     RET
 
-%macro PRED8x8L_DOWN_RIGHT 1
-cglobal pred8x8l_down_right_%1, 4,5
+%macro PRED8x8L_DOWN_RIGHT 0
+cglobal pred8x8l_down_right_8, 4,5
     sub          r0, r3
     lea          r4, [r0+r3*2]
     movq        mm0, [r0+r3*1-8]
@@ -1723,7 +1716,7 @@
     lea         r0, [r2+r3*2]
     movdqa    xmm2, xmm3
     psrldq    xmm2, 1
-INIT_XMM
+INIT_XMM cpuname
     PRED4x4_LOWPASS xmm0, xmm1, xmm2, xmm3, xmm4
     movdqa    xmm1, xmm0
     psrldq    xmm1, 1
@@ -1744,20 +1737,17 @@
     RET
 %endmacro
 
-INIT_MMX
-%define PALIGNR PALIGNR_MMX
-PRED8x8L_DOWN_RIGHT sse2
-INIT_MMX
-%define PALIGNR PALIGNR_SSSE3
-PRED8x8L_DOWN_RIGHT ssse3
+INIT_MMX sse2
+PRED8x8L_DOWN_RIGHT
+INIT_MMX ssse3
+PRED8x8L_DOWN_RIGHT
 
 ;-----------------------------------------------------------------------------
-; void pred8x8l_vertical_right(uint8_t *src, int has_topleft, int has_topright, int stride)
+; void pred8x8l_vertical_right_8(uint8_t *src, int has_topleft, int has_topright, int stride)
 ;-----------------------------------------------------------------------------
 
-INIT_MMX
-%define PALIGNR PALIGNR_MMX
-cglobal pred8x8l_vertical_right_mmxext, 4,5
+INIT_MMX mmxext
+cglobal pred8x8l_vertical_right_8, 4,5
     sub          r0, r3
     lea          r4, [r0+r3*2]
     movq        mm0, [r0+r3*1-8]
@@ -1863,8 +1853,8 @@
     movq [r4+r3*2], mm5
     RET
 
-%macro PRED8x8L_VERTICAL_RIGHT 1
-cglobal pred8x8l_vertical_right_%1, 4,5,7
+%macro PRED8x8L_VERTICAL_RIGHT 0
+cglobal pred8x8l_vertical_right_8, 4,5,7
     ; manually spill XMM registers for Win64 because
     ; the code here is initialized with INIT_MMX
     WIN64_SPILL_XMM 7
@@ -1945,7 +1935,7 @@
     pslldq      xmm0, 1
     pslldq      xmm1, 2
     pavgb       xmm2, xmm0
-INIT_XMM
+INIT_XMM cpuname
     PRED4x4_LOWPASS xmm4, xmm3, xmm1, xmm0, xmm5
     pandn       xmm6, xmm4
     movdqa      xmm5, xmm4
@@ -1974,19 +1964,17 @@
     RET
 %endmacro
 
-INIT_MMX
-%define PALIGNR PALIGNR_MMX
-PRED8x8L_VERTICAL_RIGHT sse2
-INIT_MMX
-%define PALIGNR PALIGNR_SSSE3
-PRED8x8L_VERTICAL_RIGHT ssse3
+INIT_MMX sse2
+PRED8x8L_VERTICAL_RIGHT
+INIT_MMX ssse3
+PRED8x8L_VERTICAL_RIGHT
 
 ;-----------------------------------------------------------------------------
-;void pred8x8l_vertical_left(uint8_t *src, int has_topleft, int has_topright, int stride)
+;void pred8x8l_vertical_left_8(uint8_t *src, int has_topleft, int has_topright, int stride)
 ;-----------------------------------------------------------------------------
 
-%macro PRED8x8L_VERTICAL_LEFT 1
-cglobal pred8x8l_vertical_left_%1, 4,4
+%macro PRED8x8L_VERTICAL_LEFT 0
+cglobal pred8x8l_vertical_left_8, 4,4
     sub          r0, r3
     movq        mm0, [r0-8]
     movq        mm3, [r0]
@@ -2044,7 +2032,7 @@
     pslldq    xmm1, 1
     pavgb     xmm3, xmm2
     lea         r2, [r1+r3*2]
-INIT_XMM
+INIT_XMM cpuname
     PRED4x4_LOWPASS xmm0, xmm1, xmm2, xmm4, xmm5
     psrldq    xmm0, 1
     movq [r0+r3*1], xmm3
@@ -2065,19 +2053,17 @@
     RET
 %endmacro
 
-INIT_MMX
-%define PALIGNR PALIGNR_MMX
-PRED8x8L_VERTICAL_LEFT sse2
-%define PALIGNR PALIGNR_SSSE3
-INIT_MMX
-PRED8x8L_VERTICAL_LEFT ssse3
+INIT_MMX sse2
+PRED8x8L_VERTICAL_LEFT
+INIT_MMX ssse3
+PRED8x8L_VERTICAL_LEFT
 
 ;-----------------------------------------------------------------------------
-; void pred8x8l_horizontal_up(uint8_t *src, int has_topleft, int has_topright, int stride)
+; void pred8x8l_horizontal_up_8(uint8_t *src, int has_topleft, int has_topright, int stride)
 ;-----------------------------------------------------------------------------
 
-%macro PRED8x8L_HORIZONTAL_UP 1
-cglobal pred8x8l_horizontal_up_%1, 4,4
+%macro PRED8x8L_HORIZONTAL_UP 0
+cglobal pred8x8l_horizontal_up_8, 4,4
     sub          r0, r3
     lea          r2, [r0+r3*2]
     movq        mm0, [r0+r3*1-8]
@@ -2154,19 +2140,17 @@
     RET
 %endmacro
 
-INIT_MMX
-%define PALIGNR PALIGNR_MMX
-PRED8x8L_HORIZONTAL_UP mmxext
-%define PALIGNR PALIGNR_SSSE3
-PRED8x8L_HORIZONTAL_UP ssse3
+INIT_MMX mmxext
+PRED8x8L_HORIZONTAL_UP
+INIT_MMX ssse3
+PRED8x8L_HORIZONTAL_UP
 
 ;-----------------------------------------------------------------------------
-;void pred8x8l_horizontal_down(uint8_t *src, int has_topleft, int has_topright, int stride)
+;void pred8x8l_horizontal_down_8(uint8_t *src, int has_topleft, int has_topright, int stride)
 ;-----------------------------------------------------------------------------
 
-INIT_MMX
-%define PALIGNR PALIGNR_MMX
-cglobal pred8x8l_horizontal_down_mmxext, 4,5
+INIT_MMX mmxext
+cglobal pred8x8l_horizontal_down_8, 4,5
     sub          r0, r3
     lea          r4, [r0+r3*2]
     movq        mm0, [r0+r3*1-8]
@@ -2280,8 +2264,8 @@
     movq [r0+r3*1], mm3
     RET
 
-%macro PRED8x8L_HORIZONTAL_DOWN 1
-cglobal pred8x8l_horizontal_down_%1, 4,5
+%macro PRED8x8L_HORIZONTAL_DOWN 0
+cglobal pred8x8l_horizontal_down_8, 4,5
     sub          r0, r3
     lea          r4, [r0+r3*2]
     movq        mm0, [r0+r3*1-8]
@@ -2373,7 +2357,7 @@
     movq2dq    xmm5, mm1
     pslldq     xmm5, 8
     por        xmm1, xmm5
-INIT_XMM
+INIT_XMM cpuname
     lea         r2, [r4+r3*2]
     movdqa    xmm2, xmm1
     movdqa    xmm3, xmm1
@@ -2404,18 +2388,17 @@
     RET
 %endmacro
 
-INIT_MMX
-%define PALIGNR PALIGNR_MMX
-PRED8x8L_HORIZONTAL_DOWN sse2
-INIT_MMX
-%define PALIGNR PALIGNR_SSSE3
-PRED8x8L_HORIZONTAL_DOWN ssse3
+INIT_MMX sse2
+PRED8x8L_HORIZONTAL_DOWN
+INIT_MMX ssse3
+PRED8x8L_HORIZONTAL_DOWN
 
 ;-----------------------------------------------------------------------------
-; void pred4x4_dc_mmxext(uint8_t *src, const uint8_t *topright, int stride)
+; void pred4x4_dc_8_mmxext(uint8_t *src, const uint8_t *topright, int stride)
 ;-----------------------------------------------------------------------------
 
-cglobal pred4x4_dc_mmxext, 3,5
+INIT_MMX mmxext
+cglobal pred4x4_dc_8, 3,5
     pxor   mm7, mm7
     mov     r4, r0
     sub     r0, r2
@@ -2441,11 +2424,11 @@
     RET
 
 ;-----------------------------------------------------------------------------
-; void pred4x4_tm_vp8_mmxext(uint8_t *src, const uint8_t *topright, int stride)
+; void pred4x4_tm_vp8_8_mmxext(uint8_t *src, const uint8_t *topright, int stride)
 ;-----------------------------------------------------------------------------
 
-%macro PRED4x4_TM_MMX 0
-cglobal pred4x4_tm_vp8, 3,6
+%macro PRED4x4_TM 0
+cglobal pred4x4_tm_vp8_8, 3,6
     sub        r0, r2
     pxor      mm7, mm7
     movd      mm0, [r0]
@@ -2459,7 +2442,7 @@
     sub       r3d, r4d
     movd      mm2, r1d
     movd      mm4, r3d
-%if cpuflag(mmx2)
+%if cpuflag(mmxext)
     pshufw    mm2, mm2, 0
     pshufw    mm4, mm4, 0
 %else
@@ -2481,12 +2464,12 @@
 %endmacro
 
 INIT_MMX mmx
-PRED4x4_TM_MMX
-INIT_MMX mmx2
-PRED4x4_TM_MMX
-INIT_MMX
+PRED4x4_TM
+INIT_MMX mmxext
+PRED4x4_TM
 
-cglobal pred4x4_tm_vp8_ssse3, 3,3
+INIT_XMM ssse3
+cglobal pred4x4_tm_vp8_8, 3,3
     sub         r0, r2
     movq       mm6, [tm_shuf]
     pxor       mm1, mm1
@@ -2522,11 +2505,11 @@
     RET
 
 ;-----------------------------------------------------------------------------
-; void pred4x4_vertical_vp8_mmxext(uint8_t *src, const uint8_t *topright, int stride)
+; void pred4x4_vertical_vp8_8_mmxext(uint8_t *src, const uint8_t *topright, int stride)
 ;-----------------------------------------------------------------------------
 
-INIT_MMX
-cglobal pred4x4_vertical_vp8_mmxext, 3,3
+INIT_MMX mmxext
+cglobal pred4x4_vertical_vp8_8, 3,3
     sub       r0, r2
     movd      m1, [r0-1]
     movd      m0, [r0]
@@ -2542,10 +2525,10 @@
     RET
 
 ;-----------------------------------------------------------------------------
-; void pred4x4_down_left_mmxext(uint8_t *src, const uint8_t *topright, int stride)
+; void pred4x4_down_left_8_mmxext(uint8_t *src, const uint8_t *topright, int stride)
 ;-----------------------------------------------------------------------------
-INIT_MMX
-cglobal pred4x4_down_left_mmxext, 3,3
+INIT_MMX mmxext
+cglobal pred4x4_down_left_8, 3,3
     sub       r0, r2
     movq      m1, [r0]
     punpckldq m1, [r1]
@@ -2568,11 +2551,11 @@
     RET
 
 ;-----------------------------------------------------------------------------
-; void pred4x4_vertical_left_mmxext(uint8_t *src, const uint8_t *topright, int stride)
+; void pred4x4_vertical_left_8_mmxext(uint8_t *src, const uint8_t *topright, int stride)
 ;-----------------------------------------------------------------------------
 
-INIT_MMX
-cglobal pred4x4_vertical_left_mmxext, 3,3
+INIT_MMX mmxext
+cglobal pred4x4_vertical_left_8, 3,3
     sub       r0, r2
     movq      m1, [r0]
     punpckldq m1, [r1]
@@ -2593,11 +2576,11 @@
     RET
 
 ;-----------------------------------------------------------------------------
-; void pred4x4_horizontal_up_mmxext(uint8_t *src, const uint8_t *topright, int stride)
+; void pred4x4_horizontal_up_8_mmxext(uint8_t *src, const uint8_t *topright, int stride)
 ;-----------------------------------------------------------------------------
 
-INIT_MMX
-cglobal pred4x4_horizontal_up_mmxext, 3,3
+INIT_MMX mmxext
+cglobal pred4x4_horizontal_up_8, 3,3
     sub       r0, r2
     lea       r1, [r0+r2*2]
     movd      m0, [r0+r2*1-4]
@@ -2626,12 +2609,11 @@
     RET
 
 ;-----------------------------------------------------------------------------
-; void pred4x4_horizontal_down_mmxext(uint8_t *src, const uint8_t *topright, int stride)
+; void pred4x4_horizontal_down_8_mmxext(uint8_t *src, const uint8_t *topright, int stride)
 ;-----------------------------------------------------------------------------
 
-INIT_MMX
-%define PALIGNR PALIGNR_MMX
-cglobal pred4x4_horizontal_down_mmxext, 3,3
+INIT_MMX mmxext
+cglobal pred4x4_horizontal_down_8, 3,3
     sub       r0, r2
     lea       r1, [r0+r2*2]
     movh      m0, [r0-4]      ; lt ..
@@ -2662,12 +2644,11 @@
     RET
 
 ;-----------------------------------------------------------------------------
-; void pred4x4_vertical_right_mmxext(uint8_t *src, const uint8_t *topright, int stride)
+; void pred4x4_vertical_right_8_mmxext(uint8_t *src, const uint8_t *topright, int stride)
 ;-----------------------------------------------------------------------------
 
-INIT_MMX
-%define PALIGNR PALIGNR_MMX
-cglobal pred4x4_vertical_right_mmxext, 3,3
+INIT_MMX mmxext
+cglobal pred4x4_vertical_right_8, 3,3
     sub     r0, r2
     lea     r1, [r0+r2*2]
     movh    m0, [r0]                    ; ........t3t2t1t0
@@ -2693,12 +2674,11 @@
     RET
 
 ;-----------------------------------------------------------------------------
-; void pred4x4_down_right_mmxext(uint8_t *src, const uint8_t *topright, int stride)
+; void pred4x4_down_right_8_mmxext(uint8_t *src, const uint8_t *topright, int stride)
 ;-----------------------------------------------------------------------------
 
-INIT_MMX
-%define PALIGNR PALIGNR_MMX
-cglobal pred4x4_down_right_mmxext, 3,3
+INIT_MMX mmxext
+cglobal pred4x4_down_right_8, 3,3
     sub       r0, r2
     lea       r1, [r0+r2*2]
     movq      m1, [r1-8]
diff --git a/libavcodec/x86/h264_intrapred_10bit.asm b/libavcodec/x86/h264_intrapred_10bit.asm
index 4eeb0a4..db2b25c 100644
--- a/libavcodec/x86/h264_intrapred_10bit.asm
+++ b/libavcodec/x86/h264_intrapred_10bit.asm
@@ -22,7 +22,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
@@ -53,8 +52,8 @@
 ;-----------------------------------------------------------------------------
 ; void pred4x4_down_right(pixel *src, const pixel *topright, int stride)
 ;-----------------------------------------------------------------------------
-%macro PRED4x4_DR 1
-cglobal pred4x4_down_right_10_%1, 3,3
+%macro PRED4x4_DR 0
+cglobal pred4x4_down_right_10, 3, 3
     sub       r0, r2
     lea       r1, [r0+r2*2]
     movhps    m1, [r1-8]
@@ -79,21 +78,20 @@
     RET
 %endmacro
 
-INIT_XMM
-%define PALIGNR PALIGNR_MMX
-PRED4x4_DR sse2
-%define PALIGNR PALIGNR_SSSE3
-PRED4x4_DR ssse3
+INIT_XMM sse2
+PRED4x4_DR
+INIT_XMM ssse3
+PRED4x4_DR
 %if HAVE_AVX_EXTERNAL
-INIT_AVX
-PRED4x4_DR avx
+INIT_XMM avx
+PRED4x4_DR
 %endif
 
 ;-----------------------------------------------------------------------------
 ; void pred4x4_vertical_right(pixel *src, const pixel *topright, int stride)
 ;-----------------------------------------------------------------------------
-%macro PRED4x4_VR 1
-cglobal pred4x4_vertical_right_10_%1, 3,3,6
+%macro PRED4x4_VR 0
+cglobal pred4x4_vertical_right_10, 3, 3, 6
     sub     r0, r2
     lea     r1, [r0+r2*2]
     movq    m5, [r0]            ; ........t3t2t1t0
@@ -119,21 +117,20 @@
     RET
 %endmacro
 
-INIT_XMM
-%define PALIGNR PALIGNR_MMX
-PRED4x4_VR sse2
-%define PALIGNR PALIGNR_SSSE3
-PRED4x4_VR ssse3
+INIT_XMM sse2
+PRED4x4_VR
+INIT_XMM ssse3
+PRED4x4_VR
 %if HAVE_AVX_EXTERNAL
-INIT_AVX
-PRED4x4_VR avx
+INIT_XMM avx
+PRED4x4_VR
 %endif
 
 ;-----------------------------------------------------------------------------
 ; void pred4x4_horizontal_down(pixel *src, const pixel *topright, int stride)
 ;-----------------------------------------------------------------------------
-%macro PRED4x4_HD 1
-cglobal pred4x4_horizontal_down_10_%1, 3,3
+%macro PRED4x4_HD 0
+cglobal pred4x4_horizontal_down_10, 3, 3
     sub        r0, r2
     lea        r1, [r0+r2*2]
     movq       m0, [r0-8]      ; lt ..
@@ -162,14 +159,13 @@
     RET
 %endmacro
 
-INIT_XMM
-%define PALIGNR PALIGNR_MMX
-PRED4x4_HD sse2
-%define PALIGNR PALIGNR_SSSE3
-PRED4x4_HD ssse3
+INIT_XMM sse2
+PRED4x4_HD
+INIT_XMM ssse3
+PRED4x4_HD
 %if HAVE_AVX_EXTERNAL
-INIT_AVX
-PRED4x4_HD avx
+INIT_XMM avx
+PRED4x4_HD
 %endif
 
 ;-----------------------------------------------------------------------------
@@ -192,8 +188,8 @@
     HADDD   %1, %2
 %endmacro
 
-INIT_MMX
-cglobal pred4x4_dc_10_mmxext, 3,3
+INIT_MMX mmxext
+cglobal pred4x4_dc_10, 3, 3
     sub    r0, r2
     lea    r1, [r0+r2*2]
     movq   m2, [r0+r2*1-8]
@@ -216,8 +212,8 @@
 ;-----------------------------------------------------------------------------
 ; void pred4x4_down_left(pixel *src, const pixel *topright, int stride)
 ;-----------------------------------------------------------------------------
-%macro PRED4x4_DL 1
-cglobal pred4x4_down_left_10_%1, 3,3
+%macro PRED4x4_DL 0
+cglobal pred4x4_down_left_10, 3, 3
     sub        r0, r2
     movq       m0, [r0]
     movhps     m0, [r1]
@@ -236,18 +232,18 @@
     RET
 %endmacro
 
-INIT_XMM
-PRED4x4_DL sse2
+INIT_XMM sse2
+PRED4x4_DL
 %if HAVE_AVX_EXTERNAL
-INIT_AVX
-PRED4x4_DL avx
+INIT_XMM avx
+PRED4x4_DL
 %endif
 
 ;-----------------------------------------------------------------------------
 ; void pred4x4_vertical_left(pixel *src, const pixel *topright, int stride)
 ;-----------------------------------------------------------------------------
-%macro PRED4x4_VL 1
-cglobal pred4x4_vertical_left_10_%1, 3,3
+%macro PRED4x4_VL 0
+cglobal pred4x4_vertical_left_10, 3, 3
     sub        r0, r2
     movu       m1, [r0]
     movhps     m1, [r1]
@@ -265,18 +261,18 @@
     RET
 %endmacro
 
-INIT_XMM
-PRED4x4_VL sse2
+INIT_XMM sse2
+PRED4x4_VL
 %if HAVE_AVX_EXTERNAL
-INIT_AVX
-PRED4x4_VL avx
+INIT_XMM avx
+PRED4x4_VL
 %endif
 
 ;-----------------------------------------------------------------------------
 ; void pred4x4_horizontal_up(pixel *src, const pixel *topright, int stride)
 ;-----------------------------------------------------------------------------
-INIT_MMX
-cglobal pred4x4_horizontal_up_10_mmxext, 3,3
+INIT_MMX mmxext
+cglobal pred4x4_horizontal_up_10, 3, 3
     sub       r0, r2
     lea       r1, [r0+r2*2]
     movq      m0, [r0+r2*1-8]
@@ -309,8 +305,8 @@
 ;-----------------------------------------------------------------------------
 ; void pred8x8_vertical(pixel *src, int stride)
 ;-----------------------------------------------------------------------------
-INIT_XMM
-cglobal pred8x8_vertical_10_sse2, 2,2
+INIT_XMM sse2
+cglobal pred8x8_vertical_10, 2, 2
     sub  r0, r1
     mova m0, [r0]
 %rep 3
@@ -325,8 +321,8 @@
 ;-----------------------------------------------------------------------------
 ; void pred8x8_horizontal(pixel *src, int stride)
 ;-----------------------------------------------------------------------------
-INIT_XMM
-cglobal pred8x8_horizontal_10_sse2, 2,3
+INIT_XMM sse2
+cglobal pred8x8_horizontal_10, 2, 3
     mov         r2d, 4
 .loop:
     movq         m0, [r0+r1*0-8]
@@ -355,8 +351,8 @@
 %endif
 %endmacro
 
-%macro PRED8x8_DC 2
-cglobal pred8x8_dc_10_%1, 2,6
+%macro PRED8x8_DC 1
+cglobal pred8x8_dc_10, 2, 6
     sub         r0, r1
     pxor        m4, m4
     movq        m0, [r0+0]
@@ -372,7 +368,7 @@
     paddw       m1, m3
     punpcklwd   m0, m1
 %endif
-    %2          m2, m0, 00001110b
+    %1          m2, m0, 00001110b
     paddw       m0, m2
 
     lea         r5, [r1*3]
@@ -397,8 +393,8 @@
 
     punpcklwd   m2, m3
     punpckldq   m0, m2            ; s0, s1, s2, s3
-    %2          m3, m0, 11110110b ; s2, s1, s3, s3
-    %2          m0, m0, 01110100b ; s0, s1, s3, s1
+    %1          m3, m0, 11110110b ; s2, s1, s3, s3
+    %1          m0, m0, 01110100b ; s0, s1, s3, s1
     paddw       m0, m3
     psrlw       m0, 2
     pavgw       m0, m4            ; s0+s2, s1, s3, s1+s3
@@ -424,16 +420,16 @@
     RET
 %endmacro
 
-INIT_MMX
-PRED8x8_DC mmxext, pshufw
-INIT_XMM
-PRED8x8_DC sse2  , pshuflw
+INIT_MMX mmxext
+PRED8x8_DC pshufw
+INIT_XMM sse2
+PRED8x8_DC pshuflw
 
 ;-----------------------------------------------------------------------------
 ; void pred8x8_top_dc(pixel *src, int stride)
 ;-----------------------------------------------------------------------------
-INIT_XMM
-cglobal pred8x8_top_dc_10_sse2, 2,4
+INIT_XMM sse2
+cglobal pred8x8_top_dc_10, 2, 4
     sub         r0, r1
     mova        m0, [r0]
     pshuflw     m1, m0, 0x4e
@@ -459,8 +455,8 @@
 ;-----------------------------------------------------------------------------
 ; void pred8x8_plane(pixel *src, int stride)
 ;-----------------------------------------------------------------------------
-INIT_XMM
-cglobal pred8x8_plane_10_sse2, 2,7,7
+INIT_XMM sse2
+cglobal pred8x8_plane_10, 2, 7, 7
     sub       r0, r1
     lea       r2, [r1*3]
     lea       r3, [r0+r1*4]
@@ -522,8 +518,8 @@
 ;-----------------------------------------------------------------------------
 ; void pred8x8l_128_dc(pixel *src, int has_topleft, int has_topright, int stride)
 ;-----------------------------------------------------------------------------
-%macro PRED8x8L_128_DC 1
-cglobal pred8x8l_128_dc_10_%1, 4,4
+%macro PRED8x8L_128_DC 0
+cglobal pred8x8l_128_dc_10, 4, 4
     mova      m0, [pw_512] ; (1<<(BIT_DEPTH-1))
     lea       r1, [r3*3]
     lea       r2, [r0+r3*4]
@@ -538,16 +534,16 @@
     RET
 %endmacro
 
-INIT_MMX
-PRED8x8L_128_DC mmxext
-INIT_XMM
-PRED8x8L_128_DC sse2
+INIT_MMX mmxext
+PRED8x8L_128_DC
+INIT_XMM sse2
+PRED8x8L_128_DC
 
 ;-----------------------------------------------------------------------------
 ; void pred8x8l_top_dc(pixel *src, int has_topleft, int has_topright, int stride)
 ;-----------------------------------------------------------------------------
-%macro PRED8x8L_TOP_DC 1
-cglobal pred8x8l_top_dc_10_%1, 4,4,6
+%macro PRED8x8L_TOP_DC 0
+cglobal pred8x8l_top_dc_10, 4, 4, 6
     sub         r0, r3
     mova        m0, [r0]
     shr        r1d, 14
@@ -575,19 +571,19 @@
     RET
 %endmacro
 
-INIT_XMM
-PRED8x8L_TOP_DC sse2
+INIT_XMM sse2
+PRED8x8L_TOP_DC
 %if HAVE_AVX_EXTERNAL
-INIT_AVX
-PRED8x8L_TOP_DC avx
+INIT_XMM avx
+PRED8x8L_TOP_DC
 %endif
 
 ;-----------------------------------------------------------------------------
 ;void pred8x8l_dc(pixel *src, int has_topleft, int has_topright, int stride)
 ;-----------------------------------------------------------------------------
 ;TODO: see if scalar is faster
-%macro PRED8x8L_DC 1
-cglobal pred8x8l_dc_10_%1, 4,6,6
+%macro PRED8x8L_DC 0
+cglobal pred8x8l_dc_10, 4, 6, 6
     sub         r0, r3
     lea         r4, [r0+r3*4]
     lea         r5, [r3*3]
@@ -634,18 +630,18 @@
     RET
 %endmacro
 
-INIT_XMM
-PRED8x8L_DC sse2
+INIT_XMM sse2
+PRED8x8L_DC
 %if HAVE_AVX_EXTERNAL
-INIT_AVX
-PRED8x8L_DC avx
+INIT_XMM avx
+PRED8x8L_DC
 %endif
 
 ;-----------------------------------------------------------------------------
 ; void pred8x8l_vertical(pixel *src, int has_topleft, int has_topright, int stride)
 ;-----------------------------------------------------------------------------
-%macro PRED8x8L_VERTICAL 1
-cglobal pred8x8l_vertical_10_%1, 4,4,6
+%macro PRED8x8L_VERTICAL 0
+cglobal pred8x8l_vertical_10, 4, 4, 6
     sub         r0, r3
     mova        m0, [r0]
     shr        r1d, 14
@@ -669,18 +665,18 @@
     RET
 %endmacro
 
-INIT_XMM
-PRED8x8L_VERTICAL sse2
+INIT_XMM sse2
+PRED8x8L_VERTICAL
 %if HAVE_AVX_EXTERNAL
-INIT_AVX
-PRED8x8L_VERTICAL avx
+INIT_XMM avx
+PRED8x8L_VERTICAL
 %endif
 
 ;-----------------------------------------------------------------------------
 ; void pred8x8l_horizontal(uint8_t *src, int has_topleft, int has_topright, int stride)
 ;-----------------------------------------------------------------------------
-%macro PRED8x8L_HORIZONTAL 1
-cglobal pred8x8l_horizontal_10_%1, 4,4,5
+%macro PRED8x8L_HORIZONTAL 0
+cglobal pred8x8l_horizontal_10, 4, 4, 5
     mova        m0, [r0-16]
     shr        r1d, 14
     dec         r1
@@ -723,21 +719,20 @@
     RET
 %endmacro
 
-INIT_XMM
-%define PALIGNR PALIGNR_MMX
-PRED8x8L_HORIZONTAL sse2
-%define PALIGNR PALIGNR_SSSE3
-PRED8x8L_HORIZONTAL ssse3
+INIT_XMM sse2
+PRED8x8L_HORIZONTAL
+INIT_XMM ssse3
+PRED8x8L_HORIZONTAL
 %if HAVE_AVX_EXTERNAL
-INIT_AVX
-PRED8x8L_HORIZONTAL avx
+INIT_XMM avx
+PRED8x8L_HORIZONTAL
 %endif
 
 ;-----------------------------------------------------------------------------
 ;void pred8x8l_down_left(pixel *src, int has_topleft, int has_topright, int stride)
 ;-----------------------------------------------------------------------------
-%macro PRED8x8L_DOWN_LEFT 1
-cglobal pred8x8l_down_left_10_%1, 4,4,7
+%macro PRED8x8L_DOWN_LEFT 0
+cglobal pred8x8l_down_left_10, 4, 4, 7
     sub         r0, r3
     mova        m3, [r0]
     shr        r1d, 14
@@ -792,23 +787,22 @@
     jmp .do_topright
 %endmacro
 
-INIT_XMM
-%define PALIGNR PALIGNR_MMX
-PRED8x8L_DOWN_LEFT sse2
-%define PALIGNR PALIGNR_SSSE3
-PRED8x8L_DOWN_LEFT ssse3
+INIT_XMM sse2
+PRED8x8L_DOWN_LEFT
+INIT_XMM ssse3
+PRED8x8L_DOWN_LEFT
 %if HAVE_AVX_EXTERNAL
-INIT_AVX
-PRED8x8L_DOWN_LEFT avx
+INIT_XMM avx
+PRED8x8L_DOWN_LEFT
 %endif
 
 ;-----------------------------------------------------------------------------
 ;void pred8x8l_down_right(pixel *src, int has_topleft, int has_topright, int stride)
 ;-----------------------------------------------------------------------------
-%macro PRED8x8L_DOWN_RIGHT 1
+%macro PRED8x8L_DOWN_RIGHT 0
 ; standard forbids this when has_topleft is false
 ; no need to check
-cglobal pred8x8l_down_right_10_%1, 4,5,8
+cglobal pred8x8l_down_right_10, 4, 5, 8
     sub         r0, r3
     lea         r4, [r0+r3*4]
     lea         r1, [r3*3]
@@ -867,22 +861,21 @@
     RET
 %endmacro
 
-INIT_XMM
-%define PALIGNR PALIGNR_MMX
-PRED8x8L_DOWN_RIGHT sse2
-%define PALIGNR PALIGNR_SSSE3
-PRED8x8L_DOWN_RIGHT ssse3
+INIT_XMM sse2
+PRED8x8L_DOWN_RIGHT
+INIT_XMM ssse3
+PRED8x8L_DOWN_RIGHT
 %if HAVE_AVX_EXTERNAL
-INIT_AVX
-PRED8x8L_DOWN_RIGHT avx
+INIT_XMM avx
+PRED8x8L_DOWN_RIGHT
 %endif
 
 ;-----------------------------------------------------------------------------
 ; void pred8x8l_vertical_right(pixel *src, int has_topleft, int has_topright, int stride)
 ;-----------------------------------------------------------------------------
-%macro PRED8x8L_VERTICAL_RIGHT 1
+%macro PRED8x8L_VERTICAL_RIGHT 0
 ; likewise with 8x8l_down_right
-cglobal pred8x8l_vertical_right_10_%1, 4,5,7
+cglobal pred8x8l_vertical_right_10, 4, 5, 7
     sub         r0, r3
     lea         r4, [r0+r3*4]
     lea         r1, [r3*3]
@@ -938,21 +931,20 @@
     RET
 %endmacro
 
-INIT_XMM
-%define PALIGNR PALIGNR_MMX
-PRED8x8L_VERTICAL_RIGHT sse2
-%define PALIGNR PALIGNR_SSSE3
-PRED8x8L_VERTICAL_RIGHT ssse3
+INIT_XMM sse2
+PRED8x8L_VERTICAL_RIGHT
+INIT_XMM ssse3
+PRED8x8L_VERTICAL_RIGHT
 %if HAVE_AVX_EXTERNAL
-INIT_AVX
-PRED8x8L_VERTICAL_RIGHT avx
+INIT_XMM avx
+PRED8x8L_VERTICAL_RIGHT
 %endif
 
 ;-----------------------------------------------------------------------------
 ; void pred8x8l_horizontal_up(pixel *src, int has_topleft, int has_topright, int stride)
 ;-----------------------------------------------------------------------------
-%macro PRED8x8L_HORIZONTAL_UP 1
-cglobal pred8x8l_horizontal_up_10_%1, 4,4,6
+%macro PRED8x8L_HORIZONTAL_UP 0
+cglobal pred8x8l_horizontal_up_10, 4, 4, 6
     mova        m0, [r0+r3*0-16]
     punpckhwd   m0, [r0+r3*1-16]
     shr        r1d, 14
@@ -1000,14 +992,13 @@
     RET
 %endmacro
 
-INIT_XMM
-%define PALIGNR PALIGNR_MMX
-PRED8x8L_HORIZONTAL_UP sse2
-%define PALIGNR PALIGNR_SSSE3
-PRED8x8L_HORIZONTAL_UP ssse3
+INIT_XMM sse2
+PRED8x8L_HORIZONTAL_UP
+INIT_XMM ssse3
+PRED8x8L_HORIZONTAL_UP
 %if HAVE_AVX_EXTERNAL
-INIT_AVX
-PRED8x8L_HORIZONTAL_UP avx
+INIT_XMM avx
+PRED8x8L_HORIZONTAL_UP
 %endif
 
 
@@ -1023,8 +1014,8 @@
 %endif
 %endmacro
 
-%macro PRED16x16_VERTICAL 1
-cglobal pred16x16_vertical_10_%1, 2,3
+%macro PRED16x16_VERTICAL 0
+cglobal pred16x16_vertical_10, 2, 3
     sub   r0, r1
     mov  r2d, 8
     mova  m0, [r0+ 0]
@@ -1042,16 +1033,16 @@
     REP_RET
 %endmacro
 
-INIT_MMX
-PRED16x16_VERTICAL mmxext
-INIT_XMM
-PRED16x16_VERTICAL sse2
+INIT_MMX mmxext
+PRED16x16_VERTICAL
+INIT_XMM sse2
+PRED16x16_VERTICAL
 
 ;-----------------------------------------------------------------------------
 ; void pred16x16_horizontal(pixel *src, int stride)
 ;-----------------------------------------------------------------------------
-%macro PRED16x16_HORIZONTAL 1
-cglobal pred16x16_horizontal_10_%1, 2,3
+%macro PRED16x16_HORIZONTAL 0
+cglobal pred16x16_horizontal_10, 2, 3
     mov   r2d, 8
 .vloop:
     movd   m0, [r0+r1*0-4]
@@ -1066,16 +1057,16 @@
     REP_RET
 %endmacro
 
-INIT_MMX
-PRED16x16_HORIZONTAL mmxext
-INIT_XMM
-PRED16x16_HORIZONTAL sse2
+INIT_MMX mmxext
+PRED16x16_HORIZONTAL
+INIT_XMM sse2
+PRED16x16_HORIZONTAL
 
 ;-----------------------------------------------------------------------------
 ; void pred16x16_dc(pixel *src, int stride)
 ;-----------------------------------------------------------------------------
-%macro PRED16x16_DC 1
-cglobal pred16x16_dc_10_%1, 2,6
+%macro PRED16x16_DC 0
+cglobal pred16x16_dc_10, 2, 6
     mov        r5, r0
     sub        r0, r1
     mova       m0, [r0+0]
@@ -1112,16 +1103,16 @@
     REP_RET
 %endmacro
 
-INIT_MMX
-PRED16x16_DC mmxext
-INIT_XMM
-PRED16x16_DC sse2
+INIT_MMX mmxext
+PRED16x16_DC
+INIT_XMM sse2
+PRED16x16_DC
 
 ;-----------------------------------------------------------------------------
 ; void pred16x16_top_dc(pixel *src, int stride)
 ;-----------------------------------------------------------------------------
-%macro PRED16x16_TOP_DC 1
-cglobal pred16x16_top_dc_10_%1, 2,3
+%macro PRED16x16_TOP_DC 0
+cglobal pred16x16_top_dc_10, 2, 3
     sub        r0, r1
     mova       m0, [r0+0]
     paddw      m0, [r0+mmsize]
@@ -1144,16 +1135,16 @@
     REP_RET
 %endmacro
 
-INIT_MMX
-PRED16x16_TOP_DC mmxext
-INIT_XMM
-PRED16x16_TOP_DC sse2
+INIT_MMX mmxext
+PRED16x16_TOP_DC
+INIT_XMM sse2
+PRED16x16_TOP_DC
 
 ;-----------------------------------------------------------------------------
 ; void pred16x16_left_dc(pixel *src, int stride)
 ;-----------------------------------------------------------------------------
-%macro PRED16x16_LEFT_DC 1
-cglobal pred16x16_left_dc_10_%1, 2,6
+%macro PRED16x16_LEFT_DC 0
+cglobal pred16x16_left_dc_10, 2, 6
     mov        r5, r0
 
     sub        r0, 2
@@ -1181,16 +1172,16 @@
     REP_RET
 %endmacro
 
-INIT_MMX
-PRED16x16_LEFT_DC mmxext
-INIT_XMM
-PRED16x16_LEFT_DC sse2
+INIT_MMX mmxext
+PRED16x16_LEFT_DC
+INIT_XMM sse2
+PRED16x16_LEFT_DC
 
 ;-----------------------------------------------------------------------------
 ; void pred16x16_128_dc(pixel *src, int stride)
 ;-----------------------------------------------------------------------------
-%macro PRED16x16_128_DC 1
-cglobal pred16x16_128_dc_10_%1, 2,3
+%macro PRED16x16_128_DC 0
+cglobal pred16x16_128_dc_10, 2,3
     mova       m0, [pw_512]
     mov       r2d, 8
 .loop:
@@ -1202,7 +1193,7 @@
     REP_RET
 %endmacro
 
-INIT_MMX
-PRED16x16_128_DC mmxext
-INIT_XMM
-PRED16x16_128_DC sse2
+INIT_MMX mmxext
+PRED16x16_128_DC
+INIT_XMM sse2
+PRED16x16_128_DC
diff --git a/libavcodec/x86/h264_intrapred_init.c b/libavcodec/x86/h264_intrapred_init.c
index 6d8b414..deededa 100644
--- a/libavcodec/x86/h264_intrapred_init.c
+++ b/libavcodec/x86/h264_intrapred_init.c
@@ -23,7 +23,9 @@
 #include "libavcodec/h264pred.h"
 
 #define PRED4x4(TYPE, DEPTH, OPT) \
-void ff_pred4x4_ ## TYPE ## _ ## DEPTH ## _ ## OPT (uint8_t *src, const uint8_t *topright, int stride);
+void ff_pred4x4_ ## TYPE ## _ ## DEPTH ## _ ## OPT (uint8_t *src, \
+                                                    const uint8_t *topright, \
+                                                    ptrdiff_t stride);
 
 PRED4x4(dc, 10, mmxext)
 PRED4x4(down_left, 10, sse2)
@@ -42,7 +44,8 @@
 PRED4x4(horizontal_down, 10, avx)
 
 #define PRED8x8(TYPE, DEPTH, OPT) \
-void ff_pred8x8_ ## TYPE ## _ ## DEPTH ## _ ## OPT (uint8_t *src, int stride);
+void ff_pred8x8_ ## TYPE ## _ ## DEPTH ## _ ## OPT (uint8_t *src, \
+                                                    ptrdiff_t stride);
 
 PRED8x8(dc, 10, mmxext)
 PRED8x8(dc, 10, sse2)
@@ -52,7 +55,10 @@
 PRED8x8(horizontal, 10, sse2)
 
 #define PRED8x8L(TYPE, DEPTH, OPT)\
-void ff_pred8x8l_ ## TYPE ## _ ## DEPTH ## _ ## OPT (uint8_t *src, int has_topleft, int has_topright, int stride);
+void ff_pred8x8l_ ## TYPE ## _ ## DEPTH ## _ ## OPT (uint8_t *src, \
+                                                     int has_topleft, \
+                                                     int has_topright, \
+                                                     ptrdiff_t stride);
 
 PRED8x8L(dc, 10, sse2)
 PRED8x8L(dc, 10, avx)
@@ -79,7 +85,8 @@
 PRED8x8L(horizontal_up, 10, avx)
 
 #define PRED16x16(TYPE, DEPTH, OPT)\
-void ff_pred16x16_ ## TYPE ## _ ## DEPTH ## _ ## OPT (uint8_t *src, int stride);
+void ff_pred16x16_ ## TYPE ## _ ## DEPTH ## _ ## OPT (uint8_t *src, \
+                                                      ptrdiff_t stride);
 
 PRED16x16(dc, 10, mmxext)
 PRED16x16(dc, 10, sse2)
@@ -94,79 +101,83 @@
 PRED16x16(horizontal, 10, mmxext)
 PRED16x16(horizontal, 10, sse2)
 
-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_mmx2  (uint8_t *src, int stride);
-void ff_pred16x16_horizontal_ssse3 (uint8_t *src, int stride);
-void ff_pred16x16_dc_mmx2          (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_mmx2      (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_mmx2    (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_mmx2        (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_mmx2        (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);
+/* 8-bit versions */
+PRED16x16(vertical, 8, mmx)
+PRED16x16(vertical, 8, sse)
+PRED16x16(horizontal, 8, mmx)
+PRED16x16(horizontal, 8, mmxext)
+PRED16x16(horizontal, 8, ssse3)
+PRED16x16(dc, 8, mmxext)
+PRED16x16(dc, 8, sse2)
+PRED16x16(dc, 8, ssse3)
+PRED16x16(plane_h264, 8, mmx)
+PRED16x16(plane_h264, 8, mmxext)
+PRED16x16(plane_h264, 8, sse2)
+PRED16x16(plane_h264, 8, ssse3)
+PRED16x16(plane_rv40, 8, mmx)
+PRED16x16(plane_rv40, 8, mmxext)
+PRED16x16(plane_rv40, 8, sse2)
+PRED16x16(plane_rv40, 8, ssse3)
+PRED16x16(plane_svq3, 8, mmx)
+PRED16x16(plane_svq3, 8, mmxext)
+PRED16x16(plane_svq3, 8, sse2)
+PRED16x16(plane_svq3, 8, ssse3)
+PRED16x16(tm_vp8, 8, mmx)
+PRED16x16(tm_vp8, 8, mmxext)
+PRED16x16(tm_vp8, 8, sse2)
+
+PRED8x8(top_dc, 8, mmxext)
+PRED8x8(dc_rv40, 8, mmxext)
+PRED8x8(dc, 8, mmxext)
+PRED8x8(vertical, 8, mmx)
+PRED8x8(horizontal, 8, mmx)
+PRED8x8(horizontal, 8, mmxext)
+PRED8x8(horizontal, 8, ssse3)
+PRED8x8(plane, 8, mmx)
+PRED8x8(plane, 8, mmxext)
+PRED8x8(plane, 8, sse2)
+PRED8x8(plane, 8, ssse3)
+PRED8x8(tm_vp8, 8, mmx)
+PRED8x8(tm_vp8, 8, mmxext)
+PRED8x8(tm_vp8, 8, sse2)
+PRED8x8(tm_vp8, 8, ssse3)
+
+PRED8x8L(top_dc, 8, mmxext)
+PRED8x8L(top_dc, 8, ssse3)
+PRED8x8L(dc, 8, mmxext)
+PRED8x8L(dc, 8, ssse3)
+PRED8x8L(horizontal, 8, mmxext)
+PRED8x8L(horizontal, 8, ssse3)
+PRED8x8L(vertical, 8, mmxext)
+PRED8x8L(vertical, 8, ssse3)
+PRED8x8L(down_left, 8, mmxext)
+PRED8x8L(down_left, 8, sse2)
+PRED8x8L(down_left, 8, ssse3)
+PRED8x8L(down_right, 8, mmxext)
+PRED8x8L(down_right, 8, sse2)
+PRED8x8L(down_right, 8, ssse3)
+PRED8x8L(vertical_right, 8, mmxext)
+PRED8x8L(vertical_right, 8, sse2)
+PRED8x8L(vertical_right, 8, ssse3)
+PRED8x8L(vertical_left, 8, sse2)
+PRED8x8L(vertical_left, 8, ssse3)
+PRED8x8L(horizontal_up, 8, mmxext)
+PRED8x8L(horizontal_up, 8, ssse3)
+PRED8x8L(horizontal_down, 8, mmxext)
+PRED8x8L(horizontal_down, 8, sse2)
+PRED8x8L(horizontal_down, 8, ssse3)
+
+PRED4x4(dc, 8, mmxext)
+PRED4x4(down_left, 8, mmxext)
+PRED4x4(down_right, 8, mmxext)
+PRED4x4(vertical_left, 8, mmxext)
+PRED4x4(vertical_right, 8, mmxext)
+PRED4x4(horizontal_up, 8, mmxext)
+PRED4x4(horizontal_down, 8, mmxext)
+PRED4x4(tm_vp8, 8, mmx)
+PRED4x4(tm_vp8, 8, mmxext)
+PRED4x4(tm_vp8, 8, ssse3)
+PRED4x4(vertical_vp8, 8, mmxext)
 
 void ff_h264_pred_init_x86(H264PredContext *h, int codec_id, const int bit_depth, const int chroma_format_idc)
 {
@@ -174,136 +185,136 @@
 
     if (bit_depth == 8) {
         if (EXTERNAL_MMX(mm_flags)) {
-            h->pred16x16[VERT_PRED8x8         ] = ff_pred16x16_vertical_mmx;
-            h->pred16x16[HOR_PRED8x8          ] = ff_pred16x16_horizontal_mmx;
+            h->pred16x16[VERT_PRED8x8         ] = ff_pred16x16_vertical_8_mmx;
+            h->pred16x16[HOR_PRED8x8          ] = ff_pred16x16_horizontal_8_mmx;
             if (chroma_format_idc == 1) {
-                h->pred8x8  [VERT_PRED8x8     ] = ff_pred8x8_vertical_mmx;
-                h->pred8x8  [HOR_PRED8x8      ] = ff_pred8x8_horizontal_mmx;
+                h->pred8x8  [VERT_PRED8x8     ] = ff_pred8x8_vertical_8_mmx;
+                h->pred8x8  [HOR_PRED8x8      ] = ff_pred8x8_horizontal_8_mmx;
             }
             if (codec_id == AV_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;
+                h->pred16x16[PLANE_PRED8x8    ] = ff_pred16x16_tm_vp8_8_mmx;
+                h->pred8x8  [PLANE_PRED8x8    ] = ff_pred8x8_tm_vp8_8_mmx;
+                h->pred4x4  [TM_VP8_PRED      ] = ff_pred4x4_tm_vp8_8_mmx;
             } else {
                 if (chroma_format_idc == 1)
-                    h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_plane_mmx;
+                    h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_plane_8_mmx;
                 if (codec_id == AV_CODEC_ID_SVQ3) {
                     if (mm_flags & AV_CPU_FLAG_CMOV)
-                        h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_svq3_mmx;
+                        h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_svq3_8_mmx;
                 } else if (codec_id == AV_CODEC_ID_RV40) {
-                    h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_rv40_mmx;
+                    h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_rv40_8_mmx;
                 } else {
-                    h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_h264_mmx;
+                    h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_h264_8_mmx;
                 }
             }
         }
 
         if (EXTERNAL_MMXEXT(mm_flags)) {
-            h->pred16x16[HOR_PRED8x8            ] = ff_pred16x16_horizontal_mmx2;
-            h->pred16x16[DC_PRED8x8             ] = ff_pred16x16_dc_mmx2;
+            h->pred16x16[HOR_PRED8x8            ] = ff_pred16x16_horizontal_8_mmxext;
+            h->pred16x16[DC_PRED8x8             ] = ff_pred16x16_dc_8_mmxext;
             if (chroma_format_idc == 1)
-                h->pred8x8[HOR_PRED8x8          ] = ff_pred8x8_horizontal_mmx2;
-            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;
-            h->pred4x4  [DC_PRED                ] = ff_pred4x4_dc_mmxext;
+                h->pred8x8[HOR_PRED8x8          ] = ff_pred8x8_horizontal_8_mmxext;
+            h->pred8x8l [TOP_DC_PRED            ] = ff_pred8x8l_top_dc_8_mmxext;
+            h->pred8x8l [DC_PRED                ] = ff_pred8x8l_dc_8_mmxext;
+            h->pred8x8l [HOR_PRED               ] = ff_pred8x8l_horizontal_8_mmxext;
+            h->pred8x8l [VERT_PRED              ] = ff_pred8x8l_vertical_8_mmxext;
+            h->pred8x8l [DIAG_DOWN_RIGHT_PRED   ] = ff_pred8x8l_down_right_8_mmxext;
+            h->pred8x8l [VERT_RIGHT_PRED        ] = ff_pred8x8l_vertical_right_8_mmxext;
+            h->pred8x8l [HOR_UP_PRED            ] = ff_pred8x8l_horizontal_up_8_mmxext;
+            h->pred8x8l [DIAG_DOWN_LEFT_PRED    ] = ff_pred8x8l_down_left_8_mmxext;
+            h->pred8x8l [HOR_DOWN_PRED          ] = ff_pred8x8l_horizontal_down_8_mmxext;
+            h->pred4x4  [DIAG_DOWN_RIGHT_PRED   ] = ff_pred4x4_down_right_8_mmxext;
+            h->pred4x4  [VERT_RIGHT_PRED        ] = ff_pred4x4_vertical_right_8_mmxext;
+            h->pred4x4  [HOR_DOWN_PRED          ] = ff_pred4x4_horizontal_down_8_mmxext;
+            h->pred4x4  [DC_PRED                ] = ff_pred4x4_dc_8_mmxext;
             if (codec_id == AV_CODEC_ID_VP8 || codec_id == AV_CODEC_ID_H264) {
-                h->pred4x4  [DIAG_DOWN_LEFT_PRED] = ff_pred4x4_down_left_mmxext;
+                h->pred4x4  [DIAG_DOWN_LEFT_PRED] = ff_pred4x4_down_left_8_mmxext;
             }
             if (codec_id == AV_CODEC_ID_SVQ3 || codec_id == AV_CODEC_ID_H264) {
-                h->pred4x4  [VERT_LEFT_PRED     ] = ff_pred4x4_vertical_left_mmxext;
+                h->pred4x4  [VERT_LEFT_PRED     ] = ff_pred4x4_vertical_left_8_mmxext;
             }
             if (codec_id != AV_CODEC_ID_RV40) {
-                h->pred4x4  [HOR_UP_PRED        ] = ff_pred4x4_horizontal_up_mmxext;
+                h->pred4x4  [HOR_UP_PRED        ] = ff_pred4x4_horizontal_up_8_mmxext;
             }
             if (codec_id == AV_CODEC_ID_SVQ3 || codec_id == AV_CODEC_ID_H264) {
                 if (chroma_format_idc == 1) {
-                    h->pred8x8[TOP_DC_PRED8x8   ] = ff_pred8x8_top_dc_mmxext;
-                    h->pred8x8[DC_PRED8x8       ] = ff_pred8x8_dc_mmxext;
+                    h->pred8x8[TOP_DC_PRED8x8   ] = ff_pred8x8_top_dc_8_mmxext;
+                    h->pred8x8[DC_PRED8x8       ] = ff_pred8x8_dc_8_mmxext;
                 }
             }
             if (codec_id == AV_CODEC_ID_VP8) {
-                h->pred16x16[PLANE_PRED8x8      ] = ff_pred16x16_tm_vp8_mmx2;
-                h->pred8x8  [DC_PRED8x8         ] = ff_pred8x8_dc_rv40_mmxext;
-                h->pred8x8  [PLANE_PRED8x8      ] = ff_pred8x8_tm_vp8_mmx2;
-                h->pred4x4  [TM_VP8_PRED        ] = ff_pred4x4_tm_vp8_mmx2;
-                h->pred4x4  [VERT_PRED          ] = ff_pred4x4_vertical_vp8_mmxext;
+                h->pred16x16[PLANE_PRED8x8      ] = ff_pred16x16_tm_vp8_8_mmxext;
+                h->pred8x8  [DC_PRED8x8         ] = ff_pred8x8_dc_rv40_8_mmxext;
+                h->pred8x8  [PLANE_PRED8x8      ] = ff_pred8x8_tm_vp8_8_mmxext;
+                h->pred4x4  [TM_VP8_PRED        ] = ff_pred4x4_tm_vp8_8_mmxext;
+                h->pred4x4  [VERT_PRED          ] = ff_pred4x4_vertical_vp8_8_mmxext;
             } else {
                 if (chroma_format_idc == 1)
-                    h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_plane_mmx2;
+                    h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_plane_8_mmxext;
                 if (codec_id == AV_CODEC_ID_SVQ3) {
-                    h->pred16x16[PLANE_PRED8x8  ] = ff_pred16x16_plane_svq3_mmx2;
+                    h->pred16x16[PLANE_PRED8x8  ] = ff_pred16x16_plane_svq3_8_mmxext;
                 } else if (codec_id == AV_CODEC_ID_RV40) {
-                    h->pred16x16[PLANE_PRED8x8  ] = ff_pred16x16_plane_rv40_mmx2;
+                    h->pred16x16[PLANE_PRED8x8  ] = ff_pred16x16_plane_rv40_8_mmxext;
                 } else {
-                    h->pred16x16[PLANE_PRED8x8  ] = ff_pred16x16_plane_h264_mmx2;
+                    h->pred16x16[PLANE_PRED8x8  ] = ff_pred16x16_plane_h264_8_mmxext;
                 }
             }
         }
 
         if (EXTERNAL_SSE(mm_flags)) {
-            h->pred16x16[VERT_PRED8x8] = ff_pred16x16_vertical_sse;
+            h->pred16x16[VERT_PRED8x8] = ff_pred16x16_vertical_8_sse;
         }
 
         if (EXTERNAL_SSE2(mm_flags)) {
-            h->pred16x16[DC_PRED8x8           ] = ff_pred16x16_dc_sse2;
-            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;
+            h->pred16x16[DC_PRED8x8           ] = ff_pred16x16_dc_8_sse2;
+            h->pred8x8l [DIAG_DOWN_LEFT_PRED  ] = ff_pred8x8l_down_left_8_sse2;
+            h->pred8x8l [DIAG_DOWN_RIGHT_PRED ] = ff_pred8x8l_down_right_8_sse2;
+            h->pred8x8l [VERT_RIGHT_PRED      ] = ff_pred8x8l_vertical_right_8_sse2;
+            h->pred8x8l [VERT_LEFT_PRED       ] = ff_pred8x8l_vertical_left_8_sse2;
+            h->pred8x8l [HOR_DOWN_PRED        ] = ff_pred8x8l_horizontal_down_8_sse2;
             if (codec_id == AV_CODEC_ID_VP8) {
-                h->pred16x16[PLANE_PRED8x8    ] = ff_pred16x16_tm_vp8_sse2;
-                h->pred8x8  [PLANE_PRED8x8    ] = ff_pred8x8_tm_vp8_sse2;
+                h->pred16x16[PLANE_PRED8x8    ] = ff_pred16x16_tm_vp8_8_sse2;
+                h->pred8x8  [PLANE_PRED8x8    ] = ff_pred8x8_tm_vp8_8_sse2;
             } else {
                 if (chroma_format_idc == 1)
-                    h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_plane_sse2;
+                    h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_plane_8_sse2;
                 if (codec_id == AV_CODEC_ID_SVQ3) {
-                    h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_svq3_sse2;
+                    h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_svq3_8_sse2;
                 } else if (codec_id == AV_CODEC_ID_RV40) {
-                    h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_rv40_sse2;
+                    h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_rv40_8_sse2;
                 } else {
-                    h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_h264_sse2;
+                    h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_h264_8_sse2;
                 }
             }
         }
 
         if (EXTERNAL_SSSE3(mm_flags)) {
-            h->pred16x16[HOR_PRED8x8          ] = ff_pred16x16_horizontal_ssse3;
-            h->pred16x16[DC_PRED8x8           ] = ff_pred16x16_dc_ssse3;
+            h->pred16x16[HOR_PRED8x8          ] = ff_pred16x16_horizontal_8_ssse3;
+            h->pred16x16[DC_PRED8x8           ] = ff_pred16x16_dc_8_ssse3;
             if (chroma_format_idc == 1)
-                h->pred8x8  [HOR_PRED8x8      ] = ff_pred8x8_horizontal_ssse3;
-            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;
+                h->pred8x8  [HOR_PRED8x8      ] = ff_pred8x8_horizontal_8_ssse3;
+            h->pred8x8l [TOP_DC_PRED          ] = ff_pred8x8l_top_dc_8_ssse3;
+            h->pred8x8l [DC_PRED              ] = ff_pred8x8l_dc_8_ssse3;
+            h->pred8x8l [HOR_PRED             ] = ff_pred8x8l_horizontal_8_ssse3;
+            h->pred8x8l [VERT_PRED            ] = ff_pred8x8l_vertical_8_ssse3;
+            h->pred8x8l [DIAG_DOWN_LEFT_PRED  ] = ff_pred8x8l_down_left_8_ssse3;
+            h->pred8x8l [DIAG_DOWN_RIGHT_PRED ] = ff_pred8x8l_down_right_8_ssse3;
+            h->pred8x8l [VERT_RIGHT_PRED      ] = ff_pred8x8l_vertical_right_8_ssse3;
+            h->pred8x8l [VERT_LEFT_PRED       ] = ff_pred8x8l_vertical_left_8_ssse3;
+            h->pred8x8l [HOR_UP_PRED          ] = ff_pred8x8l_horizontal_up_8_ssse3;
+            h->pred8x8l [HOR_DOWN_PRED        ] = ff_pred8x8l_horizontal_down_8_ssse3;
             if (codec_id == AV_CODEC_ID_VP8) {
-                h->pred8x8  [PLANE_PRED8x8    ] = ff_pred8x8_tm_vp8_ssse3;
-                h->pred4x4  [TM_VP8_PRED      ] = ff_pred4x4_tm_vp8_ssse3;
+                h->pred8x8  [PLANE_PRED8x8    ] = ff_pred8x8_tm_vp8_8_ssse3;
+                h->pred4x4  [TM_VP8_PRED      ] = ff_pred4x4_tm_vp8_8_ssse3;
             } else {
                 if (chroma_format_idc == 1)
-                    h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_plane_ssse3;
+                    h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_plane_8_ssse3;
                 if (codec_id == AV_CODEC_ID_SVQ3) {
-                    h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_svq3_ssse3;
+                    h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_svq3_8_ssse3;
                 } else if (codec_id == AV_CODEC_ID_RV40) {
-                    h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_rv40_ssse3;
+                    h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_rv40_8_ssse3;
                 } else {
-                    h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_h264_ssse3;
+                    h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_plane_h264_8_ssse3;
                 }
             }
         }
diff --git a/libavcodec/x86/h264_qpel.c b/libavcodec/x86/h264_qpel.c
index faf8a76..171ef2a 100644
--- a/libavcodec/x86/h264_qpel.c
+++ b/libavcodec/x86/h264_qpel.c
@@ -19,1019 +19,229 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/cpu.h"
+#include "libavutil/x86/asm.h"
+#include "libavcodec/dsputil.h"
+#include "libavcodec/mpegvideo.h"
 #include "dsputil_mmx.h"
 
-#if HAVE_INLINE_ASM
+#if HAVE_YASM
+void ff_put_pixels4_mmxext(uint8_t *block, const uint8_t *pixels, int line_size, int h);
+void ff_avg_pixels4_mmxext(uint8_t *block, const uint8_t *pixels, int line_size, int h);
+void ff_put_pixels8_mmxext(uint8_t *block, const uint8_t *pixels, int line_size, int h);
+void ff_avg_pixels8_mmxext(uint8_t *block, const uint8_t *pixels, int line_size, int h);
+static void ff_put_pixels16_mmxext(uint8_t *block, const uint8_t *pixels,
+                                   int line_size, int h)
+{
+    ff_put_pixels8_mmxext(block,     pixels,     line_size, h);
+    ff_put_pixels8_mmxext(block + 8, pixels + 8, line_size, h);
+}
+static void ff_avg_pixels16_mmxext(uint8_t *block, const uint8_t *pixels,
+                                   int line_size, int h)
+{
+    ff_avg_pixels8_mmxext(block,     pixels,     line_size, h);
+    ff_avg_pixels8_mmxext(block + 8, pixels + 8, line_size, h);
+}
+void ff_put_pixels4_l2_mmxext(uint8_t *dst, uint8_t *src1, uint8_t *src2,
+                              int dstStride, int src1Stride, int h);
+void ff_avg_pixels4_l2_mmxext(uint8_t *dst, uint8_t *src1, uint8_t *src2,
+                              int dstStride, int src1Stride, int h);
+void ff_put_pixels8_l2_mmxext(uint8_t *dst, uint8_t *src1, uint8_t *src2,
+                              int dstStride, int src1Stride, int h);
+void ff_avg_pixels8_l2_mmxext(uint8_t *dst, uint8_t *src1, uint8_t *src2,
+                              int dstStride, int src1Stride, int h);
+void ff_put_pixels16_l2_mmxext(uint8_t *dst, uint8_t *src1, uint8_t *src2,
+                               int dstStride, int src1Stride, int h);
+void ff_avg_pixels16_l2_mmxext(uint8_t *dst, uint8_t *src1, uint8_t *src2,
+                               int dstStride, int src1Stride, int h);
+void ff_put_pixels16_sse2(uint8_t *block, const uint8_t *pixels,
+                          int line_size, int h);
+void ff_avg_pixels16_sse2(uint8_t *block, const uint8_t *pixels,
+                          int line_size, int h);
+#define ff_put_pixels8_l2_sse2  ff_put_pixels8_l2_mmxext
+#define ff_avg_pixels8_l2_sse2  ff_avg_pixels8_l2_mmxext
+#define ff_put_pixels16_l2_sse2 ff_put_pixels16_l2_mmxext
+#define ff_avg_pixels16_l2_sse2 ff_avg_pixels16_l2_mmxext
 
-/***********************************/
-/* motion compensation */
+#define DEF_QPEL(OPNAME)\
+void ff_ ## OPNAME ## _h264_qpel4_h_lowpass_mmxext(uint8_t *dst, uint8_t *src, int dstStride, int srcStride);\
+void ff_ ## OPNAME ## _h264_qpel8_h_lowpass_mmxext(uint8_t *dst, uint8_t *src, int dstStride, int srcStride);\
+void ff_ ## OPNAME ## _h264_qpel8_h_lowpass_ssse3(uint8_t *dst, uint8_t *src, int dstStride, int srcStride);\
+void ff_ ## OPNAME ## _h264_qpel4_h_lowpass_l2_mmxext(uint8_t *dst, uint8_t *src, uint8_t *src2, int dstStride, int src2Stride);\
+void ff_ ## OPNAME ## _h264_qpel8_h_lowpass_l2_mmxext(uint8_t *dst, uint8_t *src, uint8_t *src2, int dstStride, int src2Stride);\
+void ff_ ## OPNAME ## _h264_qpel8_h_lowpass_l2_ssse3(uint8_t *dst, uint8_t *src, uint8_t *src2, int dstStride, int src2Stride);\
+void ff_ ## OPNAME ## _h264_qpel4_v_lowpass_mmxext(uint8_t *dst, uint8_t *src, int dstStride, int srcStride);\
+void ff_ ## OPNAME ## _h264_qpel8or16_v_lowpass_op_mmxext(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h);\
+void ff_ ## OPNAME ## _h264_qpel8or16_v_lowpass_sse2(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h);\
+void ff_ ## OPNAME ## _h264_qpel4_hv_lowpass_v_mmxext(uint8_t *src, int16_t *tmp, int srcStride);\
+void ff_ ## OPNAME ## _h264_qpel4_hv_lowpass_h_mmxext(int16_t *tmp, uint8_t *dst, int dstStride);\
+void ff_ ## OPNAME ## _h264_qpel8or16_hv1_lowpass_op_mmxext(uint8_t *src, int16_t *tmp, int srcStride, int size);\
+void ff_ ## OPNAME ## _h264_qpel8or16_hv1_lowpass_op_sse2(uint8_t *src, int16_t *tmp, int srcStride, int size);\
+void ff_ ## OPNAME ## _h264_qpel8or16_hv2_lowpass_op_mmxext(uint8_t *dst, int16_t *tmp, int dstStride, int unused, int h);\
+void ff_ ## OPNAME ## _h264_qpel8or16_hv2_lowpass_ssse3(uint8_t *dst, int16_t *tmp, int dstStride, int tmpStride, int size);\
+void ff_ ## OPNAME ## _pixels4_l2_shift5_mmxext(uint8_t *dst, int16_t *src16, uint8_t *src8, int dstStride, int src8Stride, int h);\
+void ff_ ## OPNAME ## _pixels8_l2_shift5_mmxext(uint8_t *dst, int16_t *src16, uint8_t *src8, int dstStride, int src8Stride, int h);
 
-#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)
-
+DEF_QPEL(avg)
+DEF_QPEL(put)
 
 #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;\
+static av_always_inline void ff_ ## OPNAME ## h264_qpel4_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride){\
     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"\
-        );\
+        ff_ ## OPNAME ## h264_qpel4_hv_lowpass_v_mmxext(src, tmp, srcStride);\
         tmp += 4;\
-        src += 4 - 9*srcStride;\
+        src += 4;\
     }\
     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"\
-    );\
+    ff_ ## OPNAME ## h264_qpel4_hv_lowpass_h_mmxext(tmp, dst, dstStride);\
 }\
 \
-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;\
+static av_always_inline void ff_ ## OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\
     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), "rm"(h)\
-            : "memory"\
-        );\
-        src += 4-(h+5)*srcStride;\
-        dst += 4-h*dstStride;\
-    }\
+    ff_ ## OPNAME ## h264_qpel8or16_v_lowpass_op_mmxext(dst, src, dstStride, srcStride, h);\
+    src += 4;\
+    dst += 4;\
+    ff_ ## OPNAME ## h264_qpel8or16_v_lowpass_op_mmxext(dst, src, dstStride, srcStride, h);\
 }\
-static av_always_inline void OPNAME ## h264_qpel8or16_hv1_lowpass_ ## MMX(int16_t *tmp, uint8_t *src, int tmpStride, int srcStride, int size){\
+static av_always_inline void ff_ ## 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), "rm"(size)\
-            : "memory"\
-            );\
+        ff_ ## OPNAME ## h264_qpel8or16_hv1_lowpass_op_mmxext(src, tmp, srcStride, size);\
         tmp += 4;\
-        src += 4 - (size+5)*srcStride;\
+        src += 4;\
     }\
 }\
-static av_always_inline void OPNAME ## h264_qpel8or16_hv2_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, int dstStride, int tmpStride, int size){\
+static av_always_inline void ff_ ## 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;\
+    ff_ ## OPNAME ## h264_qpel8or16_hv2_lowpass_op_mmxext(dst, tmp, dstStride, 0, size);\
+    tmp += 8;\
+    dst += 8;\
     }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_always_inline void ff_ ## OPNAME ## h264_qpel8_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
+    ff_ ## 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 ff_ ## OPNAME ## h264_qpel16_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
+    ff_ ## OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(dst  , src  , dstStride, srcStride, 16);\
+    ff_ ## 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);\
+static av_always_inline void ff_ ## OPNAME ## h264_qpel16_h_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
+    ff_ ## OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst  , src  , dstStride, srcStride);\
+    ff_ ## 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);\
+    ff_ ## OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst  , src  , dstStride, srcStride);\
+    ff_ ## 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);\
+static av_always_inline void ff_ ## OPNAME ## h264_qpel16_h_lowpass_l2_ ## MMX(uint8_t *dst, uint8_t *src, uint8_t *src2, int dstStride, int src2Stride){\
+    ff_ ## OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst  , src  , src2  , dstStride, src2Stride);\
+    ff_ ## 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);\
+    ff_ ## OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst  , src  , src2  , dstStride, src2Stride);\
+    ff_ ## 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 av_always_inline void ff_ ## OPNAME ## h264_qpel8or16_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride, int size){\
+    ff_put_h264_qpel8or16_hv1_lowpass_ ## MMX(tmp, src, tmpStride, srcStride, size);\
+    ff_ ## 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 av_always_inline void ff_ ## OPNAME ## h264_qpel8_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride){\
+    ff_ ## 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_always_inline void ff_ ## OPNAME ## h264_qpel16_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride){\
+    ff_ ## 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)\
+static av_always_inline void ff_ ## OPNAME ## pixels16_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);\
+    ff_ ## OPNAME ## pixels8_l2_shift5_ ## MMX(dst  , src16  , src8  , dstStride, src8Stride, h);\
+    ff_ ## 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"\
-    );\
-}
+
+void ff_avg_h264_qpel16_h_lowpass_l2_ssse3(uint8_t *dst, uint8_t *src, uint8_t *src2, int dstStride, int src2Stride);
+void ff_put_h264_qpel16_h_lowpass_l2_ssse3(uint8_t *dst, uint8_t *src, uint8_t *src2, int dstStride, int src2Stride);
+
 #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);\
+static av_always_inline void ff_ ## OPNAME ## h264_qpel16_h_lowpass_l2_ ## MMX(uint8_t *dst, uint8_t *src, uint8_t *src2, int dstStride, int src2Stride){\
+    ff_ ## OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst  , src  , src2  , dstStride, src2Stride);\
+    ff_ ## 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);\
+    ff_ ## OPNAME ## h264_qpel8_h_lowpass_l2_ ## MMX(dst  , src  , src2  , dstStride, src2Stride);\
+    ff_ ## 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);\
+static av_always_inline void ff_ ## OPNAME ## h264_qpel16_h_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
+    ff_ ## OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst  , src  , dstStride, srcStride);\
+    ff_ ## 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);\
+    ff_ ## OPNAME ## h264_qpel8_h_lowpass_ ## MMX(dst  , src  , dstStride, srcStride);\
+    ff_ ## 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), "rm"(h)\
-        : XMM_CLOBBERS("%xmm0", "%xmm1", "%xmm2", "%xmm3", \
-                       "%xmm4", "%xmm5", "%xmm6", "%xmm7",)\
-          "memory"\
-    );\
+static av_always_inline void ff_ ## OPNAME ## h264_qpel8_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
+    ff_ ## OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(dst  , src  , dstStride, srcStride, 8);\
 }\
-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 ff_ ## OPNAME ## h264_qpel16_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
+    ff_ ## OPNAME ## h264_qpel8or16_v_lowpass_ ## MMX(dst  , src  , dstStride, srcStride, 16);\
+    ff_ ## 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){
+static av_always_inline void ff_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), "rm"(size)
-            : XMM_CLOBBERS("%xmm0", "%xmm1", "%xmm2", "%xmm3",
-                           "%xmm4", "%xmm5", "%xmm6", "%xmm7",)
-              "memory"
-        );
+        ff_put_h264_qpel8or16_hv1_lowpass_op_sse2(src, tmp, srcStride, size);
         tmp += 8;
-        src += 8 - (size+5)*srcStride;
+        src += 8;
     }
 }
 
-#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 av_always_inline void ff_ ## OPNAME ## h264_qpel8or16_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride, int size){\
+    ff_put_h264_qpel8or16_hv1_lowpass_sse2(tmp, src, tmpStride, srcStride, size);\
+    ff_ ## 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 av_always_inline void ff_ ## OPNAME ## h264_qpel8_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride){\
+    ff_ ## 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_always_inline void ff_ ## OPNAME ## h264_qpel16_hv_lowpass_ ## MMX(uint8_t *dst, int16_t *tmp, uint8_t *src, int dstStride, int tmpStride, int srcStride){\
+    ff_ ## 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 ff_put_h264_qpel8_h_lowpass_l2_sse2  ff_put_h264_qpel8_h_lowpass_l2_mmxext
+#define ff_avg_h264_qpel8_h_lowpass_l2_sse2  ff_avg_h264_qpel8_h_lowpass_l2_mmxext
+#define ff_put_h264_qpel16_h_lowpass_l2_sse2 ff_put_h264_qpel16_h_lowpass_l2_mmxext
+#define ff_avg_h264_qpel16_h_lowpass_l2_sse2 ff_avg_h264_qpel16_h_lowpass_l2_mmxext
 
-#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 ff_put_h264_qpel8_v_lowpass_ssse3  ff_put_h264_qpel8_v_lowpass_sse2
+#define ff_avg_h264_qpel8_v_lowpass_ssse3  ff_avg_h264_qpel8_v_lowpass_sse2
+#define ff_put_h264_qpel16_v_lowpass_ssse3 ff_put_h264_qpel16_v_lowpass_sse2
+#define ff_avg_h264_qpel16_v_lowpass_ssse3 ff_avg_h264_qpel16_v_lowpass_sse2
 
-#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 ff_put_h264_qpel8or16_hv2_lowpass_sse2 ff_put_h264_qpel8or16_hv2_lowpass_mmxext
+#define ff_avg_h264_qpel8or16_hv2_lowpass_sse2 ff_avg_h264_qpel8or16_hv2_lowpass_mmxext
 
 #define H264_MC(OPNAME, SIZE, MMX, ALIGN) \
 H264_MC_C(OPNAME, SIZE, MMX, ALIGN)\
@@ -1040,77 +250,77 @@
 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);
+    ff_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);
+    ff_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 put_h264_qpel8_mc00_sse2 put_h264_qpel8_mc00_mmxext
+#define avg_h264_qpel8_mc00_sse2 avg_h264_qpel8_mc00_mmxext
 
 #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);\
+    ff_ ## 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);\
+    ff_ ## 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);\
+    ff_ ## 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);\
+    ff_ ## 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);\
+    ff_put_h264_qpel ## SIZE ## _v_lowpass_ ## MMX(temp, src, SIZE, stride);\
+    ff_ ## 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);\
+    ff_ ## 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);\
+    ff_put_h264_qpel ## SIZE ## _v_lowpass_ ## MMX(temp, src, SIZE, stride);\
+    ff_ ## 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);\
+    ff_put_h264_qpel ## SIZE ## _v_lowpass_ ## MMX(temp, src, SIZE, stride);\
+    ff_ ## 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);\
+    ff_put_h264_qpel ## SIZE ## _v_lowpass_ ## MMX(temp, src+1, SIZE, stride);\
+    ff_ ## 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);\
+    ff_put_h264_qpel ## SIZE ## _v_lowpass_ ## MMX(temp, src, SIZE, stride);\
+    ff_ ## 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);\
+    ff_put_h264_qpel ## SIZE ## _v_lowpass_ ## MMX(temp, src+1, SIZE, stride);\
+    ff_ ## 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);\
+    ff_ ## 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){\
@@ -1118,8 +328,8 @@
     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);\
+    ff_put_h264_qpel ## SIZE ## _hv_lowpass_ ## MMX(halfHV, halfV, src, SIZE, SIZE, stride);\
+    ff_ ## 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){\
@@ -1127,8 +337,8 @@
     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);\
+    ff_put_h264_qpel ## SIZE ## _hv_lowpass_ ## MMX(halfHV, halfV, src, SIZE, SIZE, stride);\
+    ff_ ## 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){\
@@ -1136,8 +346,8 @@
     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);\
+    ff_put_h264_qpel ## SIZE ## _hv_lowpass_ ## MMX(halfHV, halfV, src, SIZE, SIZE, stride);\
+    ff_ ## OPNAME ## pixels ## SIZE ## _l2_shift5_mmxext(dst, halfV+2, halfHV, stride, SIZE, SIZE);\
 }\
 \
 static void OPNAME ## h264_qpel ## SIZE ## _mc32_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
@@ -1145,8 +355,8 @@
     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);\
+    ff_put_h264_qpel ## SIZE ## _hv_lowpass_ ## MMX(halfHV, halfV, src, SIZE, SIZE, stride);\
+    ff_ ## OPNAME ## pixels ## SIZE ## _l2_shift5_mmxext(dst, halfV+3, halfHV, stride, SIZE, SIZE);\
 }\
 
 #define H264_MC_4816(MMX)\
@@ -1163,37 +373,26 @@
 QPEL(avg_, 8, XMM, 16)\
 QPEL(avg_, 16,XMM, 16)\
 
-#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(put_,        PUT_OP, mmxext)
+QPEL_H264(avg_, AVG_MMXEXT_OP, mmxext)
 QPEL_H264_V_XMM(put_,       PUT_OP, sse2)
-QPEL_H264_V_XMM(avg_,  AVG_MMX2_OP, sse2)
+QPEL_H264_V_XMM(avg_,AVG_MMXEXT_OP, sse2)
 QPEL_H264_HV_XMM(put_,       PUT_OP, sse2)
-QPEL_H264_HV_XMM(avg_,  AVG_MMX2_OP, sse2)
-#if HAVE_SSSE3_INLINE
+QPEL_H264_HV_XMM(avg_,AVG_MMXEXT_OP, sse2)
 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_H_XMM(avg_,AVG_MMXEXT_OP, ssse3)
 QPEL_H264_HV_XMM(put_,       PUT_OP, ssse3)
-QPEL_H264_HV_XMM(avg_,  AVG_MMX2_OP, ssse3)
-#endif
+QPEL_H264_HV_XMM(avg_,AVG_MMXEXT_OP, ssse3)
 #undef PAVGB
 
-H264_MC_4816(3dnow)
-H264_MC_4816(mmx2)
+H264_MC_4816(mmxext)
 H264_MC_816(H264_MC_V, sse2)
 H264_MC_816(H264_MC_HV, sse2)
-#if HAVE_SSSE3_INLINE
 H264_MC_816(H264_MC_H, ssse3)
 H264_MC_816(H264_MC_HV, ssse3)
-#endif
 
-#endif /* HAVE_INLINE_ASM */
 
 //10bit
 #define LUMA_MC_OP(OP, NUM, DEPTH, TYPE, OPT) \
@@ -1286,6 +485,8 @@
 QPEL16_OP(mc32, MMX)\
 QPEL16_OP(mc33, MMX)
 
-#if CONFIG_H264QPEL && ARCH_X86_32 && HAVE_YASM // ARCH_X86_64 implies sse2+
+#if ARCH_X86_32 && HAVE_YASM && CONFIG_H264QPEL // ARCH_X86_64 implies SSE2+
 QPEL16(mmxext)
 #endif
+
+#endif /* HAVE_YASM */
diff --git a/libavcodec/x86/h264_qpel_10bit.asm b/libavcodec/x86/h264_qpel_10bit.asm
index f380cfc..e14df84 100644
--- a/libavcodec/x86/h264_qpel_10bit.asm
+++ b/libavcodec/x86/h264_qpel_10bit.asm
@@ -22,8 +22,7 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "x86inc.asm"
-%include "x86util.asm"
+%include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA 32
 
@@ -98,81 +97,73 @@
 
 %macro MC 1
 %define OP_MOV mova
-INIT_MMX
-%1 mmxext, put, 4
-INIT_XMM
-%1 sse2  , put, 8
+INIT_MMX mmxext
+%1 put, 4
+INIT_XMM sse2
+%1 put, 8
 
 %define OP_MOV AVG_MOV
-INIT_MMX
-%1 mmxext, avg, 4
-INIT_XMM
-%1 sse2  , avg, 8
+INIT_MMX mmxext
+%1 avg, 4
+INIT_XMM sse2
+%1 avg, 8
 %endmacro
 
-%macro MCAxA 8
-%if ARCH_X86_64
-%ifnidn %1,mmxext
-MCAxA_OP %1,%2,%3,%4,%5,%6,%7,%8
-%endif
-%else
-MCAxA_OP %1,%2,%3,%4,%5,%6,%7,%8
-%endif
-%endmacro
-
-%macro MCAxA_OP 8
+%macro MCAxA_OP 7
 %if ARCH_X86_32
-cglobal %2_h264_qpel%5_%3_10_%1, %6,%7,%8
-    call stub_%2_h264_qpel%4_%3_10_%1
+cglobal %1_h264_qpel%4_%2_10, %5,%6,%7
+    call stub_%1_h264_qpel%3_%2_10 %+ SUFFIX
     mov  r0, r0m
     mov  r1, r1m
-    add  r0, %4*2
-    add  r1, %4*2
-    call stub_%2_h264_qpel%4_%3_10_%1
+    add  r0, %3*2
+    add  r1, %3*2
+    call stub_%1_h264_qpel%3_%2_10 %+ SUFFIX
     mov  r0, r0m
     mov  r1, r1m
-    lea  r0, [r0+r2*%4]
-    lea  r1, [r1+r2*%4]
-    call stub_%2_h264_qpel%4_%3_10_%1
+    lea  r0, [r0+r2*%3]
+    lea  r1, [r1+r2*%3]
+    call stub_%1_h264_qpel%3_%2_10 %+ SUFFIX
     mov  r0, r0m
     mov  r1, r1m
-    lea  r0, [r0+r2*%4+%4*2]
-    lea  r1, [r1+r2*%4+%4*2]
-    call stub_%2_h264_qpel%4_%3_10_%1
+    lea  r0, [r0+r2*%3+%3*2]
+    lea  r1, [r1+r2*%3+%3*2]
+    call stub_%1_h264_qpel%3_%2_10 %+ SUFFIX
     RET
 %else ; ARCH_X86_64
-cglobal %2_h264_qpel%5_%3_10_%1, %6,%7 + 2,%8
-    mov r%7, r0
-%assign p1 %7+1
+cglobal %1_h264_qpel%4_%2_10, %5,%6 + 2,%7
+    mov r%6, r0
+%assign p1 %6+1
     mov r %+ p1, r1
-    call stub_%2_h264_qpel%4_%3_10_%1
-    lea  r0, [r%7+%4*2]
-    lea  r1, [r %+ p1+%4*2]
-    call stub_%2_h264_qpel%4_%3_10_%1
-    lea  r0, [r%7+r2*%4]
-    lea  r1, [r %+ p1+r2*%4]
-    call stub_%2_h264_qpel%4_%3_10_%1
-    lea  r0, [r%7+r2*%4+%4*2]
-    lea  r1, [r %+ p1+r2*%4+%4*2]
+    call stub_%1_h264_qpel%3_%2_10 %+ SUFFIX
+    lea  r0, [r%6+%3*2]
+    lea  r1, [r %+ p1+%3*2]
+    call stub_%1_h264_qpel%3_%2_10 %+ SUFFIX
+    lea  r0, [r%6+r2*%3]
+    lea  r1, [r %+ p1+r2*%3]
+    call stub_%1_h264_qpel%3_%2_10 %+ SUFFIX
+    lea  r0, [r%6+r2*%3+%3*2]
+    lea  r1, [r %+ p1+r2*%3+%3*2]
 %if UNIX64 == 0 ; fall through to function
-    call stub_%2_h264_qpel%4_%3_10_%1
+    call stub_%1_h264_qpel%3_%2_10 %+ SUFFIX
     RET
 %endif
 %endif
 %endmacro
 
 ;cpu, put/avg, mc, 4/8, ...
-%macro cglobal_mc 7
-%assign i %4*2
-MCAxA %1, %2, %3, %4, i, %5,%6,%7
+%macro cglobal_mc 6
+%assign i %3*2
+%if ARCH_X86_32 || cpuflag(sse2)
+MCAxA_OP %1, %2, %3, i, %4,%5,%6
+%endif
 
-cglobal %2_h264_qpel%4_%3_10_%1, %5,%6,%7
+cglobal %1_h264_qpel%3_%2_10, %4,%5,%6
 %if UNIX64 == 0 ; no prologue or epilogue for UNIX64
-    call stub_%2_h264_qpel%4_%3_10_%1
+    call stub_%1_h264_qpel%3_%2_10 %+ SUFFIX
     RET
 %endif
 
-stub_%2_h264_qpel%4_%3_10_%1:
+stub_%1_h264_qpel%3_%2_10 %+ SUFFIX:
 %endmacro
 
 ;-----------------------------------------------------------------------------
@@ -190,14 +181,14 @@
 %endmacro
 
 %macro MC00 1
-INIT_MMX
-cglobal_mc mmxext, %1, mc00, 4, 3,4,0
+INIT_MMX mmxext
+cglobal_mc %1, mc00, 4, 3,4,0
     lea           r3, [r2*3]
     COPY4
     ret
 
-INIT_XMM
-cglobal %1_h264_qpel8_mc00_10_sse2, 3,4
+INIT_XMM sse2
+cglobal %1_h264_qpel8_mc00_10, 3,4
     lea  r3, [r2*3]
     COPY4
     lea  r0, [r0+r2*4]
@@ -205,7 +196,7 @@
     COPY4
     RET
 
-cglobal %1_h264_qpel16_mc00_10_sse2, 3,4
+cglobal %1_h264_qpel16_mc00_10, 3,4
     mov r3d, 8
 .loop:
     movu           m0, [r1      ]
@@ -234,29 +225,29 @@
 ;-----------------------------------------------------------------------------
 %macro MC_CACHE 1
 %define OP_MOV mova
-%define PALIGNR PALIGNR_MMX
-INIT_MMX
-%1 mmxext       , put, 4
-INIT_XMM
-%1 sse2_cache64 , put, 8
-%define PALIGNR PALIGNR_SSSE3
-%1 ssse3_cache64, put, 8
-%1 sse2         , put, 8, 0
+INIT_MMX mmxext
+%1 put, 4
+INIT_XMM sse2, cache64
+%1 put, 8
+INIT_XMM ssse3, cache64
+%1 put, 8
+INIT_XMM sse2
+%1 put, 8
 
 %define OP_MOV AVG_MOV
-%define PALIGNR PALIGNR_MMX
-INIT_MMX
-%1 mmxext       , avg, 4
-INIT_XMM
-%1 sse2_cache64 , avg, 8
-%define PALIGNR PALIGNR_SSSE3
-%1 ssse3_cache64, avg, 8
-%1 sse2         , avg, 8, 0
+INIT_MMX mmxext
+%1 avg, 4
+INIT_XMM sse2, cache64
+%1 avg, 8
+INIT_XMM ssse3, cache64
+%1 avg, 8
+INIT_XMM sse2
+%1 avg, 8
 %endmacro
 
-%macro MC20 3-4
-cglobal_mc %1, %2, mc20, %3, 3,4,9
-    mov     r3d, %3
+%macro MC20 2
+cglobal_mc %1, mc20, %2, 3,4,9
+    mov     r3d, %2
     mova     m1, [pw_pixel_max]
 %if num_mmregs > 8
     mova     m8, [pw_16]
@@ -316,10 +307,10 @@
 ;-----------------------------------------------------------------------------
 ; void h264_qpel_mc30(uint8_t *dst, uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
-%macro MC30 3-4
-cglobal_mc %1, %2, mc30, %3, 3,5,9
+%macro MC30 2
+cglobal_mc %1, mc30, %2, 3,5,9
     lea r4, [r1+2]
-    jmp stub_%2_h264_qpel%3_mc10_10_%1.body
+    jmp stub_%1_h264_qpel%2_mc10_10 %+ SUFFIX %+ .body
 %endmacro
 
 MC_CACHE MC30
@@ -327,11 +318,11 @@
 ;-----------------------------------------------------------------------------
 ; void h264_qpel_mc10(uint8_t *dst, uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
-%macro MC10 3-4
-cglobal_mc %1, %2, mc10, %3, 3,5,9
+%macro MC10 2
+cglobal_mc %1, mc10, %2, 3,5,9
     mov      r4, r1
 .body:
-    mov     r3d, %3
+    mov     r3d, %2
     mova     m1, [pw_pixel_max]
 %if num_mmregs > 8
     mova     m8, [pw_16]
@@ -394,8 +385,8 @@
 ;-----------------------------------------------------------------------------
 ; void h264_qpel_mc02(uint8_t *dst, uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
-%macro V_FILT 11
-v_filt%9_%10_10_%11:
+%macro V_FILT 10
+v_filt%9_%10_10
     add    r4, r2
 .no_addr4:
     FILT_V m0, m1, m2, m3, m4, m5, m6, m7
@@ -404,33 +395,33 @@
     ret
 %endmacro
 
-INIT_MMX
+INIT_MMX mmxext
 RESET_MM_PERMUTATION
 %assign i 0
 %rep 4
-V_FILT m0, m1, m2, m3, m4, m5, m6, m7, 4, i, mmxext
+V_FILT m0, m1, m2, m3, m4, m5, m6, m7, 4, i
 SWAP 0,1,2,3,4,5
 %assign i i+1
 %endrep
 
-INIT_XMM
+INIT_XMM sse2
 RESET_MM_PERMUTATION
 %assign i 0
 %rep 6
-V_FILT m0, m1, m2, m3, m4, m5, m6, m7, 8, i, sse2
+V_FILT m0, m1, m2, m3, m4, m5, m6, m7, 8, i
 SWAP 0,1,2,3,4,5
 %assign i i+1
 %endrep
 
-%macro MC02 3
-cglobal_mc %1, %2, mc02, %3, 3,4,8
+%macro MC02 2
+cglobal_mc %1, mc02, %2, 3,4,8
     PRELOAD_V
 
     sub      r0, r2
 %assign j 0
-%rep %3
+%rep %2
     %assign i (j % 6)
-    call v_filt%3_ %+ i %+ _10_%1.no_addr4
+    call v_filt%2_ %+ i %+ _10.no_addr4
     OP_MOV [r0], m0
     SWAP 0,1,2,3,4,5
     %assign j j+1
@@ -443,8 +434,8 @@
 ;-----------------------------------------------------------------------------
 ; void h264_qpel_mc01(uint8_t *dst, uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
-%macro MC01 3
-cglobal_mc %1, %2, mc01, %3, 3,5,8
+%macro MC01 2
+cglobal_mc %1, mc01, %2, 3,5,8
     mov      r4, r1
 .body:
     PRELOAD_V
@@ -452,9 +443,9 @@
     sub      r4, r2
     sub      r0, r2
 %assign j 0
-%rep %3
+%rep %2
     %assign i (j % 6)
-    call v_filt%3_ %+ i %+ _10_%1
+    call v_filt%2_ %+ i %+ _10
     movu     m7, [r4]
     pavgw    m0, m7
     OP_MOV [r0], m0
@@ -469,10 +460,10 @@
 ;-----------------------------------------------------------------------------
 ; void h264_qpel_mc03(uint8_t *dst, uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
-%macro MC03 3
-cglobal_mc %1, %2, mc03, %3, 3,5,8
+%macro MC03 2
+cglobal_mc %1, mc03, %2, 3,5,8
     lea r4, [r1+r2]
-    jmp stub_%2_h264_qpel%3_mc01_10_%1.body
+    jmp stub_%1_h264_qpel%2_mc01_10 %+ SUFFIX %+ .body
 %endmacro
 
 MC MC03
@@ -480,8 +471,8 @@
 ;-----------------------------------------------------------------------------
 ; void h264_qpel_mc11(uint8_t *dst, uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
-%macro H_FILT_AVG 3-4
-h_filt%2_%3_10_%1:
+%macro H_FILT_AVG 2-3
+h_filt%1_%2_10:
 ;FILT_H with fewer registers and averaged with the FILT_V result
 ;m6,m7 are tmp registers, m0 is the FILT_V result, the rest are to be used next in the next iteration
 ;unfortunately I need three registers, so m5 will have to be re-read from memory
@@ -508,32 +499,32 @@
     ret
 %endmacro
 
-INIT_MMX
+INIT_MMX mmxext
 RESET_MM_PERMUTATION
 %assign i 0
 %rep 3
-H_FILT_AVG mmxext, 4, i
+H_FILT_AVG 4, i
 SWAP 0,1,2,3,4,5
 %assign i i+1
 %endrep
-H_FILT_AVG mmxext, 4, i, 0
+H_FILT_AVG 4, i, 0
 
-INIT_XMM
+INIT_XMM sse2
 RESET_MM_PERMUTATION
 %assign i 0
 %rep 6
 %if i==1
-H_FILT_AVG sse2,   8, i, 0
+H_FILT_AVG 8, i, 0
 %else
-H_FILT_AVG sse2,   8, i
+H_FILT_AVG 8, i
 %endif
 SWAP 0,1,2,3,4,5
 %assign i i+1
 %endrep
 
-%macro MC11 3
+%macro MC11 2
 ; this REALLY needs x86_64
-cglobal_mc %1, %2, mc11, %3, 3,6,8
+cglobal_mc %1, mc11, %2, 3,6,8
     mov      r4, r1
 .body:
     PRELOAD_V
@@ -543,11 +534,11 @@
     mov      r5, r2
     neg      r5
 %assign j 0
-%rep %3
+%rep %2
     %assign i (j % 6)
-    call v_filt%3_ %+ i %+ _10_%1
-    call h_filt%3_ %+ i %+ _10_%1
-%if %3==8 && i==1
+    call v_filt%2_ %+ i %+ _10
+    call h_filt%2_ %+ i %+ _10
+%if %2==8 && i==1
     movu     m5, [r1+r5]
 %endif
     OP_MOV [r0], m0
@@ -562,11 +553,11 @@
 ;-----------------------------------------------------------------------------
 ; void h264_qpel_mc31(uint8_t *dst, uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
-%macro MC31 3
-cglobal_mc %1, %2, mc31, %3, 3,6,8
+%macro MC31 2
+cglobal_mc %1, mc31, %2, 3,6,8
     mov r4, r1
     add r1, 2
-    jmp stub_%2_h264_qpel%3_mc11_10_%1.body
+    jmp stub_%1_h264_qpel%2_mc11_10 %+ SUFFIX %+ .body
 %endmacro
 
 MC MC31
@@ -574,10 +565,10 @@
 ;-----------------------------------------------------------------------------
 ; void h264_qpel_mc13(uint8_t *dst, uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
-%macro MC13 3
-cglobal_mc %1, %2, mc13, %3, 3,7,12
+%macro MC13 2
+cglobal_mc %1, mc13, %2, 3,7,12
     lea r4, [r1+r2]
-    jmp stub_%2_h264_qpel%3_mc11_10_%1.body
+    jmp stub_%1_h264_qpel%2_mc11_10 %+ SUFFIX %+ .body
 %endmacro
 
 MC MC13
@@ -585,11 +576,11 @@
 ;-----------------------------------------------------------------------------
 ; void h264_qpel_mc33(uint8_t *dst, uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
-%macro MC33 3
-cglobal_mc %1, %2, mc33, %3, 3,6,8
+%macro MC33 2
+cglobal_mc %1, mc33, %2, 3,6,8
     lea r4, [r1+r2]
     add r1, 2
-    jmp stub_%2_h264_qpel%3_mc11_10_%1.body
+    jmp stub_%1_h264_qpel%2_mc11_10 %+ SUFFIX %+ .body
 %endmacro
 
 MC MC33
@@ -616,15 +607,15 @@
     FILT_H2  %1, %7, %8
 %endmacro
 
-%macro HV 2
-%ifidn %1,sse2
+%macro HV 1
+%if mmsize==16
 %define PAD 12
 %define COUNT 2
 %else
 %define PAD 4
 %define COUNT 3
 %endif
-put_hv%2_10_%1:
+put_hv%1_10:
     neg      r2           ; This actually saves instructions
     lea      r1, [r1+r2*2-mmsize+PAD]
     lea      r4, [rsp+PAD+gprsize]
@@ -641,7 +632,7 @@
     movu     m4, [r1]
     sub      r1, r2
 %assign i 0
-%rep %2-1
+%rep %1-1
     FILT_VNRD m0, m1, m2, m3, m4, m5, m6, m7
     psubw    m0, [pad20]
     movu     [r4+i*mmsize*3], m0
@@ -654,7 +645,7 @@
     movu     [r4+i*mmsize*3], m0
     add      r4, mmsize
     lea      r1, [r1+r2*8+mmsize]
-%if %2==8
+%if %1==8
     lea      r1, [r1+r2*4]
 %endif
     dec      r3d
@@ -663,12 +654,12 @@
     ret
 %endmacro
 
-INIT_MMX
-HV mmxext, 4
-INIT_XMM
-HV sse2  , 8
+INIT_MMX mmxext
+HV 4
+INIT_XMM sse2
+HV 8
 
-%macro H_LOOP 2
+%macro H_LOOP 1
 %if num_mmregs > 8
     %define s1 m8
     %define s2 m9
@@ -680,7 +671,7 @@
     %define s3 [tap3]
     %define d1 [depad]
 %endif
-h%2_loop_op_%1:
+h%1_loop_op:
     movu       m1, [r1+mmsize-4]
     movu       m2, [r1+mmsize-2]
     mova       m3, [r1+mmsize+0]
@@ -727,21 +718,21 @@
     ret
 %endmacro
 
-INIT_MMX
-H_LOOP mmxext, 4
-INIT_XMM
-H_LOOP sse2  , 8
+INIT_MMX mmxext
+H_LOOP 4
+INIT_XMM sse2
+H_LOOP 8
 
-%macro MC22 3
-cglobal_mc %1, %2, mc22, %3, 3,7,12
+%macro MC22 2
+cglobal_mc %1, mc22, %2, 3,7,12
 %define PAD mmsize*8*4*2      ; SIZE*16*4*sizeof(pixel)
     mov      r6, rsp          ; backup stack pointer
     and     rsp, ~(mmsize-1)  ; align stack
     sub     rsp, PAD
 
-    call put_hv%3_10_%1
+    call put_hv%2_10
 
-    mov       r3d, %3
+    mov       r3d, %2
     mova       m7, [pw_pixel_max]
 %if num_mmregs > 8
     pxor       m0, m0
@@ -752,7 +743,7 @@
 %endif
     mov        r1, rsp
 .h_loop:
-    call h%3_loop_op_%1
+    call h%2_loop_op
 
     OP_MOV   [r0], m1
     add        r0, r2
@@ -768,18 +759,18 @@
 ;-----------------------------------------------------------------------------
 ; void h264_qpel_mc12(uint8_t *dst, uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
-%macro MC12 3
-cglobal_mc %1, %2, mc12, %3, 3,7,12
+%macro MC12 2
+cglobal_mc %1, mc12, %2, 3,7,12
 %define PAD mmsize*8*4*2        ; SIZE*16*4*sizeof(pixel)
     mov        r6, rsp          ; backup stack pointer
     and       rsp, ~(mmsize-1)  ; align stack
     sub       rsp, PAD
 
-    call put_hv%3_10_%1
+    call put_hv%2_10
 
     xor       r4d, r4d
 .body:
-    mov       r3d, %3
+    mov       r3d, %2
     pxor       m0, m0
     mova       m7, [pw_pixel_max]
 %if num_mmregs > 8
@@ -790,7 +781,7 @@
 %endif
     mov        r1, rsp
 .h_loop:
-    call h%3_loop_op_%1
+    call h%2_loop_op
 
     movu       m3, [r1+r4-2*mmsize] ; movu needed for mc32, etc
     paddw      m3, [depad2]
@@ -813,17 +804,17 @@
 ;-----------------------------------------------------------------------------
 ; void h264_qpel_mc32(uint8_t *dst, uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
-%macro MC32 3
-cglobal_mc %1, %2, mc32, %3, 3,7,12
+%macro MC32 2
+cglobal_mc %1, mc32, %2, 3,7,12
 %define PAD mmsize*8*3*2  ; SIZE*16*4*sizeof(pixel)
     mov  r6, rsp          ; backup stack pointer
     and rsp, ~(mmsize-1)  ; align stack
     sub rsp, PAD
 
-    call put_hv%3_10_%1
+    call put_hv%2_10
 
     mov r4d, 2            ; sizeof(pixel)
-    jmp stub_%2_h264_qpel%3_mc12_10_%1.body
+    jmp stub_%1_h264_qpel%2_mc12_10 %+ SUFFIX %+ .body
 %endmacro
 
 MC MC32
@@ -831,10 +822,10 @@
 ;-----------------------------------------------------------------------------
 ; void h264_qpel_mc21(uint8_t *dst, uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
-%macro H_NRD 2
-put_h%2_10_%1:
+%macro H_NRD 1
+put_h%1_10:
     add       rsp, gprsize
-    mov       r3d, %2
+    mov       r3d, %1
     xor       r4d, r4d
     mova       m6, [pad20]
 .nextrow:
@@ -856,13 +847,13 @@
     ret
 %endmacro
 
-INIT_MMX
-H_NRD mmxext, 4
-INIT_XMM
-H_NRD sse2  , 8
+INIT_MMX mmxext
+H_NRD 4
+INIT_XMM sse2
+H_NRD 8
 
-%macro MC21 3
-cglobal_mc %1, %2, mc21, %3, 3,7,12
+%macro MC21 2
+cglobal_mc %1, mc21, %2, 3,7,12
     mov   r5, r1
 .body:
 %define PAD mmsize*8*3*2   ; SIZE*16*4*sizeof(pixel)
@@ -870,13 +861,13 @@
     and  rsp, ~(mmsize-1)  ; align stack
 
     sub  rsp, PAD
-    call put_h%3_10_%1
+    call put_h%2_10
 
     sub  rsp, PAD
-    call put_hv%3_10_%1
+    call put_hv%2_10
 
     mov r4d, PAD-mmsize    ; H buffer
-    jmp stub_%2_h264_qpel%3_mc12_10_%1.body
+    jmp stub_%1_h264_qpel%2_mc12_10 %+ SUFFIX %+ .body
 %endmacro
 
 MC MC21
@@ -884,10 +875,10 @@
 ;-----------------------------------------------------------------------------
 ; void h264_qpel_mc23(uint8_t *dst, uint8_t *src, int stride)
 ;-----------------------------------------------------------------------------
-%macro MC23 3
-cglobal_mc %1, %2, mc23, %3, 3,7,12
+%macro MC23 2
+cglobal_mc %1, mc23, %2, 3,7,12
     lea   r5, [r1+r2]
-    jmp stub_%2_h264_qpel%3_mc21_10_%1.body
+    jmp stub_%1_h264_qpel%2_mc21_10 %+ SUFFIX %+ .body
 %endmacro
 
 MC MC23
diff --git a/libavcodec/x86/h264_qpel_8bit.asm b/libavcodec/x86/h264_qpel_8bit.asm
new file mode 100644
index 0000000..2d287ba
--- /dev/null
+++ b/libavcodec/x86/h264_qpel_8bit.asm
@@ -0,0 +1,862 @@
+;*****************************************************************************
+;* MMX/SSE2/SSSE3-optimized H.264 QPEL code
+;*****************************************************************************
+;* Copyright (c) 2004-2005 Michael Niedermayer, Loren Merritt
+;* Copyright (C) 2012 Daniel Kang
+;*
+;* Authors: Daniel Kang <daniel.d.kang@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/x86util.asm"
+
+SECTION_RODATA 32
+
+cextern pw_16
+cextern pw_5
+cextern pb_0
+
+SECTION .text
+
+
+%macro op_avgh 3
+    movh   %3, %2
+    pavgb  %1, %3
+    movh   %2, %1
+%endmacro
+
+%macro op_avg 2-3
+    pavgb  %1, %2
+    mova   %2, %1
+%endmacro
+
+%macro op_puth 2-3
+    movh   %2, %1
+%endmacro
+
+%macro op_put 2-3
+    mova   %2, %1
+%endmacro
+
+%macro QPEL4_H_LOWPASS_OP 1
+cglobal %1_h264_qpel4_h_lowpass, 4,5 ; dst, src, dstStride, srcStride
+    movsxdifnidn  r2, r2d
+    movsxdifnidn  r3, r3d
+    pxor          m7, m7
+    mova          m4, [pw_5]
+    mova          m5, [pw_16]
+    mov          r4d, 4
+.loop:
+    movh          m1, [r1-1]
+    movh          m2, [r1+0]
+    movh          m3, [r1+1]
+    movh          m0, [r1+2]
+    punpcklbw     m1, m7
+    punpcklbw     m2, m7
+    punpcklbw     m3, m7
+    punpcklbw     m0, m7
+    paddw         m1, m0
+    paddw         m2, m3
+    movh          m0, [r1-2]
+    movh          m3, [r1+3]
+    punpcklbw     m0, m7
+    punpcklbw     m3, m7
+    paddw         m0, m3
+    psllw         m2, 2
+    psubw         m2, m1
+    pmullw        m2, m4
+    paddw         m0, m5
+    paddw         m0, m2
+    psraw         m0, 5
+    packuswb      m0, m0
+    op_%1h        m0, [r0], m6
+    add           r0, r2
+    add           r1, r3
+    dec          r4d
+    jg         .loop
+    REP_RET
+%endmacro
+
+INIT_MMX mmxext
+QPEL4_H_LOWPASS_OP put
+QPEL4_H_LOWPASS_OP avg
+
+%macro QPEL8_H_LOWPASS_OP 1
+cglobal %1_h264_qpel8_h_lowpass, 4,5 ; dst, src, dstStride, srcStride
+    movsxdifnidn  r2, r2d
+    movsxdifnidn  r3, r3d
+    mov          r4d, 8
+    pxor          m7, m7
+    mova          m6, [pw_5]
+.loop:
+    mova          m0, [r1]
+    mova          m2, [r1+1]
+    mova          m1, m0
+    mova          m3, m2
+    punpcklbw     m0, m7
+    punpckhbw     m1, m7
+    punpcklbw     m2, m7
+    punpckhbw     m3, m7
+    paddw         m0, m2
+    paddw         m1, m3
+    psllw         m0, 2
+    psllw         m1, 2
+    mova          m2, [r1-1]
+    mova          m4, [r1+2]
+    mova          m3, m2
+    mova          m5, m4
+    punpcklbw     m2, m7
+    punpckhbw     m3, m7
+    punpcklbw     m4, m7
+    punpckhbw     m5, m7
+    paddw         m2, m4
+    paddw         m5, m3
+    psubw         m0, m2
+    psubw         m1, m5
+    pmullw        m0, m6
+    pmullw        m1, m6
+    movd          m2, [r1-2]
+    movd          m5, [r1+7]
+    punpcklbw     m2, m7
+    punpcklbw     m5, m7
+    paddw         m2, m3
+    paddw         m4, m5
+    mova          m5, [pw_16]
+    paddw         m2, m5
+    paddw         m4, m5
+    paddw         m0, m2
+    paddw         m1, m4
+    psraw         m0, 5
+    psraw         m1, 5
+    packuswb      m0, m1
+    op_%1         m0, [r0], m4
+    add           r0, r2
+    add           r1, r3
+    dec          r4d
+    jg         .loop
+    REP_RET
+%endmacro
+
+INIT_MMX mmxext
+QPEL8_H_LOWPASS_OP put
+QPEL8_H_LOWPASS_OP avg
+
+%macro QPEL8_H_LOWPASS_OP_XMM 1
+cglobal %1_h264_qpel8_h_lowpass, 4,5,8 ; dst, src, dstStride, srcStride
+    movsxdifnidn  r2, r2d
+    movsxdifnidn  r3, r3d
+    mov          r4d, 8
+    pxor          m7, m7
+    mova          m6, [pw_5]
+.loop:
+    movu          m1, [r1-2]
+    mova          m0, m1
+    punpckhbw     m1, m7
+    punpcklbw     m0, m7
+    mova          m2, m1
+    mova          m3, m1
+    mova          m4, m1
+    mova          m5, m1
+    palignr       m4, m0, 2
+    palignr       m3, m0, 4
+    palignr       m2, m0, 6
+    palignr       m1, m0, 8
+    palignr       m5, m0, 10
+    paddw         m0, m5
+    paddw         m2, m3
+    paddw         m1, m4
+    psllw         m2, 2
+    psubw         m2, m1
+    paddw         m0, [pw_16]
+    pmullw        m2, m6
+    paddw         m2, m0
+    psraw         m2, 5
+    packuswb      m2, m2
+    op_%1h        m2, [r0], m4
+    add           r1, r3
+    add           r0, r2
+    dec          r4d
+    jne        .loop
+    REP_RET
+%endmacro
+
+INIT_XMM ssse3
+QPEL8_H_LOWPASS_OP_XMM put
+QPEL8_H_LOWPASS_OP_XMM avg
+
+
+%macro QPEL4_H_LOWPASS_L2_OP 1
+cglobal %1_h264_qpel4_h_lowpass_l2, 5,6 ; dst, src, src2, dstStride, srcStride
+    movsxdifnidn  r3, r3d
+    movsxdifnidn  r4, r4d
+    pxor          m7, m7
+    mova          m4, [pw_5]
+    mova          m5, [pw_16]
+    mov          r5d, 4
+.loop:
+    movh          m1, [r1-1]
+    movh          m2, [r1+0]
+    movh          m3, [r1+1]
+    movh          m0, [r1+2]
+    punpcklbw     m1, m7
+    punpcklbw     m2, m7
+    punpcklbw     m3, m7
+    punpcklbw     m0, m7
+    paddw         m1, m0
+    paddw         m2, m3
+    movh          m0, [r1-2]
+    movh          m3, [r1+3]
+    punpcklbw     m0, m7
+    punpcklbw     m3, m7
+    paddw         m0, m3
+    psllw         m2, 2
+    psubw         m2, m1
+    pmullw        m2, m4
+    paddw         m0, m5
+    paddw         m0, m2
+    movh          m3, [r2]
+    psraw         m0, 5
+    packuswb      m0, m0
+    pavgb         m0, m3
+    op_%1h        m0, [r0], m6
+    add           r0, r3
+    add           r1, r3
+    add           r2, r4
+    dec          r5d
+    jg         .loop
+    REP_RET
+%endmacro
+
+INIT_MMX mmxext
+QPEL4_H_LOWPASS_L2_OP put
+QPEL4_H_LOWPASS_L2_OP avg
+
+
+%macro QPEL8_H_LOWPASS_L2_OP 1
+cglobal %1_h264_qpel8_h_lowpass_l2, 5,6 ; dst, src, src2, dstStride, srcStride
+    movsxdifnidn  r3, r3d
+    movsxdifnidn  r4, r4d
+    mov          r5d, 8
+    pxor          m7, m7
+    mova          m6, [pw_5]
+.loop:
+    mova          m0, [r1]
+    mova          m2, [r1+1]
+    mova          m1, m0
+    mova          m3, m2
+    punpcklbw     m0, m7
+    punpckhbw     m1, m7
+    punpcklbw     m2, m7
+    punpckhbw     m3, m7
+    paddw         m0, m2
+    paddw         m1, m3
+    psllw         m0, 2
+    psllw         m1, 2
+    mova          m2, [r1-1]
+    mova          m4, [r1+2]
+    mova          m3, m2
+    mova          m5, m4
+    punpcklbw     m2, m7
+    punpckhbw     m3, m7
+    punpcklbw     m4, m7
+    punpckhbw     m5, m7
+    paddw         m2, m4
+    paddw         m5, m3
+    psubw         m0, m2
+    psubw         m1, m5
+    pmullw        m0, m6
+    pmullw        m1, m6
+    movd          m2, [r1-2]
+    movd          m5, [r1+7]
+    punpcklbw     m2, m7
+    punpcklbw     m5, m7
+    paddw         m2, m3
+    paddw         m4, m5
+    mova          m5, [pw_16]
+    paddw         m2, m5
+    paddw         m4, m5
+    paddw         m0, m2
+    paddw         m1, m4
+    psraw         m0, 5
+    psraw         m1, 5
+    mova          m4, [r2]
+    packuswb      m0, m1
+    pavgb         m0, m4
+    op_%1         m0, [r0], m4
+    add           r0, r3
+    add           r1, r3
+    add           r2, r4
+    dec          r5d
+    jg         .loop
+    REP_RET
+%endmacro
+
+INIT_MMX mmxext
+QPEL8_H_LOWPASS_L2_OP put
+QPEL8_H_LOWPASS_L2_OP avg
+
+
+%macro QPEL8_H_LOWPASS_L2_OP_XMM 1
+cglobal %1_h264_qpel8_h_lowpass_l2, 5,6,8 ; dst, src, src2, dstStride, src2Stride
+    movsxdifnidn  r3, r3d
+    movsxdifnidn  r4, r4d
+    mov          r5d, 8
+    pxor          m7, m7
+    mova          m6, [pw_5]
+.loop:
+    lddqu         m1, [r1-2]
+    mova          m0, m1
+    punpckhbw     m1, m7
+    punpcklbw     m0, m7
+    mova          m2, m1
+    mova          m3, m1
+    mova          m4, m1
+    mova          m5, m1
+    palignr       m4, m0, 2
+    palignr       m3, m0, 4
+    palignr       m2, m0, 6
+    palignr       m1, m0, 8
+    palignr       m5, m0, 10
+    paddw         m0, m5
+    paddw         m2, m3
+    paddw         m1, m4
+    psllw         m2, 2
+    movh          m3, [r2]
+    psubw         m2, m1
+    paddw         m0, [pw_16]
+    pmullw        m2, m6
+    paddw         m2, m0
+    psraw         m2, 5
+    packuswb      m2, m2
+    pavgb         m2, m3
+    op_%1h        m2, [r0], m4
+    add           r1, r3
+    add           r0, r3
+    add           r2, r4
+    dec          r5d
+    jg         .loop
+    REP_RET
+%endmacro
+
+INIT_XMM ssse3
+QPEL8_H_LOWPASS_L2_OP_XMM put
+QPEL8_H_LOWPASS_L2_OP_XMM avg
+
+
+; All functions that call this are required to have function arguments of
+; dst, src, dstStride, srcStride
+%macro FILT_V 1
+    mova      m6, m2
+    movh      m5, [r1]
+    paddw     m6, m3
+    psllw     m6, 2
+    psubw     m6, m1
+    psubw     m6, m4
+    punpcklbw m5, m7
+    pmullw    m6, [pw_5]
+    paddw     m0, [pw_16]
+    add       r1, r3
+    paddw     m0, m5
+    paddw     m6, m0
+    psraw     m6, 5
+    packuswb  m6, m6
+    op_%1h    m6, [r0], m0 ; 1
+    add       r0, r2
+    SWAP       0, 1, 2, 3, 4, 5
+%endmacro
+
+%macro QPEL4_V_LOWPASS_OP 1
+cglobal %1_h264_qpel4_v_lowpass, 4,4 ; dst, src, dstStride, srcStride
+    movsxdifnidn  r2, r2d
+    movsxdifnidn  r3, r3d
+    sub           r1, r3
+    sub           r1, r3
+    pxor          m7, m7
+    movh          m0, [r1]
+    movh          m1, [r1+r3]
+    lea           r1, [r1+2*r3]
+    movh          m2, [r1]
+    movh          m3, [r1+r3]
+    lea           r1, [r1+2*r3]
+    movh          m4, [r1]
+    add           r1, r3
+    punpcklbw     m0, m7
+    punpcklbw     m1, m7
+    punpcklbw     m2, m7
+    punpcklbw     m3, m7
+    punpcklbw     m4, m7
+    FILT_V        %1
+    FILT_V        %1
+    FILT_V        %1
+    FILT_V        %1
+    RET
+%endmacro
+
+INIT_MMX mmxext
+QPEL4_V_LOWPASS_OP put
+QPEL4_V_LOWPASS_OP avg
+
+
+
+%macro QPEL8OR16_V_LOWPASS_OP 1
+%if cpuflag(sse2)
+cglobal %1_h264_qpel8or16_v_lowpass, 5,5,8 ; dst, src, dstStride, srcStride, h
+    movsxdifnidn  r2, r2d
+    movsxdifnidn  r3, r3d
+    sub           r1, r3
+    sub           r1, r3
+%else
+cglobal %1_h264_qpel8or16_v_lowpass_op, 5,5,8 ; dst, src, dstStride, srcStride, h
+    movsxdifnidn  r2, r2d
+    movsxdifnidn  r3, r3d
+%endif
+    pxor          m7, m7
+    movh          m0, [r1]
+    movh          m1, [r1+r3]
+    lea           r1, [r1+2*r3]
+    movh          m2, [r1]
+    movh          m3, [r1+r3]
+    lea           r1, [r1+2*r3]
+    movh          m4, [r1]
+    add           r1, r3
+    punpcklbw     m0, m7
+    punpcklbw     m1, m7
+    punpcklbw     m2, m7
+    punpcklbw     m3, m7
+    punpcklbw     m4, m7
+    FILT_V        %1
+    FILT_V        %1
+    FILT_V        %1
+    FILT_V        %1
+    FILT_V        %1
+    FILT_V        %1
+    FILT_V        %1
+    FILT_V        %1
+    cmp          r4d, 16
+    jne         .end
+    FILT_V        %1
+    FILT_V        %1
+    FILT_V        %1
+    FILT_V        %1
+    FILT_V        %1
+    FILT_V        %1
+    FILT_V        %1
+    FILT_V        %1
+.end:
+    REP_RET
+%endmacro
+
+INIT_MMX mmxext
+QPEL8OR16_V_LOWPASS_OP put
+QPEL8OR16_V_LOWPASS_OP avg
+
+INIT_XMM sse2
+QPEL8OR16_V_LOWPASS_OP put
+QPEL8OR16_V_LOWPASS_OP avg
+
+
+; All functions that use this are required to have args:
+; src, tmp, srcSize
+%macro FILT_HV 1 ; offset
+    mova           m6, m2
+    movh           m5, [r0]
+    paddw          m6, m3
+    psllw          m6, 2
+    paddw          m0, [pw_16]
+    psubw          m6, m1
+    psubw          m6, m4
+    punpcklbw      m5, m7
+    pmullw         m6, [pw_5]
+    paddw          m0, m5
+    add            r0, r2
+    paddw          m6, m0
+    mova      [r1+%1], m6
+    SWAP            0, 1, 2, 3, 4, 5
+%endmacro
+
+%macro QPEL4_HV1_LOWPASS_OP 1
+cglobal %1_h264_qpel4_hv_lowpass_v, 3,3 ; src, tmp, srcStride
+    movsxdifnidn  r2, r2d
+    pxor          m7, m7
+    movh          m0, [r0]
+    movh          m1, [r0+r2]
+    lea           r0, [r0+2*r2]
+    movh          m2, [r0]
+    movh          m3, [r0+r2]
+    lea           r0, [r0+2*r2]
+    movh          m4, [r0]
+    add           r0, r2
+    punpcklbw     m0, m7
+    punpcklbw     m1, m7
+    punpcklbw     m2, m7
+    punpcklbw     m3, m7
+    punpcklbw     m4, m7
+    FILT_HV       0*24
+    FILT_HV       1*24
+    FILT_HV       2*24
+    FILT_HV       3*24
+    RET
+
+cglobal %1_h264_qpel4_hv_lowpass_h, 3,4 ; tmp, dst, dstStride
+    movsxdifnidn  r2, r2d
+    mov          r3d, 4
+.loop:
+    mova          m0, [r0]
+    paddw         m0, [r0+10]
+    mova          m1, [r0+2]
+    paddw         m1, [r0+8]
+    mova          m2, [r0+4]
+    paddw         m2, [r0+6]
+    psubw         m0, m1
+    psraw         m0, 2
+    psubw         m0, m1
+    paddsw        m0, m2
+    psraw         m0, 2
+    paddw         m0, m2
+    psraw         m0, 6
+    packuswb      m0, m0
+    op_%1h        m0, [r1], m7
+    add           r0, 24
+    add           r1, r2
+    dec          r3d
+    jnz        .loop
+    REP_RET
+%endmacro
+
+INIT_MMX mmxext
+QPEL4_HV1_LOWPASS_OP put
+QPEL4_HV1_LOWPASS_OP avg
+
+%macro QPEL8OR16_HV1_LOWPASS_OP 1
+cglobal %1_h264_qpel8or16_hv1_lowpass_op, 4,4,8 ; src, tmp, srcStride, size
+    movsxdifnidn  r2, r2d
+    pxor          m7, m7
+    movh          m0, [r0]
+    movh          m1, [r0+r2]
+    lea           r0, [r0+2*r2]
+    movh          m2, [r0]
+    movh          m3, [r0+r2]
+    lea           r0, [r0+2*r2]
+    movh          m4, [r0]
+    add           r0, r2
+    punpcklbw     m0, m7
+    punpcklbw     m1, m7
+    punpcklbw     m2, m7
+    punpcklbw     m3, m7
+    punpcklbw     m4, m7
+    FILT_HV     0*48
+    FILT_HV     1*48
+    FILT_HV     2*48
+    FILT_HV     3*48
+    FILT_HV     4*48
+    FILT_HV     5*48
+    FILT_HV     6*48
+    FILT_HV     7*48
+    cmp          r3d, 16
+    jne         .end
+    FILT_HV     8*48
+    FILT_HV     9*48
+    FILT_HV    10*48
+    FILT_HV    11*48
+    FILT_HV    12*48
+    FILT_HV    13*48
+    FILT_HV    14*48
+    FILT_HV    15*48
+.end:
+    REP_RET
+%endmacro
+
+INIT_MMX mmxext
+QPEL8OR16_HV1_LOWPASS_OP put
+QPEL8OR16_HV1_LOWPASS_OP avg
+
+INIT_XMM sse2
+QPEL8OR16_HV1_LOWPASS_OP put
+
+
+
+%macro QPEL8OR16_HV2_LOWPASS_OP 1
+; unused is to match ssse3 and mmxext args
+cglobal %1_h264_qpel8or16_hv2_lowpass_op, 5,5 ; dst, tmp, dstStride, unused, h
+    movsxdifnidn  r2, r2d
+.loop:
+    mova          m0, [r1]
+    mova          m3, [r1+8]
+    mova          m1, [r1+2]
+    mova          m4, [r1+10]
+    paddw         m0, m4
+    paddw         m1, m3
+    paddw         m3, [r1+18]
+    paddw         m4, [r1+16]
+    mova          m2, [r1+4]
+    mova          m5, [r1+12]
+    paddw         m2, [r1+6]
+    paddw         m5, [r1+14]
+    psubw         m0, m1
+    psubw         m3, m4
+    psraw         m0, 2
+    psraw         m3, 2
+    psubw         m0, m1
+    psubw         m3, m4
+    paddsw        m0, m2
+    paddsw        m3, m5
+    psraw         m0, 2
+    psraw         m3, 2
+    paddw         m0, m2
+    paddw         m3, m5
+    psraw         m0, 6
+    psraw         m3, 6
+    packuswb      m0, m3
+    op_%1         m0, [r0], m7
+    add           r1, 48
+    add           r0, r2
+    dec          r4d
+    jne        .loop
+    REP_RET
+%endmacro
+
+INIT_MMX mmxext
+QPEL8OR16_HV2_LOWPASS_OP put
+QPEL8OR16_HV2_LOWPASS_OP avg
+
+%macro QPEL8OR16_HV2_LOWPASS_OP_XMM 1
+cglobal %1_h264_qpel8or16_hv2_lowpass, 5,5,8 ; dst, tmp, dstStride, tmpStride, size
+    movsxdifnidn  r2, r2d
+    movsxdifnidn  r3, r3d
+    cmp          r4d, 16
+    je         .op16
+.loop8:
+    mova          m1, [r1+16]
+    mova          m0, [r1]
+    mova          m2, m1
+    mova          m3, m1
+    mova          m4, m1
+    mova          m5, m1
+    palignr       m5, m0, 10
+    palignr       m4, m0, 8
+    palignr       m3, m0, 6
+    palignr       m2, m0, 4
+    palignr       m1, m0, 2
+    paddw         m0, m5
+    paddw         m1, m4
+    paddw         m2, m3
+    psubw         m0, m1
+    psraw         m0, 2
+    psubw         m0, m1
+    paddw         m0, m2
+    psraw         m0, 2
+    paddw         m0, m2
+    psraw         m0, 6
+    packuswb      m0, m0
+    op_%1h        m0, [r0], m7
+    add           r1, 48
+    add           r0, r2
+    dec          r4d
+    jne       .loop8
+    jmp        .done
+.op16:
+    mova          m4, [r1+32]
+    mova          m5, [r1+16]
+    mova          m7, [r1]
+    mova          m3, m4
+    mova          m2, m4
+    mova          m1, m4
+    mova          m0, m4
+    palignr       m0, m5, 10
+    palignr       m1, m5, 8
+    palignr       m2, m5, 6
+    palignr       m3, m5, 4
+    palignr       m4, m5, 2
+    paddw         m0, m5
+    paddw         m1, m4
+    paddw         m2, m3
+    mova          m6, m5
+    mova          m4, m5
+    mova          m3, m5
+    palignr       m4, m7, 8
+    palignr       m6, m7, 2
+    palignr       m3, m7, 10
+    paddw         m4, m6
+    mova          m6, m5
+    palignr       m5, m7, 6
+    palignr       m6, m7, 4
+    paddw         m3, m7
+    paddw         m5, m6
+    psubw         m0, m1
+    psubw         m3, m4
+    psraw         m0, 2
+    psraw         m3, 2
+    psubw         m0, m1
+    psubw         m3, m4
+    paddw         m0, m2
+    paddw         m3, m5
+    psraw         m0, 2
+    psraw         m3, 2
+    paddw         m0, m2
+    paddw         m3, m5
+    psraw         m0, 6
+    psraw         m3, 6
+    packuswb      m3, m0
+    op_%1         m3, [r0], m7
+    add           r1, 48
+    add           r0, r2
+    dec          r4d
+    jne        .op16
+.done:
+    REP_RET
+%endmacro
+
+INIT_XMM ssse3
+QPEL8OR16_HV2_LOWPASS_OP_XMM put
+QPEL8OR16_HV2_LOWPASS_OP_XMM avg
+
+
+%macro PIXELS4_L2_SHIFT5 1
+cglobal %1_pixels4_l2_shift5,6,6 ; dst, src16, src8, dstStride, src8Stride, h
+    movsxdifnidn  r3, r3d
+    movsxdifnidn  r4, r4d
+    mova          m0, [r1]
+    mova          m1, [r1+24]
+    psraw         m0, 5
+    psraw         m1, 5
+    packuswb      m0, m0
+    packuswb      m1, m1
+    pavgb         m0, [r2]
+    pavgb         m1, [r2+r4]
+    op_%1h        m0, [r0], m4
+    op_%1h        m1, [r0+r3], m5
+    lea           r2, [r2+r4*2]
+    lea           r0, [r0+r3*2]
+    mova          m0, [r1+48]
+    mova          m1, [r1+72]
+    psraw         m0, 5
+    psraw         m1, 5
+    packuswb      m0, m0
+    packuswb      m1, m1
+    pavgb         m0, [r2]
+    pavgb         m1, [r2+r4]
+    op_%1h        m0, [r0], m4
+    op_%1h        m1, [r0+r3], m5
+    RET
+%endmacro
+
+INIT_MMX mmxext
+PIXELS4_L2_SHIFT5 put
+PIXELS4_L2_SHIFT5 avg
+
+
+%macro PIXELS8_L2_SHIFT5 1
+cglobal %1_pixels8_l2_shift5, 6, 6 ; dst, src16, src8, dstStride, src8Stride, h
+    movsxdifnidn  r3, r3d
+    movsxdifnidn  r4, r4d
+.loop:
+    mova          m0, [r1]
+    mova          m1, [r1+8]
+    mova          m2, [r1+48]
+    mova          m3, [r1+48+8]
+    psraw         m0, 5
+    psraw         m1, 5
+    psraw         m2, 5
+    psraw         m3, 5
+    packuswb      m0, m1
+    packuswb      m2, m3
+    pavgb         m0, [r2]
+    pavgb         m2, [r2+r4]
+    op_%1         m0, [r0], m4
+    op_%1         m2, [r0+r3], m5
+    lea           r2, [r2+2*r4]
+    add           r1, 48*2
+    lea           r0, [r0+2*r3]
+    sub          r5d, 2
+    jne        .loop
+    REP_RET
+%endmacro
+
+INIT_MMX mmxext
+PIXELS8_L2_SHIFT5 put
+PIXELS8_L2_SHIFT5 avg
+
+
+%if ARCH_X86_64
+%macro QPEL16_H_LOWPASS_L2_OP 1
+cglobal %1_h264_qpel16_h_lowpass_l2, 5, 6, 16 ; dst, src, src2, dstStride, src2Stride
+    movsxdifnidn  r3, r3d
+    movsxdifnidn  r4, r4d
+    mov          r5d, 16
+    pxor         m15, m15
+    mova         m14, [pw_5]
+    mova         m13, [pw_16]
+.loop:
+    lddqu         m1, [r1+6]
+    lddqu         m7, [r1-2]
+    mova          m0, m1
+    punpckhbw     m1, m15
+    punpcklbw     m0, m15
+    punpcklbw     m7, m15
+    mova          m2, m1
+    mova          m6, m0
+    mova          m3, m1
+    mova          m8, m0
+    mova          m4, m1
+    mova          m9, m0
+    mova         m12, m0
+    mova         m11, m1
+    palignr      m11, m0, 10
+    palignr      m12, m7, 10
+    palignr       m4, m0, 2
+    palignr       m9, m7, 2
+    palignr       m3, m0, 4
+    palignr       m8, m7, 4
+    palignr       m2, m0, 6
+    palignr       m6, m7, 6
+    paddw        m11, m0
+    palignr       m1, m0, 8
+    palignr       m0, m7, 8
+    paddw         m7, m12
+    paddw         m2, m3
+    paddw         m6, m8
+    paddw         m1, m4
+    paddw         m0, m9
+    psllw         m2, 2
+    psllw         m6, 2
+    psubw         m2, m1
+    psubw         m6, m0
+    paddw        m11, m13
+    paddw         m7, m13
+    pmullw        m2, m14
+    pmullw        m6, m14
+    lddqu         m3, [r2]
+    paddw         m2, m11
+    paddw         m6, m7
+    psraw         m2, 5
+    psraw         m6, 5
+    packuswb      m6, m2
+    pavgb         m6, m3
+    op_%1         m6, [r0], m11
+    add           r1, r3
+    add           r0, r3
+    add           r2, r4
+    dec          r5d
+    jg         .loop
+    REP_RET
+%endmacro
+
+INIT_XMM ssse3
+QPEL16_H_LOWPASS_L2_OP put
+QPEL16_H_LOWPASS_L2_OP avg
+%endif
diff --git a/libavcodec/x86/h264_weight.asm b/libavcodec/x86/h264_weight.asm
index 2ad5a8f..4759a06 100644
--- a/libavcodec/x86/h264_weight.asm
+++ b/libavcodec/x86/h264_weight.asm
@@ -21,7 +21,7 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
+%include "libavutil/x86/x86util.asm"
 
 SECTION .text
 
@@ -70,8 +70,8 @@
     packuswb      m0, m1
 %endmacro
 
-INIT_MMX
-cglobal h264_weight_16_mmx2, 6, 6, 0
+INIT_MMX mmxext
+cglobal h264_weight_16, 6, 6, 0
     WEIGHT_SETUP
 .nextrow:
     WEIGHT_OP 0,  4
@@ -83,8 +83,8 @@
     jnz .nextrow
     REP_RET
 
-%macro WEIGHT_FUNC_MM 3
-cglobal h264_weight_%1_%3, 6, 6, %2
+%macro WEIGHT_FUNC_MM 2
+cglobal h264_weight_%1, 6, 6, %2
     WEIGHT_SETUP
 .nextrow:
     WEIGHT_OP 0, mmsize/2
@@ -95,13 +95,13 @@
     REP_RET
 %endmacro
 
-INIT_MMX
-WEIGHT_FUNC_MM  8, 0, mmx2
-INIT_XMM
-WEIGHT_FUNC_MM 16, 8, sse2
+INIT_MMX mmxext
+WEIGHT_FUNC_MM  8, 0
+INIT_XMM sse2
+WEIGHT_FUNC_MM 16, 8
 
-%macro WEIGHT_FUNC_HALF_MM 3
-cglobal h264_weight_%1_%3, 6, 6, %2
+%macro WEIGHT_FUNC_HALF_MM 2
+cglobal h264_weight_%1, 6, 6, %2
     WEIGHT_SETUP
     sar       r2d, 1
     lea        r3, [r1*2]
@@ -120,10 +120,10 @@
     REP_RET
 %endmacro
 
-INIT_MMX
-WEIGHT_FUNC_HALF_MM 4, 0, mmx2
-INIT_XMM
-WEIGHT_FUNC_HALF_MM 8, 8, sse2
+INIT_MMX mmxext
+WEIGHT_FUNC_HALF_MM 4, 0
+INIT_XMM sse2
+WEIGHT_FUNC_HALF_MM 8, 8
 
 %macro BIWEIGHT_SETUP 0
 %if ARCH_X86_64
@@ -135,12 +135,32 @@
     add  off_regd, 1
     or   off_regd, 1
     add        r4, 1
+    cmp        r5, 128
+     jne .normal
+    sar        r5, 1
+    sar        r6, 1
+    sar  off_regd, 1
+    sub        r4, 1
+.normal
+%if cpuflag(ssse3)
+    movd       m4, r5d
+    movd       m0, r6d
+%else
     movd       m3, r5d
     movd       m4, r6d
+%endif
     movd       m5, off_regd
     movd       m6, r4d
     pslld      m5, m6
     psrld      m5, 1
+%if cpuflag(ssse3)
+    punpcklbw  m4, m0
+    pshuflw    m4, m4, 0
+    pshuflw    m5, m5, 0
+    punpcklqdq m4, m4
+    punpcklqdq m5, m5
+
+%else
 %if mmsize == 16
     pshuflw    m3, m3, 0
     pshuflw    m4, m4, 0
@@ -154,6 +174,7 @@
     pshufw     m5, m5, 0
 %endif
     pxor       m7, m7
+%endif
 %endmacro
 
 %macro BIWEIGHT_STEPA 3
@@ -174,8 +195,8 @@
     packuswb   m0, m1
 %endmacro
 
-INIT_MMX
-cglobal h264_biweight_16_mmx2, 7, 8, 0
+INIT_MMX mmxext
+cglobal h264_biweight_16, 7, 8, 0
     BIWEIGHT_SETUP
     movifnidn r3d, r3m
 .nextrow:
@@ -193,8 +214,8 @@
     jnz .nextrow
     REP_RET
 
-%macro BIWEIGHT_FUNC_MM 3
-cglobal h264_biweight_%1_%3, 7, 8, %2
+%macro BIWEIGHT_FUNC_MM 2
+cglobal h264_biweight_%1, 7, 8, %2
     BIWEIGHT_SETUP
     movifnidn r3d, r3m
 .nextrow:
@@ -209,13 +230,13 @@
     REP_RET
 %endmacro
 
-INIT_MMX
-BIWEIGHT_FUNC_MM  8, 0, mmx2
-INIT_XMM
-BIWEIGHT_FUNC_MM 16, 8, sse2
+INIT_MMX mmxext
+BIWEIGHT_FUNC_MM  8, 0
+INIT_XMM sse2
+BIWEIGHT_FUNC_MM 16, 8
 
-%macro BIWEIGHT_FUNC_HALF_MM 3
-cglobal h264_biweight_%1_%3, 7, 8, %2
+%macro BIWEIGHT_FUNC_HALF_MM 2
+cglobal h264_biweight_%1, 7, 8, %2
     BIWEIGHT_SETUP
     movifnidn r3d, r3m
     sar        r3, 1
@@ -238,40 +259,10 @@
     REP_RET
 %endmacro
 
-INIT_MMX
-BIWEIGHT_FUNC_HALF_MM 4, 0, mmx2
-INIT_XMM
-BIWEIGHT_FUNC_HALF_MM 8, 8, sse2
-
-%macro BIWEIGHT_SSSE3_SETUP 0
-%if ARCH_X86_64
-%define off_regd r7d
-%else
-%define off_regd r3d
-%endif
-    mov  off_regd, r7m
-    add  off_regd, 1
-    or   off_regd, 1
-    add        r4, 1
-    cmp        r5, 128
-     jne .normal
-    sar        r5, 1
-    sar        r6, 1
-    sar  off_regd, 1
-    sub        r4, 1
-.normal
-    movd       m4, r5d
-    movd       m0, r6d
-    movd       m5, off_regd
-    movd       m6, r4d
-    pslld      m5, m6
-    psrld      m5, 1
-    punpcklbw  m4, m0
-    pshuflw    m4, m4, 0
-    pshuflw    m5, m5, 0
-    punpcklqdq m4, m4
-    punpcklqdq m5, m5
-%endmacro
+INIT_MMX mmxext
+BIWEIGHT_FUNC_HALF_MM 4, 0
+INIT_XMM sse2
+BIWEIGHT_FUNC_HALF_MM 8, 8
 
 %macro BIWEIGHT_SSSE3_OP 0
     pmaddubsw  m0, m4
@@ -283,9 +274,9 @@
     packuswb   m0, m2
 %endmacro
 
-INIT_XMM
-cglobal h264_biweight_16_ssse3, 7, 8, 8
-    BIWEIGHT_SSSE3_SETUP
+INIT_XMM ssse3
+cglobal h264_biweight_16, 7, 8, 8
+    BIWEIGHT_SETUP
     movifnidn r3d, r3m
 
 .nextrow:
@@ -302,9 +293,9 @@
     jnz .nextrow
     REP_RET
 
-INIT_XMM
-cglobal h264_biweight_8_ssse3, 7, 8, 8
-    BIWEIGHT_SSSE3_SETUP
+INIT_XMM ssse3
+cglobal h264_biweight_8, 7, 8, 8
+    BIWEIGHT_SETUP
     movifnidn r3d, r3m
     sar        r3, 1
     lea        r4, [r2*2]
diff --git a/libavcodec/x86/h264_weight_10bit.asm b/libavcodec/x86/h264_weight_10bit.asm
index 24386f8..3b09e42 100644
--- a/libavcodec/x86/h264_weight_10bit.asm
+++ b/libavcodec/x86/h264_weight_10bit.asm
@@ -22,8 +22,7 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "x86inc.asm"
-%include "x86util.asm"
+%include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA 32
 
@@ -49,7 +48,7 @@
     movifnidn r5d, r5m
 %endmacro
 
-%macro WEIGHT_SETUP 1
+%macro WEIGHT_SETUP 0
     mova       m0, [pw_1]
     movd       m2, r3m
     pslld      m0, m2       ; 1<<log2_denom
@@ -60,19 +59,19 @@
     pshufd     m3, m3, 0
     mova       m4, [pw_pixel_max]
     paddw      m2, [sq_1]   ; log2_denom+1
-%ifnidn %1, sse4
+%if notcpuflag(sse4)
     pxor       m7, m7
 %endif
 %endmacro
 
-%macro WEIGHT_OP 2-3
-%if %0==2
-    mova        m5, [r0+%2]
+%macro WEIGHT_OP 1-2
+%if %0==1
+    mova        m5, [r0+%1]
     punpckhwd   m6, m5, m0
     punpcklwd   m5, m0
 %else
-    movq        m5, [r0+%2]
-    movq        m6, [r0+%3]
+    movq        m5, [r0+%1]
+    movq        m6, [r0+%2]
     punpcklwd   m5, m0
     punpcklwd   m6, m0
 %endif
@@ -80,7 +79,7 @@
     pmaddwd     m6, m3
     psrad       m5, m2
     psrad       m6, m2
-%ifidn %1, sse4
+%if cpuflag(sse4)
     packusdw    m5, m6
     pminsw      m5, m4
 %else
@@ -89,14 +88,14 @@
 %endif
 %endmacro
 
-%macro WEIGHT_FUNC_DBL 1
-cglobal h264_weight_16_10_%1
+%macro WEIGHT_FUNC_DBL 0
+cglobal h264_weight_16_10
     WEIGHT_PROLOGUE
-    WEIGHT_SETUP %1
+    WEIGHT_SETUP
 .nextrow:
-    WEIGHT_OP %1,  0
+    WEIGHT_OP  0
     mova [r0   ], m5
-    WEIGHT_OP %1, 16
+    WEIGHT_OP 16
     mova [r0+16], m5
     add       r0, r1
     dec       r2d
@@ -104,17 +103,18 @@
     REP_RET
 %endmacro
 
-INIT_XMM
-WEIGHT_FUNC_DBL sse2
-WEIGHT_FUNC_DBL sse4
+INIT_XMM sse2
+WEIGHT_FUNC_DBL
+INIT_XMM sse4
+WEIGHT_FUNC_DBL
 
 
-%macro WEIGHT_FUNC_MM 1
-cglobal h264_weight_8_10_%1
+%macro WEIGHT_FUNC_MM 0
+cglobal h264_weight_8_10
     WEIGHT_PROLOGUE
-    WEIGHT_SETUP %1
+    WEIGHT_SETUP
 .nextrow:
-    WEIGHT_OP  %1, 0
+    WEIGHT_OP   0
     mova     [r0], m5
     add        r0, r1
     dec        r2d
@@ -122,19 +122,20 @@
     REP_RET
 %endmacro
 
-INIT_XMM
-WEIGHT_FUNC_MM sse2
-WEIGHT_FUNC_MM sse4
+INIT_XMM sse2
+WEIGHT_FUNC_MM
+INIT_XMM sse4
+WEIGHT_FUNC_MM
 
 
-%macro WEIGHT_FUNC_HALF_MM 1
-cglobal h264_weight_4_10_%1
+%macro WEIGHT_FUNC_HALF_MM 0
+cglobal h264_weight_4_10
     WEIGHT_PROLOGUE
     sar         r2d, 1
-    WEIGHT_SETUP %1
+    WEIGHT_SETUP
     lea         r3, [r1*2]
 .nextrow:
-    WEIGHT_OP   %1, 0, r1
+    WEIGHT_OP    0, r1
     movh      [r0], m5
     movhps [r0+r1], m5
     add         r0, r3
@@ -143,9 +144,10 @@
     REP_RET
 %endmacro
 
-INIT_XMM
-WEIGHT_FUNC_HALF_MM sse2
-WEIGHT_FUNC_HALF_MM sse4
+INIT_XMM sse2
+WEIGHT_FUNC_HALF_MM
+INIT_XMM sse4
+WEIGHT_FUNC_HALF_MM
 
 
 ;-----------------------------------------------------------------------------
@@ -169,7 +171,7 @@
     movifnidn t0d, r7m
 %endmacro
 
-%macro BIWEIGHT_SETUP 1
+%macro BIWEIGHT_SETUP 0
     lea        t0, [t0*4+1] ; (offset<<2)+1
     or         t0, 1
     shl        r6, 16
@@ -183,23 +185,23 @@
     pshufd     m5, m5, 0
     mova       m3, [pw_pixel_max]
     movifnidn r3d, r3m
-%ifnidn %1, sse4
+%if notcpuflag(sse4)
     pxor       m7, m7
 %endif
 %endmacro
 
-%macro BIWEIGHT 2-3
-%if %0==2
-    mova       m0, [r0+%2]
-    mova       m1, [r1+%2]
+%macro BIWEIGHT 1-2
+%if %0==1
+    mova       m0, [r0+%1]
+    mova       m1, [r1+%1]
     punpckhwd  m2, m0, m1
     punpcklwd  m0, m1
 %else
-    movq       m0, [r0+%2]
-    movq       m1, [r1+%2]
+    movq       m0, [r0+%1]
+    movq       m1, [r1+%1]
     punpcklwd  m0, m1
-    movq       m2, [r0+%3]
-    movq       m1, [r1+%3]
+    movq       m2, [r0+%2]
+    movq       m1, [r1+%2]
     punpcklwd  m2, m1
 %endif
     pmaddwd    m0, m4
@@ -208,7 +210,7 @@
     paddd      m2, m5
     psrad      m0, m6
     psrad      m2, m6
-%ifidn %1, sse4
+%if cpuflag(sse4)
     packusdw   m0, m2
     pminsw     m0, m3
 %else
@@ -217,14 +219,14 @@
 %endif
 %endmacro
 
-%macro BIWEIGHT_FUNC_DBL 1
-cglobal h264_biweight_16_10_%1
+%macro BIWEIGHT_FUNC_DBL 0
+cglobal h264_biweight_16_10
     BIWEIGHT_PROLOGUE
-    BIWEIGHT_SETUP %1
+    BIWEIGHT_SETUP
 .nextrow:
-    BIWEIGHT  %1,  0
+    BIWEIGHT   0
     mova [r0   ], m0
-    BIWEIGHT  %1, 16
+    BIWEIGHT  16
     mova [r0+16], m0
     add       r0, r2
     add       r1, r2
@@ -233,16 +235,17 @@
     REP_RET
 %endmacro
 
-INIT_XMM
-BIWEIGHT_FUNC_DBL sse2
-BIWEIGHT_FUNC_DBL sse4
+INIT_XMM sse2
+BIWEIGHT_FUNC_DBL
+INIT_XMM sse4
+BIWEIGHT_FUNC_DBL
 
-%macro BIWEIGHT_FUNC 1
-cglobal h264_biweight_8_10_%1
+%macro BIWEIGHT_FUNC 0
+cglobal h264_biweight_8_10
     BIWEIGHT_PROLOGUE
-    BIWEIGHT_SETUP %1
+    BIWEIGHT_SETUP
 .nextrow:
-    BIWEIGHT %1, 0
+    BIWEIGHT  0
     mova   [r0], m0
     add      r0, r2
     add      r1, r2
@@ -251,18 +254,19 @@
     REP_RET
 %endmacro
 
-INIT_XMM
-BIWEIGHT_FUNC sse2
-BIWEIGHT_FUNC sse4
+INIT_XMM sse2
+BIWEIGHT_FUNC
+INIT_XMM sse4
+BIWEIGHT_FUNC
 
-%macro BIWEIGHT_FUNC_HALF 1
-cglobal h264_biweight_4_10_%1
+%macro BIWEIGHT_FUNC_HALF 0
+cglobal h264_biweight_4_10
     BIWEIGHT_PROLOGUE
-    BIWEIGHT_SETUP %1
+    BIWEIGHT_SETUP
     sar        r3d, 1
     lea        r4, [r2*2]
 .nextrow:
-    BIWEIGHT    %1, 0, r2
+    BIWEIGHT     0, r2
     movh   [r0   ], m0
     movhps [r0+r2], m0
     add         r0, r4
@@ -272,6 +276,7 @@
     REP_RET
 %endmacro
 
-INIT_XMM
-BIWEIGHT_FUNC_HALF sse2
-BIWEIGHT_FUNC_HALF sse4
+INIT_XMM sse2
+BIWEIGHT_FUNC_HALF
+INIT_XMM sse4
+BIWEIGHT_FUNC_HALF
diff --git a/libavcodec/x86/h264dsp_init.c b/libavcodec/x86/h264dsp_init.c
index f84e3e8..65d300f 100644
--- a/libavcodec/x86/h264dsp_init.c
+++ b/libavcodec/x86/h264dsp_init.c
@@ -33,9 +33,9 @@
 
 IDCT_ADD_FUNC(, 8, mmx)
 IDCT_ADD_FUNC(, 10, sse2)
-IDCT_ADD_FUNC(_dc, 8, mmx2)
-IDCT_ADD_FUNC(_dc, 10, mmx2)
-IDCT_ADD_FUNC(8_dc, 8, mmx2)
+IDCT_ADD_FUNC(_dc, 8, mmxext)
+IDCT_ADD_FUNC(_dc, 10, mmxext)
+IDCT_ADD_FUNC(8_dc, 8, mmxext)
 IDCT_ADD_FUNC(8_dc, 10, sse2)
 IDCT_ADD_FUNC(8, 8, mmx)
 IDCT_ADD_FUNC(8, 8, sse2)
@@ -51,16 +51,16 @@
      DCTELEM *block, int stride, const uint8_t nnzc[6 * 8]);
 
 IDCT_ADD_REP_FUNC(8, 4, 8, mmx)
-IDCT_ADD_REP_FUNC(8, 4, 8, mmx2)
+IDCT_ADD_REP_FUNC(8, 4, 8, mmxext)
 IDCT_ADD_REP_FUNC(8, 4, 8, sse2)
 IDCT_ADD_REP_FUNC(8, 4, 10, sse2)
 IDCT_ADD_REP_FUNC(8, 4, 10, avx)
 IDCT_ADD_REP_FUNC(, 16, 8, mmx)
-IDCT_ADD_REP_FUNC(, 16, 8, mmx2)
+IDCT_ADD_REP_FUNC(, 16, 8, mmxext)
 IDCT_ADD_REP_FUNC(, 16, 8, sse2)
 IDCT_ADD_REP_FUNC(, 16, 10, sse2)
 IDCT_ADD_REP_FUNC(, 16intra, 8, mmx)
-IDCT_ADD_REP_FUNC(, 16intra, 8, mmx2)
+IDCT_ADD_REP_FUNC(, 16intra, 8, mmxext)
 IDCT_ADD_REP_FUNC(, 16intra, 8, sse2)
 IDCT_ADD_REP_FUNC(, 16intra, 10, sse2)
 IDCT_ADD_REP_FUNC(, 16, 10, avx)
@@ -73,7 +73,7 @@
      DCTELEM *block, int stride, const uint8_t nnzc[6 * 8]);
 
 IDCT_ADD_REP_FUNC2(, 8, 8, mmx)
-IDCT_ADD_REP_FUNC2(, 8, 8, mmx2)
+IDCT_ADD_REP_FUNC2(, 8, 8, mmxext)
 IDCT_ADD_REP_FUNC2(, 8, 8, sse2)
 IDCT_ADD_REP_FUNC2(, 8, 10, sse2)
 IDCT_ADD_REP_FUNC2(, 8, 10, avx)
@@ -84,10 +84,11 @@
 /***********************************/
 /* deblocking */
 
-void ff_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);
+void ff_h264_loop_filter_strength_mmxext(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);
 
 #define LF_FUNC(DIR, TYPE, DEPTH, OPT)                                        \
 void ff_deblock_ ## DIR ## _ ## TYPE ## _ ## DEPTH ## _ ## OPT(uint8_t *pix,  \
@@ -102,12 +103,12 @@
                                                                int beta);
 
 #define LF_FUNCS(type, depth)                   \
-LF_FUNC(h,  chroma,       depth, mmx2)          \
-LF_IFUNC(h, chroma_intra, depth, mmx2)          \
-LF_FUNC(v,  chroma,       depth, mmx2)          \
-LF_IFUNC(v, chroma_intra, depth, mmx2)          \
-LF_FUNC(h,  luma,         depth, mmx2)          \
-LF_IFUNC(h, luma_intra,   depth, mmx2)          \
+LF_FUNC(h,  chroma,       depth, mmxext)        \
+LF_IFUNC(h, chroma_intra, depth, mmxext)        \
+LF_FUNC(v,  chroma,       depth, mmxext)        \
+LF_IFUNC(v, chroma_intra, depth, mmxext)        \
+LF_FUNC(h,  luma,         depth, mmxext)        \
+LF_IFUNC(h, luma_intra,   depth, mmxext)        \
 LF_FUNC(h,  luma,         depth, sse2)          \
 LF_IFUNC(h, luma_intra,   depth, sse2)          \
 LF_FUNC(v,  luma,         depth, sse2)          \
@@ -128,28 +129,27 @@
 LF_FUNCS(uint8_t,   8)
 LF_FUNCS(uint16_t, 10)
 
-#if ARCH_X86_32 && HAVE_YASM
-LF_FUNC(v8, luma, 8, mmx2)
-static void ff_deblock_v_luma_8_mmx2(uint8_t *pix, int stride, int alpha,
-                                     int beta, int8_t *tc0)
+#if ARCH_X86_32 && HAVE_MMXEXT_EXTERNAL
+LF_FUNC(v8, luma, 8, mmxext)
+static void ff_deblock_v_luma_8_mmxext(uint8_t *pix, int stride, int alpha,
+                                       int beta, int8_t *tc0)
 {
     if ((tc0[0] & tc0[1]) >= 0)
-        ff_deblock_v8_luma_8_mmx2(pix + 0, stride, alpha, beta, tc0);
+        ff_deblock_v8_luma_8_mmxext(pix + 0, stride, alpha, beta, tc0);
     if ((tc0[2] & tc0[3]) >= 0)
-        ff_deblock_v8_luma_8_mmx2(pix + 8, stride, alpha, beta, tc0 + 2);
+        ff_deblock_v8_luma_8_mmxext(pix + 8, stride, alpha, beta, tc0 + 2);
 }
-
-LF_IFUNC(v8, luma_intra, 8, mmx2)
-static void ff_deblock_v_luma_intra_8_mmx2(uint8_t *pix, int stride,
-                                           int alpha, int beta)
+LF_IFUNC(v8, luma_intra, 8, mmxext)
+static void ff_deblock_v_luma_intra_8_mmxext(uint8_t *pix, int stride,
+                                             int alpha, int beta)
 {
-    ff_deblock_v8_luma_intra_8_mmx2(pix + 0, stride, alpha, beta);
-    ff_deblock_v8_luma_intra_8_mmx2(pix + 8, stride, alpha, beta);
+    ff_deblock_v8_luma_intra_8_mmxext(pix + 0, stride, alpha, beta);
+    ff_deblock_v8_luma_intra_8_mmxext(pix + 8, stride, alpha, beta);
 }
-#endif /* ARCH_X86_32 */
+#endif /* ARCH_X86_32 && HAVE_MMXEXT_EXTERNAL */
 
-LF_FUNC(v,  luma,       10, mmx2)
-LF_IFUNC(v, luma_intra, 10, mmx2)
+LF_FUNC(v,  luma,       10, mmxext)
+LF_IFUNC(v, luma_intra, 10, mmxext)
 
 /***********************************/
 /* weighted prediction */
@@ -166,8 +166,8 @@
                                         int weights, int offset);
 
 #define H264_BIWEIGHT_MMX(W)                    \
-    H264_WEIGHT(W, mmx2)                        \
-    H264_BIWEIGHT(W, mmx2)
+    H264_WEIGHT(W, mmxext)                      \
+    H264_BIWEIGHT(W, mmxext)
 
 #define H264_BIWEIGHT_MMX_SSE(W)                \
     H264_BIWEIGHT_MMX(W)                        \
@@ -214,7 +214,7 @@
     int mm_flags = av_get_cpu_flags();
 
     if (chroma_format_idc == 1 && EXTERNAL_MMXEXT(mm_flags))
-        c->h264_loop_filter_strength = ff_h264_loop_filter_strength_mmx2;
+        c->h264_loop_filter_strength = ff_h264_loop_filter_strength_mmxext;
 
     if (bit_depth == 8) {
         if (EXTERNAL_MMX(mm_flags)) {
@@ -232,33 +232,33 @@
                 c->h264_luma_dc_dequant_idct = ff_h264_luma_dc_dequant_idct_mmx;
 
             if (EXTERNAL_MMXEXT(mm_flags)) {
-                c->h264_idct_dc_add  = ff_h264_idct_dc_add_8_mmx2;
-                c->h264_idct8_dc_add = ff_h264_idct8_dc_add_8_mmx2;
-                c->h264_idct_add16   = ff_h264_idct_add16_8_mmx2;
-                c->h264_idct8_add4   = ff_h264_idct8_add4_8_mmx2;
+                c->h264_idct_dc_add  = ff_h264_idct_dc_add_8_mmxext;
+                c->h264_idct8_dc_add = ff_h264_idct8_dc_add_8_mmxext;
+                c->h264_idct_add16   = ff_h264_idct_add16_8_mmxext;
+                c->h264_idct8_add4   = ff_h264_idct8_add4_8_mmxext;
                 if (chroma_format_idc == 1)
-                    c->h264_idct_add8 = ff_h264_idct_add8_8_mmx2;
-                c->h264_idct_add16intra = ff_h264_idct_add16intra_8_mmx2;
+                    c->h264_idct_add8 = ff_h264_idct_add8_8_mmxext;
+                c->h264_idct_add16intra = ff_h264_idct_add16intra_8_mmxext;
 
-                c->h264_v_loop_filter_chroma       = ff_deblock_v_chroma_8_mmx2;
-                c->h264_v_loop_filter_chroma_intra = ff_deblock_v_chroma_intra_8_mmx2;
+                c->h264_v_loop_filter_chroma       = ff_deblock_v_chroma_8_mmxext;
+                c->h264_v_loop_filter_chroma_intra = ff_deblock_v_chroma_intra_8_mmxext;
                 if (chroma_format_idc == 1) {
-                    c->h264_h_loop_filter_chroma       = ff_deblock_h_chroma_8_mmx2;
-                    c->h264_h_loop_filter_chroma_intra = ff_deblock_h_chroma_intra_8_mmx2;
+                    c->h264_h_loop_filter_chroma       = ff_deblock_h_chroma_8_mmxext;
+                    c->h264_h_loop_filter_chroma_intra = ff_deblock_h_chroma_intra_8_mmxext;
                 }
-#if ARCH_X86_32
-                c->h264_v_loop_filter_luma       = ff_deblock_v_luma_8_mmx2;
-                c->h264_h_loop_filter_luma       = ff_deblock_h_luma_8_mmx2;
-                c->h264_v_loop_filter_luma_intra = ff_deblock_v_luma_intra_8_mmx2;
-                c->h264_h_loop_filter_luma_intra = ff_deblock_h_luma_intra_8_mmx2;
-#endif /* ARCH_X86_32 */
-                c->weight_h264_pixels_tab[0] = ff_h264_weight_16_mmx2;
-                c->weight_h264_pixels_tab[1] = ff_h264_weight_8_mmx2;
-                c->weight_h264_pixels_tab[2] = ff_h264_weight_4_mmx2;
+#if ARCH_X86_32 && HAVE_MMXEXT_EXTERNAL
+                c->h264_v_loop_filter_luma       = ff_deblock_v_luma_8_mmxext;
+                c->h264_h_loop_filter_luma       = ff_deblock_h_luma_8_mmxext;
+                c->h264_v_loop_filter_luma_intra = ff_deblock_v_luma_intra_8_mmxext;
+                c->h264_h_loop_filter_luma_intra = ff_deblock_h_luma_intra_8_mmxext;
+#endif /* ARCH_X86_32 && HAVE_MMXEXT_EXTERNAL */
+                c->weight_h264_pixels_tab[0] = ff_h264_weight_16_mmxext;
+                c->weight_h264_pixels_tab[1] = ff_h264_weight_8_mmxext;
+                c->weight_h264_pixels_tab[2] = ff_h264_weight_4_mmxext;
 
-                c->biweight_h264_pixels_tab[0] = ff_h264_biweight_16_mmx2;
-                c->biweight_h264_pixels_tab[1] = ff_h264_biweight_8_mmx2;
-                c->biweight_h264_pixels_tab[2] = ff_h264_biweight_4_mmx2;
+                c->biweight_h264_pixels_tab[0] = ff_h264_biweight_16_mmxext;
+                c->biweight_h264_pixels_tab[1] = ff_h264_biweight_8_mmxext;
+                c->biweight_h264_pixels_tab[2] = ff_h264_biweight_4_mmxext;
 
                 if (EXTERNAL_SSE2(mm_flags)) {
                     c->h264_idct8_add  = ff_h264_idct8_add_8_sse2;
@@ -297,14 +297,14 @@
         if (EXTERNAL_MMX(mm_flags)) {
             if (EXTERNAL_MMXEXT(mm_flags)) {
 #if ARCH_X86_32
-                c->h264_v_loop_filter_chroma       = ff_deblock_v_chroma_10_mmx2;
-                c->h264_v_loop_filter_chroma_intra = ff_deblock_v_chroma_intra_10_mmx2;
-                c->h264_v_loop_filter_luma         = ff_deblock_v_luma_10_mmx2;
-                c->h264_h_loop_filter_luma         = ff_deblock_h_luma_10_mmx2;
-                c->h264_v_loop_filter_luma_intra   = ff_deblock_v_luma_intra_10_mmx2;
-                c->h264_h_loop_filter_luma_intra   = ff_deblock_h_luma_intra_10_mmx2;
+                c->h264_v_loop_filter_chroma       = ff_deblock_v_chroma_10_mmxext;
+                c->h264_v_loop_filter_chroma_intra = ff_deblock_v_chroma_intra_10_mmxext;
+                c->h264_v_loop_filter_luma         = ff_deblock_v_luma_10_mmxext;
+                c->h264_h_loop_filter_luma         = ff_deblock_h_luma_10_mmxext;
+                c->h264_v_loop_filter_luma_intra   = ff_deblock_v_luma_intra_10_mmxext;
+                c->h264_h_loop_filter_luma_intra   = ff_deblock_h_luma_intra_10_mmxext;
 #endif /* ARCH_X86_32 */
-                c->h264_idct_dc_add = ff_h264_idct_dc_add_10_mmx2;
+                c->h264_idct_dc_add = ff_h264_idct_dc_add_10_mmxext;
                 if (EXTERNAL_SSE2(mm_flags)) {
                     c->h264_idct_add     = ff_h264_idct_add_10_sse2;
                     c->h264_idct8_dc_add = ff_h264_idct8_dc_add_10_sse2;
diff --git a/libavcodec/x86/idct_mmx_xvid.c b/libavcodec/x86/idct_mmx_xvid.c
index 2465cdf..b62865e 100644
--- a/libavcodec/x86/idct_mmx_xvid.c
+++ b/libavcodec/x86/idct_mmx_xvid.c
@@ -512,7 +512,8 @@
 //-----------------------------------------------------------------------------
 
 
-void ff_idct_xvid_mmx2(short *block){
+void ff_idct_xvid_mmxext(short *block)
+{
 __asm__ volatile(
             //# Process each row
     DCT_8_INV_ROW_XMM(0*16(%0), 0*16(%0), 64*0(%2), 8*0(%1))
@@ -542,15 +543,15 @@
     ff_add_pixels_clamped_mmx(block, dest, line_size);
 }
 
-void ff_idct_xvid_mmx2_put(uint8_t *dest, int line_size, DCTELEM *block)
+void ff_idct_xvid_mmxext_put(uint8_t *dest, int line_size, DCTELEM *block)
 {
-    ff_idct_xvid_mmx2(block);
+    ff_idct_xvid_mmxext(block);
     ff_put_pixels_clamped_mmx(block, dest, line_size);
 }
 
-void ff_idct_xvid_mmx2_add(uint8_t *dest, int line_size, DCTELEM *block)
+void ff_idct_xvid_mmxext_add(uint8_t *dest, int line_size, DCTELEM *block)
 {
-    ff_idct_xvid_mmx2(block);
+    ff_idct_xvid_mmxext(block);
     ff_add_pixels_clamped_mmx(block, dest, line_size);
 }
 
diff --git a/libavcodec/x86/idct_xvid.h b/libavcodec/x86/idct_xvid.h
index 6000654..a584fba 100644
--- a/libavcodec/x86/idct_xvid.h
+++ b/libavcodec/x86/idct_xvid.h
@@ -34,9 +34,9 @@
 void ff_idct_xvid_mmx_put(uint8_t *dest, int line_size, DCTELEM *block);
 void ff_idct_xvid_mmx_add(uint8_t *dest, int line_size, DCTELEM *block);
 
-void ff_idct_xvid_mmx2(short *block);
-void ff_idct_xvid_mmx2_put(uint8_t *dest, int line_size, DCTELEM *block);
-void ff_idct_xvid_mmx2_add(uint8_t *dest, int line_size, DCTELEM *block);
+void ff_idct_xvid_mmxext(short *block);
+void ff_idct_xvid_mmxext_put(uint8_t *dest, int line_size, DCTELEM *block);
+void ff_idct_xvid_mmxext_add(uint8_t *dest, int line_size, DCTELEM *block);
 
 void ff_idct_xvid_sse2(short *block);
 void ff_idct_xvid_sse2_put(uint8_t *dest, int line_size, short *block);
diff --git a/libavcodec/x86/imdct36.asm b/libavcodec/x86/imdct36.asm
index 50b6902..d311fbe 100644
--- a/libavcodec/x86/imdct36.asm
+++ b/libavcodec/x86/imdct36.asm
@@ -19,7 +19,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
diff --git a/libavcodec/x86/mlpdsp.c b/libavcodec/x86/mlpdsp.c
index f7c0f21..de28e22 100644
--- a/libavcodec/x86/mlpdsp.c
+++ b/libavcodec/x86/mlpdsp.c
@@ -20,7 +20,7 @@
  */
 
 #include "libavutil/x86/asm.h"
-#include "libavcodec/dsputil.h"
+#include "libavcodec/mlpdsp.h"
 #include "libavcodec/mlp.h"
 
 #if HAVE_7REGS && HAVE_INLINE_ASM
@@ -173,7 +173,7 @@
 
 #endif /* HAVE_7REGS && HAVE_INLINE_ASM */
 
-void ff_mlp_init_x86(DSPContext* c, AVCodecContext *avctx)
+void ff_mlpdsp_init_x86(MLPDSPContext *c)
 {
 #if HAVE_7REGS && HAVE_INLINE_ASM
     c->mlp_filter_channel = mlp_filter_channel_x86;
diff --git a/libavcodec/x86/motion_est.c b/libavcodec/x86/motion_est.c
index 3ee68c2..e054a0d 100644
--- a/libavcodec/x86/motion_est.c
+++ b/libavcodec/x86/motion_est.c
@@ -22,6 +22,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/avassert.h"
 #include "libavutil/mem.h"
 #include "libavutil/x86/asm.h"
 #include "libavcodec/dsputil.h"
@@ -39,7 +40,7 @@
 
 static inline void sad8_1_mmx(uint8_t *blk1, uint8_t *blk2, int stride, int h)
 {
-    x86_reg len= -(stride*h);
+    x86_reg len= -(x86_reg)stride*h;
     __asm__ volatile(
         ".p2align 4                     \n\t"
         "1:                             \n\t"
@@ -73,7 +74,8 @@
     );
 }
 
-static inline void sad8_1_mmx2(uint8_t *blk1, uint8_t *blk2, int stride, int h)
+static inline void sad8_1_mmxext(uint8_t *blk1, uint8_t *blk2,
+                                 int stride, int h)
 {
     __asm__ volatile(
         ".p2align 4                     \n\t"
@@ -119,7 +121,8 @@
     return ret;
 }
 
-static inline void sad8_x2a_mmx2(uint8_t *blk1, uint8_t *blk2, int stride, int h)
+static inline void sad8_x2a_mmxext(uint8_t *blk1, uint8_t *blk2,
+                                   int stride, int h)
 {
     __asm__ volatile(
         ".p2align 4                     \n\t"
@@ -141,7 +144,8 @@
     );
 }
 
-static inline void sad8_y2a_mmx2(uint8_t *blk1, uint8_t *blk2, int stride, int h)
+static inline void sad8_y2a_mmxext(uint8_t *blk1, uint8_t *blk2,
+                                   int stride, int h)
 {
     __asm__ volatile(
         "movq (%1), %%mm0               \n\t"
@@ -166,7 +170,8 @@
     );
 }
 
-static inline void sad8_4_mmx2(uint8_t *blk1, uint8_t *blk2, int stride, int h)
+static inline void sad8_4_mmxext(uint8_t *blk1, uint8_t *blk2,
+                                 int stride, int h)
 {
     __asm__ volatile(
         "movq "MANGLE(bone)", %%mm5     \n\t"
@@ -198,7 +203,7 @@
 
 static inline void sad8_2_mmx(uint8_t *blk1a, uint8_t *blk1b, uint8_t *blk2, int stride, int h)
 {
-    x86_reg len= -(stride*h);
+    x86_reg len= -(x86_reg)stride*h;
     __asm__ volatile(
         ".p2align 4                     \n\t"
         "1:                             \n\t"
@@ -236,7 +241,7 @@
 
 static inline void sad8_4_mmx(uint8_t *blk1, uint8_t *blk2, int stride, int h)
 {
-    x86_reg len= -(stride*h);
+    x86_reg len= -(x86_reg)stride*h;
     __asm__ volatile(
         "movq (%1, %%"REG_a"), %%mm0    \n\t"
         "movq 1(%1, %%"REG_a"), %%mm2   \n\t"
@@ -303,7 +308,7 @@
     return ret&0xFFFF;
 }
 
-static inline int sum_mmx2(void)
+static inline int sum_mmxext(void)
 {
     int ret;
     __asm__ volatile(
@@ -326,7 +331,7 @@
 #define PIX_SAD(suf)\
 static int sad8_ ## suf(void *v, uint8_t *blk2, uint8_t *blk1, int stride, int h)\
 {\
-    assert(h==8);\
+    av_assert2(h==8);\
     __asm__ volatile("pxor %%mm7, %%mm7     \n\t"\
                  "pxor %%mm6, %%mm6     \n\t":);\
 \
@@ -336,7 +341,7 @@
 }\
 static int sad8_x2_ ## suf(void *v, uint8_t *blk2, uint8_t *blk1, int stride, int h)\
 {\
-    assert(h==8);\
+    av_assert2(h==8);\
     __asm__ volatile("pxor %%mm7, %%mm7     \n\t"\
                  "pxor %%mm6, %%mm6     \n\t"\
                  "movq %0, %%mm5        \n\t"\
@@ -350,7 +355,7 @@
 \
 static int sad8_y2_ ## suf(void *v, uint8_t *blk2, uint8_t *blk1, int stride, int h)\
 {\
-    assert(h==8);\
+    av_assert2(h==8);\
     __asm__ volatile("pxor %%mm7, %%mm7     \n\t"\
                  "pxor %%mm6, %%mm6     \n\t"\
                  "movq %0, %%mm5        \n\t"\
@@ -364,7 +369,7 @@
 \
 static int sad8_xy2_ ## suf(void *v, uint8_t *blk2, uint8_t *blk1, int stride, int h)\
 {\
-    assert(h==8);\
+    av_assert2(h==8);\
     __asm__ volatile("pxor %%mm7, %%mm7     \n\t"\
                  "pxor %%mm6, %%mm6     \n\t"\
                  ::);\
@@ -423,7 +428,7 @@
 }\
 
 PIX_SAD(mmx)
-PIX_SAD(mmx2)
+PIX_SAD(mmxext)
 
 #endif /* HAVE_INLINE_ASM */
 
@@ -446,19 +451,19 @@
         c->sad[1]= sad8_mmx;
     }
     if (mm_flags & AV_CPU_FLAG_MMXEXT) {
-        c->pix_abs[0][0] = sad16_mmx2;
-        c->pix_abs[1][0] = sad8_mmx2;
+        c->pix_abs[0][0] = sad16_mmxext;
+        c->pix_abs[1][0] = sad8_mmxext;
 
-        c->sad[0]= sad16_mmx2;
-        c->sad[1]= sad8_mmx2;
+        c->sad[0]        = sad16_mmxext;
+        c->sad[1]        = sad8_mmxext;
 
         if(!(avctx->flags & CODEC_FLAG_BITEXACT)){
-            c->pix_abs[0][1] = sad16_x2_mmx2;
-            c->pix_abs[0][2] = sad16_y2_mmx2;
-            c->pix_abs[0][3] = sad16_xy2_mmx2;
-            c->pix_abs[1][1] = sad8_x2_mmx2;
-            c->pix_abs[1][2] = sad8_y2_mmx2;
-            c->pix_abs[1][3] = sad8_xy2_mmx2;
+            c->pix_abs[0][1] = sad16_x2_mmxext;
+            c->pix_abs[0][2] = sad16_y2_mmxext;
+            c->pix_abs[0][3] = sad16_xy2_mmxext;
+            c->pix_abs[1][1] = sad8_x2_mmxext;
+            c->pix_abs[1][2] = sad8_y2_mmxext;
+            c->pix_abs[1][3] = sad8_xy2_mmxext;
         }
     }
     if ((mm_flags & AV_CPU_FLAG_SSE2) && !(mm_flags & AV_CPU_FLAG_3DNOW) && avctx->codec_id != AV_CODEC_ID_SNOW) {
diff --git a/libavcodec/x86/mpegaudiodec.c b/libavcodec/x86/mpegaudiodec.c
index a8b55ae..44cbf9a 100644
--- a/libavcodec/x86/mpegaudiodec.c
+++ b/libavcodec/x86/mpegaudiodec.c
@@ -232,7 +232,7 @@
 #endif
 #endif /* HAVE_YASM */
 
-void ff_mpadsp_init_mmx(MPADSPContext *s)
+void ff_mpadsp_init_x86(MPADSPContext *s)
 {
     int mm_flags = av_get_cpu_flags();
 
diff --git a/libavcodec/x86/mpegvideoenc.c b/libavcodec/x86/mpegvideoenc.c
index ee2b25f..8e711f6 100644
--- a/libavcodec/x86/mpegvideoenc.c
+++ b/libavcodec/x86/mpegvideoenc.c
@@ -47,8 +47,8 @@
 #define COMPILE_TEMPLATE_SSSE3  0
 #undef RENAME
 #undef RENAMEl
-#define RENAME(a) a ## _MMX2
-#define RENAMEl(a) a ## _mmx2
+#define RENAME(a) a ## _MMXEXT
+#define RENAMEl(a) a ## _mmxext
 #include "mpegvideoenc_template.c"
 #endif /* HAVE_MMXEXT_INLINE */
 
@@ -92,7 +92,7 @@
 #endif
 #if HAVE_MMXEXT_INLINE
         if (INLINE_MMXEXT(mm_flags))
-            s->dct_quantize = dct_quantize_MMX2;
+            s->dct_quantize = dct_quantize_MMXEXT;
 #endif
 #if HAVE_SSE2_INLINE
         if (INLINE_SSE2(mm_flags))
diff --git a/libavcodec/x86/mpegvideoenc_template.c b/libavcodec/x86/mpegvideoenc_template.c
index d874f39..47c3b43 100644
--- a/libavcodec/x86/mpegvideoenc_template.c
+++ b/libavcodec/x86/mpegvideoenc_template.c
@@ -100,7 +100,7 @@
     const uint16_t *qmat, *bias;
     LOCAL_ALIGNED_16(int16_t, temp_block, [64]);
 
-    assert((7&(int)(&temp_block[0])) == 0); //did gcc align it correctly?
+    av_assert2((7&(int)(&temp_block[0])) == 0); //did gcc align it correctly?
 
     //s->fdct (block);
     RENAMEl(ff_fdct) (block); //cannot be anything else ...
diff --git a/libavcodec/x86/pngdsp.asm b/libavcodec/x86/pngdsp.asm
index 970f3db..c05f3da 100644
--- a/libavcodec/x86/pngdsp.asm
+++ b/libavcodec/x86/pngdsp.asm
@@ -21,8 +21,7 @@
 ;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "x86inc.asm"
-%include "x86util.asm"
+%include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
 
@@ -167,7 +166,7 @@
     RET
 %endmacro
 
-INIT_MMX mmx2
+INIT_MMX mmxext
 ADD_PAETH_PRED_FN 0
 
 INIT_MMX ssse3
diff --git a/libavcodec/x86/pngdsp_init.c b/libavcodec/x86/pngdsp_init.c
index 05fd051..2355eee 100644
--- a/libavcodec/x86/pngdsp_init.c
+++ b/libavcodec/x86/pngdsp_init.c
@@ -23,8 +23,8 @@
 #include "libavutil/x86/cpu.h"
 #include "libavcodec/pngdsp.h"
 
-void ff_add_png_paeth_prediction_mmx2 (uint8_t *dst, uint8_t *src,
-                                       uint8_t *top, int w, int bpp);
+void ff_add_png_paeth_prediction_mmxext(uint8_t *dst, uint8_t *src,
+                                        uint8_t *top, int w, int bpp);
 void ff_add_png_paeth_prediction_ssse3(uint8_t *dst, uint8_t *src,
                                        uint8_t *top, int w, int bpp);
 void ff_add_bytes_l2_mmx (uint8_t *dst, uint8_t *src1,
@@ -41,7 +41,7 @@
         dsp->add_bytes_l2         = ff_add_bytes_l2_mmx;
 #endif
     if (EXTERNAL_MMXEXT(flags))
-        dsp->add_paeth_prediction = ff_add_png_paeth_prediction_mmx2;
+        dsp->add_paeth_prediction = ff_add_png_paeth_prediction_mmxext;
     if (EXTERNAL_SSE2(flags))
         dsp->add_bytes_l2         = ff_add_bytes_l2_sse2;
     if (EXTERNAL_SSSE3(flags))
diff --git a/libavcodec/x86/proresdsp.asm b/libavcodec/x86/proresdsp.asm
index 41f1087..094f872 100644
--- a/libavcodec/x86/proresdsp.asm
+++ b/libavcodec/x86/proresdsp.asm
@@ -22,8 +22,7 @@
 ;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "x86inc.asm"
-%include "x86util.asm"
+%include "libavutil/x86/x86util.asm"
 
 %define W1sh2 22725 ; W1 = 90901 = 22725<<2 + 1
 %define W2sh2 21407 ; W2 = 85627 = 21407<<2 - 1
diff --git a/libavcodec/x86/rv34dsp.asm b/libavcodec/x86/rv34dsp.asm
index 78d8c92..c099ac5 100644
--- a/libavcodec/x86/rv34dsp.asm
+++ b/libavcodec/x86/rv34dsp.asm
@@ -19,8 +19,7 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "x86inc.asm"
-%include "x86util.asm"
+%include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
 pw_row_coeffs:  times 4 dw 13
@@ -58,7 +57,7 @@
     REP_RET
 %endmacro
 
-INIT_MMX mmx2
+INIT_MMX mmxext
 %define IDCT_DC IDCT_DC_ROUND
 rv34_idct dc
 %define IDCT_DC IDCT_DC_NOROUND
@@ -134,7 +133,7 @@
     mova        mm5, [pd_512]           ; 0x200
 %endmacro
 
-; ff_rv34_idct_add_mmx2(uint8_t *dst, ptrdiff_t stride, DCTELEM *block);
+; ff_rv34_idct_add_mmxext(uint8_t *dst, ptrdiff_t stride, DCTELEM *block);
 %macro COL_TRANSFORM  4
     pshufw      mm3, %2, 0xDD        ; col. 1,3,1,3
     pshufw       %2, %2, 0x88        ; col. 0,2,0,2
@@ -155,7 +154,7 @@
     packuswb     %2, %2
     movd         %1, %2
 %endmacro
-INIT_MMX mmx2
+INIT_MMX mmxext
 cglobal rv34_idct_add, 3,3,0, d, s, b
     ROW_TRANSFORM       bq
     COL_TRANSFORM     [dq], mm0, [pw_col_coeffs+ 0], [pw_col_coeffs+ 8]
diff --git a/libavcodec/x86/rv34dsp_init.c b/libavcodec/x86/rv34dsp_init.c
index 305745a..6b6cf91 100644
--- a/libavcodec/x86/rv34dsp_init.c
+++ b/libavcodec/x86/rv34dsp_init.c
@@ -25,11 +25,11 @@
 #include "libavcodec/dsputil.h"
 #include "libavcodec/rv34dsp.h"
 
-void ff_rv34_idct_dc_mmx2(DCTELEM *block);
-void ff_rv34_idct_dc_noround_mmx2(DCTELEM *block);
+void ff_rv34_idct_dc_mmxext(DCTELEM *block);
+void ff_rv34_idct_dc_noround_mmxext(DCTELEM *block);
 void ff_rv34_idct_dc_add_mmx(uint8_t *dst, ptrdiff_t stride, int dc);
 void ff_rv34_idct_dc_add_sse4(uint8_t *dst, ptrdiff_t stride, int dc);
-void ff_rv34_idct_add_mmx2(uint8_t *dst, ptrdiff_t stride, DCTELEM *block);
+void ff_rv34_idct_add_mmxext(uint8_t *dst, ptrdiff_t stride, DCTELEM *block);
 
 av_cold void ff_rv34dsp_init_x86(RV34DSPContext* c, DSPContext *dsp)
 {
@@ -38,8 +38,8 @@
     if (EXTERNAL_MMX(mm_flags))
         c->rv34_idct_dc_add = ff_rv34_idct_dc_add_mmx;
     if (EXTERNAL_MMXEXT(mm_flags)) {
-        c->rv34_inv_transform_dc = ff_rv34_idct_dc_noround_mmx2;
-        c->rv34_idct_add         = ff_rv34_idct_add_mmx2;
+        c->rv34_inv_transform_dc = ff_rv34_idct_dc_noround_mmxext;
+        c->rv34_idct_add         = ff_rv34_idct_add_mmxext;
     }
     if (EXTERNAL_SSE4(mm_flags))
         c->rv34_idct_dc_add = ff_rv34_idct_dc_add_sse4;
diff --git a/libavcodec/x86/rv40dsp.asm b/libavcodec/x86/rv40dsp.asm
index 70c0c04..7ec72be 100644
--- a/libavcodec/x86/rv40dsp.asm
+++ b/libavcodec/x86/rv40dsp.asm
@@ -21,8 +21,7 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "x86inc.asm"
-%include "x86util.asm"
+%include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
 
@@ -241,7 +240,7 @@
 FILTER_V  put
 FILTER_H  put
 
-INIT_MMX  mmx2
+INIT_MMX  mmxext
 FILTER_V  avg
 FILTER_H  avg
 
@@ -487,7 +486,7 @@
     REP_RET
 %endmacro
 
-INIT_MMX mmx2
+INIT_MMX mmxext
 RV40_WEIGHT   rnd,    8, 3
 RV40_WEIGHT   rnd,   16, 4
 RV40_WEIGHT   nornd,  8, 3
diff --git a/libavcodec/x86/rv40dsp_init.c b/libavcodec/x86/rv40dsp_init.c
index 966e3f2..06ee86e 100644
--- a/libavcodec/x86/rv40dsp_init.c
+++ b/libavcodec/x86/rv40dsp_init.c
@@ -34,15 +34,15 @@
 #if HAVE_YASM
 void ff_put_rv40_chroma_mc8_mmx  (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_rv40_chroma_mc8_mmxext(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_rv40_chroma_mc4_mmx  (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_rv40_chroma_mc4_mmxext(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);
 
@@ -55,7 +55,7 @@
                                         int w1, int w2, ptrdiff_t stride); \
 void ff_rv40_weight_func_nornd_8_##opt (uint8_t *dst, uint8_t *src1, uint8_t *src2, \
                                         int w1, int w2, ptrdiff_t stride);
-DECLARE_WEIGHT(mmx2)
+DECLARE_WEIGHT(mmxext)
 DECLARE_WEIGHT(sse2)
 DECLARE_WEIGHT(ssse3)
 
@@ -150,9 +150,9 @@
 
 QPEL_MC_DECL(put_, _mmx)
 
-#define ff_put_rv40_qpel_h_mmx2  ff_put_rv40_qpel_h_mmx
-#define ff_put_rv40_qpel_v_mmx2  ff_put_rv40_qpel_v_mmx
-QPEL_MC_DECL(avg_, _mmx2)
+#define ff_put_rv40_qpel_h_mmxext  ff_put_rv40_qpel_h_mmx
+#define ff_put_rv40_qpel_v_mmxext  ff_put_rv40_qpel_v_mmx
+QPEL_MC_DECL(avg_, _mmxext)
 
 #define ff_put_rv40_qpel_h_3dnow  ff_put_rv40_qpel_h_mmx
 #define ff_put_rv40_qpel_v_3dnow  ff_put_rv40_qpel_v_mmx
@@ -195,25 +195,25 @@
     if (EXTERNAL_MMX(mm_flags)) {
         c->put_chroma_pixels_tab[0] = ff_put_rv40_chroma_mc8_mmx;
         c->put_chroma_pixels_tab[1] = ff_put_rv40_chroma_mc4_mmx;
-#if HAVE_INLINE_ASM
+#if HAVE_MMX_INLINE
         c->put_pixels_tab[0][15] = ff_put_rv40_qpel16_mc33_mmx;
         c->put_pixels_tab[1][15] = ff_put_rv40_qpel8_mc33_mmx;
         c->avg_pixels_tab[0][15] = ff_avg_rv40_qpel16_mc33_mmx;
         c->avg_pixels_tab[1][15] = ff_avg_rv40_qpel8_mc33_mmx;
-#endif /* HAVE_INLINE_ASM */
+#endif /* HAVE_MMX_INLINE */
 #if ARCH_X86_32
         QPEL_MC_SET(put_, _mmx)
 #endif
     }
     if (EXTERNAL_MMXEXT(mm_flags)) {
-        c->avg_chroma_pixels_tab[0] = ff_avg_rv40_chroma_mc8_mmx2;
-        c->avg_chroma_pixels_tab[1] = ff_avg_rv40_chroma_mc4_mmx2;
-        c->rv40_weight_pixels_tab[0][0] = ff_rv40_weight_func_rnd_16_mmx2;
-        c->rv40_weight_pixels_tab[0][1] = ff_rv40_weight_func_rnd_8_mmx2;
-        c->rv40_weight_pixels_tab[1][0] = ff_rv40_weight_func_nornd_16_mmx2;
-        c->rv40_weight_pixels_tab[1][1] = ff_rv40_weight_func_nornd_8_mmx2;
+        c->avg_chroma_pixels_tab[0]     = ff_avg_rv40_chroma_mc8_mmxext;
+        c->avg_chroma_pixels_tab[1]     = ff_avg_rv40_chroma_mc4_mmxext;
+        c->rv40_weight_pixels_tab[0][0] = ff_rv40_weight_func_rnd_16_mmxext;
+        c->rv40_weight_pixels_tab[0][1] = ff_rv40_weight_func_rnd_8_mmxext;
+        c->rv40_weight_pixels_tab[1][0] = ff_rv40_weight_func_nornd_16_mmxext;
+        c->rv40_weight_pixels_tab[1][1] = ff_rv40_weight_func_nornd_8_mmxext;
 #if ARCH_X86_32
-        QPEL_MC_SET(avg_, _mmx2)
+        QPEL_MC_SET(avg_, _mmxext)
 #endif
     } else if (EXTERNAL_AMD3DNOW(mm_flags)) {
         c->avg_chroma_pixels_tab[0] = ff_avg_rv40_chroma_mc8_3dnow;
diff --git a/libavcodec/x86/sbrdsp.asm b/libavcodec/x86/sbrdsp.asm
index 47cb312..c351de4 100644
--- a/libavcodec/x86/sbrdsp.asm
+++ b/libavcodec/x86/sbrdsp.asm
@@ -19,8 +19,7 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "x86inc.asm"
-%include "x86util.asm"
+%include "libavutil/x86/x86util.asm"
 
 ;SECTION_RODATA
 SECTION .text
diff --git a/libavcodec/x86/v210.asm b/libavcodec/x86/v210.asm
index 90305df..5473126 100644
--- a/libavcodec/x86/v210.asm
+++ b/libavcodec/x86/v210.asm
@@ -20,7 +20,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
diff --git a/libavcodec/x86/vc1dsp.asm b/libavcodec/x86/vc1dsp.asm
index 590aa50..546688c 100644
--- a/libavcodec/x86/vc1dsp.asm
+++ b/libavcodec/x86/vc1dsp.asm
@@ -19,7 +19,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 cextern pw_4
@@ -35,7 +34,13 @@
     punpckl%1 m%2, m%4
 %endmacro
 
-%macro STORE_4_WORDS_MMX 6
+%macro STORE_4_WORDS 6
+%if cpuflag(sse4)
+    pextrw %1, %5, %6+0
+    pextrw %2, %5, %6+1
+    pextrw %3, %5, %6+2
+    pextrw %4, %5, %6+3
+%else
     movd  %6d, %5
 %if mmsize==16
     psrldq %5, 4
@@ -49,13 +54,7 @@
     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
+%endif
 %endmacro
 
 ; in:  p1 p0 q0 q1, clobbers p0
@@ -201,14 +200,14 @@
     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
+    STORE_4_WORDS [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
+    STORE_4_WORDS [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
+    STORE_4_WORDS [r0-1], [r0+r1-1], [r0+2*r1-1], [r0+r3-1], m0, 0
+    STORE_4_WORDS [r4-1], [r4+r1-1], [r4+2*r1-1], [r4+r3-1], m0, 4
 %endif
 %endmacro
 
@@ -229,92 +228,90 @@
     imul r2, 0x01010101
 %endmacro
 
-%macro VC1_LF_MMX 1
-INIT_MMX
-cglobal vc1_v_loop_filter_internal_%1
+%macro VC1_LF 0
+cglobal vc1_v_loop_filter_internal
     VC1_V_LOOP_FILTER 4, d
     ret
 
-cglobal vc1_h_loop_filter_internal_%1
+cglobal vc1_h_loop_filter_internal
     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
+; void ff_vc1_v_loop_filter4_mmxext(uint8_t *src, int stride, int pq)
+cglobal vc1_v_loop_filter4, 3,5,0
     START_V_FILTER
-    call vc1_v_loop_filter_internal_%1
+    call vc1_v_loop_filter_internal
     RET
 
-; void ff_vc1_h_loop_filter4_mmx2(uint8_t *src, int stride, int pq)
-cglobal vc1_h_loop_filter4_%1, 3,5,0
+; void ff_vc1_h_loop_filter4_mmxext(uint8_t *src, int stride, int pq)
+cglobal vc1_h_loop_filter4, 3,5,0
     START_H_FILTER 4
-    call vc1_h_loop_filter_internal_%1
+    call vc1_h_loop_filter_internal
     RET
 
-; void ff_vc1_v_loop_filter8_mmx2(uint8_t *src, int stride, int pq)
-cglobal vc1_v_loop_filter8_%1, 3,5,0
+; void ff_vc1_v_loop_filter8_mmxext(uint8_t *src, int stride, int pq)
+cglobal vc1_v_loop_filter8, 3,5,0
     START_V_FILTER
-    call vc1_v_loop_filter_internal_%1
+    call vc1_v_loop_filter_internal
     add  r4, 4
     add  r0, 4
-    call vc1_v_loop_filter_internal_%1
+    call vc1_v_loop_filter_internal
     RET
 
-; void ff_vc1_h_loop_filter8_mmx2(uint8_t *src, int stride, int pq)
-cglobal vc1_h_loop_filter8_%1, 3,5,0
+; void ff_vc1_h_loop_filter8_mmxext(uint8_t *src, int stride, int pq)
+cglobal vc1_h_loop_filter8, 3,5,0
     START_H_FILTER 4
-    call vc1_h_loop_filter_internal_%1
+    call vc1_h_loop_filter_internal
     lea  r0, [r0+4*r1]
-    call vc1_h_loop_filter_internal_%1
+    call vc1_h_loop_filter_internal
     RET
 %endmacro
 
-%define PABSW PABSW_MMX2
-VC1_LF_MMX mmx2
+INIT_MMX mmxext
+VC1_LF
 
-INIT_XMM
+INIT_XMM sse2
 ; void ff_vc1_v_loop_filter8_sse2(uint8_t *src, int stride, int pq)
-cglobal vc1_v_loop_filter8_sse2, 3,5,8
+cglobal vc1_v_loop_filter8, 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
+cglobal vc1_h_loop_filter8, 3,6,8
     START_H_FILTER 8
     VC1_H_LOOP_FILTER 8, r5
     RET
 
-%define PABSW PABSW_SSSE3
-
-INIT_MMX
+INIT_MMX ssse3
 ; void ff_vc1_v_loop_filter4_ssse3(uint8_t *src, int stride, int pq)
-cglobal vc1_v_loop_filter4_ssse3, 3,5,0
+cglobal vc1_v_loop_filter4, 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
+cglobal vc1_h_loop_filter4, 3,5,0
     START_H_FILTER 4
     VC1_H_LOOP_FILTER 4, r4
     RET
 
-INIT_XMM
+INIT_XMM ssse3
 ; void ff_vc1_v_loop_filter8_ssse3(uint8_t *src, int stride, int pq)
-cglobal vc1_v_loop_filter8_ssse3, 3,5,8
+cglobal vc1_v_loop_filter8, 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
+cglobal vc1_h_loop_filter8, 3,6,8
     START_H_FILTER 8
     VC1_H_LOOP_FILTER 8, r5
     RET
 
+INIT_XMM sse4
 ; void ff_vc1_h_loop_filter8_sse4(uint8_t *src, int stride, int pq)
-cglobal vc1_h_loop_filter8_sse4, 3,5,8
+cglobal vc1_h_loop_filter8, 3,5,8
     START_H_FILTER 8
     VC1_H_LOOP_FILTER 8
     RET
diff --git a/libavutil/symbols.h b/libavcodec/x86/vc1dsp.h
similarity index 69%
copy from libavutil/symbols.h
copy to libavcodec/x86/vc1dsp.h
index 6011da2..fdd4de1 100644
--- a/libavutil/symbols.h
+++ b/libavcodec/x86/vc1dsp.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Ronald S. Bultje <rsbultje@gmail.com>
+ * VC-1 and WMV3 decoder - X86 DSP init functions
  *
  * This file is part of FFmpeg.
  *
@@ -18,15 +18,12 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#ifndef AVUTIL_SYMBOLS_H
-#define AVUTIL_SYMBOLS_H
+#ifndef AVCODEC_X86_VC1DSP_H
+#define AVCODEC_X86_VC1DSP_H
 
-#include "libavutil/avconfig.h"
+#include "libavcodec/vc1dsp.h"
 
-#if AV_HAVE_SHARED_LIBS && defined(_MSC_VER) && !defined(COMPILING_avutil)
-#define AVUTIL_SYMBOL __declspec(dllimport)
-#else
-#define AVUTIL_SYMBOL
-#endif
+void ff_vc1dsp_init_mmx(VC1DSPContext *dsp);
+void ff_vc1dsp_init_mmxext(VC1DSPContext *dsp);
 
-#endif /* AVUTIL_SYMBOLS_H */
+#endif /* AVCODEC_X86_VC1DSP_H */
diff --git a/libavcodec/x86/vc1dsp_init.c b/libavcodec/x86/vc1dsp_init.c
new file mode 100644
index 0000000..230d06f
--- /dev/null
+++ b/libavcodec/x86/vc1dsp_init.c
@@ -0,0 +1,123 @@
+/*
+ * VC-1 and WMV3 - DSP functions MMX-optimized
+ * Copyright (c) 2007 Christophe GISQUET <christophe.gisquet@free.fr>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use,
+ * copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following
+ * conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "libavutil/cpu.h"
+#include "libavutil/x86/cpu.h"
+#include "libavcodec/vc1dsp.h"
+#include "vc1dsp.h"
+#include "config.h"
+
+#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(mmxext)
+LOOP_FILTER(sse2)
+LOOP_FILTER(ssse3)
+
+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);
+}
+#endif /* HAVE_YASM */
+
+void ff_put_vc1_chroma_mc8_nornd_mmx  (uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_avg_vc1_chroma_mc8_nornd_mmxext(uint8_t *dst, uint8_t *src,
+                                        int stride, int h, int x, int y);
+void ff_avg_vc1_chroma_mc8_nornd_3dnow(uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_put_vc1_chroma_mc8_nornd_ssse3(uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+void ff_avg_vc1_chroma_mc8_nornd_ssse3(uint8_t *dst, uint8_t *src,
+                                       int stride, int h, int x, int y);
+
+
+av_cold void ff_vc1dsp_init_x86(VC1DSPContext *dsp)
+{
+    int mm_flags = av_get_cpu_flags();
+
+    if (INLINE_MMX(mm_flags))
+        ff_vc1dsp_init_mmx(dsp);
+
+    if (INLINE_MMXEXT(mm_flags))
+        ff_vc1dsp_init_mmxext(dsp);
+
+#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) {
+        dsp->put_no_rnd_vc1_chroma_pixels_tab[0] = ff_put_vc1_chroma_mc8_nornd_mmx;
+    }
+
+    if (mm_flags & AV_CPU_FLAG_MMXEXT) {
+        ASSIGN_LF(mmxext);
+        dsp->avg_no_rnd_vc1_chroma_pixels_tab[0] = ff_avg_vc1_chroma_mc8_nornd_mmxext;
+    } else if (mm_flags & AV_CPU_FLAG_3DNOW) {
+        dsp->avg_no_rnd_vc1_chroma_pixels_tab[0] = ff_avg_vc1_chroma_mc8_nornd_3dnow;
+    }
+
+    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_nornd_ssse3;
+        dsp->avg_no_rnd_vc1_chroma_pixels_tab[0] = ff_avg_vc1_chroma_mc8_nornd_ssse3;
+    }
+    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 /* HAVE_YASM */
+}
diff --git a/libavcodec/x86/vc1dsp_mmx.c b/libavcodec/x86/vc1dsp_mmx.c
index 66251d0..6ce65e4 100644
--- a/libavcodec/x86/vc1dsp_mmx.c
+++ b/libavcodec/x86/vc1dsp_mmx.c
@@ -27,9 +27,11 @@
 #include "libavutil/cpu.h"
 #include "libavutil/mem.h"
 #include "libavutil/x86/asm.h"
+#include "libavutil/x86/cpu.h"
 #include "libavcodec/dsputil.h"
 #include "dsputil_mmx.h"
 #include "libavcodec/vc1dsp.h"
+#include "vc1dsp.h"
 
 #if HAVE_INLINE_ASM
 
@@ -464,7 +466,10 @@
 static void put_vc1_mspel_mc ## a ## b ## _mmx(uint8_t *dst, const uint8_t *src, int stride, int rnd) { \
      put_vc1_mspel_mc(dst, src, stride, a, b, rnd);                     \
 }\
-static void avg_vc1_mspel_mc ## a ## b ## _mmx2(uint8_t *dst, const uint8_t *src, int stride, int rnd) { \
+static void avg_vc1_mspel_mc ## a ## b ## _mmxext(uint8_t *dst,         \
+                                                  const uint8_t *src,   \
+                                                  int stride, int rnd)  \
+{                                                                       \
      avg_vc1_mspel_mc(dst, src, stride, a, b, rnd);                     \
 }
 
@@ -487,7 +492,8 @@
 DECLARE_FUNCTION(3, 2)
 DECLARE_FUNCTION(3, 3)
 
-static void vc1_inv_trans_4x4_dc_mmx2(uint8_t *dest, int linesize, DCTELEM *block)
+static void vc1_inv_trans_4x4_dc_mmxext(uint8_t *dest, int linesize,
+                                        DCTELEM *block)
 {
     int dc = block[0];
     dc = (17 * dc +  4) >> 3;
@@ -525,7 +531,8 @@
     );
 }
 
-static void vc1_inv_trans_4x8_dc_mmx2(uint8_t *dest, int linesize, DCTELEM *block)
+static void vc1_inv_trans_4x8_dc_mmxext(uint8_t *dest, int linesize,
+                                        DCTELEM *block)
 {
     int dc = block[0];
     dc = (17 * dc +  4) >> 3;
@@ -586,7 +593,8 @@
     );
 }
 
-static void vc1_inv_trans_8x4_dc_mmx2(uint8_t *dest, int linesize, DCTELEM *block)
+static void vc1_inv_trans_8x4_dc_mmxext(uint8_t *dest, int linesize,
+                                        DCTELEM *block)
 {
     int dc = block[0];
     dc = ( 3 * dc +  1) >> 1;
@@ -624,7 +632,8 @@
     );
 }
 
-static void vc1_inv_trans_8x8_dc_mmx2(uint8_t *dest, int linesize, DCTELEM *block)
+static void vc1_inv_trans_8x8_dc_mmxext(uint8_t *dest, int linesize,
+                                        DCTELEM *block)
 {
     int dc = block[0];
     dc = (3 * dc +  1) >> 1;
@@ -685,57 +694,8 @@
     );
 }
 
-#endif /* HAVE_INLINE_ASM */
-
-#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(mmx2)
-LOOP_FILTER(sse2)
-LOOP_FILTER(ssse3)
-
-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)
+av_cold void ff_vc1dsp_init_mmx(VC1DSPContext *dsp)
 {
-    ff_vc1_h_loop_filter8_sse4(src,          stride, pq);
-    ff_vc1_h_loop_filter8_sse4(src+8*stride, stride, pq);
-}
-#endif /* HAVE_YASM */
-
-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);
-
-void ff_vc1dsp_init_mmx(VC1DSPContext *dsp)
-{
-    int mm_flags = av_get_cpu_flags();
-
-#if HAVE_INLINE_ASM
-    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;
@@ -755,77 +715,33 @@
         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 (HAVE_YASM)
-            dsp->put_no_rnd_vc1_chroma_pixels_tab[0]= ff_put_vc1_chroma_mc8_mmx_nornd;
-    }
-
-    if (mm_flags & AV_CPU_FLAG_MMXEXT) {
-        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;
-        dsp->avg_vc1_mspel_pixels_tab[12] = avg_vc1_mspel_mc03_mmx2;
-
-        dsp->avg_vc1_mspel_pixels_tab[ 1] = avg_vc1_mspel_mc10_mmx2;
-        dsp->avg_vc1_mspel_pixels_tab[ 5] = avg_vc1_mspel_mc11_mmx2;
-        dsp->avg_vc1_mspel_pixels_tab[ 9] = avg_vc1_mspel_mc12_mmx2;
-        dsp->avg_vc1_mspel_pixels_tab[13] = avg_vc1_mspel_mc13_mmx2;
-
-        dsp->avg_vc1_mspel_pixels_tab[ 2] = avg_vc1_mspel_mc20_mmx2;
-        dsp->avg_vc1_mspel_pixels_tab[ 6] = avg_vc1_mspel_mc21_mmx2;
-        dsp->avg_vc1_mspel_pixels_tab[10] = avg_vc1_mspel_mc22_mmx2;
-        dsp->avg_vc1_mspel_pixels_tab[14] = avg_vc1_mspel_mc23_mmx2;
-
-        dsp->avg_vc1_mspel_pixels_tab[ 3] = avg_vc1_mspel_mc30_mmx2;
-        dsp->avg_vc1_mspel_pixels_tab[ 7] = avg_vc1_mspel_mc31_mmx2;
-        dsp->avg_vc1_mspel_pixels_tab[11] = avg_vc1_mspel_mc32_mmx2;
-        dsp->avg_vc1_mspel_pixels_tab[15] = avg_vc1_mspel_mc33_mmx2;
-
-        dsp->vc1_inv_trans_8x8_dc = vc1_inv_trans_8x8_dc_mmx2;
-        dsp->vc1_inv_trans_4x8_dc = vc1_inv_trans_4x8_dc_mmx2;
-        dsp->vc1_inv_trans_8x4_dc = vc1_inv_trans_8x4_dc_mmx2;
-        dsp->vc1_inv_trans_4x4_dc = vc1_inv_trans_4x4_dc_mmx2;
-
-        if (HAVE_YASM)
-            dsp->avg_no_rnd_vc1_chroma_pixels_tab[0]= ff_avg_vc1_chroma_mc8_mmx2_nornd;
-    } else if (HAVE_YASM && mm_flags & AV_CPU_FLAG_3DNOW) {
-        dsp->avg_no_rnd_vc1_chroma_pixels_tab[0]= ff_avg_vc1_chroma_mc8_3dnow_nornd;
-    }
-
-    if (HAVE_YASM && mm_flags & AV_CPU_FLAG_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;
-    }
-#endif /* HAVE_INLINE_ASM */
-
-#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) {
-    }
-
-    if (mm_flags & AV_CPU_FLAG_MMXEXT) {
-        ASSIGN_LF(mmx2);
-    }
-
-    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);
-    }
-    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 /* HAVE_YASM */
 }
+
+av_cold void ff_vc1dsp_init_mmxext(VC1DSPContext *dsp)
+{
+        dsp->avg_vc1_mspel_pixels_tab[ 0] = ff_avg_vc1_mspel_mc00_mmxext;
+        dsp->avg_vc1_mspel_pixels_tab[ 4] = avg_vc1_mspel_mc01_mmxext;
+        dsp->avg_vc1_mspel_pixels_tab[ 8] = avg_vc1_mspel_mc02_mmxext;
+        dsp->avg_vc1_mspel_pixels_tab[12] = avg_vc1_mspel_mc03_mmxext;
+
+        dsp->avg_vc1_mspel_pixels_tab[ 1] = avg_vc1_mspel_mc10_mmxext;
+        dsp->avg_vc1_mspel_pixels_tab[ 5] = avg_vc1_mspel_mc11_mmxext;
+        dsp->avg_vc1_mspel_pixels_tab[ 9] = avg_vc1_mspel_mc12_mmxext;
+        dsp->avg_vc1_mspel_pixels_tab[13] = avg_vc1_mspel_mc13_mmxext;
+
+        dsp->avg_vc1_mspel_pixels_tab[ 2] = avg_vc1_mspel_mc20_mmxext;
+        dsp->avg_vc1_mspel_pixels_tab[ 6] = avg_vc1_mspel_mc21_mmxext;
+        dsp->avg_vc1_mspel_pixels_tab[10] = avg_vc1_mspel_mc22_mmxext;
+        dsp->avg_vc1_mspel_pixels_tab[14] = avg_vc1_mspel_mc23_mmxext;
+
+        dsp->avg_vc1_mspel_pixels_tab[ 3] = avg_vc1_mspel_mc30_mmxext;
+        dsp->avg_vc1_mspel_pixels_tab[ 7] = avg_vc1_mspel_mc31_mmxext;
+        dsp->avg_vc1_mspel_pixels_tab[11] = avg_vc1_mspel_mc32_mmxext;
+        dsp->avg_vc1_mspel_pixels_tab[15] = avg_vc1_mspel_mc33_mmxext;
+
+        dsp->vc1_inv_trans_8x8_dc = vc1_inv_trans_8x8_dc_mmxext;
+        dsp->vc1_inv_trans_4x8_dc = vc1_inv_trans_4x8_dc_mmxext;
+        dsp->vc1_inv_trans_8x4_dc = vc1_inv_trans_8x4_dc_mmxext;
+        dsp->vc1_inv_trans_4x4_dc = vc1_inv_trans_4x4_dc_mmxext;
+}
+#endif /* HAVE_INLINE_ASM */
diff --git a/libavcodec/x86/vp3dsp.asm b/libavcodec/x86/vp3dsp.asm
index dcd55f5..3a5ed03 100644
--- a/libavcodec/x86/vp3dsp.asm
+++ b/libavcodec/x86/vp3dsp.asm
@@ -19,7 +19,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 ; MMX-optimized functions cribbed from the original VP3 source code.
@@ -102,7 +101,7 @@
     mov  [r0+r3  -1], r2w
 %endmacro
 
-INIT_MMX mmx2
+INIT_MMX mmxext
 cglobal vp3_v_loop_filter, 3, 4
 %if ARCH_X86_64
     movsxd        r1, r1d
@@ -634,7 +633,7 @@
     movq   [r0+r3  ], m5
 %endmacro
 
-INIT_MMX mmx2
+INIT_MMX mmxext
 cglobal vp3_idct_dc_add, 3, 4
 %if ARCH_X86_64
     movsxd        r1, r1d
diff --git a/libavcodec/x86/vp3dsp_init.c b/libavcodec/x86/vp3dsp_init.c
index c4d462b..eddfd07 100644
--- a/libavcodec/x86/vp3dsp_init.c
+++ b/libavcodec/x86/vp3dsp_init.c
@@ -31,11 +31,13 @@
 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);
 
-void ff_vp3_idct_dc_add_mmx2(uint8_t *dest, int line_size,
-                             const DCTELEM *block);
+void ff_vp3_idct_dc_add_mmxext(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_v_loop_filter_mmxext(uint8_t *src, int stride,
+                                 int *bounding_values);
+void ff_vp3_h_loop_filter_mmxext(uint8_t *src, int stride,
+                                 int *bounding_values);
 
 av_cold void ff_vp3dsp_init_x86(VP3DSPContext *c, int flags)
 {
@@ -50,11 +52,11 @@
 #endif
 
     if (EXTERNAL_MMXEXT(cpuflags)) {
-        c->idct_dc_add = ff_vp3_idct_dc_add_mmx2;
+        c->idct_dc_add = ff_vp3_idct_dc_add_mmxext;
 
         if (!(flags & CODEC_FLAG_BITEXACT)) {
-            c->v_loop_filter = ff_vp3_v_loop_filter_mmx2;
-            c->h_loop_filter = ff_vp3_h_loop_filter_mmx2;
+            c->v_loop_filter = ff_vp3_v_loop_filter_mmxext;
+            c->h_loop_filter = ff_vp3_h_loop_filter_mmxext;
         }
     }
 
diff --git a/libavcodec/x86/vp56dsp.asm b/libavcodec/x86/vp56dsp.asm
index bc09903..3d874ea 100644
--- a/libavcodec/x86/vp56dsp.asm
+++ b/libavcodec/x86/vp56dsp.asm
@@ -20,7 +20,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 cextern pw_64
diff --git a/libavcodec/x86/vp8dsp.asm b/libavcodec/x86/vp8dsp.asm
index 32f1c25..19640c8 100644
--- a/libavcodec/x86/vp8dsp.asm
+++ b/libavcodec/x86/vp8dsp.asm
@@ -20,7 +20,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
@@ -339,7 +338,7 @@
 FILTER_SSSE3 8
 
 ; 4x4 block, H-only 4-tap filter
-INIT_MMX mmx2
+INIT_MMX mmxext
 cglobal put_vp8_epel4_h4, 6, 6 + npicregs, 0, dst, dststride, src, srcstride, height, mx, picreg
     shl       mxd, 4
 %ifdef PIC
@@ -387,7 +386,7 @@
     REP_RET
 
 ; 4x4 block, H-only 6-tap filter
-INIT_MMX mmx2
+INIT_MMX mmxext
 cglobal put_vp8_epel4_h6, 6, 6 + npicregs, 0, dst, dststride, src, srcstride, height, mx, picreg
     lea       mxd, [mxq*3]
 %ifdef PIC
@@ -674,7 +673,7 @@
     REP_RET
 %endmacro
 
-INIT_MMX mmx2
+INIT_MMX mmxext
 FILTER_V 4
 INIT_XMM sse2
 FILTER_V 8
@@ -770,7 +769,7 @@
     REP_RET
 %endmacro
 
-INIT_MMX mmx2
+INIT_MMX mmxext
 FILTER_BILINEAR 4
 INIT_XMM sse2
 FILTER_BILINEAR 8
@@ -1612,7 +1611,7 @@
 INIT_MMX mmx
 SIMPLE_LOOPFILTER v, 4
 SIMPLE_LOOPFILTER h, 5
-INIT_MMX mmx2
+INIT_MMX mmxext
 SIMPLE_LOOPFILTER v, 4
 SIMPLE_LOOPFILTER h, 5
 %endif
@@ -1839,7 +1838,7 @@
     psubusb          m6, m5          ; q2-q1
     por              m6, m4          ; abs(q2-q1)
 
-%if notcpuflag(mmx2)
+%if notcpuflag(mmxext)
     mova             m4, m_flimI
     pxor             m3, m3
     psubusb          m0, m4
@@ -1879,7 +1878,7 @@
     psubusb          m1, m3          ; p1-p0
     psubusb          m6, m2          ; p0-p1
     por              m1, m6          ; abs(p1-p0)
-%if notcpuflag(mmx2)
+%if notcpuflag(mmxext)
     mova             m6, m1
     psubusb          m1, m4
     psubusb          m6, m_hevthr
@@ -1910,7 +1909,7 @@
     psubusb          m1, m5          ; q0-q1
     psubusb          m7, m4          ; q1-q0
     por              m1, m7          ; abs(q1-q0)
-%if notcpuflag(mmx2)
+%if notcpuflag(mmxext)
     mova             m7, m1
     psubusb          m1, m6
     psubusb          m7, m_hevthr
@@ -2018,14 +2017,14 @@
 %else
     mova             m6, m_maskres
 %endif
-%if notcpuflag(mmx2)
+%if notcpuflag(mmxext)
     mova             m7, [pb_1]
 %else ; mmxext/sse2
     pxor             m7, m7
 %endif
     pand             m0, m6
     pand             m1, m6
-%if notcpuflag(mmx2)
+%if notcpuflag(mmxext)
     paddusb          m0, m7
     pand             m1, [pb_FE]
     pandn            m7, m0
@@ -2099,7 +2098,7 @@
 INNER_LOOPFILTER v,  8
 INNER_LOOPFILTER h,  8
 
-INIT_MMX mmx2
+INIT_MMX mmxext
 INNER_LOOPFILTER v, 16
 INNER_LOOPFILTER h, 16
 INNER_LOOPFILTER v,  8
@@ -2348,7 +2347,7 @@
     psubusb          m6, m5          ; q2-q1
     por              m6, m4          ; abs(q2-q1)
 
-%if notcpuflag(mmx2)
+%if notcpuflag(mmxext)
     mova             m4, m_flimI
     pxor             m3, m3
     psubusb          m0, m4
@@ -2388,7 +2387,7 @@
     psubusb          m1, m3          ; p1-p0
     psubusb          m6, m2          ; p0-p1
     por              m1, m6          ; abs(p1-p0)
-%if notcpuflag(mmx2)
+%if notcpuflag(mmxext)
     mova             m6, m1
     psubusb          m1, m4
     psubusb          m6, m_hevthr
@@ -2419,7 +2418,7 @@
     psubusb          m1, m5          ; q0-q1
     psubusb          m7, m4          ; q1-q0
     por              m1, m7          ; abs(q1-q0)
-%if notcpuflag(mmx2)
+%if notcpuflag(mmxext)
     mova             m7, m1
     psubusb          m1, m6
     psubusb          m7, m_hevthr
@@ -2758,7 +2757,7 @@
 MBEDGE_LOOPFILTER v,  8
 MBEDGE_LOOPFILTER h,  8
 
-INIT_MMX mmx2
+INIT_MMX mmxext
 MBEDGE_LOOPFILTER v, 16
 MBEDGE_LOOPFILTER h, 16
 MBEDGE_LOOPFILTER v,  8
diff --git a/libavcodec/x86/vp8dsp_init.c b/libavcodec/x86/vp8dsp_init.c
index 1556133..735619c 100644
--- a/libavcodec/x86/vp8dsp_init.c
+++ b/libavcodec/x86/vp8dsp_init.c
@@ -30,16 +30,16 @@
 /*
  * MC functions
  */
-extern void ff_put_vp8_epel4_h4_mmx2  (uint8_t *dst, ptrdiff_t dststride,
+extern void ff_put_vp8_epel4_h4_mmxext(uint8_t *dst, ptrdiff_t dststride,
                                        uint8_t *src, ptrdiff_t srcstride,
                                        int height, int mx, int my);
-extern void ff_put_vp8_epel4_h6_mmx2  (uint8_t *dst, ptrdiff_t dststride,
+extern void ff_put_vp8_epel4_h6_mmxext(uint8_t *dst, ptrdiff_t dststride,
                                        uint8_t *src, ptrdiff_t srcstride,
                                        int height, int mx, int my);
-extern void ff_put_vp8_epel4_v4_mmx2  (uint8_t *dst, ptrdiff_t dststride,
+extern void ff_put_vp8_epel4_v4_mmxext(uint8_t *dst, ptrdiff_t dststride,
                                        uint8_t *src, ptrdiff_t srcstride,
                                        int height, int mx, int my);
-extern void ff_put_vp8_epel4_v6_mmx2  (uint8_t *dst, ptrdiff_t dststride,
+extern void ff_put_vp8_epel4_v6_mmxext(uint8_t *dst, ptrdiff_t dststride,
                                        uint8_t *src, ptrdiff_t srcstride,
                                        int height, int mx, int my);
 
@@ -81,7 +81,7 @@
                                        uint8_t *src, ptrdiff_t srcstride,
                                        int height, int mx, int my);
 
-extern void ff_put_vp8_bilinear4_h_mmx2  (uint8_t *dst, ptrdiff_t dststride,
+extern void ff_put_vp8_bilinear4_h_mmxext(uint8_t *dst, ptrdiff_t dststride,
                                           uint8_t *src, ptrdiff_t srcstride,
                                           int height, int mx, int my);
 extern void ff_put_vp8_bilinear8_h_sse2  (uint8_t *dst, ptrdiff_t dststride,
@@ -94,7 +94,7 @@
                                           uint8_t *src, ptrdiff_t srcstride,
                                           int height, int mx, int my);
 
-extern void ff_put_vp8_bilinear4_v_mmx2  (uint8_t *dst, ptrdiff_t dststride,
+extern void ff_put_vp8_bilinear4_v_mmxext(uint8_t *dst, ptrdiff_t dststride,
                                           uint8_t *src, ptrdiff_t srcstride,
                                           int height, int mx, int my);
 extern void ff_put_vp8_bilinear8_v_sse2  (uint8_t *dst, ptrdiff_t dststride,
@@ -140,16 +140,16 @@
 }
 
 #if ARCH_X86_32
-TAP_W8 (mmx2,  epel, h4)
-TAP_W8 (mmx2,  epel, h6)
-TAP_W16(mmx2,  epel, h6)
-TAP_W8 (mmx2,  epel, v4)
-TAP_W8 (mmx2,  epel, v6)
-TAP_W16(mmx2,  epel, v6)
-TAP_W8 (mmx2,  bilinear, h)
-TAP_W16(mmx2,  bilinear, h)
-TAP_W8 (mmx2,  bilinear, v)
-TAP_W16(mmx2,  bilinear, v)
+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)
 #endif
 
 TAP_W16(sse2,  epel, h6)
@@ -178,13 +178,13 @@
 
 #if ARCH_X86_32
 #define HVTAPMMX(x, y) \
-HVTAP(mmx2, 8, x, y,  4,  8) \
-HVTAP(mmx2, 8, x, y,  8, 16)
+HVTAP(mmxext, 8, x, y,  4,  8) \
+HVTAP(mmxext, 8, x, y,  8, 16)
 
-HVTAP(mmx2, 8, 6, 6, 16, 16)
+HVTAP(mmxext, 8, 6, 6, 16, 16)
 #else
 #define HVTAPMMX(x, y) \
-HVTAP(mmx2, 8, x, y,  4,  8)
+HVTAP(mmxext, 8, x, y,  4,  8)
 #endif
 
 HVTAPMMX(4, 4)
@@ -219,10 +219,10 @@
         dst, dststride, tmp, SIZE,      height,     mx, my); \
 }
 
-HVBILIN(mmx2,  8,  4,  8)
+HVBILIN(mmxext,  8,  4,  8)
 #if ARCH_X86_32
-HVBILIN(mmx2,  8,  8, 16)
-HVBILIN(mmx2,  8, 16, 16)
+HVBILIN(mmxext,  8,  8, 16)
+HVBILIN(mmxext,  8, 16, 16)
 #endif
 HVBILIN(sse2,  8,  8, 16)
 HVBILIN(sse2,  8, 16, 16)
@@ -284,7 +284,7 @@
                                                     int e, int i, int hvt);
 
 DECLARE_LOOP_FILTER(mmx)
-DECLARE_LOOP_FILTER(mmx2)
+DECLARE_LOOP_FILTER(mmxext)
 DECLARE_LOOP_FILTER(sse2)
 DECLARE_LOOP_FILTER(ssse3)
 DECLARE_LOOP_FILTER(sse4)
@@ -352,26 +352,26 @@
     /* 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_MMXEXT) {
-        VP8_MC_FUNC(2, 4, mmx2);
-        VP8_BILINEAR_MC_FUNC(2, 4, mmx2);
+        VP8_MC_FUNC(2, 4, mmxext);
+        VP8_BILINEAR_MC_FUNC(2, 4, mmxext);
 #if ARCH_X86_32
-        VP8_LUMA_MC_FUNC(0, 16, mmx2);
-        VP8_MC_FUNC(1, 8, mmx2);
-        VP8_BILINEAR_MC_FUNC(0, 16, mmx2);
-        VP8_BILINEAR_MC_FUNC(1, 8, mmx2);
+        VP8_LUMA_MC_FUNC(0, 16, mmxext);
+        VP8_MC_FUNC(1, 8, mmxext);
+        VP8_BILINEAR_MC_FUNC(0, 16, mmxext);
+        VP8_BILINEAR_MC_FUNC(1,  8, mmxext);
 
-        c->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter_simple_mmx2;
-        c->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter_simple_mmx2;
+        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_mmx2;
-        c->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16y_inner_mmx2;
-        c->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_mmx2;
-        c->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_mmx2;
+        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_mmx2;
-        c->vp8_h_loop_filter16y       = ff_vp8_h_loop_filter16y_mbedge_mmx2;
-        c->vp8_v_loop_filter8uv       = ff_vp8_v_loop_filter8uv_mbedge_mmx2;
-        c->vp8_h_loop_filter8uv       = ff_vp8_h_loop_filter8uv_mbedge_mmx2;
+        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;
 #endif
     }
 
diff --git a/libavcodec/xan.c b/libavcodec/xan.c
index 703ee9e..bccbe24 100644
--- a/libavcodec/xan.c
+++ b/libavcodec/xan.c
@@ -33,12 +33,11 @@
 #include <string.h>
 
 #include "libavutil/intreadwrite.h"
+#include "libavutil/mem.h"
 #include "avcodec.h"
 #include "bytestream.h"
 #define BITSTREAM_READER_LE
 #include "get_bits.h"
-// for av_memcpy_backptr
-#include "libavutil/lzo.h"
 
 #define RUNTIME_GAMMA 0
 
@@ -79,7 +78,7 @@
     s->avctx = avctx;
     s->frame_size = 0;
 
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     s->buffer1_size = avctx->width * avctx->height;
     s->buffer1 = av_malloc(s->buffer1_size);
@@ -360,17 +359,29 @@
 
         case 9:
         case 19:
+            if (buf_end - size_segment < 1) {
+                av_log(s->avctx, AV_LOG_ERROR, "size_segment overread\n");
+                return AVERROR_INVALIDDATA;
+            }
             size = *size_segment++;
             break;
 
         case 10:
         case 20:
+            if (buf_end - size_segment < 2) {
+                av_log(s->avctx, AV_LOG_ERROR, "size_segment overread\n");
+                return AVERROR_INVALIDDATA;
+            }
             size = AV_RB16(&size_segment[0]);
             size_segment += 2;
             break;
 
         case 11:
         case 21:
+            if (buf_end - size_segment < 3) {
+                av_log(s->avctx, AV_LOG_ERROR, "size_segment overread\n");
+                return AVERROR_INVALIDDATA;
+            }
             size = AV_RB24(size_segment);
             size_segment += 3;
             break;
diff --git a/libavcodec/xbmdec.c b/libavcodec/xbmdec.c
index 626e8de..4b8704a 100644
--- a/libavcodec/xbmdec.c
+++ b/libavcodec/xbmdec.c
@@ -22,6 +22,7 @@
 
 #include "avcodec.h"
 #include "internal.h"
+#include "mathops.h"
 
 static av_cold int xbm_decode_init(AVCodecContext *avctx)
 {
@@ -74,7 +75,7 @@
         ptr += strcspn(ptr, "\n\r") + 1;
     }
 
-    avctx->pix_fmt = PIX_FMT_MONOWHITE;
+    avctx->pix_fmt = AV_PIX_FMT_MONOWHITE;
 
     if (p->data[0])
         avctx->release_buffer(avctx, p);
@@ -98,7 +99,7 @@
                 ptr++;
                 if (isxdigit(*ptr))
                     val = (val << 4) + convert(*ptr);
-                *dst++ = av_reverse[val];
+                *dst++ = ff_reverse[val];
             } else {
                 av_log(avctx, AV_LOG_ERROR, "Unexpected data at '%.8s'\n", ptr);
                 return AVERROR_INVALIDDATA;
diff --git a/libavcodec/xbmenc.c b/libavcodec/xbmenc.c
index a82ceaa..8e39969 100644
--- a/libavcodec/xbmenc.c
+++ b/libavcodec/xbmenc.c
@@ -22,7 +22,7 @@
 
 #include "avcodec.h"
 #include "internal.h"
-#include "libavutil/common.h"
+#include "mathops.h"
 
 static av_cold int xbm_encode_init(AVCodecContext *avctx)
 {
@@ -53,7 +53,7 @@
     buf += snprintf(buf, 40, "static unsigned char image_bits[] = {\n");
     for (i = 0; i < avctx->height; i++) {
         for (j = 0; j < linesize; j++)
-            buf += snprintf(buf, 7, " 0x%02X,", av_reverse[*ptr++]);
+            buf += snprintf(buf, 7, " 0x%02X,", ff_reverse[*ptr++]);
         ptr += p->linesize[0] - linesize;
         buf += snprintf(buf, 2, "\n");
     }
@@ -79,7 +79,7 @@
     .init         = xbm_encode_init,
     .encode2      = xbm_encode_frame,
     .close        = xbm_encode_close,
-    .pix_fmts     = (const enum PixelFormat[]) { PIX_FMT_MONOWHITE,
-                                                 PIX_FMT_NONE },
+    .pix_fmts     = (const enum AVPixelFormat[]) { AV_PIX_FMT_MONOWHITE,
+                                                   AV_PIX_FMT_NONE },
     .long_name    = NULL_IF_CONFIG_SMALL("XBM (X BitMap) image"),
 };
diff --git a/libavcodec/xface.c b/libavcodec/xface.c
new file mode 100644
index 0000000..0ebf2f2
--- /dev/null
+++ b/libavcodec/xface.c
@@ -0,0 +1,381 @@
+/*
+ * Copyright (c) 1990 James Ashton - Sydney University
+ * Copyright (c) 2012 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
+ * X-Face common data and utilities definition.
+ */
+
+#include "xface.h"
+
+void ff_big_add(BigInt *b, uint8_t a)
+{
+    int i;
+    uint8_t *w;
+    uint16_t c;
+
+    a &= XFACE_WORDMASK;
+    if (a == 0)
+        return;
+    w = b->words;
+    c = a;
+    for (i = 0; i < b->nb_words && c; i++) {
+        c += *w;
+        *w++ = c & XFACE_WORDMASK;
+        c >>= XFACE_BITSPERWORD;
+    }
+    if (i == b->nb_words && c) {
+        b->nb_words++;
+        *w = c & XFACE_WORDMASK;
+    }
+}
+
+void ff_big_div(BigInt *b, uint8_t a, uint8_t *r)
+{
+    int i;
+    uint8_t *w;
+    uint16_t c, d;
+
+    a &= XFACE_WORDMASK;
+    if (a == 1 || b->nb_words == 0) {
+        *r = 0;
+        return;
+    }
+
+    /* treat this as a == WORDCARRY and just shift everything right a WORD */
+    if (a == 0) {
+        i = --b->nb_words;
+        w = b->words;
+        *r = *w;
+        while (i--) {
+            *w = *(w + 1);
+            w++;
+        }
+        *w = 0;
+        return;
+    }
+    i = b->nb_words;
+    w = b->words + i;
+    c = 0;
+    while (i--) {
+        c <<= XFACE_BITSPERWORD;
+        c += *--w;
+        d = c / (uint16_t)a;
+        c = c % (uint16_t)a;
+        *w = d & XFACE_WORDMASK;
+    }
+    *r = c;
+    if (b->words[b->nb_words - 1] == 0)
+        b->nb_words--;
+}
+
+void ff_big_mul(BigInt *b, uint8_t a)
+{
+    int i;
+    uint8_t *w;
+    uint16_t c;
+
+    a &= XFACE_WORDMASK;
+    if (a == 1 || b->nb_words == 0)
+        return;
+    if (a == 0) {
+        /* treat this as a == WORDCARRY and just shift everything left a WORD */
+        i = b->nb_words++;
+        w = b->words + i;
+        while (i--) {
+            *w = *(w - 1);
+            w--;
+        }
+        *w = 0;
+        return;
+    }
+    i = b->nb_words;
+    w = b->words;
+    c = 0;
+    while (i--) {
+        c += (uint16_t)*w * (uint16_t)a;
+        *(w++) = c & XFACE_WORDMASK;
+        c >>= XFACE_BITSPERWORD;
+    }
+    if (c) {
+        b->nb_words++;
+        *w = c & XFACE_WORDMASK;
+    }
+}
+
+const ProbRange ff_xface_probranges_per_level[4][3] = {
+    //  black      grey       white
+    { {  1, 255}, {251, 0}, {  4, 251} }, /* Top of tree almost always grey */
+    { {  1, 255}, {200, 0}, { 55, 200} },
+    { { 33, 223}, {159, 0}, { 64, 159} },
+    { {131,   0}, {  0, 0}, {125, 131} }, /* Grey disallowed at bottom */
+};
+
+const ProbRange ff_xface_probranges_2x2[16] = {
+    { 0,   0},  {38,   0}, {38,  38},  {13, 152},
+    {38,  76},  {13, 165}, {13, 178},  { 6, 230},
+    {38, 114},  {13, 191}, {13, 204},  { 6, 236},
+    {13, 217},  { 6, 242}, { 5, 248},  { 3, 253},
+};
+
+/*
+ * The "guess the next pixel" tables follow. Normally there are 12
+ * neighbour pixels used to give 1<<12 cases as we get closer to the
+ * upper left corner lesser numbers of neighbours are available.
+ *
+ * Each byte in the tables represents 8 boolean values starting from
+ * the most significant bit.
+ */
+
+static const uint8_t g_00[] = {
+    0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0xe3, 0xdf, 0x05, 0x17,
+    0x05, 0x0f, 0x00, 0x1b, 0x0f, 0xdf, 0x00, 0x04, 0x00, 0x00,
+    0x0d, 0x0f, 0x03, 0x7f, 0x00, 0x00, 0x00, 0x01, 0x00, 0x1d,
+    0x45, 0x2f, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x0a, 0xff, 0xff,
+    0x00, 0x04, 0x00, 0x05, 0x01, 0x3f, 0xcf, 0xff, 0x10, 0x01,
+    0x80, 0xc9, 0x0f, 0x0f, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
+    0x1b, 0x1f, 0xff, 0xff, 0x4f, 0x54, 0x07, 0x1f, 0x57, 0x47,
+    0xd7, 0x3d, 0xff, 0xff, 0x5f, 0x1f, 0x7f, 0xff, 0x7f, 0x7f,
+    0x05, 0x0f, 0x01, 0x0f, 0x0f, 0x5f, 0x9b, 0xdf, 0x7f, 0xff,
+    0x5f, 0x1d, 0x5f, 0xff, 0x0f, 0x1f, 0x0f, 0x5f, 0x03, 0x1f,
+    0x4f, 0x5f, 0xf7, 0x7f, 0x7f, 0xff, 0x0d, 0x0f, 0xfb, 0xff,
+    0xf7, 0xbf, 0x0f, 0x4f, 0xd7, 0x3f, 0x4f, 0x7f, 0xff, 0xff,
+    0x67, 0xbf, 0x56, 0x25, 0x1f, 0x7f, 0x9f, 0xff, 0x00, 0x00,
+    0x00, 0x05, 0x5f, 0x7f, 0x01, 0xdf, 0x14, 0x00, 0x05, 0x0f,
+    0x07, 0xa2, 0x09, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x5f,
+    0x18, 0xd7, 0x94, 0x71, 0x00, 0x05, 0x1f, 0xb7, 0x0c, 0x07,
+    0x0f, 0x0f, 0x00, 0x0f, 0x0f, 0x1f, 0x84, 0x8f, 0x05, 0x15,
+    0x05, 0x0f, 0x4f, 0xff, 0x87, 0xdf, 0x05, 0x01, 0x10, 0x00,
+    0x0f, 0x0f, 0x00, 0x08, 0x05, 0x04, 0x04, 0x01, 0x4f, 0xff,
+    0x9f, 0x8f, 0x4a, 0x40, 0x5f, 0x5f, 0xff, 0xfe, 0xdf, 0xff,
+    0x7f, 0xf7, 0xff, 0x7f, 0xff, 0xff, 0x7b, 0xff, 0x0f, 0xfd,
+    0xd7, 0x5f, 0x4f, 0x7f, 0x7f, 0xdf, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0x77, 0xdf, 0x7f, 0x4f, 0xef, 0xff, 0xff, 0x77, 0xff,
+    0xff, 0xff, 0x6f, 0xff, 0x0f, 0x4f, 0xff, 0xff, 0x9d, 0xff,
+    0x0f, 0xef, 0xff, 0xdf, 0x6f, 0xff, 0xff, 0xff, 0x4f, 0xff,
+    0xcd, 0x0f, 0x4f, 0xff, 0xff, 0xdf, 0x00, 0x00, 0x00, 0x0b,
+    0x05, 0x02, 0x02, 0x0f, 0x04, 0x00, 0x00, 0x0c, 0x01, 0x06,
+    0x00, 0x0f, 0x20, 0x03, 0x00, 0x00, 0x05, 0x0f, 0x40, 0x08,
+    0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x0c, 0x0f, 0x01, 0x00,
+    0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x14, 0x01, 0x05,
+    0x01, 0x15, 0xaf, 0x0f, 0x00, 0x01, 0x10, 0x00, 0x08, 0x00,
+    0x46, 0x0c, 0x20, 0x00, 0x88, 0x00, 0x0f, 0x15, 0xff, 0xdf,
+    0x02, 0x00, 0x00, 0x0f, 0x7f, 0x5f, 0xdb, 0xff, 0x4f, 0x3e,
+    0x05, 0x0f, 0x7f, 0xf7, 0x95, 0x4f, 0x0d, 0x0f, 0x01, 0x0f,
+    0x4f, 0x5f, 0x9f, 0xdf, 0x25, 0x0e, 0x0d, 0x0d, 0x4f, 0x7f,
+    0x8f, 0x0f, 0x0f, 0xfa, 0x04, 0x4f, 0x4f, 0xff, 0xf7, 0x77,
+    0x47, 0xed, 0x05, 0x0f, 0xff, 0xff, 0xdf, 0xff, 0x4f, 0x6f,
+    0xd8, 0x5f, 0x0f, 0x7f, 0xdf, 0x5f, 0x07, 0x0f, 0x94, 0x0d,
+    0x1f, 0xff, 0xff, 0xff, 0x00, 0x02, 0x00, 0x03, 0x46, 0x57,
+    0x01, 0x0d, 0x01, 0x08, 0x01, 0x0f, 0x47, 0x6c, 0x0d, 0x0f,
+    0x02, 0x00, 0x00, 0x00, 0x0b, 0x4f, 0x00, 0x08, 0x05, 0x00,
+    0x95, 0x01, 0x0f, 0x7f, 0x0c, 0x0f, 0x01, 0x0e, 0x00, 0x00,
+    0x0f, 0x41, 0x00, 0x00, 0x04, 0x24, 0x0d, 0x0f, 0x0f, 0x7f,
+    0xcf, 0xdf, 0x00, 0x00, 0x00, 0x00, 0x04, 0x40, 0x00, 0x00,
+    0x06, 0x26, 0xcf, 0x05, 0xcf, 0x7f, 0xdf, 0xdf, 0x00, 0x00,
+    0x17, 0x5f, 0xff, 0xfd, 0xff, 0xff, 0x46, 0x09, 0x4f, 0x5f,
+    0x7f, 0xfd, 0xdf, 0xff, 0x0a, 0x88, 0xa7, 0x7f, 0x7f, 0xff,
+    0xff, 0xff, 0x0f, 0x04, 0xdf, 0x7f, 0x4f, 0xff, 0x9f, 0xff,
+    0x0e, 0xe6, 0xdf, 0xff, 0x7f, 0xff, 0xff, 0xff, 0x0f, 0xec,
+    0x8f, 0x4f, 0x7f, 0xff, 0xdf, 0xff, 0x0f, 0xcf, 0xdf, 0xff,
+    0x6f, 0x7f, 0xff, 0xff, 0x03, 0x0c, 0x9d, 0x0f, 0x7f, 0xff,
+    0xff, 0xff,
+};
+
+static const uint8_t g_01[] = {
+    0x37, 0x73, 0x00, 0x19, 0x57, 0x7f, 0xf5, 0xfb, 0x70, 0x33,
+    0xf0, 0xf9, 0x7f, 0xff, 0xff, 0xff,
+};
+
+static const uint8_t g_02[] = {
+    0x50,
+};
+
+static const uint8_t g_10[] = {
+    0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0xf3, 0x5f, 0x84, 0x04,
+    0x17, 0x9f, 0x04, 0x23, 0x05, 0xff, 0x00, 0x00, 0x00, 0x02,
+    0x03, 0x03, 0x33, 0xd7, 0x05, 0x03, 0x5f, 0x3f, 0x17, 0x33,
+    0xff, 0xff, 0x00, 0x80, 0x02, 0x04, 0x12, 0x00, 0x11, 0x57,
+    0x05, 0x25, 0x05, 0x03, 0x35, 0xbf, 0x9f, 0xff, 0x07, 0x6f,
+    0x20, 0x40, 0x17, 0x06, 0xfa, 0xe8, 0x01, 0x07, 0x1f, 0x9f,
+    0x1f, 0xff, 0xff, 0xff,
+};
+
+static const uint8_t g_20[] = {
+    0x04, 0x00, 0x01, 0x01, 0x43, 0x2e, 0xff, 0x3f,
+};
+
+static const uint8_t g_30[] = {
+    0x11, 0x11, 0x11, 0x11, 0x51, 0x11, 0x13, 0x11, 0x11, 0x11,
+    0x13, 0x11, 0x11, 0x11, 0x33, 0x11, 0x13, 0x11, 0x13, 0x13,
+    0x13, 0x13, 0x31, 0x31, 0x11, 0x01, 0x11, 0x11, 0x71, 0x11,
+    0x11, 0x75,
+};
+
+static const uint8_t g_40[] = {
+    0x00, 0x0f, 0x00, 0x09, 0x00, 0x0d, 0x00, 0x0d, 0x00, 0x0f,
+    0x00, 0x4e, 0xe4, 0x0d, 0x10, 0x0f, 0x00, 0x0f, 0x44, 0x4f,
+    0x00, 0x1e, 0x0f, 0x0f, 0xae, 0xaf, 0x45, 0x7f, 0xef, 0xff,
+    0x0f, 0xff, 0x00, 0x09, 0x01, 0x11, 0x00, 0x01, 0x1c, 0xdd,
+    0x00, 0x15, 0x00, 0xff, 0x00, 0x10, 0x00, 0xfd, 0x00, 0x0f,
+    0x4f, 0x5f, 0x3d, 0xff, 0xff, 0xff, 0x4f, 0xff, 0x1c, 0xff,
+    0xdf, 0xff, 0x8f, 0xff, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x15,
+    0x01, 0x07, 0x00, 0x01, 0x02, 0x1f, 0x01, 0x11, 0x05, 0x7f,
+    0x00, 0x1f, 0x41, 0x57, 0x1f, 0xff, 0x05, 0x77, 0x0d, 0x5f,
+    0x4d, 0xff, 0x4f, 0xff, 0x0f, 0xff, 0x00, 0x00, 0x02, 0x05,
+    0x00, 0x11, 0x05, 0x7d, 0x10, 0x15, 0x2f, 0xff, 0x40, 0x50,
+    0x0d, 0xfd, 0x04, 0x0f, 0x07, 0x1f, 0x07, 0x7f, 0x0f, 0xbf,
+    0x0d, 0x7f, 0x0f, 0xff, 0x4d, 0x7d, 0x0f, 0xff,
+};
+
+static const uint8_t g_11[] = {
+    0x01, 0x13, 0x03, 0x7f,
+};
+
+static const uint8_t g_21[] = {
+    0x17,
+};
+
+static const uint8_t g_31[] = {
+    0x55, 0x57, 0x57, 0x7f,
+};
+
+static const uint8_t g_41[] = {
+    0x01, 0x01, 0x01, 0x1f, 0x03, 0x1f, 0x3f, 0xff,
+};
+
+static const uint8_t g_12[] = {
+    0x40,
+};
+
+static const uint8_t g_22[] = {
+    0x00,
+};
+
+static const uint8_t g_32[] = {
+    0x10,
+};
+
+static const uint8_t g_42[] = {
+    0x10,
+};
+
+void ff_xface_generate_face(uint8_t *dst, uint8_t * const src)
+{
+    int h, i, j, k, l, m;
+
+    for (j = 0; j < XFACE_HEIGHT; j++) {
+        for (i = 0; i < XFACE_WIDTH; i++) {
+            h = i + j * XFACE_WIDTH;
+            k = 0;
+
+            /*
+               Compute k, encoding the bits *before* the current one, contained in the
+               image buffer. That is, given the grid:
+
+                l      i
+                |      |
+                v      v
+               +--+--+--+--+--+
+          m -> | 1| 2| 3| 4| 5|
+               +--+--+--+--+--+
+               | 6| 7| 8| 9|10|
+               +--+--+--+--+--+
+          j -> |11|12| *|  |  |
+               +--+--+--+--+--+
+
+               the value k for the pixel marked as "*" will contain the bit encoding of
+               the values in the matrix marked from "1" to "12". In case the pixel is
+               near the border of the grid, the number of values contained within the
+               grid will be lesser than 12.
+             */
+
+            for (l = i - 2; l <= i + 2; l++) {
+                for (m = j - 2; m <= j; m++) {
+                    if (l >= i && m == j)
+                        continue;
+                    if (l > 0 && l <= XFACE_WIDTH && m > 0)
+                        k = 2*k + src[l + m * XFACE_WIDTH];
+                }
+            }
+
+            /*
+              Use the guess for the given position and the computed value of k.
+
+              The following table shows the number of digits in k, depending on
+              the position of the pixel, and shows the corresponding guess table
+              to use:
+
+                 i=1  i=2  i=3       i=w-1 i=w
+               +----+----+----+ ... +----+----+
+           j=1 |  0 |  1 |  2 |     |  2 |  2 |
+               |g22 |g12 |g02 |     |g42 |g32 |
+               +----+----+----+ ... +----+----+
+           j=2 |  3 |  5 |  7 |     |  6 |  5 |
+               |g21 |g11 |g01 |     |g41 |g31 |
+               +----+----+----+ ... +----+----+
+           j=3 |  5 |  9 | 12 |     | 10 |  8 |
+               |g20 |g10 |g00 |     |g40 |g30 |
+               +----+----+----+ ... +----+----+
+            */
+
+#define GEN(table) dst[h] ^= (table[k>>3]>>(7-(k&7)))&1
+
+            switch (i) {
+            case 1:
+                switch (j) {
+                case 1:  GEN(g_22); break;
+                case 2:  GEN(g_21); break;
+                default: GEN(g_20); break;
+                }
+                break;
+            case 2:
+                switch (j) {
+                case 1:  GEN(g_12); break;
+                case 2:  GEN(g_11); break;
+                default: GEN(g_10); break;
+                }
+                break;
+            case XFACE_WIDTH - 1:
+                switch (j) {
+                case 1:  GEN(g_42); break;
+                case 2:  GEN(g_41); break;
+                default: GEN(g_40); break;
+                }
+                break;
+            case XFACE_WIDTH:
+                switch (j) {
+                case 1:  GEN(g_32); break;
+                case 2:  GEN(g_31); break;
+                default: GEN(g_30); break;
+                }
+                break;
+            default:
+                switch (j) {
+                case 1:  GEN(g_02); break;
+                case 2:  GEN(g_01); break;
+                default: GEN(g_00); break;
+                }
+                break;
+            }
+        }
+    }
+}
diff --git a/libavcodec/xface.h b/libavcodec/xface.h
new file mode 100644
index 0000000..cd59ba0
--- /dev/null
+++ b/libavcodec/xface.h
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 1990 James Ashton - Sydney University
+ * Copyright (c) 2012 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
+ * X-Face common definitions.
+ */
+
+#include <stdint.h>
+
+/* define the face size - 48x48x1 */
+#define XFACE_WIDTH  48
+#define XFACE_HEIGHT 48
+#define XFACE_PIXELS (XFACE_WIDTH * XFACE_HEIGHT)
+
+/* compressed output uses the full range of printable characters.
+ * In ASCII these are in a contiguous block so we just need to know
+ * the first and last. The total number of printables is needed too. */
+#define XFACE_FIRST_PRINT '!'
+#define XFACE_LAST_PRINT '~'
+#define XFACE_PRINTS (XFACE_LAST_PRINT - XFACE_FIRST_PRINT + 1)
+
+/*
+ * Image is encoded as a big integer, using characters from '~' to
+ * '!', for a total of 92 symbols. In order to express 48x48=2304
+ * bits, we need a total of 354 digits, as given by:
+ * ceil(lg_92(2^2304)) = 354
+ */
+#define XFACE_MAX_DIGITS 354
+
+#define XFACE_BITSPERWORD 8
+#define XFACE_WORDCARRY (1 << XFACE_BITSPERWORD)
+#define XFACE_WORDMASK (XFACE_WORDCARRY - 1)
+
+#define XFACE_MAX_WORDS ((XFACE_PIXELS * 2 + XFACE_BITSPERWORD - 1) / XFACE_BITSPERWORD)
+
+/* Portable, very large unsigned integer arithmetic is needed.
+ * Implementation uses arrays of WORDs. */
+typedef struct {
+    int nb_words;
+    uint8_t words[XFACE_MAX_WORDS];
+} BigInt;
+
+/**
+ * Add a to b storing the result in b.
+ */
+void ff_big_add(BigInt *b, uint8_t a);
+
+/**
+ * Divide b by a storing the result in b and the remainder in the word
+ * pointed to by r.
+ */
+void ff_big_div(BigInt *b, uint8_t a, uint8_t *r);
+
+/**
+ * Multiply a by b storing the result in b.
+ */
+void ff_big_mul(BigInt *b, uint8_t a);
+
+/* Each face is encoded using 9 octrees of 16x16 each. Each level of the
+ * trees has varying probabilities of being white, grey or black.
+ * The table below is based on sampling many faces */
+enum XFaceColor { XFACE_COLOR_BLACK = 0, XFACE_COLOR_GREY, XFACE_COLOR_WHITE };
+
+/* Data of varying probabilities are encoded by a value in the range 0 - 255.
+ * The probability of the data determines the range of possible encodings.
+ * Offset gives the first possible encoding of the range. */
+typedef struct {
+    int range;
+    int offset;
+} ProbRange;
+
+extern const ProbRange ff_xface_probranges_per_level[4][3];
+
+extern const ProbRange ff_xface_probranges_2x2[16];
+
+void ff_xface_generate_face(uint8_t *dst, uint8_t * const src);
diff --git a/libavcodec/xfacedec.c b/libavcodec/xfacedec.c
new file mode 100644
index 0000000..7cccfa5
--- /dev/null
+++ b/libavcodec/xfacedec.c
@@ -0,0 +1,207 @@
+/*
+ * Copyright (c) 1990 James Ashton - Sydney University
+ * Copyright (c) 2012 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
+ * X-Face decoder, based on libcompface, by James Ashton.
+ */
+
+#include "libavutil/pixdesc.h"
+#include "avcodec.h"
+#include "bytestream.h"
+#include "xface.h"
+
+static int pop_integer(BigInt *b, const ProbRange *pranges)
+{
+    uint8_t r;
+    int i;
+
+    /* extract the last byte into r, and shift right b by 8 bits */
+    ff_big_div(b, 0, &r);
+
+    i = 0;
+    while (r < pranges->offset || r >= pranges->range + pranges->offset) {
+        pranges++;
+        i++;
+    }
+    ff_big_mul(b, pranges->range);
+    ff_big_add(b, r - pranges->offset);
+    return i;
+}
+
+static void pop_greys(BigInt *b, char *bitmap, int w, int h)
+{
+    if (w > 3) {
+        w /= 2;
+        h /= 2;
+        pop_greys(b, bitmap,                       w, h);
+        pop_greys(b, bitmap + w,                   w, h);
+        pop_greys(b, bitmap + XFACE_WIDTH * h,     w, h);
+        pop_greys(b, bitmap + XFACE_WIDTH * h + w, w, h);
+    } else {
+        w = pop_integer(b, ff_xface_probranges_2x2);
+        if (w & 1) bitmap[0]               = 1;
+        if (w & 2) bitmap[1]               = 1;
+        if (w & 4) bitmap[XFACE_WIDTH]     = 1;
+        if (w & 8) bitmap[XFACE_WIDTH + 1] = 1;
+    }
+}
+
+static void decode_block(BigInt *b, char *bitmap, int w, int h, int level)
+{
+    switch (pop_integer(b, &ff_xface_probranges_per_level[level][0])) {
+    case XFACE_COLOR_WHITE:
+        return;
+    case XFACE_COLOR_BLACK:
+        pop_greys(b, bitmap, w, h);
+        return;
+    default:
+        w /= 2;
+        h /= 2;
+        level++;
+        decode_block(b, bitmap,                       w, h, level);
+        decode_block(b, bitmap + w,                   w, h, level);
+        decode_block(b, bitmap + h * XFACE_WIDTH,     w, h, level);
+        decode_block(b, bitmap + w + h * XFACE_WIDTH, w, h, level);
+        return;
+    }
+}
+
+typedef struct XFaceContext {
+    AVFrame frame;
+    uint8_t bitmap[XFACE_PIXELS]; ///< image used internally for decoding
+} XFaceContext;
+
+static av_cold int xface_decode_init(AVCodecContext *avctx)
+{
+    XFaceContext *xface = avctx->priv_data;
+
+    avcodec_get_frame_defaults(&xface->frame);
+
+    if (avctx->width || avctx->height) {
+        if (avctx->width != XFACE_WIDTH || avctx->height != XFACE_HEIGHT) {
+            av_log(avctx, AV_LOG_ERROR,
+                   "Size value %dx%d not supported, only accepts a size of %dx%d\n",
+                   avctx->width, avctx->height, XFACE_WIDTH, XFACE_HEIGHT);
+            return AVERROR(EINVAL);
+        }
+    }
+
+    avctx->width   = XFACE_WIDTH;
+    avctx->height  = XFACE_HEIGHT;
+    avctx->pix_fmt = AV_PIX_FMT_MONOWHITE;
+
+    return 0;
+}
+
+static av_cold int xface_decode_close(AVCodecContext *avctx)
+{
+    XFaceContext *xface = avctx->priv_data;
+
+    if (xface->frame.data[0])
+        avctx->release_buffer(avctx, &xface->frame);
+
+    return 0;
+}
+
+static int xface_decode_frame(AVCodecContext *avctx,
+                              void *data, int *data_size,
+                              AVPacket *avpkt)
+{
+    XFaceContext *xface = avctx->priv_data;
+    int ret, i, j, k;
+    uint8_t byte;
+    BigInt b = {0};
+    char *buf;
+    int64_t c;
+
+    if (xface->frame.data[0])
+        avctx->release_buffer(avctx, &xface->frame);
+    xface->frame.data[0] = NULL;
+    if ((ret = avctx->get_buffer(avctx, &xface->frame)) < 0)
+        return ret;
+    xface->frame.reference = 0;
+
+    for (i = 0, k = 0; avpkt->data[i] && i < avpkt->size; i++) {
+        c = avpkt->data[i];
+
+        /* ignore invalid digits */
+        if (c < XFACE_FIRST_PRINT || c > XFACE_LAST_PRINT)
+            continue;
+
+        if (++k > XFACE_MAX_DIGITS) {
+            av_log(avctx, AV_LOG_WARNING,
+                   "Buffer is longer than expected, truncating at byte %d\n", i);
+            break;
+        }
+        ff_big_mul(&b, XFACE_PRINTS);
+        ff_big_add(&b, c - XFACE_FIRST_PRINT);
+    }
+
+    /* decode image and put it in bitmap */
+    memset(xface->bitmap, 0, XFACE_PIXELS);
+    buf = xface->bitmap;
+    decode_block(&b, buf,                         16, 16, 0);
+    decode_block(&b, buf + 16,                    16, 16, 0);
+    decode_block(&b, buf + 32,                    16, 16, 0);
+    decode_block(&b, buf + XFACE_WIDTH * 16,      16, 16, 0);
+    decode_block(&b, buf + XFACE_WIDTH * 16 + 16, 16, 16, 0);
+    decode_block(&b, buf + XFACE_WIDTH * 16 + 32, 16, 16, 0);
+    decode_block(&b, buf + XFACE_WIDTH * 32     , 16, 16, 0);
+    decode_block(&b, buf + XFACE_WIDTH * 32 + 16, 16, 16, 0);
+    decode_block(&b, buf + XFACE_WIDTH * 32 + 32, 16, 16, 0);
+
+    ff_xface_generate_face(xface->bitmap, xface->bitmap);
+
+    /* convert image from 1=black 0=white bitmap to MONOWHITE */
+    buf = xface->frame.data[0];
+    for (i = 0, j = 0, k = 0, byte = 0; i < XFACE_PIXELS; i++) {
+        byte += xface->bitmap[i];
+        if (k == 7) {
+            buf[j++] = byte;
+            byte = k = 0;
+        } else {
+            k++;
+            byte <<= 1;
+        }
+        if (j == XFACE_WIDTH/8) {
+            j = 0;
+            buf += xface->frame.linesize[0];
+        }
+    }
+
+    *data_size = sizeof(AVFrame);
+    *(AVFrame*)data = xface->frame;
+
+    return avpkt->size;
+}
+
+AVCodec ff_xface_decoder = {
+    .name           = "xface",
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = AV_CODEC_ID_XFACE,
+    .priv_data_size = sizeof(XFaceContext),
+    .init           = xface_decode_init,
+    .close          = xface_decode_close,
+    .decode         = xface_decode_frame,
+    .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_MONOWHITE, AV_PIX_FMT_NONE },
+    .long_name      = NULL_IF_CONFIG_SMALL("X-face image"),
+};
diff --git a/libavcodec/xfaceenc.c b/libavcodec/xfaceenc.c
new file mode 100644
index 0000000..5206afd
--- /dev/null
+++ b/libavcodec/xfaceenc.c
@@ -0,0 +1,238 @@
+/*
+ * Copyright (c) 1990 James Ashton - Sydney University
+ * Copyright (c) 2012 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
+ * X-Face encoder, based on libcompface, by James Ashton.
+ */
+
+#include "xface.h"
+#include "avcodec.h"
+#include "internal.h"
+
+typedef struct XFaceContext {
+    AVClass *class;
+    uint8_t bitmap[XFACE_PIXELS]; ///< image used internally for decoding
+    int max_line_len;             ///< max line length for compressed data
+    int set_header;               ///< set X-Face header in the output
+} XFaceContext;
+
+static int all_same(char *bitmap, int w, int h)
+{
+    char val, *row;
+    int x;
+
+    val = *bitmap;
+    while (h--) {
+        row = bitmap;
+        x = w;
+        while (x--)
+            if (*(row++) != val)
+                return 0;
+        bitmap += XFACE_WIDTH;
+    }
+    return 1;
+}
+
+static int all_black(char *bitmap, int w, int h)
+{
+    if (w > 3) {
+        w /= 2;
+        h /= 2;
+        return (all_black(bitmap, w, h) && all_black(bitmap + w, w, h) &&
+                all_black(bitmap + XFACE_WIDTH * h, w, h) &&
+                all_black(bitmap + XFACE_WIDTH * h + w, w, h));
+    } else {
+        /* at least one pixel in the 2x2 grid is non-zero */
+        return *bitmap || *(bitmap + 1) ||
+               *(bitmap + XFACE_WIDTH) || *(bitmap + XFACE_WIDTH + 1);
+    }
+}
+
+static int all_white(char *bitmap, int w, int h)
+{
+    return *bitmap == 0 && all_same(bitmap, w, h);
+}
+
+typedef struct {
+    const ProbRange *prob_ranges[XFACE_PIXELS*2];
+    int prob_ranges_idx;
+} ProbRangesQueue;
+
+static inline int pq_push(ProbRangesQueue *pq, const ProbRange *p)
+{
+    if (pq->prob_ranges_idx >= XFACE_PIXELS * 2 - 1)
+        return -1;
+    pq->prob_ranges[pq->prob_ranges_idx++] = p;
+    return 0;
+}
+
+static void push_greys(ProbRangesQueue *pq, char *bitmap, int w, int h)
+{
+    if (w > 3) {
+        w /= 2;
+        h /= 2;
+        push_greys(pq, bitmap,                       w, h);
+        push_greys(pq, bitmap + w,                   w, h);
+        push_greys(pq, bitmap + XFACE_WIDTH * h,     w, h);
+        push_greys(pq, bitmap + XFACE_WIDTH * h + w, w, h);
+    } else {
+        const ProbRange *p = ff_xface_probranges_2x2 +
+                 *bitmap +
+            2 * *(bitmap + 1) +
+            4 * *(bitmap + XFACE_WIDTH) +
+            8 * *(bitmap + XFACE_WIDTH + 1);
+        pq_push(pq, p);
+    }
+}
+
+static void encode_block(char *bitmap, int w, int h, int level, ProbRangesQueue *pq)
+{
+    if (all_white(bitmap, w, h)) {
+        pq_push(pq, &ff_xface_probranges_per_level[level][XFACE_COLOR_WHITE]);
+    } else if (all_black(bitmap, w, h)) {
+        pq_push(pq, &ff_xface_probranges_per_level[level][XFACE_COLOR_BLACK]);
+        push_greys(pq, bitmap, w, h);
+    } else {
+        pq_push(pq, &ff_xface_probranges_per_level[level][XFACE_COLOR_GREY]);
+        w /= 2;
+        h /= 2;
+        level++;
+        encode_block(bitmap,                       w, h, level, pq);
+        encode_block(bitmap + w,                   w, h, level, pq);
+        encode_block(bitmap + h * XFACE_WIDTH,     w, h, level, pq);
+        encode_block(bitmap + w + h * XFACE_WIDTH, w, h, level, pq);
+    }
+}
+
+static av_cold int xface_encode_init(AVCodecContext *avctx)
+{
+    avctx->coded_frame = avcodec_alloc_frame();
+    if (!avctx->coded_frame)
+        return AVERROR(ENOMEM);
+    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
+
+    return 0;
+}
+
+static void push_integer(BigInt *b, const ProbRange *prange)
+{
+    uint8_t r;
+
+    ff_big_div(b, prange->range, &r);
+    ff_big_mul(b, 0);
+    ff_big_add(b, r + prange->offset);
+}
+
+static int xface_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
+                              const AVFrame *frame, int *got_packet)
+{
+    XFaceContext *xface = avctx->priv_data;
+    ProbRangesQueue pq = {{ 0 }, 0};
+    uint8_t bitmap_copy[XFACE_PIXELS];
+    BigInt b = {0};
+    int i, j, k, ret = 0;
+    const uint8_t *buf;
+    uint8_t *p;
+    char intbuf[XFACE_MAX_DIGITS];
+
+    if (avctx->width || avctx->height) {
+        if (avctx->width != XFACE_WIDTH || avctx->height != XFACE_HEIGHT) {
+            av_log(avctx, AV_LOG_ERROR,
+                   "Size value %dx%d not supported, only accepts a size of %dx%d\n",
+                   avctx->width, avctx->height, XFACE_WIDTH, XFACE_HEIGHT);
+            return AVERROR(EINVAL);
+        }
+    }
+    avctx->width  = XFACE_WIDTH;
+    avctx->height = XFACE_HEIGHT;
+
+    /* convert image from MONOWHITE to 1=black 0=white bitmap */
+    buf = frame->data[0];
+    i = j = 0;
+    do {
+        for (k = 0; k < 8; k++)
+            xface->bitmap[i++] = (buf[j]>>(7-k))&1;
+        if (++j == XFACE_WIDTH/8) {
+            buf += frame->linesize[0];
+            j = 0;
+        }
+    } while (i < XFACE_PIXELS);
+
+    /* create a copy of bitmap */
+    memcpy(bitmap_copy, xface->bitmap, XFACE_PIXELS);
+    ff_xface_generate_face(xface->bitmap, bitmap_copy);
+
+    encode_block(xface->bitmap,                         16, 16, 0, &pq);
+    encode_block(xface->bitmap + 16,                    16, 16, 0, &pq);
+    encode_block(xface->bitmap + 32,                    16, 16, 0, &pq);
+    encode_block(xface->bitmap + XFACE_WIDTH * 16,      16, 16, 0, &pq);
+    encode_block(xface->bitmap + XFACE_WIDTH * 16 + 16, 16, 16, 0, &pq);
+    encode_block(xface->bitmap + XFACE_WIDTH * 16 + 32, 16, 16, 0, &pq);
+    encode_block(xface->bitmap + XFACE_WIDTH * 32,      16, 16, 0, &pq);
+    encode_block(xface->bitmap + XFACE_WIDTH * 32 + 16, 16, 16, 0, &pq);
+    encode_block(xface->bitmap + XFACE_WIDTH * 32 + 32, 16, 16, 0, &pq);
+
+    while (pq.prob_ranges_idx > 0)
+        push_integer(&b, pq.prob_ranges[--pq.prob_ranges_idx]);
+
+    /* write the inverted big integer in b to intbuf */
+    i = 0;
+    while (b.nb_words) {
+        uint8_t r;
+        ff_big_div(&b, XFACE_PRINTS, &r);
+        intbuf[i++] = r + XFACE_FIRST_PRINT;
+    }
+
+    if ((ret = ff_alloc_packet2(avctx, pkt, i+2)) < 0)
+        return ret;
+
+    /* revert the number, and close the buffer */
+    p = pkt->data;
+    while (--i >= 0)
+        *(p++) = intbuf[i];
+    *(p++) = '\n';
+    *(p++) = 0;
+
+    pkt->flags |= AV_PKT_FLAG_KEY;
+    *got_packet = 1;
+
+    return 0;
+}
+
+static av_cold int xface_encode_close(AVCodecContext *avctx)
+{
+    av_freep(&avctx->coded_frame);
+
+    return 0;
+}
+
+AVCodec ff_xface_encoder = {
+    .name           = "xface",
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = AV_CODEC_ID_XFACE,
+    .priv_data_size = sizeof(XFaceContext),
+    .init           = xface_encode_init,
+    .close          = xface_encode_close,
+    .encode2        = xface_encode_frame,
+    .pix_fmts       = (const enum PixelFormat[]) { AV_PIX_FMT_MONOWHITE, AV_PIX_FMT_NONE },
+    .long_name      = NULL_IF_CONFIG_SMALL("X-face image"),
+};
diff --git a/libavcodec/xl.c b/libavcodec/xl.c
index b0f6e93..8c5ccd3 100644
--- a/libavcodec/xl.c
+++ b/libavcodec/xl.c
@@ -37,7 +37,8 @@
    0,   1,   2,   3,   4,   5,   6,   7,
    8,   9,  12,  15,  20,  25,  34,  46,
   64,  82,  94, 103, 108, 113, 116, 119,
- 120, 121, 122, 123, 124, 125, 126, 127};
+ 120, 121, 122, 123, 124, 125, 126, 127
+};
 
 static int decode_frame(AVCodecContext *avctx,
                         void *data, int *data_size,
@@ -48,7 +49,7 @@
     VideoXLContext * const a = avctx->priv_data;
     AVFrame * const p = &a->pic;
     uint8_t *Y, *U, *V;
-    int i, j;
+    int i, j, ret;
     int stride;
     uint32_t val;
     int y0, y1, y2, y3 = 0, c0 = 0, c1 = 0;
@@ -63,16 +64,16 @@
         return AVERROR_INVALIDDATA;
     }
 
-    if(p->data[0])
+    if (p->data[0])
         avctx->release_buffer(avctx, p);
 
     p->reference = 0;
-    if(avctx->get_buffer(avctx, p) < 0){
+    if ((ret = avctx->get_buffer(avctx, p)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
+        return ret;
     }
-    p->pict_type= AV_PICTURE_TYPE_I;
-    p->key_frame= 1;
+    p->pict_type = AV_PICTURE_TYPE_I;
+    p->key_frame = 1;
 
     Y = a->pic.data[0];
     U = a->pic.data[1];
@@ -132,16 +133,18 @@
     return buf_size;
 }
 
-static av_cold int decode_init(AVCodecContext *avctx){
+static av_cold int decode_init(AVCodecContext *avctx)
+{
     VideoXLContext * const a = avctx->priv_data;
 
     avcodec_get_frame_defaults(&a->pic);
-    avctx->pix_fmt= PIX_FMT_YUV411P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV411P;
 
     return 0;
 }
 
-static av_cold int decode_end(AVCodecContext *avctx){
+static av_cold int decode_end(AVCodecContext *avctx)
+{
     VideoXLContext * const a = avctx->priv_data;
     AVFrame *pic = &a->pic;
 
diff --git a/libavcodec/xsubdec.c b/libavcodec/xsubdec.c
index bef4838..d3367b0 100644
--- a/libavcodec/xsubdec.c
+++ b/libavcodec/xsubdec.c
@@ -26,7 +26,7 @@
 #include "bytestream.h"
 
 static av_cold int decode_init(AVCodecContext *avctx) {
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
     return 0;
 }
 
diff --git a/libavcodec/xwddec.c b/libavcodec/xwddec.c
index ea7da84..ef99a6b 100644
--- a/libavcodec/xwddec.c
+++ b/libavcodec/xwddec.c
@@ -153,22 +153,22 @@
         return AVERROR_PATCHWELCOME;
     }
 
-    avctx->pix_fmt = PIX_FMT_NONE;
+    avctx->pix_fmt = AV_PIX_FMT_NONE;
     switch (vclass) {
     case XWD_STATIC_GRAY:
     case XWD_GRAY_SCALE:
         if (bpp != 1 && bpp != 8)
             return AVERROR_INVALIDDATA;
         if (pixdepth == 1) {
-            avctx->pix_fmt = PIX_FMT_MONOWHITE;
+            avctx->pix_fmt = AV_PIX_FMT_MONOWHITE;
         } else if (pixdepth == 8) {
-            avctx->pix_fmt = PIX_FMT_GRAY8;
+            avctx->pix_fmt = AV_PIX_FMT_GRAY8;
         }
         break;
     case XWD_STATIC_COLOR:
     case XWD_PSEUDO_COLOR:
         if (bpp == 8)
-            avctx->pix_fmt = PIX_FMT_PAL8;
+            avctx->pix_fmt = AV_PIX_FMT_PAL8;
         break;
     case XWD_TRUE_COLOR:
     case XWD_DIRECT_COLOR:
@@ -176,24 +176,24 @@
             return AVERROR_INVALIDDATA;
         if (bpp == 16 && pixdepth == 15) {
             if (rgb[0] == 0x7C00 && rgb[1] == 0x3E0 && rgb[2] == 0x1F)
-                avctx->pix_fmt = be ? PIX_FMT_RGB555BE : PIX_FMT_RGB555LE;
+                avctx->pix_fmt = be ? AV_PIX_FMT_RGB555BE : AV_PIX_FMT_RGB555LE;
             else if (rgb[0] == 0x1F && rgb[1] == 0x3E0 && rgb[2] == 0x7C00)
-                avctx->pix_fmt = be ? PIX_FMT_BGR555BE : PIX_FMT_BGR555LE;
+                avctx->pix_fmt = be ? AV_PIX_FMT_BGR555BE : AV_PIX_FMT_BGR555LE;
         } else if (bpp == 16 && pixdepth == 16) {
             if (rgb[0] == 0xF800 && rgb[1] == 0x7E0 && rgb[2] == 0x1F)
-                avctx->pix_fmt = be ? PIX_FMT_RGB565BE : PIX_FMT_RGB565LE;
+                avctx->pix_fmt = be ? AV_PIX_FMT_RGB565BE : AV_PIX_FMT_RGB565LE;
             else if (rgb[0] == 0x1F && rgb[1] == 0x7E0 && rgb[2] == 0xF800)
-                avctx->pix_fmt = be ? PIX_FMT_BGR565BE : PIX_FMT_BGR565LE;
+                avctx->pix_fmt = be ? AV_PIX_FMT_BGR565BE : AV_PIX_FMT_BGR565LE;
         } else if (bpp == 24) {
             if (rgb[0] == 0xFF0000 && rgb[1] == 0xFF00 && rgb[2] == 0xFF)
-                avctx->pix_fmt = be ? PIX_FMT_RGB24 : PIX_FMT_BGR24;
+                avctx->pix_fmt = be ? AV_PIX_FMT_RGB24 : AV_PIX_FMT_BGR24;
             else if (rgb[0] == 0xFF && rgb[1] == 0xFF00 && rgb[2] == 0xFF0000)
-                avctx->pix_fmt = be ? PIX_FMT_BGR24 : PIX_FMT_RGB24;
+                avctx->pix_fmt = be ? AV_PIX_FMT_BGR24 : AV_PIX_FMT_RGB24;
         } else if (bpp == 32) {
             if (rgb[0] == 0xFF0000 && rgb[1] == 0xFF00 && rgb[2] == 0xFF)
-                avctx->pix_fmt = be ? PIX_FMT_ARGB : PIX_FMT_BGRA;
+                avctx->pix_fmt = be ? AV_PIX_FMT_ARGB : AV_PIX_FMT_BGRA;
             else if (rgb[0] == 0xFF && rgb[1] == 0xFF00 && rgb[2] == 0xFF0000)
-                avctx->pix_fmt = be ? PIX_FMT_ABGR : PIX_FMT_RGBA;
+                avctx->pix_fmt = be ? AV_PIX_FMT_ABGR : AV_PIX_FMT_RGBA;
         }
         bytestream2_skipu(&gb, ncolors * XWD_CMAP_SIZE);
         break;
@@ -202,7 +202,7 @@
         return AVERROR_INVALIDDATA;
     }
 
-    if (avctx->pix_fmt == PIX_FMT_NONE) {
+    if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
         av_log_ask_for_sample(avctx, "unknown file: bpp %d, pixdepth %d, vclass %d\n", bpp, pixdepth, vclass);
         return AVERROR_PATCHWELCOME;
     }
@@ -219,7 +219,7 @@
     p->key_frame = 1;
     p->pict_type = AV_PICTURE_TYPE_I;
 
-    if (avctx->pix_fmt == PIX_FMT_PAL8) {
+    if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
         uint32_t *dst = (uint32_t *)p->data[1];
         uint8_t red, green, blue;
 
diff --git a/libavcodec/xwdenc.c b/libavcodec/xwdenc.c
index e6ddfbb..fac3d0b 100644
--- a/libavcodec/xwdenc.c
+++ b/libavcodec/xwdenc.c
@@ -42,26 +42,27 @@
 static int xwd_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
                             const AVFrame *p, int *got_packet)
 {
-    enum PixelFormat pix_fmt = avctx->pix_fmt;
+    enum AVPixelFormat pix_fmt = avctx->pix_fmt;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
     uint32_t pixdepth, bpp, bpad, ncolors = 0, lsize, vclass, be = 0;
     uint32_t rgb[3] = { 0 }, bitorder = 0;
     uint32_t header_size;
     int i, out_size, ret;
     uint8_t *ptr, *buf;
 
-    pixdepth = av_get_bits_per_pixel(&av_pix_fmt_descriptors[pix_fmt]);
-    if (av_pix_fmt_descriptors[pix_fmt].flags & PIX_FMT_BE)
+    pixdepth = av_get_bits_per_pixel(desc);
+    if (desc->flags & PIX_FMT_BE)
         be = 1;
     switch (pix_fmt) {
-    case PIX_FMT_ARGB:
-    case PIX_FMT_BGRA:
-    case PIX_FMT_RGBA:
-    case PIX_FMT_ABGR:
-        if (pix_fmt == PIX_FMT_ARGB ||
-            pix_fmt == PIX_FMT_ABGR)
+    case AV_PIX_FMT_ARGB:
+    case AV_PIX_FMT_BGRA:
+    case AV_PIX_FMT_RGBA:
+    case AV_PIX_FMT_ABGR:
+        if (pix_fmt == AV_PIX_FMT_ARGB ||
+            pix_fmt == AV_PIX_FMT_ABGR)
             be = 1;
-        if (pix_fmt == PIX_FMT_ABGR ||
-            pix_fmt == PIX_FMT_RGBA) {
+        if (pix_fmt == AV_PIX_FMT_ABGR ||
+            pix_fmt == AV_PIX_FMT_RGBA) {
             rgb[0] = 0xFF;
             rgb[1] = 0xFF00;
             rgb[2] = 0xFF0000;
@@ -75,9 +76,9 @@
         vclass   = XWD_TRUE_COLOR;
         bpad     = 32;
         break;
-    case PIX_FMT_BGR24:
-    case PIX_FMT_RGB24:
-        if (pix_fmt == PIX_FMT_RGB24)
+    case AV_PIX_FMT_BGR24:
+    case AV_PIX_FMT_RGB24:
+        if (pix_fmt == AV_PIX_FMT_RGB24)
             be = 1;
         bpp      = 24;
         vclass   = XWD_TRUE_COLOR;
@@ -86,12 +87,12 @@
         rgb[1]   = 0xFF00;
         rgb[2]   = 0xFF;
         break;
-    case PIX_FMT_RGB565LE:
-    case PIX_FMT_RGB565BE:
-    case PIX_FMT_BGR565LE:
-    case PIX_FMT_BGR565BE:
-        if (pix_fmt == PIX_FMT_BGR565LE ||
-            pix_fmt == PIX_FMT_BGR565BE) {
+    case AV_PIX_FMT_RGB565LE:
+    case AV_PIX_FMT_RGB565BE:
+    case AV_PIX_FMT_BGR565LE:
+    case AV_PIX_FMT_BGR565BE:
+        if (pix_fmt == AV_PIX_FMT_BGR565LE ||
+            pix_fmt == AV_PIX_FMT_BGR565BE) {
             rgb[0] = 0x1F;
             rgb[1] = 0x7E0;
             rgb[2] = 0xF800;
@@ -104,12 +105,12 @@
         vclass   = XWD_TRUE_COLOR;
         bpad     = 16;
         break;
-    case PIX_FMT_RGB555LE:
-    case PIX_FMT_RGB555BE:
-    case PIX_FMT_BGR555LE:
-    case PIX_FMT_BGR555BE:
-        if (pix_fmt == PIX_FMT_BGR555LE ||
-            pix_fmt == PIX_FMT_BGR555BE) {
+    case AV_PIX_FMT_RGB555LE:
+    case AV_PIX_FMT_RGB555BE:
+    case AV_PIX_FMT_BGR555LE:
+    case AV_PIX_FMT_BGR555BE:
+        if (pix_fmt == AV_PIX_FMT_BGR555LE ||
+            pix_fmt == AV_PIX_FMT_BGR555BE) {
             rgb[0] = 0x1F;
             rgb[1] = 0x3E0;
             rgb[2] = 0x7C00;
@@ -122,22 +123,22 @@
         vclass   = XWD_TRUE_COLOR;
         bpad     = 16;
         break;
-    case PIX_FMT_RGB8:
-    case PIX_FMT_BGR8:
-    case PIX_FMT_RGB4_BYTE:
-    case PIX_FMT_BGR4_BYTE:
-    case PIX_FMT_PAL8:
+    case AV_PIX_FMT_RGB8:
+    case AV_PIX_FMT_BGR8:
+    case AV_PIX_FMT_RGB4_BYTE:
+    case AV_PIX_FMT_BGR4_BYTE:
+    case AV_PIX_FMT_PAL8:
         bpp      = 8;
         vclass   = XWD_PSEUDO_COLOR;
         bpad     = 8;
         ncolors  = 256;
         break;
-    case PIX_FMT_GRAY8:
+    case AV_PIX_FMT_GRAY8:
         bpp      = 8;
         bpad     = 8;
         vclass   = XWD_STATIC_GRAY;
         break;
-    case PIX_FMT_MONOWHITE:
+    case AV_PIX_FMT_MONOWHITE:
         be       = 1;
         bitorder = 1;
         bpp      = 1;
@@ -229,27 +230,27 @@
     .init         = xwd_encode_init,
     .encode2      = xwd_encode_frame,
     .close        = xwd_encode_close,
-    .pix_fmts     = (const enum PixelFormat[]) { PIX_FMT_BGRA,
-                                                 PIX_FMT_RGBA,
-                                                 PIX_FMT_ARGB,
-                                                 PIX_FMT_ABGR,
-                                                 PIX_FMT_RGB24,
-                                                 PIX_FMT_BGR24,
-                                                 PIX_FMT_RGB565BE,
-                                                 PIX_FMT_RGB565LE,
-                                                 PIX_FMT_BGR565BE,
-                                                 PIX_FMT_BGR565LE,
-                                                 PIX_FMT_RGB555BE,
-                                                 PIX_FMT_RGB555LE,
-                                                 PIX_FMT_BGR555BE,
-                                                 PIX_FMT_BGR555LE,
-                                                 PIX_FMT_RGB8,
-                                                 PIX_FMT_BGR8,
-                                                 PIX_FMT_RGB4_BYTE,
-                                                 PIX_FMT_BGR4_BYTE,
-                                                 PIX_FMT_PAL8,
-                                                 PIX_FMT_GRAY8,
-                                                 PIX_FMT_MONOWHITE,
-                                                 PIX_FMT_NONE },
+    .pix_fmts     = (const enum AVPixelFormat[]) { AV_PIX_FMT_BGRA,
+                                                 AV_PIX_FMT_RGBA,
+                                                 AV_PIX_FMT_ARGB,
+                                                 AV_PIX_FMT_ABGR,
+                                                 AV_PIX_FMT_RGB24,
+                                                 AV_PIX_FMT_BGR24,
+                                                 AV_PIX_FMT_RGB565BE,
+                                                 AV_PIX_FMT_RGB565LE,
+                                                 AV_PIX_FMT_BGR565BE,
+                                                 AV_PIX_FMT_BGR565LE,
+                                                 AV_PIX_FMT_RGB555BE,
+                                                 AV_PIX_FMT_RGB555LE,
+                                                 AV_PIX_FMT_BGR555BE,
+                                                 AV_PIX_FMT_BGR555LE,
+                                                 AV_PIX_FMT_RGB8,
+                                                 AV_PIX_FMT_BGR8,
+                                                 AV_PIX_FMT_RGB4_BYTE,
+                                                 AV_PIX_FMT_BGR4_BYTE,
+                                                 AV_PIX_FMT_PAL8,
+                                                 AV_PIX_FMT_GRAY8,
+                                                 AV_PIX_FMT_MONOWHITE,
+                                                 AV_PIX_FMT_NONE },
     .long_name    = NULL_IF_CONFIG_SMALL("XWD (X Window Dump) image"),
 };
diff --git a/libavcodec/xxan.c b/libavcodec/xxan.c
index 08372ee..47b3544 100644
--- a/libavcodec/xxan.c
+++ b/libavcodec/xxan.c
@@ -22,11 +22,10 @@
 
 #include "avcodec.h"
 #include "libavutil/intreadwrite.h"
+#include "libavutil/mem.h"
 #include "bytestream.h"
 #define BITSTREAM_READER_LE
 #include "get_bits.h"
-// for av_memcpy_backptr
-#include "libavutil/lzo.h"
 
 typedef struct XanContext {
     AVCodecContext *avctx;
@@ -44,7 +43,7 @@
 
     s->avctx = avctx;
 
-    avctx->pix_fmt = PIX_FMT_YUV420P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV420P;
 
     s->buffer_size = avctx->width * avctx->height;
     s->y_buffer = av_malloc(s->buffer_size);
@@ -134,7 +133,7 @@
             }
             if (dest + size + size2 > dest_end ||
                 dest - orig_dest + size < back)
-                return -1;
+                return AVERROR_INVALIDDATA;
             bytestream2_get_buffer(&s->gb, dest, size);
             dest += size;
             av_memcpy_backptr(dest, back, size2);
@@ -144,7 +143,7 @@
 
             size = finish ? opcode & 3 : ((opcode & 0x1f) << 2) + 4;
             if (dest_end - dest < size)
-                return -1;
+                return AVERROR_INVALIDDATA;
             bytestream2_get_buffer(&s->gb, dest, size);
             dest += size;
             if (finish)
@@ -168,7 +167,7 @@
         return 0;
     if (chroma_off + 4 >= bytestream2_get_bytes_left(&s->gb)) {
         av_log(avctx, AV_LOG_ERROR, "Invalid chroma block position\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
     bytestream2_seek(&s->gb, chroma_off + 4, SEEK_SET);
     mode        = bytestream2_get_le16(&s->gb);
@@ -179,7 +178,7 @@
 
     if (offset >= bytestream2_get_bytes_left(&s->gb)) {
         av_log(avctx, AV_LOG_ERROR, "Invalid chroma block offset\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     bytestream2_skip(&s->gb, offset);
@@ -187,7 +186,7 @@
     dec_size = xan_unpack(s, s->scratch_buffer, s->buffer_size);
     if (dec_size < 0) {
         av_log(avctx, AV_LOG_ERROR, "Chroma unpacking failed\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     U = s->pic.data[1];
@@ -277,7 +276,8 @@
         ybuf[j+1] = cur << 1;
         last = cur;
     }
-    ybuf[j]  = last << 1;
+    if(j < avctx->width)
+        ybuf[j]  = last << 1;
     prev_buf = ybuf;
     ybuf += avctx->width;
 
@@ -290,7 +290,8 @@
             ybuf[j+1] = cur << 1;
             last = cur;
         }
-        ybuf[j] = last << 1;
+        if(j < avctx->width)
+            ybuf[j] = last << 1;
         prev_buf = ybuf;
         ybuf += avctx->width;
     }
@@ -350,7 +351,8 @@
             ybuf[j+1] = cur;
             last = cur;
         }
-        ybuf[j] = last;
+        if(j < avctx->width)
+            ybuf[j] = last;
         ybuf += avctx->width;
     }
 
@@ -394,7 +396,7 @@
         break;
     default:
         av_log(avctx, AV_LOG_ERROR, "Unknown frame type %d\n", ftype);
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
     if (ret)
         return ret;
diff --git a/libavcodec/y41pdec.c b/libavcodec/y41pdec.c
index 97bcc99..e283690 100644
--- a/libavcodec/y41pdec.c
+++ b/libavcodec/y41pdec.c
@@ -24,7 +24,7 @@
 
 static av_cold int y41p_decode_init(AVCodecContext *avctx)
 {
-    avctx->pix_fmt             = PIX_FMT_YUV411P;
+    avctx->pix_fmt             = AV_PIX_FMT_YUV411P;
     avctx->bits_per_raw_sample = 12;
 
     if (avctx->width & 7) {
diff --git a/libavcodec/y41penc.c b/libavcodec/y41penc.c
index b8ebfbc..f0c212b 100644
--- a/libavcodec/y41penc.c
+++ b/libavcodec/y41penc.c
@@ -97,7 +97,7 @@
     .init         = y41p_encode_init,
     .encode2      = y41p_encode_frame,
     .close        = y41p_encode_close,
-    .pix_fmts     = (const enum PixelFormat[]) { PIX_FMT_YUV411P,
-                                                 PIX_FMT_NONE },
+    .pix_fmts     = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV411P,
+                                                 AV_PIX_FMT_NONE },
     .long_name    = NULL_IF_CONFIG_SMALL("Uncompressed YUV 4:1:1 12-bit"),
 };
diff --git a/libavcodec/yop.c b/libavcodec/yop.c
index 070ba76..255ed32 100644
--- a/libavcodec/yop.c
+++ b/libavcodec/yop.c
@@ -85,7 +85,6 @@
 
     if (avctx->width & 1 || avctx->height & 1 ||
         av_image_check_size(avctx->width, avctx->height, 0, avctx) < 0) {
-        av_log(avctx, AV_LOG_ERROR, "YOP has invalid dimensions\n");
         return -1;
     }
 
@@ -94,7 +93,7 @@
         return AVERROR_INVALIDDATA;
     }
 
-    avctx->pix_fmt = PIX_FMT_PAL8;
+    avctx->pix_fmt = AV_PIX_FMT_PAL8;
 
     avcodec_get_frame_defaults(&s->frame);
     s->num_pal_colors = avctx->extradata[0];
@@ -104,7 +103,7 @@
     if (s->num_pal_colors + s->first_color[0] > 256 ||
         s->num_pal_colors + s->first_color[1] > 256) {
         av_log(avctx, AV_LOG_ERROR,
-               "YOP: palette parameters invalid, header probably corrupt\n");
+               "Palette parameters invalid, header probably corrupt\n");
         return AVERROR_INVALIDDATA;
     }
 
@@ -147,8 +146,7 @@
     bufptr = s->dstptr + motion_vector[copy_tag][0] +
              s->frame.linesize[0] * motion_vector[copy_tag][1];
     if (bufptr < s->dstbuf) {
-        av_log(s->avctx, AV_LOG_ERROR,
-               "YOP: cannot decode, file probably corrupt\n");
+        av_log(s->avctx, AV_LOG_ERROR, "File probably corrupt\n");
         return AVERROR_INVALIDDATA;
     }
 
@@ -235,7 +233,7 @@
         palette[i + firstcolor] = (s->srcptr[0] << 18) |
                                   (s->srcptr[1] << 10) |
                                   (s->srcptr[2] << 2);
-        palette[i + firstcolor] |= 0xFF << 24 |
+        palette[i + firstcolor] |= 0xFFU << 24 |
                                    (palette[i + firstcolor] >> 6) & 0x30303;
     }
 
diff --git a/libavcodec/yuv4dec.c b/libavcodec/yuv4dec.c
index 0769669..ce44f13 100644
--- a/libavcodec/yuv4dec.c
+++ b/libavcodec/yuv4dec.c
@@ -24,7 +24,7 @@
 
 static av_cold int yuv4_decode_init(AVCodecContext *avctx)
 {
-    avctx->pix_fmt = PIX_FMT_YUV420P;
+    avctx->pix_fmt = AV_PIX_FMT_YUV420P;
 
     avctx->coded_frame = avcodec_alloc_frame();
 
diff --git a/libavcodec/yuv4enc.c b/libavcodec/yuv4enc.c
index 8185d06..340310a 100644
--- a/libavcodec/yuv4enc.c
+++ b/libavcodec/yuv4enc.c
@@ -87,6 +87,6 @@
     .init         = yuv4_encode_init,
     .encode2      = yuv4_encode_frame,
     .close        = yuv4_encode_close,
-    .pix_fmts     = (const enum PixelFormat[]){ PIX_FMT_YUV420P, PIX_FMT_NONE },
+    .pix_fmts     = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
     .long_name    = NULL_IF_CONFIG_SMALL("Uncompressed packed 4:2:0"),
 };
diff --git a/libavcodec/zerocodec.c b/libavcodec/zerocodec.c
index 789181c..c6a9ba9 100644
--- a/libavcodec/zerocodec.c
+++ b/libavcodec/zerocodec.c
@@ -129,7 +129,7 @@
     z_stream *zstream    = &zc->zstream;
     int zret;
 
-    avctx->pix_fmt             = PIX_FMT_UYVY422;
+    avctx->pix_fmt             = AV_PIX_FMT_UYVY422;
     avctx->bits_per_raw_sample = 8;
 
     zc->size = avpicture_get_size(avctx->pix_fmt,
diff --git a/libavcodec/zmbv.c b/libavcodec/zmbv.c
index 0a4f1cd..1b94351 100644
--- a/libavcodec/zmbv.c
+++ b/libavcodec/zmbv.c
@@ -493,6 +493,8 @@
         c->by = (c->height+ c->bh - 1) / c->bh;
         if (!c->cur || !c->prev)
             return -1;
+        memset(c->cur, 0, avctx->width * avctx->height * (c->bpp / 8));
+        memset(c->prev, 0, avctx->width * avctx->height * (c->bpp / 8));
         c->decode_intra= decode_intra;
     }
 
@@ -502,8 +504,11 @@
     }
 
     if (c->comp == 0) { //Uncompressed data
+        if (c->decomp_size < len) {
+            av_log(avctx, AV_LOG_ERROR, "decomp buffer too small\n");
+            return AVERROR_INVALIDDATA;
+        }
         memcpy(c->decomp_buf, buf, len);
-        c->decomp_size = 1;
     } else { // ZLIB-compressed data
         c->zstream.total_in = c->zstream.total_out = 0;
         c->zstream.next_in = (uint8_t*)buf;
@@ -625,12 +630,12 @@
     // Needed if zlib unused or init aborted before inflateInit
     memset(&c->zstream, 0, sizeof(z_stream));
 
-    avctx->pix_fmt = PIX_FMT_RGB24;
+    avctx->pix_fmt = AV_PIX_FMT_RGB24;
     c->decomp_size = (avctx->width + 255) * 4 * (avctx->height + 64);
 
     /* Allocate decompression buffer */
     if (c->decomp_size) {
-        if ((c->decomp_buf = av_malloc(c->decomp_size)) == NULL) {
+        if ((c->decomp_buf = av_mallocz(c->decomp_size)) == NULL) {
             av_log(avctx, AV_LOG_ERROR,
                    "Can't allocate decompression buffer.\n");
             return AVERROR(ENOMEM);
diff --git a/libavcodec/zmbvenc.c b/libavcodec/zmbvenc.c
index df5b90f..fb782a4 100644
--- a/libavcodec/zmbvenc.c
+++ b/libavcodec/zmbvenc.c
@@ -343,6 +343,6 @@
     .init           = encode_init,
     .encode2        = encode_frame,
     .close          = encode_end,
-    .pix_fmts       = (const enum PixelFormat[]){ PIX_FMT_PAL8, PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_PAL8, AV_PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("Zip Motion Blocks Video"),
 };
diff --git a/libavdevice/alsa-audio-common.c b/libavdevice/alsa-audio-common.c
index 9da868f..afe6751 100644
--- a/libavdevice/alsa-audio-common.c
+++ b/libavdevice/alsa-audio-common.c
@@ -31,7 +31,7 @@
 #include <alsa/asoundlib.h>
 #include "avdevice.h"
 #include "libavutil/avassert.h"
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 
 #include "alsa-audio.h"
 
diff --git a/libavdevice/alsa-audio.h b/libavdevice/alsa-audio.h
index 00acf9f..44b7c72 100644
--- a/libavdevice/alsa-audio.h
+++ b/libavdevice/alsa-audio.h
@@ -45,7 +45,7 @@
 
 #define ALSA_BUFFER_SIZE_MAX 65536
 
-typedef struct {
+typedef struct AlsaData {
     AVClass *class;
     snd_pcm_t *h;
     int frame_size;  ///< bytes per sample * channels
diff --git a/libavdevice/bktr.c b/libavdevice/bktr.c
index 2770551..e83c44a 100644
--- a/libavdevice/bktr.c
+++ b/libavdevice/bktr.c
@@ -273,7 +273,7 @@
     s->per_frame = ((uint64_t)1000000 * framerate.den) / framerate.num;
 
     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
-    st->codec->pix_fmt = PIX_FMT_YUV420P;
+    st->codec->pix_fmt = AV_PIX_FMT_YUV420P;
     st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
     st->codec->width = s->width;
     st->codec->height = s->height;
diff --git a/libavdevice/caca.c b/libavdevice/caca.c
index c47906e..0a74701 100644
--- a/libavdevice/caca.c
+++ b/libavdevice/caca.c
@@ -126,7 +126,7 @@
         return AVERROR(EINVAL);
     }
 
-    if (encctx->pix_fmt != PIX_FMT_RGB24) {
+    if (encctx->pix_fmt != AV_PIX_FMT_RGB24) {
         av_log(s, AV_LOG_ERROR,
                "Unsupported pixel format '%s', choose rgb24\n",
                av_get_pix_fmt_name(encctx->pix_fmt));
@@ -140,7 +140,7 @@
         goto fail;
     }
 
-    bpp = av_get_bits_per_pixel(&av_pix_fmt_descriptors[encctx->pix_fmt]);
+    bpp = av_get_bits_per_pixel(av_pix_fmt_desc_get(encctx->pix_fmt));
     c->dither = caca_create_dither(bpp, encctx->width, encctx->height,
                                    bpp / 8 * encctx->width,
                                    0x0000ff, 0x00ff00, 0xff0000, 0);
diff --git a/libavdevice/dshow.c b/libavdevice/dshow.c
index 1e86732..ea01b2a 100644
--- a/libavdevice/dshow.c
+++ b/libavdevice/dshow.c
@@ -53,7 +53,7 @@
 
     IMediaControl *control;
 
-    enum PixelFormat pixel_format;
+    enum AVPixelFormat pixel_format;
     enum AVCodecID video_codec_id;
     char *framerate;
 
@@ -66,33 +66,33 @@
     int channels;
 };
 
-static enum PixelFormat dshow_pixfmt(DWORD biCompression, WORD biBitCount)
+static enum AVPixelFormat dshow_pixfmt(DWORD biCompression, WORD biBitCount)
 {
     switch(biCompression) {
     case MKTAG('U', 'Y', 'V', 'Y'):
-        return PIX_FMT_UYVY422;
+        return AV_PIX_FMT_UYVY422;
     case MKTAG('Y', 'U', 'Y', '2'):
-        return PIX_FMT_YUYV422;
+        return AV_PIX_FMT_YUYV422;
     case MKTAG('I', '4', '2', '0'):
-        return PIX_FMT_YUV420P;
+        return AV_PIX_FMT_YUV420P;
     case BI_BITFIELDS:
     case BI_RGB:
         switch(biBitCount) { /* 1-8 are untested */
             case 1:
-                return PIX_FMT_MONOWHITE;
+                return AV_PIX_FMT_MONOWHITE;
             case 4:
-                return PIX_FMT_RGB4;
+                return AV_PIX_FMT_RGB4;
             case 8:
-                return PIX_FMT_RGB8;
+                return AV_PIX_FMT_RGB8;
             case 16:
-                return PIX_FMT_RGB555;
+                return AV_PIX_FMT_RGB555;
             case 24:
-                return PIX_FMT_BGR24;
+                return AV_PIX_FMT_BGR24;
             case 32:
-                return PIX_FMT_RGB32;
+                return AV_PIX_FMT_RGB32;
         }
     }
-    return PIX_FMT_NONE;
+    return AV_PIX_FMT_NONE;
 }
 
 static enum AVCodecID dshow_codecid(DWORD biCompression)
@@ -373,8 +373,8 @@
                 goto next;
             }
             if (!pformat_set) {
-                enum PixelFormat pix_fmt = dshow_pixfmt(bih->biCompression, bih->biBitCount);
-                if (pix_fmt == PIX_FMT_NONE) {
+                enum AVPixelFormat pix_fmt = dshow_pixfmt(bih->biCompression, bih->biBitCount);
+                if (pix_fmt == AV_PIX_FMT_NONE) {
                     enum AVCodecID codec_id = dshow_codecid(bih->biCompression);
                     AVCodec *codec = avcodec_find_decoder(codec_id);
                     if (codec_id == AV_CODEC_ID_NONE || !codec) {
@@ -396,7 +396,7 @@
                 if (ctx->video_codec_id != dshow_codecid(bih->biCompression))
                     goto next;
             }
-            if (ctx->pixel_format != PIX_FMT_NONE &&
+            if (ctx->pixel_format != AV_PIX_FMT_NONE &&
                 ctx->pixel_format != dshow_pixfmt(bih->biCompression, bih->biBitCount)) {
                 goto next;
             }
@@ -535,7 +535,7 @@
 
     int set_format = (devtype == VideoDevice && (ctx->framerate ||
                                                 (ctx->requested_width && ctx->requested_height) ||
-                                                 ctx->pixel_format != PIX_FMT_NONE ||
+                                                 ctx->pixel_format != AV_PIX_FMT_NONE ||
                                                  ctx->video_codec_id != AV_CODEC_ID_RAWVIDEO))
                   || (devtype == AudioDevice && (ctx->channels || ctx->sample_rate));
     int format_set = 0;
@@ -779,7 +779,7 @@
         codec->width      = bih->biWidth;
         codec->height     = bih->biHeight;
         codec->pix_fmt    = dshow_pixfmt(bih->biCompression, bih->biBitCount);
-        if (codec->pix_fmt == PIX_FMT_NONE) {
+        if (codec->pix_fmt == AV_PIX_FMT_NONE) {
             codec->codec_id = dshow_codecid(bih->biCompression);
             if (codec->codec_id == AV_CODEC_ID_NONE) {
                 av_log(avctx, AV_LOG_ERROR, "Unknown compression type. "
@@ -878,7 +878,7 @@
 
     ctx->video_codec_id = avctx->video_codec_id ? avctx->video_codec_id
                                                 : AV_CODEC_ID_RAWVIDEO;
-    if (ctx->pixel_format != PIX_FMT_NONE) {
+    if (ctx->pixel_format != AV_PIX_FMT_NONE) {
         if (ctx->video_codec_id != AV_CODEC_ID_RAWVIDEO) {
             av_log(avctx, AV_LOG_ERROR, "Pixel format may only be set when "
                               "video codec is not set or set to rawvideo\n");
@@ -1018,7 +1018,7 @@
 #define DEC AV_OPT_FLAG_DECODING_PARAM
 static const AVOption options[] = {
     { "video_size", "set video size given a string such as 640x480 or hd720.", OFFSET(requested_width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, DEC },
-    { "pixel_format", "set video pixel format", OFFSET(pixel_format), AV_OPT_TYPE_PIXEL_FMT, {.str = NULL}, 0, 0, DEC },
+    { "pixel_format", "set video pixel format", OFFSET(pixel_format), AV_OPT_TYPE_PIXEL_FMT, {.i64 = AV_PIX_FMT_NONE}, -1, AV_PIX_FMT_NB-1, DEC },
     { "framerate", "set video frame rate", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
     { "sample_rate", "set audio sample rate", OFFSET(sample_rate), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, DEC },
     { "sample_size", "set audio sample size", OFFSET(sample_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 16, DEC },
diff --git a/libavdevice/dshow_capture.h b/libavdevice/dshow_capture.h
index e34f14f..2446c7c 100644
--- a/libavdevice/dshow_capture.h
+++ b/libavdevice/dshow_capture.h
@@ -28,6 +28,7 @@
 
 #define COBJMACROS
 #include <windows.h>
+#define NO_DSHOW_STRSAFE
 #include <dshow.h>
 #include <dvdmedia.h>
 
diff --git a/libavdevice/dshow_filter.c b/libavdevice/dshow_filter.c
index 46d7eb0..7360adc 100644
--- a/libavdevice/dshow_filter.c
+++ b/libavdevice/dshow_filter.c
@@ -19,7 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#define NO_DSHOW_STRSAFE
 #include "dshow_capture.h"
 
 DECLARE_QUERYINTERFACE(libAVFilter,
diff --git a/libavdevice/dshow_pin.c b/libavdevice/dshow_pin.c
index 676877e..4953642 100644
--- a/libavdevice/dshow_pin.c
+++ b/libavdevice/dshow_pin.c
@@ -19,7 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#define NO_DSHOW_STRSAFE
 #include "dshow_capture.h"
 
 #include <stddef.h>
diff --git a/libavdevice/dv1394.c b/libavdevice/dv1394.c
index 2916e49..5d94f5c 100644
--- a/libavdevice/dv1394.c
+++ b/libavdevice/dv1394.c
@@ -211,7 +211,7 @@
 }
 
 static const AVOption options[] = {
-    { "standard", "", offsetof(struct dv1394_data, format), AV_OPT_TYPE_INT, {.i64 = DV1394_NTSC}, DV1394_PAL, DV1394_NTSC, AV_OPT_FLAG_DECODING_PARAM, "standard" },
+    { "standard", "", offsetof(struct dv1394_data, format), AV_OPT_TYPE_INT, {.i64 = DV1394_NTSC}, DV1394_NTSC, DV1394_PAL, AV_OPT_FLAG_DECODING_PARAM, "standard" },
     { "PAL",      "", 0, AV_OPT_TYPE_CONST, {.i64 = DV1394_PAL},   0, 0, AV_OPT_FLAG_DECODING_PARAM, "standard" },
     { "NTSC",     "", 0, AV_OPT_TYPE_CONST, {.i64 = DV1394_NTSC},  0, 0, AV_OPT_FLAG_DECODING_PARAM, "standard" },
     { "channel",  "", offsetof(struct dv1394_data, channel), AV_OPT_TYPE_INT, {.i64 = DV1394_DEFAULT_CHANNEL}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
diff --git a/libavdevice/fbdev.c b/libavdevice/fbdev.c
index d977495..30595bd 100644
--- a/libavdevice/fbdev.c
+++ b/libavdevice/fbdev.c
@@ -48,20 +48,20 @@
 struct rgb_pixfmt_map_entry {
     int bits_per_pixel;
     int red_offset, green_offset, blue_offset, alpha_offset;
-    enum PixelFormat pixfmt;
+    enum AVPixelFormat pixfmt;
 };
 
 static const 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 },
+    {  32,       0,           8,          16,           24,   AV_PIX_FMT_RGBA  },
+    {  32,      16,           8,           0,           24,   AV_PIX_FMT_BGRA  },
+    {  32,       8,          16,          24,            0,   AV_PIX_FMT_ARGB  },
+    {  32,       3,           2,           8,            0,   AV_PIX_FMT_ABGR  },
+    {  24,       0,           8,          16,            0,   AV_PIX_FMT_RGB24 },
+    {  24,      16,           8,           0,            0,   AV_PIX_FMT_BGR24 },
 };
 
-static enum PixelFormat get_pixfmt_from_fb_varinfo(struct fb_var_screeninfo *varinfo)
+static enum AVPixelFormat get_pixfmt_from_fb_varinfo(struct fb_var_screeninfo *varinfo)
 {
     int i;
 
@@ -74,7 +74,7 @@
             return entry->pixfmt;
     }
 
-    return PIX_FMT_NONE;
+    return AV_PIX_FMT_NONE;
 }
 
 typedef struct {
@@ -99,7 +99,7 @@
 {
     FBDevContext *fbdev = avctx->priv_data;
     AVStream *st = NULL;
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
     int ret, flags = O_RDONLY;
 
     ret = av_parse_video_rate(&fbdev->framerate_q, fbdev->framerate);
@@ -139,7 +139,7 @@
     }
 
     pix_fmt = get_pixfmt_from_fb_varinfo(&fbdev->varinfo);
-    if (pix_fmt == PIX_FMT_NONE) {
+    if (pix_fmt == AV_PIX_FMT_NONE) {
         ret = AVERROR(EINVAL);
         av_log(avctx, AV_LOG_ERROR,
                "Framebuffer pixel format not supported.\n");
@@ -171,7 +171,7 @@
     av_log(avctx, AV_LOG_INFO,
            "w:%d h:%d bpp:%d pixfmt:%s fps:%d/%d bit_rate:%d\n",
            fbdev->width, fbdev->height, fbdev->varinfo.bits_per_pixel,
-           av_pix_fmt_descriptors[pix_fmt].name,
+           av_get_pix_fmt_name(pix_fmt),
            fbdev->framerate_q.num, fbdev->framerate_q.den,
            st->codec->bit_rate);
     return 0;
diff --git a/libavdevice/iec61883.c b/libavdevice/iec61883.c
index 8c9a39f..a63566e 100644
--- a/libavdevice/iec61883.c
+++ b/libavdevice/iec61883.c
@@ -67,6 +67,8 @@
     DVPacket *queue_first;              ///< first element of packet queue
     DVPacket *queue_last;               ///< last element of packet queue
 
+    char *device_guid;                  ///< to select one of multiple DV devices
+
     int packets;                        ///< Number of packets queued
     int max_packets;                    ///< Max. number of packets in queue
 
@@ -138,7 +140,7 @@
 
 exit:
 #ifdef THREADS
-    pthread_cond_signal(&dv->cond);
+    pthread_cond_broadcast(&dv->cond);
     pthread_mutex_unlock(&dv->mutex);
 #endif
     return ret;
@@ -169,7 +171,7 @@
 #ifdef THREADS
             pthread_mutex_lock(&dv->mutex);
             dv->eof = 1;
-            pthread_cond_signal(&dv->cond);
+            pthread_cond_broadcast(&dv->cond);
             pthread_mutex_unlock(&dv->mutex);
 #else
             dv->eof = 1;
@@ -239,6 +241,7 @@
     int port = -1;
     int response;
     int i, j = 0;
+    uint64_t guid = 0;
 
     dv->input_port = -1;
     dv->output_port = -1;
@@ -267,25 +270,48 @@
         goto fail;
     }
 
-    /* Select first AV/C tape recorder player node */
+    if (dv->device_guid) {
+        if (sscanf(dv->device_guid, "%llx", (long long unsigned int *)&guid) != 1) {
+            av_log(context, AV_LOG_INFO, "Invalid dvguid parameter: %s\n",
+                   dv->device_guid);
+            goto fail;
+        }
+    }
 
     for (; j < nb_ports && port==-1; ++j) {
-        if (raw1394_set_port(dv->raw1394, j)) {
+        raw1394_destroy_handle(dv->raw1394);
+
+        if (!(dv->raw1394 = raw1394_new_handle_on_port(j))) {
             av_log(context, AV_LOG_ERROR, "Failed setting IEEE1394 port.\n");
             goto fail;
         }
+
         for (i=0; i<raw1394_get_nodecount(dv->raw1394); ++i) {
-            if (rom1394_get_directory(dv->raw1394, i, &rom_dir) < 0)
-                continue;
-            if (((rom1394_get_node_type(&rom_dir) == ROM1394_NODE_TYPE_AVC) &&
-                 avc1394_check_subunit_type(dv->raw1394, i, AVC1394_SUBUNIT_TYPE_VCR)) ||
-                (rom_dir.unit_spec_id == MOTDCT_SPEC_ID)) {
+
+            /* Select device explicitly by GUID */
+
+            if (guid > 1) {
+                if (guid == rom1394_get_guid(dv->raw1394, i)) {
+                    dv->node = i;
+                    port = j;
+                    break;
+                }
+            } else {
+
+                /* Select first AV/C tape recorder player node */
+
+                if (rom1394_get_directory(dv->raw1394, i, &rom_dir) < 0)
+                    continue;
+                if (((rom1394_get_node_type(&rom_dir) == ROM1394_NODE_TYPE_AVC) &&
+                     avc1394_check_subunit_type(dv->raw1394, i, AVC1394_SUBUNIT_TYPE_VCR)) ||
+                    (rom_dir.unit_spec_id == MOTDCT_SPEC_ID)) {
+                    rom1394_free_directory(&rom_dir);
+                    dv->node = i;
+                    port = j;
+                    break;
+                }
                 rom1394_free_directory(&rom_dir);
-                dv->node = i;
-                port = j;
-                break;
             }
-            rom1394_free_directory(&rom_dir);
         }
     }
 
@@ -294,6 +320,10 @@
         goto fail;
     }
 
+    /* Provide bus sanity for multiple connections */
+
+    iec61883_cmp_normalize_output(dv->raw1394, 0xffc0 | dv->node);
+
     /* Find out if device is DV or HDV */
 
     if (dv->type == IEC61883_AUTO) {
@@ -444,6 +474,7 @@
     { "dv",     "force device being treated as DV device", 0, AV_OPT_TYPE_CONST, {.i64 = IEC61883_DV},   0, 0, AV_OPT_FLAG_DECODING_PARAM, "dvtype" },
     { "hdv" ,   "force device being treated as HDV device", 0, AV_OPT_TYPE_CONST, {.i64 = IEC61883_HDV},  0, 0, AV_OPT_FLAG_DECODING_PARAM, "dvtype" },
     { "dvbuffer", "set queue buffer size (in packets)", offsetof(struct iec61883_data, max_packets), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
+    { "dvguid", "select one of multiple DV devices by its GUID", offsetof(struct iec61883_data, device_guid), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
     { NULL },
 };
 
diff --git a/libavdevice/lavfi.c b/libavdevice/lavfi.c
index e080857..4f1ba58 100644
--- a/libavdevice/lavfi.c
+++ b/libavdevice/lavfi.c
@@ -27,12 +27,14 @@
 
 #include "float.h"              /* DBL_MIN, DBL_MAX */
 
+#include "libavutil/bprint.h"
+#include "libavutil/channel_layout.h"
+#include "libavutil/file.h"
 #include "libavutil/log.h"
 #include "libavutil/mem.h"
 #include "libavutil/opt.h"
 #include "libavutil/parseutils.h"
 #include "libavutil/pixdesc.h"
-#include "libavutil/audioconvert.h"
 #include "libavfilter/avfilter.h"
 #include "libavfilter/avfiltergraph.h"
 #include "libavfilter/buffersink.h"
@@ -42,6 +44,7 @@
 typedef struct {
     AVClass *class;          ///< class for private options
     char          *graph_str;
+    char          *graph_filename;
     char          *dump_graph;
     AVFilterGraph *graph;
     AVFilterContext **sinks;
@@ -54,14 +57,17 @@
 {
     int i, j, *fmts, count = 0;
 
-    for (i = 0; i < n; i++)
-        if (!(av_pix_fmt_descriptors[i].flags & PIX_FMT_HWACCEL))
+    for (i = 0; i < n; i++) {
+        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(i);
+        if (!(desc->flags & PIX_FMT_HWACCEL))
             count++;
+    }
 
     if (!(fmts = av_malloc((count+1) * sizeof(int))))
         return NULL;
     for (j = 0, i = 0; i < n; i++) {
-        if (!(av_pix_fmt_descriptors[i].flags & PIX_FMT_HWACCEL))
+        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(i);
+        if (!(desc->flags & PIX_FMT_HWACCEL))
             fmts[j++] = i;
     }
     fmts[j] = -1;
@@ -86,7 +92,7 @@
     LavfiContext *lavfi = avctx->priv_data;
     AVFilterInOut *input_links = NULL, *output_links = NULL, *inout;
     AVFilter *buffersink, *abuffersink;
-    int *pix_fmts = create_all_formats(PIX_FMT_NB);
+    int *pix_fmts = create_all_formats(AV_PIX_FMT_NB);
     enum AVMediaType type;
     int ret = 0, i, n;
 
@@ -100,6 +106,32 @@
     buffersink = avfilter_get_by_name("ffbuffersink");
     abuffersink = avfilter_get_by_name("ffabuffersink");
 
+    if (lavfi->graph_filename && lavfi->graph_str) {
+        av_log(avctx, AV_LOG_ERROR,
+               "Only one of the graph or graph_file options must be specified\n");
+        FAIL(AVERROR(EINVAL));
+    }
+
+    if (lavfi->graph_filename) {
+        uint8_t *file_buf, *graph_buf;
+        size_t file_bufsize;
+        ret = av_file_map(lavfi->graph_filename,
+                          &file_buf, &file_bufsize, 0, avctx);
+        if (ret < 0)
+            goto end;
+
+        /* create a 0-terminated string based on the read file */
+        graph_buf = av_malloc(file_bufsize + 1);
+        if (!graph_buf) {
+            av_file_unmap(file_buf, file_bufsize);
+            FAIL(AVERROR(ENOMEM));
+        }
+        memcpy(graph_buf, file_buf, file_bufsize);
+        graph_buf[file_bufsize] = 0;
+        av_file_unmap(file_buf, file_bufsize);
+        lavfi->graph_str = graph_buf;
+    }
+
     if (!lavfi->graph_str)
         lavfi->graph_str = av_strdup(avctx->filename);
 
@@ -336,6 +368,28 @@
         memcpy(pkt->data, ref->data[0], size);
     }
 
+    if (ref->metadata) {
+        uint8_t *metadata;
+        AVDictionaryEntry *e = NULL;
+        AVBPrint meta_buf;
+
+        av_bprint_init(&meta_buf, 0, AV_BPRINT_SIZE_UNLIMITED);
+        while ((e = av_dict_get(ref->metadata, "", e, AV_DICT_IGNORE_SUFFIX))) {
+            av_bprintf(&meta_buf, "%s", e->key);
+            av_bprint_chars(&meta_buf, '\0', 1);
+            av_bprintf(&meta_buf, "%s", e->value);
+            av_bprint_chars(&meta_buf, '\0', 1);
+        }
+        if (!av_bprint_is_complete(&meta_buf) ||
+            !(metadata = av_packet_new_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA,
+                                                 meta_buf.len))) {
+            av_bprint_finalize(&meta_buf, NULL);
+            return AVERROR(ENOMEM);
+        }
+        memcpy(metadata, meta_buf.str, meta_buf.len);
+        av_bprint_finalize(&meta_buf, NULL);
+    }
+
     pkt->stream_index = stream_idx;
     pkt->pts = ref->pts;
     pkt->pos = ref->pos;
@@ -350,6 +404,7 @@
 
 static const AVOption options[] = {
     { "graph",     "set libavfilter graph", OFFSET(graph_str),  AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
+    { "graph_file","set libavfilter graph filename", OFFSET(graph_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC},
     { "dumpgraph", "dump graph to stderr",  OFFSET(dump_graph), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
     { NULL },
 };
diff --git a/libavdevice/libdc1394.c b/libavdevice/libdc1394.c
index 82dd3c5..bae1497 100644
--- a/libavdevice/libdc1394.c
+++ b/libavdevice/libdc1394.c
@@ -73,12 +73,12 @@
 struct dc1394_frame_format {
     int width;
     int height;
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
     int frame_size_id;
 } dc1394_frame_formats[] = {
-    { 320, 240, PIX_FMT_UYVY422, DC1394_VIDEO_MODE_320x240_YUV422 },
-    { 640, 480, PIX_FMT_UYYVYY411, DC1394_VIDEO_MODE_640x480_YUV411 },
-    { 640, 480, PIX_FMT_UYVY422, DC1394_VIDEO_MODE_640x480_YUV422 },
+    { 320, 240, AV_PIX_FMT_UYVY422,   DC1394_VIDEO_MODE_320x240_YUV422 },
+    { 640, 480, AV_PIX_FMT_UYYVYY411, DC1394_VIDEO_MODE_640x480_YUV411 },
+    { 640, 480, AV_PIX_FMT_UYVY422,   DC1394_VIDEO_MODE_640x480_YUV422 },
     { 0, 0, 0, 0 } /* gotta be the last one */
 };
 
@@ -124,12 +124,12 @@
     AVStream* vst;
     struct dc1394_frame_format *fmt;
     struct dc1394_frame_rate *fps;
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
     int width, height;
     AVRational framerate;
     int ret = 0;
 
-    if ((pix_fmt = av_get_pix_fmt(dc1394->pixel_format)) == PIX_FMT_NONE) {
+    if ((pix_fmt = av_get_pix_fmt(dc1394->pixel_format)) == AV_PIX_FMT_NONE) {
         av_log(c, AV_LOG_ERROR, "No such pixel format: %s.\n", dc1394->pixel_format);
         ret = AVERROR(EINVAL);
         goto out;
diff --git a/libavdevice/oss_audio.c b/libavdevice/oss_audio.c
index 5c8b3b9..aa40034 100644
--- a/libavdevice/oss_audio.c
+++ b/libavdevice/oss_audio.c
@@ -76,8 +76,11 @@
     }
 
     /* non blocking mode */
-    if (!is_output)
-        fcntl(audio_fd, F_SETFL, O_NONBLOCK);
+    if (!is_output) {
+        if (fcntl(audio_fd, F_SETFL, O_NONBLOCK) < 0) {
+            av_log(s1, AV_LOG_WARNING, "%s: Could not enable non block mode (%s)\n", audio_device, strerror(errno));
+        }
+    }
 
     s->frame_size = AUDIO_BLOCK_SIZE;
 
diff --git a/libavdevice/sdl.c b/libavdevice/sdl.c
index 5d135a5..1867139 100644
--- a/libavdevice/sdl.c
+++ b/libavdevice/sdl.c
@@ -44,12 +44,12 @@
 } SDLContext;
 
 static const struct sdl_overlay_pix_fmt_entry {
-    enum PixelFormat pix_fmt; int overlay_fmt;
+    enum AVPixelFormat pix_fmt; int overlay_fmt;
 } sdl_overlay_pix_fmt_map[] = {
-    { PIX_FMT_YUV420P, SDL_IYUV_OVERLAY },
-    { PIX_FMT_YUYV422, SDL_YUY2_OVERLAY },
-    { PIX_FMT_UYVY422, SDL_UYVY_OVERLAY },
-    { PIX_FMT_NONE,    0                },
+    { AV_PIX_FMT_YUV420P, SDL_IYUV_OVERLAY },
+    { AV_PIX_FMT_YUYV422, SDL_YUY2_OVERLAY },
+    { AV_PIX_FMT_UYVY422, SDL_UYVY_OVERLAY },
+    { AV_PIX_FMT_NONE,    0                },
 };
 
 static int sdl_write_trailer(AVFormatContext *s)
@@ -104,7 +104,7 @@
         goto fail;
     }
 
-    for (i = 0; sdl_overlay_pix_fmt_map[i].pix_fmt != PIX_FMT_NONE; i++) {
+    for (i = 0; sdl_overlay_pix_fmt_map[i].pix_fmt != AV_PIX_FMT_NONE; i++) {
         if (sdl_overlay_pix_fmt_map[i].pix_fmt == encctx->pix_fmt) {
             sdl->overlay_fmt = sdl_overlay_pix_fmt_map[i].overlay_fmt;
             break;
diff --git a/libavdevice/sndio_common.h b/libavdevice/sndio_common.h
index 5111dc7..74f41f5 100644
--- a/libavdevice/sndio_common.h
+++ b/libavdevice/sndio_common.h
@@ -28,7 +28,7 @@
 #include "libavutil/log.h"
 #include "avdevice.h"
 
-typedef struct {
+typedef struct SndioData {
     AVClass *class;
     struct sio_hdl *hdl;
     enum AVCodecID codec_id;
diff --git a/libavdevice/timefilter.c b/libavdevice/timefilter.c
index 330f26e..343f1b1 100644
--- a/libavdevice/timefilter.c
+++ b/libavdevice/timefilter.c
@@ -28,8 +28,8 @@
 #include "timefilter.h"
 
 struct TimeFilter {
-    /// Delay Locked Loop data. These variables refer to mathematical
-    /// concepts described in: http://www.kokkinizita.net/papers/usingdll.pdf
+    // Delay Locked Loop data. These variables refer to mathematical
+    // concepts described in: http://www.kokkinizita.net/papers/usingdll.pdf
     double cycle_time;
     double feedback2_factor;
     double feedback3_factor;
@@ -69,15 +69,12 @@
 {
     self->count++;
     if (self->count == 1) {
-        /// init loop
         self->cycle_time = system_time;
     } else {
         double loop_error;
         self->cycle_time += self->clock_period * period;
-        /// calculate loop error
         loop_error = system_time - self->cycle_time;
 
-        /// update loop
         self->cycle_time   += FFMAX(self->feedback2_factor, 1.0 / self->count) * loop_error;
         self->clock_period += self->feedback3_factor * loop_error;
     }
diff --git a/libavdevice/v4l.c b/libavdevice/v4l.c
index 3d75110..e2f37d6 100644
--- a/libavdevice/v4l.c
+++ b/libavdevice/v4l.c
@@ -60,16 +60,16 @@
 static const struct {
     int palette;
     int depth;
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
 } video_formats [] = {
-    {.palette = VIDEO_PALETTE_YUV420P, .depth = 12, .pix_fmt = PIX_FMT_YUV420P },
-    {.palette = VIDEO_PALETTE_YUV422,  .depth = 16, .pix_fmt = PIX_FMT_YUYV422 },
-    {.palette = VIDEO_PALETTE_UYVY,    .depth = 16, .pix_fmt = PIX_FMT_UYVY422 },
-    {.palette = VIDEO_PALETTE_YUYV,    .depth = 16, .pix_fmt = PIX_FMT_YUYV422 },
+    {.palette = VIDEO_PALETTE_YUV420P, .depth = 12, .pix_fmt = AV_PIX_FMT_YUV420P },
+    {.palette = VIDEO_PALETTE_YUV422,  .depth = 16, .pix_fmt = AV_PIX_FMT_YUYV422 },
+    {.palette = VIDEO_PALETTE_UYVY,    .depth = 16, .pix_fmt = AV_PIX_FMT_UYVY422 },
+    {.palette = VIDEO_PALETTE_YUYV,    .depth = 16, .pix_fmt = AV_PIX_FMT_YUYV422 },
     /* NOTE: v4l uses BGR24, not RGB24 */
-    {.palette = VIDEO_PALETTE_RGB24,   .depth = 24, .pix_fmt = PIX_FMT_BGR24   },
-    {.palette = VIDEO_PALETTE_RGB565,  .depth = 16, .pix_fmt = PIX_FMT_BGR565  },
-    {.palette = VIDEO_PALETTE_GREY,    .depth = 8,  .pix_fmt = PIX_FMT_GRAY8   },
+    {.palette = VIDEO_PALETTE_RGB24,   .depth = 24, .pix_fmt = AV_PIX_FMT_BGR24   },
+    {.palette = VIDEO_PALETTE_RGB565,  .depth = 16, .pix_fmt = AV_PIX_FMT_BGR565  },
+    {.palette = VIDEO_PALETTE_GREY,    .depth = 8,  .pix_fmt = AV_PIX_FMT_GRAY8   },
 };
 
 
diff --git a/libavdevice/v4l2.c b/libavdevice/v4l2.c
index 193b8e9..cd6aeb2 100644
--- a/libavdevice/v4l2.c
+++ b/libavdevice/v4l2.c
@@ -27,7 +27,7 @@
  * (http://v4l2spec.bytesex.org/v4l2spec/capture.c)
  *
  * Thanks to Michael Niedermayer for providing the mapping between
- * V4L2_PIX_FMT_* and PIX_FMT_*
+ * V4L2_PIX_FMT_* and AV_PIX_FMT_*
  */
 
 #undef __STRICT_ANSI__ //workaround due to broken kernel headers
@@ -124,34 +124,34 @@
 };
 
 struct fmt_map {
-    enum PixelFormat ff_fmt;
+    enum AVPixelFormat ff_fmt;
     enum AVCodecID codec_id;
     uint32_t v4l2_fmt;
 };
 
 static struct fmt_map fmt_conversion_table[] = {
     //ff_fmt           codec_id           v4l2_fmt
-    { PIX_FMT_YUV420P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV420  },
-    { PIX_FMT_YUV420P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YVU420  },
-    { PIX_FMT_YUV422P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV422P },
-    { PIX_FMT_YUYV422, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUYV    },
-    { PIX_FMT_UYVY422, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_UYVY    },
-    { PIX_FMT_YUV411P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV411P },
-    { PIX_FMT_YUV410P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV410  },
-    { PIX_FMT_RGB555LE,AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555  },
-    { PIX_FMT_RGB555BE,AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555X },
-    { PIX_FMT_RGB565LE,AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565  },
-    { PIX_FMT_RGB565BE,AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565X },
-    { PIX_FMT_BGR24,   AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR24   },
-    { PIX_FMT_RGB24,   AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB24   },
-    { PIX_FMT_BGR0,    AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR32   },
-    { PIX_FMT_0RGB,    AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB32   },
-    { PIX_FMT_GRAY8,   AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_GREY    },
-    { PIX_FMT_NV12,    AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_NV12    },
-    { PIX_FMT_NONE,    AV_CODEC_ID_MJPEG,    V4L2_PIX_FMT_MJPEG   },
-    { PIX_FMT_NONE,    AV_CODEC_ID_MJPEG,    V4L2_PIX_FMT_JPEG    },
+    { AV_PIX_FMT_YUV420P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV420  },
+    { AV_PIX_FMT_YUV420P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YVU420  },
+    { AV_PIX_FMT_YUV422P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV422P },
+    { AV_PIX_FMT_YUYV422, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUYV    },
+    { AV_PIX_FMT_UYVY422, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_UYVY    },
+    { AV_PIX_FMT_YUV411P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV411P },
+    { AV_PIX_FMT_YUV410P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV410  },
+    { AV_PIX_FMT_RGB555LE,AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555  },
+    { AV_PIX_FMT_RGB555BE,AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555X },
+    { AV_PIX_FMT_RGB565LE,AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565  },
+    { AV_PIX_FMT_RGB565BE,AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565X },
+    { AV_PIX_FMT_BGR24,   AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR24   },
+    { AV_PIX_FMT_RGB24,   AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB24   },
+    { AV_PIX_FMT_BGR0,    AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR32   },
+    { AV_PIX_FMT_0RGB,    AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB32   },
+    { AV_PIX_FMT_GRAY8,   AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_GREY    },
+    { AV_PIX_FMT_NV12,    AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_NV12    },
+    { AV_PIX_FMT_NONE,    AV_CODEC_ID_MJPEG,    V4L2_PIX_FMT_MJPEG   },
+    { AV_PIX_FMT_NONE,    AV_CODEC_ID_MJPEG,    V4L2_PIX_FMT_JPEG    },
 #ifdef V4L2_PIX_FMT_CPIA1
-    { PIX_FMT_NONE,    AV_CODEC_ID_CPIA,     V4L2_PIX_FMT_CPIA1   },
+    { AV_PIX_FMT_NONE,    AV_CODEC_ID_CPIA,     V4L2_PIX_FMT_CPIA1   },
 #endif
 };
 
@@ -267,14 +267,14 @@
     return 1;
 }
 
-static uint32_t fmt_ff2v4l(enum PixelFormat pix_fmt, enum AVCodecID codec_id)
+static uint32_t fmt_ff2v4l(enum AVPixelFormat pix_fmt, enum AVCodecID codec_id)
 {
     int i;
 
     for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
         if ((codec_id == AV_CODEC_ID_NONE ||
              fmt_conversion_table[i].codec_id == codec_id) &&
-            (pix_fmt == PIX_FMT_NONE ||
+            (pix_fmt == AV_PIX_FMT_NONE ||
              fmt_conversion_table[i].ff_fmt == pix_fmt)) {
             return fmt_conversion_table[i].v4l2_fmt;
         }
@@ -283,7 +283,7 @@
     return 0;
 }
 
-static enum PixelFormat fmt_v4l2ff(uint32_t v4l2_fmt, enum AVCodecID codec_id)
+static enum AVPixelFormat fmt_v4l2ff(uint32_t v4l2_fmt, enum AVCodecID codec_id)
 {
     int i;
 
@@ -294,7 +294,7 @@
         }
     }
 
-    return PIX_FMT_NONE;
+    return AV_PIX_FMT_NONE;
 }
 
 static enum AVCodecID fmt_v4l2codec(uint32_t v4l2_fmt)
@@ -342,7 +342,7 @@
 
     while(!ioctl(fd, VIDIOC_ENUM_FMT, &vfd)) {
         enum AVCodecID codec_id = fmt_v4l2codec(vfd.pixelformat);
-        enum PixelFormat pix_fmt = fmt_v4l2ff(vfd.pixelformat, codec_id);
+        enum AVPixelFormat pix_fmt = fmt_v4l2ff(vfd.pixelformat, codec_id);
 
         vfd.index++;
 
@@ -739,7 +739,7 @@
 }
 
 static uint32_t device_try_init(AVFormatContext *s1,
-                                enum PixelFormat pix_fmt,
+                                enum AVPixelFormat pix_fmt,
                                 int *width,
                                 int *height,
                                 enum AVCodecID *codec_id)
@@ -778,7 +778,7 @@
     int res = 0;
     uint32_t desired_format;
     enum AVCodecID codec_id = AV_CODEC_ID_NONE;
-    enum PixelFormat pix_fmt = PIX_FMT_NONE;
+    enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;
 
     st = avformat_new_stream(s1, NULL);
     if (!st) {
@@ -808,7 +808,7 @@
 
         pix_fmt = av_get_pix_fmt(s->pixel_format);
 
-        if (pix_fmt == PIX_FMT_NONE && !codec) {
+        if (pix_fmt == AV_PIX_FMT_NONE && !codec) {
             av_log(s1, AV_LOG_ERROR, "No such input format: %s.\n",
                    s->pixel_format);
 
diff --git a/libavdevice/version.h b/libavdevice/version.h
index a178180..5eed4f5 100644
--- a/libavdevice/version.h
+++ b/libavdevice/version.h
@@ -29,7 +29,7 @@
 
 #define LIBAVDEVICE_VERSION_MAJOR  54
 #define LIBAVDEVICE_VERSION_MINOR   3
-#define LIBAVDEVICE_VERSION_MICRO 100
+#define LIBAVDEVICE_VERSION_MICRO 102
 
 #define LIBAVDEVICE_VERSION_INT AV_VERSION_INT(LIBAVDEVICE_VERSION_MAJOR, \
                                                LIBAVDEVICE_VERSION_MINOR, \
diff --git a/libavdevice/vfwcap.c b/libavdevice/vfwcap.c
index 3b348ff..66b02be 100644
--- a/libavdevice/vfwcap.c
+++ b/libavdevice/vfwcap.c
@@ -45,32 +45,32 @@
     char *framerate;        /**< Set by a private option. */
 };
 
-static enum PixelFormat vfw_pixfmt(DWORD biCompression, WORD biBitCount)
+static enum AVPixelFormat vfw_pixfmt(DWORD biCompression, WORD biBitCount)
 {
     switch(biCompression) {
     case MKTAG('U', 'Y', 'V', 'Y'):
-        return PIX_FMT_UYVY422;
+        return AV_PIX_FMT_UYVY422;
     case MKTAG('Y', 'U', 'Y', '2'):
-        return PIX_FMT_YUYV422;
+        return AV_PIX_FMT_YUYV422;
     case MKTAG('I', '4', '2', '0'):
-        return PIX_FMT_YUV420P;
+        return AV_PIX_FMT_YUV420P;
     case BI_RGB:
         switch(biBitCount) { /* 1-8 are untested */
             case 1:
-                return PIX_FMT_MONOWHITE;
+                return AV_PIX_FMT_MONOWHITE;
             case 4:
-                return PIX_FMT_RGB4;
+                return AV_PIX_FMT_RGB4;
             case 8:
-                return PIX_FMT_RGB8;
+                return AV_PIX_FMT_RGB8;
             case 16:
-                return PIX_FMT_RGB555;
+                return AV_PIX_FMT_RGB555;
             case 24:
-                return PIX_FMT_BGR24;
+                return AV_PIX_FMT_BGR24;
             case 32:
-                return PIX_FMT_RGB32;
+                return AV_PIX_FMT_RGB32;
         }
     }
-    return PIX_FMT_NONE;
+    return AV_PIX_FMT_NONE;
 }
 
 static enum AVCodecID vfw_codecid(DWORD biCompression)
@@ -377,7 +377,7 @@
     codec->width  = bi->bmiHeader.biWidth;
     codec->height = bi->bmiHeader.biHeight;
     codec->pix_fmt = vfw_pixfmt(biCompression, biBitCount);
-    if(codec->pix_fmt == PIX_FMT_NONE) {
+    if(codec->pix_fmt == AV_PIX_FMT_NONE) {
         codec->codec_id = vfw_codecid(biCompression);
         if(codec->codec_id == AV_CODEC_ID_NONE) {
             av_log(s, AV_LOG_ERROR, "Unknown compression type. "
diff --git a/libavdevice/x11grab.c b/libavdevice/x11grab.c
index b6bd486..6124006 100644
--- a/libavdevice/x11grab.c
+++ b/libavdevice/x11grab.c
@@ -43,6 +43,7 @@
 #include "libavutil/parseutils.h"
 #include "libavutil/time.h"
 #include <time.h>
+#include <X11/cursorfont.h>
 #include <X11/X.h>
 #include <X11/Xlib.h>
 #include <X11/Xlibint.h>
@@ -157,7 +158,7 @@
     struct x11grab *x11grab = s1->priv_data;
     Display *dpy;
     AVStream *st = NULL;
-    enum PixelFormat input_pixfmt;
+    enum AVPixelFormat input_pixfmt;
     XImage *image;
     int x_off = 0;
     int y_off = 0;
@@ -260,19 +261,19 @@
     switch (image->bits_per_pixel) {
     case 8:
         av_log (s1, AV_LOG_DEBUG, "8 bit palette\n");
-        input_pixfmt = PIX_FMT_PAL8;
+        input_pixfmt = AV_PIX_FMT_PAL8;
         break;
     case 16:
         if (       image->red_mask   == 0xf800 &&
                    image->green_mask == 0x07e0 &&
                    image->blue_mask  == 0x001f ) {
             av_log (s1, AV_LOG_DEBUG, "16 bit RGB565\n");
-            input_pixfmt = PIX_FMT_RGB565;
+            input_pixfmt = AV_PIX_FMT_RGB565;
         } else if (image->red_mask   == 0x7c00 &&
                    image->green_mask == 0x03e0 &&
                    image->blue_mask  == 0x001f ) {
             av_log(s1, AV_LOG_DEBUG, "16 bit RGB555\n");
-            input_pixfmt = PIX_FMT_RGB555;
+            input_pixfmt = AV_PIX_FMT_RGB555;
         } else {
             av_log(s1, AV_LOG_ERROR, "RGB ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
             av_log(s1, AV_LOG_ERROR, "color masks: r 0x%.6lx g 0x%.6lx b 0x%.6lx\n", image->red_mask, image->green_mask, image->blue_mask);
@@ -284,11 +285,11 @@
         if (        image->red_mask   == 0xff0000 &&
                     image->green_mask == 0x00ff00 &&
                     image->blue_mask  == 0x0000ff ) {
-            input_pixfmt = PIX_FMT_BGR24;
+            input_pixfmt = AV_PIX_FMT_BGR24;
         } else if ( image->red_mask   == 0x0000ff &&
                     image->green_mask == 0x00ff00 &&
                     image->blue_mask  == 0xff0000 ) {
-            input_pixfmt = PIX_FMT_RGB24;
+            input_pixfmt = AV_PIX_FMT_RGB24;
         } else {
             av_log(s1, AV_LOG_ERROR,"rgb ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
             av_log(s1, AV_LOG_ERROR, "color masks: r 0x%.6lx g 0x%.6lx b 0x%.6lx\n", image->red_mask, image->green_mask, image->blue_mask);
@@ -297,7 +298,7 @@
         }
         break;
     case 32:
-        input_pixfmt = PIX_FMT_0RGB32;
+        input_pixfmt = AV_PIX_FMT_0RGB32;
         break;
     default:
         av_log(s1, AV_LOG_ERROR, "image depth %i not supported ... aborting\n", image->bits_per_pixel);
@@ -352,11 +353,19 @@
      * Anyone who performs further investigation of the xlib API likely risks
      * permanent brain damage. */
     uint8_t *pix = image->data;
+    Cursor c;
+    Window w;
+    XSetWindowAttributes attr;
 
     /* Code doesn't currently support 16-bit or PAL8 */
     if (image->bits_per_pixel != 24 && image->bits_per_pixel != 32)
         return;
 
+    c = XCreateFontCursor(dpy, XC_left_ptr);
+    w = DefaultRootWindow(dpy);
+    attr.cursor = c;
+    XChangeWindowAttributes(dpy, w, CWCursor, &attr);
+
     xcim = XFixesGetCursorImage(dpy);
 
     x = xcim->x - xcim->xhot;
diff --git a/libavfilter/Makefile b/libavfilter/Makefile
index ed1b9b5..0e49912 100644
--- a/libavfilter/Makefile
+++ b/libavfilter/Makefile
@@ -66,6 +66,7 @@
 OBJS-$(CONFIG_CHANNELMAP_FILTER)             += af_channelmap.o
 OBJS-$(CONFIG_CHANNELSPLIT_FILTER)           += af_channelsplit.o
 OBJS-$(CONFIG_EARWAX_FILTER)                 += af_earwax.o
+OBJS-$(CONFIG_EBUR128_FILTER)                += f_ebur128.o
 OBJS-$(CONFIG_JOIN_FILTER)                   += af_join.o
 OBJS-$(CONFIG_PAN_FILTER)                    += af_pan.o
 OBJS-$(CONFIG_RESAMPLE_FILTER)               += af_resample.o
@@ -97,12 +98,14 @@
 OBJS-$(CONFIG_DRAWTEXT_FILTER)               += vf_drawtext.o
 OBJS-$(CONFIG_EDGEDETECT_FILTER)             += vf_edgedetect.o
 OBJS-$(CONFIG_FADE_FILTER)                   += vf_fade.o
+OBJS-$(CONFIG_FIELD_FILTER)                  += vf_field.o
 OBJS-$(CONFIG_FIELDORDER_FILTER)             += vf_fieldorder.o
 OBJS-$(CONFIG_FIFO_FILTER)                   += fifo.o
 OBJS-$(CONFIG_FORMAT_FILTER)                 += vf_format.o
 OBJS-$(CONFIG_FRAMESTEP_FILTER)              += vf_framestep.o
 OBJS-$(CONFIG_FPS_FILTER)                    += vf_fps.o
 OBJS-$(CONFIG_FREI0R_FILTER)                 += vf_frei0r.o
+OBJS-$(CONFIG_GEQ_FILTER)                    += vf_geq.o
 OBJS-$(CONFIG_GRADFUN_FILTER)                += vf_gradfun.o
 OBJS-$(CONFIG_HFLIP_FILTER)                  += vf_hflip.o
 OBJS-$(CONFIG_HQDN3D_FILTER)                 += vf_hqdn3d.o
@@ -129,7 +132,6 @@
 OBJS-$(CONFIG_SETSAR_FILTER)                 += vf_aspect.o
 OBJS-$(CONFIG_SETTB_FILTER)                  += f_settb.o
 OBJS-$(CONFIG_SHOWINFO_FILTER)               += vf_showinfo.o
-OBJS-$(CONFIG_SLICIFY_FILTER)                += vf_slicify.o
 OBJS-$(CONFIG_SMARTBLUR_FILTER)              += vf_smartblur.o
 OBJS-$(CONFIG_SPLIT_FILTER)                  += split.o
 OBJS-$(CONFIG_SUPER2XSAI_FILTER)             += vf_super2xsai.o
@@ -165,14 +167,10 @@
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_dsize.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_eq2.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_eq.o
-OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_field.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_fil.o
 #OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_filmdint.o
-OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_fixpts.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_fspp.o
-OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_geq.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_harddup.o
-OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_hqdn3d.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_il.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_ilpack.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_ivtc.o
@@ -180,26 +178,21 @@
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_mcdeint.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_noise.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_ow.o
-OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_palette.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_perspective.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_phase.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_pp.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_pp7.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_pullup.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_qp.o
-OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_rectangle.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_sab.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_softpulldown.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_softskip.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_spp.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_stereo3d.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_telecine.o
-OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_tile.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_tinterlace.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_unsharp.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_uspp.o
-OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_yuvcsp.o
-OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_yvu9.o
 OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/pullup.o
 
 # multimedia filters
diff --git a/libavfilter/af_aconvert.c b/libavfilter/af_aconvert.c
index 6dd8452..54f1fcd 100644
--- a/libavfilter/af_aconvert.c
+++ b/libavfilter/af_aconvert.c
@@ -25,8 +25,8 @@
  * sample format and channel layout conversion audio filter
  */
 
-#include "libavutil/audioconvert.h"
 #include "libavutil/avstring.h"
+#include "libavutil/channel_layout.h"
 #include "libswresample/swresample.h"
 #include "avfilter.h"
 #include "audio.h"
@@ -135,7 +135,7 @@
     return 0;
 }
 
-static int  filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamplesref)
+static int  filter_frame(AVFilterLink *inlink, AVFilterBufferRef *insamplesref)
 {
     AConvertContext *aconvert = inlink->dst->priv;
     const int n = insamplesref->audio->nb_samples;
@@ -149,11 +149,30 @@
     avfilter_copy_buffer_ref_props(outsamplesref, insamplesref);
     outsamplesref->audio->channel_layout = outlink->channel_layout;
 
-    ret = ff_filter_samples(outlink, outsamplesref);
+    ret = ff_filter_frame(outlink, outsamplesref);
     avfilter_unref_buffer(insamplesref);
     return ret;
 }
 
+static const AVFilterPad aconvert_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_AUDIO,
+        .filter_frame = filter_frame,
+        .min_perms    = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad aconvert_outputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_AUDIO,
+        .config_props = config_output,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_aconvert = {
     .name          = "aconvert",
     .description   = NULL_IF_CONFIG_SMALL("Convert the input audio to sample_fmt:channel_layout."),
@@ -161,14 +180,6 @@
     .init          = init,
     .uninit        = uninit,
     .query_formats = query_formats,
-
-    .inputs    = (const AVFilterPad[]) {{ .name      = "default",
-                                    .type            = AVMEDIA_TYPE_AUDIO,
-                                    .filter_samples  = filter_samples,
-                                    .min_perms       = AV_PERM_READ, },
-                                  { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name      = "default",
-                                    .type            = AVMEDIA_TYPE_AUDIO,
-                                    .config_props    = config_output, },
-                                  { .name = NULL}},
+    .inputs        = aconvert_inputs,
+    .outputs       = aconvert_outputs,
 };
diff --git a/libavfilter/af_aformat.c b/libavfilter/af_aformat.c
index 9bc6f5b..b1d779f 100644
--- a/libavfilter/af_aformat.c
+++ b/libavfilter/af_aformat.c
@@ -23,8 +23,8 @@
  * format audio filter
  */
 
-#include "libavutil/audioconvert.h"
 #include "libavutil/avstring.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
 #include "libavutil/opt.h"
 
@@ -126,6 +126,22 @@
     return 0;
 }
 
+static const AVFilterPad avfilter_af_aformat_inputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_AUDIO,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_af_aformat_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_AUDIO
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_aformat = {
     .name          = "aformat",
     .description   = NULL_IF_CONFIG_SMALL("Convert the input audio to one of the specified formats."),
@@ -133,11 +149,7 @@
     .query_formats = query_formats,
     .priv_size     = sizeof(AFormatContext),
 
-    .inputs        = (const AVFilterPad[]) {{ .name            = "default",
-                                              .type            = AVMEDIA_TYPE_AUDIO, },
-                                            { .name = NULL}},
-    .outputs       = (const AVFilterPad[]) {{ .name            = "default",
-                                              .type            = AVMEDIA_TYPE_AUDIO},
-                                            { .name = NULL}},
-    .priv_class = &aformat_class,
+    .inputs        = avfilter_af_aformat_inputs,
+    .outputs       = avfilter_af_aformat_outputs,
+    .priv_class    = &aformat_class,
 };
diff --git a/libavfilter/af_amerge.c b/libavfilter/af_amerge.c
index 77ea297..44b71e4 100644
--- a/libavfilter/af_amerge.c
+++ b/libavfilter/af_amerge.c
@@ -23,9 +23,9 @@
  * Audio merging filter
  */
 
-#include "libavutil/audioconvert.h"
 #include "libavutil/avstring.h"
 #include "libavutil/bprint.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/opt.h"
 #include "libswresample/swresample.h" // only for SWR_CH_MAX
 #include "avfilter.h"
@@ -217,7 +217,7 @@
     }
 }
 
-static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *insamples)
 {
     AVFilterContext *ctx = inlink->dst;
     AMergeContext *am = ctx->priv;
@@ -290,7 +290,7 @@
             }
         }
     }
-    return ff_filter_samples(ctx->outputs[0], outbuf);
+    return ff_filter_frame(ctx->outputs[0], outbuf);
 }
 
 static av_cold int init(AVFilterContext *ctx, const char *args)
@@ -313,7 +313,7 @@
         AVFilterPad pad = {
             .name             = name,
             .type             = AVMEDIA_TYPE_AUDIO,
-            .filter_samples   = filter_samples,
+            .filter_frame     = filter_frame,
             .min_perms        = AV_PERM_READ | AV_PERM_PRESERVE,
         };
         if (!name)
@@ -323,6 +323,16 @@
     return 0;
 }
 
+static const AVFilterPad amerge_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_AUDIO,
+        .config_props  = config_output,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_amerge = {
     .name          = "amerge",
     .description   = NULL_IF_CONFIG_SMALL("Merge two audio streams into "
@@ -331,14 +341,7 @@
     .init          = init,
     .uninit        = uninit,
     .query_formats = query_formats,
-
-    .inputs    = (const AVFilterPad[]) { { .name = NULL } },
-    .outputs   = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_AUDIO,
-          .config_props     = config_output,
-          .request_frame    = request_frame, },
-        { .name = NULL }
-    },
-    .priv_class = &amerge_class,
+    .inputs        = NULL,
+    .outputs       = amerge_outputs,
+    .priv_class    = &amerge_class,
 };
diff --git a/libavfilter/af_amix.c b/libavfilter/af_amix.c
index 9d0f998..aeefff8 100644
--- a/libavfilter/af_amix.c
+++ b/libavfilter/af_amix.c
@@ -28,10 +28,10 @@
  * output.
  */
 
-#include "libavutil/audioconvert.h"
 #include "libavutil/audio_fifo.h"
 #include "libavutil/avassert.h"
 #include "libavutil/avstring.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
 #include "libavutil/float_dsp.h"
 #include "libavutil/mathematics.h"
@@ -280,8 +280,10 @@
         return AVERROR(ENOMEM);
 
     in_buf = ff_get_audio_buffer(outlink, AV_PERM_WRITE, nb_samples);
-    if (!in_buf)
+    if (!in_buf) {
+        avfilter_unref_buffer(out_buf);
         return AVERROR(ENOMEM);
+    }
 
     for (i = 0; i < s->nb_inputs; i++) {
         if (s->input_state[i] == INPUT_ON) {
@@ -307,7 +309,7 @@
     if (s->next_pts != AV_NOPTS_VALUE)
         s->next_pts += nb_samples;
 
-    return ff_filter_samples(outlink, out_buf);
+    return ff_filter_frame(outlink, out_buf);
 }
 
 /**
@@ -448,7 +450,7 @@
     return output_frame(outlink, available_samples);
 }
 
-static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
 {
     AVFilterContext  *ctx = inlink->dst;
     MixContext       *s = ctx->priv;
@@ -500,7 +502,7 @@
         snprintf(name, sizeof(name), "input%d", i);
         pad.type           = AVMEDIA_TYPE_AUDIO;
         pad.name           = av_strdup(name);
-        pad.filter_samples = filter_samples;
+        pad.filter_frame   = filter_frame;
 
         ff_insert_inpad(ctx, i, &pad);
     }
@@ -540,6 +542,16 @@
     return 0;
 }
 
+static const AVFilterPad avfilter_af_amix_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_AUDIO,
+        .config_props  = config_output,
+        .request_frame = request_frame
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_amix = {
     .name          = "amix",
     .description   = NULL_IF_CONFIG_SMALL("Audio mixing."),
@@ -550,10 +562,6 @@
     .query_formats  = query_formats,
 
     .inputs    = NULL,
-    .outputs   = (const AVFilterPad[]) {{ .name          = "default",
-                                          .type          = AVMEDIA_TYPE_AUDIO,
-                                          .config_props  = config_output,
-                                          .request_frame = request_frame },
-                                        { .name = NULL}},
+    .outputs   = avfilter_af_amix_outputs,
     .priv_class = &amix_class,
 };
diff --git a/libavfilter/af_anull.c b/libavfilter/af_anull.c
index 355dff6..40af7b8 100644
--- a/libavfilter/af_anull.c
+++ b/libavfilter/af_anull.c
@@ -27,18 +27,30 @@
 #include "internal.h"
 #include "libavutil/internal.h"
 
+static const AVFilterPad avfilter_af_anull_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_AUDIO,
+        .get_audio_buffer = ff_null_get_audio_buffer,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_af_anull_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_AUDIO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_anull = {
     .name      = "anull",
     .description = NULL_IF_CONFIG_SMALL("Pass the source unchanged to the output."),
 
     .priv_size = 0,
 
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_AUDIO,
-                                          .get_audio_buffer = ff_null_get_audio_buffer, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_af_anull_inputs,
 
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_AUDIO, },
-                                        { .name = NULL}},
+    .outputs   = avfilter_af_anull_outputs,
 };
diff --git a/libavfilter/af_aresample.c b/libavfilter/af_aresample.c
index f0ccb5f..2dcfd69 100644
--- a/libavfilter/af_aresample.c
+++ b/libavfilter/af_aresample.c
@@ -24,8 +24,8 @@
  * resampling audio filter
  */
 
-#include "libavutil/audioconvert.h"
 #include "libavutil/avstring.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/opt.h"
 #include "libavutil/samplefmt.h"
 #include "libavutil/avassert.h"
@@ -49,8 +49,10 @@
 
     aresample->next_pts = AV_NOPTS_VALUE;
     aresample->swr = swr_alloc();
-    if (!aresample->swr)
-        return AVERROR(ENOMEM);
+    if (!aresample->swr) {
+        ret = AVERROR(ENOMEM);
+        goto end;
+    }
 
     if (args) {
         char *ptr=argd, *token;
@@ -168,15 +170,17 @@
     return 0;
 }
 
-static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamplesref)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *insamplesref)
 {
     AResampleContext *aresample = inlink->dst->priv;
     const int n_in  = insamplesref->audio->nb_samples;
-    int n_out       = n_in * aresample->ratio * 2 ;
+    int n_out       = FFMAX(n_in * aresample->ratio * 2, 1);
     AVFilterLink *const outlink = inlink->dst->outputs[0];
     AVFilterBufferRef *outsamplesref = ff_get_audio_buffer(outlink, AV_PERM_WRITE, n_out);
     int ret;
 
+    if(!outsamplesref)
+        return AVERROR(ENOMEM);
 
     avfilter_copy_buffer_ref_props(outsamplesref, insamplesref);
     outsamplesref->format                = outlink->format;
@@ -187,11 +191,10 @@
         int64_t inpts = av_rescale(insamplesref->pts, inlink->time_base.num * (int64_t)outlink->sample_rate * inlink->sample_rate, inlink->time_base.den);
         int64_t outpts= swr_next_pts(aresample->swr, inpts);
         aresample->next_pts =
-        outsamplesref->pts  = (outpts + inlink->sample_rate/2) / inlink->sample_rate;
+        outsamplesref->pts  = ROUNDED_DIV(outpts, inlink->sample_rate);
     } else {
         outsamplesref->pts  = AV_NOPTS_VALUE;
     }
-
     n_out = swr_convert(aresample->swr, outsamplesref->extended_data, n_out,
                                  (void *)insamplesref->extended_data, n_in);
     if (n_out <= 0) {
@@ -202,7 +205,7 @@
 
     outsamplesref->audio->nb_samples  = n_out;
 
-    ret = ff_filter_samples(outlink, outsamplesref);
+    ret = ff_filter_frame(outlink, outsamplesref);
     aresample->req_fullfilled= 1;
     avfilter_unref_buffer(insamplesref);
     return ret;
@@ -240,15 +243,36 @@
         if(aresample->next_pts != AV_NOPTS_VALUE)
             aresample->next_pts += av_rescale_q(n_out, (AVRational){1 ,outlink->sample_rate}, outlink->time_base);
 #else
-        outsamplesref->pts = (swr_next_pts(aresample->swr, INT64_MIN) + inlink->sample_rate/2) / inlink->sample_rate;
+        outsamplesref->pts = swr_next_pts(aresample->swr, INT64_MIN);
+        outsamplesref->pts = ROUNDED_DIV(outsamplesref->pts, inlink->sample_rate);
 #endif
 
-        ff_filter_samples(outlink, outsamplesref);
+        ff_filter_frame(outlink, outsamplesref);
         return 0;
     }
     return ret;
 }
 
+static const AVFilterPad aresample_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_AUDIO,
+        .filter_frame = filter_frame,
+        .min_perms    = AV_PERM_READ,
+    },
+    { NULL },
+};
+
+static const AVFilterPad aresample_outputs[] = {
+    {
+        .name          = "default",
+        .config_props  = config_output,
+        .request_frame = request_frame,
+        .type          = AVMEDIA_TYPE_AUDIO,
+    },
+    { NULL },
+};
+
 AVFilter avfilter_af_aresample = {
     .name          = "aresample",
     .description   = NULL_IF_CONFIG_SMALL("Resample audio data."),
@@ -256,15 +280,6 @@
     .uninit        = uninit,
     .query_formats = query_formats,
     .priv_size     = sizeof(AResampleContext),
-
-    .inputs    = (const AVFilterPad[]) {{ .name      = "default",
-                                    .type            = AVMEDIA_TYPE_AUDIO,
-                                    .filter_samples  = filter_samples,
-                                    .min_perms       = AV_PERM_READ, },
-                                  { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name      = "default",
-                                    .config_props    = config_output,
-                                    .request_frame   = request_frame,
-                                    .type            = AVMEDIA_TYPE_AUDIO, },
-                                  { .name = NULL}},
+    .inputs        = aresample_inputs,
+    .outputs       = aresample_outputs,
 };
diff --git a/libavfilter/af_asetnsamples.c b/libavfilter/af_asetnsamples.c
index 467af76..ee80c1c 100644
--- a/libavfilter/af_asetnsamples.c
+++ b/libavfilter/af_asetnsamples.c
@@ -25,8 +25,8 @@
  */
 
 #include "libavutil/audio_fifo.h"
-#include "libavutil/audioconvert.h"
 #include "libavutil/avassert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/opt.h"
 #include "avfilter.h"
 #include "audio.h"
@@ -125,12 +125,12 @@
     if (asns->next_out_pts != AV_NOPTS_VALUE)
         asns->next_out_pts += nb_out_samples;
 
-    ff_filter_samples(outlink, outsamples);
+    ff_filter_frame(outlink, outsamples);
     asns->req_fullfilled = 1;
     return nb_out_samples;
 }
 
-static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *insamples)
 {
     AVFilterContext *ctx = inlink->dst;
     ASNSContext *asns = ctx->priv;
@@ -175,31 +175,33 @@
     return ret;
 }
 
+static const AVFilterPad asetnsamples_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_AUDIO,
+        .filter_frame = filter_frame,
+        .min_perms    = AV_PERM_READ | AV_PERM_WRITE,
+    },
+    {  NULL }
+};
+
+static const AVFilterPad asetnsamples_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_AUDIO,
+        .request_frame = request_frame,
+        .config_props  = config_props_output,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_asetnsamples = {
     .name           = "asetnsamples",
     .description    = NULL_IF_CONFIG_SMALL("Set the number of samples for each output audio frames."),
     .priv_size      = sizeof(ASNSContext),
     .init           = init,
     .uninit         = uninit,
-
-    .inputs  = (const AVFilterPad[]) {
-        {
-            .name           = "default",
-            .type           = AVMEDIA_TYPE_AUDIO,
-            .filter_samples = filter_samples,
-            .min_perms      = AV_PERM_READ|AV_PERM_WRITE
-        },
-        { .name = NULL }
-    },
-
-    .outputs = (const AVFilterPad[]) {
-        {
-            .name           = "default",
-            .type           = AVMEDIA_TYPE_AUDIO,
-            .request_frame  = request_frame,
-            .config_props   = config_props_output,
-        },
-        { .name = NULL }
-    },
-    .priv_class = &asetnsamples_class,
+    .inputs         = asetnsamples_inputs,
+    .outputs        = asetnsamples_outputs,
+    .priv_class     = &asetnsamples_class,
 };
diff --git a/libavfilter/af_ashowinfo.c b/libavfilter/af_ashowinfo.c
index 25a5e2c..7e7543f 100644
--- a/libavfilter/af_ashowinfo.c
+++ b/libavfilter/af_ashowinfo.c
@@ -23,84 +23,111 @@
  * filter for showing textual audio frame information
  */
 
+#include <inttypes.h>
+#include <stddef.h>
+
 #include "libavutil/adler32.h"
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
+#include "libavutil/common.h"
+#include "libavutil/mem.h"
 #include "libavutil/timestamp.h"
+#include "libavutil/samplefmt.h"
+
 #include "audio.h"
 #include "avfilter.h"
+#include "internal.h"
 
-typedef struct {
-    unsigned int frame;
-} ShowInfoContext;
+typedef struct AShowInfoContext {
+    /**
+     * Scratch space for individual plane checksums for planar audio
+     */
+    uint32_t *plane_checksums;
 
-static av_cold int init(AVFilterContext *ctx, const char *args)
+    /**
+     * Frame counter
+     */
+    uint64_t frame;
+} AShowInfoContext;
+
+static void uninit(AVFilterContext *ctx)
 {
-    ShowInfoContext *showinfo = ctx->priv;
-    showinfo->frame = 0;
-    return 0;
+    AShowInfoContext *s = ctx->priv;
+    av_freep(&s->plane_checksums);
 }
 
-static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *samplesref)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
 {
     AVFilterContext *ctx = inlink->dst;
-    ShowInfoContext *showinfo = ctx->priv;
-    uint32_t plane_checksum[8] = {0}, checksum = 0;
+    AShowInfoContext *s  = ctx->priv;
     char chlayout_str[128];
-    int plane;
-    int linesize =
-        samplesref->audio->nb_samples *
-        av_get_bytes_per_sample(samplesref->format);
-    if (!av_sample_fmt_is_planar(samplesref->format))
-        linesize *= av_get_channel_layout_nb_channels(samplesref->audio->channel_layout);
+    uint32_t checksum = 0;
+    int channels    = av_get_channel_layout_nb_channels(buf->audio->channel_layout);
+    int planar      = av_sample_fmt_is_planar(buf->format);
+    int block_align = av_get_bytes_per_sample(buf->format) * (planar ? 1 : channels);
+    int data_size   = buf->audio->nb_samples * block_align;
+    int planes      = planar ? channels : 1;
+    int i;
+    void *tmp_ptr = av_realloc(s->plane_checksums, channels * sizeof(*s->plane_checksums));
 
-    for (plane = 0; plane < 8 && samplesref->data[plane]; plane++) {
-        uint8_t *data = samplesref->data[plane];
+    if (!tmp_ptr)
+        return AVERROR(ENOMEM);
+    s->plane_checksums = tmp_ptr;
 
-        plane_checksum[plane] = av_adler32_update(plane_checksum[plane],
-                                                  data, linesize);
-        checksum = av_adler32_update(checksum, data, linesize);
+    for (i = 0; i < planes; i++) {
+        uint8_t *data = buf->extended_data[i];
+
+        s->plane_checksums[i] = av_adler32_update(0, data, data_size);
+        checksum = i ? av_adler32_update(checksum, data, data_size) :
+                       s->plane_checksums[0];
     }
 
     av_get_channel_layout_string(chlayout_str, sizeof(chlayout_str), -1,
-                                 samplesref->audio->channel_layout);
+                                 buf->audio->channel_layout);
 
     av_log(ctx, AV_LOG_INFO,
-           "n:%d pts:%s pts_time:%s pos:%"PRId64" "
-           "fmt:%s chlayout:%s nb_samples:%d rate:%d "
-           "checksum:%08X plane_checksum[%08X",
-           showinfo->frame,
-           av_ts2str(samplesref->pts), av_ts2timestr(samplesref->pts, &inlink->time_base),
-           samplesref->pos,
-           av_get_sample_fmt_name(samplesref->format),
-           chlayout_str,
-           samplesref->audio->nb_samples,
-           samplesref->audio->sample_rate,
-           checksum,
-           plane_checksum[0]);
+           "n:%"PRIu64" pts:%s pts_time:%s pos:%"PRId64" "
+           "fmt:%s channels:%d chlayout:%s rate:%d nb_samples:%d "
+           "checksum:%08X ",
+           s->frame,
+           av_ts2str(buf->pts), av_ts2timestr(buf->pts, &inlink->time_base),
+           buf->pos,
+           av_get_sample_fmt_name(buf->format), buf->audio->channels, chlayout_str,
+           buf->audio->sample_rate, buf->audio->nb_samples,
+           checksum);
 
-    for (plane = 1; plane < 8 && samplesref->data[plane]; plane++)
-        av_log(ctx, AV_LOG_INFO, " %08X", plane_checksum[plane]);
+    av_log(ctx, AV_LOG_INFO, "plane_checksums: [ ");
+    for (i = 0; i < planes; i++)
+        av_log(ctx, AV_LOG_INFO, "%08X ", s->plane_checksums[i]);
     av_log(ctx, AV_LOG_INFO, "]\n");
 
-    showinfo->frame++;
-    return ff_filter_samples(inlink->dst->outputs[0], samplesref);
+    s->frame++;
+    return ff_filter_frame(inlink->dst->outputs[0], buf);
 }
 
+static const AVFilterPad inputs[] = {
+    {
+        .name       = "default",
+        .type             = AVMEDIA_TYPE_AUDIO,
+        .get_audio_buffer = ff_null_get_audio_buffer,
+        .filter_frame     = filter_frame,
+        .min_perms        = AV_PERM_READ,
+    },
+    { NULL },
+};
+
+static const AVFilterPad outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_AUDIO,
+    },
+    { NULL },
+};
+
 AVFilter avfilter_af_ashowinfo = {
     .name        = "ashowinfo",
     .description = NULL_IF_CONFIG_SMALL("Show textual information for each audio frame."),
-
-    .priv_size = sizeof(ShowInfoContext),
-    .init      = init,
-
-    .inputs    = (const AVFilterPad[]) {{ .name       = "default",
-                                    .type             = AVMEDIA_TYPE_AUDIO,
-                                    .get_audio_buffer = ff_null_get_audio_buffer,
-                                    .filter_samples   = filter_samples,
-                                    .min_perms        = AV_PERM_READ, },
-                                  { .name = NULL}},
-
-    .outputs   = (const AVFilterPad[]) {{ .name       = "default",
-                                    .type             = AVMEDIA_TYPE_AUDIO },
-                                  { .name = NULL}},
+    .priv_size   = sizeof(AShowInfoContext),
+    .uninit      = uninit,
+    .inputs      = inputs,
+    .outputs     = outputs,
 };
diff --git a/libavfilter/af_astreamsync.c b/libavfilter/af_astreamsync.c
index 9768647..269ffc1 100644
--- a/libavfilter/af_astreamsync.c
+++ b/libavfilter/af_astreamsync.c
@@ -122,7 +122,7 @@
             av_q2d(ctx->outputs[out_id]->time_base) * buf->pts;
     as->var_values[VAR_T1 + out_id] += buf->audio->nb_samples /
                                    (double)ctx->inputs[out_id]->sample_rate;
-    ret = ff_filter_samples(ctx->outputs[out_id], buf);
+    ret = ff_filter_frame(ctx->outputs[out_id], buf);
     queue->nb--;
     queue->tail = (queue->tail + 1) % QUEUE_SIZE;
     if (as->req[out_id])
@@ -167,7 +167,7 @@
     return 0;
 }
 
-static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *insamples)
 {
     AVFilterContext *ctx = inlink->dst;
     AStreamSyncContext *as = ctx->priv;
@@ -180,6 +180,36 @@
     return 0;
 }
 
+static const AVFilterPad astreamsync_inputs[] = {
+    {
+        .name         = "in1",
+        .type         = AVMEDIA_TYPE_AUDIO,
+        .filter_frame = filter_frame,
+        .min_perms    = AV_PERM_READ | AV_PERM_PRESERVE,
+    },{
+        .name         = "in2",
+        .type         = AVMEDIA_TYPE_AUDIO,
+        .filter_frame = filter_frame,
+        .min_perms    = AV_PERM_READ | AV_PERM_PRESERVE,
+    },
+    { NULL }
+};
+
+static const AVFilterPad astreamsync_outputs[] = {
+    {
+        .name          = "out1",
+        .type          = AVMEDIA_TYPE_AUDIO,
+        .config_props  = config_output,
+        .request_frame = request_frame,
+    },{
+        .name          = "out2",
+        .type          = AVMEDIA_TYPE_AUDIO,
+        .config_props  = config_output,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_astreamsync = {
     .name          = "astreamsync",
     .description   = NULL_IF_CONFIG_SMALL("Copy two streams of audio data "
@@ -187,27 +217,6 @@
     .priv_size     = sizeof(AStreamSyncContext),
     .init          = init,
     .query_formats = query_formats,
-
-    .inputs    = (const AVFilterPad[]) {
-        { .name             = "in1",
-          .type             = AVMEDIA_TYPE_AUDIO,
-          .filter_samples   = filter_samples,
-          .min_perms        = AV_PERM_READ | AV_PERM_PRESERVE, },
-        { .name             = "in2",
-          .type             = AVMEDIA_TYPE_AUDIO,
-          .filter_samples   = filter_samples,
-          .min_perms        = AV_PERM_READ | AV_PERM_PRESERVE, },
-        { .name = NULL }
-    },
-    .outputs   = (const AVFilterPad[]) {
-        { .name             = "out1",
-          .type             = AVMEDIA_TYPE_AUDIO,
-          .config_props     = config_output,
-          .request_frame    = request_frame, },
-        { .name             = "out2",
-          .type             = AVMEDIA_TYPE_AUDIO,
-          .config_props     = config_output,
-          .request_frame    = request_frame, },
-        { .name = NULL }
-    },
+    .inputs        = astreamsync_inputs,
+    .outputs       = astreamsync_outputs,
 };
diff --git a/libavfilter/af_asyncts.c b/libavfilter/af_asyncts.c
index 18892d4..b5d0aea 100644
--- a/libavfilter/af_asyncts.c
+++ b/libavfilter/af_asyncts.c
@@ -39,7 +39,7 @@
     float min_delta_sec;
     int max_comp;
 
-    /* set by filter_samples() to signal an output frame to request_frame() */
+    /* set by filter_frame() to signal an output frame to request_frame() */
     int got_output;
 } ASyncContext;
 
@@ -127,7 +127,7 @@
                                                      nb_samples);
         if (!buf)
             return AVERROR(ENOMEM);
-        ret = avresample_convert(s->avr, (void**)buf->extended_data,
+        ret = avresample_convert(s->avr, buf->extended_data,
                                  buf->linesize[0], nb_samples, NULL, 0, 0);
         if (ret <= 0) {
             avfilter_unref_bufferp(&buf);
@@ -135,7 +135,7 @@
         }
 
         buf->pts = s->pts;
-        return ff_filter_samples(link, buf);
+        return ff_filter_frame(link, buf);
     }
 
     return ret;
@@ -143,7 +143,7 @@
 
 static int write_to_fifo(ASyncContext *s, AVFilterBufferRef *buf)
 {
-    int ret = avresample_convert(s->avr, NULL, 0, 0, (void**)buf->extended_data,
+    int ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
                                  buf->linesize[0], buf->audio->nb_samples);
     avfilter_unref_buffer(buf);
     return ret;
@@ -155,7 +155,7 @@
     return avresample_available(s->avr) + avresample_get_delay(s->avr);
 }
 
-static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
 {
     AVFilterContext  *ctx = inlink->dst;
     ASyncContext       *s = ctx->priv;
@@ -204,14 +204,14 @@
             goto fail;
         }
 
-        avresample_read(s->avr, (void**)buf_out->extended_data, out_size);
+        avresample_read(s->avr, buf_out->extended_data, out_size);
         buf_out->pts = s->pts;
 
         if (delta > 0) {
             av_samples_set_silence(buf_out->extended_data, out_size - delta,
                                    delta, nb_channels, buf->format);
         }
-        ret = ff_filter_samples(outlink, buf_out);
+        ret = ff_filter_frame(outlink, buf_out);
         if (ret < 0)
             goto fail;
         s->got_output = 1;
@@ -224,7 +224,7 @@
     avresample_read(s->avr, NULL, avresample_available(s->avr));
 
     s->pts = pts - avresample_get_delay(s->avr);
-    ret = avresample_convert(s->avr, NULL, 0, 0, (void**)buf->extended_data,
+    ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
                              buf->linesize[0], buf->audio->nb_samples);
 
 fail:
@@ -233,6 +233,25 @@
     return ret;
 }
 
+static const AVFilterPad avfilter_af_asyncts_inputs[] = {
+    {
+        .name           = "default",
+        .type           = AVMEDIA_TYPE_AUDIO,
+        .filter_frame   = filter_frame
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_af_asyncts_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_AUDIO,
+        .config_props  = config_props,
+        .request_frame = request_frame
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_asyncts = {
     .name        = "asyncts",
     .description = NULL_IF_CONFIG_SMALL("Sync audio data to timestamps"),
@@ -242,14 +261,7 @@
 
     .priv_size   = sizeof(ASyncContext),
 
-    .inputs      = (const AVFilterPad[]) {{ .name           = "default",
-                                            .type           = AVMEDIA_TYPE_AUDIO,
-                                            .filter_samples = filter_samples },
-                                          { NULL }},
-    .outputs     = (const AVFilterPad[]) {{ .name           = "default",
-                                            .type           = AVMEDIA_TYPE_AUDIO,
-                                            .config_props   = config_props,
-                                            .request_frame  = request_frame },
-                                          { NULL }},
+    .inputs      = avfilter_af_asyncts_inputs,
+    .outputs     = avfilter_af_asyncts_outputs,
     .priv_class = &asyncts_class,
 };
diff --git a/libavfilter/af_atempo.c b/libavfilter/af_atempo.c
index c2d1fc1..74bf9cc 100644
--- a/libavfilter/af_atempo.c
+++ b/libavfilter/af_atempo.c
@@ -40,9 +40,9 @@
 
 #include <float.h>
 #include "libavcodec/avfft.h"
-#include "libavutil/audioconvert.h"
 #include "libavutil/avassert.h"
 #include "libavutil/avstring.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/eval.h"
 #include "libavutil/opt.h"
 #include "libavutil/samplefmt.h"
@@ -138,7 +138,7 @@
     RDFTContext *complex_to_real;
     FFTSample *correlation;
 
-    // for managing AVFilterPad.request_frame and AVFilterPad.filter_samples
+    // for managing AVFilterPad.request_frame and AVFilterPad.filter_frame
     int request_fulfilled;
     AVFilterBufferRef *dst_buffer;
     uint8_t *dst;
@@ -1033,7 +1033,7 @@
                      (AVRational){ 1, outlink->sample_rate },
                      outlink->time_base);
 
-    ff_filter_samples(outlink, atempo->dst_buffer);
+    ff_filter_frame(outlink, atempo->dst_buffer);
     atempo->dst_buffer = NULL;
     atempo->dst        = NULL;
     atempo->dst_end    = NULL;
@@ -1041,7 +1041,7 @@
     atempo->nsamples_out += n_out;
 }
 
-static int filter_samples(AVFilterLink *inlink,
+static int filter_frame(AVFilterLink *inlink,
                            AVFilterBufferRef *src_buffer)
 {
     AVFilterContext  *ctx = inlink->dst;
@@ -1136,6 +1136,26 @@
     return !strcmp(cmd, "tempo") ? yae_set_tempo(ctx, arg) : AVERROR(ENOSYS);
 }
 
+static const AVFilterPad atempo_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_AUDIO,
+        .filter_frame = filter_frame,
+        .config_props = config_props,
+        .min_perms    = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad atempo_outputs[] = {
+    {
+        .name          = "default",
+        .request_frame = request_frame,
+        .type          = AVMEDIA_TYPE_AUDIO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_atempo = {
     .name            = "atempo",
     .description     = NULL_IF_CONFIG_SMALL("Adjust audio tempo."),
@@ -1144,20 +1164,6 @@
     .query_formats   = query_formats,
     .process_command = process_command,
     .priv_size       = sizeof(ATempoContext),
-
-    .inputs    = (const AVFilterPad[]) {
-        { .name            = "default",
-          .type            = AVMEDIA_TYPE_AUDIO,
-          .filter_samples  = filter_samples,
-          .config_props    = config_props,
-          .min_perms       = AV_PERM_READ, },
-        { .name = NULL}
-    },
-
-    .outputs   = (const AVFilterPad[]) {
-        { .name            = "default",
-          .request_frame   = request_frame,
-          .type            = AVMEDIA_TYPE_AUDIO, },
-        { .name = NULL}
-    },
+    .inputs          = atempo_inputs,
+    .outputs         = atempo_outputs,
 };
diff --git a/libavfilter/af_channelmap.c b/libavfilter/af_channelmap.c
index 50289c3..6fe8704 100644
--- a/libavfilter/af_channelmap.c
+++ b/libavfilter/af_channelmap.c
@@ -25,8 +25,8 @@
 
 #include <ctype.h>
 
-#include "libavutil/audioconvert.h"
 #include "libavutil/avstring.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
 #include "libavutil/mathematics.h"
 #include "libavutil/opt.h"
@@ -125,7 +125,6 @@
     ChannelMapContext *s = ctx->priv;
     int ret;
     char *mapping;
-    enum mode;
     int map_entries = 0;
     char buf[256];
     enum MappingMode mode;
@@ -313,7 +312,7 @@
     return 0;
 }
 
-static int channelmap_filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)
+static int channelmap_filter_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
 {
     AVFilterContext  *ctx = inlink->dst;
     AVFilterLink *outlink = ctx->outputs[0];
@@ -337,8 +336,8 @@
             if (buf->extended_data == buf->data) {
                 buf->extended_data = new_extended_data;
             } else {
-                buf->extended_data = new_extended_data;
                 av_free(buf->extended_data);
+                buf->extended_data = new_extended_data;
             }
         } else if (buf->extended_data != buf->data) {
             av_free(buf->extended_data);
@@ -355,7 +354,7 @@
         memcpy(buf->data, buf->extended_data,
            FFMIN(FF_ARRAY_ELEMS(buf->data), nch_out) * sizeof(buf->data[0]));
 
-    return ff_filter_samples(outlink, buf);
+    return ff_filter_frame(outlink, buf);
 }
 
 static int channelmap_config_input(AVFilterLink *inlink)
@@ -385,6 +384,25 @@
     return err;
 }
 
+static const AVFilterPad avfilter_af_channelmap_inputs[] = {
+    {
+        .name           = "default",
+        .type           = AVMEDIA_TYPE_AUDIO,
+        .min_perms      = AV_PERM_READ | AV_PERM_WRITE,
+        .filter_frame   = channelmap_filter_frame,
+        .config_props   = channelmap_config_input
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_af_channelmap_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_AUDIO
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_channelmap = {
     .name          = "channelmap",
     .description   = NULL_IF_CONFIG_SMALL("Remap audio channels."),
@@ -392,14 +410,7 @@
     .query_formats = channelmap_query_formats,
     .priv_size     = sizeof(ChannelMapContext),
 
-    .inputs        = (const AVFilterPad[]) {{ .name            = "default",
-                                              .type            = AVMEDIA_TYPE_AUDIO,
-                                              .min_perms       = AV_PERM_READ | AV_PERM_WRITE,
-                                              .filter_samples  = channelmap_filter_samples,
-                                              .config_props    = channelmap_config_input },
-                                            { .name = NULL }},
-    .outputs       = (const AVFilterPad[]) {{ .name            = "default",
-                                              .type            = AVMEDIA_TYPE_AUDIO },
-                                            { .name = NULL }},
-    .priv_class = &channelmap_class,
+    .inputs        = avfilter_af_channelmap_inputs,
+    .outputs       = avfilter_af_channelmap_outputs,
+    .priv_class    = &channelmap_class,
 };
diff --git a/libavfilter/af_channelsplit.c b/libavfilter/af_channelsplit.c
index 81f91ad..9ca9dad 100644
--- a/libavfilter/af_channelsplit.c
+++ b/libavfilter/af_channelsplit.c
@@ -23,7 +23,7 @@
  * Split an audio stream into per-channel streams.
  */
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/internal.h"
 #include "libavutil/opt.h"
 
@@ -105,7 +105,7 @@
     return 0;
 }
 
-static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
 {
     AVFilterContext *ctx = inlink->dst;
     int i, ret = 0;
@@ -122,7 +122,7 @@
         buf_out->audio->channel_layout =
             av_channel_layout_extract_channel(buf->audio->channel_layout, i);
 
-        ret = ff_filter_samples(ctx->outputs[i], buf_out);
+        ret = ff_filter_frame(ctx->outputs[i], buf_out);
         if (ret < 0)
             break;
     }
@@ -130,6 +130,15 @@
     return ret;
 }
 
+static const AVFilterPad avfilter_af_channelsplit_inputs[] = {
+    {
+        .name           = "default",
+        .type           = AVMEDIA_TYPE_AUDIO,
+        .filter_frame   = filter_frame,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_channelsplit = {
     .name           = "channelsplit",
     .description    = NULL_IF_CONFIG_SMALL("Split audio into per-channel streams"),
@@ -138,10 +147,7 @@
     .init           = init,
     .query_formats  = query_formats,
 
-    .inputs  = (const AVFilterPad[]){{ .name           = "default",
-                                       .type           = AVMEDIA_TYPE_AUDIO,
-                                       .filter_samples = filter_samples, },
-                                     { NULL }},
+    .inputs  = avfilter_af_channelsplit_inputs,
     .outputs = NULL,
     .priv_class = &channelsplit_class,
 };
diff --git a/libavfilter/af_earwax.c b/libavfilter/af_earwax.c
index 7265c43..4a2b8b7 100644
--- a/libavfilter/af_earwax.c
+++ b/libavfilter/af_earwax.c
@@ -29,7 +29,7 @@
  * front of the listener. Adapted from the libsox earwax effect.
  */
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "avfilter.h"
 #include "audio.h"
 #include "formats.h"
@@ -120,7 +120,7 @@
     return out;
 }
 
-static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *insamples)
 {
     AVFilterLink *outlink = inlink->dst->outputs[0];
     int16_t *taps, *endin, *in, *out;
@@ -129,6 +129,8 @@
                                   insamples->audio->nb_samples);
     int ret;
 
+    if (!outsamples)
+        return AVERROR(ENOMEM);
     avfilter_copy_buffer_ref_props(outsamples, insamples);
 
     taps  = ((EarwaxContext *)inlink->dst->priv)->taps;
@@ -141,29 +143,40 @@
 
     // process current input
     endin = in + insamples->audio->nb_samples * 2 - NUMTAPS;
-    out   = scalarproduct(in, endin, out);
+    scalarproduct(in, endin, out);
 
     // save part of input for next round
     memcpy(taps, endin, NUMTAPS * sizeof(*taps));
 
-    ret = ff_filter_samples(outlink, outsamples);
+    ret = ff_filter_frame(outlink, outsamples);
     avfilter_unref_buffer(insamples);
     return ret;
 }
 
+static const AVFilterPad earwax_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_AUDIO,
+        .filter_frame = filter_frame,
+        .config_props = config_input,
+        .min_perms    = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad earwax_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_AUDIO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_earwax = {
     .name           = "earwax",
     .description    = NULL_IF_CONFIG_SMALL("Widen the stereo image."),
     .query_formats  = query_formats,
     .priv_size      = sizeof(EarwaxContext),
-    .inputs  = (const AVFilterPad[])  {{  .name     = "default",
-                                    .type           = AVMEDIA_TYPE_AUDIO,
-                                    .filter_samples = filter_samples,
-                                    .config_props   = config_input,
-                                    .min_perms      = AV_PERM_READ, },
-                                 {  .name = NULL}},
-
-    .outputs = (const AVFilterPad[])  {{  .name     = "default",
-                                    .type           = AVMEDIA_TYPE_AUDIO, },
-                                 {  .name = NULL}},
+    .inputs         = earwax_inputs,
+    .outputs        = earwax_outputs,
 };
diff --git a/libavfilter/af_join.c b/libavfilter/af_join.c
index 5e338f0..864663b 100644
--- a/libavfilter/af_join.c
+++ b/libavfilter/af_join.c
@@ -25,8 +25,8 @@
  * a single output
  */
 
-#include "libavutil/audioconvert.h"
 #include "libavutil/avassert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
 #include "libavutil/opt.h"
 
@@ -94,7 +94,7 @@
     .version    = LIBAVUTIL_VERSION_INT,
 };
 
-static int filter_samples(AVFilterLink *link, AVFilterBufferRef *buf)
+static int filter_frame(AVFilterLink *link, AVFilterBufferRef *buf)
 {
     AVFilterContext *ctx = link->dst;
     JoinContext       *s = ctx->priv;
@@ -229,7 +229,7 @@
         snprintf(name, sizeof(name), "input%d", i);
         pad.type           = AVMEDIA_TYPE_AUDIO;
         pad.name           = av_strdup(name);
-        pad.filter_samples = filter_samples;
+        pad.filter_frame   = filter_frame;
 
         pad.needs_fifo = 1;
 
@@ -470,7 +470,7 @@
     priv->nb_in_buffers = ctx->nb_inputs;
     buf->buf->priv      = priv;
 
-    ret = ff_filter_samples(outlink, buf);
+    ret = ff_filter_frame(outlink, buf);
 
     memset(s->input_frames, 0, sizeof(*s->input_frames) * ctx->nb_inputs);
 
@@ -484,6 +484,16 @@
     return AVERROR(ENOMEM);
 }
 
+static const AVFilterPad avfilter_af_join_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_AUDIO,
+        .config_props  = join_config_output,
+        .request_frame = join_request_frame,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_join = {
     .name           = "join",
     .description    = NULL_IF_CONFIG_SMALL("Join multiple audio streams into "
@@ -495,10 +505,6 @@
     .query_formats  = join_query_formats,
 
     .inputs  = NULL,
-    .outputs = (const AVFilterPad[]){{ .name          = "default",
-                                       .type          = AVMEDIA_TYPE_AUDIO,
-                                       .config_props  = join_config_output,
-                                       .request_frame = join_request_frame, },
-                                     { NULL }},
+    .outputs = avfilter_af_join_outputs,
     .priv_class = &join_class,
 };
diff --git a/libavfilter/af_pan.c b/libavfilter/af_pan.c
index 80a912e..922025a 100644
--- a/libavfilter/af_pan.c
+++ b/libavfilter/af_pan.c
@@ -28,8 +28,8 @@
  */
 
 #include <stdio.h>
-#include "libavutil/audioconvert.h"
 #include "libavutil/avstring.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/opt.h"
 #include "libswresample/swresample.h"
 #include "audio.h"
@@ -115,7 +115,7 @@
     arg = av_strtok(args, ":", &tokenizer);
     ret = ff_parse_channel_layout(&pan->out_channel_layout, arg, ctx);
     if (ret < 0)
-        return ret;
+        goto fail;
     pan->nb_output_channels = av_get_channel_layout_nb_channels(pan->out_channel_layout);
 
     /* parse channel specifications */
@@ -124,13 +124,15 @@
         if (parse_channel_name(&arg, &out_ch_id, &named)) {
             av_log(ctx, AV_LOG_ERROR,
                    "Expected out channel name, got \"%.8s\"\n", arg);
-            return AVERROR(EINVAL);
+            ret = AVERROR(EINVAL);
+            goto fail;
         }
         if (named) {
             if (!((pan->out_channel_layout >> out_ch_id) & 1)) {
                 av_log(ctx, AV_LOG_ERROR,
                        "Channel \"%.8s\" does not exist in the chosen layout\n", arg0);
-                return AVERROR(EINVAL);
+                ret = AVERROR(EINVAL);
+                goto fail;
             }
             /* get the channel number in the output channel layout:
              * out_channel_layout & ((1 << out_ch_id) - 1) are all the
@@ -141,7 +143,8 @@
         if (out_ch_id < 0 || out_ch_id >= pan->nb_output_channels) {
             av_log(ctx, AV_LOG_ERROR,
                    "Invalid out channel name \"%.8s\"\n", arg0);
-            return AVERROR(EINVAL);
+            ret = AVERROR(EINVAL);
+            goto fail;
         }
         skip_spaces(&arg);
         if (*arg == '=') {
@@ -152,7 +155,8 @@
         } else {
             av_log(ctx, AV_LOG_ERROR,
                    "Syntax error after channel name in \"%.8s\"\n", arg0);
-            return AVERROR(EINVAL);
+            ret = AVERROR(EINVAL);
+            goto fail;
         }
         /* gains */
         while (1) {
@@ -162,13 +166,15 @@
             if (parse_channel_name(&arg, &in_ch_id, &named)){
                 av_log(ctx, AV_LOG_ERROR,
                        "Expected in channel name, got \"%.8s\"\n", arg);
-                return AVERROR(EINVAL);
+                 ret = AVERROR(EINVAL);
+                 goto fail;
             }
             nb_in_channels[named]++;
             if (nb_in_channels[!named]) {
                 av_log(ctx, AV_LOG_ERROR,
                        "Can not mix named and numbered channels\n");
-                return AVERROR(EINVAL);
+                ret = AVERROR(EINVAL);
+                goto fail;
             }
             pan->gain[out_ch_id][in_ch_id] = gain;
             skip_spaces(&arg);
@@ -176,15 +182,18 @@
                 break;
             if (*arg != '+') {
                 av_log(ctx, AV_LOG_ERROR, "Syntax error near \"%.8s\"\n", arg);
-                return AVERROR(EINVAL);
+                ret = AVERROR(EINVAL);
+                goto fail;
             }
             arg++;
         }
     }
     pan->need_renumber = !!nb_in_channels[1];
 
+    ret = 0;
+fail:
     av_free(args);
-    return 0;
+    return ret;
 }
 
 static int are_gains_pure(const PanContext *pan)
@@ -344,7 +353,7 @@
     return 0;
 }
 
-static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *insamples)
 {
     int ret;
     int n = insamples->audio->nb_samples;
@@ -356,7 +365,7 @@
     avfilter_copy_buffer_ref_props(outsamples, insamples);
     outsamples->audio->channel_layout = outlink->channel_layout;
 
-    ret = ff_filter_samples(outlink, outsamples);
+    ret = ff_filter_frame(outlink, outsamples);
     avfilter_unref_buffer(insamples);
     return ret;
 }
@@ -367,6 +376,25 @@
     swr_free(&pan->swr);
 }
 
+static const AVFilterPad pan_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_AUDIO,
+        .config_props = config_props,
+        .filter_frame = filter_frame,
+        .min_perms    = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad pan_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_AUDIO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_pan = {
     .name          = "pan",
     .description   = NULL_IF_CONFIG_SMALL("Remix channels with coefficients (panning)."),
@@ -374,18 +402,6 @@
     .init          = init,
     .uninit        = uninit,
     .query_formats = query_formats,
-
-    .inputs    = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_AUDIO,
-          .config_props     = config_props,
-          .filter_samples   = filter_samples,
-          .min_perms        = AV_PERM_READ, },
-        { .name = NULL}
-    },
-    .outputs   = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_AUDIO, },
-        { .name = NULL}
-    },
+    .inputs        = pan_inputs,
+    .outputs       = pan_outputs,
 };
diff --git a/libavfilter/af_resample.c b/libavfilter/af_resample.c
index eb2d2f9..c712b46 100644
--- a/libavfilter/af_resample.c
+++ b/libavfilter/af_resample.c
@@ -40,7 +40,7 @@
 
     int64_t next_pts;
 
-    /* set by filter_samples() to signal an output frame to request_frame() */
+    /* set by filter_frame() to signal an output frame to request_frame() */
     int got_output;
 } ResampleContext;
 
@@ -93,7 +93,11 @@
 
     if (inlink->channel_layout == outlink->channel_layout &&
         inlink->sample_rate    == outlink->sample_rate    &&
-        inlink->format         == outlink->format)
+        (inlink->format        == outlink->format ||
+        (av_get_channel_layout_nb_channels(inlink->channel_layout)  == 1 &&
+         av_get_channel_layout_nb_channels(outlink->channel_layout) == 1 &&
+         av_get_planar_sample_fmt(inlink->format) ==
+         av_get_planar_sample_fmt(outlink->format))))
         return 0;
 
     if (!(s->avr = avresample_alloc_context()))
@@ -149,7 +153,7 @@
         if (!buf)
             return AVERROR(ENOMEM);
 
-        ret = avresample_convert(s->avr, (void**)buf->extended_data,
+        ret = avresample_convert(s->avr, buf->extended_data,
                                  buf->linesize[0], nb_samples,
                                  NULL, 0, 0);
         if (ret <= 0) {
@@ -158,12 +162,12 @@
         }
 
         buf->pts = s->next_pts;
-        return ff_filter_samples(outlink, buf);
+        return ff_filter_frame(outlink, buf);
     }
     return ret;
 }
 
-static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
 {
     AVFilterContext  *ctx = inlink->dst;
     ResampleContext    *s = ctx->priv;
@@ -186,13 +190,14 @@
             goto fail;
         }
 
-        ret     = avresample_convert(s->avr, (void**)buf_out->extended_data,
+        ret     = avresample_convert(s->avr, buf_out->extended_data,
                                      buf_out->linesize[0], nb_samples,
-                                     (void**)buf->extended_data, buf->linesize[0],
+                                     buf->extended_data, buf->linesize[0],
                                      buf->audio->nb_samples);
-        if (ret < 0) {
+        if (ret <= 0) {
             avfilter_unref_buffer(buf_out);
-            goto fail;
+            if (ret < 0)
+                goto fail;
         }
 
         av_assert0(!avresample_available(s->avr));
@@ -219,20 +224,41 @@
 
             s->next_pts = buf_out->pts + buf_out->audio->nb_samples;
 
-            ret = ff_filter_samples(outlink, buf_out);
+            ret = ff_filter_frame(outlink, buf_out);
             s->got_output = 1;
         }
 
 fail:
         avfilter_unref_buffer(buf);
     } else {
-        ret = ff_filter_samples(outlink, buf);
+        buf->format = outlink->format;
+        ret = ff_filter_frame(outlink, buf);
         s->got_output = 1;
     }
 
     return ret;
 }
 
+static const AVFilterPad avfilter_af_resample_inputs[] = {
+    {
+        .name           = "default",
+        .type           = AVMEDIA_TYPE_AUDIO,
+        .filter_frame   = filter_frame,
+        .min_perms      = AV_PERM_READ
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_af_resample_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_AUDIO,
+        .config_props  = config_output,
+        .request_frame = request_frame
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_resample = {
     .name          = "resample",
     .description   = NULL_IF_CONFIG_SMALL("Audio resampling and conversion."),
@@ -241,14 +267,6 @@
     .uninit         = uninit,
     .query_formats  = query_formats,
 
-    .inputs    = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_AUDIO,
-                                          .filter_samples  = filter_samples,
-                                          .min_perms       = AV_PERM_READ },
-                                        { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name          = "default",
-                                          .type          = AVMEDIA_TYPE_AUDIO,
-                                          .config_props  = config_output,
-                                          .request_frame = request_frame },
-                                        { .name = NULL}},
+    .inputs    = avfilter_af_resample_inputs,
+    .outputs   = avfilter_af_resample_outputs,
 };
diff --git a/libavfilter/af_silencedetect.c b/libavfilter/af_silencedetect.c
index aea94b2..f5fccc5 100644
--- a/libavfilter/af_silencedetect.c
+++ b/libavfilter/af_silencedetect.c
@@ -23,7 +23,7 @@
  * Audio silence detector
  */
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/opt.h"
 #include "libavutil/timestamp.h"
 #include "audio.h"
@@ -35,7 +35,7 @@
     const AVClass *class;
     char *noise_str;            ///< noise option string
     double noise;               ///< noise amplitude ratio
-    int duration;               ///< minimum duration of silence until notification
+    double duration;            ///< minimum duration of silence until notification
     int64_t nb_null_samples;    ///< current number of continuous zero samples
     int64_t start;              ///< if silence is detected, this value contains the time of the first zero sample
     int last_sample_rate;       ///< last sample rate to check for sample rate changes
@@ -46,8 +46,8 @@
 static const AVOption silencedetect_options[] = {
     { "n",         "set noise tolerance",              OFFSET(noise_str), AV_OPT_TYPE_STRING, {.str="-60dB"}, CHAR_MIN, CHAR_MAX, FLAGS },
     { "noise",     "set noise tolerance",              OFFSET(noise_str), AV_OPT_TYPE_STRING, {.str="-60dB"}, CHAR_MIN, CHAR_MAX, FLAGS },
-    { "d",         "set minimum duration in seconds",  OFFSET(duration),  AV_OPT_TYPE_INT,    {.i64=2},    0, INT_MAX, FLAGS },
-    { "duration",  "set minimum duration in seconds",  OFFSET(duration),  AV_OPT_TYPE_INT,    {.i64=2},    0, INT_MAX, FLAGS },
+    { "d",         "set minimum duration in seconds",  OFFSET(duration),  AV_OPT_TYPE_DOUBLE, {.dbl=2.},             0, 24*60*60, FLAGS },
+    { "duration",  "set minimum duration in seconds",  OFFSET(duration),  AV_OPT_TYPE_DOUBLE, {.dbl=2.},             0, 24*60*60, FLAGS },
     { NULL },
 };
 
@@ -73,11 +73,18 @@
                silence->noise_str);
         return AVERROR(EINVAL);
     }
+    av_opt_free(silence);
 
     return 0;
 }
 
-static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)
+static char *get_metadata_val(AVFilterBufferRef *insamples, const char *key)
+{
+    AVDictionaryEntry *e = av_dict_get(insamples->metadata, key, NULL, 0);
+    return e && e->value ? e->value : NULL;
+}
+
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *insamples)
 {
     int i;
     SilenceDetectContext *silence = inlink->dst->priv;
@@ -93,6 +100,7 @@
     silence->last_sample_rate = srate;
 
     // TODO: support more sample formats
+    // TODO: document metadata
     if (insamples->format == AV_SAMPLE_FMT_DBL) {
         double *p = (double *)insamples->data[0];
 
@@ -101,23 +109,30 @@
                 if (!silence->start) {
                     silence->nb_null_samples++;
                     if (silence->nb_null_samples >= nb_samples_notify) {
-                        silence->start = insamples->pts - silence->duration / av_q2d(inlink->time_base);
-                        av_log(silence, AV_LOG_INFO,
-                               "silence_start: %s\n", av_ts2timestr(silence->start, &inlink->time_base));
+                        silence->start = insamples->pts - (int64_t)(silence->duration / av_q2d(inlink->time_base) + .5);
+                        av_dict_set(&insamples->metadata, "lavfi.silence_start",
+                                    av_ts2timestr(silence->start, &inlink->time_base), 0);
+                        av_log(silence, AV_LOG_INFO, "silence_start: %s\n",
+                               get_metadata_val(insamples, "lavfi.silence_start"));
                     }
                 }
             } else {
-                if (silence->start)
+                if (silence->start) {
+                    av_dict_set(&insamples->metadata, "lavfi.silence_end",
+                                av_ts2timestr(insamples->pts, &inlink->time_base), 0);
+                    av_dict_set(&insamples->metadata, "lavfi.silence_duration",
+                                av_ts2timestr(insamples->pts - silence->start, &inlink->time_base), 0);
                     av_log(silence, AV_LOG_INFO,
                            "silence_end: %s | silence_duration: %s\n",
-                           av_ts2timestr(insamples->pts,                  &inlink->time_base),
-                           av_ts2timestr(insamples->pts - silence->start, &inlink->time_base));
+                           get_metadata_val(insamples, "lavfi.silence_end"),
+                           get_metadata_val(insamples, "lavfi.silence_duration"));
+                }
                 silence->nb_null_samples = silence->start = 0;
             }
         }
     }
 
-    return ff_filter_samples(inlink->dst->outputs[0], insamples);
+    return ff_filter_frame(inlink->dst->outputs[0], insamples);
 }
 
 static int query_formats(AVFilterContext *ctx)
@@ -147,24 +162,31 @@
     return 0;
 }
 
+static const AVFilterPad silencedetect_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_AUDIO,
+        .get_audio_buffer = ff_null_get_audio_buffer,
+        .filter_frame     = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad silencedetect_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_AUDIO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_silencedetect = {
     .name          = "silencedetect",
     .description   = NULL_IF_CONFIG_SMALL("Detect silence."),
     .priv_size     = sizeof(SilenceDetectContext),
     .init          = init,
     .query_formats = query_formats,
-
-    .inputs = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_AUDIO,
-          .get_audio_buffer = ff_null_get_audio_buffer,
-          .filter_samples   = filter_samples, },
-        { .name = NULL }
-    },
-    .outputs = (const AVFilterPad[]) {
-        { .name = "default",
-          .type = AVMEDIA_TYPE_AUDIO, },
-        { .name = NULL }
-    },
-    .priv_class = &silencedetect_class,
+    .inputs        = silencedetect_inputs,
+    .outputs       = silencedetect_outputs,
+    .priv_class    = &silencedetect_class,
 };
diff --git a/libavfilter/af_volume.c b/libavfilter/af_volume.c
index 1aca7d9..7608083 100644
--- a/libavfilter/af_volume.c
+++ b/libavfilter/af_volume.c
@@ -24,7 +24,7 @@
  * based on ffmpeg.c code
  */
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/eval.h"
 #include "audio.h"
 #include "avfilter.h"
@@ -110,7 +110,7 @@
     return 0;
 }
 
-static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *insamples)
 {
     VolumeContext *vol = inlink->dst->priv;
     AVFilterLink *outlink = inlink->dst->outputs[0];
@@ -169,23 +169,33 @@
         }
         }
     }
-    return ff_filter_samples(outlink, insamples);
+    return ff_filter_frame(outlink, insamples);
 }
 
+static const AVFilterPad volume_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_AUDIO,
+        .filter_frame = filter_frame,
+        .min_perms    = AV_PERM_READ | AV_PERM_WRITE,
+    },
+    { NULL },
+};
+
+static const AVFilterPad volume_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_AUDIO,
+    },
+    { NULL },
+};
+
 AVFilter avfilter_af_volume = {
     .name           = "volume",
     .description    = NULL_IF_CONFIG_SMALL("Change input volume."),
     .query_formats  = query_formats,
     .priv_size      = sizeof(VolumeContext),
     .init           = init,
-
-    .inputs  = (const AVFilterPad[])  {{ .name     = "default",
-                                   .type           = AVMEDIA_TYPE_AUDIO,
-                                   .filter_samples = filter_samples,
-                                   .min_perms      = AV_PERM_READ|AV_PERM_WRITE},
-                                 { .name = NULL}},
-
-    .outputs = (const AVFilterPad[])  {{ .name     = "default",
-                                   .type           = AVMEDIA_TYPE_AUDIO, },
-                                 { .name = NULL}},
+    .inputs         = volume_inputs,
+    .outputs        = volume_outputs,
 };
diff --git a/libavfilter/af_volumedetect.c b/libavfilter/af_volumedetect.c
index caf8559..01f30a6 100644
--- a/libavfilter/af_volumedetect.c
+++ b/libavfilter/af_volumedetect.c
@@ -18,7 +18,7 @@
  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/avassert.h"
 #include "audio.h"
 #include "avfilter.h"
@@ -49,14 +49,14 @@
     return 0;
 }
 
-static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *samples)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *samples)
 {
     AVFilterContext *ctx = inlink->dst;
     VolDetectContext *vd = ctx->priv;
     int64_t layout  = samples->audio->channel_layout;
     int nb_samples  = samples->audio->nb_samples;
     int nb_channels = av_get_channel_layout_nb_channels(layout);
-    int nb_planes   = nb_planes;
+    int nb_planes   = nb_channels;
     int plane, i;
     int16_t *pcm;
 
@@ -70,7 +70,7 @@
             vd->histogram[pcm[i] + 0x8000]++;
     }
 
-    return ff_filter_samples(inlink->dst->outputs[0], samples);
+    return ff_filter_frame(inlink->dst->outputs[0], samples);
 }
 
 #define MAX_DB 91
@@ -126,34 +126,37 @@
     }
 }
 
-static int request_frame(AVFilterLink *outlink)
+static void uninit(AVFilterContext *ctx)
 {
-    AVFilterContext *ctx = outlink->src;
-    int ret = ff_request_frame(ctx->inputs[0]);
-    if (ret == AVERROR_EOF)
-        print_stats(ctx);
-    return ret;
+    print_stats(ctx);
 }
 
+static const AVFilterPad volumedetect_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_AUDIO,
+        .get_audio_buffer = ff_null_get_audio_buffer,
+        .filter_frame     = filter_frame,
+        .min_perms        = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad volumedetect_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_AUDIO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_volumedetect = {
     .name          = "volumedetect",
     .description   = NULL_IF_CONFIG_SMALL("Detect audio volume."),
 
     .priv_size     = sizeof(VolDetectContext),
     .query_formats = query_formats,
-
-    .inputs    = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_AUDIO,
-          .get_audio_buffer = ff_null_get_audio_buffer,
-          .filter_samples   = filter_samples,
-          .min_perms        = AV_PERM_READ, },
-        { .name = NULL }
-    },
-    .outputs   = (const AVFilterPad[]) {
-        { .name = "default",
-          .type = AVMEDIA_TYPE_AUDIO,
-          .request_frame = request_frame, },
-        { .name = NULL }
-    },
+    .uninit        = uninit,
+    .inputs        = volumedetect_inputs,
+    .outputs       = volumedetect_outputs,
 };
diff --git a/libavfilter/allfilters.c b/libavfilter/allfilters.c
index 49f166d..746e713 100644
--- a/libavfilter/allfilters.c
+++ b/libavfilter/allfilters.c
@@ -58,6 +58,7 @@
     REGISTER_FILTER (CHANNELMAP,  channelmap,  af);
     REGISTER_FILTER (CHANNELSPLIT,channelsplit,af);
     REGISTER_FILTER (EARWAX,      earwax,      af);
+    REGISTER_FILTER (EBUR128,     ebur128,     af);
     REGISTER_FILTER (JOIN,        join,        af);
     REGISTER_FILTER (PAN,         pan,         af);
     REGISTER_FILTER (SILENCEDETECT, silencedetect, af);
@@ -89,12 +90,14 @@
     REGISTER_FILTER (DRAWTEXT,    drawtext,    vf);
     REGISTER_FILTER (EDGEDETECT,  edgedetect,  vf);
     REGISTER_FILTER (FADE,        fade,        vf);
+    REGISTER_FILTER (FIELD,       field,       vf);
     REGISTER_FILTER (FIELDORDER,  fieldorder,  vf);
     REGISTER_FILTER (FIFO,        fifo,        vf);
     REGISTER_FILTER (FORMAT,      format,      vf);
     REGISTER_FILTER (FPS,         fps,         vf);
     REGISTER_FILTER (FRAMESTEP,   framestep,   vf);
     REGISTER_FILTER (FREI0R,      frei0r,      vf);
+    REGISTER_FILTER (GEQ,         geq,         vf);
     REGISTER_FILTER (GRADFUN,     gradfun,     vf);
     REGISTER_FILTER (HFLIP,       hflip,       vf);
     REGISTER_FILTER (HQDN3D,      hqdn3d,      vf);
@@ -121,7 +124,6 @@
     REGISTER_FILTER (SETSAR,      setsar,      vf);
     REGISTER_FILTER (SETTB,       settb,       vf);
     REGISTER_FILTER (SHOWINFO,    showinfo,    vf);
-    REGISTER_FILTER (SLICIFY,     slicify,     vf);
     REGISTER_FILTER (SMARTBLUR,   smartblur,   vf);
     REGISTER_FILTER (SPLIT,       split,       vf);
     REGISTER_FILTER (SUPER2XSAI,  super2xsai,  vf);
diff --git a/libavfilter/asink_anullsink.c b/libavfilter/asink_anullsink.c
index 4eee504..5a324fc 100644
--- a/libavfilter/asink_anullsink.c
+++ b/libavfilter/asink_anullsink.c
@@ -22,24 +22,27 @@
 #include "avfilter.h"
 #include "internal.h"
 
-static int null_filter_samples(AVFilterLink *link, AVFilterBufferRef *samplesref)
+static int null_filter_frame(AVFilterLink *link, AVFilterBufferRef *samplesref)
 {
+    avfilter_unref_bufferp(&samplesref);
     return 0;
 }
 
+static const AVFilterPad avfilter_asink_anullsink_inputs[] = {
+    {
+        .name           = "default",
+        .type           = AVMEDIA_TYPE_AUDIO,
+        .filter_frame   = null_filter_frame,
+    },
+    { NULL },
+};
+
 AVFilter avfilter_asink_anullsink = {
     .name        = "anullsink",
     .description = NULL_IF_CONFIG_SMALL("Do absolutely nothing with the input audio."),
 
     .priv_size = 0,
 
-    .inputs    = (const AVFilterPad[]) {
-        {
-            .name            = "default",
-            .type            = AVMEDIA_TYPE_AUDIO,
-            .filter_samples  = null_filter_samples,
-        },
-        { .name = NULL},
-    },
+    .inputs    = avfilter_asink_anullsink_inputs,
     .outputs   = NULL,
 };
diff --git a/libavfilter/asrc_aevalsrc.c b/libavfilter/asrc_aevalsrc.c
index 71eadfc..eaf7975 100644
--- a/libavfilter/asrc_aevalsrc.c
+++ b/libavfilter/asrc_aevalsrc.c
@@ -23,9 +23,9 @@
  * eval audio source
  */
 
-#include "libavutil/audioconvert.h"
 #include "libavutil/avassert.h"
 #include "libavutil/avstring.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/eval.h"
 #include "libavutil/opt.h"
 #include "libavutil/parseutils.h"
@@ -91,6 +91,12 @@
     eval->class = &aevalsrc_class;
     av_opt_set_defaults(eval);
 
+    if (!args1) {
+        av_log(ctx, AV_LOG_ERROR, "Argument is empty\n");
+        ret = args ? AVERROR(ENOMEM) : AVERROR(EINVAL);
+        goto end;
+    }
+
     /* parse expressions */
     buf = args1;
     i = 0;
@@ -231,11 +237,21 @@
     samplesref->audio->sample_rate = eval->sample_rate;
     eval->pts += eval->nb_samples;
 
-    ff_filter_samples(outlink, samplesref);
+    ff_filter_frame(outlink, samplesref);
 
     return 0;
 }
 
+static const AVFilterPad aevalsrc_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_AUDIO,
+        .config_props  = config_props,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_asrc_aevalsrc = {
     .name        = "aevalsrc",
     .description = NULL_IF_CONFIG_SMALL("Generate an audio signal generated by an expression."),
@@ -244,13 +260,7 @@
     .init        = init,
     .uninit      = uninit,
     .priv_size   = sizeof(EvalContext),
-
-    .inputs      = (const AVFilterPad[]) {{ .name = NULL}},
-
-    .outputs     = (const AVFilterPad[]) {{ .name = "default",
-                                      .type = AVMEDIA_TYPE_AUDIO,
-                                      .config_props = config_props,
-                                      .request_frame = request_frame, },
-                                    { .name = NULL}},
-    .priv_class = &aevalsrc_class,
+    .inputs      = NULL,
+    .outputs     = aevalsrc_outputs,
+    .priv_class  = &aevalsrc_class,
 };
diff --git a/libavfilter/asrc_anullsrc.c b/libavfilter/asrc_anullsrc.c
index 4e28e29..43e9a7c 100644
--- a/libavfilter/asrc_anullsrc.c
+++ b/libavfilter/asrc_anullsrc.c
@@ -27,14 +27,13 @@
 #include <inttypes.h>
 #include <stdio.h>
 
+#include "libavutil/channel_layout.h"
+#include "libavutil/internal.h"
+#include "libavutil/opt.h"
 #include "audio.h"
 #include "avfilter.h"
 #include "internal.h"
 
-#include "libavutil/audioconvert.h"
-#include "libavutil/internal.h"
-#include "libavutil/opt.h"
-
 typedef struct {
     const AVClass *class;
     char   *channel_layout_str;
@@ -112,13 +111,23 @@
     samplesref->audio->channel_layout = null->channel_layout;
     samplesref->audio->sample_rate = outlink->sample_rate;
 
-    ff_filter_samples(outlink, avfilter_ref_buffer(samplesref, ~0));
+    ff_filter_frame(outlink, avfilter_ref_buffer(samplesref, ~0));
     avfilter_unref_buffer(samplesref);
 
     null->pts += null->nb_samples;
     return 0;
 }
 
+static const AVFilterPad avfilter_asrc_anullsrc_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_AUDIO,
+        .config_props  = config_props,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_asrc_anullsrc = {
     .name        = "anullsrc",
     .description = NULL_IF_CONFIG_SMALL("Null audio source, return empty audio frames."),
@@ -128,10 +137,6 @@
 
     .inputs      = NULL,
 
-    .outputs     = (const AVFilterPad[]) {{ .name = "default",
-                                            .type = AVMEDIA_TYPE_AUDIO,
-                                            .config_props = config_props,
-                                            .request_frame = request_frame, },
-                                          { .name = NULL}},
+    .outputs     = avfilter_asrc_anullsrc_outputs,
     .priv_class = &anullsrc_class,
 };
diff --git a/libavfilter/asrc_flite.c b/libavfilter/asrc_flite.c
index 6f8cc95..04901da 100644
--- a/libavfilter/asrc_flite.c
+++ b/libavfilter/asrc_flite.c
@@ -24,7 +24,7 @@
  */
 
 #include <flite/flite.h>
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/file.h"
 #include "libavutil/opt.h"
 #include "avfilter.h"
@@ -265,9 +265,19 @@
     flite->wave_samples += nb_samples * flite->wave->num_channels;
     flite->wave_nb_samples -= nb_samples;
 
-    return ff_filter_samples(outlink, samplesref);
+    return ff_filter_frame(outlink, samplesref);
 }
 
+static const AVFilterPad flite_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_AUDIO,
+        .config_props  = config_props,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_asrc_flite = {
     .name        = "flite",
     .description = NULL_IF_CONFIG_SMALL("Synthesize voice from text using libflite."),
@@ -275,18 +285,7 @@
     .init        = init,
     .uninit      = uninit,
     .priv_size   = sizeof(FliteContext),
-
-    .inputs = (const AVFilterPad[]) {{ .name = NULL}},
-
-    .outputs = (const AVFilterPad[]) {
-        {
-            .name = "default",
-            .type = AVMEDIA_TYPE_AUDIO,
-            .config_props = config_props,
-            .request_frame = request_frame,
-        },
-        { .name = NULL }
-    },
-
-    .priv_class = &flite_class,
+    .inputs      = NULL,
+    .outputs     = flite_outputs,
+    .priv_class  = &flite_class,
 };
diff --git a/libavfilter/audio.c b/libavfilter/audio.c
index 06702a6..f157e87 100644
--- a/libavfilter/audio.c
+++ b/libavfilter/audio.c
@@ -20,7 +20,7 @@
  */
 
 #include "libavutil/avassert.h"
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
 
 #include "audio.h"
@@ -157,30 +157,29 @@
     return NULL;
 }
 
-static int default_filter_samples(AVFilterLink *link,
-                                  AVFilterBufferRef *samplesref)
+static int default_filter_frame(AVFilterLink *link, AVFilterBufferRef *frame)
 {
-    return ff_filter_samples(link->dst->outputs[0], samplesref);
+    return ff_filter_frame(link->dst->outputs[0], frame);
 }
 
 int ff_filter_samples_framed(AVFilterLink *link, AVFilterBufferRef *samplesref)
 {
-    int (*filter_samples)(AVFilterLink *, AVFilterBufferRef *);
+    int (*filter_frame)(AVFilterLink *, AVFilterBufferRef *);
     AVFilterPad *src = link->srcpad;
     AVFilterPad *dst = link->dstpad;
     int64_t pts;
     AVFilterBufferRef *buf_out;
     int ret;
 
-    FF_TPRINTF_START(NULL, filter_samples); ff_tlog_link(NULL, link, 1);
+    FF_TPRINTF_START(NULL, filter_frame); ff_tlog_link(NULL, link, 1);
 
     if (link->closed) {
         avfilter_unref_buffer(samplesref);
         return AVERROR_EOF;
     }
 
-    if (!(filter_samples = dst->filter_samples))
-        filter_samples = default_filter_samples;
+    if (!(filter_frame = dst->filter_frame))
+        filter_frame = default_filter_frame;
 
     av_assert1((samplesref->perms & src->min_perms) == src->min_perms);
     samplesref->perms &= ~ src->rej_perms;
@@ -213,7 +212,7 @@
 
     link->cur_buf = buf_out;
     pts = buf_out->pts;
-    ret = filter_samples(link, buf_out);
+    ret = filter_frame(link, buf_out);
     ff_update_link_current_pts(link, pts);
     return ret;
 }
diff --git a/libavfilter/audio.h b/libavfilter/audio.h
index a84c378..8fe4d8e 100644
--- a/libavfilter/audio.h
+++ b/libavfilter/audio.h
@@ -23,6 +23,7 @@
 #define AVFILTER_AUDIO_H
 
 #include "avfilter.h"
+#include "internal.h"
 
 static const enum AVSampleFormat ff_packed_sample_fmts_array[] = {
     AV_SAMPLE_FMT_U8,
@@ -81,6 +82,6 @@
  * min_samples.
  */
 int ff_filter_samples_framed(AVFilterLink *link,
-                              AVFilterBufferRef *samplesref);
+                             AVFilterBufferRef *samplesref);
 
 #endif /* AVFILTER_AUDIO_H */
diff --git a/libavfilter/avcodec.c b/libavfilter/avcodec.c
index a0f8b69..688f1b3 100644
--- a/libavfilter/avcodec.c
+++ b/libavfilter/avcodec.c
@@ -33,6 +33,9 @@
     dst->pos    = av_frame_get_pkt_pos(src);
     dst->format = src->format;
 
+    av_dict_free(&dst->metadata);
+    av_dict_copy(&dst->metadata, av_frame_get_metadata(src), 0);
+
     switch (dst->type) {
     case AVMEDIA_TYPE_VIDEO:
         dst->video->w                   = src->width;
@@ -57,6 +60,11 @@
     case AVMEDIA_TYPE_AUDIO:
         dst->audio->sample_rate         = src->sample_rate;
         dst->audio->channel_layout      = src->channel_layout;
+        dst->audio->channels            = src->channels;
+        if(src->channels < av_get_channel_layout_nb_channels(src->channel_layout)) {
+            av_log(NULL, AV_LOG_ERROR, "libavfilter does not support this channel layout\n");
+            return AVERROR(EINVAL);
+        }
         break;
     default:
         return AVERROR(EINVAL);
@@ -74,7 +82,10 @@
                                                   frame->format);
     if (!picref)
         return NULL;
-    avfilter_copy_frame_props(picref, frame);
+    if (avfilter_copy_frame_props(picref, frame) < 0) {
+        picref->buf->data[0] = NULL;
+        avfilter_unref_bufferp(&picref);
+    }
     return picref;
 }
 
@@ -87,7 +98,10 @@
                                                   av_frame_get_channel_layout(frame));
     if (!samplesref)
         return NULL;
-    avfilter_copy_frame_props(samplesref, frame);
+    if (avfilter_copy_frame_props(samplesref, frame) < 0) {
+        samplesref->buf->data[0] = NULL;
+        avfilter_unref_bufferp(&samplesref);
+    }
     return samplesref;
 }
 
@@ -142,12 +156,13 @@
             if (!dst->extended_data)
                 return AVERROR(ENOMEM);
             memcpy(dst->extended_data, src->extended_data,
-                   planes * sizeof(dst->extended_data));
+                   planes * sizeof(*dst->extended_data));
         } else
             dst->extended_data = dst->data;
         dst->nb_samples          = src->audio->nb_samples;
         av_frame_set_sample_rate   (dst, src->audio->sample_rate);
         av_frame_set_channel_layout(dst, src->audio->channel_layout);
+        av_frame_set_channels      (dst, src->audio->channels);
         break;
     default:
         return AVERROR(EINVAL);
diff --git a/libavfilter/avf_concat.c b/libavfilter/avf_concat.c
index c0bd621..6be2c53 100644
--- a/libavfilter/avf_concat.c
+++ b/libavfilter/avf_concat.c
@@ -23,8 +23,9 @@
  * concat audio-video filter
  */
 
-#include "libavutil/audioconvert.h"
 #include "libavutil/avassert.h"
+#include "libavutil/avstring.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/opt.h"
 #include "avfilter.h"
 #define FF_BUFQUEUE_SIZE 256
@@ -42,6 +43,7 @@
     unsigned cur_idx; /**< index of the first input of current segment */
     int64_t delta_ts; /**< timestamp to add to produce output timestamps */
     unsigned nb_in_active; /**< number of active inputs in current segment */
+    unsigned unsafe;
     struct concat_in {
         int64_t pts;
         int64_t nb_frames;
@@ -64,6 +66,9 @@
     { "a", "specify the number of audio streams",
       OFFSET(nb_streams[AVMEDIA_TYPE_AUDIO]),
       AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, A|F},
+    { "unsafe", "enable unsafe mode",
+      OFFSET(unsafe),
+      AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, A|A|F},
     { 0 }
 };
 
@@ -143,7 +148,8 @@
                    ctx->input_pads[out_no].name, outlink->w, outlink->h,
                    outlink->sample_aspect_ratio.num,
                    outlink->sample_aspect_ratio.den);
-            return AVERROR(EINVAL);
+            if (!cat->unsafe)
+                return AVERROR(EINVAL);
         }
     }
 
@@ -173,16 +179,7 @@
         in->pts = av_rescale(in->pts, in->nb_frames, in->nb_frames - 1);
 
     buf->pts += cat->delta_ts;
-    switch (buf->type) {
-    case AVMEDIA_TYPE_VIDEO:
-        ff_start_frame(outlink, buf);
-        ff_draw_slice(outlink, 0, outlink->h, 1);
-        ff_end_frame(outlink);
-        break;
-    case AVMEDIA_TYPE_AUDIO:
-        ff_filter_samples(outlink, buf);
-        break;
-    }
+    ff_filter_frame(outlink, buf);
 }
 
 static void process_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
@@ -195,7 +192,7 @@
         av_log(ctx, AV_LOG_ERROR, "Frame after EOF on input %s\n",
                ctx->input_pads[in_no].name);
         avfilter_unref_buffer(buf);
-    } if (in_no >= cat->cur_idx + ctx->nb_outputs) {
+    } else if (in_no >= cat->cur_idx + ctx->nb_outputs) {
         ff_bufqueue_add(ctx, &cat->in[in_no].queue, buf);
     } else {
         push_frame(ctx, in_no, buf);
@@ -222,24 +219,7 @@
     return ff_get_audio_buffer(outlink, perms, nb_samples);
 }
 
-static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
-{
-    return 0;
-}
-
-static int draw_slice(AVFilterLink *inlink, int y, int h, int dir)
-{
-    return 0;
-}
-
-static int end_frame(AVFilterLink *inlink)
-{
-    process_frame(inlink, inlink->cur_buf);
-    inlink->cur_buf = NULL;
-    return 0;
-}
-
-static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
 {
     process_frame(inlink, buf);
     return 0; /* enhancement: handle error return */
@@ -292,7 +272,7 @@
         av_samples_set_silence(buf->extended_data, 0, frame_nb_samples,
                                nb_channels, outlink->format);
         buf->pts = base_pts + av_rescale_q(sent, rate_tb, outlink->time_base);
-        ff_filter_samples(outlink, buf);
+        ff_filter_frame(outlink, buf);
         sent       += frame_nb_samples;
         nb_samples -= frame_nb_samples;
     }
@@ -365,7 +345,6 @@
     ConcatContext *cat = ctx->priv;
     int ret;
     unsigned seg, type, str;
-    char name[32];
 
     cat->class = &concat_class;
     av_opt_set_defaults(cat);
@@ -384,16 +363,9 @@
                     .min_perms        = AV_PERM_READ | AV_PERM_PRESERVE,
                     .get_video_buffer = get_video_buffer,
                     .get_audio_buffer = get_audio_buffer,
+                    .filter_frame     = filter_frame,
                 };
-                snprintf(name, sizeof(name), "in%d:%c%d", seg, "va"[type], str);
-                pad.name = av_strdup(name);
-                if (type == AVMEDIA_TYPE_VIDEO) {
-                    pad.start_frame = start_frame;
-                    pad.draw_slice  = draw_slice;
-                    pad.end_frame   = end_frame;
-                } else {
-                    pad.filter_samples = filter_samples;
-                }
+                pad.name = av_asprintf("in%d:%c%d", seg, "va"[type], str);
                 ff_insert_inpad(ctx, ctx->nb_inputs, &pad);
             }
         }
@@ -406,8 +378,7 @@
                 .config_props  = config_output,
                 .request_frame = request_frame,
             };
-            snprintf(name, sizeof(name), "out:%c%d", "va"[type], str);
-            pad.name = av_strdup(name);
+            pad.name = av_asprintf("out:%c%d", "va"[type], str);
             ff_insert_outpad(ctx, ctx->nb_outputs, &pad);
         }
     }
@@ -440,7 +411,7 @@
     .uninit        = uninit,
     .query_formats = query_formats,
     .priv_size     = sizeof(ConcatContext),
-    .inputs        = (const AVFilterPad[]) { { .name = NULL } },
-    .outputs       = (const AVFilterPad[]) { { .name = NULL } },
+    .inputs        = NULL,
+    .outputs       = NULL,
     .priv_class    = &concat_class,
 };
diff --git a/libavfilter/avf_showspectrum.c b/libavfilter/avf_showspectrum.c
index 3a5e026..977fca9 100644
--- a/libavfilter/avf_showspectrum.c
+++ b/libavfilter/avf_showspectrum.c
@@ -27,7 +27,7 @@
 #include <math.h>
 
 #include "libavcodec/avfft.h"
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/opt.h"
 #include "avfilter.h"
 #include "internal.h"
@@ -37,6 +37,7 @@
     int w, h;
     AVFilterBufferRef *outpicref;
     int req_fullfilled;
+    int sliding;                ///< 1 if sliding mode, 0 otherwise
     int xpos;                   ///< x position (current column)
     RDFTContext *rdft;          ///< Real Discrete Fourier Transform context
     int rdft_bits;              ///< number of bits (RDFT window size = 1<<rdft_bits)
@@ -52,6 +53,7 @@
 static const AVOption showspectrum_options[] = {
     { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x480"}, 0, 0, FLAGS },
     { "s",    "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x480"}, 0, 0, FLAGS },
+    { "slide", "set sliding mode", OFFSET(sliding), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, FLAGS },
     { NULL },
 };
 
@@ -87,8 +89,8 @@
     AVFilterChannelLayouts *layouts = NULL;
     AVFilterLink *inlink = ctx->inputs[0];
     AVFilterLink *outlink = ctx->outputs[0];
-    static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16P, -1 };
-    static const enum PixelFormat pix_fmts[] = { PIX_FMT_RGB24, -1 };
+    static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_NONE };
+    static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_RGB24, AV_PIX_FMT_NONE };
 
     /* set input audio formats */
     formats = ff_make_format_list(sample_fmts);
@@ -130,16 +132,20 @@
 
     /* (re-)configuration if the video output changed (or first init) */
     if (rdft_bits != showspectrum->rdft_bits) {
+        size_t rdft_size;
         AVFilterBufferRef *outpicref;
 
         av_rdft_end(showspectrum->rdft);
         showspectrum->rdft = av_rdft_init(rdft_bits, DFT_R2C);
         showspectrum->rdft_bits = rdft_bits;
 
-        /* RDFT buffers: x2 for each (display) channel buffer */
-        showspectrum->rdft_data =
-            av_realloc_f(showspectrum->rdft_data, 2 * win_size,
-                         sizeof(*showspectrum->rdft_data));
+        /* RDFT buffers: x2 for each (display) channel buffer.
+         * Note: we use free and malloc instead of a realloc-like function to
+         * make sure the buffer is aligned in memory for the FFT functions. */
+        av_freep(&showspectrum->rdft_data);
+        if (av_size_mult(sizeof(*showspectrum->rdft_data), 2 * win_size, &rdft_size) < 0)
+            return AVERROR(EINVAL);
+        showspectrum->rdft_data = av_malloc(rdft_size);
         if (!showspectrum->rdft_data)
             return AVERROR(ENOMEM);
         showspectrum->filled = 0;
@@ -182,9 +188,7 @@
     showspectrum->filled = 0;
     showspectrum->req_fullfilled = 1;
 
-    ff_start_frame(outlink, avfilter_ref_buffer(showspectrum->outpicref, ~AV_PERM_WRITE));
-    ff_draw_slice(outlink, 0, outlink->h, 1);
-    ff_end_frame(outlink);
+    ff_filter_frame(outlink, avfilter_ref_buffer(showspectrum->outpicref, ~AV_PERM_WRITE));
 }
 
 static int request_frame(AVFilterLink *outlink)
@@ -247,16 +251,23 @@
 
         for (y = 0; y < outlink->h; y++) {
             // FIXME: bin[0] contains first and last bins
-            const int pos = showspectrum->xpos * 3 + (outlink->h - y - 1) * outpicref->linesize[0];
+            uint8_t *p = outpicref->data[0] + (outlink->h - y - 1) * outpicref->linesize[0];
             const double w = 1. / sqrt(nb_freq);
             int a =                           sqrt(w * MAGNITUDE(RE(0), IM(0)));
             int b = nb_display_channels > 1 ? sqrt(w * MAGNITUDE(RE(1), IM(1))) : a;
 
+            if (showspectrum->sliding) {
+                memmove(p, p + 3, (outlink->w - 1) * 3);
+                p += (outlink->w - 1) * 3;
+            } else {
+                p += showspectrum->xpos * 3;
+            }
+
             a = FFMIN(a, 255);
             b = FFMIN(b, 255);
-            outpicref->data[0][pos]   = a;
-            outpicref->data[0][pos+1] = b;
-            outpicref->data[0][pos+2] = (a + b) / 2;
+            p[0] = a;
+            p[1] = b;
+            p[2] = (a + b) / 2;
         }
         outpicref->pts = insamples->pts +
             av_rescale_q(showspectrum->consumed,
@@ -268,7 +279,7 @@
     return add_samples;
 }
 
-static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *insamples)
 {
     AVFilterContext *ctx = inlink->dst;
     ShowSpectrumContext *showspectrum = ctx->priv;
@@ -285,6 +296,26 @@
     return 0;
 }
 
+static const AVFilterPad showspectrum_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_AUDIO,
+        .filter_frame = filter_frame,
+        .min_perms    = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad showspectrum_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .config_props  = config_output,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_avf_showspectrum = {
     .name           = "showspectrum",
     .description    = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output."),
@@ -292,26 +323,7 @@
     .uninit         = uninit,
     .query_formats  = query_formats,
     .priv_size      = sizeof(ShowSpectrumContext),
-
-    .inputs  = (const AVFilterPad[]) {
-        {
-            .name           = "default",
-            .type           = AVMEDIA_TYPE_AUDIO,
-            .filter_samples = filter_samples,
-            .min_perms      = AV_PERM_READ,
-        },
-        { .name = NULL }
-    },
-
-    .outputs = (const AVFilterPad[]) {
-        {
-            .name           = "default",
-            .type           = AVMEDIA_TYPE_VIDEO,
-            .config_props   = config_output,
-            .request_frame  = request_frame,
-        },
-        { .name = NULL }
-    },
-
-    .priv_class = &showspectrum_class,
+    .inputs         = showspectrum_inputs,
+    .outputs        = showspectrum_outputs,
+    .priv_class     = &showspectrum_class,
 };
diff --git a/libavfilter/avf_showwaves.c b/libavfilter/avf_showwaves.c
index dcbe8b8..30a8e1e 100644
--- a/libavfilter/avf_showwaves.c
+++ b/libavfilter/avf_showwaves.c
@@ -23,7 +23,7 @@
  * audio to video multimedia filter
  */
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/opt.h"
 #include "libavutil/parseutils.h"
 #include "avfilter.h"
@@ -87,8 +87,8 @@
     AVFilterChannelLayouts *layouts = NULL;
     AVFilterLink *inlink = ctx->inputs[0];
     AVFilterLink *outlink = ctx->outputs[0];
-    static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16, -1 };
-    static const enum PixelFormat pix_fmts[] = { PIX_FMT_GRAY8, -1 };
+    static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE };
+    static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE };
 
     /* set input audio formats */
     formats = ff_make_format_list(sample_fmts);
@@ -153,9 +153,7 @@
 {
     ShowWavesContext *showwaves = outlink->src->priv;
 
-    ff_start_frame(outlink, showwaves->outpicref);
-    ff_draw_slice(outlink, 0, outlink->h, 1);
-    ff_end_frame(outlink);
+    ff_filter_frame(outlink, showwaves->outpicref);
     showwaves->req_fullfilled = 1;
     showwaves->outpicref = NULL;
     showwaves->buf_idx = 0;
@@ -179,7 +177,7 @@
 
 #define MAX_INT16 ((1<<15) -1)
 
-static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *insamples)
 {
     AVFilterContext *ctx = inlink->dst;
     AVFilterLink *outlink = ctx->outputs[0];
@@ -195,10 +193,12 @@
 
     /* draw data in the buffer */
     for (i = 0; i < nb_samples; i++) {
-        if (showwaves->buf_idx == 0 && showwaves->sample_count_mod == 0) {
+        if (!outpicref) {
             showwaves->outpicref = outpicref =
                 ff_get_video_buffer(outlink, AV_PERM_WRITE|AV_PERM_ALIGN,
                                     outlink->w, outlink->h);
+            if (!outpicref)
+                return AVERROR(ENOMEM);
             outpicref->video->w = outlink->w;
             outpicref->video->h = outlink->h;
             outpicref->pts = insamples->pts +
@@ -226,6 +226,26 @@
     return 0;
 }
 
+static const AVFilterPad showwaves_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_AUDIO,
+        .filter_frame = filter_frame,
+        .min_perms    = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad showwaves_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .config_props  = config_output,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_avf_showwaves = {
     .name           = "showwaves",
     .description    = NULL_IF_CONFIG_SMALL("Convert input audio to a video output."),
@@ -233,26 +253,7 @@
     .uninit         = uninit,
     .query_formats  = query_formats,
     .priv_size      = sizeof(ShowWavesContext),
-
-    .inputs  = (const AVFilterPad[]) {
-        {
-            .name           = "default",
-            .type           = AVMEDIA_TYPE_AUDIO,
-            .filter_samples = filter_samples,
-            .min_perms      = AV_PERM_READ,
-        },
-        { .name = NULL }
-    },
-
-    .outputs = (const AVFilterPad[]) {
-        {
-            .name           = "default",
-            .type           = AVMEDIA_TYPE_VIDEO,
-            .config_props   = config_output,
-            .request_frame  = request_frame,
-        },
-        { .name = NULL }
-    },
-
-    .priv_class = &showwaves_class,
+    .inputs         = showwaves_inputs,
+    .outputs        = showwaves_outputs,
+    .priv_class     = &showwaves_class,
 };
diff --git a/libavfilter/avfilter.c b/libavfilter/avfilter.c
index 9f49a8b..31580f6 100644
--- a/libavfilter/avfilter.c
+++ b/libavfilter/avfilter.c
@@ -19,13 +19,16 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#include "libavutil/common.h"
-#include "libavutil/pixdesc.h"
-#include "libavutil/rational.h"
-#include "libavutil/audioconvert.h"
 #include "libavutil/avassert.h"
 #include "libavutil/avstring.h"
+#include "libavutil/channel_layout.h"
+#include "libavutil/common.h"
+#include "libavutil/imgutils.h"
+#include "libavutil/pixdesc.h"
+#include "libavutil/rational.h"
+#include "libavutil/samplefmt.h"
 
+#include "audio.h"
 #include "avfilter.h"
 #include "formats.h"
 #include "internal.h"
@@ -142,7 +145,7 @@
     link->srcpad  = &src->output_pads[srcpad];
     link->dstpad  = &dst->input_pads[dstpad];
     link->type    = src->output_pads[srcpad].type;
-    av_assert0(PIX_FMT_NONE == -1 && AV_SAMPLE_FMT_NONE == -1);
+    av_assert0(AV_PIX_FMT_NONE == -1 && AV_SAMPLE_FMT_NONE == -1);
     link->format  = -1;
 
     return 0;
@@ -311,7 +314,7 @@
         ff_tlog(ctx,
                 "link[%p s:%dx%d fmt:%s %s->%s]%s",
                 link, link->w, link->h,
-                av_pix_fmt_descriptors[link->format].name,
+                av_get_pix_fmt_name(link->format),
                 link->src ? link->src->filter->name : "",
                 link->dst ? link->dst->filter->name : "",
                 end ? "\n" : "");
@@ -409,6 +412,8 @@
 
 int avfilter_register(AVFilter *filter)
 {
+    int i;
+
     if (next_registered_avfilter_idx == MAX_REGISTERED_AVFILTERS_NB) {
         av_log(NULL, AV_LOG_ERROR,
                "Maximum number of registered filters %d reached, "
@@ -417,6 +422,12 @@
         return AVERROR(ENOMEM);
     }
 
+    for(i=0; filter->inputs && filter->inputs[i].name; i++) {
+        const AVFilterPad *input = &filter->inputs[i];
+        av_assert0(     !input->filter_frame
+                    || (!input->start_frame && !input->end_frame && !input->draw_slice));
+    }
+
     registered_avfilters[next_registered_avfilter_idx++] = filter;
     return 0;
 }
@@ -623,3 +634,23 @@
 {
     return pads[pad_idx].type;
 }
+
+int ff_filter_frame(AVFilterLink *link, AVFilterBufferRef *frame)
+{
+    int ret;
+    FF_TPRINTF_START(NULL, filter_frame); ff_tlog_link(NULL, link, 1); ff_tlog(NULL, " "); ff_tlog_ref(NULL, frame, 1);
+
+    switch (link->type) {
+    case AVMEDIA_TYPE_VIDEO:
+        if((ret = ff_start_frame(link, frame)) < 0)
+            return ret;
+        if((ret = ff_draw_slice(link, 0, frame->video->h, 1)) < 0)
+            return ret;
+        if((ret = ff_end_frame(link)) < 0)
+            return ret;
+        return ret;
+    case AVMEDIA_TYPE_AUDIO:
+        return ff_filter_samples(link, frame);
+    default: return AVERROR(EINVAL);
+    }
+}
diff --git a/libavfilter/avfilter.h b/libavfilter/avfilter.h
index d66bc00..f194d33 100644
--- a/libavfilter/avfilter.h
+++ b/libavfilter/avfilter.h
@@ -25,6 +25,7 @@
 #include <stddef.h>
 
 #include "libavutil/avutil.h"
+#include "libavutil/dict.h"
 #include "libavutil/log.h"
 #include "libavutil/samplefmt.h"
 #include "libavutil/pixfmt.h"
@@ -116,6 +117,7 @@
     uint64_t channel_layout;    ///< channel layout of audio buffer
     int nb_samples;             ///< number of audio samples per channel
     int sample_rate;            ///< audio buffer sample rate
+    int channels;               ///< number of channels
 } AVFilterBufferRefAudioProps;
 
 /**
@@ -180,6 +182,8 @@
     int perms;                  ///< permissions, see the AV_PERM_* flags
 
     enum AVMediaType type;      ///< media type of buffer data
+
+    AVDictionary *metadata;     ///< dictionary containing metadata key=value tags
 } AVFilterBufferRef;
 
 /**
@@ -270,26 +274,13 @@
     int rej_perms;
 
     /**
-     * Callback called before passing the first slice of a new frame. If
-     * NULL, the filter layer will default to storing a reference to the
-     * picture inside the link structure.
-     *
-     * The reference given as argument is also available in link->cur_buf.
-     * It can be stored elsewhere or given away, but then clearing
-     * link->cur_buf is advised, as it is automatically unreferenced.
-     * The reference must not be unreferenced before end_frame(), as it may
-     * still be in use by the automatic copy mechanism.
-     *
-     * Input video pads only.
-     *
-     * @return >= 0 on success, a negative AVERROR on error. picref will be
-     * unreferenced by the caller in case of error.
+     * @deprecated unused
      */
     int (*start_frame)(AVFilterLink *link, AVFilterBufferRef *picref);
 
     /**
      * Callback function to get a video buffer. If NULL, the filter system will
-     * use avfilter_default_get_video_buffer().
+     * use ff_default_get_video_buffer().
      *
      * Input video pads only.
      */
@@ -297,7 +288,7 @@
 
     /**
      * Callback function to get an audio buffer. If NULL, the filter system will
-     * use avfilter_default_get_audio_buffer().
+     * use ff_default_get_audio_buffer().
      *
      * Input audio pads only.
      */
@@ -305,37 +296,26 @@
                                            int nb_samples);
 
     /**
-     * Callback called after the slices of a frame are completely sent. If
-     * NULL, the filter layer will default to releasing the reference stored
-     * in the link structure during start_frame().
-     *
-     * Input video pads only.
-     *
-     * @return >= 0 on success, a negative AVERROR on error.
+     * @deprecated unused
      */
     int (*end_frame)(AVFilterLink *link);
 
     /**
-     * Slice drawing callback. This is where a filter receives video data
-     * and should do its processing.
-     *
-     * Input video pads only.
-     *
-     * @return >= 0 on success, a negative AVERROR on error.
+     * @deprecated unused
      */
     int (*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.
+     * Filtering callback. This is where a filter receives a frame with
+     * audio/video data and should do its processing.
      *
-     * Input audio pads only.
+     * Input pads only.
      *
      * @return >= 0 on success, a negative AVERROR on error. This function
-     * must ensure that samplesref is properly unreferenced on error if it
+     * must ensure that frame is properly unreferenced on error if it
      * hasn't been passed on to another filter.
      */
-    int (*filter_samples)(AVFilterLink *link, AVFilterBufferRef *samplesref);
+    int (*filter_frame)(AVFilterLink *link, AVFilterBufferRef *frame);
 
     /**
      * Frame poll callback. This returns the number of immediately available
@@ -531,7 +511,7 @@
     int h;                      ///< agreed upon image height
     AVRational sample_aspect_ratio; ///< agreed upon sample aspect ratio
     /* These parameters apply only to audio */
-    uint64_t channel_layout;    ///< channel layout of current buffer (see libavutil/audioconvert.h)
+    uint64_t channel_layout;    ///< channel layout of current buffer (see libavutil/channel_layout.h)
     int sample_rate;            ///< samples per second
 
     int format;                 ///< agreed upon media format
@@ -674,7 +654,7 @@
     int partial_buf_size;
 
     /**
-     * Minimum number of samples to filter at once. If filter_samples() is
+     * Minimum number of samples to filter at once. If filter_frame() is
      * called with fewer samples, it will accumulate them in partial_buf.
      * This field and the related ones must not be changed after filtering
      * has started.
@@ -683,7 +663,7 @@
     int min_samples;
 
     /**
-     * Maximum number of samples to filter at once. If filter_samples() is
+     * Maximum number of samples to filter at once. If filter_frame() is
      * called with more samples, it will split them.
      */
     int max_samples;
@@ -699,7 +679,7 @@
 
     /**
      * True if the link is closed.
-     * If set, all attemps of start_frame, filter_samples or request_frame
+     * If set, all attemps of start_frame, filter_frame or request_frame
      * will fail with AVERROR_EOF, and if necessary the reference will be
      * destroyed.
      * If request_frame returns AVERROR_EOF, this flag is set on the
@@ -753,7 +733,7 @@
  */
 AVFilterBufferRef *
 avfilter_get_video_buffer_ref_from_arrays(uint8_t * const data[4], const int linesize[4], int perms,
-                                          int w, int h, enum PixelFormat format);
+                                          int w, int h, enum AVPixelFormat format);
 
 /**
  * Create an audio buffer reference wrapped around an already
diff --git a/libavfilter/avfiltergraph.c b/libavfilter/avfiltergraph.c
index b745c3c..52af2ad 100644
--- a/libavfilter/avfiltergraph.c
+++ b/libavfilter/avfiltergraph.c
@@ -23,8 +23,9 @@
 #include <ctype.h>
 #include <string.h>
 
-#include "libavutil/audioconvert.h"
 #include "libavutil/avassert.h"
+#include "libavutil/channel_layout.h"
+#include "libavutil/opt.h"
 #include "libavutil/pixdesc.h"
 #include "libavcodec/avcodec.h" // avcodec_find_best_pix_fmt_of_2()
 #include "avfilter.h"
@@ -32,14 +33,19 @@
 #include "formats.h"
 #include "internal.h"
 
-#include "libavutil/audioconvert.h"
-#include "libavutil/avassert.h"
-#include "libavutil/common.h"
-#include "libavutil/log.h"
+#define OFFSET(x) offsetof(AVFilterGraph,x)
+
+static const AVOption options[]={
+{"scale_sws_opts"       , "default scale filter options"        , OFFSET(scale_sws_opts)        ,  AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, 0 },
+{"aresample_swr_opts"   , "default aresample filter options"    , OFFSET(aresample_swr_opts)    ,  AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, 0 },
+{0}
+};
+
 
 static const AVClass filtergraph_class = {
     .class_name = "AVFilterGraph",
     .item_name  = av_default_item_name,
+    .option     = options,
     .version    = LIBAVUTIL_VERSION_INT,
     .category   = AV_CLASS_CATEGORY_FILTER,
 };
@@ -61,6 +67,7 @@
         avfilter_free((*graph)->filters[(*graph)->filter_count - 1]);
     av_freep(&(*graph)->sink_links);
     av_freep(&(*graph)->scale_sws_opts);
+    av_freep(&(*graph)->aresample_swr_opts);
     av_freep(&(*graph)->filters);
     av_freep(graph);
 }
@@ -118,22 +125,25 @@
     int i, j;
 
     for (i = 0; i < graph->filter_count; i++) {
+        const AVFilterPad *pad;
         filt = graph->filters[i];
 
         for (j = 0; j < filt->nb_inputs; j++) {
             if (!filt->inputs[j] || !filt->inputs[j]->src) {
+                pad = &filt->input_pads[j];
                 av_log(log_ctx, AV_LOG_ERROR,
-                       "Input pad \"%s\" for the filter \"%s\" of type \"%s\" not connected to any source\n",
-                       filt->input_pads[j].name, filt->name, filt->filter->name);
+                       "Input pad \"%s\" with type %s of the filter instance \"%s\" of %s not connected to any source\n",
+                       pad->name, av_get_media_type_string(pad->type), filt->name, filt->filter->name);
                 return AVERROR(EINVAL);
             }
         }
 
         for (j = 0; j < filt->nb_outputs; j++) {
             if (!filt->outputs[j] || !filt->outputs[j]->dst) {
+                pad = &filt->output_pads[j];
                 av_log(log_ctx, AV_LOG_ERROR,
-                       "Output pad \"%s\" for the filter \"%s\" of type \"%s\" not connected to any destination\n",
-                       filt->output_pads[j].name, filt->name, filt->filter->name);
+                       "Output pad \"%s\" with type %s of the filter instance \"%s\" of %s not connected to any destination\n",
+                       pad->name, av_get_media_type_string(pad->type), filt->name, filt->filter->name);
                 return AVERROR(EINVAL);
             }
         }
@@ -358,7 +368,11 @@
 
                     snprintf(inst_name, sizeof(inst_name), "auto-inserted scaler %d",
                              scaler_count++);
-                    snprintf(scale_args, sizeof(scale_args), "0:0:%s", graph->scale_sws_opts);
+                    if (graph->scale_sws_opts)
+                        snprintf(scale_args, sizeof(scale_args), "0:0:%s", graph->scale_sws_opts);
+                    else
+                        snprintf(scale_args, sizeof(scale_args), "0:0");
+
                     if ((ret = avfilter_graph_create_filter(&convert, filter,
                                                             inst_name, scale_args, NULL,
                                                             graph)) < 0)
@@ -374,7 +388,7 @@
                     snprintf(inst_name, sizeof(inst_name), "auto-inserted resampler %d",
                              resampler_count++);
                     if ((ret = avfilter_graph_create_filter(&convert, filter,
-                                                            inst_name, NULL, NULL, graph)) < 0)
+                                                            inst_name, graph->aresample_swr_opts, NULL, graph)) < 0)
                         return ret;
                     break;
                 default:
@@ -424,11 +438,11 @@
 
     if (link->type == AVMEDIA_TYPE_VIDEO) {
         if(ref && ref->type == AVMEDIA_TYPE_VIDEO){
-            int has_alpha= av_pix_fmt_descriptors[ref->format].nb_components % 2 == 0;
-            enum PixelFormat best= PIX_FMT_NONE;
+            int has_alpha= av_pix_fmt_desc_get(ref->format)->nb_components % 2 == 0;
+            enum AVPixelFormat best= AV_PIX_FMT_NONE;
             int i;
             for (i=0; i<link->in_formats->format_count; i++) {
-                enum PixelFormat p = link->in_formats->formats[i];
+                enum AVPixelFormat p = link->in_formats->formats[i];
                 best= avcodec_find_best_pix_fmt_of_2(best, p, ref->format, has_alpha, NULL);
             }
             av_log(link->src,AV_LOG_DEBUG, "picking %s out of %d ref:%s alpha:%d\n",
diff --git a/libavfilter/avfiltergraph.h b/libavfilter/avfiltergraph.h
index 0518124..728bbb5 100644
--- a/libavfilter/avfiltergraph.h
+++ b/libavfilter/avfiltergraph.h
@@ -32,6 +32,8 @@
 
     char *scale_sws_opts; ///< sws options to use for the auto-inserted scale filters
 
+    char *aresample_swr_opts; ///< swr options to use for the auto-inserted aresample filters, Access ONLY through AVOptions
+
     /**
      * Private fields
      *
diff --git a/libavfilter/buffer.c b/libavfilter/buffer.c
index fc65b82..a8155ef 100644
--- a/libavfilter/buffer.c
+++ b/libavfilter/buffer.c
@@ -20,7 +20,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/avassert.h"
 #include "libavutil/common.h"
 #include "libavutil/imgutils.h"
@@ -54,6 +54,10 @@
     if (!ret)
         return NULL;
     *ret = *ref;
+
+    ret->metadata = NULL;
+    av_dict_copy(&ret->metadata, ref->metadata, 0);
+
     if (ref->type == AVMEDIA_TYPE_VIDEO) {
         ret->video = av_malloc(sizeof(AVFilterBufferRefVideoProps));
         if (!ret->video) {
@@ -172,6 +176,7 @@
         av_freep(&ref->video->qp_table);
     av_freep(&ref->video);
     av_freep(&ref->audio);
+    av_dict_free(&ref->metadata);
     av_free(ref);
 }
 
@@ -197,6 +202,9 @@
     case AVMEDIA_TYPE_AUDIO: *dst->audio = *src->audio; break;
     default: break;
     }
+
+    av_dict_free(&dst->metadata);
+    av_dict_copy(&dst->metadata, src->metadata, 0);
 }
 
 AVFilterBufferRef *ff_copy_buffer_ref(AVFilterLink *outlink,
diff --git a/libavfilter/buffersink.c b/libavfilter/buffersink.c
index 5cd0924..282be30 100644
--- a/libavfilter/buffersink.c
+++ b/libavfilter/buffersink.c
@@ -24,8 +24,8 @@
  */
 
 #include "libavutil/audio_fifo.h"
-#include "libavutil/audioconvert.h"
 #include "libavutil/avassert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
 #include "libavutil/mathematics.h"
 
@@ -48,13 +48,12 @@
         av_audio_fifo_free(sink->audio_fifo);
 }
 
-static int start_frame(AVFilterLink *link, AVFilterBufferRef *buf)
+static int filter_frame(AVFilterLink *link, AVFilterBufferRef *buf)
 {
     BufferSinkContext *s = link->dst->priv;
 
 //     av_assert0(!s->cur_buf);
     s->cur_buf    = buf;
-    link->cur_buf = NULL;
 
     return 0;
 }
@@ -140,6 +139,17 @@
     return ret;
 }
 
+static const AVFilterPad avfilter_vsink_buffer_inputs[] = {
+    {
+        .name        = "default",
+        .type        = AVMEDIA_TYPE_VIDEO,
+        .filter_frame = filter_frame,
+        .min_perms   = AV_PERM_READ,
+        .needs_fifo  = 1
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vsink_buffer = {
 #if AV_HAVE_INCOMPATIBLE_FORK_ABI
     .name      = "buffersink",
@@ -150,15 +160,21 @@
     .priv_size = sizeof(BufferSinkContext),
     .uninit    = uninit,
 
-    .inputs    = (const AVFilterPad[]) {{ .name          = "default",
-                                          .type          = AVMEDIA_TYPE_VIDEO,
-                                          .start_frame   = start_frame,
-                                          .min_perms     = AV_PERM_READ,
-                                          .needs_fifo    = 1 },
-                                        { .name = NULL }},
+    .inputs    = avfilter_vsink_buffer_inputs,
     .outputs   = NULL,
 };
 
+static const AVFilterPad avfilter_asink_abuffer_inputs[] = {
+    {
+        .name           = "default",
+        .type           = AVMEDIA_TYPE_AUDIO,
+        .filter_frame   = filter_frame,
+        .min_perms      = AV_PERM_READ,
+        .needs_fifo     = 1
+    },
+    { NULL }
+};
+
 AVFilter avfilter_asink_abuffer = {
 #if AV_HAVE_INCOMPATIBLE_FORK_ABI
     .name      = "abuffersink",
@@ -169,11 +185,6 @@
     .priv_size = sizeof(BufferSinkContext),
     .uninit    = uninit,
 
-    .inputs    = (const AVFilterPad[]) {{ .name           = "default",
-                                          .type           = AVMEDIA_TYPE_AUDIO,
-                                          .filter_samples = start_frame,
-                                          .min_perms      = AV_PERM_READ,
-                                          .needs_fifo     = 1 },
-                                        { .name = NULL }},
+    .inputs    = avfilter_asink_abuffer_inputs,
     .outputs   = NULL,
 };
diff --git a/libavfilter/buffersink.h b/libavfilter/buffersink.h
index acafa76..a401937 100644
--- a/libavfilter/buffersink.h
+++ b/libavfilter/buffersink.h
@@ -30,7 +30,7 @@
  * Struct to use for initializing a buffersink context.
  */
 typedef struct {
-    const enum PixelFormat *pixel_fmts; ///< list of allowed pixel formats, terminated by PIX_FMT_NONE
+    const enum AVPixelFormat *pixel_fmts; ///< list of allowed pixel formats, terminated by AV_PIX_FMT_NONE
 } AVBufferSinkParams;
 
 /**
diff --git a/libavfilter/buffersrc.c b/libavfilter/buffersrc.c
index db2db3a..7949098 100644
--- a/libavfilter/buffersrc.c
+++ b/libavfilter/buffersrc.c
@@ -23,6 +23,12 @@
  * memory buffer source filter
  */
 
+#include "libavutil/channel_layout.h"
+#include "libavutil/common.h"
+#include "libavutil/fifo.h"
+#include "libavutil/imgutils.h"
+#include "libavutil/opt.h"
+#include "libavutil/samplefmt.h"
 #include "audio.h"
 #include "avfilter.h"
 #include "buffersrc.h"
@@ -31,13 +37,6 @@
 #include "video.h"
 #include "avcodec.h"
 
-#include "libavutil/audioconvert.h"
-#include "libavutil/common.h"
-#include "libavutil/fifo.h"
-#include "libavutil/imgutils.h"
-#include "libavutil/opt.h"
-#include "libavutil/samplefmt.h"
-
 typedef struct {
     const AVClass    *class;
     AVFifoBuffer     *fifo;
@@ -48,7 +47,7 @@
 
     /* video only */
     int               w, h;
-    enum PixelFormat  pix_fmt;
+    enum AVPixelFormat  pix_fmt;
     AVRational        pixel_aspect;
     char              *sws_param;
 
@@ -64,8 +63,7 @@
 
 #define CHECK_VIDEO_PARAM_CHANGE(s, c, width, height, format)\
     if (c->w != width || c->h != height || c->pix_fmt != format) {\
-        av_log(s, AV_LOG_ERROR, "Changing frame properties on the fly is not supported.\n");\
-        return AVERROR(EINVAL);\
+        av_log(s, AV_LOG_INFO, "Changing frame properties on the fly is not supported by all filters.\n");\
     }
 
 #define CHECK_AUDIO_PARAM_CHANGE(s, c, srate, ch_layout, format)\
@@ -226,7 +224,7 @@
     }
 
     av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d pixfmt:%s tb:%d/%d fr:%d/%d sar:%d/%d sws_param:%s\n",
-           c->w, c->h, av_pix_fmt_descriptors[c->pix_fmt].name,
+           c->w, c->h, av_get_pix_fmt_name(c->pix_fmt),
            c->time_base.num, c->time_base.den, c->frame_rate.num, c->frame_rate.den,
            c->pixel_aspect.num, c->pixel_aspect.den, (char *)av_x_if_null(c->sws_param, ""));
     c->warning_limit = 100;
@@ -373,20 +371,7 @@
     }
     av_fifo_generic_read(c->fifo, &buf, sizeof(buf), NULL);
 
-    switch (link->type) {
-    case AVMEDIA_TYPE_VIDEO:
-        if ((ret = ff_start_frame(link, buf)) < 0 ||
-            (ret = ff_draw_slice(link, 0, link->h, 1)) < 0 ||
-            (ret = ff_end_frame(link)) < 0)
-            return ret;
-        break;
-    case AVMEDIA_TYPE_AUDIO:
-        ret = ff_filter_samples(link, buf);
-        break;
-    default:
-        avfilter_unref_bufferp(&buf);
-        return AVERROR(EINVAL);
-    }
+    ff_filter_frame(link, buf);
 
     return ret;
 }
@@ -400,6 +385,17 @@
     return size/sizeof(AVFilterBufferRef*);
 }
 
+static const AVFilterPad avfilter_vsrc_buffer_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .request_frame = request_frame,
+        .poll_frame    = poll_frame,
+        .config_props  = config_props,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vsrc_buffer = {
     .name      = "buffer",
     .description = NULL_IF_CONFIG_SMALL("Buffer video frames, and make them accessible to the filterchain."),
@@ -410,15 +406,21 @@
     .uninit    = uninit,
 
     .inputs    = NULL,
-    .outputs   = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_VIDEO,
-                                          .request_frame   = request_frame,
-                                          .poll_frame      = poll_frame,
-                                          .config_props    = config_props, },
-                                        { .name = NULL}},
+    .outputs   = avfilter_vsrc_buffer_outputs,
     .priv_class = &buffer_class,
 };
 
+static const AVFilterPad avfilter_asrc_abuffer_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_AUDIO,
+        .request_frame = request_frame,
+        .poll_frame    = poll_frame,
+        .config_props  = config_props,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_asrc_abuffer = {
     .name          = "abuffer",
     .description   = NULL_IF_CONFIG_SMALL("Buffer audio frames, and make them accessible to the filterchain."),
@@ -429,11 +431,6 @@
     .uninit    = uninit,
 
     .inputs    = NULL,
-    .outputs   = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_AUDIO,
-                                          .request_frame   = request_frame,
-                                          .poll_frame      = poll_frame,
-                                          .config_props    = config_props, },
-                                        { .name = NULL}},
+    .outputs   = avfilter_asrc_abuffer_outputs,
     .priv_class = &abuffer_class,
 };
diff --git a/libavfilter/drawutils.c b/libavfilter/drawutils.c
index 08b2659..aefd09d 100644
--- a/libavfilter/drawutils.c
+++ b/libavfilter/drawutils.c
@@ -30,19 +30,19 @@
 
 enum { RED = 0, GREEN, BLUE, ALPHA };
 
-int ff_fill_rgba_map(uint8_t *rgba_map, enum PixelFormat pix_fmt)
+int ff_fill_rgba_map(uint8_t *rgba_map, enum AVPixelFormat pix_fmt)
 {
     switch (pix_fmt) {
-    case PIX_FMT_0RGB:
-    case PIX_FMT_ARGB:  rgba_map[ALPHA] = 0; rgba_map[RED  ] = 1; rgba_map[GREEN] = 2; rgba_map[BLUE ] = 3; break;
-    case PIX_FMT_0BGR:
-    case PIX_FMT_ABGR:  rgba_map[ALPHA] = 0; rgba_map[BLUE ] = 1; rgba_map[GREEN] = 2; rgba_map[RED  ] = 3; break;
-    case PIX_FMT_RGB0:
-    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_BGR0:
-    case PIX_FMT_BGR24: rgba_map[BLUE ] = 0; rgba_map[GREEN] = 1; rgba_map[RED  ] = 2; rgba_map[ALPHA] = 3; break;
+    case AV_PIX_FMT_0RGB:
+    case AV_PIX_FMT_ARGB:  rgba_map[ALPHA] = 0; rgba_map[RED  ] = 1; rgba_map[GREEN] = 2; rgba_map[BLUE ] = 3; break;
+    case AV_PIX_FMT_0BGR:
+    case AV_PIX_FMT_ABGR:  rgba_map[ALPHA] = 0; rgba_map[BLUE ] = 1; rgba_map[GREEN] = 2; rgba_map[RED  ] = 3; break;
+    case AV_PIX_FMT_RGB0:
+    case AV_PIX_FMT_RGBA:
+    case AV_PIX_FMT_RGB24: rgba_map[RED  ] = 0; rgba_map[GREEN] = 1; rgba_map[BLUE ] = 2; rgba_map[ALPHA] = 3; break;
+    case AV_PIX_FMT_BGRA:
+    case AV_PIX_FMT_BGR0:
+    case AV_PIX_FMT_BGR24: rgba_map[BLUE ] = 0; rgba_map[GREEN] = 1; rgba_map[RED  ] = 2; rgba_map[ALPHA] = 3; break;
     default:                    /* unsupported */
         return AVERROR(EINVAL);
     }
@@ -50,12 +50,12 @@
 }
 
 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],
+                            enum AVPixelFormat 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];
+    const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(pix_fmt);
     int hsub = pix_desc->log2_chroma_w;
 
     *is_packed_rgba = ff_fill_rgba_map(rgba_map, pix_fmt) >= 0;
@@ -132,16 +132,16 @@
     }
 }
 
-int ff_draw_init(FFDrawContext *draw, enum PixelFormat format, unsigned flags)
+int ff_draw_init(FFDrawContext *draw, enum AVPixelFormat format, unsigned flags)
 {
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[format];
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
     const AVComponentDescriptor *c;
     unsigned i, nb_planes = 0;
     int pixelstep[MAX_PLANES] = { 0 };
 
     if (!desc->name)
         return AVERROR(EINVAL);
-    if (desc->flags & ~(PIX_FMT_PLANAR | PIX_FMT_RGB | PIX_FMT_PSEUDOPAL))
+    if (desc->flags & ~(PIX_FMT_PLANAR | PIX_FMT_RGB | PIX_FMT_PSEUDOPAL | PIX_FMT_ALPHA))
         return AVERROR(ENOSYS);
     for (i = 0; i < desc->nb_components; i++) {
         c = &desc->comp[i];
@@ -193,7 +193,7 @@
         color->comp[1].u8[0] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
         color->comp[2].u8[0] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
         color->comp[3].u8[0] = rgba[3];
-    } else if (draw->format == PIX_FMT_GRAY8 || draw->format == PIX_FMT_GRAY8A) {
+    } else if (draw->format == AV_PIX_FMT_GRAY8 || draw->format == AV_PIX_FMT_GRAY8A) {
         color->comp[0].u8[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
         color->comp[1].u8[0] = rgba[3];
     } else {
@@ -501,14 +501,14 @@
 
 AVFilterFormats *ff_draw_supported_pixel_formats(unsigned flags)
 {
-    enum PixelFormat i, pix_fmts[PIX_FMT_NB + 1];
+    enum AVPixelFormat i, pix_fmts[AV_PIX_FMT_NB + 1];
     unsigned n = 0;
     FFDrawContext draw;
 
-    for (i = 0; i < PIX_FMT_NB; i++)
+    for (i = 0; i < AV_PIX_FMT_NB; i++)
         if (ff_draw_init(&draw, i, flags) >= 0)
             pix_fmts[n++] = i;
-    pix_fmts[n++] = PIX_FMT_NONE;
+    pix_fmts[n++] = AV_PIX_FMT_NONE;
     return ff_make_format_list(pix_fmts);
 }
 
@@ -518,14 +518,14 @@
 
 int main(void)
 {
-    enum PixelFormat f;
+    enum AVPixelFormat f;
     const AVPixFmtDescriptor *desc;
     FFDrawContext draw;
     FFDrawColor color;
     int r, i;
 
-    for (f = 0; f < PIX_FMT_NB; f++) {
-        desc = &av_pix_fmt_descriptors[f];
+    for (f = 0; f < AV_PIX_FMT_NB; f++) {
+        desc = av_pix_fmt_desc_get(f);
         if (!desc->name)
             continue;
         printf("Testing %s...%*s", desc->name,
diff --git a/libavfilter/drawutils.h b/libavfilter/drawutils.h
index 211810a..df41695 100644
--- a/libavfilter/drawutils.h
+++ b/libavfilter/drawutils.h
@@ -28,11 +28,11 @@
 #include "avfilter.h"
 #include "libavutil/pixfmt.h"
 
-int ff_fill_rgba_map(uint8_t *rgba_map, enum PixelFormat pix_fmt);
+int ff_fill_rgba_map(uint8_t *rgba_map, enum AVPixelFormat pix_fmt);
 
 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],
+                            enum AVPixelFormat 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],
@@ -47,7 +47,7 @@
 
 typedef struct FFDrawContext {
     const struct AVPixFmtDescriptor *desc;
-    enum PixelFormat format;
+    enum AVPixelFormat format;
     unsigned nb_planes;
     int pixelstep[MAX_PLANES]; /*< offset between pixels */
     uint8_t comp_mask[MAX_PLANES]; /*< bitmask of used non-alpha components */
@@ -74,7 +74,7 @@
  * No flags currently defined.
  * @return  0 for success, < 0 for error
  */
-int ff_draw_init(FFDrawContext *draw, enum PixelFormat format, unsigned flags);
+int ff_draw_init(FFDrawContext *draw, enum AVPixelFormat format, unsigned flags);
 
 /**
  * Prepare a color.
diff --git a/libavfilter/f_ebur128.c b/libavfilter/f_ebur128.c
new file mode 100644
index 0000000..f9da80d
--- /dev/null
+++ b/libavfilter/f_ebur128.c
@@ -0,0 +1,750 @@
+/*
+ * Copyright (c) 2012 Clément Bœsch
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg 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,
+ * 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 Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+/**
+ * @file
+ * EBU R.128 implementation
+ * @see http://tech.ebu.ch/loudness
+ * @see https://www.youtube.com/watch?v=iuEtQqC-Sqo "EBU R128 Introduction - Florian Camerer"
+ * @todo True Peak
+ * @todo implement start/stop/reset through filter command injection
+ * @todo support other frequencies to avoid resampling
+ */
+
+#include <math.h>
+
+#include "libavutil/avassert.h"
+#include "libavutil/avstring.h"
+#include "libavutil/channel_layout.h"
+#include "libavutil/xga_font_data.h"
+#include "libavutil/opt.h"
+#include "libavutil/timestamp.h"
+#include "audio.h"
+#include "avfilter.h"
+#include "formats.h"
+#include "internal.h"
+
+#define MAX_CHANNELS 63
+
+/* pre-filter coefficients */
+#define PRE_B0  1.53512485958697
+#define PRE_B1 -2.69169618940638
+#define PRE_B2  1.19839281085285
+#define PRE_A1 -1.69065929318241
+#define PRE_A2  0.73248077421585
+
+/* RLB-filter coefficients */
+#define RLB_B0  1.0
+#define RLB_B1 -2.0
+#define RLB_B2  1.0
+#define RLB_A1 -1.99004745483398
+#define RLB_A2  0.99007225036621
+
+#define ABS_THRES    -70            ///< silence gate: we discard anything below this absolute (LUFS) threshold
+#define ABS_UP_THRES  10            ///< upper loud limit to consider (ABS_THRES being the minimum)
+#define HIST_GRAIN   100            ///< defines histogram precision
+#define HIST_SIZE  ((ABS_UP_THRES - ABS_THRES) * HIST_GRAIN + 1)
+
+/**
+ * An histogram is an array of HIST_SIZE hist_entry storing all the energies
+ * recorded (with an accuracy of 1/HIST_GRAIN) of the loudnesses from ABS_THRES
+ * (at 0) to ABS_UP_THRES (at HIST_SIZE-1).
+ * This fixed-size system avoids the need of a list of energies growing
+ * infinitely over the time and is thus more scalable.
+ */
+struct hist_entry {
+    int count;                      ///< how many times the corresponding value occurred
+    double energy;                  ///< E = 10^((L + 0.691) / 10)
+    double loudness;                ///< L = -0.691 + 10 * log10(E)
+};
+
+struct integrator {
+    double *cache[MAX_CHANNELS];    ///< window of filtered samples (N ms)
+    int cache_pos;                  ///< focus on the last added bin in the cache array
+    double sum[MAX_CHANNELS];       ///< sum of the last N ms filtered samples (cache content)
+    int filled;                     ///< 1 if the cache is completely filled, 0 otherwise
+    double rel_threshold;           ///< relative threshold
+    double sum_kept_powers;         ///< sum of the powers (weighted sums) above absolute threshold
+    int nb_kept_powers;             ///< number of sum above absolute threshold
+    struct hist_entry *histogram;   ///< histogram of the powers, used to compute LRA and I
+};
+
+struct rect { int x, y, w, h; };
+
+typedef struct {
+    const AVClass *class;           ///< AVClass context for log and options purpose
+
+    /* video  */
+    int do_video;                   ///< 1 if video output enabled, 0 otherwise
+    int w, h;                       ///< size of the video output
+    struct rect text;               ///< rectangle for the LU legend on the left
+    struct rect graph;              ///< rectangle for the main graph in the center
+    struct rect gauge;              ///< rectangle for the gauge on the right
+    AVFilterBufferRef *outpicref;   ///< output picture reference, updated regularly
+    int meter;                      ///< select a EBU mode between +9 and +18
+    int scale_range;                ///< the range of LU values according to the meter
+    int y_zero_lu;                  ///< the y value (pixel position) for 0 LU
+    int *y_line_ref;                ///< y reference values for drawing the LU lines in the graph and the gauge
+
+    /* audio */
+    int nb_channels;                ///< number of channels in the input
+    double *ch_weighting;           ///< channel weighting mapping
+    int sample_count;               ///< sample count used for refresh frequency, reset at refresh
+
+    /* Filter caches.
+     * The mult by 3 in the following is for X[i], X[i-1] and X[i-2] */
+    double x[MAX_CHANNELS * 3];     ///< 3 input samples cache for each channel
+    double y[MAX_CHANNELS * 3];     ///< 3 pre-filter samples cache for each channel
+    double z[MAX_CHANNELS * 3];     ///< 3 RLB-filter samples cache for each channel
+
+#define I400_BINS  (48000 * 4 / 10)
+#define I3000_BINS (48000 * 3)
+    struct integrator i400;         ///< 400ms integrator, used for Momentary loudness  (M), and Integrated loudness (I)
+    struct integrator i3000;        ///<    3s integrator, used for Short term loudness (S), and Loudness Range      (LRA)
+
+    /* I and LRA specific */
+    double integrated_loudness;     ///< integrated loudness in LUFS (I)
+    double loudness_range;          ///< loudness range in LU (LRA)
+    double lra_low, lra_high;       ///< low and high LRA values
+} EBUR128Context;
+
+#define OFFSET(x) offsetof(EBUR128Context, x)
+#define A AV_OPT_FLAG_AUDIO_PARAM
+#define V AV_OPT_FLAG_VIDEO_PARAM
+#define F AV_OPT_FLAG_FILTERING_PARAM
+static const AVOption ebur128_options[] = {
+    { "video", "set video output", OFFSET(do_video), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, V|F },
+    { "size",  "set video size",   OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x480"}, 0, 0, V|F },
+    { "meter", "set scale meter (+9 to +18)",  OFFSET(meter), AV_OPT_TYPE_INT, {.i64 = 9}, 9, 18, V|F },
+    { NULL },
+};
+
+AVFILTER_DEFINE_CLASS(ebur128);
+
+static const uint8_t graph_colors[] = {
+    0xdd, 0x66, 0x66,   // value above 0LU non reached
+    0x66, 0x66, 0xdd,   // value below 0LU non reached
+    0x96, 0x33, 0x33,   // value above 0LU reached
+    0x33, 0x33, 0x96,   // value below 0LU reached
+    0xdd, 0x96, 0x96,   // value above 0LU line non reached
+    0x96, 0x96, 0xdd,   // value below 0LU line non reached
+    0xdd, 0x33, 0x33,   // value above 0LU line reached
+    0x33, 0x33, 0xdd,   // value below 0LU line reached
+};
+
+static const uint8_t *get_graph_color(const EBUR128Context *ebur128, int v, int y)
+{
+    const int below0  = y > ebur128->y_zero_lu;
+    const int reached = y >= v;
+    const int line    = ebur128->y_line_ref[y] || y == ebur128->y_zero_lu;
+    const int colorid = 4*line + 2*reached + below0;
+    return graph_colors + 3*colorid;
+}
+
+static inline int lu_to_y(const EBUR128Context *ebur128, double v)
+{
+    v += 2 * ebur128->meter;                            // make it in range [0;...]
+    v  = av_clipf(v, 0, ebur128->scale_range);          // make sure it's in the graph scale
+    v  = ebur128->scale_range - v;                      // invert value (y=0 is on top)
+    return v * ebur128->graph.h / ebur128->scale_range; // rescale from scale range to px height
+}
+
+#define FONT8   0
+#define FONT16  1
+
+static const uint8_t font_colors[] = {
+    0xdd, 0xdd, 0x00,
+    0x00, 0x96, 0x96,
+};
+
+static void drawtext(AVFilterBufferRef *pic, int x, int y, int ftid, const uint8_t *color, const char *fmt, ...)
+{
+    int i;
+    char buf[128] = {0};
+    const uint8_t *font;
+    int font_height;
+    va_list vl;
+
+    if      (ftid == FONT16) font = avpriv_vga16_font, font_height = 16;
+    else if (ftid == FONT8)  font = avpriv_cga_font,   font_height =  8;
+    else return;
+
+    va_start(vl, fmt);
+    vsnprintf(buf, sizeof(buf), fmt, vl);
+    va_end(vl);
+
+    for (i = 0; buf[i]; i++) {
+        int char_y, mask;
+        uint8_t *p = pic->data[0] + y*pic->linesize[0] + (x + i*8)*3;
+
+        for (char_y = 0; char_y < font_height; char_y++) {
+            for (mask = 0x80; mask; mask >>= 1) {
+                if (font[buf[i] * font_height + char_y] & mask)
+                    memcpy(p, color, 3);
+                else
+                    memcpy(p, "\x00\x00\x00", 3);
+                p += 3;
+            }
+            p += pic->linesize[0] - 8*3;
+        }
+    }
+}
+
+static void drawline(AVFilterBufferRef *pic, int x, int y, int len, int step)
+{
+    int i;
+    uint8_t *p = pic->data[0] + y*pic->linesize[0] + x*3;
+
+    for (i = 0; i < len; i++) {
+        memcpy(p, "\x00\xff\x00", 3);
+        p += step;
+    }
+}
+
+static int config_video_output(AVFilterLink *outlink)
+{
+    int i, x, y;
+    uint8_t *p;
+    AVFilterContext *ctx = outlink->src;
+    EBUR128Context *ebur128 = ctx->priv;
+    AVFilterBufferRef *outpicref;
+
+    /* check if there is enough space to represent everything decently */
+    if (ebur128->w < 640 || ebur128->h < 480) {
+        av_log(ctx, AV_LOG_ERROR, "Video size %dx%d is too small, "
+               "minimum size is 640x480\n", ebur128->w, ebur128->h);
+        return AVERROR(EINVAL);
+    }
+    outlink->w = ebur128->w;
+    outlink->h = ebur128->h;
+
+#define PAD 8
+
+    /* configure text area position and size */
+    ebur128->text.x  = PAD;
+    ebur128->text.y  = 40;
+    ebur128->text.w  = 3 * 8;   // 3 characters
+    ebur128->text.h  = ebur128->h - PAD - ebur128->text.y;
+
+    /* configure gauge position and size */
+    ebur128->gauge.w = 20;
+    ebur128->gauge.h = ebur128->text.h;
+    ebur128->gauge.x = ebur128->w - PAD - ebur128->gauge.w;
+    ebur128->gauge.y = ebur128->text.y;
+
+    /* configure graph position and size */
+    ebur128->graph.x = ebur128->text.x + ebur128->text.w + PAD;
+    ebur128->graph.y = ebur128->gauge.y;
+    ebur128->graph.w = ebur128->gauge.x - ebur128->graph.x - PAD;
+    ebur128->graph.h = ebur128->gauge.h;
+
+    /* graph and gauge share the LU-to-pixel code */
+    av_assert0(ebur128->graph.h == ebur128->gauge.h);
+
+    /* prepare the initial picref buffer */
+    avfilter_unref_bufferp(&ebur128->outpicref);
+    ebur128->outpicref = outpicref =
+        ff_get_video_buffer(outlink, AV_PERM_WRITE|AV_PERM_PRESERVE|AV_PERM_REUSE2,
+                            outlink->w, outlink->h);
+    if (!outpicref)
+        return AVERROR(ENOMEM);
+    outlink->sample_aspect_ratio = (AVRational){1,1};
+
+    /* init y references values (to draw LU lines) */
+    ebur128->y_line_ref = av_calloc(ebur128->graph.h + 1, sizeof(*ebur128->y_line_ref));
+    if (!ebur128->y_line_ref)
+        return AVERROR(ENOMEM);
+
+    /* black background */
+    memset(outpicref->data[0], 0, ebur128->h * outpicref->linesize[0]);
+
+    /* draw LU legends */
+    drawtext(outpicref, PAD, PAD+16, FONT8, font_colors+3, " LU");
+    for (i = ebur128->meter; i >= -ebur128->meter * 2; i--) {
+        y = lu_to_y(ebur128, i);
+        x = PAD + (i < 10 && i > -10) * 8;
+        ebur128->y_line_ref[y] = i;
+        y -= 4; // -4 to center vertically
+        drawtext(outpicref, x, y + ebur128->graph.y, FONT8, font_colors+3,
+                 "%c%d", i < 0 ? '-' : i > 0 ? '+' : ' ', FFABS(i));
+    }
+
+    /* draw graph */
+    ebur128->y_zero_lu = lu_to_y(ebur128, 0);
+    p = outpicref->data[0] + ebur128->graph.y * outpicref->linesize[0]
+                           + ebur128->graph.x * 3;
+    for (y = 0; y < ebur128->graph.h; y++) {
+        const uint8_t *c = get_graph_color(ebur128, INT_MAX, y);
+
+        for (x = 0; x < ebur128->graph.w; x++)
+            memcpy(p + x*3, c, 3);
+        p += outpicref->linesize[0];
+    }
+
+    /* draw fancy rectangles around the graph and the gauge */
+#define DRAW_RECT(r) do { \
+    drawline(outpicref, r.x,       r.y - 1,   r.w, 3); \
+    drawline(outpicref, r.x,       r.y + r.h, r.w, 3); \
+    drawline(outpicref, r.x - 1,   r.y,       r.h, outpicref->linesize[0]); \
+    drawline(outpicref, r.x + r.w, r.y,       r.h, outpicref->linesize[0]); \
+} while (0)
+    DRAW_RECT(ebur128->graph);
+    DRAW_RECT(ebur128->gauge);
+
+    return 0;
+}
+
+static int config_audio_output(AVFilterLink *outlink)
+{
+    int i;
+    AVFilterContext *ctx = outlink->src;
+    EBUR128Context *ebur128 = ctx->priv;
+    const int nb_channels = av_get_channel_layout_nb_channels(outlink->channel_layout);
+
+#define BACK_MASK (AV_CH_BACK_LEFT    |AV_CH_BACK_CENTER    |AV_CH_BACK_RIGHT| \
+                   AV_CH_TOP_BACK_LEFT|AV_CH_TOP_BACK_CENTER|AV_CH_TOP_BACK_RIGHT)
+
+    ebur128->nb_channels  = nb_channels;
+    ebur128->ch_weighting = av_calloc(nb_channels, sizeof(*ebur128->ch_weighting));
+    if (!ebur128->ch_weighting)
+        return AVERROR(ENOMEM);
+
+    for (i = 0; i < nb_channels; i++) {
+
+        /* channel weighting */
+        if ((outlink->channel_layout & 1ULL<<i) == AV_CH_LOW_FREQUENCY)
+            continue;
+        if (outlink->channel_layout & 1ULL<<i & BACK_MASK)
+            ebur128->ch_weighting[i] = 1.41;
+        else
+            ebur128->ch_weighting[i] = 1.0;
+
+        /* bins buffer for the two integration window (400ms and 3s) */
+        ebur128->i400.cache[i]  = av_calloc(I400_BINS,  sizeof(*ebur128->i400.cache[0]));
+        ebur128->i3000.cache[i] = av_calloc(I3000_BINS, sizeof(*ebur128->i3000.cache[0]));
+        if (!ebur128->i400.cache[i] || !ebur128->i3000.cache[i])
+            return AVERROR(ENOMEM);
+    }
+
+    return 0;
+}
+
+#define ENERGY(loudness) (pow(10, ((loudness) + 0.691) / 10.))
+#define LOUDNESS(energy) (-0.691 + 10 * log10(energy))
+
+static struct hist_entry *get_histogram(void)
+{
+    int i;
+    struct hist_entry *h = av_calloc(HIST_SIZE, sizeof(*h));
+
+    for (i = 0; i < HIST_SIZE; i++) {
+        h[i].loudness = i / (double)HIST_GRAIN + ABS_THRES;
+        h[i].energy   = ENERGY(h[i].loudness);
+    }
+    return h;
+}
+
+static av_cold int init(AVFilterContext *ctx, const char *args)
+{
+    int ret;
+    EBUR128Context *ebur128 = ctx->priv;
+    AVFilterPad pad;
+
+    ebur128->class = &ebur128_class;
+    av_opt_set_defaults(ebur128);
+
+    if ((ret = av_set_options_string(ebur128, args, "=", ":")) < 0)
+        return ret;
+
+    // if meter is  +9 scale, scale range is from -18 LU to  +9 LU (or 3*9)
+    // if meter is +18 scale, scale range is from -36 LU to +18 LU (or 3*18)
+    ebur128->scale_range = 3 * ebur128->meter;
+
+    ebur128->i400.histogram  = get_histogram();
+    ebur128->i3000.histogram = get_histogram();
+
+    ebur128->integrated_loudness = ABS_THRES;
+    ebur128->loudness_range = 0;
+
+    /* insert output pads */
+    if (ebur128->do_video) {
+        pad = (AVFilterPad){
+            .name         = av_strdup("out0"),
+            .type         = AVMEDIA_TYPE_VIDEO,
+            .config_props = config_video_output,
+        };
+        if (!pad.name)
+            return AVERROR(ENOMEM);
+        ff_insert_outpad(ctx, 0, &pad);
+    }
+    pad = (AVFilterPad){
+        .name         = av_asprintf("out%d", ebur128->do_video),
+        .type         = AVMEDIA_TYPE_AUDIO,
+        .config_props = config_audio_output,
+    };
+    if (!pad.name)
+        return AVERROR(ENOMEM);
+    ff_insert_outpad(ctx, ebur128->do_video, &pad);
+
+    /* summary */
+    av_log(ctx, AV_LOG_VERBOSE, "EBU +%d scale\n", ebur128->meter);
+
+    return 0;
+}
+
+#define HIST_POS(power) (int)(((power) - ABS_THRES) * HIST_GRAIN)
+
+/* loudness and power should be set such as loudness = -0.691 +
+ * 10*log10(power), we just avoid doing that calculus two times */
+static int gate_update(struct integrator *integ, double power,
+                       double loudness, int gate_thres)
+{
+    int ipower;
+    double relative_threshold;
+    int gate_hist_pos;
+
+    /* update powers histograms by incrementing current power count */
+    ipower = av_clip(HIST_POS(loudness), 0, HIST_SIZE - 1);
+    integ->histogram[ipower].count++;
+
+    /* compute relative threshold and get its position in the histogram */
+    integ->sum_kept_powers += power;
+    integ->nb_kept_powers++;
+    relative_threshold = integ->sum_kept_powers / integ->nb_kept_powers;
+    if (!relative_threshold)
+        relative_threshold = 1e-12;
+    integ->rel_threshold = LOUDNESS(relative_threshold) + gate_thres;
+    gate_hist_pos = av_clip(HIST_POS(integ->rel_threshold), 0, HIST_SIZE - 1);
+
+    return gate_hist_pos;
+}
+
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *insamples)
+{
+    int i, ch;
+    AVFilterContext *ctx = inlink->dst;
+    EBUR128Context *ebur128 = ctx->priv;
+    const int nb_channels = ebur128->nb_channels;
+    const int nb_samples  = insamples->audio->nb_samples;
+    const double *samples = (double *)insamples->data[0];
+    AVFilterBufferRef *pic = ebur128->outpicref;
+
+    for (i = 0; i < nb_samples; i++) {
+        const int bin_id_400  = ebur128->i400.cache_pos;
+        const int bin_id_3000 = ebur128->i3000.cache_pos;
+
+#define MOVE_TO_NEXT_CACHED_ENTRY(time) do {                \
+    ebur128->i##time.cache_pos++;                           \
+    if (ebur128->i##time.cache_pos == I##time##_BINS) {     \
+        ebur128->i##time.filled    = 1;                     \
+        ebur128->i##time.cache_pos = 0;                     \
+    }                                                       \
+} while (0)
+
+        MOVE_TO_NEXT_CACHED_ENTRY(400);
+        MOVE_TO_NEXT_CACHED_ENTRY(3000);
+
+        for (ch = 0; ch < nb_channels; ch++) {
+            double bin;
+
+            if (!ebur128->ch_weighting[ch])
+                continue;
+
+            /* Y[i] = X[i]*b0 + X[i-1]*b1 + X[i-2]*b2 - Y[i-1]*a1 - Y[i-2]*a2 */
+#define FILTER(Y, X, name) do {                                                 \
+            double *dst = ebur128->Y + ch*3;                                    \
+            double *src = ebur128->X + ch*3;                                    \
+            dst[2] = dst[1];                                                    \
+            dst[1] = dst[0];                                                    \
+            dst[0] = src[0]*name##_B0 + src[1]*name##_B1 + src[2]*name##_B2     \
+                                      - dst[1]*name##_A1 - dst[2]*name##_A2;    \
+} while (0)
+
+            ebur128->x[ch * 3] = *samples++; // set X[i]
+
+            // TODO: merge both filters in one?
+            FILTER(y, x, PRE);  // apply pre-filter
+            ebur128->x[ch * 3 + 2] = ebur128->x[ch * 3 + 1];
+            ebur128->x[ch * 3 + 1] = ebur128->x[ch * 3    ];
+            FILTER(z, y, RLB);  // apply RLB-filter
+
+            bin = ebur128->z[ch * 3] * ebur128->z[ch * 3];
+
+            /* add the new value, and limit the sum to the cache size (400ms or 3s)
+             * by removing the oldest one */
+            ebur128->i400.sum [ch] = ebur128->i400.sum [ch] + bin - ebur128->i400.cache [ch][bin_id_400];
+            ebur128->i3000.sum[ch] = ebur128->i3000.sum[ch] + bin - ebur128->i3000.cache[ch][bin_id_3000];
+
+            /* override old cache entry with the new value */
+            ebur128->i400.cache [ch][bin_id_400 ] = bin;
+            ebur128->i3000.cache[ch][bin_id_3000] = bin;
+        }
+
+        /* For integrated loudness, gating blocks are 400ms long with 75%
+         * overlap (see BS.1770-2 p5), so a re-computation is needed each 100ms
+         * (4800 samples at 48kHz). */
+        if (++ebur128->sample_count == 4800) {
+            double loudness_400, loudness_3000;
+            double power_400 = 1e-12, power_3000 = 1e-12;
+            AVFilterLink *outlink = ctx->outputs[0];
+            const int64_t pts = insamples->pts +
+                av_rescale_q(i, (AVRational){ 1, inlink->sample_rate },
+                             outlink->time_base);
+
+            ebur128->sample_count = 0;
+
+#define COMPUTE_LOUDNESS(m, time) do {                                              \
+    if (ebur128->i##time.filled) {                                                  \
+        /* weighting sum of the last <time> ms */                                   \
+        for (ch = 0; ch < nb_channels; ch++)                                        \
+            power_##time += ebur128->ch_weighting[ch] * ebur128->i##time.sum[ch];   \
+        power_##time /= I##time##_BINS;                                             \
+    }                                                                               \
+    loudness_##time = LOUDNESS(power_##time);                                       \
+} while (0)
+
+            COMPUTE_LOUDNESS(M,  400);
+            COMPUTE_LOUDNESS(S, 3000);
+
+            /* Integrated loudness */
+#define I_GATE_THRES -10  // initially defined to -8 LU in the first EBU standard
+
+            if (loudness_400 >= ABS_THRES) {
+                double integrated_sum = 0;
+                int nb_integrated = 0;
+                int gate_hist_pos = gate_update(&ebur128->i400, power_400,
+                                                loudness_400, I_GATE_THRES);
+
+                /* compute integrated loudness by summing the histogram values
+                 * above the relative threshold */
+                for (i = gate_hist_pos; i < HIST_SIZE; i++) {
+                    const int nb_v = ebur128->i400.histogram[i].count;
+                    nb_integrated  += nb_v;
+                    integrated_sum += nb_v * ebur128->i400.histogram[i].energy;
+                }
+                if (nb_integrated)
+                    ebur128->integrated_loudness = LOUDNESS(integrated_sum / nb_integrated);
+            }
+
+            /* LRA */
+#define LRA_GATE_THRES -20
+#define LRA_LOWER_PRC   10
+#define LRA_HIGHER_PRC  95
+
+            /* XXX: example code in EBU 3342 is ">=" but formula in BS.1770
+             * specs is ">" */
+            if (loudness_3000 >= ABS_THRES) {
+                int nb_powers = 0;
+                int gate_hist_pos = gate_update(&ebur128->i3000, power_3000,
+                                                loudness_3000, LRA_GATE_THRES);
+
+                for (i = gate_hist_pos; i < HIST_SIZE; i++)
+                    nb_powers += ebur128->i3000.histogram[i].count;
+                if (nb_powers) {
+                    int n, nb_pow;
+
+                    /* get lower loudness to consider */
+                    n = 0;
+                    nb_pow = LRA_LOWER_PRC  * nb_powers / 100. + 0.5;
+                    for (i = gate_hist_pos; i < HIST_SIZE; i++) {
+                        n += ebur128->i3000.histogram[i].count;
+                        if (n >= nb_pow) {
+                            ebur128->lra_low = ebur128->i3000.histogram[i].loudness;
+                            break;
+                        }
+                    }
+
+                    /* get higher loudness to consider */
+                    n = nb_powers;
+                    nb_pow = LRA_HIGHER_PRC * nb_powers / 100. + 0.5;
+                    for (i = HIST_SIZE - 1; i >= 0; i--) {
+                        n -= ebur128->i3000.histogram[i].count;
+                        if (n < nb_pow) {
+                            ebur128->lra_high = ebur128->i3000.histogram[i].loudness;
+                            break;
+                        }
+                    }
+
+                    // XXX: show low & high on the graph?
+                    ebur128->loudness_range = ebur128->lra_high - ebur128->lra_low;
+                }
+            }
+
+#define LOG_FMT "M:%6.1f S:%6.1f     I:%6.1f LUFS     LRA:%6.1f LU"
+
+            /* push one video frame */
+            if (ebur128->do_video) {
+                int x, y, ret;
+                uint8_t *p;
+
+                const int y_loudness_lu_graph = lu_to_y(ebur128, loudness_3000 + 23);
+                const int y_loudness_lu_gauge = lu_to_y(ebur128, loudness_400  + 23);
+
+                /* draw the graph using the short-term loudness */
+                p = pic->data[0] + ebur128->graph.y*pic->linesize[0] + ebur128->graph.x*3;
+                for (y = 0; y < ebur128->graph.h; y++) {
+                    const uint8_t *c = get_graph_color(ebur128, y_loudness_lu_graph, y);
+
+                    memmove(p, p + 3, (ebur128->graph.w - 1) * 3);
+                    memcpy(p + (ebur128->graph.w - 1) * 3, c, 3);
+                    p += pic->linesize[0];
+                }
+
+                /* draw the gauge using the momentary loudness */
+                p = pic->data[0] + ebur128->gauge.y*pic->linesize[0] + ebur128->gauge.x*3;
+                for (y = 0; y < ebur128->gauge.h; y++) {
+                    const uint8_t *c = get_graph_color(ebur128, y_loudness_lu_gauge, y);
+
+                    for (x = 0; x < ebur128->gauge.w; x++)
+                        memcpy(p + x*3, c, 3);
+                    p += pic->linesize[0];
+                }
+
+                /* draw textual info */
+                drawtext(pic, PAD, PAD - PAD/2, FONT16, font_colors,
+                         LOG_FMT "     ", // padding to erase trailing characters
+                         loudness_400, loudness_3000,
+                         ebur128->integrated_loudness, ebur128->loudness_range);
+
+                /* set pts and push frame */
+                pic->pts = pts;
+                ret = ff_filter_frame(outlink, avfilter_ref_buffer(pic, ~AV_PERM_WRITE));
+                if (ret < 0)
+                    return ret;
+            }
+
+            av_log(ctx, ebur128->do_video ? AV_LOG_VERBOSE : AV_LOG_INFO,
+                   "t: %-10s " LOG_FMT "\n", av_ts2timestr(pts, &outlink->time_base),
+                   loudness_400, loudness_3000,
+                   ebur128->integrated_loudness, ebur128->loudness_range);
+        }
+    }
+
+    return ff_filter_frame(ctx->outputs[ebur128->do_video], insamples);
+}
+
+static int query_formats(AVFilterContext *ctx)
+{
+    EBUR128Context *ebur128 = ctx->priv;
+    AVFilterFormats *formats;
+    AVFilterChannelLayouts *layouts;
+    AVFilterLink *inlink = ctx->inputs[0];
+    AVFilterLink *outlink = ctx->outputs[0];
+
+    static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_NONE };
+    static const int input_srate[] = {48000, -1}; // ITU-R BS.1770 provides coeff only for 48kHz
+    static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_RGB24, AV_PIX_FMT_NONE };
+
+    /* set input audio formats */
+    formats = ff_make_format_list(sample_fmts);
+    if (!formats)
+        return AVERROR(ENOMEM);
+    ff_formats_ref(formats, &inlink->out_formats);
+
+    layouts = ff_all_channel_layouts();
+    if (!layouts)
+        return AVERROR(ENOMEM);
+    ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts);
+
+    formats = ff_make_format_list(input_srate);
+    if (!formats)
+        return AVERROR(ENOMEM);
+    ff_formats_ref(formats, &inlink->out_samplerates);
+
+    /* set optional output video format */
+    if (ebur128->do_video) {
+        formats = ff_make_format_list(pix_fmts);
+        if (!formats)
+            return AVERROR(ENOMEM);
+        ff_formats_ref(formats, &outlink->in_formats);
+        outlink = ctx->outputs[1];
+    }
+
+    /* set audio output formats (same as input since it's just a passthrough) */
+    formats = ff_make_format_list(sample_fmts);
+    if (!formats)
+        return AVERROR(ENOMEM);
+    ff_formats_ref(formats, &outlink->in_formats);
+
+    layouts = ff_all_channel_layouts();
+    if (!layouts)
+        return AVERROR(ENOMEM);
+    ff_channel_layouts_ref(layouts, &outlink->in_channel_layouts);
+
+    formats = ff_make_format_list(input_srate);
+    if (!formats)
+        return AVERROR(ENOMEM);
+    ff_formats_ref(formats, &outlink->in_samplerates);
+
+    return 0;
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    int i;
+    EBUR128Context *ebur128 = ctx->priv;
+
+    av_log(ctx, AV_LOG_INFO, "Summary:\n\n"
+           "  Integrated loudness:\n"
+           "    I:         %5.1f LUFS\n"
+           "    Threshold: %5.1f LUFS\n\n"
+           "  Loudness range:\n"
+           "    LRA:       %5.1f LU\n"
+           "    Threshold: %5.1f LUFS\n"
+           "    LRA low:   %5.1f LUFS\n"
+           "    LRA high:  %5.1f LUFS\n",
+           ebur128->integrated_loudness, ebur128->i400.rel_threshold,
+           ebur128->loudness_range,      ebur128->i3000.rel_threshold,
+           ebur128->lra_low, ebur128->lra_high);
+
+    av_freep(&ebur128->y_line_ref);
+    av_freep(&ebur128->ch_weighting);
+    av_freep(&ebur128->i400.histogram);
+    av_freep(&ebur128->i3000.histogram);
+    for (i = 0; i < ebur128->nb_channels; i++) {
+        av_freep(&ebur128->i400.cache[i]);
+        av_freep(&ebur128->i3000.cache[i]);
+    }
+    for (i = 0; i < ctx->nb_outputs; i++)
+        av_freep(&ctx->output_pads[i].name);
+    avfilter_unref_bufferp(&ebur128->outpicref);
+}
+
+static const AVFilterPad ebur128_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_AUDIO,
+        .get_audio_buffer = ff_null_get_audio_buffer,
+        .filter_frame     = filter_frame,
+    },
+    { NULL }
+};
+
+AVFilter avfilter_af_ebur128 = {
+    .name          = "ebur128",
+    .description   = NULL_IF_CONFIG_SMALL("EBU R128 scanner."),
+    .priv_size     = sizeof(EBUR128Context),
+    .init          = init,
+    .uninit        = uninit,
+    .query_formats = query_formats,
+    .inputs        = ebur128_inputs,
+    .outputs       = NULL,
+    .priv_class    = &ebur128_class,
+};
diff --git a/libavfilter/f_sendcmd.c b/libavfilter/f_sendcmd.c
index 7081de8..790c8be 100644
--- a/libavfilter/f_sendcmd.c
+++ b/libavfilter/f_sendcmd.c
@@ -80,17 +80,15 @@
 } SendCmdContext;
 
 #define OFFSET(x) offsetof(SendCmdContext, x)
-
-static const AVOption sendcmd_options[]= {
-    { "commands", "set commands", OFFSET(commands_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0 },
-    { "c",        "set commands", OFFSET(commands_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0 },
-    { "filename", "set commands file",  OFFSET(commands_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0 },
-    { "f",        "set commands file",  OFFSET(commands_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0 },
+#define FLAGS AV_OPT_FLAG_FILTERING_PARAM
+static const AVOption options[] = {
+    { "commands", "set commands", OFFSET(commands_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
+    { "c",        "set commands", OFFSET(commands_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
+    { "filename", "set commands file",  OFFSET(commands_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
+    { "f",        "set commands file",  OFFSET(commands_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
     {NULL},
 };
 
-AVFILTER_DEFINE_CLASS(sendcmd);
-
 #define SPACES " \f\t\n\r"
 
 static void skip_comments(const char **buf)
@@ -370,13 +368,12 @@
     return ret == 0 ? i1->index - i2->index : ret;
 }
 
-static av_cold int init(AVFilterContext *ctx, const char *args)
+static av_cold int init(AVFilterContext *ctx, const char *args, const AVClass *class)
 {
     SendCmdContext *sendcmd = ctx->priv;
     int ret, i, j;
-    char *buf;
 
-    sendcmd->class = &sendcmd_class;
+    sendcmd->class = class;
     av_opt_set_defaults(sendcmd);
 
     if ((ret = av_set_options_string(sendcmd, args, "=", ":")) < 0)
@@ -389,7 +386,7 @@
     }
 
     if (sendcmd->commands_filename) {
-        uint8_t *file_buf;
+        uint8_t *file_buf, *buf;
         size_t file_bufsize;
         ret = av_file_map(sendcmd->commands_filename,
                           &file_buf, &file_bufsize, 0, ctx);
@@ -398,8 +395,10 @@
 
         /* create a 0-terminated string based on the read file */
         buf = av_malloc(file_bufsize + 1);
-        if (!buf)
+        if (!buf) {
+            av_file_unmap(file_buf, file_bufsize);
             return AVERROR(ENOMEM);
+        }
         memcpy(buf, file_buf, file_bufsize);
         buf[file_bufsize] = 0;
         av_file_unmap(file_buf, file_bufsize);
@@ -510,68 +509,92 @@
 
     switch (inlink->type) {
     case AVMEDIA_TYPE_VIDEO: return ff_start_frame   (inlink->dst->outputs[0], ref);
-    case AVMEDIA_TYPE_AUDIO: return ff_filter_samples(inlink->dst->outputs[0], ref);
+    case AVMEDIA_TYPE_AUDIO: return ff_filter_frame(inlink->dst->outputs[0], ref);
     }
     return AVERROR(ENOSYS);
 }
 
 #if CONFIG_SENDCMD_FILTER
 
+#define sendcmd_options options
+AVFILTER_DEFINE_CLASS(sendcmd);
+
+static av_cold int sendcmd_init(AVFilterContext *ctx, const char *args)
+{
+    return init(ctx, args, &sendcmd_class);
+}
+
+static const AVFilterPad sendcmd_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .start_frame      = process_frame,
+        .end_frame        = ff_null_end_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad sendcmd_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_sendcmd = {
     .name      = "sendcmd",
     .description = NULL_IF_CONFIG_SMALL("Send commands to filters."),
 
-    .init = init,
+    .init = sendcmd_init,
     .uninit = uninit,
     .priv_size = sizeof(SendCmdContext),
-
-    .inputs = (const AVFilterPad[]) {
-        {
-            .name             = "default",
-            .type             = AVMEDIA_TYPE_VIDEO,
-            .get_video_buffer = ff_null_get_video_buffer,
-            .start_frame      = process_frame,
-            .end_frame        = ff_null_end_frame,
-        },
-        { .name = NULL }
-    },
-    .outputs = (const AVFilterPad[]) {
-        {
-            .name             = "default",
-            .type             = AVMEDIA_TYPE_VIDEO,
-        },
-        { .name = NULL }
-    },
+    .inputs    = sendcmd_inputs,
+    .outputs   = sendcmd_outputs,
+    .priv_class = &sendcmd_class,
 };
 
 #endif
 
 #if CONFIG_ASENDCMD_FILTER
 
+#define asendcmd_options options
+AVFILTER_DEFINE_CLASS(asendcmd);
+
+static av_cold int asendcmd_init(AVFilterContext *ctx, const char *args)
+{
+    return init(ctx, args, &asendcmd_class);
+}
+
+static const AVFilterPad asendcmd_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_AUDIO,
+        .get_audio_buffer = ff_null_get_audio_buffer,
+        .filter_frame     = process_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad asendcmd_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_AUDIO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_asendcmd = {
     .name      = "asendcmd",
     .description = NULL_IF_CONFIG_SMALL("Send commands to filters."),
 
-    .init = init,
+    .init = asendcmd_init,
     .uninit = uninit,
     .priv_size = sizeof(SendCmdContext),
-
-    .inputs = (const AVFilterPad[]) {
-        {
-            .name             = "default",
-            .type             = AVMEDIA_TYPE_AUDIO,
-            .get_audio_buffer = ff_null_get_audio_buffer,
-            .filter_samples   = process_frame,
-        },
-        { .name = NULL }
-    },
-    .outputs = (const AVFilterPad[]) {
-        {
-            .name             = "default",
-            .type             = AVMEDIA_TYPE_AUDIO,
-        },
-        { .name = NULL }
-    },
+    .inputs    = asendcmd_inputs,
+    .outputs   = asendcmd_outputs,
+    .priv_class = &asendcmd_class,
 };
 
 #endif
diff --git a/libavfilter/f_setpts.c b/libavfilter/f_setpts.c
index 023dc1e..e5636e2 100644
--- a/libavfilter/f_setpts.c
+++ b/libavfilter/f_setpts.c
@@ -123,40 +123,37 @@
 #define TS2D(ts) ((ts) == AV_NOPTS_VALUE ? NAN : (double)(ts))
 #define TS2T(ts, tb) ((ts) == AV_NOPTS_VALUE ? NAN : (double)(ts)*av_q2d(tb))
 
-static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *frame)
 {
     SetPTSContext *setpts = inlink->dst->priv;
+    int64_t in_pts = frame->pts;
     double d;
-    AVFilterBufferRef *outpicref = avfilter_ref_buffer(inpicref, ~0);
-
-    if (!outpicref)
-        return AVERROR(ENOMEM);
 
     if (isnan(setpts->var_values[VAR_STARTPTS])) {
-        setpts->var_values[VAR_STARTPTS] = TS2D(inpicref->pts);
-        setpts->var_values[VAR_STARTT  ] = TS2T(inpicref->pts, inlink->time_base);
+        setpts->var_values[VAR_STARTPTS] = TS2D(frame->pts);
+        setpts->var_values[VAR_STARTT  ] = TS2T(frame->pts, inlink->time_base);
     }
-    setpts->var_values[VAR_PTS       ] = TS2D(inpicref->pts);
-    setpts->var_values[VAR_T         ] = TS2T(inpicref->pts, inlink->time_base);
-    setpts->var_values[VAR_POS       ] = inpicref->pos == -1 ? NAN : inpicref->pos;
+    setpts->var_values[VAR_PTS       ] = TS2D(frame->pts);
+    setpts->var_values[VAR_T         ] = TS2T(frame->pts, inlink->time_base);
+    setpts->var_values[VAR_POS       ] = frame->pos == -1 ? NAN : frame->pos;
 
     switch (inlink->type) {
     case AVMEDIA_TYPE_VIDEO:
-        setpts->var_values[VAR_INTERLACED] = inpicref->video->interlaced;
+        setpts->var_values[VAR_INTERLACED] = frame->video->interlaced;
         break;
 
     case AVMEDIA_TYPE_AUDIO:
-        setpts->var_values[VAR_NB_SAMPLES] = inpicref->audio->nb_samples;
+        setpts->var_values[VAR_NB_SAMPLES] = frame->audio->nb_samples;
         break;
     }
 
     d = av_expr_eval(setpts->expr, setpts->var_values, NULL);
-    outpicref->pts = D2TS(d);
+    frame->pts = D2TS(d);
 
-    setpts->var_values[VAR_PREV_INPTS ] = TS2D(inpicref ->pts);
-    setpts->var_values[VAR_PREV_INT   ] = TS2T(inpicref ->pts, inlink->time_base);
-    setpts->var_values[VAR_PREV_OUTPTS] = TS2D(outpicref->pts);
-    setpts->var_values[VAR_PREV_OUTT]   = TS2T(outpicref->pts, inlink->time_base);
+    setpts->var_values[VAR_PREV_INPTS ] = TS2D(in_pts);
+    setpts->var_values[VAR_PREV_INT   ] = TS2T(in_pts, inlink->time_base);
+    setpts->var_values[VAR_PREV_OUTPTS] = TS2D(frame->pts);
+    setpts->var_values[VAR_PREV_OUTT]   = TS2T(frame->pts, inlink->time_base);
 
     av_dlog(inlink->dst,
             "n:%"PRId64" interlaced:%d nb_samples:%d nb_consumed_samples:%d "
@@ -173,10 +170,9 @@
 
     setpts->var_values[VAR_N] += 1.0;
     if (setpts->type == AVMEDIA_TYPE_AUDIO) {
-        setpts->var_values[VAR_NB_CONSUMED_SAMPLES] += inpicref->audio->nb_samples;
-        return ff_filter_samples(inlink->dst->outputs[0], outpicref);
-    } else
-        return ff_start_frame   (inlink->dst->outputs[0], outpicref);
+        setpts->var_values[VAR_NB_CONSUMED_SAMPLES] += frame->audio->nb_samples;
+    }
+    return ff_filter_frame(inlink->dst->outputs[0], frame);
 }
 
 static av_cold void uninit(AVFilterContext *ctx)
@@ -187,35 +183,56 @@
 }
 
 #if CONFIG_ASETPTS_FILTER
+static const AVFilterPad avfilter_af_asetpts_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_AUDIO,
+        .get_audio_buffer = ff_null_get_audio_buffer,
+        .config_props     = config_input,
+        .filter_frame     = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_af_asetpts_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_AUDIO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_asetpts = {
     .name      = "asetpts",
     .description = NULL_IF_CONFIG_SMALL("Set PTS for the output audio frame."),
     .init      = init,
     .uninit    = uninit,
-
     .priv_size = sizeof(SetPTSContext),
-
-    .inputs = (const AVFilterPad[]) {
-        {
-            .name             = "default",
-            .type             = AVMEDIA_TYPE_AUDIO,
-            .get_audio_buffer = ff_null_get_audio_buffer,
-            .config_props     = config_input,
-            .filter_samples   = filter_frame,
-        },
-        { .name = NULL }
-    },
-    .outputs = (const AVFilterPad[]) {
-        {
-            .name             = "default",
-            .type             = AVMEDIA_TYPE_AUDIO,
-        },
-        { .name = NULL }
-    },
+    .inputs    = avfilter_af_asetpts_inputs,
+    .outputs   = avfilter_af_asetpts_outputs,
 };
 #endif /* CONFIG_ASETPTS_FILTER */
 
 #if CONFIG_SETPTS_FILTER
+static const AVFilterPad avfilter_vf_setpts_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .config_props     = config_input,
+        .filter_frame     = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_setpts_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_setpts = {
     .name      = "setpts",
     .description = NULL_IF_CONFIG_SMALL("Set PTS for the output video frame."),
@@ -224,14 +241,7 @@
 
     .priv_size = sizeof(SetPTSContext),
 
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .get_video_buffer = ff_null_get_video_buffer,
-                                          .config_props     = config_input,
-                                          .start_frame      = filter_frame, },
-                                        { .name = NULL }},
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_setpts_inputs,
+    .outputs   = avfilter_vf_setpts_outputs,
 };
 #endif /* CONFIG_SETPTS_FILTER */
diff --git a/libavfilter/f_settb.c b/libavfilter/f_settb.c
index e6c16aa..99ea7a7 100644
--- a/libavfilter/f_settb.c
+++ b/libavfilter/f_settb.c
@@ -103,40 +103,42 @@
     return 0;
 }
 
-static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *frame)
 {
     AVFilterContext *ctx = inlink->dst;
     AVFilterLink *outlink = ctx->outputs[0];
 
     if (av_cmp_q(inlink->time_base, outlink->time_base)) {
-        int64_t orig_pts = picref->pts;
-        picref->pts = av_rescale_q(picref->pts, inlink->time_base, outlink->time_base);
+        int64_t orig_pts = frame->pts;
+        frame->pts = av_rescale_q(frame->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, orig_pts,
-               outlink->time_base.num, outlink->time_base.den, picref->pts);
-    }
-    inlink->cur_buf = NULL;
-
-    return ff_start_frame(outlink, picref);
-}
-
-static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *samplesref)
-{
-    AVFilterContext *ctx = inlink->dst;
-    AVFilterLink *outlink = ctx->outputs[0];
-
-    if (av_cmp_q(inlink->time_base, outlink->time_base)) {
-        int64_t orig_pts = samplesref->pts;
-        samplesref->pts = av_rescale_q(samplesref->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, orig_pts,
-               outlink->time_base.num, outlink->time_base.den, samplesref->pts);
+               outlink->time_base.num, outlink->time_base.den, frame->pts);
     }
 
-    return ff_filter_samples(outlink, samplesref);
+    return ff_filter_frame(outlink, frame);
 }
 
 #if CONFIG_SETTB_FILTER
+static const AVFilterPad avfilter_vf_settb_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .filter_frame     = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_settb_outputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .config_props = config_output_props,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_settb = {
     .name      = "settb",
     .description = NULL_IF_CONFIG_SMALL("Set timebase for the video output link."),
@@ -144,43 +146,38 @@
 
     .priv_size = sizeof(SetTBContext),
 
-    .inputs    = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_VIDEO,
-          .get_video_buffer = ff_null_get_video_buffer,
-          .start_frame      = start_frame,
-          .end_frame        = ff_null_end_frame },
-        { .name = NULL }
-    },
-    .outputs   = (const AVFilterPad[]) {
-        { .name            = "default",
-          .type            = AVMEDIA_TYPE_VIDEO,
-          .config_props    = config_output_props, },
-        { .name = NULL}
-    },
+    .inputs    = avfilter_vf_settb_inputs,
+    .outputs   = avfilter_vf_settb_outputs,
 };
 #endif
 
 #if CONFIG_ASETTB_FILTER
+static const AVFilterPad avfilter_af_asettb_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_AUDIO,
+        .get_audio_buffer = ff_null_get_audio_buffer,
+        .filter_frame     = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_af_asettb_outputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_AUDIO,
+        .config_props = config_output_props,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_af_asettb = {
     .name      = "asettb",
     .description = NULL_IF_CONFIG_SMALL("Set timebase for the audio output link."),
     .init      = init,
 
     .priv_size = sizeof(SetTBContext),
-
-    .inputs    = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_AUDIO,
-          .get_audio_buffer = ff_null_get_audio_buffer,
-          .filter_samples   = filter_samples, },
-        { .name = NULL }
-    },
-    .outputs   = (const AVFilterPad[]) {
-        { .name            = "default",
-          .type            = AVMEDIA_TYPE_AUDIO,
-          .config_props    = config_output_props, },
-        { .name = NULL}
-    },
+    .inputs    = avfilter_af_asettb_inputs,
+    .outputs   = avfilter_af_asettb_outputs,
 };
 #endif
diff --git a/libavfilter/fifo.c b/libavfilter/fifo.c
index 8c978cc..9597fb3 100644
--- a/libavfilter/fifo.c
+++ b/libavfilter/fifo.c
@@ -24,7 +24,7 @@
  */
 
 #include "libavutil/avassert.h"
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
 #include "libavutil/mathematics.h"
 #include "libavutil/samplefmt.h"
@@ -77,7 +77,6 @@
 {
     FifoContext *fifo = inlink->dst->priv;
 
-    inlink->cur_buf = NULL;
     fifo->last->next = av_mallocz(sizeof(Buf));
     if (!fifo->last->next) {
         avfilter_unref_buffer(buf);
@@ -99,16 +98,6 @@
     s->root.next = tmp;
 }
 
-static int end_frame(AVFilterLink *inlink)
-{
-    return 0;
-}
-
-static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
-{
-    return 0;
-}
-
 /**
  * Move data pointers and pts offset samples forward.
  */
@@ -228,7 +217,7 @@
         buf_out = s->buf_out;
         s->buf_out = NULL;
     }
-    return ff_filter_samples(link, buf_out);
+    return ff_filter_frame(link, buf_out);
 }
 
 static int request_frame(AVFilterLink *outlink)
@@ -239,34 +228,39 @@
     if (!fifo->root.next) {
         if ((ret = ff_request_frame(outlink->src->inputs[0])) < 0)
             return ret;
+        av_assert0(fifo->root.next);
     }
 
-    /* by doing this, we give ownership of the reference to the next filter,
-     * so we don't have to worry about dereferencing it ourselves. */
-    switch (outlink->type) {
-    case AVMEDIA_TYPE_VIDEO:
-        if ((ret = ff_start_frame(outlink, fifo->root.next->buf)) < 0 ||
-            (ret = ff_draw_slice(outlink, 0, outlink->h, 1)) < 0 ||
-            (ret = ff_end_frame(outlink)) < 0)
-            return ret;
-
+    if (outlink->request_samples) {
+        return return_audio_frame(outlink->src);
+    } else {
+        ret = ff_filter_frame(outlink, fifo->root.next->buf);
         queue_pop(fifo);
-        break;
-    case AVMEDIA_TYPE_AUDIO:
-        if (outlink->request_samples) {
-            return return_audio_frame(outlink->src);
-        } else {
-            ret = ff_filter_samples(outlink, fifo->root.next->buf);
-            queue_pop(fifo);
-        }
-        break;
-    default:
-        return AVERROR(EINVAL);
     }
 
     return ret;
 }
 
+static const AVFilterPad avfilter_vf_fifo_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .filter_frame     = add_to_queue,
+        .min_perms        = AV_PERM_PRESERVE,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_fifo_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_fifo = {
     .name      = "fifo",
     .description = NULL_IF_CONFIG_SMALL("Buffer input images and send them when they are requested."),
@@ -276,18 +270,28 @@
 
     .priv_size = sizeof(FifoContext),
 
-    .inputs    = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_VIDEO,
-                                          .get_video_buffer= ff_null_get_video_buffer,
-                                          .start_frame     = add_to_queue,
-                                          .draw_slice      = draw_slice,
-                                          .end_frame       = end_frame,
-                                          .min_perms       = AV_PERM_PRESERVE, },
-                                        { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_VIDEO,
-                                          .request_frame   = request_frame, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_fifo_inputs,
+    .outputs   = avfilter_vf_fifo_outputs,
+};
+
+static const AVFilterPad avfilter_af_afifo_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_AUDIO,
+        .get_audio_buffer = ff_null_get_audio_buffer,
+        .filter_frame     = add_to_queue,
+        .min_perms        = AV_PERM_PRESERVE,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_af_afifo_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_AUDIO,
+        .request_frame = request_frame,
+    },
+    { NULL }
 };
 
 AVFilter avfilter_af_afifo = {
@@ -299,14 +303,6 @@
 
     .priv_size = sizeof(FifoContext),
 
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_AUDIO,
-                                          .get_audio_buffer = ff_null_get_audio_buffer,
-                                          .filter_samples   = add_to_queue,
-                                          .min_perms        = AV_PERM_PRESERVE, },
-                                        { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_AUDIO,
-                                          .request_frame    = request_frame, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_af_afifo_inputs,
+    .outputs   = avfilter_af_afifo_outputs,
 };
diff --git a/libavfilter/formats.c b/libavfilter/formats.c
index 735f21b..ea9a184 100644
--- a/libavfilter/formats.c
+++ b/libavfilter/formats.c
@@ -19,11 +19,11 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
 #include "libavutil/eval.h"
 #include "libavutil/pixdesc.h"
 #include "libavutil/parseutils.h"
-#include "libavutil/audioconvert.h"
 #include "avfilter.h"
 #include "internal.h"
 #include "formats.h"
@@ -69,7 +69,7 @@
             for (j = 0; j < b->nb; j++)                                         \
                 if (a->fmts[i] == b->fmts[j]) {                                 \
                     if(k >= FFMIN(a->nb, b->nb)){                               \
-                        av_log(0, AV_LOG_ERROR, "Duplicate formats in avfilter_merge_formats() detected\n"); \
+                        av_log(NULL, AV_LOG_ERROR, "Duplicate formats in avfilter_merge_formats() detected\n"); \
                         av_free(ret->fmts);                                     \
                         av_free(ret);                                           \
                         return NULL;                                            \
@@ -265,13 +265,15 @@
 {
     AVFilterFormats *ret = NULL;
     int fmt;
-    int num_formats = type == AVMEDIA_TYPE_VIDEO ? PIX_FMT_NB    :
+    int num_formats = type == AVMEDIA_TYPE_VIDEO ? AV_PIX_FMT_NB    :
                       type == AVMEDIA_TYPE_AUDIO ? AV_SAMPLE_FMT_NB : 0;
 
-    for (fmt = 0; fmt < num_formats; fmt++)
+    for (fmt = 0; fmt < num_formats; fmt++) {
+        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(fmt);
         if ((type != AVMEDIA_TYPE_VIDEO) ||
-            (type == AVMEDIA_TYPE_VIDEO && !(av_pix_fmt_descriptors[fmt].flags & PIX_FMT_HWACCEL)))
+            (type == AVMEDIA_TYPE_VIDEO && !(desc->flags & PIX_FMT_HWACCEL)))
             ff_add_format(&ret, fmt);
+    }
 
     return ret;
 }
@@ -458,13 +460,13 @@
 
 /* internal functions for parsing audio format arguments */
 
-int ff_parse_pixel_format(enum PixelFormat *ret, const char *arg, void *log_ctx)
+int ff_parse_pixel_format(enum AVPixelFormat *ret, const char *arg, void *log_ctx)
 {
     char *tail;
     int pix_fmt = av_get_pix_fmt(arg);
-    if (pix_fmt == PIX_FMT_NONE) {
+    if (pix_fmt == AV_PIX_FMT_NONE) {
         pix_fmt = strtol(arg, &tail, 0);
-        if (*tail || (unsigned)pix_fmt >= PIX_FMT_NB) {
+        if (*tail || (unsigned)pix_fmt >= AV_PIX_FMT_NB) {
             av_log(log_ctx, AV_LOG_ERROR, "Invalid pixel format '%s'\n", arg);
             return AVERROR(EINVAL);
         }
diff --git a/libavfilter/gradfun.h b/libavfilter/gradfun.h
index 3ceb133..939b129 100644
--- a/libavfilter/gradfun.h
+++ b/libavfilter/gradfun.h
@@ -25,7 +25,7 @@
 #include "avfilter.h"
 
 /// Holds instance-specific information for gradfun.
-typedef struct {
+typedef struct GradFunContext {
     int thresh;    ///< threshold for gradient algorithm
     int radius;    ///< blur radius
     int chroma_w;  ///< width of the chroma planes
diff --git a/libavfilter/graphdump.c b/libavfilter/graphdump.c
index c9d0fb0..45f64c0 100644
--- a/libavfilter/graphdump.c
+++ b/libavfilter/graphdump.c
@@ -21,7 +21,7 @@
 
 #include <string.h>
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/bprint.h"
 #include "libavutil/pixdesc.h"
 #include "avfilter.h"
diff --git a/libavfilter/graphparser.c b/libavfilter/graphparser.c
index c34651f..0ce823a 100644
--- a/libavfilter/graphparser.c
+++ b/libavfilter/graphparser.c
@@ -123,7 +123,8 @@
         return ret;
     }
 
-    if (!strcmp(filt_name, "scale") && args && !strstr(args, "flags")) {
+    if (!strcmp(filt_name, "scale") && args && !strstr(args, "flags")
+        && ctx->scale_sws_opts) {
         snprintf(tmp_args, sizeof(tmp_args), "%s:%s",
                  args, ctx->scale_sws_opts);
         args = tmp_args;
@@ -238,10 +239,11 @@
             return AVERROR(ENOMEM);
 
         if (p->filter_ctx) {
-            if ((ret = link_filter(p->filter_ctx, p->pad_idx, filt_ctx, pad, log_ctx)) < 0)
-                return ret;
+            ret = link_filter(p->filter_ctx, p->pad_idx, filt_ctx, pad, log_ctx);
             av_free(p->name);
             av_free(p);
+            if (ret < 0)
+                return ret;
         } else {
             p->filter_ctx = filt_ctx;
             p->pad_idx = pad;
@@ -289,8 +291,10 @@
             av_free(name);
         } else {
             /* Not in the list, so add it as an input */
-            if (!(match = av_mallocz(sizeof(AVFilterInOut))))
+            if (!(match = av_mallocz(sizeof(AVFilterInOut)))) {
+                av_free(name);
                 return AVERROR(ENOMEM);
+            }
             match->name    = name;
             match->pad_idx = pad;
         }
@@ -318,24 +322,27 @@
         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 AVERROR(EINVAL);
 
+        if (!input) {
+            av_log(log_ctx, AV_LOG_ERROR,
+                   "No output pad can be associated to link label '%s'.\n", name);
+            av_free(name);
+            return AVERROR(EINVAL);
+        }
+        *curr_inputs = (*curr_inputs)->next;
+
         /* First check if the label is not in the open_inputs list */
         match = extract_inout(name, open_inputs);
 
         if (match) {
             if ((ret = link_filter(input->filter_ctx, input->pad_idx,
-                                   match->filter_ctx, match->pad_idx, log_ctx)) < 0)
+                                   match->filter_ctx, match->pad_idx, log_ctx)) < 0) {
+                av_free(name);
                 return ret;
+            }
             av_free(match->name);
             av_free(name);
             av_free(match);
@@ -519,6 +526,9 @@
     AVFilterInOut *open_inputs  = open_inputs_ptr  ? *open_inputs_ptr  : NULL;
     AVFilterInOut *open_outputs = open_outputs_ptr ? *open_outputs_ptr : NULL;
 
+    if ((ret = parse_sws_flags(&filters, graph)) < 0)
+        goto end;
+
     do {
         AVFilterContext *filter;
         const char *filterchain = filters;
diff --git a/libavfilter/internal.h b/libavfilter/internal.h
index e82f04d..d098156 100644
--- a/libavfilter/internal.h
+++ b/libavfilter/internal.h
@@ -101,7 +101,7 @@
 
     /**
      * Callback function to get a video buffer. If NULL, the filter system will
-     * use avfilter_default_get_video_buffer().
+     * use ff_default_get_video_buffer().
      *
      * Input video pads only.
      */
@@ -109,7 +109,7 @@
 
     /**
      * Callback function to get an audio buffer. If NULL, the filter system will
-     * use avfilter_default_get_audio_buffer().
+     * use ff_default_get_audio_buffer().
      *
      * Input audio pads only.
      */
@@ -138,16 +138,16 @@
     int (*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.
+     * Filtering callback. This is where a filter receives a frame with
+     * audio/video data and should do its processing.
      *
-     * Input audio pads only.
+     * Input pads only.
      *
      * @return >= 0 on success, a negative AVERROR on error. This function
      * must ensure that samplesref is properly unreferenced on error if it
      * hasn't been passed on to another filter.
      */
-    int (*filter_samples)(AVFilterLink *link, AVFilterBufferRef *samplesref);
+    int (*filter_frame)(AVFilterLink *link, AVFilterBufferRef *frame);
 
     /**
      * Frame poll callback. This returns the number of immediately available
@@ -223,7 +223,7 @@
  * @param log_ctx log context
  * @return 0 in case of success, a negative AVERROR code on error
  */
-int ff_parse_pixel_format(enum PixelFormat *ret, const char *arg, void *log_ctx);
+int ff_parse_pixel_format(enum AVPixelFormat *ret, const char *arg, void *log_ctx);
 
 /**
  * Parse a sample rate.
@@ -368,5 +368,17 @@
 int ff_buffersink_read_compat(AVFilterContext *ctx, AVFilterBufferRef **buf);
 int ff_buffersink_read_samples_compat(AVFilterContext *ctx, AVFilterBufferRef **pbuf,
                                       int nb_samples);
+/**
+ * Send a frame of data to the next filter.
+ *
+ * @param link   the output link over which the data is being sent
+ * @param frame a reference to the buffer of data being sent. The
+ *              receiving filter will free this reference when it no longer
+ *              needs it or pass it on to the next filter.
+ *
+ * @return >= 0 on success, a negative AVERROR on error. The receiving filter
+ * is responsible for unreferencing frame in case of error.
+ */
+int ff_filter_frame(AVFilterLink *link, AVFilterBufferRef *frame);
 
 #endif /* AVFILTER_INTERNAL_H */
diff --git a/libavfilter/lavfutils.c b/libavfilter/lavfutils.c
index 70f7e71..8b6b114 100644
--- a/libavfilter/lavfutils.c
+++ b/libavfilter/lavfutils.c
@@ -22,7 +22,7 @@
 #include "lavfutils.h"
 
 int ff_load_image(uint8_t *data[4], int linesize[4],
-                  int *w, int *h, enum PixelFormat *pix_fmt,
+                  int *w, int *h, enum AVPixelFormat *pix_fmt,
                   const char *filename, void *log_ctx)
 {
     AVInputFormat *iformat = NULL;
@@ -85,10 +85,8 @@
     av_image_copy(data, linesize, (const uint8_t **)frame->data, frame->linesize, *pix_fmt, *w, *h);
 
 end:
-    if (codec_ctx)
-        avcodec_close(codec_ctx);
-    if (format_ctx)
-        avformat_close_input(&format_ctx);
+    avcodec_close(codec_ctx);
+    avformat_close_input(&format_ctx);
     av_freep(&frame);
 
     if (ret < 0)
diff --git a/libavfilter/lavfutils.h b/libavfilter/lavfutils.h
index c0943e2..a310e83 100644
--- a/libavfilter/lavfutils.h
+++ b/libavfilter/lavfutils.h
@@ -37,7 +37,7 @@
  * @return 0 in case of success, a negative error code otherwise.
  */
 int ff_load_image(uint8_t *data[4], int linesize[4],
-                  int *w, int *h, enum PixelFormat *pix_fmt,
+                  int *w, int *h, enum AVPixelFormat *pix_fmt,
                   const char *filename, void *log_ctx);
 
 #endif  /* AVFILTER_LAVFUTILS_H */
diff --git a/libavfilter/libmpcodecs/vf_divtc.c b/libavfilter/libmpcodecs/vf_divtc.c
index 4c171d1..32064a5 100644
--- a/libavfilter/libmpcodecs/vf_divtc.c
+++ b/libavfilter/libmpcodecs/vf_divtc.c
@@ -413,7 +413,7 @@
       n++;
       }
 
-   if(!n)
+   if(n <= 15)
       {
       mp_msg(MSGT_VFILTER, MSGL_FATAL, "%s: Empty 2-pass log file.\n",
              vf_info_divtc.name);
diff --git a/libavfilter/libmpcodecs/vf_down3dright.c b/libavfilter/libmpcodecs/vf_down3dright.c
index 4dba19a..f1e1f49 100644
--- a/libavfilter/libmpcodecs/vf_down3dright.c
+++ b/libavfilter/libmpcodecs/vf_down3dright.c
@@ -103,7 +103,7 @@
         // hope we'll get DR buffer:
         dmpi=vf_get_image(vf->next, IMGFMT_YV12,
                           MP_IMGTYPE_TEMP, MP_IMGFLAG_ACCEPT_STRIDE |
-                          (vf->priv->scaleh == 1) ? MP_IMGFLAG_READABLE : 0,
+                          ((vf->priv->scaleh == 1) ? MP_IMGFLAG_READABLE : 0),
                           mpi->w * vf->priv->scalew,
                           mpi->h / vf->priv->scaleh - vf->priv->skipline);
 
diff --git a/libavfilter/libmpcodecs/vf_field.c b/libavfilter/libmpcodecs/vf_field.c
deleted file mode 100644
index fcf24be..0000000
--- a/libavfilter/libmpcodecs/vf_field.c
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * This file is part of MPlayer.
- *
- * MPlayer 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.
- *
- * MPlayer is distributed in the hope that 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 MPlayer; 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 "config.h"
-#include "mp_msg.h"
-
-#include "mp_image.h"
-#include "vf.h"
-
-struct vf_priv_s {
-    int field;
-};
-
-//===========================================================================//
-
-static int config(struct vf_instance *vf,
-        int width, int height, int d_width, int d_height,
-        unsigned int flags, unsigned int outfmt){
-    return vf_next_config(vf,width,height/2,d_width,d_height,flags,outfmt);
-}
-
-static int put_image(struct vf_instance *vf, mp_image_t *mpi, double pts){
-    vf->dmpi=vf_get_image(vf->next,mpi->imgfmt,
-        MP_IMGTYPE_EXPORT, MP_IMGFLAG_ACCEPT_STRIDE,
-        mpi->width, mpi->height/2);
-
-    // set up mpi as a double-stride image of dmpi:
-    vf->dmpi->planes[0]=mpi->planes[0]+mpi->stride[0]*vf->priv->field;
-    vf->dmpi->stride[0]=2*mpi->stride[0];
-    if(vf->dmpi->flags&MP_IMGFLAG_PLANAR){
-        vf->dmpi->planes[1]=mpi->planes[1]+
-            mpi->stride[1]*vf->priv->field;
-        vf->dmpi->stride[1]=2*mpi->stride[1];
-        vf->dmpi->planes[2]=mpi->planes[2]+
-            mpi->stride[2]*vf->priv->field;
-        vf->dmpi->stride[2]=2*mpi->stride[2];
-    } else
-        vf->dmpi->planes[1]=mpi->planes[1]; // passthru bgr8 palette!!!
-
-    return vf_next_put_image(vf,vf->dmpi, pts);
-}
-
-//===========================================================================//
-
-static void uninit(struct vf_instance *vf)
-{
-        free(vf->priv);
-}
-
-static int vf_open(vf_instance_t *vf, char *args){
-    vf->config=config;
-    vf->put_image=put_image;
-    vf->uninit=uninit;
-    vf->default_reqs=VFCAP_ACCEPT_STRIDE;
-    vf->priv=calloc(1, sizeof(struct vf_priv_s));
-    if (args) sscanf(args, "%d", &vf->priv->field);
-    vf->priv->field &= 1;
-    return 1;
-}
-
-const vf_info_t vf_info_field = {
-    "extract single field",
-    "field",
-    "Rich Felker",
-    "",
-    vf_open,
-    NULL
-};
-
-//===========================================================================//
diff --git a/libavfilter/libmpcodecs/vf_fixpts.c b/libavfilter/libmpcodecs/vf_fixpts.c
deleted file mode 100644
index ae32b40..0000000
--- a/libavfilter/libmpcodecs/vf_fixpts.c
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * This file is part of MPlayer.
- *
- * MPlayer 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.
- *
- * MPlayer is distributed in the hope that 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 MPlayer; 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 "config.h"
-#include "mp_msg.h"
-#include "help_mp.h"
-
-#include "img_format.h"
-#include "mp_image.h"
-#include "vf.h"
-
-struct vf_priv_s {
-    double current;
-    double step;
-    int autostart;
-    int autostep;
-    unsigned have_step:1;
-    unsigned print:1;
-};
-
-static int put_image(vf_instance_t *vf, mp_image_t *src, double pts)
-{
-    struct vf_priv_s *p = vf->priv;
-
-    if (p->print) {
-        if (pts == MP_NOPTS_VALUE)
-            mp_msg(MSGT_VFILTER, MSGL_INFO, "PTS: undef\n");
-        else
-            mp_msg(MSGT_VFILTER, MSGL_INFO, "PTS: %f\n", pts);
-    }
-    if (pts != MP_NOPTS_VALUE && p->autostart != 0) {
-        p->current = pts;
-        if (p->autostart > 0)
-            p->autostart--;
-    } else if (pts != MP_NOPTS_VALUE && p->autostep > 0) {
-        p->step = pts - p->current;
-        p->current = pts;
-        p->autostep--;
-        p->have_step = 1;
-    } else if (p->have_step) {
-        p->current += p->step;
-        pts = p->current;
-    } else {
-        pts = MP_NOPTS_VALUE;
-    }
-    return vf_next_put_image(vf, src, pts);
-}
-
-static void uninit(vf_instance_t *vf)
-{
-    free(vf->priv);
-}
-
-static int parse_args(struct vf_priv_s *p, const char *args)
-{
-    int pos;
-    double num, denom = 1;
-    int iarg;
-
-    while (*args != 0) {
-        pos = 0;
-        if (sscanf(args, "print%n", &pos) == 0 && pos > 0) {
-            p->print = 1;
-        } else if (sscanf(args, "fps=%lf%n/%lf%n", &num, &pos, &denom, &pos) >=
-                   1 && pos > 0) {
-            p->step = denom / num;
-            p->have_step = 1;
-        } else if (sscanf(args, "start=%lf%n", &num, &pos) >= 1 && pos > 0) {
-            p->current = num;
-        } else if (sscanf(args, "autostart=%d%n", &iarg, &pos) == 1 && pos > 0) {
-            p->autostart = iarg;
-        } else if (sscanf(args, "autofps=%d%n", &iarg, &pos) == 1 && pos > 0) {
-            p->autostep = iarg;
-        } else {
-            mp_msg(MSGT_VFILTER, MSGL_FATAL,
-                   "fixpts: unknown suboption: %s\n", args);
-            return 0;
-        }
-        args += pos;
-        if (*args == ':')
-            args++;
-    }
-    return 1;
-}
-
-static int open(vf_instance_t *vf, char *args)
-{
-    struct vf_priv_s *p;
-    struct vf_priv_s ptmp = {
-        .current = 0,
-        .step = 0,
-        .autostart = 0,
-        .autostep = 0,
-        .have_step = 0,
-        .print = 0,
-    };
-
-    if (!parse_args(&ptmp, args == NULL ? "" : args))
-        return 0;
-
-    vf->put_image = put_image;
-    vf->uninit = uninit;
-    vf->priv = p = malloc(sizeof(struct vf_priv_s));
-    *p = ptmp;
-    p->current = -p->step;
-
-    return 1;
-}
-
-const vf_info_t vf_info_fixpts = {
-    "Fix presentation timestamps",
-    "fixpts",
-    "Nicolas George",
-    "",
-    &open,
-    NULL
-};
diff --git a/libavfilter/libmpcodecs/vf_geq.c b/libavfilter/libmpcodecs/vf_geq.c
deleted file mode 100644
index 22f2938..0000000
--- a/libavfilter/libmpcodecs/vf_geq.c
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * Copyright (C) 2006 Michael Niedermayer <michaelni@gmx.at>
- *
- * This file is part of MPlayer.
- *
- * MPlayer 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.
- *
- * MPlayer is distributed in the hope that 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 MPlayer; 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 <inttypes.h>
-
-#include "config.h"
-
-#include "mp_msg.h"
-
-#include "img_format.h"
-#include "mp_image.h"
-#include "vf.h"
-
-#include "libavcodec/avcodec.h"
-#include "libavutil/eval.h"
-
-struct vf_priv_s {
-    AVExpr * e[3];
-    int framenum;
-    mp_image_t *mpi;
-};
-
-static int config(struct vf_instance *vf,
-        int width, int height, int d_width, int d_height,
-        unsigned int flags, unsigned int outfmt){
-    return vf_next_config(vf,width,height,d_width,d_height,flags,outfmt);
-}
-
-static inline double getpix(struct vf_instance *vf, double x, double y, int plane){
-    int xi, yi;
-    mp_image_t *mpi= vf->priv->mpi;
-    int stride= mpi->stride[plane];
-    uint8_t *src=  mpi->planes[plane];
-    xi=x= FFMIN(FFMAX(x, 0), (mpi->w >> (plane ? mpi->chroma_x_shift : 0))-1);
-    yi=y= FFMIN(FFMAX(y, 0), (mpi->h >> (plane ? mpi->chroma_y_shift : 0))-1);
-
-    x-=xi;
-    y-=yi;
-
-    return
-     (1-y)*((1-x)*src[xi +  yi    * stride] + x*src[xi + 1 +  yi    * stride])
-    +   y *((1-x)*src[xi + (yi+1) * stride] + x*src[xi + 1 + (yi+1) * stride]);
-}
-
-//FIXME cubic interpolate
-//FIXME keep the last few frames
-static double lum(void *vf, double x, double y){
-    return getpix(vf, x, y, 0);
-}
-
-static double cb(void *vf, double x, double y){
-    return getpix(vf, x, y, 1);
-}
-
-static double cr(void *vf, double x, double y){
-    return getpix(vf, x, y, 2);
-}
-
-static int put_image(struct vf_instance *vf, mp_image_t *mpi, double pts){
-    mp_image_t *dmpi;
-    int x,y, plane;
-
-    if(!(mpi->flags&MP_IMGFLAG_DIRECT)){
-        // no DR, so get a new image! hope we'll get DR buffer:
-        vf->dmpi=vf_get_image(vf->next,mpi->imgfmt, MP_IMGTYPE_TEMP,
-                              MP_IMGFLAG_ACCEPT_STRIDE|MP_IMGFLAG_PREFER_ALIGNED_STRIDE,
-                              mpi->w,mpi->h);
-    }
-
-    dmpi= vf->dmpi;
-    vf->priv->mpi= mpi;
-
-    vf_clone_mpi_attributes(dmpi, mpi);
-
-    for(plane=0; plane<3; plane++){
-        int w= mpi->w >> (plane ? mpi->chroma_x_shift : 0);
-        int h= mpi->h >> (plane ? mpi->chroma_y_shift : 0);
-        uint8_t *dst  = dmpi->planes[plane];
-        int dst_stride= dmpi->stride[plane];
-        double const_values[]={
-            M_PI,
-            M_E,
-            0,
-            0,
-            w,
-            h,
-            vf->priv->framenum,
-            w/(double)mpi->w,
-            h/(double)mpi->h,
-            0
-        };
-        if (!vf->priv->e[plane]) continue;
-        for(y=0; y<h; y++){
-            const_values[3]=y;
-            for(x=0; x<w; x++){
-                const_values[2]=x;
-                dst[x + y * dst_stride] = av_expr_eval(vf->priv->e[plane],
-                                                       const_values, vf);
-            }
-        }
-    }
-
-    vf->priv->framenum++;
-
-    return vf_next_put_image(vf,dmpi, pts);
-}
-
-static void uninit(struct vf_instance *vf){
-    av_free(vf->priv);
-    vf->priv=NULL;
-}
-
-//===========================================================================//
-static int vf_open(vf_instance_t *vf, char *args){
-    char eq[3][2000] = { { 0 }, { 0 }, { 0 } };
-    int plane, res;
-
-    vf->config=config;
-    vf->put_image=put_image;
-//    vf->get_image=get_image;
-    vf->uninit=uninit;
-    vf->priv=av_malloc(sizeof(struct vf_priv_s));
-    memset(vf->priv, 0, sizeof(struct vf_priv_s));
-
-    if (args) sscanf(args, "%1999[^:]:%1999[^:]:%1999[^:]", eq[0], eq[1], eq[2]);
-
-    if (!eq[1][0]) strncpy(eq[1], eq[0], sizeof(eq[0])-1);
-    if (!eq[2][0]) strncpy(eq[2], eq[1], sizeof(eq[0])-1);
-
-    for(plane=0; plane<3; plane++){
-        static const char *const_names[]={
-            "PI",
-            "E",
-            "X",
-            "Y",
-            "W",
-            "H",
-            "N",
-            "SW",
-            "SH",
-            NULL
-        };
-        static const char *func2_names[]={
-            "lum",
-            "cb",
-            "cr",
-            "p",
-            NULL
-        };
-        double (*func2[])(void *, double, double)={
-            lum,
-            cb,
-            cr,
-            plane==0 ? lum : (plane==1 ? cb : cr),
-            NULL
-        };
-        res = av_expr_parse(&vf->priv->e[plane], eq[plane], const_names, NULL, NULL, func2_names, func2, 0, NULL);
-
-        if (res < 0) {
-            mp_msg(MSGT_VFILTER, MSGL_ERR, "geq: error loading equation `%s'\n", eq[plane]);
-            return 0;
-        }
-    }
-
-    return 1;
-}
-
-const vf_info_t vf_info_geq = {
-    "generic equation filter",
-    "geq",
-    "Michael Niedermayer",
-    "",
-    vf_open,
-    NULL
-};
diff --git a/libavfilter/libmpcodecs/vf_hqdn3d.c b/libavfilter/libmpcodecs/vf_hqdn3d.c
deleted file mode 100644
index eba3439..0000000
--- a/libavfilter/libmpcodecs/vf_hqdn3d.c
+++ /dev/null
@@ -1,373 +0,0 @@
-/*
- * Copyright (C) 2003 Daniel Moreno <comac@comac.darktech.org>
- *
- * This file is part of MPlayer.
- *
- * MPlayer 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.
- *
- * MPlayer is distributed in the hope that 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 MPlayer; 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 <math.h>
-
-#include "mp_msg.h"
-#include "img_format.h"
-#include "mp_image.h"
-#include "vf.h"
-
-#define PARAM1_DEFAULT 4.0
-#define PARAM2_DEFAULT 3.0
-#define PARAM3_DEFAULT 6.0
-
-//===========================================================================//
-
-struct vf_priv_s {
-        int Coefs[4][512*16];
-        unsigned int *Line;
-        unsigned short *Frame[3];
-};
-
-
-/***************************************************************************/
-
-static void uninit(struct vf_instance *vf)
-{
-        free(vf->priv->Line);
-        free(vf->priv->Frame[0]);
-        free(vf->priv->Frame[1]);
-        free(vf->priv->Frame[2]);
-
-        vf->priv->Line     = NULL;
-        vf->priv->Frame[0] = NULL;
-        vf->priv->Frame[1] = NULL;
-        vf->priv->Frame[2] = NULL;
-}
-
-static int config(struct vf_instance *vf,
-        int width, int height, int d_width, int d_height,
-        unsigned int flags, unsigned int outfmt){
-
-        uninit(vf);
-        vf->priv->Line = malloc(width*sizeof(int));
-
-        return vf_next_config(vf,width,height,d_width,d_height,flags,outfmt);
-}
-
-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 *Frame,        // mpi->planes[x]
-                    unsigned char *FrameDest,    // dmpi->planes[x]
-                    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, Frame[X]<<16, Temporal);
-            FrameAnt[X] = ((PixelDst+0x1000007F)>>8);
-            FrameDest[X]= ((PixelDst+0x10007FFF)>>16);
-        }
-        Frame += sStride;
-        FrameDest += dStride;
-        FrameAnt += W;
-    }
-}
-
-static void deNoiseSpacial(
-                    unsigned char *Frame,        // mpi->planes[x]
-                    unsigned char *FrameDest,    // dmpi->planes[x]
-                    unsigned int *LineAnt,       // vf->priv->Line (width bytes)
-                    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,        // mpi->planes[x]
-                    unsigned char *FrameDest,    // dmpi->planes[x]
-                    unsigned int *LineAnt,      // vf->priv->Line (width bytes)
-                    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=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 int put_image(struct vf_instance *vf, mp_image_t *mpi, double pts){
-        int cw= mpi->w >> mpi->chroma_x_shift;
-        int ch= mpi->h >> mpi->chroma_y_shift;
-        int W = mpi->w, H = mpi->h;
-
-        mp_image_t *dmpi=vf_get_image(vf->next,mpi->imgfmt,
-                MP_IMGTYPE_TEMP, MP_IMGFLAG_ACCEPT_STRIDE,
-                mpi->w,mpi->h);
-
-        if(!dmpi) return 0;
-
-        deNoise(mpi->planes[0], dmpi->planes[0],
-                vf->priv->Line, &vf->priv->Frame[0], W, H,
-                mpi->stride[0], dmpi->stride[0],
-                vf->priv->Coefs[0],
-                vf->priv->Coefs[0],
-                vf->priv->Coefs[1]);
-        deNoise(mpi->planes[1], dmpi->planes[1],
-                vf->priv->Line, &vf->priv->Frame[1], cw, ch,
-                mpi->stride[1], dmpi->stride[1],
-                vf->priv->Coefs[2],
-                vf->priv->Coefs[2],
-                vf->priv->Coefs[3]);
-        deNoise(mpi->planes[2], dmpi->planes[2],
-                vf->priv->Line, &vf->priv->Frame[2], cw, ch,
-                mpi->stride[2], dmpi->stride[2],
-                vf->priv->Coefs[2],
-                vf->priv->Coefs[2],
-                vf->priv->Coefs[3]);
-
-        return vf_next_put_image(vf,dmpi, pts);
-}
-
-//===========================================================================//
-
-static int query_format(struct vf_instance *vf, unsigned int fmt){
-        switch(fmt)
-        {
-        case IMGFMT_YV12:
-        case IMGFMT_I420:
-        case IMGFMT_IYUV:
-        case IMGFMT_YVU9:
-        case IMGFMT_444P:
-        case IMGFMT_422P:
-        case IMGFMT_411P:
-                return vf_next_query_format(vf, fmt);
-        }
-        return 0;
-}
-
-
-#define ABS(A) ( (A) > 0 ? (A) : -(A) )
-
-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 - ABS(i) / (16*255.0);
-        C = pow(Simil, Gamma) * 65536.0 * (double)i / 16.0;
-        Ct[16*256+i] = (C<0) ? (C-0.5) : (C+0.5);
-    }
-
-    Ct[0] = (Dist25 != 0);
-}
-
-
-static int vf_open(vf_instance_t *vf, char *args){
-        double LumSpac, LumTmp, ChromSpac, ChromTmp;
-        double Param1, Param2, Param3, Param4;
-
-        vf->config=config;
-        vf->put_image=put_image;
-        vf->query_format=query_format;
-        vf->uninit=uninit;
-        vf->priv=malloc(sizeof(struct vf_priv_s));
-        memset(vf->priv, 0, sizeof(struct vf_priv_s));
-
-        if (args)
-        {
-            switch(sscanf(args, "%lf:%lf:%lf:%lf",
-                          &Param1, &Param2, &Param3, &Param4
-                         ))
-            {
-            case 0:
-                LumSpac = PARAM1_DEFAULT;
-                LumTmp = PARAM3_DEFAULT;
-
-                ChromSpac = PARAM2_DEFAULT;
-                ChromTmp = LumTmp * ChromSpac / LumSpac;
-                break;
-
-            case 1:
-                LumSpac = Param1;
-                LumTmp = PARAM3_DEFAULT * Param1 / PARAM1_DEFAULT;
-
-                ChromSpac = PARAM2_DEFAULT * Param1 / PARAM1_DEFAULT;
-                ChromTmp = LumTmp * ChromSpac / LumSpac;
-                break;
-
-            case 2:
-                LumSpac = Param1;
-                LumTmp = PARAM3_DEFAULT * Param1 / PARAM1_DEFAULT;
-
-                ChromSpac = Param2;
-                ChromTmp = LumTmp * ChromSpac / LumSpac;
-                break;
-
-            case 3:
-                LumSpac = Param1;
-                LumTmp = Param3;
-
-                ChromSpac = Param2;
-                ChromTmp = LumTmp * ChromSpac / LumSpac;
-                break;
-
-            case 4:
-                LumSpac = Param1;
-                LumTmp = Param3;
-
-                ChromSpac = Param2;
-                ChromTmp = Param4;
-                break;
-
-            default:
-                LumSpac = PARAM1_DEFAULT;
-                LumTmp = PARAM3_DEFAULT;
-
-                ChromSpac = PARAM2_DEFAULT;
-                ChromTmp = LumTmp * ChromSpac / LumSpac;
-            }
-        }
-        else
-        {
-            LumSpac = PARAM1_DEFAULT;
-            LumTmp = PARAM3_DEFAULT;
-
-            ChromSpac = PARAM2_DEFAULT;
-            ChromTmp = LumTmp * ChromSpac / LumSpac;
-        }
-
-        PrecalcCoefs(vf->priv->Coefs[0], LumSpac);
-        PrecalcCoefs(vf->priv->Coefs[1], LumTmp);
-        PrecalcCoefs(vf->priv->Coefs[2], ChromSpac);
-        PrecalcCoefs(vf->priv->Coefs[3], ChromTmp);
-
-        return 1;
-}
-
-const vf_info_t vf_info_hqdn3d = {
-    "High Quality 3D Denoiser",
-    "hqdn3d",
-    "Daniel Moreno & A'rpi",
-    "",
-    vf_open,
-    NULL
-};
-
-//===========================================================================//
diff --git a/libavfilter/libmpcodecs/vf_ilpack.c b/libavfilter/libmpcodecs/vf_ilpack.c
index db4a849..e98d70d 100644
--- a/libavfilter/libmpcodecs/vf_ilpack.c
+++ b/libavfilter/libmpcodecs/vf_ilpack.c
@@ -437,6 +437,7 @@
         mp_msg(MSGT_VFILTER, MSGL_WARN,
             "ilpack: unknown mode %d (fallback to linear)\n",
             vf->priv->mode);
+        /* Fallthrough */
     case 1:
         vf->priv->pack[0] = pack_li_0;
         vf->priv->pack[1] = pack_li_1;
diff --git a/libavfilter/libmpcodecs/vf_mcdeint.c b/libavfilter/libmpcodecs/vf_mcdeint.c
index 2679289..01a3cb3 100644
--- a/libavfilter/libmpcodecs/vf_mcdeint.c
+++ b/libavfilter/libmpcodecs/vf_mcdeint.c
@@ -202,7 +202,7 @@
             avctx_enc->time_base= (AVRational){1,25};  // meaningless
             avctx_enc->gop_size = 300;
             avctx_enc->max_b_frames= 0;
-            avctx_enc->pix_fmt = PIX_FMT_YUV420P;
+            avctx_enc->pix_fmt = AV_PIX_FMT_YUV420P;
             avctx_enc->flags = CODEC_FLAG_QSCALE | CODEC_FLAG_LOW_DELAY;
             avctx_enc->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
             avctx_enc->global_quality= 1;
diff --git a/libavfilter/libmpcodecs/vf_palette.c b/libavfilter/libmpcodecs/vf_palette.c
deleted file mode 100644
index 543b6c7..0000000
--- a/libavfilter/libmpcodecs/vf_palette.c
+++ /dev/null
@@ -1,236 +0,0 @@
-/*
- * This file is part of MPlayer.
- *
- * MPlayer 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.
- *
- * MPlayer is distributed in the hope that 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 MPlayer; 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 <inttypes.h>
-
-#include "config.h"
-#include "mp_msg.h"
-#include "help_mp.h"
-
-#include "img_format.h"
-#include "mp_image.h"
-#include "vf.h"
-#include "mpbswap.h"
-
-#include "libswscale/swscale.h"
-
-#include "libavutil/avstring.h"
-
-//===========================================================================//
-
-// commented out 16 and 15 bit output support, because the conversion
-// routines are incorrrect.  they assume the palette to be of the same
-// depth as the output, which is incorrect. --Joey
-
-static const unsigned int bgr_list[]={
-    IMGFMT_BGR32,
-    IMGFMT_BGR24,
-//    IMGFMT_BGR16,
-//    IMGFMT_BGR15,
-    0
-};
-static const unsigned int rgb_list[]={
-    IMGFMT_RGB32,
-    IMGFMT_RGB24,
-//    IMGFMT_RGB16,
-//    IMGFMT_RGB15,
-    0
-};
-
-/**
- * Palette is assumed to contain BGR16, see rgb32to16 to convert the palette.
- */
-static void palette8torgb16(const uint8_t *src, uint8_t *dst, long num_pixels, const uint8_t *palette)
-{
-    long i;
-    for (i=0; i<num_pixels; i++)
-        ((uint16_t *)dst)[i] = ((const uint16_t *)palette)[src[i]];
-}
-
-static void palette8tobgr16(const uint8_t *src, uint8_t *dst, long num_pixels, const uint8_t *palette)
-{
-    long i;
-    for (i=0; i<num_pixels; i++)
-        ((uint16_t *)dst)[i] = bswap_16(((const uint16_t *)palette)[src[i]]);
-}
-
-static unsigned int gray_pal[256];
-
-static unsigned int find_best(struct vf_instance *vf, unsigned int fmt){
-    unsigned int best=0;
-    int ret;
-    const unsigned int* p;
-    if(fmt==IMGFMT_BGR8) p=bgr_list;
-    else if(fmt==IMGFMT_RGB8) p=rgb_list;
-    else return 0;
-    while(*p){
-        ret=vf->next->query_format(vf->next,*p);
-        mp_msg(MSGT_VFILTER,MSGL_DBG2,"[%s] query(%s) -> %d\n",vf->info->name,vo_format_name(*p),ret&3);
-        if(ret&VFCAP_CSP_SUPPORTED_BY_HW){ best=*p; break;} // no conversion -> bingo!
-        if(ret&VFCAP_CSP_SUPPORTED && !best) best=*p; // best with conversion
-        ++p;
-    }
-    return best;
-}
-
-//===========================================================================//
-
-struct vf_priv_s {
-    unsigned int fmt;
-    int pal_msg;
-};
-
-static int config(struct vf_instance *vf,
-        int width, int height, int d_width, int d_height,
-        unsigned int flags, unsigned int outfmt){
-    if (!vf->priv->fmt)
-        vf->priv->fmt=find_best(vf,outfmt);
-    if(!vf->priv->fmt){
-        // no matching fmt, so force one...
-        if(outfmt==IMGFMT_RGB8) vf->priv->fmt=IMGFMT_RGB32;
-        else if(outfmt==IMGFMT_BGR8) vf->priv->fmt=IMGFMT_BGR32;
-        else return 0;
-    }
-    return vf_next_config(vf,width,height,d_width,d_height,flags,vf->priv->fmt);
-}
-
-static int put_image(struct vf_instance *vf, mp_image_t *mpi, double pts){
-    mp_image_t *dmpi;
-    uint8_t *old_palette = mpi->planes[1];
-
-    // hope we'll get DR buffer:
-    dmpi=vf_get_image(vf->next,vf->priv->fmt,
-        MP_IMGTYPE_TEMP, MP_IMGFLAG_ACCEPT_STRIDE,
-        mpi->w, mpi->h);
-
-    if (!mpi->planes[1])
-    {
-        if(!vf->priv->pal_msg){
-            mp_msg(MSGT_VFILTER,MSGL_V,"[%s] no palette given, assuming builtin grayscale one\n",vf->info->name);
-            vf->priv->pal_msg=1;
-        }
-        mpi->planes[1] = (unsigned char*)gray_pal;
-    }
-
-    if(mpi->w==mpi->stride[0] && dmpi->w*(dmpi->bpp>>3)==dmpi->stride[0]){
-        // no stride conversion needed
-        switch(IMGFMT_RGB_DEPTH(dmpi->imgfmt)){
-        case 15:
-        case 16:
-            if (IMGFMT_IS_BGR(dmpi->imgfmt))
-                palette8tobgr16(mpi->planes[0],dmpi->planes[0],mpi->h*mpi->w,mpi->planes[1]);
-            else
-                palette8torgb16(mpi->planes[0],dmpi->planes[0],mpi->h*mpi->w,mpi->planes[1]);
-            break;
-        case 24:
-            if (IMGFMT_IS_BGR(dmpi->imgfmt))
-                sws_convertPalette8ToPacked24(mpi->planes[0],dmpi->planes[0],mpi->h*mpi->w,mpi->planes[1]);
-            else
-                sws_convertPalette8ToPacked24(mpi->planes[0],dmpi->planes[0],mpi->h*mpi->w,mpi->planes[1]);
-            break;
-        case 32:
-            if (IMGFMT_IS_BGR(dmpi->imgfmt))
-                sws_convertPalette8ToPacked32(mpi->planes[0],dmpi->planes[0],mpi->h*mpi->w,mpi->planes[1]);
-            else
-                sws_convertPalette8ToPacked32(mpi->planes[0],dmpi->planes[0],mpi->h*mpi->w,mpi->planes[1]);
-            break;
-        }
-    } else {
-        int y;
-        for(y=0;y<mpi->h;y++){
-            unsigned char* src=mpi->planes[0]+y*mpi->stride[0];
-            unsigned char* dst=dmpi->planes[0]+y*dmpi->stride[0];
-            switch(IMGFMT_RGB_DEPTH(dmpi->imgfmt)){
-            case 15:
-            case 16:
-                if (IMGFMT_IS_BGR(dmpi->imgfmt))
-                    palette8tobgr16(src,dst,mpi->w,mpi->planes[1]);
-                else
-                    palette8torgb16(src,dst,mpi->w,mpi->planes[1]);
-                break;
-            case 24:
-                if (IMGFMT_IS_BGR(dmpi->imgfmt))
-                    sws_convertPalette8ToPacked24(src,dst,mpi->w,mpi->planes[1]);
-                else
-                    sws_convertPalette8ToPacked24(src,dst,mpi->w,mpi->planes[1]);
-                break;
-            case 32:
-                if (IMGFMT_IS_BGR(dmpi->imgfmt))
-                    sws_convertPalette8ToPacked32(src,dst,mpi->w,mpi->planes[1]);
-                else
-                    sws_convertPalette8ToPacked32(src,dst,mpi->w,mpi->planes[1]);
-                break;
-            }
-        }
-    }
-    mpi->planes[1] = old_palette;
-
-    return vf_next_put_image(vf,dmpi, pts);
-}
-
-//===========================================================================//
-
-static int query_format(struct vf_instance *vf, unsigned int fmt){
-    int best=find_best(vf,fmt);
-    if(!best) return 0; // no match
-    return vf->next->query_format(vf->next,best);
-}
-
-static void uninit(vf_instance_t *vf) {
-  free(vf->priv);
-}
-
-static int vf_open(vf_instance_t *vf, char *args){
-    unsigned int i;
-    vf->config=config;
-    vf->uninit=uninit;
-    vf->put_image=put_image;
-    vf->query_format=query_format;
-    vf->priv=malloc(sizeof(struct vf_priv_s));
-    memset(vf->priv, 0, sizeof(struct vf_priv_s));
-    for(i=0;i<256;i++) gray_pal[i]=0x01010101*i;
-    if (args)
-    {
-        if (!av_strcasecmp(args,"rgb15")) vf->priv->fmt=IMGFMT_RGB15; else
-        if (!av_strcasecmp(args,"rgb16")) vf->priv->fmt=IMGFMT_RGB16; else
-        if (!av_strcasecmp(args,"rgb24")) vf->priv->fmt=IMGFMT_RGB24; else
-        if (!av_strcasecmp(args,"rgb32")) vf->priv->fmt=IMGFMT_RGB32; else
-        if (!av_strcasecmp(args,"bgr15")) vf->priv->fmt=IMGFMT_BGR15; else
-        if (!av_strcasecmp(args,"bgr16")) vf->priv->fmt=IMGFMT_BGR16; else
-        if (!av_strcasecmp(args,"bgr24")) vf->priv->fmt=IMGFMT_BGR24; else
-        if (!av_strcasecmp(args,"bgr32")) vf->priv->fmt=IMGFMT_BGR32; else
-        {
-            mp_msg(MSGT_VFILTER, MSGL_WARN, MSGTR_MPCODECS_UnknownFormatName, args);
-            return 0;
-        }
-    }
-    return 1;
-}
-
-const vf_info_t vf_info_palette = {
-    "8bpp indexed (using palette) -> BGR 15/16/24/32 conversion",
-    "palette",
-    "A'rpi & Alex",
-    "",
-    vf_open,
-    NULL
-};
-
-//===========================================================================//
diff --git a/libavfilter/libmpcodecs/vf_phase.c b/libavfilter/libmpcodecs/vf_phase.c
index 7dd642e..101290d 100644
--- a/libavfilter/libmpcodecs/vf_phase.c
+++ b/libavfilter/libmpcodecs/vf_phase.c
@@ -242,6 +242,8 @@
 
 static void uninit(struct vf_instance *vf)
    {
+   if (!vf->priv)
+       return;
    free(vf->priv->buf[0]);
    free(vf->priv->buf[1]);
    free(vf->priv->buf[2]);
diff --git a/libavfilter/libmpcodecs/vf_pp.c b/libavfilter/libmpcodecs/vf_pp.c
index 78cce1f..713056f 100644
--- a/libavfilter/libmpcodecs/vf_pp.c
+++ b/libavfilter/libmpcodecs/vf_pp.c
@@ -54,10 +54,7 @@
 static int config(struct vf_instance *vf,
         int width, int height, int d_width, int d_height,
         unsigned int voflags, unsigned int outfmt){
-    int flags=
-          (gCpuCaps.hasMMX   ? PP_CPU_CAPS_MMX   : 0)
-        | (gCpuCaps.hasMMX2  ? PP_CPU_CAPS_MMX2  : 0)
-        | (gCpuCaps.has3DNow ? PP_CPU_CAPS_3DNOW : 0);
+    int flags= PP_CPU_CAPS_AUTO;
 
     switch(outfmt){
     case IMGFMT_444P: flags|= PP_FORMAT_444; break;
diff --git a/libavfilter/libmpcodecs/vf_pullup.c b/libavfilter/libmpcodecs/vf_pullup.c
index 02a2031..ba4ae02 100644
--- a/libavfilter/libmpcodecs/vf_pullup.c
+++ b/libavfilter/libmpcodecs/vf_pullup.c
@@ -293,7 +293,6 @@
     vf->priv = p = calloc(1, sizeof(struct vf_priv_s));
     p->ctx = c = pullup_alloc_context();
     p->fakecount = 1;
-    c->verbose = 1;
     c->junk_left = c->junk_right = 1;
     c->junk_top = c->junk_bottom = 4;
     c->strict_breaks = 0;
diff --git a/libavfilter/libmpcodecs/vf_rectangle.c b/libavfilter/libmpcodecs/vf_rectangle.c
deleted file mode 100644
index 21bc209..0000000
--- a/libavfilter/libmpcodecs/vf_rectangle.c
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * This file is part of MPlayer.
- *
- * MPlayer 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.
- *
- * MPlayer is distributed in the hope that 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 MPlayer; 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 "mp_image.h"
-#include "mp_msg.h"
-#include "vf.h"
-
-#include "libvo/fastmemcpy.h"
-#include "libavutil/common.h"
-
-struct vf_priv_s {
-    int x, y, w, h;
-};
-
-static int
-config(struct vf_instance *vf,
-       int width, int height, int d_width, int d_height,
-       unsigned int flags, unsigned int outfmt)
-{
-    if (vf->priv->w < 0 || width < vf->priv->w)
-        vf->priv->w = width;
-    if (vf->priv->h < 0 || height < vf->priv->h)
-        vf->priv->h = height;
-    if (vf->priv->x < 0)
-        vf->priv->x = (width - vf->priv->w) / 2;
-    if (vf->priv->y < 0)
-        vf->priv->y = (height - vf->priv->h) / 2;
-    if (vf->priv->w + vf->priv->x > width
-        || vf->priv->h + vf->priv->y > height) {
-        mp_msg(MSGT_VFILTER,MSGL_WARN,"rectangle: bad position/width/height - rectangle area is out of the original!\n");
-        return 0;
-    }
-    return vf_next_config(vf, width, height, d_width, d_height, flags, outfmt);
-}
-
-static int
-control(struct vf_instance *vf, int request, void *data)
-{
-    const int *const tmp = data;
-    switch(request){
-    case VFCTRL_CHANGE_RECTANGLE:
-        switch (tmp[0]){
-        case 0:
-            vf->priv->w += tmp[1];
-            return 1;
-            break;
-        case 1:
-            vf->priv->h += tmp[1];
-            return 1;
-            break;
-        case 2:
-            vf->priv->x += tmp[1];
-            return 1;
-            break;
-        case 3:
-            vf->priv->y += tmp[1];
-            return 1;
-            break;
-        default:
-            mp_msg(MSGT_VFILTER,MSGL_FATAL,"Unknown param %d \n", tmp[0]);
-            return 0;
-        }
-    }
-    return vf_next_control(vf, request, data);
-    return 0;
-}
-static int
-put_image(struct vf_instance *vf, mp_image_t* mpi, double pts){
-    mp_image_t* dmpi;
-    unsigned int bpp = mpi->bpp / 8;
-    int x, y, w, h;
-    dmpi = vf_get_image(vf->next, mpi->imgfmt, MP_IMGTYPE_TEMP,
-                        MP_IMGFLAG_ACCEPT_STRIDE | MP_IMGFLAG_PREFER_ALIGNED_STRIDE,
-                        mpi->w, mpi->h);
-
-    memcpy_pic(dmpi->planes[0],mpi->planes[0],mpi->w*bpp, mpi->h,
-               dmpi->stride[0],mpi->stride[0]);
-    if(mpi->flags&MP_IMGFLAG_PLANAR && mpi->flags&MP_IMGFLAG_YUV){
-        memcpy_pic(dmpi->planes[1],mpi->planes[1],
-                   mpi->w>>mpi->chroma_x_shift, mpi->h>>mpi->chroma_y_shift,
-                   dmpi->stride[1],mpi->stride[1]);
-        memcpy_pic(dmpi->planes[2],mpi->planes[2],
-                   mpi->w>>mpi->chroma_x_shift, mpi->h>>mpi->chroma_y_shift,
-                   dmpi->stride[2],mpi->stride[2]);
-    }
-
-    /* Draw the rectangle */
-
-    mp_msg(MSGT_VFILTER,MSGL_INFO, "rectangle: -vf rectangle=%d:%d:%d:%d \n", vf->priv->w, vf->priv->h, vf->priv->x, vf->priv->y);
-
-    x = FFMIN(vf->priv->x, dmpi->width);
-    x = FFMAX(x, 0);
-
-    w = vf->priv->x + vf->priv->w - 1 - x;
-    w = FFMIN(w, dmpi->width - x);
-    w = FFMAX(w, 0);
-
-    y = FFMIN(vf->priv->y, dmpi->height);
-    y = FFMAX(y, 0);
-
-    h = vf->priv->y + vf->priv->h - 1 - y;
-    h = FFMIN(h, dmpi->height - y);
-    h = FFMAX(h, 0);
-
-    if (0 <= vf->priv->y && vf->priv->y <= dmpi->height) {
-        unsigned char *p = dmpi->planes[0] + y * dmpi->stride[0] + x * bpp;
-        unsigned int count = w * bpp;
-        while (count--)
-            p[count] = 0xff - p[count];
-    }
-    if (h != 1 && vf->priv->y + vf->priv->h - 1 <= mpi->height) {
-        unsigned char *p = dmpi->planes[0] + (vf->priv->y + vf->priv->h - 1) * dmpi->stride[0] + x * bpp;
-        unsigned int count = w * bpp;
-        while (count--)
-            p[count] = 0xff - p[count];
-    }
-    if (0 <= vf->priv->x  && vf->priv->x <= dmpi->width) {
-        unsigned char *p = dmpi->planes[0] + y * dmpi->stride[0] + x * bpp;
-        unsigned int count = h;
-        while (count--) {
-            unsigned int i = bpp;
-            while (i--)
-                p[i] = 0xff - p[i];
-            p += dmpi->stride[0];
-        }
-    }
-    if (w != 1 && vf->priv->x + vf->priv->w - 1 <= mpi->width) {
-        unsigned char *p = dmpi->planes[0] + y * dmpi->stride[0] + (vf->priv->x + vf->priv->w - 1) * bpp;
-        unsigned int count = h;
-        while (count--) {
-            unsigned int i = bpp;
-            while (i--)
-                p[i] = 0xff - p[i];
-            p += dmpi->stride[0];
-        }
-    }
-    return vf_next_put_image(vf, dmpi, pts);
-}
-
-static int
-vf_open(vf_instance_t *vf, char *args) {
-    vf->config = config;
-    vf->control = control;
-    vf->put_image = put_image;
-    vf->priv = malloc(sizeof(struct vf_priv_s));
-    vf->priv->x = -1;
-    vf->priv->y = -1;
-    vf->priv->w = -1;
-    vf->priv->h = -1;
-    if (args)
-        sscanf(args, "%d:%d:%d:%d",
-               &vf->priv->w, &vf->priv->h, &vf->priv->x, &vf->priv->y);
-    return 1;
-}
-
-const vf_info_t vf_info_rectangle = {
-    "draw rectangle",
-    "rectangle",
-    "Kim Minh Kaplan",
-    "",
-    vf_open,
-    NULL
-};
diff --git a/libavfilter/libmpcodecs/vf_sab.c b/libavfilter/libmpcodecs/vf_sab.c
index 4dadeb7..807b726 100644
--- a/libavfilter/libmpcodecs/vf_sab.c
+++ b/libavfilter/libmpcodecs/vf_sab.c
@@ -104,7 +104,7 @@
     swsF.lumH= swsF.lumV= vec;
     swsF.chrH= swsF.chrV= NULL;
     f->preFilterContext= sws_getContext(
-        width, height, PIX_FMT_GRAY8, width, height, PIX_FMT_GRAY8, SWS_POINT, &swsF, NULL, NULL);
+        width, height, AV_PIX_FMT_GRAY8, width, height, AV_PIX_FMT_GRAY8, SWS_POINT, &swsF, NULL, NULL);
 
     sws_freeVec(vec);
     vec = sws_getGaussianVec(f->strength, 5.0);
diff --git a/libavfilter/libmpcodecs/vf_softpulldown.c b/libavfilter/libmpcodecs/vf_softpulldown.c
index 04d1eae..1a66e56 100644
--- a/libavfilter/libmpcodecs/vf_softpulldown.c
+++ b/libavfilter/libmpcodecs/vf_softpulldown.c
@@ -144,12 +144,11 @@
 
 static int vf_open(vf_instance_t *vf, char *args)
 {
-    struct vf_priv_s *p;
     vf->config = config;
     vf->put_image = put_image;
     vf->uninit = uninit;
     vf->default_reqs = VFCAP_ACCEPT_STRIDE;
-    vf->priv = p = calloc(1, sizeof(struct vf_priv_s));
+    vf->priv = calloc(1, sizeof(struct vf_priv_s));
     vf->priv->state = 0;
     return 1;
 }
diff --git a/libavfilter/libmpcodecs/vf_telecine.c b/libavfilter/libmpcodecs/vf_telecine.c
index 3b92518..3ffa87f 100644
--- a/libavfilter/libmpcodecs/vf_telecine.c
+++ b/libavfilter/libmpcodecs/vf_telecine.c
@@ -37,6 +37,8 @@
 {
     mp_image_t *dmpi;
     int ret;
+    int w            = (IMGFMT_IS_YUVP16(mpi->imgfmt) ? 2 : 1) * mpi->w;
+    int chroma_width = (IMGFMT_IS_YUVP16(mpi->imgfmt) ? 2 : 1) * mpi->chroma_width;
 
     vf->priv->frame = (vf->priv->frame+1)%4;
 
@@ -49,55 +51,56 @@
     switch (vf->priv->frame) {
     case 0:
         my_memcpy_pic(dmpi->planes[0]+dmpi->stride[0],
-            mpi->planes[0]+mpi->stride[0], mpi->w, mpi->h/2,
+            mpi->planes[0]+mpi->stride[0], w, mpi->h/2,
             dmpi->stride[0]*2, mpi->stride[0]*2);
         if (mpi->flags & MP_IMGFLAG_PLANAR) {
             my_memcpy_pic(dmpi->planes[1]+dmpi->stride[1],
                 mpi->planes[1]+mpi->stride[1],
-                mpi->chroma_width, mpi->chroma_height/2,
+                chroma_width, mpi->chroma_height/2,
                 dmpi->stride[1]*2, mpi->stride[1]*2);
             my_memcpy_pic(dmpi->planes[2]+dmpi->stride[2],
                 mpi->planes[2]+mpi->stride[2],
-                mpi->chroma_width, mpi->chroma_height/2,
+                chroma_width, mpi->chroma_height/2,
                 dmpi->stride[2]*2, mpi->stride[2]*2);
         }
         ret = vf_next_put_image(vf, dmpi, MP_NOPTS_VALUE);
+        /* Fallthrough */
     case 1:
     case 2:
-        memcpy_pic(dmpi->planes[0], mpi->planes[0], mpi->w, mpi->h,
+        memcpy_pic(dmpi->planes[0], mpi->planes[0], w, mpi->h,
             dmpi->stride[0], mpi->stride[0]);
         if (mpi->flags & MP_IMGFLAG_PLANAR) {
             memcpy_pic(dmpi->planes[1], mpi->planes[1],
-                mpi->chroma_width, mpi->chroma_height,
+                chroma_width, mpi->chroma_height,
                 dmpi->stride[1], mpi->stride[1]);
             memcpy_pic(dmpi->planes[2], mpi->planes[2],
-                mpi->chroma_width, mpi->chroma_height,
+                chroma_width, mpi->chroma_height,
                 dmpi->stride[2], mpi->stride[2]);
         }
         return vf_next_put_image(vf, dmpi, MP_NOPTS_VALUE) || ret;
     case 3:
         my_memcpy_pic(dmpi->planes[0]+dmpi->stride[0],
-            mpi->planes[0]+mpi->stride[0], mpi->w, mpi->h/2,
+            mpi->planes[0]+mpi->stride[0], w, mpi->h/2,
             dmpi->stride[0]*2, mpi->stride[0]*2);
         if (mpi->flags & MP_IMGFLAG_PLANAR) {
             my_memcpy_pic(dmpi->planes[1]+dmpi->stride[1],
                 mpi->planes[1]+mpi->stride[1],
-                mpi->chroma_width, mpi->chroma_height/2,
+                chroma_width, mpi->chroma_height/2,
                 dmpi->stride[1]*2, mpi->stride[1]*2);
             my_memcpy_pic(dmpi->planes[2]+dmpi->stride[2],
                 mpi->planes[2]+mpi->stride[2],
-                mpi->chroma_width, mpi->chroma_height/2,
+                chroma_width, mpi->chroma_height/2,
                 dmpi->stride[2]*2, mpi->stride[2]*2);
         }
         ret = vf_next_put_image(vf, dmpi, MP_NOPTS_VALUE);
-        my_memcpy_pic(dmpi->planes[0], mpi->planes[0], mpi->w, mpi->h/2,
+        my_memcpy_pic(dmpi->planes[0], mpi->planes[0], w, mpi->h/2,
             dmpi->stride[0]*2, mpi->stride[0]*2);
         if (mpi->flags & MP_IMGFLAG_PLANAR) {
             my_memcpy_pic(dmpi->planes[1], mpi->planes[1],
-                mpi->chroma_width, mpi->chroma_height/2,
+                chroma_width, mpi->chroma_height/2,
                 dmpi->stride[1]*2, mpi->stride[1]*2);
             my_memcpy_pic(dmpi->planes[2], mpi->planes[2],
-                mpi->chroma_width, mpi->chroma_height/2,
+                chroma_width, mpi->chroma_height/2,
                 dmpi->stride[2]*2, mpi->stride[2]*2);
         }
         return ret;
diff --git a/libavfilter/libmpcodecs/vf_tile.c b/libavfilter/libmpcodecs/vf_tile.c
deleted file mode 100644
index 9ec037e..0000000
--- a/libavfilter/libmpcodecs/vf_tile.c
+++ /dev/null
@@ -1,330 +0,0 @@
-/*
- * filter to tile a serie of image in a single, bigger, image
- *
- * The parameters are:
- *
- *    xtile:  number of tile on the x axis (5)
- *    ytile:  number of tile on the y axis (5)
- *    xytile: when write the image, it can be different then xtile * ytile
- *            (for example you can write 8 * 7 tile, writing the file every
- *            50 frame, to have one image every 2 seconds @ 25 fps ).
- *    start:  pixel at the start (x/y), default 2
- *    delta:  pixel between 2 tile, (x/y), default 4
- *
- * For example a valid command line is:
- *    ... -vf tile=10:5:-1:4:8 ...
- * that make images of 10 * 5 tiles, with 4 pixel at the beginning and
- * 8 pixel between tiles.
- *
- * The default command is:
- *    ... -vf tile=5:5:25:2:4
- *
- * If you omit a parameter or put a value less then 0, the default is used.
- *    ... -vf tile=10:5::-1:10
- *
- * You can also stop when you're ok
- *    ... -vf tile=10:5
- * (and this is probably the option you will use more often ...)
- *
- * Probably is good to put the scale filter before the tile :-)
- *
- * copyright (c) 2003 Daniele Forghieri ( guru@digitalfantasy.it )
- *
- * This file is part of MPlayer.
- *
- * MPlayer 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.
- *
- * MPlayer is distributed in the hope that 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 MPlayer; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
- */
-
-// strtoi memcpy_pic
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "config.h"
-#include "mp_msg.h"
-#include "help_mp.h"
-#include "cpudetect.h"
-
-#include "img_format.h"
-#include "mp_image.h"
-#include "vf.h"
-
-#include "libvo/fastmemcpy.h"
-
-/* private data */
-struct vf_priv_s {
-    /* configuration data */
-    /* Number on hor/ver tiles */
-    int  xtile;
-    int  ytile;
-    /* When write the whole frame (default = xtile * ytile) */
-    int  xytile;
-    /* pixel at start / end (default = 4) */
-    int  start;
-    /* pixel between image (default = 2) */
-    int  delta;
-//    /* Background color, in destination format */
-//    int  bkgSet;
-
-    /* Work data */
-    int  frame_cur;
-};
-
-
-static int config(struct vf_instance *vf,
-                  int width, int height, int d_width, int d_height,
-              unsigned int flags, unsigned int outfmt){
-
-    struct vf_priv_s  *priv;
-    int               xw;
-    int               yh;
-
-    /* Calculate new destination size */
-    priv = vf->priv;
-    xw = priv->start * 2 +
-        priv->xtile * width +
-        (priv->xtile - 1) * priv->delta;
-    yh = priv->start * 2 +
-        priv->ytile * height +
-        (priv->ytile - 1) * priv->delta;
-
-    mp_msg(MSGT_VFILTER,MSGL_V,"vf_tile:config size set to %d * %d\n", xw, yh);
-
-    return vf_next_config(vf, xw, yh, xw, yh, flags, outfmt);
-}
-
-/* Filter handler */
-static int put_image(struct vf_instance *vf, mp_image_t *mpi, double pts)
-{
-    mp_image_t        *dmpi;
-    struct vf_priv_s  *priv;
-    int               t;
-    int               xw;
-    int               yh;
-    int               xi;
-    int               yi;
-    int               by;
-    int               dw;
-
-    /* Calculate new size */
-    priv = vf->priv;
-    xw = priv->start * 2 +
-        priv->xtile * mpi->w +
-        (priv->xtile - 1) * priv->delta;
-    yh = priv->start * 2 +
-        priv->ytile * mpi->h+
-        (priv->ytile - 1) * priv->delta;
-
-    /* Get the big image! */
-    dmpi=vf_get_image(vf->next, mpi->imgfmt,
-                      MP_IMGTYPE_STATIC, MP_IMGFLAG_ACCEPT_STRIDE,
-                      xw, yh);
-
-    /* bytes x pixel & bytes x line */
-    if (mpi->flags & MP_IMGFLAG_PLANAR) {
-        by = 1;
-        dw = mpi->w;
-    }
-    else {
-        by = (mpi->bpp + 7) / 8;
-        dw = mpi->w * by;
-    }
-    /* Index position */
-    t = priv->frame_cur % priv->xytile;
-//    if ((t == 0) && (bkg != 0)) {
-//        /* First frame, delete the background */
-//
-//    }
-
-    /* Position of image */
-    xi = priv->start + (mpi->w + priv->delta) * (t % priv->xtile);
-    yi = priv->start + (mpi->h + priv->delta) * (t / priv->xtile);
-
-    /* Copy first (or only) plane */
-    memcpy_pic( dmpi->planes[0] + xi * by + yi * dmpi->stride[0],
-                mpi->planes[0],
-                dw,
-                mpi->h,
-                dmpi->stride[0],
-                mpi->stride[0]);
-
-    if (mpi->flags & MP_IMGFLAG_PLANAR) {
-        /* Copy the other 2 planes */
-        memcpy_pic( dmpi->planes[1] + (xi >> mpi->chroma_x_shift) + (yi >> mpi->chroma_y_shift) * dmpi->stride[1],
-                    mpi->planes[1],
-                    mpi->chroma_width,
-                    mpi->chroma_height,
-                    dmpi->stride[1],
-                    mpi->stride[1]);
-         memcpy_pic( dmpi->planes[2] + (xi >> mpi->chroma_x_shift) + (yi >> mpi->chroma_y_shift) * dmpi->stride[2],
-                    mpi->planes[2],
-                    mpi->chroma_width,
-                    mpi->chroma_height,
-                    dmpi->stride[2],
-                    mpi->stride[2]);
-    }
-
-    /* Increment current frame */
-    ++priv->frame_cur;
-
-    if (t == priv->xytile - 1)  {
-        /* Display the composition */
-        dmpi->width  = xw;
-        dmpi->height = yh;
-        return vf_next_put_image(vf, dmpi, MP_NOPTS_VALUE);
-    }
-    else {
-        /* Skip the frame */
-        return 0;
-    }
-}
-
-static void uninit(struct vf_instance *vf)
-{
-    /* free local data */
-    free(vf->priv);
-}
-
-/* rgb/bgr 12...32 supported & some Yxxx */
-static int query_format(struct vf_instance *vf, unsigned int fmt)
-{
-    switch (fmt) {
-        /* rgb 12...32 bit */
-        case IMGFMT_RGB12:
-        case IMGFMT_RGB15:
-        case IMGFMT_RGB16:
-        case IMGFMT_RGB24:
-        case IMGFMT_RGB32:
-        /* bgr 12...32 bit */
-        case IMGFMT_BGR12:
-        case IMGFMT_BGR15:
-        case IMGFMT_BGR16:
-        case IMGFMT_BGR24:
-        case IMGFMT_BGR32:
-        /* Various Yxxx Formats */
-        case IMGFMT_444P:
-        case IMGFMT_422P:
-        case IMGFMT_411P:
-        case IMGFMT_YUY2:
-        case IMGFMT_YV12:
-        case IMGFMT_I420:
-        case IMGFMT_YVU9:
-        case IMGFMT_IF09:
-        case IMGFMT_IYUV:
-        return vf_next_query_format(vf, fmt);
-    }
-    return 0;
-}
-
-/* Get an integer from the string pointed by s, adjusting s.
- * If the value is less then 0 def_val is used.
- * Return 0 for ok
- *
- * Look below ( in vf_open(...) ) for a use ...
- */
-static int parse_int(char **s, int *rt, int def_val)
-{
-
-    int     t = 0;
-
-    if (**s) {
-        /* Get value (dec, hex or octal) */
-        t = strtol( *s, s, 0 );
-
-        /* Use default */
-        if (t < 0) {
-            t = def_val;
-        }
-
-        if (**s == ':') {
-            /* Point to next character (problably a digit) */
-            ++(*s);
-        }
-        else if (**s != '\0') {
-            /* Error, we got some wrong char */
-            return 1;
-        }
-    }
-    else {
-        t = def_val;
-    }
-
-    *rt = t;
-    return 0;
-
-}
-
-/* Main entry funct for the filter */
-static int vf_open(vf_instance_t *vf, char *args)
-{
-    struct vf_priv_s *p;
-    int              er;
-
-    vf->put_image    = put_image;
-    vf->query_format = query_format;
-    vf->config       = config;
-    vf->uninit       = uninit;
-    vf->default_reqs = VFCAP_ACCEPT_STRIDE;
-    /* Private data */
-    vf->priv = p = calloc(1, sizeof(struct vf_priv_s));
-    if (p == NULL) {
-        return 0;
-    }
-
-    if (args == NULL) {
-        /* Use the default */
-        args = "";
-    }
-    /* Parse all the arguments */
-    er =  parse_int( &args, &p->xtile,  5 );
-    er |= parse_int( &args, &p->ytile,  5 );
-    er |= parse_int( &args, &p->xytile, 0 );
-    er |= parse_int( &args, &p->start,  2 );
-    er |= parse_int( &args, &p->delta,  4 );
-//    er |= parse_int( &args, &p->bkgSet, 0 );
-
-    if (er) {
-        mp_msg(MSGT_VFILTER, MSGL_ERR, MSGTR_MPCODECS_ErrorParsingArgument);
-        return 0;
-    }
-    /* Load some default */
-    if ((p->xytile <= 0) || (p->xytile > p->xtile * p->ytile)) {
-        p->xytile = p->xtile * p->ytile;
-    }
-
-    /* Say what happen: use mp_msg(...)? */
-    if ( mp_msg_test(MSGT_VFILTER,MSGL_V) ) {
-        printf("vf_tile: tiling %d * %d, output every %d frames\n",
-               p->xtile,
-               p->ytile,
-               p->xytile);
-        printf("vf_tile: start pixel %d, delta pixel %d\n",
-               p->start,
-               p->delta);
-//      printf("vf_tile: background 0x%x\n",
-//             p->bkgSet);
-    }
-    return 1;
-}
-
-const vf_info_t vf_info_tile = {
-    "Make a single image tiling x/y images",
-    "tile",
-    "Daniele Forghieri",
-    "",
-    vf_open,
-    NULL
-};
diff --git a/libavfilter/libmpcodecs/vf_tinterlace.c b/libavfilter/libmpcodecs/vf_tinterlace.c
index 6dbcbc9..8cd6ac8 100644
--- a/libavfilter/libmpcodecs/vf_tinterlace.c
+++ b/libavfilter/libmpcodecs/vf_tinterlace.c
@@ -218,10 +218,10 @@
     vf->uninit = uninit;
     vf->default_reqs = VFCAP_ACCEPT_STRIDE;
     vf->priv = p = calloc(1, sizeof(struct vf_priv_s));
-    vf->priv->mode = 0;
+    p->mode = 0;
     if (args)
-      sscanf(args, "%d", &vf->priv->mode);
-    vf->priv->frame = 0;
+      sscanf(args, "%d", &p->mode);
+    p->frame = 0;
     return 1;
 }
 
diff --git a/libavfilter/libmpcodecs/vf_uspp.c b/libavfilter/libmpcodecs/vf_uspp.c
index cc9a3db..1c683f7 100644
--- a/libavfilter/libmpcodecs/vf_uspp.c
+++ b/libavfilter/libmpcodecs/vf_uspp.c
@@ -230,7 +230,7 @@
             avctx_enc->time_base= (AVRational){1,25};  // meaningless
             avctx_enc->gop_size = 300;
             avctx_enc->max_b_frames= 0;
-            avctx_enc->pix_fmt = PIX_FMT_YUV420P;
+            avctx_enc->pix_fmt = AV_PIX_FMT_YUV420P;
             avctx_enc->flags = CODEC_FLAG_QSCALE | CODEC_FLAG_LOW_DELAY;
             avctx_enc->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
             avctx_enc->global_quality= 123;
diff --git a/libavfilter/libmpcodecs/vf_yuvcsp.c b/libavfilter/libmpcodecs/vf_yuvcsp.c
deleted file mode 100644
index 102ce14..0000000
--- a/libavfilter/libmpcodecs/vf_yuvcsp.c
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * This file is part of MPlayer.
- *
- * MPlayer 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.
- *
- * MPlayer is distributed in the hope that 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 MPlayer; 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 "config.h"
-#include "mp_msg.h"
-
-#include "img_format.h"
-#include "mp_image.h"
-#include "vf.h"
-
-struct vf_priv_s {
-    int csp;
-};
-
-//===========================================================================//
-
-static int config(struct vf_instance *vf,
-        int width, int height, int d_width, int d_height,
-        unsigned int flags, unsigned int outfmt){
-    return vf_next_config(vf, width, height, d_width, d_height, flags, outfmt);
-}
-
-static inline int clamp_y(int x){
-    return (x > 235) ? 235 : (x < 16) ? 16 : x;
-}
-
-static inline int clamp_c(int x){
-    return (x > 240) ? 240 : (x < 16) ? 16 : x;
-}
-
-static int put_image(struct vf_instance *vf, mp_image_t *mpi, double pts){
-    int i,j;
-    uint8_t *y_in, *cb_in, *cr_in;
-    uint8_t *y_out, *cb_out, *cr_out;
-
-    vf->dmpi=vf_get_image(vf->next,mpi->imgfmt,
-        MP_IMGTYPE_TEMP, MP_IMGFLAG_ACCEPT_STRIDE,
-        mpi->width, mpi->height);
-
-    y_in = mpi->planes[0];
-    cb_in = mpi->planes[1];
-    cr_in = mpi->planes[2];
-
-    y_out = vf->dmpi->planes[0];
-    cb_out = vf->dmpi->planes[1];
-    cr_out = vf->dmpi->planes[2];
-
-    for (i = 0; i < mpi->height; i++)
-        for (j = 0; j < mpi->width; j++)
-            y_out[i*vf->dmpi->stride[0]+j] = clamp_y(y_in[i*mpi->stride[0]+j]);
-
-    for (i = 0; i < mpi->chroma_height; i++)
-        for (j = 0; j < mpi->chroma_width; j++)
-        {
-            cb_out[i*vf->dmpi->stride[1]+j] = clamp_c(cb_in[i*mpi->stride[1]+j]);
-            cr_out[i*vf->dmpi->stride[2]+j] = clamp_c(cr_in[i*mpi->stride[2]+j]);
-        }
-
-    return vf_next_put_image(vf,vf->dmpi, pts);
-}
-
-//===========================================================================//
-
-/*
-static void uninit(struct vf_instance *vf){
-        free(vf->priv);
-}
-*/
-
-static int query_format(struct vf_instance *vf, unsigned int fmt){
-    switch(fmt){
-        case IMGFMT_YV12:
-        case IMGFMT_I420:
-        case IMGFMT_IYUV:
-            return 1;
-    }
-    return 0;
-}
-
-static int vf_open(vf_instance_t *vf, char *args){
-    vf->config=config;
-    vf->put_image=put_image;
-//    vf->uninit=uninit;
-    vf->query_format=query_format;
-//    vf->priv=calloc(1, sizeof(struct vf_priv_s));
-//    if (args)
-//        vf->priv->csp = atoi(args);
-    return 1;
-}
-
-const vf_info_t vf_info_yuvcsp = {
-    "yuv colorspace converter",
-    "yuvcsp",
-    "Alex Beregszaszi",
-    "",
-    vf_open,
-    NULL
-};
-
-//===========================================================================//
diff --git a/libavfilter/libmpcodecs/vf_yvu9.c b/libavfilter/libmpcodecs/vf_yvu9.c
deleted file mode 100644
index 1f74261..0000000
--- a/libavfilter/libmpcodecs/vf_yvu9.c
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * This file is part of MPlayer.
- *
- * MPlayer 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.
- *
- * MPlayer is distributed in the hope that 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 MPlayer; 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 "config.h"
-#include "mp_msg.h"
-#include "help_mp.h"
-
-#include "img_format.h"
-#include "mp_image.h"
-#include "vf.h"
-
-#include "libvo/fastmemcpy.h"
-
-//===========================================================================//
-
-static int config(struct vf_instance *vf,
-        int width, int height, int d_width, int d_height,
-        unsigned int flags, unsigned int outfmt){
-
-    if(vf_next_query_format(vf,IMGFMT_YV12)<=0){
-        mp_msg(MSGT_VFILTER, MSGL_WARN, MSGTR_MPCODECS_WarnNextFilterDoesntSupport, "YVU9");
-        return 0;
-    }
-
-    return vf_next_config(vf,width,height,d_width,d_height,flags,IMGFMT_YV12);
-}
-
-static int put_image(struct vf_instance *vf, mp_image_t *mpi, double pts){
-    mp_image_t *dmpi;
-    int y,w,h;
-
-    // hope we'll get DR buffer:
-    dmpi=vf_get_image(vf->next,IMGFMT_YV12,
-        MP_IMGTYPE_TEMP, 0/*MP_IMGFLAG_ACCEPT_STRIDE*/,
-        mpi->w, mpi->h);
-
-    for(y=0;y<mpi->h;y++)
-        fast_memcpy(dmpi->planes[0]+dmpi->stride[0]*y,
-               mpi->planes[0]+mpi->stride[0]*y,
-               mpi->w);
-
-    w=mpi->w/4; h=mpi->h/2;
-    for(y=0;y<h;y++){
-        unsigned char* s=mpi->planes[1]+mpi->stride[1]*(y>>1);
-        unsigned char* d=dmpi->planes[1]+dmpi->stride[1]*y;
-        int x;
-        for(x=0;x<w;x++) d[2*x]=d[2*x+1]=s[x];
-    }
-    for(y=0;y<h;y++){
-        unsigned char* s=mpi->planes[2]+mpi->stride[2]*(y>>1);
-        unsigned char* d=dmpi->planes[2]+dmpi->stride[2]*y;
-        int x;
-        for(x=0;x<w;x++) d[2*x]=d[2*x+1]=s[x];
-    }
-
-    vf_clone_mpi_attributes(dmpi, mpi);
-
-    return vf_next_put_image(vf,dmpi, pts);
-}
-
-//===========================================================================//
-
-static int query_format(struct vf_instance *vf, unsigned int fmt){
-    if (fmt == IMGFMT_YVU9 || fmt == IMGFMT_IF09)
-        return vf_next_query_format(vf,IMGFMT_YV12) & (~VFCAP_CSP_SUPPORTED_BY_HW);
-    return 0;
-}
-
-static int vf_open(vf_instance_t *vf, char *args){
-    vf->config=config;
-    vf->put_image=put_image;
-    vf->query_format=query_format;
-    return 1;
-}
-
-const vf_info_t vf_info_yvu9 = {
-    "fast YVU9->YV12 conversion",
-    "yvu9",
-    "alex",
-    "",
-    vf_open,
-    NULL
-};
-
-//===========================================================================//
diff --git a/libavfilter/lswsutils.c b/libavfilter/lswsutils.c
index 2c98f3a..6902ee9 100644
--- a/libavfilter/lswsutils.c
+++ b/libavfilter/lswsutils.c
@@ -20,9 +20,9 @@
 #include "lswsutils.h"
 
 int ff_scale_image(uint8_t *dst_data[4], int dst_linesize[4],
-                   int dst_w, int dst_h, enum PixelFormat dst_pix_fmt,
+                   int dst_w, int dst_h, enum AVPixelFormat dst_pix_fmt,
                    uint8_t * const src_data[4], int src_linesize[4],
-                   int src_w, int src_h, enum PixelFormat src_pix_fmt,
+                   int src_w, int src_h, enum AVPixelFormat src_pix_fmt,
                    void *log_ctx)
 {
     int ret;
diff --git a/libavfilter/lswsutils.h b/libavfilter/lswsutils.h
index 0600483..f5f5320 100644
--- a/libavfilter/lswsutils.h
+++ b/libavfilter/lswsutils.h
@@ -30,9 +30,9 @@
  * Scale image using libswscale.
  */
 int ff_scale_image(uint8_t *dst_data[4], int dst_linesize[4],
-                   int dst_w, int dst_h, enum PixelFormat dst_pix_fmt,
+                   int dst_w, int dst_h, enum AVPixelFormat dst_pix_fmt,
                    uint8_t *const src_data[4], int src_linesize[4],
-                   int src_w, int src_h, enum PixelFormat src_pix_fmt,
+                   int src_w, int src_h, enum AVPixelFormat src_pix_fmt,
                    void *log_ctx);
 
 #endif  /* AVFILTER_LSWSUTILS_H */
diff --git a/libavfilter/sink_buffer.c b/libavfilter/sink_buffer.c
index 83e43cf..88fefba 100644
--- a/libavfilter/sink_buffer.c
+++ b/libavfilter/sink_buffer.c
@@ -23,8 +23,8 @@
  * buffer sink
  */
 
-#include "libavutil/audioconvert.h"
 #include "libavutil/avassert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/fifo.h"
 #include "avfilter.h"
 #include "buffersink.h"
@@ -33,7 +33,7 @@
 
 AVBufferSinkParams *av_buffersink_params_alloc(void)
 {
-    static const int pixel_fmts[] = { -1 };
+    static const int pixel_fmts[] = { AV_PIX_FMT_NONE };
     AVBufferSinkParams *params = av_malloc(sizeof(AVBufferSinkParams));
     if (!params)
         return NULL;
@@ -44,7 +44,7 @@
 
 AVABufferSinkParams *av_abuffersink_params_alloc(void)
 {
-    static const int sample_fmts[] = { -1 };
+    static const int sample_fmts[] = { AV_SAMPLE_FMT_NONE };
     static const int64_t channel_layouts[] = { -1 };
     AVABufferSinkParams *params = av_malloc(sizeof(AVABufferSinkParams));
 
@@ -61,7 +61,7 @@
     unsigned warning_limit;
 
     /* only used for video */
-    enum PixelFormat *pixel_fmts;           ///< list of accepted pixel formats, must be terminated with -1
+    enum AVPixelFormat *pixel_fmts;           ///< list of accepted pixel formats, must be terminated with -1
 
     /* only used for audio */
     enum AVSampleFormat *sample_fmts;       ///< list of accepted sample formats, terminated by AV_SAMPLE_FMT_NONE
@@ -234,6 +234,16 @@
     return 0;
 }
 
+static const AVFilterPad ffbuffersink_inputs[] = {
+    {
+        .name      = "default",
+        .type      = AVMEDIA_TYPE_VIDEO,
+        .end_frame = end_frame,
+        .min_perms = AV_PERM_READ | AV_PERM_PRESERVE,
+    },
+    { NULL },
+};
+
 AVFilter avfilter_vsink_ffbuffersink = {
     .name      = "ffbuffersink",
     .description = NULL_IF_CONFIG_SMALL("Buffer video frames, and make them available to the end of the filter graph."),
@@ -242,13 +252,18 @@
     .uninit    = vsink_uninit,
 
     .query_formats = vsink_query_formats,
+    .inputs        = ffbuffersink_inputs,
+    .outputs       = NULL,
+};
 
-    .inputs    = (const AVFilterPad[]) {{ .name    = "default",
-                                    .type          = AVMEDIA_TYPE_VIDEO,
-                                    .end_frame     = end_frame,
-                                    .min_perms     = AV_PERM_READ | AV_PERM_PRESERVE, },
-                                  { .name = NULL }},
-    .outputs   = (const AVFilterPad[]) {{ .name = NULL }},
+static const AVFilterPad buffersink_inputs[] = {
+    {
+        .name      = "default",
+        .type      = AVMEDIA_TYPE_VIDEO,
+        .end_frame = end_frame,
+        .min_perms = AV_PERM_READ | AV_PERM_PRESERVE,
+    },
+    { NULL },
 };
 
 AVFilter avfilter_vsink_buffersink = {
@@ -259,16 +274,11 @@
     .uninit    = vsink_uninit,
 
     .query_formats = vsink_query_formats,
-
-    .inputs    = (const AVFilterPad[]) {{ .name    = "default",
-                                    .type          = AVMEDIA_TYPE_VIDEO,
-                                    .end_frame     = end_frame,
-                                    .min_perms     = AV_PERM_READ | AV_PERM_PRESERVE, },
-                                  { .name = NULL }},
-    .outputs   = (const AVFilterPad[]) {{ .name = NULL }},
+    .inputs        = buffersink_inputs,
+    .outputs       = NULL,
 };
 
-static int filter_samples(AVFilterLink *link, AVFilterBufferRef *samplesref)
+static int filter_frame(AVFilterLink *link, AVFilterBufferRef *samplesref)
 {
     end_frame(link);
     return 0;
@@ -328,6 +338,16 @@
     return 0;
 }
 
+static const AVFilterPad ffabuffersink_inputs[] = {
+    {
+        .name           = "default",
+        .type           = AVMEDIA_TYPE_AUDIO,
+        .filter_frame   = filter_frame,
+        .min_perms      = AV_PERM_READ | AV_PERM_PRESERVE,
+    },
+    { NULL },
+};
+
 AVFilter avfilter_asink_ffabuffersink = {
     .name      = "ffabuffersink",
     .description = NULL_IF_CONFIG_SMALL("Buffer audio frames, and make them available to the end of the filter graph."),
@@ -335,13 +355,18 @@
     .uninit    = asink_uninit,
     .priv_size = sizeof(BufferSinkContext),
     .query_formats = asink_query_formats,
+    .inputs        = ffabuffersink_inputs,
+    .outputs       = NULL,
+};
 
-    .inputs    = (const AVFilterPad[]) {{ .name     = "default",
-                                    .type           = AVMEDIA_TYPE_AUDIO,
-                                    .filter_samples = filter_samples,
-                                    .min_perms      = AV_PERM_READ | AV_PERM_PRESERVE, },
-                                  { .name = NULL }},
-    .outputs   = (const AVFilterPad[]) {{ .name = NULL }},
+static const AVFilterPad abuffersink_inputs[] = {
+    {
+        .name           = "default",
+        .type           = AVMEDIA_TYPE_AUDIO,
+        .filter_frame   = filter_frame,
+        .min_perms      = AV_PERM_READ | AV_PERM_PRESERVE,
+    },
+    { NULL },
 };
 
 AVFilter avfilter_asink_abuffersink = {
@@ -351,13 +376,8 @@
     .uninit    = asink_uninit,
     .priv_size = sizeof(BufferSinkContext),
     .query_formats = asink_query_formats,
-
-    .inputs    = (const AVFilterPad[]) {{ .name     = "default",
-                                    .type           = AVMEDIA_TYPE_AUDIO,
-                                    .filter_samples = filter_samples,
-                                    .min_perms      = AV_PERM_READ | AV_PERM_PRESERVE, },
-                                  { .name = NULL }},
-    .outputs   = (const AVFilterPad[]) {{ .name = NULL }},
+    .inputs        = abuffersink_inputs,
+    .outputs       = NULL,
 };
 
 /* Libav compatibility API */
@@ -372,13 +392,13 @@
 
     if (ctx->filter->          inputs[0].start_frame ==
         avfilter_vsink_buffer. inputs[0].start_frame ||
-        ctx->filter->          inputs[0].filter_samples ==
-        avfilter_asink_abuffer.inputs[0].filter_samples)
+        ctx->filter->          inputs[0].filter_frame ==
+        avfilter_asink_abuffer.inputs[0].filter_frame)
         return ff_buffersink_read_compat(ctx, buf);
     av_assert0(ctx->filter->                inputs[0].end_frame ==
                avfilter_vsink_ffbuffersink. inputs[0].end_frame ||
-               ctx->filter->                inputs[0].filter_samples ==
-               avfilter_asink_ffabuffersink.inputs[0].filter_samples);
+               ctx->filter->                inputs[0].filter_frame ==
+               avfilter_asink_ffabuffersink.inputs[0].filter_frame);
 
     ret = av_buffersink_get_buffer_ref(ctx, &tbuf,
                                        buf ? 0 : AV_BUFFERSINK_FLAG_PEEK);
@@ -399,11 +419,11 @@
     AVFilterLink *link = ctx->inputs[0];
     int nb_channels = av_get_channel_layout_nb_channels(link->channel_layout);
 
-    if (ctx->filter->          inputs[0].filter_samples ==
-        avfilter_asink_abuffer.inputs[0].filter_samples)
+    if (ctx->filter->          inputs[0].filter_frame ==
+        avfilter_asink_abuffer.inputs[0].filter_frame)
         return ff_buffersink_read_samples_compat(ctx, buf, nb_samples);
-    av_assert0(ctx->filter->                inputs[0].filter_samples ==
-               avfilter_asink_ffabuffersink.inputs[0].filter_samples);
+    av_assert0(ctx->filter->                inputs[0].filter_frame ==
+               avfilter_asink_ffabuffersink.inputs[0].filter_frame);
 
     tbuf = ff_get_audio_buffer(link, AV_PERM_WRITE, nb_samples);
     if (!tbuf)
diff --git a/libavfilter/split.c b/libavfilter/split.c
index e036a93..a54bef9 100644
--- a/libavfilter/split.c
+++ b/libavfilter/split.c
@@ -68,7 +68,7 @@
         av_freep(&ctx->output_pads[i].name);
 }
 
-static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *frame)
 {
     AVFilterContext *ctx = inlink->dst;
     int i, ret = AVERROR_EOF;
@@ -78,46 +78,29 @@
 
         if (ctx->outputs[i]->closed)
             continue;
-        buf_out = avfilter_ref_buffer(picref, ~AV_PERM_WRITE);
-        if (!buf_out)
-            return AVERROR(ENOMEM);
+        buf_out = avfilter_ref_buffer(frame, ~AV_PERM_WRITE);
+        if (!buf_out) {
+            ret = AVERROR(ENOMEM);
+            break;
+        }
 
-        ret = ff_start_frame(ctx->outputs[i], buf_out);
+        ret = ff_filter_frame(ctx->outputs[i], buf_out);
         if (ret < 0)
             break;
     }
+    avfilter_unref_bufferp(&frame);
     return ret;
 }
 
-static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
-{
-    AVFilterContext *ctx = inlink->dst;
-    int i, ret = AVERROR_EOF;
-
-    for (i = 0; i < ctx->nb_outputs; i++) {
-        if (ctx->outputs[i]->closed)
-            continue;
-        ret = ff_draw_slice(ctx->outputs[i], y, h, slice_dir);
-        if (ret < 0)
-            break;
-    }
-    return ret;
-}
-
-static int end_frame(AVFilterLink *inlink)
-{
-    AVFilterContext *ctx = inlink->dst;
-    int i, ret = AVERROR_EOF;
-
-    for (i = 0; i < ctx->nb_outputs; i++) {
-        if (ctx->outputs[i]->closed)
-            continue;
-        ret = ff_end_frame(ctx->outputs[i]);
-        if (ret < 0)
-            break;
-    }
-    return ret;
-}
+static const AVFilterPad avfilter_vf_split_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .filter_frame     = filter_frame,
+    },
+    { NULL }
+};
 
 AVFilter avfilter_vf_split = {
     .name      = "split",
@@ -126,36 +109,19 @@
     .init   = split_init,
     .uninit = split_uninit,
 
-    .inputs    = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_VIDEO,
-                                          .get_video_buffer= ff_null_get_video_buffer,
-                                          .start_frame     = start_frame,
-                                          .draw_slice      = draw_slice,
-                                          .end_frame       = end_frame, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_split_inputs,
     .outputs   = NULL,
 };
 
-static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *samplesref)
-{
-    AVFilterContext *ctx = inlink->dst;
-    int i, ret = 0;
-
-    for (i = 0; i < ctx->nb_outputs; i++) {
-        AVFilterBufferRef *buf_out = avfilter_ref_buffer(samplesref,
-                                                         ~AV_PERM_WRITE);
-        if (!buf_out) {
-            ret = AVERROR(ENOMEM);
-            break;
-        }
-
-        ret = ff_filter_samples(inlink->dst->outputs[i], buf_out);
-        if (ret < 0)
-            break;
-    }
-    avfilter_unref_buffer(samplesref);
-    return ret;
-}
+static const AVFilterPad avfilter_af_asplit_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_AUDIO,
+        .get_audio_buffer = ff_null_get_audio_buffer,
+        .filter_frame     = filter_frame,
+    },
+    { NULL }
+};
 
 AVFilter avfilter_af_asplit = {
     .name        = "asplit",
@@ -164,10 +130,6 @@
     .init   = split_init,
     .uninit = split_uninit,
 
-    .inputs  = (const AVFilterPad[]) {{ .name             = "default",
-                                        .type             = AVMEDIA_TYPE_AUDIO,
-                                        .get_audio_buffer = ff_null_get_audio_buffer,
-                                        .filter_samples   = filter_samples },
-                                      { .name = NULL }},
+    .inputs  = avfilter_af_asplit_inputs,
     .outputs = NULL,
 };
diff --git a/libavfilter/src_buffer.c b/libavfilter/src_buffer.c
index c889287..acd490b 100644
--- a/libavfilter/src_buffer.c
+++ b/libavfilter/src_buffer.c
@@ -31,8 +31,8 @@
 #include "avcodec.h"
 #include "buffersrc.h"
 #include "asrc_abuffer.h"
-#include "libavutil/audioconvert.h"
 #include "libavutil/avstring.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/fifo.h"
 #include "libavutil/imgutils.h"
 
@@ -45,7 +45,7 @@
     /* Video only */
     AVFilterContext  *scale;
     int               h, w;
-    enum PixelFormat  pix_fmt;
+    enum AVPixelFormat  pix_fmt;
     AVRational        sample_aspect_ratio;
     char              sws_param[256];
 
diff --git a/libavfilter/src_movie.c b/libavfilter/src_movie.c
index 8ebad6d..bd45766 100644
--- a/libavfilter/src_movie.c
+++ b/libavfilter/src_movie.c
@@ -197,9 +197,12 @@
     movie->class = class;
     av_opt_set_defaults(movie);
 
-    if (args)
+    if (args) {
         movie->file_name = av_get_token(&args, ":");
-    if (!movie->file_name || !*movie->file_name) {
+        if (!movie->file_name)
+            return AVERROR(ENOMEM);
+    }
+    if (!args || !*movie->file_name) {
         av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
         return AVERROR(EINVAL);
     }
@@ -569,12 +572,9 @@
     case AVMEDIA_TYPE_VIDEO:
         if (!movie->frame->sample_aspect_ratio.num)
             buf->video->sample_aspect_ratio = st->st->sample_aspect_ratio;
-        ff_start_frame(outlink, buf);
-        ff_draw_slice(outlink, 0, outlink->h, 1);
-        ff_end_frame(outlink);
-        break;
+        /* Fall through */
     case AVMEDIA_TYPE_AUDIO:
-        ff_filter_samples(outlink, buf);
+        ff_filter_frame(outlink, buf);
         break;
     }
 
@@ -612,7 +612,7 @@
     .query_formats = movie_query_formats,
 
     .inputs    = NULL,
-    .outputs   = (const AVFilterPad[]) {{ .name = NULL }},
+    .outputs   = NULL,
     .priv_class = &movie_class,
 };
 
@@ -636,8 +636,8 @@
     .uninit        = movie_uninit,
     .query_formats = movie_query_formats,
 
-    .inputs    = (const AVFilterPad[]) {{ .name = NULL }},
-    .outputs   = (const AVFilterPad[]) {{ .name = NULL }},
+    .inputs     = NULL,
+    .outputs    = NULL,
     .priv_class = &amovie_class,
 };
 
diff --git a/libavfilter/transform.c b/libavfilter/transform.c
index b3f85dd..1db8c08 100644
--- a/libavfilter/transform.c
+++ b/libavfilter/transform.c
@@ -146,7 +146,7 @@
     return v;
 }
 
-void avfilter_transform(const uint8_t *src, uint8_t *dst,
+int avfilter_transform(const uint8_t *src, uint8_t *dst,
                         int src_stride, int dst_stride,
                         int width, int height, const float *matrix,
                         enum InterpolateMethod interpolate,
@@ -167,6 +167,8 @@
         case INTERPOLATE_BIQUADRATIC:
             func = interpolate_biquadratic;
             break;
+        default:
+            return AVERROR(EINVAL);
     }
 
     for (y = 0; y < height; y++) {
@@ -195,5 +197,6 @@
             dst[y * dst_stride + x] = func(x_s, y_s, src, width, height, src_stride, def);
         }
     }
+    return 0;
 }
 
diff --git a/libavfilter/transform.h b/libavfilter/transform.h
index edd0cf2..07436bf 100644
--- a/libavfilter/transform.h
+++ b/libavfilter/transform.h
@@ -116,8 +116,9 @@
  * @param matrix      9-item affine transformation matrix
  * @param interpolate pixel interpolation method
  * @param fill        edge fill method
+ * @return negative on error
  */
-void avfilter_transform(const uint8_t *src, uint8_t *dst,
+int avfilter_transform(const uint8_t *src, uint8_t *dst,
                         int src_stride, int dst_stride,
                         int width, int height, const float *matrix,
                         enum InterpolateMethod interpolate,
diff --git a/libavfilter/version.h b/libavfilter/version.h
index e4520a3..a4a2e37 100644
--- a/libavfilter/version.h
+++ b/libavfilter/version.h
@@ -29,8 +29,8 @@
 #include "libavutil/avutil.h"
 
 #define LIBAVFILTER_VERSION_MAJOR  3
-#define LIBAVFILTER_VERSION_MINOR  18
-#define LIBAVFILTER_VERSION_MICRO 100
+#define LIBAVFILTER_VERSION_MINOR  23
+#define LIBAVFILTER_VERSION_MICRO 105
 
 #define LIBAVFILTER_VERSION_INT AV_VERSION_INT(LIBAVFILTER_VERSION_MAJOR, \
                                                LIBAVFILTER_VERSION_MINOR, \
diff --git a/libavfilter/vf_alphaextract.c b/libavfilter/vf_alphaextract.c
index f6ce1b3..35402f6 100644
--- a/libavfilter/vf_alphaextract.c
+++ b/libavfilter/vf_alphaextract.c
@@ -40,12 +40,12 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    enum PixelFormat in_fmts[] = {
-        PIX_FMT_YUVA444P, PIX_FMT_YUVA422P, PIX_FMT_YUVA420P,
-        PIX_FMT_RGBA, PIX_FMT_BGRA, PIX_FMT_ARGB, PIX_FMT_ABGR,
-        PIX_FMT_NONE
+    enum AVPixelFormat in_fmts[] = {
+        AV_PIX_FMT_YUVA444P, AV_PIX_FMT_YUVA422P, AV_PIX_FMT_YUVA420P,
+        AV_PIX_FMT_RGBA, AV_PIX_FMT_BGRA, AV_PIX_FMT_ARGB, AV_PIX_FMT_ABGR,
+        AV_PIX_FMT_NONE
     };
-    enum PixelFormat out_fmts[] = { PIX_FMT_GRAY8, PIX_FMT_NONE };
+    enum AVPixelFormat out_fmts[] = { AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE };
     ff_formats_ref(ff_make_format_list(in_fmts), &ctx->inputs[0]->out_formats);
     ff_formats_ref(ff_make_format_list(out_fmts), &ctx->outputs[0]->in_formats);
     return 0;
@@ -94,24 +94,31 @@
     return ff_draw_slice(inlink->dst->outputs[0], y0, h, slice_dir);
 }
 
+static const AVFilterPad alphaextract_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .config_props = config_input,
+        .draw_slice   = draw_slice,
+        .min_perms    = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad alphaextract_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_alphaextract = {
     .name           = "alphaextract",
     .description    = NULL_IF_CONFIG_SMALL("Extract an alpha channel as a "
                       "grayscale image component."),
     .priv_size      = sizeof(AlphaExtractContext),
     .query_formats  = query_formats,
-
-    .inputs    = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_VIDEO,
-          .config_props     = config_input,
-          .draw_slice       = draw_slice,
-          .min_perms        = AV_PERM_READ },
-        { .name = NULL }
-    },
-    .outputs   = (const AVFilterPad[]) {
-      { .name               = "default",
-        .type               = AVMEDIA_TYPE_VIDEO, },
-      { .name = NULL }
-    },
+    .inputs         = alphaextract_inputs,
+    .outputs        = alphaextract_outputs,
 };
diff --git a/libavfilter/vf_alphamerge.c b/libavfilter/vf_alphamerge.c
index 613ca89..f3800db 100644
--- a/libavfilter/vf_alphamerge.c
+++ b/libavfilter/vf_alphamerge.c
@@ -52,12 +52,12 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    enum PixelFormat main_fmts[] = {
-        PIX_FMT_YUVA444P, PIX_FMT_YUVA422P, PIX_FMT_YUVA420P,
-        PIX_FMT_RGBA, PIX_FMT_BGRA, PIX_FMT_ARGB, PIX_FMT_ABGR,
-        PIX_FMT_NONE
+    enum AVPixelFormat main_fmts[] = {
+        AV_PIX_FMT_YUVA444P, AV_PIX_FMT_YUVA422P, AV_PIX_FMT_YUVA420P,
+        AV_PIX_FMT_RGBA, AV_PIX_FMT_BGRA, AV_PIX_FMT_ARGB, AV_PIX_FMT_ABGR,
+        AV_PIX_FMT_NONE
     };
-    enum PixelFormat alpha_fmts[] = { PIX_FMT_GRAY8, PIX_FMT_NONE };
+    enum AVPixelFormat alpha_fmts[] = { AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE };
     AVFilterFormats *main_formats = ff_make_format_list(main_fmts);
     AVFilterFormats *alpha_formats = ff_make_format_list(alpha_fmts);
     ff_formats_ref(main_formats, &ctx->inputs[0]->out_formats);
@@ -95,9 +95,6 @@
     return 0;
 }
 
-static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *picref) {return 0;}
-static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir) {return 0;}
-
 static void draw_frame(AVFilterContext *ctx,
                        AVFilterBufferRef *main_buf,
                        AVFilterBufferRef *alpha_buf)
@@ -127,10 +124,9 @@
                    FFMIN(main_linesize, alpha_linesize));
         }
     }
-    ff_draw_slice(ctx->outputs[0], 0, h, 1);
 }
 
-static int end_frame(AVFilterLink *inlink)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
 {
     AVFilterContext *ctx = inlink->dst;
     AlphaMergeContext *merge = ctx->priv;
@@ -138,8 +134,7 @@
     int is_alpha = (inlink == ctx->inputs[1]);
     struct FFBufQueue *queue =
         (is_alpha ? &merge->queue_alpha : &merge->queue_main);
-    ff_bufqueue_add(ctx, queue, inlink->cur_buf);
-    inlink->cur_buf = NULL;
+    ff_bufqueue_add(ctx, queue, buf);
 
     while (1) {
         AVFilterBufferRef *main_buf, *alpha_buf;
@@ -150,11 +145,9 @@
         main_buf = ff_bufqueue_get(&merge->queue_main);
         alpha_buf = ff_bufqueue_get(&merge->queue_alpha);
 
-        ctx->outputs[0]->out_buf = main_buf;
-        ff_start_frame(ctx->outputs[0], avfilter_ref_buffer(main_buf, ~0));
         merge->frame_requested = 0;
         draw_frame(ctx, main_buf, alpha_buf);
-        ff_end_frame(ctx->outputs[0]);
+        ff_filter_frame(ctx->outputs[0], main_buf);
         avfilter_unref_buffer(alpha_buf);
     }
     return 0;
@@ -176,6 +169,33 @@
     return 0;
 }
 
+static const AVFilterPad alphamerge_inputs[] = {
+    {
+        .name             = "main",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .config_props     = config_input_main,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .filter_frame     = filter_frame,
+        .min_perms        = AV_PERM_READ | AV_PERM_WRITE | AV_PERM_PRESERVE,
+    },{
+        .name             = "alpha",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .filter_frame     = filter_frame,
+        .min_perms        = AV_PERM_READ | AV_PERM_PRESERVE,
+    },
+    { NULL }
+};
+
+static const AVFilterPad alphamerge_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .config_props  = config_output,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_alphamerge = {
     .name           = "alphamerge",
     .description    = NULL_IF_CONFIG_SMALL("Copy the luma value of the second "
@@ -183,29 +203,6 @@
     .uninit         = uninit,
     .priv_size      = sizeof(AlphaMergeContext),
     .query_formats  = query_formats,
-
-    .inputs    = (const AVFilterPad[]) {
-        { .name             = "main",
-          .type             = AVMEDIA_TYPE_VIDEO,
-          .config_props     = config_input_main,
-          .get_video_buffer = ff_null_get_video_buffer,
-          .start_frame      = start_frame,
-          .draw_slice       = draw_slice,
-          .end_frame        = end_frame,
-          .min_perms        = AV_PERM_READ | AV_PERM_WRITE | AV_PERM_PRESERVE },
-        { .name             = "alpha",
-          .type             = AVMEDIA_TYPE_VIDEO,
-          .start_frame      = start_frame,
-          .draw_slice       = draw_slice,
-          .end_frame        = end_frame,
-          .min_perms        = AV_PERM_READ | AV_PERM_PRESERVE },
-        { .name = NULL }
-    },
-    .outputs   = (const AVFilterPad[]) {
-      { .name               = "default",
-        .type               = AVMEDIA_TYPE_VIDEO,
-        .config_props       = config_output,
-        .request_frame      = request_frame },
-      { .name = NULL }
-    },
+    .inputs         = alphamerge_inputs,
+    .outputs        = alphamerge_outputs,
 };
diff --git a/libavfilter/vf_aspect.c b/libavfilter/vf_aspect.c
index 1d0c22b..7869d22 100644
--- a/libavfilter/vf_aspect.c
+++ b/libavfilter/vf_aspect.c
@@ -24,6 +24,7 @@
  */
 
 #include "libavutil/common.h"
+#include "libavutil/opt.h"
 #include "libavutil/mathematics.h"
 #include "libavutil/parseutils.h"
 #include "avfilter.h"
@@ -31,19 +32,46 @@
 #include "video.h"
 
 typedef struct {
+    const AVClass *class;
     AVRational ratio;
+    char *ratio_str;
+    int max;
 } AspectContext;
 
-static av_cold int init(AVFilterContext *ctx, const char *args)
+#define OFFSET(x) offsetof(AspectContext, x)
+#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
+
+static const AVOption options[] = {
+    {"max", "set max value for nominator or denominator in the ratio", OFFSET(max), AV_OPT_TYPE_INT, {.i64=100}, 1, INT_MAX, FLAGS },
+    {"ratio", "set ratio", OFFSET(ratio_str), AV_OPT_TYPE_STRING, {.str="0"}, 0, 0, FLAGS },
+    {"r",     "set ratio", OFFSET(ratio_str), AV_OPT_TYPE_STRING, {.str="0"}, 0, 0, FLAGS },
+    {NULL}
+};
+
+static av_cold int init(AVFilterContext *ctx, const char *args, const AVClass *class)
 {
     AspectContext *aspect = ctx->priv;
-    aspect->ratio = (AVRational) {0, 1};
+    static const char *shorthand[] = { "ratio", "max", NULL };
+    char c;
+    int ret;
+    AVRational q;
 
-    if (args) {
-        if (av_parse_ratio(&aspect->ratio, args, 100, 0, ctx) < 0 ||
-            aspect->ratio.num < 0 || aspect->ratio.den <= 0) {
+    aspect->class = class;
+    av_opt_set_defaults(aspect);
+
+    if (sscanf(args, "%d:%d%c", &q.num, &q.den, &c) == 2) {
+        aspect->ratio_str = av_strdup(args);
+        av_log(ctx, AV_LOG_WARNING,
+               "num:den syntax is deprecated, please use num/den or named options instead\n");
+    } else if ((ret = av_opt_set_from_string(aspect, args, shorthand, "=", ":")) < 0) {
+        return ret;
+    }
+
+    if (aspect->ratio_str) {
+        ret = av_parse_ratio(&aspect->ratio, aspect->ratio_str, aspect->max, 0, ctx);
+        if (ret < 0 || aspect->ratio.num < 0 || aspect->ratio.den <= 0) {
             av_log(ctx, AV_LOG_ERROR,
-                   "Invalid string '%s' for aspect ratio.\n", args);
+                   "Invalid string '%s' for aspect ratio\n", args);
             return AVERROR(EINVAL);
         }
     }
@@ -52,16 +80,31 @@
     return 0;
 }
 
-static int start_frame(AVFilterLink *link, AVFilterBufferRef *picref)
+static int filter_frame(AVFilterLink *link, AVFilterBufferRef *frame)
 {
     AspectContext *aspect = link->dst->priv;
 
-    picref->video->sample_aspect_ratio = aspect->ratio;
-    link->cur_buf = NULL;
-    return ff_start_frame(link->dst->outputs[0], picref);
+    frame->video->sample_aspect_ratio = aspect->ratio;
+    return ff_filter_frame(link->dst->outputs[0], frame);
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    AspectContext *aspect = ctx->priv;
+
+    av_opt_free(aspect);
 }
 
 #if CONFIG_SETDAR_FILTER
+
+#define setdar_options options
+AVFILTER_DEFINE_CLASS(setdar);
+
+static av_cold int setdar_init(AVFilterContext *ctx, const char *args)
+{
+    return init(ctx, args, &setdar_class);
+}
+
 static int setdar_config_props(AVFilterLink *inlink)
 {
     AspectContext *aspect = inlink->dst->priv;
@@ -79,29 +122,52 @@
     return 0;
 }
 
+static const AVFilterPad avfilter_vf_setdar_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .config_props     = setdar_config_props,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .filter_frame     = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_setdar_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_setdar = {
     .name      = "setdar",
     .description = NULL_IF_CONFIG_SMALL("Set the frame display aspect ratio."),
 
-    .init      = init,
+    .init      = setdar_init,
+    .uninit    = uninit,
 
     .priv_size = sizeof(AspectContext),
 
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .config_props     = setdar_config_props,
-                                          .get_video_buffer = ff_null_get_video_buffer,
-                                          .start_frame      = start_frame,
-                                          .end_frame        = ff_null_end_frame },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_setdar_inputs,
 
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO, },
-                                        { .name = NULL}},
+    .outputs   = avfilter_vf_setdar_outputs,
+    .priv_class = &setdar_class,
 };
+
 #endif /* CONFIG_SETDAR_FILTER */
 
 #if CONFIG_SETSAR_FILTER
+
+#define setsar_options options
+AVFILTER_DEFINE_CLASS(setsar);
+
+static av_cold int setsar_init(AVFilterContext *ctx, const char *args)
+{
+    return init(ctx, args, &setsar_class);
+}
+
 static int setsar_config_props(AVFilterLink *inlink)
 {
     AspectContext *aspect = inlink->dst->priv;
@@ -111,24 +177,38 @@
     return 0;
 }
 
+static const AVFilterPad avfilter_vf_setsar_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .config_props     = setsar_config_props,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .filter_frame     = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_setsar_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_setsar = {
     .name      = "setsar",
     .description = NULL_IF_CONFIG_SMALL("Set the pixel sample aspect ratio."),
 
-    .init      = init,
+    .init      = setsar_init,
+    .uninit    = uninit,
 
     .priv_size = sizeof(AspectContext),
 
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .config_props     = setsar_config_props,
-                                          .get_video_buffer = ff_null_get_video_buffer,
-                                          .start_frame      = start_frame,
-                                          .end_frame        = ff_null_end_frame },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_setsar_inputs,
 
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO, },
-                                        { .name = NULL}},
+    .outputs   = avfilter_vf_setsar_outputs,
+    .priv_class = &setsar_class,
 };
+
 #endif /* CONFIG_SETSAR_FILTER */
diff --git a/libavfilter/vf_ass.c b/libavfilter/vf_ass.c
index 6b20631..5f96202 100644
--- a/libavfilter/vf_ass.c
+++ b/libavfilter/vf_ass.c
@@ -54,6 +54,8 @@
 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
 
 static const AVOption ass_options[] = {
+    {"filename",       "set the filename of the ASS file to read",                 OFFSET(filename),   AV_OPT_TYPE_STRING,     {.str = NULL},  CHAR_MIN, CHAR_MAX, FLAGS },
+    {"f",              "set the filename of the ASS file to read",                 OFFSET(filename),   AV_OPT_TYPE_STRING,     {.str = NULL},  CHAR_MIN, CHAR_MAX, FLAGS },
     {"original_size",  "set the size of the original video (used to scale fonts)", OFFSET(original_w), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL},  CHAR_MIN, CHAR_MAX, FLAGS },
     {NULL},
 };
@@ -83,21 +85,20 @@
 static av_cold int init(AVFilterContext *ctx, const char *args)
 {
     AssContext *ass = ctx->priv;
+    static const char *shorthand[] = { "filename", NULL };
     int ret;
 
     ass->class = &ass_class;
     av_opt_set_defaults(ass);
 
-    if (args)
-        ass->filename = av_get_token(&args, ":");
-    if (!ass->filename || !*ass->filename) {
+    if ((ret = av_opt_set_from_string(ass, args, shorthand, "=", ":")) < 0)
+        return ret;
+
+    if (!ass->filename) {
         av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
         return AVERROR(EINVAL);
     }
 
-    if (*args++ == ':' && (ret = av_set_options_string(ass, args, "=", ":")) < 0)
-        return ret;
-
     ass->library = ass_library_init();
     if (!ass->library) {
         av_log(ctx, AV_LOG_ERROR, "Could not initialize libass.\n");
@@ -127,7 +128,7 @@
 {
     AssContext *ass = ctx->priv;
 
-    av_freep(&ass->filename);
+    av_opt_free(ass);
     if (ass->track)
         ass_free_track(ass->track);
     if (ass->renderer)
@@ -156,8 +157,6 @@
     return 0;
 }
 
-static int null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { return 0; }
-
 /* libass stores an RGBA color in the format RRGGBBTT, where TT is the transparency level */
 #define AR(c)  ( (c)>>24)
 #define AG(c)  (((c)>>16)&0xFF)
@@ -179,12 +178,11 @@
     }
 }
 
-static int end_frame(AVFilterLink *inlink)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)
 {
     AVFilterContext *ctx = inlink->dst;
     AVFilterLink *outlink = ctx->outputs[0];
     AssContext *ass = ctx->priv;
-    AVFilterBufferRef *picref = inlink->cur_buf;
     int detect_change = 0;
     double time_ms = picref->pts * av_q2d(inlink->time_base) * 1000;
     ASS_Image *image = ass_render_frame(ass->renderer, ass->track,
@@ -195,10 +193,28 @@
 
     overlay_ass_image(ass, picref, image);
 
-    ff_draw_slice(outlink, 0, picref->video->h, 1);
-    return ff_end_frame(outlink);
+    return ff_filter_frame(outlink, picref);
 }
 
+static const AVFilterPad ass_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .filter_frame     = filter_frame,
+        .config_props     = config_input,
+        .min_perms        = AV_PERM_READ | AV_PERM_WRITE,
+    },
+    { NULL }
+};
+
+static const AVFilterPad ass_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_ass = {
     .name          = "ass",
     .description   = NULL_IF_CONFIG_SMALL("Render subtitles onto input video using the libass library."),
@@ -206,22 +222,7 @@
     .init          = init,
     .uninit        = uninit,
     .query_formats = query_formats,
-
-    .inputs = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_VIDEO,
-          .get_video_buffer = ff_null_get_video_buffer,
-          .start_frame      = ff_null_start_frame,
-          .draw_slice       = null_draw_slice,
-          .end_frame        = end_frame,
-          .config_props     = config_input,
-          .min_perms        = AV_PERM_WRITE | AV_PERM_READ },
-        { .name = NULL}
-    },
-    .outputs = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_VIDEO, },
-        { .name = NULL}
-    },
-    .priv_class = &ass_class,
+    .inputs        = ass_inputs,
+    .outputs       = ass_outputs,
+    .priv_class    = &ass_class,
 };
diff --git a/libavfilter/vf_bbox.c b/libavfilter/vf_bbox.c
index a3b8a23..33b96b5 100644
--- a/libavfilter/vf_bbox.c
+++ b/libavfilter/vf_bbox.c
@@ -43,24 +43,23 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
-        PIX_FMT_YUV420P,
-        PIX_FMT_YUV444P,
-        PIX_FMT_YUV440P,
-        PIX_FMT_YUV422P,
-        PIX_FMT_YUV411P,
-        PIX_FMT_NONE,
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV420P,
+        AV_PIX_FMT_YUV444P,
+        AV_PIX_FMT_YUV440P,
+        AV_PIX_FMT_YUV422P,
+        AV_PIX_FMT_YUV411P,
+        AV_PIX_FMT_NONE,
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
     return 0;
 }
 
-static int end_frame(AVFilterLink *inlink)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)
 {
     AVFilterContext *ctx = inlink->dst;
     BBoxContext *bbox = ctx->priv;
-    AVFilterBufferRef *picref = inlink->cur_buf;
     FFBoundingBox box;
     int has_bbox, w, h;
 
@@ -86,29 +85,34 @@
     av_log(ctx, AV_LOG_INFO, "\n");
 
     bbox->frame++;
-    return ff_end_frame(inlink->dst->outputs[0]);
+    return ff_filter_frame(inlink->dst->outputs[0], picref);
 }
 
+static const AVFilterPad bbox_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .filter_frame     = filter_frame,
+        .min_perms        = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad bbox_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_bbox = {
     .name          = "bbox",
     .description   = NULL_IF_CONFIG_SMALL("Compute bounding box for each frame."),
     .priv_size     = sizeof(BBoxContext),
     .query_formats = query_formats,
     .init          = init,
-
-    .inputs = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_VIDEO,
-          .get_video_buffer = ff_null_get_video_buffer,
-          .start_frame      = ff_null_start_frame,
-          .end_frame        = end_frame,
-          .min_perms        = AV_PERM_READ, },
-        { .name = NULL }
-    },
-
-    .outputs = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_VIDEO },
-        { .name = NULL }
-    },
+    .inputs        = bbox_inputs,
+    .outputs       = bbox_outputs,
 };
diff --git a/libavfilter/vf_blackdetect.c b/libavfilter/vf_blackdetect.c
index cf1b924..f2f2cfa 100644
--- a/libavfilter/vf_blackdetect.c
+++ b/libavfilter/vf_blackdetect.c
@@ -63,19 +63,19 @@
 AVFILTER_DEFINE_CLASS(blackdetect);
 
 #define YUVJ_FORMATS \
-    PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUVJ440P
+    AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ440P
 
-static enum PixelFormat yuvj_formats[] = {
-    YUVJ_FORMATS, PIX_FMT_NONE
+static enum AVPixelFormat yuvj_formats[] = {
+    YUVJ_FORMATS, AV_PIX_FMT_NONE
 };
 
 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,
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NV12,
+        AV_PIX_FMT_NV21, AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV411P,
         YUVJ_FORMATS,
-        PIX_FMT_NONE
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -146,30 +146,20 @@
     return ret;
 }
 
-static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)
 {
     AVFilterContext *ctx = inlink->dst;
     BlackDetectContext *blackdetect = ctx->priv;
-    AVFilterBufferRef *picref = inlink->cur_buf;
+    double picture_black_ratio = 0;
+    const uint8_t *p = picref->data[0];
     int x, i;
-    const uint8_t *p = picref->data[0] + y * picref->linesize[0];
 
-    for (i = 0; i < h; i++) {
+    for (i = 0; i < inlink->h; i++) {
         for (x = 0; x < inlink->w; x++)
             blackdetect->nb_black_pixels += p[x] <= blackdetect->pixel_black_th_i;
         p += picref->linesize[0];
     }
 
-    return ff_draw_slice(ctx->outputs[0], y, h, slice_dir);
-}
-
-static int end_frame(AVFilterLink *inlink)
-{
-    AVFilterContext *ctx = inlink->dst;
-    BlackDetectContext *blackdetect = ctx->priv;
-    AVFilterBufferRef *picref = inlink->cur_buf;
-    double picture_black_ratio = 0;
-
     picture_black_ratio = (double)blackdetect->nb_black_pixels / (inlink->w * inlink->h);
 
     av_log(ctx, AV_LOG_DEBUG,
@@ -194,32 +184,36 @@
     blackdetect->last_picref_pts = picref->pts;
     blackdetect->frame_count++;
     blackdetect->nb_black_pixels = 0;
-    return ff_end_frame(inlink->dst->outputs[0]);
+    return ff_filter_frame(inlink->dst->outputs[0], picref);
 }
 
+static const AVFilterPad blackdetect_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .config_props     = config_input,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .filter_frame     = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad blackdetect_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_blackdetect = {
     .name          = "blackdetect",
     .description   = NULL_IF_CONFIG_SMALL("Detect video intervals that are (almost) black."),
     .priv_size     = sizeof(BlackDetectContext),
     .init          = init,
     .query_formats = query_formats,
-
-    .inputs = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_VIDEO,
-          .config_props     = config_input,
-          .draw_slice       = draw_slice,
-          .get_video_buffer = ff_null_get_video_buffer,
-          .start_frame      = ff_null_start_frame,
-          .end_frame        = end_frame, },
-        { .name = NULL }
-    },
-
-    .outputs = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_VIDEO,
-          .request_frame    = request_frame, },
-        { .name = NULL }
-    },
-    .priv_class = &blackdetect_class,
+    .inputs        = blackdetect_inputs,
+    .outputs       = blackdetect_outputs,
+    .priv_class    = &blackdetect_class,
 };
diff --git a/libavfilter/vf_blackframe.c b/libavfilter/vf_blackframe.c
index 5064040..cf1bcd3 100644
--- a/libavfilter/vf_blackframe.c
+++ b/libavfilter/vf_blackframe.c
@@ -47,10 +47,10 @@
 
 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
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NV12,
+        AV_PIX_FMT_NV21, AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV411P,
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -81,46 +81,54 @@
     return 0;
 }
 
-static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *frame)
 {
     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];
+    int pblack = 0;
+    uint8_t *p = frame->data[0];
 
-    for (i = 0; i < h; i++) {
+    for (i = 0; i < frame->video->h; i++) {
         for (x = 0; x < inlink->w; x++)
             blackframe->nblack += p[x] < blackframe->bthresh;
-        p += picref->linesize[0];
+        p += frame->linesize[0];
     }
 
-    return ff_draw_slice(ctx->outputs[0], y, h, slice_dir);
-}
-
-static int end_frame(AVFilterLink *inlink)
-{
-    AVFilterContext *ctx = inlink->dst;
-    BlackFrameContext *blackframe = ctx->priv;
-    AVFilterBufferRef *picref = inlink->cur_buf;
-    int pblack = 0;
-
-    if (picref->video->key_frame)
+    if (frame->video->key_frame)
         blackframe->last_keyframe = blackframe->frame;
 
     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 "
                "type:%c last_keyframe:%d\n",
-               blackframe->frame, pblack, picref->pos, picref->pts,
-               picref->pts == AV_NOPTS_VALUE ? -1 : picref->pts * av_q2d(inlink->time_base),
-               av_get_picture_type_char(picref->video->pict_type), blackframe->last_keyframe);
+               blackframe->frame, pblack, frame->pos, frame->pts,
+               frame->pts == AV_NOPTS_VALUE ? -1 : frame->pts * av_q2d(inlink->time_base),
+               av_get_picture_type_char(frame->video->pict_type), blackframe->last_keyframe);
 
     blackframe->frame++;
     blackframe->nblack = 0;
-    return ff_end_frame(inlink->dst->outputs[0]);
+    return ff_filter_frame(inlink->dst->outputs[0], frame);
 }
 
+static const AVFilterPad avfilter_vf_blackframe_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .filter_frame     = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_blackframe_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_blackframe = {
     .name        = "blackframe",
     .description = NULL_IF_CONFIG_SMALL("Detect frames that are (almost) black."),
@@ -130,15 +138,7 @@
 
     .query_formats = query_formats,
 
-    .inputs    = (const AVFilterPad[]) {{ .name = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .draw_slice       = draw_slice,
-                                          .get_video_buffer = ff_null_get_video_buffer,
-                                          .start_frame      = ff_null_start_frame,
-                                          .end_frame        = end_frame, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_blackframe_inputs,
 
-    .outputs   = (const AVFilterPad[]) {{ .name       = "default",
-                                    .type             = AVMEDIA_TYPE_VIDEO },
-                                  { .name = NULL}},
+    .outputs   = avfilter_vf_blackframe_outputs,
 };
diff --git a/libavfilter/vf_boxblur.c b/libavfilter/vf_boxblur.c
index c5056c5..df250c8 100644
--- a/libavfilter/vf_boxblur.c
+++ b/libavfilter/vf_boxblur.c
@@ -124,13 +124,13 @@
 
 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_YUVA420P,
-        PIX_FMT_YUV440P,  PIX_FMT_GRAY8,
-        PIX_FMT_YUVJ444P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ420P,
-        PIX_FMT_YUVJ440P,
-        PIX_FMT_NONE
+    enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV444P,  AV_PIX_FMT_YUV422P,  AV_PIX_FMT_YUV420P,
+        AV_PIX_FMT_YUV411P,  AV_PIX_FMT_YUV410P,  AV_PIX_FMT_YUVA420P,
+        AV_PIX_FMT_YUV440P,  AV_PIX_FMT_GRAY8,
+        AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ420P,
+        AV_PIX_FMT_YUVJ440P,
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -139,9 +139,9 @@
 
 static int config_input(AVFilterLink *inlink)
 {
-    AVFilterContext *ctx = inlink->dst;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
+    AVFilterContext    *ctx = inlink->dst;
     BoxBlurContext *boxblur = ctx->priv;
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[inlink->format];
     int w = inlink->w, h = inlink->h;
     int cw, ch;
     double var_values[VARS_NB], res;
@@ -155,12 +155,12 @@
     boxblur->hsub = desc->log2_chroma_w;
     boxblur->vsub = desc->log2_chroma_h;
 
-    var_values[VAR_W]  = inlink->w;
-    var_values[VAR_H]  = inlink->h;
+    var_values[VAR_W]       = inlink->w;
+    var_values[VAR_H]       = inlink->h;
     var_values[VAR_CW] = cw = w>>boxblur->hsub;
     var_values[VAR_CH] = ch = h>>boxblur->vsub;
-    var_values[VAR_HSUB] = 1<<boxblur->hsub;
-    var_values[VAR_VSUB] = 1<<boxblur->vsub;
+    var_values[VAR_HSUB]    = 1<<boxblur->hsub;
+    var_values[VAR_VSUB]    = 1<<boxblur->vsub;
 
 #define EVAL_RADIUS_EXPR(comp)                                          \
     expr = boxblur->comp##_radius_expr;                                 \
@@ -226,9 +226,9 @@
      * and subtracting 1 input pixel.
      * The following code adopts this faster variant.
      */
-    int x, sum = 0;
     const int length = radius*2 + 1;
     const int inv = ((1<<16) + length/2)/length;
+    int x, sum = 0;
 
     for (x = 0; x < radius; x++)
         sum += src[x*src_step]<<1;
@@ -302,36 +302,60 @@
                    h, radius, power, temp);
 }
 
-static int null_draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir) { return 0; }
-
-static int end_frame(AVFilterLink *inlink)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *in)
 {
     AVFilterContext *ctx = inlink->dst;
     BoxBlurContext *boxblur = ctx->priv;
     AVFilterLink *outlink = inlink->dst->outputs[0];
-    AVFilterBufferRef *inpicref  = inlink ->cur_buf;
-    AVFilterBufferRef *outpicref = outlink->out_buf;
+    AVFilterBufferRef *out;
     int plane;
-    int cw = inlink->w >> boxblur->hsub, ch = inlink->h >> boxblur->vsub;
+    int cw = inlink->w >> boxblur->hsub, ch = in->video->h >> boxblur->vsub;
     int w[4] = { inlink->w, cw, cw, inlink->w };
-    int h[4] = { inlink->h, ch, ch, inlink->h };
+    int h[4] = { in->video->h, ch, ch, in->video->h };
 
-    for (plane = 0; inpicref->data[plane] && plane < 4; plane++)
-        hblur(outpicref->data[plane], outpicref->linesize[plane],
-              inpicref ->data[plane], inpicref ->linesize[plane],
+    out = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+    if (!out) {
+        avfilter_unref_bufferp(&in);
+        return AVERROR(ENOMEM);
+    }
+    avfilter_copy_buffer_ref_props(out, in);
+
+    for (plane = 0; in->data[plane] && plane < 4; plane++)
+        hblur(out->data[plane], out->linesize[plane],
+              in ->data[plane], in ->linesize[plane],
               w[plane], h[plane], boxblur->radius[plane], boxblur->power[plane],
               boxblur->temp);
 
-    for (plane = 0; inpicref->data[plane] && plane < 4; plane++)
-        vblur(outpicref->data[plane], outpicref->linesize[plane],
-              outpicref->data[plane], outpicref->linesize[plane],
+    for (plane = 0; in->data[plane] && plane < 4; plane++)
+        vblur(out->data[plane], out->linesize[plane],
+              out->data[plane], out->linesize[plane],
               w[plane], h[plane], boxblur->radius[plane], boxblur->power[plane],
               boxblur->temp);
 
-    ff_draw_slice(outlink, 0, inlink->h, 1);
-    return ff_end_frame(outlink);
+    avfilter_unref_bufferp(&in);
+
+    return ff_filter_frame(outlink, out);
 }
 
+static const AVFilterPad avfilter_vf_boxblur_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .config_props = config_input,
+        .filter_frame = filter_frame,
+        .min_perms    = AV_PERM_READ
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_boxblur_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_boxblur = {
     .name          = "boxblur",
     .description   = NULL_IF_CONFIG_SMALL("Blur the input."),
@@ -340,14 +364,6 @@
     .uninit        = uninit,
     .query_formats = query_formats,
 
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .config_props     = config_input,
-                                          .draw_slice       = null_draw_slice,
-                                          .end_frame        = end_frame,
-                                          .min_perms        = AV_PERM_READ },
-                                        { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_boxblur_inputs,
+    .outputs   = avfilter_vf_boxblur_outputs,
 };
diff --git a/libavfilter/vf_colormatrix.c b/libavfilter/vf_colormatrix.c
index ca5a39d..571b9d4 100644
--- a/libavfilter/vf_colormatrix.c
+++ b/libavfilter/vf_colormatrix.c
@@ -31,6 +31,7 @@
 #include <float.h>
 #include "avfilter.h"
 #include "formats.h"
+#include "internal.h"
 #include "video.h"
 #include "libavutil/pixdesc.h"
 #include "libavutil/avstring.h"
@@ -60,7 +61,6 @@
     char src[256];
     char dst[256];
     int hsub, vsub;
-    AVFilterBufferRef *outpicref;
 } ColorMatrixContext;
 
 #define ma m[0][0]
@@ -308,7 +308,7 @@
 {
     AVFilterContext *ctx = inlink->dst;
     ColorMatrixContext *color = ctx->priv;
-    const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
+    const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
 
     color->hsub = pix_desc->log2_chroma_w;
     color->vsub = pix_desc->log2_chroma_h;
@@ -320,11 +320,11 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
-        PIX_FMT_YUV422P,
-        PIX_FMT_YUV420P,
-        PIX_FMT_UYVY422,
-        PIX_FMT_NONE
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV422P,
+        AV_PIX_FMT_YUV420P,
+        AV_PIX_FMT_UYVY422,
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -332,42 +332,49 @@
     return 0;
 }
 
-static AVFilterBufferRef *get_video_buffer(AVFilterLink *inlink, int perms, int w, int h)
-{
-    AVFilterBufferRef *picref =
-        ff_get_video_buffer(inlink->dst->outputs[0], perms, w, h);
-    return picref;
-}
-
-static int start_frame(AVFilterLink *link, AVFilterBufferRef *picref)
+static int filter_frame(AVFilterLink *link, AVFilterBufferRef *in)
 {
     AVFilterContext *ctx = link->dst;
     ColorMatrixContext *color = ctx->priv;
-    AVFilterBufferRef *outpicref = avfilter_ref_buffer(picref, ~0);
+    AVFilterLink *outlink = ctx->outputs[0];
+    AVFilterBufferRef *out;
 
-    color->outpicref = outpicref;
+    out = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+    if (!out) {
+        avfilter_unref_bufferp(&in);
+        return AVERROR(ENOMEM);
+    }
+    avfilter_copy_buffer_ref_props(out, in);
 
-    return ff_start_frame(link->dst->outputs[0], outpicref);
-}
-
-static int end_frame(AVFilterLink *link)
-{
-    AVFilterContext *ctx = link->dst;
-    ColorMatrixContext *color = ctx->priv;
-    AVFilterBufferRef *out = color->outpicref;
-
-    if (link->cur_buf->format == PIX_FMT_YUV422P)
-        process_frame_yuv422p(color, out, link->cur_buf);
-    else if (link->cur_buf->format == PIX_FMT_YUV420P)
-        process_frame_yuv420p(color, out, link->cur_buf);
+    if (in->format == AV_PIX_FMT_YUV422P)
+        process_frame_yuv422p(color, out, in);
+    else if (in->format == AV_PIX_FMT_YUV420P)
+        process_frame_yuv420p(color, out, in);
     else
-        process_frame_uyvy422(color, out, link->cur_buf);
+        process_frame_uyvy422(color, out, in);
 
-    ff_draw_slice(ctx->outputs[0], 0, link->dst->outputs[0]->h, 1);
-    return ff_end_frame(ctx->outputs[0]);
+    avfilter_unref_bufferp(&in);
+    return ff_filter_frame(outlink, out);
 }
 
-static int null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { return 0; }
+static const AVFilterPad colormatrix_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .config_props     = config_input,
+        .min_perms        = AV_PERM_READ,
+        .filter_frame     = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad colormatrix_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
 
 AVFilter avfilter_vf_colormatrix = {
     .name          = "colormatrix",
@@ -376,18 +383,6 @@
     .priv_size     = sizeof(ColorMatrixContext),
     .init          = init,
     .query_formats = query_formats,
-
-    .inputs    = (AVFilterPad[]) {{ .name             = "default",
-                                    .type             = AVMEDIA_TYPE_VIDEO,
-                                    .config_props     = config_input,
-                                    .min_perms        = AV_PERM_READ | AV_PERM_WRITE,
-                                    .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, },
-                                  { .name = NULL }},
+    .inputs        = colormatrix_inputs,
+    .outputs       = colormatrix_outputs,
 };
diff --git a/libavfilter/vf_copy.c b/libavfilter/vf_copy.c
index d62108a..a25e282 100644
--- a/libavfilter/vf_copy.c
+++ b/libavfilter/vf_copy.c
@@ -26,18 +26,28 @@
 #include "internal.h"
 #include "video.h"
 
+static const AVFilterPad avfilter_vf_copy_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .rej_perms        = ~0
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_copy_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_copy = {
     .name      = "copy",
     .description = NULL_IF_CONFIG_SMALL("Copy the input video unchanged to the output."),
 
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .get_video_buffer = ff_null_get_video_buffer,
-                                          .start_frame      = ff_null_start_frame,
-                                          .end_frame        = ff_null_end_frame,
-                                          .rej_perms        = ~0 },
-                                        { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_copy_inputs,
+    .outputs   = avfilter_vf_copy_outputs,
 };
diff --git a/libavfilter/vf_crop.c b/libavfilter/vf_crop.c
index 4e794df..d0f464f 100644
--- a/libavfilter/vf_crop.c
+++ b/libavfilter/vf_crop.c
@@ -92,30 +92,30 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
-        PIX_FMT_RGB48BE,      PIX_FMT_RGB48LE,
-        PIX_FMT_BGR48BE,      PIX_FMT_BGR48LE,
-        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
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_RGB48BE,      AV_PIX_FMT_RGB48LE,
+        AV_PIX_FMT_BGR48BE,      AV_PIX_FMT_BGR48LE,
+        AV_PIX_FMT_ARGB,         AV_PIX_FMT_RGBA,
+        AV_PIX_FMT_ABGR,         AV_PIX_FMT_BGRA,
+        AV_PIX_FMT_RGB24,        AV_PIX_FMT_BGR24,
+        AV_PIX_FMT_RGB565BE,     AV_PIX_FMT_RGB565LE,
+        AV_PIX_FMT_RGB555BE,     AV_PIX_FMT_RGB555LE,
+        AV_PIX_FMT_BGR565BE,     AV_PIX_FMT_BGR565LE,
+        AV_PIX_FMT_BGR555BE,     AV_PIX_FMT_BGR555LE,
+        AV_PIX_FMT_GRAY16BE,     AV_PIX_FMT_GRAY16LE,
+        AV_PIX_FMT_YUV420P16LE,  AV_PIX_FMT_YUV420P16BE,
+        AV_PIX_FMT_YUV422P16LE,  AV_PIX_FMT_YUV422P16BE,
+        AV_PIX_FMT_YUV444P16LE,  AV_PIX_FMT_YUV444P16BE,
+        AV_PIX_FMT_YUV444P,      AV_PIX_FMT_YUV422P,
+        AV_PIX_FMT_YUV420P,      AV_PIX_FMT_YUV411P,
+        AV_PIX_FMT_YUV410P,      AV_PIX_FMT_YUV440P,
+        AV_PIX_FMT_YUVJ444P,     AV_PIX_FMT_YUVJ422P,
+        AV_PIX_FMT_YUVJ420P,     AV_PIX_FMT_YUVJ440P,
+        AV_PIX_FMT_YUVA420P,
+        AV_PIX_FMT_RGB8,         AV_PIX_FMT_BGR8,
+        AV_PIX_FMT_RGB4_BYTE,    AV_PIX_FMT_BGR4_BYTE,
+        AV_PIX_FMT_PAL8,         AV_PIX_FMT_GRAY8,
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -165,7 +165,7 @@
 {
     AVFilterContext *ctx = link->dst;
     CropContext *crop = ctx->priv;
-    const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[link->format];
+    const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(link->format);
     int ret;
     const char *expr;
     double res;
@@ -186,8 +186,8 @@
     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;
+    crop->hsub = pix_desc->log2_chroma_w;
+    crop->vsub = pix_desc->log2_chroma_h;
 
     if ((ret = av_expr_parse_and_eval(&res, (expr = crop->ow_expr),
                                       var_names, crop->var_values,
@@ -262,23 +262,19 @@
     return 0;
 }
 
-static int start_frame(AVFilterLink *link, AVFilterBufferRef *picref)
+static int filter_frame(AVFilterLink *link, AVFilterBufferRef *frame)
 {
     AVFilterContext *ctx = link->dst;
     CropContext *crop = ctx->priv;
-    AVFilterBufferRef *ref2;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
     int i;
 
-    ref2 = avfilter_ref_buffer(picref, ~0);
-    if (!ref2)
-        return AVERROR(ENOMEM);
+    frame->video->w = crop->w;
+    frame->video->h = crop->h;
 
-    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_T] = frame->pts == AV_NOPTS_VALUE ?
+        NAN : frame->pts * av_q2d(link->time_base);
+    crop->var_values[VAR_POS] = frame->pos == -1 ? NAN : frame->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);
@@ -297,54 +293,49 @@
             (int)crop->var_values[VAR_N], crop->var_values[VAR_T], crop->x,
             crop->y, crop->x+crop->w, crop->y+crop->h);
 
-    ref2->data[0] += crop->y * ref2->linesize[0];
-    ref2->data[0] += crop->x * crop->max_step[0];
+    frame->data[0] += crop->y * frame->linesize[0];
+    frame->data[0] += crop->x * crop->max_step[0];
 
-    if (!(av_pix_fmt_descriptors[link->format].flags & PIX_FMT_PAL ||
-          av_pix_fmt_descriptors[link->format].flags & PIX_FMT_PSEUDOPAL)) {
+    if (!(desc->flags & PIX_FMT_PAL || desc->flags & PIX_FMT_PSEUDOPAL)) {
         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->max_step[i]) >> crop->hsub;
+            if (frame->data[i]) {
+                frame->data[i] += (crop->y >> crop->vsub) * frame->linesize[i];
+                frame->data[i] += (crop->x * crop->max_step[i]) >> crop->hsub;
             }
         }
     }
 
     /* alpha plane */
-    if (ref2->data[3]) {
-        ref2->data[3] += crop->y * ref2->linesize[3];
-        ref2->data[3] += crop->x * crop->max_step[3];
+    if (frame->data[3]) {
+        frame->data[3] += crop->y * frame->linesize[3];
+        frame->data[3] += crop->x * crop->max_step[3];
     }
 
-    return ff_start_frame(link->dst->outputs[0], ref2);
-}
-
-static int draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
-{
-    AVFilterContext *ctx = link->dst;
-    CropContext *crop = ctx->priv;
-
-    if (y >= crop->y + crop->h || y + h <= crop->y)
-        return 0;
-
-    if (y < crop->y) {
-        h -= crop->y - y;
-        y  = crop->y;
-    }
-    if (y + h > crop->y + crop->h)
-        h = crop->y + crop->h - y;
-
-    return ff_draw_slice(ctx->outputs[0], y - crop->y, h, slice_dir);
-}
-
-static int end_frame(AVFilterLink *link)
-{
-    CropContext *crop = link->dst->priv;
-
     crop->var_values[VAR_N] += 1.0;
-    return ff_end_frame(link->dst->outputs[0]);
+
+    return ff_filter_frame(link->dst->outputs[0], frame);
 }
 
+static const AVFilterPad avfilter_vf_crop_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .filter_frame     = filter_frame,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .config_props     = config_input,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_crop_outputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .config_props = config_output,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_crop = {
     .name      = "crop",
     .description = NULL_IF_CONFIG_SMALL("Crop the input video to width:height:x:y."),
@@ -355,16 +346,6 @@
     .init          = init,
     .uninit        = uninit,
 
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .start_frame      = start_frame,
-                                          .draw_slice       = draw_slice,
-                                          .end_frame        = end_frame,
-                                          .get_video_buffer = ff_null_get_video_buffer,
-                                          .config_props     = config_input, },
-                                        { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .config_props     = config_output, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_crop_inputs,
+    .outputs   = avfilter_vf_crop_outputs,
 };
diff --git a/libavfilter/vf_cropdetect.c b/libavfilter/vf_cropdetect.c
index bed4bfd..f91c522 100644
--- a/libavfilter/vf_cropdetect.c
+++ b/libavfilter/vf_cropdetect.c
@@ -43,13 +43,13 @@
 
 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
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVJ420P,
+        AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUVJ422P,
+        AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUVJ444P,
+        AV_PIX_FMT_YUV411P, AV_PIX_FMT_GRAY8,
+        AV_PIX_FMT_NV12,    AV_PIX_FMT_NV21,
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -107,7 +107,7 @@
     CropDetectContext *cd = ctx->priv;
 
     av_image_fill_max_pixsteps(cd->max_pixsteps, NULL,
-                               &av_pix_fmt_descriptors[inlink->format]);
+                               av_pix_fmt_desc_get(inlink->format));
 
     cd->x1 = inlink->w - 1;
     cd->y1 = inlink->h - 1;
@@ -117,11 +117,10 @@
     return 0;
 }
 
-static int end_frame(AVFilterLink *inlink)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *frame)
 {
     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;
 
@@ -129,36 +128,36 @@
     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->x1 = frame->video->w-1;
+            cd->y1 = frame->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) {
+            if (checkline(ctx, frame->data[0] + frame->linesize[0] * y, bpp, frame->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) {
+        for (y = frame->video->h-1; y > cd->y2; y--) {
+            if (checkline(ctx, frame->data[0] + frame->linesize[0] * y, bpp, frame->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) {
+            if (checkline(ctx, frame->data[0] + bpp*y, frame->linesize[0], frame->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) {
+        for (y = frame->video->w-1; y > cd->x2; y--) {
+            if (checkline(ctx, frame->data[0] + bpp*y, frame->linesize[0], frame->video->h, bpp) > cd->limit) {
                 cd->x2 = y;
                 break;
             }
@@ -189,14 +188,33 @@
 
         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),
+               cd->x1, cd->x2, cd->y1, cd->y2, w, h, x, y, frame->pos, frame->pts,
+               frame->pts == AV_NOPTS_VALUE ? -1 : frame->pts * av_q2d(inlink->time_base),
                w, h, x, y);
     }
 
-    return ff_end_frame(inlink->dst->outputs[0]);
+    return ff_filter_frame(inlink->dst->outputs[0], frame);
 }
 
+static const AVFilterPad avfilter_vf_cropdetect_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .config_props     = config_input,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .filter_frame     = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_cropdetect_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_cropdetect = {
     .name        = "cropdetect",
     .description = NULL_IF_CONFIG_SMALL("Auto-detect crop size."),
@@ -206,15 +224,7 @@
 
     .query_formats = query_formats,
 
-    .inputs    = (const AVFilterPad[]) {{ .name = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .config_props     = config_input,
-                                          .get_video_buffer = ff_null_get_video_buffer,
-                                          .start_frame      = ff_null_start_frame,
-                                          .end_frame        = end_frame, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_cropdetect_inputs,
 
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO },
-                                        { .name = NULL}},
+    .outputs   = avfilter_vf_cropdetect_outputs,
 };
diff --git a/libavfilter/vf_decimate.c b/libavfilter/vf_decimate.c
index bf3d7fe..267a435 100644
--- a/libavfilter/vf_decimate.c
+++ b/libavfilter/vf_decimate.c
@@ -161,14 +161,14 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
-        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
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV444P,      AV_PIX_FMT_YUV422P,
+        AV_PIX_FMT_YUV420P,      AV_PIX_FMT_YUV411P,
+        AV_PIX_FMT_YUV410P,      AV_PIX_FMT_YUV440P,
+        AV_PIX_FMT_YUVJ444P,     AV_PIX_FMT_YUVJ422P,
+        AV_PIX_FMT_YUVJ420P,     AV_PIX_FMT_YUVJ440P,
+        AV_PIX_FMT_YUVA420P,
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -180,21 +180,16 @@
 {
     AVFilterContext *ctx = inlink->dst;
     DecimateContext *decimate = ctx->priv;
-    const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
+    const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
     decimate->hsub = pix_desc->log2_chroma_w;
     decimate->vsub = pix_desc->log2_chroma_h;
 
     return 0;
 }
 
-static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *picref) { return 0; }
-
-static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir) { return 0; }
-
-static int end_frame(AVFilterLink *inlink)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *cur)
 {
     DecimateContext *decimate = inlink->dst->priv;
-    AVFilterBufferRef *cur = inlink->cur_buf;
     AVFilterLink *outlink = inlink->dst->outputs[0];
     int ret;
 
@@ -206,10 +201,7 @@
         inlink->cur_buf = NULL;
         decimate->drop_count = FFMIN(-1, decimate->drop_count-1);
 
-        if ((ret = ff_start_frame(outlink,
-                                  avfilter_ref_buffer(cur, ~AV_PERM_WRITE)) < 0) ||
-            (ret = ff_draw_slice(outlink, 0, inlink->h, 1)) < 0 ||
-            (ret = ff_end_frame(outlink)) < 0)
+        if (ret = ff_filter_frame(outlink, avfilter_ref_buffer(cur, ~AV_PERM_WRITE)) < 0)
             return ret;
     }
 
@@ -219,6 +211,9 @@
            av_ts2str(cur->pts), av_ts2timestr(cur->pts, &inlink->time_base),
            decimate->drop_count);
 
+    if (decimate->drop_count > 0)
+        avfilter_unref_buffer(cur);
+
     return 0;
 }
 
@@ -235,6 +230,27 @@
     return ret;
 }
 
+static const AVFilterPad decimate_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .config_props     = config_input,
+        .filter_frame     = filter_frame,
+        .min_perms        = AV_PERM_READ | AV_PERM_PRESERVE,
+    },
+    { NULL }
+};
+
+static const AVFilterPad decimate_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_decimate = {
     .name        = "decimate",
     .description = NULL_IF_CONFIG_SMALL("Remove near-duplicate frames."),
@@ -243,26 +259,6 @@
 
     .priv_size = sizeof(DecimateContext),
     .query_formats = query_formats,
-
-    .inputs = (const AVFilterPad[]) {
-        {
-            .name             = "default",
-            .type             = AVMEDIA_TYPE_VIDEO,
-            .get_video_buffer = ff_null_get_video_buffer,
-            .config_props     = config_input,
-            .start_frame      = start_frame,
-            .draw_slice       = draw_slice,
-            .end_frame        = end_frame,
-            .min_perms        = AV_PERM_READ | AV_PERM_PRESERVE,
-        },
-        { .name = NULL }
-    },
-    .outputs = (const AVFilterPad[]) {
-        {
-            .name          = "default",
-            .type          = AVMEDIA_TYPE_VIDEO,
-            .request_frame = request_frame,
-        },
-        { .name = NULL }
-    },
+    .inputs        = decimate_inputs,
+    .outputs       = decimate_outputs,
 };
diff --git a/libavfilter/vf_delogo.c b/libavfilter/vf_delogo.c
index d4e9014..3c9843f 100644
--- a/libavfilter/vf_delogo.c
+++ b/libavfilter/vf_delogo.c
@@ -80,12 +80,12 @@
     topright = src+logo_y1     * src_linesize+logo_x2-1;
     botleft  = src+(logo_y2-1) * src_linesize+logo_x1;
 
-    dst += (logo_y1+1)*dst_linesize;
-    src += (logo_y1+1)*src_linesize;
-
     if (!direct)
         av_image_copy_plane(dst, dst_linesize, src, src_linesize, w, h);
 
+    dst += (logo_y1+1)*dst_linesize;
+    src += (logo_y1+1)*src_linesize;
+
     for (y = logo_y1+1; y < logo_y2-1; y++) {
         for (x = logo_x1+1,
              xdst = dst+logo_x1+1,
@@ -157,11 +157,11 @@
 
 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_YUV440P,
-        PIX_FMT_YUVA420P, PIX_FMT_GRAY8,
-        PIX_FMT_NONE
+    enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV444P,  AV_PIX_FMT_YUV422P,  AV_PIX_FMT_YUV420P,
+        AV_PIX_FMT_YUV411P,  AV_PIX_FMT_YUV410P,  AV_PIX_FMT_YUV440P,
+        AV_PIX_FMT_YUVA420P, AV_PIX_FMT_GRAY8,
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -209,29 +209,39 @@
     return 0;
 }
 
-static int null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
-{
-    return 0;
-}
-
-static int end_frame(AVFilterLink *inlink)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *in)
 {
     DelogoContext *delogo = inlink->dst->priv;
     AVFilterLink *outlink = inlink->dst->outputs[0];
-    AVFilterBufferRef *inpicref  = inlink ->cur_buf;
-    AVFilterBufferRef *outpicref = outlink->out_buf;
-    int direct = inpicref->buf == outpicref->buf;
-    int hsub0 = av_pix_fmt_descriptors[inlink->format].log2_chroma_w;
-    int vsub0 = av_pix_fmt_descriptors[inlink->format].log2_chroma_h;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
+    AVFilterBufferRef *out;
+    int hsub0 = desc->log2_chroma_w;
+    int vsub0 = desc->log2_chroma_h;
+    int direct = 0;
     int plane;
-    int ret;
 
-    for (plane = 0; plane < 4 && inpicref->data[plane]; plane++) {
+    if (in->perms & AV_PERM_WRITE) {
+        direct = 1;
+        out = in;
+    } else {
+        out = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+        if (!out) {
+            avfilter_unref_bufferp(&in);
+            return AVERROR(ENOMEM);
+        }
+
+        avfilter_copy_buffer_ref_props(out, in);
+
+        out->video->w = outlink->w;
+        out->video->h = outlink->h;
+    }
+
+    for (plane = 0; plane < 4 && in->data[plane]; plane++) {
         int hsub = plane == 1 || plane == 2 ? hsub0 : 0;
         int vsub = plane == 1 || plane == 2 ? vsub0 : 0;
 
-        apply_delogo(outpicref->data[plane], outpicref->linesize[plane],
-                     inpicref ->data[plane], inpicref ->linesize[plane],
+        apply_delogo(out->data[plane], out->linesize[plane],
+                     in ->data[plane], in ->linesize[plane],
                      inlink->w>>hsub, inlink->h>>vsub,
                      delogo->x>>hsub, delogo->y>>vsub,
                      delogo->w>>hsub, delogo->h>>vsub,
@@ -239,12 +249,31 @@
                      delogo->show, direct);
     }
 
-    if ((ret = ff_draw_slice(outlink, 0, inlink->h, 1)) < 0 ||
-        (ret = ff_end_frame(outlink)) < 0)
-        return ret;
-    return 0;
+    if (!direct)
+        avfilter_unref_bufferp(&in);
+
+    return ff_filter_frame(outlink, out);
 }
 
+static const AVFilterPad avfilter_vf_delogo_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .filter_frame     = filter_frame,
+        .min_perms        = AV_PERM_WRITE | AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_delogo_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_delogo = {
     .name          = "delogo",
     .description   = NULL_IF_CONFIG_SMALL("Remove logo from input video."),
@@ -252,15 +281,7 @@
     .init          = init,
     .query_formats = query_formats,
 
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .get_video_buffer = ff_null_get_video_buffer,
-                                          .start_frame      = ff_inplace_start_frame,
-                                          .draw_slice       = null_draw_slice,
-                                          .end_frame        = end_frame,
-                                          .min_perms        = AV_PERM_WRITE | AV_PERM_READ },
-                                        { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_delogo_inputs,
+    .outputs   = avfilter_vf_delogo_outputs,
+    .priv_class = &delogo_class,
 };
diff --git a/libavfilter/vf_deshake.c b/libavfilter/vf_deshake.c
index ac0a013..92fb1ea 100644
--- a/libavfilter/vf_deshake.c
+++ b/libavfilter/vf_deshake.c
@@ -59,8 +59,8 @@
 
 #include "transform.h"
 
-#define CHROMA_WIDTH(link)  -((-link->w) >> av_pix_fmt_descriptors[link->format].log2_chroma_w)
-#define CHROMA_HEIGHT(link) -((-link->h) >> av_pix_fmt_descriptors[link->format].log2_chroma_h)
+#define CHROMA_WIDTH(link)  -((-link->w) >> av_pix_fmt_desc_get(link->format)->log2_chroma_w)
+#define CHROMA_HEIGHT(link) -((-link->h) >> av_pix_fmt_desc_get(link->format)->log2_chroma_h)
 
 enum SearchMethod {
     EXHAUSTIVE,        ///< Search all possible positions
@@ -386,10 +386,10 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    enum PixelFormat pix_fmts[] = {
-        PIX_FMT_YUV420P,  PIX_FMT_YUV422P,  PIX_FMT_YUV444P,  PIX_FMT_YUV410P,
-        PIX_FMT_YUV411P,  PIX_FMT_YUV440P,  PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P,
-        PIX_FMT_YUVJ444P, PIX_FMT_YUVJ440P, PIX_FMT_NONE
+    enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV420P,  AV_PIX_FMT_YUV422P,  AV_PIX_FMT_YUV444P,  AV_PIX_FMT_YUV410P,
+        AV_PIX_FMT_YUV411P,  AV_PIX_FMT_YUV440P,  AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P,
+        AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -538,6 +538,26 @@
     return 0;
 }
 
+static const AVFilterPad deshake_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .draw_slice   = draw_slice,
+        .end_frame    = end_frame,
+        .config_props = config_props,
+        .min_perms    = AV_PERM_READ | AV_PERM_PRESERVE,
+    },
+    { NULL }
+};
+
+static const AVFilterPad deshake_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_deshake = {
     .name      = "deshake",
     .description = NULL_IF_CONFIG_SMALL("Stabilize shaky video."),
@@ -547,16 +567,6 @@
     .init = init,
     .uninit = uninit,
     .query_formats = query_formats,
-
-    .inputs    = (const AVFilterPad[]) {{ .name       = "default",
-                                    .type             = AVMEDIA_TYPE_VIDEO,
-                                    .draw_slice       = draw_slice,
-                                    .end_frame        = end_frame,
-                                    .config_props     = config_props,
-                                    .min_perms        = AV_PERM_READ | AV_PERM_PRESERVE, },
-                                  { .name = NULL}},
-
-    .outputs   = (const AVFilterPad[]) {{ .name       = "default",
-                                    .type             = AVMEDIA_TYPE_VIDEO, },
-                                  { .name = NULL}},
+    .inputs        = deshake_inputs,
+    .outputs       = deshake_outputs,
 };
diff --git a/libavfilter/vf_drawbox.c b/libavfilter/vf_drawbox.c
index 3067f21..5046e7e 100644
--- a/libavfilter/vf_drawbox.c
+++ b/libavfilter/vf_drawbox.c
@@ -26,6 +26,7 @@
 
 #include "libavutil/colorspace.h"
 #include "libavutil/common.h"
+#include "libavutil/opt.h"
 #include "libavutil/pixdesc.h"
 #include "libavutil/parseutils.h"
 #include "avfilter.h"
@@ -36,42 +37,75 @@
 enum { Y, U, V, A };
 
 typedef struct {
-    int x, y, w, h;
+    const AVClass *class;
+    int x, y, w, h, thickness;
+    char *color_str;
     unsigned char yuv_color[4];
+    int invert_color; ///< invert luma color
     int vsub, hsub;   ///< chroma subsampling
 } DrawBoxContext;
 
+#define OFFSET(x) offsetof(DrawBoxContext, x)
+#define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
+
+static const AVOption drawbox_options[] = {
+    { "x",           "set the box top-left corner x position", OFFSET(x), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX, FLAGS },
+    { "y",           "set the box top-left corner y position", OFFSET(y), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX, FLAGS },
+    { "width",       "set the box width",  OFFSET(w), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS },
+    { "w",           "set the box width",  OFFSET(w), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS },
+    { "height",      "set the box height", OFFSET(h), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS },
+    { "h",           "set the box height", OFFSET(h), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS },
+    { "color",       "set the box edge color", OFFSET(color_str), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS },
+    { "c",           "set the box edge color", OFFSET(color_str), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS },
+    { "thickness",   "set the box maximum thickness", OFFSET(thickness), AV_OPT_TYPE_INT, {.i64=4}, 0, INT_MAX, FLAGS },
+    { "t",           "set the box maximum thickness", OFFSET(thickness), AV_OPT_TYPE_INT, {.i64=4}, 0, INT_MAX, FLAGS },
+    {NULL},
+};
+
+AVFILTER_DEFINE_CLASS(drawbox);
+
 static av_cold int init(AVFilterContext *ctx, const char *args)
 {
-    DrawBoxContext *drawbox= ctx->priv;
-    char color_str[1024] = "black";
+    DrawBoxContext *drawbox = ctx->priv;
     uint8_t rgba_color[4];
+    static const char *shorthand[] = { "x", "y", "w", "h", "color", "thickness", NULL };
+    int ret;
 
-    drawbox->x = drawbox->y = drawbox->w = drawbox->h = 0;
+    drawbox->class = &drawbox_class;
+    av_opt_set_defaults(drawbox);
 
-    if (args)
-        sscanf(args, "%d:%d:%d:%d:%s",
-               &drawbox->x, &drawbox->y, &drawbox->w, &drawbox->h, color_str);
+    if ((ret = av_opt_set_from_string(drawbox, args, shorthand, "=", ":")) < 0)
+        return ret;
 
-    if (av_parse_color(rgba_color, color_str, -1, ctx) < 0)
+    if (!strcmp(drawbox->color_str, "invert"))
+        drawbox->invert_color = 1;
+    else if (av_parse_color(rgba_color, drawbox->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];
+    if (!drawbox->invert_color) {
+        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 av_cold void uninit(AVFilterContext *ctx)
+{
+    DrawBoxContext *drawbox = ctx->priv;
+    av_opt_free(drawbox);
+}
+
 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
+    enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV444P,  AV_PIX_FMT_YUV422P,  AV_PIX_FMT_YUV420P,
+        AV_PIX_FMT_YUV411P,  AV_PIX_FMT_YUV410P,
+        AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ420P,
+        AV_PIX_FMT_YUV440P,  AV_PIX_FMT_YUVJ440P,
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -81,9 +115,10 @@
 static int config_input(AVFilterLink *inlink)
 {
     DrawBoxContext *drawbox = inlink->dst->priv;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
 
-    drawbox->hsub = av_pix_fmt_descriptors[inlink->format].log2_chroma_w;
-    drawbox->vsub = av_pix_fmt_descriptors[inlink->format].log2_chroma_h;
+    drawbox->hsub = desc->log2_chroma_w;
+    drawbox->vsub = desc->log2_chroma_h;
 
     if (drawbox->w == 0) drawbox->w = inlink->w;
     if (drawbox->h == 0) drawbox->h = inlink->h;
@@ -95,52 +130,70 @@
     return 0;
 }
 
-static int draw_slice(AVFilterLink *inlink, int y0, int h, int slice_dir)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *frame)
 {
     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 (y = FFMAX(yb, 0); y < frame->video->h && y < (yb + drawbox->h); y++) {
+        row[0] = frame->data[0] + y * frame->linesize[0];
 
         for (plane = 1; plane < 3; plane++)
-            row[plane] = picref->data[plane] +
-                picref->linesize[plane] * (y >> drawbox->vsub);
+            row[plane] = frame->data[plane] +
+                 frame->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 (drawbox->invert_color) {
+            for (x = FFMAX(xb, 0); x < xb + drawbox->w && x < frame->video->w; x++)
+                if ((y - yb < drawbox->thickness-1) || (yb + drawbox->h - y < drawbox->thickness) ||
+                    (x - xb < drawbox->thickness-1) || (xb + drawbox->w - x < drawbox->thickness))
+                    row[0][x] = 0xff - row[0][x];
+        } else {
+            for (x = FFMAX(xb, 0); x < xb + drawbox->w && x < frame->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];
+                if ((y - yb < drawbox->thickness-1) || (yb + drawbox->h - y < drawbox->thickness) ||
+                    (x - xb < drawbox->thickness-1) || (xb + drawbox->w - x < drawbox->thickness)) {
+                    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];
+                }
             }
         }
     }
 
-    return ff_draw_slice(inlink->dst->outputs[0], y0, h, 1);
+    return ff_filter_frame(inlink->dst->outputs[0], frame);
 }
 
+static const AVFilterPad avfilter_vf_drawbox_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .config_props     = config_input,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .filter_frame     = filter_frame,
+        .min_perms        = AV_PERM_WRITE | AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_drawbox_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 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,
+    .uninit    = uninit,
 
     .query_formats   = query_formats,
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .config_props     = config_input,
-                                          .get_video_buffer = ff_null_get_video_buffer,
-                                          .start_frame      = ff_null_start_frame,
-                                          .draw_slice       = draw_slice,
-                                          .end_frame        = ff_null_end_frame,
-                                          .min_perms        = AV_PERM_WRITE | AV_PERM_READ },
-                                        { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_drawbox_inputs,
+    .outputs   = avfilter_vf_drawbox_outputs,
+    .priv_class = &drawbox_class,
 };
diff --git a/libavfilter/vf_drawtext.c b/libavfilter/vf_drawtext.c
index 729f152..5fff9bf 100644
--- a/libavfilter/vf_drawtext.c
+++ b/libavfilter/vf_drawtext.c
@@ -31,6 +31,7 @@
 
 #include "config.h"
 #include "libavutil/avstring.h"
+#include "libavutil/bprint.h"
 #include "libavutil/common.h"
 #include "libavutil/file.h"
 #include "libavutil/eval.h"
@@ -112,13 +113,19 @@
     VAR_VARS_NB
 };
 
+enum expansion_mode {
+    EXP_NONE,
+    EXP_NORMAL,
+    EXP_STRFTIME,
+};
+
 typedef struct {
     const AVClass *class;
+    enum expansion_mode exp_mode;   ///< expansion mode to use for the text
     int reinit;                     ///< tells if the filter is being reinited
     uint8_t *fontfile;              ///< font to be used
     uint8_t *text;                  ///< text to be drawn
-    uint8_t *expanded_text;         ///< used to contain the strftime()-expanded text
-    size_t   expanded_text_size;    ///< size in bytes of the expanded_text buffer
+    AVBPrint expanded_text;         ///< used to contain the expanded text
     int ft_load_flags;              ///< flags used for loading fonts, see FT_LOAD_*
     FT_Vector *positions;           ///< positions for each element in the text
     size_t nb_positions;            ///< number of elements of positions array
@@ -181,6 +188,12 @@
 {"tabsize",  "set tab size",         OFFSET(tabsize),            AV_OPT_TYPE_INT,    {.i64=4},     0,        INT_MAX , FLAGS},
 {"basetime", "set base time",        OFFSET(basetime),           AV_OPT_TYPE_INT64,  {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX , FLAGS},
 {"draw",     "if false do not draw", OFFSET(draw_expr),          AV_OPT_TYPE_STRING, {.str="1"},   CHAR_MIN, CHAR_MAX, FLAGS},
+
+{"expansion","set the expansion mode", OFFSET(exp_mode),         AV_OPT_TYPE_INT,    {.i64=EXP_STRFTIME}, 0,        2, FLAGS, "expansion"},
+{"none",     "set no expansion",     OFFSET(exp_mode),           AV_OPT_TYPE_CONST,  {.i64=EXP_NONE},     0,        0, FLAGS, "expansion"},
+{"normal",   "set normal expansion", OFFSET(exp_mode),           AV_OPT_TYPE_CONST,  {.i64=EXP_NORMAL},   0,        0, FLAGS, "expansion"},
+{"strftime", "set strftime expansion (deprecated)", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_STRFTIME}, 0,    0, FLAGS, "expansion"},
+
 {"timecode", "set initial timecode", OFFSET(tc_opt_string),      AV_OPT_TYPE_STRING, {.str=NULL},  CHAR_MIN, CHAR_MAX, FLAGS},
 {"tc24hmax", "set 24 hours max (timecode only)", OFFSET(tc24hmax), AV_OPT_TYPE_INT,  {.i64=0},            0,        1, FLAGS},
 {"timecode_rate", "set rate (timecode only)", OFFSET(tc_rate),   AV_OPT_TYPE_RATIONAL, {.dbl=0},          0,  INT_MAX, FLAGS},
@@ -277,7 +290,7 @@
     FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
 
     /* cache the newly created glyph */
-    if (!(node = av_mallocz(av_tree_node_size))) {
+    if (!(node = av_tree_node_alloc())) {
         ret = AVERROR(ENOMEM);
         goto error;
     }
@@ -484,6 +497,12 @@
     }
     dtext->tabsize *= glyph->advance;
 
+    if (dtext->exp_mode == EXP_STRFTIME &&
+        (strchr(dtext->text, '%') || strchr(dtext->text, '\\')))
+        av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
+
+    av_bprint_init(&dtext->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
+
     return 0;
 }
 
@@ -521,6 +540,8 @@
 
     FT_Done_Face(dtext->face);
     FT_Done_FreeType(dtext->library);
+
+    av_bprint_finalize(&dtext->expanded_text, NULL);
 }
 
 static inline int is_newline(uint32_t c)
@@ -581,10 +602,179 @@
     return AVERROR(ENOSYS);
 }
 
+static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
+                    char *fct, unsigned argc, char **argv, int tag)
+{
+    DrawTextContext *dtext = ctx->priv;
+
+    av_bprintf(bp, "%.6f", dtext->var_values[VAR_T]);
+    return 0;
+}
+
+static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp,
+                          char *fct, unsigned argc, char **argv, int tag)
+{
+    DrawTextContext *dtext = ctx->priv;
+
+    av_bprintf(bp, "%d", (int)dtext->var_values[VAR_N]);
+    return 0;
+}
+
+#if !HAVE_LOCALTIME_R
+static void localtime_r(const time_t *t, struct tm *tm)
+{
+    *tm = *localtime(t);
+}
+#endif
+
+static int func_strftime(AVFilterContext *ctx, AVBPrint *bp,
+                         char *fct, unsigned argc, char **argv, int tag)
+{
+    const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
+    time_t now;
+    struct tm tm;
+
+    time(&now);
+    if (tag == 'L')
+        localtime_r(&now, &tm);
+    else
+        tm = *gmtime(&now);
+    av_bprint_strftime(bp, fmt, &tm);
+    return 0;
+}
+
+static int func_eval_expr(AVFilterContext *ctx, AVBPrint *bp,
+                          char *fct, unsigned argc, char **argv, int tag)
+{
+    DrawTextContext *dtext = ctx->priv;
+    double res;
+    int ret;
+
+    ret = av_expr_parse_and_eval(&res, argv[0], var_names, dtext->var_values,
+                                 NULL, NULL, fun2_names, fun2,
+                                 &dtext->prng, 0, ctx);
+    if (ret < 0)
+        av_log(ctx, AV_LOG_ERROR,
+               "Expression '%s' for the expr text expansion function is not valid\n",
+               argv[0]);
+    else
+        av_bprintf(bp, "%f", res);
+
+    return ret;
+}
+
+static const struct drawtext_function {
+    const char *name;
+    unsigned argc_min, argc_max;
+    int tag; /** opaque argument to func */
+    int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
+} functions[] = {
+    { "expr",      1, 1, 0,   func_eval_expr },
+    { "e",         1, 1, 0,   func_eval_expr },
+    { "pts",       0, 0, 0,   func_pts      },
+    { "gmtime",    0, 1, 'G', func_strftime },
+    { "localtime", 0, 1, 'L', func_strftime },
+    { "frame_num", 0, 0, 0,   func_frame_num },
+    { "n",         0, 0, 0,   func_frame_num },
+};
+
+static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
+                         unsigned argc, char **argv)
+{
+    unsigned i;
+
+    for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
+        if (strcmp(fct, functions[i].name))
+            continue;
+        if (argc < functions[i].argc_min) {
+            av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
+                   fct, functions[i].argc_min);
+            return AVERROR(EINVAL);
+        }
+        if (argc > functions[i].argc_max) {
+            av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
+                   fct, functions[i].argc_max);
+            return AVERROR(EINVAL);
+        }
+        break;
+    }
+    if (i >= FF_ARRAY_ELEMS(functions)) {
+        av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
+        return AVERROR(EINVAL);
+    }
+    return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
+}
+
+static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
+{
+    const char *text = *rtext;
+    char *argv[16] = { NULL };
+    unsigned argc = 0, i;
+    int ret;
+
+    if (*text != '{') {
+        av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
+        return AVERROR(EINVAL);
+    }
+    text++;
+    while (1) {
+        if (!(argv[argc++] = av_get_token(&text, ":}"))) {
+            ret = AVERROR(ENOMEM);
+            goto end;
+        }
+        if (!*text) {
+            av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
+            ret = AVERROR(EINVAL);
+            goto end;
+        }
+        if (argc == FF_ARRAY_ELEMS(argv))
+            av_freep(&argv[--argc]); /* error will be caught later */
+        if (*text == '}')
+            break;
+        text++;
+    }
+
+    if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
+        goto end;
+    ret = 0;
+    *rtext = (char *)text + 1;
+
+end:
+    for (i = 0; i < argc; i++)
+        av_freep(&argv[i]);
+    return ret;
+}
+
+static int expand_text(AVFilterContext *ctx)
+{
+    DrawTextContext *dtext = ctx->priv;
+    char *text = dtext->text;
+    AVBPrint *bp = &dtext->expanded_text;
+    int ret;
+
+    av_bprint_clear(bp);
+    while (*text) {
+        if (*text == '\\' && text[1]) {
+            av_bprint_chars(bp, text[1], 1);
+            text += 2;
+        } else if (*text == '%') {
+            text++;
+            if ((ret = expand_function(ctx, bp, &text)) < 0)
+                return ret;
+        } else {
+            av_bprint_chars(bp, *text, 1);
+            text++;
+        }
+    }
+    if (!av_bprint_is_complete(bp))
+        return AVERROR(ENOMEM);
+    return 0;
+}
+
 static int draw_glyphs(DrawTextContext *dtext, AVFilterBufferRef *picref,
                        int width, int height, const uint8_t rgbcolor[4], FFDrawColor *color, int x, int y)
 {
-    char *text = dtext->expanded_text;
+    char *text = dtext->expanded_text.str;
     uint32_t code = 0;
     int i, x1, y1;
     uint8_t *p;
@@ -637,42 +827,38 @@
 
     time_t now = time(0);
     struct tm ltime;
-    uint8_t *buf = dtext->expanded_text;
-    int buf_size = dtext->expanded_text_size;
+    AVBPrint *bp = &dtext->expanded_text;
+
+    av_bprint_clear(bp);
 
     if(dtext->basetime != AV_NOPTS_VALUE)
         now= picref->pts*av_q2d(ctx->inputs[0]->time_base) + dtext->basetime/1000000;
 
-    if (!buf) {
-        buf_size = 2*strlen(dtext->text)+1;
-        buf = av_malloc(buf_size);
+    switch (dtext->exp_mode) {
+    case EXP_NONE:
+        av_bprintf(bp, "%s", dtext->text);
+        break;
+    case EXP_NORMAL:
+        if ((ret = expand_text(ctx)) < 0)
+            return ret;
+        break;
+    case EXP_STRFTIME:
+        localtime_r(&now, &ltime);
+        av_bprint_strftime(bp, dtext->text, &ltime);
+        break;
     }
 
-#if HAVE_LOCALTIME_R
-    localtime_r(&now, &ltime);
-#else
-    if(strchr(dtext->text, '%'))
-        ltime= *localtime(&now);
-#endif
-
-    do {
-        *buf = 1;
-        if (strftime(buf, buf_size, dtext->text, &ltime) != 0 || *buf == 0)
-            break;
-        buf_size *= 2;
-    } while ((buf = av_realloc(buf, buf_size)));
-
     if (dtext->tc_opt_string) {
         char tcbuf[AV_TIMECODE_STR_SIZE];
         av_timecode_make_string(&dtext->tc, tcbuf, dtext->frame_id++);
-        buf = av_asprintf("%s%s", dtext->text, tcbuf);
+        av_bprint_clear(bp);
+        av_bprintf(bp, "%s%s", dtext->text, tcbuf);
     }
 
-    if (!buf)
+    if (!av_bprint_is_complete(bp))
         return AVERROR(ENOMEM);
-    text = dtext->expanded_text = buf;
-    dtext->expanded_text_size = buf_size;
-    if ((len = strlen(text)) > dtext->nb_positions) {
+    text = dtext->expanded_text.str;
+    if ((len = dtext->expanded_text.len) > dtext->nb_positions) {
         if (!(dtext->positions =
               av_realloc(dtext->positions, len*sizeof(*dtext->positions))))
             return AVERROR(ENOMEM);
@@ -779,23 +965,17 @@
     return 0;
 }
 
-static int null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
-{
-    return 0;
-}
-
-static int end_frame(AVFilterLink *inlink)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *frame)
 {
     AVFilterContext *ctx = inlink->dst;
     AVFilterLink *outlink = ctx->outputs[0];
     DrawTextContext *dtext = ctx->priv;
-    AVFilterBufferRef *picref = inlink->cur_buf;
     int ret;
 
-    dtext->var_values[VAR_T] = picref->pts == AV_NOPTS_VALUE ?
-        NAN : picref->pts * av_q2d(inlink->time_base);
+    dtext->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
+        NAN : frame->pts * av_q2d(inlink->time_base);
 
-    draw_text(ctx, picref, picref->video->w, picref->video->h);
+    draw_text(ctx, frame, frame->video->w, frame->video->h);
 
     av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
            (int)dtext->var_values[VAR_N], dtext->var_values[VAR_T],
@@ -804,12 +984,30 @@
 
     dtext->var_values[VAR_N] += 1.0;
 
-    if ((ret = ff_draw_slice(outlink, 0, picref->video->h, 1)) < 0 ||
-        (ret = ff_end_frame(outlink)) < 0)
-        return ret;
-    return 0;
+    return ff_filter_frame(inlink->dst->outputs[0], frame);
 }
 
+static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .filter_frame     = filter_frame,
+        .config_props     = config_input,
+        .min_perms        = AV_PERM_WRITE |
+                            AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_drawtext = {
     .name          = "drawtext",
     .description   = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
@@ -818,19 +1016,8 @@
     .uninit        = uninit,
     .query_formats = query_formats,
 
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .get_video_buffer = ff_null_get_video_buffer,
-                                          .start_frame      = ff_null_start_frame,
-                                          .draw_slice       = null_draw_slice,
-                                          .end_frame        = end_frame,
-                                          .config_props     = config_input,
-                                          .min_perms        = AV_PERM_WRITE |
-                                                              AV_PERM_READ },
-                                        { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_drawtext_inputs,
+    .outputs   = avfilter_vf_drawtext_outputs,
     .process_command = command,
     .priv_class = &drawtext_class,
 };
diff --git a/libavfilter/vf_edgedetect.c b/libavfilter/vf_edgedetect.c
index 5902c51..5837ccc 100644
--- a/libavfilter/vf_edgedetect.c
+++ b/libavfilter/vf_edgedetect.c
@@ -68,7 +68,7 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {PIX_FMT_GRAY8, PIX_FMT_NONE};
+    static const enum AVPixelFormat pix_fmts[] = {AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE};
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
     return 0;
 }
@@ -142,7 +142,7 @@
      * Gy/Gx is the tangent of the angle (theta), so Gy/Gx is compared against
      * <ref-angle>, or more simply Gy against <ref-angle>*Gx
      *
-     * Gx and Gy bounds = [1020;1020], using 16-bit arithmetic:
+     * Gx and Gy bounds = [-1020;1020], using 16-bit arithmetic:
      *   round((sqrt(2)-1) * (1<<16)) =  27146
      *   round((sqrt(2)+1) * (1<<16)) = 158218
      */
@@ -249,20 +249,26 @@
     }
 }
 
-static int end_frame(AVFilterLink *inlink)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *in)
 {
     AVFilterContext *ctx = inlink->dst;
     EdgeDetectContext *edgedetect = ctx->priv;
     AVFilterLink *outlink = inlink->dst->outputs[0];
-    AVFilterBufferRef  *inpicref = inlink->cur_buf;
-    AVFilterBufferRef *outpicref = outlink->out_buf;
     uint8_t  *tmpbuf    = edgedetect->tmpbuf;
     uint16_t *gradients = edgedetect->gradients;
+    AVFilterBufferRef *out;
+
+    out = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+    if (!out) {
+        avfilter_unref_bufferp(&in);
+        return AVERROR(ENOMEM);
+    }
+    avfilter_copy_buffer_ref_props(out, in);
 
     /* gaussian filter to reduce noise  */
     gaussian_blur(ctx, inlink->w, inlink->h,
-                  tmpbuf,            inlink->w,
-                  inpicref->data[0], inpicref->linesize[0]);
+                  tmpbuf,      inlink->w,
+                  in->data[0], in->linesize[0]);
 
     /* compute the 16-bits gradients and directions for the next step */
     sobel(ctx, inlink->w, inlink->h,
@@ -278,11 +284,11 @@
 
     /* keep high values, or low values surrounded by high values */
     double_threshold(ctx, inlink->w, inlink->h,
-                     outpicref->data[0], outpicref->linesize[0],
-                     tmpbuf,             inlink->w);
+                     out->data[0], out->linesize[0],
+                     tmpbuf,       inlink->w);
 
-    ff_draw_slice(outlink, 0, outlink->h, 1);
-    return ff_end_frame(outlink);
+    avfilter_unref_bufferp(&in);
+    return ff_filter_frame(outlink, out);
 }
 
 static av_cold void uninit(AVFilterContext *ctx)
@@ -293,7 +299,24 @@
     av_freep(&edgedetect->directions);
 }
 
-static int null_draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir) { return 0; }
+static const AVFilterPad edgedetect_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .config_props = config_props,
+        .filter_frame = filter_frame,
+        .min_perms    = AV_PERM_READ,
+     },
+     { NULL }
+};
+
+static const AVFilterPad edgedetect_outputs[] = {
+     {
+         .name = "default",
+         .type = AVMEDIA_TYPE_VIDEO,
+     },
+     { NULL }
+};
 
 AVFilter avfilter_vf_edgedetect = {
     .name          = "edgedetect",
@@ -302,23 +325,7 @@
     .init          = init,
     .uninit        = uninit,
     .query_formats = query_formats,
-
-    .inputs    = (const AVFilterPad[]) {
-       {
-           .name             = "default",
-           .type             = AVMEDIA_TYPE_VIDEO,
-           .draw_slice       = null_draw_slice,
-           .config_props     = config_props,
-           .end_frame        = end_frame,
-           .min_perms        = AV_PERM_READ
-        },
-        { .name = NULL }
-    },
-    .outputs   = (const AVFilterPad[]) {
-        {
-            .name            = "default",
-            .type            = AVMEDIA_TYPE_VIDEO,
-        },
-        { .name = NULL }
-    },
+    .inputs        = edgedetect_inputs,
+    .outputs       = edgedetect_outputs,
+    .priv_class    = &edgedetect_class,
 };
diff --git a/libavfilter/vf_fade.c b/libavfilter/vf_fade.c
index 3c5516e..5be0ec1 100644
--- a/libavfilter/vf_fade.c
+++ b/libavfilter/vf_fade.c
@@ -100,14 +100,14 @@
         if ((ret = av_opt_set(fade, "start_frame", expr, 0)) < 0) {
             av_log(ctx, AV_LOG_ERROR,
                    "Invalid value '%s' for start_frame option\n", expr);
-            return ret;
+            goto end;
         }
     }
     if (expr = av_strtok(NULL, ":", &bufptr)) {
         if ((ret = av_opt_set(fade, "nb_frames", expr, 0)) < 0) {
             av_log(ctx, AV_LOG_ERROR,
                    "Invalid value '%s' for nb_frames option\n", expr);
-            return ret;
+            goto end;
         }
     }
 
@@ -146,40 +146,40 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const 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_YUVA420P,
-        PIX_FMT_RGB24,    PIX_FMT_BGR24,
-        PIX_FMT_ARGB,     PIX_FMT_ABGR,
-        PIX_FMT_RGBA,     PIX_FMT_BGRA,
-        PIX_FMT_NONE
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV444P,  AV_PIX_FMT_YUV422P,  AV_PIX_FMT_YUV420P,
+        AV_PIX_FMT_YUV411P,  AV_PIX_FMT_YUV410P,
+        AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ420P,
+        AV_PIX_FMT_YUV440P,  AV_PIX_FMT_YUVJ440P,
+        AV_PIX_FMT_YUVA420P,
+        AV_PIX_FMT_RGB24,    AV_PIX_FMT_BGR24,
+        AV_PIX_FMT_ARGB,     AV_PIX_FMT_ABGR,
+        AV_PIX_FMT_RGBA,     AV_PIX_FMT_BGRA,
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
     return 0;
 }
 
-const static enum PixelFormat studio_level_pix_fmts[] = {
-    PIX_FMT_YUV444P,  PIX_FMT_YUV422P,  PIX_FMT_YUV420P,
-    PIX_FMT_YUV411P,  PIX_FMT_YUV410P,
-    PIX_FMT_YUV440P,
-    PIX_FMT_NONE
+const static enum AVPixelFormat studio_level_pix_fmts[] = {
+    AV_PIX_FMT_YUV444P,  AV_PIX_FMT_YUV422P,  AV_PIX_FMT_YUV420P,
+    AV_PIX_FMT_YUV411P,  AV_PIX_FMT_YUV410P,
+    AV_PIX_FMT_YUV440P,
+    AV_PIX_FMT_NONE
 };
 
-static enum PixelFormat alpha_pix_fmts[] = {
-    PIX_FMT_YUVA420P,
-    PIX_FMT_ARGB, PIX_FMT_ABGR,
-    PIX_FMT_RGBA, PIX_FMT_BGRA,
-    PIX_FMT_NONE
+static enum AVPixelFormat alpha_pix_fmts[] = {
+    AV_PIX_FMT_YUVA420P,
+    AV_PIX_FMT_ARGB, AV_PIX_FMT_ABGR,
+    AV_PIX_FMT_RGBA, AV_PIX_FMT_BGRA,
+    AV_PIX_FMT_NONE
 };
 
 static int config_props(AVFilterLink *inlink)
 {
     FadeContext *fade = inlink->dst->priv;
-    const AVPixFmtDescriptor *pixdesc = &av_pix_fmt_descriptors[inlink->format];
+    const AVPixFmtDescriptor *pixdesc = av_pix_fmt_desc_get(inlink->format);
 
     fade->hsub = pixdesc->log2_chroma_w;
     fade->vsub = pixdesc->log2_chroma_h;
@@ -216,10 +216,9 @@
     }
 }
 
-static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *frame)
 {
     FadeContext *fade = inlink->dst->priv;
-    AVFilterBufferRef *outpic = inlink->cur_buf;
     uint8_t *p;
     int i, j, plane;
 
@@ -228,22 +227,22 @@
             // alpha only
             plane = fade->is_packed_rgb ? 0 : A; // alpha is on plane 0 for packed formats
                                                  // or plane 3 for planar formats
-            fade_plane(y, h, inlink->w,
+            fade_plane(0, frame->video->h, inlink->w,
                        fade->factor, fade->black_level, fade->black_level_scaled,
                        fade->is_packed_rgb ? fade->rgba_map[A] : 0, // alpha offset for packed formats
                        fade->is_packed_rgb ? 4 : 1,                 // pixstep for 8 bit packed formats
-                       1, outpic->data[plane], outpic->linesize[plane]);
+                       1, frame->data[plane], frame->linesize[plane]);
         } else {
             /* luma or rgb plane */
-            fade_plane(y, h, inlink->w,
+            fade_plane(0, frame->video->h, inlink->w,
                        fade->factor, fade->black_level, fade->black_level_scaled,
                        0, 1, // offset & pixstep for Y plane or RGB packed format
-                       fade->bpp, outpic->data[0], outpic->linesize[0]);
-            if (outpic->data[1] && outpic->data[2]) {
+                       fade->bpp, frame->data[0], frame->linesize[0]);
+            if (frame->data[1] && frame->data[2]) {
                 /* 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 (i = 0; i < frame->video->h; i++) {
+                        p = frame->data[plane] + (i >> fade->vsub) * frame->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
@@ -257,25 +256,35 @@
         }
     }
 
-    return ff_draw_slice(inlink->dst->outputs[0], y, h, slice_dir);
-}
-
-static int end_frame(AVFilterLink *inlink)
-{
-    FadeContext *fade = inlink->dst->priv;
-    int ret;
-
-    ret = ff_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++;
 
-    return ret;
+    return ff_filter_frame(inlink->dst->outputs[0], frame);
 }
 
+static const AVFilterPad avfilter_vf_fade_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .config_props     = config_props,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .filter_frame     = filter_frame,
+        .min_perms        = AV_PERM_READ | AV_PERM_WRITE,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_fade_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_fade = {
     .name          = "fade",
     .description   = NULL_IF_CONFIG_SMALL("Fade in/out input video."),
@@ -284,17 +293,7 @@
     .priv_size     = sizeof(FadeContext),
     .query_formats = query_formats,
 
-    .inputs    = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_VIDEO,
-                                          .config_props    = config_props,
-                                          .get_video_buffer = ff_null_get_video_buffer,
-                                          .start_frame      = ff_null_start_frame,
-                                          .draw_slice      = draw_slice,
-                                          .end_frame       = end_frame,
-                                          .min_perms       = AV_PERM_READ | AV_PERM_WRITE },
-                                        { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_VIDEO, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_fade_inputs,
+    .outputs   = avfilter_vf_fade_outputs,
     .priv_class = &fade_class,
 };
diff --git a/libavfilter/vf_field.c b/libavfilter/vf_field.c
new file mode 100644
index 0000000..c9ac42b
--- /dev/null
+++ b/libavfilter/vf_field.c
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) 2003 Rich Felker
+ * Copyright (c) 2012 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
+ * field filter, based on libmpcodecs/vf_field.c by Rich Felker
+ */
+
+#include "libavutil/opt.h"
+#include "libavutil/pixdesc.h"
+#include "avfilter.h"
+#include "internal.h"
+
+enum FieldType { FIELD_TYPE_TOP = 0, FIELD_TYPE_BOTTOM };
+
+typedef struct {
+    const AVClass *class;
+    enum FieldType type;
+    int nb_planes;              ///< number of planes of the current format
+} FieldContext;
+
+#define OFFSET(x) offsetof(FieldContext, x)
+#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
+
+static const AVOption field_options[] = {
+    {"type", "set field type (top or bottom)", OFFSET(type), AV_OPT_TYPE_INT, {.i64=FIELD_TYPE_TOP}, 0, 1, FLAGS, "field_type" },
+    {"top",    "select top field",    0, AV_OPT_TYPE_CONST, {.i64=FIELD_TYPE_TOP},    INT_MIN, INT_MAX, FLAGS, "field_type"},
+    {"bottom", "select bottom field", 0, AV_OPT_TYPE_CONST, {.i64=FIELD_TYPE_BOTTOM}, INT_MIN, INT_MAX, FLAGS, "field_type"},
+
+    {NULL}
+};
+
+AVFILTER_DEFINE_CLASS(field);
+
+static av_cold int init(AVFilterContext *ctx, const char *args)
+{
+    FieldContext *field = ctx->priv;
+    static const char *shorthand[] = { "type", NULL };
+
+    field->class = &field_class;
+    av_opt_set_defaults(field);
+
+    return av_opt_set_from_string(field, args, shorthand, "=", ":");
+}
+
+static int config_props_output(AVFilterLink *outlink)
+{
+    AVFilterContext *ctx = outlink->src;
+    FieldContext *field = ctx->priv;
+    AVFilterLink *inlink = ctx->inputs[0];
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
+    int i;
+
+    for (i = 0; i < desc->nb_components; i++)
+        field->nb_planes = FFMAX(field->nb_planes, desc->comp[i].plane);
+    field->nb_planes++;
+
+    outlink->w = inlink->w;
+    outlink->h = (inlink->h + (field->type == FIELD_TYPE_TOP)) / 2;
+
+    av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d type:%s -> w:%d h:%d\n",
+           inlink->w, inlink->h, field->type == FIELD_TYPE_BOTTOM ? "bottom" : "top",
+           outlink->w, outlink->h);
+    return 0;
+}
+
+static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
+{
+    FieldContext *field = inlink->dst->priv;
+    AVFilterBufferRef *outpicref = avfilter_ref_buffer(inpicref, ~0);
+    AVFilterLink *outlink = inlink->dst->outputs[0];
+    int i;
+
+    if (!outpicref)
+        return AVERROR(ENOMEM);
+
+    outpicref->video->h = outlink->h;
+    outpicref->video->interlaced = 0;
+
+    for (i = 0; i < field->nb_planes; i++) {
+        if (field->type == FIELD_TYPE_BOTTOM)
+            outpicref->data[i] = inpicref->data[i] + inpicref->linesize[i];
+        outpicref->linesize[i] = 2 * inpicref->linesize[i];
+    }
+    return ff_start_frame(outlink, outpicref);
+}
+
+static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
+{
+    FieldContext *field = inlink->dst->priv;
+    int y1 = (y + (field->type == FIELD_TYPE_TOP)) / 2;
+    int h1 = (h + (field->type == FIELD_TYPE_TOP)) / 2;
+    return ff_draw_slice(inlink->dst->outputs[0], y1, h1, slice_dir);
+}
+
+static const AVFilterPad field_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .start_frame      = start_frame,
+        .draw_slice       = draw_slice,
+        .end_frame        = ff_null_end_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad field_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .config_props  = config_props_output,
+    },
+    { NULL }
+};
+
+AVFilter avfilter_vf_field = {
+    .name          = "field",
+    .description   = NULL_IF_CONFIG_SMALL("Extract a field from the input video."),
+
+    .priv_size     = sizeof(FieldContext),
+    .init          = init,
+
+    .inputs        = field_inputs,
+    .outputs       = field_outputs,
+    .priv_class    = &field_class,
+};
diff --git a/libavfilter/vf_fieldorder.c b/libavfilter/vf_fieldorder.c
index 8026580..06e0369 100644
--- a/libavfilter/vf_fieldorder.c
+++ b/libavfilter/vf_fieldorder.c
@@ -71,22 +71,23 @@
 static int query_formats(AVFilterContext *ctx)
 {
     AVFilterFormats  *formats;
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
     int              ret;
 
     /** accept any input pixel format that is not hardware accelerated, not
      *  a bitstream format, and does not have vertically sub-sampled chroma */
     if (ctx->inputs[0]) {
         formats = NULL;
-        for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++)
-            if (!(  av_pix_fmt_descriptors[pix_fmt].flags & PIX_FMT_HWACCEL
-                 || av_pix_fmt_descriptors[pix_fmt].flags & PIX_FMT_BITSTREAM)
-                && av_pix_fmt_descriptors[pix_fmt].nb_components
-                && !av_pix_fmt_descriptors[pix_fmt].log2_chroma_h
-                && (ret = ff_add_format(&formats, pix_fmt)) < 0) {
+        for (pix_fmt = 0; pix_fmt < AV_PIX_FMT_NB; pix_fmt++) {
+            const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
+            if (!(desc->flags & PIX_FMT_HWACCEL ||
+                  desc->flags & PIX_FMT_BITSTREAM) &&
+                desc->nb_components && !desc->log2_chroma_h &&
+                (ret = ff_add_format(&formats, pix_fmt)) < 0) {
                 ff_formats_unref(&formats);
                 return ret;
             }
+        }
         ff_formats_ref(formats, &ctx->inputs[0]->out_formats);
         ff_formats_ref(formats, &ctx->outputs[0]->in_formats);
     }
@@ -120,136 +121,88 @@
     return ff_get_video_buffer(outlink, perms, w, h);
 }
 
-static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *frame)
 {
-    AVFilterContext   *ctx        = inlink->dst;
-    AVFilterLink      *outlink    = ctx->outputs[0];
+    AVFilterContext   *ctx     = inlink->dst;
+    FieldOrderContext *s       = ctx->priv;
+    AVFilterLink      *outlink = ctx->outputs[0];
+    int h, plane, line_step, line_size, line;
+    uint8_t *data;
 
-    AVFilterBufferRef *outpicref, *for_next_filter;
-    int ret = 0;
+    if (!frame->video->interlaced ||
+        frame->video->top_field_first == s->dst_tff)
+        return ff_filter_frame(outlink, frame);
 
-    outpicref = avfilter_ref_buffer(inpicref, ~0);
-    if (!outpicref)
-        return AVERROR(ENOMEM);
-
-    for_next_filter = avfilter_ref_buffer(outpicref, ~0);
-    if (!for_next_filter) {
-        avfilter_unref_bufferp(&outpicref);
-        return AVERROR(ENOMEM);
-    }
-
-    ret = ff_start_frame(outlink, for_next_filter);
-    if (ret < 0) {
-        avfilter_unref_bufferp(&outpicref);
-        return ret;
-    }
-
-    outlink->out_buf = outpicref;
-    return 0;
-}
-
-static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
-{
-    AVFilterContext   *ctx        = inlink->dst;
-    FieldOrderContext *fieldorder = ctx->priv;
-    AVFilterLink      *outlink    = ctx->outputs[0];
-
-    AVFilterBufferRef *inpicref   = inlink->cur_buf;
-
-    /** can only currently do slices if this filter is doing nothing
-     *  because this filter is moving picture content, the output
-     *  slice will contain different video lines than the input slice
-     *  and that complexity will be added later */
-    if (  !inpicref->video->interlaced
-        || inpicref->video->top_field_first == fieldorder->dst_tff) {
-        return ff_draw_slice(outlink, y, h, slice_dir);
-    }
-    return 0;
-}
-
-static int end_frame(AVFilterLink *inlink)
-{
-    AVFilterContext   *ctx        = inlink->dst;
-    FieldOrderContext *fieldorder = ctx->priv;
-    AVFilterLink      *outlink    = ctx->outputs[0];
-
-    AVFilterBufferRef *inpicref   = inlink->cur_buf;
-    AVFilterBufferRef *outpicref  = outlink->out_buf;
-
-    int               h, plane, line_step, line_size, line;
-    uint8_t           *cpy_src, *cpy_dst;
-
-    if (    inpicref->video->interlaced
-         && inpicref->video->top_field_first != fieldorder->dst_tff) {
-        av_dlog(ctx,
-                "picture will move %s one line\n",
-                fieldorder->dst_tff ? "up" : "down");
-        h = inpicref->video->h;
-        for (plane = 0; plane < 4 && inpicref->data[plane]; plane++) {
-            line_step = inpicref->linesize[plane];
-            line_size = fieldorder->line_size[plane];
-            cpy_src = inpicref->data[plane];
-            cpy_dst = outpicref->data[plane];
-            if (fieldorder->dst_tff) {
-                /** Move every line up one line, working from
-                 *  the top to the bottom of the frame.
-                 *  The original top line is lost.
-                 *  The new last line is created as a copy of the
-                 *  penultimate line from that field. */
-                for (line = 0; line < h; line++) {
-                    if (1 + line < outpicref->video->h) {
-                        memcpy(cpy_dst, cpy_src + line_step, line_size);
-                    } else {
-                        memcpy(cpy_dst, cpy_src - line_step - line_step, line_size);
-                    }
-                    cpy_src += line_step;
-                    cpy_dst += line_step;
+    av_dlog(ctx,
+            "picture will move %s one line\n",
+            s->dst_tff ? "up" : "down");
+    h = frame->video->h;
+    for (plane = 0; plane < 4 && frame->data[plane]; plane++) {
+        line_step = frame->linesize[plane];
+        line_size = s->line_size[plane];
+        data = frame->data[plane];
+        if (s->dst_tff) {
+            /** Move every line up one line, working from
+             *  the top to the bottom of the frame.
+             *  The original top line is lost.
+             *  The new last line is created as a copy of the
+             *  penultimate line from that field. */
+            for (line = 0; line < h; line++) {
+                if (1 + line < frame->video->h) {
+                    memcpy(data, data + line_step, line_size);
+                } else {
+                    memcpy(data, data - line_step - line_step, line_size);
                 }
-            } else {
-                /** Move every line down one line, working from
-                 *  the bottom to the top of the frame.
-                 *  The original bottom line is lost.
-                 *  The new first line is created as a copy of the
-                 *  second line from that field. */
-                cpy_src += (h - 1) * line_step;
-                cpy_dst += (h - 1) * line_step;
-                for (line = h - 1; line >= 0 ; line--) {
-                    if (line > 0) {
-                        memcpy(cpy_dst, cpy_src - line_step, line_size);
-                    } else {
-                        memcpy(cpy_dst, cpy_src + line_step + line_step, line_size);
-                    }
-                    cpy_src -= line_step;
-                    cpy_dst -= line_step;
+                data += line_step;
+            }
+        } else {
+            /** Move every line down one line, working from
+             *  the bottom to the top of the frame.
+             *  The original bottom line is lost.
+             *  The new first line is created as a copy of the
+             *  second line from that field. */
+            data += (h - 1) * line_step;
+            for (line = h - 1; line >= 0 ; line--) {
+                if (line > 0) {
+                    memcpy(data, data - line_step, line_size);
+                } else {
+                    memcpy(data, data + line_step + line_step, line_size);
                 }
+                data -= line_step;
             }
         }
-        outpicref->video->top_field_first = fieldorder->dst_tff;
-        ff_draw_slice(outlink, 0, h, 1);
-    } else {
-        av_dlog(ctx,
-                "not interlaced or field order already correct\n");
     }
+    frame->video->top_field_first = s->dst_tff;
 
-    return ff_end_frame(outlink);
+    return ff_filter_frame(outlink, frame);
 }
 
+static const AVFilterPad avfilter_vf_fieldorder_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .config_props     = config_input,
+        .get_video_buffer = get_video_buffer,
+        .filter_frame     = filter_frame,
+        .min_perms        = AV_PERM_READ | AV_PERM_WRITE,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_fieldorder_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_fieldorder = {
     .name          = "fieldorder",
     .description   = NULL_IF_CONFIG_SMALL("Set the field order."),
     .init          = init,
     .priv_size     = sizeof(FieldOrderContext),
     .query_formats = query_formats,
-    .inputs        = (const AVFilterPad[]) {{ .name             = "default",
-                                              .type             = AVMEDIA_TYPE_VIDEO,
-                                              .config_props     = config_input,
-                                              .start_frame      = start_frame,
-                                              .get_video_buffer = get_video_buffer,
-                                              .draw_slice       = draw_slice,
-                                              .end_frame        = end_frame,
-                                              .min_perms        = AV_PERM_READ | AV_PERM_PRESERVE },
-                                            { .name = NULL}},
-    .outputs       = (const AVFilterPad[]) {{ .name             = "default",
-                                              .type             = AVMEDIA_TYPE_VIDEO, },
-                                            { .name = NULL}},
+    .inputs        = avfilter_vf_fieldorder_inputs,
+    .outputs       = avfilter_vf_fieldorder_outputs,
 };
diff --git a/libavfilter/vf_format.c b/libavfilter/vf_format.c
index ccd829f..df3c77a 100644
--- a/libavfilter/vf_format.c
+++ b/libavfilter/vf_format.c
@@ -39,18 +39,18 @@
      * List of flags telling if a given image format has been listed
      * as argument to the filter.
      */
-    int listed_pix_fmt_flags[PIX_FMT_NB];
+    int listed_pix_fmt_flags[AV_PIX_FMT_NB];
 } FormatContext;
 
-#define PIX_FMT_NAME_MAXSIZE 32
+#define AV_PIX_FMT_NAME_MAXSIZE 32
 
 static av_cold int init(AVFilterContext *ctx, const char *args)
 {
     FormatContext *format = ctx->priv;
     const char *cur, *sep;
-    char             pix_fmt_name[PIX_FMT_NAME_MAXSIZE];
+    char             pix_fmt_name[AV_PIX_FMT_NAME_MAXSIZE];
     int              pix_fmt_name_len, ret;
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
 
     /* parse the list of formats */
     for (cur = args; cur; cur = sep ? sep+1 : NULL) {
@@ -58,7 +58,7 @@
             pix_fmt_name_len = strlen(cur);
         else
             pix_fmt_name_len = sep - cur;
-        if (pix_fmt_name_len >= PIX_FMT_NAME_MAXSIZE) {
+        if (pix_fmt_name_len >= AV_PIX_FMT_NAME_MAXSIZE) {
             av_log(ctx, AV_LOG_ERROR, "Format name too long\n");
             return -1;
         }
@@ -78,12 +78,12 @@
 static AVFilterFormats *make_format_list(FormatContext *format, int flag)
 {
     AVFilterFormats *formats;
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
 
     formats = av_mallocz(sizeof(AVFilterFormats));
-    formats->formats = av_malloc(sizeof(enum PixelFormat) * PIX_FMT_NB);
+    formats->formats = av_malloc(sizeof(enum AVPixelFormat) * AV_PIX_FMT_NB);
 
-    for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++)
+    for (pix_fmt = 0; pix_fmt < AV_PIX_FMT_NB; pix_fmt++)
         if (format->listed_pix_fmt_flags[pix_fmt] == flag)
             formats->formats[formats->format_count++] = pix_fmt;
 
@@ -97,6 +97,23 @@
     return 0;
 }
 
+static const AVFilterPad avfilter_vf_format_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_format_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_format = {
     .name      = "format",
     .description = NULL_IF_CONFIG_SMALL("Convert the input video to one of the specified pixel formats."),
@@ -107,16 +124,8 @@
 
     .priv_size = sizeof(FormatContext),
 
-    .inputs    = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_VIDEO,
-                                          .get_video_buffer= ff_null_get_video_buffer,
-                                          .start_frame     = ff_null_start_frame,
-                                          .draw_slice      = ff_null_draw_slice,
-                                          .end_frame       = ff_null_end_frame, },
-                                        { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_VIDEO },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_format_inputs,
+    .outputs   = avfilter_vf_format_outputs,
 };
 #endif /* CONFIG_FORMAT_FILTER */
 
@@ -127,6 +136,23 @@
     return 0;
 }
 
+static const AVFilterPad avfilter_vf_noformat_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_noformat_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_noformat = {
     .name      = "noformat",
     .description = NULL_IF_CONFIG_SMALL("Force libavfilter not to use any of the specified pixel formats for the input to the next filter."),
@@ -137,15 +163,7 @@
 
     .priv_size = sizeof(FormatContext),
 
-    .inputs    = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_VIDEO,
-                                          .get_video_buffer= ff_null_get_video_buffer,
-                                          .start_frame     = ff_null_start_frame,
-                                          .draw_slice      = ff_null_draw_slice,
-                                          .end_frame       = ff_null_end_frame, },
-                                        { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_VIDEO },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_noformat_inputs,
+    .outputs   = avfilter_vf_noformat_outputs,
 };
 #endif /* CONFIG_NOFORMAT_FILTER */
diff --git a/libavfilter/vf_fps.c b/libavfilter/vf_fps.c
index c13b1bd..8e7880c 100644
--- a/libavfilter/vf_fps.c
+++ b/libavfilter/vf_fps.c
@@ -46,6 +46,7 @@
 
     AVRational framerate;   ///< target framerate
     char *fps;              ///< a string describing target framerate
+    int rounding;           ///< AVRounding method for timestamps
 
     /* statistics */
     int frames_in;             ///< number of frames on input
@@ -59,6 +60,12 @@
 #define F AV_OPT_FLAG_FILTERING_PARAM
 static const AVOption fps_options[] = {
     { "fps", "A string describing desired output framerate", OFFSET(fps), AV_OPT_TYPE_STRING, { .str = "25" }, .flags = V|F },
+    { "round", "set rounding method for timestamps", OFFSET(rounding), AV_OPT_TYPE_INT, { .i64 = AV_ROUND_NEAR_INF }, 0, 5, V|F, "round" },
+    { "zero", "round towards 0",      OFFSET(rounding), AV_OPT_TYPE_CONST, { .i64 = AV_ROUND_ZERO     }, 0, 5, V|F, "round" },
+    { "inf",  "round away from 0",    OFFSET(rounding), AV_OPT_TYPE_CONST, { .i64 = AV_ROUND_INF      }, 0, 5, V|F, "round" },
+    { "down", "round towards -infty", OFFSET(rounding), AV_OPT_TYPE_CONST, { .i64 = AV_ROUND_DOWN     }, 0, 5, V|F, "round" },
+    { "up",   "round towards +infty", OFFSET(rounding), AV_OPT_TYPE_CONST, { .i64 = AV_ROUND_UP       }, 0, 5, V|F, "round" },
+    { "near", "round to nearest",     OFFSET(rounding), AV_OPT_TYPE_CONST, { .i64 = AV_ROUND_NEAR_INF }, 0, 5, V|F, "round" },
     { NULL },
 };
 
@@ -145,9 +152,7 @@
             buf->pts = av_rescale_q(s->first_pts, ctx->inputs[0]->time_base,
                                     outlink->time_base) + s->frames_out;
 
-            if ((ret = ff_start_frame(outlink, buf)) < 0 ||
-                (ret = ff_draw_slice(outlink, 0, outlink->h, 1)) < 0 ||
-                (ret = ff_end_frame(outlink)) < 0)
+            if ((ret = ff_filter_frame(outlink, buf)) < 0)
                 return ret;
 
             s->frames_out++;
@@ -172,16 +177,14 @@
     return 0;
 }
 
-static int end_frame(AVFilterLink *inlink)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
 {
     AVFilterContext    *ctx = inlink->dst;
     FPSContext           *s = ctx->priv;
     AVFilterLink   *outlink = ctx->outputs[0];
-    AVFilterBufferRef  *buf = inlink->cur_buf;
     int64_t delta;
     int i, ret;
 
-    inlink->cur_buf = NULL;
     s->frames_in++;
     /* discard frames until we get the first timestamp */
     if (s->pts == AV_NOPTS_VALUE) {
@@ -206,8 +209,8 @@
     }
 
     /* number of output frames */
-    delta = av_rescale_q(buf->pts - s->pts, inlink->time_base,
-                         outlink->time_base);
+    delta = av_rescale_q_rnd(buf->pts - s->pts, inlink->time_base,
+                             outlink->time_base, s->rounding);
 
     if (delta < 1) {
         /* drop the frame and everything buffered except the first */
@@ -252,9 +255,7 @@
         buf_out->pts = av_rescale_q(s->first_pts, inlink->time_base,
                                     outlink->time_base) + s->frames_out;
 
-        if ((ret = ff_start_frame(outlink, buf_out)) < 0 ||
-            (ret = ff_draw_slice(outlink, 0, outlink->h, 1)) < 0 ||
-            (ret = ff_end_frame(outlink)) < 0) {
+        if ((ret = ff_filter_frame(outlink, buf_out)) < 0) {
             avfilter_unref_bufferp(&buf);
             return ret;
         }
@@ -269,15 +270,26 @@
     return ret;
 }
 
-static int null_start_frame(AVFilterLink *link, AVFilterBufferRef *buf)
-{
-    return 0;
-}
+static const AVFilterPad avfilter_vf_fps_inputs[] = {
+    {
+        .name        = "default",
+        .type        = AVMEDIA_TYPE_VIDEO,
+        .min_perms   = AV_PERM_READ | AV_PERM_PRESERVE,
+        .filter_frame = filter_frame,
+    },
+    { NULL }
+};
 
-static int null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
-{
-    return 0;
-}
+static const AVFilterPad avfilter_vf_fps_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .rej_perms     = AV_PERM_WRITE,
+        .request_frame = request_frame,
+        .config_props  = config_props
+    },
+    { NULL }
+};
 
 AVFilter avfilter_vf_fps = {
     .name        = "fps",
@@ -288,18 +300,7 @@
 
     .priv_size = sizeof(FPSContext),
 
-    .inputs    = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_VIDEO,
-                                          .min_perms       = AV_PERM_READ | AV_PERM_PRESERVE,
-                                          .start_frame     = null_start_frame,
-                                          .draw_slice      = null_draw_slice,
-                                          .end_frame       = end_frame, },
-                                        { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_VIDEO,
-                                          .rej_perms       = AV_PERM_WRITE,
-                                          .request_frame   = request_frame,
-                                          .config_props    = config_props},
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_fps_inputs,
+    .outputs   = avfilter_vf_fps_outputs,
     .priv_class = &fps_class,
 };
diff --git a/libavfilter/vf_framestep.c b/libavfilter/vf_framestep.c
index dcb2665..f848196 100644
--- a/libavfilter/vf_framestep.c
+++ b/libavfilter/vf_framestep.c
@@ -66,35 +66,18 @@
     return 0;
 }
 
-static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *ref)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *ref)
 {
     FrameStepContext *framestep = inlink->dst->priv;
 
-    framestep->frame_selected = 0;
     if (!(framestep->frame_count++ % framestep->frame_step)) {
-        inlink->cur_buf = NULL;
         framestep->frame_selected = 1;
-        return ff_start_frame(inlink->dst->outputs[0], ref);
+        return ff_filter_frame(inlink->dst->outputs[0], ref);
+    } else {
+        framestep->frame_selected = 0;
+        avfilter_unref_buffer(ref);
+        return 0;
     }
-    return 0;
-}
-
-static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
-{
-    FrameStepContext *framestep = inlink->dst->priv;
-
-    if (framestep->frame_selected)
-        return ff_draw_slice(inlink->dst->outputs[0], y, h, slice_dir);
-    return 0;
-}
-
-static int end_frame(AVFilterLink *inlink)
-{
-    FrameStepContext *framestep = inlink->dst->priv;
-
-    if (framestep->frame_selected)
-        return ff_end_frame(inlink->dst->outputs[0]);
-    return 0;
 }
 
 static int request_frame(AVFilterLink *outlink)
@@ -111,30 +94,31 @@
     return ret;
 }
 
+static const AVFilterPad framestep_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .filter_frame     = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad framestep_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .config_props  = config_output_props,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_framestep = {
     .name      = "framestep",
     .description = NULL_IF_CONFIG_SMALL("Select one frame every N frames."),
     .init      = init,
     .priv_size = sizeof(FrameStepContext),
-
-    .inputs = (const AVFilterPad[]) {
-        {
-            .name             = "default",
-            .type             = AVMEDIA_TYPE_VIDEO,
-            .get_video_buffer = ff_null_get_video_buffer,
-            .start_frame      = start_frame,
-            .draw_slice       = draw_slice,
-            .end_frame        = end_frame,
-        },
-        { .name = NULL }
-    },
-    .outputs = (const AVFilterPad[]) {
-        {
-            .name             = "default",
-            .type             = AVMEDIA_TYPE_VIDEO,
-            .config_props     = config_output_props,
-            .request_frame    = request_frame,
-        },
-        { .name = NULL }
-    },
+    .inputs    = framestep_inputs,
+    .outputs   = framestep_outputs,
 };
diff --git a/libavfilter/vf_frei0r.c b/libavfilter/vf_frei0r.c
index cd0cd6b..0fb86b4 100644
--- a/libavfilter/vf_frei0r.c
+++ b/libavfilter/vf_frei0r.c
@@ -204,13 +204,15 @@
     return 0;
 }
 
-static void *load_path(AVFilterContext *ctx, const char *prefix, const char *name)
+static int load_path(AVFilterContext *ctx, void **handle_ptr, const char *prefix, const char *name)
 {
-    char path[1024];
-
-    snprintf(path, sizeof(path), "%s%s%s", prefix, name, SLIBSUF);
+    char *path = av_asprintf("%s%s%s", prefix, name, SLIBSUF);
+    if (!path)
+        return AVERROR(ENOMEM);
     av_log(ctx, AV_LOG_DEBUG, "Looking for frei0r effect in '%s'\n", path);
-    return dlopen(path, RTLD_NOW|RTLD_LOCAL);
+    *handle_ptr = dlopen(path, RTLD_NOW|RTLD_LOCAL);
+    av_free(path);
+    return 0;
 }
 
 static av_cold int frei0r_init(AVFilterContext *ctx,
@@ -221,24 +223,55 @@
     f0r_get_plugin_info_f f0r_get_plugin_info;
     f0r_plugin_info_t *pi;
     char *path;
+    int ret = 0;
 
-    /* see: http://piksel.org/frei0r/1.2/spec/1.2/spec/group__pluglocations.html */
+    /* see: http://frei0r.dyne.org/codedoc/html/group__pluglocations.html */
     if ((path = av_strdup(getenv("FREI0R_PATH")))) {
+#ifdef _WIN32
+        const char *separator = ";";
+#else
+        const char *separator = ":";
+#endif
         char *p, *ptr = NULL;
-        for (p = path; p = av_strtok(p, ":", &ptr); p = NULL)
-            if (frei0r->dl_handle = load_path(ctx, p, dl_name))
+        for (p = path; p = av_strtok(p, separator, &ptr); p = NULL) {
+            /* add additional trailing slash in case it is missing */
+            char *p1 = av_asprintf("%s/", p);
+            if (!p1) {
+                ret = AVERROR(ENOMEM);
+                goto check_path_end;
+            }
+            ret = load_path(ctx, &frei0r->dl_handle, p1, dl_name);
+            av_free(p1);
+            if (ret < 0)
+                goto check_path_end;
+            if (frei0r->dl_handle)
                 break;
+        }
+
+    check_path_end:
         av_free(path);
+        if (ret < 0)
+            return ret;
     }
     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);
+        char *prefix = av_asprintf("%s/.frei0r-1/lib/", path);
+        if (!prefix)
+            return AVERROR(ENOMEM);
+        ret = load_path(ctx, &frei0r->dl_handle, prefix, dl_name);
+        av_free(prefix);
+        if (ret < 0)
+            return ret;
     }
-    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) {
+        ret = load_path(ctx, &frei0r->dl_handle, "/usr/local/lib/frei0r-1/", dl_name);
+        if (ret < 0)
+            return ret;
+    }
+    if (!frei0r->dl_handle) {
+        ret = load_path(ctx, &frei0r->dl_handle, "/usr/lib/frei0r-1/", dl_name);
+        if (ret < 0)
+            return ret;
+    }
     if (!frei0r->dl_handle) {
         av_log(ctx, AV_LOG_ERROR, "Could not find module '%s'\n", dl_name);
         return AVERROR(EINVAL);
@@ -329,12 +362,12 @@
     AVFilterFormats *formats = NULL;
 
     if        (frei0r->plugin_info.color_model == F0R_COLOR_MODEL_BGRA8888) {
-        ff_add_format(&formats, PIX_FMT_BGRA);
+        ff_add_format(&formats, AV_PIX_FMT_BGRA);
     } else if (frei0r->plugin_info.color_model == F0R_COLOR_MODEL_RGBA8888) {
-        ff_add_format(&formats, PIX_FMT_RGBA);
+        ff_add_format(&formats, AV_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
+        static const enum AVPixelFormat pix_fmts[] = {
+            AV_PIX_FMT_BGRA, AV_PIX_FMT_ARGB, AV_PIX_FMT_ABGR, AV_PIX_FMT_ARGB, AV_PIX_FMT_NONE
         };
         formats = ff_make_format_list(pix_fmts);
     }
@@ -346,28 +379,47 @@
     return 0;
 }
 
-static int null_draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
-{
-    return 0;
-}
-
-static int end_frame(AVFilterLink *inlink)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *in)
 {
     Frei0rContext *frei0r = inlink->dst->priv;
     AVFilterLink *outlink = inlink->dst->outputs[0];
-    AVFilterBufferRef  *inpicref =  inlink->cur_buf;
-    AVFilterBufferRef *outpicref = outlink->out_buf;
-    int ret;
+    AVFilterBufferRef *out;
 
-    frei0r->update(frei0r->instance, inpicref->pts * av_q2d(inlink->time_base) * 1000,
-                   (const uint32_t *)inpicref->data[0],
-                   (uint32_t *)outpicref->data[0]);
-    if ((ret = ff_draw_slice(outlink, 0, outlink->h, 1)) ||
-        (ret = ff_end_frame(outlink)) < 0)
-        return ret;
-    return 0;
+    out = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+    if (!out) {
+        avfilter_unref_bufferp(&in);
+        return AVERROR(ENOMEM);
+    }
+    avfilter_copy_buffer_ref_props(out, in);
+
+    frei0r->update(frei0r->instance, in->pts * av_q2d(inlink->time_base) * 1000,
+                   (const uint32_t *)in->data[0],
+                   (uint32_t *)out->data[0]);
+
+    avfilter_unref_bufferp(&in);
+
+    return ff_filter_frame(outlink, out);
 }
 
+static const AVFilterPad avfilter_vf_frei0r_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .config_props = config_input_props,
+        .filter_frame = filter_frame,
+        .min_perms    = AV_PERM_READ
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_frei0r_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_frei0r = {
     .name      = "frei0r",
     .description = NULL_IF_CONFIG_SMALL("Apply a frei0r effect."),
@@ -378,17 +430,9 @@
 
     .priv_size = sizeof(Frei0rContext),
 
-    .inputs    = (const 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}},
+    .inputs    = avfilter_vf_frei0r_inputs,
 
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO, },
-                                        { .name = NULL}},
+    .outputs   = avfilter_vf_frei0r_outputs,
 };
 
 static av_cold int source_init(AVFilterContext *ctx, const char *args)
@@ -444,8 +488,6 @@
 {
     Frei0rContext *frei0r = outlink->src->priv;
     AVFilterBufferRef *picref = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
-    AVFilterBufferRef *buf_out;
-    int ret;
 
     if (!picref)
         return AVERROR(ENOMEM);
@@ -454,30 +496,22 @@
     picref->pts = frei0r->pts++;
     picref->pos = -1;
 
-    buf_out = avfilter_ref_buffer(picref, ~0);
-    if (!buf_out) {
-        ret = AVERROR(ENOMEM);
-        goto fail;
-    }
-
-    ret = ff_start_frame(outlink, buf_out);
-    if (ret < 0)
-        goto fail;
-
     frei0r->update(frei0r->instance, av_rescale_q(picref->pts, frei0r->time_base, (AVRational){1,1000}),
                    NULL, (uint32_t *)picref->data[0]);
-    ret = ff_draw_slice(outlink, 0, outlink->h, 1);
-    if (ret < 0)
-        goto fail;
 
-    ret = ff_end_frame(outlink);
-
-fail:
-    avfilter_unref_buffer(picref);
-
-    return ret;
+    return ff_filter_frame(outlink, picref);
 }
 
+static const AVFilterPad avfilter_vsrc_frei0r_src_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .request_frame = source_request_frame,
+        .config_props  = source_config_props
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vsrc_frei0r_src = {
     .name        = "frei0r_src",
     .description = NULL_IF_CONFIG_SMALL("Generate a frei0r source."),
@@ -490,9 +524,5 @@
 
     .inputs    = NULL,
 
-    .outputs   = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_VIDEO,
-                                          .request_frame   = source_request_frame,
-                                          .config_props    = source_config_props },
-                                        { .name = NULL}},
+    .outputs   = avfilter_vsrc_frei0r_src_outputs,
 };
diff --git a/libavfilter/vf_geq.c b/libavfilter/vf_geq.c
new file mode 100644
index 0000000..2f7b50b
--- /dev/null
+++ b/libavfilter/vf_geq.c
@@ -0,0 +1,239 @@
+/*
+ * Copyright (C) 2006 Michael Niedermayer <michaelni@gmx.at>
+ * Copyright (C) 2012 Clément Bœsch <ubitux@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 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,
+ * 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 Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+/**
+ * @file
+ * Generic equation change filter
+ * Originally written by Michael Niedermayer for the MPlayer project, and
+ * ported by Clément Bœsch for FFmpeg.
+ */
+
+#include "libavutil/avstring.h"
+#include "libavutil/eval.h"
+#include "libavutil/opt.h"
+#include "libavutil/pixdesc.h"
+#include "internal.h"
+
+typedef struct {
+    const AVClass *class;
+    AVExpr *e[3];               ///< expressions for each plane
+    char *expr_str[3];          ///< expression strings for each plane
+    int framenum;               ///< frame counter
+    AVFilterBufferRef *picref;  ///< current input buffer
+    int hsub, vsub;             ///< chroma subsampling
+} GEQContext;
+
+#define OFFSET(x) offsetof(GEQContext, x)
+#define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
+
+static const AVOption geq_options[] = {
+    { "lum_expr",   "set luminance expression",   OFFSET(expr_str),                   AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS },
+    { "cb_expr",    "set chroma blue expression", OFFSET(expr_str) +   sizeof(char*), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS },
+    { "cr_expr",    "set chroma red expression",  OFFSET(expr_str) + 2*sizeof(char*), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS },
+    {NULL},
+};
+
+AVFILTER_DEFINE_CLASS(geq);
+
+static inline double getpix(void *priv, double x, double y, int plane)
+{
+    int xi, yi;
+    GEQContext *geq = priv;
+    AVFilterBufferRef *picref = geq->picref;
+    const uint8_t *src = picref->data[plane];
+    const int linesize = picref->linesize[plane];
+    const int w = picref->video->w >> (plane ? geq->hsub : 0);
+    const int h = picref->video->h >> (plane ? geq->vsub : 0);
+
+    xi = x = av_clipf(x, 0, w - 2);
+    yi = y = av_clipf(y, 0, h - 2);
+
+    x -= xi;
+    y -= yi;
+
+    return (1-y)*((1-x)*src[xi +  yi    * linesize] + x*src[xi + 1 +  yi    * linesize])
+          +   y *((1-x)*src[xi + (yi+1) * linesize] + x*src[xi + 1 + (yi+1) * linesize]);
+}
+
+//TODO: cubic interpolate
+//TODO: keep the last few frames
+static double lum(void *priv, double x, double y) { return getpix(priv, x, y, 0); }
+static double  cb(void *priv, double x, double y) { return getpix(priv, x, y, 1); }
+static double  cr(void *priv, double x, double y) { return getpix(priv, x, y, 2); }
+
+static const char *const var_names[] = {   "X",   "Y",   "W",   "H",   "N",   "SW",   "SH",   "T",        NULL };
+enum                                   { VAR_X, VAR_Y, VAR_W, VAR_H, VAR_N, VAR_SW, VAR_SH, VAR_T, VAR_VARS_NB };
+
+static av_cold int geq_init(AVFilterContext *ctx, const char *args)
+{
+    GEQContext *geq = ctx->priv;
+    int plane, ret = 0;
+    static const char *shorthand[] = { "lum_expr", "cb_expr", "cr_expr", NULL };
+
+    geq->class = &geq_class;
+    av_opt_set_defaults(geq);
+
+    if ((ret = av_opt_set_from_string(geq, args, shorthand, "=", ":")) < 0)
+        return ret;
+
+    if (!geq->expr_str[0]) {
+        av_log(ctx, AV_LOG_ERROR, "Luminance expression is mandatory\n");
+        ret = AVERROR(EINVAL);
+        goto end;
+    }
+
+    if (!geq->expr_str[1] && !geq->expr_str[2]) {
+        /* No chroma at all: fallback on luma */
+        geq->expr_str[1] = av_strdup(geq->expr_str[0]);
+        geq->expr_str[2] = av_strdup(geq->expr_str[0]);
+    } else {
+        /* One chroma unspecified, fallback on the other */
+        if (!geq->expr_str[1]) geq->expr_str[1] = av_strdup(geq->expr_str[2]);
+        if (!geq->expr_str[2]) geq->expr_str[2] = av_strdup(geq->expr_str[1]);
+    }
+
+    if (!geq->expr_str[1] || !geq->expr_str[2]) {
+        ret = AVERROR(ENOMEM);
+        goto end;
+    }
+
+    for (plane = 0; plane < 3; plane++) {
+        static double (*p[])(void *, double, double) = { lum, cb, cr };
+        static const char *const func2_names[]    = { "lum", "cb", "cr", "p", NULL };
+        double (*func2[])(void *, double, double) = { lum, cb, cr, p[plane], NULL };
+
+        ret = av_expr_parse(&geq->e[plane], geq->expr_str[plane], var_names,
+                            NULL, NULL, func2_names, func2, 0, ctx);
+        if (ret < 0)
+            break;
+    }
+
+end:
+    return ret;
+}
+
+static int geq_query_formats(AVFilterContext *ctx)
+{
+    static const enum PixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV444P,  AV_PIX_FMT_YUV422P,  AV_PIX_FMT_YUV420P,
+        AV_PIX_FMT_YUV411P,  AV_PIX_FMT_YUV410P,  AV_PIX_FMT_YUV440P,
+        AV_PIX_FMT_YUVA420P,
+        AV_PIX_FMT_NONE
+    };
+    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
+    return 0;
+}
+
+static int geq_config_props(AVFilterLink *inlink)
+{
+    GEQContext *geq = inlink->dst->priv;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
+
+    geq->hsub = desc->log2_chroma_w;
+    geq->vsub = desc->log2_chroma_h;
+    return 0;
+}
+
+static int geq_filter_frame(AVFilterLink *inlink, AVFilterBufferRef *in)
+{
+    int plane;
+    GEQContext *geq = inlink->dst->priv;
+    AVFilterLink *outlink = inlink->dst->outputs[0];
+    AVFilterBufferRef *out;
+    double values[VAR_VARS_NB] = {
+        [VAR_N] = geq->framenum++,
+        [VAR_T] = in->pts == AV_NOPTS_VALUE ? NAN : in->pts * av_q2d(inlink->time_base),
+    };
+
+    geq->picref = in;
+    out = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+    if (!out) {
+        avfilter_unref_bufferp(&in);
+        return AVERROR(ENOMEM);
+    }
+    avfilter_copy_buffer_ref_props(out, in);
+
+    for (plane = 0; plane < 3; plane++) {
+        int x, y;
+        uint8_t *dst = out->data[plane];
+        const int linesize = out->linesize[plane];
+        const int w = inlink->w >> (plane ? geq->hsub : 0);
+        const int h = inlink->h >> (plane ? geq->vsub : 0);
+
+        values[VAR_W]  = w;
+        values[VAR_H]  = h;
+        values[VAR_SW] = w / (double)inlink->w;
+        values[VAR_SH] = h / (double)inlink->h;
+
+        for (y = 0; y < h; y++) {
+            values[VAR_Y] = y;
+            for (x = 0; x < w; x++) {
+                values[VAR_X] = x;
+                dst[x] = av_expr_eval(geq->e[plane], values, geq);
+            }
+            dst += linesize;
+        }
+    }
+
+    avfilter_unref_bufferp(&geq->picref);
+    return ff_filter_frame(outlink, out);
+}
+
+static av_cold void geq_uninit(AVFilterContext *ctx)
+{
+    int i;
+    GEQContext *geq = ctx->priv;
+
+    for (i = 0; i < FF_ARRAY_ELEMS(geq->e); i++)
+        av_expr_free(geq->e[i]);
+    av_opt_free(geq);
+}
+
+static const AVFilterPad geq_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .config_props = geq_config_props,
+        .filter_frame = geq_filter_frame,
+        .min_perms    = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad geq_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
+AVFilter avfilter_vf_geq = {
+    .name          = "geq",
+    .description   = NULL_IF_CONFIG_SMALL("Apply generic equation to each pixel."),
+    .priv_size     = sizeof(GEQContext),
+    .init          = geq_init,
+    .uninit        = geq_uninit,
+    .query_formats = geq_query_formats,
+    .inputs        = geq_inputs,
+    .outputs       = geq_outputs,
+    .priv_class    = &geq_class,
+};
diff --git a/libavfilter/vf_gradfun.c b/libavfilter/vf_gradfun.c
index 5c49060..32d8796 100644
--- a/libavfilter/vf_gradfun.c
+++ b/libavfilter/vf_gradfun.c
@@ -135,7 +135,7 @@
     gf->blur_line = ff_gradfun_blur_line_c;
     gf->filter_line = ff_gradfun_filter_line_c;
 
-    if (HAVE_MMX)
+    if (ARCH_X86)
         ff_gradfun_init_x86(gf);
 
     av_log(ctx, AV_LOG_VERBOSE, "threshold:%.2f radius:%d\n", thresh, gf->radius);
@@ -151,12 +151,12 @@
 
 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
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV410P,            AV_PIX_FMT_YUV420P,
+        AV_PIX_FMT_GRAY8,              AV_PIX_FMT_NV12,
+        AV_PIX_FMT_NV21,               AV_PIX_FMT_YUV444P,
+        AV_PIX_FMT_YUV422P,            AV_PIX_FMT_YUV411P,
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -167,8 +167,9 @@
 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;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
+    int hsub = desc->log2_chroma_w;
+    int vsub = desc->log2_chroma_h;
 
     gf->buf = av_mallocz((FFALIGN(inlink->w, 16) * (gf->radius + 1) / 2 + 32) * sizeof(uint16_t));
     if (!gf->buf)
@@ -181,20 +182,29 @@
     return 0;
 }
 
-static int null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
-{
-    return 0;
-}
-
-static int end_frame(AVFilterLink *inlink)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *in)
 {
     GradFunContext *gf = inlink->dst->priv;
-    AVFilterBufferRef *inpic = inlink->cur_buf;
     AVFilterLink *outlink = inlink->dst->outputs[0];
-    AVFilterBufferRef *outpic = outlink->out_buf;
-    int p, ret;
+    AVFilterBufferRef *out;
+    int p, direct = 0;
 
-    for (p = 0; p < 4 && inpic->data[p]; p++) {
+    if (in->perms & AV_PERM_WRITE) {
+        direct = 1;
+        out = in;
+    } else {
+        out = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+        if (!out) {
+            avfilter_unref_bufferp(&in);
+            return AVERROR(ENOMEM);
+        }
+
+        avfilter_copy_buffer_ref_props(out, in);
+        out->video->w = outlink->w;
+        out->video->h = outlink->h;
+    }
+
+    for (p = 0; p < 4 && in->data[p]; p++) {
         int w = inlink->w;
         int h = inlink->h;
         int r = gf->radius;
@@ -205,17 +215,36 @@
         }
 
         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);
+            filter(gf, out->data[p], in->data[p], w, h, out->linesize[p], in->linesize[p], r);
+        else if (out->data[p] != in->data[p])
+            av_image_copy_plane(out->data[p], out->linesize[p], in->data[p], in->linesize[p], w, h);
     }
 
-    if ((ret = ff_draw_slice(outlink, 0, inlink->h, 1)) < 0 ||
-        (ret = ff_end_frame(outlink)) < 0)
-        return ret;
-    return 0;
+    if (!direct)
+        avfilter_unref_bufferp(&in);
+
+    return ff_filter_frame(outlink, out);
 }
 
+static const AVFilterPad avfilter_vf_gradfun_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .config_props = config_input,
+        .filter_frame = filter_frame,
+        .min_perms    = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_gradfun_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_gradfun = {
     .name          = "gradfun",
     .description   = NULL_IF_CONFIG_SMALL("Debands video quickly using gradients."),
@@ -224,15 +253,6 @@
     .uninit        = uninit,
     .query_formats = query_formats,
 
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .config_props     = config_input,
-                                          .start_frame      = ff_inplace_start_frame,
-                                          .draw_slice       = null_draw_slice,
-                                          .end_frame        = end_frame,
-                                          .min_perms        = AV_PERM_READ, },
-                                        { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_gradfun_inputs,
+    .outputs   = avfilter_vf_gradfun_outputs,
 };
diff --git a/libavfilter/vf_hflip.c b/libavfilter/vf_hflip.c
index eada9a0..c583ffd 100644
--- a/libavfilter/vf_hflip.c
+++ b/libavfilter/vf_hflip.c
@@ -42,32 +42,32 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
-        PIX_FMT_RGB48BE,      PIX_FMT_RGB48LE,
-        PIX_FMT_BGR48BE,      PIX_FMT_BGR48LE,
-        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_RGB444BE,     PIX_FMT_RGB444LE,
-        PIX_FMT_BGR565BE,     PIX_FMT_BGR565LE,
-        PIX_FMT_BGR555BE,     PIX_FMT_BGR555LE,
-        PIX_FMT_BGR444BE,     PIX_FMT_BGR444LE,
-        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
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_RGB48BE,      AV_PIX_FMT_RGB48LE,
+        AV_PIX_FMT_BGR48BE,      AV_PIX_FMT_BGR48LE,
+        AV_PIX_FMT_ARGB,         AV_PIX_FMT_RGBA,
+        AV_PIX_FMT_ABGR,         AV_PIX_FMT_BGRA,
+        AV_PIX_FMT_RGB24,        AV_PIX_FMT_BGR24,
+        AV_PIX_FMT_RGB565BE,     AV_PIX_FMT_RGB565LE,
+        AV_PIX_FMT_RGB555BE,     AV_PIX_FMT_RGB555LE,
+        AV_PIX_FMT_RGB444BE,     AV_PIX_FMT_RGB444LE,
+        AV_PIX_FMT_BGR565BE,     AV_PIX_FMT_BGR565LE,
+        AV_PIX_FMT_BGR555BE,     AV_PIX_FMT_BGR555LE,
+        AV_PIX_FMT_BGR444BE,     AV_PIX_FMT_BGR444LE,
+        AV_PIX_FMT_GRAY16BE,     AV_PIX_FMT_GRAY16LE,
+        AV_PIX_FMT_YUV420P16LE,  AV_PIX_FMT_YUV420P16BE,
+        AV_PIX_FMT_YUV422P16LE,  AV_PIX_FMT_YUV422P16BE,
+        AV_PIX_FMT_YUV444P16LE,  AV_PIX_FMT_YUV444P16BE,
+        AV_PIX_FMT_YUV444P,      AV_PIX_FMT_YUV422P,
+        AV_PIX_FMT_YUV420P,      AV_PIX_FMT_YUV411P,
+        AV_PIX_FMT_YUV410P,      AV_PIX_FMT_YUV440P,
+        AV_PIX_FMT_YUVJ444P,     AV_PIX_FMT_YUVJ422P,
+        AV_PIX_FMT_YUVJ420P,     AV_PIX_FMT_YUVJ440P,
+        AV_PIX_FMT_YUVA420P,
+        AV_PIX_FMT_RGB8,         AV_PIX_FMT_BGR8,
+        AV_PIX_FMT_RGB4_BYTE,    AV_PIX_FMT_BGR4_BYTE,
+        AV_PIX_FMT_PAL8,         AV_PIX_FMT_GRAY8,
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -77,46 +77,43 @@
 static int config_props(AVFilterLink *inlink)
 {
     FlipContext *flip = inlink->dst->priv;
-    const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
+    const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(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;
+    flip->hsub = pix_desc->log2_chroma_w;
+    flip->vsub = pix_desc->log2_chroma_h;
 
     return 0;
 }
 
-static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *in)
 {
-    AVFilterLink *outlink = inlink->dst->outputs[0];
-
-    outlink->out_buf =
-        ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
-    avfilter_copy_buffer_ref_props(outlink->out_buf, picref);
-
-    /* copy palette if required */
-    if (av_pix_fmt_descriptors[inlink->format].flags & PIX_FMT_PAL)
-        memcpy(inlink->dst->outputs[0]->out_buf->data[1], picref->data[1], AVPALETTE_SIZE);
-
-    return ff_start_frame(outlink, avfilter_ref_buffer(outlink->out_buf, ~0));
-}
-
-static int 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;
+    AVFilterContext *ctx  = inlink->dst;
+    FlipContext *flip     = ctx->priv;
+    AVFilterLink *outlink = ctx->outputs[0];
+    AVFilterBufferRef *out;
     uint8_t *inrow, *outrow;
     int i, j, plane, step, hsub, vsub;
 
-    for (plane = 0; plane < 4 && inpic->data[plane]; plane++) {
+    out = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+    if (!out) {
+        avfilter_unref_bufferp(&in);
+        return AVERROR(ENOMEM);
+    }
+    avfilter_copy_buffer_ref_props(out, in);
+
+    /* copy palette if required */
+    if (av_pix_fmt_desc_get(inlink->format)->flags & PIX_FMT_PAL)
+        memcpy(out->data[1], in->data[1], AVPALETTE_SIZE);
+
+    for (plane = 0; plane < 4 && in->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++) {
+        outrow = out->data[plane];
+        inrow  = in ->data[plane] + ((inlink->w >> hsub) - 1) * step;
+        for (i = 0; i < in->video->h >> vsub; i++) {
             switch (step) {
             case 1:
                 for (j = 0; j < (inlink->w >> hsub); j++)
@@ -157,28 +154,40 @@
                     memcpy(outrow + j*step, inrow - j*step, step);
             }
 
-            inrow  += inpic ->linesize[plane];
-            outrow += outpic->linesize[plane];
+            inrow  += in ->linesize[plane];
+            outrow += out->linesize[plane];
         }
     }
 
-    return ff_draw_slice(inlink->dst->outputs[0], y, h, slice_dir);
+    avfilter_unref_bufferp(&in);
+    return ff_filter_frame(outlink, out);
 }
 
+static const AVFilterPad avfilter_vf_hflip_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .filter_frame = filter_frame,
+        .config_props = config_props,
+        .min_perms    = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_hflip_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 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    = (const 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   = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_VIDEO, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_hflip_inputs,
+    .outputs   = avfilter_vf_hflip_outputs,
 };
diff --git a/libavfilter/vf_hqdn3d.c b/libavfilter/vf_hqdn3d.c
index 2fe7056..939a31d 100644
--- a/libavfilter/vf_hqdn3d.c
+++ b/libavfilter/vf_hqdn3d.c
@@ -263,27 +263,27 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
-        PIX_FMT_YUV420P,
-        PIX_FMT_YUV422P,
-        PIX_FMT_YUV444P,
-        PIX_FMT_YUV410P,
-        PIX_FMT_YUV411P,
-        PIX_FMT_YUV440P,
-        PIX_FMT_YUVJ420P,
-        PIX_FMT_YUVJ422P,
-        PIX_FMT_YUVJ444P,
-        PIX_FMT_YUVJ440P,
-        AV_NE( PIX_FMT_YUV420P9BE, PIX_FMT_YUV420P9LE ),
-        AV_NE( PIX_FMT_YUV422P9BE, PIX_FMT_YUV422P9LE ),
-        AV_NE( PIX_FMT_YUV444P9BE, PIX_FMT_YUV444P9LE ),
-        AV_NE( PIX_FMT_YUV420P10BE, PIX_FMT_YUV420P10LE ),
-        AV_NE( PIX_FMT_YUV422P10BE, PIX_FMT_YUV422P10LE ),
-        AV_NE( PIX_FMT_YUV444P10BE, PIX_FMT_YUV444P10LE ),
-        AV_NE( PIX_FMT_YUV420P16BE, PIX_FMT_YUV420P16LE ),
-        AV_NE( PIX_FMT_YUV422P16BE, PIX_FMT_YUV422P16LE ),
-        AV_NE( PIX_FMT_YUV444P16BE, PIX_FMT_YUV444P16LE ),
-        PIX_FMT_NONE
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV420P,
+        AV_PIX_FMT_YUV422P,
+        AV_PIX_FMT_YUV444P,
+        AV_PIX_FMT_YUV410P,
+        AV_PIX_FMT_YUV411P,
+        AV_PIX_FMT_YUV440P,
+        AV_PIX_FMT_YUVJ420P,
+        AV_PIX_FMT_YUVJ422P,
+        AV_PIX_FMT_YUVJ444P,
+        AV_PIX_FMT_YUVJ440P,
+        AV_NE( AV_PIX_FMT_YUV420P9BE, AV_PIX_FMT_YUV420P9LE ),
+        AV_NE( AV_PIX_FMT_YUV422P9BE, AV_PIX_FMT_YUV422P9LE ),
+        AV_NE( AV_PIX_FMT_YUV444P9BE, AV_PIX_FMT_YUV444P9LE ),
+        AV_NE( AV_PIX_FMT_YUV420P10BE, AV_PIX_FMT_YUV420P10LE ),
+        AV_NE( AV_PIX_FMT_YUV422P10BE, AV_PIX_FMT_YUV422P10LE ),
+        AV_NE( AV_PIX_FMT_YUV444P10BE, AV_PIX_FMT_YUV444P10LE ),
+        AV_NE( AV_PIX_FMT_YUV420P16BE, AV_PIX_FMT_YUV420P16LE ),
+        AV_NE( AV_PIX_FMT_YUV422P16BE, AV_PIX_FMT_YUV422P16LE ),
+        AV_NE( AV_PIX_FMT_YUV444P16BE, AV_PIX_FMT_YUV444P16LE ),
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -294,11 +294,12 @@
 static int config_input(AVFilterLink *inlink)
 {
     HQDN3DContext *hqdn3d = inlink->dst->priv;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
     int i;
 
-    hqdn3d->hsub = av_pix_fmt_descriptors[inlink->format].log2_chroma_w;
-    hqdn3d->vsub = av_pix_fmt_descriptors[inlink->format].log2_chroma_h;
-    hqdn3d->depth = av_pix_fmt_descriptors[inlink->format].comp[0].depth_minus1+1;
+    hqdn3d->hsub  = desc->log2_chroma_w;
+    hqdn3d->vsub  = desc->log2_chroma_h;
+    hqdn3d->depth = desc->comp[0].depth_minus1+1;
 
     hqdn3d->line = av_malloc(inlink->w * sizeof(*hqdn3d->line));
     if (!hqdn3d->line)
@@ -320,34 +321,63 @@
     return 0;
 }
 
-static int null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
-{
-    return 0;
-}
-
-static int end_frame(AVFilterLink *inlink)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *in)
 {
     HQDN3DContext *hqdn3d = inlink->dst->priv;
     AVFilterLink *outlink = inlink->dst->outputs[0];
-    AVFilterBufferRef *inpic  = inlink ->cur_buf;
-    AVFilterBufferRef *outpic = outlink->out_buf;
-    int ret, c;
+
+    AVFilterBufferRef *out;
+    int direct = 0, c;
+
+    if (in->perms & AV_PERM_WRITE) {
+        direct = 1;
+        out = in;
+    } else {
+        out = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+        if (!out) {
+            avfilter_unref_bufferp(&in);
+            return AVERROR(ENOMEM);
+        }
+
+        avfilter_copy_buffer_ref_props(out, in);
+        out->video->w = outlink->w;
+        out->video->h = outlink->h;
+    }
 
     for (c = 0; c < 3; c++) {
-        denoise(hqdn3d, inpic->data[c], outpic->data[c],
+        denoise(hqdn3d, in->data[c], out->data[c],
                 hqdn3d->line, &hqdn3d->frame_prev[c],
-                inpic->video->w >> (!!c * hqdn3d->hsub),
-                inpic->video->h >> (!!c * hqdn3d->vsub),
-                inpic->linesize[c], outpic->linesize[c],
+                in->video->w >> (!!c * hqdn3d->hsub),
+                in->video->h >> (!!c * hqdn3d->vsub),
+                in->linesize[c], out->linesize[c],
                 hqdn3d->coefs[c?2:0], hqdn3d->coefs[c?3:1]);
     }
 
-    if ((ret = ff_draw_slice(outlink, 0, inpic->video->h, 1)) < 0 ||
-        (ret = ff_end_frame(outlink)) < 0)
-        return ret;
-    return 0;
+    if (!direct)
+        avfilter_unref_bufferp(&in);
+
+    return ff_filter_frame(outlink, out);
 }
 
+static const AVFilterPad avfilter_vf_hqdn3d_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .config_props = config_input,
+        .filter_frame = filter_frame,
+    },
+    { NULL }
+};
+
+
+static const AVFilterPad avfilter_vf_hqdn3d_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_hqdn3d = {
     .name          = "hqdn3d",
     .description   = NULL_IF_CONFIG_SMALL("Apply a High Quality 3D Denoiser."),
@@ -357,15 +387,7 @@
     .uninit        = uninit,
     .query_formats = query_formats,
 
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .start_frame      = ff_inplace_start_frame,
-                                          .draw_slice       = null_draw_slice,
-                                          .config_props     = config_input,
-                                          .end_frame        = end_frame },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_hqdn3d_inputs,
 
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO },
-                                        { .name = NULL}},
+    .outputs   = avfilter_vf_hqdn3d_outputs,
 };
diff --git a/libavfilter/vf_hue.c b/libavfilter/vf_hue.c
index 3048a59..7bc3d37 100644
--- a/libavfilter/vf_hue.c
+++ b/libavfilter/vf_hue.c
@@ -236,12 +236,12 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
-        PIX_FMT_YUV444P,      PIX_FMT_YUV422P,
-        PIX_FMT_YUV420P,      PIX_FMT_YUV411P,
-        PIX_FMT_YUV410P,      PIX_FMT_YUV440P,
-        PIX_FMT_YUVA420P,
-        PIX_FMT_NONE
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV444P,      AV_PIX_FMT_YUV422P,
+        AV_PIX_FMT_YUV420P,      AV_PIX_FMT_YUV411P,
+        AV_PIX_FMT_YUV410P,      AV_PIX_FMT_YUV440P,
+        AV_PIX_FMT_YUVA420P,
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -252,7 +252,7 @@
 static int config_props(AVFilterLink *inlink)
 {
     HueContext *hue = inlink->dst->priv;
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[inlink->format];
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
 
     hue->hsub = desc->log2_chroma_w;
     hue->vsub = desc->log2_chroma_h;
@@ -307,22 +307,18 @@
 #define TS2D(ts) ((ts) == AV_NOPTS_VALUE ? NAN : (double)(ts))
 #define TS2T(ts, tb) ((ts) == AV_NOPTS_VALUE ? NAN : (double)(ts) * av_q2d(tb))
 
-static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpic)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *inpic)
 {
     HueContext *hue = inlink->dst->priv;
     AVFilterLink *outlink = inlink->dst->outputs[0];
-    AVFilterBufferRef *buf_out;
+    AVFilterBufferRef *outpic;
 
-    outlink->out_buf = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
-    if (!outlink->out_buf)
+    outpic = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+    if (!outpic) {
+        avfilter_unref_bufferp(&inpic);
         return AVERROR(ENOMEM);
-
-    avfilter_copy_buffer_ref_props(outlink->out_buf, inpic);
-    outlink->out_buf->video->w = outlink->w;
-    outlink->out_buf->video->h = outlink->h;
-    buf_out = avfilter_ref_buffer(outlink->out_buf, ~0);
-    if (!buf_out)
-        return AVERROR(ENOMEM);
+    }
+    avfilter_copy_buffer_ref_props(outpic, inpic);
 
     if (!hue->flat_syntax) {
         hue->var_values[VAR_T]   = TS2T(inpic->pts, inlink->time_base);
@@ -356,35 +352,17 @@
 
     hue->var_values[VAR_N] += 1;
 
-    return ff_start_frame(outlink, buf_out);
-}
-
-static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
-{
-    HueContext        *hue    = inlink->dst->priv;
-    AVFilterBufferRef *inpic  = inlink->cur_buf;
-    AVFilterBufferRef *outpic = inlink->dst->outputs[0]->out_buf;
-    uint8_t *inrow[3], *outrow[3]; // 0 : Y, 1 : U, 2 : V
-    int plane;
-
-    inrow[0]  = inpic->data[0]  + y * inpic->linesize[0];
-    outrow[0] = outpic->data[0] + y * outpic->linesize[0];
-
-    for (plane = 1; plane < 3; plane++) {
-        inrow[plane]  = inpic->data[plane]  + (y >> hue->vsub) * inpic->linesize[plane];
-        outrow[plane] = outpic->data[plane] + (y >> hue->vsub) * outpic->linesize[plane];
-    }
-
-    av_image_copy_plane(outrow[0], outpic->linesize[0],
-                        inrow[0],  inpic->linesize[0],
+    av_image_copy_plane(outpic->data[0], outpic->linesize[0],
+                        inpic->data[0],  inpic->linesize[0],
                         inlink->w, inlink->h);
 
-    process_chrominance(outrow[1], outrow[2], outpic->linesize[1],
-                        inrow[1], inrow[2], inpic->linesize[1],
+    process_chrominance(outpic->data[1], outpic->data[2], outpic->linesize[1],
+                        inpic->data[1],  inpic->data[2],  inpic->linesize[1],
                         inlink->w >> hue->hsub, inlink->h >> hue->vsub,
                         hue->hue_cos, hue->hue_sin);
 
-    return ff_draw_slice(inlink->dst->outputs[0], y, h, slice_dir);
+    avfilter_unref_bufferp(&inpic);
+    return ff_filter_frame(outlink, outpic);
 }
 
 static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
@@ -396,6 +374,25 @@
         return AVERROR(ENOSYS);
 }
 
+static const AVFilterPad hue_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .filter_frame = filter_frame,
+        .config_props = config_props,
+        .min_perms    = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad hue_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_hue = {
     .name        = "hue",
     .description = NULL_IF_CONFIG_SMALL("Adjust the hue and saturation of the input video."),
@@ -406,24 +403,7 @@
     .uninit        = uninit,
     .query_formats = query_formats,
     .process_command = process_command,
-
-    .inputs = (const 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 = (const AVFilterPad[]) {
-        {
-            .name         = "default",
-            .type         = AVMEDIA_TYPE_VIDEO,
-        },
-        { .name = NULL }
-    },
-    .priv_class = &hue_class,
+    .inputs          = hue_inputs,
+    .outputs         = hue_outputs,
+    .priv_class      = &hue_class,
 };
diff --git a/libavfilter/vf_idet.c b/libavfilter/vf_idet.c
index 8942ced..cc20fac 100644
--- a/libavfilter/vf_idet.c
+++ b/libavfilter/vf_idet.c
@@ -49,7 +49,6 @@
     AVFilterBufferRef *cur;
     AVFilterBufferRef *next;
     AVFilterBufferRef *prev;
-    AVFilterBufferRef *out;
     int (*filter_line)(const uint8_t *prev, const uint8_t *cur, const uint8_t *next, int w);
 
     const AVPixFmtDescriptor *csp;
@@ -119,11 +118,11 @@
         }
     }
 
-    if      (alpha[0] / (float)alpha[1] > idet->interlace_threshold){
+    if      (alpha[0] > idet->interlace_threshold * alpha[1]){
         type = TFF;
-    }else if(alpha[1] / (float)alpha[0] > idet->interlace_threshold){
+    }else if(alpha[1] > idet->interlace_threshold * alpha[0]){
         type = BFF;
-    }else if(alpha[1] / (float)delta    > idet->progressive_threshold){
+    }else if(alpha[1] > idet->progressive_threshold * delta){
         type = PROGRSSIVE;
     }else{
         type = UNDETERMINED;
@@ -176,6 +175,7 @@
     idet->prev = idet->cur;
     idet->cur  = idet->next;
     idet->next = picref;
+    link->cur_buf = NULL;
 
     if (!idet->cur)
         return 0;
@@ -195,7 +195,7 @@
         return 0;
 
     if (!idet->csp)
-        idet->csp = &av_pix_fmt_descriptors[link->format];
+        idet->csp = av_pix_fmt_desc_get(link->format);
     if (idet->csp->comp[0].depth_minus1 / 8 == 1)
         idet->filter_line = (void*)filter_line_c_16bit;
 
@@ -254,34 +254,34 @@
            idet->poststat[UNDETERMINED]
     );
 
-    if (idet->prev) avfilter_unref_buffer(idet->prev);
-    if (idet->cur ) avfilter_unref_buffer(idet->cur );
-    if (idet->next) avfilter_unref_buffer(idet->next);
+    avfilter_unref_bufferp(&idet->prev);
+    avfilter_unref_bufferp(&idet->cur );
+    avfilter_unref_bufferp(&idet->next);
 }
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
-        PIX_FMT_YUV420P,
-        PIX_FMT_YUV422P,
-        PIX_FMT_YUV444P,
-        PIX_FMT_YUV410P,
-        PIX_FMT_YUV411P,
-        PIX_FMT_GRAY8,
-        PIX_FMT_YUVJ420P,
-        PIX_FMT_YUVJ422P,
-        PIX_FMT_YUVJ444P,
-        AV_NE( PIX_FMT_GRAY16BE, PIX_FMT_GRAY16LE ),
-        PIX_FMT_YUV440P,
-        PIX_FMT_YUVJ440P,
-        AV_NE( PIX_FMT_YUV420P10BE, PIX_FMT_YUV420P10LE ),
-        AV_NE( PIX_FMT_YUV422P10BE, PIX_FMT_YUV422P10LE ),
-        AV_NE( PIX_FMT_YUV444P10BE, PIX_FMT_YUV444P10LE ),
-        AV_NE( PIX_FMT_YUV420P16BE, PIX_FMT_YUV420P16LE ),
-        AV_NE( PIX_FMT_YUV422P16BE, PIX_FMT_YUV422P16LE ),
-        AV_NE( PIX_FMT_YUV444P16BE, PIX_FMT_YUV444P16LE ),
-        PIX_FMT_YUVA420P,
-        PIX_FMT_NONE
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV420P,
+        AV_PIX_FMT_YUV422P,
+        AV_PIX_FMT_YUV444P,
+        AV_PIX_FMT_YUV410P,
+        AV_PIX_FMT_YUV411P,
+        AV_PIX_FMT_GRAY8,
+        AV_PIX_FMT_YUVJ420P,
+        AV_PIX_FMT_YUVJ422P,
+        AV_PIX_FMT_YUVJ444P,
+        AV_NE( AV_PIX_FMT_GRAY16BE, AV_PIX_FMT_GRAY16LE ),
+        AV_PIX_FMT_YUV440P,
+        AV_PIX_FMT_YUVJ440P,
+        AV_NE( AV_PIX_FMT_YUV420P10BE, AV_PIX_FMT_YUV420P10LE ),
+        AV_NE( AV_PIX_FMT_YUV422P10BE, AV_PIX_FMT_YUV422P10LE ),
+        AV_NE( AV_PIX_FMT_YUV444P10BE, AV_PIX_FMT_YUV444P10LE ),
+        AV_NE( AV_PIX_FMT_YUV420P16BE, AV_PIX_FMT_YUV420P16LE ),
+        AV_NE( AV_PIX_FMT_YUV422P16BE, AV_PIX_FMT_YUV422P16LE ),
+        AV_NE( AV_PIX_FMT_YUV444P16BE, AV_PIX_FMT_YUV444P16LE ),
+        AV_PIX_FMT_YUVA420P,
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -310,6 +310,29 @@
 
 static int null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { return 0; }
 
+static const AVFilterPad idet_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .start_frame  = start_frame,
+        .draw_slice   = null_draw_slice,
+        .end_frame    = end_frame,
+        .min_perms    = AV_PERM_PRESERVE,
+    },
+    { NULL }
+};
+
+static const AVFilterPad idet_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .rej_perms     = AV_PERM_WRITE,
+        .poll_frame    = poll_frame,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_idet = {
     .name          = "idet",
     .description   = NULL_IF_CONFIG_SMALL("Interlace detect Filter."),
@@ -318,19 +341,6 @@
     .init          = init,
     .uninit        = uninit,
     .query_formats = query_formats,
-
-    .inputs    = (const AVFilterPad[]) {{ .name       = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .start_frame      = start_frame,
-                                          .draw_slice       = null_draw_slice,
-                                          .end_frame        = end_frame,
-                                          .min_perms        = AV_PERM_PRESERVE },
-                                        { .name = NULL}},
-
-    .outputs   = (const AVFilterPad[]) {{ .name       = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .rej_perms        = AV_PERM_WRITE,
-                                          .poll_frame       = poll_frame,
-                                          .request_frame    = request_frame, },
-                                        { .name = NULL}},
+    .inputs        = idet_inputs,
+    .outputs       = idet_outputs,
 };
diff --git a/libavfilter/vf_libopencv.c b/libavfilter/vf_libopencv.c
index e0041a7..1b8a5dc 100644
--- a/libavfilter/vf_libopencv.c
+++ b/libavfilter/vf_libopencv.c
@@ -32,16 +32,17 @@
 #include "libavutil/file.h"
 #include "avfilter.h"
 #include "formats.h"
+#include "internal.h"
 #include "video.h"
 
-static void fill_iplimage_from_picref(IplImage *img, const AVFilterBufferRef *picref, enum PixelFormat pixfmt)
+static void fill_iplimage_from_picref(IplImage *img, const AVFilterBufferRef *picref, enum AVPixelFormat 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; }
+    if      (pixfmt == AV_PIX_FMT_GRAY8) { depth = IPL_DEPTH_8U;  channels_nb = 1; }
+    else if (pixfmt == AV_PIX_FMT_BGRA)  { depth = IPL_DEPTH_8U;  channels_nb = 4; }
+    else if (pixfmt == AV_PIX_FMT_BGR24) { depth = IPL_DEPTH_8U;  channels_nb = 3; }
     else return;
 
     tmpimg = cvCreateImageHeader((CvSize){picref->video->w, picref->video->h}, depth, channels_nb);
@@ -52,7 +53,7 @@
     img->widthStep = picref->linesize[0];
 }
 
-static void fill_picref_from_iplimage(AVFilterBufferRef *picref, const IplImage *img, enum PixelFormat pixfmt)
+static void fill_picref_from_iplimage(AVFilterBufferRef *picref, const IplImage *img, enum AVPixelFormat pixfmt)
 {
     picref->linesize[0] = img->widthStep;
     picref->data[0]     = img->imageData;
@@ -60,19 +61,14 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
-        PIX_FMT_BGR24, PIX_FMT_BGRA, PIX_FMT_GRAY8, PIX_FMT_NONE
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_BGR24, AV_PIX_FMT_BGRA, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
     return 0;
 }
 
-static int null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
-{
-    return 0;
-}
-
 typedef struct {
     const char *name;
     int (*init)(AVFilterContext *ctx, const char *args);
@@ -355,27 +351,49 @@
     memset(ocv, 0, sizeof(*ocv));
 }
 
-static int end_frame(AVFilterLink *inlink)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *in)
 {
     AVFilterContext *ctx = inlink->dst;
     OCVContext *ocv = ctx->priv;
     AVFilterLink *outlink= inlink->dst->outputs[0];
-    AVFilterBufferRef *inpicref  = inlink ->cur_buf;
-    AVFilterBufferRef *outpicref = outlink->out_buf;
+    AVFilterBufferRef *out;
     IplImage inimg, outimg;
-    int ret;
 
-    fill_iplimage_from_picref(&inimg , inpicref , inlink->format);
-    fill_iplimage_from_picref(&outimg, outpicref, inlink->format);
+    out = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+    if (!out) {
+        avfilter_unref_bufferp(&in);
+        return AVERROR(ENOMEM);
+    }
+    avfilter_copy_buffer_ref_props(out, in);
+
+    fill_iplimage_from_picref(&inimg , in , inlink->format);
+    fill_iplimage_from_picref(&outimg, out, inlink->format);
     ocv->end_frame_filter(ctx, &inimg, &outimg);
-    fill_picref_from_iplimage(outpicref, &outimg, inlink->format);
+    fill_picref_from_iplimage(out, &outimg, inlink->format);
 
-    if ((ret = ff_draw_slice(outlink, 0, outlink->h, 1)) < 0 ||
-        (ret = ff_end_frame(outlink)) < 0)
-        return ret;
-    return 0;
+    avfilter_unref_bufferp(&in);
+
+    return ff_filter_frame(outlink, out);
 }
 
+static const AVFilterPad avfilter_vf_ocv_inputs[] = {
+    {
+        .name       = "default",
+        .type       = AVMEDIA_TYPE_VIDEO,
+        .filter_frame = filter_frame,
+        .min_perms  = AV_PERM_READ
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_ocv_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_ocv = {
     .name        = "ocv",
     .description = NULL_IF_CONFIG_SMALL("Apply transform using libopencv."),
@@ -386,14 +404,7 @@
     .init = init,
     .uninit = uninit,
 
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .draw_slice       = null_draw_slice,
-                                          .end_frame        = end_frame,
-                                          .min_perms        = AV_PERM_READ },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_ocv_inputs,
 
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO, },
-                                        { .name = NULL}},
+    .outputs   = avfilter_vf_ocv_outputs,
 };
diff --git a/libavfilter/vf_lut.c b/libavfilter/vf_lut.c
index 4a7bf62..543785a 100644
--- a/libavfilter/vf_lut.c
+++ b/libavfilter/vf_lut.c
@@ -106,26 +106,26 @@
 }
 
 #define YUV_FORMATS                                         \
-    PIX_FMT_YUV444P,  PIX_FMT_YUV422P,  PIX_FMT_YUV420P,    \
-    PIX_FMT_YUV411P,  PIX_FMT_YUV410P,  PIX_FMT_YUV440P,    \
-    PIX_FMT_YUVA420P,                                       \
-    PIX_FMT_YUVJ444P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ420P,   \
-    PIX_FMT_YUVJ440P
+    AV_PIX_FMT_YUV444P,  AV_PIX_FMT_YUV422P,  AV_PIX_FMT_YUV420P,    \
+    AV_PIX_FMT_YUV411P,  AV_PIX_FMT_YUV410P,  AV_PIX_FMT_YUV440P,    \
+    AV_PIX_FMT_YUVA420P,                                       \
+    AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ420P,   \
+    AV_PIX_FMT_YUVJ440P
 
 #define RGB_FORMATS                             \
-    PIX_FMT_ARGB,         PIX_FMT_RGBA,         \
-    PIX_FMT_ABGR,         PIX_FMT_BGRA,         \
-    PIX_FMT_RGB24,        PIX_FMT_BGR24
+    AV_PIX_FMT_ARGB,         AV_PIX_FMT_RGBA,         \
+    AV_PIX_FMT_ABGR,         AV_PIX_FMT_BGRA,         \
+    AV_PIX_FMT_RGB24,        AV_PIX_FMT_BGR24
 
-static const enum PixelFormat yuv_pix_fmts[] = { YUV_FORMATS, PIX_FMT_NONE };
-static const enum PixelFormat rgb_pix_fmts[] = { RGB_FORMATS, PIX_FMT_NONE };
-static const enum PixelFormat all_pix_fmts[] = { RGB_FORMATS, YUV_FORMATS, PIX_FMT_NONE };
+static const enum AVPixelFormat yuv_pix_fmts[] = { YUV_FORMATS, AV_PIX_FMT_NONE };
+static const enum AVPixelFormat rgb_pix_fmts[] = { RGB_FORMATS, AV_PIX_FMT_NONE };
+static const enum AVPixelFormat all_pix_fmts[] = { RGB_FORMATS, YUV_FORMATS, AV_PIX_FMT_NONE };
 
 static int query_formats(AVFilterContext *ctx)
 {
     LutContext *lut = ctx->priv;
 
-    const enum PixelFormat *pix_fmts = lut->is_rgb ? rgb_pix_fmts :
+    const enum AVPixelFormat *pix_fmts = lut->is_rgb ? rgb_pix_fmts :
                                        lut->is_yuv ? yuv_pix_fmts : all_pix_fmts;
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -174,7 +174,7 @@
 {
     AVFilterContext *ctx = inlink->dst;
     LutContext *lut = ctx->priv;
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[inlink->format];
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
     int rgba_map[4]; /* component index -> RGBA color index map */
     int min[4], max[4];
     int val, comp, ret;
@@ -186,13 +186,13 @@
     lut->var_values[VAR_H] = inlink->h;
 
     switch (inlink->format) {
-    case PIX_FMT_YUV410P:
-    case PIX_FMT_YUV411P:
-    case PIX_FMT_YUV420P:
-    case PIX_FMT_YUV422P:
-    case PIX_FMT_YUV440P:
-    case PIX_FMT_YUV444P:
-    case PIX_FMT_YUVA420P:
+    case AV_PIX_FMT_YUV410P:
+    case AV_PIX_FMT_YUV411P:
+    case AV_PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUV422P:
+    case AV_PIX_FMT_YUV440P:
+    case AV_PIX_FMT_YUV444P:
+    case AV_PIX_FMT_YUVA420P:
         min[Y] = min[U] = min[V] = 16;
         max[Y] = 235;
         max[U] = max[V] = 240;
@@ -209,12 +209,12 @@
 
     if (lut->is_rgb) {
         switch (inlink->format) {
-        case PIX_FMT_ARGB:  rgba_map[0] = A; rgba_map[1] = R; rgba_map[2] = G; rgba_map[3] = B; break;
-        case PIX_FMT_ABGR:  rgba_map[0] = A; rgba_map[1] = B; rgba_map[2] = G; rgba_map[3] = R; break;
-        case PIX_FMT_RGBA:
-        case PIX_FMT_RGB24: rgba_map[0] = R; rgba_map[1] = G; rgba_map[2] = B; rgba_map[3] = A; break;
-        case PIX_FMT_BGRA:
-        case PIX_FMT_BGR24: rgba_map[0] = B; rgba_map[1] = G; rgba_map[2] = R; rgba_map[3] = A; break;
+        case AV_PIX_FMT_ARGB:  rgba_map[0] = A; rgba_map[1] = R; rgba_map[2] = G; rgba_map[3] = B; break;
+        case AV_PIX_FMT_ABGR:  rgba_map[0] = A; rgba_map[1] = B; rgba_map[2] = G; rgba_map[3] = R; break;
+        case AV_PIX_FMT_RGBA:
+        case AV_PIX_FMT_RGB24: rgba_map[0] = R; rgba_map[1] = G; rgba_map[2] = B; rgba_map[3] = A; break;
+        case AV_PIX_FMT_BGRA:
+        case AV_PIX_FMT_BGR24: rgba_map[0] = B; rgba_map[1] = G; rgba_map[2] = R; rgba_map[3] = A; break;
         }
         lut->step = av_get_bits_per_pixel(desc) >> 3;
     }
@@ -259,22 +259,28 @@
     return 0;
 }
 
-static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *in)
 {
     AVFilterContext *ctx = inlink->dst;
     LutContext *lut = ctx->priv;
     AVFilterLink *outlink = ctx->outputs[0];
-    AVFilterBufferRef *inpic  = inlink ->cur_buf;
-    AVFilterBufferRef *outpic = outlink->out_buf;
+    AVFilterBufferRef *out;
     uint8_t *inrow, *outrow, *inrow0, *outrow0;
     int i, j, plane;
 
+    out = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+    if (!out) {
+        avfilter_unref_bufferp(&in);
+        return AVERROR(ENOMEM);
+    }
+    avfilter_copy_buffer_ref_props(out, in);
+
     if (lut->is_rgb) {
         /* packed */
-        inrow0  = inpic ->data[0] + y * inpic ->linesize[0];
-        outrow0 = outpic->data[0] + y * outpic->linesize[0];
+        inrow0  = in ->data[0];
+        outrow0 = out->data[0];
 
-        for (i = 0; i < h; i ++) {
+        for (i = 0; i < in->video->h; i ++) {
             int w = inlink->w;
             const uint8_t (*tab)[256] = (const uint8_t (*)[256])lut->lut;
             inrow  = inrow0;
@@ -293,36 +299,37 @@
                 outrow += lut->step;
                 inrow  += lut->step;
             }
-            inrow0  += inpic ->linesize[0];
-            outrow0 += outpic->linesize[0];
+            inrow0  += in ->linesize[0];
+            outrow0 += out->linesize[0];
         }
     } else {
         /* planar */
-        for (plane = 0; plane < 4 && inpic->data[plane]; plane++) {
+        for (plane = 0; plane < 4 && in->data[plane]; plane++) {
             int vsub = plane == 1 || plane == 2 ? lut->vsub : 0;
             int hsub = plane == 1 || plane == 2 ? lut->hsub : 0;
 
-            inrow  = inpic ->data[plane] + (y>>vsub) * inpic ->linesize[plane];
-            outrow = outpic->data[plane] + (y>>vsub) * outpic->linesize[plane];
+            inrow  = in ->data[plane];
+            outrow = out->data[plane];
 
-            for (i = 0; i < (h + (1<<vsub) - 1)>>vsub; i ++) {
+            for (i = 0; i < (in->video->h + (1<<vsub) - 1)>>vsub; i ++) {
                 const uint8_t *tab = lut->lut[plane];
                 int w = (inlink->w + (1<<hsub) - 1)>>hsub;
                 for (j = 0; j < w; j++)
                     outrow[j] = tab[inrow[j]];
-                inrow  += inpic ->linesize[plane];
-                outrow += outpic->linesize[plane];
+                inrow  += in ->linesize[plane];
+                outrow += out->linesize[plane];
             }
         }
     }
 
-    return ff_draw_slice(outlink, y, h, slice_dir);
+    avfilter_unref_bufferp(&in);
+    return ff_filter_frame(outlink, out);
 }
 
 static const AVFilterPad inputs[] = {
     { .name            = "default",
       .type            = AVMEDIA_TYPE_VIDEO,
-      .draw_slice      = draw_slice,
+      .filter_frame    = filter_frame,
       .config_props    = config_props,
       .min_perms       = AV_PERM_READ, },
     { .name = NULL}
diff --git a/libavfilter/vf_mp.c b/libavfilter/vf_mp.c
index d57a6fe5..c70ab28 100644
--- a/libavfilter/vf_mp.c
+++ b/libavfilter/vf_mp.c
@@ -47,79 +47,79 @@
 //XXX: identical pix_fmt must be following with each others
 static const struct {
     int fmt;
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
 } conversion_map[] = {
-    {IMGFMT_ARGB, PIX_FMT_ARGB},
-    {IMGFMT_BGRA, PIX_FMT_BGRA},
-    {IMGFMT_BGR24, PIX_FMT_BGR24},
-    {IMGFMT_BGR16BE, PIX_FMT_RGB565BE},
-    {IMGFMT_BGR16LE, PIX_FMT_RGB565LE},
-    {IMGFMT_BGR15BE, PIX_FMT_RGB555BE},
-    {IMGFMT_BGR15LE, PIX_FMT_RGB555LE},
-    {IMGFMT_BGR12BE, PIX_FMT_RGB444BE},
-    {IMGFMT_BGR12LE, PIX_FMT_RGB444LE},
-    {IMGFMT_BGR8,  PIX_FMT_RGB8},
-    {IMGFMT_BGR4,  PIX_FMT_RGB4},
-    {IMGFMT_BGR1,  PIX_FMT_MONOBLACK},
-    {IMGFMT_RGB1,  PIX_FMT_MONOBLACK},
-    {IMGFMT_RG4B,  PIX_FMT_BGR4_BYTE},
-    {IMGFMT_BG4B,  PIX_FMT_RGB4_BYTE},
-    {IMGFMT_RGB48LE, PIX_FMT_RGB48LE},
-    {IMGFMT_RGB48BE, PIX_FMT_RGB48BE},
-    {IMGFMT_ABGR, PIX_FMT_ABGR},
-    {IMGFMT_RGBA, PIX_FMT_RGBA},
-    {IMGFMT_RGB24, PIX_FMT_RGB24},
-    {IMGFMT_RGB16BE, PIX_FMT_BGR565BE},
-    {IMGFMT_RGB16LE, PIX_FMT_BGR565LE},
-    {IMGFMT_RGB15BE, PIX_FMT_BGR555BE},
-    {IMGFMT_RGB15LE, PIX_FMT_BGR555LE},
-    {IMGFMT_RGB12BE, PIX_FMT_BGR444BE},
-    {IMGFMT_RGB12LE, PIX_FMT_BGR444LE},
-    {IMGFMT_RGB8,  PIX_FMT_BGR8},
-    {IMGFMT_RGB4,  PIX_FMT_BGR4},
-    {IMGFMT_BGR8,  PIX_FMT_PAL8},
-    {IMGFMT_YUY2,  PIX_FMT_YUYV422},
-    {IMGFMT_UYVY,  PIX_FMT_UYVY422},
-    {IMGFMT_NV12,  PIX_FMT_NV12},
-    {IMGFMT_NV21,  PIX_FMT_NV21},
-    {IMGFMT_Y800,  PIX_FMT_GRAY8},
-    {IMGFMT_Y8,    PIX_FMT_GRAY8},
-    {IMGFMT_YVU9,  PIX_FMT_YUV410P},
-    {IMGFMT_IF09,  PIX_FMT_YUV410P},
-    {IMGFMT_YV12,  PIX_FMT_YUV420P},
-    {IMGFMT_I420,  PIX_FMT_YUV420P},
-    {IMGFMT_IYUV,  PIX_FMT_YUV420P},
-    {IMGFMT_411P,  PIX_FMT_YUV411P},
-    {IMGFMT_422P,  PIX_FMT_YUV422P},
-    {IMGFMT_444P,  PIX_FMT_YUV444P},
-    {IMGFMT_440P,  PIX_FMT_YUV440P},
+    {IMGFMT_ARGB, AV_PIX_FMT_ARGB},
+    {IMGFMT_BGRA, AV_PIX_FMT_BGRA},
+    {IMGFMT_BGR24, AV_PIX_FMT_BGR24},
+    {IMGFMT_BGR16BE, AV_PIX_FMT_RGB565BE},
+    {IMGFMT_BGR16LE, AV_PIX_FMT_RGB565LE},
+    {IMGFMT_BGR15BE, AV_PIX_FMT_RGB555BE},
+    {IMGFMT_BGR15LE, AV_PIX_FMT_RGB555LE},
+    {IMGFMT_BGR12BE, AV_PIX_FMT_RGB444BE},
+    {IMGFMT_BGR12LE, AV_PIX_FMT_RGB444LE},
+    {IMGFMT_BGR8,  AV_PIX_FMT_RGB8},
+    {IMGFMT_BGR4,  AV_PIX_FMT_RGB4},
+    {IMGFMT_BGR1,  AV_PIX_FMT_MONOBLACK},
+    {IMGFMT_RGB1,  AV_PIX_FMT_MONOBLACK},
+    {IMGFMT_RG4B,  AV_PIX_FMT_BGR4_BYTE},
+    {IMGFMT_BG4B,  AV_PIX_FMT_RGB4_BYTE},
+    {IMGFMT_RGB48LE, AV_PIX_FMT_RGB48LE},
+    {IMGFMT_RGB48BE, AV_PIX_FMT_RGB48BE},
+    {IMGFMT_ABGR, AV_PIX_FMT_ABGR},
+    {IMGFMT_RGBA, AV_PIX_FMT_RGBA},
+    {IMGFMT_RGB24, AV_PIX_FMT_RGB24},
+    {IMGFMT_RGB16BE, AV_PIX_FMT_BGR565BE},
+    {IMGFMT_RGB16LE, AV_PIX_FMT_BGR565LE},
+    {IMGFMT_RGB15BE, AV_PIX_FMT_BGR555BE},
+    {IMGFMT_RGB15LE, AV_PIX_FMT_BGR555LE},
+    {IMGFMT_RGB12BE, AV_PIX_FMT_BGR444BE},
+    {IMGFMT_RGB12LE, AV_PIX_FMT_BGR444LE},
+    {IMGFMT_RGB8,  AV_PIX_FMT_BGR8},
+    {IMGFMT_RGB4,  AV_PIX_FMT_BGR4},
+    {IMGFMT_BGR8,  AV_PIX_FMT_PAL8},
+    {IMGFMT_YUY2,  AV_PIX_FMT_YUYV422},
+    {IMGFMT_UYVY,  AV_PIX_FMT_UYVY422},
+    {IMGFMT_NV12,  AV_PIX_FMT_NV12},
+    {IMGFMT_NV21,  AV_PIX_FMT_NV21},
+    {IMGFMT_Y800,  AV_PIX_FMT_GRAY8},
+    {IMGFMT_Y8,    AV_PIX_FMT_GRAY8},
+    {IMGFMT_YVU9,  AV_PIX_FMT_YUV410P},
+    {IMGFMT_IF09,  AV_PIX_FMT_YUV410P},
+    {IMGFMT_YV12,  AV_PIX_FMT_YUV420P},
+    {IMGFMT_I420,  AV_PIX_FMT_YUV420P},
+    {IMGFMT_IYUV,  AV_PIX_FMT_YUV420P},
+    {IMGFMT_411P,  AV_PIX_FMT_YUV411P},
+    {IMGFMT_422P,  AV_PIX_FMT_YUV422P},
+    {IMGFMT_444P,  AV_PIX_FMT_YUV444P},
+    {IMGFMT_440P,  AV_PIX_FMT_YUV440P},
 
-    {IMGFMT_420A,  PIX_FMT_YUVA420P},
+    {IMGFMT_420A,  AV_PIX_FMT_YUVA420P},
 
-    {IMGFMT_420P16_LE,  PIX_FMT_YUV420P16LE},
-    {IMGFMT_420P16_BE,  PIX_FMT_YUV420P16BE},
-    {IMGFMT_422P16_LE,  PIX_FMT_YUV422P16LE},
-    {IMGFMT_422P16_BE,  PIX_FMT_YUV422P16BE},
-    {IMGFMT_444P16_LE,  PIX_FMT_YUV444P16LE},
-    {IMGFMT_444P16_BE,  PIX_FMT_YUV444P16BE},
+    {IMGFMT_420P16_LE,  AV_PIX_FMT_YUV420P16LE},
+    {IMGFMT_420P16_BE,  AV_PIX_FMT_YUV420P16BE},
+    {IMGFMT_422P16_LE,  AV_PIX_FMT_YUV422P16LE},
+    {IMGFMT_422P16_BE,  AV_PIX_FMT_YUV422P16BE},
+    {IMGFMT_444P16_LE,  AV_PIX_FMT_YUV444P16LE},
+    {IMGFMT_444P16_BE,  AV_PIX_FMT_YUV444P16BE},
 
     // YUVJ are YUV formats that use the full Y range and not just
     // 16 - 235 (see colorspaces.txt).
     // Currently they are all treated the same way.
-    {IMGFMT_YV12,  PIX_FMT_YUVJ420P},
-    {IMGFMT_422P,  PIX_FMT_YUVJ422P},
-    {IMGFMT_444P,  PIX_FMT_YUVJ444P},
-    {IMGFMT_440P,  PIX_FMT_YUVJ440P},
+    {IMGFMT_YV12,  AV_PIX_FMT_YUVJ420P},
+    {IMGFMT_422P,  AV_PIX_FMT_YUVJ422P},
+    {IMGFMT_444P,  AV_PIX_FMT_YUVJ444P},
+    {IMGFMT_440P,  AV_PIX_FMT_YUVJ440P},
 
-    {IMGFMT_XVMC_MOCO_MPEG2, PIX_FMT_XVMC_MPEG2_MC},
-    {IMGFMT_XVMC_IDCT_MPEG2, PIX_FMT_XVMC_MPEG2_IDCT},
-    {IMGFMT_VDPAU_MPEG1,     PIX_FMT_VDPAU_MPEG1},
-    {IMGFMT_VDPAU_MPEG2,     PIX_FMT_VDPAU_MPEG2},
-    {IMGFMT_VDPAU_H264,      PIX_FMT_VDPAU_H264},
-    {IMGFMT_VDPAU_WMV3,      PIX_FMT_VDPAU_WMV3},
-    {IMGFMT_VDPAU_VC1,       PIX_FMT_VDPAU_VC1},
-    {IMGFMT_VDPAU_MPEG4,     PIX_FMT_VDPAU_MPEG4},
-    {0, PIX_FMT_NONE}
+    {IMGFMT_XVMC_MOCO_MPEG2, AV_PIX_FMT_XVMC_MPEG2_MC},
+    {IMGFMT_XVMC_IDCT_MPEG2, AV_PIX_FMT_XVMC_MPEG2_IDCT},
+    {IMGFMT_VDPAU_MPEG1,     AV_PIX_FMT_VDPAU_MPEG1},
+    {IMGFMT_VDPAU_MPEG2,     AV_PIX_FMT_VDPAU_MPEG2},
+    {IMGFMT_VDPAU_H264,      AV_PIX_FMT_VDPAU_H264},
+    {IMGFMT_VDPAU_WMV3,      AV_PIX_FMT_VDPAU_WMV3},
+    {IMGFMT_VDPAU_VC1,       AV_PIX_FMT_VDPAU_VC1},
+    {IMGFMT_VDPAU_MPEG4,     AV_PIX_FMT_VDPAU_MPEG4},
+    {0, AV_PIX_FMT_NONE}
 };
 
 //copied from vf.c
@@ -137,17 +137,13 @@
 extern const vf_info_t vf_info_eq2;
 extern const vf_info_t vf_info_eq;
 extern const vf_info_t vf_info_expand;
-extern const vf_info_t vf_info_field;
 extern const vf_info_t vf_info_fil;
 extern const vf_info_t vf_info_filmdint;
-extern const vf_info_t vf_info_fixpts;
 extern const vf_info_t vf_info_flip;
 extern const vf_info_t vf_info_format;
 extern const vf_info_t vf_info_fspp;
-extern const vf_info_t vf_info_geq;
 extern const vf_info_t vf_info_halfpack;
 extern const vf_info_t vf_info_harddup;
-extern const vf_info_t vf_info_hqdn3d;
 extern const vf_info_t vf_info_il;
 extern const vf_info_t vf_info_ilpack;
 extern const vf_info_t vf_info_ivtc;
@@ -158,14 +154,12 @@
 extern const vf_info_t vf_info_noformat;
 extern const vf_info_t vf_info_noise;
 extern const vf_info_t vf_info_ow;
-extern const vf_info_t vf_info_palette;
 extern const vf_info_t vf_info_perspective;
 extern const vf_info_t vf_info_phase;
 extern const vf_info_t vf_info_pp7;
 extern const vf_info_t vf_info_pp;
 extern const vf_info_t vf_info_pullup;
 extern const vf_info_t vf_info_qp;
-extern const vf_info_t vf_info_rectangle;
 extern const vf_info_t vf_info_sab;
 extern const vf_info_t vf_info_scale;
 extern const vf_info_t vf_info_softpulldown;
@@ -175,14 +169,11 @@
 extern const vf_info_t vf_info_telecine;
 extern const vf_info_t vf_info_test;
 extern const vf_info_t vf_info_tfields;
-extern const vf_info_t vf_info_tile;
 extern const vf_info_t vf_info_tinterlace;
 extern const vf_info_t vf_info_unsharp;
 extern const vf_info_t vf_info_uspp;
 extern const vf_info_t vf_info_vo;
 extern const vf_info_t vf_info_yadif;
-extern const vf_info_t vf_info_yuvcsp;
-extern const vf_info_t vf_info_yvu9;
 extern const vf_info_t vf_info_zrmjpeg;
 
 
@@ -195,14 +186,10 @@
     &vf_info_dsize,
     &vf_info_eq2,
     &vf_info_eq,
-    &vf_info_field,
     &vf_info_fil,
 //    &vf_info_filmdint, cmmx.h vd.h ‘opt_screen_size_x’
-    &vf_info_fixpts,
     &vf_info_fspp,
-    &vf_info_geq,
     &vf_info_harddup,
-    &vf_info_hqdn3d,
     &vf_info_il,
     &vf_info_ilpack,
     &vf_info_ivtc,
@@ -210,26 +197,21 @@
     &vf_info_mcdeint,
     &vf_info_noise,
     &vf_info_ow,
-    &vf_info_palette,
     &vf_info_perspective,
     &vf_info_phase,
     &vf_info_pp,
     &vf_info_pp7,
     &vf_info_pullup,
     &vf_info_qp,
-    &vf_info_rectangle,
     &vf_info_sab,
     &vf_info_softpulldown,
     &vf_info_softskip,
     &vf_info_spp,
     &vf_info_stereo3d,
     &vf_info_telecine,
-    &vf_info_tile,
     &vf_info_tinterlace,
     &vf_info_unsharp,
     &vf_info_uspp,
-    &vf_info_yuvcsp,
-    &vf_info_yvu9,
 
     NULL
 };
@@ -301,14 +283,14 @@
 {
         int flags, i;
         SwsFilter *dstFilterParam, *srcFilterParam;
-        enum PixelFormat dfmt, sfmt;
+        enum AVPixelFormat dfmt, sfmt;
 
         for(i=0; conversion_map[i].fmt && dstFormat != conversion_map[i].fmt; i++);
         dfmt= conversion_map[i].pix_fmt;
         for(i=0; conversion_map[i].fmt && srcFormat != conversion_map[i].fmt; i++);
         sfmt= conversion_map[i].pix_fmt;
 
-        if (srcFormat == IMGFMT_RGB8 || srcFormat == IMGFMT_BGR8) sfmt = PIX_FMT_PAL8;
+        if (srcFormat == IMGFMT_RGB8 || srcFormat == IMGFMT_BGR8) sfmt = AV_PIX_FMT_PAL8;
         sws_getFlagsAndFilterFromCmdLine(&flags, &srcFilterParam, &dstFilterParam);
 
         return sws_getContext(srcW, srcH, sfmt, dstW, dstH, dfmt, flags , srcFilterParam, dstFilterParam, NULL);
@@ -575,8 +557,8 @@
     }
 
   mpi->qscale = NULL;
-  }
   mpi->usage_count++;
+  }
 //    printf("\rVF_MPI: %p %p %p %d %d %d    \n",
 //      mpi->planes[0],mpi->planes[1],mpi->planes[2],
 //      mpi->stride[0],mpi->stride[1],mpi->stride[2]);
@@ -773,7 +755,7 @@
 {
     AVFilterFormats *avfmts=NULL;
     MPContext *m = ctx->priv;
-    enum PixelFormat lastpixfmt = PIX_FMT_NONE;
+    enum AVPixelFormat lastpixfmt = AV_PIX_FMT_NONE;
     int i;
 
     for(i=0; conversion_map[i].fmt; i++){
@@ -787,6 +769,9 @@
         }
     }
 
+    if (!avfmts)
+        return -1;
+
     //We assume all allowed input formats are also allowed output formats
     ff_set_common_formats(ctx, avfmts);
     return 0;
@@ -878,6 +863,29 @@
     return 0;
 }
 
+static const AVFilterPad mp_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .start_frame  = start_frame,
+        .draw_slice   = null_draw_slice,
+        .end_frame    = end_frame,
+        .config_props = config_inprops,
+        .min_perms    = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad mp_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .request_frame = request_frame,
+        .config_props  = config_outprops,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_mp = {
     .name      = "mp",
     .description = NULL_IF_CONFIG_SMALL("Apply a libmpcodecs filter to the input video."),
@@ -885,18 +893,6 @@
     .uninit = uninit,
     .priv_size = sizeof(MPContext),
     .query_formats = query_formats,
-
-    .inputs    = (const AVFilterPad[]) {{ .name      = "default",
-                                    .type            = AVMEDIA_TYPE_VIDEO,
-                                    .start_frame     = start_frame,
-                                    .draw_slice      = null_draw_slice,
-                                    .end_frame       = end_frame,
-                                    .config_props    = config_inprops,
-                                    .min_perms       = AV_PERM_READ, },
-                                  { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name      = "default",
-                                    .type            = AVMEDIA_TYPE_VIDEO,
-                                    .request_frame   = request_frame,
-                                    .config_props    = config_outprops, },
-                                  { .name = NULL}},
+    .inputs        = mp_inputs,
+    .outputs       = mp_outputs,
 };
diff --git a/libavfilter/vf_null.c b/libavfilter/vf_null.c
index 9ab2767..eafa268 100644
--- a/libavfilter/vf_null.c
+++ b/libavfilter/vf_null.c
@@ -26,20 +26,30 @@
 #include "internal.h"
 #include "video.h"
 
+static const AVFilterPad avfilter_vf_null_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_null_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_null = {
     .name      = "null",
     .description = NULL_IF_CONFIG_SMALL("Pass the source unchanged to the output."),
 
     .priv_size = 0,
 
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .get_video_buffer = ff_null_get_video_buffer,
-                                          .start_frame      = ff_null_start_frame,
-                                          .end_frame        = ff_null_end_frame },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_null_inputs,
 
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO, },
-                                        { .name = NULL}},
+    .outputs   = avfilter_vf_null_outputs,
 };
diff --git a/libavfilter/vf_overlay.c b/libavfilter/vf_overlay.c
index 7e5e6d0..d61d18e 100644
--- a/libavfilter/vf_overlay.c
+++ b/libavfilter/vf_overlay.c
@@ -157,18 +157,18 @@
     OverlayContext *over = ctx->priv;
 
     /* overlay formats contains alpha, for avoiding conversion with alpha information loss */
-    const enum PixelFormat main_pix_fmts_yuv[] = { PIX_FMT_YUV420P,  PIX_FMT_NONE };
-    const enum PixelFormat overlay_pix_fmts_yuv[] = { PIX_FMT_YUVA420P, PIX_FMT_NONE };
-    const enum PixelFormat main_pix_fmts_rgb[] = {
-        PIX_FMT_ARGB,  PIX_FMT_RGBA,
-        PIX_FMT_ABGR,  PIX_FMT_BGRA,
-        PIX_FMT_RGB24, PIX_FMT_BGR24,
-        PIX_FMT_NONE
+    const enum AVPixelFormat main_pix_fmts_yuv[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE };
+    const enum AVPixelFormat overlay_pix_fmts_yuv[] = { AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE };
+    const enum AVPixelFormat main_pix_fmts_rgb[] = {
+        AV_PIX_FMT_ARGB,  AV_PIX_FMT_RGBA,
+        AV_PIX_FMT_ABGR,  AV_PIX_FMT_BGRA,
+        AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
+        AV_PIX_FMT_NONE
     };
-    const enum PixelFormat overlay_pix_fmts_rgb[] = {
-        PIX_FMT_ARGB,  PIX_FMT_RGBA,
-        PIX_FMT_ABGR,  PIX_FMT_BGRA,
-        PIX_FMT_NONE
+    const enum AVPixelFormat overlay_pix_fmts_rgb[] = {
+        AV_PIX_FMT_ARGB,  AV_PIX_FMT_RGBA,
+        AV_PIX_FMT_ABGR,  AV_PIX_FMT_BGRA,
+        AV_PIX_FMT_NONE
     };
 
     AVFilterFormats *main_formats;
@@ -189,15 +189,15 @@
     return 0;
 }
 
-static const enum PixelFormat alpha_pix_fmts[] = {
-    PIX_FMT_YUVA420P, PIX_FMT_ARGB, PIX_FMT_ABGR, PIX_FMT_RGBA,
-    PIX_FMT_BGRA, PIX_FMT_NONE
+static const enum AVPixelFormat alpha_pix_fmts[] = {
+    AV_PIX_FMT_YUVA420P, AV_PIX_FMT_ARGB, AV_PIX_FMT_ABGR, AV_PIX_FMT_RGBA,
+    AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE
 };
 
 static int config_input_main(AVFilterLink *inlink)
 {
     OverlayContext *over = inlink->dst->priv;
-    const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
+    const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
 
     av_image_fill_max_pixsteps(over->main_pix_step,    NULL, pix_desc);
 
@@ -217,7 +217,7 @@
     char *expr;
     double var_values[VAR_VARS_NB], res;
     int ret;
-    const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
+    const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
 
     av_image_fill_max_pixsteps(over->overlay_pix_step, NULL, pix_desc);
 
@@ -249,10 +249,10 @@
     av_log(ctx, AV_LOG_VERBOSE,
            "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,
+           av_get_pix_fmt_name(ctx->inputs[MAIN]->format),
            over->x, over->y,
            ctx->inputs[OVERLAY]->w, ctx->inputs[OVERLAY]->h,
-           av_pix_fmt_descriptors[ctx->inputs[OVERLAY]->format].name);
+           av_get_pix_fmt_name(ctx->inputs[OVERLAY]->format));
 
     if (over->x < 0 || over->y < 0 ||
         over->x + var_values[VAR_OVERLAY_W] > var_values[VAR_MAIN_W] ||
@@ -276,24 +276,10 @@
 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_VERBOSE,
-           "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;
+    outlink->time_base = ctx->inputs[MAIN]->time_base;
 
     return 0;
 }
@@ -307,6 +293,12 @@
 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
 
+// calculate the unpremultiplied alpha, applying the general equation:
+// alpha = alpha_overlay / ( (alpha_main + alpha_overlay) - (alpha_main * alpha_overlay) )
+// (((x) << 16) - ((x) << 9) + (x)) is a faster version of: 255 * 255 * x
+// ((((x) + (y)) << 8) - ((x) + (y)) - (y) * (x)) is a faster version of: 255 * (x + y)
+#define UNPREMULTIPLY_ALPHA(x, y) ((((x) << 16) - ((x) << 9) + (x)) / ((((x) + (y)) << 8) - ((x) + (y)) - (y) * (x)))
+
 static void blend_slice(AVFilterContext *ctx,
                         AVFilterBufferRef *dst, AVFilterBufferRef *src,
                         int x, int y, int w, int h,
@@ -350,15 +342,8 @@
                 // if the main channel has an alpha channel, alpha has to be calculated
                 // to create an un-premultiplied (straight) alpha value
                 if (main_has_alpha && alpha != 0 && alpha != 255) {
-                    // apply the general equation:
-                    // alpha = alpha_overlay / ( (alpha_main + alpha_overlay) - (alpha_main * alpha_overlay) )
-                    alpha =
-                        // the next line is a faster version of: 255 * 255 * alpha
-                        ( (alpha << 16) - (alpha << 9) + alpha )
-                        /
-                        // the next line is a faster version of: 255 * (alpha + d[da])
-                        ( ((alpha + d[da]) << 8 ) - (alpha + d[da])
-                          - d[da] * alpha );
+                    uint8_t alpha_d = d[da];
+                    alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
                 }
 
                 switch (alpha) {
@@ -395,6 +380,39 @@
             sp += src->linesize[0];
         }
     } else {
+        const int main_has_alpha = over->main_has_alpha;
+        if (main_has_alpha) {
+            uint8_t *da = dst->data[3] + x * over->main_pix_step[3] +
+                          start_y * dst->linesize[3];
+            uint8_t *sa = src->data[3];
+            uint8_t alpha;          ///< the amount of overlay to blend on to main
+            if (slice_y > y)
+                sa += (slice_y - y) * src->linesize[3];
+            for (i = 0; i < height; i++) {
+                uint8_t *d = da, *s = sa;
+                for (j = 0; j < width; j++) {
+                    alpha = *s;
+                    if (alpha != 0 && alpha != 255) {
+                        uint8_t alpha_d = *d;
+                        alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
+                    }
+                    switch (alpha) {
+                    case 0:
+                        break;
+                    case 255:
+                        *d = *s;
+                        break;
+                    default:
+                        // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
+                        *d += FAST_DIV255((255 - *d) * *s);
+                    }
+                    d += 1;
+                    s += 1;
+                }
+                da += dst->linesize[3];
+                sa += src->linesize[3];
+            }
+        }
         for (i = 0; i < 3; i++) {
             int hsub = i ? over->hsub : 0;
             int vsub = i ? over->vsub : 0;
@@ -424,6 +442,24 @@
                         alpha = (alpha_v + alpha_h) >> 1;
                     } else
                         alpha = a[0];
+                    // if the main channel has an alpha channel, alpha has to be calculated
+                    // to create an un-premultiplied (straight) alpha value
+                    if (main_has_alpha && alpha != 0 && alpha != 255) {
+                        // average alpha for color components, improve quality
+                        uint8_t alpha_d;
+                        if (hsub && vsub && j+1 < hp && k+1 < wp) {
+                            alpha_d = (d[0] + d[src->linesize[3]] +
+                                       d[1] + d[src->linesize[3]+1]) >> 2;
+                        } else if (hsub || vsub) {
+                            alpha_h = hsub && k+1 < wp ?
+                                (d[0] + d[1]) >> 1 : d[0];
+                            alpha_v = vsub && j+1 < hp ?
+                                (d[0] + d[src->linesize[3]]) >> 1 : d[0];
+                            alpha_d = (alpha_v + alpha_h) >> 1;
+                        } else
+                            alpha_d = d[0];
+                        alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
+                    }
                     *d = FAST_DIV255(*d * (255 - alpha) + *s * alpha);
                     s++;
                     d++;
@@ -448,7 +484,8 @@
      * before the main frame, we can drop the current overlay. */
     while (1) {
         next_overpic = ff_bufqueue_peek(&over->queue_over, 0);
-        if (!next_overpic || next_overpic->pts > mainpic->pts)
+        if (!next_overpic || av_compare_ts(next_overpic->pts, ctx->inputs[OVERLAY]->time_base,
+                                           mainpic->pts     , ctx->inputs[MAIN]->time_base) > 0)
             break;
         ff_bufqueue_get(&over->queue_over);
         avfilter_unref_buffer(over->overpicref);
@@ -457,7 +494,8 @@
     /* If there is no next frame and no EOF and the overlay frame is before
      * the main frame, we can not know yet if it will be superseded. */
     if (!over->queue_over.available && !over->overlay_eof &&
-        (!over->overpicref || over->overpicref->pts < mainpic->pts))
+        (!over->overpicref || av_compare_ts(over->overpicref->pts, ctx->inputs[OVERLAY]->time_base,
+                                            mainpic->pts         , ctx->inputs[MAIN]->time_base) < 0))
         return AVERROR(EAGAIN);
     /* At this point, we know that the current overlay frame extends to the
      * time of the main frame. */
@@ -525,8 +563,6 @@
 
     if ((ret = flush_frames(ctx)) < 0)
         return ret;
-    inpicref->pts = av_rescale_q(inpicref->pts, ctx->inputs[MAIN]->time_base,
-                                 ctx->outputs[0]->time_base);
     if ((ret = try_start_frame(ctx, inpicref)) < 0) {
         if (ret != AVERROR(EAGAIN))
             return ret;
@@ -583,8 +619,6 @@
 
     if ((ret = flush_frames(ctx)) < 0)
         return ret;
-    inpicref->pts = av_rescale_q(inpicref->pts, ctx->inputs[OVERLAY]->time_base,
-                                 ctx->outputs[0]->time_base);
     ff_bufqueue_add(ctx, &over->queue_over, inpicref);
     ret = try_push_frame(ctx);
     return ret == AVERROR(EAGAIN) ? 0 : ret;
@@ -623,6 +657,40 @@
     return 0;
 }
 
+static const AVFilterPad avfilter_vf_overlay_inputs[] = {
+    {
+        .name         = "main",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer= get_video_buffer,
+        .config_props = config_input_main,
+        .start_frame  = start_frame_main,
+        .draw_slice   = draw_slice_main,
+        .end_frame    = end_frame_main,
+        .min_perms    = AV_PERM_READ | AV_PERM_WRITE | AV_PERM_PRESERVE,
+    },
+    {
+        .name         = "overlay",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .config_props = config_input_overlay,
+        .start_frame  = start_frame_over,
+        .draw_slice   = null_draw_slice,
+        .end_frame    = end_frame_over,
+        .min_perms    = AV_PERM_READ | AV_PERM_PRESERVE,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_overlay_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .rej_perms     = AV_PERM_WRITE,
+        .config_props  = config_output,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_overlay = {
     .name      = "overlay",
     .description = NULL_IF_CONFIG_SMALL("Overlay a video source on top of the input."),
@@ -634,27 +702,7 @@
 
     .query_formats = query_formats,
 
-    .inputs    = (const AVFilterPad[]) {{ .name            = "main",
-                                          .type            = AVMEDIA_TYPE_VIDEO,
-                                          .get_video_buffer= get_video_buffer,
-                                          .config_props    = config_input_main,
-                                          .start_frame     = start_frame_main,
-                                          .draw_slice      = draw_slice_main,
-                                          .end_frame       = end_frame_main,
-                                          .min_perms       = AV_PERM_READ | AV_PERM_WRITE | AV_PERM_PRESERVE },
-                                        { .name            = "overlay",
-                                          .type            = AVMEDIA_TYPE_VIDEO,
-                                          .config_props    = config_input_overlay,
-                                          .start_frame     = start_frame_over,
-                                          .draw_slice      = null_draw_slice,
-                                          .end_frame       = end_frame_over,
-                                          .min_perms       = AV_PERM_READ | AV_PERM_PRESERVE },
-                                        { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_VIDEO,
-                                          .rej_perms       = AV_PERM_WRITE,
-                                          .config_props    = config_output,
-                                          .request_frame   = request_frame, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_overlay_inputs,
+    .outputs   = avfilter_vf_overlay_outputs,
     .priv_class = &overlay_class,
 };
diff --git a/libavfilter/vf_pad.c b/libavfilter/vf_pad.c
index 7d2ea92..bbd37b1 100644
--- a/libavfilter/vf_pad.c
+++ b/libavfilter/vf_pad.c
@@ -88,7 +88,6 @@
     uint8_t rgba_color[4];  ///< color for the padding area
     FFDrawContext draw;
     FFDrawColor color;
-    int needs_copy;
 } PadContext;
 
 static av_cold int init(AVFilterContext *ctx, const char *args)
@@ -126,9 +125,9 @@
     var_values[VAR_IN_H]  = var_values[VAR_IH] = inlink->h;
     var_values[VAR_OUT_W] = var_values[VAR_OW] = NAN;
     var_values[VAR_OUT_H] = var_values[VAR_OH] = NAN;
-    var_values[VAR_A]     = (float) inlink->w / inlink->h;
+    var_values[VAR_A]     = (double) inlink->w / inlink->h;
     var_values[VAR_SAR]   = inlink->sample_aspect_ratio.num ?
-        (float) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1;
+        (double) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1;
     var_values[VAR_DAR]   = var_values[VAR_A] * var_values[VAR_SAR];
     var_values[VAR_HSUB]  = 1 << pad->draw.hsub_max;
     var_values[VAR_VSUB]  = 1 << pad->draw.vsub_max;
@@ -263,131 +262,106 @@
     return 0;
 }
 
-static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *in)
 {
     PadContext *pad = inlink->dst->priv;
-    AVFilterBufferRef *outpicref = avfilter_ref_buffer(inpicref, ~0);
-    AVFilterBufferRef *for_next_filter;
-    int plane, ret = 0;
+    AVFilterBufferRef *out = avfilter_ref_buffer(in, ~0);
+    int plane, needs_copy;
 
-    if (!outpicref)
+    if (!out) {
+        avfilter_unref_bufferp(&in);
         return AVERROR(ENOMEM);
+    }
 
-    for (plane = 0; plane < 4 && outpicref->data[plane] && pad->draw.pixelstep[plane]; plane++) {
+    for (plane = 0; plane < 4 && out->data[plane] && pad->draw.pixelstep[plane]; plane++) {
         int hsub = pad->draw.hsub[plane];
         int vsub = pad->draw.vsub[plane];
 
-        av_assert0(outpicref->buf->w>0 && outpicref->buf->h>0);
+        av_assert0(out->buf->w > 0 && out->buf->h > 0);
 
-        if(outpicref->format != outpicref->buf->format) //unsupported currently
+        if (out->format != out->buf->format) //unsupported currently
             break;
 
-        outpicref->data[plane] -=   (pad->x  >> hsub) * pad->draw.pixelstep[plane]
-                                  + (pad->y  >> vsub) * outpicref->linesize[plane];
+        out->data[plane] -= (pad->x  >> hsub) * pad->draw.pixelstep[plane] +
+                            (pad->y  >> vsub) * out->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)
-          )
+        if (does_clip(pad, out, plane, hsub, vsub, 0,                   0) ||
+            does_clip(pad, out, plane, hsub, vsub, 0,          pad->h - 1) ||
+            does_clip(pad, out, plane, hsub, vsub, pad->w - 1,          0) ||
+            does_clip(pad, out, plane, hsub, vsub, pad->w - 1, pad->h - 1))
             break;
     }
-    pad->needs_copy= plane < 4 && outpicref->data[plane] || !(outpicref->perms & AV_PERM_WRITE);
-    if(pad->needs_copy){
+    needs_copy = plane < 4 && out->data[plane] || !(out->perms & AV_PERM_WRITE);
+    if (needs_copy) {
         av_log(inlink->dst, AV_LOG_DEBUG, "Direct padding impossible allocating new frame\n");
-        avfilter_unref_buffer(outpicref);
-        outpicref = ff_get_video_buffer(inlink->dst->outputs[0], AV_PERM_WRITE | AV_PERM_NEG_LINESIZES,
-                                        FFMAX(inlink->w, pad->w),
-                                        FFMAX(inlink->h, pad->h));
-        if (!outpicref)
+        avfilter_unref_buffer(out);
+        out = ff_get_video_buffer(inlink->dst->outputs[0], AV_PERM_WRITE | AV_PERM_NEG_LINESIZES,
+                                  FFMAX(inlink->w, pad->w),
+                                  FFMAX(inlink->h, pad->h));
+        if (!out) {
+            avfilter_unref_bufferp(&in);
             return AVERROR(ENOMEM);
+        }
 
-        avfilter_copy_buffer_ref_props(outpicref, inpicref);
+        avfilter_copy_buffer_ref_props(out, in);
     }
 
-    outpicref->video->w = pad->w;
-    outpicref->video->h = pad->h;
+    out->video->w = pad->w;
+    out->video->h = pad->h;
 
-    for_next_filter = avfilter_ref_buffer(outpicref, ~0);
-    if (!for_next_filter) {
-        ret = AVERROR(ENOMEM);
-        goto fail;
-    }
-
-    ret = ff_start_frame(inlink->dst->outputs[0], for_next_filter);
-    if (ret < 0)
-        goto fail;
-
-    inlink->dst->outputs[0]->out_buf = outpicref;
-    return 0;
-
-fail:
-    avfilter_unref_bufferp(&outpicref);
-    return ret;
-}
-
-static int 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, ret = 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) {
+    /* top bar */
+    if (pad->y) {
         ff_fill_rectangle(&pad->draw, &pad->color,
-                          link->dst->outputs[0]->out_buf->data,
-                          link->dst->outputs[0]->out_buf->linesize,
-                          0, bar_y, pad->w, bar_h);
-        ret = ff_draw_slice(link->dst->outputs[0], bar_y, bar_h, slice_dir);
+                          out->data, out->linesize,
+                          0, 0, pad->w, pad->y);
     }
-    return ret;
-}
 
-static int 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;
-    int ret;
-
-    y += pad->y;
-
-    y = ff_draw_round_to_sub(&pad->draw, 1, -1, y);
-    h = ff_draw_round_to_sub(&pad->draw, 1, -1, h);
-
-    if (!h)
-        return 0;
-    draw_send_bar_slice(link, y, h, slice_dir, 1);
+    /* bottom bar */
+    if (pad->h > pad->y + pad->in_h) {
+        ff_fill_rectangle(&pad->draw, &pad->color,
+                          out->data, out->linesize,
+                          0, pad->y + pad->in_h, pad->w, pad->h - pad->y - pad->in_h);
+    }
 
     /* left border */
-    ff_fill_rectangle(&pad->draw, &pad->color, outpic->data, outpic->linesize,
-                      0, y, pad->x, h);
+    ff_fill_rectangle(&pad->draw, &pad->color, out->data, out->linesize,
+                      0, pad->y, pad->x, in->video->h);
 
-    if(pad->needs_copy){
+    if (needs_copy) {
         ff_copy_rectangle2(&pad->draw,
-                           outpic->data, outpic->linesize,
-                           inpic ->data, inpic ->linesize,
-                           pad->x, y, 0, y - pad->y, inpic->video->w, h);
+                          out->data, out->linesize, in->data, in->linesize,
+                          pad->x, pad->y, 0, 0, in->video->w, in->video->h);
     }
 
     /* right border */
-    ff_fill_rectangle(&pad->draw, &pad->color, outpic->data, outpic->linesize,
-                      pad->x + pad->in_w, y, pad->w - pad->x - pad->in_w, h);
-    ret = ff_draw_slice(link->dst->outputs[0], y, h, slice_dir);
-    if (ret < 0)
-        return ret;
+    ff_fill_rectangle(&pad->draw, &pad->color, out->data, out->linesize,
+                      pad->x + pad->in_w, pad->y, pad->w - pad->x - pad->in_w,
+                      in->video->h);
 
-    return draw_send_bar_slice(link, y, h, slice_dir, -1);
+    avfilter_unref_bufferp(&in);
+    return ff_filter_frame(inlink->dst->outputs[0], out);
 }
 
+static const AVFilterPad avfilter_vf_pad_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .config_props     = config_input,
+        .get_video_buffer = get_video_buffer,
+        .filter_frame     = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_pad_outputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .config_props = config_output,
+    },
+    { NULL }
+};
+
 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)."),
@@ -396,16 +370,7 @@
     .init          = init,
     .query_formats = query_formats,
 
-    .inputs    = (const 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, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_pad_inputs,
 
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .config_props     = config_output, },
-                                        { .name = NULL}},
+    .outputs   = avfilter_vf_pad_outputs,
 };
diff --git a/libavfilter/vf_pixdesctest.c b/libavfilter/vf_pixdesctest.c
index f8c5432..6ac03d9 100644
--- a/libavfilter/vf_pixdesctest.c
+++ b/libavfilter/vf_pixdesctest.c
@@ -44,7 +44,7 @@
 {
     PixdescTestContext *priv = inlink->dst->priv;
 
-    priv->pix_desc = &av_pix_fmt_descriptors[inlink->format];
+    priv->pix_desc = av_pix_fmt_desc_get(inlink->format);
 
     if (!(priv->line = av_malloc(sizeof(*priv->line) * inlink->w)))
         return AVERROR(ENOMEM);
@@ -52,80 +52,79 @@
     return 0;
 }
 
-static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *in)
 {
     PixdescTestContext *priv = inlink->dst->priv;
     AVFilterLink *outlink    = inlink->dst->outputs[0];
-    AVFilterBufferRef *outpicref, *for_next_filter;
-    int i, ret = 0;
+    AVFilterBufferRef *out;
+    int i, c, w = inlink->w, h = inlink->h;
 
-    outpicref = ff_get_video_buffer(outlink, AV_PERM_WRITE,
-                                    outlink->w, outlink->h);
-    if (!outpicref)
+    out = ff_get_video_buffer(outlink, AV_PERM_WRITE,
+                              outlink->w, outlink->h);
+    if (!out) {
+        avfilter_unref_bufferp(&in);
         return AVERROR(ENOMEM);
+    }
 
-    avfilter_copy_buffer_ref_props(outpicref, picref);
+    avfilter_copy_buffer_ref_props(out, in);
 
     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);
+        if (out->data[i]) {
+            uint8_t *data = out->data[i] +
+                (out->linesize[i] > 0 ? 0 : out->linesize[i] * (h-1));
+            memset(data, 0, FFABS(out->linesize[i]) * h);
         }
     }
 
     /* copy palette */
     if (priv->pix_desc->flags & PIX_FMT_PAL ||
         priv->pix_desc->flags & PIX_FMT_PSEUDOPAL)
-        memcpy(outpicref->data[1], picref->data[1], AVPALETTE_SIZE);
-
-    for_next_filter = avfilter_ref_buffer(outpicref, ~0);
-    if (for_next_filter)
-        ret = ff_start_frame(outlink, for_next_filter);
-    else
-        ret = AVERROR(ENOMEM);
-
-    if (ret < 0) {
-        avfilter_unref_bufferp(&outpicref);
-        return ret;
-    }
-
-    outlink->out_buf = outpicref;
-    return 0;
-}
-
-static int 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;
+        memcpy(out->data[1], in->data[1], AVPALETTE_SIZE);
 
     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++) {
+        for (i = 0; i < h1; i++) {
             av_read_image_line(priv->line,
-                               (void*)inpic->data,
-                               inpic->linesize,
+                               (void*)in->data,
+                               in->linesize,
                                priv->pix_desc,
                                0, i, c, w1, 0);
 
             av_write_image_line(priv->line,
-                                outpic->data,
-                                outpic->linesize,
+                                out->data,
+                                out->linesize,
                                 priv->pix_desc,
                                 0, i, c, w1);
         }
     }
 
-    return ff_draw_slice(inlink->dst->outputs[0], y, h, slice_dir);
+    avfilter_unref_bufferp(&in);
+    return ff_filter_frame(outlink, out);
 }
 
+static const AVFilterPad avfilter_vf_pixdesctest_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .filter_frame = filter_frame,
+        .config_props = config_props,
+        .min_perms    = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_pixdesctest_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_pixdesctest = {
     .name        = "pixdesctest",
     .description = NULL_IF_CONFIG_SMALL("Test pixel format definitions."),
@@ -133,15 +132,7 @@
     .priv_size = sizeof(PixdescTestContext),
     .uninit    = uninit,
 
-    .inputs    = (const 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}},
+    .inputs    = avfilter_vf_pixdesctest_inputs,
 
-    .outputs   = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_VIDEO, },
-                                        { .name = NULL}},
+    .outputs   = avfilter_vf_pixdesctest_outputs,
 };
diff --git a/libavfilter/vf_removelogo.c b/libavfilter/vf_removelogo.c
index 7154a54..f2228be 100644
--- a/libavfilter/vf_removelogo.c
+++ b/libavfilter/vf_removelogo.c
@@ -191,7 +191,7 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    enum PixelFormat pix_fmts[] = { PIX_FMT_YUV420P, PIX_FMT_NONE };
+    enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE };
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
     return 0;
 }
@@ -200,7 +200,7 @@
                      const char *filename, void *log_ctx)
 {
     int ret;
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
     uint8_t *src_data[4], *gray_data[4];
     int src_linesize[4], gray_linesize[4];
 
@@ -209,7 +209,7 @@
         return ret;
 
     /* convert the image to GRAY8 */
-    if ((ret = ff_scale_image(gray_data, gray_linesize, *w, *h, PIX_FMT_GRAY8,
+    if ((ret = ff_scale_image(gray_data, gray_linesize, *w, *h, AV_PIX_FMT_GRAY8,
                               src_data, src_linesize, *w, *h, pix_fmt,
                               log_ctx)) < 0)
         goto end;
@@ -535,6 +535,28 @@
 
 static int null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { return 0; }
 
+static const AVFilterPad removelogo_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .config_props     = config_props_input,
+        .draw_slice       = null_draw_slice,
+        .start_frame      = start_frame,
+        .end_frame        = end_frame,
+        .min_perms        = AV_PERM_WRITE | AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad removelogo_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_removelogo = {
     .name          = "removelogo",
     .description   = NULL_IF_CONFIG_SMALL("Remove a TV logo based on a mask image."),
@@ -542,21 +564,6 @@
     .init          = init,
     .uninit        = uninit,
     .query_formats = query_formats,
-
-    .inputs = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_VIDEO,
-          .get_video_buffer = ff_null_get_video_buffer,
-          .config_props     = config_props_input,
-          .draw_slice       = null_draw_slice,
-          .start_frame      = start_frame,
-          .end_frame        = end_frame,
-          .min_perms        = AV_PERM_WRITE | AV_PERM_READ },
-        { .name = NULL }
-    },
-    .outputs = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_VIDEO, },
-        { .name = NULL }
-    },
+    .inputs        = removelogo_inputs,
+    .outputs       = removelogo_outputs,
 };
diff --git a/libavfilter/vf_scale.c b/libavfilter/vf_scale.c
index 49988bf..71f9782 100644
--- a/libavfilter/vf_scale.c
+++ b/libavfilter/vf_scale.c
@@ -35,6 +35,7 @@
 #include "libavutil/internal.h"
 #include "libavutil/mathematics.h"
 #include "libavutil/opt.h"
+#include "libavutil/parseutils.h"
 #include "libavutil/pixdesc.h"
 #include "libavutil/imgutils.h"
 #include "libavutil/avassert.h"
@@ -67,6 +68,7 @@
 };
 
 typedef struct {
+    const AVClass *class;
     struct SwsContext *sws;     ///< software scaler context
     struct SwsContext *isws[2]; ///< software scaler context for interlaced material
 
@@ -76,6 +78,8 @@
      *  -1 = keep original aspect
      */
     int w, h;
+    char *flags_str;            ///sws flags string
+    char *size_str;
     unsigned int flags;         ///sws flags
 
     int hsub, vsub;             ///< chroma subsampling
@@ -84,35 +88,82 @@
     int output_is_pal;          ///< set to 1 if the output format is paletted
     int interlaced;
 
-    char w_expr[256];           ///< width  expression string
-    char h_expr[256];           ///< height expression string
+    char *w_expr;               ///< width  expression string
+    char *h_expr;               ///< height expression string
 } ScaleContext;
 
+#define OFFSET(x) offsetof(ScaleContext, x)
+#define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
+
+static const AVOption scale_options[] = {
+    { "w",      "set width expression",    OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
+    { "width",  "set width expression",    OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
+    { "h",      "set height expression",   OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
+    { "height", "set height expression",   OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
+    { "flags",  "set libswscale flags",    OFFSET(flags_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, INT_MAX, FLAGS },
+    { "interl", "set interlacing", OFFSET(interlaced), AV_OPT_TYPE_INT, {.i64 = 0 }, -1, 1, FLAGS },
+    { "size",   "set video size",          OFFSET(size_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, FLAGS },
+    { "s",      "set video size",          OFFSET(size_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, FLAGS },
+    { NULL },
+};
+
+AVFILTER_DEFINE_CLASS(scale);
+
 static av_cold int init(AVFilterContext *ctx, const char *args)
 {
     ScaleContext *scale = ctx->priv;
-    const char *p;
+    static const char *shorthand[] = { "w", "h", NULL };
+    int ret;
+    const char *args0 = args;
 
-    av_strlcpy(scale->w_expr, "iw", sizeof(scale->w_expr));
-    av_strlcpy(scale->h_expr, "ih", sizeof(scale->h_expr));
+    scale->class = &scale_class;
+    av_opt_set_defaults(scale);
+
+    if (args && (scale->size_str = av_get_token(&args, ":"))) {
+        if (av_parse_video_size(&scale->w, &scale->h, scale->size_str) < 0) {
+            av_freep(&scale->size_str);
+            args = args0;
+        } else if (*args)
+            args++;
+    }
+
+    if ((ret = av_opt_set_from_string(scale, args, shorthand, "=", ":")) < 0)
+        return ret;
+
+    if (scale->size_str && (scale->w_expr || scale->h_expr)) {
+        av_log(ctx, AV_LOG_ERROR,
+               "Size and width/height expressions cannot be set at the same time.\n");
+            return AVERROR(EINVAL);
+    }
+
+    if (scale->size_str) {
+        char buf[32];
+        if ((ret = av_parse_video_size(&scale->w, &scale->h, scale->size_str)) < 0) {
+            av_log(ctx, AV_LOG_ERROR,
+                   "Invalid size '%s'\n", scale->size_str);
+            return ret;
+        }
+        snprintf(buf, sizeof(buf)-1, "%d", scale->w);
+        av_opt_set(scale, "w", buf, 0);
+        snprintf(buf, sizeof(buf)-1, "%d", scale->h);
+        av_opt_set(scale, "h", buf, 0);
+    }
+    if (!scale->w_expr)
+        av_opt_set(scale, "w", "iw", 0);
+    if (!scale->h_expr)
+        av_opt_set(scale, "h", "ih", 0);
+
+    av_log(ctx, AV_LOG_VERBOSE, "w:%s h:%s flags:'%s' interl:%d\n",
+           scale->w_expr, scale->h_expr, (char *)av_x_if_null(scale->flags_str, ""), scale->interlaced);
 
     scale->flags = SWS_BILINEAR;
-    if (args) {
-        sscanf(args, "%255[^:]:%255[^:]", scale->w_expr, scale->h_expr);
-        p = strstr(args,"flags=");
-        if (p) {
-            const AVClass *class = sws_get_class();
-            const AVOption    *o = av_opt_find(&class, "sws_flags", NULL, 0,
-                                               AV_OPT_SEARCH_FAKE_OBJ);
-            int ret = av_opt_eval_flags(&class, o, p + 6, &scale->flags);
-
-            if (ret < 0)
-                return ret;
-        }
-        if(strstr(args,"interl=1")){
-            scale->interlaced=1;
-        }else if(strstr(args,"interl=-1"))
-            scale->interlaced=-1;
+    if (scale->flags_str) {
+        const AVClass *class = sws_get_class();
+        const AVOption    *o = av_opt_find(&class, "sws_flags", NULL, 0,
+                                           AV_OPT_SEARCH_FAKE_OBJ);
+        int ret = av_opt_eval_flags(&class, o, scale->flags_str, &scale->flags);
+        if (ret < 0)
+            return ret;
     }
 
     return 0;
@@ -125,17 +176,18 @@
     sws_freeContext(scale->isws[0]);
     sws_freeContext(scale->isws[1]);
     scale->sws = NULL;
+    av_opt_free(scale);
 }
 
 static int query_formats(AVFilterContext *ctx)
 {
     AVFilterFormats *formats;
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
     int ret;
 
     if (ctx->inputs[0]) {
         formats = NULL;
-        for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++)
+        for (pix_fmt = 0; pix_fmt < AV_PIX_FMT_NB; pix_fmt++)
             if (   sws_isSupportedInput(pix_fmt)
                 && (ret = ff_add_format(&formats, pix_fmt)) < 0) {
                 ff_formats_unref(&formats);
@@ -145,8 +197,8 @@
     }
     if (ctx->outputs[0]) {
         formats = NULL;
-        for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++)
-            if (   (sws_isSupportedOutput(pix_fmt) || pix_fmt == PIX_FMT_PAL8)
+        for (pix_fmt = 0; pix_fmt < AV_PIX_FMT_NB; pix_fmt++)
+            if (   (sws_isSupportedOutput(pix_fmt) || pix_fmt == AV_PIX_FMT_PAL8)
                 && (ret = ff_add_format(&formats, pix_fmt)) < 0) {
                 ff_formats_unref(&formats);
                 return ret;
@@ -161,8 +213,9 @@
 {
     AVFilterContext *ctx = outlink->src;
     AVFilterLink *inlink = outlink->src->inputs[0];
-    enum PixelFormat outfmt = outlink->format;
+    enum AVPixelFormat outfmt = outlink->format;
     ScaleContext *scale = ctx->priv;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
     int64_t w, h;
     double var_values[VARS_NB], res;
     char *expr;
@@ -172,12 +225,12 @@
     var_values[VAR_IN_H]  = var_values[VAR_IH] = inlink->h;
     var_values[VAR_OUT_W] = var_values[VAR_OW] = NAN;
     var_values[VAR_OUT_H] = var_values[VAR_OH] = NAN;
-    var_values[VAR_A]     = (float) inlink->w / inlink->h;
+    var_values[VAR_A]     = (double) inlink->w / inlink->h;
     var_values[VAR_SAR]   = inlink->sample_aspect_ratio.num ?
-        (float) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1;
+        (double) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1;
     var_values[VAR_DAR]   = var_values[VAR_A] * var_values[VAR_SAR];
-    var_values[VAR_HSUB]  = 1<<av_pix_fmt_descriptors[inlink->format].log2_chroma_w;
-    var_values[VAR_VSUB]  = 1<<av_pix_fmt_descriptors[inlink->format].log2_chroma_h;
+    var_values[VAR_HSUB]  = 1 << desc->log2_chroma_w;
+    var_values[VAR_VSUB]  = 1 << desc->log2_chroma_h;
 
     /* evaluate width and height */
     av_expr_parse_and_eval(&res, (expr = scale->w_expr),
@@ -226,11 +279,11 @@
 
     /* TODO: make algorithm configurable */
 
-    scale->input_is_pal = av_pix_fmt_descriptors[inlink->format].flags & PIX_FMT_PAL ||
-                          av_pix_fmt_descriptors[inlink->format].flags & PIX_FMT_PSEUDOPAL;
-    if (outfmt == PIX_FMT_PAL8) outfmt = PIX_FMT_BGR8;
-    scale->output_is_pal = av_pix_fmt_descriptors[outfmt].flags & PIX_FMT_PAL ||
-                           av_pix_fmt_descriptors[outfmt].flags & PIX_FMT_PSEUDOPAL;
+    scale->input_is_pal = desc->flags & PIX_FMT_PAL ||
+                          desc->flags & PIX_FMT_PSEUDOPAL;
+    if (outfmt == AV_PIX_FMT_PAL8) outfmt = AV_PIX_FMT_BGR8;
+    scale->output_is_pal = av_pix_fmt_desc_get(outfmt)->flags & PIX_FMT_PAL ||
+                           av_pix_fmt_desc_get(outfmt)->flags & PIX_FMT_PSEUDOPAL;
 
     if (scale->sws)
         sws_freeContext(scale->sws);
@@ -261,9 +314,9 @@
         outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
 
     av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d fmt:%s sar:%d/%d -> w:%d h:%d fmt:%s sar:%d/%d flags:0x%0x\n",
-           inlink ->w, inlink ->h, av_pix_fmt_descriptors[ inlink->format].name,
+           inlink ->w, inlink ->h, av_get_pix_fmt_name( inlink->format),
            inlink->sample_aspect_ratio.num, inlink->sample_aspect_ratio.den,
-           outlink->w, outlink->h, av_pix_fmt_descriptors[outlink->format].name,
+           outlink->w, outlink->h, av_get_pix_fmt_name(outlink->format),
            outlink->sample_aspect_ratio.num, outlink->sample_aspect_ratio.den,
            scale->flags);
     return 0;
@@ -276,76 +329,9 @@
     return ret;
 }
 
-static int start_frame(AVFilterLink *link, AVFilterBufferRef *picref)
+static int scale_slice(AVFilterLink *link, AVFilterBufferRef *out_buf, AVFilterBufferRef *cur_pic, struct SwsContext *sws, int y, int h, int mul, int field)
 {
     ScaleContext *scale = link->dst->priv;
-    AVFilterLink *outlink = link->dst->outputs[0];
-    AVFilterBufferRef *outpicref, *for_next_filter;
-    int ret = 0;
-
-    if(   picref->video->w != link->w
-       || picref->video->h != link->h
-       || picref->format   != link->format) {
-        int ret;
-        snprintf(scale->w_expr, sizeof(scale->w_expr)-1, "%d", outlink->w);
-        snprintf(scale->h_expr, sizeof(scale->h_expr)-1, "%d", outlink->h);
-
-        link->dst->inputs[0]->format = picref->format;
-        link->dst->inputs[0]->w      = picref->video->w;
-        link->dst->inputs[0]->h      = picref->video->h;
-
-        if ((ret = config_props(outlink)) < 0)
-            av_assert0(0); //what to do here ?
-    }
-
-
-    if (!scale->sws) {
-        outpicref = avfilter_ref_buffer(picref, ~0);
-        if (!outpicref)
-            return AVERROR(ENOMEM);
-        return ff_start_frame(outlink, outpicref);
-    }
-
-    scale->hsub = av_pix_fmt_descriptors[link->format].log2_chroma_w;
-    scale->vsub = av_pix_fmt_descriptors[link->format].log2_chroma_h;
-
-    outpicref = ff_get_video_buffer(outlink, AV_PERM_WRITE|AV_PERM_ALIGN, outlink->w, outlink->h);
-    if (!outpicref)
-        return AVERROR(ENOMEM);
-
-    avfilter_copy_buffer_ref_props(outpicref, picref);
-    outpicref->video->w = outlink->w;
-    outpicref->video->h = outlink->h;
-
-    if(scale->output_is_pal)
-        ff_set_systematic_pal2((uint32_t*)outpicref->data[1], outlink->format == PIX_FMT_PAL8 ? PIX_FMT_BGR8 : outlink->format);
-
-    av_reduce(&outpicref->video->sample_aspect_ratio.num, &outpicref->video->sample_aspect_ratio.den,
-              (int64_t)picref->video->sample_aspect_ratio.num * outlink->h * link->w,
-              (int64_t)picref->video->sample_aspect_ratio.den * outlink->w * link->h,
-              INT_MAX);
-
-    scale->slice_y = 0;
-    for_next_filter = avfilter_ref_buffer(outpicref, ~0);
-    if (for_next_filter)
-        ret = ff_start_frame(outlink, for_next_filter);
-    else
-        ret = AVERROR(ENOMEM);
-
-    if (ret < 0) {
-        avfilter_unref_bufferp(&outpicref);
-        return ret;
-    }
-
-    outlink->out_buf = outpicref;
-    return 0;
-}
-
-static int scale_slice(AVFilterLink *link, struct SwsContext *sws, int y, int h, int mul, int field)
-{
-    ScaleContext *scale = link->dst->priv;
-    AVFilterBufferRef *cur_pic = link->cur_buf;
-    AVFilterBufferRef *out_buf = link->dst->outputs[0]->out_buf;
     const uint8_t *in[4];
     uint8_t *out[4];
     int in_stride[4],out_stride[4];
@@ -367,34 +353,85 @@
                          out,out_stride);
 }
 
-static int draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
+static int filter_frame(AVFilterLink *link, AVFilterBufferRef *in)
 {
     ScaleContext *scale = link->dst->priv;
-    int out_h, ret;
+    AVFilterLink *outlink = link->dst->outputs[0];
+    AVFilterBufferRef *out;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
+    char buf[32];
 
-    if (!scale->sws) {
-        return ff_draw_slice(link->dst->outputs[0], y, h, slice_dir);
+    if(   in->video->w != link->w
+       || in->video->h != link->h
+       || in->format   != link->format) {
+        int ret;
+        snprintf(buf, sizeof(buf)-1, "%d", outlink->w);
+        av_opt_set(scale, "w", buf, 0);
+        snprintf(buf, sizeof(buf)-1, "%d", outlink->h);
+        av_opt_set(scale, "h", buf, 0);
+
+        link->dst->inputs[0]->format = in->format;
+        link->dst->inputs[0]->w      = in->video->w;
+        link->dst->inputs[0]->h      = in->video->h;
+
+        if ((ret = config_props(outlink)) < 0)
+            return ret;
     }
 
-    if (scale->slice_y == 0 && slice_dir == -1)
-        scale->slice_y = link->dst->outputs[0]->h;
+    if (!scale->sws)
+        return ff_filter_frame(outlink, in);
+
+    scale->hsub = desc->log2_chroma_w;
+    scale->vsub = desc->log2_chroma_h;
+
+    out = ff_get_video_buffer(outlink, AV_PERM_WRITE|AV_PERM_ALIGN, outlink->w, outlink->h);
+    if (!out) {
+        avfilter_unref_bufferp(&in);
+        return AVERROR(ENOMEM);
+    }
+
+    avfilter_copy_buffer_ref_props(out, in);
+    out->video->w = outlink->w;
+    out->video->h = outlink->h;
+
+    if(scale->output_is_pal)
+        avpriv_set_systematic_pal2((uint32_t*)out->data[1], outlink->format == AV_PIX_FMT_PAL8 ? AV_PIX_FMT_BGR8 : outlink->format);
+
+    av_reduce(&out->video->sample_aspect_ratio.num, &out->video->sample_aspect_ratio.den,
+              (int64_t)in->video->sample_aspect_ratio.num * outlink->h * link->w,
+              (int64_t)in->video->sample_aspect_ratio.den * outlink->w * link->h,
+              INT_MAX);
 
     if(scale->interlaced>0 || (scale->interlaced<0 && link->cur_buf->video->interlaced)){
-        av_assert0(y%(2<<scale->vsub) == 0);
-        out_h = scale_slice(link, scale->isws[0], y, (h+1)/2, 2, 0);
-        out_h+= scale_slice(link, scale->isws[1], y,  h   /2, 2, 1);
+        scale_slice(link, out, in, scale->isws[0], 0, (link->h+1)/2, 2, 0);
+        scale_slice(link, out, in, scale->isws[1], 0,  link->h   /2, 2, 1);
     }else{
-        out_h = scale_slice(link, scale->sws, y, h, 1, 0);
+        scale_slice(link, out, in, scale->sws, 0, link->h, 1, 0);
     }
 
-    if (slice_dir == -1)
-        scale->slice_y -= out_h;
-    ret = ff_draw_slice(link->dst->outputs[0], scale->slice_y, out_h, slice_dir);
-    if (slice_dir == 1)
-        scale->slice_y += out_h;
-    return ret;
+    avfilter_unref_bufferp(&in);
+    return ff_filter_frame(outlink, out);
 }
 
+static const AVFilterPad avfilter_vf_scale_inputs[] = {
+    {
+        .name        = "default",
+        .type        = AVMEDIA_TYPE_VIDEO,
+        .filter_frame = filter_frame,
+        .min_perms   = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_scale_outputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .config_props = config_props,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_scale = {
     .name      = "scale",
     .description = NULL_IF_CONFIG_SMALL("Scale the input video to width:height size and/or convert the image format."),
@@ -406,14 +443,7 @@
 
     .priv_size = sizeof(ScaleContext),
 
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .start_frame      = start_frame,
-                                          .draw_slice       = draw_slice,
-                                          .min_perms        = AV_PERM_READ, },
-                                        { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .config_props     = config_props, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_scale_inputs,
+    .outputs   = avfilter_vf_scale_outputs,
+    .priv_class = &scale_class,
 };
diff --git a/libavfilter/vf_select.c b/libavfilter/vf_select.c
index 52b03b1..e0e1863 100644
--- a/libavfilter/vf_select.c
+++ b/libavfilter/vf_select.c
@@ -204,21 +204,24 @@
         picref->video->h    == prev_picref->video->h &&
         picref->video->w    == prev_picref->video->w &&
         picref->linesize[0] == prev_picref->linesize[0]) {
-        int x, y;
-        int64_t sad;
+        int x, y, nb_sad = 0;
+        int64_t sad = 0;
         double mafd, diff;
         uint8_t *p1 =      picref->data[0];
         uint8_t *p2 = prev_picref->data[0];
         const int linesize = picref->linesize[0];
 
-        for (sad = y = 0; y < picref->video->h; y += 8)
-            for (x = 0; x < linesize; x += 8)
-                sad += select->c.sad[1](select,
-                                        p1 + y * linesize + x,
-                                        p2 + y * linesize + x,
+        for (y = 0; y < picref->video->h - 8; y += 8) {
+            for (x = 0; x < picref->video->w*3 - 8; x += 8) {
+                sad += select->c.sad[1](select, p1 + x, p2 + x,
                                         linesize, 8);
+                nb_sad += 8 * 8;
+            }
+            p1 += 8 * linesize;
+            p2 += 8 * linesize;
+        }
         emms_c();
-        mafd = sad / (picref->video->h * picref->video->w * 3);
+        mafd = nb_sad ? sad / nb_sad : 0;
         diff = fabs(mafd - select->prev_mafd);
         ret  = av_clipf(FFMIN(mafd, diff) / 100., 0, 1);
         select->prev_mafd = mafd;
@@ -238,8 +241,13 @@
     AVFilterLink *inlink = ctx->inputs[0];
     double res;
 
-    if (CONFIG_AVCODEC && select->do_scene_detect)
+    if (CONFIG_AVCODEC && select->do_scene_detect) {
+        char buf[32];
         select->var_values[VAR_SCENE] = get_scene_score(ctx, picref);
+        // TODO: document metadata
+        snprintf(buf, sizeof(buf), "%f", select->var_values[VAR_SCENE]);
+        av_dict_set(&picref->metadata, "lavfi.scene_score", buf, 0);
+    }
     if (isnan(select->var_values[VAR_START_PTS]))
         select->var_values[VAR_START_PTS] = TS2D(picref->pts);
     if (isnan(select->var_values[VAR_START_T]))
@@ -281,50 +289,27 @@
     return res;
 }
 
-static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *frame)
 {
     SelectContext *select = inlink->dst->priv;
 
-    select->select = select_frame(inlink->dst, picref);
+    select->select = select_frame(inlink->dst, frame);
     if (select->select) {
-        AVFilterBufferRef *buf_out;
         /* frame was requested through poll_frame */
         if (select->cache_frames) {
-            if (!av_fifo_space(select->pending_frames))
+            if (!av_fifo_space(select->pending_frames)) {
                 av_log(inlink->dst, AV_LOG_ERROR,
                        "Buffering limit reached, cannot cache more frames\n");
-            else
-                av_fifo_generic_write(select->pending_frames, &picref,
-                                      sizeof(picref), NULL);
+                avfilter_unref_bufferp(&frame);
+            } else
+                av_fifo_generic_write(select->pending_frames, &frame,
+                                      sizeof(frame), NULL);
             return 0;
         }
-        buf_out = avfilter_ref_buffer(picref, ~0);
-        if (!buf_out)
-            return AVERROR(ENOMEM);
-        return ff_start_frame(inlink->dst->outputs[0], buf_out);
+        return ff_filter_frame(inlink->dst->outputs[0], frame);
     }
 
-    return 0;
-}
-
-static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
-{
-    SelectContext *select = inlink->dst->priv;
-
-    if (select->select && !select->cache_frames)
-        return ff_draw_slice(inlink->dst->outputs[0], y, h, slice_dir);
-    return 0;
-}
-
-static int end_frame(AVFilterLink *inlink)
-{
-    SelectContext *select = inlink->dst->priv;
-
-    if (select->select) {
-        if (select->cache_frames)
-            return 0;
-        return ff_end_frame(inlink->dst->outputs[0]);
-    }
+    avfilter_unref_bufferp(&frame);
     return 0;
 }
 
@@ -337,14 +322,9 @@
 
     if (av_fifo_size(select->pending_frames)) {
         AVFilterBufferRef *picref;
-        int ret;
 
         av_fifo_generic_read(select->pending_frames, &picref, sizeof(picref), NULL);
-        if ((ret = ff_start_frame(outlink, picref)) < 0 ||
-            (ret = ff_draw_slice(outlink, 0, outlink->h, 1)) < 0 ||
-            (ret = ff_end_frame(outlink)) < 0);
-
-        return ret;
+        return ff_filter_frame(outlink, picref);
     }
 
     while (!select->select) {
@@ -408,15 +388,37 @@
     if (!select->do_scene_detect) {
         return ff_default_query_formats(ctx);
     } else {
-        static const enum PixelFormat pix_fmts[] = {
-            PIX_FMT_RGB24, PIX_FMT_BGR24,
-            PIX_FMT_NONE
+        static const enum AVPixelFormat pix_fmts[] = {
+            AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
+            AV_PIX_FMT_NONE
         };
         ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
     }
     return 0;
 }
 
+static const AVFilterPad avfilter_vf_select_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .min_perms        = AV_PERM_PRESERVE,
+        .config_props     = config_input,
+        .filter_frame     = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_select_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .poll_frame    = poll_frame,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_select = {
     .name      = "select",
     .description = NULL_IF_CONFIG_SMALL("Select frames to pass in output."),
@@ -426,18 +428,6 @@
 
     .priv_size = sizeof(SelectContext),
 
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .get_video_buffer = ff_null_get_video_buffer,
-                                          .min_perms        = AV_PERM_PRESERVE,
-                                          .config_props     = config_input,
-                                          .start_frame      = start_frame,
-                                          .draw_slice       = draw_slice,
-                                          .end_frame        = end_frame },
-                                        { .name = NULL }},
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .poll_frame       = poll_frame,
-                                          .request_frame    = request_frame, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_select_inputs,
+    .outputs   = avfilter_vf_select_outputs,
 };
diff --git a/libavfilter/vf_setfield.c b/libavfilter/vf_setfield.c
index 93d30c7..c62ee36 100644
--- a/libavfilter/vf_setfield.c
+++ b/libavfilter/vf_setfield.c
@@ -83,23 +83,30 @@
     return ff_start_frame(inlink->dst->outputs[0], outpicref);
 }
 
+static const AVFilterPad setfield_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .start_frame      = start_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad setfield_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_setfield = {
     .name      = "setfield",
     .description = NULL_IF_CONFIG_SMALL("Force field for the output video frame."),
     .init      = init,
 
     .priv_size = sizeof(SetFieldContext),
-
-    .inputs = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_VIDEO,
-          .get_video_buffer = ff_null_get_video_buffer,
-          .start_frame      = start_frame, },
-        { .name = NULL }
-    },
-    .outputs = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_VIDEO, },
-        { .name = NULL }
-    },
+    .inputs    = setfield_inputs,
+    .outputs   = setfield_outputs,
 };
diff --git a/libavfilter/vf_showinfo.c b/libavfilter/vf_showinfo.c
index 9d20b48..1cad3c9 100644
--- a/libavfilter/vf_showinfo.c
+++ b/libavfilter/vf_showinfo.c
@@ -42,23 +42,26 @@
     return 0;
 }
 
-static int end_frame(AVFilterLink *inlink)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *frame)
 {
     AVFilterContext *ctx = inlink->dst;
     ShowInfoContext *showinfo = ctx->priv;
-    AVFilterBufferRef *picref = inlink->cur_buf;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
     uint32_t plane_checksum[4] = {0}, checksum = 0;
-    int i, plane, vsub = av_pix_fmt_descriptors[inlink->format].log2_chroma_h;
+    int i, plane, vsub = desc->log2_chroma_h;
 
-    for (plane = 0; picref->data[plane] && plane < 4; plane++) {
-        size_t linesize = av_image_get_linesize(picref->format, picref->video->w, plane);
-        uint8_t *data = picref->data[plane];
+    for (plane = 0; frame->data[plane] && plane < 4; plane++) {
+        int64_t linesize = av_image_get_linesize(frame->format, frame->video->w, plane);
+        uint8_t *data = frame->data[plane];
         int h = plane == 1 || plane == 2 ? inlink->h >> vsub : inlink->h;
 
+        if (linesize < 0)
+            return linesize;
+
         for (i = 0; i < h; i++) {
             plane_checksum[plane] = av_adler32_update(plane_checksum[plane], data, linesize);
             checksum = av_adler32_update(checksum, data, linesize);
-            data += picref->linesize[plane];
+            data += frame->linesize[plane];
         }
     }
 
@@ -67,24 +70,43 @@
            "fmt:%s sar:%d/%d s:%dx%d i:%c iskey:%d type:%c "
            "checksum:%08X plane_checksum:[%08X",
            showinfo->frame,
-           av_ts2str(picref->pts), av_ts2timestr(picref->pts, &inlink->time_base), picref->pos,
-           av_pix_fmt_descriptors[picref->format].name,
-           picref->video->sample_aspect_ratio.num, picref->video->sample_aspect_ratio.den,
-           picref->video->w, picref->video->h,
-           !picref->video->interlaced     ? 'P' :         /* Progressive  */
-           picref->video->top_field_first ? 'T' : 'B',    /* Top / Bottom */
-           picref->video->key_frame,
-           av_get_picture_type_char(picref->video->pict_type),
+           av_ts2str(frame->pts), av_ts2timestr(frame->pts, &inlink->time_base), frame->pos,
+           desc->name,
+           frame->video->sample_aspect_ratio.num, frame->video->sample_aspect_ratio.den,
+           frame->video->w, frame->video->h,
+           !frame->video->interlaced     ? 'P' :         /* Progressive  */
+           frame->video->top_field_first ? 'T' : 'B',    /* Top / Bottom */
+           frame->video->key_frame,
+           av_get_picture_type_char(frame->video->pict_type),
            checksum, plane_checksum[0]);
 
-    for (plane = 1; picref->data[plane] && plane < 4; plane++)
+    for (plane = 1; frame->data[plane] && plane < 4; plane++)
         av_log(ctx, AV_LOG_INFO, " %08X", plane_checksum[plane]);
     av_log(ctx, AV_LOG_INFO, "]\n");
 
     showinfo->frame++;
-    return ff_end_frame(inlink->dst->outputs[0]);
+    return ff_filter_frame(inlink->dst->outputs[0], frame);
 }
 
+static const AVFilterPad avfilter_vf_showinfo_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .filter_frame     = filter_frame,
+        .min_perms        = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_showinfo_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_showinfo = {
     .name        = "showinfo",
     .description = NULL_IF_CONFIG_SMALL("Show textual information for each video frame."),
@@ -92,15 +114,7 @@
     .priv_size = sizeof(ShowInfoContext),
     .init      = init,
 
-    .inputs    = (const AVFilterPad[]) {{ .name = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .get_video_buffer = ff_null_get_video_buffer,
-                                          .start_frame      = ff_null_start_frame,
-                                          .end_frame        = end_frame,
-                                          .min_perms        = AV_PERM_READ, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_showinfo_inputs,
 
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO },
-                                        { .name = NULL}},
+    .outputs   = avfilter_vf_showinfo_outputs,
 };
diff --git a/libavfilter/vf_slicify.c b/libavfilter/vf_slicify.c
deleted file mode 100644
index 3479430..0000000
--- a/libavfilter/vf_slicify.c
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * 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
- */
-
-/**
- * @file
- * video slicing filter
- */
-
-#include "avfilter.h"
-#include "internal.h"
-#include "video.h"
-#include "libavutil/common.h"
-#include "libavutil/pixdesc.h"
-
-typedef struct {
-    int h;          ///< output slice height
-    int vshift;     ///< vertical chroma subsampling shift
-    uint32_t lcg_state; ///< LCG state used to compute random slice height
-    int use_random_h;   ///< enable the use of random slice height values
-} SliceContext;
-
-static av_cold int init(AVFilterContext *ctx, const char *args)
-{
-    SliceContext *slice = ctx->priv;
-
-    slice->h = 16;
-    if (args) {
-        if (!strcmp(args, "random")) {
-            slice->use_random_h = 1;
-        } else {
-            sscanf(args, "%d", &slice->h);
-        }
-    }
-    return 0;
-}
-
-static int config_props(AVFilterLink *link)
-{
-    SliceContext *slice = link->dst->priv;
-
-    slice->vshift = av_pix_fmt_descriptors[link->format].log2_chroma_h;
-
-    return 0;
-}
-
-static int start_frame(AVFilterLink *link, AVFilterBufferRef *picref)
-{
-    SliceContext *slice = link->dst->priv;
-
-    if (slice->use_random_h) {
-        slice->lcg_state = slice->lcg_state * 1664525 + 1013904223;
-        slice->h = 8 + (uint64_t)slice->lcg_state * 25 / UINT32_MAX;
-    }
-
-    /* ensure that slices play nice with chroma subsampling, and enforce
-     * a reasonable minimum size for the slices */
-    slice->h = FFMAX(8, slice->h & (-1 << slice->vshift));
-
-    av_log(link->dst, AV_LOG_DEBUG, "h:%d\n", slice->h);
-    link->cur_buf = NULL;
-
-    return ff_start_frame(link->dst->outputs[0], picref);
-}
-
-static int draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
-{
-    SliceContext *slice = link->dst->priv;
-    int y2, ret = 0;
-
-    if (slice_dir == 1) {
-        for (y2 = y; y2 + slice->h <= y + h; y2 += slice->h) {
-            ret = ff_draw_slice(link->dst->outputs[0], y2, slice->h, slice_dir);
-            if (ret < 0)
-                return ret;
-        }
-
-        if (y2 < y + h)
-            return ff_draw_slice(link->dst->outputs[0], y2, y + h - y2, slice_dir);
-    } else if (slice_dir == -1) {
-        for (y2 = y + h; y2 - slice->h >= y; y2 -= slice->h) {
-            ret = ff_draw_slice(link->dst->outputs[0], y2 - slice->h, slice->h, slice_dir);
-            if (ret < 0)
-                return ret;
-        }
-
-        if (y2 > y)
-            return ff_draw_slice(link->dst->outputs[0], y, y2 - y, slice_dir);
-    }
-    return 0;
-}
-
-AVFilter avfilter_vf_slicify = {
-    .name      = "slicify",
-    .description = NULL_IF_CONFIG_SMALL("Pass the images of input video on to next video filter as multiple slices."),
-
-    .init      = init,
-
-    .priv_size = sizeof(SliceContext),
-
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .get_video_buffer = ff_null_get_video_buffer,
-                                          .start_frame      = start_frame,
-                                          .draw_slice       = draw_slice,
-                                          .config_props     = config_props,
-                                          .end_frame        = ff_null_end_frame, },
-                                        { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_VIDEO, },
-                                        { .name = NULL}},
-};
diff --git a/libavfilter/vf_smartblur.c b/libavfilter/vf_smartblur.c
index 73eb1c9..54ab209 100644
--- a/libavfilter/vf_smartblur.c
+++ b/libavfilter/vf_smartblur.c
@@ -126,12 +126,12 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
-        PIX_FMT_YUV444P,      PIX_FMT_YUV422P,
-        PIX_FMT_YUV420P,      PIX_FMT_YUV411P,
-        PIX_FMT_YUV410P,      PIX_FMT_YUV440P,
-        PIX_FMT_GRAY8,
-        PIX_FMT_NONE
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV444P,      AV_PIX_FMT_YUV422P,
+        AV_PIX_FMT_YUV420P,      AV_PIX_FMT_YUV411P,
+        AV_PIX_FMT_YUV410P,      AV_PIX_FMT_YUV440P,
+        AV_PIX_FMT_GRAY8,
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -154,8 +154,8 @@
     sws_filter.lumH = sws_filter.lumV = vec;
     sws_filter.chrH = sws_filter.chrV = NULL;
     f->filter_context = sws_getCachedContext(NULL,
-                                             width, height, PIX_FMT_GRAY8,
-                                             width, height, PIX_FMT_GRAY8,
+                                             width, height, AV_PIX_FMT_GRAY8,
+                                             width, height, AV_PIX_FMT_GRAY8,
                                              flags, &sws_filter, NULL, NULL);
 
     sws_freeVec(vec);
@@ -169,7 +169,7 @@
 static int config_props(AVFilterLink *inlink)
 {
     SmartblurContext *sblur = inlink->dst->priv;
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[inlink->format];
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
 
     sblur->hsub = desc->log2_chroma_w;
     sblur->vsub = desc->log2_chroma_h;
@@ -246,14 +246,21 @@
     }
 }
 
-static int end_frame(AVFilterLink *inlink)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *inpic)
 {
     SmartblurContext  *sblur  = inlink->dst->priv;
-    AVFilterBufferRef *inpic  = inlink->cur_buf;
-    AVFilterBufferRef *outpic = inlink->dst->outputs[0]->out_buf;
+    AVFilterLink *outlink     = inlink->dst->outputs[0];
+    AVFilterBufferRef *outpic;
     int cw = inlink->w >> sblur->hsub;
     int ch = inlink->h >> sblur->vsub;
 
+    outpic = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+    if (!outpic) {
+        avfilter_unref_bufferp(&inpic);
+        return AVERROR(ENOMEM);
+    }
+    avfilter_copy_buffer_ref_props(outpic, inpic);
+
     blur(outpic->data[0], outpic->linesize[0],
          inpic->data[0],  inpic->linesize[0],
          inlink->w, inlink->h, sblur->luma.threshold,
@@ -270,9 +277,29 @@
              sblur->chroma.filter_context);
     }
 
-    return ff_end_frame(inlink->dst->outputs[0]);
+    avfilter_unref_bufferp(&inpic);
+    return ff_filter_frame(outlink, outpic);
 }
 
+static const AVFilterPad smartblur_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .filter_frame = filter_frame,
+        .config_props = config_props,
+        .min_perms    = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad smartblur_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_smartblur = {
     .name        = "smartblur",
     .description = NULL_IF_CONFIG_SMALL("Blur the input video without impacting the outlines."),
@@ -282,22 +309,6 @@
     .init          = init,
     .uninit        = uninit,
     .query_formats = query_formats,
-
-    .inputs = (const AVFilterPad[]) {
-        {
-            .name         = "default",
-            .type         = AVMEDIA_TYPE_VIDEO,
-            .end_frame    = end_frame,
-            .config_props = config_props,
-            .min_perms    = AV_PERM_READ,
-        },
-        { .name = NULL }
-    },
-    .outputs = (const AVFilterPad[]) {
-        {
-            .name         = "default",
-            .type         = AVMEDIA_TYPE_VIDEO,
-        },
-        { .name = NULL }
-    }
+    .inputs        = smartblur_inputs,
+    .outputs       = smartblur_outputs,
 };
diff --git a/libavfilter/vf_super2xsai.c b/libavfilter/vf_super2xsai.c
index 0b48155..e2db3b4 100644
--- a/libavfilter/vf_super2xsai.c
+++ b/libavfilter/vf_super2xsai.c
@@ -30,6 +30,7 @@
 #include "libavutil/intreadwrite.h"
 #include "avfilter.h"
 #include "formats.h"
+#include "internal.h"
 #include "video.h"
 
 typedef struct {
@@ -232,12 +233,12 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
-        PIX_FMT_RGBA, PIX_FMT_BGRA, PIX_FMT_ARGB, PIX_FMT_ABGR,
-        PIX_FMT_RGB24, PIX_FMT_BGR24,
-        PIX_FMT_RGB565BE, PIX_FMT_BGR565BE, PIX_FMT_RGB555BE, PIX_FMT_BGR555BE,
-        PIX_FMT_RGB565LE, PIX_FMT_BGR565LE, PIX_FMT_RGB555LE, PIX_FMT_BGR555LE,
-        PIX_FMT_NONE
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_RGBA, AV_PIX_FMT_BGRA, AV_PIX_FMT_ARGB, AV_PIX_FMT_ABGR,
+        AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
+        AV_PIX_FMT_RGB565BE, AV_PIX_FMT_BGR565BE, AV_PIX_FMT_RGB555BE, AV_PIX_FMT_BGR555BE,
+        AV_PIX_FMT_RGB565LE, AV_PIX_FMT_BGR565LE, AV_PIX_FMT_RGB555LE, AV_PIX_FMT_BGR555LE,
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -255,16 +256,16 @@
     sai->bpp  = 4;
 
     switch (inlink->format) {
-    case PIX_FMT_RGB24:
-    case PIX_FMT_BGR24:
+    case AV_PIX_FMT_RGB24:
+    case AV_PIX_FMT_BGR24:
         sai->bpp = 3;
         break;
 
-    case PIX_FMT_RGB565BE:
-    case PIX_FMT_BGR565BE:
+    case AV_PIX_FMT_RGB565BE:
+    case AV_PIX_FMT_BGR565BE:
         sai->is_be = 1;
-    case PIX_FMT_RGB565LE:
-    case PIX_FMT_BGR565LE:
+    case AV_PIX_FMT_RGB565LE:
+    case AV_PIX_FMT_BGR565LE:
         sai->hi_pixel_mask   = 0xF7DEF7DE;
         sai->lo_pixel_mask   = 0x08210821;
         sai->q_hi_pixel_mask = 0xE79CE79C;
@@ -272,11 +273,11 @@
         sai->bpp = 2;
         break;
 
-    case PIX_FMT_BGR555BE:
-    case PIX_FMT_RGB555BE:
+    case AV_PIX_FMT_BGR555BE:
+    case AV_PIX_FMT_RGB555BE:
         sai->is_be = 1;
-    case PIX_FMT_BGR555LE:
-    case PIX_FMT_RGB555LE:
+    case AV_PIX_FMT_BGR555LE:
+    case AV_PIX_FMT_RGB555LE:
         sai->hi_pixel_mask   = 0x7BDE7BDE;
         sai->lo_pixel_mask   = 0x04210421;
         sai->q_hi_pixel_mask = 0x739C739C;
@@ -302,41 +303,51 @@
     return 0;
 }
 
-static int null_draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir) { return 0; }
-
-static int end_frame(AVFilterLink *inlink)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
 {
     AVFilterLink *outlink = inlink->dst->outputs[0];
-    AVFilterBufferRef  *inpicref =  inlink->cur_buf;
-    AVFilterBufferRef *outpicref = outlink->out_buf;
+    AVFilterBufferRef *outpicref = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+    if (!outpicref) {
+        avfilter_unref_bufferp(&inpicref);
+        return AVERROR(ENOMEM);
+    }
+    avfilter_copy_buffer_ref_props(outpicref, inpicref);
+    outpicref->video->w = outlink->w;
+    outpicref->video->h = outlink->h;
 
     super2xsai(inlink->dst, inpicref->data[0], inpicref->linesize[0],
                outpicref->data[0], outpicref->linesize[0],
                inlink->w, inlink->h);
 
-    ff_draw_slice(outlink, 0, outlink->h, 1);
-    return ff_end_frame(outlink);
+    avfilter_unref_bufferp(&inpicref);
+    return ff_filter_frame(outlink, outpicref);
 }
 
+static const AVFilterPad super2xsai_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .config_props = config_input,
+        .filter_frame = filter_frame,
+        .min_perms    = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad super2xsai_outputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .config_props = config_output,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_super2xsai = {
     .name        = "super2xsai",
     .description = NULL_IF_CONFIG_SMALL("Scale the input by 2x using the Super2xSaI pixel art algorithm."),
     .priv_size   = sizeof(Super2xSaIContext),
     .query_formats = query_formats,
-
-    .inputs = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_VIDEO,
-          .config_props     = config_input,
-          .draw_slice       = null_draw_slice,
-          .end_frame        = end_frame,
-          .min_perms        = AV_PERM_READ },
-        { .name = NULL }
-    },
-    .outputs = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_VIDEO,
-          .config_props     = config_output },
-        { .name = NULL }
-    },
+    .inputs        = super2xsai_inputs,
+    .outputs       = super2xsai_outputs,
 };
diff --git a/libavfilter/vf_swapuv.c b/libavfilter/vf_swapuv.c
index 94015d9..6345c0d 100644
--- a/libavfilter/vf_swapuv.c
+++ b/libavfilter/vf_swapuv.c
@@ -61,35 +61,42 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
-        PIX_FMT_YUV420P, PIX_FMT_YUVJ420P, PIX_FMT_YUVA420P,
-        PIX_FMT_YUV444P, PIX_FMT_YUVJ444P, PIX_FMT_YUVA444P,
-        PIX_FMT_YUV440P, PIX_FMT_YUVJ440P,
-        PIX_FMT_YUV422P, PIX_FMT_YUVJ422P,
-        PIX_FMT_YUV411P,
-        PIX_FMT_NONE,
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVA420P,
+        AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVA444P,
+        AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUVJ440P,
+        AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUVJ422P,
+        AV_PIX_FMT_YUV411P,
+        AV_PIX_FMT_NONE,
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
     return 0;
 }
 
+static const AVFilterPad swapuv_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = get_video_buffer,
+        .start_frame      = start_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad swapuv_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_swapuv = {
     .name      = "swapuv",
     .description = NULL_IF_CONFIG_SMALL("Swap U and V components."),
     .priv_size = 0,
     .query_formats = query_formats,
-
-    .inputs = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_VIDEO,
-          .get_video_buffer = get_video_buffer,
-          .start_frame      = start_frame, },
-        { .name = NULL }
-    },
-    .outputs = (const AVFilterPad[]) {
-        { .name             = "default",
-          .type             = AVMEDIA_TYPE_VIDEO, },
-        { .name             = NULL }
-    },
+    .inputs        = swapuv_inputs,
+    .outputs       = swapuv_outputs,
 };
diff --git a/libavfilter/vf_thumbnail.c b/libavfilter/vf_thumbnail.c
index 67ffc51..0d245d9 100644
--- a/libavfilter/vf_thumbnail.c
+++ b/libavfilter/vf_thumbnail.c
@@ -68,27 +68,6 @@
     return 0;
 }
 
-static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
-{
-    int i, j;
-    AVFilterContext *ctx = inlink->dst;
-    ThumbContext *thumb = ctx->priv;
-    int *hist = thumb->frames[thumb->n].histogram;
-    AVFilterBufferRef *picref = inlink->cur_buf;
-    const uint8_t *p = picref->data[0] + y * picref->linesize[0];
-
-    // update current frame RGB histogram
-    for (j = 0; j < h; j++) {
-        for (i = 0; i < inlink->w; i++) {
-            hist[0*256 + p[i*3    ]]++;
-            hist[1*256 + p[i*3 + 1]]++;
-            hist[2*256 + p[i*3 + 2]]++;
-        }
-        p += picref->linesize[0];
-    }
-    return 0;
-}
-
 /**
  * @brief        Compute Sum-square deviation to estimate "closeness".
  * @param hist   color distribution histogram
@@ -107,18 +86,29 @@
     return sum_sq_err;
 }
 
-static int  end_frame(AVFilterLink *inlink)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *frame)
 {
     int i, j, best_frame_idx = 0;
     double avg_hist[HIST_SIZE] = {0}, sq_err, min_sq_err = -1;
-    AVFilterLink *outlink = inlink->dst->outputs[0];
-    ThumbContext *thumb   = inlink->dst->priv;
     AVFilterContext *ctx  = inlink->dst;
+    ThumbContext *thumb   = ctx->priv;
+    AVFilterLink *outlink = ctx->outputs[0];
     AVFilterBufferRef *picref;
+    int *hist = thumb->frames[thumb->n].histogram;
+    const uint8_t *p = frame->data[0];
 
     // keep a reference of each frame
-    thumb->frames[thumb->n].buf = inlink->cur_buf;
-    inlink->cur_buf = NULL;
+    thumb->frames[thumb->n].buf = frame;
+
+    // update current frame RGB histogram
+    for (j = 0; j < inlink->h; j++) {
+        for (i = 0; i < inlink->w; i++) {
+            hist[0*256 + p[i*3    ]]++;
+            hist[1*256 + p[i*3 + 1]]++;
+            hist[2*256 + p[i*3 + 2]]++;
+        }
+        p += frame->linesize[0];
+    }
 
     // no selection until the buffer of N frames is filled up
     if (thumb->n < thumb->n_frames - 1) {
@@ -145,8 +135,7 @@
         memset(thumb->frames[i].histogram, 0, sizeof(thumb->frames[i].histogram));
         if (i == best_frame_idx)
             continue;
-        avfilter_unref_buffer(thumb->frames[i].buf);
-        thumb->frames[i].buf = NULL;
+        avfilter_unref_bufferp(&thumb->frames[i].buf);
     }
     thumb->n = 0;
 
@@ -154,25 +143,19 @@
     picref = thumb->frames[best_frame_idx].buf;
     av_log(ctx, AV_LOG_INFO, "frame id #%d (pts_time=%f) selected\n",
            best_frame_idx, picref->pts * av_q2d(inlink->time_base));
-    ff_start_frame(outlink, picref);
     thumb->frames[best_frame_idx].buf = NULL;
-    ff_draw_slice(outlink, 0, inlink->h, 1);
-    return ff_end_frame(outlink);
+    return ff_filter_frame(outlink, picref);
 }
 
 static av_cold void uninit(AVFilterContext *ctx)
 {
     int i;
     ThumbContext *thumb = ctx->priv;
-    for (i = 0; i < thumb->n_frames && thumb->frames[i].buf; i++) {
-        avfilter_unref_buffer(thumb->frames[i].buf);
-        thumb->frames[i].buf = NULL;
-    }
+    for (i = 0; i < thumb->n_frames && thumb->frames[i].buf; i++)
+        avfilter_unref_bufferp(&thumb->frames[i].buf);
     av_freep(&thumb->frames);
 }
 
-static int null_start_frame(AVFilterLink *link, AVFilterBufferRef *picref) { return 0; }
-
 static int request_frame(AVFilterLink *link)
 {
     ThumbContext *thumb = link->src->priv;
@@ -211,14 +194,35 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
-        PIX_FMT_RGB24, PIX_FMT_BGR24,
-        PIX_FMT_NONE
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
+        AV_PIX_FMT_NONE
     };
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
     return 0;
 }
 
+static const AVFilterPad thumbnail_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = ff_null_get_video_buffer,
+        .min_perms        = AV_PERM_PRESERVE,
+        .filter_frame     = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad thumbnail_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .request_frame = request_frame,
+        .poll_frame    = poll_frame,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_thumbnail = {
     .name          = "thumbnail",
     .description   = NULL_IF_CONFIG_SMALL("Select the most representative frame in a given sequence of consecutive frames."),
@@ -226,21 +230,6 @@
     .init          = init,
     .uninit        = uninit,
     .query_formats = query_formats,
-    .inputs        = (const AVFilterPad[]) {
-        {   .name             = "default",
-            .type             = AVMEDIA_TYPE_VIDEO,
-            .get_video_buffer = ff_null_get_video_buffer,
-            .min_perms        = AV_PERM_PRESERVE,
-            .start_frame      = null_start_frame,
-            .draw_slice       = draw_slice,
-            .end_frame        = end_frame,
-        },{ .name = NULL }
-    },
-    .outputs       = (const AVFilterPad[]) {
-        {   .name             = "default",
-            .type             = AVMEDIA_TYPE_VIDEO,
-            .request_frame    = request_frame,
-            .poll_frame       = poll_frame,
-        },{ .name = NULL }
-    },
+    .inputs        = thumbnail_inputs,
+    .outputs       = thumbnail_outputs,
 };
diff --git a/libavfilter/vf_tile.c b/libavfilter/vf_tile.c
index 52d53eb..5f5c6d6 100644
--- a/libavfilter/vf_tile.c
+++ b/libavfilter/vf_tile.c
@@ -23,6 +23,7 @@
  * tile video filter
  */
 
+#include "libavutil/opt.h"
 #include "libavutil/pixdesc.h"
 #include "avfilter.h"
 #include "drawutils.h"
@@ -31,30 +32,61 @@
 #include "internal.h"
 
 typedef struct {
+    const AVClass *class;
     unsigned w, h;
+    unsigned margin;
+    unsigned padding;
     unsigned current;
+    unsigned nb_frames;
     FFDrawContext draw;
     FFDrawColor blank;
 } TileContext;
 
 #define REASONABLE_SIZE 1024
 
+#define OFFSET(x) offsetof(TileContext, x)
+#define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
+
+static const AVOption tile_options[] = {
+    { "layout", "set grid size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE,
+        {.str = "6x5"}, 0, 0, FLAGS },
+    { "margin",  "set outer border margin in pixels",    OFFSET(margin),
+        AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1024, FLAGS },
+    { "padding", "set inner border thickness in pixels", OFFSET(padding),
+        AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1024, FLAGS },
+    { "nb_frames", "set maximum number of frame to render", OFFSET(nb_frames),
+        AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, FLAGS },
+    {NULL},
+};
+
+AVFILTER_DEFINE_CLASS(tile);
+
 static av_cold int init(AVFilterContext *ctx, const char *args)
 {
     TileContext *tile = ctx->priv;
-    int r;
-    char dummy;
+    static const char *shorthand[] = { "layout", "nb_frames", "margin", "padding", NULL };
+    int ret;
 
-    if (!args)
-        args = "6x5";
-    r = sscanf(args, "%ux%u%c", &tile->w, &tile->h, &dummy);
-    if (r != 2 || !tile->w || !tile->h)
-        return AVERROR(EINVAL);
+    tile->class = &tile_class;
+    av_opt_set_defaults(tile);
+
+    if ((ret = av_opt_set_from_string(tile, args, shorthand, "=", ":")) < 0)
+        return ret;
+
     if (tile->w > REASONABLE_SIZE || tile->h > REASONABLE_SIZE) {
         av_log(ctx, AV_LOG_ERROR, "Tile size %ux%u is insane.\n",
                tile->w, tile->h);
         return AVERROR(EINVAL);
     }
+
+    if (tile->nb_frames == 0) {
+        tile->nb_frames = tile->w * tile->h;
+    } else if (tile->nb_frames > tile->w * tile->h) {
+        av_log(ctx, AV_LOG_ERROR, "nb_frames must be less than or equal to %dx%d=%d\n",
+               tile->w, tile->h, tile->w * tile->h);
+        return AVERROR(EINVAL);
+    }
+
     return 0;
 }
 
@@ -69,22 +101,24 @@
     AVFilterContext *ctx = outlink->src;
     TileContext *tile   = ctx->priv;
     AVFilterLink *inlink = ctx->inputs[0];
+    const unsigned total_margin_w = (tile->w - 1) * tile->padding + 2*tile->margin;
+    const unsigned total_margin_h = (tile->h - 1) * tile->padding + 2*tile->margin;
 
-    if (inlink->w > INT_MAX / tile->w) {
+    if (inlink->w > (INT_MAX - total_margin_w) / tile->w) {
         av_log(ctx, AV_LOG_ERROR, "Total width %ux%u is too much.\n",
                tile->w, inlink->w);
         return AVERROR(EINVAL);
     }
-    if (inlink->h > INT_MAX / tile->h) {
+    if (inlink->h > (INT_MAX - total_margin_h) / tile->h) {
         av_log(ctx, AV_LOG_ERROR, "Total height %ux%u is too much.\n",
                tile->h, inlink->h);
         return AVERROR(EINVAL);
     }
-    outlink->w = tile->w * inlink->w;
-    outlink->h = tile->h * inlink->h;
+    outlink->w = tile->w * inlink->w + total_margin_w;
+    outlink->h = tile->h * inlink->h + total_margin_h;
     outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
     outlink->frame_rate = av_mul_q(inlink->frame_rate,
-                                   (AVRational){ 1, tile->w * tile->h });
+                                   (AVRational){ 1, tile->nb_frames });
     ff_draw_init(&tile->draw, inlink->format, 0);
     /* TODO make the color an option, or find an unified way of choosing it */
     ff_draw_color(&tile->draw, &tile->blank, (uint8_t[]){ 0, 0, 0, -1 });
@@ -92,78 +126,82 @@
     return 0;
 }
 
-/* Note: direct rendering is not possible since there is no guarantee that
- * buffers are fed to start_frame in the order they were obtained from
- * get_buffer (think B-frames). */
-
-static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)
+static void get_current_tile_pos(AVFilterContext *ctx, unsigned *x, unsigned *y)
 {
-    AVFilterContext *ctx  = inlink->dst;
     TileContext *tile    = ctx->priv;
-    AVFilterLink *outlink = ctx->outputs[0];
+    AVFilterLink *inlink = ctx->inputs[0];
+    const unsigned tx = tile->current % tile->w;
+    const unsigned ty = tile->current / tile->w;
 
-    if (tile->current)
-        return 0;
-    outlink->out_buf = ff_get_video_buffer(outlink, AV_PERM_WRITE,
-                                                 outlink->w, outlink->h);
-    avfilter_copy_buffer_ref_props(outlink->out_buf, picref);
-    outlink->out_buf->video->w = outlink->w;
-    outlink->out_buf->video->h = outlink->h;
-    return 0;
-}
-
-static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
-{
-    AVFilterContext *ctx  = inlink->dst;
-    TileContext *tile    = ctx->priv;
-    AVFilterLink *outlink = ctx->outputs[0];
-    unsigned x0 = inlink->w * (tile->current % tile->w);
-    unsigned y0 = inlink->h * (tile->current / tile->w);
-
-    ff_copy_rectangle2(&tile->draw,
-                       outlink->out_buf->data, outlink->out_buf->linesize,
-                       inlink ->cur_buf->data, inlink ->cur_buf->linesize,
-                       x0, y0 + y, 0, y, inlink->cur_buf->video->w, h);
-    /* TODO if tile->w == 1 && slice_dir is always 1, we could draw_slice
-     * immediately. */
-    return 0;
+    *x = tile->margin + (inlink->w + tile->padding) * tx;
+    *y = tile->margin + (inlink->h + tile->padding) * ty;
 }
 
 static void draw_blank_frame(AVFilterContext *ctx, AVFilterBufferRef *out_buf)
 {
     TileContext *tile    = ctx->priv;
     AVFilterLink *inlink  = ctx->inputs[0];
-    unsigned x0 = inlink->w * (tile->current % tile->w);
-    unsigned y0 = inlink->h * (tile->current / tile->w);
+    unsigned x0, y0;
 
+    get_current_tile_pos(ctx, &x0, &y0);
     ff_fill_rectangle(&tile->draw, &tile->blank,
                       out_buf->data, out_buf->linesize,
                       x0, y0, inlink->w, inlink->h);
     tile->current++;
 }
-static void end_last_frame(AVFilterContext *ctx)
+static int end_last_frame(AVFilterContext *ctx)
 {
     TileContext *tile    = ctx->priv;
     AVFilterLink *outlink = ctx->outputs[0];
     AVFilterBufferRef *out_buf = outlink->out_buf;
+    int ret;
 
     outlink->out_buf = NULL;
-    ff_start_frame(outlink, out_buf);
-    while (tile->current < tile->w * tile->h)
+    while (tile->current < tile->nb_frames)
         draw_blank_frame(ctx, out_buf);
-    ff_draw_slice(outlink, 0, out_buf->video->h, 1);
-    ff_end_frame(outlink);
+    ret = ff_filter_frame(outlink, out_buf);
     tile->current = 0;
+    return ret;
 }
 
-static int end_frame(AVFilterLink *inlink)
+/* Note: direct rendering is not possible since there is no guarantee that
+ * buffers are fed to filter_frame in the order they were obtained from
+ * get_buffer (think B-frames). */
+
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)
 {
     AVFilterContext *ctx  = inlink->dst;
     TileContext *tile    = ctx->priv;
+    AVFilterLink *outlink = ctx->outputs[0];
+    unsigned x0, y0;
+
+    if (!tile->current) {
+        outlink->out_buf = ff_get_video_buffer(outlink, AV_PERM_WRITE,
+                                               outlink->w, outlink->h);
+        if (!outlink->out_buf)
+            return AVERROR(ENOMEM);
+        avfilter_copy_buffer_ref_props(outlink->out_buf, picref);
+        outlink->out_buf->video->w = outlink->w;
+        outlink->out_buf->video->h = outlink->h;
+
+        /* fill surface once for margin/padding */
+        if (tile->margin || tile->padding)
+            ff_fill_rectangle(&tile->draw, &tile->blank,
+                              outlink->out_buf->data,
+                              outlink->out_buf->linesize,
+                              0, 0, outlink->w, outlink->h);
+    }
+
+    get_current_tile_pos(ctx, &x0, &y0);
+    ff_copy_rectangle2(&tile->draw,
+                       outlink->out_buf->data, outlink->out_buf->linesize,
+                       inlink ->cur_buf->data, inlink ->cur_buf->linesize,
+                       x0, y0, 0, 0, inlink->w, inlink->h);
 
     avfilter_unref_bufferp(&inlink->cur_buf);
-    if (++tile->current == tile->w * tile->h)
-        end_last_frame(ctx);
+    if (++tile->current == tile->nb_frames)
+        return end_last_frame(ctx);
+
     return 0;
 }
 
@@ -178,17 +216,34 @@
         r = ff_request_frame(inlink);
         if (r < 0) {
             if (r == AVERROR_EOF && tile->current)
-                end_last_frame(ctx);
-            else
-                return r;
+                r = end_last_frame(ctx);
             break;
         }
         if (!tile->current) /* done */
             break;
     }
-    return 0;
+    return r;
 }
 
+static const AVFilterPad tile_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .filter_frame = filter_frame,
+        .min_perms    = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad tile_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .config_props  = config_props,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
 
 AVFilter avfilter_vf_tile = {
     .name          = "tile",
@@ -196,20 +251,7 @@
     .init          = init,
     .query_formats = query_formats,
     .priv_size     = sizeof(TileContext),
-    .inputs = (const AVFilterPad[]) {
-        { .name        = "default",
-          .type        = AVMEDIA_TYPE_VIDEO,
-          .start_frame = start_frame,
-          .draw_slice  = draw_slice,
-          .end_frame   = end_frame,
-          .min_perms   = AV_PERM_READ, },
-        { .name = NULL }
-    },
-    .outputs = (const AVFilterPad[]) {
-        { .name          = "default",
-          .type          = AVMEDIA_TYPE_VIDEO,
-          .config_props  = config_props,
-          .request_frame = request_frame },
-        { .name = NULL }
-    },
+    .inputs        = tile_inputs,
+    .outputs       = tile_outputs,
+    .priv_class    = &tile_class,
 };
diff --git a/libavfilter/vf_tinterlace.c b/libavfilter/vf_tinterlace.c
index d41889a..d24105e 100644
--- a/libavfilter/vf_tinterlace.c
+++ b/libavfilter/vf_tinterlace.c
@@ -62,19 +62,19 @@
 } TInterlaceContext;
 
 #define FULL_SCALE_YUVJ_FORMATS \
-    PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUVJ440P
+    AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ440P
 
-static enum PixelFormat full_scale_yuvj_pix_fmts[] = {
-    FULL_SCALE_YUVJ_FORMATS, PIX_FMT_NONE
+static enum AVPixelFormat full_scale_yuvj_pix_fmts[] = {
+    FULL_SCALE_YUVJ_FORMATS, AV_PIX_FMT_NONE
 };
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
-        PIX_FMT_YUV420P,  PIX_FMT_YUV422P,  PIX_FMT_YUV444P,
-        PIX_FMT_YUV444P,  PIX_FMT_YUV410P,  PIX_FMT_YUVA420P,
-        PIX_FMT_GRAY8, FULL_SCALE_YUVJ_FORMATS,
-        PIX_FMT_NONE
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV420P,  AV_PIX_FMT_YUV422P,  AV_PIX_FMT_YUV444P,
+        AV_PIX_FMT_YUV444P,  AV_PIX_FMT_YUV410P,  AV_PIX_FMT_YUVA420P,
+        AV_PIX_FMT_GRAY8, FULL_SCALE_YUVJ_FORMATS,
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -130,7 +130,7 @@
 {
     AVFilterContext *ctx = outlink->src;
     AVFilterLink *inlink = outlink->src->inputs[0];
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[outlink->format];
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(outlink->format);
     TInterlaceContext *tinterlace = ctx->priv;
 
     tinterlace->vsub = desc->log2_chroma_h;
@@ -176,10 +176,10 @@
 static inline
 void copy_picture_field(uint8_t *dst[4], int dst_linesize[4],
                         const uint8_t *src[4], int src_linesize[4],
-                        enum PixelFormat format, int w, int src_h,
+                        enum AVPixelFormat format, int w, int src_h,
                         int src_field, int interleave, int dst_field)
 {
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[format];
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
     int plane, vsub = desc->log2_chroma_h;
     int k = src_field == FIELD_UPPER_AND_LOWER ? 1 : 2;
 
@@ -188,6 +188,10 @@
         int linesize = av_image_get_linesize(format, w, plane);
         uint8_t *dstp = dst[plane];
         const uint8_t *srcp = src[plane];
+
+        if (linesize < 0)
+            return;
+
         lines /= k;
         if (src_field == FIELD_LOWER)
             srcp += src_linesize[plane];
@@ -330,24 +334,6 @@
     return 0;
 }
 
-static int poll_frame(AVFilterLink *outlink)
-{
-    TInterlaceContext *tinterlace = outlink->src->priv;
-    AVFilterLink *inlink = outlink->src->inputs[0];
-    int ret, val;
-
-    val = ff_poll_frame(inlink);
-
-    if (val == 1 && !tinterlace->next) {
-        if ((ret = ff_request_frame(inlink)) < 0)
-            return ret;
-        val = ff_poll_frame(inlink);
-    }
-    av_assert0(tinterlace->next);
-
-    return val;
-}
-
 static int request_frame(AVFilterLink *outlink)
 {
     TInterlaceContext *tinterlace = outlink->src->priv;
@@ -365,6 +351,27 @@
 
 static int null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { return 0; }
 
+static const AVFilterPad tinterlace_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .start_frame  = start_frame,
+        .draw_slice   = null_draw_slice,
+        .end_frame    = end_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad tinterlace_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .config_props  = config_out_props,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_tinterlace = {
     .name          = "tinterlace",
     .description   = NULL_IF_CONFIG_SMALL("Perform temporal field interlacing."),
@@ -372,21 +379,6 @@
     .init          = init,
     .uninit        = uninit,
     .query_formats = query_formats,
-
-    .inputs = (const AVFilterPad[]) {
-        { .name          = "default",
-          .type          = AVMEDIA_TYPE_VIDEO,
-          .start_frame   = start_frame,
-          .draw_slice    = null_draw_slice,
-          .end_frame     = end_frame, },
-        { .name = NULL}
-    },
-    .outputs = (const AVFilterPad[]) {
-        { .name          = "default",
-          .type          = AVMEDIA_TYPE_VIDEO,
-          .config_props  = config_out_props,
-          .poll_frame    = poll_frame,
-          .request_frame = request_frame },
-        { .name = NULL}
-    },
+    .inputs        = tinterlace_inputs,
+    .outputs       = tinterlace_outputs,
 };
diff --git a/libavfilter/vf_transpose.c b/libavfilter/vf_transpose.c
index 4161050..6026caa 100644
--- a/libavfilter/vf_transpose.c
+++ b/libavfilter/vf_transpose.c
@@ -28,6 +28,7 @@
 #include <stdio.h>
 
 #include "libavutil/intreadwrite.h"
+#include "libavutil/opt.h"
 #include "libavutil/pixdesc.h"
 #include "libavutil/imgutils.h"
 #include "libavutil/internal.h"
@@ -36,7 +37,14 @@
 #include "internal.h"
 #include "video.h"
 
+typedef enum {
+    TRANSPOSE_PT_TYPE_NONE,
+    TRANSPOSE_PT_TYPE_LANDSCAPE,
+    TRANSPOSE_PT_TYPE_PORTRAIT,
+} PassthroughType;
+
 typedef struct {
+    const AVClass *class;
     int hsub, vsub;
     int pixsteps[4];
 
@@ -45,46 +53,58 @@
     /* 2    Rotate by 90 degrees counterclockwise.           */
     /* 3    Rotate by 90 degrees clockwise and vflip.        */
     int dir;
-    int passthrough; ///< landscape passthrough mode enabled
+    PassthroughType passthrough; ///< landscape passthrough mode enabled
 } TransContext;
 
+#define OFFSET(x) offsetof(TransContext, x)
+#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
+
+static const AVOption transpose_options[] = {
+    { "dir", "set transpose direction", OFFSET(dir), AV_OPT_TYPE_INT, {.i64=0},  0, 7, FLAGS },
+
+    { "passthrough", "do not apply transposition if the input matches the specified geometry",
+      OFFSET(passthrough), AV_OPT_TYPE_INT, {.i64=TRANSPOSE_PT_TYPE_NONE},  0, INT_MAX, FLAGS, "passthrough" },
+    { "none",      "always apply transposition",   0, AV_OPT_TYPE_CONST, {.i64=TRANSPOSE_PT_TYPE_NONE},      INT_MIN, INT_MAX, FLAGS, "passthrough" },
+    { "portrait",  "preserve portrait geometry",   0, AV_OPT_TYPE_CONST, {.i64=TRANSPOSE_PT_TYPE_PORTRAIT},  INT_MIN, INT_MAX, FLAGS, "passthrough" },
+    { "landscape", "preserve landscape geometry",  0, AV_OPT_TYPE_CONST, {.i64=TRANSPOSE_PT_TYPE_LANDSCAPE}, INT_MIN, INT_MAX, FLAGS, "passthrough" },
+
+    { NULL },
+};
+
+AVFILTER_DEFINE_CLASS(transpose);
+
 static av_cold int init(AVFilterContext *ctx, const char *args)
 {
     TransContext *trans = ctx->priv;
-    trans->dir = 0;
+    const char *shorthand[] = { "dir", "passthrough", NULL };
 
-    if (args)
-        sscanf(args, "%d", &trans->dir);
+    trans->class = &transpose_class;
+    av_opt_set_defaults(trans);
 
-    if (trans->dir < 0 || trans->dir > 7) {
-        av_log(ctx, AV_LOG_ERROR, "Invalid value %d not between 0 and 7.\n",
-               trans->dir);
-        return AVERROR(EINVAL);
-    }
-    return 0;
+    return av_opt_set_from_string(trans, args, shorthand, "=", ":");
 }
 
 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_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_YUVJ444P,
-        PIX_FMT_YUV420P,      PIX_FMT_YUVJ420P,
-        PIX_FMT_YUV410P,
-        PIX_FMT_YUVA420P,     PIX_FMT_GRAY8,
-        PIX_FMT_NONE
+    enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_ARGB,         AV_PIX_FMT_RGBA,
+        AV_PIX_FMT_ABGR,         AV_PIX_FMT_BGRA,
+        AV_PIX_FMT_RGB24,        AV_PIX_FMT_BGR24,
+        AV_PIX_FMT_RGB565BE,     AV_PIX_FMT_RGB565LE,
+        AV_PIX_FMT_RGB555BE,     AV_PIX_FMT_RGB555LE,
+        AV_PIX_FMT_BGR565BE,     AV_PIX_FMT_BGR565LE,
+        AV_PIX_FMT_BGR555BE,     AV_PIX_FMT_BGR555LE,
+        AV_PIX_FMT_GRAY16BE,     AV_PIX_FMT_GRAY16LE,
+        AV_PIX_FMT_YUV420P16LE,  AV_PIX_FMT_YUV420P16BE,
+        AV_PIX_FMT_YUV444P16LE,  AV_PIX_FMT_YUV444P16BE,
+        AV_PIX_FMT_NV12,         AV_PIX_FMT_NV21,
+        AV_PIX_FMT_RGB8,         AV_PIX_FMT_BGR8,
+        AV_PIX_FMT_RGB4_BYTE,    AV_PIX_FMT_BGR4_BYTE,
+        AV_PIX_FMT_YUV444P,      AV_PIX_FMT_YUVJ444P,
+        AV_PIX_FMT_YUV420P,      AV_PIX_FMT_YUVJ420P,
+        AV_PIX_FMT_YUV410P,
+        AV_PIX_FMT_YUVA420P,     AV_PIX_FMT_GRAY8,
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -96,24 +116,30 @@
     AVFilterContext *ctx = outlink->src;
     TransContext *trans = ctx->priv;
     AVFilterLink *inlink = ctx->inputs[0];
-    const AVPixFmtDescriptor *pixdesc = &av_pix_fmt_descriptors[outlink->format];
+    const AVPixFmtDescriptor *desc_out = av_pix_fmt_desc_get(outlink->format);
+    const AVPixFmtDescriptor *desc_in  = av_pix_fmt_desc_get(inlink->format);
 
     if (trans->dir&4) {
+        av_log(ctx, AV_LOG_WARNING,
+               "dir values greater than 3 are deprecated, use the passthrough option instead\n");
         trans->dir &= 3;
-        if (inlink->w >= inlink->h) {
-            trans->passthrough = 1;
-
-            av_log(ctx, AV_LOG_VERBOSE,
-                   "w:%d h:%d -> w:%d h:%d (landscape passthrough mode)\n",
-                   inlink->w, inlink->h, outlink->w, outlink->h);
-            return 0;
-        }
+        trans->passthrough = TRANSPOSE_PT_TYPE_LANDSCAPE;
     }
 
-    trans->hsub = av_pix_fmt_descriptors[inlink->format].log2_chroma_w;
-    trans->vsub = av_pix_fmt_descriptors[inlink->format].log2_chroma_h;
+    if ((inlink->w >= inlink->h && trans->passthrough == TRANSPOSE_PT_TYPE_LANDSCAPE) ||
+        (inlink->w <= inlink->h && trans->passthrough == TRANSPOSE_PT_TYPE_PORTRAIT)) {
+        av_log(ctx, AV_LOG_VERBOSE,
+               "w:%d h:%d -> w:%d h:%d (passthrough mode)\n",
+               inlink->w, inlink->h, inlink->w, inlink->h);
+        return 0;
+    } else {
+        trans->passthrough = TRANSPOSE_PT_TYPE_NONE;
+    }
 
-    av_image_fill_max_pixsteps(trans->pixsteps, NULL, pixdesc);
+    trans->hsub = desc_in->log2_chroma_w;
+    trans->vsub = desc_in->log2_chroma_h;
+
+    av_image_fill_max_pixsteps(trans->pixsteps, NULL, desc_out);
 
     outlink->w = inlink->h;
     outlink->h = inlink->w;
@@ -139,107 +165,105 @@
         ff_default_get_video_buffer(inlink, perms, w, h);
 }
 
-static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)
+static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *in)
 {
     TransContext *trans = inlink->dst->priv;
     AVFilterLink *outlink = inlink->dst->outputs[0];
-    AVFilterBufferRef *buf_out;
+    AVFilterBufferRef *out;
+    int plane;
 
     if (trans->passthrough)
-        return ff_null_start_frame(inlink, picref);
+        return ff_filter_frame(outlink, in);
 
-    outlink->out_buf = ff_get_video_buffer(outlink, AV_PERM_WRITE,
-                                           outlink->w, outlink->h);
-    if (!outlink->out_buf)
+    out = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+    if (!out) {
+        avfilter_unref_bufferp(&in);
         return AVERROR(ENOMEM);
-
-    outlink->out_buf->pts = picref->pts;
-
-    if (picref->video->sample_aspect_ratio.num == 0) {
-        outlink->out_buf->video->sample_aspect_ratio = picref->video->sample_aspect_ratio;
-    } else {
-        outlink->out_buf->video->sample_aspect_ratio.num = picref->video->sample_aspect_ratio.den;
-        outlink->out_buf->video->sample_aspect_ratio.den = picref->video->sample_aspect_ratio.num;
     }
 
-    buf_out = avfilter_ref_buffer(outlink->out_buf, ~0);
-    if (!buf_out)
-        return AVERROR(ENOMEM);
-    return ff_start_frame(outlink, buf_out);
-}
+    out->pts = in->pts;
 
-static int 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, ret;
+    if (in->video->sample_aspect_ratio.num == 0) {
+        out->video->sample_aspect_ratio = in->video->sample_aspect_ratio;
+    } else {
+        out->video->sample_aspect_ratio.num = in->video->sample_aspect_ratio.den;
+        out->video->sample_aspect_ratio.den = in->video->sample_aspect_ratio.num;
+    }
 
-    if (trans->passthrough)
-        return ff_null_end_frame(inlink);
-
-    for (plane = 0; outpic->data[plane]; plane++) {
+    for (plane = 0; out->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 inh  = in->video->h>>vsub;
+        int outw = out->video->w>>hsub;
+        int outh = out->video->h>>vsub;
+        uint8_t *dst, *src;
+        int dstlinesize, srclinesize;
         int x, y;
 
-        out = outpic->data[plane]; outlinesize = outpic->linesize[plane];
-        in  = inpic ->data[plane]; inlinesize  = inpic ->linesize[plane];
+        dst = out->data[plane];
+        dstlinesize = out->linesize[plane];
+        src = in->data[plane];
+        srclinesize = in->linesize[plane];
 
         if (trans->dir&1) {
-            in +=  inpic->linesize[plane] * (inh-1);
-            inlinesize *= -1;
+            src +=  in->linesize[plane] * (inh-1);
+            srclinesize *= -1;
         }
 
         if (trans->dir&2) {
-            out += outpic->linesize[plane] * (outh-1);
-            outlinesize *= -1;
+            dst += out->linesize[plane] * (outh-1);
+            dstlinesize *= -1;
         }
 
         for (y = 0; y < outh; y++) {
             switch (pixstep) {
             case 1:
                 for (x = 0; x < outw; x++)
-                    out[x] = in[x*inlinesize + y];
+                    dst[x] = src[x*srclinesize + y];
                 break;
             case 2:
                 for (x = 0; x < outw; x++)
-                    *((uint16_t *)(out + 2*x)) = *((uint16_t *)(in + x*inlinesize + y*2));
+                    *((uint16_t *)(dst + 2*x)) = *((uint16_t *)(src + x*srclinesize + 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);
+                    int32_t v = AV_RB24(src + x*srclinesize + y*3);
+                    AV_WB24(dst + 3*x, v);
                 }
                 break;
             case 4:
                 for (x = 0; x < outw; x++)
-                    *((uint32_t *)(out + 4*x)) = *((uint32_t *)(in + x*inlinesize + y*4));
+                    *((uint32_t *)(dst + 4*x)) = *((uint32_t *)(src + x*srclinesize + y*4));
                 break;
             }
-            out += outlinesize;
+            dst += dstlinesize;
         }
     }
 
-    if ((ret = ff_draw_slice(outlink, 0, outpic->video->h, 1)) < 0 ||
-        (ret = ff_end_frame(outlink)) < 0)
-        return ret;
-    return 0;
+    avfilter_unref_bufferp(&in);
+    return ff_filter_frame(outlink, out);
 }
 
-static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
-{
-    TransContext *trans = inlink->dst->priv;
+static const AVFilterPad avfilter_vf_transpose_inputs[] = {
+    {
+        .name        = "default",
+        .type        = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer= get_video_buffer,
+        .filter_frame = filter_frame,
+        .min_perms   = AV_PERM_READ,
+    },
+    { NULL }
+};
 
-    return trans->passthrough ? ff_null_draw_slice(inlink, y, h, slice_dir) : 0;
-}
+static const AVFilterPad avfilter_vf_transpose_outputs[] = {
+    {
+        .name         = "default",
+        .config_props = config_props_output,
+        .type         = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
 
 AVFilter avfilter_vf_transpose = {
     .name      = "transpose",
@@ -250,16 +274,7 @@
 
     .query_formats = query_formats,
 
-    .inputs    = (const AVFilterPad[]) {{ .name            = "default",
-                                          .type            = AVMEDIA_TYPE_VIDEO,
-                                          .get_video_buffer= get_video_buffer,
-                                          .start_frame     = start_frame,
-                                          .draw_slice      = draw_slice,
-                                          .end_frame       = end_frame,
-                                          .min_perms       = AV_PERM_READ, },
-                                        { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name            = "default",
-                                          .config_props    = config_props_output,
-                                          .type            = AVMEDIA_TYPE_VIDEO, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_transpose_inputs,
+    .outputs   = avfilter_vf_transpose_outputs,
+    .priv_class = &transpose_class,
 };
diff --git a/libavfilter/vf_unsharp.c b/libavfilter/vf_unsharp.c
index 13fa108..1e1b009 100644
--- a/libavfilter/vf_unsharp.c
+++ b/libavfilter/vf_unsharp.c
@@ -159,10 +159,10 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    enum PixelFormat pix_fmts[] = {
-        PIX_FMT_YUV420P,  PIX_FMT_YUV422P,  PIX_FMT_YUV444P,  PIX_FMT_YUV410P,
-        PIX_FMT_YUV411P,  PIX_FMT_YUV440P,  PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P,
-        PIX_FMT_YUVJ444P, PIX_FMT_YUVJ440P, PIX_FMT_NONE
+    enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV420P,  AV_PIX_FMT_YUV422P,  AV_PIX_FMT_YUV444P,  AV_PIX_FMT_YUV410P,
+        AV_PIX_FMT_YUV411P,  AV_PIX_FMT_YUV440P,  AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P,
+        AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -187,9 +187,10 @@
 static int config_props(AVFilterLink *link)
 {
     UnsharpContext *unsharp = link->dst->priv;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
 
-    unsharp->hsub = av_pix_fmt_descriptors[link->format].log2_chroma_w;
-    unsharp->vsub = av_pix_fmt_descriptors[link->format].log2_chroma_h;
+    unsharp->hsub = desc->log2_chroma_w;
+    unsharp->vsub = desc->log2_chroma_h;
 
     init_filter_param(link->dst, &unsharp->luma,   "luma",   link->w);
     init_filter_param(link->dst, &unsharp->chroma, "chroma", SHIFTUP(link->w, unsharp->hsub));
@@ -213,29 +214,47 @@
     free_filter_param(&unsharp->chroma);
 }
 
-static int end_frame(AVFilterLink *link)
+static int filter_frame(AVFilterLink *link, AVFilterBufferRef *in)
 {
     UnsharpContext *unsharp = link->dst->priv;
-    AVFilterBufferRef *in  = link->cur_buf;
-    AVFilterBufferRef *out = link->dst->outputs[0]->out_buf;
+    AVFilterLink *outlink   = link->dst->outputs[0];
+    AVFilterBufferRef *out;
     int cw = SHIFTUP(link->w, unsharp->hsub);
     int ch = SHIFTUP(link->h, unsharp->vsub);
-    int ret;
+
+    out = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+    if (!out) {
+        avfilter_unref_bufferp(&in);
+        return AVERROR(ENOMEM);
+    }
+    avfilter_copy_buffer_ref_props(out, in);
 
     apply_unsharp(out->data[0], out->linesize[0], in->data[0], in->linesize[0], link->w, link->h, &unsharp->luma);
     apply_unsharp(out->data[1], out->linesize[1], in->data[1], in->linesize[1], cw,      ch,      &unsharp->chroma);
     apply_unsharp(out->data[2], out->linesize[2], in->data[2], in->linesize[2], cw,      ch,      &unsharp->chroma);
 
-    if ((ret = ff_draw_slice(link->dst->outputs[0], 0, link->h, 1)) < 0 ||
-        (ret = ff_end_frame(link->dst->outputs[0])) < 0)
-        return ret;
-    return 0;
+    avfilter_unref_bufferp(&in);
+    return ff_filter_frame(outlink, out);
 }
 
-static int draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
-{
-    return 0;
-}
+static const AVFilterPad avfilter_vf_unsharp_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .filter_frame = filter_frame,
+        .config_props = config_props,
+        .min_perms    = AV_PERM_READ,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_unsharp_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
 
 AVFilter avfilter_vf_unsharp = {
     .name      = "unsharp",
@@ -247,15 +266,7 @@
     .uninit = uninit,
     .query_formats = query_formats,
 
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .draw_slice       = draw_slice,
-                                          .end_frame        = end_frame,
-                                          .config_props     = config_props,
-                                          .min_perms        = AV_PERM_READ, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_unsharp_inputs,
 
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO, },
-                                        { .name = NULL}},
+    .outputs   = avfilter_vf_unsharp_outputs,
 };
diff --git a/libavfilter/vf_vflip.c b/libavfilter/vf_vflip.c
index 686cd8f..6077789 100644
--- a/libavfilter/vf_vflip.c
+++ b/libavfilter/vf_vflip.c
@@ -36,8 +36,9 @@
 static int config_input(AVFilterLink *link)
 {
     FlipContext *flip = link->dst->priv;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
 
-    flip->vsub = av_pix_fmt_descriptors[link->format].log2_chroma_h;
+    flip->vsub = desc->log2_chroma_h;
 
     return 0;
 }
@@ -68,33 +69,40 @@
     return picref;
 }
 
-static int start_frame(AVFilterLink *link, AVFilterBufferRef *inpicref)
+static int filter_frame(AVFilterLink *link, AVFilterBufferRef *frame)
 {
     FlipContext *flip = link->dst->priv;
-    AVFilterBufferRef *outpicref = avfilter_ref_buffer(inpicref, ~0);
     int i;
 
-    if (!outpicref)
-        return AVERROR(ENOMEM);
-
     for (i = 0; i < 4; i ++) {
         int vsub = i == 1 || i == 2 ? flip->vsub : 0;
 
-        if (outpicref->data[i]) {
-            outpicref->data[i] += (((link->h + (1<<vsub)-1)>> vsub)-1) * outpicref->linesize[i];
-            outpicref->linesize[i] = -outpicref->linesize[i];
+        if (frame->data[i]) {
+            frame->data[i] += (((link->h + (1<<vsub)-1)>> vsub)-1) * frame->linesize[i];
+            frame->linesize[i] = -frame->linesize[i];
         }
     }
 
-    return ff_start_frame(link->dst->outputs[0], outpicref);
+    return ff_filter_frame(link->dst->outputs[0], frame);
 }
+static const AVFilterPad avfilter_vf_vflip_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .get_video_buffer = get_video_buffer,
+        .filter_frame     = filter_frame,
+        .config_props     = config_input,
+    },
+    { NULL }
+};
 
-static int draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
-{
-    AVFilterContext *ctx = link->dst;
-
-    return ff_draw_slice(ctx->outputs[0], link->h - (y+h), h, -1 * slice_dir);
-}
+static const AVFilterPad avfilter_vf_vflip_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
 
 AVFilter avfilter_vf_vflip = {
     .name      = "vflip",
@@ -102,14 +110,6 @@
 
     .priv_size = sizeof(FlipContext),
 
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .get_video_buffer = get_video_buffer,
-                                          .start_frame      = start_frame,
-                                          .draw_slice       = draw_slice,
-                                          .config_props     = config_input, },
-                                        { .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_vflip_inputs,
+    .outputs   = avfilter_vf_vflip_outputs,
 };
diff --git a/libavfilter/vf_yadif.c b/libavfilter/vf_yadif.c
index 7a21eb4..b35f98d 100644
--- a/libavfilter/vf_yadif.c
+++ b/libavfilter/vf_yadif.c
@@ -190,7 +190,7 @@
     }
 
     if (!yadif->csp)
-        yadif->csp = &av_pix_fmt_descriptors[link->format];
+        yadif->csp = av_pix_fmt_desc_get(link->format);
     if (yadif->csp->comp[0].depth_minus1 / 8 == 1)
         yadif->filter_line = (void*)filter_line_c_16bit;
 
@@ -205,19 +205,14 @@
         } else {
             yadif->out->pts = AV_NOPTS_VALUE;
         }
-        ret = ff_start_frame(ctx->outputs[0], yadif->out);
-        if (ret < 0)
-            return ret;
     }
-    if ((ret = ff_draw_slice(ctx->outputs[0], 0, link->h, 1)) < 0 ||
-        (ret = ff_end_frame(ctx->outputs[0])) < 0)
-        return ret;
+    ret = ff_filter_frame(ctx->outputs[0], yadif->out);
 
     yadif->frame_pending = (yadif->mode&1) && !is_second;
-    return 0;
+    return ret;
 }
 
-static int start_frame(AVFilterLink *link, AVFilterBufferRef *picref)
+static int filter_frame(AVFilterLink *link, AVFilterBufferRef *picref)
 {
     AVFilterContext *ctx = link->dst;
     YADIFContext *yadif = ctx->priv;
@@ -237,7 +232,6 @@
     yadif->prev = yadif->cur;
     yadif->cur  = yadif->next;
     yadif->next = picref;
-    link->cur_buf = NULL;
 
     if (!yadif->cur)
         return 0;
@@ -250,7 +244,7 @@
         avfilter_unref_bufferp(&yadif->prev);
         if (yadif->out->pts != AV_NOPTS_VALUE)
             yadif->out->pts *= 2;
-        return ff_start_frame(ctx->outputs[0], yadif->out);
+        return ff_filter_frame(ctx->outputs[0], yadif->out);
     }
 
     if (!yadif->prev &&
@@ -268,26 +262,7 @@
     if (yadif->out->pts != AV_NOPTS_VALUE)
         yadif->out->pts *= 2;
 
-    return ff_start_frame(ctx->outputs[0], yadif->out);
-}
-
-static int end_frame(AVFilterLink *link)
-{
-    AVFilterContext *ctx = link->dst;
-    YADIFContext *yadif = ctx->priv;
-
-    if (!yadif->out)
-        return 0;
-
-    if (yadif->auto_enable && !yadif->cur->video->interlaced) {
-        int ret = ff_draw_slice(ctx->outputs[0], 0, link->h, 1);
-        if (ret >= 0)
-            ret = ff_end_frame(ctx->outputs[0]);
-        return ret;
-    }
-
-    return_frame(ctx, 0);
-    return 0;
+    return return_frame(ctx, 0);
 }
 
 static int request_frame(AVFilterLink *link)
@@ -316,8 +291,7 @@
 
             next->pts = yadif->next->pts * 2 - yadif->cur->pts;
 
-            start_frame(link->src->inputs[0], next);
-            end_frame(link->src->inputs[0]);
+            filter_frame(link->src->inputs[0], next);
             yadif->eof = 1;
         } else if (ret < 0) {
             return ret;
@@ -367,29 +341,29 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
-        PIX_FMT_YUV420P,
-        PIX_FMT_YUV422P,
-        PIX_FMT_YUV444P,
-        PIX_FMT_YUV410P,
-        PIX_FMT_YUV411P,
-        PIX_FMT_GRAY8,
-        PIX_FMT_YUVJ420P,
-        PIX_FMT_YUVJ422P,
-        PIX_FMT_YUVJ444P,
-        AV_NE( PIX_FMT_GRAY16BE, PIX_FMT_GRAY16LE ),
-        PIX_FMT_YUV440P,
-        PIX_FMT_YUVJ440P,
-        AV_NE( PIX_FMT_YUV420P10BE, PIX_FMT_YUV420P10LE ),
-        AV_NE( PIX_FMT_YUV422P10BE, PIX_FMT_YUV422P10LE ),
-        AV_NE( PIX_FMT_YUV444P10BE, PIX_FMT_YUV444P10LE ),
-        AV_NE( PIX_FMT_YUV420P16BE, PIX_FMT_YUV420P16LE ),
-        AV_NE( PIX_FMT_YUV422P16BE, PIX_FMT_YUV422P16LE ),
-        AV_NE( PIX_FMT_YUV444P16BE, PIX_FMT_YUV444P16LE ),
-        PIX_FMT_YUVA420P,
-        PIX_FMT_YUVA422P,
-        PIX_FMT_YUVA444P,
-        PIX_FMT_NONE
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV420P,
+        AV_PIX_FMT_YUV422P,
+        AV_PIX_FMT_YUV444P,
+        AV_PIX_FMT_YUV410P,
+        AV_PIX_FMT_YUV411P,
+        AV_PIX_FMT_GRAY8,
+        AV_PIX_FMT_YUVJ420P,
+        AV_PIX_FMT_YUVJ422P,
+        AV_PIX_FMT_YUVJ444P,
+        AV_NE( AV_PIX_FMT_GRAY16BE, AV_PIX_FMT_GRAY16LE ),
+        AV_PIX_FMT_YUV440P,
+        AV_PIX_FMT_YUVJ440P,
+        AV_NE( AV_PIX_FMT_YUV420P10BE, AV_PIX_FMT_YUV420P10LE ),
+        AV_NE( AV_PIX_FMT_YUV422P10BE, AV_PIX_FMT_YUV422P10LE ),
+        AV_NE( AV_PIX_FMT_YUV444P10BE, AV_PIX_FMT_YUV444P10LE ),
+        AV_NE( AV_PIX_FMT_YUV420P16BE, AV_PIX_FMT_YUV420P16LE ),
+        AV_NE( AV_PIX_FMT_YUV422P16BE, AV_PIX_FMT_YUV422P16LE ),
+        AV_NE( AV_PIX_FMT_YUV444P16BE, AV_PIX_FMT_YUV444P16LE ),
+        AV_PIX_FMT_YUVA420P,
+        AV_PIX_FMT_YUVA422P,
+        AV_PIX_FMT_YUVA444P,
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -412,7 +386,7 @@
 
     yadif->filter_line = filter_line_c;
 
-    if (HAVE_MMX)
+    if (ARCH_X86)
         ff_yadif_init_x86(yadif);
 
     av_log(ctx, AV_LOG_VERBOSE, "mode:%d parity:%d auto_enable:%d\n",
@@ -421,11 +395,6 @@
     return 0;
 }
 
-static int null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
-{
-    return 0;
-}
-
 static int config_props(AVFilterLink *link)
 {
     YADIFContext *yadif = link->src->priv;
@@ -441,6 +410,27 @@
     return 0;
 }
 
+static const AVFilterPad avfilter_vf_yadif_inputs[] = {
+    {
+        .name             = "default",
+        .type             = AVMEDIA_TYPE_VIDEO,
+        .filter_frame     = filter_frame,
+        .min_perms        = AV_PERM_PRESERVE,
+    },
+    { NULL }
+};
+
+static const AVFilterPad avfilter_vf_yadif_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .poll_frame    = poll_frame,
+        .request_frame = request_frame,
+        .config_props  = config_props,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vf_yadif = {
     .name          = "yadif",
     .description   = NULL_IF_CONFIG_SMALL("Deinterlace the input image."),
@@ -450,18 +440,7 @@
     .uninit        = uninit,
     .query_formats = query_formats,
 
-    .inputs    = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .start_frame      = start_frame,
-                                          .draw_slice       = null_draw_slice,
-                                          .end_frame        = end_frame,
-                                          .min_perms        = AV_PERM_PRESERVE, },
-                                        { .name = NULL}},
+    .inputs    = avfilter_vf_yadif_inputs,
 
-    .outputs   = (const AVFilterPad[]) {{ .name             = "default",
-                                          .type             = AVMEDIA_TYPE_VIDEO,
-                                          .poll_frame       = poll_frame,
-                                          .request_frame    = request_frame,
-                                          .config_props     = config_props, },
-                                        { .name = NULL}},
+    .outputs   = avfilter_vf_yadif_outputs,
 };
diff --git a/libavfilter/video.c b/libavfilter/video.c
index d0c95cd..46c4190 100644
--- a/libavfilter/video.c
+++ b/libavfilter/video.c
@@ -94,7 +94,7 @@
 
 AVFilterBufferRef *
 avfilter_get_video_buffer_ref_from_arrays(uint8_t * const data[4], const int linesize[4], int perms,
-                                          int w, int h, enum PixelFormat format)
+                                          int w, int h, enum AVPixelFormat format)
 {
     AVFilterBuffer *pic = av_mallocz(sizeof(AVFilterBuffer));
     AVFilterBufferRef *picref = av_mallocz(sizeof(AVFilterBufferRef));
@@ -210,7 +210,7 @@
     if (inlink->dst->nb_outputs)
         outlink = inlink->dst->outputs[0];
 
-    if (outlink) {
+    if (outlink && (inlink->dstpad->start_frame || inlink->dstpad->end_frame || inlink->dstpad->draw_slice)) {
         AVFilterBufferRef *buf_out;
         outlink->out_buf = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
         if (!outlink->out_buf)
@@ -249,9 +249,11 @@
 
     FF_TPRINTF_START(NULL, start_frame); ff_tlog_link(NULL, link, 0); ff_tlog(NULL, " "); ff_tlog_ref(NULL, picref, 1);
 
-    av_assert1(picref->format                     == link->format);
-    av_assert1(picref->video->w                   == link->w);
-    av_assert1(picref->video->h                   == link->h);
+    if (strcmp(link->dst->filter->name, "scale")) {
+        av_assert1(picref->format                     == link->format);
+        av_assert1(picref->video->w                   == link->w);
+        av_assert1(picref->video->h                   == link->h);
+    }
 
     if (link->closed) {
         avfilter_unref_buffer(picref);
@@ -284,7 +286,7 @@
         avfilter_copy_buffer_ref_props(link->cur_buf, link->src_buf);
 
         /* copy palette if required */
-        if (av_pix_fmt_descriptors[link->format].flags & PIX_FMT_PAL)
+        if (av_pix_fmt_desc_get(link->format)->flags & PIX_FMT_PAL)
             memcpy(link->cur_buf->data[1], link->src_buf-> data[1], AVPALETTE_SIZE);
     }
     else
@@ -326,7 +328,17 @@
         outlink = inlink->dst->outputs[0];
 
     if (outlink) {
-        return ff_end_frame(outlink);
+        if (inlink->dstpad->filter_frame) {
+            int ret = inlink->dstpad->filter_frame(inlink, inlink->cur_buf);
+            inlink->cur_buf = NULL;
+            return ret;
+        } else if (inlink->dstpad->start_frame || inlink->dstpad->end_frame || inlink->dstpad->draw_slice){
+            return ff_end_frame(outlink);
+        } else {
+            int ret = ff_filter_frame(outlink, inlink->cur_buf);
+            inlink->cur_buf = NULL;
+            return ret;
+        }
     }
     return 0;
 }
@@ -358,7 +370,7 @@
     if (inlink->dst->nb_outputs)
         outlink = inlink->dst->outputs[0];
 
-    if (outlink)
+    if (outlink && (inlink->dstpad->start_frame || inlink->dstpad->end_frame || inlink->dstpad->draw_slice))
         return ff_draw_slice(outlink, y, h, slice_dir);
     return 0;
 }
@@ -373,7 +385,8 @@
 
     /* copy the slice if needed for permission reasons */
     if (link->src_buf) {
-        vsub = av_pix_fmt_descriptors[link->format].log2_chroma_h;
+        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
+        vsub = desc->log2_chroma_h;
 
         for (i = 0; i < 4; i++) {
             if (link->src_buf->data[i]) {
diff --git a/libavfilter/vsink_nullsink.c b/libavfilter/vsink_nullsink.c
index 148b250..a37d346 100644
--- a/libavfilter/vsink_nullsink.c
+++ b/libavfilter/vsink_nullsink.c
@@ -20,15 +20,20 @@
 #include "internal.h"
 #include "libavutil/internal.h"
 
-static int start_frame(AVFilterLink *link, AVFilterBufferRef *picref)
+static int filter_frame(AVFilterLink *link, AVFilterBufferRef *frame)
 {
+    avfilter_unref_bufferp(&frame);
     return 0;
 }
 
-static int end_frame(AVFilterLink *link)
-{
-    return 0;
-}
+static const AVFilterPad avfilter_vsink_nullsink_inputs[] = {
+    {
+        .name        = "default",
+        .type        = AVMEDIA_TYPE_VIDEO,
+        .filter_frame = filter_frame,
+    },
+    { NULL },
+};
 
 AVFilter avfilter_vsink_nullsink = {
     .name        = "nullsink",
@@ -36,14 +41,6 @@
 
     .priv_size = 0,
 
-    .inputs    = (const AVFilterPad[]) {
-        {
-            .name            = "default",
-            .type            = AVMEDIA_TYPE_VIDEO,
-            .start_frame     = start_frame,
-            .end_frame       = end_frame,
-        },
-        { .name = NULL},
-    },
+    .inputs    = avfilter_vsink_nullsink_inputs,
     .outputs   = NULL,
 };
diff --git a/libavfilter/vsrc_cellauto.c b/libavfilter/vsrc_cellauto.c
index bfd44a1..06d9f9a 100644
--- a/libavfilter/vsrc_cellauto.c
+++ b/libavfilter/vsrc_cellauto.c
@@ -319,22 +319,28 @@
 #ifdef DEBUG
     show_cellauto_row(outlink->src);
 #endif
-
-    ff_start_frame(outlink, avfilter_ref_buffer(picref, ~0));
-    ff_draw_slice(outlink, 0, cellauto->h, 1);
-    ff_end_frame(outlink);
-    avfilter_unref_buffer(picref);
+    ff_filter_frame(outlink, picref);
 
     return 0;
 }
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = { PIX_FMT_MONOBLACK, PIX_FMT_NONE };
+    static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_NONE };
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
     return 0;
 }
 
+static const AVFilterPad cellauto_outputs[] = {
+    {
+        .name            = "default",
+        .type            = AVMEDIA_TYPE_VIDEO,
+        .request_frame   = request_frame,
+        .config_props    = config_props,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vsrc_cellauto = {
     .name        = "cellauto",
     .description = NULL_IF_CONFIG_SMALL("Create pattern generated by an elementary cellular automaton."),
@@ -342,16 +348,7 @@
     .init      = init,
     .uninit    = uninit,
     .query_formats = query_formats,
-
-    .inputs    = (const AVFilterPad[]) {
-        { .name = NULL}
-    },
-    .outputs   = (const AVFilterPad[]) {
-        { .name            = "default",
-          .type            = AVMEDIA_TYPE_VIDEO,
-          .request_frame   = request_frame,
-          .config_props    = config_props },
-        { .name = NULL}
-    },
-    .priv_class = &cellauto_class,
+    .inputs        = NULL,
+    .outputs       = cellauto_outputs,
+    .priv_class    = &cellauto_class,
 };
diff --git a/libavfilter/vsrc_life.c b/libavfilter/vsrc_life.c
index 344f0ff..d8b8355 100644
--- a/libavfilter/vsrc_life.c
+++ b/libavfilter/vsrc_life.c
@@ -439,11 +439,7 @@
 #ifdef DEBUG
     show_life_grid(outlink->src);
 #endif
-
-    ff_start_frame(outlink, avfilter_ref_buffer(picref, ~0));
-    ff_draw_slice(outlink, 0, life->h, 1);
-    ff_end_frame(outlink);
-    avfilter_unref_buffer(picref);
+    ff_filter_frame(outlink, picref);
 
     return 0;
 }
@@ -451,19 +447,29 @@
 static int query_formats(AVFilterContext *ctx)
 {
     LifeContext *life = ctx->priv;
-    enum PixelFormat pix_fmts[] = { PIX_FMT_NONE, PIX_FMT_NONE };
+    enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_NONE, AV_PIX_FMT_NONE };
     if (life->mold || memcmp(life-> life_color, "\xff\xff\xff", 3)
                    || memcmp(life->death_color, "\x00\x00\x00", 3)) {
-        pix_fmts[0] = PIX_FMT_RGB24;
+        pix_fmts[0] = AV_PIX_FMT_RGB24;
         life->draw = fill_picture_rgb;
     } else {
-        pix_fmts[0] = PIX_FMT_MONOBLACK;
+        pix_fmts[0] = AV_PIX_FMT_MONOBLACK;
         life->draw = fill_picture_monoblack;
     }
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
     return 0;
 }
 
+static const AVFilterPad life_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .request_frame = request_frame,
+        .config_props  = config_props,
+    },
+    { NULL}
+};
+
 AVFilter avfilter_vsrc_life = {
     .name        = "life",
     .description = NULL_IF_CONFIG_SMALL("Create life."),
@@ -471,16 +477,7 @@
     .init      = init,
     .uninit    = uninit,
     .query_formats = query_formats,
-
-    .inputs    = (const AVFilterPad[]) {
-        { .name = NULL}
-    },
-    .outputs   = (const AVFilterPad[]) {
-        { .name            = "default",
-          .type            = AVMEDIA_TYPE_VIDEO,
-          .request_frame   = request_frame,
-          .config_props    = config_props },
-        { .name = NULL}
-    },
-    .priv_class = &life_class,
+    .inputs        = NULL,
+    .outputs       = life_outputs,
+    .priv_class    = &life_class,
 };
diff --git a/libavfilter/vsrc_mandelbrot.c b/libavfilter/vsrc_mandelbrot.c
index 6bed9ce..1244edf 100644
--- a/libavfilter/vsrc_mandelbrot.c
+++ b/libavfilter/vsrc_mandelbrot.c
@@ -153,9 +153,9 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
-        PIX_FMT_BGR32,
-        PIX_FMT_NONE
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_BGR32,
+        AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -346,7 +346,7 @@
                         break;
                 if(j){
                     c= i-j;
-                    c= ((c<<5)&0xE0) + ((c<<16)&0xE000) + ((c<<27)&0xE00000);
+                    c= ((c<<5)&0xE0) + ((c<<10)&0xE000) + ((c<<15)&0xE00000);
                 }
                 }else if(mb->inner==CONVTIME){
                     c= floor(i*255.0/mb->maxiter+dv)*0x010101;
@@ -376,7 +376,7 @@
     FFSWAP(void*, mb->next_cache, mb->point_cache);
     mb->cache_used = next_cidx;
     if(mb->cache_used == mb->cache_allocated)
-        av_log(0, AV_LOG_INFO, "Mandelbrot cache is too small!\n");
+        av_log(ctx, AV_LOG_INFO, "Mandelbrot cache is too small!\n");
 }
 
 static int request_frame(AVFilterLink *link)
@@ -387,15 +387,22 @@
     picref->pts = mb->pts++;
     picref->pos = -1;
 
-    ff_start_frame(link, avfilter_ref_buffer(picref, ~0));
     draw_mandelbrot(link->src, (uint32_t*)picref->data[0], picref->linesize[0]/4, picref->pts);
-    ff_draw_slice(link, 0, mb->h, 1);
-    ff_end_frame(link);
-    avfilter_unref_buffer(picref);
+    ff_filter_frame(link, picref);
 
     return 0;
 }
 
+static const AVFilterPad mandelbrot_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .request_frame = request_frame,
+        .config_props  = config_props,
+    },
+    { NULL },
+};
+
 AVFilter avfilter_vsrc_mandelbrot = {
     .name        = "mandelbrot",
     .description = NULL_IF_CONFIG_SMALL("Render a Mandelbrot fractal."),
@@ -405,12 +412,7 @@
     .uninit    = uninit,
 
     .query_formats = query_formats,
-
-    .inputs    = (const AVFilterPad[]) {{ .name = NULL}},
-
-    .outputs   = (const AVFilterPad[]) {{ .name      = "default",
-                                    .type            = AVMEDIA_TYPE_VIDEO,
-                                    .request_frame   = request_frame,
-                                    .config_props    = config_props },
-                                  { .name = NULL}},
+    .inputs        = NULL,
+    .outputs       = mandelbrot_outputs,
+    .priv_class    = &mandelbrot_class,
 };
diff --git a/libavfilter/vsrc_mptestsrc.c b/libavfilter/vsrc_mptestsrc.c
index febcbc8..d526ee2 100644
--- a/libavfilter/vsrc_mptestsrc.c
+++ b/libavfilter/vsrc_mptestsrc.c
@@ -61,26 +61,26 @@
 } MPTestContext;
 
 #define OFFSET(x) offsetof(MPTestContext, x)
-
+#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
 static const AVOption mptestsrc_options[]= {
-    { "rate",     "set video rate",     OFFSET(rate),     AV_OPT_TYPE_STRING, {.str = "25"},      0, 0 },
-    { "r",        "set video rate",     OFFSET(rate),     AV_OPT_TYPE_STRING, {.str = "25"},      0, 0 },
-    { "duration", "set video duration", OFFSET(duration), AV_OPT_TYPE_STRING, {.str = NULL},      0, 0 },
-    { "d",        "set video duration", OFFSET(duration), AV_OPT_TYPE_STRING, {.str = NULL},      0, 0 },
+    { "rate",     "set video rate",     OFFSET(rate),     AV_OPT_TYPE_STRING, {.str = "25"}, 0, 0, FLAGS },
+    { "r",        "set video rate",     OFFSET(rate),     AV_OPT_TYPE_STRING, {.str = "25"}, 0, 0, FLAGS },
+    { "duration", "set video duration", OFFSET(duration), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
+    { "d",        "set video duration", OFFSET(duration), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
 
-    { "test", "set test to perform", OFFSET(test),  AV_OPT_TYPE_INT,   {.i64=TEST_ALL}, 0, INT_MAX, 0, "test" },
-    { "t",    "set test to perform", OFFSET(test),  AV_OPT_TYPE_INT,   {.i64=TEST_ALL}, 0, INT_MAX, 0, "test" },
-    { "dc_luma",     "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_DC_LUMA},     INT_MIN, INT_MAX, 0, "test" },
-    { "dc_chroma",   "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_DC_CHROMA},   INT_MIN, INT_MAX, 0, "test" },
-    { "freq_luma",   "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_FREQ_LUMA},   INT_MIN, INT_MAX, 0, "test" },
-    { "freq_chroma", "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_FREQ_CHROMA}, INT_MIN, INT_MAX, 0, "test" },
-    { "amp_luma",    "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_AMP_LUMA},    INT_MIN, INT_MAX, 0, "test" },
-    { "amp_chroma",  "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_AMP_CHROMA},  INT_MIN, INT_MAX, 0, "test" },
-    { "cbp",         "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_CBP},         INT_MIN, INT_MAX, 0, "test" },
-    { "mv",          "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_MV},          INT_MIN, INT_MAX, 0, "test" },
-    { "ring1",       "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_RING1},       INT_MIN, INT_MAX, 0, "test" },
-    { "ring2",       "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_RING2},       INT_MIN, INT_MAX, 0, "test" },
-    { "all",         "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_ALL},         INT_MIN, INT_MAX, 0, "test" },
+    { "test", "set test to perform", OFFSET(test),  AV_OPT_TYPE_INT,   {.i64=TEST_ALL}, 0, INT_MAX, FLAGS, "test" },
+    { "t",    "set test to perform", OFFSET(test),  AV_OPT_TYPE_INT,   {.i64=TEST_ALL}, 0, INT_MAX, FLAGS, "test" },
+    { "dc_luma",     "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_DC_LUMA},     INT_MIN, INT_MAX, FLAGS, "test" },
+    { "dc_chroma",   "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_DC_CHROMA},   INT_MIN, INT_MAX, FLAGS, "test" },
+    { "freq_luma",   "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_FREQ_LUMA},   INT_MIN, INT_MAX, FLAGS, "test" },
+    { "freq_chroma", "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_FREQ_CHROMA}, INT_MIN, INT_MAX, FLAGS, "test" },
+    { "amp_luma",    "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_AMP_LUMA},    INT_MIN, INT_MAX, FLAGS, "test" },
+    { "amp_chroma",  "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_AMP_CHROMA},  INT_MIN, INT_MAX, FLAGS, "test" },
+    { "cbp",         "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_CBP},         INT_MIN, INT_MAX, FLAGS, "test" },
+    { "mv",          "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_MV},          INT_MIN, INT_MAX, FLAGS, "test" },
+    { "ring1",       "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_RING1},       INT_MIN, INT_MAX, FLAGS, "test" },
+    { "ring2",       "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_RING2},       INT_MIN, INT_MAX, FLAGS, "test" },
+    { "all",         "", 0, AV_OPT_TYPE_CONST, {.i64=TEST_ALL},         INT_MIN, INT_MAX, FLAGS, "test" },
 
     { NULL },
 };
@@ -298,7 +298,7 @@
 {
     AVFilterContext *ctx = outlink->src;
     MPTestContext *test = ctx->priv;
-    const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[outlink->format];
+    const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(outlink->format);
 
     test->hsub = pix_desc->log2_chroma_w;
     test->vsub = pix_desc->log2_chroma_h;
@@ -312,8 +312,8 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
-        PIX_FMT_YUV420P, PIX_FMT_NONE
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE
     };
 
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
@@ -355,15 +355,21 @@
     }
 
     test->frame_nb++;
-
-    ff_start_frame(outlink, avfilter_ref_buffer(picref, ~0));
-    ff_draw_slice(outlink, 0, picref->video->h, 1);
-    ff_end_frame(outlink);
-    avfilter_unref_buffer(picref);
+    ff_filter_frame(outlink, picref);
 
     return 0;
 }
 
+static const AVFilterPad mptestsrc_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .request_frame = request_frame,
+        .config_props  = config_props,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vsrc_mptestsrc = {
     .name      = "mptestsrc",
     .description = NULL_IF_CONFIG_SMALL("Generate various test pattern."),
@@ -372,11 +378,7 @@
 
     .query_formats   = query_formats,
 
-    .inputs    = (const AVFilterPad[]) {{ .name = NULL}},
-
-    .outputs   = (const AVFilterPad[]) {{ .name = "default",
-                                    .type = AVMEDIA_TYPE_VIDEO,
-                                    .request_frame = request_frame,
-                                    .config_props  = config_props, },
-                                  { .name = NULL }},
+    .inputs         = NULL,
+    .outputs        = mptestsrc_outputs,
+    .priv_class     = &mptestsrc_class,
 };
diff --git a/libavfilter/vsrc_testsrc.c b/libavfilter/vsrc_testsrc.c
index 85d3789..185d382 100644
--- a/libavfilter/vsrc_testsrc.c
+++ b/libavfilter/vsrc_testsrc.c
@@ -170,7 +170,6 @@
 {
     TestSourceContext *test = outlink->src->priv;
     AVFilterBufferRef *outpicref;
-    int ret = 0;
 
     if (test->duration >= 0 &&
         av_rescale_q(test->pts, test->time_base, AV_TIME_BASE_Q) >= test->duration)
@@ -203,12 +202,7 @@
     test->pts++;
     test->nb_frame++;
 
-    if ((ret = ff_start_frame(outlink, outpicref)) < 0 ||
-        (ret = ff_draw_slice(outlink, 0, test->h, 1)) < 0 ||
-        (ret = ff_end_frame(outlink)) < 0)
-        return ret;
-
-    return 0;
+    return ff_filter_frame(outlink, outpicref);
 }
 
 #if CONFIG_COLOR_FILTER
@@ -262,6 +256,16 @@
     return 0;
 }
 
+static const AVFilterPad color_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .request_frame = request_frame,
+        .config_props  = color_config_props,
+    },
+    {  NULL }
+};
+
 AVFilter avfilter_vsrc_color = {
     .name        = "color",
     .description = NULL_IF_CONFIG_SMALL("Provide an uniformly colored input."),
@@ -271,22 +275,9 @@
     .uninit    = uninit,
 
     .query_formats = color_query_formats,
-
-    .inputs = (const AVFilterPad[]) {
-        { .name = NULL }
-    },
-
-    .outputs = (const AVFilterPad[]) {
-        {
-            .name            = "default",
-            .type            = AVMEDIA_TYPE_VIDEO,
-            .request_frame   = request_frame,
-            .config_props    = color_config_props,
-        },
-        { .name = NULL }
-    },
-
-    .priv_class = &color_class,
+    .inputs        = NULL,
+    .outputs       = color_outputs,
+    .priv_class    = &color_class,
 };
 
 #endif /* CONFIG_COLOR_FILTER */
@@ -307,19 +298,24 @@
     return init(ctx, args);
 }
 
+static const AVFilterPad nullsrc_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .request_frame = request_frame,
+        .config_props  = config_props,
+    },
+    { NULL },
+};
+
 AVFilter avfilter_vsrc_nullsrc = {
     .name        = "nullsrc",
     .description = NULL_IF_CONFIG_SMALL("Null video source, return unprocessed video frames."),
     .init       = nullsrc_init,
     .uninit     = uninit,
     .priv_size  = sizeof(TestSourceContext),
-
-    .inputs    = (const AVFilterPad[]) {{ .name = NULL}},
-    .outputs   = (const AVFilterPad[]) {{ .name = "default",
-                                    .type = AVMEDIA_TYPE_VIDEO,
-                                    .request_frame = request_frame,
-                                    .config_props  = config_props, },
-                                  { .name = NULL}},
+    .inputs     = NULL,
+    .outputs    = nullsrc_outputs,
     .priv_class = &nullsrc_class,
 };
 
@@ -518,13 +514,23 @@
 
 static int test_query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
-        PIX_FMT_RGB24, PIX_FMT_NONE
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_RGB24, AV_PIX_FMT_NONE
     };
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
     return 0;
 }
 
+static const AVFilterPad avfilter_vsrc_testsrc_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .request_frame = request_frame,
+        .config_props  = config_props,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vsrc_testsrc = {
     .name      = "testsrc",
     .description = NULL_IF_CONFIG_SMALL("Generate test pattern."),
@@ -535,12 +541,7 @@
     .query_formats   = test_query_formats,
 
     .inputs    = NULL,
-
-    .outputs   = (const AVFilterPad[]) {{ .name = "default",
-                                          .type = AVMEDIA_TYPE_VIDEO,
-                                          .request_frame = request_frame,
-                                          .config_props  = config_props, },
-                                        { .name = NULL }},
+    .outputs   = avfilter_vsrc_testsrc_outputs,
     .priv_class = &testsrc_class,
 };
 
@@ -557,29 +558,29 @@
 #define A 3
 
 static void rgbtest_put_pixel(uint8_t *dst, int dst_linesize,
-                              int x, int y, int r, int g, int b, enum PixelFormat fmt,
+                              int x, int y, int r, int g, int b, enum AVPixelFormat fmt,
                               uint8_t rgba_map[4])
 {
     int32_t v;
     uint8_t *p;
 
     switch (fmt) {
-    case PIX_FMT_BGR444: ((uint16_t*)(dst + y*dst_linesize))[x] = ((r >> 4) << 8) | ((g >> 4) << 4) | (b >> 4); break;
-    case PIX_FMT_RGB444: ((uint16_t*)(dst + y*dst_linesize))[x] = ((b >> 4) << 8) | ((g >> 4) << 4) | (r >> 4); break;
-    case PIX_FMT_BGR555: ((uint16_t*)(dst + y*dst_linesize))[x] = ((r>>3)<<10) | ((g>>3)<<5) | (b>>3); break;
-    case PIX_FMT_RGB555: ((uint16_t*)(dst + y*dst_linesize))[x] = ((b>>3)<<10) | ((g>>3)<<5) | (r>>3); break;
-    case PIX_FMT_BGR565: ((uint16_t*)(dst + y*dst_linesize))[x] = ((r>>3)<<11) | ((g>>2)<<5) | (b>>3); break;
-    case PIX_FMT_RGB565: ((uint16_t*)(dst + y*dst_linesize))[x] = ((b>>3)<<11) | ((g>>2)<<5) | (r>>3); break;
-    case PIX_FMT_RGB24:
-    case PIX_FMT_BGR24:
+    case AV_PIX_FMT_BGR444: ((uint16_t*)(dst + y*dst_linesize))[x] = ((r >> 4) << 8) | ((g >> 4) << 4) | (b >> 4); break;
+    case AV_PIX_FMT_RGB444: ((uint16_t*)(dst + y*dst_linesize))[x] = ((b >> 4) << 8) | ((g >> 4) << 4) | (r >> 4); break;
+    case AV_PIX_FMT_BGR555: ((uint16_t*)(dst + y*dst_linesize))[x] = ((r>>3)<<10) | ((g>>3)<<5) | (b>>3); break;
+    case AV_PIX_FMT_RGB555: ((uint16_t*)(dst + y*dst_linesize))[x] = ((b>>3)<<10) | ((g>>3)<<5) | (r>>3); break;
+    case AV_PIX_FMT_BGR565: ((uint16_t*)(dst + y*dst_linesize))[x] = ((r>>3)<<11) | ((g>>2)<<5) | (b>>3); break;
+    case AV_PIX_FMT_RGB565: ((uint16_t*)(dst + y*dst_linesize))[x] = ((b>>3)<<11) | ((g>>2)<<5) | (r>>3); break;
+    case AV_PIX_FMT_RGB24:
+    case AV_PIX_FMT_BGR24:
         v = (r << (rgba_map[R]*8)) + (g << (rgba_map[G]*8)) + (b << (rgba_map[B]*8));
         p = dst + 3*x + y*dst_linesize;
         AV_WL24(p, v);
         break;
-    case PIX_FMT_RGBA:
-    case PIX_FMT_BGRA:
-    case PIX_FMT_ARGB:
-    case PIX_FMT_ABGR:
+    case AV_PIX_FMT_RGBA:
+    case AV_PIX_FMT_BGRA:
+    case AV_PIX_FMT_ARGB:
+    case AV_PIX_FMT_ABGR:
         v = (r << (rgba_map[R]*8)) + (g << (rgba_map[G]*8)) + (b << (rgba_map[B]*8)) + (255 << (rgba_map[A]*8));
         p = dst + 4*x + y*dst_linesize;
         AV_WL32(p, v);
@@ -619,13 +620,13 @@
 
 static int rgbtest_query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
-        PIX_FMT_RGBA, PIX_FMT_ARGB, PIX_FMT_BGRA, PIX_FMT_ABGR,
-        PIX_FMT_BGR24, PIX_FMT_RGB24,
-        PIX_FMT_RGB444, PIX_FMT_BGR444,
-        PIX_FMT_RGB565, PIX_FMT_BGR565,
-        PIX_FMT_RGB555, PIX_FMT_BGR555,
-        PIX_FMT_NONE
+    static const enum AVPixelFormat pix_fmts[] = {
+        AV_PIX_FMT_RGBA, AV_PIX_FMT_ARGB, AV_PIX_FMT_BGRA, AV_PIX_FMT_ABGR,
+        AV_PIX_FMT_BGR24, AV_PIX_FMT_RGB24,
+        AV_PIX_FMT_RGB444, AV_PIX_FMT_BGR444,
+        AV_PIX_FMT_RGB565, AV_PIX_FMT_BGR565,
+        AV_PIX_FMT_RGB555, AV_PIX_FMT_BGR555,
+        AV_PIX_FMT_NONE
     };
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
     return 0;
@@ -639,6 +640,16 @@
     return config_props(outlink);
 }
 
+static const AVFilterPad avfilter_vsrc_rgbtestsrc_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .request_frame = request_frame,
+        .config_props  = rgbtest_config_props,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vsrc_rgbtestsrc = {
     .name      = "rgbtestsrc",
     .description = NULL_IF_CONFIG_SMALL("Generate RGB test pattern."),
@@ -650,11 +661,7 @@
 
     .inputs    = NULL,
 
-    .outputs   = (const AVFilterPad[]) {{ .name = "default",
-                                          .type = AVMEDIA_TYPE_VIDEO,
-                                          .request_frame = request_frame,
-                                          .config_props  = rgbtest_config_props, },
-                                        { .name = NULL }},
+    .outputs   = avfilter_vsrc_rgbtestsrc_outputs,
     .priv_class = &rgbtestsrc_class,
 };
 
@@ -762,6 +769,16 @@
     return config_props(outlink);
 }
 
+static const AVFilterPad smptebars_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .request_frame = request_frame,
+        .config_props  = smptebars_config_props,
+    },
+    { NULL }
+};
+
 AVFilter avfilter_vsrc_smptebars = {
     .name      = "smptebars",
     .description = NULL_IF_CONFIG_SMALL("Generate SMPTE color bars."),
@@ -770,22 +787,9 @@
     .uninit    = uninit,
 
     .query_formats = smptebars_query_formats,
-
-    .inputs = (const AVFilterPad[]) {
-        { .name = NULL }
-    },
-
-    .outputs = (const AVFilterPad[]) {
-        {
-            .name = "default",
-            .type = AVMEDIA_TYPE_VIDEO,
-            .request_frame = request_frame,
-            .config_props  = smptebars_config_props,
-        },
-        { .name = NULL }
-    },
-
-    .priv_class = &smptebars_class,
+    .inputs        = NULL,
+    .outputs       = smptebars_outputs,
+    .priv_class    = &smptebars_class,
 };
 
 #endif  /* CONFIG_SMPTEBARS_FILTER */
diff --git a/libavfilter/x86/Makefile b/libavfilter/x86/Makefile
index 46fc84f..4289f92 100644
--- a/libavfilter/x86/Makefile
+++ b/libavfilter/x86/Makefile
@@ -1,3 +1,4 @@
-MMX-OBJS-$(CONFIG_YADIF_FILTER)              += x86/yadif.o
-MMX-OBJS-$(CONFIG_GRADFUN_FILTER)            += x86/gradfun.o
+OBJS-$(CONFIG_GRADFUN_FILTER)                += x86/gradfun.o
+OBJS-$(CONFIG_YADIF_FILTER)                  += x86/yadif.o
+
 YASM-OBJS-$(CONFIG_HQDN3D_FILTER)            += x86/hqdn3d.o
diff --git a/libavfilter/x86/gradfun.c b/libavfilter/x86/gradfun.c
index 6faf7d1..5e71aab 100644
--- a/libavfilter/x86/gradfun.c
+++ b/libavfilter/x86/gradfun.c
@@ -30,7 +30,9 @@
 DECLARE_ALIGNED(16, static const uint16_t, pw_ff)[8] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
 
 #if HAVE_MMXEXT_INLINE
-static void gradfun_filter_line_mmx2(uint8_t *dst, const uint8_t *src, const uint16_t *dc, int width, int thresh, const uint16_t *dithers)
+static void gradfun_filter_line_mmxext(uint8_t *dst, const uint8_t *src, const uint16_t *dc,
+                                       int width, int thresh,
+                                       const uint16_t *dithers)
 {
     intptr_t x;
     if (width & 3) {
@@ -175,7 +177,7 @@
 
 #if HAVE_MMXEXT_INLINE
     if (cpu_flags & AV_CPU_FLAG_MMXEXT)
-        gf->filter_line = gradfun_filter_line_mmx2;
+        gf->filter_line = gradfun_filter_line_mmxext;
 #endif
 #if HAVE_SSSE3_INLINE
     if (cpu_flags & AV_CPU_FLAG_SSSE3)
diff --git a/libavfilter/x86/hqdn3d.asm b/libavfilter/x86/hqdn3d.asm
index d36ce37..961127e 100644
--- a/libavfilter/x86/hqdn3d.asm
+++ b/libavfilter/x86/hqdn3d.asm
@@ -18,7 +18,7 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "x86inc.asm"
+%include "libavutil/x86/x86util.asm"
 
 SECTION .text
 
diff --git a/libavfilter/x86/yadif.c b/libavfilter/x86/yadif.c
index 881be5a..b48a3d6 100644
--- a/libavfilter/x86/yadif.c
+++ b/libavfilter/x86/yadif.c
@@ -48,7 +48,7 @@
 
 #if HAVE_MMXEXT_INLINE
 #undef RENAME
-#define RENAME(a) a ## _mmx2
+#define RENAME(a) a ## _mmxext
 #include "yadif_template.c"
 #endif
 
@@ -60,7 +60,7 @@
 
 #if HAVE_MMXEXT_INLINE
     if (cpu_flags & AV_CPU_FLAG_MMXEXT)
-        yadif->filter_line = yadif_filter_line_mmx2;
+        yadif->filter_line = yadif_filter_line_mmxext;
 #endif
 #if HAVE_SSE2_INLINE
     if (cpu_flags & AV_CPU_FLAG_SSE2)
diff --git a/libavfilter/yadif.h b/libavfilter/yadif.h
index 45bb1dc..41691de 100644
--- a/libavfilter/yadif.h
+++ b/libavfilter/yadif.h
@@ -22,7 +22,7 @@
 #include "libavutil/pixdesc.h"
 #include "avfilter.h"
 
-typedef struct {
+typedef struct YADIFContext {
     /**
      * 0: send 1 frame for each frame
      * 1: send 1 frame for each field
diff --git a/libavformat/4xm.c b/libavformat/4xm.c
index 0a003d4..1e142f5 100644
--- a/libavformat/4xm.c
+++ b/libavformat/4xm.c
@@ -134,6 +134,10 @@
         }
 
         if (fourcc_tag == std__TAG) {
+            if (header_size < i + 16) {
+                av_log(s, AV_LOG_ERROR, "std TAG truncated\n");
+                return AVERROR_INVALIDDATA;
+            }
             fourxm->fps = av_int2float(AV_RL32(&header[i + 12]));
         } else if (fourcc_tag == vtrk_TAG) {
             /* check that there is enough data */
diff --git a/libavformat/Makefile b/libavformat/Makefile
index 92adfcd..daa406f 100644
--- a/libavformat/Makefile
+++ b/libavformat/Makefile
@@ -13,7 +13,9 @@
        cutils.o             \
        id3v1.o              \
        id3v2.o              \
+       log2_tab.o           \
        metadata.o           \
+       mux.o                \
        options.o            \
        os_support.o         \
        riff.o               \
@@ -25,7 +27,7 @@
 OBJS-$(CONFIG_NETWORK)                   += network.o
 
 # muxers/demuxers
-OBJS-$(CONFIG_A64_MUXER)                 += a64.o
+OBJS-$(CONFIG_A64_MUXER)                 += a64.o rawenc.o
 OBJS-$(CONFIG_AAC_DEMUXER)               += aacdec.o rawdec.o
 OBJS-$(CONFIG_AC3_DEMUXER)               += ac3dec.o rawdec.o
 OBJS-$(CONFIG_AC3_MUXER)                 += rawenc.o
@@ -35,6 +37,7 @@
 OBJS-$(CONFIG_ADX_MUXER)                 += rawenc.o
 OBJS-$(CONFIG_ADTS_MUXER)                += adtsenc.o
 OBJS-$(CONFIG_AEA_DEMUXER)               += aea.o pcm.o
+OBJS-$(CONFIG_AFC_DEMUXER)               += afc.o
 OBJS-$(CONFIG_AIFF_DEMUXER)              += aiffdec.o pcm.o isom.o \
                                             mov_chan.o
 OBJS-$(CONFIG_AIFF_MUXER)                += aiffenc.o isom.o
@@ -48,12 +51,14 @@
 OBJS-$(CONFIG_ASF_MUXER)                 += asfenc.o asf.o
 OBJS-$(CONFIG_ASS_DEMUXER)               += assdec.o
 OBJS-$(CONFIG_ASS_MUXER)                 += assenc.o
+OBJS-$(CONFIG_AST_DEMUXER)               += ast.o
 OBJS-$(CONFIG_AU_DEMUXER)                += au.o pcm.o
 OBJS-$(CONFIG_AU_MUXER)                  += au.o
 OBJS-$(CONFIG_AVI_DEMUXER)               += avidec.o
 OBJS-$(CONFIG_AVI_MUXER)                 += avienc.o
 OBJS-$(CONFIG_AVISYNTH)                  += avisynth.o
 OBJS-$(CONFIG_AVM2_MUXER)                += swfenc.o swf.o
+OBJS-$(CONFIG_AVR_DEMUXER)               += avr.o rawdec.o pcm.o
 OBJS-$(CONFIG_AVS_DEMUXER)               += avs.o vocdec.o voc.o
 OBJS-$(CONFIG_BETHSOFTVID_DEMUXER)       += bethsoftvid.o
 OBJS-$(CONFIG_BFI_DEMUXER)               += bfi.o
@@ -62,6 +67,7 @@
 OBJS-$(CONFIG_BIT_DEMUXER)               += bit.o
 OBJS-$(CONFIG_BIT_MUXER)                 += bit.o
 OBJS-$(CONFIG_BMV_DEMUXER)               += bmv.o
+OBJS-$(CONFIG_BRSTM_DEMUXER)             += brstm.o
 OBJS-$(CONFIG_C93_DEMUXER)               += c93.o vocdec.o voc.o
 OBJS-$(CONFIG_CAF_DEMUXER)               += cafdec.o caf.o mov.o mov_chan.o \
                                             isom.o
@@ -79,6 +85,7 @@
 OBJS-$(CONFIG_DNXHD_DEMUXER)             += dnxhddec.o rawdec.o
 OBJS-$(CONFIG_DNXHD_MUXER)               += rawenc.o
 OBJS-$(CONFIG_DSICIN_DEMUXER)            += dsicin.o
+OBJS-$(CONFIG_DTSHD_DEMUXER)             += dtshddec.o
 OBJS-$(CONFIG_DTS_DEMUXER)               += dtsdec.o rawdec.o
 OBJS-$(CONFIG_DTS_MUXER)                 += rawenc.o
 OBJS-$(CONFIG_DV_DEMUXER)                += dv.o
@@ -106,10 +113,11 @@
 OBJS-$(CONFIG_FRAMECRC_MUXER)            += framecrcenc.o framehash.o
 OBJS-$(CONFIG_FRAMEMD5_MUXER)            += md5enc.o framehash.o
 OBJS-$(CONFIG_GIF_MUXER)                 += gif.o
+OBJS-$(CONFIG_GIF_DEMUXER)               += gifdec.o
 OBJS-$(CONFIG_GSM_DEMUXER)               += gsmdec.o
 OBJS-$(CONFIG_GXF_DEMUXER)               += gxf.o
 OBJS-$(CONFIG_GXF_MUXER)                 += gxfenc.o audiointerleave.o
-OBJS-$(CONFIG_G722_DEMUXER)              += rawdec.o
+OBJS-$(CONFIG_G722_DEMUXER)              += g722.o rawdec.o
 OBJS-$(CONFIG_G722_MUXER)                += rawenc.o
 OBJS-$(CONFIG_G723_1_DEMUXER)            += g723_1.o
 OBJS-$(CONFIG_G723_1_MUXER)              += rawenc.o
@@ -121,6 +129,7 @@
 OBJS-$(CONFIG_H264_DEMUXER)              += h264dec.o rawdec.o
 OBJS-$(CONFIG_H264_MUXER)                += rawenc.o
 OBJS-$(CONFIG_HLS_DEMUXER)               += hls.o
+OBJS-$(CONFIG_HLS_MUXER)                 += hlsenc.o mpegtsenc.o
 OBJS-$(CONFIG_ICO_DEMUXER)               += icodec.o
 OBJS-$(CONFIG_ICO_MUXER)                 += icoenc.o
 OBJS-$(CONFIG_IDCIN_DEMUXER)             += idcin.o
@@ -134,9 +143,6 @@
 OBJS-$(CONFIG_IMAGE2PIPE_MUXER)          += img2enc.o img2.o
 OBJS-$(CONFIG_INGENIENT_DEMUXER)         += ingenientdec.o rawdec.o
 OBJS-$(CONFIG_IPMOVIE_DEMUXER)           += ipmovie.o
-OBJS-$(CONFIG_ISMV_MUXER)                += movenc.o isom.o avc.o       \
-                                            movenchint.o rtpenc_chain.o \
-                                            mov_chan.o
 OBJS-$(CONFIG_ISS_DEMUXER)               += iss.o
 OBJS-$(CONFIG_IV8_DEMUXER)               += iv8.o
 OBJS-$(CONFIG_IVF_DEMUXER)               += ivfdec.o
@@ -148,11 +154,12 @@
 OBJS-$(CONFIG_LATM_MUXER)                += latmenc.o rawenc.o
 OBJS-$(CONFIG_LMLM4_DEMUXER)             += lmlm4.o
 OBJS-$(CONFIG_LOAS_DEMUXER)              += loasdec.o
+OBJS-$(CONFIG_LVF_DEMUXER)               += lvfdec.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 \
-                                            isom.o rmdec.o rm.o
+OBJS-$(CONFIG_MATROSKA_DEMUXER)          += matroskadec.o matroska.o  \
+                                            isom.o rmsipr.o
 OBJS-$(CONFIG_MATROSKA_MUXER)            += matroskaenc.o matroska.o \
                                             isom.o avc.o \
                                             flacenc_header.o avlanguage.o
@@ -216,55 +223,56 @@
 OBJS-$(CONFIG_OMA_DEMUXER)               += omadec.o pcm.o oma.o
 OBJS-$(CONFIG_OMA_MUXER)                 += omaenc.o rawenc.o oma.o id3v2enc.o
 OBJS-$(CONFIG_PAF_DEMUXER)               += paf.o
-OBJS-$(CONFIG_PCM_ALAW_DEMUXER)          += pcmdec.o pcm.o rawdec.o
+OBJS-$(CONFIG_PCM_ALAW_DEMUXER)          += pcmdec.o pcm.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_DEMUXER)         += pcmdec.o pcm.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_DEMUXER)         += pcmdec.o pcm.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_DEMUXER)         += pcmdec.o pcm.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_DEMUXER)         += pcmdec.o pcm.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_DEMUXER)         += pcmdec.o pcm.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_DEMUXER)         += pcmdec.o pcm.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_DEMUXER)         += pcmdec.o pcm.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_DEMUXER)         += pcmdec.o pcm.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_DEMUXER)         += pcmdec.o pcm.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_DEMUXER)         += pcmdec.o pcm.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_DEMUXER)         += pcmdec.o pcm.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_DEMUXER)            += pcmdec.o pcm.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_DEMUXER)         += pcmdec.o pcm.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_DEMUXER)         += pcmdec.o pcm.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_DEMUXER)         += pcmdec.o pcm.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_DEMUXER)         += pcmdec.o pcm.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_DEMUXER)         += pcmdec.o pcm.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_DEMUXER)         += pcmdec.o pcm.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_DEMUXER)            += pcmdec.o pcm.o
 OBJS-$(CONFIG_PCM_U8_MUXER)              += pcmenc.o rawenc.o
 OBJS-$(CONFIG_PMP_DEMUXER)               += pmpdec.o
 OBJS-$(CONFIG_PVA_DEMUXER)               += pva.o
+OBJS-$(CONFIG_PVF_DEMUXER)               += pvfdec.o pcm.o
 OBJS-$(CONFIG_QCP_DEMUXER)               += qcp.o
 OBJS-$(CONFIG_R3D_DEMUXER)               += r3d.o
-OBJS-$(CONFIG_RAWVIDEO_DEMUXER)          += rawvideodec.o rawdec.o
+OBJS-$(CONFIG_RAWVIDEO_DEMUXER)          += rawvideodec.o
 OBJS-$(CONFIG_RAWVIDEO_MUXER)            += rawenc.o
 OBJS-$(CONFIG_REALTEXT_DEMUXER)          += realtextdec.o
 OBJS-$(CONFIG_RL2_DEMUXER)               += rl2.o
-OBJS-$(CONFIG_RM_DEMUXER)                += rmdec.o rm.o
+OBJS-$(CONFIG_RM_DEMUXER)                += rmdec.o rm.o rmsipr.o
 OBJS-$(CONFIG_RM_MUXER)                  += rmenc.o rm.o
 OBJS-$(CONFIG_ROQ_DEMUXER)               += idroqdec.o
 OBJS-$(CONFIG_ROQ_MUXER)                 += idroqenc.o rawenc.o
@@ -332,6 +340,7 @@
 OBJS-$(CONFIG_SUBVIEWER_DEMUXER)         += subviewerdec.o
 OBJS-$(CONFIG_SWF_DEMUXER)               += swfdec.o swf.o
 OBJS-$(CONFIG_SWF_MUXER)                 += swfenc.o swf.o
+OBJS-$(CONFIG_TAK_DEMUXER)               += takdec.o apetag.o img2.o rawdec.o
 OBJS-$(CONFIG_THP_DEMUXER)               += thp.o
 OBJS-$(CONFIG_TIERTEXSEQ_DEMUXER)        += tiertexseq.o
 OBJS-$(CONFIG_MKVTIMESTAMP_V2_MUXER)     += mkvtimestamp_v2.o
@@ -344,13 +353,14 @@
 OBJS-$(CONFIG_VC1_DEMUXER)               += rawdec.o
 OBJS-$(CONFIG_VC1T_DEMUXER)              += vc1test.o
 OBJS-$(CONFIG_VC1T_MUXER)                += vc1testenc.o
+OBJS-$(CONFIG_VIVO_DEMUXER)              += vivo.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 pcm.o
-OBJS-$(CONFIG_WAV_DEMUXER)               += wav.o pcm.o
-OBJS-$(CONFIG_WAV_MUXER)                 += wav.o
+OBJS-$(CONFIG_W64_DEMUXER)               += wavdec.o pcm.o
+OBJS-$(CONFIG_WAV_DEMUXER)               += wavdec.o pcm.o
+OBJS-$(CONFIG_WAV_MUXER)                 += wavenc.o
 OBJS-$(CONFIG_WC3_DEMUXER)               += wc3movie.o
 OBJS-$(CONFIG_WEBM_MUXER)                += matroskaenc.o matroska.o \
                                             isom.o avc.o \
@@ -409,7 +419,8 @@
 
 SKIPHEADERS-$(CONFIG_FFRTMPCRYPT_PROTOCOL) += rtmpdh.h
 SKIPHEADERS-$(CONFIG_NETWORK)            += network.h rtsp.h
-TESTPROGS = seek
+TESTPROGS = seek                                                        \
+            url                                                         \
 
 TOOLS     = aviocat                                                     \
             ismindex                                                    \
diff --git a/libavformat/a64.c b/libavformat/a64.c
index c1f6b67..c672fb6 100644
--- a/libavformat/a64.c
+++ b/libavformat/a64.c
@@ -23,17 +23,11 @@
 #include "libavcodec/a64enc.h"
 #include "libavcodec/bytestream.h"
 #include "avformat.h"
-
-typedef struct A64MuxerContext {
-    int interleaved;
-    AVPacket prev_pkt;
-    int prev_frame_count;
-} A64MuxerContext;
+#include "rawenc.h"
 
 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
@@ -41,7 +35,6 @@
         0x00, //charset_lifetime (multi only)
         0x00  //fps in 50/fps;
     };
-    c->interleaved = 0;
     switch (avctx->codec->id) {
     case AV_CODEC_ID_A64_MULTI:
         header[2] = 0x00;
@@ -57,109 +50,6 @@
         return AVERROR(EINVAL);
     }
     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 AV_CODEC_ID_A64_MULTI:
-    case AV_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;
 }
 
@@ -167,9 +57,7 @@
     .name           = "a64",
     .long_name      = NULL_IF_CONFIG_SMALL("a64 - video for Commodore 64"),
     .extensions     = "a64, A64",
-    .priv_data_size = sizeof (A64Context),
     .video_codec    = AV_CODEC_ID_A64_MULTI,
     .write_header   = a64_write_header,
-    .write_packet   = a64_write_packet,
-    .write_trailer  = a64_write_trailer,
+    .write_packet   = ff_raw_write_packet,
 };
diff --git a/libavformat/aea.c b/libavformat/aea.c
index 6aa7ae3..15b9b1c 100644
--- a/libavformat/aea.c
+++ b/libavformat/aea.c
@@ -20,10 +20,10 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
+#include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "pcm.h"
-#include "libavutil/intreadwrite.h"
-#include "libavutil/audioconvert.h"
 
 #define AT1_SU_SIZE     212
 
diff --git a/libavformat/afc.c b/libavformat/afc.c
new file mode 100644
index 0000000..183a8e0
--- /dev/null
+++ b/libavformat/afc.c
@@ -0,0 +1,81 @@
+/*
+ * AFC demuxer
+ * Copyright (c) 2012 Paul B Mahol
+ *
+ * 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/channel_layout.h"
+#include "avformat.h"
+#include "internal.h"
+
+typedef struct AFCDemuxContext {
+    int64_t    data_end;
+} AFCDemuxContext;
+
+static int afc_read_header(AVFormatContext *s)
+{
+    AFCDemuxContext *c = s->priv_data;
+    AVStream *st;
+
+    st = avformat_new_stream(s, NULL);
+    if (!st)
+        return AVERROR(ENOMEM);
+    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+    st->codec->codec_id   = AV_CODEC_ID_ADPCM_AFC;
+    st->codec->channels   = 2;
+    st->codec->channel_layout = AV_CH_LAYOUT_STEREO;
+    st->codec->extradata_size = 1;
+
+    st->codec->extradata = av_mallocz(1 + FF_INPUT_BUFFER_PADDING_SIZE);
+    if (!st->codec->extradata)
+        return AVERROR(ENOMEM);
+    st->codec->extradata[0] = 8 * st->codec->channels;
+
+    c->data_end = avio_rb32(s->pb) + 32LL;
+    st->duration = avio_rb32(s->pb);
+    st->codec->sample_rate = avio_rb16(s->pb);
+    avio_skip(s->pb, 22);
+    avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
+
+    return 0;
+}
+
+static int afc_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    AFCDemuxContext *c = s->priv_data;
+    int64_t size;
+    int ret;
+
+    size = FFMIN(c->data_end - avio_tell(s->pb), 18 * 128);
+    if (size <= 0)
+        return AVERROR_EOF;
+
+    ret = av_get_packet(s->pb, pkt, size);
+    pkt->stream_index = 0;
+    return ret;
+}
+
+AVInputFormat ff_afc_demuxer = {
+    .name           = "afc",
+    .long_name      = NULL_IF_CONFIG_SMALL("AFC"),
+    .priv_data_size = sizeof(AFCDemuxContext),
+    .read_header    = afc_read_header,
+    .read_packet    = afc_read_packet,
+    .extensions     = "afc",
+    .flags          = AVFMT_NOBINSEARCH | AVFMT_NOGENSEARCH | AVFMT_NO_BYTE_SEEK,
+};
diff --git a/libavformat/aiff.h b/libavformat/aiff.h
index 6ece0e0..5521568 100644
--- a/libavformat/aiff.h
+++ b/libavformat/aiff.h
@@ -28,11 +28,12 @@
 #define AVFORMAT_AIFF_H
 
 #include "avformat.h"
-#include "riff.h"
+#include "internal.h"
 
 static const AVCodecTag ff_codec_aiff_tags[] = {
     { AV_CODEC_ID_PCM_S16BE,    MKTAG('N','O','N','E') },
     { AV_CODEC_ID_PCM_S8,       MKTAG('N','O','N','E') },
+    { AV_CODEC_ID_PCM_U8,       MKTAG('r','a','w',' ') },
     { AV_CODEC_ID_PCM_S24BE,    MKTAG('N','O','N','E') },
     { AV_CODEC_ID_PCM_S32BE,    MKTAG('N','O','N','E') },
     { AV_CODEC_ID_PCM_F32BE,    MKTAG('f','l','3','2') },
diff --git a/libavformat/aiffdec.c b/libavformat/aiffdec.c
index 41fe0d2..79b7853 100644
--- a/libavformat/aiffdec.c
+++ b/libavformat/aiffdec.c
@@ -28,6 +28,7 @@
 #include "aiff.h"
 #include "isom.h"
 #include "id3v2.h"
+#include "mov_chan.h"
 
 #define AIFF                    0
 #define AIFF_C_VERSION1         0xA2805140
@@ -190,7 +191,7 @@
 /* aiff input */
 static int aiff_read_header(AVFormatContext *s)
 {
-    int size, filesize;
+    int ret, size, filesize;
     int64_t offset = 0;
     uint32_t tag;
     unsigned version = AIFF_C_VERSION1;
@@ -236,6 +237,11 @@
             break;
         case MKTAG('I', 'D', '3', ' '):
             ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
+            if (id3v2_extra_meta)
+                if ((ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0) {
+                    ff_id3v2_free_extra_meta(&id3v2_extra_meta);
+                    return ret;
+                }
             ff_id3v2_free_extra_meta(&id3v2_extra_meta);
             break;
         case MKTAG('F', 'V', 'E', 'R'):     /* Version chunk */
@@ -258,7 +264,7 @@
             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 */
+            if (st->codec->block_align && !pb->seekable)    /* Assume COMM already parsed */
                 goto got_sound;
             if (!pb->seekable) {
                 av_log(s, AV_LOG_ERROR, "file is not seekable\n");
diff --git a/libavformat/allformats.c b/libavformat/allformats.c
index 36b6988..2987b8a 100644
--- a/libavformat/allformats.c
+++ b/libavformat/allformats.c
@@ -57,6 +57,7 @@
     REGISTER_MUXER    (ADTS, adts);
     REGISTER_MUXDEMUX (ADX, adx);
     REGISTER_DEMUXER  (AEA, aea);
+    REGISTER_DEMUXER  (AFC, afc);
     REGISTER_MUXDEMUX (AIFF, aiff);
     REGISTER_MUXDEMUX (AMR, amr);
     REGISTER_DEMUXER  (ANM, anm);
@@ -64,11 +65,13 @@
     REGISTER_DEMUXER  (APE, ape);
     REGISTER_MUXDEMUX (ASF, asf);
     REGISTER_MUXDEMUX (ASS, ass);
+    REGISTER_DEMUXER  (AST, ast);
     REGISTER_MUXER    (ASF_STREAM, asf_stream);
     REGISTER_MUXDEMUX (AU, au);
     REGISTER_MUXDEMUX (AVI, avi);
     REGISTER_DEMUXER  (AVISYNTH, avisynth);
     REGISTER_MUXER    (AVM2, avm2);
+    REGISTER_DEMUXER  (AVR, avr);
     REGISTER_DEMUXER  (AVS, avs);
     REGISTER_DEMUXER  (BETHSOFTVID, bethsoftvid);
     REGISTER_DEMUXER  (BFI, bfi);
@@ -76,6 +79,7 @@
     REGISTER_DEMUXER  (BINK, bink);
     REGISTER_MUXDEMUX (BIT, bit);
     REGISTER_DEMUXER  (BMV, bmv);
+    REGISTER_DEMUXER  (BRSTM, brstm);
     REGISTER_DEMUXER  (C93, c93);
     REGISTER_MUXDEMUX (CAF, caf);
     REGISTER_MUXDEMUX (CAVSVIDEO, cavsvideo);
@@ -88,6 +92,7 @@
     REGISTER_MUXDEMUX (DNXHD, dnxhd);
     REGISTER_DEMUXER  (DSICIN, dsicin);
     REGISTER_MUXDEMUX (DTS, dts);
+    REGISTER_DEMUXER  (DTSHD, dtshd);
     REGISTER_MUXDEMUX (DV, dv);
     REGISTER_DEMUXER  (DXA, dxa);
     REGISTER_DEMUXER  (EA, ea);
@@ -106,13 +111,13 @@
     REGISTER_MUXDEMUX (G722, g722);
     REGISTER_MUXDEMUX (G723_1, g723_1);
     REGISTER_DEMUXER  (G729, g729);
-    REGISTER_MUXER    (GIF, gif);
+    REGISTER_MUXDEMUX (GIF, gif);
     REGISTER_DEMUXER  (GSM, gsm);
     REGISTER_MUXDEMUX (GXF, gxf);
     REGISTER_MUXDEMUX (H261, h261);
     REGISTER_MUXDEMUX (H263, h263);
     REGISTER_MUXDEMUX (H264, h264);
-    REGISTER_DEMUXER  (HLS, hls);
+    REGISTER_MUXDEMUX (HLS, hls);
     REGISTER_MUXDEMUX (ICO, ico);
     REGISTER_DEMUXER  (IDCIN, idcin);
     REGISTER_DEMUXER  (IDF, idf);
@@ -132,6 +137,7 @@
     REGISTER_MUXDEMUX (LATM, latm);
     REGISTER_DEMUXER  (LMLM4, lmlm4);
     REGISTER_DEMUXER  (LOAS, loas);
+    REGISTER_DEMUXER  (LVF, lvf);
     REGISTER_DEMUXER  (LXF, lxf);
     REGISTER_MUXDEMUX (M4V, m4v);
     REGISTER_MUXER    (MD5, md5);
@@ -198,6 +204,7 @@
     REGISTER_DEMUXER  (PMP, pmp);
     REGISTER_MUXER    (PSP, psp);
     REGISTER_DEMUXER  (PVA, pva);
+    REGISTER_DEMUXER  (PVF, pvf);
     REGISTER_DEMUXER  (QCP, qcp);
     REGISTER_DEMUXER  (R3D, r3d);
     REGISTER_MUXDEMUX (RAWVIDEO, rawvideo);
@@ -233,6 +240,7 @@
     REGISTER_DEMUXER  (STR, str);
     REGISTER_DEMUXER  (SUBVIEWER, subviewer);
     REGISTER_MUXDEMUX (SWF, swf);
+    REGISTER_DEMUXER  (TAK, tak);
     REGISTER_MUXER    (TG2, tg2);
     REGISTER_MUXER    (TGP, tgp);
     REGISTER_DEMUXER  (THP, thp);
@@ -245,6 +253,7 @@
     REGISTER_DEMUXER  (TTY, tty);
     REGISTER_DEMUXER  (VC1, vc1);
     REGISTER_MUXDEMUX (VC1T, vc1t);
+    REGISTER_DEMUXER  (VIVO, vivo);
     REGISTER_DEMUXER  (VMD, vmd);
     REGISTER_MUXDEMUX (VOC, voc);
     REGISTER_DEMUXER  (VQF, vqf);
@@ -264,10 +273,6 @@
     REGISTER_DEMUXER  (YOP, yop);
     REGISTER_MUXDEMUX (YUV4MPEGPIPE, yuv4mpegpipe);
 
-    /* external libraries */
-#if CONFIG_LIBMODPLUG
-    REGISTER_DEMUXER  (LIBMODPLUG, libmodplug);
-#endif
     /* protocols */
 #if FF_API_APPLEHTTP_PROTO
     REGISTER_PROTOCOL (APPLEHTTP, applehttp);
@@ -301,6 +306,7 @@
     REGISTER_PROTOCOL (UDP, udp);
 
     /* external libraries */
+    REGISTER_DEMUXER  (LIBMODPLUG, libmodplug);
     REGISTER_MUXDEMUX (LIBNUT, libnut);
     REGISTER_PROTOCOL (LIBRTMP, librtmp);
     REGISTER_PROTOCOL (LIBRTMPE, librtmpe);
diff --git a/libavformat/amr.c b/libavformat/amr.c
index 36ff9b0..07ab1ba 100644
--- a/libavformat/amr.c
+++ b/libavformat/amr.c
@@ -25,7 +25,9 @@
 Only mono files are supported.
 
 */
+
 #include "libavutil/avassert.h"
+#include "libavutil/channel_layout.h"
 #include "avformat.h"
 #include "internal.h"
 
@@ -98,6 +100,7 @@
         st->codec->sample_rate = 8000;
     }
     st->codec->channels   = 1;
+    st->codec->channel_layout = AV_CH_LAYOUT_MONO;
     st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
     avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
 
diff --git a/libavformat/apc.c b/libavformat/apc.c
index 2ccf794..bb28a62 100644
--- a/libavformat/apc.c
+++ b/libavformat/apc.c
@@ -20,6 +20,8 @@
  */
 
 #include <string.h>
+
+#include "libavutil/channel_layout.h"
 #include "avformat.h"
 
 static int apc_probe(AVProbeData *p)
@@ -58,9 +60,13 @@
     /* initial predictor values for adpcm decoder */
     avio_read(pb, st->codec->extradata, 2 * 4);
 
-    st->codec->channels = 1;
-    if (avio_rl32(pb))
-        st->codec->channels = 2;
+    if (avio_rl32(pb)) {
+        st->codec->channels       = 2;
+        st->codec->channel_layout = AV_CH_LAYOUT_STEREO;
+    } else {
+        st->codec->channels       = 1;
+        st->codec->channel_layout = AV_CH_LAYOUT_MONO;
+    }
 
     st->codec->bits_per_coded_sample = 4;
     st->codec->bit_rate = st->codec->bits_per_coded_sample * st->codec->channels
diff --git a/libavformat/apetag.c b/libavformat/apetag.c
index bf9918a..a445c84 100644
--- a/libavformat/apetag.c
+++ b/libavformat/apetag.c
@@ -142,11 +142,11 @@
         return 0;
     }
 
-    tag_start = file_size - tag_bytes - APE_TAG_FOOTER_BYTES;
-    if (tag_start < 0) {
+    if (tag_bytes > file_size - APE_TAG_FOOTER_BYTES) {
         av_log(s, AV_LOG_ERROR, "Invalid tag size %u.\n", tag_bytes);
         return 0;
     }
+    tag_start = file_size - tag_bytes - APE_TAG_FOOTER_BYTES;
 
     fields = avio_rl32(pb);    /* number of fields */
     if (fields > 65536) {
diff --git a/libavformat/asf.h b/libavformat/asf.h
index 5562865..528d4c1 100644
--- a/libavformat/asf.h
+++ b/libavformat/asf.h
@@ -28,7 +28,12 @@
 
 #define PACKET_SIZE 3200
 
-typedef struct {
+typedef struct ASFPayload {
+    uint8_t type;
+    uint16_t size;
+} ASFPayload;
+
+typedef struct ASFStream {
     int num;
     unsigned char seq;
     /* use for reading */
@@ -47,9 +52,12 @@
 
     int      palette_changed;
     uint32_t palette[256];
+
+    int payload_ext_ct;
+    ASFPayload payload[8];
 } ASFStream;
 
-typedef struct {
+typedef struct ASFMainHeader {
     ff_asf_guid guid;                  ///< generated by client computer
     uint64_t file_size;         /**< in bytes
                                  *   invalid if broadcasting */
@@ -75,7 +83,7 @@
 } ASFMainHeader;
 
 
-typedef struct {
+typedef struct ASFIndex {
     uint32_t packet_number;
     uint16_t packet_count;
 } ASFIndex;
diff --git a/libavformat/asfdec.c b/libavformat/asfdec.c
index b58cf28..2dcdf56 100644
--- a/libavformat/asfdec.c
+++ b/libavformat/asfdec.c
@@ -351,8 +351,10 @@
     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;
+        int64_t fsize = avio_size(pb);
+        if (fsize <= 0 || (int64_t)asf->hdr.file_size <= 0 || FFABS(fsize - (int64_t)asf->hdr.file_size) < 10000)
+            st->duration = asf->hdr.play_time /
+                (10000000 / 1000) - start_time;
     }
     ff_get_guid(pb, &g);
 
@@ -442,7 +444,7 @@
         tag1 = avio_rl32(pb);
         avio_skip(pb, 20);
         if (sizeX > 40) {
-            st->codec->extradata_size = sizeX - 40;
+            st->codec->extradata_size = ffio_limit(pb, 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);
         }
@@ -510,8 +512,10 @@
     stream_ct = avio_rl16(pb); //stream-name-count
     payload_ext_ct = avio_rl16(pb); //payload-extension-system-count
 
-    if (stream_num < 128)
+    if (stream_num < 128) {
         asf->stream_bitrates[stream_num] = leak_rate;
+        asf->streams[stream_num].payload_ext_ct = 0;
+    }
 
     for (i=0; i<stream_ct; i++){
         avio_rl16(pb);
@@ -520,10 +524,18 @@
     }
 
     for (i=0; i<payload_ext_ct; i++){
+        int size;
         ff_get_guid(pb, &g);
-        avio_skip(pb, 2);
+        size = avio_rl16(pb);
         ext_len=avio_rl32(pb);
         avio_skip(pb, ext_len);
+        if (stream_num < 128 && i < FF_ARRAY_ELEMS(asf->streams[stream_num].payload)) {
+            ASFPayload *p = &asf->streams[stream_num].payload[i];
+            p->type = g[0];
+            p->size = size;
+            av_log(s, AV_LOG_DEBUG, "Payload extension %x %d\n", g[0], p->size );
+            asf->streams[stream_num].payload_ext_ct ++;
+        }
     }
 
     return 0;
@@ -773,12 +785,12 @@
             if (!st->codec->bit_rate)
                 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.den,
-                          &st->sample_aspect_ratio.num,
+                av_reduce(&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.den,
-                          &st->sample_aspect_ratio.num,
+                av_reduce(&st->sample_aspect_ratio.num,
+                          &st->sample_aspect_ratio.den,
                           asf->dar[0].num, asf->dar[0].den, INT_MAX);
 
             av_dlog(s, "i=%d, st->codec->codec_type:%d, asf->dar %d:%d sar=%d:%d\n",
@@ -914,13 +926,16 @@
  */
 static int asf_read_frame_header(AVFormatContext *s, AVIOContext *pb){
     ASFContext *asf = s->priv_data;
+    ASFStream *asfst;
     int rsize = 1;
     int num = avio_r8(pb);
+    int i;
     int64_t ts0, ts1 av_unused;
 
     asf->packet_segments--;
     asf->packet_key_frame = num >> 7;
     asf->stream_index = asf->asfid2avid[num & 0x7f];
+    asfst = &asf->streams[num & 0x7f];
     // sequence should be ignored!
     DO_2BITS(asf->packet_property >> 4, asf->packet_seq, 0);
     DO_2BITS(asf->packet_property >> 2, asf->packet_frag_offset, 0);
@@ -933,23 +948,56 @@
         return AVERROR_INVALIDDATA;
     }
     if (asf->packet_replic_size >= 8) {
+        int64_t end = avio_tell(pb) + asf->packet_replic_size;
+        AVRational aspect;
         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 AVERROR_INVALIDDATA;
         }
         asf->packet_frag_timestamp = avio_rl32(pb); // timestamp
-        if(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
-            avio_skip(pb, asf->packet_replic_size - 8);
+
+        for (i=0; i<asfst->payload_ext_ct; i++) {
+            ASFPayload *p = &asfst->payload[i];
+            int size = p->size;
+            int64_t payend;
+            if(size == 0xFFFF)
+                size = avio_rl16(pb);
+            payend = avio_tell(pb) + size;
+            if (payend > end) {
+                av_log(s, AV_LOG_ERROR, "too long payload\n");
+                break;
+            }
+            switch(p->type) {
+            case 0x50:
+//              duration = avio_rl16(pb);
+                break;
+            case 0x54:
+                aspect.num = avio_r8(pb);
+                aspect.den = avio_r8(pb);
+                if (aspect.num > 0 && aspect.den > 0 && asf->stream_index >= 0) {
+                    s->streams[asf->stream_index]->sample_aspect_ratio = aspect;
+                }
+                break;
+            case 0x2A:
+                avio_skip(pb, 8);
+                ts0= avio_rl64(pb);
+                ts1= avio_rl64(pb);
+                if(ts0!= -1) asf->packet_frag_timestamp= ts0/10000;
+                else         asf->packet_frag_timestamp= AV_NOPTS_VALUE;
+                break;
+            case 0x5B:
+            case 0xB7:
+            case 0xCC:
+            case 0xC0:
+            case 0xA0:
+                //unknown
+                break;
+            }
+            avio_seek(pb, payend, SEEK_SET);
+        }
+
+        avio_seek(pb, end, SEEK_SET);
         rsize += asf->packet_replic_size; // FIXME - check validity
     } else if (asf->packet_replic_size==1){
         // multipacket - frag_offset is beginning timestamp
@@ -1006,13 +1054,14 @@
     ASFStream *asf_st = 0;
     for (;;) {
         int ret;
-        if(url_feof(pb))
+        if (url_feof(pb))
             return AVERROR_EOF;
-        if (asf->packet_size_left < FRAME_HEADER_SIZE
-            || asf->packet_segments < 1) {
-            //asf->packet_size_left <= asf->packet_padsize) {
+
+        if (asf->packet_size_left < FRAME_HEADER_SIZE ||
+            asf->packet_segments < 1) {
             int ret = asf->packet_size_left + asf->packet_padsize;
-            assert(ret>=0);
+
+            assert(ret >= 0);
             /* fail safe */
             avio_skip(pb, ret);
 
@@ -1023,19 +1072,19 @@
             return 1;
         }
         if (asf->packet_time_start == 0) {
-            if(asf_read_frame_header(s, pb) < 0){
-                asf->packet_segments= 0;
+            if (asf_read_frame_header(s, pb) < 0) {
+                asf->packet_segments = 0;
                 continue;
             }
-            if (asf->stream_index < 0
-                || s->streams[asf->stream_index]->discard >= AVDISCARD_ALL
-                || (!asf->packet_key_frame && s->streams[asf->stream_index]->discard >= AVDISCARD_NONKEY)
-                ) {
+            if (asf->stream_index < 0 ||
+                s->streams[asf->stream_index]->discard >= AVDISCARD_ALL ||
+                (!asf->packet_key_frame &&
+                 s->streams[asf->stream_index]->discard >= AVDISCARD_NONKEY)) {
                 asf->packet_time_start = 0;
                 /* unhandled packet (should not happen) */
                 avio_skip(pb, asf->packet_frag_size);
                 asf->packet_size_left -= asf->packet_frag_size;
-                if(asf->stream_index < 0)
+                if (asf->stream_index < 0)
                     av_log(s, AV_LOG_ERROR, "ff asf skip %d (unknown stream)\n", asf->packet_frag_size);
                 continue;
             }
@@ -1046,12 +1095,11 @@
         if (asf->packet_replic_size == 1) {
             // 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 = avio_r8(pb);
+            asf->packet_time_start    += asf->packet_time_delta;
+            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)
-            {
+            if (asf->packet_multi_size < asf->packet_obj_size) {
                 asf->packet_time_start = 0;
                 avio_skip(pb, asf->packet_multi_size);
                 asf->packet_size_left -= asf->packet_multi_size;
@@ -1059,29 +1107,30 @@
             }
             asf->packet_multi_size -= asf->packet_obj_size;
         }
-        if(   /*asf->packet_frag_size == asf->packet_obj_size*/
-              asf_st->frag_offset + asf->packet_frag_size <= asf_st->pkt.size
-           && asf_st->frag_offset + asf->packet_frag_size > asf->packet_obj_size){
+        if (asf_st->frag_offset + asf->packet_frag_size <= asf_st->pkt.size &&
+            asf_st->frag_offset + asf->packet_frag_size > asf->packet_obj_size) {
             av_log(s, AV_LOG_INFO, "ignoring invalid packet_obj_size (%d %d %d %d)\n",
-                asf_st->frag_offset, asf->packet_frag_size,
-                asf->packet_obj_size, asf_st->pkt.size);
-            asf->packet_obj_size= asf_st->pkt.size;
+                   asf_st->frag_offset, asf->packet_frag_size,
+                   asf->packet_obj_size, asf_st->pkt.size);
+            asf->packet_obj_size = asf_st->pkt.size;
         }
 
-        if (   asf_st->pkt.size != asf->packet_obj_size
-            || asf_st->frag_offset + asf->packet_frag_size > asf_st->pkt.size) { //FIXME is this condition sufficient?
-            if(asf_st->pkt.data){
-                av_log(s, AV_LOG_INFO, "freeing incomplete packet size %d, new %d\n", asf_st->pkt.size, asf->packet_obj_size);
+        if (asf_st->pkt.size != asf->packet_obj_size ||
+            //FIXME is this condition sufficient?
+            asf_st->frag_offset + asf->packet_frag_size > asf_st->pkt.size) {
+            if (asf_st->pkt.data) {
+                av_log(s, AV_LOG_INFO, "freeing incomplete packet size %d, "
+                       "new %d\n", asf_st->pkt.size, asf->packet_obj_size);
                 asf_st->frag_offset = 0;
                 av_free_packet(&asf_st->pkt);
             }
             /* 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->hdr.preroll;
+            asf_st->seq              = asf->packet_seq;
+            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;
+            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(&asf_st->pkt, AV_PKT_DATA_PALETTE,
@@ -1112,18 +1161,19 @@
         if (asf->packet_size_left < 0)
             continue;
 
-        if(   asf->packet_frag_offset >= asf_st->pkt.size
-           || asf->packet_frag_size > asf_st->pkt.size - asf->packet_frag_offset){
+        if (asf->packet_frag_offset >= asf_st->pkt.size ||
+            asf->packet_frag_size > asf_st->pkt.size - asf->packet_frag_offset) {
             av_log(s, AV_LOG_ERROR, "packet fragment position invalid %u,%u not in %u\n",
-                asf->packet_frag_offset, asf->packet_frag_size, asf_st->pkt.size);
+                   asf->packet_frag_offset, asf->packet_frag_size, asf_st->pkt.size);
             continue;
         }
 
         ret = avio_read(pb, asf_st->pkt.data + asf->packet_frag_offset,
-                         asf->packet_frag_size);
+                        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
@@ -1131,9 +1181,10 @@
                 memset(asf_st->pkt.data + asf->packet_frag_offset + ret, 0,
                        asf->packet_frag_size - ret);
                 ret = asf->packet_frag_size;
-            } else
+            } 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,
@@ -1142,11 +1193,11 @@
         /* test if whole packet is read */
         if (asf_st->frag_offset == asf_st->pkt.size) {
             //workaround for macroshit radio DVR-MS files
-            if(   s->streams[asf->stream_index]->codec->codec_id == AV_CODEC_ID_MPEG2VIDEO
-               && asf_st->pkt.size > 100){
+            if (s->streams[asf->stream_index]->codec->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
+                asf_st->pkt.size > 100) {
                 int i;
-                for(i=0; i<asf_st->pkt.size && !asf_st->pkt.data[i]; i++);
-                if(i == asf_st->pkt.size){
+                for (i = 0; i < asf_st->pkt.size && !asf_st->pkt.data[i]; i++);
+                if (i == asf_st->pkt.size) {
                     av_log(s, AV_LOG_DEBUG, "discarding ms fart\n");
                     asf_st->frag_offset = 0;
                     av_free_packet(&asf_st->pkt);
@@ -1156,37 +1207,39 @@
 
             /* return packet */
             if (asf_st->ds_span > 1) {
-              if(asf_st->pkt.size != asf_st->ds_packet_size * asf_st->ds_span){
-                    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 + 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;
-                        int col = off % asf_st->ds_span;
-                        int idx = row + col * asf_st->ds_packet_size / asf_st->ds_chunk_size;
-                        assert(offset + asf_st->ds_chunk_size <= asf_st->pkt.size);
-                        assert(idx+1 <= asf_st->pkt.size / asf_st->ds_chunk_size);
-                        memcpy(newdata + offset,
-                               asf_st->pkt.data + idx * asf_st->ds_chunk_size,
-                               asf_st->ds_chunk_size);
-                        offset += asf_st->ds_chunk_size;
+                if(asf_st->pkt.size != asf_st->ds_packet_size * asf_st->ds_span) {
+                    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 + 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;
+                            int col = off % asf_st->ds_span;
+                            int idx = row + col * asf_st->ds_packet_size / asf_st->ds_chunk_size;
+                            assert(offset + asf_st->ds_chunk_size <= asf_st->pkt.size);
+                            assert(idx+1 <= asf_st->pkt.size / asf_st->ds_chunk_size);
+                            memcpy(newdata + offset,
+                                   asf_st->pkt.data + idx * asf_st->ds_chunk_size,
+                                   asf_st->ds_chunk_size);
+                            offset += asf_st->ds_chunk_size;
+                        }
+                        av_free(asf_st->pkt.data);
+                        asf_st->pkt.data = newdata;
                     }
-                    av_free(asf_st->pkt.data);
-                    asf_st->pkt.data = newdata;
                 }
-              }
             }
-            asf_st->frag_offset = 0;
-            *pkt= asf_st->pkt;
-            asf_st->pkt.size = 0;
-            asf_st->pkt.data = 0;
+            asf_st->frag_offset         = 0;
+            *pkt                        = asf_st->pkt;
+            asf_st->pkt.size            = 0;
+            asf_st->pkt.data            = 0;
             asf_st->pkt.side_data_elems = 0;
-            asf_st->pkt.side_data = NULL;
+            asf_st->pkt.side_data       = NULL;
             break; // packet completed
         }
     }
diff --git a/libavformat/assdec.c b/libavformat/assdec.c
index 835fd8a..6c4614e 100644
--- a/libavformat/assdec.c
+++ b/libavformat/assdec.c
@@ -19,20 +19,16 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#include "libavutil/mathematics.h"
 #include "avformat.h"
 #include "internal.h"
-
-#define MAX_LINESIZE 2000
+#include "subtitles.h"
+#include "libavutil/bprint.h"
 
 typedef struct ASSContext{
-    uint8_t *event_buffer;
-    uint8_t **event;
-    unsigned int event_count;
-    unsigned int event_index;
+    FFDemuxSubtitlesQueue q;
 }ASSContext;
 
-static int probe(AVProbeData *p)
+static int ass_probe(AVProbeData *p)
 {
     const char *header= "[Script Info]";
 
@@ -43,173 +39,133 @@
     return 0;
 }
 
-static int read_close(AVFormatContext *s)
+static int ass_read_close(AVFormatContext *s)
 {
     ASSContext *ass = s->priv_data;
-
-    av_freep(&ass->event_buffer);
-    av_freep(&ass->event);
-
+    ff_subtitles_queue_clean(&ass->q);
     return 0;
 }
 
-static int64_t get_pts(const uint8_t *p)
+static int read_ts(const uint8_t *p, int64_t *start, int *duration)
 {
-    int hour, min, sec, hsec;
+    int64_t end;
+    int hh1, mm1, ss1, ms1;
+    int hh2, mm2, ss2, ms2;
 
-    if(sscanf(p, "%*[^,],%d:%d:%d%*c%d", &hour, &min, &sec, &hsec) != 4)
-        return AV_NOPTS_VALUE;
-
-    av_dlog(NULL, "%d %d %d %d [%s]\n", hour, min, sec, hsec, p);
-
-    min+= 60*hour;
-    sec+= 60*min;
-
-    return sec*100+hsec;
+    if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
+               &hh1, &mm1, &ss1, &ms1,
+               &hh2, &mm2, &ss2, &ms2) == 8) {
+        end    = (hh2*3600LL + mm2*60LL + ss2) * 100LL + ms2;
+        *start = (hh1*3600LL + mm1*60LL + ss1) * 100LL + ms1;
+        *duration = end - *start;
+        return 0;
+    }
+    return -1;
 }
 
-static int event_cmp(uint8_t **a, uint8_t **b)
+static int64_t get_line(AVBPrint *buf, AVIOContext *pb)
 {
-    return get_pts(*a) - get_pts(*b);
+    int64_t pos = avio_tell(pb);
+
+    av_bprint_clear(buf);
+    for (;;) {
+        char c = avio_r8(pb);
+        if (!c)
+            break;
+        av_bprint_chars(buf, c, 1);
+        if (c == '\n')
+            break;
+    }
+    return pos;
 }
 
-static int read_header(AVFormatContext *s)
+static int ass_read_header(AVFormatContext *s)
 {
-    int i, len, header_remaining;
     ASSContext *ass = s->priv_data;
-    AVIOContext *pb = s->pb;
+    AVBPrint header, line;
+    int header_remaining, res = 0;
     AVStream *st;
-    int allocated[2]={0};
-    uint8_t *p, **dst[2]={0};
-    int pos[2]={0};
 
     st = avformat_new_stream(s, NULL);
     if (!st)
-        return -1;
+        return AVERROR(ENOMEM);
     avpriv_set_pts_info(st, 64, 1, 100);
     st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
     st->codec->codec_id= AV_CODEC_ID_SSA;
 
     header_remaining= INT_MAX;
-    dst[0] = &st->codec->extradata;
-    dst[1] = &ass->event_buffer;
-    while(!url_feof(pb)){
-        uint8_t line[MAX_LINESIZE];
 
-        len = ff_get_line(pb, line, sizeof(line));
+    av_bprint_init(&header, 0, AV_BPRINT_SIZE_UNLIMITED);
+    av_bprint_init(&line,   0, AV_BPRINT_SIZE_UNLIMITED);
 
-        if(!memcmp(line, "[Events]", 8))
+    for (;;) {
+        int64_t pos = get_line(&line, s->pb);
+
+        if (!line.str[0]) // EOF
+            break;
+
+        if (!memcmp(line.str, "[Events]", 8))
             header_remaining= 2;
-        else if(line[0]=='[')
+        else if (line.str[0]=='[')
             header_remaining= INT_MAX;
 
-        i= header_remaining==0;
+        if (header_remaining) {
+            av_bprintf(&header, "%s", line.str);
+            header_remaining--;
+        } else {
+            int64_t ts_start = AV_NOPTS_VALUE;
+            int duration = -1;
+            AVPacket *sub;
 
-        if(i && get_pts(line) == AV_NOPTS_VALUE)
-            continue;
-
-        p = av_fast_realloc(*(dst[i]), &allocated[i], pos[i]+MAX_LINESIZE);
-        if(!p)
-            goto fail;
-        *(dst[i])= p;
-        memcpy(p + pos[i], line, len+1);
-        pos[i] += len;
-        if(i) ass->event_count++;
-        else  header_remaining--;
-    }
-    st->codec->extradata_size= pos[0];
-
-    if(ass->event_count >= UINT_MAX / sizeof(*ass->event))
-        goto fail;
-
-    ass->event= av_malloc(ass->event_count * sizeof(*ass->event));
-    p= ass->event_buffer;
-    for(i=0; i<ass->event_count; i++){
-        ass->event[i]= p;
-        while(*p && *p != '\n')
-            p++;
-        p++;
-    }
-
-    qsort(ass->event, ass->event_count, sizeof(*ass->event), (void*)event_cmp);
-
-    return 0;
-
-fail:
-    read_close(s);
-
-    return -1;
-}
-
-static int read_packet(AVFormatContext *s, AVPacket *pkt)
-{
-    ASSContext *ass = s->priv_data;
-    uint8_t *p, *end;
-
-    if(ass->event_index >= ass->event_count)
-        return AVERROR_EOF;
-
-    p= ass->event[ ass->event_index ];
-
-    end= strchr(p, '\n');
-    av_new_packet(pkt, end ? end-p+1 : strlen(p));
-    pkt->flags |= AV_PKT_FLAG_KEY;
-    pkt->pos= p - ass->event_buffer + s->streams[0]->codec->extradata_size;
-    pkt->pts= pkt->dts= get_pts(p);
-    memcpy(pkt->data, p, pkt->size);
-
-    ass->event_index++;
-
-    return 0;
-}
-
-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 (read_ts(line.str, &ts_start, &duration) < 0)
+                continue;
+            sub = ff_subtitles_queue_insert(&ass->q, line.str, line.len, 0);
+            if (!sub) {
+                res = AVERROR(ENOMEM);
+                goto end;
             }
+            sub->pos = pos;
+            sub->pts = ts_start;
+            sub->duration = duration;
         }
-        if (idx < 0)
-            return AVERROR(ERANGE);
-        ass->event_index = idx;
     }
-    return 0;
+
+    av_bprint_finalize(&line, NULL);
+
+    av_bprint_finalize(&header, (char **)&st->codec->extradata);
+    if (!st->codec->extradata) {
+        res = AVERROR(ENOMEM);
+        goto end;
+    }
+    st->codec->extradata_size = header.len + 1;
+
+    ff_subtitles_queue_finalize(&ass->q);
+
+end:
+    return res;
+}
+
+static int ass_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    ASSContext *ass = s->priv_data;
+    return ff_subtitles_queue_read_packet(&ass->q, pkt);
+}
+
+static int ass_read_seek(AVFormatContext *s, int stream_index,
+                         int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
+{
+    ASSContext *ass = s->priv_data;
+    return ff_subtitles_queue_seek(&ass->q, s, stream_index,
+                                   min_ts, ts, max_ts, flags);
 }
 
 AVInputFormat ff_ass_demuxer = {
     .name           = "ass",
     .long_name      = NULL_IF_CONFIG_SMALL("SSA (SubStation Alpha) subtitle"),
     .priv_data_size = sizeof(ASSContext),
-    .read_probe     = probe,
-    .read_header    = read_header,
-    .read_packet    = read_packet,
-    .read_close     = read_close,
-    .read_seek2     = read_seek2,
+    .read_probe     = ass_probe,
+    .read_header    = ass_read_header,
+    .read_packet    = ass_read_packet,
+    .read_close     = ass_read_close,
+    .read_seek2     = ass_read_seek,
 };
diff --git a/libavformat/assenc.c b/libavformat/assenc.c
index 6b98886..bda507d 100644
--- a/libavformat/assenc.c
+++ b/libavformat/assenc.c
@@ -85,5 +85,5 @@
     .write_header   = write_header,
     .write_packet   = write_packet,
     .write_trailer  = write_trailer,
-    .flags          = AVFMT_GLOBALHEADER | AVFMT_NOTIMESTAMPS,
+    .flags          = AVFMT_GLOBALHEADER | AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT,
 };
diff --git a/libavformat/ast.c b/libavformat/ast.c
new file mode 100644
index 0000000..5f69f47
--- /dev/null
+++ b/libavformat/ast.c
@@ -0,0 +1,127 @@
+/*
+ * AST demuxer
+ * Copyright (c) 2012 Paul B Mahol
+ *
+ * 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/channel_layout.h"
+#include "libavutil/intreadwrite.h"
+#include "avformat.h"
+#include "internal.h"
+
+static int ast_probe(AVProbeData *p)
+{
+    if (AV_RL32(p->buf) == MKTAG('S','T','R','M') &&
+        AV_RB16(p->buf + 10) &&
+        AV_RB16(p->buf + 12) &&
+        AV_RB32(p->buf + 16))
+        return AVPROBE_SCORE_MAX / 3 * 2;
+    return 0;
+}
+
+static int ast_read_header(AVFormatContext *s)
+{
+    int codec, depth;
+    AVStream *st;
+
+    st = avformat_new_stream(s, NULL);
+    if (!st)
+        return AVERROR(ENOMEM);
+
+    avio_skip(s->pb, 8);
+    codec = avio_rb16(s->pb);
+    switch (codec) {
+    case 0:
+        st->codec->codec_id = AV_CODEC_ID_ADPCM_AFC;
+        break;
+    case 1:
+        st->codec->codec_id = AV_CODEC_ID_PCM_S16BE_PLANAR;
+        break;
+    default:
+        av_log(s, AV_LOG_ERROR, "unsupported codec %d\n", codec);
+    }
+
+    depth = avio_rb16(s->pb);
+    if (depth != 16) {
+        av_log_ask_for_sample(s, "unsupported depth %d\n", depth);
+        return AVERROR_INVALIDDATA;
+    }
+
+    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+    st->codec->channels = avio_rb16(s->pb);
+    if (!st->codec->channels)
+        return AVERROR_INVALIDDATA;
+
+    if (st->codec->channels == 2)
+        st->codec->channel_layout = AV_CH_LAYOUT_STEREO;
+    else if (st->codec->channels == 4)
+        st->codec->channel_layout = AV_CH_LAYOUT_4POINT0;
+
+    avio_skip(s->pb, 2);
+    st->codec->sample_rate = avio_rb32(s->pb);
+    if (st->codec->sample_rate <= 0)
+        return AVERROR_INVALIDDATA;
+    st->start_time         = 0;
+    st->duration           = avio_rb32(s->pb);
+    avio_skip(s->pb, 40);
+    avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
+
+    return 0;
+}
+
+static int ast_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    uint32_t type, size;
+    int64_t pos;
+    int ret;
+
+    if (url_feof(s->pb))
+        return AVERROR_EOF;
+
+    pos  = avio_tell(s->pb);
+    type = avio_rl32(s->pb);
+    size = avio_rb32(s->pb);
+    if (size > INT_MAX / s->streams[0]->codec->channels)
+        return AVERROR_INVALIDDATA;
+
+    size *= s->streams[0]->codec->channels;
+    if ((ret = avio_skip(s->pb, 24)) < 0) // padding
+        return ret;
+
+    if (type == MKTAG('B','L','C','K')) {
+        ret = av_get_packet(s->pb, pkt, size);
+        pkt->stream_index = 0;
+        pkt->pos = pos;
+    } else {
+        av_log(s, AV_LOG_ERROR, "unknown chunk %x\n", type);
+        avio_skip(s->pb, size);
+        ret = AVERROR_INVALIDDATA;
+    }
+
+    return ret;
+}
+
+AVInputFormat ff_ast_demuxer = {
+    .name           = "ast",
+    .long_name      = NULL_IF_CONFIG_SMALL("AST (Audio Stream)"),
+    .read_probe     = ast_probe,
+    .read_header    = ast_read_header,
+    .read_packet    = ast_read_packet,
+    .extensions     = "ast",
+    .flags          = AVFMT_GENERIC_INDEX,
+};
diff --git a/libavformat/au.c b/libavformat/au.c
index 788e261..6797c3c 100644
--- a/libavformat/au.c
+++ b/libavformat/au.c
@@ -31,10 +31,11 @@
 #include "internal.h"
 #include "avio_internal.h"
 #include "pcm.h"
-#include "riff.h"
 
 /* if we don't know the size in advance */
 #define AU_UNKNOWN_SIZE ((uint32_t)(~0))
+/* the specification requires an annotation field of at least eight bytes */
+#define AU_HEADER_SIZE (24+8)
 
 /* The libavcodec codecs we support, and the IDs they have in the file */
 static const AVCodecTag codec_au_tags[] = {
@@ -45,6 +46,7 @@
     { AV_CODEC_ID_PCM_S32BE, 5 },
     { AV_CODEC_ID_PCM_F32BE, 6 },
     { AV_CODEC_ID_PCM_F64BE, 7 },
+    { AV_CODEC_ID_ADPCM_G722, 24 },
     { AV_CODEC_ID_PCM_ALAW, 27 },
     { AV_CODEC_ID_NONE, 0 },
 };
@@ -56,11 +58,12 @@
     if(!enc->codec_tag)
         return -1;
     ffio_wfourcc(pb, ".snd");    /* magic number */
-    avio_wb32(pb, 24);           /* header size */
+    avio_wb32(pb, AU_HEADER_SIZE);  /* 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);
+    avio_wb64(pb, 0); /* annotation field */
     return 0;
 }
 
@@ -97,7 +100,7 @@
         /* update file size */
         file_size = avio_tell(pb);
         avio_seek(pb, 8, SEEK_SET);
-        avio_wb32(pb, (uint32_t)(file_size - 24));
+        avio_wb32(pb, (uint32_t)(file_size - AU_HEADER_SIZE));
         avio_seek(pb, file_size, SEEK_SET);
 
         avio_flush(pb);
diff --git a/libavformat/audiointerleave.c b/libavformat/audiointerleave.c
index 609a511..35dd8d5 100644
--- a/libavformat/audiointerleave.c
+++ b/libavformat/audiointerleave.c
@@ -84,7 +84,8 @@
     if (!size || (!flush && size == av_fifo_size(aic->fifo)))
         return 0;
 
-    av_new_packet(pkt, size);
+    if (av_new_packet(pkt, size) < 0)
+        return AVERROR(ENOMEM);
     av_fifo_generic_read(aic->fifo, pkt->data, size, NULL);
 
     pkt->dts = pkt->pts = aic->dts;
@@ -133,13 +134,15 @@
         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
             AVPacket new_pkt;
             int ret;
-            while (ff_interleave_new_audio_packet(s, &new_pkt, i, flush)) {
+            while ((ret = ff_interleave_new_audio_packet(s, &new_pkt, i, flush)) > 0) {
                 ret = ff_interleave_add_packet(s, &new_pkt, compare_ts);
                 if (ret < 0)
                     return ret;
             }
+            if (ret < 0)
+                return ret;
         }
     }
 
-    return get_packet(s, out, pkt, flush);
+    return get_packet(s, out, NULL, flush);
 }
diff --git a/libavformat/audiointerleave.h b/libavformat/audiointerleave.h
index b37c8ae..4d77832 100644
--- a/libavformat/audiointerleave.h
+++ b/libavformat/audiointerleave.h
@@ -26,7 +26,7 @@
 #include "libavutil/fifo.h"
 #include "avformat.h"
 
-typedef struct {
+typedef struct AudioInterleaveContext {
     AVFifoBuffer *fifo;
     unsigned fifo_size;           ///< size of currently allocated FIFO
     uint64_t dts;                 ///< current dts
diff --git a/libavformat/avformat.h b/libavformat/avformat.h
index f7779e7..4b916cc 100644
--- a/libavformat/avformat.h
+++ b/libavformat/avformat.h
@@ -158,9 +158,15 @@
  * information will be in AVStream.time_base units, i.e. it has to be
  * multiplied by the timebase to convert them to seconds.
  *
- * The packet data belongs to the demuxer and is invalid after the next call to
- * av_read_frame(). The user must free the packet with av_free_packet() before
- * calling av_read_frame() again or closing the file.
+ * If AVPacket.destruct is set on the returned packet, then the packet is
+ * allocated dynamically and the user may keep it indefinitely.
+ * Otherwise, if AVPacket.destruct is NULL, the packet data is backed by a
+ * static storage somewhere inside the demuxer and the packet is only valid
+ * until the next av_read_frame() call or closing the file. If the caller
+ * requires a longer lifetime, av_dup_packet() will make an av_malloc()ed copy
+ * of it.
+ * In both cases, the packet must be freed with av_free_packet() when it is no
+ * longer needed.
  *
  * @section lavf_decoding_seek Seeking
  * @}
@@ -336,6 +342,7 @@
 } AVProbeData;
 
 #define AVPROBE_SCORE_MAX 100               ///< maximum score, half of that is used for file-extension-based detection
+#define AVPROBE_SCORE_RETRY (AVPROBE_SCORE_MAX/4)
 #define AVPROBE_PADDING_SIZE 32             ///< extra allocated bytes at the end of the probe buffer
 
 /// Demuxer will use avio_open, no opened file should be provided by the caller.
@@ -581,7 +588,7 @@
     AVSTREAM_PARSE_FULL_ONCE,  /**< full parsing and repack of the first frame only, only implemented for H.264 currently */
     AVSTREAM_PARSE_FULL_RAW=MKTAG(0,'R','A','W'),       /**< full parsing and repack with timestamp and position generation by parser for raw
                                                              this assumes that each packet in the file contains no demuxer level headers and
-                                                             just codec level data, otherwise position generaion would fail */
+                                                             just codec level data, otherwise position generation would fail */
 };
 
 typedef struct AVIndexEntry {
@@ -634,7 +641,7 @@
     /**
      * Format-specific stream ID.
      * decoding: set by libavformat
-     * encoding: set by the user
+     * encoding: set by the user, replaced by libavformat if left unset
      */
     int id;
     /**
@@ -672,7 +679,7 @@
      * of which frame timestamps are represented.
      *
      * decoding: set by libavformat
-     * encoding: set by libavformat in av_write_header. The muxer may use the
+     * encoding: set by libavformat in avformat_write_header. The muxer may use the
      * user-provided value of @ref AVCodecContext.time_base "codec->time_base"
      * as a hint.
      */
@@ -742,6 +749,7 @@
         int duration_count;
         double duration_error[2][2][MAX_STD_TIMEBASES];
         int64_t codec_info_duration;
+        int64_t codec_info_duration_fields;
         int found_decoder;
 
         /**
@@ -860,6 +868,16 @@
     int program_num;
     int pmt_pid;
     int pcr_pid;
+
+    /*****************************************************************
+     * All fields below this line are not part of the public API. They
+     * may not be used outside of libavformat and can be changed and
+     * removed at will.
+     * New public fields should be added right above.
+     *****************************************************************
+     */
+    int64_t start_time;
+    int64_t end_time;
 } AVProgram;
 
 #define AVFMTCTX_NOHEADER      0x0001 /**< signal that no header is present
@@ -1144,6 +1162,13 @@
      */
     enum AVDurationEstimationMethod duration_estimation_method;
 
+    /**
+     * Skip initial bytes when opening stream
+     * - encoding: unused
+     * - decoding: Set by user via AVOptions (NO direct access)
+     */
+    unsigned int skip_initial_bytes;
+
     /*****************************************************************
      * All fields below this line are not part of the public API. They
      * may not be used outside of libavformat and can be changed and
@@ -1299,7 +1324,7 @@
  *
  * @return newly created stream or NULL on error.
  */
-AVStream *avformat_new_stream(AVFormatContext *s, AVCodec *c);
+AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c);
 
 AVProgram *av_new_program(AVFormatContext *s, int id);
 
@@ -1538,13 +1563,13 @@
  * 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
- * must be freed with av_free_packet. For video, the packet contains
- * exactly one frame. For audio, it contains an integer number of
- * frames if each frame has a known fixed size (e.g. PCM or ADPCM
- * data). If the audio frames have a variable size (e.g. MPEG audio),
- * then it contains one frame.
+ * If pkt->destruct is NULL, then the packet is valid until the next
+ * av_read_frame() or until av_close_input_file(). Otherwise the packet is valid
+ * indefinitely. In both cases the packet must be freed with
+ * av_free_packet when it is no longer needed. For video, the packet contains
+ * exactly one frame. For audio, it contains an integer number of frames if each
+ * frame has a known fixed size (e.g. PCM or ADPCM data). If the audio frames
+ * have a variable size (e.g. MPEG audio), then it contains one frame.
  *
  * pkt->pts, pkt->dts and pkt->duration are always set to correct
  * values in AVStream.time_base units (and guessed if the format cannot
@@ -1712,10 +1737,10 @@
  * @param s media file handle
  * @param pkt The packet containing the data to be written. Libavformat takes
  * ownership of the data and will free it when it sees fit using the packet's
- * This can be NULL (at any time, not just at the end), to flush the
- * interleaving queues.
  * @ref AVPacket.destruct "destruct" field. The caller must not access the data
  * after this function returns, as it may already be freed.
+ * This can be NULL (at any time, not just at the end), to flush the
+ * interleaving queues.
  * Packet's @ref AVPacket.stream_index "stream_index" field must be set to the
  * index of the corresponding stream in @ref AVFormatContext.streams
  * "s.streams".
@@ -1741,7 +1766,7 @@
  * 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.
+ * May only be called after a successful call to avformat_write_header.
  *
  * @param s media file handle
  * @return 0 if OK, AVERROR_xxx on error
@@ -1778,9 +1803,9 @@
  * work in real time.
  * @param s          media file handle
  * @param stream     stream in the media file
- * @param dts[out]   DTS of the last packet output for the stream, in stream
+ * @param[out] dts   DTS of the last packet output for the stream, in stream
  *                   time_base units
- * @param wall[out]  absolute time when that packet whas output,
+ * @param[out] wall  absolute time when that packet whas output,
  *                   in microsecond
  * @return  0 if OK, AVERROR(ENOSYS) if the format does not support it
  * Note: some formats or devices may not allow to measure dts and wall
@@ -1813,7 +1838,7 @@
  *
  * @see av_hex_dump_log, av_pkt_dump2, av_pkt_dump_log2
  */
-void av_hex_dump(FILE *f, uint8_t *buf, int size);
+void av_hex_dump(FILE *f, const uint8_t *buf, int size);
 
 /**
  * Send a nice hexadecimal dump of a buffer to the log.
@@ -1827,7 +1852,7 @@
  *
  * @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);
+void av_hex_dump_log(void *avcl, int level, const uint8_t *buf, int size);
 
 /**
  * Send a nice dump of a packet to the specified file stream.
@@ -1952,6 +1977,9 @@
 /**
  * Generate an SDP for an RTP session.
  *
+ * Note, this overwrites the id values of AVStreams in the muxer contexts
+ * for getting unique dynamic payload types.
+ *
  * @param ac array of AVFormatContexts describing the RTP streams. If the
  *           array is composed by only one context, such context can contain
  *           multiple AVStreams (one AVStream per RTP stream). Otherwise,
diff --git a/libavformat/avidec.c b/libavformat/avidec.c
index b4c5fe8..974071c 100644
--- a/libavformat/avidec.c
+++ b/libavformat/avidec.c
@@ -626,7 +626,7 @@
                         pal_size = FFMIN(pal_size, st->codec->extradata_size);
                         pal_src = st->codec->extradata + st->codec->extradata_size - pal_size;
                         for (i = 0; i < pal_size/4; i++)
-                            ast->pal[i] = 0xFF<<24 | AV_RL32(pal_src+4*i);
+                            ast->pal[i] = 0xFFU<<24 | AV_RL32(pal_src+4*i);
                         ast->has_pal = 1;
                     }
 
@@ -681,10 +681,17 @@
                         av_log(s, AV_LOG_DEBUG, "overriding invalid dshow_block_align of %d\n", ast->dshow_block_align);
                         ast->dshow_block_align = 0;
                     }
+                    if(st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 1024 && ast->sample_size == 1024 ||
+                       st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 4096 && ast->sample_size == 4096 ||
+                       st->codec->codec_id == AV_CODEC_ID_MP3 && ast->dshow_block_align == 1152 && ast->sample_size == 1152) {
+                        av_log(s, AV_LOG_DEBUG, "overriding sample_size\n");
+                        ast->sample_size = 0;
+                    }
                     break;
                 case AVMEDIA_TYPE_SUBTITLE:
                     st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
                     st->request_probe= 1;
+                    avio_skip(pb, size);
                     break;
                 default:
                     st->codec->codec_type = AVMEDIA_TYPE_DATA;
@@ -1003,7 +1010,7 @@
                 avio_rl16(pb); //flags
 
                 for (; k <= last; k++)
-                    ast->pal[k] = 0xFF<<24 | avio_rb32(pb)>>8;// b + (g << 8) + (r << 16);
+                    ast->pal[k] = 0xFFU<<24 | avio_rb32(pb)>>8;// b + (g << 8) + (r << 16);
                 ast->has_pal= 1;
                 goto start_sync;
             } else if(   ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
@@ -1138,7 +1145,7 @@
             return err;
         size = err;
 
-        if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
+        if(ast->has_pal && pkt->size<(unsigned)INT_MAX/2){
             uint8_t *pal;
             pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
             if(!pal){
@@ -1265,6 +1272,11 @@
     avi->stream_index = -1;
     avio_seek(pb, idx1_pos, SEEK_SET);
 
+    if (s->nb_streams == 1 && s->streams[0]->codec->codec_tag == AV_RL32("MMES")){
+        first_packet_pos = 0;
+        data_offset = avi->movi_list;
+    }
+
     /* Read the entries and sort them in each stream component. */
     for(i = 0; i < nb_index_entries; i++) {
         if(url_feof(pb))
diff --git a/libavformat/avienc.c b/libavformat/avienc.c
index 0352f8b..15f0794 100644
--- a/libavformat/avienc.c
+++ b/libavformat/avienc.c
@@ -18,6 +18,9 @@
  * 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 "avformat.h"
 #include "internal.h"
 #include "avi.h"
@@ -26,6 +29,7 @@
 #include "libavutil/intreadwrite.h"
 #include "libavutil/dict.h"
 #include "libavutil/avassert.h"
+#include "libavutil/timestamp.h"
 
 /*
  * TODO:
@@ -106,19 +110,6 @@
     return tag;
 }
 
-static void avi_write_info_tag(AVIOContext *pb, const char *tag, const char *str)
-{
-    int len = strlen(str);
-    if (len > 0) {
-        len++;
-        ffio_wfourcc(pb, tag);
-        avio_wl32(pb, len);
-        avio_put_str(pb, str);
-        if (len & 1)
-            avio_w8(pb, 0);
-    }
-}
-
 static int avi_write_counters(AVFormatContext* s, int riff_id)
 {
     AVIOContext *pb = s->pb;
@@ -165,7 +156,7 @@
     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;
+        return AVERROR(EINVAL);
     }
 
     for(n=0;n<s->nb_streams;n++) {
@@ -256,6 +247,12 @@
 
         ff_parse_specific_params(stream, &au_byterate, &au_ssize, &au_scale);
 
+        if (   stream->codec_type == AVMEDIA_TYPE_VIDEO
+            && stream->codec_id != AV_CODEC_ID_XSUB
+            && au_byterate > 1000LL*au_scale) {
+            au_byterate = 600;
+            au_scale    = 1;
+        }
         avpriv_set_pts_info(s->streams[i], 64, au_scale, au_byterate);
         if(stream->codec_id == AV_CODEC_ID_XSUB)
             au_scale = au_byterate = 0;
@@ -285,6 +282,8 @@
         ff_end_tag(pb, strh);
 
       if(stream->codec_type != AVMEDIA_TYPE_DATA){
+          int ret;
+
         strf = ff_start_tag(pb, "strf");
         switch(stream->codec_type) {
         case AVMEDIA_TYPE_SUBTITLE:
@@ -295,16 +294,19 @@
             ff_put_bmp_header(pb, stream, ff_codec_bmp_tags, 0);
             break;
         case AVMEDIA_TYPE_AUDIO:
-            if (ff_put_wav_header(pb, stream) < 0) {
-                return -1;
+            if ((ret = ff_put_wav_header(pb, stream)) < 0) {
+                return ret;
             }
             break;
         default:
-            return -1;
+            av_log(s, AV_LOG_ERROR,
+                   "Invalid or not supported codec type '%s' found in the input\n",
+                   (char *)av_x_if_null(av_get_media_type_string(stream->codec_type), "?"));
+            return AVERROR(EINVAL);
         }
         ff_end_tag(pb, strf);
         if ((t = av_dict_get(s->streams[i]->metadata, "title", NULL, 0))) {
-            avi_write_info_tag(s->pb, "strn", t->value);
+            ff_riff_write_info_tag(s->pb, "strn", t->value);
             t = NULL;
         }
       }
@@ -381,14 +383,7 @@
 
     ff_end_tag(pb, list1);
 
-    list2 = ff_start_tag(pb, "LIST");
-    ffio_wfourcc(pb, "INFO");
-    ff_metadata_conv(&s->metadata, ff_riff_info_conv, NULL);
-    for (i = 0; *ff_riff_tags[i]; i++) {
-        if ((t = av_dict_get(s->metadata, ff_riff_tags[i], NULL, AV_DICT_MATCH_CASE)))
-            avi_write_info_tag(s->pb, t->key, t->value);
-    }
-    ff_end_tag(pb, list2);
+    ff_riff_write_info(s);
 
     /* some padding for easier tag editing */
     list2 = ff_start_tag(pb, "JUNK");
@@ -414,8 +409,11 @@
 
     av_assert0(pb->seekable);
 
-    if (avi->riff_id > AVI_MASTER_INDEX_SIZE)
-        return -1;
+    if (avi->riff_id > AVI_MASTER_INDEX_SIZE) {
+        av_log(s, AV_LOG_ERROR, "Invalid riff index %d > %d\n",
+               avi->riff_id, AVI_MASTER_INDEX_SIZE);
+        return AVERROR(EINVAL);
+    }
 
     for (i=0;i<s->nb_streams;i++) {
         AVIStream *avist= s->streams[i]->priv_data;
@@ -524,12 +522,12 @@
     AVCodecContext *enc= s->streams[stream_index]->codec;
     int size= pkt->size;
 
-//    av_log(s, AV_LOG_DEBUG, "%"PRId64" %d %d\n", pkt->dts, avist->packet_count, stream_index);
+    av_dlog(s, "dts:%s packet_count:%d stream_index:%d\n", av_ts2str(pkt->dts), avist->packet_count, stream_index);
     while(enc->block_align==0 && pkt->dts != AV_NOPTS_VALUE && pkt->dts > avist->packet_count && enc->codec_id != AV_CODEC_ID_XSUB){
         AVPacket empty_packet;
 
         if(pkt->dts - avist->packet_count > 60000){
-            av_log(s, AV_LOG_ERROR, "Too large number of skiped frames %"PRId64"\n", pkt->dts - avist->packet_count);
+            av_log(s, AV_LOG_ERROR, "Too large number of skipped frames %"PRId64" > 60000\n", pkt->dts - avist->packet_count);
             return AVERROR(EINVAL);
         }
 
@@ -538,7 +536,7 @@
         empty_packet.data= NULL;
         empty_packet.stream_index= stream_index;
         avi_write_packet(s, &empty_packet);
-//        av_log(s, AV_LOG_DEBUG, "dup %"PRId64" %d\n", pkt->dts, avist->packet_count);
+        av_dlog(s, "dup dts:%s packet_count:%d\n", av_ts2str(pkt->dts), avist->packet_count);
     }
     avist->packet_count++;
 
@@ -570,10 +568,10 @@
         if (idx->ents_allocated <= idx->entry) {
             idx->cluster = av_realloc_f(idx->cluster, sizeof(void*), cl+1);
             if (!idx->cluster)
-                return -1;
+                return AVERROR(ENOMEM);
             idx->cluster[cl] = av_malloc(AVI_INDEX_CLUSTER_SIZE*sizeof(AVIIentry));
             if (!idx->cluster[cl])
-                return -1;
+                return AVERROR(ENOMEM);
             idx->ents_allocated += AVI_INDEX_CLUSTER_SIZE;
         }
 
diff --git a/libavformat/avio.c b/libavformat/avio.c
index abc7072..6d8a8bb 100644
--- a/libavformat/avio.c
+++ b/libavformat/avio.c
@@ -85,11 +85,11 @@
 
 const char *avio_enum_protocols(void **opaque, int output)
 {
-    URLProtocol **p = (URLProtocol **)opaque;
-    *p = ffurl_protocol_next(*p);
-    if (!*p) return NULL;
-    if ((output && (*p)->url_write) || (!output && (*p)->url_read))
-        return (*p)->name;
+    URLProtocol *p;
+    *opaque = ffurl_protocol_next(*opaque);
+    if (!(p = *opaque)) return NULL;
+    if ((output && p->url_write) || (!output && p->url_read))
+        return p->name;
     return avio_enum_protocols(opaque, output);
 }
 
@@ -156,6 +156,7 @@
                     av_log(uc, AV_LOG_ERROR, "Error parsing options string %s\n", start);
                     av_freep(&uc->priv_data);
                     av_freep(&uc);
+                    err = AVERROR(EINVAL);
                     goto fail;
                 }
                 memmove(start, key+1, strlen(key));
@@ -395,7 +396,7 @@
     if (!h->prot->url_get_multi_file_handle) {
         if (!h->prot->url_get_file_handle)
             return AVERROR(ENOSYS);
-        *handles = av_malloc(sizeof(*handles));
+        *handles = av_malloc(sizeof(**handles));
         if (!*handles)
             return AVERROR(ENOMEM);
         *numhandles = 1;
diff --git a/libavformat/avio.h b/libavformat/avio.h
index b16d26f..17b341d 100644
--- a/libavformat/avio.h
+++ b/libavformat/avio.h
@@ -395,10 +395,25 @@
  * resource.
  *
  * @return 0 on success, an AVERROR < 0 on error.
+ * @see avio_closep
  */
 int avio_close(AVIOContext *s);
 
 /**
+ * Close the resource accessed by the AVIOContext *s, free it
+ * and set the pointer pointing to it to NULL.
+ * This function can only be used if s was opened by avio_open().
+ *
+ * The internal buffer is automatically flushed before closing the
+ * resource.
+ *
+ * @return 0 on success, an AVERROR < 0 on error.
+ * @see avio_close
+ */
+int avio_closep(AVIOContext **s);
+
+
+/**
  * Open a write only memory stream.
  *
  * @param s new IO context
diff --git a/libavformat/avio_internal.h b/libavformat/avio_internal.h
index df614b2..3c0fc93 100644
--- a/libavformat/avio_internal.h
+++ b/libavformat/avio_internal.h
@@ -64,7 +64,7 @@
  * @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);
+int ffio_rewind_with_probe_data(AVIOContext *s, unsigned char **buf, int buf_size);
 
 uint64_t ffio_read_varlen(AVIOContext *bc);
 
diff --git a/libavformat/aviobuf.c b/libavformat/aviobuf.c
index 282a62e..906415d 100644
--- a/libavformat/aviobuf.c
+++ b/libavformat/aviobuf.c
@@ -144,6 +144,7 @@
 
 void avio_w8(AVIOContext *s, int b)
 {
+    av_assert2(b>=-128 && b<=255);
     *s->buf_ptr++ = b;
     if (s->buf_ptr >= s->buf_end)
         flush_buffer(s);
@@ -228,12 +229,10 @@
     } else {
         int64_t res;
 
-#if CONFIG_MUXERS || CONFIG_NETWORK
         if (s->write_flag) {
             flush_buffer(s);
             s->must_flush = 1;
         }
-#endif /* CONFIG_MUXERS || CONFIG_NETWORK */
         if (!s->seek)
             return AVERROR(EPIPE);
         if ((res = s->seek(s->opaque, offset, SEEK_SET)) < 0)
@@ -285,18 +284,18 @@
 
 void avio_wl32(AVIOContext *s, unsigned int val)
 {
-    avio_w8(s, val);
-    avio_w8(s, val >> 8);
-    avio_w8(s, val >> 16);
-    avio_w8(s, val >> 24);
+    avio_w8(s, (uint8_t) val       );
+    avio_w8(s, (uint8_t)(val >> 8 ));
+    avio_w8(s, (uint8_t)(val >> 16));
+    avio_w8(s,           val >> 24 );
 }
 
 void avio_wb32(AVIOContext *s, unsigned int val)
 {
-    avio_w8(s, val >> 24);
-    avio_w8(s, val >> 16);
-    avio_w8(s, val >> 8);
-    avio_w8(s, val);
+    avio_w8(s,           val >> 24 );
+    avio_w8(s, (uint8_t)(val >> 16));
+    avio_w8(s, (uint8_t)(val >> 8 ));
+    avio_w8(s, (uint8_t) val       );
 }
 
 int avio_put_str(AVIOContext *s, const char *str)
@@ -340,7 +339,7 @@
     int i= ff_get_v_length(val);
 
     while(--i>0)
-        avio_w8(bc, 128 | (val>>(7*i)));
+        avio_w8(bc, 128 | (uint8_t)(val>>(7*i)));
 
     avio_w8(bc, val&127);
 }
@@ -359,26 +358,26 @@
 
 void avio_wl16(AVIOContext *s, unsigned int val)
 {
-    avio_w8(s, val);
-    avio_w8(s, val >> 8);
+    avio_w8(s, (uint8_t)val);
+    avio_w8(s, (int)val >> 8);
 }
 
 void avio_wb16(AVIOContext *s, unsigned int val)
 {
-    avio_w8(s, val >> 8);
-    avio_w8(s, val);
+    avio_w8(s, (int)val >> 8);
+    avio_w8(s, (uint8_t)val);
 }
 
 void avio_wl24(AVIOContext *s, unsigned int val)
 {
     avio_wl16(s, val & 0xffff);
-    avio_w8(s, val >> 16);
+    avio_w8(s, (int)val >> 16);
 }
 
 void avio_wb24(AVIOContext *s, unsigned int val)
 {
-    avio_wb16(s, val >> 8);
-    avio_w8(s, val);
+    avio_wb16(s, (int)val >> 8);
+    avio_w8(s, (uint8_t)val);
 }
 
 /* Input stream */
@@ -726,27 +725,32 @@
     return 0;
 }
 
-int ffio_rewind_with_probe_data(AVIOContext *s, unsigned char *buf, int buf_size)
+int ffio_rewind_with_probe_data(AVIOContext *s, unsigned char **bufp, int buf_size)
 {
     int64_t buffer_start;
     int buffer_size;
     int overlap, new_size, alloc_size;
+    uint8_t *buf = *bufp;
 
-    if (s->write_flag)
+    if (s->write_flag) {
+        av_freep(bufp);
         return AVERROR(EINVAL);
+    }
 
     buffer_size = s->buf_end - s->buffer;
 
     /* the buffers must touch or overlap */
-    if ((buffer_start = s->pos - buffer_size) > buf_size)
+    if ((buffer_start = s->pos - buffer_size) > buf_size) {
+        av_freep(bufp);
         return AVERROR(EINVAL);
+    }
 
     overlap = buf_size - buffer_start;
     new_size = buf_size + buffer_size - overlap;
 
     alloc_size = FFMAX(s->buffer_size, new_size);
     if (alloc_size > buf_size)
-        if (!(buf = av_realloc_f(buf, 1, alloc_size)))
+        if (!(buf = (*bufp) = av_realloc_f(buf, 1, alloc_size)))
             return AVERROR(ENOMEM);
 
     if (new_size > buf_size) {
@@ -803,6 +807,13 @@
     return ffurl_close(h);
 }
 
+int avio_closep(AVIOContext **s)
+{
+    int ret = avio_close(*s);
+    *s = NULL;
+    return ret;
+}
+
 int avio_printf(AVIOContext *s, const char *fmt, ...)
 {
     va_list ap;
diff --git a/libavformat/avr.c b/libavformat/avr.c
new file mode 100644
index 0000000..d3b23db
--- /dev/null
+++ b/libavformat/avr.c
@@ -0,0 +1,99 @@
+/*
+ * AVR demuxer
+ * Copyright (c) 2012 Paul B Mahol
+ *
+ * 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/intreadwrite.h"
+#include "avformat.h"
+#include "internal.h"
+#include "rawdec.h"
+#include "pcm.h"
+
+static int avr_probe(AVProbeData *p)
+{
+    if (AV_RL32(p->buf) == MKTAG('2', 'B', 'I', 'T'))
+        return AVPROBE_SCORE_MAX / 2;
+    return 0;
+}
+
+static int avr_read_header(AVFormatContext *s)
+{
+    uint16_t chan, sign, bps;
+    AVStream *st;
+
+    st = avformat_new_stream(s, NULL);
+    if (!st)
+        return AVERROR(ENOMEM);
+
+    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+
+    avio_skip(s->pb, 4); // magic
+    avio_skip(s->pb, 8); // sample_name
+
+    chan = avio_rb16(s->pb);
+    if (!chan) {
+        st->codec->channels = 1;
+    } else if (chan == 0xFFFFu) {
+        st->codec->channels = 2;
+    } else {
+        av_log_ask_for_sample(s, "unknown number of channels\n");
+        return AVERROR_PATCHWELCOME;
+    }
+
+    st->codec->bits_per_coded_sample = bps = avio_rb16(s->pb);
+
+    sign = avio_rb16(s->pb);
+
+    avio_skip(s->pb, 2); // loop
+    avio_skip(s->pb, 2); // midi
+    avio_skip(s->pb, 1); // replay speed
+
+    st->codec->sample_rate = avio_rb24(s->pb);
+    avio_skip(s->pb, 4 * 3);
+    avio_skip(s->pb, 2 * 3);
+    avio_skip(s->pb, 20);
+    avio_skip(s->pb, 64);
+
+    if (!sign && bps == 8) {
+        st->codec->codec_id = AV_CODEC_ID_PCM_U8;
+    } else if (!sign && bps == 16) {
+        st->codec->codec_id = AV_CODEC_ID_PCM_U16BE;
+    } else if (sign == 0xFFFFu && bps == 8) {
+        st->codec->codec_id = AV_CODEC_ID_PCM_S8;
+    } else if (sign == 0xFFFFu && bps == 16) {
+        st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
+    } else {
+        av_log_ask_for_sample(s, "unknown bits per sample\n");
+        return AVERROR_PATCHWELCOME;
+    }
+
+    avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
+    return 0;
+}
+
+AVInputFormat ff_avr_demuxer = {
+    .name           = "avr",
+    .long_name      = NULL_IF_CONFIG_SMALL("AVR (Audio Visual Research)"),
+    .read_probe     = avr_probe,
+    .read_header    = avr_read_header,
+    .read_packet    = ff_raw_read_partial_packet,
+    .read_seek      = ff_pcm_read_seek,
+    .extensions     = "avr",
+    .flags          = AVFMT_GENERIC_INDEX,
+};
diff --git a/libavformat/bethsoftvid.c b/libavformat/bethsoftvid.c
index 1a83c79..831bdd2 100644
--- a/libavformat/bethsoftvid.c
+++ b/libavformat/bethsoftvid.c
@@ -27,6 +27,7 @@
  * @see http://www.svatopluk.com/andux/docs/dfvid.html
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "internal.h"
@@ -187,7 +188,8 @@
     if (vid->palette) {
         uint8_t *pdata = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE,
                                                  BVID_PALETTE_SIZE);
-        memcpy(pdata, vid->palette, BVID_PALETTE_SIZE);
+        if (pdata)
+            memcpy(pdata, vid->palette, BVID_PALETTE_SIZE);
         av_freep(&vid->palette);
     }
 
@@ -208,7 +210,7 @@
     int ret_value;
 
     if(vid->is_finished || url_feof(pb))
-        return AVERROR(EIO);
+        return AVERROR_EOF;
 
     block_type = avio_r8(pb);
     switch(block_type){
@@ -239,6 +241,7 @@
                 st->codec->codec_type            = AVMEDIA_TYPE_AUDIO;
                 st->codec->codec_id              = AV_CODEC_ID_PCM_U8;
                 st->codec->channels              = 1;
+                st->codec->channel_layout        = AV_CH_LAYOUT_MONO;
                 st->codec->bits_per_coded_sample = 8;
                 st->codec->sample_rate           = vid->sample_rate;
                 st->codec->bit_rate              = 8 * st->codec->sample_rate;
diff --git a/libavformat/bfi.c b/libavformat/bfi.c
index c03a1de..d26d848 100644
--- a/libavformat/bfi.c
+++ b/libavformat/bfi.c
@@ -26,6 +26,7 @@
  * @see http://wiki.multimedia.cx/index.php?title=BFI
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "internal.h"
@@ -90,12 +91,13 @@
     avpriv_set_pts_info(vstream, 32, 1, fps);
     vstream->codec->codec_type = AVMEDIA_TYPE_VIDEO;
     vstream->codec->codec_id   = AV_CODEC_ID_BFI;
-    vstream->codec->pix_fmt    = PIX_FMT_PAL8;
+    vstream->codec->pix_fmt    = AV_PIX_FMT_PAL8;
 
     /* Set up the audio codec now... */
     astream->codec->codec_type      = AVMEDIA_TYPE_AUDIO;
     astream->codec->codec_id        = AV_CODEC_ID_PCM_U8;
     astream->codec->channels        = 1;
+    astream->codec->channel_layout  = AV_CH_LAYOUT_MONO;
     astream->codec->bits_per_coded_sample = 8;
     astream->codec->bit_rate        =
         astream->codec->sample_rate * astream->codec->bits_per_coded_sample;
@@ -111,7 +113,7 @@
     AVIOContext *pb = s->pb;
     int ret, audio_offset, video_offset, chunk_size, audio_size = 0;
     if (bfi->nframes == 0 || url_feof(pb)) {
-        return AVERROR(EIO);
+        return AVERROR_EOF;
     }
 
     /* If all previous chunks were completely read, then find a new one... */
diff --git a/libavformat/bink.c b/libavformat/bink.c
index 9c90480..c77a8f8 100644
--- a/libavformat/bink.c
+++ b/libavformat/bink.c
@@ -28,6 +28,7 @@
  *  http://wiki.multimedia.cx/index.php?title=Bink_Container
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "internal.h"
@@ -143,7 +144,13 @@
             flags = avio_rl16(pb);
             ast->codec->codec_id = flags & BINK_AUD_USEDCT ?
                                    AV_CODEC_ID_BINKAUDIO_DCT : AV_CODEC_ID_BINKAUDIO_RDFT;
-            ast->codec->channels = flags & BINK_AUD_STEREO ? 2 : 1;
+            if (flags & BINK_AUD_STEREO) {
+                ast->codec->channels       = 2;
+                ast->codec->channel_layout = AV_CH_LAYOUT_STEREO;
+            } else {
+                ast->codec->channels       = 1;
+                ast->codec->channel_layout = AV_CH_LAYOUT_MONO;
+            }
             ast->codec->extradata = av_mallocz(4 + FF_INPUT_BUFFER_PADDING_SIZE);
             if (!ast->codec->extradata)
                 return AVERROR(ENOMEM);
@@ -194,7 +201,7 @@
         AVStream *st = s->streams[0]; // stream 0 is video stream with index
 
         if (bink->video_pts >= st->duration)
-            return AVERROR(EIO);
+            return AVERROR_EOF;
 
         index_entry = av_index_search_timestamp(st, bink->video_pts,
                                                 AVSEEK_FLAG_ANY);
diff --git a/libavformat/bit.c b/libavformat/bit.c
index 03c6152..9f6ea4a 100644
--- a/libavformat/bit.c
+++ b/libavformat/bit.c
@@ -90,7 +90,8 @@
     if(ret != 8 * packet_size * sizeof(uint16_t))
         return AVERROR(EIO);
 
-    av_new_packet(pkt, packet_size);
+    if (av_new_packet(pkt, packet_size) < 0)
+        return AVERROR(ENOMEM);
 
     init_put_bits(&pbo, pkt->data, packet_size);
     for(j=0; j < packet_size; j++)
diff --git a/libavformat/bmv.c b/libavformat/bmv.c
index 474f4e3..ce157e8 100644
--- a/libavformat/bmv.c
+++ b/libavformat/bmv.c
@@ -19,6 +19,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "avformat.h"
 #include "internal.h"
 
@@ -50,7 +51,7 @@
     st->codec->codec_id   = AV_CODEC_ID_BMV_VIDEO;
     st->codec->width      = 640;
     st->codec->height     = 429;
-    st->codec->pix_fmt    = PIX_FMT_PAL8;
+    st->codec->pix_fmt    = AV_PIX_FMT_PAL8;
     avpriv_set_pts_info(st, 16, 1, 12);
     ast = avformat_new_stream(s, 0);
     if (!ast)
@@ -58,6 +59,7 @@
     ast->codec->codec_type      = AVMEDIA_TYPE_AUDIO;
     ast->codec->codec_id        = AV_CODEC_ID_BMV_AUDIO;
     ast->codec->channels        = 2;
+    ast->codec->channel_layout  = AV_CH_LAYOUT_STEREO;
     ast->codec->sample_rate     = 22050;
     avpriv_set_pts_info(ast, 16, 1, 22050);
 
diff --git a/libavformat/brstm.c b/libavformat/brstm.c
new file mode 100644
index 0000000..a4db35a
--- /dev/null
+++ b/libavformat/brstm.c
@@ -0,0 +1,294 @@
+/*
+ * BRSTM demuxer
+ * Copyright (c) 2012 Paul B Mahol
+ *
+ * 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/intreadwrite.h"
+#include "libavcodec/bytestream.h"
+#include "avformat.h"
+#include "internal.h"
+
+typedef struct BRSTMDemuxContext {
+    uint32_t    block_size;
+    uint32_t    block_count;
+    uint32_t    current_block;
+    uint32_t    samples_per_block;
+    uint32_t    last_block_used_bytes;
+    uint8_t     *table;
+    uint8_t     *adpc;
+} BRSTMDemuxContext;
+
+static int probe(AVProbeData *p)
+{
+    if (AV_RL32(p->buf) == MKTAG('R','S','T','M') &&
+        (AV_RL16(p->buf + 4) == 0xFFFE ||
+         AV_RL16(p->buf + 4) == 0xFEFF))
+        return AVPROBE_SCORE_MAX / 3 * 2;
+    return 0;
+}
+
+static int read_close(AVFormatContext *s)
+{
+    BRSTMDemuxContext *b = s->priv_data;
+
+    av_freep(&b->table);
+    av_freep(&b->adpc);
+
+    return 0;
+}
+
+static int read_header(AVFormatContext *s)
+{
+    BRSTMDemuxContext *b = s->priv_data;
+    int bom, major, minor, codec, chunk;
+    int64_t pos, h1offset, toffset;
+    uint32_t size, start, asize;
+    AVStream *st;
+    int ret = AVERROR_EOF;
+
+    st = avformat_new_stream(s, NULL);
+    if (!st)
+        return AVERROR(ENOMEM);
+    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+
+    avio_skip(s->pb, 4);
+
+    bom = avio_rb16(s->pb);
+    if (bom != 0xFEFF && bom != 0xFFFE) {
+        av_log(s, AV_LOG_ERROR, "invalid byte order: %X\n", bom);
+        return AVERROR_INVALIDDATA;
+    }
+    if (bom == 0xFFFE) {
+        av_log_ask_for_sample(s, "unsupported byte order");
+        return AVERROR_PATCHWELCOME;
+    }
+
+    major = avio_r8(s->pb);
+    minor = avio_r8(s->pb);
+    avio_skip(s->pb, 4); // size of file
+    size = avio_rb16(s->pb);
+    if (size < 14)
+        return AVERROR_INVALIDDATA;
+
+    avio_skip(s->pb, size - 14);
+    pos = avio_tell(s->pb);
+    if (avio_rl32(s->pb) != MKTAG('H','E','A','D'))
+        return AVERROR_INVALIDDATA;
+    size = avio_rb32(s->pb);
+    if (size < 256)
+        return AVERROR_INVALIDDATA;
+    avio_skip(s->pb, 4); // unknown
+    h1offset = avio_rb32(s->pb);
+    if (h1offset > size)
+        return AVERROR_INVALIDDATA;
+    avio_skip(s->pb, 12);
+    toffset = avio_rb32(s->pb) + 16LL;
+    if (toffset > size)
+        return AVERROR_INVALIDDATA;
+
+    avio_skip(s->pb, pos + h1offset + 8 - avio_tell(s->pb));
+    codec = avio_r8(s->pb);
+
+    switch (codec) {
+    case 0: codec = AV_CODEC_ID_PCM_S8_PLANAR;    break;
+    case 1: codec = AV_CODEC_ID_PCM_S16BE_PLANAR; break;
+    case 2: codec = AV_CODEC_ID_ADPCM_THP;        break;
+    default:
+        av_log_ask_for_sample(s, "unsupported codec: %d", codec);
+        return AVERROR_PATCHWELCOME;
+    }
+
+    avio_skip(s->pb, 1); // loop flag
+    st->codec->codec_id = codec;
+    st->codec->channels = avio_r8(s->pb);
+    if (!st->codec->channels)
+        return AVERROR_INVALIDDATA;
+
+    avio_skip(s->pb, 1); // padding
+    st->codec->sample_rate = avio_rb16(s->pb);
+    if (!st->codec->sample_rate)
+        return AVERROR_INVALIDDATA;
+
+    avio_skip(s->pb, 2); // padding
+    avio_skip(s->pb, 4); // loop start sample
+    st->start_time = 0;
+    st->duration = avio_rb32(s->pb);
+    avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
+
+    start = avio_rb32(s->pb);
+    b->current_block = 0;
+    b->block_count = avio_rb32(s->pb);
+    if (b->block_count > UINT16_MAX) {
+        av_log(s, AV_LOG_WARNING, "too many blocks: %u\n", b->block_count);
+        return AVERROR_INVALIDDATA;
+    }
+
+    b->block_size = avio_rb32(s->pb);
+    if (b->block_size > UINT16_MAX / st->codec->channels)
+        return AVERROR_INVALIDDATA;
+    b->block_size *= st->codec->channels;
+
+    b->samples_per_block = avio_rb32(s->pb);
+    b->last_block_used_bytes = avio_rb32(s->pb);
+    if (b->last_block_used_bytes > UINT16_MAX / st->codec->channels)
+        return AVERROR_INVALIDDATA;
+    b->last_block_used_bytes *= st->codec->channels;
+
+    avio_skip(s->pb, 4); // last block samples
+    avio_skip(s->pb, 4); // last block size
+
+    if (codec == AV_CODEC_ID_ADPCM_THP) {
+        int ch;
+
+        avio_skip(s->pb, pos + toffset - avio_tell(s->pb));
+        toffset = avio_rb32(s->pb) + 16LL;
+        if (toffset > size)
+            return AVERROR_INVALIDDATA;
+
+        avio_skip(s->pb, pos + toffset - avio_tell(s->pb));
+        b->table = av_mallocz(32 * st->codec->channels);
+        if (!b->table)
+            return AVERROR(ENOMEM);
+
+        for (ch = 0; ch < st->codec->channels; ch++) {
+            if (avio_read(s->pb, b->table + ch * 32, 32) != 32) {
+                ret = AVERROR_INVALIDDATA;
+                goto fail;
+            }
+            avio_skip(s->pb, 24);
+        }
+    }
+
+    if (size < (avio_tell(s->pb) - pos)) {
+        ret = AVERROR_INVALIDDATA;
+        goto fail;
+    }
+    avio_skip(s->pb, size - (avio_tell(s->pb) - pos));
+
+    while (!url_feof(s->pb)) {
+        chunk = avio_rl32(s->pb);
+        size  = avio_rb32(s->pb);
+        if (size < 8) {
+            ret = AVERROR_INVALIDDATA;
+            goto fail;
+        }
+        size -= 8;
+        switch (chunk) {
+        case MKTAG('A','D','P','C'):
+            if (codec != AV_CODEC_ID_ADPCM_THP)
+                goto skip;
+
+            asize = b->block_count * st->codec->channels * 4;
+            if (size < asize) {
+                ret = AVERROR_INVALIDDATA;
+                goto fail;
+            }
+            if (b->adpc) {
+                av_log(s, AV_LOG_WARNING, "skipping additonal ADPC chunk\n");
+                goto skip;
+            } else {
+                b->adpc = av_mallocz(asize);
+                if (!b->adpc) {
+                    ret = AVERROR(ENOMEM);
+                    goto fail;
+                }
+                avio_read(s->pb, b->adpc, asize);
+                avio_skip(s->pb, size - asize);
+            }
+            break;
+        case MKTAG('D','A','T','A'):
+            if ((start < avio_tell(s->pb)) ||
+                (!b->adpc && codec == AV_CODEC_ID_ADPCM_THP)) {
+                ret = AVERROR_INVALIDDATA;
+                goto fail;
+            }
+            avio_skip(s->pb, start - avio_tell(s->pb));
+            return 0;
+        default:
+            av_log(s, AV_LOG_WARNING, "skipping unknown chunk: %X\n", chunk);
+skip:
+            avio_skip(s->pb, size);
+        }
+    }
+
+fail:
+    read_close(s);
+
+    return ret;
+}
+
+static int read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    AVCodecContext *codec = s->streams[0]->codec;
+    BRSTMDemuxContext *b = s->priv_data;
+    uint32_t samples, size;
+    int ret;
+
+    if (url_feof(s->pb))
+        return AVERROR_EOF;
+    b->current_block++;
+    if (b->current_block == b->block_count) {
+        size    = b->last_block_used_bytes;
+        samples = size / 16 * 14;
+    } else if (b->current_block < b->block_count) {
+        size    = b->block_size;
+        samples = b->samples_per_block;
+    } else {
+        return AVERROR_EOF;
+    }
+
+    if (codec->codec_id == AV_CODEC_ID_ADPCM_THP) {
+        uint8_t *dst;
+
+        if (av_new_packet(pkt, 8 + (32 + 4) * codec->channels + size) < 0)
+            return AVERROR(ENOMEM);
+        dst = pkt->data;
+        bytestream_put_be32(&dst, size);
+        bytestream_put_be32(&dst, samples);
+        bytestream_put_buffer(&dst, b->table, 32 * codec->channels);
+        bytestream_put_buffer(&dst, b->adpc + 4 * codec->channels *
+                                    (b->current_block - 1), 4 * codec->channels);
+
+        ret = avio_read(s->pb, dst, size);
+        if (ret < 0) {
+            av_free_packet(pkt);
+            return ret;
+        }
+        pkt->duration = samples;
+    } else {
+        ret = av_get_packet(s->pb, pkt, size);
+        if (ret < 0)
+            return ret;
+    }
+
+    pkt->stream_index = 0;
+
+    return ret;
+}
+
+AVInputFormat ff_brstm_demuxer = {
+    .name           = "brstm",
+    .long_name      = NULL_IF_CONFIG_SMALL("BRSTM (Binary Revolution Stream)"),
+    .priv_data_size = sizeof(BRSTMDemuxContext),
+    .read_probe     = probe,
+    .read_header    = read_header,
+    .read_packet    = read_packet,
+    .read_close     = read_close,
+    .extensions     = "brstm",
+};
diff --git a/libavformat/c93.c b/libavformat/c93.c
index 66516e9..93a61be 100644
--- a/libavformat/c93.c
+++ b/libavformat/c93.c
@@ -133,7 +133,7 @@
     }
     if (c93->current_frame >= br->frames) {
         if (c93->current_block >= 511 || !br[1].length)
-            return AVERROR(EIO);
+            return AVERROR_EOF;
         br++;
         c93->current_block++;
         c93->current_frame = 0;
diff --git a/libavformat/cache.c b/libavformat/cache.c
index 2cfc396..35f81e8 100644
--- a/libavformat/cache.c
+++ b/libavformat/cache.c
@@ -114,7 +114,9 @@
         c->pos= pos;
         return pos;
     }else{
-        lseek(c->fd, c->pos, SEEK_SET);
+        if(lseek(c->fd, c->pos, SEEK_SET) < 0) {
+            av_log(h, AV_LOG_ERROR, "Failure to seek in cache\n");
+        }
         return AVERROR(EPIPE);
     }
 }
diff --git a/libavformat/caf.c b/libavformat/caf.c
index 5f490d8..c1ecc94 100644
--- a/libavformat/caf.c
+++ b/libavformat/caf.c
@@ -44,6 +44,7 @@
   /*{ AV_CODEC_ID_DVAUDIO,         MKTAG('d','v','c','a') },*/
     { AV_CODEC_ID_GSM,             MKTAG('a','g','s','m') },
     { AV_CODEC_ID_GSM_MS,          MKTAG('m','s', 0, '1') },
+    { AV_CODEC_ID_ILBC,            MKTAG('i','l','b','c') },
     { AV_CODEC_ID_MACE3,           MKTAG('M','A','C','3') },
     { AV_CODEC_ID_MACE6,           MKTAG('M','A','C','6') },
     { AV_CODEC_ID_MP1,             MKTAG('.','m','p','1') },
diff --git a/libavformat/cafdec.c b/libavformat/cafdec.c
index a576dac..718942b 100644
--- a/libavformat/cafdec.c
+++ b/libavformat/cafdec.c
@@ -27,7 +27,6 @@
 
 #include "avformat.h"
 #include "internal.h"
-#include "riff.h"
 #include "isom.h"
 #include "mov_chan.h"
 #include "libavutil/intreadwrite.h"
@@ -225,7 +224,7 @@
     AVStream *st;
     uint32_t tag = 0;
     int found_data, ret;
-    int64_t size;
+    int64_t size, pos;
 
     avio_skip(pb, 8); /* magic, version, file flags */
 
@@ -254,6 +253,7 @@
 
         tag  = avio_rb32(pb);
         size = avio_rb64(pb);
+        pos  = avio_tell(pb);
         if (url_feof(pb))
             break;
 
@@ -296,9 +296,14 @@
         case MKBETAG('f','r','e','e'):
             if (size < 0)
                 return AVERROR_INVALIDDATA;
-            avio_skip(pb, size);
             break;
         }
+
+        if (size > 0) {
+            if (pos + size < pos)
+                return AVERROR_INVALIDDATA;
+            avio_skip(pb, FFMAX(0, pos + size - avio_tell(pb)));
+        }
     }
 
     if (!found_data)
@@ -337,12 +342,14 @@
     int64_t left      = CAF_MAX_PKT_SIZE;
 
     if (url_feof(pb))
-        return AVERROR(EIO);
+        return AVERROR_EOF;
 
     /* don't read past end of data chunk */
     if (caf->data_size > 0) {
         left = (caf->data_start + caf->data_size) - avio_tell(pb);
-        if (left <= 0)
+        if (!left)
+            return AVERROR_EOF;
+        if (left < 0)
             return AVERROR(EIO);
     }
 
@@ -393,7 +400,7 @@
 
     if (caf->frames_per_packet > 0 && caf->bytes_per_packet > 0) {
         /* calculate new byte position based on target frame position */
-        pos = caf->bytes_per_packet * timestamp / caf->frames_per_packet;
+        pos = caf->bytes_per_packet * (timestamp / caf->frames_per_packet);
         if (caf->data_size > 0)
             pos = FFMIN(pos, caf->data_size);
         packet_cnt = pos / caf->bytes_per_packet;
diff --git a/libavformat/cafenc.c b/libavformat/cafenc.c
index fa8d583..92b61c9 100644
--- a/libavformat/cafenc.c
+++ b/libavformat/cafenc.c
@@ -25,6 +25,7 @@
 #include "isom.h"
 #include "avio_internal.h"
 #include "libavutil/intfloat.h"
+#include "libavutil/dict.h"
 
 typedef struct {
     int64_t data;
@@ -74,6 +75,7 @@
         return 64;
     case AV_CODEC_ID_AMR_NB:
     case AV_CODEC_ID_GSM:
+    case AV_CODEC_ID_ILBC:
     case AV_CODEC_ID_QCELP:
         return 160;
     case AV_CODEC_ID_GSM_MS:
@@ -102,7 +104,9 @@
     AVIOContext *pb = s->pb;
     AVCodecContext *enc = s->streams[0]->codec;
     CAFContext *caf = s->priv_data;
+    AVDictionaryEntry *t = NULL;
     unsigned int codec_tag = ff_codec_get_tag(ff_codec_caf_tags, enc->codec_id);
+    int64_t chunk_size = 0;
 
     switch (enc->codec_id) {
     case AV_CODEC_ID_AAC:
@@ -180,6 +184,20 @@
         avio_write(pb, enc->extradata, enc->extradata_size);
     }
 
+    if (av_dict_count(s->metadata)) {
+        ffio_wfourcc(pb, "info"); //< Information chunk
+        while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX))) {
+            chunk_size += strlen(t->key) + strlen(t->value) + 2;
+        }
+        avio_wb64(pb, chunk_size + 4);
+        avio_wb32(pb, av_dict_count(s->metadata));
+        t = NULL;
+        while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX))) {
+            avio_put_str(pb, t->key);
+            avio_put_str(pb, t->value);
+        }
+    }
+
     ffio_wfourcc(pb, "data"); //< Audio Data chunk
     caf->data = avio_tell(pb);
     avio_wb64(pb, -1);        //< mChunkSize
@@ -249,7 +267,7 @@
 
 AVOutputFormat ff_caf_muxer = {
     .name           = "caf",
-    .long_name      = NULL_IF_CONFIG_SMALL("Apple Core Audio Format"),
+    .long_name      = NULL_IF_CONFIG_SMALL("Apple CAF (Core Audio Format)"),
     .mime_type      = "audio/x-caf",
     .extensions     = "caf",
     .priv_data_size = sizeof(CAFContext),
@@ -258,5 +276,5 @@
     .write_header   = caf_write_header,
     .write_packet   = caf_write_packet,
     .write_trailer  = caf_write_trailer,
-    .codec_tag= (const AVCodecTag* const []){ff_codec_caf_tags, 0},
+    .codec_tag      = (const AVCodecTag* const []){ff_codec_caf_tags, 0},
 };
diff --git a/libavformat/cdxl.c b/libavformat/cdxl.c
index b65011a..185b745 100644
--- a/libavformat/cdxl.c
+++ b/libavformat/cdxl.c
@@ -19,6 +19,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "libavutil/parseutils.h"
 #include "libavutil/opt.h"
@@ -38,6 +39,48 @@
     int         audio_stream_index;
 } CDXLDemuxContext;
 
+static int cdxl_read_probe(AVProbeData *p)
+{
+    int score = AVPROBE_SCORE_MAX / 2 + 10;
+
+    if (p->buf_size < CDXL_HEADER_SIZE)
+        return 0;
+
+    /* reserved bytes should always be set to 0 */
+    if (AV_RN64(&p->buf[24]) || AV_RN16(&p->buf[10]))
+        return 0;
+
+    /* check type */
+    if (p->buf[0] != 1)
+        return 0;
+
+    /* check palette size */
+    if (AV_RB16(&p->buf[20]) > 512)
+        return 0;
+
+    /* check number of planes */
+    if (p->buf[18] || !p->buf[19])
+        return 0;
+
+    /* check widh and height */
+    if (!AV_RN16(&p->buf[14]) || !AV_RN16(&p->buf[16]))
+        return 0;
+
+    /* chunk size */
+    if (AV_RB32(&p->buf[2]) < AV_RB16(&p->buf[22]) + AV_RB16(&p->buf[20]) + CDXL_HEADER_SIZE)
+        return 0;
+
+    /* previous chunk size */
+    if (AV_RN32(&p->buf[6]))
+        score /= 2;
+
+    /* current frame number, usually starts from 1 */
+    if (AV_RB16(&p->buf[12]) != 1)
+        score /= 2;
+
+    return score;
+}
+
 static int cdxl_read_header(AVFormatContext *s)
 {
     CDXLDemuxContext *cdxl = s->priv_data;
@@ -67,7 +110,7 @@
     int64_t  pos;
     int      ret;
 
-    if (pb->eof_reached)
+    if (url_feof(pb))
         return AVERROR_EOF;
 
     pos = avio_tell(pb);
@@ -101,7 +144,13 @@
             st->codec->codec_type    = AVMEDIA_TYPE_AUDIO;
             st->codec->codec_tag     = 0;
             st->codec->codec_id      = AV_CODEC_ID_PCM_S8;
-            st->codec->channels      = cdxl->header[1] & 0x10 ? 2 : 1;
+            if (cdxl->header[1] & 0x10) {
+                st->codec->channels       = 2;
+                st->codec->channel_layout = AV_CH_LAYOUT_STEREO;
+            } else {
+                st->codec->channels       = 1;
+                st->codec->channel_layout = AV_CH_LAYOUT_MONO;
+            }
             st->codec->sample_rate   = cdxl->sample_rate;
             st->start_time           = 0;
             cdxl->audio_stream_index = st->index;
@@ -173,6 +222,7 @@
     .name           = "cdxl",
     .long_name      = NULL_IF_CONFIG_SMALL("Commodore CDXL video"),
     .priv_data_size = sizeof(CDXLDemuxContext),
+    .read_probe     = cdxl_read_probe,
     .read_header    = cdxl_read_header,
     .read_packet    = cdxl_read_packet,
     .extensions     = "cdxl,xl",
diff --git a/libavformat/crypto.c b/libavformat/crypto.c
index 93c9f23..5d518be 100644
--- a/libavformat/crypto.c
+++ b/libavformat/crypto.c
@@ -59,7 +59,7 @@
     .version        = LIBAVUTIL_VERSION_INT,
 };
 
-static int crypto_open(URLContext *h, const char *uri, int flags)
+static int crypto_open2(URLContext *h, const char *uri, int flags, AVDictionary **options)
 {
     const char *nested_url;
     int ret = 0;
@@ -83,11 +83,11 @@
         goto err;
     }
     if ((ret = ffurl_open(&c->hd, nested_url, AVIO_FLAG_READ,
-                          &h->interrupt_callback, NULL)) < 0) {
+                          &h->interrupt_callback, options)) < 0) {
         av_log(h, AV_LOG_ERROR, "Unable to open input\n");
         goto err;
     }
-    c->aes = av_mallocz(av_aes_size);
+    c->aes = av_aes_alloc();
     if (!c->aes) {
         ret = AVERROR(ENOMEM);
         goto err;
@@ -161,7 +161,7 @@
 
 URLProtocol ff_crypto_protocol = {
     .name            = "crypto",
-    .url_open        = crypto_open,
+    .url_open2       = crypto_open2,
     .url_read        = crypto_read,
     .url_close       = crypto_close,
     .priv_data_size  = sizeof(CryptoContext),
diff --git a/libavformat/daud.c b/libavformat/daud.c
index bfbcf0a..fb62ab1 100644
--- a/libavformat/daud.c
+++ b/libavformat/daud.c
@@ -18,6 +18,8 @@
  * 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/channel_layout.h"
 #include "avformat.h"
 
 static int daud_header(AVFormatContext *s) {
@@ -28,6 +30,7 @@
     st->codec->codec_id = AV_CODEC_ID_PCM_S24DAUD;
     st->codec->codec_tag = MKTAG('d', 'a', 'u', 'd');
     st->codec->channels = 6;
+    st->codec->channel_layout = AV_CH_LAYOUT_5POINT1;
     st->codec->sample_rate = 96000;
     st->codec->bit_rate = 3 * 6 * 96000 * 8;
     st->codec->block_align = 3 * 6;
diff --git a/libavformat/dnxhddec.c b/libavformat/dnxhddec.c
index e5c4381..7b55400 100644
--- a/libavformat/dnxhddec.c
+++ b/libavformat/dnxhddec.c
@@ -37,7 +37,7 @@
     if (!w || !h)
         return 0;
     compression_id = AV_RB32(p->buf + 0x28);
-    if (compression_id < 1237 || compression_id > 1253)
+    if (compression_id < 1235 || compression_id > 1253)
         return 0;
     return AVPROBE_SCORE_MAX;
 }
diff --git a/libavformat/dsicin.c b/libavformat/dsicin.c
index afc010a..b8ca57c 100644
--- a/libavformat/dsicin.c
+++ b/libavformat/dsicin.c
@@ -24,6 +24,7 @@
  * Delphine Software International CIN file demuxer
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "internal.h"
@@ -132,6 +133,7 @@
     st->codec->codec_id = AV_CODEC_ID_DSICINAUDIO;
     st->codec->codec_tag = 0;  /* no tag */
     st->codec->channels = 1;
+    st->codec->channel_layout = AV_CH_LAYOUT_MONO;
     st->codec->sample_rate = 22050;
     st->codec->bits_per_coded_sample = 8;
     st->codec->bit_rate = st->codec->sample_rate * st->codec->bits_per_coded_sample * st->codec->channels;
diff --git a/libavformat/dtshddec.c b/libavformat/dtshddec.c
new file mode 100644
index 0000000..55c4ca6
--- /dev/null
+++ b/libavformat/dtshddec.c
@@ -0,0 +1,139 @@
+/*
+ * Raw DTS-HD demuxer
+ * Copyright (c) 2012 Paul B Mahol
+ *
+ * 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/intreadwrite.h"
+#include "libavutil/dict.h"
+#include "avformat.h"
+
+#define AUPR_HDR 0x415550522D484452
+#define AUPRINFO 0x41555052494E464F
+#define BITSHVTB 0x4249545348565442
+#define BLACKOUT 0x424C41434B4F5554
+#define BRANCHPT 0x4252414E43485054
+#define BUILDVER 0x4255494C44564552
+#define CORESSMD 0x434F524553534D44
+#define DTSHDHDR 0x4454534844484452
+#define EXTSS_MD 0x45585453535f4d44
+#define FILEINFO 0x46494C45494E464F
+#define NAVI_TBL 0x4E4156492D54424C
+#define STRMDATA 0x5354524D44415441
+#define TIMECODE 0x54494D45434F4445
+
+typedef struct DTSHDDemuxContext {
+    uint64_t    data_end;
+} DTSHDDemuxContext;
+
+static int dtshd_probe(AVProbeData *p)
+{
+    if (AV_RB64(p->buf) == DTSHDHDR)
+        return AVPROBE_SCORE_MAX;
+    return 0;
+}
+
+static int dtshd_read_header(AVFormatContext *s)
+{
+    DTSHDDemuxContext *dtshd = s->priv_data;
+    AVIOContext *pb = s->pb;
+    uint64_t chunk_type, chunk_size;
+    AVStream *st;
+    int ret;
+    char *value;
+
+    st = avformat_new_stream(s, NULL);
+    if (!st)
+        return AVERROR(ENOMEM);
+    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+    st->codec->codec_id   = AV_CODEC_ID_DTS;
+    st->need_parsing      = AVSTREAM_PARSE_FULL_RAW;
+
+    while (!url_feof(pb)) {
+        chunk_type = avio_rb64(pb);
+        chunk_size = avio_rb64(pb);
+
+        if (chunk_size < 4) {
+            av_log(s, AV_LOG_ERROR, "chunk size too small\n");
+            return AVERROR_INVALIDDATA;
+        }
+        if (chunk_size > ((uint64_t)1 << 61)) {
+            av_log(s, AV_LOG_ERROR, "chunk size too big\n");
+            return AVERROR_INVALIDDATA;
+        }
+
+        switch (chunk_type) {
+        case STRMDATA:
+            dtshd->data_end = chunk_size + avio_tell(pb);
+            if (dtshd->data_end <= chunk_size)
+                return AVERROR_INVALIDDATA;
+            return 0;
+            break;
+        case FILEINFO:
+            if (chunk_size > INT_MAX)
+                goto skip;
+            value = av_malloc(chunk_size);
+            if (!value)
+                goto skip;
+            avio_read(pb, value, chunk_size);
+            value[chunk_size - 1] = 0;
+            av_dict_set(&s->metadata, "fileinfo", value,
+                        AV_DICT_DONT_STRDUP_VAL);
+            break;
+        default:
+skip:
+            ret = avio_skip(pb, chunk_size);
+            if (ret < 0)
+                return ret;
+        };
+    }
+
+    return AVERROR_EOF;
+}
+
+static int raw_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    DTSHDDemuxContext *dtshd = s->priv_data;
+    int64_t size, left;
+    int ret;
+
+    left = dtshd->data_end - avio_tell(s->pb);
+    size = FFMIN(left, 1024);
+    if (size <= 0)
+        return AVERROR_EOF;
+
+    ret = av_get_packet(s->pb, pkt, size);
+    if (ret < 0)
+        return ret;
+
+    pkt->stream_index = 0;
+
+    return ret;
+}
+
+AVInputFormat ff_dtshd_demuxer = {
+    .name           = "dtshd",
+    .long_name      = NULL_IF_CONFIG_SMALL("raw DTS-HD"),
+    .priv_data_size = sizeof(DTSHDDemuxContext),
+    .read_probe     = dtshd_probe,
+    .read_header    = dtshd_read_header,
+    .read_packet    = raw_read_packet,
+    .flags          = AVFMT_GENERIC_INDEX,
+    .extensions     = "dtshd",
+    .raw_codec_id   = AV_CODEC_ID_DTS,
+};
diff --git a/libavformat/dv.c b/libavformat/dv.c
index 01665c2..a04735a 100644
--- a/libavformat/dv.c
+++ b/libavformat/dv.c
@@ -33,6 +33,7 @@
 #include "internal.h"
 #include "libavcodec/dv_profile.h"
 #include "libavcodec/dvdata.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "libavutil/mathematics.h"
 #include "libavutil/timecode.h"
@@ -141,6 +142,11 @@
      * channels 0,1 and odd 2,3. */
     ipcm = (sys->height == 720 && !(frame[1] & 0x0C)) ? 2 : 0;
 
+    if (ipcm + sys->n_difchan > (quant == 1 ? 2 : 4)) {
+        av_log(NULL, AV_LOG_ERROR, "too many dv pcm frames\n");
+        return AVERROR_INVALIDDATA;
+    }
+
     /* for each DIF channel */
     for (chan = 0; chan < sys->n_difchan; chan++) {
         av_assert0(ipcm<4);
@@ -236,24 +242,25 @@
 
     /* Dynamic handling of the audio streams in DV */
     for (i = 0; i < ach; i++) {
-       if (!c->ast[i]) {
-           c->ast[i] = avformat_new_stream(c->fctx, NULL);
-           if (!c->ast[i])
-               break;
-           avpriv_set_pts_info(c->ast[i], 64, 1, 30000);
-           c->ast[i]->codec->codec_type = AVMEDIA_TYPE_AUDIO;
-           c->ast[i]->codec->codec_id   = AV_CODEC_ID_PCM_S16LE;
+        if (!c->ast[i]) {
+            c->ast[i] = avformat_new_stream(c->fctx, NULL);
+            if (!c->ast[i])
+                break;
+            avpriv_set_pts_info(c->ast[i], 64, 1, 30000);
+            c->ast[i]->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+            c->ast[i]->codec->codec_id   = AV_CODEC_ID_PCM_S16LE;
 
-           av_init_packet(&c->audio_pkt[i]);
-           c->audio_pkt[i].size         = 0;
-           c->audio_pkt[i].data         = c->audio_buf[i];
-           c->audio_pkt[i].stream_index = c->ast[i]->index;
-           c->audio_pkt[i].flags       |= AV_PKT_FLAG_KEY;
-       }
-       c->ast[i]->codec->sample_rate = dv_audio_frequency[freq];
-       c->ast[i]->codec->channels    = 2;
-       c->ast[i]->codec->bit_rate    = 2 * dv_audio_frequency[freq] * 16;
-       c->ast[i]->start_time         = 0;
+            av_init_packet(&c->audio_pkt[i]);
+            c->audio_pkt[i].size         = 0;
+            c->audio_pkt[i].data         = c->audio_buf[i];
+            c->audio_pkt[i].stream_index = c->ast[i]->index;
+            c->audio_pkt[i].flags       |= AV_PKT_FLAG_KEY;
+        }
+        c->ast[i]->codec->sample_rate = dv_audio_frequency[freq];
+        c->ast[i]->codec->channels    = 2;
+        c->ast[i]->codec->channel_layout = AV_CH_LAYOUT_STEREO;
+        c->ast[i]->codec->bit_rate    = 2 * dv_audio_frequency[freq] * 16;
+        c->ast[i]->start_time         = 0;
     }
     c->ach = i;
 
@@ -271,14 +278,14 @@
         avctx = c->vst->codec;
 
         avpriv_set_pts_info(c->vst, 64, c->sys->time_base.num,
-                        c->sys->time_base.den);
+                            c->sys->time_base.den);
         avctx->time_base= c->sys->time_base;
 
         /* finding out SAR is a little bit messy */
         vsc_pack = dv_extract_pack(frame, dv_video_control);
         apt      = frame[4] & 0x07;
         is16_9   = (vsc_pack && ((vsc_pack[2] & 0x07) == 0x02 ||
-                                (!apt && (vsc_pack[2] & 0x07) == 0x07)));
+                                 (!apt && (vsc_pack[2] & 0x07) == 0x07)));
         c->vst->sample_aspect_ratio = c->sys->sar[is16_9];
         avctx->bit_rate = av_rescale_q(c->sys->frame_size, (AVRational){8,1},
                                        c->sys->time_base);
@@ -336,12 +343,12 @@
     int i;
 
     for (i = 0; i < c->ach; i++) {
-       if (c->ast[i] && c->audio_pkt[i].size) {
-           *pkt = c->audio_pkt[i];
-           c->audio_pkt[i].size = 0;
-           size = pkt->size;
-           break;
-       }
+        if (c->ast[i] && c->audio_pkt[i].size) {
+            *pkt = c->audio_pkt[i];
+            c->audio_pkt[i].size = 0;
+            size = pkt->size;
+            break;
+        }
     }
 
     return size;
@@ -356,17 +363,17 @@
     if (buf_size < DV_PROFILE_BYTES ||
         !(c->sys = avpriv_dv_frame_profile(c->sys, buf, buf_size)) ||
         buf_size < c->sys->frame_size) {
-          return -1;   /* Broken frame, or not enough data */
+        return -1;   /* Broken frame, or not enough data */
     }
 
     /* Queueing audio packet */
     /* FIXME: in case of no audio/bad audio we have to do something */
     size = dv_extract_audio_info(c, buf);
     for (i = 0; i < c->ach; i++) {
-       c->audio_pkt[i].pos  = pos;
-       c->audio_pkt[i].size = size;
-       c->audio_pkt[i].pts  = c->abytes * 30000*8 / c->ast[i]->codec->bit_rate;
-       ppcm[i] = c->audio_buf[i];
+        c->audio_pkt[i].pos  = pos;
+        c->audio_pkt[i].size = size;
+        c->audio_pkt[i].pts  = c->abytes * 30000 * 8 / c->ast[i]->codec->bit_rate;
+        ppcm[i] = c->audio_buf[i];
     }
     if (c->ach)
         dv_extract_audio(buf, ppcm, c->sys);
@@ -391,7 +398,7 @@
     pkt->pos          = pos;
     pkt->size         = size;
     pkt->flags       |= AV_PKT_FLAG_KEY;
-    pkt->stream_index = c->vst->id;
+    pkt->stream_index = c->vst->index;
     pkt->pts          = c->frames;
 
     c->frames++;
@@ -462,7 +469,7 @@
     ret = dv_extract_timecode(c->dv_demux, partial_frame, timecode);
     if (ret)
         av_dict_set(&s->metadata, "timecode", timecode, 0);
-    else if (ret < 0)
+    else
         av_log(s, AV_LOG_ERROR, "Detected timecode is invalid\n");
 
 finish:
diff --git a/libavformat/dvenc.c b/libavformat/dvenc.c
index 604f4ce..a132edb 100644
--- a/libavformat/dvenc.c
+++ b/libavformat/dvenc.c
@@ -123,7 +123,7 @@
                  (1 << 3) | /* recording mode: 1 -- original */
                   7;
         buf[3] = (1 << 7) | /* direction: 1 -- forward */
-                 (c->sys->pix_fmt == PIX_FMT_YUV420P ? 0x20 : /* speed */
+                 (c->sys->pix_fmt == AV_PIX_FMT_YUV420P ? 0x20 : /* speed */
                                                        c->sys->ltc_divisor * 4);
         buf[4] = (1 << 7) | /* reserved -- always 1 */
                   0x7f;     /* genre category */
diff --git a/libavformat/electronicarts.c b/libavformat/electronicarts.c
index c5533f2..5b821a9 100644
--- a/libavformat/electronicarts.c
+++ b/libavformat/electronicarts.c
@@ -184,22 +184,31 @@
         case  3: ea->audio_codec = AV_CODEC_ID_ADPCM_EA_R3; break;
         case -1: break;
         default:
-            av_log(s, AV_LOG_ERROR, "unsupported stream type; revision=%i\n", revision);
+            av_log_ask_for_sample(s, "unsupported stream type; revision=%i\n", revision);
             return 0;
         }
         switch (revision2) {
         case  8: ea->audio_codec = AV_CODEC_ID_PCM_S16LE_PLANAR; break;
-        case 10: ea->audio_codec = AV_CODEC_ID_ADPCM_EA_R2; break;
+        case 10:
+            switch (revision) {
+            case -1:
+            case  2: ea->audio_codec = AV_CODEC_ID_ADPCM_EA_R1; break;
+            case  3: ea->audio_codec = AV_CODEC_ID_ADPCM_EA_R2; break;
+            default:
+                av_log_ask_for_sample(s, "unsupported stream type; revision=%i, revision2=%i\n", revision, revision2);
+                return 0;
+            }
+            break;
         case 16: ea->audio_codec = AV_CODEC_ID_MP3; break;
         case -1: break;
         default:
             ea->audio_codec = AV_CODEC_ID_NONE;
-            av_log(s, AV_LOG_ERROR, "unsupported stream type; revision2=%i\n", revision2);
+            av_log_ask_for_sample(s, "unsupported stream type; revision2=%i\n", revision2);
             return 0;
         }
         break;
     default:
-        av_log(s, AV_LOG_ERROR, "unsupported stream type; compression_type=%i\n", compression_type);
+        av_log_ask_for_sample(s, "unsupported stream type; compression_type=%i\n", compression_type);
         return 0;
     }
 
@@ -235,7 +244,7 @@
     case 1: ea->audio_codec = AV_CODEC_ID_PCM_MULAW; ea->bytes = 1; break;
     case 2: ea->audio_codec = AV_CODEC_ID_ADPCM_IMA_EA_EACS; break;
     default:
-        av_log (s, AV_LOG_ERROR, "unsupported stream type; audio compression_type=%i\n", compression_type);
+        av_log_ask_for_sample(s, "unsupported stream type; audio compression_type=%i\n", compression_type);
     }
 
     return 1;
@@ -323,7 +332,7 @@
         switch (blockid) {
             case ISNh_TAG:
                 if (avio_rl32(pb) != EACS_TAG) {
-                    av_log (s, AV_LOG_ERROR, "unknown 1SNh headerid\n");
+                    av_log_ask_for_sample(s, "unknown 1SNh headerid\n");
                     return 0;
                 }
                 err = process_audio_header_eacs(s);
@@ -335,7 +344,7 @@
                 if (blockid == GSTR_TAG) {
                     avio_skip(pb, 4);
                 } else if ((blockid & 0xFFFF)!=PT00_TAG) {
-                    av_log (s, AV_LOG_ERROR, "unknown SCHl headerid\n");
+                    av_log_ask_for_sample(s, "unknown SCHl headerid\n");
                     return 0;
                 }
                 err = process_audio_header_elements(s);
@@ -536,10 +545,12 @@
             case AV_CODEC_ID_ADPCM_EA_R1:
             case AV_CODEC_ID_ADPCM_EA_R2:
             case AV_CODEC_ID_ADPCM_IMA_EA_EACS:
-                pkt->duration = AV_RL32(pkt->data);
+                if (pkt->size >= 4)
+                    pkt->duration = AV_RL32(pkt->data);
                 break;
             case AV_CODEC_ID_ADPCM_EA_R3:
-                pkt->duration = AV_RB32(pkt->data);
+                if (pkt->size >= 4)
+                    pkt->duration = AV_RB32(pkt->data);
                 break;
             case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
                 pkt->duration = ret * 2 / ea->num_channels;
diff --git a/libavformat/ffm.h b/libavformat/ffm.h
index 04f19cc..b392b8d 100644
--- a/libavformat/ffm.h
+++ b/libavformat/ffm.h
@@ -54,10 +54,7 @@
     int64_t dts;
     uint8_t *packet_ptr, *packet_end;
     uint8_t packet[FFM_PACKET_SIZE];
+    int64_t start_time;
 } 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 c6d9fab..02cf790 100644
--- a/libavformat/ffmdec.c
+++ b/libavformat/ffmdec.c
@@ -25,39 +25,6 @@
 #include "internal.h"
 #include "ffm.h"
 #include "avio_internal.h"
-#if CONFIG_FFSERVER
-#include <unistd.h>
-
-int64_t ffm_read_write_index(int fd)
-{
-    uint8_t buf[8];
-
-    lseek(fd, 8, SEEK_SET);
-    if (read(fd, buf, 8) != 8)
-        return AVERROR(EIO);
-    return AV_RB64(buf);
-}
-
-int ffm_write_write_index(int fd, int64_t pos)
-{
-    uint8_t buf[8];
-    int i;
-
-    for(i=0;i<8;i++)
-        buf[i] = (pos >> (56 - i * 8)) & 0xff;
-    lseek(fd, 8, SEEK_SET);
-    if (write(fd, buf, 8) != 8)
-        return AVERROR(EIO);
-    return 8;
-}
-
-void ffm_set_write_index(AVFormatContext *s, int64_t pos, int64_t file_size)
-{
-    FFMContext *ffm = s->priv_data;
-    ffm->write_index = pos;
-    ffm->file_size = file_size;
-}
-#endif // CONFIG_FFSERVER
 
 static int ffm_is_avail_data(AVFormatContext *s, int size)
 {
@@ -144,8 +111,8 @@
             if (ffm->first_packet || (frame_offset & 0x8000)) {
                 if (!frame_offset) {
                     /* This packet has no frame headers in it */
-                    if (avio_tell(pb) >= ffm->packet_size * 3) {
-                        avio_seek(pb, -ffm->packet_size * 2, SEEK_CUR);
+                    if (avio_tell(pb) >= ffm->packet_size * 3LL) {
+                        avio_seek(pb, -ffm->packet_size * 2LL, SEEK_CUR);
                         goto retry_read;
                     }
                     /* This is bad, we cannot find a valid frame header */
@@ -261,6 +228,140 @@
     return 0;
 }
 
+static int ffm2_read_header(AVFormatContext *s)
+{
+    FFMContext *ffm = s->priv_data;
+    AVStream *st;
+    AVIOContext *pb = s->pb;
+    AVCodecContext *codec;
+
+    ffm->packet_size = avio_rb32(pb);
+    if (ffm->packet_size != FFM_PACKET_SIZE)
+        goto fail;
+    ffm->write_index = avio_rb64(pb);
+    /* get also filesize */
+    if (pb->seekable) {
+        ffm->file_size = avio_size(pb);
+        if (ffm->write_index && 0)
+            adjust_write_index(s);
+    } else {
+        ffm->file_size = (UINT64_C(1) << 63) - 1;
+    }
+
+    while(!url_feof(pb)) {
+        unsigned id = avio_rb32(pb);
+        unsigned size = avio_rb32(pb);
+        int64_t next = avio_tell(pb) + size;
+        char rc_eq_buf[128];
+
+        if(!id)
+            break;
+
+        switch(id) {
+        case MKBETAG('M', 'A', 'I', 'N'):
+            avio_rb32(pb); /* nb_streams */
+            avio_rb32(pb); /* total bitrate */
+            break;
+        case MKBETAG('C', 'O', 'M', 'M'):
+            st = avformat_new_stream(s, NULL);
+            if (!st)
+                goto fail;
+
+            avpriv_set_pts_info(st, 64, 1, 1000000);
+
+            codec = st->codec;
+            /* generic info */
+            codec->codec_id = avio_rb32(pb);
+            codec->codec_type = avio_r8(pb);
+            codec->bit_rate = avio_rb32(pb);
+            codec->flags = avio_rb32(pb);
+            codec->flags2 = avio_rb32(pb);
+            codec->debug = avio_rb32(pb);
+            if (codec->flags & CODEC_FLAG_GLOBAL_HEADER) {
+                codec->extradata_size = avio_rb32(pb);
+                codec->extradata = av_malloc(codec->extradata_size);
+                if (!codec->extradata)
+                    return AVERROR(ENOMEM);
+                avio_read(pb, codec->extradata, codec->extradata_size);
+            }
+            avio_seek(pb, next, SEEK_SET);
+            id = avio_rb32(pb);
+            size = avio_rb32(pb);
+            next = avio_tell(pb) + size;
+            switch(id) {
+            case MKBETAG('S', 'T', 'V', 'I'):
+                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_int2double(avio_rb64(pb));
+                codec->b_quant_factor = av_int2double(avio_rb64(pb));
+                codec->i_quant_offset = av_int2double(avio_rb64(pb));
+                codec->b_quant_offset = av_int2double(avio_rb64(pb));
+                codec->dct_algo = avio_rb32(pb);
+                codec->strict_std_compliance = avio_rb32(pb);
+                codec->max_b_frames = 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_int2double(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->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_int2double(avio_rb64(pb));
+                codec->qblur = av_int2double(avio_rb64(pb));
+                codec->max_qdiff = avio_rb32(pb);
+                codec->refs = avio_rb32(pb);
+                break;
+            case MKBETAG('S', 'T', 'A', 'U'):
+                codec->sample_rate = avio_rb32(pb);
+                codec->channels = avio_rl16(pb);
+                codec->frame_size = avio_rl16(pb);
+                break;
+            }
+            break;
+        }
+        avio_seek(pb, next, SEEK_SET);
+    }
+
+    /* get until end of block reached */
+    while ((avio_tell(pb) % ffm->packet_size) != 0)
+        avio_r8(pb);
+
+    /* init packet demux */
+    ffm->packet_ptr = ffm->packet;
+    ffm->packet_end = ffm->packet;
+    ffm->frame_offset = 0;
+    ffm->dts = 0;
+    ffm->read_state = READ_HEADER;
+    ffm->first_packet = 1;
+    return 0;
+ fail:
+    ffm_close(s);
+    return -1;
+}
 
 static int ffm_read_header(AVFormatContext *s)
 {
@@ -273,6 +374,8 @@
 
     /* header */
     tag = avio_rl32(pb);
+    if (tag == MKTAG('F', 'F', 'M', '2'))
+        return ffm2_read_header(s);
     if (tag != MKTAG('F', 'F', 'M', '1'))
         goto fail;
     ffm->packet_size = avio_rb32(pb);
@@ -360,7 +463,6 @@
             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;
@@ -420,7 +522,9 @@
 
         duration = AV_RB24(ffm->header + 5);
 
-        av_new_packet(pkt, size);
+        if (av_new_packet(pkt, size) < 0) {
+            return AVERROR(ENOMEM);
+        }
         pkt->stream_index = ffm->header[0];
         if ((unsigned)pkt->stream_index >= s->nb_streams) {
             av_log(s, AV_LOG_ERROR, "invalid stream index %d\n", pkt->stream_index);
@@ -477,7 +581,7 @@
     while (pos_min <= pos_max) {
         pts_min = get_dts(s, pos_min);
         pts_max = get_dts(s, pos_max);
-        if (pts_min > wanted_pts || pts_max < wanted_pts) {
+        if (pts_min > wanted_pts || pts_max <= wanted_pts) {
             pos = pts_min > wanted_pts ? pos_min : pos_max;
             goto found;
         }
@@ -518,7 +622,7 @@
 {
     if (
         p->buf[0] == 'F' && p->buf[1] == 'F' && p->buf[2] == 'M' &&
-        p->buf[3] == '1')
+        (p->buf[3] == '1' || p->buf[3] == '2'))
         return AVPROBE_SCORE_MAX + 1;
     return 0;
 }
diff --git a/libavformat/ffmenc.c b/libavformat/ffmenc.c
index 1aa4775..522945e 100644
--- a/libavformat/ffmenc.c
+++ b/libavformat/ffmenc.c
@@ -22,6 +22,7 @@
 #include "libavutil/intreadwrite.h"
 #include "libavutil/intfloat.h"
 #include "libavutil/avassert.h"
+#include "libavutil/parseutils.h"
 #include "avformat.h"
 #include "internal.h"
 #include "ffm.h"
@@ -82,21 +83,41 @@
     }
 }
 
+static void write_header_chunk(AVIOContext *pb, AVIOContext *dpb, unsigned id)
+{
+    uint8_t *dyn_buf;
+    int dyn_size= avio_close_dyn_buf(dpb, &dyn_buf);
+    avio_wb32(pb, id);
+    avio_wb32(pb, dyn_size);
+    avio_write(pb, dyn_buf, dyn_size);
+    av_free(dyn_buf);
+}
+
 static int ffm_write_header(AVFormatContext *s)
 {
     FFMContext *ffm = s->priv_data;
+    AVDictionaryEntry *t;
     AVStream *st;
     AVIOContext *pb = s->pb;
     AVCodecContext *codec;
     int bit_rate, i;
 
+    if (t = av_dict_get(s->metadata, "creation_time", NULL, 0)) {
+        int ret = av_parse_time(&ffm->start_time, t->value, 0);
+        if (ret < 0)
+            return ret;
+    }
+
     ffm->packet_size = FFM_PACKET_SIZE;
 
     /* header */
-    avio_wl32(pb, MKTAG('F', 'F', 'M', '1'));
+    avio_wl32(pb, MKTAG('F', 'F', 'M', '2'));
     avio_wb32(pb, ffm->packet_size);
     avio_wb64(pb, 0); /* current write position */
 
+    if(avio_open_dyn_buf(&pb) < 0)
+        return AVERROR(ENOMEM);
+
     avio_wb32(pb, s->nb_streams);
     bit_rate = 0;
     for(i=0;i<s->nb_streams;i++) {
@@ -105,10 +126,14 @@
     }
     avio_wb32(pb, bit_rate);
 
+    write_header_chunk(s->pb, pb, MKBETAG('M', 'A', 'I', 'N'));
+
     /* list of streams */
     for(i=0;i<s->nb_streams;i++) {
         st = s->streams[i];
         avpriv_set_pts_info(st, 64, 1, 1000000);
+        if(avio_open_dyn_buf(&pb) < 0)
+            return AVERROR(ENOMEM);
 
         codec = st->codec;
         /* generic info */
@@ -118,6 +143,13 @@
         avio_wb32(pb, codec->flags);
         avio_wb32(pb, codec->flags2);
         avio_wb32(pb, codec->debug);
+        if (codec->flags & CODEC_FLAG_GLOBAL_HEADER) {
+            avio_wb32(pb, codec->extradata_size);
+            avio_write(pb, codec->extradata, codec->extradata_size);
+        }
+        write_header_chunk(s->pb, pb, MKBETAG('C', 'O', 'M', 'M'));
+        if(avio_open_dyn_buf(&pb) < 0)
+            return AVERROR(ENOMEM);
         /* specific info */
         switch(codec->codec_type) {
         case AVMEDIA_TYPE_VIDEO:
@@ -164,21 +196,21 @@
             avio_wb64(pb, av_double2int(codec->qblur));
             avio_wb32(pb, codec->max_qdiff);
             avio_wb32(pb, codec->refs);
+            write_header_chunk(s->pb, pb, MKBETAG('S', 'T', 'V', 'I'));
             break;
         case AVMEDIA_TYPE_AUDIO:
             avio_wb32(pb, codec->sample_rate);
             avio_wl16(pb, codec->channels);
             avio_wl16(pb, codec->frame_size);
-            avio_wl16(pb, codec->sample_fmt);
+            write_header_chunk(s->pb, pb, MKBETAG('S', 'T', 'A', 'U'));
             break;
         default:
             return -1;
         }
-        if (codec->flags & CODEC_FLAG_GLOBAL_HEADER) {
-            avio_wb32(pb, codec->extradata_size);
-            avio_write(pb, codec->extradata, codec->extradata_size);
-        }
     }
+    pb = s->pb;
+
+    avio_wb64(pb, 0); // end of header
 
     /* flush until end of block reached */
     while ((avio_tell(pb) % ffm->packet_size) != 0)
@@ -199,11 +231,12 @@
 
 static int ffm_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
+    FFMContext *ffm = s->priv_data;
     int64_t dts;
     uint8_t header[FRAME_HEADER_SIZE+4];
     int header_size = FRAME_HEADER_SIZE;
 
-    dts = pkt->dts;
+    dts = ffm->start_time + pkt->dts;
     /* packet size & key_frame */
     header[0] = pkt->stream_index;
     header[1] = 0;
@@ -211,7 +244,7 @@
         header[1] |= FLAG_KEY_FRAME;
     AV_WB24(header+2, pkt->size);
     AV_WB24(header+5, pkt->duration);
-    AV_WB64(header+8, pkt->pts);
+    AV_WB64(header+8, ffm->start_time + pkt->pts);
     if (pkt->pts != pkt->dts) {
         header[1] |= FLAG_DTS;
         AV_WB32(header+16, pkt->pts - pkt->dts);
diff --git a/libavformat/file.c b/libavformat/file.c
index 8c41a3c..e09a64b 100644
--- a/libavformat/file.c
+++ b/libavformat/file.c
@@ -85,6 +85,17 @@
 
 static int file_check(URLContext *h, int mask)
 {
+#if HAVE_ACCESS && defined(R_OK)
+    int ret = 0;
+    if (access(h->filename, F_OK) < 0)
+        return AVERROR(errno);
+    if (mask&AVIO_FLAG_READ)
+        if (access(h->filename, R_OK) >= 0)
+            ret |= AVIO_FLAG_READ;
+    if (mask&AVIO_FLAG_WRITE)
+        if (access(h->filename, W_OK) >= 0)
+            ret |= AVIO_FLAG_WRITE;
+#else
     struct stat st;
     int ret = stat(h->filename, &st);
     if (ret < 0)
@@ -92,7 +103,7 @@
 
     ret |= st.st_mode&S_IRUSR ? mask&AVIO_FLAG_READ  : 0;
     ret |= st.st_mode&S_IWUSR ? mask&AVIO_FLAG_WRITE : 0;
-
+#endif
     return ret;
 }
 
@@ -135,7 +146,7 @@
 static int64_t file_seek(URLContext *h, int64_t pos, int whence)
 {
     FileContext *c = h->priv_data;
-    off_t ret;
+    int64_t ret;
 
     if (whence == AVSEEK_SIZE) {
         struct stat st;
diff --git a/libavformat/filmstripdec.c b/libavformat/filmstripdec.c
index 0d02818..b41fdb7 100644
--- a/libavformat/filmstripdec.c
+++ b/libavformat/filmstripdec.c
@@ -62,7 +62,7 @@
     avio_skip(pb, 2);
     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
     st->codec->codec_id   = AV_CODEC_ID_RAWVIDEO;
-    st->codec->pix_fmt    = PIX_FMT_RGBA;
+    st->codec->pix_fmt    = AV_PIX_FMT_RGBA;
     st->codec->codec_tag  = 0; /* no fourcc */
     st->codec->width      = avio_rb16(pb);
     st->codec->height     = avio_rb16(pb);
diff --git a/libavformat/filmstripenc.c b/libavformat/filmstripenc.c
index afbca5c..85d49be 100644
--- a/libavformat/filmstripenc.c
+++ b/libavformat/filmstripenc.c
@@ -35,8 +35,8 @@
 
 static int write_header(AVFormatContext *s)
 {
-    if (s->streams[0]->codec->pix_fmt != PIX_FMT_RGBA) {
-        av_log(s, AV_LOG_ERROR, "only PIX_FMT_RGBA is supported\n");
+    if (s->streams[0]->codec->pix_fmt != AV_PIX_FMT_RGBA) {
+        av_log(s, AV_LOG_ERROR, "only AV_PIX_FMT_RGBA is supported\n");
         return AVERROR_INVALIDDATA;
     }
     return 0;
@@ -64,7 +64,7 @@
     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));
+    avio_wb16(pb, st->codec->time_base.den / st->codec->time_base.num);
     for (i = 0; i < 16; i++)
         avio_w8(pb, 0x00);  // reserved
 
diff --git a/libavformat/flacenc.c b/libavformat/flacenc.c
index 8c270ee..b625278 100644
--- a/libavformat/flacenc.c
+++ b/libavformat/flacenc.c
@@ -69,6 +69,15 @@
     int ret;
     AVCodecContext *codec = s->streams[0]->codec;
 
+    if (s->nb_streams > 1) {
+        av_log(s, AV_LOG_ERROR, "only one stream is supported\n");
+        return AVERROR(EINVAL);
+    }
+    if (codec->codec_id != AV_CODEC_ID_FLAC) {
+        av_log(s, AV_LOG_ERROR, "unsupported codec\n");
+        return AVERROR(EINVAL);
+    }
+
     ret = ff_flac_write_header(s->pb, codec, 0);
     if (ret)
         return ret;
diff --git a/libavformat/flic.c b/libavformat/flic.c
index db3f5d8..2b9ee67 100644
--- a/libavformat/flic.c
+++ b/libavformat/flic.c
@@ -31,8 +31,8 @@
  * special FLIs from the PC games "Magic Carpet" and "X-COM: Terror from the Deep".
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
-#include "libavutil/audioconvert.h"
 #include "avformat.h"
 #include "internal.h"
 
diff --git a/libavformat/flvdec.c b/libavformat/flvdec.c
index 8c6807a..09a77c4 100644
--- a/libavformat/flvdec.c
+++ b/libavformat/flvdec.c
@@ -25,6 +25,7 @@
  */
 
 #include "libavutil/avstring.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/dict.h"
 #include "libavutil/opt.h"
 #include "libavutil/intfloat.h"
@@ -730,6 +731,8 @@
         av_log(s, AV_LOG_WARNING, "Stream discovered after head already parsed\n");
         st = create_stream(s,
              (int[]){AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_DATA}[stream_type]);
+        if (!st)
+            return AVERROR(ENOMEM);
 
     }
     av_dlog(s, "%d %X %d \n", stream_type, flags, st->discard);
@@ -776,6 +779,8 @@
         bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
         if(!st->codec->channels || !st->codec->sample_rate || !st->codec->bits_per_coded_sample) {
             st->codec->channels              = channels;
+            st->codec->channel_layout        = channels == 1 ? AV_CH_LAYOUT_MONO :
+                                                               AV_CH_LAYOUT_STEREO;
             st->codec->sample_rate           = sample_rate;
             st->codec->bits_per_coded_sample = bits_per_coded_sample;
         }
@@ -817,11 +822,12 @@
             }
             if ((ret = flv_get_extradata(s, st, size)) < 0)
                 return ret;
-            if (st->codec->codec_id == AV_CODEC_ID_AAC) {
+            if (st->codec->codec_id == AV_CODEC_ID_AAC && 0) {
                 MPEG4AudioConfig cfg;
                 if (avpriv_mpeg4audio_get_config(&cfg, st->codec->extradata,
                                              st->codec->extradata_size * 8, 1) >= 0) {
                 st->codec->channels = cfg.channels;
+                st->codec->channel_layout = 0;
                 if (cfg.ext_sample_rate)
                     st->codec->sample_rate = cfg.ext_sample_rate;
                 else
diff --git a/libavformat/framecrcenc.c b/libavformat/framecrcenc.c
index b17c922..8a69748 100644
--- a/libavformat/framecrcenc.c
+++ b/libavformat/framecrcenc.c
@@ -20,6 +20,7 @@
  */
 
 #include "libavutil/adler32.h"
+#include "libavutil/avstring.h"
 #include "avformat.h"
 #include "internal.h"
 
@@ -28,8 +29,13 @@
     uint32_t crc = av_adler32_update(0, pkt->data, pkt->size);
     char buf[256];
 
-    snprintf(buf, sizeof(buf), "%d, %10"PRId64", %10"PRId64", %8d, %8d, 0x%08x\n",
+    snprintf(buf, sizeof(buf), "%d, %10"PRId64", %10"PRId64", %8d, %8d, 0x%08x",
              pkt->stream_index, pkt->dts, pkt->pts, pkt->duration, pkt->size, crc);
+    if (pkt->flags != AV_PKT_FLAG_KEY)
+        av_strlcatf(buf, sizeof(buf), ", F=0x%0X", pkt->flags);
+    if (pkt->side_data_elems)
+        av_strlcatf(buf, sizeof(buf), ", S=%d", pkt->side_data_elems);
+    av_strlcatf(buf, sizeof(buf), "\n");
     avio_write(s->pb, buf, strlen(buf));
     avio_flush(s->pb);
     return 0;
diff --git a/libavformat/g722.c b/libavformat/g722.c
new file mode 100644
index 0000000..1a87c7d
--- /dev/null
+++ b/libavformat/g722.c
@@ -0,0 +1,57 @@
+/*
+ * g722 raw demuxer
+ * 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
+ */
+
+#include "libavutil/avassert.h"
+#include "avformat.h"
+#include "internal.h"
+#include "rawdec.h"
+
+static int g722_read_header(AVFormatContext *s)
+{
+    AVStream *st;
+
+    st = avformat_new_stream(s, NULL);
+    if (!st)
+        return AVERROR(ENOMEM);
+
+    st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
+    st->codec->codec_id    = AV_CODEC_ID_ADPCM_G722;
+    st->codec->sample_rate = 16000;
+    st->codec->channels    = 1;
+
+    st->codec->bits_per_coded_sample =
+        av_get_bits_per_sample(st->codec->codec_id);
+
+    av_assert0(st->codec->bits_per_coded_sample > 0);
+
+    avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
+    return 0;
+}
+
+AVInputFormat ff_g722_demuxer = {
+    .name           = "g722",
+    .long_name      = NULL_IF_CONFIG_SMALL("raw G.722"),
+    .read_header    = g722_read_header,
+    .read_packet    = ff_raw_read_partial_packet,
+    .flags          = AVFMT_GENERIC_INDEX,
+    .extensions     = "g722,722",
+    .raw_codec_id   = AV_CODEC_ID_ADPCM_G722,
+};
diff --git a/libavformat/g723_1.c b/libavformat/g723_1.c
index 7d97a4b..8d35f88 100644
--- a/libavformat/g723_1.c
+++ b/libavformat/g723_1.c
@@ -24,7 +24,7 @@
  * G.723.1 demuxer
  */
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "avformat.h"
 #include "internal.h"
 
diff --git a/libavformat/gif.c b/libavformat/gif.c
index 2cff81a..31b0101 100644
--- a/libavformat/gif.c
+++ b/libavformat/gif.c
@@ -223,7 +223,7 @@
         put_bits(&p, 9, 0x0100); /* clear code */
 
         for (i = (left < GIF_CHUNKS) ? left : GIF_CHUNKS; i; i--) {
-            if (pix_fmt == PIX_FMT_RGB24) {
+            if (pix_fmt == AV_PIX_FMT_RGB24) {
                 v    = gif_clut_index(ptr[0], ptr[1], ptr[2]);
                 ptr += 3;
             } else {
@@ -290,7 +290,7 @@
 //        rate = video_enc->time_base.den;
     }
 
-    if (video_enc->pix_fmt != PIX_FMT_RGB24) {
+    if (video_enc->pix_fmt != AV_PIX_FMT_RGB24) {
         av_log(s, AV_LOG_ERROR,
                "ERROR: gif only handles the rgb24 pixel format. Use -pix_fmt rgb24.\n");
         return AVERROR(EIO);
@@ -327,7 +327,7 @@
     avio_w8(pb, 0x00);
 
     gif_image_write_image(pb, 0, 0, enc->width, enc->height,
-                          buf, enc->width * 3, PIX_FMT_RGB24);
+                          buf, enc->width * 3, AV_PIX_FMT_RGB24);
 
     avio_flush(s->pb);
     return 0;
diff --git a/libavformat/gifdec.c b/libavformat/gifdec.c
new file mode 100644
index 0000000..46eef7c
--- /dev/null
+++ b/libavformat/gifdec.c
@@ -0,0 +1,291 @@
+/*
+ * GIF demuxer
+ * Copyright (c) 2012 Vitaliy E Sugrobov
+ *
+ * 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
+ * GIF demuxer.
+ */
+
+#include "avformat.h"
+#include "libavutil/intreadwrite.h"
+#include "libavutil/opt.h"
+#include "internal.h"
+#include "libavcodec/gif.h"
+
+typedef struct GIFDemuxContext {
+    const AVClass *class;
+    /**
+     * Time span in hundredths of second before
+     * the next frame should be drawn on screen.
+     */
+    int delay;
+    /**
+     * Minimum allowed delay between frames in hundredths of
+     * second. Values below this threshold considered to be
+     * invalid and set to value of default_delay.
+     */
+    int min_delay;
+    int default_delay;
+    int total_duration; ///< In hundredths of second.
+    int frame_idx;
+} GIFDemuxContext;
+
+/**
+ * Major web browsers display gifs at ~10-15fps when rate
+ * is not explicitly set or have too low values. We assume default rate to be 10.
+ * Default delay = 100hundredths of second / 10fps = 10hos per frame.
+ */
+#define GIF_DEFAULT_DELAY   10
+/**
+ * By default delay values less than this threshold considered to be invalid.
+ */
+#define GIF_MIN_DELAY       2
+
+static int gif_probe(AVProbeData *p)
+{
+    /* check magick */
+    if (memcmp(p->buf, gif87a_sig, 6) && memcmp(p->buf, gif89a_sig, 6))
+        return 0;
+
+    /* width or height contains zero? */
+    if (!AV_RL16(&p->buf[6]) || !AV_RL16(&p->buf[8]))
+        return 0;
+
+    return AVPROBE_SCORE_MAX;
+}
+
+static int gif_read_header(AVFormatContext *s)
+{
+    GIFDemuxContext *gdc = s->priv_data;
+    AVIOContext     *pb  = s->pb;
+    AVStream        *st;
+    int width, height, ret;
+
+    /* skip 6-byte magick */
+    if ((ret = avio_skip(pb, 6)) < 0)
+        return ret;
+
+    gdc->delay  = gdc->default_delay;
+    width  = avio_rl16(pb);
+    height = avio_rl16(pb);
+
+    if (width == 0 || height == 0)
+        return AVERROR_INVALIDDATA;
+
+    st = avformat_new_stream(s, NULL);
+    if (!st)
+        return AVERROR(ENOMEM);
+
+    /* GIF format operates with time in "hundredths of second",
+     * therefore timebase is 1/100 */
+    avpriv_set_pts_info(st, 64, 1, 100);
+    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
+    st->codec->codec_id   = AV_CODEC_ID_GIF;
+    st->codec->width      = width;
+    st->codec->height     = height;
+
+    /* jump to start because gif decoder needs header data too */
+    if (avio_seek(pb, 0, SEEK_SET) != 0)
+        return AVERROR(EIO);
+
+    return 0;
+}
+
+static int gif_skip_subblocks(AVIOContext *pb)
+{
+    int sb_size, ret = 0;
+
+    while (0x00 != (sb_size = avio_r8(pb))) {
+        if ((ret = avio_skip(pb, sb_size)) < 0)
+            return ret;
+    }
+
+    return ret;
+}
+
+static int gif_read_ext(AVFormatContext *s)
+{
+    GIFDemuxContext *gdc = s->priv_data;
+    AVIOContext *pb = s->pb;
+    int sb_size, ext_label = avio_r8(pb);
+    int ret;
+
+    if (ext_label == GIF_GCE_EXT_LABEL) {
+        if ((sb_size = avio_r8(pb)) < 4) {
+            av_log(s, AV_LOG_FATAL, "Graphic Control Extension block's size less than 4.\n");
+            return AVERROR_INVALIDDATA;
+        }
+
+        /* skip packed fields */
+        if ((ret = avio_skip(pb, 1)) < 0)
+            return ret;
+
+        gdc->delay = avio_rl16(pb);
+
+        if (gdc->delay < gdc->min_delay)
+            gdc->delay = gdc->default_delay;
+
+        /* skip the rest of the Graphic Control Extension block */
+        if ((ret = avio_skip(pb, sb_size - 3)) < 0 )
+            return ret;
+    }
+
+    if ((ret = gif_skip_subblocks(pb)) < 0)
+        return ret;
+
+    return 0;
+}
+
+static int gif_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    GIFDemuxContext *gdc = s->priv_data;
+    AVIOContext *pb = s->pb;
+    int packed_fields, block_label, ct_size,
+        keyframe, frame_parsed = 0, ret;
+    int64_t frame_start = avio_tell(pb), frame_end;
+    unsigned char buf[6];
+
+    if ((ret = avio_read(pb, buf, 6)) == 6) {
+        keyframe = memcmp(buf, gif87a_sig, 6) == 0 ||
+                   memcmp(buf, gif89a_sig, 6) == 0;
+    } else if (ret < 0) {
+        return ret;
+    } else {
+        keyframe = 0;
+    }
+
+    if (keyframe) {
+        /* skip 2 bytes of width and 2 of height */
+        if ((ret = avio_skip(pb, 4)) < 0)
+            return ret;
+
+        packed_fields = avio_r8(pb);
+
+        /* skip 1 byte of Background Color Index and 1 byte of Pixel Aspect Ratio */
+        if ((ret = avio_skip(pb, 2)) < 0)
+            return ret;
+
+        /* glogal color table presence */
+        if (packed_fields & 0x80) {
+            ct_size = 3 * (1 << ((packed_fields & 0x07) + 1));
+
+            if ((ret = avio_skip(pb, ct_size)) < 0)
+                return ret;
+        }
+
+        gdc->total_duration = 0;
+        gdc->frame_idx      = 0;
+    } else {
+        avio_seek(pb, -ret, SEEK_CUR);
+        ret = AVERROR_EOF;
+    }
+
+    while (GIF_TRAILER != (block_label = avio_r8(pb)) && !url_feof(pb)) {
+        if (block_label == GIF_EXTENSION_INTRODUCER) {
+            if ((ret = gif_read_ext (s)) < 0 )
+                return ret;
+        } else if (block_label == GIF_IMAGE_SEPARATOR) {
+            /* skip to last byte of Image Descriptor header */
+            if ((ret = avio_skip(pb, 8)) < 0)
+                return ret;
+
+            packed_fields = avio_r8(pb);
+
+            /* local color table presence */
+            if (packed_fields & 0x80) {
+                ct_size = 3 * (1 << ((packed_fields & 0x07) + 1));
+
+                if ((ret = avio_skip(pb, ct_size)) < 0)
+                    return ret;
+            }
+
+            /* read LZW Minimum Code Size */
+            if (avio_r8(pb) < 1) {
+                av_log(s, AV_LOG_ERROR, "lzw minimum code size must be >= 1\n");
+                return AVERROR_INVALIDDATA;
+            }
+
+            if ((ret = gif_skip_subblocks(pb)) < 0)
+                return ret;
+
+            frame_end = avio_tell(pb);
+
+            if (avio_seek(pb, frame_start, SEEK_SET) != frame_start)
+                return AVERROR(EIO);
+
+            ret = av_get_packet(pb, pkt, frame_end - frame_start);
+            if (ret < 0)
+                return ret;
+
+            if (keyframe)
+                pkt->flags |= AV_PKT_FLAG_KEY;
+
+            pkt->stream_index = 0;
+            pkt->pts = gdc->total_duration;
+            gdc->total_duration += gdc->delay;
+            pkt->duration = gdc->delay;
+            pkt->dts = gdc->frame_idx;
+
+            /* Graphic Control Extension's scope is single frame.
+             * Remove its influence. */
+            gdc->delay = gdc->default_delay;
+            gdc->frame_idx++;
+            frame_parsed = 1;
+
+            break;
+        } else {
+            av_log(s, AV_LOG_ERROR, "invalid block label\n");
+            return AVERROR_INVALIDDATA;
+        }
+    }
+
+    if (ret >= 0 && !frame_parsed) {
+        /* This might happen when there is no image block
+         * between extension blocks and GIF_TRAILER or EOF */
+        return  AVERROR_EOF;
+    } else
+        return ret;
+}
+
+static const AVOption options[] = {
+    { "min_delay"    , "minimum valid delay between frames (in hundredths of second)", offsetof(GIFDemuxContext, min_delay)    , AV_OPT_TYPE_INT, {.i64 = GIF_MIN_DELAY}    , 0, 100 * 60, AV_OPT_FLAG_DECODING_PARAM },
+    { "default_delay", "default delay between frames (in hundredths of second)"      , offsetof(GIFDemuxContext, default_delay), AV_OPT_TYPE_INT, {.i64 = GIF_DEFAULT_DELAY}, 0, 100 * 60, AV_OPT_FLAG_DECODING_PARAM },
+    { NULL },
+};
+
+static const AVClass demuxer_class = {
+    .class_name = "GIF demuxer",
+    .item_name  = av_default_item_name,
+    .option     = options,
+    .version    = LIBAVUTIL_VERSION_INT,
+    .category   = AV_CLASS_CATEGORY_DEMUXER,
+};
+
+AVInputFormat ff_gif_demuxer = {
+    .name           = "gif",
+    .long_name      = NULL_IF_CONFIG_SMALL("CompuServe Graphics Interchange Format (GIF)"),
+    .priv_data_size = sizeof(GIFDemuxContext),
+    .read_probe     = gif_probe,
+    .read_header    = gif_read_header,
+    .read_packet    = gif_read_packet,
+    .flags          = AVFMT_GENERIC_INDEX,
+    .priv_class     = &demuxer_class,
+};
diff --git a/libavformat/gsmdec.c b/libavformat/gsmdec.c
index 7ec3df5..9899266 100644
--- a/libavformat/gsmdec.c
+++ b/libavformat/gsmdec.c
@@ -19,6 +19,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/mathematics.h"
 #include "libavutil/opt.h"
 #include "avformat.h"
@@ -63,6 +64,7 @@
     st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
     st->codec->codec_id    = s->iformat->raw_codec_id;
     st->codec->channels    = 1;
+    st->codec->channel_layout = AV_CH_LAYOUT_MONO;
     st->codec->sample_rate = c->sample_rate;
     st->codec->bit_rate    = GSM_BLOCK_SIZE * 8 * c->sample_rate / GSM_BLOCK_SAMPLES;
 
diff --git a/libavformat/gxf.c b/libavformat/gxf.c
index 9f000d0..86e6291 100644
--- a/libavformat/gxf.c
+++ b/libavformat/gxf.c
@@ -19,10 +19,12 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
 #include "avformat.h"
 #include "internal.h"
 #include "gxf.h"
+#include "libavcodec/mpeg12data.h"
 
 struct gxf_stream_info {
     int64_t first_field;
@@ -140,6 +142,7 @@
             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
             st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
             st->codec->channels = 1;
+            st->codec->channel_layout = AV_CH_LAYOUT_MONO;
             st->codec->sample_rate = 48000;
             st->codec->bit_rate = 3 * 1 * 48000 * 8;
             st->codec->block_align = 3 * 1;
@@ -149,6 +152,7 @@
             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
             st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
             st->codec->channels = 1;
+            st->codec->channel_layout = AV_CH_LAYOUT_MONO;
             st->codec->sample_rate = 48000;
             st->codec->bit_rate = 2 * 1 * 48000 * 8;
             st->codec->block_align = 2 * 1;
@@ -158,6 +162,7 @@
             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
             st->codec->codec_id = AV_CODEC_ID_AC3;
             st->codec->channels = 2;
+            st->codec->channel_layout = AV_CH_LAYOUT_STEREO;
             st->codec->sample_rate = 48000;
             break;
         // timecode tracks:
@@ -201,15 +206,26 @@
     }
 }
 
+static const AVRational frame_rate_tab[] = {
+    {   60,    1},
+    {60000, 1001},
+    {   50,    1},
+    {   30,    1},
+    {30000, 1001},
+    {   25,    1},
+    {   24,    1},
+    {24000, 1001},
+    {    0,    0},
+};
+
 /**
  * @brief convert fps tag value to AVRational fps
  * @param fps fps value from tag
  * @return fps as AVRational, or 0 / 0 if unknown
  */
 static AVRational fps_tag2avr(int32_t fps) {
-    extern const AVRational avpriv_frame_rate_tab[];
     if (fps < 1 || fps > 9) fps = 9;
-    return avpriv_frame_rate_tab[9 - fps]; // values have opposite order
+    return frame_rate_tab[fps - 1];
 }
 
 /**
@@ -258,15 +274,16 @@
  */
 static void gxf_read_index(AVFormatContext *s, int pkt_len) {
     AVIOContext *pb = s->pb;
-    AVStream *st = s->streams[0];
+    AVStream *st;
     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) {
+    if ((s->flags & AVFMT_FLAG_IGNIDX) || !s->streams) {
         avio_skip(pb, pkt_len);
         return;
     }
+    st = s->streams[0];
     if (map_cnt > 1000) {
         av_log(s, AV_LOG_ERROR, "too many index entries %u (%x)\n", map_cnt, map_cnt);
         map_cnt = 1000;
diff --git a/libavformat/gxfenc.c b/libavformat/gxfenc.c
index 70370a4..28acb74 100644
--- a/libavformat/gxfenc.c
+++ b/libavformat/gxfenc.c
@@ -27,7 +27,6 @@
 #include "avformat.h"
 #include "internal.h"
 #include "gxf.h"
-#include "riff.h"
 #include "audiointerleave.h"
 
 #define GXF_AUDIO_PACKET_SIZE 65536
@@ -209,7 +208,7 @@
     size = snprintf(buffer, sizeof(buffer), "Ver 1\nBr %.6f\nIpg 1\nPpi %d\nBpiop %d\n"
                     "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,
+                    st->codec->pix_fmt == AV_PIX_FMT_YUV422P ? 2 : 1, sc->first_gop_closed == 1,
                     starting_line, (st->codec->height + 15) / 16);
     av_assert0(size < sizeof(buffer));
     avio_w8(pb, TRACK_MPG_AUX);
@@ -503,7 +502,7 @@
 {
     GXFStreamContext *sc = st->priv_data;
 
-    if (st->codec->pix_fmt == PIX_FMT_YUV422P)
+    if (st->codec->pix_fmt == AV_PIX_FMT_YUV422P)
         avio_wl32(pb, 2);
     else
         avio_wl32(pb, 1); /* default to 420 */
@@ -772,7 +771,7 @@
                 media_info = 'M';
                 break;
             case AV_CODEC_ID_DVVIDEO:
-                if (st->codec->pix_fmt == PIX_FMT_YUV422P) {
+                if (st->codec->pix_fmt == AV_PIX_FMT_YUV422P) {
                     sc->media_type += 2;
                     sc->track_type = 6;
                     gxf->flags |= 0x00002000;
@@ -796,7 +795,7 @@
     if (ff_audio_interleave_init(s, GXF_samples_per_frame, (AVRational){ 1, 48000 }) < 0)
         return -1;
 
-    if (tcr)
+    if (tcr && vsc)
         gxf_init_timecode(s, &gxf->tc, tcr->value, vsc->fields);
 
     gxf_init_timecode_track(&gxf->timecode_track, vsc);
diff --git a/libavformat/h264dec.c b/libavformat/h264dec.c
index 7e525e0..9c67ab9 100644
--- a/libavformat/h264dec.c
+++ b/libavformat/h264dec.c
@@ -54,7 +54,7 @@
             case     1:   sli++; break;
             case     5:   idr++; break;
             case     7:
-                if(p->buf[i+2]&0x03)
+                if (p->buf[i + 2] & 0x03)
                     return 0;
                 sps++;
                 break;
diff --git a/libavformat/hls.c b/libavformat/hls.c
index 00c3cf0..f515dfb 100644
--- a/libavformat/hls.c
+++ b/libavformat/hls.c
@@ -212,9 +212,14 @@
     int close_in = 0;
 
     if (!in) {
+        AVDictionary *opts = NULL;
         close_in = 1;
-        if ((ret = avio_open2(&in, url, AVIO_FLAG_READ,
-                              c->interrupt_callback, NULL)) < 0)
+        /* Some HLS servers dont like being sent the range header */
+        av_dict_set(&opts, "seekable", "0", 0);
+        ret = avio_open2(&in, url, AVIO_FLAG_READ,
+                         c->interrupt_callback, &opts);
+        av_dict_free(&opts);
+        if (ret < 0)
             return ret;
     }
 
@@ -325,17 +330,20 @@
 
 static int open_input(struct variant *var)
 {
+    AVDictionary *opts = NULL;
+    int ret;
     struct segment *seg = var->segments[var->cur_seq_no - var->start_seq_no];
+    av_dict_set(&opts, "seekable", "0", 0);
     if (seg->key_type == KEY_NONE) {
-        return ffurl_open(&var->input, seg->url, AVIO_FLAG_READ,
-                          &var->parent->interrupt_callback, NULL);
+        ret = ffurl_open(&var->input, seg->url, AVIO_FLAG_READ,
+                          &var->parent->interrupt_callback, &opts);
+        goto cleanup;
     } else if (seg->key_type == KEY_AES_128) {
         char iv[33], key[33], url[MAX_URL_SIZE];
-        int ret;
         if (strcmp(seg->key, var->key_url)) {
             URLContext *uc;
             if (ffurl_open(&uc, seg->key, AVIO_FLAG_READ,
-                           &var->parent->interrupt_callback, NULL) == 0) {
+                           &var->parent->interrupt_callback, &opts) == 0) {
                 if (ffurl_read_complete(uc, var->key, sizeof(var->key))
                     != sizeof(var->key)) {
                     av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
@@ -357,17 +365,25 @@
             snprintf(url, sizeof(url), "crypto:%s", seg->url);
         if ((ret = ffurl_alloc(&var->input, url, AVIO_FLAG_READ,
                                &var->parent->interrupt_callback)) < 0)
-            return ret;
+            goto cleanup;
         av_opt_set(var->input->priv_data, "key", key, 0);
         av_opt_set(var->input->priv_data, "iv", iv, 0);
-        if ((ret = ffurl_connect(var->input, NULL)) < 0) {
+        /* Need to repopulate options */
+        av_dict_free(&opts);
+        av_dict_set(&opts, "seekable", "0", 0);
+        if ((ret = ffurl_connect(var->input, &opts)) < 0) {
             ffurl_close(var->input);
             var->input = NULL;
-            return ret;
+            goto cleanup;
         }
-        return 0;
+        ret = 0;
     }
-    return AVERROR(ENOSYS);
+    else
+      ret = AVERROR(ENOSYS);
+
+cleanup:
+    av_dict_free(&opts);
+    return ret;
 }
 
 static int read_data(void *opaque, uint8_t *buf, int buf_size)
@@ -393,7 +409,7 @@
             /* If we need to reload the playlist again below (if
              * there's still no more segments), switch to a reload
              * interval of half the target duration. */
-            reload_interval = v->target_duration * 500000;
+            reload_interval = v->target_duration * 500000LL;
         }
         if (v->cur_seq_no < v->start_seq_no) {
             av_log(NULL, AV_LOG_WARNING,
@@ -488,6 +504,7 @@
         struct variant *v = c->variants[i];
         AVInputFormat *in_fmt = NULL;
         char bitrate_str[20];
+        AVProgram *program = NULL;
         if (v->n_segments == 0)
             continue;
 
@@ -533,6 +550,13 @@
         if (ret < 0)
             goto fail;
         snprintf(bitrate_str, sizeof(bitrate_str), "%d", v->bandwidth);
+
+        /* Create new AVprogram for variant i */
+        program = av_new_program(s, i);
+        if (!program)
+            goto fail;
+        av_dict_set(&program->metadata, "variant_bitrate", bitrate_str, 0);
+
         /* Create new AVStreams for each stream in this variant */
         for (j = 0; j < v->ctx->nb_streams; j++) {
             AVStream *st = avformat_new_stream(s, NULL);
@@ -540,6 +564,7 @@
                 ret = AVERROR(ENOMEM);
                 goto fail;
             }
+            ff_program_add_stream_index(s, i, stream_offset + j);
             st->id = i;
             avcodec_copy_context(st->codec, v->ctx->streams[j]->codec);
             if (v->bandwidth)
diff --git a/libavformat/hlsenc.c b/libavformat/hlsenc.c
new file mode 100644
index 0000000..ecf07ef
--- /dev/null
+++ b/libavformat/hlsenc.c
@@ -0,0 +1,324 @@
+/*
+ * Apple HTTP Live Streaming segmenter
+ * Copyright (c) 2012, Luca Barbato
+ *
+ * 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 <float.h>
+
+#include "libavutil/mathematics.h"
+#include "libavutil/parseutils.h"
+#include "libavutil/avstring.h"
+#include "libavutil/opt.h"
+#include "libavutil/log.h"
+
+#include "avformat.h"
+#include "internal.h"
+
+typedef struct ListEntry {
+    char  name[1024];
+    int   duration;
+    struct ListEntry *next;
+} ListEntry;
+
+typedef struct HLSContext {
+    const AVClass *class;  // Class for private options.
+    int number;
+    AVOutputFormat *oformat;
+    AVFormatContext *avf;
+    float time;            // Set by a private option.
+    int  size;             // Set by a private option.
+    int  wrap;             // Set by a private option.
+    int64_t recording_time;
+    int has_video;
+    int64_t start_pts;
+    int64_t end_pts;
+    ListEntry *list;
+    ListEntry *end_list;
+    char *basename;
+    AVIOContext *pb;
+} HLSContext;
+
+static int hls_mux_init(AVFormatContext *s)
+{
+    HLSContext *hls = s->priv_data;
+    AVFormatContext *oc;
+    int i;
+
+    hls->avf = oc = avformat_alloc_context();
+    if (!oc)
+        return AVERROR(ENOMEM);
+
+    oc->oformat            = hls->oformat;
+    oc->interrupt_callback = s->interrupt_callback;
+
+    for (i = 0; i < s->nb_streams; i++) {
+        AVStream *st;
+        if (!(st = avformat_new_stream(oc, NULL)))
+            return AVERROR(ENOMEM);
+        avcodec_copy_context(st->codec, s->streams[i]->codec);
+        st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
+    }
+
+    return 0;
+}
+
+static int append_entry(HLSContext *hls, uint64_t duration)
+{
+    ListEntry *en = av_malloc(sizeof(*en));
+
+    if (!en)
+        return AVERROR(ENOMEM);
+
+    av_get_frame_filename(en->name, sizeof(en->name), hls->basename,
+                          hls->number -1);
+
+    en->duration = duration;
+    en->next     = NULL;
+
+    if (!hls->list)
+        hls->list = en;
+    else
+        hls->end_list->next = en;
+
+    hls->end_list = en;
+
+    if (hls->number >= hls->size) {
+        en = hls->list;
+        hls->list = en->next;
+        av_free(en);
+    }
+
+    return 0;
+}
+
+static void free_entries(HLSContext *hls)
+{
+    ListEntry *p = hls->list, *en;
+
+    while(p) {
+        en = p;
+        p = p->next;
+        av_free(en);
+    }
+}
+
+static int hls_window(AVFormatContext *s, int last)
+{
+    HLSContext *hls = s->priv_data;
+    ListEntry *en;
+    int ret = 0;
+
+    if ((ret = avio_open2(&hls->pb, s->filename, AVIO_FLAG_WRITE,
+                          &s->interrupt_callback, NULL)) < 0)
+        goto fail;
+
+    avio_printf(hls->pb, "#EXTM3U\n");
+    avio_printf(hls->pb, "#EXT-X-VERSION:3\n");
+    avio_printf(hls->pb, "#EXT-X-TARGETDURATION:%d\n", (int)hls->time);
+    avio_printf(hls->pb, "#EXT-X-MEDIA-SEQUENCE:%d\n",
+                FFMAX(0, hls->number - hls->size));
+
+    for (en = hls->list; en; en = en->next) {
+        avio_printf(hls->pb, "#EXTINF:%d,\n", en->duration);
+        avio_printf(hls->pb, "%s\n", en->name);
+    }
+
+    if (last)
+        avio_printf(hls->pb, "#EXT-X-ENDLIST\n");
+
+fail:
+    avio_closep(&hls->pb);
+    return ret;
+}
+
+static int hls_start(AVFormatContext *s)
+{
+    HLSContext *c = s->priv_data;
+    AVFormatContext *oc = c->avf;
+    int err = 0;
+
+    if (c->wrap)
+        c->number %= c->wrap;
+
+    if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
+                              c->basename, c->number++) < 0)
+        return AVERROR(EINVAL);
+
+    if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
+                          &s->interrupt_callback, NULL)) < 0)
+        return err;
+
+    if (oc->oformat->priv_class && oc->priv_data)
+        av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
+
+    return 0;
+}
+
+static int hls_write_header(AVFormatContext *s)
+{
+    HLSContext *hls = s->priv_data;
+    int ret, i;
+    char *p;
+    const char *pattern = "%d.ts";
+    int basename_size = strlen(s->filename) + strlen(pattern);
+
+    hls->number      = 0;
+
+    hls->recording_time = hls->time * 1000000;
+    hls->start_pts      = AV_NOPTS_VALUE;
+
+    for (i = 0; i < s->nb_streams; i++)
+        hls->has_video +=
+            s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO;
+
+    if (hls->has_video > 1)
+        av_log(s, AV_LOG_WARNING,
+               "More than a single video stream present, "
+               "expect issues decoding it.\n");
+
+    hls->oformat = av_guess_format("mpegts", NULL, NULL);
+
+    if (!hls->oformat) {
+        ret = AVERROR_MUXER_NOT_FOUND;
+        goto fail;
+    }
+
+    hls->basename = av_malloc(basename_size);
+
+    if (!hls->basename) {
+        ret = AVERROR(ENOMEM);
+        goto fail;
+    }
+
+    strcpy(hls->basename, s->filename);
+
+    p = strrchr(hls->basename, '.');
+
+    if (p)
+        *p = '\0';
+
+    av_strlcat(hls->basename, "%d.ts", basename_size);
+
+    if ((ret = hls_mux_init(s)) < 0)
+        goto fail;
+
+    if ((ret = hls_start(s)) < 0)
+        goto fail;
+
+    if ((ret = avformat_write_header(hls->avf, NULL)) < 0)
+        return ret;
+
+
+fail:
+    if (ret) {
+        av_free(hls->basename);
+        if (hls->avf)
+            avformat_free_context(hls->avf);
+    }
+    return ret;
+}
+
+static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    HLSContext *hls = s->priv_data;
+    AVFormatContext *oc = hls->avf;
+    AVStream *st = s->streams[pkt->stream_index];
+    int64_t end_pts = hls->recording_time * hls->number;
+    int ret;
+
+    if (hls->start_pts == AV_NOPTS_VALUE) {
+        hls->start_pts = pkt->pts;
+        hls->end_pts   = pkt->pts;
+    }
+    end_pts += hls->start_pts;
+
+    if ((hls->has_video && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)      &&
+        av_compare_ts(pkt->pts, st->time_base, end_pts, AV_TIME_BASE_Q) >= 0 &&
+        pkt->flags & AV_PKT_FLAG_KEY) {
+
+        append_entry(hls, av_rescale(pkt->pts - hls->end_pts,
+                                     st->time_base.num,
+                                     st->time_base.den));
+        hls->end_pts = pkt->pts;
+
+        av_write_frame(oc, NULL); /* Flush any buffered data */
+        avio_close(oc->pb);
+
+        ret = hls_start(s);
+
+        if (ret)
+            return ret;
+
+        oc = hls->avf;
+
+        if ((ret = hls_window(s, 0)) < 0)
+            return ret;
+    }
+
+    ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
+
+    return ret;
+}
+
+static int hls_write_trailer(struct AVFormatContext *s)
+{
+    HLSContext *hls = s->priv_data;
+    AVFormatContext *oc = hls->avf;
+
+    av_write_trailer(oc);
+    avio_closep(&oc->pb);
+    avformat_free_context(oc);
+    av_free(hls->basename);
+    hls_window(s, 1);
+
+    free_entries(hls);
+    avio_close(hls->pb);
+    return 0;
+}
+
+#define OFFSET(x) offsetof(HLSContext, x)
+#define E AV_OPT_FLAG_ENCODING_PARAM
+static const AVOption options[] = {
+    {"hls_time",      "segment length in seconds",               OFFSET(time),    AV_OPT_TYPE_FLOAT,  {.dbl = 2},     0, FLT_MAX, E},
+    {"hls_list_size", "maximum number of playlist entries",      OFFSET(size),    AV_OPT_TYPE_INT,    {.i64 = 5},     0, INT_MAX, E},
+    {"hls_wrap",      "number after which the index wraps",      OFFSET(wrap),    AV_OPT_TYPE_INT,    {.i64 = 0},     0, INT_MAX, E},
+    { NULL },
+};
+
+static const AVClass hls_class = {
+    .class_name = "hls muxer",
+    .item_name  = av_default_item_name,
+    .option     = options,
+    .version    = LIBAVUTIL_VERSION_INT,
+};
+
+
+AVOutputFormat ff_hls_muxer = {
+    .name           = "hls",
+    .long_name      = NULL_IF_CONFIG_SMALL("hls"),
+    .extensions     = "m3u8",
+    .priv_data_size = sizeof(HLSContext),
+    .audio_codec    = AV_CODEC_ID_MP2,
+    .video_codec    = AV_CODEC_ID_MPEG2VIDEO,
+    .flags          = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,
+    .write_header   = hls_write_header,
+    .write_packet   = hls_write_packet,
+    .write_trailer  = hls_write_trailer,
+    .priv_class     = &hls_class,
+};
diff --git a/libavformat/hlsproto.c b/libavformat/hlsproto.c
index a290c88..79cf0e4 100644
--- a/libavformat/hlsproto.c
+++ b/libavformat/hlsproto.c
@@ -293,7 +293,7 @@
             /* If we need to reload the playlist again below (if
              * there's still no more segments), switch to a reload
              * interval of half the target duration. */
-            reload_interval = s->target_duration * 500000;
+            reload_interval = s->target_duration * 500000LL;
         }
     }
     if (s->cur_seq_no < s->start_seq_no) {
diff --git a/libavformat/http.c b/libavformat/http.c
index 6412265..308c22d 100644
--- a/libavformat/http.c
+++ b/libavformat/http.c
@@ -46,6 +46,7 @@
     int line_count;
     int http_code;
     int64_t chunksize;      /**< Used if "Transfer-Encoding: chunked" otherwise -1. */
+    char *content_type;
     char *user_agent;
     int64_t off, filesize;
     char location[MAX_URL_SIZE];
@@ -53,6 +54,7 @@
     HTTPAuthState proxy_auth_state;
     char *headers;
     int willclose;          /**< Set if the server correctly handles Connection: close and will close the connection after feeding us the content. */
+    int seekable;           /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
     int chunked_post;
     int end_chunked_post;   /**< A flag which indicates if the end of chunked encoding has been sent. */
     int end_header;         /**< A flag which indicates we have finished to read POST reply. */
@@ -60,6 +62,7 @@
     uint8_t *post_data;
     int post_datalen;
     int is_akamai;
+    int rw_timeout;
 } HTTPContext;
 
 #define OFFSET(x) offsetof(HTTPContext, x)
@@ -67,11 +70,14 @@
 #define E AV_OPT_FLAG_ENCODING_PARAM
 #define DEC AV_OPT_FLAG_DECODING_PARAM
 static const AVOption options[] = {
+{"seekable", "Control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, D },
 {"chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
 {"headers", "custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
+{"content_type", "force a content type", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
 {"user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC},
 {"multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
 {"post_data", "custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D|E },
+{"timeout", "timeout of socket i/o operations", OFFSET(rw_timeout), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, D|E },
 {NULL}
 };
 #define HTTP_CLASS(flavor)\
@@ -149,8 +155,15 @@
     ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
 
     if (!s->hd) {
+        AVDictionary *opts = NULL;
+        char opts_format[20];
+        if (s->rw_timeout != -1) {
+            snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
+            av_dict_set(&opts, "timeout", opts_format, 0);
+        } /* if option is not given, don't pass it and let tcp use its own default */
         err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
-                         &h->interrupt_callback, NULL);
+                         &h->interrupt_callback, &opts);
+        av_dict_free(&opts);
         if (err < 0)
             goto fail;
     }
@@ -210,7 +223,10 @@
 {
     HTTPContext *s = h->priv_data;
 
-    h->is_streamed = 1;
+    if( s->seekable == 1 )
+        h->is_streamed = 0;
+    else
+        h->is_streamed = 1;
 
     s->filesize = -1;
     av_strlcpy(s->location, uri, sizeof(s->location));
@@ -308,7 +324,7 @@
         while (isspace(*p))
             p++;
         if (!av_strcasecmp(tag, "Location")) {
-            strcpy(s->location, p);
+            av_strlcpy(s->location, p, sizeof(s->location));
             *new_location = 1;
         } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
             s->filesize = strtoll(p, NULL, 10);
@@ -321,9 +337,9 @@
                 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
                     s->filesize = strtoll(slash+1, NULL, 10);
             }
-            if (!s->is_akamai || s->filesize != 2147483647)
+            if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
                 h->is_streamed = 0; /* we _can_ in fact seek */
-        } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5)) {
+        } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5) && s->seekable == -1) {
             h->is_streamed = 0;
         } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
             s->filesize = -1;
@@ -414,10 +430,10 @@
     if (!has_header(s->headers, "\r\nAccept: "))
         len += av_strlcpy(headers + len, "Accept: */*\r\n",
                           sizeof(headers) - len);
-    // Note: we send this on purpose even when s->off is 0,
+    // Note: we send this on purpose even when s->off is 0 when we're probing,
     // since it allows us to detect more reliably if a (non-conforming)
     // server supports seeking by analysing the reply headers.
-    if (!has_header(s->headers, "\r\nRange: ") && !post)
+    if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->seekable == -1))
         len += av_strlcatf(headers + len, sizeof(headers) - len,
                            "Range: bytes=%"PRId64"-\r\n", s->off);
 
@@ -437,6 +453,9 @@
     if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
         len += av_strlcatf(headers + len, sizeof(headers) - len,
                            "Content-Length: %d\r\n", s->post_datalen);
+    if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
+        len += av_strlcatf(headers + len, sizeof(headers) - len,
+                           "Content-Type: %s\r\n", s->content_type);
 
     /* now add in custom headers */
     if (s->headers)
@@ -704,8 +723,13 @@
     HTTPAuthType cur_auth_type;
     char *authstr;
     int new_loc;
+    AVDictionary *opts = NULL;
+    char opts_format[20];
 
-    h->is_streamed = 1;
+    if( s->seekable == 1 )
+        h->is_streamed = 0;
+    else
+        h->is_streamed = 1;
 
     av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
                  pathbuf, sizeof(pathbuf), uri);
@@ -717,8 +741,13 @@
     ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
                 NULL);
 redo:
+    if (s->rw_timeout != -1) {
+        snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
+        av_dict_set(&opts, "timeout", opts_format, 0);
+    } /* if option is not given, don't pass it and let tcp use its own default */
     ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
-                     &h->interrupt_callback, NULL);
+                     &h->interrupt_callback, &opts);
+    av_dict_free(&opts);
     if (ret < 0)
         return ret;
 
diff --git a/libavformat/httpauth.c b/libavformat/httpauth.c
index 646f909..e97aee1 100644
--- a/libavformat/httpauth.c
+++ b/libavformat/httpauth.c
@@ -159,7 +159,7 @@
     ff_data_to_hex(cnonce, (const uint8_t*) cnonce_buf, sizeof(cnonce_buf), 1);
     cnonce[2*sizeof(cnonce_buf)] = 0;
 
-    md5ctx = av_malloc(av_md5_size);
+    md5ctx = av_md5_alloc();
     if (!md5ctx)
         return NULL;
 
diff --git a/libavformat/httpauth.h b/libavformat/httpauth.h
index 62dd25e..fc17c94 100644
--- a/libavformat/httpauth.h
+++ b/libavformat/httpauth.h
@@ -32,7 +32,7 @@
     HTTP_AUTH_DIGEST,      /**< HTTP 1.1 Digest auth from RFC 2617 */
 } HTTPAuthType;
 
-typedef struct {
+typedef struct DigestParams {
     char nonce[300];       /**< Server specified nonce */
     char algorithm[10];    /**< Server specified digest algorithm */
     char qop[30];          /**< Quality of protection, containing the one
@@ -52,7 +52,7 @@
  * HTTP Authentication state structure. Must be zero-initialized
  * before used with the functions below.
  */
-typedef struct {
+typedef struct HTTPAuthState {
     /**
      * The currently chosen auth type.
      */
diff --git a/libavformat/icoenc.c b/libavformat/icoenc.c
index e755b21..cbf8bd9 100644
--- a/libavformat/icoenc.c
+++ b/libavformat/icoenc.c
@@ -1,6 +1,6 @@
 /*
  * Microsoft Windows ICO muxer
- * Copyright (c) 2012 Michael Bradshaw <mbradshaw@sorensonmedia.com>
+ * Copyright (c) 2012 Michael Bradshaw <mjbshaw gmail com>
  *
  * This file is part of FFmpeg.
  *
@@ -45,18 +45,18 @@
 static int ico_check_attributes(AVFormatContext *s, const AVCodecContext *c)
 {
     if (c->codec_id == CODEC_ID_BMP) {
-        if (c->pix_fmt == PIX_FMT_PAL8 && PIX_FMT_RGB32 != PIX_FMT_BGRA) {
+        if (c->pix_fmt == AV_PIX_FMT_PAL8 && AV_PIX_FMT_RGB32 != AV_PIX_FMT_BGRA) {
             av_log(s, AV_LOG_ERROR, "Wrong endianness for bmp pixel format\n");
             return AVERROR(EINVAL);
-        } else if (c->pix_fmt != PIX_FMT_PAL8 &&
-                   c->pix_fmt != PIX_FMT_RGB555LE &&
-                   c->pix_fmt != PIX_FMT_BGR24 &&
-                   c->pix_fmt != PIX_FMT_BGRA) {
+        } else if (c->pix_fmt != AV_PIX_FMT_PAL8 &&
+                   c->pix_fmt != AV_PIX_FMT_RGB555LE &&
+                   c->pix_fmt != AV_PIX_FMT_BGR24 &&
+                   c->pix_fmt != AV_PIX_FMT_BGRA) {
             av_log(s, AV_LOG_ERROR, "BMP must be 1bit, 4bit, 8bit, 16bit, 24bit, or 32bit\n");
             return AVERROR(EINVAL);
         }
     } else if (c->codec_id == CODEC_ID_PNG) {
-        if (c->pix_fmt != PIX_FMT_RGBA) {
+        if (c->pix_fmt != AV_PIX_FMT_RGBA) {
             av_log(s, AV_LOG_ERROR, "PNG in ico requires pixel format to be rgba\n");
             return AVERROR(EINVAL);
         }
@@ -171,7 +171,7 @@
         avio_w8(pb, ico->images[i].height);
 
         if (s->streams[i]->codec->codec_id == CODEC_ID_BMP &&
-            s->streams[i]->codec->pix_fmt == PIX_FMT_PAL8) {
+            s->streams[i]->codec->pix_fmt == AV_PIX_FMT_PAL8) {
             avio_w8(pb, (ico->images[i].bits >= 8) ? 0 : 1 << ico->images[i].bits);
         } else {
             avio_w8(pb, 0);
diff --git a/libavformat/id3v2.c b/libavformat/id3v2.c
index 9c20287..f805f5b 100644
--- a/libavformat/id3v2.c
+++ b/libavformat/id3v2.c
@@ -508,6 +508,36 @@
     avio_seek(pb, end, SEEK_SET);
 }
 
+static void read_chapter(AVFormatContext *s, AVIOContext *pb, int taglen, char *tag, ID3v2ExtraMeta **extra_meta)
+{
+    AVRational time_base = {1, 1000};
+    char title[1024];
+    uint32_t start, end;
+
+    taglen -= avio_get_str(pb, taglen, title, sizeof(title));
+    if (taglen < 16)
+        return;
+
+    start = avio_rb32(pb);
+    end   = avio_rb32(pb);
+    taglen -= 27;
+    if (taglen > 0) {
+        char tag[4];
+
+        avio_skip(pb, 8);
+        avio_read(pb, tag, 4);
+        if (!memcmp(tag, "TIT2", 4)) {
+            taglen = FFMIN(taglen, avio_rb32(pb));
+            if (taglen < 0)
+                return;
+            avio_skip(pb, 3);
+            avio_get_str(pb, taglen, title, sizeof(title));
+        }
+    }
+
+    avpriv_new_chapter(s, s->nb_chapters + 1, time_base, start, end, title);
+}
+
 typedef struct ID3v2EMFunc {
     const char *tag3;
     const char *tag4;
@@ -518,6 +548,7 @@
 static const ID3v2EMFunc id3v2_extra_meta_funcs[] = {
     { "GEO", "GEOB", read_geobtag, free_geobtag },
     { "PIC", "APIC", read_apic,    free_apic },
+    { "CHAP","CHAP", read_chapter, NULL },
     { NULL }
 };
 
@@ -553,8 +584,10 @@
     unsigned char *buffer = NULL;
     int buffer_size = 0;
     const ID3v2EMFunc *extra_func = NULL;
-    unsigned char *compressed_buffer = NULL;
-    int compressed_buffer_size = 0;
+    unsigned char *uncompressed_buffer = NULL;
+    int uncompressed_buffer_size = 0;
+
+    av_log(s, AV_LOG_DEBUG, "id3v2 ver:%d flags:%02X len:%d\n", version, flags, len);
 
     switch (version) {
     case 2:
@@ -657,54 +690,63 @@
             avio_skip(s->pb, tlen);
         /* check for text tag or supported special meta tag */
         } else if (tag[0] == 'T' || (extra_meta && (extra_func = get_extra_meta_func(tag, isv34)))) {
-            if (unsync || tunsync || tcomp) {
-                int i, j;
+            pbx = s->pb;
 
-                av_fast_malloc(&buffer, &buffer_size, dlen);
+            if (unsync || tunsync || tcomp) {
+                av_fast_malloc(&buffer, &buffer_size, tlen);
                 if (!buffer) {
-                    av_log(s, AV_LOG_ERROR, "Failed to alloc %ld bytes\n", dlen);
+                    av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);
                     goto seek;
                 }
+            }
+            if (unsync || tunsync) {
+                int64_t end = avio_tell(s->pb) + tlen;
+                uint8_t *b;
+
+                b = buffer;
+                while (avio_tell(s->pb) < end && b - buffer < tlen) {
+                    *b++ = avio_r8(s->pb);
+                    if (*(b - 1) == 0xff && avio_tell(s->pb) < end - 1 && b - buffer < tlen) {
+                        uint8_t val = avio_r8(s->pb);
+                        *b++ = val ? val : avio_r8(s->pb);
+                    }
+                }
+                ffio_init_context(&pb, buffer, b - buffer, 0, NULL, NULL, NULL, NULL);
+                tlen = b - buffer;
+                pbx = &pb; // read from sync buffer
+            }
+
 #if CONFIG_ZLIB
                 if (tcomp) {
-                    int n, err;
+                    int err;
 
                     av_log(s, AV_LOG_DEBUG, "Compresssed frame %s tlen=%d dlen=%ld\n", tag, tlen, dlen);
 
-                    av_fast_malloc(&compressed_buffer, &compressed_buffer_size, tlen);
-                    if (!compressed_buffer) {
-                        av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);
+                    av_fast_malloc(&uncompressed_buffer, &uncompressed_buffer_size, dlen);
+                    if (!uncompressed_buffer) {
+                        av_log(s, AV_LOG_ERROR, "Failed to alloc %ld bytes\n", dlen);
                         goto seek;
                     }
 
-                    n = avio_read(s->pb, compressed_buffer, tlen);
-                    if (n < 0) {
-                        av_log(s, AV_LOG_ERROR, "Failed to read compressed tag\n");
-                        goto seek;
+                    if (!(unsync || tunsync)) {
+                        err = avio_read(s->pb, buffer, tlen);
+                        if (err < 0) {
+                            av_log(s, AV_LOG_ERROR, "Failed to read compressed tag\n");
+                            goto seek;
+                        }
+                        tlen = err;
                     }
 
-                    err = uncompress(buffer, &dlen, compressed_buffer, n);
+                    err = uncompress(uncompressed_buffer, &dlen, buffer, tlen);
                     if (err != Z_OK) {
                         av_log(s, AV_LOG_ERROR, "Failed to uncompress tag: %d\n", err);
                         goto seek;
                     }
+                    ffio_init_context(&pb, uncompressed_buffer, dlen, 0, NULL, NULL, NULL, NULL);
+                    tlen = dlen;
+                    pbx = &pb; // read from sync buffer
                 }
 #endif
-
-                for (i = 0, j = 0; i < dlen; i++, j++) {
-                    if (!tcomp)
-                        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);
-                tlen = j;
-                pbx = &pb; // read from sync buffer
-            } else {
-                pbx = s->pb; // read straight from input
-            }
             if (tag[0] == 'T')
                 /* parse text tag */
                 read_ttag(s, pbx, tlen, tag);
@@ -731,7 +773,7 @@
         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);
-    av_free(compressed_buffer);
+    av_free(uncompressed_buffer);
     return;
 }
 
diff --git a/libavformat/idcin.c b/libavformat/idcin.c
index f1df002..bede040 100644
--- a/libavformat/idcin.c
+++ b/libavformat/idcin.c
@@ -256,6 +256,8 @@
         chunk_size = avio_rl32(pb);
         /* skip the number of decoded bytes (always equal to width * height) */
         avio_skip(pb, 4);
+        if (chunk_size < 4)
+            return AVERROR_INVALIDDATA;
         chunk_size -= 4;
         ret= av_get_packet(pb, pkt, chunk_size);
         if (ret < 0)
diff --git a/libavformat/idroqdec.c b/libavformat/idroqdec.c
index 3b17ff4..6f843d7 100644
--- a/libavformat/idroqdec.c
+++ b/libavformat/idroqdec.c
@@ -27,6 +27,7 @@
  *   http://www.csse.monash.edu.au/~timf/
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "internal.h"
@@ -178,7 +179,14 @@
                 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
                 st->codec->codec_id = AV_CODEC_ID_ROQ_DPCM;
                 st->codec->codec_tag = 0;  /* no tag */
-                st->codec->channels = roq->audio_channels = chunk_type == RoQ_SOUND_STEREO ? 2 : 1;
+                if (chunk_type == RoQ_SOUND_STEREO) {
+                    st->codec->channels       = 2;
+                    st->codec->channel_layout = AV_CH_LAYOUT_STEREO;
+                } else {
+                    st->codec->channels       = 1;
+                    st->codec->channel_layout = AV_CH_LAYOUT_MONO;
+                }
+                roq->audio_channels    = st->codec->channels;
                 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 *
diff --git a/libavformat/iff.c b/libavformat/iff.c
index 0055283..e59d49b 100644
--- a/libavformat/iff.c
+++ b/libavformat/iff.c
@@ -28,14 +28,19 @@
  * http://wiki.multimedia.cx/index.php?title=IFF
  */
 
-#include "libavcodec/bytestream.h"
 #include "libavutil/avassert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "libavutil/dict.h"
+#include "libavcodec/bytestream.h"
 #include "avformat.h"
 #include "internal.h"
 
 #define ID_8SVX       MKTAG('8','S','V','X')
+#define ID_16SV       MKTAG('1','6','S','V')
+#define ID_MAUD       MKTAG('M','A','U','D')
+#define ID_MHDR       MKTAG('M','H','D','R')
+#define ID_MDAT       MKTAG('M','D','A','T')
 #define ID_VHDR       MKTAG('V','H','D','R')
 #define ID_ATAK       MKTAG('A','T','A','K')
 #define ID_RLSE       MKTAG('R','L','S','E')
@@ -62,6 +67,7 @@
 #define ID_BODY       MKTAG('B','O','D','Y')
 #define ID_DBOD       MKTAG('D','B','O','D')
 #define ID_DPEL       MKTAG('D','P','E','L')
+#define ID_DLOC       MKTAG('D','L','O','C')
 
 #define LEFT    2
 #define RIGHT   4
@@ -83,17 +89,14 @@
     COMP_EXP
 } svx8_compression_type;
 
-typedef enum {
-    BITMAP_RAW,
-    BITMAP_BYTERUN1
-} bitmap_compression_type;
-
 typedef struct {
     uint64_t  body_pos;
     uint32_t  body_size;
     uint32_t  sent_bytes;
     svx8_compression_type   svx8_compression;
-    bitmap_compression_type bitmap_compression;  ///< delta compression method used
+    unsigned  maud_bits;
+    unsigned  maud_compression;
+    unsigned  bitmap_compression;  ///< delta compression method used
     unsigned  bpp;          ///< bits per plane to decode (differs from bits_per_coded_sample if HAM)
     unsigned  ham;          ///< 0 if non-HAM or number of hold bits (6 for bpp > 6, 4 otherwise)
     unsigned  flags;        ///< 1 for EHB, 0 is no extra half darkening
@@ -126,6 +129,8 @@
 
     if (  AV_RL32(d)   == ID_FORM &&
          (AV_RL32(d+8) == ID_8SVX ||
+          AV_RL32(d+8) == ID_16SV ||
+          AV_RL32(d+8) == ID_MAUD ||
           AV_RL32(d+8) == ID_PBM  ||
           AV_RL32(d+8) == ID_ACBM ||
           AV_RL32(d+8) == ID_DEEP ||
@@ -136,6 +141,9 @@
 
 static const uint8_t deep_rgb24[] = {0, 0, 0, 3, 0, 1, 0, 8, 0, 2, 0, 8, 0, 3, 0, 8};
 static const uint8_t deep_rgba[]  = {0, 0, 0, 4, 0, 1, 0, 8, 0, 2, 0, 8, 0, 3, 0, 8};
+static const uint8_t deep_bgra[]  = {0, 0, 0, 4, 0, 3, 0, 8, 0, 2, 0, 8, 0, 1, 0, 8};
+static const uint8_t deep_argb[]  = {0, 0, 0, 4, 0,17, 0, 8, 0, 1, 0, 8, 0, 2, 0, 8};
+static const uint8_t deep_abgr[]  = {0, 0, 0, 4, 0,17, 0, 8, 0, 3, 0, 8, 0, 2, 0, 8};
 
 static int iff_read_header(AVFormatContext *s)
 {
@@ -144,7 +152,7 @@
     AVStream *st;
     uint8_t *buf;
     uint32_t chunk_id, data_size;
-    uint32_t screenmode = 0;
+    uint32_t screenmode = 0, num, den;
     unsigned transparency = 0;
     unsigned masking = 0; // no mask
     uint8_t fmt[16];
@@ -155,9 +163,14 @@
         return AVERROR(ENOMEM);
 
     st->codec->channels = 1;
+    st->codec->channel_layout = AV_CH_LAYOUT_MONO;
     avio_skip(pb, 8);
     // codec_tag used by ByteRun1 decoder to distinguish progressive (PBM) and interlaced (ILBM) content
     st->codec->codec_tag = avio_rl32(pb);
+    iff->bitmap_compression = -1;
+    iff->svx8_compression = -1;
+    iff->maud_bits = -1;
+    iff->maud_compression = -1;
 
     while(!url_feof(pb)) {
         uint64_t orig_pos;
@@ -181,9 +194,32 @@
             }
             break;
 
+        case ID_MHDR:
+            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+
+            if (data_size < 32)
+                return AVERROR_INVALIDDATA;
+            avio_skip(pb, 4);
+            iff->maud_bits = avio_rb16(pb);
+            avio_skip(pb, 2);
+            num = avio_rb32(pb);
+            den = avio_rb16(pb);
+            if (!den)
+                return AVERROR_INVALIDDATA;
+            avio_skip(pb, 2);
+            st->codec->sample_rate = num / den;
+            st->codec->channels = avio_rb16(pb);
+            iff->maud_compression = avio_rb16(pb);
+            if (st->codec->channels == 1)
+                st->codec->channel_layout = AV_CH_LAYOUT_MONO;
+            else if (st->codec->channels == 2)
+                st->codec->channel_layout = AV_CH_LAYOUT_STEREO;
+            break;
+
         case ID_ABIT:
         case ID_BODY:
         case ID_DBOD:
+        case ID_MDAT:
             iff->body_pos = avio_tell(pb);
             iff->body_size = data_size;
             break;
@@ -191,7 +227,13 @@
         case ID_CHAN:
             if (data_size < 4)
                 return AVERROR_INVALIDDATA;
-            st->codec->channels = (avio_rb32(pb) < 6) ? 1 : 2;
+            if (avio_rb32(pb) < 6) {
+                st->codec->channels       = 1;
+                st->codec->channel_layout = AV_CH_LAYOUT_MONO;
+            } else {
+                st->codec->channels       = 2;
+                st->codec->channel_layout = AV_CH_LAYOUT_STEREO;
+            }
             break;
 
         case ID_CAMG:
@@ -210,7 +252,6 @@
             break;
 
         case ID_BMHD:
-            iff->bitmap_compression = -1;
             st->codec->codec_type            = AVMEDIA_TYPE_VIDEO;
             if (data_size <= 8)
                 return AVERROR_INVALIDDATA;
@@ -238,9 +279,15 @@
             if ((fmt_size = avio_read(pb, fmt, sizeof(fmt))) < 0)
                 return fmt_size;
             if (fmt_size == sizeof(deep_rgb24) && !memcmp(fmt, deep_rgb24, sizeof(deep_rgb24)))
-                st->codec->pix_fmt = PIX_FMT_RGB24;
+                st->codec->pix_fmt = AV_PIX_FMT_RGB24;
             else if (fmt_size == sizeof(deep_rgba) && !memcmp(fmt, deep_rgba, sizeof(deep_rgba)))
-                st->codec->pix_fmt = PIX_FMT_RGBA;
+                st->codec->pix_fmt = AV_PIX_FMT_RGBA;
+            else if (fmt_size == sizeof(deep_bgra) && !memcmp(fmt, deep_bgra, sizeof(deep_bgra)))
+                st->codec->pix_fmt = AV_PIX_FMT_BGRA;
+            else if (fmt_size == sizeof(deep_argb) && !memcmp(fmt, deep_argb, sizeof(deep_argb)))
+                st->codec->pix_fmt = AV_PIX_FMT_ARGB;
+            else if (fmt_size == sizeof(deep_abgr) && !memcmp(fmt, deep_abgr, sizeof(deep_abgr)))
+                st->codec->pix_fmt = AV_PIX_FMT_ABGR;
             else {
                 av_log_ask_for_sample(s, "unsupported color format\n");
                 return AVERROR_PATCHWELCOME;
@@ -254,16 +301,18 @@
             st->codec->width                 = avio_rb16(pb);
             st->codec->height                = avio_rb16(pb);
             iff->bitmap_compression          = avio_rb16(pb);
-            if (iff->bitmap_compression != 0) {
-                av_log(s, AV_LOG_ERROR,
-                       "compression %i not supported\n", iff->bitmap_compression);
-                return AVERROR_PATCHWELCOME;
-            }
             st->sample_aspect_ratio.num      = avio_r8(pb);
             st->sample_aspect_ratio.den      = avio_r8(pb);
             st->codec->bits_per_coded_sample = 24;
             break;
 
+        case ID_DLOC:
+            if (data_size < 4)
+                return AVERROR_INVALIDDATA;
+            st->codec->width  = avio_rb16(pb);
+            st->codec->height = avio_rb16(pb);
+            break;
+
         case ID_ANNO:
         case ID_TEXT:      metadata_tag = "comment";   break;
         case ID_AUTH:      metadata_tag = "artist";    break;
@@ -286,6 +335,28 @@
     case AVMEDIA_TYPE_AUDIO:
         avpriv_set_pts_info(st, 32, 1, st->codec->sample_rate);
 
+        if (st->codec->codec_tag == ID_16SV)
+            st->codec->codec_id = AV_CODEC_ID_PCM_S16BE_PLANAR;
+        else if (st->codec->codec_tag == ID_MAUD) {
+            if (iff->maud_bits == 8 && !iff->maud_compression) {
+                st->codec->codec_id = AV_CODEC_ID_PCM_U8;
+            } else if (iff->maud_bits == 16 && !iff->maud_compression) {
+                st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
+            } else if (iff->maud_bits ==  8 && iff->maud_compression == 2) {
+                st->codec->codec_id = AV_CODEC_ID_PCM_ALAW;
+            } else if (iff->maud_bits ==  8 && iff->maud_compression == 3) {
+                st->codec->codec_id = AV_CODEC_ID_PCM_MULAW;
+            } else {
+                av_log_ask_for_sample(s, "unsupported compression %d and bit depth %d\n", iff->maud_compression, iff->maud_bits);
+                return AVERROR_PATCHWELCOME;
+            }
+
+            st->codec->bits_per_coded_sample =
+                av_get_bits_per_sample(st->codec->codec_id);
+
+            st->codec->block_align =
+                st->codec->bits_per_coded_sample * st->codec->channels / 8;
+        } else {
         switch (iff->svx8_compression) {
         case COMP_NONE:
             st->codec->codec_id = AV_CODEC_ID_PCM_S8_PLANAR;
@@ -301,8 +372,9 @@
                    "Unknown SVX8 compression method '%d'\n", iff->svx8_compression);
             return -1;
         }
+        }
 
-        st->codec->bits_per_coded_sample = iff->svx8_compression == COMP_NONE ? 8 : 4;
+        st->codec->bits_per_coded_sample = av_get_bits_per_sample(st->codec->codec_id);
         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;
         break;
@@ -331,19 +403,7 @@
         bytestream_put_byte(&buf, iff->flags);
         bytestream_put_be16(&buf, iff->transparency);
         bytestream_put_byte(&buf, iff->masking);
-
-        switch (iff->bitmap_compression) {
-        case BITMAP_RAW:
-            st->codec->codec_id = AV_CODEC_ID_IFF_ILBM;
-            break;
-        case BITMAP_BYTERUN1:
-            st->codec->codec_id = AV_CODEC_ID_IFF_BYTERUN1;
-            break;
-        default:
-            av_log(s, AV_LOG_ERROR,
-                   "Unknown bitmap compression method '%d'\n", iff->bitmap_compression);
-            return AVERROR_INVALIDDATA;
-        }
+        st->codec->codec_id = AV_CODEC_ID_IFF_ILBM;
         break;
     default:
         return -1;
@@ -364,7 +424,12 @@
         return AVERROR_EOF;
 
     if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
-        ret = av_get_packet(pb, pkt, iff->body_size);
+        if (st->codec->codec_tag == ID_MAUD) {
+            ret = av_get_packet(pb, pkt,
+                                FFMIN(iff->body_size - iff->sent_bytes, 1024 * st->codec->block_align));
+        } else {
+            ret = av_get_packet(pb, pkt, iff->body_size);
+        }
     } else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
         uint8_t *buf;
 
@@ -381,8 +446,9 @@
 
     if(iff->sent_bytes == 0)
         pkt->flags |= AV_PKT_FLAG_KEY;
-    iff->sent_bytes = iff->body_size;
-
+    if (ret < 0)
+        return ret;
+    iff->sent_bytes += ret;
     pkt->stream_index = 0;
     return ret;
 }
diff --git a/libavformat/img2.c b/libavformat/img2.c
index ed4b39a..eee100a 100644
--- a/libavformat/img2.c
+++ b/libavformat/img2.c
@@ -29,59 +29,62 @@
 } IdStrMap;
 
 static const IdStrMap img_tags[] = {
-    { AV_CODEC_ID_MJPEG     , "jpeg"},
-    { AV_CODEC_ID_MJPEG     , "jpg"},
-    { AV_CODEC_ID_MJPEG     , "jps"},
-    { AV_CODEC_ID_LJPEG     , "ljpg"},
-    { AV_CODEC_ID_JPEGLS    , "jls"},
-    { AV_CODEC_ID_PNG       , "png"},
-    { AV_CODEC_ID_PNG       , "pns"},
-    { AV_CODEC_ID_PNG       , "mng"},
-    { AV_CODEC_ID_PPM       , "ppm"},
-    { AV_CODEC_ID_PPM       , "pnm"},
-    { AV_CODEC_ID_PGM       , "pgm"},
-    { AV_CODEC_ID_PGMYUV    , "pgmyuv"},
-    { AV_CODEC_ID_PBM       , "pbm"},
-    { AV_CODEC_ID_PAM       , "pam"},
-    { AV_CODEC_ID_MPEG1VIDEO, "mpg1-img"},
-    { AV_CODEC_ID_MPEG2VIDEO, "mpg2-img"},
-    { AV_CODEC_ID_MPEG4     , "mpg4-img"},
-    { AV_CODEC_ID_FFV1      , "ffv1-img"},
-    { AV_CODEC_ID_RAWVIDEO  , "y"},
-    { AV_CODEC_ID_RAWVIDEO  , "raw"},
-    { AV_CODEC_ID_BMP       , "bmp"},
-    { AV_CODEC_ID_GIF       , "gif"},
-    { AV_CODEC_ID_TARGA     , "tga"},
-    { AV_CODEC_ID_TIFF      , "tiff"},
-    { AV_CODEC_ID_TIFF      , "tif"},
-    { AV_CODEC_ID_SGI       , "sgi"},
-    { AV_CODEC_ID_PTX       , "ptx"},
-    { AV_CODEC_ID_PCX       , "pcx"},
-    { AV_CODEC_ID_SUNRAST   , "sun"},
-    { AV_CODEC_ID_SUNRAST   , "ras"},
-    { AV_CODEC_ID_SUNRAST   , "rs"},
-    { AV_CODEC_ID_SUNRAST   , "im1"},
-    { AV_CODEC_ID_SUNRAST   , "im8"},
-    { AV_CODEC_ID_SUNRAST   , "im24"},
-    { AV_CODEC_ID_SUNRAST   , "im32"},
-    { AV_CODEC_ID_SUNRAST   , "sunras"},
-    { AV_CODEC_ID_JPEG2000  , "j2c"},
-    { AV_CODEC_ID_JPEG2000  , "j2k"},
-    { AV_CODEC_ID_JPEG2000  , "jp2"},
-    { AV_CODEC_ID_JPEG2000  , "jpc"},
-    { AV_CODEC_ID_DPX       , "dpx"},
-    { AV_CODEC_ID_EXR       , "exr"},
-    { AV_CODEC_ID_PICTOR    , "pic"},
-    { AV_CODEC_ID_V210X     , "yuv10"},
-    { AV_CODEC_ID_XBM       , "xbm"},
-    { AV_CODEC_ID_XWD       , "xwd"},
-    { AV_CODEC_ID_NONE      , NULL}
+    { AV_CODEC_ID_MJPEG,      "jpeg"     },
+    { AV_CODEC_ID_MJPEG,      "jpg"      },
+    { AV_CODEC_ID_MJPEG,      "jps"      },
+    { AV_CODEC_ID_LJPEG,      "ljpg"     },
+    { AV_CODEC_ID_JPEGLS,     "jls"      },
+    { AV_CODEC_ID_PNG,        "png"      },
+    { AV_CODEC_ID_PNG,        "pns"      },
+    { AV_CODEC_ID_PNG,        "mng"      },
+    { AV_CODEC_ID_PPM,        "ppm"      },
+    { AV_CODEC_ID_PPM,        "pnm"      },
+    { AV_CODEC_ID_PGM,        "pgm"      },
+    { AV_CODEC_ID_PGMYUV,     "pgmyuv"   },
+    { AV_CODEC_ID_PBM,        "pbm"      },
+    { AV_CODEC_ID_PAM,        "pam"      },
+    { AV_CODEC_ID_MPEG1VIDEO, "mpg1-img" },
+    { AV_CODEC_ID_MPEG2VIDEO, "mpg2-img" },
+    { AV_CODEC_ID_MPEG4,      "mpg4-img" },
+    { AV_CODEC_ID_FFV1,       "ffv1-img" },
+    { AV_CODEC_ID_RAWVIDEO,   "y"        },
+    { AV_CODEC_ID_RAWVIDEO,   "raw"      },
+    { AV_CODEC_ID_BMP,        "bmp"      },
+    { AV_CODEC_ID_GIF,        "gif"      },
+    { AV_CODEC_ID_TARGA,      "tga"      },
+    { AV_CODEC_ID_TIFF,       "tiff"     },
+    { AV_CODEC_ID_TIFF,       "tif"      },
+    { AV_CODEC_ID_SGI,        "sgi"      },
+    { AV_CODEC_ID_PTX,        "ptx"      },
+    { AV_CODEC_ID_PCX,        "pcx"      },
+    { AV_CODEC_ID_BRENDER_PIX, "pix"     },
+    { AV_CODEC_ID_SUNRAST,    "sun"      },
+    { AV_CODEC_ID_SUNRAST,    "ras"      },
+    { AV_CODEC_ID_SUNRAST,    "rs"       },
+    { AV_CODEC_ID_SUNRAST,    "im1"      },
+    { AV_CODEC_ID_SUNRAST,    "im8"      },
+    { AV_CODEC_ID_SUNRAST,    "im24"     },
+    { AV_CODEC_ID_SUNRAST,    "im32"     },
+    { AV_CODEC_ID_SUNRAST,    "sunras"   },
+    { AV_CODEC_ID_JPEG2000,   "j2c"      },
+    { AV_CODEC_ID_JPEG2000,   "j2k"      },
+    { AV_CODEC_ID_JPEG2000,   "jp2"      },
+    { AV_CODEC_ID_JPEG2000,   "jpc"      },
+    { AV_CODEC_ID_DPX,        "dpx"      },
+    { AV_CODEC_ID_EXR,        "exr"      },
+    { AV_CODEC_ID_PICTOR,     "pic"      },
+    { AV_CODEC_ID_V210X,      "yuv10"    },
+    { AV_CODEC_ID_XBM,        "xbm"      },
+    { AV_CODEC_ID_XFACE,      "xface"    },
+    { AV_CODEC_ID_XWD,        "xwd"      },
+    { AV_CODEC_ID_NONE,       NULL       }
 };
 
 static enum AVCodecID av_str2id(const IdStrMap *tags, const char *str)
 {
-    str= strrchr(str, '.');
-    if(!str) return AV_CODEC_ID_NONE;
+    str = strrchr(str, '.');
+    if (!str)
+        return AV_CODEC_ID_NONE;
     str++;
 
     while (tags->id) {
diff --git a/libavformat/img2dec.c b/libavformat/img2dec.c
index d1edf04..f492bba 100644
--- a/libavformat/img2dec.c
+++ b/libavformat/img2dec.c
@@ -61,6 +61,7 @@
 #endif
     int start_number;
     int start_number_range;
+    int frame_size;
 } VideoDemuxData;
 
 static const int sizes[][2] = {
@@ -79,13 +80,14 @@
 {
     int i;
 
-    for(i=0;i<FF_ARRAY_ELEMS(sizes);i++) {
+    for (i = 0; i < FF_ARRAY_ELEMS(sizes); i++) {
         if ((sizes[i][0] * sizes[i][1]) == size) {
-            *width_ptr = sizes[i][0];
+            *width_ptr  = sizes[i][0];
             *height_ptr = sizes[i][1];
             return 0;
         }
     }
+
     return -1;
 }
 
@@ -127,9 +129,9 @@
 
     /* find the first image */
     for (first_index = start_index; first_index < start_index + start_index_range; first_index++) {
-        if (av_get_frame_filename(buf, sizeof(buf), path, first_index) < 0){
+        if (av_get_frame_filename(buf, sizeof(buf), path, first_index) < 0) {
             *pfirst_index =
-            *plast_index = 1;
+            *plast_index  = 1;
             if (avio_check(buf, AVIO_FLAG_READ) > 0)
                 return 0;
             return -1;
@@ -142,9 +144,9 @@
 
     /* find the last image */
     last_index = first_index;
-    for(;;) {
+    for (;;) {
         range = 0;
-        for(;;) {
+        for (;;) {
             if (!range)
                 range1 = 1;
             else
@@ -165,33 +167,35 @@
         last_index += range;
     }
     *pfirst_index = first_index;
-    *plast_index = last_index;
+    *plast_index  = last_index;
     return 0;
- fail:
+
+fail:
     return -1;
 }
 
-
-static int read_probe(AVProbeData *p)
+static int img_read_probe(AVProbeData *p)
 {
     if (p->filename && ff_guess_image2_codec(p->filename)) {
         if (av_filename_number_test(p->filename))
             return AVPROBE_SCORE_MAX;
         else if (is_glob(p->filename))
             return AVPROBE_SCORE_MAX;
+        else if (av_match_ext(p->filename, "raw") || av_match_ext(p->filename, "gif"))
+            return 5;
         else
-            return AVPROBE_SCORE_MAX/2;
+            return AVPROBE_SCORE_MAX / 2;
     }
     return 0;
 }
 
-static int read_header(AVFormatContext *s1)
+static int img_read_header(AVFormatContext *s1)
 {
     VideoDemuxData *s = s1->priv_data;
     int first_index, last_index, ret = 0;
     int width = 0, height = 0;
     AVStream *st;
-    enum PixelFormat pix_fmt = PIX_FMT_NONE;
+    enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;
     AVRational framerate;
 
     s1->ctx_flags |= AVFMTCTX_NOHEADER;
@@ -201,28 +205,33 @@
         return AVERROR(ENOMEM);
     }
 
-    if (s->pixel_format && (pix_fmt = av_get_pix_fmt(s->pixel_format)) == PIX_FMT_NONE) {
-        av_log(s1, AV_LOG_ERROR, "No such pixel format: %s.\n", s->pixel_format);
+    if (s->pixel_format &&
+        (pix_fmt = av_get_pix_fmt(s->pixel_format)) == AV_PIX_FMT_NONE) {
+        av_log(s1, AV_LOG_ERROR, "No such pixel format: %s.\n",
+               s->pixel_format);
         return AVERROR(EINVAL);
     }
-    if (s->video_size && (ret = av_parse_video_size(&width, &height, s->video_size)) < 0) {
-        av_log(s, AV_LOG_ERROR, "Could not parse video size: %s.\n", s->video_size);
+    if (s->video_size &&
+        (ret = av_parse_video_size(&width, &height, s->video_size)) < 0) {
+        av_log(s, AV_LOG_ERROR,
+               "Could not parse video size: %s.\n", s->video_size);
         return ret;
     }
     if ((ret = av_parse_video_rate(&framerate, s->framerate)) < 0) {
-        av_log(s, AV_LOG_ERROR, "Could not parse framerate: %s.\n", s->framerate);
+        av_log(s, AV_LOG_ERROR,
+               "Could not parse framerate: %s.\n", s->framerate);
         return ret;
     }
 
     av_strlcpy(s->path, s1->filename, sizeof(s->path));
     s->img_number = 0;
-    s->img_count = 0;
+    s->img_count  = 0;
 
     /* find format */
     if (s1->iformat->flags & AVFMT_NOFILE)
         s->is_pipe = 0;
-    else{
-        s->is_pipe = 1;
+    else {
+        s->is_pipe       = 1;
         st->need_parsing = AVSTREAM_PARSE_FULL;
     }
 
@@ -295,43 +304,44 @@
                    "Unknown value '%d' for pattern_type option\n", s->pattern_type);
             return AVERROR(EINVAL);
         }
-        s->img_first = first_index;
-        s->img_last = last_index;
+        s->img_first  = first_index;
+        s->img_last   = last_index;
         s->img_number = first_index;
         /* compute duration */
         st->start_time = 0;
-        st->duration = last_index - first_index + 1;
+        st->duration   = last_index - first_index + 1;
     }
 
-    if(s1->video_codec_id){
+    if (s1->video_codec_id) {
         st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
-        st->codec->codec_id = s1->video_codec_id;
-    }else if(s1->audio_codec_id){
+        st->codec->codec_id   = s1->video_codec_id;
+    } else if (s1->audio_codec_id) {
         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
-        st->codec->codec_id = s1->audio_codec_id;
-    }else{
-        const char *str= strrchr(s->path, '.');
-        s->split_planes = str && !av_strcasecmp(str + 1, "y");
+        st->codec->codec_id   = s1->audio_codec_id;
+    } else {
+        const char *str = strrchr(s->path, '.');
+        s->split_planes       = str && !av_strcasecmp(str + 1, "y");
         st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
-        st->codec->codec_id = ff_guess_image2_codec(s->path);
+        st->codec->codec_id   = ff_guess_image2_codec(s->path);
         if (st->codec->codec_id == AV_CODEC_ID_LJPEG)
             st->codec->codec_id = AV_CODEC_ID_MJPEG;
     }
-    if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO && pix_fmt != PIX_FMT_NONE)
+    if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
+        pix_fmt != AV_PIX_FMT_NONE)
         st->codec->pix_fmt = pix_fmt;
 
     return 0;
 }
 
-static int read_packet(AVFormatContext *s1, AVPacket *pkt)
+static int img_read_packet(AVFormatContext *s1, AVPacket *pkt)
 {
     VideoDemuxData *s = s1->priv_data;
     char filename_bytes[1024];
     char *filename = filename_bytes;
     int i;
-    int size[3]={0}, ret[3]={0};
-    AVIOContext *f[3] = {NULL};
-    AVCodecContext *codec= s1->streams[0]->codec;
+    int size[3]           = { 0 }, ret[3] = { 0 };
+    AVIOContext *f[3]     = { NULL };
+    AVCodecContext *codec = s1->streams[0]->codec;
 
     if (!s->is_pipe) {
         /* loop over input */
@@ -346,49 +356,56 @@
 #endif
         } else {
         if (av_get_frame_filename(filename_bytes, sizeof(filename_bytes),
-                                  s->path, s->img_number)<0 && s->img_number > 1)
+                                  s->path,
+                                  s->img_number) < 0 && s->img_number > 1)
             return AVERROR(EIO);
         }
-        for(i=0; i<3; i++){
+        for (i = 0; i < 3; i++) {
             if (avio_open2(&f[i], filename, AVIO_FLAG_READ,
                            &s1->interrupt_callback, NULL) < 0) {
-                if(i>=1)
+                if (i >= 1)
                     break;
-                av_log(s1, AV_LOG_ERROR, "Could not open file : %s\n",filename);
+                av_log(s1, AV_LOG_ERROR, "Could not open file : %s\n",
+                       filename);
                 return AVERROR(EIO);
             }
-            size[i]= avio_size(f[i]);
+            size[i] = avio_size(f[i]);
 
-            if(!s->split_planes)
+            if (!s->split_planes)
                 break;
-            filename[ strlen(filename) - 1 ]= 'U' + i;
+            filename[strlen(filename) - 1] = 'U' + i;
         }
 
-        if(codec->codec_id == AV_CODEC_ID_RAWVIDEO && !codec->width)
+        if (codec->codec_id == AV_CODEC_ID_RAWVIDEO && !codec->width)
             infer_size(&codec->width, &codec->height, size[0]);
     } else {
         f[0] = s1->pb;
         if (url_feof(f[0]))
             return AVERROR(EIO);
-        size[0]= 4096;
+        if (s->frame_size > 0) {
+            size[0] = s->frame_size;
+        } else {
+            size[0] = 4096;
+        }
     }
 
-    av_new_packet(pkt, size[0] + size[1] + size[2]);
+    if (av_new_packet(pkt, size[0] + size[1] + size[2]) < 0)
+        return AVERROR(ENOMEM);
     pkt->stream_index = 0;
-    pkt->flags |= AV_PKT_FLAG_KEY;
+    pkt->flags       |= AV_PKT_FLAG_KEY;
 
-    pkt->size= 0;
-    for(i=0; i<3; i++){
-        if(f[i]){
-            ret[i]= avio_read(f[i], pkt->data + pkt->size, size[i]);
+    pkt->size = 0;
+    for (i = 0; i < 3; i++) {
+        if (f[i]) {
+            ret[i] = avio_read(f[i], pkt->data + pkt->size, size[i]);
             if (!s->is_pipe)
                 avio_close(f[i]);
-            if(ret[i]>0)
+            if (ret[i] > 0)
                 pkt->size += ret[i];
         }
     }
 
-    if (ret[0] <= 0 || ret[1]<0 || ret[2]<0) {
+    if (ret[0] <= 0 || ret[1] < 0 || ret[2] < 0) {
         av_free_packet(pkt);
         return AVERROR(EIO); /* signal EOF */
     } else {
@@ -398,7 +415,7 @@
     }
 }
 
-static int read_close(struct AVFormatContext* s1)
+static int img_read_close(struct AVFormatContext* s1)
 {
     VideoDemuxData *s = s1->priv_data;
 #if HAVE_GLOB
@@ -412,18 +429,19 @@
 #define OFFSET(x) offsetof(VideoDemuxData, x)
 #define DEC AV_OPT_FLAG_DECODING_PARAM
 static const AVOption options[] = {
-    { "framerate",    "set the video framerate",             OFFSET(framerate),    AV_OPT_TYPE_STRING, {.str = "25"}, 0, 0, DEC },
-    { "loop",         "force loop over input file sequence", OFFSET(loop),         AV_OPT_TYPE_INT,    {.i64 = 0},    0, 1, DEC },
+    { "framerate",    "set the video framerate",             OFFSET(framerate),    AV_OPT_TYPE_STRING, {.str = "25"}, 0, 0,       DEC },
+    { "loop",         "force loop over input file sequence", OFFSET(loop),         AV_OPT_TYPE_INT,    {.i64 = 0   }, 0, 1,       DEC },
 
-    { "pattern_type", "set pattern type",                    OFFSET(pattern_type), AV_OPT_TYPE_INT, {.i64=PT_GLOB_SEQUENCE}, 0, INT_MAX, DEC, "pattern_type"},
-    { "glob_sequence","glob/sequence pattern type",          0, AV_OPT_TYPE_CONST, {.i64=PT_GLOB_SEQUENCE}, INT_MIN, INT_MAX, DEC, "pattern_type" },
-    { "glob",         "glob pattern type",                   0, AV_OPT_TYPE_CONST, {.i64=PT_GLOB},          INT_MIN, INT_MAX, DEC, "pattern_type" },
-    { "sequence",     "glob pattern type",                   0, AV_OPT_TYPE_CONST, {.i64=PT_SEQUENCE},      INT_MIN, INT_MAX, DEC, "pattern_type" },
+    { "pattern_type", "set pattern type",                    OFFSET(pattern_type), AV_OPT_TYPE_INT,    {.i64=PT_GLOB_SEQUENCE}, 0,       INT_MAX, DEC, "pattern_type"},
+    { "glob_sequence","glob/sequence pattern type",          0,                    AV_OPT_TYPE_CONST,  {.i64=PT_GLOB_SEQUENCE}, INT_MIN, INT_MAX, DEC, "pattern_type" },
+    { "glob",         "glob pattern type",                   0,                    AV_OPT_TYPE_CONST,  {.i64=PT_GLOB         }, INT_MIN, INT_MAX, DEC, "pattern_type" },
+    { "sequence",     "glob pattern type",                   0,                    AV_OPT_TYPE_CONST,  {.i64=PT_SEQUENCE     }, INT_MIN, INT_MAX, DEC, "pattern_type" },
 
-    { "pixel_format", "set video pixel format",              OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
-    { "start_number", "set first number in the sequence",    OFFSET(start_number), AV_OPT_TYPE_INT,    {.i64 = 0},    0, INT_MAX, DEC },
+    { "pixel_format", "set video pixel format",              OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0,       DEC },
+    { "start_number", "set first number in the sequence",    OFFSET(start_number), AV_OPT_TYPE_INT,    {.i64 = 0   }, 0, INT_MAX, DEC },
     { "start_number_range", "set range for looking at the first sequence number", OFFSET(start_number_range), AV_OPT_TYPE_INT, {.i64 = 5}, 1, INT_MAX, DEC },
-    { "video_size",   "set video size",                      OFFSET(video_size),   AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
+    { "video_size",   "set video size",                      OFFSET(video_size),   AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0,       DEC },
+    { "frame_size",   "force frame size in bytes",           OFFSET(frame_size),   AV_OPT_TYPE_INT,    {.i64 = 0   }, 0, INT_MAX, DEC },
     { NULL },
 };
 
@@ -438,10 +456,10 @@
     .name           = "image2",
     .long_name      = NULL_IF_CONFIG_SMALL("image2 sequence"),
     .priv_data_size = sizeof(VideoDemuxData),
-    .read_probe     = read_probe,
-    .read_header    = read_header,
-    .read_packet    = read_packet,
-    .read_close     = read_close,
+    .read_probe     = img_read_probe,
+    .read_header    = img_read_header,
+    .read_packet    = img_read_packet,
+    .read_close     = img_read_close,
     .flags          = AVFMT_NOFILE,
     .priv_class     = &img2_class,
 };
@@ -457,8 +475,8 @@
     .name           = "image2pipe",
     .long_name      = NULL_IF_CONFIG_SMALL("piped image2 sequence"),
     .priv_data_size = sizeof(VideoDemuxData),
-    .read_header    = read_header,
-    .read_packet    = read_packet,
+    .read_header    = img_read_header,
+    .read_packet    = img_read_packet,
     .priv_class     = &img2pipe_class,
 };
 #endif
diff --git a/libavformat/img2enc.c b/libavformat/img2enc.c
index 2956ca0..9621d3c 100644
--- a/libavformat/img2enc.c
+++ b/libavformat/img2enc.c
@@ -24,6 +24,7 @@
 #include "libavutil/avstring.h"
 #include "libavutil/log.h"
 #include "libavutil/opt.h"
+#include "libavutil/pixdesc.h"
 #include "avformat.h"
 #include "avio_internal.h"
 #include "internal.h"
@@ -41,6 +42,8 @@
 static int write_header(AVFormatContext *s)
 {
     VideoMuxData *img = s->priv_data;
+    AVStream *st = s->streams[0];
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(st->codec->pix_fmt);
     const char *str;
 
     av_strlcpy(img->path, s->filename, sizeof(img->path));
@@ -52,74 +55,65 @@
         img->is_pipe = 1;
 
     str = strrchr(img->path, '.');
-    img->split_planes = str && !av_strcasecmp(str + 1, "y");
+    img->split_planes =     str
+                         && !av_strcasecmp(str + 1, "y")
+                         && s->nb_streams == 1
+                         && st->codec->codec_id == AV_CODEC_ID_RAWVIDEO
+                         && desc
+                         &&(desc->flags & PIX_FMT_PLANAR)
+                         && desc->nb_components >= 3;
     return 0;
 }
 
 static int write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     VideoMuxData *img = s->priv_data;
-    AVIOContext *pb[3];
+    AVIOContext *pb[4];
     char filename[1024];
-    AVCodecContext *codec= s->streams[ pkt->stream_index ]->codec;
+    AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(codec->pix_fmt);
     int i;
 
     if (!img->is_pipe) {
         if (av_get_frame_filename(filename, sizeof(filename),
-                                  img->path, img->img_number) < 0 && img->img_number>1 && !img->updatefirst) {
+                                  img->path, img->img_number) < 0 && img->img_number > 1 && !img->updatefirst) {
             av_log(s, AV_LOG_ERROR,
                    "Could not get frame filename number %d from pattern '%s'\n",
                    img->img_number, img->path);
             return AVERROR(EINVAL);
         }
-        for(i=0; i<3; i++){
+        for (i = 0; i < 4; i++) {
             if (avio_open2(&pb[i], filename, AVIO_FLAG_WRITE,
                            &s->interrupt_callback, NULL) < 0) {
-                av_log(s, AV_LOG_ERROR, "Could not open file : %s\n",filename);
+                av_log(s, AV_LOG_ERROR, "Could not open file : %s\n", filename);
                 return AVERROR(EIO);
             }
 
-            if(!img->split_planes)
+            if (!img->split_planes || i+1 >= desc->nb_components)
                 break;
-            filename[ strlen(filename) - 1 ]= 'U' + i;
+            filename[strlen(filename) - 1] = ((int[]){'U','V','A','x'})[i];
         }
     } else {
         pb[0] = s->pb;
     }
 
-    if(img->split_planes){
+    if (img->split_planes) {
         int ysize = codec->width * codec->height;
-        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);
+        int usize = ((-codec->width)>>desc->log2_chroma_w) * ((-codec->height)>>desc->log2_chroma_h);
+        if (desc->comp[0].depth_minus1 >= 8) {
+            ysize *= 2;
+            usize *= 2;
+        }
+        avio_write(pb[0], pkt->data                , ysize);
+        avio_write(pb[1], pkt->data + ysize        , usize);
+        avio_write(pb[2], pkt->data + ysize + usize, usize);
         avio_close(pb[1]);
         avio_close(pb[2]);
-    }else{
-        if(ff_guess_image2_codec(s->filename) == AV_CODEC_ID_JPEG2000){
-            AVStream *st = s->streams[0];
-            if(st->codec->extradata_size > 8 &&
-               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;
-                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 && AV_RB32(pkt->data) == 0xFF4FFF51){
-                //jpeg2000 codestream
-            }else if(pkt->size < 8 ||
-                     (!st->codec->extradata_size &&
-                      AV_RL32(pkt->data+4) != MKTAG('j','P',' ',' '))){ // signature
-            error:
-                av_log(s, AV_LOG_ERROR, "malformed JPEG 2000 codestream %X\n", AV_RB32(pkt->data));
-                return -1;
-            }
+        if (desc->nb_components > 3) {
+            avio_write(pb[3], pkt->data + ysize + 2*usize, ysize);
+            avio_close(pb[3]);
         }
+    } else {
         avio_write(pb[0], pkt->data, pkt->size);
     }
     avio_flush(pb[0]);
@@ -134,8 +128,8 @@
 #define OFFSET(x) offsetof(VideoMuxData, x)
 #define ENC AV_OPT_FLAG_ENCODING_PARAM
 static const AVOption muxoptions[] = {
-    { "updatefirst",  "", OFFSET(updatefirst),  AV_OPT_TYPE_INT,    {.i64 = 0},    0, 1, ENC },
-    { "start_number", "first number in the sequence", OFFSET(img_number), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, ENC },
+    { "updatefirst",  "",                            OFFSET(updatefirst), AV_OPT_TYPE_INT, { .i64 = 0 }, 0,       1, ENC },
+    { "start_number", "first number in the sequence", OFFSET(img_number), AV_OPT_TYPE_INT, { .i64 = 1 }, 1, INT_MAX, ENC },
     { NULL },
 };
 
@@ -152,7 +146,7 @@
     .long_name      = NULL_IF_CONFIG_SMALL("image2 sequence"),
     .extensions     = "bmp,dpx,jls,jpeg,jpg,ljpg,pam,pbm,pcx,pgm,pgmyuv,png,"
                       "ppm,sgi,tga,tif,tiff,jp2,j2c,xwd,sun,ras,rs,im1,im8,im24,"
-                      "sunras,xbm",
+                      "sunras,xbm,xface",
     .priv_data_size = sizeof(VideoMuxData),
     .video_codec    = AV_CODEC_ID_MJPEG,
     .write_header   = write_header,
diff --git a/libavformat/internal.h b/libavformat/internal.h
index cd91eb1..14f4cdb 100644
--- a/libavformat/internal.h
+++ b/libavformat/internal.h
@@ -123,7 +123,8 @@
  *
  * @param buff the buffer to append the SDP fragment to
  * @param size the size of the buff buffer
- * @param c the AVCodecContext of the media to describe
+ * @param st the AVStream of the media to describe
+ * @param idx the global stream index
  * @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
@@ -131,7 +132,7 @@
  * @param fmt the AVFormatContext, which might contain options modifying
  *            the generated SDP
  */
-void ff_sdp_write_media(char *buff, int size, AVCodecContext *c,
+void ff_sdp_write_media(char *buff, int size, AVStream *st, int idx,
                         const char *dest_addr, const char *dest_type,
                         int port, int ttl, AVFormatContext *fmt);
 
@@ -239,7 +240,7 @@
  */
 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
@@ -346,4 +347,40 @@
 
 void ff_free_stream(AVFormatContext *s, AVStream *st);
 
+/**
+ * Return the frame duration in seconds. Return 0 if not available.
+ */
+void ff_compute_frame_duration(int *pnum, int *pden, AVStream *st,
+                               AVCodecParserContext *pc, AVPacket *pkt);
+
+int ff_get_audio_frame_size(AVCodecContext *enc, int size, int mux);
+
+unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id);
+
+enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag);
+
+/**
+ * Select a PCM codec based on the given parameters.
+ *
+ * @param bps     bits-per-sample
+ * @param flt     floating-point
+ * @param be      big-endian
+ * @param sflags  signed flags. each bit corresponds to one byte of bit depth.
+ *                e.g. the 1st bit indicates if 8-bit should be signed or
+ *                unsigned, the 2nd bit indicates if 16-bit should be signed or
+ *                unsigned, etc... This is useful for formats such as WAVE where
+ *                only 8-bit is unsigned and all other bit depths are signed.
+ * @return        a PCM codec id or AV_CODEC_ID_NONE
+ */
+enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags);
+
+/**
+ * Chooses a timebase for muxing the specified stream.
+ *
+ * The choosen timebase allows sample accurate timestamps based
+ * on the framerate or sample rate for audio streams. It also is
+ * at least as precisse as 1/min_precission would be.
+ */
+AVRational ff_choose_timebase(AVFormatContext *s, AVStream *st, int min_precission);
+
 #endif /* AVFORMAT_INTERNAL_H */
diff --git a/libavformat/ipmovie.c b/libavformat/ipmovie.c
index 748f4a4..17ef7bb 100644
--- a/libavformat/ipmovie.c
+++ b/libavformat/ipmovie.c
@@ -32,6 +32,7 @@
  * up and sending out the chunks.
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "internal.h"
@@ -605,6 +606,8 @@
         st->codec->codec_id = ipmovie->audio_type;
         st->codec->codec_tag = 0;  /* no tag */
         st->codec->channels = ipmovie->audio_channels;
+        st->codec->channel_layout = st->codec->channels == 1 ? AV_CH_LAYOUT_MONO :
+                                                               AV_CH_LAYOUT_STEREO;
         st->codec->sample_rate = ipmovie->audio_sample_rate;
         st->codec->bits_per_coded_sample = ipmovie->audio_bits;
         st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *
diff --git a/libavformat/isom.c b/libavformat/isom.c
index caa4d17..811184b 100644
--- a/libavformat/isom.c
+++ b/libavformat/isom.c
@@ -26,7 +26,6 @@
 #include "avformat.h"
 #include "internal.h"
 #include "isom.h"
-#include "riff.h"
 #include "libavcodec/mpeg4audio.h"
 #include "libavcodec/mpegaudiodata.h"
 
@@ -104,6 +103,7 @@
     { AV_CODEC_ID_V410,   MKTAG('v', '4', '1', '0') }, /* UNCOMPRESSED 10BIT 4:4:4 */
     { AV_CODEC_ID_Y41P,   MKTAG('Y', '4', '1', 'P') }, /* UNCOMPRESSED 12BIT 4:1:1 */
     { AV_CODEC_ID_YUV4,   MKTAG('y', 'u', 'v', '4') }, /* libquicktime packed yuv420p */
+    { AV_CODEC_ID_TARGA_Y216, MKTAG('Y', '2', '1', '6') },
 
     { AV_CODEC_ID_MJPEG,  MKTAG('j', 'p', 'e', 'g') }, /* PhotoJPEG */
     { AV_CODEC_ID_MJPEG,  MKTAG('m', 'j', 'p', 'a') }, /* Motion-JPEG (format A) */
@@ -227,7 +227,7 @@
 
     { AV_CODEC_ID_DIRAC,     MKTAG('d', 'r', 'a', 'c') },
     { AV_CODEC_ID_DNXHD,     MKTAG('A', 'V', 'd', 'n') }, /* AVID DNxHD */
-//  { AV_CODEC_ID_FLV1,      MKTAG('H', '2', '6', '3') }, /* Flash Media Server */
+//  { AV_CODEC_ID_FLV1,      MKTAG('H', '2', '6', '3') }, /* Flash Media Server, forced in demuxer */
     { AV_CODEC_ID_MSMPEG4V3, MKTAG('3', 'I', 'V', 'D') }, /* 3ivx DivX Doctor */
     { AV_CODEC_ID_RAWVIDEO,  MKTAG('A', 'V', '1', 'x') }, /* AVID 1:1x */
     { AV_CODEC_ID_RAWVIDEO,  MKTAG('A', 'V', 'u', 'p') },
@@ -433,6 +433,11 @@
     avio_rb32(pb); /* max bitrate */
     avio_rb32(pb); /* avg bitrate */
 
+    if(avcodec_is_open(st->codec)) {
+        av_log(fc, AV_LOG_DEBUG, "codec open in read_dec_config_descr\n");
+        return -1;
+    }
+
     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);
diff --git a/libavformat/isom.h b/libavformat/isom.h
index 875c3a9..f6eba56 100644
--- a/libavformat/isom.h
+++ b/libavformat/isom.h
@@ -42,18 +42,18 @@
  * Here we just use what is needed to read the chunks
  */
 
-typedef struct {
+typedef struct MOVStts {
     int count;
     int duration;
 } MOVStts;
 
-typedef struct {
+typedef struct MOVStsc {
     int first;
     int count;
     int id;
 } MOVStsc;
 
-typedef struct {
+typedef struct MOVDref {
     uint32_t type;
     char *path;
     char *dir;
@@ -62,14 +62,14 @@
     int16_t nlvl_to, nlvl_from;
 } MOVDref;
 
-typedef struct {
+typedef struct MOVAtom {
     uint32_t type;
     int64_t size; /* total size (excluding the size and type fields) */
 } MOVAtom;
 
 struct MOVParseTableEntry;
 
-typedef struct {
+typedef struct MOVFragment {
     unsigned track_id;
     uint64_t base_data_offset;
     uint64_t moof_offset;
@@ -79,7 +79,7 @@
     unsigned flags;
 } MOVFragment;
 
-typedef struct {
+typedef struct MOVTrackExt {
     unsigned track_id;
     unsigned stsd_id;
     unsigned duration;
@@ -87,7 +87,7 @@
     unsigned flags;
 } MOVTrackExt;
 
-typedef struct {
+typedef struct MOVSbgp {
     unsigned int count;
     unsigned int index;
 } MOVSbgp;
@@ -161,6 +161,7 @@
     int itunes_metadata;  ///< metadata are itunes style
     int chapter_track;
     int use_absolute_path;
+    int ignore_editlist;
     int64_t next_root_atom; ///< offset of the next root atom
 } MOVContext;
 
@@ -204,7 +205,6 @@
 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags);
 
 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries);
-int ff_mov_read_chan(AVFormatContext *s, AVIOContext *pb, AVStream *st, int64_t size);
 void ff_mov_write_chan(AVIOContext *pb, int64_t channel_layout);
 
 #endif /* AVFORMAT_ISOM_H */
diff --git a/libavformat/iss.c b/libavformat/iss.c
index 4268900..e4335b4 100644
--- a/libavformat/iss.c
+++ b/libavformat/iss.c
@@ -26,6 +26,7 @@
  * @see http://wiki.multimedia.cx/index.php?title=FunCom_ISS
  */
 
+#include "libavutil/channel_layout.h"
 #include "avformat.h"
 #include "internal.h"
 #include "libavutil/avstring.h"
@@ -99,7 +100,13 @@
         return AVERROR(ENOMEM);
     st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
     st->codec->codec_id = AV_CODEC_ID_ADPCM_IMA_ISS;
-    st->codec->channels = stereo ? 2 : 1;
+    if (stereo) {
+        st->codec->channels       = 2;
+        st->codec->channel_layout = AV_CH_LAYOUT_STEREO;
+    } else {
+        st->codec->channels       = 1;
+        st->codec->channel_layout = AV_CH_LAYOUT_MONO;
+    }
     st->codec->sample_rate = 44100;
     if(rate_divisor > 0)
          st->codec->sample_rate /= rate_divisor;
diff --git a/libavformat/jacosubdec.c b/libavformat/jacosubdec.c
index f9defd2..1c58e3b 100644
--- a/libavformat/jacosubdec.c
+++ b/libavformat/jacosubdec.c
@@ -248,6 +248,14 @@
     return ff_subtitles_queue_read_packet(&jacosub->q, pkt);
 }
 
+static int jacosub_read_seek(AVFormatContext *s, int stream_index,
+                             int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
+{
+    JACOsubContext *jacosub = s->priv_data;
+    return ff_subtitles_queue_seek(&jacosub->q, s, stream_index,
+                                   min_ts, ts, max_ts, flags);
+}
+
 AVInputFormat ff_jacosub_demuxer = {
     .name           = "jacosub",
     .long_name      = NULL_IF_CONFIG_SMALL("JACOsub subtitle format"),
@@ -255,6 +263,7 @@
     .read_probe     = jacosub_probe,
     .read_header    = jacosub_read_header,
     .read_packet    = jacosub_read_packet,
+    .read_seek2     = jacosub_read_seek,
     .read_close     = jacosub_read_close,
     .flags          = AVFMT_GENERIC_INDEX,
 };
diff --git a/libavformat/jvdec.c b/libavformat/jvdec.c
index 2eac265..e941492 100644
--- a/libavformat/jvdec.c
+++ b/libavformat/jvdec.c
@@ -25,6 +25,7 @@
  * @author Peter Ross <pross@xvid.org>
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "internal.h"
@@ -91,6 +92,7 @@
     ast->codec->codec_tag   = 0; /* no fourcc */
     ast->codec->sample_rate = avio_rl16(pb);
     ast->codec->channels    = 1;
+    ast->codec->channel_layout = AV_CH_LAYOUT_MONO;
     avpriv_set_pts_info(ast, 64, 1, ast->codec->sample_rate);
 
     avio_skip(pb, 10);
diff --git a/libavformat/log2_tab.c b/libavformat/log2_tab.c
new file mode 100644
index 0000000..47a1df0
--- /dev/null
+++ b/libavformat/log2_tab.c
@@ -0,0 +1 @@
+#include "libavutil/log2_tab.c"
diff --git a/libavformat/lvfdec.c b/libavformat/lvfdec.c
new file mode 100644
index 0000000..08a0891
--- /dev/null
+++ b/libavformat/lvfdec.c
@@ -0,0 +1,148 @@
+/*
+ * LVF demuxer
+ * Copyright (c) 2012 Paul B Mahol
+ *
+ * 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/intreadwrite.h"
+#include "avformat.h"
+#include "riff.h"
+
+static int lvf_probe(AVProbeData *p)
+{
+    if (AV_RL32(p->buf) == MKTAG('L', 'V', 'F', 'F'))
+        return AVPROBE_SCORE_MAX / 2;
+    return 0;
+}
+
+static int lvf_read_header(AVFormatContext *s)
+{
+    AVStream *st;
+    int64_t next_offset;
+    unsigned size, nb_streams, id;
+
+    avio_skip(s->pb, 16);
+    nb_streams = avio_rl32(s->pb);
+    if (!nb_streams)
+        return AVERROR_INVALIDDATA;
+    if (nb_streams > 2) {
+        av_log_ask_for_sample(s, "too many streams\n");
+        return AVERROR_PATCHWELCOME;
+    }
+
+    avio_skip(s->pb, 1012);
+
+    while (!url_feof(s->pb)) {
+        id          = avio_rl32(s->pb);
+        size        = avio_rl32(s->pb);
+        next_offset = avio_tell(s->pb) + size;
+
+        switch (id) {
+        case MKTAG('0', '0', 'f', 'm'):
+            st = avformat_new_stream(s, 0);
+            if (!st)
+                return AVERROR(ENOMEM);
+
+            st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
+            avio_skip(s->pb, 4);
+            st->codec->width      = avio_rl32(s->pb);
+            st->codec->height     = avio_rl32(s->pb);
+            avio_skip(s->pb, 4);
+            st->codec->codec_tag  = avio_rl32(s->pb);
+            st->codec->codec_id   = ff_codec_get_id(ff_codec_bmp_tags,
+                                                    st->codec->codec_tag);
+            avpriv_set_pts_info(st, 32, 1, 1000);
+            break;
+        case MKTAG('0', '1', 'f', 'm'):
+            st = avformat_new_stream(s, 0);
+            if (!st)
+                return AVERROR(ENOMEM);
+
+            st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
+            st->codec->codec_tag   = avio_rl16(s->pb);
+            st->codec->channels    = avio_rl16(s->pb);
+            st->codec->sample_rate = avio_rl16(s->pb);
+            avio_skip(s->pb, 8);
+            st->codec->bits_per_coded_sample = avio_r8(s->pb);
+            st->codec->codec_id    = ff_codec_get_id(ff_codec_wav_tags,
+                                                     st->codec->codec_tag);
+            avpriv_set_pts_info(st, 32, 1, 1000);
+            break;
+        case 0:
+            avio_seek(s->pb, 2048 + 8, SEEK_SET);
+            return 0;
+        default:
+            av_log_ask_for_sample(s, "unknown id\n");
+            return AVERROR_PATCHWELCOME;
+        }
+
+        avio_seek(s->pb, next_offset, SEEK_SET);
+    }
+
+    return AVERROR_EOF;
+}
+
+static int lvf_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    unsigned size, flags, timestamp, id;
+    int64_t pos;
+    int ret, is_video = 0;
+
+    pos = avio_tell(s->pb);
+    while (!url_feof(s->pb)) {
+        id    = avio_rl32(s->pb);
+        size  = avio_rl32(s->pb);
+
+        if (size == 0xFFFFFFFFu)
+            return AVERROR_EOF;
+
+        switch (id) {
+        case MKTAG('0', '0', 'd', 'c'):
+            is_video = 1;
+        case MKTAG('0', '1', 'w', 'b'):
+            if (size < 8)
+                return AVERROR_INVALIDDATA;
+            timestamp = avio_rl32(s->pb);
+            flags = avio_rl32(s->pb);
+            ret = av_get_packet(s->pb, pkt, size - 8);
+            if (flags & (1 << 12))
+                pkt->flags |= AV_PKT_FLAG_KEY;
+            pkt->stream_index = is_video ? 0 : 1;
+            pkt->pts          = timestamp;
+            pkt->pos          = pos;
+            return ret;
+        default:
+            ret = avio_skip(s->pb, size);
+        }
+
+        if (ret < 0)
+            return ret;
+    }
+
+    return AVERROR_EOF;
+}
+
+AVInputFormat ff_lvf_demuxer = {
+    .name        = "lvf",
+    .long_name   = NULL_IF_CONFIG_SMALL("LVF"),
+    .read_probe  = lvf_probe,
+    .read_header = lvf_read_header,
+    .read_packet = lvf_read_packet,
+    .extensions  = "lvf",
+    .flags       = AVFMT_GENERIC_INDEX,
+};
diff --git a/libavformat/lxfdec.c b/libavformat/lxfdec.c
index 539a86a..90c4974 100644
--- a/libavformat/lxfdec.c
+++ b/libavformat/lxfdec.c
@@ -23,7 +23,6 @@
 #include "libavcodec/bytestream.h"
 #include "avformat.h"
 #include "internal.h"
-#include "riff.h"
 
 #define LXF_MAX_PACKET_HEADER_SIZE 256
 #define LXF_HEADER_DATA_SIZE    120
@@ -40,7 +39,7 @@
     { AV_CODEC_ID_DVVIDEO,     4 },    //DV25
     { AV_CODEC_ID_DVVIDEO,     5 },    //DVCPRO
     { AV_CODEC_ID_DVVIDEO,     6 },    //DVCPRO50
-    { AV_CODEC_ID_RAWVIDEO,    7 },    //PIX_FMT_ARGB, where alpha is used for chroma keying
+    { AV_CODEC_ID_RAWVIDEO,    7 },    //AV_PIX_FMT_ARGB, where alpha is used for chroma keying
     { AV_CODEC_ID_RAWVIDEO,    8 },    //16-bit chroma key
     { AV_CODEC_ID_MPEG2VIDEO,  9 },    //4:2:2 CBP ("Constrained Bytes per Gop")
     { AV_CODEC_ID_NONE,        0 },
@@ -48,7 +47,6 @@
 
 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
     uint32_t video_format, packet_type, extended_size;
 } LXFDemuxContext;
@@ -165,7 +163,7 @@
         break;
     case 1:
         //audio
-        if (!(st = s->streams[1])) {
+        if (!s->streams || !(st = s->streams[1])) {
             av_log(s, AV_LOG_INFO, "got audio packet, but no audio stream present\n");
             break;
         }
@@ -185,10 +183,10 @@
         }
 
         switch (st->codec->bits_per_coded_sample) {
-        case 16: st->codec->codec_id = AV_CODEC_ID_PCM_S16LE; break;
+        case 16: st->codec->codec_id = AV_CODEC_ID_PCM_S16LE_PLANAR; break;
         case 20: st->codec->codec_id = AV_CODEC_ID_PCM_LXF;   break;
-        case 24: st->codec->codec_id = AV_CODEC_ID_PCM_S24LE; break;
-        case 32: st->codec->codec_id = AV_CODEC_ID_PCM_S32LE; break;
+        case 24: st->codec->codec_id = AV_CODEC_ID_PCM_S24LE_PLANAR; break;
+        case 32: st->codec->codec_id = AV_CODEC_ID_PCM_S32LE_PLANAR; break;
         default:
             av_log(s, AV_LOG_WARNING,
                    "only 16-, 20-, 24- and 32-bit PCM currently supported\n");
@@ -288,28 +286,10 @@
     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 *buf;
     AVStream *ast = NULL;
     uint32_t stream;
     int ret, ret2;
@@ -339,20 +319,14 @@
     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 != AV_CODEC_ID_PCM_LXF ? lxf->temp : pkt->data;
-
-    if ((ret2 = avio_read(pb, buf, ret)) != ret) {
+    if ((ret2 = avio_read(pb, pkt->data, ret)) != ret) {
         av_free_packet(pkt);
         return ret2 < 0 ? ret2 : AVERROR_EOF;
     }
 
     pkt->stream_index = stream;
 
-    if (ast) {
-        if(ast->codec->codec_id != AV_CODEC_ID_PCM_LXF)
-            deplanarize(lxf, ast, pkt->data, ret);
-    } else {
+    if (!ast) {
         //picture type (0 = closed I, 1 = open I, 2 = P, 3 = B)
         if (((lxf->video_format >> 22) & 0x3) < 2)
             pkt->flags |= AV_PKT_FLAG_KEY;
diff --git a/libavformat/matroskadec.c b/libavformat/matroskadec.c
index 145743b..4fd4c65 100644
--- a/libavformat/matroskadec.c
+++ b/libavformat/matroskadec.c
@@ -36,7 +36,7 @@
 #include "riff.h"
 #include "isom.h"
 #if CONFIG_SIPR_DECODER
-#include "rm.h"
+#include "rmsipr.h"
 #endif
 #include "matroska.h"
 #include "libavcodec/bytestream.h"
@@ -44,7 +44,7 @@
 #include "libavutil/intfloat.h"
 #include "libavutil/intreadwrite.h"
 #include "libavutil/avstring.h"
-#if HAVE_LZO1X_999_COMPRESS
+#if CONFIG_LZO
 #include "libavutil/lzo.h"
 #endif
 #include "libavutil/dict.h"
@@ -766,8 +766,8 @@
  */
 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
 {
-    av_free(bin->data);
-    if (!(bin->data = av_malloc(length)))
+    av_fast_padded_malloc(&bin->data, &bin->size, length);
+    if (!bin->data)
         return AVERROR(ENOMEM);
 
     bin->size = length;
@@ -1066,7 +1066,7 @@
         uint8_t *header = encodings[0].compression.settings.data;
 
         if (header_size && !header) {
-            av_log(0, AV_LOG_ERROR, "Compression size but no data in headerstrip\n");
+            av_log(NULL, AV_LOG_ERROR, "Compression size but no data in headerstrip\n");
             return -1;
         }
 
@@ -1082,7 +1082,7 @@
         memcpy(pkt_data + header_size, data, isize);
         break;
     }
-#if HAVE_LZO1X_999_COMPRESS
+#if CONFIG_LZO
     case MATROSKA_TRACK_ENCODING_COMP_LZO:
         do {
             olen = pkt_size *= 3;
@@ -1218,8 +1218,10 @@
     int ret = av_grow_packet(out, in->size);
     if (ret < 0)
         return ret;
+
     memcpy(out->data + out->size - in->size, in->data, in->size);
-    av_destruct_packet(in);
+
+    av_free_packet(in);
     av_free(in);
     return 0;
 }
@@ -1554,17 +1556,17 @@
                    "Multiple combined encodings not supported");
         } else if (encodings_list->nb_elem == 1) {
             if (encodings[0].type ||
-                (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP
+                (
 #if CONFIG_ZLIB
-                 && encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB
+                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
 #endif
 #if CONFIG_BZLIB
-                 && encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB
+                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
 #endif
-#if HAVE_LZO1X_999_COMPRESS
-                 && encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO
+#if CONFIG_LZO
+                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
 #endif
-               )) {
+                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP)) {
                 encodings[0].scope = 0;
                 av_log(matroska->ctx, AV_LOG_ERROR,
                        "Unsupported encoding type");
@@ -1681,11 +1683,10 @@
         } else if (codec_id == AV_CODEC_ID_RA_144) {
             track->audio.out_samplerate = 8000;
             track->audio.channels = 1;
-        }
-#if CONFIG_RA_288_DECODER || CONFIG_COOK_DECODER || CONFIG_ATRAC3_DECODER || CONFIG_SIPR_DECODER
-          else if ((codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
+        } else if ((codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
                     codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR)
                     && track->codec_priv.data) {
+#if CONFIG_RA_288_DECODER || CONFIG_COOK_DECODER || CONFIG_ATRAC3_DECODER || CONFIG_SIPR_DECODER
             int flavor;
 
             ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
@@ -1702,18 +1703,18 @@
                 st->codec->block_align = track->audio.coded_framesize;
                 track->codec_priv.size = 0;
             } else {
-#if CONFIG_SIPR_DECODER
                 if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
                     const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
                     track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
                     st->codec->bit_rate = sipr_bit_rate[flavor];
                 }
-#endif
                 st->codec->block_align = track->audio.sub_packet_size;
                 extradata_offset = 78;
             }
-        }
+#else
+            return AVERROR_INVALIDDATA;
 #endif
+        }
         track->codec_priv.size -= extradata_offset;
 
         if (codec_id == AV_CODEC_ID_NONE)
@@ -2039,7 +2040,7 @@
             }
             memcpy(track->audio.buf + y*w, data, w);
         } else {
-            if (size < sps * w / sps) {
+            if (size < sps * w / sps || h<=0) {
                 av_log(matroska->ctx, AV_LOG_ERROR,
                        "Corrupt generic RM-style audio packet size\n");
                 return AVERROR_INVALIDDATA;
@@ -2049,18 +2050,24 @@
         }
 
         if (++track->audio.sub_packet_cnt >= h) {
+            if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
 #if CONFIG_SIPR_DECODER
-            if (st->codec->codec_id == AV_CODEC_ID_SIPR)
                 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
+#else
+                return AVERROR_INVALIDDATA;
 #endif
+            }
             track->audio.sub_packet_cnt = 0;
             track->audio.pkt_cnt = h*w / a;
         }
     }
 
     while (track->audio.pkt_cnt) {
-        AVPacket *pkt = av_mallocz(sizeof(AVPacket));
-        av_new_packet(pkt, a);
+        AVPacket *pkt = NULL;
+        if (!(pkt = av_mallocz(sizeof(AVPacket))) || av_new_packet(pkt, a) < 0){
+            av_free(pkt);
+            return AVERROR(ENOMEM);
+        }
         memcpy(pkt->data, track->audio.buf
                + a * (h*w / a - track->audio.pkt_cnt--), a);
         pkt->pts = track->audio.buf_timecode;
@@ -2241,6 +2248,7 @@
             av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
             break;
         }
+
         if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
              st->codec->codec_id == AV_CODEC_ID_COOK ||
              st->codec->codec_id == AV_CODEC_ID_SIPR ||
@@ -2414,7 +2422,7 @@
         tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
         tracks[i].end_timecode = 0;
         if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
-            && !tracks[i].stream->discard != AVDISCARD_ALL) {
+            && tracks[i].stream->discard != AVDISCARD_ALL) {
             index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
             if (index_sub >= 0
                 && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
diff --git a/libavformat/matroskaenc.c b/libavformat/matroskaenc.c
index 4fd30b8..2a8a2ea 100644
--- a/libavformat/matroskaenc.c
+++ b/libavformat/matroskaenc.c
@@ -118,7 +118,7 @@
 {
     int i = ebml_id_size(id);
     while (i--)
-        avio_w8(pb, id >> (i*8));
+        avio_w8(pb, (uint8_t)(id >> (i*8)));
 }
 
 /**
@@ -166,7 +166,7 @@
 
     num |= 1ULL << bytes*7;
     for (i = bytes - 1; i >= 0; i--)
-        avio_w8(pb, num >> i*8);
+        avio_w8(pb, (uint8_t)(num >> i*8));
 }
 
 static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
@@ -178,7 +178,7 @@
     put_ebml_id(pb, elementid);
     put_ebml_num(pb, bytes, 0);
     for (i = bytes - 1; i >= 0; i--)
-        avio_w8(pb, val >> i*8);
+        avio_w8(pb, (uint8_t)(val >> i*8));
 }
 
 static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
@@ -368,13 +368,13 @@
 {
     mkv_cuepoint *entries = cues->entries;
 
+    if (ts < 0)
+        return 0;
+
     entries = av_realloc(entries, (cues->num_entries + 1) * sizeof(mkv_cuepoint));
     if (entries == NULL)
         return AVERROR(ENOMEM);
 
-    if (ts < 0)
-        return 0;
-
     entries[cues->num_entries  ].pts = ts;
     entries[cues->num_entries  ].tracknum = stream + 1;
     entries[cues->num_entries++].cluster_pos = cluster_pos - cues->segment_offset;
@@ -640,7 +640,6 @@
                     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);
                 }
 
                 if (codec->codec_id == AV_CODEC_ID_RAWVIDEO) {
@@ -903,6 +902,9 @@
     if (!strcmp(s->oformat->name, "webm")) mkv->mode = MODE_WEBM;
     else                                   mkv->mode = MODE_MATROSKAv2;
 
+    if (s->avoid_negative_ts < 0)
+        s->avoid_negative_ts = 1;
+
     mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
     if (!mkv->tracks)
         return AVERROR(ENOMEM);
@@ -1013,8 +1015,8 @@
     if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
                &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
         return 0;
-    start = 3600000*sh + 60000*sm + 1000*ss + 10*sc;
-    end   = 3600000*eh + 60000*em + 1000*es + 10*ec;
+    start = 3600000LL*sh + 60000LL*sm + 1000LL*ss + 10LL*sc;
+    end   = 3600000LL*eh + 60000LL*em + 1000LL*es + 10LL*ec;
     return end - start;
 }
 
@@ -1164,8 +1166,12 @@
     }
 
     if (!s->pb->seekable) {
-        if (!mkv->dyn_bc)
-            avio_open_dyn_buf(&mkv->dyn_bc);
+        if (!mkv->dyn_bc) {
+            if ((ret = avio_open_dyn_buf(&mkv->dyn_bc)) < 0) {
+                av_log(s, AV_LOG_ERROR, "Failed to open dynamic buffer\n");
+                return ret;
+            }
+        }
         pb = mkv->dyn_bc;
     }
 
diff --git a/libavformat/md5enc.c b/libavformat/md5enc.c
index f365308..050efb1 100644
--- a/libavformat/md5enc.c
+++ b/libavformat/md5enc.c
@@ -23,13 +23,16 @@
 #include "avformat.h"
 #include "internal.h"
 
-#define PRIVSIZE 512
+struct MD5Context {
+    struct AVMD5 *md5;
+};
 
 static void md5_finish(struct AVFormatContext *s, char *buf)
 {
+    struct MD5Context *c = s->priv_data;
     uint8_t md5[16];
     int i, offset = strlen(buf);
-    av_md5_final(s->priv_data, md5);
+    av_md5_final(c->md5, md5);
     for (i = 0; i < sizeof(md5); i++) {
         snprintf(buf + offset, 3, "%02"PRIx8, md5[i]);
         offset += 2;
@@ -44,32 +47,36 @@
 #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);
+    struct MD5Context *c = s->priv_data;
+    c->md5 = av_md5_alloc();
+    if (!c->md5)
+        return AVERROR(ENOMEM);
+    av_md5_init(c->md5);
     return 0;
 }
 
 static int write_packet(struct AVFormatContext *s, AVPacket *pkt)
 {
-    av_md5_update(s->priv_data, pkt->data, pkt->size);
+    struct MD5Context *c = s->priv_data;
+    av_md5_update(c->md5, pkt->data, pkt->size);
     return 0;
 }
 
 static int write_trailer(struct AVFormatContext *s)
 {
+    struct MD5Context *c = s->priv_data;
     char buf[64] = "MD5=";
 
     md5_finish(s, buf);
+
+    av_freep(&c->md5);
     return 0;
 }
 
 AVOutputFormat ff_md5_muxer = {
     .name              = "md5",
     .long_name         = NULL_IF_CONFIG_SMALL("MD5 testing"),
-    .priv_data_size    = PRIVSIZE,
+    .priv_data_size    = sizeof(struct MD5Context),
     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
     .video_codec       = AV_CODEC_ID_RAWVIDEO,
     .write_header      = write_header,
@@ -80,15 +87,21 @@
 #endif
 
 #if CONFIG_FRAMEMD5_MUXER
+static int framemd5_write_header(struct AVFormatContext *s)
+{
+    struct MD5Context *c = s->priv_data;
+    c->md5 = av_md5_alloc();
+    if (!c->md5)
+        return AVERROR(ENOMEM);
+    return ff_framehash_write_header(s);
+}
+
 static int framemd5_write_packet(struct AVFormatContext *s, AVPacket *pkt)
 {
+    struct MD5Context *c = s->priv_data;
     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);
+    av_md5_init(c->md5);
+    av_md5_update(c->md5, pkt->data, pkt->size);
 
     snprintf(buf, sizeof(buf) - 64, "%d, %10"PRId64", %10"PRId64", %8d, %8d, ",
              pkt->stream_index, pkt->dts, pkt->pts, pkt->duration, pkt->size);
@@ -96,14 +109,22 @@
     return 0;
 }
 
+static int framemd5_write_trailer(struct AVFormatContext *s)
+{
+    struct MD5Context *c = s->priv_data;
+    av_freep(&c->md5);
+    return 0;
+}
+
 AVOutputFormat ff_framemd5_muxer = {
     .name              = "framemd5",
     .long_name         = NULL_IF_CONFIG_SMALL("Per-frame MD5 testing"),
-    .priv_data_size    = PRIVSIZE,
+    .priv_data_size    = sizeof(struct MD5Context),
     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
     .video_codec       = AV_CODEC_ID_RAWVIDEO,
-    .write_header      = ff_framehash_write_header,
+    .write_header      = framemd5_write_header,
     .write_packet      = framemd5_write_packet,
+    .write_trailer     = framemd5_write_trailer,
     .flags             = AVFMT_VARIABLE_FPS | AVFMT_TS_NONSTRICT,
 };
 #endif
diff --git a/libavformat/md5proto.c b/libavformat/md5proto.c
index f7c8b78..6af0a6e 100644
--- a/libavformat/md5proto.c
+++ b/libavformat/md5proto.c
@@ -27,37 +27,41 @@
 #include "avio.h"
 #include "url.h"
 
-#define PRIV_SIZE 128
+struct MD5Context {
+    struct AVMD5 *md5;
+};
 
 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;
-    }
+    struct MD5Context *c = h->priv_data;
 
     if (!(flags & AVIO_FLAG_WRITE))
         return AVERROR(EINVAL);
 
-    av_md5_init(h->priv_data);
+    c->md5 = av_md5_alloc();
+    if (!c->md5)
+        return AVERROR(ENOMEM);
+    av_md5_init(c->md5);
 
     return 0;
 }
 
 static int md5_write(URLContext *h, const unsigned char *buf, int size)
 {
-    av_md5_update(h->priv_data, buf, size);
+    struct MD5Context *c = h->priv_data;
+    av_md5_update(c->md5, buf, size);
     return size;
 }
 
 static int md5_close(URLContext *h)
 {
+    struct MD5Context *c = h->priv_data;
     const char *filename = h->filename;
     uint8_t md5[16], buf[64];
     URLContext *out;
     int i, err = 0;
 
-    av_md5_final(h->priv_data, md5);
+    av_md5_final(c->md5, md5);
     for (i = 0; i < sizeof(md5); i++)
         snprintf(buf + i*2, 3, "%02x", md5[i]);
     buf[i*2] = '\n';
@@ -76,6 +80,8 @@
             err = AVERROR(errno);
     }
 
+    av_freep(&c->md5);
+
     return err;
 }
 
@@ -85,5 +91,5 @@
     .url_open            = md5_open,
     .url_write           = md5_write,
     .url_close           = md5_close,
-    .priv_data_size      = PRIV_SIZE,
+    .priv_data_size      = sizeof(struct MD5Context),
 };
diff --git a/libavformat/microdvddec.c b/libavformat/microdvddec.c
index ecc2819..68a5d87 100644
--- a/libavformat/microdvddec.c
+++ b/libavformat/microdvddec.c
@@ -126,6 +126,14 @@
     return ff_subtitles_queue_read_packet(&microdvd->q, pkt);
 }
 
+static int microdvd_read_seek(AVFormatContext *s, int stream_index,
+                             int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
+{
+    MicroDVDContext *microdvd = s->priv_data;
+    return ff_subtitles_queue_seek(&microdvd->q, s, stream_index,
+                                   min_ts, ts, max_ts, flags);
+}
+
 static int microdvd_read_close(AVFormatContext *s)
 {
     MicroDVDContext *microdvd = s->priv_data;
@@ -140,6 +148,7 @@
     .read_probe     = microdvd_probe,
     .read_header    = microdvd_read_header,
     .read_packet    = microdvd_read_packet,
+    .read_seek2     = microdvd_read_seek,
     .read_close     = microdvd_read_close,
     .flags          = AVFMT_GENERIC_INDEX,
 };
diff --git a/libavformat/mm.c b/libavformat/mm.c
index 125a677..12a11ac 100644
--- a/libavformat/mm.c
+++ b/libavformat/mm.c
@@ -31,6 +31,7 @@
  *  http://wiki.multimedia.cx/index.php?title=American_Laser_Games_MM
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "internal.h"
@@ -124,6 +125,7 @@
         st->codec->codec_tag = 0; /* no fourcc */
         st->codec->codec_id = AV_CODEC_ID_PCM_U8;
         st->codec->channels = 1;
+        st->codec->channel_layout = AV_CH_LAYOUT_MONO;
         st->codec->sample_rate = 8000;
         avpriv_set_pts_info(st, 64, 1, 8000); /* 8000 hz */
     }
diff --git a/libavformat/mmf.c b/libavformat/mmf.c
index 18b69d4..38c6970 100644
--- a/libavformat/mmf.c
+++ b/libavformat/mmf.c
@@ -18,6 +18,8 @@
  * 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/channel_layout.h"
 #include "avformat.h"
 #include "internal.h"
 #include "avio_internal.h"
@@ -249,6 +251,7 @@
     st->codec->codec_id = AV_CODEC_ID_ADPCM_YAMAHA;
     st->codec->sample_rate = rate;
     st->codec->channels = 1;
+    st->codec->channel_layout = AV_CH_LAYOUT_MONO;
     st->codec->bits_per_coded_sample = 4;
     st->codec->bit_rate = st->codec->sample_rate * st->codec->bits_per_coded_sample;
 
@@ -265,15 +268,10 @@
     MMFContext *mmf = s->priv_data;
     int ret, size;
 
-    if (url_feof(s->pb))
-        return AVERROR(EIO);
+    if (url_feof(s->pb) || !mmf->data_size)
+        return AVERROR_EOF;
 
-    size = MAX_SIZE;
-    if(size > mmf->data_size)
-        size = mmf->data_size;
-
-    if(!size)
-        return AVERROR(EIO);
+    size = FFMIN(MAX_SIZE, mmf->data_size);
 
     ret = av_get_packet(s->pb, pkt, size);
     if (ret < 0)
diff --git a/libavformat/mms.h b/libavformat/mms.h
index cbfa79a..57e3d7e 100644
--- a/libavformat/mms.h
+++ b/libavformat/mms.h
@@ -23,11 +23,11 @@
 
 #include "url.h"
 
-typedef struct {
+typedef struct MMSStream {
     int id;
 }MMSStream;
 
-typedef struct {
+typedef struct MMSContext {
     URLContext *mms_hd;                  ///< TCP connection handle
     MMSStream *streams;
 
diff --git a/libavformat/mmsh.c b/libavformat/mmsh.c
index d6e3982..86a0575 100644
--- a/libavformat/mmsh.c
+++ b/libavformat/mmsh.c
@@ -394,7 +394,7 @@
     MMSContext *mms   = &mmsh->mms;
 
     if(pos == 0 && whence == SEEK_CUR)
-        return mms->asf_header_read_size + mms->remaining_in_len + mmsh->chunk_seq * mms->asf_packet_len;
+        return mms->asf_header_read_size + mms->remaining_in_len + mmsh->chunk_seq * (int64_t)mms->asf_packet_len;
     return AVERROR(ENOSYS);
 }
 
diff --git a/libavformat/mov.c b/libavformat/mov.c
index 3bf6dcc..f380b39 100644
--- a/libavformat/mov.c
+++ b/libavformat/mov.c
@@ -26,7 +26,7 @@
 //#define MOV_EXPORT_ALL_METADATA
 
 #include "libavutil/attributes.h"
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "libavutil/intfloat.h"
 #include "libavutil/mathematics.h"
@@ -312,6 +312,9 @@
     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(0xa9,'m','a','k'): key = "make";      break;
+    case MKTAG(0xa9,'m','o','d'): key = "model";     break;
+    case MKTAG(0xa9,'x','y','z'): key = "location";  break;
     case MKTAG( 'd','e','s','c'): key = "description";break;
     case MKTAG( 'l','d','e','s'): key = "synopsis";  break;
     case MKTAG( 't','v','s','h'): key = "show";      break;
@@ -689,7 +692,9 @@
         return 0;
     st = c->fc->streams[c->fc->nb_streams-1];
 
-    ff_get_wav_header(pb, st->codec, atom.size);
+    if (ff_get_wav_header(pb, st->codec, atom.size) < 0) {
+        av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
+    }
 
     return 0;
 }
@@ -778,14 +783,16 @@
     return mov_read_default(c, pb, atom);
 }
 
-static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
+static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
 {
     char buffer[32];
     if (time) {
         struct tm *ptm;
+        time_t timet;
         if(time >= 2082844800)
             time -= 2082844800;  /* seconds between 1904-01-01 and Epoch */
-        ptm = gmtime(&time);
+        timet = time;
+        ptm = gmtime(&timet);
         if (!ptm) return;
         strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
         av_dict_set(metadata, "creation_time", buffer, 0);
@@ -799,7 +806,7 @@
     int version;
     char language[4] = {0};
     unsigned lang;
-    time_t creation_time;
+    int64_t creation_time;
 
     if (c->fc->nb_streams < 1)
         return 0;
@@ -834,7 +841,7 @@
 
 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
-    time_t creation_time;
+    int64_t creation_time;
     int version = avio_r8(pb); /* version */
     avio_rb24(pb); /* flags */
 
@@ -1163,33 +1170,12 @@
  */
 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
 {
-    if (flags & 1) { // floating point
-        if (flags & 2) { // big endian
-            if      (bps == 32) return AV_CODEC_ID_PCM_F32BE;
-            else if (bps == 64) return AV_CODEC_ID_PCM_F64BE;
-        } else {
-            if      (bps == 32) return AV_CODEC_ID_PCM_F32LE;
-            else if (bps == 64) return AV_CODEC_ID_PCM_F64LE;
-        }
-    } else {
-        if (flags & 2) {
-            if      (bps == 8)
-                // signed integer
-                if (flags & 4)  return AV_CODEC_ID_PCM_S8;
-                else            return AV_CODEC_ID_PCM_U8;
-            else if (bps == 16) return AV_CODEC_ID_PCM_S16BE;
-            else if (bps == 24) return AV_CODEC_ID_PCM_S24BE;
-            else if (bps == 32) return AV_CODEC_ID_PCM_S32BE;
-        } else {
-            if      (bps == 8)
-                if (flags & 4)  return AV_CODEC_ID_PCM_S8;
-                else            return AV_CODEC_ID_PCM_U8;
-            else if (bps == 16) return AV_CODEC_ID_PCM_S16LE;
-            else if (bps == 24) return AV_CODEC_ID_PCM_S24LE;
-            else if (bps == 32) return AV_CODEC_ID_PCM_S32LE;
-        }
-    }
-    return AV_CODEC_ID_NONE;
+    /* lpcm flags:
+     * 0x1 = float
+     * 0x2 = big-endian
+     * 0x4 = signed
+     */
+    return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
 }
 
 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
@@ -1273,7 +1259,6 @@
             int color_greyscale;
             int color_table_id;
 
-            st->codec->codec_id = id;
             avio_rb16(pb); /* version */
             avio_rb16(pb); /* revision level */
             avio_rb32(pb); /* vendor */
@@ -1297,6 +1282,11 @@
             /* 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');
+            /* Flash Media Server streams files with Sorenson Spark and tag H263 */
+            if (!memcmp(st->codec->codec_name, "Sorenson H263", 13)
+                && format == MKTAG('H','2','6','3'))
+                id = AV_CODEC_ID_FLV1;
+            st->codec->codec_id = id;
 
             st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
             color_table_id = avio_rb16(pb); /* colortable id */
@@ -1377,6 +1367,7 @@
         } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
             int bits_per_sample, flags;
             uint16_t version = avio_rb16(pb);
+            AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
 
             st->codec->codec_id = id;
             avio_rb16(pb); /* revision level */
@@ -1393,7 +1384,8 @@
 
             //Read QT version 1 fields. In version 0 these do not exist.
             av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
-            if (!c->isom) {
+            if (!c->isom ||
+                (compatible_brands && strstr(compatible_brands->value, "qt  "))) {
                 if (version==1) {
                     sc->samples_per_frame = avio_rb32(pb);
                     avio_rb32(pb); /* bytes per packet */
@@ -1957,7 +1949,7 @@
         unsigned int rap_group_index = 0;
         unsigned int rap_group_sample = 0;
         int rap_group_present = sc->rap_group_count && sc->rap_group;
-        int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
+        int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
 
         current_dts -= sc->dts_shift;
 
@@ -2166,6 +2158,16 @@
     return AVERROR(ENOENT);
 }
 
+static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
+{
+    if (sc->time_scale <= 0) {
+        av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
+        sc->time_scale = c->time_scale;
+        if (sc->time_scale <= 0)
+            sc->time_scale = 1;
+    }
+}
+
 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
@@ -2193,12 +2195,7 @@
         return 0;
     }
 
-    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 <= 0)
-            sc->time_scale = 1;
-    }
+    fix_timescale(c, sc);
 
     avpriv_set_pts_info(st, 64, 1, sc->time_scale);
 
@@ -2223,8 +2220,9 @@
                                              ((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 (st->duration > 0)
+            av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
+                    sc->time_scale*st->nb_frames, st->duration, INT_MAX);
 
 #if FF_API_R_FRAME_RATE
         if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
@@ -2626,7 +2624,7 @@
     int i, edit_count, version, edit_start_index = 0;
     int unsupported = 0;
 
-    if (c->fc->nb_streams < 1)
+    if (c->fc->nb_streams < 1 || c->ignore_editlist)
         return 0;
     sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
 
@@ -2854,46 +2852,81 @@
 
 static int mov_probe(AVProbeData *p)
 {
-    unsigned int offset;
+    int64_t offset;
     uint32_t tag;
     int score = 0;
+    int moov_offset = -1;
 
     /* check file header */
     offset = 0;
     for (;;) {
         /* ignore invalid offset */
         if ((offset + 8) > (unsigned int)p->buf_size)
-            return score;
+            break;
         tag = AV_RL32(p->buf + offset + 4);
         switch(tag) {
         /* check for obvious tags */
-        case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
         case MKTAG('m','o','o','v'):
+            moov_offset = offset + 4;
+        case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
         case MKTAG('m','d','a','t'):
         case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
         case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
         case MKTAG('f','t','y','p'):
-            return AVPROBE_SCORE_MAX;
+            if (AV_RB32(p->buf+offset) < 8 &&
+                (AV_RB32(p->buf+offset) != 1 ||
+                 offset + 12 > (unsigned int)p->buf_size ||
+                 AV_RB64(p->buf+offset + 8) == 0)) {
+                score = FFMAX(score, AVPROBE_SCORE_MAX - 50);
+            } else {
+                score = AVPROBE_SCORE_MAX;
+            }
+            offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
+            break;
         /* those are more common words, so rate then a bit less */
         case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
         case MKTAG('w','i','d','e'):
         case MKTAG('f','r','e','e'):
         case MKTAG('j','u','n','k'):
         case MKTAG('p','i','c','t'):
-            return AVPROBE_SCORE_MAX - 5;
+            score  = FFMAX(score, AVPROBE_SCORE_MAX - 5);
+            offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
+            break;
         case MKTAG(0x82,0x82,0x7f,0x7d):
         case MKTAG('s','k','i','p'):
         case MKTAG('u','u','i','d'):
         case MKTAG('p','r','f','l'):
-            offset = AV_RB32(p->buf+offset) + offset;
             /* if we only find those cause probedata is too small at least rate them */
-            score = AVPROBE_SCORE_MAX - 50;
+            score  = FFMAX(score, AVPROBE_SCORE_MAX - 50);
+            offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
             break;
         default:
-            /* unrecognized tag */
-            return score;
+            offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
         }
     }
+    if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
+        /* moov atom in the header - we should make sure that this is not a
+         * MOV-packed MPEG-PS */
+        offset = moov_offset;
+
+        while(offset < (p->buf_size - 16)){ /* Sufficient space */
+               /* We found an actual hdlr atom */
+            if(AV_RL32(p->buf + offset     ) == MKTAG('h','d','l','r') &&
+               AV_RL32(p->buf + offset +  8) == MKTAG('m','h','l','r') &&
+               AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
+                av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
+                /* We found a media handler reference atom describing an
+                 * MPEG-PS-in-MOV, return a
+                 * low score to force expanding the probe window until
+                 * mpegps_probe finds what it needs */
+                return 5;
+            }else
+                /* Keep looking */
+                offset+=2;
+        }
+    }
+
+    return score;
 }
 
 // must be done after parsing all trak because there's no order requirement
@@ -3141,6 +3174,7 @@
     for (i = 0; i < s->nb_streams; i++) {
         AVStream *st = s->streams[i];
         MOVStreamContext *sc = st->priv_data;
+        fix_timescale(mov, sc);
         if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
             st->skip_samples = sc->start_pad;
         }
@@ -3335,7 +3369,9 @@
 static const AVOption options[] = {
     {"use_absolute_path",
         "allow using absolute path when opening alias, this is a possible security issue",
-        offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.dbl = 0},
+        offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.i64 = 0},
+        0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
+    {"ignore_editlist", "", offsetof(MOVContext, ignore_editlist), FF_OPT_TYPE_INT, {.i64 = 0},
         0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
     {NULL}
 };
@@ -3357,4 +3393,5 @@
     .read_close     = mov_read_close,
     .read_seek      = mov_read_seek,
     .priv_class     = &class,
+    .flags          = AVFMT_NO_BYTE_SEEK,
 };
diff --git a/libavformat/mov_chan.c b/libavformat/mov_chan.c
index 58aec57..cf1f839 100644
--- a/libavformat/mov_chan.c
+++ b/libavformat/mov_chan.c
@@ -25,7 +25,7 @@
 
 #include <stdint.h>
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "libavcodec/avcodec.h"
 #include "mov_chan.h"
 
diff --git a/libavformat/movenc.c b/libavformat/movenc.c
index 6de5306..f08aa7e 100644
--- a/libavformat/movenc.c
+++ b/libavformat/movenc.c
@@ -61,6 +61,7 @@
     { "min_frag_duration", "Minimum fragment duration", offsetof(MOVMuxContext, min_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
     { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
     { "ism_lookahead", "Number of lookahead entries for ISM files", offsetof(MOVMuxContext, ism_lookahead), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
+    { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
     { NULL },
 };
 
@@ -83,6 +84,12 @@
     return curpos - pos;
 }
 
+static int supports_edts(MOVMuxContext *mov)
+{
+    // EDTS with fragments is tricky as we dont know the duration when its written
+    return (mov->use_editlist<0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) || mov->use_editlist>0;
+}
+
 static int is_co64_required(const MOVTrack *track)
 {
     int i;
@@ -288,6 +295,14 @@
     return 10;
 }
 
+static int mov_write_enda_tag_be(AVIOContext *pb)
+{
+  avio_wb32(pb, 10);
+  ffio_wfourcc(pb, "enda");
+  avio_wb16(pb, 0); /* big endian */
+  return 10;
+}
+
 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
 {
     int i = 3;
@@ -369,6 +384,14 @@
            codec_id == AV_CODEC_ID_PCM_F64LE;
 }
 
+static int mov_pcm_be_gt16(enum AVCodecID codec_id)
+{
+    return codec_id == AV_CODEC_ID_PCM_S24BE ||
+           codec_id == AV_CODEC_ID_PCM_S32BE ||
+           codec_id == AV_CODEC_ID_PCM_F32BE ||
+           codec_id == AV_CODEC_ID_PCM_F64BE;
+}
+
 static int mov_write_ms_tag(AVIOContext *pb, MOVTrack *track)
 {
     int64_t pos = avio_tell(pb);
@@ -432,8 +455,10 @@
         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);
+    } else if (mov_pcm_le_gt16(track->enc->codec_id))  {
+      mov_write_enda_tag(pb);
+    } else if (mov_pcm_be_gt16(track->enc->codec_id))  {
+      mov_write_enda_tag_be(pb);
     } else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB) {
         mov_write_amr_tag(pb, track);
     } else if (track->enc->codec_id == AV_CODEC_ID_AC3) {
@@ -629,6 +654,7 @@
                 tag = AV_RL32("lpcm");
             version = 2;
         } else if (track->audio_vbr || mov_pcm_le_gt16(track->enc->codec_id) ||
+                   mov_pcm_be_gt16(track->enc->codec_id) ||
                    track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
                    track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
                    track->enc->codec_id == AV_CODEC_ID_QDM2) {
@@ -683,7 +709,11 @@
     }
 
     if(version == 1) { /* SoundDescription V1 extended info */
-        avio_wb32(pb, track->enc->frame_size); /* Samples per packet */
+        if (mov_pcm_le_gt16(track->enc->codec_id) ||
+            mov_pcm_be_gt16(track->enc->codec_id))
+            avio_wb32(pb, 1); /*  must be 1 for  uncompressed formats */
+        else
+            avio_wb32(pb, track->enc->frame_size); /* Samples per packet */
         avio_wb32(pb, track->sample_size / track->enc->channels); /* Bytes per packet */
         avio_wb32(pb, track->sample_size); /* Bytes per frame */
         avio_wb32(pb, 2); /* Bytes per sample */
@@ -697,7 +727,8 @@
         track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
         track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
         track->enc->codec_id == AV_CODEC_ID_QDM2 ||
-        (mov_pcm_le_gt16(track->enc->codec_id) && version==1)))
+        (mov_pcm_le_gt16(track->enc->codec_id) && version==1) ||
+        (mov_pcm_be_gt16(track->enc->codec_id) && version==1)))
         mov_write_wave_tag(pb, track);
     else if(track->tag == MKTAG('m','p','4','a'))
         mov_write_esds_tag(pb, track);
@@ -838,20 +869,20 @@
 {
     int tag;
 
-    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');
+    if (track->enc->width == 720) { /* SD */
+        if (track->enc->height == 480) { /* NTSC */
+            if  (track->enc->pix_fmt == AV_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 if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
+        else if (track->enc->pix_fmt == AV_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 */
+    } 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 */
+    } 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 {
+    } else {
         av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
         return 0;
     }
@@ -860,25 +891,25 @@
 }
 
 static const struct {
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
     uint32_t tag;
     unsigned bps;
 } mov_pix_fmt_tags[] = {
-    { PIX_FMT_YUYV422, MKTAG('y','u','v','2'),  0 },
-    { PIX_FMT_YUYV422, MKTAG('y','u','v','s'),  0 },
-    { PIX_FMT_UYVY422, MKTAG('2','v','u','y'),  0 },
-    { 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 },
+    { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'),  0 },
+    { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'),  0 },
+    { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'),  0 },
+    { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
+    { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
+    { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
+    { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
+    { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
+    { AV_PIX_FMT_RGB24,   MKTAG('r','a','w',' '), 24 },
+    { AV_PIX_FMT_BGR24,   MKTAG('2','4','B','G'), 24 },
+    { AV_PIX_FMT_ARGB,    MKTAG('r','a','w',' '), 32 },
+    { AV_PIX_FMT_BGRA,    MKTAG('B','G','R','A'), 32 },
+    { AV_PIX_FMT_RGBA,    MKTAG('R','G','B','A'), 32 },
+    { AV_PIX_FMT_ABGR,    MKTAG('A','B','G','R'), 32 },
+    { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
 };
 
 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
@@ -887,10 +918,11 @@
     int i;
 
     for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
-        if (track->enc->codec_tag == mov_pix_fmt_tags[i].tag && track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
+        if (track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
             tag = mov_pix_fmt_tags[i].tag;
             track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
-            break;
+            if (track->enc->codec_tag == mov_pix_fmt_tags[i].tag)
+                break;
         }
     }
 
@@ -1114,7 +1146,7 @@
 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
 {
     int64_t pos = avio_tell(pb);
-    int frame_duration = track->enc->time_base.num;
+    int frame_duration = av_rescale(track->timescale, track->enc->time_base.num, track->enc->time_base.den);
     int nb_frames = (track->timescale + frame_duration/2) / frame_duration;
 
     avio_wb32(pb, 0); /* size */
@@ -1343,6 +1375,7 @@
      * don't appear to be documented, so the
      * bytes are copied verbatim.
      */
+    if (track->tag != MKTAG('c','6','0','8')) {
     avio_wb32(pb, 0x2C);   /* size */
     ffio_wfourcc(pb, "text");
     avio_wb16(pb, 0x01);
@@ -1355,6 +1388,7 @@
     avio_wb32(pb, 0x00);
     avio_wb32(pb, 0x00004000);
     avio_wb16(pb, 0x0000);
+    }
 
     if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
         int64_t tmcd_pos = avio_tell(pb);
@@ -1403,9 +1437,14 @@
             hdlr_type = "soun";
             descr = "SoundHandler";
         } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
+            if (track->tag == MKTAG('c','6','0','8')) {
+                hdlr_type = "clcp";
+                descr = "ClosedCaptionHandler";
+            } else {
             if (track->tag == MKTAG('t','x','3','g')) hdlr_type = "sbtl";
             else                                      hdlr_type = "text";
             descr = "SubtitleHandler";
+            }
         } else if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
             hdlr_type = "tmcd";
             descr = "TimeCodeHandler";
@@ -1460,8 +1499,11 @@
     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
         mov_write_smhd_tag(pb);
     else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
-        if (track->tag == MKTAG('t','e','x','t')) mov_write_gmhd_tag(pb, track);
-        else                                      mov_write_nmhd_tag(pb);
+        if (track->tag == MKTAG('t','e','x','t') || track->tag == MKTAG('c','6','0','8')) {
+            mov_write_gmhd_tag(pb, track);
+        } else {
+            mov_write_nmhd_tag(pb);
+        }
     } else if (track->tag == MKTAG('t','m','c','d')) {
         mov_write_gmhd_tag(pb, track);
     } else if (track->tag == MKTAG('r','t','p',' ')) {
@@ -1630,6 +1672,12 @@
     avio_wb32(pb, track->enc->height << 16);
 
     avio_wb32(pb, 20);
+    ffio_wfourcc(pb, "prof");
+    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);
@@ -1673,8 +1721,8 @@
         }
         avio_wb32(pb, 0x00010000);
     } else {
-        av_assert0(track->cluster[0].dts <= 0);
-        start_ct  = -track->cluster[0].dts;
+        av_assert0(av_rescale_rnd(track->cluster[0].dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
+        start_ct  = -FFMIN(track->cluster[0].dts, 0); //FFMIN needed due to rounding
         duration += delay;
     }
 
@@ -1719,13 +1767,16 @@
     return 0x34;
 }
 
-static int mov_write_udta_sdp(AVIOContext *pb, AVFormatContext *ctx, int index)
+static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
 {
+
+    AVFormatContext *ctx = track->rtp_ctx;
     char buf[1000] = "";
     int len;
 
-    ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0]->codec, NULL, NULL, 0, 0, ctx);
-    av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", index);
+    ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
+                       NULL, NULL, 0, 0, ctx);
+    av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
     len = strlen(buf);
 
     avio_wb32(pb, len + 24);
@@ -1745,7 +1796,7 @@
     avio_wb32(pb, 0); /* size */
     ffio_wfourcc(pb, "trak");
     mov_write_tkhd_tag(pb, track, st);
-    if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) // EDTS with fragments is tricky as we dont know the duration when its written
+    if (supports_edts(mov))
         mov_write_edts_tag(pb, track);  // PSP Movies and several other cases require edts box
     if (track->tref_tag)
         mov_write_tref_tag(pb, track);
@@ -1753,7 +1804,7 @@
     if (track->mode == MODE_PSP)
         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, track->track_id);
+        mov_write_udta_sdp(pb, track);
     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO && track->mode == MODE_MOV) {
         double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
         if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio)
@@ -1980,6 +2031,24 @@
     return size;
 }
 
+static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
+                                   const char *name, const char *tag,
+                                   int len)
+{
+    AVDictionaryEntry *t = NULL;
+    uint8_t num;
+
+    if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
+        return 0;
+    num = atoi(t->value);
+
+    avio_wb32(pb, len+8);
+    ffio_wfourcc(pb, name);
+    if (len==4) avio_wb32(pb, num);
+    else        avio_w8 (pb, num);
+    return len+8;
+}
+
 /* iTunes meta data list */
 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
                               AVFormatContext *s)
@@ -2004,6 +2073,11 @@
     mov_write_string_metadata(s, pb, "tvsh",    "show"     , 1);
     mov_write_string_metadata(s, pb, "tven",    "episode_id",1);
     mov_write_string_metadata(s, pb, "tvnn",    "network"  , 1);
+    mov_write_int8_metadata  (s, pb, "tves",    "episode_sort",4);
+    mov_write_int8_metadata  (s, pb, "tvsn",    "season_number",4);
+    mov_write_int8_metadata  (s, pb, "stik",    "media_type",1);
+    mov_write_int8_metadata  (s, pb, "hdvd",    "hd_video",  1);
+    mov_write_int8_metadata  (s, pb, "pgap",    "gapless_playback",1);
     mov_write_trkn_tag(pb, mov, s);
     mov_write_tmpo_tag(pb, s);
     return update_size(pb, pos);
@@ -3130,6 +3204,9 @@
          * of this packet to be what the previous packets duration implies. */
         trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
     }
+    if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !supports_edts(mov)) {
+        trk->cluster[trk->entry].dts = trk->start_dts = 0;
+    }
     if (trk->start_dts == AV_NOPTS_VALUE)
         trk->start_dts = pkt->dts;
     trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
@@ -3372,7 +3449,7 @@
     track->mode      = mov->mode;
     track->tag       = MKTAG('t','m','c','d');
     track->src_track = src_index;
-    track->timescale = src_st->codec->time_base.den;
+    track->timescale = mov->tracks[src_index].timescale;
     if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
         track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
 
@@ -3413,6 +3490,10 @@
             mov->reserved_moov_size = -1;
     }
 
+    if (!supports_edts(mov) && s->avoid_negative_ts < 0) {
+        s->avoid_negative_ts = 1;
+    }
+
     /* Non-seekable output is ok if using fragmentation. If ism_lookahead
      * is enabled, we don't support non-seekable output at all. */
     if (!s->pb->seekable &&
@@ -3522,6 +3603,8 @@
                 track->height = track->tag>>24 == 'n' ? 486 : 576;
             }
             track->timescale = st->codec->time_base.den;
+            while(track->timescale < 10000)
+                track->timescale *= 2;
             if (track->mode == MODE_MOV && track->timescale > 100000)
                 av_log(s, AV_LOG_WARNING,
                        "WARNING codec timebase is very high. If duration is too long,\n"
diff --git a/libavformat/movenc.h b/libavformat/movenc.h
index da6f19b..b5d066f 100644
--- a/libavformat/movenc.h
+++ b/libavformat/movenc.h
@@ -62,13 +62,13 @@
     int own_data;
 } HintSample;
 
-typedef struct {
+typedef struct HintSampleQueue {
     int size;
     int len;
     HintSample *samples;
 } HintSampleQueue;
 
-typedef struct {
+typedef struct MOVFragmentInfo {
     int64_t offset;
     int64_t time;
     int64_t duration;
@@ -165,6 +165,8 @@
     int max_fragment_size;
     int ism_lookahead;
     AVIOContext *mdat_buf;
+
+    int use_editlist;
 } MOVMuxContext;
 
 #define FF_MOV_FLAG_RTP_HINT 1
diff --git a/libavformat/movenchint.c b/libavformat/movenchint.c
index 9c4ddeb..cc90f0b 100644
--- a/libavformat/movenchint.c
+++ b/libavformat/movenchint.c
@@ -44,7 +44,7 @@
     track->enc->codec_tag  = track->tag;
 
     ret = ff_rtp_chain_mux_open(&track->rtp_ctx, s, src_st, NULL,
-                                RTP_MAX_PACKET_SIZE);
+                                RTP_MAX_PACKET_SIZE, src_index);
     if (ret < 0)
         goto fail;
 
diff --git a/libavformat/mp3dec.c b/libavformat/mp3dec.c
index d3f7cbd..d11dceb 100644
--- a/libavformat/mp3dec.c
+++ b/libavformat/mp3dec.c
@@ -275,7 +275,6 @@
     AVIndexEntry *ie;
     AVStream *st = s->streams[0];
     int64_t ret  = av_index_search_timestamp(st, timestamp, flags);
-    uint32_t header = 0;
     int i, j;
 
     if (!mp3->xing_toc) {
diff --git a/libavformat/mp3enc.c b/libavformat/mp3enc.c
index 3c7c4aa..cc9f0d0 100644
--- a/libavformat/mp3enc.c
+++ b/libavformat/mp3enc.c
@@ -157,7 +157,7 @@
     }
 
     /* dummy MPEG audio header */
-    header  =  0xff                                  << 24; // sync
+    header  =  0xffU                                 << 24; // sync
     header |= (0x7 << 5 | ver << 3 | 0x1 << 1 | 0x1) << 16; // sync/audio-version/layer 3/no crc*/
     header |= (srate_idx << 2) <<  8;
     header |= channels << 6;
@@ -259,11 +259,17 @@
 {
     MP3Context  *mp3 = s->priv_data;
 
-    if (pkt && pkt->data && pkt->size >= 4) {
+    if (pkt->data && pkt->size >= 4) {
         MPADecodeHeader c;
         int av_unused base;
+        uint32_t head = AV_RB32(pkt->data);
 
-        avpriv_mpegaudio_decode_header(&c, AV_RB32(pkt->data));
+        if (ff_mpa_check_header(head) < 0) {
+            av_log(s, AV_LOG_WARNING, "Audio packet of size %d (starting with %08X...) "
+                   "is invalid, writing it anyway.\n", pkt->size, head);
+            return ff_raw_write_packet(s, pkt);
+        }
+        avpriv_mpegaudio_decode_header(&c, head);
 
         if (!mp3->initial_bitrate)
             mp3->initial_bitrate = c.bit_rate;
diff --git a/libavformat/mpc.c b/libavformat/mpc.c
index 3b818ed..b0f6f53 100644
--- a/libavformat/mpc.c
+++ b/libavformat/mpc.c
@@ -19,6 +19,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavcodec/get_bits.h"
 #include "avformat.h"
 #include "internal.h"
@@ -91,6 +92,7 @@
     st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
     st->codec->codec_id = AV_CODEC_ID_MUSEPACK7;
     st->codec->channels = 2;
+    st->codec->channel_layout = AV_CH_LAYOUT_STEREO;
     st->codec->bits_per_coded_sample = 16;
 
     st->codec->extradata_size = 16;
diff --git a/libavformat/mpc8.c b/libavformat/mpc8.c
index 56ed7ad..191f696 100644
--- a/libavformat/mpc8.c
+++ b/libavformat/mpc8.c
@@ -145,6 +145,10 @@
         av_log(s, AV_LOG_ERROR, "No seek table at given position\n");
         return;
     }
+    if (size > INT_MAX/10 || size<=0) {
+        av_log(s, AV_LOG_ERROR, "Seek table size is invalid\n");
+        return;
+    }
     if(!(buf = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE)))
         return;
     avio_read(s->pb, buf, size);
diff --git a/libavformat/mpegts.c b/libavformat/mpegts.c
index 6316d61..aa7bde5 100644
--- a/libavformat/mpegts.c
+++ b/libavformat/mpegts.c
@@ -123,9 +123,11 @@
     unsigned int nb_prg;
     struct Program *prg;
 
+    int8_t crc_validity[NB_PID_MAX];
 
     /** filters for various streams specified by PMT + for the PAT and PMT */
     MpegTSFilter *pids[NB_PID_MAX];
+    int current_pid;
 };
 
 static const AVOption options[] = {
@@ -277,6 +279,7 @@
 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
                                const uint8_t *buf, int buf_size, int is_start)
 {
+    MpegTSContext *ts = s->priv_data;
     MpegTSSectionFilter *tss = &tss1->u.section_filter;
     int len;
 
@@ -304,10 +307,19 @@
     }
 
     if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
+        int crc_valid = 1;
         tss->end_of_section_reached = 1;
-        if (!tss->check_crc ||
-            av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
-                   tss->section_buf, tss->section_h_size) == 0)
+
+        if (tss->check_crc){
+            crc_valid = !av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, tss->section_buf, tss->section_h_size);
+            if (crc_valid){
+                ts->crc_validity[ tss1->pid ] = 100;
+            }else if(ts->crc_validity[ tss1->pid ] > -10){
+                ts->crc_validity[ tss1->pid ]--;
+            }else
+                crc_valid = 2;
+        }
+        if (crc_valid)
             tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
     }
 }
@@ -586,6 +598,11 @@
 static void mpegts_find_stream_type(AVStream *st,
                                     uint32_t stream_type, const StreamType *types)
 {
+    if (avcodec_is_open(st->codec)) {
+        av_log(NULL, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
+        return;
+    }
+
     for (; types->stream_type; types++) {
         if (stream_type == types->stream_type) {
             st->codec->codec_type = types->codec_type;
@@ -601,6 +618,12 @@
 {
     int old_codec_type= st->codec->codec_type;
     int old_codec_id  = st->codec->codec_id;
+
+    if (avcodec_is_open(st->codec)) {
+        av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
+        return 0;
+    }
+
     avpriv_set_pts_info(st, 33, 1, 90000);
     st->priv_data = pes;
     st->codec->codec_type = AVMEDIA_TYPE_DATA;
@@ -1414,7 +1437,7 @@
     int i;
 
     av_dlog(ts->stream, "PMT: len %i\n", section_len);
-    hex_dump_debug(ts->stream, (uint8_t *)section, section_len);
+    hex_dump_debug(ts->stream, section, section_len);
 
     p_end = section + section_len - 4;
     p = section;
@@ -1482,6 +1505,8 @@
         if (pid < 0)
             break;
         pid &= 0x1fff;
+        if (pid == ts->current_pid)
+            break;
 
         /* now create stream */
         if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
@@ -1553,7 +1578,7 @@
     AVProgram *program;
 
     av_dlog(ts->stream, "PAT:\n");
-    hex_dump_debug(ts->stream, (uint8_t *)section, section_len);
+    hex_dump_debug(ts->stream, section, section_len);
 
     p_end = section + section_len - 4;
     p = section;
@@ -1574,6 +1599,9 @@
             break;
         pmt_pid &= 0x1fff;
 
+        if (pmt_pid == ts->current_pid)
+            break;
+
         av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
 
         if (sid == 0x0000) {
@@ -1601,7 +1629,7 @@
     char *name, *provider_name;
 
     av_dlog(ts->stream, "SDT:\n");
-    hex_dump_debug(ts->stream, (uint8_t *)section, section_len);
+    hex_dump_debug(ts->stream, section, section_len);
 
     p_end = section + section_len - 4;
     p = section;
@@ -1690,6 +1718,7 @@
     }
     if (!tss)
         return 0;
+    ts->current_pid = pid;
 
     afc = (packet[3] >> 4) & 3;
     if (afc == 0) /* reserved value */
@@ -1869,24 +1898,34 @@
 static int mpegts_probe(AVProbeData *p)
 {
     const int size= p->buf_size;
-    int score, fec_score, dvhs_score;
+    int maxscore=0;
+    int sumscore=0;
+    int i;
     int check_count= size / TS_FEC_PACKET_SIZE;
 #define CHECK_COUNT 10
+#define CHECK_BLOCK 100
 
     if (check_count < CHECK_COUNT)
         return -1;
 
-    score     = analyze(p->buf, TS_PACKET_SIZE     *check_count, TS_PACKET_SIZE     , NULL)*CHECK_COUNT/check_count;
-    dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
-    fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
-    av_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n",
-            score, dvhs_score, fec_score);
+    for (i=0; i<check_count; i+=CHECK_BLOCK){
+        int left = FFMIN(check_count - i, CHECK_BLOCK);
+        int score     = analyze(p->buf + TS_PACKET_SIZE     *i, TS_PACKET_SIZE     *left, TS_PACKET_SIZE     , NULL);
+        int dvhs_score= analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL);
+        int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL);
+        score = FFMAX3(score, dvhs_score, fec_score);
+        sumscore += score;
+        maxscore = FFMAX(maxscore, score);
+    }
 
-// we need a clear definition for the returned score otherwise things will become messy sooner or later
-    if     (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score     - CHECK_COUNT;
-    else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score  - CHECK_COUNT;
-    else if(                 fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
-    else                                    return -1;
+    sumscore = sumscore*CHECK_COUNT/check_count;
+    maxscore = maxscore*CHECK_COUNT/CHECK_BLOCK;
+
+    av_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
+
+    if (sumscore > 6)           return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
+    else if (maxscore > 6)      return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
+    else                        return -1;
 }
 
 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
diff --git a/libavformat/mpegts.h b/libavformat/mpegts.h
index eae9d46..98c4b93 100644
--- a/libavformat/mpegts.h
+++ b/libavformat/mpegts.h
@@ -65,7 +65,7 @@
                            const uint8_t *buf, int len);
 void ff_mpegts_parse_close(MpegTSContext *ts);
 
-typedef struct {
+typedef struct SLConfigDescr {
     int use_au_start;
     int use_au_end;
     int use_rand_acc_pt;
@@ -82,7 +82,7 @@
     int packet_seq_num_len;
 } SLConfigDescr;
 
-typedef struct {
+typedef struct Mp4Descr {
     int es_id;
     int dec_config_descr_len;
     uint8_t *dec_config_descr;
diff --git a/libavformat/mpegtsenc.c b/libavformat/mpegtsenc.c
index 0b7a678..1b66bab 100644
--- a/libavformat/mpegtsenc.c
+++ b/libavformat/mpegtsenc.c
@@ -669,10 +669,10 @@
     ts->sdt_packet_count = ts->sdt_packet_period-1;
 
     if (ts->mux_rate == 1)
-        av_log(s, AV_LOG_INFO, "muxrate VBR, ");
+        av_log(s, AV_LOG_VERBOSE, "muxrate VBR, ");
     else
-        av_log(s, AV_LOG_INFO, "muxrate %d, ", ts->mux_rate);
-    av_log(s, AV_LOG_INFO, "pcr every %d pkts, "
+        av_log(s, AV_LOG_VERBOSE, "muxrate %d, ", ts->mux_rate);
+    av_log(s, AV_LOG_VERBOSE, "pcr every %d pkts, "
            "sdt every %d, pat/pmt every %d pkts\n",
            service->pcr_packet_period,
            ts->sdt_packet_period, ts->pat_packet_period);
diff --git a/libavformat/mpegvideodec.c b/libavformat/mpegvideodec.c
index f9c4062..471d2f4 100644
--- a/libavformat/mpegvideodec.c
+++ b/libavformat/mpegvideodec.c
@@ -34,8 +34,9 @@
 static int mpegvideo_probe(AVProbeData *p)
 {
     uint32_t code= -1;
-    int pic=0, seq=0, slice=0, pspack=0, vpes=0, apes=0, res=0;
+    int pic=0, seq=0, slice=0, pspack=0, vpes=0, apes=0, res=0, sicle=0;
     int i;
+    uint32_t last = 0;
 
     for(i=0; i<p->buf_size; i++){
         code = (code<<8) + p->buf[i];
@@ -47,14 +48,24 @@
             case              0x1b6:
                                         res++; break;
             }
-            if (code >= SLICE_START_CODE && code <= 0x1af) slice++;
+            if (code >= SLICE_START_CODE && code <= 0x1af) {
+                if (last >= SLICE_START_CODE && last <= 0x1af) {
+                    if (code >= last) slice++;
+                    else              sicle++;
+                }else{
+                    if (code == SLICE_START_CODE) slice++;
+                    else                          sicle++;
+                }
+            }
             if     ((code & 0x1f0) == VIDEO_ID)   vpes++;
             else if((code & 0x1e0) == AUDIO_ID)   apes++;
+            last = code;
         }
     }
-    if(seq && seq*9<=pic*10 && pic*9<=slice*10 && !pspack && !apes && !res)
+    if(seq && seq*9<=pic*10 && pic*9<=slice*10 && !pspack && !apes && !res && slice > sicle) {
         if(vpes) return AVPROBE_SCORE_MAX/8;
         else     return pic>1 ? AVPROBE_SCORE_MAX/2+1 : AVPROBE_SCORE_MAX/4; // +1 for .mpg
+    }
     return 0;
 }
 
diff --git a/libavformat/mtv.c b/libavformat/mtv.c
index cb50033..622a9b8 100644
--- a/libavformat/mtv.c
+++ b/libavformat/mtv.c
@@ -136,7 +136,7 @@
     avpriv_set_pts_info(st, 64, 1, mtv->video_fps);
     st->codec->codec_type      = AVMEDIA_TYPE_VIDEO;
     st->codec->codec_id        = AV_CODEC_ID_RAWVIDEO;
-    st->codec->pix_fmt         = PIX_FMT_RGB565BE;
+    st->codec->pix_fmt         = AV_PIX_FMT_RGB565BE;
     st->codec->width           = mtv->img_width;
     st->codec->height          = mtv->img_height;
     st->codec->sample_rate     = mtv->video_fps;
diff --git a/libavformat/mux.c b/libavformat/mux.c
new file mode 100644
index 0000000..9bcee99
--- /dev/null
+++ b/libavformat/mux.c
@@ -0,0 +1,799 @@
+/*
+ * muxing functions for use within FFmpeg
+ * Copyright (c) 2000, 2001, 2002 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
+ */
+
+/* #define DEBUG */
+
+#include "avformat.h"
+#include "avio_internal.h"
+#include "internal.h"
+#include "libavcodec/internal.h"
+#include "libavcodec/bytestream.h"
+#include "libavutil/opt.h"
+#include "libavutil/dict.h"
+#include "libavutil/pixdesc.h"
+#include "libavutil/timestamp.h"
+#include "metadata.h"
+#include "id3v2.h"
+#include "libavutil/avassert.h"
+#include "libavutil/avstring.h"
+#include "libavutil/mathematics.h"
+#include "libavutil/parseutils.h"
+#include "libavutil/time.h"
+#include "riff.h"
+#include "audiointerleave.h"
+#include "url.h"
+#include <stdarg.h>
+#if CONFIG_NETWORK
+#include "network.h"
+#endif
+
+#undef NDEBUG
+#include <assert.h>
+
+/**
+ * @file
+ * muxing functions for use within libavformat
+ */
+
+/* fraction handling */
+
+/**
+ * f = val + (num / den) + 0.5.
+ *
+ * 'num' is normalized so that it is such as 0 <= num < den.
+ *
+ * @param f fractional number
+ * @param val integer value
+ * @param num must be >= 0
+ * @param den must be >= 1
+ */
+static void frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
+{
+    num += (den >> 1);
+    if (num >= den) {
+        val += num / den;
+        num  = num % den;
+    }
+    f->val = val;
+    f->num = num;
+    f->den = den;
+}
+
+/**
+ * Fractional addition to f: f = f + (incr / f->den).
+ *
+ * @param f fractional number
+ * @param incr increment, can be positive or negative
+ */
+static void frac_add(AVFrac *f, int64_t incr)
+{
+    int64_t num, den;
+
+    num = f->num + incr;
+    den = f->den;
+    if (num < 0) {
+        f->val += num / den;
+        num     = num % den;
+        if (num < 0) {
+            num += den;
+            f->val--;
+        }
+    } else if (num >= den) {
+        f->val += num / den;
+        num     = num % den;
+    }
+    f->num = num;
+}
+
+AVRational ff_choose_timebase(AVFormatContext *s, AVStream *st, int min_precission)
+{
+    AVRational q;
+    int j;
+
+    if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
+        q = (AVRational){1, st->codec->sample_rate};
+    } else {
+        q = st->codec->time_base;
+    }
+    for (j=2; j<14; j+= 1+(j>2))
+        while (q.den / q.num < min_precission && q.num % j == 0)
+            q.num /= j;
+    while (q.den / q.num < min_precission && q.den < (1<<24))
+        q.den <<= 1;
+
+    return q;
+}
+
+int avformat_alloc_output_context2(AVFormatContext **avctx, AVOutputFormat *oformat,
+                                   const char *format, const char *filename)
+{
+    AVFormatContext *s = avformat_alloc_context();
+    int ret = 0;
+
+    *avctx = NULL;
+    if (!s)
+        goto nomem;
+
+    if (!oformat) {
+        if (format) {
+            oformat = av_guess_format(format, NULL, NULL);
+            if (!oformat) {
+                av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format);
+                ret = AVERROR(EINVAL);
+                goto error;
+            }
+        } else {
+            oformat = av_guess_format(NULL, filename, NULL);
+            if (!oformat) {
+                ret = AVERROR(EINVAL);
+                av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n",
+                       filename);
+                goto error;
+            }
+        }
+    }
+
+    s->oformat = oformat;
+    if (s->oformat->priv_data_size > 0) {
+        s->priv_data = av_mallocz(s->oformat->priv_data_size);
+        if (!s->priv_data)
+            goto nomem;
+        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;
+
+    if (filename)
+        av_strlcpy(s->filename, filename, sizeof(s->filename));
+    *avctx = s;
+    return 0;
+nomem:
+    av_log(s, AV_LOG_ERROR, "Out of memory\n");
+    ret = AVERROR(ENOMEM);
+error:
+    avformat_free_context(s);
+    return ret;
+}
+
+#if FF_API_ALLOC_OUTPUT_CONTEXT
+AVFormatContext *avformat_alloc_output_context(const char *format,
+                                               AVOutputFormat *oformat, const char *filename)
+{
+    AVFormatContext *avctx;
+    int ret = avformat_alloc_output_context2(&avctx, oformat, format, filename);
+    return ret < 0 ? NULL : avctx;
+}
+#endif
+
+static int validate_codec_tag(AVFormatContext *s, AVStream *st)
+{
+    const AVCodecTag *avctag;
+    int n;
+    enum AVCodecID id = AV_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 != AV_CODEC_ID_NONE) {
+            if (avpriv_toupper4(avctag->tag) == avpriv_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 != AV_CODEC_ID_NONE)
+        return 0;
+    if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
+        return 0;
+    return 1;
+}
+
+
+static int init_muxer(AVFormatContext *s, AVDictionary **options)
+{
+    int ret = 0, i;
+    AVStream *st;
+    AVDictionary *tmp = NULL;
+    AVCodecContext *codec = NULL;
+    AVOutputFormat *of = s->oformat;
+
+    if (options)
+        av_dict_copy(&tmp, *options, 0);
+
+    if ((ret = av_opt_set_dict(s, &tmp)) < 0)
+        goto fail;
+    if (s->priv_data && s->oformat->priv_class && *(const AVClass**)s->priv_data==s->oformat->priv_class &&
+        (ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
+        goto fail;
+
+    // some sanity checks
+    if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
+        av_log(s, AV_LOG_ERROR, "no streams\n");
+        ret = AVERROR(EINVAL);
+        goto fail;
+    }
+
+    for (i = 0; i < s->nb_streams; i++) {
+        st    = s->streams[i];
+        codec = st->codec;
+
+        switch (codec->codec_type) {
+        case AVMEDIA_TYPE_AUDIO:
+            if (codec->sample_rate <= 0) {
+                av_log(s, AV_LOG_ERROR, "sample rate not set\n");
+                ret = AVERROR(EINVAL);
+                goto fail;
+            }
+            if (!codec->block_align)
+                codec->block_align = codec->channels *
+                                     av_get_bits_per_sample(codec->codec_id) >> 3;
+            break;
+        case AVMEDIA_TYPE_VIDEO:
+            if (codec->time_base.num <= 0 ||
+                codec->time_base.den <= 0) { //FIXME audio too?
+                av_log(s, AV_LOG_ERROR, "time base not set\n");
+                ret = AVERROR(EINVAL);
+                goto fail;
+            }
+
+            if ((codec->width <= 0 || codec->height <= 0) &&
+                !(of->flags & AVFMT_NODIMENSIONS)) {
+                av_log(s, AV_LOG_ERROR, "dimensions not set\n");
+                ret = AVERROR(EINVAL);
+                goto fail;
+            }
+            if (av_cmp_q(st->sample_aspect_ratio, codec->sample_aspect_ratio)
+                && FFABS(av_q2d(st->sample_aspect_ratio) - av_q2d(codec->sample_aspect_ratio)) > 0.004*av_q2d(st->sample_aspect_ratio)
+            ) {
+                av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
+                                        "(%d/%d) and encoder layer (%d/%d)\n",
+                       st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
+                       codec->sample_aspect_ratio.num,
+                       codec->sample_aspect_ratio.den);
+                ret = AVERROR(EINVAL);
+                goto fail;
+            }
+            break;
+        }
+
+        if (of->codec_tag) {
+            if (   codec->codec_tag
+                && codec->codec_id == AV_CODEC_ID_RAWVIDEO
+                && (   av_codec_get_tag(of->codec_tag, codec->codec_id) == 0
+                    || av_codec_get_tag(of->codec_tag, codec->codec_id) == MKTAG('r', 'a', 'w', ' '))
+                && !validate_codec_tag(s, st)) {
+                // the current rawvideo encoding system ends up setting
+                // the wrong codec_tag for avi/mov, we override it here
+                codec->codec_tag = 0;
+            }
+            if (codec->codec_tag) {
+                if (!validate_codec_tag(s, st)) {
+                    char tagbuf[32], cortag[32];
+                    av_get_codec_tag_string(tagbuf, sizeof(tagbuf), codec->codec_tag);
+                    av_get_codec_tag_string(cortag, sizeof(cortag), av_codec_get_tag(s->oformat->codec_tag, codec->codec_id));
+                    av_log(s, AV_LOG_ERROR,
+                           "Tag %s/0x%08x incompatible with output codec id '%d' (%s)\n",
+                           tagbuf, codec->codec_tag, codec->codec_id, cortag);
+                    ret = AVERROR_INVALIDDATA;
+                    goto fail;
+                }
+            } else
+                codec->codec_tag = av_codec_get_tag(of->codec_tag, codec->codec_id);
+        }
+
+        if (of->flags & AVFMT_GLOBALHEADER &&
+            !(codec->flags & CODEC_FLAG_GLOBAL_HEADER))
+            av_log(s, AV_LOG_WARNING,
+                   "Codec for stream %d does not use global headers "
+                   "but container format requires global headers\n", i);
+    }
+
+    if (!s->priv_data && of->priv_data_size > 0) {
+        s->priv_data = av_mallocz(of->priv_data_size);
+        if (!s->priv_data) {
+            ret = AVERROR(ENOMEM);
+            goto fail;
+        }
+        if (of->priv_class) {
+            *(const AVClass **)s->priv_data = of->priv_class;
+            av_opt_set_defaults(s->priv_data);
+            if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
+                goto fail;
+        }
+    }
+
+    /* set muxer identification string */
+    if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
+        av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
+    }
+
+    if (options) {
+         av_dict_free(options);
+         *options = tmp;
+    }
+
+    return 0;
+
+fail:
+    av_dict_free(&tmp);
+    return ret;
+}
+
+static int init_pts(AVFormatContext *s)
+{
+    int i;
+    AVStream *st;
+
+    /* init PTS generation */
+    for (i = 0; i < s->nb_streams; i++) {
+        int64_t den = AV_NOPTS_VALUE;
+        st = s->streams[i];
+
+        switch (st->codec->codec_type) {
+        case AVMEDIA_TYPE_AUDIO:
+            den = (int64_t)st->time_base.num * st->codec->sample_rate;
+            break;
+        case AVMEDIA_TYPE_VIDEO:
+            den = (int64_t)st->time_base.num * st->codec->time_base.den;
+            break;
+        default:
+            break;
+        }
+        if (den != AV_NOPTS_VALUE) {
+            if (den <= 0)
+                return AVERROR_INVALIDDATA;
+
+            frac_init(&st->pts, 0, 0, den);
+        }
+    }
+
+    return 0;
+}
+
+int avformat_write_header(AVFormatContext *s, AVDictionary **options)
+{
+    int ret = 0;
+
+    if (ret = init_muxer(s, options))
+        return ret;
+
+    if (s->oformat->write_header) {
+        ret = s->oformat->write_header(s);
+        if (ret >= 0 && s->pb && s->pb->error < 0)
+            ret = s->pb->error;
+        if (ret < 0)
+            return ret;
+    }
+
+    if ((ret = init_pts(s) < 0))
+        return ret;
+
+    return 0;
+}
+
+//FIXME merge with compute_pkt_fields
+static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
+{
+    int delay = FFMAX(st->codec->has_b_frames, st->codec->max_b_frames > 0);
+    int num, den, frame_size, i;
+
+    av_dlog(s, "compute_pkt_fields2: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
+            av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), delay, pkt->size, pkt->stream_index);
+
+    /* duration field */
+    if (pkt->duration == 0) {
+        ff_compute_frame_duration(&num, &den, st, NULL, pkt);
+        if (den && num) {
+            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
+        }
+    }
+
+    if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
+        pkt->pts = pkt->dts;
+
+    //XXX/FIXME this is a temporary hack until all encoders output pts
+    if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
+        static int warned;
+        if (!warned) {
+            av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
+            warned = 1;
+        }
+        pkt->dts =
+//        pkt->pts= st->cur_dts;
+            pkt->pts = st->pts.val;
+    }
+
+    //calculate dts from pts
+    if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
+        st->pts_buffer[0] = pkt->pts;
+        for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
+            st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
+        for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
+            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
+
+        pkt->dts = st->pts_buffer[0];
+    }
+
+    if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
+        ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
+          st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
+        av_log(s, AV_LOG_ERROR,
+               "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
+               st->index, av_ts2str(st->cur_dts), av_ts2str(pkt->dts));
+        return AVERROR(EINVAL);
+    }
+    if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
+        av_log(s, AV_LOG_ERROR, "pts (%s) < dts (%s) in stream %d\n",
+               av_ts2str(pkt->pts), av_ts2str(pkt->dts), st->index);
+        return AVERROR(EINVAL);
+    }
+
+    av_dlog(s, "av_write_frame: pts2:%s dts2:%s\n",
+            av_ts2str(pkt->pts), av_ts2str(pkt->dts));
+    st->cur_dts = pkt->dts;
+    st->pts.val = pkt->dts;
+
+    /* update pts */
+    switch (st->codec->codec_type) {
+    case AVMEDIA_TYPE_AUDIO:
+        frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 1);
+
+        /* HACK/FIXME, we skip the initial 0 size packets as they are most
+         * likely equal to the encoder delay, but it would be better if we
+         * had the real timestamps from the encoder */
+        if (frame_size >= 0 && (pkt->size || st->pts.num != st->pts.den >> 1 || st->pts.val)) {
+            frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
+        }
+        break;
+    case AVMEDIA_TYPE_VIDEO:
+        frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
+        break;
+    default:
+        break;
+    }
+    return 0;
+}
+
+int av_write_frame(AVFormatContext *s, AVPacket *pkt)
+{
+    int ret;
+
+    if (!pkt) {
+        if (s->oformat->flags & AVFMT_ALLOW_FLUSH) {
+            ret = s->oformat->write_packet(s, pkt);
+            if (ret >= 0 && s->pb && s->pb->error < 0)
+                ret = s->pb->error;
+            return ret;
+        }
+        return 1;
+    }
+
+    ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
+
+    if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
+        return ret;
+
+    ret = s->oformat->write_packet(s, pkt);
+    if (ret >= 0 && s->pb && s->pb->error < 0)
+        ret = s->pb->error;
+
+    if (ret >= 0)
+        s->streams[pkt->stream_index]->nb_frames++;
+    return ret;
+}
+
+#define CHUNK_START 0x1000
+
+int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
+                              int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
+{
+    AVPacketList **next_point, *this_pktl;
+    AVStream *st   = s->streams[pkt->stream_index];
+    int chunked    = s->max_chunk_size || s->max_chunk_duration;
+
+    this_pktl      = av_mallocz(sizeof(AVPacketList));
+    if (!this_pktl)
+        return AVERROR(ENOMEM);
+    this_pktl->pkt = *pkt;
+    pkt->destruct  = NULL;           // do not free original but only the copy
+    av_dup_packet(&this_pktl->pkt);  // duplicate the packet if it uses non-allocated memory
+
+    if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
+        next_point = &(st->last_in_packet_buffer->next);
+    } else {
+        next_point = &s->packet_buffer;
+    }
+
+    if (*next_point) {
+        if (chunked) {
+            uint64_t max= av_rescale_q(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base);
+            if (   st->interleaver_chunk_size     + pkt->size     <= s->max_chunk_size-1U
+                && st->interleaver_chunk_duration + pkt->duration <= max-1U) {
+                st->interleaver_chunk_size     += pkt->size;
+                st->interleaver_chunk_duration += pkt->duration;
+                goto next_non_null;
+            } else {
+                st->interleaver_chunk_size     =
+                st->interleaver_chunk_duration = 0;
+                this_pktl->pkt.flags |= CHUNK_START;
+            }
+        }
+
+        if (compare(s, &s->packet_buffer_end->pkt, pkt)) {
+            while (   *next_point
+                   && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
+                       || !compare(s, &(*next_point)->pkt, pkt)))
+                next_point = &(*next_point)->next;
+            if (*next_point)
+                goto next_non_null;
+        } else {
+            next_point = &(s->packet_buffer_end->next);
+        }
+    }
+    av_assert1(!*next_point);
+
+    s->packet_buffer_end = this_pktl;
+next_non_null:
+
+    this_pktl->next = *next_point;
+
+    s->streams[pkt->stream_index]->last_in_packet_buffer =
+        *next_point                                      = this_pktl;
+    return 0;
+}
+
+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];
+    int comp      = av_compare_ts(next->dts, st2->time_base, pkt->dts,
+                                  st->time_base);
+    if (s->audio_preload && ((st->codec->codec_type == AVMEDIA_TYPE_AUDIO) != (st2->codec->codec_type == AVMEDIA_TYPE_AUDIO))) {
+        int64_t ts = av_rescale_q(pkt ->dts, st ->time_base, AV_TIME_BASE_Q) - s->audio_preload*(st ->codec->codec_type == AVMEDIA_TYPE_AUDIO);
+        int64_t ts2= av_rescale_q(next->dts, st2->time_base, AV_TIME_BASE_Q) - s->audio_preload*(st2->codec->codec_type == AVMEDIA_TYPE_AUDIO);
+        if (ts == ts2) {
+            ts= ( pkt ->dts* st->time_base.num*AV_TIME_BASE - s->audio_preload*(int64_t)(st ->codec->codec_type == AVMEDIA_TYPE_AUDIO)* st->time_base.den)*st2->time_base.den
+               -( next->dts*st2->time_base.num*AV_TIME_BASE - s->audio_preload*(int64_t)(st2->codec->codec_type == AVMEDIA_TYPE_AUDIO)*st2->time_base.den)* st->time_base.den;
+            ts2=0;
+        }
+        comp= (ts>ts2) - (ts<ts2);
+    }
+
+    if (comp == 0)
+        return pkt->stream_index < next->stream_index;
+    return comp > 0;
+}
+
+int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
+                                 AVPacket *pkt, int flush)
+{
+    AVPacketList *pktl;
+    int stream_count = 0, noninterleaved_count = 0;
+    int64_t delta_dts_max = 0;
+    int i, ret;
+
+    if (pkt) {
+        ret = ff_interleave_add_packet(s, pkt, ff_interleave_compare_dts);
+        if (ret < 0)
+            return ret;
+    }
+
+    for (i = 0; i < s->nb_streams; i++) {
+        if (s->streams[i]->last_in_packet_buffer) {
+            ++stream_count;
+        } else if (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
+            ++noninterleaved_count;
+        }
+    }
+
+    if (s->nb_streams == stream_count) {
+        flush = 1;
+    } else if (!flush) {
+        for (i=0; i < s->nb_streams; i++) {
+            if (s->streams[i]->last_in_packet_buffer) {
+                int64_t delta_dts =
+                    av_rescale_q(s->streams[i]->last_in_packet_buffer->pkt.dts,
+                                s->streams[i]->time_base,
+                                AV_TIME_BASE_Q) -
+                    av_rescale_q(s->packet_buffer->pkt.dts,
+                                s->streams[s->packet_buffer->pkt.stream_index]->time_base,
+                                AV_TIME_BASE_Q);
+                delta_dts_max= FFMAX(delta_dts_max, delta_dts);
+            }
+        }
+        if (s->nb_streams == stream_count+noninterleaved_count &&
+           delta_dts_max > 20*AV_TIME_BASE) {
+            av_log(s, AV_LOG_DEBUG, "flushing with %d noninterleaved\n", noninterleaved_count);
+            flush = 1;
+        }
+    }
+    if (stream_count && flush) {
+        AVStream *st;
+        pktl = s->packet_buffer;
+        *out = pktl->pkt;
+        st   = s->streams[out->stream_index];
+
+        s->packet_buffer = pktl->next;
+        if (!s->packet_buffer)
+            s->packet_buffer_end = NULL;
+
+        if (st->last_in_packet_buffer == pktl)
+            st->last_in_packet_buffer = NULL;
+        av_freep(&pktl);
+
+        if (s->avoid_negative_ts > 0) {
+            if (out->dts != AV_NOPTS_VALUE) {
+                if (!st->mux_ts_offset && out->dts < 0) {
+                    for (i = 0; i < s->nb_streams; i++) {
+                        s->streams[i]->mux_ts_offset =
+                            av_rescale_q_rnd(-out->dts,
+                                             st->time_base,
+                                             s->streams[i]->time_base,
+                                             AV_ROUND_UP);
+                    }
+                }
+                out->dts += st->mux_ts_offset;
+            }
+            if (out->pts != AV_NOPTS_VALUE)
+                out->pts += st->mux_ts_offset;
+        }
+
+        return 1;
+    } else {
+        av_init_packet(out);
+        return 0;
+    }
+}
+
+#if FF_API_INTERLEAVE_PACKET
+int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
+                                 AVPacket *pkt, int flush)
+{
+    return ff_interleave_packet_per_dts(s, out, pkt, flush);
+}
+
+#endif
+
+/**
+ * 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
+ *              remaining packets should be output
+ * @return 1 if a packet was output, 0 if no packet could be output,
+ *         < 0 if an error occurred
+ */
+static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
+{
+    if (s->oformat->interleave_packet) {
+        int ret = s->oformat->interleave_packet(s, out, in, flush);
+        if (in)
+            av_free_packet(in);
+        return ret;
+    } else
+        return ff_interleave_packet_per_dts(s, out, in, flush);
+}
+
+int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
+{
+    int ret, flush = 0;
+
+    if (pkt) {
+        AVStream *st = s->streams[pkt->stream_index];
+
+        //FIXME/XXX/HACK drop zero sized packets
+        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size == 0)
+            return 0;
+
+        av_dlog(s, "av_interleaved_write_frame size:%d dts:%s pts:%s\n",
+                pkt->size, av_ts2str(pkt->dts), av_ts2str(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 AVERROR(EINVAL);
+    } else {
+        av_dlog(s, "av_interleaved_write_frame FLUSH\n");
+        flush = 1;
+    }
+
+    for (;; ) {
+        AVPacket opkt;
+        int ret = interleave_packet(s, &opkt, pkt, flush);
+        if (ret <= 0) //FIXME cleanup needed for ret<0 ?
+            return ret;
+
+        ret = s->oformat->write_packet(s, &opkt);
+        if (ret >= 0)
+            s->streams[opkt.stream_index]->nb_frames++;
+
+        av_free_packet(&opkt);
+        pkt = NULL;
+
+        if (ret < 0)
+            return ret;
+        if(s->pb && s->pb->error)
+            return s->pb->error;
+    }
+}
+
+int av_write_trailer(AVFormatContext *s)
+{
+    int ret, i;
+
+    for (;; ) {
+        AVPacket pkt;
+        ret = interleave_packet(s, &pkt, NULL, 1);
+        if (ret < 0) //FIXME cleanup needed for ret<0 ?
+            goto fail;
+        if (!ret)
+            break;
+
+        ret = s->oformat->write_packet(s, &pkt);
+        if (ret >= 0)
+            s->streams[pkt.stream_index]->nb_frames++;
+
+        av_free_packet(&pkt);
+
+        if (ret < 0)
+            goto fail;
+        if(s->pb && s->pb->error)
+            goto fail;
+    }
+
+    if (s->oformat->write_trailer)
+        ret = s->oformat->write_trailer(s);
+
+fail:
+    if (s->pb)
+       avio_flush(s->pb);
+    if (ret == 0)
+       ret = s->pb ? s->pb->error : 0;
+    for (i = 0; i < s->nb_streams; i++) {
+        av_freep(&s->streams[i]->priv_data);
+        av_freep(&s->streams[i]->index_entries);
+    }
+    if (s->oformat->priv_class)
+        av_opt_free(s->priv_data);
+    av_freep(&s->priv_data);
+    return ret;
+}
+
+int av_get_output_timestamp(struct AVFormatContext *s, int stream,
+                            int64_t *dts, int64_t *wall)
+{
+    if (!s->oformat || !s->oformat->get_output_timestamp)
+        return AVERROR(ENOSYS);
+    s->oformat->get_output_timestamp(s, stream, dts, wall);
+    return 0;
+}
diff --git a/libavformat/mvi.c b/libavformat/mvi.c
index 0833e11..9184927 100644
--- a/libavformat/mvi.c
+++ b/libavformat/mvi.c
@@ -19,6 +19,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "avformat.h"
 #include "internal.h"
 
@@ -53,6 +54,8 @@
 
     vst->codec->extradata_size = 2;
     vst->codec->extradata = av_mallocz(2 + FF_INPUT_BUFFER_PADDING_SIZE);
+    if (!vst->codec->extradata)
+        return AVERROR(ENOMEM);
 
     version                  = avio_r8(pb);
     vst->codec->extradata[0] = avio_r8(pb);
@@ -81,6 +84,7 @@
     ast->codec->codec_type      = AVMEDIA_TYPE_AUDIO;
     ast->codec->codec_id        = AV_CODEC_ID_PCM_U8;
     ast->codec->channels        = 1;
+    ast->codec->channel_layout  = AV_CH_LAYOUT_MONO;
     ast->codec->bits_per_coded_sample = 8;
     ast->codec->bit_rate        = ast->codec->sample_rate * 8;
 
diff --git a/libavformat/mxf.c b/libavformat/mxf.c
index 7230444..4a4158a 100644
--- a/libavformat/mxf.c
+++ b/libavformat/mxf.c
@@ -58,13 +58,13 @@
 };
 
 const MXFCodecUL ff_mxf_pixel_format_uls[] = {
-    { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x01,0x01,0x02,0x01,0x01 }, 16, PIX_FMT_UYVY422 },
-    { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x01,0x01,0x02,0x01,0x02 }, 16, PIX_FMT_YUYV422 },
-    { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },  0,    PIX_FMT_NONE },
+    { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x01,0x01,0x02,0x01,0x01 }, 16, AV_PIX_FMT_UYVY422 },
+    { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x01,0x01,0x02,0x01,0x02 }, 16, AV_PIX_FMT_YUYV422 },
+    { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },  0,    AV_PIX_FMT_NONE },
 };
 
 static const struct {
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
     const char data[16];
 } ff_mxf_pixel_layouts[] = {
     /**
@@ -76,24 +76,24 @@
      * 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                                           }},
+    {AV_PIX_FMT_ABGR,    {'A', 8,  'B', 8,  'G', 8, 'R', 8                 }},
+    {AV_PIX_FMT_ARGB,    {'A', 8,  'R', 8,  'G', 8, 'B', 8                 }},
+    {AV_PIX_FMT_BGR24,   {'B', 8,  'G', 8,  'R', 8                         }},
+    {AV_PIX_FMT_BGRA,    {'B', 8,  'G', 8,  'R', 8, 'A', 8                 }},
+    {AV_PIX_FMT_RGB24,   {'R', 8,  'G', 8,  'B', 8                         }},
+    {AV_PIX_FMT_RGB444BE,{'F', 4,  'R', 4,  'G', 4, 'B', 4                 }},
+    {AV_PIX_FMT_RGB48BE, {'R', 8,  'r', 8,  'G', 8, 'g', 8, 'B', 8, 'b', 8 }},
+    {AV_PIX_FMT_RGB48BE, {'R', 16, 'G', 16, 'B', 16                        }},
+    {AV_PIX_FMT_RGB48LE, {'r', 8,  'R', 8,  'g', 8, 'G', 8, 'b', 8, 'B', 8 }},
+    {AV_PIX_FMT_RGB555BE,{'F', 1,  'R', 5,  'G', 5, 'B', 5                 }},
+    {AV_PIX_FMT_RGB565BE,{'R', 5,  'G', 6,  'B', 5                         }},
+    {AV_PIX_FMT_RGBA,    {'R', 8,  'G', 8,  'B', 8, 'A', 8                 }},
+    {AV_PIX_FMT_PAL8,    {'P', 8                                           }},
 };
 
 static const int num_pixel_layouts = FF_ARRAY_ELEMS(ff_mxf_pixel_layouts);
 
-int ff_mxf_decode_pixel_layout(const char pixel_layout[16], enum PixelFormat *pix_fmt)
+int ff_mxf_decode_pixel_layout(const char pixel_layout[16], enum AVPixelFormat *pix_fmt)
 {
     int x;
 
diff --git a/libavformat/mxf.h b/libavformat/mxf.h
index ed3225b..4c751e8 100644
--- a/libavformat/mxf.h
+++ b/libavformat/mxf.h
@@ -55,13 +55,13 @@
     SegmentedFrame,
 };
 
-typedef struct {
+typedef struct KLVPacket {
     UID key;
     int64_t offset;
     uint64_t length;
 } KLVPacket;
 
-typedef struct {
+typedef struct MXFCodecUL {
     UID uid;
     unsigned matching_len;
     int id;
@@ -76,7 +76,7 @@
 extern const MXFCodecUL ff_mxf_codec_uls[];
 extern const MXFCodecUL ff_mxf_pixel_format_uls[];
 
-int ff_mxf_decode_pixel_layout(const char pixel_layout[16], enum PixelFormat *pix_fmt);
+int ff_mxf_decode_pixel_layout(const char pixel_layout[16], enum AVPixelFormat *pix_fmt);
 const MXFSamplesPerFrame *ff_mxf_get_samples_per_frame(AVFormatContext *s, AVRational time_base);
 
 #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, \
diff --git a/libavformat/mxfdec.c b/libavformat/mxfdec.c
index a503289..921dc42 100644
--- a/libavformat/mxfdec.c
+++ b/libavformat/mxfdec.c
@@ -46,6 +46,7 @@
 //#define DEBUG
 
 #include "libavutil/aes.h"
+#include "libavutil/avassert.h"
 #include "libavutil/mathematics.h"
 #include "libavcodec/bytestream.h"
 #include "libavutil/timecode.h"
@@ -132,6 +133,7 @@
     uint8_t track_number[4];
     AVRational edit_rate;
     int intra_only;
+    uint64_t sample_count;
 } MXFTrack;
 
 typedef struct {
@@ -154,7 +156,7 @@
     int linked_track_id;
     uint8_t *extradata;
     int extradata_size;
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
 } MXFDescriptor;
 
 typedef struct {
@@ -240,6 +242,8 @@
     enum MXFMetadataSetType type;
 } MXFMetadataReadTableEntry;
 
+static int mxf_read_close(AVFormatContext *s);
+
 /* partial keys to match */
 static const uint8_t mxf_header_partition_pack_key[]       = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
 static const uint8_t mxf_essence_element_key[]             = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
@@ -350,7 +354,7 @@
     int index;
 
     if (!mxf->aesc && s->key && s->keylen == 16) {
-        mxf->aesc = av_malloc(av_aes_size);
+        mxf->aesc = av_aes_alloc();
         if (!mxf->aesc)
             return AVERROR(ENOMEM);
         av_aes_init(mxf->aesc, s->key, 128, 1);
@@ -782,17 +786,18 @@
 static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
 {
     int code, value, ofs = 0;
-    char layout[16] = {0};
+    char layout[16] = {0}; /* not for printing, may end up not terminated on purpose */
 
     do {
         code = avio_r8(pb);
         value = avio_r8(pb);
         av_dlog(NULL, "pixel layout: code %#x\n", code);
 
-        if (ofs < 16) {
+        if (ofs <= 14) {
             layout[ofs++] = code;
             layout[ofs++] = value;
-        }
+        } else
+            break;  /* don't read byte by byte on sneaky files filled with lots of non-zeroes */
     } while (code != 0); /* SMPTE 377M E.2.46 */
 
     ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
@@ -801,7 +806,7 @@
 static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
 {
     MXFDescriptor *descriptor = arg;
-    descriptor->pix_fmt = PIX_FMT_NONE;
+    descriptor->pix_fmt = AV_PIX_FMT_NONE;
     switch(tag) {
     case 0x3F01:
         descriptor->sub_descriptors_count = avio_rb32(pb);
@@ -951,6 +956,9 @@
         if (mxf->metadata_sets[i]->type == IndexTableSegment)
             nb_segments++;
 
+    if (!nb_segments)
+        return AVERROR_INVALIDDATA;
+
     if (!(unsorted_segments = av_calloc(nb_segments, sizeof(*unsorted_segments))) ||
         !(*sorted_segments  = av_calloc(nb_segments, sizeof(**sorted_segments)))) {
         av_freep(sorted_segments);
@@ -1437,6 +1445,12 @@
         if (st->duration == -1)
             st->duration = AV_NOPTS_VALUE;
         st->start_time = component->start_position;
+        if (material_track->edit_rate.num <= 0 || material_track->edit_rate.den <= 0) {
+            av_log(mxf->fc, AV_LOG_WARNING,
+                   "invalid edit rate (%d/%d) found on stream #%d, defaulting to 25/1\n",
+                   material_track->edit_rate.num, material_track->edit_rate.den, st->index);
+            material_track->edit_rate = (AVRational){25, 1};
+        }
         avpriv_set_pts_info(st, 64, material_track->edit_rate.den, material_track->edit_rate.num);
 
         PRINT_KEY(mxf->fc, "data definition   ul", source_track->sequence->data_definition_ul);
@@ -1483,7 +1497,7 @@
 
         /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
         codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul);
-        st->codec->codec_id = codec_ul->id;
+        st->codec->codec_id = (enum AVCodecID)codec_ul->id;
         if (descriptor->extradata) {
             st->codec->extradata = descriptor->extradata;
             st->codec->extradata_size = descriptor->extradata_size;
@@ -1518,17 +1532,17 @@
             }
             if (st->codec->codec_id == AV_CODEC_ID_RAWVIDEO) {
                 st->codec->pix_fmt = descriptor->pix_fmt;
-                if (st->codec->pix_fmt == PIX_FMT_NONE) {
+                if (st->codec->pix_fmt == AV_PIX_FMT_NONE) {
                     pix_fmt_ul = mxf_get_codec_ul(ff_mxf_pixel_format_uls,
                                                   &descriptor->essence_codec_ul);
-                    st->codec->pix_fmt = pix_fmt_ul->id;
-                    if (st->codec->pix_fmt == PIX_FMT_NONE) {
+                    st->codec->pix_fmt = (enum AVPixelFormat)pix_fmt_ul->id;
+                    if (st->codec->pix_fmt == AV_PIX_FMT_NONE) {
                         /* support files created before RP224v10 by defaulting to UYVY422
                            if subsampling is 4:2:2 and component depth is 8-bit */
                         if (descriptor->horiz_subsampling == 2 &&
                             descriptor->vert_subsampling == 1 &&
                             descriptor->component_depth == 8) {
-                            st->codec->pix_fmt = PIX_FMT_UYVY422;
+                            st->codec->pix_fmt = AV_PIX_FMT_UYVY422;
                         }
                     }
                 }
@@ -1537,13 +1551,19 @@
         } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
             container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul);
             /* Only overwrite existing codec ID if it is unset or A-law, which is the default according to SMPTE RP 224. */
-            if (st->codec->codec_id == AV_CODEC_ID_NONE || (st->codec->codec_id == AV_CODEC_ID_PCM_ALAW && container_ul->id != AV_CODEC_ID_NONE))
-                st->codec->codec_id = container_ul->id;
+            if (st->codec->codec_id == AV_CODEC_ID_NONE || (st->codec->codec_id == AV_CODEC_ID_PCM_ALAW && (enum AVCodecID)container_ul->id != AV_CODEC_ID_NONE))
+                st->codec->codec_id = (enum AVCodecID)container_ul->id;
             st->codec->channels = descriptor->channels;
             st->codec->bits_per_coded_sample = descriptor->bits_per_sample;
 
-            if (descriptor->sample_rate.den > 0)
+            if (descriptor->sample_rate.den > 0) {
+                avpriv_set_pts_info(st, 64, descriptor->sample_rate.den, descriptor->sample_rate.num);
                 st->codec->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
+            } else {
+                av_log(mxf->fc, AV_LOG_WARNING, "invalid sample rate (%d/%d) found for stream #%d, time base forced to 1/48000\n",
+                       descriptor->sample_rate.num, descriptor->sample_rate.den, st->index);
+                avpriv_set_pts_info(st, 64, 1, 48000);
+            }
 
             /* TODO: implement AV_CODEC_ID_RAWAUDIO */
             if (st->codec->codec_id == AV_CODEC_ID_PCM_S16LE) {
@@ -1642,6 +1662,9 @@
         /* Accept the 64k local set limit being exceeded (Avid). Don't accept
          * it extending past the end of the KLV though (zzuf5.mxf). */
         if (avio_tell(pb) > klv_end) {
+            if (ctx_size)
+                av_free(ctx);
+
             av_log(mxf->fc, AV_LOG_ERROR,
                    "local tag %#04x extends past end of local set @ %#"PRIx64"\n",
                    tag, klv->offset);
@@ -1923,10 +1946,10 @@
     /* we need to do this before computing the index tables
      * to be able to fill in zero IndexDurations with st->duration */
     if ((ret = mxf_parse_structural_metadata(mxf)) < 0)
-        return ret;
+        goto fail;
 
     if ((ret = mxf_compute_index_tables(mxf)) < 0)
-        return ret;
+        goto fail;
 
     if (mxf->nb_index_tables > 1) {
         /* TODO: look up which IndexSID to use via EssenceContainerData */
@@ -1934,12 +1957,17 @@
                mxf->nb_index_tables, mxf->index_tables[0].index_sid);
     } else if (mxf->nb_index_tables == 0 && mxf->op == OPAtom) {
         av_log(mxf->fc, AV_LOG_ERROR, "cannot demux OPAtom without an index\n");
-        return AVERROR_INVALIDDATA;
+        ret = AVERROR_INVALIDDATA;
+        goto fail;
     }
 
     mxf_handle_small_eubc(s);
 
     return 0;
+fail:
+    mxf_read_close(s);
+
+    return ret;
 }
 
 /**
@@ -1983,6 +2011,51 @@
     return next_ofs;
 }
 
+static int mxf_compute_sample_count(MXFContext *mxf, int stream_index, uint64_t *sample_count)
+{
+    int i, total = 0, size = 0;
+    AVStream *st = mxf->fc->streams[stream_index];
+    MXFTrack *track = st->priv_data;
+    AVRational time_base = av_inv_q(track->edit_rate);
+    AVRational sample_rate = av_inv_q(st->time_base);
+    const MXFSamplesPerFrame *spf = NULL;
+
+    if ((sample_rate.num / sample_rate.den) == 48000)
+        spf = ff_mxf_get_samples_per_frame(mxf->fc, time_base);
+    if (!spf) {
+        int remainder = (sample_rate.num * time_base.num) % (time_base.den * sample_rate.den);
+        *sample_count = av_q2d(av_mul_q((AVRational){mxf->current_edit_unit, 1},
+                                        av_mul_q(sample_rate, time_base)));
+        if (remainder)
+            av_log(mxf->fc, AV_LOG_WARNING,
+                   "seeking detected on stream #%d with time base (%d/%d) and sample rate (%d/%d), audio pts won't be accurate.\n",
+                   stream_index, time_base.num, time_base.den, sample_rate.num, sample_rate.den);
+        return 0;
+    }
+
+    while (spf->samples_per_frame[size]) {
+        total += spf->samples_per_frame[size];
+        size++;
+    }
+
+    av_assert2(size);
+
+    *sample_count = (mxf->current_edit_unit / size) * (uint64_t)total;
+    for (i = 0; i < mxf->current_edit_unit % size; i++) {
+        *sample_count += spf->samples_per_frame[i];
+    }
+
+    return 0;
+}
+
+static int mxf_set_audio_pts(MXFContext *mxf, AVCodecContext *codec, AVPacket *pkt)
+{
+    MXFTrack *track = mxf->fc->streams[pkt->stream_index]->priv_data;
+    pkt->pts = track->sample_count;
+    track->sample_count += pkt->size / (codec->channels * av_get_bits_per_sample(codec->codec_id) / 8);
+    return 0;
+}
+
 static int mxf_read_packet_old(AVFormatContext *s, AVPacket *pkt)
 {
     KLVPacket klv;
@@ -2008,6 +2081,7 @@
             int64_t next_ofs, next_klv;
             AVStream *st;
             MXFTrack *track;
+            AVCodecContext *codec;
 
             if (index < 0) {
                 av_log(s, AV_LOG_ERROR, "error getting stream index %d\n", AV_RB32(klv.key+12));
@@ -2046,7 +2120,8 @@
             pkt->stream_index = index;
             pkt->pos = klv.offset;
 
-            if (s->streams[index]->codec->codec_type == AVMEDIA_TYPE_VIDEO && next_ofs >= 0) {
+            codec = s->streams[index]->codec;
+            if (codec->codec_type == AVMEDIA_TYPE_VIDEO && next_ofs >= 0) {
                 /* mxf->current_edit_unit good - see if we have an index table to derive timestamps from */
                 MXFIndexTable *t = &mxf->index_tables[0];
 
@@ -2058,6 +2133,10 @@
                      * let utils.c figure out DTS since it can be < PTS if low_delay = 0 (Sony IMX30) */
                     pkt->pts = mxf->current_edit_unit;
                 }
+            } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
+                int ret = mxf_set_audio_pts(mxf, codec, pkt);
+                if (ret < 0)
+                    return ret;
             }
 
             /* seek for truncated packets */
@@ -2115,13 +2194,18 @@
     if ((size = av_get_packet(s->pb, pkt, size)) < 0)
         return size;
 
+    pkt->stream_index = 0;
+
     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && t->ptses &&
         mxf->current_edit_unit >= 0 && mxf->current_edit_unit < t->nb_ptses) {
         pkt->dts = mxf->current_edit_unit + t->first_dts;
         pkt->pts = t->ptses[mxf->current_edit_unit];
+    } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
+        int ret = mxf_set_audio_pts(mxf, st->codec, pkt);
+        if (ret < 0)
+            return ret;
     }
 
-    pkt->stream_index = 0;
     mxf->current_edit_unit += edit_units;
 
     return 0;
@@ -2166,10 +2250,12 @@
     av_freep(&mxf->aesc);
     av_freep(&mxf->local_tags);
 
-    for (i = 0; i < mxf->nb_index_tables; i++) {
-        av_freep(&mxf->index_tables[i].segments);
-        av_freep(&mxf->index_tables[i].ptses);
-        av_freep(&mxf->index_tables[i].fake_index);
+    if (mxf->index_tables) {
+        for (i = 0; i < mxf->nb_index_tables; i++) {
+            av_freep(&mxf->index_tables[i].segments);
+            av_freep(&mxf->index_tables[i].ptses);
+            av_freep(&mxf->index_tables[i].fake_index);
+        }
     }
     av_freep(&mxf->index_tables);
 
@@ -2200,7 +2286,7 @@
     int64_t seconds;
     MXFContext* mxf = s->priv_data;
     int64_t seekpos;
-    int ret;
+    int i, ret;
     MXFIndexTable *t;
 
     if (mxf->nb_index_tables <= 0) {
@@ -2237,6 +2323,20 @@
         mxf->current_edit_unit = sample_time;
         avio_seek(s->pb, seekpos, SEEK_SET);
     }
+
+    // Update all tracks sample count
+    for (i = 0; i < s->nb_streams; i++) {
+        AVStream *cur_st = s->streams[i];
+        MXFTrack *cur_track = cur_st->priv_data;
+        uint64_t current_sample_count = 0;
+        if (cur_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
+            ret = mxf_compute_sample_count(mxf, i, &current_sample_count);
+            if (ret < 0)
+                return ret;
+
+            cur_track->sample_count = current_sample_count;
+        }
+    }
     return 0;
 }
 
diff --git a/libavformat/mxfenc.c b/libavformat/mxfenc.c
index 220b3e4..c583197 100644
--- a/libavformat/mxfenc.c
+++ b/libavformat/mxfenc.c
@@ -529,18 +529,25 @@
     return uls;
 }
 
+//one EC -> one descriptor. N ECs -> MultipleDescriptor + N descriptors
+#define DESCRIPTOR_COUNT(essence_container_count) \
+    (essence_container_count > 1 ? essence_container_count + 1 : essence_container_count)
+
 static void mxf_write_essence_container_refs(AVFormatContext *s)
 {
     MXFContext *c = s->priv_data;
     AVIOContext *pb = s->pb;
     int i;
 
-    mxf_write_refs_count(pb, c->essence_container_count);
+    mxf_write_refs_count(pb, DESCRIPTOR_COUNT(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;
         avio_write(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
     }
+
+    if (c->essence_container_count > 1)
+        avio_write(pb, multiple_desc_ul, 16);
 }
 
 static void mxf_write_preface(AVFormatContext *s)
@@ -550,7 +557,7 @@
 
     mxf_write_metadata_key(pb, 0x012f00);
     PRINT_KEY(s, "preface key", pb->buf_ptr - 16);
-    klv_encode_ber_length(pb, 130 + 16 * mxf->essence_container_count);
+    klv_encode_ber_length(pb, 130 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count));
 
     // write preface set uid
     mxf_write_local_tag(pb, 16, 0x3C0A);
@@ -579,7 +586,7 @@
     avio_write(pb, op1a_ul, 16);
 
     // write essence_container_refs
-    mxf_write_local_tag(pb, 8 + 16 * mxf->essence_container_count, 0x3B0A);
+    mxf_write_local_tag(pb, 8 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count), 0x3B0A);
     mxf_write_essence_container_refs(s);
 
     // write dm_scheme_refs
@@ -823,7 +830,7 @@
 
     mxf_write_metadata_key(pb, 0x014400);
     PRINT_KEY(s, "multiple descriptor key", pb->buf_ptr - 16);
-    klv_encode_ber_length(pb, 64 + 16 * s->nb_streams);
+    klv_encode_ber_length(pb, 64 + 16LL * s->nb_streams);
 
     mxf_write_local_tag(pb, 16, 0x3C0A);
     mxf_write_uuid(pb, MultipleDescriptor, 0);
@@ -1165,8 +1172,8 @@
     if (mxf->edit_unit_byte_count) {
         klv_encode_ber_length(pb, 80);
     } else {
-        klv_encode_ber_length(pb, 85 + 12+(s->nb_streams+1)*6 +
-                              12+mxf->edit_units_count*(11+mxf->slice_count*4));
+        klv_encode_ber_length(pb, 85 + 12+(s->nb_streams+1LL)*6 +
+                              12+mxf->edit_units_count*(11+mxf->slice_count*4LL));
     }
 
     // instance id
@@ -1326,7 +1333,7 @@
 
     // write klv
     avio_write(pb, key, 16);
-    klv_encode_ber_length(pb, 88 + 16 * mxf->essence_container_count);
+    klv_encode_ber_length(pb, 88 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count));
 
     // write partition value
     avio_wb16(pb, 1); // majorVersion
@@ -1700,16 +1707,16 @@
             if (ret < 0)
                 return ret;
             if (s->oformat == &ff_mxf_d10_muxer) {
-                if (st->codec->bit_rate == 50000000)
+                if (st->codec->bit_rate == 50000000) {
                     if (mxf->time_base.den == 25) sc->index = 3;
                     else                          sc->index = 5;
-                else if (st->codec->bit_rate == 40000000)
+                } else if (st->codec->bit_rate == 40000000) {
                     if (mxf->time_base.den == 25) sc->index = 7;
                     else                          sc->index = 9;
-                else if (st->codec->bit_rate == 30000000)
+                } else if (st->codec->bit_rate == 30000000) {
                     if (mxf->time_base.den == 25) sc->index = 11;
                     else                          sc->index = 13;
-                else {
+                } else {
                     av_log(s, AV_LOG_ERROR, "error MXF D-10 only support 30/40/50 mbit/s\n");
                     return -1;
                 }
@@ -1820,7 +1827,7 @@
     avio_w8(pb, 0x04); // content package rate
     avio_w8(pb, 0x00); // content package type
     avio_wb16(pb, 0x00); // channel handle
-    avio_wb16(pb, mxf->tc.start + frame); // continuity count
+    avio_wb16(pb, (mxf->tc.start + frame) & 0xFFFF); // continuity count, supposed to overflow
     if (mxf->essence_container_count > 1)
         avio_write(pb, multiple_desc_ul, 16);
     else {
@@ -2004,7 +2011,7 @@
     int i;
 
     avio_write(pb, random_index_pack_key, 16);
-    klv_encode_ber_length(pb, 28 + 12*mxf->body_partitions_count);
+    klv_encode_ber_length(pb, 28 + 12LL*mxf->body_partitions_count);
 
     if (mxf->edit_unit_byte_count)
         avio_wb32(pb, 1); // BodySID of header partition
@@ -2107,7 +2114,7 @@
         }
 
         *out = pktl->pkt;
-        av_dlog(s, "out st:%d dts:%lld\n", (*out).stream_index, (*out).dts);
+        av_dlog(s, "out st:%d dts:%"PRId64"\n", (*out).stream_index, (*out).dts);
         s->packet_buffer = pktl->next;
         if(s->streams[pktl->pkt.stream_index]->last_in_packet_buffer == pktl)
             s->streams[pktl->pkt.stream_index]->last_in_packet_buffer= NULL;
diff --git a/libavformat/mxg.c b/libavformat/mxg.c
index be7e6db..d911a33 100644
--- a/libavformat/mxg.c
+++ b/libavformat/mxg.c
@@ -19,6 +19,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "libavcodec/mjpeg.h"
 #include "avformat.h"
@@ -56,6 +57,7 @@
     audio_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
     audio_st->codec->codec_id = AV_CODEC_ID_PCM_ALAW;
     audio_st->codec->channels = 1;
+    audio_st->codec->channel_layout = AV_CH_LAYOUT_MONO;
     audio_st->codec->sample_rate = 8000;
     audio_st->codec->bits_per_coded_sample = 8;
     audio_st->codec->block_align = 1;
diff --git a/libavformat/network.c b/libavformat/network.c
index 0e79cae..6e924be 100644
--- a/libavformat/network.c
+++ b/libavformat/network.c
@@ -22,10 +22,10 @@
 #include "network.h"
 #include "libavcodec/internal.h"
 #include "libavutil/mem.h"
+#include "url.h"
+#include "libavutil/time.h"
 
-#define THREADS (HAVE_PTHREADS || (defined(WIN32) && !defined(__MINGW32CE__)))
-
-#if THREADS
+#if HAVE_THREADS
 #if HAVE_PTHREADS
 #include <pthread.h>
 #else
@@ -36,7 +36,7 @@
 #if CONFIG_OPENSSL
 #include <openssl/ssl.h>
 static int openssl_init;
-#if THREADS
+#if HAVE_THREADS
 #include <openssl/crypto.h>
 #include "libavutil/avutil.h"
 pthread_mutex_t *openssl_mutexes;
@@ -57,7 +57,7 @@
 #endif
 #if CONFIG_GNUTLS
 #include <gnutls/gnutls.h>
-#if THREADS && GNUTLS_VERSION_NUMBER <= 0x020b00
+#if HAVE_THREADS && GNUTLS_VERSION_NUMBER <= 0x020b00
 #include <gcrypt.h>
 #include <errno.h>
 #undef malloc
@@ -73,7 +73,7 @@
     if (!openssl_init) {
         SSL_library_init();
         SSL_load_error_strings();
-#if THREADS
+#if HAVE_THREADS
         if (!CRYPTO_get_locking_callback()) {
             int i;
             openssl_mutexes = av_malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
@@ -89,7 +89,7 @@
     openssl_init++;
 #endif
 #if CONFIG_GNUTLS
-#if THREADS && GNUTLS_VERSION_NUMBER < 0x020b00
+#if HAVE_THREADS && GNUTLS_VERSION_NUMBER < 0x020b00
     if (gcry_control(GCRYCTL_ANY_INITIALIZATION_P) == 0)
         gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
 #endif
@@ -104,7 +104,7 @@
 #if CONFIG_OPENSSL
     openssl_init--;
     if (!openssl_init) {
-#if THREADS
+#if HAVE_THREADS
         if (CRYPTO_get_locking_callback() == openssl_lock) {
             int i;
             CRYPTO_set_locking_callback(NULL);
@@ -150,6 +150,26 @@
     return ret < 0 ? ff_neterrno() : p.revents & (ev | POLLERR | POLLHUP) ? 0 : AVERROR(EAGAIN);
 }
 
+int ff_network_wait_fd_timeout(int fd, int write, int64_t timeout, AVIOInterruptCB *int_cb)
+{
+    int ret;
+    int64_t wait_start = 0;
+
+    while (1) {
+        ret = ff_network_wait_fd(fd, write);
+        if (ret != AVERROR(EAGAIN))
+            return ret;
+        if (ff_check_interrupt(int_cb))
+            return AVERROR_EXIT;
+        if (timeout) {
+            if (!wait_start)
+                wait_start = av_gettime();
+            else if (av_gettime() - wait_start > timeout)
+                return AVERROR(ETIMEDOUT);
+        }
+    }
+}
+
 void ff_network_close(void)
 {
 #if HAVE_WINSOCK2_H
diff --git a/libavformat/network.h b/libavformat/network.h
index cce188f..f8b4dee 100644
--- a/libavformat/network.h
+++ b/libavformat/network.h
@@ -22,10 +22,12 @@
 #define AVFORMAT_NETWORK_H
 
 #include <errno.h>
+#include <stdint.h>
 
 #include "config.h"
 #include "libavutil/error.h"
 #include "os_support.h"
+#include "avio.h"
 
 #if HAVE_UNISTD_H
 #include <unistd.h>
@@ -80,6 +82,18 @@
 
 int ff_network_wait_fd(int fd, int write);
 
+/**
+ * This works similarly to ff_network_wait_fd, but waits up to 'timeout' microseconds
+ * Uses ff_network_wait_fd in a loop
+ *
+ * @fd Socket descriptor
+ * @write Set 1 to wait for socket able to be read, 0 to be written
+ * @timeout Timeout interval, in microseconds. Actual precision is 100000 mcs, due to ff_network_wait_fd usage
+ * @param int_cb Interrupt callback, is checked after each ff_network_wait_fd call
+ * @return 0 if data can be read/written, AVERROR(ETIMEDOUT) if timeout expired, or negative error code
+ */
+int ff_network_wait_fd_timeout(int fd, int write, int64_t timeout, AVIOInterruptCB *int_cb);
+
 int ff_inet_aton (const char * str, struct in_addr * add);
 
 #if !HAVE_STRUCT_SOCKADDR_STORAGE
@@ -187,6 +201,14 @@
 #define gai_strerror ff_gai_strerror
 #endif
 
+#ifndef INADDR_LOOPBACK
+#define INADDR_LOOPBACK 0x7f000001
+#endif
+
+#ifndef INET_ADDRSTRLEN
+#define INET_ADDRSTRLEN 16
+#endif
+
 #ifndef INET6_ADDRSTRLEN
 #define INET6_ADDRSTRLEN INET_ADDRSTRLEN
 #endif
diff --git a/libavformat/nsvdec.c b/libavformat/nsvdec.c
index e64fffb..b6984a6 100644
--- a/libavformat/nsvdec.c
+++ b/libavformat/nsvdec.c
@@ -23,7 +23,6 @@
 #include "libavutil/mathematics.h"
 #include "avformat.h"
 #include "internal.h"
-#include "riff.h"
 #include "libavutil/dict.h"
 #include "libavutil/intreadwrite.h"
 
@@ -653,7 +652,10 @@
                 if (bps != 16) {
                     av_dlog(s, "NSV AUDIO bit/sample != 16 (%d)!!!\n", bps);
                 }
-                bps /= channels; // ???
+                if(channels)
+                    bps /= channels; // ???
+                else
+                    av_log(s, AV_LOG_WARNING, "Channels is 0\n");
                 if (bps == 8)
                     st[NSV_ST_AUDIO]->codec->codec_id = AV_CODEC_ID_PCM_U8;
                 samplerate /= 4;/* UGH ??? XXX */
diff --git a/libavformat/nut.c b/libavformat/nut.c
index 30c0eb6..62a650d 100644
--- a/libavformat/nut.c
+++ b/libavformat/nut.c
@@ -22,6 +22,7 @@
 #include "libavutil/mathematics.h"
 #include "libavutil/tree.h"
 #include "nut.h"
+#include "riff.h"
 #include "internal.h"
 
 const AVCodecTag ff_nut_subtitle_tags[] = {
@@ -33,6 +34,11 @@
     { AV_CODEC_ID_NONE        , 0                         }
 };
 
+const AVCodecTag ff_nut_data_tags[] = {
+    { AV_CODEC_ID_TEXT        , MKTAG('U', 'T', 'F', '8') },
+    { AV_CODEC_ID_NONE        , 0                         }
+};
+
 const AVCodecTag ff_nut_video_tags[] = {
     { AV_CODEC_ID_RAWVIDEO, MKTAG('R', 'G', 'B', 15 ) },
     { AV_CODEC_ID_RAWVIDEO, MKTAG('B', 'G', 'R', 15 ) },
@@ -109,9 +115,76 @@
     { AV_CODEC_ID_RAWVIDEO, MKTAG('Y', '4', 10 ,  8 ) },
     { AV_CODEC_ID_RAWVIDEO, MKTAG('Y', '4',  0 ,  8 ) },
     { AV_CODEC_ID_RAWVIDEO, MKTAG('Y', '2',  0 ,  8 ) },
+
+    { AV_CODEC_ID_RAWVIDEO, MKTAG('Y', '1',  0 ,  9 ) },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG( 9 ,  0 , '1', 'Y') },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG('Y', '4', 11 ,  9 ) },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG( 9 , 11 , '4', 'Y') },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG('Y', '4', 10 ,  9 ) },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG( 9 , 10 , '4', 'Y') },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG('Y', '4',  0 ,  9 ) },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG( 9 ,  0 , '4', 'Y') },
+
+    { AV_CODEC_ID_RAWVIDEO, MKTAG('Y', '1',  0 , 10 ) },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG(10 ,  0 , '1', 'Y') },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG('Y', '4', 11 , 10 ) },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG(10 , 11 , '4', 'Y') },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG('Y', '4', 10 , 10 ) },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG(10 , 10 , '4', 'Y') },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG('Y', '4',  0 , 10 ) },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG(10 ,  0 , '4', 'Y') },
+
+    { AV_CODEC_ID_RAWVIDEO, MKTAG('Y', '1',  0 , 16 ) },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG(16 ,  0 , '1', 'Y') },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG('Y', '4', 11 , 16 ) },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG(16 , 11 , '4', 'Y') },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG('Y', '4', 10 , 16 ) },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG(16 , 10 , '4', 'Y') },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG('Y', '4',  0 , 16 ) },
+    { AV_CODEC_ID_RAWVIDEO, MKTAG(16 ,  0 , '4', 'Y') },
+
     { AV_CODEC_ID_NONE    , 0                         }
 };
 
+static const AVCodecTag nut_audio_extra_tags[] = {
+    { AV_CODEC_ID_PCM_ALAW,         MKTAG('A', 'L', 'A', 'W') },
+    { AV_CODEC_ID_PCM_MULAW,        MKTAG('U', 'L', 'A', 'W') },
+    { AV_CODEC_ID_MP3,              MKTAG('M', 'P', '3', ' ') },
+    { AV_CODEC_ID_NONE,             0                         }
+};
+
+const AVCodecTag ff_nut_audio_tags[] = {
+    { AV_CODEC_ID_PCM_F32BE,        MKTAG(32 , 'D', 'F', 'P') },
+    { AV_CODEC_ID_PCM_F32LE,        MKTAG('P', 'F', 'D', 32 ) },
+    { AV_CODEC_ID_PCM_F64BE,        MKTAG(64 , 'D', 'F', 'P') },
+    { AV_CODEC_ID_PCM_F64LE,        MKTAG('P', 'F', 'D', 64 ) },
+    { AV_CODEC_ID_PCM_S16BE,        MKTAG(16 , 'D', 'S', 'P') },
+    { AV_CODEC_ID_PCM_S16LE,        MKTAG('P', 'S', 'D', 16 ) },
+    { AV_CODEC_ID_PCM_S24BE,        MKTAG(24 , 'D', 'S', 'P') },
+    { AV_CODEC_ID_PCM_S24LE,        MKTAG('P', 'S', 'D', 24 ) },
+    { AV_CODEC_ID_PCM_S32BE,        MKTAG(32 , 'D', 'S', 'P') },
+    { AV_CODEC_ID_PCM_S32LE,        MKTAG('P', 'S', 'D', 32 ) },
+    { AV_CODEC_ID_PCM_S8,           MKTAG('P', 'S', 'D',  8 ) },
+    { AV_CODEC_ID_PCM_U16BE,        MKTAG(16 , 'D', 'U', 'P') },
+    { AV_CODEC_ID_PCM_U16LE,        MKTAG('P', 'U', 'D', 16 ) },
+    { AV_CODEC_ID_PCM_U24BE,        MKTAG(24 , 'D', 'U', 'P') },
+    { AV_CODEC_ID_PCM_U24LE,        MKTAG('P', 'U', 'D', 24 ) },
+    { AV_CODEC_ID_PCM_U32BE,        MKTAG(32 , 'D', 'U', 'P') },
+    { AV_CODEC_ID_PCM_U32LE,        MKTAG('P', 'U', 'D', 32 ) },
+    { AV_CODEC_ID_PCM_U8,           MKTAG('P', 'U', 'D',  8 ) },
+    { AV_CODEC_ID_PCM_S8_PLANAR,    MKTAG('P', 'S', 'P',  8 ) },
+    { AV_CODEC_ID_PCM_S16BE_PLANAR, MKTAG(16 , 'P', 'S', 'P') },
+    { AV_CODEC_ID_PCM_S16LE_PLANAR, MKTAG('P', 'S', 'P', 16 ) },
+    { AV_CODEC_ID_PCM_S24LE_PLANAR, MKTAG('P', 'S', 'P', 24 ) },
+    { AV_CODEC_ID_PCM_S32LE_PLANAR, MKTAG('P', 'S', 'P', 32 ) },
+    { AV_CODEC_ID_NONE,             0                         }
+};
+
+const AVCodecTag * const ff_nut_codec_tags[] = {
+    ff_nut_video_tags, ff_nut_audio_tags, ff_nut_subtitle_tags,
+    ff_codec_bmp_tags, ff_codec_wav_tags, nut_audio_extra_tags, ff_nut_data_tags, 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++){
@@ -124,7 +197,7 @@
 }
 
 int64_t ff_lsb2full(StreamContext *stream, int64_t lsb){
-    int64_t mask = (1<<stream->msb_pts_shift)-1;
+    int64_t mask = (1ULL<<stream->msb_pts_shift)-1;
     int64_t delta= stream->last_pts - mask/2;
     return  ((lsb - delta)&mask) + delta;
 }
@@ -139,7 +212,7 @@
 
 void ff_nut_add_sp(NUTContext *nut, int64_t pos, int64_t back_ptr, int64_t ts){
     Syncpoint *sp= av_mallocz(sizeof(Syncpoint));
-    struct AVTreeNode *node= av_mallocz(av_tree_node_size);
+    struct AVTreeNode *node = av_tree_node_alloc();
 
     nut->sp_count++;
 
diff --git a/libavformat/nut.h b/libavformat/nut.h
index 39743db..ab31c27 100644
--- a/libavformat/nut.h
+++ b/libavformat/nut.h
@@ -26,7 +26,7 @@
 //#include "libavutil/adler32.h"
 //#include "libavcodec/mpegaudio.h"
 #include "avformat.h"
-#include "riff.h"
+#include "internal.h"
 #include "metadata.h"
 
 #define      MAIN_STARTCODE (0x7A561F5F04ADULL + (((uint64_t)('N'<<8) + 'M')<<48))
@@ -53,14 +53,14 @@
     FLAG_INVALID    =8192, ///<if set, frame_code is invalid
 } Flag;
 
-typedef struct {
+typedef struct Syncpoint {
     uint64_t pos;
     uint64_t back_ptr;
 //    uint64_t global_key_pts;
     int64_t ts;
 } Syncpoint;
 
-typedef struct {
+typedef struct FrameCode {
     uint16_t flags;
     uint8_t  stream_id;
     uint16_t size_mul;
@@ -70,7 +70,7 @@
     uint8_t  header_idx;
 } FrameCode;
 
-typedef struct {
+typedef struct StreamContext {
     int last_flags;
     int skip_until_key_frame;
     int64_t last_pts;
@@ -82,11 +82,11 @@
     int64_t *keyframe_pts;
 } StreamContext;
 
-typedef struct {
+typedef struct ChapterContext {
     AVRational *time_base;
 } ChapterContext;
 
-typedef struct {
+typedef struct NUTContext {
     AVFormatContext *avf;
 //    int written_packet_size;
 //    int64_t packet_start;
@@ -109,8 +109,12 @@
 
 extern const AVCodecTag ff_nut_subtitle_tags[];
 extern const AVCodecTag ff_nut_video_tags[];
+extern const AVCodecTag ff_nut_audio_tags[];
+extern const AVCodecTag ff_nut_data_tags[];
 
-typedef struct {
+extern const AVCodecTag * const ff_nut_codec_tags[];
+
+typedef struct Dispositions {
     char str[9];
     int flag;
 } Dispositions;
diff --git a/libavformat/nutdec.c b/libavformat/nutdec.c
index d6732b2..ac3ef7d 100644
--- a/libavformat/nutdec.c
+++ b/libavformat/nutdec.c
@@ -28,6 +28,7 @@
 #include "libavutil/tree.h"
 #include "avio_internal.h"
 #include "nut.h"
+#include "riff.h"
 
 #define NUT_MAX_STREAMS 256    /* arbitrary sanity check value */
 
@@ -188,13 +189,15 @@
     return 0;
 }
 
-#define GET_V(dst, check)                                                 \
-    tmp = ffio_read_varlen(bc);                                           \
-    if (!(check)) {                                                       \
-        av_log(s, AV_LOG_ERROR, "Error " #dst " is (%"PRId64")\n", tmp);  \
-        return -1;                                                        \
-    }                                                                     \
-    dst = tmp;
+#define GET_V(dst, check)                                                     \
+    do {                                                                      \
+        tmp = ffio_read_varlen(bc);                                           \
+        if (!(check)) {                                                       \
+            av_log(s, AV_LOG_ERROR, "Error " #dst " is (%"PRId64")\n", tmp);  \
+            return -1;                                                        \
+        }                                                                     \
+        dst = tmp;                                                            \
+    } while (0)
 
 static int skip_reserved(AVIOContext *bc, int64_t pos)
 {
@@ -221,8 +224,8 @@
     end  = get_packetheader(nut, bc, 1, MAIN_STARTCODE);
     end += avio_tell(bc);
 
-    GET_V(tmp, tmp >= 2 && tmp <= 3)
-    GET_V(stream_count, tmp > 0 && tmp <= NUT_MAX_STREAMS)
+    GET_V(tmp, tmp >= 2 && tmp <= 3);
+    GET_V(stream_count, tmp > 0 && tmp <= NUT_MAX_STREAMS);
 
     nut->max_distance = ffio_read_varlen(bc);
     if (nut->max_distance > 65536) {
@@ -230,12 +233,12 @@
         nut->max_distance = 65536;
     }
 
-    GET_V(nut->time_base_count, tmp > 0 && tmp < INT_MAX / sizeof(AVRational))
+    GET_V(nut->time_base_count, tmp > 0 && tmp < INT_MAX / sizeof(AVRational));
     nut->time_base = av_malloc(nut->time_base_count * sizeof(AVRational));
 
     for (i = 0; i < nut->time_base_count; i++) {
-        GET_V(nut->time_base[i].num, tmp > 0 && tmp < (1ULL << 31))
-        GET_V(nut->time_base[i].den, tmp > 0 && tmp < (1ULL << 31))
+        GET_V(nut->time_base[i].num, tmp > 0 && tmp < (1ULL << 31));
+        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 AVERROR_INVALIDDATA;
@@ -303,7 +306,7 @@
 
     if (end > avio_tell(bc) + 4) {
         int rem = 1024;
-        GET_V(nut->header_count, tmp < 128U)
+        GET_V(nut->header_count, tmp < 128U);
         nut->header_count++;
         for (i = 1; i < nut->header_count; i++) {
             uint8_t *hdr;
@@ -359,15 +362,20 @@
     case 0:
         st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
         st->codec->codec_id   = av_codec_get_id((const AVCodecTag * const []) {
-                                                    ff_codec_bmp_tags,
                                                     ff_nut_video_tags,
+                                                    ff_codec_bmp_tags,
                                                     0
                                                 },
                                                 tmp);
         break;
     case 1:
         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
-        st->codec->codec_id   = ff_codec_get_id(ff_codec_wav_tags, tmp);
+        st->codec->codec_id   = av_codec_get_id((const AVCodecTag * const []) {
+                                                    ff_nut_audio_tags,
+                                                    ff_codec_wav_tags,
+                                                    0
+                                                },
+                                                tmp);
         break;
     case 2:
         st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
@@ -375,6 +383,7 @@
         break;
     case 3:
         st->codec->codec_type = AVMEDIA_TYPE_DATA;
+        st->codec->codec_id   = ff_codec_get_id(ff_nut_data_tags, tmp);
         break;
     default:
         av_log(s, AV_LOG_ERROR, "unknown stream class (%d)\n", class);
@@ -400,8 +409,8 @@
     }
 
     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
-        GET_V(st->codec->width,  tmp > 0)
-        GET_V(st->codec->height, tmp > 0)
+        GET_V(st->codec->width,  tmp > 0);
+        GET_V(st->codec->height, tmp > 0);
         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)) {
@@ -411,9 +420,9 @@
         }
         ffio_read_varlen(bc); /* csp type */
     } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
-        GET_V(st->codec->sample_rate, tmp > 0)
+        GET_V(st->codec->sample_rate, tmp > 0);
         ffio_read_varlen(bc); // samplerate_den
-        GET_V(st->codec->channels, tmp > 0)
+        GET_V(st->codec->channels, tmp > 0);
     }
     if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
         av_log(s, AV_LOG_ERROR,
@@ -458,7 +467,7 @@
     end  = get_packetheader(nut, bc, 1, INFO_STARTCODE);
     end += avio_tell(bc);
 
-    GET_V(stream_id_plus1, tmp <= s->nb_streams)
+    GET_V(stream_id_plus1, tmp <= s->nb_streams);
     chapter_id    = get_s(bc);
     chapter_start = ffio_read_varlen(bc);
     chapter_len   = ffio_read_varlen(bc);
@@ -510,6 +519,12 @@
                 set_disposition_bits(s, str_value, stream_id_plus1 - 1);
                 continue;
             }
+
+            if (stream_id_plus1 && !strcmp(name, "r_frame_rate")) {
+                sscanf(str_value, "%d/%d", &st->r_frame_rate.num, &st->r_frame_rate.den);
+                continue;
+            }
+
             if (metadata && av_strcasecmp(name, "Uses") &&
                 av_strcasecmp(name, "Depends") && av_strcasecmp(name, "Replaces"))
                 av_dict_set(metadata, name, str_value, 0);
@@ -602,7 +617,7 @@
     end += avio_tell(bc);
 
     ffio_read_varlen(bc); // max_pts
-    GET_V(syncpoint_count, tmp < INT_MAX / 8 && tmp > 0)
+    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++) {
@@ -767,7 +782,7 @@
     if (flags & FLAG_CODED)
         flags ^= ffio_read_varlen(bc);
     if (flags & FLAG_STREAM_ID) {
-        GET_V(*stream_id, tmp < s->nb_streams)
+        GET_V(*stream_id, tmp < s->nb_streams);
     }
     stc = &nut->stream[*stream_id];
     if (flags & FLAG_CODED_PTS) {
@@ -776,7 +791,7 @@
         if (coded_pts < (1 << stc->msb_pts_shift)) {
             *pts = ff_lsb2full(stc, coded_pts);
         } else
-            *pts = coded_pts - (1 << stc->msb_pts_shift);
+            *pts = coded_pts - (1LL << stc->msb_pts_shift);
     } else
         *pts = stc->last_pts + pts_delta;
     if (flags & FLAG_SIZE_MSB)
@@ -841,7 +856,8 @@
         return 1;
     }
 
-    av_new_packet(pkt, size + nut->header_len[header_idx]);
+    if (av_new_packet(pkt, size + nut->header_len[header_idx]) < 0)
+        return AVERROR(ENOMEM);
     memcpy(pkt->data, nut->header[header_idx], nut->header_len[header_idx]);
     pkt->pos = avio_tell(bc); // FIXME
     avio_read(bc, pkt->data + nut->header_len[header_idx], size);
@@ -1026,8 +1042,5 @@
     .read_close     = nut_read_close,
     .read_seek      = read_seek,
     .extensions     = "nut",
-    .codec_tag      = (const AVCodecTag * const []) {
-        ff_codec_bmp_tags, ff_nut_video_tags, ff_codec_wav_tags,
-        ff_nut_subtitle_tags, 0
-    },
+    .codec_tag      = ff_nut_codec_tags,
 };
diff --git a/libavformat/nutenc.c b/libavformat/nutenc.c
index f719c8e..4671152 100644
--- a/libavformat/nutenc.c
+++ b/libavformat/nutenc.c
@@ -28,60 +28,67 @@
 #include "nut.h"
 #include "internal.h"
 #include "avio_internal.h"
+#include "riff.h"
 
-static int find_expected_header(AVCodecContext *c, int size, int key_frame, uint8_t out[64]){
-    int sample_rate= c->sample_rate;
+static int find_expected_header(AVCodecContext *c, int size, int key_frame,
+                                uint8_t out[64])
+{
+    int sample_rate = c->sample_rate;
 
-    if(size>4096)
+    if (size > 4096)
         return 0;
 
     AV_WB24(out, 1);
 
-    if(c->codec_id == AV_CODEC_ID_MPEG4){
-        if(key_frame){
+    if (c->codec_id == AV_CODEC_ID_MPEG4) {
+        if (key_frame) {
             return 3;
-        }else{
-            out[3]= 0xB6;
+        } else {
+            out[3] = 0xB6;
             return 4;
         }
-    }else if(c->codec_id == AV_CODEC_ID_MPEG1VIDEO || c->codec_id == AV_CODEC_ID_MPEG2VIDEO){
+    } else if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO ||
+               c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
         return 3;
-    }else if(c->codec_id == AV_CODEC_ID_H264){
+    } else if (c->codec_id == AV_CODEC_ID_H264) {
         return 3;
-    }else if(c->codec_id == AV_CODEC_ID_MP3 || c->codec_id == AV_CODEC_ID_MP2){
+    } else if (c->codec_id == AV_CODEC_ID_MP3 ||
+               c->codec_id == AV_CODEC_ID_MP2) {
         int lsf, mpeg25, sample_rate_index, bitrate_index, frame_size;
-        int layer= c->codec_id == AV_CODEC_ID_MP3 ? 3 : 2;
-        unsigned int header= 0xFFF00000;
+        int layer           = c->codec_id == AV_CODEC_ID_MP3 ? 3 : 2;
+        unsigned int header = 0xFFF00000;
 
-        lsf     = sample_rate < (24000+32000)/2;
-        mpeg25  = sample_rate < (12000+16000)/2;
+        lsf           = sample_rate < (24000 + 32000) / 2;
+        mpeg25        = sample_rate < (12000 + 16000) / 2;
         sample_rate <<= lsf + mpeg25;
-        if     (sample_rate < (32000 + 44100)/2) sample_rate_index=2;
-        else if(sample_rate < (44100 + 48000)/2) sample_rate_index=0;
-        else                                     sample_rate_index=1;
+        if      (sample_rate < (32000 + 44100) / 2) sample_rate_index = 2;
+        else if (sample_rate < (44100 + 48000) / 2) sample_rate_index = 0;
+        else                                        sample_rate_index = 1;
 
-        sample_rate= avpriv_mpa_freq_tab[sample_rate_index] >> (lsf + mpeg25);
+        sample_rate = avpriv_mpa_freq_tab[sample_rate_index] >> (lsf + mpeg25);
 
-        for(bitrate_index=2; bitrate_index<30; bitrate_index++){
-            frame_size = avpriv_mpa_bitrate_tab[lsf][layer-1][bitrate_index>>1];
-            frame_size = (frame_size * 144000) / (sample_rate << lsf) + (bitrate_index&1);
+        for (bitrate_index = 2; bitrate_index < 30; bitrate_index++) {
+            frame_size =
+                avpriv_mpa_bitrate_tab[lsf][layer - 1][bitrate_index >> 1];
+            frame_size = (frame_size * 144000) / (sample_rate << lsf) +
+                (bitrate_index & 1);
 
-            if(frame_size == size)
+            if (frame_size == size)
                 break;
         }
 
-        header |= (!lsf)<<19;
-        header |= (4-layer)<<17;
-        header |= 1<<16; //no crc
+        header |= (!lsf) << 19;
+        header |= (4 - layer) << 17;
+        header |= 1 << 16; //no crc
         AV_WB32(out, header);
-        if(size <= 0)
-            return 2; //we guess there is no crc, if there is one the user clearly does not care about overhead
-        if(bitrate_index == 30)
-            return -1; //something is wrong ...
+        if (size <= 0)
+            return 2;  //we guess there is no crc, if there is one the user clearly does not care about overhead
+        if (bitrate_index == 30)
+            return -1;  //something is wrong ...
 
-        header |= (bitrate_index>>1)<<12;
-        header |= sample_rate_index<<10;
-        header |= (bitrate_index&1)<<9;
+        header |= (bitrate_index >> 1) << 12;
+        header |= sample_rate_index << 10;
+        header |= (bitrate_index & 1) << 9;
 
         return 2; //FIXME actually put the needed ones in build_elision_headers()
         return 3; //we guess that the private bit is not set
@@ -90,175 +97,193 @@
     return 0;
 }
 
-static int find_header_idx(AVFormatContext *s, AVCodecContext *c, int size, int frame_type){
+static int find_header_idx(AVFormatContext *s, AVCodecContext *c, int size, int frame_type)
+{
     NUTContext *nut = s->priv_data;
     uint8_t out[64];
     int i;
-    int len= find_expected_header(c, size, frame_type, out);
+    int len = find_expected_header(c, size, frame_type, out);
 
-    for(i=1; i<nut->header_count; i++){
-        if(   len == nut->header_len[i]
-           && !memcmp(out, nut->header[i], len)){
+    for (i = 1; i < nut->header_count; i++) {
+        if (len == nut->header_len[i] && !memcmp(out, nut->header[i], len)) {
             return i;
         }
     }
+
     return 0;
 }
 
-static void build_elision_headers(AVFormatContext *s){
+static void build_elision_headers(AVFormatContext *s)
+{
     NUTContext *nut = s->priv_data;
     int i;
     //FIXME this is lame
     //FIXME write a 2pass mode to find the maximal headers
-    static const uint8_t headers[][5]={
-        {3, 0x00, 0x00, 0x01},
-        {4, 0x00, 0x00, 0x01, 0xB6},
-        {2, 0xFF, 0xFA}, //mp3+crc
-        {2, 0xFF, 0xFB}, //mp3
-        {2, 0xFF, 0xFC}, //mp2+crc
-        {2, 0xFF, 0xFD}, //mp2
+    static const uint8_t headers[][5] = {
+        { 3, 0x00, 0x00, 0x01 },
+        { 4, 0x00, 0x00, 0x01, 0xB6},
+        { 2, 0xFF, 0xFA }, //mp3+crc
+        { 2, 0xFF, 0xFB }, //mp3
+        { 2, 0xFF, 0xFC }, //mp2+crc
+        { 2, 0xFF, 0xFD }, //mp2
     };
 
-    nut->header_count= 7;
-    for(i=1; i<nut->header_count; i++){
-        nut->header_len[i]=  headers[i-1][0];
-        nut->header    [i]= &headers[i-1][1];
+    nut->header_count = 7;
+    for (i = 1; i < nut->header_count; i++) {
+        nut->header_len[i] = headers[i - 1][0];
+        nut->header[i]     = &headers[i - 1][1];
     }
 }
 
-static void build_frame_code(AVFormatContext *s){
+static void build_frame_code(AVFormatContext *s)
+{
     NUTContext *nut = s->priv_data;
     int key_frame, index, pred, stream_id;
-    int start=1;
-    int end= 254;
-    int keyframe_0_esc= s->nb_streams > 2;
+    int start = 1;
+    int end   = 254;
+    int keyframe_0_esc = s->nb_streams > 2;
     int pred_table[10];
     FrameCode *ft;
 
-    ft= &nut->frame_code[start];
-    ft->flags= FLAG_CODED;
-    ft->size_mul=1;
-    ft->pts_delta=1;
+    ft            = &nut->frame_code[start];
+    ft->flags     = FLAG_CODED;
+    ft->size_mul  = 1;
+    ft->pts_delta = 1;
     start++;
 
-    if(keyframe_0_esc){
+    if (keyframe_0_esc) {
         /* keyframe = 0 escape */
-        FrameCode *ft= &nut->frame_code[start];
-        ft->flags= FLAG_STREAM_ID | FLAG_SIZE_MSB | FLAG_CODED_PTS;
-        ft->size_mul=1;
+        FrameCode *ft = &nut->frame_code[start];
+        ft->flags    = FLAG_STREAM_ID | FLAG_SIZE_MSB | FLAG_CODED_PTS;
+        ft->size_mul = 1;
         start++;
     }
 
-    for(stream_id= 0; stream_id<s->nb_streams; stream_id++){
-        int start2= start + (end-start)*stream_id / s->nb_streams;
-        int end2  = start + (end-start)*(stream_id+1) / s->nb_streams;
+    for (stream_id = 0; stream_id < s->nb_streams; stream_id++) {
+        int start2 = start + (end - start) * stream_id       / s->nb_streams;
+        int end2   = start + (end - start) * (stream_id + 1) / s->nb_streams;
         AVCodecContext *codec = s->streams[stream_id]->codec;
-        int is_audio= codec->codec_type == AVMEDIA_TYPE_AUDIO;
-        int intra_only= /*codec->intra_only || */is_audio;
+        int is_audio          = codec->codec_type == AVMEDIA_TYPE_AUDIO;
+        int intra_only        = /*codec->intra_only || */ is_audio;
         int pred_count;
+        int frame_size = 0;
 
-        for(key_frame=0; key_frame<2; key_frame++){
-            if(intra_only && keyframe_0_esc && key_frame==0)
-                continue;
+        if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
+            frame_size = av_get_audio_frame_duration(codec, 0);
+            if (codec->codec_id == AV_CODEC_ID_VORBIS && !frame_size)
+                frame_size = 64;
+        } else {
+            AVRational f = av_div_q(codec->time_base, *nut->stream[stream_id].time_base);
+            if (f.den == 1 && f.num>0)
+                frame_size = f.num;
+        }
+        if (!frame_size)
+            frame_size = 1;
 
-            {
-                FrameCode *ft= &nut->frame_code[start2];
-                ft->flags= FLAG_KEY*key_frame;
-                ft->flags|= FLAG_SIZE_MSB | FLAG_CODED_PTS;
-                ft->stream_id= stream_id;
-                ft->size_mul=1;
-                if(is_audio)
-                    ft->header_idx= find_header_idx(s, codec, -1, key_frame);
+        for (key_frame = 0; key_frame < 2; key_frame++) {
+            if (!intra_only || !keyframe_0_esc || key_frame != 0) {
+                FrameCode *ft = &nut->frame_code[start2];
+                ft->flags     = FLAG_KEY * key_frame;
+                ft->flags    |= FLAG_SIZE_MSB | FLAG_CODED_PTS;
+                ft->stream_id = stream_id;
+                ft->size_mul  = 1;
+                if (is_audio)
+                    ft->header_idx = find_header_idx(s, codec, -1, key_frame);
                 start2++;
             }
         }
 
-        key_frame= intra_only;
+        key_frame = intra_only;
 #if 1
-        if(is_audio){
-            int frame_bytes= codec->frame_size*(int64_t)codec->bit_rate / (8*codec->sample_rate);
+        if (is_audio) {
+            int frame_bytes = codec->frame_size * (int64_t)codec->bit_rate /
+                              (8 * codec->sample_rate);
             int pts;
-            for(pts=0; pts<2; pts++){
-                for(pred=0; pred<2; pred++){
-                    FrameCode *ft= &nut->frame_code[start2];
-                    ft->flags= FLAG_KEY*key_frame;
-                    ft->stream_id= stream_id;
-                    ft->size_mul=frame_bytes + 2;
-                    ft->size_lsb=frame_bytes + pred;
-                    ft->pts_delta=pts;
-                    ft->header_idx= find_header_idx(s, codec, frame_bytes + pred, key_frame);
+            for (pts = 0; pts < 2; pts++) {
+                for (pred = 0; pred < 2; pred++) {
+                    FrameCode *ft  = &nut->frame_code[start2];
+                    ft->flags      = FLAG_KEY * key_frame;
+                    ft->stream_id  = stream_id;
+                    ft->size_mul   = frame_bytes + 2;
+                    ft->size_lsb   = frame_bytes + pred;
+                    ft->pts_delta  = pts * frame_size;
+                    ft->header_idx = find_header_idx(s, codec, frame_bytes + pred, key_frame);
                     start2++;
                 }
             }
-        }else{
-            FrameCode *ft= &nut->frame_code[start2];
-            ft->flags= FLAG_KEY | FLAG_SIZE_MSB;
-            ft->stream_id= stream_id;
-            ft->size_mul=1;
-            ft->pts_delta=1;
+        } else {
+            FrameCode *ft = &nut->frame_code[start2];
+            ft->flags     = FLAG_KEY | FLAG_SIZE_MSB;
+            ft->stream_id = stream_id;
+            ft->size_mul  = 1;
+            ft->pts_delta = frame_size;
             start2++;
         }
 #endif
 
-        if(codec->has_b_frames){
-            pred_count=5;
-            pred_table[0]=-2;
-            pred_table[1]=-1;
-            pred_table[2]=1;
-            pred_table[3]=3;
-            pred_table[4]=4;
-        }else if(codec->codec_id == AV_CODEC_ID_VORBIS){
-            pred_count=3;
-            pred_table[0]=2;
-            pred_table[1]=9;
-            pred_table[2]=16;
-        }else{
-            pred_count=1;
-            pred_table[0]=1;
+        if (codec->has_b_frames) {
+            pred_count    = 5;
+            pred_table[0] = -2;
+            pred_table[1] = -1;
+            pred_table[2] = 1;
+            pred_table[3] = 3;
+            pred_table[4] = 4;
+        } else if (codec->codec_id == AV_CODEC_ID_VORBIS) {
+            pred_count    = 3;
+            pred_table[0] = 2;
+            pred_table[1] = 9;
+            pred_table[2] = 16;
+        } else {
+            pred_count    = 1;
+            pred_table[0] = 1;
         }
 
-        for(pred=0; pred<pred_count; pred++){
-            int start3= start2 + (end2-start2)*pred / pred_count;
-            int end3  = start2 + (end2-start2)*(pred+1) / pred_count;
+        for (pred = 0; pred < pred_count; pred++) {
+            int start3 = start2 + (end2 - start2) * pred / pred_count;
+            int end3   = start2 + (end2 - start2) * (pred + 1) / pred_count;
 
-            for(index=start3; index<end3; index++){
-                FrameCode *ft= &nut->frame_code[index];
-                ft->flags= FLAG_KEY*key_frame;
-                ft->flags|= FLAG_SIZE_MSB;
-                ft->stream_id= stream_id;
+            pred_table[pred] *= frame_size;
+
+            for (index = start3; index < end3; index++) {
+                FrameCode *ft = &nut->frame_code[index];
+                ft->flags     = FLAG_KEY * key_frame;
+                ft->flags    |= FLAG_SIZE_MSB;
+                ft->stream_id = stream_id;
 //FIXME use single byte size and pred from last
-                ft->size_mul= end3-start3;
-                ft->size_lsb= index - start3;
-                ft->pts_delta= pred_table[pred];
-                if(is_audio)
-                    ft->header_idx= find_header_idx(s, codec, -1, key_frame);
+                ft->size_mul  = end3 - start3;
+                ft->size_lsb  = index - start3;
+                ft->pts_delta = pred_table[pred];
+                if (is_audio)
+                    ft->header_idx = find_header_idx(s, codec, -1, key_frame);
             }
         }
     }
-    memmove(&nut->frame_code['N'+1], &nut->frame_code['N'], sizeof(FrameCode)*(255-'N'));
-    nut->frame_code[  0].flags=
-    nut->frame_code[255].flags=
-    nut->frame_code['N'].flags= FLAG_INVALID;
+    memmove(&nut->frame_code['N' + 1], &nut->frame_code['N'], sizeof(FrameCode) * (255 - 'N'));
+    nut->frame_code[0].flags       =
+        nut->frame_code[255].flags =
+        nut->frame_code['N'].flags = FLAG_INVALID;
 }
 
-static void put_tt(NUTContext *nut, AVRational *time_base, AVIOContext *bc, uint64_t val){
+static void put_tt(NUTContext *nut, AVRational *time_base, AVIOContext *bc, uint64_t val)
+{
     val *= nut->time_base_count;
     val += time_base - nut->time_base;
     ff_put_v(bc, val);
 }
-
 /**
  * Store a string as vb.
  */
-static void put_str(AVIOContext *bc, const char *string){
-    int len= strlen(string);
+static void put_str(AVIOContext *bc, const char *string)
+{
+    int len = strlen(string);
 
     ff_put_v(bc, len);
     avio_write(bc, string, len);
 }
 
-static void put_s(AVIOContext *bc, int64_t val){
-    ff_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
@@ -270,8 +295,7 @@
     ff_put_v(bc, v);
 }
 
-static inline void put_s_trace(AVIOContext *bc, int64_t v, const char *file,
-                               const char *func, int line)
+static inline void put_s_trace(AVIOContext *bc, int64_t v, const char *file, const 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);
 
@@ -282,29 +306,33 @@
 #endif
 
 //FIXME remove calculate_checksum
-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= avio_close_dyn_buf(dyn_bc, &dyn_buf);
-    int forw_ptr= dyn_size + 4*calculate_checksum;
+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     = avio_close_dyn_buf(dyn_bc, &dyn_buf);
+    int forw_ptr     = dyn_size + 4 * calculate_checksum;
 
-    if(forw_ptr > 4096)
+    if (forw_ptr > 4096)
         ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
     avio_wb64(bc, startcode);
     ff_put_v(bc, forw_ptr);
-    if(forw_ptr > 4096)
+    if (forw_ptr > 4096)
         avio_wl32(bc, ffio_get_checksum(bc));
 
-    if(calculate_checksum)
+    if (calculate_checksum)
         ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
     avio_write(bc, dyn_buf, dyn_size);
-    if(calculate_checksum)
+    if (calculate_checksum)
         avio_wl32(bc, ffio_get_checksum(bc));
 
     av_free(dyn_buf);
 }
 
-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;
+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;
 
     ff_put_v(bc, 3); /* version */
@@ -312,80 +340,85 @@
     ff_put_v(bc, nut->max_distance);
     ff_put_v(bc, nut->time_base_count);
 
-    for(i=0; i<nut->time_base_count; i++){
+    for (i = 0; i < nut->time_base_count; i++) {
         ff_put_v(bc, nut->time_base[i].num);
         ff_put_v(bc, nut->time_base[i].den);
     }
 
-    tmp_pts=0;
-    tmp_mul=1;
-    tmp_stream=0;
-    tmp_match= 1-(1LL<<62);
-    tmp_head_idx= 0;
-    for(i=0; i<256;){
-        tmp_fields=0;
-        tmp_size=0;
+    tmp_pts      = 0;
+    tmp_mul      = 1;
+    tmp_stream   = 0;
+    tmp_match    = 1 - (1LL << 62);
+    tmp_head_idx = 0;
+    for (i = 0; i < 256; ) {
+        tmp_fields = 0;
+        tmp_size   = 0;
 //        tmp_res=0;
-        if(tmp_pts    != nut->frame_code[i].pts_delta) tmp_fields=1;
-        if(tmp_mul    != nut->frame_code[i].size_mul ) tmp_fields=2;
-        if(tmp_stream != nut->frame_code[i].stream_id) tmp_fields=3;
-        if(tmp_size   != nut->frame_code[i].size_lsb ) tmp_fields=4;
-//        if(tmp_res    != nut->frame_code[i].res            ) tmp_fields=5;
-        if(tmp_head_idx!=nut->frame_code[i].header_idx)tmp_fields=8;
+        if (tmp_pts      != nut->frame_code[i].pts_delta ) tmp_fields = 1;
+        if (tmp_mul      != nut->frame_code[i].size_mul  ) tmp_fields = 2;
+        if (tmp_stream   != nut->frame_code[i].stream_id ) tmp_fields = 3;
+        if (tmp_size     != nut->frame_code[i].size_lsb  ) tmp_fields = 4;
+//        if (tmp_res    != nut->frame_code[i].res            ) tmp_fields=5;
+        if (tmp_head_idx != nut->frame_code[i].header_idx) tmp_fields = 8;
 
-        tmp_pts   = nut->frame_code[i].pts_delta;
-        tmp_flags = nut->frame_code[i].flags;
-        tmp_stream= nut->frame_code[i].stream_id;
-        tmp_mul   = nut->frame_code[i].size_mul;
-        tmp_size  = nut->frame_code[i].size_lsb;
+        tmp_pts    = nut->frame_code[i].pts_delta;
+        tmp_flags  = nut->frame_code[i].flags;
+        tmp_stream = nut->frame_code[i].stream_id;
+        tmp_mul    = nut->frame_code[i].size_mul;
+        tmp_size   = nut->frame_code[i].size_lsb;
 //        tmp_res   = nut->frame_code[i].res;
-        tmp_head_idx= nut->frame_code[i].header_idx;
+        tmp_head_idx = nut->frame_code[i].header_idx;
 
-        for(j=0; i<256; j++,i++){
-            if(i == 'N'){
+        for (j = 0; i < 256; j++, i++) {
+            if (i == 'N') {
                 j--;
                 continue;
             }
-            if(nut->frame_code[i].pts_delta != tmp_pts   ) break;
-            if(nut->frame_code[i].flags     != tmp_flags ) break;
-            if(nut->frame_code[i].stream_id != tmp_stream) break;
-            if(nut->frame_code[i].size_mul  != tmp_mul   ) break;
-            if(nut->frame_code[i].size_lsb  != tmp_size+j) break;
-//            if(nut->frame_code[i].res       != tmp_res   ) break;
-            if(nut->frame_code[i].header_idx!= tmp_head_idx) break;
+            if (nut->frame_code[i].pts_delta  != tmp_pts      ||
+                nut->frame_code[i].flags      != tmp_flags    ||
+                nut->frame_code[i].stream_id  != tmp_stream   ||
+                nut->frame_code[i].size_mul   != tmp_mul      ||
+                nut->frame_code[i].size_lsb   != tmp_size + j ||
+//              nut->frame_code[i].res        != tmp_res      ||
+                nut->frame_code[i].header_idx != tmp_head_idx)
+                break;
         }
-        if(j != tmp_mul - tmp_size) tmp_fields=6;
+        if (j != tmp_mul - tmp_size)
+            tmp_fields = 6;
 
         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) 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);
+        if (tmp_fields > 0) put_s(bc, tmp_pts);
+        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);
     }
-    ff_put_v(bc, nut->header_count-1);
-    for(i=1; i<nut->header_count; i++){
+    ff_put_v(bc, nut->header_count - 1);
+    for (i = 1; i < nut->header_count; i++) {
         ff_put_v(bc, nut->header_len[i]);
         avio_write(bc, nut->header[i], nut->header_len[i]);
     }
 }
 
-static int write_streamheader(AVFormatContext *avctx, AVIOContext *bc, AVStream *st, int i){
-    NUTContext *nut = avctx->priv_data;
+static int write_streamheader(AVFormatContext *avctx, AVIOContext *bc,
+                              AVStream *st, int i)
+{
+    NUTContext *nut       = avctx->priv_data;
     AVCodecContext *codec = st->codec;
+
     ff_put_v(bc, i);
-    switch(codec->codec_type){
-    case AVMEDIA_TYPE_VIDEO: ff_put_v(bc, 0); break;
-    case AVMEDIA_TYPE_AUDIO: ff_put_v(bc, 1); break;
+    switch (codec->codec_type) {
+    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;
+    default:                    ff_put_v(bc, 3); break;
     }
     ff_put_v(bc, 4);
-    if (codec->codec_tag){
+    if (codec->codec_tag) {
         avio_wl32(bc, codec->codec_tag);
     } else {
         av_log(avctx, AV_LOG_ERROR, "No codec tag defined for stream %d\n", i);
@@ -401,7 +434,7 @@
     ff_put_v(bc, codec->extradata_size);
     avio_write(bc, codec->extradata, codec->extradata_size);
 
-    switch(codec->codec_type){
+    switch (codec->codec_type) {
     case AVMEDIA_TYPE_AUDIO:
         ff_put_v(bc, codec->sample_rate);
         ff_put_v(bc, 1);
@@ -411,10 +444,11 @@
         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){
+        if (st->sample_aspect_ratio.num <= 0 ||
+            st->sample_aspect_ratio.den <= 0) {
             ff_put_v(bc, 0);
             ff_put_v(bc, 0);
-        }else{
+        } else {
             ff_put_v(bc, st->sample_aspect_ratio.num);
             ff_put_v(bc, st->sample_aspect_ratio.den);
         }
@@ -426,21 +460,23 @@
     return 0;
 }
 
-static int add_info(AVIOContext *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, AVIOContext *bc){
-    AVFormatContext *s= nut->avf;
+static int write_globalinfo(NUTContext *nut, AVIOContext *bc)
+{
+    AVFormatContext *s   = nut->avf;
     AVDictionaryEntry *t = NULL;
     AVIOContext *dyn_bc;
-    uint8_t *dyn_buf=NULL;
-    int count=0, dyn_size;
-    int ret = avio_open_dyn_buf(&dyn_bc);
-    if(ret < 0)
+    uint8_t *dyn_buf = NULL;
+    int count        = 0, dyn_size;
+    int ret          = avio_open_dyn_buf(&dyn_bc);
+    if (ret < 0)
         return ret;
 
     while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
@@ -453,13 +489,13 @@
 
     ff_put_v(bc, count);
 
-    dyn_size= avio_close_dyn_buf(dyn_bc, &dyn_buf);
+    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, AVIOContext *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];
     AVDictionaryEntry *t = NULL;
@@ -467,7 +503,7 @@
     uint8_t *dyn_buf=NULL;
     int count=0, dyn_size, i;
     int ret = avio_open_dyn_buf(&dyn_bc);
-    if(ret < 0)
+    if (ret < 0)
         return ret;
 
     while ((t = av_dict_get(st->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
@@ -476,6 +512,11 @@
         if (st->disposition & ff_nut_dispositions[i].flag)
             count += add_info(dyn_bc, "Disposition", ff_nut_dispositions[i].str);
     }
+    if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
+        uint8_t buf[256];
+        snprintf(buf, sizeof(buf), "%d/%d", st->codec->time_base.den, st->codec->time_base.num);
+        count += add_info(dyn_bc, "r_frame_rate", buf);
+    }
     dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
 
     if (count) {
@@ -496,9 +537,9 @@
 static int write_chapter(NUTContext *nut, AVIOContext *bc, int id)
 {
     AVIOContext *dyn_bc;
-    uint8_t *dyn_buf = NULL;
+    uint8_t *dyn_buf     = NULL;
     AVDictionaryEntry *t = NULL;
-    AVChapter *ch    = nut->avf->chapters[id];
+    AVChapter *ch        = nut->avf->chapters[id];
     int ret, dyn_size, count = 0;
 
     ret = avio_open_dyn_buf(&dyn_bc);
@@ -521,7 +562,7 @@
     return 0;
 }
 
-static int write_index(NUTContext *nut, AVIOContext *bc){
+static int write_index(NUTContext *nut, AVIOContext *bc) {
     int i;
     Syncpoint dummy= { .pos= 0 };
     Syncpoint *next_node[2] = { NULL };
@@ -532,25 +573,25 @@
 
     ff_put_v(bc, nut->sp_count);
 
-    for(i=0; i<nut->sp_count; i++){
+    for (i=0; i<nut->sp_count; i++) {
         av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp, (void**)next_node);
         ff_put_v(bc, (next_node[1]->pos >> 4) - (dummy.pos>>4));
         dummy.pos = next_node[1]->pos;
     }
 
-    for(i=0; i<nut->avf->nb_streams; i++){
+    for (i=0; i<nut->avf->nb_streams; i++) {
         StreamContext *nus= &nut->stream[i];
         int64_t last_pts= -1;
         int j, k;
-        for(j=0; j<nut->sp_count; j++){
+        for (j=0; j<nut->sp_count; j++) {
             int flag = (nus->keyframe_pts[j] != AV_NOPTS_VALUE) ^ (j+1 == nut->sp_count);
             int n = 0;
-            for(; j<nut->sp_count && (nus->keyframe_pts[j] != AV_NOPTS_VALUE) == flag; j++)
+            for (; j<nut->sp_count && (nus->keyframe_pts[j] != AV_NOPTS_VALUE) == flag; j++)
                 n++;
 
             ff_put_v(bc, 1 + 2*flag + 4*n);
-            for(k= j - n; k<=j && k<nut->sp_count; k++) {
-                if(nus->keyframe_pts[k] == AV_NOPTS_VALUE)
+            for (k= j - n; k<=j && k<nut->sp_count; k++) {
+                if (nus->keyframe_pts[k] == AV_NOPTS_VALUE)
                     continue;
                 av_assert0(nus->keyframe_pts[k] > last_pts);
                 ff_put_v(bc, nus->keyframe_pts[k] - last_pts);
@@ -566,7 +607,8 @@
     return 0;
 }
 
-static int write_headers(AVFormatContext *avctx, AVIOContext *bc){
+static int write_headers(AVFormatContext *avctx, AVIOContext *bc)
+{
     NUTContext *nut = avctx->priv_data;
     AVIOContext *dyn_bc;
     int i, ret;
@@ -574,29 +616,30 @@
     ff_metadata_conv_ctx(avctx, ff_nut_metadata_conv, NULL);
 
     ret = avio_open_dyn_buf(&dyn_bc);
-    if(ret < 0)
+    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++){
+    for (i = 0; i < nut->avf->nb_streams; i++) {
         ret = avio_open_dyn_buf(&dyn_bc);
-        if(ret < 0)
+        if (ret < 0)
             return ret;
-        if ((ret = write_streamheader(avctx, dyn_bc, nut->avf->streams[i], i)) < 0)
+        ret = write_streamheader(avctx, dyn_bc, nut->avf->streams[i], i);
+        if (ret < 0)
             return ret;
         put_packet(nut, bc, dyn_bc, 1, STREAM_STARTCODE);
     }
 
     ret = avio_open_dyn_buf(&dyn_bc);
-    if(ret < 0)
+    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 = avio_open_dyn_buf(&dyn_bc);
-        if(ret < 0)
+        if (ret < 0)
             return ret;
         ret = write_streaminfo(nut, dyn_bc, i);
         if (ret < 0)
@@ -604,7 +647,7 @@
         if (ret > 0)
             put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
         else {
-            uint8_t* buf;
+            uint8_t *buf;
             avio_close_dyn_buf(dyn_bc, &buf);
             av_free(buf);
         }
@@ -624,22 +667,23 @@
         put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
     }
 
-    nut->last_syncpoint_pos= INT_MIN;
+    nut->last_syncpoint_pos = INT_MIN;
     nut->header_count++;
     return 0;
 }
 
-static int nut_write_header(AVFormatContext *s){
+static int nut_write_header(AVFormatContext *s)
+{
     NUTContext *nut = s->priv_data;
     AVIOContext *bc = s->pb;
     int i, j, ret;
 
-    nut->avf= s;
+    nut->avf = s;
 
-    nut->stream   = av_mallocz(sizeof(StreamContext)*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));
+    nut->stream   = av_mallocz(sizeof(StreamContext ) * 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));
     if (!nut->stream || !nut->chapter || !nut->time_base) {
         av_freep(&nut->stream);
         av_freep(&nut->chapter);
@@ -647,42 +691,47 @@
         return AVERROR(ENOMEM);
     }
 
-    for(i=0; i<s->nb_streams; i++){
-        AVStream *st= s->streams[i];
+    for (i = 0; i < s->nb_streams; i++) {
+        AVStream *st = s->streams[i];
         int ssize;
         AVRational time_base;
         ff_parse_specific_params(st->codec, &time_base.den, &ssize, &time_base.num);
 
+        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->sample_rate) {
+            time_base = (AVRational) {1, st->codec->sample_rate};
+        } else {
+            time_base = ff_choose_timebase(s, st, 48000);
+        }
+
         avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
 
-        for(j=0; j<nut->time_base_count; j++){
-            if(!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))){
+        for (j = 0; j < nut->time_base_count; j++)
+            if (!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))) {
                 break;
             }
-        }
-        nut->time_base[j]= time_base;
-        nut->stream[i].time_base= &nut->time_base[j];
-        if(j==nut->time_base_count)
+        nut->time_base[j]        = time_base;
+        nut->stream[i].time_base = &nut->time_base[j];
+        if (j == nut->time_base_count)
             nut->time_base_count++;
 
-        if(INT64_C(1000) * time_base.num >= time_base.den)
+        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(time_base.den, time_base.num) / time_base.num;
+        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++) {
+        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->time_base[j]         = ch->time_base;
         nut->chapter[i].time_base = &nut->time_base[j];
-        if(j == nut->time_base_count)
+        if (j == nut->time_base_count)
             nut->time_base_count++;
     }
 
@@ -705,199 +754,213 @@
     return 0;
 }
 
-static int get_needed_flags(NUTContext *nut, StreamContext *nus, FrameCode *fc, AVPacket *pkt){
-    int flags= 0;
+static int get_needed_flags(NUTContext *nut, StreamContext *nus, FrameCode *fc,
+                            AVPacket *pkt)
+{
+    int flags = 0;
 
-    if(pkt->flags & AV_PKT_FLAG_KEY             ) flags |= FLAG_KEY;
-    if(pkt->stream_index != fc->stream_id       ) flags |= FLAG_STREAM_ID;
-    if(pkt->size / fc->size_mul                 ) flags |= FLAG_SIZE_MSB;
-    if(pkt->pts - nus->last_pts != fc->pts_delta) flags |= FLAG_CODED_PTS;
-    if(pkt->size > 2*nut->max_distance          ) flags |= FLAG_CHECKSUM;
-    if(FFABS(pkt->pts - nus->last_pts)
-                         > nus->max_pts_distance) flags |= FLAG_CHECKSUM;
-    if(   pkt->size < nut->header_len[fc->header_idx]
-       || (pkt->size > 4096 && fc->header_idx)
-       || memcmp(pkt->data, nut->header[fc->header_idx], nut->header_len[fc->header_idx]))
-                                                  flags |= FLAG_HEADER_IDX;
+    if (pkt->flags & AV_PKT_FLAG_KEY)
+        flags |= FLAG_KEY;
+    if (pkt->stream_index != fc->stream_id)
+        flags |= FLAG_STREAM_ID;
+    if (pkt->size / fc->size_mul)
+        flags |= FLAG_SIZE_MSB;
+    if (pkt->pts - nus->last_pts != fc->pts_delta)
+        flags |= FLAG_CODED_PTS;
+    if (pkt->size > 2 * nut->max_distance)
+        flags |= FLAG_CHECKSUM;
+    if (FFABS(pkt->pts - nus->last_pts) > nus->max_pts_distance)
+        flags |= FLAG_CHECKSUM;
+    if (pkt->size < nut->header_len[fc->header_idx] ||
+        (pkt->size > 4096 && fc->header_idx)        ||
+        memcmp(pkt->data, nut->header[fc->header_idx],
+               nut->header_len[fc->header_idx]))
+        flags |= FLAG_HEADER_IDX;
 
     return flags | (fc->flags & FLAG_CODED);
 }
 
-static int find_best_header_idx(NUTContext *nut, AVPacket *pkt){
+static int find_best_header_idx(NUTContext *nut, AVPacket *pkt)
+{
     int i;
-    int best_i  = 0;
-    int best_len= 0;
+    int best_i   = 0;
+    int best_len = 0;
 
-    if(pkt->size > 4096)
+    if (pkt->size > 4096)
         return 0;
 
-    for(i=1; i<nut->header_count; i++){
-        if(   pkt->size >= nut->header_len[i]
-           &&  nut->header_len[i] > best_len
-           && !memcmp(pkt->data, nut->header[i], nut->header_len[i])){
-            best_i= i;
-            best_len= nut->header_len[i];
+    for (i = 1; i < nut->header_count; i++)
+        if (pkt->size >= nut->header_len[i]
+            && nut->header_len[i] > best_len
+            && !memcmp(pkt->data, nut->header[i], nut->header_len[i])) {
+            best_i   = i;
+            best_len = nut->header_len[i];
         }
-    }
     return best_i;
 }
 
-static int nut_write_packet(AVFormatContext *s, AVPacket *pkt){
-    NUTContext *nut = s->priv_data;
-    StreamContext *nus= &nut->stream[pkt->stream_index];
-    AVIOContext *bc = s->pb, *dyn_bc;
+static int nut_write_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    NUTContext *nut    = s->priv_data;
+    StreamContext *nus = &nut->stream[pkt->stream_index];
+    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;
+    int best_length, frame_code, flags, needed_flags, i, header_idx;
+    int best_header_idx;
     int key_frame = !!(pkt->flags & AV_PKT_FLAG_KEY);
-    int store_sp=0;
+    int store_sp  = 0;
     int ret;
 
     if (pkt->pts < 0) {
-        av_log(s, AV_LOG_ERROR, "Invalid negative packet pts %"PRId64" in input\n", pkt->pts);
+        av_log(s, AV_LOG_ERROR,
+               "Negative pts not supported stream %d, pts %"PRId64"\n",
+               pkt->stream_index, pkt->pts);
         return AVERROR(EINVAL);
     }
 
-    if(1LL<<(20+3*nut->header_count) <= avio_tell(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 (key_frame && !(nus->last_flags & FLAG_KEY))
+        store_sp = 1;
 
-    if(pkt->size + 30/*FIXME check*/ + avio_tell(bc) >= nut->last_syncpoint_pos + nut->max_distance)
-        store_sp= 1;
+    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.
 
-    if(store_sp){
-        Syncpoint *sp, dummy= {.pos= INT64_MAX};
+    if (store_sp) {
+        Syncpoint *sp, dummy = { .pos = INT64_MAX };
 
         ff_nut_reset_ts(nut, *nus->time_base, pkt->dts);
-        for(i=0; i<s->nb_streams; i++){
-            AVStream *st= s->streams[i];
+        for (i = 0; i < s->nb_streams; i++) {
+            AVStream *st   = s->streams[i];
             int64_t dts_tb = av_rescale_rnd(pkt->dts,
                 nus->time_base->num * (int64_t)nut->stream[i].time_base->den,
                 nus->time_base->den * (int64_t)nut->stream[i].time_base->num,
                 AV_ROUND_DOWN);
-            int index= av_index_search_timestamp(st, dts_tb, AVSEEK_FLAG_BACKWARD);
-            if(index>=0) dummy.pos= FFMIN(dummy.pos, st->index_entries[index].pos);
+            int index = av_index_search_timestamp(st, dts_tb,
+                                                  AVSEEK_FLAG_BACKWARD);
+            if (index >= 0)
+                dummy.pos = FFMIN(dummy.pos, st->index_entries[index].pos);
         }
-        if(dummy.pos == INT64_MAX)
-            dummy.pos= 0;
-        sp= av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
-                         NULL);
+        if (dummy.pos == INT64_MAX)
+            dummy.pos = 0;
+        sp = av_tree_find(nut->syncpoints, &dummy, (void *)ff_nut_sp_pos_cmp,
+                          NULL);
 
-        nut->last_syncpoint_pos= avio_tell(bc);
-        ret = avio_open_dyn_buf(&dyn_bc);
-        if(ret < 0)
+        nut->last_syncpoint_pos = avio_tell(bc);
+        ret                     = avio_open_dyn_buf(&dyn_bc);
+        if (ret < 0)
             return ret;
         put_tt(nut, nus->time_base, dyn_bc, pkt->dts);
-        ff_put_v(dyn_bc, sp ? (nut->last_syncpoint_pos - sp->pos)>>4 : 0);
+        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);
+        ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0 /*unused*/, pkt->dts);
 
-        if((1ll<<60) % nut->sp_count == 0)
-            for(i=0; i<s->nb_streams; i++){
+        if ((1ll<<60) % nut->sp_count == 0)
+            for (i=0; i<s->nb_streams; i++) {
                 int j;
                 StreamContext *nus = &nut->stream[i];
                 nus->keyframe_pts = av_realloc(nus->keyframe_pts, 2*nut->sp_count*sizeof(*nus->keyframe_pts));
-                if(!nus->keyframe_pts)
+                if (!nus->keyframe_pts)
                     return AVERROR(ENOMEM);
-                for(j=nut->sp_count == 1 ? 0 : nut->sp_count; j<2*nut->sp_count; j++)
+                for (j=nut->sp_count == 1 ? 0 : nut->sp_count; j<2*nut->sp_count; j++)
                     nus->keyframe_pts[j] = AV_NOPTS_VALUE;
         }
     }
     av_assert0(nus->last_pts != AV_NOPTS_VALUE);
 
-    coded_pts = pkt->pts & ((1<<nus->msb_pts_shift)-1);
-    if(ff_lsb2full(nus, coded_pts) != pkt->pts)
-        coded_pts= pkt->pts + (1<<nus->msb_pts_shift);
+    coded_pts = pkt->pts & ((1 << nus->msb_pts_shift) - 1);
+    if (ff_lsb2full(nus, coded_pts) != pkt->pts)
+        coded_pts = pkt->pts + (1 << nus->msb_pts_shift);
 
-    best_header_idx= find_best_header_idx(nut, pkt);
+    best_header_idx = find_best_header_idx(nut, pkt);
 
-    best_length=INT_MAX;
-    frame_code= -1;
-    for(i=0; i<256; i++){
-        int length= 0;
-        FrameCode *fc= &nut->frame_code[i];
-        int flags= fc->flags;
+    best_length = INT_MAX;
+    frame_code  = -1;
+    for (i = 0; i < 256; i++) {
+        int length    = 0;
+        FrameCode *fc = &nut->frame_code[i];
+        int flags     = fc->flags;
 
-        if(flags & FLAG_INVALID)
+        if (flags & FLAG_INVALID)
             continue;
-        needed_flags= get_needed_flags(nut, nus, fc, pkt);
+        needed_flags = get_needed_flags(nut, nus, fc, pkt);
 
-        if(flags & FLAG_CODED){
+        if (flags & FLAG_CODED) {
             length++;
             flags = needed_flags;
         }
 
-        if((flags & needed_flags) != needed_flags)
+        if ((flags & needed_flags) != needed_flags)
             continue;
 
-        if((flags ^ needed_flags) & FLAG_KEY)
+        if ((flags ^ needed_flags) & FLAG_KEY)
             continue;
 
-        if(flags & FLAG_STREAM_ID)
-            length+= ff_get_v_length(pkt->stream_index);
+        if (flags & FLAG_STREAM_ID)
+            length += ff_get_v_length(pkt->stream_index);
 
-        if(pkt->size % fc->size_mul != fc->size_lsb)
+        if (pkt->size % fc->size_mul != fc->size_lsb)
             continue;
-        if(flags & FLAG_SIZE_MSB)
+        if (flags & FLAG_SIZE_MSB)
             length += ff_get_v_length(pkt->size / fc->size_mul);
 
-        if(flags & FLAG_CHECKSUM)
-            length+=4;
+        if (flags & FLAG_CHECKSUM)
+            length += 4;
 
-        if(flags & FLAG_CODED_PTS)
+        if (flags & FLAG_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){
+        if (   (flags & FLAG_CODED)
+            && nut->header_len[best_header_idx] > nut->header_len[fc->header_idx] + 1) {
             flags |= FLAG_HEADER_IDX;
         }
 
-        if(flags & FLAG_HEADER_IDX){
+        if (flags & FLAG_HEADER_IDX) {
             length += 1 - nut->header_len[best_header_idx];
-        }else{
+        } else {
             length -= nut->header_len[fc->header_idx];
         }
 
-        length*=4;
-        length+= !(flags & FLAG_CODED_PTS);
-        length+= !(flags & FLAG_CHECKSUM);
+        length *= 4;
+        length += !(flags & FLAG_CODED_PTS);
+        length += !(flags & FLAG_CHECKSUM);
 
-        if(length < best_length){
-            best_length= length;
-            frame_code=i;
+        if (length < best_length) {
+            best_length = length;
+            frame_code  = i;
         }
     }
     av_assert0(frame_code != -1);
-    fc= &nut->frame_code[frame_code];
-    flags= fc->flags;
-    needed_flags= get_needed_flags(nut, nus, fc, pkt);
-    header_idx= fc->header_idx;
+    fc           = &nut->frame_code[frame_code];
+    flags        = fc->flags;
+    needed_flags = get_needed_flags(nut, nus, fc, pkt);
+    header_idx   = fc->header_idx;
 
     ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
     avio_w8(bc, frame_code);
-    if(flags & FLAG_CODED){
-        ff_put_v(bc, (flags^needed_flags) & ~(FLAG_CODED));
+    if (flags & FLAG_CODED) {
+        ff_put_v(bc, (flags ^ needed_flags) & ~(FLAG_CODED));
         flags = needed_flags;
     }
-    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_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)   avio_wl32(bc, ffio_get_checksum(bc));
-    else                        ffio_get_checksum(bc);
+    if (flags & FLAG_CHECKSUM)   avio_wl32(bc, ffio_get_checksum(bc));
+    else                         ffio_get_checksum(bc);
 
     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;
+    nus->last_flags = flags;
+    nus->last_pts   = pkt->pts;
 
     //FIXME just store one per syncpoint
-    if(flags & FLAG_KEY) {
+    if (flags & FLAG_KEY) {
         av_add_index_entry(
             s->streams[pkt->stream_index],
             nut->last_syncpoint_pos,
@@ -905,11 +968,11 @@
             0,
             0,
             AVINDEX_KEYFRAME);
-        if(nus->keyframe_pts && nus->keyframe_pts[nut->sp_count] == AV_NOPTS_VALUE)
+        if (nus->keyframe_pts && nus->keyframe_pts[nut->sp_count] == AV_NOPTS_VALUE)
             nus->keyframe_pts[nut->sp_count] = pkt->pts;
     }
 
-    if(!nut->max_pts_tb || av_compare_ts(nut->max_pts, *nut->max_pts_tb, pkt->pts, *nus->time_base) < 0) {
+    if (!nut->max_pts_tb || av_compare_ts(nut->max_pts, *nut->max_pts_tb, pkt->pts, *nus->time_base) < 0) {
         nut->max_pts = pkt->pts;
         nut->max_pts_tb = nus->time_base;
     }
@@ -917,22 +980,23 @@
     return 0;
 }
 
-static int nut_write_trailer(AVFormatContext *s){
-    NUTContext *nut= s->priv_data;
+static int nut_write_trailer(AVFormatContext *s)
+{
+    NUTContext *nut = s->priv_data;
     AVIOContext *bc = s->pb, *dyn_bc;
     int i, ret;
 
-    while(nut->header_count<3)
+    while (nut->header_count < 3)
         write_headers(s, bc);
 
     ret = avio_open_dyn_buf(&dyn_bc);
-    if(ret >= 0) {
+    if (ret >= 0) {
         write_index(nut, dyn_bc);
         put_packet(nut, bc, dyn_bc, 1, INDEX_STARTCODE);
     }
 
     ff_nut_free_sp(nut);
-    for(i=0; i<s->nb_streams; i++)
+    for (i=0; i<s->nb_streams; i++)
         av_freep(&nut->stream[i].keyframe_pts);
 
     av_freep(&nut->stream);
@@ -955,8 +1019,5 @@
     .write_packet   = nut_write_packet,
     .write_trailer  = nut_write_trailer,
     .flags          = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
-    .codec_tag      = (const AVCodecTag * const []){
-        ff_codec_bmp_tags, ff_nut_video_tags, ff_codec_wav_tags,
-        ff_nut_subtitle_tags, 0
-    },
+    .codec_tag      = ff_nut_codec_tags,
 };
diff --git a/libavformat/nuv.c b/libavformat/nuv.c
index c192faa..fc9e916 100644
--- a/libavformat/nuv.c
+++ b/libavformat/nuv.c
@@ -19,12 +19,19 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "libavutil/intfloat.h"
 #include "avformat.h"
 #include "internal.h"
 #include "riff.h"
 
+static const AVCodecTag nuv_audio_tags[] = {
+    { AV_CODEC_ID_PCM_S16LE, MKTAG('R', 'A', 'W', 'A') },
+    { AV_CODEC_ID_MP3,       MKTAG('L', 'A', 'M', 'E') },
+    { AV_CODEC_ID_NONE,      0 },
+};
+
 typedef struct {
     int v_id;
     int a_id;
@@ -32,14 +39,15 @@
 } NUVContext;
 
 typedef enum {
-    NUV_VIDEO = 'V',
+    NUV_VIDEO     = 'V',
     NUV_EXTRADATA = 'D',
-    NUV_AUDIO = 'A',
-    NUV_SEEKP = 'R',
-    NUV_MYTHEXT = 'X'
+    NUV_AUDIO     = 'A',
+    NUV_SEEKP     = 'R',
+    NUV_MYTHEXT   = 'X'
 } nuv_frametype;
 
-static int nuv_probe(AVProbeData *p) {
+static int nuv_probe(AVProbeData *p)
+{
     if (!memcmp(p->buf, "NuppelVideo", 12))
         return AVPROBE_SCORE_MAX;
     if (!memcmp(p->buf, "MythTVVideo", 12))
@@ -55,91 +63,113 @@
  * @param vst video stream of which to change parameters
  * @param ast video stream of which to change parameters
  * @param myth set if this is a MythTVVideo format file
- * @return 1 if all required codec data was found
+ * @return 0 or AVERROR code
  */
 static int get_codec_data(AVIOContext *pb, AVStream *vst,
-                          AVStream *ast, int myth) {
+                          AVStream *ast, int myth)
+{
     nuv_frametype frametype;
+
     if (!vst && !myth)
         return 1; // no codec data needed
     while (!url_feof(pb)) {
         int size, subtype;
+
         frametype = avio_r8(pb);
         switch (frametype) {
-            case NUV_EXTRADATA:
-                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);
-                    avio_read(pb, vst->codec->extradata, size);
-                    size = 0;
-                    if (!myth)
-                        return 1;
+        case NUV_EXTRADATA:
+            subtype = avio_r8(pb);
+            avio_skip(pb, 6);
+            size = PKTSIZE(avio_rl32(pb));
+            if (vst && subtype == 'R') {
+                if (vst->codec->extradata) {
+                    av_freep(&vst->codec->extradata);
+                    vst->codec->extradata_size = 0;
                 }
+                vst->codec->extradata = av_malloc(size);
+                if (!vst->codec->extradata)
+                    return AVERROR(ENOMEM);
+                vst->codec->extradata_size = size;
+                avio_read(pb, vst->codec->extradata, size);
+                size = 0;
+                if (!myth)
+                    return 0;
+            }
+            break;
+        case NUV_MYTHEXT:
+            avio_skip(pb, 7);
+            size = PKTSIZE(avio_rl32(pb));
+            if (size != 128 * 4)
                 break;
-            case NUV_MYTHEXT:
-                avio_skip(pb, 7);
-                size = PKTSIZE(avio_rl32(pb));
-                if (size != 128 * 4)
-                    break;
-                avio_rl32(pb); // version
-                if (vst) {
-                    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 = AV_CODEC_ID_NUV;
-                } else
-                    avio_skip(pb, 4);
+            avio_rl32(pb); // version
+            if (vst) {
+                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 = AV_CODEC_ID_NUV;
+            } else
+                avio_skip(pb, 4);
 
-                if (ast) {
-                    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,
+            if (ast) {
+                int id;
+
+                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->channel_layout        = 0;
+
+                id = ff_wav_codec_get_id(ast->codec->codec_tag,
                                          ast->codec->bits_per_coded_sample);
-                    ast->need_parsing = AVSTREAM_PARSE_FULL;
-                } else
-                    avio_skip(pb, 4 * 4);
+                if (id == AV_CODEC_ID_NONE) {
+                    id = ff_codec_get_id(nuv_audio_tags, ast->codec->codec_tag);
+                    if (id == AV_CODEC_ID_PCM_S16LE)
+                        id = ff_get_pcm_codec_id(ast->codec->bits_per_coded_sample,
+                                                 0, 0, ~1);
+                }
+                ast->codec->codec_id = id;
 
-                size -= 6 * 4;
-                avio_skip(pb, size);
-                return 1;
-            case NUV_SEEKP:
-                size = 11;
-                break;
-            default:
-                avio_skip(pb, 7);
-                size = PKTSIZE(avio_rl32(pb));
-                break;
+                ast->need_parsing = AVSTREAM_PARSE_FULL;
+            } else
+                avio_skip(pb, 4 * 4);
+
+            size -= 6 * 4;
+            avio_skip(pb, size);
+            return 0;
+        case NUV_SEEKP:
+            size = 11;
+            break;
+        default:
+            avio_skip(pb, 7);
+            size = PKTSIZE(avio_rl32(pb));
+            break;
         }
         avio_skip(pb, size);
     }
+
     return 0;
 }
 
-static int nuv_header(AVFormatContext *s) {
+static int nuv_header(AVFormatContext *s)
+{
     NUVContext *ctx = s->priv_data;
     AVIOContext *pb = s->pb;
     char id_string[12];
     double aspect, fps;
-    int is_mythtv, width, height, v_packs, a_packs;
-    int stream_nr = 0;
+    int is_mythtv, width, height, v_packs, a_packs, ret;
     AVStream *vst = NULL, *ast = NULL;
+
     avio_read(pb, id_string, 12);
     is_mythtv = !memcmp(id_string, "MythTVVideo", 12);
-    avio_skip(pb, 5); // version string
-    avio_skip(pb, 3); // padding
-    width = avio_rl32(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
+    avio_rl32(pb);          // unused, "desiredwidth"
+    avio_rl32(pb);          // unused, "desiredheight"
+    avio_r8(pb);            // 'P' == progressive, 'I' == interlaced
+    avio_skip(pb, 3);       // padding
     aspect = av_int2double(avio_rl64(pb));
     if (aspect > 0.9999 && aspect < 1.0001)
         aspect = 4.0 / 3.0;
@@ -153,16 +183,18 @@
     avio_rl32(pb); // keyframe distance (?)
 
     if (v_packs) {
-        ctx->v_id = stream_nr++;
         vst = avformat_new_stream(s, NULL);
         if (!vst)
             return AVERROR(ENOMEM);
-        vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
-        vst->codec->codec_id = AV_CODEC_ID_NUV;
-        vst->codec->width = width;
-        vst->codec->height = height;
+        ctx->v_id = vst->index;
+
+        vst->codec->codec_type            = AVMEDIA_TYPE_VIDEO;
+        vst->codec->codec_id              = AV_CODEC_ID_NUV;
+        vst->codec->width                 = width;
+        vst->codec->height                = height;
         vst->codec->bits_per_coded_sample = 10;
-        vst->sample_aspect_ratio = av_d2q(aspect * height / width, 10000);
+        vst->sample_aspect_ratio          = av_d2q(aspect * height / width,
+                                                   10000);
 #if FF_API_R_FRAME_RATE
         vst->r_frame_rate =
 #endif
@@ -172,92 +204,104 @@
         ctx->v_id = -1;
 
     if (a_packs) {
-        ctx->a_id = stream_nr++;
         ast = avformat_new_stream(s, NULL);
         if (!ast)
             return AVERROR(ENOMEM);
-        ast->codec->codec_type = AVMEDIA_TYPE_AUDIO;
-        ast->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
-        ast->codec->channels = 2;
-        ast->codec->sample_rate = 44100;
-        ast->codec->bit_rate = 2 * 2 * 44100 * 8;
-        ast->codec->block_align = 2 * 2;
+        ctx->a_id = ast->index;
+
+        ast->codec->codec_type            = AVMEDIA_TYPE_AUDIO;
+        ast->codec->codec_id              = AV_CODEC_ID_PCM_S16LE;
+        ast->codec->channels              = 2;
+        ast->codec->channel_layout        = AV_CH_LAYOUT_STEREO;
+        ast->codec->sample_rate           = 44100;
+        ast->codec->bit_rate              = 2 * 2 * 44100 * 8;
+        ast->codec->block_align           = 2 * 2;
         ast->codec->bits_per_coded_sample = 16;
         avpriv_set_pts_info(ast, 32, 1, 1000);
     } else
         ctx->a_id = -1;
 
-    get_codec_data(pb, vst, ast, is_mythtv);
+    if ((ret = get_codec_data(pb, vst, ast, is_mythtv)) < 0)
+        return ret;
+
     ctx->rtjpg_video = vst && vst->codec->codec_id == AV_CODEC_ID_NUV;
+
     return 0;
 }
 
 #define HDRSIZE 12
 
-static int nuv_packet(AVFormatContext *s, AVPacket *pkt) {
+static int nuv_packet(AVFormatContext *s, AVPacket *pkt)
+{
     NUVContext *ctx = s->priv_data;
     AVIOContext *pb = s->pb;
     uint8_t hdr[HDRSIZE];
     nuv_frametype frametype;
     int ret, size;
+
     while (!url_feof(pb)) {
         int copyhdrsize = ctx->rtjpg_video ? HDRSIZE : 0;
-        uint64_t pos = avio_tell(pb);
+        uint64_t pos    = avio_tell(pb);
+
         ret = avio_read(pb, hdr, HDRSIZE);
         if (ret < HDRSIZE)
             return ret < 0 ? ret : AVERROR(EIO);
-        frametype = hdr[0];
-        size = PKTSIZE(AV_RL32(&hdr[8]));
-        switch (frametype) {
-            case NUV_EXTRADATA:
-                if (!ctx->rtjpg_video) {
-                    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");
-                    avio_skip(pb, size);
-                    break;
-                }
-                ret = av_new_packet(pkt, copyhdrsize + size);
-                if (ret < 0)
-                    return ret;
 
-                pkt->pos = pos;
-                pkt->flags |= hdr[2] == 0 ? AV_PKT_FLAG_KEY : 0;
-                pkt->pts = AV_RL32(&hdr[4]);
-                pkt->stream_index = ctx->v_id;
-                memcpy(pkt->data, hdr, copyhdrsize);
-                ret = avio_read(pb, pkt->data + copyhdrsize, size);
-                if (ret < 0) {
-                    av_free_packet(pkt);
-                    return ret;
-                }
-                if (ret < size)
-                    av_shrink_packet(pkt, copyhdrsize + ret);
-                return 0;
-            case NUV_AUDIO:
-                if (ctx->a_id < 0) {
-                    av_log(s, AV_LOG_ERROR, "Audio packet in file without audio stream!\n");
-                    avio_skip(pb, size);
-                    break;
-                }
-                ret = av_get_packet(pb, pkt, size);
-                pkt->flags |= AV_PKT_FLAG_KEY;
-                pkt->pos = pos;
-                pkt->pts = AV_RL32(&hdr[4]);
-                pkt->stream_index = ctx->a_id;
-                if (ret < 0) return ret;
-                return 0;
-            case NUV_SEEKP:
-                // contains no data, size value is invalid
-                break;
-            default:
+        frametype = hdr[0];
+        size      = PKTSIZE(AV_RL32(&hdr[8]));
+
+        switch (frametype) {
+        case NUV_EXTRADATA:
+            if (!ctx->rtjpg_video) {
                 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");
+                avio_skip(pb, size);
+                break;
+            }
+            ret = av_new_packet(pkt, copyhdrsize + size);
+            if (ret < 0)
+                return ret;
+
+            pkt->pos          = pos;
+            pkt->flags       |= hdr[2] == 0 ? AV_PKT_FLAG_KEY : 0;
+            pkt->pts          = AV_RL32(&hdr[4]);
+            pkt->stream_index = ctx->v_id;
+            memcpy(pkt->data, hdr, copyhdrsize);
+            ret = avio_read(pb, pkt->data + copyhdrsize, size);
+            if (ret < 0) {
+                av_free_packet(pkt);
+                return ret;
+            }
+            if (ret < size)
+                av_shrink_packet(pkt, copyhdrsize + ret);
+            return 0;
+        case NUV_AUDIO:
+            if (ctx->a_id < 0) {
+                av_log(s, AV_LOG_ERROR, "Audio packet in file without audio stream!\n");
+                avio_skip(pb, size);
+                break;
+            }
+            ret               = av_get_packet(pb, pkt, size);
+            pkt->flags       |= AV_PKT_FLAG_KEY;
+            pkt->pos          = pos;
+            pkt->pts          = AV_RL32(&hdr[4]);
+            pkt->stream_index = ctx->a_id;
+            if (ret < 0)
+                return ret;
+            return 0;
+        case NUV_SEEKP:
+            // contains no data, size value is invalid
+            break;
+        default:
+            avio_skip(pb, size);
+            break;
         }
     }
+
     return AVERROR(EIO);
 }
 
diff --git a/libavformat/oggdec.c b/libavformat/oggdec.c
index a36dfae..3ca33dc 100644
--- a/libavformat/oggdec.c
+++ b/libavformat/oggdec.c
@@ -57,6 +57,7 @@
 };
 
 static int64_t ogg_calc_pts(AVFormatContext *s, int idx, int64_t *dts);
+static int ogg_read_close(AVFormatContext *s);
 
 //FIXME We could avoid some structure duplication
 static int ogg_save(AVFormatContext *s)
@@ -175,7 +176,7 @@
     uint8_t *buf;
 
     if (ogg->nstreams != 1) {
-        av_log_missing_feature(s, "Changing stream parameters in multistream ogg is", 0);
+        av_log_missing_feature(s, "Changing stream parameters in multistream ogg", 0);
         return AVERROR_PATCHWELCOME;
     }
 
@@ -596,8 +597,10 @@
     //linear headers seek from start
     do {
         ret = ogg_packet(s, NULL, NULL, NULL, NULL);
-        if (ret < 0)
+        if (ret < 0) {
+            ogg_read_close(s);
             return ret;
+        }
     } while (!ogg->headers);
     av_dlog(s, "found headers\n");
 
diff --git a/libavformat/oggenc.c b/libavformat/oggenc.c
index 4871a0e..2ff6704 100644
--- a/libavformat/oggenc.c
+++ b/libavformat/oggenc.c
@@ -387,13 +387,13 @@
         AVStream *st = s->streams[i];
         unsigned serial_num = i;
 
-        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
+        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
             if (st->codec->codec_id == AV_CODEC_ID_OPUS)
                 /* Opus requires a fixed 48kHz clock */
                 avpriv_set_pts_info(st, 64, 1, 48000);
             else
                 avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
-        else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
+        } else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
             avpriv_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
         if (st->codec->codec_id != AV_CODEC_ID_VORBIS &&
             st->codec->codec_id != AV_CODEC_ID_THEORA &&
@@ -496,7 +496,7 @@
         AVStream *st = s->streams[j];
         OGGStreamContext *oggstream = st->priv_data;
         for (i = 1; i < 3; i++) {
-            if (oggstream && oggstream->header_len[i])
+            if (oggstream->header_len[i])
                 ogg_buffer_data(s, st, oggstream->header[i],
                                 oggstream->header_len[i], 0, 1);
         }
diff --git a/libavformat/oggparseskeleton.c b/libavformat/oggparseskeleton.c
index 4b02c83..f9ad701 100644
--- a/libavformat/oggparseskeleton.c
+++ b/libavformat/oggparseskeleton.c
@@ -75,8 +75,8 @@
         target_idx = ogg_find_stream(ogg, AV_RL32(buf+12));
         start_granule = AV_RL64(buf+36);
         if (os->start_granule != OGG_NOGRANULE_VALUE) {
-            av_log_missing_feature(s, "multiple fisbone for the "
-                                      "same stream\n", 0);
+            av_log_missing_feature(s,
+                                   "Multiple fisbone for the same stream", 0);
             return 1;
         }
         if (target_idx >= 0 && start_granule != OGG_NOGRANULE_VALUE) {
diff --git a/libavformat/oggparsespeex.c b/libavformat/oggparsespeex.c
index 11b50d5..42480a3 100644
--- a/libavformat/oggparsespeex.c
+++ b/libavformat/oggparsespeex.c
@@ -25,6 +25,7 @@
 #include <stdlib.h>
 #include "libavutil/bswap.h"
 #include "libavutil/avstring.h"
+#include "libavutil/channel_layout.h"
 #include "libavcodec/get_bits.h"
 #include "libavcodec/bytestream.h"
 #include "avformat.h"
@@ -59,6 +60,12 @@
 
         st->codec->sample_rate = AV_RL32(p + 36);
         st->codec->channels = AV_RL32(p + 48);
+        if (st->codec->channels < 1 || st->codec->channels > 2) {
+            av_log(s, AV_LOG_ERROR, "invalid channel count. Speex must be mono or stereo.\n");
+            return AVERROR_INVALIDDATA;
+        }
+        st->codec->channel_layout = st->codec->channels == 1 ? AV_CH_LAYOUT_MONO :
+                                                               AV_CH_LAYOUT_STEREO;
 
         spxp->packet_size  = AV_RL32(p + 56);
         frames_per_packet  = AV_RL32(p + 64);
diff --git a/libavformat/oggparsetheora.c b/libavformat/oggparsetheora.c
index c8aaa64..6877d1e 100644
--- a/libavformat/oggparsetheora.c
+++ b/libavformat/oggparsetheora.c
@@ -113,7 +113,7 @@
     }
     break;
     case 0x81:
-        ff_vorbis_comment(s, &st->metadata, os->buf + os->pstart + 7, os->psize - 8);
+        ff_vorbis_comment(s, &st->metadata, os->buf + os->pstart + 7, os->psize - 7);
     case 0x82:
         if (!thp->version)
             return -1;
diff --git a/libavformat/omadec.c b/libavformat/omadec.c
index 1e1b980..8d29675 100644
--- a/libavformat/omadec.c
+++ b/libavformat/omadec.c
@@ -37,16 +37,15 @@
  * - Sound data organized in packets follow the EA3 header
  *   (can be encrypted using the Sony DRM!).
  *
- * CODEC SUPPORT: Only ATRAC3 codec is currently supported!
  */
 
+#include "libavutil/channel_layout.h"
 #include "avformat.h"
 #include "internal.h"
 #include "libavutil/intreadwrite.h"
 #include "libavutil/des.h"
 #include "oma.h"
 #include "pcm.h"
-#include "riff.h"
 #include "id3v2.h"
 
 
@@ -159,7 +158,7 @@
     taglen = AV_RB32(&enc_header[pos+32]);
     datalen = AV_RB32(&enc_header[pos+36]) >> 4;
 
-    if(taglen + (((uint64_t)datalen)<<4) + 44 > size)
+    if(pos + (uint64_t)taglen + (((uint64_t)datalen)<<4) + 44 > size)
         return -1;
 
     pos += 44 + taglen;
@@ -318,6 +317,7 @@
             framesize = (codec_params & 0x3FF) * 8;
             jsflag = (codec_params >> 17) & 1; /* get stereo coding mode, 1 for joint-stereo */
             st->codec->channels    = 2;
+            st->codec->channel_layout = AV_CH_LAYOUT_STEREO;
             st->codec->sample_rate = samplerate;
             st->codec->bit_rate    = st->codec->sample_rate * framesize * 8 / 1024;
 
@@ -352,6 +352,7 @@
         case OMA_CODECID_LPCM:
             /* PCM 44.1 kHz 16 bit stereo big-endian */
             st->codec->channels = 2;
+            st->codec->channel_layout = AV_CH_LAYOUT_STEREO;
             st->codec->sample_rate = 44100;
             framesize = 1024;
             /* bit rate = sample rate x PCM block align (= 4) x 8 */
diff --git a/libavformat/omaenc.c b/libavformat/omaenc.c
index ab31d65..5c5aff7 100644
--- a/libavformat/omaenc.c
+++ b/libavformat/omaenc.c
@@ -84,8 +84,9 @@
                          (format->block_align/8 - 1));
         break;
     default:
-        av_log(s, AV_LOG_ERROR, "OMA: unsupported codec tag %d for write\n",
+        av_log(s, AV_LOG_ERROR, "unsupported codec tag %d for write\n",
                format->codec_tag);
+        return AVERROR(EINVAL);
     }
     for (i = 0; i < (EA3_HEADER_SIZE - 36)/4; i++)
         avio_wl32(s->pb, 0);        /* Padding */
diff --git a/libavformat/options_table.h b/libavformat/options_table.h
index 778c740..3394706 100644
--- a/libavformat/options_table.h
+++ b/libavformat/options_table.h
@@ -72,6 +72,7 @@
 {"aggressive", "consider things that a sane encoder shouldnt do as an error", 0, AV_OPT_TYPE_CONST, {.i64 = AV_EF_AGGRESSIVE }, INT_MIN, INT_MAX, D, "err_detect"},
 {"use_wallclock_as_timestamps", "use wallclock as timestamps", OFFSET(use_wallclock_as_timestamps), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX-1, D},
 {"avoid_negative_ts", "avoid negative timestamps", OFFSET(avoid_negative_ts), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, E},
+{"skip_initial_bytes", "skip initial bytes", OFFSET(skip_initial_bytes), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX-1, D},
 {NULL},
 };
 
diff --git a/libavformat/os_support.c b/libavformat/os_support.c
index bf6b8f2..ad1a23d 100644
--- a/libavformat/os_support.c
+++ b/libavformat/os_support.c
@@ -236,8 +236,10 @@
 
     if (serv && servlen > 0) {
         struct servent *ent = NULL;
+#if HAVE_GETSERVBYPORT
         if (!(flags & NI_NUMERICSERV))
             ent = getservbyport(sin->sin_port, flags & NI_DGRAM ? "udp" : "tcp");
+#endif
 
         if (ent)
             snprintf(serv, servlen, "%s", ent->s_name);
diff --git a/libavformat/os_support.h b/libavformat/os_support.h
index 589eb7e..b06cefd 100644
--- a/libavformat/os_support.h
+++ b/libavformat/os_support.h
@@ -67,7 +67,7 @@
     return 0;
 }
 
-#if defined(__OS2__)
+#if defined(__OS2__) || defined(__Plan9__)
 #define SHUT_RD 0
 #define SHUT_WR 1
 #define SHUT_RDWR 2
diff --git a/libavformat/paf.c b/libavformat/paf.c
index 8fe2ac5..09786eb 100644
--- a/libavformat/paf.c
+++ b/libavformat/paf.c
@@ -19,6 +19,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavcodec/paf.h"
 #include "avformat.h"
 #include "internal.h"
@@ -119,6 +120,7 @@
     ast->codec->codec_tag   = 0;
     ast->codec->codec_id    = AV_CODEC_ID_PAF_AUDIO;
     ast->codec->channels    = 2;
+    ast->codec->channel_layout = AV_CH_LAYOUT_STEREO;
     ast->codec->sample_rate = 22050;
     avpriv_set_pts_info(ast, 64, 1, 22050);
 
@@ -212,8 +214,8 @@
         if (p->current_frame_block >= p->frame_blks)
             return AVERROR_INVALIDDATA;
 
-        offset = p->blocks_offset_table[p->current_frame_block] & ~(1 << 31);
-        if (p->blocks_offset_table[p->current_frame_block] & (1 << 31)) {
+        offset = p->blocks_offset_table[p->current_frame_block] & ~(1U << 31);
+        if (p->blocks_offset_table[p->current_frame_block] & (1U << 31)) {
             if (offset > p->audio_size - p->buffer_size)
                 return AVERROR_INVALIDDATA;
 
diff --git a/libavformat/pcmdec.c b/libavformat/pcmdec.c
index 178c251..30f69d3 100644
--- a/libavformat/pcmdec.c
+++ b/libavformat/pcmdec.c
@@ -20,7 +20,7 @@
  */
 
 #include "avformat.h"
-#include "rawdec.h"
+#include "internal.h"
 #include "pcm.h"
 #include "libavutil/log.h"
 #include "libavutil/opt.h"
@@ -28,7 +28,40 @@
 
 #define RAW_SAMPLES     1024
 
-static int raw_read_packet(AVFormatContext *s, AVPacket *pkt)
+typedef struct PCMAudioDemuxerContext {
+    AVClass *class;
+    int sample_rate;
+    int channels;
+} PCMAudioDemuxerContext;
+
+static int pcm_read_header(AVFormatContext *s)
+{
+    PCMAudioDemuxerContext *s1 = s->priv_data;
+    AVStream *st;
+
+    st = avformat_new_stream(s, NULL);
+    if (!st)
+        return AVERROR(ENOMEM);
+
+
+    st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
+    st->codec->codec_id    = s->iformat->raw_codec_id;
+    st->codec->sample_rate = s1->sample_rate;
+    st->codec->channels    = s1->channels;
+
+    st->codec->bits_per_coded_sample =
+        av_get_bits_per_sample(st->codec->codec_id);
+
+    av_assert0(st->codec->bits_per_coded_sample > 0);
+
+    st->codec->block_align =
+        st->codec->bits_per_coded_sample * st->codec->channels / 8;
+
+    avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
+    return 0;
+}
+
+static int pcm_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     int ret, size, bps;
     //    AVStream *st = s->streams[0];
@@ -51,8 +84,8 @@
 }
 
 static const AVOption pcm_options[] = {
-    { "sample_rate", "", offsetof(RawAudioDemuxerContext, sample_rate), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
-    { "channels",    "", offsetof(RawAudioDemuxerContext, channels),    AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
+    { "sample_rate", "", offsetof(PCMAudioDemuxerContext, sample_rate), AV_OPT_TYPE_INT, {.i64 = 44100}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
+    { "channels",    "", offsetof(PCMAudioDemuxerContext, channels),    AV_OPT_TYPE_INT, {.i64 = 1}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
     { NULL },
 };
 
@@ -66,9 +99,9 @@
 AVInputFormat ff_pcm_ ## name_ ## _demuxer = {              \
     .name           = #name_,                               \
     .long_name      = NULL_IF_CONFIG_SMALL(long_name_),     \
-    .priv_data_size = sizeof(RawAudioDemuxerContext),       \
-    .read_header    = ff_raw_read_header,                   \
-    .read_packet    = raw_read_packet,                      \
+    .priv_data_size = sizeof(PCMAudioDemuxerContext),       \
+    .read_header    = pcm_read_header,                      \
+    .read_packet    = pcm_read_packet,                      \
     .read_seek      = ff_pcm_read_seek,                     \
     .flags          = AVFMT_GENERIC_INDEX,                  \
     .extensions     = ext,                                  \
diff --git a/libavformat/psxstr.c b/libavformat/psxstr.c
index 86fba16..35a6d71 100644
--- a/libavformat/psxstr.c
+++ b/libavformat/psxstr.c
@@ -29,6 +29,7 @@
  * RIFF headers, followed by CD sectors.
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "internal.h"
@@ -253,7 +254,13 @@
                 st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
                 st->codec->codec_id    = AV_CODEC_ID_ADPCM_XA;
                 st->codec->codec_tag   = 0;  /* no fourcc */
-                st->codec->channels    = (fmt&1)?2:1;
+                if (fmt & 1) {
+                    st->codec->channels       = 2;
+                    st->codec->channel_layout = AV_CH_LAYOUT_STEREO;
+                } else {
+                    st->codec->channels       = 1;
+                    st->codec->channel_layout = AV_CH_LAYOUT_MONO;
+                }
                 st->codec->sample_rate = (fmt&4)?18900:37800;
             //    st->codec->bit_rate = 0; //FIXME;
                 st->codec->block_align = 128;
diff --git a/libavformat/pvfdec.c b/libavformat/pvfdec.c
new file mode 100644
index 0000000..9d18256
--- /dev/null
+++ b/libavformat/pvfdec.c
@@ -0,0 +1,86 @@
+/*
+ * PVF demuxer
+ * Copyright (c) 2012 Paul B Mahol
+ *
+ * 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 "avformat.h"
+#include "internal.h"
+#include "pcm.h"
+
+static int pvf_probe(AVProbeData *p)
+{
+    if (!memcmp(p->buf, "PVF1\n", 5))
+        return AVPROBE_SCORE_MAX;
+    return 0;
+}
+
+static int pvf_read_header(AVFormatContext *s)
+{
+    char buffer[32];
+    AVStream *st;
+    int bps, channels, sample_rate;
+
+    avio_skip(s->pb, 5);
+    ff_get_line(s->pb, (char *)&buffer, 32);
+    if (sscanf(buffer, "%d %d %d",
+               &channels,
+               &sample_rate,
+               &bps) != 3)
+        return AVERROR_INVALIDDATA;
+
+    if (channels <= 0 || bps <= 0 || sample_rate <= 0)
+        return AVERROR_INVALIDDATA;
+
+    st = avformat_new_stream(s, NULL);
+    if (!st)
+        return AVERROR(ENOMEM);
+
+    st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
+    st->codec->channels    = channels;
+    st->codec->sample_rate = sample_rate;
+    st->codec->codec_id    = ff_get_pcm_codec_id(bps, 0, 1, 0xFFFF);
+    st->codec->bits_per_coded_sample = bps;
+    st->codec->block_align = bps * st->codec->channels / 8;
+
+    avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
+
+    return 0;
+}
+
+static int pvf_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    int ret;
+
+    ret = av_get_packet(s->pb, pkt, 1024 * s->streams[0]->codec->block_align);
+    pkt->flags &= ~AV_PKT_FLAG_CORRUPT;
+    pkt->stream_index = 0;
+
+    return ret;
+}
+
+AVInputFormat ff_pvf_demuxer = {
+    .name           = "pvf",
+    .long_name      = NULL_IF_CONFIG_SMALL("PVF (Portable Voice Format)"),
+    .read_probe     = pvf_probe,
+    .read_header    = pvf_read_header,
+    .read_packet    = pvf_read_packet,
+    .read_seek      = ff_pcm_read_seek,
+    .extensions     = "pvf",
+    .flags          = AVFMT_GENERIC_INDEX,
+};
diff --git a/libavformat/qcp.c b/libavformat/qcp.c
index 11fc71a..3cb85fb 100644
--- a/libavformat/qcp.c
+++ b/libavformat/qcp.c
@@ -27,6 +27,7 @@
  *     http://tools.ietf.org/html/rfc3625
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
 
@@ -96,6 +97,7 @@
 
     st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
     st->codec->channels   = 1;
+    st->codec->channel_layout = AV_CH_LAYOUT_MONO;
     avio_read(pb, buf, 16);
     if (is_qcelp_13k_guid(buf)) {
         st->codec->codec_id = AV_CODEC_ID_QCELP;
diff --git a/libavformat/rawdec.c b/libavformat/rawdec.c
index 974e58c..07c2782 100644
--- a/libavformat/rawdec.c
+++ b/libavformat/rawdec.c
@@ -29,82 +29,6 @@
 #include "libavutil/pixdesc.h"
 #include "libavutil/avassert.h"
 
-/* raw input */
-int ff_raw_read_header(AVFormatContext *s)
-{
-    AVStream *st;
-    enum AVCodecID id;
-
-    st = avformat_new_stream(s, NULL);
-    if (!st)
-        return AVERROR(ENOMEM);
-
-        id = s->iformat->raw_codec_id;
-        if (id == AV_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: {
-            RawAudioDemuxerContext *s1 = s->priv_data;
-
-            st->codec->channels = 1;
-
-            if (id == AV_CODEC_ID_ADPCM_G722)
-                st->codec->sample_rate = 16000;
-
-            if (s1 && s1->sample_rate)
-                st->codec->sample_rate = s1->sample_rate;
-            if (st->codec->sample_rate <= 0) {
-                av_log(s, AV_LOG_WARNING, "Invalid sample rate %d specified using default of 44100\n",
-                       st->codec->sample_rate);
-                st->codec->sample_rate= 44100;
-            }
-
-            if (s1 && s1->channels)
-                st->codec->channels    = s1->channels;
-
-            st->codec->bits_per_coded_sample = av_get_bits_per_sample(st->codec->codec_id);
-            av_assert0(st->codec->bits_per_coded_sample > 0);
-            st->codec->block_align = st->codec->bits_per_coded_sample*st->codec->channels/8;
-            avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
-            break;
-            }
-        case AVMEDIA_TYPE_VIDEO: {
-            FFRawVideoDemuxerContext *s1 = s->priv_data;
-            int width = 0, height = 0, ret = 0;
-            enum PixelFormat pix_fmt;
-            AVRational framerate;
-
-            if (s1->video_size && (ret = av_parse_video_size(&width, &height, s1->video_size)) < 0) {
-                av_log(s, AV_LOG_ERROR, "Couldn't parse video size.\n");
-                goto fail;
-            }
-            if ((pix_fmt = av_get_pix_fmt(s1->pixel_format)) == PIX_FMT_NONE) {
-                av_log(s, AV_LOG_ERROR, "No such pixel format: %s.\n", s1->pixel_format);
-                ret = AVERROR(EINVAL);
-                goto fail;
-            }
-            if ((ret = av_parse_video_rate(&framerate, s1->framerate)) < 0) {
-                av_log(s, AV_LOG_ERROR, "Could not parse framerate: %s.\n", s1->framerate);
-                goto fail;
-            }
-            avpriv_set_pts_info(st, 64, framerate.den, framerate.num);
-            st->codec->width  = width;
-            st->codec->height = height;
-            st->codec->pix_fmt = pix_fmt;
-fail:
-            return ret;
-            }
-        default:
-            return -1;
-        }
-    return 0;
-}
-
 #define RAW_PACKET_SIZE 1024
 
 int ff_raw_read_partial_packet(AVFormatContext *s, AVPacket *pkt)
@@ -181,18 +105,6 @@
     { NULL },
 };
 
-#if CONFIG_G722_DEMUXER
-AVInputFormat ff_g722_demuxer = {
-    .name           = "g722",
-    .long_name      = NULL_IF_CONFIG_SMALL("raw G.722"),
-    .read_header    = ff_raw_read_header,
-    .read_packet    = ff_raw_read_partial_packet,
-    .flags          = AVFMT_GENERIC_INDEX,
-    .extensions     = "g722,722",
-    .raw_codec_id   = AV_CODEC_ID_ADPCM_G722,
-};
-#endif
-
 #if CONFIG_LATM_DEMUXER
 AVInputFormat ff_latm_demuxer = {
     .name           = "latm",
diff --git a/libavformat/rawdec.h b/libavformat/rawdec.h
index 5812e50..d978295 100644
--- a/libavformat/rawdec.h
+++ b/libavformat/rawdec.h
@@ -26,12 +26,6 @@
 #include "libavutil/log.h"
 #include "libavutil/opt.h"
 
-typedef struct RawAudioDemuxerContext {
-    AVClass *class;
-    int sample_rate;
-    int channels;
-} RawAudioDemuxerContext;
-
 typedef struct FFRawVideoDemuxerContext {
     const AVClass *class;     /**< Class for private options. */
     char *video_size;         /**< String describing video size, set by a private option. */
@@ -41,8 +35,6 @@
 
 extern const AVOption ff_rawvideo_options[];
 
-int ff_raw_read_header(AVFormatContext *s);
-
 int ff_raw_read_partial_packet(AVFormatContext *s, AVPacket *pkt);
 
 int ff_raw_audio_read_header(AVFormatContext *s);
diff --git a/libavformat/rawenc.c b/libavformat/rawenc.c
index 94e68c5..0345f70 100644
--- a/libavformat/rawenc.c
+++ b/libavformat/rawenc.c
@@ -141,7 +141,7 @@
     .audio_codec       = AV_CODEC_ID_G723_1,
     .video_codec       = AV_CODEC_ID_NONE,
     .write_packet      = ff_raw_write_packet,
-    .flags= AVFMT_NOTIMESTAMPS,
+    .flags             = AVFMT_NOTIMESTAMPS,
 };
 #endif
 
diff --git a/libavformat/rawvideodec.c b/libavformat/rawvideodec.c
index 2828c8d..b2ca663 100644
--- a/libavformat/rawvideodec.c
+++ b/libavformat/rawvideodec.c
@@ -19,8 +19,63 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/parseutils.h"
+#include "libavutil/pixdesc.h"
+#include "libavutil/opt.h"
+#include "internal.h"
 #include "avformat.h"
-#include "rawdec.h"
+
+typedef struct RawVideoDemuxerContext {
+    const AVClass *class;     /**< Class for private options. */
+    char *video_size;         /**< String describing video size, set by a private option. */
+    char *pixel_format;       /**< Set by a private option. */
+    char *framerate;          /**< String describing framerate, set by a private option. */
+} RawVideoDemuxerContext;
+
+
+static int rawvideo_read_header(AVFormatContext *ctx)
+{
+    RawVideoDemuxerContext *s = ctx->priv_data;
+    int width = 0, height = 0, ret = 0;
+    enum AVPixelFormat pix_fmt;
+    AVRational framerate;
+    AVStream *st;
+
+    st = avformat_new_stream(ctx, NULL);
+    if (!st)
+        return AVERROR(ENOMEM);
+
+    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
+
+    st->codec->codec_id = ctx->iformat->raw_codec_id;
+
+    if (s->video_size &&
+        (ret = av_parse_video_size(&width, &height, s->video_size)) < 0) {
+        av_log(ctx, AV_LOG_ERROR, "Couldn't parse video size.\n");
+        return ret;
+    }
+
+    if ((pix_fmt = av_get_pix_fmt(s->pixel_format)) == AV_PIX_FMT_NONE) {
+        av_log(ctx, AV_LOG_ERROR, "No such pixel format: %s.\n",
+               s->pixel_format);
+        return AVERROR(EINVAL);
+    }
+
+    if ((ret = av_parse_video_rate(&framerate, s->framerate)) < 0) {
+        av_log(ctx, AV_LOG_ERROR, "Could not parse framerate: %s.\n",
+               s->framerate);
+        return ret;
+    }
+
+    avpriv_set_pts_info(st, 64, framerate.den, framerate.num);
+
+    st->codec->width  = width;
+    st->codec->height = height;
+    st->codec->pix_fmt = pix_fmt;
+
+    return 0;
+}
+
 
 static int rawvideo_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
@@ -34,9 +89,8 @@
     if (packet_size < 0)
         return -1;
 
-    ret= av_get_packet(s->pb, pkt, packet_size);
-    pkt->pts=
-    pkt->dts= pkt->pos / packet_size;
+    ret = av_get_packet(s->pb, pkt, packet_size);
+    pkt->pts = pkt->dts = pkt->pos / packet_size;
 
     pkt->stream_index = 0;
     if (ret < 0)
@@ -44,7 +98,7 @@
     return 0;
 }
 
-#define OFFSET(x) offsetof(FFRawVideoDemuxerContext, x)
+#define OFFSET(x) offsetof(RawVideoDemuxerContext, x)
 #define DEC AV_OPT_FLAG_DECODING_PARAM
 static const AVOption rawvideo_options[] = {
     { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
@@ -63,8 +117,8 @@
 AVInputFormat ff_rawvideo_demuxer = {
     .name           = "rawvideo",
     .long_name      = NULL_IF_CONFIG_SMALL("raw video"),
-    .priv_data_size = sizeof(FFRawVideoDemuxerContext),
-    .read_header    = ff_raw_read_header,
+    .priv_data_size = sizeof(RawVideoDemuxerContext),
+    .read_header    = rawvideo_read_header,
     .read_packet    = rawvideo_read_packet,
     .flags          = AVFMT_GENERIC_INDEX,
     .extensions     = "yuv,cif,qcif,rgb",
diff --git a/libavformat/realtextdec.c b/libavformat/realtextdec.c
index cc7c184..6a6a844 100644
--- a/libavformat/realtextdec.c
+++ b/libavformat/realtextdec.c
@@ -125,6 +125,14 @@
     return ff_subtitles_queue_read_packet(&rt->q, pkt);
 }
 
+static int realtext_read_seek(AVFormatContext *s, int stream_index,
+                             int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
+{
+    RealTextContext *rt = s->priv_data;
+    return ff_subtitles_queue_seek(&rt->q, s, stream_index,
+                                   min_ts, ts, max_ts, flags);
+}
+
 static int realtext_read_close(AVFormatContext *s)
 {
     RealTextContext *rt = s->priv_data;
@@ -139,6 +147,7 @@
     .read_probe     = realtext_probe,
     .read_header    = realtext_read_header,
     .read_packet    = realtext_read_packet,
+    .read_seek2     = realtext_read_seek,
     .read_close     = realtext_read_close,
     .flags          = AVFMT_GENERIC_INDEX,
     .extensions     = "rt",
diff --git a/libavformat/riff.c b/libavformat/riff.c
index 1c34112..af48947 100644
--- a/libavformat/riff.c
+++ b/libavformat/riff.c
@@ -1,5 +1,5 @@
 /*
- * RIFF codec tags
+ * RIFF common functions and data
  * Copyright (c) 2000 Fabrice Bellard
  *
  * This file is part of FFmpeg.
@@ -39,8 +39,10 @@
     { AV_CODEC_ID_H264,         MKTAG('x', '2', '6', '4') },
     { AV_CODEC_ID_H264,         MKTAG('a', 'v', 'c', '1') },
     { AV_CODEC_ID_H264,         MKTAG('D', 'A', 'V', 'C') },
+    { AV_CODEC_ID_H264,         MKTAG('S', 'M', 'V', '2') },
     { AV_CODEC_ID_H264,         MKTAG('V', 'S', 'S', 'H') },
     { AV_CODEC_ID_H264,         MKTAG('Q', '2', '6', '4') }, /* QNAP surveillance system */
+    { AV_CODEC_ID_H264,         MKTAG('V', '2', '6', '4') },
     { AV_CODEC_ID_H263,         MKTAG('H', '2', '6', '3') },
     { AV_CODEC_ID_H263,         MKTAG('X', '2', '6', '3') },
     { AV_CODEC_ID_H263,         MKTAG('T', '2', '6', '3') },
@@ -48,6 +50,7 @@
     { AV_CODEC_ID_H263,         MKTAG('V', 'X', '1', 'K') },
     { AV_CODEC_ID_H263,         MKTAG('Z', 'y', 'G', 'o') },
     { AV_CODEC_ID_H263,         MKTAG('M', '2', '6', '3') },
+    { AV_CODEC_ID_H263,         MKTAG('l', 's', 'v', 'm') },
     { AV_CODEC_ID_H263P,        MKTAG('H', '2', '6', '3') },
     { AV_CODEC_ID_H263I,        MKTAG('I', '2', '6', '3') }, /* intel h263 */
     { AV_CODEC_ID_H261,         MKTAG('H', '2', '6', '1') },
@@ -111,6 +114,7 @@
     { AV_CODEC_ID_MSMPEG4V1,    MKTAG('M', 'P', '4', '1') },
     { AV_CODEC_ID_WMV1,         MKTAG('W', 'M', 'V', '1') },
     { AV_CODEC_ID_WMV2,         MKTAG('W', 'M', 'V', '2') },
+    { AV_CODEC_ID_WMV2,         MKTAG('G', 'X', 'V', 'E') },
     { AV_CODEC_ID_DVVIDEO,      MKTAG('d', 'v', 's', 'd') },
     { AV_CODEC_ID_DVVIDEO,      MKTAG('d', 'v', 'h', 'd') },
     { AV_CODEC_ID_DVVIDEO,      MKTAG('d', 'v', 'h', '1') },
@@ -335,8 +339,10 @@
     { AV_CODEC_ID_PCM_ALAW,        0x0006 },
     { AV_CODEC_ID_PCM_MULAW,       0x0007 },
     { AV_CODEC_ID_WMAVOICE,        0x000A },
+    { AV_CODEC_ID_ADPCM_IMA_OKI,   0x0010 },
     { AV_CODEC_ID_ADPCM_IMA_WAV,   0x0011 },
     { AV_CODEC_ID_PCM_ZORK,        0x0011 }, /* must come after adpcm_ima_wav in this list */
+    { AV_CODEC_ID_ADPCM_IMA_OKI,   0x0017 },
     { AV_CODEC_ID_ADPCM_YAMAHA,    0x0020 },
     { AV_CODEC_ID_TRUESPEECH,      0x0022 },
     { AV_CODEC_ID_GSM_MS,          0x0031 },
@@ -373,16 +379,12 @@
     { AV_CODEC_ID_PCM_MULAW,       0x6c75 },
     { AV_CODEC_ID_AAC,             0x706d },
     { AV_CODEC_ID_AAC,             0x4143 },
+    { AV_CODEC_ID_G723_1,          0xA100 },
+    { AV_CODEC_ID_AAC,             0xA106 },
     { AV_CODEC_ID_SPEEX,           0xA109 },
     { AV_CODEC_ID_FLAC,            0xF1AC },
     { AV_CODEC_ID_ADPCM_SWF,       ('S'<<8)+'F' },
     { AV_CODEC_ID_VORBIS,          ('V'<<8)+'o' }, //HACK/FIXME, does vorbis in WAV/AVI have an (in)official id?
-
-    /* FIXME: All of the IDs below are not 16 bit and thus illegal. */
-    // for NuppelVideo (nuv.c)
-    { AV_CODEC_ID_PCM_S16LE, MKTAG('R', 'A', 'W', 'A') },
-    { AV_CODEC_ID_MP3,       MKTAG('L', 'A', 'M', 'E') },
-    { AV_CODEC_ID_MP3,       MKTAG('M', 'P', '3', ' ') },
     { AV_CODEC_ID_NONE,      0 },
 };
 
@@ -410,13 +412,6 @@
     { 0 },
 };
 
-const char ff_riff_tags[][5] = {
-    "IARL", "IART", "ICMS", "ICMT", "ICOP", "ICRD", "ICRP", "IDIM", "IDPI",
-    "IENG", "IGNR", "IKEY", "ILGT", "ILNG", "IMED", "INAM", "IPLT", "IPRD",
-    "IPRT", "ISBJ", "ISFT", "ISHP", "ISMP", "ISRC", "ISRF", "ITCH",
-    {0}
-};
-
 #if CONFIG_MUXERS
 int64_t ff_start_tag(AVIOContext *pb, const char *tag)
 {
@@ -589,6 +584,90 @@
     if (!for_asf && enc->extradata_size & 1)
         avio_w8(pb, 0);
 }
+
+void ff_parse_specific_params(AVCodecContext *stream, int *au_rate, int *au_ssize, int *au_scale)
+{
+    int gcd;
+    int audio_frame_size;
+
+    /* We use the known constant frame size for the codec if known, otherwise
+       fallback to using AVCodecContext.frame_size, which is not as reliable
+       for indicating packet duration */
+    audio_frame_size = av_get_audio_frame_duration(stream, 0);
+    if (!audio_frame_size)
+        audio_frame_size = stream->frame_size;
+
+    *au_ssize= stream->block_align;
+    if (audio_frame_size && stream->sample_rate) {
+        *au_scale = audio_frame_size;
+        *au_rate= stream->sample_rate;
+    }else if(stream->codec_type == AVMEDIA_TYPE_VIDEO ||
+             stream->codec_type == AVMEDIA_TYPE_DATA ||
+             stream->codec_type == AVMEDIA_TYPE_SUBTITLE){
+        *au_scale= stream->time_base.num;
+        *au_rate = stream->time_base.den;
+    }else{
+        *au_scale= stream->block_align ? stream->block_align*8 : 8;
+        *au_rate = stream->bit_rate ? stream->bit_rate : 8*stream->sample_rate;
+    }
+    gcd= av_gcd(*au_scale, *au_rate);
+    *au_scale /= gcd;
+    *au_rate /= gcd;
+}
+
+void ff_riff_write_info_tag(AVIOContext *pb, const char *tag, const char *str)
+{
+    int len = strlen(str);
+    if (len > 0) {
+        len++;
+        ffio_wfourcc(pb, tag);
+        avio_wl32(pb, len);
+        avio_put_str(pb, str);
+        if (len & 1)
+            avio_w8(pb, 0);
+    }
+}
+
+static const char riff_tags[][5] = {
+    "IARL", "IART", "ICMS", "ICMT", "ICOP", "ICRD", "ICRP", "IDIM", "IDPI",
+    "IENG", "IGNR", "IKEY", "ILGT", "ILNG", "IMED", "INAM", "IPLT", "IPRD",
+    "IPRT", "ISBJ", "ISFT", "ISHP", "ISMP", "ISRC", "ISRF", "ITCH",
+    {0}
+};
+
+static int riff_has_valid_tags(AVFormatContext *s)
+{
+    int i;
+
+    for (i = 0; *riff_tags[i]; i++) {
+        if (av_dict_get(s->metadata, riff_tags[i], NULL, AV_DICT_MATCH_CASE))
+            return 1;
+    }
+
+    return 0;
+}
+
+void ff_riff_write_info(AVFormatContext *s)
+{
+    AVIOContext *pb = s->pb;
+    int i;
+    int64_t list_pos;
+    AVDictionaryEntry *t = NULL;
+
+    ff_metadata_conv(&s->metadata, ff_riff_info_conv, NULL);
+
+    /* writing empty LIST is not nice and may cause problems */
+    if (!riff_has_valid_tags(s))
+        return;
+
+    list_pos = ff_start_tag(pb, "LIST");
+    ffio_wfourcc(pb, "INFO");
+    for (i = 0; *riff_tags[i]; i++) {
+        if ((t = av_dict_get(s->metadata, riff_tags[i], NULL, AV_DICT_MATCH_CASE)))
+            ff_riff_write_info_tag(s->pb, t->key, t->value);
+    }
+    ff_end_tag(pb, list_pos);
+}
 #endif //CONFIG_MUXERS
 
 #if CONFIG_DEMUXERS
@@ -661,7 +740,7 @@
         codec->sample_rate = 0;
     }
     /* override bits_per_coded_sample for G.726 */
-    if (codec->codec_id == AV_CODEC_ID_ADPCM_G726)
+    if (codec->codec_id == AV_CODEC_ID_ADPCM_G726 && codec->sample_rate)
         codec->bits_per_coded_sample = codec->bit_rate / codec->sample_rate;
 
     return 0;
@@ -674,15 +753,12 @@
     id = ff_codec_get_id(ff_codec_wav_tags, tag);
     if (id <= 0)
         return id;
-    /* handle specific u8 codec */
-    if (id == AV_CODEC_ID_PCM_S16LE && bps == 8)
-        id = AV_CODEC_ID_PCM_U8;
-    if (id == AV_CODEC_ID_PCM_S16LE && bps == 24)
-        id = AV_CODEC_ID_PCM_S24LE;
-    if (id == AV_CODEC_ID_PCM_S16LE && bps == 32)
-        id = AV_CODEC_ID_PCM_S32LE;
-    if (id == AV_CODEC_ID_PCM_F32LE && bps == 64)
-        id = AV_CODEC_ID_PCM_F64LE;
+
+    if (id == AV_CODEC_ID_PCM_S16LE)
+        id = ff_get_pcm_codec_id(bps, 0, 0, ~1);
+    else if (id == AV_CODEC_ID_PCM_F32LE)
+        id = ff_get_pcm_codec_id(bps, 1, 0, 0);
+
     if (id == AV_CODEC_ID_ADPCM_IMA_WAV && bps == 8)
         id = AV_CODEC_ID_PCM_ZORK;
     return id;
@@ -705,37 +781,6 @@
     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)
-{
-    int gcd;
-    int audio_frame_size;
-
-    /* We use the known constant frame size for the codec if known, otherwise
-       fallback to using AVCodecContext.frame_size, which is not as reliable
-       for indicating packet duration */
-    audio_frame_size = av_get_audio_frame_duration(stream, 0);
-    if (!audio_frame_size)
-        audio_frame_size = stream->frame_size;
-
-    *au_ssize= stream->block_align;
-    if (audio_frame_size && stream->sample_rate) {
-        *au_scale = audio_frame_size;
-        *au_rate= stream->sample_rate;
-    }else if(stream->codec_type == AVMEDIA_TYPE_VIDEO ||
-             stream->codec_type == AVMEDIA_TYPE_DATA ||
-             stream->codec_type == AVMEDIA_TYPE_SUBTITLE){
-        *au_scale= stream->time_base.num;
-        *au_rate = stream->time_base.den;
-    }else{
-        *au_scale= stream->block_align ? stream->block_align*8 : 8;
-        *au_rate = stream->bit_rate ? stream->bit_rate : 8*stream->sample_rate;
-    }
-    gcd= av_gcd(*au_scale, *au_rate);
-    *au_scale /= gcd;
-    *au_rate /= gcd;
-}
 
 void ff_get_guid(AVIOContext *s, ff_asf_guid *g)
 {
@@ -770,14 +815,26 @@
 
         chunk_code = avio_rl32(pb);
         chunk_size = avio_rl32(pb);
+
         if (chunk_size > end || end - chunk_size < cur || chunk_size == UINT_MAX) {
-            av_log(s, AV_LOG_ERROR, "too big INFO subchunk\n");
-            return AVERROR_INVALIDDATA;
+            avio_seek(pb, -9, SEEK_CUR);
+            chunk_code = avio_rl32(pb);
+            chunk_size = avio_rl32(pb);
+            if (chunk_size > end || end - chunk_size < cur || chunk_size == UINT_MAX) {
+                av_log(s, AV_LOG_WARNING, "too big INFO subchunk\n");
+                return AVERROR_INVALIDDATA;
+            }
         }
 
         chunk_size += (chunk_size & 1);
 
-        value = av_malloc(chunk_size + 1);
+        if (!chunk_code) {
+            if (chunk_size)
+                avio_skip(pb, chunk_size);
+            continue;
+        }
+
+        value = av_mallocz(chunk_size + 1);
         if (!value) {
             av_log(s, AV_LOG_ERROR, "out of memory, unable to read INFO tag\n");
             return AVERROR(ENOMEM);
@@ -786,15 +843,12 @@
         AV_WL32(key, chunk_code);
 
         if (avio_read(pb, value, chunk_size) != chunk_size) {
-            av_freep(&value);
-            av_log(s, AV_LOG_ERROR, "premature end of file while reading INFO tag\n");
-            return AVERROR_INVALIDDATA;
+            av_log(s, AV_LOG_WARNING, "premature end of file while reading INFO tag\n");
         }
 
-        value[chunk_size] = 0;
-
         av_dict_set(&s->metadata, key, value, AV_DICT_DONT_STRDUP_VAL);
     }
 
     return 0;
 }
+#endif // CONFIG_DEMUXERS
diff --git a/libavformat/riff.h b/libavformat/riff.h
index 9126e40..8579a95 100644
--- a/libavformat/riff.h
+++ b/libavformat/riff.h
@@ -1,5 +1,5 @@
 /*
- * RIFF codec tags
+ * RIFF common functions and data
  * copyright (c) 2000 Fabrice Bellard
  *
  * This file is part of FFmpeg.
@@ -54,8 +54,6 @@
 extern const AVCodecTag ff_codec_bmp_tags[];
 extern const AVCodecTag ff_codec_wav_tags[];
 
-unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id);
-enum AVCodecID 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);
 
 typedef uint8_t ff_asf_guid[16];
@@ -86,4 +84,14 @@
 #define FF_MEDIASUBTYPE_BASE_GUID \
     0x00,0x00,0x10,0x00,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71
 
+/**
+ * Write all recognized RIFF tags from s->metadata
+ */
+void ff_riff_write_info(AVFormatContext *s);
+
+/**
+ * Write a single RIFF info tag
+ */
+void ff_riff_write_info_tag(AVIOContext *pb, const char *tag, const char *str);
+
 #endif /* AVFORMAT_RIFF_H */
diff --git a/libavformat/rm.h b/libavformat/rm.h
index b482c2f..a72e8b7 100644
--- a/libavformat/rm.h
+++ b/libavformat/rm.h
@@ -26,7 +26,6 @@
 #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;
@@ -93,11 +92,4 @@
 int ff_rm_retrieve_cache (AVFormatContext *s, AVIOContext *pb,
                           AVStream *st, RMStream *rst, AVPacket *pkt);
 
-/**
- * Perform 4-bit block reordering for SIPR data.
- *
- * @param buf SIPR data
- */
-void ff_rm_reorder_sipr_data(uint8_t *buf, int sub_packet_h, int framesize);
-
 #endif /* AVFORMAT_RM_H */
diff --git a/libavformat/rmdec.c b/libavformat/rmdec.c
index a69017d..2bfa5ce 100644
--- a/libavformat/rmdec.c
+++ b/libavformat/rmdec.c
@@ -19,12 +19,14 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/avassert.h"
 #include "libavutil/avstring.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "libavutil/dict.h"
 #include "avformat.h"
 #include "internal.h"
-#include "riff.h"
+#include "rmsipr.h"
 #include "rm.h"
 
 #define DEINT_ID_GENR MKTAG('g', 'e', 'n', 'r') ///< interleaving for Cooker/Atrac
@@ -59,21 +61,6 @@
     int audio_pkt_cnt; ///< Output packet counter
 } RMDemuxContext;
 
-static const unsigned char sipr_swaps[38][2] = {
-    {  0, 63 }, {  1, 22 }, {  2, 44 }, {  3, 90 },
-    {  5, 81 }, {  7, 31 }, {  8, 86 }, {  9, 58 },
-    { 10, 36 }, { 12, 68 }, { 13, 39 }, { 14, 73 },
-    { 15, 53 }, { 16, 69 }, { 17, 57 }, { 19, 88 },
-    { 20, 34 }, { 21, 71 }, { 24, 46 }, { 25, 94 },
-    { 26, 54 }, { 28, 75 }, { 29, 50 }, { 32, 70 },
-    { 33, 92 }, { 35, 74 }, { 38, 85 }, { 40, 56 },
-    { 42, 87 }, { 43, 65 }, { 45, 59 }, { 48, 79 },
-    { 49, 93 }, { 51, 89 }, { 55, 95 }, { 61, 76 },
-    { 67, 83 }, { 77, 80 }
-};
-
-const unsigned char ff_sipr_subpk_size[4] = { 29, 19, 37, 20 };
-
 static inline void get_strl(AVIOContext *pb, char *buf, int buf_size, int len)
 {
     int i;
@@ -154,6 +141,7 @@
             avio_skip(pb, header_size + startpos - avio_tell(pb));
         st->codec->sample_rate = 8000;
         st->codec->channels = 1;
+        st->codec->channel_layout = AV_CH_LAYOUT_MONO;
         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
         st->codec->codec_id = AV_CODEC_ID_RA_144;
         ast->deint_id = DEINT_ID_INT0;
@@ -282,7 +270,7 @@
         case DEINT_ID_VBRF:
             break;
         default:
-            av_log(NULL,0,"Unknown interleaver %X\n", ast->deint_id);
+            av_log(s, AV_LOG_ERROR, "Unknown interleaver %X\n", ast->deint_id);
             return AVERROR_INVALIDDATA;
         }
 
@@ -750,32 +738,6 @@
     }
 }
 
-/**
- * Perform 4-bit block reordering for SIPR data.
- * @todo This can be optimized, e.g. use memcpy() if data blocks are aligned
- */
-void ff_rm_reorder_sipr_data(uint8_t *buf, int sub_packet_h, int framesize)
-{
-    int n, bs = sub_packet_h * framesize * 2 / 96; // nibbles per subpacket
-
-    for (n = 0; n < 38; n++) {
-        int j;
-        int i = bs * sipr_swaps[n][0];
-        int o = bs * sipr_swaps[n][1];
-
-        /* swap 4bit-nibbles of block 'i' with 'o' */
-        for (j = 0; j < bs; j++, i++, o++) {
-            int x = (buf[i >> 1] >> (4 * (i & 1))) & 0xF,
-                y = (buf[o >> 1] >> (4 * (o & 1))) & 0xF;
-
-            buf[o >> 1] = (x << (4 * (o & 1))) |
-                (buf[o >> 1] & (0xF << (4 * !(o & 1))));
-            buf[i >> 1] = (y << (4 * (i & 1))) |
-                (buf[i >> 1] & (0xF << (4 * !(i & 1))));
-        }
-    }
-}
-
 int
 ff_rm_parse_packet (AVFormatContext *s, AVIOContext *pb,
                     AVStream *st, RMStream *ast, int len, AVPacket *pkt,
@@ -872,13 +834,14 @@
 {
     RMDemuxContext *rm = s->priv_data;
 
-    assert (rm->audio_pkt_cnt > 0);
+    av_assert0 (rm->audio_pkt_cnt > 0);
 
     if (ast->deint_id == DEINT_ID_VBRF ||
         ast->deint_id == DEINT_ID_VBRS)
         av_get_packet(pb, pkt, ast->sub_packet_lengths[ast->sub_packet_cnt - rm->audio_pkt_cnt]);
     else {
-        av_new_packet(pkt, st->codec->block_align);
+        if(av_new_packet(pkt, st->codec->block_align) < 0)
+            return AVERROR(ENOMEM);
         memcpy(pkt->data, ast->pkt.data + st->codec->block_align * //FIXME avoid this
                (ast->sub_packet_h * ast->audio_framesize / st->codec->block_align - rm->audio_pkt_cnt),
                st->codec->block_align);
@@ -906,7 +869,9 @@
         if (rm->audio_pkt_cnt) {
             // If there are queued audio packet return them first
             st = s->streams[rm->audio_stream_num];
-            ff_rm_retrieve_cache(s, s->pb, st, st->priv_data, pkt);
+            res = ff_rm_retrieve_cache(s, s->pb, st, st->priv_data, pkt);
+            if(res < 0)
+                return res;
             flags = 0;
         } else {
             if (rm->old_format) {
diff --git a/libavformat/rmsipr.c b/libavformat/rmsipr.c
new file mode 100644
index 0000000..14ec8ea
--- /dev/null
+++ b/libavformat/rmsipr.c
@@ -0,0 +1,61 @@
+/*
+ * tables and functions for demuxing SIPR audio muxed RealMedia style
+ *
+ * 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 <stdint.h>
+
+#include "rmsipr.h"
+
+const unsigned char ff_sipr_subpk_size[4] = { 29, 19, 37, 20 };
+
+static const unsigned char sipr_swaps[38][2] = {
+    {  0, 63 }, {  1, 22 }, {  2, 44 }, {  3, 90 },
+    {  5, 81 }, {  7, 31 }, {  8, 86 }, {  9, 58 },
+    { 10, 36 }, { 12, 68 }, { 13, 39 }, { 14, 73 },
+    { 15, 53 }, { 16, 69 }, { 17, 57 }, { 19, 88 },
+    { 20, 34 }, { 21, 71 }, { 24, 46 }, { 25, 94 },
+    { 26, 54 }, { 28, 75 }, { 29, 50 }, { 32, 70 },
+    { 33, 92 }, { 35, 74 }, { 38, 85 }, { 40, 56 },
+    { 42, 87 }, { 43, 65 }, { 45, 59 }, { 48, 79 },
+    { 49, 93 }, { 51, 89 }, { 55, 95 }, { 61, 76 },
+    { 67, 83 }, { 77, 80 }
+};
+
+/* This can be optimized, e.g. use memcpy() if data blocks are aligned. */
+void ff_rm_reorder_sipr_data(uint8_t *buf, int sub_packet_h, int framesize)
+{
+    int n, bs = sub_packet_h * framesize * 2 / 96; // nibbles per subpacket
+
+    for (n = 0; n < 38; n++) {
+        int j;
+        int i = bs * sipr_swaps[n][0];
+        int o = bs * sipr_swaps[n][1];
+
+        /* swap 4bit-nibbles of block 'i' with 'o' */
+        for (j = 0; j < bs; j++, i++, o++) {
+            int x = (buf[i >> 1] >> (4 * (i & 1))) & 0xF,
+                y = (buf[o >> 1] >> (4 * (o & 1))) & 0xF;
+
+            buf[o >> 1] = (x << (4 * (o & 1))) |
+                (buf[o >> 1] & (0xF << (4 * !(o & 1))));
+            buf[i >> 1] = (y << (4 * (i & 1))) |
+                (buf[i >> 1] & (0xF << (4 * !(i & 1))));
+        }
+    }
+}
diff --git a/libavutil/symbols.h b/libavformat/rmsipr.h
similarity index 66%
copy from libavutil/symbols.h
copy to libavformat/rmsipr.h
index 6011da2..2837336 100644
--- a/libavutil/symbols.h
+++ b/libavformat/rmsipr.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Ronald S. Bultje <rsbultje@gmail.com>
+ * tables and functions for demuxing SIPR audio muxed RealMedia style
  *
  * This file is part of FFmpeg.
  *
@@ -18,15 +18,18 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#ifndef AVUTIL_SYMBOLS_H
-#define AVUTIL_SYMBOLS_H
+#ifndef AVFORMAT_RMSIPR_H
+#define AVFORMAT_RMSIPR_H
 
-#include "libavutil/avconfig.h"
+#include <stdint.h>
 
-#if AV_HAVE_SHARED_LIBS && defined(_MSC_VER) && !defined(COMPILING_avutil)
-#define AVUTIL_SYMBOL __declspec(dllimport)
-#else
-#define AVUTIL_SYMBOL
-#endif
+extern const unsigned char ff_sipr_subpk_size[4];
 
-#endif /* AVUTIL_SYMBOLS_H */
+/**
+ * Perform 4-bit block reordering for SIPR data.
+ *
+ * @param buf SIPR data
+ */
+void ff_rm_reorder_sipr_data(uint8_t *buf, int sub_packet_h, int framesize);
+
+#endif /* AVFORMAT_RMSIPR_H */
diff --git a/libavformat/rpl.c b/libavformat/rpl.c
index b790597..dcc7950 100644
--- a/libavformat/rpl.c
+++ b/libavformat/rpl.c
@@ -287,7 +287,7 @@
     stream = s->streams[rpl->chunk_part];
 
     if (rpl->chunk_number >= stream->nb_index_entries)
-        return -1;
+        return AVERROR_EOF;
 
     index_entry = &stream->index_entries[rpl->chunk_number];
 
diff --git a/libavformat/rsodec.c b/libavformat/rsodec.c
index 7a22217..19c21e0 100644
--- a/libavformat/rsodec.c
+++ b/libavformat/rsodec.c
@@ -20,11 +20,11 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #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)
@@ -63,6 +63,7 @@
     st->codec->codec_tag    = id;
     st->codec->codec_id     = codec;
     st->codec->channels     = 1;
+    st->codec->channel_layout = AV_CH_LAYOUT_MONO;
     st->codec->sample_rate  = rate;
 
     avpriv_set_pts_info(st, 64, 1, rate);
diff --git a/libavformat/rtmppkt.h b/libavformat/rtmppkt.h
index 7ed3113..9b58803 100644
--- a/libavformat/rtmppkt.h
+++ b/libavformat/rtmppkt.h
@@ -253,7 +253,7 @@
 /**
  * Read AMF string value.
  *
- * Appends a trailing \0 to output string in order to
+ * Appends a trailing null byte to output string in order to
  * ease later parsing.
  *
  *@param[in,out] gbc     GetByteContext initialized with AMF-formatted data
diff --git a/libavformat/rtmpproto.c b/libavformat/rtmpproto.c
index 518e7b2..72462cf 100644
--- a/libavformat/rtmpproto.c
+++ b/libavformat/rtmpproto.c
@@ -256,9 +256,6 @@
         *value = '\0';
         value++;
 
-        if (!field || !value)
-            goto fail;
-
         ff_amf_write_field_name(p, field);
     } else {
         goto fail;
@@ -859,7 +856,7 @@
     uint8_t hmac_buf[64+32] = {0};
     int i;
 
-    sha = av_mallocz(av_sha_size);
+    sha = av_sha_alloc();
     if (!sha)
         return AVERROR(ENOMEM);
 
@@ -1371,9 +1368,9 @@
     /* By now same epoch will be sent */
     hs_my_epoch = hs_epoch;
     /* Generate random */
-    for (randomidx = 0; randomidx < (RTMP_HANDSHAKE_PACKET_SIZE);
+    for (randomidx = 8; randomidx < (RTMP_HANDSHAKE_PACKET_SIZE);
          randomidx += 4)
-        AV_WB32(hs_s1 + 8 + randomidx, av_get_random_seed());
+        AV_WB32(hs_s1 + randomidx, av_get_random_seed());
 
     ret = rtmp_send_hs_packet(rt, hs_my_epoch, 0, hs_s1,
                               RTMP_HANDSHAKE_PACKET_SIZE);
@@ -2188,7 +2185,7 @@
         } else {
             rt->playpath[0] = 0;
         }
-        strncat(rt->playpath, fname, PLAYPATH_MAX_LENGTH - 5);
+        av_strlcat(rt->playpath, fname, PLAYPATH_MAX_LENGTH);
     }
 
     if (!rt->tcurl) {
diff --git a/libavformat/rtp.c b/libavformat/rtp.c
index f9e4447..ae0fd58 100644
--- a/libavformat/rtp.c
+++ b/libavformat/rtp.c
@@ -90,7 +90,8 @@
     return -1;
 }
 
-int ff_rtp_get_payload_type(AVFormatContext *fmt, AVCodecContext *codec)
+int ff_rtp_get_payload_type(AVFormatContext *fmt,
+                            AVCodecContext *codec, int idx)
 {
     int i;
     AVOutputFormat *ofmt = fmt ? fmt->oformat : NULL;
@@ -124,8 +125,11 @@
             return AVRtpPayloadTypes[i].pt;
         }
 
+    if (idx < 0)
+        idx = codec->codec_type == AVMEDIA_TYPE_AUDIO;
+
     /* dynamic payload type */
-    return RTP_PT_PRIVATE + (codec->codec_type == AVMEDIA_TYPE_AUDIO);
+    return RTP_PT_PRIVATE + idx;
 }
 
 const char *ff_rtp_enc_name(int payload_type)
diff --git a/libavformat/rtp.h b/libavformat/rtp.h
index fa3e1fa..1732af8 100644
--- a/libavformat/rtp.h
+++ b/libavformat/rtp.h
@@ -25,13 +25,18 @@
 #include "libavcodec/avcodec.h"
 
 /**
- * Return the payload type for a given codec used in the given format context.
+ * Return the payload type for a given stream used in the given format context.
+ * Static payload types are derived from the codec.
+ * Dynamic payload type are derived from the id field in AVStream.
+ * The format context private option payload_type overrides both.
  *
  * @param fmt   The context of the format
  * @param codec The context of the codec
+ * @param idx   The stream index
  * @return The payload type (the 'PT' field in the RTP header).
  */
-int ff_rtp_get_payload_type(AVFormatContext *fmt, AVCodecContext *codec);
+int ff_rtp_get_payload_type(AVFormatContext *fmt, AVCodecContext *codec,
+                            int idx);
 
 /**
  * Initialize a codec context based on the payload type.
@@ -84,13 +89,24 @@
 
 /* RTCP packet types */
 enum RTCPType {
+    RTCP_FIR    = 192,
+    RTCP_NACK, // 193
+    RTCP_SMPTETC,// 194
+    RTCP_IJ,   // 195
     RTCP_SR     = 200,
     RTCP_RR,   // 201
     RTCP_SDES, // 202
     RTCP_BYE,  // 203
-    RTCP_APP   // 204
+    RTCP_APP,  // 204
+    RTCP_RTPFB,// 205
+    RTCP_PSFB, // 206
+    RTCP_XR,   // 207
+    RTCP_AVB,  // 208
+    RTCP_RSI,  // 209
+    RTCP_TOKEN,// 210
 };
 
-#define RTP_PT_IS_RTCP(x) ((x) >= RTCP_SR && (x) <= RTCP_APP)
+#define RTP_PT_IS_RTCP(x) (((x) >= RTCP_FIR && (x) <= RTCP_IJ) || \
+                           ((x) >= RTCP_SR  && (x) <= RTCP_TOKEN))
 
 #endif /* AVFORMAT_RTP_H */
diff --git a/libavformat/rtpdec.c b/libavformat/rtpdec.c
index e044435..e92419d 100644
--- a/libavformat/rtpdec.c
+++ b/libavformat/rtpdec.c
@@ -55,6 +55,12 @@
     .codec_id         = AV_CODEC_ID_SPEEX,
 };
 
+static RTPDynamicProtocolHandler opus_dynamic_handler = {
+    .enc_name         = "opus",
+    .codec_type       = AVMEDIA_TYPE_AUDIO,
+    .codec_id         = AV_CODEC_ID_OPUS,
+};
+
 /* statistics functions */
 static RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler= NULL;
 
@@ -85,6 +91,7 @@
     ff_register_dynamic_payload_handler(&ff_qcelp_dynamic_handler);
     ff_register_dynamic_payload_handler(&realmedia_mp3_dynamic_handler);
     ff_register_dynamic_payload_handler(&speex_dynamic_handler);
+    ff_register_dynamic_payload_handler(&opus_dynamic_handler);
 
     ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfv_handler);
     ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfa_handler);
@@ -159,71 +166,67 @@
 
 #define RTP_SEQ_MOD (1<<16)
 
-/**
-* called on parse open packet
-*/
-static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence) // called on parse open packet.
+static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence)
 {
     memset(s, 0, sizeof(RTPStatistics));
-    s->max_seq= base_sequence;
-    s->probation= 1;
+    s->max_seq   = base_sequence;
+    s->probation = 1;
 }
 
-/**
+/*
 * called whenever there is a large jump in sequence numbers, or when they get out of probation...
 */
 static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
 {
-    s->max_seq= seq;
-    s->cycles= 0;
-    s->base_seq= seq -1;
-    s->bad_seq= RTP_SEQ_MOD + 1;
-    s->received= 0;
-    s->expected_prior= 0;
-    s->received_prior= 0;
-    s->jitter= 0;
-    s->transit= 0;
+    s->max_seq        = seq;
+    s->cycles         = 0;
+    s->base_seq       = seq - 1;
+    s->bad_seq        = RTP_SEQ_MOD + 1;
+    s->received       = 0;
+    s->expected_prior = 0;
+    s->received_prior = 0;
+    s->jitter         = 0;
+    s->transit        = 0;
 }
 
-/**
+/*
 * returns 1 if we should handle this packet.
 */
 static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
 {
-    uint16_t udelta= seq - s->max_seq;
-    const int MAX_DROPOUT= 3000;
-    const int MAX_MISORDER = 100;
+    uint16_t udelta = seq - s->max_seq;
+    const int MAX_DROPOUT    = 3000;
+    const int MAX_MISORDER   = 100;
     const int MIN_SEQUENTIAL = 2;
 
     /* source not valid until MIN_SEQUENTIAL packets with sequence seq. numbers have been received */
-    if(s->probation)
-    {
-        if(seq==s->max_seq + 1) {
+    if (s->probation) {
+        if (seq == s->max_seq + 1) {
             s->probation--;
-            s->max_seq= seq;
-            if(s->probation==0) {
+            s->max_seq = seq;
+            if (s->probation == 0) {
                 rtp_init_sequence(s, seq);
                 s->received++;
                 return 1;
             }
         } else {
-            s->probation= MIN_SEQUENTIAL - 1;
+            s->probation = MIN_SEQUENTIAL - 1;
             s->max_seq = seq;
         }
     } else if (udelta < MAX_DROPOUT) {
         // in order, with permissible gap
-        if(seq < s->max_seq) {
-            //sequence number wrapped; count antother 64k cycles
+        if (seq < s->max_seq) {
+            // sequence number wrapped; count another 64k cycles
             s->cycles += RTP_SEQ_MOD;
         }
-        s->max_seq= seq;
+        s->max_seq = seq;
     } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
         // sequence made a large jump...
-        if(seq==s->bad_seq) {
+        if (seq == s->bad_seq) {
             // two sequential packets-- assume that the other side restarted without telling us; just resync.
             rtp_init_sequence(s, seq);
         } else {
-            s->bad_seq= (seq + 1) & (RTP_SEQ_MOD-1);
+            s->bad_seq = (seq + 1) & (RTP_SEQ_MOD - 1);
             return 0;
         }
     } else {
@@ -239,7 +242,7 @@
     uint8_t *buf;
     int len;
     int rtcp_bytes;
-    RTPStatistics *stats= &s->statistics;
+    RTPStatistics *stats = &s->statistics;
     uint32_t lost;
     uint32_t extended_max;
     uint32_t expected_interval;
@@ -247,7 +250,7 @@
     uint32_t lost_interval;
     uint32_t expected;
     uint32_t fraction;
-    uint64_t ntp_time= s->last_rtcp_ntp_time; // TODO: Get local ntp time?
+    uint64_t ntp_time = s->last_rtcp_ntp_time; // TODO: Get local ntp time?
 
     if (!s->rtp_ctx || (count < 1))
         return -1;
@@ -274,31 +277,32 @@
     avio_wb32(pb, s->ssrc); // server SSRC
     // some placeholders we should really fill...
     // RFC 1889/p64
-    extended_max= stats->cycles + stats->max_seq;
-    expected= extended_max - stats->base_seq + 1;
-    lost= expected - stats->received;
-    lost= FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
-    expected_interval= expected - stats->expected_prior;
-    stats->expected_prior= expected;
-    received_interval= stats->received - stats->received_prior;
-    stats->received_prior= stats->received;
-    lost_interval= expected_interval - received_interval;
-    if (expected_interval==0 || lost_interval<=0) fraction= 0;
-    else fraction = (lost_interval<<8)/expected_interval;
+    extended_max = stats->cycles + stats->max_seq;
+    expected = extended_max - stats->base_seq + 1;
+    lost = expected - stats->received;
+    lost = FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
+    expected_interval = expected - stats->expected_prior;
+    stats->expected_prior = expected;
+    received_interval = stats->received - stats->received_prior;
+    stats->received_prior = stats->received;
+    lost_interval = expected_interval - received_interval;
+    if (expected_interval == 0 || lost_interval <= 0)
+        fraction = 0;
+    else
+        fraction = (lost_interval << 8) / expected_interval;
 
-    fraction= (fraction<<24) | lost;
+    fraction = (fraction << 24) | lost;
 
     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 */
+    avio_wb32(pb, stats->jitter >> 4); /* jitter */
 
-    if(s->last_rtcp_ntp_time==AV_NOPTS_VALUE)
-    {
+    if (s->last_rtcp_ntp_time == AV_NOPTS_VALUE) {
         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;
+        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;
 
         avio_wb32(pb, middle_32_bits); /* last SR timestamp */
         avio_wb32(pb, delay_since_last); /* delay since last SR */
@@ -424,9 +428,8 @@
     return s;
 }
 
-void
-ff_rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
-                                  RTPDynamicProtocolHandler *handler)
+void ff_rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
+                                       RTPDynamicProtocolHandler *handler)
 {
     s->dynamic_protocol_context = ctx;
     s->parse_packet = handler->parse_packet;
@@ -553,7 +556,8 @@
             h = AV_RB32(buf);
             len -= 4;
             buf += 4;
-            av_new_packet(pkt, len);
+            if (av_new_packet(pkt, len) < 0)
+                return AVERROR(ENOMEM);
             memcpy(pkt->data, buf, len);
             break;
         case AV_CODEC_ID_MPEG1VIDEO:
@@ -571,11 +575,13 @@
                 buf += 4;
                 len -= 4;
             }
-            av_new_packet(pkt, len);
+            if (av_new_packet(pkt, len) < 0)
+                return AVERROR(ENOMEM);
             memcpy(pkt->data, buf, len);
             break;
         default:
-            av_new_packet(pkt, len);
+            if (av_new_packet(pkt, len) < 0)
+                return AVERROR(ENOMEM);
             memcpy(pkt->data, buf, len);
             break;
         }
@@ -664,7 +670,7 @@
 }
 
 static int rtp_parse_one_packet(RTPDemuxContext *s, AVPacket *pkt,
-                     uint8_t **bufptr, int len)
+                                uint8_t **bufptr, int len)
 {
     uint8_t* buf = bufptr ? *bufptr : NULL;
     int ret, flags = 0;
@@ -778,7 +784,7 @@
     int value_size = strlen(p) + 1;
 
     if (!(value = av_malloc(value_size))) {
-        av_log(stream, AV_LOG_ERROR, "Failed to allocate data for FMTP.\n");
+        av_log(NULL, AV_LOG_ERROR, "Failed to allocate data for FMTP.\n");
         return AVERROR(ENOMEM);
     }
 
@@ -800,3 +806,14 @@
     av_free(value);
     return 0;
 }
+
+int ff_rtp_finalize_packet(AVPacket *pkt, AVIOContext **dyn_buf, int stream_idx)
+{
+    av_init_packet(pkt);
+
+    pkt->size = avio_close_dyn_buf(*dyn_buf, &pkt->data);
+    pkt->stream_index = stream_idx;
+    pkt->destruct     = av_destruct_packet;
+    *dyn_buf = NULL;
+    return pkt->size;
+}
diff --git a/libavformat/rtpdec.h b/libavformat/rtpdec.h
index 521b2f5..15d472a 100644
--- a/libavformat/rtpdec.h
+++ b/libavformat/rtpdec.h
@@ -72,7 +72,7 @@
 int ff_rtp_check_and_send_back_rr(RTPDemuxContext *s, int count);
 
 // these statistics are used for rtcp receiver reports...
-typedef struct {
+typedef struct RTPStatistics {
     uint16_t max_seq;           ///< highest sequence number seen
     uint32_t cycles;            ///< shifted count of sequence number cycles
     uint32_t base_seq;          ///< base sequence number
@@ -202,4 +202,9 @@
 
 void av_register_rtp_dynamic_payload_handlers(void);
 
+/**
+ * Close the dynamic buffer and make a packet from it.
+ */
+int ff_rtp_finalize_packet(AVPacket *pkt, AVIOContext **dyn_buf, int stream_idx);
+
 #endif /* AVFORMAT_RTPDEC_H */
diff --git a/libavformat/rtpdec_amr.c b/libavformat/rtpdec_amr.c
index 6051dce..3f5e775 100644
--- a/libavformat/rtpdec_amr.c
+++ b/libavformat/rtpdec_amr.c
@@ -19,6 +19,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "avformat.h"
 #include "rtpdec_formats.h"
 #include "libavutil/avstring.h"
@@ -77,6 +78,7 @@
         av_log(ctx, AV_LOG_ERROR, "Only mono AMR is supported\n");
         return AVERROR_INVALIDDATA;
     }
+    st->codec->channel_layout = AV_CH_LAYOUT_MONO;
 
     /* The AMR RTP packet consists of one header byte, followed
      * by one TOC byte for each AMR frame in the packet, followed
diff --git a/libavformat/rtpdec_h263_rfc2190.c b/libavformat/rtpdec_h263_rfc2190.c
index 163d4ea..4957b33 100644
--- a/libavformat/rtpdec_h263_rfc2190.c
+++ b/libavformat/rtpdec_h263_rfc2190.c
@@ -61,7 +61,7 @@
 {
     /* Corresponding to header fields in the RFC */
     int f, p, i, sbit, ebit, src, r;
-    int header_size;
+    int header_size, ret;
 
     if (data->newformat)
         return ff_h263_handle_packet(ctx, data, st, pkt, timestamp, buf, len,
@@ -133,7 +133,7 @@
         /* Check the picture start code, only start buffering a new frame
          * if this is correct */
         if (len > 4 && AV_RB32(buf) >> 10 == 0x20) {
-            int ret = avio_open_dyn_buf(&data->buf);
+            ret = avio_open_dyn_buf(&data->buf);
             if (ret < 0)
                 return ret;
             data->timestamp = *timestamp;
@@ -185,13 +185,11 @@
         avio_w8(data->buf, data->endbyte);
     data->endbyte_bits = 0;
 
-    av_init_packet(pkt);
-    pkt->size         = avio_close_dyn_buf(data->buf, &pkt->data);
-    pkt->destruct     = av_destruct_packet;
-    pkt->stream_index = st->index;
+    ret = ff_rtp_finalize_packet(pkt, &data->buf, st->index);
+    if (ret < 0)
+        return ret;
     if (!i)
         pkt->flags   |= AV_PKT_FLAG_KEY;
-    data->buf = NULL;
 
     return 0;
 }
diff --git a/libavformat/rtpdec_jpeg.c b/libavformat/rtpdec_jpeg.c
index fb68de9..447dd36 100644
--- a/libavformat/rtpdec_jpeg.c
+++ b/libavformat/rtpdec_jpeg.c
@@ -20,6 +20,7 @@
  */
 
 #include "avformat.h"
+#include "rtpdec.h"
 #include "rtpdec_formats.h"
 #include "libavutil/intreadwrite.h"
 #include "libavcodec/mjpeg.h"
@@ -367,19 +368,11 @@
         avio_write(jpeg->frame, buf, sizeof(buf));
 
         /* Prepare the JPEG packet. */
-        av_init_packet(pkt);
-        pkt->size = avio_close_dyn_buf(jpeg->frame, &pkt->data);
-        if (pkt->size < 0) {
+        if ((ret = ff_rtp_finalize_packet(pkt, &jpeg->frame, st->index)) < 0) {
             av_log(ctx, AV_LOG_ERROR,
                    "Error occured when getting frame buffer.\n");
-            jpeg->frame = NULL;
-            return pkt->size;
+            return ret;
         }
-        pkt->stream_index = st->index;
-        pkt->destruct     = av_destruct_packet;
-
-        /* Re-init the frame buffer. */
-        jpeg->frame = NULL;
 
         return 0;
     }
diff --git a/libavformat/rtpdec_mpeg4.c b/libavformat/rtpdec_mpeg4.c
index 7b16d12..a647169 100644
--- a/libavformat/rtpdec_mpeg4.c
+++ b/libavformat/rtpdec_mpeg4.c
@@ -93,15 +93,7 @@
 
 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->au_headers);
     av_free(data->mode);
     av_free(data);
 }
diff --git a/libavformat/rtpdec_qdm2.c b/libavformat/rtpdec_qdm2.c
index f203fcf..3a8ffd5 100644
--- a/libavformat/rtpdec_qdm2.c
+++ b/libavformat/rtpdec_qdm2.c
@@ -26,6 +26,7 @@
  */
 
 #include <string.h>
+#include "libavutil/avassert.h"
 #include "libavutil/intreadwrite.h"
 #include "libavcodec/avcodec.h"
 #include "rtp.h"
@@ -193,7 +194,7 @@
     for (n = 0; n < 0x80; n++)
         if (qdm->len[n] > 0)
             break;
-    assert(n < 0x80);
+    av_assert0(n < 0x80);
 
     if ((res = av_new_packet(pkt, qdm->block_size)) < 0)
         return res;
diff --git a/libavformat/rtpdec_qt.c b/libavformat/rtpdec_qt.c
index 4decdca..f0f01d9 100644
--- a/libavformat/rtpdec_qt.c
+++ b/libavformat/rtpdec_qt.c
@@ -99,7 +99,7 @@
         if (!is_start || !is_finish) {
             av_log_missing_feature(s, "RTP-X-QT with payload description "
                                       "split over several packets", 1);
-            return AVERROR(ENOSYS);
+            return AVERROR_PATCHWELCOME;
         }
         skip_bits(&gb, 12); // reserved
         data_len = get_bits(&gb, 16);
@@ -162,7 +162,7 @@
 
     if (has_packet_info) {
         av_log_missing_feature(s, "RTP-X-QT with packet specific info", 1);
-        return AVERROR(ENOSYS);
+        return AVERROR_PATCHWELCOME;
     }
 
     alen = len - avio_tell(&pb);
@@ -225,7 +225,7 @@
 
     default:  /* unimplemented */
         av_log_missing_feature(NULL, "RTP-X-QT with packing scheme 2", 1);
-        return AVERROR(ENOSYS);
+        return AVERROR_PATCHWELCOME;
     }
 }
 
diff --git a/libavformat/rtpdec_svq3.c b/libavformat/rtpdec_svq3.c
index 99c4c52..779ad8a 100644
--- a/libavformat/rtpdec_svq3.c
+++ b/libavformat/rtpdec_svq3.c
@@ -97,12 +97,11 @@
     avio_write(sv->pktbuf, buf, len);
 
     if (end_packet) {
-        av_init_packet(pkt);
-        pkt->stream_index = st->index;
+        int ret = ff_rtp_finalize_packet(pkt, &sv->pktbuf, st->index);
+        if (ret < 0)
+            return ret;
+
         *timestamp        = sv->timestamp;
-        pkt->size         = avio_close_dyn_buf(sv->pktbuf, &pkt->data);
-        pkt->destruct     = av_destruct_packet;
-        sv->pktbuf        = NULL;
         return 0;
     }
 
diff --git a/libavformat/rtpdec_vp8.c b/libavformat/rtpdec_vp8.c
index e24bbb6..1edc152 100644
--- a/libavformat/rtpdec_vp8.c
+++ b/libavformat/rtpdec_vp8.c
@@ -1,6 +1,7 @@
 /*
  * RTP VP8 Depacketizer
  * Copyright (c) 2010 Josh Allmann
+ * Copyright (c) 2012 Martin Storsjo
  *
  * This file is part of FFmpeg.
  *
@@ -23,7 +24,7 @@
  * @file
  * @brief RTP support for the VP8 payload
  * @author Josh Allmann <joshua.allmann@gmail.com>
- * @see http://www.webmproject.org/code/specs/rtp/
+ * @see http://tools.ietf.org/html/draft-ietf-payload-vp8-05
  */
 
 #include "libavcodec/bytestream.h"
@@ -33,19 +34,8 @@
 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,
@@ -54,73 +44,76 @@
                              const uint8_t *buf,
                              int len, int flags)
 {
-    int start_packet, end_packet, has_au, ret = AVERROR(EAGAIN);
+    int start_partition, end_packet;
+    int extended_bits, part_id;
+    int pictureid_present = 0, tl0picidx_present = 0, tid_present = 0,
+        keyidx_present = 0;
 
-    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;
-    }
+    if (len < 1)
+        return AVERROR_INVALIDDATA;
 
-    start_packet = *buf & 1;
-    end_packet   = flags & RTP_FLAG_MARKER;
-    has_au       = *buf & 2;
+    extended_bits   = buf[0] & 0x80;
+    start_partition = buf[0] & 0x10;
+    part_id         = buf[0] & 0x0f;
+    end_packet      = flags & RTP_FLAG_MARKER;
     buf++;
     len--;
+    if (extended_bits) {
+        if (len < 1)
+            return AVERROR_INVALIDDATA;
+        pictureid_present = buf[0] & 0x80;
+        tl0picidx_present = buf[0] & 0x40;
+        tid_present       = buf[0] & 0x20;
+        keyidx_present    = buf[0] & 0x10;
+        buf++;
+        len--;
+    }
+    if (pictureid_present) {
+        int size;
+        if (len < 1)
+            return AVERROR_INVALIDDATA;
+        size = buf[0] & 0x80 ? 2 : 1;
+        buf += size;
+        len -= size;
+    }
+    if (tl0picidx_present) {
+        // Ignoring temporal level zero index
+        buf++;
+        len--;
+    }
+    if (tid_present || keyidx_present) {
+        // Ignoring temporal layer index, layer sync bit and keyframe index
+        buf++;
+        len--;
+    }
+    if (len < 1)
+        return AVERROR_INVALIDDATA;
 
-    if (start_packet) {
+    if (start_partition && part_id == 0) {
         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;
+            uint8_t *tmp;
+            avio_close_dyn_buf(vp8->data, &tmp);
+            av_free(tmp);
+            vp8->data = NULL;
         }
         if ((res = avio_open_dyn_buf(&vp8->data)) < 0)
             return res;
-        vp8->is_keyframe = *buf & 1;
-        vp8->timestamp   = ts;
+        vp8->timestamp = *timestamp;
      }
 
-    if (!vp8->data || vp8->timestamp != *timestamp && ret == AVERROR(EAGAIN)) {
+    if (!vp8->data || vp8->timestamp != *timestamp) {
         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;
+    avio_write(vp8->data, buf, len);
 
     if (end_packet) {
-        prepare_packet(pkt, vp8, st->index);
+        int ret = ff_rtp_finalize_packet(pkt, &vp8->data, st->index);
+        if (ret < 0)
+            return ret;
         return 0;
     }
 
@@ -129,8 +122,6 @@
 
 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));
 }
 
diff --git a/libavformat/rtpdec_xiph.c b/libavformat/rtpdec_xiph.c
index 097d1a3..ad24c26 100644
--- a/libavformat/rtpdec_xiph.c
+++ b/libavformat/rtpdec_xiph.c
@@ -201,20 +201,13 @@
 
         if (fragmented == 3) {
             // end of xiph data packet
-            av_init_packet(pkt);
-            pkt->size = avio_close_dyn_buf(data->fragment, &pkt->data);
-
-            if (pkt->size < 0) {
+            int ret = ff_rtp_finalize_packet(pkt, &data->fragment, st->index);
+            if (ret < 0) {
                 av_log(ctx, AV_LOG_ERROR,
                        "Error occurred when getting fragment buffer.");
-                return pkt->size;
+                return ret;
             }
 
-            pkt->stream_index = st->index;
-            pkt->destruct = av_destruct_packet;
-
-            data->fragment = NULL;
-
             return 0;
         }
     }
@@ -242,7 +235,7 @@
 /**
  * Based off parse_packed_headers in Vorbis RTP
  */
-static unsigned int
+static int
 parse_packed_headers(const uint8_t * packed_headers,
                      const uint8_t * packed_headers_end,
                      AVCodecContext * codec, PayloadContext * xiph_data)
@@ -312,11 +305,11 @@
 
     if (!strcmp(attr, "sampling")) {
         if (!strcmp(value, "YCbCr-4:2:0")) {
-            codec->pix_fmt = PIX_FMT_YUV420P;
+            codec->pix_fmt = AV_PIX_FMT_YUV420P;
         } else if (!strcmp(value, "YCbCr-4:4:2")) {
-            codec->pix_fmt = PIX_FMT_YUV422P;
+            codec->pix_fmt = AV_PIX_FMT_YUV422P;
         } else if (!strcmp(value, "YCbCr-4:4:4")) {
-            codec->pix_fmt = PIX_FMT_YUV444P;
+            codec->pix_fmt = AV_PIX_FMT_YUV444P;
         } else {
             av_log(codec, AV_LOG_ERROR,
                    "Unsupported pixel format %s\n", attr);
diff --git a/libavformat/rtpenc.c b/libavformat/rtpenc.c
index ea678a6..0010a92 100644
--- a/libavformat/rtpenc.c
+++ b/libavformat/rtpenc.c
@@ -77,6 +77,7 @@
     case AV_CODEC_ID_ILBC:
     case AV_CODEC_ID_MJPEG:
     case AV_CODEC_ID_SPEEX:
+    case AV_CODEC_ID_OPUS:
         return 1;
     default:
         return 0;
@@ -100,8 +101,17 @@
         return -1;
     }
 
-    if (s->payload_type < 0)
-        s->payload_type = ff_rtp_get_payload_type(s1, st->codec);
+    if (s->payload_type < 0) {
+        /* Re-validate non-dynamic payload types */
+        if (st->id < RTP_PT_PRIVATE)
+            st->id = ff_rtp_get_payload_type(s1, st->codec, -1);
+
+        s->payload_type = st->id;
+    } else {
+        /* private option takes priority */
+        st->id = s->payload_type;
+    }
+
     s->base_timestamp = av_get_random_seed();
     s->timestamp = s->base_timestamp;
     s->cur_timestamp = 0;
@@ -181,15 +191,21 @@
         s->max_payload_size -= 6; // ident+frag+tdt/vdt+pkt_num+pkt_length
         s->num_frames = 0;
         goto defaultcase;
-    case AV_CODEC_ID_VP8:
-        av_log(s1, AV_LOG_ERROR, "RTP VP8 payload implementation is "
-                                 "incompatible with the latest spec drafts.\n");
-        break;
     case AV_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. */
         avpriv_set_pts_info(st, 32, 1, 8000);
         break;
+    case AV_CODEC_ID_OPUS:
+        if (st->codec->channels > 2) {
+            av_log(s1, AV_LOG_ERROR, "Multistream opus not supported in RTP\n");
+            goto fail;
+        }
+        /* The opus RTP RFC says that all opus streams should use 48000 Hz
+         * as clock rate, since all opus sample rates can be expressed in
+         * this clock rate, and sample rate changes on the fly are supported. */
+        avpriv_set_pts_info(st, 32, 1, 48000);
+        break;
     case AV_CODEC_ID_ILBC:
         if (st->codec->block_align != 38 && st->codec->block_align != 50) {
             av_log(s1, AV_LOG_ERROR, "Incorrect iLBC block size specified\n");
@@ -529,6 +545,14 @@
     case AV_CODEC_ID_MJPEG:
         ff_rtp_send_jpeg(s1, pkt->data, size);
         break;
+    case AV_CODEC_ID_OPUS:
+        if (size > s->max_payload_size) {
+            av_log(s1, AV_LOG_ERROR,
+                   "Packet size %d too large for max RTP payload size %d\n",
+                   size, s->max_payload_size);
+            return AVERROR(EINVAL);
+        }
+        /* Intentional fallthrough */
     default:
         /* better than nothing : send the codec raw data */
         rtp_send_raw(s1, pkt->data, size);
diff --git a/libavformat/rtpenc_aac.c b/libavformat/rtpenc_aac.c
index e19b286..be8f43a 100644
--- a/libavformat/rtpenc_aac.c
+++ b/libavformat/rtpenc_aac.c
@@ -47,8 +47,8 @@
             memmove(p + 2, s->buf + 2, au_size);
         }
         /* Write the AU header size */
-        p[0] = ((au_size * 8) & 0xFF) >> 8;
-        p[1] = (au_size * 8) & 0xFF;
+        p[0] =  au_size >> 5;
+        p[1] = (au_size & 0x1F) << 3;
 
         ff_rtp_send_data(s1, p, s->buf_ptr - p, 1);
 
diff --git a/libavformat/rtpenc_chain.c b/libavformat/rtpenc_chain.c
index c0f9530..df7410d 100644
--- a/libavformat/rtpenc_chain.c
+++ b/libavformat/rtpenc_chain.c
@@ -23,10 +23,12 @@
 #include "avio_internal.h"
 #include "rtpenc_chain.h"
 #include "avio_internal.h"
+#include "rtp.h"
 #include "libavutil/opt.h"
 
 int ff_rtp_chain_mux_open(AVFormatContext **out, AVFormatContext *s,
-                          AVStream *st, URLContext *handle, int packet_size)
+                          AVStream *st, URLContext *handle, int packet_size,
+                          int idx)
 {
     AVFormatContext *rtpctx = NULL;
     int ret;
@@ -59,6 +61,14 @@
     rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio;
     rtpctx->flags |= s->flags & AVFMT_FLAG_MP4A_LATM;
 
+    /* Get the payload type from the codec */
+    if (st->id < RTP_PT_PRIVATE)
+        rtpctx->streams[0]->id =
+            ff_rtp_get_payload_type(rtpctx, st->codec, idx);
+    else
+        rtpctx->streams[0]->id = st->id;
+
+
     if (av_opt_get(s, "rtpflags", AV_OPT_SEARCH_CHILDREN, &rtpflags) >= 0)
         av_dict_set(&opts, "rtpflags", rtpflags, AV_DICT_DONT_STRDUP_VAL);
 
diff --git a/libavformat/rtpenc_chain.h b/libavformat/rtpenc_chain.h
index 1ba3617..21c27c1 100644
--- a/libavformat/rtpenc_chain.h
+++ b/libavformat/rtpenc_chain.h
@@ -26,6 +26,7 @@
 #include "url.h"
 
 int ff_rtp_chain_mux_open(AVFormatContext **out, AVFormatContext *s,
-                          AVStream *st, URLContext *handle, int packet_size);
+                          AVStream *st, URLContext *handle, int packet_size,
+                          int id);
 
 #endif /* AVFORMAT_RTPENC_CHAIN_H */
diff --git a/libavformat/rtpenc_jpeg.c b/libavformat/rtpenc_jpeg.c
index b2cfb8d..7eb0e23 100644
--- a/libavformat/rtpenc_jpeg.c
+++ b/libavformat/rtpenc_jpeg.c
@@ -29,7 +29,7 @@
     RTPMuxContext *s = s1->priv_data;
     const uint8_t *qtables = NULL;
     int nb_qtables = 0;
-    uint8_t type = 1; /* default pixel format is PIX_FMT_YUVJ420P */
+    uint8_t type = 1; /* default pixel format is AV_PIX_FMT_YUVJ420P */
     uint8_t w, h;
     uint8_t *p;
     int off = 0; /* fragment offset of the current JPEG frame */
@@ -44,9 +44,9 @@
     h = s1->streams[0]->codec->height >> 3;
 
     /* check if pixel format is not the normal 420 case */
-    if (s1->streams[0]->codec->pix_fmt == PIX_FMT_YUVJ422P) {
+    if (s1->streams[0]->codec->pix_fmt == AV_PIX_FMT_YUVJ422P) {
         type = 0;
-    } else if (s1->streams[0]->codec->pix_fmt == PIX_FMT_YUVJ420P) {
+    } else if (s1->streams[0]->codec->pix_fmt == AV_PIX_FMT_YUVJ420P) {
         type = 1;
     } else {
         av_log(s1, AV_LOG_ERROR, "Unsupported pixel format\n");
diff --git a/libavformat/rtpenc_vp8.c b/libavformat/rtpenc_vp8.c
index e865514..d16e676 100644
--- a/libavformat/rtpenc_vp8.c
+++ b/libavformat/rtpenc_vp8.c
@@ -22,7 +22,7 @@
 #include "rtpenc.h"
 
 /* Based on a draft spec for VP8 RTP.
- * ( http://www.webmproject.org/code/specs/rtp/ ) */
+ * ( http://tools.ietf.org/html/draft-ietf-payload-vp8-05 ) */
 void ff_rtp_send_vp8(AVFormatContext *s1, const uint8_t *buf, int size)
 {
     RTPMuxContext *s = s1->priv_data;
@@ -32,7 +32,9 @@
     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
+    // no extended control bits, reference frame, start of partition,
+    // partition id 0
+    *s->buf_ptr++ = 0x10;
     while (size > 0) {
         len = FFMIN(size, max_packet_size);
 
diff --git a/libavformat/rtsp.c b/libavformat/rtsp.c
index 80f1047..04ea47c 100644
--- a/libavformat/rtsp.c
+++ b/libavformat/rtsp.c
@@ -75,6 +75,9 @@
     { "audio", "Audio", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_AUDIO}, 0, 0, DEC, "allowed_media_types" }, \
     { "data", "Data", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_DATA}, 0, 0, DEC, "allowed_media_types" }
 
+#define RTSP_REORDERING_OPTS() \
+    { "reorder_queue_size", "Number of packets to buffer for handling of reordered packets", OFFSET(reordering_queue_size), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, DEC }
+
 const AVOption ff_rtsp_options[] = {
     { "initial_pause",  "Don't start playing the stream immediately", OFFSET(initial_pause), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, DEC },
     FF_RTP_FLAG_OPTS(RTSPState, rtp_muxer_flags),
@@ -88,17 +91,20 @@
     { "min_port", "Minimum local UDP port", OFFSET(rtp_port_min), AV_OPT_TYPE_INT, {.i64 = RTSP_RTP_PORT_MIN}, 0, 65535, DEC|ENC },
     { "max_port", "Maximum local UDP port", OFFSET(rtp_port_max), AV_OPT_TYPE_INT, {.i64 = RTSP_RTP_PORT_MAX}, 0, 65535, DEC|ENC },
     { "timeout", "Maximum timeout (in seconds) to wait for incoming connections. -1 is infinite. Implies flag listen", OFFSET(initial_timeout), AV_OPT_TYPE_INT, {.i64 = -1}, INT_MIN, INT_MAX, DEC },
+    RTSP_REORDERING_OPTS(),
     { NULL },
 };
 
 static const AVOption sdp_options[] = {
     RTSP_FLAG_OPTS("sdp_flags", "SDP flags"),
     RTSP_MEDIATYPE_OPTS("allowed_media_types", "Media types to accept from the server"),
+    RTSP_REORDERING_OPTS(),
     { NULL },
 };
 
 static const AVOption rtp_options[] = {
     RTSP_FLAG_OPTS("rtp_flags", "RTP flags"),
+    RTSP_REORDERING_OPTS(),
     { NULL },
 };
 
@@ -608,6 +614,13 @@
 {
     RTSPState *rt = s->priv_data;
     AVStream *st = NULL;
+    int reordering_queue_size = rt->reordering_queue_size;
+    if (reordering_queue_size < 0) {
+        if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)
+            reordering_queue_size = 0;
+        else
+            reordering_queue_size = RTP_REORDER_QUEUE_DEFAULT_SIZE;
+    }
 
     /* open the RTP context */
     if (rtsp_st->stream_index >= 0)
@@ -618,7 +631,8 @@
     if (s->oformat && CONFIG_RTSP_MUXER) {
         int ret = ff_rtp_chain_mux_open((AVFormatContext **)&rtsp_st->transport_priv, s, st,
                                         rtsp_st->rtp_handle,
-                                        RTSP_TCP_MAX_PACKET_SIZE);
+                                        RTSP_TCP_MAX_PACKET_SIZE,
+                                        rtsp_st->stream_index);
         /* Ownership of rtp_handle is passed to the rtp mux context */
         rtsp_st->rtp_handle = NULL;
         if (ret < 0)
@@ -632,8 +646,7 @@
     else if (CONFIG_RTPDEC)
         rtsp_st->transport_priv = ff_rtp_parse_open(s, st, rtsp_st->rtp_handle,
                                          rtsp_st->sdp_payload_type,
-            (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)
-            ? 0 : RTP_REORDER_QUEUE_DEFAULT_SIZE);
+                                         reordering_queue_size);
 
     if (!rtsp_st->transport_priv) {
          return AVERROR(ENOMEM);
@@ -754,8 +767,10 @@
                     th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
             } else if (!strcmp(parameter, "ttl")) {
                 if (*p == '=') {
+                    char *end;
                     p++;
-                    th->ttl = strtol(p, (char **)&p, 10);
+                    th->ttl = strtol(p, &end, 10);
+                    p = end;
                 }
             } else if (!strcmp(parameter, "destination")) {
                 if (*p == '=') {
@@ -1793,7 +1808,7 @@
                 ret = rt->recvbuf_pos < rt->recvbuf_len;
             }
         } else
-            av_assert0(0);
+            ret = -1;
         if (ret == 0) {
             rt->cur_transport_priv = NULL;
             return 0;
diff --git a/libavformat/rtsp.h b/libavformat/rtsp.h
index e55073c..3a5ad71 100644
--- a/libavformat/rtsp.h
+++ b/libavformat/rtsp.h
@@ -385,12 +385,17 @@
      * Timeout to wait for incoming connections.
      */
     int initial_timeout;
+
+    /**
+     * Size of RTP packet reordering queue.
+     */
+    int reordering_queue_size;
 } RTSPState;
 
 #define RTSP_FLAG_FILTER_SRC  0x1    /**< Filter incoming UDP packets -
                                           receive packets only from the right
                                           source address and port. */
-#define RTSP_FLAG_LISTEN 0x2         /**< Wait for incoming connections. */
+#define RTSP_FLAG_LISTEN      0x2    /**< Wait for incoming connections. */
 
 /**
  * Describe a single stream, as identified by a single m= line block in the
@@ -419,7 +424,7 @@
     int sdp_payload_type;     /**< payload type */
     //@}
 
-    /** The following are used for dynamic protocols (rtp_*.c/rdt.c) */
+    /** The following are used for dynamic protocols (rtpdec_*.c/rdt.c) */
     //@{
     /** handler structure */
     RTPDynamicProtocolHandler *dynamic_handler;
diff --git a/libavformat/rtspdec.c b/libavformat/rtspdec.c
index 856be56..da571a8 100644
--- a/libavformat/rtspdec.c
+++ b/libavformat/rtspdec.c
@@ -76,8 +76,8 @@
 
     do {
         ret = ffurl_read_complete(rt->rtsp_hd, rbuf + idx, 1);
-        if (ret < 0)
-            return ret;
+        if (ret <= 0)
+            return ret ? ret : AVERROR_EOF;
         if (rbuf[idx] == '\r') {
             /* Ignore */
         } else if (rbuf[idx] == '\n') {
@@ -436,7 +436,7 @@
         if (*methodcode == ANNOUNCE) {
             av_log(s, AV_LOG_INFO,
                    "Updating control URI to %s\n", uri);
-            strcpy(rt->control_uri, uri);
+            av_strlcpy(rt->control_uri, uri, sizeof(rt->control_uri));
         }
     }
 
@@ -621,6 +621,10 @@
     /* ff_url_join. No authorization by now (NULL) */
     ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL, host,
                 port, "%s", path);
+
+    if (port < 0)
+        port = RTSP_DEFAULT_PORT;
+
     /* Create TCP connection */
     ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port,
                 "?listen&listen_timeout=%d", rt->initial_timeout * 1000);
diff --git a/libavformat/samidec.c b/libavformat/samidec.c
index 5f29364..85fd220 100644
--- a/libavformat/samidec.c
+++ b/libavformat/samidec.c
@@ -112,6 +112,14 @@
     return ff_subtitles_queue_read_packet(&sami->q, pkt);
 }
 
+static int sami_read_seek(AVFormatContext *s, int stream_index,
+                          int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
+{
+    SAMIContext *sami = s->priv_data;
+    return ff_subtitles_queue_seek(&sami->q, s, stream_index,
+                                   min_ts, ts, max_ts, flags);
+}
+
 static int sami_read_close(AVFormatContext *s)
 {
     SAMIContext *sami = s->priv_data;
@@ -126,6 +134,7 @@
     .read_probe     = sami_probe,
     .read_header    = sami_read_header,
     .read_packet    = sami_read_packet,
+    .read_seek2     = sami_read_seek,
     .read_close     = sami_read_close,
     .flags          = AVFMT_GENERIC_INDEX,
     .extensions     = "smi,sami",
diff --git a/libavformat/sapenc.c b/libavformat/sapenc.c
index 3de615d..7abfd50 100644
--- a/libavformat/sapenc.c
+++ b/libavformat/sapenc.c
@@ -151,7 +151,7 @@
             ret = AVERROR(EIO);
             goto fail;
         }
-        ret = ff_rtp_chain_mux_open(&contexts[i], s, s->streams[i], fd, 0);
+        ret = ff_rtp_chain_mux_open(&contexts[i], s, s->streams[i], fd, 0, i);
         if (ret < 0)
             goto fail;
         s->streams[i]->priv_data = contexts[i];
diff --git a/libavformat/sbgdec.c b/libavformat/sbgdec.c
index 93c8cb3..30c3b49 100644
--- a/libavformat/sbgdec.c
+++ b/libavformat/sbgdec.c
@@ -488,7 +488,7 @@
 
 static int parse_fade(struct sbg_parser *p, struct sbg_fade *fr)
 {
-    struct sbg_fade f;
+    struct sbg_fade f = {0};
 
     if (lex_char(p, '<'))
         f.in = SBG_FADE_SILENCE;
@@ -946,7 +946,7 @@
     struct sbg_script_event *ev;
 
     if (tseq->lock++) {
-        av_log(log, 16, "Recursion loop on \"%.*s\"\n",
+        av_log(log, AV_LOG_ERROR, "Recursion loop on \"%.*s\"\n",
                tseq->name_len, tseq->name);
         return AVERROR(EINVAL);
     }
@@ -957,7 +957,7 @@
             break;
     }
     if (i >= s->nb_def) {
-        av_log(log, 16, "Tone-set \"%.*s\" not defined\n",
+        av_log(log, AV_LOG_ERROR, "Tone-set \"%.*s\" not defined\n",
                tseq->name_len, tseq->name);
         return AVERROR(EINVAL);
     }
diff --git a/libavformat/sctp.c b/libavformat/sctp.c
index b8ab63e..7fbc11f 100644
--- a/libavformat/sctp.c
+++ b/libavformat/sctp.c
@@ -121,7 +121,7 @@
     outmsg.msg_name       = NULL;
     outmsg.msg_namelen    = 0;
     outmsg.msg_iov        = &iov;
-    iov.iov_base          = msg;
+    iov.iov_base          = (void*)msg;
     iov.iov_len           = len;
     outmsg.msg_iovlen     = 1;
     outmsg.msg_controllen = 0;
diff --git a/libavformat/sdp.c b/libavformat/sdp.c
index 30941b7..cdc3e21 100644
--- a/libavformat/sdp.c
+++ b/libavformat/sdp.c
@@ -521,13 +521,13 @@
                 return NULL;
 
             switch (c->pix_fmt) {
-            case PIX_FMT_YUV420P:
+            case AV_PIX_FMT_YUV420P:
                 pix_fmt = "YCbCr-4:2:0";
                 break;
-            case PIX_FMT_YUV422P:
+            case AV_PIX_FMT_YUV422P:
                 pix_fmt = "YCbCr-4:2:2";
                 break;
-            case PIX_FMT_YUV444P:
+            case AV_PIX_FMT_YUV444P:
                 pix_fmt = "YCbCr-4:4:4";
                 break;
             default:
@@ -575,6 +575,24 @@
         case AV_CODEC_ID_SPEEX:
             av_strlcatf(buff, size, "a=rtpmap:%d speex/%d\r\n",
                                      payload_type, c->sample_rate);
+            if (c->codec) {
+                const char *mode;
+                uint64_t vad_option;
+
+                if (c->flags & CODEC_FLAG_QSCALE)
+                      mode = "on";
+                else if (!av_opt_get_int(c, "vad", AV_OPT_FLAG_ENCODING_PARAM, &vad_option) && vad_option)
+                      mode = "vad";
+                else
+                      mode = "off";
+
+                av_strlcatf(buff, size, "a=fmtp:%d vbr=%s\r\n",
+                                        payload_type, mode);
+            }
+            break;
+        case AV_CODEC_ID_OPUS:
+            av_strlcatf(buff, size, "a=rtpmap:%d opus/48000\r\n",
+                                     payload_type);
             break;
         default:
             /* Nothing special to do here... */
@@ -586,12 +604,15 @@
     return buff;
 }
 
-void ff_sdp_write_media(char *buff, int size, AVCodecContext *c, const char *dest_addr, const char *dest_type, int port, int ttl, AVFormatContext *fmt)
+void ff_sdp_write_media(char *buff, int size, AVStream *st, int idx,
+                        const char *dest_addr, const char *dest_type,
+                        int port, int ttl, AVFormatContext *fmt)
 {
+    AVCodecContext *c = st->codec;
     const char *type;
     int payload_type;
 
-    payload_type = ff_rtp_get_payload_type(fmt, c);
+    payload_type = ff_rtp_get_payload_type(fmt, c, idx);
 
     switch (c->codec_type) {
         case AVMEDIA_TYPE_VIDEO   : type = "video"      ; break;
@@ -613,7 +634,7 @@
 {
     AVDictionaryEntry *title = av_dict_get(ac[0]->metadata, "title", NULL, 0);
     struct sdp_session_level s = { 0 };
-    int i, j, port, ttl, is_multicast;
+    int i, j, port, ttl, is_multicast, index = 0;
     char dst[32], dst_type[5];
 
     memset(buf, 0, size);
@@ -652,10 +673,10 @@
                 ttl = 0;
         }
         for (j = 0; j < ac[i]->nb_streams; j++) {
-            ff_sdp_write_media(buf, size,
-                                  ac[i]->streams[j]->codec, dst[0] ? dst : NULL,
-                                  dst_type, (port > 0) ? port + j * 2 : 0, ttl,
-                                  ac[i]);
+            ff_sdp_write_media(buf, size, ac[i]->streams[j], index++,
+                               dst[0] ? dst : NULL, dst_type,
+                               (port > 0) ? port + j * 2 : 0,
+                               ttl, ac[i]);
             if (port <= 0) {
                 av_strlcatf(buf, size,
                                    "a=control:streamid=%d\r\n", i + j);
@@ -671,7 +692,9 @@
     return AVERROR(ENOSYS);
 }
 
-void ff_sdp_write_media(char *buff, int size, AVCodecContext *c, const char *dest_addr, const char *dest_type, int port, int ttl, AVFormatContext *fmt)
+void ff_sdp_write_media(char *buff, int size, AVStream *st, int idx,
+                        const char *dest_addr, const char *dest_type,
+                        int port, int ttl, AVFormatContext *fmt)
 {
 }
 #endif
diff --git a/libavformat/segafilm.c b/libavformat/segafilm.c
index d497d7b..a33ad85 100644
--- a/libavformat/segafilm.c
+++ b/libavformat/segafilm.c
@@ -113,7 +113,7 @@
         film->audio_samplerate = AV_RB16(&scratch[24]);
         film->audio_channels = scratch[21];
         film->audio_bits = scratch[22];
-        if (scratch[23] == 2)
+        if (scratch[23] == 2 && film->audio_channels > 0)
             film->audio_type = AV_CODEC_ID_ADPCM_ADX;
         else if (film->audio_channels > 0) {
             if (film->audio_bits == 8)
@@ -151,7 +151,7 @@
 
         if (film->video_type == AV_CODEC_ID_RAWVIDEO) {
             if (scratch[20] == 24) {
-                st->codec->pix_fmt = PIX_FMT_RGB24;
+                st->codec->pix_fmt = AV_PIX_FMT_RGB24;
             } else {
                 av_log(s, AV_LOG_ERROR, "raw video is using unhandled %dbpp\n", scratch[20]);
                 return -1;
@@ -248,7 +248,7 @@
     int left, right;
 
     if (film->current_sample >= film->sample_count)
-        return AVERROR(EIO);
+        return AVERROR_EOF;
 
     sample = &film->sample_table[film->current_sample];
 
diff --git a/libavformat/segment.c b/libavformat/segment.c
index 05d0db7..1ad410e 100644
--- a/libavformat/segment.c
+++ b/libavformat/segment.c
@@ -54,10 +54,10 @@
     int segment_idx;       ///< index of the segment file to write, starting from 0
     int segment_idx_wrap;  ///< number after which the index wraps
     int segment_count;     ///< number of segment files already written
+    AVOutputFormat *oformat;
     AVFormatContext *avf;
     char *format;          ///< format to use for output segment files
     char *list;            ///< filename for the segment list file
-    int   list_count;      ///< list counter
     int   list_flags;      ///< flags affecting list generation
     int   list_size;       ///< number of entries for the segment list file
     double list_max_segment_time; ///< max segment time in the current list
@@ -70,6 +70,8 @@
     int nb_times;          ///< number of elments in the times array
     char *time_delta_str;  ///< approximation value duration used for the segment times
     int64_t time_delta;
+    int  individual_header_trailer; /**< Set by a private option. */
+    int  write_header_trailer; /**< Set by a private option. */
     int has_video;
     double start_time, end_time;
 } SegmentContext;
@@ -90,17 +92,61 @@
         avio_w8(ctx, '"');
 }
 
-static int segment_start(AVFormatContext *s)
+static int segment_mux_init(AVFormatContext *s)
+{
+    SegmentContext *seg = s->priv_data;
+    AVFormatContext *oc;
+    int i;
+
+    seg->avf = oc = avformat_alloc_context();
+    if (!oc)
+        return AVERROR(ENOMEM);
+
+    oc->oformat            = seg->oformat;
+    oc->interrupt_callback = s->interrupt_callback;
+
+    for (i = 0; i < s->nb_streams; i++) {
+        AVStream *st;
+        AVCodecContext *icodec, *ocodec;
+
+        if (!(st = avformat_new_stream(oc, NULL)))
+            return AVERROR(ENOMEM);
+        icodec = s->streams[i]->codec;
+        ocodec = st->codec;
+        avcodec_copy_context(ocodec, icodec);
+        if (!oc->oformat->codec_tag ||
+            av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == ocodec->codec_id ||
+            av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0) {
+            ocodec->codec_tag = icodec->codec_tag;
+        } else {
+            ocodec->codec_tag = 0;
+        }
+        st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
+    }
+
+    return 0;
+}
+
+static int segment_start(AVFormatContext *s, int write_header)
 {
     SegmentContext *seg = s->priv_data;
     AVFormatContext *oc = seg->avf;
     int err = 0;
 
+    if (write_header) {
+        avformat_free_context(oc);
+        seg->avf = NULL;
+        if ((err = segment_mux_init(s)) < 0)
+            return err;
+        oc = seg->avf;
+    }
+
+    seg->segment_idx++;
     if (seg->segment_idx_wrap)
         seg->segment_idx %= seg->segment_idx_wrap;
 
     if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
-                              s->filename, seg->segment_idx++) < 0) {
+                              s->filename, seg->segment_idx) < 0) {
         av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
         return AVERROR(EINVAL);
     }
@@ -110,31 +156,15 @@
                           &s->interrupt_callback, NULL)) < 0)
         return err;
 
-    if (!oc->priv_data && oc->oformat->priv_data_size > 0) {
-        oc->priv_data = av_mallocz(oc->oformat->priv_data_size);
-        if (!oc->priv_data) {
-            avio_close(oc->pb);
-            return AVERROR(ENOMEM);
-        }
-        if (oc->oformat->priv_class) {
-            *(const AVClass**)oc->priv_data = oc->oformat->priv_class;
-            av_opt_set_defaults(oc->priv_data);
-        }
-    }
+    if (oc->oformat->priv_class && oc->priv_data)
+        av_opt_set(oc->priv_data, "resend_headers", "1", 0); /* mpegts specific */
 
-    if ((err = oc->oformat->write_header(oc)) < 0) {
-        goto fail;
+    if (write_header) {
+        if ((err = avformat_write_header(oc, NULL)) < 0)
+            return err;
     }
 
     return 0;
-
-fail:
-    av_log(oc, AV_LOG_ERROR, "Failure occurred when starting segment '%s'\n",
-           oc->filename);
-    avio_close(oc->pb);
-    av_freep(&oc->priv_data);
-
-    return err;
 }
 
 static int segment_list_open(AVFormatContext *s)
@@ -151,7 +181,7 @@
     if (seg->list_type == LIST_TYPE_M3U8) {
         avio_printf(seg->list_pb, "#EXTM3U\n");
         avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
-        avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->list_count);
+        avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->segment_idx);
         avio_printf(seg->list_pb, "#EXT-X-ALLOWCACHE:%d\n",
                     !!(seg->list_flags & SEGMENT_LIST_FLAG_CACHE));
         if (seg->list_flags & SEGMENT_LIST_FLAG_LIVE)
@@ -172,19 +202,19 @@
                         (int)ceil(seg->list_max_segment_time));
         avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
     }
-    seg->list_count++;
 
     avio_close(seg->list_pb);
 }
 
-static int segment_end(AVFormatContext *s)
+static int segment_end(AVFormatContext *s, int write_trailer)
 {
     SegmentContext *seg = s->priv_data;
     AVFormatContext *oc = seg->avf;
     int ret = 0;
 
-    if (oc->oformat->write_trailer)
-        ret = oc->oformat->write_trailer(oc);
+    av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
+    if (write_trailer)
+        ret = av_write_trailer(oc);
 
     if (ret < 0)
         av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
@@ -212,9 +242,6 @@
 
 end:
     avio_close(oc->pb);
-    if (oc->oformat->priv_class)
-        av_opt_free(oc->priv_data);
-    av_freep(&oc->priv_data);
 
     return ret;
 }
@@ -272,13 +299,35 @@
     return ret;
 }
 
+static int open_null_ctx(AVIOContext **ctx)
+{
+    int buf_size = 32768;
+    uint8_t *buf = av_malloc(buf_size);
+    if (!buf)
+        return AVERROR(ENOMEM);
+    *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
+    if (!*ctx) {
+        av_free(buf);
+        return AVERROR(ENOMEM);
+    }
+    return 0;
+}
+
+static void close_null_ctx(AVIOContext *pb)
+{
+    av_free(pb->buffer);
+    av_free(pb);
+}
+
 static int seg_write_header(AVFormatContext *s)
 {
     SegmentContext *seg = s->priv_data;
-    AVFormatContext *oc;
+    AVFormatContext *oc = NULL;
     int ret, i;
 
     seg->segment_count = 0;
+    if (!seg->write_header_trailer)
+        seg->individual_header_trailer = 0;
 
     if (seg->time_str && seg->times_str) {
         av_log(s, AV_LOG_ERROR,
@@ -317,11 +366,6 @@
         }
     }
 
-    oc = avformat_alloc_context();
-
-    if (!oc)
-        return AVERROR(ENOMEM);
-
     if (seg->list) {
         if (seg->list_type == LIST_TYPE_UNDEFINED) {
             if      (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
@@ -335,7 +379,7 @@
     if (seg->list_type == LIST_TYPE_EXT)
         av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
 
-    for (i = 0; i< s->nb_streams; i++)
+    for (i = 0; i < s->nb_streams; i++)
         seg->has_video +=
             (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO);
 
@@ -344,49 +388,60 @@
                "More than a single video stream present, "
                "expect issues decoding it.\n");
 
-    oc->oformat = av_guess_format(seg->format, s->filename, NULL);
+    seg->oformat = av_guess_format(seg->format, s->filename, NULL);
 
-    if (!oc->oformat) {
+    if (!seg->oformat) {
         ret = AVERROR_MUXER_NOT_FOUND;
         goto fail;
     }
-    if (oc->oformat->flags & AVFMT_NOFILE) {
+    if (seg->oformat->flags & AVFMT_NOFILE) {
         av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
-               oc->oformat->name);
+               seg->oformat->name);
         ret = AVERROR(EINVAL);
         goto fail;
     }
 
-    seg->avf = oc;
-
-    oc->streams = s->streams;
-    oc->nb_streams = s->nb_streams;
+    if ((ret = segment_mux_init(s)) < 0)
+        goto fail;
+    oc = seg->avf;
 
     if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
-                              s->filename, seg->segment_idx++) < 0) {
+                              s->filename, seg->segment_idx) < 0) {
         ret = AVERROR(EINVAL);
         goto fail;
     }
     seg->segment_count++;
 
-    if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
-                          &s->interrupt_callback, NULL)) < 0)
-        goto fail;
+    if (seg->write_header_trailer) {
+        if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
+                              &s->interrupt_callback, NULL)) < 0)
+            goto fail;
+    } else {
+        if ((ret = open_null_ctx(&oc->pb)) < 0)
+            goto fail;
+    }
 
     if ((ret = avformat_write_header(oc, NULL)) < 0) {
         avio_close(oc->pb);
         goto fail;
     }
 
+    if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
+        s->avoid_negative_ts = 1;
+
+    if (!seg->write_header_trailer) {
+        close_null_ctx(oc->pb);
+        if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
+                              &s->interrupt_callback, NULL)) < 0)
+            goto fail;
+    }
+
 fail:
     if (ret) {
-        if (oc) {
-            oc->streams = NULL;
-            oc->nb_streams = 0;
-            avformat_free_context(oc);
-        }
         if (seg->list)
             segment_list_close(s);
+        if (seg->avf)
+            avformat_free_context(seg->avf);
     }
     return ret;
 }
@@ -395,7 +450,7 @@
 {
     SegmentContext *seg = s->priv_data;
     AVFormatContext *oc = seg->avf;
-    AVStream *st = oc->streams[pkt->stream_index];
+    AVStream *st = s->streams[pkt->stream_index];
     int64_t end_pts;
     int ret;
 
@@ -415,20 +470,26 @@
         av_log(s, AV_LOG_DEBUG, "Next segment starts with packet stream:%d pts:%"PRId64" pts_time:%f\n",
                pkt->stream_index, pkt->pts, pkt->pts * av_q2d(st->time_base));
 
-        if ((ret = segment_end(s)) < 0 || (ret = segment_start(s)) < 0)
+        ret = segment_end(s, seg->individual_header_trailer);
+
+        if (!ret)
+            ret = segment_start(s, seg->individual_header_trailer);
+
+        if (ret)
             goto fail;
+
+        oc = seg->avf;
+
         seg->start_time = (double)pkt->pts * av_q2d(st->time_base);
     } else if (pkt->pts != AV_NOPTS_VALUE) {
         seg->end_time = FFMAX(seg->end_time,
                               (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
     }
 
-    ret = oc->oformat->write_packet(oc, pkt);
+    ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
 
 fail:
     if (ret < 0) {
-        oc->streams = NULL;
-        oc->nb_streams = 0;
         if (seg->list)
             avio_close(seg->list_pb);
         avformat_free_context(oc);
@@ -441,15 +502,23 @@
 {
     SegmentContext *seg = s->priv_data;
     AVFormatContext *oc = seg->avf;
-    int ret = segment_end(s);
+    int ret;
+    if (!seg->write_header_trailer) {
+        if ((ret = segment_end(s, 0)) < 0)
+            goto fail;
+        open_null_ctx(&oc->pb);
+        ret = av_write_trailer(oc);
+        close_null_ctx(oc->pb);
+    } else {
+        ret = segment_end(s, 1);
+    }
+fail:
     if (seg->list)
         segment_list_close(s);
 
     av_opt_free(seg);
     av_freep(&seg->times);
 
-    oc->streams = NULL;
-    oc->nb_streams = 0;
     avformat_free_context(oc);
     return ret;
 }
@@ -470,10 +539,13 @@
     { "csv",  "csv format",      0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV  }, INT_MIN, INT_MAX, 0, "list_type" },
     { "ext",  "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT  }, INT_MIN, INT_MAX, 0, "list_type" },
     { "m3u8", "M3U8 format",     0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, 0, "list_type" },
+    { "hls", "Apple HTTP Live Streaming compatible",     0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, 0, "list_type" },
     { "segment_time",      "set segment duration",                       OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E },
     { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta_str), AV_OPT_TYPE_STRING, {.str = "0"}, 0, 0, E },
     { "segment_times",     "set segment split time points",              OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL},  0, 0,       E },
     { "segment_wrap",      "set number after which the index wraps",     OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
+    { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
+    { "write_header_trailer", "write a header to the first segment and a trailer to the last one", OFFSET(write_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
     { NULL },
 };
 
@@ -488,7 +560,7 @@
     .name           = "segment",
     .long_name      = NULL_IF_CONFIG_SMALL("segment"),
     .priv_data_size = sizeof(SegmentContext),
-    .flags          = AVFMT_GLOBALHEADER | AVFMT_NOFILE,
+    .flags          = AVFMT_NOFILE|AVFMT_GLOBALHEADER,
     .write_header   = seg_write_header,
     .write_packet   = seg_write_packet,
     .write_trailer  = seg_write_trailer,
diff --git a/libavformat/sierravmd.c b/libavformat/sierravmd.c
index 98aa5b8..b0b582d 100644
--- a/libavformat/sierravmd.c
+++ b/libavformat/sierravmd.c
@@ -27,6 +27,7 @@
  *   http://www.pcisys.net/~melanson/codecs/
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "internal.h"
@@ -133,7 +134,13 @@
         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
         st->codec->codec_id = AV_CODEC_ID_VMDAUDIO;
         st->codec->codec_tag = 0;  /* no fourcc */
-        st->codec->channels = (vmd->vmd_header[811] & 0x80) ? 2 : 1;
+        if (vmd->vmd_header[811] & 0x80) {
+            st->codec->channels       = 2;
+            st->codec->channel_layout = AV_CH_LAYOUT_STEREO;
+        } else {
+            st->codec->channels       = 1;
+            st->codec->channel_layout = AV_CH_LAYOUT_MONO;
+        }
         st->codec->sample_rate = vmd->sample_rate;
         st->codec->block_align = AV_RL16(&vmd->vmd_header[806]);
         if (st->codec->block_align & 0x8000) {
@@ -148,7 +155,7 @@
         /* calculate pts */
         num = st->codec->block_align;
         den = st->codec->sample_rate * st->codec->channels;
-        av_reduce(&den, &num, den, num, (1UL<<31)-1);
+        av_reduce(&num, &den, num, den, (1UL<<31)-1);
         avpriv_set_pts_info(vst, 33, num, den);
         avpriv_set_pts_info(st, 33, num, den);
     }
@@ -240,7 +247,7 @@
     vmd_frame *frame;
 
     if (vmd->current_frame >= vmd->frame_count)
-        return AVERROR(EIO);
+        return AVERROR_EOF;
 
     frame = &vmd->frame_table[vmd->current_frame];
     /* position the stream (will probably be there already) */
diff --git a/libavformat/siff.c b/libavformat/siff.c
index df94dbf..a834d4d 100644
--- a/libavformat/siff.c
+++ b/libavformat/siff.c
@@ -19,6 +19,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "internal.h"
@@ -79,6 +80,7 @@
     ast->codec->codec_type      = AVMEDIA_TYPE_AUDIO;
     ast->codec->codec_id        = AV_CODEC_ID_PCM_U8;
     ast->codec->channels        = 1;
+    ast->codec->channel_layout  = AV_CH_LAYOUT_MONO;
     ast->codec->bits_per_coded_sample = 8;
     ast->codec->sample_rate     = c->rate;
     avpriv_set_pts_info(ast, 16, 1, c->rate);
@@ -125,7 +127,7 @@
     st->codec->codec_tag  = MKTAG('V', 'B', 'V', '1');
     st->codec->width      = width;
     st->codec->height     = height;
-    st->codec->pix_fmt    = PIX_FMT_PAL8;
+    st->codec->pix_fmt    = AV_PIX_FMT_PAL8;
     avpriv_set_pts_info(st, 16, 1, 12);
 
     c->cur_frame = 0;
@@ -190,7 +192,7 @@
 
     if (c->has_video){
         if (c->cur_frame >= c->frames)
-            return AVERROR(EIO);
+            return AVERROR_EOF;
         if (c->curstrm == -1){
             c->pktsize = avio_rl32(s->pb) - 4;
             c->flags = avio_rl16(s->pb);
@@ -227,7 +229,9 @@
             c->cur_frame++;
     }else{
         size = av_get_packet(s->pb, pkt, c->block_align);
-        if(size <= 0)
+        if(!size)
+            return AVERROR_EOF;
+        if(size < 0)
             return AVERROR(EIO);
         pkt->duration = size;
     }
diff --git a/libavformat/smacker.c b/libavformat/smacker.c
index cf1ab85..be22bec 100644
--- a/libavformat/smacker.c
+++ b/libavformat/smacker.c
@@ -24,6 +24,7 @@
  */
 
 #include "libavutil/bswap.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "internal.h"
@@ -161,7 +162,7 @@
     smk->videoindex = st->index;
     st->codec->width = smk->width;
     st->codec->height = smk->height;
-    st->codec->pix_fmt = PIX_FMT_PAL8;
+    st->codec->pix_fmt = AV_PIX_FMT_PAL8;
     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
     st->codec->codec_id = AV_CODEC_ID_SMACKVIDEO;
     st->codec->codec_tag = smk->magic;
@@ -191,7 +192,13 @@
             } else {
                 ast[i]->codec->codec_id = AV_CODEC_ID_PCM_U8;
             }
-            ast[i]->codec->channels = (smk->aflags[i] & SMK_AUD_STEREO) ? 2 : 1;
+            if (smk->aflags[i] & SMK_AUD_STEREO) {
+                ast[i]->codec->channels       = 2;
+                ast[i]->codec->channel_layout = AV_CH_LAYOUT_STEREO;
+            } else {
+                ast[i]->codec->channels       = 1;
+                ast[i]->codec->channel_layout = AV_CH_LAYOUT_MONO;
+            }
             ast[i]->codec->sample_rate = smk->rates[i];
             ast[i]->codec->bits_per_coded_sample = (smk->aflags[i] & SMK_AUD_16BITS) ? 16 : 8;
             if(ast[i]->codec->bits_per_coded_sample == 16 && ast[i]->codec->codec_id == AV_CODEC_ID_PCM_U8)
diff --git a/libavformat/smjpegdec.c b/libavformat/smjpegdec.c
index d1aad9f..ceb29c9 100644
--- a/libavformat/smjpegdec.c
+++ b/libavformat/smjpegdec.c
@@ -56,7 +56,7 @@
 
     duration = avio_rb32(pb); // in msec
 
-    while (!pb->eof_reached) {
+    while (!url_feof(pb)) {
         htype = avio_rl32(pb);
         switch (htype) {
         case SMJPEG_TXT:
@@ -106,10 +106,10 @@
             hlength = avio_rb32(pb);
             if (hlength < 12)
                 return AVERROR_INVALIDDATA;
-            avio_skip(pb, 4); // number of frames
             vst = avformat_new_stream(s, 0);
             if (!vst)
                 return AVERROR(ENOMEM);
+            vst->nb_frames         = avio_rb32(pb);
             vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
             vst->codec->width      = avio_rb16(pb);
             vst->codec->height     = avio_rb16(pb);
@@ -135,10 +135,11 @@
 static int smjpeg_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     SMJPEGContext *sc = s->priv_data;
-    uint32_t dtype, ret, size, timestamp;
+    uint32_t dtype, size, timestamp;
     int64_t pos;
+    int ret;
 
-    if (s->pb->eof_reached)
+    if (url_feof(s->pb))
         return AVERROR_EOF;
     pos   = avio_tell(s->pb);
     dtype = avio_rl32(s->pb);
diff --git a/libavformat/smjpegenc.c b/libavformat/smjpegenc.c
index 6dbc286..0a27687 100644
--- a/libavformat/smjpegenc.c
+++ b/libavformat/smjpegenc.c
@@ -26,7 +26,6 @@
 
 #include "avformat.h"
 #include "internal.h"
-#include "riff.h"
 #include "smjpeg.h"
 
 typedef struct SMJPEGMuxContext {
@@ -67,7 +66,7 @@
             avio_wl32(pb, SMJPEG_SND);
             avio_wb32(pb, 8);
             avio_wb16(pb, codec->sample_rate);
-            avio_w8(pb, av_get_bits_per_sample(codec->codec_id));
+            avio_w8(pb, codec->bits_per_coded_sample);
             avio_w8(pb, codec->channels);
             avio_wl32(pb, tag);
             avpriv_set_pts_info(st, 32, 1, 1000);
diff --git a/libavformat/smoothstreamingenc.c b/libavformat/smoothstreamingenc.c
index 2dfc26f..e51d088 100644
--- a/libavformat/smoothstreamingenc.c
+++ b/libavformat/smoothstreamingenc.c
@@ -108,7 +108,8 @@
         os->tail_out = NULL;
     }
     if (offset >= os->cur_start_pos) {
-        ffurl_seek(os->out, offset - os->cur_start_pos, SEEK_SET);
+        if (os->out)
+            ffurl_seek(os->out, offset - os->cur_start_pos, SEEK_SET);
         os->cur_pos = offset;
         return offset;
     }
@@ -185,18 +186,112 @@
     av_freep(&c->streams);
 }
 
+static void output_chunk_list(OutputStream *os, AVIOContext *out, int final, int skip, int window_size)
+{
+    int removed = 0, i, start = 0;
+    if (os->nb_fragments <= 0)
+        return;
+    if (os->fragments[0]->n > 0)
+        removed = 1;
+    if (final)
+        skip = 0;
+    if (window_size)
+        start = FFMAX(os->nb_fragments - skip - window_size, 0);
+    for (i = start; i < os->nb_fragments - skip; i++) {
+        Fragment *frag = os->fragments[i];
+        if (!final || removed)
+            avio_printf(out, "<c t=\"%"PRIu64"\" d=\"%"PRIu64"\" />\n", frag->start_time, frag->duration);
+        else
+            avio_printf(out, "<c n=\"%d\" d=\"%"PRIu64"\" />\n", frag->n, frag->duration);
+    }
+}
+
+static int write_manifest(AVFormatContext *s, int final)
+{
+    SmoothStreamingContext *c = s->priv_data;
+    AVIOContext *out;
+    char filename[1024];
+    int ret, i, video_chunks = 0, audio_chunks = 0, video_streams = 0, audio_streams = 0;
+    int64_t duration = 0;
+
+    snprintf(filename, sizeof(filename), "%s/Manifest", s->filename);
+    ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
+    if (ret < 0) {
+        av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", filename);
+        return ret;
+    }
+    avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
+    for (i = 0; i < s->nb_streams; i++) {
+        OutputStream *os = &c->streams[i];
+        if (os->nb_fragments > 0) {
+            Fragment *last = os->fragments[os->nb_fragments - 1];
+            duration = last->start_time + last->duration;
+        }
+        if (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
+            video_chunks = os->nb_fragments;
+            video_streams++;
+        } else {
+            audio_chunks = os->nb_fragments;
+            audio_streams++;
+        }
+    }
+    if (!final) {
+        duration = 0;
+        video_chunks = audio_chunks = 0;
+    }
+    if (c->window_size) {
+        video_chunks = FFMIN(video_chunks, c->window_size);
+        audio_chunks = FFMIN(audio_chunks, c->window_size);
+    }
+    avio_printf(out, "<SmoothStreamingMedia MajorVersion=\"2\" MinorVersion=\"0\" Duration=\"%"PRIu64"\"", duration);
+    if (!final)
+        avio_printf(out, " IsLive=\"true\" LookAheadFragmentCount=\"%d\" DVRWindowLength=\"0\"", c->lookahead_count);
+    avio_printf(out, ">\n");
+    if (c->has_video) {
+        int last = -1, index = 0;
+        avio_printf(out, "<StreamIndex Type=\"video\" QualityLevels=\"%d\" Chunks=\"%d\" Url=\"QualityLevels({bitrate})/Fragments(video={start time})\">\n", video_streams, video_chunks);
+        for (i = 0; i < s->nb_streams; i++) {
+            OutputStream *os = &c->streams[i];
+            if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_VIDEO)
+                continue;
+            last = i;
+            avio_printf(out, "<QualityLevel Index=\"%d\" Bitrate=\"%d\" FourCC=\"%s\" MaxWidth=\"%d\" MaxHeight=\"%d\" CodecPrivateData=\"%s\" />\n", index, s->streams[i]->codec->bit_rate, os->fourcc, s->streams[i]->codec->width, s->streams[i]->codec->height, os->private_str);
+            index++;
+        }
+        output_chunk_list(&c->streams[last], out, final, c->lookahead_count, c->window_size);
+        avio_printf(out, "</StreamIndex>\n");
+    }
+    if (c->has_audio) {
+        int last = -1, index = 0;
+        avio_printf(out, "<StreamIndex Type=\"audio\" QualityLevels=\"%d\" Chunks=\"%d\" Url=\"QualityLevels({bitrate})/Fragments(audio={start time})\">\n", audio_streams, audio_chunks);
+        for (i = 0; i < s->nb_streams; i++) {
+            OutputStream *os = &c->streams[i];
+            if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
+                continue;
+            last = i;
+            avio_printf(out, "<QualityLevel Index=\"%d\" Bitrate=\"%d\" FourCC=\"%s\" SamplingRate=\"%d\" Channels=\"%d\" BitsPerSample=\"16\" PacketSize=\"%d\" AudioTag=\"%d\" CodecPrivateData=\"%s\" />\n", index, s->streams[i]->codec->bit_rate, os->fourcc, s->streams[i]->codec->sample_rate, s->streams[i]->codec->channels, os->packet_size, os->audio_tag, os->private_str);
+            index++;
+        }
+        output_chunk_list(&c->streams[last], out, final, c->lookahead_count, c->window_size);
+        avio_printf(out, "</StreamIndex>\n");
+    }
+    avio_printf(out, "</SmoothStreamingMedia>\n");
+    avio_flush(out);
+    avio_close(out);
+    return 0;
+}
+
 static int ism_write_header(AVFormatContext *s)
 {
     SmoothStreamingContext *c = s->priv_data;
     int ret = 0, i;
     AVOutputFormat *oformat;
 
-    ret = mkdir(s->filename, 0777);
-    if (ret) {
-        av_log(s, AV_LOG_ERROR, "mkdir(%s): %s\n", s->filename, strerror(errno));
-        return AVERROR(errno);
+    if (mkdir(s->filename, 0777) < 0) {
+        av_log(s, AV_LOG_ERROR, "mkdir failed\n");
+        ret = AVERROR(errno);
+        goto fail;
     }
-    ret = 0;
 
     oformat = av_guess_format("ismv", NULL, NULL);
     if (!oformat) {
@@ -223,7 +318,11 @@
             goto fail;
         }
         snprintf(os->dirname, sizeof(os->dirname), "%s/QualityLevels(%d)", s->filename, s->streams[i]->codec->bit_rate);
-        mkdir(os->dirname, 0777);
+        if (mkdir(os->dirname, 0777) < 0) {
+            ret = AVERROR(errno);
+            av_log(s, AV_LOG_ERROR, "mkdir failed\n");
+            goto fail;
+        }
 
         ctx = avformat_alloc_context();
         if (!ctx) {
@@ -292,6 +391,7 @@
         av_log(s, AV_LOG_WARNING, "no video stream and no min frag duration set\n");
         ret = AVERROR(EINVAL);
     }
+    ret = write_manifest(s, 0);
 
 fail:
     if (ret)
@@ -400,99 +500,6 @@
     return ret;
 }
 
-static void output_chunk_list(OutputStream *os, AVIOContext *out, int final, int skip, int window_size)
-{
-    int removed = 0, i, start = 0;
-    if (os->nb_fragments <= 0)
-        return;
-    if (os->fragments[0]->n > 0)
-        removed = 1;
-    if (final)
-        skip = 0;
-    if (window_size)
-        start = FFMAX(os->nb_fragments - skip - window_size, 0);
-    for (i = start; i < os->nb_fragments - skip; i++) {
-        Fragment *frag = os->fragments[i];
-        if (!final || removed)
-            avio_printf(out, "<c t=\"%"PRIu64"\" d=\"%"PRIu64"\" />\n", frag->start_time, frag->duration);
-        else
-            avio_printf(out, "<c n=\"%d\" d=\"%"PRIu64"\" />\n", frag->n, frag->duration);
-    }
-}
-
-static int write_manifest(AVFormatContext *s, int final)
-{
-    SmoothStreamingContext *c = s->priv_data;
-    AVIOContext *out;
-    char filename[1024];
-    int ret, i, video_chunks = 0, audio_chunks = 0, video_streams = 0, audio_streams = 0;
-    int64_t duration = 0;
-
-    snprintf(filename, sizeof(filename), "%s/Manifest", s->filename);
-    ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
-    if (ret < 0)
-        return ret;
-    avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
-    for (i = 0; i < s->nb_streams; i++) {
-        OutputStream *os = &c->streams[i];
-        if (os->nb_fragments > 0) {
-            Fragment *last = os->fragments[os->nb_fragments - 1];
-            duration = last->start_time + last->duration;
-        }
-        if (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
-            video_chunks = os->nb_fragments;
-            video_streams++;
-        } else {
-            audio_chunks = os->nb_fragments;
-            audio_streams++;
-        }
-    }
-    if (!final) {
-        duration = 0;
-        video_chunks = audio_chunks = 0;
-    }
-    if (c->window_size) {
-        video_chunks = FFMIN(video_chunks, c->window_size);
-        audio_chunks = FFMIN(audio_chunks, c->window_size);
-    }
-    avio_printf(out, "<SmoothStreamingMedia MajorVersion=\"2\" MinorVersion=\"0\" Duration=\"%"PRIu64"\"", duration);
-    if (!final)
-        avio_printf(out, " IsLive=\"true\" LookAheadFragmentCount=\"%d\" DVRWindowLength=\"0\"", c->lookahead_count);
-    avio_printf(out, ">\n");
-    if (c->has_video) {
-        int last = -1, index = 0;
-        avio_printf(out, "<StreamIndex Type=\"video\" QualityLevels=\"%d\" Chunks=\"%d\" Url=\"QualityLevels({bitrate})/Fragments(video={start time})\">\n", video_streams, video_chunks);
-        for (i = 0; i < s->nb_streams; i++) {
-            OutputStream *os = &c->streams[i];
-            if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_VIDEO)
-                continue;
-            last = i;
-            avio_printf(out, "<QualityLevel Index=\"%d\" Bitrate=\"%d\" FourCC=\"%s\" MaxWidth=\"%d\" MaxHeight=\"%d\" CodecPrivateData=\"%s\" />\n", index, s->streams[i]->codec->bit_rate, os->fourcc, s->streams[i]->codec->width, s->streams[i]->codec->height, os->private_str);
-            index++;
-        }
-        output_chunk_list(&c->streams[last], out, final, c->lookahead_count, c->window_size);
-        avio_printf(out, "</StreamIndex>\n");
-    }
-    if (c->has_audio) {
-        int last = -1, index = 0;
-        avio_printf(out, "<StreamIndex Type=\"audio\" QualityLevels=\"%d\" Chunks=\"%d\" Url=\"QualityLevels({bitrate})/Fragments(audio={start time})\">\n", audio_streams, audio_chunks);
-        for (i = 0; i < s->nb_streams; i++) {
-            OutputStream *os = &c->streams[i];
-            if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
-                continue;
-            last = i;
-            avio_printf(out, "<QualityLevel Index=\"%d\" Bitrate=\"%d\" FourCC=\"%s\" SamplingRate=\"%d\" Channels=\"%d\" BitsPerSample=\"16\" PacketSize=\"%d\" AudioTag=\"%d\" CodecPrivateData=\"%s\" />\n", index, s->streams[i]->codec->bit_rate, os->fourcc, s->streams[i]->codec->sample_rate, s->streams[i]->codec->channels, os->packet_size, os->audio_tag, os->private_str);
-            index++;
-        }
-        output_chunk_list(&c->streams[last], out, final, c->lookahead_count, c->window_size);
-        avio_printf(out, "</StreamIndex>\n");
-    }
-    avio_printf(out, "</SmoothStreamingMedia>\n");
-    avio_flush(out);
-    avio_close(out);
-    return 0;
-}
-
 static int ism_flush(AVFormatContext *s, int final)
 {
     SmoothStreamingContext *c = s->priv_data;
@@ -550,7 +557,8 @@
         }
     }
 
-    write_manifest(s, final);
+    if (ret >= 0)
+        ret = write_manifest(s, final);
     return ret;
 }
 
@@ -559,14 +567,19 @@
     SmoothStreamingContext *c = s->priv_data;
     AVStream *st = s->streams[pkt->stream_index];
     OutputStream *os = &c->streams[pkt->stream_index];
-    int64_t end_pts = (c->nb_fragments + 1) * c->min_frag_duration;
+    int64_t end_dts = (c->nb_fragments + 1LL) * c->min_frag_duration;
+    int ret;
+
+    if (st->first_dts == AV_NOPTS_VALUE)
+        st->first_dts = pkt->dts;
 
     if ((!c->has_video || st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
-        av_compare_ts(pkt->pts, st->time_base,
-                      end_pts, AV_TIME_BASE_Q) >= 0 &&
+        av_compare_ts(pkt->dts - st->first_dts, st->time_base,
+                      end_dts, AV_TIME_BASE_Q) >= 0 &&
         pkt->flags & AV_PKT_FLAG_KEY && os->packets_written) {
 
-        ism_flush(s, 0);
+        if ((ret = ism_flush(s, 0)) < 0)
+            return ret;
         c->nb_fragments++;
     }
 
diff --git a/libavformat/smush.c b/libavformat/smush.c
index b164c75..9c8997c 100644
--- a/libavformat/smush.c
+++ b/libavformat/smush.c
@@ -32,8 +32,10 @@
 
 static int smush_read_probe(AVProbeData *p)
 {
-    if ((AV_RL32(p->buf) == MKTAG('S', 'A', 'N', 'M') ||
-         AV_RL32(p->buf) == MKTAG('A', 'N', 'I', 'M'))) {
+    if (((AV_RL32(p->buf) == MKTAG('S', 'A', 'N', 'M') &&
+          AV_RL32(p->buf + 8) == MKTAG('S', 'H', 'D', 'R')) ||
+         (AV_RL32(p->buf) == MKTAG('A', 'N', 'I', 'M') &&
+          AV_RL32(p->buf + 8) == MKTAG('A', 'H', 'D', 'R')))) {
         return AVPROBE_SCORE_MAX;
     }
 
@@ -209,7 +211,7 @@
         case MKBETAG('W', 'a', 'v', 'e'):
             if (size < 13)
                 return AVERROR_INVALIDDATA;
-            if (av_get_packet(pb, pkt, size) < 0)
+            if (av_get_packet(pb, pkt, size) < 13)
                 return AVERROR(EIO);
 
             pkt->stream_index = smush->audio_stream_index;
diff --git a/libavformat/sol.c b/libavformat/sol.c
index aca5a86..77c754a 100644
--- a/libavformat/sol.c
+++ b/libavformat/sol.c
@@ -23,6 +23,7 @@
  * Based on documents from Game Audio Player and own research
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "internal.h"
@@ -116,6 +117,8 @@
     st->codec->codec_tag = id;
     st->codec->codec_id = codec;
     st->codec->channels = channels;
+    st->codec->channel_layout = channels == 1 ? AV_CH_LAYOUT_MONO :
+                                                AV_CH_LAYOUT_STEREO;
     st->codec->sample_rate = rate;
     avpriv_set_pts_info(st, 64, 1, rate);
     return 0;
diff --git a/libavformat/spdifdec.c b/libavformat/spdifdec.c
index dce3346..94cfe84 100644
--- a/libavformat/spdifdec.c
+++ b/libavformat/spdifdec.c
@@ -92,7 +92,7 @@
     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);
+            av_log_missing_feature(s, " in IEC 61937", 1);
         }
         return AVERROR_PATCHWELCOME;
     }
@@ -213,7 +213,7 @@
         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);
+        av_log_missing_feature(s, "Codec change in IEC 61937", 0);
         return AVERROR_PATCHWELCOME;
     }
 
diff --git a/libavformat/srtdec.c b/libavformat/srtdec.c
index a66ced3..f55fb11 100644
--- a/libavformat/srtdec.c
+++ b/libavformat/srtdec.c
@@ -21,6 +21,7 @@
 
 #include "avformat.h"
 #include "internal.h"
+#include "libavutil/bprint.h"
 #include "libavutil/intreadwrite.h"
 
 static int srt_probe(AVProbeData *p)
@@ -32,7 +33,8 @@
         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)
+        if ((num == i || num + 1 == 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;
@@ -47,29 +49,30 @@
         return AVERROR(ENOMEM);
     avpriv_set_pts_info(st, 64, 1, 1000);
     st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
-    st->codec->codec_id   = AV_CODEC_ID_SRT;
+    st->codec->codec_id   = AV_CODEC_ID_SUBRIP;
     return 0;
 }
 
-static int64_t get_pts(const char *buf, int *duration)
+static int64_t get_pts(const char **buf, int *duration,
+                       int32_t *x1, int32_t *y1, int32_t *x2, int32_t *y2)
 {
-    int i, hour, min, sec, hsec;
-    int he, me, se, mse;
+    int i;
 
     for (i=0; i<2; i++) {
-        int64_t start, end;
-        if (sscanf(buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
-                   &hour, &min, &sec, &hsec, &he, &me, &se, &mse) == 8) {
-            min += 60*hour;
-            sec += 60*min;
-            start = sec*1000+hsec;
-            me += 60*he;
-            se += 60*me;
-            end = se*1000+mse;
+        int hh1, mm1, ss1, ms1;
+        int hh2, mm2, ss2, ms2;
+        if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d"
+                   "%*[ ]X1:%u X2:%u Y1:%u Y2:%u",
+                   &hh1, &mm1, &ss1, &ms1,
+                   &hh2, &mm2, &ss2, &ms2,
+                   x1, x2, y1, y2) >= 8) {
+            int64_t start = (hh1*3600LL + mm1*60LL + ss1) * 1000LL + ms1;
+            int64_t end   = (hh2*3600LL + mm2*60LL + ss2) * 1000LL + ms2;
             *duration = end - start;
+            *buf += strcspn(*buf, "\n") + 1;
             return start;
         }
-        buf += strcspn(buf, "\n") + 1;
+        *buf += strcspn(*buf, "\n") + 1;
     }
     return AV_NOPTS_VALUE;
 }
@@ -79,23 +82,86 @@
     return c == '\r' || c == '\n';
 }
 
+static void read_chunk(AVIOContext *pb, AVBPrint *buf)
+{
+    char eol_buf[5];
+    int n = 0, i = 0, nb_eol = 0;
+
+    for (;;) {
+        char c = avio_r8(pb);
+
+        if (!c)
+            break;
+
+        /* ignore all initial line breaks */
+        if (n == 0 && is_eol(c))
+            continue;
+
+        /* line break buffering: we don't want to add the trailing \r\n */
+        if (is_eol(c)) {
+            nb_eol += c == '\n';
+            if (nb_eol == 2)
+                break;
+            eol_buf[i++] = c;
+            if (i == sizeof(eol_buf) - 1)
+                break;
+            continue;
+        }
+
+        /* only one line break followed by data: we flush the line breaks
+         * buffer */
+        if (i) {
+            eol_buf[i] = 0;
+            av_bprintf(buf, "%s", eol_buf);
+            i = nb_eol = 0;
+        }
+
+        av_bprint_chars(buf, c, 1);
+        n++;
+    }
+
+    /* FIXME: remove the following when the lavc SubRip decoder is fixed
+     * (trailing tags are not correctly flushed, see what happens to FATE when
+     * you disable this code) */
+    if (buf->len)
+        av_bprintf(buf, "\n");
+}
+
 static int srt_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
-    char buffer[2048], *ptr = buffer, *ptr2;
+    AVBPrint buf;
     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) && !url_feof(s->pb) && ptr-buffer<sizeof(buffer)-1);
+    av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
+    read_chunk(s->pb, &buf);
 
-    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, &(pkt->duration));
+    if (buf.len) {
+        int64_t pts;
+        int duration, pkt_size;
+        const char *ptr = buf.str;
+        int32_t x1 = -1, y1 = -1, x2 = -1, y2 = -1;
+
+        pts = get_pts(&ptr, &duration, &x1, &y1, &x2, &y2);
+        pkt_size = buf.len - (ptr - buf.str);
+        if (pts != AV_NOPTS_VALUE && !(res = av_new_packet(pkt, pkt_size))) {
+            memcpy(pkt->data, ptr, pkt->size);
+            pkt->flags |= AV_PKT_FLAG_KEY;
+            pkt->pos = pos;
+            pkt->pts = pkt->dts = pts;
+            pkt->duration = duration;
+            if (x1 != -1) {
+                uint8_t *p = av_packet_new_side_data(pkt, AV_PKT_DATA_SUBTITLE_POSITION, 16);
+                if (p) {
+                    AV_WL32(p,      x1);
+                    AV_WL32(p +  4, y1);
+                    AV_WL32(p +  8, x2);
+                    AV_WL32(p + 12, y2);
+                }
+            }
+        }
     }
+    av_bprint_finalize(&buf, NULL);
     return res;
 }
 
diff --git a/libavformat/srtenc.c b/libavformat/srtenc.c
index 0b094b0..97b297e 100644
--- a/libavformat/srtenc.c
+++ b/libavformat/srtenc.c
@@ -35,6 +35,8 @@
 
 static int srt_write_header(AVFormatContext *avf)
 {
+    SRTContext *srt = avf->priv_data;
+
     if (avf->nb_streams != 1 ||
         avf->streams[0]->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
         av_log(avf, AV_LOG_ERROR,
@@ -50,6 +52,7 @@
         return AVERROR(EINVAL);
     }
     avpriv_set_pts_info(avf->streams[0], 64, 1, 1000);
+    srt->index = 1;
     return 0;
 }
 
@@ -58,33 +61,30 @@
     SRTContext *srt = avf->priv_data;
     int write_ts = avf->streams[0]->codec->codec_id != AV_CODEC_ID_SRT;
 
-    srt->index++;
     if (write_ts) {
-        char buf[64];
         int64_t s = pkt->pts, e, d = pkt->duration;
-        int len;
 
         if (d <= 0)
             /* For backward compatibility, fallback to convergence_duration. */
             d = pkt->convergence_duration;
-        if (s == AV_NOPTS_VALUE || d <= 0) {
-            av_log(avf, AV_LOG_ERROR, "Insufficient timestamps.\n");
-            return AVERROR(EINVAL);
+        if (s == AV_NOPTS_VALUE || d < 0) {
+            av_log(avf, AV_LOG_WARNING,
+                   "Insufficient timestamps in event number %d.\n", srt->index);
+            return 0;
         }
         e = s + d;
-        len = snprintf(buf, sizeof(buf),
-                       "%d\n%02d:%02d:%02d,%03d --> %02d:%02d:%02d,%03d\n",
+        avio_printf(avf->pb, "%d\n%02d:%02d:%02d,%03d --> %02d:%02d:%02d,%03d\n",
                        srt->index,
                        (int)(s / 3600000),      (int)(s / 60000) % 60,
                        (int)(s /    1000) % 60, (int)(s %  1000),
                        (int)(e / 3600000),      (int)(e / 60000) % 60,
                        (int)(e /    1000) % 60, (int)(e %  1000));
-        avio_write(avf->pb, buf, len);
     }
     avio_write(avf->pb, pkt->data, pkt->size);
     if (write_ts)
         avio_write(avf->pb, "\n\n", 2);
     avio_flush(avf->pb);
+    srt->index++;
     return 0;
 }
 
@@ -96,6 +96,6 @@
     .priv_data_size = sizeof(SRTContext),
     .write_header   = srt_write_header,
     .write_packet   = srt_write_packet,
-    .flags          = AVFMT_VARIABLE_FPS,
-    .subtitle_codec = AV_CODEC_ID_TEXT,
+    .flags          = AVFMT_VARIABLE_FPS | AVFMT_TS_NONSTRICT,
+    .subtitle_codec = AV_CODEC_ID_SUBRIP,
 };
diff --git a/libavformat/subtitles.c b/libavformat/subtitles.c
index 1204526..b264ec5 100644
--- a/libavformat/subtitles.c
+++ b/libavformat/subtitles.c
@@ -91,6 +91,55 @@
     return 0;
 }
 
+int ff_subtitles_queue_seek(FFDemuxSubtitlesQueue *q, AVFormatContext *s, int stream_index,
+                            int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
+{
+    if (flags & AVSEEK_FLAG_BYTE) {
+        return AVERROR(ENOSYS);
+    } else if (flags & AVSEEK_FLAG_FRAME) {
+        if (ts < 0 || ts >= q->nb_subs)
+            return AVERROR(ERANGE);
+        q->current_sub_idx = ts;
+    } else {
+        int i, idx = -1;
+        int64_t min_ts_diff = INT64_MAX;
+        int64_t ts_selected;
+        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: q->subs[] is sorted by pts so we could do a binary search */
+        for (i = 0; i < q->nb_subs; i++) {
+            int64_t pts = q->subs[i].pts;
+            uint64_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);
+        /* look back in the latest subtitles for overlapping subtitles */
+        ts_selected = q->subs[idx].pts;
+        for (i = idx - 1; i >= 0; i--) {
+            if (q->subs[i].duration <= 0)
+                continue;
+            if (q->subs[i].pts > ts_selected - q->subs[i].duration)
+                idx = i;
+            else
+                break;
+        }
+        q->current_sub_idx = idx;
+    }
+    return 0;
+}
+
 void ff_subtitles_queue_clean(FFDemuxSubtitlesQueue *q)
 {
     int i;
diff --git a/libavformat/subtitles.h b/libavformat/subtitles.h
index b089bb2..55e6182 100644
--- a/libavformat/subtitles.h
+++ b/libavformat/subtitles.h
@@ -55,6 +55,13 @@
 int ff_subtitles_queue_read_packet(FFDemuxSubtitlesQueue *q, AVPacket *pkt);
 
 /**
+ * Update current_sub_idx to emulate a seek. Except the first parameter, it
+ * matches AVInputFormat->read_seek2 prototypes.
+ */
+int ff_subtitles_queue_seek(FFDemuxSubtitlesQueue *q, AVFormatContext *s, int stream_index,
+                            int64_t min_ts, int64_t ts, int64_t max_ts, int flags);
+
+/**
  * Remove and destroy all the subtitles packets.
  */
 void ff_subtitles_queue_clean(FFDemuxSubtitlesQueue *q);
diff --git a/libavformat/subviewerdec.c b/libavformat/subviewerdec.c
index e708a28..7691d82 100644
--- a/libavformat/subviewerdec.c
+++ b/libavformat/subviewerdec.c
@@ -57,8 +57,8 @@
 
     if (sscanf(s, "%u:%u:%u.%u,%u:%u:%u.%u",
                &hh1, &mm1, &ss1, &ms1, &hh2, &mm2, &ss2, &ms2) == 8) {
-        end    = (hh2*3600 + mm2*60 + ss2) * 100 + ms2;
-        *start = (hh1*3600 + mm1*60 + ss1) * 100 + ms1;
+        end    = (hh2*3600LL + mm2*60LL + ss2) * 100LL + ms2;
+        *start = (hh1*3600LL + mm1*60LL + ss1) * 100LL + ms1;
         *duration = end - *start;
         return 0;
     }
@@ -157,6 +157,14 @@
     return ff_subtitles_queue_read_packet(&subviewer->q, pkt);
 }
 
+static int subviewer_read_seek(AVFormatContext *s, int stream_index,
+                               int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
+{
+    SubViewerContext *subviewer = s->priv_data;
+    return ff_subtitles_queue_seek(&subviewer->q, s, stream_index,
+                                   min_ts, ts, max_ts, flags);
+}
+
 static int subviewer_read_close(AVFormatContext *s)
 {
     SubViewerContext *subviewer = s->priv_data;
@@ -171,6 +179,7 @@
     .read_probe     = subviewer_probe,
     .read_header    = subviewer_read_header,
     .read_packet    = subviewer_read_packet,
+    .read_seek2     = subviewer_read_seek,
     .read_close     = subviewer_read_close,
     .flags          = AVFMT_GENERIC_INDEX,
     .extensions     = "sub",
diff --git a/libavformat/swf.h b/libavformat/swf.h
index 3c0c607..b9722c1 100644
--- a/libavformat/swf.h
+++ b/libavformat/swf.h
@@ -32,26 +32,79 @@
 #include "libavutil/fifo.h"
 #include "avformat.h"
 #include "avio.h"
-#include "riff.h"    /* for CodecTag */
+#include "internal.h"
 
 /* should have a generic way to indicate probable size */
 #define DUMMY_FILE_SIZE   (100 * 1024 * 1024)
 #define DUMMY_DURATION    600 /* in seconds */
 
-#define TAG_END           0
-#define TAG_SHOWFRAME     1
-#define TAG_DEFINESHAPE   2
-#define TAG_FREECHARACTER 3
-#define TAG_PLACEOBJECT   4
-#define TAG_REMOVEOBJECT  5
-#define TAG_STREAMHEAD    18
-#define TAG_STREAMBLOCK   19
-#define TAG_JPEG2         21
-#define TAG_PLACEOBJECT2  26
-#define TAG_STREAMHEAD2   45
-#define TAG_VIDEOSTREAM   60
-#define TAG_VIDEOFRAME    61
-#define TAG_FILEATTRIBUTES 69
+enum {
+    TAG_END                          =  0,
+    TAG_SHOWFRAME                    =  1,
+    TAG_DEFINESHAPE                  =  2,
+    TAG_FREECHARACTER                =  3,
+    TAG_PLACEOBJECT                  =  4,
+    TAG_REMOVEOBJECT                 =  5,
+    TAG_DEFINEBITS                   =  6,
+    TAG_DEFINEBUTTON                 =  7,
+    TAG_JPEGTABLES                   =  8,
+    TAG_SETBACKGROUNDCOLOR           =  9,
+    TAG_DEFINEFONT                   = 10,
+    TAG_DEFINETEXT                   = 11,
+    TAG_DOACTION                     = 12,
+    TAG_DEFINEFONTINFO               = 13,
+    TAG_DEFINESOUND                  = 14,
+    TAG_STARTSOUND                   = 15,
+    TAG_DEFINEBUTTONSOUND            = 17,
+    TAG_STREAMHEAD                   = 18,
+    TAG_STREAMBLOCK                  = 19,
+    TAG_DEFINEBITSLOSSLESS           = 20,
+    TAG_JPEG2                        = 21,
+    TAG_DEFINESHAPE2                 = 22,
+    TAG_DEFINEBUTTONCXFORM           = 23,
+    TAG_PROTECT                      = 24,
+    TAG_PLACEOBJECT2                 = 26,
+    TAG_REMOVEOBJECT2                = 28,
+    TAG_DEFINESHAPE3                 = 32,
+    TAG_DEFINETEXT2                  = 33,
+    TAG_DEFINEBUTTON2                = 34,
+    TAG_DEFINEBITSJPEG3              = 35,
+    TAG_DEFINEBITSLOSSLESS2          = 36,
+    TAG_DEFINEEDITTEXT               = 37,
+    TAG_DEFINESPRITE                 = 39,
+    TAG_FRAMELABEL                   = 43,
+    TAG_STREAMHEAD2                  = 45,
+    TAG_DEFINEMORPHSHAPE             = 46,
+    TAG_DEFINEFONT2                  = 48,
+    TAG_EXPORTASSETS                 = 56,
+    TAG_IMPORTASSETS                 = 57,
+    TAG_ENABLEDEBUGGER               = 58,
+    TAG_DOINITACTION                 = 59,
+    TAG_VIDEOSTREAM                  = 60,
+    TAG_VIDEOFRAME                   = 61,
+    TAG_DEFINEFONTINFO2              = 62,
+    TAG_ENABLEDEBUGGER2              = 64,
+    TAG_SCRIPTLIMITS                 = 65,
+    TAG_SETTABINDEX                  = 66,
+    TAG_FILEATTRIBUTES               = 69,
+    TAG_PLACEOBJECT3                 = 70,
+    TAG_IMPORTASSETS2                = 71,
+    TAG_DEFINEFONTALIGNZONES         = 73,
+    TAG_CSMTEXTSETTINGS              = 74,
+    TAG_DEFINEFONT3                  = 75,
+    TAG_SYMBOLCLASS                  = 76,
+    TAG_METADATA                     = 77,
+    TAG_DEFINESCALINGGRID            = 78,
+    TAG_DOABC                        = 82,
+    TAG_DEFINESHAPE4                 = 83,
+    TAG_DEFINEMORPHSHAPE2            = 84,
+    TAG_DEFINESCENEANDFRAMELABELDATA = 86,
+    TAG_DEFINEBINARYDATA             = 87,
+    TAG_DEFINEFONTNAME               = 88,
+    TAG_STARTSOUND2                  = 89,
+    TAG_DEFINEBITSJPEG4              = 90,
+    TAG_DEFINEFONT4                  = 91,
+};
 
 #define TAG_LONG         0x100
 
@@ -70,7 +123,7 @@
 #undef NDEBUG
 #include <assert.h>
 
-typedef struct {
+typedef struct SWFContext {
     int64_t duration_pos;
     int64_t tag_pos;
     int64_t vframes_pos;
diff --git a/libavformat/swfdec.c b/libavformat/swfdec.c
index 3967d82..6918b01 100644
--- a/libavformat/swfdec.c
+++ b/libavformat/swfdec.c
@@ -20,6 +20,9 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/avassert.h"
+#include "libavutil/channel_layout.h"
+#include "libavutil/imgutils.h"
 #include "libavutil/intreadwrite.h"
 #include "swf.h"
 
@@ -71,7 +74,7 @@
 retry:
     if (!z->avail_in) {
         int n = avio_read(s->pb, swf->zbuf_in, ZBUF_SIZE);
-        if (n <= 0)
+        if (n < 0)
             return n;
         z->next_in  = swf->zbuf_in;
         z->avail_in = n;
@@ -169,7 +172,7 @@
             /* Check for FLV1 */
             vst = avformat_new_stream(s, NULL);
             if (!vst)
-                return -1;
+                return AVERROR(ENOMEM);
             vst->id = ch_id;
             vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
             vst->codec->codec_id = ff_codec_get_id(ff_swf_codec_tags, avio_r8(pb));
@@ -190,9 +193,15 @@
             swf->samples_per_frame = avio_rl16(pb);
             ast = avformat_new_stream(s, NULL);
             if (!ast)
-                return -1;
+                return AVERROR(ENOMEM);
             ast->id = -1; /* -1 to avoid clash with video stream ch_id */
-            ast->codec->channels = 1 + (v&1);
+            if (v & 1) {
+                ast->codec->channels       = 2;
+                ast->codec->channel_layout = AV_CH_LAYOUT_STEREO;
+            } else {
+                ast->codec->channels       = 1;
+                ast->codec->channel_layout = AV_CH_LAYOUT_MONO;
+            }
             ast->codec->codec_type = AVMEDIA_TYPE_AUDIO;
             ast->codec->codec_id = ff_codec_get_id(swf_audio_codec_tags, (v>>4) & 15);
             ast->need_parsing = AVSTREAM_PARSE_FULL;
@@ -200,6 +209,44 @@
             ast->codec->sample_rate = 44100 >> (3 - sample_rate_code);
             avpriv_set_pts_info(ast, 64, 1, ast->codec->sample_rate);
             len -= 4;
+        } else if (tag == TAG_DEFINESOUND) {
+            /* audio stream */
+            int sample_rate_code;
+            int ch_id = avio_rl16(pb);
+
+            for (i=0; i<s->nb_streams; i++) {
+                st = s->streams[i];
+                if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->id == ch_id)
+                    goto skip;
+            }
+
+            // FIXME: 8-bit uncompressed PCM audio will be interpreted as 16-bit
+            // FIXME: The entire audio stream is stored in a single chunk/tag. Normally,
+            // these are smaller audio streams in DEFINESOUND tags, but it's technically
+            // possible they could be huge. Break it up into multiple packets if it's big.
+            v = avio_r8(pb);
+            ast = avformat_new_stream(s, NULL);
+            if (!ast)
+                return AVERROR(ENOMEM);
+            ast->id = ch_id;
+            ast->codec->channels = 1 + (v&1);
+            ast->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+            ast->codec->codec_id = ff_codec_get_id(swf_audio_codec_tags, (v>>4) & 15);
+            ast->need_parsing = AVSTREAM_PARSE_FULL;
+            sample_rate_code= (v>>2) & 3;
+            ast->codec->sample_rate = 44100 >> (3 - sample_rate_code);
+            avpriv_set_pts_info(ast, 64, 1, ast->codec->sample_rate);
+            ast->duration = avio_rl32(pb); // number of samples
+            if (((v>>4) & 15) == 2) { // MP3 sound data record
+                ast->skip_samples = avio_rl16(pb);
+                len -= 2;
+            }
+            len -= 7;
+            if ((res = av_get_packet(pb, pkt, len)) < 0)
+                return res;
+            pkt->pos = pos;
+            pkt->stream_index = ast->index;
+            return pkt->size;
         } else if (tag == TAG_VIDEOFRAME) {
             int ch_id = avio_rl16(pb);
             len -= 2;
@@ -215,6 +262,132 @@
                     return pkt->size;
                 }
             }
+        } else if (tag == TAG_DEFINEBITSLOSSLESS || tag == TAG_DEFINEBITSLOSSLESS2) {
+#if CONFIG_ZLIB
+            long out_len;
+            uint8_t *buf = NULL, *zbuf = NULL, *pal;
+            uint32_t colormap[AVPALETTE_COUNT] = {0};
+            const int alpha_bmp = tag == TAG_DEFINEBITSLOSSLESS2;
+            const int colormapbpp = 3 + alpha_bmp;
+            int linesize, colormapsize = 0;
+
+            const int ch_id   = avio_rl16(pb);
+            const int bmp_fmt = avio_r8(pb);
+            const int width   = avio_rl16(pb);
+            const int height  = avio_rl16(pb);
+
+            len -= 2+1+2+2;
+
+            switch (bmp_fmt) {
+            case 3: // PAL-8
+                linesize = width;
+                colormapsize = avio_r8(pb) + 1;
+                len--;
+                break;
+            case 4: // RGB15
+                linesize = width * 2;
+                break;
+            case 5: // RGB24 (0RGB)
+                linesize = width * 4;
+                break;
+            default:
+                av_log(s, AV_LOG_ERROR, "invalid bitmap format %d, skipped\n", bmp_fmt);
+                goto bitmap_end_skip;
+            }
+
+            linesize = FFALIGN(linesize, 4);
+
+            if (av_image_check_size(width, height, 0, s) < 0 ||
+                linesize >= INT_MAX / height ||
+                linesize * height >= INT_MAX - colormapsize * colormapbpp) {
+                av_log(s, AV_LOG_ERROR, "invalid frame size %dx%d\n", width, height);
+                goto bitmap_end_skip;
+            }
+
+            out_len = colormapsize * colormapbpp + linesize * height;
+
+            av_dlog(s, "bitmap: ch=%d fmt=%d %dx%d (linesize=%d) len=%d->%ld pal=%d\n",
+                    ch_id, bmp_fmt, width, height, linesize, len, out_len, colormapsize);
+
+            zbuf = av_malloc(len);
+            buf  = av_malloc(out_len);
+            if (!zbuf || !buf) {
+                res = AVERROR(ENOMEM);
+                goto bitmap_end;
+            }
+
+            len = avio_read(pb, zbuf, len);
+            if (len < 0 || (res = uncompress(buf, &out_len, zbuf, len)) != Z_OK) {
+                av_log(s, AV_LOG_WARNING, "Failed to uncompress one bitmap\n");
+                goto bitmap_end_skip;
+            }
+
+            for (i = 0; i < s->nb_streams; i++) {
+                st = s->streams[i];
+                if (st->codec->codec_id == AV_CODEC_ID_RAWVIDEO && st->id == -3)
+                    break;
+            }
+            if (i == s->nb_streams) {
+                vst = avformat_new_stream(s, NULL);
+                if (!vst) {
+                    res = AVERROR(ENOMEM);
+                    goto bitmap_end;
+                }
+                vst->id = -3; /* -3 to avoid clash with video stream and audio stream */
+                vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
+                vst->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
+                avpriv_set_pts_info(vst, 64, 256, swf->frame_rate);
+                st = vst;
+            }
+            st->codec->width  = width;
+            st->codec->height = height;
+
+            if ((res = av_new_packet(pkt, out_len - colormapsize * colormapbpp)) < 0)
+                goto bitmap_end;
+            pkt->pos = pos;
+            pkt->stream_index = st->index;
+
+            switch (bmp_fmt) {
+            case 3:
+                st->codec->pix_fmt = AV_PIX_FMT_PAL8;
+                for (i = 0; i < colormapsize; i++)
+                    if (alpha_bmp)  colormap[i] = buf[3]<<24 | AV_RB24(buf + 4*i);
+                    else            colormap[i] = 0xffU <<24 | AV_RB24(buf + 3*i);
+                pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
+                if (!pal) {
+                    res = AVERROR(ENOMEM);
+                    goto bitmap_end;
+                }
+                memcpy(pal, colormap, AVPALETTE_SIZE);
+                break;
+            case 4:
+                st->codec->pix_fmt = AV_PIX_FMT_RGB555;
+                break;
+            case 5:
+                st->codec->pix_fmt = alpha_bmp ? AV_PIX_FMT_ARGB : AV_PIX_FMT_0RGB;
+                break;
+            default:
+                av_assert0(0);
+            }
+
+            if (linesize * height > pkt->size) {
+                res = AVERROR_INVALIDDATA;
+                goto bitmap_end;
+            }
+            memcpy(pkt->data, buf + colormapsize*colormapbpp, linesize * height);
+
+            res = pkt->size;
+
+bitmap_end:
+            av_freep(&zbuf);
+            av_freep(&buf);
+            return res;
+bitmap_end_skip:
+            av_freep(&zbuf);
+            av_freep(&buf);
+#else
+            av_log(s, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
+#endif
         } else if (tag == TAG_STREAMBLOCK) {
             for (i = 0; i < s->nb_streams; i++) {
                 st = s->streams[i];
@@ -241,7 +414,7 @@
             if (i == s->nb_streams) {
                 vst = avformat_new_stream(s, NULL);
                 if (!vst)
-                    return -1;
+                    return AVERROR(ENOMEM);
                 vst->id = -2; /* -2 to avoid clash with video stream and audio stream */
                 vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
                 vst->codec->codec_id = AV_CODEC_ID_MJPEG;
diff --git a/libavformat/swfenc.c b/libavformat/swfenc.c
index 4a5be12..a8fd9f9 100644
--- a/libavformat/swfenc.c
+++ b/libavformat/swfenc.c
@@ -187,6 +187,10 @@
     for(i=0;i<s->nb_streams;i++) {
         AVCodecContext *enc = s->streams[i]->codec;
         if (enc->codec_type == AVMEDIA_TYPE_AUDIO) {
+            if (swf->audio_enc) {
+                av_log(s, AV_LOG_ERROR, "SWF muxer only supports 1 audio stream\n");
+                return AVERROR_INVALIDDATA;
+            }
             if (enc->codec_id == AV_CODEC_ID_MP3) {
                 swf->audio_enc = enc;
                 swf->audio_fifo= av_fifo_alloc(AUDIO_FIFO_SIZE);
@@ -197,6 +201,10 @@
                 return -1;
             }
         } else {
+            if (swf->video_enc) {
+                av_log(s, AV_LOG_ERROR, "SWF muxer only supports 1 video stream\n");
+                return AVERROR_INVALIDDATA;
+            }
             if (enc->codec_id == AV_CODEC_ID_VP6F ||
                 enc->codec_id == AV_CODEC_ID_FLV1 ||
                 enc->codec_id == AV_CODEC_ID_MJPEG) {
@@ -479,8 +487,10 @@
         enc = s->streams[i]->codec;
         if (enc->codec_type == AVMEDIA_TYPE_VIDEO)
             video_enc = enc;
-        else
+        else {
             av_fifo_free(swf->audio_fifo);
+            swf->audio_fifo = NULL;
+        }
     }
 
     put_swf_tag(s, TAG_END);
diff --git a/libavformat/takdec.c b/libavformat/takdec.c
new file mode 100644
index 0000000..a529017
--- /dev/null
+++ b/libavformat/takdec.c
@@ -0,0 +1,186 @@
+/*
+ * Raw TAK demuxer
+ * Copyright (c) 2012 Paul B Mahol
+ *
+ * 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 "libavcodec/tak.h"
+#include "avformat.h"
+#include "internal.h"
+#include "rawdec.h"
+#include "apetag.h"
+
+typedef struct TAKDemuxContext {
+    int      mlast_frame;
+    int64_t  data_end;
+} TAKDemuxContext;
+
+static int tak_probe(AVProbeData *p)
+{
+    if (!memcmp(p->buf, "tBaK", 4))
+        return AVPROBE_SCORE_MAX / 2;
+    return 0;
+}
+
+static int tak_read_header(AVFormatContext *s)
+{
+    TAKDemuxContext *tc = s->priv_data;
+    AVIOContext *pb = s->pb;
+    GetBitContext gb;
+    AVStream *st;
+    uint8_t *buffer = NULL;
+    int ret;
+
+    st = avformat_new_stream(s, 0);
+    if (!st)
+        return AVERROR(ENOMEM);
+
+    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+    st->codec->codec_id   = AV_CODEC_ID_TAK;
+    st->need_parsing      = AVSTREAM_PARSE_FULL_RAW;
+
+    tc->mlast_frame = 0;
+    if (avio_rl32(pb) != MKTAG('t', 'B', 'a', 'K')) {
+        avio_seek(pb, -4, SEEK_CUR);
+        return 0;
+    }
+
+    while (!url_feof(pb)) {
+        enum TAKMetaDataType type;
+        int size;
+
+        type = avio_r8(pb) & 0x7f;
+        size = avio_rl24(pb);
+
+        switch (type) {
+        case TAK_METADATA_STREAMINFO:
+        case TAK_METADATA_LAST_FRAME:
+        case TAK_METADATA_ENCODER:
+            buffer = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
+            if (!buffer)
+                return AVERROR(ENOMEM);
+
+            if (avio_read(pb, buffer, size) != size) {
+                av_freep(&buffer);
+                return AVERROR(EIO);
+            }
+
+            init_get_bits(&gb, buffer, size * 8);
+            break;
+        case TAK_METADATA_MD5: {
+            uint8_t md5[16];
+            int i;
+
+            if (size != 19)
+                return AVERROR_INVALIDDATA;
+            avio_read(pb, md5, 16);
+            avio_skip(pb, 3);
+            av_log(s, AV_LOG_VERBOSE, "MD5=");
+            for (i = 0; i < 16; i++)
+                av_log(s, AV_LOG_VERBOSE, "%02x", md5[i]);
+            av_log(s, AV_LOG_VERBOSE, "\n");
+            break;
+            }
+        case TAK_METADATA_END: {
+            int64_t curpos = avio_tell(pb);
+
+            if (pb->seekable) {
+                ff_ape_parse_tag(s);
+                avio_seek(pb, curpos, SEEK_SET);
+            }
+
+            tc->data_end += curpos;
+            return 0;
+            break;
+            }
+        default:
+            ret = avio_skip(pb, size);
+            if (ret < 0)
+                return ret;
+        }
+
+        if (type == TAK_METADATA_STREAMINFO) {
+            TAKStreamInfo ti;
+
+            avpriv_tak_parse_streaminfo(&gb, &ti);
+            if (ti.samples > 0)
+                st->duration = ti.samples;
+            st->codec->bits_per_coded_sample = ti.bps;
+            if (ti.ch_layout)
+                st->codec->channel_layout = ti.ch_layout;
+            st->codec->sample_rate = ti.sample_rate;
+            st->codec->channels    = ti.channels;
+            st->start_time         = 0;
+            avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
+            st->codec->extradata      = buffer;
+            st->codec->extradata_size = size;
+            buffer = NULL;
+        } else if (type == TAK_METADATA_LAST_FRAME) {
+            if (size != 11)
+                return AVERROR_INVALIDDATA;
+            tc->mlast_frame = 1;
+            tc->data_end = get_bits_longlong(&gb, TAK_LAST_FRAME_POS_BITS) +
+                           get_bits(&gb, TAK_LAST_FRAME_SIZE_BITS);
+            av_freep(&buffer);
+        } else if (type == TAK_METADATA_ENCODER) {
+            av_log(s, AV_LOG_VERBOSE, "encoder version: %0X\n",
+                   get_bits_long(&gb, TAK_ENCODER_VERSION_BITS));
+            av_freep(&buffer);
+        }
+    }
+
+    return AVERROR_EOF;
+}
+
+static int raw_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    TAKDemuxContext *tc = s->priv_data;
+    int ret;
+
+    if (tc->mlast_frame) {
+        AVIOContext *pb = s->pb;
+        int64_t size, left;
+
+        left = tc->data_end - avio_tell(s->pb);
+        size = FFMIN(left, 1024);
+        if (size <= 0)
+            return AVERROR_EOF;
+
+        ret = av_get_packet(pb, pkt, size);
+        if (ret < 0)
+            return ret;
+
+        pkt->stream_index = 0;
+    } else {
+        ret = ff_raw_read_partial_packet(s, pkt);
+    }
+
+    return ret;
+}
+
+AVInputFormat ff_tak_demuxer = {
+    .name           = "tak",
+    .long_name      = NULL_IF_CONFIG_SMALL("raw TAK"),
+    .priv_data_size = sizeof(TAKDemuxContext),
+    .read_probe     = tak_probe,
+    .read_header    = tak_read_header,
+    .read_packet    = raw_read_packet,
+    .flags          = AVFMT_GENERIC_INDEX,
+    .extensions     = "tak",
+    .raw_codec_id   = AV_CODEC_ID_TAK,
+};
diff --git a/libavformat/tcp.c b/libavformat/tcp.c
index 8cd217b..8b35fb1 100644
--- a/libavformat/tcp.c
+++ b/libavformat/tcp.c
@@ -20,6 +20,7 @@
  */
 #include "avformat.h"
 #include "libavutil/parseutils.h"
+#include "libavutil/opt.h"
 #include "internal.h"
 #include "network.h"
 #include "os_support.h"
@@ -29,23 +30,43 @@
 #endif
 
 typedef struct TCPContext {
+    const AVClass *class;
     int fd;
+    int listen;
+    int rw_timeout;
+    int listen_timeout;
 } TCPContext;
 
+#define OFFSET(x) offsetof(TCPContext, x)
+#define D AV_OPT_FLAG_DECODING_PARAM
+#define E AV_OPT_FLAG_ENCODING_PARAM
+static const AVOption options[] = {
+{"listen", "listen on port instead of connecting", OFFSET(listen), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
+{"timeout", "timeout of socket i/o operations", OFFSET(rw_timeout), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, D|E },
+{"listen_timeout", "connection awaiting timeout", OFFSET(listen_timeout), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, D|E },
+{NULL}
+};
+
+static const AVClass tcp_context_class = {
+    .class_name = "tcp",
+    .item_name  = av_default_item_name,
+    .option     = options,
+    .version    = LIBAVUTIL_VERSION_INT,
+};
+
 /* return non zero if error */
 static int tcp_open(URLContext *h, const char *uri, int flags)
 {
     struct addrinfo hints = { 0 }, *ai, *cur_ai;
     int port, fd = -1;
     TCPContext *s = h->priv_data;
-    int listen_socket = 0;
     const char *p;
     char buf[256];
     int ret;
     socklen_t optlen;
-    int timeout = 50, listen_timeout = -1;
     char hostname[1024],proto[1024],path[1024];
     char portstr[10];
+    h->rw_timeout = 5000000;
 
     av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname),
         &port, path, sizeof(path), uri);
@@ -58,18 +79,19 @@
     p = strchr(uri, '?');
     if (p) {
         if (av_find_info_tag(buf, sizeof(buf), "listen", p))
-            listen_socket = 1;
+            s->listen = 1;
         if (av_find_info_tag(buf, sizeof(buf), "timeout", p)) {
-            timeout = strtol(buf, NULL, 10);
+            s->rw_timeout = strtol(buf, NULL, 10);
         }
         if (av_find_info_tag(buf, sizeof(buf), "listen_timeout", p)) {
-            listen_timeout = strtol(buf, NULL, 10);
+            s->listen_timeout = strtol(buf, NULL, 10);
         }
     }
+    h->rw_timeout = s->rw_timeout;
     hints.ai_family = AF_UNSPEC;
     hints.ai_socktype = SOCK_STREAM;
     snprintf(portstr, sizeof(portstr), "%d", port);
-    if (listen_socket)
+    if (s->listen)
         hints.ai_flags |= AI_PASSIVE;
     if (!hostname[0])
         ret = getaddrinfo(NULL, portstr, &hints, &ai);
@@ -90,7 +112,7 @@
     if (fd < 0)
         goto fail;
 
-    if (listen_socket) {
+    if (s->listen) {
         int fd1;
         int reuse = 1;
         struct pollfd lp = { fd, POLLIN, 0 };
@@ -105,7 +127,7 @@
             ret = ff_neterrno();
             goto fail1;
         }
-        ret = poll(&lp, 1, listen_timeout >= 0 ? listen_timeout : -1);
+        ret = poll(&lp, 1, s->listen_timeout >= 0 ? s->listen_timeout : -1);
         if (ret <= 0) {
             ret = AVERROR(ETIMEDOUT);
             goto fail1;
@@ -126,6 +148,7 @@
 
     if (ret < 0) {
         struct pollfd p = {fd, POLLOUT, 0};
+        int64_t wait_started;
         ret = ff_neterrno();
         if (ret == AVERROR(EINTR)) {
             if (ff_check_interrupt(&h->interrupt_callback)) {
@@ -139,7 +162,8 @@
             goto fail;
 
         /* wait until we are connected or until abort */
-        while(timeout--) {
+        wait_started = av_gettime();
+        do {
             if (ff_check_interrupt(&h->interrupt_callback)) {
                 ret = AVERROR_EXIT;
                 goto fail1;
@@ -147,7 +171,7 @@
             ret = poll(&p, 1, 100);
             if (ret > 0)
                 break;
-        }
+        } while (!h->rw_timeout || (av_gettime() - wait_started < h->rw_timeout));
         if (ret <= 0) {
             ret = AVERROR(ETIMEDOUT);
             goto fail;
@@ -192,8 +216,8 @@
     int ret;
 
     if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
-        ret = ff_network_wait_fd(s->fd, 0);
-        if (ret < 0)
+        ret = ff_network_wait_fd_timeout(s->fd, 0, h->rw_timeout, &h->interrupt_callback);
+        if (ret)
             return ret;
     }
     ret = recv(s->fd, buf, size, 0);
@@ -206,8 +230,8 @@
     int ret;
 
     if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
-        ret = ff_network_wait_fd(s->fd, 1);
-        if (ret < 0)
+        ret = ff_network_wait_fd_timeout(s->fd, 1, h->rw_timeout, &h->interrupt_callback);
+        if (ret)
             return ret;
     }
     ret = send(s->fd, buf, size, 0);
@@ -252,5 +276,6 @@
     .url_get_file_handle = tcp_get_file_handle,
     .url_shutdown        = tcp_shutdown,
     .priv_data_size      = sizeof(TCPContext),
+    .priv_data_class     = &tcp_context_class,
     .flags               = URL_PROTOCOL_FLAG_NETWORK,
 };
diff --git a/libavformat/thp.c b/libavformat/thp.c
index 0e96b53..4463484 100644
--- a/libavformat/thp.c
+++ b/libavformat/thp.c
@@ -151,7 +151,7 @@
     if (thp->audiosize == 0) {
         /* Terminate when last frame is reached.  */
         if (thp->frame >= thp->framecnt)
-            return AVERROR(EIO);
+            return AVERROR_EOF;
 
         avio_seek(pb, thp->next_frame, SEEK_SET);
 
diff --git a/libavformat/tiertexseq.c b/libavformat/tiertexseq.c
index 88941b7..917a331 100644
--- a/libavformat/tiertexseq.c
+++ b/libavformat/tiertexseq.c
@@ -24,6 +24,7 @@
  * Tiertex Limited SEQ file demuxer
  */
 
+#include "libavutil/channel_layout.h"
 #include "avformat.h"
 #include "internal.h"
 
@@ -231,6 +232,7 @@
     st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
     st->codec->codec_tag = 0;  /* no tag */
     st->codec->channels = 1;
+    st->codec->channel_layout = AV_CH_LAYOUT_MONO;
     st->codec->sample_rate = SEQ_SAMPLE_RATE;
     st->codec->bits_per_coded_sample = 16;
     st->codec->bit_rate = st->codec->sample_rate * st->codec->bits_per_coded_sample * st->codec->channels;
diff --git a/libavformat/tmv.c b/libavformat/tmv.c
index 5134369..8be4dbf 100644
--- a/libavformat/tmv.c
+++ b/libavformat/tmv.c
@@ -26,6 +26,7 @@
  * @see http://www.oldskool.org/pc/8088_Corruption
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "internal.h"
@@ -112,7 +113,13 @@
 
     ast->codec->codec_type            = AVMEDIA_TYPE_AUDIO;
     ast->codec->codec_id              = AV_CODEC_ID_PCM_U8;
-    ast->codec->channels              = features & TMV_STEREO ? 2 : 1;
+    if (features & TMV_STEREO) {
+        ast->codec->channels       = 2;
+        ast->codec->channel_layout = AV_CH_LAYOUT_STEREO;
+    } else {
+        ast->codec->channels       = 1;
+        ast->codec->channel_layout = AV_CH_LAYOUT_MONO;
+    }
     ast->codec->bits_per_coded_sample = 8;
     ast->codec->bit_rate              = ast->codec->sample_rate *
                                         ast->codec->bits_per_coded_sample;
@@ -124,7 +131,7 @@
 
     vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
     vst->codec->codec_id   = AV_CODEC_ID_TMV;
-    vst->codec->pix_fmt    = PIX_FMT_PAL8;
+    vst->codec->pix_fmt    = AV_PIX_FMT_PAL8;
     vst->codec->width      = char_cols * 8;
     vst->codec->height     = char_rows * 8;
     avpriv_set_pts_info(vst, 32, fps.den, fps.num);
diff --git a/libavformat/tta.c b/libavformat/tta.c
index 1440c80..445389e 100644
--- a/libavformat/tta.c
+++ b/libavformat/tta.c
@@ -44,8 +44,9 @@
 {
     TTAContext *c = s->priv_data;
     AVStream *st;
-    int i, channels, bps, samplerate, datalen;
+    int i, channels, bps, samplerate;
     uint64_t framepos, start_offset;
+    uint32_t datalen;
 
     if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
         ff_id3v1_read(s);
@@ -64,9 +65,9 @@
     }
 
     datalen = avio_rl32(s->pb);
-    if(datalen < 0){
-        av_log(s, AV_LOG_ERROR, "nonsense datalen\n");
-        return -1;
+    if (!datalen) {
+        av_log(s, AV_LOG_ERROR, "invalid datalen\n");
+        return AVERROR_INVALIDDATA;
     }
 
     avio_skip(s->pb, 4); // header crc
diff --git a/libavformat/txd.c b/libavformat/txd.c
index 9e02d87..194945b 100644
--- a/libavformat/txd.c
+++ b/libavformat/txd.c
@@ -70,17 +70,17 @@
     }
 
     switch (id) {
-        case TXD_INFO:
-            if (chunk_size > 100)
-                break;
-        case TXD_EXTRA:
-            avio_skip(s->pb, chunk_size);
-        case TXD_FILE:
-        case TXD_TEXTURE:
-            goto next_chunk;
-        default:
-            av_log(s, AV_LOG_ERROR, "unknown chunk id %i\n", id);
-            return AVERROR_INVALIDDATA;
+    case TXD_INFO:
+        if (chunk_size > 100)
+            break;
+    case TXD_EXTRA:
+        avio_skip(s->pb, chunk_size);
+    case TXD_FILE:
+    case TXD_TEXTURE:
+        goto next_chunk;
+    default:
+        av_log(s, AV_LOG_ERROR, "unknown chunk id %i\n", id);
+        return AVERROR_INVALIDDATA;
     }
 
     ret = av_get_packet(s->pb, pkt, chunk_size);
diff --git a/libavformat/udp.c b/libavformat/udp.c
index 433f961..184ab81 100644
--- a/libavformat/udp.c
+++ b/libavformat/udp.c
@@ -312,7 +312,7 @@
 }
 
 static int udp_socket_create(UDPContext *s, struct sockaddr_storage *addr,
-                             int *addr_len, const char *localaddr)
+                             socklen_t *addr_len, const char *localaddr)
 {
     int udp_fd = -1;
     struct addrinfo *res0 = NULL, *res = NULL;
@@ -442,8 +442,12 @@
     int old_cancelstate;
 
     pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
-    ff_socket_nonblock(s->udp_fd, 0);
     pthread_mutex_lock(&s->mutex);
+    if (ff_socket_nonblock(s->udp_fd, 0) < 0) {
+        av_log(h, AV_LOG_ERROR, "Failed to set blocking mode");
+        s->circular_buffer_error = AVERROR(EIO);
+        goto end;
+    }
     while(1) {
         int len;
 
@@ -500,7 +504,7 @@
     const char *p;
     char buf[256];
     struct sockaddr_storage my_addr;
-    int len;
+    socklen_t len;
     int reuse_specified = 0;
     int i, include = 0, num_sources = 0;
     char *sources[32];
@@ -766,8 +770,10 @@
                 int64_t t = av_gettime() + 100000;
                 struct timespec tv = { .tv_sec  =  t / 1000000,
                                        .tv_nsec = (t % 1000000) * 1000 };
-                if (pthread_cond_timedwait(&s->cond, &s->mutex, &tv) < 0)
+                if (pthread_cond_timedwait(&s->cond, &s->mutex, &tv) < 0) {
+                    pthread_mutex_unlock(&s->mutex);
                     return AVERROR(errno == ETIMEDOUT ? EAGAIN : errno);
+                }
                 nonblock = 1;
             }
         } while( 1);
diff --git a/libavformat/url-test.c b/libavformat/url-test.c
new file mode 100644
index 0000000..ceaffe8
--- /dev/null
+++ b/libavformat/url-test.c
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2012 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
+ */
+
+#include "internal.h"
+
+#undef printf
+#undef exit
+
+static void test(const char *base, const char *rel)
+{
+    char buf[200], buf2[200];
+    ff_make_absolute_url(buf, sizeof(buf), base, rel);
+    printf("%s\n", buf);
+    if (base) {
+        /* Test in-buffer replacement */
+        snprintf(buf2, sizeof(buf2), "%s", base);
+        ff_make_absolute_url(buf2, sizeof(buf2), buf2, rel);
+        if (strcmp(buf, buf2)) {
+            printf("In-place handling of %s + %s failed\n", base, rel);
+            exit(1);
+        }
+    }
+}
+
+int main(void)
+{
+    test(NULL, "baz");
+    test("/foo/bar", "baz");
+    test("/foo/bar", "../baz");
+    test("/foo/bar", "/baz");
+    test("http://server/foo/", "baz");
+    test("http://server/foo/bar", "baz");
+    test("http://server/foo/", "../baz");
+    test("http://server/foo/bar/123", "../../baz");
+    test("http://server/foo/bar/123", "/baz");
+    test("http://server/foo/bar/123", "https://other/url");
+    test("http://server/foo/bar?param=value/with/slashes", "/baz");
+    test("http://server/foo/bar?param&otherparam", "?someparam");
+    test("http://server/foo/bar", "//other/url");
+    return 0;
+}
diff --git a/libavformat/utils.c b/libavformat/utils.c
index bc80dff..3bd97ee 100644
--- a/libavformat/utils.c
+++ b/libavformat/utils.c
@@ -78,56 +78,6 @@
     return ts > (RELATIVE_TS_BASE - (1LL<<48));
 }
 
-/* fraction handling */
-
-/**
- * f = val + (num / den) + 0.5.
- *
- * 'num' is normalized so that it is such as 0 <= num < den.
- *
- * @param f fractional number
- * @param val integer value
- * @param num must be >= 0
- * @param den must be >= 1
- */
-static void frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
-{
-    num += (den >> 1);
-    if (num >= den) {
-        val += num / den;
-        num = num % den;
-    }
-    f->val = val;
-    f->num = num;
-    f->den = den;
-}
-
-/**
- * Fractional addition to f: f = f + (incr / f->den).
- *
- * @param f fractional number
- * @param incr increment, can be positive or negative
- */
-static void frac_add(AVFrac *f, int64_t incr)
-{
-    int64_t num, den;
-
-    num = f->num + incr;
-    den = f->den;
-    if (num < 0) {
-        f->val += num / den;
-        num = num % den;
-        if (num < 0) {
-            num += den;
-            f->val--;
-        }
-    } else if (num >= den) {
-        f->val += num / den;
-        num = num % den;
-    }
-    f->num = num;
-}
-
 /** head of registered input format linked list */
 static AVInputFormat *first_iformat = NULL;
 /** head of registered output format linked list */
@@ -287,7 +237,7 @@
         }
 
         if(s->maxsize>=0 && remaining+1 < size){
-            av_log(0, remaining ? AV_LOG_ERROR : AV_LOG_DEBUG, "Truncating packet of size %d to %"PRId64"\n", size, remaining+1);
+            av_log(NULL, remaining ? AV_LOG_ERROR : AV_LOG_DEBUG, "Truncating packet of size %d to %"PRId64"\n", size, remaining+1);
             size= remaining+1;
         }
     }
@@ -345,6 +295,10 @@
     AVProbeData lpd = *pd;
     AVInputFormat *fmt1 = NULL, *fmt;
     int score, nodat = 0, score_max=0;
+    const static uint8_t zerobuffer[AVPROBE_PADDING_SIZE];
+
+    if (!lpd.buf)
+        lpd.buf = zerobuffer;
 
     if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
         int id3len = ff_id3v2_tag_len(lpd.buf);
@@ -475,7 +429,7 @@
 
     for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt;
         probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {
-        int score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0;
+        int score = probe_size < max_probe_size ? AVPROBE_SCORE_RETRY : 0;
         int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1;
         void *buftmp;
 
@@ -507,7 +461,7 @@
         /* guess file format */
         *fmt = av_probe_input_format2(&pd, 1, &score);
         if(*fmt){
-            if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration
+            if(score <= AVPROBE_SCORE_RETRY){ //this can only be true in the last iteration
                 av_log(logctx, AV_LOG_WARNING, "Format %s detected only with low score of %d, misdetection possible!\n", (*fmt)->name, score);
             }else
                 av_log(logctx, AV_LOG_DEBUG, "Format %s probed with size=%d and score=%d\n", (*fmt)->name, probe_size, score);
@@ -520,8 +474,7 @@
     }
 
     /* rewind. reuse probe buffer to avoid seeking */
-    if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
-        av_free(buf);
+    ret = ffio_rewind_with_probe_data(pb, &buf, pd.buf_size);
 
     return ret;
 }
@@ -531,6 +484,7 @@
 {
     int ret;
     AVProbeData pd = {filename, NULL, 0};
+    int score = AVPROBE_SCORE_RETRY;
 
     if (s->pb) {
         s->flags |= AVFMT_FLAG_CUSTOM_IO;
@@ -543,7 +497,7 @@
     }
 
     if ( (s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
-        (!s->iformat && (s->iformat = av_probe_input_format(&pd, 0))))
+        (!s->iformat && (s->iformat = av_probe_input_format2(&pd, 0, &score))))
         return 0;
 
     if ((ret = avio_open2(&s->pb, filename, AVIO_FLAG_READ | s->avio_flags,
@@ -593,7 +547,7 @@
     if (!s && !(s = avformat_alloc_context()))
         return AVERROR(ENOMEM);
     if (!s->av_class){
-        av_log(0, AV_LOG_ERROR, "Input context has not been properly allocated by avformat_alloc_context() and is not NULL either\n");
+        av_log(NULL, AV_LOG_ERROR, "Input context has not been properly allocated by avformat_alloc_context() and is not NULL either\n");
         return AVERROR(EINVAL);
     }
     if (fmt)
@@ -607,6 +561,7 @@
 
     if ((ret = init_input(s, filename, &tmp)) < 0)
         goto fail;
+    avio_skip(s->pb, s->skip_initial_bytes);
 
     /* check filename in case an image number is expected */
     if (s->iformat->flags & AVFMT_NEEDNUMBER) {
@@ -706,7 +661,7 @@
 
         if(end || av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
             int score= set_codec_from_probe_data(s, st, pd);
-            if(    (st->codec->codec_id != AV_CODEC_ID_NONE && score > AVPROBE_SCORE_MAX/4)
+            if(    (st->codec->codec_id != AV_CODEC_ID_NONE && score > AVPROBE_SCORE_RETRY)
                 || end){
                 pd->buf_size=0;
                 av_freep(&pd->buf);
@@ -830,7 +785,7 @@
 /**
  * Get the number of samples of an audio frame. Return -1 on error.
  */
-static int get_audio_frame_size(AVCodecContext *enc, int size, int mux)
+int ff_get_audio_frame_size(AVCodecContext *enc, int size, int mux)
 {
     int frame_size;
 
@@ -852,8 +807,8 @@
 /**
  * Return the frame duration in seconds. Return 0 if not available.
  */
-static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
-                                   AVCodecParserContext *pc, AVPacket *pkt)
+void ff_compute_frame_duration(int *pnum, int *pden, AVStream *st,
+                               AVCodecParserContext *pc, AVPacket *pkt)
 {
     int frame_size;
 
@@ -871,7 +826,10 @@
             *pnum = st->codec->time_base.num;
             *pden = st->codec->time_base.den;
             if (pc && pc->repeat_pict) {
-                *pnum = (*pnum) * (1 + pc->repeat_pict);
+                if (*pnum > INT_MAX / (1 + pc->repeat_pict))
+                    *pden /= 1 + pc->repeat_pict;
+                else
+                    *pnum *= 1 + pc->repeat_pict;
             }
             //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
             //Thus if we have no parser in such case leave duration undefined.
@@ -881,7 +839,7 @@
         }
         break;
     case AVMEDIA_TYPE_AUDIO:
-        frame_size = get_audio_frame_size(st->codec, pkt->size, 0);
+        frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 0);
         if (frame_size <= 0 || st->codec->sample_rate <= 0)
             break;
         *pnum = frame_size;
@@ -940,7 +898,7 @@
 {
     AVStream *st= s->streams[stream_index];
     AVPacketList *pktl= s->parse_queue ? s->parse_queue : s->packet_buffer;
-    int64_t pts_buffer[MAX_REORDER_DELAY];
+    int64_t pts_buffer[MAX_REORDER_DELAY+1];
     int64_t shift;
     int i, delay;
 
@@ -952,7 +910,7 @@
     st->cur_dts= dts;
     shift = st->first_dts - RELATIVE_TS_BASE;
 
-    for (i=0; i<MAX_REORDER_DELAY; i++)
+    for (i=0; i<MAX_REORDER_DELAY+1; i++)
         pts_buffer[i] = AV_NOPTS_VALUE;
 
     if (is_relative(pts))
@@ -1071,7 +1029,7 @@
     }
 
     if (pkt->duration == 0) {
-        compute_frame_duration(&num, &den, st, pc, pkt);
+        ff_compute_frame_duration(&num, &den, st, pc, pkt);
         if (den && num) {
             pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);
         }
@@ -2095,6 +2053,7 @@
     int64_t duration, duration1, filesize;
     int i;
     AVStream *st;
+    AVProgram *p;
 
     start_time = INT64_MAX;
     start_time_text = INT64_MAX;
@@ -2109,11 +2068,18 @@
                     start_time_text = start_time1;
             } else
                 start_time = FFMIN(start_time, start_time1);
+            end_time1 = AV_NOPTS_VALUE;
             if (st->duration != AV_NOPTS_VALUE) {
                 end_time1 = start_time1
                           + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
                 end_time = FFMAX(end_time, end_time1);
             }
+            for(p = NULL; (p = av_find_program_from_stream(ic, p, i)); ){
+                if(p->start_time == AV_NOPTS_VALUE || p->start_time > start_time1)
+                    p->start_time = start_time1;
+                if(p->end_time < end_time1)
+                    p->end_time = end_time1;
+            }
         }
         if (st->duration != AV_NOPTS_VALUE) {
             duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
@@ -2127,8 +2093,16 @@
 
     if (start_time != INT64_MAX) {
         ic->start_time = start_time;
-        if (end_time != INT64_MIN)
-            duration = FFMAX(duration, end_time - start_time);
+        if (end_time != INT64_MIN) {
+            if (ic->nb_programs) {
+                for (i=0; i<ic->nb_programs; i++) {
+                    p = ic->programs[i];
+                    if(p->start_time != AV_NOPTS_VALUE && p->end_time > p->start_time)
+                        duration = FFMAX(duration, p->end_time - p->start_time);
+                }
+            } else
+                duration = FFMAX(duration, end_time - start_time);
+        }
     }
     if (duration != INT64_MIN && duration > 0 && ic->duration == AV_NOPTS_VALUE) {
         ic->duration = duration;
@@ -2189,8 +2163,8 @@
     }
 }
 
-#define DURATION_MAX_READ_SIZE 250000
-#define DURATION_MAX_RETRY 3
+#define DURATION_MAX_READ_SIZE 250000LL
+#define DURATION_MAX_RETRY 4
 
 /* only usable for MPEG-PS streams */
 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
@@ -2343,7 +2317,7 @@
     case AVMEDIA_TYPE_VIDEO:
         if (!avctx->width)
             FAIL("unspecified size");
-        if (st->info->found_decoder >= 0 && avctx->pix_fmt == PIX_FMT_NONE)
+        if (st->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
             FAIL("unspecified pixel format");
         break;
     case AVMEDIA_TYPE_SUBTITLE:
@@ -2466,6 +2440,37 @@
     return AV_CODEC_ID_NONE;
 }
 
+enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
+{
+    if (flt) {
+        switch (bps) {
+        case 32: return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
+        case 64: return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;
+        default: return AV_CODEC_ID_NONE;
+        }
+    } else {
+        bps  += 7;
+        bps >>= 3;
+        if (sflags & (1 << (bps - 1))) {
+            switch (bps) {
+            case 1:  return AV_CODEC_ID_PCM_S8;
+            case 2:  return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
+            case 3:  return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
+            case 4:  return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
+            default: return AV_CODEC_ID_NONE;
+            }
+        } else {
+            switch (bps) {
+            case 1:  return AV_CODEC_ID_PCM_U8;
+            case 2:  return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;
+            case 3:  return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;
+            case 4:  return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;
+            default: return AV_CODEC_ID_NONE;
+            }
+        }
+    }
+}
+
 unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum AVCodecID id)
 {
     int i;
@@ -2525,6 +2530,7 @@
        || c->time_base.den <    5L*c->time_base.num
 /*       || c->codec_tag == AV_RL32("DIVX")
        || c->codec_tag == AV_RL32("XVID")*/
+       || c->codec_tag == AV_RL32("mp4v")
        || c->codec_id == AV_CODEC_ID_MPEG2VIDEO
        || c->codec_id == AV_CODEC_ID_H264
        )
@@ -2735,7 +2741,10 @@
                 av_log(ic, AV_LOG_WARNING, "max_analyze_duration %d reached at %"PRId64"\n", ic->max_analyze_duration, t);
                 break;
             }
-            st->info->codec_info_duration += pkt->duration;
+            if (pkt->duration) {
+                st->info->codec_info_duration        += pkt->duration;
+                st->info->codec_info_duration_fields += st->parser && st->codec->ticks_per_frame==2 ? st->parser->repeat_pict + 1 : 2;
+            }
         }
 #if FF_API_R_FRAME_RATE
         {
@@ -2751,7 +2760,7 @@
                     int framerate= get_std_framerate(i);
                     double sdts= dts*framerate/(1001*12);
                     for(j=0; j<2; j++){
-                        int ticks= lrintf(sdts+j*0.5);
+                        int64_t ticks= llrint(sdts+j*0.5);
                         double error= sdts - ticks + j*0.5;
                         st->info->duration_error[j][0][i] += error;
                         st->info->duration_error[j][1][i] += error*error;
@@ -2759,7 +2768,7 @@
                 }
                 st->info->duration_count++;
                 // ignore the first 4 values, they might have some random jitter
-                if (st->info->duration_count > 3)
+                if (st->info->duration_count > 3 && is_relative(pkt->dts) == is_relative(last))
                     st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
             }
             if (pkt->dts != AV_NOPTS_VALUE)
@@ -2846,13 +2855,13 @@
             }
 
             /* estimate average framerate if not set by demuxer */
-            if (st->codec_info_nb_frames>2 && !st->avg_frame_rate.num && st->info->codec_info_duration) {
+            if (st->info->codec_info_duration_fields && !st->avg_frame_rate.num && st->info->codec_info_duration) {
                 int      best_fps = 0;
                 double best_error = 0.01;
 
                 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
-                          (st->codec_info_nb_frames-2)*(int64_t)st->time_base.den,
-                          st->info->codec_info_duration*(int64_t)st->time_base.num, 60000);
+                          st->info->codec_info_duration_fields*(int64_t)st->time_base.den,
+                          st->info->codec_info_duration*2*(int64_t)st->time_base.num, 60000);
 
                 /* round guessed framerate to a "standard" framerate if it's
                  * within 1% of the original estimate*/
@@ -2975,7 +2984,7 @@
                         int flags)
 {
     int i, nb_streams = ic->nb_streams;
-    int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
+    int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1, best_bitrate = -1, best_multiframe = -1, count, bitrate, multiframe;
     unsigned *program = NULL;
     AVCodec *decoder = NULL, *best_decoder = NULL;
 
@@ -3004,9 +3013,16 @@
                 continue;
             }
         }
-        if (best_count >= st->codec_info_nb_frames)
+        count = st->codec_info_nb_frames;
+        bitrate = avctx->bit_rate;
+        multiframe = FFMIN(5, count);
+        if ((best_multiframe >  multiframe) ||
+            (best_multiframe == multiframe && best_bitrate >  bitrate) ||
+            (best_multiframe == multiframe && best_bitrate == bitrate && best_count >= count))
             continue;
-        best_count = st->codec_info_nb_frames;
+        best_count = count;
+        best_bitrate = bitrate;
+        best_multiframe = multiframe;
         ret = real_stream_index;
         best_decoder = decoder;
         if (program && i == nb_streams - 1 && ret < 0) {
@@ -3064,6 +3080,9 @@
 {
     int i;
 
+    if (!s)
+        return;
+
     av_opt_free(s);
     if (s->iformat && s->iformat->priv_class && s->priv_data)
         av_opt_free(s->priv_data);
@@ -3128,7 +3147,7 @@
 }
 #endif
 
-AVStream *avformat_new_stream(AVFormatContext *s, AVCodec *c)
+AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c)
 {
     AVStream *st;
     int i;
@@ -3205,6 +3224,9 @@
     }
     program->id = id;
 
+    program->start_time =
+    program->end_time   = AV_NOPTS_VALUE;
+
     return program;
 }
 
@@ -3232,648 +3254,6 @@
     return chapter;
 }
 
-/************************************************************/
-/* output media file */
-
-int avformat_alloc_output_context2(AVFormatContext **avctx, AVOutputFormat *oformat,
-                                   const char *format, const char *filename)
-{
-    AVFormatContext *s = avformat_alloc_context();
-    int ret = 0;
-
-    *avctx = NULL;
-    if (!s)
-        goto nomem;
-
-    if (!oformat) {
-        if (format) {
-            oformat = av_guess_format(format, NULL, NULL);
-            if (!oformat) {
-                av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format);
-                ret = AVERROR(EINVAL);
-                goto error;
-            }
-        } else {
-            oformat = av_guess_format(NULL, filename, NULL);
-            if (!oformat) {
-                ret = AVERROR(EINVAL);
-                av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n",
-                       filename);
-                goto error;
-            }
-        }
-    }
-
-    s->oformat = oformat;
-    if (s->oformat->priv_data_size > 0) {
-        s->priv_data = av_mallocz(s->oformat->priv_data_size);
-        if (!s->priv_data)
-            goto nomem;
-        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;
-
-    if (filename)
-        av_strlcpy(s->filename, filename, sizeof(s->filename));
-    *avctx = s;
-    return 0;
-nomem:
-    av_log(s, AV_LOG_ERROR, "Out of memory\n");
-    ret = AVERROR(ENOMEM);
-error:
-    avformat_free_context(s);
-    return ret;
-}
-
-#if FF_API_ALLOC_OUTPUT_CONTEXT
-AVFormatContext *avformat_alloc_output_context(const char *format,
-                                               AVOutputFormat *oformat, const char *filename)
-{
-    AVFormatContext *avctx;
-    int ret = avformat_alloc_output_context2(&avctx, oformat, format, filename);
-    return ret < 0 ? NULL : avctx;
-}
-#endif
-
-static int validate_codec_tag(AVFormatContext *s, AVStream *st)
-{
-    const AVCodecTag *avctag;
-    int n;
-    enum AVCodecID id = AV_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 != AV_CODEC_ID_NONE) {
-            if (avpriv_toupper4(avctag->tag) == avpriv_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 != AV_CODEC_ID_NONE)
-        return 0;
-    if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
-        return 0;
-    return 1;
-}
-
-int avformat_write_header(AVFormatContext *s, AVDictionary **options)
-{
-    int ret = 0, i;
-    AVStream *st;
-    AVDictionary *tmp = NULL;
-
-    if (options)
-        av_dict_copy(&tmp, *options, 0);
-    if ((ret = av_opt_set_dict(s, &tmp)) < 0)
-        goto fail;
-    if (s->priv_data && s->oformat->priv_class && *(const AVClass**)s->priv_data==s->oformat->priv_class &&
-        (ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
-        goto fail;
-
-    // some sanity checks
-    if (s->nb_streams == 0 && !(s->oformat->flags & AVFMT_NOSTREAMS)) {
-        av_log(s, AV_LOG_ERROR, "no streams\n");
-        ret = AVERROR(EINVAL);
-        goto fail;
-    }
-
-    for(i=0;i<s->nb_streams;i++) {
-        st = s->streams[i];
-
-        switch (st->codec->codec_type) {
-        case AVMEDIA_TYPE_AUDIO:
-            if(st->codec->sample_rate<=0){
-                av_log(s, AV_LOG_ERROR, "sample rate not set\n");
-                ret = AVERROR(EINVAL);
-                goto fail;
-            }
-            if(!st->codec->block_align)
-                st->codec->block_align = st->codec->channels *
-                    av_get_bits_per_sample(st->codec->codec_id) >> 3;
-            break;
-        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");
-                ret = AVERROR(EINVAL);
-                goto fail;
-            }
-            if((st->codec->width<=0 || st->codec->height<=0) && !(s->oformat->flags & AVFMT_NODIMENSIONS)){
-                av_log(s, AV_LOG_ERROR, "dimensions not set\n");
-                ret = AVERROR(EINVAL);
-                goto fail;
-            }
-            if(av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)
-               && FFABS(av_q2d(st->sample_aspect_ratio) - av_q2d(st->codec->sample_aspect_ratio)) > 0.004*av_q2d(st->sample_aspect_ratio)
-            ){
-                av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
-                       "(%d/%d) and encoder layer (%d/%d)\n",
-                       st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
-                       st->codec->sample_aspect_ratio.num,
-                       st->codec->sample_aspect_ratio.den);
-                ret = AVERROR(EINVAL);
-                goto fail;
-            }
-            break;
-        }
-
-        if(s->oformat->codec_tag){
-            if(   st->codec->codec_tag
-               && st->codec->codec_id == AV_CODEC_ID_RAWVIDEO
-               && (av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id) == 0 || av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id) ==MKTAG('r', 'a', 'w', ' '))
-               && !validate_codec_tag(s, st)){
-                //the current rawvideo encoding system ends up setting the wrong codec_tag for avi/mov, we override it here
-                st->codec->codec_tag= 0;
-            }
-            if(st->codec->codec_tag){
-                if (!validate_codec_tag(s, st)) {
-                    char tagbuf[32], cortag[32];
-                    av_get_codec_tag_string(tagbuf, sizeof(tagbuf), st->codec->codec_tag);
-                    av_get_codec_tag_string(cortag, sizeof(cortag), av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id));
-                    av_log(s, AV_LOG_ERROR,
-                           "Tag %s/0x%08x incompatible with output codec id '%d' (%s)\n",
-                           tagbuf, st->codec->codec_tag, st->codec->codec_id, cortag);
-                    ret = AVERROR_INVALIDDATA;
-                    goto fail;
-                }
-            }else
-                st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
-        }
-
-        if(s->oformat->flags & AVFMT_GLOBALHEADER &&
-            !(st->codec->flags & CODEC_FLAG_GLOBAL_HEADER))
-          av_log(s, AV_LOG_WARNING, "Codec for stream %d does not use global headers but container format requires global headers\n", i);
-    }
-
-    if (!s->priv_data && s->oformat->priv_data_size > 0) {
-        s->priv_data = av_mallocz(s->oformat->priv_data_size);
-        if (!s->priv_data) {
-            ret = AVERROR(ENOMEM);
-            goto fail;
-        }
-        if (s->oformat->priv_class) {
-            *(const AVClass**)s->priv_data= s->oformat->priv_class;
-            av_opt_set_defaults(s->priv_data);
-            if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
-                goto fail;
-        }
-    }
-
-    /* set muxer identification string */
-    if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
-        av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
-    }
-
-    if(s->oformat->write_header){
-        ret = s->oformat->write_header(s);
-        if (ret >= 0 && s->pb && s->pb->error < 0)
-            ret = s->pb->error;
-        if (ret < 0)
-            goto fail;
-    }
-
-    /* init PTS generation */
-    for(i=0;i<s->nb_streams;i++) {
-        int64_t den = AV_NOPTS_VALUE;
-        st = s->streams[i];
-
-        switch (st->codec->codec_type) {
-        case AVMEDIA_TYPE_AUDIO:
-            den = (int64_t)st->time_base.num * st->codec->sample_rate;
-            break;
-        case AVMEDIA_TYPE_VIDEO:
-            den = (int64_t)st->time_base.num * st->codec->time_base.den;
-            break;
-        default:
-            break;
-        }
-        if (den != AV_NOPTS_VALUE) {
-            if (den <= 0) {
-                ret = AVERROR_INVALIDDATA;
-                goto fail;
-            }
-            frac_init(&st->pts, 0, 0, den);
-        }
-    }
-
-    if (options) {
-        av_dict_free(options);
-        *options = tmp;
-    }
-    return 0;
-fail:
-    av_dict_free(&tmp);
-    return ret;
-}
-
-//FIXME merge with compute_pkt_fields
-static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt){
-    int delay = FFMAX(st->codec->has_b_frames, st->codec->max_b_frames > 0);
-    int num, den, frame_size, i;
-
-    av_dlog(s, "compute_pkt_fields2: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
-            av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), delay, pkt->size, pkt->stream_index);
-
-    /* duration field */
-    if (pkt->duration == 0) {
-        compute_frame_duration(&num, &den, st, NULL, pkt);
-        if (den && num) {
-            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
-        }
-    }
-
-    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)
-        pkt->pts= pkt->dts;
-
-    //XXX/FIXME this is a temporary hack until all encoders output pts
-    if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
-        static int warned;
-        if (!warned) {
-            av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
-            warned = 1;
-        }
-        pkt->dts=
-//        pkt->pts= st->cur_dts;
-        pkt->pts= st->pts.val;
-    }
-
-    //calculate dts from pts
-    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
-        st->pts_buffer[0]= pkt->pts;
-        for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
-            st->pts_buffer[i]= pkt->pts + (i-delay-1) * pkt->duration;
-        for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
-            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
-
-        pkt->dts= st->pts_buffer[0];
-    }
-
-    if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
-        ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
-          st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
-        av_log(s, AV_LOG_ERROR,
-               "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
-               st->index, av_ts2str(st->cur_dts), av_ts2str(pkt->dts));
-        return AVERROR(EINVAL);
-    }
-    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
-        av_log(s, AV_LOG_ERROR, "pts (%s) < dts (%s) in stream %d\n",
-               av_ts2str(pkt->pts), av_ts2str(pkt->dts), st->index);
-        return AVERROR(EINVAL);
-    }
-
-    av_dlog(s, "av_write_frame: pts2:%s dts2:%s\n",
-            av_ts2str(pkt->pts), av_ts2str(pkt->dts));
-    st->cur_dts= pkt->dts;
-    st->pts.val= pkt->dts;
-
-    /* update pts */
-    switch (st->codec->codec_type) {
-    case AVMEDIA_TYPE_AUDIO:
-        frame_size = get_audio_frame_size(st->codec, pkt->size, 1);
-
-        /* HACK/FIXME, we skip the initial 0 size packets as they are most
-           likely equal to the encoder delay, but it would be better if we
-           had the real timestamps from the encoder */
-        if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
-            frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
-        }
-        break;
-    case AVMEDIA_TYPE_VIDEO:
-        frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
-        break;
-    default:
-        break;
-    }
-    return 0;
-}
-
-int av_write_frame(AVFormatContext *s, AVPacket *pkt)
-{
-    int ret;
-
-    if (!pkt) {
-        if (s->oformat->flags & AVFMT_ALLOW_FLUSH) {
-            ret = s->oformat->write_packet(s, pkt);
-            if (ret >= 0 && s->pb && s->pb->error < 0)
-                ret = s->pb->error;
-            return ret;
-        }
-        return 1;
-    }
-
-    ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
-
-    if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
-        return ret;
-
-    ret= s->oformat->write_packet(s, pkt);
-    if (ret >= 0 && s->pb && s->pb->error < 0)
-        ret = s->pb->error;
-
-    if (ret >= 0)
-        s->streams[pkt->stream_index]->nb_frames++;
-    return ret;
-}
-
-#define CHUNK_START 0x1000
-
-int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
-                              int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
-{
-    AVPacketList **next_point, *this_pktl;
-    AVStream *st= s->streams[pkt->stream_index];
-    int chunked= s->max_chunk_size || s->max_chunk_duration;
-
-    this_pktl = av_mallocz(sizeof(AVPacketList));
-    if (!this_pktl)
-        return AVERROR(ENOMEM);
-    this_pktl->pkt= *pkt;
-    pkt->destruct= NULL;             // do not free original but only the copy
-    av_dup_packet(&this_pktl->pkt);  // duplicate the packet if it uses non-allocated memory
-
-    if(s->streams[pkt->stream_index]->last_in_packet_buffer){
-        next_point = &(st->last_in_packet_buffer->next);
-    }else{
-        next_point = &s->packet_buffer;
-    }
-
-    if(*next_point){
-        if(chunked){
-            uint64_t max= av_rescale_q(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base);
-            if(   st->interleaver_chunk_size     + pkt->size     <= s->max_chunk_size-1U
-               && st->interleaver_chunk_duration + pkt->duration <= max-1U){
-                st->interleaver_chunk_size     += pkt->size;
-                st->interleaver_chunk_duration += pkt->duration;
-                goto next_non_null;
-            }else{
-                st->interleaver_chunk_size     =
-                st->interleaver_chunk_duration = 0;
-                this_pktl->pkt.flags |= CHUNK_START;
-            }
-        }
-
-        if(compare(s, &s->packet_buffer_end->pkt, pkt)){
-            while(   *next_point
-                  && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
-                      || !compare(s, &(*next_point)->pkt, pkt))){
-                next_point= &(*next_point)->next;
-            }
-            if(*next_point)
-                goto next_non_null;
-        }else{
-            next_point = &(s->packet_buffer_end->next);
-        }
-    }
-    assert(!*next_point);
-
-    s->packet_buffer_end= this_pktl;
-next_non_null:
-
-    this_pktl->next= *next_point;
-
-    s->streams[pkt->stream_index]->last_in_packet_buffer=
-    *next_point= this_pktl;
-    return 0;
-}
-
-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];
-    int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
-                             st->time_base);
-    if(s->audio_preload && ((st->codec->codec_type == AVMEDIA_TYPE_AUDIO) != (st2->codec->codec_type == AVMEDIA_TYPE_AUDIO))){
-        int64_t ts = av_rescale_q(pkt ->dts, st ->time_base, AV_TIME_BASE_Q) - s->audio_preload*(st ->codec->codec_type == AVMEDIA_TYPE_AUDIO);
-        int64_t ts2= av_rescale_q(next->dts, st2->time_base, AV_TIME_BASE_Q) - s->audio_preload*(st2->codec->codec_type == AVMEDIA_TYPE_AUDIO);
-        if(ts == ts2){
-            ts= ( pkt ->dts* st->time_base.num*AV_TIME_BASE - s->audio_preload*(int64_t)(st ->codec->codec_type == AVMEDIA_TYPE_AUDIO)* st->time_base.den)*st2->time_base.den
-               -( next->dts*st2->time_base.num*AV_TIME_BASE - s->audio_preload*(int64_t)(st2->codec->codec_type == AVMEDIA_TYPE_AUDIO)*st2->time_base.den)* st->time_base.den;
-            ts2=0;
-        }
-        comp= (ts>ts2) - (ts<ts2);
-    }
-
-    if (comp == 0)
-        return pkt->stream_index < next->stream_index;
-    return comp > 0;
-}
-
-int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
-                                 AVPacket *pkt, int flush)
-{
-    AVPacketList *pktl;
-    int stream_count=0, noninterleaved_count=0;
-    int64_t delta_dts_max = 0;
-    int i, ret;
-
-    if(pkt){
-        ret = ff_interleave_add_packet(s, pkt, ff_interleave_compare_dts);
-        if (ret < 0)
-            return ret;
-    }
-
-    for(i=0; i < s->nb_streams; i++) {
-        if (s->streams[i]->last_in_packet_buffer) {
-            ++stream_count;
-        } else if(s->streams[i]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
-            ++noninterleaved_count;
-        }
-    }
-
-    if (s->nb_streams == stream_count) {
-        flush = 1;
-    } else if (!flush){
-        for(i=0; i < s->nb_streams; i++) {
-            if (s->streams[i]->last_in_packet_buffer) {
-                int64_t delta_dts =
-                    av_rescale_q(s->streams[i]->last_in_packet_buffer->pkt.dts,
-                                s->streams[i]->time_base,
-                                AV_TIME_BASE_Q) -
-                    av_rescale_q(s->packet_buffer->pkt.dts,
-                                s->streams[s->packet_buffer->pkt.stream_index]->time_base,
-                                AV_TIME_BASE_Q);
-                delta_dts_max= FFMAX(delta_dts_max, delta_dts);
-            }
-        }
-        if(s->nb_streams == stream_count+noninterleaved_count &&
-           delta_dts_max > 20*AV_TIME_BASE) {
-            av_log(s, AV_LOG_DEBUG, "flushing with %d noninterleaved\n", noninterleaved_count);
-            flush = 1;
-        }
-    }
-    if(stream_count && flush){
-        AVStream *st;
-        pktl= s->packet_buffer;
-        *out= pktl->pkt;
-        st = s->streams[out->stream_index];
-
-        s->packet_buffer= pktl->next;
-        if(!s->packet_buffer)
-            s->packet_buffer_end= NULL;
-
-        if(st->last_in_packet_buffer == pktl)
-            st->last_in_packet_buffer= NULL;
-        av_freep(&pktl);
-
-        if (s->avoid_negative_ts > 0) {
-            if (out->dts != AV_NOPTS_VALUE) {
-                if (!st->mux_ts_offset && out->dts < 0) {
-                    for(i=0; i < s->nb_streams; i++) {
-                        s->streams[i]->mux_ts_offset =
-                            av_rescale_q_rnd(-out->dts,
-                                             st->time_base,
-                                             s->streams[i]->time_base,
-                                             AV_ROUND_UP);
-                    }
-                }
-                out->dts += st->mux_ts_offset;
-            }
-            if (out->pts != AV_NOPTS_VALUE)
-                out->pts += st->mux_ts_offset;
-        }
-
-        return 1;
-    }else{
-        av_init_packet(out);
-        return 0;
-    }
-}
-
-#if FF_API_INTERLEAVE_PACKET
-int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
-                                 AVPacket *pkt, int flush)
-{
-    return ff_interleave_packet_per_dts(s, out, pkt, flush);
-}
-#endif
-
-/**
- * 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
- *              remaining packets should be output
- * @return 1 if a packet was output, 0 if no packet could be output,
- *         < 0 if an error occurred
- */
-static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
-    if (s->oformat->interleave_packet) {
-        int ret = s->oformat->interleave_packet(s, out, in, flush);
-        if (in)
-            av_free_packet(in);
-        return ret;
-    } else
-        return ff_interleave_packet_per_dts(s, out, in, flush);
-}
-
-int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
-    int ret, flush = 0;
-
-    if (pkt) {
-        AVStream *st= s->streams[ pkt->stream_index];
-
-        //FIXME/XXX/HACK drop zero sized packets
-        if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size==0)
-            return 0;
-
-        av_dlog(s, "av_interleaved_write_frame size:%d dts:%s pts:%s\n",
-                pkt->size, av_ts2str(pkt->dts), av_ts2str(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 AVERROR(EINVAL);
-    } else {
-        av_dlog(s, "av_interleaved_write_frame FLUSH\n");
-        flush = 1;
-    }
-
-    for(;;){
-        AVPacket opkt;
-        int ret= interleave_packet(s, &opkt, pkt, flush);
-        if(ret<=0) //FIXME cleanup needed for ret<0 ?
-            return ret;
-
-        ret= s->oformat->write_packet(s, &opkt);
-        if (ret >= 0)
-            s->streams[opkt.stream_index]->nb_frames++;
-
-        av_free_packet(&opkt);
-        pkt= NULL;
-
-        if(ret<0)
-            return ret;
-        if(s->pb && s->pb->error)
-            return s->pb->error;
-    }
-}
-
-int av_write_trailer(AVFormatContext *s)
-{
-    int ret, i;
-
-    for (;;) {
-        AVPacket pkt;
-        ret = interleave_packet(s, &pkt, NULL, 1);
-        if (ret < 0) //FIXME cleanup needed for ret<0 ?
-            goto fail;
-        if (!ret)
-            break;
-
-        ret = s->oformat->write_packet(s, &pkt);
-        if (ret >= 0)
-            s->streams[pkt.stream_index]->nb_frames++;
-
-        av_free_packet(&pkt);
-
-        if (ret < 0)
-            goto fail;
-        if(s->pb && s->pb->error)
-            goto fail;
-    }
-
-    if (s->oformat->write_trailer)
-        ret = s->oformat->write_trailer(s);
-
-fail:
-    if (s->pb)
-       avio_flush(s->pb);
-    if (ret == 0)
-       ret = s->pb ? s->pb->error : 0;
-    for (i = 0; i < s->nb_streams; i++) {
-        av_freep(&s->streams[i]->priv_data);
-        av_freep(&s->streams[i]->index_entries);
-    }
-    if (s->oformat->priv_class)
-        av_opt_free(s->priv_data);
-    av_freep(&s->priv_data);
-    return ret;
-}
-
-int av_get_output_timestamp(struct AVFormatContext *s, int stream,
-                            int64_t *dts, int64_t *wall)
-{
-    if (!s->oformat || !s->oformat->get_output_timestamp)
-        return AVERROR(ENOSYS);
-    s->oformat->get_output_timestamp(s, stream, dts, wall);
-    return 0;
-}
-
 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
 {
     int i, j;
@@ -4020,8 +3400,9 @@
         av_log(NULL, AV_LOG_INFO, "  Duration: ");
         if (ic->duration != AV_NOPTS_VALUE) {
             int hours, mins, secs, us;
-            secs = ic->duration / AV_TIME_BASE;
-            us = ic->duration % AV_TIME_BASE;
+            int64_t duration = ic->duration + 5000;
+            secs = duration / AV_TIME_BASE;
+            us = duration % AV_TIME_BASE;
             mins = secs / 60;
             secs %= 60;
             hours = mins / 60;
@@ -4139,7 +3520,8 @@
     return -1;
 }
 
-static void hex_dump_internal(void *avcl, FILE *f, int level, uint8_t *buf, int size)
+static void hex_dump_internal(void *avcl, FILE *f, int level,
+                              const uint8_t *buf, int size)
 {
     int len, i, j, c;
 #undef fprintf
@@ -4168,12 +3550,12 @@
 #undef PRINT
 }
 
-void av_hex_dump(FILE *f, uint8_t *buf, int size)
+void av_hex_dump(FILE *f, const uint8_t *buf, int size)
 {
     hex_dump_internal(NULL, f, 0, buf, size);
 }
 
-void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size)
+void av_hex_dump_log(void *avcl, int level, const uint8_t *buf, int size)
 {
     hex_dump_internal(avcl, NULL, level, buf, size);
 }
@@ -4238,7 +3620,7 @@
                   char *path, int path_size,
                   const char *url)
 {
-    const char *p, *ls, *ls2, *at, *col, *brk;
+    const char *p, *ls, *ls2, *at, *at2, *col, *brk;
 
     if (port_ptr)               *port_ptr = -1;
     if (proto_size > 0)         proto[0] = 0;
@@ -4273,9 +3655,10 @@
     /* the rest is hostname, use that to parse auth/port */
     if (ls != p) {
         /* authorization (user[:pass]@hostname) */
-        if ((at = strchr(p, '@')) && at < ls) {
-            av_strlcpy(authorization, p,
-                       FFMIN(authorization_size, at + 1 - p));
+        at2 = p;
+        while ((at = strchr(p, '@')) && at < ls) {
+            av_strlcpy(authorization, at2,
+                       FFMIN(authorization_size, at + 1 - at2));
             p = at + 1; /* skip '@' */
         }
 
@@ -4508,9 +3891,9 @@
         sep = strstr(buf, "://");
         if (sep) {
             /* Take scheme from base url */
-            if (rel[1] == '/')
+            if (rel[1] == '/') {
                 sep[1] = '\0';
-            else {
+            } else {
                 /* Take scheme and host from base url */
                 sep += 3;
                 sep = strchr(sep, '/');
diff --git a/libavformat/version.h b/libavformat/version.h
index 32a70d2..d82b948 100644
--- a/libavformat/version.h
+++ b/libavformat/version.h
@@ -30,8 +30,8 @@
 #include "libavutil/avutil.h"
 
 #define LIBAVFORMAT_VERSION_MAJOR 54
-#define LIBAVFORMAT_VERSION_MINOR 29
-#define LIBAVFORMAT_VERSION_MICRO 105
+#define LIBAVFORMAT_VERSION_MINOR 42
+#define LIBAVFORMAT_VERSION_MICRO 100
 
 #define LIBAVFORMAT_VERSION_INT AV_VERSION_INT(LIBAVFORMAT_VERSION_MAJOR, \
                                                LIBAVFORMAT_VERSION_MINOR, \
diff --git a/libavformat/vivo.c b/libavformat/vivo.c
new file mode 100644
index 0000000..e3487f6
--- /dev/null
+++ b/libavformat/vivo.c
@@ -0,0 +1,311 @@
+/*
+ * Vivo stream demuxer
+ * Copyright (c) 2009 Daniel Verkamp <daniel at drv.nu>
+ *
+ * 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
+ * @brief Vivo stream demuxer
+ * @author Daniel Verkamp <daniel at drv.nu>
+ * @sa http://wiki.multimedia.cx/index.php?title=Vivo
+ */
+
+#include "libavutil/parseutils.h"
+#include "avformat.h"
+#include "internal.h"
+
+typedef struct VivoContext {
+    int version;
+
+    int type;
+    int sequence;
+    int length;
+
+    uint8_t  text[1024 + 1];
+} VivoContext;
+
+static int vivo_probe(AVProbeData *p)
+{
+    const unsigned char *buf = p->buf;
+    unsigned c, length = 0;
+
+    // stream must start with packet of type 0 and sequence number 0
+    if (*buf++ != 0)
+        return 0;
+
+    // read at most 2 bytes of coded length
+    c = *buf++;
+    length = c & 0x7F;
+    if (c & 0x80) {
+        c = *buf++;
+        length = (length << 7) | (c & 0x7F);
+    }
+    if (c & 0x80 || length > 1024 || length < 21)
+        return 0;
+
+    if (memcmp(buf, "\r\nVersion:Vivo/", 15))
+        return 0;
+    buf += 15;
+
+    if (*buf < '0' && *buf > '2')
+        return 0;
+
+    return AVPROBE_SCORE_MAX;
+}
+
+static int vivo_get_packet_header(AVFormatContext *s)
+{
+    VivoContext *vivo = s->priv_data;
+    AVIOContext *pb = s->pb;
+    unsigned c, get_length = 0;
+
+    if (url_feof(pb))
+        return AVERROR_EOF;
+
+    c = avio_r8(pb);
+    if (c == 0x82) {
+        get_length = 1;
+        c = avio_r8(pb);
+    }
+
+    vivo->type     = c >> 4;
+    vivo->sequence = c & 0xF;
+
+    switch (vivo->type) {
+    case 0:   get_length =   1; break;
+    case 1: vivo->length = 128; break;
+    case 2:   get_length =   1; break;
+    case 3: vivo->length =  40; break;
+    case 4: vivo->length =  24; break;
+    default:
+        av_log(s, AV_LOG_ERROR, "unknown packet type %d\n", vivo->type);
+        return AVERROR_INVALIDDATA;
+    }
+
+    if (get_length) {
+        c = avio_r8(pb);
+        vivo->length = c & 0x7F;
+        if (c & 0x80) {
+            c = avio_r8(pb);
+            vivo->length = (vivo->length << 7) | (c & 0x7F);
+
+            if (c & 0x80) {
+                av_log(s, AV_LOG_ERROR, "coded length is more than two bytes\n");
+                return AVERROR_INVALIDDATA;
+            }
+        }
+    }
+
+    return 0;
+}
+
+static int vivo_read_header(AVFormatContext *s)
+{
+    VivoContext *vivo = s->priv_data;
+    AVRational fps = { 1, 25};
+    AVStream *ast, *vst;
+    unsigned char *line, *line_end, *key, *value;
+    long value_int;
+    int ret, value_used;
+    int64_t duration = 0;
+    char *end_value;
+
+    vst = avformat_new_stream(s, NULL);
+    ast = avformat_new_stream(s, NULL);
+    if (!ast || !vst)
+        return AVERROR(ENOMEM);
+
+    ast->codec->sample_rate = 8000;
+
+    while (1) {
+        if ((ret = vivo_get_packet_header(s)) < 0)
+            return ret;
+
+        // done reading all text header packets?
+        if (vivo->sequence || vivo->type)
+            break;
+
+        if (vivo->length <= 1024) {
+            avio_read(s->pb, vivo->text, vivo->length);
+            vivo->text[vivo->length] = 0;
+        } else {
+            av_log(s, AV_LOG_WARNING, "too big header, skipping\n");
+            avio_skip(s->pb, vivo->length);
+            continue;
+        }
+
+        line = vivo->text;
+        while (*line) {
+            line_end = strstr(line, "\r\n");
+            if (!line_end)
+                break;
+
+            *line_end = 0;
+            key = line;
+            line = line_end + 2; // skip \r\n
+
+            if (line_end == key) // skip blank lines
+                continue;
+
+            value = strchr(key, ':');
+            if (!value) {
+                av_log(s, AV_LOG_WARNING, "missing colon in key:value pair '%s'\n",
+                       value);
+                continue;
+            }
+
+            *value++ = 0;
+
+            av_log(s, AV_LOG_DEBUG, "header: '%s' = '%s'\n", key, value);
+
+            value_int = strtol(value, &end_value, 10);
+            value_used = 0;
+            if (*end_value == 0) { // valid integer
+                av_log(s, AV_LOG_DEBUG, "got a valid integer (%ld)\n", value_int);
+                value_used = 1;
+                if (!strcmp(key, "Duration")) {
+                    duration = value_int;
+                } else if (!strcmp(key, "Width")) {
+                    vst->codec->width = value_int;
+                } else if (!strcmp(key, "Height")) {
+                    vst->codec->height = value_int;
+                } else if (!strcmp(key, "TimeUnitNumerator")) {
+                    fps.num = value_int / 1000;
+                } else if (!strcmp(key, "TimeUnitDenominator")) {
+                    fps.den = value_int;
+                } else if (!strcmp(key, "SamplingFrequency")) {
+                    ast->codec->sample_rate = value_int;
+                } else if (!strcmp(key, "NominalBitrate")) {
+                } else if (!strcmp(key, "Length")) {
+                    // size of file
+                } else {
+                    value_used = 0;
+                }
+            }
+
+            if (!strcmp(key, "Version")) {
+                if (sscanf(value, "Vivo/%d.", &vivo->version) != 1)
+                    return AVERROR_INVALIDDATA;
+                value_used = 1;
+            } else if (!strcmp(key, "FPS")) {
+                AVRational tmp;
+
+                value_used = 1;
+                if (!av_parse_ratio(&tmp, value, 10000, AV_LOG_WARNING, s))
+                    fps = av_inv_q(tmp);
+            }
+
+            if (!value_used)
+                av_dict_set(&s->metadata, key, value, 0);
+        }
+    }
+
+    avpriv_set_pts_info(ast, 64, 1, ast->codec->sample_rate);
+    avpriv_set_pts_info(vst, 64, fps.num, fps.den);
+    if (duration)
+        s->duration = av_rescale(duration, 1000, 1);
+
+    vst->start_time        = 0;
+    vst->codec->codec_tag  = 0;
+    vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
+
+    if (vivo->version == 1) {
+        vst->codec->codec_id = CODEC_ID_H263;
+        ast->codec->codec_id = CODEC_ID_G723_1;
+        ast->codec->bits_per_coded_sample = 8;
+    }
+
+    ast->start_time        = 0;
+    ast->codec->codec_tag  = 0;
+    ast->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+    ast->codec->channels = 1;
+
+    return 0;
+}
+
+static int vivo_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    VivoContext *vivo = s->priv_data;
+    AVIOContext *pb = s->pb;
+    unsigned old_sequence = vivo->sequence, old_type = vivo->type;
+    int stream_index, ret = 0;
+
+restart:
+
+    if (url_feof(pb))
+        return AVERROR_EOF;
+
+    switch (vivo->type) {
+    case 0:
+        avio_skip(pb, vivo->length);
+        if ((ret = vivo_get_packet_header(s)) < 0)
+            return ret;
+        goto restart;
+    case 1:
+    case 2: // video
+        stream_index = 0;
+        break;
+    case 3:
+    case 4: // audio
+        stream_index = 1;
+        break;
+    default:
+        av_log(s, AV_LOG_ERROR, "unknown packet type %d\n", vivo->type);
+        return AVERROR_INVALIDDATA;
+    }
+
+    if ((ret = av_get_packet(pb, pkt, vivo->length)) < 0)
+        goto fail;
+
+    // get next packet header
+    if ((ret = vivo_get_packet_header(s)) < 0)
+        goto fail;
+
+    while (vivo->sequence == old_sequence &&
+           (((vivo->type - 1) >> 1) == ((old_type - 1) >> 1))) {
+        if (url_feof(pb)) {
+            ret = AVERROR_EOF;
+            break;
+        }
+
+        if ((ret = av_append_packet(pb, pkt, vivo->length)) < 0)
+            break;
+
+        // get next packet header
+        if ((ret = vivo_get_packet_header(s)) < 0)
+            break;
+    }
+
+    pkt->stream_index = stream_index;
+
+fail:
+    if (ret < 0)
+        av_free_packet(pkt);
+    return ret;
+}
+
+AVInputFormat ff_vivo_demuxer = {
+    .name           = "vivo",
+    .long_name      = NULL_IF_CONFIG_SMALL("Vivo"),
+    .priv_data_size = sizeof(VivoContext),
+    .read_probe     = vivo_probe,
+    .read_header    = vivo_read_header,
+    .read_packet    = vivo_read_packet,
+    .extensions     = "viv",
+};
diff --git a/libavformat/voc.h b/libavformat/voc.h
index 90178b3..08db970 100644
--- a/libavformat/voc.h
+++ b/libavformat/voc.h
@@ -23,7 +23,7 @@
 #define AVFORMAT_VOC_H
 
 #include "avformat.h"
-#include "riff.h"    /* for CodecTag */
+#include "internal.h"
 
 typedef struct voc_dec_context {
     int64_t remaining_size;
diff --git a/libavformat/vocenc.c b/libavformat/vocenc.c
index d97cdc4..29e9363 100644
--- a/libavformat/vocenc.c
+++ b/libavformat/vocenc.c
@@ -30,6 +30,7 @@
 static int voc_write_header(AVFormatContext *s)
 {
     AVIOContext *pb = s->pb;
+    AVCodecContext *enc = s->streams[0]->codec;
     const int header_size = 26;
     const int version = 0x0114;
 
@@ -37,6 +38,11 @@
         || s->streams[0]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
         return AVERROR_PATCHWELCOME;
 
+    if (!enc->codec_tag && enc->codec_id != AV_CODEC_ID_PCM_U8) {
+        av_log(s, AV_LOG_ERROR, "unsupported codec\n");
+        return AVERROR(EINVAL);
+    }
+
     avio_write(pb, ff_voc_magic, sizeof(ff_voc_magic) - 1);
     avio_wl16(pb, header_size);
     avio_wl16(pb, version);
diff --git a/libavformat/vqf.c b/libavformat/vqf.c
index 5fff84e..f1e6aaf 100644
--- a/libavformat/vqf.c
+++ b/libavformat/vqf.c
@@ -175,6 +175,10 @@
         break;
     default:
         st->codec->sample_rate = rate_flag*1000;
+        if (st->codec->sample_rate <= 0) {
+            av_log(s, AV_LOG_ERROR, "sample rate %d is invalid\n", st->codec->sample_rate);
+            return -1;
+        }
         break;
     }
 
diff --git a/libavformat/wav.c b/libavformat/wavdec.c
similarity index 75%
rename from libavformat/wav.c
rename to libavformat/wavdec.c
index f58bcb3..62bf263 100644
--- a/libavformat/wav.c
+++ b/libavformat/wavdec.c
@@ -1,5 +1,5 @@
 /*
- * WAV muxer and demuxer
+ * WAV demuxer
  * Copyright (c) 2001, 2002 Fabrice Bellard
  *
  * Sony Wave64 demuxer
@@ -36,15 +36,10 @@
 #include "avio.h"
 #include "metadata.h"
 
-typedef struct {
+typedef struct WAVDemuxContext {
     const AVClass *class;
-    int64_t data;
     int64_t data_end;
-    int64_t minpts;
-    int64_t maxpts;
-    int last_duration;
     int w64;
-    int write_bext;
     int64_t smv_data_ofs;
     int smv_block_size;
     int smv_frames_per_jpeg;
@@ -53,182 +48,7 @@
     int smv_eof;
     int audio_eof;
     int ignore_length;
-} WAVContext;
-
-#if CONFIG_WAV_MUXER
-static inline void bwf_write_bext_string(AVFormatContext *s, const char *key, int maxlen)
-{
-    AVDictionaryEntry *tag;
-    int len = 0;
-
-    if (tag = av_dict_get(s->metadata, key, NULL, 0)) {
-        len = strlen(tag->value);
-        len = FFMIN(len, maxlen);
-        avio_write(s->pb, tag->value, len);
-    }
-
-    ffio_fill(s->pb, 0, maxlen - len);
-}
-
-static void bwf_write_bext_chunk(AVFormatContext *s)
-{
-    AVDictionaryEntry *tmp_tag;
-    uint64_t time_reference = 0;
-    int64_t bext = ff_start_tag(s->pb, "bext");
-
-    bwf_write_bext_string(s, "description", 256);
-    bwf_write_bext_string(s, "originator", 32);
-    bwf_write_bext_string(s, "originator_reference", 32);
-    bwf_write_bext_string(s, "origination_date", 10);
-    bwf_write_bext_string(s, "origination_time", 8);
-
-    if (tmp_tag = av_dict_get(s->metadata, "time_reference", NULL, 0))
-        time_reference = strtoll(tmp_tag->value, NULL, 10);
-    avio_wl64(s->pb, time_reference);
-    avio_wl16(s->pb, 1);  // set version to 1
-
-    if (tmp_tag = av_dict_get(s->metadata, "umid", NULL, 0)) {
-        unsigned char umidpart_str[17] = {0};
-        int i;
-        uint64_t umidpart;
-        int len = strlen(tmp_tag->value+2);
-
-        for (i = 0; i < len/16; i++) {
-            memcpy(umidpart_str, tmp_tag->value + 2 + (i*16), 16);
-            umidpart = strtoll(umidpart_str, NULL, 16);
-            avio_wb64(s->pb, umidpart);
-        }
-        ffio_fill(s->pb, 0, 64 - i*8);
-    } else
-        ffio_fill(s->pb, 0, 64); // zero UMID
-
-    ffio_fill(s->pb, 0, 190); // Reserved
-
-    if (tmp_tag = av_dict_get(s->metadata, "coding_history", NULL, 0))
-        avio_put_str(s->pb, tmp_tag->value);
-
-    ff_end_tag(s->pb, bext);
-}
-
-static int wav_write_header(AVFormatContext *s)
-{
-    WAVContext *wav = s->priv_data;
-    AVIOContext *pb = s->pb;
-    int64_t fmt, fact;
-
-    ffio_wfourcc(pb, "RIFF");
-    avio_wl32(pb, 0); /* file length */
-    ffio_wfourcc(pb, "WAVE");
-
-    /* format header */
-    fmt = ff_start_tag(pb, "fmt ");
-    if (ff_put_wav_header(pb, s->streams[0]->codec) < 0) {
-        av_log(s, AV_LOG_ERROR, "%s codec not supported in WAVE format\n",
-               s->streams[0]->codec->codec ? s->streams[0]->codec->codec->name : "NONE");
-        return -1;
-    }
-    ff_end_tag(pb, fmt);
-
-    if (s->streams[0]->codec->codec_tag != 0x01 /* hence for all other than PCM */
-        && s->pb->seekable) {
-        fact = ff_start_tag(pb, "fact");
-        avio_wl32(pb, 0);
-        ff_end_tag(pb, fact);
-    }
-
-    if (wav->write_bext)
-        bwf_write_bext_chunk(s);
-
-    avpriv_set_pts_info(s->streams[0], 64, 1, s->streams[0]->codec->sample_rate);
-    wav->maxpts = wav->last_duration = 0;
-    wav->minpts = INT64_MAX;
-
-    /* data header */
-    wav->data = ff_start_tag(pb, "data");
-
-    avio_flush(pb);
-
-    return 0;
-}
-
-static int wav_write_packet(AVFormatContext *s, AVPacket *pkt)
-{
-    AVIOContext *pb  = s->pb;
-    WAVContext    *wav = s->priv_data;
-    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);
-        wav->last_duration = pkt->duration;
-    } else
-        av_log(s, AV_LOG_ERROR, "wav_write_packet: NOPTS\n");
-    return 0;
-}
-
-static int wav_write_trailer(AVFormatContext *s)
-{
-    AVIOContext *pb  = s->pb;
-    WAVContext    *wav = s->priv_data;
-    int64_t file_size;
-
-    avio_flush(pb);
-
-    if (s->pb->seekable) {
-        ff_end_tag(pb, wav->data);
-
-        /* update file size */
-        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);
-
-        avio_flush(pb);
-
-        if(s->streams[0]->codec->codec_tag != 0x01) {
-            /* Update num_samps in fact chunk */
-            int number_of_samples;
-            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);
-            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;
-}
-
-#define OFFSET(x) offsetof(WAVContext, x)
-#define ENC AV_OPT_FLAG_ENCODING_PARAM
-static const AVOption options[] = {
-    { "write_bext", "Write BEXT chunk.", OFFSET(write_bext), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, ENC },
-    { NULL },
-};
-
-static const AVClass wav_muxer_class = {
-    .class_name = "WAV muxer",
-    .item_name  = av_default_item_name,
-    .option     = options,
-    .version    = LIBAVUTIL_VERSION_INT,
-};
-
-AVOutputFormat ff_wav_muxer = {
-    .name              = "wav",
-    .long_name         = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
-    .mime_type         = "audio/x-wav",
-    .extensions        = "wav",
-    .priv_data_size    = sizeof(WAVContext),
-    .audio_codec       = AV_CODEC_ID_PCM_S16LE,
-    .video_codec       = AV_CODEC_ID_NONE,
-    .write_header      = wav_write_header,
-    .write_packet      = wav_write_packet,
-    .write_trailer     = wav_write_trailer,
-    .flags             = AVFMT_TS_NONSTRICT,
-    .codec_tag         = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
-    .priv_class        = &wav_muxer_class,
-};
-#endif /* CONFIG_WAV_MUXER */
+} WAVDemuxContext;
 
 
 #if CONFIG_WAV_DEMUXER
@@ -403,10 +223,10 @@
     int64_t size, av_uninit(data_size);
     int64_t sample_count=0;
     int rf64;
-    uint32_t tag, list_type;
+    uint32_t tag;
     AVIOContext *pb = s->pb;
     AVStream *st = NULL;
-    WAVContext *wav = s->priv_data;
+    WAVDemuxContext *wav = s->priv_data;
     int ret, got_fmt = 0;
     int64_t next_tag_ofs, data_ofs = -1;
 
@@ -520,15 +340,13 @@
             wav->smv_frames_per_jpeg = avio_rl24(pb);
             goto break_loop;
         case MKTAG('L', 'I', 'S', 'T'):
-            list_type = avio_rl32(pb);
             if (size < 4) {
                 av_log(s, AV_LOG_ERROR, "too short LIST tag\n");
                 return AVERROR_INVALIDDATA;
             }
-            switch (list_type) {
+            switch (avio_rl32(pb)) {
             case MKTAG('I', 'N', 'F', 'O'):
-                if ((ret = ff_read_riff_info(s, size - 4)) < 0)
-                    return ret;
+                ff_read_riff_info(s, size - 4);
             }
             break;
         }
@@ -589,7 +407,7 @@
     int ret, size;
     int64_t left;
     AVStream *st;
-    WAVContext *wav = s->priv_data;
+    WAVDemuxContext *wav = s->priv_data;
 
     if (wav->smv_data_ofs > 0) {
         int64_t audio_dts, video_dts;
@@ -667,7 +485,7 @@
 static int wav_read_seek(AVFormatContext *s,
                          int stream_index, int64_t timestamp, int flags)
 {
-    WAVContext *wav = s->priv_data;
+    WAVDemuxContext *wav = s->priv_data;
     AVStream *st;
     wav->smv_eof = 0;
     wav->audio_eof = 0;
@@ -694,7 +512,7 @@
     return ff_pcm_read_seek(s, stream_index, timestamp, flags);
 }
 
-#define OFFSET(x) offsetof(WAVContext, x)
+#define OFFSET(x) offsetof(WAVDemuxContext, x)
 #define DEC AV_OPT_FLAG_DECODING_PARAM
 static const AVOption demux_options[] = {
     { "ignore_length", "Ignore length", OFFSET(ignore_length), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, DEC },
@@ -710,7 +528,7 @@
 AVInputFormat ff_wav_demuxer = {
     .name           = "wav",
     .long_name      = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
-    .priv_data_size = sizeof(WAVContext),
+    .priv_data_size = sizeof(WAVDemuxContext),
     .read_probe     = wav_probe,
     .read_header    = wav_read_header,
     .read_packet    = wav_read_packet,
@@ -747,7 +565,7 @@
 {
     int64_t size;
     AVIOContext *pb  = s->pb;
-    WAVContext    *wav = s->priv_data;
+    WAVDemuxContext    *wav = s->priv_data;
     AVStream *st;
     uint8_t guid[16];
     int ret;
@@ -800,7 +618,7 @@
 AVInputFormat ff_w64_demuxer = {
     .name           = "w64",
     .long_name      = NULL_IF_CONFIG_SMALL("Sony Wave64"),
-    .priv_data_size = sizeof(WAVContext),
+    .priv_data_size = sizeof(WAVDemuxContext),
     .read_probe     = w64_probe,
     .read_header    = w64_read_header,
     .read_packet    = wav_read_packet,
diff --git a/libavformat/wavenc.c b/libavformat/wavenc.c
new file mode 100644
index 0000000..5a4b085
--- /dev/null
+++ b/libavformat/wavenc.c
@@ -0,0 +1,220 @@
+/*
+ * WAV muxer
+ * Copyright (c) 2001, 2002 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 <stdint.h>
+#include <string.h>
+
+#include "libavutil/dict.h"
+#include "libavutil/common.h"
+#include "libavutil/mathematics.h"
+#include "libavutil/opt.h"
+
+#include "avformat.h"
+#include "avio.h"
+#include "avio_internal.h"
+#include "internal.h"
+#include "riff.h"
+
+typedef struct WAVMuxContext {
+    const AVClass *class;
+    int64_t data;
+    int64_t fact_pos;
+    int64_t minpts;
+    int64_t maxpts;
+    int last_duration;
+    int write_bext;
+} WAVMuxContext;
+
+static inline void bwf_write_bext_string(AVFormatContext *s, const char *key, int maxlen)
+{
+    AVDictionaryEntry *tag;
+    int len = 0;
+
+    if (tag = av_dict_get(s->metadata, key, NULL, 0)) {
+        len = strlen(tag->value);
+        len = FFMIN(len, maxlen);
+        avio_write(s->pb, tag->value, len);
+    }
+
+    ffio_fill(s->pb, 0, maxlen - len);
+}
+
+static void bwf_write_bext_chunk(AVFormatContext *s)
+{
+    AVDictionaryEntry *tmp_tag;
+    uint64_t time_reference = 0;
+    int64_t bext = ff_start_tag(s->pb, "bext");
+
+    bwf_write_bext_string(s, "description", 256);
+    bwf_write_bext_string(s, "originator", 32);
+    bwf_write_bext_string(s, "originator_reference", 32);
+    bwf_write_bext_string(s, "origination_date", 10);
+    bwf_write_bext_string(s, "origination_time", 8);
+
+    if (tmp_tag = av_dict_get(s->metadata, "time_reference", NULL, 0))
+        time_reference = strtoll(tmp_tag->value, NULL, 10);
+    avio_wl64(s->pb, time_reference);
+    avio_wl16(s->pb, 1);  // set version to 1
+
+    if (tmp_tag = av_dict_get(s->metadata, "umid", NULL, 0)) {
+        unsigned char umidpart_str[17] = {0};
+        int i;
+        uint64_t umidpart;
+        int len = strlen(tmp_tag->value+2);
+
+        for (i = 0; i < len/16; i++) {
+            memcpy(umidpart_str, tmp_tag->value + 2 + (i*16), 16);
+            umidpart = strtoll(umidpart_str, NULL, 16);
+            avio_wb64(s->pb, umidpart);
+        }
+        ffio_fill(s->pb, 0, 64 - i*8);
+    } else
+        ffio_fill(s->pb, 0, 64); // zero UMID
+
+    ffio_fill(s->pb, 0, 190); // Reserved
+
+    if (tmp_tag = av_dict_get(s->metadata, "coding_history", NULL, 0))
+        avio_put_str(s->pb, tmp_tag->value);
+
+    ff_end_tag(s->pb, bext);
+}
+
+static int wav_write_header(AVFormatContext *s)
+{
+    WAVMuxContext *wav = s->priv_data;
+    AVIOContext *pb = s->pb;
+    int64_t fmt;
+
+    ffio_wfourcc(pb, "RIFF");
+    avio_wl32(pb, 0); /* file length */
+    ffio_wfourcc(pb, "WAVE");
+
+    /* format header */
+    fmt = ff_start_tag(pb, "fmt ");
+    if (ff_put_wav_header(pb, s->streams[0]->codec) < 0) {
+        av_log(s, AV_LOG_ERROR, "%s codec not supported in WAVE format\n",
+               s->streams[0]->codec->codec ? s->streams[0]->codec->codec->name : "NONE");
+        return -1;
+    }
+    ff_end_tag(pb, fmt);
+
+    if (s->streams[0]->codec->codec_tag != 0x01 /* hence for all other than PCM */
+        && s->pb->seekable) {
+        wav->fact_pos = ff_start_tag(pb, "fact");
+        avio_wl32(pb, 0);
+        ff_end_tag(pb, wav->fact_pos);
+    }
+
+    if (wav->write_bext)
+        bwf_write_bext_chunk(s);
+
+    avpriv_set_pts_info(s->streams[0], 64, 1, s->streams[0]->codec->sample_rate);
+    wav->maxpts = wav->last_duration = 0;
+    wav->minpts = INT64_MAX;
+
+    /* info header */
+    ff_riff_write_info(s);
+
+    /* data header */
+    wav->data = ff_start_tag(pb, "data");
+
+    avio_flush(pb);
+
+    return 0;
+}
+
+static int wav_write_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    AVIOContext *pb  = s->pb;
+    WAVMuxContext    *wav = s->priv_data;
+    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);
+        wav->last_duration = pkt->duration;
+    } else
+        av_log(s, AV_LOG_ERROR, "wav_write_packet: NOPTS\n");
+    return 0;
+}
+
+static int wav_write_trailer(AVFormatContext *s)
+{
+    AVIOContext *pb  = s->pb;
+    WAVMuxContext    *wav = s->priv_data;
+    int64_t file_size;
+
+    avio_flush(pb);
+
+    if (s->pb->seekable) {
+        ff_end_tag(pb, wav->data);
+
+        /* update file size */
+        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);
+
+        avio_flush(pb);
+
+        if(s->streams[0]->codec->codec_tag != 0x01) {
+            /* Update num_samps in fact chunk */
+            int number_of_samples;
+            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);
+            avio_seek(pb, wav->fact_pos, SEEK_SET);
+            avio_wl32(pb, number_of_samples);
+            avio_seek(pb, file_size, SEEK_SET);
+            avio_flush(pb);
+        }
+    }
+    return 0;
+}
+
+#define OFFSET(x) offsetof(WAVMuxContext, x)
+#define ENC AV_OPT_FLAG_ENCODING_PARAM
+static const AVOption options[] = {
+    { "write_bext", "Write BEXT chunk.", OFFSET(write_bext), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, ENC },
+    { NULL },
+};
+
+static const AVClass wav_muxer_class = {
+    .class_name = "WAV muxer",
+    .item_name  = av_default_item_name,
+    .option     = options,
+    .version    = LIBAVUTIL_VERSION_INT,
+};
+
+AVOutputFormat ff_wav_muxer = {
+    .name              = "wav",
+    .long_name         = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
+    .mime_type         = "audio/x-wav",
+    .extensions        = "wav",
+    .priv_data_size    = sizeof(WAVMuxContext),
+    .audio_codec       = AV_CODEC_ID_PCM_S16LE,
+    .video_codec       = AV_CODEC_ID_NONE,
+    .write_header      = wav_write_header,
+    .write_packet      = wav_write_packet,
+    .write_trailer     = wav_write_trailer,
+    .flags             = AVFMT_TS_NONSTRICT,
+    .codec_tag         = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
+    .priv_class        = &wav_muxer_class,
+};
diff --git a/libavformat/wc3movie.c b/libavformat/wc3movie.c
index 836f567..657380a 100644
--- a/libavformat/wc3movie.c
+++ b/libavformat/wc3movie.c
@@ -27,6 +27,7 @@
  *   http://www.pcisys.net/~melanson/codecs/
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "libavutil/dict.h"
 #include "avformat.h"
@@ -183,6 +184,7 @@
     st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
     st->codec->codec_tag = 1;
     st->codec->channels = WC3_AUDIO_CHANNELS;
+    st->codec->channel_layout = AV_CH_LAYOUT_MONO;
     st->codec->bits_per_coded_sample = WC3_AUDIO_BITS;
     st->codec->sample_rate = WC3_SAMPLE_RATE;
     st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *
diff --git a/libavformat/webvttdec.c b/libavformat/webvttdec.c
index b1cd293..7288e8f 100644
--- a/libavformat/webvttdec.c
+++ b/libavformat/webvttdec.c
@@ -49,8 +49,8 @@
 static int64_t read_ts(const char *s)
 {
     int hh, mm, ss, ms;
-    if (sscanf(s, "%u:%u:%u.%u", &hh, &mm, &ss, &ms) == 4) return (hh*3600 + mm*60 + ss) * 1000 + ms;
-    if (sscanf(s,    "%u:%u.%u",      &mm, &ss, &ms) == 3) return (          mm*60 + ss) * 1000 + ms;
+    if (sscanf(s, "%u:%u:%u.%u", &hh, &mm, &ss, &ms) == 4) return (hh*3600LL + mm*60LL + ss) * 1000LL + ms;
+    if (sscanf(s,    "%u:%u.%u",      &mm, &ss, &ms) == 3) return (            mm*60LL + ss) * 1000LL + ms;
     return AV_NOPTS_VALUE;
 }
 
@@ -168,6 +168,14 @@
     return ff_subtitles_queue_read_packet(&webvtt->q, pkt);
 }
 
+static int webvtt_read_seek(AVFormatContext *s, int stream_index,
+                            int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
+{
+    WebVTTContext *webvtt = s->priv_data;
+    return ff_subtitles_queue_seek(&webvtt->q, s, stream_index,
+                                   min_ts, ts, max_ts, flags);
+}
+
 static int webvtt_read_close(AVFormatContext *s)
 {
     WebVTTContext *webvtt = s->priv_data;
@@ -182,6 +190,7 @@
     .read_probe     = webvtt_probe,
     .read_header    = webvtt_read_header,
     .read_packet    = webvtt_read_packet,
+    .read_seek2     = webvtt_read_seek,
     .read_close     = webvtt_read_close,
     .flags          = AVFMT_GENERIC_INDEX,
     .extensions     = "vtt",
diff --git a/libavformat/westwood_aud.c b/libavformat/westwood_aud.c
index 2762cba..f4b8584 100644
--- a/libavformat/westwood_aud.c
+++ b/libavformat/westwood_aud.c
@@ -33,6 +33,7 @@
  * qualify a file. Refer to wsaud_probe() for the precise parameters.
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "internal.h"
@@ -68,8 +69,6 @@
     if (p->buf[10] & 0xFC)
         return 0;
 
-    /* note: only check for WS IMA (type 99) right now since there is no
-     * support for type 1 */
     if (p->buf[11] != 99 && p->buf[11] != 1)
         return 0;
 
@@ -120,6 +119,8 @@
     avpriv_set_pts_info(st, 64, 1, sample_rate);
     st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
     st->codec->channels    = channels;
+    st->codec->channel_layout = channels == 1 ? AV_CH_LAYOUT_MONO :
+                                                AV_CH_LAYOUT_STEREO;
     st->codec->sample_rate = sample_rate;
 
     return 0;
diff --git a/libavformat/wtv.c b/libavformat/wtv.c
index d85c3cf..5b1e61b 100644
--- a/libavformat/wtv.c
+++ b/libavformat/wtv.c
@@ -30,8 +30,14 @@
     {0x5B,0x05,0xE6,0x1B,0x97,0xA9,0x49,0x43,0x88,0x17,0x1A,0x65,0x5A,0x29,0x8A,0x97};
 const ff_asf_guid ff_data_guid =
     {0x95,0xC3,0xD2,0xC2,0x7E,0x9A,0xDA,0x11,0x8B,0xF7,0x00,0x07,0xE9,0x5E,0xAD,0x8D};
-const ff_asf_guid ff_stream_guid =
+const ff_asf_guid ff_SBE2_STREAM_DESC_EVENT =
     {0xED,0xA4,0x13,0x23,0x2D,0xBF,0x4F,0x45,0xAD,0x8A,0xD9,0x5B,0xA7,0xF9,0x1F,0xEE};
+const ff_asf_guid ff_stream1_guid =
+    {0xA1,0xC3,0xD2,0xC2,0x7E,0x9A,0xDA,0x11,0x8B,0xF7,0x00,0x07,0xE9,0x5E,0xAD,0x8D};
+const ff_asf_guid ff_sync_guid =
+    {0x97,0xC3,0xD2,0xC2,0x7E,0x9A,0xDA,0x11,0x8B,0xF7,0x00,0x07,0xE9,0x5E,0xAD,0x8D};
+const ff_asf_guid ff_index_guid =
+    {0x96,0xC3,0xD2,0xC2,0x7E,0x9A,0xDA,0x11,0x8B,0xF7,0x00,0x07,0xE9,0x5E,0xAD,0x8D};
 const ff_asf_guid ff_mediatype_audio =
     {'a','u','d','s',FF_MEDIASUBTYPE_BASE_GUID};
 const ff_asf_guid ff_mediatype_video =
diff --git a/libavformat/wtv.h b/libavformat/wtv.h
index 7e4f243..efe90d6 100644
--- a/libavformat/wtv.h
+++ b/libavformat/wtv.h
@@ -39,7 +39,10 @@
 extern const ff_asf_guid ff_wtv_guid;
 extern const ff_asf_guid ff_timestamp_guid;
 extern const ff_asf_guid ff_data_guid;
-extern const ff_asf_guid ff_stream_guid;
+extern const ff_asf_guid ff_SBE2_STREAM_DESC_EVENT;
+extern const ff_asf_guid ff_stream1_guid;
+extern const ff_asf_guid ff_sync_guid;
+extern const ff_asf_guid ff_index_guid;
 extern const ff_asf_guid ff_mediatype_audio;
 extern const ff_asf_guid ff_mediatype_video;
 extern const ff_asf_guid ff_format_none;
diff --git a/libavformat/wtvdec.c b/libavformat/wtvdec.c
index 319b986..0706145 100644
--- a/libavformat/wtvdec.c
+++ b/libavformat/wtvdec.c
@@ -25,6 +25,7 @@
  * @author Peter Ross <pross@xvid.org>
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "libavutil/intfloat.h"
 #include "avformat.h"
@@ -558,8 +559,14 @@
 
     /* 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;
+    case 1 :
+    case 2 :
+    case 4 : st->codec->channels       = 2;
+             st->codec->channel_layout = AV_CH_LAYOUT_STEREO;
+             break;
+    case 8 : st->codec->channels       = 1;
+             st->codec->channel_layout = AV_CH_LAYOUT_MONO;
+             break;
     }
 }
 
@@ -580,8 +587,10 @@
         if (!wst)
             return NULL;
         st = avformat_new_stream(s, NULL);
-        if (!st)
+        if (!st) {
+            av_free(wst);
             return NULL;
+        }
         st->id = sid;
         st->priv_data = wst;
     }
@@ -739,7 +748,7 @@
         avio_skip(pb, 8);
         consumed = 32;
 
-        if (!ff_guidcmp(g, ff_stream_guid)) {
+        if (!ff_guidcmp(g, ff_SBE2_STREAM_DESC_EVENT)) {
             if (ff_find_stream_index(s, sid) < 0) {
                 ff_asf_guid mediatype, subtype, formattype;
                 int size;
@@ -754,7 +763,7 @@
             }
         } else if (!ff_guidcmp(g, ff_stream2_guid)) {
             int stream_index = ff_find_stream_index(s, sid);
-            if (stream_index >= 0 && !((WtvStream*)s->streams[stream_index]->priv_data)->seen_data) {
+            if (stream_index >= 0 && s->streams[stream_index]->priv_data && !((WtvStream*)s->streams[stream_index]->priv_data)->seen_data) {
                 ff_asf_guid mediatype, subtype, formattype;
                 int size;
                 avio_skip(pb, 12);
@@ -856,8 +865,13 @@
                 }
                 return stream_index;
             }
+        } else if (!ff_guidcmp(g, /* DSATTRIB_WMDRMProtectionInfo */ (const ff_asf_guid){0x83,0x95,0x74,0x40,0x9D,0x6B,0xEC,0x4E,0xB4,0x3C,0x67,0xA1,0x80,0x1E,0x1A,0x9B})) {
+            int stream_index = ff_find_stream_index(s, sid);
+            if (stream_index >= 0)
+                av_log(s, AV_LOG_WARNING, "encrypted stream detected (st:%d), decoding will likely fail\n", 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_PBDATAG_ATTRIBUTE */ (const ff_asf_guid){0x79,0x66,0xB5,0xE0,0xB9,0x12,0xCC,0x43,0xB7,0xDF,0x57,0x8C,0xAA,0x5A,0x7B,0x63}) ||
             !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 */ ff_DSATTRIB_TRANSPORT_PROPERTIES) ||
             !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}) ||
@@ -872,9 +886,9 @@
             !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}) ||
+            !ff_guidcmp(g, ff_index_guid) ||
+            !ff_guidcmp(g, ff_sync_guid) ||
+            !ff_guidcmp(g, ff_stream1_guid) ||
             !ff_guidcmp(g, (const ff_asf_guid){0xF7,0x10,0x02,0xB9,0xEE,0x7C,0xED,0x4E,0xBD,0x7F,0x05,0x40,0x35,0x86,0x18,0xA1})) {
             //ignore known guids
         } else
diff --git a/libavformat/wtvenc.c b/libavformat/wtvenc.c
index 5bed51e..8300662 100644
--- a/libavformat/wtvenc.c
+++ b/libavformat/wtvenc.c
@@ -52,12 +52,6 @@
 
 static const ff_asf_guid sub_wtv_guid =
     {0x8C,0xC3,0xD2,0xC2,0x7E,0x9A,0xDA,0x11,0x8B,0xF7,0x00,0x07,0xE9,0x5E,0xAD,0x8D};
-static const ff_asf_guid stream1_guid =
-    {0xA1,0xC3,0xD2,0xC2,0x7E,0x9A,0xDA,0x11,0x8B,0xF7,0x00,0x07,0xE9,0x5E,0xAD,0x8D};
-static const ff_asf_guid sync_guid =
-    {0x97,0xC3,0xD2,0xC2,0x7E,0x9A,0xDA,0x11,0x8B,0xF7,0x00,0x07,0xE9,0x5E,0xAD,0x8D};
-static const ff_asf_guid index_guid =
-    {0x96,0xc3,0xd2,0xc2,0x7e,0x9a,0xda,0x11,0x8b,0xf7,0x00,0x07,0xe9,0x5e,0xad,0x8d};
 
 enum WtvFileIndex {
     WTV_TIMELINE_TABLE_0_HEADER_EVENTS = 0,
@@ -86,18 +80,43 @@
 } WtvChunkEntry;
 
 typedef struct {
+    int64_t serial;
+    int64_t value;
+} WtvSyncEntry;
+
+typedef struct {
     int64_t timeline_start_pos;
     WtvFile file[WTV_FILES];
     int64_t serial;         /** chunk serial number */
     int64_t last_chunk_pos; /** last chunk position */
-    int64_t frame_nb;
+    int64_t last_timestamp_pos; /** last timestamp chunk position */
+    int64_t first_index_pos;    /** first index_chunk position */
 
     WtvChunkEntry index[MAX_NB_INDEX];
     int nb_index;
     int first_video_flag;
-    int64_t sync_pos;
+
+    WtvSyncEntry *st_pairs; /* (serial, timestamp) pairs */
+    int nb_st_pairs;
+    WtvSyncEntry *sp_pairs; /* (serial, position) pairs */
+    int nb_sp_pairs;
+
+    int64_t last_pts;
+    int64_t last_serial;
 } WtvContext;
 
+
+static void add_serial_pair(WtvSyncEntry ** list, int * count, int64_t serial, int64_t value)
+{
+    int new_count = *count + 1;
+    WtvSyncEntry *new_list = av_realloc(*list, new_count * sizeof(WtvSyncEntry));
+    if (!new_list)
+        return;
+    new_list[*count] = (WtvSyncEntry){serial, value};
+    *list  = new_list;
+    *count = new_count;
+}
+
 typedef int WTVHeaderWriteFunc(AVIOContext *pb);
 
 typedef struct {
@@ -137,7 +156,7 @@
     avio_wl32(pb, stream_id);
     avio_wl64(pb, wctx->serial);
 
-    if ((stream_id & 0x80000000) && guid != &index_guid) {
+    if ((stream_id & 0x80000000) && guid != &ff_index_guid) {
         WtvChunkEntry *t = wctx->index + wctx->nb_index;
         av_assert0(wctx->nb_index < MAX_NB_INDEX);
         t->pos       = wctx->last_chunk_pos;
@@ -179,7 +198,7 @@
     WtvContext *wctx = s->priv_data;
     int i;
 
-    write_chunk_header2(s, &index_guid, 0x80000000);
+    write_chunk_header2(s, &ff_index_guid, 0x80000000);
     avio_wl32(pb, 0);
     avio_wl32(pb, 0);
 
@@ -193,6 +212,9 @@
     }
     wctx->nb_index = 0;   // reset index
     finish_chunk_noindex(s);
+
+    if (!wctx->first_index_pos)
+        wctx->first_index_pos = wctx->last_chunk_pos;
 }
 
 static void finish_chunk(AVFormatContext *s)
@@ -263,7 +285,7 @@
 {
     AVIOContext *pb = s->pb;
     int ret;
-    write_chunk_header2(s, &stream1_guid, 0x80000000 | 0x01);
+    write_chunk_header2(s, &ff_stream1_guid, 0x80000000 | 0x01);
 
     avio_wl32(pb,  0x01);
     write_pad(pb, 4);
@@ -284,41 +306,28 @@
     AVIOContext *pb = s->pb;
     WtvContext *wctx = s->priv_data;
     int64_t last_chunk_pos = wctx->last_chunk_pos;
-    wctx->sync_pos = avio_tell(pb) - wctx->timeline_start_pos;
 
-    write_chunk_header(s, &sync_guid, 0x18, 0);
-    write_pad(pb, 24);
+    write_chunk_header(s, &ff_sync_guid, 0x18, 0);
+    avio_wl64(pb, wctx->first_index_pos);
+    avio_wl64(pb, wctx->last_timestamp_pos);
+    avio_wl64(pb, 0);
 
     finish_chunk(s);
+    add_serial_pair(&wctx->sp_pairs, &wctx->nb_sp_pairs, wctx->serial, wctx->last_chunk_pos);
 
     wctx->last_chunk_pos = last_chunk_pos;
 }
 
-static void write_DSATTRIB_TRANSPORT_PROPERTIES_init(AVFormatContext *s, int stream_index)
-{
-    AVIOContext *pb = s->pb;
-    write_chunk_header2(s, &ff_DSATTRIB_TRANSPORT_PROPERTIES, 0x80000000 | stream_index);
-    avio_wl64(pb, stream_index);
-    avio_wl64(pb, -1);
-    avio_wl64(pb, 0);
-    finish_chunk(s);
-}
-
-static int write_stream_data(AVFormatContext *s, AVStream *st, int flag)
+static int write_stream_data(AVFormatContext *s, AVStream *st)
 {
     AVIOContext *pb = s->pb;
     int ret;
 
-    if (!flag) {
-        write_chunk_header2(s, &ff_stream_guid, 0x80000000 | (st->index + INDEX_BASE));
-        avio_wl32(pb, 0x00000001);
-        avio_wl32(pb, st->index + INDEX_BASE); //stream_id
-        avio_wl32(pb, 0x00000001);
-        write_pad(pb, 8);
-    } else {
-        write_chunk_header2(s, &ff_stream2_guid, 0x80000000 | (st->index + INDEX_BASE));
-        write_pad(pb, 4);
-    }
+    write_chunk_header2(s, &ff_SBE2_STREAM_DESC_EVENT, 0x80000000 | (st->index + INDEX_BASE));
+    avio_wl32(pb, 0x00000001);
+    avio_wl32(pb, st->index + INDEX_BASE); //stream_id
+    avio_wl32(pb, 0x00000001);
+    write_pad(pb, 8);
 
     ret = write_stream_codec_info(s, st);
     if (ret < 0) {
@@ -339,6 +348,9 @@
     int i, pad, ret;
     AVStream *st;
 
+    wctx->last_chunk_pos     = -1;
+    wctx->last_timestamp_pos = -1;
+
     ff_put_guid(pb, &ff_wtv_guid);
     ff_put_guid(pb, &sub_wtv_guid);
 
@@ -357,6 +369,7 @@
 
     pad = (1 << WTV_SECTOR_BITS) - avio_tell(pb);
     write_pad(pb, pad);
+
     wctx->timeline_start_pos = avio_tell(pb);
 
     wctx->serial = 1;
@@ -370,28 +383,19 @@
             av_log(s, AV_LOG_ERROR, "write stream codec failed codec_type(0x%x)\n", st->codec->codec_type);
             return -1;
         }
-        if (i + 1 < s->nb_streams) {
+        if (!i)
             write_sync(s);
-        }
     }
 
     for (i = 0; i < s->nb_streams; i++) {
         st = s->streams[i];
-        ret  = write_stream_data(s, st, 0);
+        ret  = write_stream_data(s, st);
         if (ret < 0) {
             av_log(s, AV_LOG_ERROR, "write stream data failed codec_type(0x%x)\n", st->codec->codec_type);
             return -1;
         }
-        ret = write_stream_data(s, st, 1);
-        if (ret < 0) {
-            av_log(s, AV_LOG_ERROR, "write stream2 data failed codec_type(0x%x)\n", st->codec->codec_type);
-            return -1;
-        }
     }
 
-    for (i = 0; i < s->nb_streams; i++)
-        write_DSATTRIB_TRANSPORT_PROPERTIES_init(s, INDEX_BASE + i);
-
     if (wctx->nb_index)
         write_index(s);
 
@@ -403,23 +407,17 @@
     AVIOContext *pb = s->pb;
     WtvContext  *wctx = s->priv_data;
     AVCodecContext *enc = s->streams[pkt->stream_index]->codec;
-    int flag = 0;
-    int64_t frame_number = 0;
 
-    if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
-        wctx->frame_nb++;
-        frame_number = wctx->frame_nb;
-        flag = pkt->flags & AV_PKT_FLAG_KEY ? 1 : 0;
-    }
     write_chunk_header(s, &ff_timestamp_guid, 56, 0x40000000 | (INDEX_BASE + pkt->stream_index));
     write_pad(pb, 8);
     avio_wl64(pb, pkt->pts == AV_NOPTS_VALUE ? -1 : pkt->pts);
     avio_wl64(pb, pkt->pts == AV_NOPTS_VALUE ? -1 : pkt->pts);
+    avio_wl64(pb, pkt->pts == AV_NOPTS_VALUE ? -1 : pkt->pts);
+    avio_wl64(pb, 0);
+    avio_wl64(pb, enc->codec_type == AVMEDIA_TYPE_VIDEO && (pkt->flags & AV_PKT_FLAG_KEY) ? 1 : 0);
+    avio_wl64(pb, 0);
 
-    avio_wl64(pb, frame_number);
-    avio_wl64(pb, 0);
-    avio_wl64(pb, flag);
-    avio_wl64(pb, 0);
+    wctx->last_timestamp_pos = wctx->last_chunk_pos;
 }
 
 static int write_packet(AVFormatContext *s, AVPacket *pkt)
@@ -427,6 +425,19 @@
     AVIOContext *pb = s->pb;
     WtvContext  *wctx = s->priv_data;
 
+    /* emit sync chunk and 'timeline.table.0.entries.Event' record every 50 frames */
+    if (wctx->serial - (wctx->nb_sp_pairs ? wctx->sp_pairs[wctx->nb_sp_pairs - 1].serial : 0) >= 50)
+        write_sync(s);
+
+    /* emit 'table.0.entries.time' record every 500ms */
+    if (pkt->pts != AV_NOPTS_VALUE && pkt->pts - (wctx->nb_st_pairs ? wctx->st_pairs[wctx->nb_st_pairs - 1].value : 0) >= 5000000)
+        add_serial_pair(&wctx->st_pairs, &wctx->nb_st_pairs, wctx->serial, pkt->pts);
+
+    if (pkt->pts != AV_NOPTS_VALUE && pkt->pts > wctx->last_pts) {
+        wctx->last_pts = pkt->pts;
+        wctx->last_serial = wctx->serial;
+    }
+
     // write timestamp chunk
     write_timestamp(s, pkt);
 
@@ -439,7 +450,7 @@
     return 0;
 }
 
-static int write_table0_header_envents(AVIOContext *pb)
+static int write_table0_header_events(AVIOContext *pb)
 {
     avio_wl32(pb, 0x10);
     write_pad(pb, 84);
@@ -468,7 +479,7 @@
 }
 
 static const WTVRootEntryTable wtv_root_entry_table[] = {
-    { timeline_table_0_header_events,          sizeof(timeline_table_0_header_events),          write_table0_header_envents},
+    { timeline_table_0_header_events,          sizeof(timeline_table_0_header_events),          write_table0_header_events},
     { ff_timeline_table_0_entries_Events_le16, sizeof(ff_timeline_table_0_entries_Events_le16), NULL},
     { ff_timeline_le16,                        sizeof(ff_timeline_le16),                        NULL},
     { table_0_header_legacy_attrib,            sizeof(table_0_header_legacy_attrib),            write_table0_header_legacy_attrib},
@@ -559,10 +570,24 @@
 {
     AVIOContext *pb = s->pb;
     WtvContext *wctx = s->priv_data;
+    int i;
+    for (i = 0; i < wctx->nb_sp_pairs; i++) {
+        avio_wl64(pb, wctx->sp_pairs[i].serial);
+        avio_wl64(pb, wctx->sp_pairs[i].value);
+    }
+}
 
-    //FIXME: output frame_nb, position pairs.
-    //We only set the first sync_chunk position here.
-    avio_wl64(pb, 0x2);   avio_wl64(pb, wctx->sync_pos);
+static void write_table_entries_time(AVFormatContext *s)
+{
+    AVIOContext *pb = s->pb;
+    WtvContext *wctx = s->priv_data;
+    int i;
+    for (i = 0; i < wctx->nb_st_pairs; i++) {
+        avio_wl64(pb, wctx->st_pairs[i].value);
+        avio_wl64(pb, wctx->st_pairs[i].serial);
+    }
+    avio_wl64(pb, wctx->last_pts);
+    avio_wl64(pb, wctx->last_serial);
 }
 
 static void write_tag(AVIOContext *pb, const char *key, const char *value)
@@ -687,7 +712,7 @@
         return -1;
 
     start_pos = avio_tell(pb);
-    //FIXME: output timestamp, frame_nb pairs here.
+    write_table_entries_time(s);
     if (finish_file(s, WTV_TABLE_0_ENTRIES_TIME, start_pos) < 0)
         return -1;
 
@@ -705,6 +730,9 @@
     avio_wl32(pb, file_end_pos >> WTV_SECTOR_BITS);
 
     avio_flush(pb);
+
+    av_free(wctx->sp_pairs);
+    av_free(wctx->st_pairs);
     return 0;
 }
 
diff --git a/libavformat/wv.c b/libavformat/wv.c
index 50e5e53..97a6c1f 100644
--- a/libavformat/wv.c
+++ b/libavformat/wv.c
@@ -19,7 +19,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "libavutil/dict.h"
 #include "avformat.h"
@@ -255,7 +255,8 @@
     st->codec->bits_per_coded_sample = wc->bpp;
     avpriv_set_pts_info(st, 64, 1, wc->rate);
     st->start_time = 0;
-    st->duration   = wc->samples;
+    if (wc->samples != 0xFFFFFFFFu)
+        st->duration = wc->samples;
 
     if (s->pb->seekable) {
         int64_t cur = avio_tell(s->pb);
@@ -340,7 +341,7 @@
     pkt->stream_index = 0;
     wc->block_parsed  = 1;
     pkt->pts          = wc->soff;
-    block_samples     = AV_RN32(wc->extra);
+    block_samples     = AV_RL32(wc->extra);
     if (block_samples > INT32_MAX)
         av_log(s, AV_LOG_WARNING,
                "Too many samples in block: %"PRIu32"\n", block_samples);
diff --git a/libavformat/wvenc.c b/libavformat/wvenc.c
index d225ed4..3cc0a50 100644
--- a/libavformat/wvenc.c
+++ b/libavformat/wvenc.c
@@ -19,19 +19,21 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "internal.h"
 #include "avio_internal.h"
 #include "apetag.h"
 
+#define WV_EXTRA_SIZE 12
+#define WV_END_BLOCK  0x1000
+
 typedef struct{
     uint32_t duration;
-    int off;
 } WVMuxContext;
 
 static int write_header(AVFormatContext *s)
 {
-    WVMuxContext *wc = s->priv_data;
     AVCodecContext *codec = s->streams[0]->codec;
 
     if (s->nb_streams > 1) {
@@ -46,7 +48,6 @@
         av_log_missing_feature(s, "remuxing from matroska container", 0);
         return AVERROR_PATCHWELCOME;
     }
-    wc->off = codec->channels > 2 ? 4 : 0;
     avpriv_set_pts_info(s->streams[0], 64, 1, codec->sample_rate);
 
     return 0;
@@ -55,18 +56,61 @@
 static int write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     WVMuxContext *wc = s->priv_data;
+    AVCodecContext *codec = s->streams[0]->codec;
     AVIOContext *pb = s->pb;
+    uint64_t size;
+    uint32_t flags;
+    uint32_t left = pkt->size;
+    uint8_t *ptr = pkt->data;
+    int off = codec->channels > 2 ? 4 : 0;
 
+    /* FIXME: Simplify decoder/demuxer so bellow code can support midstream
+     *        change of stream parameters */
     wc->duration += pkt->duration;
     ffio_wfourcc(pb, "wvpk");
-    avio_wl32(pb, pkt->size + 12 + wc->off);
+    if (off) {
+        size = AV_RL32(pkt->data);
+        if (size <= 12)
+            return AVERROR_INVALIDDATA;
+        size -= 12;
+    } else {
+        size = pkt->size;
+    }
+
+    if (size + off > left)
+        return AVERROR_INVALIDDATA;
+
+    avio_wl32(pb, size + 12);
     avio_wl16(pb, 0x410);
     avio_w8(pb, 0);
     avio_w8(pb, 0);
     avio_wl32(pb, -1);
     avio_wl32(pb, pkt->pts);
-    avio_write(s->pb, pkt->data, pkt->size);
-    avio_flush(s->pb);
+    ptr += off; left -= off;
+    flags = AV_RL32(ptr + 4);
+    avio_write(pb, ptr, size);
+    ptr += size; left -= size;
+
+    while (!(flags & WV_END_BLOCK) &&
+            (left >= 4 + WV_EXTRA_SIZE)) {
+        ffio_wfourcc(pb, "wvpk");
+        size = AV_RL32(ptr);
+        ptr += 4; left -= 4;
+        if (size < 24 || size - 24 > left)
+            return AVERROR_INVALIDDATA;
+        avio_wl32(pb, size);
+        avio_wl16(pb, 0x410);
+        avio_w8(pb, 0);
+        avio_w8(pb, 0);
+        avio_wl32(pb, -1);
+        avio_wl32(pb, pkt->pts);
+        flags = AV_RL32(ptr + 4);
+        avio_write(pb, ptr, WV_EXTRA_SIZE);
+        ptr += WV_EXTRA_SIZE; left -= WV_EXTRA_SIZE;
+        avio_write(pb, ptr, size - 24);
+        ptr += size - 24; left -= size - 24;
+    }
+    avio_flush(pb);
 
     return 0;
 }
diff --git a/libavformat/xmv.c b/libavformat/xmv.c
index f250aad..b447d6c 100644
--- a/libavformat/xmv.c
+++ b/libavformat/xmv.c
@@ -77,7 +77,7 @@
     uint16_t bits_per_sample; ///< Bits per compressed sample.
     uint32_t bit_rate;        ///< Bits of compressed data per second.
     uint16_t flags;           ///< Flags
-    uint16_t block_align;     ///< Bytes per compressed block.
+    unsigned block_align;     ///< Bytes per compressed block.
     uint16_t block_samples;   ///< Decompressed samples per compressed block.
 
     enum AVCodecID codec_id; ///< The codec ID of the compression scheme.
@@ -379,6 +379,9 @@
     AVIOContext     *pb  = s->pb;
     int result;
 
+    if (xmv->this_packet_offset == xmv->next_packet_offset)
+        return AVERROR_EOF;
+
     /* Seek to it */
     xmv->this_packet_offset = xmv->next_packet_offset;
     if (avio_seek(pb, xmv->this_packet_offset, SEEK_SET) != xmv->this_packet_offset)
diff --git a/libavformat/xwma.c b/libavformat/xwma.c
index 04c3629..db7d971 100644
--- a/libavformat/xwma.c
+++ b/libavformat/xwma.c
@@ -200,6 +200,12 @@
 
         /* Estimate the duration from the total number of output bytes. */
         const uint64_t total_decoded_bytes = dpds_table[dpds_table_size - 1];
+
+        if(!bytes_per_sample) {
+            av_log(s, AV_LOG_ERROR, "bytes_per_sample is 0\n");
+            return AVERROR_INVALIDDATA;
+        }
+
         st->duration = total_decoded_bytes / bytes_per_sample;
 
         /* Use the dpds data to build a seek table.  We can only do this after
diff --git a/libavformat/yop.c b/libavformat/yop.c
index 1185a3e..8f140ce 100644
--- a/libavformat/yop.c
+++ b/libavformat/yop.c
@@ -22,6 +22,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
 #include "internal.h"
@@ -64,6 +65,8 @@
 
     audio_stream = avformat_new_stream(s, NULL);
     video_stream = avformat_new_stream(s, NULL);
+    if (!audio_stream || !video_stream)
+        return AVERROR(ENOMEM);
 
     // Extra data that will be passed to the decoder
     video_stream->codec->extradata_size = 8;
@@ -79,6 +82,7 @@
     audio_dec->codec_type   = AVMEDIA_TYPE_AUDIO;
     audio_dec->codec_id     = AV_CODEC_ID_ADPCM_IMA_APC;
     audio_dec->channels     = 1;
+    audio_dec->channel_layout = AV_CH_LAYOUT_MONO;
     audio_dec->sample_rate  = 22050;
 
     // Video
diff --git a/libavformat/yuv4mpeg.c b/libavformat/yuv4mpeg.c
index a53d30f..bb038c9 100644
--- a/libavformat/yuv4mpeg.c
+++ b/libavformat/yuv4mpeg.c
@@ -58,53 +58,71 @@
         inter = st->codec->coded_frame->top_field_first ? 't' : 'b';
 
     switch (st->codec->pix_fmt) {
-    case PIX_FMT_GRAY8:
+    case AV_PIX_FMT_GRAY8:
         colorspace = " Cmono";
         break;
-    case PIX_FMT_GRAY16:
+    case AV_PIX_FMT_GRAY16:
         colorspace = " Cmono16";
         break;
-    case PIX_FMT_YUV411P:
+    case AV_PIX_FMT_YUV411P:
         colorspace = " C411 XYSCSS=411";
         break;
-    case PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUV420P:
         switch (st->codec->chroma_sample_location) {
         case AVCHROMA_LOC_TOPLEFT: colorspace = " C420paldv XYSCSS=420PALDV"; break;
         case AVCHROMA_LOC_LEFT:    colorspace = " C420mpeg2 XYSCSS=420MPEG2"; break;
         default:                   colorspace = " C420jpeg XYSCSS=420JPEG";   break;
         }
         break;
-    case PIX_FMT_YUV422P:
+    case AV_PIX_FMT_YUV422P:
         colorspace = " C422 XYSCSS=422";
         break;
-    case PIX_FMT_YUV444P:
+    case AV_PIX_FMT_YUV444P:
         colorspace = " C444 XYSCSS=444";
         break;
-    case PIX_FMT_YUV420P9:
+    case AV_PIX_FMT_YUV420P9:
         colorspace = " C420p9 XYSCSS=420P9";
         break;
-    case PIX_FMT_YUV422P9:
+    case AV_PIX_FMT_YUV422P9:
         colorspace = " C422p9 XYSCSS=422P9";
         break;
-    case PIX_FMT_YUV444P9:
+    case AV_PIX_FMT_YUV444P9:
         colorspace = " C444p9 XYSCSS=444P9";
         break;
-    case PIX_FMT_YUV420P10:
+    case AV_PIX_FMT_YUV420P10:
         colorspace = " C420p10 XYSCSS=420P10";
         break;
-    case PIX_FMT_YUV422P10:
+    case AV_PIX_FMT_YUV422P10:
         colorspace = " C422p10 XYSCSS=422P10";
         break;
-    case PIX_FMT_YUV444P10:
+    case AV_PIX_FMT_YUV444P10:
         colorspace = " C444p10 XYSCSS=444P10";
         break;
-    case PIX_FMT_YUV420P16:
+    case AV_PIX_FMT_YUV420P12:
+        colorspace = " C420p12 XYSCSS=420P12";
+        break;
+    case AV_PIX_FMT_YUV422P12:
+        colorspace = " C422p12 XYSCSS=422P12";
+        break;
+    case AV_PIX_FMT_YUV444P12:
+        colorspace = " C444p12 XYSCSS=444P12";
+        break;
+    case AV_PIX_FMT_YUV420P14:
+        colorspace = " C420p14 XYSCSS=420P14";
+        break;
+    case AV_PIX_FMT_YUV422P14:
+        colorspace = " C422p14 XYSCSS=422P14";
+        break;
+    case AV_PIX_FMT_YUV444P14:
+        colorspace = " C444p14 XYSCSS=444P14";
+        break;
+    case AV_PIX_FMT_YUV420P16:
         colorspace = " C420p16 XYSCSS=420P16";
         break;
-    case PIX_FMT_YUV422P16:
+    case AV_PIX_FMT_YUV422P16:
         colorspace = " C422p16 XYSCSS=422P16";
         break;
-    case PIX_FMT_YUV444P16:
+    case AV_PIX_FMT_YUV444P16:
         colorspace = " C444p16 XYSCSS=444P16";
         break;
     }
@@ -155,22 +173,28 @@
     ptr = picture->data[0];
 
     switch (st->codec->pix_fmt) {
-    case PIX_FMT_GRAY8:
-    case PIX_FMT_YUV411P:
-    case PIX_FMT_YUV420P:
-    case PIX_FMT_YUV422P:
-    case PIX_FMT_YUV444P:
+    case AV_PIX_FMT_GRAY8:
+    case AV_PIX_FMT_YUV411P:
+    case AV_PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUV422P:
+    case AV_PIX_FMT_YUV444P:
         break;
-    case PIX_FMT_GRAY16:
-    case PIX_FMT_YUV420P9:
-    case PIX_FMT_YUV422P9:
-    case PIX_FMT_YUV444P9:
-    case PIX_FMT_YUV420P10:
-    case PIX_FMT_YUV422P10:
-    case PIX_FMT_YUV444P10:
-    case PIX_FMT_YUV420P16:
-    case PIX_FMT_YUV422P16:
-    case PIX_FMT_YUV444P16:
+    case AV_PIX_FMT_GRAY16:
+    case AV_PIX_FMT_YUV420P9:
+    case AV_PIX_FMT_YUV422P9:
+    case AV_PIX_FMT_YUV444P9:
+    case AV_PIX_FMT_YUV420P10:
+    case AV_PIX_FMT_YUV422P10:
+    case AV_PIX_FMT_YUV444P10:
+    case AV_PIX_FMT_YUV420P12:
+    case AV_PIX_FMT_YUV422P12:
+    case AV_PIX_FMT_YUV444P12:
+    case AV_PIX_FMT_YUV420P14:
+    case AV_PIX_FMT_YUV422P14:
+    case AV_PIX_FMT_YUV444P14:
+    case AV_PIX_FMT_YUV420P16:
+    case AV_PIX_FMT_YUV422P16:
+    case AV_PIX_FMT_YUV444P16:
         width *= 2;
         break;
     default:
@@ -184,8 +208,8 @@
         ptr += picture->linesize[0];
     }
 
-    if (st->codec->pix_fmt != PIX_FMT_GRAY8 &&
-        st->codec->pix_fmt != PIX_FMT_GRAY16) {
+    if (st->codec->pix_fmt != AV_PIX_FMT_GRAY8 &&
+        st->codec->pix_fmt != AV_PIX_FMT_GRAY16) {
         // Adjust for smaller Cb and Cr planes
         avcodec_get_chroma_sub_sample(st->codec->pix_fmt, &h_chroma_shift,
                                       &v_chroma_shift);
@@ -216,31 +240,36 @@
         return AVERROR(EIO);
 
     if (s->streams[0]->codec->codec_id != AV_CODEC_ID_RAWVIDEO) {
-        av_log(s, AV_LOG_ERROR,
-               "A non-rawvideo stream was selected, but yuv4mpeg only handles rawvideo streams\n");
-        return AVERROR(EINVAL);
+        av_log(s, AV_LOG_ERROR, "ERROR: Only rawvideo supported.\n");
+        return AVERROR_INVALIDDATA;
     }
 
     switch (s->streams[0]->codec->pix_fmt) {
-    case PIX_FMT_YUV411P:
+    case AV_PIX_FMT_YUV411P:
         av_log(s, AV_LOG_WARNING, "Warning: generating rarely used 4:1:1 YUV "
                "stream, some mjpegtools might not work.\n");
         break;
-    case PIX_FMT_GRAY8:
-    case PIX_FMT_GRAY16:
-    case PIX_FMT_YUV420P:
-    case PIX_FMT_YUV422P:
-    case PIX_FMT_YUV444P:
+    case AV_PIX_FMT_GRAY8:
+    case AV_PIX_FMT_GRAY16:
+    case AV_PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUV422P:
+    case AV_PIX_FMT_YUV444P:
         break;
-    case PIX_FMT_YUV420P9:
-    case PIX_FMT_YUV422P9:
-    case PIX_FMT_YUV444P9:
-    case PIX_FMT_YUV420P10:
-    case PIX_FMT_YUV422P10:
-    case PIX_FMT_YUV444P10:
-    case PIX_FMT_YUV420P16:
-    case PIX_FMT_YUV422P16:
-    case PIX_FMT_YUV444P16:
+    case AV_PIX_FMT_YUV420P9:
+    case AV_PIX_FMT_YUV422P9:
+    case AV_PIX_FMT_YUV444P9:
+    case AV_PIX_FMT_YUV420P10:
+    case AV_PIX_FMT_YUV422P10:
+    case AV_PIX_FMT_YUV444P10:
+    case AV_PIX_FMT_YUV420P12:
+    case AV_PIX_FMT_YUV422P12:
+    case AV_PIX_FMT_YUV444P12:
+    case AV_PIX_FMT_YUV420P14:
+    case AV_PIX_FMT_YUV422P14:
+    case AV_PIX_FMT_YUV444P14:
+    case AV_PIX_FMT_YUV420P16:
+    case AV_PIX_FMT_YUV422P16:
+    case AV_PIX_FMT_YUV444P16:
         if (s->streams[0]->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
             av_log(s, AV_LOG_ERROR, "'%s' is not a official yuv4mpegpipe pixel format. "
                    "Use '-strict -1' to encode to this pixel format.\n",
@@ -255,6 +284,8 @@
                "yuv444p, yuv422p, yuv420p, yuv411p and gray8 pixel formats. "
                "And using 'strict -1' also yuv444p9, yuv422p9, yuv420p9, "
                "yuv444p10, yuv422p10, yuv420p10, "
+               "yuv444p12, yuv422p12, yuv420p12, "
+               "yuv444p14, yuv422p14, yuv420p14, "
                "yuv444p16, yuv422p16, yuv420p16 "
                "and gray16 pixel formats. "
                "Use -pix_fmt to select one.\n");
@@ -291,7 +322,7 @@
     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 AVPixelFormat pix_fmt = AV_PIX_FMT_NONE, alt_pix_fmt = AV_PIX_FMT_NONE;
     enum AVChromaLocation chroma_sample_location = AVCHROMA_LOC_UNSPECIFIED;
     AVStream *st;
     struct frame_attributes *s1 = s->priv_data;
@@ -328,49 +359,61 @@
             break;
         case 'C': // Color space
             if (strncmp("420jpeg", tokstart, 7) == 0) {
-                pix_fmt = PIX_FMT_YUV420P;
+                pix_fmt = AV_PIX_FMT_YUV420P;
                 chroma_sample_location = AVCHROMA_LOC_CENTER;
             } else if (strncmp("420mpeg2", tokstart, 8) == 0) {
-                pix_fmt = PIX_FMT_YUV420P;
+                pix_fmt = AV_PIX_FMT_YUV420P;
                 chroma_sample_location = AVCHROMA_LOC_LEFT;
             } else if (strncmp("420paldv", tokstart, 8) == 0) {
-                pix_fmt = PIX_FMT_YUV420P;
+                pix_fmt = AV_PIX_FMT_YUV420P;
                 chroma_sample_location = AVCHROMA_LOC_TOPLEFT;
             } else if (strncmp("420p16", tokstart, 6) == 0) {
-                pix_fmt = PIX_FMT_YUV420P16;
+                pix_fmt = AV_PIX_FMT_YUV420P16;
             } else if (strncmp("422p16", tokstart, 6) == 0) {
-                pix_fmt = PIX_FMT_YUV422P16;
+                pix_fmt = AV_PIX_FMT_YUV422P16;
             } else if (strncmp("444p16", tokstart, 6) == 0) {
-                pix_fmt = PIX_FMT_YUV444P16;
+                pix_fmt = AV_PIX_FMT_YUV444P16;
+            } else if (strncmp("420p14", tokstart, 6) == 0) {
+                pix_fmt = AV_PIX_FMT_YUV420P14;
+            } else if (strncmp("422p14", tokstart, 6) == 0) {
+                pix_fmt = AV_PIX_FMT_YUV422P14;
+            } else if (strncmp("444p14", tokstart, 6) == 0) {
+                pix_fmt = AV_PIX_FMT_YUV444P14;
+            } else if (strncmp("420p12", tokstart, 6) == 0) {
+                pix_fmt = AV_PIX_FMT_YUV420P12;
+            } else if (strncmp("422p12", tokstart, 6) == 0) {
+                pix_fmt = AV_PIX_FMT_YUV422P12;
+            } else if (strncmp("444p12", tokstart, 6) == 0) {
+                pix_fmt = AV_PIX_FMT_YUV444P12;
             } else if (strncmp("420p10", tokstart, 6) == 0) {
-                pix_fmt = PIX_FMT_YUV420P10;
+                pix_fmt = AV_PIX_FMT_YUV420P10;
             } else if (strncmp("422p10", tokstart, 6) == 0) {
-                pix_fmt = PIX_FMT_YUV422P10;
+                pix_fmt = AV_PIX_FMT_YUV422P10;
             } else if (strncmp("444p10", tokstart, 6) == 0) {
-                pix_fmt = PIX_FMT_YUV444P10;
+                pix_fmt = AV_PIX_FMT_YUV444P10;
             } else if (strncmp("420p9", tokstart, 5) == 0) {
-                pix_fmt = PIX_FMT_YUV420P9;
+                pix_fmt = AV_PIX_FMT_YUV420P9;
             } else if (strncmp("422p9", tokstart, 5) == 0) {
-                pix_fmt = PIX_FMT_YUV422P9;
+                pix_fmt = AV_PIX_FMT_YUV422P9;
             } else if (strncmp("444p9", tokstart, 5) == 0) {
-                pix_fmt = PIX_FMT_YUV444P9;
+                pix_fmt = AV_PIX_FMT_YUV444P9;
             } else if (strncmp("420", tokstart, 3) == 0) {
-                pix_fmt = PIX_FMT_YUV420P;
+                pix_fmt = AV_PIX_FMT_YUV420P;
                 chroma_sample_location = AVCHROMA_LOC_CENTER;
             } else if (strncmp("411", tokstart, 3) == 0) {
-                pix_fmt = PIX_FMT_YUV411P;
+                pix_fmt = AV_PIX_FMT_YUV411P;
             } else if (strncmp("422", tokstart, 3) == 0) {
-                pix_fmt = PIX_FMT_YUV422P;
+                pix_fmt = AV_PIX_FMT_YUV422P;
             } else if (strncmp("444alpha", tokstart, 8) == 0 ) {
                 av_log(s, AV_LOG_ERROR, "Cannot handle 4:4:4:4 "
                        "YUV4MPEG stream.\n");
                 return -1;
             } else if (strncmp("444", tokstart, 3) == 0) {
-                pix_fmt = PIX_FMT_YUV444P;
+                pix_fmt = AV_PIX_FMT_YUV444P;
             } else if (strncmp("mono16", tokstart, 6) == 0) {
-                pix_fmt = PIX_FMT_GRAY16;
+                pix_fmt = AV_PIX_FMT_GRAY16;
             } else if (strncmp("mono", tokstart, 4) == 0) {
-                pix_fmt = PIX_FMT_GRAY8;
+                pix_fmt = AV_PIX_FMT_GRAY8;
             } else {
                 av_log(s, AV_LOG_ERROR, "YUV4MPEG stream contains an unknown "
                        "pixel format.\n");
@@ -418,35 +461,47 @@
                 // Older nonstandard pixel format representation
                 tokstart += 6;
                 if (strncmp("420JPEG", tokstart, 7) == 0)
-                    alt_pix_fmt = PIX_FMT_YUV420P;
+                    alt_pix_fmt = AV_PIX_FMT_YUV420P;
                 else if (strncmp("420MPEG2", tokstart, 8) == 0)
-                    alt_pix_fmt = PIX_FMT_YUV420P;
+                    alt_pix_fmt = AV_PIX_FMT_YUV420P;
                 else if (strncmp("420PALDV", tokstart, 8) == 0)
-                    alt_pix_fmt = PIX_FMT_YUV420P;
+                    alt_pix_fmt = AV_PIX_FMT_YUV420P;
                 else if (strncmp("420P9", tokstart, 5) == 0)
-                    alt_pix_fmt = PIX_FMT_YUV420P9;
+                    alt_pix_fmt = AV_PIX_FMT_YUV420P9;
                 else if (strncmp("422P9", tokstart, 5) == 0)
-                    alt_pix_fmt = PIX_FMT_YUV422P9;
+                    alt_pix_fmt = AV_PIX_FMT_YUV422P9;
                 else if (strncmp("444P9", tokstart, 5) == 0)
-                    alt_pix_fmt = PIX_FMT_YUV444P9;
+                    alt_pix_fmt = AV_PIX_FMT_YUV444P9;
                 else if (strncmp("420P10", tokstart, 6) == 0)
-                    alt_pix_fmt = PIX_FMT_YUV420P10;
+                    alt_pix_fmt = AV_PIX_FMT_YUV420P10;
                 else if (strncmp("422P10", tokstart, 6) == 0)
-                    alt_pix_fmt = PIX_FMT_YUV422P10;
+                    alt_pix_fmt = AV_PIX_FMT_YUV422P10;
                 else if (strncmp("444P10", tokstart, 6) == 0)
-                    alt_pix_fmt = PIX_FMT_YUV444P10;
+                    alt_pix_fmt = AV_PIX_FMT_YUV444P10;
+                else if (strncmp("420P12", tokstart, 6) == 0)
+                    alt_pix_fmt = AV_PIX_FMT_YUV420P12;
+                else if (strncmp("422P12", tokstart, 6) == 0)
+                    alt_pix_fmt = AV_PIX_FMT_YUV422P12;
+                else if (strncmp("444P12", tokstart, 6) == 0)
+                    alt_pix_fmt = AV_PIX_FMT_YUV444P12;
+                else if (strncmp("420P14", tokstart, 6) == 0)
+                    alt_pix_fmt = AV_PIX_FMT_YUV420P14;
+                else if (strncmp("422P14", tokstart, 6) == 0)
+                    alt_pix_fmt = AV_PIX_FMT_YUV422P14;
+                else if (strncmp("444P14", tokstart, 6) == 0)
+                    alt_pix_fmt = AV_PIX_FMT_YUV444P14;
                 else if (strncmp("420P16", tokstart, 6) == 0)
-                    alt_pix_fmt = PIX_FMT_YUV420P16;
+                    alt_pix_fmt = AV_PIX_FMT_YUV420P16;
                 else if (strncmp("422P16", tokstart, 6) == 0)
-                    alt_pix_fmt = PIX_FMT_YUV422P16;
+                    alt_pix_fmt = AV_PIX_FMT_YUV422P16;
                 else if (strncmp("444P16", tokstart, 6) == 0)
-                    alt_pix_fmt = PIX_FMT_YUV444P16;
+                    alt_pix_fmt = AV_PIX_FMT_YUV444P16;
                 else if (strncmp("411", tokstart, 3) == 0)
-                    alt_pix_fmt = PIX_FMT_YUV411P;
+                    alt_pix_fmt = AV_PIX_FMT_YUV411P;
                 else if (strncmp("422", tokstart, 3) == 0)
-                    alt_pix_fmt = PIX_FMT_YUV422P;
+                    alt_pix_fmt = AV_PIX_FMT_YUV422P;
                 else if (strncmp("444", tokstart, 3) == 0)
-                    alt_pix_fmt = PIX_FMT_YUV444P;
+                    alt_pix_fmt = AV_PIX_FMT_YUV444P;
             }
             while (tokstart < header_end && *tokstart != 0x20)
                 tokstart++;
@@ -459,9 +514,9 @@
         return -1;
     }
 
-    if (pix_fmt == PIX_FMT_NONE) {
-        if (alt_pix_fmt == PIX_FMT_NONE)
-            pix_fmt = PIX_FMT_YUV420P;
+    if (pix_fmt == AV_PIX_FMT_NONE) {
+        if (alt_pix_fmt == AV_PIX_FMT_NONE)
+            pix_fmt = AV_PIX_FMT_YUV420P;
         else
             pix_fmt = alt_pix_fmt;
     }
@@ -497,7 +552,7 @@
 {
     int i;
     char header[MAX_FRAME_HEADER+1];
-    int packet_size, width, height;
+    int packet_size, width, height, ret;
     AVStream *st = s->streams[0];
     struct frame_attributes *s1 = s->priv_data;
 
@@ -508,20 +563,28 @@
             break;
         }
     }
-    if (i == MAX_FRAME_HEADER)
-        return -1;
+    if (s->pb->error)
+        return s->pb->error;
+    else if (s->pb->eof_reached)
+        return AVERROR_EOF;
+    else if (i == MAX_FRAME_HEADER)
+        return AVERROR_INVALIDDATA;
+
     if (strncmp(header, Y4M_FRAME_MAGIC, strlen(Y4M_FRAME_MAGIC)))
-        return -1;
+        return AVERROR_INVALIDDATA;
 
     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;
+        return packet_size;
 
-    if (av_get_packet(s->pb, pkt, packet_size) != packet_size)
-        return AVERROR(EIO);
+    ret = av_get_packet(s->pb, pkt, packet_size);
+    if (ret < 0)
+        return ret;
+    else if (ret != packet_size)
+        return s->pb->eof_reached ? AVERROR_EOF : AVERROR(EIO);
 
     if (st->codec->coded_frame) {
         st->codec->coded_frame->interlaced_frame = s1->interlaced_frame;
diff --git a/libavresample/audio_convert.c b/libavresample/audio_convert.c
index e9835c8..dcf8a39 100644
--- a/libavresample/audio_convert.c
+++ b/libavresample/audio_convert.c
@@ -284,9 +284,10 @@
     return ac;
 }
 
-int ff_audio_convert(AudioConvert *ac, AudioData *out, AudioData *in, int len)
+int ff_audio_convert(AudioConvert *ac, AudioData *out, AudioData *in)
 {
     int use_generic = 1;
+    int len         = in->nb_samples;
 
     /* determine whether to use the optimized function based on pointer and
        samples alignment in both the input and output */
diff --git a/libavresample/audio_convert.h b/libavresample/audio_convert.h
index 2b8bfac..bc27223 100644
--- a/libavresample/audio_convert.h
+++ b/libavresample/audio_convert.h
@@ -72,13 +72,16 @@
  * examined to determine whether to use the generic or optimized conversion
  * function (when available).
  *
+ * The number of samples to convert is determined by in->nb_samples. The output
+ * buffer must be large enough to handle this many samples. out->nb_samples is
+ * set by this function before a successful return.
+ *
  * @param ac     AudioConvert context
  * @param out    output audio data
  * @param in     input audio data
- * @param len    number of samples to convert
  * @return       0 on success, negative AVERROR code on failure
  */
-int ff_audio_convert(AudioConvert *ac, AudioData *out, AudioData *in, int len);
+int ff_audio_convert(AudioConvert *ac, AudioData *out, AudioData *in);
 
 /* arch-specific initialization functions */
 
diff --git a/libavresample/audio_data.c b/libavresample/audio_data.c
index d624ad3..199a68c 100644
--- a/libavresample/audio_data.c
+++ b/libavresample/audio_data.c
@@ -62,7 +62,7 @@
     return 0;
 }
 
-int ff_audio_data_init(AudioData *a, void **src, int plane_size, int channels,
+int ff_audio_data_init(AudioData *a, uint8_t **src, int plane_size, int channels,
                        int nb_samples, enum AVSampleFormat sample_fmt,
                        int read_only, const char *name)
 {
diff --git a/libavresample/audio_data.h b/libavresample/audio_data.h
index 4609ebc..558e7e6 100644
--- a/libavresample/audio_data.h
+++ b/libavresample/audio_data.h
@@ -73,7 +73,7 @@
  * @param name            name for debug logging (can be NULL)
  * @return                0 on success, negative AVERROR value on error
  */
-int ff_audio_data_init(AudioData *a, void **src, int plane_size, int channels,
+int ff_audio_data_init(AudioData *a, uint8_t **src, int plane_size, int channels,
                        int nb_samples, enum AVSampleFormat sample_fmt,
                        int read_only, const char *name);
 
diff --git a/libavresample/avresample-test.c b/libavresample/avresample-test.c
index 0d4f2df..ab49e48 100644
--- a/libavresample/avresample-test.c
+++ b/libavresample/avresample-test.c
@@ -305,8 +305,8 @@
                                 goto end;
                             }
 
-                            ret = avresample_convert(s, (void **)out_data, out_linesize, out_rate * 6,
-                                                        (void **) in_data,  in_linesize,  in_rate * 6);
+                            ret = avresample_convert(s, out_data, out_linesize, out_rate * 6,
+                                                         in_data,  in_linesize,  in_rate * 6);
                             if (ret < 0) {
                                 char errbuf[256];
                                 av_strerror(ret, errbuf, sizeof(errbuf));
diff --git a/libavresample/avresample.h b/libavresample/avresample.h
index b93aba5..affeeeb 100644
--- a/libavresample/avresample.h
+++ b/libavresample/avresample.h
@@ -23,11 +23,78 @@
 
 /**
  * @file
+ * @ingroup lavr
  * external API header
  */
 
-#include "libavutil/audioconvert.h"
+/**
+ * @defgroup lavr Libavresample
+ * @{
+ *
+ * Libavresample (lavr) is a library that handles audio resampling, sample
+ * format conversion and mixing.
+ *
+ * Interaction with lavr is done through AVAudioResampleContext, which is
+ * allocated with avresample_alloc_context(). It is opaque, so all parameters
+ * must be set with the @ref avoptions API.
+ *
+ * For example the following code will setup conversion from planar float sample
+ * format to interleaved signed 16-bit integer, downsampling from 48kHz to
+ * 44.1kHz and downmixing from 5.1 channels to stereo (using the default mixing
+ * matrix):
+ * @code
+ * AVAudioResampleContext *avr = avresample_alloc_context();
+ * av_opt_set_int(avr, "in_channel_layout",  AV_CH_LAYOUT_5POINT1, 0);
+ * av_opt_set_int(avr, "out_channel_layout", AV_CH_LAYOUT_STEREO,  0);
+ * av_opt_set_int(avr, "in_sample_rate",     48000,                0);
+ * av_opt_set_int(avr, "out_sample_rate",    44100,                0);
+ * av_opt_set_int(avr, "in_sample_fmt",      AV_SAMPLE_FMT_FLTP,   0);
+ * av_opt_set_int(avr, "out_sample_fmt,      AV_SAMPLE_FMT_S16,    0);
+ * @endcode
+ *
+ * Once the context is initialized, it must be opened with avresample_open(). If
+ * you need to change the conversion parameters, you must close the context with
+ * avresample_close(), change the parameters as described above, then reopen it
+ * again.
+ *
+ * The conversion itself is done by repeatedly calling avresample_convert().
+ * Note that the samples may get buffered in two places in lavr. The first one
+ * is the output FIFO, where the samples end up if the output buffer is not
+ * large enough. The data stored in there may be retrieved at any time with
+ * avresample_read(). The second place is the resampling delay buffer,
+ * applicable only when resampling is done. The samples in it require more input
+ * before they can be processed. Their current amount is returned by
+ * avresample_get_delay(). At the end of conversion the resampling buffer can be
+ * flushed by calling avresample_convert() with NULL input.
+ *
+ * The following code demonstrates the conversion loop assuming the parameters
+ * from above and caller-defined functions get_input() and handle_output():
+ * @code
+ * uint8_t **input;
+ * int in_linesize, in_samples;
+ *
+ * while (get_input(&input, &in_linesize, &in_samples)) {
+ *     uint8_t *output
+ *     int out_linesize;
+ *     int out_samples = avresample_available(avr) +
+ *                       av_rescale_rnd(avresample_get_delay(avr) +
+ *                                      in_samples, 44100, 48000, AV_ROUND_UP);
+ *     av_samples_alloc(&output, &out_linesize, 2, out_samples,
+ *                      AV_SAMPLE_FMT_S16, 0);
+ *     out_samples = avresample_convert(avr, &output, out_linesize, out_samples,
+ *                                      input, in_linesize, in_samples);
+ *     handle_output(output, out_linesize, out_samples);
+ *     av_freep(&output);
+ *  }
+ *  @endcode
+ *
+ *  When the conversion is finished and the FIFOs are flushed if required, the
+ *  conversion context and everything associated with it must be freed with
+ *  avresample_free().
+ */
+
 #include "libavutil/avutil.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/dict.h"
 #include "libavutil/log.h"
 
@@ -198,6 +265,10 @@
 /**
  * Convert input samples and write them to the output FIFO.
  *
+ * The upper bound on the number of output samples is given by
+ * avresample_available() + (avresample_get_delay() + number of input samples) *
+ * output sample rate / input sample rate.
+ *
  * The output data can be NULL or have fewer allocated samples than required.
  * In this case, any remaining samples not written to the output will be added
  * to an internal FIFO buffer, to be returned at the next call to this function
@@ -234,8 +305,8 @@
  *                        not including converted samples added to the internal
  *                        output FIFO
  */
-int avresample_convert(AVAudioResampleContext *avr, void **output,
-                       int out_plane_size, int out_samples, void **input,
+int avresample_convert(AVAudioResampleContext *avr, uint8_t **output,
+                       int out_plane_size, int out_samples, uint8_t **input,
                        int in_plane_size, int in_samples);
 
 /**
@@ -287,6 +358,10 @@
  * @param nb_samples  number of samples to read from the FIFO
  * @return            the number of samples written to output
  */
-int avresample_read(AVAudioResampleContext *avr, void **output, int nb_samples);
+int avresample_read(AVAudioResampleContext *avr, uint8_t **output, int nb_samples);
+
+/**
+ * @}
+ */
 
 #endif /* AVRESAMPLE_AVRESAMPLE_H */
diff --git a/libavresample/resample.c b/libavresample/resample.c
index f0af1ff..381d673 100644
--- a/libavresample/resample.c
+++ b/libavresample/resample.c
@@ -394,10 +394,9 @@
     return dst_index;
 }
 
-int ff_audio_resample(ResampleContext *c, AudioData *dst, AudioData *src,
-                      int *consumed)
+int ff_audio_resample(ResampleContext *c, AudioData *dst, AudioData *src)
 {
-    int ch, in_samples, in_leftover, out_samples = 0;
+    int ch, in_samples, in_leftover, consumed = 0, out_samples = 0;
     int ret = AVERROR(EINVAL);
 
     in_samples  = src ? src->nb_samples : 0;
@@ -430,7 +429,7 @@
     /* resample each channel plane */
     for (ch = 0; ch < c->buffer->channels; ch++) {
         out_samples = resample(c, (void *)dst->data[ch],
-                               (const void *)c->buffer->data[ch], consumed,
+                               (const void *)c->buffer->data[ch], &consumed,
                                c->buffer->nb_samples, dst->allocated_samples,
                                ch + 1 == c->buffer->channels);
     }
@@ -440,7 +439,7 @@
     }
 
     /* drain consumed samples from the internal buffer */
-    ff_audio_data_drain(c->buffer, *consumed);
+    ff_audio_data_drain(c->buffer, consumed);
 
     av_dlog(c->avr, "resampled %d in + %d leftover to %d out + %d leftover\n",
             in_samples, in_leftover, out_samples, c->buffer->nb_samples);
diff --git a/libavresample/resample.h b/libavresample/resample.h
index b42fdbb..7534e26 100644
--- a/libavresample/resample.h
+++ b/libavresample/resample.h
@@ -61,10 +61,8 @@
  * @param c         ResampleContext
  * @param dst       destination audio data
  * @param src       source audio data
- * @param consumed  number of samples consumed from the source
- * @return          number of samples written to the destination
+ * @return          0 on success, negative AVERROR code on failure
  */
-int ff_audio_resample(ResampleContext *c, AudioData *dst, AudioData *src,
-                      int *consumed);
+int ff_audio_resample(ResampleContext *c, AudioData *dst, AudioData *src);
 
 #endif /* AVRESAMPLE_RESAMPLE_H */
diff --git a/libavresample/utils.c b/libavresample/utils.c
index 8129293..5591f15 100644
--- a/libavresample/utils.c
+++ b/libavresample/utils.c
@@ -247,14 +247,14 @@
 }
 
 int attribute_align_arg avresample_convert(AVAudioResampleContext *avr,
-                                           void **output, int out_plane_size,
-                                           int out_samples, void **input,
+                                           uint8_t **output, int out_plane_size,
+                                           int out_samples, uint8_t **input,
                                            int in_plane_size, int in_samples)
 {
     AudioData input_buffer;
     AudioData output_buffer;
     AudioData *current_buffer;
-    int ret;
+    int ret, direct_output;
 
     /* reset internal buffers */
     if (avr->in_buffer) {
@@ -276,6 +276,7 @@
     av_dlog(avr, "[start conversion]\n");
 
     /* initialize output_buffer with output data */
+    direct_output = output && av_audio_fifo_size(avr->out_fifo) == 0;
     if (output) {
         ret = ff_audio_data_init(&output_buffer, output, out_plane_size,
                                  avr->out_channels, out_samples,
@@ -295,7 +296,7 @@
         current_buffer = &input_buffer;
 
         if (avr->upmix_needed && !avr->in_convert_needed && !avr->resample_needed &&
-            !avr->out_convert_needed && output && out_samples >= in_samples) {
+            !avr->out_convert_needed && direct_output && out_samples >= in_samples) {
             /* in some rare cases we can copy input to output and upmix
                directly in the output buffer */
             av_dlog(avr, "[copy] %s to output\n", current_buffer->name);
@@ -312,8 +313,8 @@
                 if (ret < 0)
                     return ret;
                 av_dlog(avr, "[convert] %s to in_buffer\n", current_buffer->name);
-                ret = ff_audio_convert(avr->ac_in, avr->in_buffer, current_buffer,
-                                       current_buffer->nb_samples);
+                ret = ff_audio_convert(avr->ac_in, avr->in_buffer,
+                                       current_buffer);
                 if (ret < 0)
                     return ret;
             } else {
@@ -341,16 +342,15 @@
 
     if (avr->resample_needed) {
         AudioData *resample_out;
-        int consumed = 0;
 
-        if (!avr->out_convert_needed && output && out_samples > 0)
+        if (!avr->out_convert_needed && direct_output && out_samples > 0)
             resample_out = &output_buffer;
         else
             resample_out = avr->resample_out_buffer;
         av_dlog(avr, "[resample] %s to %s\n", current_buffer->name,
                 resample_out->name);
         ret = ff_audio_resample(avr->resample, resample_out,
-                                current_buffer, &consumed);
+                                current_buffer);
         if (ret < 0)
             return ret;
 
@@ -377,11 +377,10 @@
     }
 
     if (avr->out_convert_needed) {
-        if (output && out_samples >= current_buffer->nb_samples) {
+        if (direct_output && out_samples >= current_buffer->nb_samples) {
             /* convert directly to output */
             av_dlog(avr, "[convert] %s to output\n", current_buffer->name);
-            ret = ff_audio_convert(avr->ac_out, &output_buffer, current_buffer,
-                                   current_buffer->nb_samples);
+            ret = ff_audio_convert(avr->ac_out, &output_buffer, current_buffer);
             if (ret < 0)
                 return ret;
 
@@ -394,7 +393,7 @@
                 return ret;
             av_dlog(avr, "[convert] %s to out_buffer\n", current_buffer->name);
             ret = ff_audio_convert(avr->ac_out, avr->out_buffer,
-                                   current_buffer, current_buffer->nb_samples);
+                                   current_buffer);
             if (ret < 0)
                 return ret;
             current_buffer = avr->out_buffer;
@@ -410,11 +409,11 @@
     return av_audio_fifo_size(avr->out_fifo);
 }
 
-int avresample_read(AVAudioResampleContext *avr, void **output, int nb_samples)
+int avresample_read(AVAudioResampleContext *avr, uint8_t **output, int nb_samples)
 {
     if (!output)
         return av_audio_fifo_drain(avr->out_fifo, nb_samples);
-    return av_audio_fifo_read(avr->out_fifo, output, nb_samples);
+    return av_audio_fifo_read(avr->out_fifo, (void**)output, nb_samples);
 }
 
 unsigned avresample_version(void)
diff --git a/libavresample/version.h b/libavresample/version.h
index c4741e4..53ba802 100644
--- a/libavresample/version.h
+++ b/libavresample/version.h
@@ -19,9 +19,9 @@
 #ifndef AVRESAMPLE_VERSION_H
 #define AVRESAMPLE_VERSION_H
 
-#define LIBAVRESAMPLE_VERSION_MAJOR  0
+#define LIBAVRESAMPLE_VERSION_MAJOR  1
 #define LIBAVRESAMPLE_VERSION_MINOR  0
-#define LIBAVRESAMPLE_VERSION_MICRO  3
+#define LIBAVRESAMPLE_VERSION_MICRO  0
 
 #define LIBAVRESAMPLE_VERSION_INT  AV_VERSION_INT(LIBAVRESAMPLE_VERSION_MAJOR, \
                                                   LIBAVRESAMPLE_VERSION_MINOR, \
diff --git a/libavresample/x86/audio_convert.asm b/libavresample/x86/audio_convert.asm
index 2ebdbc1..1d125c2 100644
--- a/libavresample/x86/audio_convert.asm
+++ b/libavresample/x86/audio_convert.asm
@@ -20,14 +20,14 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "x86inc.asm"
-%include "x86util.asm"
+%include "libavutil/x86/x86util.asm"
 %include "util.asm"
 
 SECTION_RODATA 32
 
 pf_s32_inv_scale: times 8 dd 0x30000000
 pf_s32_scale:     times 8 dd 0x4f000000
+pf_s32_clip:      times 8 dd 0x4effffff
 pf_s16_inv_scale: times 4 dd 0x38000000
 pf_s16_scale:     times 4 dd 0x47000000
 pb_shuf_unpack_even:      db -1, -1,  0,  1, -1, -1,  2,  3, -1, -1,  8,  9, -1, -1, 10, 11
@@ -197,17 +197,22 @@
 ;------------------------------------------------------------------------------
 
 %macro CONV_FLT_TO_S32 0
-cglobal conv_flt_to_s32, 3,3,5, dst, src, len
+cglobal conv_flt_to_s32, 3,3,6, dst, src, len
     lea     lenq, [lend*4]
     add     srcq, lenq
     add     dstq, lenq
     neg     lenq
     mova      m4, [pf_s32_scale]
+    mova      m5, [pf_s32_clip]
 .loop:
     mulps     m0, m4, [srcq+lenq         ]
     mulps     m1, m4, [srcq+lenq+1*mmsize]
     mulps     m2, m4, [srcq+lenq+2*mmsize]
     mulps     m3, m4, [srcq+lenq+3*mmsize]
+    minps     m0, m0, m5
+    minps     m1, m1, m5
+    minps     m2, m2, m5
+    minps     m3, m3, m5
     cvtps2dq  m0, m0
     cvtps2dq  m1, m1
     cvtps2dq  m2, m2
@@ -242,7 +247,7 @@
     add       src1q, lenq
     lea        dstq, [dstq+2*lenq]
     neg        lenq
-.loop
+.loop:
     mova         m0, [src0q+lenq       ]
     mova         m1, [src1q+lenq       ]
     mova         m2, [src0q+lenq+mmsize]
@@ -711,7 +716,7 @@
     add  src1q, lenq
     lea   dstq, [dstq+2*lenq]
     neg   lenq
-.loop
+.loop:
     mova    m0, [src0q+lenq       ]
     mova    m1, [src1q+lenq       ]
     mova    m2, [src0q+lenq+mmsize]
@@ -914,10 +919,8 @@
     REP_RET
 %endmacro
 
-%define PALIGNR PALIGNR_MMX
 INIT_XMM sse2
 CONV_S16_TO_S16P_6CH
-%define PALIGNR PALIGNR_SSSE3
 INIT_XMM ssse3
 CONV_S16_TO_S16P_6CH
 %if HAVE_AVX_EXTERNAL
@@ -1033,10 +1036,8 @@
     REP_RET
 %endmacro
 
-%define PALIGNR PALIGNR_MMX
 INIT_XMM sse2
 CONV_S16_TO_FLTP_6CH
-%define PALIGNR PALIGNR_SSSE3
 INIT_XMM ssse3
 CONV_S16_TO_FLTP_6CH
 INIT_XMM sse4
@@ -1155,10 +1156,8 @@
     REP_RET
 %endmacro
 
-%define PALIGNR PALIGNR_MMX
 INIT_XMM sse2
 CONV_FLT_TO_S16P_6CH
-%define PALIGNR PALIGNR_SSSE3
 INIT_XMM ssse3
 CONV_FLT_TO_S16P_6CH
 %if HAVE_AVX_EXTERNAL
diff --git a/libavresample/x86/audio_mix.asm b/libavresample/x86/audio_mix.asm
index 0c4a9bd..a3f1af5 100644
--- a/libavresample/x86/audio_mix.asm
+++ b/libavresample/x86/audio_mix.asm
@@ -19,8 +19,7 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "x86inc.asm"
-%include "x86util.asm"
+%include "libavutil/x86/x86util.asm"
 %include "util.asm"
 
 SECTION_TEXT
@@ -279,7 +278,15 @@
     and           rsp, ~(mmsize-1)
     sub           rsp, matrix_elements_stack * mmsize
     %else
-    %assign pad matrix_elements_stack * mmsize + (mmsize - gprsize) - (stack_offset & (mmsize - gprsize))
+    %assign matrix_stack_size matrix_elements_stack * mmsize
+    %assign pad matrix_stack_size + (mmsize - gprsize) - (stack_offset & (mmsize - gprsize))
+    ; on x86-32 for 7 and 8 channels we need more stack space for src pointers
+    %if ARCH_X86_32 && in_channels >= 7
+    %assign pad pad + 0x10
+    %define src5m [rsp+matrix_stack_size+0]
+    %define src6m [rsp+matrix_stack_size+4]
+    %define src7m [rsp+matrix_stack_size+8]
+    %endif
     SUB           rsp, pad
     %endif
 %endif
diff --git a/libavutil/Makefile b/libavutil/Makefile
index 18a5a63..61ddc9a 100644
--- a/libavutil/Makefile
+++ b/libavutil/Makefile
@@ -14,6 +14,7 @@
           blowfish.h                                                    \
           bprint.h                                                      \
           bswap.h                                                       \
+          channel_layout.h                                              \
           common.h                                                      \
           cpu.h                                                         \
           crc.h                                                         \
@@ -27,11 +28,11 @@
           intreadwrite.h                                                \
           lfg.h                                                         \
           log.h                                                         \
-          lzo.h                                                         \
           mathematics.h                                                 \
           md5.h                                                         \
           mem.h                                                         \
           dict.h                                                        \
+          old_pix_fmts.h                                                \
           opt.h                                                         \
           parseutils.h                                                  \
           pixdesc.h                                                     \
@@ -46,6 +47,8 @@
           version.h                                                     \
           xtea.h                                                        \
 
+HEADERS-$(CONFIG_LZO)                   += lzo.h
+
 ARCH_HEADERS = bswap.h                                                  \
                intmath.h                                                \
                intreadwrite.h                                           \
@@ -56,11 +59,11 @@
 OBJS = adler32.o                                                        \
        aes.o                                                            \
        audio_fifo.o                                                     \
-       audioconvert.o                                                   \
        avstring.o                                                       \
        base64.o                                                         \
        blowfish.o                                                       \
        bprint.o                                                         \
+       channel_layout.o                                                 \
        cpu.o                                                            \
        crc.o                                                            \
        des.o                                                            \
@@ -71,11 +74,11 @@
        float_dsp.o                                                      \
        imgutils.o                                                       \
        intfloat_readwrite.o                                             \
-       inverse.o                                                        \
+       intmath.o                                                        \
        lfg.o                                                            \
        lls.o                                                            \
        log.o                                                            \
-       lzo.o                                                            \
+       log2_tab.o                                                       \
        mathematics.o                                                    \
        md5.o                                                            \
        mem.o                                                            \
@@ -92,11 +95,14 @@
        timecode.o                                                       \
        tree.o                                                           \
        utils.o                                                          \
+       xga_font_data.o                                                  \
        xtea.o                                                           \
 
-OBJS-$(HAVE_BROKEN_SNPRINTF) += ../compat/msvcrt/snprintf.o
+OBJS-$(CONFIG_LZO)                      += lzo.o
 
-OBJS-$(HAVE_MSVCRT) += ../compat/strtod.o
+OBJS += $(COMPAT_OBJS:%=../compat/%)
+
+SKIPHEADERS          = old_pix_fmts.h
 
 TESTPROGS = adler32                                                     \
             aes                                                         \
@@ -125,6 +131,6 @@
 
 TESTPROGS-$(HAVE_LZO1X_999_COMPRESS) += lzo
 
-TOOLS = ffeval
+TOOLS = ffeval ffescape
 
 $(SUBDIR)lzo-test$(EXESUF): ELIBS = -llzo2
diff --git a/libavutil/aes.c b/libavutil/aes.c
index 7950902..a3eb295 100644
--- a/libavutil/aes.c
+++ b/libavutil/aes.c
@@ -41,6 +41,11 @@
 
 const int av_aes_size= sizeof(AVAES);
 
+struct AVAES *av_aes_alloc(void)
+{
+    return av_mallocz(sizeof(struct AVAES));
+}
+
 static const uint8_t rcon[10] = {
   0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36
 };
diff --git a/libavutil/aes.h b/libavutil/aes.h
index c73a7a1..09efbda 100644
--- a/libavutil/aes.h
+++ b/libavutil/aes.h
@@ -23,7 +23,8 @@
 
 #include <stdint.h>
 
-#include "symbols.h"
+#include "attributes.h"
+#include "version.h"
 
 /**
  * @defgroup lavu_aes AES
@@ -31,11 +32,16 @@
  * @{
  */
 
-extern AVUTIL_SYMBOL const int av_aes_size;
+extern const int av_aes_size;
 
 struct AVAES;
 
 /**
+ * Allocate an AVAES context.
+ */
+struct AVAES *av_aes_alloc(void);
+
+/**
  * Initialize an AVAES context.
  * @param key_bits 128, 192 or 256
  * @param decrypt 0 for encryption, 1 for decryption
diff --git a/libavutil/arm/asm.S b/libavutil/arm/asm.S
index b9d4b73..bb7c383 100644
--- a/libavutil/arm/asm.S
+++ b/libavutil/arm/asm.S
@@ -52,14 +52,7 @@
 
         .syntax unified
 T       .thumb
-
-.macro  require8 val=1
-ELF     .eabi_attribute 24, \val
-.endm
-
-.macro  preserve8 val=1
-ELF     .eabi_attribute 25, \val
-.endm
+ELF     .eabi_attribute 25, 1           @ Tag_ABI_align_preserved
 
 .macro  function name, export=0
         .set            .Lpic_idx, 0
@@ -141,7 +134,9 @@
         ldr             \rd, .Lpicoff\@
 .Lpic\@:
     .if \indir
-        ldr             \rd, [pc, \rd]
+A       ldr             \rd, [pc, \rd]
+T       add             \rd, pc
+T       ldr             \rd, [\rd]
     .else
         add             \rd, pc
     .endif
diff --git a/libavutil/arm/bswap.h b/libavutil/arm/bswap.h
index fd18e0d..c10c35f 100644
--- a/libavutil/arm/bswap.h
+++ b/libavutil/arm/bswap.h
@@ -26,13 +26,6 @@
 #ifdef __ARMCC_VERSION
 
 #if HAVE_ARMV6
-#define av_bswap16 av_bswap16
-static av_always_inline av_const unsigned av_bswap16(unsigned x)
-{
-    __asm { rev16 x, x }
-    return x;
-}
-
 #define av_bswap32 av_bswap32
 static av_always_inline av_const uint32_t av_bswap32(uint32_t x)
 {
diff --git a/libavutil/arm/float_dsp_init_neon.c b/libavutil/arm/float_dsp_init_neon.c
index 3ca0288..88eb4b3 100644
--- a/libavutil/arm/float_dsp_init_neon.c
+++ b/libavutil/arm/float_dsp_init_neon.c
@@ -29,8 +29,12 @@
 void ff_vector_fmac_scalar_neon(float *dst, const float *src, float mul,
                                 int len);
 
+void ff_vector_fmul_scalar_neon(float *dst, const float *src, float mul,
+                                int len);
+
 void ff_float_dsp_init_neon(AVFloatDSPContext *fdsp)
 {
     fdsp->vector_fmul = ff_vector_fmul_neon;
     fdsp->vector_fmac_scalar = ff_vector_fmac_scalar_neon;
+    fdsp->vector_fmul_scalar = ff_vector_fmul_scalar_neon;
 }
diff --git a/libavutil/arm/float_dsp_neon.S b/libavutil/arm/float_dsp_neon.S
index 03b1643..6d7bd52 100644
--- a/libavutil/arm/float_dsp_neon.S
+++ b/libavutil/arm/float_dsp_neon.S
@@ -22,8 +22,6 @@
 #include "config.h"
 #include "asm.S"
 
-        preserve8
-
 function ff_vector_fmul_neon, export=1
         subs            r3,  r3,  #8
         vld1.32         {d0-d3},  [r1,:128]!
@@ -110,3 +108,41 @@
         bx              lr
         .unreq          len
 endfunc
+
+function ff_vector_fmul_scalar_neon, export=1
+VFP     len .req r2
+NOVFP   len .req r3
+VFP     vdup.32         q8,  d0[0]
+NOVFP   vdup.32         q8,  r2
+        bics            r12, len, #15
+        beq             3f
+        vld1.32         {q0},[r1,:128]!
+        vld1.32         {q1},[r1,:128]!
+1:      vmul.f32        q0,  q0,  q8
+        vld1.32         {q2},[r1,:128]!
+        vmul.f32        q1,  q1,  q8
+        vld1.32         {q3},[r1,:128]!
+        vmul.f32        q2,  q2,  q8
+        vst1.32         {q0},[r0,:128]!
+        vmul.f32        q3,  q3,  q8
+        vst1.32         {q1},[r0,:128]!
+        subs            r12, r12, #16
+        beq             2f
+        vld1.32         {q0},[r1,:128]!
+        vst1.32         {q2},[r0,:128]!
+        vld1.32         {q1},[r1,:128]!
+        vst1.32         {q3},[r0,:128]!
+        b               1b
+2:      vst1.32         {q2},[r0,:128]!
+        vst1.32         {q3},[r0,:128]!
+        ands            len, len, #15
+        it              eq
+        bxeq            lr
+3:      vld1.32         {q0},[r1,:128]!
+        vmul.f32        q0,  q0,  q8
+        vst1.32         {q0},[r0,:128]!
+        subs            len, len, #4
+        bgt             3b
+        bx              lr
+        .unreq          len
+endfunc
diff --git a/libavutil/arm/intmath.h b/libavutil/arm/intmath.h
index 0ab0d4c6..0980a6f 100644
--- a/libavutil/arm/intmath.h
+++ b/libavutil/arm/intmath.h
@@ -30,19 +30,6 @@
 
 #if HAVE_ARMV6
 
-#define FASTDIV FASTDIV
-static av_always_inline av_const int FASTDIV(int a, int b)
-{
-    int r;
-    __asm__ ("cmp     %2, #2               \n\t"
-             "ldr     %0, [%3, %2, lsl #2] \n\t"
-             "ite     le                   \n\t"
-             "lsrle   %0, %1, #1           \n\t"
-             "smmulgt %0, %0, %1           \n\t"
-             : "=&r"(r) : "r"(a), "r"(b), "r"(ff_inverse) : "cc");
-    return r;
-}
-
 #define av_clip_uint8 av_clip_uint8_arm
 static av_always_inline av_const unsigned av_clip_uint8_arm(int a)
 {
@@ -99,17 +86,6 @@
     return r;
 }
 
-#else /* HAVE_ARMV6 */
-
-#define FASTDIV FASTDIV
-static av_always_inline av_const int FASTDIV(int a, int b)
-{
-    int r, t;
-    __asm__ ("umull %1, %0, %2, %3"
-             : "=&r"(r), "=&r"(t) : "r"(a), "r"(ff_inverse[b]));
-    return r;
-}
-
 #endif /* HAVE_ARMV6 */
 
 #if HAVE_ASM_MOD_Q
diff --git a/libavutil/audioconvert.h b/libavutil/audioconvert.h
index 76eb278..300a67c 100644
--- a/libavutil/audioconvert.h
+++ b/libavutil/audioconvert.h
@@ -1,208 +1,6 @@
-/*
- * Copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
- * Copyright (c) 2008 Peter Ross
- *
- * 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 AVUTIL_AUDIOCONVERT_H
-#define AVUTIL_AUDIOCONVERT_H
+#include "version.h"
 
-#include <stdint.h>
-
-/**
- * @file
- * audio conversion routines
- */
-
-/**
- * @addtogroup lavu_audio
- * @{
- */
-
-/**
- * @defgroup channel_masks 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.
-#define AV_CH_WIDE_LEFT              0x0000000080000000ULL
-#define AV_CH_WIDE_RIGHT             0x0000000100000000ULL
-#define AV_CH_SURROUND_DIRECT_LEFT   0x0000000200000000ULL
-#define AV_CH_SURROUND_DIRECT_RIGHT  0x0000000400000000ULL
-#define AV_CH_LOW_FREQUENCY_2        0x0000000800000000ULL
-
-/** 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          0x8000000000000000ULL
-
-/**
- * @}
- * @defgroup channel_mask_c 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_2POINT1           (AV_CH_LAYOUT_STEREO|AV_CH_LOW_FREQUENCY)
-#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_3POINT1           (AV_CH_LAYOUT_SURROUND|AV_CH_LOW_FREQUENCY)
-#define AV_CH_LAYOUT_4POINT0           (AV_CH_LAYOUT_SURROUND|AV_CH_BACK_CENTER)
-#define AV_CH_LAYOUT_4POINT1           (AV_CH_LAYOUT_4POINT0|AV_CH_LOW_FREQUENCY)
-#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_6POINT0           (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_CENTER)
-#define AV_CH_LAYOUT_6POINT0_FRONT     (AV_CH_LAYOUT_2_2|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
-#define AV_CH_LAYOUT_HEXAGONAL         (AV_CH_LAYOUT_5POINT0_BACK|AV_CH_BACK_CENTER)
-#define AV_CH_LAYOUT_6POINT1           (AV_CH_LAYOUT_5POINT1|AV_CH_BACK_CENTER)
-#define AV_CH_LAYOUT_6POINT1_BACK      (AV_CH_LAYOUT_5POINT1_BACK|AV_CH_BACK_CENTER)
-#define AV_CH_LAYOUT_6POINT1_FRONT     (AV_CH_LAYOUT_6POINT0_FRONT|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_7POINT0_FRONT     (AV_CH_LAYOUT_5POINT0|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
-#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|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
-#define AV_CH_LAYOUT_7POINT1_WIDE_BACK (AV_CH_LAYOUT_5POINT1_BACK|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
-#define AV_CH_LAYOUT_OCTAGONAL         (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_LEFT|AV_CH_BACK_CENTER|AV_CH_BACK_RIGHT)
-#define AV_CH_LAYOUT_STEREO_DOWNMIX    (AV_CH_STEREO_LEFT|AV_CH_STEREO_RIGHT)
-
-enum AVMatrixEncoding {
-    AV_MATRIX_ENCODING_NONE,
-    AV_MATRIX_ENCODING_DOLBY,
-    AV_MATRIX_ENCODING_DPLII,
-    AV_MATRIX_ENCODING_NB
-};
-
-/**
- * @}
- */
-
-/**
- * Return a channel layout id that matches name, or 0 if no match is found.
- *
- * name can be one or several of the following notations,
- * separated by '+' or '|':
- * - the name of an usual channel layout (mono, stereo, 4.0, quad, 5.0,
- *   5.0(side), 5.1, 5.1(side), 7.1, 7.1(wide), downmix);
- * - the name of a single channel (FL, FR, FC, LFE, BL, BR, FLC, FRC, BC,
- *   SL, SR, TC, TFL, TFC, TFR, TBL, TBC, TBR, DL, DR);
- * - a number of channels, in decimal, optionally followed by 'c', yielding
- *   the default channel layout for that number of channels (@see
- *   av_get_default_channel_layout);
- * - a channel layout mask, in hexadecimal starting with "0x" (see the
- *   AV_CH_* macros).
- *
- * Example: "stereo+FC" = "2+FC" = "2c+1c" = "0x7"
- */
-uint64_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, uint64_t channel_layout);
-
-struct AVBPrint;
-/**
- * Append a description of a channel layout to a bprint buffer.
- */
-void av_bprint_channel_layout(struct AVBPrint *bp, int nb_channels, uint64_t channel_layout);
-
-/**
- * Return the number of channels in the channel layout.
- */
-int av_get_channel_layout_nb_channels(uint64_t channel_layout);
-
-/**
- * Return default channel layout for a given number of channels.
- */
-int64_t av_get_default_channel_layout(int nb_channels);
-
-/**
- * Get the index of a channel in channel_layout.
- *
- * @param channel a channel layout describing exactly one channel which must be
- *                present in channel_layout.
- *
- * @return index of channel in channel_layout on success, a negative AVERROR
- *         on error.
- */
-int av_get_channel_layout_channel_index(uint64_t channel_layout,
-                                        uint64_t channel);
-
-/**
- * Get the channel with the given index in channel_layout.
- */
-uint64_t av_channel_layout_extract_channel(uint64_t channel_layout, int index);
-
-/**
- * Get the name of a given channel.
- *
- * @return channel name on success, NULL on error.
- */
-const char *av_get_channel_name(uint64_t channel);
-
-/**
- * Get the description of a given channel.
- *
- * @param channel  a channel layout with a single channel
- * @return  channel description on success, NULL on error
- */
-const char *av_get_channel_description(uint64_t channel);
-
-/**
- * Get the value and name of a standard channel layout.
- *
- * @param[in]  index   index in an internal list, starting at 0
- * @param[out] layout  channel layout mask
- * @param[out] name    name of the layout
- * @return  0  if the layout exists,
- *          <0 if index is beyond the limits
- */
-int av_get_standard_channel_layout(unsigned index, uint64_t *layout,
-                                   const char **name);
-
-/**
- * @}
- */
-
-#endif /* AVUTIL_AUDIOCONVERT_H */
+#if FF_API_AUDIOCONVERT
+#include "channel_layout.h"
+#endif
diff --git a/libavutil/avstring.c b/libavutil/avstring.c
index 8b258a4..802d0f8 100644
--- a/libavutil/avstring.c
+++ b/libavutil/avstring.c
@@ -252,10 +252,13 @@
         };
 
         for (i=0; i < FF_ARRAY_ELEMS(strings); i++) {
-            const char *p= strings[i];
+            const char *p = strings[i];
+            char *q;
             printf("|%s|", p);
-            printf(" -> |%s|", av_get_token(&p, ":"));
+            q = av_get_token(&p, ":");
+            printf(" -> |%s|", q);
             printf(" + |%s|\n", p);
+            av_free(q);
         }
     }
 
diff --git a/libavutil/avutil.h b/libavutil/avutil.h
index cd02b35..8f63e3b 100644
--- a/libavutil/avutil.h
+++ b/libavutil/avutil.h
@@ -26,7 +26,7 @@
  * external API header
  */
 
-/*
+/**
  * @mainpage
  *
  * @section ffmpeg_intro Introduction
@@ -39,6 +39,7 @@
  * @li @ref libavf "libavformat" I/O and muxing/demuxing library
  * @li @ref lavd "libavdevice" special devices muxing/demuxing library
  * @li @ref lavu "libavutil" common utility library
+ * @li @ref libswresample "libswresample" audio resampling, format conversion and mixing
  * @li @subpage libpostproc post processing library
  * @li @subpage libswscale  color conversion and scaling library
  */
@@ -109,43 +110,6 @@
 
 
 /**
- * @defgroup preproc_misc Preprocessor String Macros
- *
- * String manipulation macros
- *
- * @{
- */
-
-#define AV_STRINGIFY(s)         AV_TOSTRING(s)
-#define AV_TOSTRING(s) #s
-
-#define AV_GLUE(a, b) a ## b
-#define AV_JOIN(a, b) AV_GLUE(a, b)
-
-#define AV_PRAGMA(s) _Pragma(#s)
-
-/**
- * @}
- */
-
-/**
- * @defgroup version_utils Library Version Macros
- *
- * Useful to check and match library version in order to maintain
- * backward compatibility.
- *
- * @{
- */
-
-#define AV_VERSION_INT(a, b, c) (a<<16 | b<<8 | c)
-#define AV_VERSION_DOT(a, b, c) a ##.## b ##.## c
-#define AV_VERSION(a, b, c) AV_VERSION_DOT(a, b, c)
-
-/**
- * @}
- */
-
-/**
  * @addtogroup lavu_ver
  * @{
  */
diff --git a/libavutil/blowfish.c b/libavutil/blowfish.c
index 5fe95e8..cdc2952 100644
--- a/libavutil/blowfish.c
+++ b/libavutil/blowfish.c
@@ -380,15 +380,15 @@
 
             av_blowfish_crypt_ecb(ctx, &v0, &v1, decrypt);
 
-            AV_WB32(dst, v0);
-            AV_WB32(dst + 4, v1);
-
             if (iv) {
-                for (i = 0; i < 8; i++)
-                    dst[i] = dst[i] ^ iv[i];
+                v0 ^= AV_RB32(iv);
+                v1 ^= AV_RB32(iv + 4);
                 memcpy(iv, src, 8);
             }
 
+            AV_WB32(dst, v0);
+            AV_WB32(dst + 4, v1);
+
             src   += 8;
             dst   += 8;
         }
@@ -509,32 +509,61 @@
 /* plaintext bytes */
 static const uint8_t plaintext[8] = "BLOWFISH";
 
+static const uint8_t plaintext2[16] = "BLOWFISHBLOWFISH";
+
 /* ciphertext bytes */
 static const uint8_t ciphertext[8] = {
     0x32, 0x4E, 0xD0, 0xFE, 0xF4, 0x13, 0xA2, 0x03
 };
 
+static const uint8_t ciphertext2[16] = {
+    0x53, 0x00, 0x40, 0x06, 0x63, 0xf2, 0x1d, 0x99,
+    0x3b, 0x9b, 0x27, 0x64, 0x46, 0xfd, 0x20, 0xc1,
+};
+
+#define IV "blowfish"
+
+#undef exit
+static void test_blowfish(AVBlowfish *ctx, uint8_t *dst, const uint8_t *src,
+                          const uint8_t *ref, int len, uint8_t *iv, int dir,
+                          const char *test)
+{
+    av_blowfish_crypt(ctx, dst, src, len, iv, dir);
+    if (memcmp(dst, ref, 8*len)) {
+        int i;
+        printf("%s failed\ngot      ", test);
+        for (i = 0; i < 8*len; i++)
+            printf("%02x ", dst[i]);
+        printf("\nexpected ");
+        for (i = 0; i < 8*len; i++)
+            printf("%02x ", ref[i]);
+        printf("\n");
+        exit(1);
+    }
+}
+
 int main(void)
 {
     AVBlowfish ctx;
     uint32_t tmptext_l[NUM_VARIABLE_KEY_TESTS];
     uint32_t tmptext_r[NUM_VARIABLE_KEY_TESTS];
-    uint8_t tmp[8];
+    uint8_t tmp[16], iv[8];
     int i;
 
     av_blowfish_init(&ctx, "abcdefghijklmnopqrstuvwxyz", 26);
 
-    av_blowfish_crypt(&ctx, tmp, plaintext, 1, NULL, 0);
-    if (memcmp(tmp, ciphertext, 8)) {
-        printf("Test encryption failed.\n");
-        return 1;
-    }
-
-    av_blowfish_crypt(&ctx, tmp, ciphertext, 1, NULL, 1);
-    if (memcmp(tmp, plaintext, 8)) {
-        printf("Test decryption failed.\n");
-        return 1;
-    }
+    test_blowfish(&ctx, tmp, plaintext, ciphertext, 1, NULL, 0, "encryption");
+    test_blowfish(&ctx, tmp, ciphertext, plaintext, 1, NULL, 1, "decryption");
+    test_blowfish(&ctx, tmp, tmp, ciphertext, 1, NULL, 0, "Inplace encryption");
+    test_blowfish(&ctx, tmp, tmp, plaintext,  1, NULL, 1, "Inplace decryption");
+    memcpy(iv, IV, 8);
+    test_blowfish(&ctx, tmp, plaintext2, ciphertext2, 2, iv, 0, "CBC encryption");
+    memcpy(iv, IV, 8);
+    test_blowfish(&ctx, tmp, ciphertext2, plaintext2, 2, iv, 1, "CBC decryption");
+    memcpy(iv, IV, 8);
+    test_blowfish(&ctx, tmp, tmp, ciphertext2, 2, iv, 0, "Inplace CBC encryption");
+    memcpy(iv, IV, 8);
+    test_blowfish(&ctx, tmp, tmp, plaintext2,  2, iv, 1, "Inplace CBC decryption");
 
     memcpy(tmptext_l, plaintext_l, sizeof(*plaintext_l) * NUM_VARIABLE_KEY_TESTS);
     memcpy(tmptext_r, plaintext_r, sizeof(*plaintext_r) * NUM_VARIABLE_KEY_TESTS);
diff --git a/libavutil/bprint.c b/libavutil/bprint.c
index 373a492..4684ab4 100644
--- a/libavutil/bprint.c
+++ b/libavutil/bprint.c
@@ -21,6 +21,7 @@
 #include <stdarg.h>
 #include <stdio.h>
 #include <string.h>
+#include <time.h>
 #include "avassert.h"
 #include "bprint.h"
 #include "common.h"
@@ -129,6 +130,57 @@
     av_bprint_grow(buf, n);
 }
 
+void av_bprint_strftime(AVBPrint *buf, const char *fmt, const struct tm *tm)
+{
+    unsigned room;
+    size_t l;
+
+    if (!*fmt)
+        return;
+    while (1) {
+        room = av_bprint_room(buf);
+        if (room && (l = strftime(buf->str + buf->len, room, fmt, tm)))
+            break;
+        /* strftime does not tell us how much room it would need: let us
+           retry with twice as much until the buffer is large enough */
+        room = !room ? strlen(fmt) + 1 :
+               room <= INT_MAX / 2 ? room * 2 : INT_MAX;
+        if (av_bprint_alloc(buf, room)) {
+            /* impossible to grow, try to manage something useful anyway */
+            room = av_bprint_room(buf);
+            if (room < 1024) {
+                /* if strftime fails because the buffer has (almost) reached
+                   its maximum size, let us try in a local buffer; 1k should
+                   be enough to format any real date+time string */
+                char buf2[1024];
+                if ((l = strftime(buf2, sizeof(buf2), fmt, tm))) {
+                    av_bprintf(buf, "%s", buf2);
+                    return;
+                }
+            }
+            if (room) {
+                /* if anything else failed and the buffer is not already
+                   truncated, let us add a stock string and force truncation */
+                static const char txt[] = "[truncated strftime output]";
+                memset(buf->str + buf->len, '!', room);
+                memcpy(buf->str + buf->len, txt, FFMIN(sizeof(txt) - 1, room));
+                av_bprint_grow(buf, room); /* force truncation */
+            }
+            return;
+        }
+    }
+    av_bprint_grow(buf, l);
+}
+
+void av_bprint_get_buffer(AVBPrint *buf, unsigned size,
+                          unsigned char **mem, unsigned *actual_size)
+{
+    if (size > av_bprint_room(buf))
+        av_bprint_alloc(buf, size);
+    *actual_size = av_bprint_room(buf);
+    *mem = *actual_size ? buf->str + buf->len : NULL;
+}
+
 void av_bprint_clear(AVBPrint *buf)
 {
     if (buf->len) {
@@ -192,6 +244,7 @@
 {
     AVBPrint b;
     char buf[256];
+    struct tm testtime = { .tm_year = 100, .tm_mon = 11, .tm_mday = 20 };
 
     av_bprint_init(&b, 0, -1);
     bprint_pascal(&b, 5);
@@ -226,6 +279,15 @@
     bprint_pascal(&b, 25);
     printf("Long text count only buffer: %u/%u\n", (unsigned)strlen(buf), b.len);
 
+    av_bprint_init(&b, 0, -1);
+    av_bprint_strftime(&b, "%Y-%m-%d", &testtime);
+    printf("strftime full: %u/%u \"%s\"\n", (unsigned)strlen(buf), b.len, b.str);
+    av_bprint_finalize(&b, NULL);
+
+    av_bprint_init(&b, 0, 8);
+    av_bprint_strftime(&b, "%Y-%m-%d", &testtime);
+    printf("strftime truncated: %u/%u \"%s\"\n", (unsigned)strlen(buf), b.len, b.str);
+
     return 0;
 }
 
diff --git a/libavutil/bprint.h b/libavutil/bprint.h
index 2bef18d..f3915fe 100644
--- a/libavutil/bprint.h
+++ b/libavutil/bprint.h
@@ -116,7 +116,7 @@
 void av_bprint_init_for_buffer(AVBPrint *buf, char *buffer, unsigned size);
 
 /**
- * Append a formated string to a print buffer.
+ * Append a formatted string to a print buffer.
  */
 void av_bprintf(AVBPrint *buf, const char *fmt, ...) av_printf_format(2, 3);
 
@@ -125,6 +125,32 @@
  */
 void av_bprint_chars(AVBPrint *buf, char c, unsigned n);
 
+struct tm;
+/**
+ * Append a formatted date and time to a print buffer.
+ *
+ * param buf  bprint buffer to use
+ * param fmt  date and time format string, see strftime()
+ * param tm   broken-down time structure to translate
+ *
+ * @note due to poor design of the standard strftime function, it may
+ * produce poor results if the format string expands to a very long text and
+ * the bprint buffer is near the limit stated by the size_max option.
+ */
+void av_bprint_strftime(AVBPrint *buf, const char *fmt, const struct tm *tm);
+
+/**
+ * Allocate bytes in the buffer for external use.
+ *
+ * @param[in]  buf          buffer structure
+ * @param[in]  size         required size
+ * @param[out] mem          pointer to the memory area
+ * @param[out] actual_size  size of the memory area after allocation;
+ *                          can be larger or smaller than size
+ */
+void av_bprint_get_buffer(AVBPrint *buf, unsigned size,
+                          unsigned char **mem, unsigned *actual_size);
+
 /**
  * Reset the string to "" but keep internal allocated data.
  */
diff --git a/libavutil/audioconvert.c b/libavutil/channel_layout.c
similarity index 98%
rename from libavutil/audioconvert.c
rename to libavutil/channel_layout.c
index caab5e6..ef6bad7 100644
--- a/libavutil/audioconvert.c
+++ b/libavutil/channel_layout.c
@@ -20,12 +20,12 @@
 
 /**
  * @file
- * audio conversion routines
+ * audio channel layout utility functions
  */
 
 #include "avstring.h"
 #include "avutil.h"
-#include "audioconvert.h"
+#include "channel_layout.h"
 #include "bprint.h"
 #include "common.h"
 
diff --git a/libavutil/channel_layout.h b/libavutil/channel_layout.h
new file mode 100644
index 0000000..2906098
--- /dev/null
+++ b/libavutil/channel_layout.h
@@ -0,0 +1,216 @@
+/*
+ * Copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
+ * Copyright (c) 2008 Peter Ross
+ *
+ * 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 AVUTIL_CHANNEL_LAYOUT_H
+#define AVUTIL_CHANNEL_LAYOUT_H
+
+#include <stdint.h>
+
+/**
+ * @file
+ * audio channel layout utility functions
+ */
+
+/**
+ * @addtogroup lavu_audio
+ * @{
+ */
+
+/**
+ * @defgroup channel_masks Audio channel masks
+ *
+ * A channel layout is a 64-bits integer with a bit set for every channel.
+ * The number of bits set must be equal to the number of channels.
+ * The value 0 means that the channel layout is not known.
+ * @note this data structure is not powerful enough to handle channels
+ * combinations that have the same channel multiple times, such as
+ * dual-mono.
+ *
+ * @{
+ */
+#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.
+#define AV_CH_WIDE_LEFT              0x0000000080000000ULL
+#define AV_CH_WIDE_RIGHT             0x0000000100000000ULL
+#define AV_CH_SURROUND_DIRECT_LEFT   0x0000000200000000ULL
+#define AV_CH_SURROUND_DIRECT_RIGHT  0x0000000400000000ULL
+#define AV_CH_LOW_FREQUENCY_2        0x0000000800000000ULL
+
+/** 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          0x8000000000000000ULL
+
+/**
+ * @}
+ * @defgroup channel_mask_c 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_2POINT1           (AV_CH_LAYOUT_STEREO|AV_CH_LOW_FREQUENCY)
+#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_3POINT1           (AV_CH_LAYOUT_SURROUND|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_4POINT0           (AV_CH_LAYOUT_SURROUND|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_4POINT1           (AV_CH_LAYOUT_4POINT0|AV_CH_LOW_FREQUENCY)
+#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_6POINT0           (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_6POINT0_FRONT     (AV_CH_LAYOUT_2_2|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
+#define AV_CH_LAYOUT_HEXAGONAL         (AV_CH_LAYOUT_5POINT0_BACK|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_6POINT1           (AV_CH_LAYOUT_5POINT1|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_6POINT1_BACK      (AV_CH_LAYOUT_5POINT1_BACK|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_6POINT1_FRONT     (AV_CH_LAYOUT_6POINT0_FRONT|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_7POINT0_FRONT     (AV_CH_LAYOUT_5POINT0|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
+#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|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
+#define AV_CH_LAYOUT_7POINT1_WIDE_BACK (AV_CH_LAYOUT_5POINT1_BACK|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
+#define AV_CH_LAYOUT_OCTAGONAL         (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_LEFT|AV_CH_BACK_CENTER|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_STEREO_DOWNMIX    (AV_CH_STEREO_LEFT|AV_CH_STEREO_RIGHT)
+
+enum AVMatrixEncoding {
+    AV_MATRIX_ENCODING_NONE,
+    AV_MATRIX_ENCODING_DOLBY,
+    AV_MATRIX_ENCODING_DPLII,
+    AV_MATRIX_ENCODING_NB
+};
+
+/**
+ * @}
+ */
+
+/**
+ * Return a channel layout id that matches name, or 0 if no match is found.
+ *
+ * name can be one or several of the following notations,
+ * separated by '+' or '|':
+ * - the name of an usual channel layout (mono, stereo, 4.0, quad, 5.0,
+ *   5.0(side), 5.1, 5.1(side), 7.1, 7.1(wide), downmix);
+ * - the name of a single channel (FL, FR, FC, LFE, BL, BR, FLC, FRC, BC,
+ *   SL, SR, TC, TFL, TFC, TFR, TBL, TBC, TBR, DL, DR);
+ * - a number of channels, in decimal, optionally followed by 'c', yielding
+ *   the default channel layout for that number of channels (@see
+ *   av_get_default_channel_layout);
+ * - a channel layout mask, in hexadecimal starting with "0x" (see the
+ *   AV_CH_* macros).
+ *
+ * Example: "stereo+FC" = "2+FC" = "2c+1c" = "0x7"
+ */
+uint64_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, uint64_t channel_layout);
+
+struct AVBPrint;
+/**
+ * Append a description of a channel layout to a bprint buffer.
+ */
+void av_bprint_channel_layout(struct AVBPrint *bp, int nb_channels, uint64_t channel_layout);
+
+/**
+ * Return the number of channels in the channel layout.
+ */
+int av_get_channel_layout_nb_channels(uint64_t channel_layout);
+
+/**
+ * Return default channel layout for a given number of channels.
+ */
+int64_t av_get_default_channel_layout(int nb_channels);
+
+/**
+ * Get the index of a channel in channel_layout.
+ *
+ * @param channel a channel layout describing exactly one channel which must be
+ *                present in channel_layout.
+ *
+ * @return index of channel in channel_layout on success, a negative AVERROR
+ *         on error.
+ */
+int av_get_channel_layout_channel_index(uint64_t channel_layout,
+                                        uint64_t channel);
+
+/**
+ * Get the channel with the given index in channel_layout.
+ */
+uint64_t av_channel_layout_extract_channel(uint64_t channel_layout, int index);
+
+/**
+ * Get the name of a given channel.
+ *
+ * @return channel name on success, NULL on error.
+ */
+const char *av_get_channel_name(uint64_t channel);
+
+/**
+ * Get the description of a given channel.
+ *
+ * @param channel  a channel layout with a single channel
+ * @return  channel description on success, NULL on error
+ */
+const char *av_get_channel_description(uint64_t channel);
+
+/**
+ * Get the value and name of a standard channel layout.
+ *
+ * @param[in]  index   index in an internal list, starting at 0
+ * @param[out] layout  channel layout mask
+ * @param[out] name    name of the layout
+ * @return  0  if the layout exists,
+ *          <0 if index is beyond the limits
+ */
+int av_get_standard_channel_layout(unsigned index, uint64_t *layout,
+                                   const char **name);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_CHANNEL_LAYOUT_H */
diff --git a/libavutil/common.h b/libavutil/common.h
index 868ebab..0f36309 100644
--- a/libavutil/common.h
+++ b/libavutil/common.h
@@ -34,9 +34,10 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+
 #include "attributes.h"
+#include "version.h"
 #include "libavutil/avconfig.h"
-#include "symbols.h"
 
 #if AV_HAVE_BIGENDIAN
 #   define AV_NE(be, le) (be)
@@ -63,40 +64,13 @@
 #define FFALIGN(x, a) (((x)+(a)-1)&~((a)-1))
 
 /* misc math functions */
-extern AVUTIL_SYMBOL const uint8_t ff_log2_tab[256];
 
 /**
  * Reverse the order of the bits of an 8-bits unsigned integer.
  */
-extern AVUTIL_SYMBOL const uint8_t av_reverse[256];
-
-static av_always_inline av_const int av_log2_c(unsigned int v)
-{
-    int n = 0;
-    if (v & 0xffff0000) {
-        v >>= 16;
-        n += 16;
-    }
-    if (v & 0xff00) {
-        v >>= 8;
-        n += 8;
-    }
-    n += ff_log2_tab[v];
-
-    return n;
-}
-
-static av_always_inline av_const int av_log2_16bit_c(unsigned int v)
-{
-    int n = 0;
-    if (v & 0xff00) {
-        v >>= 8;
-        n += 8;
-    }
-    n += ff_log2_tab[v];
-
-    return n;
-}
+#if FF_API_AV_REVERSE
+extern attribute_deprecated const uint8_t av_reverse[256];
+#endif
 
 #ifdef HAVE_AV_CONFIG_H
 #   include "config.h"
@@ -106,6 +80,14 @@
 /* Pull in unguarded fallback defines at the end of this file. */
 #include "common.h"
 
+#ifndef av_log2
+av_const int av_log2(unsigned v);
+#endif
+
+#ifndef av_log2_16bit
+av_const int av_log2_16bit(unsigned v);
+#endif
+
 /**
  * Clip a signed integer value into the amin-amax range.
  * @param a value to clip
@@ -121,6 +103,20 @@
 }
 
 /**
+ * Clip a signed 64bit 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 av_always_inline av_const int64_t av_clip64_c(int64_t a, int64_t amin, int64_t amax)
+{
+    if      (a < amin) return amin;
+    else if (a > amax) return amax;
+    else               return a;
+}
+
+/**
  * Clip a signed integer value into the 0-255 range.
  * @param a value to clip
  * @return clipped value
@@ -275,16 +271,17 @@
 #define GET_UTF8(val, GET_BYTE, ERROR)\
     val= GET_BYTE;\
     {\
-        int ones= 7 - av_log2(val ^ 255);\
-        if(ones==1)\
+        uint32_t top = (val & 128) >> 1;\
+        if ((val & 0xc0) == 0x80)\
             ERROR\
-        val&= 127>>ones;\
-        while(--ones > 0){\
+        while (val & top) {\
             int tmp= GET_BYTE - 128;\
             if(tmp>>6)\
                 ERROR\
             val= (val<<6) + tmp;\
+            top <<= 5;\
         }\
+        val &= (top << 1) - 1;\
     }
 
 /**
@@ -387,18 +384,15 @@
  * 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_clip64
+#   define av_clip64        av_clip64_c
+#endif
 #ifndef av_clip_uint8
 #   define av_clip_uint8    av_clip_uint8_c
 #endif
diff --git a/libavutil/cpu.c b/libavutil/cpu.c
index f651cab..e14b413 100644
--- a/libavutil/cpu.c
+++ b/libavutil/cpu.c
@@ -135,6 +135,24 @@
         { "fma4"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_FMA4     },    .unit = "flags" },
         { "3dnow"   , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_3DNOW    },    .unit = "flags" },
         { "3dnowext", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_3DNOWEXT },    .unit = "flags" },
+        { "cmov",     NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_CMOV     },    .unit = "flags" },
+
+#define CPU_FLAG_P2 AV_CPU_FLAG_CMOV | AV_CPU_FLAG_MMX
+#define CPU_FLAG_P3 CPU_FLAG_P2 | AV_CPU_FLAG_MMX2 | AV_CPU_FLAG_SSE
+#define CPU_FLAG_P4 CPU_FLAG_P3| AV_CPU_FLAG_SSE2
+        { "pentium2", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPU_FLAG_P2          },    .unit = "flags" },
+        { "pentium3", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPU_FLAG_P3          },    .unit = "flags" },
+        { "pentium4", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPU_FLAG_P4          },    .unit = "flags" },
+
+#define CPU_FLAG_K62 AV_CPU_FLAG_MMX | AV_CPU_FLAG_3DNOW
+#define CPU_FLAG_ATHLON   CPU_FLAG_K62 | AV_CPU_FLAG_CMOV | AV_CPU_FLAG_3DNOWEXT | AV_CPU_FLAG_MMX2
+#define CPU_FLAG_ATHLONXP CPU_FLAG_ATHLON | AV_CPU_FLAG_SSE
+#define CPU_FLAG_K8  CPU_FLAG_ATHLONXP | AV_CPU_FLAG_SSE2
+        { "k6",       NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_MMX      },    .unit = "flags" },
+        { "k62",      NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPU_FLAG_K62         },    .unit = "flags" },
+        { "athlon",   NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPU_FLAG_ATHLON      },    .unit = "flags" },
+        { "athlonxp", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPU_FLAG_ATHLONXP    },    .unit = "flags" },
+        { "k8",       NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPU_FLAG_K8          },    .unit = "flags" },
 #elif ARCH_ARM
         { "armv5te",  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_ARMV5TE  },    .unit = "flags" },
         { "armv6",    NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_ARMV6    },    .unit = "flags" },
diff --git a/libavutil/crc.c b/libavutil/crc.c
index d640184..bba8cb1 100644
--- a/libavutil/crc.c
+++ b/libavutil/crc.c
@@ -40,22 +40,6 @@
 static AVCRC av_crc_table[AV_CRC_MAX][257];
 #endif
 
-/**
- * Initialize a CRC table.
- * @param ctx must be an array of size sizeof(AVCRC)*257 or sizeof(AVCRC)*1024
- * @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):
- *           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)
 {
     unsigned i, j;
@@ -89,11 +73,6 @@
     return 0;
 }
 
-/**
- * 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
- */
 const AVCRC *av_crc_get_table(AVCRCId crc_id)
 {
 #if !CONFIG_HARDCODED_TABLES
@@ -108,13 +87,6 @@
     return av_crc_table[crc_id];
 }
 
-/**
- * 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
- *
- * @see av_crc_init() "le" parameter
- */
 uint32_t av_crc(const AVCRC *ctx, uint32_t crc,
                 const uint8_t *buffer, size_t length)
 {
diff --git a/libavutil/crc.h b/libavutil/crc.h
index 1265054..2bdfca8 100644
--- a/libavutil/crc.h
+++ b/libavutil/crc.h
@@ -36,8 +36,39 @@
     AV_CRC_MAX,         /*< Not part of public API! Do not use outside libavutil. */
 }AVCRCId;
 
+/**
+ * Initialize a CRC table.
+ * @param ctx must be an array of size sizeof(AVCRC)*257 or sizeof(AVCRC)*1024
+ * @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):
+ *           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);
+
+/**
+ * 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
+ */
 const AVCRC *av_crc_get_table(AVCRCId crc_id);
-uint32_t av_crc(const AVCRC *ctx, uint32_t start_crc, const uint8_t *buffer, size_t length) av_pure;
+
+/**
+ * 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
+ *
+ * @see av_crc_init() "le" parameter
+ */
+uint32_t av_crc(const AVCRC *ctx, uint32_t crc,
+                const uint8_t *buffer, size_t length) av_pure;
 
 #endif /* AVUTIL_CRC_H */
diff --git a/libavutil/dict.h b/libavutil/dict.h
index 7f9924b..fde3650 100644
--- a/libavutil/dict.h
+++ b/libavutil/dict.h
@@ -74,7 +74,7 @@
 #define AV_DICT_APPEND         32   /**< If the entry already exists, append to it.  Note that no
                                       delimiter is added, the strings are simply concatenated. */
 
-typedef struct {
+typedef struct AVDictionaryEntry {
     char *key;
     char *value;
 } AVDictionaryEntry;
diff --git a/libavutil/error.c b/libavutil/error.c
index f49d214..bd66354 100644
--- a/libavutil/error.c
+++ b/libavutil/error.c
@@ -47,6 +47,7 @@
     { ERROR_TAG(PROTOCOL_NOT_FOUND), "Protocol not found"                             },
     { ERROR_TAG(STREAM_NOT_FOUND),   "Stream not found"                               },
     { ERROR_TAG(UNKNOWN),            "Unknown error occurred"                         },
+    { ERROR_TAG(EXPERIMENTAL),       "Experimental feature"                           },
 };
 
 int av_strerror(int errnum, char *errbuf, size_t errbuf_size)
diff --git a/libavutil/error.h b/libavutil/error.h
index 1768167..f3fd7bb 100644
--- a/libavutil/error.h
+++ b/libavutil/error.h
@@ -61,14 +61,15 @@
 #define AVERROR_OPTION_NOT_FOUND   FFERRTAG(0xF8,'O','P','T') ///< Option not found
 #define AVERROR_PATCHWELCOME       FFERRTAG( 'P','A','W','E') ///< Not yet implemented in FFmpeg, patches welcome
 #define AVERROR_PROTOCOL_NOT_FOUND FFERRTAG(0xF8,'P','R','O') ///< Protocol not found
-#define AVERROR_STREAM_NOT_FOUND   FFERRTAG(0xF8,'S','T','R') ///< Stream not found
 
+#define AVERROR_STREAM_NOT_FOUND   FFERRTAG(0xF8,'S','T','R') ///< Stream not found
 /**
  * This is semantically identical to AVERROR_BUG
  * it has been introduced in Libav after our AVERROR_BUG and with a modified value.
  */
 #define AVERROR_BUG2               FFERRTAG( 'B','U','G',' ')
 #define AVERROR_UNKNOWN            FFERRTAG( 'U','N','K','N') ///< Unknown error, typically from an external library
+#define AVERROR_EXPERIMENTAL       (-0x2bb2afa8) ///< Requested feature is flagged experimental. Set strict_std_compliance if you really want to use it.
 
 #define AV_ERROR_MAX_STRING_SIZE 64
 
diff --git a/libavutil/eval.c b/libavutil/eval.c
index dc2fb45..0d6bd15 100644
--- a/libavutil/eval.c
+++ b/libavutil/eval.c
@@ -258,7 +258,7 @@
                 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_div: return e->value * ((!CONFIG_FTRAPV || d2 ) ? (d / d2) : d * INFINITY);
                 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);
@@ -659,40 +659,6 @@
     return isnan(*d) ? AVERROR(EINVAL) : 0;
 }
 
-#if FF_API_OLD_EVAL_NAMES
-// LCOV_EXCL_START
-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);
-}
-// LCOV_EXCL_STOP
-#endif /* FF_API_OLD_EVAL_NAMES */
-
 #ifdef TEST
 // LCOV_EXCL_START
 #undef printf
@@ -714,7 +680,8 @@
 {
     int i;
     double d;
-    const char **expr, *exprs[] = {
+    const char *const *expr;
+    static const char *const exprs[] = {
         "",
         "1;2",
         "-20",
@@ -790,6 +757,11 @@
         "taylor(eq(mod(ld(1),4),1)-eq(mod(ld(1),4),3), PI/2, 1)",
         "root(sin(ld(0))-1, 2)",
         "root(sin(ld(0))+6+sin(ld(0)/12)-log(ld(0)), 100)",
+        "7000000B*random(0)",
+        "squish(2)",
+        "gauss(0.1)",
+        "hypot(4,3)",
+        "gcd(30,55)*min(9,1)",
         NULL
     };
 
diff --git a/libavutil/eval.h b/libavutil/eval.h
index 22fa121..a1d1fe3 100644
--- a/libavutil/eval.h
+++ b/libavutil/eval.h
@@ -91,39 +91,6 @@
  */
 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
diff --git a/libavutil/fifo.h b/libavutil/fifo.h
index ff66c95..849b9a6 100644
--- a/libavutil/fifo.h
+++ b/libavutil/fifo.h
@@ -141,15 +141,4 @@
     return ptr;
 }
 
-#if FF_API_AV_FIFO_PEEK
-/**
- * @deprecated Use av_fifo_peek2() instead.
- */
-attribute_deprecated
-static inline uint8_t av_fifo_peek(AVFifoBuffer *f, int offs)
-{
-    return *av_fifo_peek2(f, offs);
-}
-#endif
-
 #endif /* AVUTIL_FIFO_H */
diff --git a/libavutil/file.c b/libavutil/file.c
index 8dbeab6..41850f8 100644
--- a/libavutil/file.c
+++ b/libavutil/file.c
@@ -25,10 +25,12 @@
 #if HAVE_UNISTD_H
 #include <unistd.h>
 #endif
+#if HAVE_IO_H
+#include <io.h>
+#endif
 #if HAVE_MMAP
 #include <sys/mman.h>
 #elif HAVE_MAPVIEWOFFILE
-#include <io.h>
 #include <windows.h>
 #endif
 
@@ -175,6 +177,7 @@
     if (fd < 0) {
         int err = AVERROR(errno);
         av_log(&file_log_ctx, AV_LOG_ERROR, "ff_tempfile: Cannot open temporary file %s\n", *filename);
+        av_freep(filename);
         return err;
     }
     return fd; /* success */
diff --git a/libavutil/file.h b/libavutil/file.h
index f637005..b47ef80 100644
--- a/libavutil/file.h
+++ b/libavutil/file.h
@@ -57,6 +57,9 @@
  * *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.
+ * @note On very old libcs it is necessary to set a secure umask before
+ *       calling this, av_tempfile() cant call umask itself as it is used in
+ *       libraries and could interfere with the calling application.
  */
 int av_tempfile(const char *prefix, char **filename, int log_offset, void *log_ctx);
 
diff --git a/libavutil/float_dsp.c b/libavutil/float_dsp.c
index f5a8360..7b55187 100644
--- a/libavutil/float_dsp.c
+++ b/libavutil/float_dsp.c
@@ -39,10 +39,19 @@
         dst[i] += src[i] * mul;
 }
 
+static void vector_fmul_scalar_c(float *dst, const float *src, float mul,
+                                 int len)
+{
+    int i;
+    for (i = 0; i < len; i++)
+        dst[i] = src[i] * mul;
+}
+
 void avpriv_float_dsp_init(AVFloatDSPContext *fdsp, int bit_exact)
 {
     fdsp->vector_fmul = vector_fmul_c;
     fdsp->vector_fmac_scalar = vector_fmac_scalar_c;
+    fdsp->vector_fmul_scalar = vector_fmul_scalar_c;
 
 #if ARCH_ARM
     ff_float_dsp_init_arm(fdsp);
@@ -50,5 +59,7 @@
     ff_float_dsp_init_ppc(fdsp, bit_exact);
 #elif ARCH_X86
     ff_float_dsp_init_x86(fdsp);
+#elif ARCH_MIPS
+    ff_float_dsp_init_mips(fdsp);
 #endif
 }
diff --git a/libavutil/float_dsp.h b/libavutil/float_dsp.h
index 735eb34..b4e89cb 100644
--- a/libavutil/float_dsp.h
+++ b/libavutil/float_dsp.h
@@ -51,6 +51,21 @@
      */
     void (*vector_fmac_scalar)(float *dst, const float *src, float mul,
                                int len);
+
+    /**
+     * Multiply a vector of floats by a scalar float.  Source and
+     * destination vectors must overlap exactly or not at all.
+     *
+     * @param dst result vector
+     *            constraints: 16-byte aligned
+     * @param src input vector
+     *            constraints: 16-byte aligned
+     * @param mul scalar value
+     * @param len length of vector
+     *            constraints: multiple of 4
+     */
+    void (*vector_fmul_scalar)(float *dst, const float *src, float mul,
+                               int len);
 } AVFloatDSPContext;
 
 /**
@@ -65,5 +80,6 @@
 void ff_float_dsp_init_arm(AVFloatDSPContext *fdsp);
 void ff_float_dsp_init_ppc(AVFloatDSPContext *fdsp, int strict);
 void ff_float_dsp_init_x86(AVFloatDSPContext *fdsp);
+void ff_float_dsp_init_mips(AVFloatDSPContext *fdsp);
 
 #endif /* AVUTIL_FLOAT_DSP_H */
diff --git a/libavutil/imgutils.c b/libavutil/imgutils.c
index a3d4087..3060b07 100644
--- a/libavutil/imgutils.c
+++ b/libavutil/imgutils.c
@@ -21,6 +21,7 @@
  * misc image utilities
  */
 
+#include "avassert.h"
 #include "common.h"
 #include "imgutils.h"
 #include "internal.h"
@@ -53,6 +54,9 @@
 {
     int s, shifted_w, linesize;
 
+    if (!desc)
+        return AVERROR(EINVAL);
+
     if (width < 0)
         return AVERROR(EINVAL);
     s = (max_step_comp == 1 || max_step_comp == 2) ? desc->log2_chroma_w : 0;
@@ -60,34 +64,35 @@
     if (shifted_w && max_step > INT_MAX / shifted_w)
         return AVERROR(EINVAL);
     linesize = max_step * shifted_w;
+
     if (desc->flags & PIX_FMT_BITSTREAM)
         linesize = (linesize + 7) >> 3;
     return linesize;
 }
 
-int av_image_get_linesize(enum PixelFormat pix_fmt, int width, int plane)
+int av_image_get_linesize(enum AVPixelFormat pix_fmt, int width, int plane)
 {
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(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 */
 
-    if ((unsigned)pix_fmt >= PIX_FMT_NB || desc->flags & PIX_FMT_HWACCEL)
+    if ((unsigned)pix_fmt >= AV_PIX_FMT_NB || desc->flags & PIX_FMT_HWACCEL)
         return AVERROR(EINVAL);
 
     av_image_fill_max_pixsteps(max_step, max_step_comp, desc);
     return image_get_linesize(width, plane, max_step[plane], max_step_comp[plane], desc);
 }
 
-int av_image_fill_linesizes(int linesizes[4], enum PixelFormat pix_fmt, int width)
+int av_image_fill_linesizes(int linesizes[4], enum AVPixelFormat pix_fmt, int width)
 {
     int i, ret;
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(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)
+    if (!desc || desc->flags & PIX_FMT_HWACCEL)
         return AVERROR(EINVAL);
 
     av_image_fill_max_pixsteps(max_step, max_step_comp, desc);
@@ -100,15 +105,15 @@
     return 0;
 }
 
-int av_image_fill_pointers(uint8_t *data[4], enum PixelFormat pix_fmt, int height,
+int av_image_fill_pointers(uint8_t *data[4], enum AVPixelFormat pix_fmt, int height,
                            uint8_t *ptr, const int linesizes[4])
 {
     int i, total_size, size[4] = { 0 }, has_plane[4] = { 0 };
 
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
     memset(data     , 0, sizeof(data[0])*4);
 
-    if ((unsigned)pix_fmt >= PIX_FMT_NB || desc->flags & PIX_FMT_HWACCEL)
+    if (!desc || desc->flags & PIX_FMT_HWACCEL)
         return AVERROR(EINVAL);
 
     data[0] = ptr;
@@ -142,7 +147,7 @@
     return total_size;
 }
 
-int ff_set_systematic_pal2(uint32_t pal[256], enum PixelFormat pix_fmt)
+int avpriv_set_systematic_pal2(uint32_t pal[256], enum AVPixelFormat pix_fmt)
 {
     int i;
 
@@ -150,44 +155,48 @@
         int r, g, b;
 
         switch (pix_fmt) {
-        case PIX_FMT_RGB8:
+        case AV_PIX_FMT_RGB8:
             r = (i>>5    )*36;
             g = ((i>>2)&7)*36;
             b = (i&3     )*85;
             break;
-        case PIX_FMT_BGR8:
+        case AV_PIX_FMT_BGR8:
             b = (i>>6    )*85;
             g = ((i>>3)&7)*36;
             r = (i&7     )*36;
             break;
-        case PIX_FMT_RGB4_BYTE:
+        case AV_PIX_FMT_RGB4_BYTE:
             r = (i>>3    )*255;
             g = ((i>>1)&3)*85;
             b = (i&1     )*255;
             break;
-        case PIX_FMT_BGR4_BYTE:
+        case AV_PIX_FMT_BGR4_BYTE:
             b = (i>>3    )*255;
             g = ((i>>1)&3)*85;
             r = (i&1     )*255;
             break;
-        case PIX_FMT_GRAY8:
+        case AV_PIX_FMT_GRAY8:
             r = b = g = i;
             break;
         default:
             return AVERROR(EINVAL);
         }
-        pal[i] = b + (g<<8) + (r<<16) + (0xFF<<24);
+        pal[i] = b + (g<<8) + (r<<16) + (0xFFU<<24);
     }
 
     return 0;
 }
 
 int av_image_alloc(uint8_t *pointers[4], int linesizes[4],
-                   int w, int h, enum PixelFormat pix_fmt, int align)
+                   int w, int h, enum AVPixelFormat pix_fmt, int align)
 {
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
     int i, ret;
     uint8_t *buf;
 
+    if (!desc)
+        return AVERROR(EINVAL);
+
     if ((ret = av_image_check_size(w, h, 0, NULL)) < 0)
         return ret;
     if ((ret = av_image_fill_linesizes(linesizes, pix_fmt, align>7 ? FFALIGN(w, 8) : w)) < 0)
@@ -205,9 +214,8 @@
         av_free(buf);
         return ret;
     }
-    if (av_pix_fmt_descriptors[pix_fmt].flags & PIX_FMT_PAL ||
-        av_pix_fmt_descriptors[pix_fmt].flags & PIX_FMT_PSEUDOPAL)
-        ff_set_systematic_pal2((uint32_t*)pointers[1], pix_fmt);
+    if (desc->flags & PIX_FMT_PAL || desc->flags & PIX_FMT_PSEUDOPAL)
+        avpriv_set_systematic_pal2((uint32_t*)pointers[1], pix_fmt);
 
     return ret;
 }
@@ -237,6 +245,8 @@
 {
     if (!dst || !src)
         return;
+    av_assert0(abs(src_linesize) >= bytewidth);
+    av_assert0(abs(dst_linesize) >= bytewidth);
     for (;height > 0; height--) {
         memcpy(dst, src, bytewidth);
         dst += dst_linesize;
@@ -246,11 +256,11 @@
 
 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)
+                   enum AVPixelFormat pix_fmt, int width, int height)
 {
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
 
-    if (desc->flags & PIX_FMT_HWACCEL)
+    if (!desc || desc->flags & PIX_FMT_HWACCEL)
         return;
 
     if (desc->flags & PIX_FMT_PAL ||
@@ -269,6 +279,10 @@
         for (i = 0; i < planes_nb; i++) {
             int h = height;
             int bwidth = av_image_get_linesize(pix_fmt, width, i);
+            if (bwidth < 0) {
+                av_log(NULL, AV_LOG_ERROR, "av_image_get_linesize failed\n");
+                return;
+            }
             if (i == 1 || i == 2) {
                 h= -((-height)>>desc->log2_chroma_h);
             }
@@ -281,7 +295,7 @@
 
 int av_image_fill_arrays(uint8_t *dst_data[4], int dst_linesize[4],
                          const uint8_t *src,
-                         enum PixelFormat pix_fmt, int width, int height, int align)
+                         enum AVPixelFormat pix_fmt, int width, int height, int align)
 {
     int ret, i;
 
@@ -300,13 +314,17 @@
     return av_image_fill_pointers(dst_data, pix_fmt, height, (uint8_t *)src, dst_linesize);
 }
 
-int av_image_get_buffer_size(enum PixelFormat pix_fmt, int width, int height, int align)
+int av_image_get_buffer_size(enum AVPixelFormat pix_fmt, int width, int height, int align)
 {
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
     uint8_t *data[4];
     int linesize[4];
+
+    if (!desc)
+        return AVERROR(EINVAL);
     if (av_image_check_size(width, height, 0, NULL) < 0)
         return AVERROR(EINVAL);
-    if (av_pix_fmt_descriptors[pix_fmt].flags & PIX_FMT_PSEUDOPAL)
+    if (desc->flags & PIX_FMT_PSEUDOPAL)
         // do not include palette for these pseudo-paletted formats
         return width * height;
     return av_image_fill_arrays(data, linesize, NULL, pix_fmt, width, height, align);
@@ -314,10 +332,10 @@
 
 int av_image_copy_to_buffer(uint8_t *dst, int dst_size,
                             const uint8_t * const src_data[4], const int src_linesize[4],
-                            enum PixelFormat pix_fmt, int width, int height, int align)
+                            enum AVPixelFormat pix_fmt, int width, int height, int align)
 {
     int i, j, nb_planes = 0, linesize[4];
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
     int size = av_image_get_buffer_size(pix_fmt, width, height, align);
 
     if (size > dst_size || size < 0)
diff --git a/libavutil/imgutils.h b/libavutil/imgutils.h
index 3b1904b..ab32d66 100644
--- a/libavutil/imgutils.h
+++ b/libavutil/imgutils.h
@@ -55,7 +55,7 @@
  *
  * @return the computed size in bytes
  */
-int av_image_get_linesize(enum PixelFormat pix_fmt, int width, int plane);
+int av_image_get_linesize(enum AVPixelFormat pix_fmt, int width, int plane);
 
 /**
  * Fill plane linesizes for an image with pixel format pix_fmt and
@@ -64,7 +64,7 @@
  * @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);
+int av_image_fill_linesizes(int linesizes[4], enum AVPixelFormat pix_fmt, int width);
 
 /**
  * Fill plane data pointers for an image with pixel format pix_fmt and
@@ -77,7 +77,7 @@
  * @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,
+int av_image_fill_pointers(uint8_t *data[4], enum AVPixelFormat pix_fmt, int height,
                            uint8_t *ptr, const int linesizes[4]);
 
 /**
@@ -91,7 +91,7 @@
  * 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);
+                   int w, int h, enum AVPixelFormat pix_fmt, int align);
 
 /**
  * Copy image plane from src to dst.
@@ -99,6 +99,9 @@
  * The first byte of each successive line is separated by *_linesize
  * bytes.
  *
+ * bytewidth must be contained by both absolute values of dst_linesize
+ * and src_linesize, otherwise the function behavior is undefined.
+ *
  * @param dst_linesize linesize for the image plane in dst
  * @param src_linesize linesize for the image plane in src
  */
@@ -114,7 +117,7 @@
  */
 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);
+                   enum AVPixelFormat pix_fmt, int width, int height);
 
 /**
  * Setup the data pointers and linesizes based on the specified image
@@ -144,7 +147,7 @@
  */
 int av_image_fill_arrays(uint8_t *dst_data[4], int dst_linesize[4],
                          const uint8_t *src,
-                         enum PixelFormat pix_fmt, int width, int height, int align);
+                         enum AVPixelFormat pix_fmt, int width, int height, int align);
 
 /**
  * Return the size in bytes of the amount of data required to store an
@@ -152,7 +155,7 @@
  *
  * @param[in] align the assumed linesize alignment
  */
-int av_image_get_buffer_size(enum PixelFormat pix_fmt, int width, int height, int align);
+int av_image_get_buffer_size(enum AVPixelFormat pix_fmt, int width, int height, int align);
 
 /**
  * Copy image data from an image into a buffer.
@@ -173,7 +176,7 @@
  */
 int av_image_copy_to_buffer(uint8_t *dst, int dst_size,
                             const uint8_t * const src_data[4], const int src_linesize[4],
-                            enum PixelFormat pix_fmt, int width, int height, int align);
+                            enum AVPixelFormat pix_fmt, int width, int height, int align);
 
 /**
  * Check if the given dimension of an image is valid, meaning that all
@@ -187,7 +190,7 @@
  */
 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);
+int avpriv_set_systematic_pal2(uint32_t pal[256], enum AVPixelFormat pix_fmt);
 
 /**
  * @}
diff --git a/libavutil/internal.h b/libavutil/internal.h
index 2f92db6..cc977f6 100644
--- a/libavutil/internal.h
+++ b/libavutil/internal.h
@@ -48,6 +48,12 @@
 #endif
 #endif
 
+#if defined(_MSC_VER) && CONFIG_SHARED
+#    define av_export __declspec(dllimport)
+#else
+#    define av_export
+#endif
+
 #ifndef INT_BIT
 #    define INT_BIT (CHAR_BIT * sizeof(int))
 #endif
@@ -59,8 +65,6 @@
 #define free please_use_av_free
 #undef  realloc
 #define realloc please_use_av_realloc
-#undef  time
-#define time time_is_forbidden_due_to_security_issues
 #undef  rand
 #define rand rand_is_forbidden_due_to_state_trashing_use_av_lfg_get
 #undef  srand
@@ -71,8 +75,6 @@
 #define sprintf sprintf_is_forbidden_due_to_security_issues_use_snprintf
 #undef  strcat
 #define strcat strcat_is_forbidden_due_to_security_issues_use_av_strlcat
-#undef  strncpy
-#define strncpy strncpy_is_forbidden_due_to_security_issues_use_av_strlcpy
 #undef  exit
 #define exit exit_is_forbidden
 #undef  printf
diff --git a/libavutil/symbols.h b/libavutil/intmath.c
similarity index 69%
copy from libavutil/symbols.h
copy to libavutil/intmath.c
index 6011da2..1f725c7 100644
--- a/libavutil/symbols.h
+++ b/libavutil/intmath.c
@@ -1,6 +1,4 @@
 /*
- * Copyright (c) 2012 Ronald S. Bultje <rsbultje@gmail.com>
- *
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
@@ -18,15 +16,24 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#ifndef AVUTIL_SYMBOLS_H
-#define AVUTIL_SYMBOLS_H
+#include "intmath.h"
 
-#include "libavutil/avconfig.h"
+/* undef these to get the function prototypes from common.h */
+#undef av_log2
+#undef av_log2_16bit
+#include "common.h"
 
-#if AV_HAVE_SHARED_LIBS && defined(_MSC_VER) && !defined(COMPILING_avutil)
-#define AVUTIL_SYMBOL __declspec(dllimport)
-#else
-#define AVUTIL_SYMBOL
-#endif
+int av_log2(unsigned v)
+{
+    return ff_log2(v);
+}
 
-#endif /* AVUTIL_SYMBOLS_H */
+int av_log2_16bit(unsigned v)
+{
+    return ff_log2_16bit(v);
+}
+
+int av_ctz(int v)
+{
+    return ff_ctz(v);
+}
diff --git a/libavutil/intmath.h b/libavutil/intmath.h
index 461319d..e140d82 100644
--- a/libavutil/intmath.h
+++ b/libavutil/intmath.h
@@ -22,61 +22,127 @@
 #define AVUTIL_INTMATH_H
 
 #include <stdint.h>
+
 #include "config.h"
 #include "attributes.h"
-#include "symbols.h"
+
+#if ARCH_ARM
+#   include "arm/intmath.h"
+#endif
 
 /**
  * @addtogroup lavu_internal
  * @{
  */
 
-extern const uint32_t ff_inverse[257];
-
 #if   ARCH_ARM
 #   include "arm/intmath.h"
-#elif ARCH_X86
-#   include "x86/intmath.h"
 #endif
 
 #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
+#ifndef ff_log2
+#   define ff_log2(x) (31 - __builtin_clz((x)|1))
+#   ifndef ff_log2_16bit
+#      define ff_log2_16bit av_log2
 #   endif
-#endif /* av_log2 */
+#endif /* ff_log2 */
 
 #endif /* AV_GCC_VERSION_AT_LEAST(3,4) */
 
-#ifndef FASTDIV
-#   define FASTDIV(a,b) ((uint32_t)((((uint64_t)a) * ff_inverse[b]) >> 32))
-#endif /* FASTDIV */
+extern const uint8_t ff_log2_tab[256];
 
-#include "common.h"
-
-extern AVUTIL_SYMBOL const uint8_t ff_sqrt_tab[256];
-
-static inline av_const unsigned int ff_sqrt(unsigned int a)
+#ifndef ff_log2
+#define ff_log2 ff_log2_c
+static av_always_inline av_const int ff_log2_c(unsigned int v)
 {
-    unsigned int b;
-
-    if (a < 255) return (ff_sqrt_tab[a + 1] - 1) >> 4;
-    else if (a < (1 << 12)) b = ff_sqrt_tab[a >> 4] >> 2;
-#if !CONFIG_SMALL
-    else if (a < (1 << 14)) b = ff_sqrt_tab[a >> 6] >> 1;
-    else if (a < (1 << 16)) b = ff_sqrt_tab[a >> 8]   ;
-#endif
-    else {
-        int s = av_log2_16bit(a >> 16) >> 1;
-        unsigned int c = a >> (s + 2);
-        b = ff_sqrt_tab[c >> (s + 8)];
-        b = FASTDIV(c,b) + (b << s);
+    int n = 0;
+    if (v & 0xffff0000) {
+        v >>= 16;
+        n += 16;
     }
+    if (v & 0xff00) {
+        v >>= 8;
+        n += 8;
+    }
+    n += ff_log2_tab[v];
 
-    return b - (a < b * b);
+    return n;
 }
+#endif
+
+#ifndef ff_log2_16bit
+#define ff_log2_16bit ff_log2_16bit_c
+static av_always_inline av_const int ff_log2_16bit_c(unsigned int v)
+{
+    int n = 0;
+    if (v & 0xff00) {
+        v >>= 8;
+        n += 8;
+    }
+    n += ff_log2_tab[v];
+
+    return n;
+}
+#endif
+
+#define av_log2       ff_log2
+#define av_log2_16bit ff_log2_16bit
+
+/**
+ * @}
+ */
+
+/**
+ * @addtogroup lavu_math
+ * @{
+ */
+
+#if HAVE_FAST_CLZ && AV_GCC_VERSION_AT_LEAST(3,4)
+#ifndef ff_ctz
+#define ff_ctz(v) __builtin_ctz(v)
+#endif
+#endif
+
+#ifndef ff_ctz
+#define ff_ctz ff_ctz_c
+static av_always_inline av_const int ff_ctz_c(int v)
+{
+    int c;
+
+    if (v & 0x1)
+        return 0;
+
+    c = 1;
+    if (!(v & 0xffff)) {
+        v >>= 16;
+        c += 16;
+    }
+    if (!(v & 0xff)) {
+        v >>= 8;
+        c += 8;
+    }
+    if (!(v & 0xf)) {
+        v >>= 4;
+        c += 4;
+    }
+    if (!(v & 0x3)) {
+        v >>= 2;
+        c += 2;
+    }
+    c -= v & 0x1;
+
+    return c;
+}
+#endif
+
+/**
+ * Trailing zero bit count.
+ *
+ * @param v  input value. If v is 0, the result is undefined.
+ * @return   the number of trailing 0-bits
+ */
+int av_ctz(int v);
 
 /**
  * @}
diff --git a/libavutil/intreadwrite.h b/libavutil/intreadwrite.h
index 7c68ead..34e21d4 100644
--- a/libavutil/intreadwrite.h
+++ b/libavutil/intreadwrite.h
@@ -468,6 +468,33 @@
 #   define AV_WN64A(p, v) AV_WNA(64, p, v)
 #endif
 
+/*
+ * The AV_COPYxxU macros are suitable for copying data to/from unaligned
+ * memory locations.
+ */
+
+#define AV_COPYU(n, d, s) AV_WN##n(d, AV_RN##n(s));
+
+#ifndef AV_COPY16U
+#   define AV_COPY16U(d, s) AV_COPYU(16, d, s)
+#endif
+
+#ifndef AV_COPY32U
+#   define AV_COPY32U(d, s) AV_COPYU(32, d, s)
+#endif
+
+#ifndef AV_COPY64U
+#   define AV_COPY64U(d, s) AV_COPYU(64, d, s)
+#endif
+
+#ifndef AV_COPY128U
+#   define AV_COPY128U(d, s)                                    \
+    do {                                                        \
+        AV_COPY64U(d, s);                                       \
+        AV_COPY64U((char *)(d) + 8, (const char *)(s) + 8);     \
+    } while(0)
+#endif
+
 /* Parameters for AV_COPY*, AV_SWAP*, AV_ZERO* must be
  * naturally aligned. They may be implemented using MMX,
  * so emms_c() must be called before using any float code
diff --git a/libavutil/lfg.h b/libavutil/lfg.h
index 854ffce..ec90562 100644
--- a/libavutil/lfg.h
+++ b/libavutil/lfg.h
@@ -22,7 +22,7 @@
 #ifndef AVUTIL_LFG_H
 #define AVUTIL_LFG_H
 
-typedef struct {
+typedef struct AVLFG {
     unsigned int state[64];
     int index;
 } AVLFG;
diff --git a/libavutil/libm.h b/libavutil/libm.h
index d36420b..bfcc21c 100644
--- a/libavutil/libm.h
+++ b/libavutil/libm.h
@@ -33,6 +33,21 @@
 #include "libavutil/mips/libm_mips.h"
 #endif /* HAVE_MIPSFPU && HAVE_INLINE_ASM*/
 
+#if !HAVE_ATANF
+#undef atanf
+#define atanf(x) ((float)atan(x))
+#endif
+
+#if !HAVE_ATAN2F
+#undef atan2f
+#define atan2f(y, x) ((float)atan2(y, x))
+#endif
+
+#if !HAVE_POWF
+#undef powf
+#define powf(x, y) ((float)pow(x, y))
+#endif
+
 #if !HAVE_CBRTF
 static av_always_inline float cbrtf(float x)
 {
@@ -40,6 +55,16 @@
 }
 #endif
 
+#if !HAVE_COSF
+#undef cosf
+#define cosf(x) ((float)cos(x))
+#endif
+
+#if !HAVE_EXPF
+#undef expf
+#define expf(x) ((float)exp(x))
+#endif
+
 #if !HAVE_EXP2
 #undef exp2
 #define exp2(x) exp((x) * 0.693147180559945)
@@ -70,6 +95,11 @@
 }
 #endif /* HAVE_ISNAN */
 
+#if !HAVE_LDEXPF
+#undef ldexpf
+#define ldexpf(x, exp) ((float)ldexp(x, exp))
+#endif
+
 #if !HAVE_LLRINT
 #undef llrint
 #define llrint(x) ((long long)rint(x))
@@ -90,6 +120,16 @@
 #define log2f(x) ((float)log2(x))
 #endif /* HAVE_LOG2F */
 
+#if !HAVE_LOG10F
+#undef log10f
+#define log10f(x) ((float)log10(x))
+#endif
+
+#if !HAVE_SINF
+#undef sinf
+#define sinf(x) ((float)sin(x))
+#endif
+
 #if !HAVE_RINT
 static inline double rint(double x)
 {
diff --git a/libavutil/log.c b/libavutil/log.c
index 1bae1b2..57b3d5d 100644
--- a/libavutil/log.c
+++ b/libavutil/log.c
@@ -29,6 +29,9 @@
 #if HAVE_UNISTD_H
 #include <unistd.h>
 #endif
+#if HAVE_IO_H
+#include <io.h>
+#endif
 #include <stdlib.h>
 #include "avutil.h"
 #include "common.h"
@@ -39,9 +42,8 @@
 static int av_log_level = AV_LOG_INFO;
 static int flags;
 
-#if defined(_WIN32) && !defined(__MINGW32CE__)
+#if HAVE_SETCONSOLETEXTATTRIBUTE
 #include <windows.h>
-#include <io.h>
 static const uint8_t color[16 + AV_CLASS_CATEGORY_NB] = {
     [AV_LOG_PANIC  /8] = 12,
     [AV_LOG_FATAL  /8] = 12,
@@ -101,7 +103,7 @@
 static void colored_fputs(int level, const char *str)
 {
     if (use_color < 0) {
-#if defined(_WIN32) && !defined(__MINGW32CE__)
+#if HAVE_SETCONSOLETEXTATTRIBUTE
         CONSOLE_SCREEN_BUFFER_INFO con_info;
         con = GetStdHandle(STD_ERROR_HANDLE);
         use_color = (con != INVALID_HANDLE_VALUE) && !getenv("NO_COLOR") &&
diff --git a/libavutil/log2_tab.c b/libavutil/log2_tab.c
new file mode 100644
index 0000000..0dbf07d
--- /dev/null
+++ b/libavutil/log2_tab.c
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2003-2012 Michael Niedermayer <michaelni@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
+ */
+
+#include <stdint.h>
+
+const uint8_t ff_log2_tab[256]={
+        0,0,1,1,2,2,2,2,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,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,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
+        6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
+        7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+        7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+        7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+        7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7
+};
diff --git a/libavutil/lzo.c b/libavutil/lzo.c
index 3642308..c723257 100644
--- a/libavutil/lzo.c
+++ b/libavutil/lzo.c
@@ -19,17 +19,18 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include <string.h>
+
 #include "avutil.h"
 #include "common.h"
-/// Avoid e.g. MPlayers fast_memcpy, it slows things down here.
-#undef memcpy
-#include <string.h>
+#include "intreadwrite.h"
 #include "lzo.h"
 
 /// Define if we may write up to 12 bytes beyond the output buffer.
 #define OUTBUF_PADDED 1
 /// Define if we may read up to 8 bytes beyond the input buffer.
 #define INBUF_PADDED 1
+
 typedef struct LZOContext {
     const uint8_t *in, *in_end;
     uint8_t *out_start, *out, *out_end;
@@ -40,7 +41,8 @@
  * @brief Reads one byte from the input buffer, avoiding an overrun.
  * @return byte read
  */
-static inline int get_byte(LZOContext *c) {
+static inline int get_byte(LZOContext *c)
+{
     if (c->in < c->in_end)
         return *c->in++;
     c->error |= AV_LZO_INPUT_DEPLETED;
@@ -59,57 +61,45 @@
  * @param mask bits used from x
  * @return decoded length value
  */
-static inline int get_len(LZOContext *c, int x, int mask) {
+static inline int get_len(LZOContext *c, int x, int mask)
+{
     int cnt = x & mask;
     if (!cnt) {
-        while (!(x = get_byte(c))) cnt += 255;
+        while (!(x = get_byte(c)))
+            cnt += 255;
         cnt += mask + x;
     }
     return cnt;
 }
 
-//#define UNALIGNED_LOADSTORE
-#define BUILTIN_MEMCPY
-#ifdef UNALIGNED_LOADSTORE
-#define COPY2(d, s) *(uint16_t *)(d) = *(uint16_t *)(s);
-#define COPY4(d, s) *(uint32_t *)(d) = *(uint32_t *)(s);
-#elif defined(BUILTIN_MEMCPY)
-#define COPY2(d, s) memcpy(d, s, 2);
-#define COPY4(d, s) memcpy(d, s, 4);
-#else
-#define COPY2(d, s) (d)[0] = (s)[0]; (d)[1] = (s)[1];
-#define COPY4(d, s) (d)[0] = (s)[0]; (d)[1] = (s)[1]; (d)[2] = (s)[2]; (d)[3] = (s)[3];
-#endif
-
 /**
  * @brief Copies bytes from input to output buffer with checking.
  * @param cnt number of bytes to copy, must be >= 0
  */
-static inline void copy(LZOContext *c, int cnt) {
+static inline void copy(LZOContext *c, int cnt)
+{
     register const uint8_t *src = c->in;
-    register uint8_t *dst = c->out;
+    register uint8_t *dst       = c->out;
     if (cnt > c->in_end - src) {
-        cnt = FFMAX(c->in_end - src, 0);
+        cnt       = FFMAX(c->in_end - src, 0);
         c->error |= AV_LZO_INPUT_DEPLETED;
     }
     if (cnt > c->out_end - dst) {
-        cnt = FFMAX(c->out_end - dst, 0);
+        cnt       = FFMAX(c->out_end - dst, 0);
         c->error |= AV_LZO_OUTPUT_FULL;
     }
 #if defined(INBUF_PADDED) && defined(OUTBUF_PADDED)
-    COPY4(dst, src);
+    AV_COPY32U(dst, src);
     src += 4;
     dst += 4;
     cnt -= 4;
     if (cnt > 0)
 #endif
-        memcpy(dst, src, cnt);
-    c->in = src + cnt;
+    memcpy(dst, src, cnt);
+    c->in  = src + cnt;
     c->out = dst + cnt;
 }
 
-static inline void memcpy_backptr(uint8_t *dst, int back, int cnt);
-
 /**
  * @brief Copies previously decoded bytes to current position.
  * @param back how many bytes back we start, must be > 0
@@ -118,61 +108,25 @@
  * cnt > back is valid, this will copy the bytes we just copied,
  * thus creating a repeating pattern with a period length of back.
  */
-static inline void copy_backptr(LZOContext *c, int back, int cnt) {
+static inline void copy_backptr(LZOContext *c, int back, int cnt)
+{
     register const uint8_t *src = &c->out[-back];
-    register uint8_t *dst = c->out;
+    register uint8_t *dst       = c->out;
     if (src < c->out_start || src > dst) {
         c->error |= AV_LZO_INVALID_BACKPTR;
         return;
     }
     if (cnt > c->out_end - dst) {
-        cnt = FFMAX(c->out_end - dst, 0);
+        cnt       = FFMAX(c->out_end - dst, 0);
         c->error |= AV_LZO_OUTPUT_FULL;
     }
-    memcpy_backptr(dst, back, cnt);
+    av_memcpy_backptr(dst, back, cnt);
     c->out = dst + cnt;
 }
 
-static inline void memcpy_backptr(uint8_t *dst, int back, int cnt) {
-    const uint8_t *src = &dst[-back];
-    if (back <= 1) {
-        memset(dst, *src, cnt);
-    } else {
-#ifdef OUTBUF_PADDED
-        COPY2(dst, src);
-        COPY2(dst + 2, src + 2);
-        src += 4;
-        dst += 4;
-        cnt -= 4;
-        if (cnt > 0) {
-            COPY2(dst, src);
-            COPY2(dst + 2, src + 2);
-            COPY2(dst + 4, src + 4);
-            COPY2(dst + 6, src + 6);
-            src += 8;
-            dst += 8;
-            cnt -= 8;
-        }
-#endif
-        if (cnt > 0) {
-            int blocklen = back;
-            while (cnt > blocklen) {
-                memcpy(dst, src, blocklen);
-                dst += blocklen;
-                cnt -= blocklen;
-                blocklen <<= 1;
-            }
-            memcpy(dst, src, cnt);
-        }
-    }
-}
-
-void av_memcpy_backptr(uint8_t *dst, int back, int cnt) {
-    memcpy_backptr(dst, back, cnt);
-}
-
-int av_lzo1x_decode(void *out, int *outlen, const void *in, int *inlen) {
-    int state= 0;
+int av_lzo1x_decode(void *out, int *outlen, const void *in, int *inlen)
+{
+    int state = 0;
     int x;
     LZOContext c;
     if (*outlen <= 0 || *inlen <= 0) {
@@ -183,16 +137,17 @@
             res |= AV_LZO_INPUT_DEPLETED;
         return res;
     }
-    c.in = in;
-    c.in_end = (const uint8_t *)in + *inlen;
-    c.out = c.out_start = out;
-    c.out_end = (uint8_t *)out + * outlen;
-    c.error = 0;
-    x = GETB(c);
+    c.in      = in;
+    c.in_end  = (const uint8_t *)in + *inlen;
+    c.out     = c.out_start = out;
+    c.out_end = (uint8_t *)out + *outlen;
+    c.error   = 0;
+    x         = GETB(c);
     if (x > 17) {
         copy(&c, x - 17);
         x = GETB(c);
-        if (x < 16) c.error |= AV_LZO_ERROR;
+        if (x < 16)
+            c.error |= AV_LZO_ERROR;
     }
     if (c.in > c.in_end)
         c.error |= AV_LZO_INPUT_DEPLETED;
@@ -200,16 +155,16 @@
         int cnt, back;
         if (x > 15) {
             if (x > 63) {
-                cnt = (x >> 5) - 1;
+                cnt  = (x >> 5) - 1;
                 back = (GETB(c) << 3) + ((x >> 2) & 7) + 1;
             } else if (x > 31) {
-                cnt = get_len(&c, x, 31);
-                x = GETB(c);
+                cnt  = get_len(&c, x, 31);
+                x    = GETB(c);
                 back = (GETB(c) << 6) + (x >> 2) + 1;
             } else {
-                cnt = get_len(&c, x, 7);
-                back = (1 << 14) + ((x & 8) << 11);
-                x = GETB(c);
+                cnt   = get_len(&c, x, 7);
+                back  = (1 << 14) + ((x & 8) << 11);
+                x     = GETB(c);
                 back += (GETB(c) << 6) + (x >> 2);
                 if (back == (1 << 14)) {
                     if (cnt != 1)
@@ -217,21 +172,21 @@
                     break;
                 }
             }
-        } else if(!state){
-                cnt = get_len(&c, x, 15);
-                copy(&c, cnt + 3);
-                x = GETB(c);
-                if (x > 15)
-                    continue;
-                cnt = 1;
-                back = (1 << 11) + (GETB(c) << 2) + (x >> 2) + 1;
+        } else if (!state) {
+            cnt = get_len(&c, x, 15);
+            copy(&c, cnt + 3);
+            x = GETB(c);
+            if (x > 15)
+                continue;
+            cnt  = 1;
+            back = (1 << 11) + (GETB(c) << 2) + (x >> 2) + 1;
         } else {
-                cnt = 0;
-                back = (GETB(c) << 2) + (x >> 2) + 1;
+            cnt  = 0;
+            back = (GETB(c) << 2) + (x >> 2) + 1;
         }
         copy_backptr(&c, back, cnt + 2);
-        state=
-        cnt = x & 3;
+        state =
+        cnt   = x & 3;
         copy(&c, cnt);
         x = GETB(c);
     }
diff --git a/libavutil/lzo.h b/libavutil/lzo.h
index 060b5c9..c034039 100644
--- a/libavutil/lzo.h
+++ b/libavutil/lzo.h
@@ -32,18 +32,18 @@
 #include <stdint.h>
 
 /** @name Error flags returned by av_lzo1x_decode
-  * @{ */
+ * @{ */
 /// end of the input buffer reached before decoding finished
-#define AV_LZO_INPUT_DEPLETED 1
+#define AV_LZO_INPUT_DEPLETED  1
 /// decoded data did not fit into output buffer
-#define AV_LZO_OUTPUT_FULL 2
+#define AV_LZO_OUTPUT_FULL     2
 /// a reference to previously decoded data was wrong
 #define AV_LZO_INVALID_BACKPTR 4
 /// a non-specific error in the compressed bitstream
-#define AV_LZO_ERROR 8
+#define AV_LZO_ERROR           8
 /** @} */
 
-#define AV_LZO_INPUT_PADDING 8
+#define AV_LZO_INPUT_PADDING   8
 #define AV_LZO_OUTPUT_PADDING 12
 
 /**
@@ -60,17 +60,6 @@
 int av_lzo1x_decode(void *out, int *outlen, const void *in, int *inlen);
 
 /**
- * @brief deliberately overlapping memcpy implementation
- * @param dst destination buffer; must be padded with 12 additional bytes
- * @param back how many bytes back we start (the initial size of the overlapping window), must be > 0
- * @param cnt number of bytes to copy, must be >= 0
- *
- * cnt > back is valid, this will copy the bytes we just copied,
- * thus creating a repeating pattern with a period length of back.
- */
-void av_memcpy_backptr(uint8_t *dst, int back, int cnt);
-
-/**
  * @}
  */
 
diff --git a/libavutil/mathematics.c b/libavutil/mathematics.c
index 2e6a5fa..6c2f6c0 100644
--- a/libavutil/mathematics.c
+++ b/libavutil/mathematics.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005 Michael Niedermayer <michaelni@gmx.at>
+ * Copyright (c) 2005-2012 Michael Niedermayer <michaelni@gmx.at>
  *
  * This file is part of FFmpeg.
  *
@@ -25,32 +25,13 @@
 
 #include <stdint.h>
 #include <limits.h>
+
 #include "mathematics.h"
 #include "libavutil/common.h"
 #include "avassert.h"
+#include "version.h"
 
-const uint8_t ff_sqrt_tab[256]={
-  0, 16, 23, 28, 32, 36, 40, 43, 46, 48, 51, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 77, 79, 80, 82, 84, 85, 87, 88, 90,
- 91, 92, 94, 95, 96, 98, 99,100,102,103,104,105,107,108,109,110,111,112,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
-128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,144,145,146,147,148,149,150,151,151,152,153,154,155,156,156,
-157,158,159,160,160,161,162,163,164,164,165,166,167,168,168,169,170,171,171,172,173,174,174,175,176,176,177,178,179,179,180,181,
-182,182,183,184,184,185,186,186,187,188,188,189,190,190,191,192,192,193,194,194,195,196,196,197,198,198,199,200,200,201,202,202,
-203,204,204,205,205,206,207,207,208,208,209,210,210,211,212,212,213,213,214,215,215,216,216,217,218,218,219,219,220,220,221,222,
-222,223,223,224,224,225,226,226,227,227,228,228,229,230,230,231,231,232,232,233,233,234,235,235,236,236,237,237,238,238,239,239,
-240,240,241,242,242,243,243,244,244,245,245,246,246,247,247,248,248,249,249,250,250,251,251,252,252,253,253,254,254,255,255,255
-};
-
-const uint8_t ff_log2_tab[256]={
-        0,0,1,1,2,2,2,2,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,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,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
-        6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
-        7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
-        7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
-        7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
-        7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7
-};
-
+#if FF_API_AV_REVERSE
 const uint8_t av_reverse[256]={
 0x00,0x80,0x40,0xC0,0x20,0xA0,0x60,0xE0,0x10,0x90,0x50,0xD0,0x30,0xB0,0x70,0xF0,
 0x08,0x88,0x48,0xC8,0x28,0xA8,0x68,0xE8,0x18,0x98,0x58,0xD8,0x38,0xB8,0x78,0xF8,
@@ -69,6 +50,7 @@
 0x07,0x87,0x47,0xC7,0x27,0xA7,0x67,0xE7,0x17,0x97,0x57,0xD7,0x37,0xB7,0x77,0xF7,
 0x0F,0x8F,0x4F,0xCF,0x2F,0xAF,0x6F,0xEF,0x1F,0x9F,0x5F,0xDF,0x3F,0xBF,0x7F,0xFF,
 };
+#endif
 
 int64_t av_gcd(int64_t a, int64_t b){
     if(b) return av_gcd(b, a%b);
@@ -160,3 +142,26 @@
         c-= mod;
     return c;
 }
+
+int64_t av_rescale_delta(AVRational in_tb, int64_t in_ts,  AVRational fs_tb, int duration, int64_t *last, AVRational out_tb){
+    int64_t a, b, this;
+
+    av_assert0(in_ts != AV_NOPTS_VALUE);
+    av_assert0(duration >= 0);
+
+    if (*last == AV_NOPTS_VALUE || !duration || in_tb.num*(int64_t)out_tb.den <= out_tb.num*(int64_t)in_tb.den) {
+simple_round:
+        *last = av_rescale_q(in_ts, in_tb, fs_tb) + duration;
+        return av_rescale_q(in_ts, in_tb, out_tb);
+    }
+
+    a =  av_rescale_q_rnd(2*in_ts-1, in_tb, fs_tb, AV_ROUND_DOWN)   >>1;
+    b = (av_rescale_q_rnd(2*in_ts+1, in_tb, fs_tb, AV_ROUND_UP  )+1)>>1;
+    if (*last < 2*a - b || *last > 2*b - a)
+        goto simple_round;
+
+    this = av_clip64(*last, a, b);
+    *last = this + duration;
+
+    return av_rescale_q(this, fs_tb, out_tb);
+}
diff --git a/libavutil/mathematics.h b/libavutil/mathematics.h
index 5458d2f..0021d52 100644
--- a/libavutil/mathematics.h
+++ b/libavutil/mathematics.h
@@ -1,5 +1,5 @@
 /*
- * copyright (c) 2005 Michael Niedermayer <michaelni@gmx.at>
+ * copyright (c) 2005-2012 Michael Niedermayer <michaelni@gmx.at>
  *
  * This file is part of FFmpeg.
  *
@@ -123,6 +123,17 @@
 int64_t av_compare_mod(uint64_t a, uint64_t b, uint64_t mod);
 
 /**
+ * Rescale a timestamp while preserving known durations.
+ *
+ * @param in_ts Input timestamp
+ * @param in_tb Input timesbase
+ * @param fs_tb Duration and *last timebase
+ * @param duration duration till the next call
+ * @param out_tb Output timesbase
+ */
+int64_t av_rescale_delta(AVRational in_tb, int64_t in_ts,  AVRational fs_tb, int duration, int64_t *last, AVRational out_tb);
+
+/**
  * @}
  */
 
diff --git a/libavutil/md5.c b/libavutil/md5.c
index 00447f9..d0d0d27 100644
--- a/libavutil/md5.c
+++ b/libavutil/md5.c
@@ -34,6 +34,7 @@
 #include "bswap.h"
 #include "intreadwrite.h"
 #include "md5.h"
+#include "mem.h"
 
 typedef struct AVMD5{
     uint64_t len;
@@ -43,6 +44,11 @@
 
 const int av_md5_size = sizeof(AVMD5);
 
+struct AVMD5 *av_md5_alloc(void)
+{
+    return av_mallocz(sizeof(struct AVMD5));
+}
+
 static const uint8_t S[4][4] = {
     { 7, 12, 17, 22 },  /* round 1 */
     { 5,  9, 14, 20 },  /* round 2 */
diff --git a/libavutil/md5.h b/libavutil/md5.h
index 0c42d5c..1d7be9f 100644
--- a/libavutil/md5.h
+++ b/libavutil/md5.h
@@ -23,7 +23,8 @@
 
 #include <stdint.h>
 
-#include "symbols.h"
+#include "attributes.h"
+#include "version.h"
 
 /**
  * @defgroup lavu_md5 MD5
@@ -31,10 +32,11 @@
  * @{
  */
 
-extern AVUTIL_SYMBOL const int av_md5_size;
+extern const int av_md5_size;
 
 struct AVMD5;
 
+struct AVMD5 *av_md5_alloc(void);
 void av_md5_init(struct AVMD5 *ctx);
 void av_md5_update(struct AVMD5 *ctx, const uint8_t *src, const int len);
 void av_md5_final(struct AVMD5 *ctx, uint8_t *dst);
diff --git a/libavutil/mem.c b/libavutil/mem.c
index 8ec226b..d73cdde 100644
--- a/libavutil/mem.c
+++ b/libavutil/mem.c
@@ -29,6 +29,7 @@
 #include "config.h"
 
 #include <limits.h>
+#include <stdint.h>
 #include <stdlib.h>
 #include <string.h>
 #if HAVE_MALLOC_H
@@ -36,6 +37,7 @@
 #endif
 
 #include "avutil.h"
+#include "intreadwrite.h"
 #include "mem.h"
 
 /* here we can use OS-dependent allocation functions */
@@ -80,47 +82,47 @@
 #endif
 
     /* let's disallow possible ambiguous cases */
-    if (size > (max_alloc_size-32))
+    if (size > (max_alloc_size - 32))
         return NULL;
 
 #if CONFIG_MEMALIGN_HACK
-    ptr = malloc(size+ALIGN);
-    if(!ptr)
+    ptr = malloc(size + ALIGN);
+    if (!ptr)
         return ptr;
-    diff= ((-(long)ptr - 1)&(ALIGN-1)) + 1;
-    ptr = (char*)ptr + diff;
-    ((char*)ptr)[-1]= diff;
+    diff              = ((-(long)ptr - 1)&(ALIGN - 1)) + 1;
+    ptr               = (char *)ptr + diff;
+    ((char *)ptr)[-1] = diff;
 #elif HAVE_POSIX_MEMALIGN
     if (size) //OS X on SDK 10.6 has a broken posix_memalign implementation
-    if (posix_memalign(&ptr,ALIGN,size))
+    if (posix_memalign(&ptr, ALIGN, size))
         ptr = NULL;
 #elif HAVE_ALIGNED_MALLOC
     ptr = _aligned_malloc(size, ALIGN);
 #elif HAVE_MEMALIGN
-    ptr = memalign(ALIGN,size);
+    ptr = memalign(ALIGN, size);
     /* Why 64?
-       Indeed, we should align it:
-         on 4 for 386
-         on 16 for 486
-         on 32 for 586, PPro - K6-III
-         on 64 for K7 (maybe for P3 too).
-       Because L1 and L2 caches are aligned on those values.
-       But I don't want to code such logic here!
+     * Indeed, we should align it:
+     *   on  4 for 386
+     *   on 16 for 486
+     *   on 32 for 586, PPro - K6-III
+     *   on 64 for K7 (maybe for P3 too).
+     * Because L1 and L2 caches are aligned on those values.
+     * But I don't want to code such logic here!
      */
-     /* Why 32?
-        For AVX ASM. SSE / NEON needs only 16.
-        Why not larger? Because I did not see a difference in benchmarks ...
+    /* Why 32?
+     * For AVX ASM. SSE / NEON needs only 16.
+     * Why not larger? Because I did not see a difference in benchmarks ...
      */
-     /* benchmarks with P3
-        memalign(64)+1          3071,3051,3032
-        memalign(64)+2          3051,3032,3041
-        memalign(64)+4          2911,2896,2915
-        memalign(64)+8          2545,2554,2550
-        memalign(64)+16         2543,2572,2563
-        memalign(64)+32         2546,2545,2571
-        memalign(64)+64         2570,2533,2558
-
-        BTW, malloc seems to do 8-byte alignment by default here.
+    /* benchmarks with P3
+     * memalign(64) + 1          3071, 3051, 3032
+     * memalign(64) + 2          3051, 3032, 3041
+     * memalign(64) + 4          2911, 2896, 2915
+     * memalign(64) + 8          2545, 2554, 2550
+     * memalign(64) + 16         2543, 2572, 2563
+     * memalign(64) + 32         2546, 2545, 2571
+     * memalign(64) + 64         2570, 2533, 2558
+     *
+     * BTW, malloc seems to do 8-byte alignment by default here.
      */
 #else
     ptr = malloc(size);
@@ -143,15 +145,17 @@
 #endif
 
     /* let's disallow possible ambiguous cases */
-    if (size > (max_alloc_size-32))
+    if (size > (max_alloc_size - 32))
         return NULL;
 
 #if CONFIG_MEMALIGN_HACK
     //FIXME this isn't aligned correctly, though it probably isn't needed
-    if(!ptr) return av_malloc(size);
-    diff= ((char*)ptr)[-1];
-    ptr= realloc((char*)ptr - diff, size + diff);
-    if(ptr) ptr = (char*)ptr + diff;
+    if (!ptr)
+        return av_malloc(size);
+    diff = ((char *)ptr)[-1];
+    ptr = realloc((char *)ptr - diff, size + diff);
+    if (ptr)
+        ptr = (char *)ptr + diff;
     return ptr;
 #elif HAVE_ALIGNED_MALLOC
     return _aligned_realloc(ptr, size + !size, ALIGN);
@@ -179,7 +183,7 @@
 {
 #if CONFIG_MEMALIGN_HACK
     if (ptr)
-        free((char*)ptr - ((char*)ptr)[-1]);
+        free((char *)ptr - ((char *)ptr)[-1]);
 #elif HAVE_ALIGNED_MALLOC
     _aligned_free(ptr);
 #else
@@ -189,7 +193,7 @@
 
 void av_freep(void *arg)
 {
-    void **ptr= (void**)arg;
+    void **ptr = (void **)arg;
     av_free(*ptr);
     *ptr = NULL;
 }
@@ -211,8 +215,8 @@
 
 char *av_strdup(const char *s)
 {
-    char *ptr= NULL;
-    if(s){
+    char *ptr = NULL;
+    if (s) {
         int len = strlen(s) + 1;
         ptr = av_malloc(len);
         if (ptr)
@@ -242,3 +246,124 @@
     *nb_ptr = nb;
 }
 
+static void fill16(uint8_t *dst, int len)
+{
+    uint32_t v = AV_RN16(dst - 2);
+
+    v |= v << 16;
+
+    while (len >= 4) {
+        AV_WN32(dst, v);
+        dst += 4;
+        len -= 4;
+    }
+
+    while (len--) {
+        *dst = dst[-2];
+        dst++;
+    }
+}
+
+static void fill24(uint8_t *dst, int len)
+{
+#if HAVE_BIGENDIAN
+    uint32_t v = AV_RB24(dst - 3);
+    uint32_t a = v << 8  | v >> 16;
+    uint32_t b = v << 16 | v >> 8;
+    uint32_t c = v << 24 | v;
+#else
+    uint32_t v = AV_RL24(dst - 3);
+    uint32_t a = v       | v << 24;
+    uint32_t b = v >> 8  | v << 16;
+    uint32_t c = v >> 16 | v << 8;
+#endif
+
+    while (len >= 12) {
+        AV_WN32(dst,     a);
+        AV_WN32(dst + 4, b);
+        AV_WN32(dst + 8, c);
+        dst += 12;
+        len -= 12;
+    }
+
+    if (len >= 4) {
+        AV_WN32(dst, a);
+        dst += 4;
+        len -= 4;
+    }
+
+    if (len >= 4) {
+        AV_WN32(dst, b);
+        dst += 4;
+        len -= 4;
+    }
+
+    while (len--) {
+        *dst = dst[-3];
+        dst++;
+    }
+}
+
+static void fill32(uint8_t *dst, int len)
+{
+    uint32_t v = AV_RN32(dst - 4);
+
+    while (len >= 4) {
+        AV_WN32(dst, v);
+        dst += 4;
+        len -= 4;
+    }
+
+    while (len--) {
+        *dst = dst[-4];
+        dst++;
+    }
+}
+
+void av_memcpy_backptr(uint8_t *dst, int back, int cnt)
+{
+    const uint8_t *src = &dst[-back];
+    if (back <= 1) {
+        memset(dst, *src, cnt);
+    } else if (back == 2) {
+        fill16(dst, cnt);
+    } else if (back == 3) {
+        fill24(dst, cnt);
+    } else if (back == 4) {
+        fill32(dst, cnt);
+    } else {
+        if (cnt >= 16) {
+            int blocklen = back;
+            while (cnt > blocklen) {
+                memcpy(dst, src, blocklen);
+                dst       += blocklen;
+                cnt       -= blocklen;
+                blocklen <<= 1;
+            }
+            memcpy(dst, src, cnt);
+            return;
+        }
+        if (cnt >= 8) {
+            AV_COPY32U(dst,     src);
+            AV_COPY32U(dst + 4, src + 4);
+            src += 8;
+            dst += 8;
+            cnt -= 8;
+        }
+        if (cnt >= 4) {
+            AV_COPY32U(dst, src);
+            src += 4;
+            dst += 4;
+            cnt -= 4;
+        }
+        if (cnt >= 2) {
+            AV_COPY16U(dst, src);
+            src += 2;
+            dst += 2;
+            cnt -= 2;
+        }
+        if (cnt)
+            *dst = *src;
+    }
+}
+
diff --git a/libavutil/mem.h b/libavutil/mem.h
index 212dbf1..ced9453 100644
--- a/libavutil/mem.h
+++ b/libavutil/mem.h
@@ -27,6 +27,7 @@
 #define AVUTIL_MEM_H
 
 #include <limits.h>
+#include <stdint.h>
 
 #include "attributes.h"
 #include "error.h"
@@ -90,7 +91,7 @@
  * be allocated.
  * @see av_malloc()
  */
-av_alloc_size(1,2) static inline void *av_malloc_array(size_t nmemb, size_t size)
+av_alloc_size(1, 2) static inline void *av_malloc_array(size_t nmemb, size_t size)
 {
     if (size <= 0 || nmemb >= INT_MAX / size)
         return NULL;
@@ -163,7 +164,7 @@
  * @see av_mallocz()
  * @see av_malloc_array()
  */
-av_alloc_size(1,2) static inline void *av_mallocz_array(size_t nmemb, size_t size)
+av_alloc_size(1, 2) static inline void *av_mallocz_array(size_t nmemb, size_t size)
 {
     if (size <= 0 || nmemb >= INT_MAX / size)
         return NULL;
@@ -217,6 +218,17 @@
 void av_max_alloc(size_t max);
 
 /**
+ * @brief deliberately overlapping memcpy implementation
+ * @param dst destination buffer
+ * @param back how many bytes back we start (the initial size of the overlapping window), must be > 0
+ * @param cnt number of bytes to copy, must be >= 0
+ *
+ * cnt > back is valid, this will copy the bytes we just copied,
+ * thus creating a repeating pattern with a period length of back.
+ */
+void av_memcpy_backptr(uint8_t *dst, int back, int cnt);
+
+/**
  * @}
  */
 
diff --git a/libavutil/mips/Makefile b/libavutil/mips/Makefile
new file mode 100644
index 0000000..dbfa5aa
--- /dev/null
+++ b/libavutil/mips/Makefile
@@ -0,0 +1 @@
+OBJS += mips/float_dsp_mips.o
diff --git a/libavutil/mips/float_dsp_mips.c b/libavutil/mips/float_dsp_mips.c
new file mode 100644
index 0000000..8c3611d
--- /dev/null
+++ b/libavutil/mips/float_dsp_mips.c
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2012
+ *      MIPS Technologies, Inc., California.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the MIPS Technologies, Inc., nor the names of its
+ *    contributors may be used to endorse or promote products derived from
+ *    this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE MIPS TECHNOLOGIES, INC. ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE MIPS TECHNOLOGIES, INC. BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * Author:  Branimir Vasic (bvasic@mips.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
+ * Reference: libavutil/float_dsp.c
+ */
+
+#include "config.h"
+#include "libavutil/float_dsp.h"
+
+#if HAVE_INLINE_ASM && HAVE_MIPSFPU
+static void vector_fmul_mips(float *dst, const float *src0, const float *src1,
+                             int len)
+{
+    int i;
+
+    if (len & 3) {
+        for (i = 0; i < len; i++)
+            dst[i] = src0[i] * src1[i];
+    } else {
+        float *d     = (float *)dst;
+        float *d_end = d + len;
+        float *s0    = (float *)src0;
+        float *s1    = (float *)src1;
+
+        float src0_0, src0_1, src0_2, src0_3;
+        float src1_0, src1_1, src1_2, src1_3;
+
+        __asm__ volatile (
+            "1:                                         \n\t"
+            "lwc1   %[src0_0],  0(%[s0])                \n\t"
+            "lwc1   %[src1_0],  0(%[s1])                \n\t"
+            "lwc1   %[src0_1],  4(%[s0])                \n\t"
+            "lwc1   %[src1_1],  4(%[s1])                \n\t"
+            "lwc1   %[src0_2],  8(%[s0])                \n\t"
+            "lwc1   %[src1_2],  8(%[s1])                \n\t"
+            "lwc1   %[src0_3],  12(%[s0])               \n\t"
+            "lwc1   %[src1_3],  12(%[s1])               \n\t"
+            "mul.s  %[src0_0],  %[src0_0],  %[src1_0]   \n\t"
+            "mul.s  %[src0_1],  %[src0_1],  %[src1_1]   \n\t"
+            "mul.s  %[src0_2],  %[src0_2],  %[src1_2]   \n\t"
+            "mul.s  %[src0_3],  %[src0_3],  %[src1_3]   \n\t"
+            "swc1   %[src0_0],  0(%[d])                 \n\t"
+            "swc1   %[src0_1],  4(%[d])                 \n\t"
+            "swc1   %[src0_2],  8(%[d])                 \n\t"
+            "swc1   %[src0_3],  12(%[d])                \n\t"
+            "addiu  %[s0],      %[s0],      16          \n\t"
+            "addiu  %[s1],      %[s1],      16          \n\t"
+            "addiu  %[d],       %[d],       16          \n\t"
+            "bne    %[d],       %[d_end],   1b          \n\t"
+
+            : [src0_0]"=&f"(src0_0), [src0_1]"=&f"(src0_1),
+              [src0_2]"=&f"(src0_2), [src0_3]"=&f"(src0_3),
+              [src1_0]"=&f"(src1_0), [src1_1]"=&f"(src1_1),
+              [src1_2]"=&f"(src1_2), [src1_3]"=&f"(src1_3),
+              [d]"+r"(d), [s0]"+r"(s0), [s1]"+r"(s1)
+            : [d_end]"r"(d_end)
+            : "memory"
+        );
+    }
+}
+#endif /* HAVE_INLINE_ASM && HAVE_MIPSFPU */
+
+void ff_float_dsp_init_mips(AVFloatDSPContext *fdsp) {
+#if HAVE_INLINE_ASM && HAVE_MIPSFPU
+    fdsp->vector_fmul = vector_fmul_mips;
+#endif /* HAVE_INLINE_ASM && HAVE_MIPSFPU */
+}
diff --git a/libavutil/old_pix_fmts.h b/libavutil/old_pix_fmts.h
new file mode 100644
index 0000000..57b6992
--- /dev/null
+++ b/libavutil/old_pix_fmts.h
@@ -0,0 +1,171 @@
+/*
+ * copyright (c) 2006-2012 Michael Niedermayer <michaelni@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
+ */
+
+#ifndef AVUTIL_OLD_PIX_FMTS_H
+#define AVUTIL_OLD_PIX_FMTS_H
+
+/*
+ * This header exists to prevent new pixel formats from being accidentally added
+ * to the deprecated list.
+ * Do not include it directly. It will be removed on next major bump
+ *
+ * Do not add new items to this list. Use the AVPixelFormat enum instead.
+ */
+    PIX_FMT_NONE = AV_PIX_FMT_NONE,
+    PIX_FMT_YUV420P,   ///< planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
+    PIX_FMT_YUYV422,   ///< packed YUV 4:2:2, 16bpp, Y0 Cb Y1 Cr
+    PIX_FMT_RGB24,     ///< packed RGB 8:8:8, 24bpp, RGBRGB...
+    PIX_FMT_BGR24,     ///< packed RGB 8:8:8, 24bpp, BGRBGR...
+    PIX_FMT_YUV422P,   ///< planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
+    PIX_FMT_YUV444P,   ///< planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
+    PIX_FMT_YUV410P,   ///< planar YUV 4:1:0,  9bpp, (1 Cr & Cb sample per 4x4 Y samples)
+    PIX_FMT_YUV411P,   ///< planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples)
+    PIX_FMT_GRAY8,     ///<        Y        ,  8bpp
+    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), 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
+    PIX_FMT_UYYVYY411, ///< packed YUV 4:1:1, 12bpp, Cb Y0 Y1 Cr Y2 Y3
+    PIX_FMT_BGR8,      ///< packed RGB 3:3:2,  8bpp, (msb)2B 3G 3R(lsb)
+    PIX_FMT_BGR4,      ///< packed RGB 1:2:1 bitstream,  4bpp, (msb)1B 2G 1R(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits
+    PIX_FMT_BGR4_BYTE, ///< packed RGB 1:2:1,  8bpp, (msb)1B 2G 1R(lsb)
+    PIX_FMT_RGB8,      ///< packed RGB 3:3:2,  8bpp, (msb)2R 3G 3B(lsb)
+    PIX_FMT_RGB4,      ///< packed RGB 1:2:1 bitstream,  4bpp, (msb)1R 2G 1B(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits
+    PIX_FMT_RGB4_BYTE, ///< packed RGB 1:2:1,  8bpp, (msb)1R 2G 1B(lsb)
+    PIX_FMT_NV12,      ///< planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (first byte U and the following byte V)
+    PIX_FMT_NV21,      ///< as above, but U and V bytes are swapped
+
+    PIX_FMT_ARGB,      ///< packed ARGB 8:8:8:8, 32bpp, ARGBARGB...
+    PIX_FMT_RGBA,      ///< packed RGBA 8:8:8:8, 32bpp, RGBARGBA...
+    PIX_FMT_ABGR,      ///< packed ABGR 8:8:8:8, 32bpp, ABGRABGR...
+    PIX_FMT_BGRA,      ///< packed BGRA 8:8:8:8, 32bpp, BGRABGRA...
+
+    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), 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
+    PIX_FMT_VDPAU_MPEG2,///< MPEG-2 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_WMV3,///< WMV3 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_VC1, ///< VC-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
+    PIX_FMT_RGB48BE,   ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as big-endian
+    PIX_FMT_RGB48LE,   ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as little-endian
+
+    PIX_FMT_RGB565BE,  ///< packed RGB 5:6:5, 16bpp, (msb)   5R 6G 5B(lsb), big-endian
+    PIX_FMT_RGB565LE,  ///< packed RGB 5:6:5, 16bpp, (msb)   5R 6G 5B(lsb), little-endian
+    PIX_FMT_RGB555BE,  ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), big-endian, most significant bit to 0
+    PIX_FMT_RGB555LE,  ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), little-endian, most significant bit to 0
+
+    PIX_FMT_BGR565BE,  ///< packed BGR 5:6:5, 16bpp, (msb)   5B 6G 5R(lsb), big-endian
+    PIX_FMT_BGR565LE,  ///< packed BGR 5:6:5, 16bpp, (msb)   5B 6G 5R(lsb), little-endian
+    PIX_FMT_BGR555BE,  ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), big-endian, most significant bit to 1
+    PIX_FMT_BGR555LE,  ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), little-endian, most significant bit to 1
+
+    PIX_FMT_VAAPI_MOCO, ///< HW acceleration through VA API at motion compensation entry-point, Picture.data[3] contains a vaapi_render_state struct which contains macroblocks as well as various fields extracted from headers
+    PIX_FMT_VAAPI_IDCT, ///< HW acceleration through VA API at IDCT entry-point, Picture.data[3] contains a vaapi_render_state struct which contains fields extracted from headers
+    PIX_FMT_VAAPI_VLD,  ///< HW decoding through VA API, Picture.data[3] contains a vaapi_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+
+    PIX_FMT_YUV420P16LE,  ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    PIX_FMT_YUV420P16BE,  ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    PIX_FMT_YUV422P16LE,  ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    PIX_FMT_YUV422P16BE,  ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    PIX_FMT_YUV444P16LE,  ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    PIX_FMT_YUV444P16BE,  ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    PIX_FMT_VDPAU_MPEG4,  ///< MPEG4 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_DXVA2_VLD,    ///< HW decoding through DXVA2, Picture.data[3] contains a LPDIRECT3DSURFACE9 pointer
+
+    PIX_FMT_RGB444LE,  ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), little-endian, most significant bits to 0
+    PIX_FMT_RGB444BE,  ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), big-endian, most significant bits to 0
+    PIX_FMT_BGR444LE,  ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), little-endian, most significant bits to 1
+    PIX_FMT_BGR444BE,  ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), big-endian, most significant bits to 1
+    PIX_FMT_GRAY8A,    ///< 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
+
+    //the following 10 formats have the disadvantage of needing 1 format for each bit depth, thus
+    //If you want to support multiple bit depths, then using PIX_FMT_YUV420P16* with the bpp stored separately
+    //is better
+    PIX_FMT_YUV420P9BE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    PIX_FMT_YUV420P9LE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    PIX_FMT_YUV420P10BE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    PIX_FMT_YUV420P10LE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    PIX_FMT_YUV422P10BE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    PIX_FMT_YUV422P10LE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    PIX_FMT_YUV444P9BE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    PIX_FMT_YUV444P9LE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    PIX_FMT_YUV444P10BE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    PIX_FMT_YUV444P10LE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    PIX_FMT_YUV422P9BE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    PIX_FMT_YUV422P9LE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    PIX_FMT_VDA_VLD,    ///< hardware decoding through VDA
+
+#ifdef AV_PIX_FMT_ABI_GIT_MASTER
+    PIX_FMT_RGBA64BE,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
+    PIX_FMT_RGBA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
+    PIX_FMT_BGRA64BE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
+    PIX_FMT_BGRA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
+#endif
+    PIX_FMT_GBRP,      ///< planar GBR 4:4:4 24bpp
+    PIX_FMT_GBRP9BE,   ///< planar GBR 4:4:4 27bpp, big endian
+    PIX_FMT_GBRP9LE,   ///< planar GBR 4:4:4 27bpp, little endian
+    PIX_FMT_GBRP10BE,  ///< planar GBR 4:4:4 30bpp, big endian
+    PIX_FMT_GBRP10LE,  ///< planar GBR 4:4:4 30bpp, little endian
+    PIX_FMT_GBRP16BE,  ///< planar GBR 4:4:4 48bpp, big endian
+    PIX_FMT_GBRP16LE,  ///< planar GBR 4:4:4 48bpp, little endian
+
+#ifndef AV_PIX_FMT_ABI_GIT_MASTER
+    PIX_FMT_RGBA64BE=0x123,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
+    PIX_FMT_RGBA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
+    PIX_FMT_BGRA64BE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
+    PIX_FMT_BGRA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
+#endif
+    PIX_FMT_0RGB=0x123+4,      ///< packed RGB 8:8:8, 32bpp, 0RGB0RGB...
+    PIX_FMT_RGB0,      ///< packed RGB 8:8:8, 32bpp, RGB0RGB0...
+    PIX_FMT_0BGR,      ///< packed BGR 8:8:8, 32bpp, 0BGR0BGR...
+    PIX_FMT_BGR0,      ///< packed BGR 8:8:8, 32bpp, BGR0BGR0...
+    PIX_FMT_YUVA444P,  ///< planar YUV 4:4:4 32bpp, (1 Cr & Cb sample per 1x1 Y & A samples)
+    PIX_FMT_YUVA422P,  ///< planar YUV 4:2:2 24bpp, (1 Cr & Cb sample per 2x1 Y & A samples)
+
+    PIX_FMT_YUV420P12BE, ///< planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    PIX_FMT_YUV420P12LE, ///< planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    PIX_FMT_YUV420P14BE, ///< planar YUV 4:2:0,21bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    PIX_FMT_YUV420P14LE, ///< planar YUV 4:2:0,21bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    PIX_FMT_YUV422P12BE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    PIX_FMT_YUV422P12LE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    PIX_FMT_YUV422P14BE, ///< planar YUV 4:2:2,28bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    PIX_FMT_YUV422P14LE, ///< planar YUV 4:2:2,28bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    PIX_FMT_YUV444P12BE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    PIX_FMT_YUV444P12LE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    PIX_FMT_YUV444P14BE, ///< planar YUV 4:4:4,42bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    PIX_FMT_YUV444P14LE, ///< planar YUV 4:4:4,42bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    PIX_FMT_GBRP12BE,    ///< planar GBR 4:4:4 36bpp, big endian
+    PIX_FMT_GBRP12LE,    ///< planar GBR 4:4:4 36bpp, little endian
+    PIX_FMT_GBRP14BE,    ///< planar GBR 4:4:4 42bpp, big endian
+    PIX_FMT_GBRP14LE,    ///< planar GBR 4:4:4 42bpp, 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
+#endif /* AVUTIL_OLD_PIX_FMTS_H */
diff --git a/libavutil/opt.c b/libavutil/opt.c
index a10135b..0ff45c8 100644
--- a/libavutil/opt.c
+++ b/libavutil/opt.c
@@ -35,6 +35,7 @@
 #include "parseutils.h"
 #include "pixdesc.h"
 #include "mathematics.h"
+#include "samplefmt.h"
 
 #if FF_API_FIND_OPT
 //FIXME order them and do a bin search
@@ -70,6 +71,8 @@
 {
     switch (o->type) {
     case AV_OPT_TYPE_FLAGS:     *intnum = *(unsigned int*)dst;return 0;
+    case AV_OPT_TYPE_PIXEL_FMT:
+    case AV_OPT_TYPE_SAMPLE_FMT:
     case AV_OPT_TYPE_INT:       *intnum = *(int         *)dst;return 0;
     case AV_OPT_TYPE_INT64:     *intnum = *(int64_t     *)dst;return 0;
     case AV_OPT_TYPE_FLOAT:     *num    = *(float       *)dst;return 0;
@@ -85,13 +88,15 @@
 static int write_number(void *obj, const AVOption *o, void *dst, double num, int den, int64_t intnum)
 {
     if (o->max*den < num*intnum || o->min*den > num*intnum) {
-        av_log(obj, AV_LOG_ERROR, "Value %f for parameter '%s' out of range\n",
-               num*intnum/den, o->name);
+        av_log(obj, AV_LOG_ERROR, "Value %f for parameter '%s' out of range [%g - %g]\n",
+               num*intnum/den, o->name, o->min, o->max);
         return AVERROR(ERANGE);
     }
 
     switch (o->type) {
     case AV_OPT_TYPE_FLAGS:
+    case AV_OPT_TYPE_PIXEL_FMT:
+    case AV_OPT_TYPE_SAMPLE_FMT:
     case AV_OPT_TYPE_INT:   *(int       *)dst= llrint(num/den)*intnum; break;
     case AV_OPT_TYPE_INT64: *(int64_t   *)dst= llrint(num/den)*intnum; break;
     case AV_OPT_TYPE_FLOAT: *(float     *)dst= num*intnum/den;         break;
@@ -241,7 +246,9 @@
     const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
     if (!o || !target_obj)
         return AVERROR_OPTION_NOT_FOUND;
-    if (!val && (o->type != AV_OPT_TYPE_STRING && o->type != AV_OPT_TYPE_PIXEL_FMT && o->type != AV_OPT_TYPE_IMAGE_SIZE))
+    if (!val && (o->type != AV_OPT_TYPE_STRING &&
+                 o->type != AV_OPT_TYPE_PIXEL_FMT && o->type != AV_OPT_TYPE_SAMPLE_FMT &&
+                 o->type != AV_OPT_TYPE_IMAGE_SIZE))
         return AVERROR(EINVAL);
 
     dst = ((uint8_t*)target_obj) + o->offset;
@@ -264,20 +271,36 @@
             av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as image size\n", val);
         return ret;
     case AV_OPT_TYPE_PIXEL_FMT:
-        if (!val || !strcmp(val, "none"))
-            ret = PIX_FMT_NONE;
-        else {
+        if (!val || !strcmp(val, "none")) {
+            ret = AV_PIX_FMT_NONE;
+        } else {
             ret = av_get_pix_fmt(val);
-            if (ret == PIX_FMT_NONE) {
+            if (ret == AV_PIX_FMT_NONE) {
                 char *tail;
                 ret = strtol(val, &tail, 0);
-                if (*tail || (unsigned)ret >= PIX_FMT_NB) {
+                if (*tail || (unsigned)ret >= AV_PIX_FMT_NB) {
                     av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as pixel format\n", val);
                     return AVERROR(EINVAL);
                 }
             }
         }
-        *(enum PixelFormat *)dst = ret;
+        *(enum AVPixelFormat *)dst = ret;
+        return 0;
+    case AV_OPT_TYPE_SAMPLE_FMT:
+        if (!val || !strcmp(val, "none")) {
+            ret = AV_SAMPLE_FMT_NONE;
+        } else {
+            ret = av_get_sample_fmt(val);
+            if (ret == AV_SAMPLE_FMT_NONE) {
+                char *tail;
+                ret = strtol(val, &tail, 0);
+                if (*tail || (unsigned)ret >= AV_SAMPLE_FMT_NB) {
+                    av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as sample format\n", val);
+                    return AVERROR(EINVAL);
+                }
+            }
+        }
+        *(enum AVSampleFormat *)dst = ret;
         return 0;
     }
 
@@ -383,6 +406,75 @@
     return 0;
 }
 
+int av_opt_set_image_size(void *obj, const char *name, int w, int h, int search_flags)
+{
+    void *target_obj;
+    const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
+
+    if (!o || !target_obj)
+        return AVERROR_OPTION_NOT_FOUND;
+    if (o->type != AV_OPT_TYPE_IMAGE_SIZE) {
+        av_log(obj, AV_LOG_ERROR,
+               "The value set by option '%s' is not an image size.\n", o->name);
+        return AVERROR(EINVAL);
+    }
+    if (w<0 || h<0) {
+        av_log(obj, AV_LOG_ERROR,
+               "Invalid negative size value %dx%d for size '%s'\n", w, h, o->name);
+        return AVERROR(EINVAL);
+    }
+    *(int *)(((uint8_t *)target_obj)             + o->offset) = w;
+    *(int *)(((uint8_t *)target_obj+sizeof(int)) + o->offset) = h;
+    return 0;
+}
+
+static int set_format(void *obj, const char *name, int fmt, int search_flags,
+                      enum AVOptionType type, const char *desc, int nb_fmts)
+{
+    void *target_obj;
+    const AVOption *o = av_opt_find2(obj, name, NULL, 0,
+                                     search_flags, &target_obj);
+    int min, max;
+    const AVClass *class = *(AVClass **)obj;
+
+    if (!o || !target_obj)
+        return AVERROR_OPTION_NOT_FOUND;
+    if (o->type != type) {
+        av_log(obj, AV_LOG_ERROR,
+               "The value set by option '%s' is not a %s format", name, desc);
+        return AVERROR(EINVAL);
+    }
+
+#if LIBAVUTIL_VERSION_MAJOR < 53
+    if (class->version && class->version < AV_VERSION_INT(52, 11, 100)) {
+        min = -1;
+        max = nb_fmts-1;
+    } else
+#endif
+    {
+        min = FFMIN(o->min, -1);
+        max = FFMAX(o->max, nb_fmts-1);
+    }
+    if (fmt < min || fmt > max) {
+        av_log(obj, AV_LOG_ERROR,
+               "Value %d for parameter '%s' out of %s format range [%d - %d]\n",
+               fmt, name, desc, min, max);
+        return AVERROR(ERANGE);
+    }
+    *(int *)(((uint8_t *)target_obj) + o->offset) = fmt;
+    return 0;
+}
+
+int av_opt_set_pixel_fmt(void *obj, const char *name, enum AVPixelFormat fmt, int search_flags)
+{
+    return set_format(obj, name, fmt, search_flags, AV_OPT_TYPE_PIXEL_FMT, "pixel", AV_PIX_FMT_NB);
+}
+
+int av_opt_set_sample_fmt(void *obj, const char *name, enum AVSampleFormat fmt, int search_flags)
+{
+    return set_format(obj, name, fmt, search_flags, AV_OPT_TYPE_SAMPLE_FMT, "sample", AV_SAMPLE_FMT_NB);
+}
+
 #if FF_API_OLD_AVOPTIONS
 /**
  *
@@ -465,7 +557,10 @@
         ret = snprintf(buf, sizeof(buf), "%dx%d", ((int *)dst)[0], ((int *)dst)[1]);
         break;
     case AV_OPT_TYPE_PIXEL_FMT:
-        ret = snprintf(buf, sizeof(buf), "%s", (char *)av_x_if_null(av_get_pix_fmt_name(*(enum PixelFormat *)dst), "none"));
+        ret = snprintf(buf, sizeof(buf), "%s", (char *)av_x_if_null(av_get_pix_fmt_name(*(enum AVPixelFormat *)dst), "none"));
+        break;
+    case AV_OPT_TYPE_SAMPLE_FMT:
+        ret = snprintf(buf, sizeof(buf), "%s", (char *)av_x_if_null(av_get_sample_fmt_name(*(enum AVSampleFormat *)dst), "none"));
         break;
     default:
         return AVERROR(EINVAL);
@@ -574,6 +669,52 @@
     return 0;
 }
 
+int av_opt_get_image_size(void *obj, const char *name, int search_flags, int *w_out, int *h_out)
+{
+    void *dst, *target_obj;
+    const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
+    if (!o || !target_obj)
+        return AVERROR_OPTION_NOT_FOUND;
+    if (o->type != AV_OPT_TYPE_IMAGE_SIZE) {
+        av_log(obj, AV_LOG_ERROR,
+               "The value for option '%s' is not an image size.\n", name);
+        return AVERROR(EINVAL);
+    }
+
+    dst = ((uint8_t*)target_obj) + o->offset;
+    if (w_out) *w_out = *(int *)dst;
+    if (h_out) *h_out = *((int *)dst+1);
+    return 0;
+}
+
+static int get_format(void *obj, const char *name, int search_flags, int *out_fmt,
+                      enum AVOptionType type, const char *desc)
+{
+    void *dst, *target_obj;
+    const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
+    if (!o || !target_obj)
+        return AVERROR_OPTION_NOT_FOUND;
+    if (o->type != type) {
+        av_log(obj, AV_LOG_ERROR,
+               "The value for option '%s' is not a %s format.\n", desc, name);
+        return AVERROR(EINVAL);
+    }
+
+    dst = ((uint8_t*)target_obj) + o->offset;
+    *out_fmt = *(int *)dst;
+    return 0;
+}
+
+int av_opt_get_pixel_fmt(void *obj, const char *name, int search_flags, enum AVPixelFormat *out_fmt)
+{
+    return get_format(obj, name, search_flags, out_fmt, AV_OPT_TYPE_PIXEL_FMT, "pixel");
+}
+
+int av_opt_get_sample_fmt(void *obj, const char *name, int search_flags, enum AVSampleFormat *out_fmt)
+{
+    return get_format(obj, name, search_flags, out_fmt, AV_OPT_TYPE_SAMPLE_FMT, "sample");
+}
+
 int av_opt_flag_is_set(void *obj, const char *field_name, const char *flag_name)
 {
     const AVOption *field = av_opt_find(obj, field_name, NULL, 0, 0);
@@ -642,6 +783,9 @@
             case AV_OPT_TYPE_PIXEL_FMT:
                 av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<pix_fmt>");
                 break;
+            case AV_OPT_TYPE_SAMPLE_FMT:
+                av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<sample_fmt>");
+                break;
             case AV_OPT_TYPE_CONST:
             default:
                 av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "");
@@ -684,6 +828,7 @@
 void av_opt_set_defaults2(void *s, int mask, int flags)
 {
 #endif
+    const AVClass *class = *(AVClass **)s;
     const AVOption *opt = NULL;
     while ((opt = av_opt_next(s, opt)) != NULL) {
 #if FF_API_OLD_AVOPTIONS
@@ -714,9 +859,24 @@
             break;
             case AV_OPT_TYPE_STRING:
             case AV_OPT_TYPE_IMAGE_SIZE:
-            case AV_OPT_TYPE_PIXEL_FMT:
                 av_opt_set(s, opt->name, opt->default_val.str, 0);
                 break;
+            case AV_OPT_TYPE_PIXEL_FMT:
+#if LIBAVUTIL_VERSION_MAJOR < 53
+                if (class->version && class->version < AV_VERSION_INT(52, 10, 100))
+                    av_opt_set(s, opt->name, opt->default_val.str, 0);
+                else
+#endif
+                    av_opt_set_pixel_fmt(s, opt->name, opt->default_val.i64, 0);
+                break;
+            case AV_OPT_TYPE_SAMPLE_FMT:
+#if LIBAVUTIL_VERSION_MAJOR < 53
+                if (class->version && class->version < AV_VERSION_INT(52, 10, 100))
+                    av_opt_set(s, opt->name, opt->default_val.str, 0);
+                else
+#endif
+                    av_opt_set_sample_fmt(s, opt->name, opt->default_val.i64, 0);
+                break;
             case AV_OPT_TYPE_BINARY:
                 /* Cannot set default for binary */
             break;
@@ -803,42 +963,60 @@
  * Read a key from a string.
  *
  * The key consists of is_key_char characters and must be terminated by a
- * character from the delim string; spaces are ignored. The key buffer must
- * be 4 bytes larger than the longest acceptable key. If the key is too
- * long, an ellipsis will be written at the end.
+ * character from the delim string; spaces are ignored.
  *
  * @return  0 for success (even with ellipsis), <0 for failure
  */
-static int get_key(const char **ropts, const char *delim, char *key, unsigned key_size)
+static int get_key(const char **ropts, const char *delim, char **rkey)
 {
-    unsigned key_pos = 0;
     const char *opts = *ropts;
+    const char *key_start, *key_end;
 
-    opts += strspn(opts, WHITESPACES);
-    while (is_key_char(*opts)) {
-        key[key_pos++] = *opts;
-        if (key_pos == key_size)
-            key_pos--;
-        (opts)++;
-    }
+    key_start = opts += strspn(opts, WHITESPACES);
+    while (is_key_char(*opts))
+        opts++;
+    key_end = opts;
     opts += strspn(opts, WHITESPACES);
     if (!*opts || !strchr(delim, *opts))
         return AVERROR(EINVAL);
     opts++;
-    key[key_pos++] = 0;
-    if (key_pos == key_size)
-        key[key_pos - 4] = key[key_pos - 3] = key[key_pos - 2] = '.';
+    if (!(*rkey = av_malloc(key_end - key_start + 1)))
+        return AVERROR(ENOMEM);
+    memcpy(*rkey, key_start, key_end - key_start);
+    (*rkey)[key_end - key_start] = 0;
     *ropts = opts;
     return 0;
 }
 
+int av_opt_get_key_value(const char **ropts,
+                         const char *key_val_sep, const char *pairs_sep,
+                         unsigned flags,
+                         char **rkey, char **rval)
+{
+    int ret;
+    char *key = NULL, *val;
+    const char *opts = *ropts;
+
+    if ((ret = get_key(&opts, key_val_sep, &key)) < 0 &&
+        !(flags & AV_OPT_FLAG_IMPLICIT_KEY))
+        return AVERROR(EINVAL);
+    if (!(val = av_get_token(&opts, pairs_sep))) {
+        av_free(key);
+        return AVERROR(ENOMEM);
+    }
+    *ropts = opts;
+    *rkey  = key;
+    *rval  = val;
+    return 0;
+}
+
 int av_opt_set_from_string(void *ctx, const char *opts,
                            const char *const *shorthand,
                            const char *key_val_sep, const char *pairs_sep)
 {
     int ret, count = 0;
     const char *dummy_shorthand = NULL;
-    char key_buf[68], *value;
+    char *av_uninit(parsed_key), *av_uninit(value);
     const char *key;
 
     if (!opts)
@@ -847,32 +1025,38 @@
         shorthand = &dummy_shorthand;
 
     while (*opts) {
-        if ((ret = get_key(&opts, key_val_sep, key_buf, sizeof(key_buf))) < 0) {
-            if (*shorthand) {
-                key = *(shorthand++);
-            } else {
+        ret = av_opt_get_key_value(&opts, key_val_sep, pairs_sep,
+                                   *shorthand ? AV_OPT_FLAG_IMPLICIT_KEY : 0,
+                                   &parsed_key, &value);
+        if (ret < 0) {
+            if (ret == AVERROR(EINVAL))
                 av_log(ctx, AV_LOG_ERROR, "No option name near '%s'\n", opts);
-                return AVERROR(EINVAL);
-            }
-        } else {
-            key = key_buf;
+            else
+                av_log(ctx, AV_LOG_ERROR, "Unable to parse '%s': %s\n", opts,
+                       av_err2str(ret));
+            return ret;
+        }
+        if (*opts)
+            opts++;
+        if (parsed_key) {
+            key = parsed_key;
             while (*shorthand) /* discard all remaining shorthand */
                 shorthand++;
+        } else {
+            key = *(shorthand++);
         }
 
-        if (!(value = av_get_token(&opts, pairs_sep)))
-            return AVERROR(ENOMEM);
-        if (*opts && strchr(pairs_sep, *opts))
-            opts++;
-
         av_log(ctx, AV_LOG_DEBUG, "Setting '%s' to value '%s'\n", key, value);
         if ((ret = av_opt_set(ctx, key, value, 0)) < 0) {
             if (ret == AVERROR_OPTION_NOT_FOUND)
                 av_log(ctx, AV_LOG_ERROR, "Option '%s' not found\n", key);
+            av_free(value);
+            av_free(parsed_key);
             return ret;
         }
 
         av_free(value);
+        av_free(parsed_key);
         count++;
     }
     return count;
@@ -990,7 +1174,8 @@
     int flags;
     AVRational rational;
     int w, h;
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
+    enum AVSampleFormat sample_fmt;
 } TestContext;
 
 #define OFFSET(x) offsetof(TestContext, x)
@@ -1009,7 +1194,8 @@
 {"lame",     "set lame flag ", 0,                AV_OPT_TYPE_CONST,    {.i64 = TEST_FLAG_LAME}, INT_MIN,  INT_MAX, 0, "flags" },
 {"mu",       "set mu flag ",   0,                AV_OPT_TYPE_CONST,    {.i64 = TEST_FLAG_MU},   INT_MIN,  INT_MAX, 0, "flags" },
 {"size",     "set size",       OFFSET(w),        AV_OPT_TYPE_IMAGE_SIZE,{0},             0,        0                   },
-{"pix_fmt",  "set pixfmt",     OFFSET(pix_fmt),  AV_OPT_TYPE_PIXEL_FMT,{0},              0,        0                   },
+{"pix_fmt",  "set pixfmt",     OFFSET(pix_fmt),  AV_OPT_TYPE_PIXEL_FMT, {.i64 = AV_PIX_FMT_NONE}, -1, AV_PIX_FMT_NB-1},
+{"sample_fmt", "set samplefmt", OFFSET(sample_fmt), AV_OPT_TYPE_SAMPLE_FMT, {.i64 = AV_SAMPLE_FMT_NONE}, -1, AV_SAMPLE_FMT_NB-1},
 {NULL},
 };
 
@@ -1057,6 +1243,9 @@
             "pix_fmt=yuv420p",
             "pix_fmt=2",
             "pix_fmt=bogus",
+            "sample_fmt=s16",
+            "sample_fmt=2",
+            "sample_fmt=bogus",
         };
 
         test_ctx.class = &test_class;
diff --git a/libavutil/opt.h b/libavutil/opt.h
index 81fefd9..bf84a9b 100644
--- a/libavutil/opt.h
+++ b/libavutil/opt.h
@@ -31,6 +31,8 @@
 #include "avutil.h"
 #include "dict.h"
 #include "log.h"
+#include "pixfmt.h"
+#include "samplefmt.h"
 
 /**
  * @defgroup avoptions AVOptions
@@ -227,6 +229,7 @@
     AV_OPT_TYPE_CONST = 128,
     AV_OPT_TYPE_IMAGE_SIZE = MKBETAG('S','I','Z','E'), ///< offset must point to two consecutive integers
     AV_OPT_TYPE_PIXEL_FMT  = MKBETAG('P','F','M','T'),
+    AV_OPT_TYPE_SAMPLE_FMT = MKBETAG('S','F','M','T'),
 #if FF_API_OLD_AVOPTIONS
     FF_OPT_TYPE_FLAGS = 0,
     FF_OPT_TYPE_INT,
@@ -438,7 +441,7 @@
  */
 int av_opt_flag_is_set(void *obj, const char *field_name, const char *flag_name);
 
-/*
+/**
  * Set all the options from a given dictionary on an object.
  *
  * @param obj a struct whose first element is a pointer to AVClass
@@ -455,6 +458,39 @@
 int av_opt_set_dict(void *obj, struct AVDictionary **options);
 
 /**
+ * Extract a key-value pair from the beginning of a string.
+ *
+ * @param ropts        pointer to the options string, will be updated to
+ *                     point to the rest of the string (one of the pairs_sep
+ *                     or the final NUL)
+ * @param key_val_sep  a 0-terminated list of characters used to separate
+ *                     key from value, for example '='
+ * @param pairs_sep    a 0-terminated list of characters used to separate
+ *                     two pairs from each other, for example ':' or ','
+ * @param flags        flags; see the AV_OPT_FLAG_* values below
+ * @param rkey         parsed key; must be freed using av_free()
+ * @param rval         parsed value; must be freed using av_free()
+ *
+ * @return  >=0 for success, or a negative value corresponding to an
+ *          AVERROR code in case of error; in particular:
+ *          AVERROR(EINVAL) if no key is present
+ *
+ */
+int av_opt_get_key_value(const char **ropts,
+                         const char *key_val_sep, const char *pairs_sep,
+                         unsigned flags,
+                         char **rkey, char **rval);
+
+enum {
+
+    /**
+     * Accept to parse a value without a key; the key will then be returned
+     * as NULL.
+     */
+    AV_OPT_FLAG_IMPLICIT_KEY = 1,
+};
+
+/**
  * @defgroup opt_eval_funcs Evaluating option strings
  * @{
  * This group of functions can be used to evaluate option strings
@@ -595,6 +631,9 @@
 int av_opt_set_double(void *obj, const char *name, double      val, int search_flags);
 int av_opt_set_q     (void *obj, const char *name, AVRational  val, int search_flags);
 int av_opt_set_bin   (void *obj, const char *name, const uint8_t *val, int size, int search_flags);
+int av_opt_set_image_size(void *obj, const char *name, int w, int h, int search_flags);
+int av_opt_set_pixel_fmt (void *obj, const char *name, enum AVPixelFormat fmt, int search_flags);
+int av_opt_set_sample_fmt(void *obj, const char *name, enum AVSampleFormat fmt, int search_flags);
 /**
  * @}
  */
@@ -618,6 +657,9 @@
 int av_opt_get_int   (void *obj, const char *name, int search_flags, int64_t    *out_val);
 int av_opt_get_double(void *obj, const char *name, int search_flags, double     *out_val);
 int av_opt_get_q     (void *obj, const char *name, int search_flags, AVRational *out_val);
+int av_opt_get_image_size(void *obj, const char *name, int search_flags, int *w_out, int *h_out);
+int av_opt_get_pixel_fmt (void *obj, const char *name, int search_flags, enum AVPixelFormat *out_fmt);
+int av_opt_get_sample_fmt(void *obj, const char *name, int search_flags, enum AVSampleFormat *out_fmt);
 /**
  * @}
  */
diff --git a/libavutil/parseutils.c b/libavutil/parseutils.c
index 6e50d70..f188e81 100644
--- a/libavutil/parseutils.c
+++ b/libavutil/parseutils.c
@@ -47,7 +47,6 @@
 {
     char c;
     int ret;
-    int64_t gcd;
 
     if (sscanf(str, "%d:%d%c", &q->num, &q->den, &c) != 2) {
         double d;
@@ -57,12 +56,8 @@
         if (ret < 0)
             return ret;
         *q = av_d2q(d, max);
-    }
-
-    gcd = av_gcd(FFABS(q->num), FFABS(q->den));
-    if (gcd) {
-        q->num /= gcd;
-        q->den /= gcd;
+    } else {
+        av_reduce(&q->num, &q->den, q->num, q->den, max);
     }
 
     return 0;
@@ -144,11 +139,14 @@
         }
     }
     if (i == n) {
-        p = str;
-        width = strtol(p, (void*)&p, 10);
+        width = strtol(str, (void*)&p, 10);
         if (*p)
             p++;
         height = strtol(p, (void*)&p, 10);
+
+        /* trailing extraneous data detected, like in 123x345foobar */
+        if (*p)
+            return AVERROR(EINVAL);
     }
     if (width <= 0 || height <= 0)
         return AVERROR(EINVAL);
@@ -389,7 +387,7 @@
     }
 
     if (tail) {
-        unsigned long int alpha;
+        double alpha;
         const char *alpha_string = tail;
         if (!strncmp(alpha_string, "0x", 2)) {
             alpha = strtoul(alpha_string, &tail, 16);
@@ -401,7 +399,7 @@
                 alpha = 255 * norm_alpha;
         }
 
-        if (tail == alpha_string || *tail || alpha > 255) {
+        if (tail == alpha_string || *tail || alpha > 255 || alpha < 0) {
             av_log(log_ctx, AV_LOG_ERROR, "Invalid alpha value specifier '%s' in '%s'\n",
                    alpha_string, color_string);
             return AVERROR(EINVAL);
@@ -456,7 +454,8 @@
             c = *fmt++;
             switch(c) {
             case 'H':
-                val = date_get_num(&p, 0, 23, 2);
+            case 'J':
+                val = date_get_num(&p, 0, c == 'H' ? 23 : INT_MAX, 2);
                 if (val == -1)
                     return NULL;
                 dt->tm_hour = val;
@@ -583,7 +582,7 @@
             ++p;
         }
         /* parse timestr as HH:MM:SS */
-        q = av_small_strptime(p, time_fmt[0], &dt);
+        q = av_small_strptime(p, "%J:%M:%S", &dt);
         if (!q) {
             /* parse timestr as S+ */
             dt.tm_sec = strtol(p, (void *)&q, 10);
@@ -691,7 +690,7 @@
     printf("Testing av_parse_video_rate()\n");
     {
         int i;
-        const char *rates[] = {
+        static const char *const rates[] = {
             "-inf",
             "inf",
             "nan",
@@ -721,10 +720,10 @@
 
         for (i = 0; i < FF_ARRAY_ELEMS(rates); i++) {
             int ret;
-            AVRational q = (AVRational){0, 0};
+            AVRational q = { 0, 0 };
             ret = av_parse_video_rate(&q, rates[i]);
-            printf("'%s' -> %d/%d%s\n",
-                   rates[i], q.num, q.den, ret ? " error" : "");
+            printf("'%s' -> %d/%d %s\n",
+                   rates[i], q.num, q.den, ret ? "ERROR" : "OK");
         }
     }
 
@@ -732,7 +731,7 @@
     {
         int i;
         uint8_t rgba[4];
-        const char *color_names[] = {
+        static const char *const color_names[] = {
             "bikeshed",
             "RaNdOm",
             "foo",
@@ -775,7 +774,8 @@
 
         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]);
+                printf("%s -> R(%d) G(%d) B(%d) A(%d)\n",
+                       color_names[i], rgba[0], rgba[1], rgba[2], rgba[3]);
             else
                 printf("%s -> error\n", color_names[i]);
         }
diff --git a/libavutil/parseutils.h b/libavutil/parseutils.h
index da7d345..1f56a7a 100644
--- a/libavutil/parseutils.h
+++ b/libavutil/parseutils.h
@@ -141,6 +141,7 @@
  * In particular it actually supports the parameters:
  * - %H: the hour as a decimal number, using a 24-hour clock, in the
  * range '00' through '23'
+ * - %J: hours as a decimal number, in the range '0' through INT_MAX
  * - %M: the minute as a decimal number, using a 24-hour clock, in the
  * range '00' through '59'
  * - %S: the second as a decimal number, using a 24-hour clock, in the
diff --git a/libavutil/pca.c b/libavutil/pca.c
index 0839d68..54927a2 100644
--- a/libavutil/pca.c
+++ b/libavutil/pca.c
@@ -32,6 +32,7 @@
     int n;
     double *covariance;
     double *mean;
+    double *z;
 }PCA;
 
 PCA *ff_pca_init(int n){
@@ -41,6 +42,7 @@
 
     pca= av_mallocz(sizeof(PCA));
     pca->n= n;
+    pca->z = av_malloc(sizeof(*pca->z) * n);
     pca->count=0;
     pca->covariance= av_mallocz(sizeof(double)*n*n);
     pca->mean= av_mallocz(sizeof(double)*n);
@@ -51,6 +53,7 @@
 void ff_pca_free(PCA *pca){
     av_freep(&pca->covariance);
     av_freep(&pca->mean);
+    av_freep(&pca->z);
     av_free(pca);
 }
 
@@ -70,7 +73,7 @@
     int i, j, pass;
     int k=0;
     const int n= pca->n;
-    double z[n];
+    double *z = pca->z;
 
     memset(eigenvector, 0, sizeof(double)*n*n);
 
diff --git a/libavutil/pixdesc.c b/libavutil/pixdesc.c
index d64d300..0be8ae4 100644
--- a/libavutil/pixdesc.c
+++ b/libavutil/pixdesc.c
@@ -21,6 +21,8 @@
 
 #include <stdio.h>
 #include <string.h>
+
+#include "common.h"
 #include "pixfmt.h"
 #include "pixdesc.h"
 
@@ -122,8 +124,11 @@
     }
 }
 
-const AVPixFmtDescriptor av_pix_fmt_descriptors[PIX_FMT_NB] = {
-    [PIX_FMT_YUV420P] = {
+#if !FF_API_PIX_FMT_DESC
+static
+#endif
+const AVPixFmtDescriptor av_pix_fmt_descriptors[AV_PIX_FMT_NB] = {
+    [AV_PIX_FMT_YUV420P] = {
         .name = "yuv420p",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -135,7 +140,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUYV422] = {
+    [AV_PIX_FMT_YUYV422] = {
         .name = "yuyv422",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -146,7 +151,7 @@
             { 0, 3, 4, 0, 7 },        /* V */
         },
     },
-    [PIX_FMT_RGB24] = {
+    [AV_PIX_FMT_RGB24] = {
         .name = "rgb24",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -158,7 +163,7 @@
         },
         .flags = PIX_FMT_RGB,
     },
-    [PIX_FMT_BGR24] = {
+    [AV_PIX_FMT_BGR24] = {
         .name = "bgr24",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -170,7 +175,7 @@
         },
         .flags = PIX_FMT_RGB,
     },
-    [PIX_FMT_YUV422P] = {
+    [AV_PIX_FMT_YUV422P] = {
         .name = "yuv422p",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -182,7 +187,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV444P] = {
+    [AV_PIX_FMT_YUV444P] = {
         .name = "yuv444p",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -194,7 +199,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV410P] = {
+    [AV_PIX_FMT_YUV410P] = {
         .name = "yuv410p",
         .nb_components = 3,
         .log2_chroma_w = 2,
@@ -206,7 +211,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV411P] = {
+    [AV_PIX_FMT_YUV411P] = {
         .name = "yuv411p",
         .nb_components = 3,
         .log2_chroma_w = 2,
@@ -218,7 +223,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_GRAY8] = {
+    [AV_PIX_FMT_GRAY8] = {
         .name = "gray",
         .nb_components = 1,
         .log2_chroma_w = 0,
@@ -228,7 +233,7 @@
         },
         .flags = PIX_FMT_PSEUDOPAL,
     },
-    [PIX_FMT_MONOWHITE] = {
+    [AV_PIX_FMT_MONOWHITE] = {
         .name = "monow",
         .nb_components = 1,
         .log2_chroma_w = 0,
@@ -238,7 +243,7 @@
         },
         .flags = PIX_FMT_BITSTREAM,
     },
-    [PIX_FMT_MONOBLACK] = {
+    [AV_PIX_FMT_MONOBLACK] = {
         .name = "monob",
         .nb_components = 1,
         .log2_chroma_w = 0,
@@ -248,7 +253,7 @@
         },
         .flags = PIX_FMT_BITSTREAM,
     },
-    [PIX_FMT_PAL8] = {
+    [AV_PIX_FMT_PAL8] = {
         .name = "pal8",
         .nb_components = 1,
         .log2_chroma_w = 0,
@@ -258,7 +263,7 @@
         },
         .flags = PIX_FMT_PAL,
     },
-    [PIX_FMT_YUVJ420P] = {
+    [AV_PIX_FMT_YUVJ420P] = {
         .name = "yuvj420p",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -270,7 +275,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUVJ422P] = {
+    [AV_PIX_FMT_YUVJ422P] = {
         .name = "yuvj422p",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -282,7 +287,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUVJ444P] = {
+    [AV_PIX_FMT_YUVJ444P] = {
         .name = "yuvj444p",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -294,15 +299,15 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_XVMC_MPEG2_MC] = {
+    [AV_PIX_FMT_XVMC_MPEG2_MC] = {
         .name = "xvmcmc",
         .flags = PIX_FMT_HWACCEL,
     },
-    [PIX_FMT_XVMC_MPEG2_IDCT] = {
+    [AV_PIX_FMT_XVMC_MPEG2_IDCT] = {
         .name = "xvmcidct",
         .flags = PIX_FMT_HWACCEL,
     },
-    [PIX_FMT_UYVY422] = {
+    [AV_PIX_FMT_UYVY422] = {
         .name = "uyvy422",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -313,7 +318,7 @@
             { 0, 3, 3, 0, 7 },        /* V */
         },
     },
-    [PIX_FMT_UYYVYY411] = {
+    [AV_PIX_FMT_UYYVYY411] = {
         .name = "uyyvyy411",
         .nb_components = 3,
         .log2_chroma_w = 2,
@@ -324,7 +329,7 @@
             { 0, 5, 4, 0, 7 },        /* V */
         },
     },
-    [PIX_FMT_BGR8] = {
+    [AV_PIX_FMT_BGR8] = {
         .name = "bgr8",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -336,7 +341,7 @@
         },
         .flags = PIX_FMT_RGB | PIX_FMT_PSEUDOPAL,
     },
-    [PIX_FMT_BGR4] = {
+    [AV_PIX_FMT_BGR4] = {
         .name = "bgr4",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -348,7 +353,7 @@
         },
         .flags = PIX_FMT_BITSTREAM | PIX_FMT_RGB,
     },
-    [PIX_FMT_BGR4_BYTE] = {
+    [AV_PIX_FMT_BGR4_BYTE] = {
         .name = "bgr4_byte",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -360,7 +365,7 @@
         },
         .flags = PIX_FMT_RGB | PIX_FMT_PSEUDOPAL,
     },
-    [PIX_FMT_RGB8] = {
+    [AV_PIX_FMT_RGB8] = {
         .name = "rgb8",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -372,7 +377,7 @@
         },
         .flags = PIX_FMT_RGB | PIX_FMT_PSEUDOPAL,
     },
-    [PIX_FMT_RGB4] = {
+    [AV_PIX_FMT_RGB4] = {
         .name = "rgb4",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -384,7 +389,7 @@
         },
         .flags = PIX_FMT_BITSTREAM | PIX_FMT_RGB,
     },
-    [PIX_FMT_RGB4_BYTE] = {
+    [AV_PIX_FMT_RGB4_BYTE] = {
         .name = "rgb4_byte",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -396,7 +401,7 @@
         },
         .flags = PIX_FMT_RGB | PIX_FMT_PSEUDOPAL,
     },
-    [PIX_FMT_NV12] = {
+    [AV_PIX_FMT_NV12] = {
         .name = "nv12",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -408,7 +413,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_NV21] = {
+    [AV_PIX_FMT_NV21] = {
         .name = "nv21",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -420,7 +425,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_ARGB] = {
+    [AV_PIX_FMT_ARGB] = {
         .name = "argb",
         .nb_components = 4,
         .log2_chroma_w = 0,
@@ -431,9 +436,9 @@
             { 0, 3, 4, 0, 7 },        /* B */
             { 0, 3, 1, 0, 7 },        /* A */
         },
-        .flags = PIX_FMT_RGB,
+        .flags = PIX_FMT_RGB | PIX_FMT_ALPHA,
     },
-    [PIX_FMT_RGBA] = {
+    [AV_PIX_FMT_RGBA] = {
         .name = "rgba",
         .nb_components = 4,
         .log2_chroma_w = 0,
@@ -444,9 +449,9 @@
             { 0, 3, 3, 0, 7 },        /* B */
             { 0, 3, 4, 0, 7 },        /* A */
         },
-        .flags = PIX_FMT_RGB,
+        .flags = PIX_FMT_RGB | PIX_FMT_ALPHA,
     },
-    [PIX_FMT_ABGR] = {
+    [AV_PIX_FMT_ABGR] = {
         .name = "abgr",
         .nb_components = 4,
         .log2_chroma_w = 0,
@@ -457,9 +462,9 @@
             { 0, 3, 2, 0, 7 },        /* B */
             { 0, 3, 1, 0, 7 },        /* A */
         },
-        .flags = PIX_FMT_RGB,
+        .flags = PIX_FMT_RGB | PIX_FMT_ALPHA,
     },
-    [PIX_FMT_BGRA] = {
+    [AV_PIX_FMT_BGRA] = {
         .name = "bgra",
         .nb_components = 4,
         .log2_chroma_w = 0,
@@ -470,9 +475,9 @@
             { 0, 3, 1, 0, 7 },        /* B */
             { 0, 3, 4, 0, 7 },        /* A */
         },
-        .flags = PIX_FMT_RGB,
+        .flags = PIX_FMT_RGB | PIX_FMT_ALPHA,
     },
-    [PIX_FMT_0RGB] = {
+    [AV_PIX_FMT_0RGB] = {
         .name = "0rgb",
         .nb_components= 3,
         .log2_chroma_w= 0,
@@ -484,7 +489,7 @@
         },
         .flags = PIX_FMT_RGB,
     },
-    [PIX_FMT_RGB0] = {
+    [AV_PIX_FMT_RGB0] = {
         .name = "rgb0",
         .nb_components= 3,
         .log2_chroma_w= 0,
@@ -497,7 +502,7 @@
         },
         .flags = PIX_FMT_RGB,
     },
-    [PIX_FMT_0BGR] = {
+    [AV_PIX_FMT_0BGR] = {
         .name = "0bgr",
         .nb_components= 3,
         .log2_chroma_w= 0,
@@ -509,7 +514,7 @@
         },
         .flags = PIX_FMT_RGB,
     },
-    [PIX_FMT_BGR0] = {
+    [AV_PIX_FMT_BGR0] = {
         .name = "bgr0",
         .nb_components= 3,
         .log2_chroma_w= 0,
@@ -522,7 +527,7 @@
         },
         .flags = PIX_FMT_RGB,
     },
-    [PIX_FMT_GRAY16BE] = {
+    [AV_PIX_FMT_GRAY16BE] = {
         .name = "gray16be",
         .nb_components = 1,
         .log2_chroma_w = 0,
@@ -532,7 +537,7 @@
         },
         .flags = PIX_FMT_BE,
     },
-    [PIX_FMT_GRAY16LE] = {
+    [AV_PIX_FMT_GRAY16LE] = {
         .name = "gray16le",
         .nb_components = 1,
         .log2_chroma_w = 0,
@@ -541,7 +546,7 @@
             { 0, 1, 1, 0, 15 },       /* Y */
         },
     },
-    [PIX_FMT_YUV440P] = {
+    [AV_PIX_FMT_YUV440P] = {
         .name = "yuv440p",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -553,7 +558,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUVJ440P] = {
+    [AV_PIX_FMT_YUVJ440P] = {
         .name = "yuvj440p",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -565,7 +570,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUVA420P] = {
+    [AV_PIX_FMT_YUVA420P] = {
         .name = "yuva420p",
         .nb_components = 4,
         .log2_chroma_w = 1,
@@ -576,9 +581,9 @@
             { 2, 0, 1, 0, 7 },        /* V */
             { 3, 0, 1, 0, 7 },        /* A */
         },
-        .flags = PIX_FMT_PLANAR,
+        .flags = PIX_FMT_PLANAR | PIX_FMT_ALPHA,
     },
-    [PIX_FMT_YUVA422P] = {
+    [AV_PIX_FMT_YUVA422P] = {
         .name = "yuva422p",
         .nb_components = 4,
         .log2_chroma_w = 1,
@@ -589,9 +594,9 @@
             { 2, 0, 1, 0, 7 },        /* V */
             { 3, 0, 1, 0, 7 },        /* A */
         },
-        .flags = PIX_FMT_PLANAR,
+        .flags = PIX_FMT_PLANAR | PIX_FMT_ALPHA,
     },
-    [PIX_FMT_YUVA444P] = {
+    [AV_PIX_FMT_YUVA444P] = {
         .name = "yuva444p",
         .nb_components = 4,
         .log2_chroma_w = 0,
@@ -602,45 +607,279 @@
             { 2, 0, 1, 0, 7 },        /* V */
             { 3, 0, 1, 0, 7 },        /* A */
         },
-        .flags = PIX_FMT_PLANAR,
+        .flags = PIX_FMT_PLANAR | PIX_FMT_ALPHA,
     },
-    [PIX_FMT_VDPAU_H264] = {
+    [AV_PIX_FMT_YUVA420P9BE] = {
+        .name = "yuva420p9be",
+        .nb_components = 4,
+        .log2_chroma_w = 1,
+        .log2_chroma_h = 1,
+        .comp = {
+            { 0, 1, 1, 0, 8 },        /* Y */
+            { 1, 1, 1, 0, 8 },        /* U */
+            { 2, 1, 1, 0, 8 },        /* V */
+            { 3, 1, 1, 0, 8 },        /* A */
+        },
+        .flags = PIX_FMT_BE | PIX_FMT_PLANAR | PIX_FMT_ALPHA,
+    },
+    [AV_PIX_FMT_YUVA420P9LE] = {
+        .name = "yuva420p9le",
+        .nb_components = 4,
+        .log2_chroma_w = 1,
+        .log2_chroma_h = 1,
+        .comp = {
+            { 0, 1, 1, 0, 8 },        /* Y */
+            { 1, 1, 1, 0, 8 },        /* U */
+            { 2, 1, 1, 0, 8 },        /* V */
+            { 3, 1, 1, 0, 8 },        /* A */
+        },
+        .flags = PIX_FMT_PLANAR | PIX_FMT_ALPHA,
+    },
+    [AV_PIX_FMT_YUVA422P9BE] = {
+        .name = "yuva422p9be",
+        .nb_components = 4,
+        .log2_chroma_w = 1,
+        .log2_chroma_h = 0,
+        .comp = {
+            { 0, 1, 1, 0, 8 },        /* Y */
+            { 1, 1, 1, 0, 8 },        /* U */
+            { 2, 1, 1, 0, 8 },        /* V */
+            { 3, 1, 1, 0, 8 },        /* A */
+        },
+        .flags = PIX_FMT_BE | PIX_FMT_PLANAR | PIX_FMT_ALPHA,
+    },
+    [AV_PIX_FMT_YUVA422P9LE] = {
+        .name = "yuva422p9le",
+        .nb_components = 4,
+        .log2_chroma_w = 1,
+        .log2_chroma_h = 0,
+        .comp = {
+            { 0, 1, 1, 0, 8 },        /* Y */
+            { 1, 1, 1, 0, 8 },        /* U */
+            { 2, 1, 1, 0, 8 },        /* V */
+            { 3, 1, 1, 0, 8 },        /* A */
+        },
+        .flags = PIX_FMT_PLANAR | PIX_FMT_ALPHA,
+    },
+    [AV_PIX_FMT_YUVA444P9BE] = {
+        .name = "yuva444p9be",
+        .nb_components = 4,
+        .log2_chroma_w = 0,
+        .log2_chroma_h = 0,
+        .comp = {
+            { 0, 1, 1, 0, 8 },        /* Y */
+            { 1, 1, 1, 0, 8 },        /* U */
+            { 2, 1, 1, 0, 8 },        /* V */
+            { 3, 1, 1, 0, 8 },        /* A */
+        },
+        .flags = PIX_FMT_BE | PIX_FMT_PLANAR | PIX_FMT_ALPHA,
+    },
+    [AV_PIX_FMT_YUVA444P9LE] = {
+        .name = "yuva444p9le",
+        .nb_components = 4,
+        .log2_chroma_w = 0,
+        .log2_chroma_h = 0,
+        .comp = {
+            { 0, 1, 1, 0, 8 },        /* Y */
+            { 1, 1, 1, 0, 8 },        /* U */
+            { 2, 1, 1, 0, 8 },        /* V */
+            { 3, 1, 1, 0, 8 },        /* A */
+        },
+        .flags = PIX_FMT_PLANAR | PIX_FMT_ALPHA,
+    },
+    [AV_PIX_FMT_YUVA420P10BE] = {
+        .name = "yuva420p10be",
+        .nb_components = 4,
+        .log2_chroma_w = 1,
+        .log2_chroma_h = 1,
+        .comp = {
+            { 0, 1, 1, 0, 9 },        /* Y */
+            { 1, 1, 1, 0, 9 },        /* U */
+            { 2, 1, 1, 0, 9 },        /* V */
+            { 3, 1, 1, 0, 9 },        /* A */
+        },
+        .flags = PIX_FMT_BE | PIX_FMT_PLANAR | PIX_FMT_ALPHA,
+    },
+    [AV_PIX_FMT_YUVA420P10LE] = {
+        .name = "yuva420p10le",
+        .nb_components = 4,
+        .log2_chroma_w = 1,
+        .log2_chroma_h = 1,
+        .comp = {
+            { 0, 1, 1, 0, 15 },        /* Y */
+            { 1, 1, 1, 0, 15 },        /* U */
+            { 2, 1, 1, 0, 15 },        /* V */
+            { 3, 1, 1, 0, 15 },        /* A */
+        },
+        .flags = PIX_FMT_PLANAR | PIX_FMT_ALPHA,
+    },
+    [AV_PIX_FMT_YUVA422P10BE] = {
+        .name = "yuva422p10be",
+        .nb_components = 4,
+        .log2_chroma_w = 1,
+        .log2_chroma_h = 0,
+        .comp = {
+            { 0, 1, 1, 0, 15 },        /* Y */
+            { 1, 1, 1, 0, 15 },        /* U */
+            { 2, 1, 1, 0, 15 },        /* V */
+            { 3, 1, 1, 0, 15 },        /* A */
+        },
+        .flags = PIX_FMT_BE | PIX_FMT_PLANAR | PIX_FMT_ALPHA,
+    },
+    [AV_PIX_FMT_YUVA422P10LE] = {
+        .name = "yuva422p10le",
+        .nb_components = 4,
+        .log2_chroma_w = 1,
+        .log2_chroma_h = 0,
+        .comp = {
+            { 0, 1, 1, 0, 15 },        /* Y */
+            { 1, 1, 1, 0, 15 },        /* U */
+            { 2, 1, 1, 0, 15 },        /* V */
+            { 3, 1, 1, 0, 15 },        /* A */
+        },
+        .flags = PIX_FMT_PLANAR | PIX_FMT_ALPHA,
+    },
+    [AV_PIX_FMT_YUVA444P10BE] = {
+        .name = "yuva444p10be",
+        .nb_components = 4,
+        .log2_chroma_w = 0,
+        .log2_chroma_h = 0,
+        .comp = {
+            { 0, 1, 1, 0, 15 },        /* Y */
+            { 1, 1, 1, 0, 15 },        /* U */
+            { 2, 1, 1, 0, 15 },        /* V */
+            { 3, 1, 1, 0, 15 },        /* A */
+        },
+        .flags = PIX_FMT_BE | PIX_FMT_PLANAR | PIX_FMT_ALPHA,
+    },
+    [AV_PIX_FMT_YUVA444P10LE] = {
+        .name = "yuva444p10le",
+        .nb_components = 4,
+        .log2_chroma_w = 0,
+        .log2_chroma_h = 0,
+        .comp = {
+            { 0, 1, 1, 0, 15 },        /* Y */
+            { 1, 1, 1, 0, 15 },        /* U */
+            { 2, 1, 1, 0, 15 },        /* V */
+            { 3, 1, 1, 0, 15 },        /* A */
+        },
+        .flags = PIX_FMT_PLANAR | PIX_FMT_ALPHA,
+    },
+    [AV_PIX_FMT_YUVA420P16BE] = {
+        .name = "yuva420p16be",
+        .nb_components = 4,
+        .log2_chroma_w = 1,
+        .log2_chroma_h = 1,
+        .comp = {
+            { 0, 1, 1, 0, 15 },        /* Y */
+            { 1, 1, 1, 0, 15 },        /* U */
+            { 2, 1, 1, 0, 15 },        /* V */
+            { 3, 1, 1, 0, 15 },        /* A */
+        },
+        .flags = PIX_FMT_BE | PIX_FMT_PLANAR | PIX_FMT_ALPHA,
+    },
+    [AV_PIX_FMT_YUVA420P16LE] = {
+        .name = "yuva420p16le",
+        .nb_components = 4,
+        .log2_chroma_w = 1,
+        .log2_chroma_h = 1,
+        .comp = {
+            { 0, 1, 1, 0, 15 },        /* Y */
+            { 1, 1, 1, 0, 15 },        /* U */
+            { 2, 1, 1, 0, 15 },        /* V */
+            { 3, 1, 1, 0, 15 },        /* A */
+        },
+        .flags = PIX_FMT_PLANAR | PIX_FMT_ALPHA,
+    },
+    [AV_PIX_FMT_YUVA422P16BE] = {
+        .name = "yuva422p16be",
+        .nb_components = 4,
+        .log2_chroma_w = 1,
+        .log2_chroma_h = 0,
+        .comp = {
+            { 0, 1, 1, 0, 15 },        /* Y */
+            { 1, 1, 1, 0, 15 },        /* U */
+            { 2, 1, 1, 0, 15 },        /* V */
+            { 3, 1, 1, 0, 15 },        /* A */
+        },
+        .flags = PIX_FMT_BE | PIX_FMT_PLANAR | PIX_FMT_ALPHA,
+    },
+    [AV_PIX_FMT_YUVA422P16LE] = {
+        .name = "yuva422p16le",
+        .nb_components = 4,
+        .log2_chroma_w = 1,
+        .log2_chroma_h = 0,
+        .comp = {
+            { 0, 1, 1, 0, 15 },        /* Y */
+            { 1, 1, 1, 0, 15 },        /* U */
+            { 2, 1, 1, 0, 15 },        /* V */
+            { 3, 1, 1, 0, 15 },        /* A */
+        },
+        .flags = PIX_FMT_PLANAR | PIX_FMT_ALPHA,
+    },
+    [AV_PIX_FMT_YUVA444P16BE] = {
+        .name = "yuva444p16be",
+        .nb_components = 4,
+        .log2_chroma_w = 0,
+        .log2_chroma_h = 0,
+        .comp = {
+            { 0, 1, 1, 0, 15 },        /* Y */
+            { 1, 1, 1, 0, 15 },        /* U */
+            { 2, 1, 1, 0, 15 },        /* V */
+            { 3, 1, 1, 0, 15 },        /* A */
+        },
+        .flags = PIX_FMT_BE | PIX_FMT_PLANAR | PIX_FMT_ALPHA,
+    },
+    [AV_PIX_FMT_YUVA444P16LE] = {
+        .name = "yuva444p16le",
+        .nb_components = 4,
+        .log2_chroma_w = 0,
+        .log2_chroma_h = 0,
+        .comp = {
+            { 0, 1, 1, 0, 15 },        /* Y */
+            { 1, 1, 1, 0, 15 },        /* U */
+            { 2, 1, 1, 0, 15 },        /* V */
+            { 3, 1, 1, 0, 15 },        /* A */
+        },
+        .flags = PIX_FMT_PLANAR | PIX_FMT_ALPHA,
+    },
+    [AV_PIX_FMT_VDPAU_H264] = {
         .name = "vdpau_h264",
         .log2_chroma_w = 1,
         .log2_chroma_h = 1,
         .flags = PIX_FMT_HWACCEL,
     },
-    [PIX_FMT_VDPAU_MPEG1] = {
+    [AV_PIX_FMT_VDPAU_MPEG1] = {
         .name = "vdpau_mpeg1",
         .log2_chroma_w = 1,
         .log2_chroma_h = 1,
         .flags = PIX_FMT_HWACCEL,
     },
-    [PIX_FMT_VDPAU_MPEG2] = {
+    [AV_PIX_FMT_VDPAU_MPEG2] = {
         .name = "vdpau_mpeg2",
         .log2_chroma_w = 1,
         .log2_chroma_h = 1,
         .flags = PIX_FMT_HWACCEL,
     },
-    [PIX_FMT_VDPAU_WMV3] = {
+    [AV_PIX_FMT_VDPAU_WMV3] = {
         .name = "vdpau_wmv3",
         .log2_chroma_w = 1,
         .log2_chroma_h = 1,
         .flags = PIX_FMT_HWACCEL,
     },
-    [PIX_FMT_VDPAU_VC1] = {
+    [AV_PIX_FMT_VDPAU_VC1] = {
         .name = "vdpau_vc1",
         .log2_chroma_w = 1,
         .log2_chroma_h = 1,
         .flags = PIX_FMT_HWACCEL,
     },
-    [PIX_FMT_VDPAU_MPEG4] = {
+    [AV_PIX_FMT_VDPAU_MPEG4] = {
         .name = "vdpau_mpeg4",
         .log2_chroma_w = 1,
         .log2_chroma_h = 1,
         .flags = PIX_FMT_HWACCEL,
     },
-    [PIX_FMT_RGB48BE] = {
+    [AV_PIX_FMT_RGB48BE] = {
         .name = "rgb48be",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -652,7 +891,7 @@
         },
         .flags = PIX_FMT_RGB | PIX_FMT_BE,
     },
-    [PIX_FMT_RGB48LE] = {
+    [AV_PIX_FMT_RGB48LE] = {
         .name = "rgb48le",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -664,7 +903,7 @@
         },
         .flags = PIX_FMT_RGB,
     },
-    [PIX_FMT_RGBA64BE] = {
+    [AV_PIX_FMT_RGBA64BE] = {
         .name = "rgba64be",
         .nb_components= 4,
         .log2_chroma_w= 0,
@@ -675,9 +914,9 @@
             { 0, 7, 5, 0, 15 },       /* B */
             { 0, 7, 7, 0, 15 },       /* A */
         },
-        .flags = PIX_FMT_RGB | PIX_FMT_BE,
+        .flags = PIX_FMT_RGB | PIX_FMT_BE | PIX_FMT_ALPHA,
     },
-    [PIX_FMT_RGBA64LE] = {
+    [AV_PIX_FMT_RGBA64LE] = {
         .name = "rgba64le",
         .nb_components= 4,
         .log2_chroma_w= 0,
@@ -688,9 +927,9 @@
             { 0, 7, 5, 0, 15 },       /* B */
             { 0, 7, 7, 0, 15 },       /* A */
         },
-        .flags = PIX_FMT_RGB,
+        .flags = PIX_FMT_RGB | PIX_FMT_ALPHA,
     },
-    [PIX_FMT_RGB565BE] = {
+    [AV_PIX_FMT_RGB565BE] = {
         .name = "rgb565be",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -702,7 +941,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_RGB,
     },
-    [PIX_FMT_RGB565LE] = {
+    [AV_PIX_FMT_RGB565LE] = {
         .name = "rgb565le",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -714,7 +953,7 @@
         },
         .flags = PIX_FMT_RGB,
     },
-    [PIX_FMT_RGB555BE] = {
+    [AV_PIX_FMT_RGB555BE] = {
         .name = "rgb555be",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -726,7 +965,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_RGB,
     },
-    [PIX_FMT_RGB555LE] = {
+    [AV_PIX_FMT_RGB555LE] = {
         .name = "rgb555le",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -738,7 +977,7 @@
         },
         .flags = PIX_FMT_RGB,
     },
-    [PIX_FMT_RGB444BE] = {
+    [AV_PIX_FMT_RGB444BE] = {
         .name = "rgb444be",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -750,7 +989,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_RGB,
     },
-    [PIX_FMT_RGB444LE] = {
+    [AV_PIX_FMT_RGB444LE] = {
         .name = "rgb444le",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -762,7 +1001,7 @@
         },
         .flags = PIX_FMT_RGB,
     },
-    [PIX_FMT_BGR48BE] = {
+    [AV_PIX_FMT_BGR48BE] = {
         .name = "bgr48be",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -774,7 +1013,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_RGB,
     },
-    [PIX_FMT_BGR48LE] = {
+    [AV_PIX_FMT_BGR48LE] = {
         .name = "bgr48le",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -786,7 +1025,7 @@
         },
         .flags = PIX_FMT_RGB,
     },
-    [PIX_FMT_BGRA64BE] = {
+    [AV_PIX_FMT_BGRA64BE] = {
         .name = "bgra64be",
         .nb_components= 4,
         .log2_chroma_w= 0,
@@ -797,9 +1036,9 @@
             { 0, 7, 1, 0, 15 },       /* B */
             { 0, 7, 7, 0, 15 },       /* A */
         },
-        .flags = PIX_FMT_BE | PIX_FMT_RGB,
+        .flags = PIX_FMT_BE | PIX_FMT_RGB | PIX_FMT_ALPHA,
     },
-    [PIX_FMT_BGRA64LE] = {
+    [AV_PIX_FMT_BGRA64LE] = {
         .name = "bgra64le",
         .nb_components= 4,
         .log2_chroma_w= 0,
@@ -810,9 +1049,9 @@
             { 0, 7, 1, 0, 15 },       /* B */
             { 0, 7, 7, 0, 15 },       /* A */
         },
-        .flags = PIX_FMT_RGB,
+        .flags = PIX_FMT_RGB | PIX_FMT_ALPHA,
     },
-    [PIX_FMT_BGR565BE] = {
+    [AV_PIX_FMT_BGR565BE] = {
         .name = "bgr565be",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -824,7 +1063,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_RGB,
     },
-    [PIX_FMT_BGR565LE] = {
+    [AV_PIX_FMT_BGR565LE] = {
         .name = "bgr565le",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -836,7 +1075,7 @@
         },
         .flags = PIX_FMT_RGB,
     },
-    [PIX_FMT_BGR555BE] = {
+    [AV_PIX_FMT_BGR555BE] = {
         .name = "bgr555be",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -848,7 +1087,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_RGB,
      },
-    [PIX_FMT_BGR555LE] = {
+    [AV_PIX_FMT_BGR555LE] = {
         .name = "bgr555le",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -860,7 +1099,7 @@
         },
         .flags = PIX_FMT_RGB,
     },
-    [PIX_FMT_BGR444BE] = {
+    [AV_PIX_FMT_BGR444BE] = {
         .name = "bgr444be",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -872,7 +1111,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_RGB,
      },
-    [PIX_FMT_BGR444LE] = {
+    [AV_PIX_FMT_BGR444LE] = {
         .name = "bgr444le",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -884,25 +1123,25 @@
         },
         .flags = PIX_FMT_RGB,
     },
-    [PIX_FMT_VAAPI_MOCO] = {
+    [AV_PIX_FMT_VAAPI_MOCO] = {
         .name = "vaapi_moco",
         .log2_chroma_w = 1,
         .log2_chroma_h = 1,
         .flags = PIX_FMT_HWACCEL,
     },
-    [PIX_FMT_VAAPI_IDCT] = {
+    [AV_PIX_FMT_VAAPI_IDCT] = {
         .name = "vaapi_idct",
         .log2_chroma_w = 1,
         .log2_chroma_h = 1,
         .flags = PIX_FMT_HWACCEL,
     },
-    [PIX_FMT_VAAPI_VLD] = {
+    [AV_PIX_FMT_VAAPI_VLD] = {
         .name = "vaapi_vld",
         .log2_chroma_w = 1,
         .log2_chroma_h = 1,
         .flags = PIX_FMT_HWACCEL,
     },
-    [PIX_FMT_YUV420P9LE] = {
+    [AV_PIX_FMT_YUV420P9LE] = {
         .name = "yuv420p9le",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -914,7 +1153,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV420P9BE] = {
+    [AV_PIX_FMT_YUV420P9BE] = {
         .name = "yuv420p9be",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -926,7 +1165,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV420P10LE] = {
+    [AV_PIX_FMT_YUV420P10LE] = {
         .name = "yuv420p10le",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -938,7 +1177,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV420P10BE] = {
+    [AV_PIX_FMT_YUV420P10BE] = {
         .name = "yuv420p10be",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -950,7 +1189,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV420P12LE] = {
+    [AV_PIX_FMT_YUV420P12LE] = {
         .name = "yuv420p12le",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -962,7 +1201,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV420P12BE] = {
+    [AV_PIX_FMT_YUV420P12BE] = {
         .name = "yuv420p12be",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -974,7 +1213,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV420P14LE] = {
+    [AV_PIX_FMT_YUV420P14LE] = {
         .name = "yuv420p14le",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -986,7 +1225,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV420P14BE] = {
+    [AV_PIX_FMT_YUV420P14BE] = {
         .name = "yuv420p14be",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -998,7 +1237,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV420P16LE] = {
+    [AV_PIX_FMT_YUV420P16LE] = {
         .name = "yuv420p16le",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -1010,7 +1249,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV420P16BE] = {
+    [AV_PIX_FMT_YUV420P16BE] = {
         .name = "yuv420p16be",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -1022,7 +1261,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV422P9LE] = {
+    [AV_PIX_FMT_YUV422P9LE] = {
         .name = "yuv422p9le",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -1034,7 +1273,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV422P9BE] = {
+    [AV_PIX_FMT_YUV422P9BE] = {
         .name = "yuv422p9be",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -1046,7 +1285,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV422P10LE] = {
+    [AV_PIX_FMT_YUV422P10LE] = {
         .name = "yuv422p10le",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -1058,7 +1297,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV422P10BE] = {
+    [AV_PIX_FMT_YUV422P10BE] = {
         .name = "yuv422p10be",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -1070,7 +1309,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV422P12LE] = {
+    [AV_PIX_FMT_YUV422P12LE] = {
         .name = "yuv422p12le",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -1082,7 +1321,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV422P12BE] = {
+    [AV_PIX_FMT_YUV422P12BE] = {
         .name = "yuv422p12be",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -1094,7 +1333,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV422P14LE] = {
+    [AV_PIX_FMT_YUV422P14LE] = {
         .name = "yuv422p14le",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -1106,7 +1345,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV422P14BE] = {
+    [AV_PIX_FMT_YUV422P14BE] = {
         .name = "yuv422p14be",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -1118,7 +1357,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV422P16LE] = {
+    [AV_PIX_FMT_YUV422P16LE] = {
         .name = "yuv422p16le",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -1130,7 +1369,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV422P16BE] = {
+    [AV_PIX_FMT_YUV422P16BE] = {
         .name = "yuv422p16be",
         .nb_components = 3,
         .log2_chroma_w = 1,
@@ -1142,7 +1381,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV444P16LE] = {
+    [AV_PIX_FMT_YUV444P16LE] = {
         .name = "yuv444p16le",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1154,7 +1393,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV444P16BE] = {
+    [AV_PIX_FMT_YUV444P16BE] = {
         .name = "yuv444p16be",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1166,7 +1405,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV444P10LE] = {
+    [AV_PIX_FMT_YUV444P10LE] = {
         .name = "yuv444p10le",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1178,7 +1417,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV444P10BE] = {
+    [AV_PIX_FMT_YUV444P10BE] = {
         .name = "yuv444p10be",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1190,7 +1429,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV444P9LE] = {
+    [AV_PIX_FMT_YUV444P9LE] = {
         .name = "yuv444p9le",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1202,7 +1441,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV444P9BE] = {
+    [AV_PIX_FMT_YUV444P9BE] = {
         .name = "yuv444p9be",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1214,7 +1453,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV444P12LE] = {
+    [AV_PIX_FMT_YUV444P12LE] = {
         .name = "yuv444p12le",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1226,7 +1465,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV444P12BE] = {
+    [AV_PIX_FMT_YUV444P12BE] = {
         .name = "yuv444p12be",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1238,7 +1477,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV444P14LE] = {
+    [AV_PIX_FMT_YUV444P14LE] = {
         .name = "yuv444p14le",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1250,7 +1489,7 @@
         },
         .flags = PIX_FMT_PLANAR,
     },
-    [PIX_FMT_YUV444P14BE] = {
+    [AV_PIX_FMT_YUV444P14BE] = {
         .name = "yuv444p14be",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1262,27 +1501,28 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_PLANAR,
     },
-    [PIX_FMT_DXVA2_VLD] = {
+    [AV_PIX_FMT_DXVA2_VLD] = {
         .name = "dxva2_vld",
         .log2_chroma_w = 1,
         .log2_chroma_h = 1,
         .flags = PIX_FMT_HWACCEL,
     },
-    [PIX_FMT_VDA_VLD] = {
+    [AV_PIX_FMT_VDA_VLD] = {
         .name = "vda_vld",
         .log2_chroma_w = 1,
         .log2_chroma_h = 1,
         .flags = PIX_FMT_HWACCEL,
     },
-    [PIX_FMT_GRAY8A] = {
+    [AV_PIX_FMT_GRAY8A] = {
         .name = "gray8a",
         .nb_components = 2,
         .comp = {
             { 0, 1, 1, 0, 7 },        /* Y */
             { 0, 1, 2, 0, 7 },        /* A */
         },
+        .flags = PIX_FMT_ALPHA,
     },
-    [PIX_FMT_GBRP] = {
+    [AV_PIX_FMT_GBRP] = {
         .name = "gbrp",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1294,7 +1534,7 @@
         },
         .flags = PIX_FMT_PLANAR | PIX_FMT_RGB,
     },
-    [PIX_FMT_GBRP9LE] = {
+    [AV_PIX_FMT_GBRP9LE] = {
         .name = "gbrp9le",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1306,7 +1546,7 @@
         },
         .flags = PIX_FMT_PLANAR | PIX_FMT_RGB,
     },
-    [PIX_FMT_GBRP9BE] = {
+    [AV_PIX_FMT_GBRP9BE] = {
         .name = "gbrp9be",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1318,7 +1558,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_PLANAR | PIX_FMT_RGB,
     },
-    [PIX_FMT_GBRP10LE] = {
+    [AV_PIX_FMT_GBRP10LE] = {
         .name = "gbrp10le",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1330,7 +1570,7 @@
         },
         .flags = PIX_FMT_PLANAR | PIX_FMT_RGB,
     },
-    [PIX_FMT_GBRP10BE] = {
+    [AV_PIX_FMT_GBRP10BE] = {
         .name = "gbrp10be",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1342,7 +1582,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_PLANAR | PIX_FMT_RGB,
     },
-    [PIX_FMT_GBRP12LE] = {
+    [AV_PIX_FMT_GBRP12LE] = {
         .name = "gbrp12le",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1354,7 +1594,7 @@
         },
         .flags = PIX_FMT_PLANAR | PIX_FMT_RGB,
     },
-    [PIX_FMT_GBRP12BE] = {
+    [AV_PIX_FMT_GBRP12BE] = {
         .name = "gbrp12be",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1366,7 +1606,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_PLANAR | PIX_FMT_RGB,
     },
-    [PIX_FMT_GBRP14LE] = {
+    [AV_PIX_FMT_GBRP14LE] = {
         .name = "gbrp14le",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1378,7 +1618,7 @@
         },
         .flags = PIX_FMT_PLANAR | PIX_FMT_RGB,
     },
-    [PIX_FMT_GBRP14BE] = {
+    [AV_PIX_FMT_GBRP14BE] = {
         .name = "gbrp14be",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1390,7 +1630,7 @@
         },
         .flags = PIX_FMT_BE | PIX_FMT_PLANAR | PIX_FMT_RGB,
     },
-    [PIX_FMT_GBRP16LE] = {
+    [AV_PIX_FMT_GBRP16LE] = {
         .name = "gbrp16le",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1402,7 +1642,7 @@
         },
         .flags = PIX_FMT_PLANAR | PIX_FMT_RGB,
     },
-    [PIX_FMT_GBRP16BE] = {
+    [AV_PIX_FMT_GBRP16BE] = {
         .name = "gbrp16be",
         .nb_components = 3,
         .log2_chroma_w = 0,
@@ -1416,21 +1656,21 @@
     },
 };
 
-static enum PixelFormat get_pix_fmt_internal(const char *name)
+static enum AVPixelFormat get_pix_fmt_internal(const char *name)
 {
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
 
-    for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++)
+    for (pix_fmt = 0; pix_fmt < AV_PIX_FMT_NB; pix_fmt++)
         if (av_pix_fmt_descriptors[pix_fmt].name &&
             !strcmp(av_pix_fmt_descriptors[pix_fmt].name, name))
             return pix_fmt;
 
-    return PIX_FMT_NONE;
+    return AV_PIX_FMT_NONE;
 }
 
-const char *av_get_pix_fmt_name(enum PixelFormat pix_fmt)
+const char *av_get_pix_fmt_name(enum AVPixelFormat pix_fmt)
 {
-    return (unsigned)pix_fmt < PIX_FMT_NB ?
+    return (unsigned)pix_fmt < AV_PIX_FMT_NB ?
         av_pix_fmt_descriptors[pix_fmt].name : NULL;
 }
 
@@ -1440,9 +1680,9 @@
 #   define X_NE(be, le) le
 #endif
 
-enum PixelFormat av_get_pix_fmt(const char *name)
+enum AVPixelFormat av_get_pix_fmt(const char *name)
 {
-    enum PixelFormat pix_fmt;
+    enum AVPixelFormat pix_fmt;
 
     if (!strcmp(name, "rgb32"))
         name = X_NE("argb", "bgra");
@@ -1450,7 +1690,7 @@
         name = X_NE("abgr", "rgba");
 
     pix_fmt = get_pix_fmt_internal(name);
-    if (pix_fmt == PIX_FMT_NONE) {
+    if (pix_fmt == AV_PIX_FMT_NONE) {
         char name2[32];
 
         snprintf(name2, sizeof(name2), "%s%s", name, X_NE("be", "le"));
@@ -1472,7 +1712,27 @@
     return bits >> log2_pixels;
 }
 
-char *av_get_pix_fmt_string (char *buf, int buf_size, enum PixelFormat pix_fmt)
+int av_get_padded_bits_per_pixel(const AVPixFmtDescriptor *pixdesc)
+{
+    int c, bits = 0;
+    int log2_pixels = pixdesc->log2_chroma_w + pixdesc->log2_chroma_h;
+    int steps[4] = {0};
+
+    for (c = 0; c < pixdesc->nb_components; c++) {
+        AVComponentDescriptor *comp = &pixdesc->comp[c];
+        int s = c == 1 || c == 2 ? 0 : log2_pixels;
+        steps[comp->plane] = (comp->step_minus1 + 1) << s;
+    }
+    for (c = 0; c < 4; c++)
+        bits += steps[c];
+
+    if(!(pixdesc->flags & PIX_FMT_BITSTREAM))
+        bits *= 8;
+
+    return bits >> log2_pixels;
+}
+
+char *av_get_pix_fmt_string (char *buf, int buf_size, enum AVPixelFormat pix_fmt)
 {
     /* print header */
     if (pix_fmt < 0) {
@@ -1485,3 +1745,40 @@
 
     return buf;
 }
+
+const AVPixFmtDescriptor *av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
+{
+    if (pix_fmt < 0 || pix_fmt >= AV_PIX_FMT_NB)
+        return NULL;
+    return &av_pix_fmt_descriptors[pix_fmt];
+}
+
+const AVPixFmtDescriptor *av_pix_fmt_desc_next(const AVPixFmtDescriptor *prev)
+{
+    if (!prev)
+        return &av_pix_fmt_descriptors[0];
+    if (prev - av_pix_fmt_descriptors < FF_ARRAY_ELEMS(av_pix_fmt_descriptors) - 1)
+        return prev + 1;
+    return NULL;
+}
+
+enum AVPixelFormat av_pix_fmt_desc_get_id(const AVPixFmtDescriptor *desc)
+{
+    if (desc < av_pix_fmt_descriptors ||
+        desc >= av_pix_fmt_descriptors + FF_ARRAY_ELEMS(av_pix_fmt_descriptors))
+        return AV_PIX_FMT_NONE;
+
+    return desc - av_pix_fmt_descriptors;
+}
+
+int av_pix_fmt_get_chroma_sub_sample(enum AVPixelFormat pix_fmt,
+                                     int *h_shift, int *v_shift)
+{
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
+    if (!desc)
+        return AVERROR(ENOSYS);
+    *h_shift = desc->log2_chroma_w;
+    *v_shift = desc->log2_chroma_h;
+
+    return 0;
+}
diff --git a/libavutil/pixdesc.h b/libavutil/pixdesc.h
index f0ae24d..ca0722e 100644
--- a/libavutil/pixdesc.h
+++ b/libavutil/pixdesc.h
@@ -24,7 +24,6 @@
 
 #include <inttypes.h>
 #include "pixfmt.h"
-#include "symbols.h"
 
 typedef struct AVComponentDescriptor{
     uint16_t plane        :2;            ///< which of the 4 planes contains the component
@@ -100,10 +99,15 @@
  */
 #define PIX_FMT_PSEUDOPAL 64
 
+#define PIX_FMT_ALPHA   128 ///< The pixel format has an alpha channel
+
+
+#if FF_API_PIX_FMT_DESC
 /**
  * The array of all the pixel format descriptors.
  */
-extern AVUTIL_SYMBOL const AVPixFmtDescriptor av_pix_fmt_descriptors[];
+extern const AVPixFmtDescriptor av_pix_fmt_descriptors[];
+#endif
 
 /**
  * Read a line from an image, and write the values of the
@@ -150,9 +154,9 @@
  * For example in a little-endian system, first looks 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, returns AV_PIX_FMT_NONE.
  */
-enum PixelFormat av_get_pix_fmt(const char *name);
+enum AVPixelFormat av_get_pix_fmt(const char *name);
 
 /**
  * Return the short name for a pixel format, NULL in case pix_fmt is
@@ -160,7 +164,7 @@
  *
  * @see av_get_pix_fmt(), av_get_pix_fmt_string()
  */
-const char *av_get_pix_fmt_name(enum PixelFormat pix_fmt);
+const char *av_get_pix_fmt_name(enum AVPixelFormat pix_fmt);
 
 /**
  * Print in buf the string corresponding to the pixel format with
@@ -172,7 +176,7 @@
  * 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);
+char *av_get_pix_fmt_string (char *buf, int buf_size, enum AVPixelFormat pix_fmt);
 
 /**
  * Return the number of bits per pixel used by the pixel format
@@ -184,4 +188,50 @@
  */
 int av_get_bits_per_pixel(const AVPixFmtDescriptor *pixdesc);
 
+/**
+ * Return the number of bits per pixel for the pixel format
+ * described by pixdesc, including any padding or unused bits.
+ */
+int av_get_padded_bits_per_pixel(const AVPixFmtDescriptor *pixdesc);
+
+/**
+ * @return a pixel format descriptor for provided pixel format or NULL if
+ * this pixel format is unknown.
+ */
+const AVPixFmtDescriptor *av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt);
+
+/**
+ * Iterate over all pixel format descriptors known to libavutil.
+ *
+ * @param prev previous descriptor. NULL to get the first descriptor.
+ *
+ * @return next descriptor or NULL after the last descriptor
+ */
+const AVPixFmtDescriptor *av_pix_fmt_desc_next(const AVPixFmtDescriptor *prev);
+
+/**
+ * @return an AVPixelFormat id described by desc, or AV_PIX_FMT_NONE if desc
+ * is not a valid pointer to a pixel format descriptor.
+ */
+enum AVPixelFormat av_pix_fmt_desc_get_id(const AVPixFmtDescriptor *desc);
+
+/**
+ * Utility function to access log2_chroma_w log2_chroma_h from
+ * the pixel format AVPixFmtDescriptor.
+ *
+ * See avcodec_get_chroma_sub_sample() for a function that asserts a
+ * valid pixel format instead of returning an error code.
+ * Its recommanded that you use avcodec_get_chroma_sub_sample unless
+ * you do check the return code!
+ *
+ * @param[in]  pix_fmt the pixel format
+ * @param[out] h_shift store log2_chroma_h
+ * @param[out] v_shift store log2_chroma_w
+ *
+ * @return 0 on success, AVERROR(ENOSYS) on invalid or unknown pixel format
+ */
+int av_pix_fmt_get_chroma_sub_sample(enum AVPixelFormat pix_fmt,
+                                     int *h_shift, int *v_shift);
+
+
 #endif /* AVUTIL_PIXDESC_H */
diff --git a/libavutil/pixfmt.h b/libavutil/pixfmt.h
index fa771bc..8903b60 100644
--- a/libavutil/pixfmt.h
+++ b/libavutil/pixfmt.h
@@ -28,6 +28,7 @@
  */
 
 #include "libavutil/avconfig.h"
+#include "libavutil/version.h"
 
 #define AVPALETTE_SIZE 1024
 #define AVPALETTE_COUNT 256
@@ -62,197 +63,294 @@
  * and that all newly added little endian formats have pix_fmt&1==0
  * this allows simpler detection of big vs little endian.
  */
-enum PixelFormat {
-    PIX_FMT_NONE= -1,
-    PIX_FMT_YUV420P,   ///< planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
-    PIX_FMT_YUYV422,   ///< packed YUV 4:2:2, 16bpp, Y0 Cb Y1 Cr
-    PIX_FMT_RGB24,     ///< packed RGB 8:8:8, 24bpp, RGBRGB...
-    PIX_FMT_BGR24,     ///< packed RGB 8:8:8, 24bpp, BGRBGR...
-    PIX_FMT_YUV422P,   ///< planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
-    PIX_FMT_YUV444P,   ///< planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
-    PIX_FMT_YUV410P,   ///< planar YUV 4:1:0,  9bpp, (1 Cr & Cb sample per 4x4 Y samples)
-    PIX_FMT_YUV411P,   ///< planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples)
-    PIX_FMT_GRAY8,     ///<        Y        ,  8bpp
-    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), 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
-    PIX_FMT_UYYVYY411, ///< packed YUV 4:1:1, 12bpp, Cb Y0 Y1 Cr Y2 Y3
-    PIX_FMT_BGR8,      ///< packed RGB 3:3:2,  8bpp, (msb)2B 3G 3R(lsb)
-    PIX_FMT_BGR4,      ///< packed RGB 1:2:1 bitstream,  4bpp, (msb)1B 2G 1R(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits
-    PIX_FMT_BGR4_BYTE, ///< packed RGB 1:2:1,  8bpp, (msb)1B 2G 1R(lsb)
-    PIX_FMT_RGB8,      ///< packed RGB 3:3:2,  8bpp, (msb)2R 3G 3B(lsb)
-    PIX_FMT_RGB4,      ///< packed RGB 1:2:1 bitstream,  4bpp, (msb)1R 2G 1B(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits
-    PIX_FMT_RGB4_BYTE, ///< packed RGB 1:2:1,  8bpp, (msb)1R 2G 1B(lsb)
-    PIX_FMT_NV12,      ///< planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (first byte U and the following byte V)
-    PIX_FMT_NV21,      ///< as above, but U and V bytes are swapped
+enum AVPixelFormat {
+    AV_PIX_FMT_NONE = -1,
+    AV_PIX_FMT_YUV420P,   ///< planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
+    AV_PIX_FMT_YUYV422,   ///< packed YUV 4:2:2, 16bpp, Y0 Cb Y1 Cr
+    AV_PIX_FMT_RGB24,     ///< packed RGB 8:8:8, 24bpp, RGBRGB...
+    AV_PIX_FMT_BGR24,     ///< packed RGB 8:8:8, 24bpp, BGRBGR...
+    AV_PIX_FMT_YUV422P,   ///< planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
+    AV_PIX_FMT_YUV444P,   ///< planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
+    AV_PIX_FMT_YUV410P,   ///< planar YUV 4:1:0,  9bpp, (1 Cr & Cb sample per 4x4 Y samples)
+    AV_PIX_FMT_YUV411P,   ///< planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples)
+    AV_PIX_FMT_GRAY8,     ///<        Y        ,  8bpp
+    AV_PIX_FMT_MONOWHITE, ///<        Y        ,  1bpp, 0 is white, 1 is black, in each byte pixels are ordered from the msb to the lsb
+    AV_PIX_FMT_MONOBLACK, ///<        Y        ,  1bpp, 0 is black, 1 is white, in each byte pixels are ordered from the msb to the lsb
+    AV_PIX_FMT_PAL8,      ///< 8 bit with PIX_FMT_RGB32 palette
+    AV_PIX_FMT_YUVJ420P,  ///< planar YUV 4:2:0, 12bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV420P and setting color_range
+    AV_PIX_FMT_YUVJ422P,  ///< planar YUV 4:2:2, 16bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV422P and setting color_range
+    AV_PIX_FMT_YUVJ444P,  ///< planar YUV 4:4:4, 24bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV444P and setting color_range
+    AV_PIX_FMT_XVMC_MPEG2_MC,///< XVideo Motion Acceleration via common packet passing
+    AV_PIX_FMT_XVMC_MPEG2_IDCT,
+    AV_PIX_FMT_UYVY422,   ///< packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1
+    AV_PIX_FMT_UYYVYY411, ///< packed YUV 4:1:1, 12bpp, Cb Y0 Y1 Cr Y2 Y3
+    AV_PIX_FMT_BGR8,      ///< packed RGB 3:3:2,  8bpp, (msb)2B 3G 3R(lsb)
+    AV_PIX_FMT_BGR4,      ///< packed RGB 1:2:1 bitstream,  4bpp, (msb)1B 2G 1R(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits
+    AV_PIX_FMT_BGR4_BYTE, ///< packed RGB 1:2:1,  8bpp, (msb)1B 2G 1R(lsb)
+    AV_PIX_FMT_RGB8,      ///< packed RGB 3:3:2,  8bpp, (msb)2R 3G 3B(lsb)
+    AV_PIX_FMT_RGB4,      ///< packed RGB 1:2:1 bitstream,  4bpp, (msb)1R 2G 1B(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits
+    AV_PIX_FMT_RGB4_BYTE, ///< packed RGB 1:2:1,  8bpp, (msb)1R 2G 1B(lsb)
+    AV_PIX_FMT_NV12,      ///< planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (first byte U and the following byte V)
+    AV_PIX_FMT_NV21,      ///< as above, but U and V bytes are swapped
 
-    PIX_FMT_ARGB,      ///< packed ARGB 8:8:8:8, 32bpp, ARGBARGB...
-    PIX_FMT_RGBA,      ///< packed RGBA 8:8:8:8, 32bpp, RGBARGBA...
-    PIX_FMT_ABGR,      ///< packed ABGR 8:8:8:8, 32bpp, ABGRABGR...
-    PIX_FMT_BGRA,      ///< packed BGRA 8:8:8:8, 32bpp, BGRABGRA...
+    AV_PIX_FMT_ARGB,      ///< packed ARGB 8:8:8:8, 32bpp, ARGBARGB...
+    AV_PIX_FMT_RGBA,      ///< packed RGBA 8:8:8:8, 32bpp, RGBARGBA...
+    AV_PIX_FMT_ABGR,      ///< packed ABGR 8:8:8:8, 32bpp, ABGRABGR...
+    AV_PIX_FMT_BGRA,      ///< packed BGRA 8:8:8:8, 32bpp, BGRABGRA...
 
-    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), 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
-    PIX_FMT_VDPAU_MPEG2,///< MPEG-2 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_WMV3,///< WMV3 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_VC1, ///< VC-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
-    PIX_FMT_RGB48BE,   ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as big-endian
-    PIX_FMT_RGB48LE,   ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as little-endian
+    AV_PIX_FMT_GRAY16BE,  ///<        Y        , 16bpp, big-endian
+    AV_PIX_FMT_GRAY16LE,  ///<        Y        , 16bpp, little-endian
+    AV_PIX_FMT_YUV440P,   ///< planar YUV 4:4:0 (1 Cr & Cb sample per 1x2 Y samples)
+    AV_PIX_FMT_YUVJ440P,  ///< planar YUV 4:4:0 full scale (JPEG), deprecated in favor of PIX_FMT_YUV440P and setting color_range
+    AV_PIX_FMT_YUVA420P,  ///< planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples)
+    AV_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
+    AV_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
+    AV_PIX_FMT_VDPAU_MPEG2,///< MPEG-2 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
+    AV_PIX_FMT_VDPAU_WMV3,///< WMV3 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
+    AV_PIX_FMT_VDPAU_VC1, ///< VC-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
+    AV_PIX_FMT_RGB48BE,   ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as big-endian
+    AV_PIX_FMT_RGB48LE,   ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as little-endian
 
-    PIX_FMT_RGB565BE,  ///< packed RGB 5:6:5, 16bpp, (msb)   5R 6G 5B(lsb), big-endian
-    PIX_FMT_RGB565LE,  ///< packed RGB 5:6:5, 16bpp, (msb)   5R 6G 5B(lsb), little-endian
-    PIX_FMT_RGB555BE,  ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), big-endian, most significant bit to 0
-    PIX_FMT_RGB555LE,  ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), little-endian, most significant bit to 0
+    AV_PIX_FMT_RGB565BE,  ///< packed RGB 5:6:5, 16bpp, (msb)   5R 6G 5B(lsb), big-endian
+    AV_PIX_FMT_RGB565LE,  ///< packed RGB 5:6:5, 16bpp, (msb)   5R 6G 5B(lsb), little-endian
+    AV_PIX_FMT_RGB555BE,  ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), big-endian, most significant bit to 0
+    AV_PIX_FMT_RGB555LE,  ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), little-endian, most significant bit to 0
 
-    PIX_FMT_BGR565BE,  ///< packed BGR 5:6:5, 16bpp, (msb)   5B 6G 5R(lsb), big-endian
-    PIX_FMT_BGR565LE,  ///< packed BGR 5:6:5, 16bpp, (msb)   5B 6G 5R(lsb), little-endian
-    PIX_FMT_BGR555BE,  ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), big-endian, most significant bit to 1
-    PIX_FMT_BGR555LE,  ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), little-endian, most significant bit to 1
+    AV_PIX_FMT_BGR565BE,  ///< packed BGR 5:6:5, 16bpp, (msb)   5B 6G 5R(lsb), big-endian
+    AV_PIX_FMT_BGR565LE,  ///< packed BGR 5:6:5, 16bpp, (msb)   5B 6G 5R(lsb), little-endian
+    AV_PIX_FMT_BGR555BE,  ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), big-endian, most significant bit to 1
+    AV_PIX_FMT_BGR555LE,  ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), little-endian, most significant bit to 1
 
-    PIX_FMT_VAAPI_MOCO, ///< HW acceleration through VA API at motion compensation entry-point, Picture.data[3] contains a vaapi_render_state struct which contains macroblocks as well as various fields extracted from headers
-    PIX_FMT_VAAPI_IDCT, ///< HW acceleration through VA API at IDCT entry-point, Picture.data[3] contains a vaapi_render_state struct which contains fields extracted from headers
-    PIX_FMT_VAAPI_VLD,  ///< HW decoding through VA API, Picture.data[3] contains a vaapi_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+    AV_PIX_FMT_VAAPI_MOCO, ///< HW acceleration through VA API at motion compensation entry-point, Picture.data[3] contains a vaapi_render_state struct which contains macroblocks as well as various fields extracted from headers
+    AV_PIX_FMT_VAAPI_IDCT, ///< HW acceleration through VA API at IDCT entry-point, Picture.data[3] contains a vaapi_render_state struct which contains fields extracted from headers
+    AV_PIX_FMT_VAAPI_VLD,  ///< HW decoding through VA API, Picture.data[3] contains a vaapi_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
 
-    PIX_FMT_YUV420P16LE,  ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
-    PIX_FMT_YUV420P16BE,  ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
-    PIX_FMT_YUV422P16LE,  ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
-    PIX_FMT_YUV422P16BE,  ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
-    PIX_FMT_YUV444P16LE,  ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
-    PIX_FMT_YUV444P16BE,  ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
-    PIX_FMT_VDPAU_MPEG4,  ///< MPEG4 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_DXVA2_VLD,    ///< HW decoding through DXVA2, Picture.data[3] contains a LPDIRECT3DSURFACE9 pointer
+    AV_PIX_FMT_YUV420P16LE,  ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    AV_PIX_FMT_YUV420P16BE,  ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    AV_PIX_FMT_YUV422P16LE,  ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    AV_PIX_FMT_YUV422P16BE,  ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    AV_PIX_FMT_YUV444P16LE,  ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    AV_PIX_FMT_YUV444P16BE,  ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    AV_PIX_FMT_VDPAU_MPEG4,  ///< MPEG4 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
+    AV_PIX_FMT_DXVA2_VLD,    ///< HW decoding through DXVA2, Picture.data[3] contains a LPDIRECT3DSURFACE9 pointer
 
-    PIX_FMT_RGB444LE,  ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), little-endian, most significant bits to 0
-    PIX_FMT_RGB444BE,  ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), big-endian, most significant bits to 0
-    PIX_FMT_BGR444LE,  ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), little-endian, most significant bits to 1
-    PIX_FMT_BGR444BE,  ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), big-endian, most significant bits to 1
-    PIX_FMT_GRAY8A,    ///< 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
+    AV_PIX_FMT_RGB444LE,  ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), little-endian, most significant bits to 0
+    AV_PIX_FMT_RGB444BE,  ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), big-endian, most significant bits to 0
+    AV_PIX_FMT_BGR444LE,  ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), little-endian, most significant bits to 1
+    AV_PIX_FMT_BGR444BE,  ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), big-endian, most significant bits to 1
+    AV_PIX_FMT_GRAY8A,    ///< 8bit gray, 8bit alpha
+    AV_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
+    AV_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
 
     //the following 10 formats have the disadvantage of needing 1 format for each bit depth, thus
-    //If you want to support multiple bit depths, then using PIX_FMT_YUV420P16* with the bpp stored separately
+    //If you want to support multiple bit depths, then using AV_PIX_FMT_YUV420P16* with the bpp stored separately
     //is better
-    PIX_FMT_YUV420P9BE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
-    PIX_FMT_YUV420P9LE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
-    PIX_FMT_YUV420P10BE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
-    PIX_FMT_YUV420P10LE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
-    PIX_FMT_YUV422P10BE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
-    PIX_FMT_YUV422P10LE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
-    PIX_FMT_YUV444P9BE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
-    PIX_FMT_YUV444P9LE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
-    PIX_FMT_YUV444P10BE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
-    PIX_FMT_YUV444P10LE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
-    PIX_FMT_YUV422P9BE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
-    PIX_FMT_YUV422P9LE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
-    PIX_FMT_VDA_VLD,    ///< hardware decoding through VDA
+    AV_PIX_FMT_YUV420P9BE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    AV_PIX_FMT_YUV420P9LE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    AV_PIX_FMT_YUV420P10BE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    AV_PIX_FMT_YUV420P10LE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    AV_PIX_FMT_YUV422P10BE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    AV_PIX_FMT_YUV422P10LE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    AV_PIX_FMT_YUV444P9BE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    AV_PIX_FMT_YUV444P9LE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    AV_PIX_FMT_YUV444P10BE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    AV_PIX_FMT_YUV444P10LE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    AV_PIX_FMT_YUV422P9BE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    AV_PIX_FMT_YUV422P9LE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    AV_PIX_FMT_VDA_VLD,    ///< hardware decoding through VDA
 
 #ifdef AV_PIX_FMT_ABI_GIT_MASTER
-    PIX_FMT_RGBA64BE,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
-    PIX_FMT_RGBA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
-    PIX_FMT_BGRA64BE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
-    PIX_FMT_BGRA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
+    AV_PIX_FMT_RGBA64BE,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
+    AV_PIX_FMT_RGBA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
+    AV_PIX_FMT_BGRA64BE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
+    AV_PIX_FMT_BGRA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
 #endif
-    PIX_FMT_GBRP,      ///< planar GBR 4:4:4 24bpp
-    PIX_FMT_GBRP9BE,   ///< planar GBR 4:4:4 27bpp, big endian
-    PIX_FMT_GBRP9LE,   ///< planar GBR 4:4:4 27bpp, little endian
-    PIX_FMT_GBRP10BE,  ///< planar GBR 4:4:4 30bpp, big endian
-    PIX_FMT_GBRP10LE,  ///< planar GBR 4:4:4 30bpp, little endian
-    PIX_FMT_GBRP16BE,  ///< planar GBR 4:4:4 48bpp, big endian
-    PIX_FMT_GBRP16LE,  ///< planar GBR 4:4:4 48bpp, little endian
+    AV_PIX_FMT_GBRP,      ///< planar GBR 4:4:4 24bpp
+    AV_PIX_FMT_GBRP9BE,   ///< planar GBR 4:4:4 27bpp, big endian
+    AV_PIX_FMT_GBRP9LE,   ///< planar GBR 4:4:4 27bpp, little endian
+    AV_PIX_FMT_GBRP10BE,  ///< planar GBR 4:4:4 30bpp, big endian
+    AV_PIX_FMT_GBRP10LE,  ///< planar GBR 4:4:4 30bpp, little endian
+    AV_PIX_FMT_GBRP16BE,  ///< planar GBR 4:4:4 48bpp, big endian
+    AV_PIX_FMT_GBRP16LE,  ///< planar GBR 4:4:4 48bpp, little endian
+
+    /**
+     * duplicated pixel formats for compatibility with libav.
+     * FFmpeg supports these formats since May 8 2012 and Jan 28 2012 (commits f9ca1ac7 and 143a5c55)
+     * Libav added them Oct 12 2012 with incompatible values (commit 6d5600e85)
+     */
+    AV_PIX_FMT_YUVA422P_LIBAV,  ///< planar YUV 4:2:2 24bpp, (1 Cr & Cb sample per 2x1 Y & A samples)
+    AV_PIX_FMT_YUVA444P_LIBAV,  ///< planar YUV 4:4:4 32bpp, (1 Cr & Cb sample per 1x1 Y & A samples)
+
+    AV_PIX_FMT_YUVA420P9BE,  ///< planar YUV 4:2:0 22.5bpp, (1 Cr & Cb sample per 2x2 Y & A samples), big endian
+    AV_PIX_FMT_YUVA420P9LE,  ///< planar YUV 4:2:0 22.5bpp, (1 Cr & Cb sample per 2x2 Y & A samples), little endian
+    AV_PIX_FMT_YUVA422P9BE,  ///< planar YUV 4:2:2 27bpp, (1 Cr & Cb sample per 2x1 Y & A samples), big endian
+    AV_PIX_FMT_YUVA422P9LE,  ///< planar YUV 4:2:2 27bpp, (1 Cr & Cb sample per 2x1 Y & A samples), little endian
+    AV_PIX_FMT_YUVA444P9BE,  ///< planar YUV 4:4:4 36bpp, (1 Cr & Cb sample per 1x1 Y & A samples), big endian
+    AV_PIX_FMT_YUVA444P9LE,  ///< planar YUV 4:4:4 36bpp, (1 Cr & Cb sample per 1x1 Y & A samples), little endian
+    AV_PIX_FMT_YUVA420P10BE, ///< planar YUV 4:2:0 25bpp, (1 Cr & Cb sample per 2x2 Y & A samples, big endian)
+    AV_PIX_FMT_YUVA420P10LE, ///< planar YUV 4:2:0 25bpp, (1 Cr & Cb sample per 2x2 Y & A samples, little endian)
+    AV_PIX_FMT_YUVA422P10BE, ///< planar YUV 4:2:2 30bpp, (1 Cr & Cb sample per 2x1 Y & A samples, big endian)
+    AV_PIX_FMT_YUVA422P10LE, ///< planar YUV 4:2:2 30bpp, (1 Cr & Cb sample per 2x1 Y & A samples, little endian)
+    AV_PIX_FMT_YUVA444P10BE, ///< planar YUV 4:4:4 40bpp, (1 Cr & Cb sample per 1x1 Y & A samples, big endian)
+    AV_PIX_FMT_YUVA444P10LE, ///< planar YUV 4:4:4 40bpp, (1 Cr & Cb sample per 1x1 Y & A samples, little endian)
+    AV_PIX_FMT_YUVA420P16BE, ///< planar YUV 4:2:0 40bpp, (1 Cr & Cb sample per 2x2 Y & A samples, big endian)
+    AV_PIX_FMT_YUVA420P16LE, ///< planar YUV 4:2:0 40bpp, (1 Cr & Cb sample per 2x2 Y & A samples, little endian)
+    AV_PIX_FMT_YUVA422P16BE, ///< planar YUV 4:2:2 48bpp, (1 Cr & Cb sample per 2x1 Y & A samples, big endian)
+    AV_PIX_FMT_YUVA422P16LE, ///< planar YUV 4:2:2 48bpp, (1 Cr & Cb sample per 2x1 Y & A samples, little endian)
+    AV_PIX_FMT_YUVA444P16BE, ///< planar YUV 4:4:4 64bpp, (1 Cr & Cb sample per 1x1 Y & A samples, big endian)
+    AV_PIX_FMT_YUVA444P16LE, ///< planar YUV 4:4:4 64bpp, (1 Cr & Cb sample per 1x1 Y & A samples, little endian)
 
 #ifndef AV_PIX_FMT_ABI_GIT_MASTER
-    PIX_FMT_RGBA64BE=0x123,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
-    PIX_FMT_RGBA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
-    PIX_FMT_BGRA64BE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
-    PIX_FMT_BGRA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
+    AV_PIX_FMT_RGBA64BE=0x123,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
+    AV_PIX_FMT_RGBA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
+    AV_PIX_FMT_BGRA64BE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
+    AV_PIX_FMT_BGRA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
 #endif
-    PIX_FMT_0RGB=0x123+4,      ///< packed RGB 8:8:8, 32bpp, 0RGB0RGB...
-    PIX_FMT_RGB0,      ///< packed RGB 8:8:8, 32bpp, RGB0RGB0...
-    PIX_FMT_0BGR,      ///< packed BGR 8:8:8, 32bpp, 0BGR0BGR...
-    PIX_FMT_BGR0,      ///< packed BGR 8:8:8, 32bpp, BGR0BGR0...
-    PIX_FMT_YUVA444P,  ///< planar YUV 4:4:4 32bpp, (1 Cr & Cb sample per 1x1 Y & A samples)
-    PIX_FMT_YUVA422P,  ///< planar YUV 4:2:2 24bpp, (1 Cr & Cb sample per 2x1 Y & A samples)
+    AV_PIX_FMT_0RGB=0x123+4,      ///< packed RGB 8:8:8, 32bpp, 0RGB0RGB...
+    AV_PIX_FMT_RGB0,      ///< packed RGB 8:8:8, 32bpp, RGB0RGB0...
+    AV_PIX_FMT_0BGR,      ///< packed BGR 8:8:8, 32bpp, 0BGR0BGR...
+    AV_PIX_FMT_BGR0,      ///< packed BGR 8:8:8, 32bpp, BGR0BGR0...
+    AV_PIX_FMT_YUVA444P,  ///< planar YUV 4:4:4 32bpp, (1 Cr & Cb sample per 1x1 Y & A samples)
+    AV_PIX_FMT_YUVA422P,  ///< planar YUV 4:2:2 24bpp, (1 Cr & Cb sample per 2x1 Y & A samples)
 
-    PIX_FMT_YUV420P12BE, ///< planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
-    PIX_FMT_YUV420P12LE, ///< planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
-    PIX_FMT_YUV420P14BE, ///< planar YUV 4:2:0,21bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
-    PIX_FMT_YUV420P14LE, ///< planar YUV 4:2:0,21bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
-    PIX_FMT_YUV422P12BE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
-    PIX_FMT_YUV422P12LE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
-    PIX_FMT_YUV422P14BE, ///< planar YUV 4:2:2,28bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
-    PIX_FMT_YUV422P14LE, ///< planar YUV 4:2:2,28bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
-    PIX_FMT_YUV444P12BE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
-    PIX_FMT_YUV444P12LE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
-    PIX_FMT_YUV444P14BE, ///< planar YUV 4:4:4,42bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
-    PIX_FMT_YUV444P14LE, ///< planar YUV 4:4:4,42bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
-    PIX_FMT_GBRP12BE,    ///< planar GBR 4:4:4 36bpp, big endian
-    PIX_FMT_GBRP12LE,    ///< planar GBR 4:4:4 36bpp, little endian
-    PIX_FMT_GBRP14BE,    ///< planar GBR 4:4:4 42bpp, big endian
-    PIX_FMT_GBRP14LE,    ///< planar GBR 4:4:4 42bpp, little endian
+    AV_PIX_FMT_YUV420P12BE, ///< planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    AV_PIX_FMT_YUV420P12LE, ///< planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    AV_PIX_FMT_YUV420P14BE, ///< planar YUV 4:2:0,21bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    AV_PIX_FMT_YUV420P14LE, ///< planar YUV 4:2:0,21bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    AV_PIX_FMT_YUV422P12BE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    AV_PIX_FMT_YUV422P12LE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    AV_PIX_FMT_YUV422P14BE, ///< planar YUV 4:2:2,28bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    AV_PIX_FMT_YUV422P14LE, ///< planar YUV 4:2:2,28bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    AV_PIX_FMT_YUV444P12BE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    AV_PIX_FMT_YUV444P12LE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    AV_PIX_FMT_YUV444P14BE, ///< planar YUV 4:4:4,42bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    AV_PIX_FMT_YUV444P14LE, ///< planar YUV 4:4:4,42bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    AV_PIX_FMT_GBRP12BE,    ///< planar GBR 4:4:4 36bpp, big endian
+    AV_PIX_FMT_GBRP12LE,    ///< planar GBR 4:4:4 36bpp, little endian
+    AV_PIX_FMT_GBRP14BE,    ///< planar GBR 4:4:4 42bpp, big endian
+    AV_PIX_FMT_GBRP14LE,    ///< planar GBR 4:4:4 42bpp, 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
+    AV_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
+
+#if FF_API_PIX_FMT
+#include "old_pix_fmts.h"
+#endif
 };
 
-#define PIX_FMT_Y400A PIX_FMT_GRAY8A
-#define PIX_FMT_GBR24P PIX_FMT_GBRP
-
-#if AV_HAVE_BIGENDIAN
-#   define PIX_FMT_NE(be, le) PIX_FMT_##be
-#else
-#   define PIX_FMT_NE(be, le) PIX_FMT_##le
+#if AV_HAVE_INCOMPATIBLE_FORK_ABI
+#define AV_PIX_FMT_YUVA422P AV_PIX_FMT_YUVA422P_LIBAV
+#define AV_PIX_FMT_YUVA444P AV_PIX_FMT_YUVA444P_LIBAV
 #endif
 
-#define PIX_FMT_RGB32   PIX_FMT_NE(ARGB, BGRA)
-#define PIX_FMT_RGB32_1 PIX_FMT_NE(RGBA, ABGR)
-#define PIX_FMT_BGR32   PIX_FMT_NE(ABGR, RGBA)
-#define PIX_FMT_BGR32_1 PIX_FMT_NE(BGRA, ARGB)
-#define PIX_FMT_0RGB32  PIX_FMT_NE(0RGB, BGR0)
-#define PIX_FMT_0BGR32  PIX_FMT_NE(0BGR, RGB0)
 
-#define PIX_FMT_GRAY16 PIX_FMT_NE(GRAY16BE, GRAY16LE)
-#define PIX_FMT_RGB48  PIX_FMT_NE(RGB48BE,  RGB48LE)
-#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)
+#define AV_PIX_FMT_Y400A AV_PIX_FMT_GRAY8A
+#define AV_PIX_FMT_GBR24P AV_PIX_FMT_GBRP
 
-#define PIX_FMT_YUV420P9  PIX_FMT_NE(YUV420P9BE , YUV420P9LE)
-#define PIX_FMT_YUV422P9  PIX_FMT_NE(YUV422P9BE , YUV422P9LE)
-#define PIX_FMT_YUV444P9  PIX_FMT_NE(YUV444P9BE , YUV444P9LE)
-#define PIX_FMT_YUV420P10 PIX_FMT_NE(YUV420P10BE, YUV420P10LE)
-#define PIX_FMT_YUV422P10 PIX_FMT_NE(YUV422P10BE, YUV422P10LE)
-#define PIX_FMT_YUV444P10 PIX_FMT_NE(YUV444P10BE, YUV444P10LE)
-#define PIX_FMT_YUV420P12 PIX_FMT_NE(YUV420P12BE, YUV420P12LE)
-#define PIX_FMT_YUV422P12 PIX_FMT_NE(YUV422P12BE, YUV422P12LE)
-#define PIX_FMT_YUV444P12 PIX_FMT_NE(YUV444P12BE, YUV444P12LE)
-#define PIX_FMT_YUV420P14 PIX_FMT_NE(YUV420P14BE, YUV420P14LE)
-#define PIX_FMT_YUV422P14 PIX_FMT_NE(YUV422P14BE, YUV422P14LE)
-#define PIX_FMT_YUV444P14 PIX_FMT_NE(YUV444P14BE, YUV444P14LE)
-#define PIX_FMT_YUV420P16 PIX_FMT_NE(YUV420P16BE, YUV420P16LE)
-#define PIX_FMT_YUV422P16 PIX_FMT_NE(YUV422P16BE, YUV422P16LE)
-#define PIX_FMT_YUV444P16 PIX_FMT_NE(YUV444P16BE, YUV444P16LE)
+#if AV_HAVE_BIGENDIAN
+#   define AV_PIX_FMT_NE(be, le) AV_PIX_FMT_##be
+#else
+#   define AV_PIX_FMT_NE(be, le) AV_PIX_FMT_##le
+#endif
 
-#define PIX_FMT_RGBA64 PIX_FMT_NE(RGBA64BE, RGBA64LE)
-#define PIX_FMT_BGRA64 PIX_FMT_NE(BGRA64BE, BGRA64LE)
-#define PIX_FMT_GBRP9     PIX_FMT_NE(GBRP9BE ,    GBRP9LE)
-#define PIX_FMT_GBRP10    PIX_FMT_NE(GBRP10BE,    GBRP10LE)
-#define PIX_FMT_GBRP12    PIX_FMT_NE(GBRP12BE,    GBRP12LE)
-#define PIX_FMT_GBRP14    PIX_FMT_NE(GBRP14BE,    GBRP14LE)
-#define PIX_FMT_GBRP16    PIX_FMT_NE(GBRP16BE,    GBRP16LE)
+#define AV_PIX_FMT_RGB32   AV_PIX_FMT_NE(ARGB, BGRA)
+#define AV_PIX_FMT_RGB32_1 AV_PIX_FMT_NE(RGBA, ABGR)
+#define AV_PIX_FMT_BGR32   AV_PIX_FMT_NE(ABGR, RGBA)
+#define AV_PIX_FMT_BGR32_1 AV_PIX_FMT_NE(BGRA, ARGB)
+#define AV_PIX_FMT_0RGB32  AV_PIX_FMT_NE(0RGB, BGR0)
+#define AV_PIX_FMT_0BGR32  AV_PIX_FMT_NE(0BGR, RGB0)
+
+#define AV_PIX_FMT_GRAY16 AV_PIX_FMT_NE(GRAY16BE, GRAY16LE)
+#define AV_PIX_FMT_RGB48  AV_PIX_FMT_NE(RGB48BE,  RGB48LE)
+#define AV_PIX_FMT_RGB565 AV_PIX_FMT_NE(RGB565BE, RGB565LE)
+#define AV_PIX_FMT_RGB555 AV_PIX_FMT_NE(RGB555BE, RGB555LE)
+#define AV_PIX_FMT_RGB444 AV_PIX_FMT_NE(RGB444BE, RGB444LE)
+#define AV_PIX_FMT_BGR48  AV_PIX_FMT_NE(BGR48BE,  BGR48LE)
+#define AV_PIX_FMT_BGR565 AV_PIX_FMT_NE(BGR565BE, BGR565LE)
+#define AV_PIX_FMT_BGR555 AV_PIX_FMT_NE(BGR555BE, BGR555LE)
+#define AV_PIX_FMT_BGR444 AV_PIX_FMT_NE(BGR444BE, BGR444LE)
+
+#define AV_PIX_FMT_YUV420P9  AV_PIX_FMT_NE(YUV420P9BE , YUV420P9LE)
+#define AV_PIX_FMT_YUV422P9  AV_PIX_FMT_NE(YUV422P9BE , YUV422P9LE)
+#define AV_PIX_FMT_YUV444P9  AV_PIX_FMT_NE(YUV444P9BE , YUV444P9LE)
+#define AV_PIX_FMT_YUV420P10 AV_PIX_FMT_NE(YUV420P10BE, YUV420P10LE)
+#define AV_PIX_FMT_YUV422P10 AV_PIX_FMT_NE(YUV422P10BE, YUV422P10LE)
+#define AV_PIX_FMT_YUV444P10 AV_PIX_FMT_NE(YUV444P10BE, YUV444P10LE)
+#define AV_PIX_FMT_YUV420P12 AV_PIX_FMT_NE(YUV420P12BE, YUV420P12LE)
+#define AV_PIX_FMT_YUV422P12 AV_PIX_FMT_NE(YUV422P12BE, YUV422P12LE)
+#define AV_PIX_FMT_YUV444P12 AV_PIX_FMT_NE(YUV444P12BE, YUV444P12LE)
+#define AV_PIX_FMT_YUV420P14 AV_PIX_FMT_NE(YUV420P14BE, YUV420P14LE)
+#define AV_PIX_FMT_YUV422P14 AV_PIX_FMT_NE(YUV422P14BE, YUV422P14LE)
+#define AV_PIX_FMT_YUV444P14 AV_PIX_FMT_NE(YUV444P14BE, YUV444P14LE)
+#define AV_PIX_FMT_YUV420P16 AV_PIX_FMT_NE(YUV420P16BE, YUV420P16LE)
+#define AV_PIX_FMT_YUV422P16 AV_PIX_FMT_NE(YUV422P16BE, YUV422P16LE)
+#define AV_PIX_FMT_YUV444P16 AV_PIX_FMT_NE(YUV444P16BE, YUV444P16LE)
+
+#define AV_PIX_FMT_RGBA64 AV_PIX_FMT_NE(RGBA64BE, RGBA64LE)
+#define AV_PIX_FMT_BGRA64 AV_PIX_FMT_NE(BGRA64BE, BGRA64LE)
+#define AV_PIX_FMT_GBRP9     AV_PIX_FMT_NE(GBRP9BE ,    GBRP9LE)
+#define AV_PIX_FMT_GBRP10    AV_PIX_FMT_NE(GBRP10BE,    GBRP10LE)
+#define AV_PIX_FMT_GBRP12    AV_PIX_FMT_NE(GBRP12BE,    GBRP12LE)
+#define AV_PIX_FMT_GBRP14    AV_PIX_FMT_NE(GBRP14BE,    GBRP14LE)
+#define AV_PIX_FMT_GBRP16    AV_PIX_FMT_NE(GBRP16BE,    GBRP16LE)
+
+#define AV_PIX_FMT_YUVA420P9  AV_PIX_FMT_NE(YUVA420P9BE , YUVA420P9LE)
+#define AV_PIX_FMT_YUVA422P9  AV_PIX_FMT_NE(YUVA422P9BE , YUVA422P9LE)
+#define AV_PIX_FMT_YUVA444P9  AV_PIX_FMT_NE(YUVA444P9BE , YUVA444P9LE)
+#define AV_PIX_FMT_YUVA420P10 AV_PIX_FMT_NE(YUVA420P10BE, YUVA420P10LE)
+#define AV_PIX_FMT_YUVA422P10 AV_PIX_FMT_NE(YUVA422P10BE, YUVA422P10LE)
+#define AV_PIX_FMT_YUVA444P10 AV_PIX_FMT_NE(YUVA444P10BE, YUVA444P10LE)
+#define AV_PIX_FMT_YUVA420P16 AV_PIX_FMT_NE(YUVA420P16BE, YUVA420P16LE)
+#define AV_PIX_FMT_YUVA422P16 AV_PIX_FMT_NE(YUVA422P16BE, YUVA422P16LE)
+#define AV_PIX_FMT_YUVA444P16 AV_PIX_FMT_NE(YUVA444P16BE, YUVA444P16LE)
+
+#if FF_API_PIX_FMT
+#define PixelFormat AVPixelFormat
+
+#define PIX_FMT_Y400A AV_PIX_FMT_Y400A
+#define PIX_FMT_GBR24P AV_PIX_FMT_GBR24P
+
+#define PIX_FMT_NE(be, le) AV_PIX_FMT_NE(be, le)
+
+#define PIX_FMT_RGB32   AV_PIX_FMT_RGB32
+#define PIX_FMT_RGB32_1 AV_PIX_FMT_RGB32_1
+#define PIX_FMT_BGR32   AV_PIX_FMT_BGR32
+#define PIX_FMT_BGR32_1 AV_PIX_FMT_BGR32_1
+#define PIX_FMT_0RGB32  AV_PIX_FMT_0RGB32
+#define PIX_FMT_0BGR32  AV_PIX_FMT_0BGR32
+
+#define PIX_FMT_GRAY16 AV_PIX_FMT_GRAY16
+#define PIX_FMT_RGB48  AV_PIX_FMT_RGB48
+#define PIX_FMT_RGB565 AV_PIX_FMT_RGB565
+#define PIX_FMT_RGB555 AV_PIX_FMT_RGB555
+#define PIX_FMT_RGB444 AV_PIX_FMT_RGB444
+#define PIX_FMT_BGR48  AV_PIX_FMT_BGR48
+#define PIX_FMT_BGR565 AV_PIX_FMT_BGR565
+#define PIX_FMT_BGR555 AV_PIX_FMT_BGR555
+#define PIX_FMT_BGR444 AV_PIX_FMT_BGR444
+
+#define PIX_FMT_YUV420P9  AV_PIX_FMT_YUV420P9
+#define PIX_FMT_YUV422P9  AV_PIX_FMT_YUV422P9
+#define PIX_FMT_YUV444P9  AV_PIX_FMT_YUV444P9
+#define PIX_FMT_YUV420P10 AV_PIX_FMT_YUV420P10
+#define PIX_FMT_YUV422P10 AV_PIX_FMT_YUV422P10
+#define PIX_FMT_YUV444P10 AV_PIX_FMT_YUV444P10
+#define PIX_FMT_YUV420P12 AV_PIX_FMT_YUV420P12
+#define PIX_FMT_YUV422P12 AV_PIX_FMT_YUV422P12
+#define PIX_FMT_YUV444P12 AV_PIX_FMT_YUV444P12
+#define PIX_FMT_YUV420P14 AV_PIX_FMT_YUV420P14
+#define PIX_FMT_YUV422P14 AV_PIX_FMT_YUV422P14
+#define PIX_FMT_YUV444P14 AV_PIX_FMT_YUV444P14
+#define PIX_FMT_YUV420P16 AV_PIX_FMT_YUV420P16
+#define PIX_FMT_YUV422P16 AV_PIX_FMT_YUV422P16
+#define PIX_FMT_YUV444P16 AV_PIX_FMT_YUV444P16
+
+#define PIX_FMT_RGBA64 AV_PIX_FMT_RGBA64
+#define PIX_FMT_BGRA64 AV_PIX_FMT_BGRA64
+#define PIX_FMT_GBRP9  AV_PIX_FMT_GBRP9
+#define PIX_FMT_GBRP10 AV_PIX_FMT_GBRP10
+#define PIX_FMT_GBRP12 AV_PIX_FMT_GBRP12
+#define PIX_FMT_GBRP14 AV_PIX_FMT_GBRP14
+#define PIX_FMT_GBRP16 AV_PIX_FMT_GBRP16
+#endif
 
 #endif /* AVUTIL_PIXFMT_H */
diff --git a/libavutil/random_seed.c b/libavutil/random_seed.c
index d1a1fa6..c674704 100644
--- a/libavutil/random_seed.c
+++ b/libavutil/random_seed.c
@@ -23,6 +23,10 @@
 #if HAVE_UNISTD_H
 #include <unistd.h>
 #endif
+#if HAVE_CRYPTGENRANDOM
+#include <windows.h>
+#include <wincrypt.h>
+#endif
 #include <fcntl.h>
 #include <math.h>
 #include <time.h>
@@ -61,7 +65,7 @@
     clock_t last_t  = 0;
     static uint64_t i = 0;
     static uint32_t buffer[512] = {0};
-    unsigned char digest[32];
+    unsigned char digest[20];
     uint64_t last_i = i;
 
     av_assert0(sizeof(tmp) >= av_sha_size);
@@ -95,13 +99,24 @@
     av_sha_init(sha, 160);
     av_sha_update(sha, (uint8_t*)buffer, sizeof(buffer));
     av_sha_final(sha, digest);
-    return AV_RB32(digest) + AV_RB32(digest+32);
+    return AV_RB32(digest) + AV_RB32(digest+16);
 }
 
 uint32_t av_get_random_seed(void)
 {
     uint32_t seed;
 
+#if HAVE_CRYPTGENRANDOM
+    HCRYPTPROV provider;
+    if (CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
+                            CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
+        BOOL ret = CryptGenRandom(provider, sizeof(seed), (PBYTE) &seed);
+        CryptReleaseContext(provider, 0);
+        if (ret)
+            return seed;
+    }
+#endif
+
     if (read_random(&seed, "/dev/urandom") == sizeof(seed))
         return seed;
     if (read_random(&seed, "/dev/random")  == sizeof(seed))
diff --git a/libavutil/rational.c b/libavutil/rational.c
index 1a833eb..768f252 100644
--- a/libavutil/rational.c
+++ b/libavutil/rational.c
@@ -148,7 +148,7 @@
 #ifdef TEST
 int main(void)
 {
-    AVRational a,b;
+    AVRational a,b,r;
     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++) {
@@ -160,8 +160,11 @@
                     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,
+                        av_log(NULL, AV_LOG_ERROR, "%d/%d %d/%d, %d %f\n", a.num,
                                a.den, b.num, b.den, c,d);
+                    r = av_sub_q(av_add_q(b,a), b);
+                    if(b.den && (r.num*a.den != a.num*r.den || !r.num != !a.num || !r.den != !a.den))
+                        av_log(NULL, AV_LOG_ERROR, "%d/%d ", r.num, r.den);
                 }
             }
         }
diff --git a/libavutil/samplefmt.c b/libavutil/samplefmt.c
index a03648e..6f762df 100644
--- a/libavutil/samplefmt.c
+++ b/libavutil/samplefmt.c
@@ -171,7 +171,11 @@
     if (linesize)
         *linesize = line_size;
 
+#if FF_API_SAMPLES_UTILS_RETURN_ZERO
     return 0;
+#else
+    return buf_size;
+#endif
 }
 
 int av_samples_alloc(uint8_t **audio_data, int *linesize, int nb_channels,
@@ -183,7 +187,7 @@
     if (size < 0)
         return size;
 
-    buf = av_mallocz(size);
+    buf = av_malloc(size);
     if (!buf)
         return AVERROR(ENOMEM);
 
@@ -193,7 +197,14 @@
         av_free(buf);
         return size;
     }
+
+    av_samples_set_silence(audio_data, 0, nb_samples, nb_channels, sample_fmt);
+
+#if FF_API_SAMPLES_UTILS_RETURN_ZERO
     return 0;
+#else
+    return size;
+#endif
 }
 
 int av_samples_copy(uint8_t **dst, uint8_t * const *src, int dst_offset,
diff --git a/libavutil/samplefmt.h b/libavutil/samplefmt.h
index 2a7de20..e222ba2 100644
--- a/libavutil/samplefmt.h
+++ b/libavutil/samplefmt.h
@@ -183,7 +183,9 @@
  * @param nb_samples       the number of samples in a single channel
  * @param sample_fmt       the sample format
  * @param align            buffer size alignment (0 = default, 1 = no alignment)
- * @return                 0 on success or a negative error code on failure
+ * @return                 >=0 on success or a negative error code on failure
+ * @todo return minimum size in bytes required for the buffer in case
+ * of success at the next bump
  */
 int av_samples_fill_arrays(uint8_t **audio_data, int *linesize,
                            const uint8_t *buf,
@@ -194,6 +196,7 @@
  * Allocate a samples buffer for nb_samples samples, and fill data pointers and
  * linesize accordingly.
  * The allocated samples buffer can be freed by using av_freep(&audio_data[0])
+ * Allocated data will be initialized to silence.
  *
  * @see enum AVSampleFormat
  * The documentation for AVSampleFormat describes the data layout.
@@ -203,7 +206,8 @@
  * @param nb_channels      number of audio channels
  * @param nb_samples       number of samples per channel
  * @param align            buffer size alignment (0 = default, 1 = no alignment)
- * @return                 0 on success or a negative error code on failure
+ * @return                 >=0 on success or a negative error code on failure
+ * @todo return the size of the allocated buffer in case of success at the next bump
  * @see av_samples_fill_arrays()
  */
 int av_samples_alloc(uint8_t **audio_data, int *linesize, int nb_channels,
diff --git a/libavutil/sha.c b/libavutil/sha.c
index 7194d43..8d5ca45 100644
--- a/libavutil/sha.c
+++ b/libavutil/sha.c
@@ -26,6 +26,7 @@
 #include "bswap.h"
 #include "sha.h"
 #include "intreadwrite.h"
+#include "mem.h"
 
 /** hash context */
 typedef struct AVSHA {
@@ -39,6 +40,11 @@
 
 const int av_sha_size = sizeof(AVSHA);
 
+struct AVSHA *av_sha_alloc(void)
+{
+    return av_mallocz(sizeof(struct AVSHA));
+}
+
 #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
 
 /* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */
@@ -210,7 +216,7 @@
         a = T1 + T2;
     }
 #else
-    for (i = 0; i < 16;) {
+    for (i = 0; i < 16 - 7;) {
         ROUND256_0_TO_15(a, b, c, d, e, f, g, h);
         ROUND256_0_TO_15(h, a, b, c, d, e, f, g);
         ROUND256_0_TO_15(g, h, a, b, c, d, e, f);
@@ -221,7 +227,7 @@
         ROUND256_0_TO_15(b, c, d, e, f, g, h, a);
     }
 
-    for (; i < 64;) {
+    for (; i < 64 - 7;) {
         ROUND256_16_TO_63(a, b, c, d, e, f, g, h);
         ROUND256_16_TO_63(h, a, b, c, d, e, f, g);
         ROUND256_16_TO_63(g, h, a, b, c, d, e, f);
diff --git a/libavutil/sha.h b/libavutil/sha.h
index 62e4edf..bf4377e 100644
--- a/libavutil/sha.h
+++ b/libavutil/sha.h
@@ -23,7 +23,8 @@
 
 #include <stdint.h>
 
-#include "symbols.h"
+#include "attributes.h"
+#include "version.h"
 
 /**
  * @defgroup lavu_sha SHA
@@ -31,11 +32,16 @@
  * @{
  */
 
-extern AVUTIL_SYMBOL const int av_sha_size;
+extern const int av_sha_size;
 
 struct AVSHA;
 
 /**
+ * Allocate an AVSHA context.
+ */
+struct AVSHA *av_sha_alloc(void);
+
+/**
  * Initialize SHA-1 or SHA-2 hashing.
  *
  * @param context pointer to the function context (of size av_sha_size)
diff --git a/libavutil/timecode.c b/libavutil/timecode.c
index fcbd00d..77d828d 100644
--- a/libavutil/timecode.c
+++ b/libavutil/timecode.c
@@ -31,17 +31,6 @@
 #include "log.h"
 #include "error.h"
 
-#ifdef FF_API_OLD_TC_ADJUST_FRAMENUM
-int av_timecode_adjust_ntsc_framenum(int framenum)
-{
-    /* only works for NTSC 29.97 */
-    int d = framenum / 17982;
-    int m = framenum % 17982;
-    //if (m < 2) m += 2; /* not needed since -2,-1 / 1798 in C returns 0 */
-    return framenum + 18 * d + 2 * ((m - 2) / 1798);
-}
-#endif
-
 int av_timecode_adjust_ntsc_framenum2(int framenum, int fps)
 {
     /* only works for NTSC 29.97 and 59.94 */
diff --git a/libavutil/timecode.h b/libavutil/timecode.h
index 17d6b95..56e3975 100644
--- a/libavutil/timecode.h
+++ b/libavutil/timecode.h
@@ -49,16 +49,6 @@
  * Adjust frame number for NTSC drop frame time code.
  *
  * @param framenum frame number to adjust
- * @return         adjusted frame number
- * @warning        adjustment is only valid in NTSC 29.97
- * @deprecated     use av_timecode_adjust_ntsc_framenum2 instead
- */
-attribute_deprecated int av_timecode_adjust_ntsc_framenum(int framenum);
-
-/**
- * Adjust frame number for NTSC drop frame time code.
- *
- * @param framenum frame number to adjust
  * @param fps      frame per second, 30 or 60
  * @return         adjusted frame number
  * @warning        adjustment is only valid in NTSC 29.97 and 59.94
@@ -73,7 +63,7 @@
  * @return         the SMPTE binary representation
  *
  * @note Frame number adjustment is automatically done in case of drop timecode,
- *       you do NOT have to call av_timecode_adjust_ntsc_framenum().
+ *       you do NOT have to call av_timecode_adjust_ntsc_framenum2().
  * @note The frame number is relative to tc->start.
  * @note Color frame (CF), binary group flags (BGF) and biphase mark polarity
  *       correction (PC) bits are set to zero.
diff --git a/libavutil/tree.c b/libavutil/tree.c
index 4206539..c6ae23d 100644
--- a/libavutil/tree.c
+++ b/libavutil/tree.c
@@ -30,6 +30,11 @@
 
 const int av_tree_node_size = sizeof(AVTreeNode);
 
+struct AVTreeNode *av_tree_node_alloc(void)
+{
+    return av_mallocz(sizeof(struct AVTreeNode));
+}
+
 void *av_tree_find(const AVTreeNode *t, void *key,
                    int (*cmp)(void *key, const void *b), void *next[2])
 {
@@ -205,21 +210,21 @@
     av_lfg_init(&prng, 1);
 
     for (i = 0; i < 10000; i++) {
-        int j = av_lfg_get(&prng) % 86294;
+        intptr_t j = av_lfg_get(&prng) % 86294;
         if (check(root) > 999) {
             av_log(NULL, AV_LOG_ERROR, "FATAL error %d\n", i);
         print(root, 0);
             return -1;
         }
-        av_log(NULL, AV_LOG_ERROR, "inserting %4d\n", j);
+        av_log(NULL, AV_LOG_ERROR, "inserting %4d\n", (int)j);
         if (!node)
-            node = av_mallocz(av_tree_node_size);
+            node = av_tree_node_alloc();
         av_tree_insert(&root, (void *) (j + 1), cmp, &node);
 
         j = av_lfg_get(&prng) % 86294;
         {
             AVTreeNode *node2 = NULL;
-            av_log(NULL, AV_LOG_ERROR, "removing %4d\n", j);
+            av_log(NULL, AV_LOG_ERROR, "removing %4d\n", (int)j);
             av_tree_insert(&root, (void *) (j + 1), cmp, &node2);
             k = av_tree_find(root, (void *) (j + 1), cmp, NULL);
             if (k)
diff --git a/libavutil/tree.h b/libavutil/tree.h
index f2485a7..13fb91b 100644
--- a/libavutil/tree.h
+++ b/libavutil/tree.h
@@ -27,7 +27,8 @@
 #ifndef AVUTIL_TREE_H
 #define AVUTIL_TREE_H
 
-#include "symbols.h"
+#include "attributes.h"
+#include "version.h"
 
 /**
  * @addtogroup lavu_tree AVTree
@@ -42,7 +43,12 @@
 
 
 struct AVTreeNode;
-extern AVUTIL_SYMBOL const int av_tree_node_size;
+extern const int av_tree_node_size;
+
+/**
+ * Allocate an AVTreeNode.
+ */
+struct AVTreeNode *av_tree_node_alloc(void);
 
 /**
  * Find an element.
diff --git a/libavutil/utils.c b/libavutil/utils.c
index 127c4b1..01c940c 100644
--- a/libavutil/utils.c
+++ b/libavutil/utils.c
@@ -28,7 +28,7 @@
 
 unsigned avutil_version(void)
 {
-    av_assert0(PIX_FMT_VDA_VLD == 81); //check if the pix fmt enum has not had anything inserted or removed by mistake
+    av_assert0(AV_PIX_FMT_VDA_VLD == 81); //check if the pix fmt enum has not had anything inserted or removed by mistake
     av_assert0(AV_SAMPLE_FMT_DBLP == 9);
     av_assert0(AVMEDIA_TYPE_ATTACHMENT == 4);
     av_assert0(AV_PICTURE_TYPE_BI == 7);
diff --git a/libavutil/version.h b/libavutil/version.h
index 3361069..a44feda 100644
--- a/libavutil/version.h
+++ b/libavutil/version.h
@@ -21,7 +21,43 @@
 #ifndef AVUTIL_VERSION_H
 #define AVUTIL_VERSION_H
 
-#include "avutil.h"
+/**
+ * @defgroup preproc_misc Preprocessor String Macros
+ *
+ * String manipulation macros
+ *
+ * @{
+ */
+
+#define AV_STRINGIFY(s)         AV_TOSTRING(s)
+#define AV_TOSTRING(s) #s
+
+#define AV_GLUE(a, b) a ## b
+#define AV_JOIN(a, b) AV_GLUE(a, b)
+
+#define AV_PRAGMA(s) _Pragma(#s)
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup version_utils Library Version Macros
+ *
+ * Useful to check and match library version in order to maintain
+ * backward compatibility.
+ *
+ * @{
+ */
+
+#define AV_VERSION_INT(a, b, c) (a<<16 | b<<8 | c)
+#define AV_VERSION_DOT(a, b, c) a ##.## b ##.## c
+#define AV_VERSION(a, b, c) AV_VERSION_DOT(a, b, c)
+
+/**
+ * @}
+ */
+
 
 /**
  * @file
@@ -38,8 +74,8 @@
  * @{
  */
 
-#define LIBAVUTIL_VERSION_MAJOR 51
-#define LIBAVUTIL_VERSION_MINOR 73
+#define LIBAVUTIL_VERSION_MAJOR  52
+#define LIBAVUTIL_VERSION_MINOR  11
 #define LIBAVUTIL_VERSION_MICRO 101
 
 #define LIBAVUTIL_VERSION_INT   AV_VERSION_INT(LIBAVUTIL_VERSION_MAJOR, \
@@ -63,23 +99,35 @@
  * @{
  */
 
-#ifndef FF_API_OLD_EVAL_NAMES
-#define FF_API_OLD_EVAL_NAMES           (LIBAVUTIL_VERSION_MAJOR < 52)
-#endif
 #ifndef FF_API_GET_BITS_PER_SAMPLE_FMT
-#define FF_API_GET_BITS_PER_SAMPLE_FMT (LIBAVUTIL_VERSION_MAJOR < 52)
+#define FF_API_GET_BITS_PER_SAMPLE_FMT (LIBAVUTIL_VERSION_MAJOR < 53)
 #endif
 #ifndef FF_API_FIND_OPT
-#define FF_API_FIND_OPT                 (LIBAVUTIL_VERSION_MAJOR < 52)
-#endif
-#ifndef FF_API_AV_FIFO_PEEK
-#define FF_API_AV_FIFO_PEEK             (LIBAVUTIL_VERSION_MAJOR < 52)
+#define FF_API_FIND_OPT                 (LIBAVUTIL_VERSION_MAJOR < 53)
 #endif
 #ifndef FF_API_OLD_AVOPTIONS
-#define FF_API_OLD_AVOPTIONS            (LIBAVUTIL_VERSION_MAJOR < 52)
+#define FF_API_OLD_AVOPTIONS            (LIBAVUTIL_VERSION_MAJOR < 53)
 #endif
-#ifndef FF_API_OLD_TC_ADJUST_FRAMENUM
-#define FF_API_OLD_TC_ADJUST_FRAMENUM   (LIBAVUTIL_VERSION_MAJOR < 52)
+#ifndef FF_API_PIX_FMT
+#define FF_API_PIX_FMT                  (LIBAVUTIL_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_CONTEXT_SIZE
+#define FF_API_CONTEXT_SIZE             (LIBAVUTIL_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_PIX_FMT_DESC
+#define FF_API_PIX_FMT_DESC             (LIBAVUTIL_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_AV_REVERSE
+#define FF_API_AV_REVERSE               (LIBAVUTIL_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_AUDIOCONVERT
+#define FF_API_AUDIOCONVERT             (LIBAVUTIL_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_CPU_FLAG_MMX2
+#define FF_API_CPU_FLAG_MMX2            (LIBAVUTIL_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_SAMPLES_UTILS_RETURN_ZERO
+#define FF_API_SAMPLES_UTILS_RETURN_ZERO (LIBAVUTIL_VERSION_MAJOR < 53)
 #endif
 
 /**
diff --git a/libavutil/x86/Makefile b/libavutil/x86/Makefile
index 4546353..3dd696c 100644
--- a/libavutil/x86/Makefile
+++ b/libavutil/x86/Makefile
@@ -1,4 +1,5 @@
 OBJS += x86/cpu.o                                                       \
         x86/float_dsp_init.o                                            \
 
-YASM-OBJS += x86/float_dsp.o                                            \
+YASM-OBJS += x86/cpuid.o                                                \
+             x86/float_dsp.o                                            \
diff --git a/libavutil/x86/cpu.c b/libavutil/x86/cpu.c
index 994e30d..a3a5239 100644
--- a/libavutil/x86/cpu.c
+++ b/libavutil/x86/cpu.c
@@ -22,10 +22,21 @@
 
 #include <stdlib.h>
 #include <string.h>
+
 #include "libavutil/x86/asm.h"
+#include "libavutil/x86/cpu.h"
 #include "libavutil/cpu.h"
 
-#if HAVE_INLINE_ASM
+#if HAVE_YASM
+
+#define cpuid(index, eax, ebx, ecx, edx)        \
+    ff_cpu_cpuid(index, &eax, &ebx, &ecx, &edx)
+
+#define xgetbv(index, eax, edx)                 \
+    ff_cpu_xgetbv(index, &eax, &edx)
+
+#elif HAVE_INLINE_ASM
+
 /* ebx saving is necessary for PIC. gcc seems unable to see it alone */
 #define cpuid(index, eax, ebx, ecx, edx)                        \
     __asm__ volatile (                                          \
@@ -34,35 +45,9 @@
         "xchg   %%"REG_b", %%"REG_S                             \
         : "=a" (eax), "=S" (ebx), "=c" (ecx), "=d" (edx)        \
         : "0" (index))
-#elif HAVE_CPUID
-#include <intrin.h>
 
-#define cpuid(index, eax, ebx, ecx, edx)        \
-    do {                                        \
-        int info[4];                            \
-        __cpuid(info, index);                   \
-        eax = info[0];                          \
-        ebx = info[1];                          \
-        ecx = info[2];                          \
-        edx = info[3];                          \
-    } while (0)
-#endif /* HAVE_CPUID */
-
-#if HAVE_INLINE_ASM
 #define xgetbv(index, eax, edx)                                 \
     __asm__ (".byte 0x0f, 0x01, 0xd0" : "=a"(eax), "=d"(edx) : "c" (index))
-#elif HAVE_XGETBV
-#include <immintrin.h>
-
-#define xgetbv(index, eax, edx)                 \
-    do {                                        \
-        uint64_t res = __xgetbv(index);         \
-        eax = res;                              \
-        edx = res >> 32;                        \
-    } while (0)
-#endif /* HAVE_XGETBV */
-
-#if HAVE_INLINE_ASM
 
 #define get_eflags(x)                           \
     __asm__ volatile ("pushfl     \n"           \
@@ -74,28 +59,20 @@
                       "popfl      \n"           \
                       :: "r"(x))
 
-#elif HAVE_RWEFLAGS
-
-#include <intrin.h>
-
-#define get_eflags(x)                           \
-    x = __readeflags()
-
-#define set_eflags(x)                           \
-    __writeeflags(x)
-
 #endif /* HAVE_INLINE_ASM */
 
-/* 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_64
 
-#if ARCH_X86_32
+#define cpuid_test() 1
+
+#elif HAVE_YASM
+
+#define cpuid_test ff_cpu_cpuid_test
+
+#elif HAVE_INLINE_ASM
+
+static int cpuid_test(void)
+{
     x86_reg a, c;
 
     /* Check if CPUID is supported by attempting to toggle the ID bit in
@@ -104,14 +81,26 @@
     set_eflags(a ^ 0x200000);
     get_eflags(c);
 
-    if (a == c)
-        return 0; /* CPUID not supported */
+    return a != c;
+}
 #endif
 
-    cpuid(0, max_std_level, ebx, ecx, edx);
-    vendor.i[0] = ebx;
-    vendor.i[1] = edx;
-    vendor.i[2] = ecx;
+/* Function to test if multimedia instructions are supported...  */
+int ff_get_cpu_flags_x86(void)
+{
+    int rval = 0;
+
+#ifdef cpuid
+
+    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 (!cpuid_test())
+        return 0; /* CPUID not supported */
+
+    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);
@@ -206,5 +195,7 @@
             rval |= AV_CPU_FLAG_ATOM;
     }
 
+#endif /* cpuid */
+
     return rval;
 }
diff --git a/libavutil/x86/cpu.h b/libavutil/x86/cpu.h
index 76abeb9..601476e 100644
--- a/libavutil/x86/cpu.h
+++ b/libavutil/x86/cpu.h
@@ -54,4 +54,8 @@
 #define INLINE_AVX(flags)           CPUEXT(flags, _INLINE, AVX)
 #define INLINE_FMA4(flags)          CPUEXT(flags, _INLINE, FMA4)
 
+void ff_cpu_cpuid(int index, int *eax, int *ebx, int *ecx, int *edx);
+void ff_cpu_xgetbv(int op, int *eax, int *edx);
+int  ff_cpu_cpuid_test(void);
+
 #endif /* AVUTIL_X86_CPU_H */
diff --git a/libavutil/x86/cpuid.asm b/libavutil/x86/cpuid.asm
new file mode 100644
index 0000000..56876a8
--- /dev/null
+++ b/libavutil/x86/cpuid.asm
@@ -0,0 +1,91 @@
+;*****************************************************************************
+;* Copyright (C) 2005-2010 x264 project
+;*
+;* Authors: Loren Merritt <lorenm@u.washington.edu>
+;*          Jason Garrett-Glaser <darkshikari@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 "x86util.asm"
+
+SECTION .text
+
+;-----------------------------------------------------------------------------
+; void ff_cpu_cpuid(int index, int *eax, int *ebx, int *ecx, int *edx)
+;-----------------------------------------------------------------------------
+cglobal cpu_cpuid, 5,7
+    push rbx
+    push  r4
+    push  r3
+    push  r2
+    push  r1
+    mov  eax, r0d
+    xor  ecx, ecx
+    cpuid
+    pop   r4
+    mov [r4], eax
+    pop   r4
+    mov [r4], ebx
+    pop   r4
+    mov [r4], ecx
+    pop   r4
+    mov [r4], edx
+    pop  rbx
+    RET
+
+;-----------------------------------------------------------------------------
+; void ff_cpu_xgetbv(int op, int *eax, int *edx)
+;-----------------------------------------------------------------------------
+cglobal cpu_xgetbv, 3,7
+    push  r2
+    push  r1
+    mov  ecx, r0d
+    xgetbv
+    pop   r4
+    mov [r4], eax
+    pop   r4
+    mov [r4], edx
+    RET
+
+%if ARCH_X86_64 == 0
+;-----------------------------------------------------------------------------
+; int ff_cpu_cpuid_test(void)
+; return 0 if unsupported
+;-----------------------------------------------------------------------------
+cglobal cpu_cpuid_test
+    pushfd
+    push    ebx
+    push    ebp
+    push    esi
+    push    edi
+    pushfd
+    pop     eax
+    mov     ebx, eax
+    xor     eax, 0x200000
+    push    eax
+    popfd
+    pushfd
+    pop     eax
+    xor     eax, ebx
+    pop     edi
+    pop     esi
+    pop     ebp
+    pop     ebx
+    popfd
+    ret
+%endif
diff --git a/libavutil/x86/float_dsp.asm b/libavutil/x86/float_dsp.asm
index 3af928f..a3200c6 100644
--- a/libavutil/x86/float_dsp.asm
+++ b/libavutil/x86/float_dsp.asm
@@ -20,7 +20,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "x86inc.asm"
 %include "x86util.asm"
 
 SECTION .text
@@ -92,3 +91,32 @@
 INIT_YMM avx
 VECTOR_FMAC_SCALAR
 %endif
+
+;------------------------------------------------------------------------------
+; void ff_vector_fmul_scalar(float *dst, const float *src, float mul, int len)
+;------------------------------------------------------------------------------
+
+%macro VECTOR_FMUL_SCALAR 0
+%if UNIX64
+cglobal vector_fmul_scalar, 3,3,2, dst, src, len
+%else
+cglobal vector_fmul_scalar, 4,4,3, dst, src, mul, len
+%endif
+%if ARCH_X86_32
+    movss    m0, mulm
+%elif WIN64
+    SWAP 0, 2
+%endif
+    shufps   m0, m0, 0
+    lea    lenq, [lend*4-mmsize]
+.loop:
+    mova     m1, [srcq+lenq]
+    mulps    m1, m0
+    mova  [dstq+lenq], m1
+    sub    lenq, mmsize
+    jge .loop
+    REP_RET
+%endmacro
+
+INIT_XMM sse
+VECTOR_FMUL_SCALAR
diff --git a/libavutil/x86/float_dsp_init.c b/libavutil/x86/float_dsp_init.c
index 1382373..259fda1 100644
--- a/libavutil/x86/float_dsp_init.c
+++ b/libavutil/x86/float_dsp_init.c
@@ -32,6 +32,9 @@
 extern void ff_vector_fmac_scalar_avx(float *dst, const float *src, float mul,
                                       int len);
 
+extern void ff_vector_fmul_scalar_sse(float *dst, const float *src, float mul,
+                                      int len);
+
 void ff_float_dsp_init_x86(AVFloatDSPContext *fdsp)
 {
     int mm_flags = av_get_cpu_flags();
@@ -39,6 +42,7 @@
     if (EXTERNAL_SSE(mm_flags)) {
         fdsp->vector_fmul = ff_vector_fmul_sse;
         fdsp->vector_fmac_scalar = ff_vector_fmac_scalar_sse;
+        fdsp->vector_fmul_scalar = ff_vector_fmul_scalar_sse;
     }
     if (EXTERNAL_AVX(mm_flags)) {
         fdsp->vector_fmul = ff_vector_fmul_avx;
diff --git a/libavutil/x86/intmath.h b/libavutil/x86/intmath.h
deleted file mode 100644
index 4525a4d..0000000
--- a/libavutil/x86/intmath.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (c) 2010 Mans Rullgard <mans@mansr.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 AVUTIL_X86_INTMATH_H
-#define AVUTIL_X86_INTMATH_H
-
-#if HAVE_INLINE_ASM
-#define FASTDIV(a,b) \
-    ({\
-        int ret, dmy;\
-        __asm__ volatile(\
-            "mull %3"\
-            :"=d"(ret), "=a"(dmy)\
-            :"1"((unsigned int)(a)), "rm"(ff_inverse[b])\
-            );\
-        ret;\
-    })
-#endif
-
-#endif /* AVUTIL_X86_INTMATH_H */
diff --git a/libavutil/x86/x86inc.asm b/libavutil/x86/x86inc.asm
index e097bf2..faae806 100644
--- a/libavutil/x86/x86inc.asm
+++ b/libavutil/x86/x86inc.asm
@@ -34,7 +34,9 @@
 ; as this feature might be useful for others as well.  Send patches or ideas
 ; to x264-devel@videolan.org .
 
-%define program_name ff
+%ifndef program_name
+    %define program_name x264
+%endif
 
 %define WIN64  0
 %define UNIX64 0
diff --git a/libavutil/x86/x86util.asm b/libavutil/x86/x86util.asm
index cf5ea36..c11df90 100644
--- a/libavutil/x86/x86util.asm
+++ b/libavutil/x86/x86util.asm
@@ -23,6 +23,11 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
+%define program_name ff
+%define cpuflags_mmxext cpuflags_mmx2
+
+%include "libavutil/x86/x86inc.asm"
+
 %macro SBUTTERFLY 4
 %if avx_enabled == 0
     mova      m%4, m%2
@@ -141,13 +146,21 @@
 %endif
 %endmacro
 
-; PABSW macros assume %1 != %2, while ABS1/2 macros work in-place
-%macro PABSW_MMX 2
+; PABSW macro assumes %1 != %2, while ABS1/2 macros work in-place
+%macro PABSW 2
+%if cpuflag(ssse3)
+    pabsw      %1, %2
+%elif cpuflag(mmxext)
+    pxor    %1, %1
+    psubw   %1, %2
+    pmaxsw  %1, %2
+%else
     pxor       %1, %1
     pcmpgtw    %1, %2
     pxor       %2, %1
     psubw      %2, %1
     SWAP       %1, %2
+%endif
 %endmacro
 
 %macro PSIGNW_MMX 2
@@ -155,16 +168,6 @@
     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
@@ -187,13 +190,13 @@
     psubw      %2, %4
 %endmacro
 
-%macro ABS1_MMX2 2   ; a, tmp
+%macro ABS1_MMXEXT 2 ; a, tmp
     pxor    %2, %2
     psubw   %2, %1
     pmaxsw  %1, %2
 %endmacro
 
-%macro ABS2_MMX2 4   ; a, b, tmp0, tmp1
+%macro ABS2_MMXEXT 4 ; a, b, tmp0, tmp1
     pxor    %3, %3
     pxor    %4, %4
     psubw   %3, %1
@@ -278,7 +281,14 @@
 %endif
 %endmacro
 
-%macro PALIGNR_MMX 4-5 ; [dst,] src1, src2, imm, tmp
+%macro PALIGNR 4-5
+%if cpuflag(ssse3)
+%if %0==5
+    palignr %1, %2, %3, %4
+%else
+    palignr %1, %2, %3
+%endif
+%elif cpuflag(mmx) ; [dst,] src1, src2, imm, tmp
     %define %%dst %1
 %if %0==5
 %ifnidn %1, %2
@@ -297,13 +307,6 @@
     psrldq  %4, %3
 %endif
     por     %%dst, %4
-%endmacro
-
-%macro PALIGNR_SSSE3 4-5
-%if %0==5
-    palignr %1, %2, %3, %4
-%else
-    palignr %1, %2, %3
 %endif
 %endmacro
 
@@ -315,6 +318,18 @@
     %endif
 %endmacro
 
+%macro PSWAPD 2
+%if cpuflag(mmxext)
+    pshufw    %1, %2, q1032
+%elif cpuflag(3dnowext)
+    pswapd    %1, %2
+%elif cpuflag(3dnow)
+    movq      %1, %2
+    psrlq     %1, 32
+    punpckldq %1, %2
+%endif
+%endmacro
+
 %macro DEINTB 5 ; mask, reg1, mask, reg2, optional src to fill masks from
 %ifnum %5
     pand   m%3, m%5, m%4 ; src .. y6 .. y4
@@ -526,21 +541,21 @@
     movh  [%7+%8], %4
 %endmacro
 
-%macro PMINUB_MMX 3 ; dst, src, tmp
+%macro PMINUB 3 ; dst, src, ignored
+%if cpuflag(mmxext)
+    pminub   %1, %2
+%else ; dst, src, tmp
     mova     %3, %1
     psubusb  %3, %2
     psubb    %1, %3
-%endmacro
-
-%macro PMINUB_MMXEXT 3 ; dst, src, ignored
-    pminub   %1, %2
+%endif
 %endmacro
 
 %macro SPLATW 2-3 0
 %if mmsize == 16
     pshuflw    %1, %2, (%3)*0x55
     punpcklqdq %1, %1
-%elif cpuflag(mmx2)
+%elif cpuflag(mmxext)
     pshufw     %1, %2, (%3)*0x55
 %else
     %ifnidn %1, %2
@@ -559,24 +574,14 @@
 %endif
 %endmacro
 
-%macro SPLATD 2-3 0
-%if mmsize == 16
-    pshufd %1, %2, (%3)*0x55
-%else
-    pshufw %1, %2, (%3)*0x11 + ((%3)+1)*0x44
-%endif
-%endmacro
-
-%macro SPLATD_MMX 1
+%macro SPLATD 1
+%if mmsize == 8
     punpckldq  %1, %1
-%endmacro
-
-%macro SPLATD_SSE 1
-    shufps  %1, %1, 0
-%endmacro
-
-%macro SPLATD_SSE2 1
+%elif cpuflag(sse2)
     pshufd  %1, %1, 0
+%elif cpuflag(sse)
+    shufps  %1, %1, 0
+%endif
 %endmacro
 
 %macro CLIPW 3 ;(dst, min, max)
diff --git a/libavutil/xga_font_data.c b/libavutil/xga_font_data.c
new file mode 100644
index 0000000..3aed314
--- /dev/null
+++ b/libavutil/xga_font_data.c
@@ -0,0 +1,417 @@
+/*
+ * CGA/EGA/VGA ROM font data
+ *
+ * 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
+ * CGA/EGA/VGA ROM font data
+ */
+
+#include <stdint.h>
+#include "xga_font_data.h"
+
+const uint8_t avpriv_cga_font[2048] = {
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x81, 0xa5, 0x81, 0xbd, 0x99, 0x81, 0x7e,
+ 0x7e, 0xff, 0xdb, 0xff, 0xc3, 0xe7, 0xff, 0x7e, 0x6c, 0xfe, 0xfe, 0xfe, 0x7c, 0x38, 0x10, 0x00,
+ 0x10, 0x38, 0x7c, 0xfe, 0x7c, 0x38, 0x10, 0x00, 0x38, 0x7c, 0x38, 0xfe, 0xfe, 0x7c, 0x38, 0x7c,
+ 0x10, 0x10, 0x38, 0x7c, 0xfe, 0x7c, 0x38, 0x7c, 0x00, 0x00, 0x18, 0x3c, 0x3c, 0x18, 0x00, 0x00,
+ 0xff, 0xff, 0xe7, 0xc3, 0xc3, 0xe7, 0xff, 0xff, 0x00, 0x3c, 0x66, 0x42, 0x42, 0x66, 0x3c, 0x00,
+ 0xff, 0xc3, 0x99, 0xbd, 0xbd, 0x99, 0xc3, 0xff, 0x0f, 0x07, 0x0f, 0x7d, 0xcc, 0xcc, 0xcc, 0x78,
+ 0x3c, 0x66, 0x66, 0x66, 0x3c, 0x18, 0x7e, 0x18, 0x3f, 0x33, 0x3f, 0x30, 0x30, 0x70, 0xf0, 0xe0,
+ 0x7f, 0x63, 0x7f, 0x63, 0x63, 0x67, 0xe6, 0xc0, 0x99, 0x5a, 0x3c, 0xe7, 0xe7, 0x3c, 0x5a, 0x99,
+ 0x80, 0xe0, 0xf8, 0xfe, 0xf8, 0xe0, 0x80, 0x00, 0x02, 0x0e, 0x3e, 0xfe, 0x3e, 0x0e, 0x02, 0x00,
+ 0x18, 0x3c, 0x7e, 0x18, 0x18, 0x7e, 0x3c, 0x18, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x66, 0x00,
+ 0x7f, 0xdb, 0xdb, 0x7b, 0x1b, 0x1b, 0x1b, 0x00, 0x3e, 0x63, 0x38, 0x6c, 0x6c, 0x38, 0xcc, 0x78,
+ 0x00, 0x00, 0x00, 0x00, 0x7e, 0x7e, 0x7e, 0x00, 0x18, 0x3c, 0x7e, 0x18, 0x7e, 0x3c, 0x18, 0xff,
+ 0x18, 0x3c, 0x7e, 0x18, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x18, 0x7e, 0x3c, 0x18, 0x00,
+ 0x00, 0x18, 0x0c, 0xfe, 0x0c, 0x18, 0x00, 0x00, 0x00, 0x30, 0x60, 0xfe, 0x60, 0x30, 0x00, 0x00,
+ 0x00, 0x00, 0xc0, 0xc0, 0xc0, 0xfe, 0x00, 0x00, 0x00, 0x24, 0x66, 0xff, 0x66, 0x24, 0x00, 0x00,
+ 0x00, 0x18, 0x3c, 0x7e, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0x7e, 0x3c, 0x18, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x78, 0x78, 0x30, 0x30, 0x00, 0x30, 0x00,
+ 0x6c, 0x6c, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6c, 0x6c, 0xfe, 0x6c, 0xfe, 0x6c, 0x6c, 0x00,
+ 0x30, 0x7c, 0xc0, 0x78, 0x0c, 0xf8, 0x30, 0x00, 0x00, 0xc6, 0xcc, 0x18, 0x30, 0x66, 0xc6, 0x00,
+ 0x38, 0x6c, 0x38, 0x76, 0xdc, 0xcc, 0x76, 0x00, 0x60, 0x60, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x18, 0x30, 0x60, 0x60, 0x60, 0x30, 0x18, 0x00, 0x60, 0x30, 0x18, 0x18, 0x18, 0x30, 0x60, 0x00,
+ 0x00, 0x66, 0x3c, 0xff, 0x3c, 0x66, 0x00, 0x00, 0x00, 0x30, 0x30, 0xfc, 0x30, 0x30, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x30, 0x60, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x30, 0x00, 0x06, 0x0c, 0x18, 0x30, 0x60, 0xc0, 0x80, 0x00,
+ 0x7c, 0xc6, 0xce, 0xde, 0xf6, 0xe6, 0x7c, 0x00, 0x30, 0x70, 0x30, 0x30, 0x30, 0x30, 0xfc, 0x00,
+ 0x78, 0xcc, 0x0c, 0x38, 0x60, 0xcc, 0xfc, 0x00, 0x78, 0xcc, 0x0c, 0x38, 0x0c, 0xcc, 0x78, 0x00,
+ 0x1c, 0x3c, 0x6c, 0xcc, 0xfe, 0x0c, 0x1e, 0x00, 0xfc, 0xc0, 0xf8, 0x0c, 0x0c, 0xcc, 0x78, 0x00,
+ 0x38, 0x60, 0xc0, 0xf8, 0xcc, 0xcc, 0x78, 0x00, 0xfc, 0xcc, 0x0c, 0x18, 0x30, 0x30, 0x30, 0x00,
+ 0x78, 0xcc, 0xcc, 0x78, 0xcc, 0xcc, 0x78, 0x00, 0x78, 0xcc, 0xcc, 0x7c, 0x0c, 0x18, 0x70, 0x00,
+ 0x00, 0x30, 0x30, 0x00, 0x00, 0x30, 0x30, 0x00, 0x00, 0x30, 0x30, 0x00, 0x00, 0x30, 0x30, 0x60,
+ 0x18, 0x30, 0x60, 0xc0, 0x60, 0x30, 0x18, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0xfc, 0x00, 0x00,
+ 0x60, 0x30, 0x18, 0x0c, 0x18, 0x30, 0x60, 0x00, 0x78, 0xcc, 0x0c, 0x18, 0x30, 0x00, 0x30, 0x00,
+ 0x7c, 0xc6, 0xde, 0xde, 0xde, 0xc0, 0x78, 0x00, 0x30, 0x78, 0xcc, 0xcc, 0xfc, 0xcc, 0xcc, 0x00,
+ 0xfc, 0x66, 0x66, 0x7c, 0x66, 0x66, 0xfc, 0x00, 0x3c, 0x66, 0xc0, 0xc0, 0xc0, 0x66, 0x3c, 0x00,
+ 0xf8, 0x6c, 0x66, 0x66, 0x66, 0x6c, 0xf8, 0x00, 0xfe, 0x62, 0x68, 0x78, 0x68, 0x62, 0xfe, 0x00,
+ 0xfe, 0x62, 0x68, 0x78, 0x68, 0x60, 0xf0, 0x00, 0x3c, 0x66, 0xc0, 0xc0, 0xce, 0x66, 0x3e, 0x00,
+ 0xcc, 0xcc, 0xcc, 0xfc, 0xcc, 0xcc, 0xcc, 0x00, 0x78, 0x30, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00,
+ 0x1e, 0x0c, 0x0c, 0x0c, 0xcc, 0xcc, 0x78, 0x00, 0xe6, 0x66, 0x6c, 0x78, 0x6c, 0x66, 0xe6, 0x00,
+ 0xf0, 0x60, 0x60, 0x60, 0x62, 0x66, 0xfe, 0x00, 0xc6, 0xee, 0xfe, 0xfe, 0xd6, 0xc6, 0xc6, 0x00,
+ 0xc6, 0xe6, 0xf6, 0xde, 0xce, 0xc6, 0xc6, 0x00, 0x38, 0x6c, 0xc6, 0xc6, 0xc6, 0x6c, 0x38, 0x00,
+ 0xfc, 0x66, 0x66, 0x7c, 0x60, 0x60, 0xf0, 0x00, 0x78, 0xcc, 0xcc, 0xcc, 0xdc, 0x78, 0x1c, 0x00,
+ 0xfc, 0x66, 0x66, 0x7c, 0x6c, 0x66, 0xe6, 0x00, 0x78, 0xcc, 0xe0, 0x70, 0x1c, 0xcc, 0x78, 0x00,
+ 0xfc, 0xb4, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xfc, 0x00,
+ 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x78, 0x30, 0x00, 0xc6, 0xc6, 0xc6, 0xd6, 0xfe, 0xee, 0xc6, 0x00,
+ 0xc6, 0xc6, 0x6c, 0x38, 0x38, 0x6c, 0xc6, 0x00, 0xcc, 0xcc, 0xcc, 0x78, 0x30, 0x30, 0x78, 0x00,
+ 0xfe, 0xc6, 0x8c, 0x18, 0x32, 0x66, 0xfe, 0x00, 0x78, 0x60, 0x60, 0x60, 0x60, 0x60, 0x78, 0x00,
+ 0xc0, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x02, 0x00, 0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x78, 0x00,
+ 0x10, 0x38, 0x6c, 0xc6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff,
+ 0x30, 0x30, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0x76, 0x00,
+ 0xe0, 0x60, 0x60, 0x7c, 0x66, 0x66, 0xdc, 0x00, 0x00, 0x00, 0x78, 0xcc, 0xc0, 0xcc, 0x78, 0x00,
+ 0x1c, 0x0c, 0x0c, 0x7c, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x78, 0x00,
+ 0x38, 0x6c, 0x60, 0xf0, 0x60, 0x60, 0xf0, 0x00, 0x00, 0x00, 0x76, 0xcc, 0xcc, 0x7c, 0x0c, 0xf8,
+ 0xe0, 0x60, 0x6c, 0x76, 0x66, 0x66, 0xe6, 0x00, 0x30, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
+ 0x0c, 0x00, 0x0c, 0x0c, 0x0c, 0xcc, 0xcc, 0x78, 0xe0, 0x60, 0x66, 0x6c, 0x78, 0x6c, 0xe6, 0x00,
+ 0x70, 0x30, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00, 0x00, 0x00, 0xcc, 0xfe, 0xfe, 0xd6, 0xc6, 0x00,
+ 0x00, 0x00, 0xf8, 0xcc, 0xcc, 0xcc, 0xcc, 0x00, 0x00, 0x00, 0x78, 0xcc, 0xcc, 0xcc, 0x78, 0x00,
+ 0x00, 0x00, 0xdc, 0x66, 0x66, 0x7c, 0x60, 0xf0, 0x00, 0x00, 0x76, 0xcc, 0xcc, 0x7c, 0x0c, 0x1e,
+ 0x00, 0x00, 0xdc, 0x76, 0x66, 0x60, 0xf0, 0x00, 0x00, 0x00, 0x7c, 0xc0, 0x78, 0x0c, 0xf8, 0x00,
+ 0x10, 0x30, 0x7c, 0x30, 0x30, 0x34, 0x18, 0x00, 0x00, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00,
+ 0x00, 0x00, 0xcc, 0xcc, 0xcc, 0x78, 0x30, 0x00, 0x00, 0x00, 0xc6, 0xd6, 0xfe, 0xfe, 0x6c, 0x00,
+ 0x00, 0x00, 0xc6, 0x6c, 0x38, 0x6c, 0xc6, 0x00, 0x00, 0x00, 0xcc, 0xcc, 0xcc, 0x7c, 0x0c, 0xf8,
+ 0x00, 0x00, 0xfc, 0x98, 0x30, 0x64, 0xfc, 0x00, 0x1c, 0x30, 0x30, 0xe0, 0x30, 0x30, 0x1c, 0x00,
+ 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00, 0xe0, 0x30, 0x30, 0x1c, 0x30, 0x30, 0xe0, 0x00,
+ 0x76, 0xdc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6c, 0xc6, 0xc6, 0xfe, 0x00,
+ 0x78, 0xcc, 0xc0, 0xcc, 0x78, 0x18, 0x0c, 0x78, 0x00, 0xcc, 0x00, 0xcc, 0xcc, 0xcc, 0x7e, 0x00,
+ 0x1c, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x78, 0x00, 0x7e, 0xc3, 0x3c, 0x06, 0x3e, 0x66, 0x3f, 0x00,
+ 0xcc, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0x7e, 0x00, 0xe0, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0x7e, 0x00,
+ 0x30, 0x30, 0x78, 0x0c, 0x7c, 0xcc, 0x7e, 0x00, 0x00, 0x00, 0x78, 0xc0, 0xc0, 0x78, 0x0c, 0x38,
+ 0x7e, 0xc3, 0x3c, 0x66, 0x7e, 0x60, 0x3c, 0x00, 0xcc, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x78, 0x00,
+ 0xe0, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x78, 0x00, 0xcc, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
+ 0x7c, 0xc6, 0x38, 0x18, 0x18, 0x18, 0x3c, 0x00, 0xe0, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
+ 0xc6, 0x38, 0x6c, 0xc6, 0xfe, 0xc6, 0xc6, 0x00, 0x30, 0x30, 0x00, 0x78, 0xcc, 0xfc, 0xcc, 0x00,
+ 0x1c, 0x00, 0xfc, 0x60, 0x78, 0x60, 0xfc, 0x00, 0x00, 0x00, 0x7f, 0x0c, 0x7f, 0xcc, 0x7f, 0x00,
+ 0x3e, 0x6c, 0xcc, 0xfe, 0xcc, 0xcc, 0xce, 0x00, 0x78, 0xcc, 0x00, 0x78, 0xcc, 0xcc, 0x78, 0x00,
+ 0x00, 0xcc, 0x00, 0x78, 0xcc, 0xcc, 0x78, 0x00, 0x00, 0xe0, 0x00, 0x78, 0xcc, 0xcc, 0x78, 0x00,
+ 0x78, 0xcc, 0x00, 0xcc, 0xcc, 0xcc, 0x7e, 0x00, 0x00, 0xe0, 0x00, 0xcc, 0xcc, 0xcc, 0x7e, 0x00,
+ 0x00, 0xcc, 0x00, 0xcc, 0xcc, 0x7c, 0x0c, 0xf8, 0xc3, 0x18, 0x3c, 0x66, 0x66, 0x3c, 0x18, 0x00,
+ 0xcc, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0x78, 0x00, 0x18, 0x18, 0x7e, 0xc0, 0xc0, 0x7e, 0x18, 0x18,
+ 0x38, 0x6c, 0x64, 0xf0, 0x60, 0xe6, 0xfc, 0x00, 0xcc, 0xcc, 0x78, 0xfc, 0x30, 0xfc, 0x30, 0x30,
+ 0xf8, 0xcc, 0xcc, 0xfa, 0xc6, 0xcf, 0xc6, 0xc7, 0x0e, 0x1b, 0x18, 0x3c, 0x18, 0x18, 0xd8, 0x70,
+ 0x1c, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0x7e, 0x00, 0x38, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
+ 0x00, 0x1c, 0x00, 0x78, 0xcc, 0xcc, 0x78, 0x00, 0x00, 0x1c, 0x00, 0xcc, 0xcc, 0xcc, 0x7e, 0x00,
+ 0x00, 0xf8, 0x00, 0xf8, 0xcc, 0xcc, 0xcc, 0x00, 0xfc, 0x00, 0xcc, 0xec, 0xfc, 0xdc, 0xcc, 0x00,
+ 0x3c, 0x6c, 0x6c, 0x3e, 0x00, 0x7e, 0x00, 0x00, 0x38, 0x6c, 0x6c, 0x38, 0x00, 0x7c, 0x00, 0x00,
+ 0x30, 0x00, 0x30, 0x60, 0xc0, 0xcc, 0x78, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xc0, 0xc0, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0xfc, 0x0c, 0x0c, 0x00, 0x00, 0xc3, 0xc6, 0xcc, 0xde, 0x33, 0x66, 0xcc, 0x0f,
+ 0xc3, 0xc6, 0xcc, 0xdb, 0x37, 0x6f, 0xcf, 0x03, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x18, 0x00,
+ 0x00, 0x33, 0x66, 0xcc, 0x66, 0x33, 0x00, 0x00, 0x00, 0xcc, 0x66, 0x33, 0x66, 0xcc, 0x00, 0x00,
+ 0x22, 0x88, 0x22, 0x88, 0x22, 0x88, 0x22, 0x88, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa,
+ 0xdb, 0x77, 0xdb, 0xee, 0xdb, 0x77, 0xdb, 0xee, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
+ 0x18, 0x18, 0x18, 0x18, 0xf8, 0x18, 0x18, 0x18, 0x18, 0x18, 0xf8, 0x18, 0xf8, 0x18, 0x18, 0x18,
+ 0x36, 0x36, 0x36, 0x36, 0xf6, 0x36, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x36, 0x36, 0x36,
+ 0x00, 0x00, 0xf8, 0x18, 0xf8, 0x18, 0x18, 0x18, 0x36, 0x36, 0xf6, 0x06, 0xf6, 0x36, 0x36, 0x36,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x00, 0x00, 0xfe, 0x06, 0xf6, 0x36, 0x36, 0x36,
+ 0x36, 0x36, 0xf6, 0x06, 0xfe, 0x00, 0x00, 0x00, 0x36, 0x36, 0x36, 0x36, 0xfe, 0x00, 0x00, 0x00,
+ 0x18, 0x18, 0xf8, 0x18, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x18, 0x18, 0x18,
+ 0x18, 0x18, 0x18, 0x18, 0x1f, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0xff, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0xff, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1f, 0x18, 0x18, 0x18,
+ 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0xff, 0x18, 0x18, 0x18,
+ 0x18, 0x18, 0x1f, 0x18, 0x1f, 0x18, 0x18, 0x18, 0x36, 0x36, 0x36, 0x36, 0x37, 0x36, 0x36, 0x36,
+ 0x36, 0x36, 0x37, 0x30, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x30, 0x37, 0x36, 0x36, 0x36,
+ 0x36, 0x36, 0xf7, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xf7, 0x36, 0x36, 0x36,
+ 0x36, 0x36, 0x37, 0x30, 0x37, 0x36, 0x36, 0x36, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00,
+ 0x36, 0x36, 0xf7, 0x00, 0xf7, 0x36, 0x36, 0x36, 0x18, 0x18, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00,
+ 0x36, 0x36, 0x36, 0x36, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0x18, 0x18, 0x18,
+ 0x00, 0x00, 0x00, 0x00, 0xff, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x3f, 0x00, 0x00, 0x00,
+ 0x18, 0x18, 0x1f, 0x18, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x18, 0x1f, 0x18, 0x18, 0x18,
+ 0x00, 0x00, 0x00, 0x00, 0x3f, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xff, 0x36, 0x36, 0x36,
+ 0x18, 0x18, 0xff, 0x18, 0xff, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xf8, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x1f, 0x18, 0x18, 0x18, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0,
+ 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x76, 0xdc, 0xc8, 0xdc, 0x76, 0x00, 0x00, 0x78, 0xcc, 0xf8, 0xcc, 0xf8, 0xc0, 0xc0,
+ 0x00, 0xfc, 0xcc, 0xc0, 0xc0, 0xc0, 0xc0, 0x00, 0x00, 0xfe, 0x6c, 0x6c, 0x6c, 0x6c, 0x6c, 0x00,
+ 0xfc, 0xcc, 0x60, 0x30, 0x60, 0xcc, 0xfc, 0x00, 0x00, 0x00, 0x7e, 0xd8, 0xd8, 0xd8, 0x70, 0x00,
+ 0x00, 0x66, 0x66, 0x66, 0x66, 0x7c, 0x60, 0xc0, 0x00, 0x76, 0xdc, 0x18, 0x18, 0x18, 0x18, 0x00,
+ 0xfc, 0x30, 0x78, 0xcc, 0xcc, 0x78, 0x30, 0xfc, 0x38, 0x6c, 0xc6, 0xfe, 0xc6, 0x6c, 0x38, 0x00,
+ 0x38, 0x6c, 0xc6, 0xc6, 0x6c, 0x6c, 0xee, 0x00, 0x1c, 0x30, 0x18, 0x7c, 0xcc, 0xcc, 0x78, 0x00,
+ 0x00, 0x00, 0x7e, 0xdb, 0xdb, 0x7e, 0x00, 0x00, 0x06, 0x0c, 0x7e, 0xdb, 0xdb, 0x7e, 0x60, 0xc0,
+ 0x38, 0x60, 0xc0, 0xf8, 0xc0, 0x60, 0x38, 0x00, 0x78, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x00,
+ 0x00, 0xfc, 0x00, 0xfc, 0x00, 0xfc, 0x00, 0x00, 0x30, 0x30, 0xfc, 0x30, 0x30, 0x00, 0xfc, 0x00,
+ 0x60, 0x30, 0x18, 0x30, 0x60, 0x00, 0xfc, 0x00, 0x18, 0x30, 0x60, 0x30, 0x18, 0x00, 0xfc, 0x00,
+ 0x0e, 0x1b, 0x1b, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xd8, 0xd8, 0x70,
+ 0x30, 0x30, 0x00, 0xfc, 0x00, 0x30, 0x30, 0x00, 0x00, 0x76, 0xdc, 0x00, 0x76, 0xdc, 0x00, 0x00,
+ 0x38, 0x6c, 0x6c, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x0f, 0x0c, 0x0c, 0x0c, 0xec, 0x6c, 0x3c, 0x1c,
+ 0x78, 0x6c, 0x6c, 0x6c, 0x6c, 0x00, 0x00, 0x00, 0x70, 0x18, 0x30, 0x60, 0x78, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x3c, 0x3c, 0x3c, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+};
+
+const uint8_t avpriv_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
+};
diff --git a/libavutil/symbols.h b/libavutil/xga_font_data.h
similarity index 70%
rename from libavutil/symbols.h
rename to libavutil/xga_font_data.h
index 6011da2..5e40f54 100644
--- a/libavutil/symbols.h
+++ b/libavutil/xga_font_data.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Ronald S. Bultje <rsbultje@gmail.com>
+ * CGA/EGA/VGA ROM font data
  *
  * This file is part of FFmpeg.
  *
@@ -18,15 +18,18 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#ifndef AVUTIL_SYMBOLS_H
-#define AVUTIL_SYMBOLS_H
+/**
+ * @file
+ * CGA/EGA/VGA ROM font data
+ */
 
-#include "libavutil/avconfig.h"
+#ifndef AVUTIL_XGA_FONT_DATA_H
+#define AVUTIL_XGA_FONT_DATA_H
 
-#if AV_HAVE_SHARED_LIBS && defined(_MSC_VER) && !defined(COMPILING_avutil)
-#define AVUTIL_SYMBOL __declspec(dllimport)
-#else
-#define AVUTIL_SYMBOL
-#endif
+#include <stdint.h>
+#include "internal.h"
 
-#endif /* AVUTIL_SYMBOLS_H */
+extern av_export const uint8_t avpriv_cga_font[2048];
+extern av_export const uint8_t avpriv_vga16_font[4096];
+
+#endif /* AVUTIL_XGA_FONT_DATA_H */
diff --git a/libavutil/xtea.c b/libavutil/xtea.c
index 1c2bd04..28780fb 100644
--- a/libavutil/xtea.c
+++ b/libavutil/xtea.c
@@ -50,7 +50,7 @@
     if (decrypt) {
 #if CONFIG_SMALL
         int i;
-        uint32_t delta = 0x9E3779B9, sum = delta * 32;
+        uint32_t delta = 0x9E3779B9U, sum = delta * 32;
 
         for (i = 0; i < 32; i++) {
             v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + ctx->key[(sum >> 11) & 3]);
@@ -60,7 +60,7 @@
 #else
 #define DSTEP(SUM, K0, K1) \
             v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (SUM + K0); \
-            v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (SUM - 0x9E3779B9 + K1)
+            v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (SUM - 0x9E3779B9U + K1)
 
         DSTEP(0xC6EF3720U, k2, k3);
         DSTEP(0x28B7BD67U, k3, k2);
@@ -96,14 +96,14 @@
         DSTEP(0x9E3779B9U, k3, k0);
 #endif
         if (iv) {
-            v0 ^= AV_RB32(iv  );
-            v1 ^= AV_RB32(iv+4);
+            v0 ^= AV_RB32(iv);
+            v1 ^= AV_RB32(iv + 4);
             memcpy(iv, src, 8);
         }
     } else {
 #if CONFIG_SMALL
         int i;
-        uint32_t sum = 0, delta = 0x9E3779B9;
+        uint32_t sum = 0, delta = 0x9E3779B9U;
 
         for (i = 0; i < 32; i++) {
             v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + ctx->key[sum & 3]);
@@ -113,7 +113,7 @@
 #else
 #define ESTEP(SUM, K0, K1) \
             v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (SUM + K0);\
-            v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (SUM + 0x9E3779B9 + K1)
+            v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (SUM + 0x9E3779B9U + K1)
         ESTEP(0x00000000U, k0, k3);
         ESTEP(0x9E3779B9U, k1, k2);
         ESTEP(0x3C6EF372U, k2, k1);
@@ -220,27 +220,39 @@
     { 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41 }
 };
 
+#undef exit
+static void test_xtea(AVXTEA *ctx, uint8_t *dst, const uint8_t *src,
+                      const uint8_t *ref, int len, uint8_t *iv, int dir,
+                      const char *test)
+{
+    av_xtea_crypt(ctx, dst, src, len, iv, dir);
+    if (memcmp(dst, ref, 8*len)) {
+        int i;
+        printf("%s failed\ngot      ", test);
+        for (i = 0; i < 8*len; i++)
+            printf("%02x ", dst[i]);
+        printf("\nexpected ");
+        for (i = 0; i < 8*len; i++)
+            printf("%02x ", ref[i]);
+        printf("\n");
+        exit(1);
+    }
+}
+
 int main(void)
 {
     AVXTEA ctx;
     uint8_t buf[8], iv[8];
     int i;
     const uint8_t src[32] = "HelloWorldHelloWorldHelloWorld";
-    uint8_t  ct[32];
-    uint8_t  pl[32];
-
-#define CHECK(dst, src, ref, len, iv, dir, error) \
-        av_xtea_crypt(&ctx, dst, src, len, iv, dir);\
-        if (memcmp(dst, ref, 8*len)) {\
-            printf(error);\
-            return 1;\
-        }
+    uint8_t ct[32];
+    uint8_t pl[32];
 
     for (i = 0; i < XTEA_NUM_TESTS; i++) {
         av_xtea_init(&ctx, xtea_test_key[i]);
 
-        CHECK(buf, xtea_test_pt[i], xtea_test_ct[i], 1, NULL, 0, "Test encryption failed.\n");
-        CHECK(buf, xtea_test_ct[i], xtea_test_pt[i], 1, NULL, 1, "Test decryption failed.\n");
+        test_xtea(&ctx, buf, xtea_test_pt[i], xtea_test_ct[i], 1, NULL, 0, "encryption");
+        test_xtea(&ctx, buf, xtea_test_ct[i], xtea_test_pt[i], 1, NULL, 1, "decryption");
 
         /* encrypt */
         memcpy(iv, "HALLO123", 8);
@@ -248,10 +260,10 @@
 
         /* decrypt into pl */
         memcpy(iv, "HALLO123", 8);
-        CHECK(pl, ct, src, 4, iv, 1, "Test IV decryption failed.\n");
+        test_xtea(&ctx, pl, ct, src, 4, iv, 1, "CBC decryption");
 
         memcpy(iv, "HALLO123", 8);
-        CHECK(ct, ct, src, 4, iv, 1, "Test IV inplace decryption failed.\n");
+        test_xtea(&ctx, ct, ct, src, 4, iv, 1, "CBC inplace decryption");
     }
 
     printf("Test encryption/decryption success.\n");
diff --git a/libpostproc/postprocess.c b/libpostproc/postprocess.c
index f0d97d3..afe3f13 100644
--- a/libpostproc/postprocess.c
+++ b/libpostproc/postprocess.c
@@ -130,7 +130,7 @@
 DECLARE_ASM_CONST(8, int, deringThreshold)= 20;
 
 
-static struct PPFilter filters[]=
+static const struct PPFilter filters[]=
 {
     {"hb", "hdeblock",              1, 1, 3, H_DEBLOCK},
     {"vb", "vdeblock",              1, 2, 4, V_DEBLOCK},
@@ -201,7 +201,7 @@
 /**
  * Check if the given 8x8 Block is mostly "flat"
  */
-static inline int isHorizDC_C(uint8_t src[], int stride, PPContext *c)
+static inline int isHorizDC_C(const uint8_t src[], int stride, const PPContext *c)
 {
     int numEq= 0;
     int y;
@@ -224,7 +224,7 @@
 /**
  * Check if the middle 8x8 Block in the given 8x16 block is flat
  */
-static inline int isVertDC_C(uint8_t src[], int stride, PPContext *c)
+static inline int isVertDC_C(const uint8_t src[], int stride, const PPContext *c)
 {
     int numEq= 0;
     int y;
@@ -246,7 +246,7 @@
     return numEq > c->ppMode.flatnessThreshold;
 }
 
-static inline int isHorizMinMaxOk_C(uint8_t src[], int stride, int QP)
+static inline int isHorizMinMaxOk_C(const uint8_t src[], int stride, int QP)
 {
     int i;
     for(i=0; i<2; i++){
@@ -262,7 +262,7 @@
     return 1;
 }
 
-static inline int isVertMinMaxOk_C(uint8_t src[], int stride, int QP)
+static inline int isVertMinMaxOk_C(const uint8_t src[], int stride, int QP)
 {
     int x;
     src+= stride*4;
@@ -275,7 +275,7 @@
     return 1;
 }
 
-static inline int horizClassify_C(uint8_t src[], int stride, PPContext *c)
+static inline int horizClassify_C(const uint8_t src[], int stride, const PPContext *c)
 {
     if( isHorizDC_C(src, stride, c) ){
         if( isHorizMinMaxOk_C(src, stride, c->QP) )
@@ -287,7 +287,7 @@
     }
 }
 
-static inline int vertClassify_C(uint8_t src[], int stride, PPContext *c)
+static inline int vertClassify_C(const uint8_t src[], int stride, const PPContext *c)
 {
     if( isVertDC_C(src, stride, c) ){
         if( isVertMinMaxOk_C(src, stride, c->QP) )
@@ -299,7 +299,7 @@
     }
 }
 
-static inline void doHorizDefFilter_C(uint8_t dst[], int stride, PPContext *c)
+static inline void doHorizDefFilter_C(uint8_t dst[], int stride, const PPContext *c)
 {
     int y;
     for(y=0; y<BLOCK_SIZE; y++){
@@ -338,7 +338,7 @@
  * Do a horizontal low pass filter on the 10x8 block (dst points to middle 8x8 Block)
  * using the 9-Tap Filter (1,1,2,2,4,2,2,1,1)/16 (C version)
  */
-static inline void doHorizLowPass_C(uint8_t dst[], int stride, PPContext *c)
+static inline void doHorizLowPass_C(uint8_t dst[], int stride, const PPContext *c)
 {
     int y;
     for(y=0; y<BLOCK_SIZE; y++){
@@ -436,7 +436,9 @@
 /**
  * accurate deblock filter
  */
-static av_always_inline void do_a_deblock_C(uint8_t *src, int step, int stride, PPContext *c){
+static av_always_inline void do_a_deblock_C(uint8_t *src, int step,
+                                            int stride, const PPContext *c)
+{
     int y;
     const int QP= c->QP;
     const int dcOffset= ((c->nonBQP*c->ppMode.baseDcDiff)>>8) + 1;
@@ -538,136 +540,81 @@
 //Note: we have C, MMX, MMX2, 3DNOW version there is no 3DNOW+MMX2 one
 //Plain C versions
 //we always compile C for testing which needs bitexactness
-#define COMPILE_C
+#define TEMPLATE_PP_C 1
+#include "postprocess_template.c"
 
 #if HAVE_ALTIVEC
-#define COMPILE_ALTIVEC
-#endif //HAVE_ALTIVEC
+#   define TEMPLATE_PP_ALTIVEC 1
+#   include "postprocess_altivec_template.c"
+#   include "postprocess_template.c"
+#endif
 
 #if ARCH_X86 && HAVE_INLINE_ASM
-
-#if (HAVE_MMX_INLINE && !HAVE_AMD3DNOW_INLINE && !HAVE_MMXEXT_INLINE) || CONFIG_RUNTIME_CPUDETECT
-#define COMPILE_MMX
+#    if CONFIG_RUNTIME_CPUDETECT
+#        define TEMPLATE_PP_MMX 1
+#        include "postprocess_template.c"
+#        define TEMPLATE_PP_MMXEXT 1
+#        include "postprocess_template.c"
+#        define TEMPLATE_PP_3DNOW 1
+#        include "postprocess_template.c"
+#        define TEMPLATE_PP_SSE2 1
+#        include "postprocess_template.c"
+#    else
+#        if HAVE_SSE2_INLINE
+#            define TEMPLATE_PP_SSE2 1
+#            include "postprocess_template.c"
+#        elif HAVE_MMXEXT_INLINE
+#            define TEMPLATE_PP_MMXEXT 1
+#            include "postprocess_template.c"
+#        elif HAVE_AMD3DNOW_INLINE
+#            define TEMPLATE_PP_3DNOW 1
+#            include "postprocess_template.c"
+#        elif HAVE_MMX_INLINE
+#            define TEMPLATE_PP_MMX 1
+#            include "postprocess_template.c"
+#        endif
+#    endif
 #endif
 
-#if HAVE_MMXEXT_INLINE || CONFIG_RUNTIME_CPUDETECT
-#define COMPILE_MMX2
-#endif
-
-#if (HAVE_AMD3DNOW_INLINE && !HAVE_MMXEXT_INLINE) || CONFIG_RUNTIME_CPUDETECT
-#define COMPILE_3DNOW
-#endif
-#endif /* ARCH_X86 */
-
-#undef HAVE_MMX_INLINE
-#define HAVE_MMX_INLINE 0
-#undef HAVE_MMXEXT_INLINE
-#define HAVE_MMXEXT_INLINE 0
-#undef HAVE_AMD3DNOW_INLINE
-#define HAVE_AMD3DNOW_INLINE 0
-#undef HAVE_ALTIVEC
-#define HAVE_ALTIVEC 0
-
-#ifdef COMPILE_C
-#define RENAME(a) a ## _C
-#include "postprocess_template.c"
-#endif
-
-#ifdef COMPILE_ALTIVEC
-#undef RENAME
-#undef HAVE_ALTIVEC
-#define HAVE_ALTIVEC 1
-#define RENAME(a) a ## _altivec
-#include "postprocess_altivec_template.c"
-#include "postprocess_template.c"
-#endif
-
-//MMX versions
-#ifdef COMPILE_MMX
-#undef RENAME
-#undef HAVE_MMX_INLINE
-#define HAVE_MMX_INLINE 1
-#define RENAME(a) a ## _MMX
-#include "postprocess_template.c"
-#endif
-
-//MMX2 versions
-#ifdef COMPILE_MMX2
-#undef RENAME
-#undef HAVE_MMX_INLINE
-#undef HAVE_MMXEXT_INLINE
-#define HAVE_MMX_INLINE 1
-#define HAVE_MMXEXT_INLINE 1
-#define RENAME(a) a ## _MMX2
-#include "postprocess_template.c"
-#endif
-
-//3DNOW versions
-#ifdef COMPILE_3DNOW
-#undef RENAME
-#undef HAVE_MMX_INLINE
-#undef HAVE_MMXEXT_INLINE
-#undef HAVE_AMD3DNOW_INLINE
-#define HAVE_MMX_INLINE 1
-#define HAVE_MMXEXT_INLINE 0
-#define HAVE_AMD3DNOW_INLINE 1
-#define RENAME(a) a ## _3DNow
-#include "postprocess_template.c"
-#endif
-
-// minor note: the HAVE_xyz is messed up after that line so do not use it.
+typedef void (*pp_fn)(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);
 
 static inline void 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, pp_mode *vm, pp_context *vc)
 {
+    pp_fn pp = postProcess_C;
     PPContext *c= (PPContext *)vc;
     PPMode *ppMode= (PPMode *)vm;
     c->ppMode= *ppMode; //FIXME
 
-    if(ppMode->lumMode & BITEXACT) {
-        postProcess_C(src, srcStride, dst, dstStride, width, height, QPs, QPStride, isColor, c);
-        return;
-    }
-
-    // Using ifs here as they are faster than function pointers although the
-    // difference would not be measurable here but it is much better because
-    // someone might exchange the CPU whithout restarting MPlayer ;)
+    if (!(ppMode->lumMode & BITEXACT)) {
 #if CONFIG_RUNTIME_CPUDETECT
 #if ARCH_X86 && HAVE_INLINE_ASM
-    // ordered per speed fastest first
-    if(c->cpuCaps & PP_CPU_CAPS_MMX2)
-        postProcess_MMX2(src, srcStride, dst, dstStride, width, height, QPs, QPStride, isColor, c);
-    else if(c->cpuCaps & PP_CPU_CAPS_3DNOW)
-        postProcess_3DNow(src, srcStride, dst, dstStride, width, height, QPs, QPStride, isColor, c);
-    else if(c->cpuCaps & PP_CPU_CAPS_MMX)
-        postProcess_MMX(src, srcStride, dst, dstStride, width, height, QPs, QPStride, isColor, c);
-    else
-        postProcess_C(src, srcStride, dst, dstStride, width, height, QPs, QPStride, isColor, c);
-#else
-#if HAVE_ALTIVEC
-    if(c->cpuCaps & PP_CPU_CAPS_ALTIVEC)
-            postProcess_altivec(src, srcStride, dst, dstStride, width, height, QPs, QPStride, isColor, c);
-    else
-#endif
-            postProcess_C(src, srcStride, dst, dstStride, width, height, QPs, QPStride, isColor, c);
+        // ordered per speed fastest first
+        if      (c->cpuCaps & AV_CPU_FLAG_SSE2)     pp = postProcess_SSE2;
+        else if (c->cpuCaps & AV_CPU_FLAG_MMXEXT)   pp = postProcess_MMX2;
+        else if (c->cpuCaps & AV_CPU_FLAG_3DNOW)    pp = postProcess_3DNow;
+        else if (c->cpuCaps & AV_CPU_FLAG_MMX)      pp = postProcess_MMX;
+#elif HAVE_ALTIVEC
+        if      (c->cpuCaps & AV_CPU_FLAG_ALTIVEC)  pp = postProcess_altivec;
 #endif
 #else /* CONFIG_RUNTIME_CPUDETECT */
-#if   HAVE_MMXEXT_INLINE
-            postProcess_MMX2(src, srcStride, dst, dstStride, width, height, QPs, QPStride, isColor, c);
+#if     HAVE_SSE2_INLINE
+        pp = postProcess_SSE2;
+#elif   HAVE_MMXEXT_INLINE
+        pp = postProcess_MMX2;
 #elif HAVE_AMD3DNOW_INLINE
-            postProcess_3DNow(src, srcStride, dst, dstStride, width, height, QPs, QPStride, isColor, c);
+        pp = postProcess_3DNow;
 #elif HAVE_MMX_INLINE
-            postProcess_MMX(src, srcStride, dst, dstStride, width, height, QPs, QPStride, isColor, c);
+        pp = postProcess_MMX;
 #elif HAVE_ALTIVEC
-            postProcess_altivec(src, srcStride, dst, dstStride, width, height, QPs, QPStride, isColor, c);
-#else
-            postProcess_C(src, srcStride, dst, dstStride, width, height, QPs, QPStride, isColor, c);
+        pp = postProcess_altivec;
 #endif
 #endif /* !CONFIG_RUNTIME_CPUDETECT */
-}
+    }
 
-//static void postProcess(uint8_t src[], int srcStride, uint8_t dst[], int dstStride, int width, int height,
-//        QP_STORE_T QPs[], int QPStride, int isColor, struct PPMode *ppMode);
+    pp(src, srcStride, dst, dstStride, width, height, QPs, QPStride, isColor, c);
+}
 
 /* -pp Command line Help
 */
@@ -957,7 +904,6 @@
 
     memset(c, 0, sizeof(PPContext));
     c->av_class = &av_codec_context_class;
-    c->cpuCaps= cpuCaps;
     if(cpuCaps&PP_FORMAT){
         c->hChromaSubSample= cpuCaps&0x3;
         c->vChromaSubSample= (cpuCaps>>4)&0x3;
@@ -965,6 +911,15 @@
         c->hChromaSubSample= 1;
         c->vChromaSubSample= 1;
     }
+    if (cpuCaps & PP_CPU_CAPS_AUTO) {
+        c->cpuCaps = av_get_cpu_flags();
+    } else {
+        c->cpuCaps = 0;
+        if (cpuCaps & PP_CPU_CAPS_MMX)      c->cpuCaps |= AV_CPU_FLAG_MMX;
+        if (cpuCaps & PP_CPU_CAPS_MMX2)     c->cpuCaps |= AV_CPU_FLAG_MMXEXT;
+        if (cpuCaps & PP_CPU_CAPS_3DNOW)    c->cpuCaps |= AV_CPU_FLAG_3DNOW;
+        if (cpuCaps & PP_CPU_CAPS_ALTIVEC)  c->cpuCaps |= AV_CPU_FLAG_ALTIVEC;
+    }
 
     reallocBuffers(c, width, height, stride, qpStride);
 
diff --git a/libpostproc/postprocess.h b/libpostproc/postprocess.h
index 623b3b5..b1a357a 100644
--- a/libpostproc/postprocess.h
+++ b/libpostproc/postprocess.h
@@ -84,6 +84,7 @@
 #define PP_CPU_CAPS_MMX2  0x20000000
 #define PP_CPU_CAPS_3DNOW 0x40000000
 #define PP_CPU_CAPS_ALTIVEC 0x10000000
+#define PP_CPU_CAPS_AUTO  0x00080000
 
 #define PP_FORMAT         0x00000008
 #define PP_FORMAT_420    (0x00000011|PP_FORMAT)
diff --git a/libpostproc/postprocess_altivec_template.c b/libpostproc/postprocess_altivec_template.c
index 3a37562..fa6ebe2 100644
--- a/libpostproc/postprocess_altivec_template.c
+++ b/libpostproc/postprocess_altivec_template.c
@@ -825,7 +825,7 @@
 #define doHorizDefFilter_altivec(a...) doHorizDefFilter_C(a)
 #define do_a_deblock_altivec(a...) do_a_deblock_C(a)
 
-static inline void RENAME(tempNoiseReducer)(uint8_t *src, int stride,
+static inline void tempNoiseReducer_altivec(uint8_t *src, int stride,
                                             uint8_t *tempBlurred, uint32_t *tempBlurredPast, int *maxNoise)
 {
     const vector signed char neg1 = vec_splat_s8(-1);
diff --git a/libpostproc/postprocess_internal.h b/libpostproc/postprocess_internal.h
index 33c5f69..b1b8f0c 100644
--- a/libpostproc/postprocess_internal.h
+++ b/libpostproc/postprocess_internal.h
@@ -20,7 +20,7 @@
 
 /**
  * @file
- * internal api header.
+ * internal API header.
  */
 
 #ifndef POSTPROC_POSTPROCESS_INTERNAL_H
@@ -28,6 +28,7 @@
 
 #include <string.h>
 #include "libavutil/avutil.h"
+#include "libavutil/intmath.h"
 #include "libavutil/log.h"
 #include "postprocess.h"
 
@@ -53,7 +54,7 @@
 #define H_X1_FILTER     0x2000                  // 8192
 #define H_A_DEBLOCK     0x4000
 
-/// select between full y range (255-0) or standart one (234-16)
+/// select between full y range (255-0) or standard one (234-16)
 #define FULL_Y_RANGE    0x8000                  // 32768
 
 //Deinterlacing Filters
@@ -75,12 +76,10 @@
 //filters on
 //#define COMPILE_TIME_MODE 0x77
 
-static inline int CLIP(int a){
-    if(a&256) return ((a)>>31)^(-1);
-    else      return a;
-}
+#define CLIP av_clip_uint8
+
 /**
- * Postprocessng filter.
+ * Postprocessing filter.
  */
 struct PPFilter{
     const char *shortName;
@@ -92,15 +91,15 @@
 };
 
 /**
- * Postprocessng mode.
+ * Postprocessing mode.
  */
 typedef struct PPMode{
-    int lumMode;                    ///< acivates filters for luminance
-    int chromMode;                  ///< acivates filters for chrominance
+    int lumMode;                    ///< activates filters for luminance
+    int chromMode;                  ///< activates filters for chrominance
     int error;                      ///< non zero on error
 
-    int minAllowedY;                ///< for brigtness correction
-    int maxAllowedY;                ///< for brihtness correction
+    int minAllowedY;                ///< for brightness correction
+    int maxAllowedY;                ///< for brightness correction
     float maxClippedThreshold;      ///< amount of "black" you are willing to lose to get a brightness-corrected picture
 
     int maxTmpNoise[3];             ///< for Temporal Noise Reducing filter (Maximal sum of abs differences)
diff --git a/libpostproc/postprocess_template.c b/libpostproc/postprocess_template.c
index e1a3977..0b77545 100644
--- a/libpostproc/postprocess_template.c
+++ b/libpostproc/postprocess_template.c
@@ -25,37 +25,86 @@
 
 #include "libavutil/x86/asm.h"
 
+/* A single TEMPLATE_PP_* should be defined (to 1) when this template is
+ * included. The following macros will define its dependencies to 1 as well
+ * (like MMX2 depending on MMX), and will define to 0 all the others. Every
+ * TEMPLATE_PP_* need to be undef at the end. */
+
+#ifdef TEMPLATE_PP_C
+#   define RENAME(a) a ## _C
+#else
+#   define TEMPLATE_PP_C 0
+#endif
+
+#ifdef TEMPLATE_PP_ALTIVEC
+#   define RENAME(a) a ## _altivec
+#else
+#   define TEMPLATE_PP_ALTIVEC 0
+#endif
+
+#ifdef TEMPLATE_PP_MMX
+#   define RENAME(a) a ## _MMX
+#else
+#   define TEMPLATE_PP_MMX 0
+#endif
+
+#ifdef TEMPLATE_PP_MMXEXT
+#   undef  TEMPLATE_PP_MMX
+#   define TEMPLATE_PP_MMX 1
+#   define RENAME(a) a ## _MMX2
+#else
+#   define TEMPLATE_PP_MMXEXT 0
+#endif
+
+#ifdef TEMPLATE_PP_3DNOW
+#   undef  TEMPLATE_PP_MMX
+#   define TEMPLATE_PP_MMX 1
+#   define RENAME(a) a ## _3DNow
+#else
+#   define TEMPLATE_PP_3DNOW 0
+#endif
+
+#ifdef TEMPLATE_PP_SSE2
+#   undef  TEMPLATE_PP_MMX
+#   define TEMPLATE_PP_MMX 1
+#   undef  TEMPLATE_PP_MMXEXT
+#   define TEMPLATE_PP_MMXEXT 1
+#   define RENAME(a) a ## _SSE2
+#else
+#   define TEMPLATE_PP_SSE2 0
+#endif
+
 #undef REAL_PAVGB
 #undef PAVGB
 #undef PMINUB
 #undef PMAXUB
 
-#if   HAVE_MMXEXT_INLINE
+#if   TEMPLATE_PP_MMXEXT
 #define REAL_PAVGB(a,b) "pavgb " #a ", " #b " \n\t"
-#elif HAVE_AMD3DNOW_INLINE
+#elif TEMPLATE_PP_3DNOW
 #define REAL_PAVGB(a,b) "pavgusb " #a ", " #b " \n\t"
 #endif
 #define PAVGB(a,b)  REAL_PAVGB(a,b)
 
-#if   HAVE_MMXEXT_INLINE
+#if   TEMPLATE_PP_MMXEXT
 #define PMINUB(a,b,t) "pminub " #a ", " #b " \n\t"
-#elif HAVE_MMX_INLINE
+#elif TEMPLATE_PP_MMX
 #define PMINUB(b,a,t) \
     "movq " #a ", " #t " \n\t"\
     "psubusb " #b ", " #t " \n\t"\
     "psubb " #t ", " #a " \n\t"
 #endif
 
-#if   HAVE_MMXEXT_INLINE
+#if   TEMPLATE_PP_MMXEXT
 #define PMAXUB(a,b) "pmaxub " #a ", " #b " \n\t"
-#elif HAVE_MMX_INLINE
+#elif TEMPLATE_PP_MMX
 #define PMAXUB(a,b) \
     "psubusb " #a ", " #b " \n\t"\
     "paddb " #a ", " #b " \n\t"
 #endif
 
 //FIXME? |255-0| = 1 (should not be a problem ...)
-#if HAVE_MMX_INLINE
+#if TEMPLATE_PP_MMX
 /**
  * Check if the middle 8x8 Block in the given 8x16 block is flat
  */
@@ -135,7 +184,7 @@
         "psubusb %%mm3, %%mm4                   \n\t"
 
         "                                       \n\t"
-#if HAVE_MMXEXT_INLINE
+#if TEMPLATE_PP_MMXEXT
         "pxor %%mm7, %%mm7                      \n\t"
         "psadbw %%mm7, %%mm0                    \n\t"
 #else
@@ -169,16 +218,16 @@
         return 2;
     }
 }
-#endif //HAVE_MMX_INLINE
+#endif //TEMPLATE_PP_MMX
 
 /**
  * Do a vertical low pass filter on the 8x16 block (only write to the 8x8 block in the middle)
  * using the 9-Tap Filter (1,1,2,2,4,2,2,1,1)/16
  */
-#if !HAVE_ALTIVEC
+#if !TEMPLATE_PP_ALTIVEC
 static inline void RENAME(doVertLowPass)(uint8_t *src, int stride, PPContext *c)
 {
-#if HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#if TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
     src+= stride*3;
     __asm__ volatile(        //"movv %0 %1 %2\n\t"
         "movq %2, %%mm0                         \n\t"  // QP,..., QP
@@ -305,7 +354,7 @@
         : "r" (src), "r" ((x86_reg)stride), "m" (c->pQPb)
         : "%"REG_a, "%"REG_c
     );
-#else //HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#else //TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
     const int l1= stride;
     const int l2= stride + l1;
     const int l3= stride + l2;
@@ -344,9 +393,9 @@
 
         src++;
     }
-#endif //HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#endif //TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
 }
-#endif //HAVE_ALTIVEC
+#endif //TEMPLATE_PP_ALTIVEC
 
 /**
  * Experimental Filter 1
@@ -357,7 +406,7 @@
  */
 static inline void RENAME(vertX1Filter)(uint8_t *src, int stride, PPContext *co)
 {
-#if HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#if TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
     src+= stride*3;
 
     __asm__ volatile(
@@ -443,7 +492,7 @@
         : "r" (src), "r" ((x86_reg)stride), "m" (co->pQPb)
         : "%"REG_a, "%"REG_c
     );
-#else //HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#else //TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
 
     const int l1= stride;
     const int l2= stride + l1;
@@ -477,13 +526,13 @@
         }
         src++;
     }
-#endif //HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#endif //TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
 }
 
-#if !HAVE_ALTIVEC
+#if !TEMPLATE_PP_ALTIVEC
 static inline void RENAME(doVertDefFilter)(uint8_t src[], int stride, PPContext *c)
 {
-#if HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#if TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
 /*
     uint8_t tmp[16];
     const int l1= stride;
@@ -764,7 +813,7 @@
     }
 }
 */
-#elif HAVE_MMX_INLINE
+#elif TEMPLATE_PP_MMX
     DECLARE_ALIGNED(8, uint64_t, tmp)[4]; // make space for 4 8-byte vars
     src+= stride*4;
     __asm__ volatile(
@@ -872,7 +921,7 @@
         "movq (%3), %%mm2                       \n\t" // 2L0 - 5L1 + 5L2 - 2L3
         "movq 8(%3), %%mm3                      \n\t" // 2H0 - 5H1 + 5H2 - 2H3
 
-#if HAVE_MMXEXT_INLINE
+#if TEMPLATE_PP_MMXEXT
         "movq %%mm7, %%mm6                      \n\t" // 0
         "psubw %%mm0, %%mm6                     \n\t"
         "pmaxsw %%mm6, %%mm0                    \n\t" // |2L4 - 5L5 + 5L6 - 2L7|
@@ -904,7 +953,7 @@
         "psubw %%mm6, %%mm3                     \n\t" // |2H0 - 5H1 + 5H2 - 2H3|
 #endif
 
-#if HAVE_MMXEXT_INLINE
+#if TEMPLATE_PP_MMXEXT
         "pminsw %%mm2, %%mm0                    \n\t"
         "pminsw %%mm3, %%mm1                    \n\t"
 #else
@@ -968,7 +1017,7 @@
         "pand %%mm2, %%mm4                      \n\t"
         "pand %%mm3, %%mm5                      \n\t"
 
-#if HAVE_MMXEXT_INLINE
+#if TEMPLATE_PP_MMXEXT
         "pminsw %%mm0, %%mm4                    \n\t"
         "pminsw %%mm1, %%mm5                    \n\t"
 #else
@@ -995,7 +1044,7 @@
         : "r" ((x86_reg)stride), "m" (c->pQPb), "r"(tmp)
         : "%"REG_a
     );
-#else //HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#else //TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
     const int l1= stride;
     const int l2= stride + l1;
     const int l3= stride + l2;
@@ -1033,14 +1082,14 @@
         }
         src++;
     }
-#endif //HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#endif //TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
 }
-#endif //HAVE_ALTIVEC
+#endif //TEMPLATE_PP_ALTIVEC
 
-#if !HAVE_ALTIVEC
+#if !TEMPLATE_PP_ALTIVEC
 static inline void RENAME(dering)(uint8_t src[], int stride, PPContext *c)
 {
-#if HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#if TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
     DECLARE_ALIGNED(8, uint64_t, tmp)[3];
     __asm__ volatile(
         "pxor %%mm6, %%mm6                      \n\t"
@@ -1060,7 +1109,7 @@
 
 #undef REAL_FIND_MIN_MAX
 #undef FIND_MIN_MAX
-#if HAVE_MMXEXT_INLINE
+#if TEMPLATE_PP_MMXEXT
 #define REAL_FIND_MIN_MAX(addr)\
         "movq " #addr ", %%mm0                  \n\t"\
         "pminub %%mm0, %%mm7                    \n\t"\
@@ -1087,7 +1136,7 @@
 
         "movq %%mm7, %%mm4                      \n\t"
         "psrlq $8, %%mm7                        \n\t"
-#if HAVE_MMXEXT_INLINE
+#if TEMPLATE_PP_MMXEXT
         "pminub %%mm4, %%mm7                    \n\t" // min of pixels
         "pshufw $0xF9, %%mm7, %%mm4             \n\t"
         "pminub %%mm4, %%mm7                    \n\t" // min of pixels
@@ -1112,7 +1161,7 @@
 
         "movq %%mm6, %%mm4                      \n\t"
         "psrlq $8, %%mm6                        \n\t"
-#if HAVE_MMXEXT_INLINE
+#if TEMPLATE_PP_MMXEXT
         "pmaxub %%mm4, %%mm6                    \n\t" // max of pixels
         "pshufw $0xF9, %%mm6, %%mm4             \n\t"
         "pmaxub %%mm4, %%mm6                    \n\t"
@@ -1266,7 +1315,7 @@
         : : "r" (src), "r" ((x86_reg)stride), "m" (c->pQPb), "m"(c->pQPb2), "q"(tmp)
         : "%"REG_a, "%"REG_d
     );
-#else //HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#else //TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
     int y;
     int min=255;
     int max=0;
@@ -1383,9 +1432,9 @@
 //        src[0] = src[7]=src[stride*7]=src[stride*7 + 7]=255;
     }
 #endif
-#endif //HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#endif //TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
 }
-#endif //HAVE_ALTIVEC
+#endif //TEMPLATE_PP_ALTIVEC
 
 /**
  * Deinterlace the given block by linearly interpolating every second line.
@@ -1395,7 +1444,7 @@
  */
 static inline void RENAME(deInterlaceInterpolateLinear)(uint8_t src[], int stride)
 {
-#if HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#if TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
     src+= 4*stride;
     __asm__ volatile(
         "lea (%0, %1), %%"REG_a"                \n\t"
@@ -1448,13 +1497,30 @@
  */
 static inline void RENAME(deInterlaceInterpolateCubic)(uint8_t src[], int stride)
 {
-#if HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#if TEMPLATE_PP_SSE2 || TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
     src+= stride*3;
     __asm__ volatile(
         "lea (%0, %1), %%"REG_a"                \n\t"
         "lea (%%"REG_a", %1, 4), %%"REG_d"      \n\t"
         "lea (%%"REG_d", %1, 4), %%"REG_c"      \n\t"
         "add %1, %%"REG_c"                      \n\t"
+#if TEMPLATE_PP_SSE2
+        "pxor %%xmm7, %%xmm7                    \n\t"
+#define REAL_DEINT_CUBIC(a,b,c,d,e)\
+        "movq " #a ", %%xmm0                    \n\t"\
+        "movq " #b ", %%xmm1                    \n\t"\
+        "movq " #d ", %%xmm2                    \n\t"\
+        "movq " #e ", %%xmm3                    \n\t"\
+        "pavgb %%xmm2, %%xmm1                   \n\t"\
+        "pavgb %%xmm3, %%xmm0                   \n\t"\
+        "punpcklbw %%xmm7, %%xmm0               \n\t"\
+        "punpcklbw %%xmm7, %%xmm1               \n\t"\
+        "psubw %%xmm1, %%xmm0                   \n\t"\
+        "psraw $3, %%xmm0                       \n\t"\
+        "psubw %%xmm0, %%xmm1                   \n\t"\
+        "packuswb %%xmm1, %%xmm1                \n\t"\
+        "movlps %%xmm1, " #c "                  \n\t"
+#else //TEMPLATE_PP_SSE2
         "pxor %%mm7, %%mm7                      \n\t"
 //      0       1       2       3       4       5       6       7       8       9       10
 //      %0      eax     eax+%1  eax+2%1 %0+4%1  edx     edx+%1  edx+2%1 %0+8%1  edx+4%1 ecx
@@ -1465,7 +1531,7 @@
         "movq " #d ", %%mm2                     \n\t"\
         "movq " #e ", %%mm3                     \n\t"\
         PAVGB(%%mm2, %%mm1)                             /* (b+d) /2 */\
-        PAVGB(%%mm3, %%mm0)                             /* a(a+e) /2 */\
+        PAVGB(%%mm3, %%mm0)                             /* (a+e) /2 */\
         "movq %%mm0, %%mm2                      \n\t"\
         "punpcklbw %%mm7, %%mm0                 \n\t"\
         "punpckhbw %%mm7, %%mm2                 \n\t"\
@@ -1480,6 +1546,7 @@
         "psubw %%mm2, %%mm3                     \n\t"   /* H(9b + 9d - a - e)/16 */\
         "packuswb %%mm3, %%mm1                  \n\t"\
         "movq %%mm1, " #c "                     \n\t"
+#endif //TEMPLATE_PP_SSE2
 #define DEINT_CUBIC(a,b,c,d,e)  REAL_DEINT_CUBIC(a,b,c,d,e)
 
 DEINT_CUBIC((%0)        , (%%REGa, %1), (%%REGa, %1, 2), (%0, %1, 4) , (%%REGd, %1))
@@ -1488,9 +1555,14 @@
 DEINT_CUBIC((%%REGd, %1), (%0, %1, 8) , (%%REGd, %1, 4), (%%REGc)    , (%%REGc, %1, 2))
 
         : : "r" (src), "r" ((x86_reg)stride)
-        : "%"REG_a, "%"REG_d, "%"REG_c
+        :
+#if TEMPLATE_PP_SSE2
+        XMM_CLOBBERS("%xmm0", "%xmm1", "%xmm2", "%xmm3", "%xmm7",)
+#endif
+        "%"REG_a, "%"REG_d, "%"REG_c
     );
-#else //HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#undef REAL_DEINT_CUBIC
+#else //TEMPLATE_PP_SSE2 || TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
     int x;
     src+= stride*3;
     for(x=0; x<8; x++){
@@ -1500,7 +1572,7 @@
         src[stride*9] = CLIP((-src[stride*6] + 9*src[stride*8] + 9*src[stride*10] - src[stride*12])>>4);
         src++;
     }
-#endif //HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#endif //TEMPLATE_PP_SSE2 || TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
 }
 
 /**
@@ -1512,7 +1584,7 @@
  */
 static inline void RENAME(deInterlaceFF)(uint8_t src[], int stride, uint8_t *tmp)
 {
-#if HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#if TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
     src+= stride*4;
     __asm__ volatile(
         "lea (%0, %1), %%"REG_a"                \n\t"
@@ -1561,7 +1633,7 @@
         : : "r" (src), "r" ((x86_reg)stride), "r"(tmp)
         : "%"REG_a, "%"REG_d
     );
-#else //HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#else //TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
     int x;
     src+= stride*4;
     for(x=0; x<8; x++){
@@ -1579,7 +1651,7 @@
 
         src++;
     }
-#endif //HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#endif //TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
 }
 
 /**
@@ -1591,7 +1663,7 @@
  */
 static inline void RENAME(deInterlaceL5)(uint8_t src[], int stride, uint8_t *tmp, uint8_t *tmp2)
 {
-#if HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#if TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
     src+= stride*4;
     __asm__ volatile(
         "lea (%0, %1), %%"REG_a"                \n\t"
@@ -1651,7 +1723,7 @@
         : : "r" (src), "r" ((x86_reg)stride), "r"(tmp), "r"(tmp2)
         : "%"REG_a, "%"REG_d
     );
-#else //HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#else //TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
     int x;
     src+= stride*4;
     for(x=0; x<8; x++){
@@ -1680,7 +1752,7 @@
 
         src++;
     }
-#endif //HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#endif //TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
 }
 
 /**
@@ -1692,7 +1764,7 @@
  */
 static inline void RENAME(deInterlaceBlendLinear)(uint8_t src[], int stride, uint8_t *tmp)
 {
-#if HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#if TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
     src+= 4*stride;
     __asm__ volatile(
         "lea (%0, %1), %%"REG_a"                \n\t"
@@ -1739,7 +1811,7 @@
         : : "r" (src), "r" ((x86_reg)stride), "r" (tmp)
         : "%"REG_a, "%"REG_d
     );
-#else //HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#else //TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
     int a, b, c, x;
     src+= 4*stride;
 
@@ -1782,7 +1854,7 @@
         src += 4;
         tmp += 4;
     }
-#endif //HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#endif //TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
 }
 
 /**
@@ -1793,9 +1865,9 @@
  */
 static inline void RENAME(deInterlaceMedian)(uint8_t src[], int stride)
 {
-#if HAVE_MMX_INLINE
+#if TEMPLATE_PP_MMX
     src+= 4*stride;
-#if HAVE_MMXEXT_INLINE
+#if TEMPLATE_PP_MMXEXT
     __asm__ volatile(
         "lea (%0, %1), %%"REG_a"                \n\t"
         "lea (%%"REG_a", %1, 4), %%"REG_d"      \n\t"
@@ -1885,8 +1957,8 @@
         : : "r" (src), "r" ((x86_reg)stride)
         : "%"REG_a, "%"REG_d
     );
-#endif //HAVE_MMXEXT_INLINE
-#else //HAVE_MMX_INLINE
+#endif //TEMPLATE_PP_MMXEXT
+#else //TEMPLATE_PP_MMX
     int x, y;
     src+= 4*stride;
     // FIXME - there should be a way to do a few columns in parallel like w/mmx
@@ -1905,10 +1977,10 @@
         }
         src++;
     }
-#endif //HAVE_MMX_INLINE
+#endif //TEMPLATE_PP_MMX
 }
 
-#if HAVE_MMX_INLINE
+#if TEMPLATE_PP_MMX
 /**
  * Transpose and shift the given 8x8 Block into dst1 and dst2.
  */
@@ -2073,10 +2145,10 @@
         : "%"REG_a, "%"REG_d
     );
 }
-#endif //HAVE_MMX_INLINE
+#endif //TEMPLATE_PP_MMX
 //static long test=0;
 
-#if !HAVE_ALTIVEC
+#if !TEMPLATE_PP_ALTIVEC
 static inline void RENAME(tempNoiseReducer)(uint8_t *src, int stride,
                                     uint8_t *tempBlurred, uint32_t *tempBlurredPast, int *maxNoise)
 {
@@ -2087,7 +2159,7 @@
 
 #define FAST_L2_DIFF
 //#define L1_DIFF //u should change the thresholds too if u try that one
-#if HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#if TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
     __asm__ volatile(
         "lea (%2, %2, 2), %%"REG_a"             \n\t" // 3*stride
         "lea (%2, %2, 4), %%"REG_d"             \n\t" // 5*stride
@@ -2375,7 +2447,7 @@
         :: "r" (src), "r" (tempBlurred), "r"((x86_reg)stride), "m" (tempBlurredPast)
         : "%"REG_a, "%"REG_d, "%"REG_c, "memory"
     );
-#else //HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#else //TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
 {
     int y;
     int d=0;
@@ -2458,11 +2530,11 @@
         }
     }
 }
-#endif //HAVE_MMXEXT_INLINE || HAVE_AMD3DNOW_INLINE
+#endif //TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW
 }
-#endif //HAVE_ALTIVEC
+#endif //TEMPLATE_PP_ALTIVEC
 
-#if HAVE_MMX_INLINE
+#if TEMPLATE_PP_MMX
 /**
  * accurate deblock filter
  */
@@ -2865,7 +2937,7 @@
             "movq (%4), %%mm2                       \n\t" // 2L0 - 5L1 + 5L2 - 2L3
             "movq 8(%4), %%mm3                      \n\t" // 2H0 - 5H1 + 5H2 - 2H3
 
-#if HAVE_MMXEXT_INLINE
+#if TEMPLATE_PP_MMXEXT
             "movq %%mm7, %%mm6                      \n\t" // 0
             "psubw %%mm0, %%mm6                     \n\t"
             "pmaxsw %%mm6, %%mm0                    \n\t" // |2L4 - 5L5 + 5L6 - 2L7|
@@ -2897,7 +2969,7 @@
             "psubw %%mm6, %%mm3                     \n\t" // |2H0 - 5H1 + 5H2 - 2H3|
 #endif
 
-#if HAVE_MMXEXT_INLINE
+#if TEMPLATE_PP_MMXEXT
             "pminsw %%mm2, %%mm0                    \n\t"
             "pminsw %%mm3, %%mm1                    \n\t"
 #else
@@ -2961,7 +3033,7 @@
             "pand %%mm2, %%mm4                      \n\t"
             "pand %%mm3, %%mm5                      \n\t"
 
-#if HAVE_MMXEXT_INLINE
+#if TEMPLATE_PP_MMXEXT
             "pminsw %%mm0, %%mm4                    \n\t"
             "pminsw %%mm1, %%mm5                    \n\t"
 #else
@@ -2998,7 +3070,7 @@
 }
     } */
 }
-#endif //HAVE_MMX_INLINE
+#endif //TEMPLATE_PP_MMX
 
 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 *c);
@@ -3013,18 +3085,18 @@
 static inline void RENAME(blockCopy)(uint8_t dst[], int dstStride, const uint8_t src[], int srcStride,
                                      int levelFix, int64_t *packedOffsetAndScale)
 {
-#if !HAVE_MMX_INLINE
+#if !TEMPLATE_PP_MMX
     int i;
 #endif
     if(levelFix){
-#if HAVE_MMX_INLINE
+#if TEMPLATE_PP_MMX
     __asm__ volatile(
         "movq (%%"REG_a"), %%mm2        \n\t" // packedYOffset
         "movq 8(%%"REG_a"), %%mm3       \n\t" // packedYScale
         "lea (%2,%4), %%"REG_a"         \n\t"
         "lea (%3,%5), %%"REG_d"         \n\t"
         "pxor %%mm4, %%mm4              \n\t"
-#if HAVE_MMXEXT_INLINE
+#if TEMPLATE_PP_MMXEXT
 #define REAL_SCALED_CPY(src1, src2, dst1, dst2)                                                \
         "movq " #src1 ", %%mm0          \n\t"\
         "movq " #src1 ", %%mm5          \n\t"\
@@ -3047,7 +3119,7 @@
         "movq %%mm0, " #dst1 "          \n\t"\
         "movq %%mm1, " #dst2 "          \n\t"\
 
-#else //HAVE_MMXEXT_INLINE
+#else //TEMPLATE_PP_MMXEXT
 #define REAL_SCALED_CPY(src1, src2, dst1, dst2)                                        \
         "movq " #src1 ", %%mm0          \n\t"\
         "movq " #src1 ", %%mm5          \n\t"\
@@ -3074,7 +3146,7 @@
         "movq %%mm0, " #dst1 "          \n\t"\
         "movq %%mm1, " #dst2 "          \n\t"\
 
-#endif //HAVE_MMXEXT_INLINE
+#endif //TEMPLATE_PP_MMXEXT
 #define SCALED_CPY(src1, src2, dst1, dst2)\
    REAL_SCALED_CPY(src1, src2, dst1, dst2)
 
@@ -3094,13 +3166,13 @@
         "r" ((x86_reg)dstStride)
         : "%"REG_d
     );
-#else //HAVE_MMX_INLINE
+#else //TEMPLATE_PP_MMX
     for(i=0; i<8; i++)
         memcpy( &(dst[dstStride*i]),
                 &(src[srcStride*i]), BLOCK_SIZE);
-#endif //HAVE_MMX_INLINE
+#endif //TEMPLATE_PP_MMX
     }else{
-#if HAVE_MMX_INLINE
+#if TEMPLATE_PP_MMX
     __asm__ volatile(
         "lea (%0,%2), %%"REG_a"                 \n\t"
         "lea (%1,%3), %%"REG_d"                 \n\t"
@@ -3127,11 +3199,11 @@
         "r" ((x86_reg)dstStride)
         : "%"REG_a, "%"REG_d
     );
-#else //HAVE_MMX_INLINE
+#else //TEMPLATE_PP_MMX
     for(i=0; i<8; i++)
         memcpy( &(dst[dstStride*i]),
                 &(src[srcStride*i]), BLOCK_SIZE);
-#endif //HAVE_MMX_INLINE
+#endif //TEMPLATE_PP_MMX
     }
 }
 
@@ -3140,7 +3212,7 @@
  */
 static inline void RENAME(duplicate)(uint8_t src[], int stride)
 {
-#if HAVE_MMX_INLINE
+#if TEMPLATE_PP_MMX
     __asm__ volatile(
         "movq (%0), %%mm0               \n\t"
         "add %1, %0                     \n\t"
@@ -3168,8 +3240,8 @@
 {
     DECLARE_ALIGNED(8, PPContext, c)= *c2; //copy to stack for faster access
     int x,y;
-#ifdef COMPILE_TIME_MODE
-    const int mode= COMPILE_TIME_MODE;
+#ifdef TEMPLATE_PP_TIME_MODE
+    const int mode= TEMPLATE_PP_TIME_MODE;
 #else
     const int mode= isColor ? c.ppMode.chromMode : c.ppMode.lumMode;
 #endif
@@ -3177,7 +3249,7 @@
     int QPCorrecture= 256*256;
 
     int copyAhead;
-#if HAVE_MMX_INLINE
+#if TEMPLATE_PP_MMX
     int i;
 #endif
 
@@ -3190,7 +3262,7 @@
     uint8_t * const tempDst= dstStride > 0 ? c.tempDst : c.tempDst - 23*dstStride;
     //const int mbWidth= isColor ? (width+7)>>3 : (width+15)>>4;
 
-#if HAVE_MMX_INLINE
+#if TEMPLATE_PP_MMX
     for(i=0; i<57; i++){
         int offset= ((i*c.ppMode.baseDcDiff)>>8) + 1;
         int threshold= offset*2 + 1;
@@ -3225,7 +3297,7 @@
 
         c.frameNum++;
         // first frame is fscked so we ignore it
-        if(c.frameNum == 1) yHistogram[0]= width*height/64*15/256;
+        if(c.frameNum == 1) yHistogram[0]= width*(uint64_t)height/64*15/256;
 
         for(i=0; i<256; i++){
             sum+= yHistogram[i];
@@ -3248,7 +3320,7 @@
 
         scale= (double)(c.ppMode.maxAllowedY - c.ppMode.minAllowedY) / (double)(white-black);
 
-#if HAVE_MMXEXT_INLINE
+#if TEMPLATE_PP_MMXEXT
         c.packedYScale= (uint16_t)(scale*256.0 + 0.5);
         c.packedYOffset= (((black*c.packedYScale)>>8) - c.ppMode.minAllowedY) & 0xFFFF;
 #else
@@ -3281,7 +3353,7 @@
         // with the L1 Cache of the P4 ... or only a few blocks at a time or soemthing
         for(x=0; x<width; x+=BLOCK_SIZE){
 
-#if HAVE_MMXEXT_INLINE
+#if TEMPLATE_PP_MMXEXT
 /*
             prefetchnta(srcBlock + (((x>>2)&6) + 5)*srcStride + 32);
             prefetchnta(srcBlock + (((x>>2)&6) + 6)*srcStride + 32);
@@ -3308,7 +3380,7 @@
                 : "%"REG_a, "%"REG_d
             );
 
-#elif HAVE_AMD3DNOW_INLINE
+#elif TEMPLATE_PP_3DNOW
 //FIXME check if this is faster on an 3dnow chip or if it is faster without the prefetch or ...
 /*          prefetch(srcBlock + (((x>>3)&3) + 5)*srcStride + 32);
             prefetch(srcBlock + (((x>>3)&3) + 9)*srcStride + 32);
@@ -3354,7 +3426,7 @@
         //1% speedup if these are here instead of the inner loop
         const uint8_t *srcBlock= &(src[y*srcStride]);
         uint8_t *dstBlock= &(dst[y*dstStride]);
-#if HAVE_MMX_INLINE
+#if TEMPLATE_PP_MMX
         uint8_t *tempBlock1= c.tempBlocks;
         uint8_t *tempBlock2= c.tempBlocks + 8;
 #endif
@@ -3390,7 +3462,7 @@
         // with the L1 Cache of the P4 ... or only a few blocks at a time or soemthing
         for(x=0; x<width; x+=BLOCK_SIZE){
             const int stride= dstStride;
-#if HAVE_MMX_INLINE
+#if TEMPLATE_PP_MMX
             uint8_t *tmpXchg;
 #endif
             if(isColor){
@@ -3404,7 +3476,7 @@
                 yHistogram[ srcBlock[srcStride*12 + 4] ]++;
             }
             c.QP= QP;
-#if HAVE_MMX_INLINE
+#if TEMPLATE_PP_MMX
             __asm__ volatile(
                 "movd %1, %%mm7         \n\t"
                 "packuswb %%mm7, %%mm7  \n\t" // 0, 0, 0, QP, 0, 0, 0, QP
@@ -3417,7 +3489,7 @@
 #endif
 
 
-#if HAVE_MMXEXT_INLINE
+#if TEMPLATE_PP_MMXEXT
 /*
             prefetchnta(srcBlock + (((x>>2)&6) + 5)*srcStride + 32);
             prefetchnta(srcBlock + (((x>>2)&6) + 6)*srcStride + 32);
@@ -3444,7 +3516,7 @@
                 : "%"REG_a, "%"REG_d
             );
 
-#elif HAVE_AMD3DNOW_INLINE
+#elif TEMPLATE_PP_3DNOW
 //FIXME check if this is faster on an 3dnow chip or if it is faster without the prefetch or ...
 /*          prefetch(srcBlock + (((x>>3)&3) + 5)*srcStride + 32);
             prefetch(srcBlock + (((x>>3)&3) + 9)*srcStride + 32);
@@ -3488,12 +3560,12 @@
                 }
             }
 
-#if HAVE_MMX_INLINE
+#if TEMPLATE_PP_MMX
             RENAME(transpose1)(tempBlock1, tempBlock2, dstBlock, dstStride);
 #endif
             /* check if we have a previous block to deblock it with dstBlock */
             if(x - 8 >= 0){
-#if HAVE_MMX_INLINE
+#if TEMPLATE_PP_MMX
                 if(mode & H_X1_FILTER)
                         RENAME(vertX1Filter)(tempBlock1, 16, &c);
                 else if(mode & H_DEBLOCK){
@@ -3514,7 +3586,7 @@
                 if(mode & H_X1_FILTER)
                     horizX1Filter(dstBlock-4, stride, QP);
                 else if(mode & H_DEBLOCK){
-#if HAVE_ALTIVEC
+#if TEMPLATE_PP_ALTIVEC
                     DECLARE_ALIGNED(16, unsigned char, tempBlock)[272];
                     int t;
                     transpose_16x8_char_toPackedAlign_altivec(tempBlock, dstBlock - (4 + 1), stride);
@@ -3539,7 +3611,7 @@
                 }else if(mode & H_A_DEBLOCK){
                     RENAME(do_a_deblock)(dstBlock-8, 1, stride, &c);
                 }
-#endif //HAVE_MMX_INLINE
+#endif //TEMPLATE_PP_MMX
                 if(mode & DERING){
                 //FIXME filter first line
                     if(y>0) RENAME(dering)(dstBlock - stride - 8, stride, &c);
@@ -3557,7 +3629,7 @@
             dstBlock+=8;
             srcBlock+=8;
 
-#if HAVE_MMX_INLINE
+#if TEMPLATE_PP_MMX
             tmpXchg= tempBlock1;
             tempBlock1= tempBlock2;
             tempBlock2 = tmpXchg;
@@ -3597,9 +3669,9 @@
                 + dstBlock[x +14*dstStride] + dstBlock[x +15*dstStride];
         }*/
     }
-#if   HAVE_AMD3DNOW_INLINE
+#if   TEMPLATE_PP_3DNOW
     __asm__ volatile("femms");
-#elif HAVE_MMX_INLINE
+#elif TEMPLATE_PP_MMX
     __asm__ volatile("emms");
 #endif
 
@@ -3629,3 +3701,11 @@
     *c2= c; //copy local context back
 
 }
+
+#undef RENAME
+#undef TEMPLATE_PP_C
+#undef TEMPLATE_PP_ALTIVEC
+#undef TEMPLATE_PP_MMX
+#undef TEMPLATE_PP_MMXEXT
+#undef TEMPLATE_PP_3DNOW
+#undef TEMPLATE_PP_SSE2
diff --git a/libpostproc/version.h b/libpostproc/version.h
index f634630..35e1772 100644
--- a/libpostproc/version.h
+++ b/libpostproc/version.h
@@ -30,7 +30,7 @@
 
 #ifndef LIBPOSTPROC_VERSION_MAJOR
 #define LIBPOSTPROC_VERSION_MAJOR 52
-#define LIBPOSTPROC_VERSION_MINOR  1
+#define LIBPOSTPROC_VERSION_MINOR  2
 #define LIBPOSTPROC_VERSION_MICRO 100
 #endif
 
diff --git a/library.mak b/library.mak
index a61680a..470795c 100644
--- a/library.mak
+++ b/library.mak
@@ -5,7 +5,8 @@
 LIBVERSION := $(lib$(NAME)_VERSION)
 LIBMAJOR   := $(lib$(NAME)_VERSION_MAJOR)
 INCINSTDIR := $(INCDIR)/lib$(NAME)
-THIS_LIB   := $(SUBDIR)$($(CONFIG_SHARED:yes=S)LIBNAME)
+
+INSTHEADERS := $(INSTHEADERS) $(HEADERS:%=$(SUBDIR)%)
 
 all-$(CONFIG_STATIC): $(SUBDIR)$(LIBNAME)
 all-$(CONFIG_SHARED): $(SUBDIR)$(SLIBNAME)
@@ -16,17 +17,23 @@
 $(SUBDIR)%-test.o: $(SUBDIR)%.c
 	$(COMPILE_C)
 
+$(SUBDIR)%-test.i: $(SUBDIR)%-test.c
+	$(CC) $(CCFLAGS) $(CC_E) $<
+
+$(SUBDIR)%-test.i: $(SUBDIR)%.c
+	$(CC) $(CCFLAGS) $(CC_E) $<
+
 $(SUBDIR)x86/%.o: $(SUBDIR)x86/%.asm
 	$(DEPYASM) $(YASMFLAGS) -I $(<D)/ -M -o $@ $< > $(@:.o=.d)
 	$(YASM) $(YASMFLAGS) -I $(<D)/ -o $@ $<
 
-$(OBJS): CPPFLAGS := -DCOMPILING_$(NAME)=1 $(CPPFLAGS)
-$(OBJS) $(OBJS:.o=.s) $(SUBDIR)%.h.o $(TESTOBJS): CPPFLAGS += -DHAVE_AV_CONFIG_H
-$(TESTOBJS): CPPFLAGS += -DTEST
+LIBOBJS := $(OBJS) $(SUBDIR)%.h.o $(TESTOBJS)
+$(LIBOBJS) $(LIBOBJS:.o=.s) $(LIBOBJS:.o=.i):   CPPFLAGS += -DHAVE_AV_CONFIG_H
+$(TESTOBJS) $(TESTOBJS:.o=.i): CPPFLAGS += -DTEST
 
 $(SUBDIR)$(LIBNAME): $(OBJS)
 	$(RM) $@
-	$(AR) $(ARFLAGS) $(AR_O) $^ $(EXTRAOBJS)
+	$(AR) $(ARFLAGS) $(AR_O) $^
 	$(RANLIB) $@
 
 install-headers: install-lib$(NAME)-headers install-lib$(NAME)-pkgconfig
@@ -35,15 +42,18 @@
 install-libs-$(CONFIG_SHARED): install-lib$(NAME)-shared
 
 define RULES
-$(EXAMPLES) $(TESTPROGS) $(TOOLS): %$(EXESUF): %.o
-	$$(LD) $(LDFLAGS) $$(LD_O) $$^ $(FULLNAME:%=$(LD_LIB)) $(FFEXTRALIBS) $$(ELIBS)
+$(EXAMPLES) $(TOOLS): THISLIB = $(FULLNAME:%=$(LD_LIB))
+$(TESTPROGS):         THISLIB = $(SUBDIR)$(LIBNAME)
+
+$(EXAMPLES) $(TESTPROGS) $(TOOLS): %$(EXESUF): %.o $(EXEOBJS)
+	$$(LD) $(LDFLAGS) $$(LD_O) $$(filter %.o,$$^) $$(THISLIB) $(FFEXTRALIBS) $$(ELIBS)
 
 $(SUBDIR)$(SLIBNAME): $(SUBDIR)$(SLIBNAME_WITH_MAJOR)
 	$(Q)cd ./$(SUBDIR) && $(LN_S) $(SLIBNAME_WITH_MAJOR) $(SLIBNAME)
 
 $(SUBDIR)$(SLIBNAME_WITH_MAJOR): $(OBJS) $(SUBDIR)lib$(NAME).ver
 	$(SLIB_CREATE_DEF_CMD)
-	$$(LD) $(SHFLAGS) $(LDFLAGS) $$(LD_O) $$(filter %.o,$$^) $(FFEXTRALIBS) $(EXTRAOBJS)
+	$$(LD) $(SHFLAGS) $(LDFLAGS) $$(LD_O) $$(filter %.o,$$^) $(FFEXTRALIBS)
 	$(SLIB_EXTRA_CMD)
 
 ifdef SUBDIR
@@ -95,8 +105,8 @@
 
 $(eval $(RULES))
 
-#$(EXAMPLES) $(TESTPROGS) $(TOOLS): $(THIS_LIB) $(DEP_LIBS)
-$(TESTPROGS): $(SUBDIR)$(LIBNAME)
+$(EXAMPLES) $(TOOLS): $(DEP_LIBS) $(SUBDIR)$($(CONFIG_SHARED:yes=S)LIBNAME)
+$(TESTPROGS):         $(DEP_LIBS) $(SUBDIR)$(LIBNAME)
 
 examples: $(EXAMPLES)
 testprogs: $(TESTPROGS)
diff --git a/libswresample/Makefile b/libswresample/Makefile
index d85ed8b..4c3ec1c 100644
--- a/libswresample/Makefile
+++ b/libswresample/Makefile
@@ -8,6 +8,7 @@
 
 OBJS = audioconvert.o                        \
        dither.o                              \
+       log2_tab.o                            \
        rematrix.o                            \
        resample.o                            \
        swresample.o                          \
diff --git a/libswresample/audioconvert.h b/libswresample/audioconvert.h
index 9a234d4..d8af003 100644
--- a/libswresample/audioconvert.h
+++ b/libswresample/audioconvert.h
@@ -31,7 +31,6 @@
 
 #include "swresample_internal.h"
 #include "libavutil/cpu.h"
-#include "libavutil/audioconvert.h"
 
 
 typedef void (conv_func_type)(uint8_t *po, const uint8_t *pi, int is, int os, uint8_t *end);
diff --git a/libswresample/log2_tab.c b/libswresample/log2_tab.c
new file mode 100644
index 0000000..47a1df0
--- /dev/null
+++ b/libswresample/log2_tab.c
@@ -0,0 +1 @@
+#include "libavutil/log2_tab.c"
diff --git a/libswresample/rematrix.c b/libswresample/rematrix.c
index 72da438..51658ce 100644
--- a/libswresample/rematrix.c
+++ b/libswresample/rematrix.c
@@ -19,45 +19,20 @@
  */
 
 #include "swresample_internal.h"
-#include "libavutil/audioconvert.h"
 #include "libavutil/avassert.h"
+#include "libavutil/channel_layout.h"
 
-#define ONE (1.0)
-#define R(x) x
-#define SAMPLE float
-#define COEFF float
-#define INTER float
-#define RENAME(x) x ## _float
+#define TEMPLATE_REMATRIX_FLT
 #include "rematrix_template.c"
-#undef SAMPLE
-#undef RENAME
-#undef R
-#undef ONE
-#undef COEFF
-#undef INTER
+#undef TEMPLATE_REMATRIX_FLT
 
-#define ONE (1.0)
-#define R(x) x
-#define SAMPLE double
-#define COEFF double
-#define INTER double
-#define RENAME(x) x ## _double
+#define TEMPLATE_REMATRIX_DBL
 #include "rematrix_template.c"
-#undef SAMPLE
-#undef RENAME
-#undef R
-#undef ONE
-#undef COEFF
-#undef INTER
+#undef TEMPLATE_REMATRIX_DBL
 
-#define ONE (-32768)
-#define R(x) (((x) + 16384)>>15)
-#define SAMPLE int16_t
-#define COEFF int
-#define INTER int
-#define RENAME(x) x ## _s16
+#define TEMPLATE_REMATRIX_S16
 #include "rematrix_template.c"
-
+#undef TEMPLATE_REMATRIX_S16
 
 #define FRONT_LEFT             0
 #define FRONT_RIGHT            1
@@ -158,7 +133,7 @@
 
     memset(s->matrix, 0, sizeof(s->matrix));
     for(i=0; i<64; i++){
-        if(in_ch_layout & out_ch_layout & (1LL<<i))
+        if(in_ch_layout & out_ch_layout & (1ULL<<i))
             matrix[i][i]= 1.0;
     }
 
diff --git a/libswresample/rematrix_template.c b/libswresample/rematrix_template.c
index 627bf1f..a0d3fd1 100644
--- a/libswresample/rematrix_template.c
+++ b/libswresample/rematrix_template.c
@@ -18,9 +18,32 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-typedef void (RENAME(mix_any_func_type))(SAMPLE **out, const SAMPLE **in1, COEFF *coeffp, int len);
+#if defined(TEMPLATE_REMATRIX_FLT)
+#    define ONE (1.0)
+#    define R(x) x
+#    define SAMPLE float
+#    define COEFF float
+#    define INTER float
+#    define RENAME(x) x ## _float
+#elif defined(TEMPLATE_REMATRIX_DBL)
+#    define ONE (1.0)
+#    define R(x) x
+#    define SAMPLE double
+#    define COEFF double
+#    define INTER double
+#    define RENAME(x) x ## _double
+#elif defined(TEMPLATE_REMATRIX_S16)
+#    define ONE (-32768)
+#    define R(x) (((x) + 16384)>>15)
+#    define SAMPLE int16_t
+#    define COEFF int
+#    define INTER int
+#    define RENAME(x) x ## _s16
+#endif
 
-static void RENAME(sum2)(SAMPLE *out, const SAMPLE *in1, const SAMPLE *in2, COEFF *coeffp, int index1, int index2, int len){
+typedef void (RENAME(mix_any_func_type))(SAMPLE **out, const SAMPLE **in1, COEFF *coeffp, integer len);
+
+static void RENAME(sum2)(SAMPLE *out, const SAMPLE *in1, const SAMPLE *in2, COEFF *coeffp, integer index1, integer index2, integer len){
     int i;
     COEFF coeff1 = coeffp[index1];
     COEFF coeff2 = coeffp[index2];
@@ -29,14 +52,14 @@
         out[i] = R(coeff1*in1[i] + coeff2*in2[i]);
 }
 
-static void RENAME(copy)(SAMPLE *out, const SAMPLE *in, COEFF *coeffp, int index, int len){
+static void RENAME(copy)(SAMPLE *out, const SAMPLE *in, COEFF *coeffp, integer index, integer len){
     int i;
     COEFF coeff = coeffp[index];
     for(i=0; i<len; i++)
         out[i] = R(coeff*in[i]);
 }
 
-static void RENAME(mix6to2)(SAMPLE **out, const SAMPLE **in, COEFF *coeffp, int len){
+static void RENAME(mix6to2)(SAMPLE **out, const SAMPLE **in, COEFF *coeffp, integer len){
     int i;
 
     for(i=0; i<len; i++) {
@@ -46,7 +69,7 @@
     }
 }
 
-static void RENAME(mix8to2)(SAMPLE **out, const SAMPLE **in, COEFF *coeffp, int len){
+static void RENAME(mix8to2)(SAMPLE **out, const SAMPLE **in, COEFF *coeffp, integer len){
     int i;
 
     for(i=0; i<len; i++) {
@@ -72,3 +95,10 @@
 
     return NULL;
 }
+
+#undef ONE
+#undef R
+#undef SAMPLE
+#undef COEFF
+#undef INTER
+#undef RENAME
diff --git a/libswresample/resample.c b/libswresample/resample.c
index 5a82e73..2096e43 100644
--- a/libswresample/resample.c
+++ b/libswresample/resample.c
@@ -224,7 +224,7 @@
             break;
         default:
             av_log(NULL, AV_LOG_ERROR, "Unsupported sample format\n");
-            return NULL;
+            av_assert0(0);
         }
 
         c->phase_shift   = phase_shift;
@@ -289,132 +289,37 @@
     return 0;
 }
 
-#define RENAME(N) N ## _int16
-#define FILTER_SHIFT 15
-#define DELEM  int16_t
-#define FELEM  int16_t
-#define FELEM2 int32_t
-#define FELEML int64_t
-#define FELEM_MAX INT16_MAX
-#define FELEM_MIN INT16_MIN
-#define OUT(d, v) v = (v + (1<<(FILTER_SHIFT-1)))>>FILTER_SHIFT;\
-                  d = (unsigned)(v + 32768) > 65535 ? (v>>31) ^ 32767 : v
+#define TEMPLATE_RESAMPLE_S16
 #include "resample_template.c"
+#undef TEMPLATE_RESAMPLE_S16
 
-#undef RENAME
-#undef FELEM
-#undef FELEM2
-#undef DELEM
-#undef FELEML
-#undef OUT
-#undef FELEM_MIN
-#undef FELEM_MAX
-#undef FILTER_SHIFT
-
-
-#define RENAME(N) N ## _int32
-#define FILTER_SHIFT 30
-#define DELEM  int32_t
-#define FELEM  int32_t
-#define FELEM2 int64_t
-#define FELEML int64_t
-#define FELEM_MAX INT32_MAX
-#define FELEM_MIN INT32_MIN
-#define OUT(d, v) v = (v + (1<<(FILTER_SHIFT-1)))>>FILTER_SHIFT;\
-                  d = (uint64_t)(v + 0x80000000) > 0xFFFFFFFF ? (v>>63) ^ 0x7FFFFFFF : v
+#define TEMPLATE_RESAMPLE_S32
 #include "resample_template.c"
+#undef TEMPLATE_RESAMPLE_S32
 
-#undef RENAME
-#undef FELEM
-#undef FELEM2
-#undef DELEM
-#undef FELEML
-#undef OUT
-#undef FELEM_MIN
-#undef FELEM_MAX
-#undef FILTER_SHIFT
-
-
-#define RENAME(N) N ## _float
-#define FILTER_SHIFT 0
-#define DELEM  float
-#define FELEM  float
-#define FELEM2 float
-#define FELEML float
-#define OUT(d, v) d = v
+#define TEMPLATE_RESAMPLE_FLT
 #include "resample_template.c"
+#undef TEMPLATE_RESAMPLE_FLT
 
-#undef RENAME
-#undef FELEM
-#undef FELEM2
-#undef DELEM
-#undef FELEML
-#undef OUT
-#undef FELEM_MIN
-#undef FELEM_MAX
-#undef FILTER_SHIFT
-
-
-#define RENAME(N) N ## _double
-#define FILTER_SHIFT 0
-#define DELEM  double
-#define FELEM  double
-#define FELEM2 double
-#define FELEML double
-#define OUT(d, v) d = v
+#define TEMPLATE_RESAMPLE_DBL
 #include "resample_template.c"
-
-#undef RENAME
-#undef FELEM
-#undef FELEM2
-#undef DELEM
-#undef FELEML
-#undef OUT
-#undef FELEM_MIN
-#undef FELEM_MAX
-#undef FILTER_SHIFT
+#undef TEMPLATE_RESAMPLE_DBL
 
 // XXX FIXME the whole C loop should be written in asm so this x86 specific code here isnt needed
 #if HAVE_MMXEXT_INLINE
-#include "x86/resample_mmx.h"
-#define COMMON_CORE COMMON_CORE_INT16_MMX2
-#define RENAME(N) N ## _int16_mmx2
-#define FILTER_SHIFT 15
-#define DELEM  int16_t
-#define FELEM  int16_t
-#define FELEM2 int32_t
-#define FELEML int64_t
-#define FELEM_MAX INT16_MAX
-#define FELEM_MIN INT16_MIN
-#define OUT(d, v) v = (v + (1<<(FILTER_SHIFT-1)))>>FILTER_SHIFT;\
-                  d = (unsigned)(v + 32768) > 65535 ? (v>>31) ^ 32767 : v
-#include "resample_template.c"
 
-#undef COMMON_CORE
-#undef RENAME
-#undef FELEM
-#undef FELEM2
-#undef DELEM
-#undef FELEML
-#undef OUT
-#undef FELEM_MIN
-#undef FELEM_MAX
-#undef FILTER_SHIFT
+#include "x86/resample_mmx.h"
+
+#define TEMPLATE_RESAMPLE_S16_MMX2
+#include "resample_template.c"
+#undef TEMPLATE_RESAMPLE_S16_MMX2
 
 #if HAVE_SSSE3_INLINE
-#define COMMON_CORE COMMON_CORE_INT16_SSSE3
-#define RENAME(N) N ## _int16_ssse3
-#define FILTER_SHIFT 15
-#define DELEM  int16_t
-#define FELEM  int16_t
-#define FELEM2 int32_t
-#define FELEML int64_t
-#define FELEM_MAX INT16_MAX
-#define FELEM_MIN INT16_MIN
-#define OUT(d, v) v = (v + (1<<(FILTER_SHIFT-1)))>>FILTER_SHIFT;\
-                  d = (unsigned)(v + 32768) > 65535 ? (v>>31) ^ 32767 : v
+#define TEMPLATE_RESAMPLE_S16_SSSE3
 #include "resample_template.c"
+#undef TEMPLATE_RESAMPLE_S16_SSSE3
 #endif
+
 #endif // HAVE_MMXEXT_INLINE
 
 int swri_multiple_resample(ResampleContext *c, AudioData *dst, int dst_size, AudioData *src, int src_size, int *consumed){
diff --git a/libswresample/resample_template.c b/libswresample/resample_template.c
index ad84070..855296f 100644
--- a/libswresample/resample_template.c
+++ b/libswresample/resample_template.c
@@ -25,6 +25,62 @@
  * @author Michael Niedermayer <michaelni@gmx.at>
  */
 
+#if defined(TEMPLATE_RESAMPLE_DBL)
+#    define RENAME(N) N ## _double
+#    define FILTER_SHIFT 0
+#    define DELEM  double
+#    define FELEM  double
+#    define FELEM2 double
+#    define FELEML double
+#    define OUT(d, v) d = v
+
+#elif defined(TEMPLATE_RESAMPLE_FLT)
+#    define RENAME(N) N ## _float
+#    define FILTER_SHIFT 0
+#    define DELEM  float
+#    define FELEM  float
+#    define FELEM2 float
+#    define FELEML float
+#    define OUT(d, v) d = v
+
+#elif defined(TEMPLATE_RESAMPLE_S32)
+#    define RENAME(N) N ## _int32
+#    define FILTER_SHIFT 30
+#    define DELEM  int32_t
+#    define FELEM  int32_t
+#    define FELEM2 int64_t
+#    define FELEML int64_t
+#    define FELEM_MAX INT32_MAX
+#    define FELEM_MIN INT32_MIN
+#    define OUT(d, v) v = (v + (1<<(FILTER_SHIFT-1)))>>FILTER_SHIFT;\
+                      d = (uint64_t)(v + 0x80000000) > 0xFFFFFFFF ? (v>>63) ^ 0x7FFFFFFF : v
+
+#elif    defined(TEMPLATE_RESAMPLE_S16)      \
+      || defined(TEMPLATE_RESAMPLE_S16_MMX2) \
+      || defined(TEMPLATE_RESAMPLE_S16_SSSE3)
+
+#    define FILTER_SHIFT 15
+#    define DELEM  int16_t
+#    define FELEM  int16_t
+#    define FELEM2 int32_t
+#    define FELEML int64_t
+#    define FELEM_MAX INT16_MAX
+#    define FELEM_MIN INT16_MIN
+#    define OUT(d, v) v = (v + (1<<(FILTER_SHIFT-1)))>>FILTER_SHIFT;\
+                      d = (unsigned)(v + 32768) > 65535 ? (v>>31) ^ 32767 : v
+
+#    if defined(TEMPLATE_RESAMPLE_S16)
+#        define RENAME(N) N ## _int16
+#    elif defined(TEMPLATE_RESAMPLE_S16_MMX2)
+#        define COMMON_CORE COMMON_CORE_INT16_MMX2
+#        define RENAME(N) N ## _int16_mmx2
+#    elif defined(TEMPLATE_RESAMPLE_S16_SSSE3)
+#        define COMMON_CORE COMMON_CORE_INT16_SSSE3
+#        define RENAME(N) N ## _int16_ssse3
+#    endif
+
+#endif
+
 int RENAME(swri_resample)(ResampleContext *c, DELEM *dst, const DELEM *src, int *consumed, int src_size, int dst_size, int update_ctx){
     int dst_index, i;
     int index= c->index;
@@ -48,10 +104,16 @@
         index += dst_index * dst_incr;
         index += (frac + dst_index * (int64_t)dst_incr_frac) / c->src_incr;
         frac   = (frac + dst_index * (int64_t)dst_incr_frac) % c->src_incr;
+        av_assert2(index >= 0);
+        *consumed= index >> c->phase_shift;
+        index &= c->phase_mask;
     }else if(compensation_distance == 0 && !c->linear && index >= 0){
+        int sample_index = 0;
         for(dst_index=0; dst_index < dst_size; dst_index++){
-            FELEM *filter= ((FELEM*)c->filter_bank) + c->filter_alloc*(index & c->phase_mask);
-            int sample_index= index >> c->phase_shift;
+            FELEM *filter;
+            sample_index += index >> c->phase_shift;
+            index &= c->phase_mask;
+            filter= ((FELEM*)c->filter_bank) + c->filter_alloc*index;
 
             if(sample_index + c->filter_length > src_size){
                 break;
@@ -74,12 +136,17 @@
                 index++;
             }
         }
+        *consumed = sample_index;
     }else{
+        int sample_index = 0;
         for(dst_index=0; dst_index < dst_size; dst_index++){
-            FELEM *filter= ((FELEM*)c->filter_bank) + c->filter_alloc*(index & c->phase_mask);
-            int sample_index= index >> c->phase_shift;
+            FELEM *filter;
             FELEM2 val=0;
 
+            sample_index += index >> c->phase_shift;
+            index &= c->phase_mask;
+            filter = ((FELEM*)c->filter_bank) + c->filter_alloc*index;
+
             if(sample_index + c->filter_length > src_size || -sample_index >= src_size){
                 break;
             }else if(sample_index < 0){
@@ -113,14 +180,15 @@
                 dst_incr=      c->ideal_dst_incr / c->src_incr;
             }
         }
-    }
-    *consumed= FFMAX(index, 0) >> c->phase_shift;
-    if(index>=0) index &= c->phase_mask;
+        *consumed= FFMAX(sample_index, 0);
+        index += FFMIN(sample_index, 0) << c->phase_shift;
 
-    if(compensation_distance){
-        compensation_distance -= dst_index;
-        av_assert1(compensation_distance > 0);
+        if(compensation_distance){
+            compensation_distance -= dst_index;
+            av_assert1(compensation_distance > 0);
+        }
     }
+
     if(update_ctx){
         c->frac= frac;
         c->index= index;
@@ -137,3 +205,14 @@
 
     return dst_index;
 }
+
+#undef COMMON_CORE
+#undef RENAME
+#undef FILTER_SHIFT
+#undef DELEM
+#undef FELEM
+#undef FELEM2
+#undef FELEML
+#undef FELEM_MAX
+#undef FELEM_MIN
+#undef OUT
diff --git a/libswresample/swresample-test.c b/libswresample/swresample-test.c
index 03dab7f..7f50cb4 100644
--- a/libswresample/swresample-test.c
+++ b/libswresample/swresample-test.c
@@ -20,8 +20,8 @@
  */
 
 #include "libavutil/avassert.h"
+#include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
-#include "libavutil/audioconvert.h"
 #include "libavutil/opt.h"
 #include "swresample.h"
 
@@ -231,11 +231,11 @@
     uint8_t *amid[SWR_CH_MAX];
     int flush_i=0;
     int mode;
-    int max_tests = FF_ARRAY_ELEMS(rates) * FF_ARRAY_ELEMS(layouts) * FF_ARRAY_ELEMS(formats) * FF_ARRAY_ELEMS(layouts) * FF_ARRAY_ELEMS(formats);
     int num_tests = 10000;
     uint32_t seed = 0;
     uint32_t rand_seed = 0;
-    int remaining_tests[max_tests];
+    int remaining_tests[FF_ARRAY_ELEMS(rates) * FF_ARRAY_ELEMS(layouts) * FF_ARRAY_ELEMS(formats) * FF_ARRAY_ELEMS(layouts) * FF_ARRAY_ELEMS(formats)];
+    int max_tests = FF_ARRAY_ELEMS(remaining_tests);
     int test;
     int specific_test= -1;
 
@@ -304,14 +304,18 @@
         backw_ctx = swr_alloc_set_opts(backw_ctx, in_ch_layout,  in_sample_fmt,             in_sample_rate,
                                                     out_ch_layout, out_sample_fmt, out_sample_rate,
                                         0, 0);
+        if(!forw_ctx) {
+            fprintf(stderr, "Failed to init forw_cts\n");
+            return 1;
+        }
+        if(!backw_ctx) {
+            fprintf(stderr, "Failed to init backw_ctx\n");
+            return 1;
+        }
         if(swr_init( forw_ctx) < 0)
             fprintf(stderr, "swr_init(->) failed\n");
         if(swr_init(backw_ctx) < 0)
             fprintf(stderr, "swr_init(<-) failed\n");
-        if(!forw_ctx)
-            fprintf(stderr, "Failed to init forw_cts\n");
-        if(!backw_ctx)
-            fprintf(stderr, "Failed to init backw_ctx\n");
                 //FIXME test planar
         setup_array(ain , array_in ,  in_sample_fmt,   SAMPLES);
         setup_array(amid, array_mid, out_sample_fmt, 3*SAMPLES);
@@ -368,7 +372,7 @@
             sse= sum_aa + sum_bb - 2*sum_ab;
             if(sse < 0 && sse > -0.00001) sse=0; //fix rounding error
 
-            fprintf(stderr, "[e:%f c:%f max:%f] len:%5d\n", sqrt(sse/out_count), sum_ab/(sqrt(sum_aa*sum_bb)), maxdiff, out_count);
+            fprintf(stderr, "[e:%f c:%f max:%f] len:%5d\n", out_count ? sqrt(sse/out_count) : 0, sum_ab/(sqrt(sum_aa*sum_bb)), maxdiff, out_count);
         }
 
         flush_i++;
diff --git a/libswresample/swresample.c b/libswresample/swresample.c
index 5d02aaf..c1668da 100644
--- a/libswresample/swresample.c
+++ b/libswresample/swresample.c
@@ -22,7 +22,7 @@
 #include "swresample_internal.h"
 #include "audioconvert.h"
 #include "libavutil/avassert.h"
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
 
 #include <float.h>
 
@@ -41,62 +41,69 @@
 #define PARAM AV_OPT_FLAG_AUDIO_PARAM
 
 static const AVOption options[]={
-{"ich"                  ,  "Input Channel Count"        , OFFSET( in.ch_count   ), AV_OPT_TYPE_INT  , {.i64=2                     }, 0      , SWR_CH_MAX, PARAM},
-{"in_channel_count"     ,  "Input Channel Count"        , OFFSET( in.ch_count   ), AV_OPT_TYPE_INT  , {.i64=2                     }, 0      , SWR_CH_MAX, PARAM},
-{"och"                  , "Output Channel Count"        , OFFSET(out.ch_count   ), AV_OPT_TYPE_INT  , {.i64=2                     }, 0      , SWR_CH_MAX, PARAM},
-{"out_channel_count"    , "Output Channel Count"        , OFFSET(out.ch_count   ), AV_OPT_TYPE_INT  , {.i64=2                     }, 0      , SWR_CH_MAX, PARAM},
-{"uch"                  ,   "Used Channel Count"        , OFFSET(used_ch_count  ), AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , SWR_CH_MAX, PARAM},
-{"used_channel_count"   ,   "Used Channel Count"        , OFFSET(used_ch_count  ), AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , SWR_CH_MAX, PARAM},
-{"isr"                  ,  "Input Sample Rate"          , OFFSET( in_sample_rate), AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , INT_MAX   , PARAM},
-{"in_sample_rate"       ,  "Input Sample Rate"          , OFFSET( in_sample_rate), AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , INT_MAX   , PARAM},
-{"osr"                  , "Output Sample Rate"          , OFFSET(out_sample_rate), AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , INT_MAX   , PARAM},
-{"out_sample_rate"      , "Output Sample Rate"          , OFFSET(out_sample_rate), AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , INT_MAX   , PARAM},
-{"isf"                  ,    "Input Sample Format"      , OFFSET( in_sample_fmt ), AV_OPT_TYPE_INT  , {.i64=AV_SAMPLE_FMT_NONE    }, -1     , AV_SAMPLE_FMT_NB-1+256, PARAM},
-{"in_sample_fmt"        ,    "Input Sample Format"      , OFFSET( in_sample_fmt ), AV_OPT_TYPE_INT  , {.i64=AV_SAMPLE_FMT_NONE    }, -1     , AV_SAMPLE_FMT_NB-1+256, PARAM},
-{"osf"                  ,   "Output Sample Format"      , OFFSET(out_sample_fmt ), AV_OPT_TYPE_INT  , {.i64=AV_SAMPLE_FMT_NONE    }, -1     , AV_SAMPLE_FMT_NB-1+256, PARAM},
-{"out_sample_fmt"       ,   "Output Sample Format"      , OFFSET(out_sample_fmt ), AV_OPT_TYPE_INT  , {.i64=AV_SAMPLE_FMT_NONE    }, -1     , AV_SAMPLE_FMT_NB-1+256, PARAM},
-{"tsf"                  , "Internal Sample Format"      , OFFSET(int_sample_fmt ), AV_OPT_TYPE_INT  , {.i64=AV_SAMPLE_FMT_NONE    }, -1     , AV_SAMPLE_FMT_FLTP, PARAM},
-{"internal_sample_fmt"  , "Internal Sample Format"      , OFFSET(int_sample_fmt ), AV_OPT_TYPE_INT  , {.i64=AV_SAMPLE_FMT_NONE    }, -1     , AV_SAMPLE_FMT_FLTP, PARAM},
-{"icl"                  ,   "Input Channel Layout"      , OFFSET( in_ch_layout  ), AV_OPT_TYPE_INT64, {.i64=0                     }, 0      , INT64_MAX , PARAM, "channel_layout"},
-{"in_channel_layout"    ,   "Input Channel Layout"      , OFFSET( in_ch_layout  ), AV_OPT_TYPE_INT64, {.i64=0                     }, 0      , INT64_MAX , PARAM, "channel_layout"},
-{"ocl"                  ,  "Output Channel Layout"      , OFFSET(out_ch_layout  ), AV_OPT_TYPE_INT64, {.i64=0                     }, 0      , INT64_MAX , PARAM, "channel_layout"},
-{"out_channel_layout"   ,  "Output Channel Layout"      , OFFSET(out_ch_layout  ), AV_OPT_TYPE_INT64, {.i64=0                     }, 0      , INT64_MAX , PARAM, "channel_layout"},
-{"clev"                 ,    "Center Mix Level"         , OFFSET(clev           ), AV_OPT_TYPE_FLOAT, {.dbl=C_30DB                }, -32    , 32        , PARAM},
-{"center_mix_level"     ,    "Center Mix Level"         , OFFSET(clev           ), AV_OPT_TYPE_FLOAT, {.dbl=C_30DB                }, -32    , 32        , PARAM},
-{"slev"                 , "Sourround Mix Level"         , OFFSET(slev           ), AV_OPT_TYPE_FLOAT, {.dbl=C_30DB                }, -32    , 32        , PARAM},
-{"surround_mix_level"   , "Sourround Mix Level"         , OFFSET(slev           ), AV_OPT_TYPE_FLOAT, {.dbl=C_30DB                }, -32    , 32        , PARAM},
-{"lfe_mix_level"        , "LFE Mix Level"               , OFFSET(lfe_mix_level  ), AV_OPT_TYPE_FLOAT, {.dbl=0                     }, -32    , 32        , PARAM},
-{"rmvol"                , "Rematrix Volume"             , OFFSET(rematrix_volume), AV_OPT_TYPE_FLOAT, {.dbl=1.0                   }, -1000  , 1000      , PARAM},
-{"rematrix_volume"      , "Rematrix Volume"             , OFFSET(rematrix_volume), AV_OPT_TYPE_FLOAT, {.dbl=1.0                   }, -1000  , 1000      , PARAM},
-{"flags"                , NULL                          , OFFSET(flags          ), AV_OPT_TYPE_FLAGS, {.i64=0                     }, 0      , UINT_MAX  , PARAM, "flags"},
-{"swr_flags"            , NULL                          , OFFSET(flags          ), AV_OPT_TYPE_FLAGS, {.i64=0                     }, 0      , UINT_MAX  , PARAM, "flags"},
-{"res"                  , "Force Resampling"            , 0                      , AV_OPT_TYPE_CONST, {.i64=SWR_FLAG_RESAMPLE     }, INT_MIN, INT_MAX   , PARAM, "flags"},
-{"dither_scale"         , "Dither Scale"                , OFFSET(dither_scale   ), AV_OPT_TYPE_FLOAT, {.dbl=1                     }, 0      , INT_MAX   , PARAM},
-{"dither_method"        , "Dither Method"               , OFFSET(dither_method  ), AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , SWR_DITHER_NB-1, PARAM, "dither_method"},
-{"rectangular"          , "Rectangular Dither"          , 0                      , AV_OPT_TYPE_CONST, {.i64=SWR_DITHER_RECTANGULAR}, INT_MIN, INT_MAX   , PARAM, "dither_method"},
-{"triangular"           ,  "Triangular Dither"          , 0                      , AV_OPT_TYPE_CONST, {.i64=SWR_DITHER_TRIANGULAR }, INT_MIN, INT_MAX   , PARAM, "dither_method"},
-{"triangular_hp"        , "Triangular Dither With High Pass" , 0                 , AV_OPT_TYPE_CONST, {.i64=SWR_DITHER_TRIANGULAR_HIGHPASS }, INT_MIN, INT_MAX, PARAM, "dither_method"},
-{"filter_size"          , "Resampling Filter Size"      , OFFSET(filter_size)    , AV_OPT_TYPE_INT  , {.i64=16                    }, 0      , INT_MAX   , PARAM },
-{"phase_shift"          , "Resampling Phase Shift"      , OFFSET(phase_shift)    , AV_OPT_TYPE_INT  , {.i64=10                    }, 0      , 30        , PARAM },
-{"linear_interp"        , "Use Linear Interpolation"    , OFFSET(linear_interp)  , AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , 1         , PARAM },
-{"cutoff"               , "Cutoff Frequency Ratio"      , OFFSET(cutoff)         , AV_OPT_TYPE_DOUBLE,{.dbl=0.8                   }, 0      , 1         , PARAM },
-{"min_comp"             , "Minimum difference between timestamps and audio data (in seconds) below which no timestamp compensation of either kind is applied"
+{"ich"                  , "set input channel count"     , OFFSET( in.ch_count   ), AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , SWR_CH_MAX, PARAM},
+{"in_channel_count"     , "set input channel count"     , OFFSET( in.ch_count   ), AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , SWR_CH_MAX, PARAM},
+{"och"                  , "set output channel count"    , OFFSET(out.ch_count   ), AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , SWR_CH_MAX, PARAM},
+{"out_channel_count"    , "set output channel count"    , OFFSET(out.ch_count   ), AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , SWR_CH_MAX, PARAM},
+{"uch"                  , "set used channel count"      , OFFSET(used_ch_count  ), AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , SWR_CH_MAX, PARAM},
+{"used_channel_count"   , "set used channel count"      , OFFSET(used_ch_count  ), AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , SWR_CH_MAX, PARAM},
+{"isr"                  , "set input sample rate"       , OFFSET( in_sample_rate), AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , INT_MAX   , PARAM},
+{"in_sample_rate"       , "set input sample rate"       , OFFSET( in_sample_rate), AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , INT_MAX   , PARAM},
+{"osr"                  , "set output sample rate"      , OFFSET(out_sample_rate), AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , INT_MAX   , PARAM},
+{"out_sample_rate"      , "set output sample rate"      , OFFSET(out_sample_rate), AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , INT_MAX   , PARAM},
+{"isf"                  , "set input sample format"     , OFFSET( in_sample_fmt ), AV_OPT_TYPE_SAMPLE_FMT , {.i64=AV_SAMPLE_FMT_NONE}, -1   , AV_SAMPLE_FMT_NB-1, PARAM},
+{"in_sample_fmt"        , "set input sample format"     , OFFSET( in_sample_fmt ), AV_OPT_TYPE_SAMPLE_FMT , {.i64=AV_SAMPLE_FMT_NONE}, -1   , AV_SAMPLE_FMT_NB-1, PARAM},
+{"osf"                  , "set output sample format"    , OFFSET(out_sample_fmt ), AV_OPT_TYPE_SAMPLE_FMT , {.i64=AV_SAMPLE_FMT_NONE}, -1   , AV_SAMPLE_FMT_NB-1, PARAM},
+{"out_sample_fmt"       , "set output sample format"    , OFFSET(out_sample_fmt ), AV_OPT_TYPE_SAMPLE_FMT , {.i64=AV_SAMPLE_FMT_NONE}, -1   , AV_SAMPLE_FMT_NB-1, PARAM},
+{"tsf"                  , "set internal sample format"  , OFFSET(int_sample_fmt ), AV_OPT_TYPE_SAMPLE_FMT , {.i64=AV_SAMPLE_FMT_NONE}, -1   , AV_SAMPLE_FMT_NB-1, PARAM},
+{"internal_sample_fmt"  , "set internal sample format"  , OFFSET(int_sample_fmt ), AV_OPT_TYPE_SAMPLE_FMT , {.i64=AV_SAMPLE_FMT_NONE}, -1   , AV_SAMPLE_FMT_NB-1, PARAM},
+{"icl"                  , "set input channel layout"    , OFFSET( in_ch_layout  ), AV_OPT_TYPE_INT64, {.i64=0                     }, 0      , INT64_MAX , PARAM, "channel_layout"},
+{"in_channel_layout"    , "set input channel layout"    , OFFSET( in_ch_layout  ), AV_OPT_TYPE_INT64, {.i64=0                     }, 0      , INT64_MAX , PARAM, "channel_layout"},
+{"ocl"                  , "set output channel layout"   , OFFSET(out_ch_layout  ), AV_OPT_TYPE_INT64, {.i64=0                     }, 0      , INT64_MAX , PARAM, "channel_layout"},
+{"out_channel_layout"   , "set output channel layout"   , OFFSET(out_ch_layout  ), AV_OPT_TYPE_INT64, {.i64=0                     }, 0      , INT64_MAX , PARAM, "channel_layout"},
+{"clev"                 , "set center mix level"        , OFFSET(clev           ), AV_OPT_TYPE_FLOAT, {.dbl=C_30DB                }, -32    , 32        , PARAM},
+{"center_mix_level"     , "set center mix level"        , OFFSET(clev           ), AV_OPT_TYPE_FLOAT, {.dbl=C_30DB                }, -32    , 32        , PARAM},
+{"slev"                 , "set surround mix level"      , OFFSET(slev           ), AV_OPT_TYPE_FLOAT, {.dbl=C_30DB                }, -32    , 32        , PARAM},
+{"surround_mix_level"   , "set surround mix Level"      , OFFSET(slev           ), AV_OPT_TYPE_FLOAT, {.dbl=C_30DB                }, -32    , 32        , PARAM},
+{"lfe_mix_level"        , "set LFE mix level"           , OFFSET(lfe_mix_level  ), AV_OPT_TYPE_FLOAT, {.dbl=0                     }, -32    , 32        , PARAM},
+{"rmvol"                , "set rematrix volume"         , OFFSET(rematrix_volume), AV_OPT_TYPE_FLOAT, {.dbl=1.0                   }, -1000  , 1000      , PARAM},
+{"rematrix_volume"      , "set rematrix volume"         , OFFSET(rematrix_volume), AV_OPT_TYPE_FLOAT, {.dbl=1.0                   }, -1000  , 1000      , PARAM},
+
+{"flags"                , "set flags"                   , OFFSET(flags          ), AV_OPT_TYPE_FLAGS, {.i64=0                     }, 0      , UINT_MAX  , PARAM, "flags"},
+{"swr_flags"            , "set flags"                   , OFFSET(flags          ), AV_OPT_TYPE_FLAGS, {.i64=0                     }, 0      , UINT_MAX  , PARAM, "flags"},
+{"res"                  , "force resampling"            , 0                      , AV_OPT_TYPE_CONST, {.i64=SWR_FLAG_RESAMPLE     }, INT_MIN, INT_MAX   , PARAM, "flags"},
+
+{"dither_scale"         , "set dither scale"            , OFFSET(dither_scale   ), AV_OPT_TYPE_FLOAT, {.dbl=1                     }, 0      , INT_MAX   , PARAM},
+
+{"dither_method"        , "set dither method"           , OFFSET(dither_method  ), AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , SWR_DITHER_NB-1, PARAM, "dither_method"},
+{"rectangular"          , "select rectangular dither"   , 0                      , AV_OPT_TYPE_CONST, {.i64=SWR_DITHER_RECTANGULAR}, INT_MIN, INT_MAX   , PARAM, "dither_method"},
+{"triangular"           , "select triangular dither"    , 0                      , AV_OPT_TYPE_CONST, {.i64=SWR_DITHER_TRIANGULAR }, INT_MIN, INT_MAX   , PARAM, "dither_method"},
+{"triangular_hp"        , "select triangular dither with high pass" , 0                 , AV_OPT_TYPE_CONST, {.i64=SWR_DITHER_TRIANGULAR_HIGHPASS }, INT_MIN, INT_MAX, PARAM, "dither_method"},
+
+{"filter_size"          , "set resampling filter size"  , OFFSET(filter_size)    , AV_OPT_TYPE_INT  , {.i64=16                    }, 0      , INT_MAX   , PARAM },
+{"phase_shift"          , "set resampling phase shift"  , OFFSET(phase_shift)    , AV_OPT_TYPE_INT  , {.i64=10                    }, 0      , 30        , PARAM },
+{"linear_interp"        , "enable linear interpolation" , OFFSET(linear_interp)  , AV_OPT_TYPE_INT  , {.i64=0                     }, 0      , 1         , PARAM },
+{"cutoff"               , "set cutoff frequency ratio"  , OFFSET(cutoff)         , AV_OPT_TYPE_DOUBLE,{.dbl=0.8                   }, 0      , 1         , PARAM },
+{"min_comp"             , "set minimum difference between timestamps and audio data (in seconds) below which no timestamp compensation of either kind is applied"
                                                         , OFFSET(min_compensation),AV_OPT_TYPE_FLOAT ,{.dbl=FLT_MAX               }, 0      , FLT_MAX   , PARAM },
-{"min_hard_comp"        , "Minimum difference between timestamps and audio data (in seconds) to trigger padding/trimming the data."
-                                                   , OFFSET(min_hard_compensation),AV_OPT_TYPE_FLOAT ,{.dbl=0.1                   }, 0      , INT_MAX   , PARAM },
-{"comp_duration"        , "Duration (in seconds) over which data is stretched/squeezed to make it match the timestamps."
-                                              , OFFSET(soft_compensation_duration),AV_OPT_TYPE_FLOAT ,{.dbl=1                     }, 0      , INT_MAX   , PARAM },
-{"max_soft_comp"        , "Maximum factor by which data is stretched/squeezed to make it match the timestamps."
-                                                   , OFFSET(max_soft_compensation),AV_OPT_TYPE_FLOAT ,{.dbl=0                     }, INT_MIN, INT_MAX   , PARAM },
-{ "matrix_encoding"     , "Matrixed Stereo Encoding"    , OFFSET(matrix_encoding), AV_OPT_TYPE_INT   ,{.i64 = AV_MATRIX_ENCODING_NONE}, AV_MATRIX_ENCODING_NONE,     AV_MATRIX_ENCODING_NB-1, PARAM, "matrix_encoding" },
-    { "none",  "None",               0, AV_OPT_TYPE_CONST, { .i64 = AV_MATRIX_ENCODING_NONE  }, INT_MIN, INT_MAX, PARAM, "matrix_encoding" },
-    { "dolby", "Dolby",              0, AV_OPT_TYPE_CONST, { .i64 = AV_MATRIX_ENCODING_DOLBY }, INT_MIN, INT_MAX, PARAM, "matrix_encoding" },
-    { "dplii", "Dolby Pro Logic II", 0, AV_OPT_TYPE_CONST, { .i64 = AV_MATRIX_ENCODING_DPLII }, INT_MIN, INT_MAX, PARAM, "matrix_encoding" },
-{ "filter_type"         , "Filter Type"                 , OFFSET(filter_type)    , AV_OPT_TYPE_INT  , { .i64 = SWR_FILTER_TYPE_KAISER }, SWR_FILTER_TYPE_CUBIC, SWR_FILTER_TYPE_KAISER, PARAM, "filter_type" },
-    { "cubic"           , "Cubic"                       , 0                      , AV_OPT_TYPE_CONST, { .i64 = SWR_FILTER_TYPE_CUBIC            }, INT_MIN, INT_MAX, PARAM, "filter_type" },
-    { "blackman_nuttall", "Blackman Nuttall Windowed Sinc", 0                    , AV_OPT_TYPE_CONST, { .i64 = SWR_FILTER_TYPE_BLACKMAN_NUTTALL }, INT_MIN, INT_MAX, PARAM, "filter_type" },
-    { "kaiser"          , "Kaiser Windowed Sinc"        , 0                      , AV_OPT_TYPE_CONST, { .i64 = SWR_FILTER_TYPE_KAISER           }, INT_MIN, INT_MAX, PARAM, "filter_type" },
-{ "kaiser_beta"         , "Kaiser Window Beta"          ,OFFSET(kaiser_beta)     , AV_OPT_TYPE_INT  , {.i64=9                     }, 2      , 16        , PARAM },
+{"min_hard_comp"        , "set minimum difference between timestamps and audio data (in seconds) to trigger padding/trimming the data."
+                                                        , OFFSET(min_hard_compensation),AV_OPT_TYPE_FLOAT ,{.dbl=0.1                   }, 0      , INT_MAX   , PARAM },
+{"comp_duration"        , "set duration (in seconds) over which data is stretched/squeezed to make it match the timestamps."
+                                                        , OFFSET(soft_compensation_duration),AV_OPT_TYPE_FLOAT ,{.dbl=1                     }, 0      , INT_MAX   , PARAM },
+{"max_soft_comp"        , "set maximum factor by which data is stretched/squeezed to make it match the timestamps."
+                                                        , OFFSET(max_soft_compensation),AV_OPT_TYPE_FLOAT ,{.dbl=0                     }, INT_MIN, INT_MAX   , PARAM },
+
+{ "matrix_encoding"     , "set matrixed stereo encoding" , OFFSET(matrix_encoding), AV_OPT_TYPE_INT   ,{.i64 = AV_MATRIX_ENCODING_NONE}, AV_MATRIX_ENCODING_NONE,     AV_MATRIX_ENCODING_NB-1, PARAM, "matrix_encoding" },
+    { "none",  "select none",               0, AV_OPT_TYPE_CONST, { .i64 = AV_MATRIX_ENCODING_NONE  }, INT_MIN, INT_MAX, PARAM, "matrix_encoding" },
+    { "dolby", "select Dolby",              0, AV_OPT_TYPE_CONST, { .i64 = AV_MATRIX_ENCODING_DOLBY }, INT_MIN, INT_MAX, PARAM, "matrix_encoding" },
+    { "dplii", "select Dolby Pro Logic II", 0, AV_OPT_TYPE_CONST, { .i64 = AV_MATRIX_ENCODING_DPLII }, INT_MIN, INT_MAX, PARAM, "matrix_encoding" },
+
+{ "filter_type"         , "select filter type"          , OFFSET(filter_type)    , AV_OPT_TYPE_INT  , { .i64 = SWR_FILTER_TYPE_KAISER }, SWR_FILTER_TYPE_CUBIC, SWR_FILTER_TYPE_KAISER, PARAM, "filter_type" },
+    { "cubic"           , "select cubic"                , 0                      , AV_OPT_TYPE_CONST, { .i64 = SWR_FILTER_TYPE_CUBIC            }, INT_MIN, INT_MAX, PARAM, "filter_type" },
+    { "blackman_nuttall", "select Blackman Nuttall Windowed Sinc", 0             , AV_OPT_TYPE_CONST, { .i64 = SWR_FILTER_TYPE_BLACKMAN_NUTTALL }, INT_MIN, INT_MAX, PARAM, "filter_type" },
+    { "kaiser"          , "select Kaiser Windowed Sinc" , 0                      , AV_OPT_TYPE_CONST, { .i64 = SWR_FILTER_TYPE_KAISER           }, INT_MIN, INT_MAX, PARAM, "filter_type" },
+
+{ "kaiser_beta"         , "set Kaiser Window Beta"      , OFFSET(kaiser_beta)    , AV_OPT_TYPE_INT  , {.i64=9                     }, 2      , 16        , PARAM },
 
 {0}
 };
diff --git a/libswresample/swresample.h b/libswresample/swresample.h
index ac43cd2..6dd8a47 100644
--- a/libswresample/swresample.h
+++ b/libswresample/swresample.h
@@ -18,15 +18,81 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#ifndef SWRESAMPLE_SWRESAMPLE_H
+#define SWRESAMPLE_SWRESAMPLE_H
+
 /**
  * @file
  * libswresample public header
  */
 
-#ifndef SWR_H
-#define SWR_H
+/**
+ * @defgroup lswr Libswresample
+ * @{
+ *
+ * Libswresample (lswr) is a library that handles audio resampling, sample
+ * format conversion and mixing.
+ *
+ * Interaction with lswr is done through SwrContext, which is
+ * allocated with swr_alloc() or swr_alloc_set_opts(). It is opaque, so all parameters
+ * must be set with the @ref avoptions API.
+ *
+ * For example the following code will setup conversion from planar float sample
+ * format to interleaved signed 16-bit integer, downsampling from 48kHz to
+ * 44.1kHz and downmixing from 5.1 channels to stereo (using the default mixing
+ * matrix):
+ * @code
+ * SwrContext *swr = swr_alloc();
+ * av_opt_set_int(swr, "in_channel_layout",  AV_CH_LAYOUT_5POINT1, 0);
+ * av_opt_set_int(swr, "out_channel_layout", AV_CH_LAYOUT_STEREO,  0);
+ * av_opt_set_int(swr, "in_sample_rate",     48000,                0);
+ * av_opt_set_int(swr, "out_sample_rate",    44100,                0);
+ * av_opt_set_sample_fmt(swr, "in_sample_fmt", AV_SAMPLE_FMT_FLTP, 0);
+ * av_opt_set_sample_fmt(swr, "out_sample_fmt, AV_SAMPLE_FMT_S16,  0);
+ * @endcode
+ *
+ * Once all values have been set, it must be initialized with swr_init(). If
+ * you need to change the conversion parameters, you can change the parameters
+ * as described above, or by using swr_alloc_set_opts(), then call swr_init()
+ * again.
+ *
+ * The conversion itself is done by repeatedly calling swr_convert().
+ * Note that the samples may get buffered in swr if you provide insufficient
+ * output space or if sample rate conversion is done, which requires "future"
+ * samples. Samples that do not require future input can be retrieved at any
+ * time by using swr_convert() (in_count can be set to 0).
+ * At the end of conversion the resampling buffer can be flushed by calling
+ * swr_convert() with NULL in and 0 in_count.
+ *
+ * The delay between input and output, can at any time be found by using
+ * swr_get_delay().
+ *
+ * The following code demonstrates the conversion loop assuming the parameters
+ * from above and caller-defined functions get_input() and handle_output():
+ * @code
+ * uint8_t **input;
+ * int in_samples;
+ *
+ * while (get_input(&input, &in_samples)) {
+ *     uint8_t *output;
+ *     int out_samples = av_rescale_rnd(swr_get_delay(swr, 48000) +
+ *                                      in_samples, 44100, 48000, AV_ROUND_UP);
+ *     av_samples_alloc(&output, NULL, 2, out_samples,
+ *                      AV_SAMPLE_FMT_S16, 0);
+ *     out_samples = swr_convert(swr, &output, out_samples,
+ *                                      input, in_samples);
+ *     handle_output(output, out_samples);
+ *     av_freep(&output);
+ *  }
+ *  @endcode
+ *
+ * When the conversion is finished, the conversion
+ * context and everything associated with it must be freed with swr_free().
+ * There will be no memory leak if the data is not completely flushed before
+ * swr_free().
+ */
 
-#include <inttypes.h>
+#include <stdint.h>
 #include "libavutil/samplefmt.h"
 
 #include "libswresample/version.h"
@@ -135,7 +201,7 @@
 
 /**
  * Convert the next timestamp from input to output
- * timestampe are in 1/(in_sample_rate * out_sample_rate) units.
+ * timestamps are in 1/(in_sample_rate * out_sample_rate) units.
  *
  * @note There are 2 slightly differently behaving modes.
  *       First is when automatic timestamp compensation is not used, (min_compensation >= FLT_MAX)
@@ -143,8 +209,8 @@
  *       Second is when automatic timestamp compensation is used, (min_compensation < FLT_MAX)
  *              in this case the output timestamps will match output sample numbers
  *
- * @param pts   timstamp for the next input sample, INT64_MIN if unknown
- * @returns the output timestamp for the next output sample
+ * @param pts   timestamp for the next input sample, INT64_MIN if unknown
+ * @return the output timestamp for the next output sample
  */
 int64_t swr_next_pts(struct SwrContext *s, int64_t pts);
 
@@ -190,6 +256,10 @@
  * Swresample can buffer data if more input has been provided than available
  * output space, also converting between sample rates needs a delay.
  * This function returns the sum of all such delays.
+ * The exact delay is not necessarily an integer value in either input or
+ * output sample rate. Especially when downsampling by a large value, the
+ * output sample rate may be a poor choice to represent the delay, similarly
+ * for upsampling and the input sample rate.
  *
  * @param s     swr context
  * @param base  timebase in which the returned delay will be
@@ -217,4 +287,8 @@
  */
 const char *swresample_license(void);
 
-#endif
+/**
+ * @}
+ */
+
+#endif /* SWRESAMPLE_SWRESAMPLE_H */
diff --git a/libswresample/swresample_internal.h b/libswresample/swresample_internal.h
index ab17602..459b1b0 100644
--- a/libswresample/swresample_internal.h
+++ b/libswresample/swresample_internal.h
@@ -22,14 +22,21 @@
 #define SWR_INTERNAL_H
 
 #include "swresample.h"
-#include "libavutil/audioconvert.h"
+#include "libavutil/channel_layout.h"
+#include "config.h"
 
 #define SQRT3_2      1.22474487139158904909  /* sqrt(3/2) */
 
-typedef void (mix_1_1_func_type)(void *out, const void *in, void *coeffp, int index, int len);
-typedef void (mix_2_1_func_type)(void *out, const void *in1, const void *in2, void *coeffp, int index1, int index2, int len);
+#if ARCH_X86_64
+typedef int64_t integer;
+#else
+typedef int integer;
+#endif
 
-typedef void (mix_any_func_type)(uint8_t **out, const uint8_t **in1, void *coeffp, int len);
+typedef void (mix_1_1_func_type)(void *out, const void *in, void *coeffp, integer index, integer len);
+typedef void (mix_2_1_func_type)(void *out, const void *in1, const void *in2, void *coeffp, integer index1, integer index2, integer len);
+
+typedef void (mix_any_func_type)(uint8_t **out, const uint8_t **in1, void *coeffp, integer len);
 
 typedef struct AudioData{
     uint8_t *ch[SWR_CH_MAX];    ///< samples buffer per channel
diff --git a/libswresample/version.h b/libswresample/version.h
index 2c7b932..df9df48 100644
--- a/libswresample/version.h
+++ b/libswresample/version.h
@@ -29,8 +29,8 @@
 #include "libavutil/avutil.h"
 
 #define LIBSWRESAMPLE_VERSION_MAJOR 0
-#define LIBSWRESAMPLE_VERSION_MINOR 16
-#define LIBSWRESAMPLE_VERSION_MICRO 100
+#define LIBSWRESAMPLE_VERSION_MINOR 17
+#define LIBSWRESAMPLE_VERSION_MICRO 102
 
 #define LIBSWRESAMPLE_VERSION_INT  AV_VERSION_INT(LIBSWRESAMPLE_VERSION_MAJOR, \
                                                   LIBSWRESAMPLE_VERSION_MINOR, \
diff --git a/libswresample/x86/audio_convert.asm b/libswresample/x86/audio_convert.asm
index 29701a5..ad46977 100644
--- a/libswresample/x86/audio_convert.asm
+++ b/libswresample/x86/audio_convert.asm
@@ -18,7 +18,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
diff --git a/libswresample/x86/rematrix.asm b/libswresample/x86/rematrix.asm
index d63545f..84448e8 100644
--- a/libswresample/x86/rematrix.asm
+++ b/libswresample/x86/rematrix.asm
@@ -18,7 +18,6 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "libavutil/x86/x86inc.asm"
 %include "libavutil/x86/x86util.asm"
 
 
diff --git a/libswscale/bfin/swscale_bfin.c b/libswscale/bfin/swscale_bfin.c
index a51b2af..2b93858 100644
--- a/libswscale/bfin/swscale_bfin.c
+++ b/libswscale/bfin/swscale_bfin.c
@@ -73,12 +73,12 @@
 
 void ff_bfin_get_unscaled_swscale(SwsContext *c)
 {
-    if (c->dstFormat == PIX_FMT_YUV420P && c->srcFormat == PIX_FMT_UYVY422) {
+    if (c->dstFormat == AV_PIX_FMT_YUV420P && c->srcFormat == AV_PIX_FMT_UYVY422) {
         av_log(NULL, AV_LOG_VERBOSE,
                "selecting Blackfin optimized uyvytoyv12_unscaled\n");
         c->swScale = uyvytoyv12_unscaled;
     }
-    if (c->dstFormat == PIX_FMT_YUV420P && c->srcFormat == PIX_FMT_YUYV422) {
+    if (c->dstFormat == AV_PIX_FMT_YUV420P && c->srcFormat == AV_PIX_FMT_YUYV422) {
         av_log(NULL, AV_LOG_VERBOSE,
                "selecting Blackfin optimized yuyvtoyv12_unscaled\n");
         c->swScale = yuyvtoyv12_unscaled;
diff --git a/libswscale/bfin/yuv2rgb_bfin.c b/libswscale/bfin/yuv2rgb_bfin.c
index dae7f31..e1b7afa 100644
--- a/libswscale/bfin/yuv2rgb_bfin.c
+++ b/libswscale/bfin/yuv2rgb_bfin.c
@@ -173,22 +173,22 @@
     SwsFunc f;
 
     switch (c->dstFormat) {
-    case PIX_FMT_RGB555:
+    case AV_PIX_FMT_RGB555:
         f = bfin_yuv420_rgb555;
         break;
-    case PIX_FMT_BGR555:
+    case AV_PIX_FMT_BGR555:
         f = bfin_yuv420_bgr555;
         break;
-    case PIX_FMT_RGB565:
+    case AV_PIX_FMT_RGB565:
         f = bfin_yuv420_rgb565;
         break;
-    case PIX_FMT_BGR565:
+    case AV_PIX_FMT_BGR565:
         f = bfin_yuv420_bgr565;
         break;
-    case PIX_FMT_RGB24:
+    case AV_PIX_FMT_RGB24:
         f = bfin_yuv420_rgb24;
         break;
-    case PIX_FMT_BGR24:
+    case AV_PIX_FMT_BGR24:
         f = bfin_yuv420_bgr24;
         break;
     default:
diff --git a/libswscale/input.c b/libswscale/input.c
index 9234646..d3aeb22 100644
--- a/libswscale/input.c
+++ b/libswscale/input.c
@@ -49,12 +49,12 @@
 
 #define input_pixel(pos) (isBE(origin) ? AV_RB16(pos) : AV_RL16(pos))
 
-#define r ((origin == PIX_FMT_BGR48BE || origin == PIX_FMT_BGR48LE) ? b_r : r_b)
-#define b ((origin == PIX_FMT_BGR48BE || origin == PIX_FMT_BGR48LE) ? r_b : b_r)
+#define r ((origin == AV_PIX_FMT_BGR48BE || origin == AV_PIX_FMT_BGR48LE) ? b_r : r_b)
+#define b ((origin == AV_PIX_FMT_BGR48BE || origin == AV_PIX_FMT_BGR48LE) ? r_b : b_r)
 
 static av_always_inline void
 rgb64ToY_c_template(uint16_t *dst, const uint16_t *src, int width,
-                    enum PixelFormat origin)
+                    enum AVPixelFormat origin)
 {
     int i;
     for (i = 0; i < width; i++) {
@@ -69,7 +69,7 @@
 static av_always_inline void
 rgb64ToUV_c_template(uint16_t *dstU, uint16_t *dstV,
                     const uint16_t *src1, const uint16_t *src2,
-                    int width, enum PixelFormat origin)
+                    int width, enum AVPixelFormat origin)
 {
     int i;
     av_assert1(src1==src2);
@@ -86,7 +86,7 @@
 static av_always_inline void
 rgb64ToUV_half_c_template(uint16_t *dstU, uint16_t *dstV,
                           const uint16_t *src1, const uint16_t *src2,
-                          int width, enum PixelFormat origin)
+                          int width, enum AVPixelFormat origin)
 {
     int i;
     av_assert1(src1==src2);
@@ -129,12 +129,12 @@
     rgb64ToUV_half_c_template(dstU, dstV, src1, src2, width, origin); \
 }
 
-rgb64funcs(rgb, LE, PIX_FMT_RGBA64LE)
-rgb64funcs(rgb, BE, PIX_FMT_RGBA64BE)
+rgb64funcs(rgb, LE, AV_PIX_FMT_RGBA64LE)
+rgb64funcs(rgb, BE, AV_PIX_FMT_RGBA64BE)
 
 static av_always_inline void rgb48ToY_c_template(uint16_t *dst,
                                                  const uint16_t *src, int width,
-                                                 enum PixelFormat origin)
+                                                 enum AVPixelFormat origin)
 {
     int i;
     for (i = 0; i < width; i++) {
@@ -151,7 +151,7 @@
                                                   const uint16_t *src1,
                                                   const uint16_t *src2,
                                                   int width,
-                                                  enum PixelFormat origin)
+                                                  enum AVPixelFormat origin)
 {
     int i;
     av_assert1(src1 == src2);
@@ -170,7 +170,7 @@
                                                        const uint16_t *src1,
                                                        const uint16_t *src2,
                                                        int width,
-                                                       enum PixelFormat origin)
+                                                       enum AVPixelFormat origin)
 {
     int i;
     av_assert1(src1 == src2);
@@ -233,15 +233,15 @@
     rgb48ToUV_half_c_template(dstU, dstV, src1, src2, width, origin);   \
 }
 
-rgb48funcs(rgb, LE, PIX_FMT_RGB48LE)
-rgb48funcs(rgb, BE, PIX_FMT_RGB48BE)
-rgb48funcs(bgr, LE, PIX_FMT_BGR48LE)
-rgb48funcs(bgr, BE, PIX_FMT_BGR48BE)
+rgb48funcs(rgb, LE, AV_PIX_FMT_RGB48LE)
+rgb48funcs(rgb, BE, AV_PIX_FMT_RGB48BE)
+rgb48funcs(bgr, LE, AV_PIX_FMT_BGR48LE)
+rgb48funcs(bgr, BE, AV_PIX_FMT_BGR48BE)
 
-#define input_pixel(i) ((origin == PIX_FMT_RGBA ||                      \
-                         origin == PIX_FMT_BGRA ||                      \
-                         origin == PIX_FMT_ARGB ||                      \
-                         origin == PIX_FMT_ABGR)                        \
+#define input_pixel(i) ((origin == AV_PIX_FMT_RGBA ||                      \
+                         origin == AV_PIX_FMT_BGRA ||                      \
+                         origin == AV_PIX_FMT_ARGB ||                      \
+                         origin == AV_PIX_FMT_ABGR)                        \
                         ? AV_RN32A(&src[(i) * 4])                       \
                         : (isBE(origin) ? AV_RB16(&src[(i) * 2])        \
                                         : AV_RL16(&src[(i) * 2])))
@@ -249,7 +249,7 @@
 static av_always_inline void rgb16_32ToY_c_template(int16_t *dst,
                                                     const uint8_t *src,
                                                     int width,
-                                                    enum PixelFormat origin,
+                                                    enum AVPixelFormat origin,
                                                     int shr, int shg,
                                                     int shb, int shp,
                                                     int maskr, int maskg,
@@ -274,7 +274,7 @@
                                                      int16_t *dstV,
                                                      const uint8_t *src,
                                                      int width,
-                                                     enum PixelFormat origin,
+                                                     enum AVPixelFormat origin,
                                                      int shr, int shg,
                                                      int shb, int shp,
                                                      int maskr, int maskg,
@@ -301,7 +301,7 @@
                                                           int16_t *dstV,
                                                           const uint8_t *src,
                                                           int width,
-                                                          enum PixelFormat origin,
+                                                          enum AVPixelFormat origin,
                                                           int shr, int shg,
                                                           int shb, int shp,
                                                           int maskr, int maskg,
@@ -325,8 +325,8 @@
 
         b = (rb & maskb) >> shb;
         if (shp ||
-            origin == PIX_FMT_BGR565LE || origin == PIX_FMT_BGR565BE ||
-            origin == PIX_FMT_RGB565LE || origin == PIX_FMT_RGB565BE) {
+            origin == AV_PIX_FMT_BGR565LE || origin == AV_PIX_FMT_BGR565BE ||
+            origin == AV_PIX_FMT_RGB565LE || origin == AV_PIX_FMT_RGB565BE) {
             g >>= shg;
         } else {
             g = (g & maskg) >> shg;
@@ -369,22 +369,22 @@
                                  rsh, gsh, bsh, S);                     \
 }
 
-rgb16_32_wrapper(PIX_FMT_BGR32,    bgr32,  16, 0,  0, 0, 0xFF0000, 0xFF00,   0x00FF,  8, 0,  8, RGB2YUV_SHIFT + 8)
-rgb16_32_wrapper(PIX_FMT_BGR32_1,  bgr321, 16, 0,  0, 8, 0xFF0000, 0xFF00,   0x00FF,  8, 0,  8, RGB2YUV_SHIFT + 8)
-rgb16_32_wrapper(PIX_FMT_RGB32,    rgb32,   0, 0, 16, 0,   0x00FF, 0xFF00, 0xFF0000,  8, 0,  8, RGB2YUV_SHIFT + 8)
-rgb16_32_wrapper(PIX_FMT_RGB32_1,  rgb321,  0, 0, 16, 8,   0x00FF, 0xFF00, 0xFF0000,  8, 0,  8, RGB2YUV_SHIFT + 8)
-rgb16_32_wrapper(PIX_FMT_BGR565LE, bgr16le, 0, 0,  0, 0,   0x001F, 0x07E0,   0xF800, 11, 5,  0, RGB2YUV_SHIFT + 8)
-rgb16_32_wrapper(PIX_FMT_BGR555LE, bgr15le, 0, 0,  0, 0,   0x001F, 0x03E0,   0x7C00, 10, 5,  0, RGB2YUV_SHIFT + 7)
-rgb16_32_wrapper(PIX_FMT_BGR444LE, bgr12le, 0, 0,  0, 0,   0x000F, 0x00F0,   0x0F00,  8, 4,  0, RGB2YUV_SHIFT + 4)
-rgb16_32_wrapper(PIX_FMT_RGB565LE, rgb16le, 0, 0,  0, 0,   0xF800, 0x07E0,   0x001F,  0, 5, 11, RGB2YUV_SHIFT + 8)
-rgb16_32_wrapper(PIX_FMT_RGB555LE, rgb15le, 0, 0,  0, 0,   0x7C00, 0x03E0,   0x001F,  0, 5, 10, RGB2YUV_SHIFT + 7)
-rgb16_32_wrapper(PIX_FMT_RGB444LE, rgb12le, 0, 0,  0, 0,   0x0F00, 0x00F0,   0x000F,  0, 4,  8, RGB2YUV_SHIFT + 4)
-rgb16_32_wrapper(PIX_FMT_BGR565BE, bgr16be, 0, 0,  0, 0,   0x001F, 0x07E0,   0xF800, 11, 5,  0, RGB2YUV_SHIFT + 8)
-rgb16_32_wrapper(PIX_FMT_BGR555BE, bgr15be, 0, 0,  0, 0,   0x001F, 0x03E0,   0x7C00, 10, 5,  0, RGB2YUV_SHIFT + 7)
-rgb16_32_wrapper(PIX_FMT_BGR444BE, bgr12be, 0, 0,  0, 0,   0x000F, 0x00F0,   0x0F00,  8, 4,  0, RGB2YUV_SHIFT + 4)
-rgb16_32_wrapper(PIX_FMT_RGB565BE, rgb16be, 0, 0,  0, 0,   0xF800, 0x07E0,   0x001F,  0, 5, 11, RGB2YUV_SHIFT + 8)
-rgb16_32_wrapper(PIX_FMT_RGB555BE, rgb15be, 0, 0,  0, 0,   0x7C00, 0x03E0,   0x001F,  0, 5, 10, RGB2YUV_SHIFT + 7)
-rgb16_32_wrapper(PIX_FMT_RGB444BE, rgb12be, 0, 0,  0, 0,   0x0F00, 0x00F0,   0x000F,  0, 4,  8, RGB2YUV_SHIFT + 4)
+rgb16_32_wrapper(AV_PIX_FMT_BGR32,    bgr32,  16, 0,  0, 0, 0xFF0000, 0xFF00,   0x00FF,  8, 0,  8, RGB2YUV_SHIFT + 8)
+rgb16_32_wrapper(AV_PIX_FMT_BGR32_1,  bgr321, 16, 0,  0, 8, 0xFF0000, 0xFF00,   0x00FF,  8, 0,  8, RGB2YUV_SHIFT + 8)
+rgb16_32_wrapper(AV_PIX_FMT_RGB32,    rgb32,   0, 0, 16, 0,   0x00FF, 0xFF00, 0xFF0000,  8, 0,  8, RGB2YUV_SHIFT + 8)
+rgb16_32_wrapper(AV_PIX_FMT_RGB32_1,  rgb321,  0, 0, 16, 8,   0x00FF, 0xFF00, 0xFF0000,  8, 0,  8, RGB2YUV_SHIFT + 8)
+rgb16_32_wrapper(AV_PIX_FMT_BGR565LE, bgr16le, 0, 0,  0, 0,   0x001F, 0x07E0,   0xF800, 11, 5,  0, RGB2YUV_SHIFT + 8)
+rgb16_32_wrapper(AV_PIX_FMT_BGR555LE, bgr15le, 0, 0,  0, 0,   0x001F, 0x03E0,   0x7C00, 10, 5,  0, RGB2YUV_SHIFT + 7)
+rgb16_32_wrapper(AV_PIX_FMT_BGR444LE, bgr12le, 0, 0,  0, 0,   0x000F, 0x00F0,   0x0F00,  8, 4,  0, RGB2YUV_SHIFT + 4)
+rgb16_32_wrapper(AV_PIX_FMT_RGB565LE, rgb16le, 0, 0,  0, 0,   0xF800, 0x07E0,   0x001F,  0, 5, 11, RGB2YUV_SHIFT + 8)
+rgb16_32_wrapper(AV_PIX_FMT_RGB555LE, rgb15le, 0, 0,  0, 0,   0x7C00, 0x03E0,   0x001F,  0, 5, 10, RGB2YUV_SHIFT + 7)
+rgb16_32_wrapper(AV_PIX_FMT_RGB444LE, rgb12le, 0, 0,  0, 0,   0x0F00, 0x00F0,   0x000F,  0, 4,  8, RGB2YUV_SHIFT + 4)
+rgb16_32_wrapper(AV_PIX_FMT_BGR565BE, bgr16be, 0, 0,  0, 0,   0x001F, 0x07E0,   0xF800, 11, 5,  0, RGB2YUV_SHIFT + 8)
+rgb16_32_wrapper(AV_PIX_FMT_BGR555BE, bgr15be, 0, 0,  0, 0,   0x001F, 0x03E0,   0x7C00, 10, 5,  0, RGB2YUV_SHIFT + 7)
+rgb16_32_wrapper(AV_PIX_FMT_BGR444BE, bgr12be, 0, 0,  0, 0,   0x000F, 0x00F0,   0x0F00,  8, 4,  0, RGB2YUV_SHIFT + 4)
+rgb16_32_wrapper(AV_PIX_FMT_RGB565BE, rgb16be, 0, 0,  0, 0,   0xF800, 0x07E0,   0x001F,  0, 5, 11, RGB2YUV_SHIFT + 8)
+rgb16_32_wrapper(AV_PIX_FMT_RGB555BE, rgb15be, 0, 0,  0, 0,   0x7C00, 0x03E0,   0x001F,  0, 5, 10, RGB2YUV_SHIFT + 7)
+rgb16_32_wrapper(AV_PIX_FMT_RGB444BE, rgb12be, 0, 0,  0, 0,   0x0F00, 0x00F0,   0x000F,  0, 4,  8, RGB2YUV_SHIFT + 4)
 
 static void gbr24pToUV_half_c(uint8_t *_dstU, uint8_t *_dstV,
                          const uint8_t *gsrc, const uint8_t *bsrc, const uint8_t *rsrc,
@@ -864,250 +864,270 @@
 
 av_cold void ff_sws_init_input_funcs(SwsContext *c)
 {
-    enum PixelFormat srcFormat = c->srcFormat;
+    enum AVPixelFormat srcFormat = c->srcFormat;
 
     c->chrToYV12 = NULL;
     switch (srcFormat) {
-    case PIX_FMT_YUYV422:
+    case AV_PIX_FMT_YUYV422:
         c->chrToYV12 = yuy2ToUV_c;
         break;
-    case PIX_FMT_UYVY422:
+    case AV_PIX_FMT_UYVY422:
         c->chrToYV12 = uyvyToUV_c;
         break;
-    case PIX_FMT_NV12:
+    case AV_PIX_FMT_NV12:
         c->chrToYV12 = nv12ToUV_c;
         break;
-    case PIX_FMT_NV21:
+    case AV_PIX_FMT_NV21:
         c->chrToYV12 = nv21ToUV_c;
         break;
-    case PIX_FMT_RGB8:
-    case PIX_FMT_BGR8:
-    case PIX_FMT_PAL8:
-    case PIX_FMT_BGR4_BYTE:
-    case PIX_FMT_RGB4_BYTE:
+    case AV_PIX_FMT_RGB8:
+    case AV_PIX_FMT_BGR8:
+    case AV_PIX_FMT_PAL8:
+    case AV_PIX_FMT_BGR4_BYTE:
+    case AV_PIX_FMT_RGB4_BYTE:
         c->chrToYV12 = palToUV_c;
         break;
-    case PIX_FMT_GBRP9LE:
+    case AV_PIX_FMT_GBRP9LE:
         c->readChrPlanar = planar_rgb9le_to_uv;
         break;
-    case PIX_FMT_GBRP10LE:
+    case AV_PIX_FMT_GBRP10LE:
         c->readChrPlanar = planar_rgb10le_to_uv;
         break;
-    case PIX_FMT_GBRP12LE:
+    case AV_PIX_FMT_GBRP12LE:
         c->readChrPlanar = planar_rgb12le_to_uv;
         break;
-    case PIX_FMT_GBRP14LE:
+    case AV_PIX_FMT_GBRP14LE:
         c->readChrPlanar = planar_rgb14le_to_uv;
         break;
-    case PIX_FMT_GBRP16LE:
+    case AV_PIX_FMT_GBRP16LE:
         c->readChrPlanar = planar_rgb16le_to_uv;
         break;
-    case PIX_FMT_GBRP9BE:
+    case AV_PIX_FMT_GBRP9BE:
         c->readChrPlanar = planar_rgb9be_to_uv;
         break;
-    case PIX_FMT_GBRP10BE:
+    case AV_PIX_FMT_GBRP10BE:
         c->readChrPlanar = planar_rgb10be_to_uv;
         break;
-    case PIX_FMT_GBRP12BE:
+    case AV_PIX_FMT_GBRP12BE:
         c->readChrPlanar = planar_rgb12be_to_uv;
         break;
-    case PIX_FMT_GBRP14BE:
+    case AV_PIX_FMT_GBRP14BE:
         c->readChrPlanar = planar_rgb14be_to_uv;
         break;
-    case PIX_FMT_GBRP16BE:
+    case AV_PIX_FMT_GBRP16BE:
         c->readChrPlanar = planar_rgb16be_to_uv;
         break;
-    case PIX_FMT_GBRP:
+    case AV_PIX_FMT_GBRP:
         c->readChrPlanar = planar_rgb_to_uv;
         break;
 #if HAVE_BIGENDIAN
-    case PIX_FMT_YUV444P9LE:
-    case PIX_FMT_YUV422P9LE:
-    case PIX_FMT_YUV420P9LE:
-    case PIX_FMT_YUV422P10LE:
-    case PIX_FMT_YUV444P10LE:
-    case PIX_FMT_YUV420P10LE:
-    case PIX_FMT_YUV422P12LE:
-    case PIX_FMT_YUV444P12LE:
-    case PIX_FMT_YUV420P12LE:
-    case PIX_FMT_YUV422P14LE:
-    case PIX_FMT_YUV444P14LE:
-    case PIX_FMT_YUV420P14LE:
-    case PIX_FMT_YUV420P16LE:
-    case PIX_FMT_YUV422P16LE:
-    case PIX_FMT_YUV444P16LE:
+    case AV_PIX_FMT_YUV444P9LE:
+    case AV_PIX_FMT_YUV422P9LE:
+    case AV_PIX_FMT_YUV420P9LE:
+    case AV_PIX_FMT_YUV422P10LE:
+    case AV_PIX_FMT_YUV444P10LE:
+    case AV_PIX_FMT_YUV420P10LE:
+    case AV_PIX_FMT_YUV422P12LE:
+    case AV_PIX_FMT_YUV444P12LE:
+    case AV_PIX_FMT_YUV420P12LE:
+    case AV_PIX_FMT_YUV422P14LE:
+    case AV_PIX_FMT_YUV444P14LE:
+    case AV_PIX_FMT_YUV420P14LE:
+    case AV_PIX_FMT_YUV420P16LE:
+    case AV_PIX_FMT_YUV422P16LE:
+    case AV_PIX_FMT_YUV444P16LE:
+
+    case AV_PIX_FMT_YUVA444P9LE:
+    case AV_PIX_FMT_YUVA422P9LE:
+    case AV_PIX_FMT_YUVA420P9LE:
+    case AV_PIX_FMT_YUVA444P10LE:
+    case AV_PIX_FMT_YUVA422P10LE:
+    case AV_PIX_FMT_YUVA420P10LE:
+    case AV_PIX_FMT_YUVA420P16LE:
+    case AV_PIX_FMT_YUVA422P16LE:
+    case AV_PIX_FMT_YUVA444P16LE:
         c->chrToYV12 = bswap16UV_c;
         break;
 #else
-    case PIX_FMT_YUV444P9BE:
-    case PIX_FMT_YUV422P9BE:
-    case PIX_FMT_YUV420P9BE:
-    case PIX_FMT_YUV444P10BE:
-    case PIX_FMT_YUV422P10BE:
-    case PIX_FMT_YUV420P10BE:
-    case PIX_FMT_YUV444P12BE:
-    case PIX_FMT_YUV422P12BE:
-    case PIX_FMT_YUV420P12BE:
-    case PIX_FMT_YUV444P14BE:
-    case PIX_FMT_YUV422P14BE:
-    case PIX_FMT_YUV420P14BE:
-    case PIX_FMT_YUV420P16BE:
-    case PIX_FMT_YUV422P16BE:
-    case PIX_FMT_YUV444P16BE:
+    case AV_PIX_FMT_YUV444P9BE:
+    case AV_PIX_FMT_YUV422P9BE:
+    case AV_PIX_FMT_YUV420P9BE:
+    case AV_PIX_FMT_YUV444P10BE:
+    case AV_PIX_FMT_YUV422P10BE:
+    case AV_PIX_FMT_YUV420P10BE:
+    case AV_PIX_FMT_YUV444P12BE:
+    case AV_PIX_FMT_YUV422P12BE:
+    case AV_PIX_FMT_YUV420P12BE:
+    case AV_PIX_FMT_YUV444P14BE:
+    case AV_PIX_FMT_YUV422P14BE:
+    case AV_PIX_FMT_YUV420P14BE:
+    case AV_PIX_FMT_YUV420P16BE:
+    case AV_PIX_FMT_YUV422P16BE:
+    case AV_PIX_FMT_YUV444P16BE:
+
+    case AV_PIX_FMT_YUVA444P9BE:
+    case AV_PIX_FMT_YUVA422P9BE:
+    case AV_PIX_FMT_YUVA420P9BE:
+    case AV_PIX_FMT_YUVA444P10BE:
+    case AV_PIX_FMT_YUVA422P10BE:
+    case AV_PIX_FMT_YUVA420P10BE:
+    case AV_PIX_FMT_YUVA420P16BE:
+    case AV_PIX_FMT_YUVA422P16BE:
+    case AV_PIX_FMT_YUVA444P16BE:
         c->chrToYV12 = bswap16UV_c;
         break;
 #endif
     }
     if (c->chrSrcHSubSample) {
         switch (srcFormat) {
-        case PIX_FMT_RGBA64BE:
+        case AV_PIX_FMT_RGBA64BE:
             c->chrToYV12 = rgb64BEToUV_half_c;
             break;
-        case PIX_FMT_RGBA64LE:
+        case AV_PIX_FMT_RGBA64LE:
             c->chrToYV12 = rgb64LEToUV_half_c;
             break;
-        case PIX_FMT_RGB48BE:
+        case AV_PIX_FMT_RGB48BE:
             c->chrToYV12 = rgb48BEToUV_half_c;
             break;
-        case PIX_FMT_RGB48LE:
+        case AV_PIX_FMT_RGB48LE:
             c->chrToYV12 = rgb48LEToUV_half_c;
             break;
-        case PIX_FMT_BGR48BE:
+        case AV_PIX_FMT_BGR48BE:
             c->chrToYV12 = bgr48BEToUV_half_c;
             break;
-        case PIX_FMT_BGR48LE:
+        case AV_PIX_FMT_BGR48LE:
             c->chrToYV12 = bgr48LEToUV_half_c;
             break;
-        case PIX_FMT_RGB32:
+        case AV_PIX_FMT_RGB32:
             c->chrToYV12 = bgr32ToUV_half_c;
             break;
-        case PIX_FMT_RGB32_1:
+        case AV_PIX_FMT_RGB32_1:
             c->chrToYV12 = bgr321ToUV_half_c;
             break;
-        case PIX_FMT_BGR24:
+        case AV_PIX_FMT_BGR24:
             c->chrToYV12 = bgr24ToUV_half_c;
             break;
-        case PIX_FMT_BGR565LE:
+        case AV_PIX_FMT_BGR565LE:
             c->chrToYV12 = bgr16leToUV_half_c;
             break;
-        case PIX_FMT_BGR565BE:
+        case AV_PIX_FMT_BGR565BE:
             c->chrToYV12 = bgr16beToUV_half_c;
             break;
-        case PIX_FMT_BGR555LE:
+        case AV_PIX_FMT_BGR555LE:
             c->chrToYV12 = bgr15leToUV_half_c;
             break;
-        case PIX_FMT_BGR555BE:
+        case AV_PIX_FMT_BGR555BE:
             c->chrToYV12 = bgr15beToUV_half_c;
             break;
-        case PIX_FMT_GBR24P  :
+        case AV_PIX_FMT_GBR24P  :
             c->chrToYV12 = gbr24pToUV_half_c;
             break;
-        case PIX_FMT_BGR444LE:
+        case AV_PIX_FMT_BGR444LE:
             c->chrToYV12 = bgr12leToUV_half_c;
             break;
-        case PIX_FMT_BGR444BE:
+        case AV_PIX_FMT_BGR444BE:
             c->chrToYV12 = bgr12beToUV_half_c;
             break;
-        case PIX_FMT_BGR32:
+        case AV_PIX_FMT_BGR32:
             c->chrToYV12 = rgb32ToUV_half_c;
             break;
-        case PIX_FMT_BGR32_1:
+        case AV_PIX_FMT_BGR32_1:
             c->chrToYV12 = rgb321ToUV_half_c;
             break;
-        case PIX_FMT_RGB24:
+        case AV_PIX_FMT_RGB24:
             c->chrToYV12 = rgb24ToUV_half_c;
             break;
-        case PIX_FMT_RGB565LE:
+        case AV_PIX_FMT_RGB565LE:
             c->chrToYV12 = rgb16leToUV_half_c;
             break;
-        case PIX_FMT_RGB565BE:
+        case AV_PIX_FMT_RGB565BE:
             c->chrToYV12 = rgb16beToUV_half_c;
             break;
-        case PIX_FMT_RGB555LE:
+        case AV_PIX_FMT_RGB555LE:
             c->chrToYV12 = rgb15leToUV_half_c;
             break;
-        case PIX_FMT_RGB555BE:
+        case AV_PIX_FMT_RGB555BE:
             c->chrToYV12 = rgb15beToUV_half_c;
             break;
-        case PIX_FMT_RGB444LE:
+        case AV_PIX_FMT_RGB444LE:
             c->chrToYV12 = rgb12leToUV_half_c;
             break;
-        case PIX_FMT_RGB444BE:
+        case AV_PIX_FMT_RGB444BE:
             c->chrToYV12 = rgb12beToUV_half_c;
             break;
         }
     } else {
         switch (srcFormat) {
-        case PIX_FMT_RGBA64BE:
+        case AV_PIX_FMT_RGBA64BE:
             c->chrToYV12 = rgb64BEToUV_c;
             break;
-        case PIX_FMT_RGBA64LE:
+        case AV_PIX_FMT_RGBA64LE:
             c->chrToYV12 = rgb64LEToUV_c;
             break;
-        case PIX_FMT_RGB48BE:
+        case AV_PIX_FMT_RGB48BE:
             c->chrToYV12 = rgb48BEToUV_c;
             break;
-        case PIX_FMT_RGB48LE:
+        case AV_PIX_FMT_RGB48LE:
             c->chrToYV12 = rgb48LEToUV_c;
             break;
-        case PIX_FMT_BGR48BE:
+        case AV_PIX_FMT_BGR48BE:
             c->chrToYV12 = bgr48BEToUV_c;
             break;
-        case PIX_FMT_BGR48LE:
+        case AV_PIX_FMT_BGR48LE:
             c->chrToYV12 = bgr48LEToUV_c;
             break;
-        case PIX_FMT_RGB32:
+        case AV_PIX_FMT_RGB32:
             c->chrToYV12 = bgr32ToUV_c;
             break;
-        case PIX_FMT_RGB32_1:
+        case AV_PIX_FMT_RGB32_1:
             c->chrToYV12 = bgr321ToUV_c;
             break;
-        case PIX_FMT_BGR24:
+        case AV_PIX_FMT_BGR24:
             c->chrToYV12 = bgr24ToUV_c;
             break;
-        case PIX_FMT_BGR565LE:
+        case AV_PIX_FMT_BGR565LE:
             c->chrToYV12 = bgr16leToUV_c;
             break;
-        case PIX_FMT_BGR565BE:
+        case AV_PIX_FMT_BGR565BE:
             c->chrToYV12 = bgr16beToUV_c;
             break;
-        case PIX_FMT_BGR555LE:
+        case AV_PIX_FMT_BGR555LE:
             c->chrToYV12 = bgr15leToUV_c;
             break;
-        case PIX_FMT_BGR555BE:
+        case AV_PIX_FMT_BGR555BE:
             c->chrToYV12 = bgr15beToUV_c;
             break;
-        case PIX_FMT_BGR444LE:
+        case AV_PIX_FMT_BGR444LE:
             c->chrToYV12 = bgr12leToUV_c;
             break;
-        case PIX_FMT_BGR444BE:
+        case AV_PIX_FMT_BGR444BE:
             c->chrToYV12 = bgr12beToUV_c;
             break;
-        case PIX_FMT_BGR32:
+        case AV_PIX_FMT_BGR32:
             c->chrToYV12 = rgb32ToUV_c;
             break;
-        case PIX_FMT_BGR32_1:
+        case AV_PIX_FMT_BGR32_1:
             c->chrToYV12 = rgb321ToUV_c;
             break;
-        case PIX_FMT_RGB24:
+        case AV_PIX_FMT_RGB24:
             c->chrToYV12 = rgb24ToUV_c;
             break;
-        case PIX_FMT_RGB565LE:
+        case AV_PIX_FMT_RGB565LE:
             c->chrToYV12 = rgb16leToUV_c;
             break;
-        case PIX_FMT_RGB565BE:
+        case AV_PIX_FMT_RGB565BE:
             c->chrToYV12 = rgb16beToUV_c;
             break;
-        case PIX_FMT_RGB555LE:
+        case AV_PIX_FMT_RGB555LE:
             c->chrToYV12 = rgb15leToUV_c;
             break;
-        case PIX_FMT_RGB555BE:
+        case AV_PIX_FMT_RGB555BE:
             c->chrToYV12 = rgb15beToUV_c;
             break;
-        case PIX_FMT_RGB444LE:
+        case AV_PIX_FMT_RGB444LE:
             c->chrToYV12 = rgb12leToUV_c;
             break;
-        case PIX_FMT_RGB444BE:
+        case AV_PIX_FMT_RGB444BE:
             c->chrToYV12 = rgb12beToUV_c;
             break;
         }
@@ -1116,187 +1136,217 @@
     c->lumToYV12 = NULL;
     c->alpToYV12 = NULL;
     switch (srcFormat) {
-    case PIX_FMT_GBRP9LE:
+    case AV_PIX_FMT_GBRP9LE:
         c->readLumPlanar = planar_rgb9le_to_y;
         break;
-    case PIX_FMT_GBRP10LE:
+    case AV_PIX_FMT_GBRP10LE:
         c->readLumPlanar = planar_rgb10le_to_y;
         break;
-    case PIX_FMT_GBRP12LE:
+    case AV_PIX_FMT_GBRP12LE:
         c->readLumPlanar = planar_rgb12le_to_y;
         break;
-    case PIX_FMT_GBRP14LE:
+    case AV_PIX_FMT_GBRP14LE:
         c->readLumPlanar = planar_rgb14le_to_y;
         break;
-    case PIX_FMT_GBRP16LE:
+    case AV_PIX_FMT_GBRP16LE:
         c->readLumPlanar = planar_rgb16le_to_y;
         break;
-    case PIX_FMT_GBRP9BE:
+    case AV_PIX_FMT_GBRP9BE:
         c->readLumPlanar = planar_rgb9be_to_y;
         break;
-    case PIX_FMT_GBRP10BE:
+    case AV_PIX_FMT_GBRP10BE:
         c->readLumPlanar = planar_rgb10be_to_y;
         break;
-    case PIX_FMT_GBRP12BE:
+    case AV_PIX_FMT_GBRP12BE:
         c->readLumPlanar = planar_rgb12be_to_y;
         break;
-    case PIX_FMT_GBRP14BE:
+    case AV_PIX_FMT_GBRP14BE:
         c->readLumPlanar = planar_rgb14be_to_y;
         break;
-    case PIX_FMT_GBRP16BE:
+    case AV_PIX_FMT_GBRP16BE:
         c->readLumPlanar = planar_rgb16be_to_y;
         break;
-    case PIX_FMT_GBRP:
+    case AV_PIX_FMT_GBRP:
         c->readLumPlanar = planar_rgb_to_y;
         break;
 #if HAVE_BIGENDIAN
-    case PIX_FMT_YUV444P9LE:
-    case PIX_FMT_YUV422P9LE:
-    case PIX_FMT_YUV420P9LE:
-    case PIX_FMT_YUV444P10LE:
-    case PIX_FMT_YUV422P10LE:
-    case PIX_FMT_YUV420P10LE:
-    case PIX_FMT_YUV444P12LE:
-    case PIX_FMT_YUV422P12LE:
-    case PIX_FMT_YUV420P12LE:
-    case PIX_FMT_YUV444P14LE:
-    case PIX_FMT_YUV422P14LE:
-    case PIX_FMT_YUV420P14LE:
-    case PIX_FMT_YUV420P16LE:
-    case PIX_FMT_YUV422P16LE:
-    case PIX_FMT_YUV444P16LE:
-    case PIX_FMT_GRAY16LE:
+    case AV_PIX_FMT_YUV444P9LE:
+    case AV_PIX_FMT_YUV422P9LE:
+    case AV_PIX_FMT_YUV420P9LE:
+    case AV_PIX_FMT_YUV444P10LE:
+    case AV_PIX_FMT_YUV422P10LE:
+    case AV_PIX_FMT_YUV420P10LE:
+    case AV_PIX_FMT_YUV444P12LE:
+    case AV_PIX_FMT_YUV422P12LE:
+    case AV_PIX_FMT_YUV420P12LE:
+    case AV_PIX_FMT_YUV444P14LE:
+    case AV_PIX_FMT_YUV422P14LE:
+    case AV_PIX_FMT_YUV420P14LE:
+    case AV_PIX_FMT_YUV420P16LE:
+    case AV_PIX_FMT_YUV422P16LE:
+    case AV_PIX_FMT_YUV444P16LE:
+
+    case AV_PIX_FMT_GRAY16LE:
         c->lumToYV12 = bswap16Y_c;
         break;
+    case AV_PIX_FMT_YUVA444P9LE:
+    case AV_PIX_FMT_YUVA422P9LE:
+    case AV_PIX_FMT_YUVA420P9LE:
+    case AV_PIX_FMT_YUVA444P10LE:
+    case AV_PIX_FMT_YUVA422P10LE:
+    case AV_PIX_FMT_YUVA420P10LE:
+    case AV_PIX_FMT_YUVA420P16LE:
+    case AV_PIX_FMT_YUVA422P16LE:
+    case AV_PIX_FMT_YUVA444P16LE:
+        c->lumToYV12 = bswap16Y_c;
+        c->alpToYV12 = bswap16Y_c;
+        break;
 #else
-    case PIX_FMT_YUV444P9BE:
-    case PIX_FMT_YUV422P9BE:
-    case PIX_FMT_YUV420P9BE:
-    case PIX_FMT_YUV444P10BE:
-    case PIX_FMT_YUV422P10BE:
-    case PIX_FMT_YUV420P10BE:
-    case PIX_FMT_YUV444P12BE:
-    case PIX_FMT_YUV422P12BE:
-    case PIX_FMT_YUV420P12BE:
-    case PIX_FMT_YUV444P14BE:
-    case PIX_FMT_YUV422P14BE:
-    case PIX_FMT_YUV420P14BE:
-    case PIX_FMT_YUV420P16BE:
-    case PIX_FMT_YUV422P16BE:
-    case PIX_FMT_YUV444P16BE:
-    case PIX_FMT_GRAY16BE:
+    case AV_PIX_FMT_YUV444P9BE:
+    case AV_PIX_FMT_YUV422P9BE:
+    case AV_PIX_FMT_YUV420P9BE:
+    case AV_PIX_FMT_YUV444P10BE:
+    case AV_PIX_FMT_YUV422P10BE:
+    case AV_PIX_FMT_YUV420P10BE:
+    case AV_PIX_FMT_YUV444P12BE:
+    case AV_PIX_FMT_YUV422P12BE:
+    case AV_PIX_FMT_YUV420P12BE:
+    case AV_PIX_FMT_YUV444P14BE:
+    case AV_PIX_FMT_YUV422P14BE:
+    case AV_PIX_FMT_YUV420P14BE:
+    case AV_PIX_FMT_YUV420P16BE:
+    case AV_PIX_FMT_YUV422P16BE:
+    case AV_PIX_FMT_YUV444P16BE:
+
+    case AV_PIX_FMT_GRAY16BE:
         c->lumToYV12 = bswap16Y_c;
         break;
+    case AV_PIX_FMT_YUVA444P9BE:
+    case AV_PIX_FMT_YUVA422P9BE:
+    case AV_PIX_FMT_YUVA420P9BE:
+    case AV_PIX_FMT_YUVA444P10BE:
+    case AV_PIX_FMT_YUVA422P10BE:
+    case AV_PIX_FMT_YUVA420P10BE:
+    case AV_PIX_FMT_YUVA420P16BE:
+    case AV_PIX_FMT_YUVA422P16BE:
+    case AV_PIX_FMT_YUVA444P16BE:
+        c->lumToYV12 = bswap16Y_c;
+        c->alpToYV12 = bswap16Y_c;
+        break;
 #endif
-    case PIX_FMT_YUYV422:
-    case PIX_FMT_Y400A:
+    case AV_PIX_FMT_YUYV422:
+    case AV_PIX_FMT_Y400A:
         c->lumToYV12 = yuy2ToY_c;
         break;
-    case PIX_FMT_UYVY422:
+    case AV_PIX_FMT_UYVY422:
         c->lumToYV12 = uyvyToY_c;
         break;
-    case PIX_FMT_BGR24:
+    case AV_PIX_FMT_BGR24:
         c->lumToYV12 = bgr24ToY_c;
         break;
-    case PIX_FMT_BGR565LE:
+    case AV_PIX_FMT_BGR565LE:
         c->lumToYV12 = bgr16leToY_c;
         break;
-    case PIX_FMT_BGR565BE:
+    case AV_PIX_FMT_BGR565BE:
         c->lumToYV12 = bgr16beToY_c;
         break;
-    case PIX_FMT_BGR555LE:
+    case AV_PIX_FMT_BGR555LE:
         c->lumToYV12 = bgr15leToY_c;
         break;
-    case PIX_FMT_BGR555BE:
+    case AV_PIX_FMT_BGR555BE:
         c->lumToYV12 = bgr15beToY_c;
         break;
-    case PIX_FMT_BGR444LE:
+    case AV_PIX_FMT_BGR444LE:
         c->lumToYV12 = bgr12leToY_c;
         break;
-    case PIX_FMT_BGR444BE:
+    case AV_PIX_FMT_BGR444BE:
         c->lumToYV12 = bgr12beToY_c;
         break;
-    case PIX_FMT_RGB24:
+    case AV_PIX_FMT_RGB24:
         c->lumToYV12 = rgb24ToY_c;
         break;
-    case PIX_FMT_RGB565LE:
+    case AV_PIX_FMT_RGB565LE:
         c->lumToYV12 = rgb16leToY_c;
         break;
-    case PIX_FMT_RGB565BE:
+    case AV_PIX_FMT_RGB565BE:
         c->lumToYV12 = rgb16beToY_c;
         break;
-    case PIX_FMT_RGB555LE:
+    case AV_PIX_FMT_RGB555LE:
         c->lumToYV12 = rgb15leToY_c;
         break;
-    case PIX_FMT_RGB555BE:
+    case AV_PIX_FMT_RGB555BE:
         c->lumToYV12 = rgb15beToY_c;
         break;
-    case PIX_FMT_RGB444LE:
+    case AV_PIX_FMT_RGB444LE:
         c->lumToYV12 = rgb12leToY_c;
         break;
-    case PIX_FMT_RGB444BE:
+    case AV_PIX_FMT_RGB444BE:
         c->lumToYV12 = rgb12beToY_c;
         break;
-    case PIX_FMT_RGB8:
-    case PIX_FMT_BGR8:
-    case PIX_FMT_PAL8:
-    case PIX_FMT_BGR4_BYTE:
-    case PIX_FMT_RGB4_BYTE:
+    case AV_PIX_FMT_RGB8:
+    case AV_PIX_FMT_BGR8:
+    case AV_PIX_FMT_PAL8:
+    case AV_PIX_FMT_BGR4_BYTE:
+    case AV_PIX_FMT_RGB4_BYTE:
         c->lumToYV12 = palToY_c;
         break;
-    case PIX_FMT_MONOBLACK:
+    case AV_PIX_FMT_MONOBLACK:
         c->lumToYV12 = monoblack2Y_c;
         break;
-    case PIX_FMT_MONOWHITE:
+    case AV_PIX_FMT_MONOWHITE:
         c->lumToYV12 = monowhite2Y_c;
         break;
-    case PIX_FMT_RGB32:
+    case AV_PIX_FMT_RGB32:
         c->lumToYV12 = bgr32ToY_c;
         break;
-    case PIX_FMT_RGB32_1:
+    case AV_PIX_FMT_RGB32_1:
         c->lumToYV12 = bgr321ToY_c;
         break;
-    case PIX_FMT_BGR32:
+    case AV_PIX_FMT_BGR32:
         c->lumToYV12 = rgb32ToY_c;
         break;
-    case PIX_FMT_BGR32_1:
+    case AV_PIX_FMT_BGR32_1:
         c->lumToYV12 = rgb321ToY_c;
         break;
-    case PIX_FMT_RGB48BE:
+    case AV_PIX_FMT_RGB48BE:
         c->lumToYV12 = rgb48BEToY_c;
         break;
-    case PIX_FMT_RGB48LE:
+    case AV_PIX_FMT_RGB48LE:
         c->lumToYV12 = rgb48LEToY_c;
         break;
-    case PIX_FMT_BGR48BE:
+    case AV_PIX_FMT_BGR48BE:
         c->lumToYV12 = bgr48BEToY_c;
         break;
-    case PIX_FMT_BGR48LE:
+    case AV_PIX_FMT_BGR48LE:
         c->lumToYV12 = bgr48LEToY_c;
         break;
-    case PIX_FMT_RGBA64BE:
+    case AV_PIX_FMT_RGBA64BE:
         c->lumToYV12 = rgb64BEToY_c;
         break;
-    case PIX_FMT_RGBA64LE:
+    case AV_PIX_FMT_RGBA64LE:
         c->lumToYV12 = rgb64LEToY_c;
         break;
     }
     if (c->alpPixBuf) {
+        if (is16BPS(srcFormat) || isNBPS(srcFormat)) {
+            if (HAVE_BIGENDIAN == !isBE(srcFormat))
+                c->alpToYV12 = bswap16Y_c;
+        }
         switch (srcFormat) {
-        case PIX_FMT_RGBA64LE:
-        case PIX_FMT_RGBA64BE:  c->alpToYV12 = rgba64ToA_c; break;
-        case PIX_FMT_BGRA:
-        case PIX_FMT_RGBA:
+        case AV_PIX_FMT_RGBA64LE:
+        case AV_PIX_FMT_RGBA64BE:  c->alpToYV12 = rgba64ToA_c; break;
+        case AV_PIX_FMT_BGRA:
+        case AV_PIX_FMT_RGBA:
             c->alpToYV12 = rgbaToA_c;
             break;
-        case PIX_FMT_ABGR:
-        case PIX_FMT_ARGB:
+        case AV_PIX_FMT_ABGR:
+        case AV_PIX_FMT_ARGB:
             c->alpToYV12 = abgrToA_c;
             break;
-        case PIX_FMT_Y400A:
+        case AV_PIX_FMT_Y400A:
             c->alpToYV12 = uyvyToY_c;
             break;
-        case PIX_FMT_PAL8 :
+        case AV_PIX_FMT_PAL8 :
             c->alpToYV12 = palToA_c;
             break;
         }
diff --git a/libswscale/libswscale.v b/libswscale/libswscale.v
index c68f153..8b9a96a 100644
--- a/libswscale/libswscale.v
+++ b/libswscale/libswscale.v
@@ -1,4 +1,4 @@
 LIBSWSCALE_$MAJOR {
-        global: swscale_*; sws_*; ff_*;
+        global: swscale_*; sws_*;
         local: *;
 };
diff --git a/libswscale/options.c b/libswscale/options.c
index 0204750..f7d261c 100644
--- a/libswscale/options.c
+++ b/libswscale/options.c
@@ -56,8 +56,8 @@
     { "srch",            "source height",                 OFFSET(srcH),      AV_OPT_TYPE_INT,    { .i64 = 16                 }, 1,       INT_MAX,        VE },
     { "dstw",            "destination width",             OFFSET(dstW),      AV_OPT_TYPE_INT,    { .i64 = 16                 }, 1,       INT_MAX,        VE },
     { "dsth",            "destination height",            OFFSET(dstH),      AV_OPT_TYPE_INT,    { .i64 = 16                 }, 1,       INT_MAX,        VE },
-    { "src_format",      "source format",                 OFFSET(srcFormat), AV_OPT_TYPE_INT,    { .i64 = DEFAULT            }, 0,       PIX_FMT_NB - 1, VE },
-    { "dst_format",      "destination format",            OFFSET(dstFormat), AV_OPT_TYPE_INT,    { .i64 = DEFAULT            }, 0,       PIX_FMT_NB - 1, VE },
+    { "src_format",      "source format",                 OFFSET(srcFormat), AV_OPT_TYPE_INT,    { .i64 = DEFAULT            }, 0,       AV_PIX_FMT_NB - 1, VE },
+    { "dst_format",      "destination format",            OFFSET(dstFormat), AV_OPT_TYPE_INT,    { .i64 = DEFAULT            }, 0,       AV_PIX_FMT_NB - 1, VE },
     { "src_range",       "source range",                  OFFSET(srcRange),  AV_OPT_TYPE_INT,    { .i64 = DEFAULT            }, 0,       1,              VE },
     { "dst_range",       "destination range",             OFFSET(dstRange),  AV_OPT_TYPE_INT,    { .i64 = DEFAULT            }, 0,       1,              VE },
     { "param0",          "scaler param 0",                OFFSET(param[0]),  AV_OPT_TYPE_DOUBLE, { .dbl = SWS_PARAM_DEFAULT  }, INT_MIN, INT_MAX,        VE },
@@ -71,6 +71,7 @@
     .item_name  = sws_context_to_name,
     .option     = options,
     .category   = AV_CLASS_CATEGORY_SWSCALER,
+    .version    = LIBAVUTIL_VERSION_INT,
 };
 
 const AVClass *sws_get_class(void)
diff --git a/libswscale/output.c b/libswscale/output.c
index 5039629..8c20068 100644
--- a/libswscale/output.c
+++ b/libswscale/output.c
@@ -244,6 +244,10 @@
 yuv2NBPS( 9, LE, 0, 10, int16_t)
 yuv2NBPS(10, BE, 1, 10, int16_t)
 yuv2NBPS(10, LE, 0, 10, int16_t)
+yuv2NBPS(12, BE, 1, 10, int16_t)
+yuv2NBPS(12, LE, 0, 10, int16_t)
+yuv2NBPS(14, BE, 1, 10, int16_t)
+yuv2NBPS(14, LE, 0, 10, int16_t)
 yuv2NBPS(16, BE, 1, 16, int32_t)
 yuv2NBPS(16, LE, 0, 16, int32_t)
 
@@ -276,11 +280,11 @@
                         const int16_t **chrUSrc, const int16_t **chrVSrc,
                         uint8_t *dest, int chrDstW)
 {
-    enum PixelFormat dstFormat = c->dstFormat;
+    enum AVPixelFormat dstFormat = c->dstFormat;
     const uint8_t *chrDither = c->chrDither8;
     int i;
 
-    if (dstFormat == PIX_FMT_NV12)
+    if (dstFormat == AV_PIX_FMT_NV12)
         for (i=0; i<chrDstW; i++) {
             int u = chrDither[i & 7] << 12;
             int v = chrDither[(i + 3) & 7] << 12;
@@ -312,7 +316,7 @@
     acc <<= 1; \
     acc |= (val) >= (128 + 110)
 #define output_pixel(pos, acc) \
-    if (target == PIX_FMT_MONOBLACK) { \
+    if (target == AV_PIX_FMT_MONOBLACK) { \
         pos = acc; \
     } else { \
         pos = ~acc; \
@@ -324,7 +328,7 @@
                       const int16_t *chrFilter, const int16_t **chrUSrc,
                       const int16_t **chrVSrc, int chrFilterSize,
                       const int16_t **alpSrc, uint8_t *dest, int dstW,
-                      int y, enum PixelFormat target)
+                      int y, enum AVPixelFormat target)
 {
     const uint8_t * const d128=dither_8x8_220[y&7];
     int i;
@@ -362,7 +366,7 @@
                       const int16_t *ubuf[2], const int16_t *vbuf[2],
                       const int16_t *abuf[2], uint8_t *dest, int dstW,
                       int yalpha, int uvalpha, int y,
-                      enum PixelFormat target)
+                      enum AVPixelFormat target)
 {
     const int16_t *buf0  = buf[0],  *buf1  = buf[1];
     const uint8_t * const d128 = dither_8x8_220[y & 7];
@@ -397,7 +401,7 @@
 yuv2mono_1_c_template(SwsContext *c, const int16_t *buf0,
                       const int16_t *ubuf[2], const int16_t *vbuf[2],
                       const int16_t *abuf0, uint8_t *dest, int dstW,
-                      int uvalpha, int y, enum PixelFormat target)
+                      int uvalpha, int y, enum AVPixelFormat target)
 {
     const uint8_t * const d128 = dither_8x8_220[y & 7];
     int i;
@@ -453,11 +457,11 @@
                                   y, fmt); \
 }
 
-YUV2PACKEDWRAPPER(yuv2mono,, white, PIX_FMT_MONOWHITE)
-YUV2PACKEDWRAPPER(yuv2mono,, black, PIX_FMT_MONOBLACK)
+YUV2PACKEDWRAPPER(yuv2mono,, white, AV_PIX_FMT_MONOWHITE)
+YUV2PACKEDWRAPPER(yuv2mono,, black, AV_PIX_FMT_MONOBLACK)
 
 #define output_pixels(pos, Y1, U, Y2, V) \
-    if (target == PIX_FMT_YUYV422) { \
+    if (target == AV_PIX_FMT_YUYV422) { \
         dest[pos + 0] = Y1; \
         dest[pos + 1] = U;  \
         dest[pos + 2] = Y2; \
@@ -475,7 +479,7 @@
                      const int16_t *chrFilter, const int16_t **chrUSrc,
                      const int16_t **chrVSrc, int chrFilterSize,
                      const int16_t **alpSrc, uint8_t *dest, int dstW,
-                     int y, enum PixelFormat target)
+                     int y, enum AVPixelFormat target)
 {
     int i;
 
@@ -513,7 +517,7 @@
                      const int16_t *ubuf[2], const int16_t *vbuf[2],
                      const int16_t *abuf[2], uint8_t *dest, int dstW,
                      int yalpha, int uvalpha, int y,
-                     enum PixelFormat target)
+                     enum AVPixelFormat target)
 {
     const int16_t *buf0  = buf[0],  *buf1  = buf[1],
                   *ubuf0 = ubuf[0], *ubuf1 = ubuf[1],
@@ -543,7 +547,7 @@
 yuv2422_1_c_template(SwsContext *c, const int16_t *buf0,
                      const int16_t *ubuf[2], const int16_t *vbuf[2],
                      const int16_t *abuf0, uint8_t *dest, int dstW,
-                     int uvalpha, int y, enum PixelFormat target)
+                     int uvalpha, int y, enum AVPixelFormat target)
 {
     const int16_t *ubuf0 = ubuf[0], *vbuf0 = vbuf[0];
     int i;
@@ -596,11 +600,11 @@
 
 #undef output_pixels
 
-YUV2PACKEDWRAPPER(yuv2, 422, yuyv422, PIX_FMT_YUYV422)
-YUV2PACKEDWRAPPER(yuv2, 422, uyvy422, PIX_FMT_UYVY422)
+YUV2PACKEDWRAPPER(yuv2, 422, yuyv422, AV_PIX_FMT_YUYV422)
+YUV2PACKEDWRAPPER(yuv2, 422, uyvy422, AV_PIX_FMT_UYVY422)
 
-#define R_B ((target == PIX_FMT_RGB48LE || target == PIX_FMT_RGB48BE) ? R : B)
-#define B_R ((target == PIX_FMT_RGB48LE || target == PIX_FMT_RGB48BE) ? B : R)
+#define R_B ((target == AV_PIX_FMT_RGB48LE || target == AV_PIX_FMT_RGB48BE) ? R : B)
+#define B_R ((target == AV_PIX_FMT_RGB48LE || target == AV_PIX_FMT_RGB48BE) ? B : R)
 #define output_pixel(pos, val) \
     if (isBE(target)) { \
         AV_WB16(pos, val); \
@@ -614,7 +618,7 @@
                        const int16_t *chrFilter, const int32_t **chrUSrc,
                        const int32_t **chrVSrc, int chrFilterSize,
                        const int32_t **alpSrc, uint16_t *dest, int dstW,
-                       int y, enum PixelFormat target)
+                       int y, enum AVPixelFormat target)
 {
     int i;
 
@@ -672,7 +676,7 @@
                        const int32_t *ubuf[2], const int32_t *vbuf[2],
                        const int32_t *abuf[2], uint16_t *dest, int dstW,
                        int yalpha, int uvalpha, int y,
-                       enum PixelFormat target)
+                       enum AVPixelFormat target)
 {
     const int32_t *buf0  = buf[0],  *buf1  = buf[1],
                   *ubuf0 = ubuf[0], *ubuf1 = ubuf[1],
@@ -713,7 +717,7 @@
 yuv2rgb48_1_c_template(SwsContext *c, const int32_t *buf0,
                        const int32_t *ubuf[2], const int32_t *vbuf[2],
                        const int32_t *abuf0, uint16_t *dest, int dstW,
-                       int uvalpha, int y, enum PixelFormat target)
+                       int uvalpha, int y, enum AVPixelFormat target)
 {
     const int32_t *ubuf0 = ubuf[0], *vbuf0 = vbuf[0];
     int i;
@@ -826,10 +830,10 @@
                                   dstW, uvalpha, y, fmt); \
 }
 
-YUV2PACKED16WRAPPER(yuv2, rgb48, rgb48be, PIX_FMT_RGB48BE)
-YUV2PACKED16WRAPPER(yuv2, rgb48, rgb48le, PIX_FMT_RGB48LE)
-YUV2PACKED16WRAPPER(yuv2, rgb48, bgr48be, PIX_FMT_BGR48BE)
-YUV2PACKED16WRAPPER(yuv2, rgb48, bgr48le, PIX_FMT_BGR48LE)
+YUV2PACKED16WRAPPER(yuv2, rgb48, rgb48be, AV_PIX_FMT_RGB48BE)
+YUV2PACKED16WRAPPER(yuv2, rgb48, rgb48le, AV_PIX_FMT_RGB48LE)
+YUV2PACKED16WRAPPER(yuv2, rgb48, bgr48be, AV_PIX_FMT_BGR48BE)
+YUV2PACKED16WRAPPER(yuv2, rgb48, bgr48le, AV_PIX_FMT_BGR48LE)
 
 /*
  * Write out 2 RGB pixels in the target pixel format. This function takes a
@@ -843,23 +847,23 @@
 yuv2rgb_write(uint8_t *_dest, int i, int Y1, int Y2,
               unsigned A1, unsigned A2,
               const void *_r, const void *_g, const void *_b, int y,
-              enum PixelFormat target, int hasAlpha)
+              enum AVPixelFormat target, int hasAlpha)
 {
-    if (target == PIX_FMT_ARGB || target == PIX_FMT_RGBA ||
-        target == PIX_FMT_ABGR || target == PIX_FMT_BGRA) {
+    if (target == AV_PIX_FMT_ARGB || target == AV_PIX_FMT_RGBA ||
+        target == AV_PIX_FMT_ABGR || target == AV_PIX_FMT_BGRA) {
         uint32_t *dest = (uint32_t *) _dest;
         const uint32_t *r = (const uint32_t *) _r;
         const uint32_t *g = (const uint32_t *) _g;
         const uint32_t *b = (const uint32_t *) _b;
 
 #if CONFIG_SMALL
-        int sh = hasAlpha ? ((target == PIX_FMT_RGB32_1 || target == PIX_FMT_BGR32_1) ? 0 : 24) : 0;
+        int sh = hasAlpha ? ((target == AV_PIX_FMT_RGB32_1 || target == AV_PIX_FMT_BGR32_1) ? 0 : 24) : 0;
 
         dest[i * 2 + 0] = r[Y1] + g[Y1] + b[Y1] + (hasAlpha ? A1 << sh : 0);
         dest[i * 2 + 1] = r[Y2] + g[Y2] + b[Y2] + (hasAlpha ? A2 << sh : 0);
 #else
         if (hasAlpha) {
-            int sh = (target == PIX_FMT_RGB32_1 || target == PIX_FMT_BGR32_1) ? 0 : 24;
+            int sh = (target == AV_PIX_FMT_RGB32_1 || target == AV_PIX_FMT_BGR32_1) ? 0 : 24;
 
             dest[i * 2 + 0] = r[Y1] + g[Y1] + b[Y1] + (A1 << sh);
             dest[i * 2 + 1] = r[Y2] + g[Y2] + b[Y2] + (A2 << sh);
@@ -868,14 +872,14 @@
             dest[i * 2 + 1] = r[Y2] + g[Y2] + b[Y2];
         }
 #endif
-    } else if (target == PIX_FMT_RGB24 || target == PIX_FMT_BGR24) {
+    } else if (target == AV_PIX_FMT_RGB24 || target == AV_PIX_FMT_BGR24) {
         uint8_t *dest = (uint8_t *) _dest;
         const uint8_t *r = (const uint8_t *) _r;
         const uint8_t *g = (const uint8_t *) _g;
         const uint8_t *b = (const uint8_t *) _b;
 
-#define r_b ((target == PIX_FMT_RGB24) ? r : b)
-#define b_r ((target == PIX_FMT_RGB24) ? b : r)
+#define r_b ((target == AV_PIX_FMT_RGB24) ? r : b)
+#define b_r ((target == AV_PIX_FMT_RGB24) ? b : r)
 
         dest[i * 6 + 0] = r_b[Y1];
         dest[i * 6 + 1] =   g[Y1];
@@ -885,23 +889,23 @@
         dest[i * 6 + 5] = b_r[Y2];
 #undef r_b
 #undef b_r
-    } else if (target == PIX_FMT_RGB565 || target == PIX_FMT_BGR565 ||
-               target == PIX_FMT_RGB555 || target == PIX_FMT_BGR555 ||
-               target == PIX_FMT_RGB444 || target == PIX_FMT_BGR444) {
+    } else if (target == AV_PIX_FMT_RGB565 || target == AV_PIX_FMT_BGR565 ||
+               target == AV_PIX_FMT_RGB555 || target == AV_PIX_FMT_BGR555 ||
+               target == AV_PIX_FMT_RGB444 || target == AV_PIX_FMT_BGR444) {
         uint16_t *dest = (uint16_t *) _dest;
         const uint16_t *r = (const uint16_t *) _r;
         const uint16_t *g = (const uint16_t *) _g;
         const uint16_t *b = (const uint16_t *) _b;
         int dr1, dg1, db1, dr2, dg2, db2;
 
-        if (target == PIX_FMT_RGB565 || target == PIX_FMT_BGR565) {
+        if (target == AV_PIX_FMT_RGB565 || target == AV_PIX_FMT_BGR565) {
             dr1 = dither_2x2_8[ y & 1     ][0];
             dg1 = dither_2x2_4[ y & 1     ][0];
             db1 = dither_2x2_8[(y & 1) ^ 1][0];
             dr2 = dither_2x2_8[ y & 1     ][1];
             dg2 = dither_2x2_4[ y & 1     ][1];
             db2 = dither_2x2_8[(y & 1) ^ 1][1];
-        } else if (target == PIX_FMT_RGB555 || target == PIX_FMT_BGR555) {
+        } else if (target == AV_PIX_FMT_RGB555 || target == AV_PIX_FMT_BGR555) {
             dr1 = dither_2x2_8[ y & 1     ][0];
             dg1 = dither_2x2_8[ y & 1     ][1];
             db1 = dither_2x2_8[(y & 1) ^ 1][0];
@@ -926,7 +930,7 @@
         const uint8_t *b = (const uint8_t *) _b;
         int dr1, dg1, db1, dr2, dg2, db2;
 
-        if (target == PIX_FMT_RGB8 || target == PIX_FMT_BGR8) {
+        if (target == AV_PIX_FMT_RGB8 || target == AV_PIX_FMT_BGR8) {
             const uint8_t * const d64 = dither_8x8_73[y & 7];
             const uint8_t * const d32 = dither_8x8_32[y & 7];
             dr1 = dg1 = d32[(i * 2 + 0) & 7];
@@ -942,7 +946,7 @@
             dg2 =        d64[(i * 2 + 1) & 7];
         }
 
-        if (target == PIX_FMT_RGB4 || target == PIX_FMT_BGR4) {
+        if (target == AV_PIX_FMT_RGB4 || target == AV_PIX_FMT_BGR4) {
             dest[i] = r[Y1 + dr1] + g[Y1 + dg1] + b[Y1 + db1] +
                     ((r[Y2 + dr2] + g[Y2 + dg2] + b[Y2 + db2]) << 4);
         } else {
@@ -958,7 +962,7 @@
                      const int16_t *chrFilter, const int16_t **chrUSrc,
                      const int16_t **chrVSrc, int chrFilterSize,
                      const int16_t **alpSrc, uint8_t *dest, int dstW,
-                     int y, enum PixelFormat target, int hasAlpha)
+                     int y, enum AVPixelFormat target, int hasAlpha)
 {
     int i;
 
@@ -1011,7 +1015,7 @@
                      const int16_t *ubuf[2], const int16_t *vbuf[2],
                      const int16_t *abuf[2], uint8_t *dest, int dstW,
                      int yalpha, int uvalpha, int y,
-                     enum PixelFormat target, int hasAlpha)
+                     enum AVPixelFormat target, int hasAlpha)
 {
     const int16_t *buf0  = buf[0],  *buf1  = buf[1],
                   *ubuf0 = ubuf[0], *ubuf1 = ubuf[1],
@@ -1048,7 +1052,7 @@
 yuv2rgb_1_c_template(SwsContext *c, const int16_t *buf0,
                      const int16_t *ubuf[2], const int16_t *vbuf[2],
                      const int16_t *abuf0, uint8_t *dest, int dstW,
-                     int uvalpha, int y, enum PixelFormat target,
+                     int uvalpha, int y, enum AVPixelFormat target,
                      int hasAlpha)
 {
     const int16_t *ubuf0 = ubuf[0], *vbuf0 = vbuf[0];
@@ -1133,24 +1137,24 @@
 }
 
 #if CONFIG_SMALL
-YUV2RGBWRAPPER(yuv2rgb,,  32_1,  PIX_FMT_RGB32_1,   CONFIG_SWSCALE_ALPHA && c->alpPixBuf)
-YUV2RGBWRAPPER(yuv2rgb,,  32,    PIX_FMT_RGB32,     CONFIG_SWSCALE_ALPHA && c->alpPixBuf)
+YUV2RGBWRAPPER(yuv2rgb,,  32_1,  AV_PIX_FMT_RGB32_1,   CONFIG_SWSCALE_ALPHA && c->alpPixBuf)
+YUV2RGBWRAPPER(yuv2rgb,,  32,    AV_PIX_FMT_RGB32,     CONFIG_SWSCALE_ALPHA && c->alpPixBuf)
 #else
 #if CONFIG_SWSCALE_ALPHA
-YUV2RGBWRAPPER(yuv2rgb,, a32_1,  PIX_FMT_RGB32_1,   1)
-YUV2RGBWRAPPER(yuv2rgb,, a32,    PIX_FMT_RGB32,     1)
+YUV2RGBWRAPPER(yuv2rgb,, a32_1,  AV_PIX_FMT_RGB32_1,   1)
+YUV2RGBWRAPPER(yuv2rgb,, a32,    AV_PIX_FMT_RGB32,     1)
 #endif
-YUV2RGBWRAPPER(yuv2rgb,, x32_1,  PIX_FMT_RGB32_1,   0)
-YUV2RGBWRAPPER(yuv2rgb,, x32,    PIX_FMT_RGB32,     0)
+YUV2RGBWRAPPER(yuv2rgb,, x32_1,  AV_PIX_FMT_RGB32_1,   0)
+YUV2RGBWRAPPER(yuv2rgb,, x32,    AV_PIX_FMT_RGB32,     0)
 #endif
-YUV2RGBWRAPPER(yuv2, rgb, rgb24, PIX_FMT_RGB24,   0)
-YUV2RGBWRAPPER(yuv2, rgb, bgr24, PIX_FMT_BGR24,   0)
-YUV2RGBWRAPPER(yuv2rgb,,  16,    PIX_FMT_RGB565,    0)
-YUV2RGBWRAPPER(yuv2rgb,,  15,    PIX_FMT_RGB555,    0)
-YUV2RGBWRAPPER(yuv2rgb,,  12,    PIX_FMT_RGB444,    0)
-YUV2RGBWRAPPER(yuv2rgb,,   8,    PIX_FMT_RGB8,      0)
-YUV2RGBWRAPPER(yuv2rgb,,   4,    PIX_FMT_RGB4,      0)
-YUV2RGBWRAPPER(yuv2rgb,,   4b,   PIX_FMT_RGB4_BYTE, 0)
+YUV2RGBWRAPPER(yuv2, rgb, rgb24, AV_PIX_FMT_RGB24,   0)
+YUV2RGBWRAPPER(yuv2, rgb, bgr24, AV_PIX_FMT_BGR24,   0)
+YUV2RGBWRAPPER(yuv2rgb,,  16,    AV_PIX_FMT_RGB565,    0)
+YUV2RGBWRAPPER(yuv2rgb,,  15,    AV_PIX_FMT_RGB555,    0)
+YUV2RGBWRAPPER(yuv2rgb,,  12,    AV_PIX_FMT_RGB444,    0)
+YUV2RGBWRAPPER(yuv2rgb,,   8,    AV_PIX_FMT_RGB8,      0)
+YUV2RGBWRAPPER(yuv2rgb,,   4,    AV_PIX_FMT_RGB4,      0)
+YUV2RGBWRAPPER(yuv2rgb,,   4b,   AV_PIX_FMT_RGB4_BYTE, 0)
 
 static av_always_inline void
 yuv2rgb_full_X_c_template(SwsContext *c, const int16_t *lumFilter,
@@ -1158,10 +1162,10 @@
                           const int16_t *chrFilter, const int16_t **chrUSrc,
                           const int16_t **chrVSrc, int chrFilterSize,
                           const int16_t **alpSrc, uint8_t *dest,
-                          int dstW, int y, enum PixelFormat target, int hasAlpha)
+                          int dstW, int y, enum AVPixelFormat target, int hasAlpha)
 {
     int i;
-    int step = (target == PIX_FMT_RGB24 || target == PIX_FMT_BGR24) ? 3 : 4;
+    int step = (target == AV_PIX_FMT_RGB24 || target == AV_PIX_FMT_BGR24) ? 3 : 4;
 
     for (i = 0; i < dstW; i++) {
         int j;
@@ -1202,35 +1206,35 @@
         }
 
         switch(target) {
-        case PIX_FMT_ARGB:
+        case AV_PIX_FMT_ARGB:
             dest[0] = hasAlpha ? A : 255;
             dest[1] = R >> 22;
             dest[2] = G >> 22;
             dest[3] = B >> 22;
             break;
-        case PIX_FMT_RGB24:
+        case AV_PIX_FMT_RGB24:
             dest[0] = R >> 22;
             dest[1] = G >> 22;
             dest[2] = B >> 22;
             break;
-        case PIX_FMT_RGBA:
+        case AV_PIX_FMT_RGBA:
             dest[0] = R >> 22;
             dest[1] = G >> 22;
             dest[2] = B >> 22;
             dest[3] = hasAlpha ? A : 255;
             break;
-        case PIX_FMT_ABGR:
+        case AV_PIX_FMT_ABGR:
             dest[0] = hasAlpha ? A : 255;
             dest[1] = B >> 22;
             dest[2] = G >> 22;
             dest[3] = R >> 22;
             break;
-        case PIX_FMT_BGR24:
+        case AV_PIX_FMT_BGR24:
             dest[0] = B >> 22;
             dest[1] = G >> 22;
             dest[2] = R >> 22;
             break;
-        case PIX_FMT_BGRA:
+        case AV_PIX_FMT_BGRA:
             dest[0] = B >> 22;
             dest[1] = G >> 22;
             dest[2] = R >> 22;
@@ -1242,24 +1246,24 @@
 }
 
 #if CONFIG_SMALL
-YUV2RGBWRAPPERX(yuv2, rgb_full, bgra32_full, PIX_FMT_BGRA,  CONFIG_SWSCALE_ALPHA && c->alpPixBuf)
-YUV2RGBWRAPPERX(yuv2, rgb_full, abgr32_full, PIX_FMT_ABGR,  CONFIG_SWSCALE_ALPHA && c->alpPixBuf)
-YUV2RGBWRAPPERX(yuv2, rgb_full, rgba32_full, PIX_FMT_RGBA,  CONFIG_SWSCALE_ALPHA && c->alpPixBuf)
-YUV2RGBWRAPPERX(yuv2, rgb_full, argb32_full, PIX_FMT_ARGB,  CONFIG_SWSCALE_ALPHA && c->alpPixBuf)
+YUV2RGBWRAPPERX(yuv2, rgb_full, bgra32_full, AV_PIX_FMT_BGRA,  CONFIG_SWSCALE_ALPHA && c->alpPixBuf)
+YUV2RGBWRAPPERX(yuv2, rgb_full, abgr32_full, AV_PIX_FMT_ABGR,  CONFIG_SWSCALE_ALPHA && c->alpPixBuf)
+YUV2RGBWRAPPERX(yuv2, rgb_full, rgba32_full, AV_PIX_FMT_RGBA,  CONFIG_SWSCALE_ALPHA && c->alpPixBuf)
+YUV2RGBWRAPPERX(yuv2, rgb_full, argb32_full, AV_PIX_FMT_ARGB,  CONFIG_SWSCALE_ALPHA && c->alpPixBuf)
 #else
 #if CONFIG_SWSCALE_ALPHA
-YUV2RGBWRAPPERX(yuv2, rgb_full, bgra32_full, PIX_FMT_BGRA,  1)
-YUV2RGBWRAPPERX(yuv2, rgb_full, abgr32_full, PIX_FMT_ABGR,  1)
-YUV2RGBWRAPPERX(yuv2, rgb_full, rgba32_full, PIX_FMT_RGBA,  1)
-YUV2RGBWRAPPERX(yuv2, rgb_full, argb32_full, PIX_FMT_ARGB,  1)
+YUV2RGBWRAPPERX(yuv2, rgb_full, bgra32_full, AV_PIX_FMT_BGRA,  1)
+YUV2RGBWRAPPERX(yuv2, rgb_full, abgr32_full, AV_PIX_FMT_ABGR,  1)
+YUV2RGBWRAPPERX(yuv2, rgb_full, rgba32_full, AV_PIX_FMT_RGBA,  1)
+YUV2RGBWRAPPERX(yuv2, rgb_full, argb32_full, AV_PIX_FMT_ARGB,  1)
 #endif
-YUV2RGBWRAPPERX(yuv2, rgb_full, bgrx32_full, PIX_FMT_BGRA,  0)
-YUV2RGBWRAPPERX(yuv2, rgb_full, xbgr32_full, PIX_FMT_ABGR,  0)
-YUV2RGBWRAPPERX(yuv2, rgb_full, rgbx32_full, PIX_FMT_RGBA,  0)
-YUV2RGBWRAPPERX(yuv2, rgb_full, xrgb32_full, PIX_FMT_ARGB,  0)
+YUV2RGBWRAPPERX(yuv2, rgb_full, bgrx32_full, AV_PIX_FMT_BGRA,  0)
+YUV2RGBWRAPPERX(yuv2, rgb_full, xbgr32_full, AV_PIX_FMT_ABGR,  0)
+YUV2RGBWRAPPERX(yuv2, rgb_full, rgbx32_full, AV_PIX_FMT_RGBA,  0)
+YUV2RGBWRAPPERX(yuv2, rgb_full, xrgb32_full, AV_PIX_FMT_ARGB,  0)
 #endif
-YUV2RGBWRAPPERX(yuv2, rgb_full, bgr24_full,  PIX_FMT_BGR24, 0)
-YUV2RGBWRAPPERX(yuv2, rgb_full, rgb24_full,  PIX_FMT_RGB24, 0)
+YUV2RGBWRAPPERX(yuv2, rgb_full, bgr24_full,  AV_PIX_FMT_BGR24, 0)
+YUV2RGBWRAPPERX(yuv2, rgb_full, rgb24_full,  AV_PIX_FMT_RGB24, 0)
 
 av_cold void ff_sws_init_output_funcs(SwsContext *c,
                                       yuv2planar1_fn *yuv2plane1,
@@ -1269,29 +1273,37 @@
                                       yuv2packed2_fn *yuv2packed2,
                                       yuv2packedX_fn *yuv2packedX)
 {
-    enum PixelFormat dstFormat = c->dstFormat;
+    enum AVPixelFormat dstFormat = c->dstFormat;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(dstFormat);
 
     if (is16BPS(dstFormat)) {
         *yuv2planeX = isBE(dstFormat) ? yuv2planeX_16BE_c  : yuv2planeX_16LE_c;
         *yuv2plane1 = isBE(dstFormat) ? yuv2plane1_16BE_c  : yuv2plane1_16LE_c;
     } else if (is9_OR_10BPS(dstFormat)) {
-        if (av_pix_fmt_descriptors[dstFormat].comp[0].depth_minus1 == 8) {
+        if (desc->comp[0].depth_minus1 == 8) {
             *yuv2planeX = isBE(dstFormat) ? yuv2planeX_9BE_c  : yuv2planeX_9LE_c;
             *yuv2plane1 = isBE(dstFormat) ? yuv2plane1_9BE_c  : yuv2plane1_9LE_c;
-        } else {
+        } else if (desc->comp[0].depth_minus1 == 9) {
             *yuv2planeX = isBE(dstFormat) ? yuv2planeX_10BE_c  : yuv2planeX_10LE_c;
             *yuv2plane1 = isBE(dstFormat) ? yuv2plane1_10BE_c  : yuv2plane1_10LE_c;
-        }
+        } else if (desc->comp[0].depth_minus1 == 11) {
+            *yuv2planeX = isBE(dstFormat) ? yuv2planeX_12BE_c  : yuv2planeX_12LE_c;
+            *yuv2plane1 = isBE(dstFormat) ? yuv2plane1_12BE_c  : yuv2plane1_12LE_c;
+        } else if (desc->comp[0].depth_minus1 == 13) {
+            *yuv2planeX = isBE(dstFormat) ? yuv2planeX_14BE_c  : yuv2planeX_14LE_c;
+            *yuv2plane1 = isBE(dstFormat) ? yuv2plane1_14BE_c  : yuv2plane1_14LE_c;
+        } else
+            av_assert0(0);
     } else {
         *yuv2plane1 = yuv2plane1_8_c;
         *yuv2planeX = yuv2planeX_8_c;
-        if (dstFormat == PIX_FMT_NV12 || dstFormat == PIX_FMT_NV21)
+        if (dstFormat == AV_PIX_FMT_NV12 || dstFormat == AV_PIX_FMT_NV21)
             *yuv2nv12cX = yuv2nv12cX_c;
     }
 
     if(c->flags & SWS_FULL_CHR_H_INT) {
         switch (dstFormat) {
-            case PIX_FMT_RGBA:
+            case AV_PIX_FMT_RGBA:
 #if CONFIG_SMALL
                 *yuv2packedX = yuv2rgba32_full_X_c;
 #else
@@ -1305,7 +1317,7 @@
                 }
 #endif /* !CONFIG_SMALL */
                 break;
-            case PIX_FMT_ARGB:
+            case AV_PIX_FMT_ARGB:
 #if CONFIG_SMALL
                 *yuv2packedX = yuv2argb32_full_X_c;
 #else
@@ -1319,7 +1331,7 @@
                 }
 #endif /* !CONFIG_SMALL */
                 break;
-            case PIX_FMT_BGRA:
+            case AV_PIX_FMT_BGRA:
 #if CONFIG_SMALL
                 *yuv2packedX = yuv2bgra32_full_X_c;
 #else
@@ -1333,7 +1345,7 @@
                 }
 #endif /* !CONFIG_SMALL */
                 break;
-            case PIX_FMT_ABGR:
+            case AV_PIX_FMT_ABGR:
 #if CONFIG_SMALL
                 *yuv2packedX = yuv2abgr32_full_X_c;
 #else
@@ -1347,10 +1359,10 @@
                 }
 #endif /* !CONFIG_SMALL */
                 break;
-            case PIX_FMT_RGB24:
+            case AV_PIX_FMT_RGB24:
             *yuv2packedX = yuv2rgb24_full_X_c;
             break;
-        case PIX_FMT_BGR24:
+        case AV_PIX_FMT_BGR24:
             *yuv2packedX = yuv2bgr24_full_X_c;
             break;
         }
@@ -1359,28 +1371,28 @@
     } else {
         YUV_PACKED:
         switch (dstFormat) {
-        case PIX_FMT_RGB48LE:
+        case AV_PIX_FMT_RGB48LE:
             *yuv2packed1 = yuv2rgb48le_1_c;
             *yuv2packed2 = yuv2rgb48le_2_c;
             *yuv2packedX = yuv2rgb48le_X_c;
             break;
-        case PIX_FMT_RGB48BE:
+        case AV_PIX_FMT_RGB48BE:
             *yuv2packed1 = yuv2rgb48be_1_c;
             *yuv2packed2 = yuv2rgb48be_2_c;
             *yuv2packedX = yuv2rgb48be_X_c;
             break;
-        case PIX_FMT_BGR48LE:
+        case AV_PIX_FMT_BGR48LE:
             *yuv2packed1 = yuv2bgr48le_1_c;
             *yuv2packed2 = yuv2bgr48le_2_c;
             *yuv2packedX = yuv2bgr48le_X_c;
             break;
-        case PIX_FMT_BGR48BE:
+        case AV_PIX_FMT_BGR48BE:
             *yuv2packed1 = yuv2bgr48be_1_c;
             *yuv2packed2 = yuv2bgr48be_2_c;
             *yuv2packedX = yuv2bgr48be_X_c;
             break;
-        case PIX_FMT_RGB32:
-        case PIX_FMT_BGR32:
+        case AV_PIX_FMT_RGB32:
+        case AV_PIX_FMT_BGR32:
 #if CONFIG_SMALL
             *yuv2packed1 = yuv2rgb32_1_c;
             *yuv2packed2 = yuv2rgb32_2_c;
@@ -1400,8 +1412,8 @@
                 }
 #endif /* !CONFIG_SMALL */
             break;
-        case PIX_FMT_RGB32_1:
-        case PIX_FMT_BGR32_1:
+        case AV_PIX_FMT_RGB32_1:
+        case AV_PIX_FMT_BGR32_1:
 #if CONFIG_SMALL
                 *yuv2packed1 = yuv2rgb32_1_1_c;
                 *yuv2packed2 = yuv2rgb32_1_2_c;
@@ -1421,54 +1433,54 @@
                 }
 #endif /* !CONFIG_SMALL */
                 break;
-        case PIX_FMT_RGB24:
+        case AV_PIX_FMT_RGB24:
             *yuv2packed1 = yuv2rgb24_1_c;
             *yuv2packed2 = yuv2rgb24_2_c;
             *yuv2packedX = yuv2rgb24_X_c;
             break;
-        case PIX_FMT_BGR24:
+        case AV_PIX_FMT_BGR24:
             *yuv2packed1 = yuv2bgr24_1_c;
             *yuv2packed2 = yuv2bgr24_2_c;
             *yuv2packedX = yuv2bgr24_X_c;
             break;
-        case PIX_FMT_RGB565LE:
-        case PIX_FMT_RGB565BE:
-        case PIX_FMT_BGR565LE:
-        case PIX_FMT_BGR565BE:
+        case AV_PIX_FMT_RGB565LE:
+        case AV_PIX_FMT_RGB565BE:
+        case AV_PIX_FMT_BGR565LE:
+        case AV_PIX_FMT_BGR565BE:
             *yuv2packed1 = yuv2rgb16_1_c;
             *yuv2packed2 = yuv2rgb16_2_c;
             *yuv2packedX = yuv2rgb16_X_c;
             break;
-        case PIX_FMT_RGB555LE:
-        case PIX_FMT_RGB555BE:
-        case PIX_FMT_BGR555LE:
-        case PIX_FMT_BGR555BE:
+        case AV_PIX_FMT_RGB555LE:
+        case AV_PIX_FMT_RGB555BE:
+        case AV_PIX_FMT_BGR555LE:
+        case AV_PIX_FMT_BGR555BE:
             *yuv2packed1 = yuv2rgb15_1_c;
             *yuv2packed2 = yuv2rgb15_2_c;
             *yuv2packedX = yuv2rgb15_X_c;
             break;
-        case PIX_FMT_RGB444LE:
-        case PIX_FMT_RGB444BE:
-        case PIX_FMT_BGR444LE:
-        case PIX_FMT_BGR444BE:
+        case AV_PIX_FMT_RGB444LE:
+        case AV_PIX_FMT_RGB444BE:
+        case AV_PIX_FMT_BGR444LE:
+        case AV_PIX_FMT_BGR444BE:
             *yuv2packed1 = yuv2rgb12_1_c;
             *yuv2packed2 = yuv2rgb12_2_c;
             *yuv2packedX = yuv2rgb12_X_c;
             break;
-        case PIX_FMT_RGB8:
-        case PIX_FMT_BGR8:
+        case AV_PIX_FMT_RGB8:
+        case AV_PIX_FMT_BGR8:
             *yuv2packed1 = yuv2rgb8_1_c;
             *yuv2packed2 = yuv2rgb8_2_c;
             *yuv2packedX = yuv2rgb8_X_c;
             break;
-        case PIX_FMT_RGB4:
-        case PIX_FMT_BGR4:
+        case AV_PIX_FMT_RGB4:
+        case AV_PIX_FMT_BGR4:
             *yuv2packed1 = yuv2rgb4_1_c;
             *yuv2packed2 = yuv2rgb4_2_c;
             *yuv2packedX = yuv2rgb4_X_c;
             break;
-        case PIX_FMT_RGB4_BYTE:
-        case PIX_FMT_BGR4_BYTE:
+        case AV_PIX_FMT_RGB4_BYTE:
+        case AV_PIX_FMT_BGR4_BYTE:
             *yuv2packed1 = yuv2rgb4b_1_c;
             *yuv2packed2 = yuv2rgb4b_2_c;
             *yuv2packedX = yuv2rgb4b_X_c;
@@ -1476,22 +1488,22 @@
         }
     }
     switch (dstFormat) {
-    case PIX_FMT_MONOWHITE:
+    case AV_PIX_FMT_MONOWHITE:
         *yuv2packed1 = yuv2monowhite_1_c;
         *yuv2packed2 = yuv2monowhite_2_c;
         *yuv2packedX = yuv2monowhite_X_c;
         break;
-    case PIX_FMT_MONOBLACK:
+    case AV_PIX_FMT_MONOBLACK:
         *yuv2packed1 = yuv2monoblack_1_c;
         *yuv2packed2 = yuv2monoblack_2_c;
         *yuv2packedX = yuv2monoblack_X_c;
         break;
-    case PIX_FMT_YUYV422:
+    case AV_PIX_FMT_YUYV422:
         *yuv2packed1 = yuv2yuyv422_1_c;
         *yuv2packed2 = yuv2yuyv422_2_c;
         *yuv2packedX = yuv2yuyv422_X_c;
         break;
-    case PIX_FMT_UYVY422:
+    case AV_PIX_FMT_UYVY422:
         *yuv2packed1 = yuv2uyvy422_1_c;
         *yuv2packed2 = yuv2uyvy422_2_c;
         *yuv2packedX = yuv2uyvy422_X_c;
diff --git a/libswscale/ppc/swscale_altivec.c b/libswscale/ppc/swscale_altivec.c
index c621866..9ca2868 100644
--- a/libswscale/ppc/swscale_altivec.c
+++ b/libswscale/ppc/swscale_altivec.c
@@ -32,78 +32,37 @@
 
 #define vzero vec_splat_s32(0)
 
-static inline void altivec_packIntArrayToCharArray(int *val, uint8_t *dest,
-                                                   int dstW)
-{
-    register int i;
-    vector unsigned int altivec_vectorShiftInt19 =
-        vec_add(vec_splat_u32(10), vec_splat_u32(9));
-    if ((uintptr_t)dest % 16) {
-        /* badly aligned store, we force store alignment */
-        /* and will handle load misalignment on val w/ vec_perm */
-        vector unsigned char perm1;
-        vector signed int v1;
-        for (i = 0; (i < dstW) &&
-             (((uintptr_t)dest + i) % 16); i++) {
-            int t = val[i] >> 19;
-            dest[i] = (t < 0) ? 0 : ((t > 255) ? 255 : t);
-        }
-        perm1 = vec_lvsl(i << 2, val);
-        v1    = vec_ld(i << 2, val);
-        for (; i < (dstW - 15); i += 16) {
-            int offset = i << 2;
-            vector signed int v2  = vec_ld(offset + 16, val);
-            vector signed int v3  = vec_ld(offset + 32, val);
-            vector signed int v4  = vec_ld(offset + 48, val);
-            vector signed int v5  = vec_ld(offset + 64, val);
-            vector signed int v12 = vec_perm(v1, v2, perm1);
-            vector signed int v23 = vec_perm(v2, v3, perm1);
-            vector signed int v34 = vec_perm(v3, v4, perm1);
-            vector signed int v45 = vec_perm(v4, v5, perm1);
+#define yuv2planeX_8(d1, d2, l1, src, x, perm, filter) do {     \
+        vector signed short l2  = vec_ld(((x) << 1) + 16, src); \
+        vector signed short ls  = vec_perm(l1, l2, perm);       \
+        vector signed int   i1  = vec_mule(filter, ls);         \
+        vector signed int   i2  = vec_mulo(filter, ls);         \
+        vector signed int   vf1 = vec_mergeh(i1, i2);           \
+        vector signed int   vf2 = vec_mergel(i1, i2);           \
+        d1 = vec_add(d1, vf1);                                  \
+        d2 = vec_add(d2, vf2);                                  \
+        l1 = l2;                                                \
+    } while (0)
 
-            vector signed int vA      = vec_sra(v12, altivec_vectorShiftInt19);
-            vector signed int vB      = vec_sra(v23, altivec_vectorShiftInt19);
-            vector signed int vC      = vec_sra(v34, altivec_vectorShiftInt19);
-            vector signed int vD      = vec_sra(v45, altivec_vectorShiftInt19);
-            vector unsigned short vs1 = vec_packsu(vA, vB);
-            vector unsigned short vs2 = vec_packsu(vC, vD);
-            vector unsigned char vf   = vec_packsu(vs1, vs2);
-            vec_st(vf, i, dest);
-            v1 = v5;
-        }
-    } else { // dest is properly aligned, great
-        for (i = 0; i < (dstW - 15); i += 16) {
-            int offset = i << 2;
-            vector signed int v1      = vec_ld(offset, val);
-            vector signed int v2      = vec_ld(offset + 16, val);
-            vector signed int v3      = vec_ld(offset + 32, val);
-            vector signed int v4      = vec_ld(offset + 48, val);
-            vector signed int v5      = vec_sra(v1, altivec_vectorShiftInt19);
-            vector signed int v6      = vec_sra(v2, altivec_vectorShiftInt19);
-            vector signed int v7      = vec_sra(v3, altivec_vectorShiftInt19);
-            vector signed int v8      = vec_sra(v4, altivec_vectorShiftInt19);
-            vector unsigned short vs1 = vec_packsu(v5, v6);
-            vector unsigned short vs2 = vec_packsu(v7, v8);
-            vector unsigned char vf   = vec_packsu(vs1, vs2);
-            vec_st(vf, i, dest);
-        }
-    }
-    for (; i < dstW; i++) {
-        int t = val[i] >> 19;
-        dest[i] = (t < 0) ? 0 : ((t > 255) ? 255 : t);
-    }
-}
-
-// FIXME remove the usage of scratch buffers.
-static void yuv2planeX_altivec(const int16_t *filter, int filterSize,
-                               const int16_t **src, uint8_t *dest, int dstW,
-                               const uint8_t *dither, int offset)
+static void yuv2planeX_16_altivec(const int16_t *filter, int filterSize,
+                                  const int16_t **src, uint8_t *dest,
+                                  const uint8_t *dither, int offset, int x)
 {
     register int i, j;
-    DECLARE_ALIGNED(16, int, val)[dstW];
+    DECLARE_ALIGNED(16, int, val)[16];
+    vector signed int vo1, vo2, vo3, vo4;
+    vector unsigned short vs1, vs2;
+    vector unsigned char vf;
+    vector unsigned int altivec_vectorShiftInt19 =
+        vec_add(vec_splat_u32(10), vec_splat_u32(9));
 
-    for (i = 0; i < dstW; i++)
-        val[i] = dither[(i + offset) & 7] << 12;
+    for (i = 0; i < 16; i++)
+        val[i] = dither[(x + i + offset) & 7] << 12;
+
+    vo1 = vec_ld(0,  val);
+    vo2 = vec_ld(16, val);
+    vo3 = vec_ld(32, val);
+    vo4 = vec_ld(48, val);
 
     for (j = 0; j < filterSize; j++) {
         vector signed short l1, vLumFilter = vec_ld(j << 1, filter);
@@ -111,36 +70,51 @@
         vLumFilter = vec_perm(vLumFilter, vLumFilter, perm0);
         vLumFilter = vec_splat(vLumFilter, 0); // lumFilter[j] is loaded 8 times in vLumFilter
 
-        perm = vec_lvsl(0, src[j]);
-        l1   = vec_ld(0, src[j]);
+        perm = vec_lvsl(x << 1, src[j]);
+        l1   = vec_ld(x << 1, src[j]);
 
-        for (i = 0; i < (dstW - 7); i += 8) {
-            int offset = i << 2;
-            vector signed short l2 = vec_ld((i << 1) + 16, src[j]);
-
-            vector signed int v1 = vec_ld(offset, val);
-            vector signed int v2 = vec_ld(offset + 16, val);
-
-            vector signed short ls = vec_perm(l1, l2, perm); // lumSrc[j][i] ... lumSrc[j][i+7]
-
-            vector signed int i1 = vec_mule(vLumFilter, ls);
-            vector signed int i2 = vec_mulo(vLumFilter, ls);
-
-            vector signed int vf1 = vec_mergeh(i1, i2);
-            vector signed int vf2 = vec_mergel(i1, i2); // lumSrc[j][i] * lumFilter[j] ... lumSrc[j][i+7] * lumFilter[j]
-
-            vector signed int vo1 = vec_add(v1, vf1);
-            vector signed int vo2 = vec_add(v2, vf2);
-
-            vec_st(vo1, offset, val);
-            vec_st(vo2, offset + 16, val);
-
-            l1 = l2;
-        }
-        for (; i < dstW; i++)
-            val[i] += src[j][i] * filter[j];
+        yuv2planeX_8(vo1, vo2, l1, src[j], x,     perm, vLumFilter);
+        yuv2planeX_8(vo3, vo4, l1, src[j], x + 8, perm, vLumFilter);
     }
-    altivec_packIntArrayToCharArray(val, dest, dstW);
+
+    vo1 = vec_sra(vo1, altivec_vectorShiftInt19);
+    vo2 = vec_sra(vo2, altivec_vectorShiftInt19);
+    vo3 = vec_sra(vo3, altivec_vectorShiftInt19);
+    vo4 = vec_sra(vo4, altivec_vectorShiftInt19);
+    vs1 = vec_packsu(vo1, vo2);
+    vs2 = vec_packsu(vo3, vo4);
+    vf  = vec_packsu(vs1, vs2);
+    vec_st(vf, 0, dest);
+}
+
+static inline void yuv2planeX_u(const int16_t *filter, int filterSize,
+                                const int16_t **src, uint8_t *dest, int dstW,
+                                const uint8_t *dither, int offset, int x)
+{
+    int i, j;
+
+    for (i = x; i < dstW; i++) {
+        int t = dither[(i + offset) & 7] << 12;
+        for (j = 0; j < filterSize; j++)
+            t += src[j][i] * filter[j];
+        dest[i] = av_clip_uint8(t >> 19);
+    }
+}
+
+static void yuv2planeX_altivec(const int16_t *filter, int filterSize,
+                               const int16_t **src, uint8_t *dest, int dstW,
+                               const uint8_t *dither, int offset)
+{
+    int dst_u = -(uintptr_t)dest & 15;
+    int i;
+
+    yuv2planeX_u(filter, filterSize, src, dest, dst_u, dither, offset, 0);
+
+    for (i = dst_u; i < dstW - 15; i += 16)
+        yuv2planeX_16_altivec(filter, filterSize, src, dest + i, dither,
+                              offset, i);
+
+    yuv2planeX_u(filter, filterSize, src, dest, dstW, dither, offset, i);
 }
 
 static void hScale_altivec_real(SwsContext *c, int16_t *dst, int dstW,
@@ -313,7 +287,7 @@
 
 av_cold void ff_sws_init_swScale_altivec(SwsContext *c)
 {
-    enum PixelFormat dstFormat = c->dstFormat;
+    enum AVPixelFormat dstFormat = c->dstFormat;
 
     if (!(av_get_cpu_flags() & AV_CPU_FLAG_ALTIVEC))
         return;
@@ -322,7 +296,7 @@
         c->hyScale = c->hcScale = hScale_altivec_real;
     }
     if (!is16BPS(dstFormat) && !is9_OR_10BPS(dstFormat) &&
-        dstFormat != PIX_FMT_NV12 && dstFormat != PIX_FMT_NV21 &&
+        dstFormat != AV_PIX_FMT_NV12 && dstFormat != AV_PIX_FMT_NV21 &&
         !c->alpPixBuf) {
         c->yuv2planeX = yuv2planeX_altivec;
     }
@@ -331,22 +305,22 @@
      * match what's found in the body of ff_yuv2packedX_altivec() */
     if (!(c->flags & (SWS_BITEXACT | SWS_FULL_CHR_H_INT)) && !c->alpPixBuf) {
         switch (c->dstFormat) {
-        case PIX_FMT_ABGR:
+        case AV_PIX_FMT_ABGR:
             c->yuv2packedX = ff_yuv2abgr_X_altivec;
             break;
-        case PIX_FMT_BGRA:
+        case AV_PIX_FMT_BGRA:
             c->yuv2packedX = ff_yuv2bgra_X_altivec;
             break;
-        case PIX_FMT_ARGB:
+        case AV_PIX_FMT_ARGB:
             c->yuv2packedX = ff_yuv2argb_X_altivec;
             break;
-        case PIX_FMT_RGBA:
+        case AV_PIX_FMT_RGBA:
             c->yuv2packedX = ff_yuv2rgba_X_altivec;
             break;
-        case PIX_FMT_BGR24:
+        case AV_PIX_FMT_BGR24:
             c->yuv2packedX = ff_yuv2bgr24_X_altivec;
             break;
-        case PIX_FMT_RGB24:
+        case AV_PIX_FMT_RGB24:
             c->yuv2packedX = ff_yuv2rgb24_X_altivec;
             break;
         }
diff --git a/libswscale/ppc/yuv2rgb_altivec.c b/libswscale/ppc/yuv2rgb_altivec.c
index ade134d..a8501d9 100644
--- a/libswscale/ppc/yuv2rgb_altivec.c
+++ b/libswscale/ppc/yuv2rgb_altivec.c
@@ -548,41 +548,41 @@
         return NULL;
 
     switch (c->srcFormat) {
-    case PIX_FMT_YUV410P:
-    case PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUV410P:
+    case AV_PIX_FMT_YUV420P:
     /*case IMGFMT_CLPL:        ??? */
-    case PIX_FMT_GRAY8:
-    case PIX_FMT_NV12:
-    case PIX_FMT_NV21:
+    case AV_PIX_FMT_GRAY8:
+    case AV_PIX_FMT_NV12:
+    case AV_PIX_FMT_NV21:
         if ((c->srcH & 0x1) != 0)
             return NULL;
 
         switch (c->dstFormat) {
-        case PIX_FMT_RGB24:
+        case AV_PIX_FMT_RGB24:
             av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space RGB24\n");
             return altivec_yuv2_rgb24;
-        case PIX_FMT_BGR24:
+        case AV_PIX_FMT_BGR24:
             av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space BGR24\n");
             return altivec_yuv2_bgr24;
-        case PIX_FMT_ARGB:
+        case AV_PIX_FMT_ARGB:
             av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space ARGB\n");
             return altivec_yuv2_argb;
-        case PIX_FMT_ABGR:
+        case AV_PIX_FMT_ABGR:
             av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space ABGR\n");
             return altivec_yuv2_abgr;
-        case PIX_FMT_RGBA:
+        case AV_PIX_FMT_RGBA:
             av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space RGBA\n");
             return altivec_yuv2_rgba;
-        case PIX_FMT_BGRA:
+        case AV_PIX_FMT_BGRA:
             av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space BGRA\n");
             return altivec_yuv2_bgra;
         default: return NULL;
         }
         break;
 
-    case PIX_FMT_UYVY422:
+    case AV_PIX_FMT_UYVY422:
         switch (c->dstFormat) {
-        case PIX_FMT_BGR32:
+        case AV_PIX_FMT_BGR32:
             av_log(c, AV_LOG_WARNING, "ALTIVEC: Color Space UYVY -> RGB32\n");
             return altivec_uyvy_rgb32;
         default: return NULL;
@@ -631,7 +631,7 @@
                                                     const int16_t **alpSrc,
                                                     uint8_t *dest,
                                                     int dstW, int dstY,
-                                                    enum PixelFormat target)
+                                                    enum AVPixelFormat target)
 {
     int i, j;
     vector signed short X, X0, X1, Y0, U0, V0, Y1, U1, V1, U, V;
@@ -706,22 +706,22 @@
         B = vec_packclp(B0, B1);
 
         switch (target) {
-        case PIX_FMT_ABGR:
+        case AV_PIX_FMT_ABGR:
             out_abgr(R, G, B, out);
             break;
-        case PIX_FMT_BGRA:
+        case AV_PIX_FMT_BGRA:
             out_bgra(R, G, B, out);
             break;
-        case PIX_FMT_RGBA:
+        case AV_PIX_FMT_RGBA:
             out_rgba(R, G, B, out);
             break;
-        case PIX_FMT_ARGB:
+        case AV_PIX_FMT_ARGB:
             out_argb(R, G, B, out);
             break;
-        case PIX_FMT_RGB24:
+        case AV_PIX_FMT_RGB24:
             out_rgb24(R, G, B, out);
             break;
-        case PIX_FMT_BGR24:
+        case AV_PIX_FMT_BGR24:
             out_bgr24(R, G, B, out);
             break;
         default:
@@ -798,22 +798,22 @@
 
         nout = (vector unsigned char *) scratch;
         switch (target) {
-        case PIX_FMT_ABGR:
+        case AV_PIX_FMT_ABGR:
             out_abgr(R, G, B, nout);
             break;
-        case PIX_FMT_BGRA:
+        case AV_PIX_FMT_BGRA:
             out_bgra(R, G, B, nout);
             break;
-        case PIX_FMT_RGBA:
+        case AV_PIX_FMT_RGBA:
             out_rgba(R, G, B, nout);
             break;
-        case PIX_FMT_ARGB:
+        case AV_PIX_FMT_ARGB:
             out_argb(R, G, B, nout);
             break;
-        case PIX_FMT_RGB24:
+        case AV_PIX_FMT_RGB24:
             out_rgb24(R, G, B, nout);
             break;
-        case PIX_FMT_BGR24:
+        case AV_PIX_FMT_BGR24:
             out_bgr24(R, G, B, nout);
             break;
         default:
@@ -846,9 +846,9 @@
                            dest, dstW, dstY, pixfmt);                   \
 }
 
-YUV2PACKEDX_WRAPPER(abgr,  PIX_FMT_ABGR);
-YUV2PACKEDX_WRAPPER(bgra,  PIX_FMT_BGRA);
-YUV2PACKEDX_WRAPPER(argb,  PIX_FMT_ARGB);
-YUV2PACKEDX_WRAPPER(rgba,  PIX_FMT_RGBA);
-YUV2PACKEDX_WRAPPER(rgb24, PIX_FMT_RGB24);
-YUV2PACKEDX_WRAPPER(bgr24, PIX_FMT_BGR24);
+YUV2PACKEDX_WRAPPER(abgr,  AV_PIX_FMT_ABGR);
+YUV2PACKEDX_WRAPPER(bgra,  AV_PIX_FMT_BGRA);
+YUV2PACKEDX_WRAPPER(argb,  AV_PIX_FMT_ARGB);
+YUV2PACKEDX_WRAPPER(rgba,  AV_PIX_FMT_RGBA);
+YUV2PACKEDX_WRAPPER(rgb24, AV_PIX_FMT_RGB24);
+YUV2PACKEDX_WRAPPER(bgr24, AV_PIX_FMT_BGR24);
diff --git a/libswscale/ppc/yuv2yuv_altivec.c b/libswscale/ppc/yuv2yuv_altivec.c
index af78782..60d50a7 100644
--- a/libswscale/ppc/yuv2yuv_altivec.c
+++ b/libswscale/ppc/yuv2yuv_altivec.c
@@ -182,13 +182,13 @@
 void ff_swscale_get_unscaled_altivec(SwsContext *c)
 {
     if ((av_get_cpu_flags() & AV_CPU_FLAG_ALTIVEC) && !(c->srcW & 15) &&
-        !(c->flags & SWS_BITEXACT) && c->srcFormat == PIX_FMT_YUV420P) {
-        enum PixelFormat dstFormat = c->dstFormat;
+        !(c->flags & SWS_BITEXACT) && c->srcFormat == AV_PIX_FMT_YUV420P) {
+        enum AVPixelFormat dstFormat = c->dstFormat;
 
         // unscaled YV12 -> packed YUV, we want speed
-        if (dstFormat == PIX_FMT_YUYV422)
+        if (dstFormat == AV_PIX_FMT_YUYV422)
             c->swScale = yv12toyuy2_unscaled_altivec;
-        else if (dstFormat == PIX_FMT_UYVY422)
+        else if (dstFormat == AV_PIX_FMT_UYVY422)
             c->swScale = yv12touyvy_unscaled_altivec;
     }
 }
diff --git a/libswscale/rgb2rgb.c b/libswscale/rgb2rgb.c
index 321e5ff..1233a1d 100644
--- a/libswscale/rgb2rgb.c
+++ b/libswscale/rgb2rgb.c
@@ -122,7 +122,7 @@
 /*
  * RGB15->RGB16 original by Strepto/Astral
  * ported to gcc & bugfixed : A'rpi
- * MMX2, 3DNOW optimization by Nick Kurshev
+ * MMXEXT, 3DNOW optimization by Nick Kurshev
  * 32-bit C version, and and&add trick by Michael Niedermayer
  */
 
diff --git a/libswscale/rgb2rgb_template.c b/libswscale/rgb2rgb_template.c
index c05cdc8..8753594 100644
--- a/libswscale/rgb2rgb_template.c
+++ b/libswscale/rgb2rgb_template.c
@@ -77,7 +77,7 @@
 /*
  * original by Strepto/Astral
  * ported to gcc & bugfixed: A'rpi
- * MMX2, 3DNOW optimization by Nick Kurshev
+ * MMXEXT, 3DNOW optimization by Nick Kurshev
  * 32-bit C version, and and&add trick by Michael Niedermayer
  */
 static inline void rgb15to16_c(const uint8_t *src, uint8_t *dst, int src_size)
@@ -353,9 +353,9 @@
         const uint8_t *yc = ysrc, *uc = usrc, *vc = vsrc;
         for (i = 0; i < chromWidth; i += 2) {
             uint64_t k = yc[0] + (uc[0] << 8) +
-                         (yc[1] << 16) + (vc[0] << 24);
+                         (yc[1] << 16) + (unsigned)(vc[0] << 24);
             uint64_t l = yc[2] + (uc[1] << 8) +
-                         (yc[3] << 16) + (vc[1] << 24);
+                         (yc[3] << 16) + (unsigned)(vc[1] << 24);
             *ldst++ = k + (l << 32);
             yc     += 4;
             uc     += 2;
@@ -417,9 +417,9 @@
         const uint8_t *yc = ysrc, *uc = usrc, *vc = vsrc;
         for (i = 0; i < chromWidth; i += 2) {
             uint64_t k = uc[0] + (yc[0] << 8) +
-                         (vc[0] << 16) + (yc[1] << 24);
+                         (vc[0] << 16) + (unsigned)(yc[1] << 24);
             uint64_t l = uc[1] + (yc[2] << 8) +
-                         (vc[1] << 16) + (yc[3] << 24);
+                         (vc[1] << 16) + (unsigned)(yc[3] << 24);
             *ldst++ = k + (l << 32);
             yc     += 4;
             uc     += 2;
diff --git a/libswscale/sparc/yuv2rgb_vis.c b/libswscale/sparc/yuv2rgb_vis.c
index bb9ab22..ed00837 100644
--- a/libswscale/sparc/yuv2rgb_vis.c
+++ b/libswscale/sparc/yuv2rgb_vis.c
@@ -199,11 +199,11 @@
     c->sparc_coeffs[3] = (((int16_t)c->vOffset * (int16_t)c->vgCoeff >> 11) & 0xffff) * 0x0001000100010001ULL;
     c->sparc_coeffs[4] = (((int16_t)c->vOffset * (int16_t)c->vrCoeff >> 11) & 0xffff) * 0x0001000100010001ULL;
 
-    if (c->dstFormat == PIX_FMT_RGB32 && c->srcFormat == PIX_FMT_YUV422P && (c->dstW & 7) == 0) {
+    if (c->dstFormat == AV_PIX_FMT_RGB32 && c->srcFormat == AV_PIX_FMT_YUV422P && (c->dstW & 7) == 0) {
         av_log(c, AV_LOG_INFO,
                "SPARC VIS accelerated YUV422P -> RGB32 (WARNING: alpha value is wrong)\n");
         return vis_422P_ARGB32;
-    } else if (c->dstFormat == PIX_FMT_RGB32 && c->srcFormat == PIX_FMT_YUV420P && (c->dstW & 7) == 0) {
+    } else if (c->dstFormat == AV_PIX_FMT_RGB32 && c->srcFormat == AV_PIX_FMT_YUV420P && (c->dstW & 7) == 0) {
         av_log(c, AV_LOG_INFO,
                "SPARC VIS accelerated YUV420P -> RGB32 (WARNING: alpha value is wrong)\n");
         return vis_420P_ARGB32;
diff --git a/libswscale/swscale-test.c b/libswscale/swscale-test.c
index ef6c55c..40dec54 100644
--- a/libswscale/swscale-test.c
+++ b/libswscale/swscale-test.c
@@ -36,20 +36,20 @@
 /* HACK Duplicated from swscale_internal.h.
  * Should be removed when a cleaner pixel format system exists. */
 #define isGray(x)                      \
-    ((x) == PIX_FMT_GRAY8       ||     \
-     (x) == PIX_FMT_Y400A       ||     \
-     (x) == PIX_FMT_GRAY16BE    ||     \
-     (x) == PIX_FMT_GRAY16LE)
+    ((x) == AV_PIX_FMT_GRAY8       ||     \
+     (x) == AV_PIX_FMT_Y400A       ||     \
+     (x) == AV_PIX_FMT_GRAY16BE    ||     \
+     (x) == AV_PIX_FMT_GRAY16LE)
 #define hasChroma(x)                   \
     (!(isGray(x)                ||     \
-       (x) == PIX_FMT_MONOBLACK ||     \
-       (x) == PIX_FMT_MONOWHITE))
+       (x) == AV_PIX_FMT_MONOBLACK ||     \
+       (x) == AV_PIX_FMT_MONOWHITE))
 #define isALPHA(x)                     \
-    ((x) == PIX_FMT_BGR32   ||         \
-     (x) == PIX_FMT_BGR32_1 ||         \
-     (x) == PIX_FMT_RGB32   ||         \
-     (x) == PIX_FMT_RGB32_1 ||         \
-     (x) == PIX_FMT_YUVA420P)
+    ((x) == AV_PIX_FMT_BGR32   ||         \
+     (x) == AV_PIX_FMT_BGR32_1 ||         \
+     (x) == AV_PIX_FMT_RGB32   ||         \
+     (x) == AV_PIX_FMT_RGB32_1 ||         \
+     (x) == AV_PIX_FMT_YUVA420P)
 
 static uint64_t getSSD(uint8_t *src1, uint8_t *src2, int stride1,
                        int stride2, int w, int h)
@@ -77,17 +77,20 @@
 // 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,
+                  enum AVPixelFormat srcFormat, enum AVPixelFormat dstFormat,
                   int srcW, int srcH, int dstW, int dstH, int flags,
                   struct Results *r)
 {
-    static enum PixelFormat cur_srcFormat;
+    const AVPixFmtDescriptor *desc_yuva420p = av_pix_fmt_desc_get(AV_PIX_FMT_YUVA420P);
+    const AVPixFmtDescriptor *desc_src      = av_pix_fmt_desc_get(srcFormat);
+    const AVPixFmtDescriptor *desc_dst      = av_pix_fmt_desc_get(dstFormat);
+    static enum AVPixelFormat 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 dstStride[4];
+    int dstStride[4] = {0};
     int i;
     uint64_t ssdY, ssdU = 0, ssdV = 0, ssdA = 0;
     struct SwsContext *dstContext = NULL, *outContext = NULL;
@@ -112,12 +115,12 @@
                 goto end;
             }
         }
-        srcContext = sws_getContext(w, h, PIX_FMT_YUVA420P, srcW, srcH,
+        srcContext = sws_getContext(w, h, AV_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);
+                    desc_yuva420p->name,
+                    desc_src->name);
             res = -1;
             goto end;
         }
@@ -152,15 +155,14 @@
                                 flags, NULL, NULL, NULL);
     if (!dstContext) {
         fprintf(stderr, "Failed to get %s ---> %s\n",
-                av_pix_fmt_descriptors[srcFormat].name,
-                av_pix_fmt_descriptors[dstFormat].name);
+                desc_src->name, desc_dst->name);
         res = -1;
         goto end;
     }
 
     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,
+           desc_src->name, srcW, srcH,
+           desc_dst->name, dstW, dstH,
            flags);
     fflush(stdout);
 
@@ -187,12 +189,12 @@
             }
         }
         outContext = sws_getContext(dstW, dstH, dstFormat, w, h,
-                                    PIX_FMT_YUVA420P, SWS_BILINEAR,
+                                    AV_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);
+                    desc_dst->name,
+                    desc_yuva420p->name);
             res = -1;
             goto end;
         }
@@ -235,8 +237,8 @@
 }
 
 static void selfTest(uint8_t *ref[4], int refStride[4], int w, int h,
-                     enum PixelFormat srcFormat_in,
-                     enum PixelFormat dstFormat_in)
+                     enum AVPixelFormat srcFormat_in,
+                     enum AVPixelFormat dstFormat_in)
 {
     const int flags[] = { SWS_FAST_BILINEAR, SWS_BILINEAR, SWS_BICUBIC,
                           SWS_X, SWS_POINT, SWS_AREA, 0 };
@@ -244,16 +246,19 @@
     const int srcH   = h;
     const int dstW[] = { srcW - srcW / 3, srcW, srcW + srcW / 3, 0 };
     const int dstH[] = { srcH - srcH / 3, srcH, srcH + srcH / 3, 0 };
-    enum PixelFormat srcFormat, dstFormat;
+    enum AVPixelFormat srcFormat, dstFormat;
+    const AVPixFmtDescriptor *desc_src, *desc_dst;
 
-    for (srcFormat = srcFormat_in != PIX_FMT_NONE ? srcFormat_in : 0;
-         srcFormat < PIX_FMT_NB; srcFormat++) {
+    for (srcFormat = srcFormat_in != AV_PIX_FMT_NONE ? srcFormat_in : 0;
+         srcFormat < AV_PIX_FMT_NB; srcFormat++) {
         if (!sws_isSupportedInput(srcFormat) ||
             !sws_isSupportedOutput(srcFormat))
             continue;
 
-        for (dstFormat = dstFormat_in != PIX_FMT_NONE ? dstFormat_in : 0;
-             dstFormat < PIX_FMT_NB; dstFormat++) {
+        desc_src = av_pix_fmt_desc_get(srcFormat);
+
+        for (dstFormat = dstFormat_in != AV_PIX_FMT_NONE ? dstFormat_in : 0;
+             dstFormat < AV_PIX_FMT_NB; dstFormat++) {
             int i, j, k;
             int res = 0;
 
@@ -261,9 +266,9 @@
                 !sws_isSupportedOutput(dstFormat))
                 continue;
 
-            printf("%s -> %s\n",
-                   av_pix_fmt_descriptors[srcFormat].name,
-                   av_pix_fmt_descriptors[dstFormat].name);
+            desc_dst = av_pix_fmt_desc_get(dstFormat);
+
+            printf("%s -> %s\n", desc_src->name, desc_dst->name);
             fflush(stdout);
 
             for (k = 0; flags[k] && !res; k++)
@@ -273,26 +278,26 @@
                                      srcFormat, dstFormat,
                                      srcW, srcH, dstW[i], dstH[j], flags[k],
                                      NULL);
-            if (dstFormat_in != PIX_FMT_NONE)
+            if (dstFormat_in != AV_PIX_FMT_NONE)
                 break;
         }
-        if (srcFormat_in != PIX_FMT_NONE)
+        if (srcFormat_in != AV_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)
+                    enum AVPixelFormat srcFormat_in,
+                    enum AVPixelFormat dstFormat_in)
 {
     char buf[256];
 
     while (fgets(buf, sizeof(buf), fp)) {
         struct Results r;
-        enum PixelFormat srcFormat;
+        enum AVPixelFormat srcFormat;
         char srcStr[12];
         int srcW, srcH;
-        enum PixelFormat dstFormat;
+        enum AVPixelFormat dstFormat;
         char dstStr[12];
         int dstW, dstH;
         int flags;
@@ -311,12 +316,13 @@
         srcFormat = av_get_pix_fmt(srcStr);
         dstFormat = av_get_pix_fmt(dstStr);
 
-        if (srcFormat == PIX_FMT_NONE || dstFormat == PIX_FMT_NONE) {
+        if (srcFormat == AV_PIX_FMT_NONE || dstFormat == AV_PIX_FMT_NONE ||
+            srcW > 8192U || srcH > 8192U || dstW > 8192U || dstH > 8192U) {
             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))
+        if ((srcFormat_in != AV_PIX_FMT_NONE && srcFormat_in != srcFormat) ||
+            (dstFormat_in != AV_PIX_FMT_NONE && dstFormat_in != dstFormat))
             continue;
         if (ret != 12) {
             printf("%s", buf);
@@ -337,8 +343,8 @@
 
 int main(int argc, char **argv)
 {
-    enum PixelFormat srcFormat = PIX_FMT_NONE;
-    enum PixelFormat dstFormat = PIX_FMT_NONE;
+    enum AVPixelFormat srcFormat = AV_PIX_FMT_NONE;
+    enum AVPixelFormat dstFormat = AV_PIX_FMT_NONE;
     uint8_t *rgb_data   = av_malloc(W * H * 4);
     uint8_t *rgb_src[4] = { rgb_data, NULL, NULL, NULL };
     int rgb_stride[4]   = { 4 * W, 0, 0, 0 };
@@ -350,43 +356,29 @@
     AVLFG rand;
     int res = -1;
     int i;
+    FILE *fp = NULL;
 
     if (!rgb_data || !data)
         return -1;
 
-    sws = sws_getContext(W / 12, H / 12, PIX_FMT_RGB32, W, H,
-                         PIX_FMT_YUVA420P, SWS_BILINEAR, NULL, NULL, NULL);
-
-    av_lfg_init(&rand, 1);
-
-    for (y = 0; y < H; y++)
-        for (x = 0; x < W * 4; x++)
-            rgb_data[ x + y * 4 * W] = av_lfg_get(&rand);
-    sws_scale(sws, rgb_src, rgb_stride, 0, H, src, stride);
-    sws_freeContext(sws);
-    av_free(rgb_data);
-
     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");
+            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) {
+            if (srcFormat == AV_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) {
+            if (dstFormat == AV_PIX_FMT_NONE) {
                 fprintf(stderr, "invalid pixel format %s\n", argv[i + 1]);
                 return -1;
             }
@@ -397,9 +389,25 @@
         }
     }
 
-    selfTest(src, stride, W, H, srcFormat, dstFormat);
-end:
-    res = 0;
+    sws = sws_getContext(W / 12, H / 12, AV_PIX_FMT_RGB32, W, H,
+                         AV_PIX_FMT_YUVA420P, SWS_BILINEAR, NULL, NULL, NULL);
+
+    av_lfg_init(&rand, 1);
+
+    for (y = 0; y < H; y++)
+        for (x = 0; x < W * 4; x++)
+            rgb_data[ x + y * 4 * W] = av_lfg_get(&rand);
+    sws_scale(sws, rgb_src, rgb_stride, 0, H, src, stride);
+    sws_freeContext(sws);
+    av_free(rgb_data);
+
+    if(fp) {
+        res = fileTest(src, stride, W, H, fp, srcFormat, dstFormat);
+        fclose(fp);
+    } else {
+        selfTest(src, stride, W, H, srcFormat, dstFormat);
+        res = 0;
+    }
 error:
     av_free(data);
 
diff --git a/libswscale/swscale.c b/libswscale/swscale.c
index 00a8761..632e85a 100644
--- a/libswscale/swscale.c
+++ b/libswscale/swscale.c
@@ -66,13 +66,14 @@
                            const uint8_t *_src, const int16_t *filter,
                            const int32_t *filterPos, int filterSize)
 {
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(c->srcFormat);
     int i;
     int32_t *dst        = (int32_t *) _dst;
     const uint16_t *src = (const uint16_t *) _src;
-    int bits            = av_pix_fmt_descriptors[c->srcFormat].comp[0].depth_minus1;
+    int bits            = desc->comp[0].depth_minus1;
     int sh              = bits - 4;
 
-    if((isAnyRGB(c->srcFormat) || c->srcFormat==PIX_FMT_PAL8) && av_pix_fmt_descriptors[c->srcFormat].comp[0].depth_minus1<15)
+    if((isAnyRGB(c->srcFormat) || c->srcFormat==AV_PIX_FMT_PAL8) && desc->comp[0].depth_minus1<15)
         sh= 9;
 
     for (i = 0; i < dstW; i++) {
@@ -92,12 +93,13 @@
                            const uint8_t *_src, const int16_t *filter,
                            const int32_t *filterPos, int filterSize)
 {
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(c->srcFormat);
     int i;
     const uint16_t *src = (const uint16_t *) _src;
-    int sh              = av_pix_fmt_descriptors[c->srcFormat].comp[0].depth_minus1;
+    int sh              = desc->comp[0].depth_minus1;
 
     if(sh<15)
-        sh= isAnyRGB(c->srcFormat) || c->srcFormat==PIX_FMT_PAL8 ? 13 : av_pix_fmt_descriptors[c->srcFormat].comp[0].depth_minus1;
+        sh= isAnyRGB(c->srcFormat) || c->srcFormat==AV_PIX_FMT_PAL8 ? 13 : desc->comp[0].depth_minus1;
 
     for (i = 0; i < dstW; i++) {
         int j;
@@ -339,7 +341,7 @@
     const int chrSrcW                = c->chrSrcW;
     const int lumXInc                = c->lumXInc;
     const int chrXInc                = c->chrXInc;
-    const enum PixelFormat dstFormat = c->dstFormat;
+    const enum AVPixelFormat dstFormat = c->dstFormat;
     const int flags                  = c->flags;
     int32_t *vLumFilterPos           = c->vLumFilterPos;
     int32_t *vChrFilterPos           = c->vChrFilterPos;
@@ -657,9 +659,18 @@
             }
         }
     }
+    if (isPlanar(dstFormat) && isALPHA(dstFormat) && !alpPixBuf) {
+        int length = dstW;
+        int height = dstY - lastDstY;
 
-    if (isPlanar(dstFormat) && isALPHA(dstFormat) && !alpPixBuf)
-        fillPlane(dst[3], dstStride[3], dstW, dstY - lastDstY, lastDstY, 255);
+        if (is16BPS(dstFormat) || isNBPS(dstFormat)) {
+            const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(dstFormat);
+            fillPlane16(dst[3], dstStride[3], length, height, lastDstY,
+                    1, desc->comp[3].depth_minus1,
+                    isBE(dstFormat));
+        } else
+            fillPlane(dst[3], dstStride[3], length, height, lastDstY, 255);
+    }
 
 #if HAVE_MMXEXT_INLINE
     if (av_get_cpu_flags() & AV_CPU_FLAG_MMXEXT)
@@ -679,7 +690,7 @@
 
 static av_cold void sws_init_swScale_c(SwsContext *c)
 {
-    enum PixelFormat srcFormat = c->srcFormat;
+    enum AVPixelFormat srcFormat = c->srcFormat;
 
     ff_sws_init_output_funcs(c, &c->yuv2plane1, &c->yuv2planeX,
                              &c->yuv2nv12cX, &c->yuv2packed1,
@@ -724,7 +735,7 @@
     }
 
     if (!(isGray(srcFormat) || isGray(c->dstFormat) ||
-          srcFormat == PIX_FMT_MONOBLACK || srcFormat == PIX_FMT_MONOWHITE))
+          srcFormat == AV_PIX_FMT_MONOBLACK || srcFormat == AV_PIX_FMT_MONOWHITE))
         c->needs_hcscale = 1;
 }
 
@@ -752,10 +763,10 @@
     }
 }
 
-static int check_image_pointers(const uint8_t * const data[4], enum PixelFormat pix_fmt,
+static int check_image_pointers(const uint8_t * const data[4], enum AVPixelFormat pix_fmt,
                                 const int linesizes[4])
 {
-    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
     int i;
 
     for (i = 0; i < 4; i++) {
@@ -806,28 +817,28 @@
     if (usePal(c->srcFormat)) {
         for (i = 0; i < 256; i++) {
             int p, r, g, b, y, u, v, a = 0xff;
-            if (c->srcFormat == PIX_FMT_PAL8) {
+            if (c->srcFormat == AV_PIX_FMT_PAL8) {
                 p = ((const uint32_t *)(srcSlice[1]))[i];
                 a = (p >> 24) & 0xFF;
                 r = (p >> 16) & 0xFF;
                 g = (p >>  8) & 0xFF;
                 b =  p        & 0xFF;
-            } else if (c->srcFormat == PIX_FMT_RGB8) {
+            } else if (c->srcFormat == AV_PIX_FMT_RGB8) {
                 r = ( i >> 5     ) * 36;
                 g = ((i >> 2) & 7) * 36;
                 b = ( i       & 3) * 85;
-            } else if (c->srcFormat == PIX_FMT_BGR8) {
+            } else if (c->srcFormat == AV_PIX_FMT_BGR8) {
                 b = ( i >> 6     ) * 85;
                 g = ((i >> 3) & 7) * 36;
                 r = ( i       & 7) * 36;
-            } else if (c->srcFormat == PIX_FMT_RGB4_BYTE) {
+            } else if (c->srcFormat == AV_PIX_FMT_RGB4_BYTE) {
                 r = ( i >> 3     ) * 255;
                 g = ((i >> 1) & 3) * 85;
                 b = ( i       & 1) * 255;
-            } else if (c->srcFormat == PIX_FMT_GRAY8 || c->srcFormat == PIX_FMT_GRAY8A) {
+            } else if (c->srcFormat == AV_PIX_FMT_GRAY8 || c->srcFormat == AV_PIX_FMT_GRAY8A) {
                 r = g = b = i;
             } else {
-                av_assert1(c->srcFormat == PIX_FMT_BGR4_BYTE);
+                av_assert1(c->srcFormat == AV_PIX_FMT_BGR4_BYTE);
                 b = ( i >> 3     ) * 255;
                 g = ((i >> 1) & 3) * 85;
                 r = ( i       & 1) * 255;
@@ -846,33 +857,33 @@
             y = av_clip_uint8((RY * r + GY * g + BY * b + ( 33 << (RGB2YUV_SHIFT - 1))) >> RGB2YUV_SHIFT);
             u = av_clip_uint8((RU * r + GU * g + BU * b + (257 << (RGB2YUV_SHIFT - 1))) >> RGB2YUV_SHIFT);
             v = av_clip_uint8((RV * r + GV * g + BV * b + (257 << (RGB2YUV_SHIFT - 1))) >> RGB2YUV_SHIFT);
-            c->pal_yuv[i]= y + (u<<8) + (v<<16) + (a<<24);
+            c->pal_yuv[i]= y + (u<<8) + (v<<16) + ((unsigned)a<<24);
 
             switch (c->dstFormat) {
-            case PIX_FMT_BGR32:
+            case AV_PIX_FMT_BGR32:
 #if !HAVE_BIGENDIAN
-            case PIX_FMT_RGB24:
+            case AV_PIX_FMT_RGB24:
 #endif
-                c->pal_rgb[i]=  r + (g<<8) + (b<<16) + (a<<24);
+                c->pal_rgb[i]=  r + (g<<8) + (b<<16) + ((unsigned)a<<24);
                 break;
-            case PIX_FMT_BGR32_1:
+            case AV_PIX_FMT_BGR32_1:
 #if HAVE_BIGENDIAN
-            case PIX_FMT_BGR24:
+            case AV_PIX_FMT_BGR24:
 #endif
-                c->pal_rgb[i]= a + (r<<8) + (g<<16) + (b<<24);
+                c->pal_rgb[i]= a + (r<<8) + (g<<16) + ((unsigned)b<<24);
                 break;
-            case PIX_FMT_RGB32_1:
+            case AV_PIX_FMT_RGB32_1:
 #if HAVE_BIGENDIAN
-            case PIX_FMT_RGB24:
+            case AV_PIX_FMT_RGB24:
 #endif
-                c->pal_rgb[i]= a + (b<<8) + (g<<16) + (r<<24);
+                c->pal_rgb[i]= a + (b<<8) + (g<<16) + ((unsigned)r<<24);
                 break;
-            case PIX_FMT_RGB32:
+            case AV_PIX_FMT_RGB32:
 #if !HAVE_BIGENDIAN
-            case PIX_FMT_BGR24:
+            case AV_PIX_FMT_BGR24:
 #endif
             default:
-                c->pal_rgb[i]=  b + (g<<8) + (r<<16) + (a<<24);
+                c->pal_rgb[i]=  b + (g<<8) + (r<<16) + ((unsigned)a<<24);
             }
         }
     }
diff --git a/libswscale/swscale.h b/libswscale/swscale.h
index a9e803d..5189787 100644
--- a/libswscale/swscale.h
+++ b/libswscale/swscale.h
@@ -85,9 +85,7 @@
  */
 #define SWS_CPU_CAPS_MMX      0x80000000
 #define SWS_CPU_CAPS_MMXEXT   0x20000000
-#if LIBSWSCALE_VERSION_MAJOR < 3
 #define SWS_CPU_CAPS_MMX2     0x20000000
-#endif
 #define SWS_CPU_CAPS_3DNOW    0x40000000
 #define SWS_CPU_CAPS_ALTIVEC  0x10000000
 #define SWS_CPU_CAPS_BFIN     0x01000000
@@ -115,13 +113,13 @@
 
 // when used for filters they must have an odd number of elements
 // coeffs cannot be shared between vectors
-typedef struct {
+typedef struct SwsVector {
     double *coeff;              ///< pointer to the list of coefficients
     int length;                 ///< number of coefficients in the vector
 } SwsVector;
 
 // vectors can be shared
-typedef struct {
+typedef struct SwsFilter {
     SwsVector *lumH;
     SwsVector *lumV;
     SwsVector *chrH;
@@ -134,13 +132,13 @@
  * Return a positive value if pix_fmt is a supported input format, 0
  * otherwise.
  */
-int sws_isSupportedInput(enum PixelFormat pix_fmt);
+int sws_isSupportedInput(enum AVPixelFormat pix_fmt);
 
 /**
  * Return a positive value if pix_fmt is a supported output format, 0
  * otherwise.
  */
-int sws_isSupportedOutput(enum PixelFormat pix_fmt);
+int sws_isSupportedOutput(enum AVPixelFormat pix_fmt);
 
 /**
  * Allocate an empty SwsContext. This must be filled and passed to
@@ -180,8 +178,8 @@
  *       written
  * @deprecated Use sws_getCachedContext() instead.
  */
-struct SwsContext *sws_getContext(int srcW, int srcH, enum PixelFormat srcFormat,
-                                  int dstW, int dstH, enum PixelFormat dstFormat,
+struct SwsContext *sws_getContext(int srcW, int srcH, enum AVPixelFormat srcFormat,
+                                  int dstW, int dstH, enum AVPixelFormat dstFormat,
                                   int flags, SwsFilter *srcFilter,
                                   SwsFilter *dstFilter, const double *param);
 #endif
@@ -307,8 +305,8 @@
  * are assumed to remain the same.
  */
 struct SwsContext *sws_getCachedContext(struct SwsContext *context,
-                                        int srcW, int srcH, enum PixelFormat srcFormat,
-                                        int dstW, int dstH, enum PixelFormat dstFormat,
+                                        int srcW, int srcH, enum AVPixelFormat srcFormat,
+                                        int dstW, int dstH, enum AVPixelFormat dstFormat,
                                         int flags, SwsFilter *srcFilter,
                                         SwsFilter *dstFilter, const double *param);
 
diff --git a/libswscale/swscale_internal.h b/libswscale/swscale_internal.h
index 21b37ce..6a942d6 100644
--- a/libswscale/swscale_internal.h
+++ b/libswscale/swscale_internal.h
@@ -27,8 +27,10 @@
 #include <altivec.h>
 #endif
 
+#include "libavutil/avassert.h"
 #include "libavutil/avutil.h"
 #include "libavutil/common.h"
+#include "libavutil/intreadwrite.h"
 #include "libavutil/log.h"
 #include "libavutil/pixfmt.h"
 #include "libavutil/pixdesc.h"
@@ -242,8 +244,8 @@
     int chrDstH;                  ///< Height of destination chroma     planes.
     int lumXInc, chrXInc;
     int lumYInc, chrYInc;
-    enum PixelFormat dstFormat;   ///< Destination pixel format.
-    enum PixelFormat srcFormat;   ///< Source      pixel format.
+    enum AVPixelFormat dstFormat; ///< Destination pixel format.
+    enum AVPixelFormat srcFormat; ///< Source      pixel format.
     int dstFormatBpp;             ///< Number of bits per pixel of the destination pixel format.
     int srcFormatBpp;             ///< Number of bits per pixel of the source      pixel format.
     int dstBpc, srcBpc;
@@ -310,12 +312,12 @@
     int vChrFilterSize;           ///< Vertical   filter size for chroma     pixels.
     //@}
 
-    int lumMmx2FilterCodeSize;    ///< Runtime-generated MMX2 horizontal fast bilinear scaler code size for luma/alpha planes.
-    int chrMmx2FilterCodeSize;    ///< Runtime-generated MMX2 horizontal fast bilinear scaler code size for chroma     planes.
-    uint8_t *lumMmx2FilterCode;   ///< Runtime-generated MMX2 horizontal fast bilinear scaler code for luma/alpha planes.
-    uint8_t *chrMmx2FilterCode;   ///< Runtime-generated MMX2 horizontal fast bilinear scaler code for chroma     planes.
+    int lumMmxextFilterCodeSize;  ///< Runtime-generated MMXEXT horizontal fast bilinear scaler code size for luma/alpha planes.
+    int chrMmxextFilterCodeSize;  ///< Runtime-generated MMXEXT horizontal fast bilinear scaler code size for chroma planes.
+    uint8_t *lumMmxextFilterCode; ///< Runtime-generated MMXEXT horizontal fast bilinear scaler code for luma/alpha planes.
+    uint8_t *chrMmxextFilterCode; ///< Runtime-generated MMXEXT horizontal fast bilinear scaler code for chroma planes.
 
-    int canMMX2BeUsed;
+    int canMMXEXTBeUsed;
 
     int dstY;                     ///< Last destination vertical line output from last slice.
     int flags;                    ///< Flags passed by the user to select scaler algorithm, optimizations, subsampling, etc...
@@ -552,146 +554,188 @@
  * @deprecated Use av_get_pix_fmt_name() instead.
  */
 attribute_deprecated
-const char *sws_format_name(enum PixelFormat format);
+const char *sws_format_name(enum AVPixelFormat format);
 #endif
 
-#define is16BPS(x) \
-    (av_pix_fmt_descriptors[x].comp[0].depth_minus1 == 15)
+static av_always_inline int is16BPS(enum AVPixelFormat pix_fmt)
+{
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
+    av_assert0(desc);
+    return desc->comp[0].depth_minus1 == 15;
+}
 
-#define is9_OR_10BPS(x) \
-    (av_pix_fmt_descriptors[x].comp[0].depth_minus1 >= 8 && \
-     av_pix_fmt_descriptors[x].comp[0].depth_minus1 <= 13)
+static av_always_inline int is9_OR_10BPS(enum AVPixelFormat pix_fmt)
+{
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
+    av_assert0(desc);
+    return desc->comp[0].depth_minus1 >= 8 && desc->comp[0].depth_minus1 <= 13;
+}
 
 #define isNBPS(x) is9_OR_10BPS(x)
 
-#define isBE(x) \
-    (av_pix_fmt_descriptors[x].flags & PIX_FMT_BE)
+static av_always_inline int isBE(enum AVPixelFormat pix_fmt)
+{
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
+    av_assert0(desc);
+    return desc->flags & PIX_FMT_BE;
+}
 
-#define isYUV(x) \
-    (!(av_pix_fmt_descriptors[x].flags & PIX_FMT_RGB) && \
-     av_pix_fmt_descriptors[x].nb_components >= 2)
+static av_always_inline int isYUV(enum AVPixelFormat pix_fmt)
+{
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
+    av_assert0(desc);
+    return !(desc->flags & PIX_FMT_RGB) && desc->nb_components >= 2;
+}
 
-#define isPlanarYUV(x) \
-    ((av_pix_fmt_descriptors[x].flags & PIX_FMT_PLANAR) && \
-     isYUV(x))
+static av_always_inline int isPlanarYUV(enum AVPixelFormat pix_fmt)
+{
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
+    av_assert0(desc);
+    return ((desc->flags & PIX_FMT_PLANAR) && isYUV(pix_fmt));
+}
 
-#define isRGB(x) \
-    (av_pix_fmt_descriptors[x].flags & PIX_FMT_RGB)
+static av_always_inline int isRGB(enum AVPixelFormat pix_fmt)
+{
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
+    av_assert0(desc);
+    return (desc->flags & PIX_FMT_RGB);
+}
+
 #if 0 // FIXME
 #define isGray(x) \
-    (!(av_pix_fmt_descriptors[x].flags & PIX_FMT_PAL) && \
-     av_pix_fmt_descriptors[x].nb_components <= 2)
+    (!(av_pix_fmt_desc_get(x)->flags & PIX_FMT_PAL) && \
+     av_pix_fmt_desc_get(x)->nb_components <= 2)
 #else
 #define isGray(x)                      \
-    ((x) == PIX_FMT_GRAY8       ||     \
-     (x) == PIX_FMT_Y400A       ||     \
-     (x) == PIX_FMT_GRAY16BE    ||     \
-     (x) == PIX_FMT_GRAY16LE)
+    ((x) == AV_PIX_FMT_GRAY8       ||  \
+     (x) == AV_PIX_FMT_Y400A       ||  \
+     (x) == AV_PIX_FMT_GRAY16BE    ||  \
+     (x) == AV_PIX_FMT_GRAY16LE)
 #endif
 
 #define isRGBinInt(x) \
     (           \
-        (x)==PIX_FMT_RGB48BE   ||   \
-        (x)==PIX_FMT_RGB48LE   ||   \
-        (x)==PIX_FMT_RGBA64BE  ||   \
-        (x)==PIX_FMT_RGBA64LE  ||   \
-        (x)==PIX_FMT_RGB32     ||   \
-        (x)==PIX_FMT_RGB32_1   ||   \
-        (x)==PIX_FMT_RGB24     ||   \
-        (x)==PIX_FMT_RGB565BE  ||   \
-        (x)==PIX_FMT_RGB565LE  ||   \
-        (x)==PIX_FMT_RGB555BE  ||   \
-        (x)==PIX_FMT_RGB555LE  ||   \
-        (x)==PIX_FMT_RGB444BE  ||   \
-        (x)==PIX_FMT_RGB444LE  ||   \
-        (x)==PIX_FMT_RGB8      ||   \
-        (x)==PIX_FMT_RGB4      ||   \
-        (x)==PIX_FMT_RGB4_BYTE ||   \
-        (x)==PIX_FMT_MONOBLACK ||   \
-        (x)==PIX_FMT_MONOWHITE   \
+     (x) == AV_PIX_FMT_RGB48BE     ||  \
+     (x) == AV_PIX_FMT_RGB48LE     ||  \
+     (x) == AV_PIX_FMT_RGBA64BE    ||  \
+     (x) == AV_PIX_FMT_RGBA64LE    ||  \
+     (x) == AV_PIX_FMT_RGB32       ||  \
+     (x) == AV_PIX_FMT_RGB32_1     ||  \
+     (x) == AV_PIX_FMT_RGB24       ||  \
+     (x) == AV_PIX_FMT_RGB565BE    ||  \
+     (x) == AV_PIX_FMT_RGB565LE    ||  \
+     (x) == AV_PIX_FMT_RGB555BE    ||  \
+     (x) == AV_PIX_FMT_RGB555LE    ||  \
+     (x) == AV_PIX_FMT_RGB444BE    ||  \
+     (x) == AV_PIX_FMT_RGB444LE    ||  \
+     (x) == AV_PIX_FMT_RGB8        ||  \
+     (x) == AV_PIX_FMT_RGB4        ||  \
+     (x) == AV_PIX_FMT_RGB4_BYTE   ||  \
+     (x) == AV_PIX_FMT_MONOBLACK   ||  \
+     (x) == AV_PIX_FMT_MONOWHITE   \
     )
 #define isBGRinInt(x) \
     (           \
-         (x)==PIX_FMT_BGR48BE  ||   \
-         (x)==PIX_FMT_BGR48LE  ||   \
-         (x)==PIX_FMT_BGRA64BE ||   \
-         (x)==PIX_FMT_BGRA64LE ||   \
-         (x)==PIX_FMT_BGR32    ||   \
-         (x)==PIX_FMT_BGR32_1  ||   \
-         (x)==PIX_FMT_BGR24    ||   \
-         (x)==PIX_FMT_BGR565BE ||   \
-         (x)==PIX_FMT_BGR565LE ||   \
-         (x)==PIX_FMT_BGR555BE ||   \
-         (x)==PIX_FMT_BGR555LE ||   \
-         (x)==PIX_FMT_BGR444BE ||   \
-         (x)==PIX_FMT_BGR444LE ||   \
-         (x)==PIX_FMT_BGR8     ||   \
-         (x)==PIX_FMT_BGR4     ||   \
-         (x)==PIX_FMT_BGR4_BYTE||   \
-         (x)==PIX_FMT_MONOBLACK||   \
-         (x)==PIX_FMT_MONOWHITE   \
+     (x) == AV_PIX_FMT_BGR48BE     ||  \
+     (x) == AV_PIX_FMT_BGR48LE     ||  \
+     (x) == AV_PIX_FMT_BGRA64BE    ||  \
+     (x) == AV_PIX_FMT_BGRA64LE    ||  \
+     (x) == AV_PIX_FMT_BGR32       ||  \
+     (x) == AV_PIX_FMT_BGR32_1     ||  \
+     (x) == AV_PIX_FMT_BGR24       ||  \
+     (x) == AV_PIX_FMT_BGR565BE    ||  \
+     (x) == AV_PIX_FMT_BGR565LE    ||  \
+     (x) == AV_PIX_FMT_BGR555BE    ||  \
+     (x) == AV_PIX_FMT_BGR555LE    ||  \
+     (x) == AV_PIX_FMT_BGR444BE    ||  \
+     (x) == AV_PIX_FMT_BGR444LE    ||  \
+     (x) == AV_PIX_FMT_BGR8        ||  \
+     (x) == AV_PIX_FMT_BGR4        ||  \
+     (x) == AV_PIX_FMT_BGR4_BYTE   ||  \
+     (x) == AV_PIX_FMT_MONOBLACK   ||  \
+     (x) == AV_PIX_FMT_MONOWHITE   \
     )
 
 #define isRGBinBytes(x) (           \
-           (x)==PIX_FMT_RGB48BE     \
-        || (x)==PIX_FMT_RGB48LE     \
-        || (x)==PIX_FMT_RGBA64BE    \
-        || (x)==PIX_FMT_RGBA64LE    \
-        || (x)==PIX_FMT_RGBA        \
-        || (x)==PIX_FMT_ARGB        \
-        || (x)==PIX_FMT_RGB24       \
+           (x) == AV_PIX_FMT_RGB48BE     \
+        || (x) == AV_PIX_FMT_RGB48LE     \
+        || (x) == AV_PIX_FMT_RGBA64BE    \
+        || (x) == AV_PIX_FMT_RGBA64LE    \
+        || (x) == AV_PIX_FMT_RGBA        \
+        || (x) == AV_PIX_FMT_ARGB        \
+        || (x) == AV_PIX_FMT_RGB24       \
     )
 #define isBGRinBytes(x) (           \
-           (x)==PIX_FMT_BGR48BE     \
-        || (x)==PIX_FMT_BGR48LE     \
-        || (x)==PIX_FMT_BGRA64BE    \
-        || (x)==PIX_FMT_BGRA64LE    \
-        || (x)==PIX_FMT_BGRA        \
-        || (x)==PIX_FMT_ABGR        \
-        || (x)==PIX_FMT_BGR24       \
+           (x) == AV_PIX_FMT_BGR48BE     \
+        || (x) == AV_PIX_FMT_BGR48LE     \
+        || (x) == AV_PIX_FMT_BGRA64BE    \
+        || (x) == AV_PIX_FMT_BGRA64LE    \
+        || (x) == AV_PIX_FMT_BGRA        \
+        || (x) == AV_PIX_FMT_ABGR        \
+        || (x) == AV_PIX_FMT_BGR24       \
     )
 
 #define isAnyRGB(x) \
     (           \
           isRGBinInt(x)       ||    \
           isBGRinInt(x)       ||    \
-          (x)==PIX_FMT_GBR24P     \
+          (x)==AV_PIX_FMT_GBR24P     \
     )
 
-#define isALPHA(x)                                             \
-    (av_pix_fmt_descriptors[x].nb_components == 2          ||  \
-     av_pix_fmt_descriptors[x].nb_components == 4)
+static av_always_inline int isALPHA(enum AVPixelFormat pix_fmt)
+{
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
+    av_assert0(desc);
+    return desc->nb_components == 2 || desc->nb_components == 4;
+}
 
 #if 1
 #define isPacked(x)         (       \
-           (x)==PIX_FMT_PAL8        \
-        || (x)==PIX_FMT_YUYV422     \
-        || (x)==PIX_FMT_UYVY422     \
-        || (x)==PIX_FMT_Y400A       \
+           (x)==AV_PIX_FMT_PAL8        \
+        || (x)==AV_PIX_FMT_YUYV422     \
+        || (x)==AV_PIX_FMT_UYVY422     \
+        || (x)==AV_PIX_FMT_Y400A       \
         ||  isRGBinInt(x)           \
         ||  isBGRinInt(x)           \
     )
 #else
-#define isPacked(x)                                            \
-    ((av_pix_fmt_descriptors[x].nb_components >= 2         &&  \
-      !(av_pix_fmt_descriptors[x].flags & PIX_FMT_PLANAR)) ||  \
-     (x) == PIX_FMT_PAL8)
+static av_always_inline int isPacked(enum AVPixelFormat pix_fmt)
+{
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
+    av_assert0(desc);
+    return ((desc->nb_components >= 2 && !(desc->flags & PIX_FMT_PLANAR)) ||
+            pix_fmt == AV_PIX_FMT_PAL8);
+}
 
 #endif
-#define isPlanar(x)                                            \
-    (av_pix_fmt_descriptors[x].nb_components >= 2          &&  \
-     (av_pix_fmt_descriptors[x].flags & PIX_FMT_PLANAR))
+static av_always_inline int isPlanar(enum AVPixelFormat pix_fmt)
+{
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
+    av_assert0(desc);
+    return (desc->nb_components >= 2 && (desc->flags & PIX_FMT_PLANAR));
+}
 
-#define isPackedRGB(x)                                         \
-    ((av_pix_fmt_descriptors[x].flags                        & \
-     (PIX_FMT_PLANAR | PIX_FMT_RGB)) == PIX_FMT_RGB)
+static av_always_inline int isPackedRGB(enum AVPixelFormat pix_fmt)
+{
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
+    av_assert0(desc);
+    return ((desc->flags & (PIX_FMT_PLANAR | PIX_FMT_RGB)) == PIX_FMT_RGB);
+}
 
-#define isPlanarRGB(x)                                         \
-    ((av_pix_fmt_descriptors[x].flags                        & \
-     (PIX_FMT_PLANAR | PIX_FMT_RGB)) == (PIX_FMT_PLANAR | PIX_FMT_RGB))
+static av_always_inline int isPlanarRGB(enum AVPixelFormat pix_fmt)
+{
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
+    av_assert0(desc);
+    return ((desc->flags & (PIX_FMT_PLANAR | PIX_FMT_RGB)) ==
+            (PIX_FMT_PLANAR | PIX_FMT_RGB));
+}
 
-#define usePal(x) ((av_pix_fmt_descriptors[x].flags & PIX_FMT_PAL)       || \
-                   (av_pix_fmt_descriptors[x].flags & PIX_FMT_PSEUDOPAL))
+static av_always_inline int usePal(enum AVPixelFormat pix_fmt)
+{
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
+    av_assert0(desc);
+    return (desc->flags & PIX_FMT_PAL) || (desc->flags & PIX_FMT_PSEUDOPAL);
+}
 
 extern const uint64_t ff_dither4[2];
 extern const uint64_t ff_dither8[2];
@@ -726,4 +770,24 @@
 void ff_sws_init_swScale_altivec(SwsContext *c);
 void ff_sws_init_swScale_mmx(SwsContext *c);
 
+static inline void fillPlane16(uint8_t *plane, int stride, int width, int height, int y,
+                               int alpha, int bits, const int big_endian)
+{
+    int i, j;
+    uint8_t *ptr = plane + stride * y;
+    int v = alpha ? 0xFFFF>>(15-bits) : (1<<bits);
+    for (i = 0; i < height; i++) {
+#define FILL(wfunc) \
+        for (j = 0; j < width; j++) {\
+            wfunc(ptr+2*j, v);\
+        }
+        if (big_endian) {
+            FILL(AV_WB16);
+        } else {
+            FILL(AV_WL16);
+        }
+        ptr += stride;
+    }
+}
+
 #endif /* SWSCALE_SWSCALE_INTERNAL_H */
diff --git a/libswscale/swscale_unscaled.c b/libswscale/swscale_unscaled.c
index de73287..f35d1ba 100644
--- a/libswscale/swscale_unscaled.c
+++ b/libswscale/swscale_unscaled.c
@@ -139,20 +139,6 @@
     }
 }
 
-static void fillPlane16(uint8_t *plane, int stride, int width, int height, int y,
-                      int alpha, int bits)
-{
-    int i, j;
-    uint8_t *ptr = plane + stride * y;
-    int v = alpha ? -1 : (1<<bits);
-    for (i = 0; i < height; i++) {
-        for (j = 0; j < width; j++) {
-            AV_WN16(ptr+2*j, v);
-        }
-        ptr += stride;
-    }
-}
-
 static void copyPlane(const uint8_t *src, int srcStride,
                       int srcSliceY, int srcSliceH, int width,
                       uint8_t *dst, int dstStride)
@@ -180,7 +166,7 @@
     copyPlane(src[0], srcStride[0], srcSliceY, srcSliceH, c->srcW,
               dstParam[0], dstStride[0]);
 
-    if (c->dstFormat == PIX_FMT_NV12)
+    if (c->dstFormat == AV_PIX_FMT_NV12)
         interleaveBytes(src[1], src[2], dst, c->srcW / 2, srcSliceH / 2,
                         srcStride[1], srcStride[2], dstStride[0]);
     else
@@ -357,31 +343,31 @@
                            int srcSliceY, int srcSliceH, uint8_t *dst[],
                            int dstStride[])
 {
-    const enum PixelFormat srcFormat = c->srcFormat;
-    const enum PixelFormat dstFormat = c->dstFormat;
+    const enum AVPixelFormat srcFormat = c->srcFormat;
+    const enum AVPixelFormat dstFormat = c->dstFormat;
     void (*conv)(const uint8_t *src, uint8_t *dst, int num_pixels,
                  const uint8_t *palette) = NULL;
     int i;
     uint8_t *dstPtr = dst[0] + dstStride[0] * srcSliceY;
     const uint8_t *srcPtr = src[0];
 
-    if (srcFormat == PIX_FMT_GRAY8A) {
+    if (srcFormat == AV_PIX_FMT_GRAY8A) {
         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;
+        case AV_PIX_FMT_RGB32  : conv = gray8aToPacked32; break;
+        case AV_PIX_FMT_BGR32  : conv = gray8aToPacked32; break;
+        case AV_PIX_FMT_BGR32_1: conv = gray8aToPacked32_1; break;
+        case AV_PIX_FMT_RGB32_1: conv = gray8aToPacked32_1; break;
+        case AV_PIX_FMT_RGB24  : conv = gray8aToPacked24; break;
+        case AV_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;
-        case PIX_FMT_BGR32_1: conv = sws_convertPalette8ToPacked32; break;
-        case PIX_FMT_RGB32_1: conv = sws_convertPalette8ToPacked32; break;
-        case PIX_FMT_RGB24  : conv = sws_convertPalette8ToPacked24; break;
-        case PIX_FMT_BGR24  : conv = sws_convertPalette8ToPacked24; break;
+        case AV_PIX_FMT_RGB32  : conv = sws_convertPalette8ToPacked32; break;
+        case AV_PIX_FMT_BGR32  : conv = sws_convertPalette8ToPacked32; break;
+        case AV_PIX_FMT_BGR32_1: conv = sws_convertPalette8ToPacked32; break;
+        case AV_PIX_FMT_RGB32_1: conv = sws_convertPalette8ToPacked32; break;
+        case AV_PIX_FMT_RGB24  : conv = sws_convertPalette8ToPacked24; break;
+        case AV_PIX_FMT_BGR24  : conv = sws_convertPalette8ToPacked24; break;
         }
     }
 
@@ -451,7 +437,12 @@
                                  uint8_t *dst[], int dstStride[])
 {
     int alpha_first = 0;
-    if (c->srcFormat != PIX_FMT_GBRP) {
+    const uint8_t *src102[] = { src[1], src[0], src[2] };
+    const uint8_t *src201[] = { src[2], src[0], src[1] };
+    int stride102[] = { srcStride[1], srcStride[0], srcStride[2] };
+    int stride201[] = { srcStride[2], srcStride[0], srcStride[1] };
+
+    if (c->srcFormat != AV_PIX_FMT_GBRP) {
         av_log(c, AV_LOG_ERROR, "unsupported planar RGB conversion %s -> %s\n",
                av_get_pix_fmt_name(c->srcFormat),
                av_get_pix_fmt_name(c->dstFormat));
@@ -459,34 +450,30 @@
     }
 
     switch (c->dstFormat) {
-    case PIX_FMT_BGR24:
-        gbr24ptopacked24((const uint8_t *[]) { src[1], src[0], src[2] },
-                         (int []) { srcStride[1], srcStride[0], srcStride[2] },
+    case AV_PIX_FMT_BGR24:
+        gbr24ptopacked24(src102, stride102,
                          dst[0] + srcSliceY * dstStride[0], dstStride[0],
                          srcSliceH, c->srcW);
         break;
 
-    case PIX_FMT_RGB24:
-        gbr24ptopacked24((const uint8_t *[]) { src[2], src[0], src[1] },
-                         (int []) { srcStride[2], srcStride[0], srcStride[1] },
+    case AV_PIX_FMT_RGB24:
+        gbr24ptopacked24(src201, stride201,
                          dst[0] + srcSliceY * dstStride[0], dstStride[0],
                          srcSliceH, c->srcW);
         break;
 
-    case PIX_FMT_ARGB:
+    case AV_PIX_FMT_ARGB:
         alpha_first = 1;
-    case PIX_FMT_RGBA:
-        gbr24ptopacked32((const uint8_t *[]) { src[2], src[0], src[1] },
-                         (int []) { srcStride[2], srcStride[0], srcStride[1] },
+    case AV_PIX_FMT_RGBA:
+        gbr24ptopacked32(src201, stride201,
                          dst[0] + srcSliceY * dstStride[0], dstStride[0],
                          srcSliceH, alpha_first, c->srcW);
         break;
 
-    case PIX_FMT_ABGR:
+    case AV_PIX_FMT_ABGR:
         alpha_first = 1;
-    case PIX_FMT_BGRA:
-        gbr24ptopacked32((const uint8_t *[]) { src[1], src[0], src[2] },
-                         (int []) { srcStride[1], srcStride[0], srcStride[2] },
+    case AV_PIX_FMT_BGRA:
+        gbr24ptopacked32(src102, stride102,
                          dst[0] + srcSliceY * dstStride[0], dstStride[0],
                          srcSliceH, alpha_first, c->srcW);
         break;
@@ -502,41 +489,41 @@
 }
 
 #define isRGBA32(x) (            \
-           (x) == PIX_FMT_ARGB   \
-        || (x) == PIX_FMT_RGBA   \
-        || (x) == PIX_FMT_BGRA   \
-        || (x) == PIX_FMT_ABGR   \
+           (x) == AV_PIX_FMT_ARGB   \
+        || (x) == AV_PIX_FMT_RGBA   \
+        || (x) == AV_PIX_FMT_BGRA   \
+        || (x) == AV_PIX_FMT_ABGR   \
         )
 
 #define isRGBA64(x) (                \
-           (x) == PIX_FMT_RGBA64LE   \
-        || (x) == PIX_FMT_RGBA64BE   \
-        || (x) == PIX_FMT_BGRA64LE   \
-        || (x) == PIX_FMT_BGRA64BE   \
+           (x) == AV_PIX_FMT_RGBA64LE   \
+        || (x) == AV_PIX_FMT_RGBA64BE   \
+        || (x) == AV_PIX_FMT_BGRA64LE   \
+        || (x) == AV_PIX_FMT_BGRA64BE   \
         )
 
 #define isRGB48(x) (                \
-           (x) == PIX_FMT_RGB48LE   \
-        || (x) == PIX_FMT_RGB48BE   \
-        || (x) == PIX_FMT_BGR48LE   \
-        || (x) == PIX_FMT_BGR48BE   \
+           (x) == AV_PIX_FMT_RGB48LE   \
+        || (x) == AV_PIX_FMT_RGB48BE   \
+        || (x) == AV_PIX_FMT_BGR48LE   \
+        || (x) == AV_PIX_FMT_BGR48BE   \
         )
 
 /* {RGB,BGR}{15,16,24,32,32_1} -> {RGB,BGR}{15,16,24,32} */
 typedef void (* rgbConvFn) (const uint8_t *, uint8_t *, int);
 static rgbConvFn findRgbConvFn(SwsContext *c)
 {
-    const enum PixelFormat srcFormat = c->srcFormat;
-    const enum PixelFormat dstFormat = c->dstFormat;
+    const enum AVPixelFormat srcFormat = c->srcFormat;
+    const enum AVPixelFormat dstFormat = c->dstFormat;
     const int srcId = c->srcFormatBpp;
     const int dstId = c->dstFormatBpp;
     rgbConvFn conv = NULL;
 
-#define IS_NOT_NE(bpp, fmt) \
+#define IS_NOT_NE(bpp, desc) \
     (((bpp + 7) >> 3) == 2 && \
-     (!(av_pix_fmt_descriptors[fmt].flags & PIX_FMT_BE) != !HAVE_BIGENDIAN))
+     (!(desc->flags & PIX_FMT_BE) != !HAVE_BIGENDIAN))
 
-#define CONV_IS(src, dst) (srcFormat == PIX_FMT_##src && dstFormat == PIX_FMT_##dst)
+#define CONV_IS(src, dst) (srcFormat == AV_PIX_FMT_##src && dstFormat == AV_PIX_FMT_##dst)
 
     if (isRGBA32(srcFormat) && isRGBA32(dstFormat)) {
         if (     CONV_IS(ABGR, RGBA)
@@ -627,8 +614,10 @@
                            int dstStride[])
 
 {
-    const enum PixelFormat srcFormat = c->srcFormat;
-    const enum PixelFormat dstFormat = c->dstFormat;
+    const enum AVPixelFormat srcFormat = c->srcFormat;
+    const enum AVPixelFormat dstFormat = c->dstFormat;
+    const AVPixFmtDescriptor *desc_src = av_pix_fmt_desc_get(c->srcFormat);
+    const AVPixFmtDescriptor *desc_dst = av_pix_fmt_desc_get(c->dstFormat);
     const int srcBpp = (c->srcFormatBpp + 7) >> 3;
     const int dstBpp = (c->dstFormatBpp + 7) >> 3;
     rgbConvFn conv = findRgbConvFn(c);
@@ -639,14 +628,14 @@
     } else {
         const uint8_t *srcPtr = src[0];
               uint8_t *dstPtr = dst[0];
-        int src_bswap = IS_NOT_NE(c->srcFormatBpp, srcFormat);
-        int dst_bswap = IS_NOT_NE(c->dstFormatBpp, dstFormat);
+        int src_bswap = IS_NOT_NE(c->srcFormatBpp, desc_src);
+        int dst_bswap = IS_NOT_NE(c->dstFormatBpp, desc_dst);
 
-        if ((srcFormat == PIX_FMT_RGB32_1 || srcFormat == PIX_FMT_BGR32_1) &&
+        if ((srcFormat == AV_PIX_FMT_RGB32_1 || srcFormat == AV_PIX_FMT_BGR32_1) &&
             !isRGBA32(dstFormat))
             srcPtr += ALT32_CORR;
 
-        if ((dstFormat == PIX_FMT_RGB32_1 || dstFormat == PIX_FMT_BGR32_1) &&
+        if ((dstFormat == AV_PIX_FMT_RGB32_1 || dstFormat == AV_PIX_FMT_BGR32_1) &&
             !isRGBA32(srcFormat))
             dstPtr += ALT32_CORR;
 
@@ -761,6 +750,8 @@
                              int srcStride[], int srcSliceY, int srcSliceH,
                              uint8_t *dst[], int dstStride[])
 {
+    const AVPixFmtDescriptor *desc_src = av_pix_fmt_desc_get(c->srcFormat);
+    const AVPixFmtDescriptor *desc_dst = av_pix_fmt_desc_get(c->dstFormat);
     int plane, i, j;
     for (plane = 0; plane < 4; plane++) {
         int length = (plane == 0 || plane == 3) ? c->srcW  : -((-c->srcW  ) >> c->chrDstHSubSample);
@@ -777,7 +768,8 @@
         if (!src[plane] || (plane == 1 && !src[2])) {
             if (is16BPS(c->dstFormat) || isNBPS(c->dstFormat)) {
                 fillPlane16(dst[plane], dstStride[plane], length, height, y,
-                        plane == 3, av_pix_fmt_descriptors[c->dstFormat].comp[plane].depth_minus1);
+                        plane == 3, desc_dst->comp[plane].depth_minus1,
+                        isBE(c->dstFormat));
             } else {
                 fillPlane(dst[plane], dstStride[plane], length, height, y,
                         (plane == 3) ? 255 : 128);
@@ -786,8 +778,8 @@
             if(isNBPS(c->srcFormat) || isNBPS(c->dstFormat)
                || (is16BPS(c->srcFormat) != is16BPS(c->dstFormat))
             ) {
-                const int src_depth = av_pix_fmt_descriptors[c->srcFormat].comp[plane].depth_minus1 + 1;
-                const int dst_depth = av_pix_fmt_descriptors[c->dstFormat].comp[plane].depth_minus1 + 1;
+                const int src_depth = desc_src->comp[plane].depth_minus1 + 1;
+                const int dst_depth = desc_dst->comp[plane].depth_minus1 + 1;
                 const uint16_t *srcPtr2 = (const uint16_t *) srcPtr;
                 uint16_t *dstPtr2 = (uint16_t*)dstPtr;
 
@@ -905,7 +897,7 @@
             } else {
                 if (is16BPS(c->srcFormat) && is16BPS(c->dstFormat))
                     length *= 2;
-                else if (!av_pix_fmt_descriptors[c->srcFormat].comp[0].depth_minus1)
+                else if (!desc_src->comp[0].depth_minus1)
                     length >>= 3; // monowhite/black
                 for (i = 0; i < height; i++) {
                     memcpy(dstPtr, srcPtr, length);
@@ -926,8 +918,8 @@
 
 void ff_get_unscaled_swscale(SwsContext *c)
 {
-    const enum PixelFormat srcFormat = c->srcFormat;
-    const enum PixelFormat dstFormat = c->dstFormat;
+    const enum AVPixelFormat srcFormat = c->srcFormat;
+    const enum AVPixelFormat dstFormat = c->dstFormat;
     const int flags = c->flags;
     const int dstH = c->dstH;
     int needsDither;
@@ -937,26 +929,26 @@
            (c->dstFormatBpp < c->srcFormatBpp || (!isAnyRGB(srcFormat)));
 
     /* yv12_to_nv12 */
-    if ((srcFormat == PIX_FMT_YUV420P || srcFormat == PIX_FMT_YUVA420P) &&
-        (dstFormat == PIX_FMT_NV12 || dstFormat == PIX_FMT_NV21)) {
+    if ((srcFormat == AV_PIX_FMT_YUV420P || srcFormat == AV_PIX_FMT_YUVA420P) &&
+        (dstFormat == AV_PIX_FMT_NV12 || dstFormat == AV_PIX_FMT_NV21)) {
         c->swScale = planarToNv12Wrapper;
     }
     /* yuv2bgr */
-    if ((srcFormat == PIX_FMT_YUV420P || srcFormat == PIX_FMT_YUV422P ||
-         srcFormat == PIX_FMT_YUVA420P) && isAnyRGB(dstFormat) &&
+    if ((srcFormat == AV_PIX_FMT_YUV420P || srcFormat == AV_PIX_FMT_YUV422P ||
+         srcFormat == AV_PIX_FMT_YUVA420P) && isAnyRGB(dstFormat) &&
         !(flags & SWS_ACCURATE_RND) && !(dstH & 1)) {
         c->swScale = ff_yuv2rgb_get_func_ptr(c);
     }
 
-    if (srcFormat == PIX_FMT_YUV410P &&
-        (dstFormat == PIX_FMT_YUV420P || dstFormat == PIX_FMT_YUVA420P) &&
+    if (srcFormat == AV_PIX_FMT_YUV410P &&
+        (dstFormat == AV_PIX_FMT_YUV420P || dstFormat == AV_PIX_FMT_YUVA420P) &&
         !(flags & SWS_BITEXACT)) {
         c->swScale = yvu9ToYv12Wrapper;
     }
 
     /* bgr24toYV12 */
-    if (srcFormat == PIX_FMT_BGR24 &&
-        (dstFormat == PIX_FMT_YUV420P || dstFormat == PIX_FMT_YUVA420P) &&
+    if (srcFormat == AV_PIX_FMT_BGR24 &&
+        (dstFormat == AV_PIX_FMT_YUV420P || dstFormat == AV_PIX_FMT_YUVA420P) &&
         !(flags & SWS_ACCURATE_RND))
         c->swScale = bgr24ToYv12Wrapper;
 
@@ -966,74 +958,74 @@
         c->swScale= rgbToRgbWrapper;
 
 #define isByteRGB(f) (\
-        f == PIX_FMT_RGB32   ||\
-        f == PIX_FMT_RGB32_1 ||\
-        f == PIX_FMT_RGB24   ||\
-        f == PIX_FMT_BGR32   ||\
-        f == PIX_FMT_BGR32_1 ||\
-        f == PIX_FMT_BGR24)
+        f == AV_PIX_FMT_RGB32   ||\
+        f == AV_PIX_FMT_RGB32_1 ||\
+        f == AV_PIX_FMT_RGB24   ||\
+        f == AV_PIX_FMT_BGR32   ||\
+        f == AV_PIX_FMT_BGR32_1 ||\
+        f == AV_PIX_FMT_BGR24)
 
     if (isAnyRGB(srcFormat) && isPlanar(srcFormat) && isByteRGB(dstFormat))
         c->swScale = planarRgbToRgbWrapper;
 
     /* bswap 16 bits per pixel/component packed formats */
-    if (IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_BGR444) ||
-        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_BGR48)  ||
-        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_BGRA64) ||
-        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_BGR555) ||
-        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_BGR565) ||
-        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_GRAY16) ||
-        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_RGB444) ||
-        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_RGB48)  ||
-        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_RGBA64) ||
-        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_RGB555) ||
-        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_RGB565))
+    if (IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, AV_PIX_FMT_BGR444) ||
+        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, AV_PIX_FMT_BGR48)  ||
+        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, AV_PIX_FMT_BGRA64) ||
+        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, AV_PIX_FMT_BGR555) ||
+        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, AV_PIX_FMT_BGR565) ||
+        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, AV_PIX_FMT_GRAY16) ||
+        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, AV_PIX_FMT_RGB444) ||
+        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, AV_PIX_FMT_RGB48)  ||
+        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, AV_PIX_FMT_RGBA64) ||
+        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, AV_PIX_FMT_RGB555) ||
+        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, AV_PIX_FMT_RGB565))
         c->swScale = packed_16bpc_bswap;
 
     if (usePal(srcFormat) && isByteRGB(dstFormat))
         c->swScale = palToRgbWrapper;
 
-    if (srcFormat == PIX_FMT_YUV422P) {
-        if (dstFormat == PIX_FMT_YUYV422)
+    if (srcFormat == AV_PIX_FMT_YUV422P) {
+        if (dstFormat == AV_PIX_FMT_YUYV422)
             c->swScale = yuv422pToYuy2Wrapper;
-        else if (dstFormat == PIX_FMT_UYVY422)
+        else if (dstFormat == AV_PIX_FMT_UYVY422)
             c->swScale = yuv422pToUyvyWrapper;
     }
 
     /* LQ converters if -sws 0 or -sws 4*/
     if (c->flags&(SWS_FAST_BILINEAR|SWS_POINT)) {
         /* yv12_to_yuy2 */
-        if (srcFormat == PIX_FMT_YUV420P || srcFormat == PIX_FMT_YUVA420P) {
-            if (dstFormat == PIX_FMT_YUYV422)
+        if (srcFormat == AV_PIX_FMT_YUV420P || srcFormat == AV_PIX_FMT_YUVA420P) {
+            if (dstFormat == AV_PIX_FMT_YUYV422)
                 c->swScale = planarToYuy2Wrapper;
-            else if (dstFormat == PIX_FMT_UYVY422)
+            else if (dstFormat == AV_PIX_FMT_UYVY422)
                 c->swScale = planarToUyvyWrapper;
         }
     }
-    if (srcFormat == PIX_FMT_YUYV422 &&
-       (dstFormat == PIX_FMT_YUV420P || dstFormat == PIX_FMT_YUVA420P))
+    if (srcFormat == AV_PIX_FMT_YUYV422 &&
+       (dstFormat == AV_PIX_FMT_YUV420P || dstFormat == AV_PIX_FMT_YUVA420P))
         c->swScale = yuyvToYuv420Wrapper;
-    if (srcFormat == PIX_FMT_UYVY422 &&
-       (dstFormat == PIX_FMT_YUV420P || dstFormat == PIX_FMT_YUVA420P))
+    if (srcFormat == AV_PIX_FMT_UYVY422 &&
+       (dstFormat == AV_PIX_FMT_YUV420P || dstFormat == AV_PIX_FMT_YUVA420P))
         c->swScale = uyvyToYuv420Wrapper;
-    if (srcFormat == PIX_FMT_YUYV422 && dstFormat == PIX_FMT_YUV422P)
+    if (srcFormat == AV_PIX_FMT_YUYV422 && dstFormat == AV_PIX_FMT_YUV422P)
         c->swScale = yuyvToYuv422Wrapper;
-    if (srcFormat == PIX_FMT_UYVY422 && dstFormat == PIX_FMT_YUV422P)
+    if (srcFormat == AV_PIX_FMT_UYVY422 && dstFormat == AV_PIX_FMT_YUV422P)
         c->swScale = uyvyToYuv422Wrapper;
 
-#define isPlanarGray(x) (isGray(x) && (x) != PIX_FMT_GRAY8A)
+#define isPlanarGray(x) (isGray(x) && (x) != AV_PIX_FMT_GRAY8A)
     /* simple copy */
     if ( srcFormat == dstFormat ||
-        (srcFormat == PIX_FMT_YUVA420P && dstFormat == PIX_FMT_YUV420P) ||
-        (srcFormat == PIX_FMT_YUV420P && dstFormat == PIX_FMT_YUVA420P) ||
+        (srcFormat == AV_PIX_FMT_YUVA420P && dstFormat == AV_PIX_FMT_YUV420P) ||
+        (srcFormat == AV_PIX_FMT_YUV420P && dstFormat == AV_PIX_FMT_YUVA420P) ||
         (isPlanarYUV(srcFormat) && isPlanarGray(dstFormat)) ||
         (isPlanarYUV(dstFormat) && isPlanarGray(srcFormat)) ||
         (isPlanarGray(dstFormat) && isPlanarGray(srcFormat)) ||
         (isPlanarYUV(srcFormat) && isPlanarYUV(dstFormat) &&
          c->chrDstHSubSample == c->chrSrcHSubSample &&
          c->chrDstVSubSample == c->chrSrcVSubSample &&
-         dstFormat != PIX_FMT_NV12 && dstFormat != PIX_FMT_NV21 &&
-         srcFormat != PIX_FMT_NV12 && srcFormat != PIX_FMT_NV21))
+         dstFormat != AV_PIX_FMT_NV12 && dstFormat != AV_PIX_FMT_NV21 &&
+         srcFormat != AV_PIX_FMT_NV12 && srcFormat != AV_PIX_FMT_NV21))
     {
         if (isPacked(c->srcFormat))
             c->swScale = packedCopyWrapper;
diff --git a/libswscale/utils.c b/libswscale/utils.c
index 4b14c73..7761441 100644
--- a/libswscale/utils.c
+++ b/libswscale/utils.c
@@ -75,129 +75,151 @@
     int is_supported_in, is_supported_out;
 } FormatEntry;
 
-static const FormatEntry format_entries[PIX_FMT_NB] = {
-    [PIX_FMT_YUV420P]     = { 1, 1 },
-    [PIX_FMT_YUYV422]     = { 1, 1 },
-    [PIX_FMT_RGB24]       = { 1, 1 },
-    [PIX_FMT_BGR24]       = { 1, 1 },
-    [PIX_FMT_YUV422P]     = { 1, 1 },
-    [PIX_FMT_YUV444P]     = { 1, 1 },
-    [PIX_FMT_YUV410P]     = { 1, 1 },
-    [PIX_FMT_YUV411P]     = { 1, 1 },
-    [PIX_FMT_GRAY8]       = { 1, 1 },
-    [PIX_FMT_MONOWHITE]   = { 1, 1 },
-    [PIX_FMT_MONOBLACK]   = { 1, 1 },
-    [PIX_FMT_PAL8]        = { 1, 0 },
-    [PIX_FMT_YUVJ420P]    = { 1, 1 },
-    [PIX_FMT_YUVJ422P]    = { 1, 1 },
-    [PIX_FMT_YUVJ444P]    = { 1, 1 },
-    [PIX_FMT_UYVY422]     = { 1, 1 },
-    [PIX_FMT_UYYVYY411]   = { 0, 0 },
-    [PIX_FMT_BGR8]        = { 1, 1 },
-    [PIX_FMT_BGR4]        = { 0, 1 },
-    [PIX_FMT_BGR4_BYTE]   = { 1, 1 },
-    [PIX_FMT_RGB8]        = { 1, 1 },
-    [PIX_FMT_RGB4]        = { 0, 1 },
-    [PIX_FMT_RGB4_BYTE]   = { 1, 1 },
-    [PIX_FMT_NV12]        = { 1, 1 },
-    [PIX_FMT_NV21]        = { 1, 1 },
-    [PIX_FMT_ARGB]        = { 1, 1 },
-    [PIX_FMT_RGBA]        = { 1, 1 },
-    [PIX_FMT_ABGR]        = { 1, 1 },
-    [PIX_FMT_BGRA]        = { 1, 1 },
-    [PIX_FMT_0RGB]        = { 1, 1 },
-    [PIX_FMT_RGB0]        = { 1, 1 },
-    [PIX_FMT_0BGR]        = { 1, 1 },
-    [PIX_FMT_BGR0]        = { 1, 1 },
-    [PIX_FMT_GRAY16BE]    = { 1, 1 },
-    [PIX_FMT_GRAY16LE]    = { 1, 1 },
-    [PIX_FMT_YUV440P]     = { 1, 1 },
-    [PIX_FMT_YUVJ440P]    = { 1, 1 },
-    [PIX_FMT_YUVA420P]    = { 1, 1 },
-    [PIX_FMT_YUVA422P]    = { 1, 1 },
-    [PIX_FMT_YUVA444P]    = { 1, 1 },
-    [PIX_FMT_RGB48BE]     = { 1, 1 },
-    [PIX_FMT_RGB48LE]     = { 1, 1 },
-    [PIX_FMT_RGBA64BE]    = { 1, 0 },
-    [PIX_FMT_RGBA64LE]    = { 1, 0 },
-    [PIX_FMT_RGB565BE]    = { 1, 1 },
-    [PIX_FMT_RGB565LE]    = { 1, 1 },
-    [PIX_FMT_RGB555BE]    = { 1, 1 },
-    [PIX_FMT_RGB555LE]    = { 1, 1 },
-    [PIX_FMT_BGR565BE]    = { 1, 1 },
-    [PIX_FMT_BGR565LE]    = { 1, 1 },
-    [PIX_FMT_BGR555BE]    = { 1, 1 },
-    [PIX_FMT_BGR555LE]    = { 1, 1 },
-    [PIX_FMT_YUV420P16LE] = { 1, 1 },
-    [PIX_FMT_YUV420P16BE] = { 1, 1 },
-    [PIX_FMT_YUV422P16LE] = { 1, 1 },
-    [PIX_FMT_YUV422P16BE] = { 1, 1 },
-    [PIX_FMT_YUV444P16LE] = { 1, 1 },
-    [PIX_FMT_YUV444P16BE] = { 1, 1 },
-    [PIX_FMT_RGB444LE]    = { 1, 1 },
-    [PIX_FMT_RGB444BE]    = { 1, 1 },
-    [PIX_FMT_BGR444LE]    = { 1, 1 },
-    [PIX_FMT_BGR444BE]    = { 1, 1 },
-    [PIX_FMT_Y400A]       = { 1, 0 },
-    [PIX_FMT_BGR48BE]     = { 1, 1 },
-    [PIX_FMT_BGR48LE]     = { 1, 1 },
-    [PIX_FMT_BGRA64BE]    = { 0, 0 },
-    [PIX_FMT_BGRA64LE]    = { 0, 0 },
-    [PIX_FMT_YUV420P9BE]  = { 1, 1 },
-    [PIX_FMT_YUV420P9LE]  = { 1, 1 },
-    [PIX_FMT_YUV420P10BE] = { 1, 1 },
-    [PIX_FMT_YUV420P10LE] = { 1, 1 },
-    [PIX_FMT_YUV420P12BE] = { 1, 1 },
-    [PIX_FMT_YUV420P12LE] = { 1, 1 },
-    [PIX_FMT_YUV420P14BE] = { 1, 1 },
-    [PIX_FMT_YUV420P14LE] = { 1, 1 },
-    [PIX_FMT_YUV422P9BE]  = { 1, 1 },
-    [PIX_FMT_YUV422P9LE]  = { 1, 1 },
-    [PIX_FMT_YUV422P10BE] = { 1, 1 },
-    [PIX_FMT_YUV422P10LE] = { 1, 1 },
-    [PIX_FMT_YUV422P12BE] = { 1, 1 },
-    [PIX_FMT_YUV422P12LE] = { 1, 1 },
-    [PIX_FMT_YUV422P14BE] = { 1, 1 },
-    [PIX_FMT_YUV422P14LE] = { 1, 1 },
-    [PIX_FMT_YUV444P9BE]  = { 1, 1 },
-    [PIX_FMT_YUV444P9LE]  = { 1, 1 },
-    [PIX_FMT_YUV444P10BE] = { 1, 1 },
-    [PIX_FMT_YUV444P10LE] = { 1, 1 },
-    [PIX_FMT_YUV444P12BE] = { 1, 1 },
-    [PIX_FMT_YUV444P12LE] = { 1, 1 },
-    [PIX_FMT_YUV444P14BE] = { 1, 1 },
-    [PIX_FMT_YUV444P14LE] = { 1, 1 },
-    [PIX_FMT_GBRP]        = { 1, 0 },
-    [PIX_FMT_GBRP9LE]     = { 1, 0 },
-    [PIX_FMT_GBRP9BE]     = { 1, 0 },
-    [PIX_FMT_GBRP10LE]    = { 1, 0 },
-    [PIX_FMT_GBRP10BE]    = { 1, 0 },
-    [PIX_FMT_GBRP12LE]    = { 1, 0 },
-    [PIX_FMT_GBRP12BE]    = { 1, 0 },
-    [PIX_FMT_GBRP14LE]    = { 1, 0 },
-    [PIX_FMT_GBRP14BE]    = { 1, 0 },
-    [PIX_FMT_GBRP16LE]    = { 1, 0 },
-    [PIX_FMT_GBRP16BE]    = { 1, 0 },
+static const FormatEntry format_entries[AV_PIX_FMT_NB] = {
+    [AV_PIX_FMT_YUV420P]     = { 1, 1 },
+    [AV_PIX_FMT_YUYV422]     = { 1, 1 },
+    [AV_PIX_FMT_RGB24]       = { 1, 1 },
+    [AV_PIX_FMT_BGR24]       = { 1, 1 },
+    [AV_PIX_FMT_YUV422P]     = { 1, 1 },
+    [AV_PIX_FMT_YUV444P]     = { 1, 1 },
+    [AV_PIX_FMT_YUV410P]     = { 1, 1 },
+    [AV_PIX_FMT_YUV411P]     = { 1, 1 },
+    [AV_PIX_FMT_GRAY8]       = { 1, 1 },
+    [AV_PIX_FMT_MONOWHITE]   = { 1, 1 },
+    [AV_PIX_FMT_MONOBLACK]   = { 1, 1 },
+    [AV_PIX_FMT_PAL8]        = { 1, 0 },
+    [AV_PIX_FMT_YUVJ420P]    = { 1, 1 },
+    [AV_PIX_FMT_YUVJ422P]    = { 1, 1 },
+    [AV_PIX_FMT_YUVJ444P]    = { 1, 1 },
+    [AV_PIX_FMT_UYVY422]     = { 1, 1 },
+    [AV_PIX_FMT_UYYVYY411]   = { 0, 0 },
+    [AV_PIX_FMT_BGR8]        = { 1, 1 },
+    [AV_PIX_FMT_BGR4]        = { 0, 1 },
+    [AV_PIX_FMT_BGR4_BYTE]   = { 1, 1 },
+    [AV_PIX_FMT_RGB8]        = { 1, 1 },
+    [AV_PIX_FMT_RGB4]        = { 0, 1 },
+    [AV_PIX_FMT_RGB4_BYTE]   = { 1, 1 },
+    [AV_PIX_FMT_NV12]        = { 1, 1 },
+    [AV_PIX_FMT_NV21]        = { 1, 1 },
+    [AV_PIX_FMT_ARGB]        = { 1, 1 },
+    [AV_PIX_FMT_RGBA]        = { 1, 1 },
+    [AV_PIX_FMT_ABGR]        = { 1, 1 },
+    [AV_PIX_FMT_BGRA]        = { 1, 1 },
+    [AV_PIX_FMT_0RGB]        = { 1, 1 },
+    [AV_PIX_FMT_RGB0]        = { 1, 1 },
+    [AV_PIX_FMT_0BGR]        = { 1, 1 },
+    [AV_PIX_FMT_BGR0]        = { 1, 1 },
+    [AV_PIX_FMT_GRAY16BE]    = { 1, 1 },
+    [AV_PIX_FMT_GRAY16LE]    = { 1, 1 },
+    [AV_PIX_FMT_YUV440P]     = { 1, 1 },
+    [AV_PIX_FMT_YUVJ440P]    = { 1, 1 },
+    [AV_PIX_FMT_YUVA420P]    = { 1, 1 },
+    [AV_PIX_FMT_YUVA422P]    = { 1, 1 },
+    [AV_PIX_FMT_YUVA444P]    = { 1, 1 },
+    [AV_PIX_FMT_YUVA420P9BE] = { 1, 1 },
+    [AV_PIX_FMT_YUVA420P9LE] = { 1, 1 },
+    [AV_PIX_FMT_YUVA422P9BE] = { 1, 1 },
+    [AV_PIX_FMT_YUVA422P9LE] = { 1, 1 },
+    [AV_PIX_FMT_YUVA444P9BE] = { 1, 1 },
+    [AV_PIX_FMT_YUVA444P9LE] = { 1, 1 },
+    [AV_PIX_FMT_YUVA420P10BE]= { 1, 1 },
+    [AV_PIX_FMT_YUVA420P10LE]= { 1, 1 },
+    [AV_PIX_FMT_YUVA422P10BE]= { 1, 1 },
+    [AV_PIX_FMT_YUVA422P10LE]= { 1, 1 },
+    [AV_PIX_FMT_YUVA444P10BE]= { 1, 1 },
+    [AV_PIX_FMT_YUVA444P10LE]= { 1, 1 },
+    [AV_PIX_FMT_YUVA420P16BE]= { 1, 1 },
+    [AV_PIX_FMT_YUVA420P16LE]= { 1, 1 },
+    [AV_PIX_FMT_YUVA422P16BE]= { 1, 1 },
+    [AV_PIX_FMT_YUVA422P16LE]= { 1, 1 },
+    [AV_PIX_FMT_YUVA444P16BE]= { 1, 1 },
+    [AV_PIX_FMT_YUVA444P16LE]= { 1, 1 },
+    [AV_PIX_FMT_RGB48BE]     = { 1, 1 },
+    [AV_PIX_FMT_RGB48LE]     = { 1, 1 },
+    [AV_PIX_FMT_RGBA64BE]    = { 1, 0 },
+    [AV_PIX_FMT_RGBA64LE]    = { 1, 0 },
+    [AV_PIX_FMT_RGB565BE]    = { 1, 1 },
+    [AV_PIX_FMT_RGB565LE]    = { 1, 1 },
+    [AV_PIX_FMT_RGB555BE]    = { 1, 1 },
+    [AV_PIX_FMT_RGB555LE]    = { 1, 1 },
+    [AV_PIX_FMT_BGR565BE]    = { 1, 1 },
+    [AV_PIX_FMT_BGR565LE]    = { 1, 1 },
+    [AV_PIX_FMT_BGR555BE]    = { 1, 1 },
+    [AV_PIX_FMT_BGR555LE]    = { 1, 1 },
+    [AV_PIX_FMT_YUV420P16LE] = { 1, 1 },
+    [AV_PIX_FMT_YUV420P16BE] = { 1, 1 },
+    [AV_PIX_FMT_YUV422P16LE] = { 1, 1 },
+    [AV_PIX_FMT_YUV422P16BE] = { 1, 1 },
+    [AV_PIX_FMT_YUV444P16LE] = { 1, 1 },
+    [AV_PIX_FMT_YUV444P16BE] = { 1, 1 },
+    [AV_PIX_FMT_RGB444LE]    = { 1, 1 },
+    [AV_PIX_FMT_RGB444BE]    = { 1, 1 },
+    [AV_PIX_FMT_BGR444LE]    = { 1, 1 },
+    [AV_PIX_FMT_BGR444BE]    = { 1, 1 },
+    [AV_PIX_FMT_Y400A]       = { 1, 0 },
+    [AV_PIX_FMT_BGR48BE]     = { 1, 1 },
+    [AV_PIX_FMT_BGR48LE]     = { 1, 1 },
+    [AV_PIX_FMT_BGRA64BE]    = { 0, 0 },
+    [AV_PIX_FMT_BGRA64LE]    = { 0, 0 },
+    [AV_PIX_FMT_YUV420P9BE]  = { 1, 1 },
+    [AV_PIX_FMT_YUV420P9LE]  = { 1, 1 },
+    [AV_PIX_FMT_YUV420P10BE] = { 1, 1 },
+    [AV_PIX_FMT_YUV420P10LE] = { 1, 1 },
+    [AV_PIX_FMT_YUV420P12BE] = { 1, 1 },
+    [AV_PIX_FMT_YUV420P12LE] = { 1, 1 },
+    [AV_PIX_FMT_YUV420P14BE] = { 1, 1 },
+    [AV_PIX_FMT_YUV420P14LE] = { 1, 1 },
+    [AV_PIX_FMT_YUV422P9BE]  = { 1, 1 },
+    [AV_PIX_FMT_YUV422P9LE]  = { 1, 1 },
+    [AV_PIX_FMT_YUV422P10BE] = { 1, 1 },
+    [AV_PIX_FMT_YUV422P10LE] = { 1, 1 },
+    [AV_PIX_FMT_YUV422P12BE] = { 1, 1 },
+    [AV_PIX_FMT_YUV422P12LE] = { 1, 1 },
+    [AV_PIX_FMT_YUV422P14BE] = { 1, 1 },
+    [AV_PIX_FMT_YUV422P14LE] = { 1, 1 },
+    [AV_PIX_FMT_YUV444P9BE]  = { 1, 1 },
+    [AV_PIX_FMT_YUV444P9LE]  = { 1, 1 },
+    [AV_PIX_FMT_YUV444P10BE] = { 1, 1 },
+    [AV_PIX_FMT_YUV444P10LE] = { 1, 1 },
+    [AV_PIX_FMT_YUV444P12BE] = { 1, 1 },
+    [AV_PIX_FMT_YUV444P12LE] = { 1, 1 },
+    [AV_PIX_FMT_YUV444P14BE] = { 1, 1 },
+    [AV_PIX_FMT_YUV444P14LE] = { 1, 1 },
+    [AV_PIX_FMT_GBRP]        = { 1, 0 },
+    [AV_PIX_FMT_GBRP9LE]     = { 1, 0 },
+    [AV_PIX_FMT_GBRP9BE]     = { 1, 0 },
+    [AV_PIX_FMT_GBRP10LE]    = { 1, 0 },
+    [AV_PIX_FMT_GBRP10BE]    = { 1, 0 },
+    [AV_PIX_FMT_GBRP12LE]    = { 1, 0 },
+    [AV_PIX_FMT_GBRP12BE]    = { 1, 0 },
+    [AV_PIX_FMT_GBRP14LE]    = { 1, 0 },
+    [AV_PIX_FMT_GBRP14BE]    = { 1, 0 },
+    [AV_PIX_FMT_GBRP16LE]    = { 1, 0 },
+    [AV_PIX_FMT_GBRP16BE]    = { 1, 0 },
 };
 
-int sws_isSupportedInput(enum PixelFormat pix_fmt)
+int sws_isSupportedInput(enum AVPixelFormat pix_fmt)
 {
-    return (unsigned)pix_fmt < PIX_FMT_NB ?
+    return (unsigned)pix_fmt < AV_PIX_FMT_NB ?
            format_entries[pix_fmt].is_supported_in : 0;
 }
 
-int sws_isSupportedOutput(enum PixelFormat pix_fmt)
+int sws_isSupportedOutput(enum AVPixelFormat pix_fmt)
 {
-    return (unsigned)pix_fmt < PIX_FMT_NB ?
+    return (unsigned)pix_fmt < AV_PIX_FMT_NB ?
            format_entries[pix_fmt].is_supported_out : 0;
 }
 
 extern const int32_t ff_yuv2rgb_coeffs[8][4];
 
 #if FF_API_SWS_FORMAT_NAME
-const char *sws_format_name(enum PixelFormat format)
+const char *sws_format_name(enum AVPixelFormat format)
 {
-    return av_get_pix_fmt_name(format);
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
+    if (desc)
+        return desc->name;
+    else
+        return "Unknown format";
 }
 #endif
 
@@ -226,7 +248,7 @@
     int minFilterSize;
     int64_t *filter    = NULL;
     int64_t *filter2   = NULL;
-    const int64_t fone = 1LL << 54;
+    const int64_t fone = 1LL << (54 - FFMIN(av_log2(srcW/dstW), 8));
     int ret            = -1;
 
     emms_c(); // FIXME should not be required but IS (even for non-MMX versions)
@@ -352,7 +374,7 @@
                                     (-12 * B - 48 * C) * d   +
                                       (8 * B + 24 * C) * (1 << 30);
                     }
-                    coeff *= fone >> (30 + 24);
+                    coeff /= (1LL<<54)/fone;
                 }
 #if 0
                 else if (flags & SWS_X) {
@@ -509,8 +531,10 @@
     av_assert0(filterSize > 0);
     filter = av_malloc(filterSize * dstW * sizeof(*filter));
     if (filterSize >= MAX_FILTER_SIZE * 16 /
-                      ((flags & SWS_ACCURATE_RND) ? APCK_SIZE : 16) || !filter)
+                      ((flags & SWS_ACCURATE_RND) ? APCK_SIZE : 16) || !filter) {
+        av_log(NULL, AV_LOG_ERROR, "sws: filterSize %d is too large, try less extreem scaling or increase MAX_FILTER_SIZE and recompile\n", filterSize);
         goto fail;
+    }
     *outFilterSize = filterSize;
 
     if (flags & SWS_PRINT_INFO)
@@ -595,14 +619,17 @@
     ret = 0;
 
 fail:
+    if(ret < 0)
+        av_log(NULL, AV_LOG_ERROR, "sws: initFilter failed\n");
     av_free(filter);
     av_free(filter2);
     return ret;
 }
 
 #if HAVE_MMXEXT_INLINE
-static int initMMX2HScaler(int dstW, int xInc, uint8_t *filterCode,
-                           int16_t *filter, int32_t *filterPos, int numSplits)
+static int init_hscaler_mmxext(int dstW, int xInc, uint8_t *filterCode,
+                               int16_t *filter, int32_t *filterPos,
+                               int numSplits)
 {
     uint8_t *fragmentA;
     x86_reg imm8OfPShufW1A;
@@ -617,7 +644,7 @@
     int xpos, i;
 
     // create an optimized horizontal scaling routine
-    /* This scaler is made of runtime-generated MMX2 code using specially tuned
+    /* This scaler is made of runtime-generated MMXEXT code using specially tuned
      * pshufw instructions. For every four output pixels, if four input pixels
      * are enough for the fast bilinear scaling, then a chunk of fragmentB is
      * used. If five input pixels are needed, then a chunk of fragmentA is used.
@@ -765,29 +792,38 @@
 }
 #endif /* HAVE_MMXEXT_INLINE */
 
-static void getSubSampleFactors(int *h, int *v, enum PixelFormat format)
+static void getSubSampleFactors(int *h, int *v, enum AVPixelFormat format)
 {
-    *h = av_pix_fmt_descriptors[format].log2_chroma_w;
-    *v = av_pix_fmt_descriptors[format].log2_chroma_h;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
+    *h = desc->log2_chroma_w;
+    *v = desc->log2_chroma_h;
 }
 
 int sws_setColorspaceDetails(struct SwsContext *c, const int inv_table[4],
                              int srcRange, const int table[4], int dstRange,
                              int brightness, int contrast, int saturation)
 {
+    const AVPixFmtDescriptor *desc_dst = av_pix_fmt_desc_get(c->dstFormat);
+    const AVPixFmtDescriptor *desc_src = av_pix_fmt_desc_get(c->srcFormat);
     memcpy(c->srcColorspaceTable, inv_table, sizeof(int) * 4);
     memcpy(c->dstColorspaceTable, table, sizeof(int) * 4);
 
+    if(!isYUV(c->dstFormat) && !isGray(c->dstFormat))
+        dstRange = 0;
+    if(!isYUV(c->srcFormat) && !isGray(c->srcFormat))
+        srcRange = 0;
+
     c->brightness = brightness;
     c->contrast   = contrast;
     c->saturation = saturation;
     c->srcRange   = srcRange;
     c->dstRange   = dstRange;
+
     if (isYUV(c->dstFormat) || isGray(c->dstFormat))
         return -1;
 
-    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->dstFormatBpp = av_get_bits_per_pixel(desc_dst);
+    c->srcFormatBpp = av_get_bits_per_pixel(desc_src);
 
     ff_yuv2rgb_c_init_tables(c, inv_table, srcRange, brightness,
                              contrast, saturation);
@@ -817,33 +853,33 @@
     return 0;
 }
 
-static int handle_jpeg(enum PixelFormat *format)
+static int handle_jpeg(enum AVPixelFormat *format)
 {
     switch (*format) {
-    case PIX_FMT_YUVJ420P:
-        *format = PIX_FMT_YUV420P;
+    case AV_PIX_FMT_YUVJ420P:
+        *format = AV_PIX_FMT_YUV420P;
         return 1;
-    case PIX_FMT_YUVJ422P:
-        *format = PIX_FMT_YUV422P;
+    case AV_PIX_FMT_YUVJ422P:
+        *format = AV_PIX_FMT_YUV422P;
         return 1;
-    case PIX_FMT_YUVJ444P:
-        *format = PIX_FMT_YUV444P;
+    case AV_PIX_FMT_YUVJ444P:
+        *format = AV_PIX_FMT_YUV444P;
         return 1;
-    case PIX_FMT_YUVJ440P:
-        *format = PIX_FMT_YUV440P;
+    case AV_PIX_FMT_YUVJ440P:
+        *format = AV_PIX_FMT_YUV440P;
         return 1;
     default:
         return 0;
     }
 }
 
-static int handle_0alpha(enum PixelFormat *format)
+static int handle_0alpha(enum AVPixelFormat *format)
 {
     switch (*format) {
-    case PIX_FMT_0BGR    : *format = PIX_FMT_ABGR   ; return 1;
-    case PIX_FMT_BGR0    : *format = PIX_FMT_BGRA   ; return 4;
-    case PIX_FMT_0RGB    : *format = PIX_FMT_ARGB   ; return 1;
-    case PIX_FMT_RGB0    : *format = PIX_FMT_RGBA   ; return 4;
+    case AV_PIX_FMT_0BGR    : *format = AV_PIX_FMT_ABGR   ; return 1;
+    case AV_PIX_FMT_BGR0    : *format = AV_PIX_FMT_BGRA   ; return 4;
+    case AV_PIX_FMT_0RGB    : *format = AV_PIX_FMT_ARGB   ; return 1;
+    case AV_PIX_FMT_RGB0    : *format = AV_PIX_FMT_RGBA   ; return 4;
     default:                                          return 0;
     }
 }
@@ -871,8 +907,10 @@
     int dstH              = c->dstH;
     int dst_stride        = FFALIGN(dstW * sizeof(int16_t) + 66, 16);
     int flags, cpu_flags;
-    enum PixelFormat srcFormat = c->srcFormat;
-    enum PixelFormat dstFormat = c->dstFormat;
+    enum AVPixelFormat srcFormat = c->srcFormat;
+    enum AVPixelFormat dstFormat = c->dstFormat;
+    const AVPixFmtDescriptor *desc_src = av_pix_fmt_desc_get(srcFormat);
+    const AVPixFmtDescriptor *desc_dst = av_pix_fmt_desc_get(dstFormat);
 
     cpu_flags = av_get_cpu_flags();
     flags     = c->flags;
@@ -920,7 +958,7 @@
         return AVERROR(EINVAL);
     }
     /* sanity check */
-    if (srcW < 4 || srcH < 1 || dstW < 8 || dstH < 1) {
+    if (srcW < 1 || srcH < 1 || dstW < 1 || dstH < 1) {
         /* FIXME check if these are enough and try to lower them after
          * fixing the relevant parts of the code */
         av_log(c, AV_LOG_ERROR, "%dx%d -> %dx%d is invalid scaling dimension\n",
@@ -935,8 +973,8 @@
 
     c->lumXInc      = (((int64_t)srcW << 16) + (dstW >> 1)) / dstW;
     c->lumYInc      = (((int64_t)srcH << 16) + (dstH >> 1)) / dstH;
-    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->dstFormatBpp = av_get_bits_per_pixel(desc_dst);
+    c->srcFormatBpp = av_get_bits_per_pixel(desc_src);
     c->vRounder     = 4 * 0x0001000100010001ULL;
 
     usesVFilter = (srcFilter->lumV && srcFilter->lumV->length > 1) ||
@@ -963,12 +1001,12 @@
      * chroma interpolation */
     if (flags & SWS_FULL_CHR_H_INT &&
         isAnyRGB(dstFormat)        &&
-        dstFormat != PIX_FMT_RGBA  &&
-        dstFormat != PIX_FMT_ARGB  &&
-        dstFormat != PIX_FMT_BGRA  &&
-        dstFormat != PIX_FMT_ABGR  &&
-        dstFormat != PIX_FMT_RGB24 &&
-        dstFormat != PIX_FMT_BGR24) {
+        dstFormat != AV_PIX_FMT_RGBA  &&
+        dstFormat != AV_PIX_FMT_ARGB  &&
+        dstFormat != AV_PIX_FMT_BGRA  &&
+        dstFormat != AV_PIX_FMT_ABGR  &&
+        dstFormat != AV_PIX_FMT_RGB24 &&
+        dstFormat != AV_PIX_FMT_BGR24) {
         av_log(c, AV_LOG_WARNING,
                "full chroma interpolation for destination format '%s' not yet implemented\n",
                av_get_pix_fmt_name(dstFormat));
@@ -986,9 +1024,9 @@
     /* drop every other pixel for chroma calculation unless user
      * wants full chroma */
     if (isAnyRGB(srcFormat) && !(flags & SWS_FULL_CHR_H_INP)   &&
-        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 &&
+        srcFormat != AV_PIX_FMT_RGB8 && srcFormat != AV_PIX_FMT_BGR8 &&
+        srcFormat != AV_PIX_FMT_RGB4 && srcFormat != AV_PIX_FMT_BGR4 &&
+        srcFormat != AV_PIX_FMT_RGB4_BYTE && srcFormat != AV_PIX_FMT_BGR4_BYTE &&
         ((dstW >> c->chrDstHSubSample) <= (srcW >> 1) ||
          (flags & SWS_FAST_BILINEAR)))
         c->chrSrcHSubSample = 1;
@@ -1015,29 +1053,31 @@
         }
     }
 
-    c->srcBpc = 1 + av_pix_fmt_descriptors[srcFormat].comp[0].depth_minus1;
+    c->srcBpc = 1 + desc_src->comp[0].depth_minus1;
     if (c->srcBpc < 8)
         c->srcBpc = 8;
-    c->dstBpc = 1 + av_pix_fmt_descriptors[dstFormat].comp[0].depth_minus1;
+    c->dstBpc = 1 + desc_dst->comp[0].depth_minus1;
     if (c->dstBpc < 8)
         c->dstBpc = 8;
-    if (isAnyRGB(srcFormat) || srcFormat == PIX_FMT_PAL8)
+    if (isAnyRGB(srcFormat) || srcFormat == AV_PIX_FMT_PAL8)
         c->srcBpc = 16;
     if (c->dstBpc == 16)
         dst_stride <<= 1;
+
     if (INLINE_MMXEXT(cpu_flags) && c->srcBpc == 8 && c->dstBpc <= 14) {
-        c->canMMX2BeUsed = (dstW >= srcW && (dstW & 31) == 0 &&
-                            (srcW & 15) == 0) ? 1 : 0;
-        if (!c->canMMX2BeUsed && dstW >= srcW && (srcW & 15) == 0
+        c->canMMXEXTBeUsed = (dstW >= srcW && (dstW & 31) == 0 &&
+                              (srcW & 15) == 0) ? 1 : 0;
+        if (!c->canMMXEXTBeUsed && dstW >= srcW && (srcW & 15) == 0
+
             && (flags & SWS_FAST_BILINEAR)) {
             if (flags & SWS_PRINT_INFO)
                 av_log(c, AV_LOG_INFO,
-                       "output width is not a multiple of 32 -> no MMX2 scaler\n");
+                       "output width is not a multiple of 32 -> no MMXEXT scaler\n");
         }
         if (usesHFilter || isNBPS(c->srcFormat) || is16BPS(c->srcFormat) || isAnyRGB(c->srcFormat))
-            c->canMMX2BeUsed=0;
+            c->canMMXEXTBeUsed = 0;
     } else
-        c->canMMX2BeUsed = 0;
+        c->canMMXEXTBeUsed = 0;
 
     c->chrXInc = (((int64_t)c->chrSrcW << 16) + (c->chrDstW >> 1)) / c->chrDstW;
     c->chrYInc = (((int64_t)c->chrSrcH << 16) + (c->chrDstH >> 1)) / c->chrDstH;
@@ -1050,7 +1090,7 @@
      * correct variant would be like the vertical one, but that would require
      * some special code for the first and last pixel */
     if (flags & SWS_FAST_BILINEAR) {
-        if (c->canMMX2BeUsed) {
+        if (c->canMMXEXTBeUsed) {
             c->lumXInc += 20;
             c->chrXInc += 20;
         }
@@ -1061,31 +1101,45 @@
         }
     }
 
+#define USE_MMAP (HAVE_MMAP && HAVE_MPROTECT && defined MAP_ANONYMOUS)
+
     /* precalculate horizontal scaler filter coefficients */
     {
 #if HAVE_MMXEXT_INLINE
 // can't downscale !!!
-        if (c->canMMX2BeUsed && (flags & SWS_FAST_BILINEAR)) {
-            c->lumMmx2FilterCodeSize = initMMX2HScaler(dstW, c->lumXInc, NULL,
-                                                       NULL, NULL, 8);
-            c->chrMmx2FilterCodeSize = initMMX2HScaler(c->chrDstW, c->chrXInc,
-                                                       NULL, NULL, NULL, 4);
+        if (c->canMMXEXTBeUsed && (flags & SWS_FAST_BILINEAR)) {
+            c->lumMmxextFilterCodeSize = init_hscaler_mmxext(dstW, c->lumXInc, NULL,
+                                                             NULL, NULL, 8);
+            c->chrMmxextFilterCodeSize = init_hscaler_mmxext(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, -1, 0);
-            c->chrMmx2FilterCode = mmap(NULL, c->chrMmx2FilterCodeSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+#if USE_MMAP
+            c->lumMmxextFilterCode = mmap(NULL, c->lumMmxextFilterCodeSize,
+                                          PROT_READ | PROT_WRITE,
+                                          MAP_PRIVATE | MAP_ANONYMOUS,
+                                          -1, 0);
+            c->chrMmxextFilterCode = mmap(NULL, c->chrMmxextFilterCodeSize,
+                                          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);
+            c->lumMmxextFilterCode = VirtualAlloc(NULL,
+                                                  c->lumMmxextFilterCodeSize,
+                                                  MEM_COMMIT,
+                                                  PAGE_EXECUTE_READWRITE);
+            c->chrMmxextFilterCode = VirtualAlloc(NULL,
+                                                  c->chrMmxextFilterCodeSize,
+                                                  MEM_COMMIT,
+                                                  PAGE_EXECUTE_READWRITE);
 #else
-            c->lumMmx2FilterCode = av_malloc(c->lumMmx2FilterCodeSize);
-            c->chrMmx2FilterCode = av_malloc(c->chrMmx2FilterCodeSize);
+            c->lumMmxextFilterCode = av_malloc(c->lumMmxextFilterCodeSize);
+            c->chrMmxextFilterCode = av_malloc(c->chrMmxextFilterCodeSize);
 #endif
 
 #ifdef MAP_ANONYMOUS
-            if (c->lumMmx2FilterCode == MAP_FAILED || c->chrMmx2FilterCode == MAP_FAILED)
+            if (c->lumMmxextFilterCode == MAP_FAILED || c->chrMmxextFilterCode == MAP_FAILED)
 #else
-            if (!c->lumMmx2FilterCode || !c->chrMmx2FilterCode)
+            if (!c->lumMmxextFilterCode || !c->chrMmxextFilterCode)
 #endif
             {
                 av_log(c, AV_LOG_ERROR, "Failed to allocate MMX2FilterCode\n");
@@ -1097,14 +1151,14 @@
             FF_ALLOCZ_OR_GOTO(c, c->hLumFilterPos, (dstW       / 2 / 8 + 8) * sizeof(int32_t), fail);
             FF_ALLOCZ_OR_GOTO(c, c->hChrFilterPos, (c->chrDstW / 2 / 4 + 8) * sizeof(int32_t), fail);
 
-            initMMX2HScaler(      dstW, c->lumXInc, c->lumMmx2FilterCode,
-                            c->hLumFilter, (uint32_t*)c->hLumFilterPos, 8);
-            initMMX2HScaler(c->chrDstW, c->chrXInc, c->chrMmx2FilterCode,
-                            c->hChrFilter, (uint32_t*)c->hChrFilterPos, 4);
+            init_hscaler_mmxext(      dstW, c->lumXInc, c->lumMmxextFilterCode,
+                                c->hLumFilter, (uint32_t*)c->hLumFilterPos, 8);
+            init_hscaler_mmxext(c->chrDstW, c->chrXInc, c->chrMmxextFilterCode,
+                                c->hChrFilter, (uint32_t*)c->hChrFilterPos, 4);
 
-#ifdef MAP_ANONYMOUS
-            mprotect(c->lumMmx2FilterCode, c->lumMmx2FilterCodeSize, PROT_EXEC | PROT_READ);
-            mprotect(c->chrMmx2FilterCode, c->chrMmx2FilterCodeSize, PROT_EXEC | PROT_READ);
+#if USE_MMAP
+            mprotect(c->lumMmxextFilterCode, c->lumMmxextFilterCodeSize, PROT_EXEC | PROT_READ);
+            mprotect(c->chrMmxextFilterCode, c->chrMmxextFilterCodeSize, PROT_EXEC | PROT_READ);
 #endif
         } else
 #endif /* HAVE_MMXEXT_INLINE */
@@ -1225,7 +1279,7 @@
 
     // try to avoid drawing green stuff between the right end and the stride end
     for (i = 0; i < c->vChrBufSize; i++)
-        if(av_pix_fmt_descriptors[c->dstFormat].comp[0].depth_minus1 == 15){
+        if(desc_dst->comp[0].depth_minus1 == 15){
             av_assert0(c->dstBpc > 14);
             for(j=0; j<dst_stride/2+1; j++)
                 ((int32_t*)(c->chrUPixBuf[i]))[j] = 1<<18;
@@ -1264,9 +1318,9 @@
         av_log(c, AV_LOG_INFO, "from %s to %s%s ",
                av_get_pix_fmt_name(srcFormat),
 #ifdef DITHER1XBPP
-               dstFormat == PIX_FMT_BGR555   || dstFormat == PIX_FMT_BGR565   ||
-               dstFormat == PIX_FMT_RGB444BE || dstFormat == PIX_FMT_RGB444LE ||
-               dstFormat == PIX_FMT_BGR444BE || dstFormat == PIX_FMT_BGR444LE ?
+               dstFormat == AV_PIX_FMT_BGR555   || dstFormat == AV_PIX_FMT_BGR565   ||
+               dstFormat == AV_PIX_FMT_RGB444BE || dstFormat == AV_PIX_FMT_RGB444LE ||
+               dstFormat == AV_PIX_FMT_BGR444BE || dstFormat == AV_PIX_FMT_BGR444LE ?
                                                              "dithered " : "",
 #else
                "",
@@ -1274,7 +1328,7 @@
                av_get_pix_fmt_name(dstFormat));
 
         if (INLINE_MMXEXT(cpu_flags))
-            av_log(c, AV_LOG_INFO, "using MMX2\n");
+            av_log(c, AV_LOG_INFO, "using MMXEXT\n");
         else if (INLINE_AMD3DNOW(cpu_flags))
             av_log(c, AV_LOG_INFO, "using 3DNOW\n");
         else if (INLINE_MMX(cpu_flags))
@@ -1301,8 +1355,8 @@
 }
 
 #if FF_API_SWS_GETCONTEXT
-SwsContext *sws_getContext(int srcW, int srcH, enum PixelFormat srcFormat,
-                           int dstW, int dstH, enum PixelFormat dstFormat,
+SwsContext *sws_getContext(int srcW, int srcH, enum AVPixelFormat srcFormat,
+                           int dstW, int dstH, enum AVPixelFormat dstFormat,
                            int flags, SwsFilter *srcFilter,
                            SwsFilter *dstFilter, const double *param)
 {
@@ -1404,7 +1458,12 @@
 
 SwsVector *sws_allocVec(int length)
 {
-    SwsVector *vec = av_malloc(sizeof(SwsVector));
+    SwsVector *vec;
+
+    if(length <= 0 || length > INT_MAX/ sizeof(double))
+        return NULL;
+
+    vec = av_malloc(sizeof(SwsVector));
     if (!vec)
         return NULL;
     vec->length = length;
@@ -1419,7 +1478,12 @@
     const int length = (int)(variance * quality + 0.5) | 1;
     int i;
     double middle  = (length - 1) * 0.5;
-    SwsVector *vec = sws_allocVec(length);
+    SwsVector *vec;
+
+    if(variance < 0 || quality < 0)
+        return NULL;
+
+    vec = sws_allocVec(length);
 
     if (!vec)
         return NULL;
@@ -1689,22 +1753,22 @@
     av_freep(&c->hChrFilterPos);
 
 #if HAVE_MMX_INLINE
-#ifdef MAP_ANONYMOUS
-    if (c->lumMmx2FilterCode)
-        munmap(c->lumMmx2FilterCode, c->lumMmx2FilterCodeSize);
-    if (c->chrMmx2FilterCode)
-        munmap(c->chrMmx2FilterCode, c->chrMmx2FilterCodeSize);
+#if USE_MMAP
+    if (c->lumMmxextFilterCode)
+        munmap(c->lumMmxextFilterCode, c->lumMmxextFilterCodeSize);
+    if (c->chrMmxextFilterCode)
+        munmap(c->chrMmxextFilterCode, c->chrMmxextFilterCodeSize);
 #elif HAVE_VIRTUALALLOC
-    if (c->lumMmx2FilterCode)
-        VirtualFree(c->lumMmx2FilterCode, 0, MEM_RELEASE);
-    if (c->chrMmx2FilterCode)
-        VirtualFree(c->chrMmx2FilterCode, 0, MEM_RELEASE);
+    if (c->lumMmxextFilterCode)
+        VirtualFree(c->lumMmxextFilterCode, 0, MEM_RELEASE);
+    if (c->chrMmxextFilterCode)
+        VirtualFree(c->chrMmxextFilterCode, 0, MEM_RELEASE);
 #else
-    av_free(c->lumMmx2FilterCode);
-    av_free(c->chrMmx2FilterCode);
+    av_free(c->lumMmxextFilterCode);
+    av_free(c->chrMmxextFilterCode);
 #endif
-    c->lumMmx2FilterCode = NULL;
-    c->chrMmx2FilterCode = NULL;
+    c->lumMmxextFilterCode = NULL;
+    c->chrMmxextFilterCode = NULL;
 #endif /* HAVE_MMX_INLINE */
 
     av_freep(&c->yuvTable);
@@ -1714,9 +1778,9 @@
 }
 
 struct SwsContext *sws_getCachedContext(struct SwsContext *context, int srcW,
-                                        int srcH, enum PixelFormat srcFormat,
+                                        int srcH, enum AVPixelFormat srcFormat,
                                         int dstW, int dstH,
-                                        enum PixelFormat dstFormat, int flags,
+                                        enum AVPixelFormat dstFormat, int flags,
                                         SwsFilter *srcFilter,
                                         SwsFilter *dstFilter,
                                         const double *param)
diff --git a/libswscale/version.h b/libswscale/version.h
index 37dcc96..49e280d 100644
--- a/libswscale/version.h
+++ b/libswscale/version.h
@@ -28,7 +28,7 @@
 
 #define LIBSWSCALE_VERSION_MAJOR 2
 #define LIBSWSCALE_VERSION_MINOR 1
-#define LIBSWSCALE_VERSION_MICRO 101
+#define LIBSWSCALE_VERSION_MICRO 103
 
 #define LIBSWSCALE_VERSION_INT  AV_VERSION_INT(LIBSWSCALE_VERSION_MAJOR, \
                                                LIBSWSCALE_VERSION_MINOR, \
diff --git a/libswscale/x86/input.asm b/libswscale/x86/input.asm
index 0124c66..327b9f0 100644
--- a/libswscale/x86/input.asm
+++ b/libswscale/x86/input.asm
@@ -21,8 +21,7 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "x86inc.asm"
-%include "x86util.asm"
+%include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
 
diff --git a/libswscale/x86/output.asm b/libswscale/x86/output.asm
index 851165a..f9add35 100644
--- a/libswscale/x86/output.asm
+++ b/libswscale/x86/output.asm
@@ -20,8 +20,7 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "x86inc.asm"
-%include "x86util.asm"
+%include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
 
@@ -188,7 +187,7 @@
 %else ; %1 == 10/9/8
     punpcklwd       m5,  m3,  m4
     punpckhwd       m3,  m4
-    SPLATD          m0,  m0
+    SPLATD          m0
 
     pmaddwd         m5,  m0
     pmaddwd         m3,  m0
@@ -219,10 +218,10 @@
 %else ; %1 == 9/10
 %if cpuflag(sse4)
     packusdw        m2,  m1
-%else ; mmx2/sse2
+%else ; mmxext/sse2
     packssdw        m2,  m1
     pmaxsw          m2,  m6
-%endif ; mmx2/sse2/sse4/avx
+%endif ; mmxext/sse2/sse4/avx
     pminsw          m2, [yuv2yuvX_%1_upper]
 %endif ; %1 == 9/10/16
     mova   [dstq+r5*2],  m2
@@ -247,9 +246,8 @@
 %endif ; %1 == 8/9/10/16
 %endmacro
 
-%define PALIGNR PALIGNR_MMX
 %if ARCH_X86_32
-INIT_MMX mmx2
+INIT_MMX mmxext
 yuv2planeX_fn  8,  0, 7
 yuv2planeX_fn  9,  0, 5
 yuv2planeX_fn 10,  0, 5
@@ -260,7 +258,6 @@
 yuv2planeX_fn  9,  7, 5
 yuv2planeX_fn 10,  7, 5
 
-%define PALIGNR PALIGNR_SSSE3
 INIT_XMM sse4
 yuv2planeX_fn  8, 10, 7
 yuv2planeX_fn  9,  7, 5
@@ -347,7 +344,7 @@
 %if mmsize == 16
     punpcklqdq      m3, m3
 %endif ; mmsize == 16
-    PALIGNR_MMX     m3, m3, 3, m2
+    PALIGNR         m3, m3, 3, m2
 .no_rot:
 %if mmsize == 8
     mova            m2, m3
@@ -393,7 +390,7 @@
 yuv2plane1_fn  8, 0, 5
 yuv2plane1_fn 16, 0, 3
 
-INIT_MMX mmx2
+INIT_MMX mmxext
 yuv2plane1_fn  9, 0, 3
 yuv2plane1_fn 10, 0, 3
 %endif
diff --git a/libswscale/x86/rgb2rgb.c b/libswscale/x86/rgb2rgb.c
index 83734a2..1e20176 100644
--- a/libswscale/x86/rgb2rgb.c
+++ b/libswscale/x86/rgb2rgb.c
@@ -87,7 +87,7 @@
 #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.
+// Note: We have C, MMX, MMXEXT, 3DNOW versions, there is no 3DNOW + MMXEXT one.
 
 #define COMPILE_TEMPLATE_MMXEXT 0
 #define COMPILE_TEMPLATE_AMD3DNOW 0
@@ -98,11 +98,11 @@
 #define RENAME(a) a ## _MMX
 #include "rgb2rgb_template.c"
 
-//MMX2 versions
+// MMXEXT versions
 #undef RENAME
 #undef COMPILE_TEMPLATE_MMXEXT
 #define COMPILE_TEMPLATE_MMXEXT 1
-#define RENAME(a) a ## _MMX2
+#define RENAME(a) a ## _MMXEXT
 #include "rgb2rgb_template.c"
 
 //SSE2 versions
@@ -126,7 +126,7 @@
 /*
  RGB15->RGB16 original by Strepto/Astral
  ported to gcc & bugfixed : A'rpi
- MMX2, 3DNOW optimization by Nick Kurshev
+ MMXEXT, 3DNOW optimization by Nick Kurshev
  32-bit C version, and and&add trick by Michael Niedermayer
 */
 
@@ -142,7 +142,7 @@
     if (INLINE_AMD3DNOW(cpu_flags))
         rgb2rgb_init_3DNOW();
     if (INLINE_MMXEXT(cpu_flags))
-        rgb2rgb_init_MMX2();
+        rgb2rgb_init_MMXEXT();
     if (INLINE_SSE2(cpu_flags))
         rgb2rgb_init_SSE2();
 #endif /* HAVE_INLINE_ASM */
diff --git a/libswscale/x86/rgb2rgb_template.c b/libswscale/x86/rgb2rgb_template.c
index 6584249..d802ab4 100644
--- a/libswscale/x86/rgb2rgb_template.c
+++ b/libswscale/x86/rgb2rgb_template.c
@@ -178,7 +178,7 @@
 /*
  original by Strepto/Astral
  ported to gcc & bugfixed: A'rpi
- MMX2, 3DNOW optimization by Nick Kurshev
+ MMXEXT, 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, int src_size)
diff --git a/libswscale/x86/scale.asm b/libswscale/x86/scale.asm
index 6282ab2..c6dafde 100644
--- a/libswscale/x86/scale.asm
+++ b/libswscale/x86/scale.asm
@@ -19,8 +19,7 @@
 ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;******************************************************************************
 
-%include "x86inc.asm"
-%include "x86util.asm"
+%include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
 
diff --git a/libswscale/x86/swscale.c b/libswscale/x86/swscale.c
index de59a2b..02c454e 100644
--- a/libswscale/x86/swscale.c
+++ b/libswscale/x86/swscale.c
@@ -80,12 +80,12 @@
 #include "swscale_template.c"
 #endif
 
-//MMX2 versions
+// MMXEXT versions
 #if HAVE_MMXEXT_INLINE
 #undef RENAME
 #undef COMPILE_TEMPLATE_MMXEXT
 #define COMPILE_TEMPLATE_MMXEXT 1
-#define RENAME(a) a ## _MMX2
+#define RENAME(a) a ## _MMXEXT
 #include "swscale_template.c"
 #endif
 
@@ -113,7 +113,7 @@
     const int firstChrSrcY= vChrFilterPos[chrDstY]; //First line needed as input
 
     c->blueDither= ff_dither8[dstY&1];
-    if (c->dstFormat == PIX_FMT_RGB555 || c->dstFormat == PIX_FMT_BGR555)
+    if (c->dstFormat == AV_PIX_FMT_RGB555 || c->dstFormat == AV_PIX_FMT_BGR555)
         c->greenDither= ff_dither8[dstY&1];
     else
         c->greenDither= ff_dither4[dstY&1];
@@ -211,7 +211,7 @@
                            const uint8_t *dither, int offset)
 {
     if(((int)dest) & 15){
-        return yuv2yuvX_MMX2(filter, filterSize, src, dest, dstW, dither, offset);
+        return yuv2yuvX_MMXEXT(filter, filterSize, src, dest, dstW, dither, offset);
     }
     if (offset) {
         __asm__ volatile("movq       (%0), %%xmm3\n\t"
@@ -317,7 +317,7 @@
     VSCALEX_FUNC(10, opt)
 
 #if ARCH_X86_32
-VSCALEX_FUNCS(mmx2);
+VSCALEX_FUNCS(mmxext);
 #endif
 VSCALEX_FUNCS(sse2);
 VSCALEX_FUNCS(sse4);
@@ -334,7 +334,7 @@
     VSCALE_FUNC(16, opt1)
 
 #if ARCH_X86_32
-VSCALE_FUNCS(mmx, mmx2);
+VSCALE_FUNCS(mmx, mmxext);
 #endif
 VSCALE_FUNCS(sse2, sse2);
 VSCALE_FUNC(16, sse4);
@@ -381,7 +381,7 @@
         sws_init_swScale_MMX(c);
 #if HAVE_MMXEXT_INLINE
     if (cpu_flags & AV_CPU_FLAG_MMXEXT)
-        sws_init_swScale_MMX2(c);
+        sws_init_swScale_MMXEXT(c);
     if (cpu_flags & AV_CPU_FLAG_SSE3){
         if(c->use_mmx_vfilter && !(c->flags & SWS_ACCURATE_RND))
             c->yuv2planeX = yuv2yuvX_sse3;
@@ -402,7 +402,7 @@
     } else if (c->srcBpc == 12) { \
         hscalefn = c->dstBpc <= 14 ? ff_hscale12to15_ ## filtersize ## _ ## opt2 : \
                                      ff_hscale12to19_ ## filtersize ## _ ## opt1; \
-    } else if (c->srcBpc == 14 || ((c->srcFormat==PIX_FMT_PAL8||isAnyRGB(c->srcFormat)) && av_pix_fmt_descriptors[c->srcFormat].comp[0].depth_minus1<15)) { \
+    } else if (c->srcBpc == 14 || ((c->srcFormat==AV_PIX_FMT_PAL8||isAnyRGB(c->srcFormat)) && av_pix_fmt_desc_get(c->srcFormat)->comp[0].depth_minus1<15)) { \
         hscalefn = c->dstBpc <= 14 ? ff_hscale14to15_ ## filtersize ## _ ## opt2 : \
                                      ff_hscale14to19_ ## filtersize ## _ ## opt1; \
     } else { /* c->srcBpc == 16 */ \
@@ -433,7 +433,7 @@
     default: av_assert0(c->dstBpc>8); \
     }
 #define case_rgb(x, X, opt) \
-        case PIX_FMT_ ## X: \
+        case AV_PIX_FMT_ ## X: \
             c->lumToYV12 = ff_ ## x ## ToY_ ## opt; \
             if (!c->chrSrcHSubSample) \
                 c->chrToYV12 = ff_ ## x ## ToUV_ ## opt; \
@@ -442,26 +442,26 @@
     if (EXTERNAL_MMX(cpu_flags)) {
         ASSIGN_MMX_SCALE_FUNC(c->hyScale, c->hLumFilterSize, mmx, mmx);
         ASSIGN_MMX_SCALE_FUNC(c->hcScale, c->hChrFilterSize, mmx, mmx);
-        ASSIGN_VSCALE_FUNC(c->yuv2plane1, mmx, mmx2, cpu_flags & AV_CPU_FLAG_MMXEXT);
+        ASSIGN_VSCALE_FUNC(c->yuv2plane1, mmx, mmxext, cpu_flags & AV_CPU_FLAG_MMXEXT);
 
         switch (c->srcFormat) {
-        case PIX_FMT_Y400A:
+        case AV_PIX_FMT_Y400A:
             c->lumToYV12 = ff_yuyvToY_mmx;
             if (c->alpPixBuf)
                 c->alpToYV12 = ff_uyvyToY_mmx;
             break;
-        case PIX_FMT_YUYV422:
+        case AV_PIX_FMT_YUYV422:
             c->lumToYV12 = ff_yuyvToY_mmx;
             c->chrToYV12 = ff_yuyvToUV_mmx;
             break;
-        case PIX_FMT_UYVY422:
+        case AV_PIX_FMT_UYVY422:
             c->lumToYV12 = ff_uyvyToY_mmx;
             c->chrToYV12 = ff_uyvyToUV_mmx;
             break;
-        case PIX_FMT_NV12:
+        case AV_PIX_FMT_NV12:
             c->chrToYV12 = ff_nv12ToUV_mmx;
             break;
-        case PIX_FMT_NV21:
+        case AV_PIX_FMT_NV21:
             c->chrToYV12 = ff_nv21ToUV_mmx;
             break;
         case_rgb(rgb24, RGB24, mmx);
@@ -475,7 +475,7 @@
         }
     }
     if (EXTERNAL_MMXEXT(cpu_flags)) {
-        ASSIGN_VSCALEX_FUNC(c->yuv2planeX, mmx2, , 1);
+        ASSIGN_VSCALEX_FUNC(c->yuv2planeX, mmxext, , 1);
     }
 #endif /* ARCH_X86_32 */
 #define ASSIGN_SSE_SCALE_FUNC(hscalefn, filtersize, opt1, opt2) \
@@ -494,23 +494,23 @@
         ASSIGN_VSCALE_FUNC(c->yuv2plane1, sse2, sse2, 1);
 
         switch (c->srcFormat) {
-        case PIX_FMT_Y400A:
+        case AV_PIX_FMT_Y400A:
             c->lumToYV12 = ff_yuyvToY_sse2;
             if (c->alpPixBuf)
                 c->alpToYV12 = ff_uyvyToY_sse2;
             break;
-        case PIX_FMT_YUYV422:
+        case AV_PIX_FMT_YUYV422:
             c->lumToYV12 = ff_yuyvToY_sse2;
             c->chrToYV12 = ff_yuyvToUV_sse2;
             break;
-        case PIX_FMT_UYVY422:
+        case AV_PIX_FMT_UYVY422:
             c->lumToYV12 = ff_uyvyToY_sse2;
             c->chrToYV12 = ff_uyvyToUV_sse2;
             break;
-        case PIX_FMT_NV12:
+        case AV_PIX_FMT_NV12:
             c->chrToYV12 = ff_nv12ToUV_sse2;
             break;
-        case PIX_FMT_NV21:
+        case AV_PIX_FMT_NV21:
             c->chrToYV12 = ff_nv21ToUV_sse2;
             break;
         case_rgb(rgb24, RGB24, sse2);
@@ -550,16 +550,16 @@
         ASSIGN_VSCALE_FUNC(c->yuv2plane1, avx, avx, 1);
 
         switch (c->srcFormat) {
-        case PIX_FMT_YUYV422:
+        case AV_PIX_FMT_YUYV422:
             c->chrToYV12 = ff_yuyvToUV_avx;
             break;
-        case PIX_FMT_UYVY422:
+        case AV_PIX_FMT_UYVY422:
             c->chrToYV12 = ff_uyvyToUV_avx;
             break;
-        case PIX_FMT_NV12:
+        case AV_PIX_FMT_NV12:
             c->chrToYV12 = ff_nv12ToUV_avx;
             break;
-        case PIX_FMT_NV21:
+        case AV_PIX_FMT_NV21:
             c->chrToYV12 = ff_nv21ToUV_avx;
             break;
         case_rgb(rgb24, RGB24, avx);
diff --git a/libswscale/x86/swscale_template.c b/libswscale/x86/swscale_template.c
index 370a0eb..62265db 100644
--- a/libswscale/x86/swscale_template.c
+++ b/libswscale/x86/swscale_template.c
@@ -593,7 +593,7 @@
     "cmp     "#dstw", "#index"  \n\t"\
     " jb          1b            \n\t"
 
-#define WRITEBGR24MMX2(dst, dstw, index) \
+#define WRITEBGR24MMXEXT(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"\
@@ -643,7 +643,7 @@
 
 #if COMPILE_TEMPLATE_MMXEXT
 #undef WRITEBGR24
-#define WRITEBGR24(dst, dstw, index)  WRITEBGR24MMX2(dst, dstw, index)
+#define WRITEBGR24(dst, dstw, index)  WRITEBGR24MMXEXT(dst, dstw, index)
 #else
 #undef WRITEBGR24
 #define WRITEBGR24(dst, dstw, index)  WRITEBGR24MMX(dst, dstw, index)
@@ -1452,7 +1452,7 @@
 {
     int32_t *filterPos = c->hLumFilterPos;
     int16_t *filter    = c->hLumFilter;
-    void    *mmx2FilterCode= c->lumMmx2FilterCode;
+    void    *mmxextFilterCode = c->lumMmxextFilterCode;
     int i;
 #if defined(PIC)
     uint64_t ebxsave;
@@ -1485,7 +1485,7 @@
         PREFETCH"      64(%%"REG_c")            \n\t"
 
 #if ARCH_X86_64
-#define CALL_MMX2_FILTER_CODE \
+#define CALL_MMXEXT_FILTER_CODE \
         "movl            (%%"REG_b"), %%esi     \n\t"\
         "call                    *%4            \n\t"\
         "movl (%%"REG_b", %%"REG_a"), %%esi     \n\t"\
@@ -1494,7 +1494,7 @@
         "xor               %%"REG_a", %%"REG_a" \n\t"\
 
 #else
-#define CALL_MMX2_FILTER_CODE \
+#define CALL_MMXEXT_FILTER_CODE \
         "movl (%%"REG_b"), %%esi        \n\t"\
         "call         *%4                       \n\t"\
         "addl (%%"REG_b", %%"REG_a"), %%"REG_c" \n\t"\
@@ -1503,14 +1503,14 @@
 
 #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
+        CALL_MMXEXT_FILTER_CODE
+        CALL_MMXEXT_FILTER_CODE
+        CALL_MMXEXT_FILTER_CODE
+        CALL_MMXEXT_FILTER_CODE
+        CALL_MMXEXT_FILTER_CODE
+        CALL_MMXEXT_FILTER_CODE
+        CALL_MMXEXT_FILTER_CODE
+        CALL_MMXEXT_FILTER_CODE
 
 #if defined(PIC)
         "mov                      %5, %%"REG_b" \n\t"
@@ -1525,7 +1525,7 @@
 #endif
 #endif
         :: "m" (src), "m" (dst), "m" (filter), "m" (filterPos),
-           "m" (mmx2FilterCode)
+           "m" (mmxextFilterCode)
 #if defined(PIC)
           ,"m" (ebxsave)
 #endif
@@ -1548,7 +1548,7 @@
 {
     int32_t *filterPos = c->hChrFilterPos;
     int16_t *filter    = c->hChrFilter;
-    void    *mmx2FilterCode= c->chrMmx2FilterCode;
+    void    *mmxextFilterCode = c->chrMmxextFilterCode;
     int i;
 #if defined(PIC)
     DECLARE_ALIGNED(8, uint64_t, ebxsave);
@@ -1580,10 +1580,10 @@
         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
+        CALL_MMXEXT_FILTER_CODE
+        CALL_MMXEXT_FILTER_CODE
+        CALL_MMXEXT_FILTER_CODE
+        CALL_MMXEXT_FILTER_CODE
         "xor          %%"REG_a", %%"REG_a"  \n\t" // i
         "mov                 %5, %%"REG_c"  \n\t" // src
         "mov                 %6, %%"REG_D"  \n\t" // buf2
@@ -1591,10 +1591,10 @@
         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
+        CALL_MMXEXT_FILTER_CODE
+        CALL_MMXEXT_FILTER_CODE
+        CALL_MMXEXT_FILTER_CODE
+        CALL_MMXEXT_FILTER_CODE
 
 #if defined(PIC)
         "mov %7, %%"REG_b"    \n\t"
@@ -1609,7 +1609,7 @@
 #endif
 #endif
         :: "m" (src1), "m" (dst1), "m" (filter), "m" (filterPos),
-           "m" (mmx2FilterCode), "m" (src2), "m"(dst2)
+           "m" (mmxextFilterCode), "m" (src2), "m"(dst2)
 #if defined(PIC)
           ,"m" (ebxsave)
 #endif
@@ -1631,19 +1631,19 @@
 
 static av_cold void RENAME(sws_init_swScale)(SwsContext *c)
 {
-    enum PixelFormat dstFormat = c->dstFormat;
+    enum AVPixelFormat dstFormat = c->dstFormat;
 
     c->use_mmx_vfilter= 0;
-    if (!is16BPS(dstFormat) && !is9_OR_10BPS(dstFormat) && dstFormat != PIX_FMT_NV12
-        && dstFormat != PIX_FMT_NV21 && !(c->flags & SWS_BITEXACT)) {
+    if (!is16BPS(dstFormat) && !is9_OR_10BPS(dstFormat) && dstFormat != AV_PIX_FMT_NV12
+        && dstFormat != AV_PIX_FMT_NV21 && !(c->flags & SWS_BITEXACT)) {
             if (c->flags & SWS_ACCURATE_RND) {
                 if (!(c->flags & SWS_FULL_CHR_H_INT)) {
                     switch (c->dstFormat) {
-                    case PIX_FMT_RGB32:   c->yuv2packedX = RENAME(yuv2rgb32_X_ar);   break;
-                    case PIX_FMT_BGR24:   c->yuv2packedX = RENAME(yuv2bgr24_X_ar);   break;
-                    case PIX_FMT_RGB555:  c->yuv2packedX = RENAME(yuv2rgb555_X_ar);  break;
-                    case PIX_FMT_RGB565:  c->yuv2packedX = RENAME(yuv2rgb565_X_ar);  break;
-                    case PIX_FMT_YUYV422: c->yuv2packedX = RENAME(yuv2yuyv422_X_ar); break;
+                    case AV_PIX_FMT_RGB32:   c->yuv2packedX = RENAME(yuv2rgb32_X_ar);   break;
+                    case AV_PIX_FMT_BGR24:   c->yuv2packedX = RENAME(yuv2bgr24_X_ar);   break;
+                    case AV_PIX_FMT_RGB555:  c->yuv2packedX = RENAME(yuv2rgb555_X_ar);  break;
+                    case AV_PIX_FMT_RGB565:  c->yuv2packedX = RENAME(yuv2rgb565_X_ar);  break;
+                    case AV_PIX_FMT_YUYV422: c->yuv2packedX = RENAME(yuv2yuyv422_X_ar); break;
                     default: break;
                     }
                 }
@@ -1652,34 +1652,34 @@
                 c->yuv2planeX = RENAME(yuv2yuvX    );
                 if (!(c->flags & SWS_FULL_CHR_H_INT)) {
                     switch (c->dstFormat) {
-                    case PIX_FMT_RGB32:   c->yuv2packedX = RENAME(yuv2rgb32_X);   break;
-                    case PIX_FMT_BGR24:   c->yuv2packedX = RENAME(yuv2bgr24_X);   break;
-                    case PIX_FMT_RGB555:  c->yuv2packedX = RENAME(yuv2rgb555_X);  break;
-                    case PIX_FMT_RGB565:  c->yuv2packedX = RENAME(yuv2rgb565_X);  break;
-                    case PIX_FMT_YUYV422: c->yuv2packedX = RENAME(yuv2yuyv422_X); break;
+                    case AV_PIX_FMT_RGB32:   c->yuv2packedX = RENAME(yuv2rgb32_X);   break;
+                    case AV_PIX_FMT_BGR24:   c->yuv2packedX = RENAME(yuv2bgr24_X);   break;
+                    case AV_PIX_FMT_RGB555:  c->yuv2packedX = RENAME(yuv2rgb555_X);  break;
+                    case AV_PIX_FMT_RGB565:  c->yuv2packedX = RENAME(yuv2rgb565_X);  break;
+                    case AV_PIX_FMT_YUYV422: c->yuv2packedX = RENAME(yuv2yuyv422_X); break;
                     default: break;
                     }
                 }
             }
         if (!(c->flags & SWS_FULL_CHR_H_INT)) {
             switch (c->dstFormat) {
-            case PIX_FMT_RGB32:
+            case AV_PIX_FMT_RGB32:
                 c->yuv2packed1 = RENAME(yuv2rgb32_1);
                 c->yuv2packed2 = RENAME(yuv2rgb32_2);
                 break;
-            case PIX_FMT_BGR24:
+            case AV_PIX_FMT_BGR24:
                 c->yuv2packed1 = RENAME(yuv2bgr24_1);
                 c->yuv2packed2 = RENAME(yuv2bgr24_2);
                 break;
-            case PIX_FMT_RGB555:
+            case AV_PIX_FMT_RGB555:
                 c->yuv2packed1 = RENAME(yuv2rgb555_1);
                 c->yuv2packed2 = RENAME(yuv2rgb555_2);
                 break;
-            case PIX_FMT_RGB565:
+            case AV_PIX_FMT_RGB565:
                 c->yuv2packed1 = RENAME(yuv2rgb565_1);
                 c->yuv2packed2 = RENAME(yuv2rgb565_2);
                 break;
-            case PIX_FMT_YUYV422:
+            case AV_PIX_FMT_YUYV422:
                 c->yuv2packed1 = RENAME(yuv2yuyv422_1);
                 c->yuv2packed2 = RENAME(yuv2yuyv422_2);
                 break;
@@ -1690,10 +1690,9 @@
     }
 
     if (c->srcBpc == 8 && c->dstBpc <= 14) {
-    // Use the new MMX scaler if the MMX2 one can't be used (it is faster than the x86 ASM one).
+    // Use the new MMX scaler if the MMXEXT one can't be used (it is faster than the x86 ASM one).
 #if COMPILE_TEMPLATE_MMXEXT
-    if (c->flags & SWS_FAST_BILINEAR && c->canMMX2BeUsed)
-    {
+    if (c->flags & SWS_FAST_BILINEAR && c->canMMXEXTBeUsed) {
         c->hyscale_fast = RENAME(hyscale_fast);
         c->hcscale_fast = RENAME(hcscale_fast);
     } else {
diff --git a/libswscale/x86/yuv2rgb.c b/libswscale/x86/yuv2rgb.c
index 9a9220d..3938e6b 100644
--- a/libswscale/x86/yuv2rgb.c
+++ b/libswscale/x86/yuv2rgb.c
@@ -3,7 +3,7 @@
  *
  * Copyright (C) 2009 Konstantin Shishkov
  *
- * MMX/MMX2 template stuff (needed for fast movntq support),
+ * MMX/MMXEXT template stuff (needed for fast movntq support),
  * 1,4,8bpp support and context / deglobalize stuff
  * by Michael Niedermayer (michaelni@gmx.at)
  *
@@ -58,12 +58,12 @@
 #include "yuv2rgb_template.c"
 #endif /* HAVE_MMX_INLINE */
 
-//MMX2 versions
+// MMXEXT versions
 #if HAVE_MMXEXT_INLINE
 #undef RENAME
 #undef COMPILE_TEMPLATE_MMXEXT
 #define COMPILE_TEMPLATE_MMXEXT 1
-#define RENAME(a) a ## _MMX2
+#define RENAME(a) a ## _MMXEXT
 #include "yuv2rgb_template.c"
 #endif /* HAVE_MMXEXT_INLINE */
 
@@ -77,32 +77,34 @@
 #if HAVE_MMXEXT_INLINE
     if (cpu_flags & AV_CPU_FLAG_MMXEXT) {
         switch (c->dstFormat) {
-        case PIX_FMT_RGB24:  return yuv420_rgb24_MMX2;
-        case PIX_FMT_BGR24:  return yuv420_bgr24_MMX2;
+        case AV_PIX_FMT_RGB24:
+            return yuv420_rgb24_MMXEXT;
+        case AV_PIX_FMT_BGR24:
+            return yuv420_bgr24_MMXEXT;
         }
     }
 #endif
 
     if (cpu_flags & AV_CPU_FLAG_MMX) {
         switch (c->dstFormat) {
-            case PIX_FMT_RGB32:
-                if (c->srcFormat == PIX_FMT_YUVA420P) {
+            case AV_PIX_FMT_RGB32:
+                if (c->srcFormat == AV_PIX_FMT_YUVA420P) {
 #if HAVE_7REGS && CONFIG_SWSCALE_ALPHA
                     return yuva420_rgb32_MMX;
 #endif
                     break;
                 } else return yuv420_rgb32_MMX;
-            case PIX_FMT_BGR32:
-                if (c->srcFormat == PIX_FMT_YUVA420P) {
+            case AV_PIX_FMT_BGR32:
+                if (c->srcFormat == AV_PIX_FMT_YUVA420P) {
 #if HAVE_7REGS && CONFIG_SWSCALE_ALPHA
                     return yuva420_bgr32_MMX;
 #endif
                     break;
                 } else return yuv420_bgr32_MMX;
-            case PIX_FMT_RGB24:  return yuv420_rgb24_MMX;
-            case PIX_FMT_BGR24:  return yuv420_bgr24_MMX;
-            case PIX_FMT_RGB565: return yuv420_rgb16_MMX;
-            case PIX_FMT_RGB555: return yuv420_rgb15_MMX;
+            case AV_PIX_FMT_RGB24:  return yuv420_rgb24_MMX;
+            case AV_PIX_FMT_BGR24:  return yuv420_bgr24_MMX;
+            case AV_PIX_FMT_RGB565: return yuv420_rgb16_MMX;
+            case AV_PIX_FMT_RGB555: return yuv420_rgb15_MMX;
         }
     }
 #endif /* HAVE_INLINE_ASM */
diff --git a/libswscale/x86/yuv2rgb_template.c b/libswscale/x86/yuv2rgb_template.c
index 79e48fd..c879102 100644
--- a/libswscale/x86/yuv2rgb_template.c
+++ b/libswscale/x86/yuv2rgb_template.c
@@ -43,7 +43,7 @@
     if (h_size * depth > FFABS(dstStride[0]))                        \
         h_size -= 8;                                                 \
                                                                      \
-    vshift = c->srcFormat != PIX_FMT_YUV422P;                        \
+    vshift = c->srcFormat != AV_PIX_FMT_YUV422P;                        \
                                                                      \
     __asm__ volatile ("pxor %mm4, %mm4\n\t");                        \
     for (y = 0; y < srcSliceH; y++) {                                \
diff --git a/libswscale/yuv2rgb.c b/libswscale/yuv2rgb.c
index 073fa66..53b69d0 100644
--- a/libswscale/yuv2rgb.c
+++ b/libswscale/yuv2rgb.c
@@ -35,12 +35,12 @@
 #include "swscale_internal.h"
 #include "libavutil/pixdesc.h"
 
-extern const uint8_t dither_2x2_4[2][8];
-extern const uint8_t dither_2x2_8[2][8];
-extern const uint8_t dither_4x4_16[4][8];
-extern const uint8_t dither_8x8_32[8][8];
-extern const uint8_t dither_8x8_73[8][8];
-extern const uint8_t dither_8x8_220[8][8];
+extern const uint8_t dither_2x2_4[3][8];
+extern const uint8_t dither_2x2_8[3][8];
+extern const uint8_t dither_4x4_16[5][8];
+extern const uint8_t dither_8x8_32[9][8];
+extern const uint8_t dither_8x8_73[9][8];
+extern const uint8_t dither_8x8_220[9][8];
 
 const int32_t ff_yuv2rgb_coeffs[8][4] = {
     { 117504, 138453, 13954, 34903 }, /* no sequence_display_extension */
@@ -126,7 +126,7 @@
     {                                                                       \
         int y;                                                              \
                                                                             \
-        if (!alpha && c->srcFormat == PIX_FMT_YUV422P) {                    \
+        if (!alpha && c->srcFormat == AV_PIX_FMT_YUV422P) {                    \
             srcStride[1] *= 2;                                              \
             srcStride[2] *= 2;                                              \
         }                                                                   \
@@ -625,49 +625,49 @@
            av_get_pix_fmt_name(c->srcFormat), av_get_pix_fmt_name(c->dstFormat));
 
     switch (c->dstFormat) {
-    case PIX_FMT_BGR48BE:
-    case PIX_FMT_BGR48LE:
+    case AV_PIX_FMT_BGR48BE:
+    case AV_PIX_FMT_BGR48LE:
         return yuv2rgb_c_bgr48;
-    case PIX_FMT_RGB48BE:
-    case PIX_FMT_RGB48LE:
+    case AV_PIX_FMT_RGB48BE:
+    case AV_PIX_FMT_RGB48LE:
         return yuv2rgb_c_48;
-    case PIX_FMT_ARGB:
-    case PIX_FMT_ABGR:
+    case AV_PIX_FMT_ARGB:
+    case AV_PIX_FMT_ABGR:
         if (CONFIG_SWSCALE_ALPHA && isALPHA(c->srcFormat))
             return yuva2argb_c;
-    case PIX_FMT_RGBA:
-    case PIX_FMT_BGRA:
+    case AV_PIX_FMT_RGBA:
+    case AV_PIX_FMT_BGRA:
         return (CONFIG_SWSCALE_ALPHA && isALPHA(c->srcFormat)) ? yuva2rgba_c : yuv2rgb_c_32;
-    case PIX_FMT_RGB24:
+    case AV_PIX_FMT_RGB24:
         return yuv2rgb_c_24_rgb;
-    case PIX_FMT_BGR24:
+    case AV_PIX_FMT_BGR24:
         return yuv2rgb_c_24_bgr;
-    case PIX_FMT_RGB565:
-    case PIX_FMT_BGR565:
+    case AV_PIX_FMT_RGB565:
+    case AV_PIX_FMT_BGR565:
         return yuv2rgb_c_16_ordered_dither;
-    case PIX_FMT_RGB555:
-    case PIX_FMT_BGR555:
+    case AV_PIX_FMT_RGB555:
+    case AV_PIX_FMT_BGR555:
         return yuv2rgb_c_15_ordered_dither;
-    case PIX_FMT_RGB444:
-    case PIX_FMT_BGR444:
+    case AV_PIX_FMT_RGB444:
+    case AV_PIX_FMT_BGR444:
         return yuv2rgb_c_12_ordered_dither;
-    case PIX_FMT_RGB8:
-    case PIX_FMT_BGR8:
+    case AV_PIX_FMT_RGB8:
+    case AV_PIX_FMT_BGR8:
         return yuv2rgb_c_8_ordered_dither;
-    case PIX_FMT_RGB4:
-    case PIX_FMT_BGR4:
+    case AV_PIX_FMT_RGB4:
+    case AV_PIX_FMT_BGR4:
         return yuv2rgb_c_4_ordered_dither;
-    case PIX_FMT_RGB4_BYTE:
-    case PIX_FMT_BGR4_BYTE:
+    case AV_PIX_FMT_RGB4_BYTE:
+    case AV_PIX_FMT_BGR4_BYTE:
         return yuv2rgb_c_4b_ordered_dither;
-    case PIX_FMT_MONOBLACK:
+    case AV_PIX_FMT_MONOBLACK:
         return yuv2rgb_c_1_ordered_dither;
     }
     return NULL;
 }
 
 static void fill_table(uint8_t* table[256 + 2*YUVRGB_TABLE_HEADROOM], const int elemsize,
-                       const int inc, void *y_tab)
+                       const int64_t inc, void *y_tab)
 {
     int i;
     uint8_t *y_table = y_tab;
@@ -680,7 +680,7 @@
     }
 }
 
-static void fill_gv_table(int table[256 + 2*YUVRGB_TABLE_HEADROOM], const int elemsize, const int inc)
+static void fill_gv_table(int table[256 + 2*YUVRGB_TABLE_HEADROOM], const int elemsize, const int64_t inc)
 {
     int i;
     int off    = -(inc >> 9);
@@ -707,25 +707,25 @@
                                      int fullRange, int brightness,
                                      int contrast, int saturation)
 {
-    const int isRgb = c->dstFormat == PIX_FMT_RGB32     ||
-                      c->dstFormat == PIX_FMT_RGB32_1   ||
-                      c->dstFormat == PIX_FMT_BGR24     ||
-                      c->dstFormat == PIX_FMT_RGB565BE  ||
-                      c->dstFormat == PIX_FMT_RGB565LE  ||
-                      c->dstFormat == PIX_FMT_RGB555BE  ||
-                      c->dstFormat == PIX_FMT_RGB555LE  ||
-                      c->dstFormat == PIX_FMT_RGB444BE  ||
-                      c->dstFormat == PIX_FMT_RGB444LE  ||
-                      c->dstFormat == PIX_FMT_RGB8      ||
-                      c->dstFormat == PIX_FMT_RGB4      ||
-                      c->dstFormat == PIX_FMT_RGB4_BYTE ||
-                      c->dstFormat == PIX_FMT_MONOBLACK;
-    const int isNotNe = c->dstFormat == PIX_FMT_NE(RGB565LE, RGB565BE) ||
-                        c->dstFormat == PIX_FMT_NE(RGB555LE, RGB555BE) ||
-                        c->dstFormat == PIX_FMT_NE(RGB444LE, RGB444BE) ||
-                        c->dstFormat == PIX_FMT_NE(BGR565LE, BGR565BE) ||
-                        c->dstFormat == PIX_FMT_NE(BGR555LE, BGR555BE) ||
-                        c->dstFormat == PIX_FMT_NE(BGR444LE, BGR444BE);
+    const int isRgb = c->dstFormat == AV_PIX_FMT_RGB32     ||
+                      c->dstFormat == AV_PIX_FMT_RGB32_1   ||
+                      c->dstFormat == AV_PIX_FMT_BGR24     ||
+                      c->dstFormat == AV_PIX_FMT_RGB565BE  ||
+                      c->dstFormat == AV_PIX_FMT_RGB565LE  ||
+                      c->dstFormat == AV_PIX_FMT_RGB555BE  ||
+                      c->dstFormat == AV_PIX_FMT_RGB555LE  ||
+                      c->dstFormat == AV_PIX_FMT_RGB444BE  ||
+                      c->dstFormat == AV_PIX_FMT_RGB444LE  ||
+                      c->dstFormat == AV_PIX_FMT_RGB8      ||
+                      c->dstFormat == AV_PIX_FMT_RGB4      ||
+                      c->dstFormat == AV_PIX_FMT_RGB4_BYTE ||
+                      c->dstFormat == AV_PIX_FMT_MONOBLACK;
+    const int isNotNe = c->dstFormat == AV_PIX_FMT_NE(RGB565LE, RGB565BE) ||
+                        c->dstFormat == AV_PIX_FMT_NE(RGB555LE, RGB555BE) ||
+                        c->dstFormat == AV_PIX_FMT_NE(RGB444LE, RGB444BE) ||
+                        c->dstFormat == AV_PIX_FMT_NE(BGR565LE, BGR565BE) ||
+                        c->dstFormat == AV_PIX_FMT_NE(BGR555LE, BGR555BE) ||
+                        c->dstFormat == AV_PIX_FMT_NE(BGR444LE, BGR444BE);
     const int bpp = c->dstFormatBpp;
     uint8_t *y_table;
     uint16_t *y_table16;
@@ -893,8 +893,8 @@
         fill_gv_table(c->table_gV, 1, cgv);
         break;
     case 32:
-        base      = (c->dstFormat == PIX_FMT_RGB32_1 ||
-                     c->dstFormat == PIX_FMT_BGR32_1) ? 8 : 0;
+        base      = (c->dstFormat == AV_PIX_FMT_RGB32_1 ||
+                     c->dstFormat == AV_PIX_FMT_BGR32_1) ? 8 : 0;
         rbase     = base + (isRgb ? 16 : 0);
         gbase     = base + 8;
         bbase     = base + (isRgb ? 0 : 16);
diff --git a/tests/Makefile b/tests/Makefile
index 96d53c0..dfb12b0 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -31,17 +31,39 @@
 	$(M)$< $(SRC_PATH)/tests/lena.pnm $@
 
 tests/data/ffprobe-test.nut: ffmpeg$(EXESUF) | tests/data
-	$(M)./$< \
+	$(M)$(TARGET_EXEC) ./$< \
         -f lavfi -i "aevalsrc=sin(400*PI*2*t)::d=0.125[out0]; testsrc=d=0.125[out1]; testsrc=s=100x100:d=0.125[out2]" \
         -f ffmetadata -i $(SRC_PATH)/tests/test.ffmeta \
         -flags +bitexact -map 0:0 -map 0:1 -map 0:2 -map_metadata 1 \
+        -map_metadata:s:0 1:s:0 -map_metadata:s:1 1:s:1 \
         -vcodec rawvideo -acodec pcm_s16le \
         -y $@ 2>/dev/null
 
 tests/data/%.sw tests/data/asynth% tests/data/vsynth%.yuv tests/vsynth%/00.pgm tests/data/%.nut: TAG = GEN
 
+CHKCFG  = $(if $($(1))$(!$(1)),$($(1)), $(error No such config: $(1)))
+
+ALLYES  = $(strip $(call XYES, $(1)))
+XYES    = $(if $(strip $(1)),                                           \
+               $(if $(call CHKCFG,CONFIG_$(firstword $(1))),            \
+                    $(call XYES, $(wordlist 2, $(words $(1)), $(1)))),  \
+               yes)
+
+ENCDEC  = $(call ALLYES, $(firstword $(1))_ENCODER $(lastword $(1))_DECODER  \
+                         $(firstword $(2))_MUXER   $(lastword $(2))_DEMUXER)
+
+ENCDEC2 = $(call ALLYES, $(firstword $(1))_ENCODER $(lastword $(1))_DECODER  \
+                         $(firstword $(2))_ENCODER $(lastword $(2))_DECODER  \
+                         $(firstword $(3))_MUXER   $(lastword $(3))_DEMUXER)
+
+DEMDEC  = $(call ALLYES, $(1)_DEMUXER $(2:%=%_DECODER))
+ENCMUX  = $(call ALLYES, $(1:%=%_ENCODER) $(2)_MUXER)
+
 include $(SRC_PATH)/tests/fate/acodec.mak
 include $(SRC_PATH)/tests/fate/vcodec.mak
+include $(SRC_PATH)/tests/fate/avformat.mak
+include $(SRC_PATH)/tests/fate/avfilter.mak
+include $(SRC_PATH)/tests/fate/seek.mak
 
 include $(SRC_PATH)/tests/fate/aac.mak
 include $(SRC_PATH)/tests/fate/ac3.mak
@@ -55,7 +77,6 @@
 include $(SRC_PATH)/tests/fate/bmp.mak
 include $(SRC_PATH)/tests/fate/cdxl.mak
 include $(SRC_PATH)/tests/fate/cover-art.mak
-include $(SRC_PATH)/tests/fate/dct.mak
 include $(SRC_PATH)/tests/fate/demux.mak
 include $(SRC_PATH)/tests/fate/dfa.mak
 include $(SRC_PATH)/tests/fate/dpcm.mak
@@ -68,6 +89,7 @@
 include $(SRC_PATH)/tests/fate/image.mak
 include $(SRC_PATH)/tests/fate/indeo.mak
 include $(SRC_PATH)/tests/fate/libavcodec.mak
+include $(SRC_PATH)/tests/fate/libavformat.mak
 include $(SRC_PATH)/tests/fate/libavutil.mak
 include $(SRC_PATH)/tests/fate/mapchan.mak
 include $(SRC_PATH)/tests/fate/lossless-audio.mak
@@ -93,51 +115,25 @@
 include $(SRC_PATH)/tests/fate/wavpack.mak
 include $(SRC_PATH)/tests/fate/wma.mak
 
-FATE_LAVF_FATE = $(LAVF_FATE_TESTS:%=fate-lavf-fate-%)
-FATE_LAVF    = $(LAVF_TESTS:%=fate-lavf-%)
-FATE_LAVFI   = $(LAVFI_TESTS:%=fate-lavfi-%)
-FATE_SEEK    = $(SEEK_TESTS:seek_%=fate-seek-%)
-
-FATE_AVCONV += $(FATE_LAVF)                                             \
-               $(FATE_LAVFI)                                            \
-               $(FATE_SEEK)                                             \
-
 FATE_FFMPEG += $(FATE_FFMPEG-yes) $(FATE_AVCONV) $(FATE_AVCONV-yes)
 FATE-$(CONFIG_FFMPEG) += $(FATE_FFMPEG)
 FATE-$(CONFIG_FFPROBE) += $(FATE_FFPROBE)
 
-FATE-$(CONFIG_AVCODEC)  += $(FATE_LIBAVCODEC)
-
-FATE_EXTERN-$(CONFIG_FFMPEG) += $(FATE_SAMPLES_AVCONV) $(FATE_SAMPLES_FFMPEG)
+FATE_SAMPLES_AVCONV           += $(FATE_SAMPLES_AVCONV-yes)
+FATE_EXTERN-$(CONFIG_FFMPEG)  += $(FATE_SAMPLES_AVCONV) $(FATE_SAMPLES_FFMPEG) $(FATE_SAMPLES_FFPROBE)
 FATE_EXTERN += $(FATE_EXTERN-yes)
 
 FATE += $(FATE-yes)
-FATE += $(FATE_LIBAVUTIL)
 
-$(FATE_FFMPEG) $(FATE_LAVF_FATE) $(FATE_SAMPLES_AVCONV) $(FATE_SAMPLES_FFMPEG): ffmpeg$(EXESUF)
+$(FATE_FFMPEG) $(FATE_SAMPLES_AVCONV) $(FATE_SAMPLES_FFMPEG): ffmpeg$(EXESUF)
 
-$(FATE_FFPROBE): ffprobe$(EXESUF)
-
-$(FATE_LAVF):  $(AREF) $(VREF)
-$(FATE_LAVFI): $(VREF) libavfilter/filtfmts-test$(EXESUF)
-$(FATE_SEEK):  fate-acodec fate-vsynth2 fate-lavf libavformat/seek-test$(EXESUF)
-
-$(FATE_LAVF_FATE): CMD = lavffatetest
-$(FATE_LAVF):    CMD = lavftest
-$(FATE_LAVFI):   CMD = lavfitest
-$(FATE_SEEK):    CMD = seektest
-
-fate-lavf-fate: $(FATE_LAVF_FATE)
-fate-lavf:   $(FATE_LAVF)
-fate-lavfi:  $(FATE_LAVFI)
-fate-seek:   $(FATE_SEEK)
+$(FATE_FFPROBE) $(FATE_SAMPLES_FFPROBE): ffprobe$(EXESUF)
 
 ifdef SAMPLES
-FATE += $(FATE_LAVF_FATE)
 FATE += $(FATE_FULL) $(FATE_FULL-yes)
 FATE += $(FATE_EXTERN)
 fate-rsync:
-	rsync -vaLW --timeout=60 --contimeout=60 rsync://fate-suite.ffmpeg.org/fate-suite/ $(SAMPLES)
+	rsync -vrltLW --timeout=60 --contimeout=60 rsync://fate-suite.ffmpeg.org/fate-suite/ $(SAMPLES)
 else
 fate::
 	@echo "warning: only a subset of the fate tests will be run because SAMPLES is not specified"
diff --git a/tests/asynth1.sw b/tests/asynth1.sw
deleted file mode 100644
index adda4d5..0000000
--- a/tests/asynth1.sw
+++ /dev/null
Binary files differ
diff --git a/tests/fate-run.sh b/tests/fate-run.sh
index ccd04a3..1945d88 100755
--- a/tests/fate-run.sh
+++ b/tests/fate-run.sh
@@ -71,7 +71,7 @@
 }
 
 probefmt(){
-    run ffprobe -show_format_entry format_name -print_format default=nw=1:nk=1 -v 0 "$@"
+    run ffprobe -show_entries format=format_name -print_format default=nw=1:nk=1 -v 0 "$@"
 }
 
 ffmpeg(){
@@ -164,21 +164,6 @@
     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 fate/acodec- fate/vsynth2- lavf/; do
-                     test -f tests/data/$d$file && break
-                 done
-                 file=$(echo tests/data/$d$file)
-                 ;;
-    esac
-    run libavformat/seek-test $target_path/$file
-}
-
 mkdir -p "$outdir"
 
 exec 3>&2
diff --git a/tests/fate/aac.mak b/tests/fate/aac.mak
index 1ac17f1..c5c47e6 100644
--- a/tests/fate/aac.mak
+++ b/tests/fate/aac.mak
@@ -46,24 +46,17 @@
 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_AAC += fate-aac-ap05_48
 fate-aac-ap05_48: CMD = pcm -i $(SAMPLES)/aac/ap05_48.mp4
 fate-aac-ap05_48: REF = $(SAMPLES)/aac/ap05_48.s16
 
-FATE_AAC += fate-aac-latm_stereo_to_51
-fate-aac-latm_stereo_to_51: CMD = pcm -i $(SAMPLES)/aac/latm_stereo_to_51.ts -channel_layout 5.1
-fate-aac-latm_stereo_to_51: REF = $(SAMPLES)/aac/latm_stereo_to_51_ref.s16
-
 fate-aac-ct%: CMD = pcm -i $(SAMPLES)/aac/CT_DecoderCheck/$(@:fate-aac-ct-%=%)
 fate-aac-ct%: REF = $(SAMPLES)/aac/CT_DecoderCheck/aacPlusv2.wav
 
+FATE_AAC_CT_RAW = fate-aac-ct-sbr_i-ps_i.aac
+
 FATE_AAC_CT = sbr_bc-ps_i.3gp  \
               sbr_bic-ps_i.3gp \
-              sbr_i-ps_i.aac   \
               sbr_bc-ps_bc.mp4 \
               sbr_bc-ps_i.mp4  \
               sbr_i-ps_bic.mp4 \
@@ -88,8 +81,24 @@
 fate-aac-ln-encode: CMP_TARGET = 65
 fate-aac-ln-encode: SIZE_TOLERANCE = 3560
 
-FATE_SAMPLES_FFMPEG += $(FATE_AAC) $(FATE_AAC_ENCODE)
-fate-aac: $(FATE_AAC) $(FATE_AAC_ENCODE)
+FATE_AAC_LATM += 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_AAC): CMP = oneoff
-$(FATE_AAC): FUZZ = 2
+FATE_AAC_LATM += fate-aac-latm_stereo_to_51
+fate-aac-latm_stereo_to_51: CMD = pcm -i $(SAMPLES)/aac/latm_stereo_to_51.ts -channel_layout 5.1
+fate-aac-latm_stereo_to_51: REF = $(SAMPLES)/aac/latm_stereo_to_51_ref.s16
+
+FATE_AAC-$(call      DEMDEC, AAC,    AAC)      += $(FATE_AAC_CT_RAW)
+FATE_AAC-$(call      DEMDEC, MOV,    AAC)      += $(FATE_AAC)
+FATE_AAC_LATM-$(call DEMDEC, MPEGTS, AAC_LATM) += $(FATE_AAC_LATM)
+
+FATE_AAC_ALL = $(FATE_AAC-yes) $(FATE_AAC_LATM-yes)
+
+$(FATE_AAC_ALL): CMP  = oneoff
+$(FATE_AAC_ALL): FUZZ = 2
+
+FATE_SAMPLES_FFMPEG += $(FATE_AAC_ALL) $(FATE_AAC_ENCODE)
+
+fate-aac: $(FATE_AAC_ALL) $(FATE_AAC_ENCODE)
+fate-aac-latm: $(FATE_AAC_LATM-yes)
diff --git a/tests/fate/ac3.mak b/tests/fate/ac3.mak
index b16687e..2985a0e 100644
--- a/tests/fate/ac3.mak
+++ b/tests/fate/ac3.mak
@@ -1,82 +1,76 @@
 FATE_AC3 += 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_AC3 += fate-ac3-4.0
 fate-ac3-4.0: CMD = pcm -i $(SAMPLES)/ac3/millers_crossing_4.0.ac3
-fate-ac3-4.0: CMP = oneoff
 fate-ac3-4.0: REF = $(SAMPLES)/ac3/millers_crossing_4.0.pcm
 
 FATE_AC3 += fate-ac3-4.0-downmix-mono
 fate-ac3-4.0-downmix-mono: CMD = pcm -request_channels 1 -i $(SAMPLES)/ac3/millers_crossing_4.0.ac3
-fate-ac3-4.0-downmix-mono: CMP = oneoff
 fate-ac3-4.0-downmix-mono: REF = $(SAMPLES)/ac3/millers_crossing_4.0_mono.pcm
 
 FATE_AC3 += fate-ac3-4.0-downmix-stereo
 fate-ac3-4.0-downmix-stereo: CMD = pcm -request_channels 2 -i $(SAMPLES)/ac3/millers_crossing_4.0.ac3
-fate-ac3-4.0-downmix-stereo: CMP = oneoff
 fate-ac3-4.0-downmix-stereo: REF = $(SAMPLES)/ac3/millers_crossing_4.0_stereo.pcm
 
 FATE_AC3 += 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_AC3 += fate-ac3-5.1-downmix-mono
 fate-ac3-5.1-downmix-mono: CMD = pcm -request_channels 1 -i $(SAMPLES)/ac3/monsters_inc_5.1_448_small.ac3
-fate-ac3-5.1-downmix-mono: CMP = oneoff
 fate-ac3-5.1-downmix-mono: REF = $(SAMPLES)/ac3/monsters_inc_5.1_448_small_mono.pcm
 
 FATE_AC3 += fate-ac3-5.1-downmix-stereo
 fate-ac3-5.1-downmix-stereo: CMD = pcm -request_channels 2 -i $(SAMPLES)/ac3/monsters_inc_5.1_448_small.ac3
-fate-ac3-5.1-downmix-stereo: CMP = oneoff
 fate-ac3-5.1-downmix-stereo: REF = $(SAMPLES)/ac3/monsters_inc_5.1_448_small_stereo.pcm
 
-FATE_AC3 += fate-eac3-1
+FATE_EAC3 += 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_AC3 += fate-eac3-2
+FATE_EAC3 += 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_AC3 += fate-eac3-3
+FATE_EAC3 += 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_AC3 += fate-eac3-4
+FATE_EAC3 += 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_AC3 += fate-ac3-encode
+$(FATE_AC3) $(FATE_EAC3): CMP = oneoff
+
+FATE_AC3-$(call  DEMDEC, AC3,  AC3)  += $(FATE_AC3)
+FATE_EAC3-$(call DEMDEC, EAC3, EAC3) += $(FATE_EAC3)
+
+FATE_AC3-$(call ENCDEC, AC3, AC3) += fate-ac3-encode
 fate-ac3-encode: CMD = enc_dec_pcm ac3 wav s16le $(REF) -c:a ac3 -b:a 128k
-fate-ac3-encode: CMP = stddev
-fate-ac3-encode: REF = $(SAMPLES)/audio-reference/luckynight_2ch_44kHz_s16.wav
 fate-ac3-encode: CMP_SHIFT = -1024
 fate-ac3-encode: CMP_TARGET = 399.62
 fate-ac3-encode: SIZE_TOLERANCE = 488
 fate-ac3-encode: FUZZ = 4
 
-FATE_AC3 += fate-eac3-encode
+FATE_EAC3-$(call ENCDEC, EAC3, EAC3) += fate-eac3-encode
 fate-eac3-encode: CMD = enc_dec_pcm eac3 wav s16le $(REF) -c:a eac3 -b:a 128k
-fate-eac3-encode: CMP = stddev
-fate-eac3-encode: REF = $(SAMPLES)/audio-reference/luckynight_2ch_44kHz_s16.wav
 fate-eac3-encode: CMP_SHIFT = -1024
 fate-eac3-encode: CMP_TARGET = 514.02
 fate-eac3-encode: SIZE_TOLERANCE = 488
 fate-eac3-encode: FUZZ = 3
 
-FATE_AC3 += fate-ac3-fixed-encode
+fate-ac3-encode fate-eac3-encode: CMP = stddev
+fate-ac3-encode fate-eac3-encode: REF = $(SAMPLES)/audio-reference/luckynight_2ch_44kHz_s16.wav
+
+FATE_AC3-$(call ENCMUX, AC3_FIXED, AC3) += fate-ac3-fixed-encode
 fate-ac3-fixed-encode: tests/data/asynth-44100-2.wav
 fate-ac3-fixed-encode: SRC = $(TARGET_PATH)/tests/data/asynth-44100-2.wav
 fate-ac3-fixed-encode: CMD = md5 -i $(SRC) -c ac3_fixed -ab 128k -f ac3 -flags +bitexact
 fate-ac3-fixed-encode: CMP = oneline
 fate-ac3-fixed-encode: REF = a1d1fc116463b771abf5aef7ed37d7b1
 
-FATE_SAMPLES_AVCONV += $(FATE_AC3)
-fate-ac3: $(FATE_AC3)
+FATE_SAMPLES_AVCONV += $(FATE_AC3-yes) $(FATE_EAC3-yes)
+
+fate-ac3: $(FATE_AC3-yes) $(FATE_EAC3-yes)
diff --git a/tests/fate/acodec.mak b/tests/fate/acodec.mak
index 31f3441..0206486 100644
--- a/tests/fate/acodec.mak
+++ b/tests/fate/acodec.mak
@@ -2,26 +2,58 @@
 fate-acodec-%: SRC = tests/data/asynth-44100-2.wav
 fate-acodec-%: CMD = enc_dec wav $(SRC) $(FMT) "-b 128k -c $(CODEC) $(ENCOPTS)" wav "-c pcm_s16le $(DECOPTS)" -keep
 fate-acodec-%: CMP_UNIT = 2
+fate-acodec-%: REF = $(SRC_PATH)/tests/ref/acodec/$(@:fate-acodec-%=%)
 
-FATE_ACODEC_PCM = alaw mulaw                                            \
-                  s8 u8                                                 \
-                  s16be s16le                                           \
-                  s24be s24le                                           \
-                  s32be s32le                                           \
-                  f32be f32le                                           \
-                  f64be f64le
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_ALAW,  WAV) += alaw
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_MULAW, WAV) += mulaw
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_S8,    MOV) += s8
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_U8,    WAV) += u8
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_S16BE, MOV) += s16be
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_S16LE, WAV) += s16le
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_U16BE, NUT) += u16be
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_U16LE, NUT) += u16le
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_S24BE, MOV) += s24be
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_S24LE, WAV) += s24le
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_U24BE, NUT) += u24be
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_U24LE, NUT) += u24le
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_S32BE, MOV) += s32be
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_S32LE, WAV) += s32le
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_U32BE, NUT) += u32be
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_U32LE, NUT) += u32le
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_F32BE, AU)  += f32be
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_F32LE, WAV) += f32le
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_F64BE, AU)  += f64be
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_F64LE, WAV) += f64le
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_S8_PLANAR, NUT) += s8_planar
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_S16BE_PLANAR, NUT) += s16be_planar
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_S16LE_PLANAR, NUT) += s16le_planar
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_S24LE_PLANAR, NUT) += s24le_planar
+FATE_ACODEC_PCM-$(call ENCDEC, PCM_S32LE_PLANAR, NUT) += s32le_planar
 
-FATE_ACODEC += $(FATE_ACODEC_PCM:%=fate-acodec-pcm-%)
+FATE_ACODEC_PCM := $(FATE_ACODEC_PCM-yes:%=fate-acodec-pcm-%)
+FATE_ACODEC += $(FATE_ACODEC_PCM)
+fate-acodec-pcm: $(FATE_ACODEC_PCM)
 
 fate-acodec-pcm-%: FMT = wav
+fate-acodec-pcm-%_planar: FMT = nut
 fate-acodec-pcm-%: CODEC = pcm_$(@:fate-acodec-pcm-%=%)
 
 fate-acodec-pcm-s8:   FMT = mov
 fate-acodec-pcm-s%be: FMT = mov
+fate-acodec-pcm-u%be: FMT = nut
+fate-acodec-pcm-u%le: FMT = nut
 fate-acodec-pcm-f%be: FMT = au
 
-FATE_ACODEC_ADPCM = adx ima_qt ima_wav ms swf yamaha
-FATE_ACODEC += $(FATE_ACODEC_ADPCM:%=fate-acodec-adpcm-%)
+FATE_ACODEC_ADPCM-$(call ENCDEC, ADPCM_ADX,     ADX)  += adx
+FATE_ACODEC_ADPCM-$(call ENCDEC, ADPCM_IMA_QT,  AIFF) += ima_qt
+FATE_ACODEC_ADPCM-$(call ENCDEC, ADPCM_IMA_WAV, WAV)  += ima_wav
+FATE_ACODEC_ADPCM-$(call ENCDEC, ADPCM_MS,      WAV)  += ms
+FATE_ACODEC_ADPCM-$(call ENCDEC, ADPCM_SWF,     FLV)  += swf
+FATE_ACODEC_ADPCM-$(call ENCDEC, ADPCM_YAMAHA,  WAV)  += yamaha
+
+FATE_ACODEC_ADPCM := $(FATE_ACODEC_ADPCM-yes:%=fate-acodec-adpcm-%)
+FATE_ACODEC += $(FATE_ACODEC_ADPCM)
+fate-acodec-adpcm: $(FATE_ACODEC_ADPCM)
 
 fate-acodec-adpcm-%: CODEC = adpcm_$(@:fate-acodec-adpcm-%=%)
 
@@ -32,22 +64,22 @@
 fate-acodec-adpcm-swf:     FMT = flv
 fate-acodec-adpcm-yamaha:  FMT = wav
 
-FATE_ACODEC += fate-acodec-mp2
+FATE_ACODEC-$(call ENCDEC, MP2, MP2 MP3) += fate-acodec-mp2
 fate-acodec-mp2: FMT = mp2
 fate-acodec-mp2: CMP_SHIFT = -1924
 
-FATE_ACODEC += fate-acodec-alac
+FATE_ACODEC-$(call ENCDEC, ALAC, MOV) += fate-acodec-alac
 fate-acodec-alac: FMT = mov
 fate-acodec-alac: CODEC = alac -compression_level 1
 
-FATE_ACODEC += fate-acodec-dca
+FATE_ACODEC-$(call ENCDEC, DCA, DTS) += fate-acodec-dca
 fate-acodec-dca: tests/data/asynth-44100-2.wav
 fate-acodec-dca: SRC = tests/data/asynth-44100-2.wav
 fate-acodec-dca: CMD = md5 -i $(TARGET_PATH)/$(SRC) -c:a dca -strict -2 -f dts -flags +bitexact
 fate-acodec-dca: CMP = oneline
 fate-acodec-dca: REF = 66bd0e602be7fb97dc19151554c0ee29
 
-FATE_ACODEC += fate-acodec-dca2
+FATE_ACODEC-$(call ENCDEC, DCA, WAV) += fate-acodec-dca2
 fate-acodec-dca2: CMD = enc_dec_pcm dts wav s16le $(SRC) -c:a dca -strict -2 -flags +bitexact
 fate-acodec-dca2: REF = $(SRC)
 fate-acodec-dca2: CMP = stddev
@@ -55,11 +87,11 @@
 fate-acodec-dca2: CMP_TARGET = 2424
 fate-acodec-dca2: SIZE_TOLERANCE = 544
 
-FATE_ACODEC += fate-acodec-flac
+FATE_ACODEC-$(call ENCDEC, FLAC, FLAC) += fate-acodec-flac
 fate-acodec-flac: FMT = flac
 fate-acodec-flac: CODEC = flac -compression_level 2
 
-FATE_ACODEC += fate-acodec-g723_1
+FATE_ACODEC-$(call ENCDEC, G723_1, G723_1) += fate-acodec-g723_1
 fate-acodec-g723_1: tests/data/asynth-8000-1.wav
 fate-acodec-g723_1: SRC = tests/data/asynth-8000-1.wav
 fate-acodec-g723_1: FMT = g723_1
@@ -67,7 +99,7 @@
 fate-acodec-g723_1: ENCOPTS = -b:a 6.3k
 fate-acodec-g723_1: CMP_SHIFT = 8
 
-FATE_ACODEC += fate-acodec-ra144
+FATE_ACODEC-$(call ENCDEC, RA_144, WAV) += fate-acodec-ra144
 fate-acodec-ra144: tests/data/asynth-8000-1.wav
 fate-acodec-ra144: SRC = tests/data/asynth-8000-1.wav
 fate-acodec-ra144: CMD = enc_dec_pcm rm wav s16le $(SRC) -c:a real_144
@@ -76,12 +108,14 @@
 fate-acodec-ra144: CMP_TARGET = 4777
 fate-acodec-ra144: CMP_SHIFT = -320
 
-FATE_ACODEC += fate-acodec-roqaudio
+FATE_ACODEC-$(call ENCDEC, ROQ_DPCM, ROQ) += fate-acodec-roqaudio
 fate-acodec-roqaudio: FMT = roq
 fate-acodec-roqaudio: CODEC = roq_dpcm
 fate-acodec-roqaudio: ENCOPTS = -ar 22050
 fate-acodec-roqaudio: DECOPTS = -ar 44100
 
+FATE_ACODEC += $(FATE_ACODEC-yes)
+
 $(FATE_ACODEC): tests/data/asynth-44100-2.wav
 
 FATE_AVCONV += $(FATE_ACODEC)
diff --git a/tests/fate/adpcm.mak b/tests/fate/adpcm.mak
index 4205168..71764cc 100644
--- a/tests/fate/adpcm.mak
+++ b/tests/fate/adpcm.mak
@@ -1,74 +1,83 @@
-FATE_ADPCM += fate-adpcm-ea-r2
-fate-adpcm-ea-r2: CMD = crc -i $(SAMPLES)/ea-mpc/THX_logo.mpc -vn
+FATE_ADPCM-$(call DEMDEC, FOURXM, ADPCM_4XM) += fate-adpcm-4xm
+fate-adpcm-4xm: CMD = framecrc -i $(SAMPLES)/4xm/dracula.4xm -vn -map 0:6
 
-FATE_ADPCM += fate-adpcm-ea-r3
-fate-adpcm-ea-r3: CMD = crc -i $(SAMPLES)/ea-vp6/THX_logo.vp6 -vn
+FATE_ADPCM-$(call DEMDEC, AST, ADPCM_AFC) += fate-adpcm-afc
+fate-adpcm-afc: CMD = framecrc -i $(SAMPLES)/ast/demo11_02_partial.ast
 
-FATE_ADPCM += fate-adpcm-creative
+FATE_ADPCM-$(call DEMDEC, WAV, ADPCM_CT) += fate-adpcm-creative
 fate-adpcm-creative: CMD = md5 -i $(SAMPLES)/creative/intro-partial.wav -f s16le
 
-FATE_ADPCM += fate-adpcm-creative-8-2bit
+FATE_ADPCM-$(call DEMDEC, VOC, ADPCM_SBPRO_2) += fate-adpcm-creative-8-2bit
 fate-adpcm-creative-8-2bit: CMD = md5 -i $(SAMPLES)/creative/BBC_2BIT.VOC -f s16le
 
-FATE_ADPCM += fate-adpcm-creative-8-2.6bit
+FATE_ADPCM-$(call DEMDEC, VOC, ADPCM_SBPRO_3) += fate-adpcm-creative-8-2.6bit
 fate-adpcm-creative-8-2.6bit: CMD = md5 -i $(SAMPLES)/creative/BBC_3BIT.VOC -f s16le
 
-FATE_ADPCM += fate-adpcm-creative-8-4bit
+FATE_ADPCM-$(call DEMDEC, VOC, ADPCM_SBPRO_4) += fate-adpcm-creative-8-4bit
 fate-adpcm-creative-8-4bit: CMD = md5 -i $(SAMPLES)/creative/BBC_4BIT.VOC -f s16le
 
-FATE_ADPCM += fate-adpcm-ea-1
+FATE_ADPCM-$(call DEMDEC, EA, ADPCM_EA) += fate-adpcm-ea-1
 fate-adpcm-ea-1: CMD = framecrc -i $(SAMPLES)/ea-wve/networkBackbone-partial.wve -frames:a 26 -vn
 
-FATE_ADPCM += fate-adpcm-ea-2
+FATE_ADPCM-$(call DEMDEC, EA, ADPCM_EA) += fate-adpcm-ea-2
 fate-adpcm-ea-2: CMD = framecrc -i $(SAMPLES)/ea-dct/NFS2Esprit-partial.dct -vn
 
-FATE_ADPCM += fate-adpcm-ea-maxis-xa
+FATE_ADPCM-$(call DEMDEC, XA, ADPCM_EA_MAXIS_XA) += fate-adpcm-ea-maxis-xa
 fate-adpcm-ea-maxis-xa: CMD = framecrc -i $(SAMPLES)/maxis-xa/SC2KBUG.XA -frames:a 30
 
-FATE_ADPCM += fate-adpcm-ea-r1
+FATE_ADPCM-$(call DEMDEC, EA, ADPCM_EA_R1) += fate-adpcm-ea-r1
 fate-adpcm-ea-r1: CMD = framecrc -i $(SAMPLES)/ea-mad/NFS6LogoE.mad -vn
 
-FATE_ADPCM += fate-adpcm-ima-amv
+FATE_ADPCM-$(call DEMDEC, EA, ADPCM_EA_R2) += fate-adpcm-ea-r2
+fate-adpcm-ea-r2: CMD = crc -i $(SAMPLES)/ea-mpc/THX_logo.mpc -vn
+
+FATE_ADPCM-$(call DEMDEC, EA, ADPCM_EA_R3) += fate-adpcm-ea-r3
+fate-adpcm-ea-r3: CMD = crc -i $(SAMPLES)/ea-vp6/THX_logo.vp6 -vn
+
+FATE_ADPCM-$(call DEMDEC, AVI, ADPCM_IMA_AMV) += fate-adpcm-ima-amv
 fate-adpcm-ima-amv: CMD = framecrc -i $(SAMPLES)/amv/MTV_high_res_320x240_sample_Penguin_Joke_MTV_from_WMV.amv -t 10 -vn
 
-FATE_ADPCM += fate-adpcm-ima-apc
+FATE_ADPCM-$(call DEMDEC, APC, ADPCM_IMA_APC) += fate-adpcm-ima-apc
 fate-adpcm-ima-apc: CMD = md5 -i $(SAMPLES)/cryo-apc/cine007.APC -f s16le
 
-FATE_ADPCM += fate-adpcm-ima-dk3
+FATE_ADPCM-$(call DEMDEC, AVI, ADPCM_IMA_DK3) += fate-adpcm-ima-dk3
 fate-adpcm-ima-dk3: CMD = md5 -i $(SAMPLES)/duck/sop-audio-only.avi -f s16le
 
-FATE_ADPCM += fate-adpcm-ima-dk4
+FATE_ADPCM-$(call DEMDEC, AVI, ADPCM_IMA_DK4) += fate-adpcm-ima-dk4
 fate-adpcm-ima-dk4: CMD = md5 -i $(SAMPLES)/duck/salsa-audio-only.avi -f s16le
 
-FATE_ADPCM += fate-adpcm-ima-ea-eacs
+FATE_ADPCM-$(call DEMDEC, EA, ADPCM_IMA_EA_EACS) += fate-adpcm-ima-ea-eacs
 fate-adpcm-ima-ea-eacs: CMD = framecrc -i $(SAMPLES)/ea-tgv/INTRO8K-partial.TGV -vn
 
-FATE_ADPCM += fate-adpcm-ima-ea-sead
+FATE_ADPCM-$(call DEMDEC, EA, ADPCM_IMA_EA_SEAD) += fate-adpcm-ima-ea-sead
 fate-adpcm-ima-ea-sead: CMD = framecrc -i $(SAMPLES)/ea-tgv/INTEL_S.TGV -vn
 
-FATE_ADPCM += fate-adpcm-ima-iss
+FATE_ADPCM-$(call DEMDEC, ISS, ADPCM_IMA_ISS) += fate-adpcm-ima-iss
 fate-adpcm-ima-iss: CMD = md5 -i $(SAMPLES)/funcom-iss/0004010100.iss -f s16le
 
-FATE_ADPCM += fate-adpcm-ima-smjpeg
+FATE_ADPCM-$(call DEMDEC, WAV, ADPCM_IMA_OKI) += fate-adpcm-ima-oki
+fate-adpcm-ima-oki: CMD = md5 -i $(SAMPLES)/oki/test.wav -f s16le
+
+FATE_ADPCM-$(call DEMDEC, SMJPEG, ADPCM_IMA_SMJPEG) += fate-adpcm-ima-smjpeg
 fate-adpcm-ima-smjpeg: CMD = framecrc -i $(SAMPLES)/smjpeg/scenwin.mjpg -vn
 
-FATE_ADPCM += fate-adpcm-ima_wav-stereo
+FATE_ADPCM-$(call DEMDEC, MOV, ADPCM_IMA_WAV) += fate-adpcm-ima_wav-stereo
 fate-adpcm-ima_wav-stereo: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-2-16-L-ms11.mov -f s16le
 
-FATE_ADPCM += fate-adpcm-ima-ws
+FATE_ADPCM-$(call DEMDEC, WSVQA, ADPCM_IMA_WS) += fate-adpcm-ima-ws
 fate-adpcm-ima-ws: CMD = framecrc -i $(SAMPLES)/vqa/cc-demo1-partial.vqa -vn
 
-FATE_ADPCM += fate-adpcm-ms-mono
+FATE_ADPCM-$(call DEMDEC, DXA, ADPCM_MS) += fate-adpcm-ms-mono
 fate-adpcm-ms-mono: CMD = framecrc -i $(SAMPLES)/dxa/meetsquid.dxa -t 2 -vn
 
-FATE_ADPCM += fate-adpcm-thp
-fate-adpcm-thp: CMD = framecrc -i $(SAMPLES)/thp/pikmin2-opening1-partial.thp -vn
-
-FATE_ADPCM += fate-adpcm-xa
-fate-adpcm-xa: CMD = framecrc -i $(SAMPLES)/psx-str/abc000_cut.str -vn
-
-FATE_ADPCM += fate-adpcm_ms-stereo
+FATE_ADPCM-$(call DEMDEC, MOV, ADPCM_MS) += fate-adpcm_ms-stereo
 fate-adpcm_ms-stereo: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-2-16-L-ms02.mov -f s16le
 
-FATE_SAMPLES_AVCONV += $(FATE_ADPCM)
-fate-adpcm: $(FATE_ADPCM)
+FATE_ADPCM-$(call DEMDEC, THP, ADPCM_THP) += fate-adpcm-thp
+fate-adpcm-thp: CMD = framecrc -i $(SAMPLES)/thp/pikmin2-opening1-partial.thp -vn
+
+FATE_ADPCM-$(call DEMDEC, STR, ADPCM_XA) += fate-adpcm-xa
+fate-adpcm-xa: CMD = framecrc -i $(SAMPLES)/psx-str/abc000_cut.str -vn
+
+FATE_SAMPLES_AVCONV += $(FATE_ADPCM-yes)
+fate-adpcm: $(FATE_ADPCM-yes)
diff --git a/tests/fate/alac.mak b/tests/fate/alac.mak
index b55b594..d724837 100644
--- a/tests/fate/alac.mak
+++ b/tests/fate/alac.mak
@@ -1,15 +1,24 @@
-FATE_ALAC += fate-alac-level-0                                          \
-             fate-alac-level-1                                          \
-             fate-alac-level-2                                          \
-             fate-alac-lpc-orders                                       \
+FATE_ALAC += fate-alac-16-level-0                                       \
+             fate-alac-16-level-1                                       \
+             fate-alac-16-level-2                                       \
+             fate-alac-16-lpc-orders                                    \
+             fate-alac-24-level-0                                       \
+             fate-alac-24-level-1                                       \
+             fate-alac-24-level-2                                       \
+             fate-alac-24-lpc-orders                                    \
 
-fate-alac-level-%: OPTS = -compression_level $(@:fate-alac-level-%=%)
-fate-alac-lpc-orders: OPTS = -min_prediction_order 1 -max_prediction_order 30
+fate-alac-16-level-%:    OPTS = -compression_level $(@:fate-alac-16-level-%=%)
+fate-alac-24-level-%:    OPTS = -compression_level $(@:fate-alac-24-level-%=%)
+fate-alac-%-lpc-orders:  OPTS = -min_prediction_order 1 -max_prediction_order 30
 
-fate-alac-%: REF = $(SAMPLES)/audio-reference/luckynight_2ch_44kHz_s16.wav
-fate-alac-%: CMD = enc_dec_pcm mov wav s16le $(REF) -c alac $(OPTS)
+fate-alac-16-%: REF = $(SAMPLES)/audio-reference/luckynight_2ch_44kHz_s16.wav
+fate-alac-16-%: CMD = enc_dec_pcm mov wav s16le $(REF) -c alac $(OPTS)
+
+fate-alac-24-%: REF = $(SAMPLES)/audio-reference/divertimenti_2ch_96kHz_s24.wav
+fate-alac-24-%: CMD = enc_dec_pcm mov wav s24le $(REF) -c alac $(OPTS)
+
 fate-alac-%: CMP = oneoff
 fate-alac-%: FUZZ = 0
 
-FATE_SAMPLES_AVCONV += $(FATE_ALAC)
+FATE_SAMPLES_AVCONV-$(call ENCDEC, ALAC, MOV) += $(FATE_ALAC)
 fate-alac: $(FATE_ALAC)
diff --git a/tests/fate/als.mak b/tests/fate/als.mak
index ab3e1c0..5ec1189 100644
--- a/tests/fate/als.mak
+++ b/tests/fate/als.mak
@@ -7,5 +7,5 @@
 
 $(foreach N,$(ALS_SUITE),$(eval $(call FATE_ALS_SUITE,$(N))))
 
-FATE_SAMPLES_AVCONV += $(FATE_ALS)
+FATE_SAMPLES_AVCONV-$(call DEMDEC, MOV, ALS) += $(FATE_ALS)
 fate-als: $(FATE_ALS)
diff --git a/tests/fate/amrnb.mak b/tests/fate/amrnb.mak
index d163dc4..6dbba58 100644
--- a/tests/fate/amrnb.mak
+++ b/tests/fate/amrnb.mak
@@ -1,42 +1,36 @@
 FATE_AMRNB += 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 += 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 += 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 += 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 += 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 += 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 += 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 += 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_SAMPLES_AVCONV += $(FATE_AMRNB)
+$(FATE_AMRNB): CMP = stddev
+
+FATE_SAMPLES_AVCONV-$(call DEMDEC, AMR, AMRNB) += $(FATE_AMRNB)
 fate-amrnb: $(FATE_AMRNB)
diff --git a/tests/fate/amrwb.mak b/tests/fate/amrwb.mak
index cdbe2ac..99c2737 100644
--- a/tests/fate/amrwb.mak
+++ b/tests/fate/amrwb.mak
@@ -1,55 +1,47 @@
 FATE_AMRWB += 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 += 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 += 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 += 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_AMRWB += 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 += 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 += 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 += 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_AMRWB += 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_AMRWB += 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_SAMPLES_AVCONV += $(FATE_AMRWB)
+$(FATE_AMRWB): CMP = stddev
+
+FATE_SAMPLES_AVCONV-$(call DEMDEC, AMR, AMRWB) += $(FATE_AMRWB)
 fate-amrwb: $(FATE_AMRWB)
diff --git a/tests/fate/atrac.mak b/tests/fate/atrac.mak
index 3897311..3ac5553 100644
--- a/tests/fate/atrac.mak
+++ b/tests/fate/atrac.mak
@@ -1,22 +1,26 @@
-FATE_ATRAC += fate-atrac1
+FATE_ATRAC1-$(call DEMDEC, AEA, ATRAC1) += 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_ATRAC += fate-atrac3-1
+FATE_ATRAC3 += 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_ATRAC += fate-atrac3-2
+FATE_ATRAC3 += 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_ATRAC += fate-atrac3-3
+FATE_ATRAC3 += 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_SAMPLES_AVCONV += $(FATE_ATRAC)
-fate-atrac: $(FATE_ATRAC)
+FATE_ATRAC3-$(call DEMDEC, WAV, ATRAC3) += $(FATE_ATRAC3)
+
+FATE_ATRAC_ALL = $(FATE_ATRAC1-yes) $(FATE_ATRAC3-yes)
+
+$(FATE_ATRAC_ALL): CMP = oneoff
+
+FATE_SAMPLES_AVCONV += $(FATE_ATRAC_ALL)
+
+fate-atrac:  $(FATE_ATRAC_ALL)
+fate-atrac3: $(FATE_ATRAC3-yes)
diff --git a/tests/fate/audio.mak b/tests/fate/audio.mak
index ca26f5c..3e5e313 100644
--- a/tests/fate/audio.mak
+++ b/tests/fate/audio.mak
@@ -1,35 +1,35 @@
-FATE_BINKAUDIO += fate-binkaudio-dct
+FATE_BINKAUDIO-$(call DEMDEC, BINK, BINKAUDIO_DCT) += 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_BINKAUDIO += fate-binkaudio-rdft
+FATE_BINKAUDIO-$(call DEMDEC, BINK, BINKAUDIO_RDFT) += 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_SAMPLES_AUDIO += $(FATE_BINKAUDIO)
-fate-binkaudio: $(FATE_BINKAUDIO)
+$(FATE_BINKAUDIO-yes): CMP = oneoff
 
-FATE_SAMPLES_AUDIO += fate-bmv-audio
+FATE_SAMPLES_AUDIO += $(FATE_BINKAUDIO-yes)
+fate-binkaudio: $(FATE_BINKAUDIO-yes)
+
+FATE_SAMPLES_AUDIO-$(call DEMDEC, BMV, BMV_AUDIO) += fate-bmv-audio
 fate-bmv-audio: CMD = framecrc -i $(SAMPLES)/bmv/SURFING-partial.BMV -vn
 
-FATE_SAMPLES_AUDIO += fate-delphine-cin-audio
+FATE_SAMPLES_AUDIO-$(call DEMDEC, DSICIN, DSICINAUDIO) += fate-delphine-cin-audio
 fate-delphine-cin-audio: CMD = framecrc -i $(SAMPLES)/delphine-cin/LOGO-partial.CIN -vn
 
-FATE_SAMPLES_AUDIO += fate-dts
+FATE_SAMPLES_AUDIO-$(call DEMDEC, MPEGTS, DCA) += fate-dts
 fate-dts: CMD = pcm -i $(SAMPLES)/dts/dts.ts
 fate-dts: CMP = oneoff
 fate-dts: REF = $(SAMPLES)/dts/dts.pcm
 
-FATE_SAMPLES_AUDIO += fate-imc
+FATE_SAMPLES_AUDIO-$(call DEMDEC, AVI, IMC) += fate-imc
 fate-imc: CMD = pcm -i $(SAMPLES)/imc/imc.avi
 fate-imc: CMP = oneoff
 fate-imc: REF = $(SAMPLES)/imc/imc.pcm
 
-FATE_SAMPLES_AUDIO += fate-nellymoser
+FATE_SAMPLES_AUDIO-$(call DEMDEC, FLV, NELLYMOSER) += fate-nellymoser
 fate-nellymoser: CMD = pcm -i $(SAMPLES)/nellymoser/nellymoser.flv
 fate-nellymoser: CMP = oneoff
 fate-nellymoser: REF = $(SAMPLES)/nellymoser/nellymoser.pcm
@@ -43,20 +43,22 @@
 fate-nellymoser-aref-encode: CMP_TARGET = 9612
 fate-nellymoser-aref-encode: SIZE_TOLERANCE = 268
 
-FATE_SAMPLES_AUDIO += fate-paf-audio
+FATE_SAMPLES_AUDIO-$(call DEMDEC, PAF, PAF_AUDIO) += fate-paf-audio
 fate-paf-audio: CMD = framecrc -i $(SAMPLES)/paf/hod1-partial.paf -vn
 
-FATE_SAMPLES_AUDIO += fate-sierra-vmd-audio
+FATE_SAMPLES_AUDIO-$(call DEMDEC, VMD, VMDAUDIO) += fate-sierra-vmd-audio
 fate-sierra-vmd-audio: CMD = framecrc -i $(SAMPLES)/vmd/12.vmd -vn
 
-FATE_SAMPLES_AUDIO += fate-smacker-audio
+FATE_SAMPLES_AUDIO-$(call DEMDEC, SMACKER, SMACKAUD) += fate-smacker-audio
 fate-smacker-audio: CMD = framecrc -i $(SAMPLES)/smacker/wetlogo.smk -vn
 
-FATE_SAMPLES_AUDIO += fate-vima
+FATE_SAMPLES_AUDIO-$(call DEMDEC, SMUSH, VIMA) += fate-vima
 fate-vima: CMD = framecrc -i $(SAMPLES)/smush/ronin_part.znm -vn
 
-FATE_SAMPLES_AUDIO += fate-ws_snd
+FATE_SAMPLES_AUDIO-$(call DEMDEC, WSVQA, WS_SND1) += fate-ws_snd
 fate-ws_snd: CMD = md5 -i $(SAMPLES)/vqa/ws_snd.vqa -f s16le
 
+FATE_SAMPLES_AUDIO += $(FATE_SAMPLES_AUDIO-yes)
+
 FATE_SAMPLES_FFMPEG += $(FATE_SAMPLES_AUDIO)
 fate-audio: $(FATE_SAMPLES_AUDIO)
diff --git a/tests/fate/avfilter.mak b/tests/fate/avfilter.mak
new file mode 100644
index 0000000..e69d6a1
--- /dev/null
+++ b/tests/fate/avfilter.mak
@@ -0,0 +1,62 @@
+FATE_LAVFI = fate-lavfi-alphaextract_rgb                                \
+             fate-lavfi-alphaextract_yuv                                \
+             fate-lavfi-alphamerge_rgb                                  \
+             fate-lavfi-alphamerge_yuv                                  \
+             fate-lavfi-crop                                            \
+             fate-lavfi-crop_scale                                      \
+             fate-lavfi-crop_scale_vflip                                \
+             fate-lavfi-crop_vflip                                      \
+             fate-lavfi-drawbox                                         \
+             fate-lavfi-edgedetect                                      \
+             fate-lavfi-fade                                            \
+             fate-lavfi-field                                           \
+             fate-lavfi-idet                                            \
+             fate-lavfi-life                                            \
+             fate-lavfi-null                                            \
+             fate-lavfi-overlay                                         \
+             fate-lavfi-pad                                             \
+             fate-lavfi-pixfmts_copy                                    \
+             fate-lavfi-pixfmts_crop                                    \
+             fate-lavfi-pixfmts_hflip                                   \
+             fate-lavfi-pixfmts_null                                    \
+             fate-lavfi-pixfmts_pad                                     \
+             fate-lavfi-pixfmts_pixdesctest                             \
+             fate-lavfi-pixfmts_scale                                   \
+             fate-lavfi-pixfmts_vflip                                   \
+             fate-lavfi-scale200                                        \
+             fate-lavfi-scale500                                        \
+             fate-lavfi-scalenorm                                       \
+             fate-lavfi-select                                          \
+             fate-lavfi-setdar                                          \
+             fate-lavfi-setsar                                          \
+             fate-lavfi-testsrc                                         \
+             fate-lavfi-thumbnail                                       \
+             fate-lavfi-tile                                            \
+             fate-lavfi-transpose                                       \
+             fate-lavfi-unsharp                                         \
+             fate-lavfi-vflip                                           \
+             fate-lavfi-vflip_crop                                      \
+             fate-lavfi-vflip_vflip                                     \
+
+FATE_LAVFI-$(CONFIG_GPL) += fate-lavfi-colormatrix1                     \
+                            fate-lavfi-colormatrix2                     \
+                            fate-lavfi-hue                              \
+                            fate-lavfi-pixfmts_super2xsai               \
+                            fate-lavfi-tinterlace_merge                 \
+                            fate-lavfi-tinterlace_pad                   \
+
+FATE_LAVFI-$(CONFIG_MP_FILTER) += fate-lavfi-pp                         \
+             fate-lavfi-pp2                                             \
+             fate-lavfi-pp3                                             \
+             fate-lavfi-pp4                                             \
+             fate-lavfi-pp5                                             \
+             fate-lavfi-pp6                                             \
+
+FATE_LAVFI += $(FATE_LAVFI-yes)
+
+$(FATE_LAVFI): $(VREF) libavfilter/filtfmts-test$(EXESUF)
+$(FATE_LAVFI): CMD = lavfitest
+
+FATE_AVCONV += $(FATE_LAVFI)
+fate-lavfi:    $(FATE_LAVFI)
+
diff --git a/tests/fate/avformat.mak b/tests/fate/avformat.mak
new file mode 100644
index 0000000..77c6a2f
--- /dev/null
+++ b/tests/fate/avformat.mak
@@ -0,0 +1,68 @@
+FATE_LAVF-$(call ENCDEC,  PCM_S16BE,             AIFF)               += aiff
+FATE_LAVF-$(call ENCDEC,  PCM_ALAW,              PCM_ALAW)           += alaw
+FATE_LAVF-$(call ENCDEC2, MSMPEG4V3,  MP2,       ASF)                += asf
+FATE_LAVF-$(call ENCDEC,  PCM_S16BE,             AU)                 += au
+FATE_LAVF-$(call ENCDEC2, MPEG4,      MP2,       AVI)                += avi
+FATE_LAVF-$(call ENCDEC,  BMP,                   IMAGE2)             += bmp
+FATE_LAVF-$(call ENCDEC,  PCM_S16BE,             CAF)                += caf
+FATE_LAVF-$(call ENCDEC,  DPX,                   IMAGE2)             += dpx
+FATE_LAVF-$(call ENCDEC2, DVVIDEO,    PCM_S16LE, AVI)                += dv_fmt
+FATE_LAVF-$(call ENCDEC2, MPEG1VIDEO, MP2,       FFM)                += ffm
+FATE_LAVF-$(call ENCDEC,  RAWVIDEO,              FILMSTRIP)          += flm
+FATE_LAVF-$(call ENCDEC,  FLV,                   FLV)                += flv_fmt
+FATE_LAVF-$(call ENCDEC,  GIF,                   IMAGE2)             += gif
+FATE_LAVF-$(call ENCDEC2, MPEG2VIDEO, PCM_S16LE, GXF)                += gxf
+FATE_LAVF-$(call ENCDEC,  MJPEG,                 IMAGE2)             += jpg
+FATE_LAVF-$(call ENCDEC2, MPEG4,      MP2,       MATROSKA)           += mkv
+FATE_LAVF-$(call ENCDEC,  ADPCM_YAMAHA,          MMF)                += mmf
+FATE_LAVF-$(call ENCDEC2, MPEG4,      PCM_ALAW,  MOV)                += mov ismv
+FATE_LAVF-$(call ENCDEC2, MPEG1VIDEO, MP2,       MPEG1SYSTEM MPEGPS) += mpg
+FATE_LAVF-$(call ENCDEC,  PCM_MULAW,             PCM_MULAW)          += mulaw
+FATE_LAVF-$(call ENCDEC2, MPEG2VIDEO, PCM_S16LE, MXF)                += mxf
+FATE_LAVF-$(call ENCDEC2, MPEG2VIDEO, PCM_S16LE, MXF_D10 MXF)        += mxf_d10
+FATE_LAVF-$(call ENCDEC2, MPEG4,      MP2,       NUT)                += nut
+FATE_LAVF-$(call ENCDEC,  FLAC,                  OGG)                += ogg
+FATE_LAVF-$(call ENCDEC,  PAM,                   IMAGE2)             += pam
+FATE_LAVF-$(call ENCDEC,  PBM,                   IMAGE2PIPE)         += pbmpipe
+FATE_LAVF-$(call ENCDEC,  PCX,                   IMAGE2)             += pcx
+FATE_LAVF-$(call ENCDEC,  PGM,                   IMAGE2)             += pgm
+FATE_LAVF-$(call ENCDEC,  PGM,                   IMAGE2PIPE)         += pgmpipe
+FATE_LAVF-$(call ENCDEC,  PNG,                   IMAGE2)             += png
+FATE_LAVF-$(call ENCDEC,  PPM,                   IMAGE2)             += ppm
+FATE_LAVF-$(call ENCDEC,  PPM,                   IMAGE2PIPE)         += ppmpipe
+FATE_LAVF-$(call ENCMUX,  RV10 AC3_FIXED,        RM)                 += rm
+FATE_LAVF-$(call ENCDEC,  PCM_U8,                RSO)                += rso
+FATE_LAVF-$(call ENCDEC,  SGI,                   IMAGE2)             += sgi
+FATE_LAVF-$(call ENCMUX,  MJPEG PCM_S16LE,       SMJPEG)             += smjpeg
+FATE_LAVF-$(call ENCDEC,  PCM_S16LE,             SOX)                += sox
+FATE_LAVF-$(call ENCDEC,  SUNRAST,               IMAGE2)             += sunrast
+FATE_LAVF-$(call ENCDEC,  FLV,                   SWF)                += swf
+FATE_LAVF-$(call ENCDEC,  TARGA,                 IMAGE2)             += tga
+FATE_LAVF-$(call ENCDEC,  TIFF,                  IMAGE2)             += tiff
+FATE_LAVF-$(call ENCDEC2, MPEG2VIDEO, MP2,       MPEGTS)             += ts
+FATE_LAVF-$(call ENCDEC,  PCM_U8,                VOC)                += voc
+FATE_LAVF-$(call ENCDEC,  PCM_S16LE,             VOC)                += voc_s16
+FATE_LAVF-$(call ENCDEC,  PCM_S16LE,             WAV)                += wav
+FATE_LAVF-$(call ENCDEC,  MP2,                   WTV)                += wtv
+FATE_LAVF-$(call ENCDEC,  XBM,                   IMAGE2)             += xbm
+FATE_LAVF-$(call ENCDEC,  XWD,                   IMAGE2)             += xwd
+FATE_LAVF-$(CONFIG_YUV4MPEGPIPE_MUXER)                               += yuv4mpeg
+
+FATE_LAVF += $(FATE_LAVF-yes:%=fate-lavf-%)
+FATE_LAVF += fate-lavf-pixfmt
+
+$(FATE_LAVF): $(AREF) $(VREF)
+$(FATE_LAVF): CMD = lavftest
+
+FATE_AVCONV += $(FATE_LAVF)
+fate-lavf:     $(FATE_LAVF)
+
+FATE_LAVF_FATE-$(call ALLYES, MATROSKA_DEMUXER   OGG_MUXER)          += ogg_vp3
+FATE_LAVF_FATE-$(call ALLYES, MOV_DEMUXER        LATM_MUXER)         += latm
+FATE_LAVF_FATE-$(call ALLYES, MP3_DEMUXER        MP3_MUXER)          += mp3
+
+FATE_LAVF_FATE +=  $(FATE_LAVF_FATE-yes:%=fate-lavf-fate-%)
+$(FATE_LAVF_FATE): CMD = lavffatetest
+
+FATE_SAMPLES_FFMPEG += $(FATE_LAVF_FATE)
+fate-lavf-fate:        $(FATE_LAVF_FATE)
diff --git a/tests/fate/dct.mak b/tests/fate/dct.mak
deleted file mode 100644
index d79cb91..0000000
--- a/tests/fate/dct.mak
+++ /dev/null
@@ -1,5 +0,0 @@
-FATE-yes += fate-idct8x8
-fate-idct8x8: libavcodec/dct-test$(EXESUF)
-fate-idct8x8: CMD = run libavcodec/dct-test -i
-fate-idct8x8: REF = /dev/null
-fate-idct8x8: CMP = null
diff --git a/tests/fate/demux.mak b/tests/fate/demux.mak
index f6031b8..c46c863 100644
--- a/tests/fate/demux.mak
+++ b/tests/fate/demux.mak
@@ -1,83 +1,90 @@
 FATE_SAMPLES_DEMUX += fate-avio-direct
 fate-avio-direct: CMD = framecrc -avioflags direct -i $(SAMPLES)/fraps/fraps-v5-bouncing-balls-partial.avi -avioflags direct
 
-FATE_SAMPLES_DEMUX += fate-adts-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_AAC_DEMUXER) += fate-adts-demux
 fate-adts-demux: CMD = crc -i $(SAMPLES)/aac/ct_faac-adts.aac -acodec copy
 
-FATE_SAMPLES_DEMUX += fate-aea-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_AEA_DEMUXER) += fate-aea-demux
 fate-aea-demux: CMD = crc -i $(SAMPLES)/aea/chirp.aea -acodec copy
 
-FATE_SAMPLES_DEMUX += fate-bink-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_AST_DEMUXER) += fate-ast
+fate-ast: CMD = crc -i $(SAMPLES)/ast/demo11_02_partial.ast -c copy
+
+FATE_SAMPLES_DEMUX-$(CONFIG_BINK_DEMUXER) += fate-bink-demux
 fate-bink-demux: CMD = crc -i $(SAMPLES)/bink/Snd0a7d9b58.dee -vn -acodec copy
 
-FATE_SAMPLES_DEMUX += fate-caf
+FATE_SAMPLES_DEMUX-$(CONFIG_CAF_DEMUXER) += fate-caf
 fate-caf: CMD = crc -i $(SAMPLES)/caf/caf-pcm16.caf -c copy
 
-FATE_SAMPLES_DEMUX += fate-cdxl-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_CDXL_DEMUXER) += fate-cdxl-demux
 fate-cdxl-demux: CMD = framecrc -i $(SAMPLES)/cdxl/mirage.cdxl -vcodec copy -acodec copy
 
-FATE_SAMPLES_DEMUX += fate-d-cinema-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_DAUD_DEMUXER) += fate-d-cinema-demux
 fate-d-cinema-demux: CMD = framecrc -i $(SAMPLES)/d-cinema/THX_Science_FLT_1920-partial.302 -acodec copy
 
-FATE_SAMPLES_DEMUX += fate-iv8-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_IV8_DEMUXER) += fate-iv8-demux
 fate-iv8-demux: CMD = framecrc -i $(SAMPLES)/iv8/zzz-partial.mpg -vcodec copy
 
-FATE_SAMPLES_DEMUX += fate-jv-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_JV_DEMUXER) += fate-jv-demux
 fate-jv-demux: CMD = framecrc -i $(SAMPLES)/jv/intro.jv -vcodec copy -acodec copy
 
-FATE_SAMPLES_DEMUX += fate-lmlm4-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_LMLM4_DEMUXER) += fate-lmlm4-demux
 fate-lmlm4-demux: CMD = framecrc -i $(SAMPLES)/lmlm4/LMLM4_CIFat30fps.divx -t 3 -acodec copy -vcodec copy
 
-FATE_SAMPLES_DEMUX += fate-maxis-xa
+FATE_SAMPLES_DEMUX-$(CONFIG_XA_DEMUXER) += fate-maxis-xa
 fate-maxis-xa: CMD = framecrc -i $(SAMPLES)/maxis-xa/SC2KBUG.XA -frames:a 30 -c:a copy
 
-FATE_SAMPLES_DEMUX += fate-mtv
+FATE_SAMPLES_DEMUX-$(CONFIG_MTV_DEMUXER) += fate-mtv
 fate-mtv: CMD = framecrc -i $(SAMPLES)/mtv/comedian_auto-partial.mtv -c copy
 
-FATE_SAMPLES_DEMUX += fate-mxf-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_MXF_DEMUXER) += fate-mxf-demux
 fate-mxf-demux: CMD = framecrc -i $(SAMPLES)/mxf/C0023S01.mxf -acodec copy -vcodec copy
 
-FATE_SAMPLES_DEMUX += fate-nc-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_NC_DEMUXER) += fate-nc-demux
 fate-nc-demux: CMD = framecrc -i $(SAMPLES)/nc-camera/nc-sample-partial -vcodec copy
 
-FATE_SAMPLES_DEMUX += fate-nsv-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_NSV_DEMUXER) += fate-nsv-demux
 fate-nsv-demux: CMD = framecrc -i $(SAMPLES)/nsv/witchblade-51kbps.nsv -t 6 -vcodec copy -acodec copy
 
-FATE_SAMPLES_DEMUX += fate-oma-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_OMA_DEMUXER) += fate-oma-demux
 fate-oma-demux: CMD = crc -i $(SAMPLES)/oma/01-Untitled-partial.oma -acodec copy
 
-FATE_SAMPLES_DEMUX += fate-paf-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_PAF_DEMUXER) += fate-paf-demux
 fate-paf-demux: CMD = framecrc -i $(SAMPLES)/paf/hod1-partial.paf -vcodec copy -acodec copy
 
-FATE_SAMPLES_DEMUX += fate-psx-str-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_PMP_DEMUXER) += fate-pmp-demux
+fate-pmp-demux: CMD = framecrc -i $(SAMPLES)/pmp/demo.pmp -vn -c:a copy
+
+FATE_SAMPLES_DEMUX-$(CONFIG_STR_DEMUXER) += fate-psx-str-demux
 fate-psx-str-demux: CMD = framecrc -i $(SAMPLES)/psx-str/descent-partial.str -c copy
 
-FATE_SAMPLES_DEMUX += fate-pva-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_PVA_DEMUXER) += fate-pva-demux
 fate-pva-demux: CMD = framecrc -idct simple -i $(SAMPLES)/pva/PVA_test-partial.pva -t 0.6 -acodec copy
 
-FATE_SAMPLES_DEMUX += fate-qcp-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_QCP_DEMUXER) += fate-qcp-demux
 fate-qcp-demux: CMD = crc -i $(SAMPLES)/qcp/0036580847.QCP -acodec copy
 
-FATE_SAMPLES_DEMUX += fate-redcode-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_R3D_DEMUXER) += fate-redcode-demux
 fate-redcode-demux: CMD = framecrc -i $(SAMPLES)/r3d/4MB-sample.r3d -vcodec copy -acodec copy
 
-FATE_SAMPLES_DEMUX += fate-siff
+FATE_SAMPLES_DEMUX-$(CONFIG_SIFF_DEMUXER) += fate-siff
 fate-siff: CMD = framecrc -i $(SAMPLES)/SIFF/INTRO_B.VB -t 3 -pix_fmt rgb24
 
-FATE_SAMPLES_DEMUX += fate-smjpeg-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_SMJPEG_DEMUXER) += fate-smjpeg-demux
 fate-smjpeg-demux: CMD = framecrc -i $(SAMPLES)/smjpeg/scenwin.mjpg -c copy
 
-FATE_SAMPLES_DEMUX += fate-westwood-aud
+FATE_SAMPLES_DEMUX-$(CONFIG_WSAUD_DEMUXER) += fate-westwood-aud
 fate-westwood-aud: CMD = framecrc -i $(SAMPLES)/westwood-aud/excellent.aud -c copy
 
-FATE_SAMPLES_DEMUX += fate-wtv-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_WTV_DEMUXER) += fate-wtv-demux
 fate-wtv-demux: CMD = framecrc -i $(SAMPLES)/wtv/law-and-order-partial.wtv -vcodec copy -acodec copy
 
-FATE_SAMPLES_DEMUX += fate-xmv-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_XMV_DEMUXER) += fate-xmv-demux
 fate-xmv-demux: CMD = framecrc -i $(SAMPLES)/xmv/logos1p.fmv -vcodec copy -acodec copy
 
-FATE_SAMPLES_DEMUX += fate-xwma-demux
+FATE_SAMPLES_DEMUX-$(CONFIG_XWMA_DEMUXER) += fate-xwma-demux
 fate-xwma-demux: CMD = crc -i $(SAMPLES)/xwma/ergon.xwma -acodec copy
 
+FATE_SAMPLES_DEMUX += $(FATE_SAMPLES_DEMUX-yes)
 FATE_SAMPLES_FFMPEG += $(FATE_SAMPLES_DEMUX)
 fate-demux: $(FATE_SAMPLES_DEMUX)
diff --git a/tests/fate/ea.mak b/tests/fate/ea.mak
index 2f7f2ad..eb75708 100644
--- a/tests/fate/ea.mak
+++ b/tests/fate/ea.mak
@@ -1,23 +1,26 @@
-FATE_SAMPLES_EA += fate-ea-cdata
+FATE_SAMPLES_EA-$(call DEMDEC, EA_CDATA, ADPCM_EA_XAS) += fate-ea-cdata
 fate-ea-cdata: CMD = md5 -i $(SAMPLES)/ea-cdata/166b084d.46410f77.0009b440.24be960c.cdata -f s16le
 
-FATE_SAMPLES_EA += fate-ea-cmv
+FATE_SAMPLES_EA-$(call DEMDEC, EA, EACMV) += fate-ea-cmv
 fate-ea-cmv: CMD = framecrc -i $(SAMPLES)/ea-cmv/TITLE.CMV -pix_fmt rgb24
 
-FATE_SAMPLES_EA += fate-ea-tgq
+FATE_SAMPLES_EA-$(call DEMDEC, EA, EATGQ) += fate-ea-tgq
 fate-ea-tgq: CMD = framecrc -i $(SAMPLES)/ea-tgq/v27.tgq -an
 
-FATE_SAMPLES_EA += fate-ea-tqi
+FATE_SAMPLES_EA-$(call DEMDEC, EA, EATQI) += fate-ea-tqi
 fate-ea-tqi: CMD = framecrc -i $(SAMPLES)/ea-wve/networkBackbone-partial.wve -frames:v 26 -an
 
-FATE_SAMPLES_EA += fate-ea-mad
+FATE_SAMPLES_EA-$(call DEMDEC, EA, EAMAD) += fate-ea-mad
 fate-ea-mad: CMD = framecrc -i $(SAMPLES)/ea-mad/NFS6LogoE.mad -an
 
-FATE_SAMPLES_EA += fate-ea-tgv-1
+FATE_EA_TGV += fate-ea-tgv-1
 fate-ea-tgv-1: CMD = framecrc -i $(SAMPLES)/ea-tgv/INTRO8K-partial.TGV -pix_fmt rgb24 -an
 
-FATE_SAMPLES_EA += fate-ea-tgv-2
+FATE_EA_TGV += fate-ea-tgv-2
 fate-ea-tgv-2: CMD = framecrc -i $(SAMPLES)/ea-tgv/INTEL_S.TGV -pix_fmt rgb24 -an
 
-FATE_SAMPLES_FFMPEG += $(FATE_SAMPLES_EA)
-fate-ea: $(FATE_SAMPLES_EA)
+FATE_SAMPLES_EA-$(call DEMDEC, EA, EATGV) += $(FATE_EA_TGV)
+fate-ea-tgv: $(FATE_EA_TGV)
+
+FATE_SAMPLES_FFMPEG += $(FATE_SAMPLES_EA-yes)
+fate-ea: $(FATE_SAMPLES_EA-yes)
diff --git a/tests/fate/fft.mak b/tests/fate/fft.mak
index d3889cc..20d5638 100644
--- a/tests/fate/fft.mak
+++ b/tests/fate/fft.mak
@@ -38,5 +38,5 @@
 $(FATE_FFT_FIXED): CMD = run libavcodec/fft-fixed-test $(CPUFLAGS:%=-c%) $(ARGS)
 $(FATE_FFT_FIXED): REF = /dev/null
 
-FATE-$(CONFIG_FFT) += $(FATE_FFT) $(FATE_FFT_FIXED)
+FATE-$(call ALLYES, AVCODEC FFT) += $(FATE_FFT) $(FATE_FFT_FIXED)
 fate-fft: $(FATE_FFT) $(FATE_FFT_FIXED)
diff --git a/tests/fate/filter.mak b/tests/fate/filter.mak
index 3d563c8..66ff333 100644
--- a/tests/fate/filter.mak
+++ b/tests/fate/filter.mak
@@ -45,4 +45,23 @@
 FATE_FILTER-$(CONFIG_YADIF_FILTER) += $(FATE_YADIF)
 
 FATE_SAMPLES_AVCONV += $(FATE_FILTER-yes)
-fate-filter: $(FATE_FILTER-yes)
+
+#
+# Metadata tests
+#
+FILTER_METADATA_COMMAND = ffprobe$(EXESUF) -show_frames -of compact=nk=1:p=0 -bitexact -f lavfi
+
+SCENEDETECT_DEPS = FFPROBE LAVFI_INDEV MOVIE_FILTER SELECT_FILTER SCALE_FILTER \
+                   AVCODEC MOV_DEMUXER SVQ3_DECODER ZLIB
+FATE_METADATA_FILTER-$(call ALLYES, $(SCENEDETECT_DEPS)) += fate-filter-metadata-scenedetect
+fate-filter-metadata-scenedetect: SRC = $(SAMPLES)/svq3/Vertical400kbit.sorenson3.mov
+fate-filter-metadata-scenedetect: CMD = run $(FILTER_METADATA_COMMAND) "sws_flags=+accurate_rnd+bitexact;movie='$(SRC)',select=gt(scene\,.4)"
+
+SILENCEDETECT_DEPS = FFPROBE LAVFI_INDEV AMOVIE_FILTER AMR_DEMUXER AMRWB_DECODER
+FATE_METADATA_FILTER-$(call ALLYES, $(SILENCEDETECT_DEPS)) += fate-filter-metadata-silencedetect
+fate-filter-metadata-silencedetect: SRC = $(SAMPLES)/amrwb/seed-12k65.awb
+fate-filter-metadata-silencedetect: CMD = run $(FILTER_METADATA_COMMAND) "amovie='$(SRC)',silencedetect=d=.1"
+
+FATE_SAMPLES_FFPROBE += $(FATE_METADATA_FILTER-yes)
+
+fate-filter: $(FATE_FILTER-yes) $(FATE_METADATA_FILTER-yes)
diff --git a/tests/fate/flac.mak b/tests/fate/flac.mak
index dc49928..92eb743 100644
--- a/tests/fate/flac.mak
+++ b/tests/fate/flac.mak
@@ -1,17 +1,24 @@
-FATE_FLAC += fate-flac-chmode-indep                                     \
-             fate-flac-chmode-left_side                                 \
-             fate-flac-chmode-mid_side                                  \
-             fate-flac-chmode-right_side                                \
-             fate-flac-fixed                                            \
-             fate-flac-lpc-cholesky                                     \
-             fate-flac-lpc-levinson                                     \
+FATE_FLAC += fate-flac-16-chmode-indep                                  \
+             fate-flac-16-chmode-left_side                              \
+             fate-flac-16-chmode-mid_side                               \
+             fate-flac-16-chmode-right_side                             \
+             fate-flac-16-fixed                                         \
+             fate-flac-16-lpc-cholesky                                  \
+             fate-flac-16-lpc-levinson                                  \
+             fate-flac-24-comp-8                                        \
 
-fate-flac-chmode-%: OPTS = -ch_mode $(@:fate-flac-chmode-%=%)
-fate-flac-fixed: OPTS = -lpc_type fixed
-fate-flac-lpc-%: OPTS = -lpc_type $(@:fate-flac-lpc-%=%)
+fate-flac-16-chmode-%: OPTS = -ch_mode $(@:fate-flac-16-chmode-%=%)
+fate-flac-16-fixed:    OPTS = -lpc_type fixed
+fate-flac-16-lpc-%:    OPTS = -lpc_type $(@:fate-flac-16-lpc-%=%)
 
-fate-flac-%: REF = $(SAMPLES)/audio-reference/luckynight_2ch_44kHz_s16.wav
-fate-flac-%: CMD = enc_dec_pcm flac wav s16le $(REF) -c flac $(OPTS)
+fate-flac-16-%: REF = $(SAMPLES)/audio-reference/luckynight_2ch_44kHz_s16.wav
+fate-flac-16-%: CMD = enc_dec_pcm flac wav s16le $(REF) -c flac $(OPTS)
+
+fate-flac-24-comp-%: OPTS = -compression_level $(@:fate-flac-24-comp-%=%)
+
+fate-flac-24-%: REF = $(SAMPLES)/audio-reference/divertimenti_2ch_96kHz_s24.wav
+fate-flac-24-%: CMD = enc_dec_pcm flac wav s24le $(REF) -c flac $(OPTS)
+
 fate-flac-%: CMP = oneoff
 fate-flac-%: FUZZ = 0
 
diff --git a/tests/fate/h264.mak b/tests/fate/h264.mak
index 113f9ca..75fd58c 100644
--- a/tests/fate/h264.mak
+++ b/tests/fate/h264.mak
@@ -183,13 +183,15 @@
             sva_nl2_e                                                   \
 
 FATE_H264  := $(FATE_H264:%=fate-h264-conformance-%)                    \
-              fate-h264-interlace-crop                                  \
               fate-h264-lossless                                        \
               fate-h264-extreme-plane-pred                              \
-              fate-h264-bsf-mp4toannexb                                 \
 
-FATE_SAMPLES_AVCONV += $(FATE_H264)
-fate-h264: $(FATE_H264)
+FATE_H264-$(call DEMDEC, H264, H264) += $(FATE_H264)
+FATE_H264-$(call DEMDEC,  MOV, H264) += fate-h264-interlace-crop
+FATE_H264-$(call ALLYES, MOV_DEMUXER H264_MP4TOANNEXB_BSF) += fate-h264-bsf-mp4toannexb
+
+FATE_SAMPLES_AVCONV += $(FATE_H264-yes)
+fate-h264: $(FATE_H264-yes)
 
 fate-h264-conformance-aud_mw_e: CMD = framecrc -vsync drop -i $(SAMPLES)/h264-conformance/AUD_MW_E.264
 fate-h264-conformance-ba1_ft_c: CMD = framecrc -vsync drop -i $(SAMPLES)/h264-conformance/BA1_FT_C.264
diff --git a/tests/fate/image.mak b/tests/fate/image.mak
index 5b89960..8770c74 100644
--- a/tests/fate/image.mak
+++ b/tests/fate/image.mak
@@ -70,6 +70,9 @@
 FATE_IMAGE += $(FATE_TIFF)
 fate-tiff: $(FATE_TIFF)
 
+FATE_IMAGE += fate-xface
+fate-xface: CMD = framecrc -i $(SAMPLES)/xface/lena.xface
+
 FATE_SAMPLES_FFMPEG += $(FATE_IMAGE)
 fate-image: $(FATE_IMAGE)
 
diff --git a/tests/fate/indeo.mak b/tests/fate/indeo.mak
index 783af5d..5a99b46 100644
--- a/tests/fate/indeo.mak
+++ b/tests/fate/indeo.mak
@@ -1,14 +1,14 @@
-FATE_INDEO += fate-indeo2
+FATE_INDEO-$(call DEMDEC, AVI, INDEO2) += fate-indeo2
 fate-indeo2: CMD = framecrc -i $(SAMPLES)/rt21/VPAR0026.AVI
 
-FATE_INDEO += fate-indeo3
+FATE_INDEO-$(call DEMDEC, MOV, INDEO3) += fate-indeo3
 fate-indeo3: CMD = framecrc -i $(SAMPLES)/iv32/cubes.mov
 
-FATE_INDEO += fate-indeo4
+FATE_INDEO-$(call DEMDEC, AVI, INDEO4) += fate-indeo4
 fate-indeo4: CMD = framecrc -i $(SAMPLES)/iv41/indeo41-partial.avi -an
 
-FATE_INDEO += fate-indeo5
+FATE_INDEO-$(call DEMDEC, AVI, INDEO5) += fate-indeo5
 fate-indeo5: CMD = framecrc -i $(SAMPLES)/iv50/Educ_Movie_DeadlyForce.avi -an
 
-FATE_SAMPLES_AVCONV += $(FATE_INDEO)
-fate-indeo: $(FATE_INDEO)
+FATE_SAMPLES_AVCONV += $(FATE_INDEO-yes)
+fate-indeo: $(FATE_INDEO-yes)
diff --git a/tests/fate/libavcodec.mak b/tests/fate/libavcodec.mak
index 2aa9596..6e81f57 100644
--- a/tests/fate/libavcodec.mak
+++ b/tests/fate/libavcodec.mak
@@ -1,10 +1,23 @@
-FATE_LIBAVCODEC += fate-golomb
+FATE_LIBAVCODEC-$(CONFIG_GOLOMB) += fate-golomb
 fate-golomb: libavcodec/golomb-test$(EXESUF)
 fate-golomb: CMD = run libavcodec/golomb-test
 fate-golomb: REF = /dev/null
 
-FATE_LIBAVCODEC += fate-iirfilter
+FATE_LIBAVCODEC-yes += fate-idct8x8
+fate-idct8x8: libavcodec/dct-test$(EXESUF)
+fate-idct8x8: CMD = run libavcodec/dct-test -i
+fate-idct8x8: CMP = null
+fate-idct8x8: REF = /dev/null
+
+FATE_LIBAVCODEC-yes += fate-iirfilter
 fate-iirfilter: libavcodec/iirfilter-test$(EXESUF)
 fate-iirfilter: CMD = run libavcodec/iirfilter-test
 
-fate-libavcodec: $(FATE_LIBAVCODEC)
+FATE_LIBAVCODEC-$(CONFIG_RANGECODER) += fate-rangecoder
+fate-rangecoder: libavcodec/rangecoder-test$(EXESUF)
+fate-rangecoder: CMD = run libavcodec/rangecoder-test
+fate-rangecoder: CMP = null
+fate-rangecoder: REF = /dev/null
+
+FATE-$(CONFIG_AVCODEC) += $(FATE_LIBAVCODEC-yes)
+fate-libavcodec: $(FATE_LIBAVCODEC-yes)
diff --git a/tests/fate/libavformat.mak b/tests/fate/libavformat.mak
new file mode 100644
index 0000000..b6eda42
--- /dev/null
+++ b/tests/fate/libavformat.mak
@@ -0,0 +1,6 @@
+FATE_LIBAVFORMAT += fate-url
+fate-url: libavformat/url-test$(EXESUF)
+fate-url: CMD = run libavformat/url-test
+
+FATE-$(CONFIG_AVFORMAT) += $(FATE_LIBAVFORMAT)
+fate-libavformat: $(FATE_LIBAVFORMAT)
diff --git a/tests/fate/libavutil.mak b/tests/fate/libavutil.mak
index 488ec6b..b2484a5 100644
--- a/tests/fate/libavutil.mak
+++ b/tests/fate/libavutil.mak
@@ -8,6 +8,10 @@
 fate-aes: CMD = run libavutil/aes-test
 fate-aes: REF = /dev/null
 
+FATE_LIBAVUTIL += fate-avstring
+fate-avstring: libavutil/avstring-test$(EXESUF)
+fate-avstring: CMD = run libavutil/avstring-test
+
 FATE_LIBAVUTIL += fate-base64
 fate-base64: libavutil/base64-test$(EXESUF)
 fate-base64: CMD = run libavutil/base64-test
@@ -57,4 +61,5 @@
 fate-xtea: libavutil/xtea-test$(EXESUF)
 fate-xtea: CMD = run libavutil/xtea-test
 
+FATE-$(CONFIG_AVUTIL) += $(FATE_LIBAVUTIL)
 fate-libavutil: $(FATE_LIBAVUTIL)
diff --git a/tests/fate/lossless-audio.mak b/tests/fate/lossless-audio.mak
index e87bb99..50ebdd9 100644
--- a/tests/fate/lossless-audio.mak
+++ b/tests/fate/lossless-audio.mak
@@ -1,21 +1,26 @@
-FATE_SAMPLES_LOSSLESS_AUDIO += fate-lossless-alac
+FATE_SAMPLES_LOSSLESS_AUDIO-$(call DEMDEC, MOV, ALAC) += fate-lossless-alac
 fate-lossless-alac: CMD = md5 -i $(SAMPLES)/lossless-audio/inside.m4a -f s16le
 
-FATE_SAMPLES_LOSSLESS_AUDIO += fate-lossless-meridianaudio
+FATE_SAMPLES_LOSSLESS_AUDIO-$(call DEMDEC, MLP, MLP) += fate-lossless-meridianaudio
 fate-lossless-meridianaudio: CMD = md5 -i $(SAMPLES)/lossless-audio/luckynight-partial.mlp -f s16le
 
-FATE_SAMPLES_LOSSLESS_AUDIO += fate-lossless-monkeysaudio
+FATE_SAMPLES_LOSSLESS_AUDIO-$(call DEMDEC, APE, APE) += fate-lossless-monkeysaudio
 fate-lossless-monkeysaudio: CMD = md5 -i $(SAMPLES)/lossless-audio/luckynight-partial.ape -f s16le
 
-FATE_SAMPLES_LOSSLESS_AUDIO += fate-lossless-shorten
+FATE_SAMPLES_LOSSLESS_AUDIO-$(call DEMDEC, SHORTEN, SHORTEN) += fate-lossless-shorten
 fate-lossless-shorten: CMD = md5 -i $(SAMPLES)/lossless-audio/luckynight-partial.shn -f s16le
 
-FATE_SAMPLES_LOSSLESS_AUDIO += fate-lossless-tta
+FATE_SAMPLES_LOSSLESS_AUDIO-$(call DEMDEC, TAK, TAK) += fate-lossless-tak
+fate-lossless-tak: CMD = crc -i $(SAMPLES)/lossless-audio/luckynight-partial.tak
+
+FATE_SAMPLES_LOSSLESS_AUDIO-$(call DEMDEC, TTA, TTA) += fate-lossless-tta
 fate-lossless-tta: CMD = crc -i $(SAMPLES)/lossless-audio/inside.tta
 
-FATE_SAMPLES_LOSSLESS_AUDIO += fate-lossless-wma
+FATE_SAMPLES_LOSSLESS_AUDIO-$(call DEMDEC, ASF, WMALOSSLESS) += fate-lossless-wma
 fate-lossless-wma: CMD = md5 -i $(SAMPLES)/lossless-audio/luckynight-partial.wma -f s16le
 
+FATE_SAMPLES_LOSSLESS_AUDIO += $(FATE_SAMPLES_LOSSLESS_AUDIO-yes)
+
 FATE_SAMPLES_FFMPEG += $(FATE_SAMPLES_LOSSLESS_AUDIO)
 fate-lossless-audio: $(FATE_SAMPLES_LOSSLESS_AUDIO)
 
diff --git a/tests/fate/lossless-video.mak b/tests/fate/lossless-video.mak
index cbf7f52..b648b08 100644
--- a/tests/fate/lossless-video.mak
+++ b/tests/fate/lossless-video.mak
@@ -4,7 +4,7 @@
 FATE_CLLC += fate-cllc-argb
 fate-cllc-argb: CMD = framecrc -i $(SAMPLES)/cllc/sample-cllc-argb.avi
 
-FATE_LOSSLESS_VIDEO += $(FATE_CLLC)
+FATE_LOSSLESS_VIDEO-$(call DEMDEC, AVI, CLLC) += $(FATE_CLLC)
 fate-cllc: $(FATE_CLLC)
 
 FATE_LAGARITH += fate-lagarith-rgb24
@@ -19,7 +19,7 @@
 FATE_LAGARITH += fate-lagarith-yv12
 fate-lagarith-yv12: CMD = framecrc -i $(SAMPLES)/lagarith/lag-yv12.avi
 
-FATE_SAMPLES_AVCONV += $(FATE_LAGARITH)
+FATE_LOSSLESS_VIDEO-$(call DEMDEC, AVI, LAGARITH) += $(FATE_LAGARITH)
 fate-lagarith: $(FATE_LAGARITH)
 
 FATE_LOCO += fate-loco-rgb
@@ -28,22 +28,22 @@
 FATE_LOCO += fate-loco-yuy2
 fate-loco-yuy2: CMD = framecrc -i $(SAMPLES)/loco/pig-loco-0.avi
 
-FATE_LOSSLESS_VIDEO += $(FATE_LOCO)
+FATE_LOSSLESS_VIDEO-$(call DEMDEC, AVI, LOCO) += $(FATE_LOCO)
 fate-loco: $(FATE_LOCO)
 
-FATE_LOSSLESS_VIDEO += fate-msrle-8bit
+FATE_LOSSLESS_VIDEO-$(call DEMDEC, AVI, MSRLE) += fate-msrle-8bit
 fate-msrle-8bit: CMD = framecrc -i $(SAMPLES)/msrle/Search-RLE.avi -pix_fmt rgb24
 
-FATE_LOSSLESS_VIDEO += fate-mszh
+FATE_LOSSLESS_VIDEO-$(call DEMDEC, AVI, MSZH) += fate-mszh
 fate-mszh: CMD = framecrc -i $(SAMPLES)/lcl/mszh-1frame.avi
 
-FATE_LOSSLESS_VIDEO += fate-vble
+FATE_LOSSLESS_VIDEO-$(call DEMDEC, AVI, VBLE) += fate-vble
 fate-vble: CMD = framecrc -i $(SAMPLES)/vble/flowers-partial-2MB.avi
 
-FATE_LOSSLESS_VIDEO-$(CONFIG_ZLIB) += fate-zlib
+FATE_LOSSLESS_VIDEO-$(call DEMDEC, AVI, ZLIB) += fate-zlib
 fate-zlib: CMD = framecrc -i $(SAMPLES)/lcl/zlib-1frame.avi
 
-FATE_LOSSLESS_VIDEO-$(CONFIG_ZLIB) += fate-zerocodec
+FATE_LOSSLESS_VIDEO-$(call DEMDEC, AVI, ZEROCODEC) += fate-zerocodec
 fate-zerocodec: CMD = framecrc -i $(SAMPLES)/zerocodec/sample-zeco.avi
 
 FATE_LOSSLESS_VIDEO += $(FATE_LOSSLESS_VIDEO-yes)
diff --git a/tests/fate/mapchan.mak b/tests/fate/mapchan.mak
index 119f566..d8b3ba0 100644
--- a/tests/fate/mapchan.mak
+++ b/tests/fate/mapchan.mak
@@ -1,14 +1,14 @@
 FATE_MAPCHAN += fate-mapchan-6ch-extract-2
 fate-mapchan-6ch-extract-2: tests/data/asynth-22050-6.wav
-fate-mapchan-6ch-extract-2: CMD = ffmpeg -i $(TARGET_PATH)/tests/data/asynth-22050-6.wav -map_channel 0.0.0 -f wav md5: -map_channel 0.0.1 -f wav md5:
+fate-mapchan-6ch-extract-2: CMD = ffmpeg -i $(TARGET_PATH)/tests/data/asynth-22050-6.wav -map_channel 0.0.0 -flags +bitexact -f wav md5: -map_channel 0.0.1 -flags +bitexact -f wav md5:
 
 FATE_MAPCHAN += fate-mapchan-6ch-extract-2-downmix-mono
 fate-mapchan-6ch-extract-2-downmix-mono: tests/data/asynth-22050-6.wav
-fate-mapchan-6ch-extract-2-downmix-mono: CMD = md5 -i $(TARGET_PATH)/tests/data/asynth-22050-6.wav -map_channel 0.0.1 -map_channel 0.0.0 -ac 1 -f wav
+fate-mapchan-6ch-extract-2-downmix-mono: CMD = md5 -i $(TARGET_PATH)/tests/data/asynth-22050-6.wav -map_channel 0.0.1 -map_channel 0.0.0 -ac 1 -flags +bitexact -f wav
 
 FATE_MAPCHAN += fate-mapchan-silent-mono
 fate-mapchan-silent-mono: tests/data/asynth-22050-1.wav
-fate-mapchan-silent-mono: CMD = md5 -i $(TARGET_PATH)/tests/data/asynth-22050-1.wav -map_channel -1 -map_channel 0.0.0 -f wav
+fate-mapchan-silent-mono: CMD = md5 -i $(TARGET_PATH)/tests/data/asynth-22050-1.wav -map_channel -1 -map_channel 0.0.0 -flags +bitexact -f wav
 
 FATE_FFMPEG += $(FATE_MAPCHAN)
 fate-mapchan: $(FATE_MAPCHAN)
diff --git a/tests/fate/microsoft.mak b/tests/fate/microsoft.mak
index e9cd9b1..a2b3f1f 100644
--- a/tests/fate/microsoft.mak
+++ b/tests/fate/microsoft.mak
@@ -1,4 +1,4 @@
-FATE_MICROSOFT += fate-msmpeg4v1
+FATE_MICROSOFT-$(call DEMDEC, AVI, MSMPEG4V1) += fate-msmpeg4v1
 fate-msmpeg4v1: CMD = framecrc -flags +bitexact -dct fastint -idct simple -i $(SAMPLES)/msmpeg4v1/mpg4.avi -an
 
 FATE_MSVIDEO1 += fate-msvideo1-16bit
@@ -7,7 +7,7 @@
 FATE_MSVIDEO1 += fate-msvideo1-8bit
 fate-msvideo1-8bit: CMD = framecrc -i $(SAMPLES)/cram/skating.avi -t 1 -pix_fmt rgb24
 
-FATE_MICROSOFT += $(FATE_MSVIDEO1)
+FATE_MICROSOFT-$(call DEMDEC, AVI, MSVIDEO1) += $(FATE_MSVIDEO1)
 fate-msvideo1: $(FATE_MSVIDEO1)
 
 FATE_WMV8_DRM += fate-wmv8-drm
@@ -21,29 +21,31 @@
 FATE_TESTS-no += fate-wmv8-x8intra
 fate-wmv8-x8intra: CMD = framecrc -flags +bitexact -idct 19 -i $(SAMPLES)/wmv8/wmv8_x8intra.wmv -an
 
-FATE_MICROSOFT += $(FATE_WMV8_DRM)
+FATE_MICROSOFT-$(call DEMDEC, ASF, WMV3) += $(FATE_WMV8_DRM)
 fate-wmv8_drm: $(FATE_WMV8_DRM)
 
-FATE_VC1 += fate-vc1_sa00040
+FATE_VC1-$(CONFIG_VC1_DEMUXER) += fate-vc1_sa00040
 fate-vc1_sa00040: CMD = framecrc -i $(SAMPLES)/vc1/SA00040.vc1
 
-FATE_VC1 += fate-vc1_sa00050
+FATE_VC1-$(CONFIG_VC1_DEMUXER) += fate-vc1_sa00050
 fate-vc1_sa00050: CMD = framecrc -i $(SAMPLES)/vc1/SA00050.vc1
 
-FATE_VC1 += fate-vc1_sa10091
+FATE_VC1-$(CONFIG_VC1_DEMUXER) += fate-vc1_sa10091
 fate-vc1_sa10091: CMD = framecrc -i $(SAMPLES)/vc1/SA10091.vc1
 
-FATE_VC1 += fate-vc1_sa20021
+FATE_VC1-$(CONFIG_VC1_DEMUXER) += fate-vc1_sa20021
 fate-vc1_sa20021: CMD = framecrc -i $(SAMPLES)/vc1/SA20021.vc1
 
-FATE_VC1 += fate-vc1_sa10143
+FATE_VC1-$(CONFIG_VC1_DEMUXER) += fate-vc1_sa10143
 fate-vc1_sa10143: CMD = framecrc -i $(SAMPLES)/vc1/SA10143.vc1
 
-FATE_VC1 += fate-vc1-ism
+FATE_VC1-$(CONFIG_MOV_DEMUXER) += fate-vc1-ism
 fate-vc1-ism: CMD = framecrc -i $(SAMPLES)/isom/vc1-wmapro.ism -an
 
-FATE_MICROSOFT += $(FATE_VC1)
-fate-vc1: $(FATE_VC1)
+FATE_MICROSOFT-$(CONFIG_VC1_DECODER) += $(FATE_VC1-yes)
+fate-vc1: $(FATE_VC1-yes)
+
+FATE_MICROSOFT += $(FATE_MICROSOFT-yes)
 
 FATE_SAMPLES_FFMPEG += $(FATE_MICROSOFT)
 fate-microsoft: $(FATE_MICROSOFT)
diff --git a/tests/fate/mp3.mak b/tests/fate/mp3.mak
index bd0657d..2181fa6 100644
--- a/tests/fate/mp3.mak
+++ b/tests/fate/mp3.mak
@@ -34,3 +34,7 @@
 fate-mp3: $(FATE_MP3)
 $(FATE_MP3): CMP = stddev
 $(FATE_MP3): FUZZ = 0.07
+
+ifdef HAVE_NEON
+fate-mp3-float-conf-hecommon: FUZZ = 0.70
+endif
diff --git a/tests/fate/mpc.mak b/tests/fate/mpc.mak
index 5505a9a..53d236e 100644
--- a/tests/fate/mpc.mak
+++ b/tests/fate/mpc.mak
@@ -1,13 +1,13 @@
-FATE_MPC += fate-mpc7-demux
+FATE_MPC-$(CONFIG_MPC_DEMUXER) += fate-mpc7-demux
 fate-mpc7-demux: CMD = crc -i $(SAMPLES)/musepack/inside-mp7.mpc -acodec copy
 
-FATE_MPC += fate-mpc8-demux
+FATE_MPC-$(CONFIG_MPC8_DEMUXER) += fate-mpc8-demux
 fate-mpc8-demux: CMD = crc -i $(SAMPLES)/musepack/inside-mp8.mpc -acodec copy
 
-FATE_MPC += fate-musepack7
+FATE_MPC-$(call DEMDEC, MPC, MPC7) += 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_SAMPLES_FFMPEG += $(FATE_MPC)
-fate-mpc: $(FATE_MPC)
+FATE_SAMPLES_AVCONV += $(FATE_MPC-yes)
+fate-mpc: $(FATE_MPC-yes)
diff --git a/tests/fate/prores.mak b/tests/fate/prores.mak
index 9f4d1b3..00e2159 100644
--- a/tests/fate/prores.mak
+++ b/tests/fate/prores.mak
@@ -4,7 +4,7 @@
               fate-prores-422_proxy                                     \
               fate-prores-alpha                                         \
 
-FATE_SAMPLES_AVCONV += $(FATE_PRORES)
+FATE_SAMPLES_AVCONV-$(call DEMDEC, MOV, PRORES) += $(FATE_PRORES)
 fate-prores: $(FATE_PRORES)
 
 fate-prores-422:       CMD = framecrc -flags +bitexact -i $(SAMPLES)/prores/Sequence_1-Apple_ProRes_422.mov -pix_fmt yuv422p10le
diff --git a/tests/fate/qt.mak b/tests/fate/qt.mak
index 3068ac6..03b2fce 100644
--- a/tests/fate/qt.mak
+++ b/tests/fate/qt.mak
@@ -1,52 +1,52 @@
-FATE_QT += fate-8bps
+FATE_QT-$(call DEMDEC, MOV, EIGHTBPS) += fate-8bps
 fate-8bps: CMD = framecrc -i $(SAMPLES)/8bps/full9iron-partial.mov -pix_fmt rgb24
 
-FATE_QT += fate-qdm2
+FATE_QT-$(call DEMDEC, MOV, QDM2) += 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_QT += fate-qt-alaw-mono
+FATE_QT-$(call DEMDEC, MOV, PCM_ALAW) += fate-qt-alaw-mono
 fate-qt-alaw-mono: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-1-16-B-alaw.mov -f s16le
 
-FATE_QT += fate-qt-alaw-stereo
+FATE_QT-$(call DEMDEC, MOV, PCM_ALAW) += fate-qt-alaw-stereo
 fate-qt-alaw-stereo: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-2-16-B-alaw.mov -f s16le
 
-FATE_QT += fate-qt-ima4-mono
+FATE_QT-$(call DEMDEC, MOV, ADPCM_IMA_QT) += fate-qt-ima4-mono
 fate-qt-ima4-mono: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-1-16-B-ima4.mov -f s16le
 
-FATE_QT += fate-qt-ima4-stereo
+FATE_QT-$(call DEMDEC, MOV, ADPCM_IMA_QT) += fate-qt-ima4-stereo
 fate-qt-ima4-stereo: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-2-16-B-ima4.mov -f s16le
 
-FATE_QT += fate-qt-mac3-mono
+FATE_QT-$(call DEMDEC, MOV, MACE3) += fate-qt-mac3-mono
 fate-qt-mac3-mono: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-1-8-MAC3.mov -f s16le
 
-FATE_QT += fate-qt-mac3-stereo
+FATE_QT-$(call DEMDEC, MOV, MACE3) += fate-qt-mac3-stereo
 fate-qt-mac3-stereo: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-2-8-MAC3.mov -f s16le
 
-FATE_QT += fate-qt-mac6-mono
+FATE_QT-$(call DEMDEC, MOV, MACE6) += fate-qt-mac6-mono
 fate-qt-mac6-mono: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-1-8-MAC6.mov -f s16le
 
-FATE_QT += fate-qt-mac6-stereo
+FATE_QT-$(call DEMDEC, MOV, MACE6) += fate-qt-mac6-stereo
 fate-qt-mac6-stereo: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-2-8-MAC6.mov -f s16le
 
-FATE_QT += fate-qt-ulaw-mono
+FATE_QT-$(call DEMDEC, MOV, PCM_MULAW) += fate-qt-ulaw-mono
 fate-qt-ulaw-mono: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-1-16-B-ulaw.mov -f s16le
 
-FATE_QT += fate-qt-ulaw-stereo
+FATE_QT-$(call DEMDEC, MOV, PCM_MULAW) += fate-qt-ulaw-stereo
 fate-qt-ulaw-stereo: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-2-16-B-ulaw.mov -f s16le
 
-FATE_QT += fate-quickdraw
+FATE_QT-$(call DEMDEC, MOV, QDRAW) += fate-quickdraw
 fate-quickdraw: CMD = framecrc -i $(SAMPLES)/quickdraw/Airplane.mov -pix_fmt rgb24
 
-FATE_QT += fate-rpza
+FATE_QT-$(call DEMDEC, MOV, RPZA) += fate-rpza
 fate-rpza: CMD = framecrc -i $(SAMPLES)/rpza/rpza2.mov -t 2 -pix_fmt rgb24
 
-FATE_QT += fate-svq1
+FATE_QT-$(call DEMDEC, MOV, SVQ1) += fate-svq1
 fate-svq1: CMD = framecrc -i $(SAMPLES)/svq1/marymary-shackles.mov -an -t 10
 
-FATE_QT-$(CONFIG_ZLIB) += fate-svq3
+FATE_QT-$(call ALLYES, MOV_DEMUXER SVQ3_DECODER ZLIB) += fate-svq3
 fate-svq3: CMD = framecrc -i $(SAMPLES)/svq3/Vertical400kbit.sorenson3.mov -t 6 -an
 
 FATE_QT += $(FATE_QT-yes)
diff --git a/tests/fate/qtrle.mak b/tests/fate/qtrle.mak
index 3850a80..d8a6ecf 100644
--- a/tests/fate/qtrle.mak
+++ b/tests/fate/qtrle.mak
@@ -19,5 +19,5 @@
 FATE_QTRLE += fate-qtrle-32bit
 fate-qtrle-32bit: CMD = framecrc -i $(SAMPLES)/qtrle/ultra_demo_720_480_32bpp_rle.mov -pix_fmt rgb24
 
-FATE_SAMPLES_AVCONV += $(FATE_QTRLE)
+FATE_SAMPLES_AVCONV-$(call DEMDEC, MOV, QTRLE) += $(FATE_QTRLE)
 fate-qtrle: $(FATE_QTRLE)
diff --git a/tests/fate/real.mak b/tests/fate/real.mak
index aa3a5af..49b2eb4 100644
--- a/tests/fate/real.mak
+++ b/tests/fate/real.mak
@@ -1,48 +1,46 @@
-FATE_REAL += fate-ra-144
+FATE_REAL-$(call DEMDEC, RM, RA_144) += fate-ra-144
 fate-ra-144: CMD = md5 -i $(SAMPLES)/real/ra3_in_rm_file.rm -f s16le
 
-FATE_REAL += fate-ra-288
+FATE_REAL-$(call DEMDEC, RM, RA_288) += 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_REAL += fate-ra-cook
+FATE_REAL-$(call DEMDEC, RM, COOK) += 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_REAL += fate-ralf
+FATE_REAL-$(call DEMDEC, RM, RALF) += fate-ralf
 fate-ralf: CMD = md5 -i $(SAMPLES)/lossless-audio/luckynight-partial.rmvb -vn -f s16le
 
-FATE_REAL += fate-rv30
+FATE_REAL-$(call DEMDEC, RM, RV30) += fate-rv30
 fate-rv30: CMD = framecrc -flags +bitexact -dct fastint -idct simple -i $(SAMPLES)/real/rv30.rm -an
 
-FATE_REAL += fate-rv40
+FATE_REAL-$(call DEMDEC, RM, RV40) += fate-rv40
 fate-rv40: CMD = framecrc -i $(SAMPLES)/real/spygames-2MB.rmvb -t 10 -an
 
 FATE_SIPR += 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_SIPR += 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_SIPR += 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_SIPR += 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_REAL += $(FATE_SIPR)
+$(FATE_SIPR): CMP = oneoff
+
+FATE_REAL-$(call DEMDEC, RM, SIPR) += $(FATE_SIPR)
 fate-sipr: $(FATE_SIPR)
 
-FATE_SAMPLES_FFMPEG += $(FATE_REAL)
-fate-real: $(FATE_REAL)
+FATE_SAMPLES_FFMPEG += $(FATE_REAL-yes)
+fate-real: $(FATE_REAL-yes)
diff --git a/tests/fate/screen.mak b/tests/fate/screen.mak
index 14264a6..b55e02b 100644
--- a/tests/fate/screen.mak
+++ b/tests/fate/screen.mak
@@ -1,8 +1,8 @@
 # FIXME dropped frames in this test because of coarse timebase
-FATE_SCREEN += fate-cscd
+FATE_SCREEN-$(call DEMDEC, AVI, CSCD) += fate-cscd
 fate-cscd: CMD = framecrc -i $(SAMPLES)/CSCD/sample_video.avi -an -pix_fmt rgb24
 
-FATE_SCREEN += fate-dxtory
+FATE_SCREEN-$(call DEMDEC, AVI, DXTORY) += fate-dxtory
 fate-dxtory: CMD = framecrc -i $(SAMPLES)/dxtory/dxtory_mic.avi
 
 FATE_FRAPS += fate-fraps-v0
@@ -23,7 +23,7 @@
 FATE_FRAPS += fate-fraps-v5
 fate-fraps-v5: CMD = framecrc -i $(SAMPLES)/fraps/fraps-v5-bouncing-balls-partial.avi
 
-FATE_SCREEN += $(FATE_FRAPS)
+FATE_SCREEN-$(call DEMDEC, AVI, FRAPS) += $(FATE_FRAPS)
 fate-fraps: $(FATE_FRAPS)
 
 FATE_TSCC += fate-tscc-15bit
@@ -32,7 +32,7 @@
 FATE_TSCC += fate-tscc-32bit
 fate-tscc-32bit: CMD = framecrc -i $(SAMPLES)/tscc/2004-12-17-uebung9-partial.avi -pix_fmt rgb24 -an
 
-FATE_SCREEN-$(CONFIG_ZLIB) += $(FATE_TSCC)
+FATE_SCREEN-$(call DEMDEC, AVI, TSCC) += $(FATE_TSCC)
 fate-tscc: $(FATE_TSCC)
 
 FATE_VMNC += fate-vmnc-16bit
@@ -41,7 +41,7 @@
 FATE_VMNC += fate-vmnc-32bit
 fate-vmnc-32bit: CMD = framecrc -i $(SAMPLES)/VMnc/VS2k5DebugDemo-01-partial.avi -pix_fmt rgb24
 
-FATE_SCREEN += $(FATE_VMNC)
+FATE_SCREEN-$(call DEMDEC, AVI, VMNC) += $(FATE_VMNC)
 fate-vmnc: $(FATE_VMNC)
 
 FATE_ZMBV += fate-zmbv-8bit
@@ -56,7 +56,7 @@
 FATE_ZMBV += fate-zmbv-32bit
 fate-zmbv-32bit: CMD = framecrc -i $(SAMPLES)/zmbv/zmbv_32bit.avi -pix_fmt rgb24 -t 25
 
-FATE_SCREEN-$(CONFIG_ZLIB) += $(FATE_ZMBV)
+FATE_SCREEN-$(call DEMDEC, AVI, ZMBV) += $(FATE_ZMBV)
 fate-zmbv: $(FATE_ZMBV)
 
 FATE_SCREEN += $(FATE_SCREEN-yes)
diff --git a/tests/fate/seek.mak b/tests/fate/seek.mak
new file mode 100644
index 0000000..fa1f790
--- /dev/null
+++ b/tests/fate/seek.mak
@@ -0,0 +1,235 @@
+# files from fate-acodec
+
+FATE_SEEK_ACODEC-$(call ENCDEC, PCM_ALAW,      WAV)     += pcm-alaw
+FATE_SEEK_ACODEC-$(call ENCDEC, PCM_MULAW,     WAV)     += pcm-mulaw
+FATE_SEEK_ACODEC-$(call ENCDEC, PCM_S8,        MOV)     += pcm-s8
+FATE_SEEK_ACODEC-$(call ENCDEC, PCM_U8,        WAV)     += pcm-u8
+FATE_SEEK_ACODEC-$(call ENCDEC, PCM_S16BE,     MOV)     += pcm-s16be
+FATE_SEEK_ACODEC-$(call ENCDEC, PCM_S16LE,     WAV)     += pcm-s16le
+FATE_SEEK_ACODEC-$(call ENCDEC, PCM_S24BE,     MOV)     += pcm-s24be
+FATE_SEEK_ACODEC-$(call ENCDEC, PCM_S24LE,     WAV)     += pcm-s24le
+FATE_SEEK_ACODEC-$(call ENCDEC, PCM_S32BE,     MOV)     += pcm-s32be
+FATE_SEEK_ACODEC-$(call ENCDEC, PCM_S32LE,     WAV)     += pcm-s32le
+FATE_SEEK_ACODEC-$(call ENCDEC, PCM_F32BE,     AU)      += pcm-f32be
+FATE_SEEK_ACODEC-$(call ENCDEC, PCM_F32LE,     WAV)     += pcm-f32le
+FATE_SEEK_ACODEC-$(call ENCDEC, PCM_F64BE,     AU)      += pcm-f64be
+FATE_SEEK_ACODEC-$(call ENCDEC, PCM_F64LE,     WAV)     += pcm-f64le
+FATE_SEEK_ACODEC-$(call ENCDEC, ADPCM_IMA_QT,  AIFF)    += adpcm-ima_qt
+FATE_SEEK_ACODEC-$(call ENCDEC, ADPCM_IMA_WAV, WAV)     += adpcm-ima_wav
+FATE_SEEK_ACODEC-$(call ENCDEC, ADPCM_MS,      WAV)     += adpcm-ms
+FATE_SEEK_ACODEC-$(call ENCDEC, ADPCM_SWF,     FLV)     += adpcm-swf
+FATE_SEEK_ACODEC-$(call ENCDEC, ADPCM_YAMAHA,  WAV)     += adpcm-yamaha
+FATE_SEEK_ACODEC-$(call ENCDEC, ALAC,          MOV)     += alac
+FATE_SEEK_ACODEC-$(call ENCDEC, FLAC,          FLAC)    += flac
+FATE_SEEK_ACODEC-$(call ENCDEC, MP2,           MP2 MP3) += mp2
+
+fate-seek-acodec-adpcm-ima_qt:  SRC = fate/acodec-adpcm-ima_qt.aiff
+fate-seek-acodec-adpcm-ima_wav: SRC = fate/acodec-adpcm-ima_wav.wav
+fate-seek-acodec-adpcm-ms:      SRC = fate/acodec-adpcm-ms.wav
+fate-seek-acodec-adpcm-swf:     SRC = fate/acodec-adpcm-swf.flv
+fate-seek-acodec-adpcm-yamaha:  SRC = fate/acodec-adpcm-yamaha.wav
+fate-seek-acodec-alac:          SRC = fate/acodec-alac.mov
+fate-seek-acodec-flac:          SRC = fate/acodec-flac.flac
+fate-seek-acodec-mp2:           SRC = fate/acodec-mp2.mp2
+fate-seek-acodec-pcm-alaw:      SRC = fate/acodec-pcm-alaw.wav
+fate-seek-acodec-pcm-f32be:     SRC = fate/acodec-pcm-f32be.au
+fate-seek-acodec-pcm-f32le:     SRC = fate/acodec-pcm-f32le.wav
+fate-seek-acodec-pcm-f64be:     SRC = fate/acodec-pcm-f64be.au
+fate-seek-acodec-pcm-f64le:     SRC = fate/acodec-pcm-f64le.wav
+fate-seek-acodec-pcm-mulaw:     SRC = fate/acodec-pcm-mulaw.wav
+fate-seek-acodec-pcm-s16be:     SRC = fate/acodec-pcm-s16be.mov
+fate-seek-acodec-pcm-s16le:     SRC = fate/acodec-pcm-s16le.wav
+fate-seek-acodec-pcm-s24be:     SRC = fate/acodec-pcm-s24be.mov
+fate-seek-acodec-pcm-s24le:     SRC = fate/acodec-pcm-s24le.wav
+fate-seek-acodec-pcm-s32be:     SRC = fate/acodec-pcm-s32be.mov
+fate-seek-acodec-pcm-s32le:     SRC = fate/acodec-pcm-s32le.wav
+fate-seek-acodec-pcm-s8:        SRC = fate/acodec-pcm-s8.mov
+fate-seek-acodec-pcm-u8:        SRC = fate/acodec-pcm-u8.wav
+
+FATE_SEEK += $(FATE_SEEK_ACODEC-yes:%=fate-seek-acodec-%)
+
+# files from fate-vsynth2
+
+FATE_SEEK_VSYNTH2-$(call ENCDEC, ASV1,          AVI)     += asv1
+FATE_SEEK_VSYNTH2-$(call ENCDEC, ASV2,          AVI)     += asv2
+FATE_SEEK_VSYNTH2-$(call ENCDEC, DNXHD,         DNXHD)   += dnxhd-720p
+FATE_SEEK_VSYNTH2-$(call ENCDEC, DNXHD,         DNXHD)   += dnxhd-720p-rd
+FATE_SEEK_VSYNTH2-$(call ENCDEC, DNXHD,         MOV)     += dnxhd-1080i
+FATE_SEEK_VSYNTH2-$(call ENCDEC, DVVIDEO,       DV)      += dv
+FATE_SEEK_VSYNTH2-$(call ENCDEC, DVVIDEO,       DV)      += dv-411
+FATE_SEEK_VSYNTH2-$(call ENCDEC, DVVIDEO,       DV)      += dv-50
+FATE_SEEK_VSYNTH2-$(call ENCDEC, FFV1,          AVI)     += ffv1
+FATE_SEEK_VSYNTH2-$(call ENCDEC, FLASHSV,       FLV)     += flashsv
+FATE_SEEK_VSYNTH2-$(call ENCDEC, FLV,           FLV)     += flv
+FATE_SEEK_VSYNTH2-$(call ENCDEC, H261,          AVI)     += h261
+FATE_SEEK_VSYNTH2-$(call ENCDEC, H263,          AVI)     += h263
+FATE_SEEK_VSYNTH2-$(call ENCDEC, H263,          AVI)     += h263p
+FATE_SEEK_VSYNTH2-$(call ENCDEC, HUFFYUV,       AVI)     += huffyuv
+FATE_SEEK_VSYNTH2-$(call ENCDEC, JPEGLS,        AVI)     += jpegls
+FATE_SEEK_VSYNTH2-$(call ENCDEC, LJPEG MJPEG,   AVI)     += ljpeg
+FATE_SEEK_VSYNTH2-$(call ENCDEC, MJPEG,         AVI)     += mjpeg
+
+FATE_SEEK_VSYNTH2-$(call ENCDEC, MPEG1VIDEO, MPEG1VIDEO MPEGVIDEO) +=          \
+                                                    mpeg1                      \
+                                                    mpeg1b
+
+FATE_SEEK_VSYNTH2-$(call ENCDEC, MPEG2VIDEO, MPEG2VIDEO MPEGVIDEO) +=          \
+                                                    mpeg2-422                  \
+                                                    mpeg2-idct-int             \
+                                                    mpeg2-ilace                \
+                                                    mpeg2-ivlc-qprd            \
+                                                    mpeg2-thread               \
+                                                    mpeg2-thread-ivlc
+
+FATE_SEEK_VSYNTH2-$(call ENCDEC, MPEG4,         MP4 MOV) += mpeg4
+FATE_SEEK_VSYNTH2-$(call ENCDEC, MPEG4, AVI)             += $(FATE_MPEG4_AVI)
+FATE_SEEK_VSYNTH2-$(call ENCDEC, MSMPEG4V3,     AVI)     += msmpeg4
+FATE_SEEK_VSYNTH2-$(call ENCDEC, MSMPEG4V2,     AVI)     += msmpeg4v2
+FATE_SEEK_VSYNTH2-$(call ENCDEC, RAWVIDEO,      AVI)     += rgb
+FATE_SEEK_VSYNTH2-$(call ENCDEC, ROQ,           ROQ)     += roqvideo
+FATE_SEEK_VSYNTH2-$(call ENCDEC, RV10,          RM)      += rv10
+FATE_SEEK_VSYNTH2-$(call ENCDEC, RV20,          RM)      += rv20
+FATE_SEEK_VSYNTH2-$(call ENCDEC, SNOW,          AVI)     += snow
+FATE_SEEK_VSYNTH2-$(call ENCDEC, SNOW,          AVI)     += snow-ll
+FATE_SEEK_VSYNTH2-$(call ENCDEC, SVQ1,          MOV)     += svq1
+FATE_SEEK_VSYNTH2-$(call ENCDEC, WMV1,          AVI)     += wmv1
+FATE_SEEK_VSYNTH2-$(call ENCDEC, WMV2,          AVI)     += wmv2
+FATE_SEEK_VSYNTH2-$(call ENCDEC, RAWVIDEO,      AVI)     += yuv
+
+fate-seek-vsynth2-asv1:              SRC = fate/vsynth2-asv1.avi
+fate-seek-vsynth2-asv2:              SRC = fate/vsynth2-asv2.avi
+fate-seek-vsynth2-dnxhd-1080i:       SRC = fate/vsynth2-dnxhd-1080i.mov
+fate-seek-vsynth2-dnxhd-720p:        SRC = fate/vsynth2-dnxhd-720p.dnxhd
+fate-seek-vsynth2-dnxhd-720p-rd:     SRC = fate/vsynth2-dnxhd-720p.dnxhd
+fate-seek-vsynth2-dv:                SRC = fate/vsynth2-dv.dv
+fate-seek-vsynth2-dv-411:            SRC = fate/vsynth2-dv-411.dv
+fate-seek-vsynth2-dv-50:             SRC = fate/vsynth2-dv-50.dv
+fate-seek-vsynth2-ffv1:              SRC = fate/vsynth2-ffv1.avi
+fate-seek-vsynth2-flashsv:           SRC = fate/vsynth2-flashsv.flv
+fate-seek-vsynth2-flv:               SRC = fate/vsynth2-flv.flv
+fate-seek-vsynth2-h261:              SRC = fate/vsynth2-h261.avi
+fate-seek-vsynth2-h263:              SRC = fate/vsynth2-h263.avi
+fate-seek-vsynth2-h263p:             SRC = fate/vsynth2-h263p.avi
+fate-seek-vsynth2-huffyuv:           SRC = fate/vsynth2-huffyuv.avi
+fate-seek-vsynth2-jpegls:            SRC = fate/vsynth2-jpegls.avi
+fate-seek-vsynth2-ljpeg:             SRC = fate/vsynth2-ljpeg.avi
+fate-seek-vsynth2-mjpeg:             SRC = fate/vsynth2-mjpeg.avi
+fate-seek-vsynth2-mpeg1:             SRC = fate/vsynth2-mpeg1.mpeg1video
+fate-seek-vsynth2-mpeg1b:            SRC = fate/vsynth2-mpeg1b.mpeg1video
+fate-seek-vsynth2-mpeg2-422:         SRC = fate/vsynth2-mpeg2-422.mpeg2video
+fate-seek-vsynth2-mpeg2-idct-int:    SRC = fate/vsynth2-mpeg2-idct-int.mpeg2video
+fate-seek-vsynth2-mpeg2-ilace:       SRC = fate/vsynth2-mpeg2-ilace.mpeg2video
+fate-seek-vsynth2-mpeg2-ivlc-qprd:   SRC = fate/vsynth2-mpeg2-ivlc-qprd.mpeg2video
+fate-seek-vsynth2-mpeg2-thread:      SRC = fate/vsynth2-mpeg2-thread.mpeg2video
+fate-seek-vsynth2-mpeg2-thread-ivlc: SRC = fate/vsynth2-mpeg2-thread-ivlc.mpeg2video
+fate-seek-vsynth2-mpeg4:             SRC = fate/vsynth2-mpeg4.mp4
+fate-seek-vsynth2-mpeg4-adap:        SRC = fate/vsynth2-mpeg4-adap.avi
+fate-seek-vsynth2-mpeg4-adv:         SRC = fate/vsynth2-mpeg4-adv.avi
+fate-seek-vsynth2-mpeg4-error:       SRC = fate/vsynth2-mpeg4-error.avi
+fate-seek-vsynth2-mpeg4-nr:          SRC = fate/vsynth2-mpeg4-nr.avi
+fate-seek-vsynth2-mpeg4-qpel:        SRC = fate/vsynth2-mpeg4-qpel.avi
+fate-seek-vsynth2-mpeg4-qprd:        SRC = fate/vsynth2-mpeg4-qprd.avi
+fate-seek-vsynth2-mpeg4-rc:          SRC = fate/vsynth2-mpeg4-rc.avi
+fate-seek-vsynth2-mpeg4-thread:      SRC = fate/vsynth2-mpeg4-thread.avi
+fate-seek-vsynth2-msmpeg4:           SRC = fate/vsynth2-msmpeg4.avi
+fate-seek-vsynth2-msmpeg4v2:         SRC = fate/vsynth2-msmpeg4v2.avi
+fate-seek-vsynth2-rgb:               SRC = fate/vsynth2-rgb.avi
+fate-seek-vsynth2-roqvideo:          SRC = fate/vsynth2-roqvideo.roq
+fate-seek-vsynth2-rv10:              SRC = fate/vsynth2-rv10.rm
+fate-seek-vsynth2-rv20:              SRC = fate/vsynth2-rv20.rm
+fate-seek-vsynth2-snow:              SRC = fate/vsynth2-snow.avi
+fate-seek-vsynth2-snow-ll:           SRC = fate/vsynth2-snow-ll.avi
+fate-seek-vsynth2-svq1:              SRC = fate/vsynth2-svq1.mov
+fate-seek-vsynth2-wmv1:              SRC = fate/vsynth2-wmv1.avi
+fate-seek-vsynth2-wmv2:              SRC = fate/vsynth2-wmv2.avi
+fate-seek-vsynth2-yuv:               SRC = fate/vsynth2-yuv.avi
+
+FATE_SEEK += $(FATE_SEEK_VSYNTH2-yes:%=fate-seek-vsynth2-%)
+
+# files from fate-lavf
+
+FATE_SEEK_LAVF-$(call ENCDEC,  PCM_S16BE,             AIFF)        += aiff
+FATE_SEEK_LAVF-$(call ENCDEC,  PCM_ALAW,              PCM_ALAW)    += alaw
+FATE_SEEK_LAVF-$(call ENCDEC2, MSMPEG4V3,  MP2,       ASF)         += asf
+FATE_SEEK_LAVF-$(call ENCDEC,  PCM_S16BE,             AU)          += au
+FATE_SEEK_LAVF-$(call ENCDEC2, MPEG4,      MP2,       AVI)         += avi
+FATE_SEEK_LAVF-$(call ENCDEC,  BMP,                   IMAGE2)      += bmp
+FATE_SEEK_LAVF-$(call ENCDEC2, DVVIDEO,    PCM_S16LE, AVI)         += dv_fmt
+FATE_SEEK_LAVF-$(call ENCDEC2, MPEG1VIDEO, MP2,       FFM)         += ffm
+FATE_SEEK_LAVF-$(call ENCDEC,  FLV,                   FLV)         += flv_fmt
+FATE_SEEK_LAVF-$(call ENCDEC,  GIF,                   IMAGE2)      += gif
+FATE_SEEK_LAVF-$(call ENCDEC2, MPEG2VIDEO, PCM_S16LE, GXF)         += gxf
+FATE_SEEK_LAVF-$(call ENCDEC,  MJPEG,                 IMAGE2)      += jpg
+FATE_SEEK_LAVF-$(call ENCDEC2, MPEG4,      MP2,       MATROSKA)    += mkv
+FATE_SEEK_LAVF-$(call ENCDEC,  ADPCM_YAMAHA,          MMF)         += mmf
+FATE_SEEK_LAVF-$(call ENCDEC2, MPEG4,      PCM_ALAW,  MOV)         += mov
+FATE_SEEK_LAVF-$(call ENCDEC2, MPEG1VIDEO, MP2,       MPEG1SYSTEM MPEGPS) += mpg
+FATE_SEEK_LAVF-$(call ENCDEC,  PCM_MULAW,             PCM_MULAW)   += mulaw
+FATE_SEEK_LAVF-$(call ENCDEC2, MPEG2VIDEO, PCM_S16LE, MXF)         += mxf
+FATE_SEEK_LAVF-$(call ENCDEC2, MPEG2VIDEO, PCM_S16LE, MXF_D10 MXF) += mxf_d10
+FATE_SEEK_LAVF-$(call ENCDEC2, MPEG4,      MP2,       NUT)         += nut
+FATE_SEEK_LAVF-$(call ENCDEC,  FLAC,                  OGG)         += ogg
+FATE_SEEK_LAVF-$(call ENCDEC,  PBM,                   IMAGE2PIPE)  += pbmpipe
+FATE_SEEK_LAVF-$(call ENCDEC,  PCX,                   IMAGE2)      += pcx
+FATE_SEEK_LAVF-$(call ENCDEC,  PGM,                   IMAGE2)      += pgm
+FATE_SEEK_LAVF-$(call ENCDEC,  PGM,                   IMAGE2PIPE)  += pgmpipe
+FATE_SEEK_LAVF-$(call ENCDEC,  PPM,                   IMAGE2)      += ppm
+FATE_SEEK_LAVF-$(call ENCDEC,  PPM,                   IMAGE2PIPE)  += ppmpipe
+FATE_SEEK_LAVF-$(call ENCMUX,  RV10 AC3_FIXED,        RM)          += rm
+FATE_SEEK_LAVF-$(call ENCDEC,  SGI,                   IMAGE2)      += sgi
+FATE_SEEK_LAVF-$(call ENCDEC,  FLV,                   SWF)         += swf
+FATE_SEEK_LAVF-$(call ENCDEC,  TARGA,                 IMAGE2)      += tga
+FATE_SEEK_LAVF-$(call ENCDEC,  TIFF,                  IMAGE2)      += tiff
+FATE_SEEK_LAVF-$(call ENCDEC2, MPEG2VIDEO, MP2,       MPEGTS)      += ts
+FATE_SEEK_LAVF-$(call ENCDEC,  PCM_U8,                VOC)         += voc
+FATE_SEEK_LAVF-$(call ENCDEC,  PCM_S16LE,             WAV)         += wav
+FATE_SEEK_LAVF-$(call ENCDEC,  MP2,                   WTV)         += wtv
+FATE_SEEK_LAVF-$(CONFIG_YUV4MPEGPIPE_MUXER)                        += yuv4mpeg
+
+fate-seek-lavf-aiff:     SRC = lavf/lavf.aif
+fate-seek-lavf-alaw:     SRC = lavf/lavf.al
+fate-seek-lavf-asf:      SRC = lavf/lavf.asf
+fate-seek-lavf-au:       SRC = lavf/lavf.au
+fate-seek-lavf-avi:      SRC = lavf/lavf.avi
+fate-seek-lavf-bmp:      SRC = images/bmp/%02d.bmp
+fate-seek-lavf-dv_fmt:   SRC = lavf/lavf.dv
+fate-seek-lavf-ffm:      SRC = lavf/lavf.ffm
+fate-seek-lavf-flv_fmt:  SRC = lavf/lavf.flv
+fate-seek-lavf-gif:      SRC = lavf/lavf.gif
+fate-seek-lavf-gxf:      SRC = lavf/lavf.gxf
+fate-seek-lavf-jpg:      SRC = images/jpg/%02d.jpg
+fate-seek-lavf-mkv:      SRC = lavf/lavf.mkv
+fate-seek-lavf-mmf:      SRC = lavf/lavf.mmf
+fate-seek-lavf-mov:      SRC = lavf/lavf.mov
+fate-seek-lavf-mpg:      SRC = lavf/lavf.mpg
+fate-seek-lavf-mulaw:    SRC = lavf/lavf.ul
+fate-seek-lavf-mxf:      SRC = lavf/lavf.mxf
+fate-seek-lavf-mxf_d10:  SRC = lavf/lavf.mxf_d10
+fate-seek-lavf-nut:      SRC = lavf/lavf.nut
+fate-seek-lavf-ogg:      SRC = lavf/lavf.ogg
+fate-seek-lavf-pbmpipe:  SRC = lavf/pbmpipe.pbm
+fate-seek-lavf-pcx:      SRC = images/pcx/%02d.pcx
+fate-seek-lavf-pgm:      SRC = images/pgm/%02d.pgm
+fate-seek-lavf-pgmpipe:  SRC = lavf/pgmpipe.pgm
+fate-seek-lavf-ppm:      SRC = images/ppm/%02d.ppm
+fate-seek-lavf-ppmpipe:  SRC = lavf/ppmpipe.ppm
+fate-seek-lavf-rm:       SRC = lavf/lavf.rm
+fate-seek-lavf-sgi:      SRC = images/sgi/%02d.sgi
+fate-seek-lavf-swf:      SRC = lavf/lavf.swf
+fate-seek-lavf-tga:      SRC = images/tga/%02d.tga
+fate-seek-lavf-tiff:     SRC = images/tiff/%02d.tiff
+fate-seek-lavf-ts:       SRC = lavf/lavf.ts
+fate-seek-lavf-voc:      SRC = lavf/lavf.voc
+fate-seek-lavf-wav:      SRC = lavf/lavf.wav
+fate-seek-lavf-wtv:      SRC = lavf/lavf.wtv
+fate-seek-lavf-yuv4mpeg: SRC = lavf/lavf.y4m
+
+FATE_SEEK += $(FATE_SEEK_LAVF-yes:%=fate-seek-lavf-%)
+
+$(FATE_SEEK): libavformat/seek-test$(EXESUF)
+$(FATE_SEEK): CMD = run libavformat/seek-test$(EXESUF) $(TARGET_PATH)/tests/data/$(SRC)
+$(FATE_SEEK): fate-seek-%: fate-%
+fate-seek-%: REF = $(SRC_PATH)/tests/ref/seek/$(@:fate-seek-%=%)
+
+FATE_AVCONV += $(FATE_SEEK)
+fate-seek:     $(FATE_SEEK)
diff --git a/tests/fate/subtitles.mak b/tests/fate/subtitles.mak
index d73352c..d939da9 100644
--- a/tests/fate/subtitles.mak
+++ b/tests/fate/subtitles.mak
@@ -16,7 +16,7 @@
 FATE_SUBTITLES += fate-sub-sami
 fate-sub-sami: CMD = md5 -i $(SAMPLES)/sub/SAMI_capability_tester.smi -f ass
 
-FATE_SUBTITLES += fate-sub-srt
+FATE_SUBTITLES-$(call DEMDEC, SRT, SRT) += fate-sub-srt
 fate-sub-srt: CMD = md5 -i $(SAMPLES)/sub/SubRip_capability_tester.srt -f ass
 
 FATE_SUBTITLES += fate-sub-subripenc
@@ -28,5 +28,7 @@
 FATE_SUBTITLES += fate-sub-webvtt
 fate-sub-webvtt: CMD = md5 -i $(SAMPLES)/sub/WebVTT_capability_tester.vtt -f ass
 
+FATE_SUBTITLES += $(FATE_SUBTITLES-yes)
+
 FATE_SAMPLES_FFMPEG += $(FATE_SUBTITLES)
 fate-subtitles: $(FATE_SUBTITLES)
diff --git a/tests/fate/utvideo.mak b/tests/fate/utvideo.mak
index 184a3be..44e0314 100644
--- a/tests/fate/utvideo.mak
+++ b/tests/fate/utvideo.mak
@@ -25,7 +25,7 @@
 FATE_UTVIDEO += fate-utvideo_yuv422_median
 fate-utvideo_yuv422_median: CMD = framecrc -i $(SAMPLES)/utvideo/utvideo_yuv422_median.avi
 
-FATE_SAMPLES_AVCONV += $(FATE_UTVIDEO)
+FATE_SAMPLES_AVCONV-$(call DEMDEC, AVI, UTVIDEO) += $(FATE_UTVIDEO)
 fate-utvideo: $(FATE_UTVIDEO)
 
 fate-utvideoenc%: CMD = framemd5 -f image2 -vcodec pgmyuv -i $(TARGET_PATH)/tests/vsynth1/%02d.pgm -vcodec utvideo -sws_flags +accurate_rnd+bitexact ${OPTS}
@@ -68,5 +68,5 @@
 
 $(FATE_UTVIDEOENC): tests/vsynth1/00.pgm
 
-FATE_AVCONV += $(FATE_UTVIDEOENC)
+FATE_AVCONV-$(call ENCMUX, UTVIDEO, AVI) += $(FATE_UTVIDEOENC)
 fate-utvideoenc: $(FATE_UTVIDEOENC)
diff --git a/tests/fate/vcodec.mak b/tests/fate/vcodec.mak
index f4e39b8..6995c4a 100644
--- a/tests/fate/vcodec.mak
+++ b/tests/fate/vcodec.mak
@@ -4,108 +4,108 @@
 fate-vsynth%: FMT = avi
 fate-vsynth%: CMD = enc_dec "rawvideo -s 352x288 -pix_fmt yuv420p $(RAWDECOPTS)" $(SRC) $(FMT) "-c $(CODEC) $(ENCOPTS)" rawvideo "-s 352x288 -pix_fmt yuv420p -vsync 0 $(DECOPTS)" -keep "$(DECINOPTS)"
 fate-vsynth%: CMP_UNIT = 1
+fate-vsynth%: REF = $(SRC_PATH)/tests/ref/vsynth/$(@:fate-%=%)
 
-FATE_VCODEC += amv
+FATE_VCODEC-$(call ENCDEC, AMV, AVI) += amv
 
-FATE_VCODEC += asv1
+FATE_VCODEC-$(call ENCDEC, ASV1, AVI)   += asv1
 fate-vsynth%-asv1:               ENCOPTS = -qscale 10
 
-FATE_VCODEC += asv2
+FATE_VCODEC-$(call ENCDEC, ASV2, AVI)   += asv2
 fate-vsynth%-asv2:               ENCOPTS = -qscale 10
 
-FATE_VCODEC += cljr
+FATE_VCODEC-$(call ENCDEC, CLJR, AVI)   += cljr
 
-FATE_VCODEC += dnxhd-720p
+FATE_VCODEC-$(call ENCDEC, DNXHD, DNXHD) += dnxhd-720p                  \
+                                            dnxhd-720p-rd               \
+                                            dnxhd-720p-10bit
+
 fate-vsynth%-dnxhd-720p:         ENCOPTS = -s hd720 -b 90M              \
                                            -pix_fmt yuv422p -frames 5 -qmax 8
 fate-vsynth%-dnxhd-720p:         FMT     = dnxhd
 
-FATE_VCODEC += dnxhd-720p-rd
 fate-vsynth%-dnxhd-720p-rd:      ENCOPTS = -s hd720 -b 90M -threads 4 -mbd rd \
                                            -pix_fmt yuv422p -frames 5 -qmax 8
 fate-vsynth%-dnxhd-720p-rd:      FMT     = dnxhd
 
-FATE_VCODEC += dnxhd-720p-10bit
 fate-vsynth%-dnxhd-720p-10bit:   ENCOPTS = -s hd720 -b 90M              \
                                            -pix_fmt yuv422p10 -frames 5 -qmax 8
 fate-vsynth%-dnxhd-720p-10bit:   FMT     = dnxhd
 
-FATE_VCODEC += dnxhd-1080i
+FATE_VCODEC-$(call ENCDEC, DNXHD, MOV)  += dnxhd-1080i
 fate-vsynth%-dnxhd-1080i:        ENCOPTS = -s hd1080 -b 120M -flags +ildct \
                                            -pix_fmt yuv422p -frames 5 -qmax 8
 fate-vsynth%-dnxhd-1080i:        FMT     = mov
 
-FATE_VCODEC += dv
+FATE_VCODEC-$(call ENCDEC, DVVIDEO, DV) += dv dv-411 dv-50
 fate-vsynth%-dv:                 CODEC   = dvvideo
 fate-vsynth%-dv:                 ENCOPTS = -dct int -s pal
 fate-vsynth%-dv:                 FMT     = dv
 
-FATE_VCODEC += dv-411
 fate-vsynth%-dv-411:             CODEC   = dvvideo
 fate-vsynth%-dv-411:             ENCOPTS = -dct int -s pal -pix_fmt yuv411p \
                                            -sws_flags area
 fate-vsynth%-dv-411:             DECOPTS = -sws_flags area
 fate-vsynth%-dv-411:             FMT     = dv
 
-FATE_VCODEC += dv-50
 fate-vsynth%-dv-50:              CODEC   = dvvideo
 fate-vsynth%-dv-50:              ENCOPTS = -dct int -s pal -pix_fmt yuv422p \
                                            -sws_flags neighbor
 fate-vsynth%-dv-50:              DECOPTS = -sws_flags neighbor
 fate-vsynth%-dv-50:              FMT     = dv
 
-FATE_VCODEC += ffv1
+FATE_VCODEC-$(call ENCDEC, FFV1, AVI)   += ffv1
 fate-vsynth%-ffv1:               ENCOPTS = -strict -2
 
-FATE_VCODEC += ffvhuff
+FATE_VCODEC-$(call ENCDEC, FFVHUFF, AVI) += ffvhuff
 
-FATE_VCODEC-$(CONFIG_ZLIB) += flashsv
+FATE_VCODEC-$(call ENCDEC, FLASHSV, FLV) += flashsv
 fate-vsynth%-flashsv:            ENCOPTS = -sws_flags neighbor+full_chroma_int
 fate-vsynth%-flashsv:            DECOPTS = -sws_flags area
 fate-vsynth%-flashsv:            FMT     = flv
 
-FATE_VCODEC-$(CONFIG_ZLIB) += flashsv2
+FATE_VCODEC-$(call ENCDEC, FLASHSV2, FLV) += flashsv2
 fate-vsynth%-flashsv2:           ENCOPTS = -sws_flags neighbor+full_chroma_int -strict experimental -compression_level 0
 fate-vsynth%-flashsv2:           DECOPTS = -sws_flags area
 fate-vsynth%-flashsv2:           FMT     = flv
 
-FATE_VCODEC += flv
+FATE_VCODEC-$(call ENCDEC, FLV, FLV)    += flv
 fate-vsynth%-flv:                ENCOPTS = -qscale 10
 fate-vsynth%-flv:                FMT     = flv
 
-FATE_VCODEC += h261
+FATE_VCODEC-$(call ENCDEC, H261, AVI)   += h261
 fate-vsynth%-h261:               ENCOPTS = -qscale 11
 
-FATE_VCODEC += h263
+FATE_VCODEC-$(call ENCDEC, H263, AVI)   += h263 h263-obmc h263p
 fate-vsynth%-h263:               ENCOPTS = -qscale 10
-
-FATE_VCODEC += h263p
+fate-vsynth%-h263-obmc:          ENCOPTS = -qscale 10 -obmc 1
 fate-vsynth%-h263p:              ENCOPTS = -qscale 2 -flags +aic -umv 1 -aiv 1 -ps 300
 
-FATE_VCODEC += huffyuv
+FATE_VCODEC-$(call ENCDEC, HUFFYUV, AVI) += huffyuv
 fate-vsynth%-huffyuv:            ENCOPTS = -pix_fmt yuv422p -sws_flags neighbor
 fate-vsynth%-huffyuv:            DECOPTS = -strict -2 -sws_flags neighbor
 
-FATE_VCODEC += jpegls
+FATE_VCODEC-$(call ENCDEC, JPEGLS, AVI) += jpegls
 fate-vsynth%-jpegls:             ENCOPTS = -sws_flags neighbor+full_chroma_int
 fate-vsynth%-jpegls:             DECOPTS = -sws_flags area
 
-FATE_VCODEC += j2k
+FATE_VCODEC-$(call ENCDEC, JPEG2000, AVI) += j2k
 fate-vsynth%-j2k:                ENCOPTS = -qscale 7 -strict experimental -pix_fmt rgb24
 fate-vsynth%-j2k:                DECINOPTS = -vcodec j2k -strict experimental
 
-FATE_VCODEC += ljpeg
+FATE_VCODEC-$(call ENCDEC, LJPEG MJPEG, AVI) += ljpeg
 fate-vsynth%-ljpeg:              ENCOPTS = -strict -1
 
-FATE_VCODEC += mjpeg
+FATE_VCODEC-$(call ENCDEC, MJPEG, AVI)  += mjpeg mjpeg-422 mjpeg-444
 fate-vsynth%-mjpeg:              ENCOPTS = -qscale 9 -pix_fmt yuvj420p
+fate-vsynth%-mjpeg-422:          ENCOPTS = -qscale 9 -pix_fmt yuvj422p
+fate-vsynth%-mjpeg-444:          ENCOPTS = -qscale 9 -pix_fmt yuvj444p
 
-FATE_VCODEC += mpeg1
+FATE_VCODEC-$(call ENCDEC, MPEG1VIDEO, MPEG1VIDEO MPEGVIDEO) += mpeg1 mpeg1b
 fate-vsynth%-mpeg1:              FMT     = mpeg1video
 fate-vsynth%-mpeg1:              CODEC   = mpeg1video
 fate-vsynth%-mpeg1:              ENCOPTS = -qscale 10
 
-FATE_VCODEC += mpeg1b
 fate-vsynth%-mpeg1b:             CODEC   = mpeg1video
 fate-vsynth%-mpeg1b:             ENCOPTS = -qscale 8 -bf 3 -ps 200
 fate-vsynth%-mpeg1b:             FMT     = mpeg1video
@@ -118,7 +118,7 @@
              mpeg2-thread                                               \
              mpeg2-thread-ivlc
 
-FATE_VCODEC += $(FATE_MPEG2)
+FATE_VCODEC-$(call ENCDEC, MPEG2VIDEO, MPEG2VIDEO MPEGVIDEO) += $(FATE_MPEG2)
 
 $(FATE_MPEG2:%=fate-vsynth\%-%): FMT    = mpeg2video
 $(FATE_MPEG2:%=fate-vsynth\%-%): CODEC  = mpeg2video
@@ -147,140 +147,139 @@
 fate-vsynth%-mpeg2-thread-ivlc:  ENCOPTS = -qscale 10 -bf 2 -flags +ildct+ilme \
                                            -intra_vlc 1 -threads 2 -slices 2
 
-FATE_VCODEC += mpeg4
+FATE_MPEG4_MP4 = mpeg4
+FATE_MPEG4_AVI = mpeg4-rc                                               \
+                 mpeg4-adv                                              \
+                 mpeg4-qprd                                             \
+                 mpeg4-adap                                             \
+                 mpeg4-qpel                                             \
+                 mpeg4-thread                                           \
+                 mpeg4-error                                            \
+                 mpeg4-nr
+
+FATE_VCODEC-$(call ENCDEC, MPEG4, MP4 MOV) += $(FATE_MPEG4_MP4)
+FATE_VCODEC-$(call ENCDEC, MPEG4, AVI)     += $(FATE_MPEG4_AVI)
+
 fate-vsynth%-mpeg4:              ENCOPTS = -qscale 10 -flags +mv4 -mbd bits
 fate-vsynth%-mpeg4:              FMT     = mp4
 
-FATE_VCODEC += mpeg4-rc
 fate-vsynth%-mpeg4-rc:           ENCOPTS = -b 400k -bf 2
 
-FATE_VCODEC += mpeg4-adv
 fate-vsynth%-mpeg4-adv:          ENCOPTS = -qscale 9 -flags +mv4+aic       \
                                            -data_partitioning 1 -trellis 1 \
                                            -mbd bits -ps 200
 
-FATE_VCODEC += mpeg4-qprd
 fate-vsynth%-mpeg4-qprd:         ENCOPTS = -b 450k -bf 2 -trellis 1          \
                                            -flags +mv4+mv0 -mpv_flags +qp_rd \
                                            -cmp 2 -subcmp 2 -mbd rd
 
-FATE_VCODEC += mpeg4-adap
 fate-vsynth%-mpeg4-adap:         ENCOPTS = -b 550k -bf 2 -flags +mv4+mv0 \
                                            -trellis 1 -cmp 1 -subcmp 2   \
                                            -mbd rd -scplx_mask 0.3
 
-FATE_VCODEC += mpeg4-qpel
 fate-vsynth%-mpeg4-qpel:         ENCOPTS = -qscale 7 -flags +mv4+qpel -mbd 2 \
                                            -bf 2 -cmp 1 -subcmp 2
 
-FATE_VCODEC += mpeg4-thread
 fate-vsynth%-mpeg4-thread:       ENCOPTS = -b 500k -flags +mv4+aic         \
                                            -data_partitioning 1 -trellis 1 \
                                            -mbd bits -ps 200 -bf 2         \
                                            -threads 2 -slices 2
 
-FATE_VCODEC += mpeg4-error
 fate-vsynth%-mpeg4-error:        ENCOPTS = -qscale 7 -flags +mv4+aic    \
                                            -data_partitioning 1 -mbd rd \
                                            -ps 250 -error 10
 
-FATE_VCODEC += mpeg4-nr
 fate-vsynth%-mpeg4-nr:           ENCOPTS = -qscale 8 -flags +mv4 -mbd rd -nr 200
 
-FATE_VCODEC += msmpeg4
+FATE_VCODEC-$(call ENCDEC, MSMPEG4V3, AVI) += msmpeg4
 fate-vsynth%-msmpeg4:            ENCOPTS = -qscale 10
 
-FATE_VCODEC += msmpeg4v2
+FATE_VCODEC-$(call ENCDEC, MSMPEG4V2, AVI) += msmpeg4v2
 fate-vsynth%-msmpeg4v2:          ENCOPTS = -qscale 10
 
-FATE_VCODEC-$(CONFIG_ZLIB) += mpng
+FATE_VCODEC-$(call ENCDEC, PNG, AVI)    += mpng
 fate-vsynth%-mpng:               CODEC   = png
 
-FATE_VCODEC += msvideo1
+FATE_VCODEC-$(call ENCDEC, MSVIDEO1, AVI) += msvideo1
 
-FATE_VCODEC += prores
+FATE_VCODEC-$(call ENCDEC, PRORES, MOV) += prores prores_kostya
 fate-vsynth%-prores:             FMT     = mov
 
-FATE_VCODEC += prores_kostya
-fate-vsynth%-prores_kostya:             ENCOPTS = -profile hq
-fate-vsynth%-prores_kostya:             FMT     = mov
+fate-vsynth%-prores_kostya:      ENCOPTS = -profile hq
+fate-vsynth%-prores_kostya:      FMT     = mov
 
-FATE_VCODEC += qtrle
+FATE_VCODEC-$(call ENCDEC, QTRLE, MOV)  += qtrle qtrlegray
 fate-vsynth%-qtrle:              FMT     = mov
 
-FATE_VCODEC += qtrlegray
 fate-vsynth%-qtrlegray:          CODEC   = qtrle
 fate-vsynth%-qtrlegray:          ENCOPTS = -pix_fmt gray
 fate-vsynth%-qtrlegray:          FMT     = mov
 
-FATE_VCODEC += rgb
+FATE_VCODEC-$(call ENCDEC, RAWVIDEO, AVI) += rgb
 fate-vsynth%-rgb:                CODEC   = rawvideo
 fate-vsynth%-rgb:                ENCOPTS = -pix_fmt bgr24
 
-FATE_VCODEC += roqvideo
+FATE_VCODEC-$(call ENCDEC, ROQ, ROQ)    += roqvideo
 fate-vsynth%-roqvideo:           CODEC   = roqvideo
 fate-vsynth%-roqvideo:           ENCOPTS = -frames 5
 fate-vsynth%-roqvideo:           RAWDECOPTS = -r 30
 fate-vsynth%-roqvideo:           FMT     = roq
 
-FATE_VCODEC += rv10
+FATE_VCODEC-$(call ENCDEC, RV10, RM)    += rv10
 fate-vsynth%-rv10:               ENCOPTS = -qscale 10
 fate-vsynth%-rv10:               FMT     = rm
 
-FATE_VCODEC += rv20
+FATE_VCODEC-$(call ENCDEC, RV20, RM)    += rv20
 fate-vsynth%-rv20:               ENCOPTS = -qscale 10
 fate-vsynth%-rv20:               FMT     = rm
 
-FATE_VCODEC += snow
+FATE_VCODEC-$(call ENCDEC, SNOW, AVI)   += snow snow-hpel snow-ll
 fate-vsynth%-snow:               ENCOPTS = -strict -2 -qscale 2 -flags +qpel \
                                            -me_method iter -dia_size 2       \
                                            -cmp 12 -subcmp 12 -s 128x64
 
-FATE_VCODEC += snow-hpel
 fate-vsynth%-snow-hpel:          ENCOPTS = -strict -2 -qscale 2              \
                                            -me_method iter -dia_size 2       \
                                            -cmp 12 -subcmp 12 -s 128x64
 
-FATE_VCODEC += snow-ll
 fate-vsynth%-snow-ll:            ENCOPTS = -strict -2 -qscale .001 -pred 1 \
                                            -flags +mv4+qpel
 
-FATE_VCODEC += svq1
+FATE_VCODEC-$(call ENCDEC, SVQ1, MOV)   += svq1
 fate-vsynth%-svq1:               ENCOPTS = -qscale 3 -pix_fmt yuv410p
 fate-vsynth%-svq1:               FMT     = mov
 
-FATE_VCODEC += r210
+FATE_VCODEC-$(call ENCDEC, R210, AVI)   += r210
 
-FATE_VCODEC += v210
+FATE_VCODEC-$(call ENCDEC, V210, AVI)   += v210
 
-FATE_VCODEC += v308
+FATE_VCODEC-$(call ENCDEC, V308, AVI)   += v308
 
-FATE_VCODEC += v408
+FATE_VCODEC-$(call ENCDEC, V408, AVI)   += v408
 fate-vsynth%-v408:               ENCOPTS = -sws_flags neighbor+bitexact
 fate-vsynth%-v408:               DECOPTS = -sws_flags neighbor+bitexact
 
-FATE_VCODEC += avui
+FATE_VCODEC-$(call ENCDEC, AVUI, MOV)   += avui
 fate-vsynth%-avui:               ENCOPTS = -s pal -strict experimental -sws_flags neighbor+bitexact
 fate-vsynth%-avui:               DECOPTS = -sws_flags neighbor+bitexact
 fate-vsynth%-avui:               FMT     = mov
 
-FATE_VCODEC += wmv1
+FATE_VCODEC-$(call ENCDEC, WMV1, AVI)   += wmv1
 fate-vsynth%-wmv1:               ENCOPTS = -qscale 10
 
-FATE_VCODEC += wmv2
+FATE_VCODEC-$(call ENCDEC, WMV2, AVI)   += wmv2
 fate-vsynth%-wmv2:               ENCOPTS = -qscale 10
 
-FATE_VCODEC += yuv
+FATE_VCODEC-$(call ENCDEC, RAWVIDEO, AVI) += yuv
 fate-vsynth%-yuv:                CODEC = rawvideo
 
-FATE_VCODEC += yuv4
+FATE_VCODEC-$(call ENCDEC, YUV4, AVI) += yuv4
 
-FATE_VCODEC += y41p
+FATE_VCODEC-$(call ENCDEC, Y41P, AVI) += y41p
 
-FATE_VCODEC-$(CONFIG_ZLIB) += zlib
+FATE_VCODEC-$(call ENCDEC, ZLIB, AVI) += zlib
 
 FATE_VCODEC += $(FATE_VCODEC-yes)
-
 FATE_VSYNTH1 = $(FATE_VCODEC:%=fate-vsynth1-%)
 FATE_VSYNTH2 = $(FATE_VCODEC:%=fate-vsynth2-%)
 
diff --git a/tests/fate/video.mak b/tests/fate/video.mak
index 65b98a4..5689f51 100644
--- a/tests/fate/video.mak
+++ b/tests/fate/video.mak
@@ -4,79 +4,87 @@
 FATE_4XM += fate-4xm-2
 fate-4xm-2: CMD = framecrc -i $(SAMPLES)/4xm/version2.4xm -pix_fmt rgb24 -an
 
-FATE_VIDEO += $(FATE_4XM)
+FATE_VIDEO-$(call DEMDEC, FOURXM, FOURXM) += $(FATE_4XM)
 fate-4xm: $(FATE_4XM)
 
-FATE_VIDEO += fate-aasc
+FATE_VIDEO-$(call DEMDEC, AVI, AASC) += fate-aasc
 fate-aasc: CMD = framecrc -i $(SAMPLES)/aasc/AASC-1.5MB.AVI -pix_fmt rgb24
 
-FATE_VIDEO += fate-alg-mm
+FATE_VIDEO-$(call DEMDEC, MM, MMVIDEO) += fate-alg-mm
 fate-alg-mm: CMD = framecrc -i $(SAMPLES)/alg-mm/ibmlogo.mm -an -pix_fmt rgb24
 
-FATE_VIDEO += fate-amv
+FATE_VIDEO-$(call DEMDEC, AVI, AMV) += fate-amv
 fate-amv: CMD = framecrc -idct simple -i $(SAMPLES)/amv/MTV_high_res_320x240_sample_Penguin_Joke_MTV_from_WMV.amv -t 10 -an
 
-FATE_VIDEO += fate-ansi
+FATE_VIDEO-$(call DEMDEC, TTY, ANSI) += fate-ansi
 fate-ansi: CMD = framecrc -chars_per_frame 44100 -i $(SAMPLES)/ansi/TRE-IOM5.ANS -pix_fmt rgb24
 
-FATE_VIDEO += fate-ansi256
+FATE_VIDEO-$(call DEMDEC, TTY, ANSI) += fate-ansi256
 fate-ansi256: CMD = framecrc -chars_per_frame 44100 -i $(SAMPLES)/ansi/ansi256.ans -pix_fmt rgb24
 
-FATE_VIDEO += fate-armovie-escape124
+FATE_VIDEO-$(call DEMDEC, RPL, ESCAPE124) += fate-armovie-escape124
 fate-armovie-escape124: CMD = framecrc -i $(SAMPLES)/rpl/ESCAPE.RPL -pix_fmt rgb24
 
-FATE_VIDEO += fate-auravision-v1
+FATE_VIDEO-$(call DEMDEC, AVI, AURA) += fate-auravision-v1
 fate-auravision-v1: CMD = framecrc -i $(SAMPLES)/auravision/SOUVIDEO.AVI -an
 
-FATE_VIDEO += fate-auravision-v2
+FATE_VIDEO-$(call DEMDEC, AVI, AURA2) += fate-auravision-v2
 fate-auravision-v2: CMD = framecrc -i $(SAMPLES)/auravision/salma-hayek-in-ugly-betty-partial-avi -an
 
-FATE_VIDEO += fate-bethsoft-vid
+FATE_VIDEO-$(call DEMDEC, BETHSOFTVID, BETHSOFTVID) += fate-bethsoft-vid
 fate-bethsoft-vid: CMD = framecrc -i $(SAMPLES)/bethsoft-vid/ANIM0001.VID -t 5 -pix_fmt rgb24
 
-FATE_VIDEO += fate-bfi
+FATE_VIDEO-$(call DEMDEC, BFI, BFI) += fate-bfi
 fate-bfi: CMD = framecrc -i $(SAMPLES)/bfi/2287.bfi -pix_fmt rgb24
 
-FATE_VIDEO += fate-bink-video
-fate-bink-video: CMD = framecrc -i $(SAMPLES)/bink/hol2br.bik
+FATE_BINK_VIDEO += fate-bink-video-b
+fate-bink-video-b: CMD = framecrc -i $(SAMPLES)/bink/RISE.BIK -frames 30
 
-FATE_VIDEO += fate-bmv-video
+FATE_BINK_VIDEO += fate-bink-video-f
+fate-bink-video-f: CMD = framecrc -i $(SAMPLES)/bink/hol2br.bik
+
+FATE_BINK_VIDEO += fate-bink-video-i
+fate-bink-video-i: CMD = framecrc -i $(SAMPLES)/bink/RazOnBull.bik -an
+
+FATE_VIDEO-$(call DEMDEC, BINK, BINK) += $(FATE_BINK_VIDEO)
+
+FATE_VIDEO-$(call DEMDEC, BMV, BMV_VIDEO) += fate-bmv-video
 fate-bmv-video: CMD = framecrc -i $(SAMPLES)/bmv/SURFING-partial.BMV -pix_fmt rgb24 -an
 
-FATE_VIDEO += fate-cdgraphics
+FATE_VIDEO-$(call DEMDEC, CDG, CDGRAPHICS) += fate-cdgraphics
 fate-cdgraphics: CMD = framecrc -i $(SAMPLES)/cdgraphics/BrotherJohn.cdg -pix_fmt rgb24 -t 1
 
-FATE_VIDEO += fate-cljr
+FATE_VIDEO-$(call DEMDEC, AVI, CLJR) += fate-cljr
 fate-cljr: CMD = framecrc -i $(SAMPLES)/cljr/testcljr-partial.avi
 
-FATE_VIDEO-$(CONFIG_ZLIB) += fate-corepng
+FATE_VIDEO-$(call DEMDEC, AVI, PNG) += fate-corepng
 fate-corepng: CMD = framecrc -i $(SAMPLES)/png1/corepng-partial.avi
 
-FATE_VIDEO += fate-creatureshock-avs
+FATE_VIDEO-$(call DEMDEC, AVS, AVS) += fate-creatureshock-avs
 fate-creatureshock-avs: CMD = framecrc -i $(SAMPLES)/creatureshock-avs/OUTATIME.AVS -pix_fmt rgb24
 
-FATE_CVID += fate-cvid-partial
+FATE_CVID-$(CONFIG_AVI_DEMUXER) += fate-cvid-partial
 fate-cvid-partial: CMD = framecrc -i $(SAMPLES)/cvid/laracroft-cinepak-partial.avi -an
 
-FATE_CVID += fate-cvid-palette
+FATE_CVID-$(CONFIG_MOV_DEMUXER) += fate-cvid-palette
 fate-cvid-palette: CMD = framecrc -i $(SAMPLES)/cvid/catfight-cvid-pal8-partial.mov -pix_fmt rgb24 -an
 
-FATE_CVID += fate-cvid-grayscale
+FATE_CVID-$(CONFIG_AVI_DEMUXER) += fate-cvid-grayscale
 fate-cvid-grayscale: CMD = framecrc -i $(SAMPLES)/cvid/pcitva15.avi -an
 
-FATE_VIDEO += $(FATE_CVID)
-fate-cvid: $(FATE_CVID)
+FATE_VIDEO-$(CONFIG_CINEPAK_DECODER) += $(FATE_CVID-yes)
+fate-cvid: $(FATE_CVID-yes)
 
-FATE_VIDEO += fate-cyberia-c93
+FATE_VIDEO-$(call DEMDEC, C93, C93) += fate-cyberia-c93
 fate-cyberia-c93: CMD = framecrc -i $(SAMPLES)/cyberia-c93/intro1.c93 -t 3 -pix_fmt rgb24
 
-FATE_VIDEO += fate-cyuv
+FATE_VIDEO-$(call DEMDEC, AVI, CYUV) += fate-cyuv
 fate-cyuv: CMD = framecrc -i $(SAMPLES)/cyuv/cyuv.avi
 
-FATE_VIDEO += fate-delphine-cin-video
+FATE_VIDEO-$(call DEMDEC, DSICIN, DSICINVIDEO) += fate-delphine-cin-video
 fate-delphine-cin-video: CMD = framecrc -i $(SAMPLES)/delphine-cin/LOGO-partial.CIN -pix_fmt rgb24 -an
 
-FATE_VIDEO += fate-deluxepaint-anm
+FATE_VIDEO-$(call DEMDEC, ANM, ANM) += fate-deluxepaint-anm
 fate-deluxepaint-anm: CMD = framecrc -i $(SAMPLES)/deluxepaint-anm/INTRO1.ANM -pix_fmt rgb24
 
 FATE_TRUEMOTION1 += fate-truemotion1-15
@@ -85,10 +93,10 @@
 FATE_TRUEMOTION1 += fate-truemotion1-24
 fate-truemotion1-24: CMD = framecrc -i $(SAMPLES)/duck/sonic3dblast_intro-partial.avi -pix_fmt rgb24 -an
 
-FATE_VIDEO += $(FATE_TRUEMOTION1)
+FATE_VIDEO-$(call DEMDEC, AVI, TRUEMOTION1) += $(FATE_TRUEMOTION1)
 fate-truemotion1: $(FATE_TRUEMOTION1)
 
-FATE_VIDEO += fate-truemotion2
+FATE_VIDEO-$(call DEMDEC, AVI, TRUEMOTION2) += fate-truemotion2
 fate-truemotion2: CMD = framecrc -i $(SAMPLES)/duck/tm20.avi
 
 FATE_DXA += fate-dxa-feeble
@@ -97,10 +105,10 @@
 FATE_DXA += fate-dxa-scummvm
 fate-dxa-scummvm: CMD = framecrc -i $(SAMPLES)/dxa/scummvm.dxa -pix_fmt rgb24
 
-FATE_VIDEO-$(CONFIG_ZLIB) += $(FATE_DXA)
+FATE_VIDEO-$(call DEMDEC, DXA, DXA) += $(FATE_DXA)
 fate-dxa: $(FATE_DXA)
 
-FATE_SAMPLES_PCM += fate-film-cvid
+FATE_VIDEO-$(call DEMDEC, SEGAFILM, CINEPAK) += fate-film-cvid
 fate-film-cvid: CMD = framecrc -i $(SAMPLES)/film/logo-capcom.cpk -an
 
 FATE_FLIC += fate-flic-af11-palette-change
@@ -112,63 +120,66 @@
 FATE_FLIC += fate-flic-magiccarpet
 fate-flic-magiccarpet: CMD = framecrc -i $(SAMPLES)/fli/intel.dat -pix_fmt rgb24
 
-FATE_VIDEO += $(FATE_FLIC)
+FATE_VIDEO-$(call DEMDEC, FLIC, FLIC) += $(FATE_FLIC)
 fate-flic: $(FATE_FLIC)
 
-FATE_VIDEO += fate-frwu
+FATE_VIDEO-$(call DEMDEC, AVI, FRWU) += fate-frwu
 fate-frwu: CMD = framecrc -i $(SAMPLES)/frwu/frwu.avi
 
-FATE_VIDEO += fate-id-cin-video
+FATE_VIDEO-$(call DEMDEC, IDCIN, IDCIN) += fate-id-cin-video
 fate-id-cin-video: CMD = framecrc -i $(SAMPLES)/idcin/idlog-2MB.cin -pix_fmt rgb24
 
-FATE_VIDEO-$(CONFIG_AVFILTER) += fate-idroq-video-encode
+FATE_VIDEO-$(call ENCDEC, ROQ PGMYUV, ROQ IMAGE2) += fate-idroq-video-encode
 fate-idroq-video-encode: CMD = md5 -f image2 -vcodec pgmyuv -i $(SAMPLES)/ffmpeg-synthetic/vsynth1/%02d.pgm -sws_flags +bitexact -vf pad=512:512:80:112 -f roq -t 0.2
 
-FATE_IFF += fate-iff-byterun1
+FATE_IFF-$(CONFIG_IFF_BYTERUN1_DECODER) += fate-iff-byterun1
 fate-iff-byterun1: CMD = framecrc -i $(SAMPLES)/iff/ASH.LBM -pix_fmt rgb24
 
-FATE_IFF += fate-iff-fibonacci
+FATE_IFF-$(CONFIG_EIGHTSVX_FIB_DECODER) += fate-iff-fibonacci
 fate-iff-fibonacci: CMD = md5 -i $(SAMPLES)/iff/dasboot-in-compressed -f s16le
 
-FATE_IFF += fate-iff-ilbm
+FATE_IFF-$(CONFIG_IFF_ILBM_DECODER) += fate-iff-ilbm
 fate-iff-ilbm: CMD = framecrc -i $(SAMPLES)/iff/lms-matriks.ilbm -pix_fmt rgb24
 
-FATE_VIDEO += $(FATE_IFF)
-fate-iff: $(FATE_IFF)
+FATE_VIDEO-$(CONFIG_IFF_DEMUXER)  += $(FATE_IFF-yes)
+fate-iff: $(FATE_IFF-yes)
 
-FATE_VIDEO += fate-interplay-mve-8bit
+FATE_VIDEO-$(call DEMDEC, IPMOVIE, INTERPLAY_VIDEO) += fate-interplay-mve-8bit
 fate-interplay-mve-8bit: CMD = framecrc -i $(SAMPLES)/interplay-mve/interplay-logo-2MB.mve -pix_fmt rgb24 -an
 
-FATE_VIDEO += fate-interplay-mve-16bit
+FATE_VIDEO-$(call DEMDEC, IPMOVIE, INTERPLAY_VIDEO) += fate-interplay-mve-16bit
 fate-interplay-mve-16bit: CMD = framecrc -i $(SAMPLES)/interplay-mve/descent3-level5-16bit-partial.mve -pix_fmt rgb24 -an
 
-FATE_VIDEO += fate-jv
+FATE_VIDEO-$(call DEMDEC, JV, JV) += fate-jv
 fate-jv: CMD = framecrc -i $(SAMPLES)/jv/intro.jv -pix_fmt rgb24 -an
 
-FATE_VIDEO += fate-kgv1
+FATE_VIDEO-$(call DEMDEC, AVI, KGV1) += fate-kgv1
 fate-kgv1: CMD = framecrc -i $(SAMPLES)/kega/kgv1.avi -pix_fmt rgb555le -an
 
-FATE_VIDEO += fate-kmvc
+FATE_VIDEO-$(call DEMDEC, AVI, KMVC) += fate-kmvc
 fate-kmvc: CMD = framecrc -i $(SAMPLES)/KMVC/LOGO1.AVI -an -t 3 -pix_fmt rgb24
 
-FATE_VIDEO += fate-mdec
+FATE_VIDEO-$(call DEMDEC, EA, MDEC) += fate-mdec
 fate-mdec: CMD = framecrc -idct simple -i $(SAMPLES)/ea-dct/NFS2Esprit-partial.dct -an
 
-FATE_VIDEO += fate-mdec-v3
+FATE_VIDEO-$(call DEMDEC, STR, MDEC) += fate-mdec-v3
 fate-mdec-v3: CMD = framecrc -idct simple -i $(SAMPLES)/psx-str/abc000_cut.str -an
 
-FATE_VIDEO += fate-mimic
+FATE_VIDEO-$(call DEMDEC, MSNWC_TCP, MIMIC) += fate-mimic
 fate-mimic: CMD = framecrc -idct simple -i $(SAMPLES)/mimic/mimic2-womanloveffmpeg.cam
 
-FATE_VIDEO += fate-mjpegb
+FATE_VIDEO-$(call DEMDEC, MOV, MJPEGB) += fate-mjpegb
 fate-mjpegb: CMD = framecrc -idct simple -flags +bitexact -i $(SAMPLES)/mjpegb/mjpegb_part.mov -an
 
-FATE_VIDEO += fate-motionpixels
+FATE_VIDEO-$(call DEMDEC, MVI, MOTIONPIXELS) += fate-motionpixels
 fate-motionpixels: CMD = framecrc -i $(SAMPLES)/motion-pixels/INTRO-partial.MVI -an -pix_fmt rgb24 -vframes 111
 
-FATE_VIDEO += fate-mpeg2-field-enc
+FATE_VIDEO-$(call DEMDEC, MPEGTS, MPEG2VIDEO) += 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_VIDEO-$(call DEMDEC, MXG, MXPEG) += fate-mxpeg
+fate-mxpeg: CMD = framecrc -idct simple -flags +bitexact -i $(SAMPLES)/mxpeg/m1.mxg -an
+
 # FIXME dropped frames in this test because of coarse timebase
 FATE_NUV += fate-nuv-rtjpeg
 fate-nuv-rtjpeg: CMD = framecrc -idct simple -i $(SAMPLES)/nuv/Today.nuv -an
@@ -176,46 +187,46 @@
 FATE_NUV += fate-nuv-rtjpeg-fh
 fate-nuv-rtjpeg-fh: CMD = framecrc -idct simple -i $(SAMPLES)/nuv/rtjpeg_frameheader.nuv -an
 
-FATE_VIDEO += $(FATE_NUV)
+FATE_VIDEO-$(call DEMDEC, NUV, NUV) += $(FATE_NUV)
 fate-nuv: $(FATE_NUV)
 
-FATE_VIDEO += fate-paf-video
+FATE_VIDEO-$(call DEMDEC, PAF, PAF_VIDEO) += fate-paf-video
 fate-paf-video: CMD = framecrc -i $(SAMPLES)/paf/hod1-partial.paf -pix_fmt rgb24 -an
 
-FATE_VIDEO += fate-qpeg
+FATE_VIDEO-$(call DEMDEC, AVI, QPEG) += fate-qpeg
 fate-qpeg: CMD = framecrc -i $(SAMPLES)/qpeg/Clock.avi -an -pix_fmt rgb24
 
-FATE_VIDEO += fate-r210
+FATE_VIDEO-$(call DEMDEC, AVI, R210) += fate-r210
 fate-r210: CMD = framecrc -i $(SAMPLES)/r210/r210.avi -pix_fmt rgb48le
 
-FATE_VIDEO += fate-rl2
+FATE_VIDEO-$(call DEMDEC, RL2, RL2) += fate-rl2
 fate-rl2: CMD = framecrc -i $(SAMPLES)/rl2/Z4915300.RL2 -pix_fmt rgb24 -an
 
-FATE_VIDEO += fate-roqvideo
+FATE_VIDEO-$(call DEMDEC, ROQ, ROQ) += fate-roqvideo
 fate-roqvideo: CMD = framecrc -i $(SAMPLES)/idroq/idlogo.roq -an
 
-FATE_VIDEO += fate-sanm
+FATE_VIDEO-$(call DEMDEC, SMUSH, SANM) += fate-sanm
 fate-sanm: CMD = framecrc -i $(SAMPLES)/smush/ronin_part.znm -an -pix_fmt rgb24
 
-FATA_VIDEO += fate-sierra-vmd-video
+FATE_VIDEO-$(call DEMDEC, VMD, VMDVIDEO) += fate-sierra-vmd-video
 fate-sierra-vmd-video: CMD = framecrc -i $(SAMPLES)/vmd/12.vmd -pix_fmt rgb24 -an
 
-FATA_VIDEO += fate-smacker-video
+FATE_VIDEO-$(call DEMDEC, SMACKER, SMACKER) += fate-smacker-video
 fate-smacker-video: CMD = framecrc -i $(SAMPLES)/smacker/wetlogo.smk -pix_fmt rgb24 -an
 
-FATE_VIDEO += fate-smc
+FATE_VIDEO-$(call DEMDEC, MOV, SMC) += fate-smc
 fate-smc: CMD = framecrc -i $(SAMPLES)/smc/cass_schi.qt -pix_fmt rgb24
 
-FATE_VIDEO += fate-sp5x
+FATE_VIDEO-$(call DEMDEC, AVI, SP5X) += fate-sp5x
 fate-sp5x: CMD = framecrc -idct simple -i $(SAMPLES)/sp5x/sp5x_problem.avi
 
-FATE_VIDEO += fate-thp
+FATE_VIDEO-$(call DEMDEC, THP, THP) += fate-thp
 fate-thp: CMD = framecrc -idct simple -i $(SAMPLES)/thp/pikmin2-opening1-partial.thp -an
 
-FATE_VIDEO += fate-tiertex-seq
+FATE_VIDEO-$(call DEMDEC, TIERTEXSEQ, TIERTEXSEQVIDEO) += fate-tiertex-seq
 fate-tiertex-seq: CMD = framecrc -i $(SAMPLES)/tiertex-seq/Gameover.seq -pix_fmt rgb24
 
-FATE_VIDEO += fate-tmv
+FATE_VIDEO-$(call DEMDEC, TMV, TMV) += fate-tmv
 fate-tmv: CMD = framecrc -i $(SAMPLES)/tmv/pop-partial.tmv -pix_fmt rgb24
 
 FATE_TXD += fate-txd-16bpp
@@ -224,41 +235,41 @@
 FATE_TXD += fate-txd-pal8
 fate-txd-pal8: CMD = framecrc -i $(SAMPLES)/txd/outro.txd -pix_fmt rgb24 -an
 
-FATE_VIDEO += $(FATE_TXD)
+FATE_VIDEO-$(call DEMDEC, TXD, TXD) += $(FATE_TXD)
 fate-txd: $(FATE_TXD)
 
-FATE_VIDEO += fate-ulti
+FATE_VIDEO-$(call DEMDEC, AVI, ULTI) += fate-ulti
 fate-ulti: CMD = framecrc -i $(SAMPLES)/ulti/hit12w.avi -an
 
-FATE_VIDEO += fate-v210
+FATE_VIDEO-$(call DEMDEC, AVI, V210) += fate-v210
 fate-v210: CMD = framecrc -i $(SAMPLES)/v210/v210_720p-partial.avi -pix_fmt yuv422p16be -an
 
-FATE_VIDEO += fate-v410dec
+FATE_VIDEO-$(call DEMDEC, MOV, V410) += fate-v410dec
 fate-v410dec: CMD = framecrc -i $(SAMPLES)/v410/lenav410.mov -pix_fmt yuv444p10le
 
-FATE_VIDEO += fate-v410enc
+FATE_VIDEO-$(call ENCDEC, V410 PGMYUV, AVI IMAGE2) += fate-v410enc
 fate-v410enc: tests/vsynth1/00.pgm
 fate-v410enc: CMD = md5 -f image2 -vcodec pgmyuv -i $(TARGET_PATH)/tests/vsynth1/%02d.pgm -flags +bitexact -vcodec v410 -f avi
 
-FATE_VIDEO += fate-vcr1
+FATE_VIDEO-$(call DEMDEC, AVI, VCR1) += fate-vcr1
 fate-vcr1: CMD = framecrc -i $(SAMPLES)/vcr1/VCR1test.avi -an
 
-FATE_VIDEO += fate-videoxl
+FATE_VIDEO-$(call DEMDEC, AVI, XL) += fate-videoxl
 fate-videoxl: CMD = framecrc -i $(SAMPLES)/vixl/pig-vixl.avi
 
-FATE_VIDEO += fate-vqa-cc
+FATE_VIDEO-$(call DEMDEC, WSVQA, VQA) += fate-vqa-cc
 fate-vqa-cc: CMD = framecrc -i $(SAMPLES)/vqa/cc-demo1-partial.vqa -pix_fmt rgb24 -an
 
-FATE_VIDEO += fate-wc3movie-xan
+FATE_VIDEO-$(call DEMDEC, WC3, XAN_WC3) += fate-wc3movie-xan
 fate-wc3movie-xan: CMD = framecrc -i $(SAMPLES)/wc3movie/SC_32-part.MVE -pix_fmt rgb24
 
-FATE_VIDEO += fate-wnv1
+FATE_VIDEO-$(call DEMDEC, AVI, WNV1) += fate-wnv1
 fate-wnv1: CMD = framecrc -i $(SAMPLES)/wnv1/wnv1-codec.avi -an
 
-FATE_VIDEO += fate-yop
+FATE_VIDEO-$(call DEMDEC, YOP, YOP) += fate-yop
 fate-yop: CMD = framecrc -i $(SAMPLES)/yop/test1.yop -pix_fmt rgb24 -an
 
-FATE_VIDEO += fate-xxan-wc4
+FATE_VIDEO-$(call DEMDEC, AVI, XAN_WC4) += fate-xxan-wc4
 fate-xxan-wc4: CMD = framecrc -i $(SAMPLES)/wc4-xan/wc4trailer-partial.avi -an
 
 FATE_VIDEO += $(FATE_VIDEO-yes)
diff --git a/tests/fate/voice.mak b/tests/fate/voice.mak
index 6d80b7f..3535d55 100644
--- a/tests/fate/voice.mak
+++ b/tests/fate/voice.mak
@@ -37,25 +37,20 @@
 fate-g723_1: $(FATE_G723_1)
 
 FATE_G726 += fate-g726-encode-2bit
-fate-g726-encode-2bit: tests/data/asynth-8000-1.wav
-fate-g726-encode-2bit: SRC = tests/data/asynth-8000-1.wav
 fate-g726-encode-2bit: CMD = enc_dec_pcm wav md5 s16le $(SRC) -c:a g726 -b:a 16k
 
 FATE_G726 += fate-g726-encode-3bit
-fate-g726-encode-3bit: tests/data/asynth-8000-1.wav
-fate-g726-encode-3bit: SRC = tests/data/asynth-8000-1.wav
 fate-g726-encode-3bit: CMD = enc_dec_pcm wav md5 s16le $(SRC) -c:a g726 -b:a 24k
 
 FATE_G726 += fate-g726-encode-4bit
-fate-g726-encode-4bit: tests/data/asynth-8000-1.wav
-fate-g726-encode-4bit: SRC = tests/data/asynth-8000-1.wav
 fate-g726-encode-4bit: CMD = enc_dec_pcm wav md5 s16le $(SRC) -c:a g726 -b:a 32k
 
 FATE_G726 += fate-g726-encode-5bit
-fate-g726-encode-5bit: tests/data/asynth-8000-1.wav
-fate-g726-encode-5bit: SRC = tests/data/asynth-8000-1.wav
 fate-g726-encode-5bit: CMD = enc_dec_pcm wav md5 s16le $(SRC) -c:a g726 -b:a 40k
 
+$(FATE_G726): tests/data/asynth-8000-1.wav
+$(FATE_G726): SRC = tests/data/asynth-8000-1.wav
+
 FATE_VOICE += $(FATE_G726)
 fate-g726: $(FATE_G726)
 
diff --git a/tests/fate/vorbis.mak b/tests/fate/vorbis.mak
index 774cb35..39a9724 100644
--- a/tests/fate/vorbis.mak
+++ b/tests/fate/vorbis.mak
@@ -80,6 +80,6 @@
 fate-vorbis-20: CMD = pcm -i $(SAMPLES)/vorbis/6.ogg
 fate-vorbis-20: REF = $(SAMPLES)/vorbis/6.pcm
 
-FATE_SAMPLES_AVCONV += $(FATE_VORBIS)
+FATE_SAMPLES_AVCONV-$(call DEMDEC, OGG, VORBIS) += $(FATE_VORBIS)
 fate-vorbis: $(FATE_VORBIS)
 $(FATE_VORBIS): CMP = oneoff
diff --git a/tests/fate/vpx.mak b/tests/fate/vpx.mak
index d3f9cc7..fd9c905 100644
--- a/tests/fate/vpx.mak
+++ b/tests/fate/vpx.mak
@@ -1,34 +1,34 @@
-FATE_VP3 += fate-vp31
+FATE_VP3-$(CONFIG_AVI_DEMUXER) += fate-vp31
 fate-vp31: CMD = framecrc -i $(SAMPLES)/vp3/vp31.avi
 
-FATE_VP3 += fate-vp3-coeff-level64
+FATE_VP3-$(CONFIG_MATROSKA_DEMUXER) += fate-vp3-coeff-level64
 fate-vp3-coeff-level64: CMD = framecrc -i $(SAMPLES)/vp3/coeff_level64.mkv
 
-FATE_SAMPLES_AVCONV += $(FATE_VP3)
-fate-vp3: $(FATE_VP3)
+FATE_SAMPLES_AVCONV-$(CONFIG_VP3_DECODER) += $(FATE_VP3-yes)
+fate-vp3: $(FATE_VP3-yes)
 
-FATE_SAMPLES_AVCONV += fate-vp5
+FATE_SAMPLES_AVCONV-$(call DEMDEC, AVI, VP5) += fate-vp5
 fate-vp5: CMD = framecrc -i $(SAMPLES)/vp5/potter512-400-partial.avi -an
 
-FATE_VP6 += fate-vp60
+FATE_VP6-$(call DEMDEC, EA, VP6) += fate-vp60
 fate-vp60: CMD = framecrc -i $(SAMPLES)/ea-vp6/g36.vp6
 
-FATE_VP6 += fate-vp61
+FATE_VP6-$(call DEMDEC, EA, VP6) += fate-vp61
 fate-vp61: CMD = framecrc -i $(SAMPLES)/ea-vp6/MovieSkirmishGondor.vp6 -t 4
 
-FATE_VP6 += fate-vp6a
+FATE_VP6-$(call DEMDEC, FLV, VP6A) += fate-vp6a
 fate-vp6a: CMD = framecrc -i $(SAMPLES)/flash-vp6/300x180-Scr-f8-056alpha.flv
 
-FATE_VP6 += fate-vp6f
+FATE_VP6-$(call DEMDEC, FLV, VP6F) += fate-vp6f
 fate-vp6f: CMD = framecrc -i $(SAMPLES)/flash-vp6/clip1024.flv
 
-FATE_SAMPLES_AVCONV += $(FATE_VP6)
-fate-vp6: $(FATE_VP6)
+FATE_SAMPLES_AVCONV += $(FATE_VP6-yes)
+fate-vp6: $(FATE_VP6-yes)
 
 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-$(CONFIG_IVF_DEMUXER) += 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)/tests/ref/fate/vp8-test-vector-$(1)
 endef
@@ -38,16 +38,16 @@
 
 # FIXME this file contains two frames with identical timestamps,
 # so ffmpeg drops one of them
-FATE_VP8 += fate-vp8-sign-bias$(1)
+FATE_VP8-$(CONFIG_IVF_DEMUXER) += 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)/tests/ref/fate/vp8-sign-bias
 
-FATE_VP8 += fate-vp8-size-change$(1)
+FATE_VP8-$(CONFIG_MATROSKA_DEMUXER) += fate-vp8-size-change$(1)
 fate-vp8-size-change$(1): CMD = framemd5 $(2) -flags +bitexact -i $(SAMPLES)/vp8/frame_size_change.webm -frames:v 30 -sws_flags bitexact+bilinear
 fate-vp8-size-change$(1): REF = $(SRC_PATH)/tests/ref/fate/vp8-size-change
 endef
 
 $(eval $(call FATE_VP8_FULL))
 $(eval $(call FATE_VP8_FULL,-emu-edge,-flags +emu_edge))
-FATE_SAMPLES_AVCONV += $(FATE_VP8)
-fate-vp8: $(FATE_VP8)
+FATE_SAMPLES_AVCONV-$(CONFIG_VP8_DECODER) += $(FATE_VP8-yes)
+fate-vp8: $(FATE_VP8-yes)
diff --git a/tests/fate/vqf.mak b/tests/fate/vqf.mak
index b8a91c1..67ee61f 100644
--- a/tests/fate/vqf.mak
+++ b/tests/fate/vqf.mak
@@ -1,10 +1,12 @@
-FATE_VQF += fate-twinvq
+FATE_VQF-$(call DEMDEC, VQF, TWINVQ) += fate-twinvq
 fate-twinvq: CMD = pcm -i $(SAMPLES)/vqf/achterba.vqf
 fate-twinvq: CMP = oneoff
 fate-twinvq: REF = $(SAMPLES)/vqf/achterba.pcm
 
-FATE_VQF += fate-vqf-demux
+FATE_VQF-$(CONFIG_VQF_DEMUXER) += fate-vqf-demux
 fate-vqf-demux: CMD = md5 -i $(SAMPLES)/vqf/achterba.vqf -acodec copy -f framecrc
 
+FATE_VQF += $(FATE_VQF-yes)
+
 FATE_SAMPLES_FFMPEG += $(FATE_VQF)
 fate-vqf: $(FATE_VQF)
diff --git a/tests/fate/wavpack.mak b/tests/fate/wavpack.mak
index b615c9e..ef190fa 100644
--- a/tests/fate/wavpack.mak
+++ b/tests/fate/wavpack.mak
@@ -83,8 +83,10 @@
 FATE_WAVPACK += fate-wavpack-falsestereo
 fate-wavpack-falsestereo: CMD = md5 -i $(SAMPLES)/wavpack/special/false_stereo.wv -f s16le
 
-FATE_WAVPACK += fate-wavpack-matroskamode
+FATE_WAVPACK-$(call DEMDEC, WV, WAVPACK) += $(FATE_WAVPACK)
+
+FATE_WAVPACK-$(call DEMDEC, MATROSKA, WAVPACK) += fate-wavpack-matroskamode
 fate-wavpack-matroskamode: CMD = md5 -i $(SAMPLES)/wavpack/special/matroska_mode.mka -f s16le
 
-FATE_SAMPLES_AVCONV += $(FATE_WAVPACK)
-fate-wavpack: $(FATE_WAVPACK)
+FATE_SAMPLES_AVCONV += $(FATE_WAVPACK-yes)
+fate-wavpack: $(FATE_WAVPACK-yes)
diff --git a/tests/fate/wma.mak b/tests/fate/wma.mak
index ba52b31..b9a856c 100644
--- a/tests/fate/wma.mak
+++ b/tests/fate/wma.mak
@@ -1,57 +1,54 @@
-FATE_WMAPRO += fate-wmapro-2ch
+FATE_WMAPRO-$(call DEMDEC, ASF, WMAPRO) += 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_WMAPRO += fate-wmapro-5.1
+FATE_WMAPRO-$(call DEMDEC, ASF, WMAPRO) += 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_WMAPRO += fate-wmapro-ism
+FATE_WMAPRO-$(call DEMDEC, MOV, WMAPRO) += fate-wmapro-ism
 fate-wmapro-ism: CMD = pcm -i $(SAMPLES)/isom/vc1-wmapro.ism -vn
-fate-wmapro-ism: CMP = oneoff
 fate-wmapro-ism: REF = $(SAMPLES)/isom/vc1-wmapro.pcm
 
-FATE_SAMPLES_AVCONV += $(FATE_WMAPRO)
-fate-wmapro: $(FATE_WMAPRO)
+$(FATE_WMAPRO-yes): CMP = oneoff
 
-FATE_WMAVOICE += fate-wmavoice-7k
+FATE_SAMPLES_AVCONV += $(FATE_WMAPRO-yes)
+fate-wmapro: $(FATE_WMAPRO-yes)
+
+FATE_WMAVOICE-$(call DEMDEC, ASF, WMAVOICE) += 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_WMAVOICE += fate-wmavoice-11k
+FATE_WMAVOICE-$(call DEMDEC, ASF, WMAVOICE) += 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_WMAVOICE += fate-wmavoice-19k
+FATE_WMAVOICE-$(call DEMDEC, ASF, WMAVOICE) += 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_SAMPLES_AVCONV += $(FATE_WMAVOICE)
-fate-wmavoice: $(FATE_WMAVOICE)
+$(FATE_WMAVOICE-yes): CMP = stddev
 
-FATE_WMA_ENCODE += fate-wmav1-encode
+FATE_SAMPLES_AVCONV += $(FATE_WMAVOICE-yes)
+fate-wmavoice: $(FATE_WMAVOICE-yes)
+
+FATE_WMA_ENCODE-$(call ENCDEC, WMAV1, ASF) += fate-wmav1-encode
 fate-wmav1-encode: CMD = enc_dec_pcm asf wav s16le $(REF) -c:a wmav1 -b:a 128k
-fate-wmav1-encode: CMP = stddev
-fate-wmav1-encode: REF = $(SAMPLES)/audio-reference/luckynight_2ch_44kHz_s16.wav
 fate-wmav1-encode: CMP_SHIFT = -8192
 fate-wmav1-encode: CMP_TARGET = 291.06
 fate-wmav1-encode: SIZE_TOLERANCE = 4632
 
-FATE_WMA_ENCODE += fate-wmav2-encode
+FATE_WMA_ENCODE-$(call ENCDEC, WMAV2, ASF) += fate-wmav2-encode
 fate-wmav2-encode: CMD = enc_dec_pcm asf wav s16le $(REF) -c:a wmav2 -b:a 128k
-fate-wmav2-encode: CMP = stddev
-fate-wmav2-encode: REF = $(SAMPLES)/audio-reference/luckynight_2ch_44kHz_s16.wav
 fate-wmav2-encode: CMP_SHIFT = -8192
 fate-wmav2-encode: CMP_TARGET = 258.32
 fate-wmav2-encode: SIZE_TOLERANCE = 4632
 
-FATE_SAMPLES_AVCONV += $(FATE_WMA_ENCODE)
-fate-wma-encode: $(FATE_WMA_ENCODE)
+$(FATE_WMA_ENCODE-yes): CMP = stddev
+$(FATE_WMA_ENCODE-yes): REF = $(SAMPLES)/audio-reference/luckynight_2ch_44kHz_s16.wav
+
+FATE_SAMPLES_AVCONV += $(FATE_WMA_ENCODE-yes)
+fate-wma-encode: $(FATE_WMA_ENCODE-yes)
diff --git a/tests/lavf-regression.sh b/tests/lavf-regression.sh
index 4a348f5..64ebc0a 100755
--- a/tests/lavf-regression.sh
+++ b/tests/lavf-regression.sh
@@ -102,6 +102,10 @@
 do_lavf ffm "-ab 64k"
 fi
 
+if [ -n "$do_flm" ] ; then
+do_lavf flm "" "-pix_fmt rgba"
+fi
+
 if [ -n "$do_flv_fmt" ] ; then
 do_lavf flv "" "-an"
 fi
@@ -236,6 +240,11 @@
 
 if [ -n "$do_pam" ] ; then
 do_image_formats pam
+do_image_formats pam "-pix_fmt rgba"
+do_image_formats pam "-pix_fmt gray"
+do_image_formats pam "-pix_fmt gray16be"
+do_image_formats pam "-pix_fmt rgb48be"
+do_image_formats pam "-pix_fmt monob"
 fi
 
 if [ -n "$do_pcx" ] ; then
@@ -250,6 +259,13 @@
 
 if [ -n "$do_xwd" ] ; then
 do_image_formats xwd
+do_image_formats xwd "-pix_fmt rgba"
+do_image_formats xwd "-pix_fmt rgb565be"
+do_image_formats xwd "-pix_fmt rgb555be"
+do_image_formats xwd "-pix_fmt rgb8"
+do_image_formats xwd "-pix_fmt rgb4_byte"
+do_image_formats xwd "-pix_fmt gray"
+do_image_formats xwd "-pix_fmt monow"
 fi
 
 if [ -n "$do_sunrast" ] ; then
@@ -298,6 +314,10 @@
 do_audio_only rso
 fi
 
+if [ -n "$do_smjpeg" ] ; then
+do_lavf smjpeg "" "-f smjpeg"
+fi
+
 if [ -n "$do_sox" ] ; then
 do_audio_only sox
 fi
diff --git a/tests/lavfi-regression.sh b/tests/lavfi-regression.sh
index ac6bb7f..36586ef 100755
--- a/tests/lavfi-regression.sh
+++ b/tests/lavfi-regression.sh
@@ -24,12 +24,12 @@
     vfilters="$2"
 
     if [ $test = $1 ] ; then
-        do_video_filter $test "$vfilters"
+        do_video_filter $test "$2"
     fi
 }
 
 do_lavfi() {
-    do_lavfi_plain $1 "slicify=random,$2"
+    do_lavfi_plain $1 "$2"
 }
 
 do_lavfi_colormatrix() {
@@ -44,6 +44,8 @@
 do_lavfi "drawbox"            "drawbox=224:24:88:72:#FF8010@0.5"
 do_lavfi "edgedetect"         "edgedetect"
 do_lavfi "fade"               "fade=in:5:15,fade=out:30:15"
+do_lavfi "hue"                "hue=s=sin(2*PI*t)+1"
+do_lavfi "idet"               "idet"
 do_lavfi "null"               "null"
 do_lavfi "overlay"            "split[m],scale=88:72,pad=96:80:4:4[o2];[m]fifo[o1],[o1][o2]overlay=240:16"
 do_lavfi "pad"                "pad=iw*1.5:ih*1.5:iw*0.3:ih*0.2"
@@ -59,17 +61,17 @@
 do_lavfi "setdar"             "setdar=16/9"
 do_lavfi "setsar"             "setsar=16/11"
 do_lavfi "thumbnail"          "thumbnail=10"
-do_lavfi "tile"               "tile=3x3"
+do_lavfi "tile"               "tile=3x3:nb_frames=5:padding=7:margin=2"
 do_lavfi "transpose"          "transpose"
 do_lavfi "unsharp"            "unsharp=10:10:-1.5:10:10:-1.5"
 do_lavfi "vflip"              "vflip"
 do_lavfi "vflip_crop"         "vflip,crop=iw-100:ih-100:100:100"
 do_lavfi "vflip_vflip"        "vflip,vflip"
 
-do_lavfi_plain "alphamerge_rgb"     "[in]slicify=random,format=bgra,split,alphamerge[out]"
-do_lavfi_plain "alphamerge_yuv"     "[in]slicify=random,format=yuv420p,split,alphamerge[out]"
-do_lavfi_plain "alphaextract_rgb"   "[in]slicify=random,format=bgra,split,alphamerge,slicify=random,split[o3][o4];[o4]alphaextract[alpha];[o3][alpha]alphamerge[out]"
-do_lavfi_plain "alphaextract_yuv"   "[in]slicify=random,format=yuv420p,split,alphamerge,slicify=random,split[o3][o4];[o4]alphaextract[alpha];[o3][alpha]alphamerge[out]"
+do_lavfi_plain "alphamerge_rgb"     "[in]format=bgra,split,alphamerge[out]"
+do_lavfi_plain "alphamerge_yuv"     "[in]format=yuv420p,split,alphamerge[out]"
+do_lavfi_plain "alphaextract_rgb"   "[in]format=bgra,split,alphamerge,split[o3][o4];[o4]alphaextract[alpha];[o3][alpha]alphamerge[out]"
+do_lavfi_plain "alphaextract_yuv"   "[in]format=yuv420p,split,alphamerge,split[o3][o4];[o4]alphaextract[alpha];[o3][alpha]alphamerge[out]"
 
 do_lavfi_colormatrix "colormatrix" bt709 fcc bt601 smpte240m
 
@@ -100,7 +102,7 @@
     pix_fmts=$(comm -12 $scale_exclude_fmts $in_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
+        do_video_filter $pix_fmt "format=$pix_fmt,$filter=$filter_args" -pix_fmt $pix_fmt
     done
 
     rm $in_fmts $scale_in_fmts $scale_out_fmts $scale_exclude_fmts
@@ -110,6 +112,7 @@
 do_lavfi_pixfmts "copy"    ""
 do_lavfi_pixfmts "crop"    "100:100:100:100"
 do_lavfi_pixfmts "hflip"   ""
+do_lavfi_pixfmts "field"   "field" "bottom"
 do_lavfi_pixfmts "null"    ""
 do_lavfi_pixfmts "pad"     "500:400:20:20"
 do_lavfi_pixfmts "pixdesctest" ""
@@ -131,6 +134,7 @@
 
 do_lavfi_lavd "life"                 "life=s=40x40:r=5:seed=42:mold=64" -t 2
 do_lavfi_lavd "testsrc"              "testsrc=r=7:n=2:d=10"
+do_lavfi_lavd "scalenorm"            "sws_flags=+accurate_rnd+bitexact;testsrc=s=128x96:d=1:r=5,format=yuv420p[a];testsrc=s=160x120:d=1:r=5[b];[a][b]concat=unsafe=1,scale=flags=+accurate_rnd+bitexact"
 
 # TODO: add tests for
 # direct rendering,
diff --git a/tests/md5.sh b/tests/md5.sh
index e21e5c3..5e2528c 100644
--- a/tests/md5.sh
+++ b/tests/md5.sh
@@ -1,6 +1,6 @@
 # try to find an md5 program
 
-if [ X"$(echo | md5sum 2> /dev/null)" != X ]; then
+if [ X"$(echo | md5sum -b 2> /dev/null)" != X ]; then
     do_md5sum() { md5sum -b $1; }
 elif [ X"$(echo | command md5 2> /dev/null)" != X ]; then
     do_md5sum() { command md5 $1 | sed 's#MD5 (\(.*\)) = \(.*\)#\2 *\1#'; }
diff --git a/tests/ref/fate/acodec-adpcm-adx b/tests/ref/acodec/adpcm-adx
similarity index 100%
rename from tests/ref/fate/acodec-adpcm-adx
rename to tests/ref/acodec/adpcm-adx
diff --git a/tests/ref/fate/acodec-adpcm-ima_qt b/tests/ref/acodec/adpcm-ima_qt
similarity index 100%
rename from tests/ref/fate/acodec-adpcm-ima_qt
rename to tests/ref/acodec/adpcm-ima_qt
diff --git a/tests/ref/fate/acodec-adpcm-ima_wav b/tests/ref/acodec/adpcm-ima_wav
similarity index 100%
rename from tests/ref/fate/acodec-adpcm-ima_wav
rename to tests/ref/acodec/adpcm-ima_wav
diff --git a/tests/ref/fate/acodec-adpcm-ms b/tests/ref/acodec/adpcm-ms
similarity index 100%
rename from tests/ref/fate/acodec-adpcm-ms
rename to tests/ref/acodec/adpcm-ms
diff --git a/tests/ref/fate/acodec-adpcm-swf b/tests/ref/acodec/adpcm-swf
similarity index 100%
rename from tests/ref/fate/acodec-adpcm-swf
rename to tests/ref/acodec/adpcm-swf
diff --git a/tests/ref/fate/acodec-adpcm-yamaha b/tests/ref/acodec/adpcm-yamaha
similarity index 100%
rename from tests/ref/fate/acodec-adpcm-yamaha
rename to tests/ref/acodec/adpcm-yamaha
diff --git a/tests/ref/fate/acodec-adpcm_ima_qt b/tests/ref/acodec/adpcm_ima_qt
similarity index 100%
rename from tests/ref/fate/acodec-adpcm_ima_qt
rename to tests/ref/acodec/adpcm_ima_qt
diff --git a/tests/ref/fate/acodec-alac b/tests/ref/acodec/alac
similarity index 100%
rename from tests/ref/fate/acodec-alac
rename to tests/ref/acodec/alac
diff --git a/tests/ref/fate/acodec-flac b/tests/ref/acodec/flac
similarity index 100%
rename from tests/ref/fate/acodec-flac
rename to tests/ref/acodec/flac
diff --git a/tests/ref/fate/acodec-g723_1 b/tests/ref/acodec/g723_1
similarity index 100%
rename from tests/ref/fate/acodec-g723_1
rename to tests/ref/acodec/g723_1
diff --git a/tests/ref/fate/acodec-mp2 b/tests/ref/acodec/mp2
similarity index 100%
rename from tests/ref/fate/acodec-mp2
rename to tests/ref/acodec/mp2
diff --git a/tests/ref/fate/acodec-pcm-alaw b/tests/ref/acodec/pcm-alaw
similarity index 100%
rename from tests/ref/fate/acodec-pcm-alaw
rename to tests/ref/acodec/pcm-alaw
diff --git a/tests/ref/acodec/pcm-f32be b/tests/ref/acodec/pcm-f32be
new file mode 100644
index 0000000..5bd700c
--- /dev/null
+++ b/tests/ref/acodec/pcm-f32be
@@ -0,0 +1,4 @@
+e74eb6b65cb397ce541bac120b00680a *tests/data/fate/acodec-pcm-f32be.au
+2116832 tests/data/fate/acodec-pcm-f32be.au
+64151e4bcc2b717aa5a8454d424d6a1f *tests/data/fate/acodec-pcm-f32be.out.wav
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/fate/acodec-pcm-f32le b/tests/ref/acodec/pcm-f32le
similarity index 100%
rename from tests/ref/fate/acodec-pcm-f32le
rename to tests/ref/acodec/pcm-f32le
diff --git a/tests/ref/acodec/pcm-f64be b/tests/ref/acodec/pcm-f64be
new file mode 100644
index 0000000..fd0cff6
--- /dev/null
+++ b/tests/ref/acodec/pcm-f64be
@@ -0,0 +1,4 @@
+8c8ba9d2c68384c5f077306e220f1188 *tests/data/fate/acodec-pcm-f64be.au
+4233632 tests/data/fate/acodec-pcm-f64be.au
+64151e4bcc2b717aa5a8454d424d6a1f *tests/data/fate/acodec-pcm-f64be.out.wav
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/fate/acodec-pcm-f64le b/tests/ref/acodec/pcm-f64le
similarity index 100%
rename from tests/ref/fate/acodec-pcm-f64le
rename to tests/ref/acodec/pcm-f64le
diff --git a/tests/ref/fate/acodec-pcm-mulaw b/tests/ref/acodec/pcm-mulaw
similarity index 100%
rename from tests/ref/fate/acodec-pcm-mulaw
rename to tests/ref/acodec/pcm-mulaw
diff --git a/tests/ref/fate/acodec-pcm-s16be b/tests/ref/acodec/pcm-s16be
similarity index 100%
rename from tests/ref/fate/acodec-pcm-s16be
rename to tests/ref/acodec/pcm-s16be
diff --git a/tests/ref/acodec/pcm-s16be_planar b/tests/ref/acodec/pcm-s16be_planar
new file mode 100644
index 0000000..8116480
--- /dev/null
+++ b/tests/ref/acodec/pcm-s16be_planar
@@ -0,0 +1,4 @@
+cd87e6fc3bddb85c945c050d8c3fba11 *tests/data/fate/acodec-pcm-s16be_planar.nut
+1060673 tests/data/fate/acodec-pcm-s16be_planar.nut
+64151e4bcc2b717aa5a8454d424d6a1f *tests/data/fate/acodec-pcm-s16be_planar.out.wav
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/fate/acodec-pcm-s16le b/tests/ref/acodec/pcm-s16le
similarity index 100%
rename from tests/ref/fate/acodec-pcm-s16le
rename to tests/ref/acodec/pcm-s16le
diff --git a/tests/ref/acodec/pcm-s16le_planar b/tests/ref/acodec/pcm-s16le_planar
new file mode 100644
index 0000000..c933001
--- /dev/null
+++ b/tests/ref/acodec/pcm-s16le_planar
@@ -0,0 +1,4 @@
+74af9a0ae4f68451102a2f7524b2d55f *tests/data/fate/acodec-pcm-s16le_planar.nut
+1060673 tests/data/fate/acodec-pcm-s16le_planar.nut
+64151e4bcc2b717aa5a8454d424d6a1f *tests/data/fate/acodec-pcm-s16le_planar.out.wav
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/acodec/pcm-s24be b/tests/ref/acodec/pcm-s24be
new file mode 100644
index 0000000..3ebe02a
--- /dev/null
+++ b/tests/ref/acodec/pcm-s24be
@@ -0,0 +1,4 @@
+f65a7ae3b70ca53ffa354b1e7ff3a33d *tests/data/fate/acodec-pcm-s24be.mov
+1588323 tests/data/fate/acodec-pcm-s24be.mov
+64151e4bcc2b717aa5a8454d424d6a1f *tests/data/fate/acodec-pcm-s24be.out.wav
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/fate/acodec-pcm-s24le b/tests/ref/acodec/pcm-s24le
similarity index 100%
rename from tests/ref/fate/acodec-pcm-s24le
rename to tests/ref/acodec/pcm-s24le
diff --git a/tests/ref/acodec/pcm-s24le_planar b/tests/ref/acodec/pcm-s24le_planar
new file mode 100644
index 0000000..14d4cec
--- /dev/null
+++ b/tests/ref/acodec/pcm-s24le_planar
@@ -0,0 +1,4 @@
+83e315ce8083a6d035f801bb862942bf *tests/data/fate/acodec-pcm-s24le_planar.nut
+1590202 tests/data/fate/acodec-pcm-s24le_planar.nut
+64151e4bcc2b717aa5a8454d424d6a1f *tests/data/fate/acodec-pcm-s24le_planar.out.wav
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/acodec/pcm-s32be b/tests/ref/acodec/pcm-s32be
new file mode 100644
index 0000000..9075083
--- /dev/null
+++ b/tests/ref/acodec/pcm-s32be
@@ -0,0 +1,4 @@
+f9e16fafeefb2285e943f53133e9cfd5 *tests/data/fate/acodec-pcm-s32be.mov
+2117527 tests/data/fate/acodec-pcm-s32be.mov
+64151e4bcc2b717aa5a8454d424d6a1f *tests/data/fate/acodec-pcm-s32be.out.wav
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/fate/acodec-pcm-s32le b/tests/ref/acodec/pcm-s32le
similarity index 100%
rename from tests/ref/fate/acodec-pcm-s32le
rename to tests/ref/acodec/pcm-s32le
diff --git a/tests/ref/acodec/pcm-s32le_planar b/tests/ref/acodec/pcm-s32le_planar
new file mode 100644
index 0000000..7648766
--- /dev/null
+++ b/tests/ref/acodec/pcm-s32le_planar
@@ -0,0 +1,4 @@
+f6199b2c698bd5dd1438b53431357bec *tests/data/fate/acodec-pcm-s32le_planar.nut
+2120148 tests/data/fate/acodec-pcm-s32le_planar.nut
+64151e4bcc2b717aa5a8454d424d6a1f *tests/data/fate/acodec-pcm-s32le_planar.out.wav
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/fate/acodec-pcm-s8 b/tests/ref/acodec/pcm-s8
similarity index 100%
rename from tests/ref/fate/acodec-pcm-s8
rename to tests/ref/acodec/pcm-s8
diff --git a/tests/ref/acodec/pcm-s8_planar b/tests/ref/acodec/pcm-s8_planar
new file mode 100644
index 0000000..6ab6ee0
--- /dev/null
+++ b/tests/ref/acodec/pcm-s8_planar
@@ -0,0 +1,4 @@
+ce99d95295ade9945849ef7c1de8c4ca *tests/data/fate/acodec-pcm-s8_planar.nut
+531054 tests/data/fate/acodec-pcm-s8_planar.nut
+651d4eb8d98dfcdda96ae6c43d8f156b *tests/data/fate/acodec-pcm-s8_planar.out.wav
+stddev:  147.89 PSNR: 52.93 MAXDIFF:  255 bytes:  1058400/  1058400
diff --git a/tests/ref/acodec/pcm-u16be b/tests/ref/acodec/pcm-u16be
new file mode 100644
index 0000000..0214975
--- /dev/null
+++ b/tests/ref/acodec/pcm-u16be
@@ -0,0 +1,4 @@
+eab6206a2cec3c5a3be47fdaa826faff *tests/data/fate/acodec-pcm-u16be.nut
+1060673 tests/data/fate/acodec-pcm-u16be.nut
+64151e4bcc2b717aa5a8454d424d6a1f *tests/data/fate/acodec-pcm-u16be.out.wav
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/acodec/pcm-u16le b/tests/ref/acodec/pcm-u16le
new file mode 100644
index 0000000..e45fe08
--- /dev/null
+++ b/tests/ref/acodec/pcm-u16le
@@ -0,0 +1,4 @@
+8fceb284cc6a5a114b6ce7a10fd08020 *tests/data/fate/acodec-pcm-u16le.nut
+1060673 tests/data/fate/acodec-pcm-u16le.nut
+64151e4bcc2b717aa5a8454d424d6a1f *tests/data/fate/acodec-pcm-u16le.out.wav
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/acodec/pcm-u24be b/tests/ref/acodec/pcm-u24be
new file mode 100644
index 0000000..ddab6e8
--- /dev/null
+++ b/tests/ref/acodec/pcm-u24be
@@ -0,0 +1,4 @@
+d1a55f46c88ed1efa77d05b60259675d *tests/data/fate/acodec-pcm-u24be.nut
+1590202 tests/data/fate/acodec-pcm-u24be.nut
+64151e4bcc2b717aa5a8454d424d6a1f *tests/data/fate/acodec-pcm-u24be.out.wav
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/acodec/pcm-u24le b/tests/ref/acodec/pcm-u24le
new file mode 100644
index 0000000..df06ca4
--- /dev/null
+++ b/tests/ref/acodec/pcm-u24le
@@ -0,0 +1,4 @@
+6d7df9b7e074548cf18dd16365862f1b *tests/data/fate/acodec-pcm-u24le.nut
+1590202 tests/data/fate/acodec-pcm-u24le.nut
+64151e4bcc2b717aa5a8454d424d6a1f *tests/data/fate/acodec-pcm-u24le.out.wav
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/acodec/pcm-u32be b/tests/ref/acodec/pcm-u32be
new file mode 100644
index 0000000..6a53919
--- /dev/null
+++ b/tests/ref/acodec/pcm-u32be
@@ -0,0 +1,4 @@
+7078e6d7e80247b8531d5cc16d09f385 *tests/data/fate/acodec-pcm-u32be.nut
+2120148 tests/data/fate/acodec-pcm-u32be.nut
+64151e4bcc2b717aa5a8454d424d6a1f *tests/data/fate/acodec-pcm-u32be.out.wav
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/acodec/pcm-u32le b/tests/ref/acodec/pcm-u32le
new file mode 100644
index 0000000..18a5d15
--- /dev/null
+++ b/tests/ref/acodec/pcm-u32le
@@ -0,0 +1,4 @@
+34df9a7e1fe60da0bc6ec0485b68726e *tests/data/fate/acodec-pcm-u32le.nut
+2120148 tests/data/fate/acodec-pcm-u32le.nut
+64151e4bcc2b717aa5a8454d424d6a1f *tests/data/fate/acodec-pcm-u32le.out.wav
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/fate/acodec-pcm-u8 b/tests/ref/acodec/pcm-u8
similarity index 100%
rename from tests/ref/fate/acodec-pcm-u8
rename to tests/ref/acodec/pcm-u8
diff --git a/tests/ref/fate/acodec-roqaudio b/tests/ref/acodec/roqaudio
similarity index 100%
rename from tests/ref/fate/acodec-roqaudio
rename to tests/ref/acodec/roqaudio
diff --git a/tests/ref/fate/acodec-pcm-f32be b/tests/ref/fate/acodec-pcm-f32be
deleted file mode 100644
index 5b0f498..0000000
--- a/tests/ref/fate/acodec-pcm-f32be
+++ /dev/null
@@ -1,4 +0,0 @@
-118ff3dc83c62ce9ce669eef57e55bb2 *tests/data/fate/acodec-pcm-f32be.au
-2116824 tests/data/fate/acodec-pcm-f32be.au
-64151e4bcc2b717aa5a8454d424d6a1f *tests/data/fate/acodec-pcm-f32be.out.wav
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/fate/acodec-pcm-f64be b/tests/ref/fate/acodec-pcm-f64be
deleted file mode 100644
index dd882d3..0000000
--- a/tests/ref/fate/acodec-pcm-f64be
+++ /dev/null
@@ -1,4 +0,0 @@
-8112296b1ed94f72f20d04b1a54850a7 *tests/data/fate/acodec-pcm-f64be.au
-4233624 tests/data/fate/acodec-pcm-f64be.au
-64151e4bcc2b717aa5a8454d424d6a1f *tests/data/fate/acodec-pcm-f64be.out.wav
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/fate/acodec-pcm-s24be b/tests/ref/fate/acodec-pcm-s24be
deleted file mode 100644
index c89e086..0000000
--- a/tests/ref/fate/acodec-pcm-s24be
+++ /dev/null
@@ -1,4 +0,0 @@
-5d843e1f56796aae3185016f164b16b7 *tests/data/fate/acodec-pcm-s24be.mov
-1588269 tests/data/fate/acodec-pcm-s24be.mov
-64151e4bcc2b717aa5a8454d424d6a1f *tests/data/fate/acodec-pcm-s24be.out.wav
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/fate/acodec-pcm-s32be b/tests/ref/fate/acodec-pcm-s32be
deleted file mode 100644
index f7dbc52..0000000
--- a/tests/ref/fate/acodec-pcm-s32be
+++ /dev/null
@@ -1,4 +0,0 @@
-b34c66c56df1b1e75688929cf20670b9 *tests/data/fate/acodec-pcm-s32be.mov
-2117473 tests/data/fate/acodec-pcm-s32be.mov
-64151e4bcc2b717aa5a8454d424d6a1f *tests/data/fate/acodec-pcm-s32be.out.wav
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/fate/adpcm-4xm b/tests/ref/fate/adpcm-4xm
new file mode 100644
index 0000000..eb5cfe6
--- /dev/null
+++ b/tests/ref/fate/adpcm-4xm
@@ -0,0 +1,27 @@
+#tb 0: 1/22050
+0,          0,          0,     1472,     5888, 0x9086e310
+0,       1476,       1476,     1472,     5888, 0xac8491f5
+0,       2952,       2952,     1472,     5888, 0xc9a08b6b
+0,       4428,       4428,     1472,     5888, 0x4cff893b
+0,       5904,       5904,     1464,     5856, 0xfb914624
+0,       7372,       7372,     1472,     5888, 0x1dd9781f
+0,       8848,       8848,     1472,     5888, 0x75937688
+0,      10324,      10324,     1472,     5888, 0x6c93a266
+0,      11800,      11800,     1464,     5856, 0xb14e6783
+0,      13268,      13268,     1472,     5888, 0x4d268759
+0,      14744,      14744,     1472,     5888, 0xce44b8c6
+0,      16220,      16220,     1472,     5888, 0xf99f7347
+0,      17696,      17696,     1464,     5856, 0x35591adc
+0,      19164,      19164,     1472,     5888, 0x67692338
+0,      20640,      20640,     1472,     5888, 0x6465addd
+0,      22116,      22116,     1472,     5888, 0x22c66aaf
+0,      23592,      23592,     1464,     5856, 0x016b78d9
+0,      25060,      25060,     1472,     5888, 0xa9a03855
+0,      26536,      26536,     1472,     5888, 0x1aa0603f
+0,      28012,      28012,     1472,     5888, 0x190a25a1
+0,      29488,      29488,     1464,     5856, 0xc6ad8bc0
+0,      30956,      30956,     1472,     5888, 0x42bb9d6b
+0,      32432,      32432,     1472,     5888, 0x797694d7
+0,      33908,      33908,     1472,     5888, 0xd2d1fa69
+0,      35384,      35384,     1464,     5856, 0x61624e9b
+0,      36852,      36852,     1472,     5888, 0x14bf8ec0
diff --git a/tests/ref/fate/adpcm-afc b/tests/ref/fate/adpcm-afc
new file mode 100644
index 0000000..d1a1c36
--- /dev/null
+++ b/tests/ref/fate/adpcm-afc
@@ -0,0 +1,13 @@
+#tb 0: 1/44100
+0,          0,          0,    17920,    71680, 0x52373bc9
+0,      17920,      17920,    17920,    71680, 0x1f854b27
+0,      35840,      35840,    17920,    71680, 0x3d265a6d
+0,      53760,      53760,    17920,    71680, 0x7e38d624
+0,      71680,      71680,    17920,    71680, 0x003b7616
+0,      89600,      89600,    17920,    71680, 0x9fed7ca7
+0,     107520,     107520,    17920,    71680, 0x22af668c
+0,     125440,     125440,    17920,    71680, 0xefd95c4a
+0,     143360,     143360,    17920,    71680, 0x8b68142e
+0,     161280,     161280,    17920,    71680, 0x0a0614fa
+0,     179200,     179200,    17920,    71680, 0x22ababa3
+0,     197120,     197120,    17920,    71680, 0xda4b1708
diff --git a/tests/ref/fate/adpcm-ima-amv b/tests/ref/fate/adpcm-ima-amv
index 6c2fa32..ca7a168 100644
--- a/tests/ref/fate/adpcm-ima-amv
+++ b/tests/ref/fate/adpcm-ima-amv
@@ -3,159 +3,159 @@
 0,       1378,       1378,     1378,     2756, 0x8462443f
 0,       2756,       2756,     1378,     2756, 0x9f493ba6
 0,       4134,       4134,     1378,     2756, 0x634e5f06
-0,       5513,       5513,     1380,     2760, 0x51f35cd4
-0,       6891,       6891,     1378,     2756, 0x011c51e5
-0,       8269,       8269,     1378,     2756, 0x8c2c198c
-0,       9647,       9647,     1378,     2756, 0x2b4a3397
-0,      11025,      11025,     1378,     2756, 0x63794f22
-0,      12403,      12403,     1378,     2756, 0xfc363898
-0,      13781,      13781,     1378,     2756, 0x0da5486e
-0,      15159,      15159,     1378,     2756, 0xbae17a5f
+0,       5512,       5512,     1380,     2760, 0x51f35cd4
+0,       6892,       6892,     1378,     2756, 0x011c51e5
+0,       8270,       8270,     1378,     2756, 0x8c2c198c
+0,       9648,       9648,     1378,     2756, 0x2b4a3397
+0,      11026,      11026,     1378,     2756, 0x63794f22
+0,      12404,      12404,     1378,     2756, 0xfc363898
+0,      13782,      13782,     1378,     2756, 0x0da5486e
+0,      15160,      15160,     1378,     2756, 0xbae17a5f
 0,      16538,      16538,     1380,     2760, 0xba266e1b
-0,      17916,      17916,     1378,     2756, 0xdfb61002
-0,      19294,      19294,     1378,     2756, 0x15d029da
-0,      20672,      20672,     1378,     2756, 0x7bc82012
-0,      22050,      22050,     1378,     2756, 0x002e6999
-0,      23428,      23428,     1378,     2756, 0x96346ba6
-0,      24806,      24806,     1378,     2756, 0x3d54543b
-0,      26184,      26184,     1380,     2760, 0x601786e1
-0,      27563,      27563,     1378,     2756, 0xf22a5793
-0,      28941,      28941,     1378,     2756, 0x21f54d49
-0,      30319,      30319,     1378,     2756, 0x0c6d4399
-0,      31697,      31697,     1378,     2756, 0x17282f8e
-0,      33075,      33075,     1378,     2756, 0xeb698f75
-0,      34453,      34453,     1378,     2756, 0x935e1de2
-0,      35831,      35831,     1380,     2760, 0xb6fb4293
-0,      37209,      37209,     1378,     2756, 0x485053dc
-0,      38588,      38588,     1378,     2756, 0x24c35027
-0,      39966,      39966,     1378,     2756, 0x09f323ee
-0,      41344,      41344,     1378,     2756, 0xbc7d58d5
-0,      42722,      42722,     1378,     2756, 0xaefd487c
-0,      44100,      44100,     1378,     2756, 0xaca16cc0
-0,      45478,      45478,     1380,     2760, 0x98a76091
-0,      46856,      46856,     1378,     2756, 0x5d357141
-0,      48234,      48234,     1378,     2756, 0x65ea2657
-0,      49613,      49613,     1378,     2756, 0xb5e1334a
-0,      50991,      50991,     1378,     2756, 0x32cd5d91
-0,      52369,      52369,     1378,     2756, 0xdc23722b
-0,      53747,      53747,     1378,     2756, 0x2ba34684
-0,      55125,      55125,     1378,     2756, 0xf9755ba8
-0,      56503,      56503,     1380,     2760, 0x24221ddb
-0,      57881,      57881,     1378,     2756, 0xef843aa4
-0,      59259,      59259,     1378,     2756, 0x420442fe
-0,      60638,      60638,     1378,     2756, 0x5a0933cb
-0,      62016,      62016,     1378,     2756, 0xef5f6d61
-0,      63394,      63394,     1378,     2756, 0xe57e6dc0
-0,      64772,      64772,     1378,     2756, 0xc0f0495a
-0,      66150,      66150,     1380,     2760, 0x2c3b55df
-0,      67528,      67528,     1378,     2756, 0x39c2586c
-0,      68906,      68906,     1378,     2756, 0x7ffc46e5
-0,      70284,      70284,     1378,     2756, 0xa2766664
-0,      71663,      71663,     1378,     2756, 0xacb50c6c
-0,      73041,      73041,     1378,     2756, 0x7f659084
-0,      74419,      74419,     1378,     2756, 0xc72e6a12
-0,      75797,      75797,     1380,     2760, 0xdb6944df
-0,      77175,      77175,     1378,     2756, 0x954f45c1
-0,      78553,      78553,     1378,     2756, 0xa9484240
-0,      79931,      79931,     1378,     2756, 0x1d595349
-0,      81309,      81309,     1378,     2756, 0xcf2a565e
-0,      82688,      82688,     1378,     2756, 0x391028d5
-0,      84066,      84066,     1378,     2756, 0x348db7ad
-0,      85444,      85444,     1380,     2760, 0xb69b5e3a
-0,      86822,      86822,     1378,     2756, 0xe3635fbe
-0,      88200,      88200,     1378,     2756, 0xdcad3654
-0,      89578,      89578,     1378,     2756, 0x5c17abef
-0,      90956,      90956,     1378,     2756, 0xb3235184
-0,      92334,      92334,     1378,     2756, 0xdabb64a6
-0,      93713,      93713,     1378,     2756, 0xa95dc58d
-0,      95091,      95091,     1380,     2760, 0x8e7ac9eb
-0,      96469,      96469,     1378,     2756, 0x492b658e
-0,      97847,      97847,     1378,     2756, 0x377483ab
-0,      99225,      99225,     1378,     2756, 0x2c250279
-0,     100603,     100603,     1378,     2756, 0x704dbdb3
-0,     101981,     101981,     1378,     2756, 0x800d7da2
-0,     103359,     103359,     1378,     2756, 0x872aa32e
-0,     104738,     104738,     1378,     2756, 0x2d4837fe
-0,     106116,     106116,     1380,     2760, 0xc89ea57e
-0,     107494,     107494,     1378,     2756, 0x6447d7ef
-0,     108872,     108872,     1378,     2756, 0x144f59cc
-0,     110250,     110250,     1378,     2756, 0xc667154e
-0,     111628,     111628,     1378,     2756, 0xf0de66ae
-0,     113006,     113006,     1378,     2756, 0xeabf3c32
-0,     114384,     114384,     1378,     2756, 0xe98e81d1
-0,     115763,     115763,     1380,     2760, 0x56aa5889
-0,     117141,     117141,     1378,     2756, 0x4fd34c0e
-0,     118519,     118519,     1378,     2756, 0x67cf6912
-0,     119897,     119897,     1378,     2756, 0xfa944def
-0,     121275,     121275,     1378,     2756, 0xc12f23b2
-0,     122653,     122653,     1378,     2756, 0x5ea325a2
-0,     124031,     124031,     1378,     2756, 0x2b245824
-0,     125409,     125409,     1380,     2760, 0x90ac533e
-0,     126788,     126788,     1378,     2756, 0xcca34d26
-0,     128166,     128166,     1378,     2756, 0xb5f820d0
-0,     129544,     129544,     1378,     2756, 0x27f24335
-0,     130922,     130922,     1378,     2756, 0x4a9e87b7
-0,     132300,     132300,     1378,     2756, 0xbd076129
-0,     133678,     133678,     1378,     2756, 0x2e0e3f2e
-0,     135056,     135056,     1380,     2760, 0xdf534478
-0,     136434,     136434,     1378,     2756, 0xca000a2e
-0,     137813,     137813,     1378,     2756, 0x87472df3
-0,     139191,     139191,     1378,     2756, 0x16733810
-0,     140569,     140569,     1378,     2756, 0xfa0734b4
-0,     141947,     141947,     1378,     2756, 0x5eff3fc4
-0,     143325,     143325,     1378,     2756, 0xf35346bd
-0,     144703,     144703,     1378,     2756, 0xac6411c5
-0,     146081,     146081,     1380,     2760, 0x478c3c56
-0,     147459,     147459,     1378,     2756, 0xebd30bdd
-0,     148838,     148838,     1378,     2756, 0xaef95a31
-0,     150216,     150216,     1378,     2756, 0x8aad29d1
-0,     151594,     151594,     1378,     2756, 0x626863f0
-0,     152972,     152972,     1378,     2756, 0x68c05707
-0,     154350,     154350,     1378,     2756, 0x437c5e8d
-0,     155728,     155728,     1380,     2760, 0x8eca4bdb
-0,     157106,     157106,     1378,     2756, 0x62bd4162
-0,     158484,     158484,     1378,     2756, 0x9f744aa4
-0,     159863,     159863,     1378,     2756, 0x0f3f6409
-0,     161241,     161241,     1378,     2756, 0x3fee827a
-0,     162619,     162619,     1378,     2756, 0x48a0ac19
-0,     163997,     163997,     1378,     2756, 0x8e4ce0d0
-0,     165375,     165375,     1380,     2760, 0xcda82236
-0,     166753,     166753,     1378,     2756, 0x0e523255
-0,     168131,     168131,     1378,     2756, 0x84103d30
-0,     169509,     169509,     1378,     2756, 0x13941cde
-0,     170888,     170888,     1378,     2756, 0x9fc834c5
-0,     172266,     172266,     1378,     2756, 0xc0217a77
-0,     173644,     173644,     1378,     2756, 0x3f643659
-0,     175022,     175022,     1380,     2760, 0x9dbd6002
-0,     176400,     176400,     1378,     2756, 0x94f046fb
-0,     177778,     177778,     1378,     2756, 0xab01fb12
-0,     179156,     179156,     1378,     2756, 0x04cffe5c
-0,     180534,     180534,     1378,     2756, 0xef661c5e
-0,     181913,     181913,     1378,     2756, 0x094c5fc5
-0,     183291,     183291,     1378,     2756, 0xe0c1486a
-0,     184669,     184669,     1380,     2760, 0x8c3535b7
-0,     186047,     186047,     1378,     2756, 0x594934aa
-0,     187425,     187425,     1378,     2756, 0x74007238
-0,     188803,     188803,     1378,     2756, 0x61f1394d
-0,     190181,     190181,     1378,     2756, 0x72584f07
-0,     191559,     191559,     1378,     2756, 0xced9acf9
-0,     192938,     192938,     1378,     2756, 0x7d2e3ea1
-0,     194316,     194316,     1378,     2756, 0x56c06897
-0,     195694,     195694,     1380,     2760, 0x19983bbf
-0,     197072,     197072,     1378,     2756, 0x4f884f27
-0,     198450,     198450,     1378,     2756, 0x81ab2f63
-0,     199828,     199828,     1378,     2756, 0x448e681d
-0,     201206,     201206,     1378,     2756, 0x0ba9826e
-0,     202584,     202584,     1378,     2756, 0x049f36fa
-0,     203963,     203963,     1378,     2756, 0x096a2b62
-0,     205341,     205341,     1380,     2760, 0x579e2035
-0,     206719,     206719,     1378,     2756, 0xd13e30e1
-0,     208097,     208097,     1378,     2756, 0x30b6412b
-0,     209475,     209475,     1378,     2756, 0xbb1c3268
-0,     210853,     210853,     1378,     2756, 0xbc175b6a
-0,     212231,     212231,     1378,     2756, 0xf8d160e2
-0,     213609,     213609,     1378,     2756, 0xc1048154
-0,     214988,     214988,     1380,     2760, 0xb83548f4
-0,     216366,     216366,     1378,     2756, 0x22647962
-0,     217744,     217744,     1378,     2756, 0x14ca54d3
-0,     219122,     219122,     1378,     2756, 0x58754b3a
+0,      17918,      17918,     1378,     2756, 0xdfb61002
+0,      19296,      19296,     1378,     2756, 0x15d029da
+0,      20674,      20674,     1378,     2756, 0x7bc82012
+0,      22052,      22052,     1378,     2756, 0x002e6999
+0,      23430,      23430,     1378,     2756, 0x96346ba6
+0,      24808,      24808,     1378,     2756, 0x3d54543b
+0,      26186,      26186,     1380,     2760, 0x601786e1
+0,      27566,      27566,     1378,     2756, 0xf22a5793
+0,      28944,      28944,     1378,     2756, 0x21f54d49
+0,      30322,      30322,     1378,     2756, 0x0c6d4399
+0,      31700,      31700,     1378,     2756, 0x17282f8e
+0,      33078,      33078,     1378,     2756, 0xeb698f75
+0,      34456,      34456,     1378,     2756, 0x935e1de2
+0,      35834,      35834,     1380,     2760, 0xb6fb4293
+0,      37214,      37214,     1378,     2756, 0x485053dc
+0,      38592,      38592,     1378,     2756, 0x24c35027
+0,      39970,      39970,     1378,     2756, 0x09f323ee
+0,      41348,      41348,     1378,     2756, 0xbc7d58d5
+0,      42726,      42726,     1378,     2756, 0xaefd487c
+0,      44104,      44104,     1378,     2756, 0xaca16cc0
+0,      45482,      45482,     1380,     2760, 0x98a76091
+0,      46862,      46862,     1378,     2756, 0x5d357141
+0,      48240,      48240,     1378,     2756, 0x65ea2657
+0,      49618,      49618,     1378,     2756, 0xb5e1334a
+0,      50996,      50996,     1378,     2756, 0x32cd5d91
+0,      52374,      52374,     1378,     2756, 0xdc23722b
+0,      53752,      53752,     1378,     2756, 0x2ba34684
+0,      55130,      55130,     1378,     2756, 0xf9755ba8
+0,      56508,      56508,     1380,     2760, 0x24221ddb
+0,      57888,      57888,     1378,     2756, 0xef843aa4
+0,      59266,      59266,     1378,     2756, 0x420442fe
+0,      60644,      60644,     1378,     2756, 0x5a0933cb
+0,      62022,      62022,     1378,     2756, 0xef5f6d61
+0,      63400,      63400,     1378,     2756, 0xe57e6dc0
+0,      64778,      64778,     1378,     2756, 0xc0f0495a
+0,      66156,      66156,     1380,     2760, 0x2c3b55df
+0,      67536,      67536,     1378,     2756, 0x39c2586c
+0,      68914,      68914,     1378,     2756, 0x7ffc46e5
+0,      70292,      70292,     1378,     2756, 0xa2766664
+0,      71670,      71670,     1378,     2756, 0xacb50c6c
+0,      73048,      73048,     1378,     2756, 0x7f659084
+0,      74426,      74426,     1378,     2756, 0xc72e6a12
+0,      75804,      75804,     1380,     2760, 0xdb6944df
+0,      77184,      77184,     1378,     2756, 0x954f45c1
+0,      78562,      78562,     1378,     2756, 0xa9484240
+0,      79940,      79940,     1378,     2756, 0x1d595349
+0,      81318,      81318,     1378,     2756, 0xcf2a565e
+0,      82696,      82696,     1378,     2756, 0x391028d5
+0,      84074,      84074,     1378,     2756, 0x348db7ad
+0,      85452,      85452,     1380,     2760, 0xb69b5e3a
+0,      86832,      86832,     1378,     2756, 0xe3635fbe
+0,      88210,      88210,     1378,     2756, 0xdcad3654
+0,      89588,      89588,     1378,     2756, 0x5c17abef
+0,      90966,      90966,     1378,     2756, 0xb3235184
+0,      92344,      92344,     1378,     2756, 0xdabb64a6
+0,      93722,      93722,     1378,     2756, 0xa95dc58d
+0,      95100,      95100,     1380,     2760, 0x8e7ac9eb
+0,      96480,      96480,     1378,     2756, 0x492b658e
+0,      97858,      97858,     1378,     2756, 0x377483ab
+0,      99236,      99236,     1378,     2756, 0x2c250279
+0,     100614,     100614,     1378,     2756, 0x704dbdb3
+0,     101992,     101992,     1378,     2756, 0x800d7da2
+0,     103370,     103370,     1378,     2756, 0x872aa32e
+0,     104748,     104748,     1378,     2756, 0x2d4837fe
+0,     106126,     106126,     1380,     2760, 0xc89ea57e
+0,     107506,     107506,     1378,     2756, 0x6447d7ef
+0,     108884,     108884,     1378,     2756, 0x144f59cc
+0,     110262,     110262,     1378,     2756, 0xc667154e
+0,     111640,     111640,     1378,     2756, 0xf0de66ae
+0,     113018,     113018,     1378,     2756, 0xeabf3c32
+0,     114396,     114396,     1378,     2756, 0xe98e81d1
+0,     115774,     115774,     1380,     2760, 0x56aa5889
+0,     117154,     117154,     1378,     2756, 0x4fd34c0e
+0,     118532,     118532,     1378,     2756, 0x67cf6912
+0,     119910,     119910,     1378,     2756, 0xfa944def
+0,     121288,     121288,     1378,     2756, 0xc12f23b2
+0,     122666,     122666,     1378,     2756, 0x5ea325a2
+0,     124044,     124044,     1378,     2756, 0x2b245824
+0,     125422,     125422,     1380,     2760, 0x90ac533e
+0,     126802,     126802,     1378,     2756, 0xcca34d26
+0,     128180,     128180,     1378,     2756, 0xb5f820d0
+0,     129558,     129558,     1378,     2756, 0x27f24335
+0,     130936,     130936,     1378,     2756, 0x4a9e87b7
+0,     132314,     132314,     1378,     2756, 0xbd076129
+0,     133692,     133692,     1378,     2756, 0x2e0e3f2e
+0,     135070,     135070,     1380,     2760, 0xdf534478
+0,     136450,     136450,     1378,     2756, 0xca000a2e
+0,     137828,     137828,     1378,     2756, 0x87472df3
+0,     139206,     139206,     1378,     2756, 0x16733810
+0,     140584,     140584,     1378,     2756, 0xfa0734b4
+0,     141962,     141962,     1378,     2756, 0x5eff3fc4
+0,     143340,     143340,     1378,     2756, 0xf35346bd
+0,     144718,     144718,     1378,     2756, 0xac6411c5
+0,     146096,     146096,     1380,     2760, 0x478c3c56
+0,     147476,     147476,     1378,     2756, 0xebd30bdd
+0,     148854,     148854,     1378,     2756, 0xaef95a31
+0,     150232,     150232,     1378,     2756, 0x8aad29d1
+0,     151610,     151610,     1378,     2756, 0x626863f0
+0,     152988,     152988,     1378,     2756, 0x68c05707
+0,     154366,     154366,     1378,     2756, 0x437c5e8d
+0,     155744,     155744,     1380,     2760, 0x8eca4bdb
+0,     157124,     157124,     1378,     2756, 0x62bd4162
+0,     158502,     158502,     1378,     2756, 0x9f744aa4
+0,     159880,     159880,     1378,     2756, 0x0f3f6409
+0,     161258,     161258,     1378,     2756, 0x3fee827a
+0,     162636,     162636,     1378,     2756, 0x48a0ac19
+0,     164014,     164014,     1378,     2756, 0x8e4ce0d0
+0,     165392,     165392,     1380,     2760, 0xcda82236
+0,     166772,     166772,     1378,     2756, 0x0e523255
+0,     168150,     168150,     1378,     2756, 0x84103d30
+0,     169528,     169528,     1378,     2756, 0x13941cde
+0,     170906,     170906,     1378,     2756, 0x9fc834c5
+0,     172284,     172284,     1378,     2756, 0xc0217a77
+0,     173662,     173662,     1378,     2756, 0x3f643659
+0,     175040,     175040,     1380,     2760, 0x9dbd6002
+0,     176420,     176420,     1378,     2756, 0x94f046fb
+0,     177798,     177798,     1378,     2756, 0xab01fb12
+0,     179176,     179176,     1378,     2756, 0x04cffe5c
+0,     180554,     180554,     1378,     2756, 0xef661c5e
+0,     181932,     181932,     1378,     2756, 0x094c5fc5
+0,     183310,     183310,     1378,     2756, 0xe0c1486a
+0,     184688,     184688,     1380,     2760, 0x8c3535b7
+0,     186068,     186068,     1378,     2756, 0x594934aa
+0,     187446,     187446,     1378,     2756, 0x74007238
+0,     188824,     188824,     1378,     2756, 0x61f1394d
+0,     190202,     190202,     1378,     2756, 0x72584f07
+0,     191580,     191580,     1378,     2756, 0xced9acf9
+0,     192958,     192958,     1378,     2756, 0x7d2e3ea1
+0,     194336,     194336,     1378,     2756, 0x56c06897
+0,     195714,     195714,     1380,     2760, 0x19983bbf
+0,     197094,     197094,     1378,     2756, 0x4f884f27
+0,     198472,     198472,     1378,     2756, 0x81ab2f63
+0,     199850,     199850,     1378,     2756, 0x448e681d
+0,     201228,     201228,     1378,     2756, 0x0ba9826e
+0,     202606,     202606,     1378,     2756, 0x049f36fa
+0,     203984,     203984,     1378,     2756, 0x096a2b62
+0,     205362,     205362,     1380,     2760, 0x579e2035
+0,     206742,     206742,     1378,     2756, 0xd13e30e1
+0,     208120,     208120,     1378,     2756, 0x30b6412b
+0,     209498,     209498,     1378,     2756, 0xbb1c3268
+0,     210876,     210876,     1378,     2756, 0xbc175b6a
+0,     212254,     212254,     1378,     2756, 0xf8d160e2
+0,     213632,     213632,     1378,     2756, 0xc1048154
+0,     215010,     215010,     1380,     2760, 0xb83548f4
+0,     216390,     216390,     1378,     2756, 0x22647962
+0,     217768,     217768,     1378,     2756, 0x14ca54d3
+0,     219146,     219146,     1378,     2756, 0x58754b3a
diff --git a/tests/ref/fate/adpcm-ima-oki b/tests/ref/fate/adpcm-ima-oki
new file mode 100644
index 0000000..c6f1ee1
--- /dev/null
+++ b/tests/ref/fate/adpcm-ima-oki
@@ -0,0 +1 @@
+641049800e735b62e975baacc9a011a4
diff --git a/tests/ref/fate/adpcm-ima-smjpeg b/tests/ref/fate/adpcm-ima-smjpeg
index 45cb97b..3a746b6 100644
--- a/tests/ref/fate/adpcm-ima-smjpeg
+++ b/tests/ref/fate/adpcm-ima-smjpeg
@@ -1,351 +1,351 @@
 #tb 0: 1/22050
 0,          0,          0,      512,     1024, 0x00000000
-0,        507,        507,      512,     1024, 0x00000000
-0,       1014,       1014,      512,     1024, 0xd89a448e
-0,       1521,       1521,      512,     1024, 0x695b369c
-0,       2029,       2029,      512,     1024, 0xc8ba5707
-0,       2558,       2558,      512,     1024, 0xdf241fc6
-0,       3065,       3065,      512,     1024, 0x61cf4166
-0,       3572,       3572,      512,     1024, 0x97cbc386
-0,       4079,       4079,      512,     1024, 0x44899d04
-0,       4586,       4586,      512,     1024, 0xa7cbaa62
-0,       5116,       5116,      512,     1024, 0xa7aea60c
-0,       5623,       5623,      512,     1024, 0xd7b18a89
-0,       6130,       6130,      512,     1024, 0x268e81f6
-0,       6637,       6637,      512,     1024, 0x9cf83a2f
-0,       7166,       7166,      512,     1024, 0x5559b508
-0,       7673,       7673,      512,     1024, 0xe1b9e71c
-0,       8181,       8181,      512,     1024, 0xdcee733e
-0,       8688,       8688,      512,     1024, 0xe5918f60
-0,       9195,       9195,      512,     1024, 0x29dbd209
-0,       9724,       9724,      512,     1024, 0x9bcbcf16
-0,      10231,      10231,      512,     1024, 0x86f5f458
-0,      10738,      10738,      512,     1024, 0xabcbda86
-0,      11246,      11246,      512,     1024, 0xc51f77b9
-0,      11775,      11775,      512,     1024, 0xf6b3a504
-0,      12282,      12282,      512,     1024, 0x1af3e40e
-0,      12789,      12789,      512,     1024, 0x3866b03b
-0,      13296,      13296,      512,     1024, 0xbc005403
-0,      13803,      13803,      512,     1024, 0xe9dfcc51
-0,      14333,      14333,      512,     1024, 0x83c837cb
-0,      14840,      14840,      512,     1024, 0xfa649580
-0,      15347,      15347,      512,     1024, 0x519452ea
-0,      15854,      15854,      512,     1024, 0xd4978774
-0,      16383,      16383,      512,     1024, 0xe2a3b1cd
-0,      16890,      16890,      512,     1024, 0x9a9472ad
-0,      17397,      17397,      512,     1024, 0xa12d4060
-0,      17905,      17905,      512,     1024, 0x31fb0646
-0,      18412,      18412,      512,     1024, 0xfc44343f
-0,      18941,      18941,      512,     1024, 0x0847751a
-0,      19448,      19448,      512,     1024, 0x227968a2
-0,      19955,      19955,      512,     1024, 0x7cce9f1c
-0,      20462,      20462,      512,     1024, 0xb8356713
-0,      20992,      20992,      512,     1024, 0xb29f6e6f
-0,      21499,      21499,      512,     1024, 0x9e1430ab
-0,      22006,      22006,      512,     1024, 0x26d85423
-0,      22513,      22513,      512,     1024, 0x6496547d
-0,      23020,      23020,      512,     1024, 0x316b1a86
-0,      23549,      23549,      512,     1024, 0x3cd83afc
-0,      24057,      24057,      512,     1024, 0x993ff633
-0,      24564,      24564,      512,     1024, 0x0708d1a2
-0,      25071,      25071,      512,     1024, 0xd7230db9
-0,      25578,      25578,      512,     1024, 0xbb0779ca
-0,      26107,      26107,      512,     1024, 0xc6094e1b
-0,      26614,      26614,      512,     1024, 0x15a8b039
-0,      27122,      27122,      512,     1024, 0xd6dbe88c
-0,      27629,      27629,      512,     1024, 0x7e8d1140
-0,      28158,      28158,      512,     1024, 0xef88e525
-0,      28665,      28665,      512,     1024, 0x44e21149
-0,      29172,      29172,      512,     1024, 0x65b0f5f4
-0,      29679,      29679,      512,     1024, 0xb955f687
-0,      30186,      30186,      512,     1024, 0xc85fba9c
-0,      30716,      30716,      512,     1024, 0xf59655ad
-0,      31223,      31223,      512,     1024, 0x6de80bf1
-0,      31730,      31730,      512,     1024, 0x2dcf6e41
-0,      32237,      32237,      512,     1024, 0xd0ddcf8a
-0,      32766,      32766,      512,     1024, 0x00135c2d
-0,      33273,      33273,      512,     1024, 0x697f8efd
-0,      33781,      33781,      512,     1024, 0x7a9bada5
-0,      34288,      34288,      512,     1024, 0x0d22783c
-0,      34795,      34795,      512,     1024, 0x7726d07d
-0,      35324,      35324,      512,     1024, 0xa2f14f67
-0,      35831,      35831,      512,     1024, 0x7f51060d
-0,      36338,      36338,      512,     1024, 0xc4ec6aea
-0,      36846,      36846,      512,     1024, 0x9bb37ca4
-0,      37375,      37375,      512,     1024, 0x9b085577
-0,      37882,      37882,      512,     1024, 0x8812f8af
-0,      38389,      38389,      512,     1024, 0x788f5221
-0,      38896,      38896,      512,     1024, 0x3a2ce642
-0,      39403,      39403,      512,     1024, 0x72415692
-0,      39933,      39933,      512,     1024, 0xe3dcc105
-0,      40440,      40440,      512,     1024, 0xb26c0599
-0,      40947,      40947,      512,     1024, 0x5c9e55eb
-0,      41454,      41454,      512,     1024, 0x8fe88707
-0,      41983,      41983,      512,     1024, 0xc5d7beb6
-0,      42490,      42490,      512,     1024, 0xe1d3a3b4
-0,      42998,      42998,      512,     1024, 0x012da0c6
-0,      43505,      43505,      512,     1024, 0x8d010922
-0,      44012,      44012,      512,     1024, 0x3366eb0d
-0,      44541,      44541,      512,     1024, 0xc9381a27
-0,      45048,      45048,      512,     1024, 0x0774f685
-0,      45555,      45555,      512,     1024, 0xc5cae0a5
-0,      46062,      46062,      512,     1024, 0xa6f4737c
-0,      46592,      46592,      512,     1024, 0x8fb6d0d1
-0,      47099,      47099,      512,     1024, 0x05f579c2
-0,      47606,      47606,      512,     1024, 0x56905d99
-0,      48113,      48113,      512,     1024, 0x002ee18d
-0,      48620,      48620,      512,     1024, 0xeb37ef51
-0,      49149,      49149,      512,     1024, 0x38025635
-0,      49657,      49657,      512,     1024, 0x4fe643c8
-0,      50164,      50164,      512,     1024, 0x11d66ab1
-0,      50671,      50671,      512,     1024, 0xcc3051e9
-0,      51178,      51178,      512,     1024, 0xcd93e854
-0,      51707,      51707,      512,     1024, 0x38f1196d
-0,      52214,      52214,      512,     1024, 0x657a15fc
-0,      52722,      52722,      512,     1024, 0x669ce2a9
-0,      53229,      53229,      512,     1024, 0x95862dda
-0,      53758,      53758,      512,     1024, 0x1726a7b2
-0,      54265,      54265,      512,     1024, 0xd6ece2a1
-0,      54772,      54772,      512,     1024, 0x33ab9553
-0,      55279,      55279,      512,     1024, 0xd50c73a6
-0,      55787,      55787,      512,     1024, 0xfe25b63a
-0,      56316,      56316,      512,     1024, 0x7e2959e3
-0,      56823,      56823,      512,     1024, 0xa4c07b34
-0,      57330,      57330,      512,     1024, 0xd6d8f15c
-0,      57837,      57837,      512,     1024, 0x1eccddd7
-0,      58366,      58366,      512,     1024, 0x2b69f9cb
-0,      58874,      58874,      512,     1024, 0x667b775f
-0,      59381,      59381,      512,     1024, 0xad3b84e9
-0,      59888,      59888,      512,     1024, 0x4f29fc67
-0,      60395,      60395,      512,     1024, 0x8d611ab7
-0,      60924,      60924,      512,     1024, 0x278966ea
-0,      61431,      61431,      512,     1024, 0xaf33812b
-0,      61938,      61938,      512,     1024, 0xa55f4265
-0,      62446,      62446,      512,     1024, 0x023cb51c
-0,      62975,      62975,      512,     1024, 0x1d1f1005
-0,      63482,      63482,      512,     1024, 0x874cccf7
-0,      63989,      63989,      512,     1024, 0xda705428
-0,      64496,      64496,      512,     1024, 0x48d9b440
-0,      65003,      65003,      512,     1024, 0xa14e0712
-0,      65533,      65533,      512,     1024, 0x7efbad1f
-0,      66040,      66040,      512,     1024, 0xdb82c17f
-0,      66547,      66547,      512,     1024, 0xcbe87613
-0,      67054,      67054,      512,     1024, 0x3a63df1d
-0,      67583,      67583,      512,     1024, 0xd5636bba
-0,      68090,      68090,      512,     1024, 0x9397af23
-0,      68598,      68598,      512,     1024, 0x32a07c98
-0,      69105,      69105,      512,     1024, 0x202ca667
-0,      69612,      69612,      512,     1024, 0xdf969011
-0,      70141,      70141,      512,     1024, 0xc434d238
-0,      70648,      70648,      512,     1024, 0xe9ad7562
-0,      71155,      71155,      512,     1024, 0xb51b6b50
-0,      71663,      71663,      512,     1024, 0xe70aecd3
-0,      72192,      72192,      512,     1024, 0x03c816b2
-0,      72699,      72699,      512,     1024, 0x869fdf25
-0,      73206,      73206,      512,     1024, 0xd40a0a62
-0,      73713,      73713,      512,     1024, 0x5af7dd35
-0,      74220,      74220,      512,     1024, 0x891ffc72
-0,      74750,      74750,      512,     1024, 0x1ff68a08
-0,      75257,      75257,      512,     1024, 0x5a7517a9
-0,      75764,      75764,      512,     1024, 0x0f959f74
-0,      76271,      76271,      512,     1024, 0xe92a12a2
-0,      76778,      76778,      512,     1024, 0x38000e55
-0,      77307,      77307,      512,     1024, 0x39fbdd70
-0,      77814,      77814,      512,     1024, 0xca3d9184
-0,      78322,      78322,      512,     1024, 0x66c8995b
-0,      78829,      78829,      512,     1024, 0xac25acea
-0,      79358,      79358,      512,     1024, 0x3cd1046c
-0,      79865,      79865,      512,     1024, 0x6a1df31c
-0,      80372,      80372,      512,     1024, 0x21ca10a1
-0,      80879,      80879,      512,     1024, 0x1aeccedc
-0,      81387,      81387,      512,     1024, 0xddea1335
-0,      81916,      81916,      512,     1024, 0x19f5ca9f
-0,      82423,      82423,      512,     1024, 0x88e95e43
-0,      82930,      82930,      512,     1024, 0x726284fe
-0,      83437,      83437,      512,     1024, 0x6b85b40e
-0,      83966,      83966,      512,     1024, 0x111fee2a
-0,      84474,      84474,      512,     1024, 0x3656b588
-0,      84981,      84981,      512,     1024, 0xa5a2b552
-0,      85488,      85488,      512,     1024, 0x38fb2467
-0,      85995,      85995,      512,     1024, 0xaa919ccc
-0,      86524,      86524,      512,     1024, 0x15993dbc
-0,      87031,      87031,      512,     1024, 0xbe01a7b9
-0,      87539,      87539,      512,     1024, 0xefe93c09
-0,      88046,      88046,      512,     1024, 0x1bb566e5
-0,      88575,      88575,      512,     1024, 0x15ce6237
-0,      89082,      89082,      512,     1024, 0xa8552e66
-0,      89589,      89589,      512,     1024, 0x9d80187e
-0,      90096,      90096,      512,     1024, 0x5df3fc30
-0,      90603,      90603,      512,     1024, 0x1a312aa5
-0,      91133,      91133,      512,     1024, 0x6bb8e302
-0,      91640,      91640,      512,     1024, 0xbd9684bb
-0,      92147,      92147,      512,     1024, 0x78b0b166
-0,      92654,      92654,      512,     1024, 0xd9af5eae
-0,      93183,      93183,      512,     1024, 0xdb90fe82
-0,      93690,      93690,      512,     1024, 0x327614e9
-0,      94198,      94198,      512,     1024, 0x1f19b7fe
-0,      94705,      94705,      512,     1024, 0x46c53f96
-0,      95212,      95212,      512,     1024, 0x921b2189
-0,      95741,      95741,      512,     1024, 0xa8fbc85a
-0,      96248,      96248,      512,     1024, 0xabfdaaae
-0,      96755,      96755,      512,     1024, 0x6acc7387
-0,      97263,      97263,      512,     1024, 0x0d9c27b5
-0,      97792,      97792,      512,     1024, 0xba4dd809
-0,      98299,      98299,      512,     1024, 0x2a2ad521
-0,      98806,      98806,      512,     1024, 0x892de38a
-0,      99313,      99313,      512,     1024, 0xdc97a2eb
-0,      99820,      99820,      512,     1024, 0x4f614ca4
-0,     100350,     100350,      512,     1024, 0x9c8a77ea
-0,     100857,     100857,      512,     1024, 0x2d30e646
-0,     101364,     101364,      512,     1024, 0x74e800a7
-0,     101871,     101871,      512,     1024, 0x1e01fb02
-0,     102378,     102378,      512,     1024, 0x4ed2c1d8
-0,     102907,     102907,      512,     1024, 0xf2fdbe63
-0,     103415,     103415,      512,     1024, 0x8d6f63a1
-0,     103922,     103922,      512,     1024, 0xded468d9
-0,     104429,     104429,      512,     1024, 0xccad839e
-0,     104958,     104958,      512,     1024, 0xdde7c082
-0,     105465,     105465,      512,     1024, 0x548613c5
-0,     105972,     105972,      512,     1024, 0x383909bd
-0,     106479,     106479,      512,     1024, 0xfd37627b
-0,     106987,     106987,      512,     1024, 0x6d95a481
-0,     107516,     107516,      512,     1024, 0x56aa87fa
-0,     108023,     108023,      512,     1024, 0x7b67258c
-0,     108530,     108530,      512,     1024, 0x7dd99a92
-0,     109037,     109037,      512,     1024, 0x4a66d102
-0,     109566,     109566,      512,     1024, 0x7b3fce51
-0,     110074,     110074,      512,     1024, 0xbbd968aa
-0,     110581,     110581,      512,     1024, 0x8283ec36
-0,     111088,     111088,      512,     1024, 0x3c96493d
-0,     111595,     111595,      512,     1024, 0xfa4f8cf8
-0,     112124,     112124,      512,     1024, 0xe2cf872d
-0,     112631,     112631,      512,     1024, 0x0a9e7aa6
-0,     113139,     113139,      512,     1024, 0x6e7a0550
-0,     113646,     113646,      512,     1024, 0x3acfea2f
-0,     114175,     114175,      512,     1024, 0x7111d0fa
-0,     114682,     114682,      512,     1024, 0xe9a1eca9
-0,     115189,     115189,      512,     1024, 0x24da6c46
-0,     115696,     115696,      512,     1024, 0x117cff37
-0,     116204,     116204,      512,     1024, 0x0f27cab6
-0,     116733,     116733,      512,     1024, 0x69b6b4e6
-0,     117240,     117240,      512,     1024, 0x1e6cc841
-0,     117747,     117747,      512,     1024, 0xb01e2365
-0,     118254,     118254,      512,     1024, 0x14e200d3
-0,     118783,     118783,      512,     1024, 0xd1184c98
-0,     119291,     119291,      512,     1024, 0xef9140e9
-0,     119798,     119798,      512,     1024, 0x4cbb645e
-0,     120305,     120305,      512,     1024, 0xe7fe2f06
-0,     120812,     120812,      512,     1024, 0xf8c45028
-0,     121341,     121341,      512,     1024, 0x561358f4
-0,     121848,     121848,      512,     1024, 0xd0129b77
-0,     122355,     122355,      512,     1024, 0xcc636e88
-0,     122863,     122863,      512,     1024, 0xe9406321
-0,     123392,     123392,      512,     1024, 0x9f16a041
-0,     123899,     123899,      512,     1024, 0x468bf409
-0,     124406,     124406,      512,     1024, 0x3df70f7b
-0,     124913,     124913,      512,     1024, 0xa880b11b
-0,     125420,     125420,      512,     1024, 0x3286c489
-0,     125950,     125950,      512,     1024, 0x39fe9ebc
-0,     126457,     126457,      512,     1024, 0xc533d83b
-0,     126964,     126964,      512,     1024, 0x153b195d
-0,     127471,     127471,      512,     1024, 0xd84786a1
-0,     127978,     127978,      512,     1024, 0xdc295aaa
-0,     128507,     128507,      512,     1024, 0xfb764d8c
-0,     129015,     129015,      512,     1024, 0xeebc9db9
-0,     129522,     129522,      512,     1024, 0x7ba9403e
-0,     130029,     130029,      512,     1024, 0x4e5571ec
-0,     130558,     130558,      512,     1024, 0xd965fad4
-0,     131065,     131065,      512,     1024, 0x87e259f2
-0,     131572,     131572,      512,     1024, 0xae7e533b
-0,     132080,     132080,      512,     1024, 0x313cf4d6
-0,     132587,     132587,      512,     1024, 0xe1844c90
-0,     133116,     133116,      512,     1024, 0xbb057b44
-0,     133623,     133623,      512,     1024, 0xa5099687
-0,     134130,     134130,      512,     1024, 0xbff10707
-0,     134637,     134637,      512,     1024, 0x37c4ffc0
-0,     135167,     135167,      512,     1024, 0xf9fb6caa
-0,     135674,     135674,      512,     1024, 0x3b6a3a1f
-0,     136181,     136181,      512,     1024, 0x83431edb
-0,     136688,     136688,      512,     1024, 0x1eb713cf
-0,     137195,     137195,      512,     1024, 0xd7b07a6d
-0,     137724,     137724,      512,     1024, 0x81ae3391
-0,     138231,     138231,      512,     1024, 0xf150130a
-0,     138739,     138739,      512,     1024, 0x09678eaa
-0,     139246,     139246,      512,     1024, 0xb94e06f1
-0,     139775,     139775,      512,     1024, 0x67b1dbc9
-0,     140282,     140282,      512,     1024, 0xd6edc235
-0,     140789,     140789,      512,     1024, 0x34e4c499
-0,     141296,     141296,      512,     1024, 0xeefd89c0
-0,     141804,     141804,      512,     1024, 0x38afdaf1
-0,     142333,     142333,      512,     1024, 0x29a60d76
-0,     142840,     142840,      512,     1024, 0xe28a4372
-0,     143347,     143347,      512,     1024, 0x7089454d
-0,     143854,     143854,      512,     1024, 0x0c01bb7b
-0,     144383,     144383,      512,     1024, 0xbd776a72
-0,     144891,     144891,      512,     1024, 0x86776fd0
-0,     145398,     145398,      512,     1024, 0xb37c88f7
-0,     145905,     145905,      512,     1024, 0x5f90aaf8
-0,     146412,     146412,      512,     1024, 0x203d4222
-0,     146941,     146941,      512,     1024, 0x382692a6
-0,     147448,     147448,      512,     1024, 0xf37c95fd
-0,     147956,     147956,      512,     1024, 0x6c0b8877
-0,     148463,     148463,      512,     1024, 0x2e54a8b6
-0,     148992,     148992,      512,     1024, 0x7f266488
-0,     149499,     149499,      512,     1024, 0xfbf20f9a
-0,     150006,     150006,      512,     1024, 0xf2985cc0
-0,     150513,     150513,      512,     1024, 0xc7075340
-0,     151020,     151020,      512,     1024, 0xe4585695
-0,     151550,     151550,      512,     1024, 0xbdffa380
-0,     152057,     152057,      512,     1024, 0x2422a8a9
-0,     152564,     152564,      512,     1024, 0x59cbd75f
-0,     153071,     153071,      512,     1024, 0x04ad1a8c
-0,     153578,     153578,      512,     1024, 0x33c09191
-0,     154107,     154107,      512,     1024, 0x55efa6fd
-0,     154615,     154615,      512,     1024, 0xf73d0e5d
-0,     155122,     155122,      512,     1024, 0x6141ebae
-0,     155629,     155629,      512,     1024, 0x7db17a68
-0,     156158,     156158,      512,     1024, 0xa6c690b6
-0,     156665,     156665,      512,     1024, 0xa6fd6725
-0,     157172,     157172,      512,     1024, 0x50a90b9b
-0,     157680,     157680,      512,     1024, 0xef990dc8
-0,     158187,     158187,      512,     1024, 0x75adf6b5
-0,     158716,     158716,      512,     1024, 0x61eac43e
-0,     159223,     159223,      512,     1024, 0x67797a19
-0,     159730,     159730,      512,     1024, 0xf325277a
-0,     160237,     160237,      512,     1024, 0x18bf254a
-0,     160767,     160767,      512,     1024, 0x2ce6bee3
-0,     161274,     161274,      512,     1024, 0x8d320860
-0,     161781,     161781,      512,     1024, 0xc979b6e8
-0,     162288,     162288,      512,     1024, 0xdb644b41
-0,     162795,     162795,      512,     1024, 0xe1b368ba
-0,     163324,     163324,      512,     1024, 0xacc53d15
-0,     163832,     163832,      512,     1024, 0x42ea8c18
-0,     164339,     164339,      512,     1024, 0xe52c99a4
-0,     164846,     164846,      512,     1024, 0xd7db54a6
-0,     165375,     165375,      512,     1024, 0x7f27a7e3
-0,     165882,     165882,      512,     1024, 0xf7ffeaa9
-0,     166389,     166389,      512,     1024, 0x792b6088
-0,     166896,     166896,      512,     1024, 0x61d99724
-0,     167404,     167404,      512,     1024, 0x5213720e
-0,     167933,     167933,      512,     1024, 0xac09dd30
-0,     168440,     168440,      512,     1024, 0x960bf6bb
-0,     168947,     168947,      512,     1024, 0xc90168e1
-0,     169454,     169454,      512,     1024, 0x43b45768
-0,     169983,     169983,      512,     1024, 0x935d60a1
-0,     170491,     170491,      512,     1024, 0x9a342ef2
-0,     170998,     170998,      512,     1024, 0xc894709f
-0,     171505,     171505,      512,     1024, 0x59b43b07
-0,     172012,     172012,      512,     1024, 0x36a1a98d
-0,     172541,     172541,      512,     1024, 0x9e1a121c
-0,     173048,     173048,      512,     1024, 0x02208b78
-0,     173556,     173556,      512,     1024, 0xd1d7b274
-0,     174063,     174063,      512,     1024, 0xdacd5096
-0,     174592,     174592,      512,     1024, 0x51b71ead
-0,     175099,     175099,      512,     1024, 0xd009a7ca
-0,     175606,     175606,      512,     1024, 0xb6d5a938
-0,     176113,     176113,      512,     1024, 0xf3d45e47
-0,     176621,     176621,      512,     1024, 0xea8e04fc
-0,     177150,     177150,      512,     1024, 0x0b928bd8
-0,     177657,     177657,      512,     1024, 0x0f02caec
-0,     178164,     178164,      512,     1024, 0xe2b137a8
-0,     178671,     178671,      512,     1024, 0xd5f94892
+0,        512,        512,      512,     1024, 0x00000000
+0,       1024,       1024,      512,     1024, 0xed2d3f6b
+0,       1533,       1533,      512,     1024, 0x51f6ccb3
+0,       2040,       2040,      512,     1024, 0x58bd75aa
+0,       2552,       2552,      512,     1024, 0xd857a310
+0,       3064,       3064,      512,     1024, 0xc483a5b8
+0,       3576,       3576,      512,     1024, 0x923ecf67
+0,       4088,       4088,      512,     1024, 0xf87dcd53
+0,       4598,       4598,      512,     1024, 0xdc32c002
+0,       5110,       5110,      512,     1024, 0xb760def1
+0,       5622,       5622,      512,     1024, 0x6838d2b2
+0,       6134,       6134,      512,     1024, 0xe45aca1e
+0,       6646,       6646,      512,     1024, 0xde1fb955
+0,       7158,       7158,      512,     1024, 0x9e23b949
+0,       7670,       7670,      512,     1024, 0x840cc000
+0,       8182,       8182,      512,     1024, 0x0a29cbfa
+0,       8694,       8694,      512,     1024, 0x9871d4c4
+0,       9206,       9206,      512,     1024, 0xb35dc9f2
+0,       9718,       9718,      512,     1024, 0xf37fda0a
+0,      10230,      10230,      512,     1024, 0xa640f990
+0,      10742,      10742,      512,     1024, 0x516fe6f5
+0,      11254,      11254,      512,     1024, 0xc78bc6a6
+0,      11766,      11766,      512,     1024, 0x700fd6ee
+0,      12278,      12278,      512,     1024, 0x5383d5ad
+0,      12790,      12790,      512,     1024, 0xbe01d091
+0,      13302,      13302,      512,     1024, 0x72dfcfc7
+0,      13814,      13814,      512,     1024, 0xd8fecea9
+0,      14326,      14326,      512,     1024, 0xa464d79b
+0,      14838,      14838,      512,     1024, 0xf394e2cb
+0,      15350,      15350,      512,     1024, 0xa301ec49
+0,      15862,      15862,      512,     1024, 0x5e09d60f
+0,      16374,      16374,      512,     1024, 0xd13edd6f
+0,      16886,      16886,      512,     1024, 0x7423ef39
+0,      17398,      17398,      512,     1024, 0x96e2f083
+0,      17910,      17910,      512,     1024, 0x5ed7dbee
+0,      18422,      18422,      512,     1024, 0x3874f714
+0,      18934,      18934,      512,     1024, 0xa5e6edab
+0,      19446,      19446,      512,     1024, 0x0a04ee3a
+0,      19958,      19958,      512,     1024, 0xadfee6b9
+0,      20470,      20470,      512,     1024, 0xd0bbe6d2
+0,      20982,      20982,      512,     1024, 0x223eebb7
+0,      21494,      21494,      512,     1024, 0x0473e479
+0,      22006,      22006,      512,     1024, 0xdf15e51e
+0,      22518,      22518,      512,     1024, 0xa954e483
+0,      23030,      23030,      512,     1024, 0x6df3ed03
+0,      23542,      23542,      512,     1024, 0x0860e544
+0,      24054,      24054,      512,     1024, 0xc241e8dc
+0,      24566,      24566,      512,     1024, 0xd0e1d6a4
+0,      25078,      25078,      512,     1024, 0xcb2ff988
+0,      25590,      25590,      512,     1024, 0x51fae08e
+0,      26102,      26102,      512,     1024, 0xae39f2fc
+0,      26614,      26614,      512,     1024, 0xfd74f07c
+0,      27126,      27126,      512,     1024, 0x1936edc1
+0,      27638,      27638,      512,     1024, 0x95f8deae
+0,      28150,      28150,      512,     1024, 0x93bdf605
+0,      28662,      28662,      512,     1024, 0x7a07dd32
+0,      29174,      29174,      512,     1024, 0x6889fdc1
+0,      29686,      29686,      512,     1024, 0x989bf024
+0,      30198,      30198,      512,     1024, 0xc764ce80
+0,      30710,      30710,      512,     1024, 0x0e62d721
+0,      31222,      31222,      512,     1024, 0x59c2fbe3
+0,      31734,      31734,      512,     1024, 0xf14ee29d
+0,      32246,      32246,      512,     1024, 0x02a0f21b
+0,      32758,      32758,      512,     1024, 0xadb3d361
+0,      33270,      33270,      512,     1024, 0xdcb3d1fc
+0,      33782,      33782,      512,     1024, 0x2924f9dc
+0,      34294,      34294,      512,     1024, 0x7507ebec
+0,      34806,      34806,      512,     1024, 0xe009f343
+0,      35318,      35318,      512,     1024, 0x21e9e7ac
+0,      35830,      35830,      512,     1024, 0x845bda9e
+0,      36342,      36342,      512,     1024, 0xb1b3e632
+0,      36854,      36854,      512,     1024, 0x61ccf593
+0,      37366,      37366,      512,     1024, 0x8cdbf603
+0,      37878,      37878,      512,     1024, 0xf8f7e673
+0,      38390,      38390,      512,     1024, 0x55efdd24
+0,      38902,      38902,      512,     1024, 0x4059e8ff
+0,      39414,      39414,      512,     1024, 0xb3afe5be
+0,      39926,      39926,      512,     1024, 0x7236e965
+0,      40438,      40438,      512,     1024, 0xe683db69
+0,      40950,      40950,      512,     1024, 0x29e3d93c
+0,      41462,      41462,      512,     1024, 0x74f2f27f
+0,      41974,      41974,      512,     1024, 0x32cde3ba
+0,      42486,      42486,      512,     1024, 0xe907f171
+0,      42998,      42998,      512,     1024, 0x206ae2a5
+0,      43510,      43510,      512,     1024, 0x6379efa1
+0,      44022,      44022,      512,     1024, 0x0f0fee85
+0,      44534,      44534,      512,     1024, 0x3195e314
+0,      45046,      45046,      512,     1024, 0x4646ead3
+0,      45558,      45558,      512,     1024, 0x5635dcf5
+0,      46070,      46070,      512,     1024, 0xd76fc780
+0,      46582,      46582,      512,     1024, 0x847ff8a5
+0,      47094,      47094,      512,     1024, 0xaca8eda3
+0,      47606,      47606,      512,     1024, 0x9a2de1ea
+0,      48118,      48118,      512,     1024, 0xc92ff23a
+0,      48630,      48630,      512,     1024, 0x0e0ef038
+0,      49142,      49142,      512,     1024, 0xc32cf495
+0,      49654,      49654,      512,     1024, 0x6ab1ec79
+0,      50166,      50166,      512,     1024, 0xe43cd8d6
+0,      50678,      50678,      512,     1024, 0x4ba2deab
+0,      51190,      51190,      512,     1024, 0x6d16ea0e
+0,      51702,      51702,      512,     1024, 0xe5b0ee70
+0,      52214,      52214,      512,     1024, 0xcf6cf074
+0,      52726,      52726,      512,     1024, 0x2206e61d
+0,      53238,      53238,      512,     1024, 0xfbb9e7e7
+0,      53750,      53750,      512,     1024, 0x2bc1e115
+0,      54262,      54262,      512,     1024, 0x4ca6e5c5
+0,      54774,      54774,      512,     1024, 0x061cead0
+0,      55286,      55286,      512,     1024, 0x3dc9f950
+0,      55798,      55798,      512,     1024, 0x9399f10d
+0,      56310,      56310,      512,     1024, 0xa2bff5ae
+0,      56822,      56822,      512,     1024, 0xd21de569
+0,      57334,      57334,      512,     1024, 0x1c45e3be
+0,      57846,      57846,      512,     1024, 0xff5dff1c
+0,      58358,      58358,      512,     1024, 0x992df5d3
+0,      58870,      58870,      512,     1024, 0xafedea2f
+0,      59382,      59382,      512,     1024, 0x6e73d6a8
+0,      59894,      59894,      512,     1024, 0x72dff283
+0,      60406,      60406,      512,     1024, 0x50b5f1a6
+0,      60918,      60918,      512,     1024, 0xffe1decb
+0,      61430,      61430,      512,     1024, 0x8993ecff
+0,      61942,      61942,      512,     1024, 0x954bd63a
+0,      62454,      62454,      512,     1024, 0x4707f577
+0,      62966,      62966,      512,     1024, 0x7a88f81f
+0,      63478,      63478,      512,     1024, 0xc771f537
+0,      63990,      63990,      512,     1024, 0x7aade6af
+0,      64502,      64502,      512,     1024, 0x8af5ede5
+0,      65014,      65014,      512,     1024, 0x7500f3f1
+0,      65526,      65526,      512,     1024, 0xea36f707
+0,      66038,      66038,      512,     1024, 0x1a26e39a
+0,      66550,      66550,      512,     1024, 0xa04cf00d
+0,      67062,      67062,      512,     1024, 0xc362f182
+0,      67574,      67574,      512,     1024, 0x79c8f82c
+0,      68086,      68086,      512,     1024, 0x6480eee1
+0,      68598,      68598,      512,     1024, 0x7152eaa0
+0,      69110,      69110,      512,     1024, 0x5dfee6a9
+0,      69622,      69622,      512,     1024, 0x0afae660
+0,      70134,      70134,      512,     1024, 0xdc98e9fc
+0,      70646,      70646,      512,     1024, 0x10b7da06
+0,      71158,      71158,      512,     1024, 0x0571e585
+0,      71670,      71670,      512,     1024, 0x18ddf45e
+0,      72182,      72182,      512,     1024, 0x2cbef242
+0,      72694,      72694,      512,     1024, 0xf5380845
+0,      73206,      73206,      512,     1024, 0x34fff45e
+0,      73718,      73718,      512,     1024, 0x6f97e490
+0,      74230,      74230,      512,     1024, 0x77d6f0db
+0,      74742,      74742,      512,     1024, 0xa25ce2db
+0,      75254,      75254,      512,     1024, 0x8260e4e9
+0,      75766,      75766,      512,     1024, 0xc3b2f7d2
+0,      76278,      76278,      512,     1024, 0x82a7edae
+0,      76790,      76790,      512,     1024, 0x7d08dd54
+0,      77302,      77302,      512,     1024, 0x9059eda6
+0,      77814,      77814,      512,     1024, 0xbebaec88
+0,      78326,      78326,      512,     1024, 0xd9afd586
+0,      78838,      78838,      512,     1024, 0x0ca3e622
+0,      79350,      79350,      512,     1024, 0x4123e9e6
+0,      79862,      79862,      512,     1024, 0x2ff9f95c
+0,      80374,      80374,      512,     1024, 0x8522e261
+0,      80886,      80886,      512,     1024, 0xe4f8f499
+0,      81398,      81398,      512,     1024, 0x34f3f2bd
+0,      81910,      81910,      512,     1024, 0x82efe863
+0,      82422,      82422,      512,     1024, 0x9966fcea
+0,      82934,      82934,      512,     1024, 0xe94de3fd
+0,      83446,      83446,      512,     1024, 0x1ce0e27b
+0,      83958,      83958,      512,     1024, 0xd718dcde
+0,      84470,      84470,      512,     1024, 0xd503e724
+0,      84982,      84982,      512,     1024, 0x427ee3b2
+0,      85494,      85494,      512,     1024, 0x4512dcc4
+0,      86006,      86006,      512,     1024, 0xcf31e77c
+0,      86518,      86518,      512,     1024, 0xeb41ea81
+0,      87030,      87030,      512,     1024, 0xfa43e67c
+0,      87542,      87542,      512,     1024, 0x8162f3c9
+0,      88054,      88054,      512,     1024, 0x1b55f6b0
+0,      88566,      88566,      512,     1024, 0x3ebeec44
+0,      89078,      89078,      512,     1024, 0x740fe0c4
+0,      89590,      89590,      512,     1024, 0x8fb4e8b2
+0,      90102,      90102,      512,     1024, 0xe49de6a2
+0,      90614,      90614,      512,     1024, 0xd64febdf
+0,      91126,      91126,      512,     1024, 0x0e74ee08
+0,      91638,      91638,      512,     1024, 0x6c0ddf07
+0,      92150,      92150,      512,     1024, 0x7fb8e3c9
+0,      92662,      92662,      512,     1024, 0x52bfe96c
+0,      93174,      93174,      512,     1024, 0xfc22ee64
+0,      93686,      93686,      512,     1024, 0xe20ae718
+0,      94198,      94198,      512,     1024, 0xa94be395
+0,      94710,      94710,      512,     1024, 0xded306d0
+0,      95222,      95222,      512,     1024, 0x31f7c831
+0,      95734,      95734,      512,     1024, 0x0ffde0a8
+0,      96246,      96246,      512,     1024, 0xc692e3e0
+0,      96758,      96758,      512,     1024, 0x1d8ff7c7
+0,      97270,      97270,      512,     1024, 0x038ee172
+0,      97782,      97782,      512,     1024, 0x9a1eef59
+0,      98294,      98294,      512,     1024, 0x158fe750
+0,      98806,      98806,      512,     1024, 0xac15e42c
+0,      99318,      99318,      512,     1024, 0x6323ed44
+0,      99830,      99830,      512,     1024, 0xd10ce4bb
+0,     100342,     100342,      512,     1024, 0xc1cce296
+0,     100854,     100854,      512,     1024, 0x0782f094
+0,     101366,     101366,      512,     1024, 0xd109de36
+0,     101878,     101878,      512,     1024, 0x175600fb
+0,     102390,     102390,      512,     1024, 0x95d5e8d9
+0,     102902,     102902,      512,     1024, 0xebb6eee1
+0,     103414,     103414,      512,     1024, 0x187cfadc
+0,     103926,     103926,      512,     1024, 0xce35fa5c
+0,     104438,     104438,      512,     1024, 0x8327eea2
+0,     104950,     104950,      512,     1024, 0x5543f219
+0,     105462,     105462,      512,     1024, 0xaacbe0dc
+0,     105974,     105974,      512,     1024, 0xa538e9fb
+0,     106486,     106486,      512,     1024, 0x4dcbe655
+0,     106998,     106998,      512,     1024, 0x86b6d93b
+0,     107510,     107510,      512,     1024, 0x1a06f878
+0,     108022,     108022,      512,     1024, 0xd926e8ef
+0,     108534,     108534,      512,     1024, 0xc624db2f
+0,     109046,     109046,      512,     1024, 0x2153e20d
+0,     109558,     109558,      512,     1024, 0x01dce868
+0,     110070,     110070,      512,     1024, 0xfa5fd3cd
+0,     110582,     110582,      512,     1024, 0x2adef2d5
+0,     111094,     111094,      512,     1024, 0x4f48f8e2
+0,     111606,     111606,      512,     1024, 0x613feeee
+0,     112118,     112118,      512,     1024, 0x3780de8a
+0,     112630,     112630,      512,     1024, 0x2093eb65
+0,     113142,     113142,      512,     1024, 0x54baebbb
+0,     113654,     113654,      512,     1024, 0x8686dd7c
+0,     114166,     114166,      512,     1024, 0x7f8ae80c
+0,     114678,     114678,      512,     1024, 0x7aede972
+0,     115190,     115190,      512,     1024, 0x971bebc0
+0,     115702,     115702,      512,     1024, 0x2dd5fd4b
+0,     116214,     116214,      512,     1024, 0xb1b3e4a3
+0,     116726,     116726,      512,     1024, 0x192defc6
+0,     117238,     117238,      512,     1024, 0x5e46ec44
+0,     117750,     117750,      512,     1024, 0xe6d8e05a
+0,     118262,     118262,      512,     1024, 0x7e2fe2b0
+0,     118774,     118774,      512,     1024, 0x9e3bdf80
+0,     119286,     119286,      512,     1024, 0xa98cd85e
+0,     119798,     119798,      512,     1024, 0x6061e0c4
+0,     120310,     120310,      512,     1024, 0x6112f3fc
+0,     120822,     120822,      512,     1024, 0x99bdfb01
+0,     121334,     121334,      512,     1024, 0x3f5df3ca
+0,     121846,     121846,      512,     1024, 0xf5ebeb05
+0,     122358,     122358,      512,     1024, 0x8498e565
+0,     122870,     122870,      512,     1024, 0x0497f0b7
+0,     123382,     123382,      512,     1024, 0x626ae800
+0,     123894,     123894,      512,     1024, 0xfb71eec4
+0,     124406,     124406,      512,     1024, 0xa86ee739
+0,     124918,     124918,      512,     1024, 0x25c0e050
+0,     125430,     125430,      512,     1024, 0x6027e91e
+0,     125942,     125942,      512,     1024, 0x6772df6e
+0,     126454,     126454,      512,     1024, 0xfefff844
+0,     126966,     126966,      512,     1024, 0x547be862
+0,     127478,     127478,      512,     1024, 0xca84e795
+0,     127990,     127990,      512,     1024, 0xd124db3e
+0,     128502,     128502,      512,     1024, 0xcaf3deb5
+0,     129014,     129014,      512,     1024, 0x487ce92d
+0,     129526,     129526,      512,     1024, 0x117feb95
+0,     130038,     130038,      512,     1024, 0x7b63de3d
+0,     130550,     130550,      512,     1024, 0xa529d8e1
+0,     131062,     131062,      512,     1024, 0x56f6da26
+0,     131574,     131574,      512,     1024, 0xffb8d5af
+0,     132086,     132086,      512,     1024, 0xeecbdc04
+0,     132598,     132598,      512,     1024, 0xfc59d2d2
+0,     133110,     133110,      512,     1024, 0xaf7acef7
+0,     133622,     133622,      512,     1024, 0x3f9bf258
+0,     134134,     134134,      512,     1024, 0xcf54e9d6
+0,     134646,     134646,      512,     1024, 0x680cd0aa
+0,     135158,     135158,      512,     1024, 0x3c1bdc1f
+0,     135670,     135670,      512,     1024, 0x8c8ffe22
+0,     136182,     136182,      512,     1024, 0xf415d362
+0,     136694,     136694,      512,     1024, 0x8c8cdaa9
+0,     137206,     137206,      512,     1024, 0x9531e9f1
+0,     137718,     137718,      512,     1024, 0x223ce536
+0,     138230,     138230,      512,     1024, 0xdfbce5f9
+0,     138742,     138742,      512,     1024, 0x20b6ed7d
+0,     139254,     139254,      512,     1024, 0x1a17e109
+0,     139766,     139766,      512,     1024, 0xc672eaea
+0,     140278,     140278,      512,     1024, 0x12a7dc5e
+0,     140790,     140790,      512,     1024, 0x4497f342
+0,     141302,     141302,      512,     1024, 0xdfb5db4b
+0,     141814,     141814,      512,     1024, 0xde48ef6c
+0,     142326,     142326,      512,     1024, 0x1d98e316
+0,     142838,     142838,      512,     1024, 0xbd2ad72f
+0,     143350,     143350,      512,     1024, 0xf1aad776
+0,     143862,     143862,      512,     1024, 0x4db3e3c0
+0,     144374,     144374,      512,     1024, 0x832de0a0
+0,     144886,     144886,      512,     1024, 0xc5f0ef25
+0,     145398,     145398,      512,     1024, 0x419bda6e
+0,     145910,     145910,      512,     1024, 0x5de7f77e
+0,     146422,     146422,      512,     1024, 0x0063ec9a
+0,     146934,     146934,      512,     1024, 0x10c3d470
+0,     147446,     147446,      512,     1024, 0xba66d226
+0,     147958,     147958,      512,     1024, 0xea47ded3
+0,     148470,     148470,      512,     1024, 0x6202d67b
+0,     148982,     148982,      512,     1024, 0x3f80e7cf
+0,     149494,     149494,      512,     1024, 0x4e64eaae
+0,     150006,     150006,      512,     1024, 0x2108e83d
+0,     150518,     150518,      512,     1024, 0x38c3dec1
+0,     151030,     151030,      512,     1024, 0x46d3f77a
+0,     151542,     151542,      512,     1024, 0x4838e787
+0,     152054,     152054,      512,     1024, 0xc71df16d
+0,     152566,     152566,      512,     1024, 0xdbe4ebbd
+0,     153078,     153078,      512,     1024, 0xa156d07b
+0,     153590,     153590,      512,     1024, 0x34eddc80
+0,     154102,     154102,      512,     1024, 0xe840e87c
+0,     154614,     154614,      512,     1024, 0x6accf8f5
+0,     155126,     155126,      512,     1024, 0xa1dbebb9
+0,     155638,     155638,      512,     1024, 0x6d07d98c
+0,     156150,     156150,      512,     1024, 0x94c7e805
+0,     156662,     156662,      512,     1024, 0x5199e586
+0,     157174,     157174,      512,     1024, 0xe797e1aa
+0,     157686,     157686,      512,     1024, 0xff19eda7
+0,     158198,     158198,      512,     1024, 0x9cb9d040
+0,     158710,     158710,      512,     1024, 0xaeedd325
+0,     159222,     159222,      512,     1024, 0xf5ade306
+0,     159734,     159734,      512,     1024, 0x54a5e129
+0,     160246,     160246,      512,     1024, 0x6665ddeb
+0,     160758,     160758,      512,     1024, 0x9d18e033
+0,     161270,     161270,      512,     1024, 0x7f23df74
+0,     161782,     161782,      512,     1024, 0x7c34f158
+0,     162294,     162294,      512,     1024, 0x47f6dae2
+0,     162806,     162806,      512,     1024, 0x5ffdd903
+0,     163318,     163318,      512,     1024, 0x8233d108
+0,     163830,     163830,      512,     1024, 0x45c6e20d
+0,     164342,     164342,      512,     1024, 0xae11fa6e
+0,     164854,     164854,      512,     1024, 0xa30defd2
+0,     165366,     165366,      512,     1024, 0xfc1ecccf
+0,     165878,     165878,      512,     1024, 0x920edc94
+0,     166390,     166390,      512,     1024, 0xd7f3dc58
+0,     166902,     166902,      512,     1024, 0x4972d37d
+0,     167414,     167414,      512,     1024, 0xfefef358
+0,     167926,     167926,      512,     1024, 0x3648e473
+0,     168438,     168438,      512,     1024, 0x58dee6c3
+0,     168950,     168950,      512,     1024, 0x9cc6df27
+0,     169462,     169462,      512,     1024, 0x6adfe99c
+0,     169974,     169974,      512,     1024, 0x6a56e11f
+0,     170486,     170486,      512,     1024, 0x4860edf1
+0,     170998,     170998,      512,     1024, 0x9132f10a
+0,     171510,     171510,      512,     1024, 0x3e09d209
+0,     172022,     172022,      512,     1024, 0x4b6bf4d8
+0,     172534,     172534,      512,     1024, 0x0cd5e838
+0,     173046,     173046,      512,     1024, 0x080be078
+0,     173558,     173558,      512,     1024, 0xfdb0e31c
+0,     174070,     174070,      512,     1024, 0xced5e7bd
+0,     174582,     174582,      512,     1024, 0x65b3e435
+0,     175094,     175094,      512,     1024, 0x5b5bfe2e
+0,     175606,     175606,      512,     1024, 0xa8bde3cb
+0,     176118,     176118,      512,     1024, 0xfd0fdefa
+0,     176630,     176630,      512,     1024, 0xbec4ef95
+0,     177142,     177142,      512,     1024, 0x683ad8dd
+0,     177654,     177654,      512,     1024, 0x8eefeb77
+0,     178166,     178166,      512,     1024, 0x84fc5878
+0,     178678,     178678,      512,     1024, 0x9a0ded60
diff --git a/tests/ref/fate/ast b/tests/ref/fate/ast
new file mode 100644
index 0000000..5b89c2b
--- /dev/null
+++ b/tests/ref/fate/ast
@@ -0,0 +1 @@
+CRC=0x87713611
diff --git a/tests/ref/fate/avstring b/tests/ref/fate/avstring
new file mode 100644
index 0000000..bc231e8
--- /dev/null
+++ b/tests/ref/fate/avstring
@@ -0,0 +1,27 @@
+Testing av_get_token()
+|''| -> || + ||
+|| -> || + ||
+|:| -> || + |:|
+|\| -> |\| + ||
+|'| -> || + ||
+|    ''    :| -> || + |:|
+|    ''  ''  :| -> |  | + |:|
+|foo   '' :| -> |foo   | + |:|
+|'foo'| -> |foo| + ||
+|foo     | -> |foo| + ||
+|  '  foo  '  | -> |  foo  | + ||
+|foo\| -> |foo\| + ||
+|foo':  blah:blah| -> |foo:  blah:blah| + ||
+|foo\:  blah:blah| -> |foo:  blah| + |:blah|
+|foo'| -> |foo| + ||
+|'foo :  '  :blahblah| -> |foo :  | + |:blahblah|
+|\ :blah| -> | | + |:blah|
+|     foo| -> |foo| + ||
+|      foo       | -> |foo| + ||
+|      foo     \ | -> |foo      | + ||
+|foo ':blah| -> |foo :blah| + ||
+| foo   bar    :   blahblah| -> |foo   bar| + |:   blahblah|
+|\f\o\o| -> |foo| + ||
+|'foo : \ \  '   : blahblah| -> |foo : \ \  | + |: blahblah|
+|'\fo\o:': blahblah| -> |\fo\o:| + |: blahblah|
+|\'fo\o\:':  foo  '  :blahblah| -> |'foo::  foo  | + |:blahblah|
diff --git a/tests/ref/fate/bink-video-b b/tests/ref/fate/bink-video-b
new file mode 100644
index 0000000..c772eda
--- /dev/null
+++ b/tests/ref/fate/bink-video-b
@@ -0,0 +1,31 @@
+#tb 0: 1/15
+0,          0,          0,        1,    34800, 0x4fd0a8e4
+0,          1,          1,        1,    34800, 0xd381a7b7
+0,          2,          2,        1,    34800, 0x688ca315
+0,          3,          3,        1,    34800, 0xaae39c3f
+0,          4,          4,        1,    34800, 0xdcb19759
+0,          5,          5,        1,    34800, 0xd458970a
+0,          6,          6,        1,    34800, 0x99269865
+0,          7,          7,        1,    34800, 0x6d459bbc
+0,          8,          8,        1,    34800, 0x6c759cd2
+0,          9,          9,        1,    34800, 0x47459ad5
+0,         10,         10,        1,    34800, 0xe6e897b9
+0,         11,         11,        1,    34800, 0x63599374
+0,         12,         12,        1,    34800, 0x666191e2
+0,         13,         13,        1,    34800, 0x4ca8933e
+0,         14,         14,        1,    34800, 0xbea594f4
+0,         15,         15,        1,    34800, 0xa5609473
+0,         16,         16,        1,    34800, 0xe5d79234
+0,         17,         17,        1,    34800, 0xf7738e58
+0,         18,         18,        1,    34800, 0x9d0c8b24
+0,         19,         19,        1,    34800, 0x0b2d8a66
+0,         20,         20,        1,    34800, 0xf4698b72
+0,         21,         21,        1,    34800, 0xdf808d44
+0,         22,         22,        1,    34800, 0xae6b895e
+0,         23,         23,        1,    34800, 0xa67b8144
+0,         24,         24,        1,    34800, 0xc54d79c4
+0,         25,         25,        1,    34800, 0x75ca72e2
+0,         26,         26,        1,    34800, 0xc6a56f65
+0,         27,         27,        1,    34800, 0x406e740d
+0,         28,         28,        1,    34800, 0xd29478de
+0,         29,         29,        1,    34800, 0x22cf7dc2
diff --git a/tests/ref/fate/bink-video b/tests/ref/fate/bink-video-f
similarity index 100%
rename from tests/ref/fate/bink-video
rename to tests/ref/fate/bink-video-f
diff --git a/tests/ref/fate/bink-video-i b/tests/ref/fate/bink-video-i
new file mode 100644
index 0000000..32c5e10
--- /dev/null
+++ b/tests/ref/fate/bink-video-i
@@ -0,0 +1,32 @@
+#tb 0: 1/30
+0,          0,          0,        1,   460800, 0xaef133d9
+0,          1,          1,        1,   460800, 0x2da1248b
+0,          2,          2,        1,   460800, 0x3d7945b4
+0,          3,          3,        1,   460800, 0x44554f62
+0,          4,          4,        1,   460800, 0x1bc0007e
+0,          5,          5,        1,   460800, 0xe9b5c4fa
+0,          6,          6,        1,   460800, 0x41b17af0
+0,          7,          7,        1,   460800, 0x88f5d31c
+0,          8,          8,        1,   460800, 0xdedb6e2d
+0,          9,          9,        1,   460800, 0xd36f0a5e
+0,         10,         10,        1,   460800, 0xb564921c
+0,         11,         11,        1,   460800, 0xd72b1208
+0,         12,         12,        1,   460800, 0x5c87760e
+0,         13,         13,        1,   460800, 0xecb75843
+0,         14,         14,        1,   460800, 0x58deee70
+0,         15,         15,        1,   460800, 0x64b5ae3e
+0,         16,         16,        1,   460800, 0x9269e9e6
+0,         17,         17,        1,   460800, 0x47064d62
+0,         18,         18,        1,   460800, 0x88858604
+0,         19,         19,        1,   460800, 0x129d8834
+0,         20,         20,        1,   460800, 0x046ecae5
+0,         21,         21,        1,   460800, 0x6c74c134
+0,         22,         22,        1,   460800, 0x37d56c01
+0,         23,         23,        1,   460800, 0x4c0a4f15
+0,         24,         24,        1,   460800, 0xe28ef96b
+0,         25,         25,        1,   460800, 0x66c72383
+0,         26,         26,        1,   460800, 0x9487175b
+0,         27,         27,        1,   460800, 0x71034965
+0,         28,         28,        1,   460800, 0x0f99ca96
+0,         29,         29,        1,   460800, 0x8a8c79b2
+0,         30,         30,        1,   460800, 0x34d4926e
diff --git a/tests/ref/fate/bprint b/tests/ref/fate/bprint
index e027fa1..b33c1ae 100644
--- a/tests/ref/fate/bprint
+++ b/tests/ref/fate/bprint
@@ -12,3 +12,5 @@
 Long text in automatic buffer: 1000/2834
 Long text count only buffer: 0/2834
 Long text count only buffer: 255/2834
+strftime full: 255/10 "2000-12-20"
+strftime truncated: 255/10 "2000-12"
diff --git a/tests/ref/fate/d-cinema-demux b/tests/ref/fate/d-cinema-demux
index f663040..2f28e46 100644
--- a/tests/ref/fate/d-cinema-demux
+++ b/tests/ref/fate/d-cinema-demux
@@ -2,4 +2,4 @@
 0,          0,          0,     1875,    36000, 0xd592781d
 0,       1875,       1875,     1875,    36000, 0xd592781d
 0,       3750,       3750,     1875,    36000, 0xd592781d
-0,       5625,       5625,     1200,    23056, 0xde81f0d6
+0,       5625,       5625,     1200,    23056, 0xde81f0d6, F=0x3
diff --git a/tests/ref/fate/eval b/tests/ref/fate/eval
index d58cc80..73a45d1 100644
--- a/tests/ref/fate/eval
+++ b/tests/ref/fate/eval
@@ -217,5 +217,20 @@
 Evaluating 'root(sin(ld(0))+6+sin(ld(0)/12)-log(ld(0)), 100)'
 'root(sin(ld(0))+6+sin(ld(0)/12)-log(ld(0)), 100)' -> 60.965601
 
+Evaluating '7000000B*random(0)'
+'7000000B*random(0)' -> 0.003078
+
+Evaluating 'squish(2)'
+'squish(2)' -> 0.000335
+
+Evaluating 'gauss(0.1)'
+'gauss(0.1)' -> 0.396953
+
+Evaluating 'hypot(4,3)'
+'hypot(4,3)' -> 5.000000
+
+Evaluating 'gcd(30,55)*min(9,1)'
+'gcd(30,55)*min(9,1)' -> 5.000000
+
 12.700000 == 12.7
 0.931323 == 0.931322575
diff --git a/tests/ref/fate/ffprobe_compact b/tests/ref/fate/ffprobe_compact
index 5abc91b..69ba660 100644
--- a/tests/ref/fate/ffprobe_compact
+++ b/tests/ref/fate/ffprobe_compact
@@ -1,32 +1,32 @@
-packet|codec_type=audio|stream_index=0|pts=0|pts_time=0.000000|dts=0|dts_time=0.000000|duration=1024|duration_time=0.023220|convergence_duration=N/A|convergence_duration_time=N/A|size=2048|pos=403|flags=K
-frame|media_type=audio|key_frame=1|pkt_pts=0|pkt_pts_time=0.000000|pkt_dts=0|pkt_dts_time=0.000000|pkt_duration=1024|pkt_duration_time=0.023220|pkt_pos=403|sample_fmt=s16|nb_samples=1024|channels=1|channel_layout=unknown
-packet|codec_type=video|stream_index=1|pts=0|pts_time=0.000000|dts=0|dts_time=0.000000|duration=1|duration_time=0.040000|convergence_duration=N/A|convergence_duration_time=N/A|size=230400|pos=2478|flags=K
-frame|media_type=video|key_frame=1|pkt_pts=0|pkt_pts_time=0.000000|pkt_dts=0|pkt_dts_time=0.000000|pkt_duration=1|pkt_duration_time=0.040000|pkt_pos=2478|width=320|height=240|pix_fmt=rgb24|sample_aspect_ratio=1:1|pict_type=I|coded_picture_number=0|display_picture_number=0|interlaced_frame=0|top_field_first=0|repeat_pict=0|reference=0
-packet|codec_type=video|stream_index=2|pts=0|pts_time=0.000000|dts=0|dts_time=0.000000|duration=1|duration_time=0.040000|convergence_duration=N/A|convergence_duration_time=N/A|size=30000|pos=232899|flags=K
-frame|media_type=video|key_frame=1|pkt_pts=0|pkt_pts_time=0.000000|pkt_dts=0|pkt_dts_time=0.000000|pkt_duration=1|pkt_duration_time=0.040000|pkt_pos=232899|width=100|height=100|pix_fmt=rgb24|sample_aspect_ratio=1:1|pict_type=I|coded_picture_number=0|display_picture_number=0|interlaced_frame=0|top_field_first=0|repeat_pict=0|reference=0
-packet|codec_type=audio|stream_index=0|pts=1024|pts_time=0.023220|dts=1024|dts_time=0.023220|duration=1024|duration_time=0.023220|convergence_duration=N/A|convergence_duration_time=N/A|size=2048|pos=262904|flags=K
-frame|media_type=audio|key_frame=1|pkt_pts=1024|pkt_pts_time=0.023220|pkt_dts=1024|pkt_dts_time=0.023220|pkt_duration=1024|pkt_duration_time=0.023220|pkt_pos=262904|sample_fmt=s16|nb_samples=1024|channels=1|channel_layout=unknown
-packet|codec_type=video|stream_index=1|pts=1|pts_time=0.040000|dts=1|dts_time=0.040000|duration=1|duration_time=0.040000|convergence_duration=N/A|convergence_duration_time=N/A|size=230400|pos=264980|flags=K
-frame|media_type=video|key_frame=1|pkt_pts=1|pkt_pts_time=0.040000|pkt_dts=1|pkt_dts_time=0.040000|pkt_duration=1|pkt_duration_time=0.040000|pkt_pos=264980|width=320|height=240|pix_fmt=rgb24|sample_aspect_ratio=1:1|pict_type=I|coded_picture_number=0|display_picture_number=0|interlaced_frame=0|top_field_first=0|repeat_pict=0|reference=0
-packet|codec_type=video|stream_index=2|pts=1|pts_time=0.040000|dts=1|dts_time=0.040000|duration=1|duration_time=0.040000|convergence_duration=N/A|convergence_duration_time=N/A|size=30000|pos=495402|flags=K
-frame|media_type=video|key_frame=1|pkt_pts=1|pkt_pts_time=0.040000|pkt_dts=1|pkt_dts_time=0.040000|pkt_duration=1|pkt_duration_time=0.040000|pkt_pos=495402|width=100|height=100|pix_fmt=rgb24|sample_aspect_ratio=1:1|pict_type=I|coded_picture_number=0|display_picture_number=0|interlaced_frame=0|top_field_first=0|repeat_pict=0|reference=0
-packet|codec_type=audio|stream_index=0|pts=2048|pts_time=0.046440|dts=2048|dts_time=0.046440|duration=1024|duration_time=0.023220|convergence_duration=N/A|convergence_duration_time=N/A|size=2048|pos=525407|flags=K
-frame|media_type=audio|key_frame=1|pkt_pts=2048|pkt_pts_time=0.046440|pkt_dts=2048|pkt_dts_time=0.046440|pkt_duration=1024|pkt_duration_time=0.023220|pkt_pos=525407|sample_fmt=s16|nb_samples=1024|channels=1|channel_layout=unknown
-packet|codec_type=audio|stream_index=0|pts=3072|pts_time=0.069660|dts=3072|dts_time=0.069660|duration=1024|duration_time=0.023220|convergence_duration=N/A|convergence_duration_time=N/A|size=2048|pos=527478|flags=K
-frame|media_type=audio|key_frame=1|pkt_pts=3072|pkt_pts_time=0.069660|pkt_dts=3072|pkt_dts_time=0.069660|pkt_duration=1024|pkt_duration_time=0.023220|pkt_pos=527478|sample_fmt=s16|nb_samples=1024|channels=1|channel_layout=unknown
-packet|codec_type=video|stream_index=1|pts=2|pts_time=0.080000|dts=2|dts_time=0.080000|duration=1|duration_time=0.040000|convergence_duration=N/A|convergence_duration_time=N/A|size=230400|pos=529554|flags=K
-frame|media_type=video|key_frame=1|pkt_pts=2|pkt_pts_time=0.080000|pkt_dts=2|pkt_dts_time=0.080000|pkt_duration=1|pkt_duration_time=0.040000|pkt_pos=529554|width=320|height=240|pix_fmt=rgb24|sample_aspect_ratio=1:1|pict_type=I|coded_picture_number=0|display_picture_number=0|interlaced_frame=0|top_field_first=0|repeat_pict=0|reference=0
-packet|codec_type=video|stream_index=2|pts=2|pts_time=0.080000|dts=2|dts_time=0.080000|duration=1|duration_time=0.040000|convergence_duration=N/A|convergence_duration_time=N/A|size=30000|pos=759976|flags=K
-frame|media_type=video|key_frame=1|pkt_pts=2|pkt_pts_time=0.080000|pkt_dts=2|pkt_dts_time=0.080000|pkt_duration=1|pkt_duration_time=0.040000|pkt_pos=759976|width=100|height=100|pix_fmt=rgb24|sample_aspect_ratio=1:1|pict_type=I|coded_picture_number=0|display_picture_number=0|interlaced_frame=0|top_field_first=0|repeat_pict=0|reference=0
-packet|codec_type=audio|stream_index=0|pts=4096|pts_time=0.092880|dts=4096|dts_time=0.092880|duration=1024|duration_time=0.023220|convergence_duration=N/A|convergence_duration_time=N/A|size=2048|pos=789981|flags=K
-frame|media_type=audio|key_frame=1|pkt_pts=4096|pkt_pts_time=0.092880|pkt_dts=4096|pkt_dts_time=0.092880|pkt_duration=1024|pkt_duration_time=0.023220|pkt_pos=789981|sample_fmt=s16|nb_samples=1024|channels=1|channel_layout=unknown
-packet|codec_type=audio|stream_index=0|pts=5120|pts_time=0.116100|dts=5120|dts_time=0.116100|duration=1024|duration_time=0.023220|convergence_duration=N/A|convergence_duration_time=N/A|size=2048|pos=792052|flags=K
-frame|media_type=audio|key_frame=1|pkt_pts=5120|pkt_pts_time=0.116100|pkt_dts=5120|pkt_dts_time=0.116100|pkt_duration=1024|pkt_duration_time=0.023220|pkt_pos=792052|sample_fmt=s16|nb_samples=1024|channels=1|channel_layout=unknown
-packet|codec_type=video|stream_index=1|pts=3|pts_time=0.120000|dts=3|dts_time=0.120000|duration=1|duration_time=0.040000|convergence_duration=N/A|convergence_duration_time=N/A|size=230400|pos=794128|flags=K
-frame|media_type=video|key_frame=1|pkt_pts=3|pkt_pts_time=0.120000|pkt_dts=3|pkt_dts_time=0.120000|pkt_duration=1|pkt_duration_time=0.040000|pkt_pos=794128|width=320|height=240|pix_fmt=rgb24|sample_aspect_ratio=1:1|pict_type=I|coded_picture_number=0|display_picture_number=0|interlaced_frame=0|top_field_first=0|repeat_pict=0|reference=0
-packet|codec_type=video|stream_index=2|pts=3|pts_time=0.120000|dts=3|dts_time=0.120000|duration=1|duration_time=0.040000|convergence_duration=N/A|convergence_duration_time=N/A|size=30000|pos=1024550|flags=K
-frame|media_type=video|key_frame=1|pkt_pts=3|pkt_pts_time=0.120000|pkt_dts=3|pkt_dts_time=0.120000|pkt_duration=1|pkt_duration_time=0.040000|pkt_pos=1024550|width=100|height=100|pix_fmt=rgb24|sample_aspect_ratio=1:1|pict_type=I|coded_picture_number=0|display_picture_number=0|interlaced_frame=0|top_field_first=0|repeat_pict=0|reference=0
-stream|index=0|codec_name=pcm_s16le|profile=unknown|codec_type=audio|codec_time_base=1/44100|codec_tag_string=[1][0][0][0]|codec_tag=0x0001|sample_fmt=s16|sample_rate=44100|channels=1|bits_per_sample=16|id=N/A|r_frame_rate=0/0|avg_frame_rate=0/0|time_base=1/44100|start_pts=0|start_time=0.000000|duration_ts=527313|duration=11.957211|bit_rate=705600|nb_frames=N/A|nb_read_frames=6|nb_read_packets=6|disposition:default=0|disposition:dub=0|disposition:original=0|disposition:comment=0|disposition:lyrics=0|disposition:karaoke=0|disposition:forced=0|disposition:hearing_impaired=0|disposition:visual_impaired=0|disposition:clean_effects=0|disposition:attached_pic=0
-stream|index=1|codec_name=rawvideo|profile=unknown|codec_type=video|codec_time_base=1/25|codec_tag_string=RGB[24]|codec_tag=0x18424752|width=320|height=240|has_b_frames=0|sample_aspect_ratio=1:1|display_aspect_ratio=4:3|pix_fmt=rgb24|level=-99|timecode=N/A|id=N/A|r_frame_rate=25/1|avg_frame_rate=0/0|time_base=1/25|start_pts=0|start_time=0.000000|duration_ts=299|duration=11.960000|bit_rate=N/A|nb_frames=N/A|nb_read_frames=4|nb_read_packets=4|disposition:default=0|disposition:dub=0|disposition:original=0|disposition:comment=0|disposition:lyrics=0|disposition:karaoke=0|disposition:forced=0|disposition:hearing_impaired=0|disposition:visual_impaired=0|disposition:clean_effects=0|disposition:attached_pic=0
-stream|index=2|codec_name=rawvideo|profile=unknown|codec_type=video|codec_time_base=1/25|codec_tag_string=RGB[24]|codec_tag=0x18424752|width=100|height=100|has_b_frames=0|sample_aspect_ratio=1:1|display_aspect_ratio=1:1|pix_fmt=rgb24|level=-99|timecode=N/A|id=N/A|r_frame_rate=25/1|avg_frame_rate=0/0|time_base=1/25|start_pts=0|start_time=0.000000|duration_ts=299|duration=11.960000|bit_rate=N/A|nb_frames=N/A|nb_read_frames=4|nb_read_packets=4|disposition:default=0|disposition:dub=0|disposition:original=0|disposition:comment=0|disposition:lyrics=0|disposition:karaoke=0|disposition:forced=0|disposition:hearing_impaired=0|disposition:visual_impaired=0|disposition:clean_effects=0|disposition:attached_pic=0
-format|filename=tests/data/ffprobe-test.nut|nb_streams=3|format_name=nut|start_time=0.000000|duration=11.960000|size=1054625|bit_rate=705434|tag:title=ffprobe test file|tag:comment='A comment with CSV, XML & JSON special chars': <tag value="x">|tag:comment2=I ♥ Üñîçød€
+packet|codec_type=audio|stream_index=0|pts=0|pts_time=0.000000|dts=0|dts_time=0.000000|duration=1024|duration_time=0.023220|convergence_duration=N/A|convergence_duration_time=N/A|size=2048|pos=572|flags=K
+frame|media_type=audio|key_frame=1|pkt_pts=0|pkt_pts_time=0.000000|pkt_dts=0|pkt_dts_time=0.000000|pkt_duration=1024|pkt_duration_time=0.023220|pkt_pos=572|sample_fmt=s16|nb_samples=1024|channels=1|channel_layout=unknown
+packet|codec_type=video|stream_index=1|pts=0|pts_time=0.000000|dts=0|dts_time=0.000000|duration=2048|duration_time=0.040000|convergence_duration=N/A|convergence_duration_time=N/A|size=230400|pos=2647|flags=K
+frame|media_type=video|key_frame=1|pkt_pts=0|pkt_pts_time=0.000000|pkt_dts=0|pkt_dts_time=0.000000|pkt_duration=2048|pkt_duration_time=0.040000|pkt_pos=2647|width=320|height=240|pix_fmt=rgb24|sample_aspect_ratio=1:1|pict_type=I|coded_picture_number=0|display_picture_number=0|interlaced_frame=0|top_field_first=0|repeat_pict=0|reference=0
+packet|codec_type=video|stream_index=2|pts=0|pts_time=0.000000|dts=0|dts_time=0.000000|duration=2048|duration_time=0.040000|convergence_duration=N/A|convergence_duration_time=N/A|size=30000|pos=233068|flags=K
+frame|media_type=video|key_frame=1|pkt_pts=0|pkt_pts_time=0.000000|pkt_dts=0|pkt_dts_time=0.000000|pkt_duration=2048|pkt_duration_time=0.040000|pkt_pos=233068|width=100|height=100|pix_fmt=rgb24|sample_aspect_ratio=1:1|pict_type=I|coded_picture_number=0|display_picture_number=0|interlaced_frame=0|top_field_first=0|repeat_pict=0|reference=0
+packet|codec_type=audio|stream_index=0|pts=1024|pts_time=0.023220|dts=1024|dts_time=0.023220|duration=1024|duration_time=0.023220|convergence_duration=N/A|convergence_duration_time=N/A|size=2048|pos=263073|flags=K
+frame|media_type=audio|key_frame=1|pkt_pts=1024|pkt_pts_time=0.023220|pkt_dts=1024|pkt_dts_time=0.023220|pkt_duration=1024|pkt_duration_time=0.023220|pkt_pos=263073|sample_fmt=s16|nb_samples=1024|channels=1|channel_layout=unknown
+packet|codec_type=video|stream_index=1|pts=2048|pts_time=0.040000|dts=2048|dts_time=0.040000|duration=2048|duration_time=0.040000|convergence_duration=N/A|convergence_duration_time=N/A|size=230400|pos=265151|flags=K
+frame|media_type=video|key_frame=1|pkt_pts=2048|pkt_pts_time=0.040000|pkt_dts=2048|pkt_dts_time=0.040000|pkt_duration=2048|pkt_duration_time=0.040000|pkt_pos=265151|width=320|height=240|pix_fmt=rgb24|sample_aspect_ratio=1:1|pict_type=I|coded_picture_number=0|display_picture_number=0|interlaced_frame=0|top_field_first=0|repeat_pict=0|reference=0
+packet|codec_type=video|stream_index=2|pts=2048|pts_time=0.040000|dts=2048|dts_time=0.040000|duration=2048|duration_time=0.040000|convergence_duration=N/A|convergence_duration_time=N/A|size=30000|pos=495575|flags=K
+frame|media_type=video|key_frame=1|pkt_pts=2048|pkt_pts_time=0.040000|pkt_dts=2048|pkt_dts_time=0.040000|pkt_duration=2048|pkt_duration_time=0.040000|pkt_pos=495575|width=100|height=100|pix_fmt=rgb24|sample_aspect_ratio=1:1|pict_type=I|coded_picture_number=0|display_picture_number=0|interlaced_frame=0|top_field_first=0|repeat_pict=0|reference=0
+packet|codec_type=audio|stream_index=0|pts=2048|pts_time=0.046440|dts=2048|dts_time=0.046440|duration=1024|duration_time=0.023220|convergence_duration=N/A|convergence_duration_time=N/A|size=2048|pos=525580|flags=K
+frame|media_type=audio|key_frame=1|pkt_pts=2048|pkt_pts_time=0.046440|pkt_dts=2048|pkt_dts_time=0.046440|pkt_duration=1024|pkt_duration_time=0.023220|pkt_pos=525580|sample_fmt=s16|nb_samples=1024|channels=1|channel_layout=unknown
+packet|codec_type=audio|stream_index=0|pts=3072|pts_time=0.069660|dts=3072|dts_time=0.069660|duration=1024|duration_time=0.023220|convergence_duration=N/A|convergence_duration_time=N/A|size=2048|pos=527651|flags=K
+frame|media_type=audio|key_frame=1|pkt_pts=3072|pkt_pts_time=0.069660|pkt_dts=3072|pkt_dts_time=0.069660|pkt_duration=1024|pkt_duration_time=0.023220|pkt_pos=527651|sample_fmt=s16|nb_samples=1024|channels=1|channel_layout=unknown
+packet|codec_type=video|stream_index=1|pts=4096|pts_time=0.080000|dts=4096|dts_time=0.080000|duration=2048|duration_time=0.040000|convergence_duration=N/A|convergence_duration_time=N/A|size=230400|pos=529729|flags=K
+frame|media_type=video|key_frame=1|pkt_pts=4096|pkt_pts_time=0.080000|pkt_dts=4096|pkt_dts_time=0.080000|pkt_duration=2048|pkt_duration_time=0.040000|pkt_pos=529729|width=320|height=240|pix_fmt=rgb24|sample_aspect_ratio=1:1|pict_type=I|coded_picture_number=0|display_picture_number=0|interlaced_frame=0|top_field_first=0|repeat_pict=0|reference=0
+packet|codec_type=video|stream_index=2|pts=4096|pts_time=0.080000|dts=4096|dts_time=0.080000|duration=2048|duration_time=0.040000|convergence_duration=N/A|convergence_duration_time=N/A|size=30000|pos=760153|flags=K
+frame|media_type=video|key_frame=1|pkt_pts=4096|pkt_pts_time=0.080000|pkt_dts=4096|pkt_dts_time=0.080000|pkt_duration=2048|pkt_duration_time=0.040000|pkt_pos=760153|width=100|height=100|pix_fmt=rgb24|sample_aspect_ratio=1:1|pict_type=I|coded_picture_number=0|display_picture_number=0|interlaced_frame=0|top_field_first=0|repeat_pict=0|reference=0
+packet|codec_type=audio|stream_index=0|pts=4096|pts_time=0.092880|dts=4096|dts_time=0.092880|duration=1024|duration_time=0.023220|convergence_duration=N/A|convergence_duration_time=N/A|size=2048|pos=790158|flags=K
+frame|media_type=audio|key_frame=1|pkt_pts=4096|pkt_pts_time=0.092880|pkt_dts=4096|pkt_dts_time=0.092880|pkt_duration=1024|pkt_duration_time=0.023220|pkt_pos=790158|sample_fmt=s16|nb_samples=1024|channels=1|channel_layout=unknown
+packet|codec_type=audio|stream_index=0|pts=5120|pts_time=0.116100|dts=5120|dts_time=0.116100|duration=1024|duration_time=0.023220|convergence_duration=N/A|convergence_duration_time=N/A|size=2048|pos=792229|flags=K
+frame|media_type=audio|key_frame=1|pkt_pts=5120|pkt_pts_time=0.116100|pkt_dts=5120|pkt_dts_time=0.116100|pkt_duration=1024|pkt_duration_time=0.023220|pkt_pos=792229|sample_fmt=s16|nb_samples=1024|channels=1|channel_layout=unknown
+packet|codec_type=video|stream_index=1|pts=6144|pts_time=0.120000|dts=6144|dts_time=0.120000|duration=2048|duration_time=0.040000|convergence_duration=N/A|convergence_duration_time=N/A|size=230400|pos=794307|flags=K
+frame|media_type=video|key_frame=1|pkt_pts=6144|pkt_pts_time=0.120000|pkt_dts=6144|pkt_dts_time=0.120000|pkt_duration=2048|pkt_duration_time=0.040000|pkt_pos=794307|width=320|height=240|pix_fmt=rgb24|sample_aspect_ratio=1:1|pict_type=I|coded_picture_number=0|display_picture_number=0|interlaced_frame=0|top_field_first=0|repeat_pict=0|reference=0
+packet|codec_type=video|stream_index=2|pts=6144|pts_time=0.120000|dts=6144|dts_time=0.120000|duration=2048|duration_time=0.040000|convergence_duration=N/A|convergence_duration_time=N/A|size=30000|pos=1024731|flags=K
+frame|media_type=video|key_frame=1|pkt_pts=6144|pkt_pts_time=0.120000|pkt_dts=6144|pkt_dts_time=0.120000|pkt_duration=2048|pkt_duration_time=0.040000|pkt_pos=1024731|width=100|height=100|pix_fmt=rgb24|sample_aspect_ratio=1:1|pict_type=I|coded_picture_number=0|display_picture_number=0|interlaced_frame=0|top_field_first=0|repeat_pict=0|reference=0
+stream|index=0|codec_name=pcm_s16le|profile=unknown|codec_type=audio|codec_time_base=1/44100|codec_tag_string=PSD[16]|codec_tag=0x10445350|sample_fmt=s16|sample_rate=44100|channels=1|bits_per_sample=16|id=N/A|r_frame_rate=0/0|avg_frame_rate=0/0|time_base=1/44100|start_pts=0|start_time=0.000000|duration_ts=527406|duration=11.959320|bit_rate=705600|nb_frames=N/A|nb_read_frames=6|nb_read_packets=6|disposition:default=0|disposition:dub=0|disposition:original=0|disposition:comment=0|disposition:lyrics=0|disposition:karaoke=0|disposition:forced=0|disposition:hearing_impaired=0|disposition:visual_impaired=0|disposition:clean_effects=0|disposition:attached_pic=0|tag:E=mc²
+stream|index=1|codec_name=rawvideo|profile=unknown|codec_type=video|codec_time_base=1/51200|codec_tag_string=RGB[24]|codec_tag=0x18424752|width=320|height=240|has_b_frames=0|sample_aspect_ratio=1:1|display_aspect_ratio=4:3|pix_fmt=rgb24|level=-99|timecode=N/A|id=N/A|r_frame_rate=25/1|avg_frame_rate=25/1|time_base=1/51200|start_pts=0|start_time=0.000000|duration_ts=612317|duration=11.959316|bit_rate=N/A|nb_frames=N/A|nb_read_frames=4|nb_read_packets=4|disposition:default=0|disposition:dub=0|disposition:original=0|disposition:comment=0|disposition:lyrics=0|disposition:karaoke=0|disposition:forced=0|disposition:hearing_impaired=0|disposition:visual_impaired=0|disposition:clean_effects=0|disposition:attached_pic=0|tag:title=foobar|tag:duration_ts=field-and-tags-conflict-attempt
+stream|index=2|codec_name=rawvideo|profile=unknown|codec_type=video|codec_time_base=1/51200|codec_tag_string=RGB[24]|codec_tag=0x18424752|width=100|height=100|has_b_frames=0|sample_aspect_ratio=1:1|display_aspect_ratio=1:1|pix_fmt=rgb24|level=-99|timecode=N/A|id=N/A|r_frame_rate=25/1|avg_frame_rate=25/1|time_base=1/51200|start_pts=0|start_time=0.000000|duration_ts=612317|duration=11.959316|bit_rate=N/A|nb_frames=N/A|nb_read_frames=4|nb_read_packets=4|disposition:default=0|disposition:dub=0|disposition:original=0|disposition:comment=0|disposition:lyrics=0|disposition:karaoke=0|disposition:forced=0|disposition:hearing_impaired=0|disposition:visual_impaired=0|disposition:clean_effects=0|disposition:attached_pic=0
+format|filename=tests/data/ffprobe-test.nut|nb_streams=3|format_name=nut|start_time=0.000000|duration=11.959320|size=1054812|bit_rate=705599|tag:title=ffprobe test file|tag:comment='A comment with CSV, XML & JSON special chars': <tag value="x">|tag:comment2=I ♥ Üñîçød€
diff --git a/tests/ref/fate/ffprobe_csv b/tests/ref/fate/ffprobe_csv
index 94f2c51..d3a1fb9 100644
--- a/tests/ref/fate/ffprobe_csv
+++ b/tests/ref/fate/ffprobe_csv
@@ -1,32 +1,32 @@
-packet,audio,0,0,0.000000,0,0.000000,1024,0.023220,N/A,N/A,2048,403,K
-frame,audio,1,0,0.000000,0,0.000000,1024,0.023220,403,s16,1024,1,unknown
-packet,video,1,0,0.000000,0,0.000000,1,0.040000,N/A,N/A,230400,2478,K
-frame,video,1,0,0.000000,0,0.000000,1,0.040000,2478,320,240,rgb24,1:1,I,0,0,0,0,0,0
-packet,video,2,0,0.000000,0,0.000000,1,0.040000,N/A,N/A,30000,232899,K
-frame,video,1,0,0.000000,0,0.000000,1,0.040000,232899,100,100,rgb24,1:1,I,0,0,0,0,0,0
-packet,audio,0,1024,0.023220,1024,0.023220,1024,0.023220,N/A,N/A,2048,262904,K
-frame,audio,1,1024,0.023220,1024,0.023220,1024,0.023220,262904,s16,1024,1,unknown
-packet,video,1,1,0.040000,1,0.040000,1,0.040000,N/A,N/A,230400,264980,K
-frame,video,1,1,0.040000,1,0.040000,1,0.040000,264980,320,240,rgb24,1:1,I,0,0,0,0,0,0
-packet,video,2,1,0.040000,1,0.040000,1,0.040000,N/A,N/A,30000,495402,K
-frame,video,1,1,0.040000,1,0.040000,1,0.040000,495402,100,100,rgb24,1:1,I,0,0,0,0,0,0
-packet,audio,0,2048,0.046440,2048,0.046440,1024,0.023220,N/A,N/A,2048,525407,K
-frame,audio,1,2048,0.046440,2048,0.046440,1024,0.023220,525407,s16,1024,1,unknown
-packet,audio,0,3072,0.069660,3072,0.069660,1024,0.023220,N/A,N/A,2048,527478,K
-frame,audio,1,3072,0.069660,3072,0.069660,1024,0.023220,527478,s16,1024,1,unknown
-packet,video,1,2,0.080000,2,0.080000,1,0.040000,N/A,N/A,230400,529554,K
-frame,video,1,2,0.080000,2,0.080000,1,0.040000,529554,320,240,rgb24,1:1,I,0,0,0,0,0,0
-packet,video,2,2,0.080000,2,0.080000,1,0.040000,N/A,N/A,30000,759976,K
-frame,video,1,2,0.080000,2,0.080000,1,0.040000,759976,100,100,rgb24,1:1,I,0,0,0,0,0,0
-packet,audio,0,4096,0.092880,4096,0.092880,1024,0.023220,N/A,N/A,2048,789981,K
-frame,audio,1,4096,0.092880,4096,0.092880,1024,0.023220,789981,s16,1024,1,unknown
-packet,audio,0,5120,0.116100,5120,0.116100,1024,0.023220,N/A,N/A,2048,792052,K
-frame,audio,1,5120,0.116100,5120,0.116100,1024,0.023220,792052,s16,1024,1,unknown
-packet,video,1,3,0.120000,3,0.120000,1,0.040000,N/A,N/A,230400,794128,K
-frame,video,1,3,0.120000,3,0.120000,1,0.040000,794128,320,240,rgb24,1:1,I,0,0,0,0,0,0
-packet,video,2,3,0.120000,3,0.120000,1,0.040000,N/A,N/A,30000,1024550,K
-frame,video,1,3,0.120000,3,0.120000,1,0.040000,1024550,100,100,rgb24,1:1,I,0,0,0,0,0,0
-stream,0,pcm_s16le,unknown,audio,1/44100,[1][0][0][0],0x0001,s16,44100,1,16,N/A,0/0,0/0,1/44100,0,0.000000,527313,11.957211,705600,N/A,6,6,0,0,0,0,0,0,0,0,0,0,0
-stream,1,rawvideo,unknown,video,1/25,RGB[24],0x18424752,320,240,0,1:1,4:3,rgb24,-99,N/A,N/A,25/1,0/0,1/25,0,0.000000,299,11.960000,N/A,N/A,4,4,0,0,0,0,0,0,0,0,0,0,0
-stream,2,rawvideo,unknown,video,1/25,RGB[24],0x18424752,100,100,0,1:1,1:1,rgb24,-99,N/A,N/A,25/1,0/0,1/25,0,0.000000,299,11.960000,N/A,N/A,4,4,0,0,0,0,0,0,0,0,0,0,0
-format,tests/data/ffprobe-test.nut,3,nut,0.000000,11.960000,1054625,705434,ffprobe test file,"'A comment with CSV, XML & JSON special chars': <tag value=""x"">",I ♥ Üñîçød€
+packet,audio,0,0,0.000000,0,0.000000,1024,0.023220,N/A,N/A,2048,572,K
+frame,audio,1,0,0.000000,0,0.000000,1024,0.023220,572,s16,1024,1,unknown
+packet,video,1,0,0.000000,0,0.000000,2048,0.040000,N/A,N/A,230400,2647,K
+frame,video,1,0,0.000000,0,0.000000,2048,0.040000,2647,320,240,rgb24,1:1,I,0,0,0,0,0,0
+packet,video,2,0,0.000000,0,0.000000,2048,0.040000,N/A,N/A,30000,233068,K
+frame,video,1,0,0.000000,0,0.000000,2048,0.040000,233068,100,100,rgb24,1:1,I,0,0,0,0,0,0
+packet,audio,0,1024,0.023220,1024,0.023220,1024,0.023220,N/A,N/A,2048,263073,K
+frame,audio,1,1024,0.023220,1024,0.023220,1024,0.023220,263073,s16,1024,1,unknown
+packet,video,1,2048,0.040000,2048,0.040000,2048,0.040000,N/A,N/A,230400,265151,K
+frame,video,1,2048,0.040000,2048,0.040000,2048,0.040000,265151,320,240,rgb24,1:1,I,0,0,0,0,0,0
+packet,video,2,2048,0.040000,2048,0.040000,2048,0.040000,N/A,N/A,30000,495575,K
+frame,video,1,2048,0.040000,2048,0.040000,2048,0.040000,495575,100,100,rgb24,1:1,I,0,0,0,0,0,0
+packet,audio,0,2048,0.046440,2048,0.046440,1024,0.023220,N/A,N/A,2048,525580,K
+frame,audio,1,2048,0.046440,2048,0.046440,1024,0.023220,525580,s16,1024,1,unknown
+packet,audio,0,3072,0.069660,3072,0.069660,1024,0.023220,N/A,N/A,2048,527651,K
+frame,audio,1,3072,0.069660,3072,0.069660,1024,0.023220,527651,s16,1024,1,unknown
+packet,video,1,4096,0.080000,4096,0.080000,2048,0.040000,N/A,N/A,230400,529729,K
+frame,video,1,4096,0.080000,4096,0.080000,2048,0.040000,529729,320,240,rgb24,1:1,I,0,0,0,0,0,0
+packet,video,2,4096,0.080000,4096,0.080000,2048,0.040000,N/A,N/A,30000,760153,K
+frame,video,1,4096,0.080000,4096,0.080000,2048,0.040000,760153,100,100,rgb24,1:1,I,0,0,0,0,0,0
+packet,audio,0,4096,0.092880,4096,0.092880,1024,0.023220,N/A,N/A,2048,790158,K
+frame,audio,1,4096,0.092880,4096,0.092880,1024,0.023220,790158,s16,1024,1,unknown
+packet,audio,0,5120,0.116100,5120,0.116100,1024,0.023220,N/A,N/A,2048,792229,K
+frame,audio,1,5120,0.116100,5120,0.116100,1024,0.023220,792229,s16,1024,1,unknown
+packet,video,1,6144,0.120000,6144,0.120000,2048,0.040000,N/A,N/A,230400,794307,K
+frame,video,1,6144,0.120000,6144,0.120000,2048,0.040000,794307,320,240,rgb24,1:1,I,0,0,0,0,0,0
+packet,video,2,6144,0.120000,6144,0.120000,2048,0.040000,N/A,N/A,30000,1024731,K
+frame,video,1,6144,0.120000,6144,0.120000,2048,0.040000,1024731,100,100,rgb24,1:1,I,0,0,0,0,0,0
+stream,0,pcm_s16le,unknown,audio,1/44100,PSD[16],0x10445350,s16,44100,1,16,N/A,0/0,0/0,1/44100,0,0.000000,527406,11.959320,705600,N/A,6,6,0,0,0,0,0,0,0,0,0,0,0,mc²
+stream,1,rawvideo,unknown,video,1/51200,RGB[24],0x18424752,320,240,0,1:1,4:3,rgb24,-99,N/A,N/A,25/1,25/1,1/51200,0,0.000000,612317,11.959316,N/A,N/A,4,4,0,0,0,0,0,0,0,0,0,0,0,foobar,field-and-tags-conflict-attempt
+stream,2,rawvideo,unknown,video,1/51200,RGB[24],0x18424752,100,100,0,1:1,1:1,rgb24,-99,N/A,N/A,25/1,25/1,1/51200,0,0.000000,612317,11.959316,N/A,N/A,4,4,0,0,0,0,0,0,0,0,0,0,0
+format,tests/data/ffprobe-test.nut,3,nut,0.000000,11.959320,1054812,705599,ffprobe test file,"'A comment with CSV, XML & JSON special chars': <tag value=""x"">",I ♥ Üñîçød€
diff --git a/tests/ref/fate/ffprobe_default b/tests/ref/fate/ffprobe_default
index 093efe3..c30f1fb 100644
--- a/tests/ref/fate/ffprobe_default
+++ b/tests/ref/fate/ffprobe_default
@@ -10,7 +10,7 @@
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=2048
-pos=403
+pos=572
 flags=K
 [/PACKET]
 [FRAME]
@@ -22,7 +22,7 @@
 pkt_dts_time=0.000000
 pkt_duration=1024
 pkt_duration_time=0.023220
-pkt_pos=403
+pkt_pos=572
 sample_fmt=s16
 nb_samples=1024
 channels=1
@@ -35,12 +35,12 @@
 pts_time=0.000000
 dts=0
 dts_time=0.000000
-duration=1
+duration=2048
 duration_time=0.040000
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=230400
-pos=2478
+pos=2647
 flags=K
 [/PACKET]
 [FRAME]
@@ -50,9 +50,9 @@
 pkt_pts_time=0.000000
 pkt_dts=0
 pkt_dts_time=0.000000
-pkt_duration=1
+pkt_duration=2048
 pkt_duration_time=0.040000
-pkt_pos=2478
+pkt_pos=2647
 width=320
 height=240
 pix_fmt=rgb24
@@ -72,12 +72,12 @@
 pts_time=0.000000
 dts=0
 dts_time=0.000000
-duration=1
+duration=2048
 duration_time=0.040000
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=30000
-pos=232899
+pos=233068
 flags=K
 [/PACKET]
 [FRAME]
@@ -87,9 +87,9 @@
 pkt_pts_time=0.000000
 pkt_dts=0
 pkt_dts_time=0.000000
-pkt_duration=1
+pkt_duration=2048
 pkt_duration_time=0.040000
-pkt_pos=232899
+pkt_pos=233068
 width=100
 height=100
 pix_fmt=rgb24
@@ -114,7 +114,7 @@
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=2048
-pos=262904
+pos=263073
 flags=K
 [/PACKET]
 [FRAME]
@@ -126,7 +126,7 @@
 pkt_dts_time=0.023220
 pkt_duration=1024
 pkt_duration_time=0.023220
-pkt_pos=262904
+pkt_pos=263073
 sample_fmt=s16
 nb_samples=1024
 channels=1
@@ -135,28 +135,28 @@
 [PACKET]
 codec_type=video
 stream_index=1
-pts=1
+pts=2048
 pts_time=0.040000
-dts=1
+dts=2048
 dts_time=0.040000
-duration=1
+duration=2048
 duration_time=0.040000
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=230400
-pos=264980
+pos=265151
 flags=K
 [/PACKET]
 [FRAME]
 media_type=video
 key_frame=1
-pkt_pts=1
+pkt_pts=2048
 pkt_pts_time=0.040000
-pkt_dts=1
+pkt_dts=2048
 pkt_dts_time=0.040000
-pkt_duration=1
+pkt_duration=2048
 pkt_duration_time=0.040000
-pkt_pos=264980
+pkt_pos=265151
 width=320
 height=240
 pix_fmt=rgb24
@@ -172,28 +172,28 @@
 [PACKET]
 codec_type=video
 stream_index=2
-pts=1
+pts=2048
 pts_time=0.040000
-dts=1
+dts=2048
 dts_time=0.040000
-duration=1
+duration=2048
 duration_time=0.040000
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=30000
-pos=495402
+pos=495575
 flags=K
 [/PACKET]
 [FRAME]
 media_type=video
 key_frame=1
-pkt_pts=1
+pkt_pts=2048
 pkt_pts_time=0.040000
-pkt_dts=1
+pkt_dts=2048
 pkt_dts_time=0.040000
-pkt_duration=1
+pkt_duration=2048
 pkt_duration_time=0.040000
-pkt_pos=495402
+pkt_pos=495575
 width=100
 height=100
 pix_fmt=rgb24
@@ -218,7 +218,7 @@
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=2048
-pos=525407
+pos=525580
 flags=K
 [/PACKET]
 [FRAME]
@@ -230,7 +230,7 @@
 pkt_dts_time=0.046440
 pkt_duration=1024
 pkt_duration_time=0.023220
-pkt_pos=525407
+pkt_pos=525580
 sample_fmt=s16
 nb_samples=1024
 channels=1
@@ -248,7 +248,7 @@
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=2048
-pos=527478
+pos=527651
 flags=K
 [/PACKET]
 [FRAME]
@@ -260,7 +260,7 @@
 pkt_dts_time=0.069660
 pkt_duration=1024
 pkt_duration_time=0.023220
-pkt_pos=527478
+pkt_pos=527651
 sample_fmt=s16
 nb_samples=1024
 channels=1
@@ -269,28 +269,28 @@
 [PACKET]
 codec_type=video
 stream_index=1
-pts=2
+pts=4096
 pts_time=0.080000
-dts=2
+dts=4096
 dts_time=0.080000
-duration=1
+duration=2048
 duration_time=0.040000
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=230400
-pos=529554
+pos=529729
 flags=K
 [/PACKET]
 [FRAME]
 media_type=video
 key_frame=1
-pkt_pts=2
+pkt_pts=4096
 pkt_pts_time=0.080000
-pkt_dts=2
+pkt_dts=4096
 pkt_dts_time=0.080000
-pkt_duration=1
+pkt_duration=2048
 pkt_duration_time=0.040000
-pkt_pos=529554
+pkt_pos=529729
 width=320
 height=240
 pix_fmt=rgb24
@@ -306,28 +306,28 @@
 [PACKET]
 codec_type=video
 stream_index=2
-pts=2
+pts=4096
 pts_time=0.080000
-dts=2
+dts=4096
 dts_time=0.080000
-duration=1
+duration=2048
 duration_time=0.040000
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=30000
-pos=759976
+pos=760153
 flags=K
 [/PACKET]
 [FRAME]
 media_type=video
 key_frame=1
-pkt_pts=2
+pkt_pts=4096
 pkt_pts_time=0.080000
-pkt_dts=2
+pkt_dts=4096
 pkt_dts_time=0.080000
-pkt_duration=1
+pkt_duration=2048
 pkt_duration_time=0.040000
-pkt_pos=759976
+pkt_pos=760153
 width=100
 height=100
 pix_fmt=rgb24
@@ -352,7 +352,7 @@
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=2048
-pos=789981
+pos=790158
 flags=K
 [/PACKET]
 [FRAME]
@@ -364,7 +364,7 @@
 pkt_dts_time=0.092880
 pkt_duration=1024
 pkt_duration_time=0.023220
-pkt_pos=789981
+pkt_pos=790158
 sample_fmt=s16
 nb_samples=1024
 channels=1
@@ -382,7 +382,7 @@
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=2048
-pos=792052
+pos=792229
 flags=K
 [/PACKET]
 [FRAME]
@@ -394,7 +394,7 @@
 pkt_dts_time=0.116100
 pkt_duration=1024
 pkt_duration_time=0.023220
-pkt_pos=792052
+pkt_pos=792229
 sample_fmt=s16
 nb_samples=1024
 channels=1
@@ -403,28 +403,28 @@
 [PACKET]
 codec_type=video
 stream_index=1
-pts=3
+pts=6144
 pts_time=0.120000
-dts=3
+dts=6144
 dts_time=0.120000
-duration=1
+duration=2048
 duration_time=0.040000
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=230400
-pos=794128
+pos=794307
 flags=K
 [/PACKET]
 [FRAME]
 media_type=video
 key_frame=1
-pkt_pts=3
+pkt_pts=6144
 pkt_pts_time=0.120000
-pkt_dts=3
+pkt_dts=6144
 pkt_dts_time=0.120000
-pkt_duration=1
+pkt_duration=2048
 pkt_duration_time=0.040000
-pkt_pos=794128
+pkt_pos=794307
 width=320
 height=240
 pix_fmt=rgb24
@@ -440,28 +440,28 @@
 [PACKET]
 codec_type=video
 stream_index=2
-pts=3
+pts=6144
 pts_time=0.120000
-dts=3
+dts=6144
 dts_time=0.120000
-duration=1
+duration=2048
 duration_time=0.040000
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=30000
-pos=1024550
+pos=1024731
 flags=K
 [/PACKET]
 [FRAME]
 media_type=video
 key_frame=1
-pkt_pts=3
+pkt_pts=6144
 pkt_pts_time=0.120000
-pkt_dts=3
+pkt_dts=6144
 pkt_dts_time=0.120000
-pkt_duration=1
+pkt_duration=2048
 pkt_duration_time=0.040000
-pkt_pos=1024550
+pkt_pos=1024731
 width=100
 height=100
 pix_fmt=rgb24
@@ -480,8 +480,8 @@
 profile=unknown
 codec_type=audio
 codec_time_base=1/44100
-codec_tag_string=[1][0][0][0]
-codec_tag=0x0001
+codec_tag_string=PSD[16]
+codec_tag=0x10445350
 sample_fmt=s16
 sample_rate=44100
 channels=1
@@ -492,8 +492,8 @@
 time_base=1/44100
 start_pts=0
 start_time=0.000000
-duration_ts=527313
-duration=11.957211
+duration_ts=527406
+duration=11.959320
 bit_rate=705600
 nb_frames=N/A
 nb_read_frames=6
@@ -509,13 +509,14 @@
 DISPOSITION:visual_impaired=0
 DISPOSITION:clean_effects=0
 DISPOSITION:attached_pic=0
+TAG:E=mc²
 [/STREAM]
 [STREAM]
 index=1
 codec_name=rawvideo
 profile=unknown
 codec_type=video
-codec_time_base=1/25
+codec_time_base=1/51200
 codec_tag_string=RGB[24]
 codec_tag=0x18424752
 width=320
@@ -528,12 +529,12 @@
 timecode=N/A
 id=N/A
 r_frame_rate=25/1
-avg_frame_rate=0/0
-time_base=1/25
+avg_frame_rate=25/1
+time_base=1/51200
 start_pts=0
 start_time=0.000000
-duration_ts=299
-duration=11.960000
+duration_ts=612317
+duration=11.959316
 bit_rate=N/A
 nb_frames=N/A
 nb_read_frames=4
@@ -549,13 +550,15 @@
 DISPOSITION:visual_impaired=0
 DISPOSITION:clean_effects=0
 DISPOSITION:attached_pic=0
+TAG:title=foobar
+TAG:duration_ts=field-and-tags-conflict-attempt
 [/STREAM]
 [STREAM]
 index=2
 codec_name=rawvideo
 profile=unknown
 codec_type=video
-codec_time_base=1/25
+codec_time_base=1/51200
 codec_tag_string=RGB[24]
 codec_tag=0x18424752
 width=100
@@ -568,12 +571,12 @@
 timecode=N/A
 id=N/A
 r_frame_rate=25/1
-avg_frame_rate=0/0
-time_base=1/25
+avg_frame_rate=25/1
+time_base=1/51200
 start_pts=0
 start_time=0.000000
-duration_ts=299
-duration=11.960000
+duration_ts=612317
+duration=11.959316
 bit_rate=N/A
 nb_frames=N/A
 nb_read_frames=4
@@ -595,9 +598,9 @@
 nb_streams=3
 format_name=nut
 start_time=0.000000
-duration=11.960000
-size=1054625
-bit_rate=705434
+duration=11.959320
+size=1054812
+bit_rate=705599
 TAG:title=ffprobe test file
 TAG:comment='A comment with CSV, XML & JSON special chars': <tag value="x">
 TAG:comment2=I ♥ Üñîçød€
diff --git a/tests/ref/fate/ffprobe_flat b/tests/ref/fate/ffprobe_flat
index 5a0b6d8..43dcabd 100644
--- a/tests/ref/fate/ffprobe_flat
+++ b/tests/ref/fate/ffprobe_flat
@@ -9,7 +9,7 @@
 packets_and_frames.packet.0.convergence_duration="N/A"
 packets_and_frames.packet.0.convergence_duration_time="N/A"
 packets_and_frames.packet.0.size="2048"
-packets_and_frames.packet.0.pos="403"
+packets_and_frames.packet.0.pos="572"
 packets_and_frames.packet.0.flags="K"
 packets_and_frames.frame.0.media_type="audio"
 packets_and_frames.frame.0.key_frame=1
@@ -19,7 +19,7 @@
 packets_and_frames.frame.0.pkt_dts_time="0.000000"
 packets_and_frames.frame.0.pkt_duration=1024
 packets_and_frames.frame.0.pkt_duration_time="0.023220"
-packets_and_frames.frame.0.pkt_pos="403"
+packets_and_frames.frame.0.pkt_pos="572"
 packets_and_frames.frame.0.sample_fmt="s16"
 packets_and_frames.frame.0.nb_samples=1024
 packets_and_frames.frame.0.channels=1
@@ -30,12 +30,12 @@
 packets_and_frames.packet.1.pts_time="0.000000"
 packets_and_frames.packet.1.dts=0
 packets_and_frames.packet.1.dts_time="0.000000"
-packets_and_frames.packet.1.duration=1
+packets_and_frames.packet.1.duration=2048
 packets_and_frames.packet.1.duration_time="0.040000"
 packets_and_frames.packet.1.convergence_duration="N/A"
 packets_and_frames.packet.1.convergence_duration_time="N/A"
 packets_and_frames.packet.1.size="230400"
-packets_and_frames.packet.1.pos="2478"
+packets_and_frames.packet.1.pos="2647"
 packets_and_frames.packet.1.flags="K"
 packets_and_frames.frame.1.media_type="video"
 packets_and_frames.frame.1.key_frame=1
@@ -43,9 +43,9 @@
 packets_and_frames.frame.1.pkt_pts_time="0.000000"
 packets_and_frames.frame.1.pkt_dts=0
 packets_and_frames.frame.1.pkt_dts_time="0.000000"
-packets_and_frames.frame.1.pkt_duration=1
+packets_and_frames.frame.1.pkt_duration=2048
 packets_and_frames.frame.1.pkt_duration_time="0.040000"
-packets_and_frames.frame.1.pkt_pos="2478"
+packets_and_frames.frame.1.pkt_pos="2647"
 packets_and_frames.frame.1.width=320
 packets_and_frames.frame.1.height=240
 packets_and_frames.frame.1.pix_fmt="rgb24"
@@ -63,12 +63,12 @@
 packets_and_frames.packet.2.pts_time="0.000000"
 packets_and_frames.packet.2.dts=0
 packets_and_frames.packet.2.dts_time="0.000000"
-packets_and_frames.packet.2.duration=1
+packets_and_frames.packet.2.duration=2048
 packets_and_frames.packet.2.duration_time="0.040000"
 packets_and_frames.packet.2.convergence_duration="N/A"
 packets_and_frames.packet.2.convergence_duration_time="N/A"
 packets_and_frames.packet.2.size="30000"
-packets_and_frames.packet.2.pos="232899"
+packets_and_frames.packet.2.pos="233068"
 packets_and_frames.packet.2.flags="K"
 packets_and_frames.frame.2.media_type="video"
 packets_and_frames.frame.2.key_frame=1
@@ -76,9 +76,9 @@
 packets_and_frames.frame.2.pkt_pts_time="0.000000"
 packets_and_frames.frame.2.pkt_dts=0
 packets_and_frames.frame.2.pkt_dts_time="0.000000"
-packets_and_frames.frame.2.pkt_duration=1
+packets_and_frames.frame.2.pkt_duration=2048
 packets_and_frames.frame.2.pkt_duration_time="0.040000"
-packets_and_frames.frame.2.pkt_pos="232899"
+packets_and_frames.frame.2.pkt_pos="233068"
 packets_and_frames.frame.2.width=100
 packets_and_frames.frame.2.height=100
 packets_and_frames.frame.2.pix_fmt="rgb24"
@@ -101,7 +101,7 @@
 packets_and_frames.packet.3.convergence_duration="N/A"
 packets_and_frames.packet.3.convergence_duration_time="N/A"
 packets_and_frames.packet.3.size="2048"
-packets_and_frames.packet.3.pos="262904"
+packets_and_frames.packet.3.pos="263073"
 packets_and_frames.packet.3.flags="K"
 packets_and_frames.frame.3.media_type="audio"
 packets_and_frames.frame.3.key_frame=1
@@ -111,33 +111,33 @@
 packets_and_frames.frame.3.pkt_dts_time="0.023220"
 packets_and_frames.frame.3.pkt_duration=1024
 packets_and_frames.frame.3.pkt_duration_time="0.023220"
-packets_and_frames.frame.3.pkt_pos="262904"
+packets_and_frames.frame.3.pkt_pos="263073"
 packets_and_frames.frame.3.sample_fmt="s16"
 packets_and_frames.frame.3.nb_samples=1024
 packets_and_frames.frame.3.channels=1
 packets_and_frames.frame.3.channel_layout="unknown"
 packets_and_frames.packet.4.codec_type="video"
 packets_and_frames.packet.4.stream_index=1
-packets_and_frames.packet.4.pts=1
+packets_and_frames.packet.4.pts=2048
 packets_and_frames.packet.4.pts_time="0.040000"
-packets_and_frames.packet.4.dts=1
+packets_and_frames.packet.4.dts=2048
 packets_and_frames.packet.4.dts_time="0.040000"
-packets_and_frames.packet.4.duration=1
+packets_and_frames.packet.4.duration=2048
 packets_and_frames.packet.4.duration_time="0.040000"
 packets_and_frames.packet.4.convergence_duration="N/A"
 packets_and_frames.packet.4.convergence_duration_time="N/A"
 packets_and_frames.packet.4.size="230400"
-packets_and_frames.packet.4.pos="264980"
+packets_and_frames.packet.4.pos="265151"
 packets_and_frames.packet.4.flags="K"
 packets_and_frames.frame.4.media_type="video"
 packets_and_frames.frame.4.key_frame=1
-packets_and_frames.frame.4.pkt_pts=1
+packets_and_frames.frame.4.pkt_pts=2048
 packets_and_frames.frame.4.pkt_pts_time="0.040000"
-packets_and_frames.frame.4.pkt_dts=1
+packets_and_frames.frame.4.pkt_dts=2048
 packets_and_frames.frame.4.pkt_dts_time="0.040000"
-packets_and_frames.frame.4.pkt_duration=1
+packets_and_frames.frame.4.pkt_duration=2048
 packets_and_frames.frame.4.pkt_duration_time="0.040000"
-packets_and_frames.frame.4.pkt_pos="264980"
+packets_and_frames.frame.4.pkt_pos="265151"
 packets_and_frames.frame.4.width=320
 packets_and_frames.frame.4.height=240
 packets_and_frames.frame.4.pix_fmt="rgb24"
@@ -151,26 +151,26 @@
 packets_and_frames.frame.4.reference=0
 packets_and_frames.packet.5.codec_type="video"
 packets_and_frames.packet.5.stream_index=2
-packets_and_frames.packet.5.pts=1
+packets_and_frames.packet.5.pts=2048
 packets_and_frames.packet.5.pts_time="0.040000"
-packets_and_frames.packet.5.dts=1
+packets_and_frames.packet.5.dts=2048
 packets_and_frames.packet.5.dts_time="0.040000"
-packets_and_frames.packet.5.duration=1
+packets_and_frames.packet.5.duration=2048
 packets_and_frames.packet.5.duration_time="0.040000"
 packets_and_frames.packet.5.convergence_duration="N/A"
 packets_and_frames.packet.5.convergence_duration_time="N/A"
 packets_and_frames.packet.5.size="30000"
-packets_and_frames.packet.5.pos="495402"
+packets_and_frames.packet.5.pos="495575"
 packets_and_frames.packet.5.flags="K"
 packets_and_frames.frame.5.media_type="video"
 packets_and_frames.frame.5.key_frame=1
-packets_and_frames.frame.5.pkt_pts=1
+packets_and_frames.frame.5.pkt_pts=2048
 packets_and_frames.frame.5.pkt_pts_time="0.040000"
-packets_and_frames.frame.5.pkt_dts=1
+packets_and_frames.frame.5.pkt_dts=2048
 packets_and_frames.frame.5.pkt_dts_time="0.040000"
-packets_and_frames.frame.5.pkt_duration=1
+packets_and_frames.frame.5.pkt_duration=2048
 packets_and_frames.frame.5.pkt_duration_time="0.040000"
-packets_and_frames.frame.5.pkt_pos="495402"
+packets_and_frames.frame.5.pkt_pos="495575"
 packets_and_frames.frame.5.width=100
 packets_and_frames.frame.5.height=100
 packets_and_frames.frame.5.pix_fmt="rgb24"
@@ -193,7 +193,7 @@
 packets_and_frames.packet.6.convergence_duration="N/A"
 packets_and_frames.packet.6.convergence_duration_time="N/A"
 packets_and_frames.packet.6.size="2048"
-packets_and_frames.packet.6.pos="525407"
+packets_and_frames.packet.6.pos="525580"
 packets_and_frames.packet.6.flags="K"
 packets_and_frames.frame.6.media_type="audio"
 packets_and_frames.frame.6.key_frame=1
@@ -203,7 +203,7 @@
 packets_and_frames.frame.6.pkt_dts_time="0.046440"
 packets_and_frames.frame.6.pkt_duration=1024
 packets_and_frames.frame.6.pkt_duration_time="0.023220"
-packets_and_frames.frame.6.pkt_pos="525407"
+packets_and_frames.frame.6.pkt_pos="525580"
 packets_and_frames.frame.6.sample_fmt="s16"
 packets_and_frames.frame.6.nb_samples=1024
 packets_and_frames.frame.6.channels=1
@@ -219,7 +219,7 @@
 packets_and_frames.packet.7.convergence_duration="N/A"
 packets_and_frames.packet.7.convergence_duration_time="N/A"
 packets_and_frames.packet.7.size="2048"
-packets_and_frames.packet.7.pos="527478"
+packets_and_frames.packet.7.pos="527651"
 packets_and_frames.packet.7.flags="K"
 packets_and_frames.frame.7.media_type="audio"
 packets_and_frames.frame.7.key_frame=1
@@ -229,33 +229,33 @@
 packets_and_frames.frame.7.pkt_dts_time="0.069660"
 packets_and_frames.frame.7.pkt_duration=1024
 packets_and_frames.frame.7.pkt_duration_time="0.023220"
-packets_and_frames.frame.7.pkt_pos="527478"
+packets_and_frames.frame.7.pkt_pos="527651"
 packets_and_frames.frame.7.sample_fmt="s16"
 packets_and_frames.frame.7.nb_samples=1024
 packets_and_frames.frame.7.channels=1
 packets_and_frames.frame.7.channel_layout="unknown"
 packets_and_frames.packet.8.codec_type="video"
 packets_and_frames.packet.8.stream_index=1
-packets_and_frames.packet.8.pts=2
+packets_and_frames.packet.8.pts=4096
 packets_and_frames.packet.8.pts_time="0.080000"
-packets_and_frames.packet.8.dts=2
+packets_and_frames.packet.8.dts=4096
 packets_and_frames.packet.8.dts_time="0.080000"
-packets_and_frames.packet.8.duration=1
+packets_and_frames.packet.8.duration=2048
 packets_and_frames.packet.8.duration_time="0.040000"
 packets_and_frames.packet.8.convergence_duration="N/A"
 packets_and_frames.packet.8.convergence_duration_time="N/A"
 packets_and_frames.packet.8.size="230400"
-packets_and_frames.packet.8.pos="529554"
+packets_and_frames.packet.8.pos="529729"
 packets_and_frames.packet.8.flags="K"
 packets_and_frames.frame.8.media_type="video"
 packets_and_frames.frame.8.key_frame=1
-packets_and_frames.frame.8.pkt_pts=2
+packets_and_frames.frame.8.pkt_pts=4096
 packets_and_frames.frame.8.pkt_pts_time="0.080000"
-packets_and_frames.frame.8.pkt_dts=2
+packets_and_frames.frame.8.pkt_dts=4096
 packets_and_frames.frame.8.pkt_dts_time="0.080000"
-packets_and_frames.frame.8.pkt_duration=1
+packets_and_frames.frame.8.pkt_duration=2048
 packets_and_frames.frame.8.pkt_duration_time="0.040000"
-packets_and_frames.frame.8.pkt_pos="529554"
+packets_and_frames.frame.8.pkt_pos="529729"
 packets_and_frames.frame.8.width=320
 packets_and_frames.frame.8.height=240
 packets_and_frames.frame.8.pix_fmt="rgb24"
@@ -269,26 +269,26 @@
 packets_and_frames.frame.8.reference=0
 packets_and_frames.packet.9.codec_type="video"
 packets_and_frames.packet.9.stream_index=2
-packets_and_frames.packet.9.pts=2
+packets_and_frames.packet.9.pts=4096
 packets_and_frames.packet.9.pts_time="0.080000"
-packets_and_frames.packet.9.dts=2
+packets_and_frames.packet.9.dts=4096
 packets_and_frames.packet.9.dts_time="0.080000"
-packets_and_frames.packet.9.duration=1
+packets_and_frames.packet.9.duration=2048
 packets_and_frames.packet.9.duration_time="0.040000"
 packets_and_frames.packet.9.convergence_duration="N/A"
 packets_and_frames.packet.9.convergence_duration_time="N/A"
 packets_and_frames.packet.9.size="30000"
-packets_and_frames.packet.9.pos="759976"
+packets_and_frames.packet.9.pos="760153"
 packets_and_frames.packet.9.flags="K"
 packets_and_frames.frame.9.media_type="video"
 packets_and_frames.frame.9.key_frame=1
-packets_and_frames.frame.9.pkt_pts=2
+packets_and_frames.frame.9.pkt_pts=4096
 packets_and_frames.frame.9.pkt_pts_time="0.080000"
-packets_and_frames.frame.9.pkt_dts=2
+packets_and_frames.frame.9.pkt_dts=4096
 packets_and_frames.frame.9.pkt_dts_time="0.080000"
-packets_and_frames.frame.9.pkt_duration=1
+packets_and_frames.frame.9.pkt_duration=2048
 packets_and_frames.frame.9.pkt_duration_time="0.040000"
-packets_and_frames.frame.9.pkt_pos="759976"
+packets_and_frames.frame.9.pkt_pos="760153"
 packets_and_frames.frame.9.width=100
 packets_and_frames.frame.9.height=100
 packets_and_frames.frame.9.pix_fmt="rgb24"
@@ -311,7 +311,7 @@
 packets_and_frames.packet.10.convergence_duration="N/A"
 packets_and_frames.packet.10.convergence_duration_time="N/A"
 packets_and_frames.packet.10.size="2048"
-packets_and_frames.packet.10.pos="789981"
+packets_and_frames.packet.10.pos="790158"
 packets_and_frames.packet.10.flags="K"
 packets_and_frames.frame.10.media_type="audio"
 packets_and_frames.frame.10.key_frame=1
@@ -321,7 +321,7 @@
 packets_and_frames.frame.10.pkt_dts_time="0.092880"
 packets_and_frames.frame.10.pkt_duration=1024
 packets_and_frames.frame.10.pkt_duration_time="0.023220"
-packets_and_frames.frame.10.pkt_pos="789981"
+packets_and_frames.frame.10.pkt_pos="790158"
 packets_and_frames.frame.10.sample_fmt="s16"
 packets_and_frames.frame.10.nb_samples=1024
 packets_and_frames.frame.10.channels=1
@@ -337,7 +337,7 @@
 packets_and_frames.packet.11.convergence_duration="N/A"
 packets_and_frames.packet.11.convergence_duration_time="N/A"
 packets_and_frames.packet.11.size="2048"
-packets_and_frames.packet.11.pos="792052"
+packets_and_frames.packet.11.pos="792229"
 packets_and_frames.packet.11.flags="K"
 packets_and_frames.frame.11.media_type="audio"
 packets_and_frames.frame.11.key_frame=1
@@ -347,33 +347,33 @@
 packets_and_frames.frame.11.pkt_dts_time="0.116100"
 packets_and_frames.frame.11.pkt_duration=1024
 packets_and_frames.frame.11.pkt_duration_time="0.023220"
-packets_and_frames.frame.11.pkt_pos="792052"
+packets_and_frames.frame.11.pkt_pos="792229"
 packets_and_frames.frame.11.sample_fmt="s16"
 packets_and_frames.frame.11.nb_samples=1024
 packets_and_frames.frame.11.channels=1
 packets_and_frames.frame.11.channel_layout="unknown"
 packets_and_frames.packet.12.codec_type="video"
 packets_and_frames.packet.12.stream_index=1
-packets_and_frames.packet.12.pts=3
+packets_and_frames.packet.12.pts=6144
 packets_and_frames.packet.12.pts_time="0.120000"
-packets_and_frames.packet.12.dts=3
+packets_and_frames.packet.12.dts=6144
 packets_and_frames.packet.12.dts_time="0.120000"
-packets_and_frames.packet.12.duration=1
+packets_and_frames.packet.12.duration=2048
 packets_and_frames.packet.12.duration_time="0.040000"
 packets_and_frames.packet.12.convergence_duration="N/A"
 packets_and_frames.packet.12.convergence_duration_time="N/A"
 packets_and_frames.packet.12.size="230400"
-packets_and_frames.packet.12.pos="794128"
+packets_and_frames.packet.12.pos="794307"
 packets_and_frames.packet.12.flags="K"
 packets_and_frames.frame.12.media_type="video"
 packets_and_frames.frame.12.key_frame=1
-packets_and_frames.frame.12.pkt_pts=3
+packets_and_frames.frame.12.pkt_pts=6144
 packets_and_frames.frame.12.pkt_pts_time="0.120000"
-packets_and_frames.frame.12.pkt_dts=3
+packets_and_frames.frame.12.pkt_dts=6144
 packets_and_frames.frame.12.pkt_dts_time="0.120000"
-packets_and_frames.frame.12.pkt_duration=1
+packets_and_frames.frame.12.pkt_duration=2048
 packets_and_frames.frame.12.pkt_duration_time="0.040000"
-packets_and_frames.frame.12.pkt_pos="794128"
+packets_and_frames.frame.12.pkt_pos="794307"
 packets_and_frames.frame.12.width=320
 packets_and_frames.frame.12.height=240
 packets_and_frames.frame.12.pix_fmt="rgb24"
@@ -387,26 +387,26 @@
 packets_and_frames.frame.12.reference=0
 packets_and_frames.packet.13.codec_type="video"
 packets_and_frames.packet.13.stream_index=2
-packets_and_frames.packet.13.pts=3
+packets_and_frames.packet.13.pts=6144
 packets_and_frames.packet.13.pts_time="0.120000"
-packets_and_frames.packet.13.dts=3
+packets_and_frames.packet.13.dts=6144
 packets_and_frames.packet.13.dts_time="0.120000"
-packets_and_frames.packet.13.duration=1
+packets_and_frames.packet.13.duration=2048
 packets_and_frames.packet.13.duration_time="0.040000"
 packets_and_frames.packet.13.convergence_duration="N/A"
 packets_and_frames.packet.13.convergence_duration_time="N/A"
 packets_and_frames.packet.13.size="30000"
-packets_and_frames.packet.13.pos="1024550"
+packets_and_frames.packet.13.pos="1024731"
 packets_and_frames.packet.13.flags="K"
 packets_and_frames.frame.13.media_type="video"
 packets_and_frames.frame.13.key_frame=1
-packets_and_frames.frame.13.pkt_pts=3
+packets_and_frames.frame.13.pkt_pts=6144
 packets_and_frames.frame.13.pkt_pts_time="0.120000"
-packets_and_frames.frame.13.pkt_dts=3
+packets_and_frames.frame.13.pkt_dts=6144
 packets_and_frames.frame.13.pkt_dts_time="0.120000"
-packets_and_frames.frame.13.pkt_duration=1
+packets_and_frames.frame.13.pkt_duration=2048
 packets_and_frames.frame.13.pkt_duration_time="0.040000"
-packets_and_frames.frame.13.pkt_pos="1024550"
+packets_and_frames.frame.13.pkt_pos="1024731"
 packets_and_frames.frame.13.width=100
 packets_and_frames.frame.13.height=100
 packets_and_frames.frame.13.pix_fmt="rgb24"
@@ -423,8 +423,8 @@
 streams.stream.0.profile="unknown"
 streams.stream.0.codec_type="audio"
 streams.stream.0.codec_time_base="1/44100"
-streams.stream.0.codec_tag_string="[1][0][0][0]"
-streams.stream.0.codec_tag="0x0001"
+streams.stream.0.codec_tag_string="PSD[16]"
+streams.stream.0.codec_tag="0x10445350"
 streams.stream.0.sample_fmt="s16"
 streams.stream.0.sample_rate="44100"
 streams.stream.0.channels=1
@@ -435,8 +435,8 @@
 streams.stream.0.time_base="1/44100"
 streams.stream.0.start_pts=0
 streams.stream.0.start_time="0.000000"
-streams.stream.0.duration_ts=527313
-streams.stream.0.duration="11.957211"
+streams.stream.0.duration_ts=527406
+streams.stream.0.duration="11.959320"
 streams.stream.0.bit_rate="705600"
 streams.stream.0.nb_frames="N/A"
 streams.stream.0.nb_read_frames="6"
@@ -452,11 +452,12 @@
 streams.stream.0.disposition.visual_impaired=0
 streams.stream.0.disposition.clean_effects=0
 streams.stream.0.disposition.attached_pic=0
+streams.stream.0.tags.E="mc²"
 streams.stream.1.index=1
 streams.stream.1.codec_name="rawvideo"
 streams.stream.1.profile="unknown"
 streams.stream.1.codec_type="video"
-streams.stream.1.codec_time_base="1/25"
+streams.stream.1.codec_time_base="1/51200"
 streams.stream.1.codec_tag_string="RGB[24]"
 streams.stream.1.codec_tag="0x18424752"
 streams.stream.1.width=320
@@ -469,12 +470,12 @@
 streams.stream.1.timecode="N/A"
 streams.stream.1.id="N/A"
 streams.stream.1.r_frame_rate="25/1"
-streams.stream.1.avg_frame_rate="0/0"
-streams.stream.1.time_base="1/25"
+streams.stream.1.avg_frame_rate="25/1"
+streams.stream.1.time_base="1/51200"
 streams.stream.1.start_pts=0
 streams.stream.1.start_time="0.000000"
-streams.stream.1.duration_ts=299
-streams.stream.1.duration="11.960000"
+streams.stream.1.duration_ts=612317
+streams.stream.1.duration="11.959316"
 streams.stream.1.bit_rate="N/A"
 streams.stream.1.nb_frames="N/A"
 streams.stream.1.nb_read_frames="4"
@@ -490,11 +491,13 @@
 streams.stream.1.disposition.visual_impaired=0
 streams.stream.1.disposition.clean_effects=0
 streams.stream.1.disposition.attached_pic=0
+streams.stream.1.tags.title="foobar"
+streams.stream.1.tags.duration_ts="field-and-tags-conflict-attempt"
 streams.stream.2.index=2
 streams.stream.2.codec_name="rawvideo"
 streams.stream.2.profile="unknown"
 streams.stream.2.codec_type="video"
-streams.stream.2.codec_time_base="1/25"
+streams.stream.2.codec_time_base="1/51200"
 streams.stream.2.codec_tag_string="RGB[24]"
 streams.stream.2.codec_tag="0x18424752"
 streams.stream.2.width=100
@@ -507,12 +510,12 @@
 streams.stream.2.timecode="N/A"
 streams.stream.2.id="N/A"
 streams.stream.2.r_frame_rate="25/1"
-streams.stream.2.avg_frame_rate="0/0"
-streams.stream.2.time_base="1/25"
+streams.stream.2.avg_frame_rate="25/1"
+streams.stream.2.time_base="1/51200"
 streams.stream.2.start_pts=0
 streams.stream.2.start_time="0.000000"
-streams.stream.2.duration_ts=299
-streams.stream.2.duration="11.960000"
+streams.stream.2.duration_ts=612317
+streams.stream.2.duration="11.959316"
 streams.stream.2.bit_rate="N/A"
 streams.stream.2.nb_frames="N/A"
 streams.stream.2.nb_read_frames="4"
@@ -532,9 +535,9 @@
 format.nb_streams=3
 format.format_name="nut"
 format.start_time="0.000000"
-format.duration="11.960000"
-format.size="1054625"
-format.bit_rate="705434"
+format.duration="11.959320"
+format.size="1054812"
+format.bit_rate="705599"
 format.tags.title="ffprobe test file"
 format.tags.comment="'A comment with CSV, XML & JSON special chars': <tag value=\"x\">"
 format.tags.comment2="I ♥ Üñîçød€"
diff --git a/tests/ref/fate/ffprobe_ini b/tests/ref/fate/ffprobe_ini
index 9a5c197..abaf3e1 100644
--- a/tests/ref/fate/ffprobe_ini
+++ b/tests/ref/fate/ffprobe_ini
@@ -12,7 +12,7 @@
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=2048
-pos=403
+pos=572
 flags=K
 
 [packets_and_frames.frame.0]
@@ -24,7 +24,7 @@
 pkt_dts_time=0.000000
 pkt_duration=1024
 pkt_duration_time=0.023220
-pkt_pos=403
+pkt_pos=572
 sample_fmt=s16
 nb_samples=1024
 channels=1
@@ -37,12 +37,12 @@
 pts_time=0.000000
 dts=0
 dts_time=0.000000
-duration=1
+duration=2048
 duration_time=0.040000
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=230400
-pos=2478
+pos=2647
 flags=K
 
 [packets_and_frames.frame.1]
@@ -52,9 +52,9 @@
 pkt_pts_time=0.000000
 pkt_dts=0
 pkt_dts_time=0.000000
-pkt_duration=1
+pkt_duration=2048
 pkt_duration_time=0.040000
-pkt_pos=2478
+pkt_pos=2647
 width=320
 height=240
 pix_fmt=rgb24
@@ -74,12 +74,12 @@
 pts_time=0.000000
 dts=0
 dts_time=0.000000
-duration=1
+duration=2048
 duration_time=0.040000
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=30000
-pos=232899
+pos=233068
 flags=K
 
 [packets_and_frames.frame.2]
@@ -89,9 +89,9 @@
 pkt_pts_time=0.000000
 pkt_dts=0
 pkt_dts_time=0.000000
-pkt_duration=1
+pkt_duration=2048
 pkt_duration_time=0.040000
-pkt_pos=232899
+pkt_pos=233068
 width=100
 height=100
 pix_fmt=rgb24
@@ -116,7 +116,7 @@
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=2048
-pos=262904
+pos=263073
 flags=K
 
 [packets_and_frames.frame.3]
@@ -128,7 +128,7 @@
 pkt_dts_time=0.023220
 pkt_duration=1024
 pkt_duration_time=0.023220
-pkt_pos=262904
+pkt_pos=263073
 sample_fmt=s16
 nb_samples=1024
 channels=1
@@ -137,28 +137,28 @@
 [packets_and_frames.packet.4]
 codec_type=video
 stream_index=1
-pts=1
+pts=2048
 pts_time=0.040000
-dts=1
+dts=2048
 dts_time=0.040000
-duration=1
+duration=2048
 duration_time=0.040000
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=230400
-pos=264980
+pos=265151
 flags=K
 
 [packets_and_frames.frame.4]
 media_type=video
 key_frame=1
-pkt_pts=1
+pkt_pts=2048
 pkt_pts_time=0.040000
-pkt_dts=1
+pkt_dts=2048
 pkt_dts_time=0.040000
-pkt_duration=1
+pkt_duration=2048
 pkt_duration_time=0.040000
-pkt_pos=264980
+pkt_pos=265151
 width=320
 height=240
 pix_fmt=rgb24
@@ -174,28 +174,28 @@
 [packets_and_frames.packet.5]
 codec_type=video
 stream_index=2
-pts=1
+pts=2048
 pts_time=0.040000
-dts=1
+dts=2048
 dts_time=0.040000
-duration=1
+duration=2048
 duration_time=0.040000
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=30000
-pos=495402
+pos=495575
 flags=K
 
 [packets_and_frames.frame.5]
 media_type=video
 key_frame=1
-pkt_pts=1
+pkt_pts=2048
 pkt_pts_time=0.040000
-pkt_dts=1
+pkt_dts=2048
 pkt_dts_time=0.040000
-pkt_duration=1
+pkt_duration=2048
 pkt_duration_time=0.040000
-pkt_pos=495402
+pkt_pos=495575
 width=100
 height=100
 pix_fmt=rgb24
@@ -220,7 +220,7 @@
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=2048
-pos=525407
+pos=525580
 flags=K
 
 [packets_and_frames.frame.6]
@@ -232,7 +232,7 @@
 pkt_dts_time=0.046440
 pkt_duration=1024
 pkt_duration_time=0.023220
-pkt_pos=525407
+pkt_pos=525580
 sample_fmt=s16
 nb_samples=1024
 channels=1
@@ -250,7 +250,7 @@
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=2048
-pos=527478
+pos=527651
 flags=K
 
 [packets_and_frames.frame.7]
@@ -262,7 +262,7 @@
 pkt_dts_time=0.069660
 pkt_duration=1024
 pkt_duration_time=0.023220
-pkt_pos=527478
+pkt_pos=527651
 sample_fmt=s16
 nb_samples=1024
 channels=1
@@ -271,28 +271,28 @@
 [packets_and_frames.packet.8]
 codec_type=video
 stream_index=1
-pts=2
+pts=4096
 pts_time=0.080000
-dts=2
+dts=4096
 dts_time=0.080000
-duration=1
+duration=2048
 duration_time=0.040000
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=230400
-pos=529554
+pos=529729
 flags=K
 
 [packets_and_frames.frame.8]
 media_type=video
 key_frame=1
-pkt_pts=2
+pkt_pts=4096
 pkt_pts_time=0.080000
-pkt_dts=2
+pkt_dts=4096
 pkt_dts_time=0.080000
-pkt_duration=1
+pkt_duration=2048
 pkt_duration_time=0.040000
-pkt_pos=529554
+pkt_pos=529729
 width=320
 height=240
 pix_fmt=rgb24
@@ -308,28 +308,28 @@
 [packets_and_frames.packet.9]
 codec_type=video
 stream_index=2
-pts=2
+pts=4096
 pts_time=0.080000
-dts=2
+dts=4096
 dts_time=0.080000
-duration=1
+duration=2048
 duration_time=0.040000
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=30000
-pos=759976
+pos=760153
 flags=K
 
 [packets_and_frames.frame.9]
 media_type=video
 key_frame=1
-pkt_pts=2
+pkt_pts=4096
 pkt_pts_time=0.080000
-pkt_dts=2
+pkt_dts=4096
 pkt_dts_time=0.080000
-pkt_duration=1
+pkt_duration=2048
 pkt_duration_time=0.040000
-pkt_pos=759976
+pkt_pos=760153
 width=100
 height=100
 pix_fmt=rgb24
@@ -354,7 +354,7 @@
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=2048
-pos=789981
+pos=790158
 flags=K
 
 [packets_and_frames.frame.10]
@@ -366,7 +366,7 @@
 pkt_dts_time=0.092880
 pkt_duration=1024
 pkt_duration_time=0.023220
-pkt_pos=789981
+pkt_pos=790158
 sample_fmt=s16
 nb_samples=1024
 channels=1
@@ -384,7 +384,7 @@
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=2048
-pos=792052
+pos=792229
 flags=K
 
 [packets_and_frames.frame.11]
@@ -396,7 +396,7 @@
 pkt_dts_time=0.116100
 pkt_duration=1024
 pkt_duration_time=0.023220
-pkt_pos=792052
+pkt_pos=792229
 sample_fmt=s16
 nb_samples=1024
 channels=1
@@ -405,28 +405,28 @@
 [packets_and_frames.packet.12]
 codec_type=video
 stream_index=1
-pts=3
+pts=6144
 pts_time=0.120000
-dts=3
+dts=6144
 dts_time=0.120000
-duration=1
+duration=2048
 duration_time=0.040000
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=230400
-pos=794128
+pos=794307
 flags=K
 
 [packets_and_frames.frame.12]
 media_type=video
 key_frame=1
-pkt_pts=3
+pkt_pts=6144
 pkt_pts_time=0.120000
-pkt_dts=3
+pkt_dts=6144
 pkt_dts_time=0.120000
-pkt_duration=1
+pkt_duration=2048
 pkt_duration_time=0.040000
-pkt_pos=794128
+pkt_pos=794307
 width=320
 height=240
 pix_fmt=rgb24
@@ -442,28 +442,28 @@
 [packets_and_frames.packet.13]
 codec_type=video
 stream_index=2
-pts=3
+pts=6144
 pts_time=0.120000
-dts=3
+dts=6144
 dts_time=0.120000
-duration=1
+duration=2048
 duration_time=0.040000
 convergence_duration=N/A
 convergence_duration_time=N/A
 size=30000
-pos=1024550
+pos=1024731
 flags=K
 
 [packets_and_frames.frame.13]
 media_type=video
 key_frame=1
-pkt_pts=3
+pkt_pts=6144
 pkt_pts_time=0.120000
-pkt_dts=3
+pkt_dts=6144
 pkt_dts_time=0.120000
-pkt_duration=1
+pkt_duration=2048
 pkt_duration_time=0.040000
-pkt_pos=1024550
+pkt_pos=1024731
 width=100
 height=100
 pix_fmt=rgb24
@@ -482,8 +482,8 @@
 profile=unknown
 codec_type=audio
 codec_time_base=1/44100
-codec_tag_string=[1][0][0][0]
-codec_tag=0x0001
+codec_tag_string=PSD[16]
+codec_tag=0x10445350
 sample_fmt=s16
 sample_rate=44100
 channels=1
@@ -494,8 +494,8 @@
 time_base=1/44100
 start_pts=0
 start_time=0.000000
-duration_ts=527313
-duration=11.957211
+duration_ts=527406
+duration=11.959320
 bit_rate=705600
 nb_frames=N/A
 nb_read_frames=6
@@ -514,12 +514,15 @@
 clean_effects=0
 attached_pic=0
 
+[streams.stream.0.tags]
+E=mc²
+
 [streams.stream.1]
 index=1
 codec_name=rawvideo
 profile=unknown
 codec_type=video
-codec_time_base=1/25
+codec_time_base=1/51200
 codec_tag_string=RGB[24]
 codec_tag=0x18424752
 width=320
@@ -532,12 +535,12 @@
 timecode=N/A
 id=N/A
 r_frame_rate=25/1
-avg_frame_rate=0/0
-time_base=1/25
+avg_frame_rate=25/1
+time_base=1/51200
 start_pts=0
 start_time=0.000000
-duration_ts=299
-duration=11.960000
+duration_ts=612317
+duration=11.959316
 bit_rate=N/A
 nb_frames=N/A
 nb_read_frames=4
@@ -556,12 +559,16 @@
 clean_effects=0
 attached_pic=0
 
+[streams.stream.1.tags]
+title=foobar
+duration_ts=field-and-tags-conflict-attempt
+
 [streams.stream.2]
 index=2
 codec_name=rawvideo
 profile=unknown
 codec_type=video
-codec_time_base=1/25
+codec_time_base=1/51200
 codec_tag_string=RGB[24]
 codec_tag=0x18424752
 width=100
@@ -574,12 +581,12 @@
 timecode=N/A
 id=N/A
 r_frame_rate=25/1
-avg_frame_rate=0/0
-time_base=1/25
+avg_frame_rate=25/1
+time_base=1/51200
 start_pts=0
 start_time=0.000000
-duration_ts=299
-duration=11.960000
+duration_ts=612317
+duration=11.959316
 bit_rate=N/A
 nb_frames=N/A
 nb_read_frames=4
@@ -603,9 +610,9 @@
 nb_streams=3
 format_name=nut
 start_time=0.000000
-duration=11.960000
-size=1054625
-bit_rate=705434
+duration=11.959320
+size=1054812
+bit_rate=705599
 
 [format.tags]
 title=ffprobe test file
diff --git a/tests/ref/fate/ffprobe_json b/tests/ref/fate/ffprobe_json
index 19fa7b8..6b55d92 100644
--- a/tests/ref/fate/ffprobe_json
+++ b/tests/ref/fate/ffprobe_json
@@ -11,7 +11,7 @@
             "duration": 1024,
             "duration_time": "0.023220",
             "size": "2048",
-            "pos": "403",
+            "pos": "572",
             "flags": "K"
         },
         {
@@ -24,7 +24,7 @@
             "pkt_dts_time": "0.000000",
             "pkt_duration": 1024,
             "pkt_duration_time": "0.023220",
-            "pkt_pos": "403",
+            "pkt_pos": "572",
             "sample_fmt": "s16",
             "nb_samples": 1024,
             "channels": 1
@@ -37,10 +37,10 @@
             "pts_time": "0.000000",
             "dts": 0,
             "dts_time": "0.000000",
-            "duration": 1,
+            "duration": 2048,
             "duration_time": "0.040000",
             "size": "230400",
-            "pos": "2478",
+            "pos": "2647",
             "flags": "K"
         },
         {
@@ -51,9 +51,9 @@
             "pkt_pts_time": "0.000000",
             "pkt_dts": 0,
             "pkt_dts_time": "0.000000",
-            "pkt_duration": 1,
+            "pkt_duration": 2048,
             "pkt_duration_time": "0.040000",
-            "pkt_pos": "2478",
+            "pkt_pos": "2647",
             "width": 320,
             "height": 240,
             "pix_fmt": "rgb24",
@@ -74,10 +74,10 @@
             "pts_time": "0.000000",
             "dts": 0,
             "dts_time": "0.000000",
-            "duration": 1,
+            "duration": 2048,
             "duration_time": "0.040000",
             "size": "30000",
-            "pos": "232899",
+            "pos": "233068",
             "flags": "K"
         },
         {
@@ -88,9 +88,9 @@
             "pkt_pts_time": "0.000000",
             "pkt_dts": 0,
             "pkt_dts_time": "0.000000",
-            "pkt_duration": 1,
+            "pkt_duration": 2048,
             "pkt_duration_time": "0.040000",
-            "pkt_pos": "232899",
+            "pkt_pos": "233068",
             "width": 100,
             "height": 100,
             "pix_fmt": "rgb24",
@@ -114,7 +114,7 @@
             "duration": 1024,
             "duration_time": "0.023220",
             "size": "2048",
-            "pos": "262904",
+            "pos": "263073",
             "flags": "K"
         },
         {
@@ -127,7 +127,7 @@
             "pkt_dts_time": "0.023220",
             "pkt_duration": 1024,
             "pkt_duration_time": "0.023220",
-            "pkt_pos": "262904",
+            "pkt_pos": "263073",
             "sample_fmt": "s16",
             "nb_samples": 1024,
             "channels": 1
@@ -136,27 +136,27 @@
             "type": "packet",
             "codec_type": "video",
             "stream_index": 1,
-            "pts": 1,
+            "pts": 2048,
             "pts_time": "0.040000",
-            "dts": 1,
+            "dts": 2048,
             "dts_time": "0.040000",
-            "duration": 1,
+            "duration": 2048,
             "duration_time": "0.040000",
             "size": "230400",
-            "pos": "264980",
+            "pos": "265151",
             "flags": "K"
         },
         {
             "type": "frame",
             "media_type": "video",
             "key_frame": 1,
-            "pkt_pts": 1,
+            "pkt_pts": 2048,
             "pkt_pts_time": "0.040000",
-            "pkt_dts": 1,
+            "pkt_dts": 2048,
             "pkt_dts_time": "0.040000",
-            "pkt_duration": 1,
+            "pkt_duration": 2048,
             "pkt_duration_time": "0.040000",
-            "pkt_pos": "264980",
+            "pkt_pos": "265151",
             "width": 320,
             "height": 240,
             "pix_fmt": "rgb24",
@@ -173,27 +173,27 @@
             "type": "packet",
             "codec_type": "video",
             "stream_index": 2,
-            "pts": 1,
+            "pts": 2048,
             "pts_time": "0.040000",
-            "dts": 1,
+            "dts": 2048,
             "dts_time": "0.040000",
-            "duration": 1,
+            "duration": 2048,
             "duration_time": "0.040000",
             "size": "30000",
-            "pos": "495402",
+            "pos": "495575",
             "flags": "K"
         },
         {
             "type": "frame",
             "media_type": "video",
             "key_frame": 1,
-            "pkt_pts": 1,
+            "pkt_pts": 2048,
             "pkt_pts_time": "0.040000",
-            "pkt_dts": 1,
+            "pkt_dts": 2048,
             "pkt_dts_time": "0.040000",
-            "pkt_duration": 1,
+            "pkt_duration": 2048,
             "pkt_duration_time": "0.040000",
-            "pkt_pos": "495402",
+            "pkt_pos": "495575",
             "width": 100,
             "height": 100,
             "pix_fmt": "rgb24",
@@ -217,7 +217,7 @@
             "duration": 1024,
             "duration_time": "0.023220",
             "size": "2048",
-            "pos": "525407",
+            "pos": "525580",
             "flags": "K"
         },
         {
@@ -230,7 +230,7 @@
             "pkt_dts_time": "0.046440",
             "pkt_duration": 1024,
             "pkt_duration_time": "0.023220",
-            "pkt_pos": "525407",
+            "pkt_pos": "525580",
             "sample_fmt": "s16",
             "nb_samples": 1024,
             "channels": 1
@@ -246,7 +246,7 @@
             "duration": 1024,
             "duration_time": "0.023220",
             "size": "2048",
-            "pos": "527478",
+            "pos": "527651",
             "flags": "K"
         },
         {
@@ -259,7 +259,7 @@
             "pkt_dts_time": "0.069660",
             "pkt_duration": 1024,
             "pkt_duration_time": "0.023220",
-            "pkt_pos": "527478",
+            "pkt_pos": "527651",
             "sample_fmt": "s16",
             "nb_samples": 1024,
             "channels": 1
@@ -268,27 +268,27 @@
             "type": "packet",
             "codec_type": "video",
             "stream_index": 1,
-            "pts": 2,
+            "pts": 4096,
             "pts_time": "0.080000",
-            "dts": 2,
+            "dts": 4096,
             "dts_time": "0.080000",
-            "duration": 1,
+            "duration": 2048,
             "duration_time": "0.040000",
             "size": "230400",
-            "pos": "529554",
+            "pos": "529729",
             "flags": "K"
         },
         {
             "type": "frame",
             "media_type": "video",
             "key_frame": 1,
-            "pkt_pts": 2,
+            "pkt_pts": 4096,
             "pkt_pts_time": "0.080000",
-            "pkt_dts": 2,
+            "pkt_dts": 4096,
             "pkt_dts_time": "0.080000",
-            "pkt_duration": 1,
+            "pkt_duration": 2048,
             "pkt_duration_time": "0.040000",
-            "pkt_pos": "529554",
+            "pkt_pos": "529729",
             "width": 320,
             "height": 240,
             "pix_fmt": "rgb24",
@@ -305,27 +305,27 @@
             "type": "packet",
             "codec_type": "video",
             "stream_index": 2,
-            "pts": 2,
+            "pts": 4096,
             "pts_time": "0.080000",
-            "dts": 2,
+            "dts": 4096,
             "dts_time": "0.080000",
-            "duration": 1,
+            "duration": 2048,
             "duration_time": "0.040000",
             "size": "30000",
-            "pos": "759976",
+            "pos": "760153",
             "flags": "K"
         },
         {
             "type": "frame",
             "media_type": "video",
             "key_frame": 1,
-            "pkt_pts": 2,
+            "pkt_pts": 4096,
             "pkt_pts_time": "0.080000",
-            "pkt_dts": 2,
+            "pkt_dts": 4096,
             "pkt_dts_time": "0.080000",
-            "pkt_duration": 1,
+            "pkt_duration": 2048,
             "pkt_duration_time": "0.040000",
-            "pkt_pos": "759976",
+            "pkt_pos": "760153",
             "width": 100,
             "height": 100,
             "pix_fmt": "rgb24",
@@ -349,7 +349,7 @@
             "duration": 1024,
             "duration_time": "0.023220",
             "size": "2048",
-            "pos": "789981",
+            "pos": "790158",
             "flags": "K"
         },
         {
@@ -362,7 +362,7 @@
             "pkt_dts_time": "0.092880",
             "pkt_duration": 1024,
             "pkt_duration_time": "0.023220",
-            "pkt_pos": "789981",
+            "pkt_pos": "790158",
             "sample_fmt": "s16",
             "nb_samples": 1024,
             "channels": 1
@@ -378,7 +378,7 @@
             "duration": 1024,
             "duration_time": "0.023220",
             "size": "2048",
-            "pos": "792052",
+            "pos": "792229",
             "flags": "K"
         },
         {
@@ -391,7 +391,7 @@
             "pkt_dts_time": "0.116100",
             "pkt_duration": 1024,
             "pkt_duration_time": "0.023220",
-            "pkt_pos": "792052",
+            "pkt_pos": "792229",
             "sample_fmt": "s16",
             "nb_samples": 1024,
             "channels": 1
@@ -400,27 +400,27 @@
             "type": "packet",
             "codec_type": "video",
             "stream_index": 1,
-            "pts": 3,
+            "pts": 6144,
             "pts_time": "0.120000",
-            "dts": 3,
+            "dts": 6144,
             "dts_time": "0.120000",
-            "duration": 1,
+            "duration": 2048,
             "duration_time": "0.040000",
             "size": "230400",
-            "pos": "794128",
+            "pos": "794307",
             "flags": "K"
         },
         {
             "type": "frame",
             "media_type": "video",
             "key_frame": 1,
-            "pkt_pts": 3,
+            "pkt_pts": 6144,
             "pkt_pts_time": "0.120000",
-            "pkt_dts": 3,
+            "pkt_dts": 6144,
             "pkt_dts_time": "0.120000",
-            "pkt_duration": 1,
+            "pkt_duration": 2048,
             "pkt_duration_time": "0.040000",
-            "pkt_pos": "794128",
+            "pkt_pos": "794307",
             "width": 320,
             "height": 240,
             "pix_fmt": "rgb24",
@@ -437,27 +437,27 @@
             "type": "packet",
             "codec_type": "video",
             "stream_index": 2,
-            "pts": 3,
+            "pts": 6144,
             "pts_time": "0.120000",
-            "dts": 3,
+            "dts": 6144,
             "dts_time": "0.120000",
-            "duration": 1,
+            "duration": 2048,
             "duration_time": "0.040000",
             "size": "30000",
-            "pos": "1024550",
+            "pos": "1024731",
             "flags": "K"
         },
         {
             "type": "frame",
             "media_type": "video",
             "key_frame": 1,
-            "pkt_pts": 3,
+            "pkt_pts": 6144,
             "pkt_pts_time": "0.120000",
-            "pkt_dts": 3,
+            "pkt_dts": 6144,
             "pkt_dts_time": "0.120000",
-            "pkt_duration": 1,
+            "pkt_duration": 2048,
             "pkt_duration_time": "0.040000",
-            "pkt_pos": "1024550",
+            "pkt_pos": "1024731",
             "width": 100,
             "height": 100,
             "pix_fmt": "rgb24",
@@ -477,8 +477,8 @@
             "codec_name": "pcm_s16le",
             "codec_type": "audio",
             "codec_time_base": "1/44100",
-            "codec_tag_string": "[1][0][0][0]",
-            "codec_tag": "0x0001",
+            "codec_tag_string": "PSD[16]",
+            "codec_tag": "0x10445350",
             "sample_fmt": "s16",
             "sample_rate": "44100",
             "channels": 1,
@@ -488,8 +488,8 @@
             "time_base": "1/44100",
             "start_pts": 0,
             "start_time": "0.000000",
-            "duration_ts": 527313,
-            "duration": "11.957211",
+            "duration_ts": 527406,
+            "duration": "11.959320",
             "bit_rate": "705600",
             "nb_read_frames": "6",
             "nb_read_packets": "6",
@@ -505,13 +505,16 @@
                 "visual_impaired": 0,
                 "clean_effects": 0,
                 "attached_pic": 0
+            },
+            "tags": {
+                "E": "mc²"
             }
         },
         {
             "index": 1,
             "codec_name": "rawvideo",
             "codec_type": "video",
-            "codec_time_base": "1/25",
+            "codec_time_base": "1/51200",
             "codec_tag_string": "RGB[24]",
             "codec_tag": "0x18424752",
             "width": 320,
@@ -522,12 +525,12 @@
             "pix_fmt": "rgb24",
             "level": -99,
             "r_frame_rate": "25/1",
-            "avg_frame_rate": "0/0",
-            "time_base": "1/25",
+            "avg_frame_rate": "25/1",
+            "time_base": "1/51200",
             "start_pts": 0,
             "start_time": "0.000000",
-            "duration_ts": 299,
-            "duration": "11.960000",
+            "duration_ts": 612317,
+            "duration": "11.959316",
             "nb_read_frames": "4",
             "nb_read_packets": "4",
             "disposition": {
@@ -542,13 +545,17 @@
                 "visual_impaired": 0,
                 "clean_effects": 0,
                 "attached_pic": 0
+            },
+            "tags": {
+                "title": "foobar",
+                "duration_ts": "field-and-tags-conflict-attempt"
             }
         },
         {
             "index": 2,
             "codec_name": "rawvideo",
             "codec_type": "video",
-            "codec_time_base": "1/25",
+            "codec_time_base": "1/51200",
             "codec_tag_string": "RGB[24]",
             "codec_tag": "0x18424752",
             "width": 100,
@@ -559,12 +566,12 @@
             "pix_fmt": "rgb24",
             "level": -99,
             "r_frame_rate": "25/1",
-            "avg_frame_rate": "0/0",
-            "time_base": "1/25",
+            "avg_frame_rate": "25/1",
+            "time_base": "1/51200",
             "start_pts": 0,
             "start_time": "0.000000",
-            "duration_ts": 299,
-            "duration": "11.960000",
+            "duration_ts": 612317,
+            "duration": "11.959316",
             "nb_read_frames": "4",
             "nb_read_packets": "4",
             "disposition": {
@@ -587,9 +594,9 @@
         "nb_streams": 3,
         "format_name": "nut",
         "start_time": "0.000000",
-        "duration": "11.960000",
-        "size": "1054625",
-        "bit_rate": "705434",
+        "duration": "11.959320",
+        "size": "1054812",
+        "bit_rate": "705599",
         "tags": {
             "title": "ffprobe test file",
             "comment": "'A comment with CSV, XML & JSON special chars': <tag value=\"x\">",
diff --git a/tests/ref/fate/ffprobe_xml b/tests/ref/fate/ffprobe_xml
index 8308e42..ca0908e 100644
--- a/tests/ref/fate/ffprobe_xml
+++ b/tests/ref/fate/ffprobe_xml
@@ -1,49 +1,52 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <ffprobe>
     <packets_and_frames>
-        <packet codec_type="audio" stream_index="0" pts="0" pts_time="0.000000" dts="0" dts_time="0.000000" duration="1024" duration_time="0.023220" size="2048" pos="403" flags="K"/>
-        <frame media_type="audio" key_frame="1" pkt_pts="0" pkt_pts_time="0.000000" pkt_dts="0" pkt_dts_time="0.000000" pkt_duration="1024" pkt_duration_time="0.023220" pkt_pos="403" sample_fmt="s16" nb_samples="1024" channels="1"/>
-        <packet codec_type="video" stream_index="1" pts="0" pts_time="0.000000" dts="0" dts_time="0.000000" duration="1" duration_time="0.040000" size="230400" pos="2478" flags="K"/>
-        <frame media_type="video" key_frame="1" pkt_pts="0" pkt_pts_time="0.000000" pkt_dts="0" pkt_dts_time="0.000000" pkt_duration="1" pkt_duration_time="0.040000" pkt_pos="2478" width="320" height="240" pix_fmt="rgb24" sample_aspect_ratio="1:1" pict_type="I" coded_picture_number="0" display_picture_number="0" interlaced_frame="0" top_field_first="0" repeat_pict="0" reference="0"/>
-        <packet codec_type="video" stream_index="2" pts="0" pts_time="0.000000" dts="0" dts_time="0.000000" duration="1" duration_time="0.040000" size="30000" pos="232899" flags="K"/>
-        <frame media_type="video" key_frame="1" pkt_pts="0" pkt_pts_time="0.000000" pkt_dts="0" pkt_dts_time="0.000000" pkt_duration="1" pkt_duration_time="0.040000" pkt_pos="232899" width="100" height="100" pix_fmt="rgb24" sample_aspect_ratio="1:1" pict_type="I" coded_picture_number="0" display_picture_number="0" interlaced_frame="0" top_field_first="0" repeat_pict="0" reference="0"/>
-        <packet codec_type="audio" stream_index="0" pts="1024" pts_time="0.023220" dts="1024" dts_time="0.023220" duration="1024" duration_time="0.023220" size="2048" pos="262904" flags="K"/>
-        <frame media_type="audio" key_frame="1" pkt_pts="1024" pkt_pts_time="0.023220" pkt_dts="1024" pkt_dts_time="0.023220" pkt_duration="1024" pkt_duration_time="0.023220" pkt_pos="262904" sample_fmt="s16" nb_samples="1024" channels="1"/>
-        <packet codec_type="video" stream_index="1" pts="1" pts_time="0.040000" dts="1" dts_time="0.040000" duration="1" duration_time="0.040000" size="230400" pos="264980" flags="K"/>
-        <frame media_type="video" key_frame="1" pkt_pts="1" pkt_pts_time="0.040000" pkt_dts="1" pkt_dts_time="0.040000" pkt_duration="1" pkt_duration_time="0.040000" pkt_pos="264980" width="320" height="240" pix_fmt="rgb24" sample_aspect_ratio="1:1" pict_type="I" coded_picture_number="0" display_picture_number="0" interlaced_frame="0" top_field_first="0" repeat_pict="0" reference="0"/>
-        <packet codec_type="video" stream_index="2" pts="1" pts_time="0.040000" dts="1" dts_time="0.040000" duration="1" duration_time="0.040000" size="30000" pos="495402" flags="K"/>
-        <frame media_type="video" key_frame="1" pkt_pts="1" pkt_pts_time="0.040000" pkt_dts="1" pkt_dts_time="0.040000" pkt_duration="1" pkt_duration_time="0.040000" pkt_pos="495402" width="100" height="100" pix_fmt="rgb24" sample_aspect_ratio="1:1" pict_type="I" coded_picture_number="0" display_picture_number="0" interlaced_frame="0" top_field_first="0" repeat_pict="0" reference="0"/>
-        <packet codec_type="audio" stream_index="0" pts="2048" pts_time="0.046440" dts="2048" dts_time="0.046440" duration="1024" duration_time="0.023220" size="2048" pos="525407" flags="K"/>
-        <frame media_type="audio" key_frame="1" pkt_pts="2048" pkt_pts_time="0.046440" pkt_dts="2048" pkt_dts_time="0.046440" pkt_duration="1024" pkt_duration_time="0.023220" pkt_pos="525407" sample_fmt="s16" nb_samples="1024" channels="1"/>
-        <packet codec_type="audio" stream_index="0" pts="3072" pts_time="0.069660" dts="3072" dts_time="0.069660" duration="1024" duration_time="0.023220" size="2048" pos="527478" flags="K"/>
-        <frame media_type="audio" key_frame="1" pkt_pts="3072" pkt_pts_time="0.069660" pkt_dts="3072" pkt_dts_time="0.069660" pkt_duration="1024" pkt_duration_time="0.023220" pkt_pos="527478" sample_fmt="s16" nb_samples="1024" channels="1"/>
-        <packet codec_type="video" stream_index="1" pts="2" pts_time="0.080000" dts="2" dts_time="0.080000" duration="1" duration_time="0.040000" size="230400" pos="529554" flags="K"/>
-        <frame media_type="video" key_frame="1" pkt_pts="2" pkt_pts_time="0.080000" pkt_dts="2" pkt_dts_time="0.080000" pkt_duration="1" pkt_duration_time="0.040000" pkt_pos="529554" width="320" height="240" pix_fmt="rgb24" sample_aspect_ratio="1:1" pict_type="I" coded_picture_number="0" display_picture_number="0" interlaced_frame="0" top_field_first="0" repeat_pict="0" reference="0"/>
-        <packet codec_type="video" stream_index="2" pts="2" pts_time="0.080000" dts="2" dts_time="0.080000" duration="1" duration_time="0.040000" size="30000" pos="759976" flags="K"/>
-        <frame media_type="video" key_frame="1" pkt_pts="2" pkt_pts_time="0.080000" pkt_dts="2" pkt_dts_time="0.080000" pkt_duration="1" pkt_duration_time="0.040000" pkt_pos="759976" width="100" height="100" pix_fmt="rgb24" sample_aspect_ratio="1:1" pict_type="I" coded_picture_number="0" display_picture_number="0" interlaced_frame="0" top_field_first="0" repeat_pict="0" reference="0"/>
-        <packet codec_type="audio" stream_index="0" pts="4096" pts_time="0.092880" dts="4096" dts_time="0.092880" duration="1024" duration_time="0.023220" size="2048" pos="789981" flags="K"/>
-        <frame media_type="audio" key_frame="1" pkt_pts="4096" pkt_pts_time="0.092880" pkt_dts="4096" pkt_dts_time="0.092880" pkt_duration="1024" pkt_duration_time="0.023220" pkt_pos="789981" sample_fmt="s16" nb_samples="1024" channels="1"/>
-        <packet codec_type="audio" stream_index="0" pts="5120" pts_time="0.116100" dts="5120" dts_time="0.116100" duration="1024" duration_time="0.023220" size="2048" pos="792052" flags="K"/>
-        <frame media_type="audio" key_frame="1" pkt_pts="5120" pkt_pts_time="0.116100" pkt_dts="5120" pkt_dts_time="0.116100" pkt_duration="1024" pkt_duration_time="0.023220" pkt_pos="792052" sample_fmt="s16" nb_samples="1024" channels="1"/>
-        <packet codec_type="video" stream_index="1" pts="3" pts_time="0.120000" dts="3" dts_time="0.120000" duration="1" duration_time="0.040000" size="230400" pos="794128" flags="K"/>
-        <frame media_type="video" key_frame="1" pkt_pts="3" pkt_pts_time="0.120000" pkt_dts="3" pkt_dts_time="0.120000" pkt_duration="1" pkt_duration_time="0.040000" pkt_pos="794128" width="320" height="240" pix_fmt="rgb24" sample_aspect_ratio="1:1" pict_type="I" coded_picture_number="0" display_picture_number="0" interlaced_frame="0" top_field_first="0" repeat_pict="0" reference="0"/>
-        <packet codec_type="video" stream_index="2" pts="3" pts_time="0.120000" dts="3" dts_time="0.120000" duration="1" duration_time="0.040000" size="30000" pos="1024550" flags="K"/>
-        <frame media_type="video" key_frame="1" pkt_pts="3" pkt_pts_time="0.120000" pkt_dts="3" pkt_dts_time="0.120000" pkt_duration="1" pkt_duration_time="0.040000" pkt_pos="1024550" width="100" height="100" pix_fmt="rgb24" sample_aspect_ratio="1:1" pict_type="I" coded_picture_number="0" display_picture_number="0" interlaced_frame="0" top_field_first="0" repeat_pict="0" reference="0"/>
+        <packet codec_type="audio" stream_index="0" pts="0" pts_time="0.000000" dts="0" dts_time="0.000000" duration="1024" duration_time="0.023220" size="2048" pos="572" flags="K"/>
+        <frame media_type="audio" key_frame="1" pkt_pts="0" pkt_pts_time="0.000000" pkt_dts="0" pkt_dts_time="0.000000" pkt_duration="1024" pkt_duration_time="0.023220" pkt_pos="572" sample_fmt="s16" nb_samples="1024" channels="1"/>
+        <packet codec_type="video" stream_index="1" pts="0" pts_time="0.000000" dts="0" dts_time="0.000000" duration="2048" duration_time="0.040000" size="230400" pos="2647" flags="K"/>
+        <frame media_type="video" key_frame="1" pkt_pts="0" pkt_pts_time="0.000000" pkt_dts="0" pkt_dts_time="0.000000" pkt_duration="2048" pkt_duration_time="0.040000" pkt_pos="2647" width="320" height="240" pix_fmt="rgb24" sample_aspect_ratio="1:1" pict_type="I" coded_picture_number="0" display_picture_number="0" interlaced_frame="0" top_field_first="0" repeat_pict="0" reference="0"/>
+        <packet codec_type="video" stream_index="2" pts="0" pts_time="0.000000" dts="0" dts_time="0.000000" duration="2048" duration_time="0.040000" size="30000" pos="233068" flags="K"/>
+        <frame media_type="video" key_frame="1" pkt_pts="0" pkt_pts_time="0.000000" pkt_dts="0" pkt_dts_time="0.000000" pkt_duration="2048" pkt_duration_time="0.040000" pkt_pos="233068" width="100" height="100" pix_fmt="rgb24" sample_aspect_ratio="1:1" pict_type="I" coded_picture_number="0" display_picture_number="0" interlaced_frame="0" top_field_first="0" repeat_pict="0" reference="0"/>
+        <packet codec_type="audio" stream_index="0" pts="1024" pts_time="0.023220" dts="1024" dts_time="0.023220" duration="1024" duration_time="0.023220" size="2048" pos="263073" flags="K"/>
+        <frame media_type="audio" key_frame="1" pkt_pts="1024" pkt_pts_time="0.023220" pkt_dts="1024" pkt_dts_time="0.023220" pkt_duration="1024" pkt_duration_time="0.023220" pkt_pos="263073" sample_fmt="s16" nb_samples="1024" channels="1"/>
+        <packet codec_type="video" stream_index="1" pts="2048" pts_time="0.040000" dts="2048" dts_time="0.040000" duration="2048" duration_time="0.040000" size="230400" pos="265151" flags="K"/>
+        <frame media_type="video" key_frame="1" pkt_pts="2048" pkt_pts_time="0.040000" pkt_dts="2048" pkt_dts_time="0.040000" pkt_duration="2048" pkt_duration_time="0.040000" pkt_pos="265151" width="320" height="240" pix_fmt="rgb24" sample_aspect_ratio="1:1" pict_type="I" coded_picture_number="0" display_picture_number="0" interlaced_frame="0" top_field_first="0" repeat_pict="0" reference="0"/>
+        <packet codec_type="video" stream_index="2" pts="2048" pts_time="0.040000" dts="2048" dts_time="0.040000" duration="2048" duration_time="0.040000" size="30000" pos="495575" flags="K"/>
+        <frame media_type="video" key_frame="1" pkt_pts="2048" pkt_pts_time="0.040000" pkt_dts="2048" pkt_dts_time="0.040000" pkt_duration="2048" pkt_duration_time="0.040000" pkt_pos="495575" width="100" height="100" pix_fmt="rgb24" sample_aspect_ratio="1:1" pict_type="I" coded_picture_number="0" display_picture_number="0" interlaced_frame="0" top_field_first="0" repeat_pict="0" reference="0"/>
+        <packet codec_type="audio" stream_index="0" pts="2048" pts_time="0.046440" dts="2048" dts_time="0.046440" duration="1024" duration_time="0.023220" size="2048" pos="525580" flags="K"/>
+        <frame media_type="audio" key_frame="1" pkt_pts="2048" pkt_pts_time="0.046440" pkt_dts="2048" pkt_dts_time="0.046440" pkt_duration="1024" pkt_duration_time="0.023220" pkt_pos="525580" sample_fmt="s16" nb_samples="1024" channels="1"/>
+        <packet codec_type="audio" stream_index="0" pts="3072" pts_time="0.069660" dts="3072" dts_time="0.069660" duration="1024" duration_time="0.023220" size="2048" pos="527651" flags="K"/>
+        <frame media_type="audio" key_frame="1" pkt_pts="3072" pkt_pts_time="0.069660" pkt_dts="3072" pkt_dts_time="0.069660" pkt_duration="1024" pkt_duration_time="0.023220" pkt_pos="527651" sample_fmt="s16" nb_samples="1024" channels="1"/>
+        <packet codec_type="video" stream_index="1" pts="4096" pts_time="0.080000" dts="4096" dts_time="0.080000" duration="2048" duration_time="0.040000" size="230400" pos="529729" flags="K"/>
+        <frame media_type="video" key_frame="1" pkt_pts="4096" pkt_pts_time="0.080000" pkt_dts="4096" pkt_dts_time="0.080000" pkt_duration="2048" pkt_duration_time="0.040000" pkt_pos="529729" width="320" height="240" pix_fmt="rgb24" sample_aspect_ratio="1:1" pict_type="I" coded_picture_number="0" display_picture_number="0" interlaced_frame="0" top_field_first="0" repeat_pict="0" reference="0"/>
+        <packet codec_type="video" stream_index="2" pts="4096" pts_time="0.080000" dts="4096" dts_time="0.080000" duration="2048" duration_time="0.040000" size="30000" pos="760153" flags="K"/>
+        <frame media_type="video" key_frame="1" pkt_pts="4096" pkt_pts_time="0.080000" pkt_dts="4096" pkt_dts_time="0.080000" pkt_duration="2048" pkt_duration_time="0.040000" pkt_pos="760153" width="100" height="100" pix_fmt="rgb24" sample_aspect_ratio="1:1" pict_type="I" coded_picture_number="0" display_picture_number="0" interlaced_frame="0" top_field_first="0" repeat_pict="0" reference="0"/>
+        <packet codec_type="audio" stream_index="0" pts="4096" pts_time="0.092880" dts="4096" dts_time="0.092880" duration="1024" duration_time="0.023220" size="2048" pos="790158" flags="K"/>
+        <frame media_type="audio" key_frame="1" pkt_pts="4096" pkt_pts_time="0.092880" pkt_dts="4096" pkt_dts_time="0.092880" pkt_duration="1024" pkt_duration_time="0.023220" pkt_pos="790158" sample_fmt="s16" nb_samples="1024" channels="1"/>
+        <packet codec_type="audio" stream_index="0" pts="5120" pts_time="0.116100" dts="5120" dts_time="0.116100" duration="1024" duration_time="0.023220" size="2048" pos="792229" flags="K"/>
+        <frame media_type="audio" key_frame="1" pkt_pts="5120" pkt_pts_time="0.116100" pkt_dts="5120" pkt_dts_time="0.116100" pkt_duration="1024" pkt_duration_time="0.023220" pkt_pos="792229" sample_fmt="s16" nb_samples="1024" channels="1"/>
+        <packet codec_type="video" stream_index="1" pts="6144" pts_time="0.120000" dts="6144" dts_time="0.120000" duration="2048" duration_time="0.040000" size="230400" pos="794307" flags="K"/>
+        <frame media_type="video" key_frame="1" pkt_pts="6144" pkt_pts_time="0.120000" pkt_dts="6144" pkt_dts_time="0.120000" pkt_duration="2048" pkt_duration_time="0.040000" pkt_pos="794307" width="320" height="240" pix_fmt="rgb24" sample_aspect_ratio="1:1" pict_type="I" coded_picture_number="0" display_picture_number="0" interlaced_frame="0" top_field_first="0" repeat_pict="0" reference="0"/>
+        <packet codec_type="video" stream_index="2" pts="6144" pts_time="0.120000" dts="6144" dts_time="0.120000" duration="2048" duration_time="0.040000" size="30000" pos="1024731" flags="K"/>
+        <frame media_type="video" key_frame="1" pkt_pts="6144" pkt_pts_time="0.120000" pkt_dts="6144" pkt_dts_time="0.120000" pkt_duration="2048" pkt_duration_time="0.040000" pkt_pos="1024731" width="100" height="100" pix_fmt="rgb24" sample_aspect_ratio="1:1" pict_type="I" coded_picture_number="0" display_picture_number="0" interlaced_frame="0" top_field_first="0" repeat_pict="0" reference="0"/>
     </packets_and_frames>
 
     <streams>
-        <stream index="0" codec_name="pcm_s16le" codec_type="audio" codec_time_base="1/44100" codec_tag_string="[1][0][0][0]" codec_tag="0x0001" sample_fmt="s16" sample_rate="44100" channels="1" bits_per_sample="16" r_frame_rate="0/0" avg_frame_rate="0/0" time_base="1/44100" start_pts="0" start_time="0.000000" duration_ts="527313" duration="11.957211" bit_rate="705600" nb_read_frames="6" nb_read_packets="6">
+        <stream index="0" codec_name="pcm_s16le" codec_type="audio" codec_time_base="1/44100" codec_tag_string="PSD[16]" codec_tag="0x10445350" sample_fmt="s16" sample_rate="44100" channels="1" bits_per_sample="16" r_frame_rate="0/0" avg_frame_rate="0/0" time_base="1/44100" start_pts="0" start_time="0.000000" duration_ts="527406" duration="11.959320" bit_rate="705600" nb_read_frames="6" nb_read_packets="6">
             <disposition default="0" dub="0" original="0" comment="0" lyrics="0" karaoke="0" forced="0" hearing_impaired="0" visual_impaired="0" clean_effects="0" attached_pic="0"/>
+            <tag key="E" value="mc²"/>
         </stream>
-        <stream index="1" codec_name="rawvideo" codec_type="video" codec_time_base="1/25" codec_tag_string="RGB[24]" codec_tag="0x18424752" width="320" height="240" has_b_frames="0" sample_aspect_ratio="1:1" display_aspect_ratio="4:3" pix_fmt="rgb24" level="-99" r_frame_rate="25/1" avg_frame_rate="0/0" time_base="1/25" start_pts="0" start_time="0.000000" duration_ts="299" duration="11.960000" nb_read_frames="4" nb_read_packets="4">
+        <stream index="1" codec_name="rawvideo" codec_type="video" codec_time_base="1/51200" codec_tag_string="RGB[24]" codec_tag="0x18424752" width="320" height="240" has_b_frames="0" sample_aspect_ratio="1:1" display_aspect_ratio="4:3" pix_fmt="rgb24" level="-99" r_frame_rate="25/1" avg_frame_rate="25/1" time_base="1/51200" start_pts="0" start_time="0.000000" duration_ts="612317" duration="11.959316" nb_read_frames="4" nb_read_packets="4">
             <disposition default="0" dub="0" original="0" comment="0" lyrics="0" karaoke="0" forced="0" hearing_impaired="0" visual_impaired="0" clean_effects="0" attached_pic="0"/>
+            <tag key="title" value="foobar"/>
+            <tag key="duration_ts" value="field-and-tags-conflict-attempt"/>
         </stream>
-        <stream index="2" codec_name="rawvideo" codec_type="video" codec_time_base="1/25" codec_tag_string="RGB[24]" codec_tag="0x18424752" width="100" height="100" has_b_frames="0" sample_aspect_ratio="1:1" display_aspect_ratio="1:1" pix_fmt="rgb24" level="-99" r_frame_rate="25/1" avg_frame_rate="0/0" time_base="1/25" start_pts="0" start_time="0.000000" duration_ts="299" duration="11.960000" nb_read_frames="4" nb_read_packets="4">
+        <stream index="2" codec_name="rawvideo" codec_type="video" codec_time_base="1/51200" codec_tag_string="RGB[24]" codec_tag="0x18424752" width="100" height="100" has_b_frames="0" sample_aspect_ratio="1:1" display_aspect_ratio="1:1" pix_fmt="rgb24" level="-99" r_frame_rate="25/1" avg_frame_rate="25/1" time_base="1/51200" start_pts="0" start_time="0.000000" duration_ts="612317" duration="11.959316" nb_read_frames="4" nb_read_packets="4">
             <disposition default="0" dub="0" original="0" comment="0" lyrics="0" karaoke="0" forced="0" hearing_impaired="0" visual_impaired="0" clean_effects="0" attached_pic="0"/>
         </stream>
     </streams>
 
-    <format filename="tests/data/ffprobe-test.nut" nb_streams="3" format_name="nut" start_time="0.000000" duration="11.960000" size="1054625" bit_rate="705434">
+    <format filename="tests/data/ffprobe-test.nut" nb_streams="3" format_name="nut" start_time="0.000000" duration="11.959320" size="1054812" bit_rate="705599">
         <tag key="title" value="ffprobe test file"/>
         <tag key="comment" value="&apos;A comment with CSV, XML &amp; JSON special chars&apos;: &lt;tag value=&quot;x&quot;&gt;"/>
         <tag key="comment2" value="I ♥ Üñîçød€"/>
diff --git a/tests/ref/fate/filter-metadata-scenedetect b/tests/ref/fate/filter-metadata-scenedetect
new file mode 100644
index 0000000..0b344d9
--- /dev/null
+++ b/tests/ref/fate/filter-metadata-scenedetect
@@ -0,0 +1,10 @@
+video|1|1620|2.700000|1620|2.700000|1|0.001667|155751|320|240|rgb24|1:1|I|0|0|0|0|0|0|1.000000
+video|1|4140|6.900000|4140|6.900000|1|0.001667|808205|320|240|rgb24|1:1|I|0|0|0|0|0|0|0.880000
+video|1|5800|9.666667|5800|9.666667|1|0.001667|928577|320|240|rgb24|1:1|I|0|0|0|0|0|0|1.000000
+video|1|6720|11.200000|6720|11.200000|1|0.001667|1027359|320|240|rgb24|1:1|I|0|0|0|0|0|0|0.460000
+video|1|8160|13.600000|8160|13.600000|1|0.001667|1247869|320|240|rgb24|1:1|I|0|0|0|0|0|0|1.000000
+video|1|9760|16.266667|9760|16.266667|1|0.001667|1337561|320|240|rgb24|1:1|I|0|0|0|0|0|0|1.000000
+video|1|14080|23.466667|14080|23.466667|1|0.001667|1994159|320|240|rgb24|1:1|I|0|0|0|0|0|0|0.840000
+video|1|15700|26.166667|15700|26.166667|1|0.001667|2145781|320|240|rgb24|1:1|I|0|0|0|0|0|0|1.000000
+video|1|18500|30.833333|18500|30.833333|1|0.001667|2507729|320|240|rgb24|1:1|I|0|0|0|0|0|0|0.470000
+video|1|21760|36.266667|21760|36.266667|1|0.001667|2932267|320|240|rgb24|1:1|I|0|0|0|0|0|0|1.000000
diff --git a/tests/ref/fate/filter-metadata-silencedetect b/tests/ref/fate/filter-metadata-silencedetect
new file mode 100644
index 0000000..903d69e
--- /dev/null
+++ b/tests/ref/fate/filter-metadata-silencedetect
@@ -0,0 +1,512 @@
+audio|1|0|0.000000|0|0.000000|320|0.020000|44|dbl|320|1|mono
+audio|1|320|0.020000|320|0.020000|320|0.020000|77|dbl|320|1|mono
+audio|1|640|0.040000|640|0.040000|320|0.020000|110|dbl|320|1|mono
+audio|1|960|0.060000|960|0.060000|320|0.020000|143|dbl|320|1|mono
+audio|1|1280|0.080000|1280|0.080000|320|0.020000|176|dbl|320|1|mono
+audio|1|1600|0.100000|1600|0.100000|320|0.020000|209|dbl|320|1|mono
+audio|1|1920|0.120000|1920|0.120000|324|0.020250|242|dbl|320|1|mono|0.02
+audio|1|2240|0.140000|2240|0.140000|320|0.020000|275|dbl|320|1|mono
+audio|1|2560|0.160000|2560|0.160000|328|0.020500|308|dbl|320|1|mono|0.16|0.14
+audio|1|2880|0.180000|2880|0.180000|320|0.020000|341|dbl|320|1|mono
+audio|1|3200|0.200000|3200|0.200000|320|0.020000|374|dbl|320|1|mono
+audio|1|3520|0.220000|3520|0.220000|320|0.020000|407|dbl|320|1|mono
+audio|1|3840|0.240000|3840|0.240000|320|0.020000|440|dbl|320|1|mono
+audio|1|4160|0.260000|4160|0.260000|320|0.020000|473|dbl|320|1|mono
+audio|1|4480|0.280000|4480|0.280000|320|0.020000|506|dbl|320|1|mono
+audio|1|4800|0.300000|4800|0.300000|320|0.020000|539|dbl|320|1|mono
+audio|1|5120|0.320000|5120|0.320000|320|0.020000|572|dbl|320|1|mono
+audio|1|5440|0.340000|5440|0.340000|320|0.020000|605|dbl|320|1|mono
+audio|1|5760|0.360000|5760|0.360000|331|0.020688|638|dbl|320|1|mono|0.26|0.36|0.1
+audio|1|6080|0.380000|6080|0.380000|320|0.020000|671|dbl|320|1|mono
+audio|1|6400|0.400000|6400|0.400000|320|0.020000|704|dbl|320|1|mono
+audio|1|6720|0.420000|6720|0.420000|320|0.020000|737|dbl|320|1|mono
+audio|1|7040|0.440000|7040|0.440000|320|0.020000|770|dbl|320|1|mono
+audio|1|7360|0.460000|7360|0.460000|320|0.020000|803|dbl|320|1|mono
+audio|1|7680|0.480000|7680|0.480000|320|0.020000|836|dbl|320|1|mono
+audio|1|8000|0.500000|8000|0.500000|320|0.020000|869|dbl|320|1|mono
+audio|1|8320|0.520000|8320|0.520000|320|0.020000|902|dbl|320|1|mono
+audio|1|8640|0.540000|8640|0.540000|320|0.020000|935|dbl|320|1|mono
+audio|1|8960|0.560000|8960|0.560000|320|0.020000|968|dbl|320|1|mono
+audio|1|9280|0.580000|9280|0.580000|320|0.020000|1001|dbl|320|1|mono
+audio|1|9600|0.600000|9600|0.600000|320|0.020000|1034|dbl|320|1|mono
+audio|1|9920|0.620000|9920|0.620000|320|0.020000|1067|dbl|320|1|mono
+audio|1|10240|0.640000|10240|0.640000|320|0.020000|1100|dbl|320|1|mono
+audio|1|10560|0.660000|10560|0.660000|320|0.020000|1133|dbl|320|1|mono
+audio|1|10880|0.680000|10880|0.680000|320|0.020000|1166|dbl|320|1|mono
+audio|1|11200|0.700000|11200|0.700000|320|0.020000|1199|dbl|320|1|mono
+audio|1|11520|0.720000|11520|0.720000|320|0.020000|1232|dbl|320|1|mono
+audio|1|11840|0.740000|11840|0.740000|320|0.020000|1265|dbl|320|1|mono
+audio|1|12160|0.760000|12160|0.760000|320|0.020000|1298|dbl|320|1|mono
+audio|1|12480|0.780000|12480|0.780000|320|0.020000|1331|dbl|320|1|mono
+audio|1|12800|0.800000|12800|0.800000|320|0.020000|1364|dbl|320|1|mono
+audio|1|13120|0.820000|13120|0.820000|320|0.020000|1397|dbl|320|1|mono
+audio|1|13440|0.840000|13440|0.840000|320|0.020000|1430|dbl|320|1|mono
+audio|1|13760|0.860000|13760|0.860000|320|0.020000|1463|dbl|320|1|mono
+audio|1|14080|0.880000|14080|0.880000|320|0.020000|1496|dbl|320|1|mono
+audio|1|14400|0.900000|14400|0.900000|320|0.020000|1529|dbl|320|1|mono
+audio|1|14720|0.920000|14720|0.920000|320|0.020000|1562|dbl|320|1|mono
+audio|1|15040|0.940000|15040|0.940000|320|0.020000|1595|dbl|320|1|mono
+audio|1|15360|0.960000|15360|0.960000|320|0.020000|1628|dbl|320|1|mono
+audio|1|15680|0.980000|15680|0.980000|320|0.020000|1661|dbl|320|1|mono
+audio|1|16000|1.000000|16000|1.000000|320|0.020000|1694|dbl|320|1|mono
+audio|1|16320|1.020000|16320|1.020000|320|0.020000|1727|dbl|320|1|mono
+audio|1|16640|1.040000|16640|1.040000|320|0.020000|1760|dbl|320|1|mono
+audio|1|16960|1.060000|16960|1.060000|320|0.020000|1793|dbl|320|1|mono
+audio|1|17280|1.080000|17280|1.080000|320|0.020000|1826|dbl|320|1|mono
+audio|1|17600|1.100000|17600|1.100000|320|0.020000|1859|dbl|320|1|mono
+audio|1|17920|1.120000|17920|1.120000|320|0.020000|1892|dbl|320|1|mono
+audio|1|18240|1.140000|18240|1.140000|320|0.020000|1925|dbl|320|1|mono
+audio|1|18560|1.160000|18560|1.160000|320|0.020000|1958|dbl|320|1|mono
+audio|1|18880|1.180000|18880|1.180000|320|0.020000|1991|dbl|320|1|mono
+audio|1|19200|1.200000|19200|1.200000|320|0.020000|2024|dbl|320|1|mono
+audio|1|19520|1.220000|19520|1.220000|320|0.020000|2057|dbl|320|1|mono
+audio|1|19840|1.240000|19840|1.240000|320|0.020000|2090|dbl|320|1|mono
+audio|1|20160|1.260000|20160|1.260000|320|0.020000|2123|dbl|320|1|mono
+audio|1|20480|1.280000|20480|1.280000|320|0.020000|2156|dbl|320|1|mono
+audio|1|20800|1.300000|20800|1.300000|320|0.020000|2189|dbl|320|1|mono
+audio|1|21120|1.320000|21120|1.320000|320|0.020000|2222|dbl|320|1|mono
+audio|1|21440|1.340000|21440|1.340000|320|0.020000|2255|dbl|320|1|mono
+audio|1|21760|1.360000|21760|1.360000|320|0.020000|2288|dbl|320|1|mono
+audio|1|22080|1.380000|22080|1.380000|324|0.020250|2321|dbl|320|1|mono|1.28
+audio|1|22400|1.400000|22400|1.400000|320|0.020000|2354|dbl|320|1|mono
+audio|1|22720|1.420000|22720|1.420000|320|0.020000|2387|dbl|320|1|mono
+audio|1|23040|1.440000|23040|1.440000|320|0.020000|2420|dbl|320|1|mono
+audio|1|23360|1.460000|23360|1.460000|320|0.020000|2453|dbl|320|1|mono
+audio|1|23680|1.480000|23680|1.480000|320|0.020000|2486|dbl|320|1|mono
+audio|1|24000|1.500000|24000|1.500000|320|0.020000|2519|dbl|320|1|mono
+audio|1|24320|1.520000|24320|1.520000|320|0.020000|2552|dbl|320|1|mono
+audio|1|24640|1.540000|24640|1.540000|320|0.020000|2585|dbl|320|1|mono
+audio|1|24960|1.560000|24960|1.560000|320|0.020000|2618|dbl|320|1|mono
+audio|1|25280|1.580000|25280|1.580000|320|0.020000|2651|dbl|320|1|mono
+audio|1|25600|1.600000|25600|1.600000|320|0.020000|2684|dbl|320|1|mono
+audio|1|25920|1.620000|25920|1.620000|320|0.020000|2717|dbl|320|1|mono
+audio|1|26240|1.640000|26240|1.640000|320|0.020000|2750|dbl|320|1|mono
+audio|1|26560|1.660000|26560|1.660000|320|0.020000|2783|dbl|320|1|mono
+audio|1|26880|1.680000|26880|1.680000|320|0.020000|2816|dbl|320|1|mono
+audio|1|27200|1.700000|27200|1.700000|320|0.020000|2849|dbl|320|1|mono
+audio|1|27520|1.720000|27520|1.720000|320|0.020000|2882|dbl|320|1|mono
+audio|1|27840|1.740000|27840|1.740000|320|0.020000|2915|dbl|320|1|mono
+audio|1|28160|1.760000|28160|1.760000|320|0.020000|2948|dbl|320|1|mono
+audio|1|28480|1.780000|28480|1.780000|320|0.020000|2981|dbl|320|1|mono
+audio|1|28800|1.800000|28800|1.800000|320|0.020000|3014|dbl|320|1|mono
+audio|1|29120|1.820000|29120|1.820000|320|0.020000|3047|dbl|320|1|mono
+audio|1|29440|1.840000|29440|1.840000|320|0.020000|3080|dbl|320|1|mono
+audio|1|29760|1.860000|29760|1.860000|320|0.020000|3113|dbl|320|1|mono
+audio|1|30080|1.880000|30080|1.880000|320|0.020000|3146|dbl|320|1|mono
+audio|1|30400|1.900000|30400|1.900000|320|0.020000|3179|dbl|320|1|mono
+audio|1|30720|1.920000|30720|1.920000|320|0.020000|3212|dbl|320|1|mono
+audio|1|31040|1.940000|31040|1.940000|320|0.020000|3245|dbl|320|1|mono
+audio|1|31360|1.960000|31360|1.960000|320|0.020000|3278|dbl|320|1|mono
+audio|1|31680|1.980000|31680|1.980000|327|0.020438|3311|dbl|320|1|mono|1.98|0.7
+audio|1|32000|2.000000|32000|2.000000|320|0.020000|3344|dbl|320|1|mono
+audio|1|32320|2.020000|32320|2.020000|320|0.020000|3377|dbl|320|1|mono
+audio|1|32640|2.040000|32640|2.040000|320|0.020000|3410|dbl|320|1|mono
+audio|1|32960|2.060000|32960|2.060000|320|0.020000|3443|dbl|320|1|mono
+audio|1|33280|2.080000|33280|2.080000|320|0.020000|3476|dbl|320|1|mono
+audio|1|33600|2.100000|33600|2.100000|320|0.020000|3509|dbl|320|1|mono
+audio|1|33920|2.120000|33920|2.120000|320|0.020000|3542|dbl|320|1|mono
+audio|1|34240|2.140000|34240|2.140000|320|0.020000|3575|dbl|320|1|mono
+audio|1|34560|2.160000|34560|2.160000|320|0.020000|3608|dbl|320|1|mono
+audio|1|34880|2.180000|34880|2.180000|320|0.020000|3641|dbl|320|1|mono
+audio|1|35200|2.200000|35200|2.200000|320|0.020000|3674|dbl|320|1|mono
+audio|1|35520|2.220000|35520|2.220000|320|0.020000|3707|dbl|320|1|mono
+audio|1|35840|2.240000|35840|2.240000|320|0.020000|3740|dbl|320|1|mono
+audio|1|36160|2.260000|36160|2.260000|320|0.020000|3773|dbl|320|1|mono
+audio|1|36480|2.280000|36480|2.280000|320|0.020000|3806|dbl|320|1|mono
+audio|1|36800|2.300000|36800|2.300000|320|0.020000|3839|dbl|320|1|mono
+audio|1|37120|2.320000|37120|2.320000|320|0.020000|3872|dbl|320|1|mono
+audio|1|37440|2.340000|37440|2.340000|320|0.020000|3905|dbl|320|1|mono
+audio|1|37760|2.360000|37760|2.360000|320|0.020000|3938|dbl|320|1|mono
+audio|1|38080|2.380000|38080|2.380000|320|0.020000|3971|dbl|320|1|mono
+audio|1|38400|2.400000|38400|2.400000|320|0.020000|4004|dbl|320|1|mono
+audio|1|38720|2.420000|38720|2.420000|320|0.020000|4037|dbl|320|1|mono
+audio|1|39040|2.440000|39040|2.440000|320|0.020000|4070|dbl|320|1|mono
+audio|1|39360|2.460000|39360|2.460000|320|0.020000|4103|dbl|320|1|mono
+audio|1|39680|2.480000|39680|2.480000|320|0.020000|4136|dbl|320|1|mono
+audio|1|40000|2.500000|40000|2.500000|320|0.020000|4169|dbl|320|1|mono
+audio|1|40320|2.520000|40320|2.520000|320|0.020000|4202|dbl|320|1|mono
+audio|1|40640|2.540000|40640|2.540000|320|0.020000|4235|dbl|320|1|mono
+audio|1|40960|2.560000|40960|2.560000|320|0.020000|4268|dbl|320|1|mono
+audio|1|41280|2.580000|41280|2.580000|320|0.020000|4301|dbl|320|1|mono
+audio|1|41600|2.600000|41600|2.600000|320|0.020000|4334|dbl|320|1|mono
+audio|1|41920|2.620000|41920|2.620000|320|0.020000|4367|dbl|320|1|mono
+audio|1|42240|2.640000|42240|2.640000|320|0.020000|4400|dbl|320|1|mono
+audio|1|42560|2.660000|42560|2.660000|320|0.020000|4433|dbl|320|1|mono
+audio|1|42880|2.680000|42880|2.680000|320|0.020000|4466|dbl|320|1|mono
+audio|1|43200|2.700000|43200|2.700000|320|0.020000|4499|dbl|320|1|mono
+audio|1|43520|2.720000|43520|2.720000|320|0.020000|4532|dbl|320|1|mono
+audio|1|43840|2.740000|43840|2.740000|320|0.020000|4565|dbl|320|1|mono
+audio|1|44160|2.760000|44160|2.760000|320|0.020000|4598|dbl|320|1|mono
+audio|1|44480|2.780000|44480|2.780000|320|0.020000|4631|dbl|320|1|mono
+audio|1|44800|2.800000|44800|2.800000|320|0.020000|4664|dbl|320|1|mono
+audio|1|45120|2.820000|45120|2.820000|320|0.020000|4697|dbl|320|1|mono
+audio|1|45440|2.840000|45440|2.840000|320|0.020000|4730|dbl|320|1|mono
+audio|1|45760|2.860000|45760|2.860000|320|0.020000|4763|dbl|320|1|mono
+audio|1|46080|2.880000|46080|2.880000|320|0.020000|4796|dbl|320|1|mono
+audio|1|46400|2.900000|46400|2.900000|320|0.020000|4829|dbl|320|1|mono
+audio|1|46720|2.920000|46720|2.920000|320|0.020000|4862|dbl|320|1|mono
+audio|1|47040|2.940000|47040|2.940000|320|0.020000|4895|dbl|320|1|mono
+audio|1|47360|2.960000|47360|2.960000|320|0.020000|4928|dbl|320|1|mono
+audio|1|47680|2.980000|47680|2.980000|320|0.020000|4961|dbl|320|1|mono
+audio|1|48000|3.000000|48000|3.000000|320|0.020000|4994|dbl|320|1|mono
+audio|1|48320|3.020000|48320|3.020000|320|0.020000|5027|dbl|320|1|mono
+audio|1|48640|3.040000|48640|3.040000|320|0.020000|5060|dbl|320|1|mono
+audio|1|48960|3.060000|48960|3.060000|320|0.020000|5093|dbl|320|1|mono
+audio|1|49280|3.080000|49280|3.080000|320|0.020000|5126|dbl|320|1|mono
+audio|1|49600|3.100000|49600|3.100000|320|0.020000|5159|dbl|320|1|mono
+audio|1|49920|3.120000|49920|3.120000|320|0.020000|5192|dbl|320|1|mono
+audio|1|50240|3.140000|50240|3.140000|320|0.020000|5225|dbl|320|1|mono
+audio|1|50560|3.160000|50560|3.160000|320|0.020000|5258|dbl|320|1|mono
+audio|1|50880|3.180000|50880|3.180000|320|0.020000|5291|dbl|320|1|mono
+audio|1|51200|3.200000|51200|3.200000|320|0.020000|5324|dbl|320|1|mono
+audio|1|51520|3.220000|51520|3.220000|320|0.020000|5357|dbl|320|1|mono
+audio|1|51840|3.240000|51840|3.240000|320|0.020000|5390|dbl|320|1|mono
+audio|1|52160|3.260000|52160|3.260000|320|0.020000|5423|dbl|320|1|mono
+audio|1|52480|3.280000|52480|3.280000|320|0.020000|5456|dbl|320|1|mono
+audio|1|52800|3.300000|52800|3.300000|324|0.020250|5489|dbl|320|1|mono|3.2
+audio|1|53120|3.320000|53120|3.320000|320|0.020000|5522|dbl|320|1|mono
+audio|1|53440|3.340000|53440|3.340000|320|0.020000|5555|dbl|320|1|mono
+audio|1|53760|3.360000|53760|3.360000|320|0.020000|5588|dbl|320|1|mono
+audio|1|54080|3.380000|54080|3.380000|320|0.020000|5621|dbl|320|1|mono
+audio|1|54400|3.400000|54400|3.400000|320|0.020000|5654|dbl|320|1|mono
+audio|1|54720|3.420000|54720|3.420000|320|0.020000|5687|dbl|320|1|mono
+audio|1|55040|3.440000|55040|3.440000|320|0.020000|5720|dbl|320|1|mono
+audio|1|55360|3.460000|55360|3.460000|320|0.020000|5753|dbl|320|1|mono
+audio|1|55680|3.480000|55680|3.480000|320|0.020000|5786|dbl|320|1|mono
+audio|1|56000|3.500000|56000|3.500000|320|0.020000|5819|dbl|320|1|mono
+audio|1|56320|3.520000|56320|3.520000|320|0.020000|5852|dbl|320|1|mono
+audio|1|56640|3.540000|56640|3.540000|320|0.020000|5885|dbl|320|1|mono
+audio|1|56960|3.560000|56960|3.560000|320|0.020000|5918|dbl|320|1|mono
+audio|1|57280|3.580000|57280|3.580000|320|0.020000|5951|dbl|320|1|mono
+audio|1|57600|3.600000|57600|3.600000|320|0.020000|5984|dbl|320|1|mono
+audio|1|57920|3.620000|57920|3.620000|320|0.020000|6017|dbl|320|1|mono
+audio|1|58240|3.640000|58240|3.640000|320|0.020000|6050|dbl|320|1|mono
+audio|1|58560|3.660000|58560|3.660000|320|0.020000|6083|dbl|320|1|mono
+audio|1|58880|3.680000|58880|3.680000|320|0.020000|6116|dbl|320|1|mono
+audio|1|59200|3.700000|59200|3.700000|320|0.020000|6149|dbl|320|1|mono
+audio|1|59520|3.720000|59520|3.720000|320|0.020000|6182|dbl|320|1|mono
+audio|1|59840|3.740000|59840|3.740000|320|0.020000|6215|dbl|320|1|mono
+audio|1|60160|3.760000|60160|3.760000|320|0.020000|6248|dbl|320|1|mono
+audio|1|60480|3.780000|60480|3.780000|320|0.020000|6281|dbl|320|1|mono
+audio|1|60800|3.800000|60800|3.800000|320|0.020000|6314|dbl|320|1|mono
+audio|1|61120|3.820000|61120|3.820000|320|0.020000|6347|dbl|320|1|mono
+audio|1|61440|3.840000|61440|3.840000|320|0.020000|6380|dbl|320|1|mono
+audio|1|61760|3.860000|61760|3.860000|320|0.020000|6413|dbl|320|1|mono
+audio|1|62080|3.880000|62080|3.880000|320|0.020000|6446|dbl|320|1|mono
+audio|1|62400|3.900000|62400|3.900000|327|0.020438|6479|dbl|320|1|mono|3.9|0.7
+audio|1|62720|3.920000|62720|3.920000|320|0.020000|6512|dbl|320|1|mono
+audio|1|63040|3.940000|63040|3.940000|320|0.020000|6545|dbl|320|1|mono
+audio|1|63360|3.960000|63360|3.960000|320|0.020000|6578|dbl|320|1|mono
+audio|1|63680|3.980000|63680|3.980000|320|0.020000|6611|dbl|320|1|mono
+audio|1|64000|4.000000|64000|4.000000|320|0.020000|6644|dbl|320|1|mono
+audio|1|64320|4.020000|64320|4.020000|320|0.020000|6677|dbl|320|1|mono
+audio|1|64640|4.040000|64640|4.040000|320|0.020000|6710|dbl|320|1|mono
+audio|1|64960|4.060000|64960|4.060000|320|0.020000|6743|dbl|320|1|mono
+audio|1|65280|4.080000|65280|4.080000|320|0.020000|6776|dbl|320|1|mono
+audio|1|65600|4.100000|65600|4.100000|320|0.020000|6809|dbl|320|1|mono
+audio|1|65920|4.120000|65920|4.120000|320|0.020000|6842|dbl|320|1|mono
+audio|1|66240|4.140000|66240|4.140000|320|0.020000|6875|dbl|320|1|mono
+audio|1|66560|4.160000|66560|4.160000|320|0.020000|6908|dbl|320|1|mono
+audio|1|66880|4.180000|66880|4.180000|320|0.020000|6941|dbl|320|1|mono
+audio|1|67200|4.200000|67200|4.200000|320|0.020000|6974|dbl|320|1|mono
+audio|1|67520|4.220000|67520|4.220000|320|0.020000|7007|dbl|320|1|mono
+audio|1|67840|4.240000|67840|4.240000|320|0.020000|7040|dbl|320|1|mono
+audio|1|68160|4.260000|68160|4.260000|320|0.020000|7073|dbl|320|1|mono
+audio|1|68480|4.280000|68480|4.280000|320|0.020000|7106|dbl|320|1|mono
+audio|1|68800|4.300000|68800|4.300000|320|0.020000|7139|dbl|320|1|mono
+audio|1|69120|4.320000|69120|4.320000|320|0.020000|7172|dbl|320|1|mono
+audio|1|69440|4.340000|69440|4.340000|320|0.020000|7205|dbl|320|1|mono
+audio|1|69760|4.360000|69760|4.360000|320|0.020000|7238|dbl|320|1|mono
+audio|1|70080|4.380000|70080|4.380000|320|0.020000|7271|dbl|320|1|mono
+audio|1|70400|4.400000|70400|4.400000|320|0.020000|7304|dbl|320|1|mono
+audio|1|70720|4.420000|70720|4.420000|320|0.020000|7337|dbl|320|1|mono
+audio|1|71040|4.440000|71040|4.440000|320|0.020000|7370|dbl|320|1|mono
+audio|1|71360|4.460000|71360|4.460000|320|0.020000|7403|dbl|320|1|mono
+audio|1|71680|4.480000|71680|4.480000|320|0.020000|7436|dbl|320|1|mono
+audio|1|72000|4.500000|72000|4.500000|320|0.020000|7469|dbl|320|1|mono
+audio|1|72320|4.520000|72320|4.520000|320|0.020000|7502|dbl|320|1|mono
+audio|1|72640|4.540000|72640|4.540000|320|0.020000|7535|dbl|320|1|mono
+audio|1|72960|4.560000|72960|4.560000|320|0.020000|7568|dbl|320|1|mono
+audio|1|73280|4.580000|73280|4.580000|320|0.020000|7601|dbl|320|1|mono
+audio|1|73600|4.600000|73600|4.600000|320|0.020000|7634|dbl|320|1|mono
+audio|1|73920|4.620000|73920|4.620000|320|0.020000|7667|dbl|320|1|mono
+audio|1|74240|4.640000|74240|4.640000|320|0.020000|7700|dbl|320|1|mono
+audio|1|74560|4.660000|74560|4.660000|320|0.020000|7733|dbl|320|1|mono
+audio|1|74880|4.680000|74880|4.680000|320|0.020000|7766|dbl|320|1|mono
+audio|1|75200|4.700000|75200|4.700000|320|0.020000|7799|dbl|320|1|mono
+audio|1|75520|4.720000|75520|4.720000|320|0.020000|7832|dbl|320|1|mono
+audio|1|75840|4.740000|75840|4.740000|320|0.020000|7865|dbl|320|1|mono
+audio|1|76160|4.760000|76160|4.760000|320|0.020000|7898|dbl|320|1|mono
+audio|1|76480|4.780000|76480|4.780000|320|0.020000|7931|dbl|320|1|mono
+audio|1|76800|4.800000|76800|4.800000|320|0.020000|7964|dbl|320|1|mono
+audio|1|77120|4.820000|77120|4.820000|320|0.020000|7997|dbl|320|1|mono
+audio|1|77440|4.840000|77440|4.840000|320|0.020000|8030|dbl|320|1|mono
+audio|1|77760|4.860000|77760|4.860000|320|0.020000|8063|dbl|320|1|mono
+audio|1|78080|4.880000|78080|4.880000|320|0.020000|8096|dbl|320|1|mono
+audio|1|78400|4.900000|78400|4.900000|320|0.020000|8129|dbl|320|1|mono
+audio|1|78720|4.920000|78720|4.920000|320|0.020000|8162|dbl|320|1|mono
+audio|1|79040|4.940000|79040|4.940000|320|0.020000|8195|dbl|320|1|mono
+audio|1|79360|4.960000|79360|4.960000|320|0.020000|8228|dbl|320|1|mono
+audio|1|79680|4.980000|79680|4.980000|320|0.020000|8261|dbl|320|1|mono
+audio|1|80000|5.000000|80000|5.000000|324|0.020250|8294|dbl|320|1|mono|4.9
+audio|1|80320|5.020000|80320|5.020000|320|0.020000|8327|dbl|320|1|mono
+audio|1|80640|5.040000|80640|5.040000|320|0.020000|8360|dbl|320|1|mono
+audio|1|80960|5.060000|80960|5.060000|320|0.020000|8393|dbl|320|1|mono
+audio|1|81280|5.080000|81280|5.080000|320|0.020000|8426|dbl|320|1|mono
+audio|1|81600|5.100000|81600|5.100000|320|0.020000|8459|dbl|320|1|mono
+audio|1|81920|5.120000|81920|5.120000|320|0.020000|8492|dbl|320|1|mono
+audio|1|82240|5.140000|82240|5.140000|320|0.020000|8525|dbl|320|1|mono
+audio|1|82560|5.160000|82560|5.160000|320|0.020000|8558|dbl|320|1|mono
+audio|1|82880|5.180000|82880|5.180000|320|0.020000|8591|dbl|320|1|mono
+audio|1|83200|5.200000|83200|5.200000|320|0.020000|8624|dbl|320|1|mono
+audio|1|83520|5.220000|83520|5.220000|320|0.020000|8657|dbl|320|1|mono
+audio|1|83840|5.240000|83840|5.240000|320|0.020000|8690|dbl|320|1|mono
+audio|1|84160|5.260000|84160|5.260000|320|0.020000|8723|dbl|320|1|mono
+audio|1|84480|5.280000|84480|5.280000|320|0.020000|8756|dbl|320|1|mono
+audio|1|84800|5.300000|84800|5.300000|320|0.020000|8789|dbl|320|1|mono
+audio|1|85120|5.320000|85120|5.320000|320|0.020000|8822|dbl|320|1|mono
+audio|1|85440|5.340000|85440|5.340000|320|0.020000|8855|dbl|320|1|mono
+audio|1|85760|5.360000|85760|5.360000|320|0.020000|8888|dbl|320|1|mono
+audio|1|86080|5.380000|86080|5.380000|320|0.020000|8921|dbl|320|1|mono
+audio|1|86400|5.400000|86400|5.400000|320|0.020000|8954|dbl|320|1|mono
+audio|1|86720|5.420000|86720|5.420000|320|0.020000|8987|dbl|320|1|mono
+audio|1|87040|5.440000|87040|5.440000|328|0.020500|9020|dbl|320|1|mono|5.44|0.54
+audio|1|87360|5.460000|87360|5.460000|320|0.020000|9053|dbl|320|1|mono
+audio|1|87680|5.480000|87680|5.480000|320|0.020000|9086|dbl|320|1|mono
+audio|1|88000|5.500000|88000|5.500000|320|0.020000|9119|dbl|320|1|mono
+audio|1|88320|5.520000|88320|5.520000|320|0.020000|9152|dbl|320|1|mono
+audio|1|88640|5.540000|88640|5.540000|320|0.020000|9185|dbl|320|1|mono
+audio|1|88960|5.560000|88960|5.560000|320|0.020000|9218|dbl|320|1|mono
+audio|1|89280|5.580000|89280|5.580000|320|0.020000|9251|dbl|320|1|mono
+audio|1|89600|5.600000|89600|5.600000|320|0.020000|9284|dbl|320|1|mono
+audio|1|89920|5.620000|89920|5.620000|320|0.020000|9317|dbl|320|1|mono
+audio|1|90240|5.640000|90240|5.640000|320|0.020000|9350|dbl|320|1|mono
+audio|1|90560|5.660000|90560|5.660000|320|0.020000|9383|dbl|320|1|mono
+audio|1|90880|5.680000|90880|5.680000|320|0.020000|9416|dbl|320|1|mono
+audio|1|91200|5.700000|91200|5.700000|320|0.020000|9449|dbl|320|1|mono
+audio|1|91520|5.720000|91520|5.720000|320|0.020000|9482|dbl|320|1|mono
+audio|1|91840|5.740000|91840|5.740000|320|0.020000|9515|dbl|320|1|mono
+audio|1|92160|5.760000|92160|5.760000|320|0.020000|9548|dbl|320|1|mono
+audio|1|92480|5.780000|92480|5.780000|320|0.020000|9581|dbl|320|1|mono
+audio|1|92800|5.800000|92800|5.800000|320|0.020000|9614|dbl|320|1|mono
+audio|1|93120|5.820000|93120|5.820000|320|0.020000|9647|dbl|320|1|mono
+audio|1|93440|5.840000|93440|5.840000|320|0.020000|9680|dbl|320|1|mono
+audio|1|93760|5.860000|93760|5.860000|320|0.020000|9713|dbl|320|1|mono
+audio|1|94080|5.880000|94080|5.880000|320|0.020000|9746|dbl|320|1|mono
+audio|1|94400|5.900000|94400|5.900000|320|0.020000|9779|dbl|320|1|mono
+audio|1|94720|5.920000|94720|5.920000|320|0.020000|9812|dbl|320|1|mono
+audio|1|95040|5.940000|95040|5.940000|320|0.020000|9845|dbl|320|1|mono
+audio|1|95360|5.960000|95360|5.960000|320|0.020000|9878|dbl|320|1|mono
+audio|1|95680|5.980000|95680|5.980000|320|0.020000|9911|dbl|320|1|mono
+audio|1|96000|6.000000|96000|6.000000|320|0.020000|9944|dbl|320|1|mono
+audio|1|96320|6.020000|96320|6.020000|320|0.020000|9977|dbl|320|1|mono
+audio|1|96640|6.040000|96640|6.040000|320|0.020000|10010|dbl|320|1|mono
+audio|1|96960|6.060000|96960|6.060000|320|0.020000|10043|dbl|320|1|mono
+audio|1|97280|6.080000|97280|6.080000|320|0.020000|10076|dbl|320|1|mono
+audio|1|97600|6.100000|97600|6.100000|320|0.020000|10109|dbl|320|1|mono
+audio|1|97920|6.120000|97920|6.120000|320|0.020000|10142|dbl|320|1|mono
+audio|1|98240|6.140000|98240|6.140000|320|0.020000|10175|dbl|320|1|mono
+audio|1|98560|6.160000|98560|6.160000|320|0.020000|10208|dbl|320|1|mono
+audio|1|98880|6.180000|98880|6.180000|320|0.020000|10241|dbl|320|1|mono
+audio|1|99200|6.200000|99200|6.200000|320|0.020000|10274|dbl|320|1|mono
+audio|1|99520|6.220000|99520|6.220000|320|0.020000|10307|dbl|320|1|mono
+audio|1|99840|6.240000|99840|6.240000|320|0.020000|10340|dbl|320|1|mono
+audio|1|100160|6.260000|100160|6.260000|320|0.020000|10373|dbl|320|1|mono
+audio|1|100480|6.280000|100480|6.280000|320|0.020000|10406|dbl|320|1|mono
+audio|1|100800|6.300000|100800|6.300000|320|0.020000|10439|dbl|320|1|mono
+audio|1|101120|6.320000|101120|6.320000|320|0.020000|10472|dbl|320|1|mono
+audio|1|101440|6.340000|101440|6.340000|320|0.020000|10505|dbl|320|1|mono
+audio|1|101760|6.360000|101760|6.360000|320|0.020000|10538|dbl|320|1|mono
+audio|1|102080|6.380000|102080|6.380000|320|0.020000|10571|dbl|320|1|mono
+audio|1|102400|6.400000|102400|6.400000|320|0.020000|10604|dbl|320|1|mono
+audio|1|102720|6.420000|102720|6.420000|320|0.020000|10637|dbl|320|1|mono
+audio|1|103040|6.440000|103040|6.440000|320|0.020000|10670|dbl|320|1|mono
+audio|1|103360|6.460000|103360|6.460000|320|0.020000|10703|dbl|320|1|mono
+audio|1|103680|6.480000|103680|6.480000|320|0.020000|10736|dbl|320|1|mono
+audio|1|104000|6.500000|104000|6.500000|320|0.020000|10769|dbl|320|1|mono
+audio|1|104320|6.520000|104320|6.520000|320|0.020000|10802|dbl|320|1|mono
+audio|1|104640|6.540000|104640|6.540000|324|0.020250|10835|dbl|320|1|mono|6.44
+audio|1|104960|6.560000|104960|6.560000|320|0.020000|10868|dbl|320|1|mono
+audio|1|105280|6.580000|105280|6.580000|320|0.020000|10901|dbl|320|1|mono
+audio|1|105600|6.600000|105600|6.600000|320|0.020000|10934|dbl|320|1|mono
+audio|1|105920|6.620000|105920|6.620000|320|0.020000|10967|dbl|320|1|mono
+audio|1|106240|6.640000|106240|6.640000|320|0.020000|11000|dbl|320|1|mono
+audio|1|106560|6.660000|106560|6.660000|320|0.020000|11033|dbl|320|1|mono
+audio|1|106880|6.680000|106880|6.680000|320|0.020000|11066|dbl|320|1|mono
+audio|1|107200|6.700000|107200|6.700000|320|0.020000|11099|dbl|320|1|mono
+audio|1|107520|6.720000|107520|6.720000|320|0.020000|11132|dbl|320|1|mono
+audio|1|107840|6.740000|107840|6.740000|320|0.020000|11165|dbl|320|1|mono
+audio|1|108160|6.760000|108160|6.760000|320|0.020000|11198|dbl|320|1|mono
+audio|1|108480|6.780000|108480|6.780000|320|0.020000|11231|dbl|320|1|mono
+audio|1|108800|6.800000|108800|6.800000|320|0.020000|11264|dbl|320|1|mono
+audio|1|109120|6.820000|109120|6.820000|320|0.020000|11297|dbl|320|1|mono
+audio|1|109440|6.840000|109440|6.840000|320|0.020000|11330|dbl|320|1|mono
+audio|1|109760|6.860000|109760|6.860000|320|0.020000|11363|dbl|320|1|mono
+audio|1|110080|6.880000|110080|6.880000|320|0.020000|11396|dbl|320|1|mono
+audio|1|110400|6.900000|110400|6.900000|320|0.020000|11429|dbl|320|1|mono
+audio|1|110720|6.920000|110720|6.920000|320|0.020000|11462|dbl|320|1|mono
+audio|1|111040|6.940000|111040|6.940000|320|0.020000|11495|dbl|320|1|mono
+audio|1|111360|6.960000|111360|6.960000|320|0.020000|11528|dbl|320|1|mono
+audio|1|111680|6.980000|111680|6.980000|320|0.020000|11561|dbl|320|1|mono
+audio|1|112000|7.000000|112000|7.000000|320|0.020000|11594|dbl|320|1|mono
+audio|1|112320|7.020000|112320|7.020000|320|0.020000|11627|dbl|320|1|mono
+audio|1|112640|7.040000|112640|7.040000|320|0.020000|11660|dbl|320|1|mono
+audio|1|112960|7.060000|112960|7.060000|320|0.020000|11693|dbl|320|1|mono
+audio|1|113280|7.080000|113280|7.080000|320|0.020000|11726|dbl|320|1|mono
+audio|1|113600|7.100000|113600|7.100000|320|0.020000|11759|dbl|320|1|mono
+audio|1|113920|7.120000|113920|7.120000|320|0.020000|11792|dbl|320|1|mono
+audio|1|114240|7.140000|114240|7.140000|320|0.020000|11825|dbl|320|1|mono
+audio|1|114560|7.160000|114560|7.160000|320|0.020000|11858|dbl|320|1|mono
+audio|1|114880|7.180000|114880|7.180000|320|0.020000|11891|dbl|320|1|mono
+audio|1|115200|7.200000|115200|7.200000|320|0.020000|11924|dbl|320|1|mono
+audio|1|115520|7.220000|115520|7.220000|320|0.020000|11957|dbl|320|1|mono
+audio|1|115840|7.240000|115840|7.240000|320|0.020000|11990|dbl|320|1|mono
+audio|1|116160|7.260000|116160|7.260000|328|0.020500|12023|dbl|320|1|mono|7.26|0.82
+audio|1|116480|7.280000|116480|7.280000|320|0.020000|12056|dbl|320|1|mono
+audio|1|116800|7.300000|116800|7.300000|320|0.020000|12089|dbl|320|1|mono
+audio|1|117120|7.320000|117120|7.320000|320|0.020000|12122|dbl|320|1|mono
+audio|1|117440|7.340000|117440|7.340000|320|0.020000|12155|dbl|320|1|mono
+audio|1|117760|7.360000|117760|7.360000|320|0.020000|12188|dbl|320|1|mono
+audio|1|118080|7.380000|118080|7.380000|320|0.020000|12221|dbl|320|1|mono
+audio|1|118400|7.400000|118400|7.400000|320|0.020000|12254|dbl|320|1|mono
+audio|1|118720|7.420000|118720|7.420000|320|0.020000|12287|dbl|320|1|mono
+audio|1|119040|7.440000|119040|7.440000|320|0.020000|12320|dbl|320|1|mono
+audio|1|119360|7.460000|119360|7.460000|320|0.020000|12353|dbl|320|1|mono
+audio|1|119680|7.480000|119680|7.480000|320|0.020000|12386|dbl|320|1|mono
+audio|1|120000|7.500000|120000|7.500000|320|0.020000|12419|dbl|320|1|mono
+audio|1|120320|7.520000|120320|7.520000|320|0.020000|12452|dbl|320|1|mono
+audio|1|120640|7.540000|120640|7.540000|320|0.020000|12485|dbl|320|1|mono
+audio|1|120960|7.560000|120960|7.560000|320|0.020000|12518|dbl|320|1|mono
+audio|1|121280|7.580000|121280|7.580000|320|0.020000|12551|dbl|320|1|mono
+audio|1|121600|7.600000|121600|7.600000|320|0.020000|12584|dbl|320|1|mono
+audio|1|121920|7.620000|121920|7.620000|320|0.020000|12617|dbl|320|1|mono
+audio|1|122240|7.640000|122240|7.640000|320|0.020000|12650|dbl|320|1|mono
+audio|1|122560|7.660000|122560|7.660000|320|0.020000|12683|dbl|320|1|mono
+audio|1|122880|7.680000|122880|7.680000|320|0.020000|12716|dbl|320|1|mono
+audio|1|123200|7.700000|123200|7.700000|320|0.020000|12749|dbl|320|1|mono
+audio|1|123520|7.720000|123520|7.720000|320|0.020000|12782|dbl|320|1|mono
+audio|1|123840|7.740000|123840|7.740000|320|0.020000|12815|dbl|320|1|mono
+audio|1|124160|7.760000|124160|7.760000|320|0.020000|12848|dbl|320|1|mono
+audio|1|124480|7.780000|124480|7.780000|320|0.020000|12881|dbl|320|1|mono
+audio|1|124800|7.800000|124800|7.800000|320|0.020000|12914|dbl|320|1|mono
+audio|1|125120|7.820000|125120|7.820000|320|0.020000|12947|dbl|320|1|mono
+audio|1|125440|7.840000|125440|7.840000|320|0.020000|12980|dbl|320|1|mono
+audio|1|125760|7.860000|125760|7.860000|320|0.020000|13013|dbl|320|1|mono
+audio|1|126080|7.880000|126080|7.880000|320|0.020000|13046|dbl|320|1|mono
+audio|1|126400|7.900000|126400|7.900000|320|0.020000|13079|dbl|320|1|mono
+audio|1|126720|7.920000|126720|7.920000|320|0.020000|13112|dbl|320|1|mono
+audio|1|127040|7.940000|127040|7.940000|320|0.020000|13145|dbl|320|1|mono
+audio|1|127360|7.960000|127360|7.960000|320|0.020000|13178|dbl|320|1|mono
+audio|1|127680|7.980000|127680|7.980000|320|0.020000|13211|dbl|320|1|mono
+audio|1|128000|8.000000|128000|8.000000|320|0.020000|13244|dbl|320|1|mono
+audio|1|128320|8.020000|128320|8.020000|320|0.020000|13277|dbl|320|1|mono
+audio|1|128640|8.040000|128640|8.040000|320|0.020000|13310|dbl|320|1|mono
+audio|1|128960|8.060000|128960|8.060000|320|0.020000|13343|dbl|320|1|mono
+audio|1|129280|8.080000|129280|8.080000|320|0.020000|13376|dbl|320|1|mono
+audio|1|129600|8.100000|129600|8.100000|320|0.020000|13409|dbl|320|1|mono
+audio|1|129920|8.120000|129920|8.120000|320|0.020000|13442|dbl|320|1|mono
+audio|1|130240|8.140000|130240|8.140000|320|0.020000|13475|dbl|320|1|mono
+audio|1|130560|8.160000|130560|8.160000|320|0.020000|13508|dbl|320|1|mono
+audio|1|130880|8.180000|130880|8.180000|320|0.020000|13541|dbl|320|1|mono
+audio|1|131200|8.200000|131200|8.200000|320|0.020000|13574|dbl|320|1|mono
+audio|1|131520|8.220000|131520|8.220000|320|0.020000|13607|dbl|320|1|mono
+audio|1|131840|8.240000|131840|8.240000|320|0.020000|13640|dbl|320|1|mono
+audio|1|132160|8.260000|132160|8.260000|320|0.020000|13673|dbl|320|1|mono
+audio|1|132480|8.280000|132480|8.280000|320|0.020000|13706|dbl|320|1|mono
+audio|1|132800|8.300000|132800|8.300000|320|0.020000|13739|dbl|320|1|mono
+audio|1|133120|8.320000|133120|8.320000|320|0.020000|13772|dbl|320|1|mono
+audio|1|133440|8.340000|133440|8.340000|320|0.020000|13805|dbl|320|1|mono
+audio|1|133760|8.360000|133760|8.360000|320|0.020000|13838|dbl|320|1|mono
+audio|1|134080|8.380000|134080|8.380000|320|0.020000|13871|dbl|320|1|mono
+audio|1|134400|8.400000|134400|8.400000|320|0.020000|13904|dbl|320|1|mono
+audio|1|134720|8.420000|134720|8.420000|320|0.020000|13937|dbl|320|1|mono
+audio|1|135040|8.440000|135040|8.440000|320|0.020000|13970|dbl|320|1|mono
+audio|1|135360|8.460000|135360|8.460000|320|0.020000|14003|dbl|320|1|mono
+audio|1|135680|8.480000|135680|8.480000|320|0.020000|14036|dbl|320|1|mono
+audio|1|136000|8.500000|136000|8.500000|320|0.020000|14069|dbl|320|1|mono
+audio|1|136320|8.520000|136320|8.520000|320|0.020000|14102|dbl|320|1|mono
+audio|1|136640|8.540000|136640|8.540000|320|0.020000|14135|dbl|320|1|mono
+audio|1|136960|8.560000|136960|8.560000|320|0.020000|14168|dbl|320|1|mono
+audio|1|137280|8.580000|137280|8.580000|320|0.020000|14201|dbl|320|1|mono
+audio|1|137600|8.600000|137600|8.600000|324|0.020250|14234|dbl|320|1|mono|8.5
+audio|1|137920|8.620000|137920|8.620000|320|0.020000|14267|dbl|320|1|mono
+audio|1|138240|8.640000|138240|8.640000|320|0.020000|14300|dbl|320|1|mono
+audio|1|138560|8.660000|138560|8.660000|320|0.020000|14333|dbl|320|1|mono
+audio|1|138880|8.680000|138880|8.680000|328|0.020500|14366|dbl|320|1|mono|8.68|0.18
+audio|1|139200|8.700000|139200|8.700000|320|0.020000|14399|dbl|320|1|mono
+audio|1|139520|8.720000|139520|8.720000|320|0.020000|14432|dbl|320|1|mono
+audio|1|139840|8.740000|139840|8.740000|320|0.020000|14465|dbl|320|1|mono
+audio|1|140160|8.760000|140160|8.760000|320|0.020000|14498|dbl|320|1|mono
+audio|1|140480|8.780000|140480|8.780000|324|0.020250|14531|dbl|320|1|mono|8.68
+audio|1|140800|8.800000|140800|8.800000|320|0.020000|14564|dbl|320|1|mono
+audio|1|141120|8.820000|141120|8.820000|320|0.020000|14597|dbl|320|1|mono
+audio|1|141440|8.840000|141440|8.840000|320|0.020000|14630|dbl|320|1|mono
+audio|1|141760|8.860000|141760|8.860000|320|0.020000|14663|dbl|320|1|mono
+audio|1|142080|8.880000|142080|8.880000|320|0.020000|14696|dbl|320|1|mono
+audio|1|142400|8.900000|142400|8.900000|320|0.020000|14729|dbl|320|1|mono
+audio|1|142720|8.920000|142720|8.920000|320|0.020000|14762|dbl|320|1|mono
+audio|1|143040|8.940000|143040|8.940000|320|0.020000|14795|dbl|320|1|mono
+audio|1|143360|8.960000|143360|8.960000|320|0.020000|14828|dbl|320|1|mono
+audio|1|143680|8.980000|143680|8.980000|327|0.020438|14861|dbl|320|1|mono|8.98|0.3
+audio|1|144000|9.000000|144000|9.000000|320|0.020000|14894|dbl|320|1|mono
+audio|1|144320|9.020000|144320|9.020000|320|0.020000|14927|dbl|320|1|mono
+audio|1|144640|9.040000|144640|9.040000|320|0.020000|14960|dbl|320|1|mono
+audio|1|144960|9.060000|144960|9.060000|320|0.020000|14993|dbl|320|1|mono
+audio|1|145280|9.080000|145280|9.080000|320|0.020000|15026|dbl|320|1|mono
+audio|1|145600|9.100000|145600|9.100000|320|0.020000|15059|dbl|320|1|mono
+audio|1|145920|9.120000|145920|9.120000|320|0.020000|15092|dbl|320|1|mono
+audio|1|146240|9.140000|146240|9.140000|320|0.020000|15125|dbl|320|1|mono
+audio|1|146560|9.160000|146560|9.160000|320|0.020000|15158|dbl|320|1|mono
+audio|1|146880|9.180000|146880|9.180000|320|0.020000|15191|dbl|320|1|mono
+audio|1|147200|9.200000|147200|9.200000|320|0.020000|15224|dbl|320|1|mono
+audio|1|147520|9.220000|147520|9.220000|320|0.020000|15257|dbl|320|1|mono
+audio|1|147840|9.240000|147840|9.240000|320|0.020000|15290|dbl|320|1|mono
+audio|1|148160|9.260000|148160|9.260000|320|0.020000|15323|dbl|320|1|mono
+audio|1|148480|9.280000|148480|9.280000|320|0.020000|15356|dbl|320|1|mono
+audio|1|148800|9.300000|148800|9.300000|320|0.020000|15389|dbl|320|1|mono
+audio|1|149120|9.320000|149120|9.320000|320|0.020000|15422|dbl|320|1|mono
+audio|1|149440|9.340000|149440|9.340000|320|0.020000|15455|dbl|320|1|mono
+audio|1|149760|9.360000|149760|9.360000|320|0.020000|15488|dbl|320|1|mono
+audio|1|150080|9.380000|150080|9.380000|320|0.020000|15521|dbl|320|1|mono
+audio|1|150400|9.400000|150400|9.400000|320|0.020000|15554|dbl|320|1|mono
+audio|1|150720|9.420000|150720|9.420000|320|0.020000|15587|dbl|320|1|mono
+audio|1|151040|9.440000|151040|9.440000|320|0.020000|15620|dbl|320|1|mono
+audio|1|151360|9.460000|151360|9.460000|320|0.020000|15653|dbl|320|1|mono
+audio|1|151680|9.480000|151680|9.480000|320|0.020000|15686|dbl|320|1|mono
+audio|1|152000|9.500000|152000|9.500000|320|0.020000|15719|dbl|320|1|mono
+audio|1|152320|9.520000|152320|9.520000|320|0.020000|15752|dbl|320|1|mono
+audio|1|152640|9.540000|152640|9.540000|320|0.020000|15785|dbl|320|1|mono
+audio|1|152960|9.560000|152960|9.560000|320|0.020000|15818|dbl|320|1|mono
+audio|1|153280|9.580000|153280|9.580000|320|0.020000|15851|dbl|320|1|mono
+audio|1|153600|9.600000|153600|9.600000|320|0.020000|15884|dbl|320|1|mono
+audio|1|153920|9.620000|153920|9.620000|320|0.020000|15917|dbl|320|1|mono
+audio|1|154240|9.640000|154240|9.640000|320|0.020000|15950|dbl|320|1|mono
+audio|1|154560|9.660000|154560|9.660000|320|0.020000|15983|dbl|320|1|mono
+audio|1|154880|9.680000|154880|9.680000|320|0.020000|16016|dbl|320|1|mono
+audio|1|155200|9.700000|155200|9.700000|320|0.020000|16049|dbl|320|1|mono
+audio|1|155520|9.720000|155520|9.720000|320|0.020000|16082|dbl|320|1|mono
+audio|1|155840|9.740000|155840|9.740000|320|0.020000|16115|dbl|320|1|mono
+audio|1|156160|9.760000|156160|9.760000|320|0.020000|16148|dbl|320|1|mono
+audio|1|156480|9.780000|156480|9.780000|320|0.020000|16181|dbl|320|1|mono
+audio|1|156800|9.800000|156800|9.800000|320|0.020000|16214|dbl|320|1|mono
+audio|1|157120|9.820000|157120|9.820000|320|0.020000|16247|dbl|320|1|mono
+audio|1|157440|9.840000|157440|9.840000|320|0.020000|16280|dbl|320|1|mono
+audio|1|157760|9.860000|157760|9.860000|320|0.020000|16313|dbl|320|1|mono
+audio|1|158080|9.880000|158080|9.880000|320|0.020000|16346|dbl|320|1|mono
+audio|1|158400|9.900000|158400|9.900000|320|0.020000|16379|dbl|320|1|mono
+audio|1|158720|9.920000|158720|9.920000|320|0.020000|16412|dbl|320|1|mono
+audio|1|159040|9.940000|159040|9.940000|320|0.020000|16445|dbl|320|1|mono
+audio|1|159360|9.960000|159360|9.960000|320|0.020000|16478|dbl|320|1|mono
+audio|1|159680|9.980000|159680|9.980000|320|0.020000|16511|dbl|320|1|mono
+audio|1|160000|10.000000|160000|10.000000|320|0.020000|16544|dbl|320|1|mono
+audio|1|160320|10.020000|160320|10.020000|320|0.020000|16577|dbl|320|1|mono
+audio|1|160640|10.040000|160640|10.040000|320|0.020000|16610|dbl|320|1|mono
+audio|1|160960|10.060000|160960|10.060000|320|0.020000|16643|dbl|320|1|mono
+audio|1|161280|10.080000|161280|10.080000|320|0.020000|16676|dbl|320|1|mono
+audio|1|161600|10.100000|161600|10.100000|324|0.020250|16709|dbl|320|1|mono|10
+audio|1|161920|10.120000|161920|10.120000|320|0.020000|16742|dbl|320|1|mono
+audio|1|162240|10.140000|162240|10.140000|320|0.020000|16775|dbl|320|1|mono
+audio|1|162560|10.160000|162560|10.160000|320|0.020000|16808|dbl|320|1|mono
+audio|1|162880|10.180000|162880|10.180000|320|0.020000|16841|dbl|320|1|mono
+audio|1|163200|10.200000|163200|10.200000|320|0.020000|16874|dbl|320|1|mono
+audio|1|163520|10.220000|163520|10.220000|320|0.020000|16907|dbl|320|1|mono
diff --git a/tests/ref/fate/id-cin-video b/tests/ref/fate/id-cin-video
index 241cae5..f55544f 100644
--- a/tests/ref/fate/id-cin-video
+++ b/tests/ref/fate/id-cin-video
@@ -104,4 +104,3 @@
 1,      78750,      78750,     1575,     6300, 0xe3bfa403
 0,         51,         51,        1,   230400, 0x488de02d
 1,      80325,      80325,     1575,     6300, 0x2c5bd9c9
-0,         52,         52,        1,   230400, 0x488de02d
diff --git a/tests/ref/fate/iff-fibonacci b/tests/ref/fate/iff-fibonacci
index 947f78e..e452f31 100644
--- a/tests/ref/fate/iff-fibonacci
+++ b/tests/ref/fate/iff-fibonacci
@@ -1 +1 @@
-e76b025238a6a27968f8644f4ccc3207
+e968a853779bb6438339e3b8d69d8d24
diff --git a/tests/ref/fate/kgv1 b/tests/ref/fate/kgv1
index 6f35893..4f475bb 100644
--- a/tests/ref/fate/kgv1
+++ b/tests/ref/fate/kgv1
@@ -294,15 +294,15 @@
 0,        292,        292,        1,   153600, 0x1348310e
 0,        293,        293,        1,   153600, 0xb5489dad
 0,        294,        294,        1,   153600, 0xa1eb1408
-0,        295,        295,        1,   153600, 0x15e1832c
+0,        295,        295,        1,   153600, 0x15e0832b
 0,        296,        296,        1,   153600, 0xb789cba5
 0,        297,        297,        1,   153600, 0x3ee86e4f
 0,        298,        298,        1,   153600, 0x06ea3883
 0,        299,        299,        1,   153600, 0xcedd02b7
-0,        300,        300,        1,   153600, 0xbce6ce58
-0,        301,        301,        1,   153600, 0xaadf9a00
+0,        300,        300,        1,   153600, 0xbcd6ce50
+0,        301,        301,        1,   153600, 0xaacf99f8
 0,        302,        302,        1,   153600, 0x98c865a0
-0,        303,        303,        1,   153600, 0x4c8432e0
+0,        303,        303,        1,   153600, 0x4c6432d0
 0,        304,        304,        1,   153600, 0x00000000
 0,        305,        305,        1,   153600, 0x00000000
 0,        306,        306,        1,   153600, 0x00000000
diff --git a/tests/ref/fate/lmlm4-demux b/tests/ref/fate/lmlm4-demux
index 0546135..f8a6e21 100644
--- a/tests/ref/fate/lmlm4-demux
+++ b/tests/ref/fate/lmlm4-demux
@@ -3,215 +3,215 @@
 0,          0, -9223372036854775808,        1,     5951, 0xe9118e0d
 1,          0,          0,     2160,      768, 0xaebcbebb
 1,       2160,       2160,     2160,      768, 0xaebcbebb
-0,          1, -9223372036854775808,        1,     1672, 0x4b80d4ca
+0,          1, -9223372036854775808,        1,     1672, 0x4b80d4ca, F=0x0
 1,       4320,       4320,     2160,      768, 0xaebcbebb
-0,          2, -9223372036854775808,        1,     1604, 0x99e1b0a7
+0,          2, -9223372036854775808,        1,     1604, 0x99e1b0a7, F=0x0
 1,       6480,       6480,     2160,      768, 0x866fe37a
 1,       8640,       8640,     2160,      768, 0x05d76890
-0,          3, -9223372036854775808,        1,     1204, 0x9559038a
+0,          3, -9223372036854775808,        1,     1204, 0x9559038a, F=0x0
 1,      10800,      10800,     2160,      768, 0x858f5511
-0,          4, -9223372036854775808,        1,     1482, 0x60056564
+0,          4, -9223372036854775808,        1,     1482, 0x60056564, F=0x0
 1,      12960,      12960,     2160,      768, 0x97cb65ef
-0,          5, -9223372036854775808,        1,     1105, 0xf508cef4
+0,          5, -9223372036854775808,        1,     1105, 0xf508cef4, F=0x0
 1,      15120,      15120,     2160,      768, 0xe269742c
 1,      17280,      17280,     2160,      768, 0xa6015f8d
-0,          6, -9223372036854775808,        1,     1193, 0xc8e0fd36
+0,          6, -9223372036854775808,        1,     1193, 0xc8e0fd36, F=0x0
 1,      19440,      19440,     2160,      768, 0x759163e0
-0,          7, -9223372036854775808,        1,     1247, 0x8dd202e5
+0,          7, -9223372036854775808,        1,     1247, 0x8dd202e5, F=0x0
 1,      21600,      21600,     2160,      768, 0xb1e16082
 1,      23760,      23760,     2160,      768, 0x1b616429
-0,          8, -9223372036854775808,        1,     1367, 0xf59435e5
+0,          8, -9223372036854775808,        1,     1367, 0xf59435e5, F=0x0
 1,      25920,      25920,     2160,      768, 0x7e4364f7
-0,          9, -9223372036854775808,        1,     1406, 0x68ba4a7e
+0,          9, -9223372036854775808,        1,     1406, 0x68ba4a7e, F=0x0
 1,      28080,      28080,     2160,      768, 0x59bd64f7
-0,         10, -9223372036854775808,        1,     1262, 0x82c04123
+0,         10, -9223372036854775808,        1,     1262, 0x82c04123, F=0x0
 1,      30240,      30240,     2160,      768, 0xc3116fc6
 1,      32400,      32400,     2160,      768, 0x6a1c6b56
-0,         11, -9223372036854775808,        1,     1381, 0x02335cf9
+0,         11, -9223372036854775808,        1,     1381, 0x02335cf9, F=0x0
 1,      34560,      34560,     2160,      768, 0x285a64cf
-0,         12, -9223372036854775808,        1,     1450, 0x7be46fd1
+0,         12, -9223372036854775808,        1,     1450, 0x7be46fd1, F=0x0
 1,      36720,      36720,     2160,      768, 0x79b16d65
 1,      38880,      38880,     2160,      768, 0x09b47635
-0,         13, -9223372036854775808,        1,     1362, 0x75cc381a
+0,         13, -9223372036854775808,        1,     1362, 0x75cc381a, F=0x0
 1,      41040,      41040,     2160,      768, 0x81597446
-0,         14, -9223372036854775808,        1,     1409, 0x9ed74f3f
+0,         14, -9223372036854775808,        1,     1409, 0x9ed74f3f, F=0x0
 1,      43200,      43200,     2160,      768, 0xfeb66eee
-0,         15, -9223372036854775808,        1,     1253, 0x82400ae1
+0,         15, -9223372036854775808,        1,     1253, 0x82400ae1, F=0x0
 1,      45360,      45360,     2160,      768, 0x78557618
 1,      47520,      47520,     2160,      768, 0x3af170bf
 0,         16, -9223372036854775808,        1,     5499, 0xed286805
 1,      49680,      49680,     2160,      768, 0xefbd6399
-0,         17, -9223372036854775808,        1,     1403, 0x483c4cbc
+0,         17, -9223372036854775808,        1,     1403, 0x483c4cbc, F=0x0
 1,      51840,      51840,     2160,      768, 0xc98e7492
 1,      54000,      54000,     2160,      768, 0x010d7149
-0,         18, -9223372036854775808,        1,     1632, 0xa9ebcd6c
+0,         18, -9223372036854775808,        1,     1632, 0xa9ebcd6c, F=0x0
 1,      56160,      56160,     2160,      768, 0xce838b07
-0,         19, -9223372036854775808,        1,     1207, 0xc8580724
+0,         19, -9223372036854775808,        1,     1207, 0xc8580724, F=0x0
 1,      58320,      58320,     2160,      768, 0xed18726c
-0,         20, -9223372036854775808,        1,     1289, 0x61fb2fd2
+0,         20, -9223372036854775808,        1,     1289, 0x61fb2fd2, F=0x0
 1,      60480,      60480,     2160,      768, 0x017e6712
 1,      62640,      62640,     2160,      768, 0x7f9268e9
-0,         21, -9223372036854775808,        1,     1230, 0xf348f53c
+0,         21, -9223372036854775808,        1,     1230, 0xf348f53c, F=0x0
 1,      64800,      64800,     2160,      768, 0xf6f258fc
-0,         22, -9223372036854775808,        1,     1579, 0xa260b1ac
+0,         22, -9223372036854775808,        1,     1579, 0xa260b1ac, F=0x0
 1,      66960,      66960,     2160,      768, 0x9a1a6f31
-0,         23, -9223372036854775808,        1,      949, 0x91849002
+0,         23, -9223372036854775808,        1,      949, 0x91849002, F=0x0
 1,      69120,      69120,     2160,      768, 0x14b47b23
 1,      71280,      71280,     2160,      768, 0x9bdc6a50
-0,         24, -9223372036854775808,        1,      786, 0x3e33576f
+0,         24, -9223372036854775808,        1,      786, 0x3e33576f, F=0x0
 1,      73440,      73440,     2160,      768, 0x0fc46dab
-0,         25, -9223372036854775808,        1,      894, 0x9ac36a61
+0,         25, -9223372036854775808,        1,      894, 0x9ac36a61, F=0x0
 1,      75600,      75600,     2160,      768, 0x6c387372
 1,      77760,      77760,     2160,      768, 0x581e71cd
-0,         26, -9223372036854775808,        1,     1186, 0x6bfc116e
+0,         26, -9223372036854775808,        1,     1186, 0x6bfc116e, F=0x0
 1,      79920,      79920,     2160,      768, 0x00cb785f
-0,         27, -9223372036854775808,        1,     1187, 0xcfc512ae
+0,         27, -9223372036854775808,        1,     1187, 0xcfc512ae, F=0x0
 1,      82080,      82080,     2160,      768, 0x1dda7032
-0,         28, -9223372036854775808,        1,     1527, 0x5c2c965a
+0,         28, -9223372036854775808,        1,     1527, 0x5c2c965a, F=0x0
 1,      84240,      84240,     2160,      768, 0xf57c7103
 1,      86400,      86400,     2160,      768, 0x2d927183
-0,         29, -9223372036854775808,        1,     1536, 0x5ba7ac29
+0,         29, -9223372036854775808,        1,     1536, 0x5ba7ac29, F=0x0
 1,      88560,      88560,     2160,      768, 0xdae86cdf
-0,         30, -9223372036854775808,        1,     1095, 0xce06eb96
+0,         30, -9223372036854775808,        1,     1095, 0xce06eb96, F=0x0
 1,      90720,      90720,     2160,      768, 0x2a2f6c3c
 1,      92880,      92880,     2160,      768, 0x44696eba
-0,         31, -9223372036854775808,        1,     1402, 0x642f6b0d
+0,         31, -9223372036854775808,        1,     1402, 0x642f6b0d, F=0x0
 1,      95040,      95040,     2160,      768, 0xf67c71c4
 0,         32, -9223372036854775808,        1,     5551, 0xf01a9c08
 1,      97200,      97200,     2160,      768, 0xc1ce7237
-0,         33, -9223372036854775808,        1,     1211, 0x350206f7
+0,         33, -9223372036854775808,        1,     1211, 0x350206f7, F=0x0
 1,      99360,      99360,     2160,      768, 0xd9c36ef5
 1,     101520,     101520,     2160,      768, 0x63b06b03
-0,         34, -9223372036854775808,        1,      887, 0x08767619
+0,         34, -9223372036854775808,        1,      887, 0x08767619, F=0x0
 1,     103680,     103680,     2160,      768, 0x8de97ebe
-0,         35, -9223372036854775808,        1,     1042, 0xcc81a9ed
+0,         35, -9223372036854775808,        1,     1042, 0xcc81a9ed, F=0x0
 1,     105840,     105840,     2160,      768, 0xbf117c32
 1,     108000,     108000,     2160,      768, 0x82897497
-0,         36, -9223372036854775808,        1,     1247, 0x6f320614
+0,         36, -9223372036854775808,        1,     1247, 0x6f320614, F=0x0
 1,     110160,     110160,     2160,      768, 0x7a347abb
-0,         37, -9223372036854775808,        1,     1459, 0xd28975b5
+0,         37, -9223372036854775808,        1,     1459, 0xd28975b5, F=0x0
 1,     112320,     112320,     2160,      768, 0xc99b691e
-0,         38, -9223372036854775808,        1,     1116, 0x1ab1e9db
+0,         38, -9223372036854775808,        1,     1116, 0x1ab1e9db, F=0x0
 1,     114480,     114480,     2160,      768, 0xf4fc6e74
 1,     116640,     116640,     2160,      768, 0x511d6ec4
-0,         39, -9223372036854775808,        1,     1110, 0x6411f66a
+0,         39, -9223372036854775808,        1,     1110, 0x6411f66a, F=0x0
 1,     118800,     118800,     2160,      768, 0xb8c06b5f
-0,         40, -9223372036854775808,        1,     1282, 0xd468375d
+0,         40, -9223372036854775808,        1,     1282, 0xd468375d, F=0x0
 1,     120960,     120960,     2160,      768, 0xf1776aed
 1,     123120,     123120,     2160,      768, 0xe6fe7fb4
-0,         41, -9223372036854775808,        1,     1077, 0x1273c6e3
+0,         41, -9223372036854775808,        1,     1077, 0x1273c6e3, F=0x0
 1,     125280,     125280,     2160,      768, 0x36907aff
-0,         42, -9223372036854775808,        1,     1043, 0x12dbd3ae
+0,         42, -9223372036854775808,        1,     1043, 0x12dbd3ae, F=0x0
 1,     127440,     127440,     2160,      768, 0xddf666bb
-0,         43, -9223372036854775808,        1,     1087, 0x3e70d37a
+0,         43, -9223372036854775808,        1,     1087, 0x3e70d37a, F=0x0
 1,     129600,     129600,     2160,      768, 0x8e896ebc
 1,     131760,     131760,     2160,      768, 0x0aa47dfa
-0,         44, -9223372036854775808,        1,      992, 0x0651a71c
+0,         44, -9223372036854775808,        1,      992, 0x0651a71c, F=0x0
 1,     133920,     133920,     2160,      768, 0xc1736811
-0,         45, -9223372036854775808,        1,     1012, 0x6a069f8c
+0,         45, -9223372036854775808,        1,     1012, 0x6a069f8c, F=0x0
 1,     136080,     136080,     2160,      768, 0xb3e87009
-0,         46, -9223372036854775808,        1,     1320, 0x92803d69
+0,         46, -9223372036854775808,        1,     1320, 0x92803d69, F=0x0
 1,     138240,     138240,     2160,      768, 0xf23e6c00
 1,     140400,     140400,     2160,      768, 0x993a71d2
-0,         47, -9223372036854775808,        1,     1080, 0xe0ffbe95
+0,         47, -9223372036854775808,        1,     1080, 0xe0ffbe95, F=0x0
 1,     142560,     142560,     2160,      768, 0xa53466dd
 0,         48, -9223372036854775808,        1,     5639, 0x658ca26b
 1,     144720,     144720,     2160,      768, 0xb43a74b0
 1,     146880,     146880,     2160,      768, 0x348f615c
-0,         49, -9223372036854775808,        1,     1385, 0xbcb96241
+0,         49, -9223372036854775808,        1,     1385, 0xbcb96241, F=0x0
 1,     149040,     149040,     2160,      768, 0x298f6e1b
-0,         50, -9223372036854775808,        1,     1142, 0x8c6df318
+0,         50, -9223372036854775808,        1,     1142, 0x8c6df318, F=0x0
 1,     151200,     151200,     2160,      768, 0x5db469c8
-0,         51, -9223372036854775808,        1,     1175, 0xcac1faef
+0,         51, -9223372036854775808,        1,     1175, 0xcac1faef, F=0x0
 1,     153360,     153360,     2160,      768, 0x08f16c2c
 1,     155520,     155520,     2160,      768, 0x4a0474cb
-0,         52, -9223372036854775808,        1,     1091, 0xa937e32a
+0,         52, -9223372036854775808,        1,     1091, 0xa937e32a, F=0x0
 1,     157680,     157680,     2160,      768, 0x077c760b
-0,         53, -9223372036854775808,        1,     1174, 0xfa50040d
+0,         53, -9223372036854775808,        1,     1174, 0xfa50040d, F=0x0
 1,     159840,     159840,     2160,      768, 0xa5777c2e
 1,     162000,     162000,     2160,      768, 0x0d157ea6
-0,         54, -9223372036854775808,        1,     1293, 0x0c8d2740
+0,         54, -9223372036854775808,        1,     1293, 0x0c8d2740, F=0x0
 1,     164160,     164160,     2160,      768, 0x9bc26f86
-0,         55, -9223372036854775808,        1,     1262, 0x502c0c35
+0,         55, -9223372036854775808,        1,     1262, 0x502c0c35, F=0x0
 1,     166320,     166320,     2160,      768, 0x1a72742d
-0,         56, -9223372036854775808,        1,     1038, 0x5e98c0cd
+0,         56, -9223372036854775808,        1,     1038, 0x5e98c0cd, F=0x0
 1,     168480,     168480,     2160,      768, 0xa5bb6bbb
 1,     170640,     170640,     2160,      768, 0x48496c4c
-0,         57, -9223372036854775808,        1,     1362, 0x256e43cf
+0,         57, -9223372036854775808,        1,     1362, 0x256e43cf, F=0x0
 1,     172800,     172800,     2160,      768, 0x800d78f0
-0,         58, -9223372036854775808,        1,     1200, 0x29e6f055
+0,         58, -9223372036854775808,        1,     1200, 0x29e6f055, F=0x0
 1,     174960,     174960,     2160,      768, 0x40db840c
 1,     177120,     177120,     2160,      768, 0xadc96a6b
-0,         59, -9223372036854775808,        1,     1495, 0x88e9b973
+0,         59, -9223372036854775808,        1,     1495, 0x88e9b973, F=0x0
 1,     179280,     179280,     2160,      768, 0xff986b03
-0,         60, -9223372036854775808,        1,     1386, 0x849297d2
+0,         60, -9223372036854775808,        1,     1386, 0x849297d2, F=0x0
 1,     181440,     181440,     2160,      768, 0x152473d6
-0,         61, -9223372036854775808,        1,     1572, 0x63b7dc79
+0,         61, -9223372036854775808,        1,     1572, 0x63b7dc79, F=0x0
 1,     183600,     183600,     2160,      768, 0x01567323
 1,     185760,     185760,     2160,      768, 0xe5f26fe5
-0,         62, -9223372036854775808,        1,     1190, 0x32ccf4cb
+0,         62, -9223372036854775808,        1,     1190, 0x32ccf4cb, F=0x0
 1,     187920,     187920,     2160,      768, 0xa8fd72cd
-0,         63, -9223372036854775808,        1,     1395, 0xa6ec4ae9
+0,         63, -9223372036854775808,        1,     1395, 0xa6ec4ae9, F=0x0
 1,     190080,     190080,     2160,      768, 0x8857655b
 0,         64, -9223372036854775808,        1,     5692, 0x81aed6f3
 1,     192240,     192240,     2160,      768, 0x84017b13
 1,     194400,     194400,     2160,      768, 0xe6a968b3
-0,         65, -9223372036854775808,        1,     1335, 0xe98a5497
+0,         65, -9223372036854775808,        1,     1335, 0xe98a5497, F=0x0
 1,     196560,     196560,     2160,      768, 0xb03a7566
-0,         66, -9223372036854775808,        1,     1361, 0x8ae15ab5
+0,         66, -9223372036854775808,        1,     1361, 0x8ae15ab5, F=0x0
 1,     198720,     198720,     2160,      768, 0x8bea5f62
 1,     200880,     200880,     2160,      768, 0xac7570b0
-0,         67, -9223372036854775808,        1,     1525, 0xed2bc1e8
+0,         67, -9223372036854775808,        1,     1525, 0xed2bc1e8, F=0x0
 1,     203040,     203040,     2160,      768, 0x11306fac
-0,         68, -9223372036854775808,        1,     1570, 0xba70d74b
+0,         68, -9223372036854775808,        1,     1570, 0xba70d74b, F=0x0
 1,     205200,     205200,     2160,      768, 0xf2af5b28
-0,         69, -9223372036854775808,        1,     1349, 0xd97a687d
+0,         69, -9223372036854775808,        1,     1349, 0xd97a687d, F=0x0
 1,     207360,     207360,     2160,      768, 0x3069681f
 1,     209520,     209520,     2160,      768, 0x7ff07033
-0,         70, -9223372036854775808,        1,     1270, 0xca8c3ca8
+0,         70, -9223372036854775808,        1,     1270, 0xca8c3ca8, F=0x0
 1,     211680,     211680,     2160,      768, 0xd74973f2
-0,         71, -9223372036854775808,        1,     1016, 0x32d0c81a
+0,         71, -9223372036854775808,        1,     1016, 0x32d0c81a, F=0x0
 1,     213840,     213840,     2160,      768, 0xb3627304
 1,     216000,     216000,     2160,      768, 0x11ff7589
-0,         72, -9223372036854775808,        1,      983, 0x536faa97
+0,         72, -9223372036854775808,        1,      983, 0x536faa97, F=0x0
 1,     218160,     218160,     2160,      768, 0x4a156c63
-0,         73, -9223372036854775808,        1,     1111, 0x44ade015
+0,         73, -9223372036854775808,        1,     1111, 0x44ade015, F=0x0
 1,     220320,     220320,     2160,      768, 0xcb036127
-0,         74, -9223372036854775808,        1,     1314, 0xce7c477d
+0,         74, -9223372036854775808,        1,     1314, 0xce7c477d, F=0x0
 1,     222480,     222480,     2160,      768, 0x0b796bb9
 1,     224640,     224640,     2160,      768, 0x1d516c35
-0,         75, -9223372036854775808,        1,     1005, 0x0196b491
+0,         75, -9223372036854775808,        1,     1005, 0x0196b491, F=0x0
 1,     226800,     226800,     2160,      768, 0xa9146da1
-0,         76, -9223372036854775808,        1,     1162, 0xb8f6ebe6
+0,         76, -9223372036854775808,        1,     1162, 0xb8f6ebe6, F=0x0
 1,     228960,     228960,     2160,      768, 0x6d176392
 1,     231120,     231120,     2160,      768, 0x6f966269
-0,         77, -9223372036854775808,        1,     1440, 0xfca67c72
+0,         77, -9223372036854775808,        1,     1440, 0xfca67c72, F=0x0
 1,     233280,     233280,     2160,      768, 0x7ee17724
-0,         78, -9223372036854775808,        1,     1437, 0x491181b1
+0,         78, -9223372036854775808,        1,     1437, 0x491181b1, F=0x0
 1,     235440,     235440,     2160,      768, 0x3f07614a
-0,         79, -9223372036854775808,        1,     1261, 0xf0cd1898
+0,         79, -9223372036854775808,        1,     1261, 0xf0cd1898, F=0x0
 1,     237600,     237600,     2160,      768, 0x49d56945
 1,     239760,     239760,     2160,      768, 0x68eb660a
 0,         80, -9223372036854775808,        1,     5638, 0x3a25a9f2
 1,     241920,     241920,     2160,      768, 0xe7c96677
-0,         81, -9223372036854775808,        1,     1091, 0x67d9c693
+0,         81, -9223372036854775808,        1,     1091, 0x67d9c693, F=0x0
 1,     244080,     244080,     2160,      768, 0x7dc07a35
 1,     246240,     246240,     2160,      768, 0x1e9c6397
-0,         82, -9223372036854775808,        1,      875, 0x52147bb1
+0,         82, -9223372036854775808,        1,      875, 0x52147bb1, F=0x0
 1,     248400,     248400,     2160,      768, 0x93ef5de4
-0,         83, -9223372036854775808,        1,     1188, 0x8522000f
+0,         83, -9223372036854775808,        1,     1188, 0x8522000f, F=0x0
 1,     250560,     250560,     2160,      768, 0x34af6803
-0,         84, -9223372036854775808,        1,     1360, 0x89b82e7b
+0,         84, -9223372036854775808,        1,     1360, 0x89b82e7b, F=0x0
 1,     252720,     252720,     2160,      768, 0x77e068be
 1,     254880,     254880,     2160,      768, 0x65e274de
-0,         85, -9223372036854775808,        1,     1378, 0xe8644914
+0,         85, -9223372036854775808,        1,     1378, 0xe8644914, F=0x0
 1,     257040,     257040,     2160,      768, 0xb7ad6a8a
-0,         86, -9223372036854775808,        1,     1194, 0x89fef83d
+0,         86, -9223372036854775808,        1,     1194, 0x89fef83d, F=0x0
 1,     259200,     259200,     2160,      768, 0x84b3635f
-0,         87, -9223372036854775808,        1,     1422, 0x99daa18b
+0,         87, -9223372036854775808,        1,     1422, 0x99daa18b, F=0x0
 1,     261360,     261360,     2160,      768, 0x066b78f2
 1,     263520,     263520,     2160,      768, 0xda137428
-0,         88, -9223372036854775808,        1,     1049, 0x72a9cec1
+0,         88, -9223372036854775808,        1,     1049, 0x72a9cec1, F=0x0
 1,     265680,     265680,     2160,      768, 0xfd6c7597
-0,         89, -9223372036854775808,        1,     1327, 0x7d15307c
+0,         89, -9223372036854775808,        1,     1327, 0x7d15307c, F=0x0
 1,     267840,     267840,     2160,      768, 0x8d766d40
diff --git a/tests/ref/fate/lossless-tak b/tests/ref/fate/lossless-tak
new file mode 100644
index 0000000..9e9ba47
--- /dev/null
+++ b/tests/ref/fate/lossless-tak
@@ -0,0 +1 @@
+CRC=0x4ec0971f
diff --git a/tests/ref/fate/mtv b/tests/ref/fate/mtv
index 4f8f616..a781c08 100644
--- a/tests/ref/fate/mtv
+++ b/tests/ref/fate/mtv
@@ -133,6 +133,6 @@
 1,     104832,     104832,     1152,      418, 0xa105cdcc
 1,     105984,     105984,     1152,      418, 0x1477ba58
 1,     107136,     107136,     1152,      418, 0x8d0dcdb2
-0,         39,         39,        1,     3584, 0x0354c435
+0,         39,         39,        1,     3584, 0x0354c435, F=0x3
 1,     108288,     108288,     1152,      418, 0x0d7cbef4
 1,     109440,     109440,     1152,      294, 0x5e2b87c4
diff --git a/tests/ref/fate/mxf-demux b/tests/ref/fate/mxf-demux
index e162775..454722e 100644
--- a/tests/ref/fate/mxf-demux
+++ b/tests/ref/fate/mxf-demux
@@ -1,99 +1,99 @@
 #tb 0: 1/25
-#tb 1: 1/25
+#tb 1: 1/8000
 0,          0, -9223372036854775808,        1,     8468, 0xc0855553
-1,          0,          0,       50,    32000, 0x479155e6
-0,          1, -9223372036854775808,        1,     3814, 0xa10783b4
-0,          2, -9223372036854775808,        1,     3747, 0xb7bf6973
-0,          3, -9223372036854775808,        1,     3705, 0x5462a600
-0,          4, -9223372036854775808,        1,     3704, 0x1e564943
-0,          5, -9223372036854775808,        1,     3760, 0x10464b9a
-0,          6, -9223372036854775808,        1,     3799, 0xd41d6dcf
-0,          7, -9223372036854775808,        1,     3832, 0x5cf6999e
-0,          8, -9223372036854775808,        1,     3778, 0xe5fc7b9e
-0,          9, -9223372036854775808,        1,    38193, 0xd34e5dd4
+1,          0,          0,    16000,    32000, 0x479155e6
+0,          1, -9223372036854775808,        1,     3814, 0xa10783b4, F=0x0
+0,          2, -9223372036854775808,        1,     3747, 0xb7bf6973, F=0x0
+0,          3, -9223372036854775808,        1,     3705, 0x5462a600, F=0x0
+0,          4, -9223372036854775808,        1,     3704, 0x1e564943, F=0x0
+0,          5, -9223372036854775808,        1,     3760, 0x10464b9a, F=0x0
+0,          6, -9223372036854775808,        1,     3799, 0xd41d6dcf, F=0x0
+0,          7, -9223372036854775808,        1,     3832, 0x5cf6999e, F=0x0
+0,          8, -9223372036854775808,        1,     3778, 0xe5fc7b9e, F=0x0
+0,          9, -9223372036854775808,        1,    38193, 0xd34e5dd4, F=0x0
 0,         10, -9223372036854775808,        1,     8520, 0x2a203e68
-0,         11, -9223372036854775808,        1,     3832, 0xe4c4b2fe
-0,         12, -9223372036854775808,        1,     3787, 0x0cf95fee
-0,         13, -9223372036854775808,        1,     3766, 0x9e019d14
-0,         14, -9223372036854775808,        1,     3785, 0x0ea9ae75
-0,         15, -9223372036854775808,        1,     3703, 0x11d349ff
-0,         16, -9223372036854775808,        1,     3731, 0x5cf358ef
-0,         17, -9223372036854775808,        1,     3785, 0x01c8962f
-0,         18, -9223372036854775808,        1,     3741, 0xb2c47d53
-0,         19, -9223372036854775808,        1,    38150, 0x08fa1f55
+0,         11, -9223372036854775808,        1,     3832, 0xe4c4b2fe, F=0x0
+0,         12, -9223372036854775808,        1,     3787, 0x0cf95fee, F=0x0
+0,         13, -9223372036854775808,        1,     3766, 0x9e019d14, F=0x0
+0,         14, -9223372036854775808,        1,     3785, 0x0ea9ae75, F=0x0
+0,         15, -9223372036854775808,        1,     3703, 0x11d349ff, F=0x0
+0,         16, -9223372036854775808,        1,     3731, 0x5cf358ef, F=0x0
+0,         17, -9223372036854775808,        1,     3785, 0x01c8962f, F=0x0
+0,         18, -9223372036854775808,        1,     3741, 0xb2c47d53, F=0x0
+0,         19, -9223372036854775808,        1,    38150, 0x08fa1f55, F=0x0
 0,         20, -9223372036854775808,        1,     8487, 0x0c234b9a
-0,         21, -9223372036854775808,        1,     3791, 0x831192ef
-0,         22, -9223372036854775808,        1,     3612, 0x598944fb
-0,         23, -9223372036854775808,        1,     3710, 0xccbb711a
-0,         24, -9223372036854775808,        1,     3864, 0x4385966e
-0,         25, -9223372036854775808,        1,     3919, 0x24e2abc3
-0,         26, -9223372036854775808,        1,     3777, 0x210c6219
-0,         27, -9223372036854775808,        1,     3811, 0x23bf68c2
-0,         28, -9223372036854775808,        1,     3802, 0x52688862
-0,         29, -9223372036854775808,        1,    38027, 0x3d5aa8b9
+0,         21, -9223372036854775808,        1,     3791, 0x831192ef, F=0x0
+0,         22, -9223372036854775808,        1,     3612, 0x598944fb, F=0x0
+0,         23, -9223372036854775808,        1,     3710, 0xccbb711a, F=0x0
+0,         24, -9223372036854775808,        1,     3864, 0x4385966e, F=0x0
+0,         25, -9223372036854775808,        1,     3919, 0x24e2abc3, F=0x0
+0,         26, -9223372036854775808,        1,     3777, 0x210c6219, F=0x0
+0,         27, -9223372036854775808,        1,     3811, 0x23bf68c2, F=0x0
+0,         28, -9223372036854775808,        1,     3802, 0x52688862, F=0x0
+0,         29, -9223372036854775808,        1,    38027, 0x3d5aa8b9, F=0x0
 0,         30, -9223372036854775808,        1,     8333, 0x617de950
-0,         31, -9223372036854775808,        1,     3831, 0x13fad8fc
-0,         32, -9223372036854775808,        1,     3719, 0xbc317470
-0,         33, -9223372036854775808,        1,     3761, 0xeac460b6
-0,         34, -9223372036854775808,        1,     3637, 0x27d64b32
-0,         35, -9223372036854775808,        1,     3666, 0xf0f700a5
-0,         36, -9223372036854775808,        1,     3788, 0x1c4662a8
-0,         37, -9223372036854775808,        1,     3960, 0xef6b9e99
-0,         38, -9223372036854775808,        1,     3793, 0x3a6ca832
-0,         39, -9223372036854775808,        1,    38312, 0xce1317cc
+0,         31, -9223372036854775808,        1,     3831, 0x13fad8fc, F=0x0
+0,         32, -9223372036854775808,        1,     3719, 0xbc317470, F=0x0
+0,         33, -9223372036854775808,        1,     3761, 0xeac460b6, F=0x0
+0,         34, -9223372036854775808,        1,     3637, 0x27d64b32, F=0x0
+0,         35, -9223372036854775808,        1,     3666, 0xf0f700a5, F=0x0
+0,         36, -9223372036854775808,        1,     3788, 0x1c4662a8, F=0x0
+0,         37, -9223372036854775808,        1,     3960, 0xef6b9e99, F=0x0
+0,         38, -9223372036854775808,        1,     3793, 0x3a6ca832, F=0x0
+0,         39, -9223372036854775808,        1,    38312, 0xce1317cc, F=0x0
 0,         40, -9223372036854775808,        1,     8548, 0x4ca944d4
-0,         41, -9223372036854775808,        1,     3866, 0x4e85bf0f
-0,         42, -9223372036854775808,        1,     3644, 0x030338e5
-0,         43, -9223372036854775808,        1,     3634, 0xa95f4512
-0,         44, -9223372036854775808,        1,     3925, 0x7583ba86
-0,         45, -9223372036854775808,        1,     3675, 0x979f423f
-0,         46, -9223372036854775808,        1,     3703, 0x11375f7a
-0,         47, -9223372036854775808,        1,     3705, 0xb7de5d16
-0,         48, -9223372036854775808,        1,     3688, 0x1db45852
-0,         49, -9223372036854775808,        1,    38412, 0x2ee26a63
+0,         41, -9223372036854775808,        1,     3866, 0x4e85bf0f, F=0x0
+0,         42, -9223372036854775808,        1,     3644, 0x030338e5, F=0x0
+0,         43, -9223372036854775808,        1,     3634, 0xa95f4512, F=0x0
+0,         44, -9223372036854775808,        1,     3925, 0x7583ba86, F=0x0
+0,         45, -9223372036854775808,        1,     3675, 0x979f423f, F=0x0
+0,         46, -9223372036854775808,        1,     3703, 0x11375f7a, F=0x0
+0,         47, -9223372036854775808,        1,     3705, 0xb7de5d16, F=0x0
+0,         48, -9223372036854775808,        1,     3688, 0x1db45852, F=0x0
+0,         49, -9223372036854775808,        1,    38412, 0x2ee26a63, F=0x0
 0,         50, -9223372036854775808,        1,     8385, 0x0bc20a27
-1,         50,         50,       50,    32000, 0x8f7e5009
-0,         51, -9223372036854775808,        1,     3733, 0xa3e2a9a0
-0,         52, -9223372036854775808,        1,     3773, 0x27769caa
-0,         53, -9223372036854775808,        1,     3670, 0xc8335e98
-0,         54, -9223372036854775808,        1,     3596, 0xd6512fb0
-0,         55, -9223372036854775808,        1,     3579, 0xa621fbc2
-0,         56, -9223372036854775808,        1,     3641, 0x2f4f46ca
-0,         57, -9223372036854775808,        1,     3686, 0x0a92385a
-0,         58, -9223372036854775808,        1,     3672, 0xe65137b9
-0,         59, -9223372036854775808,        1,    39065, 0xc723bf8b
+1,      16000,      16000,    16000,    32000, 0x8f7e5009
+0,         51, -9223372036854775808,        1,     3733, 0xa3e2a9a0, F=0x0
+0,         52, -9223372036854775808,        1,     3773, 0x27769caa, F=0x0
+0,         53, -9223372036854775808,        1,     3670, 0xc8335e98, F=0x0
+0,         54, -9223372036854775808,        1,     3596, 0xd6512fb0, F=0x0
+0,         55, -9223372036854775808,        1,     3579, 0xa621fbc2, F=0x0
+0,         56, -9223372036854775808,        1,     3641, 0x2f4f46ca, F=0x0
+0,         57, -9223372036854775808,        1,     3686, 0x0a92385a, F=0x0
+0,         58, -9223372036854775808,        1,     3672, 0xe65137b9, F=0x0
+0,         59, -9223372036854775808,        1,    39065, 0xc723bf8b, F=0x0
 0,         60, -9223372036854775808,        1,     8611, 0x5d177f40
-0,         61, -9223372036854775808,        1,     3758, 0x33d59966
-0,         62, -9223372036854775808,        1,     3674, 0x54f37902
-0,         63, -9223372036854775808,        1,     3615, 0xa0f045fa
-0,         64, -9223372036854775808,        1,     3719, 0x41cf93ff
-0,         65, -9223372036854775808,        1,     3757, 0x3a1b7e8f
-0,         66, -9223372036854775808,        1,     3762, 0xe7f9714d
-0,         67, -9223372036854775808,        1,     3738, 0x8121805b
-0,         68, -9223372036854775808,        1,     3733, 0x13e262db
-0,         69, -9223372036854775808,        1,    38433, 0x3d58c500
+0,         61, -9223372036854775808,        1,     3758, 0x33d59966, F=0x0
+0,         62, -9223372036854775808,        1,     3674, 0x54f37902, F=0x0
+0,         63, -9223372036854775808,        1,     3615, 0xa0f045fa, F=0x0
+0,         64, -9223372036854775808,        1,     3719, 0x41cf93ff, F=0x0
+0,         65, -9223372036854775808,        1,     3757, 0x3a1b7e8f, F=0x0
+0,         66, -9223372036854775808,        1,     3762, 0xe7f9714d, F=0x0
+0,         67, -9223372036854775808,        1,     3738, 0x8121805b, F=0x0
+0,         68, -9223372036854775808,        1,     3733, 0x13e262db, F=0x0
+0,         69, -9223372036854775808,        1,    38433, 0x3d58c500, F=0x0
 0,         70, -9223372036854775808,        1,     8410, 0xa4f7fd2e
-0,         71, -9223372036854775808,        1,     3711, 0x0e112d3c
-0,         72, -9223372036854775808,        1,     3692, 0xb46574b2
-0,         73, -9223372036854775808,        1,     3563, 0xad43343d
-0,         74, -9223372036854775808,        1,     3613, 0x5cd85c4f
-0,         75, -9223372036854775808,        1,     3653, 0xe15a2853
-0,         76, -9223372036854775808,        1,     3684, 0x9ddd58cb
-0,         77, -9223372036854775808,        1,     3256, 0xd7f89f2e
-0,         78, -9223372036854775808,        1,     3698, 0x2b82624a
-0,         79, -9223372036854775808,        1,    39520, 0xd3f2b7c5
+0,         71, -9223372036854775808,        1,     3711, 0x0e112d3c, F=0x0
+0,         72, -9223372036854775808,        1,     3692, 0xb46574b2, F=0x0
+0,         73, -9223372036854775808,        1,     3563, 0xad43343d, F=0x0
+0,         74, -9223372036854775808,        1,     3613, 0x5cd85c4f, F=0x0
+0,         75, -9223372036854775808,        1,     3653, 0xe15a2853, F=0x0
+0,         76, -9223372036854775808,        1,     3684, 0x9ddd58cb, F=0x0
+0,         77, -9223372036854775808,        1,     3256, 0xd7f89f2e, F=0x0
+0,         78, -9223372036854775808,        1,     3698, 0x2b82624a, F=0x0
+0,         79, -9223372036854775808,        1,    39520, 0xd3f2b7c5, F=0x0
 0,         80, -9223372036854775808,        1,     8493, 0x163559be
-0,         81, -9223372036854775808,        1,     3719, 0x6fa0916f
-0,         82, -9223372036854775808,        1,     3655, 0xa9233de1
-0,         83, -9223372036854775808,        1,     3684, 0xa6125737
-0,         84, -9223372036854775808,        1,     3688, 0xa9da6686
-0,         85, -9223372036854775808,        1,     3685, 0x674d634e
-0,         86, -9223372036854775808,        1,     3677, 0x7a85535d
-0,         87, -9223372036854775808,        1,     3666, 0xce3600a2
-0,         88, -9223372036854775808,        1,     3837, 0x3a7090e1
-0,         89, -9223372036854775808,        1,    38696, 0x12c59cd2
+0,         81, -9223372036854775808,        1,     3719, 0x6fa0916f, F=0x0
+0,         82, -9223372036854775808,        1,     3655, 0xa9233de1, F=0x0
+0,         83, -9223372036854775808,        1,     3684, 0xa6125737, F=0x0
+0,         84, -9223372036854775808,        1,     3688, 0xa9da6686, F=0x0
+0,         85, -9223372036854775808,        1,     3685, 0x674d634e, F=0x0
+0,         86, -9223372036854775808,        1,     3677, 0x7a85535d, F=0x0
+0,         87, -9223372036854775808,        1,     3666, 0xce3600a2, F=0x0
+0,         88, -9223372036854775808,        1,     3837, 0x3a7090e1, F=0x0
+0,         89, -9223372036854775808,        1,    38696, 0x12c59cd2, F=0x0
 0,         90, -9223372036854775808,        1,     8022, 0xd343433f
-0,         91, -9223372036854775808,        1,     5157, 0x440c14e5
-0,         92, -9223372036854775808,        1,     5003, 0xf8e1daff
-0,         93, -9223372036854775808,        1,     4954, 0x89866344
-0,         94, -9223372036854775808,        1,    53664, 0xeb0c4c42
+0,         91, -9223372036854775808,        1,     5157, 0x440c14e5, F=0x0
+0,         92, -9223372036854775808,        1,     5003, 0xf8e1daff, F=0x0
+0,         93, -9223372036854775808,        1,     4954, 0x89866344, F=0x0
+0,         94, -9223372036854775808,        1,    53664, 0xeb0c4c42, F=0x0
diff --git a/tests/ref/fate/mxpeg b/tests/ref/fate/mxpeg
new file mode 100644
index 0000000..90af90f
--- /dev/null
+++ b/tests/ref/fate/mxpeg
@@ -0,0 +1,31 @@
+#tb 0: 4/63
+0,          0,          0,        1,  1843200, 0x868a4e64
+0,          4,          4,        1,  1843200, 0x8dda4373
+0,          6,          6,        1,  1843200, 0xfcde3afc
+0,          8,          8,        1,  1843200, 0xeb4048a7
+0,         12,         12,        1,  1843200, 0xe2aa5718
+0,         14,         14,        1,  1843200, 0x86c35765
+0,         16,         16,        1,  1843200, 0x05c66542
+0,         18,         18,        1,  1843200, 0x020967f8
+0,         22,         22,        1,  1843200, 0x57757510
+0,         24,         24,        1,  1843200, 0xb91c61be
+0,         26,         26,        1,  1843200, 0x702381e9
+0,         30,         30,        1,  1843200, 0xe28c6851
+0,         32,         32,        1,  1843200, 0x7f806daa
+0,         34,         34,        1,  1843200, 0xc0758a39
+0,         38,         38,        1,  1843200, 0x3af87be2
+0,         40,         40,        1,  1843200, 0x1d1876eb
+0,         42,         42,        1,  1843200, 0x720e81dd
+0,         44,         44,        1,  1843200, 0xd85b7556
+0,         48,         48,        1,  1843200, 0xb9968314
+0,         50,         50,        1,  1843200, 0x946b9d34
+0,         52,         52,        1,  1843200, 0xd2d87d03
+0,         54,         54,        1,  1843200, 0xdd1b8056
+0,         58,         58,        1,  1843200, 0x436b7937
+0,         60,         60,        1,  1843200, 0xe87a6e42
+0,         62,         62,        1,  1843200, 0x57475c09
+0,         64,         64,        1,  1843200, 0xc3b45a77
+0,         68,         68,        1,  1843200, 0x0308494c
+0,         70,         70,        1,  1843200, 0x1ed02c80
+0,         72,         72,        1,  1843200, 0x48602e92
+0,         74,         74,        1,  1843200, 0xcf332caa
diff --git a/tests/ref/fate/nc-demux b/tests/ref/fate/nc-demux
index 1d00f8e..f03aded 100644
--- a/tests/ref/fate/nc-demux
+++ b/tests/ref/fate/nc-demux
@@ -1,92 +1,92 @@
 #tb 0: 1/100
 0,          0, -9223372036854775808,        1,    19787, 0x75e463f3
-0,          1, -9223372036854775808,        1,    11913, 0x0f429c34
-0,          2, -9223372036854775808,        1,    14225, 0xbd3c704c
-0,          3, -9223372036854775808,        1,    10357, 0xbf232393
-0,          4, -9223372036854775808,        1,     9595, 0xf565d39e
-0,          5, -9223372036854775808,        1,     9262, 0x2afd6ce0
-0,          6, -9223372036854775808,        1,    12214, 0x6ae81d9b
-0,          7, -9223372036854775808,        1,    13920, 0x31b5b307
-0,          8, -9223372036854775808,        1,    10164, 0x141eca4e
-0,          9, -9223372036854775808,        1,     9516, 0xd5f2c42b
-0,         10, -9223372036854775808,        1,    10006, 0x80850a76
-0,         11, -9223372036854775808,        1,    11791, 0x10bc2dcd
-0,         12, -9223372036854775808,        1,    13756, 0xda1fee08
-0,         13, -9223372036854775808,        1,    10452, 0xbb3d62b0
-0,         14, -9223372036854775808,        1,     9171, 0x64ae10f6
-0,         15, -9223372036854775808,        1,     8816, 0x31ad8fcb
-0,         16, -9223372036854775808,        1,    13168, 0xea1085ac
-0,         17, -9223372036854775808,        1,    12797, 0x25143d22
-0,         18, -9223372036854775808,        1,    11324, 0x3a54b38e
-0,         19, -9223372036854775808,        1,     9173, 0x8b2bf552
-0,         20, -9223372036854775808,        1,     9247, 0x2e87226b
-0,         21, -9223372036854775808,        1,    14140, 0x1063786c
-0,         22, -9223372036854775808,        1,    14437, 0xde123a17
-0,         23, -9223372036854775808,        1,    11938, 0x3f1168f4
-0,         24, -9223372036854775808,        1,    11966, 0xdd6786ec
-0,         25, -9223372036854775808,        1,    13213, 0x8ab27c58
-0,         26, -9223372036854775808,        1,    11843, 0x90415d8b
-0,         27, -9223372036854775808,        1,    13345, 0x3c0e1793
-0,         28, -9223372036854775808,        1,     9977, 0x74fc7f4b
-0,         29, -9223372036854775808,        1,     9158, 0x0b5426a5
-0,         30, -9223372036854775808,        1,    12715, 0x0035d569
+0,          1, -9223372036854775808,        1,    11913, 0x0f429c34, F=0x0
+0,          2, -9223372036854775808,        1,    14225, 0xbd3c704c, F=0x0
+0,          3, -9223372036854775808,        1,    10357, 0xbf232393, F=0x0
+0,          4, -9223372036854775808,        1,     9595, 0xf565d39e, F=0x0
+0,          5, -9223372036854775808,        1,     9262, 0x2afd6ce0, F=0x0
+0,          6, -9223372036854775808,        1,    12214, 0x6ae81d9b, F=0x0
+0,          7, -9223372036854775808,        1,    13920, 0x31b5b307, F=0x0
+0,          8, -9223372036854775808,        1,    10164, 0x141eca4e, F=0x0
+0,          9, -9223372036854775808,        1,     9516, 0xd5f2c42b, F=0x0
+0,         10, -9223372036854775808,        1,    10006, 0x80850a76, F=0x0
+0,         11, -9223372036854775808,        1,    11791, 0x10bc2dcd, F=0x0
+0,         12, -9223372036854775808,        1,    13756, 0xda1fee08, F=0x0
+0,         13, -9223372036854775808,        1,    10452, 0xbb3d62b0, F=0x0
+0,         14, -9223372036854775808,        1,     9171, 0x64ae10f6, F=0x0
+0,         15, -9223372036854775808,        1,     8816, 0x31ad8fcb, F=0x0
+0,         16, -9223372036854775808,        1,    13168, 0xea1085ac, F=0x0
+0,         17, -9223372036854775808,        1,    12797, 0x25143d22, F=0x0
+0,         18, -9223372036854775808,        1,    11324, 0x3a54b38e, F=0x0
+0,         19, -9223372036854775808,        1,     9173, 0x8b2bf552, F=0x0
+0,         20, -9223372036854775808,        1,     9247, 0x2e87226b, F=0x0
+0,         21, -9223372036854775808,        1,    14140, 0x1063786c, F=0x0
+0,         22, -9223372036854775808,        1,    14437, 0xde123a17, F=0x0
+0,         23, -9223372036854775808,        1,    11938, 0x3f1168f4, F=0x0
+0,         24, -9223372036854775808,        1,    11966, 0xdd6786ec, F=0x0
+0,         25, -9223372036854775808,        1,    13213, 0x8ab27c58, F=0x0
+0,         26, -9223372036854775808,        1,    11843, 0x90415d8b, F=0x0
+0,         27, -9223372036854775808,        1,    13345, 0x3c0e1793, F=0x0
+0,         28, -9223372036854775808,        1,     9977, 0x74fc7f4b, F=0x0
+0,         29, -9223372036854775808,        1,     9158, 0x0b5426a5, F=0x0
+0,         30, -9223372036854775808,        1,    12715, 0x0035d569, F=0x0
 0,         31, -9223372036854775808,        1,    19944, 0xe2887ba8
-0,         32, -9223372036854775808,        1,    12762, 0xb0f17939
-0,         33, -9223372036854775808,        1,    10260, 0x182b27aa
-0,         34, -9223372036854775808,        1,     7405, 0x227fe9bf
-0,         35, -9223372036854775808,        1,    13317, 0x1a678c62
-0,         36, -9223372036854775808,        1,    11304, 0x3277af6d
-0,         37, -9223372036854775808,        1,    13291, 0xe267616a
-0,         38, -9223372036854775808,        1,     8975, 0xe7eeacea
-0,         39, -9223372036854775808,        1,     8473, 0x8bb1cbff
-0,         40, -9223372036854775808,        1,    13878, 0xfd3d55bb
-0,         41, -9223372036854775808,        1,    11278, 0x61c7c55e
-0,         42, -9223372036854775808,        1,    13785, 0x2acbf88f
-0,         43, -9223372036854775808,        1,     9521, 0x99e2d065
-0,         44, -9223372036854775808,        1,     9340, 0xe5c96510
-0,         45, -9223372036854775808,        1,    12777, 0x4c3c7844
-0,         46, -9223372036854775808,        1,    10685, 0x39e0f42e
-0,         47, -9223372036854775808,        1,    14237, 0x9398d07f
-0,         48, -9223372036854775808,        1,     9021, 0x3343c7ec
-0,         49, -9223372036854775808,        1,     9327, 0xad489e86
-0,         50, -9223372036854775808,        1,    13507, 0xb1344f1c
-0,         51, -9223372036854775808,        1,    10199, 0x9a8868bf
-0,         52, -9223372036854775808,        1,    14535, 0xddb13f41
-0,         53, -9223372036854775808,        1,     8773, 0x3d8b6a79
-0,         54, -9223372036854775808,        1,    16084, 0x5d915de4
-0,         55, -9223372036854775808,        1,     9156, 0x5cb08a6a
-0,         56, -9223372036854775808,        1,    15027, 0xc23b1dc8
-0,         57, -9223372036854775808,        1,     8240, 0xd6d3526c
-0,         58, -9223372036854775808,        1,     8720, 0x439c43bf
-0,         59, -9223372036854775808,        1,    13684, 0x18fc82f0
-0,         60, -9223372036854775808,        1,     8829, 0xa3ebeb30
-0,         61, -9223372036854775808,        1,    14650, 0x99e8678c
+0,         32, -9223372036854775808,        1,    12762, 0xb0f17939, F=0x0
+0,         33, -9223372036854775808,        1,    10260, 0x182b27aa, F=0x0
+0,         34, -9223372036854775808,        1,     7405, 0x227fe9bf, F=0x0
+0,         35, -9223372036854775808,        1,    13317, 0x1a678c62, F=0x0
+0,         36, -9223372036854775808,        1,    11304, 0x3277af6d, F=0x0
+0,         37, -9223372036854775808,        1,    13291, 0xe267616a, F=0x0
+0,         38, -9223372036854775808,        1,     8975, 0xe7eeacea, F=0x0
+0,         39, -9223372036854775808,        1,     8473, 0x8bb1cbff, F=0x0
+0,         40, -9223372036854775808,        1,    13878, 0xfd3d55bb, F=0x0
+0,         41, -9223372036854775808,        1,    11278, 0x61c7c55e, F=0x0
+0,         42, -9223372036854775808,        1,    13785, 0x2acbf88f, F=0x0
+0,         43, -9223372036854775808,        1,     9521, 0x99e2d065, F=0x0
+0,         44, -9223372036854775808,        1,     9340, 0xe5c96510, F=0x0
+0,         45, -9223372036854775808,        1,    12777, 0x4c3c7844, F=0x0
+0,         46, -9223372036854775808,        1,    10685, 0x39e0f42e, F=0x0
+0,         47, -9223372036854775808,        1,    14237, 0x9398d07f, F=0x0
+0,         48, -9223372036854775808,        1,     9021, 0x3343c7ec, F=0x0
+0,         49, -9223372036854775808,        1,     9327, 0xad489e86, F=0x0
+0,         50, -9223372036854775808,        1,    13507, 0xb1344f1c, F=0x0
+0,         51, -9223372036854775808,        1,    10199, 0x9a8868bf, F=0x0
+0,         52, -9223372036854775808,        1,    14535, 0xddb13f41, F=0x0
+0,         53, -9223372036854775808,        1,     8773, 0x3d8b6a79, F=0x0
+0,         54, -9223372036854775808,        1,    16084, 0x5d915de4, F=0x0
+0,         55, -9223372036854775808,        1,     9156, 0x5cb08a6a, F=0x0
+0,         56, -9223372036854775808,        1,    15027, 0xc23b1dc8, F=0x0
+0,         57, -9223372036854775808,        1,     8240, 0xd6d3526c, F=0x0
+0,         58, -9223372036854775808,        1,     8720, 0x439c43bf, F=0x0
+0,         59, -9223372036854775808,        1,    13684, 0x18fc82f0, F=0x0
+0,         60, -9223372036854775808,        1,     8829, 0xa3ebeb30, F=0x0
+0,         61, -9223372036854775808,        1,    14650, 0x99e8678c, F=0x0
 0,         62, -9223372036854775808,        1,    19626, 0x80a7ee5c
-0,         63, -9223372036854775808,        1,     7762, 0x7c209a12
-0,         64, -9223372036854775808,        1,    13636, 0xc89c1aa3
-0,         65, -9223372036854775808,        1,     8337, 0x749bf76a
-0,         66, -9223372036854775808,        1,    15098, 0xc98bc6dc
-0,         67, -9223372036854775808,        1,     9070, 0xcd4cf7f1
-0,         68, -9223372036854775808,        1,     8269, 0x90e95d54
-0,         69, -9223372036854775808,        1,    12672, 0x034888d0
-0,         70, -9223372036854775808,        1,     7519, 0x6c089672
-0,         71, -9223372036854775808,        1,    14439, 0x5d2478b9
-0,         72, -9223372036854775808,        1,     6928, 0x98fbaa67
-0,         73, -9223372036854775808,        1,     8735, 0x07643f1e
-0,         74, -9223372036854775808,        1,    13522, 0x55034cdb
-0,         75, -9223372036854775808,        1,     7807, 0xf5983103
-0,         76, -9223372036854775808,        1,    14484, 0xfc9cf260
-0,         77, -9223372036854775808,        1,     7193, 0x170a0fa1
-0,         78, -9223372036854775808,        1,     9444, 0x6f9be36f
-0,         79, -9223372036854775808,        1,    12598, 0x69b7609d
-0,         80, -9223372036854775808,        1,     7650, 0x1abaec9e
-0,         81, -9223372036854775808,        1,    15162, 0x2a87f723
-0,         82, -9223372036854775808,        1,     7752, 0xcca248aa
-0,         83, -9223372036854775808,        1,     9085, 0x1ca7d7e5
-0,         84, -9223372036854775808,        1,    13187, 0xababcc64
-0,         85, -9223372036854775808,        1,     7968, 0x64a28f46
-0,         86, -9223372036854775808,        1,    15474, 0xf34c587c
-0,         87, -9223372036854775808,        1,     8615, 0x61301034
-0,         88, -9223372036854775808,        1,    14129, 0x42c88bea
-0,         89, -9223372036854775808,        1,     7223, 0x675d7500
-0,         90, -9223372036854775808,        1,     3072, 0x4cb6254c
+0,         63, -9223372036854775808,        1,     7762, 0x7c209a12, F=0x0
+0,         64, -9223372036854775808,        1,    13636, 0xc89c1aa3, F=0x0
+0,         65, -9223372036854775808,        1,     8337, 0x749bf76a, F=0x0
+0,         66, -9223372036854775808,        1,    15098, 0xc98bc6dc, F=0x0
+0,         67, -9223372036854775808,        1,     9070, 0xcd4cf7f1, F=0x0
+0,         68, -9223372036854775808,        1,     8269, 0x90e95d54, F=0x0
+0,         69, -9223372036854775808,        1,    12672, 0x034888d0, F=0x0
+0,         70, -9223372036854775808,        1,     7519, 0x6c089672, F=0x0
+0,         71, -9223372036854775808,        1,    14439, 0x5d2478b9, F=0x0
+0,         72, -9223372036854775808,        1,     6928, 0x98fbaa67, F=0x0
+0,         73, -9223372036854775808,        1,     8735, 0x07643f1e, F=0x0
+0,         74, -9223372036854775808,        1,    13522, 0x55034cdb, F=0x0
+0,         75, -9223372036854775808,        1,     7807, 0xf5983103, F=0x0
+0,         76, -9223372036854775808,        1,    14484, 0xfc9cf260, F=0x0
+0,         77, -9223372036854775808,        1,     7193, 0x170a0fa1, F=0x0
+0,         78, -9223372036854775808,        1,     9444, 0x6f9be36f, F=0x0
+0,         79, -9223372036854775808,        1,    12598, 0x69b7609d, F=0x0
+0,         80, -9223372036854775808,        1,     7650, 0x1abaec9e, F=0x0
+0,         81, -9223372036854775808,        1,    15162, 0x2a87f723, F=0x0
+0,         82, -9223372036854775808,        1,     7752, 0xcca248aa, F=0x0
+0,         83, -9223372036854775808,        1,     9085, 0x1ca7d7e5, F=0x0
+0,         84, -9223372036854775808,        1,    13187, 0xababcc64, F=0x0
+0,         85, -9223372036854775808,        1,     7968, 0x64a28f46, F=0x0
+0,         86, -9223372036854775808,        1,    15474, 0xf34c587c, F=0x0
+0,         87, -9223372036854775808,        1,     8615, 0x61301034, F=0x0
+0,         88, -9223372036854775808,        1,    14129, 0x42c88bea, F=0x0
+0,         89, -9223372036854775808,        1,     7223, 0x675d7500, F=0x0
+0,         90, -9223372036854775808,        1,     3072, 0x4cb6254c, F=0x0
diff --git a/tests/ref/fate/nsv-demux b/tests/ref/fate/nsv-demux
index 0f09446..0ad08b1 100644
--- a/tests/ref/fate/nsv-demux
+++ b/tests/ref/fate/nsv-demux
@@ -1,173 +1,173 @@
 #tb 0: 1001/15000
 #tb 1: 1/30000000
 0,          0,          0,        1,       12, 0x1396035f
-0,          1,          1,        1,       24, 0x8ab80ac7
-0,          2,          2,        1,      208, 0x1de1603e
+0,          1,          1,        1,       24, 0x8ab80ac7, F=0x0
+0,          2,          2,        1,      208, 0x1de1603e, F=0x0
 1,    4173848,    4173848,  1567346,      104, 0x8ae85dc9
 1,    5741194,    5741194,  1567346,      105, 0xb7033847
-0,          3,          3,        1,      364, 0xffb4b341
+0,          3,          3,        1,      364, 0xffb4b341, F=0x0
 1,    7308540,    7308540,  1567346,      104, 0x5f853482
-0,          4,          4,        1,      456, 0x7a4deaeb
+0,          4,          4,        1,      456, 0x7a4deaeb, F=0x0
 1,    8875886,    8875886,  1567346,      105, 0xfcb731fd
-0,          5,          5,        1,      432, 0xf4ddd813
+0,          5,          5,        1,      432, 0xf4ddd813, F=0x0
 1,   10443232,   10443232,  1567346,      104, 0x4f8232bb
 1,   12010578,   12010578,  1567346,      105, 0x2f543039
-0,          6,          6,        1,      572, 0xc84c21ff
+0,          6,          6,        1,      572, 0xc84c21ff, F=0x0
 1,   13577924,   13577924,  1567346,      104, 0xe4cc34a1
-0,          7,          7,        1,      500, 0x0e6bf9f4
+0,          7,          7,        1,      500, 0x0e6bf9f4, F=0x0
 1,   15145270,   15145270,  1567346,      105, 0xea663711
-0,          8,          8,        1,      508, 0x2d6efe2a
+0,          8,          8,        1,      508, 0x2d6efe2a, F=0x0
 1,   16712616,   16712616,  1567346,      104, 0x3c583098
-0,          9,          9,        1,      436, 0x7d07d3c5
+0,          9,          9,        1,      436, 0x7d07d3c5, F=0x0
 1,   18279962,   18279962,  1567346,      105, 0xbe6c33ff
 1,   19847308,   19847308,  1567346,      104, 0x56de2d7a
-0,         10,         10,        1,      620, 0xa9313342
+0,         10,         10,        1,      620, 0xa9313342, F=0x0
 1,   21414654,   21414654,  1567346,      105, 0x4e80385d
 0,         11,         11,        1,     1384, 0x9b97c579
 1,   22982000,   22982000,  1567346,      104, 0x34eb340d
-0,         12,         12,        1,      760, 0xd1aa8183
+0,         12,         12,        1,      760, 0xd1aa8183, F=0x0
 1,   24549346,   24549346,  1567346,      105, 0x87e82f74
-0,         13,         13,        1,      836, 0x261da980
+0,         13,         13,        1,      836, 0x261da980, F=0x0
 1,   26116692,   26116692,  1567346,      104, 0xa546377d
 1,   27684038,   27684038,  1567346,      105, 0x92bd349d
-0,         14,         14,        1,      860, 0x52f0afa0
+0,         14,         14,        1,      860, 0x52f0afa0, F=0x0
 1,   29251384,   29251384,  1567346,      104, 0xdba53f3d
-0,         15,         15,        1,      696, 0x63845855
+0,         15,         15,        1,      696, 0x63845855, F=0x0
 1,   30818730,   30818730,  1567346,      105, 0xd3c3384e
-0,         16,         16,        1,      460, 0x2916e7be
+0,         16,         16,        1,      460, 0x2916e7be, F=0x0
 1,   32386076,   32386076,  1567346,      104, 0xdf7d30ce
 1,   33953422,   33953422,  1567346,      105, 0xae20344e
-0,         17,         17,        1,      328, 0xab8caaca
+0,         17,         17,        1,      328, 0xab8caaca, F=0x0
 1,   35520768,   35520768,  1567346,      104, 0xe4cc33b7
-0,         18,         18,        1,      396, 0xc775bc8e
+0,         18,         18,        1,      396, 0xc775bc8e, F=0x0
 1,   37088114,   37088114,  1567346,      105, 0xda993806
-0,         19,         19,        1,      344, 0x114ea25a
+0,         19,         19,        1,      344, 0x114ea25a, F=0x0
 1,   38655460,   38655460,  1567346,      104, 0xd6d12edd
 1,   40222806,   40222806,  1567346,      105, 0x6b9c2ed5
 1,   41790152,   41790152,  1567346,      104, 0xce6c3b04
-0,         21,         21,        1,      532, 0xd5650f54
+0,         21,         21,        1,      532, 0xd5650f54, F=0x0
 1,   43357498,   43357498,  1567346,      105, 0x31db399e
 1,   44924844,   44924844,  1567346,      104, 0xd50b347a
-0,         23,         23,        1,      476, 0x77f1f3a7
+0,         23,         23,        1,      476, 0x77f1f3a7, F=0x0
 1,   46492190,   46492190,  1567346,      105, 0xe87734d6
 1,   48059536,   48059536,  1567346,      104, 0x21873412
 0,         25,         25,        1,      976, 0x2f7cf7ae
 1,   50140000,   50140000,  1567346,      105, 0x29c03514
 1,   51707346,   51707346,  1567346,      104, 0x91a5347a
 1,   53274692,   53274692,  1567346,      105, 0xdbbf3696
-0,         27,         27,        1,      104, 0x8fbf2f65
+0,         27,         27,        1,      104, 0x8fbf2f65, F=0x0
 1,   54842038,   54842038,  1567346,      104, 0x3b463afc
 1,   56409384,   56409384,  1567346,      105, 0xddf53845
 1,   57976730,   57976730,  1567346,      104, 0x94c23d1a
-0,         29,         29,        1,      652, 0xa9244ac0
+0,         29,         29,        1,      652, 0xa9244ac0, F=0x0
 1,   59544076,   59544076,  1567346,      105, 0xc0fd36c4
 1,   61111422,   61111422,  1567346,      104, 0x36d535e0
-0,         31,         31,        1,      152, 0x97804cc1
+0,         31,         31,        1,      152, 0x97804cc1, F=0x0
 1,   62678768,   62678768,  1567346,      105, 0xe81a35da
 1,   64246114,   64246114,  1567346,      104, 0x2b4e3699
 1,   65813460,   65813460,  1567346,      105, 0x3978392c
-0,         33,         33,        1,      156, 0xca434d31
+0,         33,         33,        1,      156, 0xca434d31, F=0x0
 1,   67380806,   67380806,  1567346,      104, 0xca903459
-0,         34,         34,        1,      196, 0x1ff16161
+0,         34,         34,        1,      196, 0x1ff16161, F=0x0
 1,   68948152,   68948152,  1567346,      105, 0xedc4374a
-0,         35,         35,        1,      176, 0x9b455230
+0,         35,         35,        1,      176, 0x9b455230, F=0x0
 1,   70515498,   70515498,  1567346,      104, 0x0b3938d2
-0,         36,         36,        1,      156, 0xbbbf4bf3
+0,         36,         36,        1,      156, 0xbbbf4bf3, F=0x0
 1,   72082844,   72082844,  1567346,      105, 0xb2653246
 1,   73650190,   73650190,  1567346,      104, 0x76333479
-0,         37,         37,        1,      220, 0x77a97152
+0,         37,         37,        1,      220, 0x77a97152, F=0x0
 1,   75217536,   75217536,  1567346,      105, 0x779138c4
-0,         38,         38,        1,      204, 0x667d5ecf
+0,         38,         38,        1,      204, 0x667d5ecf, F=0x0
 1,   76784882,   76784882,  1567346,      104, 0xfe142f55
-0,         39,         39,        1,      232, 0x3a266ccd
+0,         39,         39,        1,      232, 0x3a266ccd, F=0x0
 1,   78352228,   78352228,  1567346,      105, 0x39aa3410
 1,   79919574,   79919574,  1567346,      104, 0x520f330d
-0,         40,         40,        1,      308, 0x844a95b7
+0,         40,         40,        1,      308, 0x844a95b7, F=0x0
 1,   81486920,   81486920,  1567346,      104, 0x1aad37b0
-0,         41,         41,        1,      384, 0x71d2c695
+0,         41,         41,        1,      384, 0x71d2c695, F=0x0
 1,   83054266,   83054266,  1567346,      105, 0x164038eb
 1,   84621612,   84621612,  1567346,      104, 0x21d434bd
-0,         43,         43,        1,      520, 0x4f9d012a
+0,         43,         43,        1,      520, 0x4f9d012a, F=0x0
 1,   86188958,   86188958,  1567346,      105, 0x9c1236d4
 1,   87756304,   87756304,  1567346,      104, 0x6aa933c3
 1,   89323650,   89323650,  1567346,      105, 0xec5c371e
-0,         45,         45,        1,      648, 0xabd13b29
+0,         45,         45,        1,      648, 0xabd13b29, F=0x0
 1,   90890996,   90890996,  1567346,      104, 0xedb33251
 1,   92458342,   92458342,  1567346,      105, 0x4f953476
 1,   94025688,   94025688,  1567346,      104, 0x7da13400
-0,         47,         47,        1,      604, 0x006b328f
+0,         47,         47,        1,      604, 0x006b328f, F=0x0
 1,   95593034,   95593034,  1567346,      105, 0x57a83aaa
 1,   97160380,   97160380,  1567346,      104, 0x8b822f2f
-0,         49,         49,        1,      492, 0xa150fac1
+0,         49,         49,        1,      492, 0xa150fac1, F=0x0
 1,   98727726,   98727726,  1567346,      105, 0x3b31341a
 1,  100295072,  100295072,  1567346,      104, 0x74a4316d
 1,  101862418,  101862418,  1567346,      105, 0x05013469
-0,         51,         51,        1,      456, 0xd3e9e52c
+0,         51,         51,        1,      456, 0xd3e9e52c, F=0x0
 1,  103429764,  103429764,  1567346,      104, 0xcc8932cb
 1,  104997110,  104997110,  1567346,      105, 0xd9233422
-0,         53,         53,        1,      340, 0x7229a1b7
+0,         53,         53,        1,      340, 0x7229a1b7, F=0x0
 1,  106564456,  106564456,  1567346,      104, 0x5c603350
 1,  108131802,  108131802,  1567346,      105, 0x76e631bc
 1,  109699148,  109699148,  1567346,      104, 0x657e3b35
-0,         55,         55,        1,      280, 0x48948b60
+0,         55,         55,        1,      280, 0x48948b60, F=0x0
 1,  111266494,  111266494,  1567346,      105, 0x9d283226
 1,  112833840,  112833840,  1567346,      104, 0x574936ef
-0,         57,         57,        1,      304, 0x3ae68dcf
+0,         57,         57,        1,      304, 0x3ae68dcf, F=0x0
 1,  114401186,  114401186,  1567346,      105, 0x1b923555
 1,  115968532,  115968532,  1567346,      104, 0x2a9f3583
 1,  117535878,  117535878,  1567346,      105, 0xb8cd306f
-0,         59,         59,        1,      324, 0x005da2ab
+0,         59,         59,        1,      324, 0x005da2ab, F=0x0
 1,  119103224,  119103224,  1567346,      104, 0xa21d3475
 1,  120670570,  120670570,  1567346,      105, 0x651539ea
-0,         61,         61,        1,      348, 0x3230a873
+0,         61,         61,        1,      348, 0x3230a873, F=0x0
 1,  122237916,  122237916,  1567346,      104, 0x7b7235b8
 1,  123805262,  123805262,  1567346,      105, 0x2bbb337a
 1,  125372608,  125372608,  1567346,      104, 0x26c332eb
-0,         63,         63,        1,      336, 0x8655ad2d
+0,         63,         63,        1,      336, 0x8655ad2d, F=0x0
 1,  126939954,  126939954,  1567346,      105, 0x990838d8
 1,  128507300,  128507300,  1567346,      104, 0x4dc63ad4
 1,  130074646,  130074646,  1567346,      105, 0xfb8e3418
-0,         65,         65,        1,      380, 0x742ebc44
+0,         65,         65,        1,      380, 0x742ebc44, F=0x0
 1,  131641992,  131641992,  1567346,      104, 0x1882388e
 1,  133209338,  133209338,  1567346,      105, 0xe6b534cc
-0,         67,         67,        1,      340, 0xfc1aa74e
+0,         67,         67,        1,      340, 0xfc1aa74e, F=0x0
 1,  134776684,  134776684,  1567346,      104, 0x60fe35d0
 1,  136344030,  136344030,  1567346,      105, 0x5164354a
 1,  137911376,  137911376,  1567346,      104, 0x92ee3115
-0,         69,         69,        1,      332, 0x3cfba56c
+0,         69,         69,        1,      332, 0x3cfba56c, F=0x0
 1,  139478722,  139478722,  1567346,      105, 0x9b32327e
 1,  141046068,  141046068,  1567346,      104, 0x9b9e394a
-0,         71,         71,        1,      332, 0xc024ad4c
+0,         71,         71,        1,      332, 0xc024ad4c, F=0x0
 1,  142613414,  142613414,  1567346,      105, 0xce3c337f
 1,  144180760,  144180760,  1567346,      104, 0x7a4e33c5
 0,         73,         73,        1,     3432, 0xcdfcd1c9
 1,  146956000,  146956000,  1567346,      105, 0x0e3d34eb
 1,  148523346,  148523346,  1567346,      104, 0xd23e338e
 1,  150090692,  150090692,  1567346,      105, 0x4abf340c
-0,         75,         75,        1,      792, 0xe7df949f
+0,         75,         75,        1,      792, 0xe7df949f, F=0x0
 1,  151658038,  151658038,  1567346,      104, 0xe7522e15
 1,  153225384,  153225384,  1567346,      105, 0x995037ba
-0,         77,         77,        1,      912, 0xbc61d549
+0,         77,         77,        1,      912, 0xbc61d549, F=0x0
 1,  154792730,  154792730,  1567346,      104, 0x5ef12e9b
 1,  156360076,  156360076,  1567346,      105, 0x5c3b3166
 1,  157927422,  157927422,  1567346,      104, 0xfc38314b
-0,         79,         79,        1,      956, 0x809bdff0
+0,         79,         79,        1,      956, 0x809bdff0, F=0x0
 1,  159494768,  159494768,  1567346,      104, 0x5e3636e4
 1,  161062114,  161062114,  1567346,      105, 0xae7b3345
-0,         81,         81,        1,      652, 0x88d3484f
+0,         81,         81,        1,      652, 0x88d3484f, F=0x0
 1,  162629460,  162629460,  1567346,      104, 0x635c317a
 1,  164196806,  164196806,  1567346,      105, 0xa90c361a
 1,  165764152,  165764152,  1567346,      104, 0x8f563594
 0,         83,         83,        1,     1284, 0xecc37164
 1,  167156000,  167156000,  1567346,      105, 0x028e3985
 1,  168723346,  168723346,  1567346,      104, 0x4fd135f6
-0,         85,         85,        1,      428, 0x4794e174
+0,         85,         85,        1,      428, 0x4794e174, F=0x0
 1,  170290692,  170290692,  1567346,      105, 0xaaf539ac
 1,  171858038,  171858038,  1567346,      104, 0x668b3265
 1,  173425384,  173425384,  1567346,      105, 0x74ad3b4b
-0,         87,         87,        1,      460, 0x7253d94a
+0,         87,         87,        1,      460, 0x7253d94a, F=0x0
 1,  174992730,  174992730,  1567346,      104, 0xbde5332f
 1,  176560076,  176560076,  1567346,      105, 0xdc3631e7
 1,  178127422,  178127422,  1567346,      104, 0x3e363a1e
-0,         89,         89,        1,       24, 0x664206ba
+0,         89,         89,        1,       24, 0x664206ba, F=0x0
 1,  179694768,  179694768,  1567346,      105, 0x48b63926
diff --git a/tests/ref/fate/options-force_key_frames b/tests/ref/fate/options-force_key_frames
index 205296c..1288624 100644
--- a/tests/ref/fate/options-force_key_frames
+++ b/tests/ref/fate/options-force_key_frames
@@ -1,4 +1,4 @@
-654970e7a09ff4869596c2a47e698007 *tests/data/fate/options-force_key_frames.avi
-113320 tests/data/fate/options-force_key_frames.avi
+5423335cd809e631a2e03f97585348e0 *tests/data/fate/options-force_key_frames.avi
+113308 tests/data/fate/options-force_key_frames.avi
 8f68ad2e602ecd87a3e0c097ba99d773 *tests/data/fate/options-force_key_frames.out.framecrc
 stddev:34363.01 PSNR:  5.61 MAXDIFF:56305 bytes:  7603200/      186
diff --git a/tests/ref/fate/paf-demux b/tests/ref/fate/paf-demux
index 689f9b1..857fb54 100644
--- a/tests/ref/fate/paf-demux
+++ b/tests/ref/fate/paf-demux
@@ -2,159 +2,159 @@
 #tb 1: 1/22050
 0,          0,          0,        1,   262144, 0x7f9a3c6a
 1,          0,          0,    57330,   131072, 0x255a6ac2
-0,          1,          1,        1,   260600, 0x0329e6f4
-0,          2,          2,        1,   259724, 0x2db0ad5e
-0,          3,          3,        1,   258616, 0xe666009d
-0,          4,          4,        1,   257364, 0xba42458c
-0,          5,          5,        1,   255964, 0xf7e04c83
-0,          6,          6,        1,   254192, 0xa04b49ff
-0,          7,          7,        1,   252232, 0x65d4ab4c
-0,          8,          8,        1,   249960, 0x8f0b3854
-0,          9,          9,        1,   247396, 0x16d70776
-0,         10,         10,        1,   244452, 0x8b0648f3
-0,         11,         11,        1,   240972, 0x07e3ef41
-0,         12,         12,        1,   237288, 0x197a1964
-0,         13,         13,        1,   233344, 0xd6c51f01
-0,         14,         14,        1,   229196, 0x48581a65
-0,         15,         15,        1,   224688, 0x710e1fdb
-0,         16,         16,        1,   219248, 0xcd96719d
-0,         17,         17,        1,   212712, 0x4de31fd8
-0,         18,         18,        1,   205864, 0x21a0a106
-0,         19,         19,        1,   199148, 0xd1d77c92
-0,         20,         20,        1,   192072, 0x620627a6
-0,         21,         21,        1,   184928, 0x81548454
-0,         22,         22,        1,   178296, 0x7bb40918
-0,         23,         23,        1,   171944, 0xa7b714bb
-0,         24,         24,        1,   165584, 0xa6246dba
-0,         25,         25,        1,   159468, 0x7bc54abb
-0,         26,         26,        1,   153524, 0xd2774028
+0,          1,          1,        1,   260600, 0x0329e6f4, F=0x0
+0,          2,          2,        1,   259724, 0x2db0ad5e, F=0x0
+0,          3,          3,        1,   258616, 0xe666009d, F=0x0
+0,          4,          4,        1,   257364, 0xba42458c, F=0x0
+0,          5,          5,        1,   255964, 0xf7e04c83, F=0x0
+0,          6,          6,        1,   254192, 0xa04b49ff, F=0x0
+0,          7,          7,        1,   252232, 0x65d4ab4c, F=0x0
+0,          8,          8,        1,   249960, 0x8f0b3854, F=0x0
+0,          9,          9,        1,   247396, 0x16d70776, F=0x0
+0,         10,         10,        1,   244452, 0x8b0648f3, F=0x0
+0,         11,         11,        1,   240972, 0x07e3ef41, F=0x0
+0,         12,         12,        1,   237288, 0x197a1964, F=0x0
+0,         13,         13,        1,   233344, 0xd6c51f01, F=0x0
+0,         14,         14,        1,   229196, 0x48581a65, F=0x0
+0,         15,         15,        1,   224688, 0x710e1fdb, F=0x0
+0,         16,         16,        1,   219248, 0xcd96719d, F=0x0
+0,         17,         17,        1,   212712, 0x4de31fd8, F=0x0
+0,         18,         18,        1,   205864, 0x21a0a106, F=0x0
+0,         19,         19,        1,   199148, 0xd1d77c92, F=0x0
+0,         20,         20,        1,   192072, 0x620627a6, F=0x0
+0,         21,         21,        1,   184928, 0x81548454, F=0x0
+0,         22,         22,        1,   178296, 0x7bb40918, F=0x0
+0,         23,         23,        1,   171944, 0xa7b714bb, F=0x0
+0,         24,         24,        1,   165584, 0xa6246dba, F=0x0
+0,         25,         25,        1,   159468, 0x7bc54abb, F=0x0
+0,         26,         26,        1,   153524, 0xd2774028, F=0x0
 1,      57330,      57330,    57330,   131072, 0xcc38a5e5
-0,         27,         27,        1,   147568, 0xd94b2368
-0,         28,         28,        1,   141536, 0xb512eae6
-0,         29,         29,        1,   135368, 0x9b6ea2b3
-0,         30,         30,        1,   128296, 0x7c26d136
-0,         31,         31,        1,   120932, 0xccb8b273
-0,         32,         32,        1,   113432, 0x9f2bb997
-0,         33,         33,        1,   105724, 0x735519f6
-0,         34,         34,        1,    98428, 0xa2933dbb
-0,         35,         35,        1,    91136, 0xbe852457
-0,         36,         36,        1,    83844, 0xc471106a
-0,         37,         37,        1,    76648, 0x3f6e1c92
-0,         38,         38,        1,    69624, 0x00f86b27
-0,         39,         39,        1,    62436, 0xf360ccf0
-0,         40,         40,        1,    55268, 0x0373c2a3
-0,         41,         41,        1,    48220, 0xd5a5e0c1
-0,         42,         42,        1,    48216, 0x1da7e0ad
-0,         43,         43,        1,    48212, 0xa984e098
-0,         44,         44,        1,    48208, 0x7962e082
-0,         45,         45,        1,    48204, 0xc245e06e
-0,         46,         46,        1,    48200, 0x4f2de059
-0,         47,         47,        1,    48196, 0x2013e043
-0,         48,         48,        1,    48192, 0x34ffe02c
-0,         49,         49,        1,    48188, 0x7f22e018
-0,         50,         50,        1,    48184, 0x0d5ae003
-0,         51,         51,        1,    48180, 0xdf91dfed
-0,         52,         52,        1,    48176, 0xf5eddfd6
+0,         27,         27,        1,   147568, 0xd94b2368, F=0x0
+0,         28,         28,        1,   141536, 0xb512eae6, F=0x0
+0,         29,         29,        1,   135368, 0x9b6ea2b3, F=0x0
+0,         30,         30,        1,   128296, 0x7c26d136, F=0x0
+0,         31,         31,        1,   120932, 0xccb8b273, F=0x0
+0,         32,         32,        1,   113432, 0x9f2bb997, F=0x0
+0,         33,         33,        1,   105724, 0x735519f6, F=0x0
+0,         34,         34,        1,    98428, 0xa2933dbb, F=0x0
+0,         35,         35,        1,    91136, 0xbe852457, F=0x0
+0,         36,         36,        1,    83844, 0xc471106a, F=0x0
+0,         37,         37,        1,    76648, 0x3f6e1c92, F=0x0
+0,         38,         38,        1,    69624, 0x00f86b27, F=0x0
+0,         39,         39,        1,    62436, 0xf360ccf0, F=0x0
+0,         40,         40,        1,    55268, 0x0373c2a3, F=0x0
+0,         41,         41,        1,    48220, 0xd5a5e0c1, F=0x0
+0,         42,         42,        1,    48216, 0x1da7e0ad, F=0x0
+0,         43,         43,        1,    48212, 0xa984e098, F=0x0
+0,         44,         44,        1,    48208, 0x7962e082, F=0x0
+0,         45,         45,        1,    48204, 0xc245e06e, F=0x0
+0,         46,         46,        1,    48200, 0x4f2de059, F=0x0
+0,         47,         47,        1,    48196, 0x2013e043, F=0x0
+0,         48,         48,        1,    48192, 0x34ffe02c, F=0x0
+0,         49,         49,        1,    48188, 0x7f22e018, F=0x0
+0,         50,         50,        1,    48184, 0x0d5ae003, F=0x0
+0,         51,         51,        1,    48180, 0xdf91dfed, F=0x0
+0,         52,         52,        1,    48176, 0xf5eddfd6, F=0x0
 1,     114660,     114660,    57330,   131072, 0x4d9c2c7e
-0,         53,         53,        1,    48172, 0x415fdfc2
-0,         54,         54,        1,    48168, 0xd0d8dfad
-0,         55,         55,        1,    48164, 0xa47edf97
-0,         56,         56,        1,    48160, 0xbc4adf80
-0,         57,         57,        1,    48156, 0x08fcdf6c
-0,         58,         58,        1,    48152, 0x99c5df57
-0,         59,         59,        1,    41116, 0x8c22a4c1
-0,         60,         60,        1,    34124, 0x33c9e476
-0,         61,         61,        1,    27272, 0x8069fb08
-0,         62,         62,        1,    20636, 0xa413e37e
-0,         63,         63,        1,    14072, 0x428a2075
-0,         64,         64,        1,     7712, 0x7c6b914f
-0,         65,         65,        1,   262144, 0x687484cb
-0,         66,         66,        1,   256292, 0x0dec8b5a
-0,         67,         67,        1,   250612, 0xd127f411
-0,         68,         68,        1,   245404, 0x4e760ddf
-0,         69,         69,        1,   241956, 0x0412f83d
-0,         70,         70,        1,   241184, 0x0de227e2
-0,         71,         71,        1,   241180, 0xebe9eafb
-0,         72,         72,        1,   241176, 0xf0c8eae5
-0,         73,         73,        1,   241172, 0x47bbeace
-0,         74,         74,        1,   241168, 0xfb8aeab9
-0,         75,         75,        1,   241164, 0x0180eaa3
-0,         76,         76,        1,   241160, 0x5978ea8c
-0,         77,         77,        1,   241156, 0xbc86ea78
-0,         78,         78,        1,   241152, 0x71b4ea63
+0,         53,         53,        1,    48172, 0x415fdfc2, F=0x0
+0,         54,         54,        1,    48168, 0xd0d8dfad, F=0x0
+0,         55,         55,        1,    48164, 0xa47edf97, F=0x0
+0,         56,         56,        1,    48160, 0xbc4adf80, F=0x0
+0,         57,         57,        1,    48156, 0x08fcdf6c, F=0x0
+0,         58,         58,        1,    48152, 0x99c5df57, F=0x0
+0,         59,         59,        1,    41116, 0x8c22a4c1, F=0x0
+0,         60,         60,        1,    34124, 0x33c9e476, F=0x0
+0,         61,         61,        1,    27272, 0x8069fb08, F=0x0
+0,         62,         62,        1,    20636, 0xa413e37e, F=0x0
+0,         63,         63,        1,    14072, 0x428a2075, F=0x0
+0,         64,         64,        1,     7712, 0x7c6b914f, F=0x0
+0,         65,         65,        1,   262144, 0x687484cb, F=0x0
+0,         66,         66,        1,   256292, 0x0dec8b5a, F=0x0
+0,         67,         67,        1,   250612, 0xd127f411, F=0x0
+0,         68,         68,        1,   245404, 0x4e760ddf, F=0x0
+0,         69,         69,        1,   241956, 0x0412f83d, F=0x0
+0,         70,         70,        1,   241184, 0x0de227e2, F=0x0
+0,         71,         71,        1,   241180, 0xebe9eafb, F=0x0
+0,         72,         72,        1,   241176, 0xf0c8eae5, F=0x0
+0,         73,         73,        1,   241172, 0x47bbeace, F=0x0
+0,         74,         74,        1,   241168, 0xfb8aeab9, F=0x0
+0,         75,         75,        1,   241164, 0x0180eaa3, F=0x0
+0,         76,         76,        1,   241160, 0x5978ea8c, F=0x0
+0,         77,         77,        1,   241156, 0xbc86ea78, F=0x0
+0,         78,         78,        1,   241152, 0x71b4ea63, F=0x0
 1,     171990,     171990,    57330,   131072, 0x1b512fb8
-0,         79,         79,        1,   241148, 0x78fbea4d
+0,         79,         79,        1,   241148, 0x78fbea4d, F=0x0
 0,         80,         80,        1,   241144, 0xd263ea36
-0,         81,         81,        1,   237912, 0xcb5839a6
-0,         82,         82,        1,   229296, 0x350f07b6
-0,         83,         83,        1,   214256, 0x3c954096
-0,         84,         84,        1,   198068, 0x1470ae1f
-0,         85,         85,        1,   180664, 0xa80de8b6
-0,         86,         86,        1,   164672, 0x11ecf816
-0,         87,         87,        1,   148996, 0x6346aa49
-0,         88,         88,        1,   134804, 0x8fe4699a
-0,         89,         89,        1,   124488, 0x63b82fa0
-0,         90,         90,        1,   116892, 0xac785c29
-0,         91,         91,        1,   109528, 0xc24da959
-0,         92,         92,        1,   102688, 0xba25eb56
-0,         93,         93,        1,    95192, 0x999820b3
-0,         94,         94,        1,    89980, 0xa81aee1a
-0,         95,         95,        1,    84696, 0xb274dad5
-0,         96,         96,        1,    79152, 0xd7936f6e
-0,         97,         97,        1,    74232, 0x1abdf78a
-0,         98,         98,        1,    69112, 0x212918e8
-0,         99,         99,        1,    63484, 0x45e36b2f
-0,        100,        100,        1,    58616, 0xef171a5a
-0,        101,        101,        1,    53396, 0xd16be9a0
-0,        102,        102,        1,    47388, 0xc602914b
-0,        103,        103,        1,    42276, 0x6b86b9dd
-0,        104,        104,        1,    36932, 0xea0d85cb
+0,         81,         81,        1,   237912, 0xcb5839a6, F=0x0
+0,         82,         82,        1,   229296, 0x350f07b6, F=0x0
+0,         83,         83,        1,   214256, 0x3c954096, F=0x0
+0,         84,         84,        1,   198068, 0x1470ae1f, F=0x0
+0,         85,         85,        1,   180664, 0xa80de8b6, F=0x0
+0,         86,         86,        1,   164672, 0x11ecf816, F=0x0
+0,         87,         87,        1,   148996, 0x6346aa49, F=0x0
+0,         88,         88,        1,   134804, 0x8fe4699a, F=0x0
+0,         89,         89,        1,   124488, 0x63b82fa0, F=0x0
+0,         90,         90,        1,   116892, 0xac785c29, F=0x0
+0,         91,         91,        1,   109528, 0xc24da959, F=0x0
+0,         92,         92,        1,   102688, 0xba25eb56, F=0x0
+0,         93,         93,        1,    95192, 0x999820b3, F=0x0
+0,         94,         94,        1,    89980, 0xa81aee1a, F=0x0
+0,         95,         95,        1,    84696, 0xb274dad5, F=0x0
+0,         96,         96,        1,    79152, 0xd7936f6e, F=0x0
+0,         97,         97,        1,    74232, 0x1abdf78a, F=0x0
+0,         98,         98,        1,    69112, 0x212918e8, F=0x0
+0,         99,         99,        1,    63484, 0x45e36b2f, F=0x0
+0,        100,        100,        1,    58616, 0xef171a5a, F=0x0
+0,        101,        101,        1,    53396, 0xd16be9a0, F=0x0
+0,        102,        102,        1,    47388, 0xc602914b, F=0x0
+0,        103,        103,        1,    42276, 0x6b86b9dd, F=0x0
+0,        104,        104,        1,    36932, 0xea0d85cb, F=0x0
 1,     229320,     229320,    57330,   131072, 0x4e478505
-0,        105,        105,        1,    30408, 0xc7df6cba
-0,        106,        106,        1,    24468, 0x80007205
-0,        107,        107,        1,    18572, 0xb4aa84d2
-0,        108,        108,        1,    12632, 0x12c2efb8
-0,        109,        109,        1,     6604, 0x75002817
-0,        110,        110,        1,   262144, 0xf9544f5b
-0,        111,        111,        1,   255448, 0x9242877e
-0,        112,        112,        1,   248532, 0xef495999
-0,        113,        113,        1,   238032, 0xac29500b
-0,        114,        114,        1,   225424, 0x73035f24
-0,        115,        115,        1,   215860, 0xed94de14
-0,        116,        116,        1,   205996, 0x4d417b16
-0,        117,        117,        1,   191904, 0xc195d49f
-0,        118,        118,        1,   182596, 0x32a14954
-0,        119,        119,        1,   174988, 0xdc83fa02
-0,        120,        120,        1,   168008, 0x5e1d7302
-0,        121,        121,        1,   161032, 0xf503efb4
-0,        122,        122,        1,   154044, 0x1df06a7c
-0,        123,        123,        1,   147056, 0x4c22ec13
-0,        124,        124,        1,   140060, 0xede97385
-0,        125,        125,        1,   133064, 0x50eefee6
-0,        126,        126,        1,   126060, 0xc6478fb8
-0,        127,        127,        1,   119056, 0xf45a2080
-0,        128,        128,        1,   112044, 0x1d49b4ae
-0,        129,        129,        1,   105028, 0xd35649dd
-0,        130,        130,        1,    98012, 0x03ede949
+0,        105,        105,        1,    30408, 0xc7df6cba, F=0x0
+0,        106,        106,        1,    24468, 0x80007205, F=0x0
+0,        107,        107,        1,    18572, 0xb4aa84d2, F=0x0
+0,        108,        108,        1,    12632, 0x12c2efb8, F=0x0
+0,        109,        109,        1,     6604, 0x75002817, F=0x0
+0,        110,        110,        1,   262144, 0xf9544f5b, F=0x0
+0,        111,        111,        1,   255448, 0x9242877e, F=0x0
+0,        112,        112,        1,   248532, 0xef495999, F=0x0
+0,        113,        113,        1,   238032, 0xac29500b, F=0x0
+0,        114,        114,        1,   225424, 0x73035f24, F=0x0
+0,        115,        115,        1,   215860, 0xed94de14, F=0x0
+0,        116,        116,        1,   205996, 0x4d417b16, F=0x0
+0,        117,        117,        1,   191904, 0xc195d49f, F=0x0
+0,        118,        118,        1,   182596, 0x32a14954, F=0x0
+0,        119,        119,        1,   174988, 0xdc83fa02, F=0x0
+0,        120,        120,        1,   168008, 0x5e1d7302, F=0x0
+0,        121,        121,        1,   161032, 0xf503efb4, F=0x0
+0,        122,        122,        1,   154044, 0x1df06a7c, F=0x0
+0,        123,        123,        1,   147056, 0x4c22ec13, F=0x0
+0,        124,        124,        1,   140060, 0xede97385, F=0x0
+0,        125,        125,        1,   133064, 0x50eefee6, F=0x0
+0,        126,        126,        1,   126060, 0xc6478fb8, F=0x0
+0,        127,        127,        1,   119056, 0xf45a2080, F=0x0
+0,        128,        128,        1,   112044, 0x1d49b4ae, F=0x0
+0,        129,        129,        1,   105028, 0xd35649dd, F=0x0
+0,        130,        130,        1,    98012, 0x03ede949, F=0x0
 1,     286650,     286650,    57330,   131072, 0xb29e283e
-0,        131,        131,        1,    91000, 0x57128fb0
-0,        132,        132,        1,    84000, 0xf7ff39c0
-0,        133,        133,        1,    77004, 0xda18e580
-0,        134,        134,        1,    70004, 0x8eff8af4
-0,        135,        135,        1,    62992, 0x665831fd
-0,        136,        136,        1,    55976, 0x130ada75
-0,        137,        137,        1,    48956, 0x4cf47b2f
-0,        138,        138,        1,    41936, 0x7a8e2006
-0,        139,        139,        1,    34920, 0x9527ca2b
-0,        140,        140,        1,    27912, 0x4c8078df
-0,        141,        141,        1,    20884, 0x1e152e1f
-0,        142,        142,        1,    13848, 0xd358d51b
-0,        143,        143,        1,   262144, 0x38f14810
-0,        144,        144,        1,   255104, 0x579bf26b
-0,        145,        145,        1,   255100, 0x6488a2d4
-0,        146,        146,        1,   248096, 0xbe966730
-0,        147,        147,        1,   241144, 0xd8e3abf6
-0,        148,        148,        1,   234268, 0xde2bb38e
-0,        149,        149,        1,   227440, 0xb78f1aed
-0,        150,        150,        1,   220692, 0x86026588
-0,        151,        151,        1,   214000, 0x0fdbc796
+0,        131,        131,        1,    91000, 0x57128fb0, F=0x0
+0,        132,        132,        1,    84000, 0xf7ff39c0, F=0x0
+0,        133,        133,        1,    77004, 0xda18e580, F=0x0
+0,        134,        134,        1,    70004, 0x8eff8af4, F=0x0
+0,        135,        135,        1,    62992, 0x665831fd, F=0x0
+0,        136,        136,        1,    55976, 0x130ada75, F=0x0
+0,        137,        137,        1,    48956, 0x4cf47b2f, F=0x0
+0,        138,        138,        1,    41936, 0x7a8e2006, F=0x0
+0,        139,        139,        1,    34920, 0x9527ca2b, F=0x0
+0,        140,        140,        1,    27912, 0x4c8078df, F=0x0
+0,        141,        141,        1,    20884, 0x1e152e1f, F=0x0
+0,        142,        142,        1,    13848, 0xd358d51b, F=0x0
+0,        143,        143,        1,   262144, 0x38f14810, F=0x0
+0,        144,        144,        1,   255104, 0x579bf26b, F=0x0
+0,        145,        145,        1,   255100, 0x6488a2d4, F=0x0
+0,        146,        146,        1,   248096, 0xbe966730, F=0x0
+0,        147,        147,        1,   241144, 0xd8e3abf6, F=0x0
+0,        148,        148,        1,   234268, 0xde2bb38e, F=0x0
+0,        149,        149,        1,   227440, 0xb78f1aed, F=0x0
+0,        150,        150,        1,   220692, 0x86026588, F=0x0
+0,        151,        151,        1,   214000, 0x0fdbc796, F=0x0
diff --git a/tests/ref/fate/parseutils b/tests/ref/fate/parseutils
index 5bf1cae..36756a8 100644
--- a/tests/ref/fate/parseutils
+++ b/tests/ref/fate/parseutils
@@ -1,29 +1,29 @@
 Testing av_parse_video_rate()
-'-inf' -> -1/0 error
-'inf' -> 1/0 error
-'nan' -> 0/0 error
-'123/0' -> 1/0 error
-'-123 / 0' -> -1/0 error
-'' -> 0/0 error
-'/' -> 0/0 error
-' 123  /  321' -> 41/107
-'foo/foo' -> 0/0 error
-'foo/1' -> 0/0 error
-'1/foo' -> 1/0 error
-'0/0' -> 0/0 error
-'/0' -> 0/0 error
-'1/' -> 1/0 error
-'1' -> 1/1
-'0' -> 0/1 error
-'-123/123' -> -1/1 error
-'-foo' -> 0/0 error
-'123.23' -> 12323/100
-'.23' -> 23/100
-'-.23' -> -23/100 error
-'-0.234' -> -117/500 error
-'-0.0000001' -> 0/1 error
-'  21332.2324   ' -> 917286/43
-' -21332.2324   ' -> -917286/43 error
+'-inf' -> -1/0 ERROR
+'inf' -> 1/0 ERROR
+'nan' -> 0/0 ERROR
+'123/0' -> 1/0 ERROR
+'-123 / 0' -> -1/0 ERROR
+'' -> 0/0 ERROR
+'/' -> 0/0 ERROR
+' 123  /  321' -> 41/107 OK
+'foo/foo' -> 0/0 ERROR
+'foo/1' -> 0/0 ERROR
+'1/foo' -> 1/0 ERROR
+'0/0' -> 0/0 ERROR
+'/0' -> 0/0 ERROR
+'1/' -> 1/0 ERROR
+'1' -> 1/1 OK
+'0' -> 0/1 ERROR
+'-123/123' -> -1/1 ERROR
+'-foo' -> 0/0 ERROR
+'123.23' -> 12323/100 OK
+'.23' -> 23/100 OK
+'-.23' -> -23/100 ERROR
+'-0.234' -> -117/500 ERROR
+'-0.0000001' -> 0/1 ERROR
+'  21332.2324   ' -> 917286/43 OK
+' -21332.2324   ' -> -917286/43 ERROR
 
 Testing av_parse_color()
 bikeshed -> R(80) G(64) B(140) A(59)
diff --git a/tests/ref/fate/pmp-demux b/tests/ref/fate/pmp-demux
new file mode 100644
index 0000000..b481db7
--- /dev/null
+++ b/tests/ref/fate/pmp-demux
@@ -0,0 +1,106 @@
+#tb 0: 1/44100
+0,          0,          0,     1152,      417, 0xcb873fba
+0,       1152,       1152,     1152,      104, 0x6d521c5a
+0,       2304,       2304,     1152,      104, 0xb3af1d64
+0,       3456,       3456,     1152,      104, 0xc0f71d86
+0,       4608,       4608,     1152,      104, 0xce3f1da8
+0,       5760,       5760,     1152,      104, 0xdb871dca
+0,       6912,       6912,     1152,      104, 0xe8cf1dec
+0,       8064,       8064,     1152,      104, 0xf6171e0e
+0,       9216,       9216,     1152,      104, 0x036e1e30
+0,      10368,      10368,     1152,      104, 0x3b921ec1
+0,      11520,      11520,     1152,      104, 0x3b921ec1
+0,      12672,      12672,     1152,      104, 0x3b921ec1
+0,      13824,      13824,     1152,      104, 0x3b921ec1
+0,      14976,      14976,     1152,      104, 0x3b921ec1
+0,      16128,      16128,     1152,      104, 0x3b921ec1
+0,      17280,      17280,     1152,      104, 0x3b921ec1
+0,      18432,      18432,     1152,      104, 0x3b921ec1
+0,      19584,      19584,     1152,      104, 0x3b921ec1
+0,      20736,      20736,     1152,      104, 0x3b921ec1
+0,      21888,      21888,     1152,      104, 0x3b921ec1
+0,      23040,      23040,     1152,      104, 0x3b921ec1
+0,      24192,      24192,     1152,      104, 0x3b921ec1
+0,      25344,      25344,     1152,      104, 0x3b921ec1
+0,      26496,      26496,     1152,      104, 0x3b921ec1
+0,      27648,      27648,     1152,      104, 0x3b921ec1
+0,      28800,      28800,     1152,      104, 0x3b921ec1
+0,      29952,      29952,     1152,      104, 0x3b921ec1
+0,      31104,      31104,     1152,      104, 0x3b921ec1
+0,      32256,      32256,     1152,      104, 0x3b921ec1
+0,      33408,      33408,     1152,      104, 0x3b921ec1
+0,      34560,      34560,     1152,      104, 0x3b921ec1
+0,      35712,      35712,     1152,      104, 0x3b921ec1
+0,      36864,      36864,     1152,      104, 0x3b921ec1
+0,      38016,      38016,     1152,      104, 0x3b921ec1
+0,      39168,      39168,     1152,      104, 0x3b921ec1
+0,      40320,      40320,     1152,      104, 0x3b921ec1
+0,      41472,      41472,     1152,      104, 0x3b921ec1
+0,      42624,      42624,     1152,      104, 0x3b921ec1
+0,      43776,      43776,     1152,      104, 0x3b921ec1
+0,      44928,      44928,     1152,      104, 0x3b921ec1
+0,      46080,      46080,     1152,      104, 0x3b921ec1
+0,      47232,      47232,     1152,      104, 0x3b921ec1
+0,      48384,      48384,     1152,      104, 0x3b921ec1
+0,      49536,      49536,     1152,      104, 0x3b921ec1
+0,      50688,      50688,     1152,      104, 0x3b921ec1
+0,      51840,      51840,     1152,      104, 0x3b921ec1
+0,      52992,      52992,     1152,      104, 0x3b921ec1
+0,      54144,      54144,     1152,      104, 0x3b921ec1
+0,      55296,      55296,     1152,      104, 0x3b921ec1
+0,      56448,      56448,     1152,      104, 0x3b921ec1
+0,      57600,      57600,     1152,      104, 0x3b921ec1
+0,      58752,      58752,     1152,      104, 0x3b921ec1
+0,      59904,      59904,     1152,      104, 0x3b921ec1
+0,      61056,      61056,     1152,      104, 0x3b921ec1
+0,      62208,      62208,     1152,      104, 0x3b921ec1
+0,      63360,      63360,     1152,      104, 0x3b921ec1
+0,      64512,      64512,     1152,      104, 0x3b921ec1
+0,      65664,      65664,     1152,      104, 0x3b921ec1
+0,      66816,      66816,     1152,      104, 0x3b921ec1
+0,      67968,      67968,     1152,      104, 0x3b921ec1
+0,      69120,      69120,     1152,      104, 0x3b921ec1
+0,      70272,      70272,     1152,      104, 0x3b921ec1
+0,      71424,      71424,     1152,      104, 0x3b921ec1
+0,      72576,      72576,     1152,      104, 0x3b921ec1
+0,      73728,      73728,     1152,      104, 0x3b921ec1
+0,      74880,      74880,     1152,      104, 0x3b921ec1
+0,      76032,      76032,     1152,      104, 0x3b921ec1
+0,      77184,      77184,     1152,      104, 0x3b921ec1
+0,      78336,      78336,     1152,      104, 0x3b921ec1
+0,      79488,      79488,     1152,      104, 0x3b921ec1
+0,      80640,      80640,     1152,      104, 0x3b921ec1
+0,      81792,      81792,     1152,      104, 0x3b921ec1
+0,      82944,      82944,     1152,      104, 0x3b921ec1
+0,      84096,      84096,     1152,      104, 0x3b921ec1
+0,      85248,      85248,     1152,      104, 0x3b921ec1
+0,      86400,      86400,     1152,      104, 0x3b921ec1
+0,      87552,      87552,     1152,      104, 0xf0211aa6
+0,      88704,      88704,     1152,      104, 0xd34224a5
+0,      89856,      89856,     1152,      104, 0x7b78282c
+0,      91008,      91008,     1152,      104, 0x06e32789
+0,      92160,      92160,     1152,      104, 0x1c502696
+0,      93312,      93312,     1152,      104, 0xd7392a5e
+0,      94464,      94464,     1152,      104, 0xbc1b288e
+0,      95616,      95616,     1152,      104, 0xbbd8261f
+0,      96768,      96768,     1152,      104, 0xebbb2f1c
+0,      97920,      97920,     1152,      104, 0xf55b31cc
+0,      99072,      99072,     1152,      104, 0xbdb930e0
+0,     100224,     100224,     1152,      104, 0x36b72db9
+0,     101376,     101376,     1152,      156, 0xbef24bc7
+0,     102528,     102528,     1152,      261, 0xefec7b06
+0,     103680,     103680,     1152,      208, 0xadcd5f92
+0,     104832,     104832,     1152,      261, 0x7ea9792e
+0,     105984,     105984,     1152,      182, 0xf7ad5524
+0,     107136,     107136,     1152,      208, 0x8f325a0c
+0,     108288,     108288,     1152,      208, 0xe6795cde
+0,     109440,     109440,     1152,      208, 0xd4bc5e11
+0,     110592,     110592,     1152,      208, 0x6762553b
+0,     111744,     111744,     1152,      156, 0x47cc39cc
+0,     112896,     112896,     1152,      130, 0xcdcd2e7b
+0,     114048,     114048,     1152,      261, 0x3864753a
+0,     115200,     115200,     1152,      156, 0xc5d24270
+0,     116352,     116352,     1152,      156, 0x3b664195
+0,     117504,     117504,     1152,      130, 0xa928320e
+0,     118656,     118656,     1152,      156, 0x58e03f10
+0,     119808,     119808,     1152,      261, 0xf0707a4c
diff --git a/tests/ref/fate/redcode-demux b/tests/ref/fate/redcode-demux
index 34a2924..a7e2838 100644
--- a/tests/ref/fate/redcode-demux
+++ b/tests/ref/fate/redcode-demux
@@ -4,4 +4,4 @@
 1,          0,          0,    18140,    14816, 0xd185e8c7
 0,      10010,      10010,    10010,  1626092, 0x070bd882
 1,      18140,      18140,    40920,    32736, 0x791b737a
-0,      20020,      20020,    10010,   893932, 0x8c7cd0a6
+0,      20020,      20020,    10010,   893932, 0x8c7cd0a6, F=0x3
diff --git a/tests/ref/fate/url b/tests/ref/fate/url
new file mode 100644
index 0000000..1a6051e
--- /dev/null
+++ b/tests/ref/fate/url
@@ -0,0 +1,13 @@
+baz
+/foo/baz
+/baz
+/baz
+http://server/foo/baz
+http://server/foo/baz
+http://server/baz
+http://server/baz
+http://server/baz
+https://other/url
+http://server/baz
+http://server/foo/bar?someparam
+http://other/url
diff --git a/tests/ref/fate/v410enc b/tests/ref/fate/v410enc
index e5332de..ab219bb 100644
--- a/tests/ref/fate/v410enc
+++ b/tests/ref/fate/v410enc
@@ -1 +1 @@
-979c9a9a09e8eaaf6467b8c22c0ac8bb
+e5c0b1f17d2a64a416dcf9bf7a38d9d9
diff --git a/tests/ref/fate/vsynth1-amv b/tests/ref/fate/vsynth1-amv
deleted file mode 100644
index 9abfb05..0000000
--- a/tests/ref/fate/vsynth1-amv
+++ /dev/null
@@ -1,4 +0,0 @@
-00947dc33a092a3080d78d5bf69ed4e3 *tests/data/fate/vsynth1-amv.avi
-1365508 tests/data/fate/vsynth1-amv.avi
-e38681b9527b6d2531942f8a176a0265 *tests/data/fate/vsynth1-amv.out.rawvideo
-stddev:   10.07 PSNR: 28.06 MAXDIFF:   98 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-asv1 b/tests/ref/fate/vsynth1-asv1
deleted file mode 100644
index 768729e..0000000
--- a/tests/ref/fate/vsynth1-asv1
+++ /dev/null
@@ -1,4 +0,0 @@
-b4ce4698764ef2328346badb7227ecbe *tests/data/fate/vsynth1-asv1.avi
-1489656 tests/data/fate/vsynth1-asv1.avi
-2dfc5dfc2c1cbbc2543257cd3d2df6af *tests/data/fate/vsynth1-asv1.out.rawvideo
-stddev:   20.00 PSNR: 22.11 MAXDIFF:  158 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-asv2 b/tests/ref/fate/vsynth1-asv2
deleted file mode 100644
index 38c6cef..0000000
--- a/tests/ref/fate/vsynth1-asv2
+++ /dev/null
@@ -1,4 +0,0 @@
-dfba6eaf58e515e324c2b370bfcd9158 *tests/data/fate/vsynth1-asv2.avi
-1456056 tests/data/fate/vsynth1-asv2.avi
-d451be09793cd0f35b6d91fc36e2571a *tests/data/fate/vsynth1-asv2.out.rawvideo
-stddev:   18.82 PSNR: 22.63 MAXDIFF:  131 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-cljr b/tests/ref/fate/vsynth1-cljr
deleted file mode 100644
index 77d73b2..0000000
--- a/tests/ref/fate/vsynth1-cljr
+++ /dev/null
@@ -1,4 +0,0 @@
-041982e4fa83428c621a127647d47b3f *tests/data/fate/vsynth1-cljr.avi
-5075660 tests/data/fate/vsynth1-cljr.avi
-7bd979b8b397f7bac22a0102c7889452 *tests/data/fate/vsynth1-cljr.out.rawvideo
-stddev:    6.74 PSNR: 31.55 MAXDIFF:   84 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-ffv1 b/tests/ref/fate/vsynth1-ffv1
deleted file mode 100644
index ab1a582..0000000
--- a/tests/ref/fate/vsynth1-ffv1
+++ /dev/null
@@ -1,4 +0,0 @@
-67ddc7edde5cca49290245d881787890 *tests/data/fate/vsynth1-ffv1.avi
-2655376 tests/data/fate/vsynth1-ffv1.avi
-c5ccac874dbf808e9088bc3107860042 *tests/data/fate/vsynth1-ffv1.out.rawvideo
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-ffvhuff b/tests/ref/fate/vsynth1-ffvhuff
deleted file mode 100644
index fc44dff..0000000
--- a/tests/ref/fate/vsynth1-ffvhuff
+++ /dev/null
@@ -1,4 +0,0 @@
-0632ffae6f1e06dd299bf41a845b9099 *tests/data/fate/vsynth1-ffvhuff.avi
-5987208 tests/data/fate/vsynth1-ffvhuff.avi
-c5ccac874dbf808e9088bc3107860042 *tests/data/fate/vsynth1-ffvhuff.out.rawvideo
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-h261 b/tests/ref/fate/vsynth1-h261
deleted file mode 100644
index eb9575d..0000000
--- a/tests/ref/fate/vsynth1-h261
+++ /dev/null
@@ -1,4 +0,0 @@
-fe87fa742c7f04449c5b1dd55bfe70e6 *tests/data/fate/vsynth1-h261.avi
-707558 tests/data/fate/vsynth1-h261.avi
-85fde92037c2ccecc02e2d6c21a169b0 *tests/data/fate/vsynth1-h261.out.rawvideo
-stddev:    9.11 PSNR: 28.93 MAXDIFF:  113 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-h263 b/tests/ref/fate/vsynth1-h263
deleted file mode 100644
index 9f31fc6..0000000
--- a/tests/ref/fate/vsynth1-h263
+++ /dev/null
@@ -1,4 +0,0 @@
-0037e453d71210d9d6a2d625c490705c *tests/data/fate/vsynth1-h263.avi
-659686 tests/data/fate/vsynth1-h263.avi
-aef88517578fa7f53fe5159c4b6754ef *tests/data/fate/vsynth1-h263.out.rawvideo
-stddev:    8.03 PSNR: 30.03 MAXDIFF:  103 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-h263p b/tests/ref/fate/vsynth1-h263p
deleted file mode 100644
index a4cf7c8..0000000
--- a/tests/ref/fate/vsynth1-h263p
+++ /dev/null
@@ -1,4 +0,0 @@
-7474e28919ea4a6951e1534b951ddd28 *tests/data/fate/vsynth1-h263p.avi
-2328374 tests/data/fate/vsynth1-h263p.avi
-911330cb57c99c440234392be1588081 *tests/data/fate/vsynth1-h263p.out.rawvideo
-stddev:    2.06 PSNR: 41.83 MAXDIFF:   20 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-huffyuv b/tests/ref/fate/vsynth1-huffyuv
deleted file mode 100644
index 3d55c6b..0000000
--- a/tests/ref/fate/vsynth1-huffyuv
+++ /dev/null
@@ -1,4 +0,0 @@
-f5f2e109af0612694ff3cd6464063e82 *tests/data/fate/vsynth1-huffyuv.avi
-7933800 tests/data/fate/vsynth1-huffyuv.avi
-c5ccac874dbf808e9088bc3107860042 *tests/data/fate/vsynth1-huffyuv.out.rawvideo
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-j2k b/tests/ref/fate/vsynth1-j2k
deleted file mode 100644
index e434db8..0000000
--- a/tests/ref/fate/vsynth1-j2k
+++ /dev/null
@@ -1,4 +0,0 @@
-8da8ef50cccb9996f4bebbc585c4edb4 *tests/data/fate/vsynth1-j2k.avi
-2306914 tests/data/fate/vsynth1-j2k.avi
-ee9b245b3b07eed90bc6f2147bbd916c *tests/data/fate/vsynth1-j2k.out.rawvideo
-stddev:    5.47 PSNR: 33.37 MAXDIFF:   64 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-jpegls b/tests/ref/fate/vsynth1-jpegls
deleted file mode 100644
index de4f109..0000000
--- a/tests/ref/fate/vsynth1-jpegls
+++ /dev/null
@@ -1,4 +0,0 @@
-870dceeb6d3931dd68b34f0c33be5d26 *tests/data/fate/vsynth1-jpegls.avi
-9089812 tests/data/fate/vsynth1-jpegls.avi
-791e1fb999deb2e4156e2286d48c4ed1 *tests/data/fate/vsynth1-jpegls.out.rawvideo
-stddev:    2.84 PSNR: 39.04 MAXDIFF:   49 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-ljpeg b/tests/ref/fate/vsynth1-ljpeg
deleted file mode 100644
index 4f95667..0000000
--- a/tests/ref/fate/vsynth1-ljpeg
+++ /dev/null
@@ -1,4 +0,0 @@
-9092f306f165b98ab0bb4f576f198ad5 *tests/data/fate/vsynth1-ljpeg.avi
-6312936 tests/data/fate/vsynth1-ljpeg.avi
-c5ccac874dbf808e9088bc3107860042 *tests/data/fate/vsynth1-ljpeg.out.rawvideo
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-mjpeg b/tests/ref/fate/vsynth1-mjpeg
deleted file mode 100644
index 6fd5c5b..0000000
--- a/tests/ref/fate/vsynth1-mjpeg
+++ /dev/null
@@ -1,4 +0,0 @@
-add304152c969eeb073157ccc9cc7799 *tests/data/fate/vsynth1-mjpeg.avi
-1515914 tests/data/fate/vsynth1-mjpeg.avi
-9a3b8169c251d19044f7087a95458c55 *tests/data/fate/vsynth1-mjpeg.out.rawvideo
-stddev:    7.87 PSNR: 30.21 MAXDIFF:   63 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-mpeg4-adap b/tests/ref/fate/vsynth1-mpeg4-adap
deleted file mode 100644
index 1764e25..0000000
--- a/tests/ref/fate/vsynth1-mpeg4-adap
+++ /dev/null
@@ -1,4 +0,0 @@
-520ee9e41fc09c5ad0d4b9852a2ea1d2 *tests/data/fate/vsynth1-mpeg4-adap.avi
-403444 tests/data/fate/vsynth1-mpeg4-adap.avi
-fad0b9dc08fe4a95b297af1a7411c1e9 *tests/data/fate/vsynth1-mpeg4-adap.out.rawvideo
-stddev:   14.05 PSNR: 25.17 MAXDIFF:  184 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-mpeg4-adv b/tests/ref/fate/vsynth1-mpeg4-adv
deleted file mode 100644
index c328a42..0000000
--- a/tests/ref/fate/vsynth1-mpeg4-adv
+++ /dev/null
@@ -1,4 +0,0 @@
-5b2b17eac3210b85d847e7088469b53c *tests/data/fate/vsynth1-mpeg4-adv.avi
-589716 tests/data/fate/vsynth1-mpeg4-adv.avi
-b651bd94456005a1990fb64c28306262 *tests/data/fate/vsynth1-mpeg4-adv.out.rawvideo
-stddev:    6.98 PSNR: 31.25 MAXDIFF:   84 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-mpeg4-error b/tests/ref/fate/vsynth1-mpeg4-error
deleted file mode 100644
index ab3a266..0000000
--- a/tests/ref/fate/vsynth1-mpeg4-error
+++ /dev/null
@@ -1,4 +0,0 @@
-ed45da2282cbc0a3e4d4d45bbcab71d8 *tests/data/fate/vsynth1-mpeg4-error.avi
-752358 tests/data/fate/vsynth1-mpeg4-error.avi
-5853c8c789f260ae4dcbf37a17d04b66 *tests/data/fate/vsynth1-mpeg4-error.out.rawvideo
-stddev:   17.33 PSNR: 23.35 MAXDIFF:  229 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-mpeg4-nr b/tests/ref/fate/vsynth1-mpeg4-nr
deleted file mode 100644
index 4814b1a..0000000
--- a/tests/ref/fate/vsynth1-mpeg4-nr
+++ /dev/null
@@ -1,4 +0,0 @@
-9f990e290b5978f0243ea5a2141feb6c *tests/data/fate/vsynth1-mpeg4-nr.avi
-675464 tests/data/fate/vsynth1-mpeg4-nr.avi
-5fee518cde41e5567f800fbe14210fb8 *tests/data/fate/vsynth1-mpeg4-nr.out.rawvideo
-stddev:    6.99 PSNR: 31.24 MAXDIFF:   86 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-mpeg4-qpel b/tests/ref/fate/vsynth1-mpeg4-qpel
deleted file mode 100644
index 00c0022..0000000
--- a/tests/ref/fate/vsynth1-mpeg4-qpel
+++ /dev/null
@@ -1,4 +0,0 @@
-8636a8011e315dafe7fa66e493a41174 *tests/data/fate/vsynth1-mpeg4-qpel.avi
-858692 tests/data/fate/vsynth1-mpeg4-qpel.avi
-5089090df7169eb482532df5471d7f5f *tests/data/fate/vsynth1-mpeg4-qpel.out.rawvideo
-stddev:    5.63 PSNR: 33.11 MAXDIFF:   70 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-mpeg4-qprd b/tests/ref/fate/vsynth1-mpeg4-qprd
deleted file mode 100644
index 8a5f84c..0000000
--- a/tests/ref/fate/vsynth1-mpeg4-qprd
+++ /dev/null
@@ -1,4 +0,0 @@
-d4746d1d22f2d464b1cdd6cc2d63ddcf *tests/data/fate/vsynth1-mpeg4-qprd.avi
-710684 tests/data/fate/vsynth1-mpeg4-qprd.avi
-693231ac7e6fbf8758415f9f2509408d *tests/data/fate/vsynth1-mpeg4-qprd.out.rawvideo
-stddev:    9.79 PSNR: 28.31 MAXDIFF:  176 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-mpeg4-rc b/tests/ref/fate/vsynth1-mpeg4-rc
deleted file mode 100644
index 74bde1c..0000000
--- a/tests/ref/fate/vsynth1-mpeg4-rc
+++ /dev/null
@@ -1,4 +0,0 @@
-7d147478239dbc75f1ea3f7e27b07c95 *tests/data/fate/vsynth1-mpeg4-rc.avi
-830506 tests/data/fate/vsynth1-mpeg4-rc.avi
-9dcd9d022ae14fe1e4a53aa4865464c6 *tests/data/fate/vsynth1-mpeg4-rc.out.rawvideo
-stddev:   10.24 PSNR: 27.92 MAXDIFF:  196 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-mpeg4-thread b/tests/ref/fate/vsynth1-mpeg4-thread
deleted file mode 100644
index b60933d..0000000
--- a/tests/ref/fate/vsynth1-mpeg4-thread
+++ /dev/null
@@ -1,4 +0,0 @@
-ae675a6a953ddeaecb7a9db14c4d0fa0 *tests/data/fate/vsynth1-mpeg4-thread.avi
-774762 tests/data/fate/vsynth1-mpeg4-thread.avi
-9aa327a244d5179acf7fe64dc1459bff *tests/data/fate/vsynth1-mpeg4-thread.out.rawvideo
-stddev:   10.13 PSNR: 28.02 MAXDIFF:  183 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-mpng b/tests/ref/fate/vsynth1-mpng
deleted file mode 100644
index 875d81b..0000000
--- a/tests/ref/fate/vsynth1-mpng
+++ /dev/null
@@ -1,4 +0,0 @@
-a8e7393fa534289eee9319ded7807f99 *tests/data/fate/vsynth1-mpng.avi
-12157242 tests/data/fate/vsynth1-mpng.avi
-93695a27c24a61105076ca7b1f010bbd *tests/data/fate/vsynth1-mpng.out.rawvideo
-stddev:    3.42 PSNR: 37.44 MAXDIFF:   48 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-msmpeg4 b/tests/ref/fate/vsynth1-msmpeg4
deleted file mode 100644
index 8d32ccc..0000000
--- a/tests/ref/fate/vsynth1-msmpeg4
+++ /dev/null
@@ -1,4 +0,0 @@
-f63295e3dcf4afe48135667dbe9b60b8 *tests/data/fate/vsynth1-msmpeg4.avi
-624714 tests/data/fate/vsynth1-msmpeg4.avi
-4529fee96b8073e02974f5355e5f6c4e *tests/data/fate/vsynth1-msmpeg4.out.rawvideo
-stddev:    7.98 PSNR: 30.09 MAXDIFF:  104 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-msmpeg4v2 b/tests/ref/fate/vsynth1-msmpeg4v2
deleted file mode 100644
index ff54534..0000000
--- a/tests/ref/fate/vsynth1-msmpeg4v2
+++ /dev/null
@@ -1,4 +0,0 @@
-6fbce2ce8618cf8c4c19897188eb1ca0 *tests/data/fate/vsynth1-msmpeg4v2.avi
-623778 tests/data/fate/vsynth1-msmpeg4v2.avi
-0476d9aafc4358654f411fa9648f9560 *tests/data/fate/vsynth1-msmpeg4v2.out.rawvideo
-stddev:    7.97 PSNR: 30.10 MAXDIFF:  105 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-msvideo1 b/tests/ref/fate/vsynth1-msvideo1
deleted file mode 100644
index 9beb739..0000000
--- a/tests/ref/fate/vsynth1-msvideo1
+++ /dev/null
@@ -1,4 +0,0 @@
-37aa67b5928794534cb6a268d4adf48c *tests/data/fate/vsynth1-msvideo1.avi
-2162264 tests/data/fate/vsynth1-msvideo1.avi
-c0665fac1bd896b6fe7fe0eead805bd5 *tests/data/fate/vsynth1-msvideo1.out.rawvideo
-stddev:   11.80 PSNR: 26.69 MAXDIFF:  151 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-prores b/tests/ref/fate/vsynth1-prores
deleted file mode 100644
index 1df41d6..0000000
--- a/tests/ref/fate/vsynth1-prores
+++ /dev/null
@@ -1,4 +0,0 @@
-31159cc9d1693bc66ad7a3083c48bcc4 *tests/data/fate/vsynth1-prores.mov
-5022811 tests/data/fate/vsynth1-prores.mov
-a2e2d1d45341a94ff994d1d92629f778 *tests/data/fate/vsynth1-prores.out.rawvideo
-stddev:    2.47 PSNR: 40.27 MAXDIFF:   31 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-prores_kostya b/tests/ref/fate/vsynth1-prores_kostya
deleted file mode 100644
index f974a7a..0000000
--- a/tests/ref/fate/vsynth1-prores_kostya
+++ /dev/null
@@ -1,4 +0,0 @@
-e7a7e17a40df5d1296cea05d55bd5724 *tests/data/fate/vsynth1-prores_kostya.mov
-3858901 tests/data/fate/vsynth1-prores_kostya.mov
-0a4153637d0cc0a88a8bcbf04cfaf8c6 *tests/data/fate/vsynth1-prores_kostya.out.rawvideo
-stddev:    3.17 PSNR: 38.09 MAXDIFF:   39 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-qtrle b/tests/ref/fate/vsynth1-qtrle
deleted file mode 100644
index 8c12699..0000000
--- a/tests/ref/fate/vsynth1-qtrle
+++ /dev/null
@@ -1,4 +0,0 @@
-9c6ee876369fceac1ff2478a0225bc9b *tests/data/fate/vsynth1-qtrle.mov
-15263148 tests/data/fate/vsynth1-qtrle.mov
-93695a27c24a61105076ca7b1f010bbd *tests/data/fate/vsynth1-qtrle.out.rawvideo
-stddev:    3.42 PSNR: 37.44 MAXDIFF:   48 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-qtrlegray b/tests/ref/fate/vsynth1-qtrlegray
deleted file mode 100644
index 3fe3e30..0000000
--- a/tests/ref/fate/vsynth1-qtrlegray
+++ /dev/null
@@ -1,4 +0,0 @@
-dfb185e38b3557eca0ead72d57ca48f8 *tests/data/fate/vsynth1-qtrlegray.mov
-5113284 tests/data/fate/vsynth1-qtrlegray.mov
-29def4aed035ed65d3a89f7d382fccbe *tests/data/fate/vsynth1-qtrlegray.out.rawvideo
-stddev:   25.95 PSNR: 19.85 MAXDIFF:  122 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-r210 b/tests/ref/fate/vsynth1-r210
deleted file mode 100644
index 68cdac8..0000000
--- a/tests/ref/fate/vsynth1-r210
+++ /dev/null
@@ -1,4 +0,0 @@
-604a34c9f9151891c2d63d2652b75329 *tests/data/fate/vsynth1-r210.avi
-22125260 tests/data/fate/vsynth1-r210.avi
-ecaafa9eec11b5e1453a63ed6d194eed *tests/data/fate/vsynth1-r210.out.rawvideo
-stddev:    3.23 PSNR: 37.94 MAXDIFF:   48 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-rgb b/tests/ref/fate/vsynth1-rgb
deleted file mode 100644
index 94e11e9..0000000
--- a/tests/ref/fate/vsynth1-rgb
+++ /dev/null
@@ -1,4 +0,0 @@
-05f0719cb52486d9a4beb9cfae3f2571 *tests/data/fate/vsynth1-rgb.avi
-15213260 tests/data/fate/vsynth1-rgb.avi
-93695a27c24a61105076ca7b1f010bbd *tests/data/fate/vsynth1-rgb.out.rawvideo
-stddev:    3.42 PSNR: 37.44 MAXDIFF:   48 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-snow b/tests/ref/fate/vsynth1-snow
deleted file mode 100644
index 0b47513..0000000
--- a/tests/ref/fate/vsynth1-snow
+++ /dev/null
@@ -1,4 +0,0 @@
-d593b3c1a9729ce6dd1721f58fa93712 *tests/data/fate/vsynth1-snow.avi
-136088 tests/data/fate/vsynth1-snow.avi
-91021b7d6d7908648fe78cc1975af8c4 *tests/data/fate/vsynth1-snow.out.rawvideo
-stddev:   22.77 PSNR: 20.98 MAXDIFF:  172 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-snow-hpel b/tests/ref/fate/vsynth1-snow-hpel
deleted file mode 100644
index e2968b1..0000000
--- a/tests/ref/fate/vsynth1-snow-hpel
+++ /dev/null
@@ -1,4 +0,0 @@
-301755ff5dcd31c2aefc8f103cfc2917 *tests/data/fate/vsynth1-snow-hpel.avi
-138712 tests/data/fate/vsynth1-snow-hpel.avi
-d6845c8f1310e041afdcebc6bbfc449b *tests/data/fate/vsynth1-snow-hpel.out.rawvideo
-stddev:   22.74 PSNR: 20.99 MAXDIFF:  171 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-snow-ll b/tests/ref/fate/vsynth1-snow-ll
deleted file mode 100644
index fdc5046..0000000
--- a/tests/ref/fate/vsynth1-snow-ll
+++ /dev/null
@@ -1,4 +0,0 @@
-6d29e8c06a645cdee45073c4f3d0004e *tests/data/fate/vsynth1-snow-ll.avi
-3419980 tests/data/fate/vsynth1-snow-ll.avi
-c5ccac874dbf808e9088bc3107860042 *tests/data/fate/vsynth1-snow-ll.out.rawvideo
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-svq1 b/tests/ref/fate/vsynth1-svq1
deleted file mode 100644
index 0c40dbd..0000000
--- a/tests/ref/fate/vsynth1-svq1
+++ /dev/null
@@ -1,4 +0,0 @@
-4654e7af0d4aa58c3db1eb145e278038 *tests/data/fate/vsynth1-svq1.mov
-1334223 tests/data/fate/vsynth1-svq1.mov
-9cc35c54b2c77d36bd7e308b393c1f81 *tests/data/fate/vsynth1-svq1.out.rawvideo
-stddev:    9.58 PSNR: 28.50 MAXDIFF:  210 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-v210 b/tests/ref/fate/vsynth1-v210
deleted file mode 100644
index 5248676..0000000
--- a/tests/ref/fate/vsynth1-v210
+++ /dev/null
@@ -1,4 +0,0 @@
-dd6c870a2a52c9e75ce61c3670e710e7 *tests/data/fate/vsynth1-v210.avi
-14752460 tests/data/fate/vsynth1-v210.avi
-50973792d3f1abe04a51ee0121f077f2 *tests/data/fate/vsynth1-v210.out.rawvideo
-stddev:    1.85 PSNR: 42.78 MAXDIFF:   29 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-v308 b/tests/ref/fate/vsynth1-v308
deleted file mode 100644
index 137dcf9..0000000
--- a/tests/ref/fate/vsynth1-v308
+++ /dev/null
@@ -1,4 +0,0 @@
-8d5f2065ce6547acc51041a679b7d6c4 *tests/data/fate/vsynth1-v308.avi
-15213260 tests/data/fate/vsynth1-v308.avi
-10fb42f1abf40a289c3edafc0390482c *tests/data/fate/vsynth1-v308.out.rawvideo
-stddev:    2.67 PSNR: 39.60 MAXDIFF:   43 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-v408 b/tests/ref/fate/vsynth1-v408
deleted file mode 100644
index c7f414c..0000000
--- a/tests/ref/fate/vsynth1-v408
+++ /dev/null
@@ -1,4 +0,0 @@
-98057c4d5ce12a1b1b3ca15839f47c95 *tests/data/fate/vsynth1-v408.avi
-20282060 tests/data/fate/vsynth1-v408.avi
-c5ccac874dbf808e9088bc3107860042 *tests/data/fate/vsynth1-v408.out.rawvideo
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-wmv1 b/tests/ref/fate/vsynth1-wmv1
deleted file mode 100644
index 9afc020..0000000
--- a/tests/ref/fate/vsynth1-wmv1
+++ /dev/null
@@ -1,4 +0,0 @@
-8c406d0253bd474d4764f5d75776fc03 *tests/data/fate/vsynth1-wmv1.avi
-626882 tests/data/fate/vsynth1-wmv1.avi
-3354066ebdd8cd8098394be2384744e7 *tests/data/fate/vsynth1-wmv1.out.rawvideo
-stddev:    7.97 PSNR: 30.09 MAXDIFF:  110 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-wmv2 b/tests/ref/fate/vsynth1-wmv2
deleted file mode 100644
index 6ce5520..0000000
--- a/tests/ref/fate/vsynth1-wmv2
+++ /dev/null
@@ -1,4 +0,0 @@
-916932bf4b81443b4b87128ba8b63580 *tests/data/fate/vsynth1-wmv2.avi
-659844 tests/data/fate/vsynth1-wmv2.avi
-3354066ebdd8cd8098394be2384744e7 *tests/data/fate/vsynth1-wmv2.out.rawvideo
-stddev:    7.97 PSNR: 30.09 MAXDIFF:  110 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-y41p b/tests/ref/fate/vsynth1-y41p
deleted file mode 100644
index d2147f6..0000000
--- a/tests/ref/fate/vsynth1-y41p
+++ /dev/null
@@ -1,4 +0,0 @@
-70bbcb52acac0a3cb3217719669a8242 *tests/data/fate/vsynth1-y41p.avi
-7610060 tests/data/fate/vsynth1-y41p.avi
-3aef1d83732a3f9835ee2523a11c95c1 *tests/data/fate/vsynth1-y41p.out.rawvideo
-stddev:    5.98 PSNR: 32.59 MAXDIFF:   87 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-yuv b/tests/ref/fate/vsynth1-yuv
deleted file mode 100644
index 5dc29aa..0000000
--- a/tests/ref/fate/vsynth1-yuv
+++ /dev/null
@@ -1,4 +0,0 @@
-eaa66c3b27a2602e882befe154a8b119 *tests/data/fate/vsynth1-yuv.avi
-7610060 tests/data/fate/vsynth1-yuv.avi
-c5ccac874dbf808e9088bc3107860042 *tests/data/fate/vsynth1-yuv.out.rawvideo
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-yuv4 b/tests/ref/fate/vsynth1-yuv4
deleted file mode 100644
index 5b7b925..0000000
--- a/tests/ref/fate/vsynth1-yuv4
+++ /dev/null
@@ -1,4 +0,0 @@
-e0d593eb635432f421b93224e425ee03 *tests/data/fate/vsynth1-yuv4.avi
-7610060 tests/data/fate/vsynth1-yuv4.avi
-c5ccac874dbf808e9088bc3107860042 *tests/data/fate/vsynth1-yuv4.out.rawvideo
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-zlib b/tests/ref/fate/vsynth1-zlib
deleted file mode 100644
index 068f154..0000000
--- a/tests/ref/fate/vsynth1-zlib
+++ /dev/null
@@ -1,4 +0,0 @@
-fe4983e551b48dc555e1aeaf628f649f *tests/data/fate/vsynth1-zlib.avi
-12108644 tests/data/fate/vsynth1-zlib.avi
-93695a27c24a61105076ca7b1f010bbd *tests/data/fate/vsynth1-zlib.out.rawvideo
-stddev:    3.42 PSNR: 37.44 MAXDIFF:   48 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-amv b/tests/ref/fate/vsynth2-amv
deleted file mode 100644
index 313edac..0000000
--- a/tests/ref/fate/vsynth2-amv
+++ /dev/null
@@ -1,4 +0,0 @@
-853ae9d6426cb3c4d4bad3592e1a2ec3 *tests/data/fate/vsynth2-amv.avi
-761988 tests/data/fate/vsynth2-amv.avi
-f256ad9feefb499c6569d06d868eb496 *tests/data/fate/vsynth2-amv.out.rawvideo
-stddev:    4.30 PSNR: 35.46 MAXDIFF:   65 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-asv1 b/tests/ref/fate/vsynth2-asv1
deleted file mode 100644
index 702244e..0000000
--- a/tests/ref/fate/vsynth2-asv1
+++ /dev/null
@@ -1,4 +0,0 @@
-4eb34d2de25f67a2706456e999338fe9 *tests/data/fate/vsynth2-asv1.avi
-832512 tests/data/fate/vsynth2-asv1.avi
-c96ff7fd17c52f99ddb7922a4cb9168f *tests/data/fate/vsynth2-asv1.out.rawvideo
-stddev:   10.47 PSNR: 27.73 MAXDIFF:   98 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-asv2 b/tests/ref/fate/vsynth2-asv2
deleted file mode 100644
index 8f6f617..0000000
--- a/tests/ref/fate/vsynth2-asv2
+++ /dev/null
@@ -1,4 +0,0 @@
-9649a4b68fb1107bad13e8a7574cc72d *tests/data/fate/vsynth2-asv2.avi
-789072 tests/data/fate/vsynth2-asv2.avi
-74a78015b64b2cf8cb9da2e44f508a69 *tests/data/fate/vsynth2-asv2.out.rawvideo
-stddev:   10.28 PSNR: 27.89 MAXDIFF:   95 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-cljr b/tests/ref/fate/vsynth2-cljr
deleted file mode 100644
index ae13185..0000000
--- a/tests/ref/fate/vsynth2-cljr
+++ /dev/null
@@ -1,4 +0,0 @@
-fdc1926e0a599de94513f0a3472b598f *tests/data/fate/vsynth2-cljr.avi
-5075660 tests/data/fate/vsynth2-cljr.avi
-965c4a134144b30b24d6d138b03ddb8c *tests/data/fate/vsynth2-cljr.out.rawvideo
-stddev:    3.29 PSNR: 37.76 MAXDIFF:   23 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-ffv1 b/tests/ref/fate/vsynth2-ffv1
deleted file mode 100644
index 0a6b184..0000000
--- a/tests/ref/fate/vsynth2-ffv1
+++ /dev/null
@@ -1,4 +0,0 @@
-d72b0960e162d4998b9acbabb07e99ab *tests/data/fate/vsynth2-ffv1.avi
-3525804 tests/data/fate/vsynth2-ffv1.avi
-dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth2-ffv1.out.rawvideo
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-ffvhuff b/tests/ref/fate/vsynth2-ffvhuff
deleted file mode 100644
index ac58147..0000000
--- a/tests/ref/fate/vsynth2-ffvhuff
+++ /dev/null
@@ -1,4 +0,0 @@
-63926d8835dd5779dca0a4bc081ca8ae *tests/data/fate/vsynth2-ffvhuff.avi
-4988056 tests/data/fate/vsynth2-ffvhuff.avi
-dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth2-ffvhuff.out.rawvideo
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-h261 b/tests/ref/fate/vsynth2-h261
deleted file mode 100644
index 375c5c6..0000000
--- a/tests/ref/fate/vsynth2-h261
+++ /dev/null
@@ -1,4 +0,0 @@
-3a11ad7fb9e953041f40d0e8fd0ff278 *tests/data/fate/vsynth2-h261.avi
-191072 tests/data/fate/vsynth2-h261.avi
-08f65e9aeeeaf189548c2bb417d5114f *tests/data/fate/vsynth2-h261.out.rawvideo
-stddev:    6.37 PSNR: 32.03 MAXDIFF:   77 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-h263 b/tests/ref/fate/vsynth2-h263
deleted file mode 100644
index 47c86c5..0000000
--- a/tests/ref/fate/vsynth2-h263
+++ /dev/null
@@ -1,4 +0,0 @@
-dc956aec267ebed753c1284847f62e2e *tests/data/fate/vsynth2-h263.avi
-160114 tests/data/fate/vsynth2-h263.avi
-b7d733ebedbaa04f49bf7493a907e223 *tests/data/fate/vsynth2-h263.out.rawvideo
-stddev:    5.43 PSNR: 33.42 MAXDIFF:   77 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-h263p b/tests/ref/fate/vsynth2-h263p
deleted file mode 100644
index 2920d7a..0000000
--- a/tests/ref/fate/vsynth2-h263p
+++ /dev/null
@@ -1,4 +0,0 @@
-628d3df9dad01c2da648f4cdc31ef62d *tests/data/fate/vsynth2-h263p.avi
-868010 tests/data/fate/vsynth2-h263p.avi
-dca18571c05c13dd691d7b0b232e43fc *tests/data/fate/vsynth2-h263p.out.rawvideo
-stddev:    1.91 PSNR: 42.50 MAXDIFF:   19 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-huffyuv b/tests/ref/fate/vsynth2-huffyuv
deleted file mode 100644
index d94cbd6..0000000
--- a/tests/ref/fate/vsynth2-huffyuv
+++ /dev/null
@@ -1,4 +0,0 @@
-ed66182be0d515e8b6cb970ad63162da *tests/data/fate/vsynth2-huffyuv.avi
-6455232 tests/data/fate/vsynth2-huffyuv.avi
-dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth2-huffyuv.out.rawvideo
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-j2k b/tests/ref/fate/vsynth2-j2k
deleted file mode 100644
index 1ad4482..0000000
--- a/tests/ref/fate/vsynth2-j2k
+++ /dev/null
@@ -1,4 +0,0 @@
-b30dc1851c0fb37726d977ec1d5ad527 *tests/data/fate/vsynth2-j2k.avi
-1151156 tests/data/fate/vsynth2-j2k.avi
-ec5218eec33a021945c28c72093382a5 *tests/data/fate/vsynth2-j2k.out.rawvideo
-stddev:    4.54 PSNR: 34.99 MAXDIFF:   61 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-jpegls b/tests/ref/fate/vsynth2-jpegls
deleted file mode 100644
index 728d54f..0000000
--- a/tests/ref/fate/vsynth2-jpegls
+++ /dev/null
@@ -1,4 +0,0 @@
-8a94dc94b6df8bdde9a639246351d816 *tests/data/fate/vsynth2-jpegls.avi
-8334630 tests/data/fate/vsynth2-jpegls.avi
-3a984506f1ebfc9fb73b6814cab201cc *tests/data/fate/vsynth2-jpegls.out.rawvideo
-stddev:    0.66 PSNR: 51.73 MAXDIFF:   14 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-ljpeg b/tests/ref/fate/vsynth2-ljpeg
deleted file mode 100644
index 529b790..0000000
--- a/tests/ref/fate/vsynth2-ljpeg
+++ /dev/null
@@ -1,4 +0,0 @@
-554a4a6a5a9058c588f8bf2de405bc70 *tests/data/fate/vsynth2-ljpeg.avi
-4766914 tests/data/fate/vsynth2-ljpeg.avi
-dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth2-ljpeg.out.rawvideo
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-mjpeg b/tests/ref/fate/vsynth2-mjpeg
deleted file mode 100644
index c823c42..0000000
--- a/tests/ref/fate/vsynth2-mjpeg
+++ /dev/null
@@ -1,4 +0,0 @@
-fb05e46b8c69ad1f00d3d15cf4be6cee *tests/data/fate/vsynth2-mjpeg.avi
-673186 tests/data/fate/vsynth2-mjpeg.avi
-9d4bd90e9abfa18192383b4adc23c8d4 *tests/data/fate/vsynth2-mjpeg.out.rawvideo
-stddev:    4.32 PSNR: 35.40 MAXDIFF:   49 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-mpeg4-adap b/tests/ref/fate/vsynth2-mpeg4-adap
deleted file mode 100644
index 0209cce..0000000
--- a/tests/ref/fate/vsynth2-mpeg4-adap
+++ /dev/null
@@ -1,4 +0,0 @@
-d1683da1db86ec4365a9629ca764951f *tests/data/fate/vsynth2-mpeg4-adap.avi
-198508 tests/data/fate/vsynth2-mpeg4-adap.avi
-87b6dbe98d276137fceaae2fa672eced *tests/data/fate/vsynth2-mpeg4-adap.out.rawvideo
-stddev:    3.75 PSNR: 36.65 MAXDIFF:   71 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-mpeg4-adv b/tests/ref/fate/vsynth2-mpeg4-adv
deleted file mode 100644
index 6d7d507..0000000
--- a/tests/ref/fate/vsynth2-mpeg4-adv
+++ /dev/null
@@ -1,4 +0,0 @@
-dee7be19486a76d96c88d18eefba8f86 *tests/data/fate/vsynth2-mpeg4-adv.avi
-141546 tests/data/fate/vsynth2-mpeg4-adv.avi
-3f3a21e9db85a9c0f7022f557a5374c1 *tests/data/fate/vsynth2-mpeg4-adv.out.rawvideo
-stddev:    4.94 PSNR: 34.25 MAXDIFF:   69 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-mpeg4-error b/tests/ref/fate/vsynth2-mpeg4-error
deleted file mode 100644
index eb9fc37..0000000
--- a/tests/ref/fate/vsynth2-mpeg4-error
+++ /dev/null
@@ -1,4 +0,0 @@
-ee46af7cbbb9c7c03311e2143190fb20 *tests/data/fate/vsynth2-mpeg4-error.avi
-180376 tests/data/fate/vsynth2-mpeg4-error.avi
-4537ba5320f1ae0971cc6e329c366776 *tests/data/fate/vsynth2-mpeg4-error.out.rawvideo
-stddev:    7.65 PSNR: 30.45 MAXDIFF:  158 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-mpeg4-nr b/tests/ref/fate/vsynth2-mpeg4-nr
deleted file mode 100644
index 0a1194a..0000000
--- a/tests/ref/fate/vsynth2-mpeg4-nr
+++ /dev/null
@@ -1,4 +0,0 @@
-a42042b1a2d3f4577d6293fc0dd077cb *tests/data/fate/vsynth2-mpeg4-nr.avi
-155006 tests/data/fate/vsynth2-mpeg4-nr.avi
-d89cd5d0b1707f48fa9c4747c66d2d56 *tests/data/fate/vsynth2-mpeg4-nr.out.rawvideo
-stddev:    4.73 PSNR: 34.63 MAXDIFF:   64 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-mpeg4-qpel b/tests/ref/fate/vsynth2-mpeg4-qpel
deleted file mode 100644
index 0869eda..0000000
--- a/tests/ref/fate/vsynth2-mpeg4-qpel
+++ /dev/null
@@ -1,4 +0,0 @@
-0e0aaf9c114eb8c60a4083b8a98ea7c7 *tests/data/fate/vsynth2-mpeg4-qpel.avi
-163674 tests/data/fate/vsynth2-mpeg4-qpel.avi
-e2ce994dbb66da51c2e1ad26617d7c2f *tests/data/fate/vsynth2-mpeg4-qpel.out.rawvideo
-stddev:    3.97 PSNR: 36.14 MAXDIFF:   54 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-mpeg4-qprd b/tests/ref/fate/vsynth2-mpeg4-qprd
deleted file mode 100644
index 8e69b3e..0000000
--- a/tests/ref/fate/vsynth2-mpeg4-qprd
+++ /dev/null
@@ -1,4 +0,0 @@
-5aca88f3b6036515a1cdd41647395dc2 *tests/data/fate/vsynth2-mpeg4-qprd.avi
-231462 tests/data/fate/vsynth2-mpeg4-qprd.avi
-3071250e0864546c2455c9f9c9b8604e *tests/data/fate/vsynth2-mpeg4-qprd.out.rawvideo
-stddev:    3.71 PSNR: 36.72 MAXDIFF:   61 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-mpeg4-rc b/tests/ref/fate/vsynth2-mpeg4-rc
deleted file mode 100644
index 4401f92..0000000
--- a/tests/ref/fate/vsynth2-mpeg4-rc
+++ /dev/null
@@ -1,4 +0,0 @@
-8e4101a166eee52093ed687c62764d5e *tests/data/fate/vsynth2-mpeg4-rc.avi
-226322 tests/data/fate/vsynth2-mpeg4-rc.avi
-6e8b62e8c3bcbfdcc58afb69a0b1c4e3 *tests/data/fate/vsynth2-mpeg4-rc.out.rawvideo
-stddev:    4.23 PSNR: 35.60 MAXDIFF:   85 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-mpeg4-thread b/tests/ref/fate/vsynth2-mpeg4-thread
deleted file mode 100644
index 664f89e..0000000
--- a/tests/ref/fate/vsynth2-mpeg4-thread
+++ /dev/null
@@ -1,4 +0,0 @@
-9859aa7d322b639b07386980bc3f4797 *tests/data/fate/vsynth2-mpeg4-thread.avi
-250104 tests/data/fate/vsynth2-mpeg4-thread.avi
-045fe9f226bbcc3d41644bffaed03b31 *tests/data/fate/vsynth2-mpeg4-thread.out.rawvideo
-stddev:    3.69 PSNR: 36.78 MAXDIFF:   65 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-mpng b/tests/ref/fate/vsynth2-mpng
deleted file mode 100644
index 1a298f9..0000000
--- a/tests/ref/fate/vsynth2-mpng
+++ /dev/null
@@ -1,4 +0,0 @@
-198a3d67c56e1b5b12bdd3ffa67d8128 *tests/data/fate/vsynth2-mpng.avi
-12557288 tests/data/fate/vsynth2-mpng.avi
-98d0e2854731472c5bf13d8638502d0a *tests/data/fate/vsynth2-mpng.out.rawvideo
-stddev:    1.26 PSNR: 46.10 MAXDIFF:   13 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-msmpeg4 b/tests/ref/fate/vsynth2-msmpeg4
deleted file mode 100644
index 0656101..0000000
--- a/tests/ref/fate/vsynth2-msmpeg4
+++ /dev/null
@@ -1,4 +0,0 @@
-cc347c58bf116cdb09b0ce1d549fa989 *tests/data/fate/vsynth2-msmpeg4.avi
-127672 tests/data/fate/vsynth2-msmpeg4.avi
-bb14902d5850d6b0ab70fdb017855775 *tests/data/fate/vsynth2-msmpeg4.out.rawvideo
-stddev:    5.33 PSNR: 33.58 MAXDIFF:   78 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-msmpeg4v2 b/tests/ref/fate/vsynth2-msmpeg4v2
deleted file mode 100644
index fe9cc4c..0000000
--- a/tests/ref/fate/vsynth2-msmpeg4v2
+++ /dev/null
@@ -1,4 +0,0 @@
-dc94a157743f7439b15e69d6a0737b8a *tests/data/fate/vsynth2-msmpeg4v2.avi
-129930 tests/data/fate/vsynth2-msmpeg4v2.avi
-537c114e1d47c54a4bccd31f4073e9bd *tests/data/fate/vsynth2-msmpeg4v2.out.rawvideo
-stddev:    5.33 PSNR: 33.59 MAXDIFF:   79 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-msvideo1 b/tests/ref/fate/vsynth2-msvideo1
deleted file mode 100644
index 8338ac4..0000000
--- a/tests/ref/fate/vsynth2-msvideo1
+++ /dev/null
@@ -1,4 +0,0 @@
-e70658b8b97eb4c7e63b2081c3a602de *tests/data/fate/vsynth2-msvideo1.avi
-1259308 tests/data/fate/vsynth2-msvideo1.avi
-cd83ffcbc73573044e3aead3094229e5 *tests/data/fate/vsynth2-msvideo1.out.rawvideo
-stddev:    7.42 PSNR: 30.72 MAXDIFF:  123 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-prores b/tests/ref/fate/vsynth2-prores
deleted file mode 100644
index 5db45d9..0000000
--- a/tests/ref/fate/vsynth2-prores
+++ /dev/null
@@ -1,4 +0,0 @@
-0faf42c187120c61d64a5e0cea4fc92a *tests/data/fate/vsynth2-prores.mov
-2844066 tests/data/fate/vsynth2-prores.mov
-b5844025c0f4c7c37db702c3213db232 *tests/data/fate/vsynth2-prores.out.rawvideo
-stddev:    1.31 PSNR: 45.77 MAXDIFF:   11 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-prores_kostya b/tests/ref/fate/vsynth2-prores_kostya
deleted file mode 100644
index 6128b8c..0000000
--- a/tests/ref/fate/vsynth2-prores_kostya
+++ /dev/null
@@ -1,4 +0,0 @@
-80dbde33cf16cde01e6229313ac7ddc7 *tests/data/fate/vsynth2-prores_kostya.mov
-3884586 tests/data/fate/vsynth2-prores_kostya.mov
-ca2f6c1162635dedfa468c90f1fdc0ef *tests/data/fate/vsynth2-prores_kostya.out.rawvideo
-stddev:    0.92 PSNR: 48.77 MAXDIFF:   10 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-qtrle b/tests/ref/fate/vsynth2-qtrle
deleted file mode 100644
index d3b045b..0000000
--- a/tests/ref/fate/vsynth2-qtrle
+++ /dev/null
@@ -1,4 +0,0 @@
-6ac61c011e1811ebd045535b141351de *tests/data/fate/vsynth2-qtrle.mov
-14798335 tests/data/fate/vsynth2-qtrle.mov
-98d0e2854731472c5bf13d8638502d0a *tests/data/fate/vsynth2-qtrle.out.rawvideo
-stddev:    1.26 PSNR: 46.10 MAXDIFF:   13 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-qtrlegray b/tests/ref/fate/vsynth2-qtrlegray
deleted file mode 100644
index 1306f3e..0000000
--- a/tests/ref/fate/vsynth2-qtrlegray
+++ /dev/null
@@ -1,4 +0,0 @@
-5a66c6d2b2db71eddbc50819483aa647 *tests/data/fate/vsynth2-qtrlegray.mov
-5111273 tests/data/fate/vsynth2-qtrlegray.mov
-f63b5ebdfdba750e547c25131b0a3fd1 *tests/data/fate/vsynth2-qtrlegray.out.rawvideo
-stddev:   19.42 PSNR: 22.36 MAXDIFF:   72 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-r210 b/tests/ref/fate/vsynth2-r210
deleted file mode 100644
index 610ba2c..0000000
--- a/tests/ref/fate/vsynth2-r210
+++ /dev/null
@@ -1,4 +0,0 @@
-d7a6f298e6869a74c0988fc3b30d0351 *tests/data/fate/vsynth2-r210.avi
-22125260 tests/data/fate/vsynth2-r210.avi
-6ea4fcd93fc83defc8770e85b64b60bb *tests/data/fate/vsynth2-r210.out.rawvideo
-stddev:    0.70 PSNR: 51.12 MAXDIFF:   12 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-rgb b/tests/ref/fate/vsynth2-rgb
deleted file mode 100644
index c89f46f..0000000
--- a/tests/ref/fate/vsynth2-rgb
+++ /dev/null
@@ -1,4 +0,0 @@
-f2e9c419023c743bf99aa5b2e55ad233 *tests/data/fate/vsynth2-rgb.avi
-15213260 tests/data/fate/vsynth2-rgb.avi
-98d0e2854731472c5bf13d8638502d0a *tests/data/fate/vsynth2-rgb.out.rawvideo
-stddev:    1.26 PSNR: 46.10 MAXDIFF:   13 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-snow b/tests/ref/fate/vsynth2-snow
deleted file mode 100644
index 0e78f32..0000000
--- a/tests/ref/fate/vsynth2-snow
+++ /dev/null
@@ -1,4 +0,0 @@
-af651d8ef0a66257ac8b2ef8b229f27b *tests/data/fate/vsynth2-snow.avi
-57700 tests/data/fate/vsynth2-snow.avi
-8890189af71a0dd3447c4e8424c9a76b *tests/data/fate/vsynth2-snow.out.rawvideo
-stddev:   10.47 PSNR: 27.72 MAXDIFF:  119 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-snow-hpel b/tests/ref/fate/vsynth2-snow-hpel
deleted file mode 100644
index 2194a13..0000000
--- a/tests/ref/fate/vsynth2-snow-hpel
+++ /dev/null
@@ -1,4 +0,0 @@
-ac1400b66514aa280300bba6477b4e97 *tests/data/fate/vsynth2-snow-hpel.avi
-61772 tests/data/fate/vsynth2-snow-hpel.avi
-8680d40905f423999d65b996c4dcb984 *tests/data/fate/vsynth2-snow-hpel.out.rawvideo
-stddev:   10.45 PSNR: 27.74 MAXDIFF:  123 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-snow-ll b/tests/ref/fate/vsynth2-snow-ll
deleted file mode 100644
index 2d33b08..0000000
--- a/tests/ref/fate/vsynth2-snow-ll
+++ /dev/null
@@ -1,4 +0,0 @@
-a8fccf278bbb17d37a756ecf11672b09 *tests/data/fate/vsynth2-snow-ll.avi
-2721758 tests/data/fate/vsynth2-snow-ll.avi
-dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth2-snow-ll.out.rawvideo
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-svq1 b/tests/ref/fate/vsynth2-svq1
deleted file mode 100644
index b2cd35f..0000000
--- a/tests/ref/fate/vsynth2-svq1
+++ /dev/null
@@ -1,4 +0,0 @@
-320a7fbbaecc0989df054bf9678bfdf6 *tests/data/fate/vsynth2-svq1.mov
-766691 tests/data/fate/vsynth2-svq1.mov
-aa03471dac3f49455a33a2b19fda1098 *tests/data/fate/vsynth2-svq1.out.rawvideo
-stddev:    3.23 PSNR: 37.93 MAXDIFF:   61 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-v210 b/tests/ref/fate/vsynth2-v210
deleted file mode 100644
index 407ad0e..0000000
--- a/tests/ref/fate/vsynth2-v210
+++ /dev/null
@@ -1,4 +0,0 @@
-db0579bd46e1ba133ff86c0f7cdd761f *tests/data/fate/vsynth2-v210.avi
-14752460 tests/data/fate/vsynth2-v210.avi
-a627fb50c8276200fd71383977d87ca3 *tests/data/fate/vsynth2-v210.out.rawvideo
-stddev:    0.34 PSNR: 57.43 MAXDIFF:    6 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-v308 b/tests/ref/fate/vsynth2-v308
deleted file mode 100644
index cd20214..0000000
--- a/tests/ref/fate/vsynth2-v308
+++ /dev/null
@@ -1,4 +0,0 @@
-214671673e6c82bad8190d0329f01fdc *tests/data/fate/vsynth2-v308.avi
-15213260 tests/data/fate/vsynth2-v308.avi
-d43cb310c130c69214332d74f6ee5f9a *tests/data/fate/vsynth2-v308.out.rawvideo
-stddev:    0.41 PSNR: 55.80 MAXDIFF:    7 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-v408 b/tests/ref/fate/vsynth2-v408
deleted file mode 100644
index 8d12fc7..0000000
--- a/tests/ref/fate/vsynth2-v408
+++ /dev/null
@@ -1,4 +0,0 @@
-033d112ec5a1a78882233d0b791e5ef7 *tests/data/fate/vsynth2-v408.avi
-20282060 tests/data/fate/vsynth2-v408.avi
-dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth2-v408.out.rawvideo
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-wmv1 b/tests/ref/fate/vsynth2-wmv1
deleted file mode 100644
index 7eb0fe6..0000000
--- a/tests/ref/fate/vsynth2-wmv1
+++ /dev/null
@@ -1,4 +0,0 @@
-0eef8e6c0bddcd7b60564e0dfcbcf461 *tests/data/fate/vsynth2-wmv1.avi
-129522 tests/data/fate/vsynth2-wmv1.avi
-dec44e3c04db4fef49a7728f164d9159 *tests/data/fate/vsynth2-wmv1.out.rawvideo
-stddev:    5.33 PSNR: 33.60 MAXDIFF:   77 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-wmv2 b/tests/ref/fate/vsynth2-wmv2
deleted file mode 100644
index 8d55a47..0000000
--- a/tests/ref/fate/vsynth2-wmv2
+++ /dev/null
@@ -1,4 +0,0 @@
-c68ca99473538064d9de3bdcc8f2e759 *tests/data/fate/vsynth2-wmv2.avi
-129846 tests/data/fate/vsynth2-wmv2.avi
-dec44e3c04db4fef49a7728f164d9159 *tests/data/fate/vsynth2-wmv2.out.rawvideo
-stddev:    5.33 PSNR: 33.60 MAXDIFF:   77 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-y41p b/tests/ref/fate/vsynth2-y41p
deleted file mode 100644
index b310e3b..0000000
--- a/tests/ref/fate/vsynth2-y41p
+++ /dev/null
@@ -1,4 +0,0 @@
-8e0139963e79180a0fc1c154e36cebe5 *tests/data/fate/vsynth2-y41p.avi
-7610060 tests/data/fate/vsynth2-y41p.avi
-d27a84ccdac09055724d122e03fea82a *tests/data/fate/vsynth2-y41p.out.rawvideo
-stddev:    1.07 PSNR: 47.54 MAXDIFF:   21 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-yuv b/tests/ref/fate/vsynth2-yuv
deleted file mode 100644
index e5409b0..0000000
--- a/tests/ref/fate/vsynth2-yuv
+++ /dev/null
@@ -1,4 +0,0 @@
-3d5ee6d2023bc15bba898819e4977e46 *tests/data/fate/vsynth2-yuv.avi
-7610060 tests/data/fate/vsynth2-yuv.avi
-dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth2-yuv.out.rawvideo
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-yuv4 b/tests/ref/fate/vsynth2-yuv4
deleted file mode 100644
index a5e9ee5..0000000
--- a/tests/ref/fate/vsynth2-yuv4
+++ /dev/null
@@ -1,4 +0,0 @@
-3d24f1d320c4ead1efbf3c952a902379 *tests/data/fate/vsynth2-yuv4.avi
-7610060 tests/data/fate/vsynth2-yuv4.avi
-dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth2-yuv4.out.rawvideo
-stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-zlib b/tests/ref/fate/vsynth2-zlib
deleted file mode 100644
index d3295e3..0000000
--- a/tests/ref/fate/vsynth2-zlib
+++ /dev/null
@@ -1,4 +0,0 @@
-f4bfa774c853abe8f06a29596c1f16cb *tests/data/fate/vsynth2-zlib.avi
-12517188 tests/data/fate/vsynth2-zlib.avi
-98d0e2854731472c5bf13d8638502d0a *tests/data/fate/vsynth2-zlib.out.rawvideo
-stddev:    1.26 PSNR: 46.10 MAXDIFF:   13 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/wmv8-drm-nodec b/tests/ref/fate/wmv8-drm-nodec
index 9067c6a..76c4e75 100644
--- a/tests/ref/fate/wmv8-drm-nodec
+++ b/tests/ref/fate/wmv8-drm-nodec
@@ -5,148 +5,148 @@
 1,        435,        435,        0,     1088, 0x8dfa1368
 1,        740,        740,        0,     1088, 0xc0d211be
 1,       1023,       1023,        0,     1088, 0x8238113a
-0,       1208,       1208,        0,      137, 0x903c415e
-0,       1250,       1250,        0,      942, 0xd5b7d2aa
-0,       1291,       1291,        0,      841, 0xaffd8ce6
+0,       1208,       1208,        0,      137, 0x903c415e, F=0x0
+0,       1250,       1250,        0,      942, 0xd5b7d2aa, F=0x0
+0,       1291,       1291,        0,      841, 0xaffd8ce6, F=0x0
 1,       1306,       1306,        0,     1088, 0x9f8924b7
-0,       1333,       1333,        0,     1164, 0x4ed84836
-0,       1375,       1375,        0,     1492, 0x37f3e8aa
-0,       1416,       1416,        0,     1663, 0xc091392d
-0,       1458,       1458,        0,     1443, 0x6162c718
-0,       1500,       1500,        0,     1721, 0x7bdb3dd0
-0,       1541,       1541,        0,     1410, 0xde689881
-0,       1583,       1583,        0,     1258, 0xb5b86920
+0,       1333,       1333,        0,     1164, 0x4ed84836, F=0x0
+0,       1375,       1375,        0,     1492, 0x37f3e8aa, F=0x0
+0,       1416,       1416,        0,     1663, 0xc091392d, F=0x0
+0,       1458,       1458,        0,     1443, 0x6162c718, F=0x0
+0,       1500,       1500,        0,     1721, 0x7bdb3dd0, F=0x0
+0,       1541,       1541,        0,     1410, 0xde689881, F=0x0
+0,       1583,       1583,        0,     1258, 0xb5b86920, F=0x0
 1,       1589,       1589,        0,     1088, 0x767f317a
-0,       1625,       1625,        0,     2050, 0x99b6d7c7
-0,       1666,       1666,        0,     1242, 0x9ba35009
-0,       1708,       1708,        0,     1630, 0x17f10192
-0,       1750,       1750,        0,     1747, 0xbbee59d7
-0,       1791,       1791,        0,     1565, 0xb09b00d9
-0,       1833,       1833,        0,     1573, 0xd2e62201
+0,       1625,       1625,        0,     2050, 0x99b6d7c7, F=0x0
+0,       1666,       1666,        0,     1242, 0x9ba35009, F=0x0
+0,       1708,       1708,        0,     1630, 0x17f10192, F=0x0
+0,       1750,       1750,        0,     1747, 0xbbee59d7, F=0x0
+0,       1791,       1791,        0,     1565, 0xb09b00d9, F=0x0
+0,       1833,       1833,        0,     1573, 0xd2e62201, F=0x0
 1,       1872,       1872,        0,     1088, 0x57000d38
-0,       1875,       1875,        0,     1353, 0x2305a24d
-0,       1916,       1916,        0,     1425, 0xf41bbb46
-0,       1958,       1958,        0,     1355, 0xfc08a762
-0,       2000,       2000,        0,     1363, 0x98cda71d
-0,       2041,       2041,        0,     1547, 0x8742f11f
-0,       2083,       2083,        0,     1967, 0x43d61723
-0,       2125,       2125,        0,     1378, 0xde22c753
-0,       2166,       2166,        0,      961, 0x2418a4da
+0,       1875,       1875,        0,     1353, 0x2305a24d, F=0x0
+0,       1916,       1916,        0,     1425, 0xf41bbb46, F=0x0
+0,       1958,       1958,        0,     1355, 0xfc08a762, F=0x0
+0,       2000,       2000,        0,     1363, 0x98cda71d, F=0x0
+0,       2041,       2041,        0,     1547, 0x8742f11f, F=0x0
+0,       2083,       2083,        0,     1967, 0x43d61723, F=0x0
+0,       2125,       2125,        0,     1378, 0xde22c753, F=0x0
+0,       2166,       2166,        0,      961, 0x2418a4da, F=0x0
 1,       2198,       2198,        0,     1088, 0xad977261
-0,       2208,       2208,        0,      968, 0x0d04ba51
-0,       2250,       2250,        0,     1140, 0x737f3543
-0,       2291,       2291,        0,     1119, 0x3c050388
-0,       2333,       2333,        0,     1078, 0xeac8d981
-0,       2375,       2375,        0,     1113, 0xebfa0314
-0,       2416,       2416,        0,     1229, 0x95dc3cb5
-0,       2458,       2458,        0,     1311, 0x8a6f5bda
-0,       2500,       2500,        0,     1270, 0x2e66540a
-0,       2541,       2541,        0,     1408, 0x5f489779
-0,       2583,       2583,        0,     1359, 0x8bd085f5
-0,       2625,       2625,        0,     1428, 0xef9ba480
-0,       2666,       2666,        0,     1179, 0x5bb221a8
-0,       2708,       2708,        0,     1108, 0x9a6019a8
-0,       2750,       2750,        0,     1205, 0xccba4d22
-0,       2791,       2791,        0,     1306, 0xde708c19
-0,       2833,       2833,        0,     1724, 0xa70b521e
-0,       2875,       2875,       41,     1336, 0xdf3974b9
-0,       2916,       2916,       41,     1259, 0x1f6b4307
-0,       2958,       2958,       41,     1194, 0x635f5a43
-0,       3000,       3000,       41,     1183, 0x1dd47115
-0,       3041,       3041,       41,     1126, 0x5bac3cc8
-0,       3083,       3083,       41,     1360, 0x1fe2d981
-0,       3125,       3125,       41,     1261, 0x34288acb
-0,       3166,       3166,       41,     1250, 0x26bd72b3
-0,       3208,       3208,       41,     1147, 0x02e81ba0
-0,       3250,       3250,       41,     1368, 0xb8146962
-0,       3291,       3291,       41,     1377, 0xf7b6ce65
-0,       3333,       3333,       41,     1396, 0x88467dee
-0,       3375,       3375,       41,     1408, 0x5585c25c
-0,       3416,       3416,       41,     1551, 0x42002c8d
-0,       3458,       3458,       41,     1524, 0xbcb609e3
+0,       2208,       2208,        0,      968, 0x0d04ba51, F=0x0
+0,       2250,       2250,        0,     1140, 0x737f3543, F=0x0
+0,       2291,       2291,        0,     1119, 0x3c050388, F=0x0
+0,       2333,       2333,        0,     1078, 0xeac8d981, F=0x0
+0,       2375,       2375,        0,     1113, 0xebfa0314, F=0x0
+0,       2416,       2416,        0,     1229, 0x95dc3cb5, F=0x0
+0,       2458,       2458,        0,     1311, 0x8a6f5bda, F=0x0
+0,       2500,       2500,        0,     1270, 0x2e66540a, F=0x0
+0,       2541,       2541,        0,     1408, 0x5f489779, F=0x0
+0,       2583,       2583,        0,     1359, 0x8bd085f5, F=0x0
+0,       2625,       2625,        0,     1428, 0xef9ba480, F=0x0
+0,       2666,       2666,        0,     1179, 0x5bb221a8, F=0x0
+0,       2708,       2708,        0,     1108, 0x9a6019a8, F=0x0
+0,       2750,       2750,        0,     1205, 0xccba4d22, F=0x0
+0,       2791,       2791,        0,     1306, 0xde708c19, F=0x0
+0,       2833,       2833,        0,     1724, 0xa70b521e, F=0x0
+0,       2875,       2875,       41,     1336, 0xdf3974b9, F=0x0
+0,       2916,       2916,       41,     1259, 0x1f6b4307, F=0x0
+0,       2958,       2958,       41,     1194, 0x635f5a43, F=0x0
+0,       3000,       3000,       41,     1183, 0x1dd47115, F=0x0
+0,       3041,       3041,       41,     1126, 0x5bac3cc8, F=0x0
+0,       3083,       3083,       41,     1360, 0x1fe2d981, F=0x0
+0,       3125,       3125,       41,     1261, 0x34288acb, F=0x0
+0,       3166,       3166,       41,     1250, 0x26bd72b3, F=0x0
+0,       3208,       3208,       41,     1147, 0x02e81ba0, F=0x0
+0,       3250,       3250,       41,     1368, 0xb8146962, F=0x0
+0,       3291,       3291,       41,     1377, 0xf7b6ce65, F=0x0
+0,       3333,       3333,       41,     1396, 0x88467dee, F=0x0
+0,       3375,       3375,       41,     1408, 0x5585c25c, F=0x0
+0,       3416,       3416,       41,     1551, 0x42002c8d, F=0x0
+0,       3458,       3458,       41,     1524, 0xbcb609e3, F=0x0
 1,       3482,       3482,        0,     1088, 0xdce57471
-0,       3500,       3500,       41,     1554, 0x3d740564
-0,       3541,       3541,       41,     1467, 0xc349f2d7
-0,       3583,       3583,       41,     1066, 0xb7401462
-0,       3625,       3625,       41,     1502, 0x3ee602ed
-0,       3666,       3666,       41,     1148, 0xba463637
-0,       3708,       3708,       41,     1351, 0x5e85ae79
-0,       3750,       3750,       41,     1187, 0xed8d6055
-0,       3791,       3791,       41,     1200, 0x64185be6
-0,       3833,       3833,       41,     1175, 0x12ad3c1e
-0,       3875,       3875,       41,     1179, 0x7e034570
-0,       3916,       3916,       41,     1136, 0x5c633c51
+0,       3500,       3500,       41,     1554, 0x3d740564, F=0x0
+0,       3541,       3541,       41,     1467, 0xc349f2d7, F=0x0
+0,       3583,       3583,       41,     1066, 0xb7401462, F=0x0
+0,       3625,       3625,       41,     1502, 0x3ee602ed, F=0x0
+0,       3666,       3666,       41,     1148, 0xba463637, F=0x0
+0,       3708,       3708,       41,     1351, 0x5e85ae79, F=0x0
+0,       3750,       3750,       41,     1187, 0xed8d6055, F=0x0
+0,       3791,       3791,       41,     1200, 0x64185be6, F=0x0
+0,       3833,       3833,       41,     1175, 0x12ad3c1e, F=0x0
+0,       3875,       3875,       41,     1179, 0x7e034570, F=0x0
+0,       3916,       3916,       41,     1136, 0x5c633c51, F=0x0
 1,       3918,       3918,        0,     1088, 0xf3887977
-0,       3958,       3958,       41,     1064, 0x5eb51d89
-0,       4000,       4000,       41,      953, 0xe148bbdd
-0,       4041,       4041,       41,      989, 0x901ec306
-0,       4083,       4083,       41,     1030, 0x680de26f
-0,       4125,       4125,       41,     1078, 0x86e0ee43
-0,       4166,       4166,       41,     1232, 0x98546a86
-0,       4208,       4208,       41,     1164, 0x93305074
-0,       4250,       4250,       41,     1348, 0x27cfa91b
-0,       4291,       4291,       41,     1417, 0x2312d70e
-0,       4333,       4333,       41,     1285, 0x46ca4cca
+0,       3958,       3958,       41,     1064, 0x5eb51d89, F=0x0
+0,       4000,       4000,       41,      953, 0xe148bbdd, F=0x0
+0,       4041,       4041,       41,      989, 0x901ec306, F=0x0
+0,       4083,       4083,       41,     1030, 0x680de26f, F=0x0
+0,       4125,       4125,       41,     1078, 0x86e0ee43, F=0x0
+0,       4166,       4166,       41,     1232, 0x98546a86, F=0x0
+0,       4208,       4208,       41,     1164, 0x93305074, F=0x0
+0,       4250,       4250,       41,     1348, 0x27cfa91b, F=0x0
+0,       4291,       4291,       41,     1417, 0x2312d70e, F=0x0
+0,       4333,       4333,       41,     1285, 0x46ca4cca, F=0x0
 1,       4353,       4353,        0,     1088, 0x1d6c8ed2
-0,       4375,       4375,       41,     1037, 0xcf09dd3d
-0,       4416,       4416,       41,     1005, 0xe780cf1f
-0,       4458,       4458,       41,      890, 0x8b1d8c1b
-0,       4500,       4500,       41,     1023, 0xd1dbd506
-0,       4541,       4541,       41,      803, 0x935e775e
-0,       4583,       4583,       41,     1035, 0x6a220483
-0,       4625,       4625,       41,      466, 0xd88bb237
+0,       4375,       4375,       41,     1037, 0xcf09dd3d, F=0x0
+0,       4416,       4416,       41,     1005, 0xe780cf1f, F=0x0
+0,       4458,       4458,       41,      890, 0x8b1d8c1b, F=0x0
+0,       4500,       4500,       41,     1023, 0xd1dbd506, F=0x0
+0,       4541,       4541,       41,      803, 0x935e775e, F=0x0
+0,       4583,       4583,       41,     1035, 0x6a220483, F=0x0
+0,       4625,       4625,       41,      466, 0xd88bb237, F=0x0
 1,       4789,       4789,        0,     1088, 0x09115bae
-0,       4916,       4916,       41,      945, 0x8f2eb1ec
+0,       4916,       4916,       41,      945, 0x8f2eb1ec, F=0x0
 0,       4958,       4958,       41,     1190, 0x4c451c1b
-0,       5000,       5000,       41,     1811, 0x727c52cb
-0,       5041,       5041,       41,     1552, 0x73f82bff
-0,       5083,       5083,       41,     1544, 0xa7241ece
-0,       5125,       5125,       41,     1707, 0x3d1a6464
-0,       5166,       5166,       41,     1103, 0x06b22710
-0,       5208,       5208,       41,     1122, 0x656725b8
+0,       5000,       5000,       41,     1811, 0x727c52cb, F=0x0
+0,       5041,       5041,       41,     1552, 0x73f82bff, F=0x0
+0,       5083,       5083,       41,     1544, 0xa7241ece, F=0x0
+0,       5125,       5125,       41,     1707, 0x3d1a6464, F=0x0
+0,       5166,       5166,       41,     1103, 0x06b22710, F=0x0
+0,       5208,       5208,       41,     1122, 0x656725b8, F=0x0
 1,       5224,       5224,        0,     1088, 0x0c8b9372
-0,       5250,       5250,       41,     1150, 0xf9674678
-0,       5291,       5291,       41,     1438, 0x03fac426
-0,       5333,       5333,       41,     1623, 0x7adb1321
-0,       5375,       5375,       41,     1677, 0x0b9a3e62
-0,       5416,       5416,       41,     1124, 0x769c0ea2
-0,       5458,       5458,       41,     1221, 0xd942409f
-0,       5500,       5500,       41,     1698, 0xd7ca3fe3
-0,       5541,       5541,       41,     1262, 0xb994692f
-0,       5583,       5583,       41,     2097, 0xf4eb663f
-0,       5625,       5625,       41,     1251, 0xfd4f633a
+0,       5250,       5250,       41,     1150, 0xf9674678, F=0x0
+0,       5291,       5291,       41,     1438, 0x03fac426, F=0x0
+0,       5333,       5333,       41,     1623, 0x7adb1321, F=0x0
+0,       5375,       5375,       41,     1677, 0x0b9a3e62, F=0x0
+0,       5416,       5416,       41,     1124, 0x769c0ea2, F=0x0
+0,       5458,       5458,       41,     1221, 0xd942409f, F=0x0
+0,       5500,       5500,       41,     1698, 0xd7ca3fe3, F=0x0
+0,       5541,       5541,       41,     1262, 0xb994692f, F=0x0
+0,       5583,       5583,       41,     2097, 0xf4eb663f, F=0x0
+0,       5625,       5625,       41,     1251, 0xfd4f633a, F=0x0
 1,       5659,       5659,        0,     1088, 0x75a82540
-0,       5666,       5666,       41,     1633, 0xb7e1290e
-0,       5708,       5708,       41,     1739, 0xecd18c38
-0,       5750,       5750,       41,     1132, 0xc83e1828
-0,       5791,       5791,       41,      825, 0xdd02867c
-0,       5833,       5833,       41,      903, 0x349ba205
-0,       5875,       5875,       41,     1013, 0x1366ec2a
-0,       5916,       5916,       41,     1340, 0xeaa2a231
-0,       5958,       5958,       41,     1102, 0x82de2889
-0,       6000,       6000,       41,     1834, 0x59b99b92
+0,       5666,       5666,       41,     1633, 0xb7e1290e, F=0x0
+0,       5708,       5708,       41,     1739, 0xecd18c38, F=0x0
+0,       5750,       5750,       41,     1132, 0xc83e1828, F=0x0
+0,       5791,       5791,       41,      825, 0xdd02867c, F=0x0
+0,       5833,       5833,       41,      903, 0x349ba205, F=0x0
+0,       5875,       5875,       41,     1013, 0x1366ec2a, F=0x0
+0,       5916,       5916,       41,     1340, 0xeaa2a231, F=0x0
+0,       5958,       5958,       41,     1102, 0x82de2889, F=0x0
+0,       6000,       6000,       41,     1834, 0x59b99b92, F=0x0
 1,       6008,       6008,        0,     1088, 0x690312b0
-0,       6041,       6041,       41,     1332, 0x0610813a
-0,       6083,       6083,       41,     1275, 0x5b0d7be7
-0,       6125,       6125,       41,     1376, 0xd915b0fe
-0,       6166,       6166,       41,     1417, 0x8606b34a
-0,       6208,       6208,       41,     1360, 0x3bcd93d3
-0,       6250,       6250,       41,     1330, 0xd0439c93
-0,       6291,       6291,       41,     1562, 0xb2560a09
+0,       6041,       6041,       41,     1332, 0x0610813a, F=0x0
+0,       6083,       6083,       41,     1275, 0x5b0d7be7, F=0x0
+0,       6125,       6125,       41,     1376, 0xd915b0fe, F=0x0
+0,       6166,       6166,       41,     1417, 0x8606b34a, F=0x0
+0,       6208,       6208,       41,     1360, 0x3bcd93d3, F=0x0
+0,       6250,       6250,       41,     1330, 0xd0439c93, F=0x0
+0,       6291,       6291,       41,     1562, 0xb2560a09, F=0x0
 1,       6312,       6312,        0,     1088, 0x76d50ff3
-0,       6333,       6333,       41,     1376, 0x4f9eb447
-0,       6375,       6375,       41,     1405, 0x85d3b084
-0,       6416,       6416,       41,     1344, 0xcdbda2ae
-0,       6458,       6458,       41,     1313, 0xe3067b35
-0,       6500,       6500,       41,     1459, 0xf9d2c56f
-0,       6541,       6541,       41,     1275, 0xf5536d81
-0,       6583,       6583,       41,     1209, 0x3b5b4ea5
+0,       6333,       6333,       41,     1376, 0x4f9eb447, F=0x0
+0,       6375,       6375,       41,     1405, 0x85d3b084, F=0x0
+0,       6416,       6416,       41,     1344, 0xcdbda2ae, F=0x0
+0,       6458,       6458,       41,     1313, 0xe3067b35, F=0x0
+0,       6500,       6500,       41,     1459, 0xf9d2c56f, F=0x0
+0,       6541,       6541,       41,     1275, 0xf5536d81, F=0x0
+0,       6583,       6583,       41,     1209, 0x3b5b4ea5, F=0x0
 1,       6595,       6595,        0,     1088, 0x8766276f
-0,       6625,       6625,       41,     1352, 0x7b199d28
-0,       6666,       6666,       41,     1349, 0x02adaaf3
-0,       6708,       6708,       41,     1464, 0x20d7cfd2
-0,       6750,       6750,       41,     1377, 0x78e0b1f4
-0,       6791,       6791,       41,      289, 0x1f2e9246
+0,       6625,       6625,       41,     1352, 0x7b199d28, F=0x0
+0,       6666,       6666,       41,     1349, 0x02adaaf3, F=0x0
+0,       6708,       6708,       41,     1464, 0x20d7cfd2, F=0x0
+0,       6750,       6750,       41,     1377, 0x78e0b1f4, F=0x0
+0,       6791,       6791,       41,      289, 0x1f2e9246, F=0x0
 1,       6878,       6878,        0,     1088, 0x678f20fd
 1,       7161,       7161,        0,     1088, 0x718afa20
 1,       7444,       7444,        0,     1088, 0x758f0939
diff --git a/tests/ref/fate/wtv-demux b/tests/ref/fate/wtv-demux
index fadc4ef..362c55b 100644
--- a/tests/ref/fate/wtv-demux
+++ b/tests/ref/fate/wtv-demux
@@ -38,104 +38,104 @@
 0,    8286442,    9486442,   400000,    41980, 0xd4920915
 1,    8399998,    8399998,   240000,      576, 0x05131eb0
 1,    8639998,    8639998,   240000,      576, 0x78151c22
-0,    8686442,    8686442,   400000,     7228, 0x1b141fa3
+0,    8686442,    8686442,   400000,     7228, 0x1b141fa3, F=0x0
 1,    8879998,    8879998,   240000,      576, 0x31771239
-0,    9086331,    9086331,   400000,     7492, 0x1a47f3e4
+0,    9086331,    9086331,   400000,     7492, 0x1a47f3e4, F=0x0
 1,    9119998,    9119998,   240000,      576, 0x3ce4097c
 1,    9359998,    9359998,   240000,      576, 0x180e15f4
-0,    9486442,   10686331,   400000,    25068, 0xcb70a744
+0,    9486442,   10686331,   400000,    25068, 0xcb70a744, F=0x0
 1,    9599998,    9599998,   240000,      576, 0x30db0604
 1,    9839998,    9839998,   240000,      576, 0x9b290284
-0,    9886442,    9886442,   400000,     7212, 0x0ab9f558
+0,    9886442,    9886442,   400000,     7212, 0x0ab9f558, F=0x0
 1,   10079998,   10079998,   240000,      576, 0xcf340753
-0,   10286442,   10286442,   400000,     7612, 0xa93054f0
+0,   10286442,   10286442,   400000,     7612, 0xa93054f0, F=0x0
 1,   10319998,   10319998,   240000,      576, 0xdaa41457
 1,   10559998,   10559998,   240000,      576, 0x34d310a2
-0,   10686331,   11886331,   400000,    22868, 0xa77db64a
+0,   10686331,   11886331,   400000,    22868, 0xa77db64a, F=0x0
 1,   10799998,   10799998,   240000,      576, 0x58b31010
 1,   11039998,   11039998,   240000,      576, 0x19610f54
-0,   11086442,   11086442,   400000,     6260, 0x6cf76411
+0,   11086442,   11086442,   400000,     6260, 0x6cf76411, F=0x0
 1,   11279998,   11279998,   240000,      576, 0x17762352
-0,   11486331,   11486331,   400000,     6156, 0xe168394b
+0,   11486331,   11486331,   400000,     6156, 0xe168394b, F=0x0
 1,   11519998,   11519998,   240000,      576, 0x1fea1448
 1,   11759998,   11759998,   240000,      576, 0x55840a01
-0,   11886331,   13086442,   400000,    23364, 0x53164f1e
+0,   11886331,   13086442,   400000,    23364, 0x53164f1e, F=0x0
 1,   11999998,   11999998,   240000,      576, 0x6c9c24ce
 1,   12239998,   12239998,   240000,      576, 0x955f1e97
-0,   12286442,   12286442,   400000,     6708, 0x89877269
+0,   12286442,   12286442,   400000,     6708, 0x89877269, F=0x0
 1,   12479998,   12479998,   240000,      576, 0x2827134f
-0,   12686442,   12686442,   400000,     6908, 0x8d62a249
+0,   12686442,   12686442,   400000,     6908, 0x8d62a249, F=0x0
 1,   12719998,   12719998,   240000,      576, 0x34a01c29
 1,   12959998,   12959998,   240000,      576, 0x7d351e52
 0,   13086442,   14286442,   400000,    38156, 0xec41f682
 1,   13199998,   13199998,   240000,      576, 0x00c91d9e
 1,   13439998,   13439998,   240000,      576, 0x57ea1a97
-0,   13486331,   13486331,   400000,     5764, 0xcc04534b
+0,   13486331,   13486331,   400000,     5764, 0xcc04534b, F=0x0
 1,   13679998,   13679998,   240000,      576, 0xef3a1c74
-0,   13886331,   13886331,   400000,     5388, 0xb8a1c3c5
+0,   13886331,   13886331,   400000,     5388, 0xb8a1c3c5, F=0x0
 1,   13919998,   13919998,   240000,      576, 0x11fc217d
 1,   14159998,   14159998,   240000,      576, 0x59ce20e5
-0,   14286442,   15486331,   400000,    16764, 0x59460d96
+0,   14286442,   15486331,   400000,    16764, 0x59460d96, F=0x0
 1,   14399998,   14399998,   240000,      576, 0xaafc1dbf
 1,   14639998,   14639998,   240000,      576, 0xdd941609
-0,   14686331,   14686331,   400000,     5548, 0x5c91e93d
+0,   14686331,   14686331,   400000,     5548, 0x5c91e93d, F=0x0
 1,   14879998,   14879998,   240000,      576, 0x900420b0
-0,   15086331,   15086331,   400000,     5652, 0x5e321aed
+0,   15086331,   15086331,   400000,     5652, 0x5e321aed, F=0x0
 1,   15119998,   15119998,   240000,      576, 0x5f4f1aa1
 1,   15359998,   15359998,   240000,      576, 0x7d7e18de
-0,   15486331,   16686331,   400000,    15564, 0xefdf5080
+0,   15486331,   16686331,   400000,    15564, 0xefdf5080, F=0x0
 1,   15599998,   15599998,   240000,      576, 0x986c0d9d
 1,   15839998,   15839998,   240000,      576, 0xcb4c21c0
-0,   15886331,   15886331,   400000,     6492, 0xd1d5c5f8
+0,   15886331,   15886331,   400000,     6492, 0xd1d5c5f8, F=0x0
 1,   16079998,   16079998,   240000,      576, 0xbcfb1e8b
-0,   16286331,   16286331,   400000,     5604, 0xf9472b44
+0,   16286331,   16286331,   400000,     5604, 0xf9472b44, F=0x0
 1,   16319998,   16319998,   240000,      576, 0xcb541b4c
 1,   16559998,   16559998,   240000,      576, 0x980426e9
-0,   16686331,   17886331,   400000,    17924, 0x45815b7b
+0,   16686331,   17886331,   400000,    17924, 0x45815b7b, F=0x0
 1,   16799998,   16799998,   240000,      576, 0x09d00aa0
 1,   17039998,   17039998,   240000,      576, 0xad591374
-0,   17086442,   17086442,   400000,     5020, 0x3cc5e554
+0,   17086442,   17086442,   400000,     5020, 0x3cc5e554, F=0x0
 1,   17279998,   17279998,   240000,      576, 0x97bf1461
-0,   17486442,   17486442,   400000,     5276, 0xa0554c12
+0,   17486442,   17486442,   400000,     5276, 0xa0554c12, F=0x0
 1,   17519998,   17519998,   240000,      576, 0xdc871cc4
 1,   17759998,   17759998,   240000,      576, 0x56781896
 0,   17886331,   19086442,   400000,    31460, 0x5765eb5f
 1,   17999998,   17999998,   240000,      576, 0xc77714e3
 1,   18239998,   18239998,   240000,      576, 0x280e18d4
-0,   18286331,   18286331,   400000,     4972, 0x91adbab7
+0,   18286331,   18286331,   400000,     4972, 0x91adbab7, F=0x0
 1,   18479998,   18479998,   240000,      576, 0xbc0d2302
-0,   18686442,   18686442,   400000,     5580, 0xfea707cb
+0,   18686442,   18686442,   400000,     5580, 0xfea707cb, F=0x0
 1,   18719998,   18719998,   240000,      576, 0x79191384
 1,   18959998,   18959998,   240000,      576, 0x65481c97
-0,   19086442,   20286331,   400000,    17412, 0x0afe4d27
+0,   19086442,   20286331,   400000,    17412, 0x0afe4d27, F=0x0
 1,   19199998,   19199998,   240000,      576, 0xc94d227d
 1,   19439998,   19439998,   240000,      576, 0xa68a1f14
-0,   19486442,   19486442,   400000,     5236, 0x03f55309
+0,   19486442,   19486442,   400000,     5236, 0x03f55309, F=0x0
 1,   19679998,   19679998,   240000,      576, 0x6af11a5c
-0,   19886331,   19886331,   400000,     4924, 0x558e753c
+0,   19886331,   19886331,   400000,     4924, 0x558e753c, F=0x0
 1,   19919998,   19919998,   240000,      576, 0x4d1019ef
 1,   20159998,   20159998,   240000,      576, 0x3b1b17b5
-0,   20286331,   21486331,   400000,    15396, 0xf145d121
+0,   20286331,   21486331,   400000,    15396, 0xf145d121, F=0x0
 1,   20399998,   20399998,   240000,      576, 0xcdd8159f
 1,   20639998,   20639998,   240000,      576, 0x97cd1d06
-0,   20686331,   20686331,   400000,     4708, 0x43066a92
+0,   20686331,   20686331,   400000,     4708, 0x43066a92, F=0x0
 1,   20879998,   20879998,   240000,      576, 0x5d1b1123
-0,   21086442,   21086442,   400000,     4332, 0x9e22bcba
+0,   21086442,   21086442,   400000,     4332, 0x9e22bcba, F=0x0
 1,   21119998,   21119998,   240000,      576, 0x888d0cb0
 1,   21359998,   21359998,   240000,      576, 0x556e1dad
-0,   21486331,   22686442,   400000,    12876, 0x46ff9ef4
+0,   21486331,   22686442,   400000,    12876, 0x46ff9ef4, F=0x0
 1,   21599998,   21599998,   240000,      576, 0xf7af0bce
 1,   21839998,   21839998,   240000,      576, 0xb5da160a
-0,   21886442,   21886442,   400000,     5940, 0x27cba62e
+0,   21886442,   21886442,   400000,     5940, 0x27cba62e, F=0x0
 1,   22079998,   22079998,   240000,      576, 0x4a8d0e98
-0,   22286442,   22286442,   400000,     6124, 0x6bab0a6d
+0,   22286442,   22286442,   400000,     6124, 0x6bab0a6d, F=0x0
 1,   22319998,   22319998,   240000,      576, 0x183b1c7e
 1,   22559998,   22559998,   240000,      576, 0xc47120e6
 0,   22686442,   23886442,   400000,    36428, 0x942f9648
 1,   22799998,   22799998,   240000,      576, 0xb1f31346
-0,   23086331,   23086331,   400000,     6660, 0x545a0db7
-0,   23486331,   23486331,   400000,     6780, 0x2d1d4189
-0,   23886442,   25086331,   400000,    16460, 0x7c3b3ca4
-0,   24286442,   24286442,   400000,     6724, 0x8538cc6f
-0,   24686442,   24686442,   400000,     7068, 0x69574fd0
-0,   25086331,   26286331,   400000,    19552, 0xf230e854
+0,   23086331,   23086331,   400000,     6660, 0x545a0db7, F=0x0
+0,   23486331,   23486331,   400000,     6780, 0x2d1d4189, F=0x0
+0,   23886442,   25086331,   400000,    16460, 0x7c3b3ca4, F=0x0
+0,   24286442,   24286442,   400000,     6724, 0x8538cc6f, F=0x0
+0,   24686442,   24686442,   400000,     7068, 0x69574fd0, F=0x0
+0,   25086331,   26286331,   400000,    19552, 0xf230e854, F=0x0
diff --git a/tests/ref/fate/xface b/tests/ref/fate/xface
new file mode 100644
index 0000000..7f1f1e6
--- /dev/null
+++ b/tests/ref/fate/xface
@@ -0,0 +1,2 @@
+#tb 0: 1/25
+0,          0,          0,        1,      288, 0x87ddaef8
diff --git a/tests/ref/fate/xmv-demux b/tests/ref/fate/xmv-demux
index 841ba9c..49f22c9 100644
--- a/tests/ref/fate/xmv-demux
+++ b/tests/ref/fate/xmv-demux
@@ -7,32 +7,32 @@
 1,        249,        249,       83,     5976, 0x4ea056f4
 1,        332,        332,       83,     5976, 0xda772d8d
 1,        415,        415,       83,     5976, 0xafacf7c9
-0,        640,        640,        0,      108, 0x06713c96
-0,        680,        680,        0,      952, 0xd306df7e
-0,        720,        720,        0,     2312, 0xaf316585
+0,        640,        640,        0,      108, 0x06713c96, F=0x0
+0,        680,        680,        0,      952, 0xd306df7e, F=0x0
+0,        720,        720,        0,     2312, 0xaf316585, F=0x0
 1,        498,        498,       83,     5976, 0xdeb003f4
-0,        760,        760,        0,     3872, 0xfc1c527c
-0,        800,        800,        0,       20, 0xaffc0edd
-0,        840,        840,        0,     6600, 0xe1b66c7f
+0,        760,        760,        0,     3872, 0xfc1c527c, F=0x0
+0,        800,        800,        0,       20, 0xaffc0edd, F=0x0
+0,        840,        840,        0,     6600, 0xe1b66c7f, F=0x0
 1,        581,        581,       28,     2016, 0xa7380d36
-0,        880,        880,        0,     6868, 0xd5b3f631
+0,        880,        880,        0,     6868, 0xd5b3f631, F=0x0
 1,        609,        609,       28,     2016, 0xbc090bac
-0,        920,        920,        0,     8420, 0xf70ee33b
+0,        920,        920,        0,     8420, 0xf70ee33b, F=0x0
 1,        637,        637,       28,     2016, 0x6f8c164c
-0,        960,        960,        0,    13144, 0x9a54ef39
+0,        960,        960,        0,    13144, 0x9a54ef39, F=0x0
 1,        665,        665,       28,     2016, 0x13b80e28
-0,       1000,       1000,        0,     6340, 0xe55bf555
+0,       1000,       1000,        0,     6340, 0xe55bf555, F=0x0
 1,        693,        693,       28,     2016, 0xd40ff863
-0,       1040,       1040,        0,     3736, 0x0b23f89f
+0,       1040,       1040,        0,     3736, 0x0b23f89f, F=0x0
 1,        721,        721,       28,     2016, 0x4d530ed7
-0,       1080,       1080,        0,     2624, 0x79e2e451
+0,       1080,       1080,        0,     2624, 0x79e2e451, F=0x0
 1,        749,        749,       30,     2160, 0x0fbc37eb
-0,       1120,       1120,        0,     1860, 0x63886f11
+0,       1120,       1120,        0,     1860, 0x63886f11, F=0x0
 1,        779,        779,      192,    13824, 0x82fb2602
-0,       1160,       1160,        0,     1244, 0x74594601
-0,       1200,       1200,        0,      564, 0xf4561dfb
-0,       1240,       1240,        0,       80, 0xbf8e2e30
-0,       1280,       1280,        0,       20, 0xa0990c29
+0,       1160,       1160,        0,     1244, 0x74594601, F=0x0
+0,       1200,       1200,        0,      564, 0xf4561dfb, F=0x0
+0,       1240,       1240,        0,       80, 0xbf8e2e30, F=0x0
+0,       1280,       1280,        0,       20, 0xa0990c29, F=0x0
 1,        971,        971,      192,    13824, 0x08771caf
 1,       1163,       1163,      192,    13824, 0xdf7d4a65
 1,       1355,       1355,      193,    13896, 0x24bf3f47
@@ -40,35 +40,35 @@
 1,       1598,       1598,       50,     3600, 0x8c666fd6
 1,       1648,       1648,       50,     3600, 0x305c6ca1
 1,       1698,       1698,       50,     3600, 0x48b04e1e
-0,       2480,       2480,        0,      104, 0x12413980
-0,       2520,       2520,        0,      796, 0x2e698ed3
+0,       2480,       2480,        0,      104, 0x12413980, F=0x0
+0,       2520,       2520,        0,      796, 0x2e698ed3, F=0x0
 1,       1748,       1748,       50,     3600, 0x8c915935
-0,       2560,       2560,        0,     1808, 0x8b3e6e5e
-0,       2600,       2600,        0,     4712, 0xdbd51737
+0,       2560,       2560,        0,     1808, 0x8b3e6e5e, F=0x0
+0,       2600,       2600,        0,     4712, 0xdbd51737, F=0x0
 1,       1798,       1798,       50,     3600, 0xa8f45e01
-0,       2640,       2640,        0,     5548, 0xee9c831c
-0,       2680,       2680,        0,     6152, 0x9c18ccc1
+0,       2640,       2640,        0,     5548, 0xee9c831c, F=0x0
+0,       2680,       2680,        0,     6152, 0x9c18ccc1, F=0x0
 1,       1848,       1848,       53,     3816, 0xc64cc5ed
-0,       2720,       2720,        0,     6452, 0x7860462a
+0,       2720,       2720,        0,     6452, 0x7860462a, F=0x0
 1,       1901,       1901,       27,     1944, 0x0ac2e3f1
-0,       2760,       2760,        0,     6676, 0xe1b1c9e4
+0,       2760,       2760,        0,     6676, 0xe1b1c9e4, F=0x0
 1,       1928,       1928,       27,     1944, 0x2197dccd
-0,       2800,       2800,        0,    10904, 0x0bded7b7
+0,       2800,       2800,        0,    10904, 0x0bded7b7, F=0x0
 1,       1955,       1955,       27,     1944, 0x0c02e77f
-0,       2840,       2840,        0,    12844, 0xe6d16cff
+0,       2840,       2840,        0,    12844, 0xe6d16cff, F=0x0
 1,       1982,       1982,       27,     1944, 0x675ee06a
-0,       2880,       2880,        0,    10920, 0xe114c46b
+0,       2880,       2880,        0,    10920, 0xe114c46b, F=0x0
 1,       2009,       2009,       30,     2160, 0x0d803a8b
-0,       2920,       2920,        0,     5952, 0xb7464634
+0,       2920,       2920,        0,     5952, 0xb7464634, F=0x0
 1,       2039,       2039,       93,     6696, 0xa7a0dfea
-0,       2960,       2960,        0,     4732, 0x2fa2e36d
-0,       3000,       3000,        0,     2592, 0xf54ddd57
-0,       3040,       3040,        0,     1516, 0x4a1cd4d5
-0,       3080,       3080,        0,      864, 0x49889afc
+0,       2960,       2960,        0,     4732, 0x2fa2e36d, F=0x0
+0,       3000,       3000,        0,     2592, 0xf54ddd57, F=0x0
+0,       3040,       3040,        0,     1516, 0x4a1cd4d5, F=0x0
+0,       3080,       3080,        0,      864, 0x49889afc, F=0x0
 1,       2132,       2132,       93,     6696, 0x59aa3145
-0,       3120,       3120,        0,      468, 0x3932e6a4
-0,       3160,       3160,        0,      116, 0x2b8341e6
-0,       3200,       3200,        0,       16, 0x6a3109cf
+0,       3120,       3120,        0,      468, 0x3932e6a4, F=0x0
+0,       3160,       3160,        0,      116, 0x2b8341e6, F=0x0
+0,       3200,       3200,        0,       16, 0x6a3109cf, F=0x0
 1,       2225,       2225,       93,     6696, 0x69be4d78
 1,       2318,       2318,       93,     6696, 0x64064c67
 1,       2411,       2411,       93,     6696, 0xc8536f98
@@ -80,104 +80,104 @@
 1,       2937,       2937,      123,     8856, 0x19e18797
 1,       3060,       3060,      123,     8856, 0x0a0c7fbd
 1,       3183,       3183,      124,     8928, 0x4a9b2d42
-0,       4640,       4640,        0,      100, 0x45023894
-0,       4680,       4680,        0,      948, 0xa65ed345
-0,       4720,       4720,        0,     2808, 0xd7285746
-0,       4760,       4760,       40,     5372, 0x05794175
+0,       4640,       4640,        0,      100, 0x45023894, F=0x0
+0,       4680,       4680,        0,      948, 0xa65ed345, F=0x0
+0,       4720,       4720,        0,     2808, 0xd7285746, F=0x0
+0,       4760,       4760,       40,     5372, 0x05794175, F=0x0
 1,       3307,       3307,       21,     1512, 0xed8b3f4b
-0,       4800,       4800,       40,    11596, 0x8636eca7
+0,       4800,       4800,       40,    11596, 0x8636eca7, F=0x0
 1,       3328,       3328,       21,     1512, 0xa27d3891
-0,       4840,       4840,       40,    11524, 0xe1f39be3
+0,       4840,       4840,       40,    11524, 0xe1f39be3, F=0x0
 1,       3349,       3349,       21,     1512, 0xb0f13eb6
-0,       4880,       4880,       40,    23392, 0xab053f05
+0,       4880,       4880,       40,    23392, 0xab053f05, F=0x0
 1,       3370,       3370,       23,     1656, 0xe5a98324
-0,       4920,       4920,       40,     4560, 0x03197d07
+0,       4920,       4920,       40,     4560, 0x03197d07, F=0x0
 1,       3393,       3393,       31,     2232, 0x15445433
-0,       4960,       4960,       40,     4440, 0x1cc361a2
+0,       4960,       4960,       40,     4440, 0x1cc361a2, F=0x0
 1,       3424,       3424,       31,     2232, 0x5cb348a9
-0,       5000,       5000,       40,    23688, 0x16030634
+0,       5000,       5000,       40,    23688, 0x16030634, F=0x0
 1,       3455,       3455,       31,     2232, 0xf10347da
-0,       5040,       5040,       40,    16132, 0xf0eca799
+0,       5040,       5040,       40,    16132, 0xf0eca799, F=0x0
 1,       3486,       3486,       34,     2448, 0x3e16a175
-0,       5080,       5080,       40,    29896, 0x0c0988ea
+0,       5080,       5080,       40,    29896, 0x0c0988ea, F=0x0
 1,       3520,       3520,       35,     2520, 0x17e3ca2b
-0,       5120,       5120,       40,    19956, 0x0093aa0b
+0,       5120,       5120,       40,    19956, 0x0093aa0b, F=0x0
 1,       3555,       3555,       27,     1944, 0x35c2de84
-0,       5160,       5160,       40,    16392, 0x8829a9ca
+0,       5160,       5160,       40,    16392, 0x8829a9ca, F=0x0
 1,       3582,       3582,       27,     1944, 0x55b4db40
-0,       5200,       5200,       40,    16772, 0x9a4a546d
+0,       5200,       5200,       40,    16772, 0x9a4a546d, F=0x0
 1,       3609,       3609,       29,     2088, 0xdaae14b2
-0,       5240,       5240,       40,     8920, 0xcd8ca203
+0,       5240,       5240,       40,     8920, 0xcd8ca203, F=0x0
 1,       3638,       3638,       27,     1944, 0x92ccd37f
-0,       5280,       5280,       40,     9632, 0x53c1d37b
+0,       5280,       5280,       40,     9632, 0x53c1d37b, F=0x0
 1,       3665,       3665,       27,     1944, 0x70efede1
-0,       5320,       5320,       40,     8976, 0xfe4da2cc
+0,       5320,       5320,       40,     8976, 0xfe4da2cc, F=0x0
 1,       3692,       3692,       27,     1944, 0x7601d304
-0,       5360,       5360,       40,     6680, 0x35348fe0
+0,       5360,       5360,       40,     6680, 0x35348fe0, F=0x0
 1,       3719,       3719,       27,     1944, 0x3922ebc2
-0,       5400,       5400,       40,     9228, 0xcbf62b0c
+0,       5400,       5400,       40,     9228, 0xcbf62b0c, F=0x0
 1,       3746,       3746,       30,     2160, 0xde462f2e
-0,       5440,       5440,       40,     5108, 0xd1d88511
+0,       5440,       5440,       40,     5108, 0xd1d88511, F=0x0
 1,       3776,       3776,       26,     1872, 0x467ac1d2
-0,       5480,       5480,       40,    10016, 0xaff4b2b2
+0,       5480,       5480,       40,    10016, 0xaff4b2b2, F=0x0
 1,       3802,       3802,       26,     1872, 0xa1e4cd43
-0,       5520,       5520,       40,     7468, 0x23e81ab8
+0,       5520,       5520,       40,     7468, 0x23e81ab8, F=0x0
 1,       3828,       3828,       26,     1872, 0x1dceccc6
-0,       5560,       5560,       40,     4172, 0x253cd05b
+0,       5560,       5560,       40,     4172, 0x253cd05b, F=0x0
 1,       3854,       3854,       26,     1872, 0x2bbad2a5
-0,       5600,       5600,       40,     8188, 0x7ede743f
+0,       5600,       5600,       40,     8188, 0x7ede743f, F=0x0
 1,       3880,       3880,       26,     1872, 0xc603d44d
-0,       5640,       5640,       40,     2884, 0x2dec55a3
+0,       5640,       5640,       40,     2884, 0x2dec55a3, F=0x0
 1,       3906,       3906,       26,     1872, 0x1b4cc261
-0,       5680,       5680,       40,     3900, 0xd0666a18
+0,       5680,       5680,       40,     3900, 0xd0666a18, F=0x0
 1,       3932,       3932,       26,     1872, 0x10edd6cf
-0,       5720,       5720,       40,     2996, 0x9cc99b8c
+0,       5720,       5720,       40,     2996, 0x9cc99b8c, F=0x0
 1,       3958,       3958,       33,     2376, 0xecdb9d61
-0,       5760,       5760,       40,     2156, 0xae612776
+0,       5760,       5760,       40,     2156, 0xae612776, F=0x0
 1,       3991,       3991,       36,     2592, 0x5559eced
-0,       5800,       5800,       40,     3988, 0x0d2c9992
-0,       5840,       5840,       40,     1512, 0x6281fc00
+0,       5800,       5800,       40,     3988, 0x0d2c9992, F=0x0
+0,       5840,       5840,       40,     1512, 0x6281fc00, F=0x0
 1,       4027,       4027,       36,     2592, 0x8848dfc7
-0,       5880,       5880,       40,     6544, 0xb75c2562
+0,       5880,       5880,       40,     6544, 0xb75c2562, F=0x0
 1,       4063,       4063,       36,     2592, 0x4ca2d7da
-0,       5920,       5920,       40,     4108, 0xfb21efc9
+0,       5920,       5920,       40,     4108, 0xfb21efc9, F=0x0
 1,       4099,       4099,       36,     2592, 0x285fd7e6
-0,       5960,       5960,       40,     1096, 0x85922a37
-0,       6000,       6000,       40,     9740, 0xe57d7647
+0,       5960,       5960,       40,     1096, 0x85922a37, F=0x0
+0,       6000,       6000,       40,     9740, 0xe57d7647, F=0x0
 1,       4135,       4135,       36,     2592, 0x2717e404
-0,       6040,       6040,       40,      416, 0x61c2ea02
+0,       6040,       6040,       40,      416, 0x61c2ea02, F=0x0
 1,       4171,       4171,       36,     2592, 0xf106111a
-0,       6080,       6080,       40,      336, 0x1dc5ac1c
+0,       6080,       6080,       40,      336, 0x1dc5ac1c, F=0x0
 1,       4207,       4207,       36,     2592, 0xd7d01119
-0,       6120,       6120,       40,      204, 0x16f57017
+0,       6120,       6120,       40,      204, 0x16f57017, F=0x0
 1,       4243,       4243,       36,     2592, 0x550cfeda
-0,       6160,       6160,       40,      112, 0x78374234
-0,       6200,       6200,       40,       40, 0x6cb21985
+0,       6160,       6160,       40,      112, 0x78374234, F=0x0
+0,       6200,       6200,       40,       40, 0x6cb21985, F=0x0
 1,       4279,       4279,       36,     2592, 0x47ad00c4
 1,       4315,       4315,       36,     2592, 0x39bbf306
 1,       4351,       4351,       45,     3240, 0x69addfce
 1,       4396,       4396,      297,    21384, 0x254f63e0
 1,       4693,       4693,      298,    21456, 0x2f7a9859
-0,       6840,       6840,       40,    14420, 0x53324ca4
-0,       6880,       6880,       40,       40, 0x10971420
+0,       6840,       6840,       40,    14420, 0x53324ca4, F=0x0
+0,       6880,       6880,       40,       40, 0x10971420, F=0x0
 1,       4991,       4991,      521,    37512, 0x6e962928
 1,       5512,       5512,       38,     2736, 0x1dc91c69
 0,       8000,       8000,       40,    24904, 0x15574f7e
 1,       5550,       5550,       38,     2736, 0x023434fd
 1,       5588,       5588,       38,     2736, 0x906f1541
-0,       8160,       8160,       40,     1908, 0xccb2dd3c
+0,       8160,       8160,       40,     1908, 0xccb2dd3c, F=0x0
 1,       5626,       5626,       38,     2736, 0x85a31102
-0,       8200,       8200,       40,     4676, 0xbfa42b7e
+0,       8200,       8200,       40,     4676, 0xbfa42b7e, F=0x0
 1,       5664,       5664,       42,     3024, 0x9296a5f3
-0,       8240,       8240,       40,     3600, 0x87c9dc58
-0,       8280,       8280,       40,     8184, 0x504a8e65
+0,       8240,       8240,       40,     3600, 0x87c9dc58, F=0x0
+0,       8280,       8280,       40,     8184, 0x504a8e65, F=0x0
 1,       5706,       5706,       27,     1944, 0x7bf4dedc
-0,       8320,       8320,       40,     9636, 0x2efb3006
+0,       8320,       8320,       40,     9636, 0x2efb3006, F=0x0
 1,       5733,       5733,       27,     1944, 0x4196c404
 1,       5760,       5760,       27,     1944, 0xcda97c7a
-0,       8360,       8360,       40,     9580, 0x0fb6f4e8
+0,       8360,       8360,       40,     9580, 0x0fb6f4e8, F=0x0
 1,       5787,       5787,       27,     1944, 0x5f4922b2
-0,       8400,       8400,       40,     7840, 0xe996f564
+0,       8400,       8400,       40,     7840, 0xe996f564, F=0x0
 1,       5814,       5814,       29,     2088, 0x37dfc157
-0,       8440,       8440,       40,     4208, 0xe9c2fba2
-0,       8480,       8480,       40,      556, 0x3f1e077c
+0,       8440,       8440,       40,     4208, 0xe9c2fba2, F=0x0
+0,       8480,       8480,       40,      556, 0x3f1e077c, F=0x0
diff --git a/tests/ref/lavf/au b/tests/ref/lavf/au
index 15f2a4b..b9b70a1 100644
--- a/tests/ref/lavf/au
+++ b/tests/ref/lavf/au
@@ -1,3 +1,3 @@
-dbd11f783219485cae32024e47c19dfb *./tests/data/lavf/lavf.au
-90136 ./tests/data/lavf/lavf.au
+dc54f834a23ddc0c086a86f0cef898d7 *./tests/data/lavf/lavf.au
+90144 ./tests/data/lavf/lavf.au
 ./tests/data/lavf/lavf.au CRC=0xf1ae5536
diff --git a/tests/ref/lavf/caf b/tests/ref/lavf/caf
index 972b27c..f2ae9c3 100644
--- a/tests/ref/lavf/caf
+++ b/tests/ref/lavf/caf
@@ -1,3 +1,3 @@
-71e1abdfc59613fe05fca2939f02e02d *./tests/data/lavf/lavf.caf
-90204 ./tests/data/lavf/lavf.caf
+6c97bfc8e455d5fb8b3b45806857a953 *./tests/data/lavf/lavf.caf
+90235 ./tests/data/lavf/lavf.caf
 ./tests/data/lavf/lavf.caf CRC=0xf1ae5536
diff --git a/tests/ref/lavf/ffm b/tests/ref/lavf/ffm
index ce0dcdd..6f67365 100644
--- a/tests/ref/lavf/ffm
+++ b/tests/ref/lavf/ffm
@@ -1,3 +1,3 @@
-e6d8254af2b1ad1f58d60da4d80c6e96 *./tests/data/lavf/lavf.ffm
+d33fae310a7f6db1dc7fb74d1a9e0e6a *./tests/data/lavf/lavf.ffm
 376832 ./tests/data/lavf/lavf.ffm
 ./tests/data/lavf/lavf.ffm CRC=0x5b136bb1
diff --git a/tests/ref/lavf/flm b/tests/ref/lavf/flm
new file mode 100644
index 0000000..59aac92
--- /dev/null
+++ b/tests/ref/lavf/flm
@@ -0,0 +1,3 @@
+ef4783171ebbc38855331c9ead978322 *./tests/data/lavf/lavf.flm
+10137636 ./tests/data/lavf/lavf.flm
+./tests/data/lavf/lavf.flm CRC=0xcdf15757
diff --git a/tests/ref/lavf/gif b/tests/ref/lavf/gif
index 19106ca..41d5018 100644
--- a/tests/ref/lavf/gif
+++ b/tests/ref/lavf/gif
@@ -1,6 +1,6 @@
 e6089fd4ef3b9df44090ab3650bdd810 *./tests/data/lavf/lavf.gif
 2906401 ./tests/data/lavf/lavf.gif
-./tests/data/lavf/lavf.gif CRC=0xe5605ff6
+./tests/data/lavf/lavf.gif CRC=0xbf89a246
 022dc66b5068404e88c618ce79d9eb5f *./tests/data/images/gif/02.gif
 ./tests/data/images/gif/%02d.gif CRC=0x032e0034
 81538 ./tests/data/images/gif/02.gif
diff --git a/tests/ref/lavf/mkv b/tests/ref/lavf/mkv
index 8820300..d92aaa8 100644
--- a/tests/ref/lavf/mkv
+++ b/tests/ref/lavf/mkv
@@ -1,3 +1,3 @@
-796a3bbf2410e55e186367037bda6bb5 *./tests/data/lavf/lavf.mkv
+84dcb326fe85aeeb5768beb44372f248 *./tests/data/lavf/lavf.mkv
 320297 ./tests/data/lavf/lavf.mkv
-./tests/data/lavf/lavf.mkv CRC=0x7065846b
+./tests/data/lavf/lavf.mkv CRC=0x4780846b
diff --git a/tests/ref/lavf/mov b/tests/ref/lavf/mov
index 7a2eed4..4554ea6 100644
--- a/tests/ref/lavf/mov
+++ b/tests/ref/lavf/mov
@@ -1,12 +1,12 @@
-0e5013f259148938ac771186308318db *./tests/data/lavf/lavf.mov
+fcbe7806047914d9751fd9053009df69 *./tests/data/lavf/lavf.mov
 367365 ./tests/data/lavf/lavf.mov
 ./tests/data/lavf/lavf.mov CRC=0xb2f59ab4
-9865100aa9c604d53cc5b4d804f94cdd *./tests/data/lavf/lavf.mov
+72eac0051107a16e41d5263dab640f26 *./tests/data/lavf/lavf.mov
 358455 ./tests/data/lavf/lavf.mov
 ./tests/data/lavf/lavf.mov CRC=0xb2f59ab4
 cbc587335946df1f08d838f48ef396f0 *./tests/data/lavf/lavf.mov
 377613 ./tests/data/lavf/lavf.mov
 ./tests/data/lavf/lavf.mov CRC=0xc882139b
-a42f977ed05f641d8aa5a69fc7291d5b *./tests/data/lavf/lavf.mov
+7c932d24837f46ef57d3e40a61331565 *./tests/data/lavf/lavf.mov
 357837 ./tests/data/lavf/lavf.mov
 ./tests/data/lavf/lavf.mov CRC=0xb2f59ab4
diff --git a/tests/ref/lavf/mxf b/tests/ref/lavf/mxf
index d8aeb4a..b489162 100644
--- a/tests/ref/lavf/mxf
+++ b/tests/ref/lavf/mxf
@@ -1,9 +1,9 @@
-3fb5387504760db6ebbed106fcda5789 *./tests/data/lavf/lavf.mxf
+c53c9f7ee2091405fbe50374f9055679 *./tests/data/lavf/lavf.mxf
 525369 ./tests/data/lavf/lavf.mxf
 ./tests/data/lavf/lavf.mxf CRC=0x17ce1069
-830a8b9ee58781bf654c55905067cdae *./tests/data/lavf/lavf.mxf
+14d0ac1513840b670a785daf4331aca8 *./tests/data/lavf/lavf.mxf
 554553 ./tests/data/lavf/lavf.mxf
-./tests/data/lavf/lavf.mxf CRC=0xa3c0dbc4
-10c6ae1bd97c851728c9abad9dddfa2e *./tests/data/lavf/lavf.mxf
+./tests/data/lavf/lavf.mxf CRC=0x468cdbc4
+5636cee18b0f34a5acb33a8efb9f80c6 *./tests/data/lavf/lavf.mxf
 525369 ./tests/data/lavf/lavf.mxf
 ./tests/data/lavf/lavf.mxf CRC=0x17ce1069
diff --git a/tests/ref/lavf/nut b/tests/ref/lavf/nut
index 81d07d7..72e59e8 100644
--- a/tests/ref/lavf/nut
+++ b/tests/ref/lavf/nut
@@ -1,3 +1,3 @@
-778e33e75965f1cb7b419a253ccd0ed8 *./tests/data/lavf/lavf.nut
-319748 ./tests/data/lavf/lavf.nut
+56c403dd91ae1dd4569348381b2b43a4 *./tests/data/lavf/lavf.nut
+319902 ./tests/data/lavf/lavf.nut
 ./tests/data/lavf/lavf.nut CRC=0x4780846b
diff --git a/tests/ref/lavf/pam b/tests/ref/lavf/pam
index e53132a..d21ccd7 100644
--- a/tests/ref/lavf/pam
+++ b/tests/ref/lavf/pam
@@ -1,3 +1,18 @@
 0dce5565222cf0f8b309467f279aecd2 *./tests/data/images/pam/02.pam
 ./tests/data/images/pam/%02d.pam CRC=0x6da01946
 304191 ./tests/data/images/pam/02.pam
+2ed31ca8d8de560afb3e0fd7a873cde5 *./tests/data/images/pam/02.pam
+./tests/data/images/pam/%02d.pam CRC=0xf07d29cd
+405573 ./tests/data/images/pam/02.pam
+587284e40b78accd54fa92fdb7ca29f4 *./tests/data/images/pam/02.pam
+./tests/data/images/pam/%02d.pam CRC=0x418d2963
+101445 ./tests/data/images/pam/02.pam
+ebd43e97839b2538a79f35757e84ffb0 *./tests/data/images/pam/02.pam
+./tests/data/images/pam/%02d.pam CRC=0x831a2963
+202823 ./tests/data/images/pam/02.pam
+032538f0313b4f240b44a5bef115f5bf *./tests/data/images/pam/02.pam
+./tests/data/images/pam/%02d.pam CRC=0x5984c023
+608321 ./tests/data/images/pam/02.pam
+e8bd9f1830e6a9db201386e96580f869 *./tests/data/images/pam/02.pam
+./tests/data/images/pam/%02d.pam CRC=0x65707c37
+101447 ./tests/data/images/pam/02.pam
diff --git a/tests/ref/lavf/pcx b/tests/ref/lavf/pcx
index bdb2204..6568b60 100644
--- a/tests/ref/lavf/pcx
+++ b/tests/ref/lavf/pcx
@@ -1,3 +1,3 @@
-2df1d747fba23d03b6ff9c91b8b465c9 *./tests/data/images/pcx/02.pcx
+c4faf65ecc812ec8412cc26140c13bd5 *./tests/data/images/pcx/02.pcx
 ./tests/data/images/pcx/%02d.pcx CRC=0x6da01946
 364147 ./tests/data/images/pcx/02.pcx
diff --git a/tests/ref/lavf/png b/tests/ref/lavf/png
index 4e64628..40e7cca 100644
--- a/tests/ref/lavf/png
+++ b/tests/ref/lavf/png
@@ -1,9 +1,9 @@
-c162094e51dc1a3203de43e496086dfd *./tests/data/images/png/02.png
+2af72da4468e61a37c220b25cb28618a *./tests/data/images/png/02.png
 ./tests/data/images/png/%02d.png CRC=0x6da01946
-248612 ./tests/data/images/png/02.png
-63805114b3723490833789277246276f *./tests/data/images/png/02.png
+248633 ./tests/data/images/png/02.png
+62b26c9582ba37dd37b76191338f3770 *./tests/data/images/png/02.png
 ./tests/data/images/png/%02d.png CRC=0x831a2963
-41666 ./tests/data/images/png/02.png
-b4c1f0b706a296ba6e791d436757dc5f *./tests/data/images/png/02.png
+41687 ./tests/data/images/png/02.png
+b4e38244c97debe3f528e7d1adb283ef *./tests/data/images/png/02.png
 ./tests/data/images/png/%02d.png CRC=0x5984c023
-511879 ./tests/data/images/png/02.png
+511900 ./tests/data/images/png/02.png
diff --git a/tests/ref/lavf/smjpeg b/tests/ref/lavf/smjpeg
new file mode 100644
index 0000000..3e7e8ed
--- /dev/null
+++ b/tests/ref/lavf/smjpeg
@@ -0,0 +1,3 @@
+2f6e613e9e257545e1048d57de92ba92 *./tests/data/lavf/lavf.smjpeg
+791463 ./tests/data/lavf/lavf.smjpeg
+./tests/data/lavf/lavf.smjpeg CRC=0x557714ff
diff --git a/tests/ref/lavf/wav b/tests/ref/lavf/wav
index bbbacc3..cc8ec1d 100644
--- a/tests/ref/lavf/wav
+++ b/tests/ref/lavf/wav
@@ -1,3 +1,3 @@
-8854ea97f2d2172383941b001c69228b *./tests/data/lavf/lavf.wav
-90158 ./tests/data/lavf/lavf.wav
+c4afa6eafac5243aa1c202397789ccb8 *./tests/data/lavf/lavf.wav
+90188 ./tests/data/lavf/lavf.wav
 ./tests/data/lavf/lavf.wav CRC=0xf1ae5536
diff --git a/tests/ref/lavf/wtv b/tests/ref/lavf/wtv
index 24cf15d..8f2c2ac 100644
--- a/tests/ref/lavf/wtv
+++ b/tests/ref/lavf/wtv
@@ -1,3 +1,3 @@
-05aff2517b5bd436ec26c736b4b8372c *./tests/data/lavf/lavf.wtv
+345516d3a03fd239c62e5e7257c9f4a2 *./tests/data/lavf/lavf.wtv
 413696 ./tests/data/lavf/lavf.wtv
 ./tests/data/lavf/lavf.wtv CRC=0xcc2dc628
diff --git a/tests/ref/lavf/xwd b/tests/ref/lavf/xwd
index 41846c7..73f859d 100644
--- a/tests/ref/lavf/xwd
+++ b/tests/ref/lavf/xwd
@@ -1,3 +1,24 @@
 50baa5560b7d1aa3188b19c1162bf7dc *./tests/data/images/xwd/02.xwd
 ./tests/data/images/xwd/%02d.xwd CRC=0x6da01946
 304239 ./tests/data/images/xwd/02.xwd
+1cdb43599c956dc8563f1e09fac5df00 *./tests/data/images/xwd/02.xwd
+./tests/data/images/xwd/%02d.xwd CRC=0xf07d29cd
+405615 ./tests/data/images/xwd/02.xwd
+c0866e9e710fce735423594a93bee604 *./tests/data/images/xwd/02.xwd
+./tests/data/images/xwd/%02d.xwd CRC=0x53209216
+202863 ./tests/data/images/xwd/02.xwd
+1300938325d5ac12caa09a43bd58f37c *./tests/data/images/xwd/02.xwd
+./tests/data/images/xwd/%02d.xwd CRC=0x14555d6e
+202863 ./tests/data/images/xwd/02.xwd
+c6f3cb7c45f7238474a89d2ad61a1caf *./tests/data/images/xwd/02.xwd
+./tests/data/images/xwd/%02d.xwd CRC=0xfaafb59b
+104559 ./tests/data/images/xwd/02.xwd
+fe1af954966a40c2cd35fc27094ff823 *./tests/data/images/xwd/02.xwd
+./tests/data/images/xwd/%02d.xwd CRC=0xd69c3a09
+104559 ./tests/data/images/xwd/02.xwd
+9e2f3d455566897692cdfda88ff10112 *./tests/data/images/xwd/02.xwd
+./tests/data/images/xwd/%02d.xwd CRC=0x418d2963
+101487 ./tests/data/images/xwd/02.xwd
+2131b4c41fe35178b0c7d121223af549 *./tests/data/images/xwd/02.xwd
+./tests/data/images/xwd/%02d.xwd CRC=0x0f5aa5cb
+12783 ./tests/data/images/xwd/02.xwd
diff --git a/tests/ref/lavfi/alphaextract_rgb b/tests/ref/lavfi/alphaextract_rgb
index 47334e7..d46b563 100644
--- a/tests/ref/lavfi/alphaextract_rgb
+++ b/tests/ref/lavfi/alphaextract_rgb
@@ -1 +1 @@
-alphaextract_rgb    c855193d17be9c54b67c17984c7d7e0f
+alphaextract_rgb    4a46df014912056534fcab2f45a02279
diff --git a/tests/ref/lavfi/alphaextract_yuv b/tests/ref/lavfi/alphaextract_yuv
index 9f7ea33..32b9ab9 100644
--- a/tests/ref/lavfi/alphaextract_yuv
+++ b/tests/ref/lavfi/alphaextract_yuv
@@ -1 +1 @@
-alphaextract_yuv    8d0b7740687981d2bfc9b5752eae900f
+alphaextract_yuv    591e2d45f96ecfa8cc326eb741456a79
diff --git a/tests/ref/lavfi/alphamerge_rgb b/tests/ref/lavfi/alphamerge_rgb
index 2cf6407..d890fae 100644
--- a/tests/ref/lavfi/alphamerge_rgb
+++ b/tests/ref/lavfi/alphamerge_rgb
@@ -1 +1 @@
-alphamerge_rgb      c855193d17be9c54b67c17984c7d7e0f
+alphamerge_rgb      4a46df014912056534fcab2f45a02279
diff --git a/tests/ref/lavfi/alphamerge_yuv b/tests/ref/lavfi/alphamerge_yuv
index 96a849d..2e58301 100644
--- a/tests/ref/lavfi/alphamerge_yuv
+++ b/tests/ref/lavfi/alphamerge_yuv
@@ -1 +1 @@
-alphamerge_yuv      8d0b7740687981d2bfc9b5752eae900f
+alphamerge_yuv      591e2d45f96ecfa8cc326eb741456a79
diff --git a/tests/ref/lavfi/colormatrix1 b/tests/ref/lavfi/colormatrix1
index b6d361f..9ec093d 100644
--- a/tests/ref/lavfi/colormatrix1
+++ b/tests/ref/lavfi/colormatrix1
@@ -1 +1 @@
-colormatrix1        8ee2d4a88ccffc806ac58bc05c95848b
+colormatrix1        600fef16b66cff4ee76540ff2a8f4480
diff --git a/tests/ref/lavfi/colormatrix2 b/tests/ref/lavfi/colormatrix2
index 0df5a7c..9961bae 100644
--- a/tests/ref/lavfi/colormatrix2
+++ b/tests/ref/lavfi/colormatrix2
@@ -1 +1 @@
-colormatrix2        fa314c32710d9d5d420c12a0f05c3b64
+colormatrix2        e4ba95b7dd5e0862aa5f5e3ddc54bda4
diff --git a/tests/ref/lavfi/crop b/tests/ref/lavfi/crop
index eec4580..dec7f29 100644
--- a/tests/ref/lavfi/crop
+++ b/tests/ref/lavfi/crop
@@ -1 +1 @@
-crop                aa9ae07e171e0734801de21e73eda551
+crop                f7b5236ddf88224188051c7c43503a14
diff --git a/tests/ref/lavfi/crop_scale b/tests/ref/lavfi/crop_scale
index d3704f9..e692a8a 100644
--- a/tests/ref/lavfi/crop_scale
+++ b/tests/ref/lavfi/crop_scale
@@ -1 +1 @@
-crop_scale          363c3faaa2612322ddb977365e1ba374
+crop_scale          c298d61e731a97d0a9600e7fde80b6b4
diff --git a/tests/ref/lavfi/crop_scale_vflip b/tests/ref/lavfi/crop_scale_vflip
index 03a54a7..9a7d326 100644
--- a/tests/ref/lavfi/crop_scale_vflip
+++ b/tests/ref/lavfi/crop_scale_vflip
@@ -1 +1 @@
-crop_scale_vflip    80d00d6f3cf00918df9429233b8e4ed0
+crop_scale_vflip    56b8204e72d0680b139a8d9dd756e332
diff --git a/tests/ref/lavfi/crop_vflip b/tests/ref/lavfi/crop_vflip
index f4a2d37..d6d6bad 100644
--- a/tests/ref/lavfi/crop_vflip
+++ b/tests/ref/lavfi/crop_vflip
@@ -1 +1 @@
-crop_vflip          2e9c8ffd3c457c7a66ffb73b1dc7023f
+crop_vflip          8368eb12fa29acc5826bade961257375
diff --git a/tests/ref/lavfi/drawbox b/tests/ref/lavfi/drawbox
index de2b209..6d2f632 100644
--- a/tests/ref/lavfi/drawbox
+++ b/tests/ref/lavfi/drawbox
@@ -1 +1 @@
-drawbox             f9a92834eb8ad666ccebd9f8197ad59f
+drawbox             b6ff6ecda5611de46ed26db05b49dc72
diff --git a/tests/ref/lavfi/edgedetect b/tests/ref/lavfi/edgedetect
index 45780df..6db0e72 100644
--- a/tests/ref/lavfi/edgedetect
+++ b/tests/ref/lavfi/edgedetect
@@ -1 +1 @@
-edgedetect          fe10771a46091b6573e5dc00dc64eab5
+edgedetect          9d396de52d56b63a77ea6933a323f61f
diff --git a/tests/ref/lavfi/fade b/tests/ref/lavfi/fade
index 59c3512..852abb9 100644
--- a/tests/ref/lavfi/fade
+++ b/tests/ref/lavfi/fade
@@ -1 +1 @@
-fade                4b3006b71829fb86715654216ff92221
+fade                129fb9b266524b0adf102689c366cac8
diff --git a/tests/ref/lavfi/field b/tests/ref/lavfi/field
new file mode 100644
index 0000000..ec50dc1
--- /dev/null
+++ b/tests/ref/lavfi/field
@@ -0,0 +1,101 @@
+0bgr                57434af4bddb691877f2400c704604eb
+0rgb                fc2ba950163aeee98590181e31fcd202
+abgr                3c78d0a72484a1ecd3cae245b9fa988c
+argb                d5057a2be412864719ffb8ba129c1f2c
+bgr0                b33c6b58b0d7bf6ce07d5a2d7c267040
+bgr24               bd6620738df19410d5df5f31e7451709
+bgr444be            219e318b7e0e05050181e71df6b9539d
+bgr444le            8354f2cf5b30de0233d302a74816649d
+bgr48be             22be50bd0aa39f07ad1b1aa57cb741ce
+bgr48le             c4b0f8057b3eac237e9228e83bdc4c66
+bgr4_byte           d4c3304b4b823a130c335379e4d3444d
+bgr555be            c3072da465233dbfc8f61dc7a9766d2c
+bgr555le            be83adcf0b802b061442f0c564fd5987
+bgr565be            bf955b9a035af0e613cf1de249f55f9d
+bgr565le            6dd85cd5e19266c53a54cbcf06d396a7
+bgr8                9669f6974f0fc1c0afa1c7d4df093c0b
+bgra                f7cabae31dd7465dab2203f45db646f8
+gray                66a09b53f7d3f79dcb6096f3ec3740c5
+gray16be            a447af6482b922c9997ac02e5d3535f1
+gray16le            c1dd0db327295898ff282d07f48c105d
+monob               1b7fb7e69a913a0a1c0dffc54e5899ea
+monow               b5d3778a054fc73d515d36f8a6bc693b
+nv12                b3829e9ae2a15349432b7efac4236068
+nv21                963cf5780e07301ff2906bf345b6d0ff
+pal8                bfedafc3bf19c2c12eeb87125833142a
+rgb0                d7481143742ff68abfbac4195edbede0
+rgb24               908d5494062c617bc87149c9daaf2167
+rgb444be            281a8f186a2726c2b31aa7e09e21c865
+rgb444le            93f9ee6265d8ad5e744ab652563f9b78
+rgb48be             0d1d60e1639edb2758ad776cb5583970
+rgb48le             c958b5e98324263e97de2bb528f5bda4
+rgb4_byte           2ec97bf65649e3d47eb6812701544593
+rgb555be            21b9138b229d4065b02d38b5b62f18d1
+rgb555le            0307ee34e562b2fb2b1c6988ae18b2b2
+rgb565be            e8f3ebcbb9a5fff000eca8a312f89782
+rgb565le            53bbd558fb0dcd82f1fad83ea855c3ad
+rgb8                67bfdd4fa88b1ab9be876f42dfc75683
+rgba                d0ebdf1495bc6b7e9d3bfbe2813a9d16
+uyvy422             a6a52504a16f09b8f2ec2405bc8190b5
+yuv410p             3feb55b1e2a385b488c82e808a12587b
+yuv411p             ab3dd8e6cf1452afe2d2e976e4726370
+yuv420p             52e26ad198368e2326bef97cdfa6a2bb
+yuv420p10be         04353bfc21e9b88cd7776e83be756742
+yuv420p10le         3f8e7167dbd12976c6ee516b8c952363
+yuv420p12be         b058ac076c8a5fe522b9fd9b8422054e
+yuv420p12le         ad0bf28e69eeb14eac5d8f9ea8b801f1
+yuv420p14be         c7a435d42f07928332ecb21a7d96ad7a
+yuv420p14le         5507e8db4e58c9517012686a7408996b
+yuv420p16be         5241d64e9fa2fd6590fd23ea0e8a6f90
+yuv420p16le         78da606f761a4fb62fdac05aa5092742
+yuv420p9be          e4bcaf5d6a7030f950b08501327f6175
+yuv420p9le          bbf80e57389578be66d4a7a12335a613
+yuv422p             e461a21995da361b88202339a2ebb879
+yuv422p10be         a3e13070215f5a016ac9bae7e7115417
+yuv422p10le         8e9e3d9adc8fdb8a0a03d79bdc31eefe
+yuv422p12be         6a2aca2ea007534e729203641a82c3a3
+yuv422p12le         aef072b55c6e9df8fd9f398d79f864df
+yuv422p14be         34e5f31372c0fdb4d77ccb7fd7bddb2f
+yuv422p14le         c2c50fbea0cff7edad5c5e907380cbad
+yuv422p16be         55cfed8fa610f82b6625e16871dab235
+yuv422p16le         e2488df0f22987fe7ed12a5ef2adf835
+yuv422p9be          80fcdd7fd9cdd79632104dcc32f78b4b
+yuv422p9le          e0ec9f94c875297ee5d0546274df40e9
+yuv440p             f8e80596babcdb94378ec8bebf2dd46d
+yuv444p             572bad9e12ed53e242658fa613412279
+yuv444p10be         c5304f086afc4624d4fffb66a3cf3cb8
+yuv444p10le         d1754974b936f74028752d49413d30aa
+yuv444p12be         7ec8fd2d7986d6e923dfed572589e643
+yuv444p12le         79d0e287e2171a53cf4f285c0d1e83ef
+yuv444p14be         be021957cd819ca3146f3247138ccae9
+yuv444p14le         bac0b0c70bcf72272d724f0cd1ac411e
+yuv444p16be         3a67c28325978db734ba03b1828c15da
+yuv444p16le         c6dc275a4277fd3c65535253bb298263
+yuv444p9be          f47357cdd775fc399aeab3ae58712fb9
+yuv444p9le          e29799ecb6fac9f5b6d85bc34d248d4b
+yuva420p            82ab09bb7a3a24bf95aeb3fa9d939847
+yuva420p10be        f4559039e99ecf74a58e7063b1e7c5d3
+yuva420p10le        b1eb7df29134936450c2c312ae23a1a4
+yuva420p16be        c580495d34c6ac6e3e3b81772a0f3070
+yuva420p16le        1c49deeafb8f81e9186f3906c9b1a670
+yuva420p9be         a788d7cc6ad67ad52619a08da126569a
+yuva420p9le         c1579a5c015908f26b76480d82f6a648
+yuva422p            c162b37ce05360c47b2a2224ea0748ad
+yuva422p10be        6df70d1018e8c0c9fa377f72f49bf81b
+yuva422p10le        2eb54f20d3e5f180c539d92a75fe66e9
+yuva422p16be        1c61492076be33404894c1d3ec578d87
+yuva422p16le        1c085c9479a57eea35e74c264c947d73
+yuva422p9be         271c6cc091052731373ef5313bc76435
+yuva422p9le         b8c2e963ac35371e8aa6a05d5c252b37
+yuva444p            4a85f1f17e95829cd53c9a28928fd8eb
+yuva444p10be        d312f0d30a88fdd18e992362ea3b5f81
+yuva444p10le        d12aed62a367bc7735e59503a3cf8cc6
+yuva444p16be        ac5c17adeb0ef6730a0de1dbd1d14a1a
+yuva444p16le        41f1a82eb686d7191bdb00206f723247
+yuva444p9be         413d01385a8b008031b2ab3ef0b9eff4
+yuva444p9le         33ede0bd20bfd85489d266ac81d035d6
+yuvj420p            762dc6a157d0bee72da3e3d852668aef
+yuvj422p            8cec955c1c62b00b6798361ef82962b7
+yuvj440p            7b469444994d8b52766ee461bcb795ea
+yuvj444p            b395162325af489c465a3e6a31fbb0e7
+yuyv422             1efb17cd0a48d2e956fd574ea6f412e7
diff --git a/tests/ref/lavfi/hue b/tests/ref/lavfi/hue
new file mode 100644
index 0000000..ab412a7
--- /dev/null
+++ b/tests/ref/lavfi/hue
@@ -0,0 +1 @@
+hue                 faddb090f2eefa663b9539fd67451352
diff --git a/tests/ref/lavfi/idet b/tests/ref/lavfi/idet
new file mode 100644
index 0000000..2c6c2ae
--- /dev/null
+++ b/tests/ref/lavfi/idet
@@ -0,0 +1 @@
+idet                1077e3cb6fc4916b5441dd08cea4c9a8
diff --git a/tests/ref/lavfi/life b/tests/ref/lavfi/life
index e50376b..05713f3 100644
--- a/tests/ref/lavfi/life
+++ b/tests/ref/lavfi/life
@@ -1 +1 @@
-life                a2895f84b84085831040e7c6b6bc5e3e
+life                bc4822aa5d473a8b5efb31fef7aeac86
diff --git a/tests/ref/lavfi/null b/tests/ref/lavfi/null
index 570c932..0b9b9b8 100644
--- a/tests/ref/lavfi/null
+++ b/tests/ref/lavfi/null
@@ -1 +1 @@
-null                489aa94d1a2abf74529ce5aaf812a338
+null                61fffd2d8425759a33ae07e718d0242d
diff --git a/tests/ref/lavfi/overlay b/tests/ref/lavfi/overlay
index 0c48b84..ca70370 100644
--- a/tests/ref/lavfi/overlay
+++ b/tests/ref/lavfi/overlay
@@ -1 +1 @@
-overlay             76e42f5b21f280ba9a0d7daf3f30636c
+overlay             4e85d551db9e56e8faddc1fc70fd6a00
diff --git a/tests/ref/lavfi/pad b/tests/ref/lavfi/pad
index 1be89f2..7a6f61e 100644
--- a/tests/ref/lavfi/pad
+++ b/tests/ref/lavfi/pad
@@ -1 +1 @@
-pad                 b01d899250b32d14d75e3f12095a9da1
+pad                 8122d716097523d0875e2d55b0926105
diff --git a/tests/ref/lavfi/pixfmts_copy b/tests/ref/lavfi/pixfmts_copy
index 85648e3..1171546 100644
--- a/tests/ref/lavfi/pixfmts_copy
+++ b/tests/ref/lavfi/pixfmts_copy
@@ -1,83 +1,101 @@
-0bgr                c60961367c88d4c4fdb74a4a03f18c24
-0rgb                6bbd6fb67c9a830026c834bc4415f2ab
-abgr                1efbf983d9e05945b223e94281ba03dd
-argb                43db1b6f92785cb1741d1a8918be1cd6
-bgr0                5df429190741e396e6374742ec3b5ebb
-bgr24               5a99ab751497ff2308654815bb386ab1
-bgr444be            ad888031403150f784afa4ab5e53fa25
-bgr444le            8bcb29875ef4446f7b40ad5cbe6293c7
-bgr48be             aef991ccc6241fe89501b791b6d1c8a4
-bgr48le             4fe26de32f985c661535592adb854ca0
-bgr4_byte           86ab90dbf28e0d1fcc474c1bc6f3e6ce
-bgr555be            83b5dc82aca5c59214e2821d7c37e101
-bgr555le            5b21fe6b886d105e086ac758c9739ef7
-bgr565be            a03cd63592f7aa85926852e1b0eefb55
-bgr565le            da9f51fd88b00b77a2bdb44092ced6ca
-bgr8                6ee3a027fdf23d9e7641cf9db622e38f
-bgra                571e36479d0bcc63c71d91432a15fd0b
-gray                669860b0e6f48784f1c4edec7d45a23d
-gray16be            c3720d00b935ae76108f6a05825f3ec4
-gray16le            1a4dfbdad429e3a0217dd03978665a60
-monob               cf885ca3ab5c4e79befec8e961b53e6b
-monow               39b7e285f47af4f11003972733a8ec04
-nv12                d0293efcd106022aee6f4696a2492594
-nv21                4b1adad7b2017b2e08a4c686778740bd
-pal8                f3442a379152b41f24a01c35bfe8b0d7
-rgb0                bea4f3e5a1c673fc49b2ed8330ad5698
-rgb24               4f016dcae1677971d5ab8fc5281b4eb1
-rgb444be            5a1f1e3248a7f74ad8a813f88d91e2c7
-rgb444le            db3babb73c538490c56f1dd1b42e32c2
-rgb48be             c157b4bfdaba46851fb409404f0e2b31
-rgb48le             aaeb094dfdd0f0390db94e558fb2e4ec
-rgb4_byte           7d2d7b9383f83902f83f78a49b401e9c
-rgb555be            cc39e0816288e2215e76520c2f3f17d8
-rgb555le            297ca82788b023a3f94677652c091f30
-rgb565be            1b0fc1a80a3913fe0eaf283e68b83d09
-rgb565le            b861ec0fa3c4197dffaef41fc66e7c52
-rgb8                d50a2f3503a8dd876197b604266cf15b
-rgba                090e417705ca0e5187f029eeb394a885
-uyvy422             95b3ca9c609beae6c61fa33a7e6fcfe3
-yuv410p             5652f52e932d718eaad651d06a11ce09
-yuv411p             857a16f561424bcf361784c2e8578d63
-yuv420p             489aa94d1a2abf74529ce5aaf812a338
-yuv420p10be         a1c91b8684cb84a946d78dfa80a6323f
-yuv420p10le         4de5eee1402ae84946a24e3cc4804502
-yuv420p12be         a0f533c65ceabba7ac74deb129435109
-yuv420p12le         fffb48e79346e5a120b12adb87e40980
-yuv420p14be         90f3cd8e808572d3b75fd258652b765f
-yuv420p14le         b41393e500813a4444ac5607c98d7d4b
-yuv420p16be         5b15ffe17c78761138a48cb91e94002e
-yuv420p16le         942b992ad799833754590f9c3371bdae
-yuv420p9be          db3b9b202f8014761e79cff2546536ea
-yuv420p9le          43341ba3955a5c1a1652218d5e466446
-yuv422p             cd9185df12127a7830820862b15d6150
-yuv422p10be         bf0d4d0d6a4d4896650eff08b0a157a4
-yuv422p10le         cab49211123e7337bf8e7b248befacdc
-yuv422p12be         ec8718c7f3a96e4b41d4e69cb1ecce0c
-yuv422p12le         a783156c3ae833b1b16b5f6238d1163b
-yuv422p14be         b58c2198c56330cc19cd61a35e7d799a
-yuv422p14le         7f74d4936577cab0e5e9d6be61a36820
-yuv422p16be         3725aa6136741d558900efc46fa02897
-yuv422p16le         e5613f26cf21e6caa14c55bfa6dbf91f
-yuv422p9be          9c162a559c912dc2a03c0ede9666d201
-yuv422p9le          d778190180fba976dc5e3162b7622d27
-yuv440p             bd74a3dbbba05205fd30e101216a8ee3
-yuv444p             14e06ce6ebba6eccda67d8c5fb0f3695
-yuv444p10be         67bcd450bb1f7de75e51b5e115083f8a
-yuv444p10le         8cd9fe3450e25e1635c5f982bc404f20
-yuv444p12be         2d709d5cbf2c61970e7e6d609fd30f44
-yuv444p12le         8096f6a0f7b6e9b7d60af2cb4d2459fe
-yuv444p14be         9ded64b1f7d37bc170d5c4f4b65c133b
-yuv444p14le         c4981882cca655f0cbc4ed07a33a24c7
-yuv444p16be         06f0ea1a525ddc34116b2c0e3021e5a9
-yuv444p16le         507fc54fe06db5fbd1e36182ec0df4a2
-yuv444p9be          29911d5ab017a4ba12d915dc078ecd87
-yuv444p9le          e55015c87e7a90d87258af0ea5cce0e3
-yuva420p            ff556e3f6cf74f322467860555612c74
-yuva422p            9370ac9fcb59806592f4a35fa8fa28e7
-yuva444p            bb5f5d0c12a9e09ae37ac3bafff907cf
-yuvj420p            295b48eaabd1d239647a20962ab2f1a3
-yuvj422p            cba3eba27031f3ff38ae511c0f7220af
-yuvj440p            53351b202fcda4e03a363e1dcdb808c0
-yuvj444p            b9a2528e0f59939f025c0ae2a885edc8
-yuyv422             1c0ecc295a449472049c9cfa5e8ee4ab
+0bgr                a06d3a7652e4885c65895e0e168aab28
+0rgb                b6b5653d2228cdf2ba3c55a72f2e713f
+abgr                1a147fa04ed70b9a7e67a4c89052f630
+argb                997df0b5c268a0d8f9c611cae4e01e05
+bgr0                218df6dc3eb5094a0c16a8bd18bc3999
+bgr24               d6370f6dc34df2ea66e1718baf74137b
+bgr444be            aba6dfea008ae12c2120a95f54293904
+bgr444le            cfb5401e8f076cc8675e17ed1114a3df
+bgr48be             ab65229b64606f6408cd732b967c0b01
+bgr48le             f1b4e718cadee9bd2978289153ce43de
+bgr4_byte           de96505ef9ad7078f87b4dfdf6fe4b61
+bgr555be            8d5de9e9200d622f27dc73958a85045c
+bgr555le            74eb9837706143a40e26305a16a79369
+bgr565be            13a36d6502be88fc0c2aec05b8d2d501
+bgr565le            ed027571692aecd522aa65a90cc7e09b
+bgr8                71ef789609c746c2e7e4be9dec29062c
+bgra                0364b074268682ea46168742a8239f7d
+gray                1e5e2b8548843a6898eedd9c974c422c
+gray16be            389f4e5a8ab413b3af32767b59ed7f9e
+gray16le            a1f912941247e45b394b9cf4f0e81130
+monob               309b5785a36bd988d17e15d88f4ffad1
+monow               8809a02bc69b58d1114b09ca79ebffad
+nv12                75e90c54d858b993e99f4ee6d2a2a38f
+nv21                8831a3f411015d45fbc5dd191245ba9c
+pal8                13de2a1c3c80cb64d14e2bc4f6f461d0
+rgb0                992f5ad24802cc255edab45c3084db4a
+rgb24               c71ba90f69f15c8275232bb3f62d0ced
+rgb444be            26eaec65d7efd2b0c9c13b47dfd9b241
+rgb444le            5f29863553107110ea817f52151d77b7
+rgb48be             a3bc81c46c21818a989f23104a599ab0
+rgb48le             e87c661ac49aea1f1e93939802883d92
+rgb4_byte           293b1b84f01efd90bde40cb3faffc127
+rgb555be            5229183fa64d4e5c7e3703d8263ee6ae
+rgb555le            c3e9978cb2a4129a5575935e8cbc433a
+rgb565be            bc123b962629ead1a06af0c18cbb6e5f
+rgb565le            20757fafe4756e62d845b2ab4c0b8f93
+rgb8                e01614f5416dcc8ad365ad7a57afc9fb
+rgba                53796fa4c392a1b2659595b6a284f8c4
+uyvy422             3f411f947e3ac8f842c88e717d68bd9a
+yuv410p             7dcf3f4770c8b494290ceacd2c2ce6db
+yuv411p             9461b188dab6f8b90d9a27e353a89f58
+yuv420p             61fffd2d8425759a33ae07e718d0242d
+yuv420p10be         2abf90242cb021cb6fcf9f2c3c92f6a7
+yuv420p10le         180b7e4de684c7225d2fb37614f842cb
+yuv420p12be         256c9e6cfc878a8abf681b30777c0620
+yuv420p12le         8dc8b86c4790da3769d4a62e87608623
+yuv420p14be         8d22756c5d2b9e501924c082bfb22a6c
+yuv420p14le         c9da19d4818bcb119ad6481b75778f7e
+yuv420p16be         4ccdcca6dd6a960f9a3333f0aee095bd
+yuv420p16le         9c5847d9b0de258a10ee906dc47e24ea
+yuv420p9be          fa7ad4f73232aac0e35def62af1e2c39
+yuv420p9le          3720ba1786b56c8f4913e67dddebbb07
+yuv422p             eee223e92f1f2e5ad4186b411ebf5816
+yuv422p10be         80fa87750491dcc3e93d175b64835654
+yuv422p10le         e1640cd315bd96c6b59f7753825a7306
+yuv422p12be         5c6d86e919515d1af71f8004a6252f9e
+yuv422p12le         7f331cadb0ab75d07656d29f47bd8bd9
+yuv422p14be         4f4e186ba683b90fe990cccc4db7e521
+yuv422p14le         d78016c9119b1f1d1c922bd5aaf47732
+yuv422p16be         1f3c216927d17966a009a42def124bba
+yuv422p16le         90adbdffaeea9b09398339c8a1322b02
+yuv422p9be          e46446534dd0821029d3b831c9c1d1b0
+yuv422p9le          520e418a2429f7efee511b7fcbf45ab6
+yuv440p             456d83524b299f2fa1bb988e421554d9
+yuv444p             068bc09d282d18c9fa35c2787943fc2a
+yuv444p10be         9f6e1490080a454243daee9229425e1e
+yuv444p10le         cc183e51041351d9ac06c4df6e8ad5f7
+yuv444p12be         34f63ac6a47ac681016105d3bfb3e118
+yuv444p12le         7964701bfe8d718edf97f6e0002935bd
+yuv444p14be         4ad3a9d52fe9c050150c0f7d2f3cf63d
+yuv444p14le         69575e5a94b978f159c4fdb1a61587b0
+yuv444p16be         4000b12fa88ed0feef182da31c7e6b96
+yuv444p16le         96a857dba8dc6792c58daec872825b32
+yuv444p9be          07727e5c9040b7f0a17d591288ac330d
+yuv444p9le          4d12d20a68dc28618594c96c2ade4ff4
+yuva420p            3a8c5c142e051367c196f95696e0e2c3
+yuva420p10be        1b7c5ec6691498e24676ce6ed97f62f8
+yuva420p10le        ad2d0424033e7acbafa6d58f59b4487e
+yuva420p16be        6afcf758f4b66c0b4173c942d42212d7
+yuva420p16le        13e195aa96329eb49921b6f9f07b875c
+yuva420p9be         05a78390de312dfd21ac666a9da05fbd
+yuva420p9le         78f5593bf51a31841ef83df41d0316eb
+yuva422p            45ae66d6f69fd5b77e6831e98d228bf4
+yuva422p10be        90ce250a517843b3e8a1ac0f4fdad733
+yuva422p10le        c74cfda8934e3bf86940b7a08c809b35
+yuva422p16be        c3f7354b6013b43439e02aa02be5fe69
+yuva422p16le        a7ccc43820683ab15061d14cf8efce6c
+yuva422p9be         14c55a16d19499b54b4341f135d3e558
+yuva422p9le         a8bf168e5d2709222192d0aff46b1373
+yuva444p            86b05da54db8c7e8cf5b6638e19c6fc5
+yuva444p10be        bea827ff82f229145a016954120b731f
+yuva444p10le        c51b0554cfba0fabacf979683dceee95
+yuva444p16be        52a9591ec0d5059e49b1b2803f8582aa
+yuva444p16le        a9272ac197e4a4195662ce90f533976c
+yuva444p9be         f72f646ef07cdab613420585aba041ac
+yuva444p9le         6d431b0a27bf4f86ea44ef5f14247a01
+yuvj420p            73661456012f20cda81207b14bb0c0a5
+yuvj422p            aa97862b57f47c5a6506156e9aaf129a
+yuvj440p            ff8b9884a49d546b035f5d2ac1e673df
+yuvj444p            b8142888d80b8065c54045839e79b331
+yuyv422             f06a4fbbdb32807d05de825daa2c3a1b
diff --git a/tests/ref/lavfi/pixfmts_crop b/tests/ref/lavfi/pixfmts_crop
index 67e5fac..797aedc 100644
--- a/tests/ref/lavfi/pixfmts_crop
+++ b/tests/ref/lavfi/pixfmts_crop
@@ -1,43 +1,43 @@
-abgr                48346c491906eca28e00a23ef5353a77
-argb                b747553e21de237b4cdd408fcbbfaecd
-bgr24               fe0151a7b7f599302c25ca8e5c4af4db
-bgr48be             7382471d86acea0d8158297666c827fe
-bgr48le             f0e53dc36fbf2eca118a9d772bdb8f8d
-bgr4_byte           82f27084cfdd119c4e0d48cf5c24d69f
-bgr555be            f5b46a880be2a51bb236e4c5128f6be8
-bgr555le            8615050ab74f49722ee34e34e809a708
-bgr565be            ce8855d8588d458778bb6c4982bd5e18
-bgr565le            83eb258b10791ed24054efc82f7bf562
-bgr8                316bf8d5b86305ff44ad7ee267a2ff69
-bgra                d902c52cbbb2e95f684b6096323d97f9
-gray                4d0af088c340dd75d357f097b52acd89
-gray16be            8f5777495e28a94cc387aa2a048b3497
-gray16le            dd3e032e02a8f651033bcdb2015a5802
-pal8                431a276e504cb02365ab3b2361ffd8bc
-rgb24               c0e1ebddf432cda28609ba6ac3f545df
-rgb48be             0a268f87065014615dee33ee9c9be31e
-rgb48le             a00ad9474040c20978b142b2b47cd236
-rgb4_byte           f7f7134258f08c517d8e93bff36ad720
-rgb555be            afeb7387a1f39cf0d9003ed0e44fa064
-rgb555le            b4fa8603e841651c1212508ab475984b
-rgb565be            53ae8b7df8eb550c11550e5e14076ca0
-rgb565le            4912344d8e2ddb8b184c62578a09dd5a
-rgb8                94f3e7f787ae73b663bf3c9eea55247e
-rgba                7f244176bd49823ada1a129aaaac0ba5
-yuv410p             a183ffd33903014dd608560cd53a6bfe
-yuv411p             fa1cd715cc0b5b04d042953000a1352a
-yuv420p             a717efee3fe5b0ae21bfec28a8814a72
-yuv420p16be         828378732914a01ed07ec44c2b7b4aec
-yuv420p16le         2a41d2ca620a240b7a035c4427065438
-yuv422p             6cfc7d6275e44d9ed8d016b9057f59ce
-yuv422p16be         af92cd1066c7249abdfc4dece1f2c590
-yuv422p16le         8e074c403be086f4bc56342807e18f67
-yuv440p             9a9da3172fc4101ffad7729eeda8a853
-yuv444p             d81cb00ffd82d232e4d35647b18927ef
-yuv444p16be         b5e81c4f939e03716505c137fee542d7
-yuv444p16le         16fdf905bbf8139af6e8a6e75fa4a091
-yuva420p            08f69b3b734b9a454590a3a7f423d74b
-yuvj420p            f34db073719616df612b059e2b799380
-yuvj422p            f1946babecd8d509fe853b33f49492a4
-yuvj440p            dd9bb7d90e6c863bb888d719da183304
-yuvj444p            74eb7e8ad11bbce02929be19fc73f4bd
+abgr                ef31d9057f6e65a7c3308a1b1daa98fa
+argb                5e5e261c4870e0de05d56ff640b9550a
+bgr24               44bec15f35513de7e957b3d59b53cb7b
+bgr48be             0b5ebce3c48eb8614d79e204b5268603
+bgr48le             c4ab61a8b9d502132730c6abb6ffd84c
+bgr4_byte           cab930dbe1fe77d58b41837ecdcb8460
+bgr555be            67162782fdb86813f446d8e1c21c73e9
+bgr555le            85913cfa8dab465f7dcfcfe7f9001a01
+bgr565be            ee9a1debb896d41c53a026f9e6ce006b
+bgr565le            ab7b6055bc3b6b7edc9a5e4de43ec90d
+bgr8                f85ff16e21d922ad6d32648ef3acfbfb
+bgra                9f2e37d73ad3b759fc9d6b12ee668c38
+gray                3266b99065a17cbd647f2339addc5303
+gray16be            02ac848ad4e28c06938599563ba81ff7
+gray16le            672aebfeb8a0f4067b3c6064340056e4
+pal8                e1fd50b8a8a67fb5abd8b44abc778bbb
+rgb24               d044123f1fe50f656f2101dd3f091ead
+rgb48be             ef5507f88948b54218911d12e1dbef36
+rgb48le             6d045d5990d6ada64a112e3b581a7b38
+rgb4_byte           0f0f9ee31c65dc60da49bf98a1b06dcf
+rgb555be            48fa619bfd04f6dee05416b02605c031
+rgb555le            292cff1f824e49076bad50a07ab1c749
+rgb565be            0dd6f6a5a8713bd1c3d9826bb7a88eab
+rgb565le            6afd85faa8c6f0f330969539178eb9a2
+rgb8                87cf541b110e35a6f9a983e9cde85e15
+rgba                7abe1af7b97f5b9a7aa5ad3e4bf32f76
+yuv410p             126e0da1da4fd89be28087b8367bbb36
+yuv411p             b94f0af107fc4796aca70c0a36d374c5
+yuv420p             74c6b331bd30f005e6c75a192423ad90
+yuv420p16be         2d3c84ebff77479e8c5b6e3e59ec4e45
+yuv420p16le         e2c906f2751609bf8cbcbeb2f629319a
+yuv422p             124bc8d668072de1bb3b894cc4bae859
+yuv422p16be         3ec47e2709107fcc388b5e0abebf7eaf
+yuv422p16le         a4183a62917bf8568fe11ff446dd18f9
+yuv440p             15c81c685fa5b9db95150caff14ff83f
+yuv444p             12b752f78af72666627cea2d0c274cdb
+yuv444p16be         f2bf0e22a1d184e37eaa199a76cf22ba
+yuv444p16le         c11b151dced5c8854d385373fa4dcc8f
+yuva420p            920c5d1b965eeb72e3a0e343696face3
+yuvj420p            f9183e49f42bae31d7d85b92161fa82f
+yuvj422p            aabeed60a6e1b2cf88665ac627bf531f
+yuvj440p            5ae4f404b42f3167f978473d9a3737fc
+yuvj444p            6728997f65b879fd5a3175cb449a8f0c
diff --git a/tests/ref/lavfi/pixfmts_hflip b/tests/ref/lavfi/pixfmts_hflip
index 8e1d538..e696997 100644
--- a/tests/ref/lavfi/pixfmts_hflip
+++ b/tests/ref/lavfi/pixfmts_hflip
@@ -1,47 +1,47 @@
-abgr                2ce3f4a300ee03b93a77fe39e55987fa
-argb                64e29bf8d65ed7103b6990e46b1a010e
-bgr24               31673b9d4bf0d0fd885bce5296dfb754
-bgr444be            34ba282584233724e20094c33b31c096
-bgr444le            08ae1f0ed1009b508802e23e57c7b147
-bgr48be             9365c39b8b4a7a4206b3b8ca9e42de00
-bgr48le             1de87874708283d574d333188188c536
-bgr4_byte           b28046fa8bda1dba75a87666715dfc26
-bgr555be            fcd71635673f337d560981be16600522
-bgr555le            29645c643e8f4d16bcd8ecce26d4aaff
-bgr565be            f9eeeed19b719b5590ce87d00536241d
-bgr565le            e1fe693f81b6403ba9b19e3412607feb
-bgr8                f36e2b3619d9a3a2b04690132332a76e
-bgra                58a0ffb544f709647a4662fbb6d399a1
-gray                144b08b0c49627aaaaa17235444ec807
-gray16be            5f302f6626a857b2563ce01866380a64
-gray16le            f2afd6c87122c48b72afa75b17e89243
-pal8                4f5eeba8ff969ed698863340f5304e8c
-rgb24               3c100ecfe1533412448853669cb13268
-rgb444be            326d3f83d1fbadfa11ecdcb113a3e8a5
-rgb444le            0ababfb3a16f0bbeacddaed0f5c8427c
-rgb48be             8f5f38388148a911031a0a94b19de1d0
-rgb48le             68e9b1e48b02c33c79ba834629cc54bf
-rgb4_byte           0a1229d6bc69cf24fbc7ce5dd5c06873
-rgb555be            38493e6ab0817e33c67c44a598e73e10
-rgb555le            f26e1089005ac6fbe45f56d39a8496f4
-rgb565be            6685e9e820cc9af85ecd8eae4d30db70
-rgb565le            bda1fe6e39bfca1b35a68e999e2da914
-rgb8                438f99353b2f495f6965268a73ba1154
-rgba                0d0008a7cff117e8dfc2abb138e98c7e
-yuv410p             be386727c9557bb7e2a4b18a1c547ab5
-yuv411p             a4a4d0247e81702fa86128d174dfa5ea
-yuv420p             8c01e844700606452b333acc5fdbc73f
-yuv420p16be         e0f01dfdf7719a44f57b6274d847e54d
-yuv420p16le         8701064f8f9b007cde3a9f50214581d8
-yuv422p             9cb0abd34a2d0bbe7eae3ec234de581e
-yuv422p16be         e1d7268ef464fcdce91cc43445c4b370
-yuv422p16le         89631ffd8ebabf9eebe9db0f969e4996
-yuv440p             debe01ae305866cd388126c078f37d61
-yuv444p             e8e77e7757574f96bd510b0159104bf4
-yuv444p16be         b259403c8be44b2a8c43768b32cfeecd
-yuv444p16le         41ce5c9cde1e019b733a5de69880d8e5
-yuva420p            9a0002557a583cd09cd0e44b01c9a7a8
-yuvj420p            d5d699d74af6c8082932cafbcffbc83e
-yuvj422p            197cbb3bd2707e94a57e25bba37e3d06
-yuvj440p            f900b0ccb1bfae557b0afbf691f2eb50
-yuvj444p            729a34a7dffcb04ed5efbbdf6c0a62f1
+abgr                8ab842e280c8b31f66450e8951dfedfa
+argb                cdb6aa47939d49c0ff72537bfc8c82e0
+bgr24               5b64fd60e2050946b50da1f4945127fb
+bgr444be            b52c1b9d9dc02cb46c04e80d97139e60
+bgr444le            48172797fa65a25c0ad30ddc7e8f5bcb
+bgr48be             58e292c33eb60708171c3393a5700615
+bgr48le             e1be8e6bfe26acdee258e76329d2f03d
+bgr4_byte           af34e1158edfbc8c6929365d651a9549
+bgr555be            c82d7877f7ef25ee1154d05b240cf54c
+bgr555le            b7a4e2c66807a82bd132dfcf8540bfb5
+bgr565be            3b464a00c619410eac7bdea9c96faf60
+bgr565le            4b4c708d4ad222f41734dce68e9d48b6
+bgr8                ad1db7a17cdfab2ede6f22c2415a3fbf
+bgra                85fa06ad9fd156c3179a647a2e741b60
+gray                35b50e78d5d27255f43e642a404dd708
+gray16be            d206a080739d89cb7dc0009ad4082ed4
+gray16le            7ebcfd9401ba85e584230de8fc02986d
+pal8                19c8735b23feeed18ec2d37913a5f3f8
+rgb24               c2752464ac2b549268e9638745dba857
+rgb444be            85586541cc7eb12e05ff7162b12304c2
+rgb444le            670da20b82403e00609bf2c1f5611223
+rgb48be             a9ee2c9946d8d54dba60cebbdbe43886
+rgb48le             28e2cf59b789249dbd0859f58f4ae55d
+rgb4_byte           31dca70b4f3537afa9840cea1b062acf
+rgb555be            c010cc746ce9483b47387ba846670179
+rgb555le            a768de014e0908dfa886108da376b2e5
+rgb565be            6727e71974c8e5dad157925c10ee1532
+rgb565le            b0a2b4817775289cfc415bb951f9ae0c
+rgb8                22fdbd14ce296c1afa9bb4a6ea09b3fe
+rgba                a37789c4df73c3bd8648ad1fe9d3f991
+yuv410p             a1280c2b9b562dba3c2d35a1e5fc4b23
+yuv411p             6bf10756ac5c7841db63a97106ff911b
+yuv420p             45f4a06481f2cd8e28fb29c7c151e110
+yuv420p16be         cde798cad650bcb087943442a399c8ea
+yuv420p16le         b7124c56605eeb12f3d13287ddc77f3a
+yuv422p             c3982fbb57e796881efedae11b8346de
+yuv422p16be         4b96fb571e686185d96b4a97e3413d5f
+yuv422p16le         503bc49bace58dae1767173746a16056
+yuv440p             44f78792c5766ab896fbe0d718976946
+yuv444p             a36b8ce12de27971b52e93267fe6583f
+yuv444p16be         9370058632b2582ab7a21725ec4f4e1d
+yuv444p16le         0674c63a0e8debbfc010a2730da66a13
+yuva420p            a62cf0a72905b54a7ef10fcaeff723bc
+yuvj420p            86370b945c5d19d809ee92386d476a53
+yuvj422p            d3bda08bd4b92a256a8ec8432c4767d1
+yuvj440p            dbae7083c82f20a38fc55e6f8bc374bc
+yuvj444p            55ce75c7bd172b28703e82f64186e6b6
diff --git a/tests/ref/lavfi/pixfmts_null b/tests/ref/lavfi/pixfmts_null
index 85648e3..1171546 100644
--- a/tests/ref/lavfi/pixfmts_null
+++ b/tests/ref/lavfi/pixfmts_null
@@ -1,83 +1,101 @@
-0bgr                c60961367c88d4c4fdb74a4a03f18c24
-0rgb                6bbd6fb67c9a830026c834bc4415f2ab
-abgr                1efbf983d9e05945b223e94281ba03dd
-argb                43db1b6f92785cb1741d1a8918be1cd6
-bgr0                5df429190741e396e6374742ec3b5ebb
-bgr24               5a99ab751497ff2308654815bb386ab1
-bgr444be            ad888031403150f784afa4ab5e53fa25
-bgr444le            8bcb29875ef4446f7b40ad5cbe6293c7
-bgr48be             aef991ccc6241fe89501b791b6d1c8a4
-bgr48le             4fe26de32f985c661535592adb854ca0
-bgr4_byte           86ab90dbf28e0d1fcc474c1bc6f3e6ce
-bgr555be            83b5dc82aca5c59214e2821d7c37e101
-bgr555le            5b21fe6b886d105e086ac758c9739ef7
-bgr565be            a03cd63592f7aa85926852e1b0eefb55
-bgr565le            da9f51fd88b00b77a2bdb44092ced6ca
-bgr8                6ee3a027fdf23d9e7641cf9db622e38f
-bgra                571e36479d0bcc63c71d91432a15fd0b
-gray                669860b0e6f48784f1c4edec7d45a23d
-gray16be            c3720d00b935ae76108f6a05825f3ec4
-gray16le            1a4dfbdad429e3a0217dd03978665a60
-monob               cf885ca3ab5c4e79befec8e961b53e6b
-monow               39b7e285f47af4f11003972733a8ec04
-nv12                d0293efcd106022aee6f4696a2492594
-nv21                4b1adad7b2017b2e08a4c686778740bd
-pal8                f3442a379152b41f24a01c35bfe8b0d7
-rgb0                bea4f3e5a1c673fc49b2ed8330ad5698
-rgb24               4f016dcae1677971d5ab8fc5281b4eb1
-rgb444be            5a1f1e3248a7f74ad8a813f88d91e2c7
-rgb444le            db3babb73c538490c56f1dd1b42e32c2
-rgb48be             c157b4bfdaba46851fb409404f0e2b31
-rgb48le             aaeb094dfdd0f0390db94e558fb2e4ec
-rgb4_byte           7d2d7b9383f83902f83f78a49b401e9c
-rgb555be            cc39e0816288e2215e76520c2f3f17d8
-rgb555le            297ca82788b023a3f94677652c091f30
-rgb565be            1b0fc1a80a3913fe0eaf283e68b83d09
-rgb565le            b861ec0fa3c4197dffaef41fc66e7c52
-rgb8                d50a2f3503a8dd876197b604266cf15b
-rgba                090e417705ca0e5187f029eeb394a885
-uyvy422             95b3ca9c609beae6c61fa33a7e6fcfe3
-yuv410p             5652f52e932d718eaad651d06a11ce09
-yuv411p             857a16f561424bcf361784c2e8578d63
-yuv420p             489aa94d1a2abf74529ce5aaf812a338
-yuv420p10be         a1c91b8684cb84a946d78dfa80a6323f
-yuv420p10le         4de5eee1402ae84946a24e3cc4804502
-yuv420p12be         a0f533c65ceabba7ac74deb129435109
-yuv420p12le         fffb48e79346e5a120b12adb87e40980
-yuv420p14be         90f3cd8e808572d3b75fd258652b765f
-yuv420p14le         b41393e500813a4444ac5607c98d7d4b
-yuv420p16be         5b15ffe17c78761138a48cb91e94002e
-yuv420p16le         942b992ad799833754590f9c3371bdae
-yuv420p9be          db3b9b202f8014761e79cff2546536ea
-yuv420p9le          43341ba3955a5c1a1652218d5e466446
-yuv422p             cd9185df12127a7830820862b15d6150
-yuv422p10be         bf0d4d0d6a4d4896650eff08b0a157a4
-yuv422p10le         cab49211123e7337bf8e7b248befacdc
-yuv422p12be         ec8718c7f3a96e4b41d4e69cb1ecce0c
-yuv422p12le         a783156c3ae833b1b16b5f6238d1163b
-yuv422p14be         b58c2198c56330cc19cd61a35e7d799a
-yuv422p14le         7f74d4936577cab0e5e9d6be61a36820
-yuv422p16be         3725aa6136741d558900efc46fa02897
-yuv422p16le         e5613f26cf21e6caa14c55bfa6dbf91f
-yuv422p9be          9c162a559c912dc2a03c0ede9666d201
-yuv422p9le          d778190180fba976dc5e3162b7622d27
-yuv440p             bd74a3dbbba05205fd30e101216a8ee3
-yuv444p             14e06ce6ebba6eccda67d8c5fb0f3695
-yuv444p10be         67bcd450bb1f7de75e51b5e115083f8a
-yuv444p10le         8cd9fe3450e25e1635c5f982bc404f20
-yuv444p12be         2d709d5cbf2c61970e7e6d609fd30f44
-yuv444p12le         8096f6a0f7b6e9b7d60af2cb4d2459fe
-yuv444p14be         9ded64b1f7d37bc170d5c4f4b65c133b
-yuv444p14le         c4981882cca655f0cbc4ed07a33a24c7
-yuv444p16be         06f0ea1a525ddc34116b2c0e3021e5a9
-yuv444p16le         507fc54fe06db5fbd1e36182ec0df4a2
-yuv444p9be          29911d5ab017a4ba12d915dc078ecd87
-yuv444p9le          e55015c87e7a90d87258af0ea5cce0e3
-yuva420p            ff556e3f6cf74f322467860555612c74
-yuva422p            9370ac9fcb59806592f4a35fa8fa28e7
-yuva444p            bb5f5d0c12a9e09ae37ac3bafff907cf
-yuvj420p            295b48eaabd1d239647a20962ab2f1a3
-yuvj422p            cba3eba27031f3ff38ae511c0f7220af
-yuvj440p            53351b202fcda4e03a363e1dcdb808c0
-yuvj444p            b9a2528e0f59939f025c0ae2a885edc8
-yuyv422             1c0ecc295a449472049c9cfa5e8ee4ab
+0bgr                a06d3a7652e4885c65895e0e168aab28
+0rgb                b6b5653d2228cdf2ba3c55a72f2e713f
+abgr                1a147fa04ed70b9a7e67a4c89052f630
+argb                997df0b5c268a0d8f9c611cae4e01e05
+bgr0                218df6dc3eb5094a0c16a8bd18bc3999
+bgr24               d6370f6dc34df2ea66e1718baf74137b
+bgr444be            aba6dfea008ae12c2120a95f54293904
+bgr444le            cfb5401e8f076cc8675e17ed1114a3df
+bgr48be             ab65229b64606f6408cd732b967c0b01
+bgr48le             f1b4e718cadee9bd2978289153ce43de
+bgr4_byte           de96505ef9ad7078f87b4dfdf6fe4b61
+bgr555be            8d5de9e9200d622f27dc73958a85045c
+bgr555le            74eb9837706143a40e26305a16a79369
+bgr565be            13a36d6502be88fc0c2aec05b8d2d501
+bgr565le            ed027571692aecd522aa65a90cc7e09b
+bgr8                71ef789609c746c2e7e4be9dec29062c
+bgra                0364b074268682ea46168742a8239f7d
+gray                1e5e2b8548843a6898eedd9c974c422c
+gray16be            389f4e5a8ab413b3af32767b59ed7f9e
+gray16le            a1f912941247e45b394b9cf4f0e81130
+monob               309b5785a36bd988d17e15d88f4ffad1
+monow               8809a02bc69b58d1114b09ca79ebffad
+nv12                75e90c54d858b993e99f4ee6d2a2a38f
+nv21                8831a3f411015d45fbc5dd191245ba9c
+pal8                13de2a1c3c80cb64d14e2bc4f6f461d0
+rgb0                992f5ad24802cc255edab45c3084db4a
+rgb24               c71ba90f69f15c8275232bb3f62d0ced
+rgb444be            26eaec65d7efd2b0c9c13b47dfd9b241
+rgb444le            5f29863553107110ea817f52151d77b7
+rgb48be             a3bc81c46c21818a989f23104a599ab0
+rgb48le             e87c661ac49aea1f1e93939802883d92
+rgb4_byte           293b1b84f01efd90bde40cb3faffc127
+rgb555be            5229183fa64d4e5c7e3703d8263ee6ae
+rgb555le            c3e9978cb2a4129a5575935e8cbc433a
+rgb565be            bc123b962629ead1a06af0c18cbb6e5f
+rgb565le            20757fafe4756e62d845b2ab4c0b8f93
+rgb8                e01614f5416dcc8ad365ad7a57afc9fb
+rgba                53796fa4c392a1b2659595b6a284f8c4
+uyvy422             3f411f947e3ac8f842c88e717d68bd9a
+yuv410p             7dcf3f4770c8b494290ceacd2c2ce6db
+yuv411p             9461b188dab6f8b90d9a27e353a89f58
+yuv420p             61fffd2d8425759a33ae07e718d0242d
+yuv420p10be         2abf90242cb021cb6fcf9f2c3c92f6a7
+yuv420p10le         180b7e4de684c7225d2fb37614f842cb
+yuv420p12be         256c9e6cfc878a8abf681b30777c0620
+yuv420p12le         8dc8b86c4790da3769d4a62e87608623
+yuv420p14be         8d22756c5d2b9e501924c082bfb22a6c
+yuv420p14le         c9da19d4818bcb119ad6481b75778f7e
+yuv420p16be         4ccdcca6dd6a960f9a3333f0aee095bd
+yuv420p16le         9c5847d9b0de258a10ee906dc47e24ea
+yuv420p9be          fa7ad4f73232aac0e35def62af1e2c39
+yuv420p9le          3720ba1786b56c8f4913e67dddebbb07
+yuv422p             eee223e92f1f2e5ad4186b411ebf5816
+yuv422p10be         80fa87750491dcc3e93d175b64835654
+yuv422p10le         e1640cd315bd96c6b59f7753825a7306
+yuv422p12be         5c6d86e919515d1af71f8004a6252f9e
+yuv422p12le         7f331cadb0ab75d07656d29f47bd8bd9
+yuv422p14be         4f4e186ba683b90fe990cccc4db7e521
+yuv422p14le         d78016c9119b1f1d1c922bd5aaf47732
+yuv422p16be         1f3c216927d17966a009a42def124bba
+yuv422p16le         90adbdffaeea9b09398339c8a1322b02
+yuv422p9be          e46446534dd0821029d3b831c9c1d1b0
+yuv422p9le          520e418a2429f7efee511b7fcbf45ab6
+yuv440p             456d83524b299f2fa1bb988e421554d9
+yuv444p             068bc09d282d18c9fa35c2787943fc2a
+yuv444p10be         9f6e1490080a454243daee9229425e1e
+yuv444p10le         cc183e51041351d9ac06c4df6e8ad5f7
+yuv444p12be         34f63ac6a47ac681016105d3bfb3e118
+yuv444p12le         7964701bfe8d718edf97f6e0002935bd
+yuv444p14be         4ad3a9d52fe9c050150c0f7d2f3cf63d
+yuv444p14le         69575e5a94b978f159c4fdb1a61587b0
+yuv444p16be         4000b12fa88ed0feef182da31c7e6b96
+yuv444p16le         96a857dba8dc6792c58daec872825b32
+yuv444p9be          07727e5c9040b7f0a17d591288ac330d
+yuv444p9le          4d12d20a68dc28618594c96c2ade4ff4
+yuva420p            3a8c5c142e051367c196f95696e0e2c3
+yuva420p10be        1b7c5ec6691498e24676ce6ed97f62f8
+yuva420p10le        ad2d0424033e7acbafa6d58f59b4487e
+yuva420p16be        6afcf758f4b66c0b4173c942d42212d7
+yuva420p16le        13e195aa96329eb49921b6f9f07b875c
+yuva420p9be         05a78390de312dfd21ac666a9da05fbd
+yuva420p9le         78f5593bf51a31841ef83df41d0316eb
+yuva422p            45ae66d6f69fd5b77e6831e98d228bf4
+yuva422p10be        90ce250a517843b3e8a1ac0f4fdad733
+yuva422p10le        c74cfda8934e3bf86940b7a08c809b35
+yuva422p16be        c3f7354b6013b43439e02aa02be5fe69
+yuva422p16le        a7ccc43820683ab15061d14cf8efce6c
+yuva422p9be         14c55a16d19499b54b4341f135d3e558
+yuva422p9le         a8bf168e5d2709222192d0aff46b1373
+yuva444p            86b05da54db8c7e8cf5b6638e19c6fc5
+yuva444p10be        bea827ff82f229145a016954120b731f
+yuva444p10le        c51b0554cfba0fabacf979683dceee95
+yuva444p16be        52a9591ec0d5059e49b1b2803f8582aa
+yuva444p16le        a9272ac197e4a4195662ce90f533976c
+yuva444p9be         f72f646ef07cdab613420585aba041ac
+yuva444p9le         6d431b0a27bf4f86ea44ef5f14247a01
+yuvj420p            73661456012f20cda81207b14bb0c0a5
+yuvj422p            aa97862b57f47c5a6506156e9aaf129a
+yuvj440p            ff8b9884a49d546b035f5d2ac1e673df
+yuvj444p            b8142888d80b8065c54045839e79b331
+yuyv422             f06a4fbbdb32807d05de825daa2c3a1b
diff --git a/tests/ref/lavfi/pixfmts_pad b/tests/ref/lavfi/pixfmts_pad
index dc9d6e6..9c31974 100644
--- a/tests/ref/lavfi/pixfmts_pad
+++ b/tests/ref/lavfi/pixfmts_pad
@@ -1,24 +1,24 @@
-0bgr                4ba083c2dacb793db850327b01ae7da3
-0rgb                a2de4fa98a0f64999456e01f7c635c45
-abgr                7c21ccd9fdd85d713a027699d2d0671e
-argb                e135bc712d28070a5191e89423ae46b6
-bgr0                843ad90650dac020795f4b9cc0ce0a74
-bgr24               52c59f3a2c6a86f18d7359aa3a881de0
-bgra                3400e09d293f3c453cc53ea729dba637
-gray                22bcdafc651e6cd229e32226e34b3b6a
-rgb0                f0be0d2e36139fc31f2db676cb29d764
-rgb24               f31b08e95b688f759e096c0504b9ecfc
-rgba                5f6a5dadcafb470dda62f51e03e1d7f5
-yuv410p             3abc794b7a763b08bd5c24e7a531cb35
-yuv411p             478f7ecc0c84859ed4a23cd2e1f96a92
-yuv420p             8da6caa13ffce6ec37c603a5ffd30ba3
-yuv422p             725eb4f0af141dc986517dec3a84b6fb
-yuv440p             e9c6a5f11a3d2697e01a361e038a4ab8
-yuv444p             cf7971198613705ae89707d5e97d94f5
-yuva420p            1f20010e667ebe3bca4105d7e4d84dbf
-yuva422p            7f4785bc4ee9e939a64bb36d9456ef01
-yuva444p            2cbd185d426d4590d99c083a830b0f7b
-yuvj420p            bfc93fbdcdf2bec93a626d323a13d68c
-yuvj422p            b61587f65d206ce5654c88ecd055f5b7
-yuvj440p            6ea611c86dd6b18c01e4ddb2926a5663
-yuvj444p            9ad40f50112d06bc447643feb6382a93
+0bgr                36ba5b43e0ac64d8daad4f897efd8cdf
+0rgb                cc3ca0f63885af19b3daa4504cadcc19
+abgr                9ddb78f395d7d3f75b65b5309223c0c5
+argb                e5fbb7bb282a80897b8f730627f68876
+bgr0                c55368036cccbb0af471d6bd82abe02a
+bgr24               67f9fd70dc6d9896b7122976b33932b4
+bgra                c8dd017b5a3b55e8b9d0ac1cdcf327bd
+gray                b1abadae3718522aa57a7972da8cbe17
+rgb0                b1977b45634c4db58a183a07feb2acff
+rgb24               e73de9dc0fdd78f4853c168603cc7aba
+rgba                5a36df3c5ba623b589728a5a442e98e2
+yuv410p             ff246b8b41d3d4a3eb90414ae3031123
+yuv411p             a82c606c665fa747679aa8bfffa8a5db
+yuv420p             0fe4d9031999f83ca96292ec2025f272
+yuv422p             5e0bffdac30b39f1bae9ec54fd9a6a34
+yuv440p             5e338303cd89d1d76ab918e5bec1e90d
+yuv444p             248bdf9747d5c3718580dc2279e2e273
+yuva420p            b5bdefbb0c5b302b6d18ee4df7c1d7c7
+yuva422p            8b56b36d9eb3c382d2a5a695107e759d
+yuva444p            389cf95e98bf24684a42d5d67b913e16
+yuvj420p            d182ac937d312e4894c1bc548883bf1c
+yuvj422p            26ac91b5daf6f2f1f3c22be489e994a3
+yuvj440p            63e2b94f81e0a6f2868055a4c8258b63
+yuvj444p            64f103c7db8fc803d062db7ed2b8dc76
diff --git a/tests/ref/lavfi/pixfmts_pixdesctest b/tests/ref/lavfi/pixfmts_pixdesctest
index 08974d7..1057c41 100644
--- a/tests/ref/lavfi/pixfmts_pixdesctest
+++ b/tests/ref/lavfi/pixfmts_pixdesctest
@@ -1,83 +1,101 @@
-0bgr                3a2f7a255895f154bbc2c0541e11b66d
-0rgb                00ac9e01d63b821c394ac6203f7cd233
-abgr                1efbf983d9e05945b223e94281ba03dd
-argb                43db1b6f92785cb1741d1a8918be1cd6
-bgr0                fe56f8c8edc63130c65045dd8f1629f9
-bgr24               5a99ab751497ff2308654815bb386ab1
-bgr444be            ad888031403150f784afa4ab5e53fa25
-bgr444le            8bcb29875ef4446f7b40ad5cbe6293c7
-bgr48be             aef991ccc6241fe89501b791b6d1c8a4
-bgr48le             4fe26de32f985c661535592adb854ca0
-bgr4_byte           86ab90dbf28e0d1fcc474c1bc6f3e6ce
-bgr555be            83b5dc82aca5c59214e2821d7c37e101
-bgr555le            5b21fe6b886d105e086ac758c9739ef7
-bgr565be            a03cd63592f7aa85926852e1b0eefb55
-bgr565le            da9f51fd88b00b77a2bdb44092ced6ca
-bgr8                6ee3a027fdf23d9e7641cf9db622e38f
-bgra                571e36479d0bcc63c71d91432a15fd0b
-gray                669860b0e6f48784f1c4edec7d45a23d
-gray16be            c3720d00b935ae76108f6a05825f3ec4
-gray16le            1a4dfbdad429e3a0217dd03978665a60
-monob               cf885ca3ab5c4e79befec8e961b53e6b
-monow               39b7e285f47af4f11003972733a8ec04
-nv12                d0293efcd106022aee6f4696a2492594
-nv21                4b1adad7b2017b2e08a4c686778740bd
-pal8                f3442a379152b41f24a01c35bfe8b0d7
-rgb0                4b3850f80188f03b7fea0a39e5a035e4
-rgb24               4f016dcae1677971d5ab8fc5281b4eb1
-rgb444be            5a1f1e3248a7f74ad8a813f88d91e2c7
-rgb444le            db3babb73c538490c56f1dd1b42e32c2
-rgb48be             c157b4bfdaba46851fb409404f0e2b31
-rgb48le             aaeb094dfdd0f0390db94e558fb2e4ec
-rgb4_byte           7d2d7b9383f83902f83f78a49b401e9c
-rgb555be            cc39e0816288e2215e76520c2f3f17d8
-rgb555le            297ca82788b023a3f94677652c091f30
-rgb565be            1b0fc1a80a3913fe0eaf283e68b83d09
-rgb565le            b861ec0fa3c4197dffaef41fc66e7c52
-rgb8                d50a2f3503a8dd876197b604266cf15b
-rgba                090e417705ca0e5187f029eeb394a885
-uyvy422             95b3ca9c609beae6c61fa33a7e6fcfe3
-yuv410p             5652f52e932d718eaad651d06a11ce09
-yuv411p             857a16f561424bcf361784c2e8578d63
-yuv420p             489aa94d1a2abf74529ce5aaf812a338
-yuv420p10be         a1c91b8684cb84a946d78dfa80a6323f
-yuv420p10le         4de5eee1402ae84946a24e3cc4804502
-yuv420p12be         a0f533c65ceabba7ac74deb129435109
-yuv420p12le         fffb48e79346e5a120b12adb87e40980
-yuv420p14be         90f3cd8e808572d3b75fd258652b765f
-yuv420p14le         b41393e500813a4444ac5607c98d7d4b
-yuv420p16be         5b15ffe17c78761138a48cb91e94002e
-yuv420p16le         942b992ad799833754590f9c3371bdae
-yuv420p9be          db3b9b202f8014761e79cff2546536ea
-yuv420p9le          43341ba3955a5c1a1652218d5e466446
-yuv422p             cd9185df12127a7830820862b15d6150
-yuv422p10be         bf0d4d0d6a4d4896650eff08b0a157a4
-yuv422p10le         cab49211123e7337bf8e7b248befacdc
-yuv422p12be         ec8718c7f3a96e4b41d4e69cb1ecce0c
-yuv422p12le         a783156c3ae833b1b16b5f6238d1163b
-yuv422p14be         b58c2198c56330cc19cd61a35e7d799a
-yuv422p14le         7f74d4936577cab0e5e9d6be61a36820
-yuv422p16be         3725aa6136741d558900efc46fa02897
-yuv422p16le         e5613f26cf21e6caa14c55bfa6dbf91f
-yuv422p9be          9c162a559c912dc2a03c0ede9666d201
-yuv422p9le          d778190180fba976dc5e3162b7622d27
-yuv440p             bd74a3dbbba05205fd30e101216a8ee3
-yuv444p             14e06ce6ebba6eccda67d8c5fb0f3695
-yuv444p10be         67bcd450bb1f7de75e51b5e115083f8a
-yuv444p10le         8cd9fe3450e25e1635c5f982bc404f20
-yuv444p12be         2d709d5cbf2c61970e7e6d609fd30f44
-yuv444p12le         8096f6a0f7b6e9b7d60af2cb4d2459fe
-yuv444p14be         9ded64b1f7d37bc170d5c4f4b65c133b
-yuv444p14le         c4981882cca655f0cbc4ed07a33a24c7
-yuv444p16be         06f0ea1a525ddc34116b2c0e3021e5a9
-yuv444p16le         507fc54fe06db5fbd1e36182ec0df4a2
-yuv444p9be          29911d5ab017a4ba12d915dc078ecd87
-yuv444p9le          e55015c87e7a90d87258af0ea5cce0e3
-yuva420p            ff556e3f6cf74f322467860555612c74
-yuva422p            9370ac9fcb59806592f4a35fa8fa28e7
-yuva444p            bb5f5d0c12a9e09ae37ac3bafff907cf
-yuvj420p            295b48eaabd1d239647a20962ab2f1a3
-yuvj422p            cba3eba27031f3ff38ae511c0f7220af
-yuvj440p            53351b202fcda4e03a363e1dcdb808c0
-yuvj444p            b9a2528e0f59939f025c0ae2a885edc8
-yuyv422             1c0ecc295a449472049c9cfa5e8ee4ab
+0bgr                2b46a6ce47a19ffc240e4e93f498f491
+0rgb                e90e5d377a3e5af69fdf7b60cbf88f51
+abgr                1a147fa04ed70b9a7e67a4c89052f630
+argb                997df0b5c268a0d8f9c611cae4e01e05
+bgr0                b61591a68252e66c576b9bb074a9eaed
+bgr24               d6370f6dc34df2ea66e1718baf74137b
+bgr444be            aba6dfea008ae12c2120a95f54293904
+bgr444le            cfb5401e8f076cc8675e17ed1114a3df
+bgr48be             ab65229b64606f6408cd732b967c0b01
+bgr48le             f1b4e718cadee9bd2978289153ce43de
+bgr4_byte           de96505ef9ad7078f87b4dfdf6fe4b61
+bgr555be            8d5de9e9200d622f27dc73958a85045c
+bgr555le            74eb9837706143a40e26305a16a79369
+bgr565be            13a36d6502be88fc0c2aec05b8d2d501
+bgr565le            ed027571692aecd522aa65a90cc7e09b
+bgr8                71ef789609c746c2e7e4be9dec29062c
+bgra                0364b074268682ea46168742a8239f7d
+gray                1e5e2b8548843a6898eedd9c974c422c
+gray16be            389f4e5a8ab413b3af32767b59ed7f9e
+gray16le            a1f912941247e45b394b9cf4f0e81130
+monob               309b5785a36bd988d17e15d88f4ffad1
+monow               8809a02bc69b58d1114b09ca79ebffad
+nv12                75e90c54d858b993e99f4ee6d2a2a38f
+nv21                8831a3f411015d45fbc5dd191245ba9c
+pal8                13de2a1c3c80cb64d14e2bc4f6f461d0
+rgb0                5774780b3c532896300fa326fcde01a8
+rgb24               c71ba90f69f15c8275232bb3f62d0ced
+rgb444be            26eaec65d7efd2b0c9c13b47dfd9b241
+rgb444le            5f29863553107110ea817f52151d77b7
+rgb48be             a3bc81c46c21818a989f23104a599ab0
+rgb48le             e87c661ac49aea1f1e93939802883d92
+rgb4_byte           293b1b84f01efd90bde40cb3faffc127
+rgb555be            5229183fa64d4e5c7e3703d8263ee6ae
+rgb555le            c3e9978cb2a4129a5575935e8cbc433a
+rgb565be            bc123b962629ead1a06af0c18cbb6e5f
+rgb565le            20757fafe4756e62d845b2ab4c0b8f93
+rgb8                e01614f5416dcc8ad365ad7a57afc9fb
+rgba                53796fa4c392a1b2659595b6a284f8c4
+uyvy422             3f411f947e3ac8f842c88e717d68bd9a
+yuv410p             7dcf3f4770c8b494290ceacd2c2ce6db
+yuv411p             9461b188dab6f8b90d9a27e353a89f58
+yuv420p             61fffd2d8425759a33ae07e718d0242d
+yuv420p10be         2abf90242cb021cb6fcf9f2c3c92f6a7
+yuv420p10le         180b7e4de684c7225d2fb37614f842cb
+yuv420p12be         256c9e6cfc878a8abf681b30777c0620
+yuv420p12le         8dc8b86c4790da3769d4a62e87608623
+yuv420p14be         8d22756c5d2b9e501924c082bfb22a6c
+yuv420p14le         c9da19d4818bcb119ad6481b75778f7e
+yuv420p16be         4ccdcca6dd6a960f9a3333f0aee095bd
+yuv420p16le         9c5847d9b0de258a10ee906dc47e24ea
+yuv420p9be          fa7ad4f73232aac0e35def62af1e2c39
+yuv420p9le          3720ba1786b56c8f4913e67dddebbb07
+yuv422p             eee223e92f1f2e5ad4186b411ebf5816
+yuv422p10be         80fa87750491dcc3e93d175b64835654
+yuv422p10le         e1640cd315bd96c6b59f7753825a7306
+yuv422p12be         5c6d86e919515d1af71f8004a6252f9e
+yuv422p12le         7f331cadb0ab75d07656d29f47bd8bd9
+yuv422p14be         4f4e186ba683b90fe990cccc4db7e521
+yuv422p14le         d78016c9119b1f1d1c922bd5aaf47732
+yuv422p16be         1f3c216927d17966a009a42def124bba
+yuv422p16le         90adbdffaeea9b09398339c8a1322b02
+yuv422p9be          e46446534dd0821029d3b831c9c1d1b0
+yuv422p9le          520e418a2429f7efee511b7fcbf45ab6
+yuv440p             456d83524b299f2fa1bb988e421554d9
+yuv444p             068bc09d282d18c9fa35c2787943fc2a
+yuv444p10be         9f6e1490080a454243daee9229425e1e
+yuv444p10le         cc183e51041351d9ac06c4df6e8ad5f7
+yuv444p12be         34f63ac6a47ac681016105d3bfb3e118
+yuv444p12le         7964701bfe8d718edf97f6e0002935bd
+yuv444p14be         4ad3a9d52fe9c050150c0f7d2f3cf63d
+yuv444p14le         69575e5a94b978f159c4fdb1a61587b0
+yuv444p16be         4000b12fa88ed0feef182da31c7e6b96
+yuv444p16le         96a857dba8dc6792c58daec872825b32
+yuv444p9be          07727e5c9040b7f0a17d591288ac330d
+yuv444p9le          4d12d20a68dc28618594c96c2ade4ff4
+yuva420p            3a8c5c142e051367c196f95696e0e2c3
+yuva420p10be        1b7c5ec6691498e24676ce6ed97f62f8
+yuva420p10le        ad2d0424033e7acbafa6d58f59b4487e
+yuva420p16be        6afcf758f4b66c0b4173c942d42212d7
+yuva420p16le        13e195aa96329eb49921b6f9f07b875c
+yuva420p9be         05a78390de312dfd21ac666a9da05fbd
+yuva420p9le         78f5593bf51a31841ef83df41d0316eb
+yuva422p            45ae66d6f69fd5b77e6831e98d228bf4
+yuva422p10be        90ce250a517843b3e8a1ac0f4fdad733
+yuva422p10le        c74cfda8934e3bf86940b7a08c809b35
+yuva422p16be        c3f7354b6013b43439e02aa02be5fe69
+yuva422p16le        a7ccc43820683ab15061d14cf8efce6c
+yuva422p9be         14c55a16d19499b54b4341f135d3e558
+yuva422p9le         a8bf168e5d2709222192d0aff46b1373
+yuva444p            86b05da54db8c7e8cf5b6638e19c6fc5
+yuva444p10be        bea827ff82f229145a016954120b731f
+yuva444p10le        c51b0554cfba0fabacf979683dceee95
+yuva444p16be        52a9591ec0d5059e49b1b2803f8582aa
+yuva444p16le        a9272ac197e4a4195662ce90f533976c
+yuva444p9be         f72f646ef07cdab613420585aba041ac
+yuva444p9le         6d431b0a27bf4f86ea44ef5f14247a01
+yuvj420p            73661456012f20cda81207b14bb0c0a5
+yuvj422p            aa97862b57f47c5a6506156e9aaf129a
+yuvj440p            ff8b9884a49d546b035f5d2ac1e673df
+yuvj444p            b8142888d80b8065c54045839e79b331
+yuyv422             f06a4fbbdb32807d05de825daa2c3a1b
diff --git a/tests/ref/lavfi/pixfmts_scale b/tests/ref/lavfi/pixfmts_scale
index 9e89213..825dc3a 100644
--- a/tests/ref/lavfi/pixfmts_scale
+++ b/tests/ref/lavfi/pixfmts_scale
@@ -1,83 +1,101 @@
-0bgr                14371787cb6f25d13641c6ee20371b6b
-0rgb                91eddb69df6a24b979160958db22a565
-abgr                77db78782b1e7ddba60632dd1a303712
-argb                39ea6501e5d6eb294cd7eaab6371d343
-bgr0                25a81868b39ec50abcbe31c87c30a314
-bgr24               262e4b1d1c5e57ec510423f8b103deb1
-bgr444be            99910395203c3e3a124b88ce38c1ab30
-bgr444le            c97f15e264c3ed7aa3e762ea6badfbc5
-bgr48be             b9355b6e2fa9540844d3a4798a2f4cbc
-bgr48le             dbba0b9a29379a207d17e86727e590ec
-bgr4_byte           30e5b2a2e359510e44ec11af0485056e
-bgr555be            acd17ba4930f945be0d8aff56913a530
-bgr555le            c2d63d263ec54a8a0ac0f18f771b6fd4
-bgr565be            da90900ef28d0a968913d818b9151775
-bgr565le            a6b1d0cf6df7b12c70a6fde5bdbd300a
-bgr8                ef4ff3880990232eaf018000336a1c22
-bgra                95f4de4d34f216043e6faab0cada8f09
-gray                9f1890b80e6461b6dc52852b8ac2b46b
-gray16be            9553a17a213df5ac39ba63561d509e8d
-gray16le            e57f8e11e4b1469a33fd7872e5041cda
-monob               138812271ce79b8406dee4f7827ee315
-monow               a426636244885f16b5b0e53d4aac8a4d
-nv12                d9c8fede0c2b37efc9d392240ffda473
-nv21                db57de603b35c8b7825bdbee47ea6290
-pal8                b98525dc50bf0c8517289414f45738e0
-rgb0                036b5084768fd1aaf1c2beed6498c3d6
-rgb24               fd56bd5ae0b363db50ea0ddeed887357
-rgb444be            3458fde34335f458131bd2774697c356
-rgb444le            79353099096cb61721bc38d99dd5bdbf
-rgb48be             3e5cf94d961eb2450c05ccaeac1a441d
-rgb48le             01763198e94e34a3aef5f96e43ea9ac4
-rgb4_byte           f334376204287fdd2501f639005256a6
-rgb555be            e9e0308ea11a24ddee93726687bc2028
-rgb555le            6e0ecb95473955230024c8043ae38b6c
-rgb565be            262ad795c9b10e89ec72f9afae9152b0
-rgb565le            968790f4301ada0029df0a92efd6a1c1
-rgb8                64c5a73c8e09bb1514841629eb26ccff
-rgba                16eb3d427c37416eda786cf4ed22fc68
-uyvy422             63aafdc5321331cc771cb2dd01a4cc4e
-yuv410p             c5c8793588a517021a2201bbcfa503c6
-yuv411p             833360b69d70c002425f8976860e540d
-yuv420p             494b13c17712eddad7b837ca88211b4f
-yuv420p10be         1b4b0d0b2f209cd4d33a84907652cfa5
-yuv420p10le         6b5459a4c4d99205ef1d6dc3c1d5a7e2
-yuv420p12be         a8d6bf744abbdd55d5c3cde24de4b9cc
-yuv420p12le         794bac4781d58821d1e60cb821388a11
-yuv420p14be         16f2114f373c9446ff2aacf4b7e5f9fc
-yuv420p14le         2cb3fbf9ed08060a68ddcccfab6f884a
-yuv420p16be         3f51012ec7ad80ad03099598d5cce958
-yuv420p16le         26daa9638fc3971c959e20c30329beb2
-yuv420p9be          f381d3dfd8ca6b5b44aaa4f5583bf026
-yuv420p9le          3ab36daca6691c1fec64eba5b7070d8c
-yuv422p             6bea21dcd2a9e790e126ad27519a6cbb
-yuv422p10be         0dcc91430b4ae83e8567efb2b785e81d
-yuv422p10le         e56817bad3ff93319a9dd6bda8add151
-yuv422p12be         f943bb452e8e297c12185114b4df3181
-yuv422p12le         92a9e51141e0aee4741ea3b8e3255b2d
-yuv422p14be         f47e4c7b3a2ac4447d7bd5679dc16d86
-yuv422p14le         ed630d01cb5aaafaf356dfd15b3f57a1
-yuv422p16be         2c3dde6ece764d011e1aa513d1594818
-yuv422p16le         8e588d6e8e1816829cc9c138bc3ca5e0
-yuv422p9be          e6f84127e542f3728605d6e4d28f0209
-yuv422p9le          914f8415eab24f9c4aa4bf4f217022f1
-yuv440p             9b1b31dc70239952ea682631ca785b7c
-yuv444p             1731b67f3439fec9435e8796dc05e8a9
-yuv444p10be         c1bb15ed5c52f151bdbed2dc16c7fda5
-yuv444p10le         7925f118e9263b5794311cf0ae700ab0
-yuv444p12be         409453278552dcc8f813b545ea545f7d
-yuv444p12le         7f6dcfb61f2f37978d1f6ed0c52fb9e8
-yuv444p14be         65463b08fed9df349520bd41f00bebfb
-yuv444p14le         d56413c2f72ceeb81749011b8a7fe190
-yuv444p16be         863b6d45d776a0f8aa3b4acb806b6f50
-yuv444p16le         2e06a8dffb7a5b09a70becc013e13ad8
-yuv444p9be          26e1db6b43dd3479b5d20238e3e5edbb
-yuv444p9le          01c31ad72aff138698bdc9f7cef3105b
-yuva420p            4f8d6eda06a404cd85ce199ce5a75bf0
-yuva422p            620f340912561c9f5f93c211cb7d0842
-yuva444p            453b560554306aa20a19c577a7bb216f
-yuvj420p            48849ed52648620980aa323ee26aa7eb
-yuvj422p            36a5699407513b677de6838718862994
-yuvj440p            43f43fd7fb4a6f94b6ec3234be785f3a
-yuvj444p            6490aa566d645012537e9427f15d21d5
-yuyv422             21759d8b1d2e83282ce7f74bf51baea7
+0bgr                710350573339f608b23e5bf8ea3327d0
+0rgb                ba87d80ccd24ffb20ac711511132adb8
+abgr                e448ff50225b119979987e55399e49e2
+argb                ef03d804e0de6315fd59e3d2edaddb9d
+bgr0                93cd61cfcbef1789d2d5ccae4de75f79
+bgr24               793fc4c2b1c92ad4f7f4dca157e624d1
+bgr444be            9af6abe0bc74cdcc75b4ab2f441f5f67
+bgr444le            b8c0e693ae2cbd7c03abcc3aeb4bf7b4
+bgr48be             3aa33b667b9baefe3f17ef44360688cd
+bgr48le             eaf353ab363fbb279fd72d6c6e3b8855
+bgr4_byte           a6e269daf7085504a01113ce5e8bff57
+bgr555be            9d71206c1a5373b8978126e5f5779726
+bgr555le            025caaa21fed9d14c382cac26af778c8
+bgr565be            fca6f07daf23d9dd84381dd4c9afd959
+bgr565le            f524e9f16bdd68b247dbcb621e543fc0
+bgr8                68a3a395043dc57335ad1f8e891229c5
+bgra                3eaf5489b8aa13a3388aad3751b597bf
+gray                045c35e6cc7d41460f2b96b3e254deab
+gray16be            70064f9acdc5e3935ccda67e765bf2fb
+gray16le            578241fb43029e5ae841a3c94d940dce
+monob               91ec2a25b13f6ca34d42da778b217de0
+monow               a991455fda8f60f373aeb744456996b9
+nv12                0617f1e13ae4a43d4cb49282b9c02f71
+nv21                8a00d5d29766c1251eeda74c0ddee3f2
+pal8                7849884994cf99604f025b053332d08d
+rgb0                6a9d26ebf674f02b5a8830583ba7a171
+rgb24               1de2978e23ad10b9b4ca2777688b4546
+rgb444be            88f534c5d07ebf5a4374484aed540893
+rgb444le            c243685bfad7c243a78892a0dafe2b9f
+rgb48be             874c8e2305ce9d82165ffddf2854d1f2
+rgb48le             877075f2ff2d9a0aec6fec843385f126
+rgb4_byte           4a8b119cf1996efe273302da29cbfbfb
+rgb555be            8aeefa1fc4eba200abee3b1eb52186af
+rgb555le            0495a7c13f9b0d0253379d5ae90cf6c4
+rgb565be            5168b66e69c25351948085e5fc51bb3a
+rgb565le            301a4d41f0db3aaed341d812ed0d7927
+rgb8                8e5786e83099bc89d2e38a76e6dfcc52
+rgba                de6a65b8c01bdad84e575202ca8b66a0
+uyvy422             479105bc4c7fbb4a33ca8745aa8c2de8
+yuv410p             d0daa93f5cee83360e219e39563ab6da
+yuv411p             e5c8f3ca024a88dd07e0a92db3e2133d
+yuv420p             485d9af8608f926ffffbf42230b4150d
+yuv420p10be         e4f12002b46549779886f27fd3c6c645
+yuv420p10le         698b7a346ae6d1315280d3e28c86b973
+yuv420p12be         10ccb1da4f69f5578e017ffdaa19adf6
+yuv420p12le         4f68fcfeee4fb70ea941979cc6a39d1f
+yuv420p14be         d7b1183a6ca2f5d80d1bddf609c35995
+yuv420p14le         934dbea61d804e7c66e805a45f1e3914
+yuv420p16be         6ebcf48a9317c6265430cd3ba5f569a2
+yuv420p16le         604a7215f384488a38aa0cffdbcbe17e
+yuv420p9be          7b293aec92897bf0a32ec3a02a20acf9
+yuv420p9le          f37fdff7d6c62ebe2ab0cf791cd049db
+yuv422p             b1724528079199908c667b3428a7c01c
+yuv422p10be         1c7281254fb980c123148dfd145c4a05
+yuv422p10le         959caa253354e897f01848db21b8006e
+yuv422p12be         9e1db2326fb3dd3a8f8d32f3a6f61305
+yuv422p12le         5a4aecf4baf74358551e75fd7f1549cd
+yuv422p14be         e75088b934f86ddb6a7ff1749b77687c
+yuv422p14le         2cdae3e0447b35ddee6161639107205b
+yuv422p16be         4ccc3e0bc94eaf3a3350e4d694c3a56c
+yuv422p16le         dde889032f13fa5f8d76b8484dd73116
+yuv422p9be          ba5eae7669d02a13f54a592344612098
+yuv422p9le          2deb39425d924a15c8946df79ceaa579
+yuv440p             19de0ba1fd354b42189e96cdf73ef7cc
+yuv444p             fba8a00cd0b182af82e9de3b2f4d2c8a
+yuv444p10be         db89397ac4d33e66b5eab3678661f73a
+yuv444p10le         28208677f07d4e4191ef228c096f3297
+yuv444p12be         55d291347d13f98b520c7d0cf7e0bdfe
+yuv444p12le         fd12d6054262cebda2a9b1a2ac4dac98
+yuv444p14be         a078f34e001828d576e748ca0850af56
+yuv444p14le         d02ba5c47b0bbb359df8ef478aa4c395
+yuv444p16be         07e27200d2f4382090ca260874f02e92
+yuv444p16le         f8bac16bf1f2afbd3626e07bcc815a9f
+yuv444p9be          db739906e3ae3b8792cdc5a0c3387565
+yuv444p9le          693b8d30958ef1a37296b1690b4b36d2
+yuva420p            df46b738bdaf30d3a7f880b5ae45b092
+yuva420p10be        8e5f3b069fdf2f0c14f49ad827991092
+yuva420p10le        e6915376ad7d0f2be9d50099e5ee33ef
+yuva420p16be        aa8ca29a93936c62ef038ca8a57f47d7
+yuva420p16le        ee0cbb31f9cdb897c1982df0caa8ffa0
+yuva420p9be         b8ca5603123aeb953b9d4fc8ec8e35e1
+yuva420p9le         220212a81cda0f2d112f7ae96d532ff9
+yuva422p            650755270debb03d2c03b2e93b64c576
+yuva422p10be        fe0d8c2509d2d23f856093f9aea83cba
+yuva422p10le        c641064c6306c6eaf95b387e5ae08d67
+yuva422p16be        0b8f9385498d2449b18fb15237b0a448
+yuva422p16le        ce22b20deb93b4846a5043aa104f22d1
+yuva422p9be         822df465d12916d8852340d6b56247c8
+yuva422p9le         f69c09e872838fe392dfe1825263d3f1
+yuva444p            72083e0941cc45af9f97b89d3cd16112
+yuva444p10be        d8b6fe8cfb60c6e516563c0a4f5c75a8
+yuva444p10le        4a85b717f21975216144efc11e2f2cda
+yuva444p16be        36a8797545163c24fc0d73f669c3108c
+yuva444p16le        c017c229aacb832a12c2297fb080a7a0
+yuva444p9be         8bfb5decfc8b71478b090a5b48c316c3
+yuva444p9le         2c7bfb90f7db9faab6862537801e1143
+yuvj420p            31386dce60a2dcc493da5d0ed9d880df
+yuvj422p            492452e50a3fe66724840cad29be4098
+yuvj440p            7632893e81d3f4f3ace3755f97479897
+yuvj444p            389388dd5d623f660c30ab840807ce82
+yuyv422             518be9b5ac93c365c0962453770fbe73
diff --git a/tests/ref/lavfi/pixfmts_super2xsai b/tests/ref/lavfi/pixfmts_super2xsai
index 5584fc9..964d04a 100644
--- a/tests/ref/lavfi/pixfmts_super2xsai
+++ b/tests/ref/lavfi/pixfmts_super2xsai
@@ -1,14 +1,14 @@
-abgr                72e4a233f5fa2c8c6b9c95583b69a3e1
-argb                8634cf8cf1e6c25eee93fc00494ed11b
-bgr24               b63dcc4d10d3e9ee70505328ba283f8f
-bgr555be            5e2f65a80547b48258f8ad1d3f8aafc2
-bgr555le            9f4c7baa78d4126993576c849abf2240
-bgr565be            1c99b149f2f1e85041716c3fc9881343
-bgr565le            750738a13ad7fa5f5704171ce2bb806f
-bgra                c28251ef6c7a7ada249accf17750f165
-rgb24               019d33663642ae0517c0215f5a5719f2
-rgb555be            a20298e4fc6574cea0ec7b6a2e4e0502
-rgb555le            bee2cdf7d0314de958d962055efb7954
-rgb565be            a69f68f33571f7d1b6a9b01f1b3cd4df
-rgb565le            94569d9dd804c85e9afebaf785aea031
-rgba                6e084b1e9e457269a970ac9385597d28
+abgr                b04e3dfb0043f6eb04a573d2d13052eb
+argb                257e33717d23298430025c0665642cd5
+bgr24               3765d88f93d4ae8baa2cfbc64b0b32e1
+bgr555be            81832e6269c509be55bba49bdd0ebed5
+bgr555le            56772e91aefba4013890d156866730ce
+bgr565be            0b3c420fbddcec5a420c285b3c4b8792
+bgr565le            6cbded26d2bab8204afe2115384c09a8
+bgra                c81430c3d1465e37b6acaa19cc54e932
+rgb24               9899359a817e705dc5b9cc363d35a625
+rgb555be            9b60d9aa1f3c78edf9936894f37e3243
+rgb555le            917fa8565f35882404a45fee3a947bf7
+rgb565be            12edaab49440fbb3aa4c1835fd697745
+rgb565le            5bf91cb1767066f23f0c672dedb4d476
+rgba                71687289b6c3ab6fa727d468de459026
diff --git a/tests/ref/lavfi/pixfmts_vflip b/tests/ref/lavfi/pixfmts_vflip
index 5d7e656..1d5d1bd 100644
--- a/tests/ref/lavfi/pixfmts_vflip
+++ b/tests/ref/lavfi/pixfmts_vflip
@@ -1,83 +1,101 @@
-0bgr                fa3f0ce97b70ae0eb6fd24f6195f2091
-0rgb                300a5d5b80b746ebf00b1640dea2d817
-abgr                67710eb7e6d6e78d87c27e5c5b65e09c
-argb                6928f47cbd595792978ecfd72f588215
-bgr0                2c010f0f89d3d11b501d9421fa1a1733
-bgr24               506a7cf8eb73ff2e91dddd8989a18f12
-bgr444be            5a89a2ed5f90b86bc839a7bde8ea95e5
-bgr444le            b98d1e8563ff726ff80a6637af85afa3
-bgr48be             c1d44eb53d02e307ff8d0a1a57c0780d
-bgr48le             03c63a5d197008306be739c56d729420
-bgr4_byte           92fe489c4d786598d3e61bb2aa72d763
-bgr555be            4b260ce6fc19c7df90bb879fcc5cf962
-bgr555le            6b535578d42afa9b014fbcb17eb3b8c3
-bgr565be            5ace50bb09467828ea8efdd8713196ec
-bgr565le            88346e2e834adbb6bf7087dc5f7d2cc7
-bgr8                2373adfcf1b4a5968d8a00140d661e48
-bgra                7a1bd62f5768e6a1739546393972e721
-gray                d9d673e4ed652c080aa42631a97b94d4
-gray16be            88f90a01c5ae2ec57ed1041943071fbf
-gray16le            bcedd3c7bee4f2dc3890710df3ce2130
-monob               dfb092a1736017f95378bd76aeef16d8
-monow               940757cf7b0245ad69b8ef343085961e
-nv12                ef41a69821ea09da1de9d9c50872b265
-nv21                2d06f7dec8273737c58548efdc2d2e22
-pal8                e22b58f3621fbec7c044857dfe962939
-rgb0                ac7b37539ff03ffcb2cdfcc1321cb717
-rgb24               baffcf29cbef4164348bb73497535692
-rgb444be            6ac1c77afef40c6c86f5454aa66cb157
-rgb444le            56d48f09ca592166e18a88d009addb73
-rgb48be             a364c17acb67ba4f96ee4399970ca048
-rgb48le             791d935fc34e307104deb9899e28a2d3
-rgb4_byte           6cf30719d7cfe876b9d34baa0d28aec8
-rgb555be            dc3732df7b05e8cc88b7150c006d105c
-rgb555le            38eab4817339589dfe938a6d9c8b74ea
-rgb565be            6c0313d6ac0093e04740438eea7036ab
-rgb565le            47c4b1ddc3b7183c9bbe9d62046bd5d8
-rgb8                e1e00c02fff5c442bacc13e01dc64135
-rgba                b65c0e739b993d8ea16a9dbcc30cb132
-uyvy422             ece83505dc69e2004b5a344c4daa5a7d
-yuv410p             3fb3bbb96873d973ed70b9121c27a8f8
-yuv411p             106a75dc1312f66dbb497611a0a02520
-yuv420p             0a88149792aa1121ce8e7755f4523df9
-yuv420p10be         d1825eb808be09f5e080a86dcf7d705f
-yuv420p10le         f65d65b1f6f48eef28adb1bfd69d201e
-yuv420p12be         32d237de66223ae4b74431677af06593
-yuv420p12le         779c4b622ad3d64b88957493ae8d280b
-yuv420p14be         acafbaeb3d520d6f097a5678918bd66c
-yuv420p14le         07ca722472a8e5d17642489cbfa3f806
-yuv420p16be         58468ae4a7ca33a493c34d914e9adc7e
-yuv420p16le         eab1411947fb9b3b174e8edf3dd33424
-yuv420p9be          e491e39ea89ce81e086ccf30b08b174d
-yuv420p9le          326126b513f1d7f4db1565906e3cd3ba
-yuv422p             b1895d434e5b461704bc78cc0fe538de
-yuv422p10be         f31e81c31db780a5a37c93843eae7e9f
-yuv422p10le         116e79220d770960a7699af8b26c35d4
-yuv422p12be         c3619c347ea8296c1ed0aa5671ff8436
-yuv422p12le         0d189a30b2fa04b37b47261c10afb8e3
-yuv422p14be         1f743eb949370e4108f8ea64911bcc6b
-yuv422p14le         73c58185507f657e557860082e5f6b99
-yuv422p16be         619de2d8b32a3bb3bd7546957b4e358f
-yuv422p16le         9010c178b564cd937bd342ccecaa7ff9
-yuv422p9be          1db36898b100e3b508a36a677e2c4f70
-yuv422p9le          49218ae028d5577b9c646866350c8ebf
-yuv440p             25e36eb7fb5ac101507b916a4e12ba67
-yuv444p             33e85a87bcc2a3c8648ea21e79375b45
-yuv444p10be         ccd6e3f7997b41f2cb6593ec1cf34448
-yuv444p10le         c9b1346bae6d5c8ce63be9695ec1a7d9
-yuv444p12be         375703e688f9bfe1cdd23c3fdfd9027e
-yuv444p12le         85f50477867b3bc85ecf4d83c7bbda03
-yuv444p14be         e97d330963f1f9484b7313265bdc7d81
-yuv444p14le         2b6504830ff9f39335bd4b1ff70ec49c
-yuv444p16be         c9660655ca9a13993a9b615bc11f4b6e
-yuv444p16le         30fa301d390505b00761805fc6fb3eb6
-yuv444p9be          ddbdd8c0d103564e9fdf257d9928c9c3
-yuv444p9le          202fbf5dadb74b0e28ba8e34409adf4a
-yuva420p            5cf02b17792c24596fba194518b002de
-yuva422p            d5cb89aac9203927d2bd4a1793b69b62
-yuva444p            f819be12766f1a2ec0663fe2cde9f2c1
-yuvj420p            7fae45038fbe310c3ec94466479b7953
-yuvj422p            9ac0943a4b5e505476f210eb7146d543
-yuvj440p            fc9b4306e4a6c7d04af83fe54215a5dc
-yuvj444p            97f525e3ae103a9706a509e4e366d7ed
-yuyv422             d775e727ab42c1f47bf52fb88ed07b4e
+0bgr                30d1f7d7081c012556da0373e6d389ee
+0rgb                66cd838e9c19f750c61efd73f66c42ac
+abgr                e6cc18ed21293e455d1dc63f9e1645e4
+argb                b5383d783698a0b3d753d01f2498e490
+bgr0                f99729e70a94d1c278c292a7acdddae5
+bgr24               c48ec71c68a9840572a548c2ad141028
+bgr444be            ab9253d2f836f58ff8f3f2b4ec76abdc
+bgr444le            b1bd8245a286b615e75e10d34fda4e62
+bgr48be             b5355b4fa578b9422288507cf7fba2b6
+bgr48le             11dc232500b6339f58a9981f46d1d7a9
+bgr4_byte           531fd9a2249a213c89b1afc9788d070e
+bgr555be            54ba55dc1dcc5a7f27f2727976be6583
+bgr555le            a45c637fe5ce84b238b1e6f66fc8c852
+bgr565be            7100c2ddfee42e7efafec1ccefecf7c6
+bgr565le            9fab295d966386d4ef99d5b43066da47
+bgr8                275ce12eeb05de67a6915f67cbb43ce5
+bgra                d29c35871248c476c366e678db580982
+gray                a53528cdf80ed31c9897042a2ea16618
+gray16be            9b23f3e79c54a6ccb62e0135a32e3045
+gray16le            93cfa8fbb2a86ead275ce1817444e6d5
+monob               c395a8efb9477b4ec53a77326e41ccd7
+monow               efaee1c763ccd5ce1a8519d2ed5aa5a9
+nv12                77373304a9c732b65dab0a33afba9295
+nv21                1e70b3ce8be75f91f465a6d62df550c3
+pal8                be51ffaaad8e8428f2ce1e10d5729d3d
+rgb0                84a83e576fc59ffd1ac5549fd7aa0023
+rgb24               a00171a51cbbdcc61ecbd0198b2e2513
+rgb444be            09a819863d3fe75518376cdac01c069f
+rgb444le            4ab35fc85b8550be2a9b96dec9bf7306
+rgb48be             97a30a902d26b4840235926dae9028dd
+rgb48le             82b33a864bab70d5463d57eaf693e78c
+rgb4_byte           afbfab537406988eab7460ec748a0389
+rgb555be            95e417e9429622245e2d2e0b1c3ab3e4
+rgb555le            e4b35d8e9c1710f6d051fb4bda8700cc
+rgb565be            c70d86afbd68a073f2d4fe0eee3a9832
+rgb565le            991576c5d3308a73068a826543b3e7af
+rgb8                42230235c5a2a66c0f9a2fcd20f9f5cd
+rgba                a6973a2940a378d2a8284194da26eec0
+uyvy422             21c48162379321bb83ec2399535f9253
+yuv410p             8699f50c04f8ac931aa5a8306827364b
+yuv411p             47af34559b92b68851df4c2b170f7736
+yuv420p             c59b35b82b5a195128736021913b35a4
+yuv420p10be         fc5eed1744cdd033728362772a450e32
+yuv420p10le         141e6b39adac979765c846f3a5a8293c
+yuv420p12be         0e0145d3592d56362c1bcc62cbd78a78
+yuv420p12le         8c3a2b27126df203786d4e05fd79e269
+yuv420p14be         6a11c75aa378f9628cd8fc3339474e68
+yuv420p14le         e8b683876508bc0371582e2b8c0eb191
+yuv420p16be         c467fae3a1936f3f91c19dd1c0c63e49
+yuv420p16le         87f09595ac106e694c538382179bfcc5
+yuv420p9be          31bc440f64fdd8d9e7cba897881345ec
+yuv420p9le          c6fed3016f03c49aa01bdcd63f846d3a
+yuv422p             5e48541d3e659046ac0e1eacb038485f
+yuv422p10be         9097b4d06f1fc598375b7c6480a2ba50
+yuv422p10le         da7bd36f65cac06bd54bc9857493d835
+yuv422p12be         9c0fd650ec9872fbe06e82dc41a7399f
+yuv422p12le         3bdb982268c06b8876e206d8b89b4583
+yuv422p14be         bb0fc25212c2aa9f273aad2d562c3384
+yuv422p14le         1f89e82da25ce459db456ed27631054f
+yuv422p16be         95ed65e718929dbeb5092bf0d852026d
+yuv422p16le         c62e554dde4a170177bec2efc3f4f1a2
+yuv422p9be          b249cd58eaab5ccac6bae3e184774362
+yuv422p9le          696fc2a55f155edaaa9fc289574b2bb8
+yuv440p             fca8395b7e43e2d0f38dd6ba822ef747
+yuv444p             1ef971a434c53e81c578e3c7cb9cbcad
+yuv444p10be         3114a7469c2b9c440a9a9ccbd6e167d6
+yuv444p10le         34cb8774a1eb627b5f32825ac7d0ae9a
+yuv444p12be         2fd83655c3223d176243d7ff871df3cc
+yuv444p12le         cfec541fde2894656f6b3401177b7604
+yuv444p14be         11671a128afd177e5eda13bd2e93ac26
+yuv444p14le         5aefe5d3f78e4f3b86ed7041a20f9b8e
+yuv444p16be         35340098dc6956c34afce17bc6ffcedd
+yuv444p16le         201e3acfa6f7628dfe2a1663de1128b1
+yuv444p9be          6143c321929ade9e0bc93ddea926e936
+yuv444p9le          e43ba2026848ec803fabf74d77c10125
+yuva420p            dc8fd115eaf203a3eac351b92a7d8f18
+yuva420p10be        b3aaa8a5c9b9c3c9d66053159af3ec99
+yuva420p10le        f43a991e8b5fe7e192cf4e0dfee2b6cb
+yuva420p16be        b5c54895e87521f65a298d33bab5eb08
+yuva420p16le        95e208bc6644e23a2126ac5fca085f06
+yuva420p9be         1ba55d16f060bf54698dd7200523b44f
+yuva420p9le         4b57b8bd1534743f6740502c74bef385
+yuva422p            6091f9c62a121c09eadb02e9173b2da2
+yuva422p10be        93b6afb2b1d1538b1c87caa040c43f4e
+yuva422p10le        1c9359025ab8d257f0f5296e6b5a5787
+yuva422p16be        3fa019b3d5e6dcb7c8e338837b9cffe1
+yuva422p16le        871f244989e14f5d3eda45abb6b3dfd1
+yuva422p9be         923c816778f782ff8a56bcd1b14ef08d
+yuva422p9le         bd882d40af0369d9ef7891c8e7891024
+yuva444p            9a55e83047abcc7a709f20805070135e
+yuva444p10be        7ae88f488969b527c1348383c0d06ade
+yuva444p10le        79a8dab388eb4d6cd12949b456ef5975
+yuva444p16be        4699a802e8ea3e74e968122980c0b0b0
+yuva444p16le        6f54a8cff38c54a235b92a0f1314e0aa
+yuva444p9be         7472bb4b0c774d5d741035086d5e4330
+yuva444p9le         ae11ddd5a3e8d69a36989f6f2a8897a1
+yuvj420p            200b0332de9944e76c94d2e0699a5a2d
+yuvj422p            a19a89ef145305cf224ef5aa247d075a
+yuvj440p            4240c9348d28af5f3edd0e642002bd2c
+yuvj444p            9e11298ba9c4faae0f5c81420d2123f2
+yuyv422             867fff568fa4170503779c48e5f25e6e
diff --git a/tests/ref/lavfi/pp b/tests/ref/lavfi/pp
index 66db725..bfa86ef 100644
--- a/tests/ref/lavfi/pp
+++ b/tests/ref/lavfi/pp
@@ -1 +1 @@
-pp                  e0756dea5d0bb61c81fbb1b940c95244
+pp                  8e68fb247880aa083e91bcbddf9d76c7
diff --git a/tests/ref/lavfi/pp2 b/tests/ref/lavfi/pp2
index 5182cc1..819d4e4 100644
--- a/tests/ref/lavfi/pp2
+++ b/tests/ref/lavfi/pp2
@@ -1 +1 @@
-pp2                 4c6d874eb355ab99bfd80ff8326d2558
+pp2                 28e91376aeb49c79dae9221b1a4997ae
diff --git a/tests/ref/lavfi/pp3 b/tests/ref/lavfi/pp3
index ad4bea1..2956375 100644
--- a/tests/ref/lavfi/pp3
+++ b/tests/ref/lavfi/pp3
@@ -1 +1 @@
-pp3                 2cdcc4683fd6c1f5c4dbd4f35428c5ee
+pp3                 d8d19c1f5e3f4032e9ed7bbb2026f030
diff --git a/tests/ref/lavfi/pp4 b/tests/ref/lavfi/pp4
index 69c2712..0557ca6 100644
--- a/tests/ref/lavfi/pp4
+++ b/tests/ref/lavfi/pp4
@@ -1 +1 @@
-pp4                 7e51ac70aab4c738642ebd006e517138
+pp4                 d79a3727359f62747edb82cc92ed040b
diff --git a/tests/ref/lavfi/pp5 b/tests/ref/lavfi/pp5
index 6afd078..4265566 100644
--- a/tests/ref/lavfi/pp5
+++ b/tests/ref/lavfi/pp5
@@ -1 +1 @@
-pp5                 263d82e8b07f92d2d6a9ed0256f545b8
+pp5                 5dc5a1f0c67d8a78e32cf50f47d1b27f
diff --git a/tests/ref/lavfi/pp6 b/tests/ref/lavfi/pp6
index c660ad3..ca40024 100644
--- a/tests/ref/lavfi/pp6
+++ b/tests/ref/lavfi/pp6
@@ -1 +1 @@
-pp6                 b46b6f830861d16153de2a9671c98e75
+pp6                 40fb584b10082dff87fb947a1bccdbef
diff --git a/tests/ref/lavfi/scale200 b/tests/ref/lavfi/scale200
index a956537..f267522 100644
--- a/tests/ref/lavfi/scale200
+++ b/tests/ref/lavfi/scale200
@@ -1 +1 @@
-scale200            065fcec08fb9d4b9ed723af659ae1e01
+scale200            e84ce966038a9f8f915704959f64278d
diff --git a/tests/ref/lavfi/scale500 b/tests/ref/lavfi/scale500
index 9dc46c4..ec4a699 100644
--- a/tests/ref/lavfi/scale500
+++ b/tests/ref/lavfi/scale500
@@ -1 +1 @@
-scale500            696a493074397146e3c5d0b49ffa5caf
+scale500            24e89b23ba4286162c2026181db8d2b7
diff --git a/tests/ref/lavfi/scalenorm b/tests/ref/lavfi/scalenorm
new file mode 100644
index 0000000..6df4bb8
--- /dev/null
+++ b/tests/ref/lavfi/scalenorm
@@ -0,0 +1 @@
+scalenorm           cad5d7b40b213deecc1d156cf45fc70d
diff --git a/tests/ref/lavfi/select b/tests/ref/lavfi/select
index f8c3297..a9d2be0 100644
--- a/tests/ref/lavfi/select
+++ b/tests/ref/lavfi/select
@@ -1 +1 @@
-select              0f5c26bc1741e0b72500a5bb7f33d15e
+select              7975bb8d0e326af9369379927324f1a6
diff --git a/tests/ref/lavfi/setdar b/tests/ref/lavfi/setdar
index 180ad75..5bc7d5d 100644
--- a/tests/ref/lavfi/setdar
+++ b/tests/ref/lavfi/setdar
@@ -1 +1 @@
-setdar              5e69edb10e33ecf536d0b2e9e42229df
+setdar              04b06d4622b116cdae756d4b475b9d5d
diff --git a/tests/ref/lavfi/setsar b/tests/ref/lavfi/setsar
index 2fee0c6..86592e8 100644
--- a/tests/ref/lavfi/setsar
+++ b/tests/ref/lavfi/setsar
@@ -1 +1 @@
-setsar              5e69edb10e33ecf536d0b2e9e42229df
+setsar              04b06d4622b116cdae756d4b475b9d5d
diff --git a/tests/ref/lavfi/testsrc b/tests/ref/lavfi/testsrc
index a562466..8e2363b 100644
--- a/tests/ref/lavfi/testsrc
+++ b/tests/ref/lavfi/testsrc
@@ -1 +1 @@
-testsrc             285e218c941d6830b7174095e9814132
+testsrc             cdac8817054b30e086d6ecabdcec5444
diff --git a/tests/ref/lavfi/thumbnail b/tests/ref/lavfi/thumbnail
index af6020c..5cfbf50 100644
--- a/tests/ref/lavfi/thumbnail
+++ b/tests/ref/lavfi/thumbnail
@@ -1 +1 @@
-thumbnail           87f897b86cbecc7130780d309b42596b
+thumbnail           33c479d5701943253df5e6adc6bc8746
diff --git a/tests/ref/lavfi/tile b/tests/ref/lavfi/tile
index 0fef007..376acfc 100644
--- a/tests/ref/lavfi/tile
+++ b/tests/ref/lavfi/tile
@@ -1 +1 @@
-tile                8016e2f3cbab976d0dcf531655220bdd
+tile                bfd98570151154d078b14398f867f0e8
diff --git a/tests/ref/lavfi/tinterlace_merge b/tests/ref/lavfi/tinterlace_merge
index 42675a4..300713f 100644
--- a/tests/ref/lavfi/tinterlace_merge
+++ b/tests/ref/lavfi/tinterlace_merge
@@ -1,10 +1,10 @@
-gray                26b6b9e89fe1f32695f726639351504c
-yuv410p             3634d715f95aecceba00c96f40c121b6
-yuv420p             62339167a917a51e4d528ccf2d26de0f
-yuv422p             de3480004bdb8e7b711f5b465014aeab
-yuv444p             9c9847984402eaefde910ad8a088e356
-yuva420p            65f7fd965c848713ecb84e462722b173
-yuvj420p            a32361014887cda411c64253be37e020
-yuvj422p            2e2252ecb9d98b355f0cadd8495b340d
-yuvj440p            fff44eb68a5bfc9815637d0706b9b23c
-yuvj444p            23f3c3bbe1cb263202c366b8a2abc649
+gray                c996e583bbc5a6f380463142eb77b7c6
+yuv410p             c9bad1317b496071d6d895238638e07d
+yuv420p             9794d11e59ec7bcdf9e30a433e4137b1
+yuv422p             e852e61e455db8ee3981ea942d510b0f
+yuv444p             a38a3f65d2f358cde5e9547c897cfcd5
+yuva420p            c1dc15d6ee78587d9f825acd795673d7
+yuvj420p            3ee7014727ee64b45292a4f15ba028d8
+yuvj422p            4f990d5473f15571276adb5770b3b773
+yuvj440p            9a005e8b8431aaa762fde8d942fd11a9
+yuvj444p            e29bf9f42e3a3632e09df529979e0040
diff --git a/tests/ref/lavfi/tinterlace_pad b/tests/ref/lavfi/tinterlace_pad
index 2e41c41..722ac85 100644
--- a/tests/ref/lavfi/tinterlace_pad
+++ b/tests/ref/lavfi/tinterlace_pad
@@ -1,10 +1,10 @@
-gray                9258e5cf66725a1814302cff34d4e765
-yuv410p             4557c54e14f761e3cafae7681d696d90
-yuv420p             d9dee6c4f0eaedc55819fda8e2fd43a3
-yuv422p             531cfaad53e2fe4021286075ca0987e0
-yuv444p             7aff195b2d5a5390f8e83f64c4c66789
-yuva420p            5260ee1f1088eb1df6a671b10229c8c8
-yuvj420p            bc1ddf876ee211a8b6ef684b66f90a02
-yuvj422p            7ff40b351f2b11d901e9ffefe9fa9e45
-yuvj440p            aa4ad715791d02e2b4a62b2a083429ef
-yuvj444p            b1b5967c63467b415acdd7d653b2cef4
+gray                25a7d1ccf1a06c1a8a0520c1e6cb30ff
+yuv410p             17163d1b4f21d894598fc62e6aeb8141
+yuv420p             f8bbae33295741c1c17d33ff8ee16f7f
+yuv422p             4fa67d1580d3453942bb0950c5784f6e
+yuv444p             f0558305fb7ca65b5b86d3ee88c4201e
+yuva420p            7c76c0ca03a62275d25e8140c68da2b9
+yuvj420p            b5b7baf11946a2265fc56e48be5b0436
+yuvj422p            2e70ab700851d12a773f926bb1785235
+yuvj440p            93319f9c8a02ee793966fae40f7e42fd
+yuvj444p            81a124fffe0214bee5205c90ae0dd201
diff --git a/tests/ref/lavfi/transpose b/tests/ref/lavfi/transpose
index 7ed6be1..1785e3a 100644
--- a/tests/ref/lavfi/transpose
+++ b/tests/ref/lavfi/transpose
@@ -1 +1 @@
-transpose           14056020d8d3d53a1e777c9cf265d590
+transpose           75d71957db820f657ccc46c14da6c8e9
diff --git a/tests/ref/lavfi/unsharp b/tests/ref/lavfi/unsharp
index 70d19b9..ad064ae 100644
--- a/tests/ref/lavfi/unsharp
+++ b/tests/ref/lavfi/unsharp
@@ -1 +1 @@
-unsharp             d8075a533238ec096926b205a27ec87c
+unsharp             7d72d2ab7b7f60159c822a097e01068b
diff --git a/tests/ref/lavfi/vflip b/tests/ref/lavfi/vflip
index 23ac2b4..ee49247 100644
--- a/tests/ref/lavfi/vflip
+++ b/tests/ref/lavfi/vflip
@@ -1 +1 @@
-vflip               0a88149792aa1121ce8e7755f4523df9
+vflip               c59b35b82b5a195128736021913b35a4
diff --git a/tests/ref/lavfi/vflip_crop b/tests/ref/lavfi/vflip_crop
index a63eb8b..43c944a 100644
--- a/tests/ref/lavfi/vflip_crop
+++ b/tests/ref/lavfi/vflip_crop
@@ -1 +1 @@
-vflip_crop          5bc8ad16993c93cd00f03b90ed376c64
+vflip_crop          cd56578bb7e89ca0853467dfecab244b
diff --git a/tests/ref/lavfi/vflip_vflip b/tests/ref/lavfi/vflip_vflip
index 5391c19..f401fc7 100644
--- a/tests/ref/lavfi/vflip_vflip
+++ b/tests/ref/lavfi/vflip_vflip
@@ -1 +1 @@
-vflip_vflip         489aa94d1a2abf74529ce5aaf812a338
+vflip_vflip         61fffd2d8425759a33ae07e718d0242d
diff --git a/tests/ref/seek/adpcm_ima_qt_aiff b/tests/ref/seek/acodec-adpcm-ima_qt
similarity index 100%
rename from tests/ref/seek/adpcm_ima_qt_aiff
rename to tests/ref/seek/acodec-adpcm-ima_qt
diff --git a/tests/ref/seek/adpcm_ima_wav_wav b/tests/ref/seek/acodec-adpcm-ima_wav
similarity index 100%
rename from tests/ref/seek/adpcm_ima_wav_wav
rename to tests/ref/seek/acodec-adpcm-ima_wav
diff --git a/tests/ref/seek/adpcm_ms_wav b/tests/ref/seek/acodec-adpcm-ms
similarity index 100%
rename from tests/ref/seek/adpcm_ms_wav
rename to tests/ref/seek/acodec-adpcm-ms
diff --git a/tests/ref/seek/adpcm_swf_flv b/tests/ref/seek/acodec-adpcm-swf
similarity index 100%
rename from tests/ref/seek/adpcm_swf_flv
rename to tests/ref/seek/acodec-adpcm-swf
diff --git a/tests/ref/seek/adpcm_yamaha_wav b/tests/ref/seek/acodec-adpcm-yamaha
similarity index 100%
rename from tests/ref/seek/adpcm_yamaha_wav
rename to tests/ref/seek/acodec-adpcm-yamaha
diff --git a/tests/ref/seek/alac_mov b/tests/ref/seek/acodec-alac
similarity index 100%
rename from tests/ref/seek/alac_mov
rename to tests/ref/seek/acodec-alac
diff --git a/tests/ref/seek/flac_flac b/tests/ref/seek/acodec-flac
similarity index 100%
rename from tests/ref/seek/flac_flac
rename to tests/ref/seek/acodec-flac
diff --git a/tests/ref/seek/mp2_mp2 b/tests/ref/seek/acodec-mp2
similarity index 100%
rename from tests/ref/seek/mp2_mp2
rename to tests/ref/seek/acodec-mp2
diff --git a/tests/ref/seek/pcm_alaw_wav b/tests/ref/seek/acodec-pcm-alaw
similarity index 100%
rename from tests/ref/seek/pcm_alaw_wav
rename to tests/ref/seek/acodec-pcm-alaw
diff --git a/tests/ref/seek/pcm_f32be_au b/tests/ref/seek/acodec-pcm-f32be
similarity index 85%
rename from tests/ref/seek/pcm_f32be_au
rename to tests/ref/seek/acodec-pcm-f32be
index 886356a..b838262 100644
--- a/tests/ref/seek/pcm_f32be_au
+++ b/tests/ref/seek/acodec-pcm-f32be
@@ -1,53 +1,53 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  8192
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size:  8192
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  8192
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size:  8192
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.894172 pts: 1.894172 pos: 668288 size:  8192
+ret: 0         st: 0 flags:1 dts: 1.894172 pts: 1.894172 pos: 668296 size:  8192
 ret: 0         st: 0 flags:0  ts: 0.788345
-ret: 0         st: 0 flags:1 dts: 0.788345 pts: 0.788345 pos: 278152 size:  8192
+ret: 0         st: 0 flags:1 dts: 0.788345 pts: 0.788345 pos: 278160 size:  8192
 ret: 0         st: 0 flags:1  ts:-0.317506
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  8192
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size:  8192
 ret: 0         st:-1 flags:0  ts: 2.576668
-ret: 0         st: 0 flags:1 dts: 2.576667 pts: 2.576667 pos: 909072 size:  8192
+ret: 0         st: 0 flags:1 dts: 2.576667 pts: 2.576667 pos: 909080 size:  8192
 ret: 0         st:-1 flags:1  ts: 1.470835
-ret: 0         st: 0 flags:1 dts: 1.470839 pts: 1.470839 pos: 518936 size:  8192
+ret: 0         st: 0 flags:1 dts: 1.470839 pts: 1.470839 pos: 518944 size:  8192
 ret: 0         st: 0 flags:0  ts: 0.365011
-ret: 0         st: 0 flags:1 dts: 0.365011 pts: 0.365011 pos: 128800 size:  8192
+ret: 0         st: 0 flags:1 dts: 0.365011 pts: 0.365011 pos: 128808 size:  8192
 ret: 0         st: 0 flags:1  ts:-0.740839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  8192
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size:  8192
 ret: 0         st:-1 flags:0  ts: 2.153336
-ret: 0         st: 0 flags:1 dts: 2.153333 pts: 2.153333 pos: 759720 size:  8192
+ret: 0         st: 0 flags:1 dts: 2.153333 pts: 2.153333 pos: 759728 size:  8192
 ret: 0         st:-1 flags:1  ts: 1.047503
-ret: 0         st: 0 flags:1 dts: 1.047506 pts: 1.047506 pos: 369584 size:  8192
+ret: 0         st: 0 flags:1 dts: 1.047506 pts: 1.047506 pos: 369592 size:  8192
 ret: 0         st: 0 flags:0  ts:-0.058322
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  8192
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size:  8192
 ret: 0         st: 0 flags:1  ts: 2.835828
-ret: 0         st: 0 flags:1 dts: 2.835828 pts: 2.835828 pos:1000504 size:  8192
+ret: 0         st: 0 flags:1 dts: 2.835828 pts: 2.835828 pos:1000512 size:  8192
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.730000 pts: 1.730000 pos: 610368 size:  8192
+ret: 0         st: 0 flags:1 dts: 1.730000 pts: 1.730000 pos: 610376 size:  8192
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.624172 pts: 0.624172 pos: 220232 size:  8192
+ret: 0         st: 0 flags:1 dts: 0.624172 pts: 0.624172 pos: 220240 size:  8192
 ret: 0         st: 0 flags:0  ts:-0.481655
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  8192
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size:  8192
 ret: 0         st: 0 flags:1  ts: 2.412494
-ret: 0         st: 0 flags:1 dts: 2.412494 pts: 2.412494 pos: 851152 size:  8192
+ret: 0         st: 0 flags:1 dts: 2.412494 pts: 2.412494 pos: 851160 size:  8192
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.306667 pts: 1.306667 pos: 461016 size:  8192
+ret: 0         st: 0 flags:1 dts: 1.306667 pts: 1.306667 pos: 461024 size:  8192
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200839 pts: 0.200839 pos:  70880 size:  8192
+ret: 0         st: 0 flags:1 dts: 0.200839 pts: 0.200839 pos:  70888 size:  8192
 ret: 0         st: 0 flags:0  ts:-0.904989
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  8192
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size:  8192
 ret: 0         st: 0 flags:1  ts: 1.989184
-ret: 0         st: 0 flags:1 dts: 1.989184 pts: 1.989184 pos: 701808 size:  8192
+ret: 0         st: 0 flags:1 dts: 1.989184 pts: 1.989184 pos: 701816 size:  8192
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.883333 pts: 0.883333 pos: 311664 size:  8192
+ret: 0         st: 0 flags:1 dts: 0.883333 pts: 0.883333 pos: 311672 size:  8192
 ret: 0         st:-1 flags:1  ts:-0.222493
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  8192
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size:  8192
 ret: 0         st: 0 flags:0  ts: 2.671678
-ret: 0         st: 0 flags:1 dts: 2.671678 pts: 2.671678 pos: 942592 size:  8192
+ret: 0         st: 0 flags:1 dts: 2.671678 pts: 2.671678 pos: 942600 size:  8192
 ret: 0         st: 0 flags:1  ts: 1.565850
-ret: 0         st: 0 flags:1 dts: 1.565850 pts: 1.565850 pos: 552456 size:  8192
+ret: 0         st: 0 flags:1 dts: 1.565850 pts: 1.565850 pos: 552464 size:  8192
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.460000 pts: 0.460000 pos: 162312 size:  8192
+ret: 0         st: 0 flags:1 dts: 0.460000 pts: 0.460000 pos: 162320 size:  8192
 ret: 0         st:-1 flags:1  ts:-0.645825
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  8192
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size:  8192
diff --git a/tests/ref/seek/pcm_f32le_wav b/tests/ref/seek/acodec-pcm-f32le
similarity index 100%
rename from tests/ref/seek/pcm_f32le_wav
rename to tests/ref/seek/acodec-pcm-f32le
diff --git a/tests/ref/seek/pcm_f64be_au b/tests/ref/seek/acodec-pcm-f64be
similarity index 85%
rename from tests/ref/seek/pcm_f64be_au
rename to tests/ref/seek/acodec-pcm-f64be
index 9be3b4e..8222351 100644
--- a/tests/ref/seek/pcm_f64be_au
+++ b/tests/ref/seek/acodec-pcm-f64be
@@ -1,53 +1,53 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size: 16384
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size: 16384
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size: 16384
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size: 16384
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.894172 pts: 1.894172 pos:1336552 size: 16384
+ret: 0         st: 0 flags:1 dts: 1.894172 pts: 1.894172 pos:1336560 size: 16384
 ret: 0         st: 0 flags:0  ts: 0.788345
-ret: 0         st: 0 flags:1 dts: 0.788345 pts: 0.788345 pos: 556280 size: 16384
+ret: 0         st: 0 flags:1 dts: 0.788345 pts: 0.788345 pos: 556288 size: 16384
 ret: 0         st: 0 flags:1  ts:-0.317506
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size: 16384
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size: 16384
 ret: 0         st:-1 flags:0  ts: 2.576668
-ret: 0         st: 0 flags:1 dts: 2.576667 pts: 2.576667 pos:1818120 size: 16384
+ret: 0         st: 0 flags:1 dts: 2.576667 pts: 2.576667 pos:1818128 size: 16384
 ret: 0         st:-1 flags:1  ts: 1.470835
-ret: 0         st: 0 flags:1 dts: 1.470839 pts: 1.470839 pos:1037848 size: 16384
+ret: 0         st: 0 flags:1 dts: 1.470839 pts: 1.470839 pos:1037856 size: 16384
 ret: 0         st: 0 flags:0  ts: 0.365011
-ret: 0         st: 0 flags:1 dts: 0.365011 pts: 0.365011 pos: 257576 size: 16384
+ret: 0         st: 0 flags:1 dts: 0.365011 pts: 0.365011 pos: 257584 size: 16384
 ret: 0         st: 0 flags:1  ts:-0.740839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size: 16384
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size: 16384
 ret: 0         st:-1 flags:0  ts: 2.153336
-ret: 0         st: 0 flags:1 dts: 2.153333 pts: 2.153333 pos:1519416 size: 16384
+ret: 0         st: 0 flags:1 dts: 2.153333 pts: 2.153333 pos:1519424 size: 16384
 ret: 0         st:-1 flags:1  ts: 1.047503
-ret: 0         st: 0 flags:1 dts: 1.047506 pts: 1.047506 pos: 739144 size: 16384
+ret: 0         st: 0 flags:1 dts: 1.047506 pts: 1.047506 pos: 739152 size: 16384
 ret: 0         st: 0 flags:0  ts:-0.058322
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size: 16384
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size: 16384
 ret: 0         st: 0 flags:1  ts: 2.835828
-ret: 0         st: 0 flags:1 dts: 2.835828 pts: 2.835828 pos:2000984 size: 16384
+ret: 0         st: 0 flags:1 dts: 2.835828 pts: 2.835828 pos:2000992 size: 16384
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.730000 pts: 1.730000 pos:1220712 size: 16384
+ret: 0         st: 0 flags:1 dts: 1.730000 pts: 1.730000 pos:1220720 size: 16384
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.624172 pts: 0.624172 pos: 440440 size: 16384
+ret: 0         st: 0 flags:1 dts: 0.624172 pts: 0.624172 pos: 440448 size: 16384
 ret: 0         st: 0 flags:0  ts:-0.481655
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size: 16384
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size: 16384
 ret: 0         st: 0 flags:1  ts: 2.412494
-ret: 0         st: 0 flags:1 dts: 2.412494 pts: 2.412494 pos:1702280 size: 16384
+ret: 0         st: 0 flags:1 dts: 2.412494 pts: 2.412494 pos:1702288 size: 16384
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.306667 pts: 1.306667 pos: 922008 size: 16384
+ret: 0         st: 0 flags:1 dts: 1.306667 pts: 1.306667 pos: 922016 size: 16384
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200839 pts: 0.200839 pos: 141736 size: 16384
+ret: 0         st: 0 flags:1 dts: 0.200839 pts: 0.200839 pos: 141744 size: 16384
 ret: 0         st: 0 flags:0  ts:-0.904989
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size: 16384
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size: 16384
 ret: 0         st: 0 flags:1  ts: 1.989184
-ret: 0         st: 0 flags:1 dts: 1.989184 pts: 1.989184 pos:1403592 size: 16384
+ret: 0         st: 0 flags:1 dts: 1.989184 pts: 1.989184 pos:1403600 size: 16384
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.883333 pts: 0.883333 pos: 623304 size: 16384
+ret: 0         st: 0 flags:1 dts: 0.883333 pts: 0.883333 pos: 623312 size: 16384
 ret: 0         st:-1 flags:1  ts:-0.222493
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size: 16384
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size: 16384
 ret: 0         st: 0 flags:0  ts: 2.671678
-ret: 0         st: 0 flags:1 dts: 2.671678 pts: 2.671678 pos:1885160 size: 16384
+ret: 0         st: 0 flags:1 dts: 2.671678 pts: 2.671678 pos:1885168 size: 16384
 ret: 0         st: 0 flags:1  ts: 1.565850
-ret: 0         st: 0 flags:1 dts: 1.565850 pts: 1.565850 pos:1104888 size: 16384
+ret: 0         st: 0 flags:1 dts: 1.565850 pts: 1.565850 pos:1104896 size: 16384
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.460000 pts: 0.460000 pos: 324600 size: 16384
+ret: 0         st: 0 flags:1 dts: 0.460000 pts: 0.460000 pos: 324608 size: 16384
 ret: 0         st:-1 flags:1  ts:-0.645825
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size: 16384
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size: 16384
diff --git a/tests/ref/seek/pcm_f64le_wav b/tests/ref/seek/acodec-pcm-f64le
similarity index 100%
rename from tests/ref/seek/pcm_f64le_wav
rename to tests/ref/seek/acodec-pcm-f64le
diff --git a/tests/ref/seek/pcm_alaw_wav b/tests/ref/seek/acodec-pcm-mulaw
similarity index 100%
copy from tests/ref/seek/pcm_alaw_wav
copy to tests/ref/seek/acodec-pcm-mulaw
diff --git a/tests/ref/seek/pcm_s16be_mov b/tests/ref/seek/acodec-pcm-s16be
similarity index 100%
rename from tests/ref/seek/pcm_s16be_mov
rename to tests/ref/seek/acodec-pcm-s16be
diff --git a/tests/ref/seek/pcm_s16le_wav b/tests/ref/seek/acodec-pcm-s16le
similarity index 100%
rename from tests/ref/seek/pcm_s16le_wav
rename to tests/ref/seek/acodec-pcm-s16le
diff --git a/tests/ref/seek/pcm_s24be_mov b/tests/ref/seek/acodec-pcm-s24be
similarity index 100%
rename from tests/ref/seek/pcm_s24be_mov
rename to tests/ref/seek/acodec-pcm-s24be
diff --git a/tests/ref/seek/pcm_s24le_wav b/tests/ref/seek/acodec-pcm-s24le
similarity index 100%
rename from tests/ref/seek/pcm_s24le_wav
rename to tests/ref/seek/acodec-pcm-s24le
diff --git a/tests/ref/seek/pcm_s32be_mov b/tests/ref/seek/acodec-pcm-s32be
similarity index 100%
rename from tests/ref/seek/pcm_s32be_mov
rename to tests/ref/seek/acodec-pcm-s32be
diff --git a/tests/ref/seek/pcm_s32le_wav b/tests/ref/seek/acodec-pcm-s32le
similarity index 100%
rename from tests/ref/seek/pcm_s32le_wav
rename to tests/ref/seek/acodec-pcm-s32le
diff --git a/tests/ref/seek/pcm_s8_mov b/tests/ref/seek/acodec-pcm-s8
similarity index 100%
rename from tests/ref/seek/pcm_s8_mov
rename to tests/ref/seek/acodec-pcm-s8
diff --git a/tests/ref/seek/pcm_u8_wav b/tests/ref/seek/acodec-pcm-u8
similarity index 100%
rename from tests/ref/seek/pcm_u8_wav
rename to tests/ref/seek/acodec-pcm-u8
diff --git a/tests/ref/seek/dnxhd_720p_rd_dnxhd b/tests/ref/seek/dnxhd_720p_rd_dnxhd
deleted file mode 100644
index b57f07d..0000000
--- a/tests/ref/seek/dnxhd_720p_rd_dnxhd
+++ /dev/null
@@ -1,40 +0,0 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:458752
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:458752
-ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 0.160000 pts: 0.160000 pos:1835008 size:458752
-ret:-1         st: 0 flags:0  ts: 0.788334
-ret:-1         st: 0 flags:1  ts:-0.317499
-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: 0.160000 pts: 0.160000 pos:1835008 size:458752
-ret:-1         st: 0 flags:0  ts: 0.365002
-ret:-1         st: 0 flags:1  ts:-0.740831
-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: 0.160000 pts: 0.160000 pos:1835008 size:458752
-ret: 0         st: 0 flags:0  ts:-0.058330
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:458752
-ret: 0         st: 0 flags:1  ts: 2.835837
-ret: 0         st: 0 flags:1 dts: 0.160000 pts: 0.160000 pos:1835008 size:458752
-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.160000 pts: 0.160000 pos:1835008 size:458752
-ret: 0         st: 0 flags:0  ts:-0.481662
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:458752
-ret: 0         st: 0 flags:1  ts: 2.412505
-ret: 0         st: 0 flags:1 dts: 0.160000 pts: 0.160000 pos:1835008 size:458752
-ret:-1         st:-1 flags:0  ts: 1.306672
-ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.160000 pts: 0.160000 pos:1835008 size:458752
-ret: 0         st: 0 flags:0  ts:-0.904994
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:458752
-ret: 0         st: 0 flags:1  ts: 1.989173
-ret: 0         st: 0 flags:1 dts: 0.160000 pts: 0.160000 pos:1835008 size:458752
-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.671674
-ret: 0         st: 0 flags:1  ts: 1.565841
-ret: 0         st: 0 flags:1 dts: 0.160000 pts: 0.160000 pos:1835008 size:458752
-ret:-1         st:-1 flags:0  ts: 0.460008
-ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/dv_dv b/tests/ref/seek/dv_dv
deleted file mode 100644
index d318794..0000000
--- a/tests/ref/seek/dv_dv
+++ /dev/null
@@ -1,53 +0,0 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:144000
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:144000
-ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos:6768000 size:144000
-ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:2880000 size:144000
-ret: 0         st: 0 flags:1  ts:-0.320000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:144000
-ret: 0         st:-1 flags:0  ts: 2.576668
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:7056000 size:144000
-ret: 0         st:-1 flags:1  ts: 1.470835
-ret: 0         st: 0 flags:1 dts: 1.480000 pts: 1.480000 pos:5328000 size:144000
-ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos:1296000 size:144000
-ret: 0         st: 0 flags:1  ts:-0.760000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:144000
-ret: 0         st:-1 flags:0  ts: 2.153336
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:7056000 size:144000
-ret: 0         st:-1 flags:1  ts: 1.047503
-ret: 0         st: 0 flags:1 dts: 1.040000 pts: 1.040000 pos:3744000 size:144000
-ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:144000
-ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:7056000 size:144000
-ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:6192000 size:144000
-ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:2304000 size:144000
-ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:144000
-ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:7056000 size:144000
-ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:4752000 size:144000
-ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos: 720000 size:144000
-ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:144000
-ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:7056000 size:144000
-ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:3168000 size:144000
-ret: 0         st:-1 flags:1  ts:-0.222493
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:144000
-ret: 0         st: 0 flags:0  ts: 2.680000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:7056000 size:144000
-ret: 0         st: 0 flags:1  ts: 1.560000
-ret: 0         st: 0 flags:1 dts: 1.560000 pts: 1.560000 pos:5616000 size:144000
-ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:1728000 size:144000
-ret: 0         st:-1 flags:1  ts:-0.645825
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:144000
diff --git a/tests/ref/seek/lavf_aif b/tests/ref/seek/lavf-aiff
similarity index 100%
rename from tests/ref/seek/lavf_aif
rename to tests/ref/seek/lavf-aiff
diff --git a/tests/ref/seek/lavf_al b/tests/ref/seek/lavf-alaw
similarity index 100%
rename from tests/ref/seek/lavf_al
rename to tests/ref/seek/lavf-alaw
diff --git a/tests/ref/seek/lavf_asf b/tests/ref/seek/lavf-asf
similarity index 100%
rename from tests/ref/seek/lavf_asf
rename to tests/ref/seek/lavf-asf
diff --git a/tests/ref/seek/lavf_au b/tests/ref/seek/lavf-au
similarity index 89%
copy from tests/ref/seek/lavf_au
copy to tests/ref/seek/lavf-au
index a2c57eb..d5a70b2 100644
--- a/tests/ref/seek/lavf_au
+++ b/tests/ref/seek/lavf-au
@@ -1,53 +1,53 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size:  2048
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size:  2048
 ret: 0         st:-1 flags:1  ts: 1.894167
 ret:-EOF
 ret: 0         st: 0 flags:0  ts: 0.788345
-ret: 0         st: 0 flags:1 dts: 0.788345 pts: 0.788345 pos:  69556 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.788345 pts: 0.788345 pos:  69564 size:  2048
 ret: 0         st: 0 flags:1  ts:-0.317506
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size:  2048
 ret: 0         st:-1 flags:0  ts: 2.576668
 ret:-EOF
 ret: 0         st:-1 flags:1  ts: 1.470835
 ret:-EOF
 ret: 0         st: 0 flags:0  ts: 0.365011
-ret: 0         st: 0 flags:1 dts: 0.365011 pts: 0.365011 pos:  32218 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.365011 pts: 0.365011 pos:  32226 size:  2048
 ret: 0         st: 0 flags:1  ts:-0.740839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size:  2048
 ret: 0         st:-1 flags:0  ts: 2.153336
 ret:-EOF
 ret: 0         st:-1 flags:1  ts: 1.047503
 ret:-EOF
 ret: 0         st: 0 flags:0  ts:-0.058322
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size:  2048
 ret: 0         st: 0 flags:1  ts: 2.835828
 ret:-EOF
 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.624172 pts: 0.624172 pos:  55076 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.624172 pts: 0.624172 pos:  55084 size:  2048
 ret: 0         st: 0 flags:0  ts:-0.481655
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size:  2048
 ret: 0         st: 0 flags:1  ts: 2.412494
 ret:-EOF
 ret: 0         st:-1 flags:0  ts: 1.306672
 ret:-EOF
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200839 pts: 0.200839 pos:  17738 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.200839 pts: 0.200839 pos:  17746 size:  2048
 ret: 0         st: 0 flags:0  ts:-0.904989
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size:  2048
 ret: 0         st: 0 flags:1  ts: 1.989184
 ret:-EOF
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.883333 pts: 0.883333 pos:  77934 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.883333 pts: 0.883333 pos:  77942 size:  2048
 ret: 0         st:-1 flags:1  ts:-0.222493
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size:  2048
 ret: 0         st: 0 flags:0  ts: 2.671678
 ret:-EOF
 ret: 0         st: 0 flags:1  ts: 1.565850
 ret:-EOF
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.460000 pts: 0.460000 pos:  40596 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.460000 pts: 0.460000 pos:  40604 size:  2048
 ret: 0         st:-1 flags:1  ts:-0.645825
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     32 size:  2048
diff --git a/tests/ref/seek/lavf_avi b/tests/ref/seek/lavf-avi
similarity index 100%
rename from tests/ref/seek/lavf_avi
rename to tests/ref/seek/lavf-avi
diff --git a/tests/ref/seek/image_bmp b/tests/ref/seek/lavf-bmp
similarity index 100%
rename from tests/ref/seek/image_bmp
rename to tests/ref/seek/lavf-bmp
diff --git a/tests/ref/seek/lavf_dv b/tests/ref/seek/lavf-dv_fmt
similarity index 100%
rename from tests/ref/seek/lavf_dv
rename to tests/ref/seek/lavf-dv_fmt
diff --git a/tests/ref/seek/lavf_ffm b/tests/ref/seek/lavf-ffm
similarity index 100%
rename from tests/ref/seek/lavf_ffm
rename to tests/ref/seek/lavf-ffm
diff --git a/tests/ref/seek/lavf_flv b/tests/ref/seek/lavf-flv_fmt
similarity index 100%
rename from tests/ref/seek/lavf_flv
rename to tests/ref/seek/lavf-flv_fmt
diff --git a/tests/ref/seek/lavf-gif b/tests/ref/seek/lavf-gif
new file mode 100644
index 0000000..0a2d1b3
--- /dev/null
+++ b/tests/ref/seek/lavf-gif
@@ -0,0 +1,40 @@
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:117024
+ret: 0         st:-1 flags:0  ts:-1.000000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:117024
+ret: 0         st:-1 flags:1  ts: 1.894167
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:117024
+ret:-1         st: 0 flags:0  ts: 0.790000
+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: 0.000000 pts: 0.000000 pos:      0 size:117024
+ret:-1         st: 0 flags:0  ts: 0.370000
+ret:-1         st: 0 flags:1  ts:-0.740000
+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: 0.000000 pts: 0.000000 pos:      0 size:117024
+ret: 0         st: 0 flags:0  ts:-0.060000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:117024
+ret: 0         st: 0 flags:1  ts: 2.840000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:117024
+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.000000 pts: 0.000000 pos:      0 size:117024
+ret: 0         st: 0 flags:0  ts:-0.480000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:117024
+ret: 0         st: 0 flags:1  ts: 2.410000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:117024
+ret:-1         st:-1 flags:0  ts: 1.306672
+ret: 0         st:-1 flags:1  ts: 0.200839
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:117024
+ret: 0         st: 0 flags:0  ts:-0.900000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:117024
+ret: 0         st: 0 flags:1  ts: 1.990000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:117024
+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.670000
+ret: 0         st: 0 flags:1  ts: 1.570000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:117024
+ret:-1         st:-1 flags:0  ts: 0.460008
+ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/lavf_gxf b/tests/ref/seek/lavf-gxf
similarity index 100%
rename from tests/ref/seek/lavf_gxf
rename to tests/ref/seek/lavf-gxf
diff --git a/tests/ref/seek/image_jpg b/tests/ref/seek/lavf-jpg
similarity index 100%
rename from tests/ref/seek/image_jpg
rename to tests/ref/seek/lavf-jpg
diff --git a/tests/ref/seek/lavf-mkv b/tests/ref/seek/lavf-mkv
new file mode 100644
index 0000000..681462c
--- /dev/null
+++ b/tests/ref/seek/lavf-mkv
@@ -0,0 +1,48 @@
+ret: 0         st: 1 flags:1 dts: 0.000000 pts: 0.000000 pos:    555 size:   208
+ret: 0         st:-1 flags:0  ts:-1.000000
+ret: 0         st: 0 flags:1 dts: 0.011000 pts: 0.011000 pos:    771 size: 27837
+ret: 0         st:-1 flags:1  ts: 1.894167
+ret: 0         st: 0 flags:1 dts: 0.971000 pts: 0.971000 pos: 292185 size: 27834
+ret: 0         st: 0 flags:0  ts: 0.788000
+ret: 0         st: 0 flags:1 dts: 0.971000 pts: 0.971000 pos: 292185 size: 27834
+ret: 0         st: 0 flags:1  ts:-0.317000
+ret: 0         st: 0 flags:1 dts: 0.011000 pts: 0.011000 pos:    771 size: 27837
+ret:-1         st: 1 flags:0  ts: 2.577000
+ret: 0         st: 1 flags:1  ts: 1.471000
+ret: 0         st: 1 flags:1 dts: 0.993000 pts: 0.993000 pos: 320026 size:   209
+ret: 0         st:-1 flags:0  ts: 0.365002
+ret: 0         st: 0 flags:1 dts: 0.491000 pts: 0.491000 pos: 146738 size: 27925
+ret: 0         st:-1 flags:1  ts:-0.740831
+ret: 0         st: 0 flags:1 dts: 0.011000 pts: 0.011000 pos:    771 size: 27837
+ret:-1         st: 0 flags:0  ts: 2.153000
+ret: 0         st: 0 flags:1  ts: 1.048000
+ret: 0         st: 0 flags:1 dts: 0.971000 pts: 0.971000 pos: 292185 size: 27834
+ret: 0         st: 1 flags:0  ts:-0.058000
+ret: 0         st: 1 flags:1 dts: 0.000000 pts: 0.000000 pos:    555 size:   208
+ret: 0         st: 1 flags:1  ts: 2.836000
+ret: 0         st: 1 flags:1 dts: 0.993000 pts: 0.993000 pos: 320026 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.491000 pts: 0.491000 pos: 146738 size: 27925
+ret: 0         st: 0 flags:0  ts:-0.482000
+ret: 0         st: 0 flags:1 dts: 0.011000 pts: 0.011000 pos:    771 size: 27837
+ret: 0         st: 0 flags:1  ts: 2.413000
+ret: 0         st: 0 flags:1 dts: 0.971000 pts: 0.971000 pos: 292185 size: 27834
+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.000000 pts: 0.000000 pos:    555 size:   208
+ret: 0         st:-1 flags:0  ts:-0.904994
+ret: 0         st: 0 flags:1 dts: 0.011000 pts: 0.011000 pos:    771 size: 27837
+ret: 0         st:-1 flags:1  ts: 1.989173
+ret: 0         st: 0 flags:1 dts: 0.971000 pts: 0.971000 pos: 292185 size: 27834
+ret: 0         st: 0 flags:0  ts: 0.883000
+ret: 0         st: 0 flags:1 dts: 0.971000 pts: 0.971000 pos: 292185 size: 27834
+ret: 0         st: 0 flags:1  ts:-0.222000
+ret: 0         st: 0 flags:1 dts: 0.011000 pts: 0.011000 pos:    771 size: 27837
+ret:-1         st: 1 flags:0  ts: 2.672000
+ret: 0         st: 1 flags:1  ts: 1.566000
+ret: 0         st: 1 flags:1 dts: 0.993000 pts: 0.993000 pos: 320026 size:   209
+ret: 0         st:-1 flags:0  ts: 0.460008
+ret: 0         st: 0 flags:1 dts: 0.491000 pts: 0.491000 pos: 146738 size: 27925
+ret: 0         st:-1 flags:1  ts:-0.645825
+ret: 0         st: 0 flags:1 dts: 0.011000 pts: 0.011000 pos:    771 size: 27837
diff --git a/tests/ref/seek/lavf_mmf b/tests/ref/seek/lavf-mmf
similarity index 100%
rename from tests/ref/seek/lavf_mmf
rename to tests/ref/seek/lavf-mmf
diff --git a/tests/ref/seek/lavf_mov b/tests/ref/seek/lavf-mov
similarity index 87%
rename from tests/ref/seek/lavf_mov
rename to tests/ref/seek/lavf-mov
index c321a8e..9563a0d 100644
--- a/tests/ref/seek/lavf_mov
+++ b/tests/ref/seek/lavf-mov
@@ -3,9 +3,9 @@
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   1727 size: 27837
 ret: 0         st:-1 flags:1  ts: 1.894167
 ret: 0         st: 1 flags:1 dts: 0.952018 pts: 0.952018 pos: 326931 size:  1024
-ret: 0         st: 0 flags:0  ts: 0.800000
+ret: 0         st: 0 flags:0  ts: 0.788359
 ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 327955 size: 27834
-ret: 0         st: 0 flags:1  ts:-0.320000
+ret: 0         st: 0 flags:1  ts:-0.317500
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   1727 size: 27837
 ret:-1         st: 1 flags:0  ts: 2.576667
 ret: 0         st: 1 flags:1  ts: 1.470839
@@ -14,8 +14,8 @@
 ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 165209 size: 27925
 ret: 0         st:-1 flags:1  ts:-0.740831
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   1727 size: 27837
-ret:-1         st: 0 flags:0  ts: 2.160000
-ret: 0         st: 0 flags:1  ts: 1.040000
+ret:-1         st: 0 flags:0  ts: 2.153359
+ret: 0         st: 0 flags:1  ts: 1.047500
 ret: 0         st: 1 flags:1 dts: 0.952018 pts: 0.952018 pos: 326931 size:  1024
 ret: 0         st: 1 flags:0  ts:-0.058322
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   1727 size: 27837
@@ -24,9 +24,9 @@
 ret:-1         st:-1 flags:0  ts: 1.730004
 ret: 0         st:-1 flags:1  ts: 0.624171
 ret: 0         st: 1 flags:1 dts: 0.464399 pts: 0.464399 pos: 164185 size:  1024
-ret: 0         st: 0 flags:0  ts:-0.480000
+ret: 0         st: 0 flags:0  ts:-0.481641
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   1727 size: 27837
-ret: 0         st: 0 flags:1  ts: 2.400000
+ret: 0         st: 0 flags:1  ts: 2.412500
 ret: 0         st: 1 flags:1 dts: 0.952018 pts: 0.952018 pos: 326931 size:  1024
 ret:-1         st: 1 flags:0  ts: 1.306667
 ret: 0         st: 1 flags:1  ts: 0.200839
@@ -35,9 +35,9 @@
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   1727 size: 27837
 ret: 0         st:-1 flags:1  ts: 1.989173
 ret: 0         st: 1 flags:1 dts: 0.952018 pts: 0.952018 pos: 326931 size:  1024
-ret: 0         st: 0 flags:0  ts: 0.880000
+ret: 0         st: 0 flags:0  ts: 0.883359
 ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 327955 size: 27834
-ret: 0         st: 0 flags:1  ts:-0.240000
+ret: 0         st: 0 flags:1  ts:-0.222500
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   1727 size: 27837
 ret:-1         st: 1 flags:0  ts: 2.671678
 ret: 0         st: 1 flags:1  ts: 1.565850
diff --git a/tests/ref/seek/lavf_mpg b/tests/ref/seek/lavf-mpg
similarity index 100%
rename from tests/ref/seek/lavf_mpg
rename to tests/ref/seek/lavf-mpg
diff --git a/tests/ref/seek/lavf_al b/tests/ref/seek/lavf-mulaw
similarity index 100%
copy from tests/ref/seek/lavf_al
copy to tests/ref/seek/lavf-mulaw
diff --git a/tests/ref/seek/lavf_mxf b/tests/ref/seek/lavf-mxf
similarity index 85%
rename from tests/ref/seek/lavf_mxf
rename to tests/ref/seek/lavf-mxf
index f7d1f67..34dddc3 100644
--- a/tests/ref/seek/lavf_mxf
+++ b/tests/ref/seek/lavf-mxf
@@ -7,8 +7,8 @@
 ret: 0         st: 0 flags:1 dts: 0.840000 pts: 0.960000 pos: 460288 size: 24711
 ret: 0         st: 0 flags:1  ts:-0.320000
 ret: 0         st: 0 flags:1 dts:-0.040000 pts: 0.000000 pos:   6144 size: 24801
-ret:-1         st: 1 flags:0  ts: 2.560000
-ret: 0         st: 1 flags:1  ts: 1.480000
+ret:-1         st: 1 flags:0  ts: 2.576667
+ret: 0         st: 1 flags:1  ts: 1.470833
 ret: 0         st: 0 flags:1 dts: 0.840000 pts: 0.960000 pos: 460288 size: 24711
 ret: 0         st:-1 flags:0  ts: 0.365002
 ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.480000 pos: 211456 size: 24786
@@ -17,9 +17,9 @@
 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.840000 pts: 0.960000 pos: 460288 size: 24711
-ret: 0         st: 1 flags:0  ts:-0.040000
+ret: 0         st: 1 flags:0  ts:-0.058333
 ret: 0         st: 0 flags:1 dts:-0.040000 pts: 0.000000 pos:   6144 size: 24801
-ret: 0         st: 1 flags:1  ts: 2.840000
+ret: 0         st: 1 flags:1  ts: 2.835833
 ret: 0         st: 0 flags:1 dts: 0.840000 pts: 0.960000 pos: 460288 size: 24711
 ret:-1         st:-1 flags:0  ts: 1.730004
 ret: 0         st:-1 flags:1  ts: 0.624171
@@ -28,9 +28,9 @@
 ret: 0         st: 0 flags:1 dts:-0.040000 pts: 0.000000 pos:   6144 size: 24801
 ret: 0         st: 0 flags:1  ts: 2.400000
 ret: 0         st: 0 flags:1 dts: 0.840000 pts: 0.960000 pos: 460288 size: 24711
-ret:-1         st: 1 flags:0  ts: 1.320000
-ret: 0         st: 1 flags:1  ts: 0.200000
-ret: 0         st: 0 flags:1 dts:-0.040000 pts: 0.000000 pos:   6144 size: 24801
+ret:-1         st: 1 flags:0  ts: 1.306667
+ret: 0         st: 1 flags:1  ts: 0.200833
+ret: 0         st: 0 flags:1 dts: 0.840000 pts: 0.960000 pos: 460288 size: 24711
 ret: 0         st:-1 flags:0  ts:-0.904994
 ret: 0         st: 0 flags:1 dts:-0.040000 pts: 0.000000 pos:   6144 size: 24801
 ret: 0         st:-1 flags:1  ts: 1.989173
@@ -39,8 +39,8 @@
 ret: 0         st: 0 flags:1 dts: 0.840000 pts: 0.960000 pos: 460288 size: 24711
 ret: 0         st: 0 flags:1  ts:-0.240000
 ret: 0         st: 0 flags:1 dts:-0.040000 pts: 0.000000 pos:   6144 size: 24801
-ret:-1         st: 1 flags:0  ts: 2.680000
-ret: 0         st: 1 flags:1  ts: 1.560000
+ret:-1         st: 1 flags:0  ts: 2.671667
+ret: 0         st: 1 flags:1  ts: 1.565833
 ret: 0         st: 0 flags:1 dts: 0.840000 pts: 0.960000 pos: 460288 size: 24711
 ret: 0         st:-1 flags:0  ts: 0.460008
 ret: 0         st: 0 flags:1 dts: 0.840000 pts: 0.960000 pos: 460288 size: 24711
diff --git a/tests/ref/seek/lavf_mxf_d10 b/tests/ref/seek/lavf-mxf_d10
similarity index 75%
rename from tests/ref/seek/lavf_mxf_d10
rename to tests/ref/seek/lavf-mxf_d10
index 4cfe595..e091c77 100644
--- a/tests/ref/seek/lavf_mxf_d10
+++ b/tests/ref/seek/lavf-mxf_d10
@@ -7,10 +7,10 @@
 ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:4265984 size:150000
 ret: 0         st: 0 flags:1  ts:-0.320000
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   6144 size:150000
-ret: 0         st: 1 flags:0  ts: 2.560000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:5117952 size:150000
-ret: 0         st: 1 flags:1  ts: 1.480000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:5117952 size:150000
+ret: 0         st: 1 flags:0  ts: 2.576667
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:5117952 size:150000
+ret: 0         st: 1 flags:1  ts: 1.470833
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:5117952 size:150000
 ret: 0         st:-1 flags:0  ts: 0.365002
 ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos:1923072 size:150000
 ret: 0         st:-1 flags:1  ts:-0.740831
@@ -19,10 +19,10 @@
 ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:5117952 size:150000
 ret: 0         st: 0 flags:1  ts: 1.040000
 ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:5117952 size:150000
-ret: 0         st: 1 flags:0  ts:-0.040000
+ret: 0         st: 1 flags:0  ts:-0.058333
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   6144 size:150000
-ret: 0         st: 1 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:5117952 size:150000
+ret: 0         st: 1 flags:1  ts: 2.835833
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:5117952 size:150000
 ret: 0         st:-1 flags:0  ts: 1.730004
 ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:5117952 size:150000
 ret: 0         st:-1 flags:1  ts: 0.624171
@@ -31,10 +31,10 @@
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   6144 size:150000
 ret: 0         st: 0 flags:1  ts: 2.400000
 ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:5117952 size:150000
-ret: 0         st: 1 flags:0  ts: 1.320000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:5117952 size:150000
-ret: 0         st: 1 flags:1  ts: 0.200000
-ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos:1071104 size:150000
+ret: 0         st: 1 flags:0  ts: 1.306667
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:5117952 size:150000
+ret: 0         st: 1 flags:1  ts: 0.200833
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:5117952 size:150000
 ret: 0         st:-1 flags:0  ts:-0.904994
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   6144 size:150000
 ret: 0         st:-1 flags:1  ts: 1.989173
@@ -43,10 +43,10 @@
 ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:4691968 size:150000
 ret: 0         st: 0 flags:1  ts:-0.240000
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   6144 size:150000
-ret: 0         st: 1 flags:0  ts: 2.680000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:5117952 size:150000
-ret: 0         st: 1 flags:1  ts: 1.560000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:5117952 size:150000
+ret: 0         st: 1 flags:0  ts: 2.671667
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:5117952 size:150000
+ret: 0         st: 1 flags:1  ts: 1.565833
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:5117952 size:150000
 ret: 0         st:-1 flags:0  ts: 0.460008
 ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:2562048 size:150000
 ret: 0         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/lavf-nut b/tests/ref/seek/lavf-nut
new file mode 100644
index 0000000..ef47ceb
--- /dev/null
+++ b/tests/ref/seek/lavf-nut
@@ -0,0 +1,53 @@
+ret: 0         st: 1 flags:1 dts: 0.000000 pts: 0.000000 pos:    339 size:   208
+ret: 0         st:-1 flags:0  ts:-1.000000
+ret: 0         st: 0 flags:1 dts: 0.010918 pts: 0.010918 pos:    567 size: 27837
+ret: 0         st:-1 flags:1  ts: 1.894167
+ret: 0         st: 0 flags:1 dts: 0.490918 pts: 0.490918 pos: 146434 size: 27925
+ret: 0         st: 0 flags:0  ts: 0.788340
+ret: 0         st: 0 flags:1 dts: 0.490918 pts: 0.490918 pos: 146434 size: 27925
+ret: 0         st: 0 flags:1  ts:-0.317500
+ret: 0         st: 0 flags:1 dts: 0.010918 pts: 0.010918 pos:    567 size: 27837
+ret: 0         st: 1 flags:0  ts: 2.576667
+ret: 0         st: 1 flags:1 dts: 0.862041 pts: 0.862041 pos: 271259 size:   209
+ret: 0         st: 1 flags:1  ts: 1.470839
+ret: 0         st: 1 flags:1 dts: 0.862041 pts: 0.862041 pos: 271259 size:   209
+ret: 0         st:-1 flags:0  ts: 0.365002
+ret: 0         st: 0 flags:1 dts: 0.490918 pts: 0.490918 pos: 146434 size: 27925
+ret: 0         st:-1 flags:1  ts:-0.740831
+ret: 0         st: 0 flags:1 dts: 0.010918 pts: 0.010918 pos:    567 size: 27837
+ret: 0         st: 0 flags:0  ts: 2.153340
+ret: 0         st: 0 flags:1 dts: 0.490918 pts: 0.490918 pos: 146434 size: 27925
+ret: 0         st: 0 flags:1  ts: 1.047500
+ret: 0         st: 0 flags:1 dts: 0.490918 pts: 0.490918 pos: 146434 size: 27925
+ret: 0         st: 1 flags:0  ts:-0.058322
+ret: 0         st: 1 flags:1 dts: 0.000000 pts: 0.000000 pos:    339 size:   208
+ret: 0         st: 1 flags:1  ts: 2.835828
+ret: 0         st: 1 flags:1 dts: 0.862041 pts: 0.862041 pos: 271259 size:   209
+ret: 0         st:-1 flags:0  ts: 1.730004
+ret: 0         st: 0 flags:1 dts: 0.490918 pts: 0.490918 pos: 146434 size: 27925
+ret: 0         st:-1 flags:1  ts: 0.624171
+ret: 0         st: 0 flags:1 dts: 0.490918 pts: 0.490918 pos: 146434 size: 27925
+ret: 0         st: 0 flags:0  ts:-0.481660
+ret: 0         st: 0 flags:1 dts: 0.010918 pts: 0.010918 pos:    567 size: 27837
+ret: 0         st: 0 flags:1  ts: 2.412500
+ret: 0         st: 0 flags:1 dts: 0.490918 pts: 0.490918 pos: 146434 size: 27925
+ret: 0         st: 1 flags:0  ts: 1.306667
+ret: 0         st: 1 flags:1 dts: 0.862041 pts: 0.862041 pos: 271259 size:   209
+ret: 0         st: 1 flags:1  ts: 0.200839
+ret: 0         st: 1 flags:1 dts: 0.182857 pts: 0.182857 pos:  71901 size:   209
+ret: 0         st:-1 flags:0  ts:-0.904994
+ret: 0         st: 0 flags:1 dts: 0.010918 pts: 0.010918 pos:    567 size: 27837
+ret: 0         st:-1 flags:1  ts: 1.989173
+ret: 0         st: 0 flags:1 dts: 0.490918 pts: 0.490918 pos: 146434 size: 27925
+ret: 0         st: 0 flags:0  ts: 0.883340
+ret: 0         st: 0 flags:1 dts: 0.490918 pts: 0.490918 pos: 146434 size: 27925
+ret: 0         st: 0 flags:1  ts:-0.222500
+ret: 0         st: 0 flags:1 dts: 0.010918 pts: 0.010918 pos:    567 size: 27837
+ret: 0         st: 1 flags:0  ts: 2.671678
+ret: 0         st: 1 flags:1 dts: 0.862041 pts: 0.862041 pos: 271259 size:   209
+ret: 0         st: 1 flags:1  ts: 1.565850
+ret: 0         st: 1 flags:1 dts: 0.862041 pts: 0.862041 pos: 271259 size:   209
+ret: 0         st:-1 flags:0  ts: 0.460008
+ret: 0         st: 0 flags:1 dts: 0.490918 pts: 0.490918 pos: 146434 size: 27925
+ret: 0         st:-1 flags:1  ts:-0.645825
+ret: 0         st: 0 flags:1 dts: 0.010918 pts: 0.010918 pos:    567 size: 27837
diff --git a/tests/ref/seek/lavf_ogg b/tests/ref/seek/lavf-ogg
similarity index 100%
rename from tests/ref/seek/lavf_ogg
rename to tests/ref/seek/lavf-ogg
diff --git a/tests/ref/seek/pbmpipe_pbm b/tests/ref/seek/lavf-pbmpipe
similarity index 100%
rename from tests/ref/seek/pbmpipe_pbm
rename to tests/ref/seek/lavf-pbmpipe
diff --git a/tests/ref/seek/image_pcx b/tests/ref/seek/lavf-pcx
similarity index 100%
rename from tests/ref/seek/image_pcx
rename to tests/ref/seek/lavf-pcx
diff --git a/tests/ref/seek/image_pgm b/tests/ref/seek/lavf-pgm
similarity index 100%
rename from tests/ref/seek/image_pgm
rename to tests/ref/seek/lavf-pgm
diff --git a/tests/ref/seek/pgmpipe_pgm b/tests/ref/seek/lavf-pgmpipe
similarity index 100%
rename from tests/ref/seek/pgmpipe_pgm
rename to tests/ref/seek/lavf-pgmpipe
diff --git a/tests/ref/seek/image_ppm b/tests/ref/seek/lavf-ppm
similarity index 100%
rename from tests/ref/seek/image_ppm
rename to tests/ref/seek/lavf-ppm
diff --git a/tests/ref/seek/ppmpipe_ppm b/tests/ref/seek/lavf-ppmpipe
similarity index 100%
rename from tests/ref/seek/ppmpipe_ppm
rename to tests/ref/seek/lavf-ppmpipe
diff --git a/tests/ref/seek/lavf_rm b/tests/ref/seek/lavf-rm
similarity index 100%
rename from tests/ref/seek/lavf_rm
rename to tests/ref/seek/lavf-rm
diff --git a/tests/ref/seek/image_sgi b/tests/ref/seek/lavf-sgi
similarity index 100%
rename from tests/ref/seek/image_sgi
rename to tests/ref/seek/lavf-sgi
diff --git a/tests/ref/seek/lavf_swf b/tests/ref/seek/lavf-swf
similarity index 100%
rename from tests/ref/seek/lavf_swf
rename to tests/ref/seek/lavf-swf
diff --git a/tests/ref/seek/image_tga b/tests/ref/seek/lavf-tga
similarity index 100%
rename from tests/ref/seek/image_tga
rename to tests/ref/seek/lavf-tga
diff --git a/tests/ref/seek/image_tiff b/tests/ref/seek/lavf-tiff
similarity index 100%
rename from tests/ref/seek/image_tiff
rename to tests/ref/seek/lavf-tiff
diff --git a/tests/ref/seek/lavf_ts b/tests/ref/seek/lavf-ts
similarity index 100%
rename from tests/ref/seek/lavf_ts
rename to tests/ref/seek/lavf-ts
diff --git a/tests/ref/seek/lavf_voc b/tests/ref/seek/lavf-voc
similarity index 100%
rename from tests/ref/seek/lavf_voc
rename to tests/ref/seek/lavf-voc
diff --git a/tests/ref/seek/lavf_au b/tests/ref/seek/lavf-wav
similarity index 89%
rename from tests/ref/seek/lavf_au
rename to tests/ref/seek/lavf-wav
index a2c57eb..16a33be 100644
--- a/tests/ref/seek/lavf_au
+++ b/tests/ref/seek/lavf-wav
@@ -1,53 +1,53 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     76 size:  4096
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     76 size:  4096
 ret: 0         st:-1 flags:1  ts: 1.894167
 ret:-EOF
 ret: 0         st: 0 flags:0  ts: 0.788345
-ret: 0         st: 0 flags:1 dts: 0.788345 pts: 0.788345 pos:  69556 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.788345 pts: 0.788345 pos:  69608 size:  4096
 ret: 0         st: 0 flags:1  ts:-0.317506
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     76 size:  4096
 ret: 0         st:-1 flags:0  ts: 2.576668
 ret:-EOF
 ret: 0         st:-1 flags:1  ts: 1.470835
 ret:-EOF
 ret: 0         st: 0 flags:0  ts: 0.365011
-ret: 0         st: 0 flags:1 dts: 0.365011 pts: 0.365011 pos:  32218 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.365011 pts: 0.365011 pos:  32270 size:  4096
 ret: 0         st: 0 flags:1  ts:-0.740839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     76 size:  4096
 ret: 0         st:-1 flags:0  ts: 2.153336
 ret:-EOF
 ret: 0         st:-1 flags:1  ts: 1.047503
 ret:-EOF
 ret: 0         st: 0 flags:0  ts:-0.058322
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     76 size:  4096
 ret: 0         st: 0 flags:1  ts: 2.835828
 ret:-EOF
 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.624172 pts: 0.624172 pos:  55076 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.624172 pts: 0.624172 pos:  55128 size:  4096
 ret: 0         st: 0 flags:0  ts:-0.481655
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     76 size:  4096
 ret: 0         st: 0 flags:1  ts: 2.412494
 ret:-EOF
 ret: 0         st:-1 flags:0  ts: 1.306672
 ret:-EOF
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200839 pts: 0.200839 pos:  17738 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.200839 pts: 0.200839 pos:  17790 size:  4096
 ret: 0         st: 0 flags:0  ts:-0.904989
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     76 size:  4096
 ret: 0         st: 0 flags:1  ts: 1.989184
 ret:-EOF
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.883333 pts: 0.883333 pos:  77934 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.883333 pts: 0.883333 pos:  77986 size:  4096
 ret: 0         st:-1 flags:1  ts:-0.222493
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     76 size:  4096
 ret: 0         st: 0 flags:0  ts: 2.671678
 ret:-EOF
 ret: 0         st: 0 flags:1  ts: 1.565850
 ret:-EOF
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.460000 pts: 0.460000 pos:  40596 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.460000 pts: 0.460000 pos:  40648 size:  4096
 ret: 0         st:-1 flags:1  ts:-0.645825
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     24 size:  2048
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     76 size:  4096
diff --git a/tests/ref/seek/lavf-wtv b/tests/ref/seek/lavf-wtv
new file mode 100644
index 0000000..67def8a
--- /dev/null
+++ b/tests/ref/seek/lavf-wtv
@@ -0,0 +1,48 @@
+ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  26344 size:   208
+ret: 0         st:-1 flags:0  ts:-1.000000
+ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  26344 size:   208
+ret: 0         st:-1 flags:1  ts: 1.894167
+ret: 0         st: 1 flags:1 dts: 0.694399 pts: 0.694399 pos: 294744 size:   209
+ret: 0         st: 0 flags:0  ts: 0.788334
+ret: 0         st: 1 flags:1 dts: 0.694399 pts: 0.694399 pos: 294744 size:   209
+ret: 0         st: 0 flags:1  ts:-0.317499
+ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  26344 size:   208
+ret:-1         st: 1 flags:0  ts: 2.576668
+ret: 0         st: 1 flags:1  ts: 1.470835
+ret: 0         st: 1 flags:1 dts: 0.694399 pts: 0.694399 pos: 294744 size:   209
+ret: 0         st:-1 flags:0  ts: 0.365002
+ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  26344 size:   208
+ret: 0         st:-1 flags:1  ts:-0.740831
+ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  26344 size:   208
+ret:-1         st: 0 flags:0  ts: 2.153336
+ret: 0         st: 0 flags:1  ts: 1.047503
+ret: 0         st: 1 flags:1 dts: 0.694399 pts: 0.694399 pos: 294744 size:   209
+ret: 0         st: 1 flags:0  ts:-0.058330
+ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  26344 size:   208
+ret: 0         st: 1 flags:1  ts: 2.835837
+ret: 0         st: 1 flags:1 dts: 0.694399 pts: 0.694399 pos: 294744 size:   209
+ret:-1         st:-1 flags:0  ts: 1.730004
+ret: 0         st:-1 flags:1  ts: 0.624171
+ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  26344 size:   208
+ret: 0         st: 0 flags:0  ts:-0.481662
+ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  26344 size:   208
+ret: 0         st: 0 flags:1  ts: 2.412505
+ret: 0         st: 1 flags:1 dts: 0.694399 pts: 0.694399 pos: 294744 size:   209
+ret:-1         st: 1 flags:0  ts: 1.306672
+ret: 0         st: 1 flags:1  ts: 0.200839
+ret: 0         st: 1 flags:1 dts: 0.224195 pts: 0.224195 pos: 112904 size:   209
+ret: 0         st:-1 flags:0  ts:-0.904994
+ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  26344 size:   208
+ret: 0         st:-1 flags:1  ts: 1.989173
+ret: 0         st: 1 flags:1 dts: 0.694399 pts: 0.694399 pos: 294744 size:   209
+ret: 0         st: 0 flags:0  ts: 0.883340
+ret: 0         st: 1 flags:1 dts: 0.694399 pts: 0.694399 pos: 294744 size:   209
+ret: 0         st: 0 flags:1  ts:-0.222493
+ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  26344 size:   208
+ret:-1         st: 1 flags:0  ts: 2.671674
+ret: 0         st: 1 flags:1  ts: 1.565841
+ret: 0         st: 1 flags:1 dts: 0.694399 pts: 0.694399 pos: 294744 size:   209
+ret: 0         st:-1 flags:0  ts: 0.460008
+ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  26344 size:   208
+ret: 0         st:-1 flags:1  ts:-0.645825
+ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  26344 size:   208
diff --git a/tests/ref/seek/lavf_y4m b/tests/ref/seek/lavf-yuv4mpeg
similarity index 100%
rename from tests/ref/seek/lavf_y4m
rename to tests/ref/seek/lavf-yuv4mpeg
diff --git a/tests/ref/seek/lavf_gif b/tests/ref/seek/lavf_gif
deleted file mode 100644
index 883f187..0000000
--- a/tests/ref/seek/lavf_gif
+++ /dev/null
@@ -1,27 +0,0 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     -1 size:2906401
-ret:-EINVAL    st:-1 flags:0  ts:-1.000000
-ret:-EINVAL    st:-1 flags:1  ts: 1.894167
-ret:-EINVAL    st: 0 flags:0  ts: 0.800000
-ret:-EINVAL    st: 0 flags:1  ts:-0.320000
-ret:-EINVAL    st:-1 flags:0  ts: 2.576668
-ret:-EINVAL    st:-1 flags:1  ts: 1.470835
-ret:-EINVAL    st: 0 flags:0  ts: 0.360000
-ret:-EINVAL    st: 0 flags:1  ts:-0.760000
-ret:-EINVAL    st:-1 flags:0  ts: 2.153336
-ret:-EINVAL    st:-1 flags:1  ts: 1.047503
-ret:-EINVAL    st: 0 flags:0  ts:-0.040000
-ret:-EINVAL    st: 0 flags:1  ts: 2.840000
-ret:-EINVAL    st:-1 flags:0  ts: 1.730004
-ret:-EINVAL    st:-1 flags:1  ts: 0.624171
-ret:-EINVAL    st: 0 flags:0  ts:-0.480000
-ret:-EINVAL    st: 0 flags:1  ts: 2.400000
-ret:-EINVAL    st:-1 flags:0  ts: 1.306672
-ret:-EINVAL    st:-1 flags:1  ts: 0.200839
-ret:-EINVAL    st: 0 flags:0  ts:-0.920000
-ret:-EINVAL    st: 0 flags:1  ts: 2.000000
-ret:-EINVAL    st:-1 flags:0  ts: 0.883340
-ret:-EINVAL    st:-1 flags:1  ts:-0.222493
-ret:-EINVAL    st: 0 flags:0  ts: 2.680000
-ret:-EINVAL    st: 0 flags:1  ts: 1.560000
-ret:-EINVAL    st:-1 flags:0  ts: 0.460008
-ret:-EINVAL    st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/lavf_mkv b/tests/ref/seek/lavf_mkv
deleted file mode 100644
index ece15a1..0000000
--- a/tests/ref/seek/lavf_mkv
+++ /dev/null
@@ -1,48 +0,0 @@
-ret: 0         st: 1 flags:1 dts:-0.011000 pts:-0.011000 pos:    555 size:   208
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 1 flags:1 dts: 0.000000 pts: 0.000000 pos:    555 size:   208
-ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 292185 size: 27834
-ret: 0         st: 0 flags:0  ts: 0.788000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 292185 size: 27834
-ret: 0         st: 0 flags:1  ts:-0.317000
-ret: 0         st: 1 flags:1 dts: 0.000000 pts: 0.000000 pos:    555 size:   208
-ret:-1         st: 1 flags:0  ts: 2.577000
-ret: 0         st: 1 flags:1  ts: 1.471000
-ret: 0         st: 1 flags:1 dts: 0.982000 pts: 0.982000 pos: 320026 size:   209
-ret: 0         st:-1 flags:0  ts: 0.365002
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146738 size: 27925
-ret: 0         st:-1 flags:1  ts:-0.740831
-ret: 0         st: 1 flags:1 dts: 0.000000 pts: 0.000000 pos:    555 size:   208
-ret:-1         st: 0 flags:0  ts: 2.153000
-ret: 0         st: 0 flags:1  ts: 1.048000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 292185 size: 27834
-ret: 0         st: 1 flags:0  ts:-0.058000
-ret: 0         st: 1 flags:1 dts: 0.015000 pts: 0.015000 pos:    555 size:   208
-ret: 0         st: 1 flags:1  ts: 2.836000
-ret: 0         st: 1 flags:1 dts: 0.982000 pts: 0.982000 pos: 320026 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: 146738 size: 27925
-ret: 0         st: 0 flags:0  ts:-0.482000
-ret: 0         st: 1 flags:1 dts: 0.000000 pts: 0.000000 pos:    555 size:   208
-ret: 0         st: 0 flags:1  ts: 2.413000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 292185 size: 27834
-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.015000 pts: 0.015000 pos:    555 size:   208
-ret: 0         st:-1 flags:0  ts:-0.904994
-ret: 0         st: 1 flags:1 dts: 0.000000 pts: 0.000000 pos:    555 size:   208
-ret: 0         st:-1 flags:1  ts: 1.989173
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 292185 size: 27834
-ret: 0         st: 0 flags:0  ts: 0.883000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 292185 size: 27834
-ret: 0         st: 0 flags:1  ts:-0.222000
-ret: 0         st: 1 flags:1 dts: 0.000000 pts: 0.000000 pos:    555 size:   208
-ret:-1         st: 1 flags:0  ts: 2.672000
-ret: 0         st: 1 flags:1  ts: 1.566000
-ret: 0         st: 1 flags:1 dts: 0.982000 pts: 0.982000 pos: 320026 size:   209
-ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146738 size: 27925
-ret: 0         st:-1 flags:1  ts:-0.645825
-ret: 0         st: 1 flags:1 dts: 0.000000 pts: 0.000000 pos:    555 size:   208
diff --git a/tests/ref/seek/lavf_nut b/tests/ref/seek/lavf_nut
deleted file mode 100644
index 83c7758..0000000
--- a/tests/ref/seek/lavf_nut
+++ /dev/null
@@ -1,53 +0,0 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    295 size: 27837
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    295 size: 27837
-ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146337 size: 27925
-ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146337 size: 27925
-ret: 0         st: 0 flags:1  ts:-0.320000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    295 size: 27837
-ret: 0         st: 1 flags:0  ts: 2.586122
-ret: 0         st: 1 flags:1 dts: 0.862041 pts: 0.862041 pos: 271130 size:   209
-ret: 0         st: 1 flags:1  ts: 1.462857
-ret: 0         st: 1 flags:1 dts: 0.862041 pts: 0.862041 pos: 271130 size:   209
-ret: 0         st:-1 flags:0  ts: 0.365002
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146337 size: 27925
-ret: 0         st:-1 flags:1  ts:-0.740831
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    295 size: 27837
-ret: 0         st: 0 flags:0  ts: 2.160000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146337 size: 27925
-ret: 0         st: 0 flags:1  ts: 1.040000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146337 size: 27925
-ret: 0         st: 1 flags:0  ts:-0.052245
-ret: 0         st: 1 flags:1 dts: 0.000000 pts: 0.000000 pos:  28149 size:   208
-ret: 0         st: 1 flags:1  ts: 2.847347
-ret: 0         st: 1 flags:1 dts: 0.862041 pts: 0.862041 pos: 271130 size:   209
-ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146337 size: 27925
-ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146337 size: 27925
-ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    295 size: 27837
-ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146337 size: 27925
-ret: 0         st: 1 flags:0  ts: 1.306122
-ret: 0         st: 1 flags:1 dts: 0.862041 pts: 0.862041 pos: 271130 size:   209
-ret: 0         st: 1 flags:1  ts: 0.208980
-ret: 0         st: 1 flags:1 dts: 0.182857 pts: 0.182857 pos:  71817 size:   209
-ret: 0         st:-1 flags:0  ts:-0.904994
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    295 size: 27837
-ret: 0         st:-1 flags:1  ts: 1.989173
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146337 size: 27925
-ret: 0         st: 0 flags:0  ts: 0.880000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146337 size: 27925
-ret: 0         st: 0 flags:1  ts:-0.240000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    295 size: 27837
-ret: 0         st: 1 flags:0  ts: 2.664490
-ret: 0         st: 1 flags:1 dts: 0.862041 pts: 0.862041 pos: 271130 size:   209
-ret: 0         st: 1 flags:1  ts: 1.567347
-ret: 0         st: 1 flags:1 dts: 0.862041 pts: 0.862041 pos: 271130 size:   209
-ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146337 size: 27925
-ret: 0         st:-1 flags:1  ts:-0.645825
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:    295 size: 27837
diff --git a/tests/ref/seek/lavf_ul b/tests/ref/seek/lavf_ul
deleted file mode 100644
index 84661ec..0000000
--- a/tests/ref/seek/lavf_ul
+++ /dev/null
@@ -1,53 +0,0 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:  1024
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:  1024
-ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.894150 pts: 1.894150 pos:  41766 size:  1024
-ret: 0         st: 0 flags:0  ts: 0.788345
-ret: 0         st: 0 flags:1 dts: 0.788345 pts: 0.788345 pos:  17383 size:  1024
-ret: 0         st: 0 flags:1  ts:-0.317506
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:  1024
-ret: 0         st:-1 flags:0  ts: 2.576668
-ret:-EOF
-ret: 0         st:-1 flags:1  ts: 1.470835
-ret: 0         st: 0 flags:1 dts: 1.470839 pts: 1.470839 pos:  32432 size:  1024
-ret: 0         st: 0 flags:0  ts: 0.364989
-ret: 0         st: 0 flags:1 dts: 0.364989 pts: 0.364989 pos:   8048 size:  1024
-ret: 0         st: 0 flags:1  ts:-0.740816
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:  1024
-ret: 0         st:-1 flags:0  ts: 2.153336
-ret:-EOF
-ret: 0         st:-1 flags:1  ts: 1.047503
-ret: 0         st: 0 flags:1 dts: 1.047483 pts: 1.047483 pos:  23097 size:  1024
-ret: 0         st: 0 flags:0  ts:-0.058322
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:  1024
-ret: 0         st: 0 flags:1  ts: 2.835828
-ret:-EOF
-ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.730023 pts: 1.730023 pos:  38147 size:  1024
-ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.624172 pts: 0.624172 pos:  13763 size:  1024
-ret: 0         st: 0 flags:0  ts:-0.481678
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:  1024
-ret: 0         st: 0 flags:1  ts: 2.412517
-ret:-EOF
-ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.306667 pts: 1.306667 pos:  28812 size:  1024
-ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200816 pts: 0.200816 pos:   4428 size:  1024
-ret: 0         st: 0 flags:0  ts:-0.904989
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:  1024
-ret: 0         st: 0 flags:1  ts: 1.989161
-ret: 0         st: 0 flags:1 dts: 1.989161 pts: 1.989161 pos:  43861 size:  1024
-ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.883356 pts: 0.883356 pos:  19478 size:  1024
-ret: 0         st:-1 flags:1  ts:-0.222493
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:  1024
-ret: 0         st: 0 flags:0  ts: 2.671655
-ret:-EOF
-ret: 0         st: 0 flags:1  ts: 1.565850
-ret: 0         st: 0 flags:1 dts: 1.565850 pts: 1.565850 pos:  34527 size:  1024
-ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.460000 pts: 0.460000 pos:  10143 size:  1024
-ret: 0         st:-1 flags:1  ts:-0.645825
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:      0 size:  1024
diff --git a/tests/ref/seek/lavf_wav b/tests/ref/seek/lavf_wav
deleted file mode 100644
index 1a9cfc5..0000000
--- a/tests/ref/seek/lavf_wav
+++ /dev/null
@@ -1,53 +0,0 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     46 size:  4096
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     46 size:  4096
-ret: 0         st:-1 flags:1  ts: 1.894167
-ret:-EOF
-ret: 0         st: 0 flags:0  ts: 0.788345
-ret: 0         st: 0 flags:1 dts: 0.788345 pts: 0.788345 pos:  69578 size:  4096
-ret: 0         st: 0 flags:1  ts:-0.317506
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     46 size:  4096
-ret: 0         st:-1 flags:0  ts: 2.576668
-ret:-EOF
-ret: 0         st:-1 flags:1  ts: 1.470835
-ret:-EOF
-ret: 0         st: 0 flags:0  ts: 0.365011
-ret: 0         st: 0 flags:1 dts: 0.365011 pts: 0.365011 pos:  32240 size:  4096
-ret: 0         st: 0 flags:1  ts:-0.740839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     46 size:  4096
-ret: 0         st:-1 flags:0  ts: 2.153336
-ret:-EOF
-ret: 0         st:-1 flags:1  ts: 1.047503
-ret:-EOF
-ret: 0         st: 0 flags:0  ts:-0.058322
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     46 size:  4096
-ret: 0         st: 0 flags:1  ts: 2.835828
-ret:-EOF
-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.624172 pts: 0.624172 pos:  55098 size:  4096
-ret: 0         st: 0 flags:0  ts:-0.481655
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     46 size:  4096
-ret: 0         st: 0 flags:1  ts: 2.412494
-ret:-EOF
-ret: 0         st:-1 flags:0  ts: 1.306672
-ret:-EOF
-ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200839 pts: 0.200839 pos:  17760 size:  4096
-ret: 0         st: 0 flags:0  ts:-0.904989
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     46 size:  4096
-ret: 0         st: 0 flags:1  ts: 1.989184
-ret:-EOF
-ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.883333 pts: 0.883333 pos:  77956 size:  4096
-ret: 0         st:-1 flags:1  ts:-0.222493
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     46 size:  4096
-ret: 0         st: 0 flags:0  ts: 2.671678
-ret:-EOF
-ret: 0         st: 0 flags:1  ts: 1.565850
-ret:-EOF
-ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.460000 pts: 0.460000 pos:  40618 size:  4096
-ret: 0         st:-1 flags:1  ts:-0.645825
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     46 size:  4096
diff --git a/tests/ref/seek/lavf_wtv b/tests/ref/seek/lavf_wtv
deleted file mode 100644
index e2a1697..0000000
--- a/tests/ref/seek/lavf_wtv
+++ /dev/null
@@ -1,41 +0,0 @@
-ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  27072 size:   208
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  27072 size:   208
-ret:-1         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:0  ts: 0.788334
-ret: 0         st: 1 flags:1 dts: 0.772766 pts: 0.772766 pos: 321528 size:   209
-ret: 0         st: 0 flags:1  ts:-0.317499
-ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  27072 size:   208
-ret:-1         st: 1 flags:0  ts: 2.576668
-ret:-1         st: 1 flags:1  ts: 1.470835
-ret: 0         st:-1 flags:0  ts: 0.365002
-ret: 0         st: 1 flags:1 dts: 0.380930 pts: 0.380930 pos: 167728 size:   209
-ret: 0         st:-1 flags:1  ts:-0.740831
-ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  27072 size:   208
-ret:-1         st: 0 flags:0  ts: 2.153336
-ret:-1         st: 0 flags:1  ts: 1.047503
-ret: 0         st: 1 flags:0  ts:-0.058330
-ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  27072 size:   208
-ret:-1         st: 1 flags:1  ts: 2.835837
-ret:-1         st:-1 flags:0  ts: 1.730004
-ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 1 flags:1 dts: 0.616032 pts: 0.616032 pos: 266872 size:   209
-ret: 0         st: 0 flags:0  ts:-0.481662
-ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  27072 size:   208
-ret:-1         st: 0 flags:1  ts: 2.412505
-ret:-1         st: 1 flags:0  ts: 1.306672
-ret: 0         st: 1 flags:1  ts: 0.200839
-ret: 0         st: 1 flags:1 dts: 0.224195 pts: 0.224195 pos: 113632 size:   209
-ret: 0         st:-1 flags:0  ts:-0.904994
-ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  27072 size:   208
-ret:-1         st:-1 flags:1  ts: 1.989173
-ret: 0         st: 0 flags:0  ts: 0.883340
-ret: 0         st: 1 flags:1 dts: 0.903379 pts: 0.903379 pos: 358360 size:   209
-ret: 0         st: 0 flags:1  ts:-0.222493
-ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  27072 size:   208
-ret:-1         st: 1 flags:0  ts: 2.671674
-ret:-1         st: 1 flags:1  ts: 1.565841
-ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 1 flags:1 dts: 0.459297 pts: 0.459297 pos: 206056 size:   209
-ret: 0         st:-1 flags:1  ts:-0.645825
-ret: 0         st: 1 flags:1 dts:-0.010907 pts:-0.010907 pos:  27072 size:   208
diff --git a/tests/ref/seek/msmpeg4v2_avi b/tests/ref/seek/msmpeg4v2_avi
deleted file mode 100644
index 21804fe..0000000
--- a/tests/ref/seek/msmpeg4v2_avi
+++ /dev/null
@@ -1,46 +0,0 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  9003
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  9003
-ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83882 size: 11165
-ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54790 size: 10010
-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.440000 pts: 1.440000 pos:  83882 size: 11165
-ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29782 size:  8869
-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: 0.960000 pts: 0.960000 pos:  54790 size: 10010
-ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  9003
-ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116124 size: 11578
-ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116124 size: 11578
-ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29782 size:  8869
-ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  9003
-ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116124 size: 11578
-ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83882 size: 11165
-ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  9003
-ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  9003
-ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116124 size: 11578
-ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54790 size: 10010
-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.440000 pts: 1.440000 pos:  83882 size: 11165
-ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29782 size:  8869
-ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/pcm_mulaw_wav b/tests/ref/seek/pcm_mulaw_wav
deleted file mode 100644
index e5466bd..0000000
--- a/tests/ref/seek/pcm_mulaw_wav
+++ /dev/null
@@ -1,53 +0,0 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     58 size:  4096
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     58 size:  4096
-ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.894172 pts: 1.894172 pos: 167124 size:  4096
-ret: 0         st: 0 flags:0  ts: 0.788345
-ret: 0         st: 0 flags:1 dts: 0.788345 pts: 0.788345 pos:  69590 size:  4096
-ret: 0         st: 0 flags:1  ts:-0.317506
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     58 size:  4096
-ret: 0         st:-1 flags:0  ts: 2.576668
-ret: 0         st: 0 flags:1 dts: 2.576667 pts: 2.576667 pos: 227320 size:  4096
-ret: 0         st:-1 flags:1  ts: 1.470835
-ret: 0         st: 0 flags:1 dts: 1.470839 pts: 1.470839 pos: 129786 size:  4096
-ret: 0         st: 0 flags:0  ts: 0.365011
-ret: 0         st: 0 flags:1 dts: 0.365011 pts: 0.365011 pos:  32252 size:  4096
-ret: 0         st: 0 flags:1  ts:-0.740839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     58 size:  4096
-ret: 0         st:-1 flags:0  ts: 2.153336
-ret: 0         st: 0 flags:1 dts: 2.153333 pts: 2.153333 pos: 189982 size:  4096
-ret: 0         st:-1 flags:1  ts: 1.047503
-ret: 0         st: 0 flags:1 dts: 1.047506 pts: 1.047506 pos:  92448 size:  4096
-ret: 0         st: 0 flags:0  ts:-0.058322
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     58 size:  4096
-ret: 0         st: 0 flags:1  ts: 2.835828
-ret: 0         st: 0 flags:1 dts: 2.835828 pts: 2.835828 pos: 250178 size:  4096
-ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.730000 pts: 1.730000 pos: 152644 size:  4096
-ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.624172 pts: 0.624172 pos:  55110 size:  4096
-ret: 0         st: 0 flags:0  ts:-0.481655
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     58 size:  4096
-ret: 0         st: 0 flags:1  ts: 2.412494
-ret: 0         st: 0 flags:1 dts: 2.412494 pts: 2.412494 pos: 212840 size:  4096
-ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.306667 pts: 1.306667 pos: 115306 size:  4096
-ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200839 pts: 0.200839 pos:  17772 size:  4096
-ret: 0         st: 0 flags:0  ts:-0.904989
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     58 size:  4096
-ret: 0         st: 0 flags:1  ts: 1.989184
-ret: 0         st: 0 flags:1 dts: 1.989184 pts: 1.989184 pos: 175504 size:  4096
-ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.883333 pts: 0.883333 pos:  77968 size:  4096
-ret: 0         st:-1 flags:1  ts:-0.222493
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     58 size:  4096
-ret: 0         st: 0 flags:0  ts: 2.671678
-ret: 0         st: 0 flags:1 dts: 2.671678 pts: 2.671678 pos: 235700 size:  4096
-ret: 0         st: 0 flags:1  ts: 1.565850
-ret: 0         st: 0 flags:1 dts: 1.565850 pts: 1.565850 pos: 138166 size:  4096
-ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.460000 pts: 0.460000 pos:  40630 size:  4096
-ret: 0         st:-1 flags:1  ts:-0.645825
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     58 size:  4096
diff --git a/tests/ref/seek/asv1_avi b/tests/ref/seek/vsynth2-asv1
similarity index 87%
rename from tests/ref/seek/asv1_avi
rename to tests/ref/seek/vsynth2-asv1
index eb6abc2..5873bb1 100644
--- a/tests/ref/seek/asv1_avi
+++ b/tests/ref/seek/vsynth2-asv1
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5668 size: 14316
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 14316
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5668 size: 14316
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 14316
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos: 776852 size: 18256
+ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos: 776840 size: 18256
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos: 305364 size: 16180
+ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos: 305352 size: 16180
 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: 595460 size: 17980
+ret: 0         st: 0 flags:1 dts: 1.480000 pts: 1.480000 pos: 595448 size: 17980
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos: 135528 size: 14868
+ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos: 135516 size: 14868
 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: 404112 size: 16856
+ret: 0         st: 0 flags:1 dts: 1.040000 pts: 1.040000 pos: 404100 size: 16856
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5668 size: 14316
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 14316
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 813408 size: 18296
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 813396 size: 18296
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos: 704148 size: 18140
+ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos: 704136 size: 18140
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos: 241776 size: 15736
+ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos: 241764 size: 15736
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5668 size: 14316
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 14316
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 813408 size: 18296
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 813396 size: 18296
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos: 524500 size: 17548
+ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos: 524488 size: 17548
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos:  77032 size: 14496
+ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos:  77020 size: 14496
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5668 size: 14316
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 14316
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 813408 size: 18296
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 813396 size: 18296
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos: 337820 size: 16388
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos: 337808 size: 16388
 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: 631596 size: 18188
+ret: 0         st: 0 flags:1 dts: 1.560000 pts: 1.560000 pos: 631584 size: 18188
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 180224 size: 15168
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 180212 size: 15168
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/asv2_avi b/tests/ref/seek/vsynth2-asv2
similarity index 87%
rename from tests/ref/seek/asv2_avi
rename to tests/ref/seek/vsynth2-asv2
index f7b7f69..7d37b7a 100644
--- a/tests/ref/seek/asv2_avi
+++ b/tests/ref/seek/vsynth2-asv2
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5668 size: 13732
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 13732
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5668 size: 13732
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 13732
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos: 736164 size: 17340
+ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos: 736152 size: 17340
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos: 289720 size: 15300
+ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos: 289708 size: 15300
 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: 564152 size: 17016
+ret: 0         st: 0 flags:1 dts: 1.480000 pts: 1.480000 pos: 564140 size: 17016
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos: 128576 size: 14052
+ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos: 128564 size: 14052
 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: 383256 size: 15896
+ret: 0         st: 0 flags:1 dts: 1.040000 pts: 1.040000 pos: 383244 size: 15896
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5668 size: 13732
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 13732
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 770864 size: 17400
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 770852 size: 17400
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos: 667028 size: 17172
+ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos: 667016 size: 17172
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos: 229400 size: 14956
+ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos: 229388 size: 14956
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5668 size: 13732
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 13732
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 770864 size: 17400
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 770852 size: 17400
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos: 496944 size: 16564
+ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos: 496932 size: 16564
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos:  73188 size: 13664
+ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos:  73176 size: 13664
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5668 size: 13732
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 13732
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 770864 size: 17400
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 770852 size: 17400
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos: 320456 size: 15592
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos: 320444 size: 15592
 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: 598300 size: 17180
+ret: 0         st: 0 flags:1 dts: 1.560000 pts: 1.560000 pos: 598288 size: 17180
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 171024 size: 14392
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 171012 size: 14392
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/dnxhd_1080i_mov b/tests/ref/seek/vsynth2-dnxhd-1080i
similarity index 79%
rename from tests/ref/seek/dnxhd_1080i_mov
rename to tests/ref/seek/vsynth2-dnxhd-1080i
index 6c41d67..a5f0ce9 100644
--- a/tests/ref/seek/dnxhd_1080i_mov
+++ b/tests/ref/seek/vsynth2-dnxhd-1080i
@@ -3,41 +3,41 @@
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     36 size:606208
 ret: 0         st:-1 flags:1  ts: 1.894167
 ret: 0         st: 0 flags:1 dts: 0.160000 pts: 0.160000 pos:2424868 size:606208
-ret:-1         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1  ts:-0.320000
+ret:-1         st: 0 flags:0  ts: 0.788359
+ret: 0         st: 0 flags:1  ts:-0.317500
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     36 size:606208
 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: 0.160000 pts: 0.160000 pos:2424868 size:606208
-ret:-1         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1  ts:-0.760000
+ret:-1         st: 0 flags:0  ts: 0.365000
+ret: 0         st: 0 flags:1  ts:-0.740859
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     36 size:606208
 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: 0.160000 pts: 0.160000 pos:2424868 size:606208
-ret: 0         st: 0 flags:0  ts:-0.040000
+ret: 0         st: 0 flags:0  ts:-0.058359
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     36 size:606208
-ret: 0         st: 0 flags:1  ts: 2.840000
+ret: 0         st: 0 flags:1  ts: 2.835859
 ret: 0         st: 0 flags:1 dts: 0.160000 pts: 0.160000 pos:2424868 size:606208
 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.160000 pts: 0.160000 pos:2424868 size:606208
-ret: 0         st: 0 flags:0  ts:-0.480000
+ret: 0         st: 0 flags:0  ts:-0.481641
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     36 size:606208
-ret: 0         st: 0 flags:1  ts: 2.400000
+ret: 0         st: 0 flags:1  ts: 2.412500
 ret: 0         st: 0 flags:1 dts: 0.160000 pts: 0.160000 pos:2424868 size:606208
 ret:-1         st:-1 flags:0  ts: 1.306672
 ret: 0         st:-1 flags:1  ts: 0.200839
 ret: 0         st: 0 flags:1 dts: 0.160000 pts: 0.160000 pos:2424868 size:606208
-ret: 0         st: 0 flags:0  ts:-0.920000
+ret: 0         st: 0 flags:0  ts:-0.905000
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     36 size:606208
-ret: 0         st: 0 flags:1  ts: 2.000000
+ret: 0         st: 0 flags:1  ts: 1.989141
 ret: 0         st: 0 flags:1 dts: 0.160000 pts: 0.160000 pos:2424868 size:606208
 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:     36 size:606208
-ret:-1         st: 0 flags:0  ts: 2.680000
-ret: 0         st: 0 flags:1  ts: 1.560000
+ret:-1         st: 0 flags:0  ts: 2.671641
+ret: 0         st: 0 flags:1  ts: 1.565859
 ret: 0         st: 0 flags:1 dts: 0.160000 pts: 0.160000 pos:2424868 size:606208
 ret:-1         st:-1 flags:0  ts: 0.460008
 ret: 0         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/dnxhd_720p_dnxhd b/tests/ref/seek/vsynth2-dnxhd-720p
similarity index 100%
copy from tests/ref/seek/dnxhd_720p_dnxhd
copy to tests/ref/seek/vsynth2-dnxhd-720p
diff --git a/tests/ref/seek/dnxhd_720p_dnxhd b/tests/ref/seek/vsynth2-dnxhd-720p-rd
similarity index 100%
rename from tests/ref/seek/dnxhd_720p_dnxhd
rename to tests/ref/seek/vsynth2-dnxhd-720p-rd
diff --git a/tests/ref/seek/dv_411_dv b/tests/ref/seek/vsynth2-dv
similarity index 100%
rename from tests/ref/seek/dv_411_dv
rename to tests/ref/seek/vsynth2-dv
diff --git a/tests/ref/seek/dv_411_dv b/tests/ref/seek/vsynth2-dv-411
similarity index 100%
copy from tests/ref/seek/dv_411_dv
copy to tests/ref/seek/vsynth2-dv-411
diff --git a/tests/ref/seek/dv_50_dv b/tests/ref/seek/vsynth2-dv-50
similarity index 100%
rename from tests/ref/seek/dv_50_dv
rename to tests/ref/seek/vsynth2-dv-50
diff --git a/tests/ref/seek/ffv1_avi b/tests/ref/seek/vsynth2-ffv1
similarity index 87%
rename from tests/ref/seek/ffv1_avi
rename to tests/ref/seek/vsynth2-ffv1
index 04edb8d..a1272f8 100644
--- a/tests/ref/seek/ffv1_avi
+++ b/tests/ref/seek/vsynth2-ffv1
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 70200
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 70200
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 70200
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 70200
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:2485810 size: 74128
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:2485798 size: 74128
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1622716 size: 71128
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1622704 size: 71128
 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.440000 pts: 1.440000 pos:2485810 size: 74128
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:2485798 size: 74128
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 796840 size: 67971
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 796828 size: 67971
 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: 0.960000 pts: 0.960000 pos:1622716 size: 71128
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1622704 size: 71128
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 70200
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 70200
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:3374440 size: 75606
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:3374428 size: 75606
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:3374440 size: 75606
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:3374428 size: 75606
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 796840 size: 67971
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 796828 size: 67971
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 70200
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 70200
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:3374440 size: 75606
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:3374428 size: 75606
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:2485810 size: 74128
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:2485798 size: 74128
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 70200
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 70200
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 70200
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 70200
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:3374440 size: 75606
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:3374428 size: 75606
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1622716 size: 71128
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1622704 size: 71128
 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.440000 pts: 1.440000 pos:2485810 size: 74128
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:2485798 size: 74128
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 796840 size: 67971
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 796828 size: 67971
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/flashsv_flv b/tests/ref/seek/vsynth2-flashsv
similarity index 100%
rename from tests/ref/seek/flashsv_flv
rename to tests/ref/seek/vsynth2-flashsv
diff --git a/tests/ref/seek/flv_flv b/tests/ref/seek/vsynth2-flv
similarity index 100%
rename from tests/ref/seek/flv_flv
rename to tests/ref/seek/vsynth2-flv
diff --git a/tests/ref/seek/h261_avi b/tests/ref/seek/vsynth2-h261
similarity index 87%
rename from tests/ref/seek/h261_avi
rename to tests/ref/seek/vsynth2-h261
index 55ccf97..48ee00f 100644
--- a/tests/ref/seek/h261_avi
+++ b/tests/ref/seek/vsynth2-h261
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  9645
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9645
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  9645
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9645
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 126506 size: 11377
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 126494 size: 11377
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  82064 size: 10322
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  82052 size: 10322
 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.440000 pts: 1.440000 pos: 126506 size: 11377
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 126494 size: 11377
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  44676 size:  9404
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  44664 size:  9404
 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: 0.960000 pts: 0.960000 pos:  82064 size: 10322
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  82052 size: 10322
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  9645
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9645
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 175868 size: 11707
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 175856 size: 11707
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 175868 size: 11707
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 175856 size: 11707
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  44676 size:  9404
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  44664 size:  9404
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  9645
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9645
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 175868 size: 11707
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 175856 size: 11707
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 126506 size: 11377
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 126494 size: 11377
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  9645
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9645
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  9645
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9645
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 175868 size: 11707
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 175856 size: 11707
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  82064 size: 10322
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  82052 size: 10322
 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.440000 pts: 1.440000 pos: 126506 size: 11377
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 126494 size: 11377
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  44676 size:  9404
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  44664 size:  9404
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/h263_avi b/tests/ref/seek/vsynth2-h263
similarity index 87%
rename from tests/ref/seek/h263_avi
rename to tests/ref/seek/vsynth2-h263
index c9f7908..6b7df48 100644
--- a/tests/ref/seek/h263_avi
+++ b/tests/ref/seek/vsynth2-h263
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 10381
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10381
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 10381
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10381
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 103714 size: 12296
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 103702 size: 12296
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  66804 size: 11128
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  66792 size: 11128
 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.440000 pts: 1.440000 pos: 103714 size: 12296
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 103702 size: 12296
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  36450 size: 10090
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  36438 size: 10090
 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: 0.960000 pts: 0.960000 pos:  66804 size: 11128
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  66792 size: 11128
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 10381
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10381
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 144564 size: 12731
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 144552 size: 12731
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 144564 size: 12731
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 144552 size: 12731
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  36450 size: 10090
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  36438 size: 10090
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 10381
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10381
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 144564 size: 12731
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 144552 size: 12731
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 103714 size: 12296
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 103702 size: 12296
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 10381
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10381
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 10381
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10381
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 144564 size: 12731
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 144552 size: 12731
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  66804 size: 11128
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  66792 size: 11128
 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.440000 pts: 1.440000 pos: 103714 size: 12296
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 103702 size: 12296
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  36450 size: 10090
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  36438 size: 10090
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/h263p_avi b/tests/ref/seek/vsynth2-h263p
similarity index 87%
rename from tests/ref/seek/h263p_avi
rename to tests/ref/seek/vsynth2-h263p
index 2756439..7dd4852 100644
--- a/tests/ref/seek/h263p_avi
+++ b/tests/ref/seek/vsynth2-h263p
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 36208
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 36208
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 36208
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 36208
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 569930 size: 45151
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 569918 size: 45151
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 355980 size: 40907
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 355968 size: 40907
 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.440000 pts: 1.440000 pos: 569930 size: 45151
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 569918 size: 45151
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 171054 size: 36514
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 171042 size: 36514
 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: 0.960000 pts: 0.960000 pos: 355980 size: 40907
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 355968 size: 40907
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 36208
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 36208
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 804370 size: 46411
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 804358 size: 46411
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 804370 size: 46411
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 804358 size: 46411
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 171054 size: 36514
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 171042 size: 36514
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 36208
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 36208
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 804370 size: 46411
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 804358 size: 46411
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 569930 size: 45151
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 569918 size: 45151
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 36208
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 36208
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 36208
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 36208
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 804370 size: 46411
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 804358 size: 46411
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 355980 size: 40907
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 355968 size: 40907
 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.440000 pts: 1.440000 pos: 569930 size: 45151
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 569918 size: 45151
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 171054 size: 36514
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 171042 size: 36514
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/huffyuv_avi b/tests/ref/seek/vsynth2-huffyuv
similarity index 87%
rename from tests/ref/seek/huffyuv_avi
rename to tests/ref/seek/vsynth2-huffyuv
index 8e3cbc1..69a37f5 100644
--- a/tests/ref/seek/huffyuv_avi
+++ b/tests/ref/seek/vsynth2-huffyuv
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5736 size:129760
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5724 size:129760
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5736 size:129760
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5724 size:129760
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos:6069184 size:128520
+ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos:6069172 size:128520
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:2579624 size:129192
+ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:2579612 size:129192
 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:4778240 size:129424
+ret: 0         st: 0 flags:1 dts: 1.480000 pts: 1.480000 pos:4778228 size:129424
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos:1160260 size:128504
+ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos:1160248 size:128504
 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:3355296 size:129424
+ret: 0         st: 0 flags:1 dts: 1.040000 pts: 1.040000 pos:3355284 size:129424
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5736 size:129760
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5724 size:129760
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:6326136 size:128288
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:6326124 size:128288
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:5554008 size:129016
+ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:5553996 size:129016
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:2062504 size:129204
+ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:2062492 size:129204
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5736 size:129760
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5724 size:129760
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:6326136 size:128288
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:6326124 size:128288
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:4260872 size:129280
+ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:4260860 size:129280
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos: 646920 size:128204
+ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos: 646908 size:128204
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5736 size:129760
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5724 size:129760
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:6326136 size:128288
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:6326124 size:128288
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:2838080 size:129268
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:2838068 size:129268
 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:5037036 size:129284
+ret: 0         st: 0 flags:1 dts: 1.560000 pts: 1.560000 pos:5037024 size:129284
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:1546184 size:128860
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:1546172 size:128860
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/jpegls_avi b/tests/ref/seek/vsynth2-jpegls
similarity index 87%
rename from tests/ref/seek/jpegls_avi
rename to tests/ref/seek/vsynth2-jpegls
index b95ec5a..3c0da21 100644
--- a/tests/ref/seek/jpegls_avi
+++ b/tests/ref/seek/vsynth2-jpegls
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:164074
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:164074
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:164074
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:164074
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos:7804130 size:176295
+ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos:7804118 size:176295
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:3172792 size:164643
+ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:3172780 size:164643
 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:6052986 size:174097
+ret: 0         st: 0 flags:1 dts: 1.480000 pts: 1.480000 pos:6052974 size:174097
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos:1402356 size:157283
+ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos:1402344 size:157283
 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:4170260 size:168401
+ret: 0         st: 0 flags:1 dts: 1.040000 pts: 1.040000 pos:4170248 size:168401
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:164074
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:164074
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:8157028 size:176793
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:8157016 size:176793
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:7101766 size:175326
+ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:7101754 size:175326
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:2519272 size:162522
+ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:2519260 size:162522
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:164074
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:164074
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:8157028 size:176793
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:8157016 size:176793
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:5360830 size:172183
+ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:5360818 size:172183
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos: 779846 size:154579
+ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos: 779834 size:154579
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:164074
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:164074
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:8157028 size:176793
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:8157016 size:176793
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:3502840 size:166017
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:3502828 size:166017
 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:6401464 size:174815
+ret: 0         st: 0 flags:1 dts: 1.560000 pts: 1.560000 pos:6401452 size:174815
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:1876428 size:159659
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:1876416 size:159659
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/ljpeg_avi b/tests/ref/seek/vsynth2-ljpeg
similarity index 87%
rename from tests/ref/seek/ljpeg_avi
rename to tests/ref/seek/vsynth2-ljpeg
index 76442fe..92264c9 100644
--- a/tests/ref/seek/ljpeg_avi
+++ b/tests/ref/seek/vsynth2-ljpeg
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 96069
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 96069
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 96069
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 96069
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos:4481876 size: 94870
+ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos:4481864 size: 94870
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:1902330 size: 95465
+ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:1902318 size: 95465
 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:3527736 size: 95724
+ret: 0         st: 0 flags:1 dts: 1.480000 pts: 1.480000 pos:3527724 size: 95724
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos: 854956 size: 94635
+ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos: 854944 size: 94635
 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:2475578 size: 95649
+ret: 0         st: 0 flags:1 dts: 1.040000 pts: 1.040000 pos:2475566 size: 95649
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 96069
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 96069
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:4671510 size: 94595
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:4671498 size: 94595
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:4101350 size: 95353
+ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:4101338 size: 95353
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:1520296 size: 95410
+ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:1520284 size: 95410
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 96069
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 96069
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:4671510 size: 94595
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:4671498 size: 94595
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:3145126 size: 95587
+ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:3145114 size: 95587
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos: 477238 size: 94261
+ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos: 477226 size: 94261
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 96069
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 96069
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:4671510 size: 94595
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:4671498 size: 94595
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:2093314 size: 95528
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:2093302 size: 95528
 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:3719138 size: 95615
+ret: 0         st: 0 flags:1 dts: 1.560000 pts: 1.560000 pos:3719126 size: 95615
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:1139250 size: 95032
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:1139238 size: 95032
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/mjpeg_avi b/tests/ref/seek/vsynth2-mjpeg
similarity index 87%
rename from tests/ref/seek/mjpeg_avi
rename to tests/ref/seek/vsynth2-mjpeg
index e172b91..c1395a9 100644
--- a/tests/ref/seek/mjpeg_avi
+++ b/tests/ref/seek/vsynth2-mjpeg
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 12096
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 12096
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 12096
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 12096
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos: 627826 size: 14806
+ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos: 627814 size: 14806
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos: 247510 size: 12959
+ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos: 247498 size: 12959
 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: 480748 size: 14519
+ret: 0         st: 0 flags:1 dts: 1.480000 pts: 1.480000 pos: 480736 size: 14519
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos: 111008 size: 11924
+ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos: 110996 size: 11924
 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: 326692 size: 13491
+ret: 0         st: 0 flags:1 dts: 1.040000 pts: 1.040000 pos: 326680 size: 13491
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 12096
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 12096
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 657480 size: 14897
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 657468 size: 14897
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos: 568618 size: 14751
+ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos: 568606 size: 14751
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos: 196432 size: 12720
+ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos: 196420 size: 12720
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 12096
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 12096
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 657480 size: 14897
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 657468 size: 14897
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos: 423482 size: 14114
+ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos: 423470 size: 14114
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos:  63874 size: 11715
+ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos:  63862 size: 11715
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 12096
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 12096
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 657480 size: 14897
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 657468 size: 14897
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos: 273524 size: 13122
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos: 273512 size: 13122
 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: 509904 size: 14594
+ret: 0         st: 0 flags:1 dts: 1.560000 pts: 1.560000 pos: 509892 size: 14594
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146962 size: 12173
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146950 size: 12173
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/mpeg1_mpeg1video b/tests/ref/seek/vsynth2-mpeg1
similarity index 100%
rename from tests/ref/seek/mpeg1_mpeg1video
rename to tests/ref/seek/vsynth2-mpeg1
diff --git a/tests/ref/seek/mpeg1b_mpeg1video b/tests/ref/seek/vsynth2-mpeg1b
similarity index 100%
rename from tests/ref/seek/mpeg1b_mpeg1video
rename to tests/ref/seek/vsynth2-mpeg1b
diff --git a/tests/ref/seek/mpeg2_422_mpeg2video b/tests/ref/seek/vsynth2-mpeg2-422
similarity index 100%
rename from tests/ref/seek/mpeg2_422_mpeg2video
rename to tests/ref/seek/vsynth2-mpeg2-422
diff --git a/tests/ref/seek/mpeg2_idct_int_mpeg2video b/tests/ref/seek/vsynth2-mpeg2-idct-int
similarity index 100%
rename from tests/ref/seek/mpeg2_idct_int_mpeg2video
rename to tests/ref/seek/vsynth2-mpeg2-idct-int
diff --git a/tests/ref/seek/mpeg2_ilace_mpeg2video b/tests/ref/seek/vsynth2-mpeg2-ilace
similarity index 100%
rename from tests/ref/seek/mpeg2_ilace_mpeg2video
rename to tests/ref/seek/vsynth2-mpeg2-ilace
diff --git a/tests/ref/seek/mpeg2_ivlc_qprd_mpeg2video b/tests/ref/seek/vsynth2-mpeg2-ivlc-qprd
similarity index 100%
rename from tests/ref/seek/mpeg2_ivlc_qprd_mpeg2video
rename to tests/ref/seek/vsynth2-mpeg2-ivlc-qprd
diff --git a/tests/ref/seek/mpeg2_thread_mpeg2video b/tests/ref/seek/vsynth2-mpeg2-thread
similarity index 100%
rename from tests/ref/seek/mpeg2_thread_mpeg2video
rename to tests/ref/seek/vsynth2-mpeg2-thread
diff --git a/tests/ref/seek/mpeg2_thread_ivlc_mpeg2video b/tests/ref/seek/vsynth2-mpeg2-thread-ivlc
similarity index 100%
rename from tests/ref/seek/mpeg2_thread_ivlc_mpeg2video
rename to tests/ref/seek/vsynth2-mpeg2-thread-ivlc
diff --git a/tests/ref/seek/mpeg4_mp4 b/tests/ref/seek/vsynth2-mpeg4
similarity index 82%
rename from tests/ref/seek/mpeg4_mp4
rename to tests/ref/seek/vsynth2-mpeg4
index 70cff1e..b1c8a19 100644
--- a/tests/ref/seek/mpeg4_mp4
+++ b/tests/ref/seek/vsynth2-mpeg4
@@ -3,46 +3,46 @@
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     44 size:  8719
 ret: 0         st:-1 flags:1  ts: 1.894167
 ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  75140 size: 10776
-ret: 0         st: 0 flags:0  ts: 0.800000
+ret: 0         st: 0 flags:0  ts: 0.788359
 ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  47228 size:  9634
-ret: 0         st: 0 flags:1  ts:-0.320000
+ret: 0         st: 0 flags:1  ts:-0.317500
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     44 size:  8719
 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.440000 pts: 1.440000 pos:  75140 size: 10776
-ret: 0         st: 0 flags:0  ts: 0.360000
+ret: 0         st: 0 flags:0  ts: 0.365000
 ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  23271 size:  8524
-ret: 0         st: 0 flags:1  ts:-0.760000
+ret: 0         st: 0 flags:1  ts:-0.740859
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     44 size:  8719
 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: 0.960000 pts: 0.960000 pos:  47228 size:  9634
-ret: 0         st: 0 flags:0  ts:-0.040000
+ret: 0         st: 0 flags:0  ts:-0.058359
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     44 size:  8719
-ret: 0         st: 0 flags:1  ts: 2.840000
+ret: 0         st: 0 flags:1  ts: 2.835859
 ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 106181 size: 11182
 ret: 0         st:-1 flags:0  ts: 1.730004
 ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 106181 size: 11182
 ret: 0         st:-1 flags:1  ts: 0.624171
 ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  23271 size:  8524
-ret: 0         st: 0 flags:0  ts:-0.480000
+ret: 0         st: 0 flags:0  ts:-0.481641
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     44 size:  8719
-ret: 0         st: 0 flags:1  ts: 2.400000
+ret: 0         st: 0 flags:1  ts: 2.412500
 ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 106181 size: 11182
 ret: 0         st:-1 flags:0  ts: 1.306672
 ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  75140 size: 10776
 ret: 0         st:-1 flags:1  ts: 0.200839
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     44 size:  8719
-ret: 0         st: 0 flags:0  ts:-0.920000
+ret: 0         st: 0 flags:0  ts:-0.905000
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     44 size:  8719
-ret: 0         st: 0 flags:1  ts: 2.000000
+ret: 0         st: 0 flags:1  ts: 1.989141
 ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 106181 size: 11182
 ret: 0         st:-1 flags:0  ts: 0.883340
 ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  47228 size:  9634
 ret: 0         st:-1 flags:1  ts:-0.222493
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     44 size:  8719
-ret:-1         st: 0 flags:0  ts: 2.680000
-ret: 0         st: 0 flags:1  ts: 1.560000
+ret:-1         st: 0 flags:0  ts: 2.671641
+ret: 0         st: 0 flags:1  ts: 1.565859
 ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  75140 size: 10776
 ret: 0         st:-1 flags:0  ts: 0.460008
 ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  23271 size:  8524
diff --git a/tests/ref/seek/mpeg4_adap_avi b/tests/ref/seek/vsynth2-mpeg4-adap
similarity index 87%
rename from tests/ref/seek/mpeg4_adap_avi
rename to tests/ref/seek/vsynth2-mpeg4-adap
index c627014..cb6beee 100644
--- a/tests/ref/seek/mpeg4_adap_avi
+++ b/tests/ref/seek/vsynth2-mpeg4-adap
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size:  6855
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size:  6855
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size:  6855
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size:  6855
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174454 size: 16883
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174442 size: 16883
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  98228 size: 17063
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  98216 size: 17063
 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.360000 pts: NOPTS    pos: 135590 size: 17525
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 135578 size: 17525
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  59454 size: 17261
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  59442 size: 17261
 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: 0.880000 pts: NOPTS    pos:  98228 size: 17063
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  98216 size: 17063
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size:  6855
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size:  6855
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174454 size: 16883
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174442 size: 16883
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174454 size: 16883
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174442 size: 16883
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  59454 size: 17261
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  59442 size: 17261
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size:  6855
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size:  6855
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174454 size: 16883
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174442 size: 16883
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 135590 size: 17525
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 135578 size: 17525
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size:  6855
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size:  6855
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size:  6855
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size:  6855
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174454 size: 16883
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174442 size: 16883
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  98228 size: 17063
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  98216 size: 17063
 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.360000 pts: NOPTS    pos: 135590 size: 17525
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 135578 size: 17525
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  98228 size: 17063
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  98216 size: 17063
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/mpeg4_adv_avi b/tests/ref/seek/vsynth2-mpeg4-adv
similarity index 87%
rename from tests/ref/seek/mpeg4_adv_avi
rename to tests/ref/seek/vsynth2-mpeg4-adv
index 2e66b77..6765864 100644
--- a/tests/ref/seek/mpeg4_adv_avi
+++ b/tests/ref/seek/vsynth2-mpeg4-adv
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8653
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8653
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8653
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8653
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  91730 size: 11013
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  91718 size: 11013
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  59504 size:  9815
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  59492 size:  9815
 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.440000 pts: 1.440000 pos:  91730 size: 11013
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  91718 size: 11013
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  31944 size:  8753
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  31932 size:  8753
 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: 0.960000 pts: 0.960000 pos:  59504 size:  9815
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  59492 size:  9815
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8653
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8653
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 127624 size: 11279
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 127612 size: 11279
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 127624 size: 11279
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 127612 size: 11279
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  31944 size:  8753
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  31932 size:  8753
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8653
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8653
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 127624 size: 11279
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 127612 size: 11279
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  91730 size: 11013
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  91718 size: 11013
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8653
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8653
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8653
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8653
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 127624 size: 11279
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 127612 size: 11279
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  59504 size:  9815
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  59492 size:  9815
 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.440000 pts: 1.440000 pos:  91730 size: 11013
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  91718 size: 11013
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  31944 size:  8753
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  31932 size:  8753
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/mpeg4_error_avi b/tests/ref/seek/vsynth2-mpeg4-error
similarity index 87%
rename from tests/ref/seek/mpeg4_error_avi
rename to tests/ref/seek/vsynth2-mpeg4-error
index ca77060..e31df5d 100644
--- a/tests/ref/seek/mpeg4_error_avi
+++ b/tests/ref/seek/vsynth2-mpeg4-error
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  9729
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9729
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  9729
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9729
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 113194 size: 15063
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 113182 size: 15063
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  73154 size: 10235
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  73142 size: 10235
 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.440000 pts: 1.440000 pos: 113194 size: 15063
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 113182 size: 15063
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  38240 size: 10303
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  38228 size: 10303
 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: 0.960000 pts: 0.960000 pos:  73154 size: 10235
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  73142 size: 10235
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  9729
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9729
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 163076 size: 13980
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 163064 size: 13980
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 163076 size: 13980
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 163064 size: 13980
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  38240 size: 10303
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  38228 size: 10303
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  9729
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9729
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 163076 size: 13980
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 163064 size: 13980
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 113194 size: 15063
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 113182 size: 15063
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  9729
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9729
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  9729
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9729
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 163076 size: 13980
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 163064 size: 13980
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  73154 size: 10235
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  73142 size: 10235
 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.440000 pts: 1.440000 pos: 113194 size: 15063
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 113182 size: 15063
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  38240 size: 10303
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  38228 size: 10303
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/mpeg4_nr_avi b/tests/ref/seek/vsynth2-mpeg4-nr
similarity index 87%
rename from tests/ref/seek/mpeg4_nr_avi
rename to tests/ref/seek/vsynth2-mpeg4-nr
index f31619f..3d6b5ce 100644
--- a/tests/ref/seek/mpeg4_nr_avi
+++ b/tests/ref/seek/vsynth2-mpeg4-nr
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 10673
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10673
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 10673
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10673
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 100664 size: 12464
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 100652 size: 12464
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  65500 size: 11180
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  65488 size: 11180
 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.440000 pts: 1.440000 pos: 100664 size: 12464
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 100652 size: 12464
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  35322 size:  9987
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  35310 size:  9987
 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: 0.960000 pts: 0.960000 pos:  65500 size: 11180
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  65488 size: 11180
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 10673
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10673
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139384 size: 12911
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139372 size: 12911
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139384 size: 12911
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139372 size: 12911
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  35322 size:  9987
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  35310 size:  9987
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 10673
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10673
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139384 size: 12911
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139372 size: 12911
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 100664 size: 12464
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 100652 size: 12464
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 10673
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10673
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 10673
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10673
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139384 size: 12911
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139372 size: 12911
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  65500 size: 11180
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  65488 size: 11180
 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.440000 pts: 1.440000 pos: 100664 size: 12464
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 100652 size: 12464
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  35322 size:  9987
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  35310 size:  9987
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/mpeg4_qpel_avi b/tests/ref/seek/vsynth2-mpeg4-qpel
similarity index 87%
rename from tests/ref/seek/mpeg4_qpel_avi
rename to tests/ref/seek/vsynth2-mpeg4-qpel
index 63b474c..cd6eaf0 100644
--- a/tests/ref/seek/mpeg4_qpel_avi
+++ b/tests/ref/seek/vsynth2-mpeg4-qpel
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 11938
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 11938
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 11938
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 11938
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141538 size: 15554
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141526 size: 15554
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  64122 size: 13377
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  64110 size: 13377
 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.360000 pts: NOPTS    pos: 100348 size: 15055
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 100336 size: 15055
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  32848 size: 11806
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  32836 size: 11806
 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: 0.880000 pts: NOPTS    pos:  64122 size: 13377
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  64110 size: 13377
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 11938
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 11938
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141538 size: 15554
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141526 size: 15554
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141538 size: 15554
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141526 size: 15554
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  32848 size: 11806
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  32836 size: 11806
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 11938
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 11938
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141538 size: 15554
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141526 size: 15554
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 100348 size: 15055
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 100336 size: 15055
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 11938
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 11938
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 11938
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 11938
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141538 size: 15554
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141526 size: 15554
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  64122 size: 13377
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  64110 size: 13377
 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.360000 pts: NOPTS    pos: 100348 size: 15055
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 100336 size: 15055
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  64122 size: 13377
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  64110 size: 13377
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/mpeg4_qprd_avi b/tests/ref/seek/vsynth2-mpeg4-qprd
similarity index 87%
rename from tests/ref/seek/mpeg4_qprd_avi
rename to tests/ref/seek/vsynth2-mpeg4-qprd
index 61605de..74aee79 100644
--- a/tests/ref/seek/mpeg4_qprd_avi
+++ b/tests/ref/seek/vsynth2-mpeg4-qprd
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 14873
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14873
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 14873
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14873
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211042 size: 14638
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211030 size: 14638
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 150666 size: 14502
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 150654 size: 14502
 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.360000 pts: NOPTS    pos: 180790 size: 14371
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 180778 size: 14371
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  93036 size: 29366
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  93024 size: 29366
 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: 0.880000 pts: NOPTS    pos: 150666 size: 14502
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 150654 size: 14502
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 14873
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14873
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211042 size: 14638
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211030 size: 14638
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211042 size: 14638
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211030 size: 14638
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  93036 size: 29366
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  93024 size: 29366
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 14873
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14873
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211042 size: 14638
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211030 size: 14638
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 180790 size: 14371
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 180778 size: 14371
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 14873
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14873
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 14873
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14873
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211042 size: 14638
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211030 size: 14638
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 150666 size: 14502
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 150654 size: 14502
 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.360000 pts: NOPTS    pos: 180790 size: 14371
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 180778 size: 14371
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 150666 size: 14502
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 150654 size: 14502
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/mpeg4_rc_avi b/tests/ref/seek/vsynth2-mpeg4-rc
similarity index 87%
rename from tests/ref/seek/mpeg4_rc_avi
rename to tests/ref/seek/vsynth2-mpeg4-rc
index fbefdc0..6bcfd48 100644
--- a/tests/ref/seek/mpeg4_rc_avi
+++ b/tests/ref/seek/vsynth2-mpeg4-rc
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 15766
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 15766
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 15766
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 15766
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207962 size: 13826
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207950 size: 13826
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 153796 size: 13377
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 153784 size: 13377
 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.360000 pts: NOPTS    pos: 180958 size: 13326
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 180946 size: 13326
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  94586 size: 32807
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  94574 size: 32807
 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: 0.880000 pts: NOPTS    pos: 153796 size: 13377
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 153784 size: 13377
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 15766
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 15766
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207962 size: 13826
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207950 size: 13826
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207962 size: 13826
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207950 size: 13826
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  94586 size: 32807
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  94574 size: 32807
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 15766
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 15766
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207962 size: 13826
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207950 size: 13826
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 180958 size: 13326
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 180946 size: 13326
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 15766
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 15766
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 15766
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 15766
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207962 size: 13826
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207950 size: 13826
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 153796 size: 13377
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 153784 size: 13377
 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.360000 pts: NOPTS    pos: 180958 size: 13326
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 180946 size: 13326
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 153796 size: 13377
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 153784 size: 13377
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/mpeg4_thread_avi b/tests/ref/seek/vsynth2-mpeg4-thread
similarity index 87%
rename from tests/ref/seek/mpeg4_thread_avi
rename to tests/ref/seek/vsynth2-mpeg4-thread
index 6ddeeb2..ca849f3 100644
--- a/tests/ref/seek/mpeg4_thread_avi
+++ b/tests/ref/seek/vsynth2-mpeg4-thread
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 14874
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14874
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 14874
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14874
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228198 size: 16323
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228186 size: 16323
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 162168 size: 16462
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 162156 size: 16462
 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.360000 pts: NOPTS    pos: 195342 size: 16153
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 195330 size: 16153
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  97844 size: 33332
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  97832 size: 33332
 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: 0.880000 pts: NOPTS    pos: 162168 size: 16462
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 162156 size: 16462
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 14874
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14874
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228198 size: 16323
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228186 size: 16323
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228198 size: 16323
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228186 size: 16323
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  97844 size: 33332
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  97832 size: 33332
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 14874
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14874
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228198 size: 16323
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228186 size: 16323
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 195342 size: 16153
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 195330 size: 16153
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 14874
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14874
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5660 size: 14874
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14874
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228198 size: 16323
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228186 size: 16323
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 162168 size: 16462
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 162156 size: 16462
 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.360000 pts: NOPTS    pos: 195342 size: 16153
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 195330 size: 16153
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 162168 size: 16462
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 162156 size: 16462
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/msmpeg4_avi b/tests/ref/seek/vsynth2-msmpeg4
similarity index 87%
copy from tests/ref/seek/msmpeg4_avi
copy to tests/ref/seek/vsynth2-msmpeg4
index f95d615..e096f76 100644
--- a/tests/ref/seek/msmpeg4_avi
+++ b/tests/ref/seek/vsynth2-msmpeg4
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8637
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8637
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  82520 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  82508 size: 10783
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  53858 size:  9624
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  53846 size:  9624
 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.440000 pts: 1.440000 pos:  82520 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  82508 size: 10783
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29400 size:  8502
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29388 size:  8502
 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: 0.960000 pts: 0.960000 pos:  53858 size:  9624
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  53846 size:  9624
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8637
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114268 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114256 size: 11180
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114268 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114256 size: 11180
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29400 size:  8502
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29388 size:  8502
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8637
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114268 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114256 size: 11180
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  82520 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  82508 size: 10783
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8637
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8637
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114268 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114256 size: 11180
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  53858 size:  9624
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  53846 size:  9624
 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.440000 pts: 1.440000 pos:  82520 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  82508 size: 10783
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29400 size:  8502
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29388 size:  8502
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/msmpeg4_avi b/tests/ref/seek/vsynth2-msmpeg4v2
similarity index 87%
copy from tests/ref/seek/msmpeg4_avi
copy to tests/ref/seek/vsynth2-msmpeg4v2
index f95d615..00a175d 100644
--- a/tests/ref/seek/msmpeg4_avi
+++ b/tests/ref/seek/vsynth2-msmpeg4v2
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9003
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9003
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  82520 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83870 size: 11165
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  53858 size:  9624
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54778 size: 10010
 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.440000 pts: 1.440000 pos:  82520 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83870 size: 11165
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29400 size:  8502
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29770 size:  8869
 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: 0.960000 pts: 0.960000 pos:  53858 size:  9624
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54778 size: 10010
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9003
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114268 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116112 size: 11578
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114268 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116112 size: 11578
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29400 size:  8502
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29770 size:  8869
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9003
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114268 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116112 size: 11578
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  82520 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83870 size: 11165
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9003
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9003
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114268 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116112 size: 11578
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  53858 size:  9624
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54778 size: 10010
 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.440000 pts: 1.440000 pos:  82520 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83870 size: 11165
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29400 size:  8502
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29770 size:  8869
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/rgb_avi b/tests/ref/seek/vsynth2-rgb
similarity index 86%
rename from tests/ref/seek/rgb_avi
rename to tests/ref/seek/vsynth2-rgb
index 888032b..91f7260 100644
--- a/tests/ref/seek/rgb_avi
+++ b/tests/ref/seek/vsynth2-rgb
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:304128
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 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: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 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:1 dts: 1.880000 pts: 1.880000 pos:14300040 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: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:6088368 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:1 dts: 1.480000 pts: 1.480000 pos:11258680 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: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos:2742872 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:1 dts: 1.040000 pts: 1.040000 pos:7913184 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 dts: 0.000000 pts: 0.000000 pos:   5648 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: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:14908312 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: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:13083496 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:1 dts: 0.640000 pts: 0.640000 pos:4871824 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 dts: 0.000000 pts: 0.000000 pos:   5648 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: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:14908312 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: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:10042136 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:1 dts: 0.200000 pts: 0.200000 pos:1526328 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 dts: 0.000000 pts: 0.000000 pos:   5648 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: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:14908312 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: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:6696640 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: 0 flags:1 dts: 1.560000 pts: 1.560000 pos:11866952 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: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:3655280 size:304128
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/roqvideo_roq b/tests/ref/seek/vsynth2-roqvideo
similarity index 100%
rename from tests/ref/seek/roqvideo_roq
rename to tests/ref/seek/vsynth2-roqvideo
diff --git a/tests/ref/seek/rv10_rm b/tests/ref/seek/vsynth2-rv10
similarity index 100%
rename from tests/ref/seek/rv10_rm
rename to tests/ref/seek/vsynth2-rv10
diff --git a/tests/ref/seek/rv20_rm b/tests/ref/seek/vsynth2-rv20
similarity index 100%
rename from tests/ref/seek/rv20_rm
rename to tests/ref/seek/vsynth2-rv20
diff --git a/tests/ref/seek/snow_avi b/tests/ref/seek/vsynth2-snow
similarity index 87%
rename from tests/ref/seek/snow_avi
rename to tests/ref/seek/vsynth2-snow
index 39f8ac8..d8f5aae 100644
--- a/tests/ref/seek/snow_avi
+++ b/tests/ref/seek/vsynth2-snow
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  3035
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  3035
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  3035
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  3035
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  39726 size:  3640
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  39714 size:  3640
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  27446 size:  3494
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  27434 size:  3494
 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.440000 pts: 1.440000 pos:  39726 size:  3640
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  39714 size:  3640
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  16136 size:  3244
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  16124 size:  3244
 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: 0.960000 pts: 0.960000 pos:  27446 size:  3494
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  27434 size:  3494
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  3035
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  3035
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:  52616 size:  3582
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:  52604 size:  3582
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:  52616 size:  3582
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:  52604 size:  3582
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  16136 size:  3244
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  16124 size:  3244
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  3035
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  3035
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:  52616 size:  3582
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:  52604 size:  3582
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  39726 size:  3640
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  39714 size:  3640
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  3035
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  3035
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  3035
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  3035
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:  52616 size:  3582
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:  52604 size:  3582
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  27446 size:  3494
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  27434 size:  3494
 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.440000 pts: 1.440000 pos:  39726 size:  3640
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  39714 size:  3640
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  16136 size:  3244
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  16124 size:  3244
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/snow_ll_avi b/tests/ref/seek/vsynth2-snow-ll
similarity index 87%
rename from tests/ref/seek/snow_ll_avi
rename to tests/ref/seek/vsynth2-snow-ll
index 5eb0ba0..95a4a79 100644
--- a/tests/ref/seek/snow_ll_avi
+++ b/tests/ref/seek/vsynth2-snow-ll
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 72476
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 72476
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 72476
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 72476
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:1902800 size: 78837
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:1902788 size: 78837
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1239102 size: 74994
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1239090 size: 74994
 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.440000 pts: 1.440000 pos:1902800 size: 78837
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:1902788 size: 78837
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 605640 size: 71059
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 605628 size: 71059
 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: 0.960000 pts: 0.960000 pos:1239102 size: 74994
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1239090 size: 74994
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 72476
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 72476
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:2585626 size: 79731
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:2585614 size: 79731
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:2585626 size: 79731
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:2585614 size: 79731
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 605640 size: 71059
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 605628 size: 71059
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 72476
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 72476
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:2585626 size: 79731
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:2585614 size: 79731
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:1902800 size: 78837
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:1902788 size: 78837
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 72476
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 72476
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 72476
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 72476
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:2585626 size: 79731
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:2585614 size: 79731
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1239102 size: 74994
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1239090 size: 74994
 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.440000 pts: 1.440000 pos:1902800 size: 78837
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:1902788 size: 78837
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 605640 size: 71059
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 605628 size: 71059
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/svq1_mov b/tests/ref/seek/vsynth2-svq1
similarity index 82%
rename from tests/ref/seek/svq1_mov
rename to tests/ref/seek/vsynth2-svq1
index 17bb99e..33fe33e 100644
--- a/tests/ref/seek/svq1_mov
+++ b/tests/ref/seek/vsynth2-svq1
@@ -3,46 +3,46 @@
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     36 size: 22300
 ret: 0         st:-1 flags:1  ts: 1.894167
 ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 517568 size: 25636
-ret: 0         st: 0 flags:0  ts: 0.800000
+ret: 0         st: 0 flags:0  ts: 0.788359
 ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 326556 size: 23552
-ret: 0         st: 0 flags:1  ts:-0.320000
+ret: 0         st: 0 flags:1  ts:-0.317500
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     36 size: 22300
 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.440000 pts: 1.440000 pos: 517568 size: 25636
-ret: 0         st: 0 flags:0  ts: 0.360000
+ret: 0         st: 0 flags:0  ts: 0.365000
 ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 157040 size: 21896
-ret: 0         st: 0 flags:1  ts:-0.760000
+ret: 0         st: 0 flags:1  ts:-0.740859
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     36 size: 22300
 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: 0.960000 pts: 0.960000 pos: 326556 size: 23552
-ret: 0         st: 0 flags:0  ts:-0.040000
+ret: 0         st: 0 flags:0  ts:-0.058359
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     36 size: 22300
-ret: 0         st: 0 flags:1  ts: 2.840000
+ret: 0         st: 0 flags:1  ts: 2.835859
 ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 722804 size: 25888
 ret: 0         st:-1 flags:0  ts: 1.730004
 ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 722804 size: 25888
 ret: 0         st:-1 flags:1  ts: 0.624171
 ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 157040 size: 21896
-ret: 0         st: 0 flags:0  ts:-0.480000
+ret: 0         st: 0 flags:0  ts:-0.481641
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     36 size: 22300
-ret: 0         st: 0 flags:1  ts: 2.400000
+ret: 0         st: 0 flags:1  ts: 2.412500
 ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 722804 size: 25888
 ret: 0         st:-1 flags:0  ts: 1.306672
 ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 517568 size: 25636
 ret: 0         st:-1 flags:1  ts: 0.200839
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     36 size: 22300
-ret: 0         st: 0 flags:0  ts:-0.920000
+ret: 0         st: 0 flags:0  ts:-0.905000
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     36 size: 22300
-ret: 0         st: 0 flags:1  ts: 2.000000
+ret: 0         st: 0 flags:1  ts: 1.989141
 ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 722804 size: 25888
 ret: 0         st:-1 flags:0  ts: 0.883340
 ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 326556 size: 23552
 ret: 0         st:-1 flags:1  ts:-0.222493
 ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:     36 size: 22300
-ret:-1         st: 0 flags:0  ts: 2.680000
-ret: 0         st: 0 flags:1  ts: 1.560000
+ret:-1         st: 0 flags:0  ts: 2.671641
+ret: 0         st: 0 flags:1  ts: 1.565859
 ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 517568 size: 25636
 ret: 0         st:-1 flags:0  ts: 0.460008
 ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 157040 size: 21896
diff --git a/tests/ref/seek/msmpeg4_avi b/tests/ref/seek/vsynth2-wmv1
similarity index 87%
rename from tests/ref/seek/msmpeg4_avi
rename to tests/ref/seek/vsynth2-wmv1
index f95d615..0f073b2 100644
--- a/tests/ref/seek/msmpeg4_avi
+++ b/tests/ref/seek/vsynth2-wmv1
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8990
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8990
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  82520 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83742 size: 11099
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  53858 size:  9624
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54758 size:  9931
 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.440000 pts: 1.440000 pos:  82520 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83742 size: 11099
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29400 size:  8502
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29794 size:  8796
 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: 0.960000 pts: 0.960000 pos:  53858 size:  9624
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54758 size:  9931
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8990
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114268 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 115806 size: 11486
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114268 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 115806 size: 11486
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29400 size:  8502
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29794 size:  8796
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8990
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114268 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 115806 size: 11486
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  82520 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83742 size: 11099
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8990
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8990
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114268 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 115806 size: 11486
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  53858 size:  9624
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54758 size:  9931
 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.440000 pts: 1.440000 pos:  82520 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83742 size: 11099
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29400 size:  8502
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29794 size:  8796
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/msmpeg4_avi b/tests/ref/seek/vsynth2-wmv2
similarity index 87%
copy from tests/ref/seek/msmpeg4_avi
copy to tests/ref/seek/vsynth2-wmv2
index f95d615..8b9d3f3 100644
--- a/tests/ref/seek/msmpeg4_avi
+++ b/tests/ref/seek/vsynth2-wmv2
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8917
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8917
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  82520 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83790 size: 11169
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  53858 size:  9624
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54572 size:  9989
 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.440000 pts: 1.440000 pos:  82520 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83790 size: 11169
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29400 size:  8502
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29632 size:  8839
 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: 0.960000 pts: 0.960000 pos:  53858 size:  9624
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54572 size:  9989
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8917
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114268 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116044 size: 11554
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114268 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116044 size: 11554
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29400 size:  8502
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29632 size:  8839
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8917
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114268 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116044 size: 11554
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  82520 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83790 size: 11169
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8917
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8917
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114268 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116044 size: 11554
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  53858 size:  9624
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54572 size:  9989
 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.440000 pts: 1.440000 pos:  82520 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83790 size: 11169
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29400 size:  8502
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29632 size:  8839
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/yuv_avi b/tests/ref/seek/vsynth2-yuv
similarity index 87%
rename from tests/ref/seek/yuv_avi
rename to tests/ref/seek/vsynth2-yuv
index 49c514e..d440761 100644
--- a/tests/ref/seek/yuv_avi
+++ b/tests/ref/seek/vsynth2-yuv
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:152064
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 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: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 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:1 dts: 1.880000 pts: 1.880000 pos:7153032 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: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:3047088 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:1 dts: 1.480000 pts: 1.480000 pos:5632312 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: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos:1374296 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:1 dts: 1.040000 pts: 1.040000 pos:3959520 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 dts: 0.000000 pts: 0.000000 pos:   5648 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: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:7457176 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: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:6544744 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:1 dts: 0.640000 pts: 0.640000 pos:2438800 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 dts: 0.000000 pts: 0.000000 pos:   5648 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: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:7457176 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: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:5024024 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:1 dts: 0.200000 pts: 0.200000 pos: 766008 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 dts: 0.000000 pts: 0.000000 pos:   5648 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: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:7457176 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: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:3351232 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: 0 flags:1 dts: 1.560000 pts: 1.560000 pos:5936456 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: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:1830512 size:152064
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/wmv1_avi b/tests/ref/seek/wmv1_avi
deleted file mode 100644
index 836f7b6..0000000
--- a/tests/ref/seek/wmv1_avi
+++ /dev/null
@@ -1,46 +0,0 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8990
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8990
-ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83754 size: 11099
-ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54770 size:  9931
-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.440000 pts: 1.440000 pos:  83754 size: 11099
-ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29806 size:  8796
-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: 0.960000 pts: 0.960000 pos:  54770 size:  9931
-ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8990
-ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 115818 size: 11486
-ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 115818 size: 11486
-ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29806 size:  8796
-ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8990
-ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 115818 size: 11486
-ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83754 size: 11099
-ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8990
-ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size:  8990
-ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 115818 size: 11486
-ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54770 size:  9931
-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.440000 pts: 1.440000 pos:  83754 size: 11099
-ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29806 size:  8796
-ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/wmv2_avi b/tests/ref/seek/wmv2_avi
deleted file mode 100644
index af03bea..0000000
--- a/tests/ref/seek/wmv2_avi
+++ /dev/null
@@ -1,46 +0,0 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5664 size:  8917
-ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5664 size:  8917
-ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83802 size: 11169
-ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54584 size:  9989
-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.440000 pts: 1.440000 pos:  83802 size: 11169
-ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29644 size:  8839
-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: 0.960000 pts: 0.960000 pos:  54584 size:  9989
-ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5664 size:  8917
-ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116056 size: 11554
-ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116056 size: 11554
-ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29644 size:  8839
-ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5664 size:  8917
-ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116056 size: 11554
-ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83802 size: 11169
-ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5664 size:  8917
-ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5664 size:  8917
-ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116056 size: 11554
-ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54584 size:  9989
-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.440000 pts: 1.440000 pos:  83802 size: 11169
-ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29644 size:  8839
-ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/vsynth/vsynth1-amv b/tests/ref/vsynth/vsynth1-amv
new file mode 100644
index 0000000..f7c7f57
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-amv
@@ -0,0 +1,4 @@
+34c4d4033d31c7401d32fee9d6ce0de2 *tests/data/fate/vsynth1-amv.avi
+1365496 tests/data/fate/vsynth1-amv.avi
+e38681b9527b6d2531942f8a176a0265 *tests/data/fate/vsynth1-amv.out.rawvideo
+stddev:   10.07 PSNR: 28.06 MAXDIFF:   98 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-asv1 b/tests/ref/vsynth/vsynth1-asv1
new file mode 100644
index 0000000..e640f1c
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-asv1
@@ -0,0 +1,4 @@
+41b011551d23ddadaab1083cb2106d9f *tests/data/fate/vsynth1-asv1.avi
+1489644 tests/data/fate/vsynth1-asv1.avi
+2dfc5dfc2c1cbbc2543257cd3d2df6af *tests/data/fate/vsynth1-asv1.out.rawvideo
+stddev:   20.00 PSNR: 22.11 MAXDIFF:  158 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-asv2 b/tests/ref/vsynth/vsynth1-asv2
new file mode 100644
index 0000000..6282ad4
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-asv2
@@ -0,0 +1,4 @@
+a0773690d0e772ff832adea1e8c16773 *tests/data/fate/vsynth1-asv2.avi
+1456044 tests/data/fate/vsynth1-asv2.avi
+d451be09793cd0f35b6d91fc36e2571a *tests/data/fate/vsynth1-asv2.out.rawvideo
+stddev:   18.82 PSNR: 22.63 MAXDIFF:  131 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-avui b/tests/ref/vsynth/vsynth1-avui
similarity index 74%
rename from tests/ref/fate/vsynth1-avui
rename to tests/ref/vsynth/vsynth1-avui
index 720fa32..03f2b31 100644
--- a/tests/ref/fate/vsynth1-avui
+++ b/tests/ref/vsynth/vsynth1-avui
@@ -1,4 +1,4 @@
-6094fe77d3a4c49cae45a3de088bdb1a *tests/data/fate/vsynth1-avui.mov
+853dad3a1248614c6d61c2f9dc2a999c *tests/data/fate/vsynth1-avui.mov
 42624907 tests/data/fate/vsynth1-avui.mov
 c5ccac874dbf808e9088bc3107860042 *tests/data/fate/vsynth1-avui.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-cljr b/tests/ref/vsynth/vsynth1-cljr
new file mode 100644
index 0000000..5207d92
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-cljr
@@ -0,0 +1,4 @@
+eb9131f74c29cda83ba706293c85afb4 *tests/data/fate/vsynth1-cljr.avi
+5075648 tests/data/fate/vsynth1-cljr.avi
+7bd979b8b397f7bac22a0102c7889452 *tests/data/fate/vsynth1-cljr.out.rawvideo
+stddev:    6.74 PSNR: 31.55 MAXDIFF:   84 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-dnxhd-1080i b/tests/ref/vsynth/vsynth1-dnxhd-1080i
similarity index 76%
rename from tests/ref/fate/vsynth1-dnxhd-1080i
rename to tests/ref/vsynth/vsynth1-dnxhd-1080i
index d47f76b..899ef9e 100644
--- a/tests/ref/fate/vsynth1-dnxhd-1080i
+++ b/tests/ref/vsynth/vsynth1-dnxhd-1080i
@@ -1,4 +1,4 @@
-fac7cbb7541f485ec3b1a7a24dbdca8f *tests/data/fate/vsynth1-dnxhd-1080i.mov
+9a4781b0a052d9efaafbaf8893db9632 *tests/data/fate/vsynth1-dnxhd-1080i.mov
 3031911 tests/data/fate/vsynth1-dnxhd-1080i.mov
 e55bf857297ba4d911a9d17a984b125d *tests/data/fate/vsynth1-dnxhd-1080i.out.rawvideo
 stddev:    6.29 PSNR: 32.15 MAXDIFF:   64 bytes:  7603200/   760320
diff --git a/tests/ref/fate/vsynth1-dnxhd-720p b/tests/ref/vsynth/vsynth1-dnxhd-720p
similarity index 100%
rename from tests/ref/fate/vsynth1-dnxhd-720p
rename to tests/ref/vsynth/vsynth1-dnxhd-720p
diff --git a/tests/ref/fate/vsynth1-dnxhd-720p-10bit b/tests/ref/vsynth/vsynth1-dnxhd-720p-10bit
similarity index 100%
rename from tests/ref/fate/vsynth1-dnxhd-720p-10bit
rename to tests/ref/vsynth/vsynth1-dnxhd-720p-10bit
diff --git a/tests/ref/fate/vsynth1-dnxhd-720p-rd b/tests/ref/vsynth/vsynth1-dnxhd-720p-rd
similarity index 100%
rename from tests/ref/fate/vsynth1-dnxhd-720p-rd
rename to tests/ref/vsynth/vsynth1-dnxhd-720p-rd
diff --git a/tests/ref/fate/vsynth1-dnxhd_1080i b/tests/ref/vsynth/vsynth1-dnxhd_1080i
similarity index 100%
rename from tests/ref/fate/vsynth1-dnxhd_1080i
rename to tests/ref/vsynth/vsynth1-dnxhd_1080i
diff --git a/tests/ref/fate/vsynth1-dv b/tests/ref/vsynth/vsynth1-dv
similarity index 100%
rename from tests/ref/fate/vsynth1-dv
rename to tests/ref/vsynth/vsynth1-dv
diff --git a/tests/ref/fate/vsynth1-dv-411 b/tests/ref/vsynth/vsynth1-dv-411
similarity index 100%
rename from tests/ref/fate/vsynth1-dv-411
rename to tests/ref/vsynth/vsynth1-dv-411
diff --git a/tests/ref/fate/vsynth1-dv-50 b/tests/ref/vsynth/vsynth1-dv-50
similarity index 100%
rename from tests/ref/fate/vsynth1-dv-50
rename to tests/ref/vsynth/vsynth1-dv-50
diff --git a/tests/ref/fate/vsynth1-dv_411 b/tests/ref/vsynth/vsynth1-dv_411
similarity index 100%
rename from tests/ref/fate/vsynth1-dv_411
rename to tests/ref/vsynth/vsynth1-dv_411
diff --git a/tests/ref/vsynth/vsynth1-ffv1 b/tests/ref/vsynth/vsynth1-ffv1
new file mode 100644
index 0000000..99787ed
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-ffv1
@@ -0,0 +1,4 @@
+91c237f18bc19975077c85175daed734 *tests/data/fate/vsynth1-ffv1.avi
+2655364 tests/data/fate/vsynth1-ffv1.avi
+c5ccac874dbf808e9088bc3107860042 *tests/data/fate/vsynth1-ffv1.out.rawvideo
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-ffvhuff b/tests/ref/vsynth/vsynth1-ffvhuff
new file mode 100644
index 0000000..d752c4b
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-ffvhuff
@@ -0,0 +1,4 @@
+96789e7ed68de5314e65bc496c75e0a5 *tests/data/fate/vsynth1-ffvhuff.avi
+5987196 tests/data/fate/vsynth1-ffvhuff.avi
+c5ccac874dbf808e9088bc3107860042 *tests/data/fate/vsynth1-ffvhuff.out.rawvideo
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-flashsv b/tests/ref/vsynth/vsynth1-flashsv
similarity index 100%
rename from tests/ref/fate/vsynth1-flashsv
rename to tests/ref/vsynth/vsynth1-flashsv
diff --git a/tests/ref/fate/vsynth1-flashsv2 b/tests/ref/vsynth/vsynth1-flashsv2
similarity index 100%
rename from tests/ref/fate/vsynth1-flashsv2
rename to tests/ref/vsynth/vsynth1-flashsv2
diff --git a/tests/ref/fate/vsynth1-flv b/tests/ref/vsynth/vsynth1-flv
similarity index 100%
rename from tests/ref/fate/vsynth1-flv
rename to tests/ref/vsynth/vsynth1-flv
diff --git a/tests/ref/vsynth/vsynth1-h261 b/tests/ref/vsynth/vsynth1-h261
new file mode 100644
index 0000000..02b956b
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-h261
@@ -0,0 +1,4 @@
+2e613918f64c3473b887306fc5eb3c3d *tests/data/fate/vsynth1-h261.avi
+707546 tests/data/fate/vsynth1-h261.avi
+85fde92037c2ccecc02e2d6c21a169b0 *tests/data/fate/vsynth1-h261.out.rawvideo
+stddev:    9.11 PSNR: 28.93 MAXDIFF:  113 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-h263 b/tests/ref/vsynth/vsynth1-h263
new file mode 100644
index 0000000..f985d61
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-h263
@@ -0,0 +1,4 @@
+36abb66d2480121f66a23e07d2b903be *tests/data/fate/vsynth1-h263.avi
+659674 tests/data/fate/vsynth1-h263.avi
+aef88517578fa7f53fe5159c4b6754ef *tests/data/fate/vsynth1-h263.out.rawvideo
+stddev:    8.03 PSNR: 30.03 MAXDIFF:  103 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-h263-obmc b/tests/ref/vsynth/vsynth1-h263-obmc
new file mode 100644
index 0000000..f60e252
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-h263-obmc
@@ -0,0 +1,4 @@
+ec2262cb7c674fd85afb14d9eb27d9d6 *tests/data/fate/vsynth1-h263-obmc.avi
+657316 tests/data/fate/vsynth1-h263-obmc.avi
+844f7ee27fa122e199fe20987b41a15c *tests/data/fate/vsynth1-h263-obmc.out.rawvideo
+stddev:    8.16 PSNR: 29.89 MAXDIFF:  113 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-h263p b/tests/ref/vsynth/vsynth1-h263p
new file mode 100644
index 0000000..72ef0ff
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-h263p
@@ -0,0 +1,4 @@
+03ebe03b70ee93524ec30c5abb69205a *tests/data/fate/vsynth1-h263p.avi
+2328362 tests/data/fate/vsynth1-h263p.avi
+911330cb57c99c440234392be1588081 *tests/data/fate/vsynth1-h263p.out.rawvideo
+stddev:    2.06 PSNR: 41.83 MAXDIFF:   20 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-huffyuv b/tests/ref/vsynth/vsynth1-huffyuv
new file mode 100644
index 0000000..ed08365
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-huffyuv
@@ -0,0 +1,4 @@
+829bf3e22e5d1df2aa9a709c9d5aff57 *tests/data/fate/vsynth1-huffyuv.avi
+7933788 tests/data/fate/vsynth1-huffyuv.avi
+c5ccac874dbf808e9088bc3107860042 *tests/data/fate/vsynth1-huffyuv.out.rawvideo
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-j2k b/tests/ref/vsynth/vsynth1-j2k
new file mode 100644
index 0000000..1e2f3f2
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-j2k
@@ -0,0 +1,4 @@
+e6e3d338eeb394d6fadc7bbb55fa9e6e *tests/data/fate/vsynth1-j2k.avi
+2306902 tests/data/fate/vsynth1-j2k.avi
+ee9b245b3b07eed90bc6f2147bbd916c *tests/data/fate/vsynth1-j2k.out.rawvideo
+stddev:    5.47 PSNR: 33.37 MAXDIFF:   64 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-jpegls b/tests/ref/vsynth/vsynth1-jpegls
new file mode 100644
index 0000000..fc21074
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-jpegls
@@ -0,0 +1,4 @@
+f8acf917e24ea6c9200f2cdf99744ca9 *tests/data/fate/vsynth1-jpegls.avi
+9089800 tests/data/fate/vsynth1-jpegls.avi
+791e1fb999deb2e4156e2286d48c4ed1 *tests/data/fate/vsynth1-jpegls.out.rawvideo
+stddev:    2.84 PSNR: 39.04 MAXDIFF:   49 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-ljpeg b/tests/ref/vsynth/vsynth1-ljpeg
new file mode 100644
index 0000000..e229db5
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-ljpeg
@@ -0,0 +1,4 @@
+2b1a2d5ad7f357df955d8548320d13f7 *tests/data/fate/vsynth1-ljpeg.avi
+6312924 tests/data/fate/vsynth1-ljpeg.avi
+c5ccac874dbf808e9088bc3107860042 *tests/data/fate/vsynth1-ljpeg.out.rawvideo
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-mjpeg b/tests/ref/vsynth/vsynth1-mjpeg
new file mode 100644
index 0000000..80f15ca
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-mjpeg
@@ -0,0 +1,4 @@
+3d3a9cef95621e1c153649721c5a8590 *tests/data/fate/vsynth1-mjpeg.avi
+1515902 tests/data/fate/vsynth1-mjpeg.avi
+9a3b8169c251d19044f7087a95458c55 *tests/data/fate/vsynth1-mjpeg.out.rawvideo
+stddev:    7.87 PSNR: 30.21 MAXDIFF:   63 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-mjpeg-422 b/tests/ref/vsynth/vsynth1-mjpeg-422
new file mode 100644
index 0000000..e631a2b
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-mjpeg-422
@@ -0,0 +1,4 @@
+cd452cb6a2967b2f3bd2d31de6c95bf1 *tests/data/fate/vsynth1-mjpeg-422.avi
+1756300 tests/data/fate/vsynth1-mjpeg-422.avi
+c35eea486c6d72050f4848eab64032b5 *tests/data/fate/vsynth1-mjpeg-422.out.rawvideo
+stddev:    7.45 PSNR: 30.69 MAXDIFF:   63 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-mjpeg-444 b/tests/ref/vsynth/vsynth1-mjpeg-444
new file mode 100644
index 0000000..3ad0c51
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-mjpeg-444
@@ -0,0 +1,4 @@
+bf3e8f03857c8b3c7b1cdc7bb1aa5bae *tests/data/fate/vsynth1-mjpeg-444.avi
+1987582 tests/data/fate/vsynth1-mjpeg-444.avi
+313a4a76af13d5879ea4910107b7ea74 *tests/data/fate/vsynth1-mjpeg-444.out.rawvideo
+stddev:    7.37 PSNR: 30.77 MAXDIFF:   63 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-mpeg1 b/tests/ref/vsynth/vsynth1-mpeg1
similarity index 100%
rename from tests/ref/fate/vsynth1-mpeg1
rename to tests/ref/vsynth/vsynth1-mpeg1
diff --git a/tests/ref/fate/vsynth1-mpeg1b b/tests/ref/vsynth/vsynth1-mpeg1b
similarity index 100%
rename from tests/ref/fate/vsynth1-mpeg1b
rename to tests/ref/vsynth/vsynth1-mpeg1b
diff --git a/tests/ref/fate/vsynth1-mpeg2 b/tests/ref/vsynth/vsynth1-mpeg2
similarity index 100%
rename from tests/ref/fate/vsynth1-mpeg2
rename to tests/ref/vsynth/vsynth1-mpeg2
diff --git a/tests/ref/fate/vsynth1-mpeg2-422 b/tests/ref/vsynth/vsynth1-mpeg2-422
similarity index 100%
rename from tests/ref/fate/vsynth1-mpeg2-422
rename to tests/ref/vsynth/vsynth1-mpeg2-422
diff --git a/tests/ref/fate/vsynth1-mpeg2-idct-int b/tests/ref/vsynth/vsynth1-mpeg2-idct-int
similarity index 100%
rename from tests/ref/fate/vsynth1-mpeg2-idct-int
rename to tests/ref/vsynth/vsynth1-mpeg2-idct-int
diff --git a/tests/ref/fate/vsynth1-mpeg2-ilace b/tests/ref/vsynth/vsynth1-mpeg2-ilace
similarity index 100%
rename from tests/ref/fate/vsynth1-mpeg2-ilace
rename to tests/ref/vsynth/vsynth1-mpeg2-ilace
diff --git a/tests/ref/fate/vsynth1-mpeg2-ivlc-qprd b/tests/ref/vsynth/vsynth1-mpeg2-ivlc-qprd
similarity index 100%
rename from tests/ref/fate/vsynth1-mpeg2-ivlc-qprd
rename to tests/ref/vsynth/vsynth1-mpeg2-ivlc-qprd
diff --git a/tests/ref/fate/vsynth1-mpeg2-thread b/tests/ref/vsynth/vsynth1-mpeg2-thread
similarity index 100%
rename from tests/ref/fate/vsynth1-mpeg2-thread
rename to tests/ref/vsynth/vsynth1-mpeg2-thread
diff --git a/tests/ref/fate/vsynth1-mpeg2-thread-ivlc b/tests/ref/vsynth/vsynth1-mpeg2-thread-ivlc
similarity index 100%
rename from tests/ref/fate/vsynth1-mpeg2-thread-ivlc
rename to tests/ref/vsynth/vsynth1-mpeg2-thread-ivlc
diff --git a/tests/ref/fate/vsynth1-mpeg4 b/tests/ref/vsynth/vsynth1-mpeg4
similarity index 74%
rename from tests/ref/fate/vsynth1-mpeg4
rename to tests/ref/vsynth/vsynth1-mpeg4
index f556c21..b6da11c 100644
--- a/tests/ref/fate/vsynth1-mpeg4
+++ b/tests/ref/vsynth/vsynth1-mpeg4
@@ -1,4 +1,4 @@
-1283a1904765c40b7602402867a86c4f *tests/data/fate/vsynth1-mpeg4.mp4
+a2acdf772bf7b7641079d8a03ea03ccf *tests/data/fate/vsynth1-mpeg4.mp4
 540024 tests/data/fate/vsynth1-mpeg4.mp4
 f80ec173d37f2f91add031e95579a220 *tests/data/fate/vsynth1-mpeg4.out.rawvideo
 stddev:    7.97 PSNR: 30.10 MAXDIFF:  105 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-mpeg4-adap b/tests/ref/vsynth/vsynth1-mpeg4-adap
new file mode 100644
index 0000000..00ea53d
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-mpeg4-adap
@@ -0,0 +1,4 @@
+2aa8bfefc09135a9a25dc23e3a14c6a4 *tests/data/fate/vsynth1-mpeg4-adap.avi
+403432 tests/data/fate/vsynth1-mpeg4-adap.avi
+fad0b9dc08fe4a95b297af1a7411c1e9 *tests/data/fate/vsynth1-mpeg4-adap.out.rawvideo
+stddev:   14.05 PSNR: 25.17 MAXDIFF:  184 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-mpeg4-adv b/tests/ref/vsynth/vsynth1-mpeg4-adv
new file mode 100644
index 0000000..a67cc14
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-mpeg4-adv
@@ -0,0 +1,4 @@
+b12cf575e8a28975cfeb67c23870afdd *tests/data/fate/vsynth1-mpeg4-adv.avi
+589704 tests/data/fate/vsynth1-mpeg4-adv.avi
+b651bd94456005a1990fb64c28306262 *tests/data/fate/vsynth1-mpeg4-adv.out.rawvideo
+stddev:    6.98 PSNR: 31.25 MAXDIFF:   84 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-mpeg4-error b/tests/ref/vsynth/vsynth1-mpeg4-error
new file mode 100644
index 0000000..b694362
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-mpeg4-error
@@ -0,0 +1,4 @@
+5a6d923425ff437924d4723aa73a817f *tests/data/fate/vsynth1-mpeg4-error.avi
+752346 tests/data/fate/vsynth1-mpeg4-error.avi
+5853c8c789f260ae4dcbf37a17d04b66 *tests/data/fate/vsynth1-mpeg4-error.out.rawvideo
+stddev:   17.33 PSNR: 23.35 MAXDIFF:  229 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-mpeg4-nr b/tests/ref/vsynth/vsynth1-mpeg4-nr
new file mode 100644
index 0000000..e71dd2b
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-mpeg4-nr
@@ -0,0 +1,4 @@
+6515d1676d4d0c92c85c0468c53261aa *tests/data/fate/vsynth1-mpeg4-nr.avi
+675452 tests/data/fate/vsynth1-mpeg4-nr.avi
+5fee518cde41e5567f800fbe14210fb8 *tests/data/fate/vsynth1-mpeg4-nr.out.rawvideo
+stddev:    6.99 PSNR: 31.24 MAXDIFF:   86 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-mpeg4-qpel b/tests/ref/vsynth/vsynth1-mpeg4-qpel
new file mode 100644
index 0000000..67b72a1
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-mpeg4-qpel
@@ -0,0 +1,4 @@
+594626acf31cbfc4a14af4d9b3cd8a6c *tests/data/fate/vsynth1-mpeg4-qpel.avi
+858680 tests/data/fate/vsynth1-mpeg4-qpel.avi
+5089090df7169eb482532df5471d7f5f *tests/data/fate/vsynth1-mpeg4-qpel.out.rawvideo
+stddev:    5.63 PSNR: 33.11 MAXDIFF:   70 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-mpeg4-qprd b/tests/ref/vsynth/vsynth1-mpeg4-qprd
new file mode 100644
index 0000000..0475e70
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-mpeg4-qprd
@@ -0,0 +1,4 @@
+96590e5921628ff84d109624e6124911 *tests/data/fate/vsynth1-mpeg4-qprd.avi
+710672 tests/data/fate/vsynth1-mpeg4-qprd.avi
+693231ac7e6fbf8758415f9f2509408d *tests/data/fate/vsynth1-mpeg4-qprd.out.rawvideo
+stddev:    9.79 PSNR: 28.31 MAXDIFF:  176 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-mpeg4-rc b/tests/ref/vsynth/vsynth1-mpeg4-rc
new file mode 100644
index 0000000..96e41be
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-mpeg4-rc
@@ -0,0 +1,4 @@
+59cf839b030f7df30b95fd300c4defb1 *tests/data/fate/vsynth1-mpeg4-rc.avi
+830494 tests/data/fate/vsynth1-mpeg4-rc.avi
+9dcd9d022ae14fe1e4a53aa4865464c6 *tests/data/fate/vsynth1-mpeg4-rc.out.rawvideo
+stddev:   10.24 PSNR: 27.92 MAXDIFF:  196 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-mpeg4-thread b/tests/ref/vsynth/vsynth1-mpeg4-thread
new file mode 100644
index 0000000..a998273
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-mpeg4-thread
@@ -0,0 +1,4 @@
+14059560812963039e852f4f6419c238 *tests/data/fate/vsynth1-mpeg4-thread.avi
+774750 tests/data/fate/vsynth1-mpeg4-thread.avi
+9aa327a244d5179acf7fe64dc1459bff *tests/data/fate/vsynth1-mpeg4-thread.out.rawvideo
+stddev:   10.13 PSNR: 28.02 MAXDIFF:  183 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-mpng b/tests/ref/vsynth/vsynth1-mpng
new file mode 100644
index 0000000..5ca268b
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-mpng
@@ -0,0 +1,4 @@
+10bcdf8600d3985aeb57dc774df2b747 *tests/data/fate/vsynth1-mpng.avi
+12158276 tests/data/fate/vsynth1-mpng.avi
+93695a27c24a61105076ca7b1f010bbd *tests/data/fate/vsynth1-mpng.out.rawvideo
+stddev:    3.42 PSNR: 37.44 MAXDIFF:   48 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-msmpeg4 b/tests/ref/vsynth/vsynth1-msmpeg4
new file mode 100644
index 0000000..4adabbe
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-msmpeg4
@@ -0,0 +1,4 @@
+7d9d622b04156246348bde2e3a4d9c9c *tests/data/fate/vsynth1-msmpeg4.avi
+624702 tests/data/fate/vsynth1-msmpeg4.avi
+4529fee96b8073e02974f5355e5f6c4e *tests/data/fate/vsynth1-msmpeg4.out.rawvideo
+stddev:    7.98 PSNR: 30.09 MAXDIFF:  104 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-msmpeg4v2 b/tests/ref/vsynth/vsynth1-msmpeg4v2
new file mode 100644
index 0000000..775d575
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-msmpeg4v2
@@ -0,0 +1,4 @@
+a0539692d72e763448fc0dbe98d92ea3 *tests/data/fate/vsynth1-msmpeg4v2.avi
+623766 tests/data/fate/vsynth1-msmpeg4v2.avi
+0476d9aafc4358654f411fa9648f9560 *tests/data/fate/vsynth1-msmpeg4v2.out.rawvideo
+stddev:    7.97 PSNR: 30.10 MAXDIFF:  105 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-msvideo1 b/tests/ref/vsynth/vsynth1-msvideo1
new file mode 100644
index 0000000..0ab8860
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-msvideo1
@@ -0,0 +1,4 @@
+bea8dd62e64453fb08e4f3d19be23792 *tests/data/fate/vsynth1-msvideo1.avi
+2051892 tests/data/fate/vsynth1-msvideo1.avi
+f4605ac6df556a3ca7053c49aaac04d8 *tests/data/fate/vsynth1-msvideo1.out.rawvideo
+stddev:   11.89 PSNR: 26.62 MAXDIFF:  159 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-prores b/tests/ref/vsynth/vsynth1-prores
new file mode 100644
index 0000000..16517ee
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-prores
@@ -0,0 +1,4 @@
+6f7ce83099b35e5af0cf484f2e9f1f4f *tests/data/fate/vsynth1-prores.mov
+5022821 tests/data/fate/vsynth1-prores.mov
+a2e2d1d45341a94ff994d1d92629f778 *tests/data/fate/vsynth1-prores.out.rawvideo
+stddev:    2.47 PSNR: 40.27 MAXDIFF:   31 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-prores_kostya b/tests/ref/vsynth/vsynth1-prores_kostya
new file mode 100644
index 0000000..ab6ecff
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-prores_kostya
@@ -0,0 +1,4 @@
+36411e06db3f86ddedd6171a56784d6b *tests/data/fate/vsynth1-prores_kostya.mov
+3858911 tests/data/fate/vsynth1-prores_kostya.mov
+0a4153637d0cc0a88a8bcbf04cfaf8c6 *tests/data/fate/vsynth1-prores_kostya.out.rawvideo
+stddev:    3.17 PSNR: 38.09 MAXDIFF:   39 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-qtrle b/tests/ref/vsynth/vsynth1-qtrle
new file mode 100644
index 0000000..9bd79cc
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-qtrle
@@ -0,0 +1,4 @@
+4eaa59011403ce3e53f8abb5cf6d26e5 *tests/data/fate/vsynth1-qtrle.mov
+15263158 tests/data/fate/vsynth1-qtrle.mov
+93695a27c24a61105076ca7b1f010bbd *tests/data/fate/vsynth1-qtrle.out.rawvideo
+stddev:    3.42 PSNR: 37.44 MAXDIFF:   48 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-qtrlegray b/tests/ref/vsynth/vsynth1-qtrlegray
new file mode 100644
index 0000000..425c11f
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-qtrlegray
@@ -0,0 +1,4 @@
+d010ff7be190f4cd053d79ee7f601ce2 *tests/data/fate/vsynth1-qtrlegray.mov
+5113294 tests/data/fate/vsynth1-qtrlegray.mov
+29def4aed035ed65d3a89f7d382fccbe *tests/data/fate/vsynth1-qtrlegray.out.rawvideo
+stddev:   25.95 PSNR: 19.85 MAXDIFF:  122 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-r210 b/tests/ref/vsynth/vsynth1-r210
new file mode 100644
index 0000000..15b56a2
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-r210
@@ -0,0 +1,4 @@
+80c966b18025897207ab624206a6e7a0 *tests/data/fate/vsynth1-r210.avi
+22125248 tests/data/fate/vsynth1-r210.avi
+ecaafa9eec11b5e1453a63ed6d194eed *tests/data/fate/vsynth1-r210.out.rawvideo
+stddev:    3.23 PSNR: 37.94 MAXDIFF:   48 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-rgb b/tests/ref/vsynth/vsynth1-rgb
new file mode 100644
index 0000000..3db3348
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-rgb
@@ -0,0 +1,4 @@
+d78bcd5828862c3342388ec8a2c34fef *tests/data/fate/vsynth1-rgb.avi
+15213248 tests/data/fate/vsynth1-rgb.avi
+93695a27c24a61105076ca7b1f010bbd *tests/data/fate/vsynth1-rgb.out.rawvideo
+stddev:    3.42 PSNR: 37.44 MAXDIFF:   48 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-roqvideo b/tests/ref/vsynth/vsynth1-roqvideo
similarity index 100%
rename from tests/ref/fate/vsynth1-roqvideo
rename to tests/ref/vsynth/vsynth1-roqvideo
diff --git a/tests/ref/fate/vsynth1-rv10 b/tests/ref/vsynth/vsynth1-rv10
similarity index 100%
rename from tests/ref/fate/vsynth1-rv10
rename to tests/ref/vsynth/vsynth1-rv10
diff --git a/tests/ref/fate/vsynth1-rv20 b/tests/ref/vsynth/vsynth1-rv20
similarity index 100%
rename from tests/ref/fate/vsynth1-rv20
rename to tests/ref/vsynth/vsynth1-rv20
diff --git a/tests/ref/vsynth/vsynth1-snow b/tests/ref/vsynth/vsynth1-snow
new file mode 100644
index 0000000..701b5cc
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-snow
@@ -0,0 +1,4 @@
+44fed844eb715fba0cc2433e7d7713bb *tests/data/fate/vsynth1-snow.avi
+136076 tests/data/fate/vsynth1-snow.avi
+91021b7d6d7908648fe78cc1975af8c4 *tests/data/fate/vsynth1-snow.out.rawvideo
+stddev:   22.77 PSNR: 20.98 MAXDIFF:  172 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-snow-hpel b/tests/ref/vsynth/vsynth1-snow-hpel
new file mode 100644
index 0000000..c22ad0a
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-snow-hpel
@@ -0,0 +1,4 @@
+f60c8cb8f41b66bc38df87e9bdb84b34 *tests/data/fate/vsynth1-snow-hpel.avi
+138700 tests/data/fate/vsynth1-snow-hpel.avi
+d6845c8f1310e041afdcebc6bbfc449b *tests/data/fate/vsynth1-snow-hpel.out.rawvideo
+stddev:   22.74 PSNR: 20.99 MAXDIFF:  171 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-snow-ll b/tests/ref/vsynth/vsynth1-snow-ll
new file mode 100644
index 0000000..1636af5
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-snow-ll
@@ -0,0 +1,4 @@
+bdc7a025cd306f3da0d377b06bbe909b *tests/data/fate/vsynth1-snow-ll.avi
+3419968 tests/data/fate/vsynth1-snow-ll.avi
+c5ccac874dbf808e9088bc3107860042 *tests/data/fate/vsynth1-snow-ll.out.rawvideo
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-svq1 b/tests/ref/vsynth/vsynth1-svq1
new file mode 100644
index 0000000..6be76e1
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-svq1
@@ -0,0 +1,4 @@
+ea441979fa5bf694d1f6cee958d56560 *tests/data/fate/vsynth1-svq1.mov
+1334233 tests/data/fate/vsynth1-svq1.mov
+9cc35c54b2c77d36bd7e308b393c1f81 *tests/data/fate/vsynth1-svq1.out.rawvideo
+stddev:    9.58 PSNR: 28.50 MAXDIFF:  210 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-v210 b/tests/ref/vsynth/vsynth1-v210
new file mode 100644
index 0000000..defd2f6
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-v210
@@ -0,0 +1,4 @@
+054d7e903fb4d9e68700c56b93d45916 *tests/data/fate/vsynth1-v210.avi
+14752448 tests/data/fate/vsynth1-v210.avi
+50973792d3f1abe04a51ee0121f077f2 *tests/data/fate/vsynth1-v210.out.rawvideo
+stddev:    1.85 PSNR: 42.78 MAXDIFF:   29 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-v308 b/tests/ref/vsynth/vsynth1-v308
new file mode 100644
index 0000000..7dc5de9
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-v308
@@ -0,0 +1,4 @@
+05552ba36d003f8d5fec739c5ed90a67 *tests/data/fate/vsynth1-v308.avi
+15213248 tests/data/fate/vsynth1-v308.avi
+10fb42f1abf40a289c3edafc0390482c *tests/data/fate/vsynth1-v308.out.rawvideo
+stddev:    2.67 PSNR: 39.60 MAXDIFF:   43 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-v408 b/tests/ref/vsynth/vsynth1-v408
new file mode 100644
index 0000000..f1523d1
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-v408
@@ -0,0 +1,4 @@
+415c94a79b0eb58c445221a362e0054e *tests/data/fate/vsynth1-v408.avi
+20282048 tests/data/fate/vsynth1-v408.avi
+c5ccac874dbf808e9088bc3107860042 *tests/data/fate/vsynth1-v408.out.rawvideo
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-wmv1 b/tests/ref/vsynth/vsynth1-wmv1
new file mode 100644
index 0000000..8d24543
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-wmv1
@@ -0,0 +1,4 @@
+2760d19cb77d84bd5bfc588d23306113 *tests/data/fate/vsynth1-wmv1.avi
+626870 tests/data/fate/vsynth1-wmv1.avi
+3354066ebdd8cd8098394be2384744e7 *tests/data/fate/vsynth1-wmv1.out.rawvideo
+stddev:    7.97 PSNR: 30.09 MAXDIFF:  110 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-wmv2 b/tests/ref/vsynth/vsynth1-wmv2
new file mode 100644
index 0000000..79a1302
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-wmv2
@@ -0,0 +1,4 @@
+532f99495482015c12a2773ec1065a4d *tests/data/fate/vsynth1-wmv2.avi
+659832 tests/data/fate/vsynth1-wmv2.avi
+3354066ebdd8cd8098394be2384744e7 *tests/data/fate/vsynth1-wmv2.out.rawvideo
+stddev:    7.97 PSNR: 30.09 MAXDIFF:  110 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-y41p b/tests/ref/vsynth/vsynth1-y41p
new file mode 100644
index 0000000..93fa938
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-y41p
@@ -0,0 +1,4 @@
+c9fce228075067c51511d8b070fde340 *tests/data/fate/vsynth1-y41p.avi
+7610048 tests/data/fate/vsynth1-y41p.avi
+3aef1d83732a3f9835ee2523a11c95c1 *tests/data/fate/vsynth1-y41p.out.rawvideo
+stddev:    5.98 PSNR: 32.59 MAXDIFF:   87 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-yuv b/tests/ref/vsynth/vsynth1-yuv
new file mode 100644
index 0000000..2eeff80
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-yuv
@@ -0,0 +1,4 @@
+9622cbbe3ced7490f50e74cf088bc7c9 *tests/data/fate/vsynth1-yuv.avi
+7610048 tests/data/fate/vsynth1-yuv.avi
+c5ccac874dbf808e9088bc3107860042 *tests/data/fate/vsynth1-yuv.out.rawvideo
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-yuv4 b/tests/ref/vsynth/vsynth1-yuv4
new file mode 100644
index 0000000..5c473a2
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-yuv4
@@ -0,0 +1,4 @@
+45805be52d9807f0c6f76011a64bf67b *tests/data/fate/vsynth1-yuv4.avi
+7610048 tests/data/fate/vsynth1-yuv4.avi
+c5ccac874dbf808e9088bc3107860042 *tests/data/fate/vsynth1-yuv4.out.rawvideo
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-zlib b/tests/ref/vsynth/vsynth1-zlib
new file mode 100644
index 0000000..f5441e1
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-zlib
@@ -0,0 +1,4 @@
+fd52fff386f172bb3aef97761b99331c *tests/data/fate/vsynth1-zlib.avi
+12108632 tests/data/fate/vsynth1-zlib.avi
+93695a27c24a61105076ca7b1f010bbd *tests/data/fate/vsynth1-zlib.out.rawvideo
+stddev:    3.42 PSNR: 37.44 MAXDIFF:   48 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth1-zmbv b/tests/ref/vsynth/vsynth1-zmbv
similarity index 100%
rename from tests/ref/fate/vsynth1-zmbv
rename to tests/ref/vsynth/vsynth1-zmbv
diff --git a/tests/ref/vsynth/vsynth2-amv b/tests/ref/vsynth/vsynth2-amv
new file mode 100644
index 0000000..6937df3
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-amv
@@ -0,0 +1,4 @@
+26d039bc37b2186d57522a8e3dc76217 *tests/data/fate/vsynth2-amv.avi
+761976 tests/data/fate/vsynth2-amv.avi
+f256ad9feefb499c6569d06d868eb496 *tests/data/fate/vsynth2-amv.out.rawvideo
+stddev:    4.30 PSNR: 35.46 MAXDIFF:   65 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-asv1 b/tests/ref/vsynth/vsynth2-asv1
new file mode 100644
index 0000000..282435b
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-asv1
@@ -0,0 +1,4 @@
+ae8d79e0e421138a9a67a148a42c26c5 *tests/data/fate/vsynth2-asv1.avi
+832500 tests/data/fate/vsynth2-asv1.avi
+c96ff7fd17c52f99ddb7922a4cb9168f *tests/data/fate/vsynth2-asv1.out.rawvideo
+stddev:   10.47 PSNR: 27.73 MAXDIFF:   98 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-asv2 b/tests/ref/vsynth/vsynth2-asv2
new file mode 100644
index 0000000..8942862
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-asv2
@@ -0,0 +1,4 @@
+ccf6762758395eee9a29ef7a4ef3cd58 *tests/data/fate/vsynth2-asv2.avi
+789060 tests/data/fate/vsynth2-asv2.avi
+74a78015b64b2cf8cb9da2e44f508a69 *tests/data/fate/vsynth2-asv2.out.rawvideo
+stddev:   10.28 PSNR: 27.89 MAXDIFF:   95 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-avui b/tests/ref/vsynth/vsynth2-avui
similarity index 74%
rename from tests/ref/fate/vsynth2-avui
rename to tests/ref/vsynth/vsynth2-avui
index 7489018..59bac8d 100644
--- a/tests/ref/fate/vsynth2-avui
+++ b/tests/ref/vsynth/vsynth2-avui
@@ -1,4 +1,4 @@
-4b05ddf2d099b9189978032a18b376ea *tests/data/fate/vsynth2-avui.mov
+d6ed112daf14e73ea50f1c32ecc6d4ce *tests/data/fate/vsynth2-avui.mov
 42624907 tests/data/fate/vsynth2-avui.mov
 dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth2-avui.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-cljr b/tests/ref/vsynth/vsynth2-cljr
new file mode 100644
index 0000000..c93da2e
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-cljr
@@ -0,0 +1,4 @@
+d9da8b1a1e78a8f0438d37c10f975ba3 *tests/data/fate/vsynth2-cljr.avi
+5075648 tests/data/fate/vsynth2-cljr.avi
+965c4a134144b30b24d6d138b03ddb8c *tests/data/fate/vsynth2-cljr.out.rawvideo
+stddev:    3.29 PSNR: 37.76 MAXDIFF:   23 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-dnxhd-1080i b/tests/ref/vsynth/vsynth2-dnxhd-1080i
similarity index 76%
rename from tests/ref/fate/vsynth2-dnxhd-1080i
rename to tests/ref/vsynth/vsynth2-dnxhd-1080i
index 61d3910..874e60b 100644
--- a/tests/ref/fate/vsynth2-dnxhd-1080i
+++ b/tests/ref/vsynth/vsynth2-dnxhd-1080i
@@ -1,4 +1,4 @@
-30ce40fa86812462456a6e68c79a0f6a *tests/data/fate/vsynth2-dnxhd-1080i.mov
+93b878dcf8f2ecc9798d0e0885c9eec9 *tests/data/fate/vsynth2-dnxhd-1080i.mov
 3031911 tests/data/fate/vsynth2-dnxhd-1080i.mov
 27edc8dfe2ca19097c7f9119705b3a60 *tests/data/fate/vsynth2-dnxhd-1080i.out.rawvideo
 stddev:    1.31 PSNR: 45.77 MAXDIFF:   23 bytes:  7603200/   760320
diff --git a/tests/ref/fate/vsynth2-dnxhd-720p b/tests/ref/vsynth/vsynth2-dnxhd-720p
similarity index 100%
rename from tests/ref/fate/vsynth2-dnxhd-720p
rename to tests/ref/vsynth/vsynth2-dnxhd-720p
diff --git a/tests/ref/fate/vsynth2-dnxhd-720p-10bit b/tests/ref/vsynth/vsynth2-dnxhd-720p-10bit
similarity index 100%
rename from tests/ref/fate/vsynth2-dnxhd-720p-10bit
rename to tests/ref/vsynth/vsynth2-dnxhd-720p-10bit
diff --git a/tests/ref/fate/vsynth2-dnxhd-720p-rd b/tests/ref/vsynth/vsynth2-dnxhd-720p-rd
similarity index 100%
rename from tests/ref/fate/vsynth2-dnxhd-720p-rd
rename to tests/ref/vsynth/vsynth2-dnxhd-720p-rd
diff --git a/tests/ref/fate/vsynth2-dnxhd_1080i b/tests/ref/vsynth/vsynth2-dnxhd_1080i
similarity index 100%
rename from tests/ref/fate/vsynth2-dnxhd_1080i
rename to tests/ref/vsynth/vsynth2-dnxhd_1080i
diff --git a/tests/ref/fate/vsynth2-dv b/tests/ref/vsynth/vsynth2-dv
similarity index 100%
rename from tests/ref/fate/vsynth2-dv
rename to tests/ref/vsynth/vsynth2-dv
diff --git a/tests/ref/fate/vsynth2-dv-411 b/tests/ref/vsynth/vsynth2-dv-411
similarity index 100%
rename from tests/ref/fate/vsynth2-dv-411
rename to tests/ref/vsynth/vsynth2-dv-411
diff --git a/tests/ref/fate/vsynth2-dv-50 b/tests/ref/vsynth/vsynth2-dv-50
similarity index 100%
rename from tests/ref/fate/vsynth2-dv-50
rename to tests/ref/vsynth/vsynth2-dv-50
diff --git a/tests/ref/fate/vsynth2-dv_411 b/tests/ref/vsynth/vsynth2-dv_411
similarity index 100%
rename from tests/ref/fate/vsynth2-dv_411
rename to tests/ref/vsynth/vsynth2-dv_411
diff --git a/tests/ref/vsynth/vsynth2-ffv1 b/tests/ref/vsynth/vsynth2-ffv1
new file mode 100644
index 0000000..888e843
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-ffv1
@@ -0,0 +1,4 @@
+3a757276e299bf88c30e06dfb53f1c99 *tests/data/fate/vsynth2-ffv1.avi
+3525792 tests/data/fate/vsynth2-ffv1.avi
+dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth2-ffv1.out.rawvideo
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-ffvhuff b/tests/ref/vsynth/vsynth2-ffvhuff
new file mode 100644
index 0000000..164e773
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-ffvhuff
@@ -0,0 +1,4 @@
+6689843a60dcc046fe1d7be3afab2cab *tests/data/fate/vsynth2-ffvhuff.avi
+4988044 tests/data/fate/vsynth2-ffvhuff.avi
+dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth2-ffvhuff.out.rawvideo
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-flashsv b/tests/ref/vsynth/vsynth2-flashsv
similarity index 100%
rename from tests/ref/fate/vsynth2-flashsv
rename to tests/ref/vsynth/vsynth2-flashsv
diff --git a/tests/ref/fate/vsynth2-flashsv2 b/tests/ref/vsynth/vsynth2-flashsv2
similarity index 100%
rename from tests/ref/fate/vsynth2-flashsv2
rename to tests/ref/vsynth/vsynth2-flashsv2
diff --git a/tests/ref/fate/vsynth2-flv b/tests/ref/vsynth/vsynth2-flv
similarity index 100%
rename from tests/ref/fate/vsynth2-flv
rename to tests/ref/vsynth/vsynth2-flv
diff --git a/tests/ref/vsynth/vsynth2-h261 b/tests/ref/vsynth/vsynth2-h261
new file mode 100644
index 0000000..f9091c7
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-h261
@@ -0,0 +1,4 @@
+dc32bc8a9e6eae15362ab86f8156f96a *tests/data/fate/vsynth2-h261.avi
+191060 tests/data/fate/vsynth2-h261.avi
+08f65e9aeeeaf189548c2bb417d5114f *tests/data/fate/vsynth2-h261.out.rawvideo
+stddev:    6.37 PSNR: 32.03 MAXDIFF:   77 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-h263 b/tests/ref/vsynth/vsynth2-h263
new file mode 100644
index 0000000..944d8ea
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-h263
@@ -0,0 +1,4 @@
+949d8c9926914751af5f433af0f8fd65 *tests/data/fate/vsynth2-h263.avi
+160102 tests/data/fate/vsynth2-h263.avi
+b7d733ebedbaa04f49bf7493a907e223 *tests/data/fate/vsynth2-h263.out.rawvideo
+stddev:    5.43 PSNR: 33.42 MAXDIFF:   77 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-h263-obmc b/tests/ref/vsynth/vsynth2-h263-obmc
new file mode 100644
index 0000000..a704318
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-h263-obmc
@@ -0,0 +1,4 @@
+7825a0bdf024673da2371829e3f01cc3 *tests/data/fate/vsynth2-h263-obmc.avi
+154726 tests/data/fate/vsynth2-h263-obmc.avi
+588d992d9d8096da8bdc5027268da914 *tests/data/fate/vsynth2-h263-obmc.out.rawvideo
+stddev:    5.39 PSNR: 33.49 MAXDIFF:   82 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-h263p b/tests/ref/vsynth/vsynth2-h263p
new file mode 100644
index 0000000..b4ebed9
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-h263p
@@ -0,0 +1,4 @@
+3894234818ed65426b5f20f058d27c73 *tests/data/fate/vsynth2-h263p.avi
+867998 tests/data/fate/vsynth2-h263p.avi
+dca18571c05c13dd691d7b0b232e43fc *tests/data/fate/vsynth2-h263p.out.rawvideo
+stddev:    1.91 PSNR: 42.50 MAXDIFF:   19 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-huffyuv b/tests/ref/vsynth/vsynth2-huffyuv
new file mode 100644
index 0000000..9b67815
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-huffyuv
@@ -0,0 +1,4 @@
+b5ae95ae03856ee14bbd38784a02f3ca *tests/data/fate/vsynth2-huffyuv.avi
+6455220 tests/data/fate/vsynth2-huffyuv.avi
+dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth2-huffyuv.out.rawvideo
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-j2k b/tests/ref/vsynth/vsynth2-j2k
new file mode 100644
index 0000000..4f038fe
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-j2k
@@ -0,0 +1,4 @@
+fc49816ba28731689872f5c87ca91c10 *tests/data/fate/vsynth2-j2k.avi
+1151144 tests/data/fate/vsynth2-j2k.avi
+ec5218eec33a021945c28c72093382a5 *tests/data/fate/vsynth2-j2k.out.rawvideo
+stddev:    4.54 PSNR: 34.99 MAXDIFF:   61 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-jpegls b/tests/ref/vsynth/vsynth2-jpegls
new file mode 100644
index 0000000..f8f7081
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-jpegls
@@ -0,0 +1,4 @@
+f34315ed0e30cf4d94dd21ff1d4cea1b *tests/data/fate/vsynth2-jpegls.avi
+8334618 tests/data/fate/vsynth2-jpegls.avi
+3a984506f1ebfc9fb73b6814cab201cc *tests/data/fate/vsynth2-jpegls.out.rawvideo
+stddev:    0.66 PSNR: 51.73 MAXDIFF:   14 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-ljpeg b/tests/ref/vsynth/vsynth2-ljpeg
new file mode 100644
index 0000000..fa2f978
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-ljpeg
@@ -0,0 +1,4 @@
+db9fd56e154b1056c9443a82a96db6f5 *tests/data/fate/vsynth2-ljpeg.avi
+4766902 tests/data/fate/vsynth2-ljpeg.avi
+dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth2-ljpeg.out.rawvideo
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mjpeg b/tests/ref/vsynth/vsynth2-mjpeg
new file mode 100644
index 0000000..f1780c5
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-mjpeg
@@ -0,0 +1,4 @@
+302197cccebb4d9797a08d06ca189533 *tests/data/fate/vsynth2-mjpeg.avi
+673174 tests/data/fate/vsynth2-mjpeg.avi
+9d4bd90e9abfa18192383b4adc23c8d4 *tests/data/fate/vsynth2-mjpeg.out.rawvideo
+stddev:    4.32 PSNR: 35.40 MAXDIFF:   49 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mjpeg-422 b/tests/ref/vsynth/vsynth2-mjpeg-422
new file mode 100644
index 0000000..fc0a4ba
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-mjpeg-422
@@ -0,0 +1,4 @@
+1ec800caa1dd2244677220d8a2b342ca *tests/data/fate/vsynth2-mjpeg-422.avi
+746530 tests/data/fate/vsynth2-mjpeg-422.avi
+451ac80989c4e14445cf951fd7f83b6d *tests/data/fate/vsynth2-mjpeg-422.out.rawvideo
+stddev:    4.18 PSNR: 35.70 MAXDIFF:   49 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mjpeg-444 b/tests/ref/vsynth/vsynth2-mjpeg-444
new file mode 100644
index 0000000..e04c31c
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-mjpeg-444
@@ -0,0 +1,4 @@
+0af500d33a7e4d04e9778fb9ed6180b3 *tests/data/fate/vsynth2-mjpeg-444.avi
+856628 tests/data/fate/vsynth2-mjpeg-444.avi
+34edcb9c87ff7aac456a4fb07f43504b *tests/data/fate/vsynth2-mjpeg-444.out.rawvideo
+stddev:    4.05 PSNR: 35.96 MAXDIFF:   49 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-mpeg1 b/tests/ref/vsynth/vsynth2-mpeg1
similarity index 100%
rename from tests/ref/fate/vsynth2-mpeg1
rename to tests/ref/vsynth/vsynth2-mpeg1
diff --git a/tests/ref/fate/vsynth2-mpeg1b b/tests/ref/vsynth/vsynth2-mpeg1b
similarity index 100%
rename from tests/ref/fate/vsynth2-mpeg1b
rename to tests/ref/vsynth/vsynth2-mpeg1b
diff --git a/tests/ref/fate/vsynth2-mpeg2 b/tests/ref/vsynth/vsynth2-mpeg2
similarity index 100%
rename from tests/ref/fate/vsynth2-mpeg2
rename to tests/ref/vsynth/vsynth2-mpeg2
diff --git a/tests/ref/fate/vsynth2-mpeg2-422 b/tests/ref/vsynth/vsynth2-mpeg2-422
similarity index 100%
rename from tests/ref/fate/vsynth2-mpeg2-422
rename to tests/ref/vsynth/vsynth2-mpeg2-422
diff --git a/tests/ref/fate/vsynth2-mpeg2-idct-int b/tests/ref/vsynth/vsynth2-mpeg2-idct-int
similarity index 100%
rename from tests/ref/fate/vsynth2-mpeg2-idct-int
rename to tests/ref/vsynth/vsynth2-mpeg2-idct-int
diff --git a/tests/ref/fate/vsynth2-mpeg2-ilace b/tests/ref/vsynth/vsynth2-mpeg2-ilace
similarity index 100%
rename from tests/ref/fate/vsynth2-mpeg2-ilace
rename to tests/ref/vsynth/vsynth2-mpeg2-ilace
diff --git a/tests/ref/fate/vsynth2-mpeg2-ivlc-qprd b/tests/ref/vsynth/vsynth2-mpeg2-ivlc-qprd
similarity index 100%
rename from tests/ref/fate/vsynth2-mpeg2-ivlc-qprd
rename to tests/ref/vsynth/vsynth2-mpeg2-ivlc-qprd
diff --git a/tests/ref/fate/vsynth2-mpeg2-thread b/tests/ref/vsynth/vsynth2-mpeg2-thread
similarity index 100%
rename from tests/ref/fate/vsynth2-mpeg2-thread
rename to tests/ref/vsynth/vsynth2-mpeg2-thread
diff --git a/tests/ref/fate/vsynth2-mpeg2-thread-ivlc b/tests/ref/vsynth/vsynth2-mpeg2-thread-ivlc
similarity index 100%
rename from tests/ref/fate/vsynth2-mpeg2-thread-ivlc
rename to tests/ref/vsynth/vsynth2-mpeg2-thread-ivlc
diff --git a/tests/ref/fate/vsynth2-mpeg4 b/tests/ref/vsynth/vsynth2-mpeg4
similarity index 74%
rename from tests/ref/fate/vsynth2-mpeg4
rename to tests/ref/vsynth/vsynth2-mpeg4
index ae56b6e..399ef58 100644
--- a/tests/ref/fate/vsynth2-mpeg4
+++ b/tests/ref/vsynth/vsynth2-mpeg4
@@ -1,4 +1,4 @@
-d87d88d02c63f07e574c39a72a95a3af *tests/data/fate/vsynth2-mpeg4.mp4
+04f74c54f4db25e1d454ede9216632c1 *tests/data/fate/vsynth2-mpeg4.mp4
 119661 tests/data/fate/vsynth2-mpeg4.mp4
 9a1e085d9e488c5ead0c940c9612a37a *tests/data/fate/vsynth2-mpeg4.out.rawvideo
 stddev:    5.34 PSNR: 33.57 MAXDIFF:   83 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mpeg4-adap b/tests/ref/vsynth/vsynth2-mpeg4-adap
new file mode 100644
index 0000000..175552d
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-mpeg4-adap
@@ -0,0 +1,4 @@
+4b39d46a436f1bce59e2902cec3478e9 *tests/data/fate/vsynth2-mpeg4-adap.avi
+198496 tests/data/fate/vsynth2-mpeg4-adap.avi
+87b6dbe98d276137fceaae2fa672eced *tests/data/fate/vsynth2-mpeg4-adap.out.rawvideo
+stddev:    3.75 PSNR: 36.65 MAXDIFF:   71 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mpeg4-adv b/tests/ref/vsynth/vsynth2-mpeg4-adv
new file mode 100644
index 0000000..b3bf264
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-mpeg4-adv
@@ -0,0 +1,4 @@
+1875ae5a45936c08778c4430a22e87eb *tests/data/fate/vsynth2-mpeg4-adv.avi
+141534 tests/data/fate/vsynth2-mpeg4-adv.avi
+3f3a21e9db85a9c0f7022f557a5374c1 *tests/data/fate/vsynth2-mpeg4-adv.out.rawvideo
+stddev:    4.94 PSNR: 34.25 MAXDIFF:   69 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mpeg4-error b/tests/ref/vsynth/vsynth2-mpeg4-error
new file mode 100644
index 0000000..c6a2218
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-mpeg4-error
@@ -0,0 +1,4 @@
+599a21c149a150072db364298dbcdda2 *tests/data/fate/vsynth2-mpeg4-error.avi
+180364 tests/data/fate/vsynth2-mpeg4-error.avi
+4537ba5320f1ae0971cc6e329c366776 *tests/data/fate/vsynth2-mpeg4-error.out.rawvideo
+stddev:    7.65 PSNR: 30.45 MAXDIFF:  158 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mpeg4-nr b/tests/ref/vsynth/vsynth2-mpeg4-nr
new file mode 100644
index 0000000..45db4b6
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-mpeg4-nr
@@ -0,0 +1,4 @@
+e1cf863ec6c0a4975d49326df63342ca *tests/data/fate/vsynth2-mpeg4-nr.avi
+154994 tests/data/fate/vsynth2-mpeg4-nr.avi
+d89cd5d0b1707f48fa9c4747c66d2d56 *tests/data/fate/vsynth2-mpeg4-nr.out.rawvideo
+stddev:    4.73 PSNR: 34.63 MAXDIFF:   64 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mpeg4-qpel b/tests/ref/vsynth/vsynth2-mpeg4-qpel
new file mode 100644
index 0000000..8705bd5
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-mpeg4-qpel
@@ -0,0 +1,4 @@
+b36ad1ca7ac6e1aff6d69b8df4386011 *tests/data/fate/vsynth2-mpeg4-qpel.avi
+163662 tests/data/fate/vsynth2-mpeg4-qpel.avi
+e2ce994dbb66da51c2e1ad26617d7c2f *tests/data/fate/vsynth2-mpeg4-qpel.out.rawvideo
+stddev:    3.97 PSNR: 36.14 MAXDIFF:   54 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mpeg4-qprd b/tests/ref/vsynth/vsynth2-mpeg4-qprd
new file mode 100644
index 0000000..1bbda29
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-mpeg4-qprd
@@ -0,0 +1,4 @@
+ee24ddde5e3c06a6c44093a59e7ac413 *tests/data/fate/vsynth2-mpeg4-qprd.avi
+231450 tests/data/fate/vsynth2-mpeg4-qprd.avi
+3071250e0864546c2455c9f9c9b8604e *tests/data/fate/vsynth2-mpeg4-qprd.out.rawvideo
+stddev:    3.71 PSNR: 36.72 MAXDIFF:   61 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mpeg4-rc b/tests/ref/vsynth/vsynth2-mpeg4-rc
new file mode 100644
index 0000000..2a26a16
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-mpeg4-rc
@@ -0,0 +1,4 @@
+20028333988bb7a0888a79799ea63b19 *tests/data/fate/vsynth2-mpeg4-rc.avi
+226310 tests/data/fate/vsynth2-mpeg4-rc.avi
+6e8b62e8c3bcbfdcc58afb69a0b1c4e3 *tests/data/fate/vsynth2-mpeg4-rc.out.rawvideo
+stddev:    4.23 PSNR: 35.60 MAXDIFF:   85 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mpeg4-thread b/tests/ref/vsynth/vsynth2-mpeg4-thread
new file mode 100644
index 0000000..d8d87c4
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-mpeg4-thread
@@ -0,0 +1,4 @@
+d50954ec2c64c2634d88ba1df879dde0 *tests/data/fate/vsynth2-mpeg4-thread.avi
+250092 tests/data/fate/vsynth2-mpeg4-thread.avi
+045fe9f226bbcc3d41644bffaed03b31 *tests/data/fate/vsynth2-mpeg4-thread.out.rawvideo
+stddev:    3.69 PSNR: 36.78 MAXDIFF:   65 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mpng b/tests/ref/vsynth/vsynth2-mpng
new file mode 100644
index 0000000..2e6865c
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-mpng
@@ -0,0 +1,4 @@
+b8f9aa584da89837058c96fc5c3a6562 *tests/data/fate/vsynth2-mpng.avi
+12558330 tests/data/fate/vsynth2-mpng.avi
+98d0e2854731472c5bf13d8638502d0a *tests/data/fate/vsynth2-mpng.out.rawvideo
+stddev:    1.26 PSNR: 46.10 MAXDIFF:   13 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-msmpeg4 b/tests/ref/vsynth/vsynth2-msmpeg4
new file mode 100644
index 0000000..274cecc
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-msmpeg4
@@ -0,0 +1,4 @@
+6eb2a9770c223636befacfba83f72c44 *tests/data/fate/vsynth2-msmpeg4.avi
+127660 tests/data/fate/vsynth2-msmpeg4.avi
+bb14902d5850d6b0ab70fdb017855775 *tests/data/fate/vsynth2-msmpeg4.out.rawvideo
+stddev:    5.33 PSNR: 33.58 MAXDIFF:   78 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-msmpeg4v2 b/tests/ref/vsynth/vsynth2-msmpeg4v2
new file mode 100644
index 0000000..a851a2f
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-msmpeg4v2
@@ -0,0 +1,4 @@
+e0929f2cebefc9f6259870b806829de3 *tests/data/fate/vsynth2-msmpeg4v2.avi
+129918 tests/data/fate/vsynth2-msmpeg4v2.avi
+537c114e1d47c54a4bccd31f4073e9bd *tests/data/fate/vsynth2-msmpeg4v2.out.rawvideo
+stddev:    5.33 PSNR: 33.59 MAXDIFF:   79 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-msvideo1 b/tests/ref/vsynth/vsynth2-msvideo1
new file mode 100644
index 0000000..a915c13
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-msvideo1
@@ -0,0 +1,4 @@
+6c1709d61202ec2e73b467e76cb79f9b *tests/data/fate/vsynth2-msvideo1.avi
+914560 tests/data/fate/vsynth2-msvideo1.avi
+9a6ac7c0171286f009d159b59fdc1154 *tests/data/fate/vsynth2-msvideo1.out.rawvideo
+stddev:    7.97 PSNR: 30.10 MAXDIFF:  123 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-prores b/tests/ref/vsynth/vsynth2-prores
new file mode 100644
index 0000000..b5c80e2
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-prores
@@ -0,0 +1,4 @@
+a6351254cccdbc7147600951a798172a *tests/data/fate/vsynth2-prores.mov
+2844076 tests/data/fate/vsynth2-prores.mov
+b5844025c0f4c7c37db702c3213db232 *tests/data/fate/vsynth2-prores.out.rawvideo
+stddev:    1.31 PSNR: 45.77 MAXDIFF:   11 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-prores_kostya b/tests/ref/vsynth/vsynth2-prores_kostya
new file mode 100644
index 0000000..16b6078
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-prores_kostya
@@ -0,0 +1,4 @@
+7de64c634620de738c98aa22e9df927d *tests/data/fate/vsynth2-prores_kostya.mov
+3884596 tests/data/fate/vsynth2-prores_kostya.mov
+ca2f6c1162635dedfa468c90f1fdc0ef *tests/data/fate/vsynth2-prores_kostya.out.rawvideo
+stddev:    0.92 PSNR: 48.77 MAXDIFF:   10 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-qtrle b/tests/ref/vsynth/vsynth2-qtrle
new file mode 100644
index 0000000..5f53608
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-qtrle
@@ -0,0 +1,4 @@
+f2aea57de225cccadb936bba4086a836 *tests/data/fate/vsynth2-qtrle.mov
+14798345 tests/data/fate/vsynth2-qtrle.mov
+98d0e2854731472c5bf13d8638502d0a *tests/data/fate/vsynth2-qtrle.out.rawvideo
+stddev:    1.26 PSNR: 46.10 MAXDIFF:   13 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-qtrlegray b/tests/ref/vsynth/vsynth2-qtrlegray
new file mode 100644
index 0000000..4568391
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-qtrlegray
@@ -0,0 +1,4 @@
+fa10a87e9cf648d635340b90e41d2d38 *tests/data/fate/vsynth2-qtrlegray.mov
+5111283 tests/data/fate/vsynth2-qtrlegray.mov
+f63b5ebdfdba750e547c25131b0a3fd1 *tests/data/fate/vsynth2-qtrlegray.out.rawvideo
+stddev:   19.42 PSNR: 22.36 MAXDIFF:   72 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-r210 b/tests/ref/vsynth/vsynth2-r210
new file mode 100644
index 0000000..a91c12a
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-r210
@@ -0,0 +1,4 @@
+4568992c4f5562be06374519a419d3a3 *tests/data/fate/vsynth2-r210.avi
+22125248 tests/data/fate/vsynth2-r210.avi
+6ea4fcd93fc83defc8770e85b64b60bb *tests/data/fate/vsynth2-r210.out.rawvideo
+stddev:    0.70 PSNR: 51.12 MAXDIFF:   12 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-rgb b/tests/ref/vsynth/vsynth2-rgb
new file mode 100644
index 0000000..6f5169d
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-rgb
@@ -0,0 +1,4 @@
+01199075994e44f282fbb6a8e3ccc668 *tests/data/fate/vsynth2-rgb.avi
+15213248 tests/data/fate/vsynth2-rgb.avi
+98d0e2854731472c5bf13d8638502d0a *tests/data/fate/vsynth2-rgb.out.rawvideo
+stddev:    1.26 PSNR: 46.10 MAXDIFF:   13 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-roqvideo b/tests/ref/vsynth/vsynth2-roqvideo
similarity index 100%
rename from tests/ref/fate/vsynth2-roqvideo
rename to tests/ref/vsynth/vsynth2-roqvideo
diff --git a/tests/ref/fate/vsynth2-rv10 b/tests/ref/vsynth/vsynth2-rv10
similarity index 100%
rename from tests/ref/fate/vsynth2-rv10
rename to tests/ref/vsynth/vsynth2-rv10
diff --git a/tests/ref/fate/vsynth2-rv20 b/tests/ref/vsynth/vsynth2-rv20
similarity index 100%
rename from tests/ref/fate/vsynth2-rv20
rename to tests/ref/vsynth/vsynth2-rv20
diff --git a/tests/ref/vsynth/vsynth2-snow b/tests/ref/vsynth/vsynth2-snow
new file mode 100644
index 0000000..12f3811
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-snow
@@ -0,0 +1,4 @@
+4b6236e23ae4a52655f2c24c5a09380a *tests/data/fate/vsynth2-snow.avi
+57688 tests/data/fate/vsynth2-snow.avi
+8890189af71a0dd3447c4e8424c9a76b *tests/data/fate/vsynth2-snow.out.rawvideo
+stddev:   10.47 PSNR: 27.72 MAXDIFF:  119 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-snow-hpel b/tests/ref/vsynth/vsynth2-snow-hpel
new file mode 100644
index 0000000..955f1bf
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-snow-hpel
@@ -0,0 +1,4 @@
+9872032345c33cf8e8fc26ab655be3d3 *tests/data/fate/vsynth2-snow-hpel.avi
+61760 tests/data/fate/vsynth2-snow-hpel.avi
+8680d40905f423999d65b996c4dcb984 *tests/data/fate/vsynth2-snow-hpel.out.rawvideo
+stddev:   10.45 PSNR: 27.74 MAXDIFF:  123 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-snow-ll b/tests/ref/vsynth/vsynth2-snow-ll
new file mode 100644
index 0000000..9a72549
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-snow-ll
@@ -0,0 +1,4 @@
+30b40e0bf64f92b23d6f94056c0c6da5 *tests/data/fate/vsynth2-snow-ll.avi
+2721746 tests/data/fate/vsynth2-snow-ll.avi
+dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth2-snow-ll.out.rawvideo
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-svq1 b/tests/ref/vsynth/vsynth2-svq1
new file mode 100644
index 0000000..bdde55e
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-svq1
@@ -0,0 +1,4 @@
+11da7948184b3fee455f66cc5f6f8ca5 *tests/data/fate/vsynth2-svq1.mov
+766701 tests/data/fate/vsynth2-svq1.mov
+aa03471dac3f49455a33a2b19fda1098 *tests/data/fate/vsynth2-svq1.out.rawvideo
+stddev:    3.23 PSNR: 37.93 MAXDIFF:   61 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-v210 b/tests/ref/vsynth/vsynth2-v210
new file mode 100644
index 0000000..eb80b34
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-v210
@@ -0,0 +1,4 @@
+ddc80f41b9e92c26adbe09567a4c7a1d *tests/data/fate/vsynth2-v210.avi
+14752448 tests/data/fate/vsynth2-v210.avi
+a627fb50c8276200fd71383977d87ca3 *tests/data/fate/vsynth2-v210.out.rawvideo
+stddev:    0.34 PSNR: 57.43 MAXDIFF:    6 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-v308 b/tests/ref/vsynth/vsynth2-v308
new file mode 100644
index 0000000..f7c46fc
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-v308
@@ -0,0 +1,4 @@
+aba17ed2860ac714da0e378ebe47e7bb *tests/data/fate/vsynth2-v308.avi
+15213248 tests/data/fate/vsynth2-v308.avi
+d43cb310c130c69214332d74f6ee5f9a *tests/data/fate/vsynth2-v308.out.rawvideo
+stddev:    0.41 PSNR: 55.80 MAXDIFF:    7 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-v408 b/tests/ref/vsynth/vsynth2-v408
new file mode 100644
index 0000000..4c63dec
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-v408
@@ -0,0 +1,4 @@
+d689d4a53081765f0fbc965554c06faa *tests/data/fate/vsynth2-v408.avi
+20282048 tests/data/fate/vsynth2-v408.avi
+dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth2-v408.out.rawvideo
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-wmv1 b/tests/ref/vsynth/vsynth2-wmv1
new file mode 100644
index 0000000..6e56b6f
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-wmv1
@@ -0,0 +1,4 @@
+dc2affb9b9a95a09dd69c25c75c50174 *tests/data/fate/vsynth2-wmv1.avi
+129510 tests/data/fate/vsynth2-wmv1.avi
+dec44e3c04db4fef49a7728f164d9159 *tests/data/fate/vsynth2-wmv1.out.rawvideo
+stddev:    5.33 PSNR: 33.60 MAXDIFF:   77 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-wmv2 b/tests/ref/vsynth/vsynth2-wmv2
new file mode 100644
index 0000000..41beb4e
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-wmv2
@@ -0,0 +1,4 @@
+f2a29f4e98a526e104067ca381716e47 *tests/data/fate/vsynth2-wmv2.avi
+129834 tests/data/fate/vsynth2-wmv2.avi
+dec44e3c04db4fef49a7728f164d9159 *tests/data/fate/vsynth2-wmv2.out.rawvideo
+stddev:    5.33 PSNR: 33.60 MAXDIFF:   77 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-y41p b/tests/ref/vsynth/vsynth2-y41p
new file mode 100644
index 0000000..ac9d64a
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-y41p
@@ -0,0 +1,4 @@
+0689a7a5c4dd6ac6ac515b54d45d249e *tests/data/fate/vsynth2-y41p.avi
+7610048 tests/data/fate/vsynth2-y41p.avi
+d27a84ccdac09055724d122e03fea82a *tests/data/fate/vsynth2-y41p.out.rawvideo
+stddev:    1.07 PSNR: 47.54 MAXDIFF:   21 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-yuv b/tests/ref/vsynth/vsynth2-yuv
new file mode 100644
index 0000000..d6b8736
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-yuv
@@ -0,0 +1,4 @@
+0029ade090172b34687cdc9163748e47 *tests/data/fate/vsynth2-yuv.avi
+7610048 tests/data/fate/vsynth2-yuv.avi
+dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth2-yuv.out.rawvideo
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-yuv4 b/tests/ref/vsynth/vsynth2-yuv4
new file mode 100644
index 0000000..8fa347a
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-yuv4
@@ -0,0 +1,4 @@
+00454056d8560cde37409e0b578209d8 *tests/data/fate/vsynth2-yuv4.avi
+7610048 tests/data/fate/vsynth2-yuv4.avi
+dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth2-yuv4.out.rawvideo
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-zlib b/tests/ref/vsynth/vsynth2-zlib
new file mode 100644
index 0000000..0a7ed3c
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-zlib
@@ -0,0 +1,4 @@
+d0e240b5241c3e0a5f813644d3dc5d9f *tests/data/fate/vsynth2-zlib.avi
+12517176 tests/data/fate/vsynth2-zlib.avi
+98d0e2854731472c5bf13d8638502d0a *tests/data/fate/vsynth2-zlib.out.rawvideo
+stddev:    1.26 PSNR: 46.10 MAXDIFF:   13 bytes:  7603200/  7603200
diff --git a/tests/ref/fate/vsynth2-zmbv b/tests/ref/vsynth/vsynth2-zmbv
similarity index 100%
rename from tests/ref/fate/vsynth2-zmbv
rename to tests/ref/vsynth/vsynth2-zmbv
diff --git a/tests/test.ffmeta b/tests/test.ffmeta
index 8c19e5e..ad37b02 100644
--- a/tests/test.ffmeta
+++ b/tests/test.ffmeta
@@ -2,3 +2,8 @@
 title=ffprobe test file
 comment='A comment with CSV, XML & JSON special chars': <tag value=\"x\">
 comment2=I ♥ Üñîçød€
+[STREAM]
+E=mc²
+[STREAM]
+title=foobar
+duration_ts=field-and-tags-conflict-attempt
diff --git a/tests/tiny_psnr.c b/tests/tiny_psnr.c
index b912061..264aa4d 100644
--- a/tests/tiny_psnr.c
+++ b/tests/tiny_psnr.c
@@ -231,7 +231,7 @@
         } else {
             char *end;
             len = strtol(argv[3], &end, 0);
-            if (*end || len > 2) {
+            if (*end || len < 1 || len > 2) {
                 fprintf(stderr, "Unsupported sample format: %s\n", argv[3]);
                 return 1;
             }
diff --git a/tools/cws2fws.c b/tools/cws2fws.c
index 74588c1..84feda9 100644
--- a/tools/cws2fws.c
+++ b/tools/cws2fws.c
@@ -62,7 +62,10 @@
         return 1;
     }
 
-    fstat(fd_in, &statbuf);
+    if (fstat(fd_in, &statbuf) < 0) {
+        perror("fstat failed");
+        return 1;
+    }
     comp_len   = statbuf.st_size;
     uncomp_len = buf_in[4] | (buf_in[5] << 8) | (buf_in[6] << 16) | (buf_in[7] << 24);
 
@@ -79,7 +82,10 @@
     zstream.zalloc = NULL;
     zstream.zfree  = NULL;
     zstream.opaque = NULL;
-    inflateInit(&zstream);
+    if (inflateInit(&zstream) != Z_OK) {
+        fprintf(stderr, "inflateInit failed\n");
+        return 1;
+    }
 
     for (i = 0; i < comp_len - 8;) {
         int ret, len = read(fd_in, &buf_in, 1024);
@@ -125,8 +131,8 @@
         buf_in[2] = ((zstream.total_out + 8) >> 16) & 0xff;
         buf_in[3] = ((zstream.total_out + 8) >> 24) & 0xff;
 
-        lseek(fd_out, 4, SEEK_SET);
-        if (write(fd_out, &buf_in, 4) < 4) {
+        if (   lseek(fd_out, 4, SEEK_SET) < 0
+            || write(fd_out, &buf_in, 4) < 4) {
             perror("Error writing output file");
             return 1;
         }
diff --git a/tools/ffescape.c b/tools/ffescape.c
new file mode 100644
index 0000000..d777fe4
--- /dev/null
+++ b/tools/ffescape.c
@@ -0,0 +1,233 @@
+/*
+ * Copyright (c) 2012 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
+ */
+
+#include "config.h"
+#if HAVE_UNISTD_H
+#include <unistd.h>             /* getopt */
+#endif
+
+#include "libavutil/log.h"
+#include "libavutil/bprint.h"
+
+#if !HAVE_GETOPT
+#include "compat/getopt.c"
+#endif
+
+/**
+ * @file
+ * escaping utility
+ */
+
+static void usage(void)
+{
+    printf("Escape an input string, adopting the av_get_token() escaping logic\n");
+    printf("usage: ffescape [OPTIONS]\n");
+    printf("\n"
+           "Options:\n"
+           "-e                echo each input line on output\n"
+           "-h                print this help\n"
+           "-i INFILE         set INFILE as input file, stdin if omitted\n"
+           "-l LEVEL          set the number of escaping levels, 1 if omitted\n"
+           "-m ESCAPE_MODE    select escape mode between 'full', 'lazy', 'quote', default is 'lazy'\n"
+           "-o OUTFILE        set OUTFILE as output file, stdout if omitted\n"
+           "-p PROMPT         set output prompt, is '=> ' by default\n"
+           "-s SPECIAL_CHARS  set the list of special characters\n");
+}
+
+#define WHITESPACES " \n\t"
+
+enum EscapeMode {
+    ESCAPE_MODE_FULL,
+    ESCAPE_MODE_LAZY,
+    ESCAPE_MODE_QUOTE,
+};
+
+static int escape(char **dst, const char *src, const char *special_chars,
+                  enum EscapeMode mode)
+{
+    AVBPrint dstbuf;
+
+    av_bprint_init(&dstbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
+
+    switch (mode) {
+    case ESCAPE_MODE_FULL:
+    case ESCAPE_MODE_LAZY:
+        /* \-escape characters */
+
+        if (mode == ESCAPE_MODE_LAZY && strchr(WHITESPACES, *src))
+            av_bprintf(&dstbuf, "\\%c", *src++);
+
+        for (; *src; src++) {
+            if ((special_chars && strchr(special_chars, *src)) ||
+                strchr("'\\", *src) ||
+                (mode == ESCAPE_MODE_FULL && strchr(WHITESPACES, *src)))
+                av_bprintf(&dstbuf, "\\%c", *src);
+            else
+                av_bprint_chars(&dstbuf, *src, 1);
+        }
+
+        if (mode == ESCAPE_MODE_LAZY && strchr(WHITESPACES, dstbuf.str[dstbuf.len-1])) {
+            char c = dstbuf.str[dstbuf.len-1];
+            dstbuf.str[dstbuf.len-1] = '\\';
+            av_bprint_chars(&dstbuf, c, 1);
+        }
+        break;
+
+    case ESCAPE_MODE_QUOTE:
+        /* enclose between '' the string */
+        av_bprint_chars(&dstbuf, '\'', 1);
+        for (; *src; src++) {
+            if (*src == '\'')
+                av_bprintf(&dstbuf, "'\\''");
+            else
+                av_bprint_chars(&dstbuf, *src, 1);
+        }
+        av_bprint_chars(&dstbuf, '\'', 1);
+        break;
+
+    default:
+        /* unknown escape mode */
+        return AVERROR(EINVAL);
+    }
+
+    if (!av_bprint_is_complete(&dstbuf)) {
+        av_bprint_finalize(&dstbuf, NULL);
+        return AVERROR(ENOMEM);
+    } else {
+        av_bprint_finalize(&dstbuf, dst);
+        return 0;
+    }
+}
+
+int main(int argc, char **argv)
+{
+    AVBPrint src;
+    char *src_buf, *dst_buf;
+    const char *outfilename = NULL, *infilename = NULL;
+    FILE *outfile = NULL, *infile = NULL;
+    const char *prompt = "=> ";
+    enum EscapeMode escape_mode = ESCAPE_MODE_LAZY;
+    int level = 1;
+    int echo = 0;
+    char *special_chars = NULL;
+    int c;
+
+    while ((c = getopt(argc, argv, "ehi:l:o:m:p:s:")) != -1) {
+        switch (c) {
+        case 'e':
+            echo = 1;
+            break;
+        case 'h':
+            usage();
+            return 0;
+        case 'i':
+            infilename = optarg;
+            break;
+        case 'l':
+        {
+            char *tail;
+            long int li = strtol(optarg, &tail, 10);
+            if (*tail || li > INT_MAX || li < 0) {
+                av_log(NULL, AV_LOG_ERROR,
+                        "Invalid value '%s' for option -l, argument must be a non negative integer\n",
+                        optarg);
+                return 1;
+            }
+            level = li;
+            break;
+        }
+        case 'm':
+            if      (!strcmp(optarg, "full"))  escape_mode = ESCAPE_MODE_FULL;
+            else if (!strcmp(optarg, "lazy"))  escape_mode = ESCAPE_MODE_LAZY;
+            else if (!strcmp(optarg, "quote")) escape_mode = ESCAPE_MODE_QUOTE;
+            else {
+                av_log(NULL, AV_LOG_ERROR,
+                       "Invalid value '%s' for option -m, "
+                       "valid arguments are 'full', 'lazy', 'quote'\n", optarg);
+                return 1;
+            }
+            break;
+        case 'o':
+            outfilename = optarg;
+            break;
+        case 'p':
+            prompt = optarg;
+            break;
+        case 's':
+            special_chars = optarg;
+            break;
+        case '?':
+            return 1;
+        }
+    }
+
+    if (!infilename || !strcmp(infilename, "-")) {
+        infilename = "stdin";
+        infile = stdin;
+    } else {
+        infile = fopen(infilename, "r");
+    }
+    if (!infile) {
+        av_log(NULL, AV_LOG_ERROR, "Impossible to open input file '%s': %s\n", infilename, strerror(errno));
+        return 1;
+    }
+
+    if (!outfilename || !strcmp(outfilename, "-")) {
+        outfilename = "stdout";
+        outfile = stdout;
+    } else {
+        outfile = fopen(outfilename, "w");
+    }
+    if (!outfile) {
+        av_log(NULL, AV_LOG_ERROR, "Impossible to open output file '%s': %s\n", outfilename, strerror(errno));
+        return 1;
+    }
+
+    /* grab the input and store it in src */
+    av_bprint_init(&src, 1, AV_BPRINT_SIZE_UNLIMITED);
+    while ((c = fgetc(infile)) != EOF)
+        av_bprint_chars(&src, c, 1);
+    av_bprint_chars(&src, 0, 1);
+
+    if (!av_bprint_is_complete(&src)) {
+        av_log(NULL, AV_LOG_ERROR, "Could not allocate a buffer for the source string\n");
+        av_bprint_finalize(&src, NULL);
+        return 1;
+    }
+    av_bprint_finalize(&src, &src_buf);
+
+    if (echo)
+        fprintf(outfile, "%s", src_buf);
+
+    /* escape */
+    dst_buf = src_buf;
+    while (level--) {
+        if (escape(&dst_buf, src_buf, special_chars, escape_mode) < 0) {
+            av_log(NULL, AV_LOG_ERROR, "Could not escape string\n");
+            return 1;
+        }
+        av_free(src_buf);
+        src_buf = dst_buf;
+    }
+
+    fprintf(outfile, "%s%s", prompt, dst_buf);
+    av_free(dst_buf);
+    return 0;
+}
diff --git a/tools/ffeval.c b/tools/ffeval.c
index 027cd48..0fab877 100644
--- a/tools/ffeval.c
+++ b/tools/ffeval.c
@@ -18,9 +18,17 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "config.h"
+#if HAVE_UNISTD_H
 #include <unistd.h>             /* getopt */
+#endif
+
 #include "libavutil/eval.h"
 
+#if !HAVE_GETOPT
+#include "compat/getopt.c"
+#endif
+
 /**
  * @file
  * simple arithmetic expression evaluator
@@ -49,7 +57,7 @@
     FILE *outfile = NULL, *infile = NULL;
     const char *prompt = "=> ";
     int count = 0, echo = 0;
-    char c;
+    int c;
 
     av_max_alloc(MAX_BLOCK_SIZE);
 
@@ -75,17 +83,23 @@
         }
     }
 
-    if (!infilename || !strcmp(infilename, "-"))
-        infilename = "/dev/stdin";
-    infile = fopen(infilename, "r");
+    if (!infilename || !strcmp(infilename, "-")) {
+        infilename = "stdin";
+        infile = stdin;
+    } else {
+        infile = fopen(infilename, "r");
+    }
     if (!infile) {
         fprintf(stderr, "Impossible to open input file '%s': %s\n", infilename, strerror(errno));
         return 1;
     }
 
-    if (!outfilename || !strcmp(outfilename, "-"))
-        outfilename = "/dev/stdout";
-    outfile = fopen(outfilename, "w");
+    if (!outfilename || !strcmp(outfilename, "-")) {
+        outfilename = "stdout";
+        outfile = stdout;
+    } else {
+        outfile = fopen(outfilename, "w");
+    }
     if (!outfile) {
         fprintf(stderr, "Impossible to open output file '%s': %s\n", outfilename, strerror(errno));
         return 1;
diff --git a/tools/fourcc2pixfmt.c b/tools/fourcc2pixfmt.c
index 84d5af3..77cb0b6 100644
--- a/tools/fourcc2pixfmt.c
+++ b/tools/fourcc2pixfmt.c
@@ -28,6 +28,9 @@
 #include "libavutil/common.h"
 #include "libavcodec/raw.h"
 
+#undef printf
+#undef fprintf
+
 #if !HAVE_GETOPT
 #include "compat/getopt.c"
 #endif
@@ -44,11 +47,11 @@
            "-h                print this help\n");
 }
 
-static void print_pix_fmt_fourccs(enum PixelFormat pix_fmt, char sep)
+static void print_pix_fmt_fourccs(enum AVPixelFormat pix_fmt, char sep)
 {
     int i;
 
-    for (i = 0; ff_raw_pix_fmt_tags[i].pix_fmt != PIX_FMT_NONE; i++) {
+    for (i = 0; ff_raw_pix_fmt_tags[i].pix_fmt != AV_PIX_FMT_NONE; i++) {
         if (ff_raw_pix_fmt_tags[i].pix_fmt == pix_fmt) {
             char buf[32];
             av_get_codec_tag_string(buf, sizeof(buf), ff_raw_pix_fmt_tags[i].fourcc);
@@ -89,7 +92,7 @@
     }
 
     if (list_fourcc_pix_fmt) {
-        for (i = 0; ff_raw_pix_fmt_tags[i].pix_fmt != PIX_FMT_NONE; i++) {
+        for (i = 0; ff_raw_pix_fmt_tags[i].pix_fmt != AV_PIX_FMT_NONE; i++) {
             char buf[32];
             av_get_codec_tag_string(buf, sizeof(buf), ff_raw_pix_fmt_tags[i].fourcc);
             printf("%s: %s\n", buf, av_get_pix_fmt_name(ff_raw_pix_fmt_tags[i].pix_fmt));
@@ -97,8 +100,8 @@
     }
 
     if (list_pix_fmt_fourccs) {
-        for (i = 0; i < PIX_FMT_NB; i++) {
-            const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[i];
+        for (i = 0; i < AV_PIX_FMT_NB; i++) {
+            const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(i);
             if (!pix_desc->name || pix_desc->flags & PIX_FMT_HWACCEL)
                 continue;
             printf("%s: ", pix_desc->name);
@@ -108,8 +111,8 @@
     }
 
     if (pix_fmt_name) {
-        enum PixelFormat pix_fmt = av_get_pix_fmt(pix_fmt_name);
-        if (pix_fmt == PIX_FMT_NONE) {
+        enum AVPixelFormat pix_fmt = av_get_pix_fmt(pix_fmt_name);
+        if (pix_fmt == AV_PIX_FMT_NONE) {
             fprintf(stderr, "Invalid pixel format selected '%s'\n", pix_fmt_name);
             return 1;
         }
diff --git a/tools/graph2dot.c b/tools/graph2dot.c
index c4a50a8..74075c7 100644
--- a/tools/graph2dot.c
+++ b/tools/graph2dot.c
@@ -25,9 +25,9 @@
 #include <stdio.h>
 #include <string.h>
 
+#include "libavutil/channel_layout.h"
 #include "libavutil/mem.h"
 #include "libavutil/pixdesc.h"
-#include "libavutil/audioconvert.h"
 #include "libavfilter/avfiltergraph.h"
 
 #if !HAVE_GETOPT
@@ -82,9 +82,10 @@
                         link->srcpad->name, link->dstpad->name);
 
                 if (link->type == AVMEDIA_TYPE_VIDEO) {
+                    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
                     fprintf(outfile,
                             "fmt:%s w:%d h:%d tb:%d/%d",
-                            av_pix_fmt_descriptors[link->format].name,
+                            desc->name,
                             link->w, link->h,
                             link->time_base.num, link->time_base.den);
                 } else if (link->type == AVMEDIA_TYPE_AUDIO) {
diff --git a/tools/ismindex.c b/tools/ismindex.c
index b801d43..9efdebe 100644
--- a/tools/ismindex.c
+++ b/tools/ismindex.c
@@ -251,7 +251,10 @@
     if (codec->codec_id == AV_CODEC_ID_VC1)
         return get_private_data(vf, codec);
 
-    avio_open_dyn_buf(&io);
+    if (avio_open_dyn_buf(&io) < 0)  {
+        err = AVERROR(ENOMEM);
+        goto fail;
+    }
     if (codec->extradata_size < 11 || codec->extradata[0] != 1)
         goto fail;
     sps_size = AV_RB16(&codec->extradata[6]);
diff --git a/tools/probetest.c b/tools/probetest.c
index f8a617d..b13c6f9 100644
--- a/tools/probetest.c
+++ b/tools/probetest.c
@@ -63,6 +63,16 @@
     if(argc >= 3)
         max_size = atoi(argv[2]);
 
+    if (max_size > 1000000000U/8) {
+        fprintf(stderr, "max_size out of bounds\n");
+        return 1;
+    }
+
+    if (retry_count > 1000000000U) {
+        fprintf(stderr, "retry_count out of bounds\n");
+        return 1;
+    }
+
     avcodec_register_all();
     av_register_all();
 
@@ -74,6 +84,8 @@
         pd.buf      = av_realloc(pd.buf, size + AVPROBE_PADDING_SIZE);
         pd.filename = "";
 
+        memset(pd.buf, 0, size + AVPROBE_PADDING_SIZE);
+
         fprintf(stderr, "testing size=%d\n", size);
 
         for (retry = 0; retry < retry_count; retry += FFMAX(size, 32)) {
diff --git a/tools/qt-faststart.c b/tools/qt-faststart.c
index b9dbdfd..ecf163a 100644
--- a/tools/qt-faststart.c
+++ b/tools/qt-faststart.c
@@ -97,7 +97,7 @@
     uint64_t i, j;
     uint32_t offset_count;
     uint64_t current_offset;
-    uint64_t start_offset = 0;
+    int64_t start_offset = 0;
     unsigned char *copy_buffer = NULL;
     int bytes_to_copy;
 
@@ -136,22 +136,27 @@
                        atom_size);
                 goto error_out;
             }
-            fseeko(infile, -ATOM_PREAMBLE_SIZE, SEEK_CUR);
-            if (fread(ftyp_atom, atom_size, 1, infile) != 1) {
+            if (   fseeko(infile, -ATOM_PREAMBLE_SIZE, SEEK_CUR)
+                || fread(ftyp_atom, atom_size, 1, infile) != 1
+                || (start_offset = ftello(infile))<0) {
                 perror(argv[1]);
                 goto error_out;
             }
-            start_offset = ftello(infile);
         } else {
+            int ret;
             /* 64-bit special case */
             if (atom_size == 1) {
                 if (fread(atom_bytes, ATOM_PREAMBLE_SIZE, 1, infile) != 1) {
                     break;
                 }
                 atom_size = BE_64(&atom_bytes[0]);
-                fseeko(infile, atom_size - ATOM_PREAMBLE_SIZE * 2, SEEK_CUR);
+                ret = fseeko(infile, atom_size - ATOM_PREAMBLE_SIZE * 2, SEEK_CUR);
             } else {
-                fseeko(infile, atom_size - ATOM_PREAMBLE_SIZE, SEEK_CUR);
+                ret = fseeko(infile, atom_size - ATOM_PREAMBLE_SIZE, SEEK_CUR);
+            }
+            if(ret) {
+                perror(argv[1]);
+                goto error_out;
             }
         }
         printf("%c%c%c%c %10"PRIu64" %"PRIu64"\n",
@@ -192,7 +197,10 @@
 
     /* moov atom was, in fact, the last atom in the chunk; load the whole
      * moov atom */
-    fseeko(infile, -atom_size, SEEK_END);
+    if (fseeko(infile, -atom_size, SEEK_END)) {
+        perror(argv[1]);
+        goto error_out;
+    }
     last_offset    = ftello(infile);
     moov_atom_size = atom_size;
     moov_atom      = malloc(moov_atom_size);
@@ -268,7 +276,11 @@
     }
 
     if (start_offset > 0) { /* seek after ftyp atom */
-        fseeko(infile, start_offset, SEEK_SET);
+        if (fseeko(infile, start_offset, SEEK_SET)) {
+            perror(argv[1]);
+            goto error_out;
+        }
+
         last_offset -= start_offset;
     }
 
@@ -298,7 +310,7 @@
     bytes_to_copy = FFMIN(COPY_BUFFER_SIZE, last_offset);
     copy_buffer = malloc(bytes_to_copy);
     if (!copy_buffer) {
-        printf("could not allocate %"PRIu64" bytes for copy_buffer\n", bytes_to_copy);
+        printf("could not allocate %d bytes for copy_buffer\n", bytes_to_copy);
         goto error_out;
     }
     printf(" copying rest of file...\n");
diff --git a/tools/trasher.c b/tools/trasher.c
index 93bfc0c..aaa09f4 100644
--- a/tools/trasher.c
+++ b/tools/trasher.c
@@ -56,7 +56,10 @@
     while (count--) {
         int burst = 1 + ran() * (uint64_t) (abs(maxburst) - 1) / UINT32_MAX;
         int pos   = ran() * (uint64_t) length / UINT32_MAX;
-        fseek(f, pos, SEEK_SET);
+        if (fseek(f, pos, SEEK_SET) < 0) {
+            fprintf(stderr, "seek failed\n");
+            return 1;
+        }
 
         if (maxburst < 0)
             burst = -maxburst;