Merge branch 'origin/master' into merge-m43

Change-Id: If048232b9af5da8efd1e2418a2e06e67a0cc54d7
diff --git a/.gitignore b/.gitignore
index ebc1169..4f39b12 100644
--- a/.gitignore
+++ b/.gitignore
@@ -83,6 +83,7 @@
 /tools/pktdumper
 /tools/probetest
 /tools/qt-faststart
+/tools/sidxindex
 /tools/trasher
 /tools/seek_print
 /tools/uncoded_frame
diff --git a/Changelog b/Changelog
index 109f4b1..567bd74 100644
--- a/Changelog
+++ b/Changelog
@@ -2,6 +2,15 @@
 releases are sorted from youngest to oldest.
 
 version <next>:
+- FFT video filter
+- TDSC decoder
+- DTS lossless extension (XLL) decoding (not lossless, disabled by default)
+- showwavespic filter
+- libdcadec wrapper
+- Drop support for nvenc API before 5.0
+
+
+version 2.6:
 - nvenc encoder
 - 10bit spp filter
 - colorlevels filter
@@ -17,6 +26,25 @@
 - fspp, uspp, pp7 MPlayer postprocessing filters ported to native filters
 - showpalette filter
 - Twofish symmetric block cipher
+- Support DNx100 (960x720@8)
+- eq2 filter ported from libmpcodecs as eq filter
+- removed libmpcodecs
+- Changed default DNxHD colour range in QuickTime .mov derivatives to mpeg range
+- ported softpulldown filter from libmpcodecs as repeatfields filter
+- dcshift filter
+- RTP depacketizer for loss tolerant payload format for MP3 audio (RFC 5219)
+- RTP depacketizer for AC3 payload format (RFC 4184)
+- palettegen and paletteuse filters
+- VP9 RTP payload format (draft 0) experimental depacketizer
+- RTP depacketizer for DV (RFC 6469)
+- DXVA2-accelerated HEVC decoding
+- AAC ELD 480 decoding
+- Intel QSV-accelerated H.264 decoding
+- DSS SP decoder and DSS demuxer
+- Fix stsd atom corruption in DNxHD QuickTimes
+- Canopus HQX decoder
+- RTP depacketization of T.140 text (RFC 4103)
+- Port MIPS optimizations to 64-bit
 
 
 version 2.5:
diff --git a/LICENSE.md b/LICENSE.md
index fb52cad..42c6b9c 100644
--- a/LICENSE.md
+++ b/LICENSE.md
@@ -1,74 +1,73 @@
 #FFmpeg:
 
 Most files in FFmpeg are under the GNU Lesser General Public License version 2.1
-or later (LGPL v2.1+). Read the file COPYING.LGPLv2.1 for details. Some other
+or later (LGPL v2.1+). Read the file `COPYING.LGPLv2.1` for details. Some other
 files have MIT/X11/BSD-style licenses. In combination the LGPL v2.1+ applies to
 FFmpeg.
 
 Some optional parts of FFmpeg are licensed under the GNU General Public License
-version 2 or later (GPL v2+). See the file COPYING.GPLv2 for details. None of
-these parts are used by default, you have to explicitly pass --enable-gpl to
+version 2 or later (GPL v2+). See the file `COPYING.GPLv2` for details. None of
+these parts are used by default, you have to explicitly pass `--enable-gpl` to
 configure to activate them. In this case, FFmpeg's license changes to GPL v2+.
 
 Specifically, the GPL parts of FFmpeg are:
 
 - libpostproc
-- libmpcodecs
 - optional x86 optimizations in the files
-  libavcodec/x86/flac_dsp_gpl.asm
-  libavcodec/x86/idct_mmx.c
+  - `libavcodec/x86/flac_dsp_gpl.asm`
+  - `libavcodec/x86/idct_mmx.c`
 - libutvideo encoding/decoding wrappers in
-  libavcodec/libutvideo*.cpp
-- the X11 grabber in libavdevice/x11grab.c
+  `libavcodec/libutvideo*.cpp`
+- the X11 grabber in `libavdevice/x11grab.c`
 - the swresample test app in
-  libswresample/swresample-test.c
-- the texi2pod.pl tool
+  `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_delogo.c
-    - vf_eq.c
-    - vf_fspp.c
-    - vf_geq.c
-    - vf_histeq.c
-    - vf_hqdn3d.c
-    - vf_interlace.c
-    - vf_kerndeint.c
-    - vf_mcdeint.c
-    - vf_mp.c
-    - vf_mpdecimate.c
-    - vf_owdenoise.c
-    - vf_perspective.c
-    - vf_phase.c
-    - vf_pp.c
-    - vf_pp7.c
-    - vf_pullup.c
-    - vf_sab.c
-    - vf_smartblur.c
-    - vf_spp.c
-    - vf_stereo3d.c
-    - vf_super2xsai.c
-    - vf_tinterlace.c
-    - vf_uspp.c
-    - vsrc_mptestsrc.c
+    - `f_ebur128.c`
+    - `vf_blackframe.c`
+    - `vf_boxblur.c`
+    - `vf_colormatrix.c`
+    - `vf_cropdetect.c`
+    - `vf_delogo.c`
+    - `vf_eq.c`
+    - `vf_fspp.c`
+    - `vf_geq.c`
+    - `vf_histeq.c`
+    - `vf_hqdn3d.c`
+    - `vf_interlace.c`
+    - `vf_kerndeint.c`
+    - `vf_mcdeint.c`
+    - `vf_mpdecimate.c`
+    - `vf_owdenoise.c`
+    - `vf_perspective.c`
+    - `vf_phase.c`
+    - `vf_pp.c`
+    - `vf_pp7.c`
+    - `vf_pullup.c`
+    - `vf_sab.c`
+    - `vf_smartblur.c`
+    - `vf_repeatfields.c`
+    - `vf_spp.c`
+    - `vf_stereo3d.c`
+    - `vf_super2xsai.c`
+    - `vf_tinterlace.c`
+    - `vf_uspp.c`
+    - `vsrc_mptestsrc.c`
 
 Should you, for whatever reason, prefer to use version 3 of the (L)GPL, then
-the configure parameter --enable-version3 will activate this licensing option
-for you. Read the file COPYING.LGPLv3 or, if you have enabled GPL parts,
-COPYING.GPLv3 to learn the exact legal terms that apply in this case.
+the configure parameter `--enable-version3` will activate this licensing option
+for you. Read the file `COPYING.LGPLv3` or, if you have enabled GPL parts,
+`COPYING.GPLv3` to learn the exact legal terms that apply in this case.
 
 There are a handful of files under other licensing terms, namely:
 
-* The files libavcodec/jfdctfst.c, libavcodec/jfdctint_template.c and
-  libavcodec/jrevdct.c are taken from libjpeg, see the top of the files for
+* The files `libavcodec/jfdctfst.c`, `libavcodec/jfdctint_template.c` and
+  `libavcodec/jrevdct.c` are taken from libjpeg, see the top of the files for
   licensing details. Specifically note that you must credit the IJG in the
   documentation accompanying your program if you only distribute executables.
   You must also indicate any changes including additions and deletions to
   those three files in the documentation.
-  tests/reference.pnm is under the expat license
+* `tests/reference.pnm` is under the expat license.
 
 
 external libraries
@@ -81,21 +80,22 @@
 --------------------
 
 The following libraries are under GPL:
-    - frei0r
-    - libcdio
-    - libutvideo
-    - libvidstab
-    - libx264
-    - libx265
-    - libxavs
-    - libxvid
+- frei0r
+- libcdio
+- libutvideo
+- libvidstab
+- libx264
+- libx265
+- libxavs
+- libxvid
+
 When combining them with FFmpeg, FFmpeg needs to be licensed as GPL as well by
-passing --enable-gpl to configure.
+passing `--enable-gpl` to configure.
 
 The OpenCORE and VisualOn libraries are under the Apache License 2.0. That
 license is incompatible with the LGPL v2.1 and the GPL v2, but not with
 version 3 of those licenses. So to combine these libraries with FFmpeg, the
-license version needs to be upgraded by passing --enable-version3 to configure.
+license version needs to be upgraded by passing `--enable-version3` to configure.
 
 incompatible libraries
 ----------------------
@@ -103,7 +103,7 @@
 The Fraunhofer AAC library, FAAC and aacplus are under licenses which
 are incompatible with the GPLv2 and v3. We do not know for certain if their
 licenses are compatible with the LGPL.
-If you wish to enable these libraries, pass --enable-nonfree to configure.
+If you wish to enable these libraries, pass `--enable-nonfree` to configure.
 But note that if you enable any of these libraries the resulting binary will
 be under a complex license mix that is more restrictive than the LGPL and that
 may result in additional obligations. It is possible that these
diff --git a/MAINTAINERS b/MAINTAINERS
index 13b211e..8d036c0 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -166,6 +166,7 @@
   dca.c                                 Kostya Shishkov, Benjamin Larsson
   dnxhd*                                Baptiste Coudurier
   dpcm.c                                Mike Melanson
+  dss_sp.c                              Oleksij Rempel, Michael Niedermayer
   dv.c                                  Roman Shaposhnik
   dvbsubdec.c                           Anshul Maheshwari
   dxa.c                                 Kostya Shishkov
@@ -401,6 +402,7 @@
   cdxl.c                                Paul B Mahol
   crc.c                                 Michael Niedermayer
   daud.c                                Reimar Doeffinger
+  dss.c                                 Oleksij Rempel, Michael Niedermayer
   dtshddec.c                            Paul B Mahol
   dv.c                                  Roman Shaposhnik
   dxa.c                                 Kostya Shishkov
@@ -465,9 +467,13 @@
   rmdec.c, rmenc.c                      Ronald S. Bultje, Kostya Shishkov
   rtmp*                                 Kostya Shishkov
   rtp.c, rtpenc.c                       Martin Storsjo
+  rtpdec_ac3.*                          Gilles Chanteperdrix
+  rtpdec_dv.*                           Thomas Volkert
   rtpdec_h261.*, rtpenc_h261.*          Thomas Volkert
   rtpdec_hevc.*, rtpenc_hevc.*          Thomas Volkert
+  rtpdec_mpa_robust.*                   Gilles Chanteperdrix
   rtpdec_asf.*                          Ronald S. Bultje
+  rtpdec_vp9.c                          Thomas Volkert
   rtpenc_mpv.*, rtpenc_aac.*            Martin Storsjo
   rtsp.c                                Luca Barbato
   sbgdec.c                              Nicolas George
@@ -539,10 +545,10 @@
 Releases
 ========
 
+2.6                                     Michael Niedermayer
 2.5                                     Michael Niedermayer
 2.4                                     Michael Niedermayer
 2.2                                     Michael Niedermayer
-1.2                                     Michael Niedermayer
 
 If you want to maintain an older release, please contact us
 
diff --git a/Makefile b/Makefile
index 845a274..ca2ce59 100644
--- a/Makefile
+++ b/Makefile
@@ -80,7 +80,7 @@
                HEADERS ARCH_HEADERS BUILT_HEADERS SKIPHEADERS            \
                ARMV5TE-OBJS ARMV6-OBJS ARMV8-OBJS VFP-OBJS NEON-OBJS     \
                ALTIVEC-OBJS MMX-OBJS YASM-OBJS                           \
-               MIPSFPU-OBJS MIPSDSPR2-OBJS MIPSDSPR1-OBJS MIPS32R2-OBJS  \
+               MIPSFPU-OBJS MIPSDSPR2-OBJS MIPSDSPR1-OBJS                \
                OBJS SLIBOBJS HOSTOBJS TESTOBJS
 
 define RESET
diff --git a/README.chromium b/README.chromium
index 77aa9bb..0e41dbd 100644
--- a/README.chromium
+++ b/README.chromium
@@ -3,7 +3,7 @@
 License: LGPL 2.1
 License File: LICENSE.md
 Upstream Git: git://source.ffmpeg.org/ffmpeg.git
-Last Upstream Merge: e5b7e2224f62e9cb6697e664b7d1245302cca9e7, Jan 29 2015
+Last Upstream Merge: 19321a295a641cbc067ec0df597bc1b69addf049, Mar 24 2015
 
 This file documents the layout of the Chromium copy of FFmpeg git, some common
 tasks, how to produce the FFmpeg include directory, and how to create the
@@ -26,13 +26,9 @@
     chromium/config/...: Pregenerated FFmpeg config options for each platform
       and architecture; e.g., ChromeOS: ARM-Neon, Linux: X64, etc.
 
-    chromium/patches/...: Chromium specific changes which haven't yet made it
-      upstream.  See chromium/patches/README for more details on each patch.
+    chromium/patches/README: Details of Chromium specific changes which haven't
+      yet made it upstream.
 
-      Historically, the .patch files were staged on top of a source tarball
-      instead of the Git repository we have now.  The .patch files are kept for
-      tracking purposes.  The new system only requires that you add an entry to
-      the README file with a link to the tracking issue and code review.
 
 Help w/ Common Tasks:
 =====================
@@ -91,7 +87,7 @@
   git checkout master -b my_new_branch
 
   # Pull the patch out of upstream.
-  git cherry-pick <hash of commit in upstream>
+  git cherry-pick -x <hash of commit in upstream>
 
   <Follow rest of "Submitting changes to Chromium's FFmpeg git repository.">
 
diff --git a/README.md b/README.md
index 04089e4..58e1eff 100644
--- a/README.md
+++ b/README.md
@@ -19,8 +19,10 @@
 * [ffmpeg](http://ffmpeg.org/ffmpeg.html) is a command line toolbox to
   manipulate, convert and stream multimedia content.
 * [ffplay](http://ffmpeg.org/ffplay.html) is a minimalistic multimedia player.
-* [ffprobe](http://ffmpeg.org/ffprobe.html) is a simple analisys tool to inspect
+* [ffprobe](http://ffmpeg.org/ffprobe.html) is a simple analysis tool to inspect
   multimedia content.
+* [ffserver](http://ffmpeg.org/ffserver.html) is a multimedia streaming server
+  for live broadcasts.
 * Additional small tools such as `aviocat`, `ismindex` and `qt-faststart`.
 
 ## Documentation
diff --git a/RELEASE b/RELEASE
index 5db7a1a..3359b98 100644
--- a/RELEASE
+++ b/RELEASE
@@ -1 +1 @@
-2.5.git
+2.6.git
diff --git a/RELEASE_NOTES b/RELEASE_NOTES
deleted file mode 100644
index 7362561..0000000
--- a/RELEASE_NOTES
+++ /dev/null
@@ -1,101 +0,0 @@
- ┌────────────────────────────────────────┐
- │ RELEASE NOTES for FFmpeg 2.5 "Bohr"    │
- └────────────────────────────────────────┘
-
-   The FFmpeg Project proudly presents FFmpeg 2.5 "Bohr", just 2.5 months
-   after the release of 2.4. Since this wasn't a long time ago, the Changelog
-   is a bit short this time.
-
-   As usual, if you have any question on this release or any FFmpeg related
-   topic, feel free to join us on the #ffmpeg IRC channel (on
-   irc.freenode.net).
-
-   ┌────────────────────────────┐
-   │ 🔨  API Information         │
-   └────────────────────────────┘
-
-     FFmpeg 2.5 includes the following library versions:
-
-       • libavutil      54.15.100
-       • libavcodec     56.13.100
-       • libavformat    56.15.102
-       • libavdevice    56. 3.100
-       • libavfilter     5. 2.103
-       • libswscale      3. 1.101
-       • libswresample   1. 1.100
-       • libpostproc    53. 3.100
-
-     Important API changes since 2.4:
-
-       • avpriv_dv_frame_profile2() has been deprecated
-
-
-     Please refer to the doc/APIchanges file for more information.
-
- ┌────────────────────────────┐
- │ ★  List of New Features    │
- └────────────────────────────┘
-
-   ┌────────────────────────────┐
-   │ ffprobe                    │
-   └────────────────────────────┘
-
-    • -show_pixel_formats option
-
-   ┌────────────────────────────┐
-   │ ffserver                   │
-   └────────────────────────────┘
-
-    • codec private options support
-
-   ┌────────────────────────────┐
-   │ libavcodec                 │
-   └────────────────────────────┘
-
-    • STL subtitle decoder
-    • libutvideo YUV 4:2:2 10bit support
-    • animated WebP decoding support
-    • zygoaudio decoding support
-
-   ┌────────────────────────────┐
-   │ libavdevice                │
-   └────────────────────────────┘
-
-    • XCB-based screen-grabber
-    • AVFoundation screen capturing support
-
-   ┌────────────────────────────┐
-   │ libavformat                │
-   └────────────────────────────┘
-
-    • HEVC/H.265 RTP payload format (draft v6) packetizer
-    • SUP/PGS subtitle demuxer
-    • STL subtitle demuxer
-    • UDP-Lite support (RFC 3828)
-    • creating DASH compatible fragmented MP4, MPEG-DASH segmenting muxer
-    • WebP muxer
-    • APNG demuxer
-
-   ┌────────────────────────────┐
-   │ libavfilter                │
-   └────────────────────────────┘
-
-    • xBR scaling filter
-
-   ┌────────────────────────────┐
-   │ libavutil                  │
-   └────────────────────────────┘
-
-    • CAST128 symmetric block cipher, ECB mode
-
-   ┌────────────────────────────┐
-   │ libpostproc                │
-   └────────────────────────────┘
-
-    • visualization support
-
- ┌────────────────────────────┐
- │ ⚠  Behaviour changes       │
- └────────────────────────────┘
-    • XMP metadata is not exported by default anymore as it can be huge.
-      see the export_xmp option
diff --git a/arch.mak b/arch.mak
index 0e866d8..48bc2d3 100644
--- a/arch.mak
+++ b/arch.mak
@@ -5,7 +5,6 @@
 OBJS-$(HAVE_NEON)    += $(NEON-OBJS)    $(NEON-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)
 OBJS-$(HAVE_MIPSDSPR2) += $(MIPSDSPR2-OBJS)  $(MIPSDSPR2-OBJS-yes)
 
diff --git a/chromium/patches/README b/chromium/patches/README
index f26c30b..6c02552 100644
--- a/chromium/patches/README
+++ b/chromium/patches/README
@@ -1,4 +1,4 @@
-Current Status as of February 2, 2015
+Current Status as of Mar 24, 2015
 
 Upstream cherry-picks:
 
@@ -36,9 +36,6 @@
     libavutil/internal.h.
 
   Misc things that were not documented
-    Add CONFIG_ERROR_RESILIENCE guard around some code in
-    libavcodec/h264_slice.c.
-
     Enable av_max_alloc(0) to remove alloc size bound in libavutil/mem.c.
 
     Misc changes in libavformat/mp3dec.c.
@@ -46,5 +43,5 @@
     Add FF_DISABLE_DEPRECATION_WARNINGS/FF_ENABLE_DEPRECATION_WARNINGS pairs in
     libavformat/mux.c.
 
-    Remove static av_always_inline av_const unsigned av_clip_uintp2_arm() from
-    libavutil/arm/intmath.h due to compilation failure.
+    Remove static av_always_inline av_const unsigned av_clip_uintp2_arm() and
+    av_clip_intp2_arm() from libavutil/arm/intmath.h due to compilation failure.
diff --git a/cmdutils.c b/cmdutils.c
index 53268d8..46d0b4b 100644
--- a/cmdutils.c
+++ b/cmdutils.c
@@ -1081,8 +1081,7 @@
         av_log(NULL, level, " Copyright (c) %d-%d the FFmpeg developers",
                program_birth_year, CONFIG_THIS_YEAR);
     av_log(NULL, level, "\n");
-    av_log(NULL, level, "%sbuilt on %s %s with %s\n",
-           indent, __DATE__, __TIME__, CC_IDENT);
+    av_log(NULL, level, "%sbuilt with %s\n", indent, CC_IDENT);
 
     av_log(NULL, level, "%sconfiguration: " FFMPEG_CONFIGURATION "\n", indent);
 }
@@ -1913,7 +1912,8 @@
     }
 
 out:
-    av_log(NULL, AV_LOG_ERROR, "IO error: %s\n", av_err2str(ret));
+    if (ret < 0)
+        av_log(NULL, AV_LOG_ERROR, "IO error: %s\n", av_err2str(ret));
     fclose(f);
     return ret;
 }
diff --git a/common.mak b/common.mak
index a493792..eac8bd9 100644
--- a/common.mak
+++ b/common.mak
@@ -5,6 +5,14 @@
 # first so "all" becomes default target
 all: all-yes
 
+DEFAULT_YASMD=.dbg
+
+ifeq ($(DBG),1)
+YASMD=$(DEFAULT_YASMD)
+else
+YASMD=
+endif
+
 ifndef SUBDIR
 
 ifndef V
@@ -138,17 +146,17 @@
 
 OBJDIRS := $(OBJDIRS) $(dir $(OBJS) $(HOBJS) $(HOSTOBJS) $(SLIBOBJS) $(TESTOBJS))
 
-CLEANSUFFIXES     = *.d *.o *~ *.h.c *.map *.ver *.ho *.gcno *.gcda
+CLEANSUFFIXES     = *.d *.o *~ *.h.c *.map *.ver *.ho *.gcno *.gcda *$(DEFAULT_YASMD).asm
 DISTCLEANSUFFIXES = *.pc
 LIBSUFFIXES       = *.a *.lib *.so *.so.* *.dylib *.dll *.def *.dll.a
 
 define RULES
 clean::
-	$(RM) $(OBJS) $(OBJS:.o=.d)
+	$(RM) $(OBJS) $(OBJS:.o=.d) $(OBJS:.o=$(DEFAULT_YASMD).d)
 	$(RM) $(HOSTPROGS)
 	$(RM) $(TOOLS)
 endef
 
 $(eval $(RULES))
 
--include $(wildcard $(OBJS:.o=.d) $(HOSTOBJS:.o=.d) $(TESTOBJS:.o=.d) $(HOBJS:.o=.d) $(SLIBOBJS:.o=.d))
+-include $(wildcard $(OBJS:.o=.d) $(HOSTOBJS:.o=.d) $(TESTOBJS:.o=.d) $(HOBJS:.o=.d) $(SLIBOBJS:.o=.d)) $(OBJS:.o=$(DEFAULT_YASMD).d)
diff --git a/compat/avisynth/windowsPorts/windows2linux.h b/compat/avisynth/windowsPorts/windows2linux.h
index 5476afe..7cf4600 100644
--- a/compat/avisynth/windowsPorts/windows2linux.h
+++ b/compat/avisynth/windowsPorts/windows2linux.h
@@ -52,8 +52,8 @@
 //
 // Functions
 //
-#define MAKEDWORD(a,b,c,d) ((a << 24) | (b << 16) | (c << 8) | (d))
-#define MAKEWORD(a,b) ((a << 8) | (b))
+#define MAKEDWORD(a,b,c,d) (((a) << 24) | ((b) << 16) | ((c) << 8) | (d))
+#define MAKEWORD(a,b) (((a) << 8) | (b))
 
 #define lstrlen                             strlen
 #define lstrcpy                             strcpy
diff --git a/configure b/configure
index 80985cb..ede517e 100755
--- a/configure
+++ b/configure
@@ -133,9 +133,9 @@
   --disable-postproc       disable libpostproc build
   --disable-avfilter       disable libavfilter build
   --enable-avresample      enable libavresample build [no]
-  --disable-pthreads       disable pthreads [auto]
-  --disable-w32threads     disable Win32 threads [auto]
-  --disable-os2threads     disable OS/2 threads [auto]
+  --disable-pthreads       disable pthreads [autodetect]
+  --disable-w32threads     disable Win32 threads [autodetect]
+  --disable-os2threads     disable OS/2 threads [autodetect]
   --disable-network        disable network support [no]
   --disable-dct            disable DCT code
   --disable-dwt            disable DWT code
@@ -210,6 +210,7 @@
   --enable-libcdio         enable audio CD grabbing with libcdio [no]
   --enable-libdc1394       enable IIDC-1394 grabbing using libdc1394
                            and libraw1394 [no]
+  --enable-libdcadec       enable DCA decoding via libdcadec [no]
   --enable-libfaac         enable AAC encoding via libfaac [no]
   --enable-libfdk-aac      enable AAC de/encoding via libfdk-aac [no]
   --enable-libflite        enable flite (voice synthesis) support via libflite [no]
@@ -219,6 +220,7 @@
   --enable-libgsm          enable GSM de/encoding via libgsm [no]
   --enable-libiec61883     enable iec61883 via libiec61883 [no]
   --enable-libilbc         enable iLBC de/encoding via libilbc [no]
+  --enable-libmfx          enable HW acceleration through libmfx
   --enable-libmodplug      enable ModPlug via libmodplug [no]
   --enable-libmp3lame      enable MP3 encoding via libmp3lame [no]
   --enable-libnut          enable NUT (de)muxing via libnut,
@@ -254,10 +256,10 @@
   --enable-libx264         enable H.264 encoding via x264 [no]
   --enable-libx265         enable HEVC encoding via x265 [no]
   --enable-libxavs         enable AVS encoding via xavs [no]
-  --enable-libxcb          enable X11 grabbing using XCB [auto]
-  --enable-libxcb-shm      enable X11 grabbing shm communication [auto]
-  --enable-libxcb-xfixes   enable X11 grabbing mouse rendering [auto]
-  --enable-libxcb-shape    enable X11 grabbing shape rendering [auto]
+  --enable-libxcb          enable X11 grabbing using XCB [autodetect]
+  --enable-libxcb-shm      enable X11 grabbing shm communication [autodetect]
+  --enable-libxcb-xfixes   enable X11 grabbing mouse rendering [autodetect]
+  --enable-libxcb-shape    enable X11 grabbing shape rendering [autodetect]
   --enable-libxvid         enable Xvid encoding via xvidcore,
                            native MPEG-4/Xvid encoder exists [no]
   --enable-libzmq          enable message passing via libzmq [no]
@@ -357,7 +359,6 @@
   --disable-neon           disable NEON optimizations
   --disable-inline-asm     disable use of inline assembly
   --disable-yasm           disable use of nasm/yasm assembly
-  --disable-mips32r2       disable MIPS32R2 optimizations
   --disable-mipsdspr1      disable MIPS DSP ASE R1 optimizations
   --disable-mipsdspr2      disable MIPS DSP ASE R2 optimizations
   --disable-mipsfpu        disable floating point MIPS optimizations
@@ -1328,6 +1329,7 @@
     filtering_video_example
     metadata_example
     muxing_example
+    qsvdec_example
     remuxing_example
     resampling_audio_example
     scaling_video_example
@@ -1352,6 +1354,7 @@
     libcdio
     libcelt
     libdc1394
+    libdcadec
     libfaac
     libfdk_aac
     libflite
@@ -1362,6 +1365,7 @@
     libgsm
     libiec61883
     libilbc
+    libmfx
     libmodplug
     libmp3lame
     libnut
@@ -1766,6 +1770,7 @@
 TOOLCHAIN_FEATURES="
     as_dn_directive
     as_func
+    as_object_arch
     asm_mod_q
     attribute_may_alias
     attribute_packed
@@ -1835,6 +1840,7 @@
     section_data_rel_ro
     texi2html
     threads
+    vaapi_x11
     vdpau_x11
     xlib
 "
@@ -1853,6 +1859,7 @@
     faandct
     faanidct
     fdctdsp
+    fmtconvert
     frame_thread_encoder
     gcrypt
     golomb
@@ -1868,6 +1875,7 @@
     huffyuvencdsp
     idctdsp
     iirfilter
+    imdct15
     intrax8
     lgplv3
     llauddsp
@@ -1882,6 +1890,7 @@
     nettle
     pixblockdsp
     qpeldsp
+    qsv
     rangecoder
     riffdec
     riffenc
@@ -1992,7 +2001,6 @@
 map 'eval ${v}_inline_deps=inline_asm' $ARCH_EXT_LIST_ARM
 
 mipsfpu_deps="mips"
-mips32r2_deps="mips"
 mipsdspr1_deps="mips"
 mipsdspr2_deps="mips"
 
@@ -2067,10 +2075,10 @@
 mpegvideoenc_select="me_cmp mpegvideo pixblockdsp qpeldsp"
 
 # decoders / encoders
-aac_decoder_select="mdct sinewin"
+aac_decoder_select="imdct15 mdct sinewin"
 aac_encoder_select="audio_frame_queue iirfilter mdct sinewin"
 aac_latm_decoder_select="aac_decoder aac_latm_parser"
-ac3_decoder_select="ac3_parser ac3dsp bswapdsp mdct"
+ac3_decoder_select="ac3_parser ac3dsp bswapdsp fmtconvert mdct"
 ac3_fixed_decoder_select="ac3_parser ac3dsp bswapdsp mdct"
 ac3_encoder_select="ac3dsp audiodsp mdct me_cmp"
 ac3_fixed_encoder_select="ac3dsp audiodsp mdct me_cmp"
@@ -2100,7 +2108,7 @@
 cook_decoder_select="audiodsp mdct sinewin"
 cscd_decoder_select="lzo"
 cscd_decoder_suggest="zlib"
-dca_decoder_select="mdct"
+dca_decoder_select="fmtconvert mdct"
 dirac_decoder_select="dwt golomb videodsp mpegvideoenc"
 dnxhd_decoder_select="blockdsp idctdsp"
 dnxhd_encoder_select="aandcttables blockdsp fdctdsp idctdsp mpegvideoenc pixblockdsp"
@@ -2138,6 +2146,8 @@
 h263p_encoder_select="h263_encoder"
 h264_decoder_select="cabac golomb h264chroma h264dsp h264pred h264qpel startcode videodsp"
 h264_decoder_suggest="error_resilience"
+h264_qsv_decoder_deps="libmfx"
+h264_qsv_decoder_select="h264_mp4toannexb_bsf h264_parser qsv h264_qsv_hwaccel"
 hevc_decoder_select="bswapdsp cabac golomb videodsp"
 huffyuv_decoder_select="bswapdsp huffyuvdsp llviddsp"
 huffyuv_encoder_select="bswapdsp huffman huffyuvencdsp llviddsp"
@@ -2192,6 +2202,7 @@
 nuv_decoder_select="idctdsp lzo"
 on2avc_decoder_select="mdct"
 opus_decoder_deps="swresample"
+opus_decoder_select="imdct15"
 png_decoder_select="zlib"
 png_encoder_select="huffyuvencdsp zlib"
 prores_decoder_select="blockdsp idctdsp"
@@ -2222,6 +2233,7 @@
 svq3_decoder_select="h264_decoder hpeldsp tpeldsp"
 svq3_decoder_suggest="zlib"
 tak_decoder_select="audiodsp"
+tdsc_decoder_select="zlib mjpeg_decoder"
 theora_decoder_select="vp3_decoder"
 thp_decoder_select="mjpeg_decoder"
 tiff_decoder_suggest="zlib lzma"
@@ -2282,6 +2294,7 @@
 h264_crystalhd_decoder_select="crystalhd h264_mp4toannexb_bsf h264_parser"
 h264_dxva2_hwaccel_deps="dxva2"
 h264_dxva2_hwaccel_select="h264_decoder"
+h264_qsv_hwaccel_deps="libmfx"
 h264_vaapi_hwaccel_deps="vaapi"
 h264_vaapi_hwaccel_select="h264_decoder"
 h264_vda_decoder_deps="vda"
@@ -2348,6 +2361,7 @@
 # external libraries
 libaacplus_encoder_deps="libaacplus"
 libcelt_decoder_deps="libcelt"
+libdcadec_decoder_deps="libdcadec"
 libfaac_encoder_deps="libfaac"
 libfaac_encoder_select="audio_frame_queue"
 libfdk_aac_decoder_deps="libfdk_aac"
@@ -2448,6 +2462,7 @@
 mpegts_muxer_select="adts_muxer latm_muxer"
 mpegtsraw_demuxer_select="mpegts_demuxer"
 mxf_d10_muxer_select="mxf_muxer"
+mxf_opatom_muxer_select="mxf_muxer"
 nut_muxer_select="riffenc"
 nuv_demuxer_select="riffdec"
 oga_muxer_select="ogg_muxer"
@@ -2481,7 +2496,7 @@
 # indevs / outdevs
 alsa_indev_deps="alsa_asoundlib_h snd_pcm_htimestamp"
 alsa_outdev_deps="alsa_asoundlib_h"
-avfoundation_indev_extralibs="-framework CoreVideo -framework Foundation -framework AVFoundation -framework CoreMedia -framework CoreGraphics"
+avfoundation_indev_extralibs="-framework CoreVideo -framework Foundation -framework AVFoundation -framework CoreMedia"
 avfoundation_indev_select="avfoundation"
 bktr_indev_deps_any="dev_bktr_ioctl_bt848_h machine_ioctl_bt848_h dev_video_bktr_ioctl_bt848_h dev_ic_bt8xx_h"
 caca_outdev_deps="libcaca"
@@ -2585,6 +2600,8 @@
 drawtext_filter_deps="libfreetype"
 ebur128_filter_deps="gpl"
 eq_filter_deps="gpl"
+fftfilt_filter_deps="avcodec"
+fftfilt_filter_select="rdft"
 flite_filter_deps="libflite"
 frei0r_filter_deps="frei0r dlopen"
 frei0r_src_filter_deps="frei0r dlopen"
@@ -2597,7 +2614,6 @@
 ladspa_filter_deps="ladspa dlopen"
 mcdeint_filter_deps="avcodec gpl"
 movie_filter_deps="avcodec avformat"
-mp_filter_deps="gpl avcodec swscale"
 mpdecimate_filter_deps="gpl"
 mpdecimate_filter_select="pixelutils"
 mptestsrc_filter_deps="gpl"
@@ -2611,6 +2627,7 @@
 pp_filter_deps="gpl postproc"
 pullup_filter_deps="gpl"
 removelogo_filter_deps="avcodec avformat swscale"
+repeatfields_filter_deps="gpl"
 resample_filter_deps="avresample"
 sab_filter_deps="gpl swscale"
 scale_filter_deps="swscale"
@@ -2644,6 +2661,7 @@
 filtering_video_example_deps="avfilter avcodec avformat avutil"
 metadata_example_deps="avformat avutil"
 muxing_example_deps="avcodec avformat avutil swscale"
+qsvdec_example_deps="avcodec avutil libmfx h264_qsv_decoder vaapi_x11"
 remuxing_example_deps="avcodec avformat avutil"
 resampling_audio_example_deps="avutil swresample"
 scaling_video_example_deps="avutil swscale"
@@ -2980,24 +2998,6 @@
 echo "# $0 $FFMPEG_CONFIGURATION" > $logfile
 set >> $logfile
 
-test -n "$cross_prefix" && enable cross_compile
-
-if enabled cross_compile; then
-    test -n "$arch" && test -n "$target_os" ||
-        die "Must specify target arch and OS when cross-compiling"
-fi
-
-ar_default="${cross_prefix}${ar_default}"
-cc_default="${cross_prefix}${cc_default}"
-cxx_default="${cross_prefix}${cxx_default}"
-nm_default="${cross_prefix}${nm_default}"
-pkg_config_default="${cross_prefix}${pkg_config_default}"
-ranlib_default="${cross_prefix}${ranlib_default}"
-strip_default="${cross_prefix}${strip_default}"
-windres_default="${cross_prefix}${windres_default}"
-
-sysinclude_default="${sysroot}/usr/include"
-
 test -n "$valgrind" && toolchain="valgrind-memcheck"
 
 case "$toolchain" in
@@ -3084,6 +3084,24 @@
     ;;
 esac
 
+test -n "$cross_prefix" && enable cross_compile
+
+if enabled cross_compile; then
+    test -n "$arch" && test -n "$target_os" ||
+        die "Must specify target arch and OS when cross-compiling"
+fi
+
+ar_default="${cross_prefix}${ar_default}"
+cc_default="${cross_prefix}${cc_default}"
+cxx_default="${cross_prefix}${cxx_default}"
+nm_default="${cross_prefix}${nm_default}"
+pkg_config_default="${cross_prefix}${pkg_config_default}"
+ranlib_default="${cross_prefix}${ranlib_default}"
+strip_default="${cross_prefix}${strip_default}"
+windres_default="${cross_prefix}${windres_default}"
+
+sysinclude_default="${sysroot}/usr/include"
+
 set_default arch cc cxx doxygen pkg_config ranlib strip sysinclude \
     target_exec target_os yasmexe
 enabled cross_compile || host_cc_default=$cc
@@ -3242,8 +3260,8 @@
             -Wall)                echo -W4 -wd4244 -wd4127 -wd4018 -wd4389     \
                                        -wd4146 -wd4057 -wd4204 -wd4706 -wd4305 \
                                        -wd4152 -wd4324 -we4013 -wd4100 -wd4214 \
-                                       -wd4554 \
-                                       -wd4273 -wd4701 ;;
+                                       -wd4307 \
+                                       -wd4273 -wd4554 -wd4701 ;;
         esac
     done
 }
@@ -3520,7 +3538,9 @@
         _flags='-nologo'
         _cflags='-D_USE_MATH_DEFINES -D_CRT_SECURE_NO_WARNINGS -Dinline=__inline -FIstdlib.h -Dstrtoll=_strtoi64'
         if [ $pfx = hostcc ]; then
-            append _cflags -Dsnprintf=_snprintf
+            if [ -z "$cl_major_ver" ] || [ $cl_major_ver -le 18 ]; then
+                append _cflags -Dsnprintf=_snprintf
+            fi
         fi
         disable stripping
     elif $_cc --version 2>/dev/null | grep -q ^cparser; then
@@ -3734,6 +3754,7 @@
         elif check_arm_arch 6T2;      then echo armv6t2;
         elif check_arm_arch 7;        then echo armv7;
         elif check_arm_arch 7A  7_A;  then echo armv7-a;
+        elif check_arm_arch 7S;       then echo armv7-a;
         elif check_arm_arch 7R  7_R;  then echo armv7-r;
         elif check_arm_arch 7M  7_M;  then echo armv7-m;
         elif check_arm_arch 7EM 7E_M; then echo armv7-m;
@@ -4024,6 +4045,7 @@
         SHFLAGS='-shared -Wl,-h,$$(@F)'
         enabled x86 && SHFLAGS="-mimpure-text $SHFLAGS"
         network_extralibs="-lsocket -lnsl"
+        add_cppflags -D__EXTENSIONS__
         # When using suncc to build, the Solaris linker will mark
         # an executable with each instruction set encountered by
         # the Solaris assembler.  As our libraries contain their own
@@ -4068,7 +4090,7 @@
         SLIBNAME_WITH_MAJOR='$(SLIBPREF)$(FULLNAME).$(LIBMAJOR)$(SLIBSUF)'
         objformat="macho"
         enabled x86_64 && objformat="macho64"
-        enabled_any pic shared ||
+        enabled_any pic shared x86_64 ||
             { check_cflags -mdynamic-no-pic && add_asflags -mdynamic-no-pic; }
         ;;
     mingw32*)
@@ -4307,10 +4329,12 @@
         add_compat strtod.o strtod=avpriv_strtod
         ;;
     msvcrt)
-        add_compat strtod.o strtod=avpriv_strtod
-        add_compat msvcrt/snprintf.o snprintf=avpriv_snprintf   \
-                                     _snprintf=avpriv_snprintf  \
-                                     vsnprintf=avpriv_vsnprintf
+        if [ -z "$cl_major_ver" ] || [ $cl_major_ver -le 18 ]; then
+            add_compat strtod.o strtod=avpriv_strtod
+            add_compat msvcrt/snprintf.o snprintf=avpriv_snprintf   \
+                                         _snprintf=avpriv_snprintf  \
+                                         vsnprintf=avpriv_vsnprintf
+        fi
         ;;
 esac
 
@@ -4551,13 +4575,29 @@
 .unreq ra
 EOF
 
+    # llvm's integrated assembler supports .object_arch from llvm 3.5
+    [ "$objformat" = elf ] && check_as <<EOF && enable as_object_arch
+.object_arch armv4
+EOF
+
     [ $target_os != win32 ] && enabled_all armv6t2 shared !pic && enable_weak_pic
 
 elif enabled mips; then
 
     check_inline_asm loongson '"dmult.g $1, $2, $3"'
-    enabled mips32r2  && add_cflags "-mips32r2" && add_asflags "-mips32r2" &&
-     check_inline_asm mips32r2  '"rotr $t0, $t1, 1"'
+
+    # Enable minimum ISA based on selected options
+    if enabled mips64 && (enabled mipsdspr1 || enabled mipsdspr2); then
+        add_cflags "-mips64r2"
+        add_asflags "-mips64r2"
+    elif enabled mips64 && enabled mipsfpu; then
+        add_cflags "-mips64"
+        add_asflags "-mips64"
+    elif enabled mipsfpu || enabled mipsdspr1 || enabled mipsdspr2; then
+        add_cflags "-mips32r2"
+        add_asflags "-mips32r2"
+    fi
+
     enabled mipsdspr1 && add_cflags "-mdsp" && add_asflags "-mdsp" &&
      check_inline_asm mipsdspr1 '"addu.qb $t0, $t1, $t2"'
     enabled mipsdspr2 && add_cflags "-mdspr2" && add_asflags "-mdspr2" &&
@@ -4868,6 +4908,8 @@
 
 # these are off by default, so fail if requested and not available
 enabled avfoundation_indev && { check_header_oc AVFoundation/AVFoundation.h || disable avfoundation_indev; }
+enabled avfoundation_indev && { check_lib2 CoreGraphics/CoreGraphics.h CGGetActiveDisplayList -framework CoreGraphics ||
+                                check_lib2 ApplicationServices/ApplicationServices.h CGGetActiveDisplayList -framework ApplicationServices; }
 enabled avisynth          && { { check_lib2 "windows.h" LoadLibrary; } ||
                                { check_lib2 "dlfcn.h" dlopen -ldl; } ||
                                die "ERROR: LoadLibrary/dlopen not found for avisynth"; }
@@ -4884,6 +4926,7 @@
                              { check_lib celt/celt.h celt_decoder_create_custom -lcelt0 ||
                                die "ERROR: libcelt must be installed and version must be >= 0.11.0."; }
 enabled libcaca           && require_pkg_config caca caca.h caca_create_canvas
+enabled libdcadec         && require libdcadec libdcadec/dca_context.h dcadec_context_create -ldcadec
 enabled libfaac           && require2 libfaac "stdint.h faac.h" faacEncGetVersion -lfaac
 enabled libfdk_aac        && require libfdk_aac fdk-aac/aacenc_lib.h aacEncOpen -lfdk-aac
 flite_libs="-lflite_cmu_time_awb -lflite_cmu_us_awb -lflite_cmu_us_kal -lflite_cmu_us_kal16 -lflite_cmu_us_rms -lflite_cmu_us_slt -lflite_usenglish -lflite_cmulex -lflite"
@@ -4897,6 +4940,7 @@
                                    check_lib "${gsm_hdr}" gsm_create -lgsm && break;
                                done || die "ERROR: libgsm not found"; }
 enabled libilbc           && require libilbc ilbc.h WebRtcIlbcfix_InitDecode -lilbc
+enabled libmfx            && require_pkg_config libmfx "mfx/mfxvideo.h" MFXInit
 enabled libmodplug        && require_pkg_config libmodplug libmodplug/modplug.h ModPlug_Load
 enabled libmp3lame        && require "libmp3lame >= 3.98.3" lame/lame.h lame_set_VBR_quality -lmp3lame
 enabled libnut            && require libnut libnut.h nut_demuxer_init -lnut
@@ -4954,6 +4998,8 @@
 enabled libzmq            && require_pkg_config libzmq zmq.h zmq_ctx_new
 enabled libzvbi           && require libzvbi libzvbi.h vbi_decoder_new -lzvbi
 enabled nvenc             && { check_header nvEncodeAPI.h || die "ERROR: nvEncodeAPI.h not found."; } &&
+                             { check_cpp_condition nvEncodeAPI.h "NVENCAPI_MAJOR_VERSION >= 5" ||
+                               die "ERROR: NVENC API version 4 or older is not supported"; } &&
                              { [ $target_os != cygwin ] || die "ERROR: NVENC is not supported on Cygwin currently."; }
 enabled openal            && { { for al_libs in "${OPENAL_LIBS}" "-lopenal" "-lOpenAL32"; do
                                check_lib 'AL/al.h' alGetError "${al_libs}" && break; done } ||
@@ -4985,7 +5031,7 @@
 
 # libdc1394 check
 if enabled libdc1394; then
-    { check_lib dc1394/dc1394.h dc1394_new -ldc1394 -lraw1394 &&
+    { require_pkg_config libdc1394-2 dc1394/dc1394.h dc1394_new &&
         enable libdc1394_2; } ||
     { check_lib libdc1394/dc1394_control.h dc1394_create_handle -ldc1394_control -lraw1394 &&
         enable libdc1394_1; } ||
@@ -5069,7 +5115,7 @@
 if enabled libcdio; then
     check_lib2 "cdio/cdda.h cdio/paranoia.h" cdio_cddap_open -lcdio_paranoia -lcdio_cdda -lcdio ||
     check_lib2 "cdio/paranoia/cdda.h cdio/paranoia/paranoia.h" cdio_cddap_open -lcdio_paranoia -lcdio_cdda -lcdio ||
-    die "ERROR: libcdio-paranoia not found"
+    die "ERROR: No usable libcdio/cdparanoia found"
 fi
 
 enabled xlib &&
@@ -5123,6 +5169,10 @@
     check_lib va/va.h vaInitialize -lva ||
     disable vaapi
 
+enabled vaapi && enabled xlib &&
+    check_lib2 "va/va.h va/va_x11.h" vaGetDisplay -lva -lva-x11 &&
+    enable vaapi_x11
+
 enabled vdpau &&
     check_cpp_condition vdpau/vdpau.h "defined VDP_DECODER_PROFILE_MPEG4_PART2_ASP" ||
     disable vdpau
@@ -5256,7 +5306,9 @@
     # 10006: ignoring unknown option -fno-signed-zeros
     # 10148: ignoring unknown option -Wno-parentheses
     # 10156: ignoring option '-W'; no argument required
-    check_cflags -wd144,167,188,556,1292,1419,10006,10148,10156
+    # 13200: No EMMS instruction before call to function
+    # 13203: No EMMS instruction before return from function
+    check_cflags -wd144,167,188,556,1292,1419,10006,10148,10156,13200,13203
     # 11030: Warning unknown option --as-needed
     # 10156: ignoring option '-export'; no argument required
     check_ldflags -wd10156,11030
@@ -5284,6 +5336,7 @@
     check_cflags -Werror=return-type
     check_cflags -Werror=vla
     check_cflags -Wformat
+    check_cflags -fdiagnostics-color=auto
     enabled extra_warnings || check_disable_warning -Wno-maybe-uninitialized
 elif enabled llvm_gcc; then
     check_cflags -mllvm -stack-alignment=16
@@ -5370,7 +5423,7 @@
 fi
 
 enabled_all dxva2 dxva2api_cobj CoTaskMemFree &&
-    prepend ffmpeg_libs $($ldflags_filter "-lole32") &&
+    prepend ffmpeg_libs $($ldflags_filter "-lole32" "-luser32") &&
     enable dxva2_lib
 
 ! enabled_any memalign posix_memalign aligned_malloc &&
@@ -5422,9 +5475,9 @@
 enabled atempo_filter       && prepend avfilter_deps "avcodec"
 enabled ebur128_filter && enabled swresample && prepend avfilter_deps "swresample"
 enabled elbg_filter         && prepend avfilter_deps "avcodec"
+enabled fftfilt_filter      && prepend avfilter_deps "avcodec"
 enabled mcdeint_filter      && prepend avfilter_deps "avcodec"
 enabled movie_filter    && prepend avfilter_deps "avformat avcodec"
-enabled mp_filter           && prepend avfilter_deps "avcodec"
 enabled pan_filter          && prepend avfilter_deps "swresample"
 enabled pp_filter           && prepend avfilter_deps "postproc"
 enabled removelogo_filter   && prepend avfilter_deps "avformat avcodec swscale"
@@ -5503,7 +5556,6 @@
 fi
 if enabled mips; then
     echo "MIPS FPU enabled          ${mipsfpu-no}"
-    echo "MIPS32R2 enabled          ${mips32r2-no}"
     echo "MIPS DSP R1 enabled       ${mipsdspr1-no}"
     echo "MIPS DSP R2 enabled       ${mipsdspr2-no}"
 fi
diff --git a/doc/APIchanges b/doc/APIchanges
index 65fd599..3f153e9 100644
--- a/doc/APIchanges
+++ b/doc/APIchanges
@@ -15,21 +15,42 @@
 
 API changes, most recent first:
 
-2015-01-xx - xxxxxxx - lavc 56.12.0, lavu 54.8.0 - avcodec.h, frame.h
+-------- 8< --------- FFmpeg 2.6 was cut here -------- 8< ---------
+
+2015-03-04 - cca4476 - lavf 56.25.100
+  Add avformat_flush()
+
+2015-03-03 - 81a9126 - lavf 56.24.100
+  Add avio_put_str16be()
+
+2015-02-19 - 560eb71 / 31d2039 - lavc 56.23.100 / 56.13.0
+  Add width, height, coded_width, coded_height and format to
+  AVCodecParserContext.
+
+2015-02-19 - e375511 / 5b1d9ce - lavu 54.19.100 / 54.9.0
+  Add AV_PIX_FMT_QSV for QSV hardware acceleration.
+
+2015-02-14 - ba22295 - lavc 56.21.102
+  Deprecate VIMA decoder.
+
+2015-01-27 - 62a82c6 / 728685f - lavc 56.21.100 / 56.12.0, lavu 54.18.100 / 54.8.0 - avcodec.h, frame.h
   Add AV_PKT_DATA_AUDIO_SERVICE_TYPE and AV_FRAME_DATA_AUDIO_SERVICE_TYPE for
   storing the audio service type as side data.
 
+2015-01-16 - a47c933 - lavf 56.19.100 - avformat.h
+  Add data_codec and data_codec_id for storing codec of data stream
+
 2015-01-11 - 007c33d - lavd 56.4.100 - avdevice.h
   Add avdevice_list_input_sources().
   Add avdevice_list_output_sinks().
 
-2014-12-27 - d7aaeea / c220a60 - lavc 56.19.100 / 56.10.0 - vdpau.h
+2014-12-25 - d7aaeea / c220a60 - lavc 56.19.100 / 56.10.0 - vdpau.h
   Add av_vdpau_get_surface_parameters().
 
-2014-12-27 - ddb9a24 / 6c99c92 - lavc 56.18.100 / 56.9.0 - avcodec.h
+2014-12-25 - ddb9a24 / 6c99c92 - lavc 56.18.100 / 56.9.0 - avcodec.h
   Add AV_HWACCEL_FLAG_ALLOW_HIGH_DEPTH flag to av_vdpau_bind_context().
 
-2014-12-27 - d16079a / 57b6704 - lavc 56.17.100 / 56.8.0 - avcodec.h
+2014-12-25 - d16079a / 57b6704 - lavc 56.17.100 / 56.8.0 - avcodec.h
   Add AVCodecContext.sw_pix_fmt.
 
 2014-12-04 - 6e9ac02 - lavc 56.14.100 - dv_profile.h
@@ -275,7 +296,7 @@
   Add avcodec_free_context(). From now on it should be used for freeing
   AVCodecContext.
 
-2014-05-17 - 0eec06e - lavu 52.84.100 - time.h
+2014-05-17 - 0eec06e / 1bd0bdc - lavu 52.84.100 / 54.5.0 - time.h
   Add av_gettime_relative() av_gettime_relative_is_monotonic()
 
 2014-05-15 - eacf7d6 / 0c1959b - lavf 55.38.100 / 55.17.0 - avformat.h
diff --git a/doc/Makefile b/doc/Makefile
index 2502922..697142f 100644
--- a/doc/Makefile
+++ b/doc/Makefile
@@ -46,6 +46,7 @@
 DOC_EXAMPLES-$(CONFIG_FILTERING_VIDEO_EXAMPLE)   += filtering_video
 DOC_EXAMPLES-$(CONFIG_METADATA_EXAMPLE)          += metadata
 DOC_EXAMPLES-$(CONFIG_MUXING_EXAMPLE)            += muxing
+DOC_EXAMPLES-$(CONFIG_QSVDEC_EXAMPLE)            += qsvdec
 DOC_EXAMPLES-$(CONFIG_REMUXING_EXAMPLE)          += remuxing
 DOC_EXAMPLES-$(CONFIG_RESAMPLING_AUDIO_EXAMPLE)  += resampling_audio
 DOC_EXAMPLES-$(CONFIG_SCALING_VIDEO_EXAMPLE)     += scaling_video
@@ -114,9 +115,9 @@
 
 doc/%.1 doc/%.3: TAG = MAN
 doc/%.1: doc/%.pod $(GENTEXI)
-	$(M)pod2man --section=1 --center=" " --release=" " $< > $@
+	$(M)pod2man --section=1 --center=" " --release=" " --date=" " $< > $@
 doc/%.3: doc/%.pod $(GENTEXI)
-	$(M)pod2man --section=3 --center=" " --release=" " $< > $@
+	$(M)pod2man --section=3 --center=" " --release=" " --date=" " $< > $@
 
 $(DOCS) doc/doxy/html: | doc/
 $(DOC_EXAMPLES:%$(EXESUF)=%.o): | doc/examples
diff --git a/doc/build_system.txt b/doc/build_system.txt
index 2efde5c..20242b1 100644
--- a/doc/build_system.txt
+++ b/doc/build_system.txt
@@ -7,6 +7,11 @@
     Disable the default terse mode, the full command issued by make and its
     output will be shown on the screen.
 
+DBG
+    Preprocess x86 external assembler files to a .dbg.asm file in the object
+    directory, which then gets compiled. Helps developping those assembler
+    files.
+
 DESTDIR
     Destination directory for the install targets, useful to prepare packages
     or install FFmpeg in cross-environments.
diff --git a/doc/developer.texi b/doc/developer.texi
index f1351a5..d9ccf7b 100644
--- a/doc/developer.texi
+++ b/doc/developer.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle Developer Documentation
 @titlepage
@@ -227,7 +228,7 @@
 @end example
 
 For Emacs, add these roughly equivalent lines to your @file{.emacs.d/init.el}:
-@example
+@lisp
 (c-add-style "ffmpeg"
              '("k&r"
                (c-basic-offset . 4)
@@ -238,7 +239,7 @@
                )
              )
 (setq c-default-style "ffmpeg")
-@end example
+@end lisp
 
 @section Development Policy
 
diff --git a/doc/doxy-wrapper.sh b/doc/doxy-wrapper.sh
index d88f60e..9720e54 100755
--- a/doc/doxy-wrapper.sh
+++ b/doc/doxy-wrapper.sh
@@ -6,8 +6,16 @@
 
 shift 3
 
+if [ -e "$SRC_PATH/VERSION" ]; then
+    VERSION=`cat "$SRC_PATH/VERSION"`
+else
+    VERSION=`cd "$SRC_PATH"; git describe`
+fi
+
 $DOXYGEN - <<EOF
 @INCLUDE        = ${DOXYFILE}
 INPUT           = $@
 EXAMPLE_PATH    = ${SRC_PATH}/doc/examples
+HTML_TIMESTAMP  = NO
+PROJECT_NUMBER  = $VERSION
 EOF
diff --git a/doc/examples/demuxing_decoding.c b/doc/examples/demuxing_decoding.c
index 2ce4018..feeeb96 100644
--- a/doc/examples/demuxing_decoding.c
+++ b/doc/examples/demuxing_decoding.c
@@ -36,6 +36,8 @@
 
 static AVFormatContext *fmt_ctx = NULL;
 static AVCodecContext *video_dec_ctx = NULL, *audio_dec_ctx;
+static int width, height;
+static enum AVPixelFormat pix_fmt;
 static AVStream *video_stream = NULL, *audio_stream = NULL;
 static const char *src_filename = NULL;
 static const char *video_dst_filename = NULL;
@@ -79,6 +81,20 @@
             fprintf(stderr, "Error decoding video frame (%s)\n", av_err2str(ret));
             return ret;
         }
+        if (video_dec_ctx->width != width || video_dec_ctx->height != height ||
+            video_dec_ctx->pix_fmt != pix_fmt) {
+            /* To handle this change, one could call av_image_alloc again and
+             * decode the following frames into another rawvideo file. */
+            fprintf(stderr, "Error: Width, height and pixel format have to be "
+                    "constant in a rawvideo file, but the width, height or "
+                    "pixel format of the input video changed:\n"
+                    "old: width = %d, height = %d, format = %s\n"
+                    "new: width = %d, height = %d, format = %s\n",
+                    width, height, av_get_pix_fmt_name(pix_fmt),
+                    video_dec_ctx->width, video_dec_ctx->height,
+                    av_get_pix_fmt_name(video_dec_ctx->pix_fmt));
+            return -1;
+        }
 
         if (*got_frame) {
             printf("video_frame%s n:%d coded_n:%d pts:%s\n",
@@ -90,7 +106,7 @@
              * this is required since rawvideo expects non aligned data */
             av_image_copy(video_dst_data, video_dst_linesize,
                           (const uint8_t **)(frame->data), frame->linesize,
-                          video_dec_ctx->pix_fmt, video_dec_ctx->width, video_dec_ctx->height);
+                          pix_fmt, width, height);
 
             /* write to rawvideo file */
             fwrite(video_dst_data[0], 1, video_dst_bufsize, video_dst_file);
@@ -138,7 +154,7 @@
 static int open_codec_context(int *stream_idx,
                               AVFormatContext *fmt_ctx, enum AVMediaType type)
 {
-    int ret;
+    int ret, stream_index;
     AVStream *st;
     AVCodecContext *dec_ctx = NULL;
     AVCodec *dec = NULL;
@@ -150,8 +166,8 @@
                 av_get_media_type_string(type), src_filename);
         return ret;
     } else {
-        *stream_idx = ret;
-        st = fmt_ctx->streams[*stream_idx];
+        stream_index = ret;
+        st = fmt_ctx->streams[stream_index];
 
         /* find decoder for the stream */
         dec_ctx = st->codec;
@@ -170,6 +186,7 @@
                     av_get_media_type_string(type));
             return ret;
         }
+        *stream_idx = stream_index;
     }
 
     return 0;
@@ -264,9 +281,11 @@
         }
 
         /* allocate image where the decoded image will be put */
+        width = video_dec_ctx->width;
+        height = video_dec_ctx->height;
+        pix_fmt = video_dec_ctx->pix_fmt;
         ret = av_image_alloc(video_dst_data, video_dst_linesize,
-                             video_dec_ctx->width, video_dec_ctx->height,
-                             video_dec_ctx->pix_fmt, 1);
+                             width, height, pix_fmt, 1);
         if (ret < 0) {
             fprintf(stderr, "Could not allocate raw video buffer\n");
             goto end;
@@ -341,7 +360,7 @@
     if (video_stream) {
         printf("Play the output video file with the command:\n"
                "ffplay -f rawvideo -pix_fmt %s -video_size %dx%d %s\n",
-               av_get_pix_fmt_name(video_dec_ctx->pix_fmt), video_dec_ctx->width, video_dec_ctx->height,
+               av_get_pix_fmt_name(pix_fmt), width, height,
                video_dst_filename);
     }
 
diff --git a/doc/examples/qsvdec.c b/doc/examples/qsvdec.c
new file mode 100644
index 0000000..6dbb210
--- /dev/null
+++ b/doc/examples/qsvdec.c
@@ -0,0 +1,484 @@
+/*
+ * Copyright (c) 2015 Anton Khirnov
+ *
+ * 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.
+ */
+
+/**
+ * @file
+ * Intel QSV-accelerated H.264 decoding example.
+ *
+ * @example qsvdec.c
+ * This example shows how to do QSV-accelerated H.264 decoding with output
+ * frames in the VA-API video surfaces.
+ */
+
+#include "config.h"
+
+#include <stdio.h>
+
+#include <mfx/mfxvideo.h>
+
+#include <va/va.h>
+#include <va/va_x11.h>
+#include <X11/Xlib.h>
+
+#include "libavformat/avformat.h"
+#include "libavformat/avio.h"
+
+#include "libavcodec/avcodec.h"
+#include "libavcodec/qsv.h"
+
+#include "libavutil/error.h"
+#include "libavutil/mem.h"
+
+typedef struct DecodeContext {
+    mfxSession mfx_session;
+    VADisplay va_dpy;
+
+    VASurfaceID *surfaces;
+    mfxMemId    *surface_ids;
+    int         *surface_used;
+    int       nb_surfaces;
+
+    mfxFrameInfo frame_info;
+} DecodeContext;
+
+static mfxStatus frame_alloc(mfxHDL pthis, mfxFrameAllocRequest *req,
+                             mfxFrameAllocResponse *resp)
+{
+    DecodeContext *decode = pthis;
+    int err, i;
+
+    if (decode->surfaces) {
+        fprintf(stderr, "Multiple allocation requests.\n");
+        return MFX_ERR_MEMORY_ALLOC;
+    }
+    if (!(req->Type & MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET)) {
+        fprintf(stderr, "Unsupported surface type: %d\n", req->Type);
+        return MFX_ERR_UNSUPPORTED;
+    }
+    if (req->Info.BitDepthLuma != 8 || req->Info.BitDepthChroma != 8 ||
+        req->Info.Shift || req->Info.FourCC != MFX_FOURCC_NV12 ||
+        req->Info.ChromaFormat != MFX_CHROMAFORMAT_YUV420) {
+        fprintf(stderr, "Unsupported surface properties.\n");
+        return MFX_ERR_UNSUPPORTED;
+    }
+
+    decode->surfaces     = av_malloc_array (req->NumFrameSuggested, sizeof(*decode->surfaces));
+    decode->surface_ids  = av_malloc_array (req->NumFrameSuggested, sizeof(*decode->surface_ids));
+    decode->surface_used = av_mallocz_array(req->NumFrameSuggested, sizeof(*decode->surface_used));
+    if (!decode->surfaces || !decode->surface_ids || !decode->surface_used)
+        goto fail;
+
+    err = vaCreateSurfaces(decode->va_dpy, VA_RT_FORMAT_YUV420,
+                           req->Info.Width, req->Info.Height,
+                           decode->surfaces, req->NumFrameSuggested,
+                           NULL, 0);
+    if (err != VA_STATUS_SUCCESS) {
+        fprintf(stderr, "Error allocating VA surfaces\n");
+        goto fail;
+    }
+    decode->nb_surfaces = req->NumFrameSuggested;
+
+    for (i = 0; i < decode->nb_surfaces; i++)
+        decode->surface_ids[i] = &decode->surfaces[i];
+
+    resp->mids           = decode->surface_ids;
+    resp->NumFrameActual = decode->nb_surfaces;
+
+    decode->frame_info = req->Info;
+
+    return MFX_ERR_NONE;
+fail:
+    av_freep(&decode->surfaces);
+    av_freep(&decode->surface_ids);
+    av_freep(&decode->surface_used);
+
+    return MFX_ERR_MEMORY_ALLOC;
+}
+
+static mfxStatus frame_free(mfxHDL pthis, mfxFrameAllocResponse *resp)
+{
+    DecodeContext *decode = pthis;
+
+    if (decode->surfaces)
+        vaDestroySurfaces(decode->va_dpy, decode->surfaces, decode->nb_surfaces);
+    av_freep(&decode->surfaces);
+    av_freep(&decode->surface_ids);
+    av_freep(&decode->surface_used);
+    decode->nb_surfaces = 0;
+
+    return MFX_ERR_NONE;
+}
+
+static mfxStatus frame_lock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
+{
+    return MFX_ERR_UNSUPPORTED;
+}
+
+static mfxStatus frame_unlock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
+{
+    return MFX_ERR_UNSUPPORTED;
+}
+
+static mfxStatus frame_get_hdl(mfxHDL pthis, mfxMemId mid, mfxHDL *hdl)
+{
+    *hdl = mid;
+    return MFX_ERR_NONE;
+}
+
+static void free_buffer(void *opaque, uint8_t *data)
+{
+    int *used = opaque;
+    *used = 0;
+    av_freep(&data);
+}
+
+static int get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
+{
+    DecodeContext *decode = avctx->opaque;
+
+    mfxFrameSurface1 *surf;
+    AVBufferRef *surf_buf;
+    int idx;
+
+    for (idx = 0; idx < decode->nb_surfaces; idx++) {
+        if (!decode->surface_used[idx])
+            break;
+    }
+    if (idx == decode->nb_surfaces) {
+        fprintf(stderr, "No free surfaces\n");
+        return AVERROR(ENOMEM);
+    }
+
+    surf = av_mallocz(sizeof(*surf));
+    if (!surf)
+        return AVERROR(ENOMEM);
+    surf_buf = av_buffer_create((uint8_t*)surf, sizeof(*surf), free_buffer,
+                                &decode->surface_used[idx], AV_BUFFER_FLAG_READONLY);
+    if (!surf_buf) {
+        av_freep(&surf);
+        return AVERROR(ENOMEM);
+    }
+
+    surf->Info       = decode->frame_info;
+    surf->Data.MemId = &decode->surfaces[idx];
+
+    frame->buf[0]  = surf_buf;
+    frame->data[3] = (uint8_t*)surf;
+
+    decode->surface_used[idx] = 1;
+
+    return 0;
+}
+
+static int get_format(AVCodecContext *avctx, const enum AVPixelFormat *pix_fmts)
+{
+    while (*pix_fmts != AV_PIX_FMT_NONE) {
+        if (*pix_fmts == AV_PIX_FMT_QSV) {
+            if (!avctx->hwaccel_context) {
+                DecodeContext *decode = avctx->opaque;
+                AVQSVContext *qsv = av_qsv_alloc_context();
+                if (!qsv)
+                    return AV_PIX_FMT_NONE;
+
+                qsv->session   = decode->mfx_session;
+                qsv->iopattern = MFX_IOPATTERN_OUT_VIDEO_MEMORY;
+
+                avctx->hwaccel_context = qsv;
+            }
+
+            return AV_PIX_FMT_QSV;
+        }
+
+        pix_fmts++;
+    }
+
+    fprintf(stderr, "The QSV pixel format not offered in get_format()\n");
+
+    return AV_PIX_FMT_NONE;
+}
+
+static int decode_packet(DecodeContext *decode, AVCodecContext *decoder_ctx,
+                         AVFrame *frame, AVPacket *pkt,
+                         AVIOContext *output_ctx)
+{
+    int ret = 0;
+    int got_frame = 1;
+
+    while (pkt->size > 0 || (!pkt->data && got_frame)) {
+        ret = avcodec_decode_video2(decoder_ctx, frame, &got_frame, pkt);
+        if (ret < 0) {
+            fprintf(stderr, "Error during decoding\n");
+            return ret;
+        }
+
+        pkt->data += ret;
+        pkt->size -= ret;
+
+        /* A real program would do something useful with the decoded frame here.
+         * We just retrieve the raw data and write it to a file, which is rather
+         * useless but pedagogic. */
+        if (got_frame) {
+            mfxFrameSurface1 *surf = (mfxFrameSurface1*)frame->data[3];
+            VASurfaceID    surface = *(VASurfaceID*)surf->Data.MemId;
+
+            VAImageFormat img_fmt = {
+                .fourcc         = VA_FOURCC_NV12,
+                .byte_order     = VA_LSB_FIRST,
+                .bits_per_pixel = 8,
+                .depth          = 8,
+            };
+
+            VAImage img;
+
+            VAStatus err;
+            uint8_t *data;
+            int i, j;
+
+            img.buf      = VA_INVALID_ID;
+            img.image_id = VA_INVALID_ID;
+
+            err = vaCreateImage(decode->va_dpy, &img_fmt,
+                                frame->width, frame->height, &img);
+            if (err != VA_STATUS_SUCCESS) {
+                fprintf(stderr, "Error creating an image: %s\n",
+                        vaErrorStr(err));
+                ret = AVERROR_UNKNOWN;
+                goto fail;
+            }
+
+            err = vaGetImage(decode->va_dpy, surface, 0, 0,
+                             frame->width, frame->height,
+                             img.image_id);
+            if (err != VA_STATUS_SUCCESS) {
+                fprintf(stderr, "Error getting an image: %s\n",
+                        vaErrorStr(err));
+                ret = AVERROR_UNKNOWN;
+                goto fail;
+            }
+
+            err = vaMapBuffer(decode->va_dpy, img.buf, (void**)&data);
+            if (err != VA_STATUS_SUCCESS) {
+                fprintf(stderr, "Error mapping the image buffer: %s\n",
+                        vaErrorStr(err));
+                ret = AVERROR_UNKNOWN;
+                goto fail;
+            }
+
+            for (i = 0; i < img.num_planes; i++)
+                for (j = 0; j < (img.height >> (i > 0)); j++)
+                    avio_write(output_ctx, data + img.offsets[i] + j * img.pitches[i], img.width);
+
+fail:
+            if (img.buf != VA_INVALID_ID)
+                vaUnmapBuffer(decode->va_dpy, img.buf);
+            if (img.image_id != VA_INVALID_ID)
+                vaDestroyImage(decode->va_dpy, img.image_id);
+            av_frame_unref(frame);
+
+            if (ret < 0)
+                return ret;
+        }
+    }
+
+    return 0;
+}
+
+int main(int argc, char **argv)
+{
+    AVFormatContext *input_ctx = NULL;
+    AVStream *video_st = NULL;
+    AVCodecContext *decoder_ctx = NULL;
+    const AVCodec *decoder;
+
+    AVPacket pkt = { 0 };
+    AVFrame *frame = NULL;
+
+    DecodeContext decode = { NULL };
+
+    Display *dpy = NULL;
+    int va_ver_major, va_ver_minor;
+
+    mfxIMPL mfx_impl = MFX_IMPL_AUTO_ANY;
+    mfxVersion mfx_ver = { { 1, 1 } };
+
+    mfxFrameAllocator frame_allocator = {
+        .pthis = &decode,
+        .Alloc = frame_alloc,
+        .Lock  = frame_lock,
+        .Unlock = frame_unlock,
+        .GetHDL = frame_get_hdl,
+        .Free   = frame_free,
+    };
+
+    AVIOContext *output_ctx = NULL;
+
+    int ret, i, err;
+
+    av_register_all();
+
+    if (argc < 3) {
+        fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
+        return 1;
+    }
+
+    /* open the input file */
+    ret = avformat_open_input(&input_ctx, argv[1], NULL, NULL);
+    if (ret < 0) {
+        fprintf(stderr, "Cannot open input file '%s': ", argv[1]);
+        goto finish;
+    }
+
+    /* find the first H.264 video stream */
+    for (i = 0; i < input_ctx->nb_streams; i++) {
+        AVStream *st = input_ctx->streams[i];
+
+        if (st->codec->codec_id == AV_CODEC_ID_H264 && !video_st)
+            video_st = st;
+        else
+            st->discard = AVDISCARD_ALL;
+    }
+    if (!video_st) {
+        fprintf(stderr, "No H.264 video stream in the input file\n");
+        goto finish;
+    }
+
+    /* initialize VA-API */
+    dpy = XOpenDisplay(NULL);
+    if (!dpy) {
+        fprintf(stderr, "Cannot open the X display\n");
+        goto finish;
+    }
+    decode.va_dpy = vaGetDisplay(dpy);
+    if (!decode.va_dpy) {
+        fprintf(stderr, "Cannot open the VA display\n");
+        goto finish;
+    }
+
+    err = vaInitialize(decode.va_dpy, &va_ver_major, &va_ver_minor);
+    if (err != VA_STATUS_SUCCESS) {
+        fprintf(stderr, "Cannot initialize VA: %s\n", vaErrorStr(err));
+        goto finish;
+    }
+    fprintf(stderr, "Initialized VA v%d.%d\n", va_ver_major, va_ver_minor);
+
+    /* initialize an MFX session */
+    err = MFXInit(mfx_impl, &mfx_ver, &decode.mfx_session);
+    if (err != MFX_ERR_NONE) {
+        fprintf(stderr, "Error initializing an MFX session\n");
+        goto finish;
+    }
+
+    MFXVideoCORE_SetHandle(decode.mfx_session, MFX_HANDLE_VA_DISPLAY, decode.va_dpy);
+    MFXVideoCORE_SetFrameAllocator(decode.mfx_session, &frame_allocator);
+
+    /* initialize the decoder */
+    decoder = avcodec_find_decoder_by_name("h264_qsv");
+    if (!decoder) {
+        fprintf(stderr, "The QSV decoder is not present in libavcodec\n");
+        goto finish;
+    }
+
+    decoder_ctx = avcodec_alloc_context3(decoder);
+    if (!decoder_ctx) {
+        ret = AVERROR(ENOMEM);
+        goto finish;
+    }
+    decoder_ctx->codec_id = AV_CODEC_ID_H264;
+    if (video_st->codec->extradata_size) {
+        decoder_ctx->extradata = av_mallocz(video_st->codec->extradata_size +
+                                            FF_INPUT_BUFFER_PADDING_SIZE);
+        if (!decoder_ctx->extradata) {
+            ret = AVERROR(ENOMEM);
+            goto finish;
+        }
+        memcpy(decoder_ctx->extradata, video_st->codec->extradata,
+               video_st->codec->extradata_size);
+        decoder_ctx->extradata_size = video_st->codec->extradata_size;
+    }
+    decoder_ctx->refcounted_frames = 1;
+
+    decoder_ctx->opaque      = &decode;
+    decoder_ctx->get_buffer2 = get_buffer;
+    decoder_ctx->get_format  = get_format;
+
+    ret = avcodec_open2(decoder_ctx, NULL, NULL);
+    if (ret < 0) {
+        fprintf(stderr, "Error opening the decoder: ");
+        goto finish;
+    }
+
+    /* open the output stream */
+    ret = avio_open(&output_ctx, argv[2], AVIO_FLAG_WRITE);
+    if (ret < 0) {
+        fprintf(stderr, "Error opening the output context: ");
+        goto finish;
+    }
+
+    frame = av_frame_alloc();
+    if (!frame) {
+        ret = AVERROR(ENOMEM);
+        goto finish;
+    }
+
+    /* actual decoding */
+    while (ret >= 0) {
+        ret = av_read_frame(input_ctx, &pkt);
+        if (ret < 0)
+            break;
+
+        if (pkt.stream_index == video_st->index)
+            ret = decode_packet(&decode, decoder_ctx, frame, &pkt, output_ctx);
+
+        av_packet_unref(&pkt);
+    }
+
+    /* flush the decoder */
+    pkt.data = NULL;
+    pkt.size = 0;
+    ret = decode_packet(&decode, decoder_ctx, frame, &pkt, output_ctx);
+
+finish:
+    if (ret < 0) {
+        char buf[1024];
+        av_strerror(ret, buf, sizeof(buf));
+        fprintf(stderr, "%s\n", buf);
+    }
+
+    avformat_close_input(&input_ctx);
+
+    av_frame_free(&frame);
+
+    if (decode.mfx_session)
+        MFXClose(decode.mfx_session);
+    if (decode.va_dpy)
+        vaTerminate(decode.va_dpy);
+    if (dpy)
+        XCloseDisplay(dpy);
+
+    if (decoder_ctx)
+        av_freep(&decoder_ctx->hwaccel_context);
+    avcodec_free_context(&decoder_ctx);
+
+    avio_close(output_ctx);
+
+    return ret;
+}
diff --git a/doc/faq.texi b/doc/faq.texi
index 3d94d4d..5fe716b 100644
--- a/doc/faq.texi
+++ b/doc/faq.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle FFmpeg FAQ
 @titlepage
@@ -348,7 +349,7 @@
 @code{concat}} protocol designed specifically for that, with examples in the
 documentation.
 
-A few multimedia containers (MPEG-1, MPEG-2 PS, DV) allow to concatenate
+A few multimedia containers (MPEG-1, MPEG-2 PS, DV) allow one to concatenate
 video by merely concatenating the files containing them.
 
 Hence you may concatenate your multimedia files by first transcoding them to
@@ -466,6 +467,40 @@
 @option{-qscale} and @option{-qmax}, but you should peruse the documentation
 of the encoder you chose.
 
+@section I have a stretched video, why does scaling does not fix it?
+
+A lot of video codecs and formats can store the @emph{aspect ratio} of the
+video: this is the ratio between the width and the height of either the full
+image (DAR, display aspect ratio) or individual pixels (SAR, sample aspect
+ratio). For example, EGA screens at resolution 640×350 had 4:3 DAR and 35:48
+SAR.
+
+Most still image processing work with square pixels, i.e. 1:1 SAR, but a lot
+of video standards, especially from the analogic-numeric transition era, use
+non-square pixels.
+
+Most processing filters in FFmpeg handle the aspect ratio to avoid
+stretching the image: cropping adjusts the DAR to keep the SAR constant,
+scaling adjusts the SAR to keep the DAR constant.
+
+If you want to stretch, or “unstretch”, the image, you need to override the
+information with the
+@url{http://ffmpeg.org/ffmpeg-filters.html#setdar_002c-setsar, @code{setdar or setsar filters}}.
+
+Do not forget to examine carefully the original video to check whether the
+stretching comes from the image or from the aspect ratio information.
+
+For example, to fix a badly encoded EGA capture, use the following commands,
+either the first one to upscale to square pixels or the second one to set
+the correct aspect ratio or the third one to avoid transcoding (may not work
+depending on the format / codec / player / phase of the moon):
+
+@example
+ffmpeg -i ega_screen.nut -vf scale=640:480,setsar=1 ega_screen_scaled.nut
+ffmpeg -i ega_screen.nut -vf setdar=4/3 ega_screen_anamorphic.nut
+ffmpeg -i ega_screen.nut -aspect 4/3 -c copy ega_screen_overridden.nut
+@end example
+
 @chapter Development
 
 @section Are there examples illustrating how to use the FFmpeg libraries, particularly libavcodec and libavformat?
diff --git a/doc/fate.texi b/doc/fate.texi
index 4e5cbd7..353443a 100644
--- a/doc/fate.texi
+++ b/doc/fate.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle FFmpeg Automated Testing Environment
 @titlepage
@@ -12,36 +13,36 @@
 
 @chapter Introduction
 
-  FATE is an extended regression suite on the client-side and a means
+FATE is an extended regression suite on the client-side and a means
 for results aggregation and presentation on the server-side.
 
-  The first part of this document explains how you can use FATE from
+The first part of this document explains how you can use FATE from
 your FFmpeg source directory to test your ffmpeg binary. The second
 part describes how you can run FATE to submit the results to FFmpeg's
 FATE server.
 
-  In any way you can have a look at the publicly viewable FATE results
+In any way you can have a look at the publicly viewable FATE results
 by visiting this website:
 
-  @url{http://fate.ffmpeg.org/}
+@url{http://fate.ffmpeg.org/}
 
-  This is especially recommended for all people contributing source
+This is especially recommended for all people contributing source
 code to FFmpeg, as it can be seen if some test on some platform broke
 with their recent contribution. This usually happens on the platforms
 the developers could not test on.
 
-  The second part of this document describes how you can run FATE to
+The second part of this document describes how you can run FATE to
 submit your results to FFmpeg's FATE server. If you want to submit your
 results be sure to check that your combination of CPU, OS and compiler
 is not already listed on the above mentioned website.
 
-  In the third part you can find a comprehensive listing of FATE makefile
+In the third part you can find a comprehensive listing of FATE makefile
 targets and variables.
 
 
 @chapter Using FATE from your FFmpeg source directory
 
-  If you want to run FATE on your machine you need to have the samples
+If you want to run FATE on your machine you need to have the samples
 in place. You can get the samples via the build target fate-rsync.
 Use this command from the top-level source directory:
 
@@ -50,11 +51,11 @@
 make fate       SAMPLES=fate-suite/
 @end example
 
-  The above commands set the samples location by passing a makefile
+The above commands set the samples location by passing a makefile
 variable via command line. It is also possible to set the samples
 location at source configuration time by invoking configure with
-`--samples=<path to the samples directory>'. Afterwards you can
-invoke the makefile targets without setting the SAMPLES makefile
+@option{--samples=<path to the samples directory>}. Afterwards you can
+invoke the makefile targets without setting the @var{SAMPLES} makefile
 variable. This is illustrated by the following commands:
 
 @example
@@ -63,7 +64,7 @@
 make fate
 @end example
 
-  Yet another way to tell FATE about the location of the sample
+Yet another way to tell FATE about the location of the sample
 directory is by making sure the environment variable FATE_SAMPLES
 contains the path to your samples directory. This can be achieved
 by e.g. putting that variable in your shell profile or by setting
@@ -84,7 +85,7 @@
 
 @chapter Submitting the results to the FFmpeg result aggregation server
 
-  To submit your results to the server you should run fate through the
+To submit your results to the server you should run fate through the
 shell script @file{tests/fate.sh} from the FFmpeg sources. This script needs
 to be invoked with a configuration file as its first argument.
 
@@ -92,23 +93,23 @@
 tests/fate.sh /path/to/fate_config
 @end example
 
-  A configuration file template with comments describing the individual
+A configuration file template with comments describing the individual
 configuration variables can be found at @file{doc/fate_config.sh.template}.
 
 @ifhtml
-  The mentioned configuration template is also available here:
+The mentioned configuration template is also available here:
 @verbatiminclude fate_config.sh.template
 @end ifhtml
 
-  Create a configuration that suits your needs, based on the configuration
-template. The `slot' configuration variable can be any string that is not
+Create a configuration that suits your needs, based on the configuration
+template. The @env{slot} configuration variable can be any string that is not
 yet used, but it is suggested that you name it adhering to the following
-pattern <arch>-<os>-<compiler>-<compiler version>. The configuration file
-itself will be sourced in a shell script, therefore all shell features may
-be used. This enables you to setup the environment as you need it for your
-build.
+pattern @samp{@var{arch}-@var{os}-@var{compiler}-@var{compiler version}}. The
+configuration file itself will be sourced in a shell script, therefore all
+shell features may be used. This enables you to setup the environment as you
+need it for your build.
 
-  For your first test runs the `fate_recv' variable should be empty or
+For your first test runs the @env{fate_recv} variable should be empty or
 commented out. This will run everything as normal except that it will omit
 the submission of the results to the server. The following files should be
 present in $workdir as specified in the configuration file:
@@ -121,29 +122,29 @@
     @item version
 @end itemize
 
-  When you have everything working properly you can create an SSH key pair
+When you have everything working properly you can create an SSH key pair
 and send the public key to the FATE server administrator who can be contacted
 at the email address @email{fate-admin@@ffmpeg.org}.
 
-  Configure your SSH client to use public key authentication with that key
+Configure your SSH client to use public key authentication with that key
 when connecting to the FATE server. Also do not forget to check the identity
 of the server and to accept its host key. This can usually be achieved by
 running your SSH client manually and killing it after you accepted the key.
 The FATE server's fingerprint is:
 
-@table @option
+@table @samp
 @item RSA
    d3:f1:83:97:a4:75:2b:a6:fb:d6:e8:aa:81:93:97:51
 @item ECDSA
    76:9f:68:32:04:1e:d5:d4:ec:47:3f:dc:fc:18:17:86
 @end table
 
-  If you have problems connecting to the FATE server, it may help to try out
+If you have problems connecting to the FATE server, it may help to try out
 the @command{ssh} command with one or more @option{-v} options. You should
 get detailed output concerning your SSH configuration and the authentication
 process.
 
-  The only thing left is to automate the execution of the fate.sh script and
+The only thing left is to automate the execution of the fate.sh script and
 the synchronisation of the samples directory.
 
 
@@ -164,7 +165,7 @@
 
 @section Makefile variables
 
-@table @option
+@table @env
 @item V
 Verbosity level, can be set to 0, 1 or 2.
     @itemize
@@ -182,20 +183,20 @@
 quite useful to detect thread-related regressions.
 
 @item THREAD_TYPE
-Specify which threading strategy test, either @var{slice} or @var{frame},
-by default @var{slice+frame}
+Specify which threading strategy test, either @samp{slice} or @samp{frame},
+by default @samp{slice+frame}
 
 @item CPUFLAGS
 Specify CPU flags.
 
 @item TARGET_EXEC
 Specify or override the wrapper used to run the tests.
-The @var{TARGET_EXEC} option provides a way to run FATE wrapped in
+The @env{TARGET_EXEC} option provides a way to run FATE wrapped in
 @command{valgrind}, @command{qemu-user} or @command{wine} or on remote targets
 through @command{ssh}.
 
 @item GEN
-Set to @var{1} to generate the missing or mismatched references.
+Set to @samp{1} to generate the missing or mismatched references.
 @end table
 
 @section Examples
diff --git a/doc/ffmpeg-bitstream-filters.texi b/doc/ffmpeg-bitstream-filters.texi
index e33e005..bbde257 100644
--- a/doc/ffmpeg-bitstream-filters.texi
+++ b/doc/ffmpeg-bitstream-filters.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle FFmpeg Bitstream Filters Documentation
 @titlepage
diff --git a/doc/ffmpeg-codecs.texi b/doc/ffmpeg-codecs.texi
index 6f8f5a3..7df4391 100644
--- a/doc/ffmpeg-codecs.texi
+++ b/doc/ffmpeg-codecs.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle FFmpeg Codecs Documentation
 @titlepage
diff --git a/doc/ffmpeg-devices.texi b/doc/ffmpeg-devices.texi
index b44bd72..721c0df 100644
--- a/doc/ffmpeg-devices.texi
+++ b/doc/ffmpeg-devices.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle FFmpeg Devices Documentation
 @titlepage
diff --git a/doc/ffmpeg-filters.texi b/doc/ffmpeg-filters.texi
index bb920ce..b643f2c 100644
--- a/doc/ffmpeg-filters.texi
+++ b/doc/ffmpeg-filters.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle FFmpeg Filters Documentation
 @titlepage
diff --git a/doc/ffmpeg-formats.texi b/doc/ffmpeg-formats.texi
index e205caa..d916ee8 100644
--- a/doc/ffmpeg-formats.texi
+++ b/doc/ffmpeg-formats.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle FFmpeg Formats Documentation
 @titlepage
diff --git a/doc/ffmpeg-protocols.texi b/doc/ffmpeg-protocols.texi
index d992e75..f3a09f6 100644
--- a/doc/ffmpeg-protocols.texi
+++ b/doc/ffmpeg-protocols.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle FFmpeg Protocols Documentation
 @titlepage
diff --git a/doc/ffmpeg-resampler.texi b/doc/ffmpeg-resampler.texi
index 5bef789..be3784f 100644
--- a/doc/ffmpeg-resampler.texi
+++ b/doc/ffmpeg-resampler.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle FFmpeg Resampler Documentation
 @titlepage
diff --git a/doc/ffmpeg-scaler.texi b/doc/ffmpeg-scaler.texi
index c4ddc09..9ab12a1 100644
--- a/doc/ffmpeg-scaler.texi
+++ b/doc/ffmpeg-scaler.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle FFmpeg Scaler Documentation
 @titlepage
diff --git a/doc/ffmpeg-utils.texi b/doc/ffmpeg-utils.texi
index 581e2ea..e39cfa8 100644
--- a/doc/ffmpeg-utils.texi
+++ b/doc/ffmpeg-utils.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle FFmpeg Utilities Documentation
 @titlepage
diff --git a/doc/ffmpeg.texi b/doc/ffmpeg.texi
index 396c623..1dde682 100644
--- a/doc/ffmpeg.texi
+++ b/doc/ffmpeg.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle ffmpeg Documentation
 @titlepage
@@ -994,6 +995,13 @@
 taken. You can leave either video or audio unchanged and sync the
 remaining stream(s) to the unchanged one.
 
+@item -frame_drop_threshold @var{parameter}
+Frame drop threshold, which specifies how much behind video frames can
+be before they are dropped. In frame rate units, so 1.0 is one frame.
+The default is -1.1. One possible usecase is to avoid framedrops in case
+of noisy timestamps or to increase frame drop precision in case of exact
+timestamps.
+
 @item -async @var{samples_per_second}
 Audio sync method. "Stretches/squeezes" the audio stream to match the timestamps,
 the parameter is the maximum samples per second by which the audio is changed.
@@ -1150,6 +1158,12 @@
 transcoding. Use @option{-noaccurate_seek} to disable it, which may be useful
 e.g. when copying some streams and transcoding the others.
 
+@item -thread_message_queue @var{size} (@emph{input})
+This option sets the maximum number of queued packets when reading from the
+file or device. With low latency / high rate live streams, packets may be
+discarded if they are not read in a timely manner; raising this value can
+avoid it.
+
 @item -override_ffserver (@emph{global})
 Overrides the input specifications from @command{ffserver}. Using this
 option you can map any input stream to @command{ffserver} and control
@@ -1455,7 +1469,7 @@
 
 For creating a video from many images:
 @example
-ffmpeg -f image2 -i foo-%03d.jpeg -r 12 -s WxH foo.avi
+ffmpeg -f image2 -framerate 12 -i foo-%03d.jpeg -s WxH foo.avi
 @end example
 
 The syntax @code{foo-%03d.jpeg} specifies to use a decimal number
@@ -1470,7 +1484,7 @@
 For example, for creating a video from filenames matching the glob pattern
 @code{foo-*.jpeg}:
 @example
-ffmpeg -f image2 -pattern_type glob -i 'foo-*.jpeg' -r 12 -s WxH foo.avi
+ffmpeg -f image2 -pattern_type glob -framerate 12 -i 'foo-*.jpeg' -s WxH foo.avi
 @end example
 
 @item
diff --git a/doc/ffplay.texi b/doc/ffplay.texi
index 45731a2..d5397a9 100644
--- a/doc/ffplay.texi
+++ b/doc/ffplay.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle ffplay Documentation
 @titlepage
diff --git a/doc/ffprobe.texi b/doc/ffprobe.texi
index 5c90470..2024eed 100644
--- a/doc/ffprobe.texi
+++ b/doc/ffprobe.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle ffprobe Documentation
 @titlepage
@@ -446,17 +447,17 @@
 It can assume one of the following values:
 @table @option
 @item c
-Perform C-like escaping. Strings containing a newline ('\n'), carriage
-return ('\r'), a tab ('\t'), a form feed ('\f'), the escaping
-character ('\') or the item separator character @var{SEP} are escaped using C-like fashioned
-escaping, so that a newline is converted to the sequence "\n", a
-carriage return to "\r", '\' to "\\" and the separator @var{SEP} is
-converted to "\@var{SEP}".
+Perform C-like escaping. Strings containing a newline (@samp{\n}), carriage
+return (@samp{\r}), a tab (@samp{\t}), a form feed (@samp{\f}), the escaping
+character (@samp{\}) or the item separator character @var{SEP} are escaped
+using C-like fashioned escaping, so that a newline is converted to the
+sequence @samp{\n}, a carriage return to @samp{\r}, @samp{\} to @samp{\\} and
+the separator @var{SEP} is converted to @samp{\@var{SEP}}.
 
 @item csv
 Perform CSV-like escaping, as described in RFC4180.  Strings
-containing a newline ('\n'), a carriage return ('\r'), a double quote
-('"'), or @var{SEP} are enclosed in double-quotes.
+containing a newline (@samp{\n}), a carriage return (@samp{\r}), a double quote
+(@samp{"}), or @var{SEP} are enclosed in double-quotes.
 
 @item none
 Perform no escaping.
@@ -484,7 +485,7 @@
 Separator character used to separate the chapter, the section name, IDs and
 potential tags in the printed field key.
 
-Default value is '.'.
+Default value is @samp{.}.
 
 @item hierarchical, h
 Specify if the section name specification should be hierarchical. If
@@ -506,21 +507,22 @@
 @item
 all key and values are UTF-8
 @item
-'.' is the subgroup separator
+@samp{.} is the subgroup separator
 @item
-newline, '\t', '\f', '\b' and the following characters are escaped
+newline, @samp{\t}, @samp{\f}, @samp{\b} and the following characters are
+escaped
 @item
-'\' is the escape character
+@samp{\} is the escape character
 @item
-'#' is the comment indicator
+@samp{#} is the comment indicator
 @item
-'=' is the key/value separator
+@samp{=} is the key/value separator
 @item
-':' is not used but usually parsed as key/value separator
+@samp{:} is not used but usually parsed as key/value separator
 @end itemize
 
 This writer accepts options as a list of @var{key}=@var{value} pairs,
-separated by ":".
+separated by @samp{:}.
 
 The description of the accepted options follows.
 
diff --git a/doc/ffprobe.xsd b/doc/ffprobe.xsd
index 226169e..d745e96 100644
--- a/doc/ffprobe.xsd
+++ b/doc/ffprobe.xsd
@@ -171,6 +171,8 @@
       <!-- video attributes -->
       <xsd:attribute name="width"                type="xsd:int"/>
       <xsd:attribute name="height"               type="xsd:int"/>
+      <xsd:attribute name="coded_width"          type="xsd:int"/>
+      <xsd:attribute name="coded_height"         type="xsd:int"/>
       <xsd:attribute name="has_b_frames"         type="xsd:int"/>
       <xsd:attribute name="sample_aspect_ratio"  type="xsd:string"/>
       <xsd:attribute name="display_aspect_ratio" type="xsd:string"/>
@@ -254,8 +256,6 @@
     <xsd:complexType name="programVersionType">
       <xsd:attribute name="version"          type="xsd:string" use="required"/>
       <xsd:attribute name="copyright"        type="xsd:string" use="required"/>
-      <xsd:attribute name="build_date"       type="xsd:string" use="required"/>
-      <xsd:attribute name="build_time"       type="xsd:string" use="required"/>
       <xsd:attribute name="compiler_ident"   type="xsd:string" use="required"/>
       <xsd:attribute name="configuration"    type="xsd:string" use="required"/>
     </xsd:complexType>
diff --git a/doc/ffserver.texi b/doc/ffserver.texi
index 83b6520..336cec1 100644
--- a/doc/ffserver.texi
+++ b/doc/ffserver.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle ffserver Documentation
 @titlepage
@@ -71,7 +72,7 @@
 configuration file.
 
 Each feed is associated to a file which is stored on disk. This stored
-file is used to allow to send pre-recorded data to a player as fast as
+file is used to send pre-recorded data to a player as fast as
 possible when new content is added in real-time to the stream.
 
 A "live-stream" or "stream" is a resource published by
diff --git a/doc/fftools-common-opts.texi b/doc/fftools-common-opts.texi
index 6556909..2e7c9f7 100644
--- a/doc/fftools-common-opts.texi
+++ b/doc/fftools-common-opts.texi
@@ -50,6 +50,9 @@
 Matches streams with the metadata tag @var{key} having the specified value. If
 @var{value} is not given, matches streams that contain the given tag with any
 value.
+@item u
+Matches streams with usable configuration, the codec must be defined and the
+essential information such as video dimension or audio sample rate must be present.
 
 Note that in @command{ffmpeg}, matching by metadata will only work properly for
 input files.
diff --git a/doc/filters.texi b/doc/filters.texi
index cba2697..f2999f2 100644
--- a/doc/filters.texi
+++ b/doc/filters.texi
@@ -163,13 +163,13 @@
 
 If the option value itself is a list of items (e.g. the @code{format} filter
 takes a list of pixel formats), the items in the list are usually separated by
-'|'.
+@samp{|}.
 
-The list of arguments can be quoted using the character "'" as initial
-and ending mark, and the character '\' for escaping the characters
+The list of arguments can be quoted using the character @samp{'} as initial
+and ending mark, and the character @samp{\} for escaping the characters
 within the quoted text; otherwise the argument string is considered
 terminated when the next special character (belonging to the set
-"[]=;,") is encountered.
+@samp{[]=;,}) is encountered.
 
 The name and arguments of the filter are optionally preceded and
 followed by a list of link labels.
@@ -917,6 +917,7 @@
 A list of Adler-32 checksums for each data plane.
 @end table
 
+@anchor{astats}
 @section astats
 
 Display time domain statistical information about the audio channels.
@@ -1394,6 +1395,24 @@
 @end example
 @end itemize
 
+@section dcshift
+Apply a DC shift to the audio.
+
+This can be useful to remove a DC offset (caused perhaps by a hardware problem
+in the recording chain) from the audio. The effect of a DC offset is reduced
+headroom and hence volume. The @ref{astats} filter can be used to determine if
+a signal has a DC offset.
+
+@table @option
+@item shift
+Set the DC shift, allowed range is [-1, 1]. It indicates the amount to shift
+the audio.
+
+@item limitergain
+Optional. It should have a value much less than 1 (e.g. 0.05 or 0.02) and is
+used to prevent clipping.
+@end table
+
 @section earwax
 
 Make audio easier to listen to on headphones.
@@ -3467,7 +3486,7 @@
 may want to reduce this value, at the cost of a less effective filter and the
 risk of various artefacts.
 
-If the overlapping value doesn't allow to process the whole input width or
+If the overlapping value doesn't permit processing the whole input width or
 height, a warning will be displayed and according borders won't be denoised.
 
 Default value is @var{blocksize}-1, which is the best possible setting.
@@ -4130,7 +4149,7 @@
 If @option{expansion} is set to @code{normal} (which is the default),
 the following expansion mechanism is used.
 
-The backslash character '\', followed by any character, always expands to
+The backslash character @samp{\}, followed by any character, always expands to
 the second character.
 
 Sequence of the form @code{%@{...@}} are expanded. The text between the
@@ -4162,8 +4181,9 @@
 Evaluate the expression's value and output as formatted integer.
 
 The first argument is the expression to be evaluated, just as for the @var{expr} function.
-The second argument specifies the output format. Allowed values are 'x', 'X', 'd' and
-'u'. They are treated exactly as in the printf function.
+The second argument specifies the output format. Allowed values are @samp{x},
+@samp{X}, @samp{d} and @samp{u}. They are treated exactly as in the
+@code{printf} function.
 The third parameter is optional and sets the number of positions taken by the output.
 It can be used to add padding with zeros from the left.
 
@@ -4347,39 +4367,106 @@
 
 @table @option
 @item contrast
-Set the contrast value. It accepts a float value in range @code{-2.0} to
-@code{2.0}. The default value is @code{0.0}.
+Set the contrast expression. The value must be a float value in range
+@code{-2.0} to @code{2.0}. The default value is "0".
 
 @item brightness
-Set the brightness value. It accepts a float value in range @code{-1.0} to
-@code{1.0}. The default value is @code{0.0}.
+Set the brightness expression. The value must be a float value in
+range @code{-1.0} to @code{1.0}. The default value is "0".
 
 @item saturation
-Set the saturation value. It accepts a float value in range @code{0.0} to
-@code{3.0}. The default value is @code{1.0}.
+Set the saturation expression. The value must be a float in
+range @code{0.0} to @code{3.0}. The default value is "1".
 
 @item gamma
-Set the gamma value. It accepts a float value in range @code{0.1} to @code{10.0}.
-The default value is @code{1.0}.
+Set the gamma expression. The value must be a float in range
+@code{0.1} to @code{10.0}.  The default value is "1".
 
 @item gamma_r
-Set the gamma value for red. It accepts a float value in range
-@code{0.1} to @code{10.0}. The default value is @code{1.0}.
+Set the gamma expression for red. The value must be a float in
+range @code{0.1} to @code{10.0}. The default value is "1".
 
 @item gamma_g
-Set the gamma value for green. It accepts a float value in range
-@code{0.1} to @code{10.0}. The default value is @code{1.0}.
+Set the gamma expression for green. The value must be a float in range
+@code{0.1} to @code{10.0}. The default value is "1".
 
 @item gamma_b
-Set the gamma value for blue. It accepts a float value in range
-@code{0.1} to @code{10.0}. The default value is @code{1.0}.
+Set the gamma expression for blue. The value must be a float in range
+@code{0.1} to @code{10.0}. The default value is "1".
 
 @item gamma_weight
-Can be used to reduce the effect of a high gamma value on bright image areas,
-e.g. keep them from getting overamplified and just plain white. It accepts a
-float value in range @code{0.0} to @code{1.0}.A value of @code{0.0} turns the
-gamma correction all the way down while @code{1.0} leaves it at its full strength.
-Default is @code{1.0}.
+Set the gamma weight expression. It can be used to reduce the effect
+of a high gamma value on bright image areas, e.g. keep them from
+getting overamplified and just plain white. The value must be a float
+in range @code{0.0} to @code{1.0}. A value of @code{0.0} turns the
+gamma correction all the way down while @code{1.0} leaves it at its
+full strength. Default is "1".
+
+@item eval
+Set when the expressions for brightness, contrast, saturation and
+gamma expressions are evaluated.
+
+It accepts the following values:
+@table @samp
+@item init
+only evaluate expressions once during the filter initialization or
+when a command is processed
+
+@item frame
+evaluate expressions for each incoming frame
+@end table
+
+Default value is @samp{init}.
+@end table
+
+The expressions accept the following parameters:
+@table @option
+@item n
+frame count of the input frame starting from 0
+
+@item pos
+byte position of the corresponding packet in the input file, NAN if
+unspecified
+
+@item r
+frame rate of the input video, NAN if the input frame rate is unknown
+
+@item t
+timestamp expressed in seconds, NAN if the input timestamp is unknown
+@end table
+
+@subsection Commands
+The filter supports the following commands:
+
+@table @option
+@item contrast
+Set the contrast expression.
+
+@item brightness
+Set the brightness expression.
+
+@item saturation
+Set the saturation expression.
+
+@item gamma
+Set the gamma expression.
+
+@item gamma_r
+Set the gamma_r expression.
+
+@item gamma_g
+Set gamma_g expression.
+
+@item gamma_b
+Set gamma_b expression.
+
+@item gamma_weight
+Set gamma_weight expression.
+
+The command accepts the same syntax of the corresponding option.
+
+If the specified expression is not valid, it is kept at its current
+value.
 
 @end table
 
@@ -4484,7 +4571,8 @@
 fade-in effect the output video will have the same intensity as the input video,
 at the end of the fade-out transition the output video will be filled with the
 selected @option{color}.
-If both duration and nb_frames are specified, duration is used. Default is 0.
+If both duration and nb_frames are specified, duration is used. Default is 0
+(nb_frames is used by default).
 
 @item color, c
 Specify the color of the fade. Default is "black".
@@ -4537,6 +4625,67 @@
 
 @end itemize
 
+@section fftfilt
+Apply arbitrary expressions to samples in frequency domain
+
+@table @option
+@item dc_Y
+Adjust the dc value (gain) of the luma plane of the image. The filter
+accepts an integer value in range @code{0} to @code{1000}. The default
+value is set to @code{0}.
+
+@item dc_U
+Adjust the dc value (gain) of the 1st chroma plane of the image. The
+filter accepts an integer value in range @code{0} to @code{1000}. The
+default value is set to @code{0}.
+
+@item dc_V
+Adjust the dc value (gain) of the 2nd chroma plane of the image. The
+filter accepts an integer value in range @code{0} to @code{1000}. The
+default value is set to @code{0}.
+
+@item weight_Y
+Set the frequency domain weight expression for the luma plane.
+
+@item weight_U
+Set the frequency domain weight expression for the 1st chroma plane.
+
+@item weight_V
+Set the frequency domain weight expression for the 2nd chroma plane.
+
+The filter accepts the following variables:
+@item X
+@item Y
+The coordinates of the current sample.
+
+@item W
+@item H
+The width and height of the image.
+@end table
+
+@subsection Examples
+
+@itemize
+@item
+High-pass:
+@example
+fftfilt=dc_Y=128:weight_Y='squish(1-(Y+X)/100)'
+@end example
+
+@item
+Low-pass:
+@example
+fftfilt=dc_Y=0:weight_Y='squish((Y+X)/100-1)'
+@end example
+
+@item
+Sharpen:
+@example
+fftfilt=dc_Y=0:weight_Y='1+squish(1-(Y+X)/100)'
+@end example
+
+@end itemize
+
 @section field
 
 Extract a single field from an interlaced image using stride
@@ -6263,36 +6412,6 @@
 optimal individual vectors. Default value is 1.
 @end table
 
-@section mp
-
-Apply an MPlayer filter to the input video.
-
-This filter provides a wrapper around some of the filters of
-MPlayer/MEncoder.
-
-This wrapper is considered experimental. Some of the wrapped filters
-may not work properly and we may drop support for them, as they will
-be implemented natively into FFmpeg. Thus you should avoid
-depending on them when writing portable scripts.
-
-The filter accepts the parameters:
-@var{filter_name}[:=]@var{filter_params}
-
-@var{filter_name} is the name of a supported MPlayer filter,
-@var{filter_params} is a string containing the parameters accepted by
-the named filter.
-
-The list of the currently supported filters follows:
-@table @var
-@item softpulldown
-@end table
-
-The parameter syntax and behavior for the listed filters are the same
-of the corresponding MPlayer filters. For detailed instructions check
-the "VIDEO FILTERS" section in the MPlayer manual.
-
-See also mplayer(1), @url{http://www.mplayerhq.hu/}.
-
 @section mpdecimate
 
 Drop frames that do not differ greatly from the previous frame in
@@ -6920,6 +7039,121 @@
 @end example
 @end itemize
 
+@anchor{palettegen}
+@section palettegen
+
+Generate one palette for a whole video stream.
+
+It accepts the following options:
+
+@table @option
+@item max_colors
+Set the maximum number of colors to quantize in the palette.
+Note: the palette will still contain 256 colors; the unused palette entries
+will be black.
+
+@item reserve_transparent
+Create a palette of 255 colors maximum and reserve the last one for
+transparency. Reserving the transparency color is useful for GIF optimization.
+If not set, the maximum of colors in the palette will be 256. You probably want
+to disable this option for a standalone image.
+Set by default.
+
+@item stats_mode
+Set statistics mode.
+
+It accepts the following values:
+@table @samp
+@item full
+Compute full frame histograms.
+@item diff
+Compute histograms only for the part that differs from previous frame. This
+might be relevant to give more importance to the moving part of your input if
+the background is static.
+@end table
+
+Default value is @var{full}.
+@end table
+
+The filter also exports the frame metadata @code{lavfi.color_quant_ratio}
+(@code{nb_color_in / nb_color_out}) which you can use to evaluate the degree of
+color quantization of the palette. This information is also visible at
+@var{info} logging level.
+
+@subsection Examples
+
+@itemize
+@item
+Generate a representative palette of a given video using @command{ffmpeg}:
+@example
+ffmpeg -i input.mkv -vf palettegen palette.png
+@end example
+@end itemize
+
+@section paletteuse
+
+Use a palette to downsample an input video stream.
+
+The filter takes two inputs: one video stream and a palette. The palette must
+be a 256 pixels image.
+
+It accepts the following options:
+
+@table @option
+@item dither
+Select dithering mode. Available algorithms are:
+@table @samp
+@item bayer
+Ordered 8x8 bayer dithering (deterministic)
+@item heckbert
+Dithering as defined by Paul Heckbert in 1982 (simple error diffusion).
+Note: this dithering is sometimes considered "wrong" and is included as a
+reference.
+@item floyd_steinberg
+Floyd and Steingberg dithering (error diffusion)
+@item sierra2
+Frankie Sierra dithering v2 (error diffusion)
+@item sierra2_4a
+Frankie Sierra dithering v2 "Lite" (error diffusion)
+@end table
+
+Default is @var{sierra2_4a}.
+
+@item bayer_scale
+When @var{bayer} dithering is selected, this option defines the scale of the
+pattern (how much the crosshatch pattern is visible). A low value means more
+visible pattern for less banding, and higher value means less visible pattern
+at the cost of more banding.
+
+The option must be an integer value in the range [0,5]. Default is @var{2}.
+
+@item diff_mode
+If set, define the zone to process
+
+@table @samp
+@item rectangle
+Only the changing rectangle will be reprocessed. This is similar to GIF
+cropping/offsetting compression mechanism. This option can be useful for speed
+if only a part of the image is changing, and has use cases such as limiting the
+scope of the error diffusal @option{dither} to the rectangle that bounds the
+moving scene (it leads to more deterministic output if the scene doesn't change
+much, and as a result less moving noise and better GIF compression).
+@end table
+
+Default is @var{none}.
+@end table
+
+@subsection Examples
+
+@itemize
+@item
+Use a palette (generated for example with @ref{palettegen}) to encode a GIF
+using @command{ffmpeg}:
+@example
+ffmpeg -i input.mkv -i palette.png -lavfi paletteuse output.gif
+@end example
+@end itemize
+
 @section perspective
 
 Correct perspective of video not recorded perpendicular to the screen.
@@ -7448,6 +7682,11 @@
 the image and will destroy more information than necessary, and extra
 pixels will slow things down on a large logo.
 
+@section repeatfields
+
+This filter uses the repeat_field flag from the Video ES headers and hard repeats
+fields based on its value.
+
 @section rotate
 
 Rotate video by an arbitrary angle expressed in radians.
@@ -7681,8 +7920,8 @@
 the default flags.
 
 @item size, s
-Set the video size. For the syntax of this option, check the "Video size"
-section in the ffmpeg-utils manual.
+Set the video size. For the syntax of this option, check the
+@ref{video size syntax,,"Video size" section in the ffmpeg-utils manual,ffmpeg-utils}.
 
 @item in_color_matrix
 @item out_color_matrix
@@ -8079,8 +8318,8 @@
 @var{num}/@var{den}.
 
 @item s
-The size of the input frame. For the syntax of this option, check the "Video size"
-section in the ffmpeg-utils manual.
+The size of the input frame. For the syntax of this option, check the
+@ref{video size syntax,,"Video size" section in the ffmpeg-utils manual,ffmpeg-utils}.
 
 @item i
 The type of interlaced mode ("P" for "progressive", "T" for top field first, "B"
@@ -8573,10 +8812,10 @@
 
 @item original_size
 Specify the size of the original video, the video for which the ASS file
-was composed. For the syntax of this option, check the "Video size" section in
-the ffmpeg-utils manual. Due to a misdesign in ASS aspect ratio arithmetic,
-this is necessary to correctly scale the fonts if the aspect ratio has been
-changed.
+was composed. For the syntax of this option, check the
+@ref{video size syntax,,"Video size" section in the ffmpeg-utils manual,ffmpeg-utils}.
+Due to a misdesign in ASS aspect ratio arithmetic, this is necessary to
+correctly scale the fonts if the aspect ratio has been changed.
 
 @item charenc
 Set subtitles input character encoding. @code{subtitles} filter only. Only
@@ -8584,6 +8823,10 @@
 
 @item stream_index, si
 Set subtitles stream index. @code{subtitles} filter only.
+
+@item force_style
+Override default style or script info parameters of the subtitles. It accepts a
+string containing ASS style format @code{KEY=VALUE} couples separated by ",".
 @end table
 
 If the first key is not specified, it is assumed that the first value
@@ -8610,6 +8853,12 @@
 subtitles=video.mkv:si=1
 @end example
 
+To make the subtitles stream from @file{sub.srt} appear in transparent green
+@code{DejaVu Serif}, use:
+@example
+subtitles=sub.srt:force_style='FontName=DejaVu Serif,PrimaryColour=&HAA00FF00'
+@end example
+
 @section super2xsai
 
 Scale the input by 2x and smooth using the Super2xSaI (Scale and
@@ -8700,7 +8949,8 @@
 
 @item layout
 Set the grid size (i.e. the number of lines and columns). For the syntax of
-this option, check the "Video size" section in the ffmpeg-utils manual.
+this option, check the
+@ref{video size syntax,,"Video size" section in the ffmpeg-utils manual,ffmpeg-utils}.
 
 @item nb_frames
 Set the maximum number of frames to render in the given area. It must be less
@@ -9758,8 +10008,8 @@
 
 @item video_size
 Specify the size (width and height) of the buffered video frames. For the
-syntax of this option, check the "Video size" section in the ffmpeg-utils
-manual.
+syntax of this option, check the
+@ref{video size syntax,,"Video size" section in the ffmpeg-utils manual,ffmpeg-utils}.
 
 @item width
 The input video width.
@@ -9859,8 +10109,8 @@
 Default value is 110.
 
 @item size, s
-Set the size of the output video. For the syntax of this option, check
-the "Video size" section in the ffmpeg-utils manual.
+Set the size of the output video. For the syntax of this option, check the
+@ref{video size syntax,,"Video size" section in the ffmpeg-utils manual,ffmpeg-utils}.
 
 If @option{filename} or @option{pattern} is specified, the size is set
 by default to the width of the specified initial state row, and the
@@ -10060,7 +10310,7 @@
 
 @item size
 The size of the video to generate. For the syntax of this option, check the
-"Video size" section in the ffmpeg-utils manual.
+@ref{video size syntax,,"Video size" section in the ffmpeg-utils manual,ffmpeg-utils}.
 
 @item framerate
 The framerate of the generated video. It may be a string of the form
@@ -10149,7 +10399,7 @@
 
 @item size, s
 Set the size of the output video. For the syntax of this option, check the
-"Video size" section in the ffmpeg-utils manual.
+@ref{video size syntax,,"Video size" section in the ffmpeg-utils manual,ffmpeg-utils}.
 
 If @option{filename} is specified, the size is set by default to the
 same size of the input file. If @option{size} is set, it must contain
@@ -10260,8 +10510,8 @@
 
 @item size, s
 Specify the size of the sourced video. For the syntax of this option, check the
-"Video size" section in the ffmpeg-utils manual. The default value is
-"320x240".
+@ref{video size syntax,,"Video size" section in the ffmpeg-utils manual,ffmpeg-utils}.
+The default value is @code{320x240}.
 
 This option is not available with the @code{haldclutsrc} filter.
 
@@ -10387,8 +10637,9 @@
 Default value is @samp{lissajous}.
 
 @item size, s
-Set the video size for the output. For the syntax of this option, check the "Video size"
-section in the ffmpeg-utils manual. Default value is @code{400x400}.
+Set the video size for the output. For the syntax of this option, check the
+@ref{video size syntax,,"Video size" section in the ffmpeg-utils manual,ffmpeg-utils}.
+Default value is @code{400x400}.
 
 @item rate, r
 Set the output frame rate. Default value is @code{25}.
@@ -10528,8 +10779,9 @@
 
 @item size
 Set the video size. This option is for video only. For the syntax of this
-option, check the "Video size" section in the ffmpeg-utils manual. Default
-and minimum resolution is @code{640x480}.
+option, check the
+@ref{video size syntax,,"Video size" section in the ffmpeg-utils manual,ffmpeg-utils}.
+Default and minimum resolution is @code{640x480}.
 
 @item meter
 Set the EBU scale meter. Default is @code{9}. Common values are @code{9} and
@@ -11351,9 +11603,9 @@
 
 @table @option
 @item size, s
-Specify the video size for the output. For the syntax of this option, check
-the "Video size" section in the ffmpeg-utils manual. Default value is
-@code{640x512}.
+Specify the video size for the output. For the syntax of this option, check the
+@ref{video size syntax,,"Video size" section in the ffmpeg-utils manual,ffmpeg-utils}.
+Default value is @code{640x512}.
 
 @item slide
 Specify how the spectrum should slide along the window.
@@ -11465,9 +11717,9 @@
 
 @table @option
 @item size, s
-Specify the video size for the output. For the syntax of this option, check
-the "Video size" section in the ffmpeg-utils manual. Default value
-is "600x240".
+Specify the video size for the output. For the syntax of this option, check the
+@ref{video size syntax,,"Video size" section in the ffmpeg-utils manual,ffmpeg-utils}.
+Default value is @code{600x240}.
 
 @item mode
 Set display mode.
@@ -11522,6 +11774,33 @@
 @end example
 @end itemize
 
+@section showwavespic
+
+Convert input audio to a single video frame, representing the samples waves.
+
+The filter accepts the following options:
+
+@table @option
+@item size, s
+Specify the video size for the output. For the syntax of this option, check the
+@ref{video size syntax,,"Video size" section in the ffmpeg-utils manual,ffmpeg-utils}.
+Default value is @code{600x240}.
+
+@item split_channels
+Set if channels should be drawn separately or overlap. Default value is 0.
+@end table
+
+@subsection Examples
+
+@itemize
+@item
+Extract a channel split representation of the wave form of a whole audio track
+in a 1024x800 picture using @command{ffmpeg}:
+@example
+ffmpeg -i audio.flac -lavfi showwavespic=split_channels=1:s=1024x800 waveform.png
+@end example
+@end itemize
+
 @section split, asplit
 
 Split input into several identical outputs.
diff --git a/doc/formats.texi b/doc/formats.texi
index 4138709..cbbdc10 100644
--- a/doc/formats.texi
+++ b/doc/formats.texi
@@ -23,7 +23,7 @@
 
 @item probesize @var{integer} (@emph{input})
 Set probing size in bytes, i.e. the size of the data to analyze to get
-stream information. A higher value will allow to detect more
+stream information. A higher value will enable detecting more
 information in case it is dispersed into the stream, but will increase
 latency. Must be an integer not lesser than 32. It is 5000000 by default.
 
@@ -67,7 +67,7 @@
 
 @item analyzeduration @var{integer} (@emph{input})
 Specify how many microseconds are analyzed to probe the input. A
-higher value will allow to detect more accurate information, but will
+higher value will enable detecting more accurate information, but will
 increase latency. It defaults to 5,000,000 microseconds = 5 seconds.
 
 @item cryptokey @var{hexadecimal string} (@emph{input})
diff --git a/doc/general.texi b/doc/general.texi
index 49f5ade..a8e4f37 100644
--- a/doc/general.texi
+++ b/doc/general.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle General Documentation
 @titlepage
@@ -251,6 +252,8 @@
     @tab Used in the game Cyberia from Interplay.
 @item Delphine Software International CIN @tab   @tab X
     @tab Multimedia format used by Delphine Software games.
+@item Digital Speech Standard (DSS) @tab   @tab X
+@item Canopus HQX               @tab   @tab X
 @item CD+G                      @tab   @tab X
     @tab Video format used by CD+G karaoke disks
 @item Phantom Cine              @tab   @tab X
@@ -463,6 +466,7 @@
 @item SoX native format         @tab X @tab X
 @item SUN AU format             @tab X @tab X
 @item SUP raw PGS subtitles     @tab   @tab X
+@item TDSC                      @tab   @tab X
 @item Text files                @tab   @tab X
 @item THP                       @tab   @tab X
     @tab Used on the Nintendo GameCube.
@@ -897,10 +901,12 @@
     @tab decoding supported through external library libcelt
 @item Delphine Software International CIN audio  @tab     @tab  X
     @tab Codec used in Delphine Software International games.
+@item Digital Speech Standard - Standard Play mode (DSS SP) @tab     @tab  X
 @item Discworld II BMV Audio @tab     @tab  X
 @item COOK                   @tab     @tab  X
     @tab All versions except 5.1 are supported.
 @item DCA (DTS Coherent Acoustics)  @tab  X  @tab  X
+    @tab supported extensions: XCh, XLL (partially)
 @item DPCM id RoQ            @tab  X  @tab  X
     @tab Used in Quake III, Jedi Knight 2 and other computer games.
 @item DPCM Interplay         @tab     @tab  X
diff --git a/doc/git-howto.texi b/doc/git-howto.texi
index 750662a..8ece341 100644
--- a/doc/git-howto.texi
+++ b/doc/git-howto.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle Using git to develop FFmpeg
 
diff --git a/doc/indevs.texi b/doc/indevs.texi
index ae61331..9818531 100644
--- a/doc/indevs.texi
+++ b/doc/indevs.texi
@@ -1,7 +1,7 @@
 @chapter Input Devices
 @c man begin INPUT DEVICES
 
-Input devices are configured elements in FFmpeg which allow to access
+Input devices are configured elements in FFmpeg which enable accessing
 the data coming from a multimedia device attached to your system.
 
 When you configure your FFmpeg build, all the supported input devices
@@ -150,6 +150,81 @@
 
 BSD video input device.
 
+@section decklink
+
+The decklink input device provides capture capabilities for Blackmagic
+DeckLink devices.
+
+To enable this input device, you need the Blackmagic DeckLink SDK and you
+need to configure with the appropriate @code{--extra-cflags}
+and @code{--extra-ldflags}.
+On Windows, you need to run the IDL files through @command{widl}.
+
+DeckLink is very picky about the formats it supports. Pixel format is
+uyvy422 or v210, framerate and video size must be determined for your device with
+@command{-list_formats 1}. Audio sample rate is always 48 kHz and the number
+of channels can be 2, 8 or 16.
+
+@subsection Options
+
+@table @option
+
+@item list_devices
+If set to @option{true}, print a list of devices and exit.
+Defaults to @option{false}.
+
+@item list_formats
+If set to @option{true}, print a list of supported formats and exit.
+Defaults to @option{false}.
+
+@item bm_v210
+If set to @samp{1}, video is captured in 10 bit v210 instead
+of uyvy422. Not all Blackmagic devices support this option.
+
+@end table
+
+@subsection Examples
+
+@itemize
+
+@item
+List input devices:
+@example
+ffmpeg -f decklink -list_devices 1 -i dummy
+@end example
+
+@item
+List supported formats:
+@example
+ffmpeg -f decklink -list_formats 1 -i 'Intensity Pro'
+@end example
+
+@item
+Capture video clip at 1080i50 (format 11):
+@example
+ffmpeg -f decklink -i 'Intensity Pro@@11' -acodec copy -vcodec copy output.avi
+@end example
+
+@item
+Capture video clip at 1080i50 10 bit:
+@example
+ffmpeg -bm_v210 1 -f decklink -i 'UltraStudio Mini Recorder@@11' -acodec copy -vcodec copy output.avi
+@end example
+
+@item
+Capture video clip at 720p50 with 32bit audio:
+@example
+ffmpeg -bm_audiodepth 32 -f decklink -i 'UltraStudio Mini Recorder@@14' -acodec copy -vcodec copy output.avi
+@end example
+
+@item
+Capture video clip at 576i50 with 8 audio channels:
+@example
+ffmpeg -bm_channels 8 -f decklink -i 'UltraStudio Mini Recorder@@3' -acodec copy -vcodec copy output.avi
+@end example
+
+@end itemize
+
 @section dshow
 
 Windows DirectShow input device.
@@ -627,20 +702,47 @@
 
 @section libcdio
 
-Audio-CD input device based on cdio.
+Audio-CD input device based on libcdio.
 
 To enable this input device during configuration you need libcdio
-installed on your system. Requires the configure option
+installed on your system. It requires the configure option
 @code{--enable-libcdio}.
 
 This device allows playing and grabbing from an Audio-CD.
 
-For example to copy with @command{ffmpeg} the entire Audio-CD in /dev/sr0,
+For example to copy with @command{ffmpeg} the entire Audio-CD in @file{/dev/sr0},
 you may run the command:
 @example
 ffmpeg -f libcdio -i /dev/sr0 cd.wav
 @end example
 
+@subsection Options
+@table @option
+@item speed
+Set drive reading speed. Default value is 0.
+
+The speed is specified CD-ROM speed units. The speed is set through
+the libcdio @code{cdio_cddap_speed_set} function. On many CD-ROM
+drives, specifying a value too large will result in using the fastest
+speed.
+
+@item paranoia_mode
+Set paranoia recovery mode flags. It accepts one of the following values:
+
+@table @samp
+@item disable
+@item verify
+@item overlap
+@item neverskip
+@item full
+@end table
+
+Default value is @samp{disable}.
+
+For more information about the available recovery modes, consult the
+paranoia project documentation.
+@end table
+
 @section libdc1394
 
 IIDC1394 input device, based on libdc1394 and libraw1394.
@@ -878,6 +980,12 @@
 and @command{ffplay}:
 @itemize
 @item
+List supported formats for a video4linux2 device:
+@example
+ffplay -f video4linux2 -list_formats all /dev/video0
+@end example
+
+@item
 Grab and show the input of a video4linux2 device:
 @example
 ffplay -f video4linux2 -framerate 30 -video_size hd720 /dev/video0
@@ -975,8 +1083,12 @@
 
 X11 video input device.
 
-Depends on X11, Xext, and Xfixes. Requires the configure option
-@code{--enable-x11grab}.
+To enable this input device during configuration you need libxcb
+installed on your system. It will be automatically detected during
+configuration.
+
+Alternatively, the configure option @option{--enable-x11grab} exists
+for legacy Xlib users.
 
 This device allows one to capture a region of an X11 display.
 
@@ -994,10 +1106,12 @@
 area with respect to the top-left border of the X11 screen. They
 default to 0.
 
-Check the X11 documentation (e.g. man X) for more detailed information.
+Check the X11 documentation (e.g. @command{man X}) for more detailed
+information.
 
-Use the @command{dpyinfo} program for getting basic information about the
-properties of your X11 display (e.g. grep for "name" or "dimensions").
+Use the @command{xdpyinfo} program for getting basic information about
+the properties of your X11 display (e.g. grep for "name" or
+"dimensions").
 
 For example to grab from @file{:0.0} using @command{ffmpeg}:
 @example
@@ -1046,6 +1160,10 @@
 region will be indicated on screen. With this option, it is easy to
 know what is being grabbed if only a portion of the screen is grabbed.
 
+@item region_border
+Set the region border thickness if @option{-show_region 1} is used.
+Range is 1 to 128 and default is 3 (XCB-based x11grab only).
+
 For example:
 @example
 ffmpeg -f x11grab -show_region 1 -framerate 25 -video_size cif -i :0.0+10,20 out.mpg
@@ -1061,61 +1179,19 @@
 
 @item use_shm
 Use the MIT-SHM extension for shared memory. Default value is @code{1}.
-It may be necessary to disable it for remote displays.
+It may be necessary to disable it for remote displays (legacy x11grab
+only).
 @end table
 
-@section decklink
+@subsection @var{grab_x} @var{grab_y} AVOption
 
-The decklink input device provides capture capabilities for Blackmagic
-DeckLink devices.
-
-To enable this input device, you need the Blackmagic DeckLink SDK and you
-need to configure with the appropriate @code{--extra-cflags}
-and @code{--extra-ldflags}.
-On Windows, you need to run the IDL files through @command{widl}.
-
-DeckLink is very picky about the formats it supports. Pixel format is always
-uyvy422, framerate and video size must be determined for your device with
-@command{-list_formats 1}. Audio sample rate is always 48 kHz and the number
-of channels currently is limited to 2 (stereo).
-
-@subsection Options
-
-@table @option
-
-@item list_devices
-If set to @option{true}, print a list of devices and exit.
-Defaults to @option{false}.
-
-@item list_formats
-If set to @option{true}, print a list of supported formats and exit.
-Defaults to @option{false}.
-
-@end table
-
-@subsection Examples
-
-@itemize
-
-@item
-List input devices:
+The syntax is:
 @example
-ffmpeg -f decklink -list_devices 1 -i dummy
+-grab_x @var{x_offset} -grab_y @var{y_offset}
 @end example
 
-@item
-List supported formats:
-@example
-ffmpeg -f decklink -list_formats 1 -i 'Intensity Pro'
-@end example
-
-@item
-Capture video clip at 1080i50 (format 11):
-@example
-ffmpeg -f decklink -i 'Intensity Pro@@11' -acodec copy -vcodec copy output.avi
-@end example
-
-@end itemize
+Set the grabbing region coordinates. They are expressed as offset from the top left
+corner of the X11 window. The default value is 0.
 
 
 @c man end INPUT DEVICES
diff --git a/doc/libavcodec.texi b/doc/libavcodec.texi
index 618f9f6..87b90db 100644
--- a/doc/libavcodec.texi
+++ b/doc/libavcodec.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle Libavcodec Documentation
 @titlepage
diff --git a/doc/libavdevice.texi b/doc/libavdevice.texi
index d5f790b..9b10282 100644
--- a/doc/libavdevice.texi
+++ b/doc/libavdevice.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle Libavdevice Documentation
 @titlepage
diff --git a/doc/libavfilter.texi b/doc/libavfilter.texi
index 4f82944..52e0753 100644
--- a/doc/libavfilter.texi
+++ b/doc/libavfilter.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle Libavfilter Documentation
 @titlepage
diff --git a/doc/libavformat.texi b/doc/libavformat.texi
index 85e49cb..d505d64 100644
--- a/doc/libavformat.texi
+++ b/doc/libavformat.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle Libavformat Documentation
 @titlepage
diff --git a/doc/libavutil.texi b/doc/libavutil.texi
index 5ec7e84..7a1c332 100644
--- a/doc/libavutil.texi
+++ b/doc/libavutil.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle Libavutil Documentation
 @titlepage
diff --git a/doc/libswresample.texi b/doc/libswresample.texi
index 383e537..bb57278 100644
--- a/doc/libswresample.texi
+++ b/doc/libswresample.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle Libswresample Documentation
 @titlepage
diff --git a/doc/libswscale.texi b/doc/libswscale.texi
index 818e988..757fd24 100644
--- a/doc/libswscale.texi
+++ b/doc/libswscale.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle Libswscale Documentation
 @titlepage
diff --git a/doc/metadata.texi b/doc/metadata.texi
index b7fc789..bddcc99 100644
--- a/doc/metadata.texi
+++ b/doc/metadata.texi
@@ -12,10 +12,10 @@
 each on its own line.
 
 @item
-The header is a ';FFMETADATA' string, followed by a version number (now 1).
+The header is a @samp{;FFMETADATA} string, followed by a version number (now 1).
 
 @item
-Metadata tags are of the form 'key=value'
+Metadata tags are of the form @samp{key=value}
 
 @item
 Immediately after header follows global metadata
@@ -26,26 +26,30 @@
 
 @item
 A section starts with the section name in uppercase (i.e. STREAM or CHAPTER) in
-brackets ('[', ']') and ends with next section or end of file.
+brackets (@samp{[}, @samp{]}) and ends with next section or end of file.
 
 @item
 At the beginning of a chapter section there may be an optional timebase to be
-used for start/end values. It must be in form 'TIMEBASE=num/den', where num and
-den are integers. If the timebase is missing then start/end times are assumed to
+used for start/end values. It must be in form
+@samp{TIMEBASE=@var{num}/@var{den}}, where @var{num} and @var{den} are
+integers. If the timebase is missing then start/end times are assumed to
 be in milliseconds.
+
 Next a chapter section must contain chapter start and end times in form
-'START=num', 'END=num', where num is a positive integer.
+@samp{START=@var{num}}, @samp{END=@var{num}}, where @var{num} is a positive
+integer.
 
 @item
-Empty lines and lines starting with ';' or '#' are ignored.
+Empty lines and lines starting with @samp{;} or @samp{#} are ignored.
 
 @item
-Metadata keys or values containing special characters ('=', ';', '#', '\' and a
-newline) must be escaped with a backslash '\'.
+Metadata keys or values containing special characters (@samp{=}, @samp{;},
+@samp{#}, @samp{\} and a newline) must be escaped with a backslash @samp{\}.
 
 @item
-Note that whitespace in metadata (e.g. foo = bar) is considered to be a part of
-the tag (in the example above key is 'foo ', value is ' bar').
+Note that whitespace in metadata (e.g. @samp{foo = bar}) is considered to be
+a part of the tag (in the example above key is @samp{foo }, value is
+@samp{ bar}).
 @end enumerate
 
 A ffmetadata file might look like this:
diff --git a/doc/muxers.texi b/doc/muxers.texi
index e356235..a8225fc 100644
--- a/doc/muxers.texi
+++ b/doc/muxers.texi
@@ -381,8 +381,7 @@
 
 @table @option
 @item start_number
-Start the sequence from the specified number. Default value is 1. Must
-be a non-negative number.
+Start the sequence from the specified number. Default value is 0.
 
 @item update
 If set to 1, the filename will always be interpreted as just a
@@ -690,6 +689,9 @@
 transponder in DVB.
 @item -mpegts_service_id @var{number}
 Set the service_id (default 0x0001) also known as program in DVB.
+@item -mpegts_service_type @var{number}
+Set the program service_type (default @var{digital_tv}), see below
+a list of pre defined values.
 @item -mpegts_pmt_start_pid @var{number}
 Set the first PID for PMT (default 0x1000, max 0x1f00).
 @item -mpegts_start_pid @var{number}
@@ -724,6 +726,27 @@
 @end example
 @end table
 
+Option mpegts_service_type accepts the following values:
+
+@table @option
+@item hex_value
+Any hexdecimal value between 0x01 to 0xff as defined in ETSI 300 468.
+@item digital_tv
+Digital TV service.
+@item digital_radio
+Digital Radio service.
+@item teletext
+Teletext service.
+@item advanced_codec_digital_radio
+Advanced Codec Digital Radio service.
+@item mpeg2_digital_hdtv
+MPEG2 Digital HDTV service.
+@item advanced_codec_digital_sdtv
+Advanced Codec Digital SDTV service.
+@item advanced_codec_digital_hdtv
+Advanced Codec Digital HDTV service.
+@end table
+
 Option mpegts_flags may take a set of such flags:
 
 @table @option
@@ -806,6 +829,11 @@
 possible. A value of 1 will effectively use 1 packet-per-page in most
 situations, giving a small seek granularity at the cost of additional container
 overhead.
+@item -serial_offset @var{value}
+Serial value from which to set the streams serial number.
+Setting it to different and sufficiently large values ensures that the produced
+ogg files can be safely chained.
+
 @end table
 
 @anchor{segment}
@@ -814,8 +842,9 @@
 Basic stream segmenter.
 
 This muxer outputs streams to a number of separate files of nearly
-fixed duration. Output filename pattern can be set in a fashion similar to
-@ref{image2}.
+fixed duration. Output filename pattern can be set in a fashion
+similar to @ref{image2}, or by using a @code{strftime} template if
+the @option{strftime} option is enabled.
 
 @code{stream_segment} is a variant of the muxer used to write to
 streaming output formats, i.e. which do not require global headers,
@@ -995,6 +1024,12 @@
 @item segment_start_number @var{number}
 Set the sequence number of the first segment. Defaults to @code{0}.
 
+@item strftime @var{1|0}
+Use the @code{strftime} function to define the name of the new
+segments to write. If this is selected, the output segment name must
+contain a @code{strftime} function template. Default value is
+@code{0}.
+
 @item reset_timestamps @var{1|0}
 Reset timestamps at the begin of each segment, so that each segment
 will start with near-zero timestamps. It is meant to ease the playback
diff --git a/doc/nut.texi b/doc/nut.texi
index fee12da..a02f86a 100644
--- a/doc/nut.texi
+++ b/doc/nut.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle NUT
 
diff --git a/doc/optimization.txt b/doc/optimization.txt
index 94a4277..1a0b98c 100644
--- a/doc/optimization.txt
+++ b/doc/optimization.txt
@@ -191,6 +191,11 @@
 Use external asm (nasm/yasm) or inline asm (__asm__()), do not use intrinsics.
 The latter requires a good optimizing compiler which gcc is not.
 
+When debugging a x86 external asm compilation issue, if lost in the macro
+expansions, add DBG=1 to your make command-line: the input file will be
+preprocessed, stripped of the debug/empty lines, then compiled, showing the
+actual lines causing issues.
+
 Inline asm vs. external asm
 ---------------------------
 Both inline asm (__asm__("..") in a .c file, handled by a compiler such as gcc)
diff --git a/doc/platform.texi b/doc/platform.texi
index a852170..705a680 100644
--- a/doc/platform.texi
+++ b/doc/platform.texi
@@ -1,4 +1,5 @@
 \input texinfo @c -*- texinfo -*-
+@documentencoding UTF-8
 
 @settitle Platform Specific Information
 @titlepage
@@ -136,8 +137,6 @@
 @item @uref{http://msys2.github.io/, MSYS2}
 @item @uref{http://yasm.tortall.net/, YASM}
 (Also available via MSYS2's package manager.)
-@item @uref{http://gnuwin32.sourceforge.net/packages/bc.htm, bc for Windows} if
-you want to run @uref{fate.html, FATE}.
 @end itemize
 
 To set up a proper environment in MSYS2, you need to run @code{msys_shell.bat} from
@@ -284,7 +283,7 @@
 
 In order to run FATE you will also need the following "Utils" packages:
 @example
-bc, diffutils
+diffutils
 @end example
 
 If you want to build FFmpeg with additional libraries, download Cygwin
diff --git a/doc/protocols.texi b/doc/protocols.texi
index d165bda..2a19b41 100644
--- a/doc/protocols.texi
+++ b/doc/protocols.texi
@@ -63,7 +63,7 @@
 
 Physical concatenation protocol.
 
-Allow to read and seek from many resource in sequence as if they were
+Read and seek from many resources in sequence as if they were
 a unique resource.
 
 A URL accepted by this protocol has the syntax:
@@ -117,7 +117,7 @@
 
 File access protocol.
 
-Allow to read from or write to a file.
+Read from or write to a file.
 
 A file URL can have the form:
 @example
@@ -155,7 +155,7 @@
 
 FTP (File Transfer Protocol).
 
-Allow to read from or write to remote resources using FTP protocol.
+Read from or write to remote resources using FTP protocol.
 
 Following syntax is required.
 @example
@@ -374,7 +374,7 @@
 
 UNIX pipe access protocol.
 
-Allow to read and write from UNIX pipes.
+Read and write from UNIX pipes.
 
 The accepted syntax is:
 @example
@@ -614,7 +614,7 @@
 
 Secure File Transfer Protocol via libssh
 
-Allow to read from or write to remote resources using SFTP protocol.
+Read from or write to remote resources using SFTP protocol.
 
 Following syntax is required.
 
@@ -1055,7 +1055,9 @@
 @end example
 
 Play an AVI file directly from a TAR archive:
+@example
 subfile,,start,183241728,end,366490624,,:archive.tar
+@end example
 
 @section tcp
 
@@ -1081,8 +1083,8 @@
 This option is only relevant in read mode: if no data arrived in more
 than this time interval, raise error.
 
-@item listen_timeout=@var{microseconds}
-Set listen timeout, expressed in microseconds.
+@item listen_timeout=@var{milliseconds}
+Set listen timeout, expressed in milliseconds.
 @end table
 
 The following example shows how to setup a listening TCP connection
diff --git a/doc/t2h.pm b/doc/t2h.pm
new file mode 100644
index 0000000..5efb2da
--- /dev/null
+++ b/doc/t2h.pm
@@ -0,0 +1,339 @@
+# makeinfo HTML output init file
+#
+# Copyright (c) 2011, 2012 Free Software Foundation, Inc.
+# Copyright (c) 2014 Andreas Cadhalpun
+# Copyright (c) 2014 Tiancheng "Timothy" Gu
+#
+# 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 3 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
+
+# no navigation elements
+set_from_init_file('HEADERS', 0);
+
+sub ffmpeg_heading_command($$$$$)
+{
+    my $self = shift;
+    my $cmdname = shift;
+    my $command = shift;
+    my $args = shift;
+    my $content = shift;
+
+    my $result = '';
+
+    # not clear that it may really happen
+    if ($self->in_string) {
+        $result .= $self->command_string($command) ."\n" if ($cmdname ne 'node');
+        $result .= $content if (defined($content));
+        return $result;
+    }
+
+    my $element_id = $self->command_id($command);
+    $result .= "<a name=\"$element_id\"></a>\n"
+        if (defined($element_id) and $element_id ne '');
+
+    print STDERR "Process $command "
+        .Texinfo::Structuring::_print_root_command_texi($command)."\n"
+            if ($self->get_conf('DEBUG'));
+    my $element;
+    if ($Texinfo::Common::root_commands{$command->{'cmdname'}}
+        and $command->{'parent'}
+        and $command->{'parent'}->{'type'}
+        and $command->{'parent'}->{'type'} eq 'element') {
+        $element = $command->{'parent'};
+    }
+    if ($element) {
+        $result .= &{$self->{'format_element_header'}}($self, $cmdname,
+                                                       $command, $element);
+    }
+
+    my $heading_level;
+    # node is used as heading if there is nothing else.
+    if ($cmdname eq 'node') {
+        if (!$element or (!$element->{'extra'}->{'section'}
+            and $element->{'extra'}->{'node'}
+            and $element->{'extra'}->{'node'} eq $command
+             # bogus node may not have been normalized
+            and defined($command->{'extra'}->{'normalized'}))) {
+            if ($command->{'extra'}->{'normalized'} eq 'Top') {
+                $heading_level = 0;
+            } else {
+                $heading_level = 3;
+            }
+        }
+    } else {
+        $heading_level = $command->{'level'};
+    }
+
+    my $heading = $self->command_text($command);
+    # $heading not defined may happen if the command is a @node, for example
+    # if there is an error in the node.
+    if (defined($heading) and $heading ne '' and defined($heading_level)) {
+
+        if ($Texinfo::Common::root_commands{$cmdname}
+            and $Texinfo::Common::sectioning_commands{$cmdname}) {
+            my $content_href = $self->command_contents_href($command, 'contents',
+                                                            $self->{'current_filename'});
+            if ($content_href) {
+                my $this_href = $content_href =~ s/^\#toc-/\#/r;
+                $heading .= '<span class="pull-right">'.
+                              '<a class="anchor hidden-xs" '.
+                                 "href=\"$this_href\" aria-hidden=\"true\">".
+            ($ENV{"FA_ICONS"} ? '<i class="fa fa-link"></i>'
+                              : '#').
+                              '</a> '.
+                              '<a class="anchor hidden-xs"'.
+                                 "href=\"$content_href\" aria-hidden=\"true\">".
+            ($ENV{"FA_ICONS"} ? '<i class="fa fa-navicon"></i>'
+                              : 'TOC').
+                              '</a>'.
+                            '</span>';
+            }
+        }
+
+        if ($self->in_preformatted()) {
+            $result .= $heading."\n";
+        } else {
+            # if the level was changed, set the command name right
+            if ($cmdname ne 'node'
+                and $heading_level ne $Texinfo::Common::command_structuring_level{$cmdname}) {
+                $cmdname
+                    = $Texinfo::Common::level_to_structuring_command{$cmdname}->[$heading_level];
+            }
+            $result .= &{$self->{'format_heading_text'}}(
+                        $self, $cmdname, $heading,
+                        $heading_level +
+                        $self->get_conf('CHAPTER_HEADER_LEVEL') - 1, $command);
+        }
+    }
+    $result .= $content if (defined($content));
+    return $result;
+}
+
+foreach my $command (keys(%Texinfo::Common::sectioning_commands), 'node') {
+    texinfo_register_command_formatting($command, \&ffmpeg_heading_command);
+}
+
+# print the TOC where @contents is used
+set_from_init_file('INLINE_CONTENTS', 1);
+
+# make chapters <h2>
+set_from_init_file('CHAPTER_HEADER_LEVEL', 2);
+
+# Do not add <hr>
+set_from_init_file('DEFAULT_RULE', '');
+set_from_init_file('BIG_RULE', '');
+
+# Customized file beginning
+sub ffmpeg_begin_file($$$)
+{
+    my $self = shift;
+    my $filename = shift;
+    my $element = shift;
+
+    my $command;
+    if ($element and $self->get_conf('SPLIT')) {
+        $command = $self->element_command($element);
+    }
+
+    my ($title, $description, $encoding, $date, $css_lines,
+        $doctype, $bodytext, $copying_comment, $after_body_open,
+        $extra_head, $program_and_version, $program_homepage,
+        $program, $generator) = $self->_file_header_informations($command);
+
+    my $links = $self->_get_links ($filename, $element);
+
+    my $head1 = $ENV{"FFMPEG_HEADER1"} || <<EOT;
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<html>
+<!-- Created by $program_and_version, $program_homepage -->
+  <head>
+    <meta charset="utf-8">
+    <title>
+EOT
+    my $head_title = <<EOT;
+      $title
+EOT
+
+    my $head2 = $ENV{"FFMPEG_HEADER2"} || <<EOT;
+    </title>
+    <meta name="viewport" content="width=device-width,initial-scale=1.0">
+    <link rel="stylesheet" type="text/css" href="bootstrap.min.css">
+    <link rel="stylesheet" type="text/css" href="style.min.css">
+  </head>
+  <body>
+    <div style="width: 95%; margin: auto">
+      <h1>
+EOT
+
+    my $head3 = $ENV{"FFMPEG_HEADER3"} || <<EOT;
+      </h1>
+EOT
+
+    return $head1 . $head_title . $head2 . $head_title . $head3;
+}
+texinfo_register_formatting_function('begin_file', \&ffmpeg_begin_file);
+
+sub ffmpeg_program_string($)
+{
+  my $self = shift;
+  if (defined($self->get_conf('PROGRAM'))
+      and $self->get_conf('PROGRAM') ne ''
+      and defined($self->get_conf('PACKAGE_URL'))) {
+    return $self->convert_tree(
+      $self->gdt('This document was generated using @uref{{program_homepage}, @emph{{program}}}.',
+         { 'program_homepage' => $self->get_conf('PACKAGE_URL'),
+           'program' => $self->get_conf('PROGRAM') }));
+  } else {
+    return $self->convert_tree(
+      $self->gdt('This document was generated automatically.'));
+  }
+}
+texinfo_register_formatting_function('program_string', \&ffmpeg_program_string);
+
+# Customized file ending
+sub ffmpeg_end_file($)
+{
+    my $self = shift;
+    my $program_string = &{$self->{'format_program_string'}}($self);
+    my $program_text = <<EOT;
+      <p style="font-size: small;">
+        $program_string
+      </p>
+EOT
+    my $footer = $ENV{FFMPEG_FOOTER} || <<EOT;
+    </div>
+  </body>
+</html>
+EOT
+    return $program_text . $footer;
+}
+texinfo_register_formatting_function('end_file', \&ffmpeg_end_file);
+
+# Dummy title command
+# Ignore title. Title is handled through ffmpeg_begin_file().
+set_from_init_file('USE_TITLEPAGE_FOR_TITLE', 1);
+sub ffmpeg_title($$$$)
+{
+    return '';
+}
+
+texinfo_register_command_formatting('titlefont',
+                                    \&ffmpeg_title);
+
+# Customized float command. Part of code borrowed from GNU Texinfo.
+sub ffmpeg_float($$$$$)
+{
+    my $self = shift;
+    my $cmdname = shift;
+    my $command = shift;
+    my $args = shift;
+    my $content = shift;
+
+    my ($caption, $prepended) = Texinfo::Common::float_name_caption($self,
+                                                                $command);
+    my $caption_text = '';
+    my $prepended_text;
+    my $prepended_save = '';
+
+    if ($self->in_string()) {
+        if ($prepended) {
+            $prepended_text = $self->convert_tree_new_formatting_context(
+                $prepended, 'float prepended');
+        } else {
+            $prepended_text = '';
+        }
+        if ($caption) {
+            $caption_text = $self->convert_tree_new_formatting_context(
+                {'contents' => $caption->{'args'}->[0]->{'contents'}},
+                'float caption');
+        }
+        return $prepended.$content.$caption_text;
+    }
+
+    my $id = $self->command_id($command);
+    my $label;
+    if (defined($id) and $id ne '') {
+        $label = "<a name=\"$id\"></a>";
+    } else {
+        $label = '';
+    }
+
+    if ($prepended) {
+        if ($caption) {
+            # prepend the prepended tree to the first paragraph
+            my @caption_original_contents = @{$caption->{'args'}->[0]->{'contents'}};
+            my @caption_contents;
+            my $new_paragraph;
+            while (@caption_original_contents) {
+                my $content = shift @caption_original_contents;
+                if ($content->{'type'} and $content->{'type'} eq 'paragraph') {
+                    %{$new_paragraph} = %{$content};
+                    $new_paragraph->{'contents'} = [@{$content->{'contents'}}];
+                    unshift (@{$new_paragraph->{'contents'}}, {'cmdname' => 'strong',
+                             'args' => [{'type' => 'brace_command_arg',
+                                                    'contents' => [$prepended]}]});
+                    push @caption_contents, $new_paragraph;
+                    last;
+                } else {
+                    push @caption_contents, $content;
+                }
+            }
+            push @caption_contents, @caption_original_contents;
+            if ($new_paragraph) {
+                $caption_text = $self->convert_tree_new_formatting_context(
+                 {'contents' => \@caption_contents}, 'float caption');
+                $prepended_text = '';
+            }
+        }
+        if ($caption_text eq '') {
+            $prepended_text = $self->convert_tree_new_formatting_context(
+                $prepended, 'float prepended');
+            if ($prepended_text ne '') {
+                $prepended_save = $prepended_text;
+                $prepended_text = '<p><strong>'.$prepended_text.'</strong></p>';
+            }
+        }
+    } else {
+        $prepended_text = '';
+    }
+
+    if ($caption and $caption_text eq '') {
+        $caption_text = $self->convert_tree_new_formatting_context(
+            $caption->{'args'}->[0], 'float caption');
+    }
+    if ($prepended_text.$caption_text ne '') {
+        $prepended_text = $self->_attribute_class('div','float-caption'). '>'
+                . $prepended_text;
+        $caption_text .= '</div>';
+    }
+    my $html_class = '';
+    if ($prepended_save =~ /NOTE/) {
+        $html_class = 'info';
+        $prepended_text = '';
+        $caption_text   = '';
+    } elsif ($prepended_save =~ /IMPORTANT/) {
+        $html_class = 'warning';
+        $prepended_text = '';
+        $caption_text   = '';
+    }
+    return $self->_attribute_class('div', $html_class). '>' . "\n" .
+        $prepended_text . $caption_text . $content . '</div>';
+}
+
+texinfo_register_command_formatting('float',
+                                    \&ffmpeg_float);
+
+1;
diff --git a/doc/utils.texi b/doc/utils.texi
index b0455af..6517ac0 100644
--- a/doc/utils.texi
+++ b/doc/utils.texi
@@ -12,17 +12,17 @@
 
 @itemize
 @item
-@code{'} and @code{\} are special characters (respectively used for
+@samp{'} and @samp{\} 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 '\'.
+A special character is escaped by prefixing it with a @samp{\}.
 
 @item
-All characters enclosed between '' are included literally in the
-parsed string. The quote character @code{'} itself cannot be quoted,
+All characters enclosed between @samp{''} are included literally in the
+parsed string. The quote character @samp{'} itself cannot be quoted,
 so you may need to close the quote and escape it.
 
 @item
@@ -71,7 +71,7 @@
 @end example
 
 @item
-To include a literal @code{\} you can use either escaping or quoting:
+To include a literal @samp{\} you can use either escaping or quoting:
 @example
 'c:\foo' can be written as c:\\foo
 @end example
@@ -844,7 +844,7 @@
 Return 1.0 if @var{x} is NAN, 0.0 otherwise.
 
 @item ld(var)
-Allow to load the value of the internal variable with number
+Load the value of the internal variable with number
 @var{var}, which was previously stored with st(@var{var}, @var{expr}).
 The function returns the loaded value.
 
@@ -912,7 +912,7 @@
 Compute expression @code{1/(1 + exp(4*x))}.
 
 @item st(var, expr)
-Allow to store the value of the expression @var{expr} in an internal
+Store the value of the expression @var{expr} in an internal
 variable. @var{var} specifies the number of the variable where to
 store the value, and it is a value ranging from 0 to 9. The function
 returns the value stored in the internal variable.
diff --git a/ffmpeg.c b/ffmpeg.c
index b836448..67ce1f3 100644
--- a/ffmpeg.c
+++ b/ffmpeg.c
@@ -62,8 +62,6 @@
 #include "libavutil/threadmessage.h"
 #include "libavformat/os_support.h"
 
-#include "libavformat/ffm.h" // not public API
-
 # include "libavfilter/avcodec.h"
 # include "libavfilter/avfilter.h"
 # include "libavfilter/buffersrc.h"
@@ -155,8 +153,9 @@
 static int restore_tty;
 #endif
 
+#if HAVE_PTHREADS
 static void free_input_threads(void);
-
+#endif
 
 /* sub2video hack:
    Convert subtitles to video with alpha to insert them in filter graphs.
@@ -963,7 +962,9 @@
         }
     case VSYNC_CFR:
         // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
-        if (delta < -1.1)
+        if (frame_drop_threshold && delta < frame_drop_threshold && ost->frame_number) {
+            nb_frames = 0;
+        } else if (delta < -1.1)
             nb_frames = 0;
         else if (delta > 1.1) {
             nb_frames = lrintf(delta);
@@ -1181,8 +1182,8 @@
     enc = ost->enc_ctx;
     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
         frame_number = ost->st->nb_frames;
-        fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
-        if (enc->flags&CODEC_FLAG_PSNR)
+        fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame ? enc->coded_frame->quality / (float)FF_QP2LAMBDA : 0);
+        if (enc->coded_frame && (enc->flags&CODEC_FLAG_PSNR))
             fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
 
         fprintf(vstats_file,"f_size= %6d ", frame_size);
@@ -1195,7 +1196,7 @@
         avg_bitrate = (double)(ost->data_size * 8) / ti1 / 1000.0;
         fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
                (double)ost->data_size / 1024, ti1, bitrate, avg_bitrate);
-        fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
+        fprintf(vstats_file, "type= %c\n", enc->coded_frame ? av_get_picture_type_char(enc->coded_frame->pict_type) : 'I');
     }
 }
 
@@ -1527,8 +1528,8 @@
             nb_frames_drop += ost->last_droped;
     }
 
-    secs = pts / AV_TIME_BASE;
-    us = pts % AV_TIME_BASE;
+    secs = FFABS(pts) / AV_TIME_BASE;
+    us = FFABS(pts) % AV_TIME_BASE;
     mins = secs / 60;
     secs %= 60;
     hours = mins / 60;
@@ -1540,6 +1541,8 @@
                                  "size=N/A time=");
     else                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
                                  "size=%8.0fkB time=", total_size / 1024.0);
+    if (pts < 0)
+        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "-");
     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
              "%02d:%02d:%02d.%02d ", hours, mins, secs,
              (100 * us) / AV_TIME_BASE);
@@ -2357,7 +2360,7 @@
                        "%s hwaccel requested for input stream #%d:%d, "
                        "but cannot be initialized.\n", hwaccel->name,
                        ist->file_index, ist->st->index);
-                exit_program(1);
+                return AV_PIX_FMT_NONE;
             }
             continue;
         }
@@ -2844,6 +2847,7 @@
                     int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
                     ost->frame_rate = ost->enc->supported_framerates[idx];
                 }
+                // reduce frame rate for mpeg4 to be within the spec limits
                 if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) {
                     av_reduce(&ost->frame_rate.num, &ost->frame_rate.den,
                               ost->frame_rate.num, ost->frame_rate.den, 65535);
@@ -3353,6 +3357,7 @@
 static void *input_thread(void *arg)
 {
     InputFile *f = arg;
+    unsigned flags = f->non_blocking ? AV_THREAD_MESSAGE_NONBLOCK : 0;
     int ret = 0;
 
     while (1) {
@@ -3368,7 +3373,15 @@
             break;
         }
         av_dup_packet(&pkt);
-        ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, 0);
+        ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
+        if (flags && ret == AVERROR(EAGAIN)) {
+            flags = 0;
+            ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
+            av_log(f->ctx, AV_LOG_WARNING,
+                   "Thread message queue blocking; consider raising the "
+                   "thread_queue_size option (current value: %d)\n",
+                   f->thread_queue_size);
+        }
         if (ret < 0) {
             if (ret != AVERROR_EOF)
                 av_log(f->ctx, AV_LOG_ERROR,
@@ -3417,7 +3430,7 @@
             strcmp(f->ctx->iformat->name, "lavfi"))
             f->non_blocking = 1;
         ret = av_thread_message_queue_alloc(&f->in_thread_queue,
-                                            8, sizeof(AVPacket));
+                                            f->thread_queue_size, sizeof(AVPacket));
         if (ret < 0)
             return ret;
 
@@ -3840,11 +3853,15 @@
 
         ret = transcode_step();
         if (ret < 0) {
-            if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
+            if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN)) {
                 continue;
+            } else {
+                char errbuf[128];
+                av_strerror(ret, errbuf, sizeof(errbuf));
 
-            av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
-            break;
+                av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
+                break;
+            }
         }
 
         /* dump report by using the output first video and audio streams */
diff --git a/ffmpeg.h b/ffmpeg.h
index cb425b3..7c0c22c 100644
--- a/ffmpeg.h
+++ b/ffmpeg.h
@@ -111,6 +111,7 @@
     int64_t input_ts_offset;
     int rate_emu;
     int accurate_seek;
+    int thread_queue_size;
 
     SpecifierOpt *ts_scale;
     int        nb_ts_scale;
@@ -350,6 +351,7 @@
     pthread_t thread;           /* thread reading from this file */
     int non_blocking;           /* reading packets from the thread should not block */
     int joined;                 /* the thread has been joined */
+    int thread_queue_size;      /* maximum number of queued packets */
 #endif
 } InputFile;
 
@@ -482,6 +484,7 @@
 extern int audio_volume;
 extern int audio_sync_method;
 extern int video_sync_method;
+extern float frame_drop_threshold;
 extern int do_benchmark;
 extern int do_benchmark_all;
 extern int do_deinterlace;
diff --git a/ffmpeg_opt.c b/ffmpeg_opt.c
index c5e3896..39c5f49 100644
--- a/ffmpeg_opt.c
+++ b/ffmpeg_opt.c
@@ -86,6 +86,7 @@
 int audio_volume      = 256;
 int audio_sync_method = 0;
 int video_sync_method = VSYNC_AUTO;
+float frame_drop_threshold = 0;
 int do_deinterlace    = 0;
 int do_benchmark      = 0;
 int do_benchmark_all  = 0;
@@ -858,6 +859,7 @@
     MATCH_PER_TYPE_OPT(codec_names, str,    video_codec_name, ic, "v");
     MATCH_PER_TYPE_OPT(codec_names, str,    audio_codec_name, ic, "a");
     MATCH_PER_TYPE_OPT(codec_names, str, subtitle_codec_name, ic, "s");
+    MATCH_PER_TYPE_OPT(codec_names, str,     data_codec_name, ic, "d");
 
     ic->video_codec_id   = video_codec_name ?
         find_codec_or_die(video_codec_name   , AVMEDIA_TYPE_VIDEO   , 0)->id : AV_CODEC_ID_NONE;
@@ -949,6 +951,9 @@
     f->nb_streams = ic->nb_streams;
     f->rate_emu   = o->rate_emu;
     f->accurate_seek = o->accurate_seek;
+#if HAVE_PTHREADS
+    f->thread_queue_size = o->thread_queue_size > 0 ? o->thread_queue_size : 8;
+#endif
 
     /* check if all codec options have been used */
     unused_opts = strip_specifiers(o->g->codec_opts);
@@ -1392,8 +1397,10 @@
             video_enc->rc_override =
                 av_realloc_array(video_enc->rc_override,
                                  i + 1, sizeof(RcOverride));
-            if (!video_enc->rc_override)
+            if (!video_enc->rc_override) {
+                av_log(NULL, AV_LOG_FATAL, "Could not (re)allocate memory for rc_override.\n");
                 exit_program(1);
+            }
             video_enc->rc_override[i].start_frame = start;
             video_enc->rc_override[i].end_frame   = end;
             if (q > 0) {
@@ -1934,7 +1941,15 @@
                     }
                 }
         }
-        /* do something with data? */
+        /* Data only if codec id match */
+        if (!o->data_disable ) {
+            enum AVCodecID codec_id = av_guess_codec(oc->oformat, NULL, filename, NULL, AVMEDIA_TYPE_DATA);
+            for (i = 0; codec_id != AV_CODEC_ID_NONE && i < nb_input_streams; i++) {
+                if (input_streams[i]->st->codec->codec_type == AVMEDIA_TYPE_DATA
+                    && input_streams[i]->st->codec->codec_id == codec_id )
+                    new_data_stream(o, oc, i);
+            }
+        }
     } else {
         for (i = 0; i < o->nb_stream_maps; i++) {
             StreamMap *map = &o->stream_maps[i];
@@ -2873,6 +2888,8 @@
         " \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
     { "vsync",          HAS_ARG | OPT_EXPERT,                        { opt_vsync },
         "video sync method", "" },
+    { "frame_drop_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT,      { &frame_drop_threshold },
+        "frame drop threshold", "" },
     { "async",          HAS_ARG | OPT_INT | OPT_EXPERT,              { &audio_sync_method },
         "audio sync method", "" },
     { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT,          { &audio_drift_threshold },
@@ -2943,6 +2960,9 @@
     { "disposition",    OPT_STRING | HAS_ARG | OPT_SPEC |
                         OPT_OUTPUT,                                  { .off = OFFSET(disposition) },
         "disposition", "" },
+    { "thread_queue_size", HAS_ARG | OPT_INT | OPT_OFFSET | OPT_EXPERT | OPT_INPUT,
+                                                                     { .off = OFFSET(thread_queue_size) },
+        "set the maximum number of queued packets from the demuxer" },
 
     /* video options */
     { "vframes",      OPT_VIDEO | HAS_ARG  | OPT_PERFILE | OPT_OUTPUT,           { .func_arg = opt_video_frames },
diff --git a/ffplay.c b/ffplay.c
index 72ec35d..8fa8566 100644
--- a/ffplay.c
+++ b/ffplay.c
@@ -191,12 +191,11 @@
     AVRational start_pts_tb;
     int64_t next_pts;
     AVRational next_pts_tb;
+    SDL_Thread *decoder_tid;
 } Decoder;
 
 typedef struct VideoState {
     SDL_Thread *read_tid;
-    SDL_Thread *video_tid;
-    SDL_Thread *audio_tid;
     AVInputFormat *iformat;
     int abort_request;
     int force_refresh;
@@ -264,7 +263,6 @@
     int xpos;
     double last_vis_time;
 
-    SDL_Thread *subtitle_tid;
     int subtitle_stream;
     AVStream *subtitle_st;
     PacketQueue subtitleq;
@@ -280,6 +278,7 @@
     struct SwsContext *img_convert_ctx;
 #endif
     SDL_Rect last_display_rect;
+    int eof;
 
     char filename[1024];
     int width, height, xleft, ytop;
@@ -768,6 +767,15 @@
         return -1;
 }
 
+static void decoder_abort(Decoder *d, FrameQueue *fq)
+{
+    packet_queue_abort(d->queue);
+    frame_queue_signal(fq);
+    SDL_WaitThread(d->decoder_tid, NULL);
+    d->decoder_tid = NULL;
+    packet_queue_flush(d->queue);
+}
+
 static inline void fill_rectangle(SDL_Surface *screen,
                                   int x, int y, int w, int h, int color, int update)
 {
@@ -1239,7 +1247,10 @@
             s->rdft_bits = rdft_bits;
             s->rdft_data = av_malloc_array(nb_freq, 4 *sizeof(*s->rdft_data));
         }
-        {
+        if (!s->rdft || !s->rdft_data){
+            av_log(NULL, AV_LOG_ERROR, "Failed to allocate buffers for RDFT, switching to waves display\n");
+            s->show_mode = SHOW_MODE_WAVES;
+        } else {
             FFTSample *data[2];
             for (ch = 0; ch < nb_display_channels; ch++) {
                 data[ch] = s->rdft_data + 2 * nb_freq * ch;
@@ -1494,7 +1505,7 @@
 static void stream_toggle_pause(VideoState *is)
 {
     if (is->paused) {
-        is->frame_timer += av_gettime_relative() / 1000000.0 + is->vidclk.pts_drift - is->vidclk.pts;
+        is->frame_timer += av_gettime_relative() / 1000000.0 - is->vidclk.last_updated;
         if (is->read_pause_return != AVERROR(ENOSYS)) {
             is->vidclk.paused = 0;
         }
@@ -2196,6 +2207,12 @@
     return ret;
 }
 
+static void decoder_start(Decoder *d, int (*fn)(void *), void *arg)
+{
+    packet_queue_start(d->queue);
+    d->decoder_tid = SDL_CreateThread(fn, arg);
+}
+
 static int video_thread(void *arg)
 {
     VideoState *is = arg;
@@ -2214,8 +2231,14 @@
     enum AVPixelFormat last_format = -2;
     int last_serial = -1;
     int last_vfilter_idx = 0;
+    if (!graph)
+        return AVERROR(ENOMEM);
+
 #endif
 
+    if (!frame)
+        return AVERROR(ENOMEM);
+
     for (;;) {
         ret = get_video_frame(is, frame);
         if (ret < 0)
@@ -2687,6 +2710,7 @@
         goto fail;
     }
 
+    is->eof = 0;
     ic->streams[stream_index]->discard = AVDISCARD_DEFAULT;
     switch (avctx->codec_type) {
     case AVMEDIA_TYPE_AUDIO:
@@ -2729,31 +2753,28 @@
         is->audio_stream = stream_index;
         is->audio_st = ic->streams[stream_index];
 
-        packet_queue_start(&is->audioq);
         decoder_init(&is->auddec, avctx, &is->audioq, is->continue_read_thread);
         if ((is->ic->iformat->flags & (AVFMT_NOBINSEARCH | AVFMT_NOGENSEARCH | AVFMT_NO_BYTE_SEEK)) && !is->ic->iformat->read_seek) {
             is->auddec.start_pts = is->audio_st->start_time;
             is->auddec.start_pts_tb = is->audio_st->time_base;
         }
-        is->audio_tid = SDL_CreateThread(audio_thread, is);
+        decoder_start(&is->auddec, audio_thread, is);
         SDL_PauseAudio(0);
         break;
     case AVMEDIA_TYPE_VIDEO:
         is->video_stream = stream_index;
         is->video_st = ic->streams[stream_index];
 
-        packet_queue_start(&is->videoq);
         decoder_init(&is->viddec, avctx, &is->videoq, is->continue_read_thread);
-        is->video_tid = SDL_CreateThread(video_thread, is);
+        decoder_start(&is->viddec, video_thread, is);
         is->queue_attachments_req = 1;
         break;
     case AVMEDIA_TYPE_SUBTITLE:
         is->subtitle_stream = stream_index;
         is->subtitle_st = ic->streams[stream_index];
 
-        packet_queue_start(&is->subtitleq);
         decoder_init(&is->subdec, avctx, &is->subtitleq, is->continue_read_thread);
-        is->subtitle_tid = SDL_CreateThread(subtitle_thread, is);
+        decoder_start(&is->subdec, subtitle_thread, is);
         break;
     default:
         break;
@@ -2776,13 +2797,9 @@
 
     switch (avctx->codec_type) {
     case AVMEDIA_TYPE_AUDIO:
-        packet_queue_abort(&is->audioq);
-        frame_queue_signal(&is->sampq);
+        decoder_abort(&is->auddec, &is->sampq);
         SDL_CloseAudio();
-        SDL_WaitThread(is->audio_tid, NULL);
-
         decoder_destroy(&is->auddec);
-        packet_queue_flush(&is->audioq);
         swr_free(&is->swr_ctx);
         av_freep(&is->audio_buf1);
         is->audio_buf1_size = 0;
@@ -2796,28 +2813,12 @@
         }
         break;
     case AVMEDIA_TYPE_VIDEO:
-        packet_queue_abort(&is->videoq);
-
-        /* note: we also signal this mutex to make sure we deblock the
-           video thread in all cases */
-        frame_queue_signal(&is->pictq);
-
-        SDL_WaitThread(is->video_tid, NULL);
-
+        decoder_abort(&is->viddec, &is->pictq);
         decoder_destroy(&is->viddec);
-        packet_queue_flush(&is->videoq);
         break;
     case AVMEDIA_TYPE_SUBTITLE:
-        packet_queue_abort(&is->subtitleq);
-
-        /* note: we also signal this mutex to make sure we deblock the
-           video thread in all cases */
-        frame_queue_signal(&is->subpq);
-
-        SDL_WaitThread(is->subtitle_tid, NULL);
-
+        decoder_abort(&is->subdec, &is->subpq);
         decoder_destroy(&is->subdec);
-        packet_queue_flush(&is->subtitleq);
         break;
     default:
         break;
@@ -2873,7 +2874,6 @@
     int err, i, ret;
     int st_index[AVMEDIA_TYPE_NB];
     AVPacket pkt1, *pkt = &pkt1;
-    int eof = 0;
     int64_t stream_start_time;
     int pkt_in_play_range = 0;
     AVDictionaryEntry *t;
@@ -2881,13 +2881,20 @@
     int orig_nb_streams;
     SDL_mutex *wait_mutex = SDL_CreateMutex();
     int scan_all_pmts_set = 0;
+    int64_t pkt_ts;
 
     memset(st_index, -1, sizeof(st_index));
     is->last_video_stream = is->video_stream = -1;
     is->last_audio_stream = is->audio_stream = -1;
     is->last_subtitle_stream = is->subtitle_stream = -1;
+    is->eof = 0;
 
     ic = avformat_alloc_context();
+    if (!ic) {
+        av_log(NULL, AV_LOG_FATAL, "Could not allocate context.\n");
+        ret = AVERROR(ENOMEM);
+        goto fail;
+    }
     ic->interrupt_callback.callback = decode_interrupt_cb;
     ic->interrupt_callback.opaque = is;
     if (!av_dict_get(format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE)) {
@@ -3083,7 +3090,7 @@
             }
             is->seek_req = 0;
             is->queue_attachments_req = 1;
-            eof = 0;
+            is->eof = 0;
             if (is->paused)
                 step_to_next_frame(is);
         }
@@ -3123,14 +3130,14 @@
         }
         ret = av_read_frame(ic, pkt);
         if (ret < 0) {
-            if ((ret == AVERROR_EOF || avio_feof(ic->pb)) && !eof) {
+            if ((ret == AVERROR_EOF || avio_feof(ic->pb)) && !is->eof) {
                 if (is->video_stream >= 0)
                     packet_queue_put_nullpacket(&is->videoq, is->video_stream);
                 if (is->audio_stream >= 0)
                     packet_queue_put_nullpacket(&is->audioq, is->audio_stream);
                 if (is->subtitle_stream >= 0)
                     packet_queue_put_nullpacket(&is->subtitleq, is->subtitle_stream);
-                eof = 1;
+                is->eof = 1;
             }
             if (ic->pb && ic->pb->error)
                 break;
@@ -3139,12 +3146,13 @@
             SDL_UnlockMutex(wait_mutex);
             continue;
         } else {
-            eof = 0;
+            is->eof = 0;
         }
         /* check if packet is in play range specified by user, then queue, otherwise discard */
         stream_start_time = ic->streams[pkt->stream_index]->start_time;
+        pkt_ts = pkt->pts == AV_NOPTS_VALUE ? pkt->dts : pkt->pts;
         pkt_in_play_range = duration == AV_NOPTS_VALUE ||
-                (pkt->pts - (stream_start_time != AV_NOPTS_VALUE ? stream_start_time : 0)) *
+                (pkt_ts - (stream_start_time != AV_NOPTS_VALUE ? stream_start_time : 0)) *
                 av_q2d(ic->streams[pkt->stream_index]->time_base) -
                 (double)(start_time != AV_NOPTS_VALUE ? start_time : 0) / 1000000
                 <= ((double)duration / 1000000);
diff --git a/ffprobe.c b/ffprobe.c
index 38879f1..9ee2850 100644
--- a/ffprobe.c
+++ b/ffprobe.c
@@ -86,7 +86,7 @@
 static char *stream_specifier;
 static char *show_data_hash;
 
-typedef struct {
+typedef struct ReadInterval {
     int id;             ///< identifier
     int64_t start, end; ///< start, end in second/AV_TIME_BASE units
     int has_start, has_end;
@@ -338,7 +338,7 @@
     unsigned int nb_section_frame;  ///< number of the frame  section in case we are in "packets_and_frames" section
     unsigned int nb_section_packet_frame; ///< nb_section_packet or nb_section_frame according if is_packets_and_frames
 
-    StringValidation string_validation;
+    int string_validation;
     char *string_validation_replacement;
     unsigned int string_validation_utf8_flags;
 };
@@ -1192,7 +1192,7 @@
 
 /* INI format output */
 
-typedef struct {
+typedef struct INIContext {
     const AVClass *class;
     int hierarchical;
 } INIContext;
@@ -1296,7 +1296,7 @@
 
 /* JSON output */
 
-typedef struct {
+typedef struct JSONContext {
     const AVClass *class;
     int indent_level;
     int compact;
@@ -1458,7 +1458,7 @@
 
 /* XML output */
 
-typedef struct {
+typedef struct XMLContext {
     const AVClass *class;
     int within_tag;
     int indent_level;
@@ -2094,6 +2094,8 @@
         case AVMEDIA_TYPE_VIDEO:
             print_int("width",        dec_ctx->width);
             print_int("height",       dec_ctx->height);
+            print_int("coded_width",  dec_ctx->coded_width);
+            print_int("coded_height", dec_ctx->coded_height);
             print_int("has_b_frames", dec_ctx->has_b_frames);
             sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, NULL);
             if (sar.den) {
@@ -2562,8 +2564,6 @@
     print_str("version", FFMPEG_VERSION);
     print_fmt("copyright", "Copyright (c) %d-%d the FFmpeg developers",
               program_birth_year, CONFIG_THIS_YEAR);
-    print_str("build_date", __DATE__);
-    print_str("build_time", __TIME__);
     print_str("compiler_ident", CC_IDENT);
     print_str("configuration", FFMPEG_CONFIGURATION);
     writer_print_section_footer(w);
diff --git a/ffserver.c b/ffserver.c
index 0946d0e..4803b96 100644
--- a/ffserver.c
+++ b/ffserver.c
@@ -209,10 +209,10 @@
 
 /* HTTP handling */
 static int handle_connection(HTTPContext *c);
-static int http_parse_request(HTTPContext *c);
-static int http_send_data(HTTPContext *c);
 static void compute_status(HTTPContext *c);
 static int open_input_stream(HTTPContext *c, const char *info);
+static int http_parse_request(HTTPContext *c);
+static int http_send_data(HTTPContext *c);
 static int http_start_receive_data(HTTPContext *c);
 static int http_receive_data(HTTPContext *c);
 
@@ -465,7 +465,8 @@
     my_addr->sin_family = AF_INET;
     if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
         char bindmsg[32];
-        snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)", ntohs(my_addr->sin_port));
+        snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)",
+                 ntohs(my_addr->sin_port));
         perror (bindmsg);
         closesocket(server_fd);
         return -1;
@@ -725,7 +726,8 @@
                        nb_connections, config.nb_max_connections);
     av_assert0(len < sizeof(buffer));
     if (send(fd, buffer, len, 0) < len)
-        av_log(NULL, AV_LOG_WARNING, "Could not send too-busy reply, send() failed\n");
+        av_log(NULL, AV_LOG_WARNING,
+               "Could not send too-busy reply, send() failed\n");
 }
 
 
@@ -1091,7 +1093,8 @@
     return 0;
 }
 
-static int find_stream_in_feed(FFServerStream *feed, AVCodecContext *codec, int bit_rate)
+static int find_stream_in_feed(FFServerStream *feed, AVCodecContext *codec,
+                               int bit_rate)
 {
     int i;
     int best_bitrate = 100000000;
@@ -1113,7 +1116,8 @@
          */
 
         if (feed_codec->bit_rate <= bit_rate) {
-            if (best_bitrate > bit_rate || feed_codec->bit_rate > best_bitrate) {
+            if (best_bitrate > bit_rate ||
+                feed_codec->bit_rate > best_bitrate) {
                 best_bitrate = feed_codec->bit_rate;
                 best = i;
             }
@@ -1183,7 +1187,8 @@
     *pp = p;
 }
 
-static FFServerIPAddressACL* parse_dynamic_acl(FFServerStream *stream, HTTPContext *c)
+static FFServerIPAddressACL* parse_dynamic_acl(FFServerStream *stream,
+                                               HTTPContext *c)
 {
     FILE* f;
     char line[1024];
@@ -1211,7 +1216,8 @@
         ffserver_get_arg(cmd, sizeof(cmd), &p);
 
         if (!av_strcasecmp(cmd, "ACL"))
-            ffserver_parse_acl_row(NULL, NULL, acl, p, stream->dynamic_acl, line_num);
+            ffserver_parse_acl_row(NULL, NULL, acl, p, stream->dynamic_acl,
+                                   line_num);
     }
     fclose(f);
     return acl;
@@ -1339,7 +1345,8 @@
     av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
 
     if (config.debug)
-        http_log("%s - - New connection: %s %s\n", inet_ntoa(c->from_addr.sin_addr), cmd, url);
+        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 */
     p1 = strchr(url, '?');
@@ -1414,7 +1421,8 @@
                       "\r\n"
                       "<html><head><title>Moved</title></head><body>\r\n"
                       "You should be <a href=\"%s\">redirected</a>.\r\n"
-                      "</body></html>\r\n", stream->feed_filename, stream->feed_filename);
+                      "</body></html>\r\n",
+                 stream->feed_filename, stream->feed_filename);
         q += strlen(q);
         /* prepare output buffer */
         c->buffer_ptr = c->buffer;
@@ -1454,7 +1462,8 @@
                       "<p>The server is too busy to serve your request at this time.</p>\r\n"
                       "<p>The bandwidth being served (including your stream) is %"PRIu64"kbit/sec, "
                       "and this exceeds the limit of %"PRIu64"kbit/sec.</p>\r\n"
-                      "</body></html>\r\n", current_bandwidth, config.max_bandwidth);
+                      "</body></html>\r\n",
+                 current_bandwidth, config.max_bandwidth);
         q += strlen(q);
         /* prepare output buffer */
         c->buffer_ptr = c->buffer;
@@ -1760,7 +1769,8 @@
 
     avio_printf(pb, "<html><head><title>%s Status</title>\n", program_name);
     if (c->stream->feed_filename[0])
-        avio_printf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n", c->stream->feed_filename);
+        avio_printf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n",
+                    c->stream->feed_filename);
     avio_printf(pb, "</head>\n<body>");
     avio_printf(pb, "<h1>%s Status</h1>\n", program_name);
     /* format status */
@@ -2042,8 +2052,11 @@
     }
 
     /* open stream */
-    if ((ret = avformat_open_input(&s, input_filename, c->stream->ifmt, &c->stream->in_opts)) < 0) {
-        http_log("Could not open input '%s': %s\n", input_filename, av_err2str(ret));
+    ret = avformat_open_input(&s, input_filename, c->stream->ifmt,
+                              &c->stream->in_opts);
+    if (ret < 0) {
+        http_log("Could not open input '%s': %s\n",
+                 input_filename, av_err2str(ret));
         return ret;
     }
 
@@ -2113,7 +2126,8 @@
         c->fmt_ctx = *ctx;
         av_freep(&ctx);
         av_dict_copy(&(c->fmt_ctx.metadata), c->stream->metadata, 0);
-        c->fmt_ctx.streams = av_mallocz_array(c->stream->nb_streams, sizeof(AVStream *));
+        c->fmt_ctx.streams = av_mallocz_array(c->stream->nb_streams,
+                                              sizeof(AVStream *));
 
         for(i=0;i<c->stream->nb_streams;i++) {
             AVStream *src;
@@ -2268,7 +2282,8 @@
                             max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
                         else
                             max_packet_size = c->rtp_handles[c->packet_stream_index]->max_packet_size;
-                        ret = ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size);
+                        ret = ffio_open_dyn_packet_buf(&ctx->pb,
+                                                       max_packet_size);
                     } else {
                         ret = avio_open_dyn_buf(&ctx->pb);
                     }
@@ -2280,10 +2295,13 @@
 
                     ctx->pb->seekable = 0;
                     if (pkt.dts != AV_NOPTS_VALUE)
-                        pkt.dts = av_rescale_q(pkt.dts, ist->time_base, ost->time_base);
+                        pkt.dts = av_rescale_q(pkt.dts, ist->time_base,
+                                               ost->time_base);
                     if (pkt.pts != AV_NOPTS_VALUE)
-                        pkt.pts = av_rescale_q(pkt.pts, ist->time_base, ost->time_base);
-                    pkt.duration = av_rescale_q(pkt.duration, ist->time_base, ost->time_base);
+                        pkt.pts = av_rescale_q(pkt.pts, ist->time_base,
+                                               ost->time_base);
+                    pkt.duration = av_rescale_q(pkt.duration, ist->time_base,
+                                                ost->time_base);
                     if ((ret = av_write_frame(ctx, &pkt)) < 0) {
                         http_log("Error writing frame to output for stream '%s': %s\n",
                                  c->stream->filename, av_err2str(ret));
@@ -2407,7 +2425,7 @@
 
                     /* send everything we can NOW */
                     len = send(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
-                                rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0);
+                               rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0);
                     if (len > 0)
                         rtsp_c->packet_buffer_ptr += len;
                     if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) {
@@ -2425,11 +2443,13 @@
                     ffurl_write(c->rtp_handles[c->packet_stream_index],
                                 c->buffer_ptr, len);
                     c->buffer_ptr += len;
-                    /* here we continue as we can send several packets per 10 ms slot */
+                    /* here we continue as we can send several packets
+                     * per 10 ms slot */
                 }
             } else {
                 /* TCP data output */
-                len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
+                len = send(c->fd, c->buffer_ptr,
+                           c->buffer_end - c->buffer_ptr, 0);
                 if (len < 0) {
                     if (ff_neterrno() != AVERROR(EAGAIN) &&
                         ff_neterrno() != AVERROR(EINTR))
@@ -2457,13 +2477,15 @@
     int ret;
 
     if (c->stream->feed_opened) {
-        http_log("Stream feed '%s' was not opened\n", c->stream->feed_filename);
+        http_log("Stream feed '%s' was not opened\n",
+                 c->stream->feed_filename);
         return AVERROR(EINVAL);
     }
 
     /* Don't permit writing to this one */
     if (c->stream->readonly) {
-        http_log("Cannot write to read-only file '%s'\n", c->stream->feed_filename);
+        http_log("Cannot write to read-only file '%s'\n",
+                 c->stream->feed_filename);
         return AVERROR(EINVAL);
     }
 
@@ -2498,7 +2520,8 @@
         }
     }
 
-    c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd), FFM_PACKET_SIZE);
+    c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd),
+                                        FFM_PACKET_SIZE);
     c->stream->feed_size = lseek(fd, 0, SEEK_END);
     lseek(fd, 0, SEEK_SET);
 
@@ -2592,12 +2615,14 @@
                 feed->feed_size = feed->feed_write_index;
 
             /* handle wrap around if max file size reached */
-            if (c->stream->feed_max_size && feed->feed_write_index >= c->stream->feed_max_size)
+            if (c->stream->feed_max_size &&
+                feed->feed_write_index >= c->stream->feed_max_size)
                 feed->feed_write_index = FFM_PACKET_SIZE;
 
             /* write index */
             if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
-                http_log("Error writing index to feed file: %s\n", strerror(errno));
+                http_log("Error writing index to feed file: %s\n",
+                         strerror(errno));
                 goto fail;
             }
 
@@ -2812,9 +2837,12 @@
         snprintf(avc->filename, 1024, "rtp://0.0.0.0");
     }
 
-    if (!(avc->streams = av_malloc_array(avc->nb_streams, sizeof(*avc->streams))))
+    avc->streams = av_malloc_array(avc->nb_streams, sizeof(*avc->streams));
+    if (!avc->streams)
         goto sdp_done;
-    if (!(avs = av_malloc_array(avc->nb_streams, sizeof(*avs))))
+
+    avs = av_malloc_array(avc->nb_streams, sizeof(*avs));
+    if (!avs)
         goto sdp_done;
 
     for(i = 0; i < stream->nb_streams; i++) {
@@ -2838,7 +2866,8 @@
 //    rtsp_reply_header(c, RTSP_STATUS_OK);
     avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
     avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
-    avio_printf(c->pb, "Public: %s\r\n", "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
+    avio_printf(c->pb, "Public: %s\r\n",
+                "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
     avio_printf(c->pb, "\r\n");
 }
 
@@ -2875,7 +2904,8 @@
     /* get the host IP */
     len = sizeof(my_addr);
     getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
-    content_length = prepare_sdp_description(stream, &content, my_addr.sin_addr);
+    content_length = prepare_sdp_description(stream, &content,
+                                             my_addr.sin_addr);
     if (content_length < 0) {
         rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
         return;
@@ -3123,7 +3153,8 @@
     avio_printf(c->pb, "\r\n");
 }
 
-static void rtsp_cmd_interrupt(HTTPContext *c, const char *url, RTSPMessageHeader *h, int pause_only)
+static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
+                               RTSPMessageHeader *h, int pause_only)
 {
     HTTPContext *rtp_c;
 
@@ -3157,7 +3188,8 @@
 /* RTP handling */
 
 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
-                                       FFServerStream *stream, const char *session_id,
+                                       FFServerStream *stream,
+                                       const char *session_id,
                                        enum RTSPLowerTransport rtp_protocol)
 {
     HTTPContext *c = NULL;
@@ -3321,7 +3353,8 @@
 /********************************************************************/
 /* ffserver initialization */
 
-static AVStream *add_av_stream1(FFServerStream *stream, AVCodecContext *codec, int copy)
+static AVStream *add_av_stream1(FFServerStream *stream,
+                                AVCodecContext *codec, int copy)
 {
     AVStream *fst;
 
@@ -3424,7 +3457,8 @@
     if (!mpeg4_count)
         return;
 
-    printf("MPEG4 without extra data: trying to find header in %s\n", infile->filename);
+    printf("MPEG4 without extra data: trying to find header in %s\n",
+           infile->filename);
     while (mpeg4_count > 0) {
         if (av_read_frame(infile, &pkt) < 0)
             break;
@@ -3440,7 +3474,6 @@
                 if (p[0] == 0x00 && p[1] == 0x00 &&
                     p[2] == 0x01 && p[3] == 0xb6) {
                     size = p - pkt.data;
-                    //                    av_hex_dump_log(infile, AV_LOG_DEBUG, pkt.data, size);
                     st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
                     st->codec->extradata_size = size;
                     memcpy(st->codec->extradata, pkt.data, size);
@@ -3476,13 +3509,18 @@
             }
 
             if (!stream->feed_filename[0]) {
-                http_log("Unspecified feed file for stream '%s'\n", stream->filename);
+                http_log("Unspecified feed file for stream '%s'\n",
+                         stream->filename);
                 goto fail;
             }
 
-            http_log("Opening feed file '%s' for stream '%s'\n", stream->feed_filename, stream->filename);
-            if ((ret = avformat_open_input(&infile, stream->feed_filename, stream->ifmt, &stream->in_opts)) < 0) {
-                http_log("Could not open '%s': %s\n", stream->feed_filename, av_err2str(ret));
+            http_log("Opening feed file '%s' for stream '%s'\n",
+                     stream->feed_filename, stream->filename);
+            ret = avformat_open_input(&infile, stream->feed_filename,
+                                      stream->ifmt, &stream->in_opts);
+            if (ret < 0) {
+                http_log("Could not open '%s': %s\n", stream->feed_filename,
+                         av_err2str(ret));
                 /* remove stream (no need to spend more time on it) */
             fail:
                 remove_stream(stream);
@@ -3522,7 +3560,8 @@
             } else {
                 /* we handle a stream coming from a feed */
                 for(i=0;i<stream->nb_streams;i++)
-                    stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]);
+                    stream->feed_streams[i] = add_av_stream(feed,
+                                                            stream->streams[i]);
             }
         }
     }
@@ -3690,7 +3729,9 @@
                 int uptime = time(0) - feed->pid_start;
 
                 feed->pid = 0;
-                fprintf(stderr, "%s: Pid %d exited with status %d after %d seconds\n", feed->filename, pid, status, uptime);
+                fprintf(stderr,
+                        "%s: Pid %d exited with status %d after %d seconds\n",
+                        feed->filename, pid, status, uptime);
 
                 if (uptime < 30)
                     /* Turn off any more restarts */
diff --git a/libavcodec/012v.c b/libavcodec/012v.c
index c2b6a35..b87551e 100644
--- a/libavcodec/012v.c
+++ b/libavcodec/012v.c
@@ -38,15 +38,15 @@
 static int zero12v_decode_frame(AVCodecContext *avctx, void *data,
                                 int *got_frame, AVPacket *avpkt)
 {
-    int line = 0, ret;
+    int line, ret;
     const int width = avctx->width;
     AVFrame *pic = data;
     uint16_t *y, *u, *v;
     const uint8_t *line_end, *src = avpkt->data;
     int stride = avctx->width * 8 / 3;
 
-    if (width == 1) {
-        av_log(avctx, AV_LOG_ERROR, "Width 1 not supported.\n");
+    if (width <= 1 || avctx->height <= 0) {
+        av_log(avctx, AV_LOG_ERROR, "Dimensions %dx%d not supported.\n", width, avctx->height);
         return AVERROR_INVALIDDATA;
     }
 
@@ -67,45 +67,45 @@
     pic->pict_type = AV_PICTURE_TYPE_I;
     pic->key_frame = 1;
 
-    y = (uint16_t *)pic->data[0];
-    u = (uint16_t *)pic->data[1];
-    v = (uint16_t *)pic->data[2];
     line_end = avpkt->data + stride;
+    for (line = 0; line < avctx->height; line++) {
+        uint16_t y_temp[6] = {0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000};
+        uint16_t u_temp[3] = {0x8000, 0x8000, 0x8000};
+        uint16_t v_temp[3] = {0x8000, 0x8000, 0x8000};
+        int x;
+        y = (uint16_t *)(pic->data[0] + line * pic->linesize[0]);
+        u = (uint16_t *)(pic->data[1] + line * pic->linesize[1]);
+        v = (uint16_t *)(pic->data[2] + line * pic->linesize[2]);
 
-    while (line++ < avctx->height) {
-        while (1) {
-            uint32_t t = AV_RL32(src);
+        for (x = 0; x < width; x += 6) {
+            uint32_t t;
+
+            if (width - x < 6 || line_end - src < 16) {
+                y = y_temp;
+                u = u_temp;
+                v = v_temp;
+            }
+
+            if (line_end - src < 4)
+                break;
+
+            t = AV_RL32(src);
             src += 4;
             *u++ = t <<  6 & 0xFFC0;
             *y++ = t >>  4 & 0xFFC0;
             *v++ = t >> 14 & 0xFFC0;
 
-            if (src >= line_end - 1) {
-                *y = 0x80;
-                src++;
-                line_end += stride;
-                y = (uint16_t *)(pic->data[0] + line * pic->linesize[0]);
-                u = (uint16_t *)(pic->data[1] + line * pic->linesize[1]);
-                v = (uint16_t *)(pic->data[2] + line * pic->linesize[2]);
+            if (line_end - src < 4)
                 break;
-            }
 
             t = AV_RL32(src);
             src += 4;
             *y++ = t <<  6 & 0xFFC0;
             *u++ = t >>  4 & 0xFFC0;
             *y++ = t >> 14 & 0xFFC0;
-            if (src >= line_end - 2) {
-                if (!(width & 1)) {
-                    *y = 0x80;
-                    src += 2;
-                }
-                line_end += stride;
-                y = (uint16_t *)(pic->data[0] + line * pic->linesize[0]);
-                u = (uint16_t *)(pic->data[1] + line * pic->linesize[1]);
-                v = (uint16_t *)(pic->data[2] + line * pic->linesize[2]);
+
+            if (line_end - src < 4)
                 break;
-            }
 
             t = AV_RL32(src);
             src += 4;
@@ -113,15 +113,8 @@
             *y++ = t >>  4 & 0xFFC0;
             *u++ = t >> 14 & 0xFFC0;
 
-            if (src >= line_end - 1) {
-                *y = 0x80;
-                src++;
-                line_end += stride;
-                y = (uint16_t *)(pic->data[0] + line * pic->linesize[0]);
-                u = (uint16_t *)(pic->data[1] + line * pic->linesize[1]);
-                v = (uint16_t *)(pic->data[2] + line * pic->linesize[2]);
+            if (line_end - src < 4)
                 break;
-            }
 
             t = AV_RL32(src);
             src += 4;
@@ -129,18 +122,21 @@
             *v++ = t >>  4 & 0xFFC0;
             *y++ = t >> 14 & 0xFFC0;
 
-            if (src >= line_end - 2) {
-                if (width & 1) {
-                    *y = 0x80;
-                    src += 2;
-                }
-                line_end += stride;
-                y = (uint16_t *)(pic->data[0] + line * pic->linesize[0]);
-                u = (uint16_t *)(pic->data[1] + line * pic->linesize[1]);
-                v = (uint16_t *)(pic->data[2] + line * pic->linesize[2]);
+            if (width - x < 6)
                 break;
-            }
         }
+
+        if (x < width) {
+            y = x   + (uint16_t *)(pic->data[0] + line * pic->linesize[0]);
+            u = x/2 + (uint16_t *)(pic->data[1] + line * pic->linesize[1]);
+            v = x/2 + (uint16_t *)(pic->data[2] + line * pic->linesize[2]);
+            memcpy(y, y_temp, sizeof(*y) * (width - x));
+            memcpy(u, u_temp, sizeof(*u) * (width - x + 1) / 2);
+            memcpy(v, v_temp, sizeof(*v) * (width - x + 1) / 2);
+        }
+
+        line_end += stride;
+        src = line_end - stride;
     }
 
     *got_frame = 1;
diff --git a/libavcodec/Makefile b/libavcodec/Makefile
index db8d45a..1a0c734 100644
--- a/libavcodec/Makefile
+++ b/libavcodec/Makefile
@@ -7,6 +7,7 @@
           dv_profile.h                                                  \
           dxva2.h                                                       \
           old_codec_ids.h                                               \
+          qsv.h                                                         \
           vaapi.h                                                       \
           vda.h                                                         \
           vdpau.h                                                       \
@@ -23,11 +24,11 @@
        bitstream_filter.o                                               \
        codec_desc.o                                                     \
        dv_profile.o                                                     \
-       fmtconvert.o                                                     \
        imgconvert.o                                                     \
        mathtables.o                                                     \
        options.o                                                        \
        parser.o                                                         \
+       qsv_api.o                                                        \
        raw.o                                                            \
        resample.o                                                       \
        resample2.o                                                      \
@@ -54,6 +55,7 @@
 OBJS-$(CONFIG_FFT)                     += avfft.o fft_fixed.o fft_float.o \
                                           fft_fixed_32.o fft_init_table.o \
                                           $(FFT-OBJS-yes)
+OBJS-$(CONFIG_FMTCONVERT)              += fmtconvert.o
 OBJS-$(CONFIG_GOLOMB)                  += golomb.o
 OBJS-$(CONFIG_H263DSP)                 += h263dsp.o
 OBJS-$(CONFIG_H264CHROMA)              += h264chroma.o
@@ -66,6 +68,7 @@
 OBJS-$(CONFIG_HUFFYUVENCDSP)           += huffyuvencdsp.o
 OBJS-$(CONFIG_IDCTDSP)                 += idctdsp.o simple_idct.o jrevdct.o
 OBJS-$(CONFIG_IIRFILTER)               += iirfilter.o
+OBJS-$(CONFIG_IMDCT15)                 += imdct15.o
 OBJS-$(CONFIG_INTRAX8)                 += intrax8.o intrax8dsp.o
 OBJS-$(CONFIG_LIBXVID)                 += libxvid_rc.o
 OBJS-$(CONFIG_LLAUDDSP)                += lossless_audiodsp.o
@@ -88,6 +91,7 @@
                                           mpegvideoencdsp.o
 OBJS-$(CONFIG_PIXBLOCKDSP)             += pixblockdsp.o
 OBJS-$(CONFIG_QPELDSP)                 += qpeldsp.o
+OBJS-$(CONFIG_QSV)                     += qsv.o
 OBJS-$(CONFIG_RANGECODER)              += rangecoder.o
 RDFT-OBJS-$(CONFIG_HARDCODED_TABLES)   += sin_tables.o
 OBJS-$(CONFIG_RDFT)                    += rdft.o $(RDFT-OBJS-yes)
@@ -188,8 +192,9 @@
 OBJS-$(CONFIG_CSCD_DECODER)            += cscd.o
 OBJS-$(CONFIG_CYUV_DECODER)            += cyuv.o
 OBJS-$(CONFIG_DCA_DECODER)             += dcadec.o dca.o dcadsp.o      \
-                                          synth_filter.o
-OBJS-$(CONFIG_DCA_ENCODER)             += dcaenc.o dca.o
+                                          dcadata.o dca_exss.o         \
+                                          dca_xll.o synth_filter.o
+OBJS-$(CONFIG_DCA_ENCODER)             += dcaenc.o dca.o dcadata.o
 OBJS-$(CONFIG_DIRAC_DECODER)           += diracdec.o dirac.o diracdsp.o \
                                           dirac_arith.o mpeg12data.o dirac_dwt.o
 OBJS-$(CONFIG_DFA_DECODER)             += dfa.o
@@ -203,6 +208,7 @@
 OBJS-$(CONFIG_DSD_MSBF_PLANAR_DECODER) += dsddec.o
 OBJS-$(CONFIG_DSICINAUDIO_DECODER)     += dsicinaudio.o
 OBJS-$(CONFIG_DSICINVIDEO_DECODER)     += dsicinvideo.o
+OBJS-$(CONFIG_DSS_SP_DECODER)          += dss_sp.o
 OBJS-$(CONFIG_DVBSUB_DECODER)          += dvbsubdec.o
 OBJS-$(CONFIG_DVBSUB_ENCODER)          += dvbsub.o
 OBJS-$(CONFIG_DVDSUB_DECODER)          += dvdsubdec.o
@@ -211,7 +217,7 @@
 OBJS-$(CONFIG_DVVIDEO_ENCODER)         += dvenc.o dv.o dvdata.o
 OBJS-$(CONFIG_DXA_DECODER)             += dxa.o
 OBJS-$(CONFIG_DXTORY_DECODER)          += dxtory.o
-OBJS-$(CONFIG_EAC3_DECODER)            += eac3dec.o eac3_data.o
+OBJS-$(CONFIG_EAC3_DECODER)            += eac3_data.o
 OBJS-$(CONFIG_EAC3_ENCODER)            += eac3enc.o eac3_data.o
 OBJS-$(CONFIG_EACMV_DECODER)           += eacmv.o
 OBJS-$(CONFIG_EAMAD_DECODER)           += eamad.o eaidct.o mpeg12.o \
@@ -261,10 +267,12 @@
                                           h264_mb.o h264_picture.o h264_ps.o \
                                           h264_refs.o h264_sei.o h264_slice.o
 OBJS-$(CONFIG_H264_VDA_DECODER)        += vda_h264_dec.o
+OBJS-$(CONFIG_H264_QSV_DECODER)        += qsv_h264.o
 OBJS-$(CONFIG_HEVC_DECODER)            += hevc.o hevc_mvs.o hevc_ps.o hevc_sei.o \
                                           hevc_cabac.o hevc_refs.o hevcpred.o    \
                                           hevcdsp.o hevc_filter.o
 OBJS-$(CONFIG_HNM4_VIDEO_DECODER)      += hnm4video.o
+OBJS-$(CONFIG_HQX_DECODER)             += hqx.o hqxvlc.o
 OBJS-$(CONFIG_HUFFYUV_DECODER)         += huffyuv.o huffyuvdec.o
 OBJS-$(CONFIG_HUFFYUV_ENCODER)         += huffyuv.o huffyuvenc.o
 OBJS-$(CONFIG_IDCIN_DECODER)           += idcinvideo.o
@@ -351,8 +359,7 @@
 OBJS-$(CONFIG_NVENC_ENCODER)           += nvenc.o
 OBJS-$(CONFIG_ON2AVC_DECODER)          += on2avc.o on2avcdata.o
 OBJS-$(CONFIG_OPUS_DECODER)            += opusdec.o opus.o opus_celt.o \
-                                          opus_imdct.o opus_silk.o     \
-                                          vorbis_data.o
+                                          opus_silk.o vorbis_data.o
 OBJS-$(CONFIG_PAF_AUDIO_DECODER)       += pafaudio.o
 OBJS-$(CONFIG_PAF_VIDEO_DECODER)       += pafvideo.o
 OBJS-$(CONFIG_PAM_DECODER)             += pnmdec.o pnm.o
@@ -451,6 +458,7 @@
 OBJS-$(CONFIG_TARGA_DECODER)           += targa.o
 OBJS-$(CONFIG_TARGA_ENCODER)           += targaenc.o rle.o
 OBJS-$(CONFIG_TARGA_Y216_DECODER)      += targa_y216dec.o
+OBJS-$(CONFIG_TDSC_DECODER)            += tdsc.o
 OBJS-$(CONFIG_TIERTEXSEQVIDEO_DECODER) += tiertexseqv.o
 OBJS-$(CONFIG_TIFF_DECODER)            += tiff.o lzw.o faxcompr.o tiff_data.o tiff_common.o
 OBJS-$(CONFIG_TIFF_ENCODER)            += tiffenc.o rle.o lzwenc.o tiff_data.o
@@ -619,8 +627,8 @@
 OBJS-$(CONFIG_ADPCM_EA_R2_DECODER)        += adpcm.o adpcm_data.o
 OBJS-$(CONFIG_ADPCM_EA_R3_DECODER)        += adpcm.o adpcm_data.o
 OBJS-$(CONFIG_ADPCM_EA_XAS_DECODER)       += adpcm.o adpcm_data.o
-OBJS-$(CONFIG_ADPCM_G722_DECODER)         += g722.o g722dec.o
-OBJS-$(CONFIG_ADPCM_G722_ENCODER)         += g722.o g722enc.o
+OBJS-$(CONFIG_ADPCM_G722_DECODER)         += g722.o g722dsp.o g722dec.o
+OBJS-$(CONFIG_ADPCM_G722_ENCODER)         += g722.o g722dsp.o g722enc.o
 OBJS-$(CONFIG_ADPCM_G726_DECODER)         += g726.o
 OBJS-$(CONFIG_ADPCM_G726_ENCODER)         += g726.o
 OBJS-$(CONFIG_ADPCM_G726LE_DECODER)       += g726.o
@@ -702,6 +710,7 @@
 OBJS-$(CONFIG_MPEGTS_DEMUXER)          += mpeg4audio.o mpegaudiodata.o
 OBJS-$(CONFIG_MXF_MUXER)               += dnxhddata.o
 OBJS-$(CONFIG_NUT_MUXER)               += mpegaudiodata.o
+OBJS-$(CONFIG_NUT_DEMUXER)             += mpegaudiodata.o mpeg4audio.o
 OBJS-$(CONFIG_OGA_MUXER)               += flac.o flacdata.o
 OBJS-$(CONFIG_OGG_DEMUXER)             += mpeg12data.o \
                                           dirac.o vorbis_data.o
@@ -723,6 +732,7 @@
 # external codec libraries
 OBJS-$(CONFIG_LIBAACPLUS_ENCODER)         += libaacplus.o
 OBJS-$(CONFIG_LIBCELT_DECODER)            += libcelt_dec.o
+OBJS-$(CONFIG_LIBDCADEC_DECODER)          += libdcadec.o
 OBJS-$(CONFIG_LIBFAAC_ENCODER)            += libfaac.o
 OBJS-$(CONFIG_LIBFDK_AAC_DECODER)         += libfdk-aacdec.o
 OBJS-$(CONFIG_LIBFDK_AAC_ENCODER)         += libfdk-aacenc.o
@@ -812,9 +822,7 @@
 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 vc1dsp.o \
-                                          msmpeg4.o msmpeg4data.o mpeg4video.o \
-                                          h263.o
+OBJS-$(CONFIG_VC1_PARSER)              += vc1_parser.o
 OBJS-$(CONFIG_VP3_PARSER)              += vp3_parser.o
 OBJS-$(CONFIG_VP8_PARSER)              += vp8_parser.o
 OBJS-$(CONFIG_VP9_PARSER)              += vp9_parser.o
@@ -857,6 +865,7 @@
 SKIPHEADERS-$(CONFIG_DXVA2)            += dxva2.h dxva2_internal.h
 SKIPHEADERS-$(CONFIG_LIBSCHROEDINGER)  += libschroedinger.h
 SKIPHEADERS-$(CONFIG_LIBUTVIDEO)       += libutvideo.h
+SKIPHEADERS-$(CONFIG_QSV)              += qsv.h qsv_internal.h
 SKIPHEADERS-$(CONFIG_XVMC)             += xvmc.h
 SKIPHEADERS-$(CONFIG_VAAPI)            += vaapi_internal.h
 SKIPHEADERS-$(CONFIG_VDA)              += vda.h vda_internal.h
@@ -864,6 +873,7 @@
 
 TESTPROGS = imgconvert                                                  \
             options                                                     \
+            avfft                                                       \
 
 
 TESTPROGS-$(CONFIG_CABAC)                 += cabac
diff --git a/libavcodec/a64multienc.c b/libavcodec/a64multienc.c
index 6438c27..f9c4f36 100644
--- a/libavcodec/a64multienc.c
+++ b/libavcodec/a64multienc.c
@@ -28,6 +28,7 @@
 #include "a64tables.h"
 #include "elbg.h"
 #include "internal.h"
+#include "libavutil/avassert.h"
 #include "libavutil/common.h"
 #include "libavutil/intreadwrite.h"
 
@@ -65,7 +66,7 @@
 //static const int mc_colors[5]={0x0,0x8,0xa,0xf,0x7};
 //static const int mc_colors[5]={0x0,0x9,0x8,0xa,0x3};
 
-static void to_meta_with_crop(AVCodecContext *avctx, AVFrame *p, int *dest)
+static void to_meta_with_crop(AVCodecContext *avctx, const AVFrame *p, int *dest)
 {
     int blockx, blocky, x, y;
     int luma = 0;
@@ -78,9 +79,13 @@
             for (y = blocky; y < blocky + 8 && y < C64YRES; y++) {
                 for (x = blockx; x < blockx + 8 && x < C64XRES; x += 2) {
                     if(x < width && y < height) {
-                        /* build average over 2 pixels */
-                        luma = (src[(x + 0 + y * p->linesize[0])] +
-                                src[(x + 1 + y * p->linesize[0])]) / 2;
+                        if (x + 1 < width) {
+                            /* build average over 2 pixels */
+                            luma = (src[(x + 0 + y * p->linesize[0])] +
+                                    src[(x + 1 + y * p->linesize[0])]) / 2;
+                        } else {
+                            luma = src[(x + y * p->linesize[0])];
+                        }
                         /* write blocks as linear data now so they are suitable for elbg */
                         dest[0] = luma;
                     }
@@ -186,7 +191,6 @@
 static av_cold int a64multi_close_encoder(AVCodecContext *avctx)
 {
     A64Context *c = avctx->priv_data;
-    av_frame_free(&avctx->coded_frame);
     av_freep(&c->mc_meta_charset);
     av_freep(&c->mc_best_cb);
     av_freep(&c->mc_charset);
@@ -220,7 +224,7 @@
                            a64_palette[mc_colors[a]][2] * 0.11;
     }
 
-    if (!(c->mc_meta_charset = av_malloc_array(c->mc_lifetime, 32000 * sizeof(int))) ||
+    if (!(c->mc_meta_charset = av_mallocz_array(c->mc_lifetime, 32000 * sizeof(int))) ||
        !(c->mc_best_cb       = av_malloc(CHARSET_CHARS * 32 * sizeof(int)))     ||
        !(c->mc_charmap       = av_mallocz_array(c->mc_lifetime, 1000 * sizeof(int))) ||
        !(c->mc_colram        = av_mallocz(CHARSET_CHARS * sizeof(uint8_t)))     ||
@@ -238,14 +242,6 @@
     AV_WB32(avctx->extradata, c->mc_lifetime);
     AV_WB32(avctx->extradata + 16, INTERLACED);
 
-    avctx->coded_frame = av_frame_alloc();
-    if (!avctx->coded_frame) {
-        a64multi_close_encoder(avctx);
-        return AVERROR(ENOMEM);
-    }
-
-    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
-    avctx->coded_frame->key_frame = 1;
     if (!avctx->codec_tag)
          avctx->codec_tag = AV_RL32("a64m");
 
@@ -270,10 +266,9 @@
 }
 
 static int a64multi_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
-                                 const AVFrame *pict, int *got_packet)
+                                 const AVFrame *p, int *got_packet)
 {
     A64Context *c = avctx->priv_data;
-    AVFrame *const p = avctx->coded_frame;
 
     int frame;
     int x, y;
@@ -304,7 +299,7 @@
     }
 
     /* no data, means end encoding asap */
-    if (!pict) {
+    if (!p) {
         /* all done, end encoding */
         if (!c->mc_lifetime) return 0;
         /* no more frames in queue, prepare to flush remaining frames */
@@ -317,13 +312,10 @@
     } else {
         /* fill up mc_meta_charset with data until lifetime exceeds */
         if (c->mc_frame_counter < c->mc_lifetime) {
-            *p = *pict;
-            p->pict_type = AV_PICTURE_TYPE_I;
-            p->key_frame = 1;
             to_meta_with_crop(avctx, p, meta + 32000 * c->mc_frame_counter);
             c->mc_frame_counter++;
             if (c->next_pts == AV_NOPTS_VALUE)
-                c->next_pts = pict->pts;
+                c->next_pts = p->pts;
             /* lifetime is not reached so wait for next frame first */
             return 0;
         }
@@ -334,8 +326,8 @@
         req_size = 0;
         /* any frames to encode? */
         if (c->mc_lifetime) {
-            req_size = charset_size + c->mc_lifetime*(screen_size + colram_size);
-            if ((ret = ff_alloc_packet2(avctx, pkt, req_size)) < 0)
+            int alloc_size = charset_size + c->mc_lifetime*(screen_size + colram_size);
+            if ((ret = ff_alloc_packet2(avctx, pkt, alloc_size)) < 0)
                 return ret;
             buf = pkt->data;
 
@@ -357,6 +349,7 @@
 
             /* advance pointers */
             buf      += charset_size;
+            req_size += charset_size;
         }
 
         /* write x frames to buf */
@@ -393,6 +386,7 @@
         pkt->pts = pkt->dts = c->next_pts;
         c->next_pts         = AV_NOPTS_VALUE;
 
+        av_assert0(pkt->size >= req_size);
         pkt->size   = req_size;
         pkt->flags |= AV_PKT_FLAG_KEY;
         *got_packet = !!req_size;
diff --git a/libavcodec/aac.h b/libavcodec/aac.h
index a151737..b25b40c 100644
--- a/libavcodec/aac.h
+++ b/libavcodec/aac.h
@@ -32,10 +32,10 @@
 
 #include "libavutil/float_dsp.h"
 #include "avcodec.h"
+#include "imdct15.h"
 #include "fft.h"
 #include "mpeg4audio.h"
 #include "sbr.h"
-#include "fmtconvert.h"
 
 #include <stdint.h>
 
@@ -233,7 +233,8 @@
     float sf[120];                                  ///< scalefactors
     int sf_idx[128];                                ///< scalefactor indices (used by encoder)
     uint8_t zeroes[128];                            ///< band is not coded (used by encoder)
-    DECLARE_ALIGNED(32, float,   coeffs)[1024];     ///< coefficients for IMDCT
+    DECLARE_ALIGNED(32, float,   pcoeffs)[1024];    ///< coefficients for IMDCT, pristine
+    DECLARE_ALIGNED(32, float,   coeffs)[1024];     ///< coefficients for IMDCT, maybe processed
     DECLARE_ALIGNED(32, float,   saved)[1536];      ///< overlap
     DECLARE_ALIGNED(32, float,   ret_buf)[2048];    ///< PCM output buffer
     DECLARE_ALIGNED(16, float,   ltp_state)[3072];  ///< time signal for LTP
@@ -294,7 +295,7 @@
     FFTContext mdct_small;
     FFTContext mdct_ld;
     FFTContext mdct_ltp;
-    FmtConvertContext fmt_conv;
+    IMDCT15Context *mdct480;
     AVFloatDSPContext *fdsp;
     int random_state;
     /** @} */
diff --git a/libavcodec/aac_adtstoasc_bsf.c b/libavcodec/aac_adtstoasc_bsf.c
index b1515fd..1f11d02 100644
--- a/libavcodec/aac_adtstoasc_bsf.c
+++ b/libavcodec/aac_adtstoasc_bsf.c
@@ -90,6 +90,10 @@
         av_free(avctx->extradata);
         avctx->extradata_size = 2 + pce_size;
         avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
+        if (!avctx->extradata) {
+            avctx->extradata_size = 0;
+            return AVERROR(ENOMEM);
+        }
 
         init_put_bits(&pb, avctx->extradata, avctx->extradata_size);
         put_bits(&pb, 5, hdr.object_type);
diff --git a/libavcodec/aaccoder.c b/libavcodec/aaccoder.c
index 5bf6a9c..64eee32 100644
--- a/libavcodec/aaccoder.c
+++ b/libavcodec/aaccoder.c
@@ -161,7 +161,7 @@
                         di = t - CLIPPED_ESCAPE;
                         curbits += 21;
                     } else {
-                        int c = av_clip(quant(t, Q), 0, 8191);
+                        int c = av_clip_uintp2(quant(t, Q), 13);
                         di = t - c*cbrtf(c)*IQ;
                         curbits += av_log2(c)*2 - 4 + 1;
                     }
@@ -191,7 +191,7 @@
             if (BT_ESC) {
                 for (j = 0; j < 2; j++) {
                     if (ff_aac_codebook_vectors[cb-1][curidx*2+j] == 64.0f) {
-                        int coef = av_clip(quant(fabsf(in[i+j]), Q), 0, 8191);
+                        int coef = av_clip_uintp2(quant(fabsf(in[i+j]), Q), 13);
                         int len = av_log2(coef);
 
                         put_bits(pb, len - 4 + 1, (1 << (len - 4 + 1)) - 2);
@@ -1069,10 +1069,10 @@
                     float minthr = FFMIN(band0->threshold, band1->threshold);
                     float maxthr = FFMAX(band0->threshold, band1->threshold);
                     for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
-                        M[i] = (sce0->coeffs[start+w2*128+i]
-                              + sce1->coeffs[start+w2*128+i]) * 0.5;
+                        M[i] = (sce0->pcoeffs[start+w2*128+i]
+                              + sce1->pcoeffs[start+w2*128+i]) * 0.5;
                         S[i] =  M[i]
-                              - sce1->coeffs[start+w2*128+i];
+                              - sce1->pcoeffs[start+w2*128+i];
                     }
                     abs_pow34_v(L34, sce0->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
                     abs_pow34_v(R34, sce1->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
diff --git a/libavcodec/aacdec.c b/libavcodec/aacdec.c
index d00b3d0..daec5bc 100644
--- a/libavcodec/aacdec.c
+++ b/libavcodec/aacdec.c
@@ -87,7 +87,7 @@
 #include "internal.h"
 #include "get_bits.h"
 #include "fft.h"
-#include "fmtconvert.h"
+#include "imdct15.h"
 #include "lpc.h"
 #include "kbdwin.h"
 #include "sinewin.h"
@@ -102,7 +102,6 @@
 #include "aacadtsdec.h"
 #include "libavutil/intfloat.h"
 
-#include <assert.h>
 #include <errno.h>
 #include <math.h>
 #include <stdint.h>
@@ -801,6 +800,7 @@
         avpriv_request_sample(avctx, "960/120 MDCT window");
         return AVERROR_PATCHWELCOME;
     }
+    m4ac->frame_length_short = 0;
 
     if (get_bits1(gb))       // dependsOnCoreCoder
         skip_bits(gb, 14);   // coreCoderDelay
@@ -878,11 +878,7 @@
     m4ac->ps  = 0;
     m4ac->sbr = 0;
 
-    if (get_bits1(gb)) { // frameLengthFlag
-        avpriv_request_sample(avctx, "960/120 MDCT window");
-        return AVERROR_PATCHWELCOME;
-    }
-
+    m4ac->frame_length_short = get_bits1(gb);
     res_flags = get_bits(gb, 3);
     if (res_flags) {
         avpriv_report_missing_feature(avctx,
@@ -1136,7 +1132,6 @@
 
     ff_aac_sbr_init();
 
-    ff_fmt_convert_init(&ac->fmt_conv, avctx);
     ac->fdsp = avpriv_float_dsp_alloc(avctx->flags & CODEC_FLAG_BITEXACT);
     if (!ac->fdsp) {
         return AVERROR(ENOMEM);
@@ -1160,6 +1155,10 @@
     ff_mdct_init(&ac->mdct_ld,    10, 1, 1.0 / (32768.0 * 512.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);
+    ret = ff_imdct15_init(&ac->mdct480, 5);
+    if (ret < 0)
+        return ret;
+
     // 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);
@@ -1231,11 +1230,14 @@
 static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
                            GetBitContext *gb)
 {
-    int aot = ac->oc[1].m4ac.object_type;
+    const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
+    const int aot = m4ac->object_type;
+    const int sampling_index = m4ac->sampling_index;
     if (aot != AOT_ER_AAC_ELD) {
         if (get_bits1(gb)) {
             av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
-            return AVERROR_INVALIDDATA;
+            if (ac->avctx->err_recognition & AV_EF_BITSTREAM)
+                return AVERROR_INVALIDDATA;
         }
         ics->window_sequence[1] = ics->window_sequence[0];
         ics->window_sequence[0] = get_bits(gb, 2);
@@ -1264,23 +1266,29 @@
             }
         }
         ics->num_windows       = 8;
-        ics->swb_offset        =    ff_swb_offset_128[ac->oc[1].m4ac.sampling_index];
-        ics->num_swb           =   ff_aac_num_swb_128[ac->oc[1].m4ac.sampling_index];
-        ics->tns_max_bands     = ff_tns_max_bands_128[ac->oc[1].m4ac.sampling_index];
+        ics->swb_offset        =    ff_swb_offset_128[sampling_index];
+        ics->num_swb           =   ff_aac_num_swb_128[sampling_index];
+        ics->tns_max_bands     = ff_tns_max_bands_128[sampling_index];
         ics->predictor_present = 0;
     } else {
-        ics->max_sfb               = get_bits(gb, 6);
-        ics->num_windows           = 1;
+        ics->max_sfb           = get_bits(gb, 6);
+        ics->num_windows       = 1;
         if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {
-            ics->swb_offset        =     ff_swb_offset_512[ac->oc[1].m4ac.sampling_index];
-            ics->num_swb           =    ff_aac_num_swb_512[ac->oc[1].m4ac.sampling_index];
-            ics->tns_max_bands     =  ff_tns_max_bands_512[ac->oc[1].m4ac.sampling_index];
+            if (m4ac->frame_length_short) {
+                ics->swb_offset    =     ff_swb_offset_480[sampling_index];
+                ics->num_swb       =    ff_aac_num_swb_480[sampling_index];
+                ics->tns_max_bands =  ff_tns_max_bands_480[sampling_index];
+            } else {
+                ics->swb_offset    =     ff_swb_offset_512[sampling_index];
+                ics->num_swb       =    ff_aac_num_swb_512[sampling_index];
+                ics->tns_max_bands =  ff_tns_max_bands_512[sampling_index];
+            }
             if (!ics->num_swb || !ics->swb_offset)
                 return AVERROR_BUG;
         } else {
-            ics->swb_offset        =    ff_swb_offset_1024[ac->oc[1].m4ac.sampling_index];
-            ics->num_swb           =   ff_aac_num_swb_1024[ac->oc[1].m4ac.sampling_index];
-            ics->tns_max_bands     = ff_tns_max_bands_1024[ac->oc[1].m4ac.sampling_index];
+            ics->swb_offset    =    ff_swb_offset_1024[sampling_index];
+            ics->num_swb       =   ff_aac_num_swb_1024[sampling_index];
+            ics->tns_max_bands = ff_tns_max_bands_1024[sampling_index];
         }
         if (aot != AOT_ER_AAC_ELD) {
             ics->predictor_present     = get_bits1(gb);
@@ -2585,12 +2593,13 @@
     float *in    = sce->coeffs;
     float *out   = sce->ret;
     float *saved = sce->saved;
-    const float *const window = ff_aac_eld_window;
     float *buf  = ac->buf_mdct;
     int i;
-    const int n  = 512;
+    const int n  = ac->oc[1].m4ac.frame_length_short ? 480 : 512;
     const int n2 = n >> 1;
     const int n4 = n >> 2;
+    const float *const window = n == 480 ? ff_aac_eld_window_480 :
+                                           ff_aac_eld_window_512;
 
     // Inverse transform, mapped to the conventional IMDCT by
     // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
@@ -2602,7 +2611,10 @@
         temp =  in[i    ]; in[i    ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
         temp = -in[i + 1]; in[i + 1] =  in[n - 2 - i]; in[n - 2 - i] = temp;
     }
-    ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
+    if (n == 480)
+        ac->mdct480->imdct_half(ac->mdct480, buf, in, 1, -1.f/(16*1024*960));
+    else
+        ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
     for (i = 0; i < n; i+=2) {
         buf[i] = -buf[i];
     }
@@ -2835,6 +2847,7 @@
         ac->oc[1].m4ac.sample_rate     = hdr_info.sample_rate;
         ac->oc[1].m4ac.sampling_index  = hdr_info.sampling_index;
         ac->oc[1].m4ac.object_type     = hdr_info.object_type;
+        ac->oc[1].m4ac.frame_length_short = 0;
         if (ac->oc[0].status != OC_LOCKED ||
             ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
             ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
@@ -2851,11 +2864,12 @@
                                int *got_frame_ptr, GetBitContext *gb)
 {
     AACContext *ac = avctx->priv_data;
+    const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
     ChannelElement *che;
     int err, i;
-    int samples = 1024;
-    int chan_config = ac->oc[1].m4ac.chan_config;
-    int aot = ac->oc[1].m4ac.object_type;
+    int samples = m4ac->frame_length_short ? 960 : 1024;
+    int chan_config = m4ac->chan_config;
+    int aot = m4ac->object_type;
 
     if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
         samples >>= 1;
@@ -2867,13 +2881,13 @@
 
     // The FF_PROFILE_AAC_* defines are all object_type - 1
     // This may lead to an undefined profile being signaled
-    ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
+    ac->avctx->profile = aot - 1;
 
     ac->tags_mapped = 0;
 
     if (chan_config < 0 || chan_config >= 8) {
         avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
-                              ac->oc[1].m4ac.chan_config);
+                              chan_config);
         return AVERROR_INVALIDDATA;
     }
     for (i = 0; i < tags_per_config[chan_config]; i++) {
@@ -3169,6 +3183,7 @@
     ff_mdct_end(&ac->mdct_small);
     ff_mdct_end(&ac->mdct_ld);
     ff_mdct_end(&ac->mdct_ltp);
+    ff_imdct15_uninit(&ac->mdct480);
     av_freep(&ac->fdsp);
     return 0;
 }
@@ -3427,7 +3442,17 @@
         return AVERROR_INVALIDDATA;
     }
 
-    if ((err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb, avpkt)) < 0)
+    switch (latmctx->aac_ctx.oc[1].m4ac.object_type) {
+    case AOT_ER_AAC_LC:
+    case AOT_ER_AAC_LTP:
+    case AOT_ER_AAC_LD:
+    case AOT_ER_AAC_ELD:
+        err = aac_decode_er_frame(avctx, out, got_frame_ptr, &gb);
+        break;
+    default:
+        err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb, avpkt);
+    }
+    if (err < 0)
         return err;
 
     return muxlength;
diff --git a/libavcodec/aacenc.c b/libavcodec/aacenc.c
index 635123e..7015a27 100644
--- a/libavcodec/aacenc.c
+++ b/libavcodec/aacenc.c
@@ -53,6 +53,11 @@
         return AVERROR(EINVAL); \
     }
 
+#define WARN_IF(cond, ...) \
+    if (cond) { \
+        av_log(avctx, AV_LOG_WARNING, __VA_ARGS__); \
+    }
+
 float ff_aac_pow34sf_tab[428];
 
 static const uint8_t swb_size_1024_96[] = {
@@ -102,7 +107,8 @@
     swb_size_1024_96, swb_size_1024_96, swb_size_1024_64,
     swb_size_1024_48, swb_size_1024_48, swb_size_1024_32,
     swb_size_1024_24, swb_size_1024_24, swb_size_1024_16,
-    swb_size_1024_16, swb_size_1024_16, swb_size_1024_8
+    swb_size_1024_16, swb_size_1024_16, swb_size_1024_8,
+    swb_size_1024_8
 };
 
 static const uint8_t swb_size_128_96[] = {
@@ -131,7 +137,8 @@
     swb_size_128_96, swb_size_128_96, swb_size_128_96,
     swb_size_128_48, swb_size_128_48, swb_size_128_48,
     swb_size_128_24, swb_size_128_24, swb_size_128_16,
-    swb_size_128_16, swb_size_128_16, swb_size_128_8
+    swb_size_128_16, swb_size_128_16, swb_size_128_8,
+    swb_size_128_8
 };
 
 /** default channel configurations */
@@ -165,7 +172,7 @@
     PutBitContext pb;
     AACEncContext *s = avctx->priv_data;
 
-    init_put_bits(&pb, avctx->extradata, avctx->extradata_size*8);
+    init_put_bits(&pb, avctx->extradata, avctx->extradata_size);
     put_bits(&pb, 5, 2); //object type - AAC-LC
     put_bits(&pb, 4, s->samplerate_index); //sample rate index
     put_bits(&pb, 4, s->channels);
@@ -260,6 +267,7 @@
         for (i = 0; i < 1024; i += 128)
             s->mdct128.mdct_calc(&s->mdct128, sce->coeffs + i, output + i*2);
     memcpy(audio, audio + 1024, sizeof(audio[0]) * 1024);
+    memcpy(sce->pcoeffs, sce->coeffs, sizeof(sce->pcoeffs));
 }
 
 /**
@@ -311,20 +319,23 @@
         start = 0;
         maxsfb = 0;
         cpe->ch[ch].pulse.num_pulse = 0;
-        for (w = 0; w < ics->num_windows*16; w += 16) {
-            for (g = 0; g < ics->num_swb; g++) {
-                //apply M/S
-                if (cpe->common_window && !ch && cpe->ms_mask[w + g]) {
-                    for (i = 0; i < ics->swb_sizes[g]; i++) {
-                        cpe->ch[0].coeffs[start+i] = (cpe->ch[0].coeffs[start+i] + cpe->ch[1].coeffs[start+i]) / 2.0;
-                        cpe->ch[1].coeffs[start+i] =  cpe->ch[0].coeffs[start+i] - cpe->ch[1].coeffs[start+i];
+        for (w = 0; w < ics->num_windows; w += ics->group_len[w]) {
+            for (w2 = 0; w2 < ics->group_len[w]; w2++) {
+                start = (w+w2) * 128;
+                for (g = 0; g < ics->num_swb; g++) {
+                    //apply M/S
+                    if (cpe->common_window && !ch && cpe->ms_mask[w*16 + g]) {
+                        for (i = 0; i < ics->swb_sizes[g]; i++) {
+                            cpe->ch[0].coeffs[start+i] = (cpe->ch[0].pcoeffs[start+i] + cpe->ch[1].pcoeffs[start+i]) * 0.5f;
+                            cpe->ch[1].coeffs[start+i] = cpe->ch[0].coeffs[start+i] - cpe->ch[1].pcoeffs[start+i];
+                        }
                     }
+                    start += ics->swb_sizes[g];
                 }
-                start += ics->swb_sizes[g];
+                for (cmaxsfb = ics->num_swb; cmaxsfb > 0 && cpe->ch[ch].zeroes[w*16+cmaxsfb-1]; cmaxsfb--)
+                    ;
+                maxsfb = FFMAX(maxsfb, cmaxsfb);
             }
-            for (cmaxsfb = ics->num_swb; cmaxsfb > 0 && cpe->ch[ch].zeroes[w+cmaxsfb-1]; cmaxsfb--)
-                ;
-            maxsfb = FFMAX(maxsfb, cmaxsfb);
         }
         ics->max_sfb = maxsfb;
 
@@ -507,7 +518,7 @@
     AACEncContext *s = avctx->priv_data;
     float **samples = s->planar_samples, *samples2, *la, *overlap;
     ChannelElement *cpe;
-    int i, ch, w, g, chans, tag, start_ch, ret;
+    int i, ch, w, g, chans, tag, start_ch, ret, ms_mode = 0;
     int chan_el_counter[4];
     FFPsyWindowInfo windows[AAC_MAX_CHANNELS];
 
@@ -630,6 +641,7 @@
                 if (cpe->common_window) {
                     put_ics_info(s, &cpe->ch[0].ics);
                     encode_ms_info(&s->pb, cpe);
+                    if (cpe->ms_mode) ms_mode = 1;
                 }
             }
             for (ch = 0; ch < chans; ch++) {
@@ -644,6 +656,15 @@
             s->psy.bitres.bits = frame_bits / s->channels;
             break;
         }
+        if (ms_mode) {
+            for (i = 0; i < s->chan_map[0]; i++) {
+                // Must restore coeffs
+                chans = tag == TYPE_CPE ? 2 : 1;
+                cpe = &s->cpe[i];
+                for (ch = 0; ch < chans; ch++)
+                    memcpy(cpe->ch[ch].coeffs, cpe->ch[ch].pcoeffs, sizeof(cpe->ch[ch].coeffs));
+            }
+        }
 
         s->lambda *= avctx->bit_rate * 1024.0f / avctx->sample_rate / frame_bits;
 
@@ -740,14 +761,20 @@
 
     s->channels = avctx->channels;
 
-    ERROR_IF(i == 16,
+    ERROR_IF(i == 16
+                || i >= (sizeof(swb_size_1024) / sizeof(*swb_size_1024))
+                || i >= (sizeof(swb_size_128) / sizeof(*swb_size_128)),
              "Unsupported sample rate %d\n", avctx->sample_rate);
     ERROR_IF(s->channels > AAC_MAX_CHANNELS,
              "Unsupported number of channels: %d\n", s->channels);
     ERROR_IF(avctx->profile != FF_PROFILE_UNKNOWN && avctx->profile != FF_PROFILE_AAC_LOW,
              "Unsupported profile %d\n", avctx->profile);
-    ERROR_IF(1024.0 * avctx->bit_rate / avctx->sample_rate > 6144 * s->channels,
-             "Too many bits per frame requested\n");
+    WARN_IF(1024.0 * avctx->bit_rate / avctx->sample_rate > 6144 * s->channels,
+             "Too many bits per frame requested, clamping to max\n");
+
+    avctx->bit_rate = (int)FFMIN(
+        6144 * s->channels / 1024.0 * avctx->sample_rate,
+        avctx->bit_rate);
 
     s->samplerate_index = i;
 
diff --git a/libavcodec/aacpsy.c b/libavcodec/aacpsy.c
index 9eeb836..d1e65f6 100644
--- a/libavcodec/aacpsy.c
+++ b/libavcodec/aacpsy.c
@@ -162,7 +162,7 @@
 /**
  * LAME psy model preset struct
  */
-typedef struct {
+typedef struct PsyLamePreset {
     int   quality;  ///< Quality to map the rest of the vaules to.
      /* This is overloaded to be both kbps per channel in ABR mode, and
       * requested quality in constant quality mode.
@@ -717,7 +717,7 @@
             }
             desired_pe_no_ah = FFMAX(desired_pe - (pe - pe_no_ah), 0.0f);
             if (active_lines > 0.0f)
-                reduction += calc_reduction_3gpp(a, desired_pe_no_ah, pe_no_ah, active_lines);
+                reduction = calc_reduction_3gpp(a, desired_pe_no_ah, pe_no_ah, active_lines);
 
             pe = 0.0f;
             for (w = 0; w < wi->num_windows*16; w += 16) {
diff --git a/libavcodec/aacsbr.c b/libavcodec/aacsbr.c
index 94a5685..b582d3f 100644
--- a/libavcodec/aacsbr.c
+++ b/libavcodec/aacsbr.c
@@ -635,7 +635,7 @@
                          GetBitContext *gb, SBRData *ch_data)
 {
     int i;
-    unsigned bs_pointer = 0;
+    int bs_pointer = 0;
     // frameLengthFlag ? 15 : 16; 960 sample length frames unsupported; this value is numTimeSlots
     int abs_bord_trail = 16;
     int num_rel_lead, num_rel_trail;
@@ -728,6 +728,7 @@
         break;
     }
 
+    av_assert0(bs_pointer >= 0);
     if (bs_pointer > ch_data->bs_num_env + 1) {
         av_log(ac->avctx, AV_LOG_ERROR,
                "Invalid bitstream, bs_pointer points to a middle noise border outside the time borders table: %d\n",
@@ -747,11 +748,11 @@
     ch_data->t_q[0]                     = ch_data->t_env[0];
     ch_data->t_q[ch_data->bs_num_noise] = ch_data->t_env[ch_data->bs_num_env];
     if (ch_data->bs_num_noise > 1) {
-        unsigned int idx;
+        int idx;
         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((int)bs_pointer - 1, 1);
+            idx = ch_data->bs_num_env - FFMAX(bs_pointer - 1, 1);
         } else { // VARFIX
             if (!bs_pointer)
                 idx = 1;
diff --git a/libavcodec/aactab.c b/libavcodec/aactab.c
index eb882e8..25f6de2 100644
--- a/libavcodec/aactab.c
+++ b/libavcodec/aactab.c
@@ -44,6 +44,10 @@
      0,  0,  0, 36, 36, 37, 31, 31,  0,  0,  0,  0,  0
 };
 
+const uint8_t ff_aac_num_swb_480[] = {
+     0,  0,  0, 35, 35, 37, 30, 30,  0,  0,  0,  0,  0
+};
+
 const uint8_t ff_aac_num_swb_128[] = {
     12, 12, 12, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15
 };
@@ -1126,6 +1130,14 @@
     364, 396, 428, 460, 512
 };
 
+static const uint16_t swb_offset_480_48[] = {
+      0,   4,   8,  12,  16,  20,  24,  28,
+     32,  36,  40,  44,  48,  52,  56,  64,
+     72,  80,  88,  96, 108, 120, 132, 144,
+    156, 172, 188, 212, 240, 272, 304, 336,
+    368, 400, 432, 480
+};
+
 static const uint16_t swb_offset_128_48[] = {
      0,   4,   8,  12,  16,  20,  28,  36,
     44,  56,  68,  80,  96, 112, 128
@@ -1149,6 +1161,14 @@
     352, 384, 416, 448, 480, 512
 };
 
+static const uint16_t swb_offset_480_32[] = {
+      0,   4,   8,  12,  16,  20,  24,  28,
+     32,  36,  40,  44,  48,  52,  56,  60,
+     64,  72,  80,  88,  96, 104, 112, 124,
+    136, 148, 164, 180, 200, 224, 256, 288,
+    320, 352, 384, 416, 448, 480
+ };
+
 static const uint16_t swb_offset_1024_24[] = {
       0,   4,   8,  12,  16,  20,  24,  28,
      32,  36,  40,  44,  52,  60,  68,  76,
@@ -1165,6 +1185,13 @@
     288, 320, 352, 384, 416, 448, 480, 512,
 };
 
+static const uint16_t swb_offset_480_24[] = {
+      0,   4,   8,  12,  16,  20,  24,  28,
+     32,  36,  40,  44,  52,  60,  68,  80,
+     92, 104, 120, 140, 164, 192, 224, 256,
+    288, 320, 352, 384, 416, 448, 480
+};
+
 static const uint16_t swb_offset_128_24[] = {
      0,   4,   8,  12,  16,  20,  24,  28,
     36,  44,  52,  64,  76,  92, 108, 128
@@ -1214,6 +1241,14 @@
     NULL
 };
 
+const uint16_t * const ff_swb_offset_480[] = {
+    NULL,               NULL,               NULL,
+    swb_offset_480_48,  swb_offset_480_48,  swb_offset_480_32,
+    swb_offset_480_24,  swb_offset_480_24,  NULL,
+    NULL,               NULL,               NULL,
+    NULL
+};
+
 const uint16_t * const ff_swb_offset_128[] = {
     /* The last entry on the following row is swb_offset_128_64 but is a
        duplicate of swb_offset_128_96. */
@@ -1240,12 +1275,16 @@
     0, 0, 0, 31, 32, 37, 31, 31, 0, 0, 0, 0, 0
 };
 
+const uint8_t ff_tns_max_bands_480[] = {
+    0, 0, 0, 31, 32, 37, 30, 30, 0, 0, 0, 0, 0
+};
+
 const uint8_t ff_tns_max_bands_128[] = {
     9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14
 };
 // @}
 
-const DECLARE_ALIGNED(32, float, ff_aac_eld_window)[1920] = {
+const DECLARE_ALIGNED(32, float, ff_aac_eld_window_512)[1920] = {
      0.00338834,  0.00567745,  0.00847677,  0.01172641,
      0.01532555,  0.01917664,  0.02318809,  0.02729259,
      0.03144503,  0.03560261,  0.03972499,  0.04379783,
@@ -1727,3 +1766,456 @@
     -0.00116552, -0.00115223, -0.00113877, -0.00112517,
     -0.00111144, -0.00109764, -0.00108377, -0.00106989,
 };
+
+const DECLARE_ALIGNED(32, float, ff_aac_eld_window_480)[1800] = {
+     0.00101191,  0.00440397,  0.00718669,  0.01072130,
+     0.01459757,  0.01875954,  0.02308987,  0.02751541,
+     0.03198130,  0.03643738,  0.04085290,  0.04522835,
+     0.04957620,  0.05390454,  0.05821503,  0.06251214,
+     0.06680463,  0.07109582,  0.07538014,  0.07965207,
+     0.08390857,  0.08815177,  0.09238785,  0.09662163,
+     0.10085860,  0.10510892,  0.10938110,  0.11367819,
+     0.11800355,  0.12236410,  0.12676834,  0.13122384,
+     0.13573476,  0.14030106,  0.14492340,  0.14960315,
+     0.15433828,  0.15912396,  0.16395663,  0.16883310,
+     0.17374837,  0.17869679,  0.18367394,  0.18867661,
+     0.19370368,  0.19875413,  0.20382641,  0.20892055,
+     0.21403775,  0.21917761,  0.22433899,  0.22952250,
+     0.23472991,  0.23996189,  0.24521859,  0.25049930,
+     0.25580312,  0.26112942,  0.26647748,  0.27184703,
+     0.27723785,  0.28264967,  0.28808086,  0.29352832,
+     0.29898979,  0.30446379,  0.30994292,  0.31541664,
+     0.32087942,  0.32632772,  0.33176291,  0.33718641,
+     0.34259612,  0.34799346,  0.35338857,  0.35878843,
+     0.36419504,  0.36960630,  0.37501567,  0.38042067,
+     0.38582069,  0.39121276,  0.39659312,  0.40195993,
+     0.40731155,  0.41264382,  0.41795277,  0.42323670,
+     0.42849480,  0.43372753,  0.43893452,  0.44411398,
+     0.44927117,  0.45441882,  0.45956191,  0.46470167,
+     0.46983016,  0.47493636,  0.48001827,  0.48507480,
+     0.49010240,  0.49509781,  0.50005986,  0.50499037,
+     0.50989790,  0.51478708,  0.51965805,  0.52450975,
+     0.52933955,  0.53414668,  0.53893113,  0.54369178,
+     0.54842731,  0.55313757,  0.55782259,  0.56248253,
+     0.56711762,  0.57172819,  0.57631468,  0.58087761,
+     0.58719976,  0.59173064,  0.59623644,  0.60071719,
+     0.60517294,  0.60960372,  0.61400958,  0.61839056,
+     0.62274670,  0.62707805,  0.63138475,  0.63566700,
+     0.63992500,  0.64415895,  0.64836893,  0.65255499,
+     0.65671715,  0.66085548,  0.66497005,  0.66906094,
+     0.67312824,  0.67717199,  0.68119219,  0.68518882,
+     0.68916187,  0.69311129,  0.69703698,  0.70093884,
+     0.70481679,  0.70867071,  0.71250047,  0.71630596,
+     0.72008705,  0.72384360,  0.72757549,  0.73128256,
+     0.73496463,  0.73862141,  0.74225263,  0.74585799,
+     0.74943730,  0.75299039,  0.75651711,  0.76001729,
+     0.76349062,  0.76693670,  0.77035516,  0.77374564,
+     0.77710790,  0.78044169,  0.78374678,  0.78702291,
+     0.79026979,  0.79348715,  0.79667471,  0.79983215,
+     0.80295914,  0.80605536,  0.80912047,  0.81215417,
+     0.81515616,  0.81812616,  0.82106389,  0.82396915,
+     0.82684176,  0.82968154,  0.83248830,  0.83526186,
+     0.83800204,  0.84070866,  0.84338156,  0.84602058,
+     0.84862556,  0.85119636,  0.85373292,  0.85623523,
+     0.85870326,  0.86113701,  0.86353649,  0.86590173,
+     0.86823275,  0.87052968,  0.87279275,  0.87502220,
+     0.87721829,  0.87938130,  0.88151157,  0.88360940,
+     0.88567517,  0.88770954,  0.88971328,  0.89168716,
+     0.89363199,  0.89554856,  0.89743771,  0.89930025,
+     0.90113740,  0.90295086,  0.90474240,  0.90651380,
+     0.90826684,  0.91000335,  0.91172515,  0.91343416,
+     0.91513276,  0.91682357,  0.91850924,  0.92019170,
+     0.92187129,  0.92354778,  0.92522116,  0.92688597,
+     0.92852960,  0.93013861,  0.93169897,  0.93319114,
+     0.93458502,  0.93587626,  0.93694276,  0.93825562,
+     0.93882222,  0.93910780,  0.93944183,  0.93981497,
+     0.94021434,  0.94062629,  0.94103714,  0.94144084,
+     0.94184042,  0.94223966,  0.94264206,  0.94304859,
+     0.94345831,  0.94387033,  0.94428390,  0.94469895,
+     0.94511572,  0.94553441,  0.94595520,  0.94637816,
+     0.94680335,  0.94723080,  0.94766054,  0.94809253,
+     0.94852674,  0.94896314,  0.94940178,  0.94984276,
+     0.95028618,  0.95073213,  0.95118056,  0.95163139,
+     0.95208451,  0.95253992,  0.95299770,  0.95345799,
+     0.95392092,  0.95438653,  0.95485472,  0.95532539,
+     0.95579847,  0.95627397,  0.95675201,  0.95723273,
+     0.95771618,  0.95820232,  0.95869103,  0.95918218,
+     0.95967573,  0.96017172,  0.96067026,  0.96117144,
+     0.96167526,  0.96218157,  0.96269026,  0.96320119,
+     0.96371437,  0.96422988,  0.96474782,  0.96526824,
+     0.96579106,  0.96631614,  0.96684334,  0.96737257,
+     0.96790390,  0.96843740,  0.96897315,  0.96951112,
+     0.97005119,  0.97059318,  0.97113697,  0.97168253,
+     0.97222994,  0.97277928,  0.97333058,  0.97388375,
+     0.97443863,  0.97499505,  0.97555292,  0.97611230,
+     0.97667326,  0.97723589,  0.97780016,  0.97836591,
+     0.97893300,  0.97950127,  0.98007071,  0.98064139,
+     0.98121342,  0.98178684,  0.98236156,  0.98293743,
+     0.98351428,  0.98409205,  0.98467078,  0.98525056,
+     0.98583146,  0.98641348,  0.98699650,  0.98758037,
+     0.98816497,  0.98875030,  0.98933647,  0.98992356,
+     0.99051163,  0.99110062,  0.99169038,  0.99228079,
+     0.99287177,  0.99346341,  0.99405581,  0.99464907,
+     0.99524320,  0.99583812,  0.99643375,  0.99702997,
+     0.99762671,  0.99822386,  0.99882134,  0.99941903,
+     1.00058131,  1.00118006,  1.00177930,  1.00237893,
+     1.00297887,  1.00357902,  1.00417927,  1.00477954,
+     1.00537972,  1.00597973,  1.00657959,  1.00717940,
+     1.00777926,  1.00837925,  1.00897929,  1.00957926,
+     1.01017901,  1.01077847,  1.01137769,  1.01197678,
+     1.01257582,  1.01317482,  1.01377365,  1.01437217,
+     1.01497025,  1.01556786,  1.01616510,  1.01676205,
+     1.01735876,  1.01795514,  1.01855103,  1.01914627,
+     1.01974076,  1.02033455,  1.02092772,  1.02152037,
+     1.02211247,  1.02270387,  1.02329439,  1.02388387,
+     1.02447229,  1.02505972,  1.02564624,  1.02623190,
+     1.02681660,  1.02740017,  1.02798242,  1.02856326,
+     1.02914272,  1.02972087,  1.03029778,  1.03087344,
+     1.03144768,  1.03202035,  1.03259127,  1.03316042,
+     1.03372788,  1.03429373,  1.03485801,  1.03542064,
+     1.03598146,  1.03654030,  1.03709708,  1.03765185,
+     1.03820470,  1.03875571,  1.03930488,  1.03985206,
+     1.04039712,  1.04093989,  1.04148037,  1.04201865,
+     1.04255481,  1.04308893,  1.04362093,  1.04415068,
+     1.04467803,  1.04520292,  1.04572542,  1.04624566,
+     1.04676376,  1.04727974,  1.04779350,  1.04830493,
+     1.04881391,  1.04932048,  1.04982477,  1.05032693,
+     1.05082705,  1.05132510,  1.05182098,  1.05231457,
+     1.05280584,  1.05329485,  1.05378171,  1.05426654,
+     1.05474937,  1.05523018,  1.05570892,  1.05618554,
+     1.05666005,  1.05713251,  1.05760297,  1.05807149,
+     1.05853828,  1.05900355,  1.05946756,  1.05993024,
+     1.06039075,  1.06084806,  1.06130111,  1.06175099,
+     1.06220164,  1.06265732,  1.06312146,  1.06358726,
+     1.06403924,  1.06446186,  1.06484048,  1.06516440,
+     1.06527864,  1.06498077,  1.06470196,  1.06425743,
+     1.06372091,  1.06311464,  1.06246622,  1.06179277,
+     1.06110808,  1.06042455,  1.05974495,  1.05906206,
+     1.05836706,  1.05765243,  1.05691470,  1.05615178,
+     1.05536069,  1.05454152,  1.05370030,  1.05284445,
+     1.05198094,  1.05111433,  1.05024634,  1.04937859,
+     1.04851245,  1.04764614,  1.04677586,  1.04589855,
+     1.04501046,  1.04410500,  1.04317417,  1.04221010,
+     1.04120649,  1.04016012,  1.03906851,  1.03792894,
+     1.03674090,  1.03550649,  1.03422800,  1.03290769,
+     1.03154944,  1.03015834,  1.02873938,  1.02729712,
+     1.02583470,  1.02435463,  1.02285952,  1.02135114,
+     1.01982974,  1.01829520,  1.01674752,  1.01518534,
+     1.01360559,  1.01200510,  1.01038076,  1.00872996,
+     1.00705045,  1.00533999,  1.00359618,  1.00181613,
+     0.99999673,  0.99813477,  0.99622793,  0.99427571,
+     0.99227814,  0.99023501,  0.98815128,  0.98603857,
+     0.98390898,  0.98177413,  0.97964151,  0.97751528,
+     0.97539999,  0.97329751,  0.97119933,  0.96909179,
+     0.96696152,  0.96479824,  0.96259840,  0.96036028,
+     0.95808180,  0.95576295,  0.95340622,  0.95101436,
+     0.94859030,  0.94614009,  0.94367232,  0.94119555,
+     0.93871796,  0.93624630,  0.93378636,  0.93134465,
+     0.92892076,  0.92649974,  0.92406255,  0.92159041,
+     0.91907411,  0.91651711,  0.91392425,  0.91130056,
+     0.90865471,  0.90599838,  0.90334350,  0.90069934,
+     0.89806435,  0.89543132,  0.89279335,  0.89014496,
+     0.88748403,  0.88480945,  0.88211997,  0.87941558,
+     0.87669794,  0.87396891,  0.87123030,  0.86848394,
+     0.86573164,  0.86297523,  0.86021649,  0.85745725,
+     0.85474342,  0.85193656,  0.84911455,  0.84627969,
+     0.84343424,  0.84058046,  0.83772057,  0.83485680,
+     0.83199134,  0.82912621,  0.82626143,  0.82339529,
+     0.82052619,  0.81765147,  0.81476433,  0.81185593,
+     0.80891701,  0.80594452,  0.80294885,  0.79994431,
+     0.79694485,  0.79396166,  0.79100220,  0.78807349,
+     0.78518123,  0.78231422,  0.77944709,  0.77655407,
+     0.77361369,  0.77062281,  0.76758806,  0.76451506,
+     0.76141145,  0.75828860,  0.75515892,  0.75203479,
+     0.74892561,  0.74583682,  0.74277342,  0.73974008,
+     0.73673754,  0.73376310,  0.73081444,  0.72788616,
+     0.72496070,  0.72201426,  0.71902283,  0.71596990,
+     0.71285541,  0.70968427,  0.70646064,  0.70319589,
+     0.69991077,  0.69662714,  0.69336592,  0.69013742,
+     0.68694302,  0.68378420,  0.68066143,  0.67757157,
+     0.67450951,  0.67147030,  0.66844879,  0.66543949,
+     0.66243677,  0.65943505,  0.65642754,  0.65340591,
+     0.65036160,  0.64728630,  0.64417440,  0.64102268,
+     0.63782771,  0.63458757,  0.63130628,  0.62799109,
+     0.62464879,  0.62128816,  0.61792203,  0.61456438,
+     0.61122915,  0.60792802,  0.60466971,  0.60146257,
+     0.59831460,  0.59522876,  0.59220375,  0.58923859,
+     0.58632936,  0.58346064,  0.58061078,  0.57775874,
+     0.57488246,  0.57195790,  0.56896078,  0.56586637,
+     0.56266594,  0.55937186,  0.55599898,  0.55256299,
+     0.54909184,  0.54562376,  0.54219742,  0.53884728,
+     0.53559047,  0.53243453,  0.52938894,  0.52645052,
+     0.52358958,  0.52076862,  0.51795080,  0.51510761,
+     0.51222179,  0.50927733,  0.50625944,  0.50317073,
+     0.50002767,  0.49685021,  0.49364116,  0.49048690,
+     0.48726128,  0.48404889,  0.48090875,  0.47783482,
+     0.47481564,  0.47184024,  0.46889391,  0.46595836,
+     0.46301611,  0.46005089,  0.45705924,  0.45404822,
+     0.45102447,  0.44799543,  0.44497138,  0.44196397,
+     0.43898547,  0.43604105,  0.43312057,  0.43020942,
+     0.42729337,  0.42436272,  0.42141388,  0.41844400,
+     0.41545081,  0.41244014,  0.40942464,  0.40641716,
+     0.40342874,  0.40046292,  0.39751923,  0.39459758,
+     0.39169692,  0.38881435,  0.38594643,  0.38308980,
+     0.38024146,  0.37739896,  0.37455986,  0.37172187,
+     0.36888463,  0.36604937,  0.36321735,  0.36038967,
+     0.35756668,  0.35474832,  0.35193455,  0.34912542,
+     0.34632129,  0.34352258,  0.34072974,  0.33794323,
+     0.33516354,  0.33239114,  0.32962648,  0.32686967,
+     0.32412042,  0.32137919,  0.31864044,  0.31588373,
+     0.31309909,  0.31028631,  0.30745528,  0.30462678,
+     0.30180656,  0.29899424,  0.29619082,  0.29339717,
+     0.29061333,  0.28783935,  0.28507563,  0.28232266,
+     0.27958067,  0.27684984,  0.27413017,  0.27142157,
+     0.26872396,  0.26603737,  0.26336211,  0.26069855,
+     0.25804700,  0.25540830,  0.25278329,  0.25017211,
+     0.24757451,  0.24498713,  0.24240740,  0.23983550,
+     0.23727200,  0.23471866,  0.23217624,  0.22964458,
+     0.22712346,  0.22461258,  0.22211202,  0.21962197,
+     0.21714290,  0.21467522,  0.21221877,  0.20977323,
+     0.20733693,  0.20490860,  0.20248823,  0.20007615,
+     0.19767358,  0.19528091,  0.19289781,  0.19052347,
+     0.18815661,  0.18579693,  0.18344441,  0.18110010,
+     0.17876595,  0.17644344,  0.17413400,  0.17183905,
+     0.16956003,  0.16729836,  0.16505547,  0.16283278,
+     0.15990780,  0.15776021,  0.15563325,  0.15352557,
+     0.15143584,  0.14936270,  0.14730481,  0.14526081,
+     0.14322937,  0.14120918,  0.13919977,  0.13720138,
+     0.13521422,  0.13323852,  0.13127445,  0.12932216,
+     0.12738181,  0.12545358,  0.12353773,  0.12163457,
+     0.11974436,  0.11786730,  0.11600347,  0.11415293,
+     0.11231573,  0.11049201,  0.10868196,  0.10688578,
+     0.10510362,  0.10333551,  0.10158143,  0.09984133,
+     0.09811524,  0.09640327,  0.09470556,  0.09302228,
+     0.09135347,  0.08969907,  0.08805903,  0.08643326,
+     0.08482183,  0.08322486,  0.08164249,  0.08007481,
+     0.07852179,  0.07698335,  0.07545938,  0.07394984,
+     0.07245482,  0.07097444,  0.06950883,  0.06805800,
+     0.06662187,  0.06520031,  0.06379324,  0.06240065,
+     0.06102266,  0.05965936,  0.05831084,  0.05697701,
+     0.05565775,  0.05435290,  0.05306239,  0.05178628,
+     0.05052464,  0.04927758,  0.04804510,  0.04682709,
+     0.04562344,  0.04443405,  0.04325893,  0.04209822,
+     0.04095208,  0.03982059,  0.03870371,  0.03760131,
+     0.03651325,  0.03543944,  0.03437987,  0.03333454,
+     0.03230348,  0.03128653,  0.03028332,  0.02929346,
+     0.02831658,  0.02735252,  0.02640127,  0.02546283,
+     0.02453725,  0.02362471,  0.02272547,  0.02183980,
+     0.02096810,  0.02011108,  0.01926957,  0.01844439,
+     0.01763565,  0.01684248,  0.01606394,  0.01529909,
+     0.01454726,  0.01380802,  0.01308092,  0.01236569,
+     0.01166273,  0.01097281,  0.01029671,  0.00963479,
+     0.00898646,  0.00835089,  0.00772725,  0.00711521,
+     0.00651513,  0.00592741,  0.00535249,  0.00479089,
+     0.00424328,  0.00371041,  0.00319271,  0.00268947,
+     0.00219928,  0.00172084,  0.00125271,  0.00079311,
+     0.00034023, -0.00010786, -0.00055144, -0.00098865,
+    -0.00141741, -0.00183557, -0.00224010, -0.00262725,
+    -0.00299314, -0.00333475, -0.00365250, -0.00394867,
+    -0.00422533, -0.00448528, -0.00473278, -0.00497252,
+    -0.00520916, -0.00544584, -0.00568360, -0.00592326,
+    -0.00616547, -0.00640861, -0.00664914, -0.00688354,
+    -0.00710845, -0.00732136, -0.00752022, -0.00770289,
+    -0.00786789, -0.00801521, -0.00814526, -0.00825839,
+    -0.00835563, -0.00843882, -0.00850996, -0.00857097,
+    -0.00862360, -0.00866943, -0.00871004, -0.00874688,
+    -0.00878091, -0.00881277, -0.00884320, -0.00887248,
+    -0.00890002, -0.00892494, -0.00894641, -0.00896355,
+    -0.00897541, -0.00898104, -0.00897948, -0.00896990,
+    -0.00895149, -0.00892346, -0.00888519, -0.00883670,
+    -0.00877839, -0.00871058, -0.00863388, -0.00854936,
+    -0.00845826, -0.00836179, -0.00826124, -0.00815807,
+    -0.00805372, -0.00794953, -0.00784572, -0.00774156,
+    -0.00763634, -0.00752929, -0.00741941, -0.00730556,
+    -0.00718664, -0.00706184, -0.00693107, -0.00679443,
+    -0.00665200, -0.00650428, -0.00635230, -0.00619718,
+    -0.00603995, -0.00588133, -0.00572169, -0.00556143,
+    -0.00540085, -0.00523988, -0.00507828, -0.00491582,
+    -0.00475220, -0.00458693, -0.00441953, -0.00424950,
+    -0.00407681, -0.00390204, -0.00372581, -0.00354874,
+    -0.00337115, -0.00319318, -0.00301494, -0.00283652,
+    -0.00265797, -0.00247934, -0.00230066, -0.00212197,
+    -0.00194331, -0.00176471, -0.00158620, -0.00140787,
+    -0.00122989, -0.00105244, -0.00087567, -0.00069976,
+    -0.00052487, -0.00035115, -0.00017875, -0.00000782,
+     0.00000779,  0.00017701,  0.00034552,  0.00051313,
+     0.00067966,  0.00084492,  0.00100873,  0.00117093,
+     0.00133133,  0.00148978,  0.00164611,  0.00180023,
+     0.00195211,  0.00210172,  0.00224898,  0.00239383,
+     0.00253618,  0.00267593,  0.00281306,  0.00294756,
+     0.00307942,  0.00320864,  0.00333502,  0.00345816,
+     0.00357762,  0.00369297,  0.00380414,  0.00391140,
+     0.00401499,  0.00411524,  0.00421242,  0.00430678,
+     0.00439859,  0.00448799,  0.00457487,  0.00465908,
+     0.00474045,  0.00481857,  0.00489277,  0.00496235,
+     0.00502666,  0.00508546,  0.00513877,  0.00518662,
+     0.00522904,  0.00526648,  0.00529956,  0.00532895,
+     0.00535532,  0.00537929,  0.00540141,  0.00542228,
+     0.00544196,  0.00545981,  0.00547515,  0.00548726,
+     0.00549542,  0.00549899,  0.00549732,  0.00548986,
+     0.00547633,  0.00545664,  0.00543067,  0.00539849,
+     0.00536061,  0.00531757,  0.00526993,  0.00521822,
+     0.00516300,  0.00510485,  0.00504432,  0.00498194,
+     0.00491822,  0.00485364,  0.00478862,  0.00472309,
+     0.00465675,  0.00458939,  0.00452067,  0.00445003,
+     0.00437688,  0.00430063,  0.00422062,  0.00413609,
+     0.00404632,  0.00395060,  0.00384863,  0.00374044,
+     0.00362600,  0.00350540,  0.00337934,  0.00324885,
+     0.00311486,  0.00297849,  0.00284122,  0.00270458,
+     0.00257013,  0.00243867,  0.00231005,  0.00218399,
+     0.00206023,  0.00193766,  0.00181460,  0.00168938,
+     0.00156050,  0.00142701,  0.00128830,  0.00114365,
+     0.00099297,  0.00083752,  0.00067884,  0.00051845,
+     0.00035760,  0.00019720,  0.00003813, -0.00011885,
+    -0.00027375, -0.00042718, -0.00057975, -0.00073204,
+    -0.00088453, -0.00103767, -0.00119192, -0.00134747,
+    -0.00150411, -0.00166151, -0.00181932, -0.00197723,
+    -0.00213493, -0.00229210, -0.00244849, -0.00260415,
+    -0.00275928, -0.00291410, -0.00306879, -0.00322332,
+    -0.00337759, -0.00353145, -0.00368470, -0.00383722,
+    -0.00398892, -0.00413972, -0.00428967, -0.00443889,
+    -0.00458749, -0.00473571, -0.00488366, -0.00503137,
+    -0.00517887, -0.00532610, -0.00547302, -0.00561965,
+    -0.00576598, -0.00591199, -0.00605766, -0.00620300,
+    -0.00634801, -0.00649273, -0.00663727, -0.00678170,
+    -0.00692617, -0.00707084, -0.00721583, -0.00736129,
+    -0.00750735, -0.00765415, -0.00780184, -0.00795059,
+    -0.00810058, -0.00825195, -0.00840487, -0.00855950,
+    -0.00871607, -0.00887480, -0.00903596, -0.00919978,
+    -0.00936650, -0.00953635, -0.00970931, -0.00988421,
+    -0.01005916, -0.01023208, -0.01040130, -0.01056627,
+    -0.01072678, -0.01088259, -0.01103348, -0.01117933,
+    -0.01132004, -0.01145552, -0.01158573, -0.01171065,
+    -0.01183025, -0.01194454, -0.01205352, -0.01215722,
+    -0.01225572, -0.01234911, -0.01243749, -0.01252102,
+    -0.01259985, -0.01267419, -0.01274437, -0.01281078,
+    -0.01287379, -0.01293350, -0.01298972, -0.01304224,
+    -0.01309086, -0.01313556, -0.01317644, -0.01321357,
+    -0.01324707, -0.01327697, -0.01330334, -0.01332622,
+    -0.01334570, -0.01336194, -0.01337510, -0.01338538,
+    -0.01339276, -0.01339708, -0.01339816, -0.01339584,
+    -0.01339014, -0.01338116, -0.01336903, -0.01335382,
+    -0.01333545, -0.01331381, -0.01328876, -0.01326033,
+    -0.01322880, -0.01319457, -0.01315806, -0.01311968,
+    -0.01307987, -0.01303906, -0.01299769, -0.01295623,
+    -0.01308207, -0.01304153, -0.01299802, -0.01295155,
+    -0.01290215, -0.01284980, -0.01279450, -0.01273625,
+    -0.01267501, -0.01261077, -0.01254347, -0.01247306,
+    -0.01239950, -0.01232277, -0.01224304, -0.01216055,
+    -0.01207554, -0.01198813, -0.01189829, -0.01180590,
+    -0.01171090, -0.01161335, -0.01151352, -0.01141167,
+    -0.01130807, -0.01120289, -0.01109626, -0.01098830,
+    -0.01087916, -0.01076898, -0.01065793, -0.01054618,
+    -0.01043380, -0.01032068, -0.01020670, -0.01009171,
+    -0.00997585, -0.00985959, -0.00974338, -0.00962765,
+    -0.00951273, -0.00939888, -0.00928634, -0.00917534,
+    -0.00906604, -0.00895860, -0.00885313, -0.00874977,
+    -0.00864862, -0.00854979, -0.00845337, -0.00835939,
+    -0.00826785, -0.00817872, -0.00809195, -0.00800745,
+    -0.00792506, -0.00784469, -0.00776588, -0.00768695,
+    -0.00760568, -0.00752004, -0.00742875, -0.00733186,
+    -0.00722976, -0.00712279, -0.00701130, -0.00689559,
+    -0.00677595, -0.00665269, -0.00652610, -0.00639649,
+    -0.00626417, -0.00612943, -0.00599252, -0.00585368,
+    -0.00571315, -0.00557115, -0.00542792, -0.00528367,
+    -0.00513864, -0.00499301, -0.00484693, -0.00470054,
+    -0.00455395, -0.00440733, -0.00426086, -0.00411471,
+    -0.00396904, -0.00382404, -0.00367991, -0.00353684,
+    -0.00339502, -0.00325472, -0.00311618, -0.00297967,
+    -0.00284531, -0.00271307, -0.00258290, -0.00245475,
+    -0.00232860, -0.00220447, -0.00208236, -0.00196233,
+    -0.00184450, -0.00172906, -0.00161620, -0.00150603,
+    -0.00139852, -0.00129358, -0.00119112, -0.00109115,
+    -0.00099375, -0.00089902, -0.00080705, -0.00071796,
+    -0.00063185, -0.00054886, -0.00046904, -0.00039231,
+    -0.00031845, -0.00024728, -0.00017860, -0.00011216,
+    -0.00004771,  0.00001500,  0.00007600,  0.00013501,
+     0.00019176,  0.00024595,  0.00029720,  0.00034504,
+     0.00038902,  0.00042881,  0.00046456,  0.00049662,
+     0.00052534,  0.00055114,  0.00057459,  0.00059629,
+     0.00061684,  0.00063660,  0.00065568,  0.00067417,
+     0.00069213,  0.00070935,  0.00072545,  0.00074005,
+     0.00075283,  0.00076356,  0.00077209,  0.00077828,
+     0.00078205,  0.00078350,  0.00078275,  0.00077992,
+     0.00077520,  0.00076884,  0.00076108,  0.00075218,
+     0.00074232,  0.00073170,  0.00072048,  0.00070881,
+     0.00069680,  0.00068450,  0.00067201,  0.00065934,
+     0.00064647,  0.00063335,  0.00061994,  0.00060621,
+     0.00059211,  0.00057763,  0.00056274,  0.00054743,
+     0.00053169,  0.00051553,  0.00049897,  0.00048206,
+     0.00046487,  0.00044748,  0.00042996,  0.00041241,
+     0.00039492,  0.00037759,  0.00036049,  0.00034371,
+     0.00032732,  0.00031137,  0.00029587,  0.00028079,
+     0.00026612,  0.00025183,  0.00023789,  0.00022428,
+     0.00021097,  0.00019797,  0.00018530,  0.00017297,
+     0.00016100,  0.00014942,  0.00013827,  0.00012757,
+     0.00011736,  0.00010764,  0.00009841,  0.00008969,
+     0.00008145,  0.00007369,  0.00006641,  0.00005958,
+     0.00005320,  0.00004725,  0.00004171,  0.00003659,
+     0.00003186,  0.00002752,  0.00002357,  0.00001999,
+     0.00001679,  0.00001392,  0.00001140,  0.00000918,
+     0.00000726,  0.00000562,  0.00000424,  0.00000309,
+     0.00000217,  0.00000143,  0.00000088,  0.00000048,
+     0.00000020,  0.00000004, -0.00000004, -0.00000006,
+    -0.00000004, -0.00000000,  0.00000002,  0.00000000,
+     0.00000000,  0.00000002, -0.00000000, -0.00000004,
+    -0.00000005, -0.00000004,  0.00000004,  0.00000019,
+     0.00000045,  0.00000083,  0.00000134,  0.00000201,
+     0.00000285,  0.00000387,  0.00000510,  0.00000654,
+     0.00000821,  0.00001011,  0.00001227,  0.00001468,
+     0.00001735,  0.00002030,  0.00002352,  0.00002702,
+     0.00003080,  0.00003486,  0.00003918,  0.00004379,
+     0.00004866,  0.00005382,  0.00005924,  0.00006495,
+     0.00007093,  0.00007719,  0.00008373,  0.00009053,
+     0.00009758,  0.00010488,  0.00011240,  0.00012010,
+     0.00012796,  0.00013596,  0.00014406,  0.00015226,
+     0.00016053,  0.00016886,  0.00017725,  0.00018571,
+     0.00019424,  0.00020286,  0.00021156,  0.00022037,
+     0.00022928,  0.00023825,  0.00024724,  0.00025621,
+     0.00026509,  0.00027385,  0.00028241,  0.00029072,
+     0.00029874,  0.00030643,  0.00031374,  0.00032065,
+     0.00032715,  0.00033325,  0.00033895,  0.00034425,
+     0.00034917,  0.00035374,  0.00035796,  0.00036187,
+     0.00036549,  0.00036883,  0.00037194,  0.00037479,
+     0.00037736,  0.00037963,  0.00038154,  0.00038306,
+     0.00038411,  0.00038462,  0.00038453,  0.00038373,
+     0.00038213,  0.00037965,  0.00037621,  0.00037179,
+     0.00036636,  0.00035989,  0.00035244,  0.00034407,
+     0.00033488,  0.00032497,  0.00031449,  0.00030361,
+     0.00029252,  0.00028133,  0.00027003,  0.00025862,
+     0.00024706,  0.00023524,  0.00022297,  0.00021004,
+     0.00019626,  0.00018150,  0.00016566,  0.00014864,
+     0.00013041,  0.00011112,  0.00009096,  0.00007014,
+     0.00004884,  0.00002718,  0.00000530, -0.00001667,
+    -0.00003871, -0.00006090, -0.00008331, -0.00010600,
+    -0.00012902, -0.00015244, -0.00017631, -0.00020065,
+    -0.00022541, -0.00025052, -0.00027594, -0.00030159,
+    -0.00032740, -0.00035332, -0.00037928, -0.00040527,
+    -0.00043131, -0.00045741, -0.00048357, -0.00050978,
+    -0.00053599, -0.00056217, -0.00058827, -0.00061423,
+    -0.00064002, -0.00066562, -0.00069100, -0.00071616,
+    -0.00074110, -0.00076584, -0.00079036, -0.00081465,
+    -0.00083869, -0.00086245, -0.00088590, -0.00090901,
+    -0.00093176, -0.00095413, -0.00097608, -0.00099758,
+    -0.00101862, -0.00103918, -0.00105924, -0.00107879,
+    -0.00109783, -0.00111635, -0.00113434, -0.00115181,
+    -0.00116873, -0.00118510, -0.00120091, -0.00121615,
+    -0.00123082, -0.00124490, -0.00125838, -0.00127125,
+    -0.00128350, -0.00129511, -0.00130610, -0.00131643,
+    -0.00132610, -0.00133509, -0.00134334, -0.00135069,
+    -0.00135711, -0.00136272, -0.00136768, -0.00137225,
+    -0.00137649, -0.00138042, -0.00138404, -0.00138737,
+    -0.00139041, -0.00139317, -0.00139565, -0.00139785,
+    -0.00139976, -0.00140137, -0.00140267, -0.00140366,
+    -0.00140432, -0.00140464, -0.00140461, -0.00140423,
+    -0.00140347, -0.00140235, -0.00140084, -0.00139894,
+    -0.00139664, -0.00139388, -0.00139065, -0.00138694,
+    -0.00138278, -0.00137818, -0.00137317, -0.00136772,
+    -0.00136185, -0.00135556, -0.00134884, -0.00134170,
+    -0.00133415, -0.00132619, -0.00131784, -0.00130908,
+    -0.00129991, -0.00129031, -0.00128031, -0.00126990,
+    -0.00125912, -0.00124797, -0.00123645, -0.00122458,
+    -0.00121233, -0.00119972, -0.00118676, -0.00117347,
+    -0.00115988, -0.00114605, -0.00113200, -0.00111778,
+    -0.00110343, -0.00108898, -0.00107448, -0.00105995,
+};
diff --git a/libavcodec/aactab.h b/libavcodec/aactab.h
index 5ed8508..9f5a7e4 100644
--- a/libavcodec/aactab.h
+++ b/libavcodec/aactab.h
@@ -46,7 +46,8 @@
  */
 DECLARE_ALIGNED(32, extern float,  ff_aac_kbd_long_1024)[1024];
 DECLARE_ALIGNED(32, extern float,  ff_aac_kbd_short_128)[128];
-const DECLARE_ALIGNED(32, extern float, ff_aac_eld_window)[1920];
+const DECLARE_ALIGNED(32, extern float, ff_aac_eld_window_512)[1920];
+const DECLARE_ALIGNED(32, extern float, ff_aac_eld_window_480)[1800];
 // @}
 
 /* @name number of scalefactor window bands for long and short transform windows respectively
@@ -54,6 +55,7 @@
  */
 extern const uint8_t ff_aac_num_swb_1024[];
 extern const uint8_t ff_aac_num_swb_512 [];
+extern const uint8_t ff_aac_num_swb_480 [];
 extern const uint8_t ff_aac_num_swb_128 [];
 // @}
 
@@ -72,10 +74,12 @@
 
 extern const uint16_t * const ff_swb_offset_1024[13];
 extern const uint16_t * const ff_swb_offset_512 [13];
+extern const uint16_t * const ff_swb_offset_480 [13];
 extern const uint16_t * const ff_swb_offset_128 [13];
 
 extern const uint8_t ff_tns_max_bands_1024[13];
 extern const uint8_t ff_tns_max_bands_512 [13];
+extern const uint8_t ff_tns_max_bands_480 [13];
 extern const uint8_t ff_tns_max_bands_128 [13];
 
 #endif /* AVCODEC_AACTAB_H */
diff --git a/libavcodec/aarch64/Makefile b/libavcodec/aarch64/Makefile
index 964428e..2afff29 100644
--- a/libavcodec/aarch64/Makefile
+++ b/libavcodec/aarch64/Makefile
@@ -3,11 +3,11 @@
 OBJS-$(CONFIG_H264DSP)                  += aarch64/h264dsp_init_aarch64.o
 OBJS-$(CONFIG_H264QPEL)                 += aarch64/h264qpel_init_aarch64.o
 OBJS-$(CONFIG_HPELDSP)                  += aarch64/hpeldsp_init_aarch64.o
+OBJS-$(CONFIG_IMDCT15)                  += aarch64/imdct15_init.o
 OBJS-$(CONFIG_MPEGAUDIODSP)             += aarch64/mpegaudiodsp_init.o
 OBJS-$(CONFIG_NEON_CLOBBER_TEST)        += aarch64/neontest.o
 OBJS-$(CONFIG_VIDEODSP)                 += aarch64/videodsp_init.o
 
-OBJS-$(CONFIG_OPUS_DECODER)             += aarch64/opus_imdct_init.o
 OBJS-$(CONFIG_RV40_DECODER)             += aarch64/rv40dsp_init_aarch64.o
 OBJS-$(CONFIG_VC1_DECODER)              += aarch64/vc1dsp_init_aarch64.o
 OBJS-$(CONFIG_VORBIS_DECODER)           += aarch64/vorbisdsp_init.o
@@ -21,8 +21,8 @@
 NEON-OBJS-$(CONFIG_H264QPEL)            += aarch64/h264qpel_neon.o             \
                                            aarch64/hpeldsp_neon.o
 NEON-OBJS-$(CONFIG_HPELDSP)             += aarch64/hpeldsp_neon.o
+NEON-OBJS-$(CONFIG_IMDCT15)             += aarch64/imdct15_neon.o
 NEON-OBJS-$(CONFIG_MPEGAUDIODSP)        += aarch64/mpegaudiodsp_neon.o
 NEON-OBJS-$(CONFIG_MDCT)                += aarch64/mdct_neon.o
 
-NEON-OBJS-$(CONFIG_OPUS_DECODER)        += aarch64/opus_imdct_neon.o
 NEON-OBJS-$(CONFIG_VORBIS_DECODER)      += aarch64/vorbisdsp_neon.o
diff --git a/libavcodec/aarch64/h264dsp_init_aarch64.c b/libavcodec/aarch64/h264dsp_init_aarch64.c
index ed5e4bd..e0f378f 100644
--- a/libavcodec/aarch64/h264dsp_init_aarch64.c
+++ b/libavcodec/aarch64/h264dsp_init_aarch64.c
@@ -78,6 +78,7 @@
         c->h264_v_loop_filter_luma   = ff_h264_v_loop_filter_luma_neon;
         c->h264_h_loop_filter_luma   = ff_h264_h_loop_filter_luma_neon;
         c->h264_v_loop_filter_chroma = ff_h264_v_loop_filter_chroma_neon;
+        if (chroma_format_idc <= 1)
         c->h264_h_loop_filter_chroma = ff_h264_h_loop_filter_chroma_neon;
 
         c->weight_h264_pixels_tab[0] = ff_weight_h264_pixels_16_neon;
diff --git a/libavcodec/aarch64/opus_imdct_init.c b/libavcodec/aarch64/imdct15_init.c
similarity index 66%
rename from libavcodec/aarch64/opus_imdct_init.c
rename to libavcodec/aarch64/imdct15_init.c
index 3fa9a11..58af9f0 100644
--- a/libavcodec/aarch64/opus_imdct_init.c
+++ b/libavcodec/aarch64/imdct15_init.c
@@ -21,21 +21,22 @@
 #include "libavutil/cpu.h"
 #include "libavutil/aarch64/cpu.h"
 #include "libavutil/internal.h"
-#include "libavcodec/opus_imdct.h"
+
+#include "libavcodec/imdct15.h"
 
 #include "asm-offsets.h"
 
-AV_CHECK_OFFSET(CeltIMDCTContext, exptab,         CELT_EXPTAB);
-AV_CHECK_OFFSET(CeltIMDCTContext, fft_n,          CELT_FFT_N);
-AV_CHECK_OFFSET(CeltIMDCTContext, len2,           CELT_LEN2);
-AV_CHECK_OFFSET(CeltIMDCTContext, len4,           CELT_LEN4);
-AV_CHECK_OFFSET(CeltIMDCTContext, tmp,            CELT_TMP);
-AV_CHECK_OFFSET(CeltIMDCTContext, twiddle_exptab, CELT_TWIDDLE);
+AV_CHECK_OFFSET(IMDCT15Context, exptab,         CELT_EXPTAB);
+AV_CHECK_OFFSET(IMDCT15Context, fft_n,          CELT_FFT_N);
+AV_CHECK_OFFSET(IMDCT15Context, len2,           CELT_LEN2);
+AV_CHECK_OFFSET(IMDCT15Context, len4,           CELT_LEN4);
+AV_CHECK_OFFSET(IMDCT15Context, tmp,            CELT_TMP);
+AV_CHECK_OFFSET(IMDCT15Context, twiddle_exptab, CELT_TWIDDLE);
 
-void ff_celt_imdct_half_neon(CeltIMDCTContext *s, float *dst, const float *src,
+void ff_celt_imdct_half_neon(IMDCT15Context *s, float *dst, const float *src,
                              ptrdiff_t stride, float scale);
 
-void ff_celt_imdct_init_aarch64(CeltIMDCTContext *s)
+void ff_imdct15_init_aarch64(IMDCT15Context *s)
 {
     int cpu_flags = av_get_cpu_flags();
 
diff --git a/libavcodec/aarch64/opus_imdct_neon.S b/libavcodec/aarch64/imdct15_neon.S
similarity index 100%
rename from libavcodec/aarch64/opus_imdct_neon.S
rename to libavcodec/aarch64/imdct15_neon.S
diff --git a/libavcodec/ac3.c b/libavcodec/ac3.c
index 29e132f..c4fc77c 100644
--- a/libavcodec/ac3.c
+++ b/libavcodec/ac3.c
@@ -200,9 +200,9 @@
             if (band >= AC3_CRITICAL_BANDS || dba_lengths[seg] > AC3_CRITICAL_BANDS-band)
                 return -1;
             if (dba_values[seg] >= 4) {
-                delta = (dba_values[seg] - 3) << 7;
+                delta = (dba_values[seg] - 3) * 128;
             } else {
-                delta = (dba_values[seg] - 4) << 7;
+                delta = (dba_values[seg] - 4) * 128;
             }
             for (i = 0; i < dba_lengths[seg]; i++) {
                 mask[band++] += delta;
diff --git a/libavcodec/ac3.h b/libavcodec/ac3.h
index 871640b..1fe30b9 100644
--- a/libavcodec/ac3.h
+++ b/libavcodec/ac3.h
@@ -67,8 +67,8 @@
 #define AC3_RENAME(x)           x ## _fixed
 #define AC3_NORM(norm)          (1<<24)/(norm)
 #define AC3_MUL(a,b)            ((((int64_t) (a)) * (b))>>12)
-#define AC3_RANGE(x)            (x|((x&128)<<1))
-#define AC3_HEAVY_RANGE(x)      (x<<1)
+#define AC3_RANGE(x)            ((x)|(((x)&128)<<1))
+#define AC3_HEAVY_RANGE(x)      ((x)<<1)
 #define AC3_DYNAMIC_RANGE(x)    (x)
 #define AC3_SPX_BLEND(x)        (x)
 #define AC3_DYNAMIC_RANGE1      0
diff --git a/libavcodec/ac3dec.c b/libavcodec/ac3dec.c
index d3e8713..e3bf292 100644
--- a/libavcodec/ac3dec.c
+++ b/libavcodec/ac3dec.c
@@ -112,7 +112,7 @@
 static inline int
 symmetric_dequant(int code, int levels)
 {
-    return ((code - (levels >> 1)) << 24) / levels;
+    return ((code - (levels >> 1)) * (1 << 24)) / levels;
 }
 
 /*
@@ -196,10 +196,10 @@
     s->fdsp = avpriv_alloc_fixed_dsp(avctx->flags & CODEC_FLAG_BITEXACT);
 #else
     s->fdsp = avpriv_float_dsp_alloc(avctx->flags & CODEC_FLAG_BITEXACT);
+    ff_fmt_convert_init(&s->fmt_conv, avctx);
 #endif
 
     ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
-    ff_fmt_convert_init(&s->fmt_conv, avctx);
     av_lfg_init(&s->dith_state, 0);
 
     if (USE_FIXED)
@@ -470,7 +470,7 @@
                 int cpl_coord = s->cpl_coords[ch][band] << 5;
                 for (bin = band_start; bin < band_end; bin++) {
                     s->fixed_coeffs[ch][bin] =
-                        MULH(s->fixed_coeffs[CPL_CH][bin] << 4, cpl_coord);
+                        MULH(s->fixed_coeffs[CPL_CH][bin] * (1 << 4), cpl_coord);
                 }
                 if (ch == 2 && s->phase_flags[band]) {
                     for (bin = band_start; bin < band_end; bin++)
@@ -485,7 +485,7 @@
 /**
  * Grouped mantissas for 3-level 5-level and 11-level quantization
  */
-typedef struct {
+typedef struct mant_groups {
     int b1_mant[2];
     int b2_mant[2];
     int b4_mant;
@@ -567,8 +567,7 @@
                 av_log(s->avctx, AV_LOG_ERROR, "bap %d is invalid in plain AC-3\n", bap);
                 bap = 15;
             }
-            mantissa = get_sbits(gbc, quantization_tab[bap]);
-            mantissa <<= 24 - quantization_tab[bap];
+            mantissa = (unsigned)get_sbits(gbc, quantization_tab[bap]) << (24 - quantization_tab[bap]);
             break;
         }
         coeffs[freq] = mantissa >> exps[freq];
@@ -872,7 +871,7 @@
                 start_subband += start_subband - 7;
             end_subband    = get_bits(gbc, 3) + 5;
 #if USE_FIXED
-            s->spx_dst_end_freq = end_freq_inv_tab[end_subband];
+            s->spx_dst_end_freq = end_freq_inv_tab[end_subband-5];
 #endif
             if (end_subband   > 7)
                 end_subband   += end_subband   - 7;
@@ -924,14 +923,13 @@
 
                     bin = s->spx_src_start_freq;
                     for (bnd = 0; bnd < s->num_spx_bands; bnd++) {
-                        int bandsize;
+                        int bandsize = s->spx_band_sizes[bnd];
                         int spx_coord_exp, spx_coord_mant;
                         INTFLOAT nratio, sblend, nblend;
 #if USE_FIXED
-                        int64_t accu;
                         /* calculate blending factors */
-                        bandsize = s->spx_band_sizes[bnd];
-                        accu = (int64_t)((bin << 23) + (bandsize << 22)) * s->spx_dst_end_freq;
+                        int64_t accu = ((bin << 23) + (bandsize << 22))
+                                     * (int64_t)s->spx_dst_end_freq;
                         nratio = (int)(accu >> 32);
                         nratio -= spx_blend << 18;
 
@@ -939,7 +937,7 @@
                             nblend = 0;
                             sblend = 0x800000;
                         } else if (nratio > 0x7fffff) {
-                            nblend = 0x800000;
+                            nblend = 14529495; // sqrt(3) in FP.23
                             sblend = 0;
                         } else {
                             nblend = fixed_sqrt(nratio, 23);
@@ -951,7 +949,6 @@
                         float spx_coord;
 
                         /* calculate blending factors */
-                        bandsize = s->spx_band_sizes[bnd];
                         nratio = ((float)((bin + (bandsize >> 1))) / s->spx_dst_end_freq) - spx_blend;
                         nratio = av_clipf(nratio, 0.0f, 1.0f);
                         nblend = sqrtf(3.0f * nratio); // noise is scaled by sqrt(3)
@@ -1429,7 +1426,8 @@
         memcpy(s->input_buffer, buf, FFMIN(buf_size, AC3_FRAME_BUFFER_SIZE));
     buf = s->input_buffer;
     /* initialize the GetBitContext with the start of valid AC-3 Frame */
-    init_get_bits(&s->gbc, buf, buf_size * 8);
+    if ((ret = init_get_bits8(&s->gbc, buf, buf_size)) < 0)
+        return ret;
 
     /* parse the syncinfo */
     err = parse_frame_header(s);
diff --git a/libavcodec/ac3dec.h b/libavcodec/ac3dec.h
index be29f00..5259c60 100644
--- a/libavcodec/ac3dec.h
+++ b/libavcodec/ac3dec.h
@@ -243,19 +243,19 @@
  * Parse the E-AC-3 frame header.
  * This parses both the bit stream info and audio frame header.
  */
-int ff_eac3_parse_header(AC3DecodeContext *s);
+static int ff_eac3_parse_header(AC3DecodeContext *s);
 
 /**
  * Decode mantissas in a single channel for the entire frame.
  * This is used when AHT mode is enabled.
  */
-void ff_eac3_decode_transform_coeffs_aht_ch(AC3DecodeContext *s, int ch);
+static void ff_eac3_decode_transform_coeffs_aht_ch(AC3DecodeContext *s, int ch);
 
 /**
  * Apply spectral extension to each channel by copying lower frequency
  * coefficients to higher frequency bins and applying side information to
  * approximate the original high frequency signal.
  */
-void ff_eac3_apply_spectral_extension(AC3DecodeContext *s);
+static void ff_eac3_apply_spectral_extension(AC3DecodeContext *s);
 
 #endif /* AVCODEC_AC3DEC_H */
diff --git a/libavcodec/ac3dec_fixed.c b/libavcodec/ac3dec_fixed.c
index cb3b251..b4beee6 100644
--- a/libavcodec/ac3dec_fixed.c
+++ b/libavcodec/ac3dec_fixed.c
@@ -164,6 +164,7 @@
     }
 }
 
+#include "eac3dec.c"
 #include "ac3dec.c"
 
 static const AVOption options[] = {
diff --git a/libavcodec/ac3dec_float.c b/libavcodec/ac3dec_float.c
index e7fc5cb..d74a0df 100644
--- a/libavcodec/ac3dec_float.c
+++ b/libavcodec/ac3dec_float.c
@@ -28,6 +28,7 @@
  * Upmix delay samples from stereo to original channel layout.
  */
 #include "ac3dec.h"
+#include "eac3dec.c"
 #include "ac3dec.c"
 
 static const AVOption options[] = {
diff --git a/libavcodec/ac3dsp.c b/libavcodec/ac3dsp.c
index b746817..fe87b5b 100644
--- a/libavcodec/ac3dsp.c
+++ b/libavcodec/ac3dsp.c
@@ -125,7 +125,7 @@
         band_end = FFMIN(band_end, end);
 
         for (; bin < band_end; bin++) {
-            int address = av_clip((psd[bin] - m) >> 5, 0, 63);
+            int address = av_clip_uintp2((psd[bin] - m) >> 5, 6);
             bap[bin] = bap_tab[address];
         }
     } while (end > band_end);
diff --git a/libavcodec/adpcm.c b/libavcodec/adpcm.c
index 7785a7a..1c3fdc4 100644
--- a/libavcodec/adpcm.c
+++ b/libavcodec/adpcm.c
@@ -269,7 +269,7 @@
     if (sign) predictor -= diff;
     else predictor += diff;
 
-    c->predictor = av_clip(predictor, -2048, 2047);
+    c->predictor = av_clip_intp2(predictor, 11);
     c->step_index = step_index;
 
     return c->predictor << 4;
diff --git a/libavcodec/adpcmenc.c b/libavcodec/adpcmenc.c
index ea6cc23..50872c3 100644
--- a/libavcodec/adpcmenc.c
+++ b/libavcodec/adpcmenc.c
@@ -227,7 +227,7 @@
         bias = -c->idelta / 2;
 
     nibble = (nibble + bias) / c->idelta;
-    nibble = av_clip(nibble, -8, 7) & 0x0F;
+    nibble = av_clip_intp2(nibble, 3) & 0x0F;
 
     predictor += ((nibble & 0x08) ? (nibble - 0x10) : nibble) * c->idelta;
 
@@ -541,7 +541,7 @@
     case AV_CODEC_ID_ADPCM_IMA_QT:
     {
         PutBitContext pb;
-        init_put_bits(&pb, dst, pkt_size * 8);
+        init_put_bits(&pb, dst, pkt_size);
 
         for (ch = 0; ch < avctx->channels; ch++) {
             ADPCMChannelStatus *status = &c->status[ch];
@@ -571,7 +571,7 @@
     case AV_CODEC_ID_ADPCM_SWF:
     {
         PutBitContext pb;
-        init_put_bits(&pb, dst, pkt_size * 8);
+        init_put_bits(&pb, dst, pkt_size);
 
         n = frame->nb_samples - 1;
 
@@ -581,7 +581,7 @@
         // init the encoder state
         for (i = 0; i < avctx->channels; i++) {
             // clip step so it fits 6 bits
-            c->status[i].step_index = av_clip(c->status[i].step_index, 0, 63);
+            c->status[i].step_index = av_clip_uintp2(c->status[i].step_index, 6);
             put_sbits(&pb, 16, samples[i]);
             put_bits(&pb, 6, c->status[i].step_index);
             c->status[i].prev_sample = samples[i];
diff --git a/libavcodec/adxenc.c b/libavcodec/adxenc.c
index 4387ffb..7736d09 100644
--- a/libavcodec/adxenc.c
+++ b/libavcodec/adxenc.c
@@ -81,7 +81,7 @@
     for (i = 0, j = 0; j < 32; i += channels, j++) {
         d = ((wav[i] << COEFF_BITS) - c->coeff[0] * s1 - c->coeff[1] * s2) >> COEFF_BITS;
 
-        d = av_clip(ROUNDED_DIV(d, scale), -8, 7);
+        d = av_clip_intp2(ROUNDED_DIV(d, scale), 3);
 
         put_sbits(&pb, 4, d);
 
diff --git a/libavcodec/aic.c b/libavcodec/aic.c
index e5e2236..648ccba 100644
--- a/libavcodec/aic.c
+++ b/libavcodec/aic.c
@@ -438,8 +438,8 @@
     ctx->mb_width  = FFALIGN(avctx->width,  16) >> 4;
     ctx->mb_height = FFALIGN(avctx->height, 16) >> 4;
 
-    ctx->num_x_slices = 16;
-    ctx->slice_width  = ctx->mb_width / 16;
+    ctx->num_x_slices = (ctx->mb_width + 15) >> 4;
+    ctx->slice_width  = 16;
     for (i = 1; i < 32; i++) {
         if (!(ctx->mb_width % i) && (ctx->mb_width / i < 32)) {
             ctx->slice_width  = ctx->mb_width / i;
diff --git a/libavcodec/alac.c b/libavcodec/alac.c
index aec7bb4..ffd2d77 100644
--- a/libavcodec/alac.c
+++ b/libavcodec/alac.c
@@ -60,7 +60,7 @@
 
 #define ALAC_EXTRADATA_SIZE 36
 
-typedef struct {
+typedef struct ALACContext {
     AVClass *class;
     AVCodecContext *avctx;
     GetBitContext gb;
diff --git a/libavcodec/allcodecs.c b/libavcodec/allcodecs.c
index 2fe3609..071446f 100644
--- a/libavcodec/allcodecs.c
+++ b/libavcodec/allcodecs.c
@@ -77,6 +77,7 @@
     REGISTER_HWACCEL(H263_VAAPI,        h263_vaapi);
     REGISTER_HWACCEL(H263_VDPAU,        h263_vdpau);
     REGISTER_HWACCEL(H264_DXVA2,        h264_dxva2);
+    REGISTER_HWACCEL(H264_QSV,          h264_qsv);
     REGISTER_HWACCEL(H264_VAAPI,        h264_vaapi);
     REGISTER_HWACCEL(H264_VDA,          h264_vda);
     REGISTER_HWACCEL(H264_VDA_OLD,      h264_vda_old);
@@ -170,10 +171,12 @@
     REGISTER_ENCDEC (H263P,             h263p);
     REGISTER_DECODER(H264,              h264);
     REGISTER_DECODER(H264_CRYSTALHD,    h264_crystalhd);
+    REGISTER_DECODER(H264_QSV,          h264_qsv);
     REGISTER_DECODER(H264_VDA,          h264_vda);
     REGISTER_DECODER(H264_VDPAU,        h264_vdpau);
     REGISTER_DECODER(HEVC,              hevc);
     REGISTER_DECODER(HNM4_VIDEO,        hnm4_video);
+    REGISTER_DECODER(HQX,               hqx);
     REGISTER_ENCDEC (HUFFYUV,           huffyuv);
     REGISTER_DECODER(IDCIN,             idcin);
     REGISTER_DECODER(IFF_BYTERUN1,      iff_byterun1);
@@ -266,6 +269,7 @@
     REGISTER_DECODER(SVQ3,              svq3);
     REGISTER_ENCDEC (TARGA,             targa);
     REGISTER_DECODER(TARGA_Y216,        targa_y216);
+    REGISTER_DECODER(TDSC,              tdsc);
     REGISTER_DECODER(THEORA,            theora);
     REGISTER_DECODER(THP,               thp);
     REGISTER_DECODER(TIERTEXSEQVIDEO,   tiertexseqvideo);
@@ -346,6 +350,7 @@
     REGISTER_DECODER(DSD_LSBF_PLANAR,   dsd_lsbf_planar);
     REGISTER_DECODER(DSD_MSBF_PLANAR,   dsd_msbf_planar);
     REGISTER_DECODER(DSICINAUDIO,       dsicinaudio);
+    REGISTER_DECODER(DSS_SP,            dss_sp);
     REGISTER_ENCDEC (EAC3,              eac3);
     REGISTER_DECODER(EVRC,              evrc);
     REGISTER_DECODER(FFWAVESYNTH,       ffwavesynth);
@@ -477,7 +482,9 @@
     REGISTER_DECODER(ADPCM_VIMA,        adpcm_vima);
     REGISTER_DECODER(ADPCM_XA,          adpcm_xa);
     REGISTER_ENCDEC (ADPCM_YAMAHA,      adpcm_yamaha);
+#if FF_API_VIMA_DECODER
     REGISTER_DECODER(VIMA,              vima);
+#endif
 
     /* subtitles */
     REGISTER_ENCDEC (SSA,               ssa);
@@ -505,6 +512,7 @@
 
     /* external libraries */
     REGISTER_DECODER(LIBCELT,           libcelt);
+    REGISTER_DECODER(LIBDCADEC,         libdcadec)
     REGISTER_ENCODER(LIBFAAC,           libfaac);
     REGISTER_ENCDEC (LIBFDK_AAC,        libfdk_aac);
     REGISTER_ENCDEC (LIBGSM,            libgsm);
@@ -536,13 +544,16 @@
     REGISTER_ENCODER(LIBXVID,           libxvid);
     REGISTER_DECODER(LIBZVBI_TELETEXT,  libzvbi_teletext);
     REGISTER_ENCODER(LIBAACPLUS,        libaacplus);
-    REGISTER_ENCODER(LIBOPENH264,       libopenh264);
 
     /* text */
     REGISTER_DECODER(BINTEXT,           bintext);
     REGISTER_DECODER(XBIN,              xbin);
     REGISTER_DECODER(IDF,               idf);
 
+    /* external libraries, that shouldn't be used by default if one of the
+     * above is available */
+    REGISTER_ENCODER(LIBOPENH264,       libopenh264);
+
     /* parsers */
     REGISTER_PARSER(AAC,                aac);
     REGISTER_PARSER(AAC_LATM,           aac_latm);
diff --git a/libavcodec/alsdec.c b/libavcodec/alsdec.c
index cfece44..bac434f 100644
--- a/libavcodec/alsdec.c
+++ b/libavcodec/alsdec.c
@@ -152,7 +152,7 @@
 };
 
 
-typedef struct {
+typedef struct ALSSpecificConfig {
     uint32_t samples;         ///< number of samples, 0xFFFFFFFF if unknown
     int resolution;           ///< 000 = 8-bit; 001 = 16-bit; 010 = 24-bit; 011 = 32-bit
     int floating;             ///< 1 = IEEE 32-bit floating-point, 0 = integer
@@ -178,7 +178,7 @@
 } ALSSpecificConfig;
 
 
-typedef struct {
+typedef struct ALSChannelData {
     int stop_flag;
     int master_channel;
     int time_diff_flag;
@@ -188,7 +188,7 @@
 } ALSChannelData;
 
 
-typedef struct {
+typedef struct ALSDecContext {
     AVCodecContext *avctx;
     ALSSpecificConfig sconf;
     GetBitContext gb;
@@ -228,7 +228,7 @@
 } ALSDecContext;
 
 
-typedef struct {
+typedef struct ALSBlockData {
     unsigned int block_length;      ///< number of samples within the block
     unsigned int ra_block;          ///< if true, this is a random access block
     int          *const_block;      ///< if true, this is a constant value block
@@ -1478,7 +1478,8 @@
     int invalid_frame, ret;
     unsigned int c, sample, ra_frame, bytes_read, shift;
 
-    init_get_bits(&ctx->gb, buffer, buffer_size * 8);
+    if ((ret = init_get_bits8(&ctx->gb, buffer, buffer_size)) < 0)
+        return ret;
 
     // In the case that the distance between random access frames is set to zero
     // (sconf->ra_distance == 0) no frame is treated as a random access frame.
diff --git a/libavcodec/amrnbdec.c b/libavcodec/amrnbdec.c
index 43ddb62..3fa639d 100644
--- a/libavcodec/amrnbdec.c
+++ b/libavcodec/amrnbdec.c
@@ -399,17 +399,17 @@
         decode_pitch_lag_1_6(&pitch_lag_int, &pitch_lag_frac,
                              amr_subframe->p_lag, p->pitch_lag_int,
                              subframe);
-    } else
+    } else {
         ff_decode_pitch_lag(&pitch_lag_int, &pitch_lag_frac,
                             amr_subframe->p_lag,
                             p->pitch_lag_int, subframe,
                             mode != MODE_4k75 && mode != MODE_5k15,
                             mode <= MODE_6k7 ? 4 : (mode == MODE_7k95 ? 5 : 6));
+        pitch_lag_frac *= 2;
+    }
 
     p->pitch_lag_int = pitch_lag_int; // store previous lag in a uint8_t
 
-    pitch_lag_frac <<= (p->cur_frame_mode != MODE_12k2);
-
     pitch_lag_int += pitch_lag_frac > 0;
 
     /* Calculate the pitch vector by interpolating the past excitation at the
diff --git a/libavcodec/amrwbdec.c b/libavcodec/amrwbdec.c
index bf668bb..8771a2a 100644
--- a/libavcodec/amrwbdec.c
+++ b/libavcodec/amrwbdec.c
@@ -44,7 +44,7 @@
 #include "amrwbdata.h"
 #include "mips/amrwbdec_mips.h"
 
-typedef struct {
+typedef struct AMRWBContext {
     AMRWBFrame                             frame; ///< AMRWB parameters decoded from bitstream
     enum Mode                        fr_cur_mode; ///< mode index of current frame
     uint8_t                           fr_quality; ///< frame quality index (FQI)
diff --git a/libavcodec/ansi.c b/libavcodec/ansi.c
index 92981cc..2023359 100644
--- a/libavcodec/ansi.c
+++ b/libavcodec/ansi.c
@@ -50,7 +50,7 @@
     0,  4,  2,  6,  1,  5,  3, 7, 8, 12, 10, 14,  9, 13, 11, 15
 };
 
-typedef struct {
+typedef struct AnsiContext {
     AVFrame *frame;
     int x;                /**< x cursor position (pixels) */
     int y;                /**< y cursor position (pixels) */
diff --git a/libavcodec/apedec.c b/libavcodec/apedec.c
index 383b7fe..536361c 100644
--- a/libavcodec/apedec.c
+++ b/libavcodec/apedec.c
@@ -505,10 +505,7 @@
         rice->k++;
 
     /* Convert to signed */
-    if (x & 1)
-        return (x >> 1) + 1;
-    else
-        return -(x >> 1);
+    return ((x >> 1) ^ ((x & 1) - 1)) + 1;
 }
 
 static inline int ape_decode_value_3900(APEContext *ctx, APERice *rice)
@@ -542,10 +539,7 @@
     update_rice(rice, x);
 
     /* Convert to signed */
-    if (x & 1)
-        return (x >> 1) + 1;
-    else
-        return -(x >> 1);
+    return ((x >> 1) ^ ((x & 1) - 1)) + 1;
 }
 
 static inline int ape_decode_value_3990(APEContext *ctx, APERice *rice)
@@ -588,10 +582,7 @@
     update_rice(rice, x);
 
     /* Convert to signed */
-    if (x & 1)
-        return (x >> 1) + 1;
-    else
-        return -(x >> 1);
+    return ((x >> 1) ^ ((x & 1) - 1)) + 1;
 }
 
 static void decode_array_0000(APEContext *ctx, GetBitContext *gb,
@@ -634,12 +625,8 @@
         }
     }
 
-    for (i = 0; i < blockstodecode; i++) {
-        if (out[i] & 1)
-            out[i] = (out[i] >> 1) + 1;
-        else
-            out[i] = -(out[i] >> 1);
-    }
+    for (i = 0; i < blockstodecode; i++)
+        out[i] = ((out[i] >> 1) ^ ((out[i] & 1) - 1)) + 1;
 }
 
 static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode)
@@ -899,11 +886,11 @@
     return p->filterA[filter];
 }
 
-static void long_filter_high_3800(int32_t *buffer, int order, int shift,
-                                  int32_t *coeffs, int32_t *delay, int length)
+static void long_filter_high_3800(int32_t *buffer, int order, int shift, int length)
 {
     int i, j;
     int32_t dotprod, sign;
+    int32_t coeffs[256], delay[256];
 
     memset(coeffs, 0, order * sizeof(*coeffs));
     for (i = 0; i < order; i++)
@@ -947,13 +934,12 @@
     APEPredictor *p = &ctx->predictor;
     int32_t *decoded0 = ctx->decoded[0];
     int32_t *decoded1 = ctx->decoded[1];
-    int32_t coeffs[256], delay[256];
     int start = 4, shift = 10;
 
     if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
         start = 16;
-        long_filter_high_3800(decoded0, 16, 9, coeffs, delay, count);
-        long_filter_high_3800(decoded1, 16, 9, coeffs, delay, count);
+        long_filter_high_3800(decoded0, 16, 9, count);
+        long_filter_high_3800(decoded1, 16, 9, count);
     } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
         int order = 128, shift2 = 11;
 
@@ -965,8 +951,8 @@
             long_filter_ehigh_3830(decoded1 + order, count - order);
         }
         start = order;
-        long_filter_high_3800(decoded0, order, shift2, coeffs, delay, count);
-        long_filter_high_3800(decoded1, order, shift2, coeffs, delay, count);
+        long_filter_high_3800(decoded0, order, shift2, count);
+        long_filter_high_3800(decoded1, order, shift2, count);
     }
 
     while (count--) {
@@ -1002,12 +988,11 @@
 {
     APEPredictor *p = &ctx->predictor;
     int32_t *decoded0 = ctx->decoded[0];
-    int32_t coeffs[256], delay[256];
     int start = 4, shift = 10;
 
     if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
         start = 16;
-        long_filter_high_3800(decoded0, 16, 9, coeffs, delay, count);
+        long_filter_high_3800(decoded0, 16, 9, count);
     } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
         int order = 128, shift2 = 11;
 
@@ -1018,7 +1003,7 @@
             long_filter_ehigh_3830(decoded0 + order, count - order);
         }
         start = order;
-        long_filter_high_3800(decoded0, order, shift2, coeffs, delay, count);
+        long_filter_high_3800(decoded0, order, shift2, count);
     }
 
     while (count--) {
diff --git a/libavcodec/arm/Makefile b/libavcodec/arm/Makefile
index e0af6bc..2f87396 100644
--- a/libavcodec/arm/Makefile
+++ b/libavcodec/arm/Makefile
@@ -1,7 +1,5 @@
 ARCH_HEADERS = mathops.h
 
-OBJS                                   += arm/fmtconvert_init_arm.o
-
 # subsystems
 OBJS-$(CONFIG_AC3DSP)                  += arm/ac3dsp_init_arm.o         \
                                           arm/ac3dsp_arm.o
@@ -9,6 +7,7 @@
 OBJS-$(CONFIG_BLOCKDSP)                += arm/blockdsp_init_arm.o
 OBJS-$(CONFIG_FFT)                     += arm/fft_init_arm.o            \
                                           arm/fft_fixed_init_arm.o
+OBJS-$(CONFIG_FMTCONVERT)              += arm/fmtconvert_init_arm.o
 OBJS-$(CONFIG_H264CHROMA)              += arm/h264chroma_init_arm.o
 OBJS-$(CONFIG_H264DSP)                 += arm/h264dsp_init_arm.o
 OBJS-$(CONFIG_H264PRED)                += arm/h264pred_init_arm.o
@@ -32,10 +31,13 @@
 # decoders/encoders
 OBJS-$(CONFIG_AAC_DECODER)             += arm/aacpsdsp_init_arm.o       \
                                           arm/sbrdsp_init_arm.o
+OBJS-$(CONFIG_ADPCM_G722_DECODER)      += arm/g722dsp_init_arm.o
+OBJS-$(CONFIG_ADPCM_G722_ENCODER)      += arm/g722dsp_init_arm.o
 OBJS-$(CONFIG_DCA_DECODER)             += arm/dcadsp_init_arm.o
 OBJS-$(CONFIG_FLAC_DECODER)            += arm/flacdsp_init_arm.o        \
                                           arm/flacdsp_arm.o
 OBJS-$(CONFIG_FLAC_ENCODER)            += arm/flacdsp_init_arm.o
+OBJS-$(CONFIG_HEVC_DECODER)            += arm/hevcdsp_init_arm.o
 OBJS-$(CONFIG_MLP_DECODER)             += arm/mlpdsp_init_arm.o
 OBJS-$(CONFIG_VC1_DECODER)             += arm/vc1dsp_init_arm.o
 OBJS-$(CONFIG_VORBIS_DECODER)          += arm/vorbisdsp_init_arm.o
@@ -85,12 +87,11 @@
 
 
 # VFP optimizations
-VFP-OBJS                               += arm/fmtconvert_vfp.o
 
 # subsystems
 VFP-OBJS-$(CONFIG_FFT)                 += arm/fft_vfp.o
+VFP-OBJS-$(CONFIG_FMTCONVERT)          += arm/fmtconvert_vfp.o
 VFP-OBJS-$(CONFIG_MDCT)                += arm/mdct_vfp.o
-VFP-OBJS-$(HAVE_ARMV6)                 += arm/fmtconvert_vfp_armv6.o
 
 # decoders/encoders
 VFP-OBJS-$(CONFIG_DCA_DECODER)         += arm/dcadsp_vfp.o              \
@@ -98,7 +99,6 @@
 
 
 # NEON optimizations
-NEON-OBJS                              += arm/fmtconvert_neon.o
 
 # subsystems
 NEON-OBJS-$(CONFIG_AC3DSP)             += arm/ac3dsp_neon.o
@@ -109,6 +109,7 @@
                                           arm/blockdsp_neon.o
 NEON-OBJS-$(CONFIG_FFT)                += arm/fft_neon.o                \
                                           arm/fft_fixed_neon.o
+NEON-OBJS-$(CONFIG_FMTCONVERT)         += arm/fmtconvert_neon.o
 NEON-OBJS-$(CONFIG_H264CHROMA)         += arm/h264cmc_neon.o
 NEON-OBJS-$(CONFIG_H264DSP)            += arm/h264dsp_neon.o            \
                                           arm/h264idct_neon.o
@@ -129,9 +130,15 @@
 # decoders/encoders
 NEON-OBJS-$(CONFIG_AAC_DECODER)        += arm/aacpsdsp_neon.o           \
                                           arm/sbrdsp_neon.o
+NEON-OBJS-$(CONFIG_ADPCM_G722_DECODER) += arm/g722dsp_neon.o
+NEON-OBJS-$(CONFIG_ADPCM_G722_ENCODER) += arm/g722dsp_neon.o
 NEON-OBJS-$(CONFIG_LLAUDDSP)           += arm/lossless_audiodsp_neon.o
 NEON-OBJS-$(CONFIG_DCA_DECODER)        += arm/dcadsp_neon.o             \
                                           arm/synth_filter_neon.o
+NEON-OBJS-$(CONFIG_HEVC_DECODER)       += arm/hevcdsp_init_neon.o       \
+                                          arm/hevcdsp_deblock_neon.o    \
+                                          arm/hevcdsp_idct_neon.o       \
+                                          arm/hevcdsp_qpel_neon.o
 NEON-OBJS-$(CONFIG_RV30_DECODER)       += arm/rv34dsp_neon.o
 NEON-OBJS-$(CONFIG_RV40_DECODER)       += arm/rv34dsp_neon.o            \
                                           arm/rv40dsp_neon.o
diff --git a/libavcodec/arm/fmtconvert_init_arm.c b/libavcodec/arm/fmtconvert_init_arm.c
index 37319ed..58589c4 100644
--- a/libavcodec/arm/fmtconvert_init_arm.c
+++ b/libavcodec/arm/fmtconvert_init_arm.c
@@ -34,11 +34,6 @@
                                        const int32_t *src, const float *mul,
                                        int len);
 
-void ff_float_to_int16_neon(int16_t *dst, const float *src, long len);
-void ff_float_to_int16_interleave_neon(int16_t *, const float **, long, int);
-
-void ff_float_to_int16_vfp(int16_t *dst, const float *src, long len);
-
 av_cold void ff_fmt_convert_init_arm(FmtConvertContext *c, AVCodecContext *avctx)
 {
     int cpu_flags = av_get_cpu_flags();
@@ -48,18 +43,9 @@
             c->int32_to_float_fmul_scalar = ff_int32_to_float_fmul_scalar_vfp;
             c->int32_to_float_fmul_array8 = ff_int32_to_float_fmul_array8_vfp;
         }
-
-        if (have_armv6(cpu_flags)) {
-            c->float_to_int16 = ff_float_to_int16_vfp;
-        }
     }
 
     if (have_neon(cpu_flags)) {
         c->int32_to_float_fmul_scalar = ff_int32_to_float_fmul_scalar_neon;
-
-        if (!(avctx->flags & CODEC_FLAG_BITEXACT)) {
-            c->float_to_int16            = ff_float_to_int16_neon;
-            c->float_to_int16_interleave = ff_float_to_int16_interleave_neon;
-        }
     }
 }
diff --git a/libavcodec/arm/fmtconvert_neon.S b/libavcodec/arm/fmtconvert_neon.S
index 4662e28..a9ad57f 100644
--- a/libavcodec/arm/fmtconvert_neon.S
+++ b/libavcodec/arm/fmtconvert_neon.S
@@ -22,347 +22,6 @@
 #include "config.h"
 #include "libavutil/arm/asm.S"
 
-function ff_float_to_int16_neon, export=1
-        subs            r2,  r2,  #8
-        vld1.64         {d0-d1},  [r1,:128]!
-        vcvt.s32.f32    q8,  q0,  #16
-        vld1.64         {d2-d3},  [r1,:128]!
-        vcvt.s32.f32    q9,  q1,  #16
-        beq             3f
-        bics            ip,  r2,  #15
-        beq             2f
-1:      subs            ip,  ip,  #16
-        vshrn.s32       d4,  q8,  #16
-        vld1.64         {d0-d1},  [r1,:128]!
-        vcvt.s32.f32    q0,  q0,  #16
-        vshrn.s32       d5,  q9,  #16
-        vld1.64         {d2-d3},  [r1,:128]!
-        vcvt.s32.f32    q1,  q1,  #16
-        vshrn.s32       d6,  q0,  #16
-        vst1.64         {d4-d5},  [r0,:128]!
-        vshrn.s32       d7,  q1,  #16
-        vld1.64         {d16-d17},[r1,:128]!
-        vcvt.s32.f32    q8,  q8,  #16
-        vld1.64         {d18-d19},[r1,:128]!
-        vcvt.s32.f32    q9,  q9,  #16
-        vst1.64         {d6-d7},  [r0,:128]!
-        bne             1b
-        ands            r2,  r2,  #15
-        beq             3f
-2:      vld1.64         {d0-d1},  [r1,:128]!
-        vshrn.s32       d4,  q8,  #16
-        vcvt.s32.f32    q0,  q0,  #16
-        vld1.64         {d2-d3},  [r1,:128]!
-        vshrn.s32       d5,  q9,  #16
-        vcvt.s32.f32    q1,  q1,  #16
-        vshrn.s32       d6,  q0,  #16
-        vst1.64         {d4-d5},  [r0,:128]!
-        vshrn.s32       d7,  q1,  #16
-        vst1.64         {d6-d7},  [r0,:128]!
-        bx              lr
-3:      vshrn.s32       d4,  q8,  #16
-        vshrn.s32       d5,  q9,  #16
-        vst1.64         {d4-d5},  [r0,:128]!
-        bx              lr
-endfunc
-
-function ff_float_to_int16_interleave_neon, export=1
-        cmp             r3, #2
-        itt             lt
-        ldrlt           r1, [r1]
-        blt             X(ff_float_to_int16_neon)
-        bne             4f
-
-        ldr             r3, [r1]
-        ldr             r1, [r1, #4]
-
-        subs            r2,  r2,  #8
-        vld1.64         {d0-d1},  [r3,:128]!
-        vcvt.s32.f32    q8,  q0,  #16
-        vld1.64         {d2-d3},  [r3,:128]!
-        vcvt.s32.f32    q9,  q1,  #16
-        vld1.64         {d20-d21},[r1,:128]!
-        vcvt.s32.f32    q10, q10, #16
-        vld1.64         {d22-d23},[r1,:128]!
-        vcvt.s32.f32    q11, q11, #16
-        beq             3f
-        bics            ip,  r2,  #15
-        beq             2f
-1:      subs            ip,  ip,  #16
-        vld1.64         {d0-d1},  [r3,:128]!
-        vcvt.s32.f32    q0,  q0,  #16
-        vsri.32         q10, q8,  #16
-        vld1.64         {d2-d3},  [r3,:128]!
-        vcvt.s32.f32    q1,  q1,  #16
-        vld1.64         {d24-d25},[r1,:128]!
-        vcvt.s32.f32    q12, q12, #16
-        vld1.64         {d26-d27},[r1,:128]!
-        vsri.32         q11, q9,  #16
-        vst1.64         {d20-d21},[r0,:128]!
-        vcvt.s32.f32    q13, q13, #16
-        vst1.64         {d22-d23},[r0,:128]!
-        vsri.32         q12, q0,  #16
-        vld1.64         {d16-d17},[r3,:128]!
-        vsri.32         q13, q1,  #16
-        vst1.64         {d24-d25},[r0,:128]!
-        vcvt.s32.f32    q8,  q8,  #16
-        vld1.64         {d18-d19},[r3,:128]!
-        vcvt.s32.f32    q9,  q9,  #16
-        vld1.64         {d20-d21},[r1,:128]!
-        vcvt.s32.f32    q10, q10, #16
-        vld1.64         {d22-d23},[r1,:128]!
-        vcvt.s32.f32    q11, q11, #16
-        vst1.64         {d26-d27},[r0,:128]!
-        bne             1b
-        ands            r2,  r2,  #15
-        beq             3f
-2:      vsri.32         q10, q8,  #16
-        vld1.64         {d0-d1},  [r3,:128]!
-        vcvt.s32.f32    q0,  q0,  #16
-        vld1.64         {d2-d3},  [r3,:128]!
-        vcvt.s32.f32    q1,  q1,  #16
-        vld1.64         {d24-d25},[r1,:128]!
-        vcvt.s32.f32    q12, q12, #16
-        vsri.32         q11, q9,  #16
-        vld1.64         {d26-d27},[r1,:128]!
-        vcvt.s32.f32    q13, q13, #16
-        vst1.64         {d20-d21},[r0,:128]!
-        vsri.32         q12, q0,  #16
-        vst1.64         {d22-d23},[r0,:128]!
-        vsri.32         q13, q1,  #16
-        vst1.64         {d24-d27},[r0,:128]!
-        bx              lr
-3:      vsri.32         q10, q8,  #16
-        vsri.32         q11, q9,  #16
-        vst1.64         {d20-d23},[r0,:128]!
-        bx              lr
-
-4:      push            {r4-r8,lr}
-        cmp             r3,  #4
-        lsl             ip,  r3,  #1
-        blt             4f
-
-        @ 4 channels
-5:      ldmia           r1!, {r4-r7}
-        mov             lr,  r2
-        mov             r8,  r0
-        vld1.64         {d16-d17},[r4,:128]!
-        vcvt.s32.f32    q8,  q8,  #16
-        vld1.64         {d18-d19},[r5,:128]!
-        vcvt.s32.f32    q9,  q9,  #16
-        vld1.64         {d20-d21},[r6,:128]!
-        vcvt.s32.f32    q10, q10, #16
-        vld1.64         {d22-d23},[r7,:128]!
-        vcvt.s32.f32    q11, q11, #16
-6:      subs            lr,  lr,  #8
-        vld1.64         {d0-d1},  [r4,:128]!
-        vcvt.s32.f32    q0,  q0,  #16
-        vsri.32         q9,  q8,  #16
-        vld1.64         {d2-d3},  [r5,:128]!
-        vcvt.s32.f32    q1,  q1,  #16
-        vsri.32         q11, q10, #16
-        vld1.64         {d4-d5},  [r6,:128]!
-        vcvt.s32.f32    q2,  q2,  #16
-        vzip.32         d18, d22
-        vld1.64         {d6-d7},  [r7,:128]!
-        vcvt.s32.f32    q3,  q3,  #16
-        vzip.32         d19, d23
-        vst1.64         {d18},    [r8], ip
-        vsri.32         q1,  q0,  #16
-        vst1.64         {d22},    [r8], ip
-        vsri.32         q3,  q2,  #16
-        vst1.64         {d19},    [r8], ip
-        vzip.32         d2,  d6
-        vst1.64         {d23},    [r8], ip
-        vzip.32         d3,  d7
-        beq             7f
-        vld1.64         {d16-d17},[r4,:128]!
-        vcvt.s32.f32    q8,  q8,  #16
-        vst1.64         {d2},     [r8], ip
-        vld1.64         {d18-d19},[r5,:128]!
-        vcvt.s32.f32    q9,  q9,  #16
-        vst1.64         {d6},     [r8], ip
-        vld1.64         {d20-d21},[r6,:128]!
-        vcvt.s32.f32    q10, q10, #16
-        vst1.64         {d3},     [r8], ip
-        vld1.64         {d22-d23},[r7,:128]!
-        vcvt.s32.f32    q11, q11, #16
-        vst1.64         {d7},     [r8], ip
-        b               6b
-7:      vst1.64         {d2},     [r8], ip
-        vst1.64         {d6},     [r8], ip
-        vst1.64         {d3},     [r8], ip
-        vst1.64         {d7},     [r8], ip
-        subs            r3,  r3,  #4
-        it              eq
-        popeq           {r4-r8,pc}
-        cmp             r3,  #4
-        add             r0,  r0,  #8
-        bge             5b
-
-        @ 2 channels
-4:      cmp             r3,  #2
-        blt             4f
-        ldmia           r1!, {r4-r5}
-        mov             lr,  r2
-        mov             r8,  r0
-        tst             lr,  #8
-        vld1.64         {d16-d17},[r4,:128]!
-        vcvt.s32.f32    q8,  q8,  #16
-        vld1.64         {d18-d19},[r5,:128]!
-        vcvt.s32.f32    q9,  q9,  #16
-        vld1.64         {d20-d21},[r4,:128]!
-        vcvt.s32.f32    q10, q10, #16
-        vld1.64         {d22-d23},[r5,:128]!
-        vcvt.s32.f32    q11, q11, #16
-        beq             6f
-        subs            lr,  lr,  #8
-        beq             7f
-        vsri.32         d18, d16, #16
-        vsri.32         d19, d17, #16
-        vld1.64         {d16-d17},[r4,:128]!
-        vcvt.s32.f32    q8,  q8,  #16
-        vst1.32         {d18[0]}, [r8], ip
-        vsri.32         d22, d20, #16
-        vst1.32         {d18[1]}, [r8], ip
-        vsri.32         d23, d21, #16
-        vst1.32         {d19[0]}, [r8], ip
-        vst1.32         {d19[1]}, [r8], ip
-        vld1.64         {d18-d19},[r5,:128]!
-        vcvt.s32.f32    q9,  q9,  #16
-        vst1.32         {d22[0]}, [r8], ip
-        vst1.32         {d22[1]}, [r8], ip
-        vld1.64         {d20-d21},[r4,:128]!
-        vcvt.s32.f32    q10, q10, #16
-        vst1.32         {d23[0]}, [r8], ip
-        vst1.32         {d23[1]}, [r8], ip
-        vld1.64         {d22-d23},[r5,:128]!
-        vcvt.s32.f32    q11, q11, #16
-6:      subs            lr,  lr,  #16
-        vld1.64         {d0-d1},  [r4,:128]!
-        vcvt.s32.f32    q0,  q0,  #16
-        vsri.32         d18, d16, #16
-        vld1.64         {d2-d3},  [r5,:128]!
-        vcvt.s32.f32    q1,  q1,  #16
-        vsri.32         d19, d17, #16
-        vld1.64         {d4-d5},  [r4,:128]!
-        vcvt.s32.f32    q2,  q2,  #16
-        vld1.64         {d6-d7},  [r5,:128]!
-        vcvt.s32.f32    q3,  q3,  #16
-        vst1.32         {d18[0]}, [r8], ip
-        vsri.32         d22, d20, #16
-        vst1.32         {d18[1]}, [r8], ip
-        vsri.32         d23, d21, #16
-        vst1.32         {d19[0]}, [r8], ip
-        vsri.32         d2,  d0,  #16
-        vst1.32         {d19[1]}, [r8], ip
-        vsri.32         d3,  d1,  #16
-        vst1.32         {d22[0]}, [r8], ip
-        vsri.32         d6,  d4,  #16
-        vst1.32         {d22[1]}, [r8], ip
-        vsri.32         d7,  d5,  #16
-        vst1.32         {d23[0]}, [r8], ip
-        vst1.32         {d23[1]}, [r8], ip
-        beq             6f
-        vld1.64         {d16-d17},[r4,:128]!
-        vcvt.s32.f32    q8,  q8,  #16
-        vst1.32         {d2[0]},  [r8], ip
-        vst1.32         {d2[1]},  [r8], ip
-        vld1.64         {d18-d19},[r5,:128]!
-        vcvt.s32.f32    q9,  q9,  #16
-        vst1.32         {d3[0]},  [r8], ip
-        vst1.32         {d3[1]},  [r8], ip
-        vld1.64         {d20-d21},[r4,:128]!
-        vcvt.s32.f32    q10, q10, #16
-        vst1.32         {d6[0]},  [r8], ip
-        vst1.32         {d6[1]},  [r8], ip
-        vld1.64         {d22-d23},[r5,:128]!
-        vcvt.s32.f32    q11, q11, #16
-        vst1.32         {d7[0]},  [r8], ip
-        vst1.32         {d7[1]},  [r8], ip
-        bgt             6b
-6:      vst1.32         {d2[0]},  [r8], ip
-        vst1.32         {d2[1]},  [r8], ip
-        vst1.32         {d3[0]},  [r8], ip
-        vst1.32         {d3[1]},  [r8], ip
-        vst1.32         {d6[0]},  [r8], ip
-        vst1.32         {d6[1]},  [r8], ip
-        vst1.32         {d7[0]},  [r8], ip
-        vst1.32         {d7[1]},  [r8], ip
-        b               8f
-7:      vsri.32         d18, d16, #16
-        vsri.32         d19, d17, #16
-        vst1.32         {d18[0]}, [r8], ip
-        vsri.32         d22, d20, #16
-        vst1.32         {d18[1]}, [r8], ip
-        vsri.32         d23, d21, #16
-        vst1.32         {d19[0]}, [r8], ip
-        vst1.32         {d19[1]}, [r8], ip
-        vst1.32         {d22[0]}, [r8], ip
-        vst1.32         {d22[1]}, [r8], ip
-        vst1.32         {d23[0]}, [r8], ip
-        vst1.32         {d23[1]}, [r8], ip
-8:      subs            r3,  r3,  #2
-        add             r0,  r0,  #4
-        it              eq
-        popeq           {r4-r8,pc}
-
-        @ 1 channel
-4:      ldr             r4,  [r1],#4
-        tst             r2,  #8
-        mov             lr,  r2
-        mov             r5,  r0
-        vld1.64         {d0-d1},  [r4,:128]!
-        vcvt.s32.f32    q0,  q0,  #16
-        vld1.64         {d2-d3},  [r4,:128]!
-        vcvt.s32.f32    q1,  q1,  #16
-        bne             8f
-6:      subs            lr,  lr,  #16
-        vld1.64         {d4-d5},  [r4,:128]!
-        vcvt.s32.f32    q2,  q2,  #16
-        vld1.64         {d6-d7},  [r4,:128]!
-        vcvt.s32.f32    q3,  q3,  #16
-        vst1.16         {d0[1]},  [r5,:16], ip
-        vst1.16         {d0[3]},  [r5,:16], ip
-        vst1.16         {d1[1]},  [r5,:16], ip
-        vst1.16         {d1[3]},  [r5,:16], ip
-        vst1.16         {d2[1]},  [r5,:16], ip
-        vst1.16         {d2[3]},  [r5,:16], ip
-        vst1.16         {d3[1]},  [r5,:16], ip
-        vst1.16         {d3[3]},  [r5,:16], ip
-        beq             7f
-        vld1.64         {d0-d1},  [r4,:128]!
-        vcvt.s32.f32    q0,  q0,  #16
-        vld1.64         {d2-d3},  [r4,:128]!
-        vcvt.s32.f32    q1,  q1,  #16
-7:      vst1.16         {d4[1]},  [r5,:16], ip
-        vst1.16         {d4[3]},  [r5,:16], ip
-        vst1.16         {d5[1]},  [r5,:16], ip
-        vst1.16         {d5[3]},  [r5,:16], ip
-        vst1.16         {d6[1]},  [r5,:16], ip
-        vst1.16         {d6[3]},  [r5,:16], ip
-        vst1.16         {d7[1]},  [r5,:16], ip
-        vst1.16         {d7[3]},  [r5,:16], ip
-        bgt             6b
-        pop             {r4-r8,pc}
-8:      subs            lr,  lr,  #8
-        vst1.16         {d0[1]},  [r5,:16], ip
-        vst1.16         {d0[3]},  [r5,:16], ip
-        vst1.16         {d1[1]},  [r5,:16], ip
-        vst1.16         {d1[3]},  [r5,:16], ip
-        vst1.16         {d2[1]},  [r5,:16], ip
-        vst1.16         {d2[3]},  [r5,:16], ip
-        vst1.16         {d3[1]},  [r5,:16], ip
-        vst1.16         {d3[3]},  [r5,:16], ip
-        it              eq
-        popeq           {r4-r8,pc}
-        vld1.64         {d0-d1},  [r4,:128]!
-        vcvt.s32.f32    q0,  q0,  #16
-        vld1.64         {d2-d3},  [r4,:128]!
-        vcvt.s32.f32    q1,  q1,  #16
-        b               6b
-endfunc
-
 function ff_int32_to_float_fmul_scalar_neon, export=1
 VFP     vdup.32         q0,  d0[0]
 VFP     len     .req    r2
diff --git a/libavcodec/arm/fmtconvert_vfp_armv6.S b/libavcodec/arm/fmtconvert_vfp_armv6.S
deleted file mode 100644
index 7b012bc..0000000
--- a/libavcodec/arm/fmtconvert_vfp_armv6.S
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (c) 2008 Siarhei Siamashka <ssvb@users.sourceforge.net>
- *
- * 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"
-#include "libavutil/arm/asm.S"
-
-/**
- * ARM VFP optimized float to int16 conversion.
- * Assume that len is a positive number and is multiple of 8, destination
- * buffer is at least 4 bytes aligned (8 bytes alignment is better for
- * performance), little-endian byte sex.
- */
-@ void ff_float_to_int16_vfp(int16_t *dst, const float *src, int len)
-function ff_float_to_int16_vfp, export=1
-        push            {r4-r8,lr}
-        vpush           {d8-d11}
-        vldmia          r1!, {s16-s23}
-        vcvt.s32.f32    s0,  s16
-        vcvt.s32.f32    s1,  s17
-        vcvt.s32.f32    s2,  s18
-        vcvt.s32.f32    s3,  s19
-        vcvt.s32.f32    s4,  s20
-        vcvt.s32.f32    s5,  s21
-        vcvt.s32.f32    s6,  s22
-        vcvt.s32.f32    s7,  s23
-1:
-        subs            r2,  r2,  #8
-        vmov            r3,  r4,  s0, s1
-        vmov            r5,  r6,  s2, s3
-        vmov            r7,  r8,  s4, s5
-        vmov            ip,  lr,  s6, s7
-        it              gt
-        vldmiagt        r1!, {s16-s23}
-        ssat            r4,  #16, r4
-        ssat            r3,  #16, r3
-        ssat            r6,  #16, r6
-        ssat            r5,  #16, r5
-        pkhbt           r3,  r3,  r4, lsl #16
-        pkhbt           r4,  r5,  r6, lsl #16
-        itttt           gt
-        vcvtgt.s32.f32  s0,  s16
-        vcvtgt.s32.f32  s1,  s17
-        vcvtgt.s32.f32  s2,  s18
-        vcvtgt.s32.f32  s3,  s19
-        itttt           gt
-        vcvtgt.s32.f32  s4,  s20
-        vcvtgt.s32.f32  s5,  s21
-        vcvtgt.s32.f32  s6,  s22
-        vcvtgt.s32.f32  s7,  s23
-        ssat            r8,  #16, r8
-        ssat            r7,  #16, r7
-        ssat            lr,  #16, lr
-        ssat            ip,  #16, ip
-        pkhbt           r5,  r7,  r8, lsl #16
-        pkhbt           r6,  ip,  lr, lsl #16
-        stmia           r0!, {r3-r6}
-        bgt             1b
-
-        vpop            {d8-d11}
-        pop             {r4-r8,pc}
-endfunc
diff --git a/libavcodec/arm/g722dsp_init_arm.c b/libavcodec/arm/g722dsp_init_arm.c
new file mode 100644
index 0000000..c0e5d8b
--- /dev/null
+++ b/libavcodec/arm/g722dsp_init_arm.c
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2015 Peter Meerwald <pmeerw@pmeerw.net>
+ *
+ * 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/attributes.h"
+#include "libavutil/arm/cpu.h"
+#include "libavcodec/g722dsp.h"
+
+extern void ff_g722_apply_qmf_neon(const int16_t *prev_samples, int xout[2]);
+
+av_cold void ff_g722dsp_init_arm(G722DSPContext *dsp)
+{
+    int cpu_flags = av_get_cpu_flags();
+
+    if (have_neon(cpu_flags))
+        dsp->apply_qmf = ff_g722_apply_qmf_neon;
+}
diff --git a/libavcodec/arm/g722dsp_neon.S b/libavcodec/arm/g722dsp_neon.S
new file mode 100644
index 0000000..757e53f
--- /dev/null
+++ b/libavcodec/arm/g722dsp_neon.S
@@ -0,0 +1,69 @@
+/*
+ * ARM NEON optimised DSP functions for G722 coding
+ * Copyright (c) 2015 Peter Meerwald <pmeerw@pmeerw.net>
+ *
+ * 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/arm/asm.S"
+
+function ff_g722_apply_qmf_neon, export=1, align=4
+        movrel          r3, qmf_coeffs
+        vld1.s16        {d2,d3,d4}, [r0]! /* load prev_samples */
+        vld1.s16        {d16,d17,d18}, [r3,:64]! /* load qmf_coeffs */
+        vmull.s16       q0, d2, d16
+        vmlal.s16       q0, d3, d17
+        vmlal.s16       q0, d4, d18
+
+        vld1.s16        {d5,d6,d7}, [r0]! /* load prev_samples */
+        vld1.s16        {d19,d20,d21}, [r3,:64]! /* load qmf_coeffs */
+        vmlal.s16       q0, d5, d19
+        vmlal.s16       q0, d6, d20
+        vmlal.s16       q0, d7, d21
+
+        vadd.s32        d0, d1, d0
+        vrev64.32       d0, d0
+        vst1.s32        {d0}, [r1]
+        bx              lr
+endfunc
+
+const qmf_coeffs, align=4
+        .hword          3
+        .hword          -11
+        .hword          -11
+        .hword          53
+        .hword          12
+        .hword          -156
+        .hword          32
+        .hword          362
+        .hword          -210
+        .hword          -805
+        .hword          951
+        .hword          3876
+        .hword          3876
+        .hword          951
+        .hword          -805
+        .hword          -210
+        .hword          362
+        .hword          32
+        .hword          -156
+        .hword          12
+        .hword          53
+        .hword          -11
+        .hword          -11
+        .hword          3
+endconst
diff --git a/libavcodec/arm/h264dsp_init_arm.c b/libavcodec/arm/h264dsp_init_arm.c
index 88dfd75..90144d0 100644
--- a/libavcodec/arm/h264dsp_init_arm.c
+++ b/libavcodec/arm/h264dsp_init_arm.c
@@ -76,8 +76,8 @@
     if (bit_depth == 8) {
         c->h264_v_loop_filter_luma   = ff_h264_v_loop_filter_luma_neon;
         c->h264_h_loop_filter_luma   = ff_h264_h_loop_filter_luma_neon;
-        if(chroma_format_idc == 1){
         c->h264_v_loop_filter_chroma = ff_h264_v_loop_filter_chroma_neon;
+        if(chroma_format_idc == 1){
         c->h264_h_loop_filter_chroma = ff_h264_h_loop_filter_chroma_neon;
         }
 
diff --git a/libavcodec/arm/hevcdsp_arm.h b/libavcodec/arm/hevcdsp_arm.h
new file mode 100644
index 0000000..7735df9
--- /dev/null
+++ b/libavcodec/arm/hevcdsp_arm.h
@@ -0,0 +1,26 @@
+/*
+ * 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_ARM_HEVCDSP_ARM_H
+#define AVCODEC_ARM_HEVCDSP_ARM_H
+
+#include "libavcodec/hevcdsp.h"
+
+void ff_hevcdsp_init_neon(HEVCDSPContext *c, const int bit_depth);
+
+#endif /* AVCODEC_ARM_HEVCDSP_ARM_H */
diff --git a/libavcodec/arm/hevcdsp_deblock_neon.S b/libavcodec/arm/hevcdsp_deblock_neon.S
new file mode 100644
index 0000000..166bddb
--- /dev/null
+++ b/libavcodec/arm/hevcdsp_deblock_neon.S
@@ -0,0 +1,385 @@
+/*
+ * Copyright (c) 2014 Seppo Tomperi <seppo.tomperi@vtt.fi>
+ *
+ * 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/arm/asm.S"
+#include "neon.S"
+
+.macro hevc_loop_filter_chroma_start
+        ldr      r12, [r2]
+        ldr      r3, [r2, #4]
+        add      r2, r3, r12
+        cmp      r2, #0
+        it       eq
+        bxeq     lr
+.endm
+
+.macro hevc_loop_filter_chroma_body
+        vsubl.u8  q3, d4, d2
+        vsubl.u8  q11, d18, d19
+        vshl.i16  q3, #2
+        vadd.i16  q11, q3
+        vdup.16   d0, r12
+        vdup.16   d1, r3
+        vrshr.s16 q11, q11, #3
+        vneg.s16  q12, q0
+        vmovl.u8  q2, d4
+        vmin.s16  q11, q11, q0
+        vmax.s16  q11, q11, q12
+        vaddw.u8  q1, q11, d2
+        vsub.i16  q2, q11
+        vqmovun.s16 d2, q1
+        vqmovun.s16 d4, q2
+.endm
+
+.macro hevc_loop_filter_luma_start
+        ldr     r12, [r3]
+        ldr      r3, [r3, #4]
+        lsl      r3, #16
+        orr      r3, r12
+        cmp      r3, #0
+        it       eq
+        bxeq     lr
+        lsr      r3, #16
+.endm
+
+.macro hevc_loop_filter_luma_body
+        vmovl.u8  q8, d16
+        vmovl.u8  q9, d18
+        vmovl.u8  q10, d20
+        vmovl.u8  q11, d22
+        vmovl.u8  q12, d24
+        vmovl.u8  q13, d26
+        vmovl.u8  q14, d28
+        vmovl.u8  q15, d30
+
+        vadd.i16   q7, q9, q11
+        vadd.i16   q6, q14, q12
+        vsub.i16   q7, q10
+        vsub.i16   q6, q13
+        vabd.s16   q7, q7, q10
+        vabd.s16   q6, q6, q13
+
+
+        vdup.16    q0, r2
+        vmov       q4, q7
+        vmov       q5, q6
+        vdup.16    d4, r12
+        vtrn.16    q7, q4
+        vtrn.16    q6, q5
+
+        vshl.u64   q7, #32
+        vshr.u64   q4, #32
+        vshl.u64   q6, #32
+        vshr.u64   q5, #32
+        vshr.u64   q7, #32
+        vshr.u64   q6, #32
+        vshl.u64   q5, #32
+        vshl.u64   q4, #32
+        vorr       q6, q5
+        vorr       q7, q4
+        vdup.16    d5, r3
+        vadd.i16   q5, q7, q6
+
+        vmov       q4, q5
+        vmov       q3, q5
+        vtrn.32    q3, q4
+
+        vadd.i16   q4, q3
+
+        vshl.s16   q5, q5, #1
+        vcgt.s16   q3, q0, q4
+
+        vmovn.i16  d6, q3
+        vshr.s16   q1, q0, #2
+        vmovn.i16  d6, q3
+        vcgt.s16   q5, q1, q5
+        vmov       r7, s12
+        cmp        r7, #0
+        beq        bypasswrite
+
+        vpadd.i32  d0, d14, d12
+        vpadd.i32  d1, d15, d13
+        vmov       q4, q2
+        vshl.s16   q2, #2
+        vshr.s16   q1, q1, #1
+        vrhadd.s16 q2, q4
+
+        vabd.s16   q7, q8, q11
+        vaba.s16   q7, q15, q12
+
+        vmovn.i32  d0, q0
+        vmov       r5, r6, s0, s1
+        vcgt.s16   q6, q1, q7
+        vand       q5, q5, q6
+        vabd.s16   q7, q11, q12
+        vcgt.s16   q6, q2, q7
+        vand       q5, q5, q6
+
+        vmov       q2, q5
+        vtrn.s16   q5, q2
+        vshr.u64   q2, #32
+        vshl.u64   q5, #32
+        vshl.u64   q2, #32
+        vshr.u64   q5, #32
+        vorr       q5, q2
+
+        vmov       q2, q5
+        vshl.i16   q7, q4, #1
+        vtrn.32    q2, q5
+        vand       q5, q2
+        vneg.s16   q6, q7
+        vmovn.i16  d4, q5
+        vmovn.i16  d4, q2
+        vmov       r8, s8
+
+        and        r9, r8, r7
+        cmp        r9, #0
+        beq        weakfilter_\@
+
+        vadd.i16  q2, q11, q12
+        vadd.i16  q4, q9, q8
+        vadd.i16  q1, q2, q10
+        vdup.16   d10, r9
+        vadd.i16  q0, q1, q9
+        vshl.i16  q4, #1
+        lsr        r9, #16
+        vadd.i16  q1, q0
+        vrshr.s16 q3, q0, #2
+        vadd.i16  q1, q13
+        vadd.i16  q4, q0
+        vsub.i16  q3, q10
+        vrshr.s16 q1, #3
+        vrshr.s16 q4, #3
+        vmax.s16  q3, q6
+        vsub.i16  q1, q11
+        vsub.i16  q4, q9
+        vmin.s16  q3, q7
+        vmax.s16  q4, q6
+        vmax.s16  q1, q6
+        vadd.i16  q3, q10
+        vmin.s16  q4, q7
+        vmin.s16  q1, q7
+        vdup.16   d11, r9
+        vadd.i16  q4, q9
+        vadd.i16  q1, q11
+        vbit      q9, q4, q5
+        vadd.i16  q4, q2, q13
+        vbit      q11, q1, q5
+        vadd.i16  q0, q4, q14
+        vadd.i16  q2, q15, q14
+        vadd.i16  q4, q0
+
+        vshl.i16  q2, #1
+        vadd.i16  q4, q10
+        vbit      q10, q3, q5
+        vrshr.s16 q4, #3
+        vadd.i16  q2, q0
+        vrshr.s16 q3, q0, #2
+        vsub.i16  q4, q12
+        vrshr.s16 q2, #3
+        vsub.i16  q3, q13
+        vmax.s16  q4, q6
+        vsub.i16  q2, q14
+        vmax.s16  q3, q6
+        vmin.s16  q4, q7
+        vmax.s16  q2, q6
+        vmin.s16  q3, q7
+        vadd.i16  q4, q12
+        vmin.s16  q2, q7
+        vadd.i16  q3, q13
+        vbit      q12, q4, q5
+        vadd.i16  q2, q14
+        vbit      q13, q3, q5
+        vbit      q14, q2, q5
+
+weakfilter_\@:
+        mvn       r8, r8
+        and       r9, r8, r7
+        cmp       r9, #0
+        beq       ready_\@
+
+        vdup.16    q4, r2
+
+        vdup.16   d10, r9
+        lsr       r9, #16
+        vmov       q1, q4
+        vdup.16   d11, r9
+        vshr.s16   q1, #1
+        vsub.i16  q2, q12, q11
+        vadd.i16   q4, q1
+        vshl.s16  q0, q2, #3
+        vshr.s16   q4, #3
+        vadd.i16  q2, q0
+        vsub.i16  q0, q13, q10
+        vsub.i16  q2, q0
+        vshl.i16  q0, q0, #1
+        vsub.i16  q2, q0
+        vshl.s16  q1, q7, 2
+        vrshr.s16 q2, q2, #4
+        vadd.i16  q1, q7
+        vabs.s16  q3, q2
+        vshr.s16  q6, q6, #1
+        vcgt.s16  q1, q1, q3
+        vand      q5, q1
+        vshr.s16  q7, q7, #1
+        vmax.s16  q2, q2, q6
+        vmin.s16  q2, q2, q7
+
+        vshr.s16  q7, q7, #1
+        vrhadd.s16 q3, q9, q11
+        vneg.s16  q6, q7
+        vsub.s16  q3, q10
+        vdup.16   d2, r5
+        vhadd.s16 q3, q2
+        vdup.16   d3, r6
+        vmax.s16  q3, q3, q6
+        vcgt.s16  q1, q4, q1
+        vmin.s16  q3, q3, q7
+        vand      q1, q5
+        vadd.i16  q3, q10
+        lsr       r5, #16
+        lsr       r6, #16
+        vbit      q10, q3, q1
+
+        vrhadd.s16 q3, q14, q12
+        vdup.16   d2, r5
+        vsub.s16  q3, q13
+        vdup.16   d3, r6
+        vhsub.s16 q3, q2
+        vcgt.s16  q1, q4, q1
+        vmax.s16  q3, q3, q6
+        vand      q1, q5
+        vmin.s16  q3, q3, q7
+        vadd.i16  q3, q13
+        vbit      q13, q3, q1
+        vadd.i16  q0, q11, q2
+        vsub.i16  q4, q12, q2
+        vbit      q11, q0, q5
+        vbit      q12, q4, q5
+
+ready_\@:
+        vqmovun.s16 d16, q8
+        vqmovun.s16 d18, q9
+        vqmovun.s16 d20, q10
+        vqmovun.s16 d22, q11
+        vqmovun.s16 d24, q12
+        vqmovun.s16 d26, q13
+        vqmovun.s16 d28, q14
+        vqmovun.s16 d30, q15
+.endm
+
+function ff_hevc_v_loop_filter_luma_neon, export=1
+        hevc_loop_filter_luma_start
+        push     {r5-r11}
+        vpush    {d8-d15}
+        sub      r0, #4
+        vld1.8   {d16}, [r0], r1
+        vld1.8   {d18}, [r0], r1
+        vld1.8   {d20}, [r0], r1
+        vld1.8   {d22}, [r0], r1
+        vld1.8   {d24}, [r0], r1
+        vld1.8   {d26}, [r0], r1
+        vld1.8   {d28}, [r0], r1
+        vld1.8   {d30}, [r0], r1
+        sub      r0, r0, r1, lsl #3
+        transpose_8x8 d16, d18, d20, d22, d24, d26, d28, d30
+        hevc_loop_filter_luma_body
+        transpose_8x8 d16, d18, d20, d22, d24, d26, d28, d30
+        vst1.8   {d16}, [r0], r1
+        vst1.8   {d18}, [r0], r1
+        vst1.8   {d20}, [r0], r1
+        vst1.8   {d22}, [r0], r1
+        vst1.8   {d24}, [r0], r1
+        vst1.8   {d26}, [r0], r1
+        vst1.8   {d28}, [r0], r1
+        vst1.8   {d30}, [r0]
+        vpop     {d8-d15}
+        pop      {r5-r11}
+        bx lr
+endfunc
+
+function ff_hevc_h_loop_filter_luma_neon, export=1
+        hevc_loop_filter_luma_start
+        push     {r5-r11}
+        vpush    {d8-d15}
+        sub      r0, r0, r1, lsl #2
+        vld1.8  {d16}, [r0], r1
+        vld1.8  {d18}, [r0], r1
+        vld1.8  {d20}, [r0], r1
+        vld1.8  {d22}, [r0], r1
+        vld1.8  {d24}, [r0], r1
+        vld1.8  {d26}, [r0], r1
+        vld1.8  {d28}, [r0], r1
+        vld1.8  {d30}, [r0], r1
+        sub        r0, r0, r1, lsl #3
+        add        r0, r1
+        hevc_loop_filter_luma_body
+        vst1.8   {d18}, [r0], r1
+        vst1.8   {d20}, [r0], r1
+        vst1.8   {d22}, [r0], r1
+        vst1.8   {d24}, [r0], r1
+        vst1.8   {d26}, [r0], r1
+        vst1.8   {d28}, [r0]
+bypasswrite:
+        vpop     {d8-d15}
+        pop      {r5-r11}
+        bx lr
+endfunc
+
+function ff_hevc_v_loop_filter_chroma_neon, export=1
+        hevc_loop_filter_chroma_start
+        sub      r0, #4
+        vld1.8   {d16}, [r0], r1
+        vld1.8   {d17}, [r0], r1
+        vld1.8   {d18}, [r0], r1
+        vld1.8   {d2},  [r0], r1
+        vld1.8   {d4},  [r0], r1
+        vld1.8   {d19}, [r0], r1
+        vld1.8   {d20}, [r0], r1
+        vld1.8   {d21}, [r0], r1
+        sub      r0, r0, r1, lsl #3
+        transpose_8x8 d16, d17, d18, d2, d4, d19, d20, d21
+        hevc_loop_filter_chroma_body
+        transpose_8x8 d16, d17, d18, d2, d4, d19, d20, d21
+        vst1.8   {d16}, [r0], r1
+        vst1.8   {d17}, [r0], r1
+        vst1.8   {d18}, [r0], r1
+        vst1.8   {d2},  [r0], r1
+        vst1.8   {d4},  [r0], r1
+        vst1.8   {d19}, [r0], r1
+        vst1.8   {d20}, [r0], r1
+        vst1.8   {d21}, [r0]
+        bx       lr
+endfunc
+
+function ff_hevc_h_loop_filter_chroma_neon, export=1
+        hevc_loop_filter_chroma_start
+        sub      r0, r0, r1, lsl #1
+        vld1.8   {d18}, [r0], r1
+        vld1.8   {d2}, [r0], r1
+        vld1.8   {d4}, [r0], r1
+        vld1.8   {d19}, [r0]
+        sub      r0, r0, r1, lsl #1
+        hevc_loop_filter_chroma_body
+        vst1.8   {d2}, [r0], r1
+        vst1.8   {d4}, [r0]
+        bx       lr
+endfunc
diff --git a/libavcodec/arm/hevcdsp_idct_neon.S b/libavcodec/arm/hevcdsp_idct_neon.S
new file mode 100644
index 0000000..13d540e
--- /dev/null
+++ b/libavcodec/arm/hevcdsp_idct_neon.S
@@ -0,0 +1,465 @@
+/*
+ * Copyright (c) 2014 Seppo Tomperi <seppo.tomperi@vtt.fi>
+ *
+ * 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/arm/asm.S"
+#include "neon.S"
+
+function ff_hevc_idct_4x4_dc_neon_8, export=1
+        ldrsh       r1, [r0]
+        ldr         r2, =0x20
+        add         r1, #1
+        asr         r1, #1
+        add         r1, r2
+        asr         r1, #6
+        vdup.16     q0, r1
+        vdup.16     q1, r1
+        vst1.16     {q0, q1}, [r0]
+        bx lr
+endfunc
+
+function ff_hevc_idct_8x8_dc_neon_8, export=1
+        ldrsh       r1, [r0]
+        ldr         r2, =0x20
+        add         r1, #1
+        asr         r1, #1
+        add         r1, r2
+        asr         r1, #6
+        vdup.16     q8, r1
+        vdup.16     q9, r1
+        vmov.16     q10, q8
+        vmov.16     q11, q8
+        vmov.16     q12, q8
+        vmov.16     q13, q8
+        vmov.16     q14, q8
+        vmov.16     q15, q8
+        vstm        r0, {q8-q15}
+        bx lr
+endfunc
+
+function ff_hevc_idct_16x16_dc_neon_8, export=1
+        ldrsh       r1, [r0]
+        ldr         r2, =0x20
+        add         r1, #1
+        asr         r1, #1
+        add         r1, r2
+        asr         r1, #6
+        vdup.16     q8, r1
+        vdup.16     q9, r1
+        vmov.16     q10, q8
+        vmov.16     q11, q8
+        vmov.16     q12, q8
+        vmov.16     q13, q8
+        vmov.16     q14, q8
+        vmov.16     q15, q8
+        vstm        r0!, {q8-q15}
+        vstm        r0!, {q8-q15}
+        vstm        r0!, {q8-q15}
+        vstm        r0, {q8-q15}
+        bx lr
+endfunc
+
+function ff_hevc_idct_32x32_dc_neon_8, export=1
+        ldrsh       r1, [r0]
+        ldr         r2, =0x20
+        add         r1, #1
+        asr         r1, #1
+        add         r1, r2
+        asr         r1, #6
+        mov         r3, #16
+        vdup.16     q8, r1
+        vdup.16     q9, r1
+        vmov.16     q10, q8
+        vmov.16     q11, q8
+        vmov.16     q12, q8
+        vmov.16     q13, q8
+        vmov.16     q14, q8
+        vmov.16     q15, q8
+1:      subs        r3, #1
+        vstm        r0!, {q8-q15}
+        bne         1b
+        bx lr
+endfunc
+
+function ff_hevc_transform_add_4x4_neon_8, export=1
+        vldm        r1, {q0-q1}
+        vld1.32     d4[0], [r0], r2
+        vld1.32     d4[1], [r0], r2
+        vld1.32     d5[0], [r0], r2
+        vld1.32     d5[1], [r0], r2
+        sub         r0, r0, r2, lsl #2
+        vmovl.u8    q8, d4
+        vmovl.u8    q9, d5
+        vqadd.s16   q0, q0, q8
+        vqadd.s16   q1, q1, q9
+        vqmovun.s16 d0, q0
+        vqmovun.s16 d1, q1
+        vst1.32     d0[0], [r0], r2
+        vst1.32     d0[1], [r0], r2
+        vst1.32     d1[0], [r0], r2
+        vst1.32     d1[1], [r0], r2
+        bx          lr
+endfunc
+
+function ff_hevc_transform_add_8x8_neon_8, export=1
+        mov         r3,   #8
+1:      subs        r3,   #1
+        vld1.16     {q0}, [r1]!
+        vld1.8      d16,  [r0]
+        vmovl.u8    q8,   d16
+        vqadd.s16   q0,   q8
+        vqmovun.s16 d0,   q0
+        vst1.32     d0,   [r0], r2
+        bne         1b
+        bx          lr
+endfunc
+
+function ff_hevc_transform_add_16x16_neon_8, export=1
+        mov         r3,   #16
+1:      subs        r3,   #1
+        vld1.16     {q0, q1}, [r1]!
+        vld1.8      {q8},  [r0]
+        vmovl.u8    q9,  d16
+        vmovl.u8    q10, d17
+        vqadd.s16   q0,  q9
+        vqadd.s16   q1,  q10
+        vqmovun.s16 d0,  q0
+        vqmovun.s16 d1,  q1
+        vst1.8      {q0},   [r0], r2
+        bne         1b
+        bx          lr
+endfunc
+
+function ff_hevc_transform_add_32x32_neon_8, export=1
+        mov         r3,   #32
+1:      subs        r3,   #1
+        vldm        r1!, {q0-q3}
+        vld1.8      {q8, q9},  [r0]
+        vmovl.u8    q10, d16
+        vmovl.u8    q11, d17
+        vmovl.u8    q12, d18
+        vmovl.u8    q13, d19
+        vqadd.s16   q0,  q10
+        vqadd.s16   q1,  q11
+        vqadd.s16   q2,  q12
+        vqadd.s16   q3,  q13
+        vqmovun.s16 d0,  q0
+        vqmovun.s16 d1,  q1
+        vqmovun.s16 d2,  q2
+        vqmovun.s16 d3,  q3
+        vst1.8     {q0, q1},   [r0], r2
+        bne         1b
+        bx          lr
+endfunc
+
+.macro  transpose_16b_8x8   r0, r1, r2, r3, r4, r5, r6, r7
+        vtrn.64         \r0, \r4
+        vtrn.64         \r1, \r5
+        vtrn.64         \r2, \r6
+        vtrn.64         \r3, \r7
+        vtrn.32         \r0, \r2
+        vtrn.32         \r1, \r3
+        vtrn.32         \r4, \r6
+        vtrn.32         \r5, \r7
+        vtrn.16         \r0, \r1
+        vtrn.16         \r2, \r3
+        vtrn.16         \r4, \r5
+        vtrn.16         \r6, \r7
+.endm
+
+// in 4 q regs
+// output 8 d regs
+.macro transpose_16b_4x4    r0, r1, r2, r3
+        vtrn.32         \r0, \r2
+        vtrn.32         \r1, \r3
+        vtrn.16         \r0, \r1
+        vtrn.16         \r2, \r3
+.endm
+
+/* uses registers q2 - q9 for temp values */
+/* TODO: reorder */
+.macro tr4_luma_shift r0, r1, r2, r3, shift
+        vaddl.s16   q5, \r0, \r2    // c0 = src0 + src2
+        vaddl.s16   q2, \r2, \r3    // c1 = src2 + src3
+        vsubl.s16   q4, \r0, \r3    // c2 = src0 - src3
+        vmull.s16   q6, \r1, d0[0]  // c3 = 74 * src1
+
+        vaddl.s16   q7, \r0, \r3    // src0 + src3
+        vsubw.s16   q7, q7, \r2     // src0 - src2 + src3
+        vmul.s32    q7, q7, d0[0]   // dst2 = 74 * (src0 - src2 + src3)
+
+        vmul.s32    q8, q5, d0[1]   // 29 * c0
+        vmul.s32    q9, q2, d1[0]   // 55 * c1
+        vadd.s32    q8, q9          // 29 * c0 + 55 * c1
+        vadd.s32    q8, q6          // dst0 = 29 * c0 + 55 * c1 + c3
+
+        vmul.s32    q2, q2, d0[1]   // 29 * c1
+        vmul.s32    q9, q4, d1[0]   // 55 * c2
+        vsub.s32    q9, q2          // 55 * c2 - 29 * c1
+        vadd.s32    q9, q6          // dst1 = 55 * c2 - 29 * c1 + c3
+
+        vmul.s32    q5, q5, d1[0]   // 55 * c0
+        vmul.s32    q4, q4, d0[1]   // 29 * c2
+        vadd.s32    q5, q4          // 55 * c0 + 29 * c2
+        vsub.s32    q5, q6          // dst3 = 55 * c0 + 29 * c2 - c3
+
+        vqrshrn.s32   \r0, q8, \shift
+        vqrshrn.s32   \r1, q9, \shift
+        vqrshrn.s32   \r2, q7, \shift
+        vqrshrn.s32   \r3, q5, \shift
+.endm
+
+/* uses registers q2 - q6 for temp values */
+.macro tr4 r0, r1, r2, r3
+        vmull.s16  q4, \r1, d0[0]   // 83 * src1
+        vmull.s16  q6, \r1, d0[1]   // 36 * src1
+        vshll.s16  q2, \r0, #6   // 64 * src0
+        vshll.s16  q3, \r2, #6   // 64 * src2
+        vadd.s32   q5, q2, q3    // 64 * (src0 + src2)     e0
+        vsub.s32   q2, q2, q3    // 64 * (src0 - src2)     e1
+        vmlal.s16  q4, \r3, d0[1]   // 83 * src1 + 36 * src3  o0
+        vmlsl.s16  q6, \r3, d0[0]   // 36 * src1 - 83 * src3  o1
+
+        vsub.s32   q3, q5, q4    // e0 - o0
+        vadd.s32   q4, q5, q4    // e0 + o0
+        vadd.s32   q5, q2, q6    // e1 + o1
+        vsub.s32   q6, q2, q6    // e1 - o1
+.endm
+
+.macro tr4_shift r0, r1, r2, r3, shift
+        vmull.s16  q4, \r1, d0[0]   // 83 * src1
+        vmull.s16  q6, \r1, d0[1]   // 36 * src1
+        vshll.s16  q2, \r0, #6   // 64 * src0
+        vshll.s16  q3, \r2, #6   // 64 * src2
+        vadd.s32   q5, q2, q3    // 64 * (src0 + src2)     e0
+        vsub.s32   q2, q2, q3    // 64 * (src0 - src2)     e1
+        vmlal.s16  q4, \r3, d0[1]   // 83 * src1 + 36 * src3  o0
+        vmlsl.s16  q6, \r3, d0[0]   // 36 * src1 - 83 * src3  o1
+
+        vsub.s32   q3, q5, q4    // e0 - o0
+        vadd.s32   q4, q5, q4    // e0 + o0
+        vadd.s32   q5, q2, q6    // e1 + o1
+        vsub.s32   q6, q2, q6    // e1 - o1
+
+        vqrshrn.s32   \r0, q4, \shift
+        vqrshrn.s32   \r1, q5, \shift
+        vqrshrn.s32   \r2, q6, \shift
+        vqrshrn.s32   \r3, q3, \shift
+.endm
+
+function ff_hevc_transform_4x4_neon_8, export=1
+        vpush       {d8-d15}
+        vld1.16     {q14, q15}, [r0]  // coeffs
+        ldr         r3, =0x00240053 // 36 and 83
+        vmov.32     d0[0], r3
+
+        tr4_shift d28, d29, d30, d31, #7
+
+        vtrn.16     d28, d29
+        vtrn.16     d30, d31
+        vtrn.32     q14, q15
+
+        tr4_shift d28, d29, d30, d31, #12
+
+        vtrn.16     d28, d29
+        vtrn.16     d30, d31
+        vtrn.32     q14, q15
+
+        vst1.16     {q14, q15}, [r0]
+        vpop        {d8-d15}
+        bx lr
+endfunc
+
+function ff_hevc_transform_luma_4x4_neon_8, export=1
+        vpush       {d8-d15}
+        vld1.16     {q14, q15}, [r0]  // coeffs
+        ldr         r3, =0x4a  // 74
+        vmov.32     d0[0], r3
+        ldr         r3, =0x1d  // 29
+        vmov.32     d0[1], r3
+        ldr         r3, =0x37  // 55
+        vmov.32     d1[0], r3
+
+        tr4_luma_shift d28, d29, d30, d31, #7
+
+        vtrn.16     d28, d29
+        vtrn.16     d30, d31
+        vtrn.32     q14, q15
+
+        tr4_luma_shift d28, d29, d30, d31, #12
+
+        vtrn.16     d28, d29
+        vtrn.16     d30, d31
+        vtrn.32     q14, q15
+        vst1.16     {q14, q15}, [r0]
+        vpop        {d8-d15}
+        bx lr
+endfunc
+
+.macro tr8_begin in0, in1, in2, in3
+        vmull.s16  q7, \in0, d1[1]   // 89 * src1
+        vmull.s16  q8, \in0, d1[0]   // 75 * src1
+        vmull.s16  q9, \in0, d1[3]   // 50 * src1
+        vmull.s16  q10, \in0, d1[2]  // 18 * src1
+
+        vmlal.s16  q7, \in1, d1[0]   // 75 * src3
+        vmlsl.s16  q8, \in1, d1[2]   //-18 * src3
+        vmlsl.s16  q9, \in1, d1[1]   //-89 * src3
+        vmlsl.s16  q10, \in1, d1[3]  //-50 * src3
+
+        vmlal.s16  q7, \in2, d1[3]   // 50 * src5
+        vmlsl.s16  q8, \in2, d1[1]   //-89 * src5
+        vmlal.s16  q9, \in2, d1[2]   // 18 * src5
+        vmlal.s16  q10, \in2, d1[0]  // 75 * src5
+
+        vmlal.s16  q7, \in3, d1[2]   // 18 * src7
+        vmlsl.s16  q8, \in3, d1[3]   //-50 * src7
+        vmlal.s16  q9, \in3, d1[0]   // 75 * src7
+        vmlsl.s16  q10, \in3, d1[1]  //-89 * src7
+.endm
+
+.macro tr8_end shift
+        vadd.s32   q1, q4, q7   //  e_8[0] + o_8[0], dst[0]
+        vsub.s32   q4, q4, q7   //  e_8[0] - o_8[0], dst[7]
+
+        vadd.s32   q2, q5, q8   // e_8[1] + o_8[1], dst[1]
+        vsub.s32   q5, q5, q8   // e_8[1] - o_8[1], dst[6]
+
+        vadd.s32   q11, q6, q9  // e_8[2] + o_8[2], dst[2]
+        vsub.s32    q6, q6, q9  // e_8[2] - o_8[2], dst[5]
+
+        vadd.s32   q12, q3, q10 // e_8[3] + o_8[3], dst[3]
+        vsub.s32   q3, q3, q10  // e_8[3] - o_8[3], dst[4]
+        vqrshrn.s32   d2, q1, \shift
+        vqrshrn.s32   d3, q2, \shift
+        vqrshrn.s32   d4, q11, \shift
+        vqrshrn.s32   d5, q12, \shift
+        vqrshrn.s32   d6, q3, \shift
+        vqrshrn.s32   d7, q6, \shift
+        vqrshrn.s32   d9, q4, \shift
+        vqrshrn.s32   d8, q5, \shift
+.endm
+
+function ff_hevc_transform_8x8_neon_8, export=1
+        push   {r4-r8}
+        vpush {d8-d15}
+        mov    r5, #16
+
+        adr       r3, tr4f
+        vld1.16   {d0, d1}, [r3]
+
+        // left half
+        vld1.16 {d24}, [r0], r5
+        vld1.16 {d25}, [r0], r5
+        vld1.16 {d26}, [r0], r5
+        vld1.16 {d27}, [r0], r5
+        vld1.16 {d28}, [r0], r5
+        vld1.16 {d29}, [r0], r5
+        vld1.16 {d30}, [r0], r5
+        vld1.16 {d31}, [r0], r5
+        sub      r0, #128
+        tr8_begin d25, d27, d29, d31
+        tr4       d24, d26, d28, d30
+        tr8_end   #7
+        vst1.16 {d2}, [r0], r5
+        vst1.16 {d3}, [r0], r5
+        vst1.16 {d4}, [r0], r5
+        vst1.16 {d5}, [r0], r5
+        vst1.16 {d6}, [r0], r5
+        vst1.16 {d7}, [r0], r5
+        vst1.16 {d8}, [r0], r5
+        vst1.16 {d9}, [r0], r5
+        sub      r0, #128
+        //skip right half if col_limit in r1 is less than 4
+        cmp      r1, #4
+        blt      1f
+        //right half
+        add      r0, #8
+        vld1.16 {d24}, [r0], r5
+        vld1.16 {d25}, [r0], r5
+        vld1.16 {d26}, [r0], r5
+        vld1.16 {d27}, [r0], r5
+        vld1.16 {d28}, [r0], r5
+        vld1.16 {d29}, [r0], r5
+        vld1.16 {d30}, [r0], r5
+        vld1.16 {d31}, [r0], r5
+        sub      r0, #128
+        tr8_begin d25, d27, d29, d31
+        tr4       d24, d26, d28, d30
+        tr8_end   #7
+        vst1.16 {d2}, [r0], r5
+        vst1.16 {d3}, [r0], r5
+        vst1.16 {d4}, [r0], r5
+        vst1.16 {d5}, [r0], r5
+        vst1.16 {d6}, [r0], r5
+        vst1.16 {d7}, [r0], r5
+        vst1.16 {d8}, [r0], r5
+        vst1.16 {d9}, [r0], r5
+        sub      r0, #136
+1:
+        // top half
+        vldm r0, {q12-q15} // coeffs
+        transpose_16b_4x4 d24, d26, d28, d30
+        transpose_16b_4x4 d25, d27, d29, d31
+        tr8_begin d26, d30, d27, d31
+        tr4 d24, d28, d25, d29
+        tr8_end #12
+        transpose_16b_4x4 d2, d3, d4, d5
+        transpose_16b_4x4 d6, d7, d8, d9
+        vswp     d7, d5
+        vswp     d7, d8
+        vswp     d3, d6
+        vswp     d6, d4
+        vstm r0!, {q1-q4}
+
+        // bottom half
+        vldm r0, {q12-q15} // coeffs
+        transpose_16b_4x4 d24, d26, d28, d30
+        transpose_16b_4x4 d25, d27, d29, d31
+        tr8_begin d26, d30, d27, d31
+        tr4 d24, d28, d25, d29
+        tr8_end #12
+        transpose_16b_4x4 d2, d3, d4, d5
+        transpose_16b_4x4 d6, d7, d8, d9
+        vswp     d7, d5
+        vswp     d7, d8
+        vswp     d3, d6
+        vswp     d6, d4
+        //vstm     r0, {q1-q4}
+        vst1.16 {q1-q2}, [r0]
+        add     r0, #32
+        vst1.16 {q3-q4}, [r0]
+        sub     r0, #32
+        vpop {d8-d15}
+        pop {r4-r8}
+        bx lr
+endfunc
+
+.align 4
+tr4f:
+.word 0x00240053  // 36 and d1[0] = 83
+.word 0x00000000
+tr8f:
+.word 0x0059004b  // 89, d0[0] = 75
+.word 0x00320012  // 50, d0[2] = 18
+tr16:
+.word 0x005a0057  // 90, d2[0] = 87
+.word 0x00500046  // 80, d2[2] = 70
+.word 0x0039002b  // 57, d2[0] = 43
+.word 0x00190009  // 25, d2[2] = 9
diff --git a/libavcodec/arm/hevcdsp_init_arm.c b/libavcodec/arm/hevcdsp_init_arm.c
new file mode 100644
index 0000000..adcc454
--- /dev/null
+++ b/libavcodec/arm/hevcdsp_init_arm.c
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2014 Seppo Tomperi <seppo.tomperi@vtt.fi>
+ *
+ * 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/attributes.h"
+#include "libavutil/arm/cpu.h"
+#include "libavcodec/hevcdsp.h"
+#include "hevcdsp_arm.h"
+
+av_cold void ff_hevcdsp_init_arm(HEVCDSPContext *c, const int bit_depth)
+{
+    int cpu_flags = av_get_cpu_flags();
+
+    if (have_neon(cpu_flags))
+        ff_hevcdsp_init_neon(c, bit_depth);
+}
diff --git a/libavcodec/arm/hevcdsp_init_neon.c b/libavcodec/arm/hevcdsp_init_neon.c
new file mode 100644
index 0000000..5591807
--- /dev/null
+++ b/libavcodec/arm/hevcdsp_init_neon.c
@@ -0,0 +1,224 @@
+/*
+ * Copyright (c) 2014 Seppo Tomperi <seppo.tomperi@vtt.fi>
+ *
+ * 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/attributes.h"
+#include "libavutil/arm/cpu.h"
+#include "libavcodec/hevcdsp.h"
+#include "hevcdsp_arm.h"
+
+void ff_hevc_v_loop_filter_luma_neon(uint8_t *_pix, ptrdiff_t _stride, int _beta, int *_tc, uint8_t *_no_p, uint8_t *_no_q);
+void ff_hevc_h_loop_filter_luma_neon(uint8_t *_pix, ptrdiff_t _stride, int _beta, int *_tc, uint8_t *_no_p, uint8_t *_no_q);
+void ff_hevc_v_loop_filter_chroma_neon(uint8_t *_pix, ptrdiff_t _stride, int *_tc, uint8_t *_no_p, uint8_t *_no_q);
+void ff_hevc_h_loop_filter_chroma_neon(uint8_t *_pix, ptrdiff_t _stride, int *_tc, uint8_t *_no_p, uint8_t *_no_q);
+void ff_hevc_transform_4x4_neon_8(int16_t *coeffs, int col_limit);
+void ff_hevc_transform_8x8_neon_8(int16_t *coeffs, int col_limit);
+void ff_hevc_idct_4x4_dc_neon_8(int16_t *coeffs);
+void ff_hevc_idct_8x8_dc_neon_8(int16_t *coeffs);
+void ff_hevc_idct_16x16_dc_neon_8(int16_t *coeffs);
+void ff_hevc_idct_32x32_dc_neon_8(int16_t *coeffs);
+void ff_hevc_transform_luma_4x4_neon_8(int16_t *coeffs);
+void ff_hevc_transform_add_4x4_neon_8(uint8_t *_dst, int16_t *coeffs,
+                                      ptrdiff_t stride);
+void ff_hevc_transform_add_8x8_neon_8(uint8_t *_dst, int16_t *coeffs,
+                                      ptrdiff_t stride);
+void ff_hevc_transform_add_16x16_neon_8(uint8_t *_dst, int16_t *coeffs,
+                                      ptrdiff_t stride);
+void ff_hevc_transform_add_32x32_neon_8(uint8_t *_dst, int16_t *coeffs,
+                                      ptrdiff_t stride);
+
+#define PUT_PIXELS(name) \
+    void name(int16_t *dst, uint8_t *src, \
+                                ptrdiff_t srcstride, int height, \
+                                intptr_t mx, intptr_t my, int width)
+PUT_PIXELS(ff_hevc_put_pixels_w2_neon_8);
+PUT_PIXELS(ff_hevc_put_pixels_w4_neon_8);
+PUT_PIXELS(ff_hevc_put_pixels_w6_neon_8);
+PUT_PIXELS(ff_hevc_put_pixels_w8_neon_8);
+PUT_PIXELS(ff_hevc_put_pixels_w12_neon_8);
+PUT_PIXELS(ff_hevc_put_pixels_w16_neon_8);
+PUT_PIXELS(ff_hevc_put_pixels_w24_neon_8);
+PUT_PIXELS(ff_hevc_put_pixels_w32_neon_8);
+PUT_PIXELS(ff_hevc_put_pixels_w48_neon_8);
+PUT_PIXELS(ff_hevc_put_pixels_w64_neon_8);
+#undef PUT_PIXELS
+
+static void (*put_hevc_qpel_neon[4][4])(int16_t *dst, ptrdiff_t dststride, uint8_t *src, ptrdiff_t srcstride,
+                                   int height, int width);
+static void (*put_hevc_qpel_uw_neon[4][4])(uint8_t *dst, ptrdiff_t dststride, uint8_t *_src, ptrdiff_t _srcstride,
+                                   int width, int height, int16_t* src2, ptrdiff_t src2stride);
+void ff_hevc_put_qpel_neon_wrapper(int16_t *dst, uint8_t *src, ptrdiff_t srcstride,
+                                   int height, intptr_t mx, intptr_t my, int width);
+void ff_hevc_put_qpel_uni_neon_wrapper(uint8_t *dst, ptrdiff_t dststride, uint8_t *src, ptrdiff_t srcstride,
+                                   int height, intptr_t mx, intptr_t my, int width);
+void ff_hevc_put_qpel_bi_neon_wrapper(uint8_t *dst, ptrdiff_t dststride, uint8_t *src, ptrdiff_t srcstride,
+                                       int16_t *src2,
+                                       int height, intptr_t mx, intptr_t my, int width);
+#define QPEL_FUNC(name) \
+    void name(int16_t *dst, ptrdiff_t dststride, uint8_t *src, ptrdiff_t srcstride, \
+                                   int height, int width)
+
+QPEL_FUNC(ff_hevc_put_qpel_v1_neon_8);
+QPEL_FUNC(ff_hevc_put_qpel_v2_neon_8);
+QPEL_FUNC(ff_hevc_put_qpel_v3_neon_8);
+QPEL_FUNC(ff_hevc_put_qpel_h1_neon_8);
+QPEL_FUNC(ff_hevc_put_qpel_h2_neon_8);
+QPEL_FUNC(ff_hevc_put_qpel_h3_neon_8);
+QPEL_FUNC(ff_hevc_put_qpel_h1v1_neon_8);
+QPEL_FUNC(ff_hevc_put_qpel_h1v2_neon_8);
+QPEL_FUNC(ff_hevc_put_qpel_h1v3_neon_8);
+QPEL_FUNC(ff_hevc_put_qpel_h2v1_neon_8);
+QPEL_FUNC(ff_hevc_put_qpel_h2v2_neon_8);
+QPEL_FUNC(ff_hevc_put_qpel_h2v3_neon_8);
+QPEL_FUNC(ff_hevc_put_qpel_h3v1_neon_8);
+QPEL_FUNC(ff_hevc_put_qpel_h3v2_neon_8);
+QPEL_FUNC(ff_hevc_put_qpel_h3v3_neon_8);
+#undef QPEL_FUNC
+
+#define QPEL_FUNC_UW_PIX(name) \
+    void name(uint8_t *dst, ptrdiff_t dststride, uint8_t *_src, ptrdiff_t _srcstride, \
+                                   int height, intptr_t mx, intptr_t my, int width);
+QPEL_FUNC_UW_PIX(ff_hevc_put_qpel_uw_pixels_w4_neon_8);
+QPEL_FUNC_UW_PIX(ff_hevc_put_qpel_uw_pixels_w8_neon_8);
+QPEL_FUNC_UW_PIX(ff_hevc_put_qpel_uw_pixels_w16_neon_8);
+QPEL_FUNC_UW_PIX(ff_hevc_put_qpel_uw_pixels_w24_neon_8);
+QPEL_FUNC_UW_PIX(ff_hevc_put_qpel_uw_pixels_w32_neon_8);
+QPEL_FUNC_UW_PIX(ff_hevc_put_qpel_uw_pixels_w48_neon_8);
+QPEL_FUNC_UW_PIX(ff_hevc_put_qpel_uw_pixels_w64_neon_8);
+#undef QPEL_FUNC_UW_PIX
+
+#define QPEL_FUNC_UW(name) \
+    void name(uint8_t *dst, ptrdiff_t dststride, uint8_t *_src, ptrdiff_t _srcstride, \
+                                   int width, int height, int16_t* src2, ptrdiff_t src2stride);
+QPEL_FUNC_UW(ff_hevc_put_qpel_uw_pixels_neon_8);
+QPEL_FUNC_UW(ff_hevc_put_qpel_uw_v1_neon_8);
+QPEL_FUNC_UW(ff_hevc_put_qpel_uw_v2_neon_8);
+QPEL_FUNC_UW(ff_hevc_put_qpel_uw_v3_neon_8);
+QPEL_FUNC_UW(ff_hevc_put_qpel_uw_h1_neon_8);
+QPEL_FUNC_UW(ff_hevc_put_qpel_uw_h2_neon_8);
+QPEL_FUNC_UW(ff_hevc_put_qpel_uw_h3_neon_8);
+QPEL_FUNC_UW(ff_hevc_put_qpel_uw_h1v1_neon_8);
+QPEL_FUNC_UW(ff_hevc_put_qpel_uw_h1v2_neon_8);
+QPEL_FUNC_UW(ff_hevc_put_qpel_uw_h1v3_neon_8);
+QPEL_FUNC_UW(ff_hevc_put_qpel_uw_h2v1_neon_8);
+QPEL_FUNC_UW(ff_hevc_put_qpel_uw_h2v2_neon_8);
+QPEL_FUNC_UW(ff_hevc_put_qpel_uw_h2v3_neon_8);
+QPEL_FUNC_UW(ff_hevc_put_qpel_uw_h3v1_neon_8);
+QPEL_FUNC_UW(ff_hevc_put_qpel_uw_h3v2_neon_8);
+QPEL_FUNC_UW(ff_hevc_put_qpel_uw_h3v3_neon_8);
+#undef QPEL_FUNC_UW
+
+void ff_hevc_put_qpel_neon_wrapper(int16_t *dst, uint8_t *src, ptrdiff_t srcstride,
+                                   int height, intptr_t mx, intptr_t my, int width) {
+
+    put_hevc_qpel_neon[my][mx](dst, MAX_PB_SIZE, src, srcstride, height, width);
+}
+
+void ff_hevc_put_qpel_uni_neon_wrapper(uint8_t *dst, ptrdiff_t dststride, uint8_t *src, ptrdiff_t srcstride,
+                                   int height, intptr_t mx, intptr_t my, int width) {
+
+    put_hevc_qpel_uw_neon[my][mx](dst, dststride, src, srcstride, width, height, NULL, 0);
+}
+
+void ff_hevc_put_qpel_bi_neon_wrapper(uint8_t *dst, ptrdiff_t dststride, uint8_t *src, ptrdiff_t srcstride,
+                                       int16_t *src2,
+                                       int height, intptr_t mx, intptr_t my, int width) {
+    put_hevc_qpel_uw_neon[my][mx](dst, dststride, src, srcstride, width, height, src2, MAX_PB_SIZE);
+}
+
+av_cold void ff_hevcdsp_init_neon(HEVCDSPContext *c, const int bit_depth)
+{
+    if (bit_depth == 8) {
+        int x;
+        c->hevc_v_loop_filter_luma     = ff_hevc_v_loop_filter_luma_neon;
+        c->hevc_h_loop_filter_luma     = ff_hevc_h_loop_filter_luma_neon;
+        c->hevc_v_loop_filter_chroma   = ff_hevc_v_loop_filter_chroma_neon;
+        c->hevc_h_loop_filter_chroma   = ff_hevc_h_loop_filter_chroma_neon;
+        c->idct[0]                     = ff_hevc_transform_4x4_neon_8;
+        c->idct[1]                     = ff_hevc_transform_8x8_neon_8;
+        c->idct_dc[0]                  = ff_hevc_idct_4x4_dc_neon_8;
+        c->idct_dc[1]                  = ff_hevc_idct_8x8_dc_neon_8;
+        c->idct_dc[2]                  = ff_hevc_idct_16x16_dc_neon_8;
+        c->idct_dc[3]                  = ff_hevc_idct_32x32_dc_neon_8;
+        c->transform_add[0]            = ff_hevc_transform_add_4x4_neon_8;
+        c->transform_add[1]            = ff_hevc_transform_add_8x8_neon_8;
+        c->transform_add[2]            = ff_hevc_transform_add_16x16_neon_8;
+        c->transform_add[3]            = ff_hevc_transform_add_32x32_neon_8;
+        c->idct_4x4_luma               = ff_hevc_transform_luma_4x4_neon_8;
+        put_hevc_qpel_neon[1][0]       = ff_hevc_put_qpel_v1_neon_8;
+        put_hevc_qpel_neon[2][0]       = ff_hevc_put_qpel_v2_neon_8;
+        put_hevc_qpel_neon[3][0]       = ff_hevc_put_qpel_v3_neon_8;
+        put_hevc_qpel_neon[0][1]       = ff_hevc_put_qpel_h1_neon_8;
+        put_hevc_qpel_neon[0][2]       = ff_hevc_put_qpel_h2_neon_8;
+        put_hevc_qpel_neon[0][3]       = ff_hevc_put_qpel_h3_neon_8;
+        put_hevc_qpel_neon[1][1]       = ff_hevc_put_qpel_h1v1_neon_8;
+        put_hevc_qpel_neon[1][2]       = ff_hevc_put_qpel_h2v1_neon_8;
+        put_hevc_qpel_neon[1][3]       = ff_hevc_put_qpel_h3v1_neon_8;
+        put_hevc_qpel_neon[2][1]       = ff_hevc_put_qpel_h1v2_neon_8;
+        put_hevc_qpel_neon[2][2]       = ff_hevc_put_qpel_h2v2_neon_8;
+        put_hevc_qpel_neon[2][3]       = ff_hevc_put_qpel_h3v2_neon_8;
+        put_hevc_qpel_neon[3][1]       = ff_hevc_put_qpel_h1v3_neon_8;
+        put_hevc_qpel_neon[3][2]       = ff_hevc_put_qpel_h2v3_neon_8;
+        put_hevc_qpel_neon[3][3]       = ff_hevc_put_qpel_h3v3_neon_8;
+        put_hevc_qpel_uw_neon[1][0]      = ff_hevc_put_qpel_uw_v1_neon_8;
+        put_hevc_qpel_uw_neon[2][0]      = ff_hevc_put_qpel_uw_v2_neon_8;
+        put_hevc_qpel_uw_neon[3][0]      = ff_hevc_put_qpel_uw_v3_neon_8;
+        put_hevc_qpel_uw_neon[0][1]      = ff_hevc_put_qpel_uw_h1_neon_8;
+        put_hevc_qpel_uw_neon[0][2]      = ff_hevc_put_qpel_uw_h2_neon_8;
+        put_hevc_qpel_uw_neon[0][3]      = ff_hevc_put_qpel_uw_h3_neon_8;
+        put_hevc_qpel_uw_neon[1][1]      = ff_hevc_put_qpel_uw_h1v1_neon_8;
+        put_hevc_qpel_uw_neon[1][2]      = ff_hevc_put_qpel_uw_h2v1_neon_8;
+        put_hevc_qpel_uw_neon[1][3]      = ff_hevc_put_qpel_uw_h3v1_neon_8;
+        put_hevc_qpel_uw_neon[2][1]      = ff_hevc_put_qpel_uw_h1v2_neon_8;
+        put_hevc_qpel_uw_neon[2][2]      = ff_hevc_put_qpel_uw_h2v2_neon_8;
+        put_hevc_qpel_uw_neon[2][3]      = ff_hevc_put_qpel_uw_h3v2_neon_8;
+        put_hevc_qpel_uw_neon[3][1]      = ff_hevc_put_qpel_uw_h1v3_neon_8;
+        put_hevc_qpel_uw_neon[3][2]      = ff_hevc_put_qpel_uw_h2v3_neon_8;
+        put_hevc_qpel_uw_neon[3][3]      = ff_hevc_put_qpel_uw_h3v3_neon_8;
+        for (x = 0; x < 10; x++) {
+            c->put_hevc_qpel[x][1][0]         = ff_hevc_put_qpel_neon_wrapper;
+            c->put_hevc_qpel[x][0][1]         = ff_hevc_put_qpel_neon_wrapper;
+            c->put_hevc_qpel[x][1][1]         = ff_hevc_put_qpel_neon_wrapper;
+            c->put_hevc_qpel_uni[x][1][0]     = ff_hevc_put_qpel_uni_neon_wrapper;
+            c->put_hevc_qpel_uni[x][0][1]     = ff_hevc_put_qpel_uni_neon_wrapper;
+            c->put_hevc_qpel_uni[x][1][1]     = ff_hevc_put_qpel_uni_neon_wrapper;
+            c->put_hevc_qpel_bi[x][1][0]      = ff_hevc_put_qpel_bi_neon_wrapper;
+            c->put_hevc_qpel_bi[x][0][1]      = ff_hevc_put_qpel_bi_neon_wrapper;
+            c->put_hevc_qpel_bi[x][1][1]      = ff_hevc_put_qpel_bi_neon_wrapper;
+        }
+        c->put_hevc_qpel[0][0][0]  = ff_hevc_put_pixels_w2_neon_8;
+        c->put_hevc_qpel[1][0][0]  = ff_hevc_put_pixels_w4_neon_8;
+        c->put_hevc_qpel[2][0][0]  = ff_hevc_put_pixels_w6_neon_8;
+        c->put_hevc_qpel[3][0][0]  = ff_hevc_put_pixels_w8_neon_8;
+        c->put_hevc_qpel[4][0][0]  = ff_hevc_put_pixels_w12_neon_8;
+        c->put_hevc_qpel[5][0][0]  = ff_hevc_put_pixels_w16_neon_8;
+        c->put_hevc_qpel[6][0][0]  = ff_hevc_put_pixels_w24_neon_8;
+        c->put_hevc_qpel[7][0][0]  = ff_hevc_put_pixels_w32_neon_8;
+        c->put_hevc_qpel[8][0][0]  = ff_hevc_put_pixels_w48_neon_8;
+        c->put_hevc_qpel[9][0][0]  = ff_hevc_put_pixels_w64_neon_8;
+
+        c->put_hevc_qpel_uni[1][0][0]  = ff_hevc_put_qpel_uw_pixels_w4_neon_8;
+        c->put_hevc_qpel_uni[3][0][0]  = ff_hevc_put_qpel_uw_pixels_w8_neon_8;
+        c->put_hevc_qpel_uni[5][0][0]  = ff_hevc_put_qpel_uw_pixels_w16_neon_8;
+        c->put_hevc_qpel_uni[6][0][0]  = ff_hevc_put_qpel_uw_pixels_w24_neon_8;
+        c->put_hevc_qpel_uni[7][0][0]  = ff_hevc_put_qpel_uw_pixels_w32_neon_8;
+        c->put_hevc_qpel_uni[8][0][0]  = ff_hevc_put_qpel_uw_pixels_w48_neon_8;
+        c->put_hevc_qpel_uni[9][0][0]  = ff_hevc_put_qpel_uw_pixels_w64_neon_8;
+    }
+}
diff --git a/libavcodec/arm/hevcdsp_qpel_neon.S b/libavcodec/arm/hevcdsp_qpel_neon.S
new file mode 100644
index 0000000..86f92cf
--- /dev/null
+++ b/libavcodec/arm/hevcdsp_qpel_neon.S
@@ -0,0 +1,999 @@
+/*
+ * Copyright (c) 2014 - 2015 Seppo Tomperi <seppo.tomperi@vtt.fi>
+ *
+ * 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/arm/asm.S"
+#include "neon.S"
+
+#define MAX_PB_SIZE #64
+
+.macro regshuffle_d8
+    vmov d16, d17
+    vmov d17, d18
+    vmov d18, d19
+    vmov d19, d20
+    vmov d20, d21
+    vmov d21, d22
+    vmov d22, d23
+.endm
+
+.macro regshuffle_q8
+    vmov q0, q1
+    vmov q1, q2
+    vmov q2, q3
+    vmov q3, q4
+    vmov q4, q5
+    vmov q5, q6
+    vmov q6, q7
+.endm
+
+.macro vextin8
+        pld       [r2]
+        vld1.8    {q11}, [r2], r3
+        vext.8    d16, d22, d23, #1
+        vext.8    d17, d22, d23, #2
+        vext.8    d18, d22, d23, #3
+        vext.8    d19, d22, d23, #4
+        vext.8    d20, d22, d23, #5
+        vext.8    d21, d22, d23, #6
+        vext.8    d22, d22, d23, #7
+.endm
+
+.macro loadin8
+        pld       [r2]
+        vld1.8    {d16}, [r2], r3
+        pld       [r2]
+        vld1.8    {d17}, [r2], r3
+        pld       [r2]
+        vld1.8    {d18}, [r2], r3
+        pld       [r2]
+        vld1.8    {d19}, [r2], r3
+        pld       [r2]
+        vld1.8    {d20}, [r2], r3
+        pld       [r2]
+        vld1.8    {d21}, [r2], r3
+        pld       [r2]
+        vld1.8    {d22}, [r2], r3
+        pld       [r2]
+        vld1.8    {d23}, [r2], r3
+.endm
+
+.macro qpel_filter_1_32b
+        vmov.i16   d16, #58
+        vmov.i16   d17, #10
+        vmull.s16   q9, d6, d16   // 58 * d0
+        vmull.s16  q10, d7, d16   // 58 * d1
+        vmov.i16   d16, #17
+        vmull.s16  q11, d4, d17   // 10 * c0
+        vmull.s16  q12, d5, d17   // 10 * c1
+        vmov.i16   d17, #5
+        vmull.s16  q13, d8, d16   // 17 * e0
+        vmull.s16  q14, d9, d16   // 17 * e1
+        vmull.s16  q15, d10, d17  //  5 * f0
+        vmull.s16   q8, d11, d17  //  5 * f1
+        vsub.s32    q9, q11       // 58 * d0 - 10 * c0
+        vsub.s32   q10, q12       // 58 * d1 - 10 * c1
+        vshll.s16  q11, d2, #2    // 4 * b0
+        vshll.s16  q12, d3, #2    // 4 * b1
+        vadd.s32    q9, q13       // 58 * d0 - 10 * c0 + 17 * e0
+        vadd.s32   q10, q14       // 58 * d1 - 10 * c1 + 17 * e1
+        vsubl.s16  q13, d12, d0   // g0 - a0
+        vsubl.s16  q14, d13, d1   // g1 - a1
+        vadd.s32    q9, q11       // 58 * d0 - 10 * c0 + 17 * e0 + 4 * b0
+        vadd.s32   q10, q12       // 58 * d1 - 10 * c1 + 17 * e1 + 4 * b1
+        vsub.s32   q13, q15       // g0 - a0 - 5 * f0
+        vsub.s32   q14, q8        // g1 - a1 - 5 * f1
+        vadd.s32    q9, q13       // 58 * d0 - 10 * c0 + 17 * e0 + 4 * b0 + g0 - a0 - 5 * f0
+        vadd.s32   q10, q14       // 58 * d1 - 10 * c1 + 17 * e1 + 4 * b1 + g1 - a1 - 5 * f1
+        vqshrn.s32  d16, q9, #6
+        vqshrn.s32  d17, q10, #6
+.endm
+
+// input  q0 - q7
+// output q8
+.macro qpel_filter_2_32b
+        vmov.i32   q8, #11
+        vaddl.s16   q9, d6, d8   // d0 + e0
+        vaddl.s16  q10, d7, d9   // d1 + e1
+        vaddl.s16  q11, d4, d10  // c0 + f0
+        vaddl.s16  q12, d5, d11  // c1 + f1
+        vmul.s32   q11, q8       // 11 * (c0 + f0)
+        vmul.s32   q12, q8       // 11 * (c1 + f1)
+        vmov.i32   q8, #40
+        vaddl.s16  q15, d2, d12  // b0 + g0
+        vmul.s32    q9, q8       // 40 * (d0 + e0)
+        vmul.s32   q10, q8       // 40 * (d1 + e1)
+        vaddl.s16   q8, d3, d13  // b1 + g1
+        vaddl.s16  q13, d0, d14  // a0 + h0
+        vaddl.s16  q14, d1, d15  // a1 + h1
+        vshl.s32   q15, #2       // 4*(b0+g0)
+        vshl.s32    q8, #2       // 4*(b1+g1)
+        vadd.s32   q11, q13      // 11 * (c0 + f0) + a0 + h0
+        vadd.s32   q12, q14      // 11 * (c1 + f1) + a1 + h1
+        vadd.s32   q9, q15       // 40 * (d0 + e0) + 4*(b0+g0)
+        vadd.s32   q10, q8       // 40 * (d1 + e1) + 4*(b1+g1)
+        vsub.s32   q9, q11       // 40 * (d0 + e0) + 4*(b0+g0) - (11 * (c0 + f0) + a0 + h0)
+        vsub.s32   q10, q12      // 40 * (d1 + e1) + 4*(b1+g1) - (11 * (c1 + f1) + a1 + h1)
+        vqshrn.s32  d16, q9, #6
+        vqshrn.s32  d17, q10, #6
+.endm
+
+.macro qpel_filter_3_32b
+        vmov.i16   d16, #58
+        vmov.i16   d17, #10
+        vmull.s16   q9, d8, d16   // 58 * d0
+        vmull.s16  q10, d9, d16   // 58 * d1
+        vmov.i16   d16, #17
+        vmull.s16  q11, d10, d17  // 10 * c0
+        vmull.s16  q12, d11, d17  // 10 * c1
+        vmov.i16   d17, #5
+        vmull.s16  q13, d6, d16   // 17 * e0
+        vmull.s16  q14, d7, d16   // 17 * e1
+        vmull.s16  q15, d4, d17   //  5 * f0
+        vmull.s16   q8, d5, d17   //  5 * f1
+        vsub.s32    q9, q11       // 58 * d0 - 10 * c0
+        vsub.s32   q10, q12       // 58 * d1 - 10 * c1
+        vshll.s16  q11, d12, #2   // 4 * b0
+        vshll.s16  q12, d13, #2   // 4 * b1
+        vadd.s32    q9, q13       // 58 * d0 - 10 * c0 + 17 * e0
+        vadd.s32   q10, q14       // 58 * d1 - 10 * c1 + 17 * e1
+        vsubl.s16  q13, d2, d14   // g0 - a0
+        vsubl.s16  q14, d3, d15   // g1 - a1
+        vadd.s32    q9, q11       // 58 * d0 - 10 * c0 + 17 * e0 + 4 * b0
+        vadd.s32   q10, q12       // 58 * d1 - 10 * c1 + 17 * e1 + 4 * b1
+        vsub.s32   q13, q15       // g0 - a0 - 5 * f0
+        vsub.s32   q14, q8        // g1 - a1 - 5 * f1
+        vadd.s32    q9, q13       // 58 * d0 - 10 * c0 + 17 * e0 + 4 * b0 + g0 - a0 - 5 * f0
+        vadd.s32   q10, q14       // 58 * d1 - 10 * c1 + 17 * e1 + 4 * b1 + g1 - a1 - 5 * f1
+        vqshrn.s32  d16, q9, #6
+        vqshrn.s32  d17, q10, #6
+.endm
+
+.macro qpel_filter_1 out=q7
+        vmov.u8    d24, #58
+        vmov.u8    d25, #10
+        vshll.u8   q13, d20, #4   // 16*e
+        vshll.u8   q14, d21, #2   // 4*f
+        vmull.u8  \out, d19, d24  // 58*d
+        vaddw.u8   q13, q13, d20  // 17*e
+        vmull.u8   q15, d18, d25  // 10*c
+        vaddw.u8   q14, q14, d21  // 5*f
+        vsubl.u8   q12, d22, d16  // g - a
+        vadd.u16  \out, q13       // 58d + 17e
+        vshll.u8   q13, d17, #2   // 4*b
+        vadd.u16   q15, q14       // 10*c + 5*f
+        vadd.s16   q13, q12       // - a + 4*b + g
+        vsub.s16  \out, q15       // -10*c + 58*d + 17*e -5*f
+        vadd.s16  \out, q13       // -a + 4*b -10*c + 58*d + 17*e -5*f
+.endm
+
+.macro qpel_filter_2 out=q7
+        vmov.i16   q12, #10
+        vmov.i16   q14, #11
+        vaddl.u8   q13, d19, d20   // d + e
+        vaddl.u8   q15, d18, d21   // c + f
+        vmul.u16   q13, q12        // 10 * (d+e)
+        vmul.u16   q15, q14        // 11 * ( c + f)
+        vaddl.u8  \out, d17, d22   // b + g
+        vaddl.u8   q12, d16, d23   // a + h
+        vadd.u16  \out, q13        // b + 10 * (d + e) + g
+        vadd.s16   q12, q15
+        vshl.u16  \out, #2         // 4 * (b + 10 * (d + e) + g)
+        vsub.s16  \out, q12
+.endm
+
+.macro qpel_filter_3 out=q7
+        vmov.u8    d24, #58
+        vmov.u8    d25, #10
+        vshll.u8   q13, d19, #4     // 16*e
+        vshll.u8   q14, d18, #2     // 4*f
+        vmull.u8  \out, d20, d24    // 58*d
+        vaddw.u8   q13, q13, d19    // 17*e
+        vmull.u8   q15, d21, d25    // 10*c
+        vaddw.u8   q14, q14, d18    // 5*f
+        vsubl.u8   q12, d17, d23    // g - a
+        vadd.u16  \out, q13         // 58d + 17e
+        vshll.u8   q13, d22, #2     // 4*b
+        vadd.u16   q15, q14         // 10*c + 5*f
+        vadd.s16   q13, q12         // - a + 4*b + g
+        vsub.s16  \out, q15         // -10*c + 58*d + 17*e -5*f
+        vadd.s16  \out, q13         // -a + 4*b -10*c + 58*d + 17*e -5*f
+.endm
+
+.macro  hevc_put_qpel_vX_neon_8 filter
+        push   {r4, r5, r6, r7}
+        ldr    r4, [sp, #16] // height
+        ldr    r5, [sp, #20] // width
+        vpush {d8-d15}
+        sub       r2, r2, r3, lsl #1
+        sub       r2, r3
+        mov       r12, r4
+        mov       r6, r0
+        mov       r7, r2
+        lsl       r1, #1
+0:      loadin8
+        cmp       r5, #4
+        beq       4f
+8:      subs r4, #1
+        \filter
+        vst1.16    {q7}, [r0], r1
+        regshuffle_d8
+        vld1.8    {d23}, [r2], r3
+        bne 8b
+        subs  r5, #8
+        beq       99f
+        mov r4, r12
+        add r6, #16
+        mov r0, r6
+        add r7, #8
+        mov r2, r7
+        b     0b
+4:      subs r4, #1
+        \filter
+        vst1.16    d14, [r0], r1
+        regshuffle_d8
+        vld1.32    {d23[0]}, [r2], r3
+        bne 4b
+99:     vpop {d8-d15}
+        pop {r4, r5, r6, r7}
+        bx lr
+.endm
+
+.macro  hevc_put_qpel_uw_vX_neon_8 filter
+        push   {r4-r10}
+        ldr    r5, [sp, #28] // width
+        ldr    r4, [sp, #32] // height
+        ldr    r8, [sp, #36] // src2
+        ldr    r9, [sp, #40] // src2stride
+        vpush {d8-d15}
+        sub       r2, r2, r3, lsl #1
+        sub       r2, r3
+        mov       r12, r4
+        mov       r6, r0
+        mov       r7, r2
+        cmp       r8, #0
+        bne       .Lbi\@
+0:      loadin8
+        cmp       r5, #4
+        beq       4f
+8:      subs r4, #1
+        \filter
+        vqrshrun.s16   d0, q7, #6
+        vst1.8    d0, [r0], r1
+        regshuffle_d8
+        vld1.8    {d23}, [r2], r3
+        bne 8b
+        subs  r5, #8
+        beq       99f
+        mov r4, r12
+        add r6, #8
+        mov r0, r6
+        add r7, #8
+        mov r2, r7
+        b     0b
+4:      subs r4, #1
+        \filter
+        vqrshrun.s16   d0, q7, #6
+        vst1.32    d0[0], [r0], r1
+        regshuffle_d8
+        vld1.32    {d23[0]}, [r2], r3
+        bne 4b
+        b   99f
+.Lbi\@: lsl       r9, #1
+        mov       r10, r8
+0:      loadin8
+        cmp       r5, #4
+        beq       4f
+8:      subs r4, #1
+        \filter
+        vld1.16        {q0}, [r8], r9
+        vqadd.s16      q0, q7
+        vqrshrun.s16   d0, q0, #7
+        vst1.8         d0, [r0], r1
+        regshuffle_d8
+        vld1.8    {d23}, [r2], r3
+        bne 8b
+        subs  r5, #8
+        beq       99f
+        mov r4, r12
+        add r6, #8
+        mov r0, r6
+        add r10, #16
+        mov r8, r10
+        add r7, #8
+        mov r2, r7
+        b     0b
+4:      subs r4, #1
+        \filter
+        vld1.16      d0, [r8], r9
+        vqadd.s16    d0, d14
+        vqrshrun.s16 d0, q0, #7
+        vst1.32      d0[0], [r0], r1
+        regshuffle_d8
+        vld1.32    {d23[0]}, [r2], r3
+        bne 4b
+99:     vpop {d8-d15}
+        pop {r4-r10}
+        bx lr
+.endm
+
+function ff_hevc_put_qpel_v1_neon_8, export=1
+        hevc_put_qpel_vX_neon_8 qpel_filter_1
+endfunc
+
+function ff_hevc_put_qpel_v2_neon_8, export=1
+        hevc_put_qpel_vX_neon_8 qpel_filter_2
+endfunc
+
+function ff_hevc_put_qpel_v3_neon_8, export=1
+        hevc_put_qpel_vX_neon_8 qpel_filter_3
+endfunc
+
+
+function ff_hevc_put_qpel_uw_v1_neon_8, export=1
+        hevc_put_qpel_uw_vX_neon_8 qpel_filter_1
+endfunc
+
+function ff_hevc_put_qpel_uw_v2_neon_8, export=1
+        hevc_put_qpel_uw_vX_neon_8 qpel_filter_2
+endfunc
+
+function ff_hevc_put_qpel_uw_v3_neon_8, export=1
+        hevc_put_qpel_uw_vX_neon_8 qpel_filter_3
+endfunc
+
+.macro hevc_put_qpel_hX_neon_8 filter
+        push     {r4, r5, r6, r7}
+        ldr    r4, [sp, #16] // height
+        ldr    r5, [sp, #20] // width
+
+        vpush    {d8-d15}
+        sub       r2, #4
+        lsl       r1, #1
+        mov      r12, r4
+        mov       r6, r0
+        mov       r7, r2
+        cmp       r5, #4
+        beq       4f
+8:      subs      r4, #1
+        vextin8
+        \filter
+        vst1.16   {q7}, [r0], r1
+        bne       8b
+        subs      r5, #8
+        beq      99f
+        mov       r4, r12
+        add       r6, #16
+        mov       r0, r6
+        add       r7, #8
+        mov       r2, r7
+        cmp       r5, #4
+        bne       8b
+4:      subs      r4, #1
+        vextin8
+        \filter
+        vst1.16  d14, [r0], r1
+        bne       4b
+99:     vpop     {d8-d15}
+        pop      {r4, r5, r6, r7}
+        bx lr
+.endm
+
+.macro hevc_put_qpel_uw_hX_neon_8 filter
+        push     {r4-r10}
+        ldr       r5, [sp, #28] // width
+        ldr       r4, [sp, #32] // height
+        ldr       r8, [sp, #36] // src2
+        ldr       r9, [sp, #40] // src2stride
+        vpush    {d8-d15}
+        sub       r2, #4
+        mov      r12, r4
+        mov       r6, r0
+        mov       r7, r2
+        cmp       r8, #0
+        bne       .Lbi\@
+        cmp       r5, #4
+        beq       4f
+8:      subs      r4, #1
+        vextin8
+        \filter
+        vqrshrun.s16   d0, q7, #6
+        vst1.8    d0, [r0], r1
+        bne       8b
+        subs      r5, #8
+        beq      99f
+        mov       r4, r12
+        add       r6, #8
+        mov       r0, r6
+        add       r7, #8
+        mov       r2, r7
+        cmp       r5, #4
+        bne       8b
+4:      subs      r4, #1
+        vextin8
+        \filter
+        vqrshrun.s16   d0, q7, #6
+        vst1.32  d0[0], [r0], r1
+        bne       4b
+        b         99f
+.Lbi\@:
+        lsl       r9, #1
+        cmp       r5, #4
+        beq       4f
+        mov       r10, r8
+8:      subs      r4, #1
+        vextin8
+        \filter
+        vld1.16        {q0}, [r8], r9
+        vqadd.s16      q0, q7
+        vqrshrun.s16   d0, q0, #7
+        vst1.8         d0, [r0], r1
+        bne       8b
+        subs      r5, #8
+        beq      99f
+        mov       r4, r12
+        add       r6, #8
+        add       r10, #16
+        mov       r8, r10
+        mov       r0, r6
+        add       r7, #8
+        mov       r2, r7
+        cmp       r5, #4
+        bne       8b
+4:      subs      r4, #1
+        vextin8
+        \filter
+        vld1.16      d0, [r8], r9
+        vqadd.s16    d0, d14
+        vqrshrun.s16 d0, q0, #7
+        vst1.32      d0[0], [r0], r1
+        bne       4b
+99:     vpop     {d8-d15}
+        pop      {r4-r10}
+        bx lr
+.endm
+
+function ff_hevc_put_qpel_h1_neon_8, export=1
+        hevc_put_qpel_hX_neon_8 qpel_filter_1
+endfunc
+
+function ff_hevc_put_qpel_h2_neon_8, export=1
+        hevc_put_qpel_hX_neon_8 qpel_filter_2
+endfunc
+
+function ff_hevc_put_qpel_h3_neon_8, export=1
+        hevc_put_qpel_hX_neon_8 qpel_filter_3
+endfunc
+
+
+function ff_hevc_put_qpel_uw_h1_neon_8, export=1
+        hevc_put_qpel_uw_hX_neon_8 qpel_filter_1
+endfunc
+
+function ff_hevc_put_qpel_uw_h2_neon_8, export=1
+        hevc_put_qpel_uw_hX_neon_8 qpel_filter_2
+endfunc
+
+function ff_hevc_put_qpel_uw_h3_neon_8, export=1
+        hevc_put_qpel_uw_hX_neon_8 qpel_filter_3
+endfunc
+
+.macro hevc_put_qpel_hXvY_neon_8 filterh filterv
+        push   {r4, r5, r6, r7}
+        ldr    r4, [sp, #16] // height
+        ldr    r5, [sp, #20] // width
+
+        vpush {d8-d15}
+        sub       r2, #4
+        sub       r2, r2, r3, lsl #1
+        sub       r2, r3  // extra_before 3
+        lsl       r1, #1
+        mov       r12, r4
+        mov       r6, r0
+        mov       r7, r2
+0:      vextin8
+        \filterh q0
+        vextin8
+        \filterh q1
+        vextin8
+        \filterh q2
+        vextin8
+        \filterh q3
+        vextin8
+        \filterh q4
+        vextin8
+        \filterh q5
+        vextin8
+        \filterh q6
+        vextin8
+        \filterh q7
+        cmp r5, #4
+        beq 4f
+8:      subs  r4, #1
+        \filterv
+        vst1.16    {q8}, [r0], r1
+        regshuffle_q8
+        vextin8
+        \filterh q7
+        bne 8b
+        subs  r5, #8
+        beq 99f
+        mov r4, r12
+        add r6, #16
+        mov r0, r6
+        add r7, #8
+        mov r2, r7
+        b 0b
+4:      subs  r4, #1
+        \filterv
+        vst1.16    d16, [r0], r1
+        regshuffle_q8
+        vextin8
+        \filterh q7
+        bne 4b
+99:     vpop {d8-d15}
+        pop {r4, r5, r6, r7}
+        bx lr
+.endm
+
+.macro hevc_put_qpel_uw_hXvY_neon_8 filterh filterv
+        push     {r4-r10}
+        ldr       r5, [sp, #28] // width
+        ldr       r4, [sp, #32] // height
+        ldr       r8, [sp, #36] // src2
+        ldr       r9, [sp, #40] // src2stride
+        vpush {d8-d15}
+        sub       r2, #4
+        sub       r2, r2, r3, lsl #1
+        sub       r2, r3  // extra_before 3
+        mov       r12, r4
+        mov       r6, r0
+        mov       r7, r2
+        cmp       r8, #0
+        bne       .Lbi\@
+0:      vextin8
+        \filterh q0
+        vextin8
+        \filterh q1
+        vextin8
+        \filterh q2
+        vextin8
+        \filterh q3
+        vextin8
+        \filterh q4
+        vextin8
+        \filterh q5
+        vextin8
+        \filterh q6
+        vextin8
+        \filterh q7
+        cmp r5, #4
+        beq 4f
+8:      subs  r4, #1
+        \filterv
+        vqrshrun.s16   d0, q8, #6
+        vst1.8    d0, [r0], r1
+        regshuffle_q8
+        vextin8
+        \filterh q7
+        bne 8b
+        subs  r5, #8
+        beq 99f
+        mov r4, r12
+        add r6, #8
+        mov r0, r6
+        add r7, #8
+        mov r2, r7
+        b 0b
+4:      subs  r4, #1
+        \filterv
+        vqrshrun.s16   d0, q8, #6
+        vst1.32        d0[0], [r0], r1
+        regshuffle_q8
+        vextin8
+        \filterh q7
+        bne 4b
+        b   99f
+.Lbi\@: lsl      r9, #1
+        mov      r10, r8
+0:      vextin8
+        \filterh q0
+        vextin8
+        \filterh q1
+        vextin8
+        \filterh q2
+        vextin8
+        \filterh q3
+        vextin8
+        \filterh q4
+        vextin8
+        \filterh q5
+        vextin8
+        \filterh q6
+        vextin8
+        \filterh q7
+        cmp r5, #4
+        beq 4f
+8:      subs  r4, #1
+        \filterv
+        vld1.16        {q0}, [r8], r9
+        vqadd.s16      q0, q8
+        vqrshrun.s16   d0, q0, #7
+        vst1.8         d0, [r0], r1
+        regshuffle_q8
+        vextin8
+        \filterh q7
+        bne 8b
+        subs  r5, #8
+        beq 99f
+        mov r4, r12
+        add r6, #8
+        mov r0, r6
+        add r10, #16
+        mov r8, r10
+        add r7, #8
+        mov r2, r7
+        b 0b
+4:      subs  r4, #1
+        \filterv
+        vld1.16      d0, [r8], r9
+        vqadd.s16    d0, d16
+        vqrshrun.s16 d0, q0, #7
+        vst1.32      d0[0], [r0], r1
+        regshuffle_q8
+        vextin8
+        \filterh q7
+        bne 4b
+99:     vpop {d8-d15}
+        pop {r4-r10}
+        bx lr
+.endm
+
+
+function ff_hevc_put_qpel_h1v1_neon_8, export=1
+        hevc_put_qpel_hXvY_neon_8 qpel_filter_1 qpel_filter_1_32b
+endfunc
+
+function ff_hevc_put_qpel_h2v1_neon_8, export=1
+        hevc_put_qpel_hXvY_neon_8 qpel_filter_2 qpel_filter_1_32b
+endfunc
+
+function ff_hevc_put_qpel_h3v1_neon_8, export=1
+        hevc_put_qpel_hXvY_neon_8 qpel_filter_3 qpel_filter_1_32b
+endfunc
+
+function ff_hevc_put_qpel_h1v2_neon_8, export=1
+        hevc_put_qpel_hXvY_neon_8 qpel_filter_1 qpel_filter_2_32b
+endfunc
+
+function ff_hevc_put_qpel_h2v2_neon_8, export=1
+        hevc_put_qpel_hXvY_neon_8 qpel_filter_2 qpel_filter_2_32b
+endfunc
+
+function ff_hevc_put_qpel_h3v2_neon_8, export=1
+        hevc_put_qpel_hXvY_neon_8 qpel_filter_3 qpel_filter_2_32b
+endfunc
+
+function ff_hevc_put_qpel_h1v3_neon_8, export=1
+        hevc_put_qpel_hXvY_neon_8 qpel_filter_1 qpel_filter_3_32b
+endfunc
+
+function ff_hevc_put_qpel_h2v3_neon_8, export=1
+        hevc_put_qpel_hXvY_neon_8 qpel_filter_2 qpel_filter_3_32b
+endfunc
+
+function ff_hevc_put_qpel_h3v3_neon_8, export=1
+        hevc_put_qpel_hXvY_neon_8 qpel_filter_3 qpel_filter_3_32b
+endfunc
+
+
+function ff_hevc_put_qpel_uw_h1v1_neon_8, export=1
+        hevc_put_qpel_uw_hXvY_neon_8 qpel_filter_1 qpel_filter_1_32b
+endfunc
+
+function ff_hevc_put_qpel_uw_h2v1_neon_8, export=1
+        hevc_put_qpel_uw_hXvY_neon_8 qpel_filter_2 qpel_filter_1_32b
+endfunc
+
+function ff_hevc_put_qpel_uw_h3v1_neon_8, export=1
+        hevc_put_qpel_uw_hXvY_neon_8 qpel_filter_3 qpel_filter_1_32b
+endfunc
+
+function ff_hevc_put_qpel_uw_h1v2_neon_8, export=1
+        hevc_put_qpel_uw_hXvY_neon_8 qpel_filter_1 qpel_filter_2_32b
+endfunc
+
+function ff_hevc_put_qpel_uw_h2v2_neon_8, export=1
+        hevc_put_qpel_uw_hXvY_neon_8 qpel_filter_2 qpel_filter_2_32b
+endfunc
+
+function ff_hevc_put_qpel_uw_h3v2_neon_8, export=1
+        hevc_put_qpel_uw_hXvY_neon_8 qpel_filter_3 qpel_filter_2_32b
+endfunc
+
+function ff_hevc_put_qpel_uw_h1v3_neon_8, export=1
+        hevc_put_qpel_uw_hXvY_neon_8 qpel_filter_1 qpel_filter_3_32b
+endfunc
+
+function ff_hevc_put_qpel_uw_h2v3_neon_8, export=1
+        hevc_put_qpel_uw_hXvY_neon_8 qpel_filter_2 qpel_filter_3_32b
+endfunc
+
+function ff_hevc_put_qpel_uw_h3v3_neon_8, export=1
+        hevc_put_qpel_uw_hXvY_neon_8 qpel_filter_3 qpel_filter_3_32b
+endfunc
+
+.macro init_put_pixels
+        pld    [r1]
+        pld    [r1, r2]
+        mov    r12, MAX_PB_SIZE
+        lsl    r12, #1
+.endm
+
+function ff_hevc_put_pixels_w2_neon_8, export=1
+        init_put_pixels
+        vmov.u8      d5, #255
+        vshr.u64     d5, #32
+0:      subs r3, #1
+        vld1.32     {d0[0]}, [r1], r2
+        pld [r1]
+        vld1.32     d6, [r0]
+        vshll.u8    q0, d0, #6
+        vbit        d6, d0, d5
+        vst1.32     d6, [r0], r12
+        bne 0b
+        bx lr
+endfunc
+
+function ff_hevc_put_pixels_w4_neon_8, export=1
+        init_put_pixels
+0:      subs r3, #2
+        vld1.32   {d0[0]}, [r1], r2
+        vld1.32   {d0[1]}, [r1], r2
+        pld       [r1]
+        pld       [r1, r2]
+        vshll.u8   q0, d0, #6
+        vst1.64   {d0}, [r0], r12
+        vst1.64   {d1}, [r0], r12
+        bne 0b
+        bx lr
+endfunc
+
+function ff_hevc_put_pixels_w6_neon_8, export=1
+        init_put_pixels
+        vmov.u8      q10, #255
+        vshr.u64     d21, #32
+0:      subs r3, #1
+        vld1.16     {d0}, [r1], r2
+        pld [r1]
+        vshll.u8    q0, d0, #6
+        vld1.8      {q12}, [r0]
+        vbit        q12, q0, q10
+        vst1.8      {q12}, [r0], r12
+        bne 0b
+        bx lr
+endfunc
+
+function ff_hevc_put_pixels_w8_neon_8, export=1
+        init_put_pixels
+0:      subs r3, #2
+        vld1.8   {d0}, [r1], r2
+        vld1.8   {d2}, [r1], r2
+        pld        [r1]
+        pld        [r1, r2]
+        vshll.u8   q0, d0, #6
+        vshll.u8   q1, d2, #6
+        vst1.16   {q0}, [r0], r12
+        vst1.16   {q1}, [r0], r12
+        bne 0b
+        bx lr
+endfunc
+
+function ff_hevc_put_pixels_w12_neon_8, export=1
+        init_put_pixels
+0:      subs r3, #2
+        vld1.64    {d0}, [r1]
+        add       r1, #8
+        vld1.32   {d1[0]}, [r1], r2
+        sub       r1, #8
+        vld1.64    {d2}, [r1]
+        add       r1, #8
+        vld1.32   {d1[1]}, [r1], r2
+        sub       r1, #8
+        pld       [r1]
+        pld       [r1, r2]
+        vshll.u8  q8, d0, #6
+        vshll.u8  q9, d1, #6
+        vshll.u8  q10, d2, #6
+        vmov      d22, d19
+        vst1.64   {d16, d17, d18}, [r0], r12
+        vst1.64   {d20, d21, d22}, [r0], r12
+        bne 0b
+        bx lr
+endfunc
+
+function ff_hevc_put_pixels_w16_neon_8, export=1
+        init_put_pixels
+0:      subs r3, #2
+        vld1.8   {q0}, [r1], r2
+        vld1.8   {q1}, [r1], r2
+        pld       [r1]
+        pld       [r1, r2]
+        vshll.u8  q8, d0, #6
+        vshll.u8  q9, d1, #6
+        vshll.u8  q10, d2, #6
+        vshll.u8  q11, d3, #6
+        vst1.8    {q8, q9}, [r0], r12
+        vst1.8    {q10, q11}, [r0], r12
+        bne 0b
+        bx lr
+endfunc
+
+function ff_hevc_put_pixels_w24_neon_8, export=1
+        init_put_pixels
+0:      subs r3, #1
+        vld1.8   {d0, d1, d2}, [r1], r2
+        pld       [r1]
+        vshll.u8  q10, d0, #6
+        vshll.u8  q11, d1, #6
+        vshll.u8  q12, d2, #6
+        vstm     r0, {q10, q11, q12}
+        add      r0, r12
+        bne 0b
+        bx lr
+endfunc
+
+function ff_hevc_put_pixels_w32_neon_8, export=1
+        init_put_pixels
+0:      subs r3, #1
+        vld1.8 {q0, q1}, [r1], r2
+        pld       [r1]
+        vshll.u8  q8, d0, #6
+        vshll.u8  q9, d1, #6
+        vshll.u8  q10, d2, #6
+        vshll.u8  q11, d3, #6
+        vstm    r0, {q8, q9, q10, q11}
+        add     r0, r12
+        bne 0b
+        bx lr
+endfunc
+
+function ff_hevc_put_pixels_w48_neon_8, export=1
+        init_put_pixels
+0:      subs r3, #1
+        vld1.8    {q0, q1}, [r1]
+        add r1, #32
+        vld1.8    {q2}, [r1], r2
+        sub r1, #32
+        pld       [r1]
+        vshll.u8  q8, d0, #6
+        vshll.u8  q9, d1, #6
+        vshll.u8  q10, d2, #6
+        vshll.u8  q11, d3, #6
+        vshll.u8  q12, d4, #6
+        vshll.u8  q13, d5, #6
+        vstm r0, {q8, q9, q10, q11, q12, q13}
+        add  r0, r12
+        bne 0b
+        bx lr
+endfunc
+
+function ff_hevc_put_pixels_w64_neon_8, export=1
+        init_put_pixels
+0:      subs r3, #1
+        vld1.8    {q0, q1}, [r1]
+        add      r1, #32
+        vld1.8    {q2, q3}, [r1], r2
+        sub      r1, #32
+        pld       [r1]
+        vshll.u8  q8, d0, #6
+        vshll.u8  q9, d1, #6
+        vshll.u8  q10, d2, #6
+        vshll.u8  q11, d3, #6
+        vshll.u8  q12, d4, #6
+        vshll.u8  q13, d5, #6
+        vshll.u8  q14, d6, #6
+        vshll.u8  q15, d7, #6
+        vstm    r0, {q8, q9, q10, q11, q12, q13, q14, q15}
+        add r0, r12
+        bne 0b
+        bx lr
+endfunc
+
+function ff_hevc_put_qpel_uw_pixels_neon_8, export=1
+        push   {r4-r9}
+        ldr    r5, [sp, #24] // width
+        ldr    r4, [sp, #28] // height
+        ldr    r8, [sp, #32] // src2
+        ldr    r9, [sp, #36] // src2stride
+        vpush {d8-d15}
+        cmp    r8, #0
+        bne    2f
+1:      subs r4, #1
+        vld1.8     {d0}, [r2], r3
+        vst1.8      d0, [r0], r1
+        bne 1b
+        vpop {d8-d15}
+        pop   {r4-r9}
+        bx lr
+2:      subs  r4, #1
+        vld1.8         {d0}, [r2], r3
+        vld1.16        {q1}, [r8], r9
+        vshll.u8       q0, d0, #6
+        vqadd.s16      q0, q1
+        vqrshrun.s16   d0, q0, #7
+        vst1.8      d0, [r0], r1
+        bne 2b
+        vpop {d8-d15}
+        pop   {r4-r9}
+        bx lr
+endfunc
+
+.macro put_qpel_uw_pixels width, regs, regs2, regs3, regs4
+function ff_hevc_put_qpel_uw_pixels_w\width\()_neon_8, export=1
+        ldr    r12, [sp] // height
+1:      subs   r12, #4
+        vld1.32     {\regs}  , [r2], r3
+        vld1.32     {\regs2} , [r2], r3
+        vld1.32     {\regs3} , [r2], r3
+        vld1.32     {\regs4} , [r2], r3
+        vst1.32     {\regs}  , [r0], r1
+        vst1.32     {\regs2} , [r0], r1
+        vst1.32     {\regs3} , [r0], r1
+        vst1.32     {\regs4} , [r0], r1
+        bne 1b
+        bx lr
+endfunc
+.endm
+
+.macro put_qpel_uw_pixels_m width, regs, regs2, regs3, regs4
+function ff_hevc_put_qpel_uw_pixels_w\width\()_neon_8, export=1
+        push   {r4-r5}
+        ldr    r12, [sp, #8] // height
+1:      subs r12, #2
+        mov      r4, r2
+        vld1.32   {\regs} , [r2]!
+        vld1.32   {\regs2} , [r2]
+        add      r2, r4, r3
+        mov      r4, r2
+        vld1.32   {\regs3} , [r2]!
+        vld1.32   {\regs4} , [r2]
+        add      r2, r4, r3
+        mov      r5, r0
+        vst1.32   {\regs} , [r0]!
+        vst1.32   {\regs2} , [r0]
+        add      r0, r5, r1
+        mov      r5, r0
+        vst1.32   {\regs3} , [r0]!
+        vst1.32   {\regs4} , [r0]
+        add      r0, r5, r1
+        bne 1b
+        pop   {r4-r5}
+        bx lr
+endfunc
+.endm
+
+put_qpel_uw_pixels    4, d0[0], d0[1], d1[0], d1[1]
+put_qpel_uw_pixels    8, d0,    d1,    d2,    d3
+put_qpel_uw_pixels_m 12, d0,    d1[0], d2,    d3[0]
+put_qpel_uw_pixels   16, q0,    q1,    q2,    q3
+put_qpel_uw_pixels   24, d0-d2, d3-d5, d16-d18, d19-d21
+put_qpel_uw_pixels   32, q0-q1, q2-q3, q8-q9, q10-q11
+put_qpel_uw_pixels_m 48, q0-q1, q2,    q8-q9, q10
+put_qpel_uw_pixels_m 64, q0-q1, q2-q3, q8-q9, q10-q11
diff --git a/libavcodec/arm/videodsp_armv5te.S b/libavcodec/arm/videodsp_armv5te.S
index 55bcce5..aff1161 100644
--- a/libavcodec/arm/videodsp_armv5te.S
+++ b/libavcodec/arm/videodsp_armv5te.S
@@ -23,9 +23,10 @@
 #include "libavutil/arm/asm.S"
 
 function ff_prefetch_arm, export=1
+1:
         subs            r2,  r2,  #1
         pld             [r0]
         add             r0,  r0,  r1
-        bne             X(ff_prefetch_arm)
+        bne             1b
         bx              lr
 endfunc
diff --git a/libavcodec/atrac1.c b/libavcodec/atrac1.c
index aeb068c..f965dcc 100644
--- a/libavcodec/atrac1.c
+++ b/libavcodec/atrac1.c
@@ -57,7 +57,7 @@
 /**
  * Sound unit struct, one unit is used per channel
  */
-typedef struct {
+typedef struct AT1SUCtx {
     int                 log2_block_count[AT1_QMF_BANDS];    ///< log2 number of blocks in a band
     int                 num_bfus;                           ///< number of Block Floating Units
     float*              spectrum[2];
@@ -71,7 +71,7 @@
 /**
  * The atrac1 context, holds all needed parameters for decoding
  */
-typedef struct {
+typedef struct AT1Ctx {
     AT1SUCtx            SUs[AT1_MAX_CHANNELS];              ///< channel sound unit
     DECLARE_ALIGNED(32, float, spec)[AT1_SU_SAMPLES];      ///< the mdct spectrum buffer
 
diff --git a/libavcodec/atrac3.c b/libavcodec/atrac3.c
index 9dc0811..5aa3d8d 100644
--- a/libavcodec/atrac3.c
+++ b/libavcodec/atrac3.c
@@ -42,7 +42,6 @@
 #include "avcodec.h"
 #include "bytestream.h"
 #include "fft.h"
-#include "fmtconvert.h"
 #include "get_bits.h"
 #include "internal.h"
 
@@ -108,7 +107,6 @@
 
     AtracGCContext    gainc_ctx;
     FFTContext        mdct_ctx;
-    FmtConvertContext fmt_conv;
     AVFloatDSPContext *fdsp;
 } ATRAC3Context;
 
@@ -917,7 +915,6 @@
 
     ff_atrac_init_gain_compensation(&q->gainc_ctx, 4, 3);
     q->fdsp = avpriv_float_dsp_alloc(avctx->flags & CODEC_FLAG_BITEXACT);
-    ff_fmt_convert_init(&q->fmt_conv, avctx);
 
     q->units = av_mallocz_array(avctx->channels, sizeof(*q->units));
     if (!q->units || !q->fdsp) {
diff --git a/libavcodec/atrac3plusdec.c b/libavcodec/atrac3plusdec.c
index 78121e8..e6f0416 100644
--- a/libavcodec/atrac3plusdec.c
+++ b/libavcodec/atrac3plusdec.c
@@ -333,10 +333,8 @@
     float **samples_p = (float **)frame->extended_data;
 
     frame->nb_samples = ATRAC3P_FRAME_SAMPLES;
-    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
-        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
         return ret;
-    }
 
     if ((ret = init_get_bits8(&ctx->gb, avpkt->data, avpkt->size)) < 0)
         return ret;
diff --git a/libavcodec/audioconvert.h b/libavcodec/audioconvert.h
index 556ab31..996c3f3 100644
--- a/libavcodec/audioconvert.h
+++ b/libavcodec/audioconvert.h
@@ -23,6 +23,8 @@
 #ifndef AVCODEC_AUDIOCONVERT_H
 #define AVCODEC_AUDIOCONVERT_H
 
+#include "version.h"
+
 /**
  * @file
  * Audio format conversion routines
diff --git a/libavcodec/avcodec.h b/libavcodec/avcodec.h
index d7807a6..8cbad90 100644
--- a/libavcodec/avcodec.h
+++ b/libavcodec/avcodec.h
@@ -291,6 +291,8 @@
     AV_CODEC_ID_SGIRLE_DEPRECATED,
     AV_CODEC_ID_MVC1_DEPRECATED,
     AV_CODEC_ID_MVC2_DEPRECATED,
+    AV_CODEC_ID_HQX,
+    AV_CODEC_ID_TDSC,
 
     AV_CODEC_ID_BRENDER_PIX= MKBETAG('B','P','I','X'),
     AV_CODEC_ID_Y41P       = MKBETAG('Y','4','1','P'),
@@ -391,7 +393,9 @@
     AV_CODEC_ID_ADPCM_IMA_APC,
     AV_CODEC_ID_ADPCM_VIMA_DEPRECATED,
     AV_CODEC_ID_ADPCM_VIMA = MKBETAG('V','I','M','A'),
+#if FF_API_VIMA_DECODER
     AV_CODEC_ID_VIMA       = MKBETAG('V','I','M','A'),
+#endif
     AV_CODEC_ID_ADPCM_AFC  = MKBETAG('A','F','C',' '),
     AV_CODEC_ID_ADPCM_IMA_OKI = MKBETAG('O','K','I',' '),
     AV_CODEC_ID_ADPCM_DTK  = MKBETAG('D','T','K',' '),
@@ -482,6 +486,7 @@
     AV_CODEC_ID_METASOUND,
     AV_CODEC_ID_PAF_AUDIO_DEPRECATED,
     AV_CODEC_ID_ON2AVC,
+    AV_CODEC_ID_DSS_SP,
     AV_CODEC_ID_FFWAVESYNTH = MKBETAG('F','F','W','S'),
     AV_CODEC_ID_SONIC       = MKBETAG('S','O','N','C'),
     AV_CODEC_ID_SONIC_LS    = MKBETAG('S','O','N','L'),
@@ -1820,7 +1825,7 @@
     /**
      * precision of the intra DC coefficient - 8
      * - encoding: Set by user.
-     * - decoding: unused
+     * - decoding: Set by libavcodec
      */
     int intra_dc_precision;
 
@@ -2847,6 +2852,7 @@
 #define FF_PROFILE_DTS_96_24   40
 #define FF_PROFILE_DTS_HD_HRA  50
 #define FF_PROFILE_DTS_HD_MA   60
+#define FF_PROFILE_DTS_EXPRESS 70
 
 #define FF_PROFILE_MPEG2_422    0
 #define FF_PROFILE_MPEG2_HIGH   1
@@ -3259,6 +3265,11 @@
      * Will be called when seeking
      */
     void (*flush)(AVCodecContext *);
+    /**
+     * Internal codec capabilities.
+     * See FF_CODEC_CAP_* in internal.h
+     */
+    int caps_internal;
 } AVCodec;
 
 int av_codec_get_max_lowres(const AVCodec *codec);
@@ -3654,6 +3665,9 @@
  *
  * @warning This function is not thread safe!
  *
+ * @note Always call this function before using decoding routines (such as
+ * @ref avcodec_decode_video2()).
+ *
  * @code
  * avcodec_register_all();
  * av_dict_set(&opts, "b", "2.5M", 0);
@@ -4102,6 +4116,9 @@
  *          larger than the actual read bytes because some optimized bitstream
  *          readers read 32 or 64 bits at once and could read over the end.
  *
+ * @note The AVCodecContext MUST have been opened with @ref avcodec_open2()
+ * before packets may be fed to the decoder.
+ *
  * @param      avctx the codec context
  * @param[out] frame The AVFrame in which to store decoded audio samples.
  *                   The decoder will allocate a buffer for the decoded frame by
@@ -4146,6 +4163,9 @@
  * between input and output, these need to be fed with avpkt->data=NULL,
  * avpkt->size=0 at the end to return the remaining frames.
  *
+ * @note The AVCodecContext MUST have been opened with @ref avcodec_open2()
+ * before packets may be fed to the decoder.
+ *
  * @param avctx the codec context
  * @param[out] picture The AVFrame in which the decoded video frame will be stored.
  *             Use av_frame_alloc() to get an AVFrame. The codec will
@@ -4192,6 +4212,9 @@
  * returning subtitles. It is safe to flush even those decoders that are not
  * marked with CODEC_CAP_DELAY, then no subtitles will be returned.
  *
+ * @note The AVCodecContext MUST have been opened with @ref avcodec_open2()
+ * before packets may be fed to the decoder.
+ *
  * @param avctx the codec context
  * @param[out] sub The Preallocated AVSubtitle in which the decoded subtitle will be stored,
  *                 must be freed with avsubtitle_free if *got_sub_ptr is set.
@@ -4368,6 +4391,28 @@
      * For example, this corresponds to H.264 PicOrderCnt.
      */
     int output_picture_number;
+
+    /**
+     * Dimensions of the decoded video intended for presentation.
+     */
+    int width;
+    int height;
+
+    /**
+     * Dimensions of the coded video.
+     */
+    int coded_width;
+    int coded_height;
+
+    /**
+     * The format of the coded data, corresponds to enum AVPixelFormat for video
+     * and for enum AVSampleFormat for audio.
+     *
+     * Note that a decoder can have considerable freedom in how exactly it
+     * decodes the data, so the format reported here might be different from the
+     * one returned by a decoder.
+     */
+    int format;
 } AVCodecParserContext;
 
 typedef struct AVCodecParser {
diff --git a/libavcodec/avfft.c b/libavcodec/avfft.c
index 2200f37..675d2b9 100644
--- a/libavcodec/avfft.c
+++ b/libavcodec/avfft.c
@@ -142,4 +142,38 @@
     }
 }
 
+#ifdef TEST
+int main(int argc, char **argv)
+{
+    int i;
+#define LEN 1024
+    FFTSample *ref  = av_malloc_array(LEN, sizeof(*ref));
+    FFTSample *data = av_malloc_array(LEN, sizeof(*data));
+    RDFTContext *rdft_context  = av_rdft_init(10, DFT_R2C);
+    RDFTContext *irdft_context = av_rdft_init(10, IDFT_C2R);
+
+    if (!ref || !data || !rdft_context || !irdft_context)
+        return 2;
+    for (i=0; i<LEN; i++) {
+        ref[i] = data[i] = i*456 + 123 + i*i;
+    }
+    av_rdft_calc(rdft_context, data);
+    av_rdft_calc(irdft_context, data);
+
+    for (i=0; i<LEN; i++) {
+        if (fabs(ref[i] - data[i]/LEN*2) > 1) {
+            fprintf(stderr, "Failed at %d (%f %f)\n", i, ref[i], data[i]/LEN*2);
+            return 1;
+        }
+    }
+
+    av_rdft_end(rdft_context);
+    av_rdft_end(irdft_context);
+    av_free(data);
+    av_free(ref);
+
+    return 0;
+}
+#endif
+
 #endif /* CONFIG_DCT */
diff --git a/libavcodec/avpacket.c b/libavcodec/avpacket.c
index 1867476..22a2d5d 100644
--- a/libavcodec/avpacket.c
+++ b/libavcodec/avpacket.c
@@ -548,8 +548,10 @@
         memcpy(dst->buf->data, src->data, src->size);
     } else {
         dst->buf = av_buffer_ref(src->buf);
-        if (!dst->buf)
+        if (!dst->buf) {
+            ret = AVERROR(ENOMEM);
             goto fail;
+        }
     }
 
     dst->size = src->size;
diff --git a/libavcodec/avs.c b/libavcodec/avs.c
index 976d325..8205689 100644
--- a/libavcodec/avs.c
+++ b/libavcodec/avs.c
@@ -23,8 +23,7 @@
 #include "get_bits.h"
 #include "internal.h"
 
-
-typedef struct {
+typedef struct AvsContext {
     AVFrame *frame;
 } AvsContext;
 
diff --git a/libavcodec/avuienc.c b/libavcodec/avuienc.c
index 4b1b408..b91f782 100644
--- a/libavcodec/avuienc.c
+++ b/libavcodec/avuienc.c
@@ -99,7 +99,7 @@
 
 static av_cold int avui_encode_close(AVCodecContext *avctx)
 {
-    av_freep(&avctx->coded_frame);
+    av_frame_free(&avctx->coded_frame);
 
     return 0;
 }
diff --git a/libavcodec/binkaudio.c b/libavcodec/binkaudio.c
index 064ee7e..f30ea12 100644
--- a/libavcodec/binkaudio.c
+++ b/libavcodec/binkaudio.c
@@ -34,7 +34,6 @@
 #include "get_bits.h"
 #include "dct.h"
 #include "rdft.h"
-#include "fmtconvert.h"
 #include "internal.h"
 #include "wma_freqs.h"
 #include "libavutil/intfloat.h"
@@ -44,7 +43,7 @@
 #define MAX_CHANNELS 2
 #define BINK_BLOCK_MAX_SIZE (MAX_CHANNELS << 11)
 
-typedef struct {
+typedef struct BinkAudioContext {
     GetBitContext gb;
     int version_b;          ///< Bink version 'b'
     int first;
diff --git a/libavcodec/bitstream.c b/libavcodec/bitstream.c
index d041643..6e550ff 100644
--- a/libavcodec/bitstream.c
+++ b/libavcodec/bitstream.c
@@ -130,7 +130,7 @@
            (uint32_t)ff_reverse[ x >> 24];
 }
 
-typedef struct {
+typedef struct VLCcode {
     uint8_t bits;
     uint16_t symbol;
     /** codeword, with the first bit-to-be-read in the msb
diff --git a/libavcodec/bmvvideo.c b/libavcodec/bmvvideo.c
index 5143b2a..76a3d6f 100644
--- a/libavcodec/bmvvideo.c
+++ b/libavcodec/bmvvideo.c
@@ -51,7 +51,7 @@
     const uint8_t *stream;
 } BMVDecContext;
 
-#define NEXT_BYTE(v) v = forward ? v + 1 : v - 1;
+#define NEXT_BYTE(v) (v) = forward ? (v) + 1 : (v) - 1;
 
 static int decode_bmv_frame(const uint8_t *source, int src_len, uint8_t *frame, int frame_off)
 {
diff --git a/libavcodec/c93.c b/libavcodec/c93.c
index ad3fa3b..eff8887 100644
--- a/libavcodec/c93.c
+++ b/libavcodec/c93.c
@@ -23,7 +23,7 @@
 #include "bytestream.h"
 #include "internal.h"
 
-typedef struct {
+typedef struct C93DecoderContext {
     AVFrame *pictures[2];
     int currentpic;
 } C93DecoderContext;
diff --git a/libavcodec/cavs.c b/libavcodec/cavs.c
index 8307390..10a25d8 100644
--- a/libavcodec/cavs.c
+++ b/libavcodec/cavs.c
@@ -91,9 +91,9 @@
 }
 
 #define SET_PARAMS                                                \
-    alpha = alpha_tab[av_clip(qp_avg + h->alpha_offset, 0, 63)];  \
-    beta  =  beta_tab[av_clip(qp_avg + h->beta_offset,  0, 63)];  \
-    tc    =    tc_tab[av_clip(qp_avg + h->alpha_offset, 0, 63)];
+    alpha = alpha_tab[av_clip_uintp2(qp_avg + h->alpha_offset, 6)];  \
+    beta  =  beta_tab[av_clip_uintp2(qp_avg + h->beta_offset,  6)];  \
+    tc    =    tc_tab[av_clip_uintp2(qp_avg + h->alpha_offset, 6)];
 
 /**
  * in-loop deblocking filter for a single macroblock
diff --git a/libavcodec/ccaption_dec.c b/libavcodec/ccaption_dec.c
index 1666797..06981cc 100644
--- a/libavcodec/ccaption_dec.c
+++ b/libavcodec/ccaption_dec.c
@@ -137,6 +137,8 @@
 struct Screen {
     /* +1 is used to compensate null character of string */
     uint8_t characters[SCREEN_ROWS][SCREEN_COLUMNS+1];
+    uint8_t colors[SCREEN_ROWS][SCREEN_COLUMNS+1];
+    uint8_t fonts[SCREEN_ROWS][SCREEN_COLUMNS+1];
     /*
      * Bitmask of used rows; if a bit is not set, the
      * corresponding row is not used.
@@ -149,7 +151,6 @@
 
 typedef struct CCaptionSubContext {
     AVClass *class;
-    int row_cnt;
     struct Screen screen[2];
     int active_screen;
     uint8_t cursor_row;
@@ -177,15 +178,19 @@
 
     av_bprint_init(&ctx->buffer, 0, AV_BPRINT_SIZE_UNLIMITED);
     /* taking by default roll up to 2 */
+    ctx->mode = CCMODE_ROLLUP_2;
     ctx->rollup = 2;
     ret = ff_ass_subtitle_header_default(avctx);
+    if(ret < 0) {
+        goto fail;
+    }
     /* allocate pkt buffer */
     ctx->pktbuf = av_buffer_alloc(128);
     if( !ctx->pktbuf) {
         ret = AVERROR(ENOMEM);
     }
 
-
+fail:
     return ret;
 }
 
@@ -278,6 +283,68 @@
     return NULL;
 }
 
+static void roll_up(CCaptionSubContext *ctx)
+{
+    struct Screen *screen;
+    int i, keep_lines;
+
+    if(ctx->mode == CCMODE_TEXT)
+        return;
+
+    screen = get_writing_screen(ctx);
+
+    /* +1 signify cursor_row starts from 0
+     * Can't keep lines less then row cursor pos
+     */
+    keep_lines = FFMIN(ctx->cursor_row + 1, ctx->rollup);
+
+    for( i = 0; i < ctx->cursor_row - keep_lines; i++ )
+        UNSET_FLAG(screen->row_used, i);
+
+
+    for( i = 0; i < keep_lines && screen->row_used; i++ ) {
+        const int i_row = ctx->cursor_row - keep_lines + i + 1;
+
+        memcpy( screen->characters[i_row], screen->characters[i_row+1], SCREEN_COLUMNS );
+        memcpy( screen->colors[i_row], screen->colors[i_row+1], SCREEN_COLUMNS);
+        memcpy( screen->fonts[i_row], screen->fonts[i_row+1], SCREEN_COLUMNS);
+        if(CHECK_FLAG(screen->row_used, i_row + 1))
+            SET_FLAG(screen->row_used, i_row);
+
+    }
+    UNSET_FLAG(screen->row_used, ctx->cursor_row);
+
+}
+
+static int reap_screen(CCaptionSubContext *ctx, int64_t pts)
+{
+    int i;
+    int ret = 0;
+    struct Screen *screen = ctx->screen + ctx->active_screen;
+    ctx->start_time = ctx->startv_time;
+
+    for( i = 0; screen->row_used && i < SCREEN_ROWS; i++)
+    {
+        if(CHECK_FLAG(screen->row_used,i)) {
+            char *str = screen->characters[i];
+            /* skip space */
+            while (*str == ' ')
+                str++;
+
+            av_bprintf(&ctx->buffer, "%s\\N", str);
+            ret = av_bprint_is_complete(&ctx->buffer);
+            if( ret == 0) {
+                ret = AVERROR(ENOMEM);
+                break;
+            }
+        }
+
+    }
+    ctx->startv_time = pts;
+    ctx->end_time = pts;
+    return ret;
+}
+
 static void handle_textattr( CCaptionSubContext *ctx, uint8_t hi, uint8_t lo )
 {
     int i = lo - 0x20;
@@ -307,8 +374,10 @@
     char *row;
     int indent,i,ret;
 
-    if( row_map[index] <= 0 )
+    if( row_map[index] <= 0 ) {
+        av_log(ctx, AV_LOG_DEBUG,"Invalid pac index encountered\n");
         return;
+    }
 
     lo &= 0x1f;
 
@@ -331,32 +400,12 @@
  */
 static int handle_edm(CCaptionSubContext *ctx,int64_t pts)
 {
-    int i;
     int ret = 0;
     struct Screen *screen = ctx->screen + ctx->active_screen;
 
-    ctx->start_time = ctx->startv_time;
-    for( i = 0; screen->row_used && i < SCREEN_ROWS; i++)
-    {
-        if(CHECK_FLAG(screen->row_used,i)) {
-            char *str = screen->characters[i];
-            /* skip space */
-            while (*str == ' ')
-                str++;
-            av_bprint_append_data(&ctx->buffer, str, strlen(str));
-            av_bprint_append_data(&ctx->buffer, "\\N",2);
-            UNSET_FLAG(screen->row_used, i);
-            ret = av_bprint_is_complete(&ctx->buffer);
-            if( ret == 0) {
-                ret = AVERROR(ENOMEM);
-                break;
-            }
-        }
-
-    }
-    ctx->startv_time = pts;
+    reap_screen(ctx, pts);
+    screen->row_used = 0;
     ctx->screen_changed = 1;
-    ctx->end_time = pts;
     return ret;
 }
 
@@ -424,10 +473,13 @@
         handle_delete_end_of_row(ctx, hi, lo);
     } else if ( COR3(hi, 0x14, 0x15, 0x1C) && lo == 0x25 ) {
         ctx->rollup = 2;
+        ctx->mode = CCMODE_ROLLUP_2;
     } else if ( COR3(hi, 0x14, 0x15, 0x1C) && lo == 0x26 ) {
         ctx->rollup = 3;
+        ctx->mode = CCMODE_ROLLUP_3;
     } else if ( COR3(hi, 0x14, 0x15, 0x1C) && lo == 0x27 ) {
         ctx->rollup = 4;
+        ctx->mode = CCMODE_ROLLUP_4;
     } else if ( COR3(hi, 0x14, 0x15, 0x1C) && lo == 0x29 ) {
     /* resume direct captioning */
         ctx->mode = CCMODE_PAINTON;
@@ -439,21 +491,21 @@
         ret = handle_edm(ctx, pts);
     } else if ( COR3(hi, 0x14, 0x15, 0x1C) && lo == 0x2D ) {
     /* carriage return */
-        ctx->row_cnt++;
-        if(ctx->row_cnt >= ctx->rollup) {
-            ctx->row_cnt = 0;
-            ret = handle_edm(ctx, pts);
-            ctx->active_screen = !ctx->active_screen;
-        }
+        av_dlog(ctx, "carriage return\n");
+        reap_screen(ctx, pts);
+        roll_up(ctx);
+        ctx->screen_changed = 1;
         ctx->cursor_column = 0;
     } else if ( COR3(hi, 0x14, 0x15, 0x1C) && lo == 0x2F ) {
     /* end of caption */
+        av_dlog(ctx, "handle_eoc\n");
         ret = handle_eoc(ctx, pts);
     } else if (hi>=0x20) {
     /* Standard characters (always in pairs) */
         handle_char(ctx, hi, lo, pts);
     } else {
     /* Ignoring all other non data code */
+        av_dlog(ctx, "Unknown command 0x%hhx 0x%hhx\n", hi, lo);
     }
 
     /* set prev command */
diff --git a/libavcodec/cdxl.c b/libavcodec/cdxl.c
index 7fe4a70..1117cab 100644
--- a/libavcodec/cdxl.c
+++ b/libavcodec/cdxl.c
@@ -37,7 +37,7 @@
 #define BIT_LINE     0x80
 #define BYTE_LINE    0xC0
 
-typedef struct {
+typedef struct CDXLVideoContext {
     AVCodecContext *avctx;
     int            bpp;
     int            format;
@@ -78,7 +78,8 @@
     GetBitContext gb;
     int x, y, plane;
 
-    init_get_bits(&gb, c->video, c->video_size * 8);
+    if (init_get_bits8(&gb, c->video, c->video_size) < 0)
+        return;
     for (plane = 0; plane < c->bpp; plane++) {
         for (y = 0; y < c->avctx->height; y++) {
             for (x = 0; x < c->avctx->width; x++)
@@ -93,7 +94,8 @@
     GetBitContext  gb;
     int x, y, plane;
 
-    init_get_bits(&gb, c->video, c->video_size * 8);
+    if (init_get_bits8(&gb, c->video, c->video_size) < 0)
+        return;
     for (y = 0; y < c->avctx->height; y++) {
         for (plane = 0; plane < c->bpp; plane++) {
             for (x = 0; x < c->avctx->width; x++)
diff --git a/libavcodec/cinepak.c b/libavcodec/cinepak.c
index f651c48..1a6d4f5 100644
--- a/libavcodec/cinepak.c
+++ b/libavcodec/cinepak.c
@@ -47,7 +47,7 @@
 
 #define MAX_STRIPS      32
 
-typedef struct {
+typedef struct cvid_strip {
     uint16_t          id;
     uint16_t          x1, y1;
     uint16_t          x2, y2;
diff --git a/libavcodec/cllc.c b/libavcodec/cllc.c
index 9c710bb..829cb52 100644
--- a/libavcodec/cllc.c
+++ b/libavcodec/cllc.c
@@ -394,7 +394,8 @@
     ctx->bdsp.bswap16_buf((uint16_t *) ctx->swapped_buf, (uint16_t *) src,
                           data_size / 2);
 
-    init_get_bits(&gb, ctx->swapped_buf, data_size * 8);
+    if ((ret = init_get_bits8(&gb, ctx->swapped_buf, data_size)) < 0)
+        return ret;
 
     /*
      * Read in coding type. The types are as follows:
diff --git a/libavcodec/cngenc.c b/libavcodec/cngenc.c
index bf5f7bf..58918aa 100644
--- a/libavcodec/cngenc.c
+++ b/libavcodec/cngenc.c
@@ -87,7 +87,7 @@
     energy /= frame->nb_samples;
     if (energy > 0) {
         double dbov = 10 * log10(energy / 1081109975);
-        qdbov = av_clip(-floor(dbov), 0, 127);
+        qdbov = av_clip_uintp2(-floor(dbov), 7);
     } else {
         qdbov = 127;
     }
diff --git a/libavcodec/codec_desc.c b/libavcodec/codec_desc.c
index 0af66f4..b51d0e9 100644
--- a/libavcodec/codec_desc.c
+++ b/libavcodec/codec_desc.c
@@ -1238,6 +1238,13 @@
         .long_name = NULL_IF_CONFIG_SMALL("SGI RLE 8-bit"),
         .props     = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
     },
+    {
+        .id        = AV_CODEC_ID_HQX,
+        .type      = AVMEDIA_TYPE_VIDEO,
+        .name      = "hqx",
+        .long_name = NULL_IF_CONFIG_SMALL("Canopus HQX"),
+        .props     = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSY,
+    },
 
     /* image codecs */
     {
@@ -1388,6 +1395,13 @@
         .mime_types= MT("image/x-targa", "image/x-tga"),
     },
     {
+        .id        = AV_CODEC_ID_TDSC,
+        .type      = AVMEDIA_TYPE_VIDEO,
+        .name      = "tdsc",
+        .long_name = NULL_IF_CONFIG_SMALL("TDSC"),
+        .props     = AV_CODEC_PROP_LOSSY,
+    },
+    {
         .id        = AV_CODEC_ID_TIFF,
         .type      = AVMEDIA_TYPE_VIDEO,
         .name      = "tiff",
@@ -2366,6 +2380,13 @@
         .props     = AV_CODEC_PROP_LOSSY,
     },
     {
+        .id        = AV_CODEC_ID_DSS_SP,
+        .type      = AVMEDIA_TYPE_AUDIO,
+        .name      = "dss_sp",
+        .long_name = NULL_IF_CONFIG_SMALL("Digital Speech Standard - Standard Play mode (DSS SP)"),
+        .props     = AV_CODEC_PROP_LOSSY,
+    },
+    {
         .id        = AV_CODEC_ID_G729,
         .type      = AVMEDIA_TYPE_AUDIO,
         .name      = "g729",
@@ -2807,6 +2828,7 @@
                      AV_CODEC_PROP_LOSSLESS,
     },
 
+#if FF_API_VIMA_DECODER
     {
         .id        = AV_CODEC_ID_VIMA,
         .type      = AVMEDIA_TYPE_AUDIO,
@@ -2814,6 +2836,7 @@
         .long_name = NULL_IF_CONFIG_SMALL("LucasArts VIMA audio (deprecated id)"),
         .props     = AV_CODEC_PROP_LOSSY,
     },
+#endif
     {
         .id        = AV_CODEC_ID_ADPCM_VIMA_DEPRECATED,
         .type      = AVMEDIA_TYPE_AUDIO,
diff --git a/libavcodec/cook.c b/libavcodec/cook.c
index cfbce2a..02ac0e0 100644
--- a/libavcodec/cook.c
+++ b/libavcodec/cook.c
@@ -65,12 +65,12 @@
 #define SUBBAND_SIZE    20
 #define MAX_SUBPACKETS   5
 
-typedef struct {
+typedef struct cook_gains {
     int *now;
     int *previous;
 } cook_gains;
 
-typedef struct {
+typedef struct COOKSubpacket {
     int                 ch_idx;
     int                 size;
     int                 num_channels;
@@ -418,7 +418,7 @@
         num_bits = 0;
         index    = 0;
         for (j = p->total_subbands; j > 0; j--) {
-            exp_idx = av_clip((i - quant_index_table[index] + bias) / 2, 0, 7);
+            exp_idx = av_clip_uintp2((i - quant_index_table[index] + bias) / 2, 3);
             index++;
             num_bits += expbits_tab[exp_idx];
         }
@@ -429,7 +429,7 @@
     /* Calculate total number of bits. */
     num_bits = 0;
     for (i = 0; i < p->total_subbands; i++) {
-        exp_idx = av_clip((bias - quant_index_table[i]) / 2, 0, 7);
+        exp_idx = av_clip_uintp2((bias - quant_index_table[i]) / 2, 3);
         num_bits += expbits_tab[exp_idx];
         exp_index1[i] = exp_idx;
         exp_index2[i] = exp_idx;
diff --git a/libavcodec/cscd.c b/libavcodec/cscd.c
index e875dd7..07f2f5e 100644
--- a/libavcodec/cscd.c
+++ b/libavcodec/cscd.c
@@ -30,7 +30,7 @@
 #endif
 #include "libavutil/lzo.h"
 
-typedef struct {
+typedef struct CamStudioContext {
     AVFrame *pic;
     int linelen, height, bpp;
     unsigned int decomp_size;
diff --git a/libavcodec/dca.c b/libavcodec/dca.c
index 22be88f..8dd0430 100644
--- a/libavcodec/dca.c
+++ b/libavcodec/dca.c
@@ -28,6 +28,7 @@
 #include "libavutil/error.h"
 
 #include "dca.h"
+#include "dca_syncwords.h"
 #include "put_bits.h"
 
 const uint32_t avpriv_dca_sample_rates[16] = {
@@ -49,18 +50,18 @@
 
     mrk = AV_RB32(src);
     switch (mrk) {
-    case DCA_MARKER_RAW_BE:
+    case DCA_SYNCWORD_CORE_BE:
         memcpy(dst, src, src_size);
         return src_size;
-    case DCA_MARKER_RAW_LE:
+    case DCA_SYNCWORD_CORE_LE:
         for (i = 0; i < (src_size + 1) >> 1; i++)
             *sdst++ = av_bswap16(*ssrc++);
         return src_size;
-    case DCA_MARKER_14B_BE:
-    case DCA_MARKER_14B_LE:
+    case DCA_SYNCWORD_CORE_14B_BE:
+    case DCA_SYNCWORD_CORE_14B_LE:
         init_put_bits(&pb, dst, max_size);
         for (i = 0; i < (src_size + 1) >> 1; i++, src += 2) {
-            tmp = ((mrk == DCA_MARKER_14B_BE) ? AV_RB16(src) : AV_RL16(src)) & 0x3FFF;
+            tmp = ((mrk == DCA_SYNCWORD_CORE_14B_BE) ? AV_RB16(src) : AV_RL16(src)) & 0x3FFF;
             put_bits(&pb, 14, tmp);
         }
         flush_put_bits(&pb);
diff --git a/libavcodec/dca.h b/libavcodec/dca.h
index 70dade5..897ebf4 100644
--- a/libavcodec/dca.h
+++ b/libavcodec/dca.h
@@ -26,16 +26,265 @@
 #define AVCODEC_DCA_H
 
 #include <stdint.h>
+
+#include "libavutil/float_dsp.h"
 #include "libavutil/internal.h"
 
-/** DCA syncwords, also used for bitstream type detection */
-#define DCA_MARKER_RAW_BE 0x7FFE8001
-#define DCA_MARKER_RAW_LE 0xFE7F0180
-#define DCA_MARKER_14B_BE 0x1FFFE800
-#define DCA_MARKER_14B_LE 0xFF1F00E8
+#include "avcodec.h"
+#include "dcadsp.h"
+#include "fmtconvert.h"
+#include "get_bits.h"
 
-/** DCA-HD specific block starts with this marker. */
-#define DCA_HD_MARKER     0x64582025
+#define DCA_PRIM_CHANNELS_MAX  (7)
+#define DCA_ABITS_MAX         (32)      /* Should be 28 */
+#define DCA_SUBSUBFRAMES_MAX   (4)
+#define DCA_SUBFRAMES_MAX     (16)
+#define DCA_BLOCKS_MAX        (16)
+#define DCA_LFE_MAX            (3)
+#define DCA_CHSETS_MAX         (4)
+#define DCA_CHSET_CHANS_MAX    (8)
+
+#define DCA_PRIM_CHANNELS_MAX  (7)
+#define DCA_ABITS_MAX         (32)      /* Should be 28 */
+#define DCA_SUBSUBFRAMES_MAX   (4)
+#define DCA_SUBFRAMES_MAX     (16)
+#define DCA_BLOCKS_MAX        (16)
+#define DCA_LFE_MAX            (3)
+#define DCA_XLL_FBANDS_MAX     (4)
+#define DCA_XLL_SEGMENTS_MAX  (16)
+#define DCA_XLL_CHSETS_MAX    (16)
+#define DCA_XLL_CHANNELS_MAX  (16)
+#define DCA_XLL_AORDER_MAX    (15)
+
+/* Arbitrary limit; not sure what the maximum really is, but much larger. */
+#define DCA_XLL_DMIX_NCOEFFS_MAX (18)
+
+#define DCA_MAX_FRAME_SIZE       16384
+#define DCA_MAX_EXSS_HEADER_SIZE  4096
+
+#define DCA_BUFFER_PADDING_SIZE   1024
+
+enum DCAExtensionMask {
+    DCA_EXT_CORE       = 0x001, ///< core in core substream
+    DCA_EXT_XXCH       = 0x002, ///< XXCh channels extension in core substream
+    DCA_EXT_X96        = 0x004, ///< 96/24 extension in core substream
+    DCA_EXT_XCH        = 0x008, ///< XCh channel extension in core substream
+    DCA_EXT_EXSS_CORE  = 0x010, ///< core in ExSS (extension substream)
+    DCA_EXT_EXSS_XBR   = 0x020, ///< extended bitrate extension in ExSS
+    DCA_EXT_EXSS_XXCH  = 0x040, ///< XXCh channels extension in ExSS
+    DCA_EXT_EXSS_X96   = 0x080, ///< 96/24 extension in ExSS
+    DCA_EXT_EXSS_LBR   = 0x100, ///< low bitrate component in ExSS
+    DCA_EXT_EXSS_XLL   = 0x200, ///< lossless extension in ExSS
+};
+
+typedef struct XllChSetSubHeader {
+    int channels;               ///< number of channels in channel set, at most 16
+    int residual_encode;        ///< residual channel encoding
+    int bit_resolution;         ///< input sample bit-width
+    int bit_width;              ///< original input sample bit-width
+    int sampling_frequency;     ///< sampling frequency
+    int samp_freq_interp;       ///< sampling frequency interpolation multiplier
+    int replacement_set;        ///< replacement channel set group
+    int active_replace_set;     ///< current channel set is active channel set
+    int primary_ch_set;
+    int downmix_coeff_code_embedded;
+    int downmix_embedded;
+    int downmix_type;
+    int hier_chset;             ///< hierarchical channel set
+    int downmix_ncoeffs;
+    int downmix_coeffs[DCA_XLL_DMIX_NCOEFFS_MAX];
+    int ch_mask_enabled;
+    int ch_mask;
+    int mapping_coeffs_present;
+    int num_freq_bands;
+
+    /* m_nOrigChanOrder */
+    uint8_t orig_chan_order[DCA_XLL_FBANDS_MAX][DCA_XLL_CHANNELS_MAX];
+    uint8_t orig_chan_order_inv[DCA_XLL_FBANDS_MAX][DCA_XLL_CHANNELS_MAX];
+    /* Coefficients for channel pairs (at most 8), m_anPWChPairsCoeffs */
+    int8_t pw_ch_pairs_coeffs[DCA_XLL_FBANDS_MAX][DCA_XLL_CHANNELS_MAX/2];
+    /* m_nCurrHighestLPCOrder */
+    uint8_t adapt_order_max[DCA_XLL_FBANDS_MAX];
+    /* m_pnAdaptPredOrder */
+    uint8_t adapt_order[DCA_XLL_FBANDS_MAX][DCA_XLL_CHANNELS_MAX];
+    /* m_pnFixedPredOrder */
+    uint8_t fixed_order[DCA_XLL_FBANDS_MAX][DCA_XLL_CHANNELS_MAX];
+    /* m_pnLPCReflCoeffsQInd, unsigned version */
+    uint8_t lpc_refl_coeffs_q_ind[DCA_XLL_FBANDS_MAX]
+                                 [DCA_XLL_CHANNELS_MAX][DCA_XLL_AORDER_MAX];
+
+    int lsb_fsize[DCA_XLL_FBANDS_MAX];
+    int8_t scalable_lsbs[DCA_XLL_FBANDS_MAX][DCA_XLL_CHANNELS_MAX];
+    int8_t bit_width_adj_per_ch[DCA_XLL_FBANDS_MAX][DCA_XLL_CHANNELS_MAX];
+} XllChSetSubHeader;
+
+typedef struct XllNavi {
+    GetBitContext gb;  // Context for parsing the data segments
+    unsigned band_size[DCA_XLL_FBANDS_MAX];
+    unsigned segment_size[DCA_XLL_FBANDS_MAX][DCA_XLL_SEGMENTS_MAX];
+    unsigned chset_size[DCA_XLL_FBANDS_MAX][DCA_XLL_SEGMENTS_MAX][DCA_XLL_CHSETS_MAX];
+} XllNavi;
+
+typedef struct QMF64_table {
+    float dct4_coeff[32][32];
+    float dct2_coeff[32][32];
+    float rcos[32];
+    float rsin[32];
+} QMF64_table;
+
+typedef struct DCAContext {
+    const AVClass *class;       ///< class for AVOptions
+    AVCodecContext *avctx;
+    /* Frame header */
+    int frame_type;             ///< type of the current frame
+    int samples_deficit;        ///< deficit sample count
+    int crc_present;            ///< crc is present in the bitstream
+    int sample_blocks;          ///< number of PCM sample blocks
+    int frame_size;             ///< primary frame byte size
+    int amode;                  ///< audio channels arrangement
+    int sample_rate;            ///< audio sampling rate
+    int bit_rate;               ///< transmission bit rate
+    int bit_rate_index;         ///< transmission bit rate index
+
+    int dynrange;               ///< embedded dynamic range flag
+    int timestamp;              ///< embedded time stamp flag
+    int aux_data;               ///< auxiliary data flag
+    int hdcd;                   ///< source material is mastered in HDCD
+    int ext_descr;              ///< extension audio descriptor flag
+    int ext_coding;             ///< extended coding flag
+    int aspf;                   ///< audio sync word insertion flag
+    int lfe;                    ///< low frequency effects flag
+    int predictor_history;      ///< predictor history flag
+    int header_crc;             ///< header crc check bytes
+    int multirate_inter;        ///< multirate interpolator switch
+    int version;                ///< encoder software revision
+    int copy_history;           ///< copy history
+    int source_pcm_res;         ///< source pcm resolution
+    int front_sum;              ///< front sum/difference flag
+    int surround_sum;           ///< surround sum/difference flag
+    int dialog_norm;            ///< dialog normalisation parameter
+
+    /* Primary audio coding header */
+    int subframes;              ///< number of subframes
+    int total_channels;         ///< number of channels including extensions
+    int prim_channels;          ///< number of primary audio channels
+    int subband_activity[DCA_PRIM_CHANNELS_MAX];    ///< subband activity count
+    int vq_start_subband[DCA_PRIM_CHANNELS_MAX];    ///< high frequency vq start subband
+    int joint_intensity[DCA_PRIM_CHANNELS_MAX];     ///< joint intensity coding index
+    int transient_huffman[DCA_PRIM_CHANNELS_MAX];   ///< transient mode code book
+    int scalefactor_huffman[DCA_PRIM_CHANNELS_MAX]; ///< scale factor code book
+    int bitalloc_huffman[DCA_PRIM_CHANNELS_MAX];    ///< bit allocation quantizer select
+    int quant_index_huffman[DCA_PRIM_CHANNELS_MAX][DCA_ABITS_MAX]; ///< quantization index codebook select
+    float scalefactor_adj[DCA_PRIM_CHANNELS_MAX][DCA_ABITS_MAX];   ///< scale factor adjustment
+
+    /* Primary audio coding side information */
+    int subsubframes[DCA_SUBFRAMES_MAX];                         ///< number of subsubframes
+    int partial_samples[DCA_SUBFRAMES_MAX];                      ///< partial subsubframe samples count
+    int prediction_mode[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];    ///< prediction mode (ADPCM used or not)
+    int prediction_vq[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];      ///< prediction VQ coefs
+    int bitalloc[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];           ///< bit allocation index
+    int transition_mode[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];    ///< transition mode (transients)
+    int32_t scale_factor[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][2];///< scale factors (2 if transient)
+    int joint_huff[DCA_PRIM_CHANNELS_MAX];                       ///< joint subband scale factors codebook
+    int joint_scale_factor[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS]; ///< joint subband scale factors
+    float downmix_coef[DCA_PRIM_CHANNELS_MAX + 1][2];            ///< stereo downmix coefficients
+    int dynrange_coef;                                           ///< dynamic range coefficient
+
+    /* Core substream's embedded downmix coefficients (cf. ETSI TS 102 114 V1.4.1)
+     * Input:  primary audio channels (incl. LFE if present)
+     * Output: downmix audio channels (up to 4, no LFE) */
+    uint8_t  core_downmix;                                       ///< embedded downmix coefficients available
+    uint8_t  core_downmix_amode;                                 ///< audio channel arrangement of embedded downmix
+    uint16_t core_downmix_codes[DCA_PRIM_CHANNELS_MAX + 1][4];   ///< embedded downmix coefficients (9-bit codes)
+
+    int32_t  high_freq_vq[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];  ///< VQ encoded high frequency subbands
+
+    float lfe_data[2 * DCA_LFE_MAX * (DCA_BLOCKS_MAX + 4)];      ///< Low frequency effect data
+    int lfe_scale_factor;
+
+    /* Subband samples history (for ADPCM) */
+    DECLARE_ALIGNED(16, float, subband_samples_hist)[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][4];
+    /* Half size is sufficient for core decoding, but for 96 kHz data
+     * we need QMF with 64 subbands and 1024 samples. */
+    DECLARE_ALIGNED(32, float, subband_fir_hist)[DCA_PRIM_CHANNELS_MAX][1024];
+    DECLARE_ALIGNED(32, float, subband_fir_noidea)[DCA_PRIM_CHANNELS_MAX][64];
+    int hist_index[DCA_PRIM_CHANNELS_MAX];
+    DECLARE_ALIGNED(32, float, raXin)[32];
+
+    int output;                 ///< type of output
+
+    DECLARE_ALIGNED(32, float, subband_samples)[DCA_BLOCKS_MAX][DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][8];
+    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
+
+    const int8_t *channel_order_tab;  ///< channel reordering table, lfe and non lfe
+    GetBitContext gb;
+    /* Current position in DCA frame */
+    int current_subframe;
+    int current_subsubframe;
+
+    int core_ext_mask;          ///< present extensions in the core substream
+    int exss_ext_mask;          ///< Non-core extensions
+
+    /* XCh extension information */
+    int xch_present;            ///< XCh extension present and valid
+    int xch_base_channel;       ///< index of first (only) channel containing XCH data
+    int xch_disable;            ///< whether the XCh extension should be decoded or not
+
+    /* XXCH extension information */
+    int xxch_chset;
+    int xxch_nbits_spk_mask;
+    uint32_t xxch_core_spkmask;
+    uint32_t xxch_spk_masks[4]; /* speaker masks, last element is core mask */
+    int xxch_chset_nch[4];
+    float xxch_dmix_sf[DCA_CHSETS_MAX];
+
+    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 */
+
+    int8_t xxch_order_tab[32];
+    int8_t lfe_index;
+
+    /* XLL extension information */
+    int xll_disable;
+    int xll_nch_sets;           ///< number of channel sets per frame
+    int xll_channels;           ///< total number of channels (in all channel sets)
+    int xll_residual_channels;  ///< number of residual channels
+    int xll_segments;           ///< number of segments per frame
+    int xll_log_smpl_in_seg;    ///< supposedly this is "nBits4SamplLoci"
+    int xll_smpl_in_seg;        ///< samples in segment per one frequency band for the first channel set
+    int xll_bits4seg_size;      ///< number of bits used to read segment size
+    int xll_banddata_crc;       ///< presence of CRC16 within each frequency band
+    int xll_scalable_lsb;
+    int xll_bits4ch_mask;       ///< channel position mask
+    int xll_fixed_lsb_width;
+    XllChSetSubHeader xll_chsets[DCA_XLL_CHSETS_MAX];
+    XllNavi xll_navi;
+    int *xll_sample_buf;
+    unsigned int xll_sample_buf_size;
+
+    /* ExSS header parser */
+    int static_fields;          ///< static fields present
+    int mix_metadata;           ///< mixing metadata present
+    int num_mix_configs;        ///< number of mix out configurations
+    int mix_config_num_ch[4];   ///< number of channels in each mix out configuration
+
+    int profile;
+    int one2one_map_chtospkr;
+
+    int debug_flag;             ///< used for suppressing repeated error messages output
+    AVFloatDSPContext *fdsp;
+    FFTContext imdct;
+    SynthFilterContext synth;
+    DCADSPContext dcadsp;
+    QMF64_table *qmf64_table;
+    FmtConvertContext fmt_conv;
+} DCAContext;
 
 extern av_export const uint32_t avpriv_dca_sample_rates[16];
 
@@ -45,4 +294,13 @@
 int avpriv_dca_convert_bitstream(const uint8_t *src, int src_size, uint8_t *dst,
                              int max_size);
 
+int ff_dca_xbr_parse_frame(DCAContext *s);
+int ff_dca_xxch_decode_frame(DCAContext *s);
+
+void ff_dca_exss_parse_header(DCAContext *s);
+
+int ff_dca_xll_decode_header(DCAContext *s);
+int ff_dca_xll_decode_navi(DCAContext *s, int asset_end);
+int ff_dca_xll_decode_audio(DCAContext *s, AVFrame *frame);
+
 #endif /* AVCODEC_DCA_H */
diff --git a/libavcodec/dca_exss.c b/libavcodec/dca_exss.c
new file mode 100644
index 0000000..ed01490
--- /dev/null
+++ b/libavcodec/dca_exss.c
@@ -0,0 +1,373 @@
+/*
+ * DCA ExSS extension
+ *
+ * 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 "libavutil/log.h"
+
+#include "dca.h"
+#include "dca_syncwords.h"
+#include "get_bits.h"
+
+/* extensions that reside in core substream */
+#define DCA_CORE_EXTS (DCA_EXT_XCH | DCA_EXT_XXCH | DCA_EXT_X96)
+
+/* these are unconfirmed but should be mostly correct */
+enum DCAExSSSpeakerMask {
+    DCA_EXSS_FRONT_CENTER          = 0x0001,
+    DCA_EXSS_FRONT_LEFT_RIGHT      = 0x0002,
+    DCA_EXSS_SIDE_REAR_LEFT_RIGHT  = 0x0004,
+    DCA_EXSS_LFE                   = 0x0008,
+    DCA_EXSS_REAR_CENTER           = 0x0010,
+    DCA_EXSS_FRONT_HIGH_LEFT_RIGHT = 0x0020,
+    DCA_EXSS_REAR_LEFT_RIGHT       = 0x0040,
+    DCA_EXSS_FRONT_HIGH_CENTER     = 0x0080,
+    DCA_EXSS_OVERHEAD              = 0x0100,
+    DCA_EXSS_CENTER_LEFT_RIGHT     = 0x0200,
+    DCA_EXSS_WIDE_LEFT_RIGHT       = 0x0400,
+    DCA_EXSS_SIDE_LEFT_RIGHT       = 0x0800,
+    DCA_EXSS_LFE2                  = 0x1000,
+    DCA_EXSS_SIDE_HIGH_LEFT_RIGHT  = 0x2000,
+    DCA_EXSS_REAR_HIGH_CENTER      = 0x4000,
+    DCA_EXSS_REAR_HIGH_LEFT_RIGHT  = 0x8000,
+};
+
+/**
+ * Return the number of channels in an ExSS speaker mask (HD)
+ */
+static int dca_exss_mask2count(int mask)
+{
+    /* count bits that mean speaker pairs twice */
+    return av_popcount(mask) +
+           av_popcount(mask & (DCA_EXSS_CENTER_LEFT_RIGHT      |
+                               DCA_EXSS_FRONT_LEFT_RIGHT       |
+                               DCA_EXSS_FRONT_HIGH_LEFT_RIGHT  |
+                               DCA_EXSS_WIDE_LEFT_RIGHT        |
+                               DCA_EXSS_SIDE_LEFT_RIGHT        |
+                               DCA_EXSS_SIDE_HIGH_LEFT_RIGHT   |
+                               DCA_EXSS_SIDE_REAR_LEFT_RIGHT   |
+                               DCA_EXSS_REAR_LEFT_RIGHT        |
+                               DCA_EXSS_REAR_HIGH_LEFT_RIGHT));
+}
+
+/**
+ * Skip mixing coefficients of a single mix out configuration (HD)
+ */
+static void dca_exss_skip_mix_coeffs(GetBitContext *gb, int channels, int out_ch)
+{
+    int i;
+
+    for (i = 0; i < channels; i++) {
+        int mix_map_mask = get_bits(gb, out_ch);
+        int num_coeffs = av_popcount(mix_map_mask);
+        skip_bits_long(gb, num_coeffs * 6);
+    }
+}
+
+/**
+ * Parse extension substream asset header (HD)
+ */
+static int dca_exss_parse_asset_header(DCAContext *s)
+{
+    int header_pos = get_bits_count(&s->gb);
+    int header_size;
+    int channels = 0;
+    int embedded_stereo = 0;
+    int embedded_6ch    = 0;
+    int drc_code_present;
+    int extensions_mask = 0;
+    int i, j;
+
+    if (get_bits_left(&s->gb) < 16)
+        return AVERROR_INVALIDDATA;
+
+    /* We will parse just enough to get to the extensions bitmask with which
+     * we can set the profile value. */
+
+    header_size = get_bits(&s->gb, 9) + 1;
+    skip_bits(&s->gb, 3); // asset index
+
+    if (s->static_fields) {
+        if (get_bits1(&s->gb))
+            skip_bits(&s->gb, 4); // asset type descriptor
+        if (get_bits1(&s->gb))
+            skip_bits_long(&s->gb, 24); // language descriptor
+
+        if (get_bits1(&s->gb)) {
+            /* How can one fit 1024 bytes of text here if the maximum value
+             * for the asset header size field above was 512 bytes? */
+            int text_length = get_bits(&s->gb, 10) + 1;
+            if (get_bits_left(&s->gb) < text_length * 8)
+                return AVERROR_INVALIDDATA;
+            skip_bits_long(&s->gb, text_length * 8); // info text
+        }
+
+        skip_bits(&s->gb, 5); // bit resolution - 1
+        skip_bits(&s->gb, 4); // max sample rate code
+        channels = get_bits(&s->gb, 8) + 1;
+
+        s->one2one_map_chtospkr = get_bits1(&s->gb);
+        if (s->one2one_map_chtospkr) {
+            int spkr_remap_sets;
+            int spkr_mask_size = 16;
+            int num_spkrs[7];
+
+            if (channels > 2)
+                embedded_stereo = get_bits1(&s->gb);
+            if (channels > 6)
+                embedded_6ch = get_bits1(&s->gb);
+
+            if (get_bits1(&s->gb)) {
+                spkr_mask_size = (get_bits(&s->gb, 2) + 1) << 2;
+                skip_bits(&s->gb, spkr_mask_size); // spkr activity mask
+            }
+
+            spkr_remap_sets = get_bits(&s->gb, 3);
+
+            for (i = 0; i < spkr_remap_sets; i++) {
+                /* std layout mask for each remap set */
+                num_spkrs[i] = dca_exss_mask2count(get_bits(&s->gb, spkr_mask_size));
+            }
+
+            for (i = 0; i < spkr_remap_sets; i++) {
+                int num_dec_ch_remaps = get_bits(&s->gb, 5) + 1;
+                if (get_bits_left(&s->gb) < 0)
+                    return AVERROR_INVALIDDATA;
+
+                for (j = 0; j < num_spkrs[i]; j++) {
+                    int remap_dec_ch_mask = get_bits_long(&s->gb, num_dec_ch_remaps);
+                    int num_dec_ch = av_popcount(remap_dec_ch_mask);
+                    skip_bits_long(&s->gb, num_dec_ch * 5); // remap codes
+                }
+            }
+        } else {
+            skip_bits(&s->gb, 3); // representation type
+        }
+    }
+
+    drc_code_present = get_bits1(&s->gb);
+    if (drc_code_present)
+        get_bits(&s->gb, 8); // drc code
+
+    if (get_bits1(&s->gb))
+        skip_bits(&s->gb, 5); // dialog normalization code
+
+    if (drc_code_present && embedded_stereo)
+        get_bits(&s->gb, 8); // drc stereo code
+
+    if (s->mix_metadata && get_bits1(&s->gb)) {
+        skip_bits(&s->gb, 1); // external mix
+        skip_bits(&s->gb, 6); // post mix gain code
+
+        if (get_bits(&s->gb, 2) != 3) // mixer drc code
+            skip_bits(&s->gb, 3); // drc limit
+        else
+            skip_bits(&s->gb, 8); // custom drc code
+
+        if (get_bits1(&s->gb)) // channel specific scaling
+            for (i = 0; i < s->num_mix_configs; i++)
+                skip_bits_long(&s->gb, s->mix_config_num_ch[i] * 6); // scale codes
+        else
+            skip_bits_long(&s->gb, s->num_mix_configs * 6); // scale codes
+
+        for (i = 0; i < s->num_mix_configs; i++) {
+            if (get_bits_left(&s->gb) < 0)
+                return AVERROR_INVALIDDATA;
+            dca_exss_skip_mix_coeffs(&s->gb, channels, s->mix_config_num_ch[i]);
+            if (embedded_6ch)
+                dca_exss_skip_mix_coeffs(&s->gb, 6, s->mix_config_num_ch[i]);
+            if (embedded_stereo)
+                dca_exss_skip_mix_coeffs(&s->gb, 2, s->mix_config_num_ch[i]);
+        }
+    }
+
+    switch (get_bits(&s->gb, 2)) {
+    case 0:
+        extensions_mask = get_bits(&s->gb, 12);
+        break;
+    case 1:
+        extensions_mask = DCA_EXT_EXSS_XLL;
+        break;
+    case 2:
+        extensions_mask = DCA_EXT_EXSS_LBR;
+        break;
+    case 3:
+        extensions_mask = 0; /* aux coding */
+        break;
+    }
+
+    /* not parsed further, we were only interested in the extensions mask */
+
+    if (get_bits_left(&s->gb) < 0)
+        return AVERROR_INVALIDDATA;
+
+    if (get_bits_count(&s->gb) - header_pos > header_size * 8) {
+        av_log(s->avctx, AV_LOG_WARNING, "Asset header size mismatch.\n");
+        return AVERROR_INVALIDDATA;
+    }
+    skip_bits_long(&s->gb, header_pos + header_size * 8 - get_bits_count(&s->gb));
+
+    if (extensions_mask & DCA_EXT_EXSS_XLL)
+        s->profile = FF_PROFILE_DTS_HD_MA;
+    else if (extensions_mask & (DCA_EXT_EXSS_XBR | DCA_EXT_EXSS_X96 |
+                                DCA_EXT_EXSS_XXCH))
+        s->profile = FF_PROFILE_DTS_HD_HRA;
+
+    if (!(extensions_mask & DCA_EXT_CORE))
+        av_log(s->avctx, AV_LOG_WARNING, "DTS core detection mismatch.\n");
+    if ((extensions_mask & DCA_CORE_EXTS) != s->core_ext_mask)
+        av_log(s->avctx, AV_LOG_WARNING,
+               "DTS extensions detection mismatch (%d, %d)\n",
+               extensions_mask & DCA_CORE_EXTS, s->core_ext_mask);
+
+    return 0;
+}
+
+/**
+ * Parse extension substream header (HD)
+ */
+void ff_dca_exss_parse_header(DCAContext *s)
+{
+    int asset_size[8];
+    int ss_index;
+    int blownup;
+    int num_audiop = 1;
+    int num_assets = 1;
+    int active_ss_mask[8];
+    int i, j;
+    int start_pos;
+    int hdrsize;
+    uint32_t mkr;
+
+    if (get_bits_left(&s->gb) < 52)
+        return;
+
+    start_pos = get_bits_count(&s->gb) - 32;
+
+    skip_bits(&s->gb, 8); // user data
+    ss_index = get_bits(&s->gb, 2);
+
+    blownup = get_bits1(&s->gb);
+    hdrsize = get_bits(&s->gb,  8 + 4 * blownup) + 1; // header_size
+    skip_bits(&s->gb, 16 + 4 * blownup); // hd_size
+
+    s->static_fields = get_bits1(&s->gb);
+    if (s->static_fields) {
+        skip_bits(&s->gb, 2); // reference clock code
+        skip_bits(&s->gb, 3); // frame duration code
+
+        if (get_bits1(&s->gb))
+            skip_bits_long(&s->gb, 36); // timestamp
+
+        /* a single stream can contain multiple audio assets that can be
+         * combined to form multiple audio presentations */
+
+        num_audiop = get_bits(&s->gb, 3) + 1;
+        if (num_audiop > 1) {
+            avpriv_request_sample(s->avctx,
+                                  "Multiple DTS-HD audio presentations");
+            /* ignore such streams for now */
+            return;
+        }
+
+        num_assets = get_bits(&s->gb, 3) + 1;
+        if (num_assets > 1) {
+            avpriv_request_sample(s->avctx, "Multiple DTS-HD audio assets");
+            /* ignore such streams for now */
+            return;
+        }
+
+        for (i = 0; i < num_audiop; i++)
+            active_ss_mask[i] = get_bits(&s->gb, ss_index + 1);
+
+        for (i = 0; i < num_audiop; i++)
+            for (j = 0; j <= ss_index; j++)
+                if (active_ss_mask[i] & (1 << j))
+                    skip_bits(&s->gb, 8); // active asset mask
+
+        s->mix_metadata = get_bits1(&s->gb);
+        if (s->mix_metadata) {
+            int mix_out_mask_size;
+
+            skip_bits(&s->gb, 2); // adjustment level
+            mix_out_mask_size  = (get_bits(&s->gb, 2) + 1) << 2;
+            s->num_mix_configs =  get_bits(&s->gb, 2) + 1;
+
+            for (i = 0; i < s->num_mix_configs; i++) {
+                int mix_out_mask        = get_bits(&s->gb, mix_out_mask_size);
+                s->mix_config_num_ch[i] = dca_exss_mask2count(mix_out_mask);
+            }
+        }
+    }
+
+    av_assert0(num_assets > 0); // silence a warning
+
+    for (i = 0; i < num_assets; i++)
+        asset_size[i] = get_bits_long(&s->gb, 16 + 4 * blownup) + 1;
+
+    for (i = 0; i < num_assets; i++) {
+        if (dca_exss_parse_asset_header(s))
+            return;
+    }
+
+        j = get_bits_count(&s->gb);
+        if (start_pos + hdrsize * 8 > j)
+            skip_bits_long(&s->gb, start_pos + hdrsize * 8 - j);
+
+        for (i = 0; i < num_assets; i++) {
+            int end_pos;
+            start_pos = get_bits_count(&s->gb);
+            end_pos   = start_pos + asset_size[i] * 8;
+            mkr       = get_bits_long(&s->gb, 32);
+
+            /* parse extensions that we know about */
+            switch (mkr) {
+            case DCA_SYNCWORD_XBR:
+                ff_dca_xbr_parse_frame(s);
+                break;
+            case DCA_SYNCWORD_XXCH:
+                ff_dca_xxch_decode_frame(s);
+                s->core_ext_mask |= DCA_EXT_XXCH; /* xxx use for chan reordering */
+                break;
+            case DCA_SYNCWORD_XLL:
+                if (s->xll_disable) {
+                    av_log(s->avctx, AV_LOG_DEBUG,
+                           "DTS-XLL: ignoring XLL extension\n");
+                    break;
+                }
+                av_log(s->avctx, AV_LOG_DEBUG,
+                       "DTS-XLL: decoding XLL extension\n");
+                if (ff_dca_xll_decode_header(s)        == 0 &&
+                    ff_dca_xll_decode_navi(s, end_pos) == 0)
+                    s->exss_ext_mask |= DCA_EXT_EXSS_XLL;
+                break;
+            default:
+                av_log(s->avctx, AV_LOG_DEBUG,
+                       "DTS-ExSS: unknown marker = 0x%08x\n", mkr);
+            }
+
+            /* skip to end of block */
+            j = get_bits_count(&s->gb);
+            if (j > end_pos)
+                av_log(s->avctx, AV_LOG_ERROR,
+                       "DTS-ExSS: Processed asset too long.\n");
+            if (j < end_pos)
+                skip_bits_long(&s->gb, end_pos - j);
+        }
+}
diff --git a/libavcodec/dca_parser.c b/libavcodec/dca_parser.c
index 9fa6d0d..9797760 100644
--- a/libavcodec/dca_parser.c
+++ b/libavcodec/dca_parser.c
@@ -23,6 +23,7 @@
  */
 
 #include "dca.h"
+#include "dca_syncwords.h"
 #include "get_bits.h"
 #include "parser.h"
 
@@ -35,9 +36,9 @@
 } DCAParseContext;
 
 #define IS_MARKER(state, i, buf, buf_size) \
-    ((state == DCA_MARKER_14B_LE && (i < buf_size - 2) && (buf[i + 1] & 0xF0) == 0xF0 &&  buf[i + 2]         == 0x07) || \
-     (state == DCA_MARKER_14B_BE && (i < buf_size - 2) &&  buf[i + 1]         == 0x07 && (buf[i + 2] & 0xF0) == 0xF0) || \
-      state == DCA_MARKER_RAW_LE || state == DCA_MARKER_RAW_BE || state == DCA_HD_MARKER)
+    ((state == DCA_SYNCWORD_CORE_14B_LE && (i < buf_size - 2) && (buf[i + 1] & 0xF0) == 0xF0 &&  buf[i + 2]         == 0x07) || \
+     (state == DCA_SYNCWORD_CORE_14B_BE && (i < buf_size - 2) &&  buf[i + 1]         == 0x07 && (buf[i + 2] & 0xF0) == 0xF0) || \
+      state == DCA_SYNCWORD_CORE_LE || state == DCA_SYNCWORD_CORE_BE || state == DCA_SYNCWORD_SUBSTREAM)
 
 /**
  * Find the end of the current frame in the bitstream.
@@ -58,7 +59,7 @@
         for (i = 0; i < buf_size; i++) {
             state = (state << 8) | buf[i];
             if (IS_MARKER(state, i, buf, buf_size)) {
-                if (!pc1->lastmarker || state == pc1->lastmarker || pc1->lastmarker == DCA_HD_MARKER) {
+                if (!pc1->lastmarker || state == pc1->lastmarker || pc1->lastmarker == DCA_SYNCWORD_SUBSTREAM) {
                     start_found     = 1;
                     pc1->lastmarker = state;
                     i++;
@@ -71,9 +72,9 @@
         for (; i < buf_size; i++) {
             pc1->size++;
             state = (state << 8) | buf[i];
-            if (state == DCA_HD_MARKER && !pc1->hd_pos)
+            if (state == DCA_SYNCWORD_SUBSTREAM && !pc1->hd_pos)
                 pc1->hd_pos = pc1->size;
-            if (IS_MARKER(state, i, buf, buf_size) && (state == pc1->lastmarker || pc1->lastmarker == DCA_HD_MARKER)) {
+            if (IS_MARKER(state, i, buf, buf_size) && (state == pc1->lastmarker || pc1->lastmarker == DCA_SYNCWORD_SUBSTREAM)) {
                 if (pc1->framesize > pc1->size)
                     continue;
                 pc->frame_start_found = 0;
diff --git a/libavcodec/dca_syncwords.h b/libavcodec/dca_syncwords.h
new file mode 100644
index 0000000..3466b6b
--- /dev/null
+++ b/libavcodec/dca_syncwords.h
@@ -0,0 +1,37 @@
+/*
+ * 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_DCA_SYNCWORDS_H
+#define AVCODEC_DCA_SYNCWORDS_H
+
+enum DCASyncwords {
+    DCA_SYNCWORD_CORE_BE        = 0x7FFE8001U,
+    DCA_SYNCWORD_CORE_LE        = 0xFE7F0180U,
+    DCA_SYNCWORD_CORE_14B_BE    = 0x1FFFE800U,
+    DCA_SYNCWORD_CORE_14B_LE    = 0xFF1F00E8U,
+    DCA_SYNCWORD_XCH            = 0x5A5A5A5AU,
+    DCA_SYNCWORD_XXCH           = 0x47004A03U,
+    DCA_SYNCWORD_X96            = 0x1D95F262U,
+    DCA_SYNCWORD_XBR            = 0x655E315EU,
+    DCA_SYNCWORD_LBR            = 0x0A801921U,
+    DCA_SYNCWORD_XLL            = 0x41A29547U,
+    DCA_SYNCWORD_SUBSTREAM      = 0x64582025U,
+    DCA_SYNCWORD_SUBSTREAM_CORE = 0x02B09261U,
+};
+
+#endif /* AVCODEC_DCA_SYNCWORDS_H */
diff --git a/libavcodec/dca_xll.c b/libavcodec/dca_xll.c
new file mode 100644
index 0000000..9e1085c
--- /dev/null
+++ b/libavcodec/dca_xll.c
@@ -0,0 +1,747 @@
+/*
+ * DCA XLL extension
+ *
+ * Copyright (C) 2012 Paul B Mahol
+ * Copyright (C) 2014 Niels Möller
+ *
+ * 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/attributes.h"
+#include "libavutil/common.h"
+#include "libavutil/internal.h"
+
+#include "avcodec.h"
+#include "dca.h"
+#include "dcadata.h"
+#include "get_bits.h"
+#include "unary.h"
+
+/* Sign as bit 0 */
+static inline int get_bits_sm(GetBitContext *s, unsigned n)
+{
+    int x = get_bits(s, n);
+    if (x & 1)
+        return -(x >> 1) - 1;
+    else
+        return x >> 1;
+}
+
+/* Return -1 on error. */
+static int32_t get_dmix_coeff(DCAContext *s, int inverse)
+{
+    unsigned code = get_bits(&s->gb, 9);
+    int32_t sign = (int32_t) (code >> 8) - 1;
+    unsigned idx = code & 0xff;
+    int inv_offset = FF_DCA_DMIXTABLE_SIZE -FF_DCA_INV_DMIXTABLE_SIZE;
+    if (idx >= FF_DCA_DMIXTABLE_SIZE) {
+        av_log(s->avctx, AV_LOG_ERROR,
+               "XLL: Invalid channel set downmix code %x\n", code);
+        return -1;
+    } else if (!inverse) {
+        return (ff_dca_dmixtable[idx] ^ sign) - sign;
+    } else if (idx < inv_offset) {
+        av_log(s->avctx, AV_LOG_ERROR,
+               "XLL: Invalid channel set inverse downmix code %x\n", code);
+        return -1;
+    } else {
+        return (ff_dca_inv_dmixtable[idx - inv_offset] ^ sign) - sign;
+    }
+}
+
+static int32_t dca_get_dmix_coeff(DCAContext *s)
+{
+    return get_dmix_coeff(s, 0);
+}
+
+static int32_t dca_get_inv_dmix_coeff(DCAContext *s)
+{
+    return get_dmix_coeff(s, 1);
+}
+
+/* parse XLL header */
+int ff_dca_xll_decode_header(DCAContext *s)
+{
+    int hdr_pos, hdr_size;
+    av_unused int version, frame_size;
+    int i, chset_index;
+
+    /* get bit position of sync header */
+    hdr_pos    = get_bits_count(&s->gb) - 32;
+
+    version    = get_bits(&s->gb, 4) + 1;
+    hdr_size   = get_bits(&s->gb, 8) + 1;
+
+    frame_size = get_bits_long(&s->gb, get_bits(&s->gb, 5) + 1) + 1;
+
+    s->xll_channels          =
+    s->xll_residual_channels = 0;
+    s->xll_nch_sets          = get_bits(&s->gb, 4) + 1;
+    s->xll_segments          = 1 << get_bits(&s->gb, 4);
+    s->xll_log_smpl_in_seg   = get_bits(&s->gb, 4);
+    s->xll_smpl_in_seg       = 1 << s->xll_log_smpl_in_seg;
+    s->xll_bits4seg_size     = get_bits(&s->gb, 5) + 1;
+    s->xll_banddata_crc      = get_bits(&s->gb, 2);
+    s->xll_scalable_lsb      = get_bits1(&s->gb);
+    s->xll_bits4ch_mask      = get_bits(&s->gb, 5) + 1;
+
+    if (s->xll_scalable_lsb) {
+        s->xll_fixed_lsb_width = get_bits(&s->gb, 4);
+        if (s->xll_fixed_lsb_width)
+            av_log(s->avctx, AV_LOG_WARNING,
+                   "XLL: fixed lsb width = %d, non-zero not supported.\n",
+                   s->xll_fixed_lsb_width);
+    }
+    /* skip to the end of the common header */
+    i = get_bits_count(&s->gb);
+    if (hdr_pos + hdr_size * 8 > i)
+        skip_bits_long(&s->gb, hdr_pos + hdr_size * 8 - i);
+
+    for (chset_index = 0; chset_index < s->xll_nch_sets; chset_index++) {
+        XllChSetSubHeader *chset = &s->xll_chsets[chset_index];
+        hdr_pos  = get_bits_count(&s->gb);
+        hdr_size = get_bits(&s->gb, 10) + 1;
+
+        chset->channels           = get_bits(&s->gb, 4) + 1;
+        chset->residual_encode    = get_bits(&s->gb, chset->channels);
+        chset->bit_resolution     = get_bits(&s->gb, 5) + 1;
+        chset->bit_width          = get_bits(&s->gb, 5) + 1;
+        chset->sampling_frequency = ff_dca_sampling_freqs[get_bits(&s->gb, 4)];
+        chset->samp_freq_interp   = get_bits(&s->gb, 2);
+        chset->replacement_set    = get_bits(&s->gb, 2);
+        if (chset->replacement_set)
+            chset->active_replace_set = get_bits(&s->gb, 1);
+
+        if (s->one2one_map_chtospkr) {
+            chset->primary_ch_set              = get_bits(&s->gb, 1);
+            chset->downmix_coeff_code_embedded = get_bits(&s->gb, 1);
+            if (chset->downmix_coeff_code_embedded) {
+                chset->downmix_embedded = get_bits(&s->gb, 1);
+                if (chset->primary_ch_set) {
+                    chset->downmix_type = get_bits(&s->gb, 3);
+                    if (chset->downmix_type > 6) {
+                        av_log(s->avctx, AV_LOG_ERROR,
+                               "XLL: Invalid channel set downmix type\n");
+                        return AVERROR_INVALIDDATA;
+                    }
+                }
+            }
+            chset->hier_chset = get_bits(&s->gb, 1);
+
+            if (chset->downmix_coeff_code_embedded) {
+                /* nDownmixCoeffs is specified as N * M. For a primary
+                 * channel set, it appears that N = number of
+                 * channels, and M is the number of downmix channels.
+                 *
+                 * For a non-primary channel set, N is specified as
+                 * number of channels + 1, and M is derived from the
+                 * channel set hierarchy, and at least in simple cases
+                 * M is the number of channels in preceding channel
+                 * sets. */
+                if (chset->primary_ch_set) {
+                    static const char dmix_table[7] = { 1, 2, 2, 3, 3, 4, 4 };
+                    chset->downmix_ncoeffs = chset->channels * dmix_table[chset->downmix_type];
+                } else
+                    chset->downmix_ncoeffs = (chset->channels + 1) * s->xll_channels;
+
+                if (chset->downmix_ncoeffs > DCA_XLL_DMIX_NCOEFFS_MAX) {
+                    avpriv_request_sample(s->avctx,
+                                          "XLL: More than %d downmix coefficients",
+                                          DCA_XLL_DMIX_NCOEFFS_MAX);
+                    return AVERROR_PATCHWELCOME;
+                } else if (chset->primary_ch_set) {
+                    for (i = 0; i < chset->downmix_ncoeffs; i++)
+                        if ((chset->downmix_coeffs[i] = dca_get_dmix_coeff(s)) == -1)
+                            return AVERROR_INVALIDDATA;
+                } else {
+                    unsigned c, r;
+                    for (c = 0, i = 0; c < s->xll_channels; c++, i += chset->channels + 1) {
+                        if ((chset->downmix_coeffs[i] = dca_get_inv_dmix_coeff(s)) == -1)
+                            return AVERROR_INVALIDDATA;
+                        for (r = 1; r <= chset->channels; r++) {
+                            int32_t coeff = dca_get_dmix_coeff(s);
+                            if (coeff == -1)
+                                return AVERROR_INVALIDDATA;
+                            chset->downmix_coeffs[i + r] =
+                                (chset->downmix_coeffs[i] * (int64_t) coeff + (1 << 15)) >> 16;
+                        }
+                    }
+                }
+            }
+            chset->ch_mask_enabled = get_bits(&s->gb, 1);
+            if (chset->ch_mask_enabled)
+                chset->ch_mask = get_bits(&s->gb, s->xll_bits4ch_mask);
+            else
+                /* Skip speaker configuration bits */
+                skip_bits_long(&s->gb, 25 * chset->channels);
+        } else {
+            chset->primary_ch_set              = 1;
+            chset->downmix_coeff_code_embedded = 0;
+            /* Spec: NumChHierChSet = 0, NumDwnMixCodeCoeffs = 0, whatever that means. */
+            chset->mapping_coeffs_present = get_bits(&s->gb, 1);
+            if (chset->mapping_coeffs_present) {
+                avpriv_report_missing_feature(s->avctx, "XLL: mapping coefficients");
+                return AVERROR_PATCHWELCOME;
+            }
+        }
+        if (chset->sampling_frequency > 96000)
+            chset->num_freq_bands = 2 * (1 + get_bits(&s->gb, 1));
+        else
+            chset->num_freq_bands = 1;
+
+        if (chset->num_freq_bands > 1) {
+            avpriv_report_missing_feature(s->avctx, "XLL: num_freq_bands > 1");
+            return AVERROR_PATCHWELCOME;
+        }
+
+        if (get_bits(&s->gb, 1)) { /* pw_ch_decor_enabled */
+            int bits = av_ceil_log2(chset->channels);
+            for (i = 0; i < chset->channels; i++) {
+                unsigned j = get_bits(&s->gb, bits);
+                if (j >= chset->channels) {
+                    av_log(s->avctx, AV_LOG_ERROR,
+                           "Original channel order value %u too large, only %d channels.\n",
+                           j, chset->channels);
+                    return AVERROR_INVALIDDATA;
+                }
+                chset->orig_chan_order[0][i]     = j;
+                chset->orig_chan_order_inv[0][j] = i;
+            }
+            for (i = 0; i < chset->channels / 2; i++) {
+                if (get_bits(&s->gb, 1)) /* bChPFlag */
+                    chset->pw_ch_pairs_coeffs[0][i] = get_bits_sm(&s->gb, 7);
+                else
+                    chset->pw_ch_pairs_coeffs[0][i] = 0;
+            }
+        } else {
+            for (i = 0; i < chset->channels; i++)
+                chset->orig_chan_order[0][i]     =
+                chset->orig_chan_order_inv[0][i] = i;
+            for (i = 0; i < chset->channels / 2; i++)
+                chset->pw_ch_pairs_coeffs[0][i] = 0;
+        }
+        /* Adaptive prediction order */
+        chset->adapt_order_max[0] = 0;
+        for (i = 0; i < chset->channels; i++) {
+            chset->adapt_order[0][i] = get_bits(&s->gb, 4);
+            if (chset->adapt_order_max[0] < chset->adapt_order[0][i])
+                chset->adapt_order_max[0] = chset->adapt_order[0][i];
+        }
+        /* Fixed prediction order, used in case the adaptive order
+         * above is zero */
+        for (i = 0; i < chset->channels; i++)
+            chset->fixed_order[0][i] =
+                chset->adapt_order[0][i] ? 0 : get_bits(&s->gb, 2);
+
+        for (i = 0; i < chset->channels; i++) {
+            unsigned j;
+            for (j = 0; j < chset->adapt_order[0][i]; j++)
+                chset->lpc_refl_coeffs_q_ind[0][i][j] = get_bits(&s->gb, 8);
+        }
+
+        if (s->xll_scalable_lsb) {
+            chset->lsb_fsize[0] = get_bits(&s->gb, s->xll_bits4seg_size);
+
+            for (i = 0; i < chset->channels; i++)
+                chset->scalable_lsbs[0][i] = get_bits(&s->gb, 4);
+            for (i = 0; i < chset->channels; i++)
+                chset->bit_width_adj_per_ch[0][i] = get_bits(&s->gb, 4);
+        } else {
+            memset(chset->scalable_lsbs[0], 0,
+                   chset->channels * sizeof(chset->scalable_lsbs[0][0]));
+            memset(chset->bit_width_adj_per_ch[0], 0,
+                   chset->channels * sizeof(chset->bit_width_adj_per_ch[0][0]));
+        }
+
+        s->xll_channels          += chset->channels;
+        s->xll_residual_channels += chset->channels -
+                                    av_popcount(chset->residual_encode);
+
+        /* FIXME: Parse header data for extra frequency bands. */
+
+        /* Skip to end of channel set sub header. */
+        i = get_bits_count(&s->gb);
+        if (hdr_pos + 8 * hdr_size < i) {
+            av_log(s->avctx, AV_LOG_ERROR,
+                   "chset header too large, %d bits, should be <= %d bits\n",
+                   i - hdr_pos, 8 * hdr_size);
+            return AVERROR_INVALIDDATA;
+        }
+        if (hdr_pos + 8 * hdr_size > i)
+            skip_bits_long(&s->gb, hdr_pos + 8 * hdr_size - i);
+    }
+    return 0;
+}
+
+/* parse XLL navigation table */
+int ff_dca_xll_decode_navi(DCAContext *s, int asset_end)
+{
+    int nbands, band, chset, seg, data_start;
+
+    /* FIXME: Supports only a single frequency band */
+    nbands = 1;
+
+    for (band = 0; band < nbands; band++) {
+        s->xll_navi.band_size[band] = 0;
+        for (seg = 0; seg < s->xll_segments; seg++) {
+            /* Note: The spec, ETSI TS 102 114 V1.4.1 (2012-09), says
+             * we should read a base value for segment_size from the
+             * stream, before reading the sizes of the channel sets.
+             * But that's apparently incorrect. */
+            s->xll_navi.segment_size[band][seg] = 0;
+
+            for (chset = 0; chset < s->xll_nch_sets; chset++)
+                if (band < s->xll_chsets[chset].num_freq_bands) {
+                    s->xll_navi.chset_size[band][seg][chset] =
+                        get_bits(&s->gb, s->xll_bits4seg_size) + 1;
+                    s->xll_navi.segment_size[band][seg] +=
+                        s->xll_navi.chset_size[band][seg][chset];
+                }
+            s->xll_navi.band_size[band] += s->xll_navi.segment_size[band][seg];
+        }
+    }
+    /* Align to 8 bits and skip 16-bit CRC. */
+    skip_bits_long(&s->gb, 16 + ((-get_bits_count(&s->gb)) & 7));
+
+    data_start = get_bits_count(&s->gb);
+    if (data_start + 8 * s->xll_navi.band_size[0] > asset_end) {
+        av_log(s->avctx, AV_LOG_ERROR,
+               "XLL: Data in NAVI table exceeds containing asset\n"
+               "start: %d (bit), size %u (bytes), end %d (bit), error %u\n",
+               data_start, s->xll_navi.band_size[0], asset_end,
+               data_start + 8 * s->xll_navi.band_size[0] - asset_end);
+        return AVERROR_INVALIDDATA;
+    }
+    init_get_bits(&s->xll_navi.gb, s->gb.buffer + data_start / 8,
+                  8 * s->xll_navi.band_size[0]);
+    return 0;
+}
+
+static void dca_xll_inv_adapt_pred(int *samples, int nsamples, unsigned order,
+                                   const int *prev, const uint8_t *q_ind)
+{
+    static const uint16_t table[0x81] = {
+            0,  3070,  5110,  7140,  9156, 11154, 13132, 15085,
+        17010, 18904, 20764, 22588, 24373, 26117, 27818, 29474,
+        31085, 32648, 34164, 35631, 37049, 38418, 39738, 41008,
+        42230, 43404, 44530, 45609, 46642, 47630, 48575, 49477,
+        50337, 51157, 51937, 52681, 53387, 54059, 54697, 55302,
+        55876, 56421, 56937, 57426, 57888, 58326, 58741, 59132,
+        59502, 59852, 60182, 60494, 60789, 61066, 61328, 61576,
+        61809, 62029, 62236, 62431, 62615, 62788, 62951, 63105,
+        63250, 63386, 63514, 63635, 63749, 63855, 63956, 64051,
+        64140, 64224, 64302, 64376, 64446, 64512, 64573, 64631,
+        64686, 64737, 64785, 64830, 64873, 64913, 64950, 64986,
+        65019, 65050, 65079, 65107, 65133, 65157, 65180, 65202,
+        65222, 65241, 65259, 65275, 65291, 65306, 65320, 65333,
+        65345, 65357, 65368, 65378, 65387, 65396, 65405, 65413,
+        65420, 65427, 65434, 65440, 65446, 65451, 65456, 65461,
+        65466, 65470, 65474, 65478, 65481, 65485, 65488, 65491,
+        65535, /* Final value is for the -128 corner case, see below. */
+    };
+    int c[DCA_XLL_AORDER_MAX];
+    int64_t s;
+    unsigned i, j;
+
+    for (i = 0; i < order; i++) {
+        if (q_ind[i] & 1)
+            /* The index value 0xff corresponds to a lookup of entry 0x80 in
+             * the table, and no value is provided in the specification. */
+            c[i] = -table[(q_ind[i] >> 1) + 1];
+        else
+            c[i] = table[q_ind[i] >> 1];
+    }
+    /* The description in the spec is a bit convoluted. We can convert
+     * the reflected values to direct values in place, using a
+     * sequence of reflections operating on two values. */
+    for (i = 1; i < order; i++) {
+        /* i = 1: scale c[0]
+         * i = 2: reflect c[0] <-> c[1]
+         * i = 3: scale c[1], reflect c[0] <-> c[2]
+         * i = 4: reflect c[0] <-> c[3] reflect c[1] <-> c[2]
+         * ... */
+        if (i & 1)
+            c[i / 2] += ((int64_t) c[i] * c[i / 2] + 0x8000) >> 16;
+        for (j = 0; j < i / 2; j++) {
+            int r0 = c[j];
+            int r1 = c[i - j - 1];
+            c[j]         += ((int64_t) c[i] * r1 + 0x8000) >> 16;
+            c[i - j - 1] += ((int64_t) c[i] * r0 + 0x8000) >> 16;
+        }
+    }
+    /* Apply predictor. */
+    /* NOTE: Processing samples in this order means that the
+     * predictor is applied to the newly reconstructed samples. */
+    if (prev) {
+        for (i = 0; i < order; i++) {
+            for (j = s = 0; j < i; j++)
+                s += (int64_t) c[j] * samples[i - 1 - j];
+            for (; j < order; j++)
+                s += (int64_t) c[j] * prev[DCA_XLL_AORDER_MAX + i - 1 - j];
+
+            samples[i] -= av_clip((s + 0x8000) >> 16, -0x1000000, 0xffffff);
+        }
+    }
+    for (i = order; i < nsamples; i++) {
+        for (j = s = 0; j < order; j++)
+            s += (int64_t) c[j] * samples[i - 1 - j];
+
+        /* NOTE: Equations seem to imply addition, while the
+         * pseudocode seems to use subtraction.*/
+        samples[i] -= av_clip((s + 0x8000) >> 16, -0x1000000, 0xffffff);
+    }
+}
+
+int ff_dca_xll_decode_audio(DCAContext *s, AVFrame *frame)
+{
+    /* FIXME: Decodes only the first frequency band. */
+    int seg, chset_i;
+
+    /* Coding parameters for each channel set. */
+    struct coding_params {
+        int seg_type;
+        int rice_code_flag[16];
+        int pancAuxABIT[16];
+        int pancABIT0[16];  /* Not sure what this is */
+        int pancABIT[16];   /* Not sure what this is */
+        int nSamplPart0[16];
+    } param_state[16];
+
+    GetBitContext *gb = &s->xll_navi.gb;
+    int *history;
+
+    /* Layout: First the sample buffer for one segment per channel,
+     * followed by history buffers of DCA_XLL_AORDER_MAX samples for
+     * each channel. */
+    av_fast_malloc(&s->xll_sample_buf, &s->xll_sample_buf_size,
+                   (s->xll_smpl_in_seg + DCA_XLL_AORDER_MAX) *
+                   s->xll_channels * sizeof(*s->xll_sample_buf));
+    if (!s->xll_sample_buf)
+        return AVERROR(ENOMEM);
+
+    history = s->xll_sample_buf + s->xll_smpl_in_seg * s->xll_channels;
+
+    for (seg = 0; seg < s->xll_segments; seg++) {
+        unsigned in_channel;
+
+        for (chset_i = in_channel = 0; chset_i < s->xll_nch_sets; chset_i++) {
+            /* The spec isn't very explicit, but I think the NAVI sizes are in bytes. */
+            int end_pos = get_bits_count(gb) +
+                          8 * s->xll_navi.chset_size[0][seg][chset_i];
+            int i, j;
+            struct coding_params *params = &param_state[chset_i];
+            /* I think this flag means that we should keep seg_type and
+             * other parameters from the previous segment. */
+            int use_seg_state_code_param;
+            XllChSetSubHeader *chset = &s->xll_chsets[chset_i];
+            if (in_channel >= s->avctx->channels)
+                /* FIXME: Could go directly to next segment */
+                goto next_chset;
+
+            if (s->avctx->sample_rate != chset->sampling_frequency) {
+                av_log(s->avctx, AV_LOG_WARNING,
+                       "XLL: unexpected chset sample rate %d, expected %d\n",
+                       chset->sampling_frequency, s->avctx->sample_rate);
+                goto next_chset;
+            }
+            if (seg != 0)
+                use_seg_state_code_param = get_bits(gb, 1);
+            else
+                use_seg_state_code_param = 0;
+
+            if (!use_seg_state_code_param) {
+                int num_param_sets, i;
+                unsigned bits4ABIT;
+
+                params->seg_type = get_bits(gb, 1);
+                num_param_sets   = params->seg_type ? 1 : chset->channels;
+
+                if (chset->bit_width > 16) {
+                    bits4ABIT = 5;
+                } else {
+                    if (chset->bit_width > 8)
+                        bits4ABIT = 4;
+                    else
+                        bits4ABIT = 3;
+                    if (s->xll_nch_sets > 1)
+                        bits4ABIT++;
+                }
+
+                for (i = 0; i < num_param_sets; i++) {
+                    params->rice_code_flag[i] = get_bits(gb, 1);
+                    if (!params->seg_type && params->rice_code_flag[i] && get_bits(gb, 1))
+                        params->pancAuxABIT[i] = get_bits(gb, bits4ABIT) + 1;
+                    else
+                        params->pancAuxABIT[i] = 0;
+                }
+
+                for (i = 0; i < num_param_sets; i++) {
+                    if (!seg) {
+                        /* Parameters for part 1 */
+                        params->pancABIT0[i] = get_bits(gb, bits4ABIT);
+                        if (params->rice_code_flag[i] == 0 && params->pancABIT0[i] > 0)
+                            /* For linear code */
+                            params->pancABIT0[i]++;
+
+                        /* NOTE: In the spec, not indexed by band??? */
+                        if (params->seg_type == 0)
+                            params->nSamplPart0[i] = chset->adapt_order[0][i];
+                        else
+                            params->nSamplPart0[i] = chset->adapt_order_max[0];
+                    } else
+                        params->nSamplPart0[i] = 0;
+
+                    /* Parameters for part 2 */
+                    params->pancABIT[i] = get_bits(gb, bits4ABIT);
+                    if (params->rice_code_flag[i] == 0 && params->pancABIT[i] > 0)
+                        /* For linear code */
+                        params->pancABIT[i]++;
+                }
+            }
+            for (i = 0; i < chset->channels; i++) {
+                int param_index = params->seg_type ? 0 : i;
+                int part0       = params->nSamplPart0[param_index];
+                int bits        = part0 ? params->pancABIT0[param_index] : 0;
+                int *sample_buf = s->xll_sample_buf +
+                                  (in_channel + i) * s->xll_smpl_in_seg;
+
+                if (!params->rice_code_flag[param_index]) {
+                    /* Linear code */
+                    if (bits)
+                        for (j = 0; j < part0; j++)
+                            sample_buf[j] = get_bits_sm(gb, bits);
+                    else
+                        memset(sample_buf, 0, part0 * sizeof(sample_buf[0]));
+
+                    /* Second part */
+                    bits = params->pancABIT[param_index];
+                    if (bits)
+                        for (j = part0; j < s->xll_smpl_in_seg; j++)
+                            sample_buf[j] = get_bits_sm(gb, bits);
+                    else
+                        memset(sample_buf + part0, 0,
+                               (s->xll_smpl_in_seg - part0) * sizeof(sample_buf[0]));
+                } else {
+                    int aux_bits = params->pancAuxABIT[param_index];
+
+                    for (j = 0; j < part0; j++) {
+                        /* FIXME: Is this identical to Golomb code? */
+                        int t = get_unary(gb, 1, 33) << bits;
+                        /* FIXME: Could move this test outside of the loop, for efficiency. */
+                        if (bits)
+                            t |= get_bits(gb, bits);
+                        sample_buf[j] = (t & 1) ? -(t >> 1) - 1 : (t >> 1);
+                    }
+
+                    /* Second part */
+                    bits = params->pancABIT[param_index];
+
+                    /* Follow the spec's suggestion of using the
+                     * buffer also to store the hybrid-rice flags. */
+                    memset(sample_buf + part0, 0,
+                           (s->xll_smpl_in_seg - part0) * sizeof(sample_buf[0]));
+
+                    if (aux_bits > 0) {
+                        /* For hybrid rice encoding, some samples are linearly
+                         * coded. According to the spec, "nBits4SamplLoci" bits
+                         * are used for each index, but this value is not
+                         * defined. I guess we should use log2(xll_smpl_in_seg)
+                         * bits. */
+                        int count = get_bits(gb, s->xll_log_smpl_in_seg);
+                        av_log(s->avctx, AV_LOG_DEBUG, "aux count %d (bits %d)\n",
+                               count, s->xll_log_smpl_in_seg);
+
+                        for (j = 0; j < count; j++)
+                            sample_buf[get_bits(gb, s->xll_log_smpl_in_seg)] = 1;
+                    }
+                    for (j = part0; j < s->xll_smpl_in_seg; j++) {
+                        if (!sample_buf[j]) {
+                            int t = get_unary(gb, 1, 33);
+                            if (bits)
+                                t = (t << bits) | get_bits(gb, bits);
+                            sample_buf[j] = (t & 1) ? -(t >> 1) - 1 : (t >> 1);
+                        } else
+                            sample_buf[j] = get_bits_sm(gb, aux_bits);
+                    }
+                }
+            }
+
+            for (i = 0; i < chset->channels; i++) {
+                unsigned adapt_order = chset->adapt_order[0][i];
+                int *sample_buf = s->xll_sample_buf +
+                                  (in_channel + i) * s->xll_smpl_in_seg;
+                int *prev = history + (in_channel + i) * DCA_XLL_AORDER_MAX;
+
+                if (!adapt_order) {
+                    unsigned order;
+                    for (order = chset->fixed_order[0][i]; order > 0; order--) {
+                        unsigned j;
+                        for (j = 1; j < s->xll_smpl_in_seg; j++)
+                            sample_buf[j] += sample_buf[j - 1];
+                    }
+                } else
+                    /* Inverse adaptive prediction, in place. */
+                    dca_xll_inv_adapt_pred(sample_buf, s->xll_smpl_in_seg,
+                                           adapt_order, seg ? prev : NULL,
+                                           chset->lpc_refl_coeffs_q_ind[0][i]);
+                memcpy(prev, sample_buf + s->xll_smpl_in_seg - DCA_XLL_AORDER_MAX,
+                       DCA_XLL_AORDER_MAX * sizeof(*prev));
+            }
+            for (i = 1; i < chset->channels; i += 2) {
+                int coeff = chset->pw_ch_pairs_coeffs[0][i / 2];
+                if (coeff != 0) {
+                    int *sample_buf = s->xll_sample_buf +
+                                      (in_channel + i) * s->xll_smpl_in_seg;
+                    int *prev = sample_buf - s->xll_smpl_in_seg;
+                    unsigned j;
+                    for (j = 0; j < s->xll_smpl_in_seg; j++)
+                        /* Shift is unspecified, but should apparently be 3. */
+                        sample_buf[j] += ((int64_t) coeff * prev[j] + 4) >> 3;
+                }
+            }
+
+            if (s->xll_scalable_lsb) {
+                int lsb_start = end_pos - 8 * chset->lsb_fsize[0] -
+                                8 * (s->xll_banddata_crc & 2);
+                int done;
+                i = get_bits_count(gb);
+                if (i > lsb_start) {
+                    av_log(s->avctx, AV_LOG_ERROR,
+                           "chset data lsb exceeds NAVI size, end_pos %d, lsb_start %d, pos %d\n",
+                           end_pos, lsb_start, i);
+                    return AVERROR_INVALIDDATA;
+                }
+                if (i < lsb_start)
+                    skip_bits_long(gb, lsb_start - i);
+
+                for (i = done = 0; i < chset->channels; i++) {
+                    int bits = chset->scalable_lsbs[0][i];
+                    if (bits > 0) {
+                        /* The channel reordering is conceptually done
+                         * before adding the lsb:s, so we need to do
+                         * the inverse permutation here. */
+                        unsigned pi = chset->orig_chan_order_inv[0][i];
+                        int *sample_buf = s->xll_sample_buf +
+                                          (in_channel + pi) * s->xll_smpl_in_seg;
+                        int adj = chset->bit_width_adj_per_ch[0][i];
+                        int msb_shift = bits;
+                        unsigned j;
+
+                        if (adj > 0)
+                            msb_shift += adj - 1;
+
+                        for (j = 0; j < s->xll_smpl_in_seg; j++)
+                            sample_buf[j] = (sample_buf[j] << msb_shift) +
+                                            (get_bits(gb, bits) << adj);
+
+                        done += bits * s->xll_smpl_in_seg;
+                    }
+                }
+                if (done > 8 * chset->lsb_fsize[0]) {
+                    av_log(s->avctx, AV_LOG_ERROR,
+                           "chset lsb exceeds lsb_size\n");
+                    return AVERROR_INVALIDDATA;
+                }
+            }
+
+            /* Store output. */
+            for (i = 0; i < chset->channels; i++) {
+                int *sample_buf = s->xll_sample_buf +
+                                  (in_channel + i) * s->xll_smpl_in_seg;
+                int shift = 1 - chset->bit_resolution;
+                int out_channel = chset->orig_chan_order[0][i];
+                float *out;
+
+                /* XLL uses the channel order C, L, R, and we want L,
+                 * R, C. FIXME: Generalize. */
+                if (chset->ch_mask_enabled &&
+                    (chset->ch_mask & 7) == 7 && out_channel < 3)
+                    out_channel = out_channel ? out_channel - 1 : 2;
+
+                out_channel += in_channel;
+                if (out_channel >= s->avctx->channels)
+                    continue;
+
+                out  = (float *) frame->extended_data[out_channel];
+                out += seg * s->xll_smpl_in_seg;
+
+                /* NOTE: A one bit means residual encoding is *not* used. */
+                if ((chset->residual_encode >> i) & 1) {
+                    /* Replace channel samples.
+                     * FIXME: Most likely not the right thing to do. */
+                    for (j = 0; j < s->xll_smpl_in_seg; j++)
+                        out[j] = ldexpf(sample_buf[j], shift);
+                } else {
+                    /* Add residual signal to core channel */
+                    for (j = 0; j < s->xll_smpl_in_seg; j++)
+                        out[j] += ldexpf(sample_buf[j], shift);
+                }
+            }
+
+            if (chset->downmix_coeff_code_embedded &&
+                !chset->primary_ch_set && chset->hier_chset) {
+                /* Undo hierarchical downmix of earlier channels. */
+                unsigned mix_channel;
+                for (mix_channel = 0; mix_channel < in_channel; mix_channel++) {
+                    float *mix_buf;
+                    const int *col;
+                    float coeff;
+                    unsigned row;
+                    /* Similar channel reorder C, L, R vs L, R, C reorder. */
+                    if (chset->ch_mask_enabled &&
+                        (chset->ch_mask & 7) == 7 && mix_channel < 3)
+                        mix_buf = (float *) frame->extended_data[mix_channel ? mix_channel - 1 : 2];
+                    else
+                        mix_buf = (float *) frame->extended_data[mix_channel];
+
+                    mix_buf += seg * s->xll_smpl_in_seg;
+                    col = &chset->downmix_coeffs[mix_channel * (chset->channels + 1)];
+
+                    /* Scale */
+                    coeff = ldexpf(col[0], -16);
+                    for (j = 0; j < s->xll_smpl_in_seg; j++)
+                        mix_buf[j] *= coeff;
+
+                    for (row = 0;
+                         row < chset->channels && in_channel + row < s->avctx->channels;
+                         row++)
+                        if (col[row + 1]) {
+                            const float *new_channel =
+                                (const float *) frame->extended_data[in_channel + row];
+                            new_channel += seg * s->xll_smpl_in_seg;
+                            coeff        = ldexpf(col[row + 1], -15);
+                            for (j = 0; j < s->xll_smpl_in_seg; j++)
+                                mix_buf[j] -= coeff * new_channel[j];
+                        }
+                }
+            }
+
+next_chset:
+            in_channel += chset->channels;
+            /* Skip to next channel set using the NAVI info. */
+            i = get_bits_count(gb);
+            if (i > end_pos) {
+                av_log(s->avctx, AV_LOG_ERROR,
+                       "chset data exceeds NAVI size\n");
+                return AVERROR_INVALIDDATA;
+            }
+            if (i < end_pos)
+                skip_bits_long(gb, end_pos - i);
+        }
+    }
+    return 0;
+}
diff --git a/libavcodec/dcadata.c b/libavcodec/dcadata.c
new file mode 100644
index 0000000..5d7d594
--- /dev/null
+++ b/libavcodec/dcadata.c
@@ -0,0 +1,8497 @@
+/*
+ * DCA compatible decoder data
+ * Copyright (C) 2004 Gildas Bazin
+ * Copyright (c) 2006 Benjamin Larsson
+ *
+ * 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/channel_layout.h"
+#include "libavutil/mem.h"
+
+#include "dca.h"
+#include "dcadata.h"
+
+/* Generic tables */
+
+const uint32_t ff_dca_bit_rates[32] = {
+      32000,   56000,   64000,   96000,  112000, 128000,
+     192000,  224000,  256000,  320000,  384000,
+     448000,  512000,  576000,  640000,  768000,
+     896000, 1024000, 1152000, 1280000, 1344000,
+    1408000, 1411200, 1472000, 1536000, 1920000,
+    2048000, 3072000, 3840000, 1 /* open */, 2 /* variable */, 3 /* lossless */
+};
+
+const uint8_t ff_dca_channels[16] = {
+    1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 8
+};
+
+const uint8_t ff_dca_bits_per_sample[7] = {
+    16, 16, 20, 20, 0, 24, 24
+};
+
+/* ADPCM data */
+
+/* 16bits signed fractional Q13 binary codes */
+const int16_t ff_dca_adpcm_vb[4096][4] = {
+    {   9928,  -2618,  -1093, -1263 },
+    {  11077,  -2876,  -1747,  -308 },
+    {  10503,  -1082,  -1426, -1167 },
+    {   9337,  -2403,  -1495,   274 },
+    {  10698,  -2529,   -532, -1122 },
+    {  10368,  -3974,  -1264,  -750 },
+    {  10070,  -3667,    346,   863 },
+    {  10278,  -3093,    311,  -576 },
+    {   9894,  -1330,  -1428,  -860 },
+    {  10544,  -1923,  -1058,  -971 },
+    {  10996,  -1632,   -841, -1404 },
+    {  11832,  -3465,   1658, -1990 },
+    {  10852,   -688,  -2658,  -499 },
+    {  10546,  -1749,   -147, -1733 },
+    {  10801,  -1004,   -708, -1453 },
+    {  10588,   -441,  -2113,  -952 },
+    {  10141,  -3331,   -582, -1432 },
+    {   9608,  -2590,    383,   258 },
+    {  11422,  -3265,    229, -1544 },
+    {  10460,  -1338,   -713, -1568 },
+    {  10306,  -1721,  -1660,  -603 },
+    {   9580,  -1812,  -1235, -1061 },
+    {  11471,  -2285,  -1617,  -607 },
+    {  10081,  -2225,  -1408,  -868 },
+    {  10715,  -2624,  -1367,  -704 },
+    {  10616,  -1871,  -2770,   -35 },
+    {   9352,  -2340,  -1024, -1566 },
+    {  11065,  -1458,  -1926,  -735 },
+    {  11334,  -2056,  -1041, -1144 },
+    {   9825,  -2048,   -794, -1536 },
+    {  11850,  -2695,  -1123,  -867 },
+    {  10654,  -2226,  -1891,  -373 },
+    {  10024,  -1557,   -808, -1069 },
+    {  11142,  -1266,  -3238,   128 },
+    {  11729,  -3282,   -514, -1011 },
+    {  11402,  -2094,  -2335,  -189 },
+    {  10195,  -3658,    181, -1875 },
+    {  11431,  -2626,   -404, -1377 },
+    {  11001,  -3868,   -619, -1077 },
+    {  10894,  -2559,    274, -1758 },
+    {   9633,  -1482,  -2253,  -773 },
+    {  11245,  -3321,    830, -1972 },
+    {   9768,  -2701,   -199, -1859 },
+    {  10500,  -2042,    525, -2043 },
+    {  11669,  -4069,    293, -1468 },
+    {   9192,  -1991,   -583,   -61 },
+    {  10057,  -3220,  -2015,  -473 },
+    {   9497,  -2315,  -2490,  -467 },
+    {  10455,  -3069,  -1194, -1007 },
+    {   9994,  -1936,    -60, -1225 },
+    {   9295,  -2156,  -1761, -1134 },
+    {  10085,  -3748,  -1026,   197 },
+    {   9334,  -2360,    804,  -351 },
+    {  11561,  -2553,   1352, -2313 },
+    {  12837,  -3998,   1195, -1958 },
+    {  10114,  -1100,  -2414,  -394 },
+    {   9341,  -2530,    315,   755 },
+    {  10131,  -3164,   1411,  -674 },
+    {   9535,   -905,  -1551,   579 },
+    {  11717,  -1519,  -3051,    91 },
+    {   9824,  -2911,  -2775,   192 },
+    {   9662,  -2934,   -561,  1450 },
+    {  11085,  -3392,  -1298,  -659 },
+    {   8955,  -2102,  -1899,   703 },
+    {   8607,  -1742,  -4348,   814 },
+    {   7640,  -2063,  -3617,    52 },
+    {   7074,   -826,  -4325,  4375 },
+    {   7714,    584,  -4238,  1927 },
+    {   6355,   -952,  -4912,  3127 },
+    {   7069,   -660,  -6413,  4087 },
+    {   8313,   -132,  -2964,  -876 },
+    {   6952,  -1422,  -3962,   -24 },
+    {   9299,   -734,  -3088,  -263 },
+    {   9484,   -574,  -4513,   466 },
+    {   7246,    -91,  -3735,  -704 },
+    {   8325,  -1417,  -3090,  -530 },
+    {   6469,  -1226,  -4757,   829 },
+    {   6652,   -368,  -5682,  1393 },
+    {   7971,  -1278,  -2284,  1205 },
+    {   7229,   -699,  -3556,  1840 },
+    {   7994,   1284,  -2729,   732 },
+    {   9005,   -698,  -4522,  2189 },
+    {   6963,    197,  -2727,   380 },
+    {   8527,    135,  -3991,  -213 },
+    {   8840,    934,  -3014,  -567 },
+    {  10125,    418,  -3284,  -371 },
+    {   6367,    361,  -2318,  2554 },
+    {   7892,    172,  -5247,  4673 },
+    {   6674,    387,  -5424,  4398 },
+    {   6240,    684,  -4047,  1219 },
+    {  11170,   -794,  -5081,  1195 },
+    {  11765,   -648,  -6265,  2052 },
+    {  10845,   -775,  -3837,   366 },
+    {  12496,   -689,  -8260,  3562 },
+    {   7893,  -1166,  -4972,   988 },
+    {   8592,   1052,  -5986,  3087 },
+    {   7277,   1874,  -5685,  3579 },
+    {   6900,   2016,  -4809,  3491 },
+    {   8530,  -2405,  -3250,  1986 },
+    {   9426,    494,  -7067,  5038 },
+    {  10285,    564,  -8210,  5370 },
+    {   8749,  -2207,  -3980,  2852 },
+    {   9653,  -2686,  -4300,  1400 },
+    {   9770,  -2286,  -5663,  4233 },
+    {   8490,     -4,  -7048,  4496 },
+    {   7697,  -1209,  -5328,  3183 },
+    {   6451,    801,  -4324,  -554 },
+    {   7387,   1806,  -5265,   545 },
+    {   7450,  -2302,  -4445,  1418 },
+    {   8817,  -1370,  -5827,  2168 },
+    {  10324,  -2406,  -5629,  2579 },
+    {   8863,  -2578,  -3537,   467 },
+    {   6901,  -1624,  -3169,  3392 },
+    {   7846,    156,  -6948,  3381 },
+    {   7928,  -1115,  -5972,  4816 },
+    {   6089,   -599,  -4368,  -320 },
+    {   7833,   1246,  -3960,  -621 },
+    {   8931,   2521,  -6768,  2052 },
+    {   8900,   1944,  -4126,    40 },
+    {   7661,    -34,  -2855,  2480 },
+    {   5873,    474,  -3262,  3712 },
+    {   7535,   -234,  -4699,   216 },
+    {   5856,    143,  -5142,    73 },
+    {   8944,   -106,  -5874,  3663 },
+    {   7134,    426,  -5879,  2895 },
+    {  10199,   1011,  -4762,   369 },
+    {   8454,    264,  -5971,  1291 },
+    {   7822,  -2449,  -4333,  4540 },
+    {   6200,  -2758,  -2632,  1497 },
+    {   6070,  -4315,  -2699,   414 },
+    {   7047,  -3739,  -3210,  1060 },
+    {   5675,  -3801,  -2717,  -407 },
+    {   4789,  -4063,  -2628,  -744 },
+    {   4023,  -3366,  -3133,  -726 },
+    {   4296,  -2407,  -3381,  -513 },
+    {   4388,  -2931,  -2820,  1512 },
+    {   4559,  -4233,  -1941,  1976 },
+    {   6702,  -3208,  -1755,  1680 },
+    {   4416,  -3521,  -1052,  2984 },
+    {   7154,  -4266,  -1203,  3732 },
+    {   3625,  -4242,  -3244,  1395 },
+    {   6518,  -2856,  -1304,  2887 },
+    {   6170,  -1949,  -3014,  3973 },
+    {   5189,  -2451,  -4020,  3477 },
+    {   6218,  -2988,  -1921,  3844 },
+    {   4827,  -3688,  -1928,  3343 },
+    {   6668,  -3991,  -2805,  3095 },
+    {   5297,  -3115,  -3684,  2390 },
+    {   5354,  -4614,  -2662,  1504 },
+    {   4196,  -3091,  -4147,  1135 },
+    {   3540,  -2893,  -4007,   100 },
+    {   5569,  -1602,  -4007,  1909 },
+    {   4341,  -2091,  -4272,   252 },
+    {   5559,  -2878,  -3832,   498 },
+    {   4548,  -4479,  -2898,   -27 },
+    {   5176,  -2494,  -4635,  1476 },
+    {   3294,  -3485,  -3738,   716 },
+    {   4920,  -1229,  -4195,  -365 },
+    {   3257,  -3518,  -3349,  2862 },
+    {   5286,  -1948,  -3485,  -778 },
+    {   6502,  -3051,   -152,  2854 },
+    {   5864,  -4192,  -1076,  3451 },
+    {   4656,  -3122,  -3448,   179 },
+    {   5907,   -754,  -1596,  3116 },
+    {   7229,  -3680,  -1590,  2892 },
+    {   5107,  -3888,  -3364,   806 },
+    {   6764,  -2635,  -3450,   134 },
+    {   5258,  -2827,  -2844, -1052 },
+    {   5798,  -1725,  -4305,   205 },
+    {   5404,  -1213,  -3362,   449 },
+    {   6224,  -2738,  -3046,  -581 },
+    {   4223,  -2438,  -2725,  3745 },
+    {   4751,  -3411,  -2123,   116 },
+    {   3868,  -3000,  -3954,  2297 },
+    {   6819,  -2899,  -4277,  2825 },
+    {   4207,  -4754,  -2808,   865 },
+    {   4804,  -1494,  -1997,  4688 },
+    {   5282,  -2213,   -548,  3559 },
+    {   5580,  -1912,   -566,  4370 },
+    {   6168,  -2857,   -672,  4053 },
+    {   6583,  -4515,  -2850,  1670 },
+    {   6511,  -3093,  -3988,  1421 },
+    {   4646,  -1790,  -1443,  3650 },
+    {   5915,   -924,  -2020,   896 },
+    {   7814,  -4181,  -3152,  2007 },
+    {   6190,  -2238,  -4817,  2279 },
+    {   4737,  -4034,  -3288,  1835 },
+    {   8161,  -3633,  -3423,  3137 },
+    {   7415,  -2351,  -2088,  4290 },
+    {   4106,  -2517,    -62,  2905 },
+    {   4909,  -3145,   -614,  4112 },
+    {   4938,  -3281,   -397,  1100 },
+    {   -173,    919,   1589, -5363 },
+    {    -13,    796,   -295, -6655 },
+    {  -1860,   -829,   1141, -4555 },
+    {   2298,   -838,   -664, -5005 },
+    {   -884,  -1097,   2074, -4613 },
+    {   -101,    281,   2846, -4535 },
+    {   1166,    453,   2429, -5910 },
+    {    879,   -664,   2370, -5452 },
+    {   1415,   -370,  -1699, -4727 },
+    {  -1413,   1277,   -669, -6649 },
+    {   2133,    304,   -968, -4624 },
+    {    380,    586,  -2087, -4892 },
+    {   1336,    275,    -82, -5789 },
+    {  -2459,   1057,    -34, -5416 },
+    {   2278,  -1758,    866, -5653 },
+    {   1945,  -2295,   -149, -5302 },
+    {   1287,  -3525,    996, -5255 },
+    {   2297,    803,   1177, -6067 },
+    {    187,   -180,   -619, -6202 },
+    {   -793,  -2537,   1554, -5057 },
+    {  -2703,   -204,   -629, -5853 },
+    {  -1007,   -146,    313, -5582 },
+    {    830,    357,    869, -6363 },
+    {   -228,   -575,  -3177, -4433 },
+    {  -1001,  -1553,   -142, -5708 },
+    {  -1644,   1683,   1721, -4533 },
+    {    893,   1924,    -15, -5791 },
+    {   2195,   2061,   -262, -5471 },
+    {   3031,    270,    311, -5096 },
+    {   1912,   1638,  -1523, -4677 },
+    {  -3142,    -55,    253, -4914 },
+    {    356,  -1680,    343, -6123 },
+    {  -2241,  -1734,   -976, -5939 },
+    {  -2196,  -2893,    547, -4938 },
+    {  -1245,    126,  -1916, -5419 },
+    {   -249,  -3755,  -1422, -5594 },
+    {    575,  -2683,  -1926, -4566 },
+    {   -762,   1885,    192, -5880 },
+    {   -811,  -2562,  -1068, -6013 },
+    {  -2264,  -3086,   -976, -4775 },
+    {     70,  -1215,   2880, -4410 },
+    {    714,  -3760,   2916, -4691 },
+    {   -244,  -3404,   1740, -4493 },
+    {    684,  -5137,   -328, -5608 },
+    {   -529,  -3825,  -1786, -4535 },
+    {   -713,  -4743,  -1118, -5546 },
+    {   2718,  -3788,   1798, -5708 },
+    {  -1639,  -3679,  -1564, -6095 },
+    {   1693,  -2642,  -1389, -4539 },
+    {    505,  -1573,  -1651, -4878 },
+    {   -835,  -2256,  -1941, -5352 },
+    {   1464,   -411,   1993, -6441 },
+    {    493,  -3184,   -145, -6148 },
+    {  -1413,    499,  -1617, -6479 },
+    {   -294,   1722,  -1419, -5725 },
+    {  -2937,  -1528,   -175, -4624 },
+    {   -594,  -5911,    -56, -6146 },
+    {   -300,  -4275,   1156, -5947 },
+    {    552,  -2643,   2669, -3959 },
+    {    905,  -4158,   1789, -5809 },
+    {   1336,  -2009,   2108, -5903 },
+    {   1555,  -3600,   1110, -6759 },
+    {  -1294,  -3464,     77, -6084 },
+    {  -1139,  -4006,  -1270, -4181 },
+    {  -5094,  -3296,   1092, -2847 },
+    {  -5503,  -2883,   1984, -2067 },
+    {  -4671,  -4218,  -1417, -4132 },
+    {  -3763,  -3818,   1262, -3082 },
+    {  -5132,  -3430,   2928,  -728 },
+    {  -5957,  -2877,   1251, -2446 },
+    {  -4425,  -2319,   -212, -4276 },
+    {  -6201,  -1993,   1774, -2182 },
+    {  -5500,  -3836,   2201, -1396 },
+    {  -6934,  -2334,   2366, -1293 },
+    {  -6124,  -4140,   1337, -1977 },
+    {  -6553,  -4186,   1756, -1325 },
+    {  -5126,  -1258,    744, -3656 },
+    {  -5167,  -1390,   1581, -2895 },
+    {  -4525,  -3398,   2429, -1865 },
+    {  -4076,  -3183,   2027, -2510 },
+    {  -6191,  -3274,   1838, -1814 },
+    {  -4454,  -2753,   2723, -1185 },
+    {  -6655,  -4797,    251, -2595 },
+    {  -6332,  -2232,   1832,   217 },
+    {  -5869,  -1698,    134,   340 },
+    {  -6614,  -1045,   2126, -1932 },
+    {  -4859,  -2107,   2010, -2435 },
+    {  -6274,  -1622,   2808, -1374 },
+    {  -3119,  -3209,    521, -3988 },
+    {  -5676,  -2082,   -420, -2711 },
+    {  -7073,  -3623,    696, -2343 },
+    {  -5986,  -4224,    572, -2454 },
+    {  -4340,  -4521,    882, -2771 },
+    {  -6178,  -1933,    535, -1444 },
+    {  -4923,  -4163,   1744, -2066 },
+    {  -6410,  -1519,   1058, -2683 },
+    {  -5077,  -1185,    856, -2216 },
+    {  -7091,  -2444,    687, -2597 },
+    {  -5284,  -2165,   3239,  -993 },
+    {  -4763,  -1497,    197, -3179 },
+    {  -4128,  -4958,   -396, -3578 },
+    {  -5054,  -3878,   -647, -2672 },
+    {  -7005,  -3348,   1679, -1579 },
+    {  -5767,  -1017,   2582, -1915 },
+    {  -7069,  -2787,   1331, -2070 },
+    {  -5532,  -2296,    706, -2950 },
+    {  -5059,  -3543,   -821, -3637 },
+    {  -6639,  -1835,   1016,  -696 },
+    {  -5611,  -5220,   -694, -3371 },
+    {  -5994,  -2803,   2933,  -729 },
+    {  -5948,   -619,   1596, -2676 },
+    {  -5486,  -4419,    153, -3265 },
+    {  -4329,  -3440,   1646, -1439 },
+    {  -4083,  -3978,    177, -3569 },
+    {  -4289,  -2599,   1224, -3075 },
+    {  -5707,  -3253,   1912,  -759 },
+    {  -6606,  -3437,   2562,  -571 },
+    {  -5254,  -2444,    769,  -352 },
+    {  -6545,  -3154,    582, -1103 },
+    {  -5328,  -2241,   2566, -1775 },
+    {  -7216,  -1936,   1538, -1983 },
+    {  -3730,  -2451,    426, -3869 },
+    {  -5110,  -1385,   2031, -1169 },
+    {  -6470,  -2715,    269, -3123 },
+    {  -5806,  -2480,    -97, -3832 },
+    {  -3683,  -4916,   -490, -4330 },
+    {  -6341,  -2083,   -669,  -115 },
+    {  -4913,  -4079,   -837, -4673 },
+    {  -3274,  -2497,   2334, -2652 },
+    {  -1286,  -1731,   2550, -3756 },
+    {  -3375,   -877,    926, -3977 },
+    {  -2525,  -2079,   2879, -2625 },
+    {  -5308,   -504,   3111, -1607 },
+    {  -4904,    460,   4093, -1232 },
+    {  -1993,   1616,   4656, -1913 },
+    {  -3481,  -1176,   3119, -2236 },
+    {  -4132,  -1502,   2339, -2545 },
+    {  -2542,   1151,   3569, -2550 },
+    {  -4381,    430,   3147, -2082 },
+    {  -3888,    867,   3899, -1657 },
+    {  -2861,   1290,   4202, -1979 },
+    {  -3893,   -253,   2363, -2764 },
+    {  -1705,    688,   3827, -2923 },
+    {  -2223,   2312,   3700, -3148 },
+    {  -1986,   -720,   5021,  -795 },
+    {  -3177,    242,   1952, -3352 },
+    {  -1854,   1509,   2528, -3815 },
+    {  -3173,     97,   5019,  -706 },
+    {  -2689,   -145,   1375, -3915 },
+    {  -4838,   -385,   2488, -2427 },
+    {  -4557,   -355,   1603, -3060 },
+    {  -3522,   1832,   3292, -2674 },
+    {  -3769,    780,   2378, -2704 },
+    {  -4323,  -1932,   3414, -1169 },
+    {  -2740,   1158,   2729, -3273 },
+    {  -3647,    210,   1464, -2892 },
+    {  -2342,  -2097,   1513, -3727 },
+    {  -4422,  -1242,   3130, -1833 },
+    {  -1308,  -1039,   4290, -1875 },
+    {  -1754,  -2535,   3298, -2314 },
+    {  -4102,   -186,   4037, -1094 },
+    {  -1008,   1570,   3290,   171 },
+    {  -3322,  -2621,   2791, -1536 },
+    {  -2539,  -2597,   3442, -1672 },
+    {  -3411,  -2015,   3670, -1174 },
+    {  -2097,    730,   5581, -1399 },
+    {  -1510,    -74,   4820, -2004 },
+    {  -4086,   -868,   4425,  -771 },
+    {   -956,   -986,   3640, -2925 },
+    {  -2087,  -1250,   3464, -2458 },
+    {  -3308,  -2411,   1334, -3667 },
+    {  -2264,   -389,   4004, -1854 },
+    {   -680,    239,   4058, -3388 },
+    {  -1357,     30,   2993, -3658 },
+    {  -3601,   -552,   1177, -1136 },
+    {  -2641,    442,   4374, -1625 },
+    {  -2525,    770,   1640, -3895 },
+    {  -3172,   -891,   3893, -1608 },
+    {  -2996,     13,   3277, -2414 },
+    {   -899,   1055,   4470, -2501 },
+    {   -422,   -584,   3475, -3787 },
+    {  -1978,   -593,   2566, -3415 },
+    {  -3150,  -1280,   2362, -3047 },
+    {  -3592,    224,   1026, -3932 },
+    {  -4840,  -1189,   3633,  -879 },
+    {  -3952,  -2255,   2916, -1826 },
+    {  -1695,     28,   1810,  -349 },
+    {   -745,  -2484,   3308, -3293 },
+    {  -1016,   1563,   5365, -1823 },
+    {  -2172,  -1787,   4266, -1287 },
+    {  -1241,  -1951,   3982, -2413 },
+    {  -2009,  -2639,   2330, -3480 },
+    {   5105,  -1618,  -2588, -2015 },
+    {   6497,  -1523,  -3218,  -910 },
+    {   6526,  -2305,  -2029, -1790 },
+    {   5289,    -99,  -3436,  -400 },
+    {   5781,  -1623,  -1577, -2617 },
+    {   5259,   -670,  -3125, -1700 },
+    {   6343,  -1256,   -331, -3222 },
+    {   7967,   -678,  -2195, -1462 },
+    {   6119,   -695,  -2988, -1538 },
+    {   6108,    494,  -3359, -1548 },
+    {   5067,    969,  -2328, -2707 },
+    {   7595,   -435,  -1497, -2056 },
+    {   6929,   -719,  -2420, -1665 },
+    {   5190,    584,  -2982, -2103 },
+    {   6106,   -444,  -1411, -2739 },
+    {   5584,    289,  -1804, -2803 },
+    {   5276,    227,  -1180, -3361 },
+    {   7544,  -1525,  -1834, -1725 },
+    {   5986,  -1470,  -2606, -1701 },
+    {   5096,   -765,  -1712, -3006 },
+    {   5423,   -149,  -3933, -1157 },
+    {   7651,     26,  -2445, -1507 },
+    {   4745,   -464,  -1735, -2362 },
+    {   5352,  -1011,  -1094, -1999 },
+    {   6300,   -672,   -542, -1950 },
+    {   6675,  -1020,  -1318, -1059 },
+    {   7218,  -2036,   -603, -2462 },
+    {   7755,  -1514,  -2430, -1229 },
+    {   5041,    449,  -1056, -2405 },
+    {   6710,  -2277,  -1344, -2284 },
+    {   6824,  -1347,  -2254,   251 },
+    {   6068,  -1857,   -983, -1316 },
+    {   5603,  -2177,  -2730, -1477 },
+    {   5838,  -1059,  -3604,  -970 },
+    {   5076,   -789,   -335, -2413 },
+    {   6191,  -1634,  -2000, -2129 },
+    {   5092,  -1292,  -2543, -1034 },
+    {   5305,    435,  -1710, -1850 },
+    {   6140,    561,  -2176, -2380 },
+    {   6752,    348,  -2496, -1890 },
+    {   6405,    273,  -1098, -2778 },
+    {   6942,  -1340,   -496, -1381 },
+    {   5238,   -687,  -2454, -2349 },
+    {   6959,   -882,  -1833, -2061 },
+    {   6292,   -253,  -2125, -2199 },
+    {   5838,   -574,   -759, -3215 },
+    {   6954,  -1484,   -640, -2771 },
+    {   7498,  -1706,  -1210, -2154 },
+    {   6772,  -1003,  -1235, -2532 },
+    {   6014,    228,  -2154, -1108 },
+    {   6943,  -2178,  -2644, -1122 },
+    {   7262,   -763,  -3056, -1090 },
+    {   6273,  -1478,  -1072,   177 },
+    {   4734,    425,  -2912,   357 },
+    {   7129,    168,  -1537, -2327 },
+    {   7204,   -434,   -746, -2660 },
+    {   6879,     57,  -3087, -1310 },
+    {   4623,   -610,   -718, -3459 },
+    {   6565,   -543,  -1998,  -339 },
+    {   4752,   -277,  -2066, -1405 },
+    {   7435,  -1416,  -1904,  -505 },
+    {   4076,    150,  -1222, -3556 },
+    {   7082,    -28,  -1456, -1174 },
+    {   5941,   -446,  -1326, -1158 },
+    {   3870,  -1648,  -2474, -2589 },
+    {    858,     37,  -3387, -3721 },
+    {   3557,  -1503,  -1664, -3383 },
+    {   3336,  -1972,  -3079, -2216 },
+    {   3186,     60,  -4185,  -863 },
+    {   3456,   -773,  -3066, -2457 },
+    {   4131,   -913,  -2060, -2601 },
+    {   4431,   -691,  -4114,  -972 },
+    {   3461,   -334,  -3680, -1751 },
+    {   2006,   -459,  -2214, -3827 },
+    {   1322,     32,  -2816, -3203 },
+    {   4425,  -1897,  -2791, -1946 },
+    {   4504,     23,  -3421, -1909 },
+    {   3090,   -885,  -2366, -3264 },
+    {   3209,  -2363,  -3730,  -834 },
+    {   3312,  -1471,  -3641, -1579 },
+    {   4184,  -1669,  -3323, -1248 },
+    {   2190,   -931,  -3302, -2944 },
+    {   2947,   -229,  -4791, -1195 },
+    {   2020,  -1626,  -2700, -3125 },
+    {   2214,   -326,  -4352, -1683 },
+    {   3286,  -2619,  -2412, -2458 },
+    {   1000,  -2571,  -4129, -2158 },
+    {   2496,  -2627,  -3611, -1433 },
+    {   2043,  -2191,  -2167, -3827 },
+    {   2571,  -2544,  -1915, -3222 },
+    {   2022,  -1501,  -3856, -2165 },
+    {   2685,  -1180,  -1461, -4038 },
+    {   1610,  -2313,  -4391, -1173 },
+    {   2340,  -2490,  -4215,  -516 },
+    {   1742,  -2615,  -3632, -2146 },
+    {    523,  -1293,  -4246, -2442 },
+    {   3725,  -2723,  -3014, -1576 },
+    {   3554,  -1381,  -4200,  -824 },
+    {   1291,  -1594,  -4777, -1430 },
+    {   1452,    515,  -2960, -3830 },
+    {   4264,   -894,  -3305, -1826 },
+    {   2606,  -1452,  -4522,  -966 },
+    {   1196,   -830,  -4807, -1816 },
+    {   1054,   -775,  -2616, -4071 },
+    {   4206,    415,  -4344, -1132 },
+    {   3044,    491,  -4126, -1934 },
+    {    988,   -901,  -3353, -3443 },
+    {   1729,  -3063,  -2267, -3370 },
+    {   3915,    912,  -2989, -2387 },
+    {   3781,    300,  -2457, -3050 },
+    {   2712,    924,  -1350, -1206 },
+    {   4230,    405,  -2343,   665 },
+    {   1878,   -873,   -225,   -29 },
+    {   3510,     56,  -1334, -3420 },
+    {   2850,   1447,  -2651, -3150 },
+    {   1510,   -706,  -4125, -2483 },
+    {   3115,    793,  -1692, -3894 },
+    {   2667,    213,  -2973, -2786 },
+    {   1184,  -2384,  -3051, -3173 },
+    {   2139,    796,  -2079, -3697 },
+    {   1464,  -1483,  -3726, -2754 },
+    {   2407,  -1148,  -3915, -1569 },
+    {   2612,  -1779,  -3217, -2271 },
+    {   2406,  -2870,  -2937, -2496 },
+    {   2140,    126,  -3646, -2758 },
+    {   2952,  -1036,    268, -1423 },
+    {     93,  -1931,  -3841, -3535 },
+    {    389,  -2953,  -3383, -3343 },
+    {   8652,  -5511,  -1662,   565 },
+    {   7427,  -2791,  -2535,  -842 },
+    {   8541,  -4253,  -1407,  -988 },
+    {   8018,  -3203,  -2998,   105 },
+    {   7231,  -3926,   -958,  1308 },
+    {   7331,  -3690,   -363,  2586 },
+    {   6803,  -3646,  -2226,  -903 },
+    {   8163,  -2811,   -477, -2235 },
+    {   9356,  -3818,  -1685,  -684 },
+    {   8466,  -2854,   -302,  -698 },
+    {   8458,  -3224,    517,   279 },
+    {   8074,  -2619,  -1326,  2596 },
+    {   8779,  -2761,  -2527,  -441 },
+    {   6533,  -2887,   -899,  -696 },
+    {   7394,  -2305,  -1642,  -120 },
+    {   8281,  -3780,    -22,  1305 },
+    {   9158,  -4413,   -779,   901 },
+    {   9031,  -5240,  -1109,  1678 },
+    {   8717,  -3650,    410, -1075 },
+    {   7317,  -3197,   -818, -2264 },
+    {   7934,  -2385,  -1214, -1886 },
+    {   8256,  -4441,   -291,  -587 },
+    {   7358,  -3395,   1090,  -270 },
+    {   9446,  -4910,  -1343,  -473 },
+    {   8187,  -4726,   -808,  1166 },
+    {   7504,  -3845,    -47,   267 },
+    {   8029,  -2146,  -1283,  -383 },
+    {   7461,  -2705,   -853,   783 },
+    {   9367,  -3636,   -645,  -354 },
+    {   8955,  -3473,   -308, -1947 },
+    {   8676,  -2683,  -2099,  1485 },
+    {   7481,  -3003,   -871,  -444 },
+    {   8015,  -2839,  -1673,  1175 },
+    {   6947,  -4643,  -1527, -1047 },
+    {   7622,  -2575,   -137,  -960 },
+    {   9388,  -4279,   -707, -1322 },
+    {   8382,  -5259,  -1283,  -565 },
+    {   6856,  -4138,  -1030,   630 },
+    {   8659,  -2571,  -1124, -1666 },
+    {   8763,  -3807,   -537,  2543 },
+    {   8049,  -3578,  -2186,  -604 },
+    {   8272,  -2351,  -1985, -1214 },
+    {   6855,  -3796,  -1527, -1631 },
+    {   7178,  -2896,  -1600, -1756 },
+    {   7040,  -2888,    -89, -1586 },
+    {   6261,  -3403,   -264,   998 },
+    {   7756,  -4699,  -1543,  -834 },
+    {   7682,  -4622,   -758, -1721 },
+    {   8839,  -4232,  -2932,  1959 },
+    {   9363,  -4679,  -1956,    39 },
+    {   7883,  -3616,  -1414, -1432 },
+    {   8828,  -3188,  -1356, -1312 },
+    {   7746,  -3987,   -121, -2424 },
+    {   9262,  -3256,   -693,   818 },
+    {   7670,  -3420,   -148,  3504 },
+    {   7344,  -3183,    608,  1595 },
+    {   8976,  -4139,  -1848,  1304 },
+    {   6708,  -4131,     33,  -852 },
+    {   7840,  -4429,  -2275,    79 },
+    {   8980,  -3858,  -2838,   453 },
+    {   7815,  -4604,  -2563,   944 },
+    {   8372,  -4422,  -1783,  3071 },
+    {   8623,  -5128,  -1754,  2888 },
+    {   7462,  -3281,    889,   920 },
+    {   8416,    -59,  -1320, -1825 },
+    {   7928,  -1488,   -414, -2499 },
+    {   8110,   -977,  -1047, -2042 },
+    {   8278,   -687,  -1597, -1550 },
+    {   7988,   -174,   -977, -2106 },
+    {   8609,  -1547,  -1628, -1527 },
+    {   9000,  -1798,   -946, -1761 },
+    {   8954,   -872,  -1404, -1594 },
+    {   8939,    466,   -748, -1212 },
+    {   9549,   -329,   -177, -1360 },
+    {   9411,    -18,  -1126, -1568 },
+    {   8859,   -782,   -488, -1338 },
+    {   8955,   -218,    -43, -1209 },
+    {   9131,    -69,   -453, -1001 },
+    {   9069,  -1519,  -1091, -1199 },
+    {   9247,  -1309,   -566, -1146 },
+    {   8528,  -1617,   -287, -1313 },
+    {   7763,   -745,   -149, -2040 },
+    {   8294,   -343,    257, -2633 },
+    {  10149,   -893,   -552, -1649 },
+    {   9398,   -915,    218, -2042 },
+    {   9703,  -1194,   -675, -1592 },
+    {   9586,   -700,   -427, -1710 },
+    {   8930,    497,  -1445, -1218 },
+    {   9285,  -1323,   -163, -1552 },
+    {   8431,  -1289,   -985, -1404 },
+    {   8965,   -655,    653, -1483 },
+    {   9542,  -1001,   -951, -1128 },
+    {   9205,   -647,    -37,  -882 },
+    {   8603,    -56,    514, -1793 },
+    {   9300,    -12,  -1324,  -567 },
+    {   8773,    238,   -184, -1456 },
+    {   9941,  -1306,    -69, -1792 },
+    {   9360,    279,   -376, -1919 },
+    {   9180,   -285,     95, -2170 },
+    {   9922,   -501,   -970, -1570 },
+    {   8341,  -1493,   -856, -2092 },
+    {   8780,   -981,   -850, -1014 },
+    {   9721,   -548,  -1504, -1094 },
+    {   9973,  -1493,    482, -2105 },
+    {   8707,   -333,  -1027, -1087 },
+    {   9098,   -469,   -315, -1723 },
+    {   8879,  -1050,   -661, -2020 },
+    {   8857,    602,   -866, -1918 },
+    {   8945,  -1025,  -2154, -1071 },
+    {   8484,  -1930,   -468, -2179 },
+    {   9177,  -1903,   -224, -2112 },
+    {   8652,   -137,  -2097, -1214 },
+    {   9063,   -973,  -1405,  -772 },
+    {   9328,   -456,    662, -2469 },
+    {  10101,   -697,    127, -2113 },
+    {   9685,    811,  -2359, -1024 },
+    {   8586,    -94,   -460, -1982 },
+    {   7924,   -141,   -509, -2513 },
+    {   7773,   -669,   -107, -2835 },
+    {   8636,  -1064,    -46, -2409 },
+    {   9748,    596,  -1815, -1349 },
+    {   8924,    304,    547, -2614 },
+    {   9442,    746,  -1153, -1679 },
+    {   9454,   -278,   -529, -1976 },
+    {   8488,    561,    -32, -2160 },
+    {  10083,    -63,  -1544, -1364 },
+    {   9390,  -1278,    568, -1131 },
+    {   9740,    -49,  -2253,  -910 },
+    {   3636,  -2391,  -1115, -3614 },
+    {   6014,  -3204,  -1902, -1808 },
+    {   5787,  -3497,  -1116, -2590 },
+    {   4365,  -3046,  -1632, -2668 },
+    {   4733,  -2192,  -2029, -2468 },
+    {   5412,  -2753,  -1633, -2464 },
+    {   4455,  -3375,   -767, -3399 },
+    {   4456,  -1644,   -983, -2841 },
+    {   4039,  -2523,     38, -3967 },
+    {   3406,  -2662,     72, -4757 },
+    {   4279,  -2005,   1055, -4399 },
+    {   4321,  -1377,   -860, -3786 },
+    {   3743,  -5739,   -651, -3047 },
+    {   3528,  -5510,    361, -4060 },
+    {   6496,  -4886,   -136, -2689 },
+    {   4513,  -5254,    551, -4010 },
+    {   6557,  -3413,    -92, -3063 },
+    {   4186,  -2059,    187,    47 },
+    {   6210,  -4117,  -1256, -1985 },
+    {   6038,  -4343,    351, -2124 },
+    {   4305,  -4780,  -2077, -1897 },
+    {   4480,  -3815,  -2228, -1533 },
+    {   5582,  -3689,   1221, -3429 },
+    {   5532,  -4874,   1195, -2765 },
+    {   6518,  -2853,   -905, -2568 },
+    {   5467,  -2192,    470, -4115 },
+    {   4139,  -1577,    240, -3493 },
+    {   5281,  -1926,   -729, -3340 },
+    {   5214,  -2870,   1359, -4289 },
+    {   3046,  -3510,  -1536, -3214 },
+    {   5433,  -2881,  -1230, -1184 },
+    {   4861,  -3932,  -1071, -2791 },
+    {   5693,  -4234,  -1906, -1502 },
+    {   4004,  -3935,  -1804, -2383 },
+    {   3728,  -3792,    681, -4773 },
+    {   3621,  -3030,  -1951, -2598 },
+    {   5133,  -3903,     44, -3700 },
+    {   3561,  -3451,   1183, -5301 },
+    {   5026,  -2762,  -2341, -1780 },
+    {   5841,  -2492,   -467, -3210 },
+    {   5591,  -1791,    497, -2472 },
+    {   5054,  -3898,  -1822, -2097 },
+    {   5813,  -2792,     83, -1469 },
+    {   4432,  -4497,   1670, -5193 },
+    {   5338,  -4653,  -1109, -2200 },
+    {   3239,  -4401,   -648, -3655 },
+    {   2147,  -3598,  -1200, -4242 },
+    {   4417,  -2271,  -1552, -3210 },
+    {   6494,  -4360,    852, -3565 },
+    {   2393,  -6358,   -856, -4524 },
+    {   4959,  -4196,   -847, -1403 },
+    {   4924,  -5438,   -226, -3026 },
+    {   4254,  -5303,  -1306, -2424 },
+    {   4121,  -3126,  -2334, -1981 },
+    {   3437,  -4443,  -1464, -2953 },
+    {   3203,  -3459,   -529, -4339 },
+    {   5896,  -5945,    543, -3246 },
+    {   1987,  -4733,   -220, -4863 },
+    {   4358,  -4431,   -514, -3081 },
+    {   4583,  -2416,   -492, -2287 },
+    {   2943,  -5035,    419, -4927 },
+    {   5358,  -5129,    987, -4309 },
+    {   4460,  -3392,   1752, -5634 },
+    {   3415,  -4633,   1507, -5945 },
+    {    811,  -4692,   -445,  2333 },
+    {   1009,  -5613,  -1857,  1360 },
+    {   1338,  -2712,  -2720,  3036 },
+    {   1002,  -3754,  -2582,  2344 },
+    {    750,  -4608,  -2334,   714 },
+    {   2043,  -3207,  -2822,  2173 },
+    {   -140,  -4654,  -2953,   357 },
+    {    -54,  -4026,  -2376,  2695 },
+    {   1858,  -5022,   -717,  2287 },
+    {   2064,  -3894,   -722,  3255 },
+    {   2727,  -4558,   -332,  2603 },
+    {   1810,  -5378,    283,  1826 },
+    {   3935,  -4326,    762,  3383 },
+    {   -767,  -4697,  -2510,  1922 },
+    {   2146,  -4312,  -3090,  1641 },
+    {     54,  -5881,  -2114,   921 },
+    {   1992,  -5766,   -640,  1574 },
+    {   1200,  -5371,  -1114,  1828 },
+    {   2973,  -5337,     34,  2266 },
+    {   1531,  -5018,  -2817,  1192 },
+    {   3078,  -4570,    117,  1990 },
+    {    924,  -4286,  -1388,  2713 },
+    {    142,  -5058,  -2848,  1487 },
+    {   -106,  -6180,   -881,   842 },
+    {    673,  -5433,   -229,  1596 },
+    {    783,  -5710,  -2784,   562 },
+    {   1935,  -5729,  -2009,   856 },
+    {   -410,  -3375,  -3326,  2734 },
+    {    234,  -3000,  -2628,  3260 },
+    {    733,  -3405,  -3806,  1589 },
+    {    771,  -4285,  -3544,  1314 },
+    {   1192,  -3563,  -3960,  2178 },
+    {    206,  -5555,  -1250,  1546 },
+    {   -130,  -3815,  -1210,  3041 },
+    {    646,  -3940,   -393,  2992 },
+    {   -184,  -4931,  -1767,  1925 },
+    {   2746,  -5120,  -2275,  1464 },
+    {   2440,  -3731,  -3352,  2729 },
+    {   -490,  -4942,  -3779,   997 },
+    {     68,  -2636,  -4167,  3778 },
+    {     48,  -3986,  -4118,  2106 },
+    {   -978,  -5486,  -1336,  1390 },
+    {   1126,  -5297,   -855,   640 },
+    {   -472,  -3975,  -3622,  1557 },
+    {   2456,  -5344,  -1523,  1648 },
+    {   -774,  -5652,  -2417,  1147 },
+    {    995,  -6122,   -812,  1132 },
+    {   3282,  -4571,  -1763,  2175 },
+    {   3655,  -3862,   -676,  3568 },
+    {   3038,  -3647,  -1672,  3381 },
+    {   2595,  -2964,  -2772,  3263 },
+    {   4176,  -3353,  -1148,  4354 },
+    {   1603,  -3442,  -1500,  3444 },
+    {    828,  -6226,  -1783,   678 },
+    {   1421,  -3333,  -3080,  3403 },
+    {   1121,  -4727,  -1924,  1984 },
+    {   -186,  -5083,   -682,  1796 },
+    {    819,  -2778,  -3488,   530 },
+    {    421,  -2873,  -3832,  2596 },
+    {   2164,  -4263,  -1605,  2282 },
+    {    585,  -4437,   -682,  -491 },
+    {   -644,  -4452,  -1157,  2325 },
+    {   1991,  -4299,    210,  2834 },
+    {   2135,  -3632,  -2113,   665 },
+    {  -7482,  -2724,  -2662, -1380 },
+    {  -6983,  -2166,  -3756, -3509 },
+    {  -7085,  -1439,  -2397, -3112 },
+    {  -7760,  -3049,  -3319, -2822 },
+    {  -8413,  -2760,  -4406, -3298 },
+    {  -5995,  -3943,  -1260, -3750 },
+    {  -7879,  -1554,  -3464, -2606 },
+    {  -6314,  -2034,  -3878, -1681 },
+    {  -8849,  -2084,  -1399, -1231 },
+    {  -7153,  -2602,  -1384,  -817 },
+    {  -8041,  -2571,   -407, -2785 },
+    {  -7246,  -2233,  -1578,   260 },
+    {  -7336,  -3883,  -4061, -1342 },
+    {  -7619,  -3908,  -2342,   382 },
+    {  -8684,  -3724,  -1662,  -727 },
+    {  -7850,  -2922,  -1770, -3449 },
+    {  -6766,  -2034,  -1293, -1988 },
+    {  -6895,  -2116,   -968, -3744 },
+    {  -7136,  -5147,  -2618, -2809 },
+    {  -8224,  -3724,  -2519, -1589 },
+    {  -6711,  -2750,  -3021,  -219 },
+    {  -8059,  -1638,  -1102, -3175 },
+    {  -8710,  -4839,  -3963, -3143 },
+    {  -9363,  -4965,  -3257, -1002 },
+    {  -6099,  -1751,  -3157,  -395 },
+    {  -6453,  -3216,  -4597,  -483 },
+    {  -7879,  -5477,   -839, -2638 },
+    {  -7202,  -4038,   -526, -2856 },
+    {  -8022,  -1228,  -1910, -1646 },
+    {  -9117,  -1393,  -1582, -2535 },
+    {  -9095,  -2693,   -636, -2605 },
+    {  -9076,  -2580,  -3481, -2519 },
+    {  -8327,  -4859,  -2422,    83 },
+    {  -8368,  -2129,  -2324, -2173 },
+    {  -8554,  -4563,  -3842, -2007 },
+    { -10462,  -4261,  -1934, -2084 },
+    {  -9717,  -3187,  -2294, -1896 },
+    {  -9625,  -3889,  -3020, -3224 },
+    {  -9857,  -4955,  -4239, -2184 },
+    {  -9752,  -2351,  -2277, -3129 },
+    {  -7219,  -1302,  -2639, -1603 },
+    {  -7477,  -4360,  -3718,  -559 },
+    {  -5680,  -2033,  -2326, -3078 },
+    { -10190,  -5548,  -4643, -3601 },
+    {  -9431,  -4121,   -879, -2479 },
+    {  -8365,  -5450,  -2020, -1439 },
+    {  -6289,  -5178,  -1605, -3845 },
+    {  -8319,  -3866,   -687, -2792 },
+    {  -8131,  -1031,  -3608, -3947 },
+    { -10510,  -2560,  -1199, -2082 },
+    { -11015,  -3640,  -2748, -3041 },
+    {  -8762,  -5022,  -5231, -1162 },
+    { -10153,  -2715,  -4648, -4859 },
+    {  -7930,  -5205,  -1900, -3600 },
+    {  -9561,  -3548,  -4812, -3722 },
+    {  -7663,  -4709,  -1180, -1475 },
+    {  -9073,  -5707,  -1815, -2980 },
+    {  -8602,  -2363,  -2675, -3770 },
+    {  -9967,  -5614,  -3575, -3838 },
+    {  -8324,  -1005,  -2131, -3254 },
+    { -10331,  -5737,  -2550, -2940 },
+    {  -8234,  -3354,  -3361, -4479 },
+    {  -8140,  -1951,  -4526, -4545 },
+    {  -6679,  -2662,  -2284, -4182 },
+    {  -1122,  -1514,  -6427,  -212 },
+    {     54,  -1660,  -5424, -1404 },
+    {    254,  -2778,  -5222,   846 },
+    {   -267,  -1661,  -6577,   814 },
+    {   -305,  -2021,  -5759,  1484 },
+    {  -1791,  -2446,  -6867,   -86 },
+    {  -2929,  -3158,  -6603, -1799 },
+    {  -1391,  -3189,  -5557, -1053 },
+    {  -1602,   -884,  -6767, -1213 },
+    {   -361,   -318,  -6219,   -44 },
+    {  -4078,  -2635,  -5523,  -433 },
+    {   -956,    478,  -4382,  1470 },
+    {  -3300,  -2462,  -6021, -2721 },
+    {    708,  -2434,  -5085,  -540 },
+    {  -2435,  -3607,  -5647, -2110 },
+    {   -491,  -1134,  -4681, -2886 },
+    {     87,  -3435,  -4641, -1194 },
+    {   -586,  -2927,  -4784,   366 },
+    {  -1394,  -2326,  -6021,   350 },
+    {     97,  -2519,  -4678, -2120 },
+    {  -1547,  -1907,  -5069, -2993 },
+    {    268,  -3724,  -4719,   127 },
+    {   -827,  -1190,  -5912,  1144 },
+    {  -3959,  -2322,  -6898, -1974 },
+    {  -2728,  -2228,  -6426,  -562 },
+    {   -456,   -666,  -5785, -1609 },
+    {    531,  -1096,  -5731,  -656 },
+    {  -3569,   -688,  -3915,   110 },
+    {  -4752,  -1725,  -4393,  -377 },
+    {  -3210,  -3315,  -6960,  -840 },
+    {   -688,  -3416,  -4971,  1221 },
+    {  -1833,     77,  -6491, -2434 },
+    {   -239,   -255,  -6850,  -886 },
+    {  -2112,  -1490,  -6291, -2689 },
+    {  -1544,  -4579,  -5198, -1261 },
+    {  -2771,  -4014,  -5520,   683 },
+    {  -1635,  -2829,  -5512,  1214 },
+    {   -958,  -2582,  -4823,  2360 },
+    {  -2077,  -4566,  -4642,   365 },
+    {  -3112,  -4214,  -5960,  -823 },
+    {  -2467,  -2510,  -4858,  1467 },
+    {  -1561,  -3399,  -5822,   211 },
+    {   -775,  -1081,  -4424,  2636 },
+    {  -1263,     25,  -6378, -1392 },
+    {  -3476,   -366,  -5417, -1393 },
+    {  -3176,  -1476,  -4149,  1466 },
+    {  -2479,    518,  -4448,  -257 },
+    {  -2992,    158,  -4660, -1279 },
+    {  -1320,  -3872,  -4479,  1147 },
+    {  -1475,   -312,  -5318,   539 },
+    {  -3527,  -1679,  -5860, -1681 },
+    {  -3397,  -3438,  -5593,  1866 },
+    {  -4089,  -2439,  -4763,  1275 },
+    {   -748,  -4513,  -4687,   -48 },
+    {  -2166,  -4531,  -4691, -2856 },
+    {  -2385,   -853,  -6035,  -627 },
+    {  -1194,  -4091,  -4472, -1963 },
+    {   -682,  -3234,  -4084, -3033 },
+    {  -3255,  -5015,  -5328,   -12 },
+    {  -2313,  -3436,  -4601,  -155 },
+    {  -2792,  -1038,  -6947, -2019 },
+    {  -1244,  -1526,  -5771, -1882 },
+    {  -4679,  -3731,  -5506,   283 },
+    {  -3062,    -66,  -3558,  -758 },
+    {  -4895,  -1187,   4751,  3728 },
+    {  -7600,  -2752,   3320,  4613 },
+    {  -5703,  -2975,   3944,  2659 },
+    {  -4972,  -1257,   -246,  2952 },
+    {  -4221,  -2487,   1702,  4295 },
+    {  -2900,  -1529,   2458,  4935 },
+    {  -5061,    407,   2416,  4050 },
+    {  -6931,  -3478,   2761,  2213 },
+    {  -6037,  -3921,   3192,  1866 },
+    {  -6113,   -811,   2407,  3782 },
+    {  -5878,  -1716,   1207,  3478 },
+    {  -5953,  -2853,   2207,  2712 },
+    {  -6807,  -3223,   2749,  3595 },
+    {  -3272,  -3157,   1389,  3788 },
+    {  -5368,  -1904,   1980,  5077 },
+    {  -7235,  -1398,   3075,  4548 },
+    {  -4765,  -3487,   2755,  2796 },
+    {  -7658,  -4435,   2694,  2582 },
+    {  -6997,  -4282,    456,  3832 },
+    {  -5563,  -3115,    -63,  3713 },
+    {  -4244,  -4220,   1450,  2767 },
+    {  -3801,  -2194,    190,  4303 },
+    {  -5458,  -4119,   1958,  2274 },
+    {  -7300,  -3469,   3514,  3193 },
+    {  -4594,  -2067,    775,  4752 },
+    {  -3389,  -1654,   1464,  5412 },
+    {  -4845,  -3483,    964,  3437 },
+    {  -6007,  -2818,   1666,  4659 },
+    {  -8709,  -5007,   1757,  3287 },
+    {  -5833,  -4389,   1025,  3171 },
+    {  -5788,  -1780,   3944,  3661 },
+    {  -4430,   -920,   1938,  4753 },
+    {  -7066,  -1857,   4591,  4538 },
+    {  -3549,   -513,   1427,  5317 },
+    {  -7517,  -1220,   2883,  3049 },
+    {  -7605,  -2687,   1874,  2735 },
+    {  -8718,  -4035,   2676,  3730 },
+    {  -7990,  -3907,   1185,  2607 },
+    {  -6058,  -1744,   3349,  5157 },
+    {  -5954,    565,   3161,  3250 },
+    {  -6478,   -612,   1930,  2271 },
+    {  -6535,  -1445,     -2,  1618 },
+    {  -8963,  -4151,   1192,  4044 },
+    {  -7227,  -3570,   1600,  4234 },
+    {  -4674,     79,    595,  3015 },
+    {  -3974,    430,   2727,  5137 },
+    {  -5299,      9,   3714,  4779 },
+    {  -6779,  -2699,     -8,  2436 },
+    {  -7016,  -1145,   1293,  2310 },
+    {  -6955,  -3312,   1534,  1801 },
+    {  -4025,    740,   1850,  4054 },
+    {  -9589,  -3460,   4154,  5270 },
+    {  -4404,  -1181,   4298,  5173 },
+    {  -7356,  -4583,    -18,  2644 },
+    {  -6516,  -1235,   4439,  6234 },
+    {  -3453,   -301,   4344,  4464 },
+    {  -4643,   1530,   3315,  4340 },
+    {  -4575,  -2557,   3754,  3682 },
+    {  -3643,  -3501,   2051,  2997 },
+    {  -5412,  -2475,   2301,  1579 },
+    {  -5846,    259,   1360,  2348 },
+    {  -5258,  -1358,   1050,   838 },
+    {  -5542,   -219,   6377,  5750 },
+    {  -5713,  -2952,    922,   899 },
+    {  -2049,  -1135,   5206,  1033 },
+    {  -1693,  -1886,   4835,  -106 },
+    {  -2344,  -3504,   4232,   -13 },
+    {  -2475,  -2334,   5043,  1126 },
+    {   -787,  -2549,   3880,  2138 },
+    {  -3159,  -2341,   4830,  2887 },
+    {  -1780,  -1009,   6240,  2061 },
+    {  -4327,  -3363,   2818,   886 },
+    {  -3376,  -2743,   4104,   207 },
+    {  -3250,  -4640,   2718,  1498 },
+    {   -382,  -1075,   4382,  3460 },
+    {  -2416,  -4168,   3530,   816 },
+    {  -1756,  -2708,   4861,   622 },
+    {  -1879,  -2097,   5156,  2889 },
+    {  -2496,  -2418,   3722,  2671 },
+    {  -2717,  -3252,   3341,  1944 },
+    {  -4063,  -4091,   3306,   267 },
+    {  -3549,  -3808,   3747,   842 },
+    {  -2635,    546,   5794,  1894 },
+    {  -1857,  -1121,   4383,  3964 },
+    {  -2226,  -2166,   3489,  3678 },
+    {  -3492,   -660,   5323,  1063 },
+    {  -3033,  -3130,   4382,  1828 },
+    {  -2703,   -625,   6369,  2851 },
+    {  -1656,  -2842,   4584,  -528 },
+    {  -4781,  -2622,   4390,  2097 },
+    {   -413,  -2045,   5081,  3035 },
+    {  -3810,  -2662,   4532,  1095 },
+    {  -3144,  -1858,   5215,  1880 },
+    {  -3562,  -1795,   4928,   670 },
+    {  -4800,  -1509,   5189,  1859 },
+    {  -1085,  -3832,   4169,   900 },
+    {  -1969,  -3270,   2857,  2878 },
+    {  -4267,  -4140,   3176,  1805 },
+    {  -5145,  -3727,   3524,  1168 },
+    {  -1346,  -1876,   5501,  1748 },
+    {  -4998,  -2945,   3699,   338 },
+    {  -3458,  -3096,   3406,  -635 },
+    {  -1751,  -3209,   3508,   395 },
+    {  -2507,    170,   5987,   705 },
+    {  -3756,  -1072,   5647,  3536 },
+    {  -2870,  -1439,   5026,  3212 },
+    {  -3913,  -3225,   3669,  2144 },
+    {  -3739,    226,   5747,   764 },
+    {  -2052,   -820,   5266,  3093 },
+    {  -3214,  -3820,   2409,  2391 },
+    {  -4398,  -2588,   3501,  -218 },
+    {  -4484,  -1763,   4180,  -198 },
+    {  -3368,  -1525,   4362,  -134 },
+    {  -2407,    224,   4905,  3533 },
+    {  -1369,  -2937,   4728,  1788 },
+    {  -4848,  -1707,   4159,   851 },
+    {  -3454,  -1749,   4281,  3230 },
+    {  -1990,  -3853,   3487,  1735 },
+    {  -3117,     92,   6155,  4075 },
+    {  -2676,  -2472,   4078,  -589 },
+    {  -1547,  -2012,   2626,  1835 },
+    {  -4275,   -588,   4824,   725 },
+    {   -601,  -2249,   3736,  3548 },
+    {  -4060,    -61,   5333,  3097 },
+    {  -4303,      7,   6551,  3054 },
+    {  -5003,  -1029,   5786,  3319 },
+    {  -2810,   -728,   5392,   199 },
+    {  -1232,   -200,   5228,  3121 },
+    {   2621,    165,  -6255,   298 },
+    {   3669,    537,  -6844,  1564 },
+    {   1598,  -1190,  -6235,  2523 },
+    {   2164,    -32,  -6894,  1383 },
+    {    853,  -1597,  -6069,  1449 },
+    {   1377,  -1661,  -5266,   108 },
+    {   2660,     48,  -5172,  -517 },
+    {   1903,   -391,  -5677,  1010 },
+    {   3792,    206,  -5274,   -11 },
+    {   1239,   2776,  -2929,  2721 },
+    {   4071,    149,  -7259,  3125 },
+    {   1436,   -480,  -6156,  -196 },
+    {   1373,  -1960,  -5005,  3122 },
+    {   3413,  -1271,  -5176,  3283 },
+    {   3060,    -68,  -6495,  2238 },
+    {   2700,  -2075,  -4681,    91 },
+    {   2928,  -1728,  -5168,  1858 },
+    {   4424,    828,  -4471,    88 },
+    {   2672,  -2604,  -4038,  2753 },
+    {   5223,   -123,  -6749,  2295 },
+    {   4237,   -420,  -5538,  1353 },
+    {   4744,  -1281,  -4097,  4708 },
+    {   1103,  -2764,  -4751,  2024 },
+    {   3747,  -1913,  -3911,  3960 },
+    {   2470,  -1416,  -5542,   615 },
+    {   4847,  -1354,  -5334,  1733 },
+    {   5336,     88,  -7593,  4007 },
+    {   2388,  -2880,  -4807,  1037 },
+    {   4495,   1391,  -5685,  -139 },
+    {   5253,   1637,  -6450,  1533 },
+    {   1199,    795,  -5515,  1261 },
+    {   1397,  -1259,  -4252,  3838 },
+    {    746,     70,  -6640,   604 },
+    {   1584,    166,  -4972,  3072 },
+    {    380,   -999,  -5397,  2267 },
+    {   2974,   1707,  -3242,  5360 },
+    {   5202,   -403,  -5453,  2832 },
+    {   3718,  -1731,  -4760,   714 },
+    {   4150,   -975,  -4792,    61 },
+    {   2925,   -818,  -4841,    15 },
+    {   5301,    577,  -4006,  3259 },
+    {   5265,   1986,  -5679,  3028 },
+    {   3752,   1928,  -4509,  3729 },
+    {   3278,   1925,  -6370,  1247 },
+    {   5107,   1721,  -4853,  3127 },
+    {   3279,   2982,  -2515,  4005 },
+    {   4622,    668,  -6204,   759 },
+    {   6034,    317,  -5763,  4818 },
+    {   -558,     57,  -3785,  2817 },
+    {   4476,   1616,  -3965,  4536 },
+    {   5953,   2056,  -8215,  2715 },
+    {   4387,   2613,  -7463,   868 },
+    {   5834,   1088,  -4736,  4924 },
+    {   6473,   -856,  -6991,  4172 },
+    {   4959,   -293,  -5162,    76 },
+    {   2731,   -843,  -6119,  3847 },
+    {   3245,   1202,  -6833,   616 },
+    {   2553,   1383,  -3829,  3859 },
+    {   4332,   2099,  -3480,  3622 },
+    {   2110,   2683,  -2728,  3990 },
+    {    876,   1167,  -3290,  3466 },
+    {   3991,   1709,  -2410,  4077 },
+    {   5105,    939,  -2584,  3256 },
+    {   4719,    688,  -1566,  3040 },
+    {  -3632,   4335,   1266, -3303 },
+    {  -4956,   3207,   1312, -2806 },
+    {  -4669,   2627,   2663, -2435 },
+    {  -4282,   3708,   2303, -3038 },
+    {  -4536,   2297,   -175, -3350 },
+    {  -5234,   2503,   -139,  -880 },
+    {  -3978,   1512,   1092, -3619 },
+    {  -4519,   4649,   1363, -2455 },
+    {  -5118,   3132,   1961, -1577 },
+    {  -5196,   3379,   -182, -1378 },
+    {  -6420,   4486,   2397, -1993 },
+    {  -5030,   5046,   1292, -1118 },
+    {  -4559,   2573,   -927, -1406 },
+    {  -3501,   3730,    691, -4930 },
+    {  -4364,   2758,   1007, -3909 },
+    {  -4026,   2839,  -1559, -2340 },
+    {  -5037,   4053,    836, -1571 },
+    {  -4727,   5136,   1110, -3588 },
+    {  -5245,   2799,   -999, -2164 },
+    {  -4954,   1501,    422, -3963 },
+    {  -5994,   2726,   1462, -2833 },
+    {  -5621,   5159,   2038, -2512 },
+    {  -4991,   2291,   1917, -3151 },
+    {  -5469,   4382,   -148, -2978 },
+    {  -5858,   1983,    807, -2720 },
+    {  -4709,   3556,    952,  -467 },
+    {  -2489,   2362,   1714, -4230 },
+    {  -4717,   5004,  -1180, -3672 },
+    {  -5914,   3653,   1359, -1317 },
+    {  -5506,   2995,    780, -1059 },
+    {  -5287,   3945,   2480, -2293 },
+    {  -3849,   4358,    322, -1770 },
+    {  -3911,   3570,    252, -3185 },
+    {  -3660,   5128,    158, -3719 },
+    {  -4599,   3277,   -503, -2727 },
+    {  -3673,   3760,  -1252, -3339 },
+    {  -5161,   2337,    388, -1943 },
+    {  -3529,   2216,   2156, -3080 },
+    {  -4309,   4331,   1808, -1460 },
+    {  -4782,   3820,    480, -2504 },
+    {  -4166,   3544,   -378, -1567 },
+    {  -5572,   2466,   -418, -2909 },
+    {  -6096,   2930,    119, -1878 },
+    {  -5963,   3554,   1011, -2233 },
+    {  -6433,   4335,    935, -2930 },
+    {  -5004,   3314,  -1352, -3430 },
+    {  -6042,   3463,  -1008, -3940 },
+    {  -4671,   2214,   -640, -5040 },
+    {  -2795,   3759,   1412, -3803 },
+    {  -3647,   4436,    729,  -515 },
+    {  -3594,   1033,     56, -4148 },
+    {  -2908,   3027,   2889, -3485 },
+    {  -3338,   2234,    313, -4285 },
+    {  -3825,   4497,   -561, -2634 },
+    {  -6167,   3012,    -48, -3149 },
+    {  -4828,   3515,   -969, -4475 },
+    {  -5789,   2757,   -539, -4173 },
+    {  -2452,   3067,    564, -4249 },
+    {  -4921,   1358,   1331, -2889 },
+    {  -3127,   4239,  -1045, -1523 },
+    {  -4780,   2326,  -1118, -3446 },
+    {  -3908,   5546,    152, -2622 },
+    {  -6972,   2976,    337, -2809 },
+    {  -4839,   4613,    -35, -4077 },
+    {  -1408,   4822,  -1149, -4997 },
+    {   -981,   4979,   -912, -6304 },
+    {  -2098,   5689,   -888, -2878 },
+    {  -3343,   4814,   -657, -4434 },
+    {  -2461,   3601,   -967, -4869 },
+    {  -2652,   3944,     87, -5520 },
+    {  -1104,   6076,    174, -6407 },
+    {    355,   5370,  -1721, -5869 },
+    {   1242,   4497,  -1107, -5091 },
+    {    -89,   4002,  -1491, -5182 },
+    {   1059,   5693,  -1591, -4905 },
+    {   1323,   4682,  -2078, -4768 },
+    {    818,   3996,   -549, -5468 },
+    {   -287,   4529,    929, -5543 },
+    {   -919,   5519,  -2791, -2844 },
+    {  -1407,   5679,  -3289, -3974 },
+    {   -189,   6530,  -3547, -4002 },
+    {   -900,   7039,  -3371, -4855 },
+    {  -2983,   7211,   -363, -4835 },
+    {   -814,   6503,   -104, -5106 },
+    {  -2386,   6896,    809, -4919 },
+    {    845,   4492,    352, -6621 },
+    {  -1998,   7237,  -1646, -4231 },
+    {  -3380,   6251,    471, -4577 },
+    {  -1908,   7059,     84, -5726 },
+    {   -340,   6346,   -803, -6265 },
+    {  -2279,   5834,    -47, -4633 },
+    {  -1532,   5286,  -1748, -1901 },
+    {  -2757,   6188,   -453, -3415 },
+    {  -1255,   6405,  -2043, -6357 },
+    {    918,   5581,   -121, -5667 },
+    {   1840,   5336,   -821, -5034 },
+    {  -2475,   4992,  -1825, -3104 },
+    {  -2413,   5606,  -1789, -4298 },
+    {    132,   5128,  -2389, -4442 },
+    {    223,   6400,  -2653, -4742 },
+    {   -673,   5012,    680, -4582 },
+    {  -1657,   6624,   -349, -3596 },
+    {   -755,   6289,  -1860, -3978 },
+    {   -572,   6894,  -1946, -5207 },
+    {  -1141,   4756,  -2665, -5586 },
+    {  -1073,   4269,   -431, -4030 },
+    {    186,   5761,    916, -5868 },
+    {  -1907,   4836,   1017, -5106 },
+    {   -963,   3363,  -1248, -6348 },
+    {  -3262,   4774,  -1818, -5858 },
+    {    847,   3812,  -2538, -4302 },
+    {  -1223,   5903,   1360, -5479 },
+    {  -1094,   6923,  -1244, -2381 },
+    {    267,   6276,   -709, -2846 },
+    {   -157,   5840,   1124, -4266 },
+    {    889,   3206,   -910, -5305 },
+    {  -1736,   3344,    582, -4838 },
+    {  -2357,   5676,  -2695, -6277 },
+    {  -1916,   6901,   -986, -5397 },
+    {  -3062,   6028,   -695, -5687 },
+    {   1836,   3566,  -1357, -5226 },
+    {  -2176,   4938,    646, -3872 },
+    {  -2199,   3055,   -208, -6124 },
+    {   -236,   3032,   -821, -5325 },
+    {  -3989,   7277,   -565, -3899 },
+    {   -595,   4362,     74, -5975 },
+    {    684,   5874,   -841, -4424 },
+    {  -2731,   6305,  -2389, -5465 },
+    {  -5775,   1325,    -56, -2528 },
+    {  -7029,   -534,  -1890, -3278 },
+    {  -5798,    -15,  -2734, -2210 },
+    {  -5504,  -1198,   -353, -3659 },
+    {  -5079,    960,   -894, -4336 },
+    {  -6073,    -36,   -133, -3014 },
+    {  -5782,   -259,  -1025, -3986 },
+    {  -6843,   1262,   -807, -1639 },
+    {  -5263,   -918,  -3290,  -579 },
+    {  -4840,    461,  -2158,  -533 },
+    {  -6014,    -50,   -620,   504 },
+    {  -5843,    241,  -1359,  -282 },
+    {  -5898,    577,    769, -3271 },
+    {  -6833,   -946,   -466, -3347 },
+    {  -6026,   1459,   -512,  -729 },
+    {  -7361,    747,   -388, -1110 },
+    {  -6391,   2142,  -1160, -2513 },
+    {  -6995,    304,    498, -2673 },
+    {  -6757,    679,   -386,  -433 },
+    {  -5222,   1688,  -1093, -1032 },
+    {  -5019,    575,    184, -3627 },
+    {  -4237,    628,  -3507, -1243 },
+    {  -7479,   -456,  -1722, -1486 },
+    {  -6464,    713,  -1273, -1153 },
+    {  -6255,   1682,   -606, -3607 },
+    {  -7033,   1497,    -71, -1955 },
+    {  -6694,   1556,  -1721, -3214 },
+    {  -6114,   -356,    813, -2575 },
+    {  -5308,    632,  -1851, -1636 },
+    {  -5742,   -911,  -1733,   383 },
+    {  -6083,   -387,  -2313,  -879 },
+    {  -6535,   -530,  -1505, -2083 },
+    {  -4896,   1223,  -2750, -1816 },
+    {  -6392,   -463,  -3247, -2093 },
+    {  -5373,   1264,  -2706, -3042 },
+    {  -3894,  -1390,  -1020,  -891 },
+    {  -6179,   1168,  -1966, -1922 },
+    {  -5162,   1668,  -1617, -1916 },
+    {  -6453,    920,  -1169, -2432 },
+    {  -6130,   2005,   -536, -1519 },
+    {  -6552,    -98,   -518, -1938 },
+    {  -7528,    355,  -1101, -1772 },
+    {  -5745,    610,   -247, -1360 },
+    {  -7003,    177,  -2064, -1958 },
+    {  -6956,   -570,  -2220, -4225 },
+    {  -7830,    791,  -1394, -2774 },
+    {  -7634,    480,  -3171, -4224 },
+    {  -7913,   1154,   -350, -2381 },
+    {  -5063,   1704,  -1804, -2977 },
+    {  -4887,   -524,  -2703,   188 },
+    {  -5551,    406,  -1620, -3063 },
+    {  -7109,   1342,    381, -3021 },
+    {  -6846,    631,   -458, -3398 },
+    {  -4606,   -605,     11, -3930 },
+    {  -8134,   -225,  -1738, -2648 },
+    {  -7043,    402,  -2734, -3059 },
+    {  -7417,   1825,  -2545, -4389 },
+    {  -6971,   -236,  -1031,  -665 },
+    {  -5752,   2111,  -1632, -3808 },
+    {  -7660,    -78,   -624, -3135 },
+    {  -6358,    619,  -1951, -3911 },
+    {  -8134,    408,  -1935, -3695 },
+    {  -6335,   1911,  -2368, -4505 },
+    {  -7116,   2163,   -344, -2753 },
+    {   2357,   4488,   2220, -5682 },
+    {   1385,   3206,   2300, -5305 },
+    {   1419,   2557,   5203, -3516 },
+    {    262,   4315,   3920, -1847 },
+    {   3316,   3187,   1612, -5609 },
+    {   1729,   2350,   1673, -6068 },
+    {   1603,   6126,   1467, -2839 },
+    {  -1339,   3316,   3691, -3530 },
+    {   -563,   4618,   3180, -4548 },
+    {    463,   4624,   3111, -5614 },
+    {   1246,   5455,   3356, -5720 },
+    {    480,   2149,   5422, -2893 },
+    {   1768,   4827,    913, -5579 },
+    {   -149,   5381,   4366, -3297 },
+    {    985,   3672,   2644,   -92 },
+    {   -258,   2911,   5817, -2213 },
+    {   3428,   3289,   3351, -3541 },
+    {   -666,   3295,   4727, -2869 },
+    {     35,   6641,   4160, -4052 },
+    {    623,   6787,   3156, -4560 },
+    {   2654,   4360,   4676, -4632 },
+    {   1386,   5246,   4834, -4497 },
+    {   3488,   4574,   3856, -5946 },
+    {    383,   4481,   4168, -4110 },
+    {   1753,   3652,   4288, -3326 },
+    {   1344,   4905,   2508, -4660 },
+    {   1580,   4106,   3104, -2224 },
+    {   2027,   5038,   1683, -1554 },
+    {    446,   3699,   5872, -3013 },
+    {   4637,   4087,   3578, -5018 },
+    {   2629,   3560,   5331, -4900 },
+    {   1527,   6674,   2523, -4131 },
+    {  -1437,   2804,   2528, -4464 },
+    {   -229,   3355,   2016, -5537 },
+    {   3666,   3418,   4374, -4581 },
+    {   1192,   3799,    923, -6596 },
+    {   2040,   2956,    448, -5322 },
+    {   2468,   5768,   4029, -5869 },
+    {   3438,   6516,   3529, -6667 },
+    {   2737,   5495,    680, -5535 },
+    {   3896,   5727,   1801, -4958 },
+    {   4988,   4957,   3592, -6518 },
+    {   -542,   4416,   5794, -2787 },
+    {   4136,   4354,   2064, -4696 },
+    {   3067,   5936,   1207, -3396 },
+    {   2789,   4966,   2405, -3854 },
+    {   1731,   3270,   3251, -1063 },
+    {   1767,   5537,   2084, -2349 },
+    {    465,   3116,   4532,  -837 },
+    {   1499,   2627,   4610, -2212 },
+    {    122,   3095,   3642, -3552 },
+    {   2542,   2866,   2705, -6402 },
+    {   3134,   4323,    698, -4785 },
+    {    731,   1859,   3112, -5242 },
+    {   2553,   2980,   3241, -4846 },
+    {   1329,   5310,   1607, -6624 },
+    {   2468,   1858,   3476, -1034 },
+    {   -172,   4996,   2000, -5562 },
+    {   2621,   4220,   1574, -3386 },
+    {   -333,   1832,   3362, -4117 },
+    {   2169,   6762,   3065, -6225 },
+    {   2844,   5528,   3223, -4765 },
+    {    526,   5175,   1644, -4267 },
+    {   2922,   4426,   2414, -2610 },
+    {    452,   1399,  -4516, -2636 },
+    {   2872,   1720,  -4667, -1435 },
+    {   1279,    702,  -5424, -1984 },
+    {   2187,    870,  -5021, -1341 },
+    {    583,   -144,  -4628, -2464 },
+    {      3,   2237,  -5284, -2827 },
+    {    -19,   1005,  -5460, -1819 },
+    {   2897,   2084,  -5885,  -515 },
+    {   -400,   3370,  -5527, -2947 },
+    {   1505,   2593,  -5518, -1802 },
+    {   1341,   4534,  -5094, -1899 },
+    {   3241,   3670,  -5493, -1252 },
+    {  -1287,    921,  -5994, -1675 },
+    {    627,    408,  -6652,  -364 },
+    {   -260,   1127,  -4849, -3247 },
+    {    371,   3400,  -5976, -2285 },
+    {   1533,   1566,  -6373,  -610 },
+    {   2462,   4274,  -6184, -1254 },
+    {   1782,   3363,  -6222, -1381 },
+    {    572,   4650,  -5673, -2754 },
+    {   2674,   3414,  -4460, -2154 },
+    {   3614,   3820,  -6883,  -398 },
+    {   1136,     -1,  -5511, -1112 },
+    {  -1773,   1137,  -5647, -2377 },
+    {   -753,   2104,  -6085, -2565 },
+    {   -204,   3025,  -4731, -1418 },
+    {  -1486,   1438,  -4380,  -216 },
+    {    302,    858,  -5786,  -264 },
+    {   3486,   1495,  -5234,  -783 },
+    {    888,   2327,  -3423, -3720 },
+    {   -259,    772,  -6596, -1311 },
+    {  -1197,   2073,  -5174, -1826 },
+    {   1500,   3470,  -4462, -2645 },
+    {   3072,   1960,  -3277, -2264 },
+    {   1841,    952,  -4324, -2340 },
+    {   1994,   2200,  -3940, -2923 },
+    {  -1782,   1699,  -4667, -1075 },
+    {  -1464,   2906,  -3468,  -375 },
+    {    366,   2380,  -3747,  1467 },
+    {   -545,   1645,  -4619,   376 },
+    {   1724,   2350,  -2374, -3512 },
+    {   3184,   2628,  -2996, -3275 },
+    {    734,   2010,  -6239, -1479 },
+    {    524,   3756,  -4496, -3263 },
+    {   1492,   3570,  -3494, -3600 },
+    {   -932,    618,  -5389, -2894 },
+    {   -133,   2161,  -4083, -3267 },
+    {    786,    774,  -3279, -3731 },
+    {   1078,    803,  -3843, -3007 },
+    {   -332,   3405,  -3347,    40 },
+    {    -17,      6,  -4005, -3690 },
+    {   -189,   4372,  -4488, -2561 },
+    {   -450,   3846,  -3790, -1370 },
+    {    362,   2212,  -5272,   -15 },
+    {  -1529,    791,  -6802, -2296 },
+    {   2145,   4241,  -4474,   376 },
+    {   1813,   2426,  -2932, -2726 },
+    {   -542,   4557,  -3140, -1080 },
+    {   1192,   3784,  -4371,   -20 },
+    {   2784,   5188,  -6399, -1394 },
+    {    431,   4561,  -3673, -1398 },
+    {   1382,   3096,  -4083,  1253 },
+    {   1209,   4224,  -2930,  1500 },
+    {   2798,   2684,  -6676,  -606 },
+    {  -2396,   1510,  -5381, -2713 },
+    {  -2625,   2542,  -4032, -2880 },
+    {  -1231,   3967,  -4098, -2886 },
+    {  -1393,   2374,  -3862, -4525 },
+    {  -2495,   1665,  -1637, -5445 },
+    {  -3854,   1759,  -1750, -4944 },
+    {  -2373,   1668,  -2856, -6251 },
+    {  -2668,   1981,   -886, -4557 },
+    {  -2927,   4427,  -3451, -6172 },
+    {  -1925,   2596,  -4696, -2527 },
+    {  -3202,   2847,  -3928, -5896 },
+    {  -3332,   1665,  -5025, -3412 },
+    {  -3212,   3115,  -4155, -4062 },
+    {  -1013,   3205,  -5133, -3751 },
+    {  -2022,   4595,  -3947, -5611 },
+    {  -3556,   1755,  -3715, -2300 },
+    {  -1784,   4114,  -2723, -1773 },
+    {  -3586,   4081,  -2733, -4942 },
+    {  -1608,   3685,  -4154, -4573 },
+    {  -3368,   4042,  -4452, -6227 },
+    {  -1407,   3881,  -5729, -3719 },
+    {  -2751,   3281,  -5077, -4999 },
+    {  -3791,   2410,  -4906, -5288 },
+    {   -730,   2303,  -4217, -3755 },
+    {  -1812,   2311,  -5492, -3709 },
+    {   -610,   4336,  -3915, -3783 },
+    {  -2841,   4337,  -4278, -4430 },
+    {  -1662,   4666,  -4661, -3964 },
+    {   -589,   5209,  -4923, -3682 },
+    {  -4155,   2234,  -4076, -4218 },
+    {  -3951,   2770,  -2665, -2805 },
+    {  -2302,   3228,  -3717, -1908 },
+    {  -3129,   4373,  -2264, -2851 },
+    {   -447,   1363,  -3578, -4323 },
+    {  -2648,   4237,  -3159, -3071 },
+    {  -4072,   3241,  -3541, -4605 },
+    {  -4507,   3458,  -2339, -3838 },
+    {  -1646,    997,  -4926, -3970 },
+    {  -3025,   1614,  -3940, -1242 },
+    {  -1337,   1756,  -3163, -5529 },
+    {  -3203,   1865,  -3282, -4354 },
+    {  -1646,   2118,  -2203, -6018 },
+    {    174,   1871,  -2707, -4639 },
+    {  -2607,   1485,  -4778, -4750 },
+    {  -2199,   3991,  -3134, -4879 },
+    {  -2962,   3323,  -2816, -2419 },
+    {  -5286,   2495,  -4548, -5395 },
+    {  -2810,   3710,  -2274, -4211 },
+    {   -330,   3006,  -2993, -4678 },
+    {  -1187,   2411,  -2743, -5196 },
+    {   -664,   4033,  -3101, -5641 },
+    {  -1458,   3602,  -2816, -5371 },
+    {  -4116,   4923,  -3321, -5630 },
+    {  -4165,   2528,  -2592, -4798 },
+    {  -2759,   3080,  -2333, -5719 },
+    {  -5157,   3011,  -5526, -6348 },
+    {  -3095,   2126,  -5881, -4234 },
+    {  -4377,   3849,  -3600, -6099 },
+    {  -1994,   4947,  -5235, -4753 },
+    {  -1067,    600,  -3258, -5133 },
+    {  -4992,   3302,  -2208, -5051 },
+    {  -3377,   2981,  -1655, -4815 },
+    {  -3325,   2446,  -1787, -6116 },
+    {  -2341,   2737,  -3240, -6347 },
+    {  -2258,  -3732,   3710, -1235 },
+    {  -1558,  -3849,   2694, -3012 },
+    {   -599,  -4837,   3050, -2951 },
+    {  -2246,  -5433,   2798, -1910 },
+    {  -2255,  -4989,   3260,   270 },
+    {  -3026,  -5353,   2693, -1036 },
+    {  -1151,  -6097,   1097, -3782 },
+    {  -3391,  -6012,   2130, -1303 },
+    {  -2850,  -4422,   3375,  -480 },
+    {  -1138,  -3779,   1491, -4162 },
+    {   -551,  -3892,   3787, -2082 },
+    {  -3221,  -3676,   3144, -1202 },
+    {  -3023,  -5196,   2650,   605 },
+    {  -1756,  -5729,   2646,   321 },
+    {  -2693,  -4409,    494, -4797 },
+    {  -1913,  -4573,   3372, -1730 },
+    {  -1277,  -3604,   4061,  -993 },
+    {   -420,  -4993,   1351, -4796 },
+    {  -3052,  -5333,   1435, -1242 },
+    {   -602,  -5034,   3869, -1141 },
+    {  -2436,  -4680,   1665, -3019 },
+    {  -2657,  -3658,   1459, -3391 },
+    {  -1220,  -6246,   2749,  -525 },
+    {  -3838,  -4844,   2265, -1735 },
+    {  -1247,  -5679,   3356, -1417 },
+    {   -917,  -5448,   3342,   105 },
+    {  -1756,  -6839,   2276, -2350 },
+    {   -412,  -5206,   1764, -3539 },
+    {  -1439,  -6915,   1442, -3750 },
+    {  -1381,  -4439,   3863,  -282 },
+    {  -3482,  -4953,   2726,  -336 },
+    {  -1376,  -5931,   1714, -1987 },
+    {  -1716,  -4405,   2608,   105 },
+    {  -1590,  -5191,   2652, -2704 },
+    {  -2149,  -6442,   2453, -1263 },
+    {  -3426,  -3832,   2334, -1829 },
+    {  -2747,  -5948,   2362,  -173 },
+    {  -2435,  -3267,   2966, -1710 },
+    {  -3979,  -4282,   2705,  -775 },
+    {   -356,  -4238,   2544, -4343 },
+    {  -1363,  -6471,   2817, -1836 },
+    {  -2878,  -5117,    218, -3149 },
+    {  -3539,  -5196,   1710, -2356 },
+    {  -2888,  -4537,   2746, -1701 },
+    {  -1870,  -4439,   1496, -4121 },
+    {  -1486,  -3388,   3349, -2145 },
+    {  -3333,  -4138,   1467, -2876 },
+    {   -345,  -5340,   1012, -1190 },
+    {  -1672,  -4992,   2289, -1029 },
+    {  -2146,  -5528,   3038,  -635 },
+    {   -316,  -3656,   3426, -3152 },
+    {  -2695,  -5812,   2336, -2050 },
+    {  -2067,  -6052,    737, -3258 },
+    {  -2664,  -4205,   -350, -1266 },
+    {   -617,  -5406,     80, -4853 },
+    {  -2418,  -3825,   1853, -1326 },
+    {  -1961,  -4339,    583, -4315 },
+    {  -1495,  -5141,   -133, -5205 },
+    {  -3208,  -6440,   1691, -2069 },
+    {  -2632,  -3633,   2325, -2761 },
+    {  -2624,  -5670,   1252, -3676 },
+    {  -3687,  -5608,    687, -2833 },
+    {  -3320,  -5707,     16, -3877 },
+    {  -2738,  -6112,     84, -5135 },
+    {   2277,  -5661,   3076,   843 },
+    {   1555,  -5769,   2821, -5236 },
+    {    536,  -6381,    603, -4910 },
+    {    734,  -4609,   3314, -4092 },
+    {   1836,  -4547,   3267, -4322 },
+    {    -13,  -5976,   3752, -1607 },
+    {   1423,  -6318,   2336,   398 },
+    {    365,  -7779,   1498,  -534 },
+    {   2104,  -8366,   2946, -1345 },
+    {    143,  -5545,   1898, -3756 },
+    {    655,  -6852,   1430,   148 },
+    {      4,  -6653,   2397,   -59 },
+    {   2346,  -5996,   4562,  -934 },
+    {   1229,  -7104,   2963,  -598 },
+    {   -528,  -7048,   2887, -1790 },
+    {   1451,  -6857,   3900, -1637 },
+    {    554,  -6018,   3336,     9 },
+    {   3278,  -5758,   4034,   129 },
+    {   3541,  -7145,   4905, -1575 },
+    {   2339,  -6907,   3464,  -301 },
+    {   2775,  -7301,   1667, -3894 },
+    {    539,  -7887,    991, -4156 },
+    {   2115,  -7421,   3131, -3075 },
+    {   2803,  -8546,   2564, -5836 },
+    {   2869,  -5833,   1620, -4561 },
+    {   2591,  -7281,   3215, -4719 },
+    {  -1228,  -8477,    706, -4782 },
+    {   1967,  -5243,   4813, -1940 },
+    {    701,  -7010,   2273, -3893 },
+    {    915,  -8470,   1918, -5620 },
+    {    -94,  -6715,    156, -3873 },
+    {   1074,  -5607,   4389, -1017 },
+    {   2739,  -6551,   1227, -3521 },
+    {    725,  -7835,   2701, -1291 },
+    {   -493,  -7475,   2263, -1075 },
+    {   -412,  -6508,   2984,  -744 },
+    {    665,  -5451,   3725, -2692 },
+    {   1499,  -8129,   3564, -2072 },
+    {   2870,  -6333,   4487, -2108 },
+    {    706,  -5007,   3911,  -152 },
+    {   -482,  -8660,   1483, -2900 },
+    {   2481,  -6596,   2518, -1715 },
+    {   1403,  -6414,   1398, -5387 },
+    {    652,  -6267,    583, -5942 },
+    {    694,  -7540,    646, -6272 },
+    {   2275,  -7614,    256, -5015 },
+    {   1416,  -9727,   1900, -3153 },
+    {   2760,  -6433,   3875, -3771 },
+    {   2325, -11196,   2182, -5155 },
+    {   1223, -11061,   1377, -5097 },
+    {    108, -10603,    307, -4952 },
+    {   -118,  -8268,   1650, -1572 },
+    {   1839,  -7943,   1755,  -612 },
+    {   2501,  -9056,    981, -2969 },
+    {   2902,  -8476,   1491, -5780 },
+    {   1995, -11175,   1585, -3643 },
+    {    696,  -8212,    828, -2474 },
+    {   1526,  -8649,   1380, -1210 },
+    {    461,  -7253,   3222, -2229 },
+    {   2966,  -8641,   4121, -3271 },
+    {    833,  -6039,   2361, -1086 },
+    {   3565,  -7312,   1980, -5427 },
+    {   2850,  -8671,   3760, -1846 },
+    {   2643,  -7281,   2163,  -173 },
+    {   3463,  -3706,  -3132,  -923 },
+    {   1315,  -3825,  -3443,     2 },
+    {   2594,  -4083,  -3815,   670 },
+    {   1826,  -4291,  -2741,  -155 },
+    {    868,  -3749,  -4175,  -298 },
+    {   2008,  -4237,  -3897,  -517 },
+    {   1242,  -3493,  -4335, -1335 },
+    {    -88,  -4142,  -3390, -1529 },
+    {   2176,  -3488,  -3822,  -975 },
+    {   1706,  -5188,  -3415,  -637 },
+    {   2717,  -6159,  -2333,  -882 },
+    {   1276,  -3978,  -4361,   537 },
+    {   2471,  -5556,  -2866,  -208 },
+    {    799,  -4673,  -4086,    56 },
+    {   1901,  -4786,  -3533,   270 },
+    {   3036,  -3902,  -3606,  -333 },
+    {   2249,  -3317,  -4319,  -144 },
+    {   2594,  -4207,  -2105, -2930 },
+    {   4008,  -4774,  -2626,  -902 },
+    {   1038,  -3659,  -3496, -2454 },
+    {   2725,  -3597,  -3298, -1535 },
+    {   1662,  -5803,  -2813,   175 },
+    {    705,  -3757,  -3441, -1484 },
+    {   1860,  -5987,  -2821,  -886 },
+    {   3786,  -4918,  -2199, -1929 },
+    {   3683,  -4235,  -2547, -1287 },
+    {   2531,  -4896,  -2956, -1593 },
+    {   1005,  -5585,  -3324,  -180 },
+    {   1625,  -5229,  -1756, -3642 },
+    {   1494,  -5041,  -2989, -2685 },
+    {   2718,  -4655,  -3224,  -867 },
+    {   2374,  -6640,  -1745, -2975 },
+    {   2133,  -6436,  -2477, -1499 },
+    {   1833,  -4418,  -3523, -1512 },
+    {   1128,  -4910,  -2658, -1106 },
+    {    689,  -4777,  -2831, -2085 },
+    {   3593,  -5280,  -2627,  -315 },
+    {   3264,  -3771,  -2673, -1861 },
+    {   3202,  -5602,  -2409,   402 },
+    {    552,  -4618,  -2221, -3002 },
+    {   3095,  -5356,  -2666, -1083 },
+    {   3401,  -4609,  -3146,    45 },
+    {   3051,  -4662,  -2192, -2232 },
+    {   2798,  -5552,  -2462, -1941 },
+    {   2354,  -5815,  -2223, -2619 },
+    {    192,  -3708,  -2807, -2658 },
+    {   1886,  -4226,  -1862, -3529 },
+    {   2526,  -3976,  -2819, -2332 },
+    {   1577,  -3870,  -2711, -2806 },
+    {   1288,  -5588,  -3382, -1403 },
+    {   2711,  -5399,  -1564, -3253 },
+    {   1459,  -5492,  -2222,  -322 },
+    {   2823,  -5091,  -2886,   776 },
+    {   3559,  -5821,  -2109, -1360 },
+    {   1587,  -6331,  -2760, -1909 },
+    {   2139,  -5213,  -2874, -2120 },
+    {   1318,  -4337,  -3695, -2098 },
+    {    821,  -4471,  -1849,  -565 },
+    {   3329,  -4782,  -1725,   -89 },
+    {    582,  -4914,  -4105, -1119 },
+    {    417,  -4144,  -4072, -2529 },
+    {   -199,  -3803,  -2765, -4042 },
+    {   2731,  -4283,  -2143,     1 },
+    {   2911,  -6187,  -1951, -2116 },
+    {   1573,  -6094,   -493, -2838 },
+    {   2081,  -6927,   -864, -3211 },
+    {   1058,  -7826,     79,  -364 },
+    {   3147,  -5570,   -684,  -978 },
+    {   3572,  -5856,   1060,  1824 },
+    {   1143,  -6702,  -1478,   338 },
+    {   2341,  -7220,    -88,   260 },
+    {   3639,  -6861,    668,   815 },
+    {   2227,  -6268,  -1706,   446 },
+    {   3390,  -6082,   -353,  1302 },
+    {   1123,  -7556,  -1237,  -430 },
+    {   1729,  -7742,    729,  -218 },
+    {   1457,  -6774,    587,   579 },
+    {    505,  -6919,   -569,   371 },
+    {   1106,  -7245,     78,   158 },
+    {   2755,  -6745,  -1122,   338 },
+    {   3069,  -6040,  -1415,   986 },
+    {   2174,  -7064,  -1430,  -283 },
+    {   1390,  -8626,   -446, -3031 },
+    {   3534,  -6890,   -431,   547 },
+    {   2267,  -9618,    475, -2994 },
+    {   3672,  -7673,     75,  -115 },
+    {   2131,  -7560,  -1206,  -750 },
+    {   2972,  -7477,   -685,  -262 },
+    {   1604,  -6637,   -672,   699 },
+    {   1666,  -7577,   -577,  -240 },
+    {   1591,  -6554,  -2158,   -94 },
+    {   2348,  -6286,   -353,  1123 },
+    {   2017,  -8810,   -412, -1805 },
+    {   2892,  -6713,  -1765,  -554 },
+    {   2500,  -6828,  -1995, -1197 },
+    {   3877,  -6639,   -224, -1655 },
+    {   2392,  -7872,    -91,  -333 },
+    {   3562,  -7370,   -532, -2836 },
+    {   2552,  -7614,    164, -1805 },
+    {    990,  -6104,    218,   438 },
+    {    910,  -7861,    312, -1195 },
+    {   1472,  -6327,    372,  -640 },
+    {   1576,  -7143,  -1983,  -843 },
+    {    422,  -7625,   -457,  -278 },
+    {   1797,  -8532,    405, -1011 },
+    {   1088,  -7396,   -238, -2277 },
+    {   3209,  -6753,  -1431, -2072 },
+    {   2617,  -6839,    100, -2573 },
+    {   2575,  -8573,   -387, -3188 },
+    {   3618,  -6971,  -1190,  -321 },
+    {   2205,  -7361,  -1695, -2008 },
+    {   2985,  -6297,   1464,  1179 },
+    {   2804,  -7310,   1053,   338 },
+    {   1362,  -6074,  -1163,  -840 },
+    {   3336,  -6325,  -1794,    21 },
+    {   2836,  -8109,    818,  -329 },
+    {   2791,  -5879,    560,  1546 },
+    {   2392,  -6064,    135,   100 },
+    {   1838,  -6194,    596,  1085 },
+    {   1926,  -7515,   -414, -4901 },
+    {   3225,  -7298,  -1202, -1189 },
+    {   3960,  -7558,   -659,  -719 },
+    {   3442,  -6647,  -1692, -1095 },
+    {   3381,  -6441,    262,  -886 },
+    {   1431,  -8150,  -1186, -1406 },
+    {    340,  -8498,   -150,  -899 },
+    {   3004,  -8149,   -260,  -953 },
+    {   2749,  -6611,    563,   873 },
+    {  -6647,  -1325,  -4517, -4691 },
+    {  -6005,  -1657,  -4089, -3797 },
+    {  -3157,    588,  -5213, -3068 },
+    {  -3311,  -1425,  -6329, -3726 },
+    {  -5866,   -819,  -3857, -2744 },
+    {  -5001,  -1799,  -1075, -4621 },
+    {  -5330,  -2650,  -2672, -4664 },
+    {  -4930,   -539,  -2363, -4010 },
+    {  -2984,     10,  -3863, -5749 },
+    {  -1055,  -2106,  -3713, -4267 },
+    {  -5476,   -502,  -4279, -6504 },
+    {  -5231,  -1543,  -5018, -6425 },
+    {  -5134,   -363,  -3165, -5109 },
+    {  -3953,   -771,  -4107, -6393 },
+    {  -2159,   -563,  -3652, -5342 },
+    {  -3888,  -2321,   -919, -5057 },
+    {  -1236,   -597,  -4235, -4193 },
+    {  -4053,    675,  -3083, -6174 },
+    {  -2793,  -1089,  -5396, -3460 },
+    {  -3000,    -44,  -2209, -6575 },
+    {  -3336,  -1531,  -4313, -5160 },
+    {  -2127,    128,  -4851, -3692 },
+    {  -3321,    136,  -2067, -5660 },
+    {  -5215,   1404,  -4374, -4356 },
+    {  -2747,    400,  -6340, -3691 },
+    {  -3926,   -599,  -5361, -5006 },
+    {  -2875,  -2592,  -5143, -4092 },
+    {  -4991,  -1958,  -5322, -4891 },
+    {  -4965,  -1318,  -6652, -5333 },
+    {  -4920,  -1691,  -3388, -5561 },
+    {  -3644,  -3354,  -2688, -5982 },
+    {  -5076,   -919,  -4563, -2984 },
+    {  -6114,    250,  -3884, -3915 },
+    {  -4014,    744,  -3973, -1924 },
+    {  -5543,  -1041,  -5557, -3847 },
+    {  -4711,  -1352,  -5649, -2603 },
+    {  -3362,    775,  -5305, -4879 },
+    {  -5001,    107,  -3554, -2888 },
+    {  -6258,  -1651,  -6356, -6566 },
+    {  -4529,    407,  -5003, -3865 },
+    {  -5154,    550,  -5278, -5465 },
+    {  -4195,   -467,  -1894, -3129 },
+    {  -5022,   1127,  -3349, -3314 },
+    {  -6075,   1250,  -4313, -5641 },
+    {  -2677,  -2283,  -2312, -5903 },
+    {  -4113,    193,  -1195, -4833 },
+    {  -3940,  -1048,  -1389, -5079 },
+    {  -3703,    917,  -4043, -4451 },
+    {  -3366,  -4231,  -1534, -5488 },
+    {  -3326,  -3583,  -2091, -4903 },
+    {  -5144,   1254,  -2532, -4949 },
+    {  -5982,   -870,  -2545, -4555 },
+    {  -3925,   -157,  -5367, -2281 },
+    {  -6419,   -746,  -5668, -4371 },
+    {  -5787,    518,  -7096, -5805 },
+    {  -4258,    954,  -6453, -4321 },
+    {  -4771,   -695,  -4158, -1639 },
+    {  -7078,   -760,  -5195, -5877 },
+    {  -7348,     83,  -4101, -4586 },
+    {  -2430,    184,  -2874, -1679 },
+    {  -2284,  -3943,  -2924, -5034 },
+    {  -1804,  -1785,  -3002, -4710 },
+    {  -4399,  -2772,  -1815, -4637 },
+    {  -6340,  -2626,  -2824, -5191 },
+    {  -4998,  -5168,  -3480,  1905 },
+    {  -3958,  -5492,  -1599,  1579 },
+    {  -2471,  -3755,   -276,  3182 },
+    {  -3033,  -5779,  -1063,  1554 },
+    {  -2936,  -4829,  -1290,  2386 },
+    {  -1835,  -5073,  -3051,  1299 },
+    {  -1724,  -3771,  -3935,  2324 },
+    {  -5070,  -2550,  -3692,   768 },
+    {  -4326,  -5333,   -297,  1878 },
+    {  -3472,  -5619,  -3094,   992 },
+    {  -3027,  -4384,  -3038,  2265 },
+    {  -3201,  -5332,     67,  2200 },
+    {  -1681,  -4373,  -1947,  2461 },
+    {  -3221,  -3329,  -4238,  2564 },
+    {  -1262,  -2968,  -2915,  3227 },
+    {  -3419,  -1878,  -3373,  2110 },
+    {  -2244,  -5583,  -2012,  1288 },
+    {  -1971,  -5266,   -990,  1812 },
+    {  -2975,  -2778,   -452,  4063 },
+    {  -2198,  -1165,  -3298,  2965 },
+    {  -4782,  -4894,  -4767,   664 },
+    {  -6002,  -3950,  -2806,  2025 },
+    {  -3142,  -3162,  -2859,  3295 },
+    {  -3262,  -3340,  -4123,  1596 },
+    {  -4014,  -3918,  -1955,  3361 },
+    {  -1700,  -3463,  -1346,  3449 },
+    {  -4245,  -4445,  -4743,  1644 },
+    {  -4180,  -3969,   -401,  3281 },
+    {  -2782,  -5240,  -4117,  1156 },
+    {  -5744,  -4040,  -1439,  3470 },
+    {  -5063,  -4663,   -323,  3172 },
+    {  -4531,  -3319,   -844,  3988 },
+    {  -6226,  -5125,  -2064,  2976 },
+    {  -3115,  -3267,  -1531,  3898 },
+    {  -4628,  -4421,  -2864,  2808 },
+    {  -4559,  -2989,  -3442,  2024 },
+    {  -1775,  -4487,   -656,  2477 },
+    {  -2664,  -1865,  -1884,  4081 },
+    {  -1828,  -2575,  -3894,  3378 },
+    {  -6441,  -3677,  -2025,  1677 },
+    {  -4141,  -2156,  -1191,  3474 },
+    {  -4802,  -1623,  -1727,  2160 },
+    {  -5474,  -2745,  -1475,  2498 },
+    {  -3664,  -1056,  -1975,  2491 },
+    {  -4672,  -3062,  -2235,  2933 },
+    {  -4205,  -5960,  -2849,  1517 },
+    {  -4995,  -5708,  -1739,  1805 },
+    {  -4892,  -6080,  -4793,   872 },
+    {  -4270,  -4172,  -4263,  2185 },
+    {  -4687,  -1470,  -2905,  1023 },
+    {  -6446,  -5017,  -3919,  1000 },
+    {  -6046,  -5538,  -3943,  2006 },
+    {  -6028,  -3750,  -3953,   771 },
+    {  -5959,  -4582,  -5024,   824 },
+    {  -5818,  -2576,  -2249,  1326 },
+    {  -5659,  -5345,  -1119,  2500 },
+    {  -3346,  -4155,    606,  2749 },
+    {  -5680,  -4827,  -2501,  1838 },
+    {  -6193,  -2543,  -1295,   840 },
+    {  -6871,  -4925,  -3512,  1801 },
+    {  -5605,  -1788,  -1895,   779 },
+    {  -3922,  -5712,  -4644,   510 },
+    {  -4745,  -3869,  -4533,    99 },
+    {  -2984,  -4907,   -399,  1497 },
+    {   1847,   -478,   3061, -5812 },
+    {   4450,  -1116,   3609, -6570 },
+    {   3139,     99,   3007, -5532 },
+    {   2590,  -3782,   3138, -4770 },
+    {   1881,   1204,   5778, -3404 },
+    {   3631,   2060,   5566, -5038 },
+    {   3461,   1961,   5167, -3800 },
+    {   2947,    273,   4536, -4389 },
+    {   4453,  -1730,   5788, -4370 },
+    {   4032,   1805,   2666, -4534 },
+    {   3487,   -944,   2313, -6028 },
+    {   1313,     34,   4210, -4067 },
+    {   5632,  -1502,   5825, -5855 },
+    {   7736,   -547,   4879, -5476 },
+    {   4906,  -1512,   4760, -5760 },
+    {   3843,    447,   1091, -4958 },
+    {   2982,  -1135,   5442, -4386 },
+    {   3579,    271,   3031, -6770 },
+    {   3932,   -211,   4688, -5507 },
+    {   4411,   1720,   2387, -5584 },
+    {   5379,   -479,   4575, -6280 },
+    {   3613,   -362,   2012, -4885 },
+    {   3744,  -2013,   4493, -5073 },
+    {   5693,    109,   4379, -3362 },
+    {   5475,   -621,   5317, -3985 },
+    {   6411,   -673,   5708, -4752 },
+    {   4933,   -796,   7262, -4290 },
+    {   2804,    444,   6276, -3655 },
+    {   4120,   -517,   6078, -4531 },
+    {   5119,    841,   3486, -3910 },
+    {   4738,   1539,   3525, -2970 },
+    {   5086,    370,   5895, -5640 },
+    {   4235,   2716,   4589, -5044 },
+    {   3691,    682,   6199, -4700 },
+    {   6111,   -570,   6271, -6528 },
+    {   2611,   1277,   3756, -4802 },
+    {   4395,    970,   3807, -5879 },
+    {   5225,   2299,   3242, -4333 },
+    {   5144,   1778,   4946, -5545 },
+    {   2989,  -3016,   3247, -5495 },
+    {   2983,    920,   2071, -6059 },
+    {   5270,   -903,   4434, -2350 },
+    {   6415,   -585,   3970, -3554 },
+    {   3866,   -197,   5216, -2884 },
+    {   3767,  -1298,   6702, -3315 },
+    {   6299,   2620,   5284, -6824 },
+    {   6654,    646,   3653, -4927 },
+    {   4770,   3047,   5160, -6287 },
+    {   5364,    434,   2919, -5207 },
+    {   2998,   1344,   4801, -2456 },
+    {   3896,   1013,   3773, -1864 },
+    {   2115,    655,   2999, -6344 },
+    {   5170,   -981,   2849, -4464 },
+    {   2735,  -2159,   2717, -5776 },
+    {   2430,  -1952,   4392, -4559 },
+    {   6143,  -1180,   3659, -4746 },
+    {   4978,  -1483,   1726, -4875 },
+    {   3486,  -2383,   3306, -4301 },
+    {   1434,  -1372,   4171, -4770 },
+    {   3354,  -2627,   1525, -5093 },
+    {   6790,   2386,   3995, -5909 },
+    {   1475,  -2674,   3451, -4204 },
+    {   1999,  -3494,   3693, -5556 },
+    {   4764,  -2848,   2856, -5589 },
+    {  -3677,   5131,   2827, -2934 },
+    {  -2844,   7078,   2852, -3580 },
+    {  -3902,   6434,   4118, -1911 },
+    {  -1769,   7530,   3492, -3541 },
+    {  -1937,   5679,   -447, -1127 },
+    {  -2456,   4680,   4196, -2407 },
+    {  -2778,   8241,   1698, -4288 },
+    {  -2876,   6104,   5182, -2387 },
+    {  -2802,   7341,   4463, -2938 },
+    {  -1025,   6267,   4752, -3201 },
+    {  -2349,   5413,   2041, -3794 },
+    {  -2252,   8225,   2856, -4269 },
+    {  -1465,   4967,   4976, -2500 },
+    {   -636,   7565,   3517, -4233 },
+    {  -1905,   5618,   3904, -2942 },
+    {   -302,   6816,   3343, -3316 },
+    {  -2210,   4156,   2817, -3511 },
+    {   -717,   6568,   1863, -2951 },
+    {  -3873,   5682,   2164,  -575 },
+    {  -2878,   5835,    440, -2597 },
+    {  -3228,   7701,   2610, -2514 },
+    {  -3608,   8888,   3377, -2468 },
+    {  -2582,   9717,   2519, -3126 },
+    {  -5238,   6202,   2866, -2831 },
+    {  -3428,   7370,   3056,  -335 },
+    {  -1681,   8836,   1210, -2010 },
+    {  -3276,   6724,   1156, -3930 },
+    {   -894,   8149,    827, -1258 },
+    {  -2965,   8631,   2549, -1320 },
+    {  -3961,   6902,   3581,    55 },
+    {  -1894,   7745,   1750,  -841 },
+    {   -821,   6844,    850,  -676 },
+    {   -608,   6948,     -4, -1376 },
+    {    615,   6524,   1089, -1147 },
+    {  -2972,   5668,   1091,  -489 },
+    {   -157,   4649,   2904,  -413 },
+    {    673,   5121,   1498,   -66 },
+    {   -390,   5902,   1611,  -245 },
+    {  -2349,   5478,   4772, -1320 },
+    {     88,   6798,   1972, -1859 },
+    {  -1213,   5120,   2991,   200 },
+    {  -2347,   6040,   2839,   376 },
+    {   -578,   5976,   3364, -1796 },
+    {  -1391,   5872,   3002,  -965 },
+    {   -564,   4496,   3946, -1186 },
+    {  -2299,   6386,   3135, -2176 },
+    {  -2131,   5641,   2011,  1223 },
+    {   -772,   5807,   1124,   895 },
+    {  -2837,   6758,   2297,  -740 },
+    {  -3091,   6298,   1415, -2126 },
+    {  -4197,   6036,   1843, -3022 },
+    {    -41,   6459,     92,   344 },
+    {  -2241,   6860,   2095, -4396 },
+    {  -1931,   7088,   2117, -2135 },
+    {  -2375,   4422,   1688, -3169 },
+    {  -1742,   6674,   1538,  -119 },
+    {  -4818,   7749,   4192, -1577 },
+    {  -2004,   5672,    193,  -430 },
+    {  -3825,   6042,   2128, -1898 },
+    {  -1108,   8033,   2119, -3013 },
+    {  -2370,   5453,   1721,   266 },
+    {  -1570,   7134,    614, -2638 },
+    {  -1519,   8752,   3503, -4330 },
+    {  -2050,   3845,   2907, -1126 },
+    {   5085,   4412,   -335, -1923 },
+    {   3618,   1423,   -613, -4012 },
+    {   4481,   3729,    589, -4631 },
+    {   4270,   3216,  -1763, -3168 },
+    {   4241,   1796,  -1701, -2796 },
+    {   4787,   2338,   -487, -3639 },
+    {   2915,   3429,   -621, -4753 },
+    {   5175,   1660,  -1265, -3223 },
+    {   4280,   4057,   -684, -4079 },
+    {   4980,   4419,  -1455, -2719 },
+    {   5436,   2464,    387, -4197 },
+    {   4507,   4018,   1121, -3314 },
+    {   6020,   2401,   -413, -3201 },
+    {   4200,   3789,   -333, -2813 },
+    {   5229,   2493,  -1194, -1878 },
+    {   5851,   2695,   -492, -2292 },
+    {   5743,   3288,   -697, -1221 },
+    {   5692,   2612,    979, -2227 },
+    {   5085,   2067,   1046, -1214 },
+    {   3163,   2240,  -2098, -3435 },
+    {   5228,   1898,    145, -2397 },
+    {   5860,   3976,   -418, -2872 },
+    {   6008,   3399,   1027, -3506 },
+    {   4126,   2035,   1865,  -893 },
+    {   5375,   3596,    511, -2362 },
+    {   1937,   1493,   -852,  -122 },
+    {   3473,   4849,    547, -2603 },
+    {   4631,   2977,   1141, -1768 },
+    {   6149,   3050,    -71, -1886 },
+    {   4069,   4353,   -289, -1429 },
+    {   2884,   1225,  -1388,   365 },
+    {   5485,   2518,   -235,  -571 },
+    {   1216,   4375,   1443,   398 },
+    {   4988,   3106,    107, -1435 },
+    {   4511,   2801,    307,  -444 },
+    {   3235,   4386,    327,  -676 },
+    {   2055,   3708,   1657,  -305 },
+    {   5839,   2374,    290, -1385 },
+    {   5110,   3305,   1936, -4206 },
+    {   6416,   2920,    338, -2736 },
+    {   3350,   2824,  -1269, -3881 },
+    {   4840,   1815,    464,   186 },
+    {   2399,   3332,    238,  1238 },
+    {   3516,   1363,   1582,   688 },
+    {   3582,   1874,    154, -4770 },
+    {   3261,   2878,    886,   283 },
+    {   3877,   2658,   -327,   884 },
+    {   4151,   3436,   2173, -2923 },
+    {   3592,   3674,   1281, -1295 },
+    {   4561,   3730,  -1114, -1747 },
+    {   4595,   3625,   -558,  -575 },
+    {   2577,   2348,   2267,   120 },
+    {   5242,   3299,     32, -3412 },
+    {   4264,   3637,    709, -2320 },
+    {   6556,   3570,   -838, -2472 },
+    {   5745,   4014,   -940, -1973 },
+    {   5629,   4475,    477, -3328 },
+    {   5269,   3199,   1682, -3085 },
+    {   4432,   2416,   1145, -3299 },
+    {   4465,   2505,   2162, -2186 },
+    {   4643,   4941,    -88, -2885 },
+    {   4568,   5231,    552, -3915 },
+    {   5667,   3075,  -1406, -2963 },
+    {   5418,   5259,   -771, -2818 },
+    {   -256,  -7875,    511,  -471 },
+    {  -1813,  -7971,   -424,  -396 },
+    {   -306,  -7006,    862,   282 },
+    {  -2306,  -6422,  -1440,   508 },
+    {   -245,  -6787,    375,  -100 },
+    {  -1309,  -6065,    -20,   779 },
+    {  -1656,  -6047,   -641,  1307 },
+    {  -1496,  -6522,    964,   726 },
+    {  -2291,  -6588,   -202,   795 },
+    {   -762,  -7522,   1454,  -558 },
+    {  -2270,  -7004,   -834,  -580 },
+    {  -1139,  -7078,    259,   362 },
+    {  -2535,  -7568,  -1040,    49 },
+    {  -3786,  -7280,    934,  -476 },
+    {  -3336,  -6368,    606,  1056 },
+    {  -3602,  -6924,     52,   714 },
+    {  -2278,  -6550,   1674,   204 },
+    {  -2855,  -5765,    930,  1530 },
+    {  -2889,  -7325,   -215,   305 },
+    {  -2749,  -6080,   -237,  1452 },
+    {   -985,  -6667,   1577,   400 },
+    {  -2036,  -6083,    380,  1267 },
+    {  -2077,  -7460,    380,   -30 },
+    {  -1775,  -7175,   1540,  -386 },
+    {  -3065,  -6927,    989,   168 },
+    {  -2836,  -7602,    117, -3392 },
+    {  -1058,  -6396,    593, -3078 },
+    {   -844,  -6062,    999,  -236 },
+    {  -3261,  -6951,   1491,  -720 },
+    {  -2186,  -8484,     75, -1287 },
+    {  -2882,  -7756,    456,  -510 },
+    {  -1800,  -6879,    960, -1183 },
+    {  -2554,  -7241,   1614, -1474 },
+    {  -2608,  -5305,    392,   851 },
+    {  -2973,  -6562,   -859,   858 },
+    {  -2640,  -5989,   1031,  -416 },
+    {   -977,  -8366,    705, -1434 },
+    {  -1213,  -7409,    -77, -1390 },
+    {  -1335,  -6657,   2125,  -123 },
+    {  -2544,  -6862,   1852,  -737 },
+    {  -3235,  -6422,   1752,  -103 },
+    {  -1300,  -7557,    939,  -348 },
+    {  -3476,  -7579,    202,  -109 },
+    {  -2482,  -6572,    753,   619 },
+    {  -2554,  -8136,   -648,  -429 },
+    {  -1012,  -7870,     -3,  -421 },
+    {  -3604,  -6247,     32, -3102 },
+    {  -1486,  -7271,   2013, -1021 },
+    {   -578,  -6799,   -523,   405 },
+    {  -2841,  -5948,   1644,   911 },
+    {  -2411,  -7473,   1084,  -484 },
+    {  -2238,  -6033,    294, -1059 },
+    {  -3459,  -6470,   -201,  -790 },
+    {  -2027,  -6009,   1833,   805 },
+    {  -1433,  -8047,   1531, -1754 },
+    {  -3258,  -7884,    763, -1422 },
+    {  -1544,  -6928,   -729,   478 },
+    {  -2314,  -8415,     74, -3757 },
+    {  -3201,  -5684,     95, -2214 },
+    {  -2423,  -8694,    725, -3631 },
+    {  -3545,  -7071,   1162, -1798 },
+    {   -294,  -9662,    403, -2274 },
+    {  -2290,  -5460,   1196,   402 },
+    {  -1603,  -6713,    903, -2363 },
+    {   4121,   2491,  -3142, -2482 },
+    {   4500,   3305,  -3671, -1567 },
+    {   5973,   3172,  -1348,  -534 },
+    {   4830,   3379,  -1549,   643 },
+    {   5214,   3938,  -2641, -2302 },
+    {   4639,   4826,  -5532,  -847 },
+    {   5639,   2731,  -2170,  -963 },
+    {   6084,   3487,  -3525, -1346 },
+    {   5971,   3154,  -2190, -2316 },
+    {   5618,   4865,  -6927,   116 },
+    {   5345,   3568,  -7391,   709 },
+    {   5429,   5078,  -3811, -1524 },
+    {   6960,   2037,  -3515, -1096 },
+    {   7092,   2531,  -4557,  -588 },
+    {   6061,   4247,  -5651,  -478 },
+    {   4595,   3684,  -4907,  -827 },
+    {   7497,   3213,  -3048,  -424 },
+    {   5996,   2137,  -3098, -1745 },
+    {   6198,   5199,  -2223, -2274 },
+    {   6888,   2851,  -2768, -1675 },
+    {   6114,   4210,  -2316,  -954 },
+    {   7127,   4242,  -3041, -1408 },
+    {   6126,   3668,  -1517, -1427 },
+    {   6245,   6129,  -4225, -1186 },
+    {   6816,   3213,  -2101,  -964 },
+    {   5345,   5276,  -2643,  -847 },
+    {   6592,   4665,  -4338,   484 },
+    {   6746,   3751,  -3443,   124 },
+    {   5453,   1980,  -2738,  2606 },
+    {   4662,   2179,  -4226, -1059 },
+    {   5571,   3208,  -3554,   174 },
+    {   5256,   4447,  -1815, -1481 },
+    {   5400,   2570,  -1210,   235 },
+    {   7056,   2549,  -2674,   318 },
+    {   4574,   4340,  -2892,  -130 },
+    {   6203,   4587,  -3273,  -305 },
+    {   5103,   1925,  -2715, -2137 },
+    {   3905,   4296,  -1700,   247 },
+    {   4421,   4605,  -3299,   811 },
+    {   5671,   1273,  -3870,  -924 },
+    {   5486,   1805,  -4901,   133 },
+    {   6437,   2578,  -1828,  -106 },
+    {   5530,   5253,  -5058,  1223 },
+    {   4816,   2025,  -1215,  1443 },
+    {   3457,   3525,  -2456,  3217 },
+    {   3316,   2595,  -1108,  2459 },
+    {   3068,   3810,  -2207,  1926 },
+    {   6351,   5436,  -6470,   600 },
+    {   6324,   4240,  -5365,  2416 },
+    {   4851,   4774,  -4075,  1878 },
+    {   4900,   3679,  -5198,  1078 },
+    {   8347,   3633,  -4565,  -171 },
+    {   5244,   5718,  -3853,   173 },
+    {   3960,   3492,  -2939,  2105 },
+    {   6070,   3473,  -2351,   161 },
+    {   8228,   3034,  -3360,  -901 },
+    {   7006,   3985,  -1940, -1926 },
+    {   7123,   4681,  -4301,  -878 },
+    {   5122,   4097,  -1851,  -449 },
+    {   6200,   2060,  -2251,  1049 },
+    {   7106,   3844,  -7209,  2625 },
+    {   7108,   3370,  -6734,   533 },
+    {   6859,   2849,  -3992,  1360 },
+    {   5458,   2278,  -3253,  1131 },
+    {  -1072,  -2109,   4783, -1073 },
+    {   -319,  -2604,   4257, -2418 },
+    {   2466,   1300,   3476,  -314 },
+    {   2847,  -1502,   5296,  -141 },
+    {   1667,  -1273,   5559, -2725 },
+    {   2877,  -3402,   6434,   204 },
+    {     53,  -2637,   5275, -1181 },
+    {   1091,  -2215,   5803, -1549 },
+    {   2397,   -922,   4327,  1182 },
+    {    219,  -3747,   4647, -1564 },
+    {    -29,  -2705,   4812,  1277 },
+    {   1499,  -2608,   5648,  1407 },
+    {   2139,  -2399,   4202,  2791 },
+    {   -426,  -2064,   5528,   151 },
+    {   2560,  -2803,   6179, -2806 },
+    {   4537,  -2479,   3797,  1095 },
+    {    888,  -3357,   5341,  -415 },
+    {   4460,  -1814,   5388, -1227 },
+    {   3920,  -3268,   6364,  -703 },
+    {   3343,  -4698,   4410,   784 },
+    {    309,  -1897,   6306,  1223 },
+    {    958,  -3318,   4254, -3167 },
+    {    -99,   1596,   6018, -1983 },
+    {   -429,   -853,   6407,   878 },
+    {   1170,  -1322,   6290,  -417 },
+    {   2288,   -505,   6303, -1999 },
+    {   3312,  -1674,   6749, -2494 },
+    {   -415,  -3401,   4721,  -371 },
+    {   -189,  -1210,   4844, -2002 },
+    {    888,  -4142,   4377,   130 },
+    {   2469,  -4381,   5398, -2492 },
+    {   2879,  -2912,   5094, -2598 },
+    {   -717,   -617,   5650,  -685 },
+    {   1470,  -3863,   5352, -1684 },
+    {   3935,    -96,   3823,  -730 },
+    {   3769,   -430,   3168,   694 },
+    {   2556,    385,   3539,   512 },
+    {     77,  -1415,   5111,  2655 },
+    {   2724,  -2158,   6715,  -822 },
+    {   1832,   1001,   5385, -1900 },
+    {    900,   2198,   4464,  -559 },
+    {    441,     69,   5921, -1743 },
+    {  -1161,    738,   6732,  -308 },
+    {    257,   2035,   4091,   736 },
+    {   1607,   1288,   4355,   -23 },
+    {    -13,   1316,   4180,  1672 },
+    {   1511,   1336,   3057,  1435 },
+    {   2189,  -3813,   4530,   939 },
+    {   3632,   -706,   2646,  1375 },
+    {   4266,  -3761,   4241,  1077 },
+    {   3101,   -427,   5273, -1202 },
+    {   2293,    276,   4810,  -313 },
+    {   3430,  -1851,   3101,  2045 },
+    {   3453,  -2979,   5142,   942 },
+    {   1683,  -3281,   4802,  2002 },
+    {   3954,  -4715,   5611,   578 },
+    {   1272,   -155,   5085,   454 },
+    {    128,   -194,   5095,  1409 },
+    {    820,    880,   5797, -2658 },
+    {  -1095,    656,   5774,  1095 },
+    {    813,  -1669,   4320, -3251 },
+    {   -119,    518,   6372,  -651 },
+    {   2922,  -4299,   6115,  -877 },
+    {   4205,  -4273,   4004,  2642 },
+    {  -1211,  -3892,    224,  3127 },
+    {    -34,  -4371,   1321,  2318 },
+    {     77,  -6326,   1201,   828 },
+    {   3995,  -3775,   1958,  3233 },
+    {    178,  -3301,   1985,  3318 },
+    {   2330,  -3801,   1033,  3195 },
+    {   1413,  -5536,    826,  1709 },
+    {   2468,  -3499,   3653,  3631 },
+    {    741,  -4617,   1723,  2008 },
+    {   1246,  -3043,   2978,  3949 },
+    {   -343,  -4308,   2258,  2189 },
+    {   -682,  -4640,    454,  2272 },
+    {   1236,  -4829,   2491,  1642 },
+    {   -512,  -3766,   1182,  3052 },
+    {    119,  -3939,   3712,   971 },
+    {  -1145,  -4624,   1360,  2281 },
+    {    101,  -4746,   2866,  1255 },
+    {  -1500,  -5455,    539,  1637 },
+    {   -969,  -5909,   1414,  1128 },
+    {  -1261,  -4939,   -231,  2022 },
+    {   -226,  -5345,   1207,   705 },
+    {   2712,  -5109,   3205,  1866 },
+    {   -476,  -5913,    273,  1208 },
+    {  -2039,  -4464,    624,  2545 },
+    {  -2351,  -3930,   2019,  2673 },
+    {  -2675,  -4849,   1522,  1990 },
+    {  -1524,  -3461,   1446,  3204 },
+    {    477,  -5314,   1710,  1577 },
+    {    656,  -3729,   2346,  2511 },
+    {    550,  -5917,   1975,  1040 },
+    {   1728,  -4704,   3067,  1058 },
+    {     -9,  -5247,    506,  1760 },
+    {   -574,  -5135,   1675,  1672 },
+    {   2129,  -3781,   3444,  2313 },
+    {   1144,  -4439,   2214,  2529 },
+    {   1292,  -4160,   3185,  1833 },
+    {   2445,  -3262,   2534,  3227 },
+    {   2266,  -4401,   2023,  2400 },
+    {   -587,  -3602,   3408,  2067 },
+    {   -885,  -4951,   3228,  1174 },
+    {   -728,  -2711,   2807,  3552 },
+    {   1019,  -3043,   3195,  2954 },
+    {   1888,  -4615,   1140,  2454 },
+    {    660,  -5616,    754,   800 },
+    {  -1975,  -5371,   1649,  1585 },
+    {  -1544,  -5436,   2422,  1081 },
+    {   -422,  -5882,   2390,   750 },
+    {   1336,  -5557,   2441,  1230 },
+    {    136,  -4001,    267,  2854 },
+    {   -522,  -3289,   2226,  2728 },
+    {   -971,  -4580,   2471,   708 },
+    {    704,  -5306,   3300,  1001 },
+    {    325,  -3464,   3555,  2398 },
+    {    794,  -3686,    848,  3169 },
+    {    660,  -3017,   4584,  3242 },
+    {  -1486,  -3978,   2170,  1644 },
+    {  -1615,  -4650,   2688,  1844 },
+    {    750,  -4578,    538,  2239 },
+    {   1668,  -5849,   1455,  1031 },
+    {   3486,  -4681,   2030,  2183 },
+    {   2642,  -5429,   1696,  1761 },
+    {   4491,  -4502,   3538,  2767 },
+    {   3545,  -4528,   3514,  2982 },
+    {   3269,  -3676,   2758,  3966 },
+    {   5572,   1146,    209, -3379 },
+    {   7459,   1053,    593, -1896 },
+    {   4480,    200,   -310, -4259 },
+    {   5577,   -939,    242, -3992 },
+    {   8142,    442,   1257, -3083 },
+    {   5442,   1261,   1424, -3236 },
+    {   6260,   -183,   3125, -2532 },
+    {   7179,    889,   1618, -2548 },
+    {   6416,    932,   2379, -2487 },
+    {   7094,   2560,    961, -3392 },
+    {   7322,    463,   2732, -3735 },
+    {   6632,   1577,   1912, -3272 },
+    {   6312,   1349,   3028, -3460 },
+    {   6105,    386,   1213,  -977 },
+    {   5478,   1158,   1114,  -486 },
+    {   6493,    410,   1686, -2180 },
+    {   6378,   1881,   1333, -2240 },
+    {   5711,    812,   1958, -1300 },
+    {   6844,    877,    730, -1189 },
+    {   6824,   -245,   2249, -2000 },
+    {   7515,   1521,   1251, -3058 },
+    {   6697,   1051,   1300, -1749 },
+    {   6476,   1425,    811, -2773 },
+    {   7350,    465,    -76, -2849 },
+    {   6975,   2095,    567, -2492 },
+    {   4691,   1736,   2660, -2289 },
+    {   7837,   1456,    340, -2767 },
+    {   7930,    507,    838, -2074 },
+    {   6106,   1502,    766, -1110 },
+    {   4891,   -659,    835, -3954 },
+    {   7250,    141,   1369, -1523 },
+    {   7651,     67,   1651, -2298 },
+    {   7364,   -305,    601, -3132 },
+    {   7179,    193,   2491, -2871 },
+    {   6504,   -272,   2167, -1322 },
+    {   4456,    983,   2300,  -421 },
+    {   4817,    457,   1695,   371 },
+    {   6914,    555,    850, -3159 },
+    {   5904,   1030,    202, -1959 },
+    {   6258,    880,   2233, -4503 },
+    {   6029,     10,   2130, -3600 },
+    {   6449,    985,   1129, -3963 },
+    {   6616,    -18,   -111, -3285 },
+    {   4496,    775,    817, -4276 },
+    {   6134,   2338,   1470, -2973 },
+    {   6911,    152,    430, -1946 },
+    {   4053,    991,   3218, -1193 },
+    {   5435,   1285,   3124, -2412 },
+    {   5507,   1836,   1935, -1988 },
+    {   5240,    689,   2189, -2670 },
+    {   6638,   1719,    606, -1799 },
+    {   5556,   -180,    129, -2595 },
+    {   5644,   1918,   1281, -4316 },
+    {   6410,   1088,   -282, -3117 },
+    {   6503,   1841,    312, -3514 },
+    {   6947,     20,   1358, -3886 },
+    {   5464,   2109,   2398, -3194 },
+    {   5616,   -407,   2140,  -498 },
+    {   6121,   2707,   2379, -4096 },
+    {   7303,   1846,   2266, -4095 },
+    {   5444,    470,   2718, -1553 },
+    {   5817,   -645,   3285, -1349 },
+    {   5625,   1427,   1103, -1991 },
+    {   6041,   -806,   1196, -2943 },
+    {   3050,  -5722,   4070, -5460 },
+    {   3420,  -4386,   4078, -5155 },
+    {   6020,  -3982,   7268, -2689 },
+    {   7502,  -4317,   7894, -3973 },
+    {   4156,  -3558,   5247, -4316 },
+    {   4725,  -4401,   7290, -1540 },
+    {   6688,  -5122,   8216, -3210 },
+    {   9176,  -6576,   9276, -4963 },
+    {   8706,  -5708,   7987, -4621 },
+    {   7060,  -3535,   6532, -3308 },
+    {   5600,  -2719,   5363, -1568 },
+    {   4661,  -2803,   6263, -4716 },
+    {   3673,  -3636,   6147, -3433 },
+    {   5305,  -2585,   6073, -2638 },
+    {   7614,  -1962,   6079, -5266 },
+    {   6760,  -3366,   7382, -4322 },
+    {   6385,  -3883,   4797, -1353 },
+    {   8182,  -5120,   4298, -4641 },
+    {   9130,  -6198,   4975, -3063 },
+    {   7421,  -5436,   5576, -3713 },
+    {   3483,  -4898,   5443, -2745 },
+    {   4907,  -5643,   6390, -4105 },
+    {   8119,  -7008,   7992, -6764 },
+    {   6528,  -6122,   6967, -5590 },
+    {   5890,  -4190,   6624, -5688 },
+    {   6815,  -7934,   7275, -5456 },
+    {   5434,  -4306,   5169, -5378 },
+    {   4364,  -6436,   5376, -2604 },
+    {   8152,  -3404,   5913, -5048 },
+    {   7983,  -4863,   4262, -2461 },
+    {   8023,  -6188,   6238, -5062 },
+    {   6753,  -3692,   3935, -3723 },
+    {   6826,  -4760,   3284, -4051 },
+    {   7224,  -7423,   4492, -3875 },
+    {   6904,  -2590,   6587, -6248 },
+    {   6106,  -1944,   7345, -5506 },
+    {   4956,  -2990,   7808, -3146 },
+    {   6908,  -6885,   5949, -1288 },
+    {   7162,  -6058,   3419, -3401 },
+    {   7015,  -7080,   6907, -3018 },
+    {   6971,  -6832,   5646, -3273 },
+    {   8014,  -5546,   5471, -1544 },
+    {   6792,  -2220,   5105, -2879 },
+    {   8494,  -3974,   4408, -3999 },
+    {   9591,  -4866,   6027, -4558 },
+    {   5264,  -5161,   6101,  -738 },
+    {   5803,  -6141,   5197, -5231 },
+    {   4657,  -6822,   3232, -5189 },
+    {   4791,  -5135,   3809, -4665 },
+    {   6108,  -5103,   2379, -3873 },
+    {   4680,  -3909,   3234, -5093 },
+    {   5802,  -3853,   3795, -4984 },
+    {   4360,  -7483,   4802, -3877 },
+    {   5429,  -7517,   5911, -3717 },
+    {   6866,  -2280,   4880, -4634 },
+    {  10131,  -4628,   4414, -4092 },
+    {  10811,  -5189,   7746, -5337 },
+    {   5663,  -8941,   5287, -5680 },
+    {   8023,  -5991,   7403, -2796 },
+    {   9669,  -6919,   6525, -4932 },
+    {   7275,  -3796,   4962, -2547 },
+    {   8848,  -4806,   5677, -3080 },
+    {   8128,  -4308,   7749, -6569 },
+    {   4032,  -5196,   2282, -6239 },
+    {   6593,    700,   -229,   304 },
+    {   8260,    539,    -66, -1259 },
+    {   6605,    176,   -814,  -109 },
+    {   8057,      0,     -1,  -136 },
+    {   7382,    -38,   -484, -1129 },
+    {   8373,   -929,    682,  -454 },
+    {   7674,    690,  -1278,   546 },
+    {   7326,   -517,    406, -1283 },
+    {   7612,  -1715,  -1167,  1175 },
+    {   8590,    441,   -782,  -710 },
+    {   8572,  -1202,   -291,   260 },
+    {   7308,   -147,  -1785,   414 },
+    {   6787,   -353,   -672,   934 },
+    {   5177,   -133,    179,    82 },
+    {   4161,    -34,    447,  1497 },
+    {   5997,   -902,   1533,  -121 },
+    {   5727,   -871,  -1370,   945 },
+    {   8386,   -252,    293,  -823 },
+    {   6573,  -1354,    682,   616 },
+    {   7650,  -2096,    725,   457 },
+    {   8122,     78,    636, -1400 },
+    {   8421,    428,  -1620,   131 },
+    {   7341,  -1292,   -717,   186 },
+    {   7998,    -49,   -720,   266 },
+    {   5987,   -351,    669,   844 },
+    {   7314,  -1620,    250,  -603 },
+    {   7219,  -1562,   -572,  1994 },
+    {   8682,   -358,   -290,  -388 },
+    {   5810,    155,   -178,  1199 },
+    {   7246,    -12,   1042,  -786 },
+    {   7357,   -923,   1468,  -475 },
+    {   7801,    621,   -212,  -724 },
+    {   5346,   -514,   1210,  1356 },
+    {   8459,     36,   -127,  -779 },
+    {   6878,  -2429,    854,  1750 },
+    {   7280,  -1401,  -1353,  2845 },
+    {   7579,  -2148,  -1463,  2087 },
+    {   6637,    946,   -872,   750 },
+    {   4807,  -1100,   1289,  2602 },
+    {   4495,    219,   1551,  1128 },
+    {   7639,    506,    446, -1107 },
+    {   6359,    188,   1009,  -115 },
+    {   6641,  -1820,   1655,   723 },
+    {   5394,  -2382,   1604,  2542 },
+    {   6021,  -2644,   2396,  1407 },
+    {   4698,    882,    245,  1525 },
+    {   8103,    573,   -798,  -349 },
+    {   8045,   -519,    997, -1092 },
+    {   7571,   -122,    227,  -338 },
+    {   5347,  -1200,    630,  1718 },
+    {   7070,    790,    218,  -544 },
+    {   7440,    728,   -527,   -20 },
+    {   6402,   -355,    197,  -736 },
+    {   4031,    771,    866,  1895 },
+    {   6009,    896,    445,   -31 },
+    {   5160,   1098,   -856,  1784 },
+    {   7980,   -886,  -1293,  1396 },
+    {   6318,  -1361,   2423,   252 },
+    {   7547,   -699,    133,   506 },
+    {   8562,  -2344,    940,   264 },
+    {   5890,   1187,  -1425,  2194 },
+    {   6558,   -645,  -1311,  2621 },
+    {   4634,  -1671,   2075,  1623 },
+    {   5614,    105,   -816,  2376 },
+    {   6646,   1558,  -1365,   630 },
+    {   6998,   1150,  -2117,  -990 },
+    {   6555,   2311,  -1093, -1783 },
+    {   6682,   1430,  -2391, -1940 },
+    {   7861,   1555,  -2977, -1188 },
+    {   6745,   1723,   -459, -2085 },
+    {   7504,   1229,  -1666, -2060 },
+    {   7937,    671,  -2128, -1529 },
+    {   7139,    991,   -735, -2632 },
+    {   6867,   1592,  -1303, -2324 },
+    {   6401,   2230,  -1732, -2508 },
+    {   7201,   2184,  -2169, -1988 },
+    {   6636,   2190,   -995, -2840 },
+    {   7620,   2306,  -2089,  -651 },
+    {   7584,   1875,  -1438,  -631 },
+    {   9214,   1561,  -2464, -1139 },
+    {   6154,   1318,  -1237, -2917 },
+    {   7917,   2847,  -1797, -1599 },
+    {   8309,   2029,  -2555,  -465 },
+    {   8204,   1282,   -584, -2405 },
+    {   8440,   1035,  -1147, -1137 },
+    {   7107,   1858,    -60, -1568 },
+    {   6781,   2912,   -873, -1463 },
+    {   7603,   1316,   -319, -1249 },
+    {   7833,   1335,    -78, -1849 },
+    {   7930,   1141,  -1016,  -695 },
+    {   7883,   1610,  -1017, -1314 },
+    {   8069,   1409,  -1811,  -196 },
+    {   8319,   1031,   -582, -1590 },
+    {   5948,   1537,  -2153, -2373 },
+    {   8684,   1171,  -1871,  -850 },
+    {   8357,   2484,  -2411, -1292 },
+    {   6516,   2092,   -193, -1167 },
+    {   6112,   1697,     22,  -525 },
+    {   7161,    703,   -602, -1879 },
+    {   6047,   2351,   -807,  -219 },
+    {   8072,   1854,  -1817, -1553 },
+    {   6956,   1304,     76, -1011 },
+    {   6607,   1481,   -544,  -162 },
+    {   6958,   2541,   -265, -1938 },
+    {   6416,   2514,   -777,  -850 },
+    {   7272,   2110,   -899, -1171 },
+    {   7741,   2153,   -283, -2614 },
+    {   6482,   2041,  -1758, -1221 },
+    {   6762,    940,  -1862, -2281 },
+    {   5610,   1194,  -1691, -1561 },
+    {   7833,   2164,   -823, -1952 },
+    {   5460,   1438,   -848,  1189 },
+    {   6011,   1377,   -771, -1557 },
+    {   7679,    544,  -1134, -2214 },
+    {   7209,   1292,  -2714, -1564 },
+    {   5567,   1200,   -404,  -169 },
+    {   5853,   1461,  -1465,  -518 },
+    {   6782,    689,   -844,  -860 },
+    {   7330,   1337,  -1152,   -71 },
+    {   7189,   1506,   -653,  -685 },
+    {   6860,   2116,  -1403,  -240 },
+    {   8804,   1516,  -1391, -1760 },
+    {   7210,   2689,  -1498,  -989 },
+    {   7030,   3022,  -1441, -2083 },
+    {   5649,   1836,   -407,   525 },
+    {   7451,   3099,   -717, -2464 },
+    {   7384,   1656,  -2007,   398 },
+    {   6504,    707,  -1919,  -134 },
+    {  -1851,   3639,  -2279,  -695 },
+    {  -4037,   1644,    -77,  1329 },
+    {  -4025,   1960,  -1565,  -567 },
+    {  -3430,   2495,   -795,   368 },
+    {  -4771,   2480,    993,   756 },
+    {  -3431,   2058,  -2539,  -971 },
+    {  -3802,   3418,    380,   217 },
+    {  -3074,   3350,  -1652, -1056 },
+    {  -3705,    326,  -1650,  1535 },
+    {  -3122,   1281,  -1192,  1607 },
+    {  -4601,   1367,   -968,    53 },
+    {  -3808,    958,     44,  2560 },
+    {  -2079,   2530,  -1485,  1166 },
+    {  -3707,    343,  -2889,   180 },
+    {  -5249,   1431,    -31,   688 },
+    {  -4990,    125,   -704,  1270 },
+    {  -2771,   1334,  -2446,   746 },
+    {  -2292,    994,  -1527,  2630 },
+    {  -1261,   3070,  -2519,   268 },
+    {  -2544,   3890,  -1057,  -552 },
+    {  -4421,    255,  -1980,   530 },
+    {  -2951,    454,    -13,  3643 },
+    {  -2262,   1815,   -370,  2880 },
+    {  -2383,   3657,   -649,   576 },
+    {  -3541,   -161,  -1389,  2550 },
+    {  -4241,   1575,   1325,  2561 },
+    {  -2767,   4037,   1221,  1578 },
+    {  -3748,   2697,   1148,  1801 },
+    {  -4686,   2385,   -220,     0 },
+    {  -1531,   1645,  -2751,  1327 },
+    {    -45,   4032,   -799,  2298 },
+    {  -2915,   2280,    709,  2495 },
+    {  -1199,   3278,   -406,  2346 },
+    {  -2471,    116,  -2706,  2060 },
+    {  -2440,   2173,  -2894,  -344 },
+    {  -3375,   2287,   1781,  3226 },
+    {  -2153,   3568,   1827,  2918 },
+    {   -862,   2267,  -1626,  2527 },
+    {  -2698,   1135,    301,  4239 },
+    {  -2364,   2123,   1010,  3710 },
+    {  -2447,   3281,    -81,  1408 },
+    {  -2660,   4735,    472,   258 },
+    {  -1053,   3097,   2682,  2398 },
+    {  -3366,  -1037,  -1152,  -868 },
+    {   -643,   4242,   2212,  1259 },
+    {    971,   3991,    934,   643 },
+    {  -1617,   2002,   2139,  2195 },
+    {  -4897,    972,    784,  1719 },
+    {  -1275,   2992,   1039,  3821 },
+    {   -392,   4973,   -209,  1821 },
+    {  -1028,   4718,  -1479,  -137 },
+    {     50,   3914,    553,  2210 },
+    {    678,   4364,    359,  1303 },
+    {   -582,   4911,    514,  1671 },
+    {   1276,   3914,  -1252,  2934 },
+    {  -1496,   3984,    857,  2330 },
+    {    772,   4744,   -655,  2332 },
+    {   -799,   5283,   -439,   624 },
+    {   1341,   2937,    650,  2027 },
+    {  -1739,   4892,   1275,  1702 },
+    {   -892,   2596,   -151,  3951 },
+    {  -3532,   1090,   1292,    32 },
+    {    321,   3146,   2647,  1475 },
+    {    264,   4199,  -1591,  1317 },
+    {   -452,  -2357,   2266,  4192 },
+    {   3022,  -1033,  -2389,  5678 },
+    {  -1162,  -1342,   3543,  4990 },
+    {   -474,  -1477,  -1223,  5016 },
+    {   -699,  -2857,    900,  3835 },
+    {   -461,  -2255,   -117,  4626 },
+    {   1204,  -2062,  -1211,  4403 },
+    {   2192,  -3035,   -337,  3966 },
+    {    108,   -831,    279,  5643 },
+    {   1457,   -620,  -2908,  5276 },
+    {  -2527,    -78,   1085,  5460 },
+    {  -1978,  -1918,   -949,  4733 },
+    {     32,    367,  -1904,  5166 },
+    {   1890,  -1665,    440,  4752 },
+    {   -518,   -348,   2816,  4891 },
+    {   3695,  -2490,  -1374,  4603 },
+    {    246,  -1965,   3549,  3969 },
+    {   1100,  -3111,    656,  3737 },
+    {  -1379,    870,   -414,  4575 },
+    {    628,   -357,  -1227,  6179 },
+    {  -1129,  -1318,  -2457,  4576 },
+    {   -425,    -98,    -73,  6336 },
+    {    367,   -887,   2990,  4207 },
+    {   2091,  -1251,   2444,  3557 },
+    {  -1759,  -1610,   2046,  5273 },
+    {   3210,   1414,    -20,  2616 },
+    {   3303,  -2636,   1005,  4237 },
+    {   -327,  -3107,   -640,  3687 },
+    {   -197,    764,    572,  5486 },
+    {    646,   -767,   1388,  5464 },
+    {    104,   2742,   -228,  3907 },
+    {   -236,   1829,   -579,  4585 },
+    {  -2150,   -474,  -1525,  4006 },
+    {    -23,  -2632,  -2400,  3892 },
+    {    -12,  -1739,  -2910,  4867 },
+    {  -2310,   -368,   -102,  4583 },
+    {  -1991,  -2061,    533,  4531 },
+    {   3884,  -1446,   -153,  4393 },
+    {   1568,     14,   -289,  5268 },
+    {  -1376,   -253,  -2797,  3417 },
+    {   3193,  -2577,   2475,  3566 },
+    {   3418,    617,   1350,  1857 },
+    {   3792,    -24,   -272,  3370 },
+    {    153,   1159,   2906,  2877 },
+    {    511,   2162,   1548,  2741 },
+    {    262,    819,  -2791,  3734 },
+    {   4232,  -2015,   1486,  3477 },
+    {   2943,  -1110,  -1014,  5480 },
+    {   2842,    369,    703,  3476 },
+    {   3011,   1634,   -933,  3553 },
+    {   4412,  -1548,   -942,  5021 },
+    {  -1405,    593,   2372,  5267 },
+    {   2093,   2129,    896,  2365 },
+    {   4845,  -1980,      0,  3823 },
+    {  -2140,     81,   3278,  5637 },
+    {   1484,   2665,   -324,  3653 },
+    {     10,    192,   1620,  5291 },
+    {   2152,    738,  -2269,  5000 },
+    {   2102,   2748,  -1652,  4707 },
+    {   2855,  -2131,   -387,  5188 },
+    {   1173,    676,   1338,  3277 },
+    {   2340,  -2329,  -2064,  4095 },
+    {    861,  -2024,   1296,  5055 },
+    {   2189,   3225,   -695,  2626 },
+    {   6196,  -7079,   1943,  -822 },
+    {   4547,  -4813,   3261,  1856 },
+    {   4243,  -6904,   3443,   448 },
+    {   4581,  -7503,    946,   506 },
+    {   6626,  -7754,   3427,   470 },
+    {   3407,  -9088,   3269, -1496 },
+    {   4079,  -6464,   2304,   777 },
+    {   5621,  -9336,   2684,  -768 },
+    {   5351,  -6464,   5238,  -214 },
+    {   5961,  -8007,   1724, -3091 },
+    {   4213,  -8067,    603,  -246 },
+    {   7208,  -7403,   3168, -1738 },
+    {   6098,  -7700,    329, -1379 },
+    {   6525,  -6735,   4248, -1072 },
+    {   6073,  -6241,   2167, -2378 },
+    {   4609,  -9218,   3051, -1033 },
+    {   6813,  -7283,   1581, -1897 },
+    {   6126,  -6275,   2789,   681 },
+    {   4423,  -6538,   1621, -1692 },
+    {   6272,  -8298,   3167, -1855 },
+    {   6172,  -8558,   4498, -1169 },
+    {   4844,  -8588,   1647,  -366 },
+    {   6209,  -8807,   1581,  -369 },
+    {   5389,  -8059,    550,  -192 },
+    {   6654,  -9775,   2504, -1063 },
+    {   7103,  -7998,    806,   530 },
+    {   5662,  -6736,   1565, -3620 },
+    {   4165,  -9564,   4191, -2131 },
+    {   4526,  -7181,    576, -2875 },
+    {   4633,  -8623,   2807, -4742 },
+    {   3709,  -7794,   1815,    34 },
+    {   3634,  -8622,   2313,  -826 },
+    {   6991,  -8447,   2063, -3198 },
+    {   7757,  -9486,   2255,  -558 },
+    {   4149,  -7778,   4728, -1696 },
+    {   5767,  -7427,   1113,   707 },
+    {   4592,  -6261,   2329,  1864 },
+    {   3159, -10498,   1677, -4273 },
+    {   3534,  -9010,   2437, -3565 },
+    {   4479, -10821,   2715, -4942 },
+    {   3207,  -9805,   3054, -3886 },
+    {   4627,  -8189,   3018, -2354 },
+    {   5527, -10566,   3244, -2749 },
+    {   4346, -10127,   3335, -3084 },
+    {   6132, -10085,   3316, -1308 },
+    {   5629,  -9704,   2178, -3058 },
+    {   3603,  -8538,   1246,  -624 },
+    {   3737,  -8488,    395, -3167 },
+    {   5465, -11414,   2810, -4640 },
+    {   5306,  -7745,   2721, -3988 },
+    {   7000,  -9111,   1695, -1409 },
+    {   6663,  -7741,   2466, -4079 },
+    {   4083,  -7175,   1836, -4831 },
+    {   3613,  -9926,   1342, -3455 },
+    {   6588,  -8033,    457,  -258 },
+    {   4720,  -8102,     17, -1209 },
+    {   7414,  -8709,   1294,  -344 },
+    {   5437, -10030,   4043, -1704 },
+    {   4862,  -9281,   1558, -1431 },
+    {   6800,  -6403,   5113,   862 },
+    {   4623,  -8242,   2667,  -228 },
+    {   5919,  -5083,   3348,  2135 },
+    {   5985,  -8889,   2733, -5105 },
+    {   5029,  -5767,   4407,   719 },
+    {    354,  -6158,   -838, -3001 },
+    {    351,  -5943,  -2104, -1534 },
+    {   -633,  -7190,    -25, -4798 },
+    {  -1595,  -7235,  -3812, -1400 },
+    {    103,  -6197,  -2933,   -78 },
+    {  -1722,  -5020,  -3441, -4333 },
+    {  -1963,  -5644,  -4365,  -270 },
+    {   -846,  -5743,  -3477,   196 },
+    {   -191,  -5348,  -4054,  -469 },
+    {  -2515,  -7754,  -3495,  -818 },
+    {  -2090,  -6710,  -2701,   117 },
+    {   -546,  -7036,  -1398,   163 },
+    {   -278,  -7091,  -2662,  -536 },
+    {   -622,  -7962,  -2731, -1464 },
+    {  -1555,  -8118,  -3612, -2057 },
+    {  -1094,  -6280,  -2314,   505 },
+    {  -2556,  -8538,  -4024, -2247 },
+    {    109,  -7134,  -3107, -1823 },
+    {   -900,  -6954,  -3340,  -717 },
+    {   -605,  -7113,  -3656, -2154 },
+    {    837,  -6263,  -3211, -2177 },
+    {   -417,  -5810,  -3871, -1469 },
+    {  -1318,  -5649,  -4207, -3198 },
+    {    413,  -6765,  -2082,   -33 },
+    {  -3101,  -6450,  -4362,  -766 },
+    {    755,  -6489,  -2967,  -846 },
+    {   1117,  -7106,  -2452, -1352 },
+    {  -1202,  -8387,  -3072, -2897 },
+    {   -365,  -4894,  -3561, -2937 },
+    {  -2372,  -8776,   -265, -4441 },
+    {  -1224,  -8678,   -896, -5074 },
+    {   -755, -10096,   -600, -6623 },
+    {    300,  -8206,   -225, -4568 },
+    {  -1176,  -6824,  -2633, -3527 },
+    {  -2006,  -5443,  -1526, -5849 },
+    {  -1115,  -5540,  -2363, -4785 },
+    {   1059,  -6812,  -2543, -2654 },
+    {  -1976,  -6861,  -3062, -5508 },
+    {   -379,  -5328,  -2321, -3624 },
+    {  -2108,  -5860,  -4518, -1915 },
+    {   -379,  -7885,  -1329,  -594 },
+    {    774,  -5389,   -581, -5213 },
+    {  -2601,  -5083,  -1849, -4921 },
+    {   -176,  -5580,     74, -5075 },
+    {   -204,  -6780,   -190, -6232 },
+    {    418,  -7594,  -1987,  -820 },
+    {  -1873,  -8529,  -2926, -1609 },
+    {   1340,  -6362,   -919, -4975 },
+    {    577,  -7990,  -2044, -1873 },
+    {  -2572,  -7413,  -1745, -2224 },
+    {  -2037,  -7030,  -1461, -7138 },
+    {  -2559,  -8756,  -2039, -5836 },
+    {  -2079,  -6764,  -1209, -5669 },
+    {  -1613,  -7801,  -2006,  -685 },
+    {  -1865,  -6583,   -722, -3529 },
+    {   -589,  -6358,  -1377, -1003 },
+    {   -540,  -7514,  -1331, -3542 },
+    {    419,  -6192,  -1677, -4927 },
+    {  -2786,  -8763,  -2966, -5065 },
+    {  -2172,  -8411,  -1726, -4675 },
+    {  -3382,  -9833,  -3497, -5722 },
+    {  -2433, -10169,  -2077, -5775 },
+    {   -424,  -9451,  -1096, -3658 },
+    {   -537,  -8522,   -910, -1897 },
+    {  -5550,   2807,   1683,  -693 },
+    {  -6395,    635,   3573, -1246 },
+    {  -7544,   2280,   2140,    44 },
+    {  -8751,   1136,   2951,  -794 },
+    {  -5605,   2709,   2052,   916 },
+    {  -7650,    654,    869,   135 },
+    {  -6939,    967,   1409,   870 },
+    {  -7834,   2123,   3310,   974 },
+    {  -6935,   2818,   1274, -1678 },
+    {  -5605,   2233,   1013,   471 },
+    {  -7095,   1849,   1648,   198 },
+    {  -6636,   1634,    712,   -37 },
+    {  -7279,    978,    296,  -315 },
+    {  -7664,   3504,   3292,  -216 },
+    {  -7836,   1209,   1221,  -257 },
+    {  -7913,   2201,   1765, -1529 },
+    {  -7077,   3783,   2632, -1407 },
+    {  -5565,   1645,   1410,  -622 },
+    {  -6494,   2879,   1181,  -759 },
+    {  -7073,   3137,   3010,   550 },
+    {  -7249,   1839,    847,  -805 },
+    {  -6630,   2197,    282, -1096 },
+    {  -8836,   1573,   1988, -1090 },
+    {  -7809,   1274,    836, -1198 },
+    {  -7895,   2970,   3511, -1097 },
+    {  -6960,   1664,   1356, -2442 },
+    {  -6582,   2866,   2273,   307 },
+    {  -7221,    821,   2851, -1435 },
+    {  -6015,   1703,   2001, -2367 },
+    {  -8082,   1034,   2103,   239 },
+    {  -5952,   1912,    301,  -465 },
+    {  -6099,    841,    379,   567 },
+    {  -6343,     50,    494,   658 },
+    {  -6586,    983,    591,  -893 },
+    {  -5500,    869,   2187, -2479 },
+    {  -6482,     60,   1545,  -979 },
+    {  -6705,    515,   1974,   -53 },
+    {  -6460,   1755,   1325, -1275 },
+    {  -6093,   2617,   2465,  -623 },
+    {  -7330,   2161,    594, -2115 },
+    {  -7324,    762,   1593, -2004 },
+    {  -6385,    679,   1510, -2514 },
+    {  -6159,    241,   2976, -1631 },
+    {  -8583,   3030,   4045,  -162 },
+    {  -6299,     66,   2209, -2103 },
+    {  -5428,   1279,   3267, -1846 },
+    {  -6438,   1335,   2728, -1631 },
+    {  -8012,   1070,   2428, -1151 },
+    {  -6201,   2781,   2349, -1918 },
+    {  -5918,   1139,   3121,  -148 },
+    {  -6314,   2481,   3137, -1808 },
+    {  -7180,   1722,   2435, -1602 },
+    {  -6750,   1829,   3763, -1145 },
+    {  -6713,   1777,   2221,  1212 },
+    {  -7479,   1835,   3627,  -479 },
+    {  -7299,     10,   2406, -1593 },
+    {  -8249,   3129,    996, -2870 },
+    {  -8374,   1534,   1333, -1882 },
+    {  -7507,   3353,   1598, -2299 },
+    {  -7379,   2701,   2326, -1167 },
+    {  -8440,   2276,   2796,  -542 },
+    { -10348,   1527,   2649, -1165 },
+    {  -8184,   3614,   2574, -1738 },
+    {  -5539,   1574,   1733,  1138 },
+    {   9404,  -7652,     67,    79 },
+    {   8654,  -3972,   1358,   -60 },
+    {   8617,  -4794,    117,  2318 },
+    {   7886,  -4505,   1784,  1200 },
+    {   8636,  -6125,   3879, -1003 },
+    {   9654,  -6836,   1816,   205 },
+    {   9374,  -6553,    913,  1875 },
+    {   8020,  -6150,   1134,  2390 },
+    {   7786,  -4970,   2078, -1857 },
+    {   8691,  -6119,    711,   708 },
+    {   9039,  -5568,   2944, -1902 },
+    {   9955,  -5048,   1433,  -601 },
+    {   8089,  -6927,   3093, -2846 },
+    {   8487,  -7024,   2415,    19 },
+    {   9388,  -5287,   3577, -2655 },
+    {   8591,  -7371,   2300,  -996 },
+    {   9104,  -4763,   1453, -2558 },
+    {   7615,  -5457,    596,   164 },
+    {   9860,  -7047,   3433,  -614 },
+    {   8756,  -4404,   2235,  -964 },
+    {   9462,  -4660,    299, -1822 },
+    {  10119,  -5550,   2689, -1273 },
+    {  10915,  -7471,   2705, -1007 },
+    {  11433,  -7090,   1410, -1198 },
+    {   9882,  -7431,   2965, -1895 },
+    {   7628,  -5219,    769, -2661 },
+    {   8169,  -5318,   2262,    70 },
+    {   8846,  -6320,   1939,  -754 },
+    {   7147,  -5593,   1248,  -971 },
+    {  10652,  -5485,    935,   137 },
+    {   7778,  -6533,   2564, -1932 },
+    {   8878,  -5173,   1214,  -361 },
+    {   9828,  -4943,    282,   510 },
+    {  10042,  -6134,   3895, -1914 },
+    {   7965,  -6630,   3566,  -433 },
+    {   8573,  -4502,   3574, -1209 },
+    {   8398,  -4801,   1031, -1347 },
+    {  10136,  -7772,   2612,  1547 },
+    {   9890,  -7280,   1768, -1083 },
+    {   8407,  -6585,   -706,   -58 },
+    {   7976,  -7582,    229,  -131 },
+    {  10481,  -8866,   1166,  -147 },
+    {  10914,  -4342,   3189, -2412 },
+    {  10440,  -5198,   -104, -1109 },
+    {  11227,  -6530,   2381, -2449 },
+    {   8487,  -8064,   1086,   230 },
+    {   9975,  -6123,   -857,  -134 },
+    {   8339,  -6498,   1232, -2337 },
+    {  11042,  -4506,   1119, -2098 },
+    {  12563,  -5592,   1837, -2062 },
+    {  11801,  -5590,    632, -1296 },
+    {  10152,  -5617,   1511, -1917 },
+    {   7800,  -6473,     51, -1337 },
+    {   7941,  -5560,   2438, -3270 },
+    {   6554,  -3834,   2100,  1476 },
+    {   9065,  -5520,   -226, -1120 },
+    {  10794,  -7120,   -243,   122 },
+    {  10429,  -6968,    272,  -806 },
+    {   8942,  -8914,   1442,  -392 },
+    {   9969,  -5051,   2033, -2953 },
+    {   7275,  -4152,   3058,   -64 },
+    {  11127,  -5488,   4589, -3227 },
+    {   9626,  -6666,   2739, -2958 },
+    {   6943,  -5362,   4470,  1008 },
+    {  -7456,   -967,   2936, -1002 },
+    {  -8622,   -333,   6962,  2606 },
+    {  -7486,  -3392,   3668,  1287 },
+    {  -8053,   -827,   5148,  1097 },
+    {  -6610,    454,   4952,    96 },
+    {  -7701,  -1982,   3161,  -468 },
+    {  -7307,  -1132,   4071,   -36 },
+    {  -8125,   -271,   5199,  3862 },
+    {  -9182,  -1950,   2813,  1878 },
+    {  -9855,   -952,   4794,  3010 },
+    {  -7241,   1431,   4202,  2468 },
+    {  -9646,    157,   4766,  1046 },
+    {  -9371,   1230,   6009,  2958 },
+    { -11514,    -64,   8630,  5248 },
+    {  -6766,    565,   2766,  2140 },
+    {  -8426,     -9,   2852,  1271 },
+    { -11291,  -1113,   5087,  2937 },
+    {  -8297,   2092,   4495,  1264 },
+    {  -9983,    735,   3809,   -51 },
+    {  -9048,  -1000,   3191,  -308 },
+    {  -7331,  -1987,   2655,  1391 },
+    {  -7144,    -21,   4333,  2161 },
+    {  -6032,  -1540,   3543,   896 },
+    {  -7987,  -1036,   1985,  1529 },
+    {  -9264,   2004,   5194,   290 },
+    { -11308,   -840,   5754,  1654 },
+    {  -9130,  -2398,   4292,  2973 },
+    {  -6248,    838,   3563,  1223 },
+    {  -6819,  -2760,   3511,   119 },
+    {  -7213,  -2006,   4364,   762 },
+    {  -5431,  -1047,   4533,   166 },
+    {  -7098,   -641,   2021,   639 },
+    {  -8628,  -2249,   3588,   399 },
+    {  -6352,  -1498,   3560,  -648 },
+    {  -7033,  -2190,   4870,  2562 },
+    {  -7405,    -46,   3772,  -581 },
+    {  -6104,    796,   5143,  1965 },
+    {  -5787,    943,   5784,  3030 },
+    {  -8367,   1465,   7192,  4097 },
+    {  -8259,    789,   5694,  1963 },
+    { -10614,  -1899,   5748,  2645 },
+    {  -8258,   -805,   3698,  2275 },
+    {  -6877,   -972,   6431,  3160 },
+    {  -6483,    363,   7018,  3129 },
+    {  -6283,  -1358,   5191,  1524 },
+    {  -8853,  -3157,   4119,  1741 },
+    {  -6086,   -267,   3883,  -835 },
+    {  -7254,   1032,   6613,  4017 },
+    { -11470,  -3350,   4649,  3426 },
+    {  -6743,    481,   6148,  1239 },
+    {  -5394,   -166,   5309,  3165 },
+    {  -7958,   1068,   4268,  -240 },
+    { -10520,   2256,   7916,  2828 },
+    {  -5132,     -4,   5739,  1176 },
+    {  -8643,    120,   3255,  -629 },
+    {  -9631,   1974,   8870,  4362 },
+    { -10663,  -1221,   3733,   589 },
+    {  -8224,  -1843,   5806,  2655 },
+    {  -8282,   1255,   8647,  3478 },
+    { -12311,  -1505,   9043,  6256 },
+    { -11312,   -856,   7136,  4681 },
+    { -11944,   -722,   7941,  3309 },
+    {  -7868,   -463,   6846,  4196 },
+    {  -8679,   -241,   7410,  5347 },
+    {   6759,  -4680,   -508,  1220 },
+    {   5176,  -6111,    944,   121 },
+    {   6843,  -5667,  -1368,  -533 },
+    {   5616,  -5884,  -1471,  -695 },
+    {   6030,  -5089,  -1808,  -940 },
+    {   7444,  -5463,    -52,  1881 },
+    {   4207,  -6079,   -506,  1571 },
+    {   6785,  -4410,   -649,  3084 },
+    {   4838,  -5214,   2026,  2998 },
+    {   4201,  -5790,    645,  1811 },
+    {   6930,  -5129,  -1940,  1698 },
+    {   6332,  -4627,    692,  3027 },
+    {   6285,  -4314,   -106,  3644 },
+    {   6255,  -5450,  -1975,   742 },
+    {   4199,  -4676,   -459,  1796 },
+    {   5592,  -5500,   1345,  1300 },
+    {   4358,  -5556,  -2236,   114 },
+    {   4620,  -5875,  -1563,   888 },
+    {   4892,  -7550,   -327,  -419 },
+    {   4734,  -7085,      7,   613 },
+    {   3883,  -5562,  -1969,  1080 },
+    {   5610,  -4990,   -204,   834 },
+    {   4117,  -6482,  -1271,   341 },
+    {   6585,  -5107,    892,  1169 },
+    {   6632,  -3683,    302,  3002 },
+    {   6326,  -5351,   -983, -1250 },
+    {   4382,  -7192,   -730,  -158 },
+    {   5227,  -6540,   -451,  1123 },
+    {   5468,  -6472,   -870, -1471 },
+    {   5191,  -6402,  -1365,  -127 },
+    {   7407,  -6317,   -973,  -336 },
+    {   4611,  -6530,   -820, -1980 },
+    {   4963,  -5159,  -2050,  -966 },
+    {   4414,  -5691,   -211,  -998 },
+    {   5954,  -5873,    750, -1749 },
+    {   4394,  -4796,  -1268,   254 },
+    {   7161,  -6214,  -1010,   689 },
+    {   4965,  -3598,   2372,  1711 },
+    {   6248,  -6180,    981,   864 },
+    {   6473,  -5336,    525,  -600 },
+    {   4591,  -6864,  -1131,  -900 },
+    {   6314,  -6440,  -1021,  -375 },
+    {   5838,  -6209,  -1199,   944 },
+    {   5308,  -5283,  -2100,  1267 },
+    {   4342,  -5860,  -1637, -1356 },
+    {   5680,  -4388,  -1227,  -104 },
+    {   4900,  -4098,   1449,  4046 },
+    {   4677,  -4284,   -106,  3190 },
+    {   7574,  -6173,   -848,  1859 },
+    {   6493,  -7207,   -131,   726 },
+    {   5513,  -5261,  -2117,     4 },
+    {   6191,  -7352,   -193,  -505 },
+    {   5885,  -4333,    324,  -134 },
+    {   6162,  -6081,   -312, -2044 },
+    {   4216,  -6200,  -1810,  -572 },
+    {   5652,  -7035,   -696,  -197 },
+    {   7131,  -7189,   -366,   -60 },
+    {   5032,  -4803,  -1514,  2832 },
+    {   7386,  -4610,   -606,  3489 },
+    {   4211,  -5031,   1221,  3047 },
+    {   4050,  -4653,   1584,  1469 },
+    {   6852,  -5302,  -1861,   206 },
+    {   7736,  -4816,  -1794,  3359 },
+    {   6290,  -3439,   1522,  2454 },
+    {   1768,   5990,  -5560, -2594 },
+    {   3903,   5326,  -1530, -1501 },
+    {   2472,   3738,  -2117, -4240 },
+    {   3260,   5448,   -904, -4733 },
+    {   1435,   7297,  -3676, -4102 },
+    {   4096,   5951,   -656, -3312 },
+    {   2178,   6009,  -3146, -3724 },
+    {   3787,   5493,  -5473, -1633 },
+    {   2998,   7286,  -3334, -3571 },
+    {   2894,   6576,  -4708, -2804 },
+    {    830,   6163,  -4286, -3348 },
+    {   4755,   5569,  -1730, -2739 },
+    {   4604,   6065,  -3562, -2605 },
+    {   2749,   5141,  -3986, -2775 },
+    {   3942,   4875,  -2143, -3340 },
+    {   2819,   8517,  -2004, -2724 },
+    {   2146,   6298,   -689, -3093 },
+    {   5196,   6504,  -3393, -1475 },
+    {   1851,   8386,  -1748, -1420 },
+    {   3474,   8572,  -3534, -2688 },
+    {   4503,   7560,  -3561, -2245 },
+    {   4433,   6219,  -2393, -1575 },
+    {   3506,   7248,  -2275, -1977 },
+    {   3490,   7409,  -3147,  -604 },
+    {   4214,   6447,  -3520,   516 },
+    {    619,   7034,   -829, -1705 },
+    {   1732,   7395,   -356, -2208 },
+    {   1226,   5204,  -3294, -3732 },
+    {   2027,   5619,  -1813, -4146 },
+    {   3078,   5877,     47, -2651 },
+    {   1654,   5458,    424,  -682 },
+    {   3163,   5464,  -2026,  -270 },
+    {   2884,   5375,   -685,  -530 },
+    {   2950,   7286,    -35, -2967 },
+    {   1986,   5066,   -597,   482 },
+    {   3459,   4308,  -3845, -2333 },
+    {   3155,   7037,  -1346, -4345 },
+    {   2193,   6696,   -717, -1319 },
+    {   3677,   5089,  -3892,  -487 },
+    {   2186,   5136,  -4186, -1492 },
+    {    773,   5796,   -917,   817 },
+    {   2489,   6546,  -3570, -2117 },
+    {   1223,   6469,  -1362,   -33 },
+    {    271,   6061,  -1466, -1725 },
+    {   2540,   5171,  -1847,  1032 },
+    {   2548,   5251,  -2697,  1677 },
+    {    771,   7600,   -768,  -632 },
+    {   4710,   6647,  -4736, -1275 },
+    {   1369,   5917,  -2971, -1056 },
+    {    163,   5239,  -3499, -2275 },
+    {   2104,   4285,  -3211, -3286 },
+    {   1107,   7411,  -1972, -1671 },
+    {   2196,   7262,  -2310, -1926 },
+    {   -244,   6439,  -1745,  -839 },
+    {   3293,   3832,  -2890, -3000 },
+    {    419,   6443,   -379,  -407 },
+    {   3077,   4930,  -1156, -2869 },
+    {   2131,   5874,  -2330,   224 },
+    {    690,   6538,  -2212, -2841 },
+    {   1602,   4421,  -2515,  1542 },
+    {   3318,   9373,  -3032, -3477 },
+    {   5646,   7462,  -5153, -1463 },
+    {   4139,   7137,  -1539, -3321 },
+    {   3481,   9077,  -1645, -3653 },
+    {  -7747,    375,   -106,  -543 },
+    {  -8587,  -1379,   -586,  -461 },
+    { -10146,   -892,   2094,   694 },
+    {  -8103,    382,    504,  -325 },
+    {  -8548,    -92,     94,  -656 },
+    {  -7460,     38,    152,   388 },
+    {  -8266,   -271,   -459,  -883 },
+    {  -7935,   -664,  -1026,  -802 },
+    {  -8341,   -109,    853,   161 },
+    {  -8802,  -1355,   1099,   630 },
+    {  -8957,     -6,   1108,  -669 },
+    {  -7260,  -1520,    -43,  -407 },
+    {  -7555,   -174,    668, -2562 },
+    {  -9014,   -126,    227, -1191 },
+    {  -8184,    769,    290, -1375 },
+    {  -9476,     55,    962, -1528 },
+    {  -8679,    541,    755, -1030 },
+    {  -9842,  -1626,    838, -1588 },
+    {  -8513,   -702,    788, -1998 },
+    { -10101,  -1558,   -366, -1841 },
+    {  -8135,     78,   1479, -1813 },
+    {  -9128,   -454,    313, -1786 },
+    {  -7554,  -1084,    831, -2442 },
+    {  -7576,   -701,   2068, -1665 },
+    {  -7791,  -1481,   1587, -1808 },
+    {  -6701,   -596,    -97,   802 },
+    {  -7418,    -15,    684,  -963 },
+    {  -7127,   -477,   -139,  -426 },
+    {  -8097,   -110,    -36,  -264 },
+    {  -7620,  -1922,   -590,  -101 },
+    {  -7647,  -1201,    279,   660 },
+    {  -7856,  -1974,    758, -2271 },
+    {  -8496,   -167,   2232, -1143 },
+    {  -8506,  -1359,    624,  -740 },
+    {  -7274,  -1052,   1062,  -139 },
+    {  -7800,   -217,     91, -1794 },
+    {  -7030,  -1694,   -955,   615 },
+    {  -9020,  -1864,    101, -2182 },
+    {  -9400,   -740,    598,  -667 },
+    {  -8448,  -1184,   2024, -1272 },
+    {  -8812,   -570,   -897, -2384 },
+    { -10559,  -1286,    538, -1536 },
+    {  -8728,   -888,  -1089, -1397 },
+    {  -7080,  -1185,    636, -1252 },
+    {  -9880,    233,   2344,  -782 },
+    {  -7952,  -1326,   -378, -1947 },
+    {  -7207,   -378,   1408, -2237 },
+    {  -8467,  -1545,    902, -1987 },
+    {  -9163,  -1474,    924, -1739 },
+    {  -8159,   -992,    -77, -2744 },
+    {  -8343,    148,   -423, -1573 },
+    {  -9105,   -649,   -254, -1214 },
+    {  -8939,    456,    281, -1905 },
+    {  -8837,    179,   -394, -2634 },
+    {  -9145,    757,   1547, -1319 },
+    {  -9775,   -723,    441, -1680 },
+    {  -8910,   -686,   1529, -1525 },
+    {  -9492,  -1134,   2064,  -938 },
+    {  -6111,   -943,    677,   -31 },
+    {  -7411,   -613,   -814,    46 },
+    {  -9479,   -922,   -430, -2061 },
+    { -11298,  -1268,   1318, -1117 },
+    {  -8190,    832,    671, -2214 },
+    { -10453,   -550,   1672,  -886 },
+    {   1044,   9353,  -1651, -5423 },
+    {   1034,   8149,   -455, -6166 },
+    {    761,   8293,  -3214, -4838 },
+    {    938,   8077,    164, -5130 },
+    {   1295,   8673,   2582, -5490 },
+    {   -314,   7973,  -2395, -5231 },
+    {   -507,   9012,  -2497, -5775 },
+    {   2396,   8314,  -1022, -4673 },
+    {  -1516,   8501,   1950, -4969 },
+    {   -308,   7401,   1549, -4866 },
+    {   -112,   8340,   3003, -4920 },
+    {    -50,   9315,   1371, -5666 },
+    {   -659,   9449,   2496, -5547 },
+    {   2573,   9148,  -2270, -4783 },
+    {    830,   7104,   -438, -3907 },
+    {    522,  10672,   -677, -6483 },
+    {  -1190,  10108,   -510, -6518 },
+    {   -427,   8271,   -579, -6315 },
+    {   1602,   8113,  -1927, -4418 },
+    {  -2266,   8180,    448, -5190 },
+    {  -1633,   8816,   -226, -5771 },
+    {    759,   9481,   -105, -5813 },
+    {   2254,   6679,   -466, -5662 },
+    {    -88,   6946,    895, -5958 },
+    {  -1705,  10009,   1394, -5574 },
+    {    748,   7943,    540, -6692 },
+    {   1411,   7009,    232, -6145 },
+    {    697,   7290,  -1221, -5342 },
+    {  -1764,  10580,   1944, -3981 },
+    {  -1334,   9124,   1195, -3903 },
+    {   -905,  10067,    635, -5039 },
+    {    664,  10680,     49, -4625 },
+    {   1374,   9536,   -777, -3591 },
+    {    252,   9698,   -597, -2931 },
+    {    824,   9164,  -1014, -2144 },
+    {   2438,  10569,  -2289, -4424 },
+    {   2101,   7102,    507, -3614 },
+    {    294,   8051,   -432, -1518 },
+    {   -665,  10337,    547, -2852 },
+    {   1168,  11989,   -492, -5427 },
+    {   1344,   6416,    302, -5061 },
+    {  -1727,  12264,   1507, -4543 },
+    {    674,  10889,   -902, -3605 },
+    {   -582,   9504,    300, -3618 },
+    {    641,   7654,    689, -2109 },
+    {   2065,   9243,    508, -4367 },
+    {   1055,   8373,    688, -3144 },
+    {   -641,   8185,    986, -3307 },
+    {   1120,   7426,   1785, -3757 },
+    {   1660,   8070,   -593, -3104 },
+    {   2002,   9467,  -1722, -3475 },
+    {   2361,   8368,    100, -3709 },
+    {   -772,   7845,   -613, -4988 },
+    {   1485,   7430,   1896, -6127 },
+    {   -432,   7823,   -947, -2882 },
+    {    313,  11122,   -760, -4871 },
+    {    412,   8412,   -283, -4231 },
+    {   1585,  10402,  -1884, -3267 },
+    {    321,   6952,    773, -3016 },
+    {   -105,   9014,    121, -2249 },
+    {   1585,  10313,   -977, -4812 },
+    {   1619,  11869,   1306, -6876 },
+    {  -1168,   8886,    -81, -2500 },
+    {   -395,  10886,    733, -6490 },
+    {  -4949,   4274,   3992, -1054 },
+    {  -4241,   5299,   4262, -1584 },
+    {  -2710,   3862,   4552, -1673 },
+    {  -4608,   2472,   3672, -1715 },
+    {  -2843,   2816,   4003, -2326 },
+    {  -5229,   2964,   5636,    90 },
+    {  -4924,   3442,   5015, -1096 },
+    {  -1281,   3313,   5537, -2066 },
+    {  -3808,   1939,   4351,  -919 },
+    {  -1915,   2585,   4939, -1614 },
+    {  -3470,   1843,   5562,  -682 },
+    {  -3800,    870,   5827,   144 },
+    {  -4985,   1452,   4728,  -709 },
+    {  -3745,   2750,   7220,   259 },
+    {  -1875,   1900,   6514,  -826 },
+    {  -4329,   1574,   7192,  1304 },
+    {  -5408,   1444,   6208,   631 },
+    {  -3327,   5312,   5707, -1541 },
+    {  -6966,   3334,   4034,  1028 },
+    {  -7484,   4245,   4218,  -212 },
+    {  -6567,   5839,   4539,  -512 },
+    {  -5715,   5935,   3747, -1186 },
+    {  -6410,   4881,   3356, -1610 },
+    {  -5146,   2590,   2850,  2172 },
+    {  -5196,   4095,   2569,  -373 },
+    {  -5043,   6025,   4318,   692 },
+    {  -5525,   4884,   3513,   370 },
+    {  -6804,   7533,   5812,  -488 },
+    {  -5657,   2480,   4061,  1234 },
+    {  -3155,   1472,   6071,  1188 },
+    {  -3427,   5217,   3442,   858 },
+    {  -4698,   3013,   5517,  2586 },
+    {  -4449,   2226,   5418,  3580 },
+    {  -6395,   3547,   5487,  2028 },
+    {  -3500,   5019,   4787,     1 },
+    {  -4038,   2578,   3073,  3151 },
+    {  -2750,   1955,   4469,  3856 },
+    {  -5696,   1659,   6118,  2469 },
+    {  -4350,   1241,   6840,  3126 },
+    {  -5565,   5058,   5196,  1314 },
+    {  -1642,   4190,   3948,   607 },
+    {  -1233,   4108,   4850,  -640 },
+    {   -997,   3428,   3239,  1378 },
+    {  -6488,   2741,   6926,  2792 },
+    {  -4188,   3763,   4235,  2018 },
+    {  -3210,   3224,   5646,  1427 },
+    {  -5526,   6909,   5070,  -627 },
+    {  -2815,   3994,   3425,  1903 },
+    {  -2163,   2734,   5423,   145 },
+    {  -4149,   4247,   2355,   734 },
+    {   -410,   2521,   4138,   -16 },
+    {  -2411,   2385,   4927,  2105 },
+    {  -6077,   3591,   3114,   594 },
+    {  -4186,   4834,   5926, -1004 },
+    {  -7315,   3369,   5966,   448 },
+    {  -7042,   5721,   5771,   238 },
+    {  -4466,   3907,   3535, -1751 },
+    {  -2116,   3970,   6163, -1392 },
+    {  -7239,   2143,   8407,  3630 },
+    {  -5431,   4486,   6486,   -42 },
+    {  -1874,   1617,   6333,   519 },
+    {  -6478,   2629,   4634,  -505 },
+    {  -7784,   2342,   7216,  1365 },
+    {  -1154,   1432,   4831,  1544 },
+    {  -4964,  -5801,   1797,   506 },
+    {  -4436,  -6905,   1059, -1237 },
+    {  -5400,  -6886,    884,  -290 },
+    {  -6259,  -7103,    523,  -227 },
+    {  -4819,  -6450,   1412,  -450 },
+    {  -4056,  -6213,   1725,  -943 },
+    {  -5642,  -6091,   1357,   605 },
+    {  -4196,  -5678,   2187,  -173 },
+    {  -4726,  -5126,   2470,   321 },
+    {  -6642,  -5091,   1507, -1005 },
+    {  -5304,  -5250,   1944,  1579 },
+    {  -7179,  -5520,   1468,  -425 },
+    {  -6033,  -4895,   1876,  -955 },
+    {  -6595,  -5143,   2207,  1291 },
+    {  -4224,  -4943,   1846,  1792 },
+    {  -7128,  -6950,    539,   724 },
+    {  -4369,  -4901,   2590,  1103 },
+    {  -7413,  -5696,   1712,  1440 },
+    {  -5885,  -6821,    418,   871 },
+    {  -6828,  -5599,    710, -1563 },
+    {  -6123,  -5817,   1358,  1631 },
+    {  -5291,  -5622,    578,  2138 },
+    {  -7171,  -6004,    347,  2208 },
+    {  -6083,  -5251,   2132,   425 },
+    {  -4329,  -5721,    407, -2993 },
+    {  -5326,  -5056,   1119, -1837 },
+    {  -5485,  -5856,    185, -2389 },
+    {  -6529,  -5178,    403,  -697 },
+    {  -6719,  -4412,   2726,   871 },
+    {  -5126,  -5629,   1835,  -771 },
+    {  -5622,  -4361,   2973,   858 },
+    {  -5282,  -5895,     45,  -335 },
+    {  -4357,  -5656,   1696, -1558 },
+    {  -7139,  -6659,    627,  -409 },
+    {  -4415,  -6328,     35,  1306 },
+    {  -7639,  -6110,   1134,   197 },
+    {  -3626,  -5592,   2019,   901 },
+    {  -3547,  -5064,   1176,  1738 },
+    {  -5075,  -3899,   2087,   266 },
+    {  -4086,  -6311,   1479,   360 },
+    {  -6210,  -5220,   -199, -1477 },
+    {  -3910,  -5063,   1356,   -15 },
+    {  -7616,  -4977,    461,  2401 },
+    {  -6118,  -6131,   1258,  -563 },
+    {  -6127,  -4968,   1286,   -27 },
+    {  -4121,  -5852,   1113,  1476 },
+    {  -5157,  -4881,   1162,  -662 },
+    {  -4637,  -5031,   1179,   709 },
+    {  -5509,  -5452,   -397,  1224 },
+    {  -4597,  -6861,    646,   467 },
+    {  -6247,  -4043,    468,   278 },
+    {  -5336,  -6465,    874, -1472 },
+    {  -6998,  -6346,     78, -1798 },
+    {  -4915,  -4530,   2756,  -203 },
+    {  -6048,  -4373,   1468,  1052 },
+    {  -4273,  -7100,    942,  -323 },
+    {  -6552,  -4287,   2351,    69 },
+    {  -6954,  -4613,    722,  1521 },
+    {  -4201,  -5361,    763, -1562 },
+    {  -6881,  -5596,   -748,   669 },
+    {  -6695,  -3547,    -34,  1299 },
+    {  -3981,  -5728,     84,   111 },
+    {  -4663,  -4809,   2173, -1031 },
+    {  -6599,  -6077,   1303,   256 },
+    {  -7596,  -4265,  -5791, -4140 },
+    {  -6610,  -2758,  -5288, -3936 },
+    {  -5880,  -3865,  -6563, -3088 },
+    {  -7228,  -5510,  -7677, -3912 },
+    {  -8854,  -6553,  -8318, -5361 },
+    {  -9362,  -5249,  -6413, -4319 },
+    {  -4418,  -3110,  -6368, -4358 },
+    {  -5544,  -4203,  -6863, -5013 },
+    {  -3056,  -4316,  -5567, -3181 },
+    {  -3078,  -5999,  -5051, -2657 },
+    {  -5884,  -6292,  -5756, -4013 },
+    {  -4825,  -4549,  -5535, -4053 },
+    {  -4443,  -6126,  -5316, -1368 },
+    {  -3972,  -6341,  -6098, -2686 },
+    {  -5751,  -2781,  -5398, -6230 },
+    {  -4466,  -6135,  -5570, -3679 },
+    {  -4291,  -5992,  -3564, -5189 },
+    {  -7189,  -4429,  -7279, -6082 },
+    {  -5076,  -4433,  -2748, -5366 },
+    {  -6225,  -2825,  -6833, -5663 },
+    {  -2989,  -4792,  -3960, -4492 },
+    {  -7836,  -7773,  -7722, -5741 },
+    {  -6559,  -5703,  -5844, -5589 },
+    {  -7612,  -5438,  -4136, -3774 },
+    {  -4218,  -4176,  -6591, -2333 },
+    {  -4837,  -5063,  -6581,   322 },
+    {  -6590,  -5990,  -2980, -3847 },
+    {  -5558,  -2971,  -5489, -1932 },
+    {  -7001,  -5323,  -4975, -1697 },
+    {  -4694,  -2688,  -6904, -3044 },
+    {  -8511,  -5379,  -5767, -2549 },
+    {  -7548,  -5412,  -6522, -2572 },
+    {  -6597,  -4973,  -6423, -1274 },
+    {  -6415,  -4022,  -5168, -1072 },
+    {  -5528,  -5530,  -7218, -2345 },
+    {  -4845,  -4805,  -5943, -1227 },
+    {  -6049,  -7150,  -6744, -2161 },
+    {  -9061,  -7299,  -8542, -4375 },
+    {  -5010,  -5546,  -5416,   -82 },
+    {  -4135,  -4205,  -5109, -3373 },
+    {  -3311,  -5869,  -4007, -5061 },
+    {  -5993,  -6472,  -3962, -4718 },
+    {  -2966,  -5832,  -2821, -6305 },
+    {  -4851,  -5152,  -2067, -3930 },
+    {  -3620,  -4441,  -3362, -5836 },
+    {  -4469,  -5221,  -4534, -5592 },
+    {  -4022,  -6335,  -4321, -6107 },
+    {  -4899,  -4503,  -3084, -3725 },
+    {  -4490,  -8276,  -4620, -6236 },
+    {  -6591,  -4342,  -7365, -4063 },
+    {  -6498,  -5057,  -5553,   485 },
+    {  -6060,  -2714,  -7093, -4144 },
+    {  -6199,  -7774,  -7094, -4057 },
+    {  -7536,  -6424,  -6415, -4265 },
+    {  -7439,  -2454,  -6348, -4827 },
+    {  -5333,  -7565,  -4417, -4639 },
+    {  -4353,  -7103,  -4197, -2689 },
+    {  -5229,  -6549,  -5129, -6804 },
+    {  -6129,  -7701,  -5236, -4836 },
+    {  -6797,  -3983,  -3884, -4406 },
+    {  -6624,  -4467,  -4745, -5052 },
+    {  -3324,  -7596,  -2720, -6553 },
+    {  -5473,  -6284,  -1704, -4511 },
+    {  -4131,  -7263,  -3180, -5196 },
+    {  -7116,  -5565,  -3469,   685 },
+    {  -6002,  -6021,  -3858,   576 },
+    {  -3144,  -8203,  -1291,  -434 },
+    {  -6096,  -7027,  -4004,  1353 },
+    {  -3943,  -7709,  -2344,   -36 },
+    {  -4510,  -6767,  -2642,   631 },
+    {  -3657, -11541,  -2570, -3984 },
+    {  -5959,  -8854,  -1333,  -867 },
+    {  -6699,  -8866,  -1606,  -344 },
+    {  -3836,  -7961,  -2334, -2028 },
+    {  -3430,  -8045,  -3037,  -672 },
+    {  -3868,  -9184,  -3635, -1819 },
+    {  -4258,  -9060,  -2621, -1008 },
+    {  -3595,  -8693,  -2022,  -752 },
+    {  -4573,  -8048,  -3166, -2622 },
+    {  -4852,  -7903,  -1405,   256 },
+    {  -4591,  -7057,  -1560,   965 },
+    {  -6963,  -7655,   -980,   808 },
+    {  -5179,  -6641,  -3356,  1196 },
+    {  -7102,  -6941,  -2798,  2123 },
+    {  -6867,  -5834,  -3320,  -770 },
+    {  -5977,  -7369,  -2500,  -778 },
+    {  -6160,  -6400,   -934, -2543 },
+    {  -6741,  -7608,   -355, -1289 },
+    {  -6856,  -6466,  -1433, -1643 },
+    {  -4786,  -6292,  -4970,   376 },
+    {  -5407,  -8866,  -2255,  -400 },
+    {  -3814,  -6506,  -1387, -3620 },
+    {  -4998,  -6137,  -1200, -4092 },
+    {  -5123,  -9557,  -2849, -1306 },
+    {  -4259,  -6444,  -4395,  -338 },
+    {  -5221,  -6810,   -883,  1225 },
+    {  -6137,  -6215,  -2165,   554 },
+    {  -3895,  -6557,  -3176, -1829 },
+    {  -3886,  -8188,    -87,  -954 },
+    {  -7243,  -6707,  -2216,  -316 },
+    {  -5592,  -7606,     85,  -432 },
+    {  -3957,  -7945,   -504,  -144 },
+    {  -4617,  -7624,    218,  -312 },
+    {  -4797,  -8737,   -844, -1051 },
+    {  -4478,  -8516,  -1401,  -454 },
+    {  -4557,  -7058,   -302, -2332 },
+    {  -6623,  -7736,   -271,   -50 },
+    {  -3157,  -7532,  -1111, -2207 },
+    {  -3590,  -7300,  -1271,   517 },
+    {  -4442,  -7306,   -507,   590 },
+    {  -6458,  -7524,  -2807,   666 },
+    {  -4991,  -8466,  -3363,  -785 },
+    {  -7474,  -7541,  -1056, -1839 },
+    {  -7501,  -8316,   -938,  -180 },
+    {  -5329,  -7739,   -579, -2341 },
+    {  -4549,  -7063,   -176, -3539 },
+    {  -5191,  -8612,  -1504, -4250 },
+    {  -3083,  -7058,  -2251,    32 },
+    {  -4003,  -7043,  -1093,  -791 },
+    {  -5523,  -8093,   -678,  -114 },
+    {  -3022, -10265,  -2070, -3109 },
+    {  -3905,  -6274,   -182, -3652 },
+    {  -3269,  -9217,   -551, -2650 },
+    {  -3138,  -9314,  -1726, -1704 },
+    {  -4420, -10339,  -1744, -3459 },
+    {  -4163,  -8609,  -2298, -4113 },
+    {  -5566,  -6505,  -1241,  -463 },
+    {  -3130,  -9746,  -2352, -4884 },
+    {  -7825,  -3439,   1451, -1468 },
+    {  -8451,  -3318,   2360,  -435 },
+    {  -8462,  -4130,   1438, -1024 },
+    {  -9425,  -4564,   1328,  -689 },
+    { -11014,  -3202,   2278,  2080 },
+    {  -8269,  -2761,   -146,  -440 },
+    {  -7497,  -2618,   -166,   413 },
+    {  -8250,  -3060,    522, -2133 },
+    {  -8365,  -5366,   1347,  -451 },
+    {  -8589,  -3979,   2943,   714 },
+    {  -8111,  -2572,   1272, -1748 },
+    {  -7830,  -5193,    605, -1484 },
+    {  -8119,  -4736,   2141,   256 },
+    {  -7724,  -4769,   1463,  -812 },
+    {  -7363,  -3911,   2540,     4 },
+    {  -7974,  -3397,   2363,  1366 },
+    {  -7359,  -4204,   1752,  -958 },
+    {  -7622,  -3505,    660,   916 },
+    {  -9934,  -3665,   3165,   828 },
+    {  -8721,  -4162,     62,  1718 },
+    {  -9433,  -4768,   2722,  1234 },
+    {  -7960,  -4496,    138,  1528 },
+    {  -8198,  -3454,   -443,   631 },
+    {  -7756,  -2246,    655,  1137 },
+    {  -8841,  -3145,   1113,   829 },
+    {  -7817,  -3298,   1251,   230 },
+    {  -9413,  -2733,    323, -1862 },
+    {  -9408,  -4168,   1270,  1549 },
+    {  -9037,  -3892,   -942,   283 },
+    {  -8255,  -3849,   1301,  1762 },
+    {  -9057,  -3987,    -41,  -682 },
+    {  -9441,  -4187,   2019,  -111 },
+    {  -9740,  -3178,   1602,  -871 },
+    {  -8344,  -2474,   1461,  1506 },
+    {  -9752,  -2925,   1996,  1243 },
+    {  -9199,  -3796,    180,   537 },
+    {  -9060,  -2405,   1140, -1562 },
+    {  -9348,  -2376,    309,  -162 },
+    { -10786,  -3182,     -5, -1500 },
+    {  -8142,  -4540,   -434,  -826 },
+    {  -7528,  -2341,   1104,   -73 },
+    {  -9360,  -2658,   3062,    56 },
+    {  -8267,  -2335,   2000, -1193 },
+    { -12169,  -3154,   1287,  -640 },
+    { -11398,  -2120,    946, -1163 },
+    {  -8940,  -4559,    328, -1696 },
+    { -11025,  -4213,   2813,   840 },
+    {  -9224,  -3581,   2224,  2039 },
+    {  -8943,  -3337,   1248, -1298 },
+    {  -7900,  -4042,    485, -2080 },
+    {  -9221,  -1947,   2191,  -880 },
+    { -10762,  -1800,   2516,  -324 },
+    { -10095,  -2238,    981, -1335 },
+    { -11908,  -2808,   3255,   645 },
+    { -10640,  -4105,   1283,  -595 },
+    {  -7663,  -2863,   2467,  -797 },
+    { -10712,  -3854,   3710,  1538 },
+    { -10823,  -2893,   1408,  -801 },
+    {  -9874,  -3832,    256, -1638 },
+    { -10394,  -3391,   2315,   -94 },
+    { -11525,  -4079,   4153,  2122 },
+    {  -9546,  -2088,   1541,   481 },
+    {  -8731,  -2433,   1042,  2160 },
+    {  -7852,  -3977,  -1370,  1677 },
+    {   7072,  -3420,   1398, -1741 },
+    {   6180,  -1976,   1280, -3557 },
+    {   7692,  -1793,   2844, -1700 },
+    {   8363,  -1773,   3104, -2679 },
+    {   9213,  -3266,   3756, -3542 },
+    {   9650,  -2644,   1426, -1318 },
+    {   7712,  -2796,   3686, -1975 },
+    {   7316,  -3517,   2821,  -622 },
+    {   7434,  -2594,   2305, -2264 },
+    {   7237,  -1797,    255, -3114 },
+    {   8663,  -1983,   1338, -3056 },
+    {   6616,   -952,   4059, -2652 },
+    {   8823,  -1327,   1362, -1356 },
+    {   9938,  -1722,   1287, -2362 },
+    {   7207,  -1057,   1913, -1315 },
+    {   7508,  -1585,    870, -1982 },
+    {   8217,  -3680,   1417, -3170 },
+    {   8329,  -2541,   1684,  -585 },
+    {   8062,  -2335,    252, -2800 },
+    {   8204,  -4108,   3097, -2569 },
+    {   7701,  -3367,    576, -3008 },
+    {   7350,   -786,   2414, -2129 },
+    {   6948,  -2568,   1607,  -225 },
+    {   7684,  -2387,   1308, -3449 },
+    {   8306,  -3458,   2394, -1454 },
+    {   8438,  -2781,   1043, -1362 },
+    {   9175,  -2076,   2144, -1987 },
+    {   8347,  -2709,   3489, -4301 },
+    {   5696,  -2377,   2870,   851 },
+    {   8825,  -1243,   2219, -2603 },
+    {   8801,  -1614,    584, -2513 },
+    {   8413,   -384,   1421, -2244 },
+    {   9228,  -3050,   3279, -2164 },
+    {   6342,  -2698,   3547,  -107 },
+    {  10053,  -2476,   2837, -3168 },
+    {   7439,   -604,   3177, -3991 },
+    {   7749,  -1064,   4329, -4855 },
+    {   8655,  -2177,   2252, -3519 },
+    {   8490,   -228,   1958, -3233 },
+    {  10513,  -2968,   1911, -2340 },
+    {   8146,   -862,   1884, -1723 },
+    {   7788,   -666,   3004, -2891 },
+    {   7785,  -1620,   4133, -3417 },
+    {  10262,  -3731,   3455, -2971 },
+    {   8570,   -905,   4519, -4649 },
+    {   9129,  -2562,    463, -2465 },
+    {   9451,  -3587,   1904, -3056 },
+    {   6549,  -2236,   3010, -4523 },
+    {   7175,  -2684,   2967, -3458 },
+    {   9872,  -3278,   1054, -2472 },
+    {   9153,   -931,   1217, -2565 },
+    {   8789,  -3469,    753, -2568 },
+    {   6683,  -3791,   1797, -3968 },
+    {   6801,  -1977,   2311,  -452 },
+    {   6336,  -1572,   2612, -3264 },
+    {   7996,  -1008,    730, -2964 },
+    {   7521,  -1059,   1573, -3694 },
+    {   8148,  -3973,   2600, -3572 },
+    {   7765,  -1532,   2528, -3856 },
+    {   7404,  -3918,   4472,  -143 },
+    {   8894,  -1398,   3299, -3685 },
+    {   5768,  -2041,   1487,  -637 },
+    {   5131,  -2865,   2463,  -811 },
+    {   6439,  -1568,   3500, -1550 },
+    {  -8878,  -6798,  -5319, -1452 },
+    {  -6332,  -9713,  -3112,  -990 },
+    {  -8444,  -6316,  -3694,  -687 },
+    {  -6123, -10840,  -3637, -4358 },
+    {  -4784,  -9580,  -4577, -2581 },
+    {  -6108, -10515,  -4859, -2524 },
+    {  -7605,  -7518,  -2327, -2797 },
+    {  -9662,  -8775,  -2467, -2010 },
+    {  -6494,  -7523,  -4715,  -118 },
+    {  -8290,  -8982,  -1672,  -317 },
+    {  -8798, -11051,  -3888, -1426 },
+    {  -6273,  -6623,  -6791,  -142 },
+    {  -8313,  -7668,  -2141, -1275 },
+    {  -6453,  -8412,  -3589, -4102 },
+    {  -6747,  -7750,  -5690, -2498 },
+    {  -7814,  -6693,  -3174, -2446 },
+    { -10383, -10130,  -3931, -2364 },
+    { -10606,  -8467,  -5539, -2772 },
+    {  -9475,  -6671,  -3305, -2271 },
+    {  -8982,  -9457,  -5635, -4005 },
+    { -10111,  -7965,  -6515, -4180 },
+    {  -7301,  -6479,  -5364,   720 },
+    {  -9543,  -8999,  -7921,  -912 },
+    {  -9534,  -8562,  -3469,  -384 },
+    {  -7601, -10344,  -3205, -1127 },
+    {  -8088,  -8620,  -4954, -2888 },
+    {  -8202,  -8406,  -7038, -3775 },
+    {  -7312,  -8324,  -3334, -1775 },
+    {  -8566,  -9262,  -8071, -4174 },
+    {  -7068, -11300,  -5573, -2907 },
+    {  -8295,  -8952,  -4366, -1544 },
+    { -11104, -10210,  -2285,  -384 },
+    {  -5213,  -7520,  -5008, -1339 },
+    {  -5889,  -7940,  -5987, -1385 },
+    { -10816,  -8201,  -4153, -1485 },
+    { -10277,  -8919,  -6315, -1652 },
+    {  -5888, -10320,  -3821, -1733 },
+    { -10497,  -7181,  -6083, -3032 },
+    {  -7721,  -9724,  -6591, -5336 },
+    {  -5688,  -7894,  -3486, -2552 },
+    { -10014, -10500,  -3247,  -820 },
+    {  -6301,  -8765,  -4506, -2923 },
+    {  -8261,  -7847,  -6213, -1552 },
+    { -10212,  -7481,  -8113, -3954 },
+    {  -6938, -10874,  -6074, -4703 },
+    {  -7183, -10968,  -4446, -1773 },
+    {  -7120,  -9193,  -1966, -2509 },
+    {  -6234,  -9263,  -2313, -4284 },
+    {  -8503,  -9857,  -2429,  -608 },
+    {  -9372,  -7844,  -8391, -2120 },
+    {  -7951,  -7157,  -6535,   -11 },
+    {  -7256,  -9473,  -2172,  -660 },
+    { -10063,  -9612,  -2515,   -15 },
+    {  -6684,  -9134,  -6109, -4206 },
+    {  -8204, -11932,  -5220, -2306 },
+    {  -9710,  -6706,  -4115, -3275 },
+    {  -6855,  -7078,  -2409, -4447 },
+    {  -7344,  -7673,  -4479, -4116 },
+    {  -8851,  -6842,  -4927, -2948 },
+    {  -8927, -10452,  -5633, -2194 },
+    {  -8627,  -9002,  -7176, -1575 },
+    {  -8209,  -9722,  -7021, -3324 },
+    {  -3770, -10249,  -3623, -4816 },
+    {  -8183,  -7465,  -4090,   646 },
+    {  -8163,  -7149,    200,   498 },
+    {  -8289,  -6266,    686,  -206 },
+    { -10030,  -6241,  -1032, -1864 },
+    {  -8793,  -8327,   -773,  -169 },
+    {  -9149,  -6215,    969,   -15 },
+    {  -8303,  -5859,     -7,  2006 },
+    {  -9682,  -7283,    255,  1322 },
+    {  -9293,  -7227,     71,  -231 },
+    {  -8525,  -6215,    287,  -837 },
+    { -10477,  -5379,   1159,  1449 },
+    { -10726,  -7856,   -130,   102 },
+    {  -8694,  -7461,  -1210,   690 },
+    {  -9367,  -5324,   1103,  3170 },
+    { -10686,  -8055,   -831,  1633 },
+    {  -9201,  -6873,  -2704,  2258 },
+    {  -8421,  -5358,  -1405,   226 },
+    {  -9066,  -5830,   -307, -1571 },
+    { -11150,  -7381,  -2746,  -900 },
+    {  -9978,  -5925,  -2006,  -437 },
+    {  -9464,  -4741,   -273,  1061 },
+    { -10543,  -6684,  -1113,  1660 },
+    { -10073,  -5576,   1083,  -269 },
+    {  -8826,  -5763,   1600,  1486 },
+    { -10445,  -9071,  -1253,   -64 },
+    { -12085,  -5799,      2,   769 },
+    { -12939,  -6663,   1650,  1437 },
+    { -10932,  -6434,  -1252,  -649 },
+    { -11650,  -7826,  -2053,   710 },
+    { -12122,  -6733,  -1889,  -731 },
+    {  -9093,  -6095,  -2463,  -842 },
+    { -10977,  -4364,    469,   420 },
+    { -11488,  -6908,   -521,   893 },
+    {  -9669,  -5478,   -842,   337 },
+    { -10606,  -5203,   -632, -1361 },
+    { -10198,  -6284,   1662,  1277 },
+    { -10135,  -5292,   2435,  3493 },
+    { -11027,  -6561,    655,    56 },
+    { -10977,  -5030,   1127,  -358 },
+    { -12766,  -3986,   1348,  -335 },
+    { -14244,  -7731,    264,   317 },
+    { -15124, -10309,   -508,  1447 },
+    { -12821,  -8638,   -608,   137 },
+    { -13076,  -8693,  -2852,  -431 },
+    { -11156,  -5546,  -2252, -1600 },
+    {  -8692,  -7366,   -819, -1223 },
+    { -12507,  -9816,  -1714,  -121 },
+    { -10712,  -6666,    544,  3349 },
+    { -12462,  -5890,  -2491, -2318 },
+    { -12468,  -7226,    437,   232 },
+    { -11300,  -5226,   2068,   687 },
+    { -11994,  -8320,   -626,  2728 },
+    { -12222,  -5476,   1142,    18 },
+    { -10277,  -8122,  -2418,  2003 },
+    { -13418,  -6115,  -3563, -2802 },
+    { -14759,  -9834,  -1243,    21 },
+    { -13699,  -5665,   1525,   507 },
+    { -16269,  -9476,   -701,   163 },
+    { -12677,  -5437,   -247, -1019 },
+    { -11827,  -4295,   -181, -1243 },
+    { -12847,  -4496,   2984,  1123 },
+    { -13860,  -7915,  -1166,  -547 },
+    { -12276,  -8145,  -2290, -1527 },
+    { -11417,  -4830,   2983,  1854 },
+    { -11793,  -6002,   1163,  1940 },
+    {  11443,  -4920,  -3235,  3151 },
+    {  11300,  -6616,  -1506,  1175 },
+    {   9198,  -4628,  -2060,  2390 },
+    {  10532,  -4027,   -643,   912 },
+    {   9902,  -3573,  -1606,  1327 },
+    {   9653,  -3536,  -2240,  1869 },
+    {   9948,  -5171,   -423,  2662 },
+    {  12316,  -4004,  -1989,   281 },
+    {  12125,  -4800,  -1265,  -163 },
+    {  10650,  -2617,  -2337,  1462 },
+    {   9909,  -4968,  -2376,   916 },
+    {  12944,  -4647,  -1958,   460 },
+    {  12988,  -5283,  -1141,    41 },
+    {  12321,  -2915,  -3621,  1025 },
+    {  11449,  -2894,  -2728,   351 },
+    {  12087,  -3041,  -2002,   -32 },
+    {  11558,  -4031,  -1343,  -399 },
+    {  12983,  -3740,  -3516,  1245 },
+    {  12099,  -2515,  -2752,   225 },
+    {  12515,  -3465,  -2701,   550 },
+    {  14683,  -5022,  -5272,  2996 },
+    {  12260,  -3383,  -1215,  -528 },
+    {  13810,  -5422,  -2443,  1166 },
+    {  13421,  -5378,  -1886,   721 },
+    {  12961,  -4259,  -2594,   796 },
+    {  12266,  -2104,  -4768,  1591 },
+    {  13523,  -4710,  -3045,  1342 },
+    {  12437,  -2099,  -5610,  2117 },
+    {  11850,  -2183,  -3497,   661 },
+    {  12275,  -3936,   -597,  -697 },
+    {  12459,  -5253,   -517,  -544 },
+    {  12835,  -4094,  -1322,  -168 },
+    {  14360,  -5677,  -3305,  1859 },
+    {  13905,  -4552,  -4309,  2117 },
+    {  11559,  -3412,  -1847,   -81 },
+    {  13379,  -3167,  -5764,  2746 },
+    {  11910,  -1634,  -4342,  1052 },
+    {  12662,  -4742,     71,  -974 },
+    {  13057,  -3254,  -4424,  1705 },
+    {  15046,  -5706,  -4851,  3019 },
+    {  14162,  -4142,  -5514,  2843 },
+    {  12764,  -1845,  -6684,  2888 },
+    {  13714,  -2374,  -7838,  3857 },
+    {  13295,  -1663,  -8293,  4073 },
+    {  10032,  -4152,  -3403,  1421 },
+    {  10942,  -5386,  -2222,   950 },
+    {  10532,  -6385,  -1750,  1925 },
+    {  10273,  -5972,  -1534,   643 },
+    {  10605,  -4782,  -1695,    27 },
+    {  10988,  -5153,  -1123,  -341 },
+    {  11629,  -5884,  -1060,    48 },
+    {  10441,  -4045,  -2431,   311 },
+    {  10788,  -3595,  -4171,  1807 },
+    {  12110,  -5686,  -2127,   976 },
+    {  11746,  -4773,  -2639,   891 },
+    {  11541,  -5299,  -3031,  1732 },
+    {  11416,  -2559,  -5359,  2198 },
+    {  11583,  -5376,   -704,   677 },
+    {  10416,  -3214,  -3516,   872 },
+    {   9651,  -5435,  -1618,  3255 },
+    {   9973,  -5133,   -996,  3923 },
+    {  11707,  -4643,   -430,  -796 },
+    {  10994,  -2709,  -3587,  2302 },
+    {  10716,  -5118,   -645,   270 },
+    {  14100, -10314,   1095,  1531 },
+    {  12944,  -8049,   1105,  -741 },
+    {  13276,  -7035,   -511,   274 },
+    {  14008,  -7254,   -283,   139 },
+    {  11594,  -6536,    -91,  1671 },
+    {  11732,  -8645,    746,    15 },
+    {  14613,  -7085,  -1578,  1183 },
+    {  13083,  -6224,   -750,    -4 },
+    {  13988,  -6256,  -1592,   820 },
+    {  14678,  -8683,    441,   126 },
+    {  15571,  -8872,   -521,  1139 },
+    {  15642,  -9533,    341,   697 },
+    {  15960,  -9586,   -168,  1121 },
+    {  15464, -10239,   1433,    -1 },
+    {  14934,  -7887,  -1046,  1080 },
+    {  15252,  -7630,  -1899,  1628 },
+    {  15485,  -8384,  -1234,  1484 },
+    {  15962,  -8638,  -1815,  1931 },
+    {  16501, -10664,    398,  1167 },
+    {  16146, -10145,    411,   918 },
+    {  14573,  -7475,   -697,   601 },
+    {  14302,  -7996,     28,   257 },
+    {  14769,  -6792,  -2286,  1574 },
+    {  14144,  -6137,  -2169,  1257 },
+    {  14770,  -6271,  -3111,  1933 },
+    {  14110,  -8312,   1083,  -531 },
+    {  15235,  -6991,  -2993,  2174 },
+    {  13222,  -5805,    547,  -891 },
+    {  14796,  -8762,   1254,  -246 },
+    {  16040,  -9181,  -1005,  1551 },
+    {  16487, -10086,   -373,  1420 },
+    {  15077,  -9479,    966,    51 },
+    {  13026,  -6468,    932, -1080 },
+    {  12703,  -6152,    -33,  -573 },
+    {  15641,  -6810,  -4128,  2874 },
+    {  13282,  -7673,   1583, -1283 },
+    {  12373,  -7150,   1512,  -917 },
+    {  12992,  -7751,   -678,   783 },
+    {  10907,  -6858,   -313,  2597 },
+    {  13026,  -8963,    125,  2152 },
+    {  12770,  -9946,   1957,  -505 },
+    {  12482,  -6849,  -1268,   833 },
+    {  13790,  -6181,   -138,  -279 },
+    {  12709,  -8382,   2044,   227 },
+    {  12244,  -6630,    203,  -457 },
+    {  14209,  -6816,  -1032,   632 },
+    {  15134,  -8267,   -288,   640 },
+    {  13619,  -6157,  -1090,   356 },
+    {  14044,  -7413,    725,  -484 },
+    {  12958,  -7753,   2585, -1980 },
+    {  13188,  -8396,   2306, -1558 },
+    {  14379,  -9980,   2132,  -688 },
+    {  14275,  -9857,   1162,   179 },
+    {  13690,  -8648,   1621,  -889 },
+    {  11770,  -6829,   -746,   278 },
+    {  12732,  -8202,    286,    90 },
+    {  13630, -10146,   1867,  -207 },
+    {  12072,  -8740,   1299,  -645 },
+    {  12852,  -9492,   1226,    62 },
+    {  11792,  -7382,    -54,  -116 },
+    {  13779,  -9014,    487,   351 },
+    {  11951,  -7729,    121,   834 },
+    {  11970,  -9781,   2276,    -4 },
+    {  12680,  -7984,   2787,  -787 },
+    {  13300, -14488,   6408, -1927 },
+    {  13635, -15355,   9153, -3073 },
+    {  12804, -13566,   5517, -1625 },
+    {  16624, -10854,   1690,    28 },
+    {  20387, -18532,   6162,  -261 },
+    {  16515, -12642,   3392,  -519 },
+    {  15800, -11095,   2151,  -202 },
+    {  16824, -11790,   1651,   599 },
+    {  17604, -13213,   2563,   538 },
+    {  17892, -14177,   3562,   147 },
+    {  16987, -11399,    869,  1052 },
+    {  17003, -12456,   2442,   265 },
+    {  21657, -21806,   9198, -1250 },
+    {  16825, -13341,   3980,  -686 },
+    {  17525, -12714,   1887,   805 },
+    {  16419, -11034,   1216,   617 },
+    {  20931, -19939,   7469,  -684 },
+    {  18452, -15390,   4573,  -191 },
+    {  14778, -10077,   2841, -1209 },
+    {  17402, -13319,   3042,   160 },
+    {  19365, -17922,   7087, -1061 },
+    {  16298, -11941,   2810,  -351 },
+    {  19087, -16176,   4775,   -84 },
+    {  17666, -12289,    938,  1224 },
+    {  18581, -15894,   5132,  -430 },
+    {  19823, -16717,   4142,   545 },
+    {  19960, -19423,   8400, -1492 },
+    {  18973, -16817,   5906,  -594 },
+    {  19079, -15431,   3528,   503 },
+    {  16667, -12485,   4467, -1302 },
+    {  19791, -17797,   6196,  -529 },
+    {  20005, -17606,   5354,   -20 },
+    {  20123, -18599,   6886,  -728 },
+    {  19068, -14805,   2394,  1105 },
+    {  14443, -13723,   5631, -2029 },
+    {  14730, -14231,   5631, -1450 },
+    {  16089, -15959,   7271, -2029 },
+    {  13473, -11200,   3236,  -924 },
+    {  14413, -10902,   2347,  -267 },
+    {  17666, -18662,  11381, -3496 },
+    {  14749, -11042,   3305,  -275 },
+    {  15304, -10486,   1869,  -240 },
+    {  14809, -12126,   3369,  -616 },
+    {  16896, -16561,   7307, -1845 },
+    {  15782, -14336,   5380, -1264 },
+    {  16395, -15520,   6415, -1588 },
+    {  13681, -11114,   2584,  -320 },
+    {  14244, -12326,   4480, -1632 },
+    {  15247, -13119,   4265,  -898 },
+    {  13987, -12091,   3469,  -597 },
+    {  13941, -12770,   4240,  -839 },
+    {  13771, -13627,   5252, -1384 },
+    {  15010, -16074,   7592, -2249 },
+    {  15852, -17226,   8619, -2655 },
+    {  18921, -16916,   6875, -1501 },
+    {  14909, -11678,   2768,  -295 },
+    {  18988, -18353,   8424, -2070 },
+    {  15457, -15080,   6218, -1513 },
+    {  14916, -15512,   6949, -1883 },
+    {  18108, -14702,   4681,  -701 },
+    {  17600, -15733,   5616,  -775 },
+    {  14070, -13683,   6472, -2626 },
+    {  13832, -11914,   5201, -2232 },
+    {  18846, -19009,   9192, -1961 },
+    { -11981, -10994,  -6324, -2264 },
+    { -10976,  -9047,  -6546, -3828 },
+    { -11288, -10532,  -7014, -4191 },
+    { -10139, -10189,  -7799, -2688 },
+    { -10555,  -9988,  -9181, -2040 },
+    { -11596, -11339, -10022, -2707 },
+    { -13400, -13395, -11306, -4206 },
+    {  -9774, -12281,  -7466, -4133 },
+    { -10842, -13125,  -8777, -4956 },
+    { -11964, -15082,  -9779, -5095 },
+    {  -9382, -10188,  -9053, -4927 },
+    { -11562, -11296,  -3651,  -985 },
+    {  -9287, -10083,  -7918, -4069 },
+    { -12821, -16556, -11410, -6195 },
+    { -12628,  -8959,  -4521, -1113 },
+    { -13845, -11581,  -3649,  -681 },
+    { -12685, -10269,  -5483, -1275 },
+    { -14988, -12874,  -5107, -1189 },
+    { -13761, -11367,  -6202, -1804 },
+    { -13225, -11249,  -7820, -3354 },
+    { -14809, -11992,  -3202,  -312 },
+    { -15620, -15519, -10210, -3433 },
+    { -12954, -10200,  -3139,  -611 },
+    { -11536,  -9981,  -5284,  -923 },
+    { -13034, -12417,  -4612, -1098 },
+    { -16911, -15505,  -6123, -1352 },
+    { -17396, -17685,  -8330, -2171 },
+    { -14120, -10764,  -2265,   -99 },
+    { -12598,  -7367,  -5406, -3530 },
+    { -14143, -12793, -10909, -5226 },
+    { -14692, -16871, -11626, -5554 },
+    { -12581, -11197,  -9194, -3837 },
+    { -16752, -16726,  -9746, -2808 },
+    { -10600, -10358,  -6560, -1227 },
+    { -14573, -13312,  -8957, -3393 },
+    { -10172,  -8463,  -8579, -3387 },
+    { -11418, -12421,  -5522, -1842 },
+    { -11855, -14204,  -6669, -2625 },
+    { -13308,  -8191,  -3941, -2194 },
+    { -10007, -12266,  -5022, -1811 },
+    { -13532, -15771,  -9497, -3175 },
+    { -11760, -11148, -10339, -5529 },
+    { -12149, -12763, -11198, -3697 },
+    { -12029, -12119,  -8555, -1792 },
+    { -16995, -19957, -11447, -3471 },
+    { -13144, -14504,  -9988, -3191 },
+    {  -9938, -11064,  -6139, -3162 },
+    {  -8873, -11550,  -8294, -6550 },
+    {  -9303, -13010,  -6150, -2711 },
+    { -15463, -10469,  -1766,  -170 },
+    { -15985, -11693,  -3007,  -650 },
+    { -17142, -10671,  -1434,    47 },
+    { -16063, -13858,  -4817, -1058 },
+    { -19446, -19599,  -9594, -2464 },
+    { -20076, -18744,  -8313, -1889 },
+    { -15047, -16085,  -7590, -2250 },
+    { -13481, -16195,  -8552, -2998 },
+    { -13829, -14869,  -6704, -1932 },
+    { -16357, -18484,  -9802, -2959 },
+    { -10551,  -8393,  -9303, -5070 },
+    { -11345,  -9156,  -5641, -3107 },
+    { -13217, -13449,  -9270, -4541 },
+    { -11988, -13732,  -9995, -6374 },
+    { -11007,  -9519,  -5168, -4107 },
+    {   9930,  -7858,   8061, -4375 },
+    {   8274,  -7867,   5992, -2096 },
+    {   9692,  -9675,   7621, -3670 },
+    {   9589,  -8110,   6509, -3010 },
+    {  12617, -11976,  10122, -5360 },
+    {  11867,  -8895,   7948, -5323 },
+    {  10388, -10482,   9234, -4324 },
+    {   8188,  -8220,   7810, -2737 },
+    {  10407,  -8787,   4806, -1930 },
+    {  10348,  -8845,   9233, -6614 },
+    {   9422,  -7091,   4820, -2878 },
+    {   9758,  -9796,   5584, -2256 },
+    {  10188,  -7994,   5347, -3343 },
+    {  11133,  -7455,   4015, -2306 },
+    {  10676, -10744,   6093, -2629 },
+    {  11522, -12184,   7848, -3375 },
+    {   8805,  -9883,   5317, -3071 },
+    {   9498,  -9654,   6555, -3592 },
+    {  10488,  -8008,   4066, -1252 },
+    {  11261,  -8930,   6068, -2738 },
+    {  12180, -10397,   5027, -1531 },
+    {   9138,  -8531,   3601, -1959 },
+    {   8107,  -8380,   4970, -2061 },
+    {   9737, -13248,   6438, -2617 },
+    {  11178, -10423,   2622,  -522 },
+    {   9572, -12372,   5199, -2019 },
+    {  12057, -12144,   4147, -1099 },
+    {   9047,  -9925,   2516,  -665 },
+    {  10790,  -8030,   5882, -4386 },
+    {   7199,  -8426,   6337, -2841 },
+    {   7778,  -8285,   3529, -3442 },
+    {   7559, -10569,   3484, -1332 },
+    {   9404,  -8115,   7484, -5541 },
+    {   7792, -11976,   5546, -2573 },
+    {   9313, -10264,   7661, -5195 },
+    {   6701, -10725,   4370, -1784 },
+    {   4918, -11361,   4507, -4527 },
+    {   5147, -12305,   3978, -5556 },
+    {   6525,  -9899,   4481, -3129 },
+    {   7538, -12855,   6060, -4826 },
+    {   8659, -12111,   7159, -4430 },
+    {   8440, -11304,   4547, -1747 },
+    {   9216, -10918,   3507, -1195 },
+    {   6165,  -9254,   4771, -4677 },
+    {   9163, -11019,   5637, -4935 },
+    {  13441, -11509,   6676, -2434 },
+    {   7912,  -9398,   6663, -4048 },
+    {  11723, -13745,   8131, -4148 },
+    {   6065, -10257,   5005, -6327 },
+    {  11618, -12417,   5336, -1894 },
+    {   8891, -13924,   8407, -6131 },
+    {   9622, -12563,   7908, -5109 },
+    {  11479, -10315,   8349, -3991 },
+    {  11676, -14103,   6611, -2330 },
+    {  11951,  -8953,   3829, -1550 },
+    {  10486,  -8044,  10493, -5920 },
+    {  11801, -10769,   9763, -5305 },
+    {   6109,  -8676,   5827, -1346 },
+    {   7030,  -9611,   5624, -5761 },
+    {  12808, -12886,   8683, -4148 },
+    {  13213, -10464,   6381, -3189 },
+    {  11796, -13681,  10703, -6075 },
+    {   9639,  -7949,   9625, -3944 },
+    {   8538,  -6997,   5309,   453 }
+};
+
+/* quantization tables */
+
+const uint32_t ff_dca_scale_factor_quant6[64] = {
+          1,       2,       2,       3,       3,       4,       6,       7,
+         10,      12,      16,      20,      26,      34,      44,      56,
+         72,      93,     120,     155,     200,     257,     331,     427,
+        550,     708,     912,    1175,    1514,    1950,    2512,    3236,
+       4169,    5370,    6918,    8913,   11482,   14791,   19055,   24547,
+      31623,   40738,   52481,   67608,   87096,  112202,  144544,  186209,
+     239883,  309030,  398107,  512861,  660693,  851138, 1096478, 1412538,
+    1819701, 2344229, 3019952, 3890451, 5011872, 6456542, 8317638,       0
+};
+
+const uint32_t ff_dca_scale_factor_quant7[128] = {
+          1,       1,       2,       2,       2,       2,       3,       3,
+          3,       4,       4,       5,       6,       7,       7,       8,
+         10,      11,      12,      14,      16,      18,      20,      23,
+         26,      30,      34,      38,      44,      50,      56,      64,
+         72,      82,      93,     106,     120,     136,     155,     176,
+        200,     226,     257,     292,     331,     376,     427,     484,
+        550,     624,     708,     804,     912,    1035,    1175,    1334,
+       1514,    1718,    1950,    2213,    2512,    2851,    3236,    3673,
+       4169,    4732,    5370,    6095,    6918,    7852,    8913,   10116,
+      11482,   13032,   14791,   16788,   19055,   21627,   24547,   27861,
+      31623,   35892,   40738,   46238,   52481,   59566,   67608,   76736,
+      87096,   98855,  112202,  127350,  144544,  164059,  186209,  211349,
+     239883,  272270,  309030,  350752,  398107,  451856,  512861,  582103,
+     660693,  749894,  851138,  966051, 1096478, 1244515, 1412538, 1603245,
+    1819701, 2065380, 2344229, 2660725, 3019952, 3427678, 3890451, 4415704,
+    5011872, 5688529, 6456542, 7328245, 8317638,       0,       0,       0
+};
+
+/* 20bits unsigned fractional binary codes */
+const uint32_t ff_dca_lossy_quant[32] = {
+         0, 6710886, 4194304, 3355443, 2474639, 2097152, 1761608, 1426063,
+    796918,  461373,  251658,  146801,   79692,   46137,   27263,   16777,
+     10486,    5872,    3355,    1887,    1258,     713,     336,     168,
+        84,      42,      21,       0,       0,       0,       0,       0
+};
+
+const float ff_dca_lossy_quant_d[32] = {
+          0,     1.6,      1.0,     0.8,    0.59,    0.50,    0.42,    0.34,
+       0.19,    0.11,     0.06,   0.035,   0.019,   0.011,  0.0065,  0.0040,
+     0.0025,  0.0014,   0.0008, 0.00045, 0.00030, 0.00017, 0.00008, 0.00004,
+    0.00002, 0.00001, 0.000005,       0,       0,       0,       0,       0
+};
+
+/* 20bits unsigned fractional binary codes */
+const uint32_t ff_dca_lossless_quant[32] = {
+         0, 4194304, 2097152, 1384120, 1048576, 696254, 524288, 348127,
+    262144,  131072,   65431,   33026,   16450,   8208,   4100,   2049,
+      1024,     512,     256,     128,      64,     32,     16,      8,
+         4,       2,       1,       0,       0,      0,      0,      0
+};
+
+const float ff_dca_lossless_quant_d[32] = {
+           0,      1.0,      0.5,     0.33,     0.25,    0.166,    0.125,
+       0.083,   0.0625,  0.03125,   0.0156, 7.874E-3, 3.922E-3, 1.957E-3,
+    9.775E-4, 4.885E-4, 2.442E-4, 1.221E-4, 6.104E-5, 3.052E-5, 1.526E-5,
+    7.629E-6, 3.815E-6, 1.907E-6, 9.537E-7, 4.768E-7, 2.384E-7,        0,
+           0,        0,        0,        0
+};
+
+/* Vector quantization tables */
+
+DECLARE_ALIGNED(8, const int8_t, ff_dca_high_freq_vq)[1024][32] = {
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+       0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0 },
+    { -4, -2,  2,  1,-16,-10,  1,  3,  1,  0,  6,  1, -3,  7,  1,-22,
+       2, -4, -3, 11, 14,  6, -1,  1,-13, 29,-28, 10, 10, -8,  0, -9 },
+    { -8,  8, -7, 10, -3,-12, -5, -8,  1, -2,  9, -2, -5,-18,  1,  9,
+      -8, -8,  3, 41,  7, -9, -9, 22,-42,-29, 14,-18,-14,-32,  1,-15 },
+    {-16,  8, 15, 16,-16,  5,  2,  7, -6,-16, -7,  1,  1, -3, -2,  0,
+       8, 20,-26,-11,  2,-17,  0, -3,-34,-37, 10, 44, -2, 22,  2, -4 },
+    {  7, 14,  5,  6, 15, -1,  3, -3, -9,-23, -5,-14,  8, -1,-14, -6,
+      -5, -8, 54, 31, -6, 18,  2,-19, -2,-11,-30, -6,-19,  2, -2,-14 },
+    {  1,  2, -2, -1, -3, -3,  1, -5,  1, -3, -4, -8,  5, -4,  0,  1,
+       3,  7, -5, -4, -3,-12,  3, -2, -3, 12,-53,-51,  6, -1,  6,  8 },
+    {  0, -1,  5,  1, -6, -8,  7,  5,-18, -4, -1,  1,  0, -3, -3,-14,
+      -1, -6,  0,-14, -1, -1,  5, -3,-11,  1,-20, 10,  2, 19, -2, -2 },
+    {  2,  4,  3,  0,  5,  0,  3,  1, -2,  0, -6, -3, -4, -5, -3, -3,
+      -7,  0,-34,  4,-43, 17,  0,-53,-13, -7, 24, 14,  5,-18,  9,-20 },
+    {  1,  0, -3,  2,  3, -5, -2,  7,-21,  5,-25, 23, 11,-28,  2,  1,
+     -11,  9, 13, -6,-12,  5,  7,  2,  4,-11, -6, -1,  8,  0,  1, -2 },
+    {  2, -4, -6, -4,  0, -5,-29, 13, -6,-22, -3,-43, 12,-41,  5, 24,
+      18, -9,-36, -6,  4, -7, -4, 13,  4,-15, -1, -5,  1,  2, -5,  4 },
+    {  0, -1, 13, -6, -5,  1,  0, -3,  1, -5, 19,-22, 31,-27,  4,-15,
+      -6, 15,  9,-13,  1, -9, 10,-17,  4, -1, -1,  4,  2,  0, -3, -5 },
+    { -7,  3, -8, 13, 19,-12,  8,-19, -3, -2,-24, 31, 14,  0,  7,-13,
+     -18,  0,  3,  6, 13, -2,  1,-12,-21,  9, -2, 30, 21,-14,  2,-14 },
+    { -3, -7,  8, -1, -2, -9,  6,  1, -7,  7, 13,  3, -1,-10, 30,  4,
+     -10, 12,  5,  6,-13, -7, -4, -2, -2,  7, -3, -6,  3,  4,  1,  2 },
+    { -8,  9,  2, -3, -5,  2,  0,  9,  3,  7, -4,-16,-13,  3, 23,-27,
+      18, 46,-38,  6,  4, 43, -1,  0,  8, -7, -4, -1, 11, -7,  6, -3 },
+    {  1,  1, 18, -8, -6,  0,  3,  4, 22, -3, -4, -2, -4,-11, 40, -7,
+      -3,-13,-14, -7,-10, 14,  7,  5,-14, 11, -5,  7, 21, -2,  9, -3 },
+    {  0,  0, -2,  4, -2,  0,  2,  0, -1,  2, -1,  0,  0,  2,  2,  2,
+      -1,  1, -3, -1,-15, -2,-63,-27,-21,-47,-14,  1,-14, 10,  0,  2 },
+    {  1,  0, -4,  0, -3, -9,  4,  2,  6, -6,  0, -5, 11, -7,-15,  6,
+      -7, -6,  3,  7,-15, -5, 23,-13, -6, 12, -8,  9,  2, -3,  3,  4 },
+    {  6,  0,  3,  0, -2, -4,  2,  1,  1, -1,  1, -2, -1, -4,-22,-15,
+     -46,-66, 10, 20,  2,-17, 12, -6,  1, -2, -2,  0,  1, -5,  1,  2 },
+    { -1,  0,  0,  1,  0, -4,  0,  1,-10, -3, -8,  5,  7,-11,  2,-11,
+      29,-25, 11, 10,  0, -1,  5, -7, -2, -5, -2,  4,  4, -3,  5, -2 },
+    {  1, -1, -1, -3, -2,  1, -8, -3,  2, -2,  4, -5, -1, -7, -2,  1,
+     -14, -7,  3,-30,-15,-14,  3, -4, -1,  3,-13, -1, -3,  1,  2,  3 },
+    { -1, -2, -3,  2,  2, -3,  3,  1, -3,  2,  0, -4,  6,  5, -5, 10,
+     -57,  3, 22,-50,  1, -2, -5, -6, -1,  5,  1,  2,  2,  1, -2,  2 },
+    {  2,  0, -1, -7,  2,  1,  3,  2,  0,  4,  3, -2,  3, -3,  4, -4,
+      24,-35, -3, 38, -6, -5, 15, 20,  3, 16, -7, -5,  0, -4, -5,  0 },
+    {  0,  1,  0,  0,  0, -1, -1,  1,  1, -1,  1, -2,  0,  0,  0,  0,
+       0, -1, -2, -1, -5, -2,-43, -3, 46,-52,-10,  7, -8, 11, -2, -1 },
+    {  0,  0, -1,  0, -1,  2,-41, 33,-44,-48,-15,-26, -9,  6,  3,  3,
+      -3,  2,  2,  2,  2, -1, -1, -2,  1,  3,  0,  0,  5,  2,  3,  1 },
+    { -4,  1,  6,  1, -6, -1, -2,  1,-14, -4,  0, -5, -2,  2, -2,  0,
+      -6,  1,  0,  8,-21, 32, -3,-36, -6, -2, -1, -7,  3,  0,  1, -6 },
+    { -3, -2,  3,  0,  2,  2,  8, -4, -4,  6,  2,  1,  3, -6,  4,  3,
+      13,  0,-12, -1, 25,-20, -2,-23,-15,  7, -3,-11, -3,  6, -1,  0 },
+    {  0,  0, -3, -1,  0,  0, -2, -1, -2, -2,  1, -1,  0,  0, 10,  3,
+      -2,  3,  3, -7, -6, -5,  0, -4,-60,-16, -6, 38,  5,  6, -5,  0 },
+    {  0,  1,  0,  0,  0,  0,  0,  0,  1, -1, -1,  0,  1,  0,  0,  1,
+       0,  0, -1,  0, -8,  2, -9, 10, 40, 31,-56,-21,  4, 20, -4,  7 },
+    { -2, -2,  0,  4, -3, -1,  7,  3,  1,  3, -8,  0,  3,  1,  2,  5,
+       1, -2, 14,  5,  4,  5,  5,  5, -5,  9,-66,  0,-20, -2, -8,  4 },
+    { -2, -1,  4, -1, -8, -2, -4, -1, -3, -3,  2, -7, -3,  5,  7, -2,
+      45, 31,-17,-16, -2, -2, -1,-22,  1, -1, -3,  3,  5, -3,  5, -1 },
+    { -4,  0,  7,  5,  8,  7,  2,  9, -9, -9, -7,-11, -3, -8, 17, -4,
+      34, 32, 18, 22,  1,  2,  1, -7, -5,  6, -1,  6,  4, 10, -2, -7 },
+    {  6,  0, 14,  9,  6, -1, -2, -3,  4, -6, -8,  4,  7, -1, 28, 38,
+      15, -1, 16,-11,  5,  8,  4,-10,  3,-10,-17,  5,  3,  3,  3,  1 },
+    {  1,  1,  2, -1,  2,  1,  0,  0, -1,  0,  0, -2,  1, -3,  0,  1,
+       2, -2, -4, -2,  0, -1,  1, -3,  1,  1,  1, -1,  8,  8, 66, 33 },
+    { -5,  2, -3, -7,  2, -8, -4, 10, 17,-18, -7,  4, -4, -7, -6, -6,
+      -5,  5,-12,  2,  0,  6,  8, -2,  1,  4,-11,  2,  1,  8, 31, 19 },
+    {  6,  9, 16, -6, -6, -1, -2, -3,-11, -2,  7,  7, 17,  3,  4, 10,
+       2,  5,-13,  8,  7,  1,  4,  5,  7,  6,  7, -8,  9, -8, 33,  6 },
+    {  3, -1,  1,  0, -7, -5,  0, 14, -7,  1, -7,  1,  2, -4,  7, 10,
+     -16, 12,  1, -6,  3,  8, -1, 10,-13, -6,-12,-23, 12, -3, 30, 14 },
+    { -2,-15,  0,  8,  3,-19,  5, -3,  2,  3, 13,  7, 14, -3,-10,  0,
+       8,  5, -6,-16, -8, -8, 14,  2, -1,  1, -9,-11, 11, -5, 27,  9 },
+    { -8,  6, -4,  4, -4, -1,  5,  4,  1, -7, -5, -4,-15,  1,  9,  0,
+       8,  4,  1,-17, 11, -2,-19, -1, -6, -8,  3,-12,  3,-17, 33,-10 },
+    { -3, -1,  2,  7,  7, -2,  9,  8,-18, -1,-13,-10, -3, -3, 11,  8,
+      -2,-12, -8,  1,  4,  9, 14, 10, -3,  0,  2,  1, -2,  3, 31, 10 },
+    { -3,-10,  8, -1, -5,-11,  7, -5,  3,  6,  1,  4,-16, 10,  5, -4,
+      -2,-10, -1, 13,  6, -5, -7, 12,  7, -3,-17,  1, 12, -4, 29,  8 },
+    {  1,  2,  5,  2, -6, -7,  0, -1,  6, -1, 10,  6, -4,  5,  2,  2,
+      -2, -8, -6,-11, 14,-13, 27,  3, -2,-12,  5,-16,  2,-26, 20, 15 },
+    { -1, -3, -5, -3, -3,  6, -1,  3, -5,  1,  7,  2,  1,  0, -1, -1,
+       0, -1,  9,  7, -6, -3,  4, -5, -4,  8, -8,-25, -8, -4, 34, 23 },
+    { -1, -2,  1,  1, -1, -2, -1,  1, -1,  0,  0,  0,  0, -2, -1,  1,
+       0,  2,  1, -1,  4,  0,  0,  1, -1,  0,  5,  3, 12, -9, 68,-16 },
+    { 10,  0, -8, 14, -6,  1,-12,  0,  0, -3, -5,-11, -6, 12,  9,-10,
+      -3,  5,  0,  7, 11,  2,  4, -3, -8, -3,  7,  4,  3, -3, 34,  4 },
+    {-12, 13, -5,  7,-11, -2, -1,  1, -4,-14,-21,  3, -3, -3, -4, -7,
+      -9, -4,  3,-17, -2,-13, 10, -2, 12, -4,  0, -9,  1, -5, 31, 10 },
+    {-10,  6,  5,  6,  4, -7, 10,  0,-28, -3,  0,-11, -1, -5, 16,-10,
+     -16,  7, 20,  2, -4,  2, -5,  0, 15,  6,  5,-10,  7, -9, 20,  4 },
+    {  1, -7, -2, -7,  4, -3, -2, -7, -1,-14,  6,-16,  4, -5, -4, -6,
+      -5,  0, -2,  2, -6,  9, -5,  4,-18,  8,-10,  8, 15,  0, 32,  1 },
+    { -5,  7, -3,  7, 15, -4,  0,-16,  9,  5, -5,  5,  4, -3,-12, -9,
+     -18, 10,  2,  2, -3,  7,  3, -1,  6, -9,-10,  3, 15, -4, 35, -7 },
+    { -1,-10,  2,  2, -4, -2, 10,  2, -1,  2, -2,  1, -1,-14,-11,  3,
+      -8,  5, -8, -2,  6, -1, -7,  1,  7,  5,  7,  8, 30, -4, 30, 14 },
+    {  2, -2,  1,  2,  3, -8,  3,  0, -2,  0, -9,  2,  1,  4, -6, -1,
+      -2,  5,  0,  1, -2, 12,  6, -3,  9, -3,  4,-12, 21,-39, 24, -2 },
+    {  3,  5,  1, -2, -2, -2, -3,  6, -8, -2,-11, -8, -1,  4,  2,  2,
+      -4,-10, 12, -5,-11,  1,-15,-34,-11, -7,-11, -1,  7,-14, 38, -1 },
+    { -4,  4,  8,  9,  8,  1, -5, -9,  4, -2, 15, -4, 11,-15, 20, -1,
+      -1, -3,  4, -9, -2, -2, -2,  8,  6, 12, -5,  0, 11,-12, 27, -4 },
+    {  0,  8, -4,  3,-11,  6,-11,  2,  3,  0,  5, -8, -7, -6, -9,-21,
+       4,-11, -1,-16, -7, 16, -3,  7, -7,  4, -5,  0, 11, -7, 31,  3 },
+    {  1,  3,  4, 11,-11, -2, -3, -6,  6,  5,  0,  3, -9, -6,  4, -4,
+       0,  4, -8, 13, -6,-13, -1, -5, -1,  4,  0,  0,  9,-22, 24, 18 },
+    { -7,  3, 10,-13, -6,  6, -6,  6, 22,  1,  0,-14,  2,  3,  7, -1,
+       8, 20, -1,  5, -4, 13,  9, -9, -9,  6,  0, -4,  0, -8, 31, -4 },
+    { -3, -4,  0,  1,  7,  3, -7,  0,  5, -2,  1,  3,  3,  1, -5, -2,
+       5,  2,-11,  4,  0, -1, 12,  0, -3,-13, 15,  8, -6,-27, 34,  0 },
+    { -3, -3, 10, -4,  2, -1, -3,  0, -1, -1, -4,  2,  6, -2, 12,  1,
+       3, -6, -7, -6, -5,  4,-19, -6, -8,-34, -4, -8, 10, -7, 23, 10 },
+    { -7,  0, -1, -6,  8,  4, -4,  2, -5, -8, -7, -9, -8,  5,  9,  7,
+      -6,  1,-12,-12, -1,-16,  5,  0, 16,  3, -7, -8, 27, -4, 23, 15 },
+    { -8,  4,  8,  5,  6, 11, -3,  5,  3, -1,-11,  6, -5,  0,  2, -6,
+      -3, -6,  4, -1,  5, -5,-12, -6,  7, -5,  9,  3,  6, -7, 29,  1 },
+    {  1,  3, -2, -2, -6, -2,  1,  6, -6, -3,  1,  2,  3,  4,  1,  5,
+      -1,  0,  4,  2, 11,  6,  2, -3, 13, -9,-19, 18,-15,-10, 36, 21 },
+    { -3, -3,  2, -1, -7,  6, -4,  1, -3, -1, -2,  2,  3, -7, -3,  0,
+      -2,  0, -2,  6,-19,  3, -8,  2, -6,  7, -1,  0, 29, -6, 28,-10 },
+    { -5,  1, -3, -7,-12, -4,  1,  1, -1, 13,-10, -1, -9, -5,-13,  6,
+      13,  3, -4,  2,  3, 11,  2,  6,-25,-16, -6,  0, 14, -1, 27, 16 },
+    { -6, -1, -7, -5, -2, -5, -5, -1,  9,  1,  0,  3, -8,-12, -6,  5,
+      -6,  5,  3, -9,  1,  4, -7,-10, -9, -7,-17, -5,-15,-23, 25,  3 },
+    { -8, -2,  9, -3, -4,  3, -1,  8, -7, -7, -5, -4, -2,  9,  4, -1,
+      -7, -4, -5,-16,  3, -6, 18,-13, -9, 16,-15,  8, 15,-10, 24,  5 },
+    {  1,-38,  2, 34,  9, 10, 11,  2,  2, -6,  3,  2, -2,  5,  4, -7,
+      -1,  1,  4,  0,  3,  1, -8, -1, -6,  5,  4,  2, -4,  5,  2, -1 },
+    {  1,-22, 15, 18, -2, 10,-16, -9, -8,-11,  8,  4,  0,  7,-14, -5,
+      -1, -7, 12, 17,  9,  5, -7, -4,-12, -6,  7,  0,  7,  2, -2,  1 },
+    {-11,-29,  7, 10, 19, -1, -8, -9,  7,  1,  9,  6,  8, -7,-14,  8,
+      -3,-11,-13,  0, -7,-23, -2, -8, 12,  9,  2, 14, 19,  1, -1,  5 },
+    {-24,-27,-11, 36,  2,  6, -3,  4, -6,  8,  0, 12, -1, -4, -6,  3,
+       4, -1,  2, -3, -2,  3,  2, -1, -2, -4,  0, -1, -2,  7,  2,  3 },
+    { -9,-24, 11, 13,-10,-12, 12, -2,  7,  4,  8, 13, -3, -3,  2,  9,
+      -3, -4,  4, 13,  5, 13, -6, -3,  1, 15,  7, -3,  0, 19, -2, -9 },
+    { -8,-15,  7, 14, -4, -5,  2,-18,-19, -2,  2, 17, 16,  6,-10, 10,
+      -9, 14, -1, -5, -1, -6, -7,  2,  9, 11, 13,  6, -5,-12,  3,  2 },
+    {-10,-37, 13,  1,  3,-14,  0,-20,  4, -3,  8,  2, -2, -3, -9, -5,
+      -3,-17, -1, 13,-11,  2, -6,  4,  4,  0,  3,  1, -9, -4, -5, -4 },
+    { -2,-22, -5, 46, -8,  5,  9,-11,  8,  7,  7, -1, -1, -2, -7,  2,
+      -3,  3, -1, -2,  7,  0,  2, -1,  1, -2, -2, -3,  6,  0, -4, -6 },
+    {-16,-27, 15, 16, -4, 14, -7,-26,  2, -2,  6,  5, -3, 11,  0,  2,
+       3,  9, -7, -1,  2, -4, -4, -1,  6, 10,  1,  1, -3, -2,  3,  0 },
+    { -3,-22, 10, 26,  1,  2, -3,  3, 17, -3, -7,  9,  1,-21, -4,  5,
+       3,  0, -7, -6,  3,  3, -8, -7, -9,  3,  7,  1, -8, 12,  6, -7 },
+    { -9,-25,  3, 18,  9, -6,-11,  0, -5,-12,  9, -8, -7, -6, -6, 22,
+       2, -6, -3, 15,  3,  2, -2,  9, 14,-10, -7, 15, 13,  6, -2, 11 },
+    {  5,-20, -5, 28, 11, 10, -4, -4,  0, -7,  3,  5,  2, -5, -8,  2,
+       6, 10,  9, -9,-18,  3, 14,  1,  3, -3, -1, -6,  7,  7,  2, -1 },
+    { -8,-30,  7, 12, 10,  8,  7,-13,-16,  0,  1, -1, -6,-11,-15,  4,
+       1, -2, 10,-15,  1, 11, -2,  8,  9, -7, -7,  9, -5,  2,  7,-18 },
+    {-10,-32, 10, 11,  3, -1,  3, -5,  5,  2, 14, -6,  3,  1,  5,-15,
+     -11,  6, 20,  4,  0,-12, -7,  3,  1, -1, 10,  6, -1, -9, -4, -1 },
+    {  1,-25,-14, 12,-11,  9,  9,-16,-24,-17, 22, -9, 11,-30, -3, -4,
+       6, -7,  9,  2, -1, -5, -6,  2, -1, -1, 10,  1, -3,  3,  4,  8 },
+    {-14,-26, -6,  9,  8, 17,-11,-24, -7, -4, -8, -2, 10,  2,  2, -1,
+       2, 13, 12, -7,  4, -6,-10,  6,  6,-13,-11, -7,-16,  0, -2,  5 },
+    { -4,-30,-13, 12, 16, -6, 12,-16,-13,  5, 15, -2, -2,-10, -7,  7,
+      11, -1, -4, -2, -4,  7,  4, -8,  1,  3,  0, 11,  3, -2, -5,  4 },
+    { -4,-21, 20, 22,  2, 20, -8,  1,-12, -5, -9,  4,-10,-17, -3, -8,
+      -3,  3,-12,  1, -3,  0,  7,  4,  7,  7, -3,  7,  5,  3,  1, -5 },
+    {-12,-20,  2, 29, 11, -6,  9, -7, -6, -4,  0,  6, 17,-13, -2,-10,
+     -17, -1,-18,  2,  0, 14, -6,  1,  0,  3,  2,-10,  1, -5, -2,  5 },
+    { 16,-37, -1, 26, -2,-14,  1, -5,-14,  2,  2,  3,  6,  1,  1,  4,
+       0, -1,  0, -2, -2,  4,  9, -6,  0, -2, 10, -7, -2,  4,  1,  0 },
+    { -9,-24,-12,  5,  5,  3,-17,-14,  4,  3,  2, -4, 10,-22, -8, -3,
+       6,  1, 12, -8,  4,  1,  9, -1, 18, -3,  6,  5,  3, -5,  9, -5 },
+    {-14,-33, -2, 20,-13,-10,  2, -7, -1, 11, -9, -8, 18, -3,  1,  8,
+       0, -2, 10,  7, -2,-13,  9, -3, -4,  5, -2, -2, -1, -5,  1, -7 },
+    {-10,-23,  8, 14,  1,  7,  1, -3, -7,  4,  1,  1,  8, -7, 15,-14,
+      13, 14,  2,  5,-13, -5, -8, -1,  6,  3,  6,  9,  6, 15, 14,  5 },
+    {-13,-25,-10, 13,-17,-24, -7,-13, -6,-10, -8,  2,  0,-13,-10, -4,
+      -8,  4, -9,  9, -4,  4, -3, -3,  3,  3, -5, -9,  1, -2, 11,  2 },
+    {-12,-23,  1, 18,-11, -2,  5,  9, -5,  5, 14, -9, -3, -2, -6,  2,
+      -2, 11,-13,  1, -3, 11, -9, -4, -2, -6,  8, 10,  1,  4,  2,  1 },
+    { -5,-18, 16, 22,  2,  0,  8, -6, -9, -7, 10,-16, 23, 10,-11, -1,
+       7,  2,  7,  2,  1, -5,  6,  1,  0, -4,  9,  2, -3,  1,  0, -4 },
+    { -3,-26, 14, 11,  2, -9, 17, -2, -1, -5,-16, -9, -5, 10,-13,  1,
+       6, 12, 10, 11,  0,  0, -3,-14,  6, -2,  0,  4, -5, -1, -7, -1 },
+    {-10,-33,  1,  8, 11, -5,  1, -6,  7,  4,  5,  6,  1, -2,-10, -5,
+      -6, 12,-11,  5,-10,  4, 12, -1, -1, -3,  4, -1,  9,  0, 16,-17 },
+    {-14,-37,  7,  7, -2,  5, -8,-11,  2,-13,  4,-19,  1,  8,  8,  4,
+      -9,  2, -4,  3, 12,  2,  4, -4, -8,  8,  1,  4,  8, -1,  6, -2 },
+    { -6,-30, 18, 17,  1,-22, -3,  4, -7,-10,  7,  0, -8,  8, -1,  4,
+       2,  8,  6, -2,  2,  7,  4,  4,  3, -6,  2,  1, -3,  1, -1, -5 },
+    {-17,-18, -3, 22, -8,  1,  9, -2,-17, 20, -5, -5,-12, -5,  4, -5,
+      -9,  8, -2, 16, -3,  0, 19, -8,  8,  1,  2, -4,  0, 11,  0, -3 },
+    { -9,-23,  3, 10,  4,  4, -3, -2, -2, -2,  1,-22, 11,  0, -2,  5,
+      -2, 14, -9,-11, -4,  7,  5, 32,  1, -3, -7,  0, 21, -9,  7, -6 },
+    {  0,  0,  0,  2, -1,  1,  0,  1,  3,  0,  0,  1,  0,  1,  0,  1,
+      -3,  0, -1, -2,  0, -1, -1, -3, -1,  1, -4,  1, -1, -5,-69,-19 },
+    { -3, -5, -8,-12,  4, -3,-19,-11, -5,  0,-14,  7, 18, -6,  7, 22,
+       8, 14, 15, 10,  3, -1, -3,  5, -1,  7, -7,  1, -6,  3,-26,-11 },
+    { -1, -6,  4, -4, -5,-16,  0, -6, -3, 11,  1,  0,  9,  5, 16,  3,
+      -4,-33, -4,  4, -7,  0,  1,  6,-11, -2,-13, -2,-18, 20,-25,-16 },
+    {  4,  0, -1,  0, -5,  1,  0,  2,  0, 11,-10,  4,-10,  7, 16,  2,
+      16, 15,  2, -1,  2,  9,  2,  8, -3, -5, -2,  0, -3,  0,-33, -2 },
+    { -3,-15, 10, 10, -9, -1,  7,  3,  5, -5, -8, -8, -3, 15, -9,  4,
+      12, 13,-13,-14, 10, -6,  9, 22,-27, 23, -1,  5,-24,  2,-30,  5 },
+    {  0, -2,  7, -5, -5,  3,  5,  3, -3, -5,  2,  1, -4,  3, -3, -1,
+       1, -2, 10, 22, -3, -4, -2, -2, -7,  3,  8,  1, 14,  4,-37,  9 },
+    { -3, -4, -1,  1, -4,  0,  6,  2,  6, -7,-10,-10, -1, -4, 11, -3,
+       7, -6,  4,-12, -1,  5,  1, -7, 10, -6, 17, -4,  8,  3,-40, 13 },
+    {  2, 12,  4, -7, 14, -3, 16, -2, 18,  2, 13,  5,  5,  1, 11, -1,
+       0,  9,  2, -6, -1,  2, -6,  2, -5,  3,  5,  1, -1,  1,-32, -7 },
+    {-16, 11,  7, -4,  2, -5, -9,  9, 11, 11, 15,-13,-11, 11,  9,  4,
+       3, -8,-10, 12, 12,  0,  0,-16, -9, 13,  2,  9,  4,-13,-33,  3 },
+    {  6,  4,  5,  4,  3, -1,  5,  6,  4,  2,-11, -1,-15,-11, -1,  1,
+      11, -3, -2, 24, -4, -6,-25,-10,-15, -8,  0,  0, -5,  4,-30,  2 },
+    { 10, -3, -6,  1, -9, -5,  6,  9,-10, -3,  8, -1,  4, -1, 11,-11,
+       3,  9, 11, -3,  6,-17,  5, -8,-33,  9,-13, 19, -2,  9,-25,  2 },
+    {  0,  0, -1, -3,  0, -2,  1,  0,  0,  2,  1,  0, -2,  0, -1,  2,
+       0, -1,  4, -1,  2, -3,  4, -2,  3,  3,  1,  0,-15, 12,-63, 27 },
+    { -2, 14,  9, -1,  3,  0,  1,  1,-19, 15,  3,  4,  0,-10,  1, -5,
+       3,  0, -5,-10,  2,-16, -4,  8,-12, -6,  7, -5,-10, -1,-33, -4 },
+    {  0,  3,  1,  3,  1,  2,  4,  4,  9, -6, -8, -5,  1,-12,  3,  8,
+     -10,  6, -1,  1, 13, -5, -5,  2, -4, 13,-18,-10, -7, -9,-33, 10 },
+    { -6, -3,-12,  5, -1, 11, -6,  0, -2,  1,  2, -7,  3,  1,  3, -2,
+       1,  8,-10,  7, -1, -3,  3,  0, 13,  1,  6,  7,-16, -7,-39,  8 },
+    { -6, -1, 11,  6, -3,  8,  3, -5,  3,  0, -5, -2, -6, -3, -4,  2,
+      -3, 13,-11,  1,  7,  5, 19, -5, -3,-15, -1,  7, -1,  6,-33,  8 },
+    { -7,  3, -4, -3, -4,  1,  6, -5, -5,  6, -8, -1, -7,  4, -1, -6,
+      -2,  1,  7,  0,  1,  1, -5,  2, -2,  0,-13, -2,-31,-14,-39,-12 },
+    {-10,  9,  0, -3,  1, -1, -1,  0,  1, -5, -1, -4, -2,  5,  2, -7,
+      18, -8, -2,-19, -7, -7,-12,-14,-11, -1, -9,-13, -7,-12,-31, -9 },
+    { -3,-16, 10,  9,  1,-10,-12,  2, -2,  2,  7, -3, -3,  1, -4, -5,
+      -9,  5,  7,  3, -1,  4,-11, -8,  4, 13,-10, 13, 10, -4,-36,  1 },
+    { -7,-12,  4,-20, -7, -7,  2, 11, -1, -2,  3,-12,  1,  0, -6, -7,
+       6,  4, 13,  3, -3,  4,  3, -6,-12,  5, -5,-22,-13, -8,-37, -6 },
+    { -7,  5,  3,  5,  7,  9,-14, -3, 10, 17, -1,  1,-12,  5, -6,  0,
+      -4, -9,  0,-11,-14,  3, 13,  6,-25, -8,-12,  4,-10, 18,-30, -1 },
+    {-10,  6,-10,  6,  6,  1,-10,  0, -7,  5, -2, 17,-18, -4,  0, -3,
+     -16, -6, -3, -8,  5,  1, -4,  6, -7, 16,  6, 10, -1,  0,-32,-11 },
+    { -1,  9,  9, -5,  4,  9,  6,  9, -4, -2,  7, 11,  4,  2, -5, -4,
+      -6,  0,  2, -3, -1,  5, 10,  0, 12,-10,-18, -3, -1, 14,-33,  2 },
+    {  4, -8,-18, -4, -5,-11,  4,-10, -4,  9, 13,-12,  1, -6,  1,  2,
+       4, -9,  8,  3, -6, 21, 13, -1, -2,  1, -2,  6, -7,  0,-30,  1 },
+    {  6, -1,  2, -3, -1, -4,  6, -4,  0,  4,  2,  2, -9,  2,  6,  3,
+      -2,  4, -1,  9, -6,  0,  7, -8,  5, 19, -2,  9, -5,  2,-33, -8 },
+    {  2,  1, 12, -5, -8,  8,  3, -2, -4,  1, -2,  5, -4, -9, -8, -8,
+       7,-11, -4,  6,-10,  7, -1, -1, -2, -1, 16, 32, -7, 20,-33, -6 },
+    {-18,  2,  6, 13,  9,  9, -1,  3,-17, 24, -2, -6, 28,  8, -2,  6,
+       3,-10,-34,-16,-13, -4,-15,-11,-12, -3,-10,  4, -8,  4,-31, -4 },
+    {-11,  0, 18,  2,-16, -9,-13, -2, -2,-12, -3,-22, 30,  0,  8,  3,
+       9, -4,-16,  1,  0,-11, 15, -2, -4,  6, -5,  6,  1,  2,-25,-12 },
+    { 14, -1,  5,  7,  3,-15, -8,  1,  5, -2, 12, 13, 11,-25,  3,  1,
+       0, -2, -4,-16,-23,  0, -5,-17,  7,  5, -9,  6, -5,  2,-32, -7 },
+    {  3, -1,  6, 14,  2,-12, -9, -9,  4,  7,  4,  6,  5, -8,  4,  2,
+       4,  5, -2,  8,  8, -6,  0, 10,-20, -1,  3, -1,  8, 23,-33, -5 },
+    { -3, 11, -6,  3, -4,  5,  7,  3,  4,  5, -2,  3, -1, 30,  6,  1,
+       8, -6,  0,  0, -9,  6, -9,  4,  2,  9, -6,  1,-12,  0,-34, 18 },
+    {-17, 13,  0,  1,  9, -4,-11,  0,  7,  0,-10, -4, -1,  6, -6,  4,
+       1,  6, -9,  3, -5, -6,-11,  2, -4, 14, 23, -3,  2,  5,-30, 12 },
+    {-14,  5,-27,  2,  0,  7,  1,  4, 30,  8,  7,  5,  1, -1,  0,  5,
+       8,-10, 48,-11, 12, 33,  6,  8,-15, 20, -2, -5, 32,  5,-19, 10 },
+    {-16, -4,-12, -7, -2,  0,  8, -6,-20,-18, 16, -3,  0, 31, -2, 11,
+       2, -9, 49,-19,-12,-23, 10, 26, 16, -2,  4,-21,-14, 13,-11, -9 },
+    { -5, -9, -1,  3, -5,-21,  2, 10,  0,  0, 10,-21, -7,  7,-26, -9,
+      22, 32, 58, 11, -3, 11, -5, -8,-13,  6, -5, -9,  1, 10, 14, -8 },
+    {  7,  7, 10,  3, -2, -1,-11,-11, -6,-43, -3, 14,-19,-18, 19, 18,
+     -32, 10, 45, -6,  6, 21,-20,-12,  2,  4,  6,  6, -4,  3,  3,  1 },
+    { 21, 22, -3, -2,-11, -6, -1, -2,  8,  8, 32,-21,  7, 28, -4, -6,
+      -3, -2, 50,  2,  2, 27, -5, -8, 12,  7, -5, -1, -4,-17, 27,  6 },
+    { 13,  7,  2, -6,-12,  2,-10, -5,-17, 11,  4, 17,-12, -2,  5,-17,
+      37,-16, 48,-14,-18, 29,  8, 24, 11, -5, -9, 11, -1,  1,-13, -3 },
+    {  1,  1, -1,  2,  0,  0,  0, -1,  1, -1,  7,  2, -3,  3,  0,  6,
+       2, 10, 54,-25,  7, 54, -5, -6, -1,-15,  9, 13,-24,-15,-12,  3 },
+    { 21,  5,  8,  3, -3, -4, -2, -4,  3,-11, -5, -8,  9, 16,  8, -9,
+     -10, -3, 46,-46,  2,  1,-10, 10, 17, 11,-20,-36, 10, 14,  0, -5 },
+    {  7,-13, -6, -9,-24, 45,  2,  8,  8,  0, 17, 20, 12,-24,  1, -7,
+     -15, -3, 46,-13, -2, 20,  1,-13,-11,-13,  2, 15,  1, 10, -1,  3 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1,  0, -2, -1,
+     -16, -9, 31,-69,-34, 26,  7, 17, -1, -6, -1,  0,  0,  0,  0,  0 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -4,
+      -5,-20, 18,-82, 22,  3, -7,  9,  4,  6,  2, -4, -1,  0, -2,  2 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  4, -1,
+      15, -5, 62,-36,  4, 52, -7,  5,  0,  6,  1,  2,  1,  1, -1,  0 },
+    {  3,-19, 19,-20, 13, -4,-11,  8,  8,-16, 10,  1,-14, 30,  1,-33,
+      10,-11, 45,-30,  3, -4, -3,-13,  7, 12,  3,-22,  3, -2, -4, -2 },
+    { -1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  0,  2,  1,
+      11,  8, 70, 48,-10, 21,  4,  9, -9, -9, -4, -6,  0, -1,  0,  0 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  2,  0,
+       2, -1, 80,  2,-15,-36,-10, -5, -2,  8, -2,  2,  0,  0,  0,  0 },
+    { 10,  8, -8, -8,-24, 12, -1,  0, 20,  9, -1, -2,  2, -2, 12,-10,
+      -2,-13, 35,-43, 44, 15,-10,-25,  4, 10, -3, -5, -5,  7, -1,  3 },
+    {  1,  1,  1,  1,  0,  0,  1,  0,  0,  0,  0,  0,  0,  0, -2, -1,
+     -18,  9, 49,-72,  7, -8,  7, -5,  2,  3,  2, -2,  1, -2, -3,  1 },
+    { -1,  4, -3, 10, 19,  4,  3, 20,  6,-24,  6,  9,  8, 15, 18, 18,
+     -36, 19, 57,-11,  4, -3,  8,  7,  2, -3, -2, -9,-15, -2, 12, -4 },
+    { 20,  3, 11, -9, -4, 22, 42,-25,  1,  5,-10,-19,  0,  9,-16,  5,
+       2, 10, 44,-29, 17, -3, -9, -2, -1,  8, 14, -7, -1, 16, -5,  1 },
+    { -7, 16,-11, 12,  6, 33,-15, 14,-23,  2,-26,  8,  2, 10,  0, -5,
+       8, -8, 38,-38, -4,  5,  5,  5,  1, 22,-15,  7,  6,  0,  4, 28 },
+    { -1,-12,  2, 10, -2,  0,  7, 17, 12, 22, -4, 10, 25, 29,  5, 18,
+       4,  1, 27,-39, 31, 17,  2,  2, 22,-23, 13, 16,  1, -7, -4, -5 },
+    {  0,  1,  0,  0,  0,  0,  0,  0,  0,  0, -1,  0, -2,  0,-14,  0,
+      -7,-11, 49,-22, -4, 19, 17,-39,  4,-29, 10,  2, 36, -4, 23, -1 },
+    { -2, -2, -2, -2,  1, 15, -5, -7,-16, -8,-19, 16, -3,-20, 36, -9,
+      -3, 20, 39,-20,  0,  2, 27,-16, 10, 10,-14,-22,-16, -3, 13, -8 },
+    {  5, -9,  6,-25,  7, 37, 13,-10, -5,  3, -5,  7, 18,-22, -7,  9,
+      -5, -4, 50,-11, -4, -5, -5,  8, -4, -2, -4,-27, 14, 20,  7, -9 },
+    {  0,-14,-10,-27,-14,-17, -6, 26, 10,  2, 14,-12, -5,  0,  8,  9,
+       0,-28, 55, -7,-12, -7,  4,-10, 10,  7,-12, 11,  3,  5,  9, -8 },
+    {  2, 23,  4, -2, -1,-20, -2, 14, 10, -9, -9,-24, 10,  0, 11,-12,
+      12, 11, 49,-25, -2, 29,  7,-13, 21,-10, 11,-17,  3,  1, -8,  5 },
+    {  3,  0,-14, -6, 18, -2, 17, -9,-19,  9, -5,  9, 14,  6, 19, -3,
+      27,  1, 41,-21, 20,-15, 33,  0, 26, 14,  7, 10,  3, 20, -3,-12 },
+    { -1, 16, 15, -8,  3, -8, -8, 21, -5,-16,-29,  4,  1, -6, -4,-28,
+       2, 31, 37,-26, -2, 13, 24,  8, -9, -6,-29, 10,  7,  2,  7,  8 },
+    {-10,-10, 11, 13,-32,  2, 16,  9, 14, 23,-15,-13, 24, 13,  4,-27,
+      14, 12, 31,-18, 17, 23, -2, -7,-14,  9,-17, -6,-10, 20,  9,  6 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  2,  0,
+       5,  1, 89,  8, 10, -6,  2, -1,  0,  0,  0,  0,  0,  0,  0,  0 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  2, -1,
+       4, -7, 64,-50,  7, 37,  2,  5,  0,  0,  0,  0,  0,  0,  0,  0 },
+    { -2,  5,  3, -4, -4, -3,  2, -3,  3, -3,  5,  4,  1, -6, -1,  1,
+       6, -2, 50,-35, -7, 43,  7, -7, -5,-26, 24, 21,  3,-15,  5,  6 },
+    { -8, 21,-19, 33, -8, 22,-11, 17,  3,  0,  0, -2,  1, -3,  6, -1,
+      10, -8,  4,-11, -4, -5,  0,  8, -4,  3,  1, -4,  4,  2,  8,  4 },
+    { -7,  5,-20,  9,-22,  3,-14,  1,  6, 13, 23, -2, -4, -7,  2,  0,
+      11,  4,  6,  3, -7,-11, -7,  4,  5,  5,-12,  8,  2,  4,  7, -3 },
+    { -7,  6, -4, 20,-20, 16, -2,  7,  6, 16, 11, 12, -7, -7,  5,  3,
+      -9, -4,  1,  2,  5,  2,  1, -9, -2,-17, -4,  6,-10,  7, -7, -6 },
+    { -9, 18,-17, 12,-24,  1, -1,  4, 14,  9,  4,  3,  2,  8,-12,-14,
+       4, -8, -4,  7,  7,  6, -1, 13, -9, -4, -1,  1,  0, -4, 15,  8 },
+    {-25,  2,-11,  6, -5, 24,-28, -5,  8, 12, -2,  6,  8, -3,  8, -9,
+      -1, -5, -1, -5,  6, -1, -1, -1, -4,  8,-12, -2,-13,  7,  2,  1 },
+    {-14, 14,-18, 20,-10, 12, -2,  9,  1,  0, 12, -2, 15,-10, 26,-17,
+      16,-11, 10,-10,  9, -2,  4, -8,  2, -3,  4,  4,  2, -3, -5,  1 },
+    {-18, 12,-18, 21, -6, 12, -6, 13,-25, 18,  1, 11, -9, -5,  0, 10,
+      -5,  3, -3,  8, -9,  7,  4,  2, -9,  0,  5,  0,  2, -3,  9, -8 },
+    { -4, 16,  1, 18,-30,  9,  1,  6, -8, 13, 13,-12, -6, -1, 13,  7,
+       6,  2,-15, -3,  5,  5,  1, -6,  1, -5,  0,  2,-16,  0,  3, -4 },
+    {-21,  1, -2,  6,-43, 18, -1,  5, -1,  4,  6, -2, -1, -3, -1, -3,
+       0,  1,  2, -9,  0, -1,  0, -2,  0, -1, -1, -2,  6,  0,  1, -2 },
+    {-23, 10,  4,  7,-32,-11,-18,  2, -2, -7, -6, -3, -3,-12, 19,  3,
+      -5, -6, 16, -6, 16,  2, 16, 16,  8, -2, 13,  8,-15,-11,  2, 10 },
+    { -8,  2,-13,  2,-29, 24,-20, 19,  1, 10, -4, 10,  1,  2, -9, 11,
+      -1, -2,  9, -5, 19, -7, 16, -9, -2,-18, 11,  1,  1,  0,  7, -3 },
+    { -6,  3,  4, 13,-26, 10,-10, 28, -7, 28,  1,  7,  0,-14,  5,  7,
+       4, -4,  3, -2,  3,  3,-11,  7,  6,  4,  0, -1,  2, -1, -3,  2 },
+    { -6, 16,-31, 13,-10, 17, -6,  4,-14,  4,  4, -1,-10, 12, -5,  1,
+     -14, 15,  0, -8,  1, -5,  3,  3,  9, -5,  7,-20,  7,  4, 11, -5 },
+    {-19,  3,-17, 14,-12, 16,-22, 18, 14,  8, -2,  4, 10, 12,-14,  4,
+      -3,  2,  3,  7, -7,  7, -6,  2, -2, -4, -5,  0, -5, -2,  2,  1 },
+    { -9, -7,-11, 24,-36, -9,-11,  5,  7,-12,-13, 18, -2, 20,  1, -4,
+      -1,-10, 15, -6, 14,  1,  0,  2,  1,  2, -9,-16,-11,  7, 13,  0 },
+    {-24, 24,-18, 18,-22, 14,-11, 13,-12, 11,-10, 11, -7, 11, -5, -4,
+      -1,  1,  5,  2,  3, -1,  1, -5,  7, -4,  5, -6,  8, -7,  8, -6 },
+    { -6, 18,-22, 22,  5, 11, -1,  6, 19, 22,  8,  4, -8, 20, -2, 15,
+      -6,-18,  0,-33, -9,-12, -1,  6,  5,  2,  5,  5, -5,-17, -3, -3 },
+    {  1, 11,-16,  9,-18, 11, -4, 18, 20, 26,-10,  8,  1,-11,  8, -4,
+       0,  7,  3,  5,  2,  2, 10, -2, -4,  4, -4, -2,  1, -4, -5, -1 },
+    {-10,  6, -1, 18,-17, 27, -3, 10, -2, 12, -7, -9,  1,  1, -1,  7,
+     -12, -1, -7, -6, -1,  8,  3,-15,  8,  9,  3, -7,  4, -1,  1, -1 },
+    {-14,  6,-16, 22,  2,  5,  0,  5,-18, 11,  6, -3, 22,-20, -9, -3,
+       6, -6, -7,-15,  1, 15, -8, 11,  8, -3, -8,  1, -8,  2,  6, -2 },
+    {-21,  5,-19, 19, -7,  4, -7,  0, -8,  6, 12,  5, -3,-22,-13, -6,
+      -1, -3, -2,-14,  6, -3,  1, -8, -7, -5, -6, 11, -3,-10, -5,  2 },
+    { -1,  9,-12, 15, -6,  6,-19, 14, -9, 11,  3, 12,-17, -3,  8, -4,
+      -3, -4,  1, -5,  4,  5, -7,-15, -7, 15, -6, -5,  1, -5, -3,  1 },
+    {-12, 20,-15, 20,-14,  3,-14,  9, -6, 33,-13,  6, -2,  8, -6,  7,
+      -5, -6, -3, -3,  0,  8, -3, -3,  1, -2,  2,  2,  6, -5, -5, -2 },
+    { -7, 12,-18, 12,-18, 10, -4,  8,  2,  4,  8,  9,  0,  3, -8,  3,
+       6,-12, -4,  1, 25, -5, -9,  6, -7,  0, -9, -7,  3, -5, -4, -4 },
+    {-18, 12,-10, 11,-22,  0,-15,  5, -2,  2, -3,  6, -4, -4, -3,-15,
+      -2, -3, 21,  6,-12,-11, 19,  3,  3,-14,  7,  0,-11,-22,-10,  0 },
+    {-15,  2,-30, 15,-17, 13,-16,  8, -7, 10, -8,  2, 11,  3, 10, -7,
+       7,-22, 12,-10,  3,-12,  6,-10, 12,-10,  7, -8,  5,  2,  9,  1 },
+    { -9, 11,-14,  6,-10, 21,  5, 12, -5,  5,  7, 21,  6,  2, -2, -1,
+      -1,  4,  2,-20,-18, -1,-14,  3, -1,  4, -7, 10,  1, 11,  4, -4 },
+    {-22,  8,-30, 13,-21, -4,  4, -1, 12,  9, -2, -3,  2, -6,  4,-13,
+      -2,  8,  8,  1, -7,  3, -4, -5, -1, -7, -2,  8,  8,  7,  8,  0 },
+    { -6, -4,-35, 16,-13, 15,-11, 14, -7,  9, -1, 11,  7,  0, 13, 10,
+      -1,  8,  1,  1, -2,  8, -1,  2,  2,  3,-10, -1,  7,-13, -3, -7 },
+    {-15,  7,-16, 14,-18, 17, -6, 14,  3,  4,  7, -3, 10,-22,  5,-15,
+       4, -4,-11, 15,-15, 11,-11, 20,  1,  0,  2,  1, 11, -3, 11, -7 },
+    {-12,  3,  5, 16,-37, -1, 15, 15,-15, 10,  3,-10,  1, 15,  7,-15,
+     -13,  8,  9, -3,  2, 12, -8,  2, -5,  0, -3,  4,  5, -9, -4,  5 },
+    {-16, 26, -4, 14,-22, 26,  6, -3, -8,  4, 21,  6, 16, -4,-11,  7,
+     -10,  3,  3,  7, -4,  2, -9,  8, -2,  2,  5, -2, -4, -2,  7, -1 },
+    { -7,-10,  4,  3,  2, -4,-12,-10, -4, -5, 16, 19,-16,  1,  2, -9,
+     -10,  0,  9,  7, -8,  3, 12,  8, -6,-11,-13, -1, -3,-20,  6, -5 },
+    {-14,-17,  3, -5, 14,-12,-12,  8, -6,-25, 21, 21, 10, -8,-12,  4,
+      10, -4,  3, -9, 11,  9,  0,  4,  2,-15,  1,-14,  4,  1,  0, -4 },
+    { -4, -9, -3, -1,  6,  3, -6,  6,-10, -4, 14,  8,  2, -3,-12,-19,
+       0, 11,-20,  1,  6, -2,-27, -6, 10,-17,-14,-17, -9,  8, -8,  3 },
+    {-12,-13, 16, -4, -2, 12, -7,-11,  2,-13,  3,  7,-16,-18, -1,-12,
+      -2,  1,-12, -9, -2, -6,  2,  9,-22, -3, -4,-14, -7,  7, -1,  2 },
+    { -7, -8, -8, 15, 15, 18, 15, 16, -4,-37, 11, 15,-12, -1, -3,  3,
+       6,  6,  0, -5, -3, -5,  9,  1,  1,-11, -1, -8, -6,  2,  3,  0 },
+    { -6,  7, -5,-12, 13, 10,-18, -4, -3,-21,  6, 16,-15, -7,-12, -9,
+       1,-12, -1, 10, -2, -1, -3,  4, -4,  1,-16, -1, 12, -9,  5,  9 },
+    {-14, -5,  9,  3,  4, 26,-28,  3, -6,-24,  4,  5,  3, 13,  5, -1,
+       3, -1,  3,  1,  1, -5,  3,  0, -7, -8, -7, -3,  3, -5,  4,  0 },
+    { -4,  2,-10, -6, 25, 26, -6, 10, -6, -8, 15, 11, -6, -3,  2, -7,
+       5, 14,  9, -1,  0,-12,  4, -4,-10,  1, -3,  3, -2, -2, -6, -1 },
+    {-10,  8,-15,-10, 19, 17, -8,  0, -3, -7,  7,  5,-13, -1,  7, -7,
+       1, 13,-12,-13, 17,-12,  1, 26,-18, -3, -5, -6,  4,  5,  8,  1 },
+    {  2, -5,  3,  0,  0,  0,  2, -3, -2, -5,  7, 13, -4,  9,  0, -5,
+       4, -1,-11, -8, -4,  0,-13,  2,-47,-23, -8,-11, -4,  4, -2, -3 },
+    {-18, -4,  4,  5, -1, 17,-12, -8,  1,-12,  7, 20,-12,  3, -2,-11,
+      16, 12, -6,  1,-13,-16, -6, -3, -3, -5,  4,-12, -5, -9, 10,  1 },
+    {-11,  0,  4,  7,  7,  8,  3, -1,  3,-19, 32,  8,-19, -8,  2,  4,
+     -12, 15,-16,  3,  1,  9, -2,  1, -2,  8,  5,  6, -4, -1, 11, -8 },
+    {  3, -1,  4, -2, 14, 32, -9,-23,-10,-12, 22, 15, -1, -2, 10,  0,
+       4,  6, -8,  4,-15, -2, -1, -4,  0, -8,  4,  1, -8,  3,  4,  1 },
+    {-17,-12,  6, -8, 16, 13,-20, -8, -1,-16, 10, 21,-19, 11, -9, -5,
+       7, 18, -6,  7, -7,-18, 13,  2, -2,  8,-12, -9,  2,  4, -5, 16 },
+    {  4,  0, 17,-11, 12,  7,-12,  5, -1,-25, 30, -8, -7, -6, -4, -7,
+       9,  8,  7,  3,  3,-16,  8,  0, -2, -2,-18, -3, -4, -5,  1,  4 },
+    { -3, -6,  6,-16, 17,  6, -3,  2, -9,-17, 12, 11, 11,  2,-20,  8,
+       1,  1,  0,  2, -2, -6,-21,-13, -9,-15, -1, -8, -6, -8,  0, -2 },
+    {-11, -7,  6, -9,  3,  6,  8, 16,  4, -5, 23, 26,-10, -3,  4,  0,
+       2,  2, -4,  4, -2,-12, 12, 10,-11,  0,-10,-16,  3,  0,  0,-10 },
+    { -5,-16, 10, -6, 27, 13, -3,  4, -2,-13, 15,  5,  2,  5,  3, -4,
+      13, 12,-11, -7,  0,  1, 11, 12,  2, 13,-15, -8,  9, -2,  3,  8 },
+    { -5, -8,  4,  3,  9,  3,-11, 10, 14,-25, 14,  8, -2,  5,-12,-21,
+       2, 10, -7,  2, -3,  2,  0,  2, -1, -3, -5, -6, -1,-16,  2,  8 },
+    { -1,  5,  1,-11,  5,  9, -7,  8,-13,-12,  4, 12, -4,  1, -1, -1,
+      27, 29, 10, 15,  2, -6, -3,  4,-21, 10, -9,-11, -6, -1, -9, -3 },
+    { -6, -3, -1, -6, 11, -5,  0, -2, -5,-31, 11,  3, -1,  5, -3,  4,
+       5,  7,-10,  5,-10,-13,  4, 12,-15, -2,  2, -7,  1, -9, -3,-10 },
+    { -3, -7, 17, -8, -5, 36,  8, -7, -8,-20, 12,  8,  1, -1,  3,  0,
+       1,  4,-10,  3,  1,  4, -2, -3, -2, -3,-10,  4, -1, -7,  3,  2 },
+    {-13, -3, -5,  9, 22,  6,-23,  3,-10, -7, 17, 17, 18,-14, -8, -8,
+       2,  4, -8,  2, -3, -8,  6,  4, -1,  7,  0,  0, -3,  0,-12, -3 },
+    { -3,-10,-15, -3,  9,  3,-23, -9,-13,-18, 12, 13, -2,  0,  1,  8,
+      -1,  2, -7,-12, -5, 14,  2,  1,-22,  6,-10, -8, -9, 28, -7,-14 },
+    { -3,  1,  2, -1, 13,  7, -2, -7,  1, -3,  6,  9, -3, -2,  4, -2,
+       2,  1,-10, -2, -2,-22, -2, -7,-10, -5,-11,-27,-12,-16,  4, -7 },
+    {  2, -6, -3,  1,  8,  0, -2, 12, -3, -4, 58, 15,-10, -4, -2,  2,
+      -2,  0, -2, -6,  2,  4, -1,  1, -4,  1, -1, -5, -4, -3,  3,  1 },
+    { 10, -1,  0,  5, 21,  7,-14,  6, -3,-16, 15, 17,-16, 13,  3, -6,
+      -4,  6,-12, -5,  1, -4, -7, -8,  2,  3, -6,  6, -1, -8,  5,  4 },
+    { -6, -2, -8,-11, 15, 10,  0,  8, -6,-15, 33,  8, -2, 18,-15,-11,
+       5, -1,  0, 15,-15, -4, -4, -1, 10,  7,-13,  4, -4,  0,  8,  3 },
+    { -7, -2,  0, -2,  0, -2, -4, -5,-14,-16, 12, 38,  7, 12,  6, -4,
+       0, -1,  0,  3, -2, -6,  0,  2, -9,  1,  0, -1,  0, -2,  4,  1 },
+    { -8, -4, 18,  1, 14,  5,-12, -3, 20,-17,  5, 19,-11, -8, 11, -3,
+       3,  9, -7, -8,  9,-17,  2, 15,-10,-11,  5, -5,  7, 15, -6, -2 },
+    { -7,  2, 38,  5, 19, 16, -5,  4,-13,-20,  0,  4, -4,  6,  4,  2,
+      -7,  6, -8, -2, -5, -7,  6,  3, -4, -3, -2, -3,  7, -6, -4,  0 },
+    {-11,-12,  8,-15, -3, 14, -7,-22,-11,  2, 22, 14,-19,  2,-19, -6,
+       1,  3,-18, 14,  2, -6, -2, -8, -3, -6,  5, -7, -8, -4,  1,  1 },
+    {  8,  7, 25,-21, 12, -6, -5, -4,-10,  6,  0, 10,  1,-12, 18, -5,
+     -15,  4,  1, 14, -1,  5,  8, -7,  1, -7, -3,  9, 10,  1, -1,  0 },
+    {  9, 10, 32,-15,  8,  2, 11, -7,-18, -8,  2, -6, -9,-16, -3,  3,
+      -1,  3,  1, -5,  4, -2,  1, -8,  0, -6, -3,-11,  1,  5,  0,  0 },
+    { 14,  0, 23,-25, 22,  3,  7, 10,  0, -2,  7,  8,  0, 10,  0,  0,
+       3,  2,  3,-10,  0, 10,  0, -7,  0, 10, -1, -5, -7,  1, -1,  2 },
+    { 12,  0, 25,-18, -5, -4, 13,-10,  3, -6,  7, 21,  0,-16,  3,-10,
+      -6,  5, -7, -3,  2,  5,  3, -6,  4,  9, -8, 12, -2,  3,  2,  4 },
+    { 31, 15, 27,-20, 10, -7, 15,-10,  9, -8,  4, -5,  3, -3,  5,  6,
+      11, -2,-12, -2,  6, -2,  1,  2, -1, -1,  1,  1,  3,  1,  1,  2 },
+    { 12, -4, 13,-23, 12, -6,  2,  4, -3, 13,  6, -7,  5,-19, -7, 18,
+       1, -7,  7,  1, 16, -7,  3,  0,  3,  0,-12,  8,-11,  9,  4,  7 },
+    { 29,  1,  3,-22, -5,  6,  0, 12,-14, 11,  1,  6, -3,  4,  6, -2,
+       4,-13, 12,  1,  1,  3,-11,  9,-10, -1, -7, 16,-11, -1,  3,  9 },
+    {  4,  4, 36,-23, -5, -8,-15,  1, -6,  3, 13, -1, -5, -7,  4,  9,
+       2,-11, -3,  5,  1,  3, -6, -1, -4, -4, -2,  2,  3, -1, -5, -2 },
+    { 19, 10,  6,-17,  2, -4, -2, -4, -3, 13,  2,  2,-13, -7, -3,-11,
+       9, -6,  1, -9, -5,  4, -5, -9,-18, -7,-11,  9,  4,-11,  8,  4 },
+    { 16, -3,  9,-16, 18, -2,-12,-16,-11, 11,-18, 16,-13,  6,  2,  8,
+       3,  8, -4,-16, 10,-11, -1, -3, -8,  5, -9, -4,  9, -4,  0, -3 },
+    { 14, 15,  3,-23, -5,  7, -8, -6,  2, 17,  2, 12, -8,-12, 13, -1,
+      -9,  3,  1,  1, 19, 15,  4, -1,  1,  2, -3,  2, -3,  1,  5,  3 },
+    { 32,  5,-10,-47, -5, -1,  4, 11, -7,  0,  2, -2,  1, -7,  6, -4,
+       6,  2, -4, -2,  2, -2,  0, -4,  1, -6, -5,  2, -2, -1, -3, -4 },
+    { 20,  8, 10,-21, -7, -9,-16, 12,  1,  4,  6, -5,  9,-11, -7,  4,
+     -11, 28, -3,  2,  4, -6, 10, -8, -5, -5, -9,  9, -2, -1,  6, -5 },
+    { 38,  3, 23,-25, -6,-18,  3,-10, -8,  6,-10,  1,-10,  2,  2,  0,
+      -7,  2, -4,  5, -1,  8, -3,  0,  3,  3, -1,  1,  0, -4, -4,  0 },
+    { 20,  5, 16,-22, 24,-18,  2,-12,-14, -7, -3, 10,  2,  7,-10,  2,
+      -8,  1,  8, -1,  4,  1,  4, -2,  5, -9,-18, -8,-13,  5,-11, 10 },
+    { 14,  8,-12,-16,  9,-11, -3, -6,-25, -7,  6,  5, -7,-16, 10,  2,
+      -7, -1, -9, -3, 16,  4,  3,  3, -3, -3,-15, 13, -3,  4, 13, -7 },
+    { 16, -9, 19,-23,  7,-19, -3, -5,-15, 11,-21, 21,-16, 18, -1,  6,
+      10,-10, 18,-14, 16,-15,  6, -5, -9,  5,-17, 13,-10, 13,  0, 10 },
+    {  8, -4,  4,-24,  8,-21,-18,  9,-11,  4, -6, 17,  5, -9, -2, -2,
+       2, 15, -2, -3, -2,  1,  7,-13, 15,-10, -8,-11,  3,  3, -1, -1 },
+    { 14, 17,  6,-32,  5,-17, -2,  0, 15, -1, -5, 16,  1, -5, -2,  9,
+      -3,  8,  4, -2, -2, -4, -3,  1,  0,  7, -3,  4, -5,  0, -7,  2 },
+    { 24,  6, 22,-12,  8,  3,-14,  4, -7,  8,  6,  5,  6,  1,  6,-12,
+      15, 10,  4, 11,  9,  6, -7, -4, 10, -9,  2, -1, -5, 11, 15,  3 },
+    { 17, 12,  3,-23,  5, -1, -2,  1, -9, -1, -3,  1,  8,  1, -5, 17,
+      11,  0, -2,-11,  7,  4,  0,-27, -7,  1,  2, -8,  9,  7,  5,  3 },
+    { 12, 10, 12,-10, -4,  5, -1,  2,-24,  5, -8,  2,  6,-17, 19,  5,
+      12, -2, 16, -7, -6,-14,  4,  1, -3, 13,-16,  5, -1,  4,  1,  1 },
+    { 31,  9, 11,-17, 10, -3, -7,  7,  1,  2,  2,  4, -3, -1, 11,  4,
+      -5, -8,  1,  4, 15, -6,-28,  1,  8,  3, -6,  5, 17, -2,  2, -4 },
+    { 11, 19, 16,-26,  0, -7, -7,  2,-13,-15,-12,  9, -3, 27,  8,  4,
+      -6,  1,  4, -6, 11, -1, -6, -7, -3,  0, -6,  4, -6, -7, -3, -1 },
+    { 10, 18, 16,-32, 19, -9, -4, -3, -7,  8,  8, -3,-11, -2, -6,-16,
+      13, 13, -6, -1, 10, -2, -2, -9,  0, -3,  9,  4, 11, -2, -6,  6 },
+    {  9,  4, 19,-33,  4,  7,-12, 36, -3, -1,  8, -2,  2, -8, -9, -4,
+      -8,  0,  1, -1,  0, -4, -4,  3,  0,  3,  6,  0, -6,  2,  0, -2 },
+    { 25,  7, 15,-12,  2,-24, -1, 24, -4,  4,  9,  0, -2, -9,  4,  6,
+       3, 13, -3,  1,  5, -1, -3, -5, -1,  7, -2,  3,  4,  4,  1,  0 },
+    { 19,  6,  8,-20,  9, -9,  5, -4,-13,  7, 11, -3,  5,-13, -9,  6,
+     -11, -1,  0,  4, 11, 26,  3,  6, -7, 12,  6, -3,  1, -9,  7,  1 },
+    { 15,  6, 19,-23, -3, -9,  3, 16, -6, -4,  6, -5,-10,  1, 16,-14,
+       2,  0,  2,-13, -3,  8, -6,  3,  1,  1,  2, -5, 12, -4, -8, -3 },
+    { 14,  4, 16,-20,  1, 12,  0,  6, -3,  9,  4, 16, 10,-16,  5,  7,
+       5, -4, -4,-18, -3,-11, -4,  4, -7,  3, 13,  7,  3,  3,  2, -7 },
+    { 22,  3, -1,-30, 18, -3, -9,  9, -2, 11,-16, -2,-14, 12,  0,  4,
+      -5,  4, -1,  3,-20, 12,  4,-10, -2, -2,-12,-12, 10,  6, 11, -3 },
+    { 15,  7,  2,-21,  5,  4,  9, -9,-33,  7,  7,  3, -6,-14, -8, 10,
+      12,  0,  2, -1,  5,  4, -2,  0, -7,  0,  2,  4,  0,  1, -3,  8 },
+    { -7,  0, 12,  3,  0, -6,  8, -4,  0,  2, 14,-15,  2, -7,-31, -3,
+      14,  0, 14,-15, -1, -4,-15, 10,  1, -3,  1,  2,  5,  2, -8,  1 },
+    { -2,  5,  1,  0, -3,  3,  3, -6, -1,  2, -4,  1,-19,  0,-11, 18,
+      11, 10, 21,  5,  6,  2, 10,  3, -6,  0, -2, 13,  5, -1, -2,  9 },
+    { -9,  1, -5,  0,  0,-15,  8,  4,  8,  3,  8, 12,-13, -2,-39, -2,
+       4, -4,  5, -3, -4,  3, -3,  3, 10,  5,  3,  2, -3,  5, -2,  8 },
+    { -9,  6,  6, -8, 12,-12, 23,-18,  4,-15, -5,  2,-20, 13, -7,  7,
+       7,-12, 14,-12,  6,  1,  1, -3, -8,  9,  0,  1, -7,  3,  7, -6 },
+    {-18, 13,  4,  3,-10,-30,-10, -6,-14,  1, -7, -4,-35,  5,-25, 11,
+       9,  8, 19, -4, -7, -3,-18, -8,  1,  5, 10, -4,-14, -9,  3, -4 },
+    { -6, -1,  4, -9, -9,  4, 20,  0,  0,  3, 11,  7,-16,-17,-20, 11,
+      -6,-14,  1,  4, 19,  2, -8,  6,-15,  3,  6, -5,-14,  3,  7,  2 },
+    {  1,  6, -2, -8, -5, -3,  3, -8, 21,  1,  3, 16,-14, -2, -9, -4,
+      13, -2, 18, 14, 14, 19,-13,  5,-10,  2, -3,  3,  5,  5,  1, -1 },
+    { -1, -5, -6, -2,-11, -7,  5, -4,  5, -1,  0,  3, -3,  2,-19, 18,
+      16,  4, 14,-22, -2,-11,-22,  1, -1, 11,  1,  2, 11,-10,  7,-12 },
+    {  1,  4,  5, -1, -9, -5,  1, 12,  5,  6, 12,  9,-24, 23,  1, 20,
+      14,-11, 13,  5, -2, -2,  5,  6,  2,  1, -9,  6, 10,  5, -4, 11 },
+    { -1, -1,  1,  7, -3, -4,  8,-16, 15, -1, -7,  9,-22,-11,-11, 10,
+      16,  9, -2,  4, 13, 10,  6, 16,  4,  7,  1, -8, -7,-14, -7,  4 },
+    {  1,  3, -6,  0, 15, -9, -4,  0,  4,  6, 12,  9, -6, -5,-22, 17,
+       7,-11, 15, -5,  1,  3,-19,  0,-15, -3, 16,  5,  5, -7,-11, 12 },
+    { -2, -1, 13,  2,  4,-24, 37, -5, -2, -6, 12,  7, -2,-23, -4,  9,
+       2, -3,  3,  2,  3,  3,-14, 11,  0, -4, -2, -2,  3, 10,-10,  4 },
+    {  2,  9,  8, -6,-28, 14, 28,-11, 18,-11,  0,  2, -2,  4,-12,  3,
+       6,  0,  7, -7, -6,  2,  5, -1, -1, -1,  5,  2,  3,  0, -3,  9 },
+    { -7, 14,  5,-10, -3,  7,  4, -5,  7, -8, -7,  4,-12, 14,-16, 25,
+       3,  0,  1, -5, 12,-10,  0,-10,  0, 12, 12, 17, 12, 10, -1,  0 },
+    { -4, -2,  5, -2,-17, -3,  5, -5,  7,-17,  1,  5, -4,  4,-20,  0,
+      11,-15, 13, -8, 10,  1,  1,  5,-12,  9, -8,  0,  6, -1,-11,  4 },
+    { -3, 12, 13,-15, -7, -7,  0,  5, 33,  3,  3, -6,-13, -7,-15, 10,
+       3,  3,  3, -5,  2,  7, -1,  0,-12,  2, 11, -6, -9,  0,  5, 11 },
+    { -8,  5, 10, -7,-14, -4, 13,  0, 18, -3, -6,  7,  1, -6,  0, 21,
+       8, -7, 10, -8, -3, 17, -9,  0, -5,  1,  4,  8, -3, 11, -5,  0 },
+    { -8,  8, -3, -8,  8,-11, 16,-16, 17,  0,  8, 16,-17, 10,-16, 10,
+      -8,  6, 11,  0, 10,  7,  4,  5,  7, -5, -5, -6, -7, -5, -1, 16 },
+    { -6,  0,  6,  1, -8, -8,  8, -7, -5,-10,-11,  8,-19,  6, -7, 13,
+       5, -3,  4, -8,  7, -1,-18,  9,  0, -5,  6, 26,  3,  8,  2,  4 },
+    { -2, -2, 23, -2,-20,  2,  7, -7, -6,-15,  3,  9,-19, -2,-10,  7,
+      -2,  7,  9, 11,  0,  4, -4,  6,  9, -2,  4, -3,  4,  3,  2,  8 },
+    { -6, 12, 10,-10, -7,  4, 17, 11, -6,  1, 12, 11,-18,  8,-12,  4,
+       1, 13,  6,-13, 23,  9, -5,  8, -2, -5,  1,  3,  0, -2, -4,  4 },
+    {  7,  1,  7,-17, -8,  8, -1, -7,  5, -6,  4, -3,-16,  9,-24, 18,
+      -3, 10, 13,-11, -6,-11, -4, 10,  0, 11,  8,  2,  6, -5,-11,  4 },
+    { -4,  1, -5,-10,  0, -3,  9, -2,  4, -1,  1,  5,-41,-10, -7,  4,
+      -3,  3,  1,  0,-12,  4, -3,  0,  2, -1, -2, -5,  3,  2, -7,  5 },
+    { -2,  1,  4,  4, -3, -6,  1,  0, 12, -5, 11,  0,-17, -3, -1, 11,
+       4,  1, 27,-12,  0,-14,  2,-15, -3, -9,  0, -7, -3, 15, -8,  6 },
+    { -6,  4,  9,  2,  4,  3,  7,-10, 28,  1, -2, 48,  7,  0,-10, 10,
+       1, -9,  2, -1,  0,  3, -5,  5, -4, -2,  7,  7,  1,  3,  2,  5 },
+    { -3,  3, -1,  3, -9,  0, -1,  3,  2, -6, 39,-14,-12,  5,-19, 21,
+       7, -6,  4, -1, -4,  0, -4,  1,  0, -9,  1, 10,  0, -2,  0,  7 },
+    {  4,  2,-29, 12,  5, -3, 16, -6, 15,-13, -4, -1,-13, 22,-16, 17,
+      16,  4,  9, -4,  4, -6, -4, 11, -8,  7,  8,  4,  3, -3, -7,-13 },
+    {  0,  3,  3, -6, -4,  0,  9,  0,  5,  0, 10, 10,  4,-13,-12, 16,
+      23, -4,-12, -6, -4, 20,  2,  0, -4, 23,  1,  8, 11, -4, -5, 15 },
+    { -6,  4,-15, -9, -1,-19, 12,-30,-17, -4,  1,-13,-13,  4, -3, 26,
+       5,-25, 11,-14, -6,-13,  0, -7,  9,  2,  8, -1, -8,  1, -8, 13 },
+    {  1,  6,  1, -4, -4,  1,  2,  0, -3,  2, 10,  6, -6, -2,-11,  4,
+      32, 15, 15,-47, -8,  3,-12,  4, -5,  4, -1,  0, -5,  5,  1, -7 },
+    {  2, -1,  0,  0, -1, -6,  0, -6,  4, -4,  5,  9, -5,  1, -3, 51,
+       4, -5,  4,-14, -1, -4, -3,  1, -4, -1,  0,  2, -8,  0,  1,  2 },
+    {  0,  4, -2, -7, -2, -9,  6, -8, 11, -3, -6,  3,-11, -8,-12,  8,
+      11,  5, 19,  3,-24, 19,-14, 11, -5,-18, -8,-12, -5, -4, -1,  4 },
+    { 16,  9, 10, 14,-18, -2,-18,-27, 10, -5, 12, 14,  4,  0, -2, -6,
+     -12, -7, -1,  3,  4,  7, 11, 10,  5, -5, -7,-16, -3, -6,  6,  9 },
+    {  7, 15, -9, 10,-19,  4, -5,-37, -2, -4,  8,  2,  4, -1,  1,  9,
+      -5, -5,-12,  1, -1, -8,  3, -3,  4,  6,  9,  3,  3, -1,  2,  4 },
+    { 13, 17,  3,  9, -7, -7,-15,-17, -8,-13, -4, -8, 19,  2, 16, 25,
+       7, 15,  2, 16, -5, -6,-10, -9, -7, -6, -2, -7,  7,  2,  4,  5 },
+    { 24,  7,  9,  8,-13, -2,  0, -4,  1,-13,  3,  6,  7, 10, -4, 15,
+       5,  7, -4,  5, -5,  3, 13, -7,  5, 15,-11, -2,  7,  5,  8,  6 },
+    { 17,  6,-15, 23, -2, -1, -6, -2,  0, -4, 11, -3, 12, 15,  6, -8,
+     -15, 10, -9,  7, -1,-11,  2, -8, -4,  3,  4,-10,  4,  4, 11,  1 },
+    { 21, 12, -3,  6, -8,  8,-11, -8, -5, -5,  3,  7, -1, -5, 12, 15,
+     -10,-11,  3, 15,  8,  4,  2,-15,  0, 14,  1, -8, -1,  3, 10, -7 },
+    { 16, 12,  5, 13, -6, 15,-23,  0,-17, -9,  0,  4, -9, 13,  6, 18,
+       0,  0, -4, -1,  0, 14,  5, -1,  8, -4, -8, -6,  5, -2, -2,  0 },
+    { 14, 16, -1, 12,-15, -9, -6,-20,  4,  6,  8,  9,  3,  1, -9, -4,
+      -1,-11,  9, 11,-12,  1,-14, -7,  2, -8, 11,  9, -4, 10,  4,-16 },
+    { 13, 10,  3,  7,  0, -8,-33, -6,  4, -4, 19, -2, 14,  6,  5,  7,
+       6, -3, -1,-10,-10, -9,  4, -3,  5,  9,  2,  2, 10,  9, -2, -3 },
+    { 11, 10, 25, 18, -1, -6,-21,-21,-11,-16,  6,  5, 14,  4,  8,  7,
+       0,-10, -7, -9, -5, -4,  3, -1,  1,  6, -1,  6, -2,  2, -3, -9 },
+    { 15,  9,  5, 22,-17, 15, -9,  7,  7, -9, 13,  9, 10, -1,  8, -3,
+      -2,  6,  1, 17,  8,-14,  7, -3, 12,  9,  1,  0,  1, -5, 17,-18 },
+    { 25, 19,-17, 12, -4,-10,  1,-13,-19, -7, -3,  9,  6, -2,  3,  1,
+       4, -2,-11,-14, -1, -7, -5, -9,  7, -1, -3,  4, -5,  1,  0, -1 },
+    { 20,  8, -3,-10,-24,  3, -6, -2,  0,-12, 14,  6,  7, 11,  4,  7,
+     -12, -5, -8,-10,  5, -1, -4,  4, 16,  7,-14,  6, -1, -2, -7,-11 },
+    { 16, 18, 17,  1,-15, -6, -5, -3, -1,-19,  8, -2,  2,  8, 12,-19,
+     -12,  8,  0, -3, -1, -1,  4,-14,  9, -1,-12, -1, -7, 10, -3,  5 },
+    { 18, 12, -7,  7,  0, -3,-13,  0, -1, -4,  9, -2,  6, -1,  0,  1,
+      15,-21,  1, -8, 25,-19, 13, -9,  2, 12,  5, -7, -3, -1, -3,  1 },
+    { 13, 16, -4,  9, -2,  2, -1,-19, -7, -4, 18, -6, 14, 18, -5,  4,
+      -6, -3,-19,-14, -1,-12, 10,  6,  7, 17,-12,-13,-10, -4,  5,  4 },
+    { 27, 17,  4, 14, -9, -2, -4, -8,  0, -6, 14,-11, -7,  2, -3, -3,
+      -2, -3,-13, 12, 16,  1, -5, -9,-10,-11, -2,  3, -7,  5, 11, -7 },
+    {  7, 17,-16, -2,-14,-28, -7, -8, 15,-10,  7, 15,  8, 17, 13, -1,
+       4, -7,-12,-11,  0,  0,  2,  3, -3,  7, -6,  6,  1,-16,  1, -2 },
+    { 23, 11, -9, 15,-23, -4, -6, -4,  2, -9, -7,  9, -8,  3,-13, -4,
+       8, 18, -6, -2,  1, -5,  6,-14, -5, -2, -6, -5, -3, -2,  4, -5 },
+    { 12, 13, 18, 18,-35,  2,  7,-17,  3,-11,  6,  9, -3, -2, 10, -4,
+       3,  3, -2, -7,  0,  2, -4,  0, -4,  0, -6,  5, 10,  4, -3, -1 },
+    { 19, 11,  1, 20,-14,  4, -9,-13, -2, 11,  0, 17, -1, -1, -1, -1,
+      -5, -8,  0,  5, -1, -8,  5, -1,  3,  2,-12, 21, -2,-24,  5,  7 },
+    { 15, 15,-15, 17,-14,-22,  3, -4,-11, -3, -7,  1, 18, 10,  1, 10,
+      -6, -3,  8,  2, -7,  0, -2,  1,  1,  2, -9, -2,  1,  2, -3,  4 },
+    { 45, 13,  8, 17, -5,  2,-16,  2,  8, -2,  8,-15,  4,  5, -1,  7,
+      -6, -2, -6,  2, -3,  0,  0, -9, -1,  7,  2,  3, -3, -3, -1,  5 },
+    {  1, 18, -8, 18,-12,-10,  3,  4,-22,-12, 20,  8, -3,  9,  2, 10,
+     -10, -3,  9,  3,  6, -3, 10, -1, -3,  2, -2,  4,  2,  3, -3,-18 },
+    {  9, 10, -5,  9,-35,-21,-18,-16, -1,-12, -6, -7,-15,-19, 12,  4,
+       4,  9, -7,  2, 14,  1,  4,  0, -1,  6, -7,  2,  1,  1, -4,  4 },
+    { 31,  8,-17, 35, -8,  1, -5, -6, -7, -6, 10, -2, -3,  6,  9,  3,
+      -6, -2,  3,  3,  5, -3,  0,  6,  0,  1, -5, -3, -2, -4, -1,  0 },
+    { 18,  4, -8,  7, -8,-15, -1,-16, 12, 18,  3, 19,  2,  4,  8,  8,
+       0, -5, -8,-12, 10, -5,  0,  1,  0,  4, -3, 16, 11, 11, -2, -6 },
+    { 27, 15,-17,-10,-23,-22, -1,-14, -4, -7, 20, -2, -7,  6, 15, -5,
+      32,  4,  9,-11, -3, -8, 11, -4, -1, -4, -8, -6, -4, -5, -2, -7 },
+    { 22,  4, -7,  2,-15,-11,-17,-10,  2,  0, 15, 11,  7, 12, -8,  6,
+     -10,-18, -6,-12,  7,  3, 22,  3, -7, 14, -5, -2,-13, -7, -1, -7 },
+    { 18, 13,  9, 24, -4,-19, -9,-11, 13,  8,  2,  4, -1,  8, 14, 10,
+     -12,  0,  0,  5, 10,  5,  4, -1,  5,  1, -1, 11,  2, -4,  0, -9 },
+    { 15, 19, -5,  1, -4,-10, -8,-27,  6,  8,  5, 10,  4, 11,  5, -5,
+     -11,  0,-11,-14, -4, -9, -8, -8,  6, -9,  4, -5, -1,  1,  5, -4 },
+    { 18,  1,-13, 14,-14,  9,-15, -7, 12,  1, 13, -4,-20, 12, 10, 12,
+     -12,  7,  1,-13, 10, -6,  5, -3,  4,  8, 10,-13, -3, -6,  9, -3 },
+    { 19,-14,  5, -8, -6,  2, -5,  5, -3, -1,-28, 11, 18, -6, -4, -2,
+      11, 14,-43,-42,  9,  2, 20,-23,  6, 32,  0,  5,  0,  6,  9,  5 },
+    {  8, 11,-14, -1,  7, 12, -7,  2,-16,  2, 10, -3, -1, -7, -7, -1,
+       1,-10,-60,-23,-18, 42,-13,  9, 18,-11,  0,  1,  0,  2, -5,  1 },
+    { -5, -1,  2,  0,  3, -3,  3, -2, -6,  0, -3, -3,  7,  2,  0, -2,
+      -2,  3,-34,-15, 37, 47, 10, 20,  9,  1,  3,-21,-25,-33,-14,  8 },
+    {  5,  6,  2, -2, -2, -2,  6,  5, -5,  7, -3,  1, -5,-13,  9,  3,
+     -17,-19, -2,-79,-12, -7, -8, -6, -2, -2, -1, -1, -7,-13,  6, -1 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1, -1,
+       0,  3,  4,-87,  6,-11, 16, -9, -1,  8,  0,  5,  0,  1,  2,  1 },
+    { -5,  6,  2,-24,  5, -9, -7,  0,  7,  3, -3, 16,-14,-16,  0, 18,
+      15, -9,-14,-28,-17, 53, 14, -6,-28, -1, -3,-10, -7,-14, 19,-15 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -3,  0,
+     -13,  0,-53,  3,-22, 63, 19, 16,  1,-11,  0, -3,  0, -3,  0,  1 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1, -1,
+      -1, -6,-43,-43, -2, 65,-13, -4,  9,  1,  1,  2,  1,  0,  0,  1 },
+    {  0,  1,  0,  0, -1,  0,  1,  1,  0,  0,  1,  2, -1, -1, -3, -1,
+     -23,  1,-61,-55,  3,-28, -6, -4, -4,  8,  2,  1,  1, -1,  0,  0 },
+    {  0,  1, -1,  1, -1,  0, -1,  0,  1, -1,  0,  1, -1,  0, -9, -4,
+     -48,-19,-52,-46, 11,-12,  5,-14,  0,-10,  0,  0, -1, -2, -1,  0 },
+    {  0, -3, -1, -4,  2, -1, -7,  3,  1,  3, -1,  1, -3,  0, -7,  0,
+       3, -7,-61,-51, -4,-21,-16,-21,-11, 14, -7,  8,  3, -5,  1,  2 },
+    {  0,  0,  0,  1,  0,  0, -1,  0,  0,  0,  0,  0,  1, -1,  9, -3,
+      56,-11, -6,-67, -1, 13,  0,  7,  1, -9, -1, -1,  0,  0,  1,  0 },
+    { 14,  9, -2, 14,-10,-10,  9, -5,  1, -8,-23, 30,  8, -7, 23,  8,
+       2, 10, -1,-27,-17, 57, 22,  4, -5,  2,-12, -6,  2, -7, -4, -9 },
+    {  1,  5, 12, -2, -2, -3,  2, -3,  6,  0,  4, -2, -8, -6,  0, 16,
+     -15, 29,-55,-29,-24, 29,  3, 10,  6, 13, 10, -5, 21, 11,-14,  5 },
+    {  4,  2, 26, -6, 10, 11,-23,-10,-27,-20,  3,-24,-11,-10,-13, 25,
+     -10,  5, -9,-36, -7, 43,  3,-13,  6, 13, -2,  0,  1,  3, -3, -4 },
+    { -1,  0, -1,  0,  0,  0,  0, -1,  1,  0, -1,  0,  0,  0, -1,  1,
+     -12, 12,-26,-64,-15, 29, 37, -7, -3,-12, -5, 14,  8, -8,-10, -2 },
+    { 19, -4,-11,-16,  8, 14,  5, 19,  3, 22,-11,-21, -1, -6,-11, 11,
+      10,-24,-23,-40, -8, 20, 17,  5, 13, -6,  3, 14,-20, -8,  3, 28 },
+    {  2,-12, 10,-14,-18, 26,-22,  4, -2,  5,-21,  8,  3,  1, 19,  0,
+     -12, 24,-14,-40, 15, 29,-15,  6, 15,  1,-19,  2,  4,  7,-12, -3 },
+    {  0, 17, 13,  7, -5,-11,  2,-19,  3, 38,-21, -3, -6, -4,  7,  1,
+       1, -5,-40,-10, -2, 35,  8,  8,-10, -8, -9, 33,  4,  4,  0, -2 },
+    { -2,-12,  7, 29,-24,  2, 16, -1, -7, 16, 10, -2, -2, -2, 13, -2,
+     -37, 15,-22,-40,-11, 33, 10, -1,  8, 10,  6,  8,  9,  0,-12,  2 },
+    { 15, -8, -9, -2,  7,-17,  7, 19, 14,  4, 12, 27, 11, 10,  4, 11,
+     -15, 14,-13,-48,  5, 18,  0, -9,-36,-11,  2,  4,  5,  5,-15,-12 },
+    {-12,  0,  3,  4,  7, -5,  5,-14,-24,-18, -6,-15, -8,-20,  1, -7,
+     -33,-28,-40,-38,-18,-10, -5, 17,-12,  4,  3, -5,  5,-13,  4, -7 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1, -1,
+      -3, -9,-49,-60, -5, 45, -1,  6,  0,  0,  0,  0,  0,  0,  0,  0 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1, -1,
+      -3, -9,-49,-60, -5, 45, -1,  6,  0,  0,  0,  0,  0,  0,  0,  0 },
+    {  0,  0,  0,  0,  0,  1,  0,  0,  0,  0,  0,  0, -1,  0,  0,  0,
+       3, -2,  9,-29,-11, 55,  8, 32,-36,-13, -7, 37,  4, 11,  0,  3 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+       4, -1,-39, -4,-30, 63, 28,-17, -6, 10,  7,-14, -9, 11,  9,  7 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1,
+      13, -2,-50,-32, 22, 51,  4,  7,  6, 11,-20,-13,  9, -5, 21, -4 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1, -1,
+      -3, -9,-49,-60, -5, 45, -1,  6,  0,  0,  0,  0,  0,  0,  0,  0 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1, -1,
+      -3, -9,-49,-60, -5, 45, -1,  6,  0,  0,  0,  0,  0,  0,  0,  0 },
+    {  0,  0,  0,  0,  0,  1,  0,  0,  0,  0,  0,  0, -1,  0,  0,  0,
+       3, -2,  9,-29,-11, 55,  8, 32,-36,-13, -7, 37,  4, 11,  0,  3 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+       4, -1,-39, -4,-30, 63, 28,-17, -6, 10,  7,-14, -9, 11,  9,  7 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1,
+      13, -2,-50,-32, 22, 51,  4,  7,  6, 11,-20,-13,  9, -5, 21, -4 },
+    { -8,  2,  1, 22,-31, -6,-25, -3, -3,  1,-15,-11, -2, -3,  4,-13,
+      -9, 15,-18, 37, -7,-37, 12,-13,-11,-25,-10,-11,-22,  7, 16,  7 },
+    { 14, 10,  4,-10, -1, -5, -7, -3, 16, 13, -5,-15,  5, 11, -1,  8,
+     -27,  7,-12, 49, 17,-22,  9, -2, -9, -1,  2,-15, -1, 41,-18,-17 },
+    { -4, -9,-15, -3,  3,  4,  4,  2,  7, -3, -7, -8, -5, 17,-19, -7,
+      36, -9,-38, 17,  1,-48, 11,-18,-13, -2, -8,  4,-10, -5, 21, 11 },
+    { 15,-13,  4,  2,  1, -5, -2,  1,-10,  7, -1,  3, -6,  0, 11,-11,
+       8, 20,-17, 51,-17,-41,  2, 15,  4,  8, -2, 16,-32, -1, 17,  6 },
+    { -8,  8,-18, -5,  4,  6, -3,  8,  0, -4,  2,  0, -1, -4,  5,  8,
+      30, 30, -8, 70,  2,  8,  2,  0,  7,  1, 13, -1, -6, -7,-11,  2 },
+    { -8, -7,  9,-10,-13,  6,-11,-14, 13, 25,-26,  5,  2, -5, -5,  5,
+      -8,  4,  0, 33, 12,-38, -4,  6, 13,  6, 25, 34, -1, 25,-19, -5 },
+    { 18,  3,-17,  4, -8,  7, 20,  1, -1,  5, -5, -2, -8,  8,-35, 15,
+      24, 43, -5, 51,  5,-12, -3,  1, -2,  3, -3, -3, -9,  8, -9,  2 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,
+       2, 10, 24, 76, -2,-22, 11, -1,  4, 33,  4,  1, -1,  1,  2,  0 },
+    {  0, -1,  0,  1,  0,  1,  0,  1,  0,  0,  0,  0,  0,  1,  2,  0,
+      24, 13, 32, 70, 26,  5,-21, -9, -6,-15,  2, -2,  2,  4,  1,  1 },
+    {  5, -4,-11,  4, -4, 22, 10, -2, 13,-11, -4,-21,-17,  0, -7,  4,
+      10,-34, 11, 52,  2,-46, -5,  0,  0, -1,  2,  4, -9,  1,  1, -7 },
+    {  0,  1,  1,  0, -1,  0,  1,  0,  1,  1,  0,  1,  0,  0, -3,  1,
+      -8,  9, -1, 64,-13,-61, -3,  3, -5, 10,  1,  3, -1, -1, -1, -1 },
+    {  0,  1,  0, -1,  0, -1,  0,  0,  1,  0,  0,  0,  1,  1,  2,  1,
+      10, -2,-31, 79,-10, 27,  0, -1,  3,  8,  1,  1,  0, -1,  0, -1 },
+    {  3, 12, 10, 26,-19, 10, -9,  6, -4,-15, 10,  3,-16,  6, 11,-19,
+       3, 10, 18, 44,  5,-30,  5, -9, 21,  4, 20, 10, 14,-25,  8,-17 },
+    {  0,  0,  0,  1, -1,  0, -1,  0,  1,  0,  1,  1,  0,  0, -6, -2,
+       8, -8, 13, 69, 26,-19,-25,-17, 16,  6,-12, 22,  2, -6,  9,  5 },
+    {  0, -1,  0,  1,  0, -1, -1,  0,  0,  1, -2,  1,  0,  0, -4, -1,
+     -34,-15,-33, 56,  9,-42,  9, 10,  6,  9, -8,-11,  0, -6, 15,  5 },
+    { 10,  2,-14, -3,-15,-35, -1,  7,-18, 14,  8, -1,-15,-26,  6,-15,
+     -18, 22,  9, 33,  0,-32, -9,  3,-11,  7,  4, -1,  5, 30,  9,  1 },
+    {  4, 15,  0,  6, -5,-11,  9,  6,  6,  6, 14,  2, -1, 10,-24,-25,
+      -2, -4, -1, 37,  2,-29, 14, -9, 22, 17, -2, 33, 10,-25, 11,-11 },
+    {  0,  5,  2, 18,-12, 21, 22, 33, -7, 21, -9, -7,  7,-15, -7, 16,
+       7,  0,-14, 44, 10,-25,  5, -4, 15, -8, 10, -4,  5,  9, -1, 16 },
+    {  3, 13, 12, 12,  8, 25,-23,  8,-22, -3,-18, -8, 15, 12,  9, 19,
+       0,  0, -9, 49,-27,-15, -9,-15, 12, -8,-16, -7, 13,  5, 13,  2 },
+    { 12, -6,  7, -2, 20, -9,-14, 12, 13, -5,-17, 22, -8, -4,  2,  7,
+     -13, -2,-15, 43, -5,-30, 27,  4, 10,-27,  5, 27,-10,-10,-18,  0 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,
+      -1, 10,-18, 70, -2,-52, -1, -7,  0,  0,  0,  0,  0,  0,  0,  0 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,
+      -1, 10,-18, 70, -2,-52, -1, -7,  0,  0,  0,  0,  0,  0,  0,  0 },
+    { 15,-13,-20, 16,  2, 13,  5,-11, -8, -5, -3,  2, 24,-23, 30, -7,
+      11, 30,-15, 43,  5,-15, 15, -3,-14,  1,-23,  8,  3,  9,  4,-11 },
+    {  0, -1,  0,  1,  0, -1, -1,  0,  0,  1, -2,  1,  0,  0, -4, -1,
+     -34,-15,-33, 56,  9,-42,  9, 10,  6,  9, -8,-11,  0, -6, 15,  5 },
+    { 10,  2,-14, -3,-15,-35, -1,  7,-18, 14,  8, -1,-15,-26,  6,-15,
+     -18, 22,  9, 33,  0,-32, -9,  3,-11,  7,  4, -1,  5, 30,  9,  1 },
+    {  4, 15,  0,  6, -5,-11,  9,  6,  6,  6, 14,  2, -1, 10,-24,-25,
+      -2, -4, -1, 37,  2,-29, 14, -9, 22, 17, -2, 33, 10,-25, 11,-11 },
+    {  0,  5,  2, 18,-12, 21, 22, 33, -7, 21, -9, -7,  7,-15, -7, 16,
+       7,  0,-14, 44, 10,-25,  5, -4, 15, -8, 10, -4,  5,  9, -1, 16 },
+    {  3, 13, 12, 12,  8, 25,-23,  8,-22, -3,-18, -8, 15, 12,  9, 19,
+       0,  0, -9, 49,-27,-15, -9,-15, 12, -8,-16, -7, 13,  5, 13,  2 },
+    { 12, -6,  7, -2, 20, -9,-14, 12, 13, -5,-17, 22, -8, -4,  2,  7,
+     -13, -2,-15, 43, -5,-30, 27,  4, 10,-27,  5, 27,-10,-10,-18,  0 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,
+      -1, 10,-18, 70, -2,-52, -1, -7,  0,  0,  0,  0,  0,  0,  0,  0 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,
+      -1, 10,-18, 70, -2,-52, -1, -7,  0,  0,  0,  0,  0,  0,  0,  0 },
+    { 15,-13,-20, 16,  2, 13,  5,-11, -8, -5, -3,  2, 24,-23, 30, -7,
+      11, 30,-15, 43,  5,-15, 15, -3,-14,  1,-23,  8,  3,  9,  4,-11 },
+    { 16,-18,  7, -4, 31,-15, -9,-13, 20,-12, -6,  0, 12, -6, -2,  4,
+       3, -3, -1,  0,  1,  3,  3, -2,  1,  6,  4,  0, -3,  2, -5,  1 },
+    { 38, -5,-13, -4,  8,-15, 11,  1,  2, -4, -1,  9, 13,  4,-12, -7,
+       0, -2,  7,  2, -6, -2, -3, -2,  3, -4,  6, 15,  1,  1,-11, -2 },
+    { 47,-22,  9,-26,  3, -5,  2, -7,  4, -2,  2, -2,  3,  0,  3, -4,
+       3, -3,  2, -3,  7, -3, -1,  1,  1, -5,  5,  0,  2, -5, -3, -2 },
+    { 14,-16,  2, -6,  7, -2, -7, -4, -4, -7, 14, -3,  7,-19,-14,-17,
+     -29,  6, 26, 16, -5, 13, -4, -1, 21, 14,  1,  3, -6,  0, -7, -1 },
+    { 29,-11,  5, -3,  4, 11,  4,-10,  1,-22, -3,-10,  5,  4,  2,  8,
+      -2, -7,-12,-12, -8, -3,-18, -2, -9, -5, -1, -3,  2,-14,-14,  7 },
+    { 28,-12,  5,  3,  9, -7,  0, -2,  2,  1,  4,  0, -7, -3, -2,  4,
+       4, 14,  8, -1, -4, 14, -7, 17, -2, -2, -9,  2, 19, -7,  9, -8 },
+    { 31,-18,-22,  8, 15, -5,-10,-15,  1, 10,  6,  7,  6, -8,  2, -1,
+      12, -3,  3, -1,  1,  5, -6, -4,  0,  1,  7,-10, -2,  4, -3, -4 },
+    { 53,-30, -4, 12,  2,  3, -3, -3,  0,  1,  6,  5, -5, -4, -7,  1,
+       0,  2,  1,  3,  1,  5,  0,  2,  2, -1,  0,  4,  2,  0, -2,  0 },
+    { 27,-18, -3, -2,  4, -8,  3, -2,-11,  2, 10, -8, -8, -4,  0, -2,
+       8,  0,  9,  0,-16, 11,  1, -6, 13, -3,-10,-13,-15, 25,  1,  0 },
+    { 35, -5, -1, -8, 23, 11,-14, -3,  2, -2,  8, -6, 17, -2,  7,  0,
+      -2, 10,-17, 13, -2, -2, 11, 11,-14,  2, -2, -3, -8, -1,-12, -5 },
+    { 29, -9,  7,  3,  2,-10,  0,  3,  9,  0, -3,  5,  1,-10, 10, -5,
+       3,  6,-20, -9, -6, -4,  1,  0, 12, 17, -8,  9,  3, -1, -9,  0 },
+    { 15,-16, 18,-19, 16,-15, 17,-18, 13,-16, 17,-14, 15, -9, 13,-17,
+       9, -7,  4, -5,  3, -4, -3,  0, -6,  7, -9,  7, -2,  7, -9,  9 },
+    { 21,-10,  7, -2, 12, -7, 13,-17, 11, -2, 20,  3,  5,-11, -6, -6,
+     -15,  0, -9,  5,-11,  7, -1,  7,  8,-10, -9,  3, -5,  9, -8, -2 },
+    { 23,-22, 15, -5, 16, -4, -3,-12,  9,  3, -1, -2, -8,  2, -2,-16,
+       3,  4, -2, -6, -7, 12, -8,  2,-14,  2, -7, 11, -2,  6, -4, -1 },
+    { 34,-17, -4,  8,  4, -6,  1,  8,  4, 16,  3,  6, 12, -1, -1,-15,
+       6,  4, -7, -6,  6,  0,  2,  1, -2,  2,  3,  3, -3, -2,  8, -6 },
+    { 18,-18,  2, -2, 10,  1, 18,-23, -3,-10,  0,  4, 20,-19, -3, -4,
+       2,  8,  6,  1, -3,  1,  1,  3,  5, -1,-11,  3, -7,  5, -1,  1 },
+    { 15,-14,  2,  3, 10, -8, 12,-13, 13,-15,  6, -8, -4,-10, 14, -9,
+      24,  2, -7,-18, 13,-11,  8, 14, -6, -2,  3, -1, -4,  7, -7, -4 },
+    { 20,-12, 13,  5, -1,-10, 15, -6,  8, -1, -3,-10, 17,  0, -6,-19,
+       2, -1,  8, -3,-16,  0, -3,  2, -2,  0,  8, -9,  0,  1,-10, -9 },
+    { 32,  0, -9, -5, -1,  5, 13,-11,  8,  3, 11,-11,  0, -8, -2,-14,
+       7, 10,  6, -5,  1, 10,  2, 12,-10,  4,  4,  6,  4,  0, -7,-10 },
+    { 16,-14, 10, -7, 11,-11, 11,-11, 18,-13,  8,-15, 16,-11, 13, -9,
+       8, -7, 12,-11,  7, -6,  3, -5,  9, -5,  4, -1,  7, -4,  8, -3 },
+    { 24,-27, -1,  5,  8, -5, 12,  7,  4, -3,  3, -1, -9,-11,-13, -5,
+      10,  0,-13,  7,  1, -5,  4, -9,  7, -3, 13,  2, -5, -3,-17, -2 },
+    { 23,-19, 15,  1,-10,-18,-12, -6,  8, -3, 12,  0,-12,-10, -4, -4,
+       8,-10,  4,  2, -2, -8, 13, -3, -2, -6,  2, -3,  5, -2,  2, 11 },
+    { 25,-12,  4,  2, 24, -3,  3, -6, 14, 11,  0,-21, -3, -3,  1, -8,
+       7,  0,  0,  3,  3, -6, -7,  6,  2,  1, -4,  5, -1, 10, -2,  9 },
+    { 24, -8, -6,  7, 16,-12, 13, -1, 11,-21,  2, -6,  3,-12,  0,  9,
+       4, 11, -7,  1,  4,  1, -8,  3,  3, -6,  3,  3,  0, -8,  8,  4 },
+    { 25,-21, 13, 14, 13,-18,  4, -3,  0, -5, -4,  5, -3,  0,  4, 12,
+       7,  3,  5, -5,  2, -2,  3,-10,  2, -9,-15,  6,  1,  7, -5,  1 },
+    { 23,-16, -2, 10,  4, -1,  3,  1, 32,  3, -5, -2,  9, 10, -1, -4,
+      -6,  2,  9, -1, 14, 12, -6, -1,-17, -2, -4, -9, -7, -6, -8,  3 },
+    { 50, -8,  5,  2,-11, 10,  0,  0,  6, -3,  7,  0, -3, -2, -3,  0,
+       6, -4,  2, -5, -9,  0,  3, 10,  1, -7, -2, -3, -6, -9,  1, -2 },
+    { 28,-17,  0, -2,  2, -9,  1,  5, -4, -1,  0,  0, 19,-27,  5,-12,
+       7,-14, -3, -6, 10, -2, -4, -2,  4, -5, -2, -7,  1,  7, -9,  4 },
+    { 22,-19, -6, -6,  3,-22,  3,  5, 20, -8,-14, -5,  1,  1, 20,  2,
+      16,  6,  3, 14,  4,  3,  5,  1,  5, -7,-10, -6,  3, -6,  1,-14 },
+    { 29,-14, -8, 13,  8,-10, -6,  4,  4, -6,  5, -7,  1, 12, 14, 11,
+      -7,  1,  2, -9,-11, -9,  0,  4, -1,  7, 10,  4,  4, 20, -1,-11 },
+    { 18, -9,  4,  1,  7,-29, 12,  1, -1, -9, -2, -1, -2,  2,  9, -8,
+     -13,  5,  4,-13, -4,  2, -5, -7, -6, 14,-10,-34, -3,  1, -3,-13 },
+    { 38, -9, 24,  8, 11,  4, -6,-11, -2,-12,  1,  1,-11, -8, -5, -2,
+     -15, -8,  8,  0,  1, -7,  5,  4, -1,  8, -2, 11, -3, -1, -5, -5 },
+    {-20, 11, -4, 24,-11,  1, 15,  4,  0,-28,-10, -1, 10, 10, -6,  5,
+      -6,  2,  7, -2,  1, -2, -6, -3, -7,  1,  2, 12, -1,  7,  0, -2 },
+    { -9, 10,-23, 27, -4,-17, 20, -6, 14,-17,  5, -1,  5, -9, -7,  5,
+      -6,  4, -2,  9,  0,  8,  0,  1, -3, -3, -5, -8,  5, -2, -2, 12 },
+    {-10, 19,  4,  9,  1,-16, 17, -2,  9,-29,-16,-11, -4,  7, -5,  4,
+      -1, -3,  3,  2,  3, -4,  5,-12, -2,  6,  5, -4,  4,  1,  4, 10 },
+    {-20, 10,-24, 14, -5, 11,  9,  0, 16,-20, 10, -5, -6, -6, -1,  2,
+      -4,  5,-16,  8, -2,  5,  5,-11,  9,-11,  4,-11, -1, -1,  4,  3 },
+    { -9, 11,  3, 19, 24,  4,  5,-14, 30,-17, -4, -2,-17,  7,  2,  3,
+       1,  3, -7, -4,  2, -3,  1,  4, -1, -1,  3,-12, -2,  3, -3, 10 },
+    {-19, 18, 11, 19, 19, 19, 10,  4, 13,  6,  5,  4,  8,  3, -2, 12,
+      -6, -2,  7, -6, 15, 12, 16, 16, 18, -3, -4,-20,  0, 10, -9, -3 },
+    {-21,  9, 20, 12,  0, -3,  5, -9, 15,-13,  5, -5, -6, 24,  2,  9,
+      -5,  2, -7,  2,  5,  7, -5,  2, 15,  3,  1, -1, -4, -2,  7,  0 },
+    {-18, 16, 13, 15,  2,-10, 14,-11,  4,-11,  5, 12, 12, 20,  8, 30,
+       2, 11, -9,  7,  0, -3,-16, -5, -6,  5, -4,-21,  0,  5,  6,  1 },
+    {-26,  8,-13,  9,  6,-10,  2,-11,  7, -4,  6,-19,-11, -6,-12, 16,
+       0,  5, -7,  8,  5,  6, 17, -9, 10,-10,  5, -3,-11,  2,  4, 10 },
+    {-11, 17, -3, 22, -5, 18,  3,  1,  4, -5, 14,-27,  5, -7, -4, -5,
+     -10, 11,  1, 15,  1,  1, -6, -5, 10,-22, -7, -7,-15, 13, -4,  5 },
+    {-17, 14, -7, 13,  3,  0, 13, -6,  9,-14,-22, -1,  1, 19, 14, -3,
+       4,-13,-13,  2, -4,  8, -2, -2, 13,-12, 13,-12, -7, -5, -3,  6 },
+    {-17, 17, -1, 33,  6,  3,  9,-16,  3,-14, -8,  6,-17,  8,  3, 13,
+       8, -6,  3,  1, -2,  0, -2,  8,  4,  9, 13,-10,  4,-17,  0, -6 },
+    {-20,  7,  7, 21,  1, -3,  7, -3, -2,-12,  9, -7,  2, -3, 14,  1,
+      -1, -7, 12,-10,  5,-20, 11, -2,  0,-24,-17,  6,  6, -4,  3, -1 },
+    { -8, 10,  6,  7, -1, -6, 28, -6, 10,-33,  1,-20,  0,-12, 10,  1,
+      -6,  8, -3, -1,-10,  8,  5,  0, 10, -2,  8, 16, -5, -3, -7,  4 },
+    {-17, 13,  3, 15,  1, -5, 27, -5,  6, -6, 12,  2, -4,  8, -1, -3,
+      -2, 12,-15,  3,  4,  1,  2, -9,  0,-16,-21,  2, -4, 16, -7,  4 },
+    {-15, 20,  8, 17,  5,-14, 15,-11, 21,-11, 13,-13,  2,-15,-13,  1,
+      -5,  5,  2, 10, -9,  4, -1,  3,  2, -4, 13, -5,  1, -4,  5, -3 },
+    {-21,  8,  2, 16, -1,  2, 15,-16, 13,-12,-12, -7, -8,  2, -7, 11,
+      -8,  5,  2, -7, 16, -4,  1, -7,  3,-15,  6, -5, -8,  2, -8,  5 },
+    {-15, 17, -6,  3, -3,  3,  9, -7, 14,-23, 11,  1, -1,  4,  7,  6,
+      -1,-14,  7,  6, -8,  5,  1,-15, 10, -9,  2, -3, -1,  4,-10, -4 },
+    {-10, 18,  3, 11,  1,  4, 14,-14,  7, -4, 15,-10, 10,-11, 10, -4,
+       5,-14, 10,  4, 15,-12, 15,-13, 20,-15, 14,-15,  8,-11,  4, -6 },
+    { -7, 23,  2, 20,  7,  8, 19, -5,  9,-16, -8,-17, -5,  1,  5, -6,
+      -8,  1, -6, -4, 10,  6,  6,  2,-11, -4,  0,  2,  4,  7,  9, -4 },
+    {-15, 20, -5, 22, 11, -8,  9, -5, 10,-13, -8,  8,  2, -2, -3,  7,
+       6, 10,  1,  2, -5, -9,  1, 10, 16,-22, -7,  0,  7,  7,  6,  1 },
+    {-26, 19, -5,  3,  5, 25, 18, -5,  9,-14, -8, -6, -2, -6,  2,  3,
+      -8, -2, -7,  7, -3,  7,  3,  4, -8,  0,  1, -8, -4, -2, -2,  1 },
+    {-20, 14,-10,  6, -3,  7,  8,-32, -2, -7, -2,-10, 16,-12, -9, 15,
+      -2, -5, -6,  2, -7,  5,  9,  1,  6, -7, -1,  0, -2, -4, -7,  3 },
+    {-14, 16,  4, 11, -8,  1, 23, -4, 17,-13,-10,  1, 12,  9, 12, -4,
+       7, -1, -1,  5, -8, -6,  3,  3, -6, -3,-18,  0, 18, 20,  4, -2 },
+    {-33, 19,-10, 30, 15,  2, -3, -1, -4,-14,  7, -7, -1,  7, -8,  9,
+      -1, -3, -5,  2,  2,  4,  0,  5,  0,  0,  2,  3,  3, -3, -3,  4 },
+    { -6, 20,  0,  5, 17,-10, 18,-17,  9,-16,  4,-13, -6,  2,-14, 14,
+     -28,  9,-12, 25, -4,  7,  7, -8,  6, -6, -2,-10,  2,-11, -1,  2 },
+    {-12, 14, 12, 52, -3,  5, -5,  4,  8,-13,  2, -5, -4,  2, -2, -1,
+      -2,  3,  3,  5,  2,  3,  0,  1, -5,  2, -4, -3,  1, -5, -2,  0 },
+    {-13,  6,  9, 24,  0,  8, 14,-15, 18, -9,-11, -8,  3, 15, -2, -4,
+      -9,  4, -3, 12, 14,-13, 11, -4,  2, -4,  0, -6, -6, -6,-14, -1 },
+    {-10, 28,  3, 12,  9,  3, 11,-28,  6,-11, -7,  4,  0,  7,  8, -9,
+       0, -6,  0,-16,  4,  7,  4,  4,  7,  3,  4, -7,  0, -3,-10,  6 },
+    {-11, 14, -2, 19, -1, -1,  7,  9, -2,-27, 10,-14, 15, -4, 12, -4,
+       2, -2, -6, 12, -6,  0, -5, -4, -5,  1,  3,-11,  5, -9,  3, -8 },
+    {-18,  7, 13, 16, -4,  3,  9,-10, 10,-10, -3,-22, -4,-12,  3,-16,
+       0, -3,-16,  8,-11,  1, 10, -7, 15,  3,  0, -1,-13,  8,  1,  6 },
+    {-20, 10,-10, 10,  8, -1,  6,  0, 16,-12,  9,-10, -1, -5, -4,-13,
+      13, 16, -8, 12, -2, 14, 18, 13,  0,-16,  2, -5, -5, -5, -4,  3 },
+    {-14,  5, -7,-17,  5,-13, 23, 20, -4, -1,  1, -6, 13,  5, -1,  4,
+     -14, -2, -7,  8,  3,  2,  2, -7,  2, -1,  4,  7,  3, -9, -1, -5 },
+    {-19,  3,-24,-28, -9, -7, 19,  3,  2, 19,  7,  5,-13,  8,-15,-17,
+       3,-11,  4, 13,  3,  2, -1, -3, -4, -4,  2,  0, -5, -6,  6,  2 },
+    {-17, 18,-30,-20, -2, -3,  1, 15, -1,-11,  6, -4, 11, 11, -4, -5,
+     -10,  0,  0,  1,  3, -7,  8,  2,  5,  1,  5, -5,  1,  6,  4,  1 },
+    { -6,  1,-30,-25, -1, -8, -2, -9,-17, 16,  3, -1, -2, -9, -6, -7,
+      -3, 12,  6, -4,-10,  0, 10, -8, -6, -5, -3,-11, -4,  0, -1, -3 },
+    { -1, -1,-34,-28,  1,-10,  2,  9,  4, 16,  2,  6, 14, 17,  0,  7,
+      -4,  4,  4,  4,  0,  1, -1, -5,  8,  1, -4,  1, -9, -2,  5,  6 },
+    {-11, 14,  1,-31, -7,-24,  9,  7,  6,  5,-13,  1, -1,  3,  4, -1,
+      -2, -8, -6,  3,  5, -4, -6,  7, -2,  5,  3,  3,  0,  0, -5,  2 },
+    {-25,  8,-11,-18,  1, -4,  8, -3, -4, 15,  6, -5,  8,  2,  3,  4,
+      -4,  5,  6,  8, -7,  6,  1,-11,-15,-13,  9, -4,-14, 10, 12,  7 },
+    {-20, 11,-15,-25,  3,  4, 18, 13, -4, -5, -9, -1, -5, -2, -2, -7,
+      16,  5, -4, -5, -7, -2, -3, -9, 11, -2,  0, -7,-17, -6,-11,  6 },
+    {-11, 18, -5,-20,-15, -3,  9, 11,-20, 12,  5,  5, 11, -3,  7,  1,
+      10, -6, -3, -3,  3,  3, 14, -7, 10,-17,  9,-11, -2, -6,  7,-12 },
+    {-20,  8,-14,-17, -9,-13, -3,  0,-27,-14, -3,-14,  4,  3,  6, -6,
+       7,  4, 23,  9, 11,  9,  3, -4,  9,  2,  4, -1, -6,  1, -8,-11 },
+    { -9, 14,  2,-37, -7, 13,  6,-11, -6,  9, 18,-11, -6,  2, 12,  4,
+      -1,  3,  1, -2, -2,  1, -9, -4, -2, -3,  3,  5, -6,  0, -2, -8 },
+    {-29,  8, -1,-13, -2,  8, 23,  2,-10,  7, 13, -6, -5, 11, 13,  0,
+     -10,-13, 11,-12,-10,  6,  4,  6,  4,  3,  6, -5, -9, -2, -1,  3 },
+    {-18,  6,-10,-55, -4,-11, -2,  0,  1, -3, -9, -6,  3, -2, -1,  6,
+       3, -1,  3,  1, -4, -7, -2,  6,  3, -2, -1, -3, -2,  0,  4,  1 },
+    {-14,  5,  3,-21, -8,-16, -4, -2,-11, 27, 15,-20,  3,  0,  1,  1,
+       2, -5, -5,  4,  1, -9,  5, -3,  3,  0, -4, -2,-11, -4, -3,  7 },
+    {-17, -1, -9,-17, -8,-18, 12,-13, -9, 13, -3,  3,  3, -3,  1, -2,
+       0, 16, -9,  6, 12,  9,  5, 11,  2,-15,  1, -4,-16,  7, -4,-12 },
+    {-18,  8, -6,-11, -8, -7, 13,  7,  1,  6,  8, -1, 21, -4, 14, 15,
+      18, -4, -3, 15,  0,  9,  4,  7,  3, -1,  9, -2,  0,  7, -8,  2 },
+    {-10,  7,-18,-29,  3, 12, 12,  9, 11,  4, -1,-15,  1, -1,  8, -2,
+      -2, 10,-15, -1,  0,  6, 12, -6, -1, 10, -6, -3,-11, -4,  9, -6 },
+    {-14, 14, -9,-21,-12, -2, -1, -7, -5,-10,  5, -8,  0,  6,  9,-11,
+      11, -3, -5,  3,  8, 15, -2, -4,-22,  4, -6, 12,  2, 13,  6, -7 },
+    {-12, 11, -5,-29,-25,  4, 12,-13,-11, -7,  4,  2,  2, -5,  5,  8,
+       7, -5, -5,  6,  3,-10,  1, -6,  6, -6, -5, -1, -2, -4,  7,  6 },
+    {-15, 11, -5,-16,  0,-13, 26,-23, -6, -3,  5, -2, -2, 21, -6, -3,
+      -5, -1,  6, -1,  0,-13,  2, -3, -9, -1, -4, -3,  5, -4, 12,-16 },
+    { -9,  9, -1,-17, -3, -6, 12,  6,-18, -2, 11,-14, -6,  3, 14,-12,
+     -11, -5, 14,  2,  5, -8, -4,-11,  2, -5, 16,  6, -7, -4,  8, 13 },
+    {-13,  5,  3,-28,-14,  0,  6, 23,  5,  4, -1,-17,  1, -3,  0,  0,
+       5,  4,  0,-18, 14, 10,  4,  2,  5, -2,  4, -3,  2,  0,  2,  0 },
+    {-15,  4,-13,-16, -3,-12, -2,  2,  7, 10,  9,  3, 11,  4, 23, 14,
+       9, 16,  4,  1,-12, -3,  4, -7,-15, -7,-10,-14, -6, -8, -1, -6 },
+    { -7, 10, -5,-10, -3,-13, 16, -1,-12,  7, -3,-12,  2, 13, 13,  2,
+      17, 15,-13,  1, -5, -2,  3, -1,  1, -3,  6, -3,-12,-16,  7, -7 },
+    {-11, -5,-12,-30, -6,-22,  1,  4, -6, -3, 12,  6,  7,  0, 16,  6,
+      -2,  0,-22, -2, -9,  2,-13,  8,  6, -8,  4, -7, -1, -6,  4,  6 },
+    {-14,  5,  1,-27, -4,  2,  1, 14,-11, -7, -8, -4,  1,  8,  0, -6,
+     -13, 11,-12, -7, -5,  1, 10,  7,  3, -2,  0,  6, -8,  2, 10, -1 },
+    {-10, 10,-25,-13,-20, -4, 19,  3, 13,  5,  5,  7, -8,  2,  4,  2,
+       3, -1, -1, -9, 14, 10,  9, 14,  3,  3, -6,  0, -5,  4,  1, -1 },
+    { -9, 15,-18,-17,  4,-11,  6,  7,-12,  8, -1,-11,  2,  3,  7, 16,
+      -3, -9,  7,-12, 23,  0,  6,  7,-14, -9,  8,  1, -2,  6, -2, -1 },
+    { -6,  9,-16,-26,-14,-11,  9, -6,  5, -2, 13, 17, 21,  7, 18,-19,
+       6,-23, -2,-15, -2,  2,-10, -8,  2,  1, -2,  4, -3, -4, -5, -4 },
+    {  0,  6, -5,-28,-17,-32,  2,-10, 11,  3, -5,  9, 10,  3, 11, 11,
+      -3, 12, -2,  2,  4, -6,  9, -4, -4, -4, -4, -9,  2,  0,  2,  4 },
+    {  0, -8,-18,-34, -9, -7, -4,-11, 10, 15, 11, -1, -8, 15,  6,-13,
+       9,  2, -4,-12,  0, -1, 19, 12,  6,  5,  0, -3,-10,-12,  3, -5 },
+    {-10,  6, -9,-17,-12,-11,  9, -6, 11, 11, 18, -7,  0, 16,  4,  2,
+      -6,  3,-12, -1,  0,  1, -5,-22, -2,-12,  0,  6, 17,  5,  5,  6 },
+    { 12, -5,  7,  1, -5, -2, -1,  2,  2, -4, -3, -3, -3, -2,-29, 11,
+       5,-13,-73, 24, 12,  4,-14,-10,  5,  1,  0,-11, -7, -7,  7,  3 },
+    { 10, -3, -1, -3,  4,-11, -5, -2, -8,  7,  9,  2, -8, -6,  6,  7,
+      21, 17,-54, 47,-14,-10, 14, 19, 13, 21, -4,  3,  1,  2, -4,  2 },
+    {-12,  4,-16,-12,  5, -9, -4, 19, -7,-22,-22,-17,  3,  0, -6,  8,
+      23, -4,-55,-28,  2,-26,  2,  1,  4,  0,-13,  6,  0, 10, -7,-11 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3, -1,
+      35, -1,-67,-35,-24,-24, -6,  2,  2, -2,  1,  3,  2,  0, -1,  1 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  5,  0,
+      41, -4,-73,-15, 18,  4, 17,  8, -1,-16, -1, -2,  1,  0,  0,  0 },
+    { -4, -4,  4,  6, -1,  2,-16,-10,-15,-10, 21, -2, -6, -2, 14, -7,
+      10, -5,-55, 34,-12, 11,-13, -2,  2, 28,-26,  0,  7,  4, 21, -7 },
+    {  2,  1, 15,-22, 10, -3, 14, -6, -2, 15, -2, -7, 20,  6,-15, -7,
+      23, 10,-60,  8, -4, 29,-22,  2,-13,  9,-10, 12, -1, -3,  4,  7 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1,  0, -1, -2, 11, -5,
+     -21,-11,-60,-27,-17,-39,  6, 36,  0, -8,  2,  2,  0,  0, -2,  3 },
+    {  2, -5,  9,-17, -1,  2, -3, -6,  8, 12,  7, -6,-33,-11,-14,-40,
+      10, 36,-46,  0,-19,  5,  0,-10,  3, 12, -6, -8,  6,-12, -7,  1 },
+    {  1,  1,  0,  0,  0,  0,  1,  0,  0,  0, -1,  0,  1,  0, -2,  0,
+       4, -2,-87, -3, -2,  2, -2, 20,  2,  6, -1,  6,  0,  0,  2, -1 },
+    {  1,  0,  0,  0,  0, -1,  0,  0,  0,  0,  0,  0, -1,  0,  0,  1,
+       1,  7,-76, 41, -7,-24,  0, -6,  3,  6,  0, -2, -1,  1,  0,  0 },
+    {  0, -3,  4,  2,  3,  2,  2,  0,  3, -1,  4,  0, -1,  4, -2, -4,
+     -32,-11,-64,-29, -9,-43,  2,-11, -1, -7,  0, -4, -2, -2, -2,  2 },
+    { 10,-20,  3, -3, 13, 13,  0, -4,  2,  7, -8,  7, -2,  2,-20,-20,
+     -19,  3,-47,-18,-16, -6,-15,-42,-17, 14, -6,  8, 12,-10, 11,-12 },
+    { -3, -2, -2, -1, -1,  4, -3, -1, -6, -2,  3,  2, -3,  6, -1, -9,
+      10, 13,-68, -9, 26,  3,  5,  3,-21, 10,-15, 21,-22, 19, 11,-14 },
+    {  1,  5, 18,-19,-29,-13, -2, 18,-10, 20,  2, 10,-10, 11,  1,  8,
+     -16,-17,-41, 10,-14,-25,  0,-14,-19, 17,  7,-12, 14,-11, 14,  5 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3, -1,-43,  5,
+       6,-12,-48, 19,  8,-38, -8, -3, 22,-21,-10, 15, 20, -9, -5,  8 },
+    {  0,  0,  0,  0, -1,  1, -1,  0,  0,  0,  0,  0,  0,  0,  6, -3,
+      22,-14,-71,-24, -2,-33, 23,  7, -8,  7, -3,  2, -4,  1, -8, -2 },
+    {  1,  0, -1,  2,  0, -2,  0,  0, -1,  0,  4,  0, 26, -1, 10,-11,
+     -17,-32,-58, 14,-14,-11, -2, 15,  2, -8, 12, 10, -9, 13,-33,-14 },
+    { 15,-17,-19,  7, -8,-15,-32,-22,  7, 12, 18,  0,  0,-15, -4, 16,
+      37, -2,-46, 11,  2, -8,-10, -8, 14,  9, -4,  5,  7,-17,  4,  3 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -2,  0,
+      -5,  3,-85, 23, -9,-17, -2, -2,  0,  0,  0,  0,  0,  0,  0,  0 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -2,  0,
+      -5,  3,-85, 23, -9,-17, -2, -2,  0,  0,  0,  0,  0,  0,  0,  0 },
+    {  1,  0,  0,  0,  0, -1,  0,  0,  0,  0,  0,  0, -1,  0,  0,  1,
+       1,  7,-76, 41, -7,-24,  0, -6,  3,  6,  0, -2, -1,  1,  0,  0 },
+    {  0, -3,  4,  2,  3,  2,  2,  0,  3, -1,  4,  0, -1,  4, -2, -4,
+     -32,-11,-64,-29, -9,-43,  2,-11, -1, -7,  0, -4, -2, -2, -2,  2 },
+    { 10,-20,  3, -3, 13, 13,  0, -4,  2,  7, -8,  7, -2,  2,-20,-20,
+     -19,  3,-47,-18,-16, -6,-15,-42,-17, 14, -6,  8, 12,-10, 11,-12 },
+    { -3, -2, -2, -1, -1,  4, -3, -1, -6, -2,  3,  2, -3,  6, -1, -9,
+      10, 13,-68, -9, 26,  3,  5,  3,-21, 10,-15, 21,-22, 19, 11,-14 },
+    {  1,  5, 18,-19,-29,-13, -2, 18,-10, 20,  2, 10,-10, 11,  1,  8,
+     -16,-17,-41, 10,-14,-25,  0,-14,-19, 17,  7,-12, 14,-11, 14,  5 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3, -1,-43,  5,
+       6,-12,-48, 19,  8,-38, -8, -3, 22,-21,-10, 15, 20, -9, -5,  8 },
+    {  0,  0,  0,  0, -1,  1, -1,  0,  0,  0,  0,  0,  0,  0,  6, -3,
+      22,-14,-71,-24, -2,-33, 23,  7, -8,  7, -3,  2, -4,  1, -8, -2 },
+    {  1,  0, -1,  2,  0, -2,  0,  0, -1,  0,  4,  0, 26, -1, 10,-11,
+     -17,-32,-58, 14,-14,-11, -2, 15,  2, -8, 12, 10, -9, 13,-33,-14 },
+    { 15,-17,-19,  7, -8,-15,-32,-22,  7, 12, 18,  0,  0,-15, -4, 16,
+      37, -2,-46, 11,  2, -8,-10, -8, 14,  9, -4,  5,  7,-17,  4,  3 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -2,  0,
+      -5,  3,-85, 23, -9,-17, -2, -2,  0,  0,  0,  0,  0,  0,  0,  0 },
+    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -2,  0,
+      -5,  3,-85, 23, -9,-17, -2, -2,  0,  0,  0,  0,  0,  0,  0,  0 },
+    { 16, 65, -2, -2,  4,  3,  0, -7,  3,  1,  3,  1,  0,  5,  1, -5,
+       0,  2, -1,  3,  0,  0, -1, -2,  6,  0, -2,  0,  0, -1,  1,  1 },
+    {  5, 37, -4,  8, -4, -1,  9, 17,  6, -7,  5, -1, 11,  6, -4,  7,
+      -2,  4,  1, -3, 11,  3,  3, -9,  6,  0, -2, -4, -5,  4,-12,-11 },
+    { 15, 24,-14,  2,  6, 17, 26,  5,  8, 11, -9, -7, -6, -8,  3, -5,
+       9, 10, -3, 10,  0,  1,  4, -9,  4,  9,  3,  0,  4,  0, -5,  3 },
+    {  9, 36, -9, -8,  7,  7,  4,  3, -1,-16, -2,  7, -5, -6,  6, 12,
+     -11,-12,  9, -1, -3, -9, 12,  6, -6,  2,  2,  5,  0,  5,  6, -6 },
+    { 25, 39, -5, 24,  3, 10,  3, -6, 13, -8,  3, -7,  2,-10, -5,  2,
+      -2,  3,  5, -2,  1,  5, -2,  3, -4,  1, -5, -4,  0,  1, -2,  0 },
+    { 16, 27, -1,  0,-14,  6,  4, -5,  7, -2, -6,  0, -3, -5,  2, -1,
+      -1,-19,  5, -8,  0, 11, 12,  5,  0,  3, 10,  6,-14, 14,-13,-15 },
+    { 12, 23,-14,  2,  1,  4, -3, 16,  7, -8,  2, -8,  8,  6, -8, -7,
+      -3,  0,  2,  8,-13,  7, 13, -6, -4,  6,-13,-16, 14, 11, -7,  5 },
+    { 16, 28, -7, -1,  6, -3,  9,  0, -7,  3,  0,  3,-12, 20,  8,  9,
+       8, 23,  8,-13, -2,  4,  9,  3, -5, 13,  5, -2, 12, 14,  5, -1 },
+    { 19, 37, 19,  5,  7,  5, 10,  5, 19, 10, 14,  0,  2,  5,  1, -4,
+      -4,  2,  2, -5, -2, -1,  2, -6, -4, -4, -5, -3,  2, -2, -2, -2 },
+    { 24, 21,  1,-11,-10, 17,-14, 14,  6, -1, -6, -1,  0,-13, -1,-12,
+      -2, -5,  6, -4,-12, 14,  5, -2, -8, -8, 15, -7,-30,-12,  4,  0 },
+    { 11, 26, -3,  3,  5, -1, -2,  3, -2, 10, 15, -4, 10,-28, 10,-17,
+      -8,  1,  2, -7, -1, -6,-15, -1,  4,  5, -7,  9,  0, -5, -4,  4 },
+    { 18, 32,  1,  2, -7,  4, 15,  2, -9, -2, 12,-11,  7, 11, 13,  2,
+       0,  5,  9,-10, 16,  3, -3,  5, -9,-23,  2, -2, -1,  5,  2, 11 },
+    { 35, 24,-20,  2,  4, -1,  5, 14,-10, -9,  8, -7,  0,  5, -7, -7,
+      11,  1,  5,  3,  2,  0, -2,  3,  0,  1,  4,  0, -2, -8,  0, -4 },
+    {  9, 35, -1,  2, -1,-19, -3, 12, -1,  8,  8,-13, -1, -2,  2,  5,
+      -8, -1, 13, -2, 11,  1,  0,-10,  0, -3, -7,  2,  1,-12,  3, 12 },
+    { 20, 27,-12,-12,  7,  4, -1,-13, -1, -9,  2, 13,-11,  5,  7, -9,
+       9,  1,  1,  8, -9,  0, -6,  7,  4,  2, -2,  7,  3, -2,  1, -9 },
+    {  8, 37,-20, -5,  0,-21, 10, -8,  3, 19, -9,  7, -3, -8, 10, -2,
+       0,  5,  6, -4, -2, -1,  0, -7,  6,  1,  0,  4, -5,  6, -8,  2 },
+    {  8, 27,  1, -3, -5,  1,  6,  0, 15,  2, 17, -1,  3,-17, 10,  5,
+       5, -6, -6,  6,-10, 18, -5,  0,  0, 13,  7, 10, -5, -6, -2, -4 },
+    { 14, 29,-20, -4, -3,  1, -5, -1,  2, 12,-10, -3,  4,-18,  4, 14,
+      -4, -1, -9, 15, -2,  2, -5, -3,  2,  9, -2,-14, -3,  4, -4, -7 },
+    { 23, 23,-23,-11, 27,  4,  4, -1,  7,  0, -5,  9,  2,-11,  3,  7,
+      -2, -5,  2, -7, -7, 13, -3, -6,  2,  3,  3, -4, -1, -8,  5, -2 },
+    { 16, 26, -6,  8, -9, -1, -2, -1, -8,  4, -2,  0,-12,  9, -1,  0,
+     -17, -9, 30, -5,-15,-16,-13,  0, 10,-11, -7, -3, -1,  0,-11, -2 },
+    { 12, 32, -4, -5, 10, 19,-10,  4,-12,  5, -6,  9,-12, -6, -6, -8,
+       4,  1,  3,  0,  8,  0, -3, -4, -7, -4, 10,  8,  6,  5, -1,  4 },
+    { 46, 42, -3,-14, -2, -6,  6, -2, -5, -1, -3, -3,  1, -1,  3,  1,
+       1,  4, -1,  2,  3,  1, -2,  6,  0, -1, -2,  4, -2, -1,  2,  2 },
+    {  9, 33,-13,  4,-11,  3, -8, 22, 12, -2,  4,  0,-16,  5,  4, -1,
+       7, -6, -9,  1,  7,  5,  0, -5,  5, -1, 10,  3, -2, -1,  3, -2 },
+    {  9, 30,  6, -3,  6,  1, -7,  5, 11, 14,  7,  1,  0,  2,  2, -1,
+       8,  7, -6,-13,-10, -2,  1, -6, 10,  7,  6,  5, -2, -5, -1,-16 },
+    {  9, 28,-11,-10,  9,-10, 15,  8,  4,  9, -4, -7,  0, -5,  9,  8,
+      -7,  2,-15,-23,  4, -4,  4, 16, -8, -3,  0, -8, 14,  5, -3, 15 },
+    { 17, 26, -5, -5, -1, -8, 20, 18, -7, -2,  4, -7, -8, -5, -4, 16,
+       0,  0, -7, -2,-13, -5, -2,  3, 12,  1,  3, -5,  2,  2,  0, -1 },
+    { 11, 37,  7,-23,  6, -1, 15, 13,  4, -9,  7,  5,  3, -3, -5, -8,
+      -2,  3, -5, -1, -8,  7,  2, 13,  1,  3,  0, -3, -1,  2,  0, -2 },
+    { 21, 33,  7, 20, 21,-10,  6, -5, -5, -6, -9,  2, 10,  0,  8, -4,
+      10,  2, -2, -2,  0,-10, -6, -2,  0, -5,  3,-11,  3, -9, -3,  1 },
+    {  6, 30,-15, -8, 16,  1,  4,  6,  4,  5,  8, -3,  8, -9, -1, -6,
+       8,  2, -2,  4, -2,  5, 11,-21,  3,-10, 16,-11, 24, 10, 14, -6 },
+    { 15, 36, -3, -9,-20, 12,  0, -7,-18, -4, -8, -9,  9, -7, -3, -1,
+       2,  7, -5, -8,  6,  2,  2, -1,  7,  1,  1, -3,  3, -4, -8,  1 },
+    { 16, 34, 21,  3, -9, 10,  7,  9, -7,  1, -4, -9, -4, -5, -5,  3,
+       3,-19,  1,  5,  4, -2, -6, -5,-10,-11, -8, -2,  2, -5, -8, -7 },
+    { 28, 29, -3, 18, -2,  0, -6, 12, -2, 10,-11, -4,-13,-12, -6, -4,
+       0,  4, -1, -8,  6,  4, 12, 11, 10, 10, -3, -6,  1,  2,  1,  7 },
+    {  3,  8, 22, -8,  3, 36, -8, -1,  9,  6,-13,-14,  8, -1,  1,  2,
+      -2, -8,  0,  3,  1,  2, -1,  5, -1, -8,  0, -2,  2,  2, -1,  1 },
+    {  0,  6,  0,  0,  4, 13, -7,-16, -6, 15,-14,-21, -9,-10,-10, -6,
+     -21,  5,  4,  2, 12,  4, 12, 11, -4, -6, -6,-10, -7,-18,  1,  4 },
+    { -1,  3, 10,  1, -1, 15,  4, -7,-16,  3,  0,-22, 10,  2, -3, -2,
+      13,  5, -8, 16, -5,  4,  0,-11,-10,-22,  0, -4,-17,  5,  2,  1 },
+    { 12,  8, -4, -9, 14, 40,-21,  0,  1,-15,-10,-12, 12,  6,-10,  2,
+       8,  6,-12,-10,-11,  1,  0,-11,  2,  1, 13,  0,  6,  3,  8,  4 },
+    {-10,  3,  5, -4, -3,  3,  0, -9,  2,  8,-22,-23, 17,  8,-17, -3,
+      14, -8, -4,  1, -8,  3,  0,  5, -1, -3, -2, -4,  1,-10,  0, -2 },
+    {  0, -1,  5, -7,  4, 12, -2,  0, -7,  2,-16,-15, 12, 21, -7, -4,
+       7, -7,-11,-15, -7, -9, -5, -8,  0, -6,  8, -3, -8, 22, -7, -9 },
+    {  7, 19,  4, -9, 24, 22,  2, -6,  8, 13,-14,-20, -4, 11,  8, -4,
+      -1,  2,  0, -7,  5,-17, -3,  3, -6,  5,  3,  4, -5, -7, -3, 14 },
+    { -2,  6,  2,  8, -2,  5, -4, -2,-10,  3,-45,-30, -3, -3,-12, -4,
+      -3, -3, -1,  9, -6, -6,  5, -4,  0,  5, -1, -2, -1,  0, -6, -1 },
+    { -3, 14,-16,-10, 10,  0, -2,-40, -9, 12,  2,-19, 15, -4,  4,  3,
+       3, -4,  7,  1, -4, -5,  0,  4, -1,  0, -9, -2, -4, -1, -2,  0 },
+    {  7, 16,  2, -7,  8,  2,  0,  1,  5, 21,-10,-26,  7,  2, -9, -7,
+      -3,-16,  8,  5,  5, -6, 10,  4,-14, -6,  5,  3, -2, -2, -4,  1 },
+    { -9, 14, -1,  3,  3, 11,  1, -5, -3, 13,-16,-18, 20,  6, -5,  0,
+      -3,  2,  8,  4,-19, -9, 12,  0, -8,  2,  2,  1,  6, 13, -7,-11 },
+    {  2,  5, 16, -4, 19, 15,  4,  0,-11,  7,-10,-10,-16, 18,-11,-12,
+      -9, -4,  7, -4, -4,-17,  1,  1, -8, -3, -3,  5, -2, -6,-11, -5 },
+    {  2, 12,  0, -9,-10, 14,  6,  2, -3,  2,-12,-28, 12,  1, -1,  2,
+       0, -3, -4,  7, 16,  5, -7,  8, -4, -3, -1,  3,-12,  4,-17, -5 },
+    { -4,  7, 11,  6,  1, 14, -4, -6,  5,  5, -6,-24, 23, -9,-15, 13,
+      -7, -9,-15, 10, -1,  8, -5,  1, 12,  6,  2,  0,  4, -2,  9,-10 },
+    {  1,  5, 11,  3,  6, 12, -3,  8,-21,  5, -7,-20, 12, -2, -9, -3,
+      17, -7, -8, -9,-14,  3,-13, 18, -8,  9,  2, -8,  4, -8, -5, -2 },
+    { -3, -3, -1,  5, -2, 15,  3,  2,  1, -8,  1,-39, -6, 13,-13,  0,
+      -2, -5, -6, -3,  0, -5, -2, 15, -9,  5, -3, -6, -2,  7,  0,-13 },
+    {  2,  8,  5,-12,-13, 22,  8,-16, 11,  5, -2,-32, -2, -4, 11,  5,
+       5, -6,  1,  3,  1,  5,  3,  6, -5,  4,  4, -8,  8,  4,  1,  3 },
+    { 13,  9,  5, -4,  9, 18,-11,  2, -1, 15,-10,-19, -2, 14,  0,-10,
+       1,  1,-18,  3,  2, -6, -8, 20,  7, -8, 16,  9,  9,-13, -3, -2 },
+    {-13, 11, 11, -9,-10, 13, -3,-18,  2, 10,  5,-21,  6, 15,-11,-21,
+       3, 14,  0,-12,  9, -1, -2, -4,  3, -3, -9, -8, -5, -2, -8,  2 },
+    {  3,  3, 11,  4,  0, 13,  1, -8, 10, 13, -6,-26,  2, 12, -3, -5,
+      12, -2,  1,  8, -7,-17,-19,  5, 10,  7, -3,  2, -3,  0,  5,  0 },
+    {  5,  0,  3, -3, -9,  5,-15, -5, -5, 17, -5,-31,  0, 13, 13,  5,
+      -1, -6,-14,  7, -8,  9,-14, -2,-16, -4, -4, -6,  6, -6,-10,  6 },
+    { 13,  3,  1,  7, -3,  4, -1, -2, -1,  4, -8,-32, -1, -4,  0,  3,
+     -10,  7, 10,-10,  4, -1,  6,  2,-16, -9,  4,  3, 13,-23, -3, -4 },
+    {  4, 11, -4, -9,  4, 11,-12,-12,-12,  6,  1,-28, -3, 14, 18, -2,
+     -12,  7, 15, -3, -5, -7, -3,  2, -6,  4,  4, -2, -5, -3,  2,-13 },
+    {  8,  7, -7,  0, 13,  7, -8, -7,  8, 36,-10,-22,  3, 23, -3,-10,
+      -3, 11,  1, -7,  3,  3, -1, -7, -4,  2,  3,  2,  5,  3, -4, -1 },
+    { -1,  1, 13,  1, -6, -1, -6, -9,-18, 17, -5,-37, -1, -1, -6, -4,
+       1, -6,-15,  2, 17, -9,  0, -3,  0,  4,  0, -5,  0,  4,  1, -5 },
+    {  0, 14,  5,  0, -7,  2, -6, 17, -6, -9,  7,-16, -5, 23,-14,-13,
+       8,-15, 11, 10,-11,-13,-33, -5, -2,  1,  6,  8,  0,-13, -9,  5 },
+    { 11,  7, -2, -8,  9, 11, 25,-14,  7,  3, -1,-33, 14,  8, -6,-19,
+       3,  3,  2, -1, -3, -1, -2,-10, -3,  1,  2,  1,  4,  2, -3,  4 },
+    { -2,  8,  4, -2,  9, 13, -4, -2,-15, -3, 19,-37,  9, 25, -9,  2,
+      -5, -2, -2, -4,  4,  2,  2,  0,  3,  3,  3,  5, -2, -3, -4, -3 },
+    { 10, 13, -1,-15,  4,  6,-18, -4, 25,  1,-23,-17, 15, 13, -8, -8,
+       7,  4, -5,  3,  6,  9, -7,  6,  0, -5,  8,  0, -6, -1, -2, -2 },
+    {  1,  3,  9, -5, 27, 15, -9,-31, -1, 23, -2, -9,  1,  8, -1, -7,
+      -2, -8, -4, -4, -2, -1,  3,  5,  0,  0, -1,  1, -7,  7, -3, -3 },
+    { -8,  7,  3, -6,  8,  3,-11, -2, 36, 14,  1,-30,  6, 10,-12, -6,
+      -6, -2, -4, -3, -5,  0,  9,  4, -5, -5, -8, 12,  4, -3,  1, -8 },
+    { -2,  9, 33,  0, 12, -3, -7, -4, -4, -1,  6,-25, 11, -6, -9,-11,
+      -2, -4, -2,  6, -1, -3, -6, 15, -6,  3, 10, -4,  1,  0,  5,  8 },
+    {-22,-21, -9,-19, -5, -7,-12,-15, -8,  9,-19, 14, -7, -4,  5, -8,
+      -2,  7,  1, -3,  4, -4,  6, 11,  2,  6, -3, -5,  2, -2,  0, -3 },
+    {-32,-13,  3,-24,  3, -8,  4,  1,-10, 14,-15,  0,  4,  6, -1,  6,
+       7, -1,  6,  4, -3,-17,  1,  4, -6, -1,  1,  0,  3,  3, -7, -4 },
+    {-32,-11,  7, -8,-12, 13, -5,-22, -4, 12,-16,  2,  0,  4,  0,  1,
+       0,  6, -5, -8,  2,  6,  5,  0, -3, -6,  5,  6,  5,  5, 13, -4 },
+    {-44,-33,  6, -4,  2,  0, -9, 10,  3,  4,  7,  0, -1,  7,  5,  1,
+       1, -3,  1,  6, -1,  0,  2,  3, -4,  0,  0,  1,  0, -1, -2, -1 },
+    {-30,-18,-24, -8,  5,  0, -2, 14,  7,  0,  1, 12,  6,  4, -9,  7,
+       5,  7,-11, -5,  1, -8, -1,  2,  2, -9,  7, -1,  7,  5,  6,  6 },
+    {-22,-20,-13, -9, 20, -3, 10, -8,  6, -4,  2, -7, 10,  8,  0, -1,
+       2, -3,  6,-19,  2,  4,  3,  3, -7,  2, -1, -6,  1,  1,  6, -2 },
+    {-27, -8, -1,  3, -1,-11, 24,  4, -1,  1, -8,  8,  5,-11, 15, -3,
+     -15, -1, -1,-13, -1,  1, -5,  5,  2,  3, -9,  0,  4,  3, -7,  6 },
+    {-33,-16, -1, -8, 10,-23,  6, 13, -1, -3, -9,  0,  5, -7, -5,-12,
+      -2,  3,  3,  6, -2, -3,  2, -3,  9, -6, -3, -2,  0,  5, -3, -4 },
+    {-22,-17, 11, -3,  3,  1, -1, -5, 17,  2,-15, -2, 10, -9,  6, 14,
+     -16,-12, 20, -1, -7,  6, -3,-12,  1, 10,-10, -1,  7, -3, -1, 10 },
+    {-28,-13,  1, -3, -1, -1,  0,  3,  3,  5,  1, 10,-10, -3,  7,  2,
+       4, 19, -1, -1, 10,  5, -8,  1, 11,-15, -4, -3, -5,  4,-13,  3 },
+    {-22,-13, 42,-20,  5,-13,  7,-11,  1,  1, -1,  1,  6,  3,  6,-11,
+       3,  3, -2,  0, -4,  4, -3, -1, -5,  2,  0,  0, -9, -1,  4,  4 },
+    {-26,-15, -2, -6, -4, -2, 16,  8, 21,  8,  1, -3,-10,  7, -8,-12,
+      -5, 12, -9,  3, -2, -3, 18,  1,-12,-15, -4,  5, -3,  0, 12,  7 },
+    {-26,-16,  5,  6, 14, -3, 15,  6,  1, -7,-13, 16,-15,  5, 11, -2,
+       9, -7, -4, -2,  0,  0, -2,  7, -8, -6, -5,  2,  7, -3,  2, 12 },
+    {-31,-17, -8,-30,  4, 14,  6, -6,  6,-11,  0,  3, -4,  0,  0, -4,
+       0, -4,  1,  4,  3,  4,  0, -5,  3,  2,  2,  0,  2,  1,  3,  5 },
+    {-61,-10,  4, 10,  4,  7,  0, -3,  0,  1,  0, -3,  0,  1,  0, -2,
+      -1,  1,  2, -2,  4, -3,  1,  1, -1,  1, -2, -4, -4,  4,  0,  0 },
+    {-28,-13, -8, -4,  3, -3,  2,  1, 11, 14,  3,  9,  1, 13,  3,  5,
+      -3, -2, -2,-12,-14, -9,-11,-15,-12, -5, -4,-12,  3, -3,  0, -5 },
+    {-41,  0, 12,-24, 13,  4,  5, 16, -5, -4,  0,  0, 13, -4,  1, -9,
+       9, -6, -1,  6, -2,  5,  2,  9,  6, -9, -8,  8, -2, -3, -6, -4 },
+    {-26,-19, -2,-15,  4,-14,  6,  0, 26, 20,  8,  9,  9,  3, -4, -5,
+      -8,  1,  0, -1,  5,  9,  3,  4,  4,  7,  1,  3, -2, -2,-10,  0 },
+    {-29,-18,  9, -4,  1, -5,-14,-12,  5,-10, -5,  4, -5,  0, -1, -1,
+       4, -5,  7,-16,-11,  2,  7,-15,  2, -4,  6, -4, -6,  7, -3,  7 },
+    {-27,-16,  9,-14,  3, -8,  9,  0,  7, -4, -3, -7,  0,-10, -1,  2,
+       1, -2, 15,-10, 14,  7,  6, 17,  3, -4,  3,-10,  8, -8,  3, 11 },
+    {-21,-20, -8, -8,  4,  5, -3, -2,  0, -5, 14,-10, 11, -4, 13,  0,
+       5,-11, 19,-18, 18,  3, -5, -3, -4, -8, 11,-10, 10,  3,  4, -9 },
+    {-35,-15, 13,-12,  4,  0, -2, -4,-12, -3, -8,-24, -7,  1,  7,  8,
+      -3,  0, -2, -1,  3, -2, -2, -6,  8,  1,  0,  1, -6, -1,  2, -6 },
+    {-19,-14, 13,-10,  9, -1,  1,  3,-12,  5,-16,  7, 13,  9,  4, -4,
+       6, -5,  4,  9, -3, 17, -4, 12,-11, -6, -5, -6, 13,  2,  7, -9 },
+    {-34, -8, -4,  1,  2, -1,  3,  6,-20,-11,  8, -1,  4,  2, -9,  4,
+      -4, -5, 16, 10, -4, 14,-13,  1, -6,  0,  2,-10,  0, -3, -3,  7 },
+    {-36,-10, -8, -3,  2, -2, 14, -4, -1, -7, -4, 10, -1, -3, 15,-11,
+       0,  2,  3, -1,  4,  0,  8, -1,  0, 18,-11, -5, 15, -5, 13,-12 },
+    {-22,-13, 14,-20, 15, 25, 16, 10,  8, -2,-10, -5, -1, -8, 11,  8,
+      -1, -2, -4,  1,  2, -1, -7,  0,  0,  0, -3,  0,  2, -1,  0,  2 },
+    {-31,-22,  7,  6, -2,  5,-20, 14, -6,  7,  0, 14,  3, -7,  3, -6,
+      -2,  1, -3, -5,  1,-10,  1,-24,  6, -2,  3, -7,  1, -7,  8,  7 },
+    {-25,-20, -3, -9, 10,  6, 12,  7,  5,  4, -3,  6, -1, -5, -6, -8,
+       3,  5,  6,  5,-10, 10, -4,-15,-15, -2, -9,  2, 18,  1,  8, 12 },
+    {-24,-19, -2, -4, -7, 11,  6,  9, 16,  2, -7, 18,  6, -7,  6,  6,
+      -2, -9,  3, 12, -2,  3, -1,  6,  7,  8,  0,  8,-11,  8,  4,  2 },
+    {-26,-20,-12,-12, -2, -3,  1, -5, -1, -2,  0,  3,  7,  9, -2,  2,
+       9, 22, 13,  4, -4, -1, -2,-14,  5, 15, -8, -5, -7,-11,-14, -6 },
+    {-21,-18, -1, -4,  0,  3,  7, -2, 10,  8, -8, -1, 15,  1, -9,  3,
+       1,  3, -5, -2,  2,  4,  0, -1, 10,  2,-19, -8,  8, 30, -7,  8 },
+    {-25, -6, 26,  4, -8,  4, -2, 21,  5, -4,-16,  5, 13,  4,-10, -1,
+      -6, -2,  2,-10,-13,  1,  3, -3, -6, -8,  2, 11,  1, -7,  0,  5 },
+    {  0, -1, -2, 19,-12,-48, -6, 11,  8, -2, -4, -2, -7,  5, -3,  2,
+      -2, -1, -1, -7,  0, -3, -3, -4, -4,  4,  1,  3, -3, -1, -2, -5 },
+    {-11, -8,-28, 18, 16,-24, -8, 19,  4,  8,-12,  9, -4, -2,  4, -7,
+       6,  2,  3,  3, -4,  0,  1, -6, -4, -2,  2,  6,  0, -3,  1,-16 },
+    { -9, -5,-26,  7, -3,-37,-16, -2,  2, -7,  4,-13,  0, -4, -6, -5,
+      -6, -4,  0,  3,  4, -3, -4, -4,  4, -3,  9, -4, -2,  2,  7, -4 },
+    {  2,  9,-18,  7, 29,-24, -1,  7, 14, 10,  3, -3, -2, -5,  6,-10,
+      -6, -3, -8,  0,  5,  1,  4,  3,-12,  2,  6,  1,  3,  4,  1, -3 },
+    {-20,  2,  8, 20, -9,-24, -4, 18,  3, 11, -1,-11,  6,  9, -1, -3,
+       1, -1,-15,  3, 15,  9,  3,  2,-13,  2, -8,  8,  1, -1,  1, -8 },
+    {-12,  5,-11,  6, 19,-26,-17, -6,  4, 14,  6, -8,  9,  5, -6, -5,
+       2, -1, 20,  1,-11,-10,-18, 20, -7,  0, -3,  4,  2,  0, 10,  4 },
+    {-15,  1, -2, 13, -8,-21,-22,  4,  4,  3,  3, -7,-31,  4,-10,-14,
+       0,  8,  4,  5,  8, 11,  2, -8,  6,  7,  0, -2,  6,  8,  8,  7 },
+    {-13,-10, -9, 12, 19,-16, -3, -2,  9,  2, 11,-29, -1,  9,  4, -3,
+       1,-10,-10, 16,  1,  7, -7, -6, -4, -1, -5,  3,  6,  0,  3,  1 },
+    {-17, -1, -5, 19, 12, -9,-21, -5,  2, 12, -7, -7, -3,  8,  7, -2,
+       6, -9, -9,  1, -4,  1,  1,  3,-14,  2, -8,  0, 10,  1,-12, -6 },
+    {-13, -5,  8, 15,  0,-20, -2, 20,  8, -8,  8,-19, 12, 10,  2,-11,
+       0, 12,  1,-11,  0,-11,-15,  5,-11,  2,  4, -4,-11,  5, -4, -5 },
+    {  3,-11, -7,  8,  0,-17,-26, 15, 19, -7, 10, -9, -5, -5, 14,-25,
+       0, -8,  2, -9, -3,  9,  1, -6,  4, -4,  3, -9, -1,  6,  2,  2 },
+    {-12,  5,  5,  9, 14,-18,-19,  4,  2, 16, 14,-21,-15, -9, -1, 16,
+      12,-11,-10, -5, -7,  4, 15, -8, -5, -1,  1, 14, 13, -7, -1, -4 },
+    {-10, -5, -1,  8,  7,-23,-10, 14,  6, 11, 10,-16, -3, 16,  6,  0,
+       0,  9,  6, -2, -7,  1, 22,  5,  3, -8,  0,  3, -2,-10,  3,  0 },
+    { -2,-14,  2, 16, 15,-17,-17,  6, 19,  4,-10,-15, -1, 15, 11,-14,
+      -8,  5,  8,  8, -2, -8,-11, 10, 10, -8,-14,  2, 13,  4, -2,-12 },
+    {-10,  3,  6,  4, 19,-23,-19,  1,  4, -9,-30,  3, -6, 18,  0,  2,
+       0,-11,  0,  3,  7, -2,  8,  5,  2, -3,  6, -9,  1, -4,  7, -6 },
+    {  9,  5, -2, 21, 20,-33,-13,  7,-10,  8,  8,-15, -6, -4,  1,  5,
+       3,  7, -2, -9, -1,  4, -6,  1,  0,  9, -1, -5,  2,  1, -3,  3 },
+    { -9, -3,  3, 15, -3,-30, -7, -7,-25,  6,  2, -6,  1, 19,  1,-12,
+       1, -8,-13,  9, 13,  1,  8,  2,  5, 15, -2,  3, -9,  0, -4,  4 },
+    { -6,-12,-17, 25, 22,-13,-10,  9,  2, 11, -7,-16,  4,  6,  1,  0,
+       0, 18, -4, -5,  4, -2, -1, -5,  0, -4,  6,  1,  6, -1,  7,  0 },
+    { -1,  0,-10,  8,  8,-27,  0, -2, 29, 16, -2, -4,  9, -1,  2,  0,
+       6, 10,  6,  4,  2, -7,  9,-18,  3,  3,  3,-10, 17, 10,  9, -6 },
+    { -3,-12, -6, 11, 20,-32,  5, 21,  3, -4, -9,  2,-10,  1,  7, -4,
+       5,  0,  0, -1, -8, -9, -7,  4,-10,  5,  0,  2, -5,  4,  9,  1 },
+    { -5, -1, -5,  1,  2,-19,-13,  1,  6, 12,  2,-16,-17, 11, 10, 13,
+      16,-12,-11,  3, -6,  0,  6,  4, -3,  1,  8,  2,  5,-11,  3,-14 },
+    {-19,  5, 10, 11,  2,-23, -9, 16, -2,  7,  0,-11, -7, 10,  6, -7,
+      26,-15, -4,  8,  6, -4,  7, -9,-15,  1,  8, -4,  4,  2,-12, 16 },
+    {-11,  1, 11, -4,  1,-31,-13, -1,  8,  5,  4, -2,  0, 13,  7,-17,
+       7,-10, -6,  1,  4, -1,  2, -9, -4,  9,  3,  3, -4, -5,  3,  4 },
+    { -3,  1, 10, -1,  0,-15,-22,  4, 40,-11, -4, -3,-14,  9, 11, -1,
+       9, -1, -6,  6,  3, -6,  0,  0,-12,  7, -2,  0,  9,  3,  1,  3 },
+    { -1, -1, -1, 14,  8,-24,-14, -8,  5,  8,  5,-12,-17,  8,  2,  7,
+      10, -8,  0,  4, -6, -6,-10,  8,  4,-12,  3, -9,-12,  5,  4, -3 },
+    { -5,  1,-11,  8,  9,-24,  0,  2,  2, 14,-12,-13,  1,  6,  7,  0,
+       7, -6,  9, 26, 11,-14,  8, 10,  1,  9,  0, 11, -2,  6,  2,-10 },
+    {-13,  1,  4, 34, 19,-17,-15,  0,  3, -2, -7, -1,  0, -3, -3, -1,
+       1, -1,-10,  8,  5,  0, -8,  4,-17,  9, -2,  0,  0,  6,  2, -3 },
+    { -6, -4,  1,  2,  2,-14,-29,  0,  9, 34, -3, -5,-14,  6,-10, -9,
+      -5, -1,  0,  3,  3,  0,  1, -1, -2, -1, -1, -3, -3, -4,  3, -3 },
+    { -4,  6,  3, 14, 14, -8,-29, 31, 11, 14, -4, -5, -6, 10,  6, -9,
+      -1,-11, -7,  1,  7,  4,  1, -6,  4,  0, 10, -7, -5, -1,  2,  4 },
+    { -4, -4, -2, 14,  6,-32, -6,-14, 14, -5,-11, 10,-18, -4,  6, -8,
+       9,  5, -4,  1, -4,  5, -2, -9,  3,  5,  2,-10, -6,-17,  3, 17 },
+    {-16,  9, 21, 19,  4,-20,-17, 14,  9, 15, -6,-17, -1,  1,  6, -3,
+       1,  1,  8, -3, -6,  6,  9,  4,  9, -9, -5,  1, -1,  0, -1,  2 },
+    { -7, -5,  3, 19,  1,-20, -9, 14, 21, -7,-18, -9, 26, -7,-17, -7,
+      12,  6,  0, -9, -6, 14,  9, -9, -8,  4, 15, -7, -9, -1,  9,  1 },
+    {-20, 30, -6, 11, 24, -4,  0, -6, -2,  8, -4, 12, -8,-17,  0,  5,
+      -4,  1, -1,  3, -3,  5,  3,  3,  7, -2, -3, -2,  4,  0,  0, -1 },
+    {-35, 17,  6,  1, -9, -1,-16,  3,-20,-13,  8,  7, -4, -7, -4,-20,
+       7, 12, -5,  5, -5,-11, 12, -1, 15, -9, -6, 16, -4, -9,-13,  4 },
+    {-21, 36,-19,  9,  0, -7, -8,  9, -4, -3,  3,  0,  7, -8, -2, -2,
+     -11, 13, -1,  5, -3,  7,  2,  3, -1, -2, -5,  1, -1, -2, -5, -3 },
+    {-12, 33, -4,  1,-12, -9,  0,-13, -1,  2, -8,  4,-10,  6,-16, -7,
+      -1, -4,-10, 15, -1,  0, -5, -8,  5,  5, -3,  0,  2, -7,  1, -7 },
+    {-14, 32,  5, -7,-15,  3, -5,  8, 14,  5,  9, 13,  3, 18, -3,  7,
+       4,-10,-10, 10, -1,  2,  0, -2,-11,  5, -3, -4,  2,  2,  7,  4 },
+    {-14, 34,  1, 20, -1,-12,  0, -3, -7, -4,  7, 18,  9, -3, 14, -7,
+      -9,-20, -7, -4,-13, 12,  1, 12,  5, -6,  2, -4,  0,-15,  1,  3 },
+    {-21, 23,  7, -8,  3,-13, -3,  0, -6, -2, -7,  6,-12,  9, -6, -2,
+      -2, -4, -1,  6,  9,  5, -9, 15,  0,  8, -8,  7,  6,-15,  3, -5 },
+    {-27, 32, -1, -4, -2,  4,-10, 12, -3,  8, 13,  7,  0,-15,  4, -2,
+       3,  5,  7, -4,  9,-12, -1, -2, -1, -4,  0, -4,  2, -5,  6, -6 },
+    {-17, 29, 15,  0, -1, -4,-10, 13, 12, -1, -8,-10,-10,  4,  7, -2,
+       6, -5,-13, 19,  6,  1, -7,  2, -9, -2, 12, -4, -8, -3,  2,  4 },
+    {-38, 27, 16,-15, -6,  3, -7, -4,  0, -1,  6, -2, -3, -6,  6, -6,
+      -3,  0,  2,  0, -4,  6,  1, -1,  0,  4, -1,  3,  4,  1, -2,  5 },
+    {-33, 40, -4,  2,  1,  0,  0,-10,-14,  0, -7,  4, -1,  3, -2,  5,
+       7,  6, -1,  4,  1,  3,  1, -7,  1, -4,  5,  7,  0,  4,  3, -4 },
+    {-20, 25, 12, -4, 16, -4,  2,  2,-14, -2, -3, 29, -1,  1,  3,  1,
+       9, -5,  2, -8, -3,  1, -7, -2, -7,  1,  0,  4, 16, -2, -1, -1 },
+    {-10, 30, 17,  3, -5, -2,  0, -5,-22,  4,  5,  5, -3,-18, -6, 10,
+      -5, -7,  2,  8,  7, -7,-11, -2,  0, -3,  3,  2, 11, -4,  4, -4 },
+    {-11, 30, 11,  4, -3, -8,  1, -2,  4, 18,  3,  1, -1,  0, -8, -4,
+      -3, 10, 13, 14,  5, -5,  1,  1,-10,  2, 15,  4,  9, -1, -5, -3 },
+    {-17, 32, 18,-18, -3, -5,  6, 10,  1,-15, -5,  9,  8,-12,-10, -6,
+      11,  9, -5, -8, -7, 10,  5,-10,-14, -4, -3,  1,  9,-11,  2,  1 },
+    {-13, 28,-11, -1,  2,-16, -2,  7,-24,  0,  3,  6,  3, -1, -8, -7,
+     -12,  2,  2,-20, 10,  4,  0,-13, -2, -2,  1,  8,-14,  0,  4,  1 },
+    {-14, 23, 12,  8,  8,-26,  2, -4,-14, 13,-14, 15,  3, -9, -1,-13,
+     -10, -2,-10,  6,-16, 12,  8,  0,  9,-10, -7, -4, -4,  7, -8,  8 },
+    {-20, 45, 10,-14,  4, 16,  8, -9,  1, -8, 10,  5, -7, -2,  2, -5,
+      -1,  0, -5,  4, -6, -2,  4,  1,  3,  4, -4,  2, -2, -2,  5,  1 },
+    {-20, 26, -4,  1,  7,  4, -8,  1, -5,-13,  2, 13, -7, -3,  6, -6,
+      22,  0,  5, 11, -4,-11,  8, -9,  2, -2, -4, -2,  2,-13, -4, -8 },
+    {-28, 18, 17,  3, -8,-23,-16, -6,  5,-10, 14, 10,  5, -1, -8,  4,
+      -2, 13, -3, -2,  3,  4,  3, -2, -3, -4,  0,  1,  3,  4,  0,  4 },
+    {-12, 32, -6,-16, 18, 12,-16,  0,  7, 13, -4,  5, -8, -1, -3,  4,
+       6, -2, -1,-13,  4, -1,  3, 12, -3,-10,  1,  6,  8,-11, -2,  4 },
+    {-18, 26,  2,  5,  0, -9,-17, 14,  5,  1,  7, -3, -8, -3, 11,  7,
+      -5,-12, -8,  7,  0, -7,  2,-12, -9, 13,-11,  9,  6,-11, -5, 11 },
+    {-24, 22,-15, -9,  8,  1, -7,-12, -9,  3, 11, 15, 14,-11, 12,-15,
+      -5,  7, -2,  0, -8,  3,  3, -1,  2, 11,-11, 14, -6, 13,  1, -6 },
+    {-20, 28, 18, -4, -6, -5, 12, 14,  2, 10,-13, -6, -8, -6,-13, -1,
+     -26, 22, -3,-14,  6,  0, 10,-15,-13, -9,  6, -7,  1, -5, -4, -1 },
+    {-19, 26, -8, -3,-14, -6, -9, -4, -8, 15, -8,  3,-12, -4, -2, -7,
+      -5,  3, 13, -3, -4,-25,  4, -1,  5,-12, -1,-13,  5,  2,  0,  6 },
+    {-18, 43, 14, -8,  1,-23, -2, -2,  1,  3, -7,  0,  0,  8, -1, -3,
+      -5,  1,  5,  2,  0, -2, -2, -2,  1, -1, -1, -7,  0,  3, -3,  9 },
+    {-11, 30, 10,-14,  3,  1, 10,-11,  1, -7, -4, 14,  2,  1, -9,  1,
+     -11, -2, -7,  5,-11,  1,  3, 14,  1,-16, -8,  3, -5,  7, -4,  4 },
+    {-18, 24,  6,  3,  8,  7,-22, -7, -7,  3, -8,  4, 23,  9,  3, -1,
+       3,  6,  7, -1, -7,  6,  4,  1, -3,  1, -6, -1,  2, -7,  3,  3 },
+    {-15, 38, -7, -1,-11,  2,-17,-24, 24,  8,  7, -4, -5,  2,  2, -7,
+       1,  4,  0, -9,  5,  0, -1,  1, -1, -5, -6,  3,  0,  7,  8, -3 },
+    {-14, 22,  1, -5,  9,-12, -9, -5, -6,  5,  7,  8, -1, -4, -9, -3,
+     -33,-16, -9, -1, 12,-11, 17, -7, -3, -1, -7,  3,  2, -3, 16, -4 },
+    {-14, 20,  6,  4,-10, -4, -4, -4,  1, -7,  2,  6,  8,-12,  4,  1,
+      -1, 12, 10,  3,-14,-10, -3, 18, -2, 33, -5,-17, 17, -5,  9,  7 },
+    {-12, 23, 13,  0,-11, -8,-11, 12, -5, -9,-16, 11,  6,  4, 12, -5,
+       5,-13,  7,-12, -3,  1,  2, 12,  1, -4, -1,  5,  4, 11,-12, -3 },
+    { 15,  2, 14,  7,  1,  2,  1, 12, 10, 23,  4,  6,-20,-10,  4, 26,
+      -6, 13,  4,  3,  2,-11,  5, -7,-10,  4,  9,  1, 10, -4, 11,  4 },
+    { 17, 15, 31, 17, 18, 16, 11, 24,  2,  4,  2,  3, -8, -3,  7, -3,
+      -5, -7, -2, -6, -4, -5, -4, -1, -4, -2, -5, -6,  2, -1,  4, -2 },
+    { 16,  8, 15, 14,  3,  7, 21,  9,  8, 15, 21,  6,  8, 12,  5, -5,
+       7, -3, 10,  2, -3,  8,  6,  0,  5,  5,  6, -3,  2,  4,  0, -5 },
+    {  5, -4,  6, 12,  6, 13, 24, 17, -5, 17, -1, -6, -7,-10, -8,-18,
+       3, -2,  2,  7,-15,-11, 12, -3, -2, -2, -4, -7,  2,  0,  5,  5 },
+    { 10, -6,  8, 11, 12, 20, 22,-11, -3, 15, -3, 15, -2, -2,  0,  2,
+       5, -8,  4, -5, -9, -4, -1,  2, -1, -3,  1,  3, 13, -1,  9,  7 },
+    { -5,  8,  5, 11, 14, -5, 14, -9,  2, 35,  8, 15,  1, -2,  2, -2,
+       4, -9, -3,-14,-12, -2, -2, -4, -2, -8, -3,  1, -6,  3, 10,  0 },
+    { 16,  0, -6, 15, -3,  4,  4,  3,  3, 20,  5, -4, 10,  9, -9, -3,
+     -10, -2, -7, 11,-11,-10, 17, -1,  3,-15,  2,  9,-15,-10, 16, 10 },
+    { 14,  4, -7, 19,  3,  0, 19,  8, 16, 34, -9,  6,-13, -1,  6,  5,
+      -1, -2,  4,  3,  2,  1,  1, -1,  0, -7,  2, -1,  1,  0,  6, -1 },
+    {  1,  6,  9, 13,  9, 10, 15, 16, 10, 18, 13, 17,  3, -1, -7,  2,
+     -15,-11,-10, -4,-13, -6,-17,-13, -6,-14,  1,-10,  6,  4, -1, -1 },
+    { 13,  1,  7, 10, 14, 13, -7,  5,  5, 28, 14, 14, -2,  2,  3, -3,
+     -13, -4, 10, -9, 19, -4, -3,  4, -5, -5,  0,  5, -5,  0,  3, -4 },
+    {  1,  0,  6, 22,  9, 18, 18, -3,  5, 10, 12, -2,  1, -3, -8,-12,
+       9,-10, -7,  1, -1, 19,  0,  2, -8,-11,-10,  9,  6, 11,  0,  3 },
+    { 10, 11, 19, 44,  0, 14,  1, -7,  6, 22,  2, -1,  9,  2,  0, -4,
+       4,  0, -6, -6,  3,  0,  0, -2,  2, -5,  1, -2,  0,  1,  1,  1 },
+    {  5,  7,  0, 32, 30, 26,  5,  4, -7, -3, 15, -6,  3,-10,  7,  6,
+      -8, -7,  2,-13, -5, -1, -3,  7,  3, -2, -8,  0,  6,  4,  5,  0 },
+    {  9,  8, -2,  4,  2, 11,  4, 29, -5, 14,  8, -5,-14,  8,  0,  9,
+       8,-10,  5,-15, -6, -9,  9, -1, 18,-16,  9,-21, -3,-13, -2,  8 },
+    { 25,  7, -9, 23, 20, 18,  6, 16, -9,  8,  8, -5, 11, 13, -8,  7,
+       4, 10, -2, -1, -7, -9, -7, -9, -4,  1,  1, -5,-10,  8,  4, -5 },
+    {  9,  2, 16, 14, -5, 14,  1,  0,-21, 17, -1,  9, 12, -3, -3,  4,
+      -4, 14, 10,  3,  0,-10,  7,  4,  4,-11,  2,  4, -1, -3,  9, -1 },
+    { 17,  8, 11, 26, 15, -3, 14, -1, 12,  9, 10, -8,  8,-18,-11, -3,
+     -14, -7,  7, -3, -3, -4,  1, -7, -3,  2, -3, 16, 10,  0,  9,  6 },
+    {  9,  8,  3,  8, 18, 14, 11,  1, 10,  6,  1, -4,-16, -2, 14, -2,
+       1,  8, 12, 14,  3, -3,  8,  8, 12,-15,  3, -3,  3, -2, 14, 10 },
+    { 22, -3,-11, 13, -7, 11,  4, 11,  3, 14,  0, -6, -2, -9,  4,  2,
+      -2,  0, -5,-27,-10,  3, -1,  5,  8,-24, -3,-11, -3,  2, 11, -1 },
+    { 19,  2,  8, 36,  5, -6,  3, 15, -3, -4, -5, 14,-10,  1,-12,-10,
+      -3, -4,  3, -2,  1, -8,  4,  3,  5, -3,  0,  4,  8, -2,  8,  4 },
+    {  8, 14, 15,  9, -4, 10,  5, 11,  9, 10,  8,  9,-15, 15,  6, -8,
+     -10,-13,  5, -8,-20,-13, -6,-11, -1, -3, -6, -4, -1,  0, 13, 15 },
+    { -2, -1,  9, 12,  2,  2, 13,  3,-23, 33, 15,  2, -4, -1,  3,  8,
+       8,  6,  6, -7,  8,  6,  9, -1,  3, -8,  0, -4,  1, -8, 11, -1 },
+    {  6,  5, -6, 16,  2, -3, 31, 21, -9, 12,  0, -1, -4,  1,-12,  3,
+     -13,-18,  2,-11, -9,  2, -8, -6, 11, -3, -1,  0, -1,  0, 13,  5 },
+    {  5, -1,  2,  0, 25,  5, 10, 16, -5, 21, 14, 12, 13,  2, -5,  5,
+       5, -3, -2,-14,  0,-12,  7, 11, -1, -7, 19, -1, -1, -1,  8, -1 },
+    { 10,  7,  3, 11,  0,  8, 22,  3,  3, 19, -4, 12, 15,  9,  5, 15,
+       2,  1,  2,-10,-10,  0,  2, -1,  0,  1,-12, -1, 21, 16,  9, -7 },
+    { 11, -4, -5, 24, -7, 11, 20, 11,-15, 18,  5,-13,-15,  0, -5,  9,
+       1,  0, -1, -9,  4, -8,  6, -8,  1, -2, -7, 20,  9,  3,  9,  3 },
+    { 20,  0,-12, -6,  9, 31,  9, 12,  8, 27, 15,  7,-16,  5, -3, -7,
+      -1, -9, -2, -7, -3,  4, -8, -3,  3, -6, -2, -2, -3, -6, -1,  2 },
+    {  6, -6, 48,  8, -3, 19, 12, 11, -7,  2,  3,  0, -1,  1,  8, -4,
+       4, -6,  0, -4, -4, -3,  3,  6,  3,-13, -8,  5, -3, -7,  8,  5 },
+    {  7, -2,  6, 11, 12,  2, 14,  4, -5, 12,  2,  9,  4,  2,  0, -1,
+       2,  0,-15, -9,-16, -2,  8,-17, -5,-22,-19, -5, -1,-10,  1, -2 },
+    { 11, -9,  3, 12,  6,  6,  1, 17, -6, 19, 14,  7, -7, -1, -1, -9,
+       9,-11,-17,  0, -6, 16,  0,  1,  9,-24,  3,  3, -9, -3,  3, -2 },
+    {  9,  0,  1,  8,  1,  7,  2, -5, -3,  8, -1,  7,  2,  6, -3, -6,
+       5, -2,  6, -2, -4, -3,  0, -3, 13,-50,  1, -2,  2,  4,  4,  3 },
+    {  7,  0, 26, 21, -4,  2, 17,  8,  7, 11, -7,  1, -1,-15, -1,-15,
+     -11, -4,-17, -4,  1, -7,  3,  6,  3, -9,  2,  3,  6, 10,  6, 12 },
+    {  1, -2,  2, -1,-10, -4,  6, -3, -5, -2, -8,  2,  2,  2,  8,  0,
+       1,  1,  6,  0, 11, 13,  3,  4,  0,-12, 11, -5, 19, 20,  2,  5 },
+    {  5,  3,-13, -2,  1,-12, 11, -7,-12,  7, 10,  0,  7,  0, -2,  4,
+      -6, -9,-11,-12,-23, 12, 10, -3,  0,  6, 19, -1, 24, 18,  9, 12 },
+    {  6, -3,  2,  5,  2,  2, -2, -5, -8,-11, -4,  3, -8, -4,  5, -3,
+     -16, -4,  3,-12, -4,  3, 32,  7,  2,  8, 32,-18, -1, 12,  1,  7 },
+    {  0, -8, -1,  0, -8,  7, -8, -1, -1,  4,-12, -1,  3,  0,  1,-18,
+       8,  8,-14,-10,-11, 19,  9,  5, -7,  6,  8, -4, 26, 12, -1,  6 },
+    {  3,  5,-14,  7, 14,  8, 20,-13,-16,-10, -2, 17, -7,  4, -8, -9,
+      14, -5,  3, -4,-12,  7, 14,-10,-19,-20, 35,  8, 13, 14, -2,  9 },
+    { -2, -4, -1,  1, -3,  0, -1,  1,  2,  2,  6,  0,  0,  4,  5, -2,
+       3,  3,  3, -2, -7, -3, -3, -1,  6, -2, 29, 22, 13, 34,  0, 14 },
+    { -3, -9,  3,  1,  5, -4,  2,  0,  7, -9,  0,  2, -5, -3,  0,  6,
+      -1, -1, -1,  2,  2,  4,  8,  7, 20, -6,  7, 16, 33, 20,  6, -1 },
+    {-11,  1, -3, -3,-11,  3, -9,-25, -1,-16,  4, -8, 15,  1, -2,  7,
+       8, 23,  2, 18,-13, 16,  3, -7,  6,  3, 16, -8, 12, 16,  3,  4 },
+    {  0,  5,  5, -5,  1, -1,  2, -3, -2,  1,-13,  2,  2, 10,  6,  7,
+      18, 18,  7,  9,  8,  9, 21, 14,  7, 12, 15, 14, 15, 12, 11,  5 },
+    {  1, -5, 11, -2, 17,  8,  3,  0, -1,  6, 11, -7,  6,  6,  7,  5,
+     -15, 14,  1, 11,  4, 10, 12,  1,  2,  4, 30,  1, 11,  1,  6, 13 },
+    {  2,  4,  3, -7,  5,  8,-11,  7, -5,  9,-10,  6,  8,-10, -3, 10,
+       1,-29, -4,-26,  5, -8, 13,  4,  3,  6, 35,  1,  3,  6,  3,  0 },
+    { -2,  1,  0,  0, -1, -3, -7, -3, -9, -3, -1, -6,  3,  4,  4,  0,
+       5, -1, -2, -2, -1, -4,-10,  8,  0, -6, 10, -4, 46, 12,  2, 28 },
+    {  4, -1,  4,  1,  0,  4, -2, -2, -2, -1,  2, -4,  1,  5,  0, -3,
+       1,  1, -2,  0,  1, -2, -1, -1,  3, -6, 35,-11, 13, 53, -3, -1 },
+    { -5, -2,  0,-13,-16,  5,-12,-11,  1,-30,  3,-18,-24, -8, -5,-19,
+       1, -3, -8,  7, -7, -8, 15,-19,  4, 10, 30, 24,  6,  1, -9, 10 },
+    { -4,  8, -7, -4, -6, 12, -1, -9, -4,  2, -9,  3,  2, -2,  4,  2,
+      22,  9,  4, -5,  0,  5, -2, -9, -3,  1, 18,-12, 18, 16,  4, 16 },
+    { -5, -8, -3, -5, -3,  6, -7, -3, -2, -5, -3,  1,  2,  2,  4, -6,
+      10,  3, 12, -3, 20,  0, 27, -4, 16,  5, 18, -3, 23,  4, 12, 11 },
+    {  0,  1,  0,  1, -2,  1,  2,  1, -1,  0, -2,  2, -2, -4,  1, -2,
+      -2, -1, -5, -2,  0,  0, -2,  2,  9,  7, 63,  5, 12, -1,  1,  0 },
+    {  4, -3, -7, -5,-11, -5,-12,-10,-10,-12,-15,-12,-14,-14,  1,  1,
+      10,-10, 16,  6,  2,  9, 11,  9,  9,  8, 12, -1, 13, 12,  6,  3 },
+    {  7, -3, -2,  4,  6, -8,  2, -3,-12, -5, -9, -8,-10, 15, -2, -4,
+       8,  9,  7,-13,-18, 34, -5,  7, 12, 22, 16,-11, 13, 25,-15,-11 },
+    { -3, -2,  0, -4,  1,  0, -3,-13, -7, 13, 12, -7,-10, 13, 19,  6,
+      16, 15,-12,-15, -3, 34,  1,  5,  1, -9, 11, 21,  8, 17, -5, -6 },
+    {  3, -5,  0, -4,  0,  4,-11,  4, -7, -3, -1, -8,  3, -2,  2,  1,
+      11,  5,  6, 14, -3,  2, -4, -7,  0, 31, 15, -2, 24, 11,  5,  4 },
+    { -1, -4, -9,  5, -8,-18, -4, -9,-20,-18,  7,-14,-16,  3,  8, -3,
+      29, 11,-13,-13,  7,  1, 17,  6,  6, 21, 11,  1, 14, -8,  2,  5 },
+    { -3,  8,-10, -6, 12,  2,  1,  3,  3,  3,  3, -6, -8,-14, 15, -5,
+      16,  4, 16,  0,  7, -1,  0, 16,  2,  1, 22,  4, 19, 13,-11,  1 },
+    {  2, -3, 10, 20, -4, -1, -8,  5, -8, -9, -6, -2, -4, -7,  8,-10,
+       0,  8, -6,  1, -8, 14, 13,  5, 17, -6, 26, -1,  7, -1,  0, 12 },
+    { -4, -7,-31, -2, -7, -1,  5, -5, -5,-12,  4, -7, -6,  3, 15, -2,
+       5, -2,  7, -1, 10,  7,  8, -1, 14, 20, 14,  9, 16, 16,  8, 24 },
+    { -7,  0, -3, -6,  1,  3,-13, -6, -4, -4, -5, -9, -1,-10, -4, -8,
+       2,  0, -1,  1, 24, 24, 21, 31,  5,  2, 11, 12,  7,  4,  3,  6 },
+    { -3, -5,  6, -4, -3, -1,  2, -1, -2,  1,  0, -8, -1,  2,  0, -4,
+       6, 22, -1, -5,  8, 12, -1, -2, 28, 27, 20,-27, 14,  1,  2, -3 },
+    {  1, -5, -2, -2,  6, -2,  9,  1, -2, -5,  3,  4, 11,  5,  2,  8,
+      -3, -1,  1, -2, -3, -5,  5,  8, 49, 12,  8, -3,  9, 20, 12, 17 },
+    { -6,  0,  1,  7,  0,  9, -2, -4,  8,  0, -2,-10,  0,  7, 21, -1,
+       0,  1, 17, -7, -5,  2,  4, 16, -2, 17, 14,-20, 15, 14,  4, 15 },
+    {  0,  3, -4,  9, -4,  0,  6,  4, -6, -6, -5, -7,  2, -9,-10, -2,
+      -5,  0, -3,-21,  9, 14,-11, 13, 29,  2, 25,  4, 22, -1,  2, -3 },
+    {  2, 12,-11,  2, 16,  9, -4,  7,  1,-10,-15, 11, -4,  3, -2,  4,
+       4, -5,-10,  1,  4, 19,-15,  6, -4, -2, 30, -7, 11, 21,-12,  5 },
+    { -2, -3, -2,  4, -1, -5, -3, -7, -5,  1,  0, -6,  1, -6,  7,  0,
+       8, -7, -3, -2,  2, 14,  2, -3,-26, -1, 26, 22, 32,  1, -2,  6 },
+    {  1,-38, -1,-20, -2, -3, -6, -4,  2,  2,  7,  0,  3,  5,  3, 10,
+       6,  1, -3, -5,  7,  5, -5, -4,  8,  3,  1,-14, -1, -9, -5, -4 },
+    { -5,-26, -7,-19,-10, -5,-11,  5,-11,-25, -8,-14, -9,-16, -8, -6,
+     -17,-14, -1, -1,  6,  2,  2,  2,  3,  0,  2,  8, -8,  3,  0, -3 },
+    { 17,-49, -3,-23, -1, 11,  7,  3,  4, -4,  0,  0, -1,  4,  2,  4,
+      -2, -4,  2, -2, -1, -2,  2,  0,  0, -1,  0,  0,  1,  2,  0,  0 },
+    {  4,-34, -6, -9,  1, 21, -7,  3, -2, -1, -3, 18,  2,-16,  7, -3,
+       8,  7, -5,  7,  2,  4,  8, -6, -7, -2, -5, -1,  4,  1,  2, -4 },
+    {  5,-29, 13, -2,-14,  3,  1, 18,-15,  4, -8,  8,-10,  8,  2,  1,
+      -8, 15,  3,-10, -4, -4, -2,  0, -3, -4,  2, -3, -4, -3, 12, -6 },
+    { 13,-20,  3,-18,-17,  4,-14, 13, 28, 11, -8, -6, 16,  6,  0, 10,
+       3,  4, -9, 13,  5, -7, 12, -5,  0, -7,  5,  1,  3,  3,  2,  1 },
+    {  3,-27, -5,-11,-21,-11,-12,  0, -5,  7,-22,  1,  3,  5,  0, -5,
+       8,  7,  1, -5, -7,  2, -5,  4,  1,  3, -8, -2,  0,  4, -2,  6 },
+    { 31,-45,  0, -1,-12,  1,  2, -6,  4,  3, -1,  3,  3,  0,  5,  3,
+      -5, 12,  4,  6,  2,  1, -2,  1,  3,  2,  5,  2,  2,  2,  3, -1 },
+    {  9,-45,  6,  5, -1,-17, -2, 18, -3,  2,  0,  1,  0, -1, 10,  8,
+      -7, -2, -5, -8,  6, -1,  0,  4,  6, -3, 12, -1, -2,  0,  5, -7 },
+    {  3,-26, -2,-12,-12,  2,-10, 16, -3, 12,  4,  5, 11,  8,-16,-17,
+      -2, -3, -3,  2,  5, -9, 13,  1, 10, 11,  3,  5, -2,  2,  2, -7 },
+    {  8,-26, 32, -7, -5, 22,  2, 14,-10, -8, -7,  3,  3,  7,  0, -5,
+       0, -1, -3,  0,  8,  4, -5, -7,  6, -1,  4,  8,  1,  1,  7, -6 },
+    {  4,-31,  2,-14,  2,  0,  1,  8, -6, -1, 17, -3, 13, -6,  5,-10,
+      -2,-10, -2,-10, -3,  7,  1,  5, -8,  8,-14, -3,-15,  7,-10, -6 },
+    { 16,-27, 13, -4,-23,  7, -9,  6, -7,  5,  4,  2, -1, -3, 23,-18,
+       7,  0, -3,  4, -3,  9, -6, -2, -1,  8, -6,  2,  6, -3,  2, -2 },
+    { -1,-35, -2, -8, 11, -1, -7, -3, -2, 11,  7,  6, -6,-10,  9,  6,
+      -3, -5, -6, -3,  9, 16,-16, -9,-20, 12,  3,  5, -3,  1, -9,  4 },
+    {  2,-24,  1,-12,-16,  5, -4,  3, -4, -1,-11,-11, -8,-14, 14, 10,
+      -8, 20,  8, -3,-11,  1,  1, -4, -4, -7, -3, 15,  2, -6, -2,  7 },
+    {  9,-21,  2,-19, -7, -5, -8, 25,  3, 17,  5, -3,  9,-12,  8,  2,
+      -4,  3,  3,  1, 11, -9, -4, -3,  4,  3,-22,  6,  4,  6, 11, -5 },
+    { 16,-23, 13,-17,-21,-12,  5,  9,-20,  7,  6, -6,  0,  2, -9,  6,
+      -6,-13, -7, -1,  5, -3,  5, -7,-10,  1,  0,  8, -9, 11,  0, -8 },
+    { 10,-26, -9, -7,-19, -4,  6, 16, -7,  5, -4,  4,  8,  0,  4, -1,
+       6, -7,  1, -8,-11, 10,-14,  0,-16,  6, -3,  5, -1, 14, 12,  1 },
+    {  8,-27, 12,-14, -1, -1,-19, 10,-11, 21,-14,  9, -8, -3,  8, -1,
+      12,-13,  3, -4, -2,  0, -9,  0, -7,  2, -3, 12,  1, -3,  3,  1 },
+    { 18,-20,-14,-14,-16, -3,-24,  6,-17,  2, -3,-11,  2, -3, 12, 10,
+      10,  1, 10,  7,  8,  5,  5,  4, -1,  7,  2,  2,  0,  4,  7,  0 },
+    {  0,-30,  9,-16,-18, 15, 12, -3,  4, -4, -5,-11, -4,-12,-10,  0,
+       2, -2, -4, -1,  2,  0, -1, -6,  2, -3,  4, -5,  7,  3,  5,  7 },
+    { 25,-24, -1, -6, -9,  6,-13, -2,  3, 15, -3, 11,  4, -8,-11,  2,
+       0, -9, -2,  7,  4,  8,  5, -8,  5,  6, -1,-11,-15, -5,  0, 11 },
+    {  0,-34, -7,-11, -7,  9, -3, 19,  4, -8,  3,-11, 11, -3, -9, 12,
+       9,  9,  2,  1, -7,  1, -3,  0, -6, -2, -1,  3,  0, -7, -2, -5 },
+    {  6,-34, -4, -5, -3, -9,  2,  9, -1,  9, -5, -3,-26,-12,  8, -6,
+      -7, 11, -8,  4,  4,  1, -1,  0,  8,  9, -4,  7, -1,  1, -3, -1 },
+    {  3,-30,  5,  6,-10,  3, -7,  6,  3,  3,-26,-19, -3,  1,  7,  5,
+      -4, -5,  6, 10, 13,-10,  4, -7, -4,  5, -3,  9, -6,  3,  9,  5 },
+    {  4,-24,  9,-19,  2, -4, -5,  8, -3,  2,  0,-15, -1,  9, -4, 22,
+       6,  9,  3,  7, 11, -9,  0, -3,  4,  5, -5, 10, -8,  5, -7, -3 },
+    {  8,-27,  7, -3, -1,  2, -9, 13,  7, 12, -4, -6, -6,  5,  0,  7,
+       5,  1, 15, -3, -4,  0, -5, -2,  7, -5, -7,  1, -2, 13, -8, 13 },
+    { 17,-22,-15,-11, -8, 16,-14, 18,  2, -1, 14, -7, 14, -6, -6, -7,
+      -8, 17,  6,  4,  4, -7, -5, -9,-14, -6, -1,  9, -3,  1,  6, -5 },
+    { 25,-30,  2,-12,-13, 18,-18, 16,  8, -3, 10, -8, -3, -1, -6,  3,
+      -5, -7,  4,  6,  7,  1,  1,-11, -5,  6,  2, -4,  9, -1, -5, -2 },
+    {  7,-23,  7,-15, -1, -3, -1,  0,-10, 12,  2,  5, -4,  0,  4,  6,
+      -1,  5, -9, -1, -1, -7,  1, 17,  9,-17,-16,  8,  4,-14, 11, 14 },
+    {  0,-31,  7,-13,  3,-11, -7,  6,  1,-11,  8, -7, 15, -3, 16,-11,
+      -1,-15, 16, -3,  5,  0, -2, -2, -6, 11,  5,  6,  5, -5,  6,  3 },
+    { 13,-24, -2,-20,-10,  7, -3, -1, 15,  2,  6, -5, -7,-10,-20,  1,
+      -4, 14,  8, -2,  3,-13, -3,  1, -4,  1, -3,  2,  8, -7, 16, -4 },
+    {  1, -2, -2, -3, -4, -7,  0,  3,  6,  7,  3,  2,  1, -2, -1,  0,
+      -6,  4,  2, -4, -3, -4,  5,  9,  5,  0, -3, -3, -4, -7,-31,-50 },
+    { -1, -3,  7,  2, -1,  2,  4,  6,  0, 10, -2,  0,-20, -6, -3,  9,
+     -20,-22, -1, -1, 15,  9,-12, 10,-13,-20, 12,  3,  5,  6, -7,-26 },
+    {  0,  4, -2,-14,-12,  6,-13, 11,-10,  3, 22,  6, 16, -2, -5,  1,
+      -3,-11,  0, -7,  5, -5,  0,  1, -1, -6,  8,  8, 10,  9, -5,-27 },
+    { -5, 10, -2,  7,  9, -9,  5, -9,  5,  4,-15, 14,  1,  3,-10,  5,
+       0, -2,  7,  3,-13,  6,  9, -6,  5,-14,-17, -1, 11, 14, -2,-26 },
+    {  0,  6, -3,  0, -8,  6,  0,  1,  4, -8,  2, -5,  4,  7, 15, 11,
+       9, 19, -2, 14, -8,  7, -1,  3, -3, -3,-10, -2, 12, -2,-12,-29 },
+    {-12, -5,  0, -3, -2,  6,  3, -3,  2, -2,  1, 11,  2, -7,  5,  1,
+       2, -2,-14,  0, -1, -5,  3,  8,-28,-26,  6, -6,  3,  8,-10,-27 },
+    { -1, -3,  6,  2,  4, 15,  1,  0,  2, -2, -2, 13,  3,  6,  0,  6,
+      -1, -4, -1, -5,  8, -1,  5, -5,-15, 11, -8, -5, 14, -6,-14,-29 },
+    { -5, -6,  0,  1,  0,  6, -3,  2, -5, -1,  5, -3,  2,-10,  3,  4,
+       3,  0, 13, -3, -1,  4, -4, -6,  2,  9,  8,  2, -3, 28,-11,-31 },
+    {  1, -4,-10, -9, -4, -3,-15, -6,  1,  5, -3, -6,  5, -6,-22, 27,
+     -13,  5,  3, -7, -4, 20, -7,-12, -1,-24, -4,-13, -8,-11,-15,-21 },
+    { -6, -4, 19, -6,  2, 11, -6,  1, -3,-10,  9, -9, 12,-10,  2,  1,
+      -9,  1, 15,  7, -5,  5,-29,-35,  4,-30,  9,  9, 19, 17,  2,-17 },
+    { -3,  3, -3,  1,  2,  5, -1,  5, -2, -3,  1, -3, -8,  3, -4, -2,
+      -4, -1, 12,  0,  2, -8, -6, -4, 16, -1,-14, -2, 25, -6,-15,-36 },
+    {  0, -1,  3, -4, -4, -1,  7, -4,  8,  0, 10,  9, -4,  1, 10, -1,
+      -3,-13, -5, -4, -1, -4,  8, 11, 14, -7, -5, 16, 12, 13, -1,-28 },
+    {  1, -2,  2, -3, -8, 10,  4,  9, 12,  3,  5,  0,  8, -3, -6,  2,
+      16,-11, 11,  0,  1,  6,  1, 18,-10,-16, -1, -4,  5,-14,-15,-20 },
+    {  1,-12,  5,  4, -7,  8, -1,-17, -2, -9,-14,-11,  6, -9,  5, -4,
+       3, -2,  7, 18, -5,  5,  6, -1,-11, -2,-10, -3,  8, -3, -2,-32 },
+    {-12,  5, 20, -5, -6,-11, -6, -6,-13,  4, -6, 19, -8,  2,  3, -9,
+      -4, -4, -1,  9, -1, 21, -1,  7, 15,-10, -1, -3,  9, -3,  2,-24 },
+    {  0, -3,  2, -6,  4, -1, -9, -2, -1, -3,  6, -1, -5, -6, -5, -8,
+       0, -2, -6,  9, -4,  3,  2,-13,  1, -7, 23,-13,  4, -3,-15,-33 },
+    { -7,  2,-15, 11,-10, 14,  0,-11,  3, -1, 12, -4, -4,  9, 11,-13,
+     -13, -3,-14,  1,  3,  6, -5,  8,  0,  5,  5,-10,  4,  5, -6,-30 },
+    { -6,  4,  0, -5,  4,  1, -1, -1,  3,  6,  5, -2, -5,  0, -2,  5,
+      -4, -2, -4, -2,  4,  7, -7, -1,  1, -4, -3,-19, 37, 12, 10,-40 },
+    { -7,  2, -7,-12, 17, 11, -7,  2,  2,  3,  1, -1,  3,  4, -2, -5,
+       9, -9,  6,  4,  9, 12, 11, -5,  2, -1,  0,  9,  5, -7, -2,-24 },
+    { -7,  6,  1,  3,  1,  0,  6,  0,  4,-12, -2, -2,  1, -9, 10, -2,
+      11, -1, 21,-12, 15, -5, 10, -5,  5, -5, 14, -6,  5, -7, -3,-29 },
+    { -2,  0, -5, -2, -3,  1, -3,  0,  4,  2,  3,  0,  2, -2,  7, -2,
+       3, -5,  2, -1,  6, -4,  0, -3,  8,-11, 19, -8, 22,-34, 13,-35 },
+    { -1, -3, -1,  9, 11, -3, -3, -1,  7, 18, 11, -5,  2,-12,-11, 18,
+       9, -5,  1, -6, -9, 12,  1, -3, -3, -9,-14,  9,  9,  8, -6,-26 },
+    {  0,  5, -5, -1, -1, -2,  4,  6,  8,  2, -1, -2,  5,  1, -5, -4,
+       1,  1, 18,  1,  7,-10,  3, -2, 12, -1,-15,  9, 12,-14, 13,-38 },
+    {  3,  0, -8, -1,  0,  8, -9, -3, -8, 16,  3, 16, -5, -9,  0, -1,
+      -7, -1, -4, 13,  7,  0,  1,  2, -1,-16,  0, -2,  1,  8, -8,-28 },
+    {  7,  9, -5, -3, -2,  2,  0,  3, 11, -6, -4, -2, -2, -5, 28,-18,
+      -6,  2, 15,-10,-15,-10, -2,  0, -2, -2,  4, -3,  7, 11,  5,-30 },
+    {  9,  0, -7, -1, -4, -7,  2,  2,  9, -2,  2,  3, -8, -6, -6,  3,
+     -10,  4, 10,  5, 21, -4, 14,-18,  1,  3,-10, -2,  6, 14, -8,-26 },
+    {-14, -1,  2,  3, -3,  7,  1,-22, -1, -1,  0,  1, 12,-14,  3, -5,
+       0, 10, -3,  1, -5, 12, -3, 10, -8,-22,-11,-13, -7,-10,-13,-25 },
+    { -2, -5, -4, -4, -9,-18,  9, -3, -5, 17, 13,  5,  6, 11,  3,  8,
+      20,  4,  2,  9,  8,  5,  6,  1,  7, -7, -6, -2, -7,  0,-17,-23 },
+    { -5, -5,  2,  0,  6,  2, -2,  2, -3,  4,  4,  0, -5, -2, -4,  6,
+       8, 10, -1,  1, -5,  5,-14, -2,-11,  8,  6, 25,  7, -1,  0,-43 },
+    { -4,  0,  4, -2,  7,  0,  3, 17,  5,  2, -5,  1, 21,  3, -2,-10,
+     -16, -9,  7,-12,  9, -8,  2,  5, -5,-10, -2,-11, -5, -1, -9,-30 },
+    { -2,  3,  1, -4, -1,  0,  8,  1, 12,  4, -1, -1,  3,-17, 13,  9,
+       0,  7, -6, -5,  9,  1,  5,  4,-10,-18,  0, 14, 11, -4,-16,-28 },
+    { -1,  0,  2, -1,  4,  1, -1,  1, -1, -2, -1, -2,  3,  0,  0, -1,
+      -1,  1,  2, -2,  3,  3, -2,  4, -2, -1, -6,  1, -1, -1,  6,-70 },
+    {  7,  3,-11, -1, 12, -4,-14,  4,  4, -4,  4, -2,  2,-12, -4, 15,
+     -17, -4, -3,  6,  8, -5, 22,-22,  5,-11, 15, -4,  4, -1,-21, -1 },
+    { 10, -2,-13, 11,  4, 14,  4,  9,  8,  8, 19, 15, 14, 15,  5, 10,
+       8, 15, -5,  4, 14, -8,  1,  1,  2,  1, -1, -3, 21,  8,-29, 13 },
+    { -6,  0, -6,  6, -1,  2,  8, -4, -5,  4, -4, -5,  0, -2, -4,  0,
+       9, -2,  1, -2, 26,-19, 21,-10,  4,  1, -8,  5, 22,-10,-13, 15 },
+    { 11, -5,  1,  0,  6,  3,  7, -2, -2, -3, -5, -1, -2, -6,  1,  1,
+      -8, -5,-13, 13, -2, -3, -1, -9,-28,  4,  2,-11, 18,-20,-24,  9 },
+    {  7,  4, -3,  6,  6, -6, -7, -5, -7, -4, -4,  0, -7, -5, -6, -5,
+       2,-13,-12,  2,  0,  5, 18, 15,-13, -7, 13,-20, 16,-10,-19,  6 },
+    {  5, -8, -1,  5, 10,  2, -1,-10,-11, 23,  8, -5, -8,  4, -5, -4,
+      -5, -5,-11, -8,  5,  1,  7, -9, -9, -6, 12, 14, 17,-12,-22,  3 },
+    { -5, -8, -3,  3, 12, -1,  0, -4, -5,  1,  1,  6,  1,  5, -5,  7,
+      -2,  7,  1,  6,  6,  2,  0, -5, 17, -4, -5,-24, 13,-20,-27, 14 },
+    { -1,  2, -3,  1, -3,  1, -3,  0, -2,  3, -2,  1,  2, -1, -2, -1,
+      -2, -5,  5, -2,  0, -7,  1, -6,  8,  8, 11, -5, 24,-43,-13,  2 },
+    { -2,  4,  7, -3, -4,  4, 13, -4,  0,  0, -2,  9,  0, -3, -6,  1,
+      -7,  1, -1, 10,  0,  5, -1,-24, 25,-15,  7,  2, 22,-10,-21,  0 },
+    { -5,  2,  6, -2, 13,  3,  5,-12,-11, 16,  6, 10, -5,  0, -3,  6,
+       5, -5, -5, 10, 12, 10, 11, -7,  8,-14,  2,-15, 13,-14, -8, -3 },
+    {  5,  6, -7, -5,  5,  2,  9,  5,  0, -1, -4,  2,  8,  0,  3,  5,
+     -12,  3, -3, -6,  2, -1, -5, 14, 11,-20,-21,-25, 24, -1,-10,  6 },
+    { -5,  5, -2,  9,  4, -4, -1, -6, 11, -6,  5,  0,  2, -3,  6, -1,
+     -17,-18, -4,-13,  9, -1,  9, -7, -4, -8,  2, -3, 12,-31,-18,  5 },
+    { -7,-11,  6, -8,  4, -3,-12,  0, -1, -6, -3,  0,  5,  9,  7,  2,
+       1, -8, -6,  8,  2, -5,  7, -1, 16,-10, 16,-12, 18, -1,-25,-12 },
+    {  3,-12,  1,  2, -2,-18, -8,-15,-10, -9,  2, -7, 11,-11,  2, -1,
+      -1, -1, -9, -6,  3,-14, -2, -1,  2,-13, -7, -9, 19, -5,-17,  2 },
+    {  7,  1, -8,  7, 17,-13,-10,  5,  7,  1, -6,  4,  9, -4,  0,  3,
+       8,  1,-14, -9,  4,  7, -9,  0,  6, -5,-12, -2, 25, -2,-19,  1 },
+    {  7, -3,  6, -3,  1,  6, -7,  0, 10,  0,  4, -5,-17, -4,  4, -1,
+       0, -3, -7, 19, 24, -1, 21,  8, 10,  9,  8, -1, 23, -2,-18, -2 },
+    {  3, -3,  0,  5,  8, -2, -9,  2,  9,  6, 19,  8,  2,  6, -9, -2,
+      -4, -3, -8,  7, -7, -8,  5,  4, 26, -6,  7, 18, 24,  0,-13,  4 },
+    {  0,-13,-11, -1,  3, -9,  5,  4, -7,  3,  0,  2, -1,  4, -5,  2,
+       9, -2,-11, 15,  1,-21,  1, -1,  0,  4,-14, -4, 24,-16,-13,  1 },
+    {  1, -9, -8,  0,  0, -4, 11, -1, 14, 16,  0, 17, -2, -9,-12,  0,
+      -1,-14, -9,-14,  0, -2, 19,  4,  6,  4,  4,-11,  8,-17,-19, -5 },
+    { -3,  1,  2, 12, -4,-18, -1, -4, -7, 14, -3,  2,  0, -7, -8, 12,
+      -5, -9, 14, 12, -9, -2,  4, -6,  4, 18, -1,-25, 22,  2,-23, -5 },
+    { -2,  0,  0,  0,  1,  3,  5, -1,  5, -2, -2,  2, -3,  0,  1,  2,
+       0, -1,  2, -1, -9, -6, -7, -4, -2,  4, -7, -5, 64, -3,-25,  4 },
+    { 12, -2, -3,  0,  8, -9, 13, -7,  6, -3,-12, 12, 15, -9, -4,  2,
+       9, -4,-12,  3, 14,  1,  7,-15, 15,  0, -6,-12,  0, -3,-20,  6 },
+    {  2, -1, -4,  5,  9,  6, -7,  2, -2, -7, -2,  0, -1,-18, -4, -6,
+     -15, -5, 11,  5,-10, -1,  2,  7, 12,-19, -7,  8, 21, -4,-15,  4 },
+    {  4,  2,  5,  5, -5,  1,  3,  2, -8, 13,  0, -5, -2,-14,-11,  6,
+       2, 17,  8,-13, 26, -2,  5,-15, -4,-14, 12, -9, 13,-21,-23, -4 },
+    {  2, -3, -2, -3,  3, -2,  6,  9, -9, 13,  4,  2, 12, -3, -3,  1,
+     -17,-22, -3,  4,  3, -2,  1, -9,  1, -6, 11,-13, 14,  0,-15,  6 },
+    {-16, -4, 17, -2,-20,-11, 11, 10,  5, -8, 16,  2,-17,-14, 11, 11,
+      -6,-11, -7, 12, 12,-10, -6,  5,  8, -4, -2, -5, 28,  3,-13,  4 },
+    {  0, -3,  3, -7,  6,  8,-12, 20,-19, 18,-11, 10, -5,  0, -9, 11,
+       3,  0, -2,  9, -7, -5, 18,  3, -2,-16,  1,  6, 12, -7,-16,  1 },
+    {  4,  1,  5, -5, 15,  2, -8,  3,  5,-11, 15, -3,  8, -8, -1,  7,
+       4,  7, -2,  6, -9,  5, 12,  2, 33, -2, -6,-18,  4,  0,-18, 11 },
+    {  3, -1,  1, -1,  0,  1,  4, -1, -5,  0,  1,  0,  4,  2, -1,  4,
+      -3,  2,  0, -2,  4,  6, -1,  6, 42, 19, -4,-37, 19,  1,-15, -4 },
+    {  2,  0, -5,  0, 10,  0,  0, -5,  3,  0,  0, -3, -3,  0,  2, -4,
+     -10,  2, -6,  4,  4,  1, 27, -7, 17,-34,  5, -9, 15,-16, -7, -5 },
+    { -2,  7,  7, -2,  9, -2,-15, 11, 11,  7,  5,  1, 15,  1, -9, 31,
+       2,-15,  2,  4,  3,  4, -1, -8,  2, -7,  6,-17, 11,-14,-11,  2 },
+    {  1,  1,-11,  9,  9, -6,-14,-11,-10,  8, -3, 11, 16, -9, -8,-13,
+      -8,  9,  0,  6,  6, -2, 13, -8, -2,  3, 13, -3, 10, -6,-17,  4 },
+    { 14,  5,  4, -6,-12, 10, -7,  8, 21, -8,-30, 15, -2,  1, 11, -9,
+      -5,  1,  0, -1, -1, -6, -2,  3, -5,  7,  9,  5, -5,  2,  0,  1 },
+    { -1,  2, 20,-17,-15,  3,  3,  7, 11,-17,-13, -6, -3, 18, 17,-15,
+      -4, -4, -5, 22, 14,-14, -2,-10, -7, 11,  8, -7, -3,  0, -7, 11 },
+    {  7,-11, -7, -8,-14, 22,  5,  2,  6, 13,-12, -2, 10,  3,  0,-21,
+      -4, 20,  3, 10, 21,-10,-12,  8, 11,  2, -5,  2,  1,  3, -1, 15 },
+    { -1, -2, -1, -2,-13,  8, -4,  0,  7, -2,-17,  8, 18,  5,  3,  8,
+      -8, -2,  3, -4, 14,-18,-13, 14, 15,-13, -1, -2,  4, 11,  1, 12 },
+    { 13, -6, -4,-16,-17, 16, 21, -2,  5,-11, -9, 19, 21,-17, -3,-17,
+       3, 12,  8,-12, -6,  1, -7,  9,  9, -7, -5, -1, -3,  5, -6, -4 },
+    { 11,  5, 12,-20, -6, 10,  4, 12,  8, -5,-10, 15, 13, 14, 10,-15,
+     -13,  1,  6, 14, 15,-17,-13,  4, -5, 10,  7, -6, -8, -3, -4, 12 },
+    { 25, -1,  7, -5, -7, 11,  1, 17, 13,-15,-14, -4,  5,  3,  8, -3,
+      -2,  2,  0,  6, 16,-12, -6, -4,  4, -3,  7,-10, -3, -7,-13,  7 },
+    { -8, 10, -3,-13,  5,  2,  4,  9,  9,-17,-13,  2, 11,  1,  6, -4,
+       8,-10,  4,  1, 19,-15, -4, 12, 31,  7, -5,-17, -4,  9, -2,  7 },
+    { 14, -6, -6, -6,-14, 13, 17, -5,  4,-14, -9,  7,  7, -9,  3,-16,
+     -15, 11, 11,  6,  4,-11,-19,  3,  5,  8, 13,-14,-14,  3, -4, 12 },
+    { -2, -4, 10, -4, -7, -1, 27,  5,  2,-16,-18,  4, 12, -2, -3, -2,
+      -1,  1, -8,-12,  3, -4,  8, 15,  2,  4,  9,-13,-14,  9, -7,  5 },
+    {  4,  2,-10, -5, -7,  2,  1,  4, -1, -6,-15,  6,  1, 10,  5,-10,
+      -9, -1, 13, -3,  5,-21,-11,  8,  8,  5, 27,-21,-18, -5, -1, 15 },
+    { 11,  1,-16, -8,-11,  0,  5, -8,-12,-13,-17, 22,  4, -6, -1,-18,
+     -10,  0, 19,  2, -2, -8, -7, -3,  2, -2, -9,-17, -5,  4,  4, 10 },
+    {  8, -6,-19, -5, -4, 12, 14, 15, 10, -9, -1, -9, 19, 12,  0, -1,
+       2,  4,  7,  9, 16,-16,-14,  9, -4,  3,  1,  0, -2, 10, -1, -1 },
+    { 12, -8, 12, -9,  0, 25,  7,  9,  2,-31, -9, -4, 15,  4, -5,  1,
+     -10, 11,  8, 10,  0, -6,  5, 11, -1, -6,  4,-10, -9,  6,  4,  5 },
+    { 14,  6,-17, -2, 17, 12, -9,  2,  0,-25,-14,  5, 20, 14,  8,-20,
+       5,  2, -2, -3,  9,-13, -3, -1, -6,  3,  7, -6,  0,  2,  3,  1 },
+    {  8,  4,-15, -3, 10, 18, -4, 13,  8,-22,-10,  9, 19,-15,  7, -5,
+     -13, 12, -4,  9,  2, -9, -6,  0,  2,  1, -9, -6,  6,  1, -1, 11 },
+    {  4,  1,  4, -5,-10, 18,  7,  2, -4, -9,-11,  0, 32, -7,  4,-16,
+      -1,  0,  6,  3,  6, -3,-14, 16,  9, -2,  7, -1,  0, -5,  5, -3 },
+    { -3,  2,  3, -8, -6,  4,  6,  2,  4,-12,-15,  2,  8,  8,  9, -3,
+     -18,  6, 34, 11, 12,-15, -1,  2,  9,  2, -4, -4,  2,  4,  2, -3 },
+    { 18, -6,-12, -8, -1, 15, 20, -4, -1,-11, -5,  6,  6,-11,-15, -7,
+       3,  7, 10,  2,  8,-10, -5,  8, 15, -5,  5,-17,-13, 13, 11,  7 },
+    {  8, -4, -6, -1,-14, -3,  6, -2,  1, -5, -1, 10, 10,-15,  5,  0,
+     -10, -4, -3,  7, -4,-19,-15, 27, 11, 18,  3,-19, -2,  6,  0, 12 },
+    { 12,  0, -5,  0,  4, -5,  1,  5, 10, -7,-11, 21, 29,  1, -2,  1,
+      -4,-11, -1, 13, 11,-20, -1,  4,  4,  4, -5,  6,-13, -2, 11,  9 },
+    {  2, -7, -7, -3,-10, -1, 20, 12,  1,-19,-19, -1,  5,  4, -7,-25,
+      14,  1, -3,  2, 12, -4, -3, -3, -2,  6,  1,  0,  3,  2,  5, -1 },
+    { 12, -8,  3,-12,-10, 10, 13,  0, 23,-14,-18, 10,  0, 15,  3,-12,
+      -3, -5,  5, -4,  2,-14,-10,  8,  2,  9, -1,-11, -3,  5, 13,  2 },
+    {  9, -6,  7, -7,-30, 17,  6, 13,  1,-14,  0, -1,  6, -9,  8,  3,
+      -4,  0, -1, -7, -5,-13,-19, -3, -4,  4, -6, -2,-13,  1, -2,  3 },
+    { 10,  1,  3,-18,-26, 17,  4,-16,  4, -3,-13, -4, -6,-11, -4,-21,
+       7,  8,  2,  5, 13, -6,  1,  5,  8,  7,  9, -6, -6,  1, -1,  2 },
+    { -3, -1,  0, -2, -2,  0, -1,  3,  4,-14, -8, -9, 13,  2, 50,-23,
+      -8,  8,  7, 11, 16,  3, -7,  0, -2,  6,  5, -1,  1, -2,  4,  3 },
+    {  1,  3,  1,  1, -6,  3,  6,  6,  2, -2, -3, 10,  2, -8, -5, -5,
+       5,  4,  4, -2, 10, -8,-40, -1, 21,  8,  3, -4, -1, 13,  4,  7 },
+    {  2,  0, -4, -8,  5,  2,  7, -5,  5, -8, -4, -1, 12,  2, 12,-13,
+      -9,  0,  1,-12,  9,-43,  1, -5, 12,  1,  3,  6,  1, -1,  3, -2 },
+    {  6, -2, -1,  1,  0,  4,  8, 14,  4, -7,-23, -5, 23,-17, -6,-15,
+      -8,  7, 10, -1,  7,-16,  4, -6,  2,  3, -3, -3, -1,  8, -1,  4 },
+    { 10,  4, -4,  1,  7, -3,  2, 11,  4, -6, -3,  8,  5,  4,  1,-45,
+      -6, -4,  4,  2,  1,-14,-10,  1,  1,  6,  2, -8, -1, -3,  3,  3 },
+    {  1, -1,  2, -3, -8,  9,  3,  3, -2, -5, -8,  8,  7, -7, -4, -6,
+       5, -9, 11, -2, 46, -5, -1,  9, -2,  0,  3, -5, -3, -5,  7,  0 },
+    { -4,  1, -2, -1,-11, 11,  8, -3, -2,-10,  0,  4,  9,  9,-17,-17,
+     -34, -4, -5, -7, -3,-12, -3, 11, 18,  3, -2, -5,-18, -5, -3,  6 },
+    {  7, -5, -3,  1, -4, -3, -5, -1,  2,  5, -2,  3,-10, 12,-18, -5,
+     -10, 12, -9,  4, -6,  2,  0, 16,-17, 15, 14,-12,-10, -2, -9, -1 },
+    {  4, -5, -3, -5, -3, -1,  7, 18, -7, 12,  3,  5, -8, -4,-20,  1,
+     -25,  1, -8, 13,-10,  8,-19, -1, -8, 10,  6, -9, -1,  0, 12,  4 },
+    { -4,  5,  0, -1,  2,  5, -8, -2, -6,  4, -8,  9,  3,  2, -7,  4,
+     -25, 13,-23, 10, 14, 15,-11,  3,-18,  4, 16, -4,  1,-10,-10,  3 },
+    {  5, -3, -1, -3,  4,  1, -3, -4, -5,  1,-12, 14, -7, 11,-15,  6,
+      -6, 24, -4, 13, -1, 15,-13,  8,  3,  7, -5,  2,  2,  0,  3, -7 },
+    { -3,  1,  0,  8,  6, -1,  6,  5, -5, -2,-12,  4,  0, -2, -3,  5,
+      -6,  0, -8,  9,-10,  4,-28, 12,-20, 11,-13,  7,-18,  1,-11,  1 },
+    {  1, -4,-15,  5,  0,-13, -5, 13,-11,  4, -4, -5,  5,-14,-16,  0,
+     -14,  5,-20, 12, 10, -7, -5,  6,  6, 22,  6, -4, -2,  3,  8, 11 },
+    { 13,-11, -2, 16, 16, -7,  0, 20, -7, -1,  0,  5, -9, 12, -2, -5,
+     -22,  5,-10, 12, -6, 11,  9, 21, -8, 15,  4,  0, -8, -4, -4, 10 },
+    { 18, -4,-13,  0,  1,-15, -1, -3,  2, 10, -1,  6,  1, -4,-20, -5,
+      -8,  6, -8, 17, -5,  5,-10,  8,-22,  6, -5, -2,  8,-17,  8,  2 },
+    {  1, -2, -9,  6,-31, -8, -8,  8,  0,  5, -9, -4,  2,  3,-12, 11,
+     -18, 10, -5,  3,-11, 13, -6, 11, -3, 12, -7,  3, -9, -1,  2, 11 },
+    { -9, -6, 21, -8,-15,  4,-11, 12,-11, 17, -1,  2, -6,  0,-15, 13,
+     -12, 19,  0,  2, -6, -3, -9, 10,  3, 17, -2,  5,-10, -3,  0,  1 },
+    {  4, -6,  5,-10,  1, -5,  1,  0,  0,  0,  2,  7, -2,  2, -2,  0,
+      -4,  3, -4,  1,-12,  6,-49, 16,-10, 13,  0, -2,  8,  6,  1,  8 },
+    {  5, -8, -7,  9, 13, -5,  7,  0, 10, 11, -4, -3, -1, 13,-14,  6,
+     -15, -6,-14, 16, 15,  1,-18, -4,-20, 20, -7, -1, -9, -2,-10, 10 },
+    {-12,  4,  0, 10,  0,  3,  8,  4,-27, -1, -2, 19, -4,  2,-13,  3,
+       1,  9,-12,  1,-22, 19, -5,  4, -9, 12,  2, -9, -8, 11, -3,  7 },
+    {  4, -5, 11, -6, 17,-17,  5, -4, -2, -6,  1, -5,  2,  4,-14,  6,
+     -20, 19,-20, 12,-21,  5,-14, 13, -2, 11,  4, -3,  0,-10, -4, -2 },
+    { -2, -1, -3,  8, -9, -7,-22, -3,-24, 13, -2, 10,-15,  5, -9,  4,
+      -7,  0, -5, 15, -8, 11,-13,  6, -4, 19, -8, 12, -4,  6,  9,  7 },
+    {  2, -3,  2, -1,  0,  3,  1,  2,  1, -4, -2, -3,  1,  5,-12,  6,
+     -16, 14,-23, 10,-14, 17,-15, 16, -2,  9,-25,  9,-10, 16,  4,  9 },
+    { -3,  7, -8, -3,  2,  2, -4, -8, -9, 10,  3,-11, 25,-10,-28, 27,
+      -9,  7,-13,  9, -2,  4,-12, -8,-14,  6,  7,-10,  3,  3, -3,  5 },
+    { -8, -3,  1,-10,  8, -3, -9, -4, 13,  7,  2,  4,-10,  4,  3,  7,
+     -18,  2,-22, 15,  4, 20, -7,  5, -6, 13, -1,  4, -7, -6,  6, 13 },
+    { -2,  3,  0,  2, -4, -2,  0,  0,  1,  2, -2, -5,  0,  1, -4,  0,
+      -2, -3,  1,  2, -1,  2, -8, -1,-24, 68, -3,  8,  3,  3, -1, -1 },
+    {-15, -2, -9, -7, -1,  8,-14,  8,  3,  6,  0, -1, -8,  8,-23,  2,
+     -14, 17,-15,  8, -4,  7,-18,  0, -8, -3, -1, -4,-10,  4, -1,  4 },
+    {  8,  0,  2, -7,  0,  5,  1,  3,-11,  4, -8, 14,  3, 20,  1, 26,
+     -11, 13,-13, 20, -2,  0, -8,  2, -6,  6, -1,  9,  3, -6, -3, 10 },
+    {  5,  0, -1, -7, 10,  1, -3,  5,  4,  7, -5, -1, -3, -1, 12, -3,
+     -15,  7, -9, 22,-19,  8, -9,  4,-23, 13,-14,  6, -6,-14, -4,  7 },
+    { 14, -5, -8,-10, 25,  3,-23, -7,-28,  0, -1, -9,  4,  1,-13, 20,
+      -8, 10,-16,  8, 12,-13,-21,  5,-13, 11, -2,  1, 12, -7,  2,-10 },
+    { -5, -4,  9,  5, -6, 35, -7,  8, 15,  2, -1, -9, -6,  2,-18,  7,
+     -15,  6, -3,  2,  8, 12,-30,  7, -4, 20,  2,  6, 13, -6, -4,  0 },
+    {  1,  8, -9,  9, -5, 12, -9, 16, -9, 16,-17, 14,-13, 15,-18, 14,
+     -15, 17,-12, 14,-13,  7,-16, 13, -9,  5,-11, 10, -9,  6,-12, 13 },
+    {-10, -4,  5,  3,  1,  6,  8,-14, -5, 15,  7,  4,  8,  7,-22,  8,
+      -7, -8,-15, 26,  1, 13, -3, 17, -5,  9, -2,  4, -6,  3, -8,  9 },
+    {  8, -3,  2,  3,  3,  1, -2, -1,-11,  8, -4,  0, -6, -5, -1, 13,
+     -37,  9,  1, -6,-10, -2,-10, 11,  8, 13, -3, -2, -6,  8, -4, 13 },
+    {  3,  2, -3, -4, -4,  7, -8,  9, -8,  9,-20, 12,-19, 15,-18, 17,
+     -15,  7, -1, 20,-11,  6, -6,  3,  1,  9,  2,-14, -2, -2,  2,  1 },
+    { -7,  1, -1, -3, -6,  4,  4, -3,  3, -1,  5, -4,  3,  2, -1,  9,
+     -59,  5, -4, 30,  3,  3, -2, -3, -1,  2,  2,  1, -1, -1, -2,  1 },
+    {  0, -3,  2,  0, -1, -8,  0,  2, -3,  4, -4,  1, 10,  6, -6,  8,
+      -7,  4, 10, 11,-41, 27,-20,  3, -3,  8,  1, 11, -5, -8,  0,  4 },
+    {  5,  1,  4, -2,  1,  2, -1,  6, -7,  2, 11,  4,  0,  0, -8,  7,
+     -10,  0,  0,  8,  2, 10, -1,  1, -2, 44, -2,-21,-12, -3, -1,  2 },
+    { -4,  4, -2, -2,  6, -8,  2,  1,-10, 14,  8,  6,  5,  1, -2,  4,
+     -13,  4,  2,  5, 10, -2,-21, 32, -3, 18,  9, -6, -9, -9, 10,  2 },
+    {  9,-16, -6, -2,  1,  4, 22,  2, -2,  1, -3, -2, -9,  3, 16, 19,
+     -24, -6, -6, -5, -8, -7,  8, -7, -1,-12,  5, -3,  0,  4,  2, -3 },
+    { 10,  3,-16, -4, -1, 13,  4,  4,  1, -3,  1, -6,-14, 18,  3,  8,
+      -8,-28,-16,  4,  4,  2, 12,  7,  9, -4, -4,  5, -1, -1,  2,  2 },
+    { -5,-13,-22, -3, -8, 21, -2, -9, 21, -4, -9,  5, -8, 15,  5,  1,
+      -5, -9, -7, -2, -5, -5, -1, -5, -5, -5,  3, 10, -4,  0, -7, -2 },
+    {  5,-10,-18,  2, 20,  4, 13,-10,  8,-15,-11, -3, -1, 16, 10,  9,
+      -8,  6,  7, -5,  6, 11,  5, 17, -4,  7,-11,  5, -3, -6,  2,  1 },
+    {  3, -5,-19,  1,  1, -3, -2,-25,-11,-17,  0,-13, -4, 10, 10,  2,
+      -5,  4,  0,  3, -3, -5,-10, -2, 13,-22,  0,  3,-11, -5,  7, -1 },
+    { 12,-14,-29,  6, -1, 10,  7,-17,-12, 14,  3,  9, -9,  9,  7,  6,
+      -3,-13,  0,  5,  3, -1, -6, -1,  0,  2,  4,-12, -5, -1,  2, 11 },
+    { 12,-15, -7, -2,-12, 17, 20,-16, -2,-12, -6, 15, -6, 12, 11,  9,
+       7, -6,  7, -4,-19,  6,  2,  2,  3,-11,-10, -4, -5, -3,  3,  2 },
+    { 11,-22, -6,  0,  8, 18,  3,-11, -4, -7,-15,-17,-12,  6, 16,  4,
+      -9,  4, -5,  3,  6,-16, 10, -7, -7, -3,  5,  0,  1,-15, -4,  5 },
+    { 12,-22,-16,  5, -6,  8, 12, -4, -9,-17,-11,  3,  5,  8,-17,  0,
+      11, -4,-13, -6,  2, -1, -1,  3,  3,-11,-12, -1,  1,  1, 12, -2 },
+    {  8,-10,-33, -5, -3, -6,  1, -7, -8, -4, -6, -1,  5, -4, -6,-12,
+     -16, -8, 11,  8,-14,  7, 12, 11,  4,-14, -3,  6, -7, -5, -3,  3 },
+    {  0, -8, -7,  2, -4, 24,  2, -9,-11, -3, -7, 11,-12, 17,  1, -1,
+       3, -5, -7, 12,  4, 11,  0,  3,  2,-18, -3,  4,  7, -6,  3, 15 },
+    { 10,-15,-16, -2, -4, -9,  7,-15, -6,  2,-16, 13, -8,  7, 19,-21,
+      -4,-12, -9, -3, -3,  6, 11, -3, -1,-19,  3, -7, -9, -4,  3, -6 },
+    { -5,-10,-21,  0, -3, -7, 18,-21, 15, -5,-12, -4,-13,  2,  6, -9,
+      -9,-11, -4, 13, -3,  6,  4, -1,  7, -9, -4,  9,  5,  2,  6,  3 },
+    { 15, -1,-27, -2, 10,  3,  7, -8,  9, -2,  7,  1, -2, -5, 18,  9,
+     -11,-17, -2,  7, -9, 11, 10,  0, -8,  6,-16, -3,  2, -7,  3, 11 },
+    {  4, -9,-39, 19,  6,-13, 13, -5, -5,-15, -2,  9,  0,  4, 14,  6,
+     -10, -4, -5,  2, -4, -2,  5,-11,  3,  3, -2, -2, -7,  9,  7,-10 },
+    {  5,-11, -8, 10, -2, 12, 16,  0, 12, -2, -6,  8, 14,  8,  7,  1,
+      18,-30,  4, 10, -4, -6,  2,-11,  9,-10, -8,  5,  0,  0, -7,  6 },
+    { -1,-16,-10, 11,  0, 13, 12, -4, -4, -5,-21, 12,  4, 13, 14, -7,
+       6,-16,-13,  8,  2,  9, 15,-12,  1, -9,-22, 10, -9,  9,  9, -7 },
+    {  4,-12,-27,  1, -2, 11, 15,  3, 14,-14, -9,  0, -9, 16, 22, 10,
+      16,-10,  5, -5, -9,  1,  1,  6,  6, -4,  2,-17, -5, -6,-15, -1 },
+    {  7,-12,-17,  1, -9,  5, 20, -7,  3, 23, -8, -8, -8, -1, 13, 17,
+      -7,-13,  4, -4,  7, 14,  8, 11, -3, -3,  4,  0,  4,  6, -1, -9 },
+    {  7,-15,-15, -4, 10, 12,  3,-13,  6, 14,  9, -8,-15, 14, 23, -5,
+     -10, -5,  1, 15,-10, -7,  1,  9,  4,-13,-10, 10,  7, -3,  2,  3 },
+    {  4,-10,-14,  0,  3,  4,  0, -9, -3, -4,-11,  2,-17,  8,  2, 15,
+       6,-12,-12, 15, -5, 17, 18,  3, -3, -3, -4, -6, -8, 13,  4, 10 },
+    { -2,-18,-26, 10, -4, 10, 13,  4, -4,-16, -7,-17, -3,  5, -4,  2,
+     -15,-10, -1, -8, -7, -3,  2,  2,  8,-10, -7,  2,  2, -4,  4, -1 },
+    {  4,-19, -5, -1, -1, -6,  2, -8, 10,-16,-28, -6,  8, -1, 11, 28,
+       2,-10, -4,  6, -6,  6, 11, 15, -4, -2,  7,  3,  7, -7,  4,  1 },
+    { -3, -6,-10, -5, 13, 18, 10,-15, -5, -3,-13,  5,  1,  2, 18, -5,
+     -10,-10, -7,  4,  2,  1,  5,  4,  2,  5,  4,  8, -9,-17,  7,  7 },
+    { 20,-12, -2, -4,  5, 14,  7,-11, -1,-16, -6, -4,-11, 17, 14,  0,
+      -8,-10, -8, 10,  3,  5, 10,-16,  3, -8,-14, 10,  3,  9,  0,  3 },
+    { 12,-10,-36,  0,  7, 15,  2,-16,  2, -1,  0, -1,  5,  4,  5, -3,
+       1,-10,  5, -1,-15, -3,-12, 12,  2,  5, -1,  5,  6, -3, -2,  2 },
+    { 17,-15,-31, 23, -4, 15, -2, -3,  6, -7, -5,  1,-12,  4,  6,  8,
+     -10,  8,  3,  5, -4,  1,  5,  3, -1, -4, -3,  1, 10, -4, -2, -2 },
+    {  6,-18, -5, 12, 10, 12, 14,-11, 15,  2, -9, -6, -5, -2, -9,  4,
+      -5,-28, -4, 14,  0,-16,  9, 14, -1,  3, -4, -4,  2,  1,  0,  4 },
+    { -5,-14,-31,  8, 16,  7, 13,-13,  5,  6,-16, 10, -5,  2, -2,  2,
+      14, -5,  8, -5,  7,-16,  6,-13, -5,  0, -5,  8, -3, -1,  4,  3 },
+    {  1, -2, -1,  0,  6,  5,  2, -4, -3, -1,  0,  1,  4,  2, 43, 28,
+     -12,-35, -2, -2, -7, -1,  0,  2, -1, -2, -2,  1, -4,  0, -2,  3 },
+    {  2, -9,-22, 12,  3,  3, -7, -4,-19,-22,-14, -4, -1, 21,  9, -3,
+     -15,-16,-13,  1,-11,  4, -9,  1, -7, -1, -1,  0, -2,  9,-13, -3 },
+    { -1, -3,-23,  0,  2, 12,  3, -9, -4,  7,  3,  9,-10,  1, 27, 28,
+       0,  9,-15, -2, -2,  1,  6,  8, -8,  7, -3, 20,  0,  0, -1, -6 },
+    { -1, 11,  8, -2,  1,  5, -6, -1,  4,  2, -4,  0, -1, -5,  4, -6,
+     -10,-12, 19,  1, -7,  9, -8, -9,-16,-11, -2, 12, 14,  4,  4, 34 },
+    { 17,  7, -6,  1,  4,-10, -5,  4,-11,  3,-18,  4, 14,-13, -3,  1,
+       0,  0,-11,  0,  7,-17, -4,  4,-11, -6, -8, 18,  0,  0,  0, 26 },
+    { -6, -7, -1, -1, 11, -8,  1,  3,  2, 11, -6, -6, 10, -3,  1, -3,
+       7,  4,-12, -8,  0, -9,  8,-22, -5,  0, -6, 22, -2, 11,-13, 24 },
+    { -3,  4,  0,  3,  9, 10, -1,  3, -9,-12,  1, -5, 18,  0, -3,  8,
+      25, 15, -8,  2,  2, -2,  4,  8,  9, -1, -5, 10, -3,  1, -1, 23 },
+    { -5,  2, -9, -1, -3,  0,  3, -1,-10, -4,  0,-13, 16,  9, -1,-14,
+       2,  6, -2, -6, -5, -2, -7,  7,  5,  3, 11, -2,-14,  0, -9, 30 },
+    {  4,  6,  6,  5, -3, -1,  4,  5, 10,  0,  5, -4,  7,-11, 14, 14,
+       7, 34, -9,  0,-10, 22, -7, -1,  7, -9,  2, -8,  0, -7, -5, 29 },
+    { -4,  3, -1, -4, -3,  5,  1, -4,  0,  2,  4,  2,  1, -1,-10,  1,
+       6, -6, -4,  1,  4, -3, -3, -5,  0,  3,  7,-12,  0, -2,-10, 55 },
+    {  5,  9, -1,  0,  4,  9,-21, -9,  4,  2,  6, -7, 11, -7,  1, -5,
+       0, -4,  2, -3,-13, -8,  0, -9, -4,  2, 16, -2,-15, -7,-11, 31 },
+    {  8,  2, -1,  0,  3, -5, -5,  5,  1, -1, -9,  1,  0, -6, -2, -1,
+       5,  2,  0,  0, 12, 20,-19,  1,  8,-12,-11,  0,  6, -5,  2, 31 },
+    { -1, -1, -2,  1, -1,  3, -9, -5,  8, -2,  5, -1,  0, -2,  4, -2,
+      -3,-12,  0, -2,  3,  0,  9,  4, -1, 21, -8,  3, -4,  9, -6, 30 },
+    { -4,  0, -7, 17, 10,-12, -2,-10,-12, -3, 10,  0, 11, -4,-13, -3,
+       5,  6, 10,  7, -8,  0, -7,-13,  1,  0, -2,  7,-12,  4, -3, 24 },
+    {-13,  9,  4, -2,  2, -4,-14, -1, -3, -5,-10,  4, 13, -2,  5, 13,
+       8,  3, -2,  1,  5, -6,  7,-18,-10,  1, -1,  5,  4,  1,  0, 25 },
+    { -5, -1, 18, 12,  8,  8,-16, -1,  1,  1,  1, -4, -5,  3,  3,  4,
+       4,-11,-12,-16, -6,  2, 12,-13,  0,  9,  7,  9, -9,  0,-10, 24 },
+    { -4,  1, -3,  0,  2, -4,  4,  1,  5,  0, -3,  2, -3, -2,  2, -1,
+       1,  4, -1, -2, -2,  1, -1, -1, -4, -1, -4, -2, -6,  6, 12, 69 },
+    {  8,  5, 11,  0,-15, -4, 13,  6,  0, -4,  9,  1, -5, -3, 15,  0,
+       1,  6, -5,  0,  1,  6,  5,  8,  0,  7,  1, -1, -4,-11, -9, 41 },
+    { -4, -9, 32, -6,  0,  7, -4,  6, -6,  1, -6, -2,  4, -8, -5, -3,
+     -16, -1, -2, -6,  1, 15,  0, 21,  3, -3, -4,  3,-12, 16,  2, 27 },
+    { -6, -5,  1, -9, -5,  3,  7, -3,  5,  5, 14, 13, 20, -7, -1, 12,
+      -1, 10,-11,-11, -7, -4,-14,  7,-14, 13, 22, 18, -1,  0, 14, 28 },
+    { -8,  3, -2,  0,  5,  6, -1, -4,  1,  3, -7,  3,  1,-15,  4, -9,
+      22,-10, -9, -4,  1,  8, -4,  9,-15,  2, -6, -4,-16, 12,-10, 23 },
+    {  0,  0,  2,  0, -1,  3, -3, -1,  3, -5,  7,  1,  5, -5, -8,  1,
+      13,-15, -5, -7, 12, -6, -2,  3, 10, -5, -8, 17, -5,-11,-14, 23 },
+    { -7, -4,  6, -4,  5, -6, -5,  2, -4, 11,  9, -4,  2, -2, -4,  6,
+      15,  3, -3, 18,-15, -2, -6,  3,  3,-20, 17, 11, -4,  2,  3, 29 },
+    {  6,  1, -6,  2,  3,  0,  0, -3,  3,  3, -1,  3, -4, -6, -6, -7,
+      -3, -2, -7, -2, -4,  5,  3, -5,-20,-13, -4, 10,-14,-29, 14, 37 },
+    {  3,  4,  3, -6, -4,  5,  0,  3,  2,  3,  0, -2,  4,  0, -3, -5,
+      -4,  4, -4,  4,  4,  3,  1, -4, -4, -9,-14, 20,-30,  3,-18, 33 },
+    {  0,  2,  5, -2, -4, -2, -1,  2, -6, -3, -2, -2,  2, -5, -1,  4,
+       3,  2, -3,  0, -1, -1,-10, -7,  2, -4,-18,  2,-37, -1, 12, 40 },
+    { -7,  2, -1,  0, -2,  4, -8,  1, -4, 12,  7,  4, 15, -7,  1, -9,
+      18,  0, 12,-17, -3, -1,  0,  0,  0,  2, -6,  0, -4, -3, -1, 26 },
+    { -6,  4,  8, -5, -6, -2,  2, -1,  1, -1,-15,  8,  7, -1,-17, -4,
+       1,  5,  6,-11, -6, 14, 17, -5,-15, 11,  8,  0, -3,-15, -6, 28 },
+    { -1,  0,  0,  0,  1,  0, -1,  0,  1,  3,  2, -2,  3, -1, -1,  2,
+       2, -1, -1, -7,  1,  2, -9,  0, -1, -4,-18,  7,-10, 49,-13, 32 },
+    { -1, -3,  4,  1,  2, -5,  1, -7, -1,  5, -9,  4,  4, 25,  1, -1,
+       2, -5,  2, -7, 17, -2, 10, -5,  0,  2,-15,  3, -9,  7, -9, 30 },
+    { -5, -1,  0,  2,  1, -1,  2,  5,-33,  3, -5, 14, 11,  7,  5, -3,
+       2, -8, -4, -2, -7, -6,  4, -8, -1, -8,  2, -2, -8, -1, -4, 27 },
+    { -1,  0, -1, -2,  1, -1, -2, -1,  2,  0,  1,  2,  2,  4,  1,  3,
+       4,  2,  1, -7, -4,  1, -3, -4,-35,-25, 17, 10, -3,-26, -7, 32 },
+    { -5,  1,  6, -2,  6,  6, -9,  3, -1, -4,  5, -4, -2, -2, -9,  2,
+      -5,  2,  2,  4,  3,  5, -5,-16,-31,-12,-11,  2,-19, 20, -2, 21 },
+    { -5,  2,  7, -7, -7,  5, -7,  2,  0,  0, -4,  3, -1,  0, -1, -2,
+       0, -3,  5,-11, -8, -3, -7, -7, 28,-11, -7,  0,-16,-11, -4, 29 },
+    {  2,  1, -3, -2, -1,  3,  4,  0,  1,  0, -1, -5,  4, -5,-12,  2,
+      -2, -5,-22, -2, -1, 11,  8, -7,-12,  0,-34,  6, -5, 11, -8, 19 },
+    { -1, -3,  5, 11, 18, -2, -2, -5, -2,  4, -1,  8,  5, -6,  1, -1,
+       2,  8,  4, -5, -8, -2,  5,-18,  7, 12,  7, 19,-18,  2, -6,-13 },
+    {  9,  0,  0,  5,  4,  3, -6,  4,  1, -4,  5, -1, -4,  8,  8,  6,
+      -8, -6,  0,  6, -3,  3,  5, -3, 17, 31, 16, 10,-13,  0, -9,-19 },
+    { 12,-10,  2, -2, -2, -1, -3,  6,-12, -5, -2, 14,-16,  4, 12, 12,
+      17,  4,  7,-16,  7, -6, 11,  7,  7,  2,-25, 23,-24,  5, -7, -9 },
+    { 10,  4, 13, 10, 10,  3, -6,  3,  3,  2, -1, -6,  8,  4, 10,  0,
+       1,  2, -4,  2, -3, -8,  0, -1,  9,  9,-10, -3,-29,  1, -1,-27 },
+    {  2,  2,  0,  7,  9, -2,-10, -1, -1,  1, -9, -5,  8,  4,  1,  2,
+     -10,  1, 13, 12, -3, 15, -9,  2, -7,  1,-10, 23,-20,-18, -9,-15 },
+    { -3, -5, -1,  8,  0, -5, -1,  4,  7, -1, -7,  2, -8, -5, 11,  7,
+      -6,  3, -3, -9,  7,  9,-22,  1,  6, -4, 14, 27,-25,-14,  3, -5 },
+    {  1,  3,  8,  4,  7,  6, 12,-17,-15,  1, -8,-10,  7,-14, -8,  6,
+      -2, -2,-11,-11, -7, 13, -2, -2,  4,  5, -5, 13,-23, -6,-17, -8 },
+    { -5,  4,-14, -5, -4, -5,  6,  5, -8, -5, -2,-11, -7,-12,  3,-11,
+       2, -6,  4,-10, -5, -7, 14,  5, 23, 11,  7, 12,-16, -6, -4,-16 },
+    {  5,  6,  2,  5, -2, -5, -5, -6, -5,-19,-13, -1, -3,-13,  5,  0,
+       6, -2, -2, -6, -7, -7, -1, -9,  4, 14, 17,-12,-27,  3,  0, -1 },
+    {  7, -1,  9,-10,  8,  2, -7, -2,  5,  2, -3, -7,  3,  0,  6,  4,
+      12,  5, 11, 14,-13, -1,  8,  1, 13,  9, 12, 12,-18,-14,-11,-16 },
+    { -7, -5, -6, -5,  0, -1, -3,  2,  2,  1,  4,  9,  2,  3,  5, -2,
+       2,  1,  8,  0,  3,  0, -2,  2,  1,  7, 29,  0,-36, -5, -9,-21 },
+    { 14, -6, -9,  0, -1, -8, -8,-11,  2,  2, -9,-12, 12, -4,  5,  3,
+      -5, -9, 11, -1, -3, 12,-21, -3, 12,  5,  3, 11,-18,-15,  1, -2 },
+    { -1,  3, -9, -3,  7, -7,-18,  2,  4, 12,-10,  2,  8, -3,-14, 13,
+      17, -5,  5, -9, 13, -3, -7,-18, 17, -2,  5,  7,-20, -3, -6,-11 },
+    { -3,  3,  3, -1,  1, -6, -5,  1,  5, -3,-14, -6, -5, -8, 14, -6,
+       7, -1,  5,  1, 15, -1, -7, -4,  6,-11,  9, -2,-37, 16, -7, -3 },
+    { -1,  0,  6,  1, -3, -9,  0, 11, -8,  2, -2,  0,  5,  2, 12,-10,
+      10, 13,  2,  7, -6,  2,-10,-10, 21, -5,  5,  5,-12,-23,  3,-14 },
+    {  6,  0, -2,  1,  0,  1,  0, -4,  1,  1,  8, -2,  2, -5, -2,  1,
+       8, -4, -1, -1,  4, -1,  2,  6, 32,  1, -5,-20,-40, -4,-18,-14 },
+    {  2,  2, -7, -2,  4,  4, -1,  2,  0, -2, -4, -7,  3,  5,  0, -5,
+       1,  2, -6,  4, -1, -2, -1,-15,  8,  3,  9, 46, -7,-18,  6,-11 },
+    {  5,  5, 16, 21,  3,-11, -4, 11,-12,  2,  4,-12, -1, 11,  8,  1,
+      -4, 11,-11,-21,  1,  1,-11,  3, 13,  1,  5, 12,-25,  1, -3, -2 },
+    {  1,  6, -7,  4,  2,  3,  1, -5,  8,  9,-15,  3, -3,-14, 17,  4,
+      -8, 14, -2, -8, -4,  5,  8, -7,  8,  9,  7,  6,-29,-17,  8,  4 },
+    { -7, -7,  4,  0, 13,  1,  0,  4,  4,-16,-10, -7,  5,  9,-15,-10,
+     -10,  8, -4, -1,-11, -1,-10,-15,  3,  3, 14, 10,-19,  2,-18,-12 },
+    { -4,  0,  2,  0,  5, -2, -9,  0,  4, -4,  2, -1, -2,  2, -4,  9,
+       2, -6, -4, -2, -1, -3, -3, -1,  2,  5, -1, 11,-24,-44, -9,-15 },
+    { -1,-10,  6, 21, 11, 15, -7, 10,-14, -9, -8, -8,  4,  6, 19,  1,
+      -6,  1, -5,-17, -8,-10,  9,  5, 11, 18, -1, 10,-16, -7, -9, -8 },
+    {  3, -5,  0,  0, -2, -2, -6,  4, -4,  1, -1,  0,  7, -3,  4, -4,
+      -7,  7, 17,-20,  6,  4,  1, -6,-12, 31, 13, 19,-14,-10, -7, -2 },
+    { -2,  6,-10,  3,  9,  6,-14, 15,  2, -5,  2,-11,  9, -8,  4,  6,
+      20,-15, -3, -3, -1, 32,-21,  6,  1,  9, 11, 17,-19,  6, -1, -3 },
+    {  8, 10, -2,  0, -8,-16,  7,  7,  6, 10,  4,-14,  7, -6, 21, -7,
+      10,  5,  5,  0, -7,  2, -6,  0, -7, 11, -9, 15,-20, -7,-11,  2 },
+    {  0, -7,  5,  2,  0, -3, -6, -4, -2, -1, -4, -5,-13, -1, 27, -9,
+      -6,-11, -7,  1, 11, -4, -4,-14, -2, 11,  6, 10,-19, -6,-15,  2 },
+    {  0,  7, -1,  2, -7,-15, -2, -3, 13, -5, -5, 12,  3,  0,  5, -5,
+     -22,  2,  7, 22, 13,  0, -1,  2,  3,  2, -7,  7,-27, -4, -4,-12 },
+    { 11,  1,-16,  6,-15,  1,  3,  2,  0,  2, -3,  2,  5, -2, -5,  9,
+       5, -3,  3, -2,-11,  3,  9,  6,  9,  3, -1, 12,-41,  8, -6,  9 },
+    {  3, -7,  3,  2,  5,  5,  0, -1,  1,  3, -5, -2,-13,  7, -1, -2,
+      -2, -6,  4, -6,  0,  2, -2,  2,  4,  1, -4,  1,-47,-21,  7, -6 },
+    {  3, 16, -7, 13, -4, -2, 10, -3, -1, 18,-13,  7,-13, -4,  8,  4,
+       8,  9, -5, 13,  8, -5,  3, -6,  7, 18, -8, 10,-25, -3,-12,-12 },
+    {  1, -1, -1,  0,  2,  5, -5, -3,  0, -5, -1,  0, -4, -8, -2,  3,
+       2, -2,-17, -6, -4,  1, 33, -6,-20, -6,  8, 31,-26, -8, -1, -4 },
+    {  3, -3, -3,  5, -3, -2,  1,  7,  0,  3,  6,  3,  6, -2,  9, 15,
+     -10, -3,-15, -5, -3, -4, -6,-30, 17, -8, -2,  2,-20,  0, -8, -2 },
+    { -2, -1, -1, -1,  3, -5, -2, -3,  4, -2,  0,  5,  8, -3,  1, -4,
+       1,  1, -3,  4,  4,-14,  3, 11, -5,  3, -3,  7, -3, 13, 23,-16 },
+    {  2, -6,  1, -3,  5,  0, -6,-11, -7, -4, -1,  2, -7, -1, -1,  7,
+       1, -2,  6, 12, -6,  8,-13, 17, 25,-23,-19, -7,-12,  9, 16,-17 },
+    {  9,  4,  4,  4, -3, -1,  6, -2, -3,  0, 13, -4, -7, 14,  1, -7,
+       0, -5,  3,-19, -3,  5,  3,  9, -1,  9,-13, 13,-17,  4, 21,-26 },
+    {  0, -5,  0,  0, -4, -5,  2, -6, -4,  5, -7, 10,  0,  2,  0, -2,
+      -2,  0,  4, -6,  7, -2,  6,  5, -5,  2,-12,  1,-29, 29, 27, 12 },
+    {  9,-10,-22,  6, -1, -1,  9,-14,-12, -2,  1, -1, 10,-11,-16,  0,
+       3, 11, 13,-14, -9, -2, -1,  6,  4,-14,  0,-10, -2, 16, 17,-11 },
+    {  2,  0, -1, -2,  4,  3, -6, -2,  1, -1,  1,  3, -4,  1,  3, -4,
+      -1, -1,  4, -1,  1,  0,  1,  6, -5, -7,  2,  1,-47, -3, 50,-17 },
+    {  8, -4,-11, -7, 11, 11, 14, -7, 12, -7,  6,  2, 13, -6, -3, -2,
+     -14,  6,  6,  6,  0,  2, -1,  5,-20,  2, -1,  4, -5,  6, 21,-11 },
+    { -2, -9,  3,  0, -6,  7,  8, -8,  1, -3,  4,  1,  5, -2, -3, -7,
+       4,  7,-12, -9, -2, 10, -6, 13,  6,  5, 20,  2,-15,  9, 28, -7 },
+    {  0, -5, -6, -6, -6,  1, -6,  6, -2,  4,  8, -3, 12, -1, -4, -2,
+       6, 16,-14,  9,-14, -2, -8,-27, -3, 18, -1, -7, -3,  8, 23,-23 },
+    {  1,  4, -9, -1, -5, 10, -2,  1,-11,  1, -9,  4,  7, 14, -9, -2,
+      -3,  2, -5, -1, -6,-10, -7, 11, 20,  2,  3,-19,  3, 15, 30, -9 },
+    {  7,  2,-14, -4,  0, -2,  5,  2,  5, -2,  8, -3, -7,  6,  6,-11,
+     -14,  1, 10, -1, -7, -8,  1, 10,  3, -6,-15,-12,-17,  4, 30, -6 },
+    {  4,  2,  1, -2,  3,  0,  1,  0,  2,  0,  1,  6, -7,  0,  3,  4,
+       4, -4, -2, -5, -2,  2, -1, -2,  0, -2,-11, -7, -3, 42, 24,-14 },
+    {  4,  1,  3,  2,  0, -2, -3, -2,  2, -1,  4, 11, -2,  2,  3, -4,
+      -5,  9,  2, -4, -9,  5,  8, -1, -7,  1, 24,-13,-28, 20, 15,-22 },
+    { -3,  7,  6,  3, -2, -5,-10, -2, -2, -1, -6, -6, -2,-14,-16, -6,
+      -5,  0, 18,  0,  9,  1,  7,-13, -5, -6, -9, 11,-15,  9, 22,-11 },
+    {  9, -2,  6,  5,  2,  9,-10,  1,  1,  5, -4, 12,  2,  2,-10, -7,
+      -4, -6,  7,  9,  6, 15,  6,  6,-10, 10,  5,-13, -5,  6, 24,-12 },
+    {  1,  3, -3, -3,  8,  1, -6,  2, -5, -3,  7,  2, 14,  6,  9, -6,
+      -5, -4, 27,  7, -3,  8, -6,  3, -8,  8, 22, -5, -6, -2, 22,-17 },
+    { -2, -2,  3, 10,  9,  9, 12,-15, -1,-11,-13,  3, -2,  1, -3,-11,
+       7,  9, 16, -3,-10, -5, -5,  1,  8, -3,  9,  9, -5,  3, 31,-12 },
+    {  7, -5, 10, -4, -8,  2, 16, -2, 10, 10, -3, -2,  3, -8, -3,  3,
+     -13, -6, 15, 20, -9, -3,-12,  1, -2,-16,  8,  8, -1, 16, 22, -5 },
+    {  5, -3,-15, -2, 12, -8,  8, -5,  2, -8, 20,-18, 14, -4,  3,  3,
+       7,-13,-16,  1,-10,  7, 16,  7,  4,-14, -4, -5, -9,  8, 23, -6 },
+    {  5, -4, -5, -4,  1,  8,  4, -7, -5,  8, 10,  6, -6,-10, -2,  6,
+       9,-17,-14, 11, 12, -3,-13, -7,  2, 18,  3,-25,-16, 18, 22, -5 },
+    {  5,  6, -7,-20, -4,  2,  8,  4,-24, -4,  1,  4, -5, -2,  1,-10,
+      -2,  9,  3, -4, -3, -4, -4, -4, 10, 10,  3,  0, -6, 25, 21,-11 },
+    {  0,  7, -1, 14, -6, -4,-10,  5,  4,  4,  4, -5,  3,  4, -1, -7,
+       8,-19,  0,  6,  2,  3,-18, -3, -6,  2,  8, 14,-26, 22, 27,-13 },
+    { -2, -6,  7, -5, 12, -7,  8, -1,  3, -2,  4,  1,  8, -2,  0, 14,
+       6, -5,  6, -4, -7,  7,-21,  8,  1,  8, -9, -4, -3, 11, 25,-13 },
+    {  4,  4, -1, -6,  4,  9, -8,  1, -3,-10, -2,  0, 15, -9,-16, 11,
+       1,  1,  6,  3, -9, -5, 16, 26,  1,-14,  1, -3,-14,  7, 15, -9 },
+    {-12, -2, -9,-13,  2,  6, 14,  0,  1,  0, -1,-13,  0, 10, -1,  6,
+       9, -7,  8,  8, 19,  6, -1,  9, 10, -4,  1, -7,-22, -2, 29, -7 },
+    {  2,  4, 13,-12, -8, -4, -5, 13, 12, -5, -3, -3, -4,  1, -1, 10,
+      15, -6, -1,-11,-30,  4, 15, -1,  9, -7,  0, -2, -7, 10, 25,-16 },
+    {  7,-15, -7, -7, -1, -5, -5,-11,-20, 10,  3,-10, -3,  5, 20, -4,
+       0, -2, -2, 17,  2,  0, -3,  3,  6,  5, -1,-12, -3, 15, 22,-16 },
+    {  4, -1,  3,  4, -5,  0, -1, -5,-24,-29,  4, -9,  1, -3,  0,  0,
+       0, -4,  7, -4, -4, -4,  3,  1, -6,  5, -3, -5,-10,  3, 25,-10 },
+    { -2, -1, -1,  4,  4, -1,  2,  0, -4, -4,  2, -1, -3, -1, -2, -2,
+       1, -3, -5, -1,  2, -3, -4, -4, -3,  5, -9,  1,-11,  7, 46,-46 },
+    {  0, -9,  3,  4,  4,  3, -5, -6,  5, -4,  4, -2,  1,  7, -4,-10,
+      13,  1,  3, -6,  4, -4,  7,  2,-19,-25, -3,-16,-12, 16, 20, -1 },
+    { 18,  6,  4,-12,  0,-14,  9, -6, -1, -4, -5,  2,  1, 12,  4,  2,
+       7,  0,  2,  5,-11, -5, -2,  2, -4, 10,  0, -9, -7,  9, 25, -8 },
+    {  5,  0, -6,  5,  6,  3,  3,-10, -5,  1, -1,  4,  3,-11, -8,  5,
+       4, -5,  5, -5, -7, -5, 11,  5, 20, -8,-16, 21, -4, 27, 23, -5 }
+};
+
+/* FIR filter coefficients, they can be cut on half and maybe use float instead of double */
+
+DECLARE_ALIGNED(16, const float, ff_dca_fir_32bands_perfect)[512] = {
+    +1.135985195E-010,
+    +7.018770981E-011,
+    -1.608403011E-008,
+    -5.083275667E-008,
+    -1.543309907E-007,
+    -3.961981463E-007,
+    -7.342250683E-007,
+    -3.970030775E-007,
+    -4.741137047E-007,
+    -6.022448247E-007,
+    -6.628192182E-007,
+    -6.982898526E-007,
+    -7.020648809E-007,
+    -6.767839409E-007,
+    -6.262345096E-007,
+    -5.564140224E-007,
+    +7.003467317E-007,
+    +8.419976893E-007,
+    +9.742954035E-007,
+    +1.085227950E-006,
+    +1.162929266E-006,
+    +1.194632091E-006,
+    +1.179182050E-006,
+    +1.033426656E-006,
+    +9.451737242E-007,
+    +1.975324267E-006,
+    +1.190443072E-006,
+    +5.234479659E-007,
+    +2.014677420E-007,
+    +7.834767501E-008,
+    -6.702406963E-010,
+    -1.613285505E-009,
+    -2.682709610E-009,
+    -3.399493131E-009,
+    +1.314406006E-008,
+    +7.506701927E-009,
+    +2.788728892E-008,
+    +1.444918922E-007,
+    +3.132386439E-007,
+    +1.399798180E-006,
+    +2.032118118E-006,
+    +2.715013807E-006,
+    +3.453840463E-006,
+    +4.195037945E-006,
+    +4.896494374E-006,
+    +5.516381407E-006,
+    +6.015239251E-006,
+    +6.361419310E-006,
+    +8.006985809E-006,
+    +8.087732567E-006,
+    +7.941360309E-006,
+    +7.568834008E-006,
+    +6.986399967E-006,
+    +6.225028756E-006,
+    +5.315936960E-006,
+    +4.429412002E-006,
+    +3.332600045E-006,
+    +8.427224429E-007,
+    +4.341498823E-007,
+    +9.458596395E-008,
+    +2.975164826E-008,
+    +6.402664354E-008,
+    -3.246264413E-008,
+    -3.809887872E-008,
+    +8.434094667E-008,
+    +6.437721822E-008,
+    +1.189317118E-006,
+    +2.497214155E-006,
+    +3.617151151E-006,
+    +3.157242645E-006,
+    +2.319611212E-006,
+    +7.869333785E-006,
+    +9.826449968E-006,
+    +1.177108606E-005,
+    +1.379448349E-005,
+    +1.571428584E-005,
+    +1.743183020E-005,
+    +1.884208177E-005,
+    +1.987093310E-005,
+    +2.042970118E-005,
+    -3.144468428E-005,
+    -3.334947178E-005,
+    -3.460439257E-005,
+    -3.515914432E-005,
+    -3.495384954E-005,
+    -3.397853652E-005,
+    -3.225446198E-005,
+    -2.978993689E-005,
+    -2.677291741E-005,
+    -1.806914770E-005,
+    -1.776598037E-005,
+    -1.661818715E-005,
+    -1.207003334E-005,
+    -6.993315310E-006,
+    -5.633860383E-007,
+    -9.984935332E-007,
+    -1.470520488E-006,
+    -1.853591357E-006,
+    +7.198007665E-007,
+    +3.086857760E-006,
+    +6.084746474E-006,
+    +9.561075785E-006,
+    +1.309637537E-005,
+    +2.263354872E-005,
+    +2.847247197E-005,
+    +3.415624451E-005,
+    +3.946387005E-005,
+    +4.425736552E-005,
+    +4.839275425E-005,
+    +5.176846025E-005,
+    +5.429694284E-005,
+    +5.595519906E-005,
+    +4.916387297E-006,
+    +9.299508747E-006,
+    +1.356193479E-005,
+    +1.751866148E-005,
+    +2.093936746E-005,
+    +2.362549276E-005,
+    +2.537086584E-005,
+    +2.618136386E-005,
+    +2.554462844E-005,
+    +3.018750249E-005,
+    +2.570833203E-005,
+    +1.985177369E-005,
+    +1.191342653E-005,
+    +2.525620175E-006,
+    -1.521241393E-005,
+    -1.617751332E-005,
+    +1.992636317E-005,
+    +1.774702469E-005,
+    +4.624524081E-005,
+    +5.610509834E-005,
+    +6.568001118E-005,
+    +7.513730816E-005,
+    +8.413690375E-005,
+    +8.757545584E-005,
+    +9.517164290E-005,
+    +1.020687996E-004,
+    +1.084438481E-004,
+    +1.140582463E-004,
+    +1.187910311E-004,
+    +1.224978914E-004,
+    +1.250260248E-004,
+    +1.262027217E-004,
+    +1.226499153E-004,
+    +1.213575742E-004,
+    +1.180980107E-004,
+    +1.126275165E-004,
+    +1.047207043E-004,
+    +9.417100227E-005,
+    +8.078388782E-005,
+    +6.447290798E-005,
+    +4.491530854E-005,
+    +2.470704203E-005,
+    -1.714242217E-006,
+    -3.193307566E-005,
+    -6.541742187E-005,
+    -1.024175072E-004,
+    -1.312203676E-004,
+    -1.774113771E-004,
+    -2.233728592E-004,
+    -2.682086197E-004,
+    -3.347633174E-004,
+    -3.906481725E-004,
+    -4.490280990E-004,
+    -5.099929986E-004,
+    -5.729619297E-004,
+    -6.358824321E-004,
+    -7.021900383E-004,
+    -7.698345580E-004,
+    -8.385353722E-004,
+    -9.078957955E-004,
+    -9.775133803E-004,
+    -1.046945457E-003,
+    -1.115717343E-003,
+    -1.183370827E-003,
+    -1.252829796E-003,
+    -1.316190348E-003,
+    -1.376571832E-003,
+    -1.433344092E-003,
+    -1.485876855E-003,
+    -1.533520175E-003,
+    -1.575609902E-003,
+    -1.611457788E-003,
+    -1.640390139E-003,
+    -1.661288203E-003,
+    -1.674512983E-003,
+    -1.678415807E-003,
+    -1.672798418E-003,
+    -1.656501088E-003,
+    -1.633993932E-003,
+    -1.593449386E-003,
+    +1.542080659E-003,
+    +1.479332102E-003,
+    +1.395521569E-003,
+    +1.303116791E-003,
+    +1.196175464E-003,
+    +1.073757303E-003,
+    +9.358961834E-004,
+    +7.817269652E-004,
+    +6.114174030E-004,
+    +4.244441516E-004,
+    +2.206075296E-004,
+    -2.719412748E-007,
+    -2.382978710E-004,
+    -4.935106263E-004,
+    -7.658848190E-004,
+    -1.055365428E-003,
+    -1.361547387E-003,
+    -1.684492454E-003,
+    -2.023874084E-003,
+    -2.379294252E-003,
+    -2.750317100E-003,
+    -3.136433195E-003,
+    -3.537061159E-003,
+    -3.951539751E-003,
+    -4.379155114E-003,
+    -4.819062538E-003,
+    -5.270531867E-003,
+    -5.732392892E-003,
+    -6.203945260E-003,
+    -6.683901884E-003,
+    -7.170005701E-003,
+    -7.664063945E-003,
+    -8.162760176E-003,
+    -8.665001951E-003,
+    -9.170533158E-003,
+    -9.676489048E-003,
+    -1.018219907E-002,
+    -1.068630442E-002,
+    -1.118756086E-002,
+    -1.168460958E-002,
+    -1.217562053E-002,
+    -1.265939046E-002,
+    -1.313448418E-002,
+    -1.359948888E-002,
+    -1.405300573E-002,
+    -1.449365262E-002,
+    -1.492007636E-002,
+    -1.533095632E-002,
+    -1.572482102E-002,
+    -1.610082202E-002,
+    -1.645756140E-002,
+    -1.679391414E-002,
+    -1.710879989E-002,
+    -1.740120351E-002,
+    -1.767017506E-002,
+    -1.791484281E-002,
+    -1.813439466E-002,
+    -1.832821220E-002,
+    -1.849545911E-002,
+    -1.863567345E-002,
+    -1.874836907E-002,
+    -1.883326657E-002,
+    -1.889026538E-002,
+    -1.891860925E-002,
+    +1.891860925E-002,
+    +1.889026538E-002,
+    +1.883326657E-002,
+    +1.874836907E-002,
+    +1.863567345E-002,
+    +1.849545911E-002,
+    +1.832821220E-002,
+    +1.813439466E-002,
+    +1.791484281E-002,
+    +1.767017506E-002,
+    +1.740120351E-002,
+    +1.710879989E-002,
+    +1.679391414E-002,
+    +1.645756140E-002,
+    +1.610082202E-002,
+    +1.572482102E-002,
+    +1.533095632E-002,
+    +1.492007636E-002,
+    +1.449365262E-002,
+    +1.405300573E-002,
+    +1.359948888E-002,
+    +1.313448418E-002,
+    +1.265939046E-002,
+    +1.217562053E-002,
+    +1.168460958E-002,
+    +1.118756086E-002,
+    +1.068630442E-002,
+    +1.018219907E-002,
+    +9.676489048E-003,
+    +9.170533158E-003,
+    +8.665001951E-003,
+    +8.162760176E-003,
+    +7.664063945E-003,
+    +7.170005701E-003,
+    +6.683901884E-003,
+    +6.203945260E-003,
+    +5.732392892E-003,
+    +5.270531867E-003,
+    +4.819062538E-003,
+    +4.379155114E-003,
+    +3.951539751E-003,
+    +3.537061159E-003,
+    +3.136433195E-003,
+    +2.750317100E-003,
+    +2.379294252E-003,
+    +2.023874084E-003,
+    +1.684492454E-003,
+    +1.361547387E-003,
+    +1.055365428E-003,
+    +7.658848190E-004,
+    +4.935106263E-004,
+    +2.382978710E-004,
+    +2.719412748E-007,
+    -2.206075296E-004,
+    -4.244441516E-004,
+    -6.114174030E-004,
+    -7.817269652E-004,
+    -9.358961834E-004,
+    -1.073757303E-003,
+    -1.196175464E-003,
+    -1.303116791E-003,
+    -1.395521569E-003,
+    -1.479332102E-003,
+    -1.542080659E-003,
+    +1.593449386E-003,
+    +1.633993932E-003,
+    +1.656501088E-003,
+    +1.672798418E-003,
+    +1.678415807E-003,
+    +1.674512983E-003,
+    +1.661288203E-003,
+    +1.640390139E-003,
+    +1.611457788E-003,
+    +1.575609902E-003,
+    +1.533520175E-003,
+    +1.485876855E-003,
+    +1.433344092E-003,
+    +1.376571832E-003,
+    +1.316190348E-003,
+    +1.252829796E-003,
+    +1.183370827E-003,
+    +1.115717343E-003,
+    +1.046945457E-003,
+    +9.775133803E-004,
+    +9.078957955E-004,
+    +8.385353722E-004,
+    +7.698345580E-004,
+    +7.021900383E-004,
+    +6.358824321E-004,
+    +5.729619297E-004,
+    +5.099929986E-004,
+    +4.490280990E-004,
+    +3.906481725E-004,
+    +3.347633174E-004,
+    +2.682086197E-004,
+    +2.233728592E-004,
+    +1.774113771E-004,
+    +1.312203676E-004,
+    +1.024175072E-004,
+    +6.541742187E-005,
+    +3.193307566E-005,
+    +1.714242217E-006,
+    -2.470704203E-005,
+    -4.491530854E-005,
+    -6.447290798E-005,
+    -8.078388782E-005,
+    -9.417100227E-005,
+    -1.047207043E-004,
+    -1.126275165E-004,
+    -1.180980107E-004,
+    -1.213575742E-004,
+    -1.226499153E-004,
+    -1.262027217E-004,
+    -1.250260248E-004,
+    -1.224978914E-004,
+    -1.187910311E-004,
+    -1.140582463E-004,
+    -1.084438481E-004,
+    -1.020687996E-004,
+    -9.517164290E-005,
+    -8.757545584E-005,
+    -8.413690375E-005,
+    -7.513730816E-005,
+    -6.568001118E-005,
+    -5.610509834E-005,
+    -4.624524081E-005,
+    -1.774702469E-005,
+    -1.992636317E-005,
+    +1.617751332E-005,
+    +1.521241393E-005,
+    -2.525620175E-006,
+    -1.191342653E-005,
+    -1.985177369E-005,
+    -2.570833203E-005,
+    -3.018750249E-005,
+    -2.554462844E-005,
+    -2.618136386E-005,
+    -2.537086584E-005,
+    -2.362549276E-005,
+    -2.093936746E-005,
+    -1.751866148E-005,
+    -1.356193479E-005,
+    -9.299508747E-006,
+    -4.916387297E-006,
+    -5.595519906E-005,
+    -5.429694284E-005,
+    -5.176846025E-005,
+    -4.839275425E-005,
+    -4.425736552E-005,
+    -3.946387005E-005,
+    -3.415624451E-005,
+    -2.847247197E-005,
+    -2.263354872E-005,
+    -1.309637537E-005,
+    -9.561075785E-006,
+    -6.084746474E-006,
+    -3.086857760E-006,
+    -7.198007665E-007,
+    +1.853591357E-006,
+    +1.470520488E-006,
+    +9.984935332E-007,
+    +5.633860383E-007,
+    +6.993315310E-006,
+    +1.207003334E-005,
+    +1.661818715E-005,
+    +1.776598037E-005,
+    +1.806914770E-005,
+    +2.677291741E-005,
+    +2.978993689E-005,
+    +3.225446198E-005,
+    +3.397853652E-005,
+    +3.495384954E-005,
+    +3.515914432E-005,
+    +3.460439257E-005,
+    +3.334947178E-005,
+    +3.144468428E-005,
+    -2.042970118E-005,
+    -1.987093310E-005,
+    -1.884208177E-005,
+    -1.743183020E-005,
+    -1.571428584E-005,
+    -1.379448349E-005,
+    -1.177108606E-005,
+    -9.826449968E-006,
+    -7.869333785E-006,
+    -2.319611212E-006,
+    -3.157242645E-006,
+    -3.617151151E-006,
+    -2.497214155E-006,
+    -1.189317118E-006,
+    -6.437721822E-008,
+    -8.434094667E-008,
+    +3.809887872E-008,
+    +3.246264413E-008,
+    -6.402664354E-008,
+    -2.975164826E-008,
+    -9.458596395E-008,
+    -4.341498823E-007,
+    -8.427224429E-007,
+    -3.332600045E-006,
+    -4.429412002E-006,
+    -5.315936960E-006,
+    -6.225028756E-006,
+    -6.986399967E-006,
+    -7.568834008E-006,
+    -7.941360309E-006,
+    -8.087732567E-006,
+    -8.006985809E-006,
+    -6.361419310E-006,
+    -6.015239251E-006,
+    -5.516381407E-006,
+    -4.896494374E-006,
+    -4.195037945E-006,
+    -3.453840463E-006,
+    -2.715013807E-006,
+    -2.032118118E-006,
+    -1.399798180E-006,
+    -3.132386439E-007,
+    -1.444918922E-007,
+    -2.788728892E-008,
+    -7.506701927E-009,
+    -1.314406006E-008,
+    +3.399493131E-009,
+    +2.682709610E-009,
+    +1.613285505E-009,
+    +6.702406963E-010,
+    -7.834767501E-008,
+    -2.014677420E-007,
+    -5.234479659E-007,
+    -1.190443072E-006,
+    -1.975324267E-006,
+    -9.451737242E-007,
+    -1.033426656E-006,
+    -1.179182050E-006,
+    -1.194632091E-006,
+    -1.162929266E-006,
+    -1.085227950E-006,
+    -9.742954035E-007,
+    -8.419976893E-007,
+    -7.003467317E-007,
+    +5.564140224E-007,
+    +6.262345096E-007,
+    +6.767839409E-007,
+    +7.020648809E-007,
+    +6.982898526E-007,
+    +6.628192182E-007,
+    +6.022448247E-007,
+    +4.741137047E-007,
+    +3.970030775E-007,
+    +7.342250683E-007,
+    +3.961981463E-007,
+    +1.543309907E-007,
+    +5.083275667E-008,
+    +1.608403011E-008,
+    -7.018770981E-011,
+    -1.135985195E-010
+};
+
+DECLARE_ALIGNED(16, const float, ff_dca_fir_32bands_nonperfect)[512] = {
+    -1.390191784E-007,
+    -1.693738625E-007,
+    -2.030677564E-007,
+    -2.404238444E-007,
+    -2.818143514E-007,
+    -3.276689142E-007,
+    -3.784752209E-007,
+    -4.347855338E-007,
+    -4.972276315E-007,
+    -5.665120852E-007,
+    -6.434325428E-007,
+    -7.288739425E-007,
+    -8.238164355E-007,
+    -9.293416952E-007,
+    -1.046637067E-006,
+    -1.176999604E-006,
+    -1.321840614E-006,
+    -1.482681114E-006,
+    -1.661159786E-006,
+    -1.859034001E-006,
+    -2.078171747E-006,
+    -2.320550948E-006,
+    -2.588257530E-006,
+    -2.883470643E-006,
+    -3.208459020E-006,
+    -3.565570978E-006,
+    -3.957220997E-006,
+    -4.385879038E-006,
+    -4.854050530E-006,
+    -5.364252502E-006,
+    -5.918994248E-006,
+    -6.520755960E-006,
+    -7.171964626E-006,
+    -7.874960829E-006,
+    -8.631964192E-006,
+    -9.445050637E-006,
+    -1.031611009E-005,
+    -1.124680875E-005,
+    -1.223855270E-005,
+    -1.329243969E-005,
+    -1.440921824E-005,
+    -1.558924305E-005,
+    -1.683242772E-005,
+    -1.813820381E-005,
+    -1.950545993E-005,
+    -2.093250441E-005,
+    -2.241701623E-005,
+    -2.395598858E-005,
+    -2.554569073E-005,
+    -2.718161704E-005,
+    -2.885844333E-005,
+    -3.056998685E-005,
+    -3.230916263E-005,
+    -3.406793985E-005,
+    -3.583733633E-005,
+    -3.760734762E-005,
+    -3.936696885E-005,
+    -4.110412556E-005,
+    -4.280570283E-005,
+    -4.445751256E-005,
+    -4.604430433E-005,
+    -4.754976908E-005,
+    -4.895655002E-005,
+    -5.024627535E-005,
+    +5.139957648E-005,
+    +5.239612074E-005,
+    +5.321469871E-005,
+    +5.383323878E-005,
+    +5.422891263E-005,
+    +5.437819709E-005,
+    +5.425697600E-005,
+    +5.384063843E-005,
+    +5.310418419E-005,
+    +5.202236207E-005,
+    +5.056979353E-005,
+    +4.872112549E-005,
+    +4.645117951E-005,
+    +4.373511547E-005,
+    +4.054862075E-005,
+    +3.686808850E-005,
+    +3.267079956E-005,
+    +2.793515523E-005,
+    +2.264085742E-005,
+    +1.676913780E-005,
+    +1.030297699E-005,
+    +3.227306706E-006,
+    -4.470633485E-006,
+    -1.280130618E-005,
+    -2.177240640E-005,
+    -3.138873581E-005,
+    -4.165195787E-005,
+    -5.256036457E-005,
+    -6.410864444E-005,
+    -7.628766616E-005,
+    -8.908427117E-005,
+    -1.024810626E-004,
+    -1.164562127E-004,
+    -1.309833024E-004,
+    -1.460311323E-004,
+    -1.615635992E-004,
+    -1.775395358E-004,
+    -1.939126523E-004,
+    -2.106313768E-004,
+    -2.276388550E-004,
+    -2.448728774E-004,
+    -2.622658503E-004,
+    -2.797449124E-004,
+    -2.972317743E-004,
+    -3.146430245E-004,
+    -3.318900708E-004,
+    -3.488793736E-004,
+    -3.655125911E-004,
+    -3.816867538E-004,
+    -3.972945851E-004,
+    -4.122247046E-004,
+    -4.263620067E-004,
+    -4.395879805E-004,
+    -4.517810594E-004,
+    -4.628172028E-004,
+    -4.725702747E-004,
+    -4.809123348E-004,
+    -4.877146275E-004,
+    -4.928477574E-004,
+    -4.961824161E-004,
+    -4.975944757E-004,
+    -4.969481961E-004,
+    -4.941228544E-004,
+    -4.889960401E-004,
+    +4.814492422E-004,
+    +4.713678791E-004,
+    +4.586426076E-004,
+    +4.431701091E-004,
+    +4.248536134E-004,
+    +4.036037717E-004,
+    +3.793396754E-004,
+    +3.519894381E-004,
+    +3.214911267E-004,
+    +2.877934603E-004,
+    +2.508567995E-004,
+    +2.106537577E-004,
+    +1.671699720E-004,
+    +1.204049113E-004,
+    +7.037253090E-005,
+    +1.710198012E-005,
+    -3.936182839E-005,
+    -9.895755647E-005,
+    -1.616069785E-004,
+    -2.272142592E-004,
+    -2.956659591E-004,
+    -3.668301215E-004,
+    -4.405563814E-004,
+    -5.166754709E-004,
+    -5.949990009E-004,
+    -6.753197522E-004,
+    -7.574109477E-004,
+    -8.410271257E-004,
+    -9.259034996E-004,
+    -1.011756598E-003,
+    -1.098284614E-003,
+    -1.185167348E-003,
+    -1.272067428E-003,
+    -1.358630019E-003,
+    -1.444484224E-003,
+    -1.529243193E-003,
+    -1.612505526E-003,
+    -1.693855622E-003,
+    -1.772865304E-003,
+    -1.849094522E-003,
+    -1.922092517E-003,
+    -1.991399564E-003,
+    -2.056547208E-003,
+    -2.117061289E-003,
+    -2.172462177E-003,
+    -2.222266514E-003,
+    -2.265989315E-003,
+    -2.303145360E-003,
+    -2.333251061E-003,
+    -2.355825622E-003,
+    -2.370394068E-003,
+    -2.376487479E-003,
+    -2.373647178E-003,
+    -2.361423569E-003,
+    -2.339380793E-003,
+    -2.307097195E-003,
+    -2.264167881E-003,
+    -2.210205887E-003,
+    -2.144844970E-003,
+    -2.067740774E-003,
+    -1.978572691E-003,
+    -1.877046190E-003,
+    -1.762894331E-003,
+    -1.635878929E-003,
+    +1.495792647E-003,
+    +1.342460280E-003,
+    +1.175740734E-003,
+    +9.955273708E-004,
+    +8.017504588E-004,
+    +5.943773431E-004,
+    +3.734139318E-004,
+    +1.389056415E-004,
+    -1.090620208E-004,
+    -3.703625989E-004,
+    -6.448282511E-004,
+    -9.322494152E-004,
+    -1.232374110E-003,
+    -1.544908970E-003,
+    -1.869517611E-003,
+    -2.205822384E-003,
+    -2.553403843E-003,
+    -2.911801683E-003,
+    -3.280514618E-003,
+    -3.659002949E-003,
+    -4.046686925E-003,
+    -4.442950245E-003,
+    -4.847140983E-003,
+    -5.258570891E-003,
+    -5.676518660E-003,
+    -6.100233644E-003,
+    -6.528933067E-003,
+    -6.961807609E-003,
+    -7.398022339E-003,
+    -7.836719044E-003,
+    -8.277016692E-003,
+    -8.718019351E-003,
+    -9.158811532E-003,
+    -9.598465636E-003,
+    -1.003604382E-002,
+    -1.047059800E-002,
+    -1.090117730E-002,
+    -1.132682897E-002,
+    -1.174659748E-002,
+    -1.215953380E-002,
+    -1.256469358E-002,
+    -1.296114177E-002,
+    -1.334795821E-002,
+    -1.372423489E-002,
+    -1.408908330E-002,
+    -1.444163360E-002,
+    -1.478104480E-002,
+    -1.510649733E-002,
+    -1.541720331E-002,
+    -1.571240649E-002,
+    -1.599138230E-002,
+    -1.625344716E-002,
+    -1.649795473E-002,
+    -1.672429405E-002,
+    -1.693190821E-002,
+    -1.712027565E-002,
+    -1.728892699E-002,
+    -1.743743755E-002,
+    -1.756543480E-002,
+    -1.767260395E-002,
+    -1.775865816E-002,
+    -1.782339066E-002,
+    -1.786663756E-002,
+    -1.788828894E-002,
+    +1.788828894E-002,
+    +1.786663756E-002,
+    +1.782339066E-002,
+    +1.775865816E-002,
+    +1.767260395E-002,
+    +1.756543480E-002,
+    +1.743743755E-002,
+    +1.728892699E-002,
+    +1.712027565E-002,
+    +1.693190821E-002,
+    +1.672429405E-002,
+    +1.649795473E-002,
+    +1.625344716E-002,
+    +1.599138230E-002,
+    +1.571240649E-002,
+    +1.541720331E-002,
+    +1.510649733E-002,
+    +1.478104480E-002,
+    +1.444163360E-002,
+    +1.408908330E-002,
+    +1.372423489E-002,
+    +1.334795821E-002,
+    +1.296114177E-002,
+    +1.256469358E-002,
+    +1.215953380E-002,
+    +1.174659748E-002,
+    +1.132682897E-002,
+    +1.090117730E-002,
+    +1.047059800E-002,
+    +1.003604382E-002,
+    +9.598465636E-003,
+    +9.158811532E-003,
+    +8.718019351E-003,
+    +8.277016692E-003,
+    +7.836719044E-003,
+    +7.398022339E-003,
+    +6.961807609E-003,
+    +6.528933067E-003,
+    +6.100233644E-003,
+    +5.676518660E-003,
+    +5.258570891E-003,
+    +4.847140983E-003,
+    +4.442950245E-003,
+    +4.046686925E-003,
+    +3.659002949E-003,
+    +3.280514618E-003,
+    +2.911801683E-003,
+    +2.553403843E-003,
+    +2.205822384E-003,
+    +1.869517611E-003,
+    +1.544908970E-003,
+    +1.232374110E-003,
+    +9.322494152E-004,
+    +6.448282511E-004,
+    +3.703625989E-004,
+    +1.090620208E-004,
+    -1.389056415E-004,
+    -3.734139318E-004,
+    -5.943773431E-004,
+    -8.017504588E-004,
+    -9.955273708E-004,
+    -1.175740734E-003,
+    -1.342460280E-003,
+    -1.495792647E-003,
+    +1.635878929E-003,
+    +1.762894331E-003,
+    +1.877046190E-003,
+    +1.978572691E-003,
+    +2.067740774E-003,
+    +2.144844970E-003,
+    +2.210205887E-003,
+    +2.264167881E-003,
+    +2.307097195E-003,
+    +2.339380793E-003,
+    +2.361423569E-003,
+    +2.373647178E-003,
+    +2.376487479E-003,
+    +2.370394068E-003,
+    +2.355825622E-003,
+    +2.333251061E-003,
+    +2.303145360E-003,
+    +2.265989315E-003,
+    +2.222266514E-003,
+    +2.172462177E-003,
+    +2.117061289E-003,
+    +2.056547208E-003,
+    +1.991399564E-003,
+    +1.922092517E-003,
+    +1.849094522E-003,
+    +1.772865304E-003,
+    +1.693855622E-003,
+    +1.612505526E-003,
+    +1.529243193E-003,
+    +1.444484224E-003,
+    +1.358630019E-003,
+    +1.272067428E-003,
+    +1.185167348E-003,
+    +1.098284614E-003,
+    +1.011756598E-003,
+    +9.259034996E-004,
+    +8.410271257E-004,
+    +7.574109477E-004,
+    +6.753197522E-004,
+    +5.949990009E-004,
+    +5.166754709E-004,
+    +4.405563814E-004,
+    +3.668301215E-004,
+    +2.956659591E-004,
+    +2.272142592E-004,
+    +1.616069785E-004,
+    +9.895755647E-005,
+    +3.936182839E-005,
+    -1.710198012E-005,
+    -7.037253090E-005,
+    -1.204049113E-004,
+    -1.671699720E-004,
+    -2.106537577E-004,
+    -2.508567995E-004,
+    -2.877934603E-004,
+    -3.214911267E-004,
+    -3.519894381E-004,
+    -3.793396754E-004,
+    -4.036037717E-004,
+    -4.248536134E-004,
+    -4.431701091E-004,
+    -4.586426076E-004,
+    -4.713678791E-004,
+    -4.814492422E-004,
+    +4.889960401E-004,
+    +4.941228544E-004,
+    +4.969481961E-004,
+    +4.975944757E-004,
+    +4.961824161E-004,
+    +4.928477574E-004,
+    +4.877146275E-004,
+    +4.809123348E-004,
+    +4.725702747E-004,
+    +4.628172028E-004,
+    +4.517810594E-004,
+    +4.395879805E-004,
+    +4.263620067E-004,
+    +4.122247046E-004,
+    +3.972945851E-004,
+    +3.816867538E-004,
+    +3.655125911E-004,
+    +3.488793736E-004,
+    +3.318900708E-004,
+    +3.146430245E-004,
+    +2.972317743E-004,
+    +2.797449124E-004,
+    +2.622658503E-004,
+    +2.448728774E-004,
+    +2.276388550E-004,
+    +2.106313768E-004,
+    +1.939126523E-004,
+    +1.775395358E-004,
+    +1.615635992E-004,
+    +1.460311323E-004,
+    +1.309833024E-004,
+    +1.164562127E-004,
+    +1.024810626E-004,
+    +8.908427117E-005,
+    +7.628766616E-005,
+    +6.410864444E-005,
+    +5.256036457E-005,
+    +4.165195787E-005,
+    +3.138873581E-005,
+    +2.177240640E-005,
+    +1.280130618E-005,
+    +4.470633485E-006,
+    -3.227306706E-006,
+    -1.030297699E-005,
+    -1.676913780E-005,
+    -2.264085742E-005,
+    -2.793515523E-005,
+    -3.267079956E-005,
+    -3.686808850E-005,
+    -4.054862075E-005,
+    -4.373511547E-005,
+    -4.645117951E-005,
+    -4.872112549E-005,
+    -5.056979353E-005,
+    -5.202236207E-005,
+    -5.310418419E-005,
+    -5.384063843E-005,
+    -5.425697600E-005,
+    -5.437819709E-005,
+    -5.422891263E-005,
+    -5.383323878E-005,
+    -5.321469871E-005,
+    -5.239612074E-005,
+    -5.139957648E-005,
+    +5.024627535E-005,
+    +4.895655002E-005,
+    +4.754976908E-005,
+    +4.604430433E-005,
+    +4.445751256E-005,
+    +4.280570283E-005,
+    +4.110412556E-005,
+    +3.936696885E-005,
+    +3.760734762E-005,
+    +3.583733633E-005,
+    +3.406793985E-005,
+    +3.230916263E-005,
+    +3.056998685E-005,
+    +2.885844333E-005,
+    +2.718161704E-005,
+    +2.554569073E-005,
+    +2.395598858E-005,
+    +2.241701623E-005,
+    +2.093250441E-005,
+    +1.950545993E-005,
+    +1.813820381E-005,
+    +1.683242772E-005,
+    +1.558924305E-005,
+    +1.440921824E-005,
+    +1.329243969E-005,
+    +1.223855270E-005,
+    +1.124680875E-005,
+    +1.031611009E-005,
+    +9.445050637E-006,
+    +8.631964192E-006,
+    +7.874960829E-006,
+    +7.171964626E-006,
+    +6.520755960E-006,
+    +5.918994248E-006,
+    +5.364252502E-006,
+    +4.854050530E-006,
+    +4.385879038E-006,
+    +3.957220997E-006,
+    +3.565570978E-006,
+    +3.208459020E-006,
+    +2.883470643E-006,
+    +2.588257530E-006,
+    +2.320550948E-006,
+    +2.078171747E-006,
+    +1.859034001E-006,
+    +1.661159786E-006,
+    +1.482681114E-006,
+    +1.321840614E-006,
+    +1.176999604E-006,
+    +1.046637067E-006,
+    +9.293416952E-007,
+    +8.238164355E-007,
+    +7.288739425E-007,
+    +6.434325428E-007,
+    +5.665120852E-007,
+    +4.972276315E-007,
+    +4.347855338E-007,
+    +3.784752209E-007,
+    +3.276689142E-007,
+    +2.818143514E-007,
+    +2.404238444E-007,
+    +2.030677564E-007,
+    +1.693738625E-007,
+    +1.390191784E-007
+};
+
+/* pre-scale lfe fir coefficients
+ *
+ * Permuted compared to table D.8 in the spec. First, the table in the
+ * spec has twice the number of coefficients, but they are reflected,
+ * T[i] = T[511 - i]. Furthermore, the indices are permuted, so that
+ *
+ *   lfe_fir_64[8 * k + j] = T[64 * j + k]
+ *
+ * for 0 <= k < 32 and 0 <= j < 8. (This corresponds to adding a
+ * leading zero to the 8-bit index, and rotating it right by 3 bits
+ * as a 9-bit field). Values with j >= 4 can be reflected, as
+ *
+ *   lfe_fir_64[8 * k + j] = T[64 * (7 - j) + (63 - k)]
+ *
+ * so all values in T get included. */
+#define SCALE(c) ((c) / (256.0f * 32768.0f))
+DECLARE_ALIGNED(16, const float, ff_dca_lfe_fir_64)[256] = {
+    SCALE(2.658434386830777e-4), SCALE(9.029330685734748e-3),
+    SCALE(7.939263433218002e-2), SCALE(2.425158768892288e-1),
+    SCALE(3.430179357528686e-1), SCALE(2.398228943347931e-1),
+    SCALE(7.746443897485733e-2), SCALE(8.622321300208569e-3),
+    SCALE(8.179365249816328e-5), SCALE(9.450953453779220e-3),
+    SCALE(8.134882897138596e-2), SCALE(2.451938837766648e-1),
+    SCALE(3.429597318172455e-1), SCALE(2.371159791946411e-1),
+    SCALE(7.556436210870743e-2), SCALE(8.229630999267101e-3),
+    SCALE(9.439323912374676e-5), SCALE(9.887560270726680e-3),
+    SCALE(8.333285897970200e-2), SCALE(2.478559017181396e-1),
+    SCALE(3.428434133529663e-1), SCALE(2.343961596488952e-1),
+    SCALE(7.369252294301987e-2), SCALE(7.850865833461285e-3),
+    SCALE(1.082170274457894e-4), SCALE(1.033949479460716e-2),
+    SCALE(8.534456789493561e-2), SCALE(2.505008876323700e-1),
+    SCALE(3.426689505577088e-1), SCALE(2.316644787788391e-1),
+    SCALE(7.184901088476181e-2), SCALE(7.485736627131701e-3),
+    SCALE(1.233371440321207e-4), SCALE(1.080708485096693e-2),
+    SCALE(8.738376945257187e-2), SCALE(2.531278133392334e-1),
+    SCALE(3.424364924430847e-1), SCALE(2.289219647645950e-1),
+    SCALE(7.003392279148102e-2), SCALE(7.133882027119398e-3),
+    SCALE(1.397485757479444e-4), SCALE(1.129068247973919e-2),
+    SCALE(8.945026248693466e-2), SCALE(2.557355761528015e-1),
+    SCALE(3.421461284160614e-1), SCALE(2.261696159839630e-1),
+    SCALE(6.824731826782227e-2), SCALE(6.794991903007030e-3),
+    SCALE(1.575958012836054e-4), SCALE(1.179065089672804e-2),
+    SCALE(9.154383838176728e-2), SCALE(2.583232223987580e-1),
+    SCALE(3.417979776859284e-1), SCALE(2.234084606170654e-1),
+    SCALE(6.648923456668854e-2), SCALE(6.468691397458315e-3),
+    SCALE(1.769922382663936e-4), SCALE(1.230732165277004e-2),
+    SCALE(9.366425126791000e-2), SCALE(2.608896791934967e-1),
+    SCALE(3.413922190666198e-1), SCALE(2.206395119428635e-1),
+    SCALE(6.475970894098282e-2), SCALE(6.154712289571762e-3),
+    SCALE(1.981738605536520e-4), SCALE(1.284105982631445e-2),
+    SCALE(9.581124037504196e-2), SCALE(2.634339034557342e-1),
+    SCALE(3.409290313720703e-1), SCALE(2.178637981414795e-1),
+    SCALE(6.305878609418869e-2), SCALE(5.852684378623962e-3),
+    SCALE(2.211847313446924e-4), SCALE(1.339218579232693e-2),
+    SCALE(9.798453748226166e-2), SCALE(2.659549415111542e-1),
+    SCALE(3.404086530208588e-1), SCALE(2.150822728872299e-1),
+    SCALE(6.138643622398376e-2), SCALE(5.562345497310162e-3),
+    SCALE(2.460231189616024e-4), SCALE(1.396108977496624e-2),
+    SCALE(1.001838669180870e-1), SCALE(2.684516608715058e-1),
+    SCALE(3.398312926292420e-1), SCALE(2.122959494590759e-1),
+    SCALE(5.974265560507774e-2), SCALE(5.283284001052380e-3),
+    SCALE(2.726115926634520e-4), SCALE(1.454808749258518e-2),
+    SCALE(1.024089083075523e-1), SCALE(2.709231376647949e-1),
+    SCALE(3.391972482204438e-1), SCALE(2.095058411359787e-1),
+    SCALE(5.812742188572884e-2), SCALE(5.015311297029257e-3),
+    SCALE(3.013863170053810e-4), SCALE(1.515355054289102e-2),
+    SCALE(1.046593263745308e-1), SCALE(2.733682692050934e-1),
+    SCALE(3.385068178176880e-1), SCALE(2.067128717899322e-1),
+    SCALE(5.654069408774376e-2), SCALE(4.758012015372515e-3),
+    SCALE(3.328395541757345e-4), SCALE(1.577781140804291e-2),
+    SCALE(1.069347932934761e-1), SCALE(2.757860720157624e-1),
+    SCALE(3.377602994441986e-1), SCALE(2.039180546998978e-1),
+    SCALE(5.498242005705833e-2), SCALE(4.511159844696522e-3),
+    SCALE(3.658991190604866e-4), SCALE(1.642123050987720e-2),
+    SCALE(1.092349365353584e-1), SCALE(2.781755328178406e-1),
+    SCALE(3.369580209255218e-1), SCALE(2.011223286390304e-1),
+    SCALE(5.345252528786659e-2), SCALE(4.274417180567980e-3),
+    SCALE(4.018281470052898e-4), SCALE(1.708412915468216e-2),
+    SCALE(1.115593686699867e-1), SCALE(2.805356979370117e-1),
+    SCALE(3.361004292964936e-1), SCALE(1.983266174793244e-1),
+    SCALE(5.195093154907227e-2), SCALE(4.047499038279056e-3),
+    SCALE(4.401875485200435e-4), SCALE(1.776690222322941e-2),
+    SCALE(1.139076948165894e-1), SCALE(2.828655838966370e-1),
+    SCALE(3.351879119873047e-1), SCALE(1.955319195985794e-1),
+    SCALE(5.047753453254700e-2), SCALE(3.830091329291463e-3),
+    SCALE(4.812776169274002e-4), SCALE(1.846982724964619e-2),
+    SCALE(1.162794977426529e-1), SCALE(2.851640880107880e-1),
+    SCALE(3.342207968235016e-1), SCALE(1.927391141653061e-1),
+    SCALE(4.903224110603333e-2), SCALE(3.621967276558280e-3),
+    SCALE(5.252459668554366e-4), SCALE(1.919330470263958e-2),
+    SCALE(1.186743453145027e-1), SCALE(2.874303460121155e-1),
+    SCALE(3.331996202468872e-1), SCALE(1.899491697549820e-1),
+    SCALE(4.761491715908051e-2), SCALE(3.422776935622096e-3),
+    SCALE(5.721592460758984e-4), SCALE(1.993762329220772e-2),
+    SCALE(1.210917681455612e-1), SCALE(2.896633744239807e-1),
+    SCALE(3.321248590946198e-1), SCALE(1.871629506349564e-1),
+    SCALE(4.622544348239899e-2), SCALE(3.232272574678064e-3),
+    SCALE(6.222130032256246e-4), SCALE(2.070316113531590e-2),
+    SCALE(1.235313042998314e-1), SCALE(2.918621897697448e-1),
+    SCALE(3.309969604015350e-1), SCALE(1.843813359737396e-1),
+    SCALE(4.486365616321564e-2), SCALE(3.050152910873294e-3),
+    SCALE(6.755515350960195e-4), SCALE(2.149021252989769e-2),
+    SCALE(1.259924471378326e-1), SCALE(2.940258979797364e-1),
+    SCALE(3.298164308071136e-1), SCALE(1.816052496433258e-1),
+    SCALE(4.352942481637001e-2), SCALE(2.876190468668938e-3),
+    SCALE(7.324148900806904e-4), SCALE(2.229913882911205e-2),
+    SCALE(1.284746825695038e-1), SCALE(2.961534857749939e-1),
+    SCALE(3.285838961601258e-1), SCALE(1.788355410099030e-1),
+    SCALE(4.222255200147629e-2), SCALE(2.710093278437853e-3),
+    SCALE(7.928516715764999e-4), SCALE(2.313023805618286e-2),
+    SCALE(1.309774816036224e-1), SCALE(2.982441186904907e-1),
+    SCALE(3.272998929023742e-1), SCALE(1.760730892419815e-1),
+    SCALE(4.094288870692253e-2), SCALE(2.551567042246461e-3),
+    SCALE(8.570110658183694e-4), SCALE(2.398385666310787e-2),
+    SCALE(1.335003077983856e-1), SCALE(3.002967536449432e-1),
+    SCALE(3.259649574756622e-1), SCALE(1.733186990022659e-1),
+    SCALE(3.969023004174232e-2), SCALE(2.400433411821723e-3),
+    SCALE(9.251192095689476e-4), SCALE(2.486028522253036e-2),
+    SCALE(1.360425949096680e-1), SCALE(3.023106753826142e-1),
+    SCALE(3.245797157287598e-1), SCALE(1.705732345581055e-1),
+    SCALE(3.846437484025955e-2), SCALE(2.256359672173858e-3),
+    SCALE(9.974770946428180e-4), SCALE(2.575986087322235e-2),
+    SCALE(1.386037617921829e-1), SCALE(3.042849004268646e-1),
+    SCALE(3.231448531150818e-1), SCALE(1.678375005722046e-1),
+    SCALE(3.726511076092720e-2), SCALE(2.119151875376701e-3),
+    SCALE(1.073930296115577e-3), SCALE(2.668286114931106e-2),
+    SCALE(1.411831974983215e-1), SCALE(3.062185347080230e-1),
+    SCALE(3.216609656810760e-1), SCALE(1.651122719049454e-1),
+    SCALE(3.609224036335945e-2), SCALE(1.988604199141264e-3),
+    SCALE(1.155023579485714e-3), SCALE(2.762960828840732e-2),
+    SCALE(1.437802612781525e-1), SCALE(3.081108033657074e-1),
+    SCALE(3.201287388801574e-1), SCALE(1.623983532190323e-1),
+    SCALE(3.494550660252571e-2), SCALE(1.864377525635064e-3),
+    SCALE(1.240676851011813e-3), SCALE(2.860039286315441e-2),
+    SCALE(1.463943719863892e-1), SCALE(3.099608123302460e-1),
+    SCALE(3.185488879680634e-1), SCALE(1.596965193748474e-1),
+    SCALE(3.382468968629837e-2), SCALE(1.746327499859035e-3),
+    SCALE(1.331258914433420e-3), SCALE(2.959549613296986e-2),
+    SCALE(1.490248143672943e-1), SCALE(3.117676973342896e-1),
+    SCALE(3.169221282005310e-1), SCALE(1.570075154304504e-1),
+    SCALE(3.272953629493714e-2), SCALE(1.634211512282491e-3),
+    SCALE(1.426893868483603e-3), SCALE(3.061520494520664e-2),
+    SCALE(1.516709625720978e-1), SCALE(3.135308027267456e-1),
+    SCALE(3.152491748332978e-1), SCALE(1.543320864439010e-1),
+    SCALE(3.165979683399200e-2), SCALE(1.527829794213176e-3),
+};
+
+/* Permuted compared to table D.8 in the spec. First, the table in the
+ * spec has twice the number of coefficients, but they are reflected,
+ * T[i] = T[511 - i]. Furthermore, the indices are permuted, so that
+ *
+ *   lfe_fir_128[4 * k + j] = T[128 * j + k]
+ *
+ * for 0 <= k < 64 and 0 <= j < 4. Values with j >= 2 can be
+ * reflected, as
+ *
+ *   lfe_fir_128[4 * k + j] = T[128 * (3 - j) + (127 - k)]
+ *
+ * so all values in T get included. */
+DECLARE_ALIGNED(16, const float, ff_dca_lfe_fir_128)[256] = {
+    SCALE(0.00053168571), SCALE(0.15878495574), SCALE(0.68603444099), SCALE(0.15492856503),
+    SCALE(0.00016358691), SCALE(0.16269733012), SCALE(0.68591803312), SCALE(0.15112841129),
+    SCALE(0.00018878609), SCALE(0.16666537523), SCALE(0.68568539619), SCALE(0.14738474786),
+    SCALE(0.00021643363), SCALE(0.17068879306), SCALE(0.68533653021), SCALE(0.14369773865),
+    SCALE(0.00024667382), SCALE(0.17476719618), SCALE(0.68487155437), SCALE(0.14006754756),
+    SCALE(0.00027949660), SCALE(0.17890018225), SCALE(0.68429082632), SCALE(0.13649433851),
+    SCALE(0.00031519096), SCALE(0.18308731914), SCALE(0.68359452486), SCALE(0.13297818601),
+    SCALE(0.00035398375), SCALE(0.18732811511), SCALE(0.68278300762), SCALE(0.12951917946),
+    SCALE(0.00039634691), SCALE(0.19162209332), SCALE(0.68185669184), SCALE(0.12611730397),
+    SCALE(0.00044236859), SCALE(0.19596865773), SCALE(0.68081587553), SCALE(0.12277261168),
+    SCALE(0.00049204525), SCALE(0.20036731660), SCALE(0.67966115475), SCALE(0.11948505789),
+    SCALE(0.00054522208), SCALE(0.20481738448), SCALE(0.67839306593), SCALE(0.11625462025),
+    SCALE(0.00060277141), SCALE(0.20931822062), SCALE(0.67701220512), SCALE(0.11308115721),
+    SCALE(0.00066567765), SCALE(0.21386915445), SCALE(0.67551922798), SCALE(0.10996460915),
+    SCALE(0.00073179678), SCALE(0.21846942604), SCALE(0.67391467094), SCALE(0.10690483451),
+    SCALE(0.00080365466), SCALE(0.22311829031), SCALE(0.67219948769), SCALE(0.10390164703),
+    SCALE(0.00088037323), SCALE(0.22781492770), SCALE(0.67037439346), SCALE(0.10095486045),
+    SCALE(0.00096255314), SCALE(0.23255851865), SCALE(0.66844022274), SCALE(0.09806428105),
+    SCALE(0.00105048984), SCALE(0.23734821379), SCALE(0.66639786959), SCALE(0.09522963315),
+    SCALE(0.00114431616), SCALE(0.24218304455), SCALE(0.66424828768), SCALE(0.09245070815),
+    SCALE(0.00124442333), SCALE(0.24706205726), SCALE(0.66199249029), SCALE(0.08972713351),
+    SCALE(0.00135110028), SCALE(0.25198432803), SCALE(0.65963155031), SCALE(0.08705867827),
+    SCALE(0.00146482687), SCALE(0.25694879889), SCALE(0.65716648102), SCALE(0.08444493264),
+    SCALE(0.00158570008), SCALE(0.26195442677), SCALE(0.65459835529), SCALE(0.08188561350),
+    SCALE(0.00171401864), SCALE(0.26700007915), SCALE(0.65192854404), SCALE(0.07938029617),
+    SCALE(0.00185023469), SCALE(0.27208462358), SCALE(0.64915806055), SCALE(0.07692859322),
+    SCALE(0.00199495023), SCALE(0.27720692754), SCALE(0.64628833532), SCALE(0.07453006506),
+    SCALE(0.00214785640), SCALE(0.28236576915), SCALE(0.64332056046), SCALE(0.07218432426),
+    SCALE(0.00231004250), SCALE(0.28755992651), SCALE(0.64025616646), SCALE(0.06989086419),
+    SCALE(0.00248134881), SCALE(0.29278811812), SCALE(0.63709646463), SCALE(0.06764923781),
+    SCALE(0.00266251224), SCALE(0.29804900289), SCALE(0.63384294510), SCALE(0.06545893103),
+    SCALE(0.00285378192), SCALE(0.30334126949), SCALE(0.63049703836), SCALE(0.06331945211),
+    SCALE(0.00305565330), SCALE(0.30866351724), SCALE(0.62706029415), SCALE(0.06123027951),
+    SCALE(0.00326841651), SCALE(0.31401440501), SCALE(0.62353414297), SCALE(0.05919086933),
+    SCALE(0.00349264755), SCALE(0.31939238310), SCALE(0.61992025375), SCALE(0.05720067024),
+    SCALE(0.00372874714), SCALE(0.32479602098), SCALE(0.61622029543), SCALE(0.05525910854),
+    SCALE(0.00397720048), SCALE(0.33022382855), SCALE(0.61243581772), SCALE(0.05336561054),
+    SCALE(0.00423829490), SCALE(0.33567428589), SCALE(0.60856848955), SCALE(0.05151961371),
+    SCALE(0.00451271003), SCALE(0.34114575386), SCALE(0.60462015867), SCALE(0.04972046614),
+    SCALE(0.00480085658), SCALE(0.34663668275), SCALE(0.60059231520), SCALE(0.04796761274),
+    SCALE(0.00510312291), SCALE(0.35214546323), SCALE(0.59648692608), SCALE(0.04626038298),
+    SCALE(0.00542017492), SCALE(0.35767036676), SCALE(0.59230577946), SCALE(0.04459818453),
+    SCALE(0.00575236930), SCALE(0.36320972443), SCALE(0.58805054426), SCALE(0.04298033938),
+    SCALE(0.00610029325), SCALE(0.36876192689), SCALE(0.58372318745), SCALE(0.04140623659),
+    SCALE(0.00646453211), SCALE(0.37432509661), SCALE(0.57932555676), SCALE(0.03987516090),
+    SCALE(0.00684553990), SCALE(0.37989753485), SCALE(0.57485944033), SCALE(0.03838652745),
+    SCALE(0.00724391919), SCALE(0.38547745347), SCALE(0.57032698393), SCALE(0.03693958372),
+    SCALE(0.00766016589), SCALE(0.39106300473), SCALE(0.56572991610), SCALE(0.03553372994),
+    SCALE(0.00809498038), SCALE(0.39665243030), SCALE(0.56107026339), SCALE(0.03416819125),
+    SCALE(0.00854881573), SCALE(0.40224379301), SCALE(0.55634999275), SCALE(0.03284239396),
+    SCALE(0.00902230106), SCALE(0.40783521533), SCALE(0.55157101154), SCALE(0.03155555204),
+    SCALE(0.00951600447), SCALE(0.41342487931), SCALE(0.54673534632), SCALE(0.03030703776),
+    SCALE(0.01003060210), SCALE(0.41901078820), SCALE(0.54184508324), SCALE(0.02909611352),
+    SCALE(0.01056654565), SCALE(0.42459106445), SCALE(0.53690224886), SCALE(0.02792212367),
+    SCALE(0.01112466771), SCALE(0.43016362190), SCALE(0.53190881014), SCALE(0.02678431384),
+    SCALE(0.01170534454), SCALE(0.43572667241), SCALE(0.52686679363), SCALE(0.02568206564),
+    SCALE(0.01230939943), SCALE(0.44127810001), SCALE(0.52177828550), SCALE(0.02461459488),
+    SCALE(0.01293735672), SCALE(0.44681602716), SCALE(0.51664537191), SCALE(0.02358125709),
+    SCALE(0.01358995494), SCALE(0.45233830810), SCALE(0.51147013903), SCALE(0.02258131653),
+    SCALE(0.01426773332), SCALE(0.45784294605), SCALE(0.50625455379), SCALE(0.02161412500),
+    SCALE(0.01497144438), SCALE(0.46332800388), SCALE(0.50100076199), SCALE(0.02067894675),
+    SCALE(0.01570170000), SCALE(0.46879136562), SCALE(0.49571081996), SCALE(0.01977507770),
+    SCALE(0.01645922661), SCALE(0.47423094511), SCALE(0.49038675427), SCALE(0.01890186779),
+    SCALE(0.01724460535), SCALE(0.47964480519), SCALE(0.48503074050), SCALE(0.01805862412),
+};
+#undef SCALE
+
+
+#define SCALE(c) ((float)(c) / (256.0f * 32768.0f * 8388608.0f))
+DECLARE_ALIGNED(16, const float, ff_dca_lfe_xll_fir_64)[256] = {
+    SCALE(   6103), SCALE(  52170), SCALE(-558064), SCALE(1592440),
+    SCALE(6290049), SCALE(1502534), SCALE(-546669), SCALE(  53047),
+    SCALE(   1930), SCALE(  51089), SCALE(-568920), SCALE(1683709),
+    SCALE(6286575), SCALE(1414057), SCALE(-534782), SCALE(  53729),
+    SCALE(   2228), SCALE(  49794), SCALE(-579194), SCALE(1776276),
+    SCALE(6279634), SCALE(1327070), SCALE(-522445), SCALE(  54228),
+    SCALE(   2552), SCALE(  48275), SCALE(-588839), SCALE(1870070),
+    SCALE(6269231), SCALE(1241632), SCALE(-509702), SCALE(  54550),
+    SCALE(   2904), SCALE(  46523), SCALE(-597808), SCALE(1965017),
+    SCALE(6255380), SCALE(1157798), SCALE(-496595), SCALE(  54708),
+    SCALE(   3287), SCALE(  44529), SCALE(-606054), SCALE(2061044),
+    SCALE(6238099), SCALE(1075621), SCALE(-483164), SCALE(  54710),
+    SCALE(   3704), SCALE(  42282), SCALE(-613529), SCALE(2158071),
+    SCALE(6217408), SCALE( 995149), SCALE(-469451), SCALE(  54566),
+    SCALE(   4152), SCALE(  39774), SCALE(-620186), SCALE(2256019),
+    SCALE(6193332), SCALE( 916430), SCALE(-455494), SCALE(  54285),
+    SCALE(   4631), SCALE(  36995), SCALE(-625976), SCALE(2354805),
+    SCALE(6165900), SCALE( 839507), SCALE(-441330), SCALE(  53876),
+    SCALE(   5139), SCALE(  33937), SCALE(-630850), SCALE(2454343),
+    SCALE(6135146), SCALE( 764419), SCALE(-426998), SCALE(  53348),
+    SCALE(   5682), SCALE(  30591), SCALE(-634759), SCALE(2554547),
+    SCALE(6101107), SCALE( 691203), SCALE(-412531), SCALE(  52711),
+    SCALE(   6264), SCALE(  26948), SCALE(-637655), SCALE(2655326),
+    SCALE(6063824), SCALE( 619894), SCALE(-397966), SCALE(  51972),
+    SCALE(   6886), SCALE(  23001), SCALE(-639488), SCALE(2756591),
+    SCALE(6023343), SCALE( 550521), SCALE(-383335), SCALE(  51140),
+    SCALE(   7531), SCALE(  18741), SCALE(-640210), SCALE(2858248),
+    SCALE(5979711), SCALE( 483113), SCALE(-368671), SCALE(  50224),
+    SCALE(   8230), SCALE(  14162), SCALE(-639772), SCALE(2960201),
+    SCALE(5932981), SCALE( 417692), SCALE(-354003), SCALE(  49231),
+    SCALE(   8959), SCALE(   9257), SCALE(-638125), SCALE(3062355),
+    SCALE(5883210), SCALE( 354281), SCALE(-339362), SCALE(  48168),
+    SCALE(   9727), SCALE(   4018), SCALE(-635222), SCALE(3164612),
+    SCALE(5830457), SCALE( 292897), SCALE(-324777), SCALE(  47044),
+    SCALE(  10535), SCALE(  -1558), SCALE(-631014), SCALE(3266872),
+    SCALE(5774785), SCALE( 233555), SCALE(-310273), SCALE(  45866),
+    SCALE(  11381), SCALE(  -7480), SCALE(-625455), SCALE(3369035),
+    SCALE(5716260), SCALE( 176267), SCALE(-295877), SCALE(  44640),
+    SCALE(  12267), SCALE( -13750), SCALE(-618499), SCALE(3471000),
+    SCALE(5654952), SCALE( 121042), SCALE(-281613), SCALE(  43373),
+    SCALE(  13190), SCALE( -20372), SCALE(-610098), SCALE(3572664),
+    SCALE(5590933), SCALE(  67886), SCALE(-267505), SCALE(  42072),
+    SCALE(  14152), SCALE( -27352), SCALE(-600209), SCALE(3673924),
+    SCALE(5524280), SCALE(  16800), SCALE(-253574), SCALE(  40743),
+    SCALE(  15153), SCALE( -34691), SCALE(-588788), SCALE(3774676),
+    SCALE(5455069), SCALE( -32214), SCALE(-239840), SCALE(  39391),
+    SCALE(  16192), SCALE( -42390), SCALE(-575791), SCALE(3874816),
+    SCALE(5383383), SCALE( -79159), SCALE(-226323), SCALE(  38022),
+    SCALE(  17267), SCALE( -50453), SCALE(-561178), SCALE(3974239),
+    SCALE(5309305), SCALE(-124041), SCALE(-213041), SCALE(  36642),
+    SCALE(  18377), SCALE( -58879), SCALE(-544906), SCALE(4072841),
+    SCALE(5232922), SCALE(-166869), SCALE(-200010), SCALE(  35256),
+    SCALE(  19525), SCALE( -67667), SCALE(-526937), SCALE(4170517),
+    SCALE(5154321), SCALE(-207653), SCALE(-187246), SCALE(  33866),
+    SCALE(  20704), SCALE( -76817), SCALE(-507233), SCALE(4267162),
+    SCALE(5073593), SCALE(-246406), SCALE(-174764), SCALE(  32480),
+    SCALE(  21915), SCALE( -86327), SCALE(-485757), SCALE(4362672),
+    SCALE(4990831), SCALE(-283146), SCALE(-162575), SCALE(  31101),
+    SCALE(  23157), SCALE( -96193), SCALE(-462476), SCALE(4456942),
+    SCALE(4906129), SCALE(-317890), SCALE(-150692), SCALE(  29732),
+    SCALE(  24426), SCALE(-106412), SCALE(-437356), SCALE(4549871),
+    SCALE(4819584), SCALE(-350658), SCALE(-139125), SCALE(  28376),
+    SCALE(  25721), SCALE(-116977), SCALE(-410365), SCALE(4641355),
+    SCALE(4731293), SCALE(-381475), SCALE(-127884), SCALE(  27038),
+};
+#undef SCALE
+
+DECLARE_ALIGNED(16, const float, ff_dca_fir_64bands)[1024] = {
+    /* Bank 0 */
+    -7.1279389866041690e-8, -7.0950903150874990e-8,
+    -7.9525034321375090e-8, -8.9326871281374790e-8,
+    -9.7483190494874640e-8, -1.0586659510721950e-7,
+    -1.1527363411865760e-7, -1.2523109645615350e-7,
+    -1.3555636137971380e-7, -1.4640931821191640e-7,
+    -1.5787424998123710e-7, -1.6994592926571220e-7,
+    -1.8264184311018150e-7, -1.9600594587757850e-7,
+    -2.1007899706006800e-7, -2.2489759047553620e-7,
+    -2.4050245877923400e-7, -2.5693874615777660e-7,
+    -2.7425370308549580e-7, -2.9249662541757600e-7,
+    -3.1171981968268900e-7, -3.3197864040473180e-7,
+    -3.5333134588843600e-7, -3.7583910465412180e-7,
+    -3.9956628121669190e-7, -4.2458045296159330e-7,
+    -4.5095249563698380e-7, -4.7875659112606760e-7,
+    -5.0807031294631050e-7, -5.3897464223335550e-7,
+    -5.7155423388793000e-7, -6.0589741192019800e-7,
+    -6.4209580087853050e-7, -6.8024432849991400e-7,
+    -7.2044165259013450e-7, -7.6279018172077200e-7,
+    -8.0739610368280600e-7, -8.5436937020293650e-7,
+    -9.0382333224895500e-7, -9.5587472540498280e-7,
+    -1.0106437128213760e-6, -1.0682538906146330e-6,
+    -1.1288323637155430e-6, -1.1925097184646100e-6,
+    -1.2594193438633260e-6, -1.3296974052300520e-6,
+    -1.4034829433780260e-6, -1.4809178634979940e-6,
+    -1.5621465913980060e-6, -1.6473160377545360e-6,
+    -1.7365751553971340e-6, -1.8300749104526120e-6,
+    -1.9279680902322050e-6, -2.0304092660990760e-6,
+    -2.1375541686662320e-6, -2.2495596253776460e-6,
+    -2.3665828120950560e-6, -2.4887811970856540e-6,
+    -2.6163120571644820e-6, -2.7493324266391140e-6,
+    -2.8879984579501380e-6, -3.0324653639203880e-6,
+    -3.1828867865974640e-6, -3.3394147240855820e-6,
+    -3.5021985520037540e-6, -3.6713849262294680e-6,
+    -3.8471166218015830e-6, -4.0295324657699800e-6,
+    -4.2187670209852250e-6, -4.4149505043312320e-6,
+    -4.6182073040543900e-6, -4.8286558658894680e-6,
+    -5.0464076705003400e-6, -5.2715671455405850e-6,
+    -5.5042307535458100e-6, -5.7444868785028750e-6,
+    -5.9924142424804800e-6, -6.2480817863072800e-6,
+    -6.5115476278604000e-6, -6.7828589565804950e-6,
+    -7.0620507545154100e-6, -7.3491456697144900e-6,
+    -7.6441525098592000e-6, -7.9470661364365490e-6,
+    -8.2578666429227760e-6, -8.5765192154768100e-6,
+    -8.9029718900122000e-6, -9.2371554195468400e-6,
+    -9.5789825988253100e-6, -9.9283481667264540e-6,
+    -1.0285127334608450e-5, -1.0649175634328590e-5,
+    -1.1020327046334650e-5, -1.1398393880881060e-5,
+    -1.1783166036693560e-5, -1.2174410889256530e-5,
+    -1.2571871574469220e-5, -1.2975266858030310e-5,
+    -1.3384289978242060e-5, -1.3798608540965960e-5,
+    -1.4217863365843780e-5, -1.4641668383496450e-5,
+    -1.5069609527679710e-5, -1.5501244597782600e-5,
+    -1.5936101341640500e-5, -1.6373677426466900e-5,
+    -1.6813441716539560e-5, -1.7254834143068570e-5,
+    -1.7697261563607500e-5, -1.8140097714618200e-5,
+    -1.8582686308483550e-5, -1.9024340970099240e-5,
+    -1.9464340744880170e-5, -1.9901930030141080e-5,
+    -2.0336321557464510e-5, -2.0766696417773940e-5,
+    -2.1192201630574280e-5, -2.1611950084231910e-5,
+    -2.2025021652894630e-5, -2.2430463239517170e-5,
+    -2.2827288605503470e-5, -2.3214478371918170e-5,
+    -2.3590980216497750e-5, -2.3955708939763280e-5,
+    -2.4307547722489910e-5, -2.4645348200903720e-5,
+    -2.4967930863542620e-5, -2.5274085082324960e-5,
+    /* Bank 1 */
+     2.5562569399199020e-5,  2.5832111724562040e-5,
+     2.6081413415833200e-5,  2.6309149390520640e-5,
+     2.6513966535124460e-5,  2.6694483850464800e-5,
+     2.6849297239997120e-5,  2.6976979753245170e-5,
+     2.7076082153012070e-5,  2.7145133103663890e-5,
+     2.7182642746157720e-5,  2.7187102980536760e-5,
+     2.7156990105794550e-5,  2.7090765064735940e-5,
+     2.6986876191054700e-5,  2.6843759539035120e-5,
+     2.6659843389908530e-5,  2.6433548592482960e-5,
+     2.6163291550639320e-5,  2.5847484577439320e-5,
+     2.5484540698002960e-5,  2.5072874052447260e-5,
+     2.4610903957661350e-5,  2.4097055300584120e-5,
+     2.3529763128539150e-5,  2.2907473117403740e-5,
+     2.2228647280994560e-5,  2.1491764461832140e-5,
+     2.0695325418576370e-5,  1.9837853265502040e-5,
+    /* NOTE: The spec has a duplicated row "160 | 1.7934037335534700e-5" ! */
+     1.8917898053528080e-5,  1.7934037335534700e-5,
+     1.6884884022311310e-5,  1.5769086921577900e-5,
+     1.4585334740507920e-5,  1.3332356590263080e-5,
+     1.2008929083235120e-5,  1.0613876973541650e-5,
+     9.1460801506922300e-6,  7.6044740757265500e-6,
+     5.9880523825897000e-6,  4.2958677847708840e-6,
+     2.5270494199802070e-6,  6.8080315386959900e-7,
+    -1.2435990827839660e-6, -3.2468187066945930e-6,
+    -5.3294268968052800e-6, -7.4919036559427900e-6,
+    -9.7346407524871100e-6, -1.2057941408635810e-5,
+    -1.4462010500550970e-5, -1.6946953848107710e-5,
+    -1.9512772389215240e-5, -2.2159361597292710e-5,
+    -2.4886504491416160e-5, -2.7693871041862060e-5,
+    -3.0581012081916960e-5, -3.3547358765259040e-5,
+    -3.6592216716540970e-5, -3.9714765485539260e-5,
+    -4.2914052387856640e-5, -4.6188991961724560e-5,
+    -4.9538360176954340e-5, -5.2960794000140600e-5,
+    -5.6454787620185350e-5, -6.0018691972791050e-5,
+    -6.3650708053788550e-5, -6.7348886525882700e-5,
+    -7.1111125753722860e-5, -7.4935171411178040e-5,
+    -7.8818609806320000e-5, -8.2758867628623800e-5,
+    -8.6753213062403400e-5, -9.0798755482139240e-5,
+    -9.4892437636254000e-5, -9.9031035415475500e-5,
+    -1.0321116057304920e-4, -1.0742926070674010e-4,
+    -1.1168161614264270e-4, -1.1596433966772030e-4,
+    -1.2027337376184880e-4, -1.2460449089034750e-4,
+    -1.2895330270761850e-4, -1.3331525983885840e-4,
+    -1.3768563787408340e-4, -1.4205953760578120e-4,
+    -1.4643190426323540e-4, -1.5079752791692290e-4,
+    -1.5515103314094370e-4, -1.5948687909058970e-4,
+    -1.6379937154642740e-4, -1.6808266356446820e-4,
+    -1.7233075773584680e-4, -1.7653750646560020e-4,
+    -1.8069661584612290e-4, -1.8480164638953740e-4,
+    -1.8884602526638050e-4, -1.9282304696531290e-4,
+    -1.9672587556804270e-4, -2.0054754547108610e-4,
+    -2.0428097498957360e-4, -2.0791896735659270e-4,
+    -2.1145421910491280e-4, -2.1487932080488700e-4,
+    -2.1818676491655660e-4, -2.2136894706917190e-4,
+    -2.2441818635854840e-4, -2.2732672676686290e-4,
+    -2.3008674810081220e-4, -2.3269036653525150e-4,
+    -2.3512963563507800e-4, -2.3739654799291240e-4,
+    -2.3948307023621970e-4, -2.4138114593372380e-4,
+    -2.4308272452941820e-4, -2.4457975717687980e-4,
+    -2.4586407616017000e-4, -2.4692741569938220e-4,
+    -2.4776199025177680e-4, -2.4836046092637280e-4,
+    -2.4871461830381660e-4, -2.4881540457247040e-4,
+    -2.4865471770248810e-4, -2.4822543333608940e-4,
+    -2.4752008219951220e-4, -2.4653081794176570e-4,
+    -2.4525003217524440e-4, -2.4367037437341020e-4,
+    /* Bank 2 */
+     2.4178457457919800e-4,  2.3958543985834340e-4,
+     2.3706595356421380e-4,  2.3421928008696620e-4,
+     2.3103877007019660e-4,  2.2751796132972940e-4,
+     2.2365059385031200e-4,  2.1943061159567880e-4,
+     2.1485218733324290e-4,  2.0990972538755550e-4,
+     2.0459789739171640e-4,  1.9891164424316180e-4,
+     1.9284618337957900e-4,  1.8639701070854740e-4,
+     1.7955993578371750e-4,  1.7233108395155490e-4,
+     1.6470690840351980e-4,  1.5668419239382670e-4,
+     1.4826008597798460e-4,  1.3943210818407590e-4,
+     1.3019815804235450e-4,  1.2055651618705740e-4,
+     1.1050586906665980e-4,  1.0004531116378850e-4,
+     8.9174369623037550e-5,  7.7893006105444910e-5,
+     6.6201632959158800e-5,  5.4101115008963200e-5,
+     4.1592792755171040e-5,  2.8678484003389880e-5,
+     1.5360496520469550e-5,  1.6416297019304470e-6,
+    -1.2474801400564880e-5, -2.6984964757674160e-5,
+    -4.1884506316022560e-5, -5.7168548169515050e-5,
+    -7.2831653374563650e-5, -8.8867825335203200e-5,
+    -1.0527052946041040e-4, -1.2203269185287530e-4,
+    -1.3914664880465400e-4, -1.5660414556657680e-4,
+    -1.7439635977956720e-4, -1.9251390142613000e-4,
+    -2.1094678833176480e-4, -2.2968444457655940e-4,
+    -2.4871569004884240e-4, -2.6802874127778880e-4,
+    -2.8761124019708440e-4, -3.0745025297166030e-4,
+    -3.2753221542219500e-4, -3.4784293347385130e-4,
+    -3.6836764760397900e-4, -3.8909103335715320e-4,
+    -4.0999714822829530e-4, -4.3106943097409840e-4,
+    -4.5229073958127750e-4, -4.7364335350426610e-4,
+    -4.9510898492628230e-4, -5.1666877822680600e-4,
+    -5.3830328700499900e-4, -5.5999247625413450e-4,
+    -5.8171579317559550e-4, -6.0345216810040500e-4,
+    -6.2517996394886800e-4, -6.4687697763330650e-4,
+    -6.6852052145861900e-4, -6.9008742526480550e-4,
+    -7.1155400216196750e-4, -7.3289605035434600e-4,
+    -7.5408892753413600e-4, -7.7510755325530950e-4,
+    -7.9592638676398950e-4, -8.1651942936660300e-4,
+    -8.3686029869896850e-4, -8.5692223230171550e-4,
+    -8.7667809201044900e-4, -8.9610036547340950e-4,
+    -9.1516119514986000e-4, -9.3383238324995840e-4,
+    -9.5208547141354700e-4, -9.6989174214394400e-4,
+    -9.8722217067251400e-4, -1.0040474297445790e-3,
+    -1.0203380430448350e-3, -1.0360643900964910e-3,
+    -1.0511966606168980e-3, -1.0657048556038330e-3,
+    -1.0795588568782010e-3, -1.0927284332850520e-3,
+    -1.1051833075734240e-3, -1.1168931605293980e-3,
+    -1.1278276550234160e-3, -1.1379564405661050e-3,
+    -1.1472492294891640e-3, -1.1556758000499310e-3,
+    -1.1632059885511800e-3, -1.1698096960154200e-3,
+    -1.1754570428998680e-3, -1.1801183720212010e-3,
+    -1.1837641581852870e-3, -1.1863650153060240e-3,
+    -1.1878919433902330e-3, -1.1883163316843900e-3,
+    -1.1876097809178440e-3, -1.1857441072376680e-3,
+    -1.1826916065321440e-3, -1.1784250628415020e-3,
+    -1.1729176690707690e-3, -1.1661430294353880e-3,
+    -1.1580752925519680e-3, -1.1486891568700730e-3,
+    -1.1379598570807350e-3, -1.1258631690530700e-3,
+    -1.1123755320313420e-3, -1.0974740543942100e-3,
+    -1.0811365181610850e-3, -1.0633413819325920e-3,
+    -1.0440678410743190e-3, -1.0232958338441730e-3,
+    -1.0010061160103870e-3, -9.7718026613602800e-4,
+    -9.5180072722007060e-4, -9.2485080945546600e-4,
+    -8.9631470926558100e-4, -8.6617751390929650e-4,
+    -8.3442528375666700e-4, -8.0104505655578600e-4,
+    /* Bank 3 */
+     7.6602485902806300e-4,  7.2935371157849700e-4,
+     6.9102172032639350e-4,  6.5102007948960100e-4,
+     6.0934103180698750e-4,  5.6597787244591100e-4,
+     5.2092507454409450e-4,  4.7417829303612970e-4,
+     4.2573432329476060e-4,  3.7559110239316400e-4,
+     3.2374777823389440e-4,  2.7020471361387040e-4,
+     2.1496350652513040e-4,  1.5802699163104190e-4,
+     9.9399252442146460e-5,  3.9085623279149610e-5,
+    -2.2907279717153710e-5, -8.6571556658577800e-5,
+    -1.5189801251884410e-4, -2.1887615668780720e-4,
+    -2.8749420455512610e-4, -3.5773907519488100e-4,
+    -4.2959633884346400e-4, -5.0305021853266900e-4,
+    -5.7808367853976800e-4, -6.5467842279709950e-4,
+    -7.3281477145293300e-4, -8.1247166091487090e-4,
+    -8.9362676824381250e-4, -9.7625651350435400e-4,
+    -1.0603359870796300e-3, -1.1458389497708370e-3,
+    -1.2327379076720450e-3, -1.3210041125919850e-3,
+    -1.4106074964587530e-3, -1.5015166759080980e-3,
+    -1.5936991188210680e-3, -1.6871211446584360e-3,
+    -1.7817477652804130e-3, -1.8775426862784720e-3,
+    -1.9744684954557180e-3, -2.0724866717198650e-3,
+    -2.1715575922482770e-3, -2.2716405301701940e-3,
+    -2.3726935964105480e-3, -2.4746737418493600e-3,
+    -2.5775368629845300e-3, -2.6812378156433060e-3,
+    -2.7857306109716460e-3, -2.8909684129992950e-3,
+    -2.9969032890820140e-3, -3.1034862132032660e-3,
+    -3.2106673881690480e-3, -3.3183962566563890e-3,
+    -3.4266214220855450e-3, -3.5352906520539890e-3,
+    -3.6443510330122110e-3, -3.7537489709635930e-3,
+    -3.8634300521859240e-3, -3.9733390588103910e-3,
+    -4.0834204508378470e-3, -4.1936183686073460e-3,
+    -4.3038762050876900e-3, -4.4141366059086620e-3,
+    -4.5243418977567100e-3, -4.6344341075783170e-3,
+    -4.7443549566589130e-3, -4.8540458565358850e-3,
+    -4.9634478250060780e-3, -5.0725014978718950e-3,
+    -5.1811474713480250e-3, -5.2893263173827950e-3,
+    -5.3969785783205650e-3, -5.5040447592375600e-3,
+    -5.6104651646665850e-3, -5.7161799140263450e-3,
+    -5.8211294443412250e-3, -5.9252545216101900e-3,
+    -6.0284959882028950e-3, -6.1307947602360250e-3,
+    -6.2320920224565700e-3, -6.3323292492425800e-3,
+    -6.4314484717364400e-3, -6.5293922762311450e-3,
+    -6.6261035015351700e-3, -6.7215252466922100e-3,
+    -6.8156013434509950e-3, -6.9082763630156450e-3,
+    -6.9994952920827200e-3, -7.0892035490577050e-3,
+    -7.1773476647806300e-3, -7.2638752839566550e-3,
+    -7.3487345159041400e-3, -7.4318739341000500e-3,
+    -7.5132432154309250e-3, -7.5927931627681400e-3,
+    -7.6704755623721500e-3, -7.7462431738117650e-3,
+    -7.8200496507836000e-3, -7.8918495587816850e-3,
+    -7.9615988430090790e-3, -8.0292548409052500e-3,
+    -8.0947760898363200e-3, -8.1581223027535600e-3,
+    -8.2192540249893810e-3, -8.2781326752680240e-3,
+    -8.3347217911436610e-3, -8.3889870206274740e-3,
+    -8.4408946925453690e-3, -8.4904118087845760e-3,
+    -8.5375073033623590e-3, -8.5821520672029750e-3,
+    -8.6243182341614300e-3, -8.6639791627160300e-3,
+    -8.7011097471794110e-3, -8.7356864659172800e-3,
+    -8.7676881309490440e-3, -8.7970958152554810e-3,
+    -8.8238905039462850e-3, -8.8480531477483150e-3,
+    -8.8695681885783190e-3, -8.8884235927356400e-3,
+    -8.9046080555685600e-3, -8.9181109318560050e-3,
+    -8.9289234995380550e-3, -8.9370390010903460e-3,
+    -8.9424522900292110e-3, -8.9451598223763610e-3,
+    /* Bank 4 */
+     8.9451598223763610e-3,  8.9424522900292110e-3,
+     8.9370390010903460e-3,  8.9289234995380550e-3,
+     8.9181109318560050e-3,  8.9046080555685600e-3,
+     8.8884235927356400e-3,  8.8695681885783190e-3,
+     8.8480531477483150e-3,  8.8238905039462850e-3,
+     8.7970958152554810e-3,  8.7676881309490440e-3,
+     8.7356864659172800e-3,  8.7011097471794110e-3,
+     8.6639791627160300e-3,  8.6243182341614300e-3,
+     8.5821520672029750e-3,  8.5375073033623590e-3,
+     8.4904118087845760e-3,  8.4408946925453690e-3,
+     8.3889870206274740e-3,  8.3347217911436610e-3,
+     8.2781326752680240e-3,  8.2192540249893810e-3,
+     8.1581223027535600e-3,  8.0947760898363200e-3,
+     8.0292548409052500e-3,  7.9615988430090790e-3,
+     7.8918495587816850e-3,  7.8200496507836000e-3,
+     7.7462431738117650e-3,  7.6704755623721500e-3,
+     7.5927931627681400e-3,  7.5132432154309250e-3,
+     7.4318739341000500e-3,  7.3487345159041400e-3,
+     7.2638752839566550e-3,  7.1773476647806300e-3,
+     7.0892035490577050e-3,  6.9994952920827200e-3,
+     6.9082763630156450e-3,  6.8156013434509950e-3,
+     6.7215252466922100e-3,  6.6261035015351700e-3,
+     6.5293922762311450e-3,  6.4314484717364400e-3,
+     6.3323292492425800e-3,  6.2320920224565700e-3,
+     6.1307947602360250e-3,  6.0284959882028950e-3,
+     5.9252545216101900e-3,  5.8211294443412250e-3,
+     5.7161799140263450e-3,  5.6104651646665850e-3,
+     5.5040447592375600e-3,  5.3969785783205650e-3,
+     5.2893263173827950e-3,  5.1811474713480250e-3,
+     5.0725014978718950e-3,  4.9634478250060780e-3,
+     4.8540458565358850e-3,  4.7443549566589130e-3,
+     4.6344341075783170e-3,  4.5243418977567100e-3,
+     4.4141366059086620e-3,  4.3038762050876900e-3,
+     4.1936183686073460e-3,  4.0834204508378470e-3,
+     3.9733390588103910e-3,  3.8634300521859240e-3,
+     3.7537489709635930e-3,  3.6443510330122110e-3,
+     3.5352906520539890e-3,  3.4266214220855450e-3,
+     3.3183962566563890e-3,  3.2106673881690480e-3,
+     3.1034862132032660e-3,  2.9969032890820140e-3,
+     2.8909684129992950e-3,  2.7857306109716460e-3,
+     2.6812378156433060e-3,  2.5775368629845300e-3,
+     2.4746737418493600e-3,  2.3726935964105480e-3,
+     2.2716405301701940e-3,  2.1715575922482770e-3,
+     2.0724866717198650e-3,  1.9744684954557180e-3,
+     1.8775426862784720e-3,  1.7817477652804130e-3,
+     1.6871211446584360e-3,  1.5936991188210680e-3,
+     1.5015166759080980e-3,  1.4106074964587530e-3,
+     1.3210041125919850e-3,  1.2327379076720450e-3,
+     1.1458389497708370e-3,  1.0603359870796300e-3,
+     9.7625651350435400e-4,  8.9362676824381250e-4,
+     8.1247166091487090e-4,  7.3281477145293300e-4,
+     6.5467842279709950e-4,  5.7808367853976800e-4,
+     5.0305021853266900e-4,  4.2959633884346400e-4,
+     3.5773907519488100e-4,  2.8749420455512610e-4,
+     2.1887615668780720e-4,  1.5189801251884410e-4,
+     8.6571556658577800e-5,  2.2907279717153710e-5,
+    -3.9085623279149610e-5, -9.9399252442146460e-5,
+    -1.5802699163104190e-4, -2.1496350652513040e-4,
+    -2.7020471361387040e-4, -3.2374777823389440e-4,
+    -3.7559110239316400e-4, -4.2573432329476060e-4,
+    -4.7417829303612970e-4, -5.2092507454409450e-4,
+    -5.6597787244591100e-4, -6.0934103180698750e-4,
+    -6.5102007948960100e-4, -6.9102172032639350e-4,
+    -7.2935371157849700e-4, -7.6602485902806300e-4,
+    /* Bank 5 */
+     8.0104505655578600e-4,  8.3442528375666700e-4,
+     8.6617751390929650e-4,  8.9631470926558100e-4,
+     9.2485080945546600e-4,  9.5180072722007060e-4,
+     9.7718026613602800e-4,  1.0010061160103870e-3,
+     1.0232958338441730e-3,  1.0440678410743190e-3,
+     1.0633413819325920e-3,  1.0811365181610850e-3,
+     1.0974740543942100e-3,  1.1123755320313420e-3,
+     1.1258631690530700e-3,  1.1379598570807350e-3,
+     1.1486891568700730e-3,  1.1580752925519680e-3,
+     1.1661430294353880e-3,  1.1729176690707690e-3,
+     1.1784250628415020e-3,  1.1826916065321440e-3,
+     1.1857441072376680e-3,  1.1876097809178440e-3,
+     1.1883163316843900e-3,  1.1878919433902330e-3,
+     1.1863650153060240e-3,  1.1837641581852870e-3,
+     1.1801183720212010e-3,  1.1754570428998680e-3,
+     1.1698096960154200e-3,  1.1632059885511800e-3,
+     1.1556758000499310e-3,  1.1472492294891640e-3,
+     1.1379564405661050e-3,  1.1278276550234160e-3,
+     1.1168931605293980e-3,  1.1051833075734240e-3,
+     1.0927284332850520e-3,  1.0795588568782010e-3,
+     1.0657048556038330e-3,  1.0511966606168980e-3,
+     1.0360643900964910e-3,  1.0203380430448350e-3,
+     1.0040474297445790e-3,  9.8722217067251400e-4,
+     9.6989174214394400e-4,  9.5208547141354700e-4,
+     9.3383238324995840e-4,  9.1516119514986000e-4,
+     8.9610036547340950e-4,  8.7667809201044900e-4,
+     8.5692223230171550e-4,  8.3686029869896850e-4,
+     8.1651942936660300e-4,  7.9592638676398950e-4,
+     7.7510755325530950e-4,  7.5408892753413600e-4,
+     7.3289605035434600e-4,  7.1155400216196750e-4,
+     6.9008742526480550e-4,  6.6852052145861900e-4,
+     6.4687697763330650e-4,  6.2517996394886800e-4,
+     6.0345216810040500e-4,  5.8171579317559550e-4,
+     5.5999247625413450e-4,  5.3830328700499900e-4,
+     5.1666877822680600e-4,  4.9510898492628230e-4,
+     4.7364335350426610e-4,  4.5229073958127750e-4,
+     4.3106943097409840e-4,  4.0999714822829530e-4,
+     3.8909103335715320e-4,  3.6836764760397900e-4,
+     3.4784293347385130e-4,  3.2753221542219500e-4,
+     3.0745025297166030e-4,  2.8761124019708440e-4,
+     2.6802874127778880e-4,  2.4871569004884240e-4,
+     2.2968444457655940e-4,  2.1094678833176480e-4,
+     1.9251390142613000e-4,  1.7439635977956720e-4,
+     1.5660414556657680e-4,  1.3914664880465400e-4,
+     1.2203269185287530e-4,  1.0527052946041040e-4,
+     8.8867825335203200e-5,  7.2831653374563650e-5,
+     5.7168548169515050e-5,  4.1884506316022560e-5,
+     2.6984964757674160e-5,  1.2474801400564880e-5,
+    -1.6416297019304470e-6, -1.5360496520469550e-5,
+    -2.8678484003389880e-5, -4.1592792755171040e-5,
+    -5.4101115008963200e-5, -6.6201632959158800e-5,
+    -7.7893006105444910e-5, -8.9174369623037550e-5,
+    -1.0004531116378850e-4, -1.1050586906665980e-4,
+    -1.2055651618705740e-4, -1.3019815804235450e-4,
+    -1.3943210818407590e-4, -1.4826008597798460e-4,
+    -1.5668419239382670e-4, -1.6470690840351980e-4,
+    -1.7233108395155490e-4, -1.7955993578371750e-4,
+    -1.8639701070854740e-4, -1.9284618337957900e-4,
+    -1.9891164424316180e-4, -2.0459789739171640e-4,
+    -2.0990972538755550e-4, -2.1485218733324290e-4,
+    -2.1943061159567880e-4, -2.2365059385031200e-4,
+    -2.2751796132972940e-4, -2.3103877007019660e-4,
+    -2.3421928008696620e-4, -2.3706595356421380e-4,
+    -2.3958543985834340e-4, -2.4178457457919800e-4,
+    /* Bank 6 */
+     2.4367037437341020e-4,  2.4525003217524440e-4,
+     2.4653081794176570e-4,  2.4752008219951220e-4,
+     2.4822543333608940e-4,  2.4865471770248810e-4,
+     2.4881540457247040e-4,  2.4871461830381660e-4,
+     2.4836046092637280e-4,  2.4776199025177680e-4,
+     2.4692741569938220e-4,  2.4586407616017000e-4,
+     2.4457975717687980e-4,  2.4308272452941820e-4,
+     2.4138114593372380e-4,  2.3948307023621970e-4,
+     2.3739654799291240e-4,  2.3512963563507800e-4,
+     2.3269036653525150e-4,  2.3008674810081220e-4,
+     2.2732672676686290e-4,  2.2441818635854840e-4,
+     2.2136894706917190e-4,  2.1818676491655660e-4,
+     2.1487932080488700e-4,  2.1145421910491280e-4,
+     2.0791896735659270e-4,  2.0428097498957360e-4,
+     2.0054754547108610e-4,  1.9672587556804270e-4,
+     1.9282304696531290e-4,  1.8884602526638050e-4,
+     1.8480164638953740e-4,  1.8069661584612290e-4,
+     1.7653750646560020e-4,  1.7233075773584680e-4,
+     1.6808266356446820e-4,  1.6379937154642740e-4,
+     1.5948687909058970e-4,  1.5515103314094370e-4,
+     1.5079752791692290e-4,  1.4643190426323540e-4,
+     1.4205953760578120e-4,  1.3768563787408340e-4,
+     1.3331525983885840e-4,  1.2895330270761850e-4,
+     1.2460449089034750e-4,  1.2027337376184880e-4,
+     1.1596433966772030e-4,  1.1168161614264270e-4,
+     1.0742926070674010e-4,  1.0321116057304920e-4,
+     9.9031035415475500e-5,  9.4892437636254000e-5,
+     9.0798755482139240e-5,  8.6753213062403400e-5,
+     8.2758867628623800e-5,  7.8818609806320000e-5,
+     7.4935171411178040e-5,  7.1111125753722860e-5,
+     6.7348886525882700e-5,  6.3650708053788550e-5,
+     6.0018691972791050e-5,  5.6454787620185350e-5,
+     5.2960794000140600e-5,  4.9538360176954340e-5,
+     4.6188991961724560e-5,  4.2914052387856640e-5,
+     3.9714765485539260e-5,  3.6592216716540970e-5,
+     3.3547358765259040e-5,  3.0581012081916960e-5,
+     2.7693871041862060e-5,  2.4886504491416160e-5,
+     2.2159361597292710e-5,  1.9512772389215240e-5,
+     1.6946953848107710e-5,  1.4462010500550970e-5,
+     1.2057941408635810e-5,  9.7346407524871100e-6,
+     7.4919036559427900e-6,  5.3294268968052800e-6,
+     3.2468187066945930e-6,  1.2435990827839660e-6,
+    -6.8080315386959900e-7, -2.5270494199802070e-6,
+    -4.2958677847708840e-6, -5.9880523825897000e-6,
+    -7.6044740757265500e-6, -9.1460801506922300e-6,
+    -1.0613876973541650e-5, -1.2008929083235120e-5,
+    -1.3332356590263080e-5, -1.4585334740507920e-5,
+    -1.5769086921577900e-5, -1.6884884022311310e-5,
+    -1.7934037335534700e-5, -1.8917898053528080e-5,
+    -1.9837853265502040e-5, -2.0695325418576370e-5,
+    -2.1491764461832140e-5, -2.2228647280994560e-5,
+    -2.2907473117403740e-5, -2.3529763128539150e-5,
+    -2.4097055300584120e-5, -2.4610903957661350e-5,
+    -2.5072874052447260e-5, -2.5484540698002960e-5,
+    -2.5847484577439320e-5, -2.6163291550639320e-5,
+    -2.6433548592482960e-5, -2.6659843389908530e-5,
+    -2.6843759539035120e-5, -2.6986876191054700e-5,
+    -2.7090765064735940e-5, -2.7156990105794550e-5,
+    -2.7187102980536760e-5, -2.7182642746157720e-5,
+    -2.7145133103663890e-5, -2.7076082153012070e-5,
+    -2.6976979753245170e-5, -2.6849297239997120e-5,
+    -2.6694483850464800e-5, -2.6513966535124460e-5,
+    -2.6309149390520640e-5, -2.6081413415833200e-5,
+    -2.5832111724562040e-5, -2.5562569399199020e-5,
+    /* Bank 7 */
+     2.5274085082324960e-5,  2.4967930863542620e-5,
+     2.4645348200903720e-5,  2.4307547722489910e-5,
+     2.3955708939763280e-5,  2.3590980216497750e-5,
+     2.3214478371918170e-5,  2.2827288605503470e-5,
+     2.2430463239517170e-5,  2.2025021652894630e-5,
+     2.1611950084231910e-5,  2.1192201630574280e-5,
+     2.0766696417773940e-5,  2.0336321557464510e-5,
+     1.9901930030141080e-5,  1.9464340744880170e-5,
+     1.9024340970099240e-5,  1.8582686308483550e-5,
+     1.8140097714618200e-5,  1.7697261563607500e-5,
+     1.7254834143068570e-5,  1.6813441716539560e-5,
+     1.6373677426466900e-5,  1.5936101341640500e-5,
+     1.5501244597782600e-5,  1.5069609527679710e-5,
+     1.4641668383496450e-5,  1.4217863365843780e-5,
+     1.3798608540965960e-5,  1.3384289978242060e-5,
+     1.2975266858030310e-5,  1.2571871574469220e-5,
+     1.2174410889256530e-5,  1.1783166036693560e-5,
+     1.1398393880881060e-5,  1.1020327046334650e-5,
+     1.0649175634328590e-5,  1.0285127334608450e-5,
+     9.9283481667264540e-6,  9.5789825988253100e-6,
+     9.2371554195468400e-6,  8.9029718900122000e-6,
+     8.5765192154768100e-6,  8.2578666429227760e-6,
+     7.9470661364365490e-6,  7.6441525098592000e-6,
+     7.3491456697144900e-6,  7.0620507545154100e-6,
+     6.7828589565804950e-6,  6.5115476278604000e-6,
+     6.2480817863072800e-6,  5.9924142424804800e-6,
+     5.7444868785028750e-6,  5.5042307535458100e-6,
+     5.2715671455405850e-6,  5.0464076705003400e-6,
+     4.8286558658894680e-6,  4.6182073040543900e-6,
+     4.4149505043312320e-6,  4.2187670209852250e-6,
+     4.0295324657699800e-6,  3.8471166218015830e-6,
+     3.6713849262294680e-6,  3.5021985520037540e-6,
+     3.3394147240855820e-6,  3.1828867865974640e-6,
+     3.0324653639203880e-6,  2.8879984579501380e-6,
+     2.7493324266391140e-6,  2.6163120571644820e-6,
+     2.4887811970856540e-6,  2.3665828120950560e-6,
+     2.2495596253776460e-6,  2.1375541686662320e-6,
+     2.0304092660990760e-6,  1.9279680902322050e-6,
+     1.8300749104526120e-6,  1.7365751553971340e-6,
+     1.6473160377545360e-6,  1.5621465913980060e-6,
+     1.4809178634979940e-6,  1.4034829433780260e-6,
+     1.3296974052300520e-6,  1.2594193438633260e-6,
+     1.1925097184646100e-6,  1.1288323637155430e-6,
+     1.0682538906146330e-6,  1.0106437128213760e-6,
+     9.5587472540498280e-7,  9.0382333224895500e-7,
+     8.5436937020293650e-7,  8.0739610368280600e-7,
+     7.6279018172077200e-7,  7.2044165259013450e-7,
+     6.8024432849991400e-7,  6.4209580087853050e-7,
+     6.0589741192019800e-7,  5.7155423388793000e-7,
+     5.3897464223335550e-7,  5.0807031294631050e-7,
+     4.7875659112606760e-7,  4.5095249563698380e-7,
+     4.2458045296159330e-7,  3.9956628121669190e-7,
+     3.7583910465412180e-7,  3.5333134588843600e-7,
+     3.3197864040473180e-7,  3.1171981968268900e-7,
+     2.9249662541757600e-7,  2.7425370308549580e-7,
+     2.5693874615777660e-7,  2.4050245877923400e-7,
+     2.2489759047553620e-7,  2.1007899706006800e-7,
+     1.9600594587757850e-7,  1.8264184311018150e-7,
+     1.6994592926571220e-7,  1.5787424998123710e-7,
+     1.4640931821191640e-7,  1.3555636137971380e-7,
+     1.2523109645615350e-7,  1.1527363411865760e-7,
+     1.0586659510721950e-7,  9.7483190494874640e-8,
+     8.9326871281374790e-8,  7.9525034321375090e-8,
+     7.0950903150874990e-8,  7.1279389866041690e-8,
+};
+
+/*
+ * D.11 Look-up Table for Downmix Scale Factors
+ *
+ * Note that the range of the entries in DmixTable[] is between -60 dB and 0 dB
+ * with addition of -inf (|DMixCoeff| = 0), which is coded with a DmixCode = 0.
+ * Furthermore, the range [-60 to 0] is subdivided into 3 regions, each with a
+ * different grid resolution:
+ *
+ * 1) [-60.000 to -30] with resolution of 0.500 dB
+ * 2) [-29.750 to -15] with resolution of 0.250 dB
+ * 3) [-14.875 to   0] with resolution of 0.125 dB
+ */
+const uint16_t ff_dca_dmixtable[FF_DCA_DMIXTABLE_SIZE] = {
+        0,    33,    35,    37,    39,    41,    44,    46,
+       49,    52,    55,    58,    62,    65,    69,    73,
+       78,    82,    87,    92,    98,   104,   110,   116,
+      123,   130,   138,   146,   155,   164,   174,   184,
+      195,   207,   219,   232,   246,   260,   276,   292,
+      309,   328,   347,   368,   389,   413,   437,   463,
+      490,   519,   550,   583,   617,   654,   693,   734,
+      777,   823,   872,   924,   978,  1036,  1066,  1098,
+     1130,  1163,  1197,  1232,  1268,  1305,  1343,  1382,
+     1422,  1464,  1506,  1550,  1596,  1642,  1690,  1740,
+     1790,  1843,  1896,  1952,  2009,  2068,  2128,  2190,
+     2254,  2320,  2388,  2457,  2529,  2603,  2679,  2757,
+     2838,  2920,  3006,  3093,  3184,  3277,  3372,  3471,
+     3572,  3677,  3784,  3894,  4008,  4125,  4246,  4370,
+     4497,  4629,  4764,  4903,  5046,  5193,  5345,  5501,
+     5662,  5827,  5912,  5997,  6084,  6172,  6262,  6353,
+     6445,  6538,  6633,  6729,  6827,  6925,  7026,  7128,
+     7231,  7336,  7442,  7550,  7659,  7771,  7883,  7997,
+     8113,  8231,  8350,  8471,  8594,  8719,  8845,  8973,
+     9103,  9235,  9369,  9505,  9643,  9783,  9924, 10068,
+    10214, 10362, 10512, 10665, 10819, 10976, 11135, 11297,
+    11460, 11627, 11795, 11966, 12139, 12315, 12494, 12675,
+    12859, 13045, 13234, 13426, 13621, 13818, 14018, 14222,
+    14428, 14637, 14849, 15064, 15283, 15504, 15729, 15957,
+    16188, 16423, 16661, 16902, 17147, 17396, 17648, 17904,
+    18164, 18427, 18694, 18965, 19240, 19519, 19802, 20089,
+    20380, 20675, 20975, 21279, 21587, 21900, 22218, 22540,
+    22867, 23170, 23534, 23875, 24221, 24573, 24929, 25290,
+    25657, 26029, 26406, 26789, 27177, 27571, 27970, 28376,
+    28787, 29205, 29628, 30057, 30493, 30935, 31383, 31838,
+    32300, 32768,
+};
+
+const uint32_t ff_dca_inv_dmixtable[FF_DCA_INV_DMIXTABLE_SIZE] = {
+    6553600, 6186997, 5840902, 5514167, 5205710, 4914507, 4639593, 4380059,
+    4135042, 3903731, 3685360, 3479204, 3284581, 3100844, 2927386, 2763630,
+    2609035, 2463088, 2325305, 2195230, 2072430, 2013631, 1956500, 1900990,
+    1847055, 1794651, 1743733, 1694260, 1646190, 1599484, 1554103, 1510010,
+    1467168, 1425542, 1385096, 1345798, 1307615, 1270515, 1234468, 1199444,
+    1165413, 1132348, 1100221, 1069005, 1038676, 1009206,  980573,  952752,
+     925721,  899456,  873937,  849141,  825049,  801641,  778897,  756798,
+     735326,  714463,  694193,  674497,  655360,  636766,  618700,  601146,
+     584090,  567518,  551417,  535772,  520571,  505801,  491451,  477507,
+     463959,  450796,  438006,  425579,  413504,  401772,  390373,  379297,
+     368536,  363270,  358080,  352964,  347920,  342949,  338049,  333219,
+     328458,  323765,  319139,  314579,  310084,  305654,  301287,  296982,
+     292739,  288556,  284433,  280369,  276363,  272414,  268522,  264685,
+     260904,  257176,  253501,  249879,  246309,  242790,  239321,  235901,
+     232531,  229208,  225933,  222705,  219523,  216386,  213295,  210247,
+     207243,  204282,  201363,  198486,  195650,  192855,  190099,  187383,
+     184706,  182066,  179465,  176901,  174373,  171882,  169426,  167005,
+     164619,  162267,  159948,  157663,  155410,  153190,  151001,  148844,
+     146717,  144621,  142554,  140517,  138510,  136531,  134580,  132657,
+     130762,  128893,  127052,  125236,  123447,  121683,  119944,  118231,
+     116541,  114876,  113235,  111617,  110022,  108450,  106901,  105373,
+     103868,  102383,  100921,   99479,   98057,   96656,   95275,   93914,
+      92682,   91249,   89946,   88660,   87394,   86145,   84914,   83701,
+      82505,   81326,   80164,   79019,   77890,   76777,   75680,   74598,
+      73533,   72482,   71446,   70425,   69419,   68427,   67450,   66486,
+      65536,
+};
+
+const float ff_dca_default_coeffs[10][6][2] = {
+    { { 0.707107, 0.707107 }, { 0.000000, 0.000000 },                                                                                                 }, // A [LFE]
+    { { 1.000000, 0.000000 }, { 0.000000, 1.000000 }, { 0.000000, 0.000000 },                                                                         }, // A + B (dual mono) [LFE]
+    { { 1.000000, 0.000000 }, { 0.000000, 1.000000 }, { 0.000000, 0.000000 },                                                                         }, // L + R (stereo) [LFE]
+    { { 1.000000, 0.000000 }, { 0.000000, 1.000000 }, { 0.000000, 0.000000 },                                                                         }, // (L+R) + (L-R) (sum-difference) [LFE]
+    { { 1.000000, 0.000000 }, { 0.000000, 1.000000 }, { 0.000000, 0.000000 },                                                                         }, // LT + RT (left and right total) [LFE]
+    { { 0.501187, 0.501187 }, { 0.707107, 0.000000 }, { 0.000000, 0.707107 }, { 0.000000, 0.000000 },                                                 }, // C + L + R [LFE]
+    { { 0.707107, 0.000000 }, { 0.000000, 0.707107 }, { 0.501187, 0.501187 }, { 0.000000, 0.000000 },                                                 }, // L + R + S [LFE]
+    { { 0.501187, 0.501187 }, { 0.707107, 0.000000 }, { 0.000000, 0.707107 }, { 0.501187, 0.501187 }, { 0.000000, 0.000000 },                         }, // C + L + R + S [LFE]
+    { { 0.707107, 0.000000 }, { 0.000000, 0.707107 }, { 0.501187, 0.000000 }, { 0.000000, 0.501187 }, { 0.000000, 0.000000 },                         }, // L + R + SL + SR [LFE]
+    { { 0.501187, 0.501187 }, { 0.707107, 0.000000 }, { 0.000000, 0.707107 }, { 0.501187, 0.000000 }, { 0.000000, 0.501187 }, { 0.000000, 0.000000 }, }, // C + L + R + SL + SR [LFE]
+};
+
+const int32_t ff_dca_sampling_freqs[16] = {
+      8000,  16000, 32000, 64000, 128000, 22050,  44100,  88200,
+    176400, 352800, 12000, 24000,  48000, 96000, 192000, 384000,
+};
+
+/* downmix coeffs
+ *
+ * TABLE 9
+ * ______________________________________
+ * Down-mix coefficients for 8-channel source
+ * audio (5 + 3 format)
+ * lt
+ * cen- rt lt ctr rt
+ * lt ter ctr center
+ * rt srd srd srd
+ * ______________________________________
+ * 1 0.71 0.74 1.0 0.71 0.71 0.58 0.58 0.58
+ * 2 left 1.0 0.89 0.71 0.46 0.71 0.50
+ * rt 0.45 0.71 0.89 1.0 0.50 0.71
+ * 3 lt 1.0 0.89 0.71 0.45
+ * rt 0.45 0.71 0.89 1.0
+ * srd 0.71 0.71 0.71
+ * 4 lt 1.0 0.89 0.71 0.45
+ * rt 0.45 0.71 0.89 1.0
+ * lt srd 1.0 0.71
+ * rt srd 0.71 0.71
+ * 4 lt 1.0 0.5
+ * ctr 0.87 1.0 0.87
+ * rt 0.5 1.0
+ * srd 0.71 0.71 0.71
+ * 5 lt 1.0 0.5
+ * ctr 0.87 1.0 0.87
+ * rt 0.5 1.0
+ * lt srd 1.0 0.71
+ * rt srd 0.71 1.0
+ * 6 lt 1.0 0.5
+ * lt ctr 0.87 0.71
+ * rt ctr 0.71 0.87
+ * rt 0.5 1.0
+ * lt srd 1.0 0.71
+ * rt srd 0.71 1.0
+ * 6 lt 1.0 0.5
+ * ctr 0.86 1.0 0.86
+ * rt 0.5 1.0
+ * lt srd 1.0
+ * ctr srd 1.0
+ * rt srd 1.0
+ * 7 lt 1.0
+ * lt ctr 1.0
+ * ctr 1.0
+ * rt ctr 1.0
+ * rt 1.0
+ * lt srd 1.0 0.71
+ * rt srd 0.71 1.0
+ * 7 lt 1.0 0.5
+ * lt ctr 0.87 0.71
+ * rt ctr 0.71 0.87
+ * rt 0.5 1.0
+ * lt srd 1.0
+ * ctr srd 1.0
+ * rt srd 1.0
+ * 8 lt 1.0 0.5
+ * lt ctr 0.87 0.71
+ * rt ctr 0.71 0.87
+ * rt 0.5 1.0
+ * lt 1 srd 0.87 0.35
+ * lt 2 srd 0.5 0.61
+ * rt 2 srd 0.61 0.50
+ * rt 2 srd 0.35 0.87
+ *
+ * Generation of Lt Rt
+ *
+ * In the case when the playback system has analog or digital surround
+ * multi-channel capability, a down matrix from 5, 4, or 3 channel to
+ * Lt Rt may be desirable. In the case when the number of decoded audio
+ * channels exceeds 5, 4 or 3 respectively a first stage down mix to 5,
+ * 4 or 3 chs should be used as described above.
+ *
+ * The down matrixing equations for 5-channel source audio to a
+ * two-channel Lt Rt playback system are given by:
+ *
+ * Left  = left  + 0.7 * center - 0.7 * (lt surround + rt surround)
+ *
+ * Right = right + 0.7 * center + 0.7 * (lt surround + rt surround)
+ *
+ * Embedded mixing to 2-channel
+ *
+ * One concern arising from the proliferation of multi-channel audio
+ * systems is that most home systems presently have only two channel
+ * playback capability. To accommodate this a fixed 2-channel down
+ * matrix processes is commonly used following the multi-channel
+ * decoding stage. However, for music only applications the image
+ * quality etc. of the down matrixed signal may not match that of an
+ * equivalent stereo recording found on CD.
+ *
+ * The concept of embedded mixing is to allow the producer to
+ * dynamically specify the matrixing coefficients within the audio
+ * frame itself. In this way the stereo down mix at the decoder may be
+ * better matched to a 2-channel playback environment.
+ *
+ * CHS*2, 7-bit down mix indexes (MCOEFFS) are transmitted along with
+ * the multi-channel audio once in every frame. The indexes are
+ * converted to attenuation factors using a 7 bit LUT. The 2-ch down
+ * mix equations are as follows,
+ *
+ * Left Ch  = sum (MCOEFF[n]       * Ch[n]) for n=1, CHS
+ *
+ * Right Ch = sum (MCOEFF[n + CHS] * Ch[n]) for n=1, CHS
+ *
+ * where Ch(n) represents the subband samples in the (n)th audio channel.
+ */
+
+const uint32_t ff_dca_map_xxch_to_native[28] = {
+    AV_CH_FRONT_CENTER,
+    AV_CH_FRONT_LEFT,
+    AV_CH_FRONT_RIGHT,
+    AV_CH_SIDE_LEFT,
+    AV_CH_SIDE_RIGHT,
+    AV_CH_LOW_FREQUENCY,
+    AV_CH_BACK_CENTER,
+    AV_CH_BACK_LEFT,
+    AV_CH_BACK_RIGHT,
+    AV_CH_SIDE_LEFT,           /* side surround left -- dup sur side L */
+    AV_CH_SIDE_RIGHT,          /* side surround right -- dup sur side R */
+    AV_CH_FRONT_LEFT_OF_CENTER,
+    AV_CH_FRONT_RIGHT_OF_CENTER,
+    AV_CH_TOP_FRONT_LEFT,
+    AV_CH_TOP_FRONT_CENTER,
+    AV_CH_TOP_FRONT_RIGHT,
+    AV_CH_LOW_FREQUENCY,        /* lfe2 -- duplicate lfe1 position */
+    AV_CH_FRONT_LEFT_OF_CENTER, /* side front left -- dup front cntr L */
+    AV_CH_FRONT_RIGHT_OF_CENTER,/* side front right -- dup front cntr R */
+    AV_CH_TOP_CENTER,           /* overhead */
+    AV_CH_TOP_FRONT_LEFT,       /* side high left -- dup */
+    AV_CH_TOP_FRONT_RIGHT,      /* side high right -- dup */
+    AV_CH_TOP_BACK_CENTER,
+    AV_CH_TOP_BACK_LEFT,
+    AV_CH_TOP_BACK_RIGHT,
+    AV_CH_BACK_CENTER,          /* rear low center -- dup */
+    AV_CH_BACK_LEFT,            /* rear low left -- dup */
+    AV_CH_BACK_RIGHT            /* read low right -- dup  */
+};
+
+/* -1 are reserved or unknown */
+const int ff_dca_ext_audio_descr_mask[8] = {
+    DCA_EXT_XCH,
+    -1,
+    DCA_EXT_X96,
+    DCA_EXT_XCH | DCA_EXT_X96,
+    -1,
+    -1,
+    DCA_EXT_XXCH,
+    -1,
+};
+
+/* Tables for mapping dts channel configurations to libavcodec multichannel api.
+ * Some compromises have been made for special configurations. Most configurations
+ * are never used so complete accuracy is not needed.
+ *
+ * L = left, R = right, C = center, S = surround, F = front, R = rear, T = total, OV = overhead.
+ * S  -> side, when both rear and back are configured move one of them to the side channel
+ * OV -> center back
+ * All 2 channel configurations -> AV_CH_LAYOUT_STEREO
+ */
+const uint64_t ff_dca_core_channel_layout[16] = {
+    AV_CH_FRONT_CENTER,                                                     ///< 1, A
+    AV_CH_LAYOUT_STEREO,                                                    ///< 2, A + B (dual mono)
+    AV_CH_LAYOUT_STEREO,                                                    ///< 2, L + R (stereo)
+    AV_CH_LAYOUT_STEREO,                                                    ///< 2, (L + R) + (L - R) (sum-difference)
+    AV_CH_LAYOUT_STEREO,                                                    ///< 2, LT + RT (left and right total)
+    AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER,                               ///< 3, C + L + R
+    AV_CH_LAYOUT_STEREO | AV_CH_BACK_CENTER,                                ///< 3, L + R + S
+    AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER | AV_CH_BACK_CENTER,           ///< 4, C + L + R + S
+    AV_CH_LAYOUT_STEREO | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT,               ///< 4, L + R + SL + SR
+
+    AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER | AV_CH_SIDE_LEFT |
+    AV_CH_SIDE_RIGHT,                                                       ///< 5, C + L + R + SL + SR
+
+    AV_CH_LAYOUT_STEREO | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT |
+    AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER,               ///< 6, CL + CR + L + R + SL + SR
+
+    AV_CH_LAYOUT_STEREO | AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT |
+    AV_CH_FRONT_CENTER  | AV_CH_BACK_CENTER,                                ///< 6, C + L + R + LR + RR + OV
+
+    AV_CH_FRONT_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER |
+    AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_BACK_CENTER   |
+    AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT,                                     ///< 6, CF + CR + LF + RF + LR + RR
+
+    AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_CENTER   |
+    AV_CH_FRONT_RIGHT_OF_CENTER | AV_CH_LAYOUT_STEREO |
+    AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT,                                     ///< 7, CL + C + CR + L + R + SL + SR
+
+    AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER |
+    AV_CH_LAYOUT_STEREO | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT |
+    AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT,                                     ///< 8, CL + CR + L + R + SL1 + SL2 + SR1 + SR2
+
+    AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_CENTER   |
+    AV_CH_FRONT_RIGHT_OF_CENTER | AV_CH_LAYOUT_STEREO |
+    AV_CH_SIDE_LEFT | AV_CH_BACK_CENTER | AV_CH_SIDE_RIGHT,                 ///< 8, CL + C + CR + L + R + SL + S + SR
+};
+
+const int8_t ff_dca_lfe_index[16] = {
+    1, 2, 2, 2, 2, 3, 2, 3, 2, 3, 2, 3, 1, 3, 2, 3
+};
+
+const int8_t ff_dca_channel_reorder_lfe[16][9] = {
+    { 0, -1, -1, -1, -1, -1, -1, -1, -1 },
+    { 0,  1, -1, -1, -1, -1, -1, -1, -1 },
+    { 0,  1, -1, -1, -1, -1, -1, -1, -1 },
+    { 0,  1, -1, -1, -1, -1, -1, -1, -1 },
+    { 0,  1, -1, -1, -1, -1, -1, -1, -1 },
+    { 2,  0,  1, -1, -1, -1, -1, -1, -1 },
+    { 0,  1,  3, -1, -1, -1, -1, -1, -1 },
+    { 2,  0,  1,  4, -1, -1, -1, -1, -1 },
+    { 0,  1,  3,  4, -1, -1, -1, -1, -1 },
+    { 2,  0,  1,  4,  5, -1, -1, -1, -1 },
+    { 3,  4,  0,  1,  5,  6, -1, -1, -1 },
+    { 2,  0,  1,  4,  5,  6, -1, -1, -1 },
+    { 0,  6,  4,  5,  2,  3, -1, -1, -1 },
+    { 4,  2,  5,  0,  1,  6,  7, -1, -1 },
+    { 5,  6,  0,  1,  7,  3,  8,  4, -1 },
+    { 4,  2,  5,  0,  1,  6,  8,  7, -1 },
+};
+
+const int8_t ff_dca_channel_reorder_lfe_xch[16][9] = {
+    { 0,  2, -1, -1, -1, -1, -1, -1, -1 },
+    { 0,  1,  3, -1, -1, -1, -1, -1, -1 },
+    { 0,  1,  3, -1, -1, -1, -1, -1, -1 },
+    { 0,  1,  3, -1, -1, -1, -1, -1, -1 },
+    { 0,  1,  3, -1, -1, -1, -1, -1, -1 },
+    { 2,  0,  1,  4, -1, -1, -1, -1, -1 },
+    { 0,  1,  3,  4, -1, -1, -1, -1, -1 },
+    { 2,  0,  1,  4,  5, -1, -1, -1, -1 },
+    { 0,  1,  4,  5,  3, -1, -1, -1, -1 },
+    { 2,  0,  1,  5,  6,  4, -1, -1, -1 },
+    { 3,  4,  0,  1,  6,  7,  5, -1, -1 },
+    { 2,  0,  1,  4,  5,  6,  7, -1, -1 },
+    { 0,  6,  4,  5,  2,  3,  7, -1, -1 },
+    { 4,  2,  5,  0,  1,  7,  8,  6, -1 },
+    { 5,  6,  0,  1,  8,  3,  9,  4,  7 },
+    { 4,  2,  5,  0,  1,  6,  9,  8,  7 },
+};
+
+const int8_t ff_dca_channel_reorder_nolfe[16][9] = {
+    { 0, -1, -1, -1, -1, -1, -1, -1, -1 },
+    { 0,  1, -1, -1, -1, -1, -1, -1, -1 },
+    { 0,  1, -1, -1, -1, -1, -1, -1, -1 },
+    { 0,  1, -1, -1, -1, -1, -1, -1, -1 },
+    { 0,  1, -1, -1, -1, -1, -1, -1, -1 },
+    { 2,  0,  1, -1, -1, -1, -1, -1, -1 },
+    { 0,  1,  2, -1, -1, -1, -1, -1, -1 },
+    { 2,  0,  1,  3, -1, -1, -1, -1, -1 },
+    { 0,  1,  2,  3, -1, -1, -1, -1, -1 },
+    { 2,  0,  1,  3,  4, -1, -1, -1, -1 },
+    { 2,  3,  0,  1,  4,  5, -1, -1, -1 },
+    { 2,  0,  1,  3,  4,  5, -1, -1, -1 },
+    { 0,  5,  3,  4,  1,  2, -1, -1, -1 },
+    { 3,  2,  4,  0,  1,  5,  6, -1, -1 },
+    { 4,  5,  0,  1,  6,  2,  7,  3, -1 },
+    { 3,  2,  4,  0,  1,  5,  7,  6, -1 },
+};
+
+const int8_t ff_dca_channel_reorder_nolfe_xch[16][9] = {
+    { 0,  1, -1, -1, -1, -1, -1, -1, -1 },
+    { 0,  1,  2, -1, -1, -1, -1, -1, -1 },
+    { 0,  1,  2, -1, -1, -1, -1, -1, -1 },
+    { 0,  1,  2, -1, -1, -1, -1, -1, -1 },
+    { 0,  1,  2, -1, -1, -1, -1, -1, -1 },
+    { 2,  0,  1,  3, -1, -1, -1, -1, -1 },
+    { 0,  1,  2,  3, -1, -1, -1, -1, -1 },
+    { 2,  0,  1,  3,  4, -1, -1, -1, -1 },
+    { 0,  1,  3,  4,  2, -1, -1, -1, -1 },
+    { 2,  0,  1,  4,  5,  3, -1, -1, -1 },
+    { 2,  3,  0,  1,  5,  6,  4, -1, -1 },
+    { 2,  0,  1,  3,  4,  5,  6, -1, -1 },
+    { 0,  5,  3,  4,  1,  2,  6, -1, -1 },
+    { 3,  2,  4,  0,  1,  6,  7,  5, -1 },
+    { 4,  5,  0,  1,  7,  2,  8,  3,  6 },
+    { 3,  2,  4,  0,  1,  5,  8,  7,  6 },
+};
+
+const uint16_t ff_dca_vlc_offs[63] = {
+        0,   512,   640,   768,  1282,  1794,  2436,  3080,  3770,  4454,  5364,
+     5372,  5380,  5388,  5392,  5396,  5412,  5420,  5428,  5460,  5492,  5508,
+     5572,  5604,  5668,  5796,  5860,  5892,  6412,  6668,  6796,  7308,  7564,
+     7820,  8076,  8620,  9132,  9388,  9910, 10166, 10680, 11196, 11726, 12240,
+    12752, 13298, 13810, 14326, 14840, 15500, 16022, 16540, 17158, 17678, 18264,
+    18796, 19352, 19926, 20468, 21472, 22398, 23014, 23622,
+};
diff --git a/libavcodec/dcadata.h b/libavcodec/dcadata.h
index 582f14d..1d3d605 100644
--- a/libavcodec/dcadata.h
+++ b/libavcodec/dcadata.h
@@ -1,7 +1,5 @@
 /*
  * DCA compatible decoder data
- * Copyright (C) 2004 Gildas Bazin
- * Copyright (c) 2006 Benjamin Larsson
  *
  * This file is part of FFmpeg.
  *
@@ -25,7642 +23,55 @@
 
 #include <stdint.h>
 
-#include "libavutil/mem.h"
+extern const uint32_t ff_dca_bit_rates[32];
 
-/* Generic tables */
+extern const uint8_t ff_dca_channels[16];
 
-static const uint32_t dca_bit_rates[32] = {
-      32000,   56000,   64000,   96000,  112000, 128000,
-     192000,  224000,  256000,  320000,  384000,
-     448000,  512000,  576000,  640000,  768000,
-     896000, 1024000, 1152000, 1280000, 1344000,
-    1408000, 1411200, 1472000, 1536000, 1920000,
-    2048000, 3072000, 3840000, 1 /* open */, 2 /* variable */, 3 /* lossless */
-};
+extern const uint8_t ff_dca_bits_per_sample[7];
 
-static const uint8_t dca_channels[16] = {
-    1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 8
-};
+extern const int16_t ff_dca_adpcm_vb[4096][4];
 
-static const uint8_t dca_bits_per_sample[7] = {
-    16, 16, 20, 20, 0, 24, 24
-};
+extern const uint32_t ff_dca_scale_factor_quant6[64];
+extern const uint32_t ff_dca_scale_factor_quant7[128];
 
-/* ADPCM data */
+extern const uint32_t ff_dca_lossy_quant[32];
+extern const float ff_dca_lossy_quant_d[32];
 
-/* 16bits signed fractional Q13 binary codes */
-static const int16_t adpcm_vb[4096][4] = {
-    {   9928,  -2618,  -1093, -1263 },
-    {  11077,  -2876,  -1747,  -308 },
-    {  10503,  -1082,  -1426, -1167 },
-    {   9337,  -2403,  -1495,   274 },
-    {  10698,  -2529,   -532, -1122 },
-    {  10368,  -3974,  -1264,  -750 },
-    {  10070,  -3667,    346,   863 },
-    {  10278,  -3093,    311,  -576 },
-    {   9894,  -1330,  -1428,  -860 },
-    {  10544,  -1923,  -1058,  -971 },
-    {  10996,  -1632,   -841, -1404 },
-    {  11832,  -3465,   1658, -1990 },
-    {  10852,   -688,  -2658,  -499 },
-    {  10546,  -1749,   -147, -1733 },
-    {  10801,  -1004,   -708, -1453 },
-    {  10588,   -441,  -2113,  -952 },
-    {  10141,  -3331,   -582, -1432 },
-    {   9608,  -2590,    383,   258 },
-    {  11422,  -3265,    229, -1544 },
-    {  10460,  -1338,   -713, -1568 },
-    {  10306,  -1721,  -1660,  -603 },
-    {   9580,  -1812,  -1235, -1061 },
-    {  11471,  -2285,  -1617,  -607 },
-    {  10081,  -2225,  -1408,  -868 },
-    {  10715,  -2624,  -1367,  -704 },
-    {  10616,  -1871,  -2770,   -35 },
-    {   9352,  -2340,  -1024, -1566 },
-    {  11065,  -1458,  -1926,  -735 },
-    {  11334,  -2056,  -1041, -1144 },
-    {   9825,  -2048,   -794, -1536 },
-    {  11850,  -2695,  -1123,  -867 },
-    {  10654,  -2226,  -1891,  -373 },
-    {  10024,  -1557,   -808, -1069 },
-    {  11142,  -1266,  -3238,   128 },
-    {  11729,  -3282,   -514, -1011 },
-    {  11402,  -2094,  -2335,  -189 },
-    {  10195,  -3658,    181, -1875 },
-    {  11431,  -2626,   -404, -1377 },
-    {  11001,  -3868,   -619, -1077 },
-    {  10894,  -2559,    274, -1758 },
-    {   9633,  -1482,  -2253,  -773 },
-    {  11245,  -3321,    830, -1972 },
-    {   9768,  -2701,   -199, -1859 },
-    {  10500,  -2042,    525, -2043 },
-    {  11669,  -4069,    293, -1468 },
-    {   9192,  -1991,   -583,   -61 },
-    {  10057,  -3220,  -2015,  -473 },
-    {   9497,  -2315,  -2490,  -467 },
-    {  10455,  -3069,  -1194, -1007 },
-    {   9994,  -1936,    -60, -1225 },
-    {   9295,  -2156,  -1761, -1134 },
-    {  10085,  -3748,  -1026,   197 },
-    {   9334,  -2360,    804,  -351 },
-    {  11561,  -2553,   1352, -2313 },
-    {  12837,  -3998,   1195, -1958 },
-    {  10114,  -1100,  -2414,  -394 },
-    {   9341,  -2530,    315,   755 },
-    {  10131,  -3164,   1411,  -674 },
-    {   9535,   -905,  -1551,   579 },
-    {  11717,  -1519,  -3051,    91 },
-    {   9824,  -2911,  -2775,   192 },
-    {   9662,  -2934,   -561,  1450 },
-    {  11085,  -3392,  -1298,  -659 },
-    {   8955,  -2102,  -1899,   703 },
-    {   8607,  -1742,  -4348,   814 },
-    {   7640,  -2063,  -3617,    52 },
-    {   7074,   -826,  -4325,  4375 },
-    {   7714,    584,  -4238,  1927 },
-    {   6355,   -952,  -4912,  3127 },
-    {   7069,   -660,  -6413,  4087 },
-    {   8313,   -132,  -2964,  -876 },
-    {   6952,  -1422,  -3962,   -24 },
-    {   9299,   -734,  -3088,  -263 },
-    {   9484,   -574,  -4513,   466 },
-    {   7246,    -91,  -3735,  -704 },
-    {   8325,  -1417,  -3090,  -530 },
-    {   6469,  -1226,  -4757,   829 },
-    {   6652,   -368,  -5682,  1393 },
-    {   7971,  -1278,  -2284,  1205 },
-    {   7229,   -699,  -3556,  1840 },
-    {   7994,   1284,  -2729,   732 },
-    {   9005,   -698,  -4522,  2189 },
-    {   6963,    197,  -2727,   380 },
-    {   8527,    135,  -3991,  -213 },
-    {   8840,    934,  -3014,  -567 },
-    {  10125,    418,  -3284,  -371 },
-    {   6367,    361,  -2318,  2554 },
-    {   7892,    172,  -5247,  4673 },
-    {   6674,    387,  -5424,  4398 },
-    {   6240,    684,  -4047,  1219 },
-    {  11170,   -794,  -5081,  1195 },
-    {  11765,   -648,  -6265,  2052 },
-    {  10845,   -775,  -3837,   366 },
-    {  12496,   -689,  -8260,  3562 },
-    {   7893,  -1166,  -4972,   988 },
-    {   8592,   1052,  -5986,  3087 },
-    {   7277,   1874,  -5685,  3579 },
-    {   6900,   2016,  -4809,  3491 },
-    {   8530,  -2405,  -3250,  1986 },
-    {   9426,    494,  -7067,  5038 },
-    {  10285,    564,  -8210,  5370 },
-    {   8749,  -2207,  -3980,  2852 },
-    {   9653,  -2686,  -4300,  1400 },
-    {   9770,  -2286,  -5663,  4233 },
-    {   8490,     -4,  -7048,  4496 },
-    {   7697,  -1209,  -5328,  3183 },
-    {   6451,    801,  -4324,  -554 },
-    {   7387,   1806,  -5265,   545 },
-    {   7450,  -2302,  -4445,  1418 },
-    {   8817,  -1370,  -5827,  2168 },
-    {  10324,  -2406,  -5629,  2579 },
-    {   8863,  -2578,  -3537,   467 },
-    {   6901,  -1624,  -3169,  3392 },
-    {   7846,    156,  -6948,  3381 },
-    {   7928,  -1115,  -5972,  4816 },
-    {   6089,   -599,  -4368,  -320 },
-    {   7833,   1246,  -3960,  -621 },
-    {   8931,   2521,  -6768,  2052 },
-    {   8900,   1944,  -4126,    40 },
-    {   7661,    -34,  -2855,  2480 },
-    {   5873,    474,  -3262,  3712 },
-    {   7535,   -234,  -4699,   216 },
-    {   5856,    143,  -5142,    73 },
-    {   8944,   -106,  -5874,  3663 },
-    {   7134,    426,  -5879,  2895 },
-    {  10199,   1011,  -4762,   369 },
-    {   8454,    264,  -5971,  1291 },
-    {   7822,  -2449,  -4333,  4540 },
-    {   6200,  -2758,  -2632,  1497 },
-    {   6070,  -4315,  -2699,   414 },
-    {   7047,  -3739,  -3210,  1060 },
-    {   5675,  -3801,  -2717,  -407 },
-    {   4789,  -4063,  -2628,  -744 },
-    {   4023,  -3366,  -3133,  -726 },
-    {   4296,  -2407,  -3381,  -513 },
-    {   4388,  -2931,  -2820,  1512 },
-    {   4559,  -4233,  -1941,  1976 },
-    {   6702,  -3208,  -1755,  1680 },
-    {   4416,  -3521,  -1052,  2984 },
-    {   7154,  -4266,  -1203,  3732 },
-    {   3625,  -4242,  -3244,  1395 },
-    {   6518,  -2856,  -1304,  2887 },
-    {   6170,  -1949,  -3014,  3973 },
-    {   5189,  -2451,  -4020,  3477 },
-    {   6218,  -2988,  -1921,  3844 },
-    {   4827,  -3688,  -1928,  3343 },
-    {   6668,  -3991,  -2805,  3095 },
-    {   5297,  -3115,  -3684,  2390 },
-    {   5354,  -4614,  -2662,  1504 },
-    {   4196,  -3091,  -4147,  1135 },
-    {   3540,  -2893,  -4007,   100 },
-    {   5569,  -1602,  -4007,  1909 },
-    {   4341,  -2091,  -4272,   252 },
-    {   5559,  -2878,  -3832,   498 },
-    {   4548,  -4479,  -2898,   -27 },
-    {   5176,  -2494,  -4635,  1476 },
-    {   3294,  -3485,  -3738,   716 },
-    {   4920,  -1229,  -4195,  -365 },
-    {   3257,  -3518,  -3349,  2862 },
-    {   5286,  -1948,  -3485,  -778 },
-    {   6502,  -3051,   -152,  2854 },
-    {   5864,  -4192,  -1076,  3451 },
-    {   4656,  -3122,  -3448,   179 },
-    {   5907,   -754,  -1596,  3116 },
-    {   7229,  -3680,  -1590,  2892 },
-    {   5107,  -3888,  -3364,   806 },
-    {   6764,  -2635,  -3450,   134 },
-    {   5258,  -2827,  -2844, -1052 },
-    {   5798,  -1725,  -4305,   205 },
-    {   5404,  -1213,  -3362,   449 },
-    {   6224,  -2738,  -3046,  -581 },
-    {   4223,  -2438,  -2725,  3745 },
-    {   4751,  -3411,  -2123,   116 },
-    {   3868,  -3000,  -3954,  2297 },
-    {   6819,  -2899,  -4277,  2825 },
-    {   4207,  -4754,  -2808,   865 },
-    {   4804,  -1494,  -1997,  4688 },
-    {   5282,  -2213,   -548,  3559 },
-    {   5580,  -1912,   -566,  4370 },
-    {   6168,  -2857,   -672,  4053 },
-    {   6583,  -4515,  -2850,  1670 },
-    {   6511,  -3093,  -3988,  1421 },
-    {   4646,  -1790,  -1443,  3650 },
-    {   5915,   -924,  -2020,   896 },
-    {   7814,  -4181,  -3152,  2007 },
-    {   6190,  -2238,  -4817,  2279 },
-    {   4737,  -4034,  -3288,  1835 },
-    {   8161,  -3633,  -3423,  3137 },
-    {   7415,  -2351,  -2088,  4290 },
-    {   4106,  -2517,    -62,  2905 },
-    {   4909,  -3145,   -614,  4112 },
-    {   4938,  -3281,   -397,  1100 },
-    {   -173,    919,   1589, -5363 },
-    {    -13,    796,   -295, -6655 },
-    {  -1860,   -829,   1141, -4555 },
-    {   2298,   -838,   -664, -5005 },
-    {   -884,  -1097,   2074, -4613 },
-    {   -101,    281,   2846, -4535 },
-    {   1166,    453,   2429, -5910 },
-    {    879,   -664,   2370, -5452 },
-    {   1415,   -370,  -1699, -4727 },
-    {  -1413,   1277,   -669, -6649 },
-    {   2133,    304,   -968, -4624 },
-    {    380,    586,  -2087, -4892 },
-    {   1336,    275,    -82, -5789 },
-    {  -2459,   1057,    -34, -5416 },
-    {   2278,  -1758,    866, -5653 },
-    {   1945,  -2295,   -149, -5302 },
-    {   1287,  -3525,    996, -5255 },
-    {   2297,    803,   1177, -6067 },
-    {    187,   -180,   -619, -6202 },
-    {   -793,  -2537,   1554, -5057 },
-    {  -2703,   -204,   -629, -5853 },
-    {  -1007,   -146,    313, -5582 },
-    {    830,    357,    869, -6363 },
-    {   -228,   -575,  -3177, -4433 },
-    {  -1001,  -1553,   -142, -5708 },
-    {  -1644,   1683,   1721, -4533 },
-    {    893,   1924,    -15, -5791 },
-    {   2195,   2061,   -262, -5471 },
-    {   3031,    270,    311, -5096 },
-    {   1912,   1638,  -1523, -4677 },
-    {  -3142,    -55,    253, -4914 },
-    {    356,  -1680,    343, -6123 },
-    {  -2241,  -1734,   -976, -5939 },
-    {  -2196,  -2893,    547, -4938 },
-    {  -1245,    126,  -1916, -5419 },
-    {   -249,  -3755,  -1422, -5594 },
-    {    575,  -2683,  -1926, -4566 },
-    {   -762,   1885,    192, -5880 },
-    {   -811,  -2562,  -1068, -6013 },
-    {  -2264,  -3086,   -976, -4775 },
-    {     70,  -1215,   2880, -4410 },
-    {    714,  -3760,   2916, -4691 },
-    {   -244,  -3404,   1740, -4493 },
-    {    684,  -5137,   -328, -5608 },
-    {   -529,  -3825,  -1786, -4535 },
-    {   -713,  -4743,  -1118, -5546 },
-    {   2718,  -3788,   1798, -5708 },
-    {  -1639,  -3679,  -1564, -6095 },
-    {   1693,  -2642,  -1389, -4539 },
-    {    505,  -1573,  -1651, -4878 },
-    {   -835,  -2256,  -1941, -5352 },
-    {   1464,   -411,   1993, -6441 },
-    {    493,  -3184,   -145, -6148 },
-    {  -1413,    499,  -1617, -6479 },
-    {   -294,   1722,  -1419, -5725 },
-    {  -2937,  -1528,   -175, -4624 },
-    {   -594,  -5911,    -56, -6146 },
-    {   -300,  -4275,   1156, -5947 },
-    {    552,  -2643,   2669, -3959 },
-    {    905,  -4158,   1789, -5809 },
-    {   1336,  -2009,   2108, -5903 },
-    {   1555,  -3600,   1110, -6759 },
-    {  -1294,  -3464,     77, -6084 },
-    {  -1139,  -4006,  -1270, -4181 },
-    {  -5094,  -3296,   1092, -2847 },
-    {  -5503,  -2883,   1984, -2067 },
-    {  -4671,  -4218,  -1417, -4132 },
-    {  -3763,  -3818,   1262, -3082 },
-    {  -5132,  -3430,   2928,  -728 },
-    {  -5957,  -2877,   1251, -2446 },
-    {  -4425,  -2319,   -212, -4276 },
-    {  -6201,  -1993,   1774, -2182 },
-    {  -5500,  -3836,   2201, -1396 },
-    {  -6934,  -2334,   2366, -1293 },
-    {  -6124,  -4140,   1337, -1977 },
-    {  -6553,  -4186,   1756, -1325 },
-    {  -5126,  -1258,    744, -3656 },
-    {  -5167,  -1390,   1581, -2895 },
-    {  -4525,  -3398,   2429, -1865 },
-    {  -4076,  -3183,   2027, -2510 },
-    {  -6191,  -3274,   1838, -1814 },
-    {  -4454,  -2753,   2723, -1185 },
-    {  -6655,  -4797,    251, -2595 },
-    {  -6332,  -2232,   1832,   217 },
-    {  -5869,  -1698,    134,   340 },
-    {  -6614,  -1045,   2126, -1932 },
-    {  -4859,  -2107,   2010, -2435 },
-    {  -6274,  -1622,   2808, -1374 },
-    {  -3119,  -3209,    521, -3988 },
-    {  -5676,  -2082,   -420, -2711 },
-    {  -7073,  -3623,    696, -2343 },
-    {  -5986,  -4224,    572, -2454 },
-    {  -4340,  -4521,    882, -2771 },
-    {  -6178,  -1933,    535, -1444 },
-    {  -4923,  -4163,   1744, -2066 },
-    {  -6410,  -1519,   1058, -2683 },
-    {  -5077,  -1185,    856, -2216 },
-    {  -7091,  -2444,    687, -2597 },
-    {  -5284,  -2165,   3239,  -993 },
-    {  -4763,  -1497,    197, -3179 },
-    {  -4128,  -4958,   -396, -3578 },
-    {  -5054,  -3878,   -647, -2672 },
-    {  -7005,  -3348,   1679, -1579 },
-    {  -5767,  -1017,   2582, -1915 },
-    {  -7069,  -2787,   1331, -2070 },
-    {  -5532,  -2296,    706, -2950 },
-    {  -5059,  -3543,   -821, -3637 },
-    {  -6639,  -1835,   1016,  -696 },
-    {  -5611,  -5220,   -694, -3371 },
-    {  -5994,  -2803,   2933,  -729 },
-    {  -5948,   -619,   1596, -2676 },
-    {  -5486,  -4419,    153, -3265 },
-    {  -4329,  -3440,   1646, -1439 },
-    {  -4083,  -3978,    177, -3569 },
-    {  -4289,  -2599,   1224, -3075 },
-    {  -5707,  -3253,   1912,  -759 },
-    {  -6606,  -3437,   2562,  -571 },
-    {  -5254,  -2444,    769,  -352 },
-    {  -6545,  -3154,    582, -1103 },
-    {  -5328,  -2241,   2566, -1775 },
-    {  -7216,  -1936,   1538, -1983 },
-    {  -3730,  -2451,    426, -3869 },
-    {  -5110,  -1385,   2031, -1169 },
-    {  -6470,  -2715,    269, -3123 },
-    {  -5806,  -2480,    -97, -3832 },
-    {  -3683,  -4916,   -490, -4330 },
-    {  -6341,  -2083,   -669,  -115 },
-    {  -4913,  -4079,   -837, -4673 },
-    {  -3274,  -2497,   2334, -2652 },
-    {  -1286,  -1731,   2550, -3756 },
-    {  -3375,   -877,    926, -3977 },
-    {  -2525,  -2079,   2879, -2625 },
-    {  -5308,   -504,   3111, -1607 },
-    {  -4904,    460,   4093, -1232 },
-    {  -1993,   1616,   4656, -1913 },
-    {  -3481,  -1176,   3119, -2236 },
-    {  -4132,  -1502,   2339, -2545 },
-    {  -2542,   1151,   3569, -2550 },
-    {  -4381,    430,   3147, -2082 },
-    {  -3888,    867,   3899, -1657 },
-    {  -2861,   1290,   4202, -1979 },
-    {  -3893,   -253,   2363, -2764 },
-    {  -1705,    688,   3827, -2923 },
-    {  -2223,   2312,   3700, -3148 },
-    {  -1986,   -720,   5021,  -795 },
-    {  -3177,    242,   1952, -3352 },
-    {  -1854,   1509,   2528, -3815 },
-    {  -3173,     97,   5019,  -706 },
-    {  -2689,   -145,   1375, -3915 },
-    {  -4838,   -385,   2488, -2427 },
-    {  -4557,   -355,   1603, -3060 },
-    {  -3522,   1832,   3292, -2674 },
-    {  -3769,    780,   2378, -2704 },
-    {  -4323,  -1932,   3414, -1169 },
-    {  -2740,   1158,   2729, -3273 },
-    {  -3647,    210,   1464, -2892 },
-    {  -2342,  -2097,   1513, -3727 },
-    {  -4422,  -1242,   3130, -1833 },
-    {  -1308,  -1039,   4290, -1875 },
-    {  -1754,  -2535,   3298, -2314 },
-    {  -4102,   -186,   4037, -1094 },
-    {  -1008,   1570,   3290,   171 },
-    {  -3322,  -2621,   2791, -1536 },
-    {  -2539,  -2597,   3442, -1672 },
-    {  -3411,  -2015,   3670, -1174 },
-    {  -2097,    730,   5581, -1399 },
-    {  -1510,    -74,   4820, -2004 },
-    {  -4086,   -868,   4425,  -771 },
-    {   -956,   -986,   3640, -2925 },
-    {  -2087,  -1250,   3464, -2458 },
-    {  -3308,  -2411,   1334, -3667 },
-    {  -2264,   -389,   4004, -1854 },
-    {   -680,    239,   4058, -3388 },
-    {  -1357,     30,   2993, -3658 },
-    {  -3601,   -552,   1177, -1136 },
-    {  -2641,    442,   4374, -1625 },
-    {  -2525,    770,   1640, -3895 },
-    {  -3172,   -891,   3893, -1608 },
-    {  -2996,     13,   3277, -2414 },
-    {   -899,   1055,   4470, -2501 },
-    {   -422,   -584,   3475, -3787 },
-    {  -1978,   -593,   2566, -3415 },
-    {  -3150,  -1280,   2362, -3047 },
-    {  -3592,    224,   1026, -3932 },
-    {  -4840,  -1189,   3633,  -879 },
-    {  -3952,  -2255,   2916, -1826 },
-    {  -1695,     28,   1810,  -349 },
-    {   -745,  -2484,   3308, -3293 },
-    {  -1016,   1563,   5365, -1823 },
-    {  -2172,  -1787,   4266, -1287 },
-    {  -1241,  -1951,   3982, -2413 },
-    {  -2009,  -2639,   2330, -3480 },
-    {   5105,  -1618,  -2588, -2015 },
-    {   6497,  -1523,  -3218,  -910 },
-    {   6526,  -2305,  -2029, -1790 },
-    {   5289,    -99,  -3436,  -400 },
-    {   5781,  -1623,  -1577, -2617 },
-    {   5259,   -670,  -3125, -1700 },
-    {   6343,  -1256,   -331, -3222 },
-    {   7967,   -678,  -2195, -1462 },
-    {   6119,   -695,  -2988, -1538 },
-    {   6108,    494,  -3359, -1548 },
-    {   5067,    969,  -2328, -2707 },
-    {   7595,   -435,  -1497, -2056 },
-    {   6929,   -719,  -2420, -1665 },
-    {   5190,    584,  -2982, -2103 },
-    {   6106,   -444,  -1411, -2739 },
-    {   5584,    289,  -1804, -2803 },
-    {   5276,    227,  -1180, -3361 },
-    {   7544,  -1525,  -1834, -1725 },
-    {   5986,  -1470,  -2606, -1701 },
-    {   5096,   -765,  -1712, -3006 },
-    {   5423,   -149,  -3933, -1157 },
-    {   7651,     26,  -2445, -1507 },
-    {   4745,   -464,  -1735, -2362 },
-    {   5352,  -1011,  -1094, -1999 },
-    {   6300,   -672,   -542, -1950 },
-    {   6675,  -1020,  -1318, -1059 },
-    {   7218,  -2036,   -603, -2462 },
-    {   7755,  -1514,  -2430, -1229 },
-    {   5041,    449,  -1056, -2405 },
-    {   6710,  -2277,  -1344, -2284 },
-    {   6824,  -1347,  -2254,   251 },
-    {   6068,  -1857,   -983, -1316 },
-    {   5603,  -2177,  -2730, -1477 },
-    {   5838,  -1059,  -3604,  -970 },
-    {   5076,   -789,   -335, -2413 },
-    {   6191,  -1634,  -2000, -2129 },
-    {   5092,  -1292,  -2543, -1034 },
-    {   5305,    435,  -1710, -1850 },
-    {   6140,    561,  -2176, -2380 },
-    {   6752,    348,  -2496, -1890 },
-    {   6405,    273,  -1098, -2778 },
-    {   6942,  -1340,   -496, -1381 },
-    {   5238,   -687,  -2454, -2349 },
-    {   6959,   -882,  -1833, -2061 },
-    {   6292,   -253,  -2125, -2199 },
-    {   5838,   -574,   -759, -3215 },
-    {   6954,  -1484,   -640, -2771 },
-    {   7498,  -1706,  -1210, -2154 },
-    {   6772,  -1003,  -1235, -2532 },
-    {   6014,    228,  -2154, -1108 },
-    {   6943,  -2178,  -2644, -1122 },
-    {   7262,   -763,  -3056, -1090 },
-    {   6273,  -1478,  -1072,   177 },
-    {   4734,    425,  -2912,   357 },
-    {   7129,    168,  -1537, -2327 },
-    {   7204,   -434,   -746, -2660 },
-    {   6879,     57,  -3087, -1310 },
-    {   4623,   -610,   -718, -3459 },
-    {   6565,   -543,  -1998,  -339 },
-    {   4752,   -277,  -2066, -1405 },
-    {   7435,  -1416,  -1904,  -505 },
-    {   4076,    150,  -1222, -3556 },
-    {   7082,    -28,  -1456, -1174 },
-    {   5941,   -446,  -1326, -1158 },
-    {   3870,  -1648,  -2474, -2589 },
-    {    858,     37,  -3387, -3721 },
-    {   3557,  -1503,  -1664, -3383 },
-    {   3336,  -1972,  -3079, -2216 },
-    {   3186,     60,  -4185,  -863 },
-    {   3456,   -773,  -3066, -2457 },
-    {   4131,   -913,  -2060, -2601 },
-    {   4431,   -691,  -4114,  -972 },
-    {   3461,   -334,  -3680, -1751 },
-    {   2006,   -459,  -2214, -3827 },
-    {   1322,     32,  -2816, -3203 },
-    {   4425,  -1897,  -2791, -1946 },
-    {   4504,     23,  -3421, -1909 },
-    {   3090,   -885,  -2366, -3264 },
-    {   3209,  -2363,  -3730,  -834 },
-    {   3312,  -1471,  -3641, -1579 },
-    {   4184,  -1669,  -3323, -1248 },
-    {   2190,   -931,  -3302, -2944 },
-    {   2947,   -229,  -4791, -1195 },
-    {   2020,  -1626,  -2700, -3125 },
-    {   2214,   -326,  -4352, -1683 },
-    {   3286,  -2619,  -2412, -2458 },
-    {   1000,  -2571,  -4129, -2158 },
-    {   2496,  -2627,  -3611, -1433 },
-    {   2043,  -2191,  -2167, -3827 },
-    {   2571,  -2544,  -1915, -3222 },
-    {   2022,  -1501,  -3856, -2165 },
-    {   2685,  -1180,  -1461, -4038 },
-    {   1610,  -2313,  -4391, -1173 },
-    {   2340,  -2490,  -4215,  -516 },
-    {   1742,  -2615,  -3632, -2146 },
-    {    523,  -1293,  -4246, -2442 },
-    {   3725,  -2723,  -3014, -1576 },
-    {   3554,  -1381,  -4200,  -824 },
-    {   1291,  -1594,  -4777, -1430 },
-    {   1452,    515,  -2960, -3830 },
-    {   4264,   -894,  -3305, -1826 },
-    {   2606,  -1452,  -4522,  -966 },
-    {   1196,   -830,  -4807, -1816 },
-    {   1054,   -775,  -2616, -4071 },
-    {   4206,    415,  -4344, -1132 },
-    {   3044,    491,  -4126, -1934 },
-    {    988,   -901,  -3353, -3443 },
-    {   1729,  -3063,  -2267, -3370 },
-    {   3915,    912,  -2989, -2387 },
-    {   3781,    300,  -2457, -3050 },
-    {   2712,    924,  -1350, -1206 },
-    {   4230,    405,  -2343,   665 },
-    {   1878,   -873,   -225,   -29 },
-    {   3510,     56,  -1334, -3420 },
-    {   2850,   1447,  -2651, -3150 },
-    {   1510,   -706,  -4125, -2483 },
-    {   3115,    793,  -1692, -3894 },
-    {   2667,    213,  -2973, -2786 },
-    {   1184,  -2384,  -3051, -3173 },
-    {   2139,    796,  -2079, -3697 },
-    {   1464,  -1483,  -3726, -2754 },
-    {   2407,  -1148,  -3915, -1569 },
-    {   2612,  -1779,  -3217, -2271 },
-    {   2406,  -2870,  -2937, -2496 },
-    {   2140,    126,  -3646, -2758 },
-    {   2952,  -1036,    268, -1423 },
-    {     93,  -1931,  -3841, -3535 },
-    {    389,  -2953,  -3383, -3343 },
-    {   8652,  -5511,  -1662,   565 },
-    {   7427,  -2791,  -2535,  -842 },
-    {   8541,  -4253,  -1407,  -988 },
-    {   8018,  -3203,  -2998,   105 },
-    {   7231,  -3926,   -958,  1308 },
-    {   7331,  -3690,   -363,  2586 },
-    {   6803,  -3646,  -2226,  -903 },
-    {   8163,  -2811,   -477, -2235 },
-    {   9356,  -3818,  -1685,  -684 },
-    {   8466,  -2854,   -302,  -698 },
-    {   8458,  -3224,    517,   279 },
-    {   8074,  -2619,  -1326,  2596 },
-    {   8779,  -2761,  -2527,  -441 },
-    {   6533,  -2887,   -899,  -696 },
-    {   7394,  -2305,  -1642,  -120 },
-    {   8281,  -3780,    -22,  1305 },
-    {   9158,  -4413,   -779,   901 },
-    {   9031,  -5240,  -1109,  1678 },
-    {   8717,  -3650,    410, -1075 },
-    {   7317,  -3197,   -818, -2264 },
-    {   7934,  -2385,  -1214, -1886 },
-    {   8256,  -4441,   -291,  -587 },
-    {   7358,  -3395,   1090,  -270 },
-    {   9446,  -4910,  -1343,  -473 },
-    {   8187,  -4726,   -808,  1166 },
-    {   7504,  -3845,    -47,   267 },
-    {   8029,  -2146,  -1283,  -383 },
-    {   7461,  -2705,   -853,   783 },
-    {   9367,  -3636,   -645,  -354 },
-    {   8955,  -3473,   -308, -1947 },
-    {   8676,  -2683,  -2099,  1485 },
-    {   7481,  -3003,   -871,  -444 },
-    {   8015,  -2839,  -1673,  1175 },
-    {   6947,  -4643,  -1527, -1047 },
-    {   7622,  -2575,   -137,  -960 },
-    {   9388,  -4279,   -707, -1322 },
-    {   8382,  -5259,  -1283,  -565 },
-    {   6856,  -4138,  -1030,   630 },
-    {   8659,  -2571,  -1124, -1666 },
-    {   8763,  -3807,   -537,  2543 },
-    {   8049,  -3578,  -2186,  -604 },
-    {   8272,  -2351,  -1985, -1214 },
-    {   6855,  -3796,  -1527, -1631 },
-    {   7178,  -2896,  -1600, -1756 },
-    {   7040,  -2888,    -89, -1586 },
-    {   6261,  -3403,   -264,   998 },
-    {   7756,  -4699,  -1543,  -834 },
-    {   7682,  -4622,   -758, -1721 },
-    {   8839,  -4232,  -2932,  1959 },
-    {   9363,  -4679,  -1956,    39 },
-    {   7883,  -3616,  -1414, -1432 },
-    {   8828,  -3188,  -1356, -1312 },
-    {   7746,  -3987,   -121, -2424 },
-    {   9262,  -3256,   -693,   818 },
-    {   7670,  -3420,   -148,  3504 },
-    {   7344,  -3183,    608,  1595 },
-    {   8976,  -4139,  -1848,  1304 },
-    {   6708,  -4131,     33,  -852 },
-    {   7840,  -4429,  -2275,    79 },
-    {   8980,  -3858,  -2838,   453 },
-    {   7815,  -4604,  -2563,   944 },
-    {   8372,  -4422,  -1783,  3071 },
-    {   8623,  -5128,  -1754,  2888 },
-    {   7462,  -3281,    889,   920 },
-    {   8416,    -59,  -1320, -1825 },
-    {   7928,  -1488,   -414, -2499 },
-    {   8110,   -977,  -1047, -2042 },
-    {   8278,   -687,  -1597, -1550 },
-    {   7988,   -174,   -977, -2106 },
-    {   8609,  -1547,  -1628, -1527 },
-    {   9000,  -1798,   -946, -1761 },
-    {   8954,   -872,  -1404, -1594 },
-    {   8939,    466,   -748, -1212 },
-    {   9549,   -329,   -177, -1360 },
-    {   9411,    -18,  -1126, -1568 },
-    {   8859,   -782,   -488, -1338 },
-    {   8955,   -218,    -43, -1209 },
-    {   9131,    -69,   -453, -1001 },
-    {   9069,  -1519,  -1091, -1199 },
-    {   9247,  -1309,   -566, -1146 },
-    {   8528,  -1617,   -287, -1313 },
-    {   7763,   -745,   -149, -2040 },
-    {   8294,   -343,    257, -2633 },
-    {  10149,   -893,   -552, -1649 },
-    {   9398,   -915,    218, -2042 },
-    {   9703,  -1194,   -675, -1592 },
-    {   9586,   -700,   -427, -1710 },
-    {   8930,    497,  -1445, -1218 },
-    {   9285,  -1323,   -163, -1552 },
-    {   8431,  -1289,   -985, -1404 },
-    {   8965,   -655,    653, -1483 },
-    {   9542,  -1001,   -951, -1128 },
-    {   9205,   -647,    -37,  -882 },
-    {   8603,    -56,    514, -1793 },
-    {   9300,    -12,  -1324,  -567 },
-    {   8773,    238,   -184, -1456 },
-    {   9941,  -1306,    -69, -1792 },
-    {   9360,    279,   -376, -1919 },
-    {   9180,   -285,     95, -2170 },
-    {   9922,   -501,   -970, -1570 },
-    {   8341,  -1493,   -856, -2092 },
-    {   8780,   -981,   -850, -1014 },
-    {   9721,   -548,  -1504, -1094 },
-    {   9973,  -1493,    482, -2105 },
-    {   8707,   -333,  -1027, -1087 },
-    {   9098,   -469,   -315, -1723 },
-    {   8879,  -1050,   -661, -2020 },
-    {   8857,    602,   -866, -1918 },
-    {   8945,  -1025,  -2154, -1071 },
-    {   8484,  -1930,   -468, -2179 },
-    {   9177,  -1903,   -224, -2112 },
-    {   8652,   -137,  -2097, -1214 },
-    {   9063,   -973,  -1405,  -772 },
-    {   9328,   -456,    662, -2469 },
-    {  10101,   -697,    127, -2113 },
-    {   9685,    811,  -2359, -1024 },
-    {   8586,    -94,   -460, -1982 },
-    {   7924,   -141,   -509, -2513 },
-    {   7773,   -669,   -107, -2835 },
-    {   8636,  -1064,    -46, -2409 },
-    {   9748,    596,  -1815, -1349 },
-    {   8924,    304,    547, -2614 },
-    {   9442,    746,  -1153, -1679 },
-    {   9454,   -278,   -529, -1976 },
-    {   8488,    561,    -32, -2160 },
-    {  10083,    -63,  -1544, -1364 },
-    {   9390,  -1278,    568, -1131 },
-    {   9740,    -49,  -2253,  -910 },
-    {   3636,  -2391,  -1115, -3614 },
-    {   6014,  -3204,  -1902, -1808 },
-    {   5787,  -3497,  -1116, -2590 },
-    {   4365,  -3046,  -1632, -2668 },
-    {   4733,  -2192,  -2029, -2468 },
-    {   5412,  -2753,  -1633, -2464 },
-    {   4455,  -3375,   -767, -3399 },
-    {   4456,  -1644,   -983, -2841 },
-    {   4039,  -2523,     38, -3967 },
-    {   3406,  -2662,     72, -4757 },
-    {   4279,  -2005,   1055, -4399 },
-    {   4321,  -1377,   -860, -3786 },
-    {   3743,  -5739,   -651, -3047 },
-    {   3528,  -5510,    361, -4060 },
-    {   6496,  -4886,   -136, -2689 },
-    {   4513,  -5254,    551, -4010 },
-    {   6557,  -3413,    -92, -3063 },
-    {   4186,  -2059,    187,    47 },
-    {   6210,  -4117,  -1256, -1985 },
-    {   6038,  -4343,    351, -2124 },
-    {   4305,  -4780,  -2077, -1897 },
-    {   4480,  -3815,  -2228, -1533 },
-    {   5582,  -3689,   1221, -3429 },
-    {   5532,  -4874,   1195, -2765 },
-    {   6518,  -2853,   -905, -2568 },
-    {   5467,  -2192,    470, -4115 },
-    {   4139,  -1577,    240, -3493 },
-    {   5281,  -1926,   -729, -3340 },
-    {   5214,  -2870,   1359, -4289 },
-    {   3046,  -3510,  -1536, -3214 },
-    {   5433,  -2881,  -1230, -1184 },
-    {   4861,  -3932,  -1071, -2791 },
-    {   5693,  -4234,  -1906, -1502 },
-    {   4004,  -3935,  -1804, -2383 },
-    {   3728,  -3792,    681, -4773 },
-    {   3621,  -3030,  -1951, -2598 },
-    {   5133,  -3903,     44, -3700 },
-    {   3561,  -3451,   1183, -5301 },
-    {   5026,  -2762,  -2341, -1780 },
-    {   5841,  -2492,   -467, -3210 },
-    {   5591,  -1791,    497, -2472 },
-    {   5054,  -3898,  -1822, -2097 },
-    {   5813,  -2792,     83, -1469 },
-    {   4432,  -4497,   1670, -5193 },
-    {   5338,  -4653,  -1109, -2200 },
-    {   3239,  -4401,   -648, -3655 },
-    {   2147,  -3598,  -1200, -4242 },
-    {   4417,  -2271,  -1552, -3210 },
-    {   6494,  -4360,    852, -3565 },
-    {   2393,  -6358,   -856, -4524 },
-    {   4959,  -4196,   -847, -1403 },
-    {   4924,  -5438,   -226, -3026 },
-    {   4254,  -5303,  -1306, -2424 },
-    {   4121,  -3126,  -2334, -1981 },
-    {   3437,  -4443,  -1464, -2953 },
-    {   3203,  -3459,   -529, -4339 },
-    {   5896,  -5945,    543, -3246 },
-    {   1987,  -4733,   -220, -4863 },
-    {   4358,  -4431,   -514, -3081 },
-    {   4583,  -2416,   -492, -2287 },
-    {   2943,  -5035,    419, -4927 },
-    {   5358,  -5129,    987, -4309 },
-    {   4460,  -3392,   1752, -5634 },
-    {   3415,  -4633,   1507, -5945 },
-    {    811,  -4692,   -445,  2333 },
-    {   1009,  -5613,  -1857,  1360 },
-    {   1338,  -2712,  -2720,  3036 },
-    {   1002,  -3754,  -2582,  2344 },
-    {    750,  -4608,  -2334,   714 },
-    {   2043,  -3207,  -2822,  2173 },
-    {   -140,  -4654,  -2953,   357 },
-    {    -54,  -4026,  -2376,  2695 },
-    {   1858,  -5022,   -717,  2287 },
-    {   2064,  -3894,   -722,  3255 },
-    {   2727,  -4558,   -332,  2603 },
-    {   1810,  -5378,    283,  1826 },
-    {   3935,  -4326,    762,  3383 },
-    {   -767,  -4697,  -2510,  1922 },
-    {   2146,  -4312,  -3090,  1641 },
-    {     54,  -5881,  -2114,   921 },
-    {   1992,  -5766,   -640,  1574 },
-    {   1200,  -5371,  -1114,  1828 },
-    {   2973,  -5337,     34,  2266 },
-    {   1531,  -5018,  -2817,  1192 },
-    {   3078,  -4570,    117,  1990 },
-    {    924,  -4286,  -1388,  2713 },
-    {    142,  -5058,  -2848,  1487 },
-    {   -106,  -6180,   -881,   842 },
-    {    673,  -5433,   -229,  1596 },
-    {    783,  -5710,  -2784,   562 },
-    {   1935,  -5729,  -2009,   856 },
-    {   -410,  -3375,  -3326,  2734 },
-    {    234,  -3000,  -2628,  3260 },
-    {    733,  -3405,  -3806,  1589 },
-    {    771,  -4285,  -3544,  1314 },
-    {   1192,  -3563,  -3960,  2178 },
-    {    206,  -5555,  -1250,  1546 },
-    {   -130,  -3815,  -1210,  3041 },
-    {    646,  -3940,   -393,  2992 },
-    {   -184,  -4931,  -1767,  1925 },
-    {   2746,  -5120,  -2275,  1464 },
-    {   2440,  -3731,  -3352,  2729 },
-    {   -490,  -4942,  -3779,   997 },
-    {     68,  -2636,  -4167,  3778 },
-    {     48,  -3986,  -4118,  2106 },
-    {   -978,  -5486,  -1336,  1390 },
-    {   1126,  -5297,   -855,   640 },
-    {   -472,  -3975,  -3622,  1557 },
-    {   2456,  -5344,  -1523,  1648 },
-    {   -774,  -5652,  -2417,  1147 },
-    {    995,  -6122,   -812,  1132 },
-    {   3282,  -4571,  -1763,  2175 },
-    {   3655,  -3862,   -676,  3568 },
-    {   3038,  -3647,  -1672,  3381 },
-    {   2595,  -2964,  -2772,  3263 },
-    {   4176,  -3353,  -1148,  4354 },
-    {   1603,  -3442,  -1500,  3444 },
-    {    828,  -6226,  -1783,   678 },
-    {   1421,  -3333,  -3080,  3403 },
-    {   1121,  -4727,  -1924,  1984 },
-    {   -186,  -5083,   -682,  1796 },
-    {    819,  -2778,  -3488,   530 },
-    {    421,  -2873,  -3832,  2596 },
-    {   2164,  -4263,  -1605,  2282 },
-    {    585,  -4437,   -682,  -491 },
-    {   -644,  -4452,  -1157,  2325 },
-    {   1991,  -4299,    210,  2834 },
-    {   2135,  -3632,  -2113,   665 },
-    {  -7482,  -2724,  -2662, -1380 },
-    {  -6983,  -2166,  -3756, -3509 },
-    {  -7085,  -1439,  -2397, -3112 },
-    {  -7760,  -3049,  -3319, -2822 },
-    {  -8413,  -2760,  -4406, -3298 },
-    {  -5995,  -3943,  -1260, -3750 },
-    {  -7879,  -1554,  -3464, -2606 },
-    {  -6314,  -2034,  -3878, -1681 },
-    {  -8849,  -2084,  -1399, -1231 },
-    {  -7153,  -2602,  -1384,  -817 },
-    {  -8041,  -2571,   -407, -2785 },
-    {  -7246,  -2233,  -1578,   260 },
-    {  -7336,  -3883,  -4061, -1342 },
-    {  -7619,  -3908,  -2342,   382 },
-    {  -8684,  -3724,  -1662,  -727 },
-    {  -7850,  -2922,  -1770, -3449 },
-    {  -6766,  -2034,  -1293, -1988 },
-    {  -6895,  -2116,   -968, -3744 },
-    {  -7136,  -5147,  -2618, -2809 },
-    {  -8224,  -3724,  -2519, -1589 },
-    {  -6711,  -2750,  -3021,  -219 },
-    {  -8059,  -1638,  -1102, -3175 },
-    {  -8710,  -4839,  -3963, -3143 },
-    {  -9363,  -4965,  -3257, -1002 },
-    {  -6099,  -1751,  -3157,  -395 },
-    {  -6453,  -3216,  -4597,  -483 },
-    {  -7879,  -5477,   -839, -2638 },
-    {  -7202,  -4038,   -526, -2856 },
-    {  -8022,  -1228,  -1910, -1646 },
-    {  -9117,  -1393,  -1582, -2535 },
-    {  -9095,  -2693,   -636, -2605 },
-    {  -9076,  -2580,  -3481, -2519 },
-    {  -8327,  -4859,  -2422,    83 },
-    {  -8368,  -2129,  -2324, -2173 },
-    {  -8554,  -4563,  -3842, -2007 },
-    { -10462,  -4261,  -1934, -2084 },
-    {  -9717,  -3187,  -2294, -1896 },
-    {  -9625,  -3889,  -3020, -3224 },
-    {  -9857,  -4955,  -4239, -2184 },
-    {  -9752,  -2351,  -2277, -3129 },
-    {  -7219,  -1302,  -2639, -1603 },
-    {  -7477,  -4360,  -3718,  -559 },
-    {  -5680,  -2033,  -2326, -3078 },
-    { -10190,  -5548,  -4643, -3601 },
-    {  -9431,  -4121,   -879, -2479 },
-    {  -8365,  -5450,  -2020, -1439 },
-    {  -6289,  -5178,  -1605, -3845 },
-    {  -8319,  -3866,   -687, -2792 },
-    {  -8131,  -1031,  -3608, -3947 },
-    { -10510,  -2560,  -1199, -2082 },
-    { -11015,  -3640,  -2748, -3041 },
-    {  -8762,  -5022,  -5231, -1162 },
-    { -10153,  -2715,  -4648, -4859 },
-    {  -7930,  -5205,  -1900, -3600 },
-    {  -9561,  -3548,  -4812, -3722 },
-    {  -7663,  -4709,  -1180, -1475 },
-    {  -9073,  -5707,  -1815, -2980 },
-    {  -8602,  -2363,  -2675, -3770 },
-    {  -9967,  -5614,  -3575, -3838 },
-    {  -8324,  -1005,  -2131, -3254 },
-    { -10331,  -5737,  -2550, -2940 },
-    {  -8234,  -3354,  -3361, -4479 },
-    {  -8140,  -1951,  -4526, -4545 },
-    {  -6679,  -2662,  -2284, -4182 },
-    {  -1122,  -1514,  -6427,  -212 },
-    {     54,  -1660,  -5424, -1404 },
-    {    254,  -2778,  -5222,   846 },
-    {   -267,  -1661,  -6577,   814 },
-    {   -305,  -2021,  -5759,  1484 },
-    {  -1791,  -2446,  -6867,   -86 },
-    {  -2929,  -3158,  -6603, -1799 },
-    {  -1391,  -3189,  -5557, -1053 },
-    {  -1602,   -884,  -6767, -1213 },
-    {   -361,   -318,  -6219,   -44 },
-    {  -4078,  -2635,  -5523,  -433 },
-    {   -956,    478,  -4382,  1470 },
-    {  -3300,  -2462,  -6021, -2721 },
-    {    708,  -2434,  -5085,  -540 },
-    {  -2435,  -3607,  -5647, -2110 },
-    {   -491,  -1134,  -4681, -2886 },
-    {     87,  -3435,  -4641, -1194 },
-    {   -586,  -2927,  -4784,   366 },
-    {  -1394,  -2326,  -6021,   350 },
-    {     97,  -2519,  -4678, -2120 },
-    {  -1547,  -1907,  -5069, -2993 },
-    {    268,  -3724,  -4719,   127 },
-    {   -827,  -1190,  -5912,  1144 },
-    {  -3959,  -2322,  -6898, -1974 },
-    {  -2728,  -2228,  -6426,  -562 },
-    {   -456,   -666,  -5785, -1609 },
-    {    531,  -1096,  -5731,  -656 },
-    {  -3569,   -688,  -3915,   110 },
-    {  -4752,  -1725,  -4393,  -377 },
-    {  -3210,  -3315,  -6960,  -840 },
-    {   -688,  -3416,  -4971,  1221 },
-    {  -1833,     77,  -6491, -2434 },
-    {   -239,   -255,  -6850,  -886 },
-    {  -2112,  -1490,  -6291, -2689 },
-    {  -1544,  -4579,  -5198, -1261 },
-    {  -2771,  -4014,  -5520,   683 },
-    {  -1635,  -2829,  -5512,  1214 },
-    {   -958,  -2582,  -4823,  2360 },
-    {  -2077,  -4566,  -4642,   365 },
-    {  -3112,  -4214,  -5960,  -823 },
-    {  -2467,  -2510,  -4858,  1467 },
-    {  -1561,  -3399,  -5822,   211 },
-    {   -775,  -1081,  -4424,  2636 },
-    {  -1263,     25,  -6378, -1392 },
-    {  -3476,   -366,  -5417, -1393 },
-    {  -3176,  -1476,  -4149,  1466 },
-    {  -2479,    518,  -4448,  -257 },
-    {  -2992,    158,  -4660, -1279 },
-    {  -1320,  -3872,  -4479,  1147 },
-    {  -1475,   -312,  -5318,   539 },
-    {  -3527,  -1679,  -5860, -1681 },
-    {  -3397,  -3438,  -5593,  1866 },
-    {  -4089,  -2439,  -4763,  1275 },
-    {   -748,  -4513,  -4687,   -48 },
-    {  -2166,  -4531,  -4691, -2856 },
-    {  -2385,   -853,  -6035,  -627 },
-    {  -1194,  -4091,  -4472, -1963 },
-    {   -682,  -3234,  -4084, -3033 },
-    {  -3255,  -5015,  -5328,   -12 },
-    {  -2313,  -3436,  -4601,  -155 },
-    {  -2792,  -1038,  -6947, -2019 },
-    {  -1244,  -1526,  -5771, -1882 },
-    {  -4679,  -3731,  -5506,   283 },
-    {  -3062,    -66,  -3558,  -758 },
-    {  -4895,  -1187,   4751,  3728 },
-    {  -7600,  -2752,   3320,  4613 },
-    {  -5703,  -2975,   3944,  2659 },
-    {  -4972,  -1257,   -246,  2952 },
-    {  -4221,  -2487,   1702,  4295 },
-    {  -2900,  -1529,   2458,  4935 },
-    {  -5061,    407,   2416,  4050 },
-    {  -6931,  -3478,   2761,  2213 },
-    {  -6037,  -3921,   3192,  1866 },
-    {  -6113,   -811,   2407,  3782 },
-    {  -5878,  -1716,   1207,  3478 },
-    {  -5953,  -2853,   2207,  2712 },
-    {  -6807,  -3223,   2749,  3595 },
-    {  -3272,  -3157,   1389,  3788 },
-    {  -5368,  -1904,   1980,  5077 },
-    {  -7235,  -1398,   3075,  4548 },
-    {  -4765,  -3487,   2755,  2796 },
-    {  -7658,  -4435,   2694,  2582 },
-    {  -6997,  -4282,    456,  3832 },
-    {  -5563,  -3115,    -63,  3713 },
-    {  -4244,  -4220,   1450,  2767 },
-    {  -3801,  -2194,    190,  4303 },
-    {  -5458,  -4119,   1958,  2274 },
-    {  -7300,  -3469,   3514,  3193 },
-    {  -4594,  -2067,    775,  4752 },
-    {  -3389,  -1654,   1464,  5412 },
-    {  -4845,  -3483,    964,  3437 },
-    {  -6007,  -2818,   1666,  4659 },
-    {  -8709,  -5007,   1757,  3287 },
-    {  -5833,  -4389,   1025,  3171 },
-    {  -5788,  -1780,   3944,  3661 },
-    {  -4430,   -920,   1938,  4753 },
-    {  -7066,  -1857,   4591,  4538 },
-    {  -3549,   -513,   1427,  5317 },
-    {  -7517,  -1220,   2883,  3049 },
-    {  -7605,  -2687,   1874,  2735 },
-    {  -8718,  -4035,   2676,  3730 },
-    {  -7990,  -3907,   1185,  2607 },
-    {  -6058,  -1744,   3349,  5157 },
-    {  -5954,    565,   3161,  3250 },
-    {  -6478,   -612,   1930,  2271 },
-    {  -6535,  -1445,     -2,  1618 },
-    {  -8963,  -4151,   1192,  4044 },
-    {  -7227,  -3570,   1600,  4234 },
-    {  -4674,     79,    595,  3015 },
-    {  -3974,    430,   2727,  5137 },
-    {  -5299,      9,   3714,  4779 },
-    {  -6779,  -2699,     -8,  2436 },
-    {  -7016,  -1145,   1293,  2310 },
-    {  -6955,  -3312,   1534,  1801 },
-    {  -4025,    740,   1850,  4054 },
-    {  -9589,  -3460,   4154,  5270 },
-    {  -4404,  -1181,   4298,  5173 },
-    {  -7356,  -4583,    -18,  2644 },
-    {  -6516,  -1235,   4439,  6234 },
-    {  -3453,   -301,   4344,  4464 },
-    {  -4643,   1530,   3315,  4340 },
-    {  -4575,  -2557,   3754,  3682 },
-    {  -3643,  -3501,   2051,  2997 },
-    {  -5412,  -2475,   2301,  1579 },
-    {  -5846,    259,   1360,  2348 },
-    {  -5258,  -1358,   1050,   838 },
-    {  -5542,   -219,   6377,  5750 },
-    {  -5713,  -2952,    922,   899 },
-    {  -2049,  -1135,   5206,  1033 },
-    {  -1693,  -1886,   4835,  -106 },
-    {  -2344,  -3504,   4232,   -13 },
-    {  -2475,  -2334,   5043,  1126 },
-    {   -787,  -2549,   3880,  2138 },
-    {  -3159,  -2341,   4830,  2887 },
-    {  -1780,  -1009,   6240,  2061 },
-    {  -4327,  -3363,   2818,   886 },
-    {  -3376,  -2743,   4104,   207 },
-    {  -3250,  -4640,   2718,  1498 },
-    {   -382,  -1075,   4382,  3460 },
-    {  -2416,  -4168,   3530,   816 },
-    {  -1756,  -2708,   4861,   622 },
-    {  -1879,  -2097,   5156,  2889 },
-    {  -2496,  -2418,   3722,  2671 },
-    {  -2717,  -3252,   3341,  1944 },
-    {  -4063,  -4091,   3306,   267 },
-    {  -3549,  -3808,   3747,   842 },
-    {  -2635,    546,   5794,  1894 },
-    {  -1857,  -1121,   4383,  3964 },
-    {  -2226,  -2166,   3489,  3678 },
-    {  -3492,   -660,   5323,  1063 },
-    {  -3033,  -3130,   4382,  1828 },
-    {  -2703,   -625,   6369,  2851 },
-    {  -1656,  -2842,   4584,  -528 },
-    {  -4781,  -2622,   4390,  2097 },
-    {   -413,  -2045,   5081,  3035 },
-    {  -3810,  -2662,   4532,  1095 },
-    {  -3144,  -1858,   5215,  1880 },
-    {  -3562,  -1795,   4928,   670 },
-    {  -4800,  -1509,   5189,  1859 },
-    {  -1085,  -3832,   4169,   900 },
-    {  -1969,  -3270,   2857,  2878 },
-    {  -4267,  -4140,   3176,  1805 },
-    {  -5145,  -3727,   3524,  1168 },
-    {  -1346,  -1876,   5501,  1748 },
-    {  -4998,  -2945,   3699,   338 },
-    {  -3458,  -3096,   3406,  -635 },
-    {  -1751,  -3209,   3508,   395 },
-    {  -2507,    170,   5987,   705 },
-    {  -3756,  -1072,   5647,  3536 },
-    {  -2870,  -1439,   5026,  3212 },
-    {  -3913,  -3225,   3669,  2144 },
-    {  -3739,    226,   5747,   764 },
-    {  -2052,   -820,   5266,  3093 },
-    {  -3214,  -3820,   2409,  2391 },
-    {  -4398,  -2588,   3501,  -218 },
-    {  -4484,  -1763,   4180,  -198 },
-    {  -3368,  -1525,   4362,  -134 },
-    {  -2407,    224,   4905,  3533 },
-    {  -1369,  -2937,   4728,  1788 },
-    {  -4848,  -1707,   4159,   851 },
-    {  -3454,  -1749,   4281,  3230 },
-    {  -1990,  -3853,   3487,  1735 },
-    {  -3117,     92,   6155,  4075 },
-    {  -2676,  -2472,   4078,  -589 },
-    {  -1547,  -2012,   2626,  1835 },
-    {  -4275,   -588,   4824,   725 },
-    {   -601,  -2249,   3736,  3548 },
-    {  -4060,    -61,   5333,  3097 },
-    {  -4303,      7,   6551,  3054 },
-    {  -5003,  -1029,   5786,  3319 },
-    {  -2810,   -728,   5392,   199 },
-    {  -1232,   -200,   5228,  3121 },
-    {   2621,    165,  -6255,   298 },
-    {   3669,    537,  -6844,  1564 },
-    {   1598,  -1190,  -6235,  2523 },
-    {   2164,    -32,  -6894,  1383 },
-    {    853,  -1597,  -6069,  1449 },
-    {   1377,  -1661,  -5266,   108 },
-    {   2660,     48,  -5172,  -517 },
-    {   1903,   -391,  -5677,  1010 },
-    {   3792,    206,  -5274,   -11 },
-    {   1239,   2776,  -2929,  2721 },
-    {   4071,    149,  -7259,  3125 },
-    {   1436,   -480,  -6156,  -196 },
-    {   1373,  -1960,  -5005,  3122 },
-    {   3413,  -1271,  -5176,  3283 },
-    {   3060,    -68,  -6495,  2238 },
-    {   2700,  -2075,  -4681,    91 },
-    {   2928,  -1728,  -5168,  1858 },
-    {   4424,    828,  -4471,    88 },
-    {   2672,  -2604,  -4038,  2753 },
-    {   5223,   -123,  -6749,  2295 },
-    {   4237,   -420,  -5538,  1353 },
-    {   4744,  -1281,  -4097,  4708 },
-    {   1103,  -2764,  -4751,  2024 },
-    {   3747,  -1913,  -3911,  3960 },
-    {   2470,  -1416,  -5542,   615 },
-    {   4847,  -1354,  -5334,  1733 },
-    {   5336,     88,  -7593,  4007 },
-    {   2388,  -2880,  -4807,  1037 },
-    {   4495,   1391,  -5685,  -139 },
-    {   5253,   1637,  -6450,  1533 },
-    {   1199,    795,  -5515,  1261 },
-    {   1397,  -1259,  -4252,  3838 },
-    {    746,     70,  -6640,   604 },
-    {   1584,    166,  -4972,  3072 },
-    {    380,   -999,  -5397,  2267 },
-    {   2974,   1707,  -3242,  5360 },
-    {   5202,   -403,  -5453,  2832 },
-    {   3718,  -1731,  -4760,   714 },
-    {   4150,   -975,  -4792,    61 },
-    {   2925,   -818,  -4841,    15 },
-    {   5301,    577,  -4006,  3259 },
-    {   5265,   1986,  -5679,  3028 },
-    {   3752,   1928,  -4509,  3729 },
-    {   3278,   1925,  -6370,  1247 },
-    {   5107,   1721,  -4853,  3127 },
-    {   3279,   2982,  -2515,  4005 },
-    {   4622,    668,  -6204,   759 },
-    {   6034,    317,  -5763,  4818 },
-    {   -558,     57,  -3785,  2817 },
-    {   4476,   1616,  -3965,  4536 },
-    {   5953,   2056,  -8215,  2715 },
-    {   4387,   2613,  -7463,   868 },
-    {   5834,   1088,  -4736,  4924 },
-    {   6473,   -856,  -6991,  4172 },
-    {   4959,   -293,  -5162,    76 },
-    {   2731,   -843,  -6119,  3847 },
-    {   3245,   1202,  -6833,   616 },
-    {   2553,   1383,  -3829,  3859 },
-    {   4332,   2099,  -3480,  3622 },
-    {   2110,   2683,  -2728,  3990 },
-    {    876,   1167,  -3290,  3466 },
-    {   3991,   1709,  -2410,  4077 },
-    {   5105,    939,  -2584,  3256 },
-    {   4719,    688,  -1566,  3040 },
-    {  -3632,   4335,   1266, -3303 },
-    {  -4956,   3207,   1312, -2806 },
-    {  -4669,   2627,   2663, -2435 },
-    {  -4282,   3708,   2303, -3038 },
-    {  -4536,   2297,   -175, -3350 },
-    {  -5234,   2503,   -139,  -880 },
-    {  -3978,   1512,   1092, -3619 },
-    {  -4519,   4649,   1363, -2455 },
-    {  -5118,   3132,   1961, -1577 },
-    {  -5196,   3379,   -182, -1378 },
-    {  -6420,   4486,   2397, -1993 },
-    {  -5030,   5046,   1292, -1118 },
-    {  -4559,   2573,   -927, -1406 },
-    {  -3501,   3730,    691, -4930 },
-    {  -4364,   2758,   1007, -3909 },
-    {  -4026,   2839,  -1559, -2340 },
-    {  -5037,   4053,    836, -1571 },
-    {  -4727,   5136,   1110, -3588 },
-    {  -5245,   2799,   -999, -2164 },
-    {  -4954,   1501,    422, -3963 },
-    {  -5994,   2726,   1462, -2833 },
-    {  -5621,   5159,   2038, -2512 },
-    {  -4991,   2291,   1917, -3151 },
-    {  -5469,   4382,   -148, -2978 },
-    {  -5858,   1983,    807, -2720 },
-    {  -4709,   3556,    952,  -467 },
-    {  -2489,   2362,   1714, -4230 },
-    {  -4717,   5004,  -1180, -3672 },
-    {  -5914,   3653,   1359, -1317 },
-    {  -5506,   2995,    780, -1059 },
-    {  -5287,   3945,   2480, -2293 },
-    {  -3849,   4358,    322, -1770 },
-    {  -3911,   3570,    252, -3185 },
-    {  -3660,   5128,    158, -3719 },
-    {  -4599,   3277,   -503, -2727 },
-    {  -3673,   3760,  -1252, -3339 },
-    {  -5161,   2337,    388, -1943 },
-    {  -3529,   2216,   2156, -3080 },
-    {  -4309,   4331,   1808, -1460 },
-    {  -4782,   3820,    480, -2504 },
-    {  -4166,   3544,   -378, -1567 },
-    {  -5572,   2466,   -418, -2909 },
-    {  -6096,   2930,    119, -1878 },
-    {  -5963,   3554,   1011, -2233 },
-    {  -6433,   4335,    935, -2930 },
-    {  -5004,   3314,  -1352, -3430 },
-    {  -6042,   3463,  -1008, -3940 },
-    {  -4671,   2214,   -640, -5040 },
-    {  -2795,   3759,   1412, -3803 },
-    {  -3647,   4436,    729,  -515 },
-    {  -3594,   1033,     56, -4148 },
-    {  -2908,   3027,   2889, -3485 },
-    {  -3338,   2234,    313, -4285 },
-    {  -3825,   4497,   -561, -2634 },
-    {  -6167,   3012,    -48, -3149 },
-    {  -4828,   3515,   -969, -4475 },
-    {  -5789,   2757,   -539, -4173 },
-    {  -2452,   3067,    564, -4249 },
-    {  -4921,   1358,   1331, -2889 },
-    {  -3127,   4239,  -1045, -1523 },
-    {  -4780,   2326,  -1118, -3446 },
-    {  -3908,   5546,    152, -2622 },
-    {  -6972,   2976,    337, -2809 },
-    {  -4839,   4613,    -35, -4077 },
-    {  -1408,   4822,  -1149, -4997 },
-    {   -981,   4979,   -912, -6304 },
-    {  -2098,   5689,   -888, -2878 },
-    {  -3343,   4814,   -657, -4434 },
-    {  -2461,   3601,   -967, -4869 },
-    {  -2652,   3944,     87, -5520 },
-    {  -1104,   6076,    174, -6407 },
-    {    355,   5370,  -1721, -5869 },
-    {   1242,   4497,  -1107, -5091 },
-    {    -89,   4002,  -1491, -5182 },
-    {   1059,   5693,  -1591, -4905 },
-    {   1323,   4682,  -2078, -4768 },
-    {    818,   3996,   -549, -5468 },
-    {   -287,   4529,    929, -5543 },
-    {   -919,   5519,  -2791, -2844 },
-    {  -1407,   5679,  -3289, -3974 },
-    {   -189,   6530,  -3547, -4002 },
-    {   -900,   7039,  -3371, -4855 },
-    {  -2983,   7211,   -363, -4835 },
-    {   -814,   6503,   -104, -5106 },
-    {  -2386,   6896,    809, -4919 },
-    {    845,   4492,    352, -6621 },
-    {  -1998,   7237,  -1646, -4231 },
-    {  -3380,   6251,    471, -4577 },
-    {  -1908,   7059,     84, -5726 },
-    {   -340,   6346,   -803, -6265 },
-    {  -2279,   5834,    -47, -4633 },
-    {  -1532,   5286,  -1748, -1901 },
-    {  -2757,   6188,   -453, -3415 },
-    {  -1255,   6405,  -2043, -6357 },
-    {    918,   5581,   -121, -5667 },
-    {   1840,   5336,   -821, -5034 },
-    {  -2475,   4992,  -1825, -3104 },
-    {  -2413,   5606,  -1789, -4298 },
-    {    132,   5128,  -2389, -4442 },
-    {    223,   6400,  -2653, -4742 },
-    {   -673,   5012,    680, -4582 },
-    {  -1657,   6624,   -349, -3596 },
-    {   -755,   6289,  -1860, -3978 },
-    {   -572,   6894,  -1946, -5207 },
-    {  -1141,   4756,  -2665, -5586 },
-    {  -1073,   4269,   -431, -4030 },
-    {    186,   5761,    916, -5868 },
-    {  -1907,   4836,   1017, -5106 },
-    {   -963,   3363,  -1248, -6348 },
-    {  -3262,   4774,  -1818, -5858 },
-    {    847,   3812,  -2538, -4302 },
-    {  -1223,   5903,   1360, -5479 },
-    {  -1094,   6923,  -1244, -2381 },
-    {    267,   6276,   -709, -2846 },
-    {   -157,   5840,   1124, -4266 },
-    {    889,   3206,   -910, -5305 },
-    {  -1736,   3344,    582, -4838 },
-    {  -2357,   5676,  -2695, -6277 },
-    {  -1916,   6901,   -986, -5397 },
-    {  -3062,   6028,   -695, -5687 },
-    {   1836,   3566,  -1357, -5226 },
-    {  -2176,   4938,    646, -3872 },
-    {  -2199,   3055,   -208, -6124 },
-    {   -236,   3032,   -821, -5325 },
-    {  -3989,   7277,   -565, -3899 },
-    {   -595,   4362,     74, -5975 },
-    {    684,   5874,   -841, -4424 },
-    {  -2731,   6305,  -2389, -5465 },
-    {  -5775,   1325,    -56, -2528 },
-    {  -7029,   -534,  -1890, -3278 },
-    {  -5798,    -15,  -2734, -2210 },
-    {  -5504,  -1198,   -353, -3659 },
-    {  -5079,    960,   -894, -4336 },
-    {  -6073,    -36,   -133, -3014 },
-    {  -5782,   -259,  -1025, -3986 },
-    {  -6843,   1262,   -807, -1639 },
-    {  -5263,   -918,  -3290,  -579 },
-    {  -4840,    461,  -2158,  -533 },
-    {  -6014,    -50,   -620,   504 },
-    {  -5843,    241,  -1359,  -282 },
-    {  -5898,    577,    769, -3271 },
-    {  -6833,   -946,   -466, -3347 },
-    {  -6026,   1459,   -512,  -729 },
-    {  -7361,    747,   -388, -1110 },
-    {  -6391,   2142,  -1160, -2513 },
-    {  -6995,    304,    498, -2673 },
-    {  -6757,    679,   -386,  -433 },
-    {  -5222,   1688,  -1093, -1032 },
-    {  -5019,    575,    184, -3627 },
-    {  -4237,    628,  -3507, -1243 },
-    {  -7479,   -456,  -1722, -1486 },
-    {  -6464,    713,  -1273, -1153 },
-    {  -6255,   1682,   -606, -3607 },
-    {  -7033,   1497,    -71, -1955 },
-    {  -6694,   1556,  -1721, -3214 },
-    {  -6114,   -356,    813, -2575 },
-    {  -5308,    632,  -1851, -1636 },
-    {  -5742,   -911,  -1733,   383 },
-    {  -6083,   -387,  -2313,  -879 },
-    {  -6535,   -530,  -1505, -2083 },
-    {  -4896,   1223,  -2750, -1816 },
-    {  -6392,   -463,  -3247, -2093 },
-    {  -5373,   1264,  -2706, -3042 },
-    {  -3894,  -1390,  -1020,  -891 },
-    {  -6179,   1168,  -1966, -1922 },
-    {  -5162,   1668,  -1617, -1916 },
-    {  -6453,    920,  -1169, -2432 },
-    {  -6130,   2005,   -536, -1519 },
-    {  -6552,    -98,   -518, -1938 },
-    {  -7528,    355,  -1101, -1772 },
-    {  -5745,    610,   -247, -1360 },
-    {  -7003,    177,  -2064, -1958 },
-    {  -6956,   -570,  -2220, -4225 },
-    {  -7830,    791,  -1394, -2774 },
-    {  -7634,    480,  -3171, -4224 },
-    {  -7913,   1154,   -350, -2381 },
-    {  -5063,   1704,  -1804, -2977 },
-    {  -4887,   -524,  -2703,   188 },
-    {  -5551,    406,  -1620, -3063 },
-    {  -7109,   1342,    381, -3021 },
-    {  -6846,    631,   -458, -3398 },
-    {  -4606,   -605,     11, -3930 },
-    {  -8134,   -225,  -1738, -2648 },
-    {  -7043,    402,  -2734, -3059 },
-    {  -7417,   1825,  -2545, -4389 },
-    {  -6971,   -236,  -1031,  -665 },
-    {  -5752,   2111,  -1632, -3808 },
-    {  -7660,    -78,   -624, -3135 },
-    {  -6358,    619,  -1951, -3911 },
-    {  -8134,    408,  -1935, -3695 },
-    {  -6335,   1911,  -2368, -4505 },
-    {  -7116,   2163,   -344, -2753 },
-    {   2357,   4488,   2220, -5682 },
-    {   1385,   3206,   2300, -5305 },
-    {   1419,   2557,   5203, -3516 },
-    {    262,   4315,   3920, -1847 },
-    {   3316,   3187,   1612, -5609 },
-    {   1729,   2350,   1673, -6068 },
-    {   1603,   6126,   1467, -2839 },
-    {  -1339,   3316,   3691, -3530 },
-    {   -563,   4618,   3180, -4548 },
-    {    463,   4624,   3111, -5614 },
-    {   1246,   5455,   3356, -5720 },
-    {    480,   2149,   5422, -2893 },
-    {   1768,   4827,    913, -5579 },
-    {   -149,   5381,   4366, -3297 },
-    {    985,   3672,   2644,   -92 },
-    {   -258,   2911,   5817, -2213 },
-    {   3428,   3289,   3351, -3541 },
-    {   -666,   3295,   4727, -2869 },
-    {     35,   6641,   4160, -4052 },
-    {    623,   6787,   3156, -4560 },
-    {   2654,   4360,   4676, -4632 },
-    {   1386,   5246,   4834, -4497 },
-    {   3488,   4574,   3856, -5946 },
-    {    383,   4481,   4168, -4110 },
-    {   1753,   3652,   4288, -3326 },
-    {   1344,   4905,   2508, -4660 },
-    {   1580,   4106,   3104, -2224 },
-    {   2027,   5038,   1683, -1554 },
-    {    446,   3699,   5872, -3013 },
-    {   4637,   4087,   3578, -5018 },
-    {   2629,   3560,   5331, -4900 },
-    {   1527,   6674,   2523, -4131 },
-    {  -1437,   2804,   2528, -4464 },
-    {   -229,   3355,   2016, -5537 },
-    {   3666,   3418,   4374, -4581 },
-    {   1192,   3799,    923, -6596 },
-    {   2040,   2956,    448, -5322 },
-    {   2468,   5768,   4029, -5869 },
-    {   3438,   6516,   3529, -6667 },
-    {   2737,   5495,    680, -5535 },
-    {   3896,   5727,   1801, -4958 },
-    {   4988,   4957,   3592, -6518 },
-    {   -542,   4416,   5794, -2787 },
-    {   4136,   4354,   2064, -4696 },
-    {   3067,   5936,   1207, -3396 },
-    {   2789,   4966,   2405, -3854 },
-    {   1731,   3270,   3251, -1063 },
-    {   1767,   5537,   2084, -2349 },
-    {    465,   3116,   4532,  -837 },
-    {   1499,   2627,   4610, -2212 },
-    {    122,   3095,   3642, -3552 },
-    {   2542,   2866,   2705, -6402 },
-    {   3134,   4323,    698, -4785 },
-    {    731,   1859,   3112, -5242 },
-    {   2553,   2980,   3241, -4846 },
-    {   1329,   5310,   1607, -6624 },
-    {   2468,   1858,   3476, -1034 },
-    {   -172,   4996,   2000, -5562 },
-    {   2621,   4220,   1574, -3386 },
-    {   -333,   1832,   3362, -4117 },
-    {   2169,   6762,   3065, -6225 },
-    {   2844,   5528,   3223, -4765 },
-    {    526,   5175,   1644, -4267 },
-    {   2922,   4426,   2414, -2610 },
-    {    452,   1399,  -4516, -2636 },
-    {   2872,   1720,  -4667, -1435 },
-    {   1279,    702,  -5424, -1984 },
-    {   2187,    870,  -5021, -1341 },
-    {    583,   -144,  -4628, -2464 },
-    {      3,   2237,  -5284, -2827 },
-    {    -19,   1005,  -5460, -1819 },
-    {   2897,   2084,  -5885,  -515 },
-    {   -400,   3370,  -5527, -2947 },
-    {   1505,   2593,  -5518, -1802 },
-    {   1341,   4534,  -5094, -1899 },
-    {   3241,   3670,  -5493, -1252 },
-    {  -1287,    921,  -5994, -1675 },
-    {    627,    408,  -6652,  -364 },
-    {   -260,   1127,  -4849, -3247 },
-    {    371,   3400,  -5976, -2285 },
-    {   1533,   1566,  -6373,  -610 },
-    {   2462,   4274,  -6184, -1254 },
-    {   1782,   3363,  -6222, -1381 },
-    {    572,   4650,  -5673, -2754 },
-    {   2674,   3414,  -4460, -2154 },
-    {   3614,   3820,  -6883,  -398 },
-    {   1136,     -1,  -5511, -1112 },
-    {  -1773,   1137,  -5647, -2377 },
-    {   -753,   2104,  -6085, -2565 },
-    {   -204,   3025,  -4731, -1418 },
-    {  -1486,   1438,  -4380,  -216 },
-    {    302,    858,  -5786,  -264 },
-    {   3486,   1495,  -5234,  -783 },
-    {    888,   2327,  -3423, -3720 },
-    {   -259,    772,  -6596, -1311 },
-    {  -1197,   2073,  -5174, -1826 },
-    {   1500,   3470,  -4462, -2645 },
-    {   3072,   1960,  -3277, -2264 },
-    {   1841,    952,  -4324, -2340 },
-    {   1994,   2200,  -3940, -2923 },
-    {  -1782,   1699,  -4667, -1075 },
-    {  -1464,   2906,  -3468,  -375 },
-    {    366,   2380,  -3747,  1467 },
-    {   -545,   1645,  -4619,   376 },
-    {   1724,   2350,  -2374, -3512 },
-    {   3184,   2628,  -2996, -3275 },
-    {    734,   2010,  -6239, -1479 },
-    {    524,   3756,  -4496, -3263 },
-    {   1492,   3570,  -3494, -3600 },
-    {   -932,    618,  -5389, -2894 },
-    {   -133,   2161,  -4083, -3267 },
-    {    786,    774,  -3279, -3731 },
-    {   1078,    803,  -3843, -3007 },
-    {   -332,   3405,  -3347,    40 },
-    {    -17,      6,  -4005, -3690 },
-    {   -189,   4372,  -4488, -2561 },
-    {   -450,   3846,  -3790, -1370 },
-    {    362,   2212,  -5272,   -15 },
-    {  -1529,    791,  -6802, -2296 },
-    {   2145,   4241,  -4474,   376 },
-    {   1813,   2426,  -2932, -2726 },
-    {   -542,   4557,  -3140, -1080 },
-    {   1192,   3784,  -4371,   -20 },
-    {   2784,   5188,  -6399, -1394 },
-    {    431,   4561,  -3673, -1398 },
-    {   1382,   3096,  -4083,  1253 },
-    {   1209,   4224,  -2930,  1500 },
-    {   2798,   2684,  -6676,  -606 },
-    {  -2396,   1510,  -5381, -2713 },
-    {  -2625,   2542,  -4032, -2880 },
-    {  -1231,   3967,  -4098, -2886 },
-    {  -1393,   2374,  -3862, -4525 },
-    {  -2495,   1665,  -1637, -5445 },
-    {  -3854,   1759,  -1750, -4944 },
-    {  -2373,   1668,  -2856, -6251 },
-    {  -2668,   1981,   -886, -4557 },
-    {  -2927,   4427,  -3451, -6172 },
-    {  -1925,   2596,  -4696, -2527 },
-    {  -3202,   2847,  -3928, -5896 },
-    {  -3332,   1665,  -5025, -3412 },
-    {  -3212,   3115,  -4155, -4062 },
-    {  -1013,   3205,  -5133, -3751 },
-    {  -2022,   4595,  -3947, -5611 },
-    {  -3556,   1755,  -3715, -2300 },
-    {  -1784,   4114,  -2723, -1773 },
-    {  -3586,   4081,  -2733, -4942 },
-    {  -1608,   3685,  -4154, -4573 },
-    {  -3368,   4042,  -4452, -6227 },
-    {  -1407,   3881,  -5729, -3719 },
-    {  -2751,   3281,  -5077, -4999 },
-    {  -3791,   2410,  -4906, -5288 },
-    {   -730,   2303,  -4217, -3755 },
-    {  -1812,   2311,  -5492, -3709 },
-    {   -610,   4336,  -3915, -3783 },
-    {  -2841,   4337,  -4278, -4430 },
-    {  -1662,   4666,  -4661, -3964 },
-    {   -589,   5209,  -4923, -3682 },
-    {  -4155,   2234,  -4076, -4218 },
-    {  -3951,   2770,  -2665, -2805 },
-    {  -2302,   3228,  -3717, -1908 },
-    {  -3129,   4373,  -2264, -2851 },
-    {   -447,   1363,  -3578, -4323 },
-    {  -2648,   4237,  -3159, -3071 },
-    {  -4072,   3241,  -3541, -4605 },
-    {  -4507,   3458,  -2339, -3838 },
-    {  -1646,    997,  -4926, -3970 },
-    {  -3025,   1614,  -3940, -1242 },
-    {  -1337,   1756,  -3163, -5529 },
-    {  -3203,   1865,  -3282, -4354 },
-    {  -1646,   2118,  -2203, -6018 },
-    {    174,   1871,  -2707, -4639 },
-    {  -2607,   1485,  -4778, -4750 },
-    {  -2199,   3991,  -3134, -4879 },
-    {  -2962,   3323,  -2816, -2419 },
-    {  -5286,   2495,  -4548, -5395 },
-    {  -2810,   3710,  -2274, -4211 },
-    {   -330,   3006,  -2993, -4678 },
-    {  -1187,   2411,  -2743, -5196 },
-    {   -664,   4033,  -3101, -5641 },
-    {  -1458,   3602,  -2816, -5371 },
-    {  -4116,   4923,  -3321, -5630 },
-    {  -4165,   2528,  -2592, -4798 },
-    {  -2759,   3080,  -2333, -5719 },
-    {  -5157,   3011,  -5526, -6348 },
-    {  -3095,   2126,  -5881, -4234 },
-    {  -4377,   3849,  -3600, -6099 },
-    {  -1994,   4947,  -5235, -4753 },
-    {  -1067,    600,  -3258, -5133 },
-    {  -4992,   3302,  -2208, -5051 },
-    {  -3377,   2981,  -1655, -4815 },
-    {  -3325,   2446,  -1787, -6116 },
-    {  -2341,   2737,  -3240, -6347 },
-    {  -2258,  -3732,   3710, -1235 },
-    {  -1558,  -3849,   2694, -3012 },
-    {   -599,  -4837,   3050, -2951 },
-    {  -2246,  -5433,   2798, -1910 },
-    {  -2255,  -4989,   3260,   270 },
-    {  -3026,  -5353,   2693, -1036 },
-    {  -1151,  -6097,   1097, -3782 },
-    {  -3391,  -6012,   2130, -1303 },
-    {  -2850,  -4422,   3375,  -480 },
-    {  -1138,  -3779,   1491, -4162 },
-    {   -551,  -3892,   3787, -2082 },
-    {  -3221,  -3676,   3144, -1202 },
-    {  -3023,  -5196,   2650,   605 },
-    {  -1756,  -5729,   2646,   321 },
-    {  -2693,  -4409,    494, -4797 },
-    {  -1913,  -4573,   3372, -1730 },
-    {  -1277,  -3604,   4061,  -993 },
-    {   -420,  -4993,   1351, -4796 },
-    {  -3052,  -5333,   1435, -1242 },
-    {   -602,  -5034,   3869, -1141 },
-    {  -2436,  -4680,   1665, -3019 },
-    {  -2657,  -3658,   1459, -3391 },
-    {  -1220,  -6246,   2749,  -525 },
-    {  -3838,  -4844,   2265, -1735 },
-    {  -1247,  -5679,   3356, -1417 },
-    {   -917,  -5448,   3342,   105 },
-    {  -1756,  -6839,   2276, -2350 },
-    {   -412,  -5206,   1764, -3539 },
-    {  -1439,  -6915,   1442, -3750 },
-    {  -1381,  -4439,   3863,  -282 },
-    {  -3482,  -4953,   2726,  -336 },
-    {  -1376,  -5931,   1714, -1987 },
-    {  -1716,  -4405,   2608,   105 },
-    {  -1590,  -5191,   2652, -2704 },
-    {  -2149,  -6442,   2453, -1263 },
-    {  -3426,  -3832,   2334, -1829 },
-    {  -2747,  -5948,   2362,  -173 },
-    {  -2435,  -3267,   2966, -1710 },
-    {  -3979,  -4282,   2705,  -775 },
-    {   -356,  -4238,   2544, -4343 },
-    {  -1363,  -6471,   2817, -1836 },
-    {  -2878,  -5117,    218, -3149 },
-    {  -3539,  -5196,   1710, -2356 },
-    {  -2888,  -4537,   2746, -1701 },
-    {  -1870,  -4439,   1496, -4121 },
-    {  -1486,  -3388,   3349, -2145 },
-    {  -3333,  -4138,   1467, -2876 },
-    {   -345,  -5340,   1012, -1190 },
-    {  -1672,  -4992,   2289, -1029 },
-    {  -2146,  -5528,   3038,  -635 },
-    {   -316,  -3656,   3426, -3152 },
-    {  -2695,  -5812,   2336, -2050 },
-    {  -2067,  -6052,    737, -3258 },
-    {  -2664,  -4205,   -350, -1266 },
-    {   -617,  -5406,     80, -4853 },
-    {  -2418,  -3825,   1853, -1326 },
-    {  -1961,  -4339,    583, -4315 },
-    {  -1495,  -5141,   -133, -5205 },
-    {  -3208,  -6440,   1691, -2069 },
-    {  -2632,  -3633,   2325, -2761 },
-    {  -2624,  -5670,   1252, -3676 },
-    {  -3687,  -5608,    687, -2833 },
-    {  -3320,  -5707,     16, -3877 },
-    {  -2738,  -6112,     84, -5135 },
-    {   2277,  -5661,   3076,   843 },
-    {   1555,  -5769,   2821, -5236 },
-    {    536,  -6381,    603, -4910 },
-    {    734,  -4609,   3314, -4092 },
-    {   1836,  -4547,   3267, -4322 },
-    {    -13,  -5976,   3752, -1607 },
-    {   1423,  -6318,   2336,   398 },
-    {    365,  -7779,   1498,  -534 },
-    {   2104,  -8366,   2946, -1345 },
-    {    143,  -5545,   1898, -3756 },
-    {    655,  -6852,   1430,   148 },
-    {      4,  -6653,   2397,   -59 },
-    {   2346,  -5996,   4562,  -934 },
-    {   1229,  -7104,   2963,  -598 },
-    {   -528,  -7048,   2887, -1790 },
-    {   1451,  -6857,   3900, -1637 },
-    {    554,  -6018,   3336,     9 },
-    {   3278,  -5758,   4034,   129 },
-    {   3541,  -7145,   4905, -1575 },
-    {   2339,  -6907,   3464,  -301 },
-    {   2775,  -7301,   1667, -3894 },
-    {    539,  -7887,    991, -4156 },
-    {   2115,  -7421,   3131, -3075 },
-    {   2803,  -8546,   2564, -5836 },
-    {   2869,  -5833,   1620, -4561 },
-    {   2591,  -7281,   3215, -4719 },
-    {  -1228,  -8477,    706, -4782 },
-    {   1967,  -5243,   4813, -1940 },
-    {    701,  -7010,   2273, -3893 },
-    {    915,  -8470,   1918, -5620 },
-    {    -94,  -6715,    156, -3873 },
-    {   1074,  -5607,   4389, -1017 },
-    {   2739,  -6551,   1227, -3521 },
-    {    725,  -7835,   2701, -1291 },
-    {   -493,  -7475,   2263, -1075 },
-    {   -412,  -6508,   2984,  -744 },
-    {    665,  -5451,   3725, -2692 },
-    {   1499,  -8129,   3564, -2072 },
-    {   2870,  -6333,   4487, -2108 },
-    {    706,  -5007,   3911,  -152 },
-    {   -482,  -8660,   1483, -2900 },
-    {   2481,  -6596,   2518, -1715 },
-    {   1403,  -6414,   1398, -5387 },
-    {    652,  -6267,    583, -5942 },
-    {    694,  -7540,    646, -6272 },
-    {   2275,  -7614,    256, -5015 },
-    {   1416,  -9727,   1900, -3153 },
-    {   2760,  -6433,   3875, -3771 },
-    {   2325, -11196,   2182, -5155 },
-    {   1223, -11061,   1377, -5097 },
-    {    108, -10603,    307, -4952 },
-    {   -118,  -8268,   1650, -1572 },
-    {   1839,  -7943,   1755,  -612 },
-    {   2501,  -9056,    981, -2969 },
-    {   2902,  -8476,   1491, -5780 },
-    {   1995, -11175,   1585, -3643 },
-    {    696,  -8212,    828, -2474 },
-    {   1526,  -8649,   1380, -1210 },
-    {    461,  -7253,   3222, -2229 },
-    {   2966,  -8641,   4121, -3271 },
-    {    833,  -6039,   2361, -1086 },
-    {   3565,  -7312,   1980, -5427 },
-    {   2850,  -8671,   3760, -1846 },
-    {   2643,  -7281,   2163,  -173 },
-    {   3463,  -3706,  -3132,  -923 },
-    {   1315,  -3825,  -3443,     2 },
-    {   2594,  -4083,  -3815,   670 },
-    {   1826,  -4291,  -2741,  -155 },
-    {    868,  -3749,  -4175,  -298 },
-    {   2008,  -4237,  -3897,  -517 },
-    {   1242,  -3493,  -4335, -1335 },
-    {    -88,  -4142,  -3390, -1529 },
-    {   2176,  -3488,  -3822,  -975 },
-    {   1706,  -5188,  -3415,  -637 },
-    {   2717,  -6159,  -2333,  -882 },
-    {   1276,  -3978,  -4361,   537 },
-    {   2471,  -5556,  -2866,  -208 },
-    {    799,  -4673,  -4086,    56 },
-    {   1901,  -4786,  -3533,   270 },
-    {   3036,  -3902,  -3606,  -333 },
-    {   2249,  -3317,  -4319,  -144 },
-    {   2594,  -4207,  -2105, -2930 },
-    {   4008,  -4774,  -2626,  -902 },
-    {   1038,  -3659,  -3496, -2454 },
-    {   2725,  -3597,  -3298, -1535 },
-    {   1662,  -5803,  -2813,   175 },
-    {    705,  -3757,  -3441, -1484 },
-    {   1860,  -5987,  -2821,  -886 },
-    {   3786,  -4918,  -2199, -1929 },
-    {   3683,  -4235,  -2547, -1287 },
-    {   2531,  -4896,  -2956, -1593 },
-    {   1005,  -5585,  -3324,  -180 },
-    {   1625,  -5229,  -1756, -3642 },
-    {   1494,  -5041,  -2989, -2685 },
-    {   2718,  -4655,  -3224,  -867 },
-    {   2374,  -6640,  -1745, -2975 },
-    {   2133,  -6436,  -2477, -1499 },
-    {   1833,  -4418,  -3523, -1512 },
-    {   1128,  -4910,  -2658, -1106 },
-    {    689,  -4777,  -2831, -2085 },
-    {   3593,  -5280,  -2627,  -315 },
-    {   3264,  -3771,  -2673, -1861 },
-    {   3202,  -5602,  -2409,   402 },
-    {    552,  -4618,  -2221, -3002 },
-    {   3095,  -5356,  -2666, -1083 },
-    {   3401,  -4609,  -3146,    45 },
-    {   3051,  -4662,  -2192, -2232 },
-    {   2798,  -5552,  -2462, -1941 },
-    {   2354,  -5815,  -2223, -2619 },
-    {    192,  -3708,  -2807, -2658 },
-    {   1886,  -4226,  -1862, -3529 },
-    {   2526,  -3976,  -2819, -2332 },
-    {   1577,  -3870,  -2711, -2806 },
-    {   1288,  -5588,  -3382, -1403 },
-    {   2711,  -5399,  -1564, -3253 },
-    {   1459,  -5492,  -2222,  -322 },
-    {   2823,  -5091,  -2886,   776 },
-    {   3559,  -5821,  -2109, -1360 },
-    {   1587,  -6331,  -2760, -1909 },
-    {   2139,  -5213,  -2874, -2120 },
-    {   1318,  -4337,  -3695, -2098 },
-    {    821,  -4471,  -1849,  -565 },
-    {   3329,  -4782,  -1725,   -89 },
-    {    582,  -4914,  -4105, -1119 },
-    {    417,  -4144,  -4072, -2529 },
-    {   -199,  -3803,  -2765, -4042 },
-    {   2731,  -4283,  -2143,     1 },
-    {   2911,  -6187,  -1951, -2116 },
-    {   1573,  -6094,   -493, -2838 },
-    {   2081,  -6927,   -864, -3211 },
-    {   1058,  -7826,     79,  -364 },
-    {   3147,  -5570,   -684,  -978 },
-    {   3572,  -5856,   1060,  1824 },
-    {   1143,  -6702,  -1478,   338 },
-    {   2341,  -7220,    -88,   260 },
-    {   3639,  -6861,    668,   815 },
-    {   2227,  -6268,  -1706,   446 },
-    {   3390,  -6082,   -353,  1302 },
-    {   1123,  -7556,  -1237,  -430 },
-    {   1729,  -7742,    729,  -218 },
-    {   1457,  -6774,    587,   579 },
-    {    505,  -6919,   -569,   371 },
-    {   1106,  -7245,     78,   158 },
-    {   2755,  -6745,  -1122,   338 },
-    {   3069,  -6040,  -1415,   986 },
-    {   2174,  -7064,  -1430,  -283 },
-    {   1390,  -8626,   -446, -3031 },
-    {   3534,  -6890,   -431,   547 },
-    {   2267,  -9618,    475, -2994 },
-    {   3672,  -7673,     75,  -115 },
-    {   2131,  -7560,  -1206,  -750 },
-    {   2972,  -7477,   -685,  -262 },
-    {   1604,  -6637,   -672,   699 },
-    {   1666,  -7577,   -577,  -240 },
-    {   1591,  -6554,  -2158,   -94 },
-    {   2348,  -6286,   -353,  1123 },
-    {   2017,  -8810,   -412, -1805 },
-    {   2892,  -6713,  -1765,  -554 },
-    {   2500,  -6828,  -1995, -1197 },
-    {   3877,  -6639,   -224, -1655 },
-    {   2392,  -7872,    -91,  -333 },
-    {   3562,  -7370,   -532, -2836 },
-    {   2552,  -7614,    164, -1805 },
-    {    990,  -6104,    218,   438 },
-    {    910,  -7861,    312, -1195 },
-    {   1472,  -6327,    372,  -640 },
-    {   1576,  -7143,  -1983,  -843 },
-    {    422,  -7625,   -457,  -278 },
-    {   1797,  -8532,    405, -1011 },
-    {   1088,  -7396,   -238, -2277 },
-    {   3209,  -6753,  -1431, -2072 },
-    {   2617,  -6839,    100, -2573 },
-    {   2575,  -8573,   -387, -3188 },
-    {   3618,  -6971,  -1190,  -321 },
-    {   2205,  -7361,  -1695, -2008 },
-    {   2985,  -6297,   1464,  1179 },
-    {   2804,  -7310,   1053,   338 },
-    {   1362,  -6074,  -1163,  -840 },
-    {   3336,  -6325,  -1794,    21 },
-    {   2836,  -8109,    818,  -329 },
-    {   2791,  -5879,    560,  1546 },
-    {   2392,  -6064,    135,   100 },
-    {   1838,  -6194,    596,  1085 },
-    {   1926,  -7515,   -414, -4901 },
-    {   3225,  -7298,  -1202, -1189 },
-    {   3960,  -7558,   -659,  -719 },
-    {   3442,  -6647,  -1692, -1095 },
-    {   3381,  -6441,    262,  -886 },
-    {   1431,  -8150,  -1186, -1406 },
-    {    340,  -8498,   -150,  -899 },
-    {   3004,  -8149,   -260,  -953 },
-    {   2749,  -6611,    563,   873 },
-    {  -6647,  -1325,  -4517, -4691 },
-    {  -6005,  -1657,  -4089, -3797 },
-    {  -3157,    588,  -5213, -3068 },
-    {  -3311,  -1425,  -6329, -3726 },
-    {  -5866,   -819,  -3857, -2744 },
-    {  -5001,  -1799,  -1075, -4621 },
-    {  -5330,  -2650,  -2672, -4664 },
-    {  -4930,   -539,  -2363, -4010 },
-    {  -2984,     10,  -3863, -5749 },
-    {  -1055,  -2106,  -3713, -4267 },
-    {  -5476,   -502,  -4279, -6504 },
-    {  -5231,  -1543,  -5018, -6425 },
-    {  -5134,   -363,  -3165, -5109 },
-    {  -3953,   -771,  -4107, -6393 },
-    {  -2159,   -563,  -3652, -5342 },
-    {  -3888,  -2321,   -919, -5057 },
-    {  -1236,   -597,  -4235, -4193 },
-    {  -4053,    675,  -3083, -6174 },
-    {  -2793,  -1089,  -5396, -3460 },
-    {  -3000,    -44,  -2209, -6575 },
-    {  -3336,  -1531,  -4313, -5160 },
-    {  -2127,    128,  -4851, -3692 },
-    {  -3321,    136,  -2067, -5660 },
-    {  -5215,   1404,  -4374, -4356 },
-    {  -2747,    400,  -6340, -3691 },
-    {  -3926,   -599,  -5361, -5006 },
-    {  -2875,  -2592,  -5143, -4092 },
-    {  -4991,  -1958,  -5322, -4891 },
-    {  -4965,  -1318,  -6652, -5333 },
-    {  -4920,  -1691,  -3388, -5561 },
-    {  -3644,  -3354,  -2688, -5982 },
-    {  -5076,   -919,  -4563, -2984 },
-    {  -6114,    250,  -3884, -3915 },
-    {  -4014,    744,  -3973, -1924 },
-    {  -5543,  -1041,  -5557, -3847 },
-    {  -4711,  -1352,  -5649, -2603 },
-    {  -3362,    775,  -5305, -4879 },
-    {  -5001,    107,  -3554, -2888 },
-    {  -6258,  -1651,  -6356, -6566 },
-    {  -4529,    407,  -5003, -3865 },
-    {  -5154,    550,  -5278, -5465 },
-    {  -4195,   -467,  -1894, -3129 },
-    {  -5022,   1127,  -3349, -3314 },
-    {  -6075,   1250,  -4313, -5641 },
-    {  -2677,  -2283,  -2312, -5903 },
-    {  -4113,    193,  -1195, -4833 },
-    {  -3940,  -1048,  -1389, -5079 },
-    {  -3703,    917,  -4043, -4451 },
-    {  -3366,  -4231,  -1534, -5488 },
-    {  -3326,  -3583,  -2091, -4903 },
-    {  -5144,   1254,  -2532, -4949 },
-    {  -5982,   -870,  -2545, -4555 },
-    {  -3925,   -157,  -5367, -2281 },
-    {  -6419,   -746,  -5668, -4371 },
-    {  -5787,    518,  -7096, -5805 },
-    {  -4258,    954,  -6453, -4321 },
-    {  -4771,   -695,  -4158, -1639 },
-    {  -7078,   -760,  -5195, -5877 },
-    {  -7348,     83,  -4101, -4586 },
-    {  -2430,    184,  -2874, -1679 },
-    {  -2284,  -3943,  -2924, -5034 },
-    {  -1804,  -1785,  -3002, -4710 },
-    {  -4399,  -2772,  -1815, -4637 },
-    {  -6340,  -2626,  -2824, -5191 },
-    {  -4998,  -5168,  -3480,  1905 },
-    {  -3958,  -5492,  -1599,  1579 },
-    {  -2471,  -3755,   -276,  3182 },
-    {  -3033,  -5779,  -1063,  1554 },
-    {  -2936,  -4829,  -1290,  2386 },
-    {  -1835,  -5073,  -3051,  1299 },
-    {  -1724,  -3771,  -3935,  2324 },
-    {  -5070,  -2550,  -3692,   768 },
-    {  -4326,  -5333,   -297,  1878 },
-    {  -3472,  -5619,  -3094,   992 },
-    {  -3027,  -4384,  -3038,  2265 },
-    {  -3201,  -5332,     67,  2200 },
-    {  -1681,  -4373,  -1947,  2461 },
-    {  -3221,  -3329,  -4238,  2564 },
-    {  -1262,  -2968,  -2915,  3227 },
-    {  -3419,  -1878,  -3373,  2110 },
-    {  -2244,  -5583,  -2012,  1288 },
-    {  -1971,  -5266,   -990,  1812 },
-    {  -2975,  -2778,   -452,  4063 },
-    {  -2198,  -1165,  -3298,  2965 },
-    {  -4782,  -4894,  -4767,   664 },
-    {  -6002,  -3950,  -2806,  2025 },
-    {  -3142,  -3162,  -2859,  3295 },
-    {  -3262,  -3340,  -4123,  1596 },
-    {  -4014,  -3918,  -1955,  3361 },
-    {  -1700,  -3463,  -1346,  3449 },
-    {  -4245,  -4445,  -4743,  1644 },
-    {  -4180,  -3969,   -401,  3281 },
-    {  -2782,  -5240,  -4117,  1156 },
-    {  -5744,  -4040,  -1439,  3470 },
-    {  -5063,  -4663,   -323,  3172 },
-    {  -4531,  -3319,   -844,  3988 },
-    {  -6226,  -5125,  -2064,  2976 },
-    {  -3115,  -3267,  -1531,  3898 },
-    {  -4628,  -4421,  -2864,  2808 },
-    {  -4559,  -2989,  -3442,  2024 },
-    {  -1775,  -4487,   -656,  2477 },
-    {  -2664,  -1865,  -1884,  4081 },
-    {  -1828,  -2575,  -3894,  3378 },
-    {  -6441,  -3677,  -2025,  1677 },
-    {  -4141,  -2156,  -1191,  3474 },
-    {  -4802,  -1623,  -1727,  2160 },
-    {  -5474,  -2745,  -1475,  2498 },
-    {  -3664,  -1056,  -1975,  2491 },
-    {  -4672,  -3062,  -2235,  2933 },
-    {  -4205,  -5960,  -2849,  1517 },
-    {  -4995,  -5708,  -1739,  1805 },
-    {  -4892,  -6080,  -4793,   872 },
-    {  -4270,  -4172,  -4263,  2185 },
-    {  -4687,  -1470,  -2905,  1023 },
-    {  -6446,  -5017,  -3919,  1000 },
-    {  -6046,  -5538,  -3943,  2006 },
-    {  -6028,  -3750,  -3953,   771 },
-    {  -5959,  -4582,  -5024,   824 },
-    {  -5818,  -2576,  -2249,  1326 },
-    {  -5659,  -5345,  -1119,  2500 },
-    {  -3346,  -4155,    606,  2749 },
-    {  -5680,  -4827,  -2501,  1838 },
-    {  -6193,  -2543,  -1295,   840 },
-    {  -6871,  -4925,  -3512,  1801 },
-    {  -5605,  -1788,  -1895,   779 },
-    {  -3922,  -5712,  -4644,   510 },
-    {  -4745,  -3869,  -4533,    99 },
-    {  -2984,  -4907,   -399,  1497 },
-    {   1847,   -478,   3061, -5812 },
-    {   4450,  -1116,   3609, -6570 },
-    {   3139,     99,   3007, -5532 },
-    {   2590,  -3782,   3138, -4770 },
-    {   1881,   1204,   5778, -3404 },
-    {   3631,   2060,   5566, -5038 },
-    {   3461,   1961,   5167, -3800 },
-    {   2947,    273,   4536, -4389 },
-    {   4453,  -1730,   5788, -4370 },
-    {   4032,   1805,   2666, -4534 },
-    {   3487,   -944,   2313, -6028 },
-    {   1313,     34,   4210, -4067 },
-    {   5632,  -1502,   5825, -5855 },
-    {   7736,   -547,   4879, -5476 },
-    {   4906,  -1512,   4760, -5760 },
-    {   3843,    447,   1091, -4958 },
-    {   2982,  -1135,   5442, -4386 },
-    {   3579,    271,   3031, -6770 },
-    {   3932,   -211,   4688, -5507 },
-    {   4411,   1720,   2387, -5584 },
-    {   5379,   -479,   4575, -6280 },
-    {   3613,   -362,   2012, -4885 },
-    {   3744,  -2013,   4493, -5073 },
-    {   5693,    109,   4379, -3362 },
-    {   5475,   -621,   5317, -3985 },
-    {   6411,   -673,   5708, -4752 },
-    {   4933,   -796,   7262, -4290 },
-    {   2804,    444,   6276, -3655 },
-    {   4120,   -517,   6078, -4531 },
-    {   5119,    841,   3486, -3910 },
-    {   4738,   1539,   3525, -2970 },
-    {   5086,    370,   5895, -5640 },
-    {   4235,   2716,   4589, -5044 },
-    {   3691,    682,   6199, -4700 },
-    {   6111,   -570,   6271, -6528 },
-    {   2611,   1277,   3756, -4802 },
-    {   4395,    970,   3807, -5879 },
-    {   5225,   2299,   3242, -4333 },
-    {   5144,   1778,   4946, -5545 },
-    {   2989,  -3016,   3247, -5495 },
-    {   2983,    920,   2071, -6059 },
-    {   5270,   -903,   4434, -2350 },
-    {   6415,   -585,   3970, -3554 },
-    {   3866,   -197,   5216, -2884 },
-    {   3767,  -1298,   6702, -3315 },
-    {   6299,   2620,   5284, -6824 },
-    {   6654,    646,   3653, -4927 },
-    {   4770,   3047,   5160, -6287 },
-    {   5364,    434,   2919, -5207 },
-    {   2998,   1344,   4801, -2456 },
-    {   3896,   1013,   3773, -1864 },
-    {   2115,    655,   2999, -6344 },
-    {   5170,   -981,   2849, -4464 },
-    {   2735,  -2159,   2717, -5776 },
-    {   2430,  -1952,   4392, -4559 },
-    {   6143,  -1180,   3659, -4746 },
-    {   4978,  -1483,   1726, -4875 },
-    {   3486,  -2383,   3306, -4301 },
-    {   1434,  -1372,   4171, -4770 },
-    {   3354,  -2627,   1525, -5093 },
-    {   6790,   2386,   3995, -5909 },
-    {   1475,  -2674,   3451, -4204 },
-    {   1999,  -3494,   3693, -5556 },
-    {   4764,  -2848,   2856, -5589 },
-    {  -3677,   5131,   2827, -2934 },
-    {  -2844,   7078,   2852, -3580 },
-    {  -3902,   6434,   4118, -1911 },
-    {  -1769,   7530,   3492, -3541 },
-    {  -1937,   5679,   -447, -1127 },
-    {  -2456,   4680,   4196, -2407 },
-    {  -2778,   8241,   1698, -4288 },
-    {  -2876,   6104,   5182, -2387 },
-    {  -2802,   7341,   4463, -2938 },
-    {  -1025,   6267,   4752, -3201 },
-    {  -2349,   5413,   2041, -3794 },
-    {  -2252,   8225,   2856, -4269 },
-    {  -1465,   4967,   4976, -2500 },
-    {   -636,   7565,   3517, -4233 },
-    {  -1905,   5618,   3904, -2942 },
-    {   -302,   6816,   3343, -3316 },
-    {  -2210,   4156,   2817, -3511 },
-    {   -717,   6568,   1863, -2951 },
-    {  -3873,   5682,   2164,  -575 },
-    {  -2878,   5835,    440, -2597 },
-    {  -3228,   7701,   2610, -2514 },
-    {  -3608,   8888,   3377, -2468 },
-    {  -2582,   9717,   2519, -3126 },
-    {  -5238,   6202,   2866, -2831 },
-    {  -3428,   7370,   3056,  -335 },
-    {  -1681,   8836,   1210, -2010 },
-    {  -3276,   6724,   1156, -3930 },
-    {   -894,   8149,    827, -1258 },
-    {  -2965,   8631,   2549, -1320 },
-    {  -3961,   6902,   3581,    55 },
-    {  -1894,   7745,   1750,  -841 },
-    {   -821,   6844,    850,  -676 },
-    {   -608,   6948,     -4, -1376 },
-    {    615,   6524,   1089, -1147 },
-    {  -2972,   5668,   1091,  -489 },
-    {   -157,   4649,   2904,  -413 },
-    {    673,   5121,   1498,   -66 },
-    {   -390,   5902,   1611,  -245 },
-    {  -2349,   5478,   4772, -1320 },
-    {     88,   6798,   1972, -1859 },
-    {  -1213,   5120,   2991,   200 },
-    {  -2347,   6040,   2839,   376 },
-    {   -578,   5976,   3364, -1796 },
-    {  -1391,   5872,   3002,  -965 },
-    {   -564,   4496,   3946, -1186 },
-    {  -2299,   6386,   3135, -2176 },
-    {  -2131,   5641,   2011,  1223 },
-    {   -772,   5807,   1124,   895 },
-    {  -2837,   6758,   2297,  -740 },
-    {  -3091,   6298,   1415, -2126 },
-    {  -4197,   6036,   1843, -3022 },
-    {    -41,   6459,     92,   344 },
-    {  -2241,   6860,   2095, -4396 },
-    {  -1931,   7088,   2117, -2135 },
-    {  -2375,   4422,   1688, -3169 },
-    {  -1742,   6674,   1538,  -119 },
-    {  -4818,   7749,   4192, -1577 },
-    {  -2004,   5672,    193,  -430 },
-    {  -3825,   6042,   2128, -1898 },
-    {  -1108,   8033,   2119, -3013 },
-    {  -2370,   5453,   1721,   266 },
-    {  -1570,   7134,    614, -2638 },
-    {  -1519,   8752,   3503, -4330 },
-    {  -2050,   3845,   2907, -1126 },
-    {   5085,   4412,   -335, -1923 },
-    {   3618,   1423,   -613, -4012 },
-    {   4481,   3729,    589, -4631 },
-    {   4270,   3216,  -1763, -3168 },
-    {   4241,   1796,  -1701, -2796 },
-    {   4787,   2338,   -487, -3639 },
-    {   2915,   3429,   -621, -4753 },
-    {   5175,   1660,  -1265, -3223 },
-    {   4280,   4057,   -684, -4079 },
-    {   4980,   4419,  -1455, -2719 },
-    {   5436,   2464,    387, -4197 },
-    {   4507,   4018,   1121, -3314 },
-    {   6020,   2401,   -413, -3201 },
-    {   4200,   3789,   -333, -2813 },
-    {   5229,   2493,  -1194, -1878 },
-    {   5851,   2695,   -492, -2292 },
-    {   5743,   3288,   -697, -1221 },
-    {   5692,   2612,    979, -2227 },
-    {   5085,   2067,   1046, -1214 },
-    {   3163,   2240,  -2098, -3435 },
-    {   5228,   1898,    145, -2397 },
-    {   5860,   3976,   -418, -2872 },
-    {   6008,   3399,   1027, -3506 },
-    {   4126,   2035,   1865,  -893 },
-    {   5375,   3596,    511, -2362 },
-    {   1937,   1493,   -852,  -122 },
-    {   3473,   4849,    547, -2603 },
-    {   4631,   2977,   1141, -1768 },
-    {   6149,   3050,    -71, -1886 },
-    {   4069,   4353,   -289, -1429 },
-    {   2884,   1225,  -1388,   365 },
-    {   5485,   2518,   -235,  -571 },
-    {   1216,   4375,   1443,   398 },
-    {   4988,   3106,    107, -1435 },
-    {   4511,   2801,    307,  -444 },
-    {   3235,   4386,    327,  -676 },
-    {   2055,   3708,   1657,  -305 },
-    {   5839,   2374,    290, -1385 },
-    {   5110,   3305,   1936, -4206 },
-    {   6416,   2920,    338, -2736 },
-    {   3350,   2824,  -1269, -3881 },
-    {   4840,   1815,    464,   186 },
-    {   2399,   3332,    238,  1238 },
-    {   3516,   1363,   1582,   688 },
-    {   3582,   1874,    154, -4770 },
-    {   3261,   2878,    886,   283 },
-    {   3877,   2658,   -327,   884 },
-    {   4151,   3436,   2173, -2923 },
-    {   3592,   3674,   1281, -1295 },
-    {   4561,   3730,  -1114, -1747 },
-    {   4595,   3625,   -558,  -575 },
-    {   2577,   2348,   2267,   120 },
-    {   5242,   3299,     32, -3412 },
-    {   4264,   3637,    709, -2320 },
-    {   6556,   3570,   -838, -2472 },
-    {   5745,   4014,   -940, -1973 },
-    {   5629,   4475,    477, -3328 },
-    {   5269,   3199,   1682, -3085 },
-    {   4432,   2416,   1145, -3299 },
-    {   4465,   2505,   2162, -2186 },
-    {   4643,   4941,    -88, -2885 },
-    {   4568,   5231,    552, -3915 },
-    {   5667,   3075,  -1406, -2963 },
-    {   5418,   5259,   -771, -2818 },
-    {   -256,  -7875,    511,  -471 },
-    {  -1813,  -7971,   -424,  -396 },
-    {   -306,  -7006,    862,   282 },
-    {  -2306,  -6422,  -1440,   508 },
-    {   -245,  -6787,    375,  -100 },
-    {  -1309,  -6065,    -20,   779 },
-    {  -1656,  -6047,   -641,  1307 },
-    {  -1496,  -6522,    964,   726 },
-    {  -2291,  -6588,   -202,   795 },
-    {   -762,  -7522,   1454,  -558 },
-    {  -2270,  -7004,   -834,  -580 },
-    {  -1139,  -7078,    259,   362 },
-    {  -2535,  -7568,  -1040,    49 },
-    {  -3786,  -7280,    934,  -476 },
-    {  -3336,  -6368,    606,  1056 },
-    {  -3602,  -6924,     52,   714 },
-    {  -2278,  -6550,   1674,   204 },
-    {  -2855,  -5765,    930,  1530 },
-    {  -2889,  -7325,   -215,   305 },
-    {  -2749,  -6080,   -237,  1452 },
-    {   -985,  -6667,   1577,   400 },
-    {  -2036,  -6083,    380,  1267 },
-    {  -2077,  -7460,    380,   -30 },
-    {  -1775,  -7175,   1540,  -386 },
-    {  -3065,  -6927,    989,   168 },
-    {  -2836,  -7602,    117, -3392 },
-    {  -1058,  -6396,    593, -3078 },
-    {   -844,  -6062,    999,  -236 },
-    {  -3261,  -6951,   1491,  -720 },
-    {  -2186,  -8484,     75, -1287 },
-    {  -2882,  -7756,    456,  -510 },
-    {  -1800,  -6879,    960, -1183 },
-    {  -2554,  -7241,   1614, -1474 },
-    {  -2608,  -5305,    392,   851 },
-    {  -2973,  -6562,   -859,   858 },
-    {  -2640,  -5989,   1031,  -416 },
-    {   -977,  -8366,    705, -1434 },
-    {  -1213,  -7409,    -77, -1390 },
-    {  -1335,  -6657,   2125,  -123 },
-    {  -2544,  -6862,   1852,  -737 },
-    {  -3235,  -6422,   1752,  -103 },
-    {  -1300,  -7557,    939,  -348 },
-    {  -3476,  -7579,    202,  -109 },
-    {  -2482,  -6572,    753,   619 },
-    {  -2554,  -8136,   -648,  -429 },
-    {  -1012,  -7870,     -3,  -421 },
-    {  -3604,  -6247,     32, -3102 },
-    {  -1486,  -7271,   2013, -1021 },
-    {   -578,  -6799,   -523,   405 },
-    {  -2841,  -5948,   1644,   911 },
-    {  -2411,  -7473,   1084,  -484 },
-    {  -2238,  -6033,    294, -1059 },
-    {  -3459,  -6470,   -201,  -790 },
-    {  -2027,  -6009,   1833,   805 },
-    {  -1433,  -8047,   1531, -1754 },
-    {  -3258,  -7884,    763, -1422 },
-    {  -1544,  -6928,   -729,   478 },
-    {  -2314,  -8415,     74, -3757 },
-    {  -3201,  -5684,     95, -2214 },
-    {  -2423,  -8694,    725, -3631 },
-    {  -3545,  -7071,   1162, -1798 },
-    {   -294,  -9662,    403, -2274 },
-    {  -2290,  -5460,   1196,   402 },
-    {  -1603,  -6713,    903, -2363 },
-    {   4121,   2491,  -3142, -2482 },
-    {   4500,   3305,  -3671, -1567 },
-    {   5973,   3172,  -1348,  -534 },
-    {   4830,   3379,  -1549,   643 },
-    {   5214,   3938,  -2641, -2302 },
-    {   4639,   4826,  -5532,  -847 },
-    {   5639,   2731,  -2170,  -963 },
-    {   6084,   3487,  -3525, -1346 },
-    {   5971,   3154,  -2190, -2316 },
-    {   5618,   4865,  -6927,   116 },
-    {   5345,   3568,  -7391,   709 },
-    {   5429,   5078,  -3811, -1524 },
-    {   6960,   2037,  -3515, -1096 },
-    {   7092,   2531,  -4557,  -588 },
-    {   6061,   4247,  -5651,  -478 },
-    {   4595,   3684,  -4907,  -827 },
-    {   7497,   3213,  -3048,  -424 },
-    {   5996,   2137,  -3098, -1745 },
-    {   6198,   5199,  -2223, -2274 },
-    {   6888,   2851,  -2768, -1675 },
-    {   6114,   4210,  -2316,  -954 },
-    {   7127,   4242,  -3041, -1408 },
-    {   6126,   3668,  -1517, -1427 },
-    {   6245,   6129,  -4225, -1186 },
-    {   6816,   3213,  -2101,  -964 },
-    {   5345,   5276,  -2643,  -847 },
-    {   6592,   4665,  -4338,   484 },
-    {   6746,   3751,  -3443,   124 },
-    {   5453,   1980,  -2738,  2606 },
-    {   4662,   2179,  -4226, -1059 },
-    {   5571,   3208,  -3554,   174 },
-    {   5256,   4447,  -1815, -1481 },
-    {   5400,   2570,  -1210,   235 },
-    {   7056,   2549,  -2674,   318 },
-    {   4574,   4340,  -2892,  -130 },
-    {   6203,   4587,  -3273,  -305 },
-    {   5103,   1925,  -2715, -2137 },
-    {   3905,   4296,  -1700,   247 },
-    {   4421,   4605,  -3299,   811 },
-    {   5671,   1273,  -3870,  -924 },
-    {   5486,   1805,  -4901,   133 },
-    {   6437,   2578,  -1828,  -106 },
-    {   5530,   5253,  -5058,  1223 },
-    {   4816,   2025,  -1215,  1443 },
-    {   3457,   3525,  -2456,  3217 },
-    {   3316,   2595,  -1108,  2459 },
-    {   3068,   3810,  -2207,  1926 },
-    {   6351,   5436,  -6470,   600 },
-    {   6324,   4240,  -5365,  2416 },
-    {   4851,   4774,  -4075,  1878 },
-    {   4900,   3679,  -5198,  1078 },
-    {   8347,   3633,  -4565,  -171 },
-    {   5244,   5718,  -3853,   173 },
-    {   3960,   3492,  -2939,  2105 },
-    {   6070,   3473,  -2351,   161 },
-    {   8228,   3034,  -3360,  -901 },
-    {   7006,   3985,  -1940, -1926 },
-    {   7123,   4681,  -4301,  -878 },
-    {   5122,   4097,  -1851,  -449 },
-    {   6200,   2060,  -2251,  1049 },
-    {   7106,   3844,  -7209,  2625 },
-    {   7108,   3370,  -6734,   533 },
-    {   6859,   2849,  -3992,  1360 },
-    {   5458,   2278,  -3253,  1131 },
-    {  -1072,  -2109,   4783, -1073 },
-    {   -319,  -2604,   4257, -2418 },
-    {   2466,   1300,   3476,  -314 },
-    {   2847,  -1502,   5296,  -141 },
-    {   1667,  -1273,   5559, -2725 },
-    {   2877,  -3402,   6434,   204 },
-    {     53,  -2637,   5275, -1181 },
-    {   1091,  -2215,   5803, -1549 },
-    {   2397,   -922,   4327,  1182 },
-    {    219,  -3747,   4647, -1564 },
-    {    -29,  -2705,   4812,  1277 },
-    {   1499,  -2608,   5648,  1407 },
-    {   2139,  -2399,   4202,  2791 },
-    {   -426,  -2064,   5528,   151 },
-    {   2560,  -2803,   6179, -2806 },
-    {   4537,  -2479,   3797,  1095 },
-    {    888,  -3357,   5341,  -415 },
-    {   4460,  -1814,   5388, -1227 },
-    {   3920,  -3268,   6364,  -703 },
-    {   3343,  -4698,   4410,   784 },
-    {    309,  -1897,   6306,  1223 },
-    {    958,  -3318,   4254, -3167 },
-    {    -99,   1596,   6018, -1983 },
-    {   -429,   -853,   6407,   878 },
-    {   1170,  -1322,   6290,  -417 },
-    {   2288,   -505,   6303, -1999 },
-    {   3312,  -1674,   6749, -2494 },
-    {   -415,  -3401,   4721,  -371 },
-    {   -189,  -1210,   4844, -2002 },
-    {    888,  -4142,   4377,   130 },
-    {   2469,  -4381,   5398, -2492 },
-    {   2879,  -2912,   5094, -2598 },
-    {   -717,   -617,   5650,  -685 },
-    {   1470,  -3863,   5352, -1684 },
-    {   3935,    -96,   3823,  -730 },
-    {   3769,   -430,   3168,   694 },
-    {   2556,    385,   3539,   512 },
-    {     77,  -1415,   5111,  2655 },
-    {   2724,  -2158,   6715,  -822 },
-    {   1832,   1001,   5385, -1900 },
-    {    900,   2198,   4464,  -559 },
-    {    441,     69,   5921, -1743 },
-    {  -1161,    738,   6732,  -308 },
-    {    257,   2035,   4091,   736 },
-    {   1607,   1288,   4355,   -23 },
-    {    -13,   1316,   4180,  1672 },
-    {   1511,   1336,   3057,  1435 },
-    {   2189,  -3813,   4530,   939 },
-    {   3632,   -706,   2646,  1375 },
-    {   4266,  -3761,   4241,  1077 },
-    {   3101,   -427,   5273, -1202 },
-    {   2293,    276,   4810,  -313 },
-    {   3430,  -1851,   3101,  2045 },
-    {   3453,  -2979,   5142,   942 },
-    {   1683,  -3281,   4802,  2002 },
-    {   3954,  -4715,   5611,   578 },
-    {   1272,   -155,   5085,   454 },
-    {    128,   -194,   5095,  1409 },
-    {    820,    880,   5797, -2658 },
-    {  -1095,    656,   5774,  1095 },
-    {    813,  -1669,   4320, -3251 },
-    {   -119,    518,   6372,  -651 },
-    {   2922,  -4299,   6115,  -877 },
-    {   4205,  -4273,   4004,  2642 },
-    {  -1211,  -3892,    224,  3127 },
-    {    -34,  -4371,   1321,  2318 },
-    {     77,  -6326,   1201,   828 },
-    {   3995,  -3775,   1958,  3233 },
-    {    178,  -3301,   1985,  3318 },
-    {   2330,  -3801,   1033,  3195 },
-    {   1413,  -5536,    826,  1709 },
-    {   2468,  -3499,   3653,  3631 },
-    {    741,  -4617,   1723,  2008 },
-    {   1246,  -3043,   2978,  3949 },
-    {   -343,  -4308,   2258,  2189 },
-    {   -682,  -4640,    454,  2272 },
-    {   1236,  -4829,   2491,  1642 },
-    {   -512,  -3766,   1182,  3052 },
-    {    119,  -3939,   3712,   971 },
-    {  -1145,  -4624,   1360,  2281 },
-    {    101,  -4746,   2866,  1255 },
-    {  -1500,  -5455,    539,  1637 },
-    {   -969,  -5909,   1414,  1128 },
-    {  -1261,  -4939,   -231,  2022 },
-    {   -226,  -5345,   1207,   705 },
-    {   2712,  -5109,   3205,  1866 },
-    {   -476,  -5913,    273,  1208 },
-    {  -2039,  -4464,    624,  2545 },
-    {  -2351,  -3930,   2019,  2673 },
-    {  -2675,  -4849,   1522,  1990 },
-    {  -1524,  -3461,   1446,  3204 },
-    {    477,  -5314,   1710,  1577 },
-    {    656,  -3729,   2346,  2511 },
-    {    550,  -5917,   1975,  1040 },
-    {   1728,  -4704,   3067,  1058 },
-    {     -9,  -5247,    506,  1760 },
-    {   -574,  -5135,   1675,  1672 },
-    {   2129,  -3781,   3444,  2313 },
-    {   1144,  -4439,   2214,  2529 },
-    {   1292,  -4160,   3185,  1833 },
-    {   2445,  -3262,   2534,  3227 },
-    {   2266,  -4401,   2023,  2400 },
-    {   -587,  -3602,   3408,  2067 },
-    {   -885,  -4951,   3228,  1174 },
-    {   -728,  -2711,   2807,  3552 },
-    {   1019,  -3043,   3195,  2954 },
-    {   1888,  -4615,   1140,  2454 },
-    {    660,  -5616,    754,   800 },
-    {  -1975,  -5371,   1649,  1585 },
-    {  -1544,  -5436,   2422,  1081 },
-    {   -422,  -5882,   2390,   750 },
-    {   1336,  -5557,   2441,  1230 },
-    {    136,  -4001,    267,  2854 },
-    {   -522,  -3289,   2226,  2728 },
-    {   -971,  -4580,   2471,   708 },
-    {    704,  -5306,   3300,  1001 },
-    {    325,  -3464,   3555,  2398 },
-    {    794,  -3686,    848,  3169 },
-    {    660,  -3017,   4584,  3242 },
-    {  -1486,  -3978,   2170,  1644 },
-    {  -1615,  -4650,   2688,  1844 },
-    {    750,  -4578,    538,  2239 },
-    {   1668,  -5849,   1455,  1031 },
-    {   3486,  -4681,   2030,  2183 },
-    {   2642,  -5429,   1696,  1761 },
-    {   4491,  -4502,   3538,  2767 },
-    {   3545,  -4528,   3514,  2982 },
-    {   3269,  -3676,   2758,  3966 },
-    {   5572,   1146,    209, -3379 },
-    {   7459,   1053,    593, -1896 },
-    {   4480,    200,   -310, -4259 },
-    {   5577,   -939,    242, -3992 },
-    {   8142,    442,   1257, -3083 },
-    {   5442,   1261,   1424, -3236 },
-    {   6260,   -183,   3125, -2532 },
-    {   7179,    889,   1618, -2548 },
-    {   6416,    932,   2379, -2487 },
-    {   7094,   2560,    961, -3392 },
-    {   7322,    463,   2732, -3735 },
-    {   6632,   1577,   1912, -3272 },
-    {   6312,   1349,   3028, -3460 },
-    {   6105,    386,   1213,  -977 },
-    {   5478,   1158,   1114,  -486 },
-    {   6493,    410,   1686, -2180 },
-    {   6378,   1881,   1333, -2240 },
-    {   5711,    812,   1958, -1300 },
-    {   6844,    877,    730, -1189 },
-    {   6824,   -245,   2249, -2000 },
-    {   7515,   1521,   1251, -3058 },
-    {   6697,   1051,   1300, -1749 },
-    {   6476,   1425,    811, -2773 },
-    {   7350,    465,    -76, -2849 },
-    {   6975,   2095,    567, -2492 },
-    {   4691,   1736,   2660, -2289 },
-    {   7837,   1456,    340, -2767 },
-    {   7930,    507,    838, -2074 },
-    {   6106,   1502,    766, -1110 },
-    {   4891,   -659,    835, -3954 },
-    {   7250,    141,   1369, -1523 },
-    {   7651,     67,   1651, -2298 },
-    {   7364,   -305,    601, -3132 },
-    {   7179,    193,   2491, -2871 },
-    {   6504,   -272,   2167, -1322 },
-    {   4456,    983,   2300,  -421 },
-    {   4817,    457,   1695,   371 },
-    {   6914,    555,    850, -3159 },
-    {   5904,   1030,    202, -1959 },
-    {   6258,    880,   2233, -4503 },
-    {   6029,     10,   2130, -3600 },
-    {   6449,    985,   1129, -3963 },
-    {   6616,    -18,   -111, -3285 },
-    {   4496,    775,    817, -4276 },
-    {   6134,   2338,   1470, -2973 },
-    {   6911,    152,    430, -1946 },
-    {   4053,    991,   3218, -1193 },
-    {   5435,   1285,   3124, -2412 },
-    {   5507,   1836,   1935, -1988 },
-    {   5240,    689,   2189, -2670 },
-    {   6638,   1719,    606, -1799 },
-    {   5556,   -180,    129, -2595 },
-    {   5644,   1918,   1281, -4316 },
-    {   6410,   1088,   -282, -3117 },
-    {   6503,   1841,    312, -3514 },
-    {   6947,     20,   1358, -3886 },
-    {   5464,   2109,   2398, -3194 },
-    {   5616,   -407,   2140,  -498 },
-    {   6121,   2707,   2379, -4096 },
-    {   7303,   1846,   2266, -4095 },
-    {   5444,    470,   2718, -1553 },
-    {   5817,   -645,   3285, -1349 },
-    {   5625,   1427,   1103, -1991 },
-    {   6041,   -806,   1196, -2943 },
-    {   3050,  -5722,   4070, -5460 },
-    {   3420,  -4386,   4078, -5155 },
-    {   6020,  -3982,   7268, -2689 },
-    {   7502,  -4317,   7894, -3973 },
-    {   4156,  -3558,   5247, -4316 },
-    {   4725,  -4401,   7290, -1540 },
-    {   6688,  -5122,   8216, -3210 },
-    {   9176,  -6576,   9276, -4963 },
-    {   8706,  -5708,   7987, -4621 },
-    {   7060,  -3535,   6532, -3308 },
-    {   5600,  -2719,   5363, -1568 },
-    {   4661,  -2803,   6263, -4716 },
-    {   3673,  -3636,   6147, -3433 },
-    {   5305,  -2585,   6073, -2638 },
-    {   7614,  -1962,   6079, -5266 },
-    {   6760,  -3366,   7382, -4322 },
-    {   6385,  -3883,   4797, -1353 },
-    {   8182,  -5120,   4298, -4641 },
-    {   9130,  -6198,   4975, -3063 },
-    {   7421,  -5436,   5576, -3713 },
-    {   3483,  -4898,   5443, -2745 },
-    {   4907,  -5643,   6390, -4105 },
-    {   8119,  -7008,   7992, -6764 },
-    {   6528,  -6122,   6967, -5590 },
-    {   5890,  -4190,   6624, -5688 },
-    {   6815,  -7934,   7275, -5456 },
-    {   5434,  -4306,   5169, -5378 },
-    {   4364,  -6436,   5376, -2604 },
-    {   8152,  -3404,   5913, -5048 },
-    {   7983,  -4863,   4262, -2461 },
-    {   8023,  -6188,   6238, -5062 },
-    {   6753,  -3692,   3935, -3723 },
-    {   6826,  -4760,   3284, -4051 },
-    {   7224,  -7423,   4492, -3875 },
-    {   6904,  -2590,   6587, -6248 },
-    {   6106,  -1944,   7345, -5506 },
-    {   4956,  -2990,   7808, -3146 },
-    {   6908,  -6885,   5949, -1288 },
-    {   7162,  -6058,   3419, -3401 },
-    {   7015,  -7080,   6907, -3018 },
-    {   6971,  -6832,   5646, -3273 },
-    {   8014,  -5546,   5471, -1544 },
-    {   6792,  -2220,   5105, -2879 },
-    {   8494,  -3974,   4408, -3999 },
-    {   9591,  -4866,   6027, -4558 },
-    {   5264,  -5161,   6101,  -738 },
-    {   5803,  -6141,   5197, -5231 },
-    {   4657,  -6822,   3232, -5189 },
-    {   4791,  -5135,   3809, -4665 },
-    {   6108,  -5103,   2379, -3873 },
-    {   4680,  -3909,   3234, -5093 },
-    {   5802,  -3853,   3795, -4984 },
-    {   4360,  -7483,   4802, -3877 },
-    {   5429,  -7517,   5911, -3717 },
-    {   6866,  -2280,   4880, -4634 },
-    {  10131,  -4628,   4414, -4092 },
-    {  10811,  -5189,   7746, -5337 },
-    {   5663,  -8941,   5287, -5680 },
-    {   8023,  -5991,   7403, -2796 },
-    {   9669,  -6919,   6525, -4932 },
-    {   7275,  -3796,   4962, -2547 },
-    {   8848,  -4806,   5677, -3080 },
-    {   8128,  -4308,   7749, -6569 },
-    {   4032,  -5196,   2282, -6239 },
-    {   6593,    700,   -229,   304 },
-    {   8260,    539,    -66, -1259 },
-    {   6605,    176,   -814,  -109 },
-    {   8057,      0,     -1,  -136 },
-    {   7382,    -38,   -484, -1129 },
-    {   8373,   -929,    682,  -454 },
-    {   7674,    690,  -1278,   546 },
-    {   7326,   -517,    406, -1283 },
-    {   7612,  -1715,  -1167,  1175 },
-    {   8590,    441,   -782,  -710 },
-    {   8572,  -1202,   -291,   260 },
-    {   7308,   -147,  -1785,   414 },
-    {   6787,   -353,   -672,   934 },
-    {   5177,   -133,    179,    82 },
-    {   4161,    -34,    447,  1497 },
-    {   5997,   -902,   1533,  -121 },
-    {   5727,   -871,  -1370,   945 },
-    {   8386,   -252,    293,  -823 },
-    {   6573,  -1354,    682,   616 },
-    {   7650,  -2096,    725,   457 },
-    {   8122,     78,    636, -1400 },
-    {   8421,    428,  -1620,   131 },
-    {   7341,  -1292,   -717,   186 },
-    {   7998,    -49,   -720,   266 },
-    {   5987,   -351,    669,   844 },
-    {   7314,  -1620,    250,  -603 },
-    {   7219,  -1562,   -572,  1994 },
-    {   8682,   -358,   -290,  -388 },
-    {   5810,    155,   -178,  1199 },
-    {   7246,    -12,   1042,  -786 },
-    {   7357,   -923,   1468,  -475 },
-    {   7801,    621,   -212,  -724 },
-    {   5346,   -514,   1210,  1356 },
-    {   8459,     36,   -127,  -779 },
-    {   6878,  -2429,    854,  1750 },
-    {   7280,  -1401,  -1353,  2845 },
-    {   7579,  -2148,  -1463,  2087 },
-    {   6637,    946,   -872,   750 },
-    {   4807,  -1100,   1289,  2602 },
-    {   4495,    219,   1551,  1128 },
-    {   7639,    506,    446, -1107 },
-    {   6359,    188,   1009,  -115 },
-    {   6641,  -1820,   1655,   723 },
-    {   5394,  -2382,   1604,  2542 },
-    {   6021,  -2644,   2396,  1407 },
-    {   4698,    882,    245,  1525 },
-    {   8103,    573,   -798,  -349 },
-    {   8045,   -519,    997, -1092 },
-    {   7571,   -122,    227,  -338 },
-    {   5347,  -1200,    630,  1718 },
-    {   7070,    790,    218,  -544 },
-    {   7440,    728,   -527,   -20 },
-    {   6402,   -355,    197,  -736 },
-    {   4031,    771,    866,  1895 },
-    {   6009,    896,    445,   -31 },
-    {   5160,   1098,   -856,  1784 },
-    {   7980,   -886,  -1293,  1396 },
-    {   6318,  -1361,   2423,   252 },
-    {   7547,   -699,    133,   506 },
-    {   8562,  -2344,    940,   264 },
-    {   5890,   1187,  -1425,  2194 },
-    {   6558,   -645,  -1311,  2621 },
-    {   4634,  -1671,   2075,  1623 },
-    {   5614,    105,   -816,  2376 },
-    {   6646,   1558,  -1365,   630 },
-    {   6998,   1150,  -2117,  -990 },
-    {   6555,   2311,  -1093, -1783 },
-    {   6682,   1430,  -2391, -1940 },
-    {   7861,   1555,  -2977, -1188 },
-    {   6745,   1723,   -459, -2085 },
-    {   7504,   1229,  -1666, -2060 },
-    {   7937,    671,  -2128, -1529 },
-    {   7139,    991,   -735, -2632 },
-    {   6867,   1592,  -1303, -2324 },
-    {   6401,   2230,  -1732, -2508 },
-    {   7201,   2184,  -2169, -1988 },
-    {   6636,   2190,   -995, -2840 },
-    {   7620,   2306,  -2089,  -651 },
-    {   7584,   1875,  -1438,  -631 },
-    {   9214,   1561,  -2464, -1139 },
-    {   6154,   1318,  -1237, -2917 },
-    {   7917,   2847,  -1797, -1599 },
-    {   8309,   2029,  -2555,  -465 },
-    {   8204,   1282,   -584, -2405 },
-    {   8440,   1035,  -1147, -1137 },
-    {   7107,   1858,    -60, -1568 },
-    {   6781,   2912,   -873, -1463 },
-    {   7603,   1316,   -319, -1249 },
-    {   7833,   1335,    -78, -1849 },
-    {   7930,   1141,  -1016,  -695 },
-    {   7883,   1610,  -1017, -1314 },
-    {   8069,   1409,  -1811,  -196 },
-    {   8319,   1031,   -582, -1590 },
-    {   5948,   1537,  -2153, -2373 },
-    {   8684,   1171,  -1871,  -850 },
-    {   8357,   2484,  -2411, -1292 },
-    {   6516,   2092,   -193, -1167 },
-    {   6112,   1697,     22,  -525 },
-    {   7161,    703,   -602, -1879 },
-    {   6047,   2351,   -807,  -219 },
-    {   8072,   1854,  -1817, -1553 },
-    {   6956,   1304,     76, -1011 },
-    {   6607,   1481,   -544,  -162 },
-    {   6958,   2541,   -265, -1938 },
-    {   6416,   2514,   -777,  -850 },
-    {   7272,   2110,   -899, -1171 },
-    {   7741,   2153,   -283, -2614 },
-    {   6482,   2041,  -1758, -1221 },
-    {   6762,    940,  -1862, -2281 },
-    {   5610,   1194,  -1691, -1561 },
-    {   7833,   2164,   -823, -1952 },
-    {   5460,   1438,   -848,  1189 },
-    {   6011,   1377,   -771, -1557 },
-    {   7679,    544,  -1134, -2214 },
-    {   7209,   1292,  -2714, -1564 },
-    {   5567,   1200,   -404,  -169 },
-    {   5853,   1461,  -1465,  -518 },
-    {   6782,    689,   -844,  -860 },
-    {   7330,   1337,  -1152,   -71 },
-    {   7189,   1506,   -653,  -685 },
-    {   6860,   2116,  -1403,  -240 },
-    {   8804,   1516,  -1391, -1760 },
-    {   7210,   2689,  -1498,  -989 },
-    {   7030,   3022,  -1441, -2083 },
-    {   5649,   1836,   -407,   525 },
-    {   7451,   3099,   -717, -2464 },
-    {   7384,   1656,  -2007,   398 },
-    {   6504,    707,  -1919,  -134 },
-    {  -1851,   3639,  -2279,  -695 },
-    {  -4037,   1644,    -77,  1329 },
-    {  -4025,   1960,  -1565,  -567 },
-    {  -3430,   2495,   -795,   368 },
-    {  -4771,   2480,    993,   756 },
-    {  -3431,   2058,  -2539,  -971 },
-    {  -3802,   3418,    380,   217 },
-    {  -3074,   3350,  -1652, -1056 },
-    {  -3705,    326,  -1650,  1535 },
-    {  -3122,   1281,  -1192,  1607 },
-    {  -4601,   1367,   -968,    53 },
-    {  -3808,    958,     44,  2560 },
-    {  -2079,   2530,  -1485,  1166 },
-    {  -3707,    343,  -2889,   180 },
-    {  -5249,   1431,    -31,   688 },
-    {  -4990,    125,   -704,  1270 },
-    {  -2771,   1334,  -2446,   746 },
-    {  -2292,    994,  -1527,  2630 },
-    {  -1261,   3070,  -2519,   268 },
-    {  -2544,   3890,  -1057,  -552 },
-    {  -4421,    255,  -1980,   530 },
-    {  -2951,    454,    -13,  3643 },
-    {  -2262,   1815,   -370,  2880 },
-    {  -2383,   3657,   -649,   576 },
-    {  -3541,   -161,  -1389,  2550 },
-    {  -4241,   1575,   1325,  2561 },
-    {  -2767,   4037,   1221,  1578 },
-    {  -3748,   2697,   1148,  1801 },
-    {  -4686,   2385,   -220,     0 },
-    {  -1531,   1645,  -2751,  1327 },
-    {    -45,   4032,   -799,  2298 },
-    {  -2915,   2280,    709,  2495 },
-    {  -1199,   3278,   -406,  2346 },
-    {  -2471,    116,  -2706,  2060 },
-    {  -2440,   2173,  -2894,  -344 },
-    {  -3375,   2287,   1781,  3226 },
-    {  -2153,   3568,   1827,  2918 },
-    {   -862,   2267,  -1626,  2527 },
-    {  -2698,   1135,    301,  4239 },
-    {  -2364,   2123,   1010,  3710 },
-    {  -2447,   3281,    -81,  1408 },
-    {  -2660,   4735,    472,   258 },
-    {  -1053,   3097,   2682,  2398 },
-    {  -3366,  -1037,  -1152,  -868 },
-    {   -643,   4242,   2212,  1259 },
-    {    971,   3991,    934,   643 },
-    {  -1617,   2002,   2139,  2195 },
-    {  -4897,    972,    784,  1719 },
-    {  -1275,   2992,   1039,  3821 },
-    {   -392,   4973,   -209,  1821 },
-    {  -1028,   4718,  -1479,  -137 },
-    {     50,   3914,    553,  2210 },
-    {    678,   4364,    359,  1303 },
-    {   -582,   4911,    514,  1671 },
-    {   1276,   3914,  -1252,  2934 },
-    {  -1496,   3984,    857,  2330 },
-    {    772,   4744,   -655,  2332 },
-    {   -799,   5283,   -439,   624 },
-    {   1341,   2937,    650,  2027 },
-    {  -1739,   4892,   1275,  1702 },
-    {   -892,   2596,   -151,  3951 },
-    {  -3532,   1090,   1292,    32 },
-    {    321,   3146,   2647,  1475 },
-    {    264,   4199,  -1591,  1317 },
-    {   -452,  -2357,   2266,  4192 },
-    {   3022,  -1033,  -2389,  5678 },
-    {  -1162,  -1342,   3543,  4990 },
-    {   -474,  -1477,  -1223,  5016 },
-    {   -699,  -2857,    900,  3835 },
-    {   -461,  -2255,   -117,  4626 },
-    {   1204,  -2062,  -1211,  4403 },
-    {   2192,  -3035,   -337,  3966 },
-    {    108,   -831,    279,  5643 },
-    {   1457,   -620,  -2908,  5276 },
-    {  -2527,    -78,   1085,  5460 },
-    {  -1978,  -1918,   -949,  4733 },
-    {     32,    367,  -1904,  5166 },
-    {   1890,  -1665,    440,  4752 },
-    {   -518,   -348,   2816,  4891 },
-    {   3695,  -2490,  -1374,  4603 },
-    {    246,  -1965,   3549,  3969 },
-    {   1100,  -3111,    656,  3737 },
-    {  -1379,    870,   -414,  4575 },
-    {    628,   -357,  -1227,  6179 },
-    {  -1129,  -1318,  -2457,  4576 },
-    {   -425,    -98,    -73,  6336 },
-    {    367,   -887,   2990,  4207 },
-    {   2091,  -1251,   2444,  3557 },
-    {  -1759,  -1610,   2046,  5273 },
-    {   3210,   1414,    -20,  2616 },
-    {   3303,  -2636,   1005,  4237 },
-    {   -327,  -3107,   -640,  3687 },
-    {   -197,    764,    572,  5486 },
-    {    646,   -767,   1388,  5464 },
-    {    104,   2742,   -228,  3907 },
-    {   -236,   1829,   -579,  4585 },
-    {  -2150,   -474,  -1525,  4006 },
-    {    -23,  -2632,  -2400,  3892 },
-    {    -12,  -1739,  -2910,  4867 },
-    {  -2310,   -368,   -102,  4583 },
-    {  -1991,  -2061,    533,  4531 },
-    {   3884,  -1446,   -153,  4393 },
-    {   1568,     14,   -289,  5268 },
-    {  -1376,   -253,  -2797,  3417 },
-    {   3193,  -2577,   2475,  3566 },
-    {   3418,    617,   1350,  1857 },
-    {   3792,    -24,   -272,  3370 },
-    {    153,   1159,   2906,  2877 },
-    {    511,   2162,   1548,  2741 },
-    {    262,    819,  -2791,  3734 },
-    {   4232,  -2015,   1486,  3477 },
-    {   2943,  -1110,  -1014,  5480 },
-    {   2842,    369,    703,  3476 },
-    {   3011,   1634,   -933,  3553 },
-    {   4412,  -1548,   -942,  5021 },
-    {  -1405,    593,   2372,  5267 },
-    {   2093,   2129,    896,  2365 },
-    {   4845,  -1980,      0,  3823 },
-    {  -2140,     81,   3278,  5637 },
-    {   1484,   2665,   -324,  3653 },
-    {     10,    192,   1620,  5291 },
-    {   2152,    738,  -2269,  5000 },
-    {   2102,   2748,  -1652,  4707 },
-    {   2855,  -2131,   -387,  5188 },
-    {   1173,    676,   1338,  3277 },
-    {   2340,  -2329,  -2064,  4095 },
-    {    861,  -2024,   1296,  5055 },
-    {   2189,   3225,   -695,  2626 },
-    {   6196,  -7079,   1943,  -822 },
-    {   4547,  -4813,   3261,  1856 },
-    {   4243,  -6904,   3443,   448 },
-    {   4581,  -7503,    946,   506 },
-    {   6626,  -7754,   3427,   470 },
-    {   3407,  -9088,   3269, -1496 },
-    {   4079,  -6464,   2304,   777 },
-    {   5621,  -9336,   2684,  -768 },
-    {   5351,  -6464,   5238,  -214 },
-    {   5961,  -8007,   1724, -3091 },
-    {   4213,  -8067,    603,  -246 },
-    {   7208,  -7403,   3168, -1738 },
-    {   6098,  -7700,    329, -1379 },
-    {   6525,  -6735,   4248, -1072 },
-    {   6073,  -6241,   2167, -2378 },
-    {   4609,  -9218,   3051, -1033 },
-    {   6813,  -7283,   1581, -1897 },
-    {   6126,  -6275,   2789,   681 },
-    {   4423,  -6538,   1621, -1692 },
-    {   6272,  -8298,   3167, -1855 },
-    {   6172,  -8558,   4498, -1169 },
-    {   4844,  -8588,   1647,  -366 },
-    {   6209,  -8807,   1581,  -369 },
-    {   5389,  -8059,    550,  -192 },
-    {   6654,  -9775,   2504, -1063 },
-    {   7103,  -7998,    806,   530 },
-    {   5662,  -6736,   1565, -3620 },
-    {   4165,  -9564,   4191, -2131 },
-    {   4526,  -7181,    576, -2875 },
-    {   4633,  -8623,   2807, -4742 },
-    {   3709,  -7794,   1815,    34 },
-    {   3634,  -8622,   2313,  -826 },
-    {   6991,  -8447,   2063, -3198 },
-    {   7757,  -9486,   2255,  -558 },
-    {   4149,  -7778,   4728, -1696 },
-    {   5767,  -7427,   1113,   707 },
-    {   4592,  -6261,   2329,  1864 },
-    {   3159, -10498,   1677, -4273 },
-    {   3534,  -9010,   2437, -3565 },
-    {   4479, -10821,   2715, -4942 },
-    {   3207,  -9805,   3054, -3886 },
-    {   4627,  -8189,   3018, -2354 },
-    {   5527, -10566,   3244, -2749 },
-    {   4346, -10127,   3335, -3084 },
-    {   6132, -10085,   3316, -1308 },
-    {   5629,  -9704,   2178, -3058 },
-    {   3603,  -8538,   1246,  -624 },
-    {   3737,  -8488,    395, -3167 },
-    {   5465, -11414,   2810, -4640 },
-    {   5306,  -7745,   2721, -3988 },
-    {   7000,  -9111,   1695, -1409 },
-    {   6663,  -7741,   2466, -4079 },
-    {   4083,  -7175,   1836, -4831 },
-    {   3613,  -9926,   1342, -3455 },
-    {   6588,  -8033,    457,  -258 },
-    {   4720,  -8102,     17, -1209 },
-    {   7414,  -8709,   1294,  -344 },
-    {   5437, -10030,   4043, -1704 },
-    {   4862,  -9281,   1558, -1431 },
-    {   6800,  -6403,   5113,   862 },
-    {   4623,  -8242,   2667,  -228 },
-    {   5919,  -5083,   3348,  2135 },
-    {   5985,  -8889,   2733, -5105 },
-    {   5029,  -5767,   4407,   719 },
-    {    354,  -6158,   -838, -3001 },
-    {    351,  -5943,  -2104, -1534 },
-    {   -633,  -7190,    -25, -4798 },
-    {  -1595,  -7235,  -3812, -1400 },
-    {    103,  -6197,  -2933,   -78 },
-    {  -1722,  -5020,  -3441, -4333 },
-    {  -1963,  -5644,  -4365,  -270 },
-    {   -846,  -5743,  -3477,   196 },
-    {   -191,  -5348,  -4054,  -469 },
-    {  -2515,  -7754,  -3495,  -818 },
-    {  -2090,  -6710,  -2701,   117 },
-    {   -546,  -7036,  -1398,   163 },
-    {   -278,  -7091,  -2662,  -536 },
-    {   -622,  -7962,  -2731, -1464 },
-    {  -1555,  -8118,  -3612, -2057 },
-    {  -1094,  -6280,  -2314,   505 },
-    {  -2556,  -8538,  -4024, -2247 },
-    {    109,  -7134,  -3107, -1823 },
-    {   -900,  -6954,  -3340,  -717 },
-    {   -605,  -7113,  -3656, -2154 },
-    {    837,  -6263,  -3211, -2177 },
-    {   -417,  -5810,  -3871, -1469 },
-    {  -1318,  -5649,  -4207, -3198 },
-    {    413,  -6765,  -2082,   -33 },
-    {  -3101,  -6450,  -4362,  -766 },
-    {    755,  -6489,  -2967,  -846 },
-    {   1117,  -7106,  -2452, -1352 },
-    {  -1202,  -8387,  -3072, -2897 },
-    {   -365,  -4894,  -3561, -2937 },
-    {  -2372,  -8776,   -265, -4441 },
-    {  -1224,  -8678,   -896, -5074 },
-    {   -755, -10096,   -600, -6623 },
-    {    300,  -8206,   -225, -4568 },
-    {  -1176,  -6824,  -2633, -3527 },
-    {  -2006,  -5443,  -1526, -5849 },
-    {  -1115,  -5540,  -2363, -4785 },
-    {   1059,  -6812,  -2543, -2654 },
-    {  -1976,  -6861,  -3062, -5508 },
-    {   -379,  -5328,  -2321, -3624 },
-    {  -2108,  -5860,  -4518, -1915 },
-    {   -379,  -7885,  -1329,  -594 },
-    {    774,  -5389,   -581, -5213 },
-    {  -2601,  -5083,  -1849, -4921 },
-    {   -176,  -5580,     74, -5075 },
-    {   -204,  -6780,   -190, -6232 },
-    {    418,  -7594,  -1987,  -820 },
-    {  -1873,  -8529,  -2926, -1609 },
-    {   1340,  -6362,   -919, -4975 },
-    {    577,  -7990,  -2044, -1873 },
-    {  -2572,  -7413,  -1745, -2224 },
-    {  -2037,  -7030,  -1461, -7138 },
-    {  -2559,  -8756,  -2039, -5836 },
-    {  -2079,  -6764,  -1209, -5669 },
-    {  -1613,  -7801,  -2006,  -685 },
-    {  -1865,  -6583,   -722, -3529 },
-    {   -589,  -6358,  -1377, -1003 },
-    {   -540,  -7514,  -1331, -3542 },
-    {    419,  -6192,  -1677, -4927 },
-    {  -2786,  -8763,  -2966, -5065 },
-    {  -2172,  -8411,  -1726, -4675 },
-    {  -3382,  -9833,  -3497, -5722 },
-    {  -2433, -10169,  -2077, -5775 },
-    {   -424,  -9451,  -1096, -3658 },
-    {   -537,  -8522,   -910, -1897 },
-    {  -5550,   2807,   1683,  -693 },
-    {  -6395,    635,   3573, -1246 },
-    {  -7544,   2280,   2140,    44 },
-    {  -8751,   1136,   2951,  -794 },
-    {  -5605,   2709,   2052,   916 },
-    {  -7650,    654,    869,   135 },
-    {  -6939,    967,   1409,   870 },
-    {  -7834,   2123,   3310,   974 },
-    {  -6935,   2818,   1274, -1678 },
-    {  -5605,   2233,   1013,   471 },
-    {  -7095,   1849,   1648,   198 },
-    {  -6636,   1634,    712,   -37 },
-    {  -7279,    978,    296,  -315 },
-    {  -7664,   3504,   3292,  -216 },
-    {  -7836,   1209,   1221,  -257 },
-    {  -7913,   2201,   1765, -1529 },
-    {  -7077,   3783,   2632, -1407 },
-    {  -5565,   1645,   1410,  -622 },
-    {  -6494,   2879,   1181,  -759 },
-    {  -7073,   3137,   3010,   550 },
-    {  -7249,   1839,    847,  -805 },
-    {  -6630,   2197,    282, -1096 },
-    {  -8836,   1573,   1988, -1090 },
-    {  -7809,   1274,    836, -1198 },
-    {  -7895,   2970,   3511, -1097 },
-    {  -6960,   1664,   1356, -2442 },
-    {  -6582,   2866,   2273,   307 },
-    {  -7221,    821,   2851, -1435 },
-    {  -6015,   1703,   2001, -2367 },
-    {  -8082,   1034,   2103,   239 },
-    {  -5952,   1912,    301,  -465 },
-    {  -6099,    841,    379,   567 },
-    {  -6343,     50,    494,   658 },
-    {  -6586,    983,    591,  -893 },
-    {  -5500,    869,   2187, -2479 },
-    {  -6482,     60,   1545,  -979 },
-    {  -6705,    515,   1974,   -53 },
-    {  -6460,   1755,   1325, -1275 },
-    {  -6093,   2617,   2465,  -623 },
-    {  -7330,   2161,    594, -2115 },
-    {  -7324,    762,   1593, -2004 },
-    {  -6385,    679,   1510, -2514 },
-    {  -6159,    241,   2976, -1631 },
-    {  -8583,   3030,   4045,  -162 },
-    {  -6299,     66,   2209, -2103 },
-    {  -5428,   1279,   3267, -1846 },
-    {  -6438,   1335,   2728, -1631 },
-    {  -8012,   1070,   2428, -1151 },
-    {  -6201,   2781,   2349, -1918 },
-    {  -5918,   1139,   3121,  -148 },
-    {  -6314,   2481,   3137, -1808 },
-    {  -7180,   1722,   2435, -1602 },
-    {  -6750,   1829,   3763, -1145 },
-    {  -6713,   1777,   2221,  1212 },
-    {  -7479,   1835,   3627,  -479 },
-    {  -7299,     10,   2406, -1593 },
-    {  -8249,   3129,    996, -2870 },
-    {  -8374,   1534,   1333, -1882 },
-    {  -7507,   3353,   1598, -2299 },
-    {  -7379,   2701,   2326, -1167 },
-    {  -8440,   2276,   2796,  -542 },
-    { -10348,   1527,   2649, -1165 },
-    {  -8184,   3614,   2574, -1738 },
-    {  -5539,   1574,   1733,  1138 },
-    {   9404,  -7652,     67,    79 },
-    {   8654,  -3972,   1358,   -60 },
-    {   8617,  -4794,    117,  2318 },
-    {   7886,  -4505,   1784,  1200 },
-    {   8636,  -6125,   3879, -1003 },
-    {   9654,  -6836,   1816,   205 },
-    {   9374,  -6553,    913,  1875 },
-    {   8020,  -6150,   1134,  2390 },
-    {   7786,  -4970,   2078, -1857 },
-    {   8691,  -6119,    711,   708 },
-    {   9039,  -5568,   2944, -1902 },
-    {   9955,  -5048,   1433,  -601 },
-    {   8089,  -6927,   3093, -2846 },
-    {   8487,  -7024,   2415,    19 },
-    {   9388,  -5287,   3577, -2655 },
-    {   8591,  -7371,   2300,  -996 },
-    {   9104,  -4763,   1453, -2558 },
-    {   7615,  -5457,    596,   164 },
-    {   9860,  -7047,   3433,  -614 },
-    {   8756,  -4404,   2235,  -964 },
-    {   9462,  -4660,    299, -1822 },
-    {  10119,  -5550,   2689, -1273 },
-    {  10915,  -7471,   2705, -1007 },
-    {  11433,  -7090,   1410, -1198 },
-    {   9882,  -7431,   2965, -1895 },
-    {   7628,  -5219,    769, -2661 },
-    {   8169,  -5318,   2262,    70 },
-    {   8846,  -6320,   1939,  -754 },
-    {   7147,  -5593,   1248,  -971 },
-    {  10652,  -5485,    935,   137 },
-    {   7778,  -6533,   2564, -1932 },
-    {   8878,  -5173,   1214,  -361 },
-    {   9828,  -4943,    282,   510 },
-    {  10042,  -6134,   3895, -1914 },
-    {   7965,  -6630,   3566,  -433 },
-    {   8573,  -4502,   3574, -1209 },
-    {   8398,  -4801,   1031, -1347 },
-    {  10136,  -7772,   2612,  1547 },
-    {   9890,  -7280,   1768, -1083 },
-    {   8407,  -6585,   -706,   -58 },
-    {   7976,  -7582,    229,  -131 },
-    {  10481,  -8866,   1166,  -147 },
-    {  10914,  -4342,   3189, -2412 },
-    {  10440,  -5198,   -104, -1109 },
-    {  11227,  -6530,   2381, -2449 },
-    {   8487,  -8064,   1086,   230 },
-    {   9975,  -6123,   -857,  -134 },
-    {   8339,  -6498,   1232, -2337 },
-    {  11042,  -4506,   1119, -2098 },
-    {  12563,  -5592,   1837, -2062 },
-    {  11801,  -5590,    632, -1296 },
-    {  10152,  -5617,   1511, -1917 },
-    {   7800,  -6473,     51, -1337 },
-    {   7941,  -5560,   2438, -3270 },
-    {   6554,  -3834,   2100,  1476 },
-    {   9065,  -5520,   -226, -1120 },
-    {  10794,  -7120,   -243,   122 },
-    {  10429,  -6968,    272,  -806 },
-    {   8942,  -8914,   1442,  -392 },
-    {   9969,  -5051,   2033, -2953 },
-    {   7275,  -4152,   3058,   -64 },
-    {  11127,  -5488,   4589, -3227 },
-    {   9626,  -6666,   2739, -2958 },
-    {   6943,  -5362,   4470,  1008 },
-    {  -7456,   -967,   2936, -1002 },
-    {  -8622,   -333,   6962,  2606 },
-    {  -7486,  -3392,   3668,  1287 },
-    {  -8053,   -827,   5148,  1097 },
-    {  -6610,    454,   4952,    96 },
-    {  -7701,  -1982,   3161,  -468 },
-    {  -7307,  -1132,   4071,   -36 },
-    {  -8125,   -271,   5199,  3862 },
-    {  -9182,  -1950,   2813,  1878 },
-    {  -9855,   -952,   4794,  3010 },
-    {  -7241,   1431,   4202,  2468 },
-    {  -9646,    157,   4766,  1046 },
-    {  -9371,   1230,   6009,  2958 },
-    { -11514,    -64,   8630,  5248 },
-    {  -6766,    565,   2766,  2140 },
-    {  -8426,     -9,   2852,  1271 },
-    { -11291,  -1113,   5087,  2937 },
-    {  -8297,   2092,   4495,  1264 },
-    {  -9983,    735,   3809,   -51 },
-    {  -9048,  -1000,   3191,  -308 },
-    {  -7331,  -1987,   2655,  1391 },
-    {  -7144,    -21,   4333,  2161 },
-    {  -6032,  -1540,   3543,   896 },
-    {  -7987,  -1036,   1985,  1529 },
-    {  -9264,   2004,   5194,   290 },
-    { -11308,   -840,   5754,  1654 },
-    {  -9130,  -2398,   4292,  2973 },
-    {  -6248,    838,   3563,  1223 },
-    {  -6819,  -2760,   3511,   119 },
-    {  -7213,  -2006,   4364,   762 },
-    {  -5431,  -1047,   4533,   166 },
-    {  -7098,   -641,   2021,   639 },
-    {  -8628,  -2249,   3588,   399 },
-    {  -6352,  -1498,   3560,  -648 },
-    {  -7033,  -2190,   4870,  2562 },
-    {  -7405,    -46,   3772,  -581 },
-    {  -6104,    796,   5143,  1965 },
-    {  -5787,    943,   5784,  3030 },
-    {  -8367,   1465,   7192,  4097 },
-    {  -8259,    789,   5694,  1963 },
-    { -10614,  -1899,   5748,  2645 },
-    {  -8258,   -805,   3698,  2275 },
-    {  -6877,   -972,   6431,  3160 },
-    {  -6483,    363,   7018,  3129 },
-    {  -6283,  -1358,   5191,  1524 },
-    {  -8853,  -3157,   4119,  1741 },
-    {  -6086,   -267,   3883,  -835 },
-    {  -7254,   1032,   6613,  4017 },
-    { -11470,  -3350,   4649,  3426 },
-    {  -6743,    481,   6148,  1239 },
-    {  -5394,   -166,   5309,  3165 },
-    {  -7958,   1068,   4268,  -240 },
-    { -10520,   2256,   7916,  2828 },
-    {  -5132,     -4,   5739,  1176 },
-    {  -8643,    120,   3255,  -629 },
-    {  -9631,   1974,   8870,  4362 },
-    { -10663,  -1221,   3733,   589 },
-    {  -8224,  -1843,   5806,  2655 },
-    {  -8282,   1255,   8647,  3478 },
-    { -12311,  -1505,   9043,  6256 },
-    { -11312,   -856,   7136,  4681 },
-    { -11944,   -722,   7941,  3309 },
-    {  -7868,   -463,   6846,  4196 },
-    {  -8679,   -241,   7410,  5347 },
-    {   6759,  -4680,   -508,  1220 },
-    {   5176,  -6111,    944,   121 },
-    {   6843,  -5667,  -1368,  -533 },
-    {   5616,  -5884,  -1471,  -695 },
-    {   6030,  -5089,  -1808,  -940 },
-    {   7444,  -5463,    -52,  1881 },
-    {   4207,  -6079,   -506,  1571 },
-    {   6785,  -4410,   -649,  3084 },
-    {   4838,  -5214,   2026,  2998 },
-    {   4201,  -5790,    645,  1811 },
-    {   6930,  -5129,  -1940,  1698 },
-    {   6332,  -4627,    692,  3027 },
-    {   6285,  -4314,   -106,  3644 },
-    {   6255,  -5450,  -1975,   742 },
-    {   4199,  -4676,   -459,  1796 },
-    {   5592,  -5500,   1345,  1300 },
-    {   4358,  -5556,  -2236,   114 },
-    {   4620,  -5875,  -1563,   888 },
-    {   4892,  -7550,   -327,  -419 },
-    {   4734,  -7085,      7,   613 },
-    {   3883,  -5562,  -1969,  1080 },
-    {   5610,  -4990,   -204,   834 },
-    {   4117,  -6482,  -1271,   341 },
-    {   6585,  -5107,    892,  1169 },
-    {   6632,  -3683,    302,  3002 },
-    {   6326,  -5351,   -983, -1250 },
-    {   4382,  -7192,   -730,  -158 },
-    {   5227,  -6540,   -451,  1123 },
-    {   5468,  -6472,   -870, -1471 },
-    {   5191,  -6402,  -1365,  -127 },
-    {   7407,  -6317,   -973,  -336 },
-    {   4611,  -6530,   -820, -1980 },
-    {   4963,  -5159,  -2050,  -966 },
-    {   4414,  -5691,   -211,  -998 },
-    {   5954,  -5873,    750, -1749 },
-    {   4394,  -4796,  -1268,   254 },
-    {   7161,  -6214,  -1010,   689 },
-    {   4965,  -3598,   2372,  1711 },
-    {   6248,  -6180,    981,   864 },
-    {   6473,  -5336,    525,  -600 },
-    {   4591,  -6864,  -1131,  -900 },
-    {   6314,  -6440,  -1021,  -375 },
-    {   5838,  -6209,  -1199,   944 },
-    {   5308,  -5283,  -2100,  1267 },
-    {   4342,  -5860,  -1637, -1356 },
-    {   5680,  -4388,  -1227,  -104 },
-    {   4900,  -4098,   1449,  4046 },
-    {   4677,  -4284,   -106,  3190 },
-    {   7574,  -6173,   -848,  1859 },
-    {   6493,  -7207,   -131,   726 },
-    {   5513,  -5261,  -2117,     4 },
-    {   6191,  -7352,   -193,  -505 },
-    {   5885,  -4333,    324,  -134 },
-    {   6162,  -6081,   -312, -2044 },
-    {   4216,  -6200,  -1810,  -572 },
-    {   5652,  -7035,   -696,  -197 },
-    {   7131,  -7189,   -366,   -60 },
-    {   5032,  -4803,  -1514,  2832 },
-    {   7386,  -4610,   -606,  3489 },
-    {   4211,  -5031,   1221,  3047 },
-    {   4050,  -4653,   1584,  1469 },
-    {   6852,  -5302,  -1861,   206 },
-    {   7736,  -4816,  -1794,  3359 },
-    {   6290,  -3439,   1522,  2454 },
-    {   1768,   5990,  -5560, -2594 },
-    {   3903,   5326,  -1530, -1501 },
-    {   2472,   3738,  -2117, -4240 },
-    {   3260,   5448,   -904, -4733 },
-    {   1435,   7297,  -3676, -4102 },
-    {   4096,   5951,   -656, -3312 },
-    {   2178,   6009,  -3146, -3724 },
-    {   3787,   5493,  -5473, -1633 },
-    {   2998,   7286,  -3334, -3571 },
-    {   2894,   6576,  -4708, -2804 },
-    {    830,   6163,  -4286, -3348 },
-    {   4755,   5569,  -1730, -2739 },
-    {   4604,   6065,  -3562, -2605 },
-    {   2749,   5141,  -3986, -2775 },
-    {   3942,   4875,  -2143, -3340 },
-    {   2819,   8517,  -2004, -2724 },
-    {   2146,   6298,   -689, -3093 },
-    {   5196,   6504,  -3393, -1475 },
-    {   1851,   8386,  -1748, -1420 },
-    {   3474,   8572,  -3534, -2688 },
-    {   4503,   7560,  -3561, -2245 },
-    {   4433,   6219,  -2393, -1575 },
-    {   3506,   7248,  -2275, -1977 },
-    {   3490,   7409,  -3147,  -604 },
-    {   4214,   6447,  -3520,   516 },
-    {    619,   7034,   -829, -1705 },
-    {   1732,   7395,   -356, -2208 },
-    {   1226,   5204,  -3294, -3732 },
-    {   2027,   5619,  -1813, -4146 },
-    {   3078,   5877,     47, -2651 },
-    {   1654,   5458,    424,  -682 },
-    {   3163,   5464,  -2026,  -270 },
-    {   2884,   5375,   -685,  -530 },
-    {   2950,   7286,    -35, -2967 },
-    {   1986,   5066,   -597,   482 },
-    {   3459,   4308,  -3845, -2333 },
-    {   3155,   7037,  -1346, -4345 },
-    {   2193,   6696,   -717, -1319 },
-    {   3677,   5089,  -3892,  -487 },
-    {   2186,   5136,  -4186, -1492 },
-    {    773,   5796,   -917,   817 },
-    {   2489,   6546,  -3570, -2117 },
-    {   1223,   6469,  -1362,   -33 },
-    {    271,   6061,  -1466, -1725 },
-    {   2540,   5171,  -1847,  1032 },
-    {   2548,   5251,  -2697,  1677 },
-    {    771,   7600,   -768,  -632 },
-    {   4710,   6647,  -4736, -1275 },
-    {   1369,   5917,  -2971, -1056 },
-    {    163,   5239,  -3499, -2275 },
-    {   2104,   4285,  -3211, -3286 },
-    {   1107,   7411,  -1972, -1671 },
-    {   2196,   7262,  -2310, -1926 },
-    {   -244,   6439,  -1745,  -839 },
-    {   3293,   3832,  -2890, -3000 },
-    {    419,   6443,   -379,  -407 },
-    {   3077,   4930,  -1156, -2869 },
-    {   2131,   5874,  -2330,   224 },
-    {    690,   6538,  -2212, -2841 },
-    {   1602,   4421,  -2515,  1542 },
-    {   3318,   9373,  -3032, -3477 },
-    {   5646,   7462,  -5153, -1463 },
-    {   4139,   7137,  -1539, -3321 },
-    {   3481,   9077,  -1645, -3653 },
-    {  -7747,    375,   -106,  -543 },
-    {  -8587,  -1379,   -586,  -461 },
-    { -10146,   -892,   2094,   694 },
-    {  -8103,    382,    504,  -325 },
-    {  -8548,    -92,     94,  -656 },
-    {  -7460,     38,    152,   388 },
-    {  -8266,   -271,   -459,  -883 },
-    {  -7935,   -664,  -1026,  -802 },
-    {  -8341,   -109,    853,   161 },
-    {  -8802,  -1355,   1099,   630 },
-    {  -8957,     -6,   1108,  -669 },
-    {  -7260,  -1520,    -43,  -407 },
-    {  -7555,   -174,    668, -2562 },
-    {  -9014,   -126,    227, -1191 },
-    {  -8184,    769,    290, -1375 },
-    {  -9476,     55,    962, -1528 },
-    {  -8679,    541,    755, -1030 },
-    {  -9842,  -1626,    838, -1588 },
-    {  -8513,   -702,    788, -1998 },
-    { -10101,  -1558,   -366, -1841 },
-    {  -8135,     78,   1479, -1813 },
-    {  -9128,   -454,    313, -1786 },
-    {  -7554,  -1084,    831, -2442 },
-    {  -7576,   -701,   2068, -1665 },
-    {  -7791,  -1481,   1587, -1808 },
-    {  -6701,   -596,    -97,   802 },
-    {  -7418,    -15,    684,  -963 },
-    {  -7127,   -477,   -139,  -426 },
-    {  -8097,   -110,    -36,  -264 },
-    {  -7620,  -1922,   -590,  -101 },
-    {  -7647,  -1201,    279,   660 },
-    {  -7856,  -1974,    758, -2271 },
-    {  -8496,   -167,   2232, -1143 },
-    {  -8506,  -1359,    624,  -740 },
-    {  -7274,  -1052,   1062,  -139 },
-    {  -7800,   -217,     91, -1794 },
-    {  -7030,  -1694,   -955,   615 },
-    {  -9020,  -1864,    101, -2182 },
-    {  -9400,   -740,    598,  -667 },
-    {  -8448,  -1184,   2024, -1272 },
-    {  -8812,   -570,   -897, -2384 },
-    { -10559,  -1286,    538, -1536 },
-    {  -8728,   -888,  -1089, -1397 },
-    {  -7080,  -1185,    636, -1252 },
-    {  -9880,    233,   2344,  -782 },
-    {  -7952,  -1326,   -378, -1947 },
-    {  -7207,   -378,   1408, -2237 },
-    {  -8467,  -1545,    902, -1987 },
-    {  -9163,  -1474,    924, -1739 },
-    {  -8159,   -992,    -77, -2744 },
-    {  -8343,    148,   -423, -1573 },
-    {  -9105,   -649,   -254, -1214 },
-    {  -8939,    456,    281, -1905 },
-    {  -8837,    179,   -394, -2634 },
-    {  -9145,    757,   1547, -1319 },
-    {  -9775,   -723,    441, -1680 },
-    {  -8910,   -686,   1529, -1525 },
-    {  -9492,  -1134,   2064,  -938 },
-    {  -6111,   -943,    677,   -31 },
-    {  -7411,   -613,   -814,    46 },
-    {  -9479,   -922,   -430, -2061 },
-    { -11298,  -1268,   1318, -1117 },
-    {  -8190,    832,    671, -2214 },
-    { -10453,   -550,   1672,  -886 },
-    {   1044,   9353,  -1651, -5423 },
-    {   1034,   8149,   -455, -6166 },
-    {    761,   8293,  -3214, -4838 },
-    {    938,   8077,    164, -5130 },
-    {   1295,   8673,   2582, -5490 },
-    {   -314,   7973,  -2395, -5231 },
-    {   -507,   9012,  -2497, -5775 },
-    {   2396,   8314,  -1022, -4673 },
-    {  -1516,   8501,   1950, -4969 },
-    {   -308,   7401,   1549, -4866 },
-    {   -112,   8340,   3003, -4920 },
-    {    -50,   9315,   1371, -5666 },
-    {   -659,   9449,   2496, -5547 },
-    {   2573,   9148,  -2270, -4783 },
-    {    830,   7104,   -438, -3907 },
-    {    522,  10672,   -677, -6483 },
-    {  -1190,  10108,   -510, -6518 },
-    {   -427,   8271,   -579, -6315 },
-    {   1602,   8113,  -1927, -4418 },
-    {  -2266,   8180,    448, -5190 },
-    {  -1633,   8816,   -226, -5771 },
-    {    759,   9481,   -105, -5813 },
-    {   2254,   6679,   -466, -5662 },
-    {    -88,   6946,    895, -5958 },
-    {  -1705,  10009,   1394, -5574 },
-    {    748,   7943,    540, -6692 },
-    {   1411,   7009,    232, -6145 },
-    {    697,   7290,  -1221, -5342 },
-    {  -1764,  10580,   1944, -3981 },
-    {  -1334,   9124,   1195, -3903 },
-    {   -905,  10067,    635, -5039 },
-    {    664,  10680,     49, -4625 },
-    {   1374,   9536,   -777, -3591 },
-    {    252,   9698,   -597, -2931 },
-    {    824,   9164,  -1014, -2144 },
-    {   2438,  10569,  -2289, -4424 },
-    {   2101,   7102,    507, -3614 },
-    {    294,   8051,   -432, -1518 },
-    {   -665,  10337,    547, -2852 },
-    {   1168,  11989,   -492, -5427 },
-    {   1344,   6416,    302, -5061 },
-    {  -1727,  12264,   1507, -4543 },
-    {    674,  10889,   -902, -3605 },
-    {   -582,   9504,    300, -3618 },
-    {    641,   7654,    689, -2109 },
-    {   2065,   9243,    508, -4367 },
-    {   1055,   8373,    688, -3144 },
-    {   -641,   8185,    986, -3307 },
-    {   1120,   7426,   1785, -3757 },
-    {   1660,   8070,   -593, -3104 },
-    {   2002,   9467,  -1722, -3475 },
-    {   2361,   8368,    100, -3709 },
-    {   -772,   7845,   -613, -4988 },
-    {   1485,   7430,   1896, -6127 },
-    {   -432,   7823,   -947, -2882 },
-    {    313,  11122,   -760, -4871 },
-    {    412,   8412,   -283, -4231 },
-    {   1585,  10402,  -1884, -3267 },
-    {    321,   6952,    773, -3016 },
-    {   -105,   9014,    121, -2249 },
-    {   1585,  10313,   -977, -4812 },
-    {   1619,  11869,   1306, -6876 },
-    {  -1168,   8886,    -81, -2500 },
-    {   -395,  10886,    733, -6490 },
-    {  -4949,   4274,   3992, -1054 },
-    {  -4241,   5299,   4262, -1584 },
-    {  -2710,   3862,   4552, -1673 },
-    {  -4608,   2472,   3672, -1715 },
-    {  -2843,   2816,   4003, -2326 },
-    {  -5229,   2964,   5636,    90 },
-    {  -4924,   3442,   5015, -1096 },
-    {  -1281,   3313,   5537, -2066 },
-    {  -3808,   1939,   4351,  -919 },
-    {  -1915,   2585,   4939, -1614 },
-    {  -3470,   1843,   5562,  -682 },
-    {  -3800,    870,   5827,   144 },
-    {  -4985,   1452,   4728,  -709 },
-    {  -3745,   2750,   7220,   259 },
-    {  -1875,   1900,   6514,  -826 },
-    {  -4329,   1574,   7192,  1304 },
-    {  -5408,   1444,   6208,   631 },
-    {  -3327,   5312,   5707, -1541 },
-    {  -6966,   3334,   4034,  1028 },
-    {  -7484,   4245,   4218,  -212 },
-    {  -6567,   5839,   4539,  -512 },
-    {  -5715,   5935,   3747, -1186 },
-    {  -6410,   4881,   3356, -1610 },
-    {  -5146,   2590,   2850,  2172 },
-    {  -5196,   4095,   2569,  -373 },
-    {  -5043,   6025,   4318,   692 },
-    {  -5525,   4884,   3513,   370 },
-    {  -6804,   7533,   5812,  -488 },
-    {  -5657,   2480,   4061,  1234 },
-    {  -3155,   1472,   6071,  1188 },
-    {  -3427,   5217,   3442,   858 },
-    {  -4698,   3013,   5517,  2586 },
-    {  -4449,   2226,   5418,  3580 },
-    {  -6395,   3547,   5487,  2028 },
-    {  -3500,   5019,   4787,     1 },
-    {  -4038,   2578,   3073,  3151 },
-    {  -2750,   1955,   4469,  3856 },
-    {  -5696,   1659,   6118,  2469 },
-    {  -4350,   1241,   6840,  3126 },
-    {  -5565,   5058,   5196,  1314 },
-    {  -1642,   4190,   3948,   607 },
-    {  -1233,   4108,   4850,  -640 },
-    {   -997,   3428,   3239,  1378 },
-    {  -6488,   2741,   6926,  2792 },
-    {  -4188,   3763,   4235,  2018 },
-    {  -3210,   3224,   5646,  1427 },
-    {  -5526,   6909,   5070,  -627 },
-    {  -2815,   3994,   3425,  1903 },
-    {  -2163,   2734,   5423,   145 },
-    {  -4149,   4247,   2355,   734 },
-    {   -410,   2521,   4138,   -16 },
-    {  -2411,   2385,   4927,  2105 },
-    {  -6077,   3591,   3114,   594 },
-    {  -4186,   4834,   5926, -1004 },
-    {  -7315,   3369,   5966,   448 },
-    {  -7042,   5721,   5771,   238 },
-    {  -4466,   3907,   3535, -1751 },
-    {  -2116,   3970,   6163, -1392 },
-    {  -7239,   2143,   8407,  3630 },
-    {  -5431,   4486,   6486,   -42 },
-    {  -1874,   1617,   6333,   519 },
-    {  -6478,   2629,   4634,  -505 },
-    {  -7784,   2342,   7216,  1365 },
-    {  -1154,   1432,   4831,  1544 },
-    {  -4964,  -5801,   1797,   506 },
-    {  -4436,  -6905,   1059, -1237 },
-    {  -5400,  -6886,    884,  -290 },
-    {  -6259,  -7103,    523,  -227 },
-    {  -4819,  -6450,   1412,  -450 },
-    {  -4056,  -6213,   1725,  -943 },
-    {  -5642,  -6091,   1357,   605 },
-    {  -4196,  -5678,   2187,  -173 },
-    {  -4726,  -5126,   2470,   321 },
-    {  -6642,  -5091,   1507, -1005 },
-    {  -5304,  -5250,   1944,  1579 },
-    {  -7179,  -5520,   1468,  -425 },
-    {  -6033,  -4895,   1876,  -955 },
-    {  -6595,  -5143,   2207,  1291 },
-    {  -4224,  -4943,   1846,  1792 },
-    {  -7128,  -6950,    539,   724 },
-    {  -4369,  -4901,   2590,  1103 },
-    {  -7413,  -5696,   1712,  1440 },
-    {  -5885,  -6821,    418,   871 },
-    {  -6828,  -5599,    710, -1563 },
-    {  -6123,  -5817,   1358,  1631 },
-    {  -5291,  -5622,    578,  2138 },
-    {  -7171,  -6004,    347,  2208 },
-    {  -6083,  -5251,   2132,   425 },
-    {  -4329,  -5721,    407, -2993 },
-    {  -5326,  -5056,   1119, -1837 },
-    {  -5485,  -5856,    185, -2389 },
-    {  -6529,  -5178,    403,  -697 },
-    {  -6719,  -4412,   2726,   871 },
-    {  -5126,  -5629,   1835,  -771 },
-    {  -5622,  -4361,   2973,   858 },
-    {  -5282,  -5895,     45,  -335 },
-    {  -4357,  -5656,   1696, -1558 },
-    {  -7139,  -6659,    627,  -409 },
-    {  -4415,  -6328,     35,  1306 },
-    {  -7639,  -6110,   1134,   197 },
-    {  -3626,  -5592,   2019,   901 },
-    {  -3547,  -5064,   1176,  1738 },
-    {  -5075,  -3899,   2087,   266 },
-    {  -4086,  -6311,   1479,   360 },
-    {  -6210,  -5220,   -199, -1477 },
-    {  -3910,  -5063,   1356,   -15 },
-    {  -7616,  -4977,    461,  2401 },
-    {  -6118,  -6131,   1258,  -563 },
-    {  -6127,  -4968,   1286,   -27 },
-    {  -4121,  -5852,   1113,  1476 },
-    {  -5157,  -4881,   1162,  -662 },
-    {  -4637,  -5031,   1179,   709 },
-    {  -5509,  -5452,   -397,  1224 },
-    {  -4597,  -6861,    646,   467 },
-    {  -6247,  -4043,    468,   278 },
-    {  -5336,  -6465,    874, -1472 },
-    {  -6998,  -6346,     78, -1798 },
-    {  -4915,  -4530,   2756,  -203 },
-    {  -6048,  -4373,   1468,  1052 },
-    {  -4273,  -7100,    942,  -323 },
-    {  -6552,  -4287,   2351,    69 },
-    {  -6954,  -4613,    722,  1521 },
-    {  -4201,  -5361,    763, -1562 },
-    {  -6881,  -5596,   -748,   669 },
-    {  -6695,  -3547,    -34,  1299 },
-    {  -3981,  -5728,     84,   111 },
-    {  -4663,  -4809,   2173, -1031 },
-    {  -6599,  -6077,   1303,   256 },
-    {  -7596,  -4265,  -5791, -4140 },
-    {  -6610,  -2758,  -5288, -3936 },
-    {  -5880,  -3865,  -6563, -3088 },
-    {  -7228,  -5510,  -7677, -3912 },
-    {  -8854,  -6553,  -8318, -5361 },
-    {  -9362,  -5249,  -6413, -4319 },
-    {  -4418,  -3110,  -6368, -4358 },
-    {  -5544,  -4203,  -6863, -5013 },
-    {  -3056,  -4316,  -5567, -3181 },
-    {  -3078,  -5999,  -5051, -2657 },
-    {  -5884,  -6292,  -5756, -4013 },
-    {  -4825,  -4549,  -5535, -4053 },
-    {  -4443,  -6126,  -5316, -1368 },
-    {  -3972,  -6341,  -6098, -2686 },
-    {  -5751,  -2781,  -5398, -6230 },
-    {  -4466,  -6135,  -5570, -3679 },
-    {  -4291,  -5992,  -3564, -5189 },
-    {  -7189,  -4429,  -7279, -6082 },
-    {  -5076,  -4433,  -2748, -5366 },
-    {  -6225,  -2825,  -6833, -5663 },
-    {  -2989,  -4792,  -3960, -4492 },
-    {  -7836,  -7773,  -7722, -5741 },
-    {  -6559,  -5703,  -5844, -5589 },
-    {  -7612,  -5438,  -4136, -3774 },
-    {  -4218,  -4176,  -6591, -2333 },
-    {  -4837,  -5063,  -6581,   322 },
-    {  -6590,  -5990,  -2980, -3847 },
-    {  -5558,  -2971,  -5489, -1932 },
-    {  -7001,  -5323,  -4975, -1697 },
-    {  -4694,  -2688,  -6904, -3044 },
-    {  -8511,  -5379,  -5767, -2549 },
-    {  -7548,  -5412,  -6522, -2572 },
-    {  -6597,  -4973,  -6423, -1274 },
-    {  -6415,  -4022,  -5168, -1072 },
-    {  -5528,  -5530,  -7218, -2345 },
-    {  -4845,  -4805,  -5943, -1227 },
-    {  -6049,  -7150,  -6744, -2161 },
-    {  -9061,  -7299,  -8542, -4375 },
-    {  -5010,  -5546,  -5416,   -82 },
-    {  -4135,  -4205,  -5109, -3373 },
-    {  -3311,  -5869,  -4007, -5061 },
-    {  -5993,  -6472,  -3962, -4718 },
-    {  -2966,  -5832,  -2821, -6305 },
-    {  -4851,  -5152,  -2067, -3930 },
-    {  -3620,  -4441,  -3362, -5836 },
-    {  -4469,  -5221,  -4534, -5592 },
-    {  -4022,  -6335,  -4321, -6107 },
-    {  -4899,  -4503,  -3084, -3725 },
-    {  -4490,  -8276,  -4620, -6236 },
-    {  -6591,  -4342,  -7365, -4063 },
-    {  -6498,  -5057,  -5553,   485 },
-    {  -6060,  -2714,  -7093, -4144 },
-    {  -6199,  -7774,  -7094, -4057 },
-    {  -7536,  -6424,  -6415, -4265 },
-    {  -7439,  -2454,  -6348, -4827 },
-    {  -5333,  -7565,  -4417, -4639 },
-    {  -4353,  -7103,  -4197, -2689 },
-    {  -5229,  -6549,  -5129, -6804 },
-    {  -6129,  -7701,  -5236, -4836 },
-    {  -6797,  -3983,  -3884, -4406 },
-    {  -6624,  -4467,  -4745, -5052 },
-    {  -3324,  -7596,  -2720, -6553 },
-    {  -5473,  -6284,  -1704, -4511 },
-    {  -4131,  -7263,  -3180, -5196 },
-    {  -7116,  -5565,  -3469,   685 },
-    {  -6002,  -6021,  -3858,   576 },
-    {  -3144,  -8203,  -1291,  -434 },
-    {  -6096,  -7027,  -4004,  1353 },
-    {  -3943,  -7709,  -2344,   -36 },
-    {  -4510,  -6767,  -2642,   631 },
-    {  -3657, -11541,  -2570, -3984 },
-    {  -5959,  -8854,  -1333,  -867 },
-    {  -6699,  -8866,  -1606,  -344 },
-    {  -3836,  -7961,  -2334, -2028 },
-    {  -3430,  -8045,  -3037,  -672 },
-    {  -3868,  -9184,  -3635, -1819 },
-    {  -4258,  -9060,  -2621, -1008 },
-    {  -3595,  -8693,  -2022,  -752 },
-    {  -4573,  -8048,  -3166, -2622 },
-    {  -4852,  -7903,  -1405,   256 },
-    {  -4591,  -7057,  -1560,   965 },
-    {  -6963,  -7655,   -980,   808 },
-    {  -5179,  -6641,  -3356,  1196 },
-    {  -7102,  -6941,  -2798,  2123 },
-    {  -6867,  -5834,  -3320,  -770 },
-    {  -5977,  -7369,  -2500,  -778 },
-    {  -6160,  -6400,   -934, -2543 },
-    {  -6741,  -7608,   -355, -1289 },
-    {  -6856,  -6466,  -1433, -1643 },
-    {  -4786,  -6292,  -4970,   376 },
-    {  -5407,  -8866,  -2255,  -400 },
-    {  -3814,  -6506,  -1387, -3620 },
-    {  -4998,  -6137,  -1200, -4092 },
-    {  -5123,  -9557,  -2849, -1306 },
-    {  -4259,  -6444,  -4395,  -338 },
-    {  -5221,  -6810,   -883,  1225 },
-    {  -6137,  -6215,  -2165,   554 },
-    {  -3895,  -6557,  -3176, -1829 },
-    {  -3886,  -8188,    -87,  -954 },
-    {  -7243,  -6707,  -2216,  -316 },
-    {  -5592,  -7606,     85,  -432 },
-    {  -3957,  -7945,   -504,  -144 },
-    {  -4617,  -7624,    218,  -312 },
-    {  -4797,  -8737,   -844, -1051 },
-    {  -4478,  -8516,  -1401,  -454 },
-    {  -4557,  -7058,   -302, -2332 },
-    {  -6623,  -7736,   -271,   -50 },
-    {  -3157,  -7532,  -1111, -2207 },
-    {  -3590,  -7300,  -1271,   517 },
-    {  -4442,  -7306,   -507,   590 },
-    {  -6458,  -7524,  -2807,   666 },
-    {  -4991,  -8466,  -3363,  -785 },
-    {  -7474,  -7541,  -1056, -1839 },
-    {  -7501,  -8316,   -938,  -180 },
-    {  -5329,  -7739,   -579, -2341 },
-    {  -4549,  -7063,   -176, -3539 },
-    {  -5191,  -8612,  -1504, -4250 },
-    {  -3083,  -7058,  -2251,    32 },
-    {  -4003,  -7043,  -1093,  -791 },
-    {  -5523,  -8093,   -678,  -114 },
-    {  -3022, -10265,  -2070, -3109 },
-    {  -3905,  -6274,   -182, -3652 },
-    {  -3269,  -9217,   -551, -2650 },
-    {  -3138,  -9314,  -1726, -1704 },
-    {  -4420, -10339,  -1744, -3459 },
-    {  -4163,  -8609,  -2298, -4113 },
-    {  -5566,  -6505,  -1241,  -463 },
-    {  -3130,  -9746,  -2352, -4884 },
-    {  -7825,  -3439,   1451, -1468 },
-    {  -8451,  -3318,   2360,  -435 },
-    {  -8462,  -4130,   1438, -1024 },
-    {  -9425,  -4564,   1328,  -689 },
-    { -11014,  -3202,   2278,  2080 },
-    {  -8269,  -2761,   -146,  -440 },
-    {  -7497,  -2618,   -166,   413 },
-    {  -8250,  -3060,    522, -2133 },
-    {  -8365,  -5366,   1347,  -451 },
-    {  -8589,  -3979,   2943,   714 },
-    {  -8111,  -2572,   1272, -1748 },
-    {  -7830,  -5193,    605, -1484 },
-    {  -8119,  -4736,   2141,   256 },
-    {  -7724,  -4769,   1463,  -812 },
-    {  -7363,  -3911,   2540,     4 },
-    {  -7974,  -3397,   2363,  1366 },
-    {  -7359,  -4204,   1752,  -958 },
-    {  -7622,  -3505,    660,   916 },
-    {  -9934,  -3665,   3165,   828 },
-    {  -8721,  -4162,     62,  1718 },
-    {  -9433,  -4768,   2722,  1234 },
-    {  -7960,  -4496,    138,  1528 },
-    {  -8198,  -3454,   -443,   631 },
-    {  -7756,  -2246,    655,  1137 },
-    {  -8841,  -3145,   1113,   829 },
-    {  -7817,  -3298,   1251,   230 },
-    {  -9413,  -2733,    323, -1862 },
-    {  -9408,  -4168,   1270,  1549 },
-    {  -9037,  -3892,   -942,   283 },
-    {  -8255,  -3849,   1301,  1762 },
-    {  -9057,  -3987,    -41,  -682 },
-    {  -9441,  -4187,   2019,  -111 },
-    {  -9740,  -3178,   1602,  -871 },
-    {  -8344,  -2474,   1461,  1506 },
-    {  -9752,  -2925,   1996,  1243 },
-    {  -9199,  -3796,    180,   537 },
-    {  -9060,  -2405,   1140, -1562 },
-    {  -9348,  -2376,    309,  -162 },
-    { -10786,  -3182,     -5, -1500 },
-    {  -8142,  -4540,   -434,  -826 },
-    {  -7528,  -2341,   1104,   -73 },
-    {  -9360,  -2658,   3062,    56 },
-    {  -8267,  -2335,   2000, -1193 },
-    { -12169,  -3154,   1287,  -640 },
-    { -11398,  -2120,    946, -1163 },
-    {  -8940,  -4559,    328, -1696 },
-    { -11025,  -4213,   2813,   840 },
-    {  -9224,  -3581,   2224,  2039 },
-    {  -8943,  -3337,   1248, -1298 },
-    {  -7900,  -4042,    485, -2080 },
-    {  -9221,  -1947,   2191,  -880 },
-    { -10762,  -1800,   2516,  -324 },
-    { -10095,  -2238,    981, -1335 },
-    { -11908,  -2808,   3255,   645 },
-    { -10640,  -4105,   1283,  -595 },
-    {  -7663,  -2863,   2467,  -797 },
-    { -10712,  -3854,   3710,  1538 },
-    { -10823,  -2893,   1408,  -801 },
-    {  -9874,  -3832,    256, -1638 },
-    { -10394,  -3391,   2315,   -94 },
-    { -11525,  -4079,   4153,  2122 },
-    {  -9546,  -2088,   1541,   481 },
-    {  -8731,  -2433,   1042,  2160 },
-    {  -7852,  -3977,  -1370,  1677 },
-    {   7072,  -3420,   1398, -1741 },
-    {   6180,  -1976,   1280, -3557 },
-    {   7692,  -1793,   2844, -1700 },
-    {   8363,  -1773,   3104, -2679 },
-    {   9213,  -3266,   3756, -3542 },
-    {   9650,  -2644,   1426, -1318 },
-    {   7712,  -2796,   3686, -1975 },
-    {   7316,  -3517,   2821,  -622 },
-    {   7434,  -2594,   2305, -2264 },
-    {   7237,  -1797,    255, -3114 },
-    {   8663,  -1983,   1338, -3056 },
-    {   6616,   -952,   4059, -2652 },
-    {   8823,  -1327,   1362, -1356 },
-    {   9938,  -1722,   1287, -2362 },
-    {   7207,  -1057,   1913, -1315 },
-    {   7508,  -1585,    870, -1982 },
-    {   8217,  -3680,   1417, -3170 },
-    {   8329,  -2541,   1684,  -585 },
-    {   8062,  -2335,    252, -2800 },
-    {   8204,  -4108,   3097, -2569 },
-    {   7701,  -3367,    576, -3008 },
-    {   7350,   -786,   2414, -2129 },
-    {   6948,  -2568,   1607,  -225 },
-    {   7684,  -2387,   1308, -3449 },
-    {   8306,  -3458,   2394, -1454 },
-    {   8438,  -2781,   1043, -1362 },
-    {   9175,  -2076,   2144, -1987 },
-    {   8347,  -2709,   3489, -4301 },
-    {   5696,  -2377,   2870,   851 },
-    {   8825,  -1243,   2219, -2603 },
-    {   8801,  -1614,    584, -2513 },
-    {   8413,   -384,   1421, -2244 },
-    {   9228,  -3050,   3279, -2164 },
-    {   6342,  -2698,   3547,  -107 },
-    {  10053,  -2476,   2837, -3168 },
-    {   7439,   -604,   3177, -3991 },
-    {   7749,  -1064,   4329, -4855 },
-    {   8655,  -2177,   2252, -3519 },
-    {   8490,   -228,   1958, -3233 },
-    {  10513,  -2968,   1911, -2340 },
-    {   8146,   -862,   1884, -1723 },
-    {   7788,   -666,   3004, -2891 },
-    {   7785,  -1620,   4133, -3417 },
-    {  10262,  -3731,   3455, -2971 },
-    {   8570,   -905,   4519, -4649 },
-    {   9129,  -2562,    463, -2465 },
-    {   9451,  -3587,   1904, -3056 },
-    {   6549,  -2236,   3010, -4523 },
-    {   7175,  -2684,   2967, -3458 },
-    {   9872,  -3278,   1054, -2472 },
-    {   9153,   -931,   1217, -2565 },
-    {   8789,  -3469,    753, -2568 },
-    {   6683,  -3791,   1797, -3968 },
-    {   6801,  -1977,   2311,  -452 },
-    {   6336,  -1572,   2612, -3264 },
-    {   7996,  -1008,    730, -2964 },
-    {   7521,  -1059,   1573, -3694 },
-    {   8148,  -3973,   2600, -3572 },
-    {   7765,  -1532,   2528, -3856 },
-    {   7404,  -3918,   4472,  -143 },
-    {   8894,  -1398,   3299, -3685 },
-    {   5768,  -2041,   1487,  -637 },
-    {   5131,  -2865,   2463,  -811 },
-    {   6439,  -1568,   3500, -1550 },
-    {  -8878,  -6798,  -5319, -1452 },
-    {  -6332,  -9713,  -3112,  -990 },
-    {  -8444,  -6316,  -3694,  -687 },
-    {  -6123, -10840,  -3637, -4358 },
-    {  -4784,  -9580,  -4577, -2581 },
-    {  -6108, -10515,  -4859, -2524 },
-    {  -7605,  -7518,  -2327, -2797 },
-    {  -9662,  -8775,  -2467, -2010 },
-    {  -6494,  -7523,  -4715,  -118 },
-    {  -8290,  -8982,  -1672,  -317 },
-    {  -8798, -11051,  -3888, -1426 },
-    {  -6273,  -6623,  -6791,  -142 },
-    {  -8313,  -7668,  -2141, -1275 },
-    {  -6453,  -8412,  -3589, -4102 },
-    {  -6747,  -7750,  -5690, -2498 },
-    {  -7814,  -6693,  -3174, -2446 },
-    { -10383, -10130,  -3931, -2364 },
-    { -10606,  -8467,  -5539, -2772 },
-    {  -9475,  -6671,  -3305, -2271 },
-    {  -8982,  -9457,  -5635, -4005 },
-    { -10111,  -7965,  -6515, -4180 },
-    {  -7301,  -6479,  -5364,   720 },
-    {  -9543,  -8999,  -7921,  -912 },
-    {  -9534,  -8562,  -3469,  -384 },
-    {  -7601, -10344,  -3205, -1127 },
-    {  -8088,  -8620,  -4954, -2888 },
-    {  -8202,  -8406,  -7038, -3775 },
-    {  -7312,  -8324,  -3334, -1775 },
-    {  -8566,  -9262,  -8071, -4174 },
-    {  -7068, -11300,  -5573, -2907 },
-    {  -8295,  -8952,  -4366, -1544 },
-    { -11104, -10210,  -2285,  -384 },
-    {  -5213,  -7520,  -5008, -1339 },
-    {  -5889,  -7940,  -5987, -1385 },
-    { -10816,  -8201,  -4153, -1485 },
-    { -10277,  -8919,  -6315, -1652 },
-    {  -5888, -10320,  -3821, -1733 },
-    { -10497,  -7181,  -6083, -3032 },
-    {  -7721,  -9724,  -6591, -5336 },
-    {  -5688,  -7894,  -3486, -2552 },
-    { -10014, -10500,  -3247,  -820 },
-    {  -6301,  -8765,  -4506, -2923 },
-    {  -8261,  -7847,  -6213, -1552 },
-    { -10212,  -7481,  -8113, -3954 },
-    {  -6938, -10874,  -6074, -4703 },
-    {  -7183, -10968,  -4446, -1773 },
-    {  -7120,  -9193,  -1966, -2509 },
-    {  -6234,  -9263,  -2313, -4284 },
-    {  -8503,  -9857,  -2429,  -608 },
-    {  -9372,  -7844,  -8391, -2120 },
-    {  -7951,  -7157,  -6535,   -11 },
-    {  -7256,  -9473,  -2172,  -660 },
-    { -10063,  -9612,  -2515,   -15 },
-    {  -6684,  -9134,  -6109, -4206 },
-    {  -8204, -11932,  -5220, -2306 },
-    {  -9710,  -6706,  -4115, -3275 },
-    {  -6855,  -7078,  -2409, -4447 },
-    {  -7344,  -7673,  -4479, -4116 },
-    {  -8851,  -6842,  -4927, -2948 },
-    {  -8927, -10452,  -5633, -2194 },
-    {  -8627,  -9002,  -7176, -1575 },
-    {  -8209,  -9722,  -7021, -3324 },
-    {  -3770, -10249,  -3623, -4816 },
-    {  -8183,  -7465,  -4090,   646 },
-    {  -8163,  -7149,    200,   498 },
-    {  -8289,  -6266,    686,  -206 },
-    { -10030,  -6241,  -1032, -1864 },
-    {  -8793,  -8327,   -773,  -169 },
-    {  -9149,  -6215,    969,   -15 },
-    {  -8303,  -5859,     -7,  2006 },
-    {  -9682,  -7283,    255,  1322 },
-    {  -9293,  -7227,     71,  -231 },
-    {  -8525,  -6215,    287,  -837 },
-    { -10477,  -5379,   1159,  1449 },
-    { -10726,  -7856,   -130,   102 },
-    {  -8694,  -7461,  -1210,   690 },
-    {  -9367,  -5324,   1103,  3170 },
-    { -10686,  -8055,   -831,  1633 },
-    {  -9201,  -6873,  -2704,  2258 },
-    {  -8421,  -5358,  -1405,   226 },
-    {  -9066,  -5830,   -307, -1571 },
-    { -11150,  -7381,  -2746,  -900 },
-    {  -9978,  -5925,  -2006,  -437 },
-    {  -9464,  -4741,   -273,  1061 },
-    { -10543,  -6684,  -1113,  1660 },
-    { -10073,  -5576,   1083,  -269 },
-    {  -8826,  -5763,   1600,  1486 },
-    { -10445,  -9071,  -1253,   -64 },
-    { -12085,  -5799,      2,   769 },
-    { -12939,  -6663,   1650,  1437 },
-    { -10932,  -6434,  -1252,  -649 },
-    { -11650,  -7826,  -2053,   710 },
-    { -12122,  -6733,  -1889,  -731 },
-    {  -9093,  -6095,  -2463,  -842 },
-    { -10977,  -4364,    469,   420 },
-    { -11488,  -6908,   -521,   893 },
-    {  -9669,  -5478,   -842,   337 },
-    { -10606,  -5203,   -632, -1361 },
-    { -10198,  -6284,   1662,  1277 },
-    { -10135,  -5292,   2435,  3493 },
-    { -11027,  -6561,    655,    56 },
-    { -10977,  -5030,   1127,  -358 },
-    { -12766,  -3986,   1348,  -335 },
-    { -14244,  -7731,    264,   317 },
-    { -15124, -10309,   -508,  1447 },
-    { -12821,  -8638,   -608,   137 },
-    { -13076,  -8693,  -2852,  -431 },
-    { -11156,  -5546,  -2252, -1600 },
-    {  -8692,  -7366,   -819, -1223 },
-    { -12507,  -9816,  -1714,  -121 },
-    { -10712,  -6666,    544,  3349 },
-    { -12462,  -5890,  -2491, -2318 },
-    { -12468,  -7226,    437,   232 },
-    { -11300,  -5226,   2068,   687 },
-    { -11994,  -8320,   -626,  2728 },
-    { -12222,  -5476,   1142,    18 },
-    { -10277,  -8122,  -2418,  2003 },
-    { -13418,  -6115,  -3563, -2802 },
-    { -14759,  -9834,  -1243,    21 },
-    { -13699,  -5665,   1525,   507 },
-    { -16269,  -9476,   -701,   163 },
-    { -12677,  -5437,   -247, -1019 },
-    { -11827,  -4295,   -181, -1243 },
-    { -12847,  -4496,   2984,  1123 },
-    { -13860,  -7915,  -1166,  -547 },
-    { -12276,  -8145,  -2290, -1527 },
-    { -11417,  -4830,   2983,  1854 },
-    { -11793,  -6002,   1163,  1940 },
-    {  11443,  -4920,  -3235,  3151 },
-    {  11300,  -6616,  -1506,  1175 },
-    {   9198,  -4628,  -2060,  2390 },
-    {  10532,  -4027,   -643,   912 },
-    {   9902,  -3573,  -1606,  1327 },
-    {   9653,  -3536,  -2240,  1869 },
-    {   9948,  -5171,   -423,  2662 },
-    {  12316,  -4004,  -1989,   281 },
-    {  12125,  -4800,  -1265,  -163 },
-    {  10650,  -2617,  -2337,  1462 },
-    {   9909,  -4968,  -2376,   916 },
-    {  12944,  -4647,  -1958,   460 },
-    {  12988,  -5283,  -1141,    41 },
-    {  12321,  -2915,  -3621,  1025 },
-    {  11449,  -2894,  -2728,   351 },
-    {  12087,  -3041,  -2002,   -32 },
-    {  11558,  -4031,  -1343,  -399 },
-    {  12983,  -3740,  -3516,  1245 },
-    {  12099,  -2515,  -2752,   225 },
-    {  12515,  -3465,  -2701,   550 },
-    {  14683,  -5022,  -5272,  2996 },
-    {  12260,  -3383,  -1215,  -528 },
-    {  13810,  -5422,  -2443,  1166 },
-    {  13421,  -5378,  -1886,   721 },
-    {  12961,  -4259,  -2594,   796 },
-    {  12266,  -2104,  -4768,  1591 },
-    {  13523,  -4710,  -3045,  1342 },
-    {  12437,  -2099,  -5610,  2117 },
-    {  11850,  -2183,  -3497,   661 },
-    {  12275,  -3936,   -597,  -697 },
-    {  12459,  -5253,   -517,  -544 },
-    {  12835,  -4094,  -1322,  -168 },
-    {  14360,  -5677,  -3305,  1859 },
-    {  13905,  -4552,  -4309,  2117 },
-    {  11559,  -3412,  -1847,   -81 },
-    {  13379,  -3167,  -5764,  2746 },
-    {  11910,  -1634,  -4342,  1052 },
-    {  12662,  -4742,     71,  -974 },
-    {  13057,  -3254,  -4424,  1705 },
-    {  15046,  -5706,  -4851,  3019 },
-    {  14162,  -4142,  -5514,  2843 },
-    {  12764,  -1845,  -6684,  2888 },
-    {  13714,  -2374,  -7838,  3857 },
-    {  13295,  -1663,  -8293,  4073 },
-    {  10032,  -4152,  -3403,  1421 },
-    {  10942,  -5386,  -2222,   950 },
-    {  10532,  -6385,  -1750,  1925 },
-    {  10273,  -5972,  -1534,   643 },
-    {  10605,  -4782,  -1695,    27 },
-    {  10988,  -5153,  -1123,  -341 },
-    {  11629,  -5884,  -1060,    48 },
-    {  10441,  -4045,  -2431,   311 },
-    {  10788,  -3595,  -4171,  1807 },
-    {  12110,  -5686,  -2127,   976 },
-    {  11746,  -4773,  -2639,   891 },
-    {  11541,  -5299,  -3031,  1732 },
-    {  11416,  -2559,  -5359,  2198 },
-    {  11583,  -5376,   -704,   677 },
-    {  10416,  -3214,  -3516,   872 },
-    {   9651,  -5435,  -1618,  3255 },
-    {   9973,  -5133,   -996,  3923 },
-    {  11707,  -4643,   -430,  -796 },
-    {  10994,  -2709,  -3587,  2302 },
-    {  10716,  -5118,   -645,   270 },
-    {  14100, -10314,   1095,  1531 },
-    {  12944,  -8049,   1105,  -741 },
-    {  13276,  -7035,   -511,   274 },
-    {  14008,  -7254,   -283,   139 },
-    {  11594,  -6536,    -91,  1671 },
-    {  11732,  -8645,    746,    15 },
-    {  14613,  -7085,  -1578,  1183 },
-    {  13083,  -6224,   -750,    -4 },
-    {  13988,  -6256,  -1592,   820 },
-    {  14678,  -8683,    441,   126 },
-    {  15571,  -8872,   -521,  1139 },
-    {  15642,  -9533,    341,   697 },
-    {  15960,  -9586,   -168,  1121 },
-    {  15464, -10239,   1433,    -1 },
-    {  14934,  -7887,  -1046,  1080 },
-    {  15252,  -7630,  -1899,  1628 },
-    {  15485,  -8384,  -1234,  1484 },
-    {  15962,  -8638,  -1815,  1931 },
-    {  16501, -10664,    398,  1167 },
-    {  16146, -10145,    411,   918 },
-    {  14573,  -7475,   -697,   601 },
-    {  14302,  -7996,     28,   257 },
-    {  14769,  -6792,  -2286,  1574 },
-    {  14144,  -6137,  -2169,  1257 },
-    {  14770,  -6271,  -3111,  1933 },
-    {  14110,  -8312,   1083,  -531 },
-    {  15235,  -6991,  -2993,  2174 },
-    {  13222,  -5805,    547,  -891 },
-    {  14796,  -8762,   1254,  -246 },
-    {  16040,  -9181,  -1005,  1551 },
-    {  16487, -10086,   -373,  1420 },
-    {  15077,  -9479,    966,    51 },
-    {  13026,  -6468,    932, -1080 },
-    {  12703,  -6152,    -33,  -573 },
-    {  15641,  -6810,  -4128,  2874 },
-    {  13282,  -7673,   1583, -1283 },
-    {  12373,  -7150,   1512,  -917 },
-    {  12992,  -7751,   -678,   783 },
-    {  10907,  -6858,   -313,  2597 },
-    {  13026,  -8963,    125,  2152 },
-    {  12770,  -9946,   1957,  -505 },
-    {  12482,  -6849,  -1268,   833 },
-    {  13790,  -6181,   -138,  -279 },
-    {  12709,  -8382,   2044,   227 },
-    {  12244,  -6630,    203,  -457 },
-    {  14209,  -6816,  -1032,   632 },
-    {  15134,  -8267,   -288,   640 },
-    {  13619,  -6157,  -1090,   356 },
-    {  14044,  -7413,    725,  -484 },
-    {  12958,  -7753,   2585, -1980 },
-    {  13188,  -8396,   2306, -1558 },
-    {  14379,  -9980,   2132,  -688 },
-    {  14275,  -9857,   1162,   179 },
-    {  13690,  -8648,   1621,  -889 },
-    {  11770,  -6829,   -746,   278 },
-    {  12732,  -8202,    286,    90 },
-    {  13630, -10146,   1867,  -207 },
-    {  12072,  -8740,   1299,  -645 },
-    {  12852,  -9492,   1226,    62 },
-    {  11792,  -7382,    -54,  -116 },
-    {  13779,  -9014,    487,   351 },
-    {  11951,  -7729,    121,   834 },
-    {  11970,  -9781,   2276,    -4 },
-    {  12680,  -7984,   2787,  -787 },
-    {  13300, -14488,   6408, -1927 },
-    {  13635, -15355,   9153, -3073 },
-    {  12804, -13566,   5517, -1625 },
-    {  16624, -10854,   1690,    28 },
-    {  20387, -18532,   6162,  -261 },
-    {  16515, -12642,   3392,  -519 },
-    {  15800, -11095,   2151,  -202 },
-    {  16824, -11790,   1651,   599 },
-    {  17604, -13213,   2563,   538 },
-    {  17892, -14177,   3562,   147 },
-    {  16987, -11399,    869,  1052 },
-    {  17003, -12456,   2442,   265 },
-    {  21657, -21806,   9198, -1250 },
-    {  16825, -13341,   3980,  -686 },
-    {  17525, -12714,   1887,   805 },
-    {  16419, -11034,   1216,   617 },
-    {  20931, -19939,   7469,  -684 },
-    {  18452, -15390,   4573,  -191 },
-    {  14778, -10077,   2841, -1209 },
-    {  17402, -13319,   3042,   160 },
-    {  19365, -17922,   7087, -1061 },
-    {  16298, -11941,   2810,  -351 },
-    {  19087, -16176,   4775,   -84 },
-    {  17666, -12289,    938,  1224 },
-    {  18581, -15894,   5132,  -430 },
-    {  19823, -16717,   4142,   545 },
-    {  19960, -19423,   8400, -1492 },
-    {  18973, -16817,   5906,  -594 },
-    {  19079, -15431,   3528,   503 },
-    {  16667, -12485,   4467, -1302 },
-    {  19791, -17797,   6196,  -529 },
-    {  20005, -17606,   5354,   -20 },
-    {  20123, -18599,   6886,  -728 },
-    {  19068, -14805,   2394,  1105 },
-    {  14443, -13723,   5631, -2029 },
-    {  14730, -14231,   5631, -1450 },
-    {  16089, -15959,   7271, -2029 },
-    {  13473, -11200,   3236,  -924 },
-    {  14413, -10902,   2347,  -267 },
-    {  17666, -18662,  11381, -3496 },
-    {  14749, -11042,   3305,  -275 },
-    {  15304, -10486,   1869,  -240 },
-    {  14809, -12126,   3369,  -616 },
-    {  16896, -16561,   7307, -1845 },
-    {  15782, -14336,   5380, -1264 },
-    {  16395, -15520,   6415, -1588 },
-    {  13681, -11114,   2584,  -320 },
-    {  14244, -12326,   4480, -1632 },
-    {  15247, -13119,   4265,  -898 },
-    {  13987, -12091,   3469,  -597 },
-    {  13941, -12770,   4240,  -839 },
-    {  13771, -13627,   5252, -1384 },
-    {  15010, -16074,   7592, -2249 },
-    {  15852, -17226,   8619, -2655 },
-    {  18921, -16916,   6875, -1501 },
-    {  14909, -11678,   2768,  -295 },
-    {  18988, -18353,   8424, -2070 },
-    {  15457, -15080,   6218, -1513 },
-    {  14916, -15512,   6949, -1883 },
-    {  18108, -14702,   4681,  -701 },
-    {  17600, -15733,   5616,  -775 },
-    {  14070, -13683,   6472, -2626 },
-    {  13832, -11914,   5201, -2232 },
-    {  18846, -19009,   9192, -1961 },
-    { -11981, -10994,  -6324, -2264 },
-    { -10976,  -9047,  -6546, -3828 },
-    { -11288, -10532,  -7014, -4191 },
-    { -10139, -10189,  -7799, -2688 },
-    { -10555,  -9988,  -9181, -2040 },
-    { -11596, -11339, -10022, -2707 },
-    { -13400, -13395, -11306, -4206 },
-    {  -9774, -12281,  -7466, -4133 },
-    { -10842, -13125,  -8777, -4956 },
-    { -11964, -15082,  -9779, -5095 },
-    {  -9382, -10188,  -9053, -4927 },
-    { -11562, -11296,  -3651,  -985 },
-    {  -9287, -10083,  -7918, -4069 },
-    { -12821, -16556, -11410, -6195 },
-    { -12628,  -8959,  -4521, -1113 },
-    { -13845, -11581,  -3649,  -681 },
-    { -12685, -10269,  -5483, -1275 },
-    { -14988, -12874,  -5107, -1189 },
-    { -13761, -11367,  -6202, -1804 },
-    { -13225, -11249,  -7820, -3354 },
-    { -14809, -11992,  -3202,  -312 },
-    { -15620, -15519, -10210, -3433 },
-    { -12954, -10200,  -3139,  -611 },
-    { -11536,  -9981,  -5284,  -923 },
-    { -13034, -12417,  -4612, -1098 },
-    { -16911, -15505,  -6123, -1352 },
-    { -17396, -17685,  -8330, -2171 },
-    { -14120, -10764,  -2265,   -99 },
-    { -12598,  -7367,  -5406, -3530 },
-    { -14143, -12793, -10909, -5226 },
-    { -14692, -16871, -11626, -5554 },
-    { -12581, -11197,  -9194, -3837 },
-    { -16752, -16726,  -9746, -2808 },
-    { -10600, -10358,  -6560, -1227 },
-    { -14573, -13312,  -8957, -3393 },
-    { -10172,  -8463,  -8579, -3387 },
-    { -11418, -12421,  -5522, -1842 },
-    { -11855, -14204,  -6669, -2625 },
-    { -13308,  -8191,  -3941, -2194 },
-    { -10007, -12266,  -5022, -1811 },
-    { -13532, -15771,  -9497, -3175 },
-    { -11760, -11148, -10339, -5529 },
-    { -12149, -12763, -11198, -3697 },
-    { -12029, -12119,  -8555, -1792 },
-    { -16995, -19957, -11447, -3471 },
-    { -13144, -14504,  -9988, -3191 },
-    {  -9938, -11064,  -6139, -3162 },
-    {  -8873, -11550,  -8294, -6550 },
-    {  -9303, -13010,  -6150, -2711 },
-    { -15463, -10469,  -1766,  -170 },
-    { -15985, -11693,  -3007,  -650 },
-    { -17142, -10671,  -1434,    47 },
-    { -16063, -13858,  -4817, -1058 },
-    { -19446, -19599,  -9594, -2464 },
-    { -20076, -18744,  -8313, -1889 },
-    { -15047, -16085,  -7590, -2250 },
-    { -13481, -16195,  -8552, -2998 },
-    { -13829, -14869,  -6704, -1932 },
-    { -16357, -18484,  -9802, -2959 },
-    { -10551,  -8393,  -9303, -5070 },
-    { -11345,  -9156,  -5641, -3107 },
-    { -13217, -13449,  -9270, -4541 },
-    { -11988, -13732,  -9995, -6374 },
-    { -11007,  -9519,  -5168, -4107 },
-    {   9930,  -7858,   8061, -4375 },
-    {   8274,  -7867,   5992, -2096 },
-    {   9692,  -9675,   7621, -3670 },
-    {   9589,  -8110,   6509, -3010 },
-    {  12617, -11976,  10122, -5360 },
-    {  11867,  -8895,   7948, -5323 },
-    {  10388, -10482,   9234, -4324 },
-    {   8188,  -8220,   7810, -2737 },
-    {  10407,  -8787,   4806, -1930 },
-    {  10348,  -8845,   9233, -6614 },
-    {   9422,  -7091,   4820, -2878 },
-    {   9758,  -9796,   5584, -2256 },
-    {  10188,  -7994,   5347, -3343 },
-    {  11133,  -7455,   4015, -2306 },
-    {  10676, -10744,   6093, -2629 },
-    {  11522, -12184,   7848, -3375 },
-    {   8805,  -9883,   5317, -3071 },
-    {   9498,  -9654,   6555, -3592 },
-    {  10488,  -8008,   4066, -1252 },
-    {  11261,  -8930,   6068, -2738 },
-    {  12180, -10397,   5027, -1531 },
-    {   9138,  -8531,   3601, -1959 },
-    {   8107,  -8380,   4970, -2061 },
-    {   9737, -13248,   6438, -2617 },
-    {  11178, -10423,   2622,  -522 },
-    {   9572, -12372,   5199, -2019 },
-    {  12057, -12144,   4147, -1099 },
-    {   9047,  -9925,   2516,  -665 },
-    {  10790,  -8030,   5882, -4386 },
-    {   7199,  -8426,   6337, -2841 },
-    {   7778,  -8285,   3529, -3442 },
-    {   7559, -10569,   3484, -1332 },
-    {   9404,  -8115,   7484, -5541 },
-    {   7792, -11976,   5546, -2573 },
-    {   9313, -10264,   7661, -5195 },
-    {   6701, -10725,   4370, -1784 },
-    {   4918, -11361,   4507, -4527 },
-    {   5147, -12305,   3978, -5556 },
-    {   6525,  -9899,   4481, -3129 },
-    {   7538, -12855,   6060, -4826 },
-    {   8659, -12111,   7159, -4430 },
-    {   8440, -11304,   4547, -1747 },
-    {   9216, -10918,   3507, -1195 },
-    {   6165,  -9254,   4771, -4677 },
-    {   9163, -11019,   5637, -4935 },
-    {  13441, -11509,   6676, -2434 },
-    {   7912,  -9398,   6663, -4048 },
-    {  11723, -13745,   8131, -4148 },
-    {   6065, -10257,   5005, -6327 },
-    {  11618, -12417,   5336, -1894 },
-    {   8891, -13924,   8407, -6131 },
-    {   9622, -12563,   7908, -5109 },
-    {  11479, -10315,   8349, -3991 },
-    {  11676, -14103,   6611, -2330 },
-    {  11951,  -8953,   3829, -1550 },
-    {  10486,  -8044,  10493, -5920 },
-    {  11801, -10769,   9763, -5305 },
-    {   6109,  -8676,   5827, -1346 },
-    {   7030,  -9611,   5624, -5761 },
-    {  12808, -12886,   8683, -4148 },
-    {  13213, -10464,   6381, -3189 },
-    {  11796, -13681,  10703, -6075 },
-    {   9639,  -7949,   9625, -3944 },
-    {   8538,  -6997,   5309,   453 }
-};
+extern const uint32_t ff_dca_lossless_quant[32];
+extern const float ff_dca_lossless_quant_d[32];
 
-/* quantization tables */
+extern const int8_t ff_dca_high_freq_vq[1024][32];
 
-static const uint32_t scale_factor_quant6[64] = {
-          1,       2,       2,       3,       3,       4,       6,       7,
-         10,      12,      16,      20,      26,      34,      44,      56,
-         72,      93,     120,     155,     200,     257,     331,     427,
-        550,     708,     912,    1175,    1514,    1950,    2512,    3236,
-       4169,    5370,    6918,    8913,   11482,   14791,   19055,   24547,
-      31623,   40738,   52481,   67608,   87096,  112202,  144544,  186209,
-     239883,  309030,  398107,  512861,  660693,  851138, 1096478, 1412538,
-    1819701, 2344229, 3019952, 3890451, 5011872, 6456542, 8317638,       0
-};
+extern const float ff_dca_fir_32bands_perfect[512];
+extern const float ff_dca_fir_32bands_nonperfect[512];
 
-static const uint32_t scale_factor_quant7[128] = {
-          1,       1,       2,       2,       2,       2,       3,       3,
-          3,       4,       4,       5,       6,       7,       7,       8,
-         10,      11,      12,      14,      16,      18,      20,      23,
-         26,      30,      34,      38,      44,      50,      56,      64,
-         72,      82,      93,     106,     120,     136,     155,     176,
-        200,     226,     257,     292,     331,     376,     427,     484,
-        550,     624,     708,     804,     912,    1035,    1175,    1334,
-       1514,    1718,    1950,    2213,    2512,    2851,    3236,    3673,
-       4169,    4732,    5370,    6095,    6918,    7852,    8913,   10116,
-      11482,   13032,   14791,   16788,   19055,   21627,   24547,   27861,
-      31623,   35892,   40738,   46238,   52481,   59566,   67608,   76736,
-      87096,   98855,  112202,  127350,  144544,  164059,  186209,  211349,
-     239883,  272270,  309030,  350752,  398107,  451856,  512861,  582103,
-     660693,  749894,  851138,  966051, 1096478, 1244515, 1412538, 1603245,
-    1819701, 2065380, 2344229, 2660725, 3019952, 3427678, 3890451, 4415704,
-    5011872, 5688529, 6456542, 7328245, 8317638,       0,       0,       0
-};
+extern const float ff_dca_lfe_fir_64[256];
+extern const float ff_dca_lfe_fir_128[256];
+extern const float ff_dca_lfe_xll_fir_64[256];
+extern const float ff_dca_fir_64bands[1024];
 
-/* 20bits unsigned fractional binary codes */
-static const uint32_t lossy_quant[32] = {
-         0, 6710886, 4194304, 3355443, 2474639, 2097152, 1761608, 1426063,
-    796918,  461373,  251658,  146801,   79692,   46137,   27263,   16777,
-     10486,    5872,    3355,    1887,    1258,     713,     336,     168,
-        84,      42,      21,       0,       0,       0,       0,       0
-};
+#define FF_DCA_DMIXTABLE_SIZE      242
+#define FF_DCA_INV_DMIXTABLE_SIZE  201
 
-static const float lossy_quant_d[32] = {
-          0,     1.6,      1.0,     0.8,    0.59,    0.50,    0.42,    0.34,
-       0.19,    0.11,     0.06,   0.035,   0.019,   0.011,  0.0065,  0.0040,
-     0.0025,  0.0014,   0.0008, 0.00045, 0.00030, 0.00017, 0.00008, 0.00004,
-    0.00002, 0.00001, 0.000005,       0,       0,       0,       0,       0
-};
+extern const uint16_t ff_dca_dmixtable[FF_DCA_DMIXTABLE_SIZE];
+extern const uint32_t ff_dca_inv_dmixtable[FF_DCA_INV_DMIXTABLE_SIZE];
 
-/* 20bits unsigned fractional binary codes */
-static const uint32_t lossless_quant[32] = {
-         0, 4194304, 2097152, 1384120, 1048576, 696254, 524288, 348127,
-    262144,  131072,   65431,   33026,   16450,   8208,   4100,   2049,
-      1024,     512,     256,     128,      64,     32,     16,      8,
-         4,       2,       1,       0,       0,      0,      0,      0
-};
+extern const float ff_dca_default_coeffs[10][6][2];
 
-static const float lossless_quant_d[32] = {
-           0,      1.0,      0.5,     0.33,     0.25,    0.166,    0.125,
-       0.083,   0.0625,  0.03125,   0.0156, 7.874E-3, 3.922E-3, 1.957E-3,
-    9.775E-4, 4.885E-4, 2.442E-4, 1.221E-4, 6.104E-5, 3.052E-5, 1.526E-5,
-    7.629E-6, 3.815E-6, 1.907E-6, 9.537E-7, 4.768E-7, 2.384E-7,        0,
-           0,        0,        0,        0
-};
+extern const uint32_t ff_dca_map_xxch_to_native[28];
+extern const int ff_dca_ext_audio_descr_mask[8];
 
-/* Vector quantization tables */
+extern const uint64_t ff_dca_core_channel_layout[16];
 
-DECLARE_ALIGNED(8, static const int8_t, high_freq_vq)[1024][32] = {
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-       0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0 },
-    { -4, -2,  2,  1,-16,-10,  1,  3,  1,  0,  6,  1, -3,  7,  1,-22,
-       2, -4, -3, 11, 14,  6, -1,  1,-13, 29,-28, 10, 10, -8,  0, -9 },
-    { -8,  8, -7, 10, -3,-12, -5, -8,  1, -2,  9, -2, -5,-18,  1,  9,
-      -8, -8,  3, 41,  7, -9, -9, 22,-42,-29, 14,-18,-14,-32,  1,-15 },
-    {-16,  8, 15, 16,-16,  5,  2,  7, -6,-16, -7,  1,  1, -3, -2,  0,
-       8, 20,-26,-11,  2,-17,  0, -3,-34,-37, 10, 44, -2, 22,  2, -4 },
-    {  7, 14,  5,  6, 15, -1,  3, -3, -9,-23, -5,-14,  8, -1,-14, -6,
-      -5, -8, 54, 31, -6, 18,  2,-19, -2,-11,-30, -6,-19,  2, -2,-14 },
-    {  1,  2, -2, -1, -3, -3,  1, -5,  1, -3, -4, -8,  5, -4,  0,  1,
-       3,  7, -5, -4, -3,-12,  3, -2, -3, 12,-53,-51,  6, -1,  6,  8 },
-    {  0, -1,  5,  1, -6, -8,  7,  5,-18, -4, -1,  1,  0, -3, -3,-14,
-      -1, -6,  0,-14, -1, -1,  5, -3,-11,  1,-20, 10,  2, 19, -2, -2 },
-    {  2,  4,  3,  0,  5,  0,  3,  1, -2,  0, -6, -3, -4, -5, -3, -3,
-      -7,  0,-34,  4,-43, 17,  0,-53,-13, -7, 24, 14,  5,-18,  9,-20 },
-    {  1,  0, -3,  2,  3, -5, -2,  7,-21,  5,-25, 23, 11,-28,  2,  1,
-     -11,  9, 13, -6,-12,  5,  7,  2,  4,-11, -6, -1,  8,  0,  1, -2 },
-    {  2, -4, -6, -4,  0, -5,-29, 13, -6,-22, -3,-43, 12,-41,  5, 24,
-      18, -9,-36, -6,  4, -7, -4, 13,  4,-15, -1, -5,  1,  2, -5,  4 },
-    {  0, -1, 13, -6, -5,  1,  0, -3,  1, -5, 19,-22, 31,-27,  4,-15,
-      -6, 15,  9,-13,  1, -9, 10,-17,  4, -1, -1,  4,  2,  0, -3, -5 },
-    { -7,  3, -8, 13, 19,-12,  8,-19, -3, -2,-24, 31, 14,  0,  7,-13,
-     -18,  0,  3,  6, 13, -2,  1,-12,-21,  9, -2, 30, 21,-14,  2,-14 },
-    { -3, -7,  8, -1, -2, -9,  6,  1, -7,  7, 13,  3, -1,-10, 30,  4,
-     -10, 12,  5,  6,-13, -7, -4, -2, -2,  7, -3, -6,  3,  4,  1,  2 },
-    { -8,  9,  2, -3, -5,  2,  0,  9,  3,  7, -4,-16,-13,  3, 23,-27,
-      18, 46,-38,  6,  4, 43, -1,  0,  8, -7, -4, -1, 11, -7,  6, -3 },
-    {  1,  1, 18, -8, -6,  0,  3,  4, 22, -3, -4, -2, -4,-11, 40, -7,
-      -3,-13,-14, -7,-10, 14,  7,  5,-14, 11, -5,  7, 21, -2,  9, -3 },
-    {  0,  0, -2,  4, -2,  0,  2,  0, -1,  2, -1,  0,  0,  2,  2,  2,
-      -1,  1, -3, -1,-15, -2,-63,-27,-21,-47,-14,  1,-14, 10,  0,  2 },
-    {  1,  0, -4,  0, -3, -9,  4,  2,  6, -6,  0, -5, 11, -7,-15,  6,
-      -7, -6,  3,  7,-15, -5, 23,-13, -6, 12, -8,  9,  2, -3,  3,  4 },
-    {  6,  0,  3,  0, -2, -4,  2,  1,  1, -1,  1, -2, -1, -4,-22,-15,
-     -46,-66, 10, 20,  2,-17, 12, -6,  1, -2, -2,  0,  1, -5,  1,  2 },
-    { -1,  0,  0,  1,  0, -4,  0,  1,-10, -3, -8,  5,  7,-11,  2,-11,
-      29,-25, 11, 10,  0, -1,  5, -7, -2, -5, -2,  4,  4, -3,  5, -2 },
-    {  1, -1, -1, -3, -2,  1, -8, -3,  2, -2,  4, -5, -1, -7, -2,  1,
-     -14, -7,  3,-30,-15,-14,  3, -4, -1,  3,-13, -1, -3,  1,  2,  3 },
-    { -1, -2, -3,  2,  2, -3,  3,  1, -3,  2,  0, -4,  6,  5, -5, 10,
-     -57,  3, 22,-50,  1, -2, -5, -6, -1,  5,  1,  2,  2,  1, -2,  2 },
-    {  2,  0, -1, -7,  2,  1,  3,  2,  0,  4,  3, -2,  3, -3,  4, -4,
-      24,-35, -3, 38, -6, -5, 15, 20,  3, 16, -7, -5,  0, -4, -5,  0 },
-    {  0,  1,  0,  0,  0, -1, -1,  1,  1, -1,  1, -2,  0,  0,  0,  0,
-       0, -1, -2, -1, -5, -2,-43, -3, 46,-52,-10,  7, -8, 11, -2, -1 },
-    {  0,  0, -1,  0, -1,  2,-41, 33,-44,-48,-15,-26, -9,  6,  3,  3,
-      -3,  2,  2,  2,  2, -1, -1, -2,  1,  3,  0,  0,  5,  2,  3,  1 },
-    { -4,  1,  6,  1, -6, -1, -2,  1,-14, -4,  0, -5, -2,  2, -2,  0,
-      -6,  1,  0,  8,-21, 32, -3,-36, -6, -2, -1, -7,  3,  0,  1, -6 },
-    { -3, -2,  3,  0,  2,  2,  8, -4, -4,  6,  2,  1,  3, -6,  4,  3,
-      13,  0,-12, -1, 25,-20, -2,-23,-15,  7, -3,-11, -3,  6, -1,  0 },
-    {  0,  0, -3, -1,  0,  0, -2, -1, -2, -2,  1, -1,  0,  0, 10,  3,
-      -2,  3,  3, -7, -6, -5,  0, -4,-60,-16, -6, 38,  5,  6, -5,  0 },
-    {  0,  1,  0,  0,  0,  0,  0,  0,  1, -1, -1,  0,  1,  0,  0,  1,
-       0,  0, -1,  0, -8,  2, -9, 10, 40, 31,-56,-21,  4, 20, -4,  7 },
-    { -2, -2,  0,  4, -3, -1,  7,  3,  1,  3, -8,  0,  3,  1,  2,  5,
-       1, -2, 14,  5,  4,  5,  5,  5, -5,  9,-66,  0,-20, -2, -8,  4 },
-    { -2, -1,  4, -1, -8, -2, -4, -1, -3, -3,  2, -7, -3,  5,  7, -2,
-      45, 31,-17,-16, -2, -2, -1,-22,  1, -1, -3,  3,  5, -3,  5, -1 },
-    { -4,  0,  7,  5,  8,  7,  2,  9, -9, -9, -7,-11, -3, -8, 17, -4,
-      34, 32, 18, 22,  1,  2,  1, -7, -5,  6, -1,  6,  4, 10, -2, -7 },
-    {  6,  0, 14,  9,  6, -1, -2, -3,  4, -6, -8,  4,  7, -1, 28, 38,
-      15, -1, 16,-11,  5,  8,  4,-10,  3,-10,-17,  5,  3,  3,  3,  1 },
-    {  1,  1,  2, -1,  2,  1,  0,  0, -1,  0,  0, -2,  1, -3,  0,  1,
-       2, -2, -4, -2,  0, -1,  1, -3,  1,  1,  1, -1,  8,  8, 66, 33 },
-    { -5,  2, -3, -7,  2, -8, -4, 10, 17,-18, -7,  4, -4, -7, -6, -6,
-      -5,  5,-12,  2,  0,  6,  8, -2,  1,  4,-11,  2,  1,  8, 31, 19 },
-    {  6,  9, 16, -6, -6, -1, -2, -3,-11, -2,  7,  7, 17,  3,  4, 10,
-       2,  5,-13,  8,  7,  1,  4,  5,  7,  6,  7, -8,  9, -8, 33,  6 },
-    {  3, -1,  1,  0, -7, -5,  0, 14, -7,  1, -7,  1,  2, -4,  7, 10,
-     -16, 12,  1, -6,  3,  8, -1, 10,-13, -6,-12,-23, 12, -3, 30, 14 },
-    { -2,-15,  0,  8,  3,-19,  5, -3,  2,  3, 13,  7, 14, -3,-10,  0,
-       8,  5, -6,-16, -8, -8, 14,  2, -1,  1, -9,-11, 11, -5, 27,  9 },
-    { -8,  6, -4,  4, -4, -1,  5,  4,  1, -7, -5, -4,-15,  1,  9,  0,
-       8,  4,  1,-17, 11, -2,-19, -1, -6, -8,  3,-12,  3,-17, 33,-10 },
-    { -3, -1,  2,  7,  7, -2,  9,  8,-18, -1,-13,-10, -3, -3, 11,  8,
-      -2,-12, -8,  1,  4,  9, 14, 10, -3,  0,  2,  1, -2,  3, 31, 10 },
-    { -3,-10,  8, -1, -5,-11,  7, -5,  3,  6,  1,  4,-16, 10,  5, -4,
-      -2,-10, -1, 13,  6, -5, -7, 12,  7, -3,-17,  1, 12, -4, 29,  8 },
-    {  1,  2,  5,  2, -6, -7,  0, -1,  6, -1, 10,  6, -4,  5,  2,  2,
-      -2, -8, -6,-11, 14,-13, 27,  3, -2,-12,  5,-16,  2,-26, 20, 15 },
-    { -1, -3, -5, -3, -3,  6, -1,  3, -5,  1,  7,  2,  1,  0, -1, -1,
-       0, -1,  9,  7, -6, -3,  4, -5, -4,  8, -8,-25, -8, -4, 34, 23 },
-    { -1, -2,  1,  1, -1, -2, -1,  1, -1,  0,  0,  0,  0, -2, -1,  1,
-       0,  2,  1, -1,  4,  0,  0,  1, -1,  0,  5,  3, 12, -9, 68,-16 },
-    { 10,  0, -8, 14, -6,  1,-12,  0,  0, -3, -5,-11, -6, 12,  9,-10,
-      -3,  5,  0,  7, 11,  2,  4, -3, -8, -3,  7,  4,  3, -3, 34,  4 },
-    {-12, 13, -5,  7,-11, -2, -1,  1, -4,-14,-21,  3, -3, -3, -4, -7,
-      -9, -4,  3,-17, -2,-13, 10, -2, 12, -4,  0, -9,  1, -5, 31, 10 },
-    {-10,  6,  5,  6,  4, -7, 10,  0,-28, -3,  0,-11, -1, -5, 16,-10,
-     -16,  7, 20,  2, -4,  2, -5,  0, 15,  6,  5,-10,  7, -9, 20,  4 },
-    {  1, -7, -2, -7,  4, -3, -2, -7, -1,-14,  6,-16,  4, -5, -4, -6,
-      -5,  0, -2,  2, -6,  9, -5,  4,-18,  8,-10,  8, 15,  0, 32,  1 },
-    { -5,  7, -3,  7, 15, -4,  0,-16,  9,  5, -5,  5,  4, -3,-12, -9,
-     -18, 10,  2,  2, -3,  7,  3, -1,  6, -9,-10,  3, 15, -4, 35, -7 },
-    { -1,-10,  2,  2, -4, -2, 10,  2, -1,  2, -2,  1, -1,-14,-11,  3,
-      -8,  5, -8, -2,  6, -1, -7,  1,  7,  5,  7,  8, 30, -4, 30, 14 },
-    {  2, -2,  1,  2,  3, -8,  3,  0, -2,  0, -9,  2,  1,  4, -6, -1,
-      -2,  5,  0,  1, -2, 12,  6, -3,  9, -3,  4,-12, 21,-39, 24, -2 },
-    {  3,  5,  1, -2, -2, -2, -3,  6, -8, -2,-11, -8, -1,  4,  2,  2,
-      -4,-10, 12, -5,-11,  1,-15,-34,-11, -7,-11, -1,  7,-14, 38, -1 },
-    { -4,  4,  8,  9,  8,  1, -5, -9,  4, -2, 15, -4, 11,-15, 20, -1,
-      -1, -3,  4, -9, -2, -2, -2,  8,  6, 12, -5,  0, 11,-12, 27, -4 },
-    {  0,  8, -4,  3,-11,  6,-11,  2,  3,  0,  5, -8, -7, -6, -9,-21,
-       4,-11, -1,-16, -7, 16, -3,  7, -7,  4, -5,  0, 11, -7, 31,  3 },
-    {  1,  3,  4, 11,-11, -2, -3, -6,  6,  5,  0,  3, -9, -6,  4, -4,
-       0,  4, -8, 13, -6,-13, -1, -5, -1,  4,  0,  0,  9,-22, 24, 18 },
-    { -7,  3, 10,-13, -6,  6, -6,  6, 22,  1,  0,-14,  2,  3,  7, -1,
-       8, 20, -1,  5, -4, 13,  9, -9, -9,  6,  0, -4,  0, -8, 31, -4 },
-    { -3, -4,  0,  1,  7,  3, -7,  0,  5, -2,  1,  3,  3,  1, -5, -2,
-       5,  2,-11,  4,  0, -1, 12,  0, -3,-13, 15,  8, -6,-27, 34,  0 },
-    { -3, -3, 10, -4,  2, -1, -3,  0, -1, -1, -4,  2,  6, -2, 12,  1,
-       3, -6, -7, -6, -5,  4,-19, -6, -8,-34, -4, -8, 10, -7, 23, 10 },
-    { -7,  0, -1, -6,  8,  4, -4,  2, -5, -8, -7, -9, -8,  5,  9,  7,
-      -6,  1,-12,-12, -1,-16,  5,  0, 16,  3, -7, -8, 27, -4, 23, 15 },
-    { -8,  4,  8,  5,  6, 11, -3,  5,  3, -1,-11,  6, -5,  0,  2, -6,
-      -3, -6,  4, -1,  5, -5,-12, -6,  7, -5,  9,  3,  6, -7, 29,  1 },
-    {  1,  3, -2, -2, -6, -2,  1,  6, -6, -3,  1,  2,  3,  4,  1,  5,
-      -1,  0,  4,  2, 11,  6,  2, -3, 13, -9,-19, 18,-15,-10, 36, 21 },
-    { -3, -3,  2, -1, -7,  6, -4,  1, -3, -1, -2,  2,  3, -7, -3,  0,
-      -2,  0, -2,  6,-19,  3, -8,  2, -6,  7, -1,  0, 29, -6, 28,-10 },
-    { -5,  1, -3, -7,-12, -4,  1,  1, -1, 13,-10, -1, -9, -5,-13,  6,
-      13,  3, -4,  2,  3, 11,  2,  6,-25,-16, -6,  0, 14, -1, 27, 16 },
-    { -6, -1, -7, -5, -2, -5, -5, -1,  9,  1,  0,  3, -8,-12, -6,  5,
-      -6,  5,  3, -9,  1,  4, -7,-10, -9, -7,-17, -5,-15,-23, 25,  3 },
-    { -8, -2,  9, -3, -4,  3, -1,  8, -7, -7, -5, -4, -2,  9,  4, -1,
-      -7, -4, -5,-16,  3, -6, 18,-13, -9, 16,-15,  8, 15,-10, 24,  5 },
-    {  1,-38,  2, 34,  9, 10, 11,  2,  2, -6,  3,  2, -2,  5,  4, -7,
-      -1,  1,  4,  0,  3,  1, -8, -1, -6,  5,  4,  2, -4,  5,  2, -1 },
-    {  1,-22, 15, 18, -2, 10,-16, -9, -8,-11,  8,  4,  0,  7,-14, -5,
-      -1, -7, 12, 17,  9,  5, -7, -4,-12, -6,  7,  0,  7,  2, -2,  1 },
-    {-11,-29,  7, 10, 19, -1, -8, -9,  7,  1,  9,  6,  8, -7,-14,  8,
-      -3,-11,-13,  0, -7,-23, -2, -8, 12,  9,  2, 14, 19,  1, -1,  5 },
-    {-24,-27,-11, 36,  2,  6, -3,  4, -6,  8,  0, 12, -1, -4, -6,  3,
-       4, -1,  2, -3, -2,  3,  2, -1, -2, -4,  0, -1, -2,  7,  2,  3 },
-    { -9,-24, 11, 13,-10,-12, 12, -2,  7,  4,  8, 13, -3, -3,  2,  9,
-      -3, -4,  4, 13,  5, 13, -6, -3,  1, 15,  7, -3,  0, 19, -2, -9 },
-    { -8,-15,  7, 14, -4, -5,  2,-18,-19, -2,  2, 17, 16,  6,-10, 10,
-      -9, 14, -1, -5, -1, -6, -7,  2,  9, 11, 13,  6, -5,-12,  3,  2 },
-    {-10,-37, 13,  1,  3,-14,  0,-20,  4, -3,  8,  2, -2, -3, -9, -5,
-      -3,-17, -1, 13,-11,  2, -6,  4,  4,  0,  3,  1, -9, -4, -5, -4 },
-    { -2,-22, -5, 46, -8,  5,  9,-11,  8,  7,  7, -1, -1, -2, -7,  2,
-      -3,  3, -1, -2,  7,  0,  2, -1,  1, -2, -2, -3,  6,  0, -4, -6 },
-    {-16,-27, 15, 16, -4, 14, -7,-26,  2, -2,  6,  5, -3, 11,  0,  2,
-       3,  9, -7, -1,  2, -4, -4, -1,  6, 10,  1,  1, -3, -2,  3,  0 },
-    { -3,-22, 10, 26,  1,  2, -3,  3, 17, -3, -7,  9,  1,-21, -4,  5,
-       3,  0, -7, -6,  3,  3, -8, -7, -9,  3,  7,  1, -8, 12,  6, -7 },
-    { -9,-25,  3, 18,  9, -6,-11,  0, -5,-12,  9, -8, -7, -6, -6, 22,
-       2, -6, -3, 15,  3,  2, -2,  9, 14,-10, -7, 15, 13,  6, -2, 11 },
-    {  5,-20, -5, 28, 11, 10, -4, -4,  0, -7,  3,  5,  2, -5, -8,  2,
-       6, 10,  9, -9,-18,  3, 14,  1,  3, -3, -1, -6,  7,  7,  2, -1 },
-    { -8,-30,  7, 12, 10,  8,  7,-13,-16,  0,  1, -1, -6,-11,-15,  4,
-       1, -2, 10,-15,  1, 11, -2,  8,  9, -7, -7,  9, -5,  2,  7,-18 },
-    {-10,-32, 10, 11,  3, -1,  3, -5,  5,  2, 14, -6,  3,  1,  5,-15,
-     -11,  6, 20,  4,  0,-12, -7,  3,  1, -1, 10,  6, -1, -9, -4, -1 },
-    {  1,-25,-14, 12,-11,  9,  9,-16,-24,-17, 22, -9, 11,-30, -3, -4,
-       6, -7,  9,  2, -1, -5, -6,  2, -1, -1, 10,  1, -3,  3,  4,  8 },
-    {-14,-26, -6,  9,  8, 17,-11,-24, -7, -4, -8, -2, 10,  2,  2, -1,
-       2, 13, 12, -7,  4, -6,-10,  6,  6,-13,-11, -7,-16,  0, -2,  5 },
-    { -4,-30,-13, 12, 16, -6, 12,-16,-13,  5, 15, -2, -2,-10, -7,  7,
-      11, -1, -4, -2, -4,  7,  4, -8,  1,  3,  0, 11,  3, -2, -5,  4 },
-    { -4,-21, 20, 22,  2, 20, -8,  1,-12, -5, -9,  4,-10,-17, -3, -8,
-      -3,  3,-12,  1, -3,  0,  7,  4,  7,  7, -3,  7,  5,  3,  1, -5 },
-    {-12,-20,  2, 29, 11, -6,  9, -7, -6, -4,  0,  6, 17,-13, -2,-10,
-     -17, -1,-18,  2,  0, 14, -6,  1,  0,  3,  2,-10,  1, -5, -2,  5 },
-    { 16,-37, -1, 26, -2,-14,  1, -5,-14,  2,  2,  3,  6,  1,  1,  4,
-       0, -1,  0, -2, -2,  4,  9, -6,  0, -2, 10, -7, -2,  4,  1,  0 },
-    { -9,-24,-12,  5,  5,  3,-17,-14,  4,  3,  2, -4, 10,-22, -8, -3,
-       6,  1, 12, -8,  4,  1,  9, -1, 18, -3,  6,  5,  3, -5,  9, -5 },
-    {-14,-33, -2, 20,-13,-10,  2, -7, -1, 11, -9, -8, 18, -3,  1,  8,
-       0, -2, 10,  7, -2,-13,  9, -3, -4,  5, -2, -2, -1, -5,  1, -7 },
-    {-10,-23,  8, 14,  1,  7,  1, -3, -7,  4,  1,  1,  8, -7, 15,-14,
-      13, 14,  2,  5,-13, -5, -8, -1,  6,  3,  6,  9,  6, 15, 14,  5 },
-    {-13,-25,-10, 13,-17,-24, -7,-13, -6,-10, -8,  2,  0,-13,-10, -4,
-      -8,  4, -9,  9, -4,  4, -3, -3,  3,  3, -5, -9,  1, -2, 11,  2 },
-    {-12,-23,  1, 18,-11, -2,  5,  9, -5,  5, 14, -9, -3, -2, -6,  2,
-      -2, 11,-13,  1, -3, 11, -9, -4, -2, -6,  8, 10,  1,  4,  2,  1 },
-    { -5,-18, 16, 22,  2,  0,  8, -6, -9, -7, 10,-16, 23, 10,-11, -1,
-       7,  2,  7,  2,  1, -5,  6,  1,  0, -4,  9,  2, -3,  1,  0, -4 },
-    { -3,-26, 14, 11,  2, -9, 17, -2, -1, -5,-16, -9, -5, 10,-13,  1,
-       6, 12, 10, 11,  0,  0, -3,-14,  6, -2,  0,  4, -5, -1, -7, -1 },
-    {-10,-33,  1,  8, 11, -5,  1, -6,  7,  4,  5,  6,  1, -2,-10, -5,
-      -6, 12,-11,  5,-10,  4, 12, -1, -1, -3,  4, -1,  9,  0, 16,-17 },
-    {-14,-37,  7,  7, -2,  5, -8,-11,  2,-13,  4,-19,  1,  8,  8,  4,
-      -9,  2, -4,  3, 12,  2,  4, -4, -8,  8,  1,  4,  8, -1,  6, -2 },
-    { -6,-30, 18, 17,  1,-22, -3,  4, -7,-10,  7,  0, -8,  8, -1,  4,
-       2,  8,  6, -2,  2,  7,  4,  4,  3, -6,  2,  1, -3,  1, -1, -5 },
-    {-17,-18, -3, 22, -8,  1,  9, -2,-17, 20, -5, -5,-12, -5,  4, -5,
-      -9,  8, -2, 16, -3,  0, 19, -8,  8,  1,  2, -4,  0, 11,  0, -3 },
-    { -9,-23,  3, 10,  4,  4, -3, -2, -2, -2,  1,-22, 11,  0, -2,  5,
-      -2, 14, -9,-11, -4,  7,  5, 32,  1, -3, -7,  0, 21, -9,  7, -6 },
-    {  0,  0,  0,  2, -1,  1,  0,  1,  3,  0,  0,  1,  0,  1,  0,  1,
-      -3,  0, -1, -2,  0, -1, -1, -3, -1,  1, -4,  1, -1, -5,-69,-19 },
-    { -3, -5, -8,-12,  4, -3,-19,-11, -5,  0,-14,  7, 18, -6,  7, 22,
-       8, 14, 15, 10,  3, -1, -3,  5, -1,  7, -7,  1, -6,  3,-26,-11 },
-    { -1, -6,  4, -4, -5,-16,  0, -6, -3, 11,  1,  0,  9,  5, 16,  3,
-      -4,-33, -4,  4, -7,  0,  1,  6,-11, -2,-13, -2,-18, 20,-25,-16 },
-    {  4,  0, -1,  0, -5,  1,  0,  2,  0, 11,-10,  4,-10,  7, 16,  2,
-      16, 15,  2, -1,  2,  9,  2,  8, -3, -5, -2,  0, -3,  0,-33, -2 },
-    { -3,-15, 10, 10, -9, -1,  7,  3,  5, -5, -8, -8, -3, 15, -9,  4,
-      12, 13,-13,-14, 10, -6,  9, 22,-27, 23, -1,  5,-24,  2,-30,  5 },
-    {  0, -2,  7, -5, -5,  3,  5,  3, -3, -5,  2,  1, -4,  3, -3, -1,
-       1, -2, 10, 22, -3, -4, -2, -2, -7,  3,  8,  1, 14,  4,-37,  9 },
-    { -3, -4, -1,  1, -4,  0,  6,  2,  6, -7,-10,-10, -1, -4, 11, -3,
-       7, -6,  4,-12, -1,  5,  1, -7, 10, -6, 17, -4,  8,  3,-40, 13 },
-    {  2, 12,  4, -7, 14, -3, 16, -2, 18,  2, 13,  5,  5,  1, 11, -1,
-       0,  9,  2, -6, -1,  2, -6,  2, -5,  3,  5,  1, -1,  1,-32, -7 },
-    {-16, 11,  7, -4,  2, -5, -9,  9, 11, 11, 15,-13,-11, 11,  9,  4,
-       3, -8,-10, 12, 12,  0,  0,-16, -9, 13,  2,  9,  4,-13,-33,  3 },
-    {  6,  4,  5,  4,  3, -1,  5,  6,  4,  2,-11, -1,-15,-11, -1,  1,
-      11, -3, -2, 24, -4, -6,-25,-10,-15, -8,  0,  0, -5,  4,-30,  2 },
-    { 10, -3, -6,  1, -9, -5,  6,  9,-10, -3,  8, -1,  4, -1, 11,-11,
-       3,  9, 11, -3,  6,-17,  5, -8,-33,  9,-13, 19, -2,  9,-25,  2 },
-    {  0,  0, -1, -3,  0, -2,  1,  0,  0,  2,  1,  0, -2,  0, -1,  2,
-       0, -1,  4, -1,  2, -3,  4, -2,  3,  3,  1,  0,-15, 12,-63, 27 },
-    { -2, 14,  9, -1,  3,  0,  1,  1,-19, 15,  3,  4,  0,-10,  1, -5,
-       3,  0, -5,-10,  2,-16, -4,  8,-12, -6,  7, -5,-10, -1,-33, -4 },
-    {  0,  3,  1,  3,  1,  2,  4,  4,  9, -6, -8, -5,  1,-12,  3,  8,
-     -10,  6, -1,  1, 13, -5, -5,  2, -4, 13,-18,-10, -7, -9,-33, 10 },
-    { -6, -3,-12,  5, -1, 11, -6,  0, -2,  1,  2, -7,  3,  1,  3, -2,
-       1,  8,-10,  7, -1, -3,  3,  0, 13,  1,  6,  7,-16, -7,-39,  8 },
-    { -6, -1, 11,  6, -3,  8,  3, -5,  3,  0, -5, -2, -6, -3, -4,  2,
-      -3, 13,-11,  1,  7,  5, 19, -5, -3,-15, -1,  7, -1,  6,-33,  8 },
-    { -7,  3, -4, -3, -4,  1,  6, -5, -5,  6, -8, -1, -7,  4, -1, -6,
-      -2,  1,  7,  0,  1,  1, -5,  2, -2,  0,-13, -2,-31,-14,-39,-12 },
-    {-10,  9,  0, -3,  1, -1, -1,  0,  1, -5, -1, -4, -2,  5,  2, -7,
-      18, -8, -2,-19, -7, -7,-12,-14,-11, -1, -9,-13, -7,-12,-31, -9 },
-    { -3,-16, 10,  9,  1,-10,-12,  2, -2,  2,  7, -3, -3,  1, -4, -5,
-      -9,  5,  7,  3, -1,  4,-11, -8,  4, 13,-10, 13, 10, -4,-36,  1 },
-    { -7,-12,  4,-20, -7, -7,  2, 11, -1, -2,  3,-12,  1,  0, -6, -7,
-       6,  4, 13,  3, -3,  4,  3, -6,-12,  5, -5,-22,-13, -8,-37, -6 },
-    { -7,  5,  3,  5,  7,  9,-14, -3, 10, 17, -1,  1,-12,  5, -6,  0,
-      -4, -9,  0,-11,-14,  3, 13,  6,-25, -8,-12,  4,-10, 18,-30, -1 },
-    {-10,  6,-10,  6,  6,  1,-10,  0, -7,  5, -2, 17,-18, -4,  0, -3,
-     -16, -6, -3, -8,  5,  1, -4,  6, -7, 16,  6, 10, -1,  0,-32,-11 },
-    { -1,  9,  9, -5,  4,  9,  6,  9, -4, -2,  7, 11,  4,  2, -5, -4,
-      -6,  0,  2, -3, -1,  5, 10,  0, 12,-10,-18, -3, -1, 14,-33,  2 },
-    {  4, -8,-18, -4, -5,-11,  4,-10, -4,  9, 13,-12,  1, -6,  1,  2,
-       4, -9,  8,  3, -6, 21, 13, -1, -2,  1, -2,  6, -7,  0,-30,  1 },
-    {  6, -1,  2, -3, -1, -4,  6, -4,  0,  4,  2,  2, -9,  2,  6,  3,
-      -2,  4, -1,  9, -6,  0,  7, -8,  5, 19, -2,  9, -5,  2,-33, -8 },
-    {  2,  1, 12, -5, -8,  8,  3, -2, -4,  1, -2,  5, -4, -9, -8, -8,
-       7,-11, -4,  6,-10,  7, -1, -1, -2, -1, 16, 32, -7, 20,-33, -6 },
-    {-18,  2,  6, 13,  9,  9, -1,  3,-17, 24, -2, -6, 28,  8, -2,  6,
-       3,-10,-34,-16,-13, -4,-15,-11,-12, -3,-10,  4, -8,  4,-31, -4 },
-    {-11,  0, 18,  2,-16, -9,-13, -2, -2,-12, -3,-22, 30,  0,  8,  3,
-       9, -4,-16,  1,  0,-11, 15, -2, -4,  6, -5,  6,  1,  2,-25,-12 },
-    { 14, -1,  5,  7,  3,-15, -8,  1,  5, -2, 12, 13, 11,-25,  3,  1,
-       0, -2, -4,-16,-23,  0, -5,-17,  7,  5, -9,  6, -5,  2,-32, -7 },
-    {  3, -1,  6, 14,  2,-12, -9, -9,  4,  7,  4,  6,  5, -8,  4,  2,
-       4,  5, -2,  8,  8, -6,  0, 10,-20, -1,  3, -1,  8, 23,-33, -5 },
-    { -3, 11, -6,  3, -4,  5,  7,  3,  4,  5, -2,  3, -1, 30,  6,  1,
-       8, -6,  0,  0, -9,  6, -9,  4,  2,  9, -6,  1,-12,  0,-34, 18 },
-    {-17, 13,  0,  1,  9, -4,-11,  0,  7,  0,-10, -4, -1,  6, -6,  4,
-       1,  6, -9,  3, -5, -6,-11,  2, -4, 14, 23, -3,  2,  5,-30, 12 },
-    {-14,  5,-27,  2,  0,  7,  1,  4, 30,  8,  7,  5,  1, -1,  0,  5,
-       8,-10, 48,-11, 12, 33,  6,  8,-15, 20, -2, -5, 32,  5,-19, 10 },
-    {-16, -4,-12, -7, -2,  0,  8, -6,-20,-18, 16, -3,  0, 31, -2, 11,
-       2, -9, 49,-19,-12,-23, 10, 26, 16, -2,  4,-21,-14, 13,-11, -9 },
-    { -5, -9, -1,  3, -5,-21,  2, 10,  0,  0, 10,-21, -7,  7,-26, -9,
-      22, 32, 58, 11, -3, 11, -5, -8,-13,  6, -5, -9,  1, 10, 14, -8 },
-    {  7,  7, 10,  3, -2, -1,-11,-11, -6,-43, -3, 14,-19,-18, 19, 18,
-     -32, 10, 45, -6,  6, 21,-20,-12,  2,  4,  6,  6, -4,  3,  3,  1 },
-    { 21, 22, -3, -2,-11, -6, -1, -2,  8,  8, 32,-21,  7, 28, -4, -6,
-      -3, -2, 50,  2,  2, 27, -5, -8, 12,  7, -5, -1, -4,-17, 27,  6 },
-    { 13,  7,  2, -6,-12,  2,-10, -5,-17, 11,  4, 17,-12, -2,  5,-17,
-      37,-16, 48,-14,-18, 29,  8, 24, 11, -5, -9, 11, -1,  1,-13, -3 },
-    {  1,  1, -1,  2,  0,  0,  0, -1,  1, -1,  7,  2, -3,  3,  0,  6,
-       2, 10, 54,-25,  7, 54, -5, -6, -1,-15,  9, 13,-24,-15,-12,  3 },
-    { 21,  5,  8,  3, -3, -4, -2, -4,  3,-11, -5, -8,  9, 16,  8, -9,
-     -10, -3, 46,-46,  2,  1,-10, 10, 17, 11,-20,-36, 10, 14,  0, -5 },
-    {  7,-13, -6, -9,-24, 45,  2,  8,  8,  0, 17, 20, 12,-24,  1, -7,
-     -15, -3, 46,-13, -2, 20,  1,-13,-11,-13,  2, 15,  1, 10, -1,  3 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1,  0, -2, -1,
-     -16, -9, 31,-69,-34, 26,  7, 17, -1, -6, -1,  0,  0,  0,  0,  0 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -4,
-      -5,-20, 18,-82, 22,  3, -7,  9,  4,  6,  2, -4, -1,  0, -2,  2 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  4, -1,
-      15, -5, 62,-36,  4, 52, -7,  5,  0,  6,  1,  2,  1,  1, -1,  0 },
-    {  3,-19, 19,-20, 13, -4,-11,  8,  8,-16, 10,  1,-14, 30,  1,-33,
-      10,-11, 45,-30,  3, -4, -3,-13,  7, 12,  3,-22,  3, -2, -4, -2 },
-    { -1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  0,  2,  1,
-      11,  8, 70, 48,-10, 21,  4,  9, -9, -9, -4, -6,  0, -1,  0,  0 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  2,  0,
-       2, -1, 80,  2,-15,-36,-10, -5, -2,  8, -2,  2,  0,  0,  0,  0 },
-    { 10,  8, -8, -8,-24, 12, -1,  0, 20,  9, -1, -2,  2, -2, 12,-10,
-      -2,-13, 35,-43, 44, 15,-10,-25,  4, 10, -3, -5, -5,  7, -1,  3 },
-    {  1,  1,  1,  1,  0,  0,  1,  0,  0,  0,  0,  0,  0,  0, -2, -1,
-     -18,  9, 49,-72,  7, -8,  7, -5,  2,  3,  2, -2,  1, -2, -3,  1 },
-    { -1,  4, -3, 10, 19,  4,  3, 20,  6,-24,  6,  9,  8, 15, 18, 18,
-     -36, 19, 57,-11,  4, -3,  8,  7,  2, -3, -2, -9,-15, -2, 12, -4 },
-    { 20,  3, 11, -9, -4, 22, 42,-25,  1,  5,-10,-19,  0,  9,-16,  5,
-       2, 10, 44,-29, 17, -3, -9, -2, -1,  8, 14, -7, -1, 16, -5,  1 },
-    { -7, 16,-11, 12,  6, 33,-15, 14,-23,  2,-26,  8,  2, 10,  0, -5,
-       8, -8, 38,-38, -4,  5,  5,  5,  1, 22,-15,  7,  6,  0,  4, 28 },
-    { -1,-12,  2, 10, -2,  0,  7, 17, 12, 22, -4, 10, 25, 29,  5, 18,
-       4,  1, 27,-39, 31, 17,  2,  2, 22,-23, 13, 16,  1, -7, -4, -5 },
-    {  0,  1,  0,  0,  0,  0,  0,  0,  0,  0, -1,  0, -2,  0,-14,  0,
-      -7,-11, 49,-22, -4, 19, 17,-39,  4,-29, 10,  2, 36, -4, 23, -1 },
-    { -2, -2, -2, -2,  1, 15, -5, -7,-16, -8,-19, 16, -3,-20, 36, -9,
-      -3, 20, 39,-20,  0,  2, 27,-16, 10, 10,-14,-22,-16, -3, 13, -8 },
-    {  5, -9,  6,-25,  7, 37, 13,-10, -5,  3, -5,  7, 18,-22, -7,  9,
-      -5, -4, 50,-11, -4, -5, -5,  8, -4, -2, -4,-27, 14, 20,  7, -9 },
-    {  0,-14,-10,-27,-14,-17, -6, 26, 10,  2, 14,-12, -5,  0,  8,  9,
-       0,-28, 55, -7,-12, -7,  4,-10, 10,  7,-12, 11,  3,  5,  9, -8 },
-    {  2, 23,  4, -2, -1,-20, -2, 14, 10, -9, -9,-24, 10,  0, 11,-12,
-      12, 11, 49,-25, -2, 29,  7,-13, 21,-10, 11,-17,  3,  1, -8,  5 },
-    {  3,  0,-14, -6, 18, -2, 17, -9,-19,  9, -5,  9, 14,  6, 19, -3,
-      27,  1, 41,-21, 20,-15, 33,  0, 26, 14,  7, 10,  3, 20, -3,-12 },
-    { -1, 16, 15, -8,  3, -8, -8, 21, -5,-16,-29,  4,  1, -6, -4,-28,
-       2, 31, 37,-26, -2, 13, 24,  8, -9, -6,-29, 10,  7,  2,  7,  8 },
-    {-10,-10, 11, 13,-32,  2, 16,  9, 14, 23,-15,-13, 24, 13,  4,-27,
-      14, 12, 31,-18, 17, 23, -2, -7,-14,  9,-17, -6,-10, 20,  9,  6 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  2,  0,
-       5,  1, 89,  8, 10, -6,  2, -1,  0,  0,  0,  0,  0,  0,  0,  0 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  2, -1,
-       4, -7, 64,-50,  7, 37,  2,  5,  0,  0,  0,  0,  0,  0,  0,  0 },
-    { -2,  5,  3, -4, -4, -3,  2, -3,  3, -3,  5,  4,  1, -6, -1,  1,
-       6, -2, 50,-35, -7, 43,  7, -7, -5,-26, 24, 21,  3,-15,  5,  6 },
-    { -8, 21,-19, 33, -8, 22,-11, 17,  3,  0,  0, -2,  1, -3,  6, -1,
-      10, -8,  4,-11, -4, -5,  0,  8, -4,  3,  1, -4,  4,  2,  8,  4 },
-    { -7,  5,-20,  9,-22,  3,-14,  1,  6, 13, 23, -2, -4, -7,  2,  0,
-      11,  4,  6,  3, -7,-11, -7,  4,  5,  5,-12,  8,  2,  4,  7, -3 },
-    { -7,  6, -4, 20,-20, 16, -2,  7,  6, 16, 11, 12, -7, -7,  5,  3,
-      -9, -4,  1,  2,  5,  2,  1, -9, -2,-17, -4,  6,-10,  7, -7, -6 },
-    { -9, 18,-17, 12,-24,  1, -1,  4, 14,  9,  4,  3,  2,  8,-12,-14,
-       4, -8, -4,  7,  7,  6, -1, 13, -9, -4, -1,  1,  0, -4, 15,  8 },
-    {-25,  2,-11,  6, -5, 24,-28, -5,  8, 12, -2,  6,  8, -3,  8, -9,
-      -1, -5, -1, -5,  6, -1, -1, -1, -4,  8,-12, -2,-13,  7,  2,  1 },
-    {-14, 14,-18, 20,-10, 12, -2,  9,  1,  0, 12, -2, 15,-10, 26,-17,
-      16,-11, 10,-10,  9, -2,  4, -8,  2, -3,  4,  4,  2, -3, -5,  1 },
-    {-18, 12,-18, 21, -6, 12, -6, 13,-25, 18,  1, 11, -9, -5,  0, 10,
-      -5,  3, -3,  8, -9,  7,  4,  2, -9,  0,  5,  0,  2, -3,  9, -8 },
-    { -4, 16,  1, 18,-30,  9,  1,  6, -8, 13, 13,-12, -6, -1, 13,  7,
-       6,  2,-15, -3,  5,  5,  1, -6,  1, -5,  0,  2,-16,  0,  3, -4 },
-    {-21,  1, -2,  6,-43, 18, -1,  5, -1,  4,  6, -2, -1, -3, -1, -3,
-       0,  1,  2, -9,  0, -1,  0, -2,  0, -1, -1, -2,  6,  0,  1, -2 },
-    {-23, 10,  4,  7,-32,-11,-18,  2, -2, -7, -6, -3, -3,-12, 19,  3,
-      -5, -6, 16, -6, 16,  2, 16, 16,  8, -2, 13,  8,-15,-11,  2, 10 },
-    { -8,  2,-13,  2,-29, 24,-20, 19,  1, 10, -4, 10,  1,  2, -9, 11,
-      -1, -2,  9, -5, 19, -7, 16, -9, -2,-18, 11,  1,  1,  0,  7, -3 },
-    { -6,  3,  4, 13,-26, 10,-10, 28, -7, 28,  1,  7,  0,-14,  5,  7,
-       4, -4,  3, -2,  3,  3,-11,  7,  6,  4,  0, -1,  2, -1, -3,  2 },
-    { -6, 16,-31, 13,-10, 17, -6,  4,-14,  4,  4, -1,-10, 12, -5,  1,
-     -14, 15,  0, -8,  1, -5,  3,  3,  9, -5,  7,-20,  7,  4, 11, -5 },
-    {-19,  3,-17, 14,-12, 16,-22, 18, 14,  8, -2,  4, 10, 12,-14,  4,
-      -3,  2,  3,  7, -7,  7, -6,  2, -2, -4, -5,  0, -5, -2,  2,  1 },
-    { -9, -7,-11, 24,-36, -9,-11,  5,  7,-12,-13, 18, -2, 20,  1, -4,
-      -1,-10, 15, -6, 14,  1,  0,  2,  1,  2, -9,-16,-11,  7, 13,  0 },
-    {-24, 24,-18, 18,-22, 14,-11, 13,-12, 11,-10, 11, -7, 11, -5, -4,
-      -1,  1,  5,  2,  3, -1,  1, -5,  7, -4,  5, -6,  8, -7,  8, -6 },
-    { -6, 18,-22, 22,  5, 11, -1,  6, 19, 22,  8,  4, -8, 20, -2, 15,
-      -6,-18,  0,-33, -9,-12, -1,  6,  5,  2,  5,  5, -5,-17, -3, -3 },
-    {  1, 11,-16,  9,-18, 11, -4, 18, 20, 26,-10,  8,  1,-11,  8, -4,
-       0,  7,  3,  5,  2,  2, 10, -2, -4,  4, -4, -2,  1, -4, -5, -1 },
-    {-10,  6, -1, 18,-17, 27, -3, 10, -2, 12, -7, -9,  1,  1, -1,  7,
-     -12, -1, -7, -6, -1,  8,  3,-15,  8,  9,  3, -7,  4, -1,  1, -1 },
-    {-14,  6,-16, 22,  2,  5,  0,  5,-18, 11,  6, -3, 22,-20, -9, -3,
-       6, -6, -7,-15,  1, 15, -8, 11,  8, -3, -8,  1, -8,  2,  6, -2 },
-    {-21,  5,-19, 19, -7,  4, -7,  0, -8,  6, 12,  5, -3,-22,-13, -6,
-      -1, -3, -2,-14,  6, -3,  1, -8, -7, -5, -6, 11, -3,-10, -5,  2 },
-    { -1,  9,-12, 15, -6,  6,-19, 14, -9, 11,  3, 12,-17, -3,  8, -4,
-      -3, -4,  1, -5,  4,  5, -7,-15, -7, 15, -6, -5,  1, -5, -3,  1 },
-    {-12, 20,-15, 20,-14,  3,-14,  9, -6, 33,-13,  6, -2,  8, -6,  7,
-      -5, -6, -3, -3,  0,  8, -3, -3,  1, -2,  2,  2,  6, -5, -5, -2 },
-    { -7, 12,-18, 12,-18, 10, -4,  8,  2,  4,  8,  9,  0,  3, -8,  3,
-       6,-12, -4,  1, 25, -5, -9,  6, -7,  0, -9, -7,  3, -5, -4, -4 },
-    {-18, 12,-10, 11,-22,  0,-15,  5, -2,  2, -3,  6, -4, -4, -3,-15,
-      -2, -3, 21,  6,-12,-11, 19,  3,  3,-14,  7,  0,-11,-22,-10,  0 },
-    {-15,  2,-30, 15,-17, 13,-16,  8, -7, 10, -8,  2, 11,  3, 10, -7,
-       7,-22, 12,-10,  3,-12,  6,-10, 12,-10,  7, -8,  5,  2,  9,  1 },
-    { -9, 11,-14,  6,-10, 21,  5, 12, -5,  5,  7, 21,  6,  2, -2, -1,
-      -1,  4,  2,-20,-18, -1,-14,  3, -1,  4, -7, 10,  1, 11,  4, -4 },
-    {-22,  8,-30, 13,-21, -4,  4, -1, 12,  9, -2, -3,  2, -6,  4,-13,
-      -2,  8,  8,  1, -7,  3, -4, -5, -1, -7, -2,  8,  8,  7,  8,  0 },
-    { -6, -4,-35, 16,-13, 15,-11, 14, -7,  9, -1, 11,  7,  0, 13, 10,
-      -1,  8,  1,  1, -2,  8, -1,  2,  2,  3,-10, -1,  7,-13, -3, -7 },
-    {-15,  7,-16, 14,-18, 17, -6, 14,  3,  4,  7, -3, 10,-22,  5,-15,
-       4, -4,-11, 15,-15, 11,-11, 20,  1,  0,  2,  1, 11, -3, 11, -7 },
-    {-12,  3,  5, 16,-37, -1, 15, 15,-15, 10,  3,-10,  1, 15,  7,-15,
-     -13,  8,  9, -3,  2, 12, -8,  2, -5,  0, -3,  4,  5, -9, -4,  5 },
-    {-16, 26, -4, 14,-22, 26,  6, -3, -8,  4, 21,  6, 16, -4,-11,  7,
-     -10,  3,  3,  7, -4,  2, -9,  8, -2,  2,  5, -2, -4, -2,  7, -1 },
-    { -7,-10,  4,  3,  2, -4,-12,-10, -4, -5, 16, 19,-16,  1,  2, -9,
-     -10,  0,  9,  7, -8,  3, 12,  8, -6,-11,-13, -1, -3,-20,  6, -5 },
-    {-14,-17,  3, -5, 14,-12,-12,  8, -6,-25, 21, 21, 10, -8,-12,  4,
-      10, -4,  3, -9, 11,  9,  0,  4,  2,-15,  1,-14,  4,  1,  0, -4 },
-    { -4, -9, -3, -1,  6,  3, -6,  6,-10, -4, 14,  8,  2, -3,-12,-19,
-       0, 11,-20,  1,  6, -2,-27, -6, 10,-17,-14,-17, -9,  8, -8,  3 },
-    {-12,-13, 16, -4, -2, 12, -7,-11,  2,-13,  3,  7,-16,-18, -1,-12,
-      -2,  1,-12, -9, -2, -6,  2,  9,-22, -3, -4,-14, -7,  7, -1,  2 },
-    { -7, -8, -8, 15, 15, 18, 15, 16, -4,-37, 11, 15,-12, -1, -3,  3,
-       6,  6,  0, -5, -3, -5,  9,  1,  1,-11, -1, -8, -6,  2,  3,  0 },
-    { -6,  7, -5,-12, 13, 10,-18, -4, -3,-21,  6, 16,-15, -7,-12, -9,
-       1,-12, -1, 10, -2, -1, -3,  4, -4,  1,-16, -1, 12, -9,  5,  9 },
-    {-14, -5,  9,  3,  4, 26,-28,  3, -6,-24,  4,  5,  3, 13,  5, -1,
-       3, -1,  3,  1,  1, -5,  3,  0, -7, -8, -7, -3,  3, -5,  4,  0 },
-    { -4,  2,-10, -6, 25, 26, -6, 10, -6, -8, 15, 11, -6, -3,  2, -7,
-       5, 14,  9, -1,  0,-12,  4, -4,-10,  1, -3,  3, -2, -2, -6, -1 },
-    {-10,  8,-15,-10, 19, 17, -8,  0, -3, -7,  7,  5,-13, -1,  7, -7,
-       1, 13,-12,-13, 17,-12,  1, 26,-18, -3, -5, -6,  4,  5,  8,  1 },
-    {  2, -5,  3,  0,  0,  0,  2, -3, -2, -5,  7, 13, -4,  9,  0, -5,
-       4, -1,-11, -8, -4,  0,-13,  2,-47,-23, -8,-11, -4,  4, -2, -3 },
-    {-18, -4,  4,  5, -1, 17,-12, -8,  1,-12,  7, 20,-12,  3, -2,-11,
-      16, 12, -6,  1,-13,-16, -6, -3, -3, -5,  4,-12, -5, -9, 10,  1 },
-    {-11,  0,  4,  7,  7,  8,  3, -1,  3,-19, 32,  8,-19, -8,  2,  4,
-     -12, 15,-16,  3,  1,  9, -2,  1, -2,  8,  5,  6, -4, -1, 11, -8 },
-    {  3, -1,  4, -2, 14, 32, -9,-23,-10,-12, 22, 15, -1, -2, 10,  0,
-       4,  6, -8,  4,-15, -2, -1, -4,  0, -8,  4,  1, -8,  3,  4,  1 },
-    {-17,-12,  6, -8, 16, 13,-20, -8, -1,-16, 10, 21,-19, 11, -9, -5,
-       7, 18, -6,  7, -7,-18, 13,  2, -2,  8,-12, -9,  2,  4, -5, 16 },
-    {  4,  0, 17,-11, 12,  7,-12,  5, -1,-25, 30, -8, -7, -6, -4, -7,
-       9,  8,  7,  3,  3,-16,  8,  0, -2, -2,-18, -3, -4, -5,  1,  4 },
-    { -3, -6,  6,-16, 17,  6, -3,  2, -9,-17, 12, 11, 11,  2,-20,  8,
-       1,  1,  0,  2, -2, -6,-21,-13, -9,-15, -1, -8, -6, -8,  0, -2 },
-    {-11, -7,  6, -9,  3,  6,  8, 16,  4, -5, 23, 26,-10, -3,  4,  0,
-       2,  2, -4,  4, -2,-12, 12, 10,-11,  0,-10,-16,  3,  0,  0,-10 },
-    { -5,-16, 10, -6, 27, 13, -3,  4, -2,-13, 15,  5,  2,  5,  3, -4,
-      13, 12,-11, -7,  0,  1, 11, 12,  2, 13,-15, -8,  9, -2,  3,  8 },
-    { -5, -8,  4,  3,  9,  3,-11, 10, 14,-25, 14,  8, -2,  5,-12,-21,
-       2, 10, -7,  2, -3,  2,  0,  2, -1, -3, -5, -6, -1,-16,  2,  8 },
-    { -1,  5,  1,-11,  5,  9, -7,  8,-13,-12,  4, 12, -4,  1, -1, -1,
-      27, 29, 10, 15,  2, -6, -3,  4,-21, 10, -9,-11, -6, -1, -9, -3 },
-    { -6, -3, -1, -6, 11, -5,  0, -2, -5,-31, 11,  3, -1,  5, -3,  4,
-       5,  7,-10,  5,-10,-13,  4, 12,-15, -2,  2, -7,  1, -9, -3,-10 },
-    { -3, -7, 17, -8, -5, 36,  8, -7, -8,-20, 12,  8,  1, -1,  3,  0,
-       1,  4,-10,  3,  1,  4, -2, -3, -2, -3,-10,  4, -1, -7,  3,  2 },
-    {-13, -3, -5,  9, 22,  6,-23,  3,-10, -7, 17, 17, 18,-14, -8, -8,
-       2,  4, -8,  2, -3, -8,  6,  4, -1,  7,  0,  0, -3,  0,-12, -3 },
-    { -3,-10,-15, -3,  9,  3,-23, -9,-13,-18, 12, 13, -2,  0,  1,  8,
-      -1,  2, -7,-12, -5, 14,  2,  1,-22,  6,-10, -8, -9, 28, -7,-14 },
-    { -3,  1,  2, -1, 13,  7, -2, -7,  1, -3,  6,  9, -3, -2,  4, -2,
-       2,  1,-10, -2, -2,-22, -2, -7,-10, -5,-11,-27,-12,-16,  4, -7 },
-    {  2, -6, -3,  1,  8,  0, -2, 12, -3, -4, 58, 15,-10, -4, -2,  2,
-      -2,  0, -2, -6,  2,  4, -1,  1, -4,  1, -1, -5, -4, -3,  3,  1 },
-    { 10, -1,  0,  5, 21,  7,-14,  6, -3,-16, 15, 17,-16, 13,  3, -6,
-      -4,  6,-12, -5,  1, -4, -7, -8,  2,  3, -6,  6, -1, -8,  5,  4 },
-    { -6, -2, -8,-11, 15, 10,  0,  8, -6,-15, 33,  8, -2, 18,-15,-11,
-       5, -1,  0, 15,-15, -4, -4, -1, 10,  7,-13,  4, -4,  0,  8,  3 },
-    { -7, -2,  0, -2,  0, -2, -4, -5,-14,-16, 12, 38,  7, 12,  6, -4,
-       0, -1,  0,  3, -2, -6,  0,  2, -9,  1,  0, -1,  0, -2,  4,  1 },
-    { -8, -4, 18,  1, 14,  5,-12, -3, 20,-17,  5, 19,-11, -8, 11, -3,
-       3,  9, -7, -8,  9,-17,  2, 15,-10,-11,  5, -5,  7, 15, -6, -2 },
-    { -7,  2, 38,  5, 19, 16, -5,  4,-13,-20,  0,  4, -4,  6,  4,  2,
-      -7,  6, -8, -2, -5, -7,  6,  3, -4, -3, -2, -3,  7, -6, -4,  0 },
-    {-11,-12,  8,-15, -3, 14, -7,-22,-11,  2, 22, 14,-19,  2,-19, -6,
-       1,  3,-18, 14,  2, -6, -2, -8, -3, -6,  5, -7, -8, -4,  1,  1 },
-    {  8,  7, 25,-21, 12, -6, -5, -4,-10,  6,  0, 10,  1,-12, 18, -5,
-     -15,  4,  1, 14, -1,  5,  8, -7,  1, -7, -3,  9, 10,  1, -1,  0 },
-    {  9, 10, 32,-15,  8,  2, 11, -7,-18, -8,  2, -6, -9,-16, -3,  3,
-      -1,  3,  1, -5,  4, -2,  1, -8,  0, -6, -3,-11,  1,  5,  0,  0 },
-    { 14,  0, 23,-25, 22,  3,  7, 10,  0, -2,  7,  8,  0, 10,  0,  0,
-       3,  2,  3,-10,  0, 10,  0, -7,  0, 10, -1, -5, -7,  1, -1,  2 },
-    { 12,  0, 25,-18, -5, -4, 13,-10,  3, -6,  7, 21,  0,-16,  3,-10,
-      -6,  5, -7, -3,  2,  5,  3, -6,  4,  9, -8, 12, -2,  3,  2,  4 },
-    { 31, 15, 27,-20, 10, -7, 15,-10,  9, -8,  4, -5,  3, -3,  5,  6,
-      11, -2,-12, -2,  6, -2,  1,  2, -1, -1,  1,  1,  3,  1,  1,  2 },
-    { 12, -4, 13,-23, 12, -6,  2,  4, -3, 13,  6, -7,  5,-19, -7, 18,
-       1, -7,  7,  1, 16, -7,  3,  0,  3,  0,-12,  8,-11,  9,  4,  7 },
-    { 29,  1,  3,-22, -5,  6,  0, 12,-14, 11,  1,  6, -3,  4,  6, -2,
-       4,-13, 12,  1,  1,  3,-11,  9,-10, -1, -7, 16,-11, -1,  3,  9 },
-    {  4,  4, 36,-23, -5, -8,-15,  1, -6,  3, 13, -1, -5, -7,  4,  9,
-       2,-11, -3,  5,  1,  3, -6, -1, -4, -4, -2,  2,  3, -1, -5, -2 },
-    { 19, 10,  6,-17,  2, -4, -2, -4, -3, 13,  2,  2,-13, -7, -3,-11,
-       9, -6,  1, -9, -5,  4, -5, -9,-18, -7,-11,  9,  4,-11,  8,  4 },
-    { 16, -3,  9,-16, 18, -2,-12,-16,-11, 11,-18, 16,-13,  6,  2,  8,
-       3,  8, -4,-16, 10,-11, -1, -3, -8,  5, -9, -4,  9, -4,  0, -3 },
-    { 14, 15,  3,-23, -5,  7, -8, -6,  2, 17,  2, 12, -8,-12, 13, -1,
-      -9,  3,  1,  1, 19, 15,  4, -1,  1,  2, -3,  2, -3,  1,  5,  3 },
-    { 32,  5,-10,-47, -5, -1,  4, 11, -7,  0,  2, -2,  1, -7,  6, -4,
-       6,  2, -4, -2,  2, -2,  0, -4,  1, -6, -5,  2, -2, -1, -3, -4 },
-    { 20,  8, 10,-21, -7, -9,-16, 12,  1,  4,  6, -5,  9,-11, -7,  4,
-     -11, 28, -3,  2,  4, -6, 10, -8, -5, -5, -9,  9, -2, -1,  6, -5 },
-    { 38,  3, 23,-25, -6,-18,  3,-10, -8,  6,-10,  1,-10,  2,  2,  0,
-      -7,  2, -4,  5, -1,  8, -3,  0,  3,  3, -1,  1,  0, -4, -4,  0 },
-    { 20,  5, 16,-22, 24,-18,  2,-12,-14, -7, -3, 10,  2,  7,-10,  2,
-      -8,  1,  8, -1,  4,  1,  4, -2,  5, -9,-18, -8,-13,  5,-11, 10 },
-    { 14,  8,-12,-16,  9,-11, -3, -6,-25, -7,  6,  5, -7,-16, 10,  2,
-      -7, -1, -9, -3, 16,  4,  3,  3, -3, -3,-15, 13, -3,  4, 13, -7 },
-    { 16, -9, 19,-23,  7,-19, -3, -5,-15, 11,-21, 21,-16, 18, -1,  6,
-      10,-10, 18,-14, 16,-15,  6, -5, -9,  5,-17, 13,-10, 13,  0, 10 },
-    {  8, -4,  4,-24,  8,-21,-18,  9,-11,  4, -6, 17,  5, -9, -2, -2,
-       2, 15, -2, -3, -2,  1,  7,-13, 15,-10, -8,-11,  3,  3, -1, -1 },
-    { 14, 17,  6,-32,  5,-17, -2,  0, 15, -1, -5, 16,  1, -5, -2,  9,
-      -3,  8,  4, -2, -2, -4, -3,  1,  0,  7, -3,  4, -5,  0, -7,  2 },
-    { 24,  6, 22,-12,  8,  3,-14,  4, -7,  8,  6,  5,  6,  1,  6,-12,
-      15, 10,  4, 11,  9,  6, -7, -4, 10, -9,  2, -1, -5, 11, 15,  3 },
-    { 17, 12,  3,-23,  5, -1, -2,  1, -9, -1, -3,  1,  8,  1, -5, 17,
-      11,  0, -2,-11,  7,  4,  0,-27, -7,  1,  2, -8,  9,  7,  5,  3 },
-    { 12, 10, 12,-10, -4,  5, -1,  2,-24,  5, -8,  2,  6,-17, 19,  5,
-      12, -2, 16, -7, -6,-14,  4,  1, -3, 13,-16,  5, -1,  4,  1,  1 },
-    { 31,  9, 11,-17, 10, -3, -7,  7,  1,  2,  2,  4, -3, -1, 11,  4,
-      -5, -8,  1,  4, 15, -6,-28,  1,  8,  3, -6,  5, 17, -2,  2, -4 },
-    { 11, 19, 16,-26,  0, -7, -7,  2,-13,-15,-12,  9, -3, 27,  8,  4,
-      -6,  1,  4, -6, 11, -1, -6, -7, -3,  0, -6,  4, -6, -7, -3, -1 },
-    { 10, 18, 16,-32, 19, -9, -4, -3, -7,  8,  8, -3,-11, -2, -6,-16,
-      13, 13, -6, -1, 10, -2, -2, -9,  0, -3,  9,  4, 11, -2, -6,  6 },
-    {  9,  4, 19,-33,  4,  7,-12, 36, -3, -1,  8, -2,  2, -8, -9, -4,
-      -8,  0,  1, -1,  0, -4, -4,  3,  0,  3,  6,  0, -6,  2,  0, -2 },
-    { 25,  7, 15,-12,  2,-24, -1, 24, -4,  4,  9,  0, -2, -9,  4,  6,
-       3, 13, -3,  1,  5, -1, -3, -5, -1,  7, -2,  3,  4,  4,  1,  0 },
-    { 19,  6,  8,-20,  9, -9,  5, -4,-13,  7, 11, -3,  5,-13, -9,  6,
-     -11, -1,  0,  4, 11, 26,  3,  6, -7, 12,  6, -3,  1, -9,  7,  1 },
-    { 15,  6, 19,-23, -3, -9,  3, 16, -6, -4,  6, -5,-10,  1, 16,-14,
-       2,  0,  2,-13, -3,  8, -6,  3,  1,  1,  2, -5, 12, -4, -8, -3 },
-    { 14,  4, 16,-20,  1, 12,  0,  6, -3,  9,  4, 16, 10,-16,  5,  7,
-       5, -4, -4,-18, -3,-11, -4,  4, -7,  3, 13,  7,  3,  3,  2, -7 },
-    { 22,  3, -1,-30, 18, -3, -9,  9, -2, 11,-16, -2,-14, 12,  0,  4,
-      -5,  4, -1,  3,-20, 12,  4,-10, -2, -2,-12,-12, 10,  6, 11, -3 },
-    { 15,  7,  2,-21,  5,  4,  9, -9,-33,  7,  7,  3, -6,-14, -8, 10,
-      12,  0,  2, -1,  5,  4, -2,  0, -7,  0,  2,  4,  0,  1, -3,  8 },
-    { -7,  0, 12,  3,  0, -6,  8, -4,  0,  2, 14,-15,  2, -7,-31, -3,
-      14,  0, 14,-15, -1, -4,-15, 10,  1, -3,  1,  2,  5,  2, -8,  1 },
-    { -2,  5,  1,  0, -3,  3,  3, -6, -1,  2, -4,  1,-19,  0,-11, 18,
-      11, 10, 21,  5,  6,  2, 10,  3, -6,  0, -2, 13,  5, -1, -2,  9 },
-    { -9,  1, -5,  0,  0,-15,  8,  4,  8,  3,  8, 12,-13, -2,-39, -2,
-       4, -4,  5, -3, -4,  3, -3,  3, 10,  5,  3,  2, -3,  5, -2,  8 },
-    { -9,  6,  6, -8, 12,-12, 23,-18,  4,-15, -5,  2,-20, 13, -7,  7,
-       7,-12, 14,-12,  6,  1,  1, -3, -8,  9,  0,  1, -7,  3,  7, -6 },
-    {-18, 13,  4,  3,-10,-30,-10, -6,-14,  1, -7, -4,-35,  5,-25, 11,
-       9,  8, 19, -4, -7, -3,-18, -8,  1,  5, 10, -4,-14, -9,  3, -4 },
-    { -6, -1,  4, -9, -9,  4, 20,  0,  0,  3, 11,  7,-16,-17,-20, 11,
-      -6,-14,  1,  4, 19,  2, -8,  6,-15,  3,  6, -5,-14,  3,  7,  2 },
-    {  1,  6, -2, -8, -5, -3,  3, -8, 21,  1,  3, 16,-14, -2, -9, -4,
-      13, -2, 18, 14, 14, 19,-13,  5,-10,  2, -3,  3,  5,  5,  1, -1 },
-    { -1, -5, -6, -2,-11, -7,  5, -4,  5, -1,  0,  3, -3,  2,-19, 18,
-      16,  4, 14,-22, -2,-11,-22,  1, -1, 11,  1,  2, 11,-10,  7,-12 },
-    {  1,  4,  5, -1, -9, -5,  1, 12,  5,  6, 12,  9,-24, 23,  1, 20,
-      14,-11, 13,  5, -2, -2,  5,  6,  2,  1, -9,  6, 10,  5, -4, 11 },
-    { -1, -1,  1,  7, -3, -4,  8,-16, 15, -1, -7,  9,-22,-11,-11, 10,
-      16,  9, -2,  4, 13, 10,  6, 16,  4,  7,  1, -8, -7,-14, -7,  4 },
-    {  1,  3, -6,  0, 15, -9, -4,  0,  4,  6, 12,  9, -6, -5,-22, 17,
-       7,-11, 15, -5,  1,  3,-19,  0,-15, -3, 16,  5,  5, -7,-11, 12 },
-    { -2, -1, 13,  2,  4,-24, 37, -5, -2, -6, 12,  7, -2,-23, -4,  9,
-       2, -3,  3,  2,  3,  3,-14, 11,  0, -4, -2, -2,  3, 10,-10,  4 },
-    {  2,  9,  8, -6,-28, 14, 28,-11, 18,-11,  0,  2, -2,  4,-12,  3,
-       6,  0,  7, -7, -6,  2,  5, -1, -1, -1,  5,  2,  3,  0, -3,  9 },
-    { -7, 14,  5,-10, -3,  7,  4, -5,  7, -8, -7,  4,-12, 14,-16, 25,
-       3,  0,  1, -5, 12,-10,  0,-10,  0, 12, 12, 17, 12, 10, -1,  0 },
-    { -4, -2,  5, -2,-17, -3,  5, -5,  7,-17,  1,  5, -4,  4,-20,  0,
-      11,-15, 13, -8, 10,  1,  1,  5,-12,  9, -8,  0,  6, -1,-11,  4 },
-    { -3, 12, 13,-15, -7, -7,  0,  5, 33,  3,  3, -6,-13, -7,-15, 10,
-       3,  3,  3, -5,  2,  7, -1,  0,-12,  2, 11, -6, -9,  0,  5, 11 },
-    { -8,  5, 10, -7,-14, -4, 13,  0, 18, -3, -6,  7,  1, -6,  0, 21,
-       8, -7, 10, -8, -3, 17, -9,  0, -5,  1,  4,  8, -3, 11, -5,  0 },
-    { -8,  8, -3, -8,  8,-11, 16,-16, 17,  0,  8, 16,-17, 10,-16, 10,
-      -8,  6, 11,  0, 10,  7,  4,  5,  7, -5, -5, -6, -7, -5, -1, 16 },
-    { -6,  0,  6,  1, -8, -8,  8, -7, -5,-10,-11,  8,-19,  6, -7, 13,
-       5, -3,  4, -8,  7, -1,-18,  9,  0, -5,  6, 26,  3,  8,  2,  4 },
-    { -2, -2, 23, -2,-20,  2,  7, -7, -6,-15,  3,  9,-19, -2,-10,  7,
-      -2,  7,  9, 11,  0,  4, -4,  6,  9, -2,  4, -3,  4,  3,  2,  8 },
-    { -6, 12, 10,-10, -7,  4, 17, 11, -6,  1, 12, 11,-18,  8,-12,  4,
-       1, 13,  6,-13, 23,  9, -5,  8, -2, -5,  1,  3,  0, -2, -4,  4 },
-    {  7,  1,  7,-17, -8,  8, -1, -7,  5, -6,  4, -3,-16,  9,-24, 18,
-      -3, 10, 13,-11, -6,-11, -4, 10,  0, 11,  8,  2,  6, -5,-11,  4 },
-    { -4,  1, -5,-10,  0, -3,  9, -2,  4, -1,  1,  5,-41,-10, -7,  4,
-      -3,  3,  1,  0,-12,  4, -3,  0,  2, -1, -2, -5,  3,  2, -7,  5 },
-    { -2,  1,  4,  4, -3, -6,  1,  0, 12, -5, 11,  0,-17, -3, -1, 11,
-       4,  1, 27,-12,  0,-14,  2,-15, -3, -9,  0, -7, -3, 15, -8,  6 },
-    { -6,  4,  9,  2,  4,  3,  7,-10, 28,  1, -2, 48,  7,  0,-10, 10,
-       1, -9,  2, -1,  0,  3, -5,  5, -4, -2,  7,  7,  1,  3,  2,  5 },
-    { -3,  3, -1,  3, -9,  0, -1,  3,  2, -6, 39,-14,-12,  5,-19, 21,
-       7, -6,  4, -1, -4,  0, -4,  1,  0, -9,  1, 10,  0, -2,  0,  7 },
-    {  4,  2,-29, 12,  5, -3, 16, -6, 15,-13, -4, -1,-13, 22,-16, 17,
-      16,  4,  9, -4,  4, -6, -4, 11, -8,  7,  8,  4,  3, -3, -7,-13 },
-    {  0,  3,  3, -6, -4,  0,  9,  0,  5,  0, 10, 10,  4,-13,-12, 16,
-      23, -4,-12, -6, -4, 20,  2,  0, -4, 23,  1,  8, 11, -4, -5, 15 },
-    { -6,  4,-15, -9, -1,-19, 12,-30,-17, -4,  1,-13,-13,  4, -3, 26,
-       5,-25, 11,-14, -6,-13,  0, -7,  9,  2,  8, -1, -8,  1, -8, 13 },
-    {  1,  6,  1, -4, -4,  1,  2,  0, -3,  2, 10,  6, -6, -2,-11,  4,
-      32, 15, 15,-47, -8,  3,-12,  4, -5,  4, -1,  0, -5,  5,  1, -7 },
-    {  2, -1,  0,  0, -1, -6,  0, -6,  4, -4,  5,  9, -5,  1, -3, 51,
-       4, -5,  4,-14, -1, -4, -3,  1, -4, -1,  0,  2, -8,  0,  1,  2 },
-    {  0,  4, -2, -7, -2, -9,  6, -8, 11, -3, -6,  3,-11, -8,-12,  8,
-      11,  5, 19,  3,-24, 19,-14, 11, -5,-18, -8,-12, -5, -4, -1,  4 },
-    { 16,  9, 10, 14,-18, -2,-18,-27, 10, -5, 12, 14,  4,  0, -2, -6,
-     -12, -7, -1,  3,  4,  7, 11, 10,  5, -5, -7,-16, -3, -6,  6,  9 },
-    {  7, 15, -9, 10,-19,  4, -5,-37, -2, -4,  8,  2,  4, -1,  1,  9,
-      -5, -5,-12,  1, -1, -8,  3, -3,  4,  6,  9,  3,  3, -1,  2,  4 },
-    { 13, 17,  3,  9, -7, -7,-15,-17, -8,-13, -4, -8, 19,  2, 16, 25,
-       7, 15,  2, 16, -5, -6,-10, -9, -7, -6, -2, -7,  7,  2,  4,  5 },
-    { 24,  7,  9,  8,-13, -2,  0, -4,  1,-13,  3,  6,  7, 10, -4, 15,
-       5,  7, -4,  5, -5,  3, 13, -7,  5, 15,-11, -2,  7,  5,  8,  6 },
-    { 17,  6,-15, 23, -2, -1, -6, -2,  0, -4, 11, -3, 12, 15,  6, -8,
-     -15, 10, -9,  7, -1,-11,  2, -8, -4,  3,  4,-10,  4,  4, 11,  1 },
-    { 21, 12, -3,  6, -8,  8,-11, -8, -5, -5,  3,  7, -1, -5, 12, 15,
-     -10,-11,  3, 15,  8,  4,  2,-15,  0, 14,  1, -8, -1,  3, 10, -7 },
-    { 16, 12,  5, 13, -6, 15,-23,  0,-17, -9,  0,  4, -9, 13,  6, 18,
-       0,  0, -4, -1,  0, 14,  5, -1,  8, -4, -8, -6,  5, -2, -2,  0 },
-    { 14, 16, -1, 12,-15, -9, -6,-20,  4,  6,  8,  9,  3,  1, -9, -4,
-      -1,-11,  9, 11,-12,  1,-14, -7,  2, -8, 11,  9, -4, 10,  4,-16 },
-    { 13, 10,  3,  7,  0, -8,-33, -6,  4, -4, 19, -2, 14,  6,  5,  7,
-       6, -3, -1,-10,-10, -9,  4, -3,  5,  9,  2,  2, 10,  9, -2, -3 },
-    { 11, 10, 25, 18, -1, -6,-21,-21,-11,-16,  6,  5, 14,  4,  8,  7,
-       0,-10, -7, -9, -5, -4,  3, -1,  1,  6, -1,  6, -2,  2, -3, -9 },
-    { 15,  9,  5, 22,-17, 15, -9,  7,  7, -9, 13,  9, 10, -1,  8, -3,
-      -2,  6,  1, 17,  8,-14,  7, -3, 12,  9,  1,  0,  1, -5, 17,-18 },
-    { 25, 19,-17, 12, -4,-10,  1,-13,-19, -7, -3,  9,  6, -2,  3,  1,
-       4, -2,-11,-14, -1, -7, -5, -9,  7, -1, -3,  4, -5,  1,  0, -1 },
-    { 20,  8, -3,-10,-24,  3, -6, -2,  0,-12, 14,  6,  7, 11,  4,  7,
-     -12, -5, -8,-10,  5, -1, -4,  4, 16,  7,-14,  6, -1, -2, -7,-11 },
-    { 16, 18, 17,  1,-15, -6, -5, -3, -1,-19,  8, -2,  2,  8, 12,-19,
-     -12,  8,  0, -3, -1, -1,  4,-14,  9, -1,-12, -1, -7, 10, -3,  5 },
-    { 18, 12, -7,  7,  0, -3,-13,  0, -1, -4,  9, -2,  6, -1,  0,  1,
-      15,-21,  1, -8, 25,-19, 13, -9,  2, 12,  5, -7, -3, -1, -3,  1 },
-    { 13, 16, -4,  9, -2,  2, -1,-19, -7, -4, 18, -6, 14, 18, -5,  4,
-      -6, -3,-19,-14, -1,-12, 10,  6,  7, 17,-12,-13,-10, -4,  5,  4 },
-    { 27, 17,  4, 14, -9, -2, -4, -8,  0, -6, 14,-11, -7,  2, -3, -3,
-      -2, -3,-13, 12, 16,  1, -5, -9,-10,-11, -2,  3, -7,  5, 11, -7 },
-    {  7, 17,-16, -2,-14,-28, -7, -8, 15,-10,  7, 15,  8, 17, 13, -1,
-       4, -7,-12,-11,  0,  0,  2,  3, -3,  7, -6,  6,  1,-16,  1, -2 },
-    { 23, 11, -9, 15,-23, -4, -6, -4,  2, -9, -7,  9, -8,  3,-13, -4,
-       8, 18, -6, -2,  1, -5,  6,-14, -5, -2, -6, -5, -3, -2,  4, -5 },
-    { 12, 13, 18, 18,-35,  2,  7,-17,  3,-11,  6,  9, -3, -2, 10, -4,
-       3,  3, -2, -7,  0,  2, -4,  0, -4,  0, -6,  5, 10,  4, -3, -1 },
-    { 19, 11,  1, 20,-14,  4, -9,-13, -2, 11,  0, 17, -1, -1, -1, -1,
-      -5, -8,  0,  5, -1, -8,  5, -1,  3,  2,-12, 21, -2,-24,  5,  7 },
-    { 15, 15,-15, 17,-14,-22,  3, -4,-11, -3, -7,  1, 18, 10,  1, 10,
-      -6, -3,  8,  2, -7,  0, -2,  1,  1,  2, -9, -2,  1,  2, -3,  4 },
-    { 45, 13,  8, 17, -5,  2,-16,  2,  8, -2,  8,-15,  4,  5, -1,  7,
-      -6, -2, -6,  2, -3,  0,  0, -9, -1,  7,  2,  3, -3, -3, -1,  5 },
-    {  1, 18, -8, 18,-12,-10,  3,  4,-22,-12, 20,  8, -3,  9,  2, 10,
-     -10, -3,  9,  3,  6, -3, 10, -1, -3,  2, -2,  4,  2,  3, -3,-18 },
-    {  9, 10, -5,  9,-35,-21,-18,-16, -1,-12, -6, -7,-15,-19, 12,  4,
-       4,  9, -7,  2, 14,  1,  4,  0, -1,  6, -7,  2,  1,  1, -4,  4 },
-    { 31,  8,-17, 35, -8,  1, -5, -6, -7, -6, 10, -2, -3,  6,  9,  3,
-      -6, -2,  3,  3,  5, -3,  0,  6,  0,  1, -5, -3, -2, -4, -1,  0 },
-    { 18,  4, -8,  7, -8,-15, -1,-16, 12, 18,  3, 19,  2,  4,  8,  8,
-       0, -5, -8,-12, 10, -5,  0,  1,  0,  4, -3, 16, 11, 11, -2, -6 },
-    { 27, 15,-17,-10,-23,-22, -1,-14, -4, -7, 20, -2, -7,  6, 15, -5,
-      32,  4,  9,-11, -3, -8, 11, -4, -1, -4, -8, -6, -4, -5, -2, -7 },
-    { 22,  4, -7,  2,-15,-11,-17,-10,  2,  0, 15, 11,  7, 12, -8,  6,
-     -10,-18, -6,-12,  7,  3, 22,  3, -7, 14, -5, -2,-13, -7, -1, -7 },
-    { 18, 13,  9, 24, -4,-19, -9,-11, 13,  8,  2,  4, -1,  8, 14, 10,
-     -12,  0,  0,  5, 10,  5,  4, -1,  5,  1, -1, 11,  2, -4,  0, -9 },
-    { 15, 19, -5,  1, -4,-10, -8,-27,  6,  8,  5, 10,  4, 11,  5, -5,
-     -11,  0,-11,-14, -4, -9, -8, -8,  6, -9,  4, -5, -1,  1,  5, -4 },
-    { 18,  1,-13, 14,-14,  9,-15, -7, 12,  1, 13, -4,-20, 12, 10, 12,
-     -12,  7,  1,-13, 10, -6,  5, -3,  4,  8, 10,-13, -3, -6,  9, -3 },
-    { 19,-14,  5, -8, -6,  2, -5,  5, -3, -1,-28, 11, 18, -6, -4, -2,
-      11, 14,-43,-42,  9,  2, 20,-23,  6, 32,  0,  5,  0,  6,  9,  5 },
-    {  8, 11,-14, -1,  7, 12, -7,  2,-16,  2, 10, -3, -1, -7, -7, -1,
-       1,-10,-60,-23,-18, 42,-13,  9, 18,-11,  0,  1,  0,  2, -5,  1 },
-    { -5, -1,  2,  0,  3, -3,  3, -2, -6,  0, -3, -3,  7,  2,  0, -2,
-      -2,  3,-34,-15, 37, 47, 10, 20,  9,  1,  3,-21,-25,-33,-14,  8 },
-    {  5,  6,  2, -2, -2, -2,  6,  5, -5,  7, -3,  1, -5,-13,  9,  3,
-     -17,-19, -2,-79,-12, -7, -8, -6, -2, -2, -1, -1, -7,-13,  6, -1 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1, -1,
-       0,  3,  4,-87,  6,-11, 16, -9, -1,  8,  0,  5,  0,  1,  2,  1 },
-    { -5,  6,  2,-24,  5, -9, -7,  0,  7,  3, -3, 16,-14,-16,  0, 18,
-      15, -9,-14,-28,-17, 53, 14, -6,-28, -1, -3,-10, -7,-14, 19,-15 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -3,  0,
-     -13,  0,-53,  3,-22, 63, 19, 16,  1,-11,  0, -3,  0, -3,  0,  1 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1, -1,
-      -1, -6,-43,-43, -2, 65,-13, -4,  9,  1,  1,  2,  1,  0,  0,  1 },
-    {  0,  1,  0,  0, -1,  0,  1,  1,  0,  0,  1,  2, -1, -1, -3, -1,
-     -23,  1,-61,-55,  3,-28, -6, -4, -4,  8,  2,  1,  1, -1,  0,  0 },
-    {  0,  1, -1,  1, -1,  0, -1,  0,  1, -1,  0,  1, -1,  0, -9, -4,
-     -48,-19,-52,-46, 11,-12,  5,-14,  0,-10,  0,  0, -1, -2, -1,  0 },
-    {  0, -3, -1, -4,  2, -1, -7,  3,  1,  3, -1,  1, -3,  0, -7,  0,
-       3, -7,-61,-51, -4,-21,-16,-21,-11, 14, -7,  8,  3, -5,  1,  2 },
-    {  0,  0,  0,  1,  0,  0, -1,  0,  0,  0,  0,  0,  1, -1,  9, -3,
-      56,-11, -6,-67, -1, 13,  0,  7,  1, -9, -1, -1,  0,  0,  1,  0 },
-    { 14,  9, -2, 14,-10,-10,  9, -5,  1, -8,-23, 30,  8, -7, 23,  8,
-       2, 10, -1,-27,-17, 57, 22,  4, -5,  2,-12, -6,  2, -7, -4, -9 },
-    {  1,  5, 12, -2, -2, -3,  2, -3,  6,  0,  4, -2, -8, -6,  0, 16,
-     -15, 29,-55,-29,-24, 29,  3, 10,  6, 13, 10, -5, 21, 11,-14,  5 },
-    {  4,  2, 26, -6, 10, 11,-23,-10,-27,-20,  3,-24,-11,-10,-13, 25,
-     -10,  5, -9,-36, -7, 43,  3,-13,  6, 13, -2,  0,  1,  3, -3, -4 },
-    { -1,  0, -1,  0,  0,  0,  0, -1,  1,  0, -1,  0,  0,  0, -1,  1,
-     -12, 12,-26,-64,-15, 29, 37, -7, -3,-12, -5, 14,  8, -8,-10, -2 },
-    { 19, -4,-11,-16,  8, 14,  5, 19,  3, 22,-11,-21, -1, -6,-11, 11,
-      10,-24,-23,-40, -8, 20, 17,  5, 13, -6,  3, 14,-20, -8,  3, 28 },
-    {  2,-12, 10,-14,-18, 26,-22,  4, -2,  5,-21,  8,  3,  1, 19,  0,
-     -12, 24,-14,-40, 15, 29,-15,  6, 15,  1,-19,  2,  4,  7,-12, -3 },
-    {  0, 17, 13,  7, -5,-11,  2,-19,  3, 38,-21, -3, -6, -4,  7,  1,
-       1, -5,-40,-10, -2, 35,  8,  8,-10, -8, -9, 33,  4,  4,  0, -2 },
-    { -2,-12,  7, 29,-24,  2, 16, -1, -7, 16, 10, -2, -2, -2, 13, -2,
-     -37, 15,-22,-40,-11, 33, 10, -1,  8, 10,  6,  8,  9,  0,-12,  2 },
-    { 15, -8, -9, -2,  7,-17,  7, 19, 14,  4, 12, 27, 11, 10,  4, 11,
-     -15, 14,-13,-48,  5, 18,  0, -9,-36,-11,  2,  4,  5,  5,-15,-12 },
-    {-12,  0,  3,  4,  7, -5,  5,-14,-24,-18, -6,-15, -8,-20,  1, -7,
-     -33,-28,-40,-38,-18,-10, -5, 17,-12,  4,  3, -5,  5,-13,  4, -7 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1, -1,
-      -3, -9,-49,-60, -5, 45, -1,  6,  0,  0,  0,  0,  0,  0,  0,  0 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1, -1,
-      -3, -9,-49,-60, -5, 45, -1,  6,  0,  0,  0,  0,  0,  0,  0,  0 },
-    {  0,  0,  0,  0,  0,  1,  0,  0,  0,  0,  0,  0, -1,  0,  0,  0,
-       3, -2,  9,-29,-11, 55,  8, 32,-36,-13, -7, 37,  4, 11,  0,  3 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-       4, -1,-39, -4,-30, 63, 28,-17, -6, 10,  7,-14, -9, 11,  9,  7 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1,
-      13, -2,-50,-32, 22, 51,  4,  7,  6, 11,-20,-13,  9, -5, 21, -4 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1, -1,
-      -3, -9,-49,-60, -5, 45, -1,  6,  0,  0,  0,  0,  0,  0,  0,  0 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1, -1,
-      -3, -9,-49,-60, -5, 45, -1,  6,  0,  0,  0,  0,  0,  0,  0,  0 },
-    {  0,  0,  0,  0,  0,  1,  0,  0,  0,  0,  0,  0, -1,  0,  0,  0,
-       3, -2,  9,-29,-11, 55,  8, 32,-36,-13, -7, 37,  4, 11,  0,  3 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-       4, -1,-39, -4,-30, 63, 28,-17, -6, 10,  7,-14, -9, 11,  9,  7 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1,
-      13, -2,-50,-32, 22, 51,  4,  7,  6, 11,-20,-13,  9, -5, 21, -4 },
-    { -8,  2,  1, 22,-31, -6,-25, -3, -3,  1,-15,-11, -2, -3,  4,-13,
-      -9, 15,-18, 37, -7,-37, 12,-13,-11,-25,-10,-11,-22,  7, 16,  7 },
-    { 14, 10,  4,-10, -1, -5, -7, -3, 16, 13, -5,-15,  5, 11, -1,  8,
-     -27,  7,-12, 49, 17,-22,  9, -2, -9, -1,  2,-15, -1, 41,-18,-17 },
-    { -4, -9,-15, -3,  3,  4,  4,  2,  7, -3, -7, -8, -5, 17,-19, -7,
-      36, -9,-38, 17,  1,-48, 11,-18,-13, -2, -8,  4,-10, -5, 21, 11 },
-    { 15,-13,  4,  2,  1, -5, -2,  1,-10,  7, -1,  3, -6,  0, 11,-11,
-       8, 20,-17, 51,-17,-41,  2, 15,  4,  8, -2, 16,-32, -1, 17,  6 },
-    { -8,  8,-18, -5,  4,  6, -3,  8,  0, -4,  2,  0, -1, -4,  5,  8,
-      30, 30, -8, 70,  2,  8,  2,  0,  7,  1, 13, -1, -6, -7,-11,  2 },
-    { -8, -7,  9,-10,-13,  6,-11,-14, 13, 25,-26,  5,  2, -5, -5,  5,
-      -8,  4,  0, 33, 12,-38, -4,  6, 13,  6, 25, 34, -1, 25,-19, -5 },
-    { 18,  3,-17,  4, -8,  7, 20,  1, -1,  5, -5, -2, -8,  8,-35, 15,
-      24, 43, -5, 51,  5,-12, -3,  1, -2,  3, -3, -3, -9,  8, -9,  2 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,
-       2, 10, 24, 76, -2,-22, 11, -1,  4, 33,  4,  1, -1,  1,  2,  0 },
-    {  0, -1,  0,  1,  0,  1,  0,  1,  0,  0,  0,  0,  0,  1,  2,  0,
-      24, 13, 32, 70, 26,  5,-21, -9, -6,-15,  2, -2,  2,  4,  1,  1 },
-    {  5, -4,-11,  4, -4, 22, 10, -2, 13,-11, -4,-21,-17,  0, -7,  4,
-      10,-34, 11, 52,  2,-46, -5,  0,  0, -1,  2,  4, -9,  1,  1, -7 },
-    {  0,  1,  1,  0, -1,  0,  1,  0,  1,  1,  0,  1,  0,  0, -3,  1,
-      -8,  9, -1, 64,-13,-61, -3,  3, -5, 10,  1,  3, -1, -1, -1, -1 },
-    {  0,  1,  0, -1,  0, -1,  0,  0,  1,  0,  0,  0,  1,  1,  2,  1,
-      10, -2,-31, 79,-10, 27,  0, -1,  3,  8,  1,  1,  0, -1,  0, -1 },
-    {  3, 12, 10, 26,-19, 10, -9,  6, -4,-15, 10,  3,-16,  6, 11,-19,
-       3, 10, 18, 44,  5,-30,  5, -9, 21,  4, 20, 10, 14,-25,  8,-17 },
-    {  0,  0,  0,  1, -1,  0, -1,  0,  1,  0,  1,  1,  0,  0, -6, -2,
-       8, -8, 13, 69, 26,-19,-25,-17, 16,  6,-12, 22,  2, -6,  9,  5 },
-    {  0, -1,  0,  1,  0, -1, -1,  0,  0,  1, -2,  1,  0,  0, -4, -1,
-     -34,-15,-33, 56,  9,-42,  9, 10,  6,  9, -8,-11,  0, -6, 15,  5 },
-    { 10,  2,-14, -3,-15,-35, -1,  7,-18, 14,  8, -1,-15,-26,  6,-15,
-     -18, 22,  9, 33,  0,-32, -9,  3,-11,  7,  4, -1,  5, 30,  9,  1 },
-    {  4, 15,  0,  6, -5,-11,  9,  6,  6,  6, 14,  2, -1, 10,-24,-25,
-      -2, -4, -1, 37,  2,-29, 14, -9, 22, 17, -2, 33, 10,-25, 11,-11 },
-    {  0,  5,  2, 18,-12, 21, 22, 33, -7, 21, -9, -7,  7,-15, -7, 16,
-       7,  0,-14, 44, 10,-25,  5, -4, 15, -8, 10, -4,  5,  9, -1, 16 },
-    {  3, 13, 12, 12,  8, 25,-23,  8,-22, -3,-18, -8, 15, 12,  9, 19,
-       0,  0, -9, 49,-27,-15, -9,-15, 12, -8,-16, -7, 13,  5, 13,  2 },
-    { 12, -6,  7, -2, 20, -9,-14, 12, 13, -5,-17, 22, -8, -4,  2,  7,
-     -13, -2,-15, 43, -5,-30, 27,  4, 10,-27,  5, 27,-10,-10,-18,  0 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,
-      -1, 10,-18, 70, -2,-52, -1, -7,  0,  0,  0,  0,  0,  0,  0,  0 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,
-      -1, 10,-18, 70, -2,-52, -1, -7,  0,  0,  0,  0,  0,  0,  0,  0 },
-    { 15,-13,-20, 16,  2, 13,  5,-11, -8, -5, -3,  2, 24,-23, 30, -7,
-      11, 30,-15, 43,  5,-15, 15, -3,-14,  1,-23,  8,  3,  9,  4,-11 },
-    {  0, -1,  0,  1,  0, -1, -1,  0,  0,  1, -2,  1,  0,  0, -4, -1,
-     -34,-15,-33, 56,  9,-42,  9, 10,  6,  9, -8,-11,  0, -6, 15,  5 },
-    { 10,  2,-14, -3,-15,-35, -1,  7,-18, 14,  8, -1,-15,-26,  6,-15,
-     -18, 22,  9, 33,  0,-32, -9,  3,-11,  7,  4, -1,  5, 30,  9,  1 },
-    {  4, 15,  0,  6, -5,-11,  9,  6,  6,  6, 14,  2, -1, 10,-24,-25,
-      -2, -4, -1, 37,  2,-29, 14, -9, 22, 17, -2, 33, 10,-25, 11,-11 },
-    {  0,  5,  2, 18,-12, 21, 22, 33, -7, 21, -9, -7,  7,-15, -7, 16,
-       7,  0,-14, 44, 10,-25,  5, -4, 15, -8, 10, -4,  5,  9, -1, 16 },
-    {  3, 13, 12, 12,  8, 25,-23,  8,-22, -3,-18, -8, 15, 12,  9, 19,
-       0,  0, -9, 49,-27,-15, -9,-15, 12, -8,-16, -7, 13,  5, 13,  2 },
-    { 12, -6,  7, -2, 20, -9,-14, 12, 13, -5,-17, 22, -8, -4,  2,  7,
-     -13, -2,-15, 43, -5,-30, 27,  4, 10,-27,  5, 27,-10,-10,-18,  0 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,
-      -1, 10,-18, 70, -2,-52, -1, -7,  0,  0,  0,  0,  0,  0,  0,  0 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,
-      -1, 10,-18, 70, -2,-52, -1, -7,  0,  0,  0,  0,  0,  0,  0,  0 },
-    { 15,-13,-20, 16,  2, 13,  5,-11, -8, -5, -3,  2, 24,-23, 30, -7,
-      11, 30,-15, 43,  5,-15, 15, -3,-14,  1,-23,  8,  3,  9,  4,-11 },
-    { 16,-18,  7, -4, 31,-15, -9,-13, 20,-12, -6,  0, 12, -6, -2,  4,
-       3, -3, -1,  0,  1,  3,  3, -2,  1,  6,  4,  0, -3,  2, -5,  1 },
-    { 38, -5,-13, -4,  8,-15, 11,  1,  2, -4, -1,  9, 13,  4,-12, -7,
-       0, -2,  7,  2, -6, -2, -3, -2,  3, -4,  6, 15,  1,  1,-11, -2 },
-    { 47,-22,  9,-26,  3, -5,  2, -7,  4, -2,  2, -2,  3,  0,  3, -4,
-       3, -3,  2, -3,  7, -3, -1,  1,  1, -5,  5,  0,  2, -5, -3, -2 },
-    { 14,-16,  2, -6,  7, -2, -7, -4, -4, -7, 14, -3,  7,-19,-14,-17,
-     -29,  6, 26, 16, -5, 13, -4, -1, 21, 14,  1,  3, -6,  0, -7, -1 },
-    { 29,-11,  5, -3,  4, 11,  4,-10,  1,-22, -3,-10,  5,  4,  2,  8,
-      -2, -7,-12,-12, -8, -3,-18, -2, -9, -5, -1, -3,  2,-14,-14,  7 },
-    { 28,-12,  5,  3,  9, -7,  0, -2,  2,  1,  4,  0, -7, -3, -2,  4,
-       4, 14,  8, -1, -4, 14, -7, 17, -2, -2, -9,  2, 19, -7,  9, -8 },
-    { 31,-18,-22,  8, 15, -5,-10,-15,  1, 10,  6,  7,  6, -8,  2, -1,
-      12, -3,  3, -1,  1,  5, -6, -4,  0,  1,  7,-10, -2,  4, -3, -4 },
-    { 53,-30, -4, 12,  2,  3, -3, -3,  0,  1,  6,  5, -5, -4, -7,  1,
-       0,  2,  1,  3,  1,  5,  0,  2,  2, -1,  0,  4,  2,  0, -2,  0 },
-    { 27,-18, -3, -2,  4, -8,  3, -2,-11,  2, 10, -8, -8, -4,  0, -2,
-       8,  0,  9,  0,-16, 11,  1, -6, 13, -3,-10,-13,-15, 25,  1,  0 },
-    { 35, -5, -1, -8, 23, 11,-14, -3,  2, -2,  8, -6, 17, -2,  7,  0,
-      -2, 10,-17, 13, -2, -2, 11, 11,-14,  2, -2, -3, -8, -1,-12, -5 },
-    { 29, -9,  7,  3,  2,-10,  0,  3,  9,  0, -3,  5,  1,-10, 10, -5,
-       3,  6,-20, -9, -6, -4,  1,  0, 12, 17, -8,  9,  3, -1, -9,  0 },
-    { 15,-16, 18,-19, 16,-15, 17,-18, 13,-16, 17,-14, 15, -9, 13,-17,
-       9, -7,  4, -5,  3, -4, -3,  0, -6,  7, -9,  7, -2,  7, -9,  9 },
-    { 21,-10,  7, -2, 12, -7, 13,-17, 11, -2, 20,  3,  5,-11, -6, -6,
-     -15,  0, -9,  5,-11,  7, -1,  7,  8,-10, -9,  3, -5,  9, -8, -2 },
-    { 23,-22, 15, -5, 16, -4, -3,-12,  9,  3, -1, -2, -8,  2, -2,-16,
-       3,  4, -2, -6, -7, 12, -8,  2,-14,  2, -7, 11, -2,  6, -4, -1 },
-    { 34,-17, -4,  8,  4, -6,  1,  8,  4, 16,  3,  6, 12, -1, -1,-15,
-       6,  4, -7, -6,  6,  0,  2,  1, -2,  2,  3,  3, -3, -2,  8, -6 },
-    { 18,-18,  2, -2, 10,  1, 18,-23, -3,-10,  0,  4, 20,-19, -3, -4,
-       2,  8,  6,  1, -3,  1,  1,  3,  5, -1,-11,  3, -7,  5, -1,  1 },
-    { 15,-14,  2,  3, 10, -8, 12,-13, 13,-15,  6, -8, -4,-10, 14, -9,
-      24,  2, -7,-18, 13,-11,  8, 14, -6, -2,  3, -1, -4,  7, -7, -4 },
-    { 20,-12, 13,  5, -1,-10, 15, -6,  8, -1, -3,-10, 17,  0, -6,-19,
-       2, -1,  8, -3,-16,  0, -3,  2, -2,  0,  8, -9,  0,  1,-10, -9 },
-    { 32,  0, -9, -5, -1,  5, 13,-11,  8,  3, 11,-11,  0, -8, -2,-14,
-       7, 10,  6, -5,  1, 10,  2, 12,-10,  4,  4,  6,  4,  0, -7,-10 },
-    { 16,-14, 10, -7, 11,-11, 11,-11, 18,-13,  8,-15, 16,-11, 13, -9,
-       8, -7, 12,-11,  7, -6,  3, -5,  9, -5,  4, -1,  7, -4,  8, -3 },
-    { 24,-27, -1,  5,  8, -5, 12,  7,  4, -3,  3, -1, -9,-11,-13, -5,
-      10,  0,-13,  7,  1, -5,  4, -9,  7, -3, 13,  2, -5, -3,-17, -2 },
-    { 23,-19, 15,  1,-10,-18,-12, -6,  8, -3, 12,  0,-12,-10, -4, -4,
-       8,-10,  4,  2, -2, -8, 13, -3, -2, -6,  2, -3,  5, -2,  2, 11 },
-    { 25,-12,  4,  2, 24, -3,  3, -6, 14, 11,  0,-21, -3, -3,  1, -8,
-       7,  0,  0,  3,  3, -6, -7,  6,  2,  1, -4,  5, -1, 10, -2,  9 },
-    { 24, -8, -6,  7, 16,-12, 13, -1, 11,-21,  2, -6,  3,-12,  0,  9,
-       4, 11, -7,  1,  4,  1, -8,  3,  3, -6,  3,  3,  0, -8,  8,  4 },
-    { 25,-21, 13, 14, 13,-18,  4, -3,  0, -5, -4,  5, -3,  0,  4, 12,
-       7,  3,  5, -5,  2, -2,  3,-10,  2, -9,-15,  6,  1,  7, -5,  1 },
-    { 23,-16, -2, 10,  4, -1,  3,  1, 32,  3, -5, -2,  9, 10, -1, -4,
-      -6,  2,  9, -1, 14, 12, -6, -1,-17, -2, -4, -9, -7, -6, -8,  3 },
-    { 50, -8,  5,  2,-11, 10,  0,  0,  6, -3,  7,  0, -3, -2, -3,  0,
-       6, -4,  2, -5, -9,  0,  3, 10,  1, -7, -2, -3, -6, -9,  1, -2 },
-    { 28,-17,  0, -2,  2, -9,  1,  5, -4, -1,  0,  0, 19,-27,  5,-12,
-       7,-14, -3, -6, 10, -2, -4, -2,  4, -5, -2, -7,  1,  7, -9,  4 },
-    { 22,-19, -6, -6,  3,-22,  3,  5, 20, -8,-14, -5,  1,  1, 20,  2,
-      16,  6,  3, 14,  4,  3,  5,  1,  5, -7,-10, -6,  3, -6,  1,-14 },
-    { 29,-14, -8, 13,  8,-10, -6,  4,  4, -6,  5, -7,  1, 12, 14, 11,
-      -7,  1,  2, -9,-11, -9,  0,  4, -1,  7, 10,  4,  4, 20, -1,-11 },
-    { 18, -9,  4,  1,  7,-29, 12,  1, -1, -9, -2, -1, -2,  2,  9, -8,
-     -13,  5,  4,-13, -4,  2, -5, -7, -6, 14,-10,-34, -3,  1, -3,-13 },
-    { 38, -9, 24,  8, 11,  4, -6,-11, -2,-12,  1,  1,-11, -8, -5, -2,
-     -15, -8,  8,  0,  1, -7,  5,  4, -1,  8, -2, 11, -3, -1, -5, -5 },
-    {-20, 11, -4, 24,-11,  1, 15,  4,  0,-28,-10, -1, 10, 10, -6,  5,
-      -6,  2,  7, -2,  1, -2, -6, -3, -7,  1,  2, 12, -1,  7,  0, -2 },
-    { -9, 10,-23, 27, -4,-17, 20, -6, 14,-17,  5, -1,  5, -9, -7,  5,
-      -6,  4, -2,  9,  0,  8,  0,  1, -3, -3, -5, -8,  5, -2, -2, 12 },
-    {-10, 19,  4,  9,  1,-16, 17, -2,  9,-29,-16,-11, -4,  7, -5,  4,
-      -1, -3,  3,  2,  3, -4,  5,-12, -2,  6,  5, -4,  4,  1,  4, 10 },
-    {-20, 10,-24, 14, -5, 11,  9,  0, 16,-20, 10, -5, -6, -6, -1,  2,
-      -4,  5,-16,  8, -2,  5,  5,-11,  9,-11,  4,-11, -1, -1,  4,  3 },
-    { -9, 11,  3, 19, 24,  4,  5,-14, 30,-17, -4, -2,-17,  7,  2,  3,
-       1,  3, -7, -4,  2, -3,  1,  4, -1, -1,  3,-12, -2,  3, -3, 10 },
-    {-19, 18, 11, 19, 19, 19, 10,  4, 13,  6,  5,  4,  8,  3, -2, 12,
-      -6, -2,  7, -6, 15, 12, 16, 16, 18, -3, -4,-20,  0, 10, -9, -3 },
-    {-21,  9, 20, 12,  0, -3,  5, -9, 15,-13,  5, -5, -6, 24,  2,  9,
-      -5,  2, -7,  2,  5,  7, -5,  2, 15,  3,  1, -1, -4, -2,  7,  0 },
-    {-18, 16, 13, 15,  2,-10, 14,-11,  4,-11,  5, 12, 12, 20,  8, 30,
-       2, 11, -9,  7,  0, -3,-16, -5, -6,  5, -4,-21,  0,  5,  6,  1 },
-    {-26,  8,-13,  9,  6,-10,  2,-11,  7, -4,  6,-19,-11, -6,-12, 16,
-       0,  5, -7,  8,  5,  6, 17, -9, 10,-10,  5, -3,-11,  2,  4, 10 },
-    {-11, 17, -3, 22, -5, 18,  3,  1,  4, -5, 14,-27,  5, -7, -4, -5,
-     -10, 11,  1, 15,  1,  1, -6, -5, 10,-22, -7, -7,-15, 13, -4,  5 },
-    {-17, 14, -7, 13,  3,  0, 13, -6,  9,-14,-22, -1,  1, 19, 14, -3,
-       4,-13,-13,  2, -4,  8, -2, -2, 13,-12, 13,-12, -7, -5, -3,  6 },
-    {-17, 17, -1, 33,  6,  3,  9,-16,  3,-14, -8,  6,-17,  8,  3, 13,
-       8, -6,  3,  1, -2,  0, -2,  8,  4,  9, 13,-10,  4,-17,  0, -6 },
-    {-20,  7,  7, 21,  1, -3,  7, -3, -2,-12,  9, -7,  2, -3, 14,  1,
-      -1, -7, 12,-10,  5,-20, 11, -2,  0,-24,-17,  6,  6, -4,  3, -1 },
-    { -8, 10,  6,  7, -1, -6, 28, -6, 10,-33,  1,-20,  0,-12, 10,  1,
-      -6,  8, -3, -1,-10,  8,  5,  0, 10, -2,  8, 16, -5, -3, -7,  4 },
-    {-17, 13,  3, 15,  1, -5, 27, -5,  6, -6, 12,  2, -4,  8, -1, -3,
-      -2, 12,-15,  3,  4,  1,  2, -9,  0,-16,-21,  2, -4, 16, -7,  4 },
-    {-15, 20,  8, 17,  5,-14, 15,-11, 21,-11, 13,-13,  2,-15,-13,  1,
-      -5,  5,  2, 10, -9,  4, -1,  3,  2, -4, 13, -5,  1, -4,  5, -3 },
-    {-21,  8,  2, 16, -1,  2, 15,-16, 13,-12,-12, -7, -8,  2, -7, 11,
-      -8,  5,  2, -7, 16, -4,  1, -7,  3,-15,  6, -5, -8,  2, -8,  5 },
-    {-15, 17, -6,  3, -3,  3,  9, -7, 14,-23, 11,  1, -1,  4,  7,  6,
-      -1,-14,  7,  6, -8,  5,  1,-15, 10, -9,  2, -3, -1,  4,-10, -4 },
-    {-10, 18,  3, 11,  1,  4, 14,-14,  7, -4, 15,-10, 10,-11, 10, -4,
-       5,-14, 10,  4, 15,-12, 15,-13, 20,-15, 14,-15,  8,-11,  4, -6 },
-    { -7, 23,  2, 20,  7,  8, 19, -5,  9,-16, -8,-17, -5,  1,  5, -6,
-      -8,  1, -6, -4, 10,  6,  6,  2,-11, -4,  0,  2,  4,  7,  9, -4 },
-    {-15, 20, -5, 22, 11, -8,  9, -5, 10,-13, -8,  8,  2, -2, -3,  7,
-       6, 10,  1,  2, -5, -9,  1, 10, 16,-22, -7,  0,  7,  7,  6,  1 },
-    {-26, 19, -5,  3,  5, 25, 18, -5,  9,-14, -8, -6, -2, -6,  2,  3,
-      -8, -2, -7,  7, -3,  7,  3,  4, -8,  0,  1, -8, -4, -2, -2,  1 },
-    {-20, 14,-10,  6, -3,  7,  8,-32, -2, -7, -2,-10, 16,-12, -9, 15,
-      -2, -5, -6,  2, -7,  5,  9,  1,  6, -7, -1,  0, -2, -4, -7,  3 },
-    {-14, 16,  4, 11, -8,  1, 23, -4, 17,-13,-10,  1, 12,  9, 12, -4,
-       7, -1, -1,  5, -8, -6,  3,  3, -6, -3,-18,  0, 18, 20,  4, -2 },
-    {-33, 19,-10, 30, 15,  2, -3, -1, -4,-14,  7, -7, -1,  7, -8,  9,
-      -1, -3, -5,  2,  2,  4,  0,  5,  0,  0,  2,  3,  3, -3, -3,  4 },
-    { -6, 20,  0,  5, 17,-10, 18,-17,  9,-16,  4,-13, -6,  2,-14, 14,
-     -28,  9,-12, 25, -4,  7,  7, -8,  6, -6, -2,-10,  2,-11, -1,  2 },
-    {-12, 14, 12, 52, -3,  5, -5,  4,  8,-13,  2, -5, -4,  2, -2, -1,
-      -2,  3,  3,  5,  2,  3,  0,  1, -5,  2, -4, -3,  1, -5, -2,  0 },
-    {-13,  6,  9, 24,  0,  8, 14,-15, 18, -9,-11, -8,  3, 15, -2, -4,
-      -9,  4, -3, 12, 14,-13, 11, -4,  2, -4,  0, -6, -6, -6,-14, -1 },
-    {-10, 28,  3, 12,  9,  3, 11,-28,  6,-11, -7,  4,  0,  7,  8, -9,
-       0, -6,  0,-16,  4,  7,  4,  4,  7,  3,  4, -7,  0, -3,-10,  6 },
-    {-11, 14, -2, 19, -1, -1,  7,  9, -2,-27, 10,-14, 15, -4, 12, -4,
-       2, -2, -6, 12, -6,  0, -5, -4, -5,  1,  3,-11,  5, -9,  3, -8 },
-    {-18,  7, 13, 16, -4,  3,  9,-10, 10,-10, -3,-22, -4,-12,  3,-16,
-       0, -3,-16,  8,-11,  1, 10, -7, 15,  3,  0, -1,-13,  8,  1,  6 },
-    {-20, 10,-10, 10,  8, -1,  6,  0, 16,-12,  9,-10, -1, -5, -4,-13,
-      13, 16, -8, 12, -2, 14, 18, 13,  0,-16,  2, -5, -5, -5, -4,  3 },
-    {-14,  5, -7,-17,  5,-13, 23, 20, -4, -1,  1, -6, 13,  5, -1,  4,
-     -14, -2, -7,  8,  3,  2,  2, -7,  2, -1,  4,  7,  3, -9, -1, -5 },
-    {-19,  3,-24,-28, -9, -7, 19,  3,  2, 19,  7,  5,-13,  8,-15,-17,
-       3,-11,  4, 13,  3,  2, -1, -3, -4, -4,  2,  0, -5, -6,  6,  2 },
-    {-17, 18,-30,-20, -2, -3,  1, 15, -1,-11,  6, -4, 11, 11, -4, -5,
-     -10,  0,  0,  1,  3, -7,  8,  2,  5,  1,  5, -5,  1,  6,  4,  1 },
-    { -6,  1,-30,-25, -1, -8, -2, -9,-17, 16,  3, -1, -2, -9, -6, -7,
-      -3, 12,  6, -4,-10,  0, 10, -8, -6, -5, -3,-11, -4,  0, -1, -3 },
-    { -1, -1,-34,-28,  1,-10,  2,  9,  4, 16,  2,  6, 14, 17,  0,  7,
-      -4,  4,  4,  4,  0,  1, -1, -5,  8,  1, -4,  1, -9, -2,  5,  6 },
-    {-11, 14,  1,-31, -7,-24,  9,  7,  6,  5,-13,  1, -1,  3,  4, -1,
-      -2, -8, -6,  3,  5, -4, -6,  7, -2,  5,  3,  3,  0,  0, -5,  2 },
-    {-25,  8,-11,-18,  1, -4,  8, -3, -4, 15,  6, -5,  8,  2,  3,  4,
-      -4,  5,  6,  8, -7,  6,  1,-11,-15,-13,  9, -4,-14, 10, 12,  7 },
-    {-20, 11,-15,-25,  3,  4, 18, 13, -4, -5, -9, -1, -5, -2, -2, -7,
-      16,  5, -4, -5, -7, -2, -3, -9, 11, -2,  0, -7,-17, -6,-11,  6 },
-    {-11, 18, -5,-20,-15, -3,  9, 11,-20, 12,  5,  5, 11, -3,  7,  1,
-      10, -6, -3, -3,  3,  3, 14, -7, 10,-17,  9,-11, -2, -6,  7,-12 },
-    {-20,  8,-14,-17, -9,-13, -3,  0,-27,-14, -3,-14,  4,  3,  6, -6,
-       7,  4, 23,  9, 11,  9,  3, -4,  9,  2,  4, -1, -6,  1, -8,-11 },
-    { -9, 14,  2,-37, -7, 13,  6,-11, -6,  9, 18,-11, -6,  2, 12,  4,
-      -1,  3,  1, -2, -2,  1, -9, -4, -2, -3,  3,  5, -6,  0, -2, -8 },
-    {-29,  8, -1,-13, -2,  8, 23,  2,-10,  7, 13, -6, -5, 11, 13,  0,
-     -10,-13, 11,-12,-10,  6,  4,  6,  4,  3,  6, -5, -9, -2, -1,  3 },
-    {-18,  6,-10,-55, -4,-11, -2,  0,  1, -3, -9, -6,  3, -2, -1,  6,
-       3, -1,  3,  1, -4, -7, -2,  6,  3, -2, -1, -3, -2,  0,  4,  1 },
-    {-14,  5,  3,-21, -8,-16, -4, -2,-11, 27, 15,-20,  3,  0,  1,  1,
-       2, -5, -5,  4,  1, -9,  5, -3,  3,  0, -4, -2,-11, -4, -3,  7 },
-    {-17, -1, -9,-17, -8,-18, 12,-13, -9, 13, -3,  3,  3, -3,  1, -2,
-       0, 16, -9,  6, 12,  9,  5, 11,  2,-15,  1, -4,-16,  7, -4,-12 },
-    {-18,  8, -6,-11, -8, -7, 13,  7,  1,  6,  8, -1, 21, -4, 14, 15,
-      18, -4, -3, 15,  0,  9,  4,  7,  3, -1,  9, -2,  0,  7, -8,  2 },
-    {-10,  7,-18,-29,  3, 12, 12,  9, 11,  4, -1,-15,  1, -1,  8, -2,
-      -2, 10,-15, -1,  0,  6, 12, -6, -1, 10, -6, -3,-11, -4,  9, -6 },
-    {-14, 14, -9,-21,-12, -2, -1, -7, -5,-10,  5, -8,  0,  6,  9,-11,
-      11, -3, -5,  3,  8, 15, -2, -4,-22,  4, -6, 12,  2, 13,  6, -7 },
-    {-12, 11, -5,-29,-25,  4, 12,-13,-11, -7,  4,  2,  2, -5,  5,  8,
-       7, -5, -5,  6,  3,-10,  1, -6,  6, -6, -5, -1, -2, -4,  7,  6 },
-    {-15, 11, -5,-16,  0,-13, 26,-23, -6, -3,  5, -2, -2, 21, -6, -3,
-      -5, -1,  6, -1,  0,-13,  2, -3, -9, -1, -4, -3,  5, -4, 12,-16 },
-    { -9,  9, -1,-17, -3, -6, 12,  6,-18, -2, 11,-14, -6,  3, 14,-12,
-     -11, -5, 14,  2,  5, -8, -4,-11,  2, -5, 16,  6, -7, -4,  8, 13 },
-    {-13,  5,  3,-28,-14,  0,  6, 23,  5,  4, -1,-17,  1, -3,  0,  0,
-       5,  4,  0,-18, 14, 10,  4,  2,  5, -2,  4, -3,  2,  0,  2,  0 },
-    {-15,  4,-13,-16, -3,-12, -2,  2,  7, 10,  9,  3, 11,  4, 23, 14,
-       9, 16,  4,  1,-12, -3,  4, -7,-15, -7,-10,-14, -6, -8, -1, -6 },
-    { -7, 10, -5,-10, -3,-13, 16, -1,-12,  7, -3,-12,  2, 13, 13,  2,
-      17, 15,-13,  1, -5, -2,  3, -1,  1, -3,  6, -3,-12,-16,  7, -7 },
-    {-11, -5,-12,-30, -6,-22,  1,  4, -6, -3, 12,  6,  7,  0, 16,  6,
-      -2,  0,-22, -2, -9,  2,-13,  8,  6, -8,  4, -7, -1, -6,  4,  6 },
-    {-14,  5,  1,-27, -4,  2,  1, 14,-11, -7, -8, -4,  1,  8,  0, -6,
-     -13, 11,-12, -7, -5,  1, 10,  7,  3, -2,  0,  6, -8,  2, 10, -1 },
-    {-10, 10,-25,-13,-20, -4, 19,  3, 13,  5,  5,  7, -8,  2,  4,  2,
-       3, -1, -1, -9, 14, 10,  9, 14,  3,  3, -6,  0, -5,  4,  1, -1 },
-    { -9, 15,-18,-17,  4,-11,  6,  7,-12,  8, -1,-11,  2,  3,  7, 16,
-      -3, -9,  7,-12, 23,  0,  6,  7,-14, -9,  8,  1, -2,  6, -2, -1 },
-    { -6,  9,-16,-26,-14,-11,  9, -6,  5, -2, 13, 17, 21,  7, 18,-19,
-       6,-23, -2,-15, -2,  2,-10, -8,  2,  1, -2,  4, -3, -4, -5, -4 },
-    {  0,  6, -5,-28,-17,-32,  2,-10, 11,  3, -5,  9, 10,  3, 11, 11,
-      -3, 12, -2,  2,  4, -6,  9, -4, -4, -4, -4, -9,  2,  0,  2,  4 },
-    {  0, -8,-18,-34, -9, -7, -4,-11, 10, 15, 11, -1, -8, 15,  6,-13,
-       9,  2, -4,-12,  0, -1, 19, 12,  6,  5,  0, -3,-10,-12,  3, -5 },
-    {-10,  6, -9,-17,-12,-11,  9, -6, 11, 11, 18, -7,  0, 16,  4,  2,
-      -6,  3,-12, -1,  0,  1, -5,-22, -2,-12,  0,  6, 17,  5,  5,  6 },
-    { 12, -5,  7,  1, -5, -2, -1,  2,  2, -4, -3, -3, -3, -2,-29, 11,
-       5,-13,-73, 24, 12,  4,-14,-10,  5,  1,  0,-11, -7, -7,  7,  3 },
-    { 10, -3, -1, -3,  4,-11, -5, -2, -8,  7,  9,  2, -8, -6,  6,  7,
-      21, 17,-54, 47,-14,-10, 14, 19, 13, 21, -4,  3,  1,  2, -4,  2 },
-    {-12,  4,-16,-12,  5, -9, -4, 19, -7,-22,-22,-17,  3,  0, -6,  8,
-      23, -4,-55,-28,  2,-26,  2,  1,  4,  0,-13,  6,  0, 10, -7,-11 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3, -1,
-      35, -1,-67,-35,-24,-24, -6,  2,  2, -2,  1,  3,  2,  0, -1,  1 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  5,  0,
-      41, -4,-73,-15, 18,  4, 17,  8, -1,-16, -1, -2,  1,  0,  0,  0 },
-    { -4, -4,  4,  6, -1,  2,-16,-10,-15,-10, 21, -2, -6, -2, 14, -7,
-      10, -5,-55, 34,-12, 11,-13, -2,  2, 28,-26,  0,  7,  4, 21, -7 },
-    {  2,  1, 15,-22, 10, -3, 14, -6, -2, 15, -2, -7, 20,  6,-15, -7,
-      23, 10,-60,  8, -4, 29,-22,  2,-13,  9,-10, 12, -1, -3,  4,  7 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1,  0, -1, -2, 11, -5,
-     -21,-11,-60,-27,-17,-39,  6, 36,  0, -8,  2,  2,  0,  0, -2,  3 },
-    {  2, -5,  9,-17, -1,  2, -3, -6,  8, 12,  7, -6,-33,-11,-14,-40,
-      10, 36,-46,  0,-19,  5,  0,-10,  3, 12, -6, -8,  6,-12, -7,  1 },
-    {  1,  1,  0,  0,  0,  0,  1,  0,  0,  0, -1,  0,  1,  0, -2,  0,
-       4, -2,-87, -3, -2,  2, -2, 20,  2,  6, -1,  6,  0,  0,  2, -1 },
-    {  1,  0,  0,  0,  0, -1,  0,  0,  0,  0,  0,  0, -1,  0,  0,  1,
-       1,  7,-76, 41, -7,-24,  0, -6,  3,  6,  0, -2, -1,  1,  0,  0 },
-    {  0, -3,  4,  2,  3,  2,  2,  0,  3, -1,  4,  0, -1,  4, -2, -4,
-     -32,-11,-64,-29, -9,-43,  2,-11, -1, -7,  0, -4, -2, -2, -2,  2 },
-    { 10,-20,  3, -3, 13, 13,  0, -4,  2,  7, -8,  7, -2,  2,-20,-20,
-     -19,  3,-47,-18,-16, -6,-15,-42,-17, 14, -6,  8, 12,-10, 11,-12 },
-    { -3, -2, -2, -1, -1,  4, -3, -1, -6, -2,  3,  2, -3,  6, -1, -9,
-      10, 13,-68, -9, 26,  3,  5,  3,-21, 10,-15, 21,-22, 19, 11,-14 },
-    {  1,  5, 18,-19,-29,-13, -2, 18,-10, 20,  2, 10,-10, 11,  1,  8,
-     -16,-17,-41, 10,-14,-25,  0,-14,-19, 17,  7,-12, 14,-11, 14,  5 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3, -1,-43,  5,
-       6,-12,-48, 19,  8,-38, -8, -3, 22,-21,-10, 15, 20, -9, -5,  8 },
-    {  0,  0,  0,  0, -1,  1, -1,  0,  0,  0,  0,  0,  0,  0,  6, -3,
-      22,-14,-71,-24, -2,-33, 23,  7, -8,  7, -3,  2, -4,  1, -8, -2 },
-    {  1,  0, -1,  2,  0, -2,  0,  0, -1,  0,  4,  0, 26, -1, 10,-11,
-     -17,-32,-58, 14,-14,-11, -2, 15,  2, -8, 12, 10, -9, 13,-33,-14 },
-    { 15,-17,-19,  7, -8,-15,-32,-22,  7, 12, 18,  0,  0,-15, -4, 16,
-      37, -2,-46, 11,  2, -8,-10, -8, 14,  9, -4,  5,  7,-17,  4,  3 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -2,  0,
-      -5,  3,-85, 23, -9,-17, -2, -2,  0,  0,  0,  0,  0,  0,  0,  0 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -2,  0,
-      -5,  3,-85, 23, -9,-17, -2, -2,  0,  0,  0,  0,  0,  0,  0,  0 },
-    {  1,  0,  0,  0,  0, -1,  0,  0,  0,  0,  0,  0, -1,  0,  0,  1,
-       1,  7,-76, 41, -7,-24,  0, -6,  3,  6,  0, -2, -1,  1,  0,  0 },
-    {  0, -3,  4,  2,  3,  2,  2,  0,  3, -1,  4,  0, -1,  4, -2, -4,
-     -32,-11,-64,-29, -9,-43,  2,-11, -1, -7,  0, -4, -2, -2, -2,  2 },
-    { 10,-20,  3, -3, 13, 13,  0, -4,  2,  7, -8,  7, -2,  2,-20,-20,
-     -19,  3,-47,-18,-16, -6,-15,-42,-17, 14, -6,  8, 12,-10, 11,-12 },
-    { -3, -2, -2, -1, -1,  4, -3, -1, -6, -2,  3,  2, -3,  6, -1, -9,
-      10, 13,-68, -9, 26,  3,  5,  3,-21, 10,-15, 21,-22, 19, 11,-14 },
-    {  1,  5, 18,-19,-29,-13, -2, 18,-10, 20,  2, 10,-10, 11,  1,  8,
-     -16,-17,-41, 10,-14,-25,  0,-14,-19, 17,  7,-12, 14,-11, 14,  5 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3, -1,-43,  5,
-       6,-12,-48, 19,  8,-38, -8, -3, 22,-21,-10, 15, 20, -9, -5,  8 },
-    {  0,  0,  0,  0, -1,  1, -1,  0,  0,  0,  0,  0,  0,  0,  6, -3,
-      22,-14,-71,-24, -2,-33, 23,  7, -8,  7, -3,  2, -4,  1, -8, -2 },
-    {  1,  0, -1,  2,  0, -2,  0,  0, -1,  0,  4,  0, 26, -1, 10,-11,
-     -17,-32,-58, 14,-14,-11, -2, 15,  2, -8, 12, 10, -9, 13,-33,-14 },
-    { 15,-17,-19,  7, -8,-15,-32,-22,  7, 12, 18,  0,  0,-15, -4, 16,
-      37, -2,-46, 11,  2, -8,-10, -8, 14,  9, -4,  5,  7,-17,  4,  3 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -2,  0,
-      -5,  3,-85, 23, -9,-17, -2, -2,  0,  0,  0,  0,  0,  0,  0,  0 },
-    {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, -2,  0,
-      -5,  3,-85, 23, -9,-17, -2, -2,  0,  0,  0,  0,  0,  0,  0,  0 },
-    { 16, 65, -2, -2,  4,  3,  0, -7,  3,  1,  3,  1,  0,  5,  1, -5,
-       0,  2, -1,  3,  0,  0, -1, -2,  6,  0, -2,  0,  0, -1,  1,  1 },
-    {  5, 37, -4,  8, -4, -1,  9, 17,  6, -7,  5, -1, 11,  6, -4,  7,
-      -2,  4,  1, -3, 11,  3,  3, -9,  6,  0, -2, -4, -5,  4,-12,-11 },
-    { 15, 24,-14,  2,  6, 17, 26,  5,  8, 11, -9, -7, -6, -8,  3, -5,
-       9, 10, -3, 10,  0,  1,  4, -9,  4,  9,  3,  0,  4,  0, -5,  3 },
-    {  9, 36, -9, -8,  7,  7,  4,  3, -1,-16, -2,  7, -5, -6,  6, 12,
-     -11,-12,  9, -1, -3, -9, 12,  6, -6,  2,  2,  5,  0,  5,  6, -6 },
-    { 25, 39, -5, 24,  3, 10,  3, -6, 13, -8,  3, -7,  2,-10, -5,  2,
-      -2,  3,  5, -2,  1,  5, -2,  3, -4,  1, -5, -4,  0,  1, -2,  0 },
-    { 16, 27, -1,  0,-14,  6,  4, -5,  7, -2, -6,  0, -3, -5,  2, -1,
-      -1,-19,  5, -8,  0, 11, 12,  5,  0,  3, 10,  6,-14, 14,-13,-15 },
-    { 12, 23,-14,  2,  1,  4, -3, 16,  7, -8,  2, -8,  8,  6, -8, -7,
-      -3,  0,  2,  8,-13,  7, 13, -6, -4,  6,-13,-16, 14, 11, -7,  5 },
-    { 16, 28, -7, -1,  6, -3,  9,  0, -7,  3,  0,  3,-12, 20,  8,  9,
-       8, 23,  8,-13, -2,  4,  9,  3, -5, 13,  5, -2, 12, 14,  5, -1 },
-    { 19, 37, 19,  5,  7,  5, 10,  5, 19, 10, 14,  0,  2,  5,  1, -4,
-      -4,  2,  2, -5, -2, -1,  2, -6, -4, -4, -5, -3,  2, -2, -2, -2 },
-    { 24, 21,  1,-11,-10, 17,-14, 14,  6, -1, -6, -1,  0,-13, -1,-12,
-      -2, -5,  6, -4,-12, 14,  5, -2, -8, -8, 15, -7,-30,-12,  4,  0 },
-    { 11, 26, -3,  3,  5, -1, -2,  3, -2, 10, 15, -4, 10,-28, 10,-17,
-      -8,  1,  2, -7, -1, -6,-15, -1,  4,  5, -7,  9,  0, -5, -4,  4 },
-    { 18, 32,  1,  2, -7,  4, 15,  2, -9, -2, 12,-11,  7, 11, 13,  2,
-       0,  5,  9,-10, 16,  3, -3,  5, -9,-23,  2, -2, -1,  5,  2, 11 },
-    { 35, 24,-20,  2,  4, -1,  5, 14,-10, -9,  8, -7,  0,  5, -7, -7,
-      11,  1,  5,  3,  2,  0, -2,  3,  0,  1,  4,  0, -2, -8,  0, -4 },
-    {  9, 35, -1,  2, -1,-19, -3, 12, -1,  8,  8,-13, -1, -2,  2,  5,
-      -8, -1, 13, -2, 11,  1,  0,-10,  0, -3, -7,  2,  1,-12,  3, 12 },
-    { 20, 27,-12,-12,  7,  4, -1,-13, -1, -9,  2, 13,-11,  5,  7, -9,
-       9,  1,  1,  8, -9,  0, -6,  7,  4,  2, -2,  7,  3, -2,  1, -9 },
-    {  8, 37,-20, -5,  0,-21, 10, -8,  3, 19, -9,  7, -3, -8, 10, -2,
-       0,  5,  6, -4, -2, -1,  0, -7,  6,  1,  0,  4, -5,  6, -8,  2 },
-    {  8, 27,  1, -3, -5,  1,  6,  0, 15,  2, 17, -1,  3,-17, 10,  5,
-       5, -6, -6,  6,-10, 18, -5,  0,  0, 13,  7, 10, -5, -6, -2, -4 },
-    { 14, 29,-20, -4, -3,  1, -5, -1,  2, 12,-10, -3,  4,-18,  4, 14,
-      -4, -1, -9, 15, -2,  2, -5, -3,  2,  9, -2,-14, -3,  4, -4, -7 },
-    { 23, 23,-23,-11, 27,  4,  4, -1,  7,  0, -5,  9,  2,-11,  3,  7,
-      -2, -5,  2, -7, -7, 13, -3, -6,  2,  3,  3, -4, -1, -8,  5, -2 },
-    { 16, 26, -6,  8, -9, -1, -2, -1, -8,  4, -2,  0,-12,  9, -1,  0,
-     -17, -9, 30, -5,-15,-16,-13,  0, 10,-11, -7, -3, -1,  0,-11, -2 },
-    { 12, 32, -4, -5, 10, 19,-10,  4,-12,  5, -6,  9,-12, -6, -6, -8,
-       4,  1,  3,  0,  8,  0, -3, -4, -7, -4, 10,  8,  6,  5, -1,  4 },
-    { 46, 42, -3,-14, -2, -6,  6, -2, -5, -1, -3, -3,  1, -1,  3,  1,
-       1,  4, -1,  2,  3,  1, -2,  6,  0, -1, -2,  4, -2, -1,  2,  2 },
-    {  9, 33,-13,  4,-11,  3, -8, 22, 12, -2,  4,  0,-16,  5,  4, -1,
-       7, -6, -9,  1,  7,  5,  0, -5,  5, -1, 10,  3, -2, -1,  3, -2 },
-    {  9, 30,  6, -3,  6,  1, -7,  5, 11, 14,  7,  1,  0,  2,  2, -1,
-       8,  7, -6,-13,-10, -2,  1, -6, 10,  7,  6,  5, -2, -5, -1,-16 },
-    {  9, 28,-11,-10,  9,-10, 15,  8,  4,  9, -4, -7,  0, -5,  9,  8,
-      -7,  2,-15,-23,  4, -4,  4, 16, -8, -3,  0, -8, 14,  5, -3, 15 },
-    { 17, 26, -5, -5, -1, -8, 20, 18, -7, -2,  4, -7, -8, -5, -4, 16,
-       0,  0, -7, -2,-13, -5, -2,  3, 12,  1,  3, -5,  2,  2,  0, -1 },
-    { 11, 37,  7,-23,  6, -1, 15, 13,  4, -9,  7,  5,  3, -3, -5, -8,
-      -2,  3, -5, -1, -8,  7,  2, 13,  1,  3,  0, -3, -1,  2,  0, -2 },
-    { 21, 33,  7, 20, 21,-10,  6, -5, -5, -6, -9,  2, 10,  0,  8, -4,
-      10,  2, -2, -2,  0,-10, -6, -2,  0, -5,  3,-11,  3, -9, -3,  1 },
-    {  6, 30,-15, -8, 16,  1,  4,  6,  4,  5,  8, -3,  8, -9, -1, -6,
-       8,  2, -2,  4, -2,  5, 11,-21,  3,-10, 16,-11, 24, 10, 14, -6 },
-    { 15, 36, -3, -9,-20, 12,  0, -7,-18, -4, -8, -9,  9, -7, -3, -1,
-       2,  7, -5, -8,  6,  2,  2, -1,  7,  1,  1, -3,  3, -4, -8,  1 },
-    { 16, 34, 21,  3, -9, 10,  7,  9, -7,  1, -4, -9, -4, -5, -5,  3,
-       3,-19,  1,  5,  4, -2, -6, -5,-10,-11, -8, -2,  2, -5, -8, -7 },
-    { 28, 29, -3, 18, -2,  0, -6, 12, -2, 10,-11, -4,-13,-12, -6, -4,
-       0,  4, -1, -8,  6,  4, 12, 11, 10, 10, -3, -6,  1,  2,  1,  7 },
-    {  3,  8, 22, -8,  3, 36, -8, -1,  9,  6,-13,-14,  8, -1,  1,  2,
-      -2, -8,  0,  3,  1,  2, -1,  5, -1, -8,  0, -2,  2,  2, -1,  1 },
-    {  0,  6,  0,  0,  4, 13, -7,-16, -6, 15,-14,-21, -9,-10,-10, -6,
-     -21,  5,  4,  2, 12,  4, 12, 11, -4, -6, -6,-10, -7,-18,  1,  4 },
-    { -1,  3, 10,  1, -1, 15,  4, -7,-16,  3,  0,-22, 10,  2, -3, -2,
-      13,  5, -8, 16, -5,  4,  0,-11,-10,-22,  0, -4,-17,  5,  2,  1 },
-    { 12,  8, -4, -9, 14, 40,-21,  0,  1,-15,-10,-12, 12,  6,-10,  2,
-       8,  6,-12,-10,-11,  1,  0,-11,  2,  1, 13,  0,  6,  3,  8,  4 },
-    {-10,  3,  5, -4, -3,  3,  0, -9,  2,  8,-22,-23, 17,  8,-17, -3,
-      14, -8, -4,  1, -8,  3,  0,  5, -1, -3, -2, -4,  1,-10,  0, -2 },
-    {  0, -1,  5, -7,  4, 12, -2,  0, -7,  2,-16,-15, 12, 21, -7, -4,
-       7, -7,-11,-15, -7, -9, -5, -8,  0, -6,  8, -3, -8, 22, -7, -9 },
-    {  7, 19,  4, -9, 24, 22,  2, -6,  8, 13,-14,-20, -4, 11,  8, -4,
-      -1,  2,  0, -7,  5,-17, -3,  3, -6,  5,  3,  4, -5, -7, -3, 14 },
-    { -2,  6,  2,  8, -2,  5, -4, -2,-10,  3,-45,-30, -3, -3,-12, -4,
-      -3, -3, -1,  9, -6, -6,  5, -4,  0,  5, -1, -2, -1,  0, -6, -1 },
-    { -3, 14,-16,-10, 10,  0, -2,-40, -9, 12,  2,-19, 15, -4,  4,  3,
-       3, -4,  7,  1, -4, -5,  0,  4, -1,  0, -9, -2, -4, -1, -2,  0 },
-    {  7, 16,  2, -7,  8,  2,  0,  1,  5, 21,-10,-26,  7,  2, -9, -7,
-      -3,-16,  8,  5,  5, -6, 10,  4,-14, -6,  5,  3, -2, -2, -4,  1 },
-    { -9, 14, -1,  3,  3, 11,  1, -5, -3, 13,-16,-18, 20,  6, -5,  0,
-      -3,  2,  8,  4,-19, -9, 12,  0, -8,  2,  2,  1,  6, 13, -7,-11 },
-    {  2,  5, 16, -4, 19, 15,  4,  0,-11,  7,-10,-10,-16, 18,-11,-12,
-      -9, -4,  7, -4, -4,-17,  1,  1, -8, -3, -3,  5, -2, -6,-11, -5 },
-    {  2, 12,  0, -9,-10, 14,  6,  2, -3,  2,-12,-28, 12,  1, -1,  2,
-       0, -3, -4,  7, 16,  5, -7,  8, -4, -3, -1,  3,-12,  4,-17, -5 },
-    { -4,  7, 11,  6,  1, 14, -4, -6,  5,  5, -6,-24, 23, -9,-15, 13,
-      -7, -9,-15, 10, -1,  8, -5,  1, 12,  6,  2,  0,  4, -2,  9,-10 },
-    {  1,  5, 11,  3,  6, 12, -3,  8,-21,  5, -7,-20, 12, -2, -9, -3,
-      17, -7, -8, -9,-14,  3,-13, 18, -8,  9,  2, -8,  4, -8, -5, -2 },
-    { -3, -3, -1,  5, -2, 15,  3,  2,  1, -8,  1,-39, -6, 13,-13,  0,
-      -2, -5, -6, -3,  0, -5, -2, 15, -9,  5, -3, -6, -2,  7,  0,-13 },
-    {  2,  8,  5,-12,-13, 22,  8,-16, 11,  5, -2,-32, -2, -4, 11,  5,
-       5, -6,  1,  3,  1,  5,  3,  6, -5,  4,  4, -8,  8,  4,  1,  3 },
-    { 13,  9,  5, -4,  9, 18,-11,  2, -1, 15,-10,-19, -2, 14,  0,-10,
-       1,  1,-18,  3,  2, -6, -8, 20,  7, -8, 16,  9,  9,-13, -3, -2 },
-    {-13, 11, 11, -9,-10, 13, -3,-18,  2, 10,  5,-21,  6, 15,-11,-21,
-       3, 14,  0,-12,  9, -1, -2, -4,  3, -3, -9, -8, -5, -2, -8,  2 },
-    {  3,  3, 11,  4,  0, 13,  1, -8, 10, 13, -6,-26,  2, 12, -3, -5,
-      12, -2,  1,  8, -7,-17,-19,  5, 10,  7, -3,  2, -3,  0,  5,  0 },
-    {  5,  0,  3, -3, -9,  5,-15, -5, -5, 17, -5,-31,  0, 13, 13,  5,
-      -1, -6,-14,  7, -8,  9,-14, -2,-16, -4, -4, -6,  6, -6,-10,  6 },
-    { 13,  3,  1,  7, -3,  4, -1, -2, -1,  4, -8,-32, -1, -4,  0,  3,
-     -10,  7, 10,-10,  4, -1,  6,  2,-16, -9,  4,  3, 13,-23, -3, -4 },
-    {  4, 11, -4, -9,  4, 11,-12,-12,-12,  6,  1,-28, -3, 14, 18, -2,
-     -12,  7, 15, -3, -5, -7, -3,  2, -6,  4,  4, -2, -5, -3,  2,-13 },
-    {  8,  7, -7,  0, 13,  7, -8, -7,  8, 36,-10,-22,  3, 23, -3,-10,
-      -3, 11,  1, -7,  3,  3, -1, -7, -4,  2,  3,  2,  5,  3, -4, -1 },
-    { -1,  1, 13,  1, -6, -1, -6, -9,-18, 17, -5,-37, -1, -1, -6, -4,
-       1, -6,-15,  2, 17, -9,  0, -3,  0,  4,  0, -5,  0,  4,  1, -5 },
-    {  0, 14,  5,  0, -7,  2, -6, 17, -6, -9,  7,-16, -5, 23,-14,-13,
-       8,-15, 11, 10,-11,-13,-33, -5, -2,  1,  6,  8,  0,-13, -9,  5 },
-    { 11,  7, -2, -8,  9, 11, 25,-14,  7,  3, -1,-33, 14,  8, -6,-19,
-       3,  3,  2, -1, -3, -1, -2,-10, -3,  1,  2,  1,  4,  2, -3,  4 },
-    { -2,  8,  4, -2,  9, 13, -4, -2,-15, -3, 19,-37,  9, 25, -9,  2,
-      -5, -2, -2, -4,  4,  2,  2,  0,  3,  3,  3,  5, -2, -3, -4, -3 },
-    { 10, 13, -1,-15,  4,  6,-18, -4, 25,  1,-23,-17, 15, 13, -8, -8,
-       7,  4, -5,  3,  6,  9, -7,  6,  0, -5,  8,  0, -6, -1, -2, -2 },
-    {  1,  3,  9, -5, 27, 15, -9,-31, -1, 23, -2, -9,  1,  8, -1, -7,
-      -2, -8, -4, -4, -2, -1,  3,  5,  0,  0, -1,  1, -7,  7, -3, -3 },
-    { -8,  7,  3, -6,  8,  3,-11, -2, 36, 14,  1,-30,  6, 10,-12, -6,
-      -6, -2, -4, -3, -5,  0,  9,  4, -5, -5, -8, 12,  4, -3,  1, -8 },
-    { -2,  9, 33,  0, 12, -3, -7, -4, -4, -1,  6,-25, 11, -6, -9,-11,
-      -2, -4, -2,  6, -1, -3, -6, 15, -6,  3, 10, -4,  1,  0,  5,  8 },
-    {-22,-21, -9,-19, -5, -7,-12,-15, -8,  9,-19, 14, -7, -4,  5, -8,
-      -2,  7,  1, -3,  4, -4,  6, 11,  2,  6, -3, -5,  2, -2,  0, -3 },
-    {-32,-13,  3,-24,  3, -8,  4,  1,-10, 14,-15,  0,  4,  6, -1,  6,
-       7, -1,  6,  4, -3,-17,  1,  4, -6, -1,  1,  0,  3,  3, -7, -4 },
-    {-32,-11,  7, -8,-12, 13, -5,-22, -4, 12,-16,  2,  0,  4,  0,  1,
-       0,  6, -5, -8,  2,  6,  5,  0, -3, -6,  5,  6,  5,  5, 13, -4 },
-    {-44,-33,  6, -4,  2,  0, -9, 10,  3,  4,  7,  0, -1,  7,  5,  1,
-       1, -3,  1,  6, -1,  0,  2,  3, -4,  0,  0,  1,  0, -1, -2, -1 },
-    {-30,-18,-24, -8,  5,  0, -2, 14,  7,  0,  1, 12,  6,  4, -9,  7,
-       5,  7,-11, -5,  1, -8, -1,  2,  2, -9,  7, -1,  7,  5,  6,  6 },
-    {-22,-20,-13, -9, 20, -3, 10, -8,  6, -4,  2, -7, 10,  8,  0, -1,
-       2, -3,  6,-19,  2,  4,  3,  3, -7,  2, -1, -6,  1,  1,  6, -2 },
-    {-27, -8, -1,  3, -1,-11, 24,  4, -1,  1, -8,  8,  5,-11, 15, -3,
-     -15, -1, -1,-13, -1,  1, -5,  5,  2,  3, -9,  0,  4,  3, -7,  6 },
-    {-33,-16, -1, -8, 10,-23,  6, 13, -1, -3, -9,  0,  5, -7, -5,-12,
-      -2,  3,  3,  6, -2, -3,  2, -3,  9, -6, -3, -2,  0,  5, -3, -4 },
-    {-22,-17, 11, -3,  3,  1, -1, -5, 17,  2,-15, -2, 10, -9,  6, 14,
-     -16,-12, 20, -1, -7,  6, -3,-12,  1, 10,-10, -1,  7, -3, -1, 10 },
-    {-28,-13,  1, -3, -1, -1,  0,  3,  3,  5,  1, 10,-10, -3,  7,  2,
-       4, 19, -1, -1, 10,  5, -8,  1, 11,-15, -4, -3, -5,  4,-13,  3 },
-    {-22,-13, 42,-20,  5,-13,  7,-11,  1,  1, -1,  1,  6,  3,  6,-11,
-       3,  3, -2,  0, -4,  4, -3, -1, -5,  2,  0,  0, -9, -1,  4,  4 },
-    {-26,-15, -2, -6, -4, -2, 16,  8, 21,  8,  1, -3,-10,  7, -8,-12,
-      -5, 12, -9,  3, -2, -3, 18,  1,-12,-15, -4,  5, -3,  0, 12,  7 },
-    {-26,-16,  5,  6, 14, -3, 15,  6,  1, -7,-13, 16,-15,  5, 11, -2,
-       9, -7, -4, -2,  0,  0, -2,  7, -8, -6, -5,  2,  7, -3,  2, 12 },
-    {-31,-17, -8,-30,  4, 14,  6, -6,  6,-11,  0,  3, -4,  0,  0, -4,
-       0, -4,  1,  4,  3,  4,  0, -5,  3,  2,  2,  0,  2,  1,  3,  5 },
-    {-61,-10,  4, 10,  4,  7,  0, -3,  0,  1,  0, -3,  0,  1,  0, -2,
-      -1,  1,  2, -2,  4, -3,  1,  1, -1,  1, -2, -4, -4,  4,  0,  0 },
-    {-28,-13, -8, -4,  3, -3,  2,  1, 11, 14,  3,  9,  1, 13,  3,  5,
-      -3, -2, -2,-12,-14, -9,-11,-15,-12, -5, -4,-12,  3, -3,  0, -5 },
-    {-41,  0, 12,-24, 13,  4,  5, 16, -5, -4,  0,  0, 13, -4,  1, -9,
-       9, -6, -1,  6, -2,  5,  2,  9,  6, -9, -8,  8, -2, -3, -6, -4 },
-    {-26,-19, -2,-15,  4,-14,  6,  0, 26, 20,  8,  9,  9,  3, -4, -5,
-      -8,  1,  0, -1,  5,  9,  3,  4,  4,  7,  1,  3, -2, -2,-10,  0 },
-    {-29,-18,  9, -4,  1, -5,-14,-12,  5,-10, -5,  4, -5,  0, -1, -1,
-       4, -5,  7,-16,-11,  2,  7,-15,  2, -4,  6, -4, -6,  7, -3,  7 },
-    {-27,-16,  9,-14,  3, -8,  9,  0,  7, -4, -3, -7,  0,-10, -1,  2,
-       1, -2, 15,-10, 14,  7,  6, 17,  3, -4,  3,-10,  8, -8,  3, 11 },
-    {-21,-20, -8, -8,  4,  5, -3, -2,  0, -5, 14,-10, 11, -4, 13,  0,
-       5,-11, 19,-18, 18,  3, -5, -3, -4, -8, 11,-10, 10,  3,  4, -9 },
-    {-35,-15, 13,-12,  4,  0, -2, -4,-12, -3, -8,-24, -7,  1,  7,  8,
-      -3,  0, -2, -1,  3, -2, -2, -6,  8,  1,  0,  1, -6, -1,  2, -6 },
-    {-19,-14, 13,-10,  9, -1,  1,  3,-12,  5,-16,  7, 13,  9,  4, -4,
-       6, -5,  4,  9, -3, 17, -4, 12,-11, -6, -5, -6, 13,  2,  7, -9 },
-    {-34, -8, -4,  1,  2, -1,  3,  6,-20,-11,  8, -1,  4,  2, -9,  4,
-      -4, -5, 16, 10, -4, 14,-13,  1, -6,  0,  2,-10,  0, -3, -3,  7 },
-    {-36,-10, -8, -3,  2, -2, 14, -4, -1, -7, -4, 10, -1, -3, 15,-11,
-       0,  2,  3, -1,  4,  0,  8, -1,  0, 18,-11, -5, 15, -5, 13,-12 },
-    {-22,-13, 14,-20, 15, 25, 16, 10,  8, -2,-10, -5, -1, -8, 11,  8,
-      -1, -2, -4,  1,  2, -1, -7,  0,  0,  0, -3,  0,  2, -1,  0,  2 },
-    {-31,-22,  7,  6, -2,  5,-20, 14, -6,  7,  0, 14,  3, -7,  3, -6,
-      -2,  1, -3, -5,  1,-10,  1,-24,  6, -2,  3, -7,  1, -7,  8,  7 },
-    {-25,-20, -3, -9, 10,  6, 12,  7,  5,  4, -3,  6, -1, -5, -6, -8,
-       3,  5,  6,  5,-10, 10, -4,-15,-15, -2, -9,  2, 18,  1,  8, 12 },
-    {-24,-19, -2, -4, -7, 11,  6,  9, 16,  2, -7, 18,  6, -7,  6,  6,
-      -2, -9,  3, 12, -2,  3, -1,  6,  7,  8,  0,  8,-11,  8,  4,  2 },
-    {-26,-20,-12,-12, -2, -3,  1, -5, -1, -2,  0,  3,  7,  9, -2,  2,
-       9, 22, 13,  4, -4, -1, -2,-14,  5, 15, -8, -5, -7,-11,-14, -6 },
-    {-21,-18, -1, -4,  0,  3,  7, -2, 10,  8, -8, -1, 15,  1, -9,  3,
-       1,  3, -5, -2,  2,  4,  0, -1, 10,  2,-19, -8,  8, 30, -7,  8 },
-    {-25, -6, 26,  4, -8,  4, -2, 21,  5, -4,-16,  5, 13,  4,-10, -1,
-      -6, -2,  2,-10,-13,  1,  3, -3, -6, -8,  2, 11,  1, -7,  0,  5 },
-    {  0, -1, -2, 19,-12,-48, -6, 11,  8, -2, -4, -2, -7,  5, -3,  2,
-      -2, -1, -1, -7,  0, -3, -3, -4, -4,  4,  1,  3, -3, -1, -2, -5 },
-    {-11, -8,-28, 18, 16,-24, -8, 19,  4,  8,-12,  9, -4, -2,  4, -7,
-       6,  2,  3,  3, -4,  0,  1, -6, -4, -2,  2,  6,  0, -3,  1,-16 },
-    { -9, -5,-26,  7, -3,-37,-16, -2,  2, -7,  4,-13,  0, -4, -6, -5,
-      -6, -4,  0,  3,  4, -3, -4, -4,  4, -3,  9, -4, -2,  2,  7, -4 },
-    {  2,  9,-18,  7, 29,-24, -1,  7, 14, 10,  3, -3, -2, -5,  6,-10,
-      -6, -3, -8,  0,  5,  1,  4,  3,-12,  2,  6,  1,  3,  4,  1, -3 },
-    {-20,  2,  8, 20, -9,-24, -4, 18,  3, 11, -1,-11,  6,  9, -1, -3,
-       1, -1,-15,  3, 15,  9,  3,  2,-13,  2, -8,  8,  1, -1,  1, -8 },
-    {-12,  5,-11,  6, 19,-26,-17, -6,  4, 14,  6, -8,  9,  5, -6, -5,
-       2, -1, 20,  1,-11,-10,-18, 20, -7,  0, -3,  4,  2,  0, 10,  4 },
-    {-15,  1, -2, 13, -8,-21,-22,  4,  4,  3,  3, -7,-31,  4,-10,-14,
-       0,  8,  4,  5,  8, 11,  2, -8,  6,  7,  0, -2,  6,  8,  8,  7 },
-    {-13,-10, -9, 12, 19,-16, -3, -2,  9,  2, 11,-29, -1,  9,  4, -3,
-       1,-10,-10, 16,  1,  7, -7, -6, -4, -1, -5,  3,  6,  0,  3,  1 },
-    {-17, -1, -5, 19, 12, -9,-21, -5,  2, 12, -7, -7, -3,  8,  7, -2,
-       6, -9, -9,  1, -4,  1,  1,  3,-14,  2, -8,  0, 10,  1,-12, -6 },
-    {-13, -5,  8, 15,  0,-20, -2, 20,  8, -8,  8,-19, 12, 10,  2,-11,
-       0, 12,  1,-11,  0,-11,-15,  5,-11,  2,  4, -4,-11,  5, -4, -5 },
-    {  3,-11, -7,  8,  0,-17,-26, 15, 19, -7, 10, -9, -5, -5, 14,-25,
-       0, -8,  2, -9, -3,  9,  1, -6,  4, -4,  3, -9, -1,  6,  2,  2 },
-    {-12,  5,  5,  9, 14,-18,-19,  4,  2, 16, 14,-21,-15, -9, -1, 16,
-      12,-11,-10, -5, -7,  4, 15, -8, -5, -1,  1, 14, 13, -7, -1, -4 },
-    {-10, -5, -1,  8,  7,-23,-10, 14,  6, 11, 10,-16, -3, 16,  6,  0,
-       0,  9,  6, -2, -7,  1, 22,  5,  3, -8,  0,  3, -2,-10,  3,  0 },
-    { -2,-14,  2, 16, 15,-17,-17,  6, 19,  4,-10,-15, -1, 15, 11,-14,
-      -8,  5,  8,  8, -2, -8,-11, 10, 10, -8,-14,  2, 13,  4, -2,-12 },
-    {-10,  3,  6,  4, 19,-23,-19,  1,  4, -9,-30,  3, -6, 18,  0,  2,
-       0,-11,  0,  3,  7, -2,  8,  5,  2, -3,  6, -9,  1, -4,  7, -6 },
-    {  9,  5, -2, 21, 20,-33,-13,  7,-10,  8,  8,-15, -6, -4,  1,  5,
-       3,  7, -2, -9, -1,  4, -6,  1,  0,  9, -1, -5,  2,  1, -3,  3 },
-    { -9, -3,  3, 15, -3,-30, -7, -7,-25,  6,  2, -6,  1, 19,  1,-12,
-       1, -8,-13,  9, 13,  1,  8,  2,  5, 15, -2,  3, -9,  0, -4,  4 },
-    { -6,-12,-17, 25, 22,-13,-10,  9,  2, 11, -7,-16,  4,  6,  1,  0,
-       0, 18, -4, -5,  4, -2, -1, -5,  0, -4,  6,  1,  6, -1,  7,  0 },
-    { -1,  0,-10,  8,  8,-27,  0, -2, 29, 16, -2, -4,  9, -1,  2,  0,
-       6, 10,  6,  4,  2, -7,  9,-18,  3,  3,  3,-10, 17, 10,  9, -6 },
-    { -3,-12, -6, 11, 20,-32,  5, 21,  3, -4, -9,  2,-10,  1,  7, -4,
-       5,  0,  0, -1, -8, -9, -7,  4,-10,  5,  0,  2, -5,  4,  9,  1 },
-    { -5, -1, -5,  1,  2,-19,-13,  1,  6, 12,  2,-16,-17, 11, 10, 13,
-      16,-12,-11,  3, -6,  0,  6,  4, -3,  1,  8,  2,  5,-11,  3,-14 },
-    {-19,  5, 10, 11,  2,-23, -9, 16, -2,  7,  0,-11, -7, 10,  6, -7,
-      26,-15, -4,  8,  6, -4,  7, -9,-15,  1,  8, -4,  4,  2,-12, 16 },
-    {-11,  1, 11, -4,  1,-31,-13, -1,  8,  5,  4, -2,  0, 13,  7,-17,
-       7,-10, -6,  1,  4, -1,  2, -9, -4,  9,  3,  3, -4, -5,  3,  4 },
-    { -3,  1, 10, -1,  0,-15,-22,  4, 40,-11, -4, -3,-14,  9, 11, -1,
-       9, -1, -6,  6,  3, -6,  0,  0,-12,  7, -2,  0,  9,  3,  1,  3 },
-    { -1, -1, -1, 14,  8,-24,-14, -8,  5,  8,  5,-12,-17,  8,  2,  7,
-      10, -8,  0,  4, -6, -6,-10,  8,  4,-12,  3, -9,-12,  5,  4, -3 },
-    { -5,  1,-11,  8,  9,-24,  0,  2,  2, 14,-12,-13,  1,  6,  7,  0,
-       7, -6,  9, 26, 11,-14,  8, 10,  1,  9,  0, 11, -2,  6,  2,-10 },
-    {-13,  1,  4, 34, 19,-17,-15,  0,  3, -2, -7, -1,  0, -3, -3, -1,
-       1, -1,-10,  8,  5,  0, -8,  4,-17,  9, -2,  0,  0,  6,  2, -3 },
-    { -6, -4,  1,  2,  2,-14,-29,  0,  9, 34, -3, -5,-14,  6,-10, -9,
-      -5, -1,  0,  3,  3,  0,  1, -1, -2, -1, -1, -3, -3, -4,  3, -3 },
-    { -4,  6,  3, 14, 14, -8,-29, 31, 11, 14, -4, -5, -6, 10,  6, -9,
-      -1,-11, -7,  1,  7,  4,  1, -6,  4,  0, 10, -7, -5, -1,  2,  4 },
-    { -4, -4, -2, 14,  6,-32, -6,-14, 14, -5,-11, 10,-18, -4,  6, -8,
-       9,  5, -4,  1, -4,  5, -2, -9,  3,  5,  2,-10, -6,-17,  3, 17 },
-    {-16,  9, 21, 19,  4,-20,-17, 14,  9, 15, -6,-17, -1,  1,  6, -3,
-       1,  1,  8, -3, -6,  6,  9,  4,  9, -9, -5,  1, -1,  0, -1,  2 },
-    { -7, -5,  3, 19,  1,-20, -9, 14, 21, -7,-18, -9, 26, -7,-17, -7,
-      12,  6,  0, -9, -6, 14,  9, -9, -8,  4, 15, -7, -9, -1,  9,  1 },
-    {-20, 30, -6, 11, 24, -4,  0, -6, -2,  8, -4, 12, -8,-17,  0,  5,
-      -4,  1, -1,  3, -3,  5,  3,  3,  7, -2, -3, -2,  4,  0,  0, -1 },
-    {-35, 17,  6,  1, -9, -1,-16,  3,-20,-13,  8,  7, -4, -7, -4,-20,
-       7, 12, -5,  5, -5,-11, 12, -1, 15, -9, -6, 16, -4, -9,-13,  4 },
-    {-21, 36,-19,  9,  0, -7, -8,  9, -4, -3,  3,  0,  7, -8, -2, -2,
-     -11, 13, -1,  5, -3,  7,  2,  3, -1, -2, -5,  1, -1, -2, -5, -3 },
-    {-12, 33, -4,  1,-12, -9,  0,-13, -1,  2, -8,  4,-10,  6,-16, -7,
-      -1, -4,-10, 15, -1,  0, -5, -8,  5,  5, -3,  0,  2, -7,  1, -7 },
-    {-14, 32,  5, -7,-15,  3, -5,  8, 14,  5,  9, 13,  3, 18, -3,  7,
-       4,-10,-10, 10, -1,  2,  0, -2,-11,  5, -3, -4,  2,  2,  7,  4 },
-    {-14, 34,  1, 20, -1,-12,  0, -3, -7, -4,  7, 18,  9, -3, 14, -7,
-      -9,-20, -7, -4,-13, 12,  1, 12,  5, -6,  2, -4,  0,-15,  1,  3 },
-    {-21, 23,  7, -8,  3,-13, -3,  0, -6, -2, -7,  6,-12,  9, -6, -2,
-      -2, -4, -1,  6,  9,  5, -9, 15,  0,  8, -8,  7,  6,-15,  3, -5 },
-    {-27, 32, -1, -4, -2,  4,-10, 12, -3,  8, 13,  7,  0,-15,  4, -2,
-       3,  5,  7, -4,  9,-12, -1, -2, -1, -4,  0, -4,  2, -5,  6, -6 },
-    {-17, 29, 15,  0, -1, -4,-10, 13, 12, -1, -8,-10,-10,  4,  7, -2,
-       6, -5,-13, 19,  6,  1, -7,  2, -9, -2, 12, -4, -8, -3,  2,  4 },
-    {-38, 27, 16,-15, -6,  3, -7, -4,  0, -1,  6, -2, -3, -6,  6, -6,
-      -3,  0,  2,  0, -4,  6,  1, -1,  0,  4, -1,  3,  4,  1, -2,  5 },
-    {-33, 40, -4,  2,  1,  0,  0,-10,-14,  0, -7,  4, -1,  3, -2,  5,
-       7,  6, -1,  4,  1,  3,  1, -7,  1, -4,  5,  7,  0,  4,  3, -4 },
-    {-20, 25, 12, -4, 16, -4,  2,  2,-14, -2, -3, 29, -1,  1,  3,  1,
-       9, -5,  2, -8, -3,  1, -7, -2, -7,  1,  0,  4, 16, -2, -1, -1 },
-    {-10, 30, 17,  3, -5, -2,  0, -5,-22,  4,  5,  5, -3,-18, -6, 10,
-      -5, -7,  2,  8,  7, -7,-11, -2,  0, -3,  3,  2, 11, -4,  4, -4 },
-    {-11, 30, 11,  4, -3, -8,  1, -2,  4, 18,  3,  1, -1,  0, -8, -4,
-      -3, 10, 13, 14,  5, -5,  1,  1,-10,  2, 15,  4,  9, -1, -5, -3 },
-    {-17, 32, 18,-18, -3, -5,  6, 10,  1,-15, -5,  9,  8,-12,-10, -6,
-      11,  9, -5, -8, -7, 10,  5,-10,-14, -4, -3,  1,  9,-11,  2,  1 },
-    {-13, 28,-11, -1,  2,-16, -2,  7,-24,  0,  3,  6,  3, -1, -8, -7,
-     -12,  2,  2,-20, 10,  4,  0,-13, -2, -2,  1,  8,-14,  0,  4,  1 },
-    {-14, 23, 12,  8,  8,-26,  2, -4,-14, 13,-14, 15,  3, -9, -1,-13,
-     -10, -2,-10,  6,-16, 12,  8,  0,  9,-10, -7, -4, -4,  7, -8,  8 },
-    {-20, 45, 10,-14,  4, 16,  8, -9,  1, -8, 10,  5, -7, -2,  2, -5,
-      -1,  0, -5,  4, -6, -2,  4,  1,  3,  4, -4,  2, -2, -2,  5,  1 },
-    {-20, 26, -4,  1,  7,  4, -8,  1, -5,-13,  2, 13, -7, -3,  6, -6,
-      22,  0,  5, 11, -4,-11,  8, -9,  2, -2, -4, -2,  2,-13, -4, -8 },
-    {-28, 18, 17,  3, -8,-23,-16, -6,  5,-10, 14, 10,  5, -1, -8,  4,
-      -2, 13, -3, -2,  3,  4,  3, -2, -3, -4,  0,  1,  3,  4,  0,  4 },
-    {-12, 32, -6,-16, 18, 12,-16,  0,  7, 13, -4,  5, -8, -1, -3,  4,
-       6, -2, -1,-13,  4, -1,  3, 12, -3,-10,  1,  6,  8,-11, -2,  4 },
-    {-18, 26,  2,  5,  0, -9,-17, 14,  5,  1,  7, -3, -8, -3, 11,  7,
-      -5,-12, -8,  7,  0, -7,  2,-12, -9, 13,-11,  9,  6,-11, -5, 11 },
-    {-24, 22,-15, -9,  8,  1, -7,-12, -9,  3, 11, 15, 14,-11, 12,-15,
-      -5,  7, -2,  0, -8,  3,  3, -1,  2, 11,-11, 14, -6, 13,  1, -6 },
-    {-20, 28, 18, -4, -6, -5, 12, 14,  2, 10,-13, -6, -8, -6,-13, -1,
-     -26, 22, -3,-14,  6,  0, 10,-15,-13, -9,  6, -7,  1, -5, -4, -1 },
-    {-19, 26, -8, -3,-14, -6, -9, -4, -8, 15, -8,  3,-12, -4, -2, -7,
-      -5,  3, 13, -3, -4,-25,  4, -1,  5,-12, -1,-13,  5,  2,  0,  6 },
-    {-18, 43, 14, -8,  1,-23, -2, -2,  1,  3, -7,  0,  0,  8, -1, -3,
-      -5,  1,  5,  2,  0, -2, -2, -2,  1, -1, -1, -7,  0,  3, -3,  9 },
-    {-11, 30, 10,-14,  3,  1, 10,-11,  1, -7, -4, 14,  2,  1, -9,  1,
-     -11, -2, -7,  5,-11,  1,  3, 14,  1,-16, -8,  3, -5,  7, -4,  4 },
-    {-18, 24,  6,  3,  8,  7,-22, -7, -7,  3, -8,  4, 23,  9,  3, -1,
-       3,  6,  7, -1, -7,  6,  4,  1, -3,  1, -6, -1,  2, -7,  3,  3 },
-    {-15, 38, -7, -1,-11,  2,-17,-24, 24,  8,  7, -4, -5,  2,  2, -7,
-       1,  4,  0, -9,  5,  0, -1,  1, -1, -5, -6,  3,  0,  7,  8, -3 },
-    {-14, 22,  1, -5,  9,-12, -9, -5, -6,  5,  7,  8, -1, -4, -9, -3,
-     -33,-16, -9, -1, 12,-11, 17, -7, -3, -1, -7,  3,  2, -3, 16, -4 },
-    {-14, 20,  6,  4,-10, -4, -4, -4,  1, -7,  2,  6,  8,-12,  4,  1,
-      -1, 12, 10,  3,-14,-10, -3, 18, -2, 33, -5,-17, 17, -5,  9,  7 },
-    {-12, 23, 13,  0,-11, -8,-11, 12, -5, -9,-16, 11,  6,  4, 12, -5,
-       5,-13,  7,-12, -3,  1,  2, 12,  1, -4, -1,  5,  4, 11,-12, -3 },
-    { 15,  2, 14,  7,  1,  2,  1, 12, 10, 23,  4,  6,-20,-10,  4, 26,
-      -6, 13,  4,  3,  2,-11,  5, -7,-10,  4,  9,  1, 10, -4, 11,  4 },
-    { 17, 15, 31, 17, 18, 16, 11, 24,  2,  4,  2,  3, -8, -3,  7, -3,
-      -5, -7, -2, -6, -4, -5, -4, -1, -4, -2, -5, -6,  2, -1,  4, -2 },
-    { 16,  8, 15, 14,  3,  7, 21,  9,  8, 15, 21,  6,  8, 12,  5, -5,
-       7, -3, 10,  2, -3,  8,  6,  0,  5,  5,  6, -3,  2,  4,  0, -5 },
-    {  5, -4,  6, 12,  6, 13, 24, 17, -5, 17, -1, -6, -7,-10, -8,-18,
-       3, -2,  2,  7,-15,-11, 12, -3, -2, -2, -4, -7,  2,  0,  5,  5 },
-    { 10, -6,  8, 11, 12, 20, 22,-11, -3, 15, -3, 15, -2, -2,  0,  2,
-       5, -8,  4, -5, -9, -4, -1,  2, -1, -3,  1,  3, 13, -1,  9,  7 },
-    { -5,  8,  5, 11, 14, -5, 14, -9,  2, 35,  8, 15,  1, -2,  2, -2,
-       4, -9, -3,-14,-12, -2, -2, -4, -2, -8, -3,  1, -6,  3, 10,  0 },
-    { 16,  0, -6, 15, -3,  4,  4,  3,  3, 20,  5, -4, 10,  9, -9, -3,
-     -10, -2, -7, 11,-11,-10, 17, -1,  3,-15,  2,  9,-15,-10, 16, 10 },
-    { 14,  4, -7, 19,  3,  0, 19,  8, 16, 34, -9,  6,-13, -1,  6,  5,
-      -1, -2,  4,  3,  2,  1,  1, -1,  0, -7,  2, -1,  1,  0,  6, -1 },
-    {  1,  6,  9, 13,  9, 10, 15, 16, 10, 18, 13, 17,  3, -1, -7,  2,
-     -15,-11,-10, -4,-13, -6,-17,-13, -6,-14,  1,-10,  6,  4, -1, -1 },
-    { 13,  1,  7, 10, 14, 13, -7,  5,  5, 28, 14, 14, -2,  2,  3, -3,
-     -13, -4, 10, -9, 19, -4, -3,  4, -5, -5,  0,  5, -5,  0,  3, -4 },
-    {  1,  0,  6, 22,  9, 18, 18, -3,  5, 10, 12, -2,  1, -3, -8,-12,
-       9,-10, -7,  1, -1, 19,  0,  2, -8,-11,-10,  9,  6, 11,  0,  3 },
-    { 10, 11, 19, 44,  0, 14,  1, -7,  6, 22,  2, -1,  9,  2,  0, -4,
-       4,  0, -6, -6,  3,  0,  0, -2,  2, -5,  1, -2,  0,  1,  1,  1 },
-    {  5,  7,  0, 32, 30, 26,  5,  4, -7, -3, 15, -6,  3,-10,  7,  6,
-      -8, -7,  2,-13, -5, -1, -3,  7,  3, -2, -8,  0,  6,  4,  5,  0 },
-    {  9,  8, -2,  4,  2, 11,  4, 29, -5, 14,  8, -5,-14,  8,  0,  9,
-       8,-10,  5,-15, -6, -9,  9, -1, 18,-16,  9,-21, -3,-13, -2,  8 },
-    { 25,  7, -9, 23, 20, 18,  6, 16, -9,  8,  8, -5, 11, 13, -8,  7,
-       4, 10, -2, -1, -7, -9, -7, -9, -4,  1,  1, -5,-10,  8,  4, -5 },
-    {  9,  2, 16, 14, -5, 14,  1,  0,-21, 17, -1,  9, 12, -3, -3,  4,
-      -4, 14, 10,  3,  0,-10,  7,  4,  4,-11,  2,  4, -1, -3,  9, -1 },
-    { 17,  8, 11, 26, 15, -3, 14, -1, 12,  9, 10, -8,  8,-18,-11, -3,
-     -14, -7,  7, -3, -3, -4,  1, -7, -3,  2, -3, 16, 10,  0,  9,  6 },
-    {  9,  8,  3,  8, 18, 14, 11,  1, 10,  6,  1, -4,-16, -2, 14, -2,
-       1,  8, 12, 14,  3, -3,  8,  8, 12,-15,  3, -3,  3, -2, 14, 10 },
-    { 22, -3,-11, 13, -7, 11,  4, 11,  3, 14,  0, -6, -2, -9,  4,  2,
-      -2,  0, -5,-27,-10,  3, -1,  5,  8,-24, -3,-11, -3,  2, 11, -1 },
-    { 19,  2,  8, 36,  5, -6,  3, 15, -3, -4, -5, 14,-10,  1,-12,-10,
-      -3, -4,  3, -2,  1, -8,  4,  3,  5, -3,  0,  4,  8, -2,  8,  4 },
-    {  8, 14, 15,  9, -4, 10,  5, 11,  9, 10,  8,  9,-15, 15,  6, -8,
-     -10,-13,  5, -8,-20,-13, -6,-11, -1, -3, -6, -4, -1,  0, 13, 15 },
-    { -2, -1,  9, 12,  2,  2, 13,  3,-23, 33, 15,  2, -4, -1,  3,  8,
-       8,  6,  6, -7,  8,  6,  9, -1,  3, -8,  0, -4,  1, -8, 11, -1 },
-    {  6,  5, -6, 16,  2, -3, 31, 21, -9, 12,  0, -1, -4,  1,-12,  3,
-     -13,-18,  2,-11, -9,  2, -8, -6, 11, -3, -1,  0, -1,  0, 13,  5 },
-    {  5, -1,  2,  0, 25,  5, 10, 16, -5, 21, 14, 12, 13,  2, -5,  5,
-       5, -3, -2,-14,  0,-12,  7, 11, -1, -7, 19, -1, -1, -1,  8, -1 },
-    { 10,  7,  3, 11,  0,  8, 22,  3,  3, 19, -4, 12, 15,  9,  5, 15,
-       2,  1,  2,-10,-10,  0,  2, -1,  0,  1,-12, -1, 21, 16,  9, -7 },
-    { 11, -4, -5, 24, -7, 11, 20, 11,-15, 18,  5,-13,-15,  0, -5,  9,
-       1,  0, -1, -9,  4, -8,  6, -8,  1, -2, -7, 20,  9,  3,  9,  3 },
-    { 20,  0,-12, -6,  9, 31,  9, 12,  8, 27, 15,  7,-16,  5, -3, -7,
-      -1, -9, -2, -7, -3,  4, -8, -3,  3, -6, -2, -2, -3, -6, -1,  2 },
-    {  6, -6, 48,  8, -3, 19, 12, 11, -7,  2,  3,  0, -1,  1,  8, -4,
-       4, -6,  0, -4, -4, -3,  3,  6,  3,-13, -8,  5, -3, -7,  8,  5 },
-    {  7, -2,  6, 11, 12,  2, 14,  4, -5, 12,  2,  9,  4,  2,  0, -1,
-       2,  0,-15, -9,-16, -2,  8,-17, -5,-22,-19, -5, -1,-10,  1, -2 },
-    { 11, -9,  3, 12,  6,  6,  1, 17, -6, 19, 14,  7, -7, -1, -1, -9,
-       9,-11,-17,  0, -6, 16,  0,  1,  9,-24,  3,  3, -9, -3,  3, -2 },
-    {  9,  0,  1,  8,  1,  7,  2, -5, -3,  8, -1,  7,  2,  6, -3, -6,
-       5, -2,  6, -2, -4, -3,  0, -3, 13,-50,  1, -2,  2,  4,  4,  3 },
-    {  7,  0, 26, 21, -4,  2, 17,  8,  7, 11, -7,  1, -1,-15, -1,-15,
-     -11, -4,-17, -4,  1, -7,  3,  6,  3, -9,  2,  3,  6, 10,  6, 12 },
-    {  1, -2,  2, -1,-10, -4,  6, -3, -5, -2, -8,  2,  2,  2,  8,  0,
-       1,  1,  6,  0, 11, 13,  3,  4,  0,-12, 11, -5, 19, 20,  2,  5 },
-    {  5,  3,-13, -2,  1,-12, 11, -7,-12,  7, 10,  0,  7,  0, -2,  4,
-      -6, -9,-11,-12,-23, 12, 10, -3,  0,  6, 19, -1, 24, 18,  9, 12 },
-    {  6, -3,  2,  5,  2,  2, -2, -5, -8,-11, -4,  3, -8, -4,  5, -3,
-     -16, -4,  3,-12, -4,  3, 32,  7,  2,  8, 32,-18, -1, 12,  1,  7 },
-    {  0, -8, -1,  0, -8,  7, -8, -1, -1,  4,-12, -1,  3,  0,  1,-18,
-       8,  8,-14,-10,-11, 19,  9,  5, -7,  6,  8, -4, 26, 12, -1,  6 },
-    {  3,  5,-14,  7, 14,  8, 20,-13,-16,-10, -2, 17, -7,  4, -8, -9,
-      14, -5,  3, -4,-12,  7, 14,-10,-19,-20, 35,  8, 13, 14, -2,  9 },
-    { -2, -4, -1,  1, -3,  0, -1,  1,  2,  2,  6,  0,  0,  4,  5, -2,
-       3,  3,  3, -2, -7, -3, -3, -1,  6, -2, 29, 22, 13, 34,  0, 14 },
-    { -3, -9,  3,  1,  5, -4,  2,  0,  7, -9,  0,  2, -5, -3,  0,  6,
-      -1, -1, -1,  2,  2,  4,  8,  7, 20, -6,  7, 16, 33, 20,  6, -1 },
-    {-11,  1, -3, -3,-11,  3, -9,-25, -1,-16,  4, -8, 15,  1, -2,  7,
-       8, 23,  2, 18,-13, 16,  3, -7,  6,  3, 16, -8, 12, 16,  3,  4 },
-    {  0,  5,  5, -5,  1, -1,  2, -3, -2,  1,-13,  2,  2, 10,  6,  7,
-      18, 18,  7,  9,  8,  9, 21, 14,  7, 12, 15, 14, 15, 12, 11,  5 },
-    {  1, -5, 11, -2, 17,  8,  3,  0, -1,  6, 11, -7,  6,  6,  7,  5,
-     -15, 14,  1, 11,  4, 10, 12,  1,  2,  4, 30,  1, 11,  1,  6, 13 },
-    {  2,  4,  3, -7,  5,  8,-11,  7, -5,  9,-10,  6,  8,-10, -3, 10,
-       1,-29, -4,-26,  5, -8, 13,  4,  3,  6, 35,  1,  3,  6,  3,  0 },
-    { -2,  1,  0,  0, -1, -3, -7, -3, -9, -3, -1, -6,  3,  4,  4,  0,
-       5, -1, -2, -2, -1, -4,-10,  8,  0, -6, 10, -4, 46, 12,  2, 28 },
-    {  4, -1,  4,  1,  0,  4, -2, -2, -2, -1,  2, -4,  1,  5,  0, -3,
-       1,  1, -2,  0,  1, -2, -1, -1,  3, -6, 35,-11, 13, 53, -3, -1 },
-    { -5, -2,  0,-13,-16,  5,-12,-11,  1,-30,  3,-18,-24, -8, -5,-19,
-       1, -3, -8,  7, -7, -8, 15,-19,  4, 10, 30, 24,  6,  1, -9, 10 },
-    { -4,  8, -7, -4, -6, 12, -1, -9, -4,  2, -9,  3,  2, -2,  4,  2,
-      22,  9,  4, -5,  0,  5, -2, -9, -3,  1, 18,-12, 18, 16,  4, 16 },
-    { -5, -8, -3, -5, -3,  6, -7, -3, -2, -5, -3,  1,  2,  2,  4, -6,
-      10,  3, 12, -3, 20,  0, 27, -4, 16,  5, 18, -3, 23,  4, 12, 11 },
-    {  0,  1,  0,  1, -2,  1,  2,  1, -1,  0, -2,  2, -2, -4,  1, -2,
-      -2, -1, -5, -2,  0,  0, -2,  2,  9,  7, 63,  5, 12, -1,  1,  0 },
-    {  4, -3, -7, -5,-11, -5,-12,-10,-10,-12,-15,-12,-14,-14,  1,  1,
-      10,-10, 16,  6,  2,  9, 11,  9,  9,  8, 12, -1, 13, 12,  6,  3 },
-    {  7, -3, -2,  4,  6, -8,  2, -3,-12, -5, -9, -8,-10, 15, -2, -4,
-       8,  9,  7,-13,-18, 34, -5,  7, 12, 22, 16,-11, 13, 25,-15,-11 },
-    { -3, -2,  0, -4,  1,  0, -3,-13, -7, 13, 12, -7,-10, 13, 19,  6,
-      16, 15,-12,-15, -3, 34,  1,  5,  1, -9, 11, 21,  8, 17, -5, -6 },
-    {  3, -5,  0, -4,  0,  4,-11,  4, -7, -3, -1, -8,  3, -2,  2,  1,
-      11,  5,  6, 14, -3,  2, -4, -7,  0, 31, 15, -2, 24, 11,  5,  4 },
-    { -1, -4, -9,  5, -8,-18, -4, -9,-20,-18,  7,-14,-16,  3,  8, -3,
-      29, 11,-13,-13,  7,  1, 17,  6,  6, 21, 11,  1, 14, -8,  2,  5 },
-    { -3,  8,-10, -6, 12,  2,  1,  3,  3,  3,  3, -6, -8,-14, 15, -5,
-      16,  4, 16,  0,  7, -1,  0, 16,  2,  1, 22,  4, 19, 13,-11,  1 },
-    {  2, -3, 10, 20, -4, -1, -8,  5, -8, -9, -6, -2, -4, -7,  8,-10,
-       0,  8, -6,  1, -8, 14, 13,  5, 17, -6, 26, -1,  7, -1,  0, 12 },
-    { -4, -7,-31, -2, -7, -1,  5, -5, -5,-12,  4, -7, -6,  3, 15, -2,
-       5, -2,  7, -1, 10,  7,  8, -1, 14, 20, 14,  9, 16, 16,  8, 24 },
-    { -7,  0, -3, -6,  1,  3,-13, -6, -4, -4, -5, -9, -1,-10, -4, -8,
-       2,  0, -1,  1, 24, 24, 21, 31,  5,  2, 11, 12,  7,  4,  3,  6 },
-    { -3, -5,  6, -4, -3, -1,  2, -1, -2,  1,  0, -8, -1,  2,  0, -4,
-       6, 22, -1, -5,  8, 12, -1, -2, 28, 27, 20,-27, 14,  1,  2, -3 },
-    {  1, -5, -2, -2,  6, -2,  9,  1, -2, -5,  3,  4, 11,  5,  2,  8,
-      -3, -1,  1, -2, -3, -5,  5,  8, 49, 12,  8, -3,  9, 20, 12, 17 },
-    { -6,  0,  1,  7,  0,  9, -2, -4,  8,  0, -2,-10,  0,  7, 21, -1,
-       0,  1, 17, -7, -5,  2,  4, 16, -2, 17, 14,-20, 15, 14,  4, 15 },
-    {  0,  3, -4,  9, -4,  0,  6,  4, -6, -6, -5, -7,  2, -9,-10, -2,
-      -5,  0, -3,-21,  9, 14,-11, 13, 29,  2, 25,  4, 22, -1,  2, -3 },
-    {  2, 12,-11,  2, 16,  9, -4,  7,  1,-10,-15, 11, -4,  3, -2,  4,
-       4, -5,-10,  1,  4, 19,-15,  6, -4, -2, 30, -7, 11, 21,-12,  5 },
-    { -2, -3, -2,  4, -1, -5, -3, -7, -5,  1,  0, -6,  1, -6,  7,  0,
-       8, -7, -3, -2,  2, 14,  2, -3,-26, -1, 26, 22, 32,  1, -2,  6 },
-    {  1,-38, -1,-20, -2, -3, -6, -4,  2,  2,  7,  0,  3,  5,  3, 10,
-       6,  1, -3, -5,  7,  5, -5, -4,  8,  3,  1,-14, -1, -9, -5, -4 },
-    { -5,-26, -7,-19,-10, -5,-11,  5,-11,-25, -8,-14, -9,-16, -8, -6,
-     -17,-14, -1, -1,  6,  2,  2,  2,  3,  0,  2,  8, -8,  3,  0, -3 },
-    { 17,-49, -3,-23, -1, 11,  7,  3,  4, -4,  0,  0, -1,  4,  2,  4,
-      -2, -4,  2, -2, -1, -2,  2,  0,  0, -1,  0,  0,  1,  2,  0,  0 },
-    {  4,-34, -6, -9,  1, 21, -7,  3, -2, -1, -3, 18,  2,-16,  7, -3,
-       8,  7, -5,  7,  2,  4,  8, -6, -7, -2, -5, -1,  4,  1,  2, -4 },
-    {  5,-29, 13, -2,-14,  3,  1, 18,-15,  4, -8,  8,-10,  8,  2,  1,
-      -8, 15,  3,-10, -4, -4, -2,  0, -3, -4,  2, -3, -4, -3, 12, -6 },
-    { 13,-20,  3,-18,-17,  4,-14, 13, 28, 11, -8, -6, 16,  6,  0, 10,
-       3,  4, -9, 13,  5, -7, 12, -5,  0, -7,  5,  1,  3,  3,  2,  1 },
-    {  3,-27, -5,-11,-21,-11,-12,  0, -5,  7,-22,  1,  3,  5,  0, -5,
-       8,  7,  1, -5, -7,  2, -5,  4,  1,  3, -8, -2,  0,  4, -2,  6 },
-    { 31,-45,  0, -1,-12,  1,  2, -6,  4,  3, -1,  3,  3,  0,  5,  3,
-      -5, 12,  4,  6,  2,  1, -2,  1,  3,  2,  5,  2,  2,  2,  3, -1 },
-    {  9,-45,  6,  5, -1,-17, -2, 18, -3,  2,  0,  1,  0, -1, 10,  8,
-      -7, -2, -5, -8,  6, -1,  0,  4,  6, -3, 12, -1, -2,  0,  5, -7 },
-    {  3,-26, -2,-12,-12,  2,-10, 16, -3, 12,  4,  5, 11,  8,-16,-17,
-      -2, -3, -3,  2,  5, -9, 13,  1, 10, 11,  3,  5, -2,  2,  2, -7 },
-    {  8,-26, 32, -7, -5, 22,  2, 14,-10, -8, -7,  3,  3,  7,  0, -5,
-       0, -1, -3,  0,  8,  4, -5, -7,  6, -1,  4,  8,  1,  1,  7, -6 },
-    {  4,-31,  2,-14,  2,  0,  1,  8, -6, -1, 17, -3, 13, -6,  5,-10,
-      -2,-10, -2,-10, -3,  7,  1,  5, -8,  8,-14, -3,-15,  7,-10, -6 },
-    { 16,-27, 13, -4,-23,  7, -9,  6, -7,  5,  4,  2, -1, -3, 23,-18,
-       7,  0, -3,  4, -3,  9, -6, -2, -1,  8, -6,  2,  6, -3,  2, -2 },
-    { -1,-35, -2, -8, 11, -1, -7, -3, -2, 11,  7,  6, -6,-10,  9,  6,
-      -3, -5, -6, -3,  9, 16,-16, -9,-20, 12,  3,  5, -3,  1, -9,  4 },
-    {  2,-24,  1,-12,-16,  5, -4,  3, -4, -1,-11,-11, -8,-14, 14, 10,
-      -8, 20,  8, -3,-11,  1,  1, -4, -4, -7, -3, 15,  2, -6, -2,  7 },
-    {  9,-21,  2,-19, -7, -5, -8, 25,  3, 17,  5, -3,  9,-12,  8,  2,
-      -4,  3,  3,  1, 11, -9, -4, -3,  4,  3,-22,  6,  4,  6, 11, -5 },
-    { 16,-23, 13,-17,-21,-12,  5,  9,-20,  7,  6, -6,  0,  2, -9,  6,
-      -6,-13, -7, -1,  5, -3,  5, -7,-10,  1,  0,  8, -9, 11,  0, -8 },
-    { 10,-26, -9, -7,-19, -4,  6, 16, -7,  5, -4,  4,  8,  0,  4, -1,
-       6, -7,  1, -8,-11, 10,-14,  0,-16,  6, -3,  5, -1, 14, 12,  1 },
-    {  8,-27, 12,-14, -1, -1,-19, 10,-11, 21,-14,  9, -8, -3,  8, -1,
-      12,-13,  3, -4, -2,  0, -9,  0, -7,  2, -3, 12,  1, -3,  3,  1 },
-    { 18,-20,-14,-14,-16, -3,-24,  6,-17,  2, -3,-11,  2, -3, 12, 10,
-      10,  1, 10,  7,  8,  5,  5,  4, -1,  7,  2,  2,  0,  4,  7,  0 },
-    {  0,-30,  9,-16,-18, 15, 12, -3,  4, -4, -5,-11, -4,-12,-10,  0,
-       2, -2, -4, -1,  2,  0, -1, -6,  2, -3,  4, -5,  7,  3,  5,  7 },
-    { 25,-24, -1, -6, -9,  6,-13, -2,  3, 15, -3, 11,  4, -8,-11,  2,
-       0, -9, -2,  7,  4,  8,  5, -8,  5,  6, -1,-11,-15, -5,  0, 11 },
-    {  0,-34, -7,-11, -7,  9, -3, 19,  4, -8,  3,-11, 11, -3, -9, 12,
-       9,  9,  2,  1, -7,  1, -3,  0, -6, -2, -1,  3,  0, -7, -2, -5 },
-    {  6,-34, -4, -5, -3, -9,  2,  9, -1,  9, -5, -3,-26,-12,  8, -6,
-      -7, 11, -8,  4,  4,  1, -1,  0,  8,  9, -4,  7, -1,  1, -3, -1 },
-    {  3,-30,  5,  6,-10,  3, -7,  6,  3,  3,-26,-19, -3,  1,  7,  5,
-      -4, -5,  6, 10, 13,-10,  4, -7, -4,  5, -3,  9, -6,  3,  9,  5 },
-    {  4,-24,  9,-19,  2, -4, -5,  8, -3,  2,  0,-15, -1,  9, -4, 22,
-       6,  9,  3,  7, 11, -9,  0, -3,  4,  5, -5, 10, -8,  5, -7, -3 },
-    {  8,-27,  7, -3, -1,  2, -9, 13,  7, 12, -4, -6, -6,  5,  0,  7,
-       5,  1, 15, -3, -4,  0, -5, -2,  7, -5, -7,  1, -2, 13, -8, 13 },
-    { 17,-22,-15,-11, -8, 16,-14, 18,  2, -1, 14, -7, 14, -6, -6, -7,
-      -8, 17,  6,  4,  4, -7, -5, -9,-14, -6, -1,  9, -3,  1,  6, -5 },
-    { 25,-30,  2,-12,-13, 18,-18, 16,  8, -3, 10, -8, -3, -1, -6,  3,
-      -5, -7,  4,  6,  7,  1,  1,-11, -5,  6,  2, -4,  9, -1, -5, -2 },
-    {  7,-23,  7,-15, -1, -3, -1,  0,-10, 12,  2,  5, -4,  0,  4,  6,
-      -1,  5, -9, -1, -1, -7,  1, 17,  9,-17,-16,  8,  4,-14, 11, 14 },
-    {  0,-31,  7,-13,  3,-11, -7,  6,  1,-11,  8, -7, 15, -3, 16,-11,
-      -1,-15, 16, -3,  5,  0, -2, -2, -6, 11,  5,  6,  5, -5,  6,  3 },
-    { 13,-24, -2,-20,-10,  7, -3, -1, 15,  2,  6, -5, -7,-10,-20,  1,
-      -4, 14,  8, -2,  3,-13, -3,  1, -4,  1, -3,  2,  8, -7, 16, -4 },
-    {  1, -2, -2, -3, -4, -7,  0,  3,  6,  7,  3,  2,  1, -2, -1,  0,
-      -6,  4,  2, -4, -3, -4,  5,  9,  5,  0, -3, -3, -4, -7,-31,-50 },
-    { -1, -3,  7,  2, -1,  2,  4,  6,  0, 10, -2,  0,-20, -6, -3,  9,
-     -20,-22, -1, -1, 15,  9,-12, 10,-13,-20, 12,  3,  5,  6, -7,-26 },
-    {  0,  4, -2,-14,-12,  6,-13, 11,-10,  3, 22,  6, 16, -2, -5,  1,
-      -3,-11,  0, -7,  5, -5,  0,  1, -1, -6,  8,  8, 10,  9, -5,-27 },
-    { -5, 10, -2,  7,  9, -9,  5, -9,  5,  4,-15, 14,  1,  3,-10,  5,
-       0, -2,  7,  3,-13,  6,  9, -6,  5,-14,-17, -1, 11, 14, -2,-26 },
-    {  0,  6, -3,  0, -8,  6,  0,  1,  4, -8,  2, -5,  4,  7, 15, 11,
-       9, 19, -2, 14, -8,  7, -1,  3, -3, -3,-10, -2, 12, -2,-12,-29 },
-    {-12, -5,  0, -3, -2,  6,  3, -3,  2, -2,  1, 11,  2, -7,  5,  1,
-       2, -2,-14,  0, -1, -5,  3,  8,-28,-26,  6, -6,  3,  8,-10,-27 },
-    { -1, -3,  6,  2,  4, 15,  1,  0,  2, -2, -2, 13,  3,  6,  0,  6,
-      -1, -4, -1, -5,  8, -1,  5, -5,-15, 11, -8, -5, 14, -6,-14,-29 },
-    { -5, -6,  0,  1,  0,  6, -3,  2, -5, -1,  5, -3,  2,-10,  3,  4,
-       3,  0, 13, -3, -1,  4, -4, -6,  2,  9,  8,  2, -3, 28,-11,-31 },
-    {  1, -4,-10, -9, -4, -3,-15, -6,  1,  5, -3, -6,  5, -6,-22, 27,
-     -13,  5,  3, -7, -4, 20, -7,-12, -1,-24, -4,-13, -8,-11,-15,-21 },
-    { -6, -4, 19, -6,  2, 11, -6,  1, -3,-10,  9, -9, 12,-10,  2,  1,
-      -9,  1, 15,  7, -5,  5,-29,-35,  4,-30,  9,  9, 19, 17,  2,-17 },
-    { -3,  3, -3,  1,  2,  5, -1,  5, -2, -3,  1, -3, -8,  3, -4, -2,
-      -4, -1, 12,  0,  2, -8, -6, -4, 16, -1,-14, -2, 25, -6,-15,-36 },
-    {  0, -1,  3, -4, -4, -1,  7, -4,  8,  0, 10,  9, -4,  1, 10, -1,
-      -3,-13, -5, -4, -1, -4,  8, 11, 14, -7, -5, 16, 12, 13, -1,-28 },
-    {  1, -2,  2, -3, -8, 10,  4,  9, 12,  3,  5,  0,  8, -3, -6,  2,
-      16,-11, 11,  0,  1,  6,  1, 18,-10,-16, -1, -4,  5,-14,-15,-20 },
-    {  1,-12,  5,  4, -7,  8, -1,-17, -2, -9,-14,-11,  6, -9,  5, -4,
-       3, -2,  7, 18, -5,  5,  6, -1,-11, -2,-10, -3,  8, -3, -2,-32 },
-    {-12,  5, 20, -5, -6,-11, -6, -6,-13,  4, -6, 19, -8,  2,  3, -9,
-      -4, -4, -1,  9, -1, 21, -1,  7, 15,-10, -1, -3,  9, -3,  2,-24 },
-    {  0, -3,  2, -6,  4, -1, -9, -2, -1, -3,  6, -1, -5, -6, -5, -8,
-       0, -2, -6,  9, -4,  3,  2,-13,  1, -7, 23,-13,  4, -3,-15,-33 },
-    { -7,  2,-15, 11,-10, 14,  0,-11,  3, -1, 12, -4, -4,  9, 11,-13,
-     -13, -3,-14,  1,  3,  6, -5,  8,  0,  5,  5,-10,  4,  5, -6,-30 },
-    { -6,  4,  0, -5,  4,  1, -1, -1,  3,  6,  5, -2, -5,  0, -2,  5,
-      -4, -2, -4, -2,  4,  7, -7, -1,  1, -4, -3,-19, 37, 12, 10,-40 },
-    { -7,  2, -7,-12, 17, 11, -7,  2,  2,  3,  1, -1,  3,  4, -2, -5,
-       9, -9,  6,  4,  9, 12, 11, -5,  2, -1,  0,  9,  5, -7, -2,-24 },
-    { -7,  6,  1,  3,  1,  0,  6,  0,  4,-12, -2, -2,  1, -9, 10, -2,
-      11, -1, 21,-12, 15, -5, 10, -5,  5, -5, 14, -6,  5, -7, -3,-29 },
-    { -2,  0, -5, -2, -3,  1, -3,  0,  4,  2,  3,  0,  2, -2,  7, -2,
-       3, -5,  2, -1,  6, -4,  0, -3,  8,-11, 19, -8, 22,-34, 13,-35 },
-    { -1, -3, -1,  9, 11, -3, -3, -1,  7, 18, 11, -5,  2,-12,-11, 18,
-       9, -5,  1, -6, -9, 12,  1, -3, -3, -9,-14,  9,  9,  8, -6,-26 },
-    {  0,  5, -5, -1, -1, -2,  4,  6,  8,  2, -1, -2,  5,  1, -5, -4,
-       1,  1, 18,  1,  7,-10,  3, -2, 12, -1,-15,  9, 12,-14, 13,-38 },
-    {  3,  0, -8, -1,  0,  8, -9, -3, -8, 16,  3, 16, -5, -9,  0, -1,
-      -7, -1, -4, 13,  7,  0,  1,  2, -1,-16,  0, -2,  1,  8, -8,-28 },
-    {  7,  9, -5, -3, -2,  2,  0,  3, 11, -6, -4, -2, -2, -5, 28,-18,
-      -6,  2, 15,-10,-15,-10, -2,  0, -2, -2,  4, -3,  7, 11,  5,-30 },
-    {  9,  0, -7, -1, -4, -7,  2,  2,  9, -2,  2,  3, -8, -6, -6,  3,
-     -10,  4, 10,  5, 21, -4, 14,-18,  1,  3,-10, -2,  6, 14, -8,-26 },
-    {-14, -1,  2,  3, -3,  7,  1,-22, -1, -1,  0,  1, 12,-14,  3, -5,
-       0, 10, -3,  1, -5, 12, -3, 10, -8,-22,-11,-13, -7,-10,-13,-25 },
-    { -2, -5, -4, -4, -9,-18,  9, -3, -5, 17, 13,  5,  6, 11,  3,  8,
-      20,  4,  2,  9,  8,  5,  6,  1,  7, -7, -6, -2, -7,  0,-17,-23 },
-    { -5, -5,  2,  0,  6,  2, -2,  2, -3,  4,  4,  0, -5, -2, -4,  6,
-       8, 10, -1,  1, -5,  5,-14, -2,-11,  8,  6, 25,  7, -1,  0,-43 },
-    { -4,  0,  4, -2,  7,  0,  3, 17,  5,  2, -5,  1, 21,  3, -2,-10,
-     -16, -9,  7,-12,  9, -8,  2,  5, -5,-10, -2,-11, -5, -1, -9,-30 },
-    { -2,  3,  1, -4, -1,  0,  8,  1, 12,  4, -1, -1,  3,-17, 13,  9,
-       0,  7, -6, -5,  9,  1,  5,  4,-10,-18,  0, 14, 11, -4,-16,-28 },
-    { -1,  0,  2, -1,  4,  1, -1,  1, -1, -2, -1, -2,  3,  0,  0, -1,
-      -1,  1,  2, -2,  3,  3, -2,  4, -2, -1, -6,  1, -1, -1,  6,-70 },
-    {  7,  3,-11, -1, 12, -4,-14,  4,  4, -4,  4, -2,  2,-12, -4, 15,
-     -17, -4, -3,  6,  8, -5, 22,-22,  5,-11, 15, -4,  4, -1,-21, -1 },
-    { 10, -2,-13, 11,  4, 14,  4,  9,  8,  8, 19, 15, 14, 15,  5, 10,
-       8, 15, -5,  4, 14, -8,  1,  1,  2,  1, -1, -3, 21,  8,-29, 13 },
-    { -6,  0, -6,  6, -1,  2,  8, -4, -5,  4, -4, -5,  0, -2, -4,  0,
-       9, -2,  1, -2, 26,-19, 21,-10,  4,  1, -8,  5, 22,-10,-13, 15 },
-    { 11, -5,  1,  0,  6,  3,  7, -2, -2, -3, -5, -1, -2, -6,  1,  1,
-      -8, -5,-13, 13, -2, -3, -1, -9,-28,  4,  2,-11, 18,-20,-24,  9 },
-    {  7,  4, -3,  6,  6, -6, -7, -5, -7, -4, -4,  0, -7, -5, -6, -5,
-       2,-13,-12,  2,  0,  5, 18, 15,-13, -7, 13,-20, 16,-10,-19,  6 },
-    {  5, -8, -1,  5, 10,  2, -1,-10,-11, 23,  8, -5, -8,  4, -5, -4,
-      -5, -5,-11, -8,  5,  1,  7, -9, -9, -6, 12, 14, 17,-12,-22,  3 },
-    { -5, -8, -3,  3, 12, -1,  0, -4, -5,  1,  1,  6,  1,  5, -5,  7,
-      -2,  7,  1,  6,  6,  2,  0, -5, 17, -4, -5,-24, 13,-20,-27, 14 },
-    { -1,  2, -3,  1, -3,  1, -3,  0, -2,  3, -2,  1,  2, -1, -2, -1,
-      -2, -5,  5, -2,  0, -7,  1, -6,  8,  8, 11, -5, 24,-43,-13,  2 },
-    { -2,  4,  7, -3, -4,  4, 13, -4,  0,  0, -2,  9,  0, -3, -6,  1,
-      -7,  1, -1, 10,  0,  5, -1,-24, 25,-15,  7,  2, 22,-10,-21,  0 },
-    { -5,  2,  6, -2, 13,  3,  5,-12,-11, 16,  6, 10, -5,  0, -3,  6,
-       5, -5, -5, 10, 12, 10, 11, -7,  8,-14,  2,-15, 13,-14, -8, -3 },
-    {  5,  6, -7, -5,  5,  2,  9,  5,  0, -1, -4,  2,  8,  0,  3,  5,
-     -12,  3, -3, -6,  2, -1, -5, 14, 11,-20,-21,-25, 24, -1,-10,  6 },
-    { -5,  5, -2,  9,  4, -4, -1, -6, 11, -6,  5,  0,  2, -3,  6, -1,
-     -17,-18, -4,-13,  9, -1,  9, -7, -4, -8,  2, -3, 12,-31,-18,  5 },
-    { -7,-11,  6, -8,  4, -3,-12,  0, -1, -6, -3,  0,  5,  9,  7,  2,
-       1, -8, -6,  8,  2, -5,  7, -1, 16,-10, 16,-12, 18, -1,-25,-12 },
-    {  3,-12,  1,  2, -2,-18, -8,-15,-10, -9,  2, -7, 11,-11,  2, -1,
-      -1, -1, -9, -6,  3,-14, -2, -1,  2,-13, -7, -9, 19, -5,-17,  2 },
-    {  7,  1, -8,  7, 17,-13,-10,  5,  7,  1, -6,  4,  9, -4,  0,  3,
-       8,  1,-14, -9,  4,  7, -9,  0,  6, -5,-12, -2, 25, -2,-19,  1 },
-    {  7, -3,  6, -3,  1,  6, -7,  0, 10,  0,  4, -5,-17, -4,  4, -1,
-       0, -3, -7, 19, 24, -1, 21,  8, 10,  9,  8, -1, 23, -2,-18, -2 },
-    {  3, -3,  0,  5,  8, -2, -9,  2,  9,  6, 19,  8,  2,  6, -9, -2,
-      -4, -3, -8,  7, -7, -8,  5,  4, 26, -6,  7, 18, 24,  0,-13,  4 },
-    {  0,-13,-11, -1,  3, -9,  5,  4, -7,  3,  0,  2, -1,  4, -5,  2,
-       9, -2,-11, 15,  1,-21,  1, -1,  0,  4,-14, -4, 24,-16,-13,  1 },
-    {  1, -9, -8,  0,  0, -4, 11, -1, 14, 16,  0, 17, -2, -9,-12,  0,
-      -1,-14, -9,-14,  0, -2, 19,  4,  6,  4,  4,-11,  8,-17,-19, -5 },
-    { -3,  1,  2, 12, -4,-18, -1, -4, -7, 14, -3,  2,  0, -7, -8, 12,
-      -5, -9, 14, 12, -9, -2,  4, -6,  4, 18, -1,-25, 22,  2,-23, -5 },
-    { -2,  0,  0,  0,  1,  3,  5, -1,  5, -2, -2,  2, -3,  0,  1,  2,
-       0, -1,  2, -1, -9, -6, -7, -4, -2,  4, -7, -5, 64, -3,-25,  4 },
-    { 12, -2, -3,  0,  8, -9, 13, -7,  6, -3,-12, 12, 15, -9, -4,  2,
-       9, -4,-12,  3, 14,  1,  7,-15, 15,  0, -6,-12,  0, -3,-20,  6 },
-    {  2, -1, -4,  5,  9,  6, -7,  2, -2, -7, -2,  0, -1,-18, -4, -6,
-     -15, -5, 11,  5,-10, -1,  2,  7, 12,-19, -7,  8, 21, -4,-15,  4 },
-    {  4,  2,  5,  5, -5,  1,  3,  2, -8, 13,  0, -5, -2,-14,-11,  6,
-       2, 17,  8,-13, 26, -2,  5,-15, -4,-14, 12, -9, 13,-21,-23, -4 },
-    {  2, -3, -2, -3,  3, -2,  6,  9, -9, 13,  4,  2, 12, -3, -3,  1,
-     -17,-22, -3,  4,  3, -2,  1, -9,  1, -6, 11,-13, 14,  0,-15,  6 },
-    {-16, -4, 17, -2,-20,-11, 11, 10,  5, -8, 16,  2,-17,-14, 11, 11,
-      -6,-11, -7, 12, 12,-10, -6,  5,  8, -4, -2, -5, 28,  3,-13,  4 },
-    {  0, -3,  3, -7,  6,  8,-12, 20,-19, 18,-11, 10, -5,  0, -9, 11,
-       3,  0, -2,  9, -7, -5, 18,  3, -2,-16,  1,  6, 12, -7,-16,  1 },
-    {  4,  1,  5, -5, 15,  2, -8,  3,  5,-11, 15, -3,  8, -8, -1,  7,
-       4,  7, -2,  6, -9,  5, 12,  2, 33, -2, -6,-18,  4,  0,-18, 11 },
-    {  3, -1,  1, -1,  0,  1,  4, -1, -5,  0,  1,  0,  4,  2, -1,  4,
-      -3,  2,  0, -2,  4,  6, -1,  6, 42, 19, -4,-37, 19,  1,-15, -4 },
-    {  2,  0, -5,  0, 10,  0,  0, -5,  3,  0,  0, -3, -3,  0,  2, -4,
-     -10,  2, -6,  4,  4,  1, 27, -7, 17,-34,  5, -9, 15,-16, -7, -5 },
-    { -2,  7,  7, -2,  9, -2,-15, 11, 11,  7,  5,  1, 15,  1, -9, 31,
-       2,-15,  2,  4,  3,  4, -1, -8,  2, -7,  6,-17, 11,-14,-11,  2 },
-    {  1,  1,-11,  9,  9, -6,-14,-11,-10,  8, -3, 11, 16, -9, -8,-13,
-      -8,  9,  0,  6,  6, -2, 13, -8, -2,  3, 13, -3, 10, -6,-17,  4 },
-    { 14,  5,  4, -6,-12, 10, -7,  8, 21, -8,-30, 15, -2,  1, 11, -9,
-      -5,  1,  0, -1, -1, -6, -2,  3, -5,  7,  9,  5, -5,  2,  0,  1 },
-    { -1,  2, 20,-17,-15,  3,  3,  7, 11,-17,-13, -6, -3, 18, 17,-15,
-      -4, -4, -5, 22, 14,-14, -2,-10, -7, 11,  8, -7, -3,  0, -7, 11 },
-    {  7,-11, -7, -8,-14, 22,  5,  2,  6, 13,-12, -2, 10,  3,  0,-21,
-      -4, 20,  3, 10, 21,-10,-12,  8, 11,  2, -5,  2,  1,  3, -1, 15 },
-    { -1, -2, -1, -2,-13,  8, -4,  0,  7, -2,-17,  8, 18,  5,  3,  8,
-      -8, -2,  3, -4, 14,-18,-13, 14, 15,-13, -1, -2,  4, 11,  1, 12 },
-    { 13, -6, -4,-16,-17, 16, 21, -2,  5,-11, -9, 19, 21,-17, -3,-17,
-       3, 12,  8,-12, -6,  1, -7,  9,  9, -7, -5, -1, -3,  5, -6, -4 },
-    { 11,  5, 12,-20, -6, 10,  4, 12,  8, -5,-10, 15, 13, 14, 10,-15,
-     -13,  1,  6, 14, 15,-17,-13,  4, -5, 10,  7, -6, -8, -3, -4, 12 },
-    { 25, -1,  7, -5, -7, 11,  1, 17, 13,-15,-14, -4,  5,  3,  8, -3,
-      -2,  2,  0,  6, 16,-12, -6, -4,  4, -3,  7,-10, -3, -7,-13,  7 },
-    { -8, 10, -3,-13,  5,  2,  4,  9,  9,-17,-13,  2, 11,  1,  6, -4,
-       8,-10,  4,  1, 19,-15, -4, 12, 31,  7, -5,-17, -4,  9, -2,  7 },
-    { 14, -6, -6, -6,-14, 13, 17, -5,  4,-14, -9,  7,  7, -9,  3,-16,
-     -15, 11, 11,  6,  4,-11,-19,  3,  5,  8, 13,-14,-14,  3, -4, 12 },
-    { -2, -4, 10, -4, -7, -1, 27,  5,  2,-16,-18,  4, 12, -2, -3, -2,
-      -1,  1, -8,-12,  3, -4,  8, 15,  2,  4,  9,-13,-14,  9, -7,  5 },
-    {  4,  2,-10, -5, -7,  2,  1,  4, -1, -6,-15,  6,  1, 10,  5,-10,
-      -9, -1, 13, -3,  5,-21,-11,  8,  8,  5, 27,-21,-18, -5, -1, 15 },
-    { 11,  1,-16, -8,-11,  0,  5, -8,-12,-13,-17, 22,  4, -6, -1,-18,
-     -10,  0, 19,  2, -2, -8, -7, -3,  2, -2, -9,-17, -5,  4,  4, 10 },
-    {  8, -6,-19, -5, -4, 12, 14, 15, 10, -9, -1, -9, 19, 12,  0, -1,
-       2,  4,  7,  9, 16,-16,-14,  9, -4,  3,  1,  0, -2, 10, -1, -1 },
-    { 12, -8, 12, -9,  0, 25,  7,  9,  2,-31, -9, -4, 15,  4, -5,  1,
-     -10, 11,  8, 10,  0, -6,  5, 11, -1, -6,  4,-10, -9,  6,  4,  5 },
-    { 14,  6,-17, -2, 17, 12, -9,  2,  0,-25,-14,  5, 20, 14,  8,-20,
-       5,  2, -2, -3,  9,-13, -3, -1, -6,  3,  7, -6,  0,  2,  3,  1 },
-    {  8,  4,-15, -3, 10, 18, -4, 13,  8,-22,-10,  9, 19,-15,  7, -5,
-     -13, 12, -4,  9,  2, -9, -6,  0,  2,  1, -9, -6,  6,  1, -1, 11 },
-    {  4,  1,  4, -5,-10, 18,  7,  2, -4, -9,-11,  0, 32, -7,  4,-16,
-      -1,  0,  6,  3,  6, -3,-14, 16,  9, -2,  7, -1,  0, -5,  5, -3 },
-    { -3,  2,  3, -8, -6,  4,  6,  2,  4,-12,-15,  2,  8,  8,  9, -3,
-     -18,  6, 34, 11, 12,-15, -1,  2,  9,  2, -4, -4,  2,  4,  2, -3 },
-    { 18, -6,-12, -8, -1, 15, 20, -4, -1,-11, -5,  6,  6,-11,-15, -7,
-       3,  7, 10,  2,  8,-10, -5,  8, 15, -5,  5,-17,-13, 13, 11,  7 },
-    {  8, -4, -6, -1,-14, -3,  6, -2,  1, -5, -1, 10, 10,-15,  5,  0,
-     -10, -4, -3,  7, -4,-19,-15, 27, 11, 18,  3,-19, -2,  6,  0, 12 },
-    { 12,  0, -5,  0,  4, -5,  1,  5, 10, -7,-11, 21, 29,  1, -2,  1,
-      -4,-11, -1, 13, 11,-20, -1,  4,  4,  4, -5,  6,-13, -2, 11,  9 },
-    {  2, -7, -7, -3,-10, -1, 20, 12,  1,-19,-19, -1,  5,  4, -7,-25,
-      14,  1, -3,  2, 12, -4, -3, -3, -2,  6,  1,  0,  3,  2,  5, -1 },
-    { 12, -8,  3,-12,-10, 10, 13,  0, 23,-14,-18, 10,  0, 15,  3,-12,
-      -3, -5,  5, -4,  2,-14,-10,  8,  2,  9, -1,-11, -3,  5, 13,  2 },
-    {  9, -6,  7, -7,-30, 17,  6, 13,  1,-14,  0, -1,  6, -9,  8,  3,
-      -4,  0, -1, -7, -5,-13,-19, -3, -4,  4, -6, -2,-13,  1, -2,  3 },
-    { 10,  1,  3,-18,-26, 17,  4,-16,  4, -3,-13, -4, -6,-11, -4,-21,
-       7,  8,  2,  5, 13, -6,  1,  5,  8,  7,  9, -6, -6,  1, -1,  2 },
-    { -3, -1,  0, -2, -2,  0, -1,  3,  4,-14, -8, -9, 13,  2, 50,-23,
-      -8,  8,  7, 11, 16,  3, -7,  0, -2,  6,  5, -1,  1, -2,  4,  3 },
-    {  1,  3,  1,  1, -6,  3,  6,  6,  2, -2, -3, 10,  2, -8, -5, -5,
-       5,  4,  4, -2, 10, -8,-40, -1, 21,  8,  3, -4, -1, 13,  4,  7 },
-    {  2,  0, -4, -8,  5,  2,  7, -5,  5, -8, -4, -1, 12,  2, 12,-13,
-      -9,  0,  1,-12,  9,-43,  1, -5, 12,  1,  3,  6,  1, -1,  3, -2 },
-    {  6, -2, -1,  1,  0,  4,  8, 14,  4, -7,-23, -5, 23,-17, -6,-15,
-      -8,  7, 10, -1,  7,-16,  4, -6,  2,  3, -3, -3, -1,  8, -1,  4 },
-    { 10,  4, -4,  1,  7, -3,  2, 11,  4, -6, -3,  8,  5,  4,  1,-45,
-      -6, -4,  4,  2,  1,-14,-10,  1,  1,  6,  2, -8, -1, -3,  3,  3 },
-    {  1, -1,  2, -3, -8,  9,  3,  3, -2, -5, -8,  8,  7, -7, -4, -6,
-       5, -9, 11, -2, 46, -5, -1,  9, -2,  0,  3, -5, -3, -5,  7,  0 },
-    { -4,  1, -2, -1,-11, 11,  8, -3, -2,-10,  0,  4,  9,  9,-17,-17,
-     -34, -4, -5, -7, -3,-12, -3, 11, 18,  3, -2, -5,-18, -5, -3,  6 },
-    {  7, -5, -3,  1, -4, -3, -5, -1,  2,  5, -2,  3,-10, 12,-18, -5,
-     -10, 12, -9,  4, -6,  2,  0, 16,-17, 15, 14,-12,-10, -2, -9, -1 },
-    {  4, -5, -3, -5, -3, -1,  7, 18, -7, 12,  3,  5, -8, -4,-20,  1,
-     -25,  1, -8, 13,-10,  8,-19, -1, -8, 10,  6, -9, -1,  0, 12,  4 },
-    { -4,  5,  0, -1,  2,  5, -8, -2, -6,  4, -8,  9,  3,  2, -7,  4,
-     -25, 13,-23, 10, 14, 15,-11,  3,-18,  4, 16, -4,  1,-10,-10,  3 },
-    {  5, -3, -1, -3,  4,  1, -3, -4, -5,  1,-12, 14, -7, 11,-15,  6,
-      -6, 24, -4, 13, -1, 15,-13,  8,  3,  7, -5,  2,  2,  0,  3, -7 },
-    { -3,  1,  0,  8,  6, -1,  6,  5, -5, -2,-12,  4,  0, -2, -3,  5,
-      -6,  0, -8,  9,-10,  4,-28, 12,-20, 11,-13,  7,-18,  1,-11,  1 },
-    {  1, -4,-15,  5,  0,-13, -5, 13,-11,  4, -4, -5,  5,-14,-16,  0,
-     -14,  5,-20, 12, 10, -7, -5,  6,  6, 22,  6, -4, -2,  3,  8, 11 },
-    { 13,-11, -2, 16, 16, -7,  0, 20, -7, -1,  0,  5, -9, 12, -2, -5,
-     -22,  5,-10, 12, -6, 11,  9, 21, -8, 15,  4,  0, -8, -4, -4, 10 },
-    { 18, -4,-13,  0,  1,-15, -1, -3,  2, 10, -1,  6,  1, -4,-20, -5,
-      -8,  6, -8, 17, -5,  5,-10,  8,-22,  6, -5, -2,  8,-17,  8,  2 },
-    {  1, -2, -9,  6,-31, -8, -8,  8,  0,  5, -9, -4,  2,  3,-12, 11,
-     -18, 10, -5,  3,-11, 13, -6, 11, -3, 12, -7,  3, -9, -1,  2, 11 },
-    { -9, -6, 21, -8,-15,  4,-11, 12,-11, 17, -1,  2, -6,  0,-15, 13,
-     -12, 19,  0,  2, -6, -3, -9, 10,  3, 17, -2,  5,-10, -3,  0,  1 },
-    {  4, -6,  5,-10,  1, -5,  1,  0,  0,  0,  2,  7, -2,  2, -2,  0,
-      -4,  3, -4,  1,-12,  6,-49, 16,-10, 13,  0, -2,  8,  6,  1,  8 },
-    {  5, -8, -7,  9, 13, -5,  7,  0, 10, 11, -4, -3, -1, 13,-14,  6,
-     -15, -6,-14, 16, 15,  1,-18, -4,-20, 20, -7, -1, -9, -2,-10, 10 },
-    {-12,  4,  0, 10,  0,  3,  8,  4,-27, -1, -2, 19, -4,  2,-13,  3,
-       1,  9,-12,  1,-22, 19, -5,  4, -9, 12,  2, -9, -8, 11, -3,  7 },
-    {  4, -5, 11, -6, 17,-17,  5, -4, -2, -6,  1, -5,  2,  4,-14,  6,
-     -20, 19,-20, 12,-21,  5,-14, 13, -2, 11,  4, -3,  0,-10, -4, -2 },
-    { -2, -1, -3,  8, -9, -7,-22, -3,-24, 13, -2, 10,-15,  5, -9,  4,
-      -7,  0, -5, 15, -8, 11,-13,  6, -4, 19, -8, 12, -4,  6,  9,  7 },
-    {  2, -3,  2, -1,  0,  3,  1,  2,  1, -4, -2, -3,  1,  5,-12,  6,
-     -16, 14,-23, 10,-14, 17,-15, 16, -2,  9,-25,  9,-10, 16,  4,  9 },
-    { -3,  7, -8, -3,  2,  2, -4, -8, -9, 10,  3,-11, 25,-10,-28, 27,
-      -9,  7,-13,  9, -2,  4,-12, -8,-14,  6,  7,-10,  3,  3, -3,  5 },
-    { -8, -3,  1,-10,  8, -3, -9, -4, 13,  7,  2,  4,-10,  4,  3,  7,
-     -18,  2,-22, 15,  4, 20, -7,  5, -6, 13, -1,  4, -7, -6,  6, 13 },
-    { -2,  3,  0,  2, -4, -2,  0,  0,  1,  2, -2, -5,  0,  1, -4,  0,
-      -2, -3,  1,  2, -1,  2, -8, -1,-24, 68, -3,  8,  3,  3, -1, -1 },
-    {-15, -2, -9, -7, -1,  8,-14,  8,  3,  6,  0, -1, -8,  8,-23,  2,
-     -14, 17,-15,  8, -4,  7,-18,  0, -8, -3, -1, -4,-10,  4, -1,  4 },
-    {  8,  0,  2, -7,  0,  5,  1,  3,-11,  4, -8, 14,  3, 20,  1, 26,
-     -11, 13,-13, 20, -2,  0, -8,  2, -6,  6, -1,  9,  3, -6, -3, 10 },
-    {  5,  0, -1, -7, 10,  1, -3,  5,  4,  7, -5, -1, -3, -1, 12, -3,
-     -15,  7, -9, 22,-19,  8, -9,  4,-23, 13,-14,  6, -6,-14, -4,  7 },
-    { 14, -5, -8,-10, 25,  3,-23, -7,-28,  0, -1, -9,  4,  1,-13, 20,
-      -8, 10,-16,  8, 12,-13,-21,  5,-13, 11, -2,  1, 12, -7,  2,-10 },
-    { -5, -4,  9,  5, -6, 35, -7,  8, 15,  2, -1, -9, -6,  2,-18,  7,
-     -15,  6, -3,  2,  8, 12,-30,  7, -4, 20,  2,  6, 13, -6, -4,  0 },
-    {  1,  8, -9,  9, -5, 12, -9, 16, -9, 16,-17, 14,-13, 15,-18, 14,
-     -15, 17,-12, 14,-13,  7,-16, 13, -9,  5,-11, 10, -9,  6,-12, 13 },
-    {-10, -4,  5,  3,  1,  6,  8,-14, -5, 15,  7,  4,  8,  7,-22,  8,
-      -7, -8,-15, 26,  1, 13, -3, 17, -5,  9, -2,  4, -6,  3, -8,  9 },
-    {  8, -3,  2,  3,  3,  1, -2, -1,-11,  8, -4,  0, -6, -5, -1, 13,
-     -37,  9,  1, -6,-10, -2,-10, 11,  8, 13, -3, -2, -6,  8, -4, 13 },
-    {  3,  2, -3, -4, -4,  7, -8,  9, -8,  9,-20, 12,-19, 15,-18, 17,
-     -15,  7, -1, 20,-11,  6, -6,  3,  1,  9,  2,-14, -2, -2,  2,  1 },
-    { -7,  1, -1, -3, -6,  4,  4, -3,  3, -1,  5, -4,  3,  2, -1,  9,
-     -59,  5, -4, 30,  3,  3, -2, -3, -1,  2,  2,  1, -1, -1, -2,  1 },
-    {  0, -3,  2,  0, -1, -8,  0,  2, -3,  4, -4,  1, 10,  6, -6,  8,
-      -7,  4, 10, 11,-41, 27,-20,  3, -3,  8,  1, 11, -5, -8,  0,  4 },
-    {  5,  1,  4, -2,  1,  2, -1,  6, -7,  2, 11,  4,  0,  0, -8,  7,
-     -10,  0,  0,  8,  2, 10, -1,  1, -2, 44, -2,-21,-12, -3, -1,  2 },
-    { -4,  4, -2, -2,  6, -8,  2,  1,-10, 14,  8,  6,  5,  1, -2,  4,
-     -13,  4,  2,  5, 10, -2,-21, 32, -3, 18,  9, -6, -9, -9, 10,  2 },
-    {  9,-16, -6, -2,  1,  4, 22,  2, -2,  1, -3, -2, -9,  3, 16, 19,
-     -24, -6, -6, -5, -8, -7,  8, -7, -1,-12,  5, -3,  0,  4,  2, -3 },
-    { 10,  3,-16, -4, -1, 13,  4,  4,  1, -3,  1, -6,-14, 18,  3,  8,
-      -8,-28,-16,  4,  4,  2, 12,  7,  9, -4, -4,  5, -1, -1,  2,  2 },
-    { -5,-13,-22, -3, -8, 21, -2, -9, 21, -4, -9,  5, -8, 15,  5,  1,
-      -5, -9, -7, -2, -5, -5, -1, -5, -5, -5,  3, 10, -4,  0, -7, -2 },
-    {  5,-10,-18,  2, 20,  4, 13,-10,  8,-15,-11, -3, -1, 16, 10,  9,
-      -8,  6,  7, -5,  6, 11,  5, 17, -4,  7,-11,  5, -3, -6,  2,  1 },
-    {  3, -5,-19,  1,  1, -3, -2,-25,-11,-17,  0,-13, -4, 10, 10,  2,
-      -5,  4,  0,  3, -3, -5,-10, -2, 13,-22,  0,  3,-11, -5,  7, -1 },
-    { 12,-14,-29,  6, -1, 10,  7,-17,-12, 14,  3,  9, -9,  9,  7,  6,
-      -3,-13,  0,  5,  3, -1, -6, -1,  0,  2,  4,-12, -5, -1,  2, 11 },
-    { 12,-15, -7, -2,-12, 17, 20,-16, -2,-12, -6, 15, -6, 12, 11,  9,
-       7, -6,  7, -4,-19,  6,  2,  2,  3,-11,-10, -4, -5, -3,  3,  2 },
-    { 11,-22, -6,  0,  8, 18,  3,-11, -4, -7,-15,-17,-12,  6, 16,  4,
-      -9,  4, -5,  3,  6,-16, 10, -7, -7, -3,  5,  0,  1,-15, -4,  5 },
-    { 12,-22,-16,  5, -6,  8, 12, -4, -9,-17,-11,  3,  5,  8,-17,  0,
-      11, -4,-13, -6,  2, -1, -1,  3,  3,-11,-12, -1,  1,  1, 12, -2 },
-    {  8,-10,-33, -5, -3, -6,  1, -7, -8, -4, -6, -1,  5, -4, -6,-12,
-     -16, -8, 11,  8,-14,  7, 12, 11,  4,-14, -3,  6, -7, -5, -3,  3 },
-    {  0, -8, -7,  2, -4, 24,  2, -9,-11, -3, -7, 11,-12, 17,  1, -1,
-       3, -5, -7, 12,  4, 11,  0,  3,  2,-18, -3,  4,  7, -6,  3, 15 },
-    { 10,-15,-16, -2, -4, -9,  7,-15, -6,  2,-16, 13, -8,  7, 19,-21,
-      -4,-12, -9, -3, -3,  6, 11, -3, -1,-19,  3, -7, -9, -4,  3, -6 },
-    { -5,-10,-21,  0, -3, -7, 18,-21, 15, -5,-12, -4,-13,  2,  6, -9,
-      -9,-11, -4, 13, -3,  6,  4, -1,  7, -9, -4,  9,  5,  2,  6,  3 },
-    { 15, -1,-27, -2, 10,  3,  7, -8,  9, -2,  7,  1, -2, -5, 18,  9,
-     -11,-17, -2,  7, -9, 11, 10,  0, -8,  6,-16, -3,  2, -7,  3, 11 },
-    {  4, -9,-39, 19,  6,-13, 13, -5, -5,-15, -2,  9,  0,  4, 14,  6,
-     -10, -4, -5,  2, -4, -2,  5,-11,  3,  3, -2, -2, -7,  9,  7,-10 },
-    {  5,-11, -8, 10, -2, 12, 16,  0, 12, -2, -6,  8, 14,  8,  7,  1,
-      18,-30,  4, 10, -4, -6,  2,-11,  9,-10, -8,  5,  0,  0, -7,  6 },
-    { -1,-16,-10, 11,  0, 13, 12, -4, -4, -5,-21, 12,  4, 13, 14, -7,
-       6,-16,-13,  8,  2,  9, 15,-12,  1, -9,-22, 10, -9,  9,  9, -7 },
-    {  4,-12,-27,  1, -2, 11, 15,  3, 14,-14, -9,  0, -9, 16, 22, 10,
-      16,-10,  5, -5, -9,  1,  1,  6,  6, -4,  2,-17, -5, -6,-15, -1 },
-    {  7,-12,-17,  1, -9,  5, 20, -7,  3, 23, -8, -8, -8, -1, 13, 17,
-      -7,-13,  4, -4,  7, 14,  8, 11, -3, -3,  4,  0,  4,  6, -1, -9 },
-    {  7,-15,-15, -4, 10, 12,  3,-13,  6, 14,  9, -8,-15, 14, 23, -5,
-     -10, -5,  1, 15,-10, -7,  1,  9,  4,-13,-10, 10,  7, -3,  2,  3 },
-    {  4,-10,-14,  0,  3,  4,  0, -9, -3, -4,-11,  2,-17,  8,  2, 15,
-       6,-12,-12, 15, -5, 17, 18,  3, -3, -3, -4, -6, -8, 13,  4, 10 },
-    { -2,-18,-26, 10, -4, 10, 13,  4, -4,-16, -7,-17, -3,  5, -4,  2,
-     -15,-10, -1, -8, -7, -3,  2,  2,  8,-10, -7,  2,  2, -4,  4, -1 },
-    {  4,-19, -5, -1, -1, -6,  2, -8, 10,-16,-28, -6,  8, -1, 11, 28,
-       2,-10, -4,  6, -6,  6, 11, 15, -4, -2,  7,  3,  7, -7,  4,  1 },
-    { -3, -6,-10, -5, 13, 18, 10,-15, -5, -3,-13,  5,  1,  2, 18, -5,
-     -10,-10, -7,  4,  2,  1,  5,  4,  2,  5,  4,  8, -9,-17,  7,  7 },
-    { 20,-12, -2, -4,  5, 14,  7,-11, -1,-16, -6, -4,-11, 17, 14,  0,
-      -8,-10, -8, 10,  3,  5, 10,-16,  3, -8,-14, 10,  3,  9,  0,  3 },
-    { 12,-10,-36,  0,  7, 15,  2,-16,  2, -1,  0, -1,  5,  4,  5, -3,
-       1,-10,  5, -1,-15, -3,-12, 12,  2,  5, -1,  5,  6, -3, -2,  2 },
-    { 17,-15,-31, 23, -4, 15, -2, -3,  6, -7, -5,  1,-12,  4,  6,  8,
-     -10,  8,  3,  5, -4,  1,  5,  3, -1, -4, -3,  1, 10, -4, -2, -2 },
-    {  6,-18, -5, 12, 10, 12, 14,-11, 15,  2, -9, -6, -5, -2, -9,  4,
-      -5,-28, -4, 14,  0,-16,  9, 14, -1,  3, -4, -4,  2,  1,  0,  4 },
-    { -5,-14,-31,  8, 16,  7, 13,-13,  5,  6,-16, 10, -5,  2, -2,  2,
-      14, -5,  8, -5,  7,-16,  6,-13, -5,  0, -5,  8, -3, -1,  4,  3 },
-    {  1, -2, -1,  0,  6,  5,  2, -4, -3, -1,  0,  1,  4,  2, 43, 28,
-     -12,-35, -2, -2, -7, -1,  0,  2, -1, -2, -2,  1, -4,  0, -2,  3 },
-    {  2, -9,-22, 12,  3,  3, -7, -4,-19,-22,-14, -4, -1, 21,  9, -3,
-     -15,-16,-13,  1,-11,  4, -9,  1, -7, -1, -1,  0, -2,  9,-13, -3 },
-    { -1, -3,-23,  0,  2, 12,  3, -9, -4,  7,  3,  9,-10,  1, 27, 28,
-       0,  9,-15, -2, -2,  1,  6,  8, -8,  7, -3, 20,  0,  0, -1, -6 },
-    { -1, 11,  8, -2,  1,  5, -6, -1,  4,  2, -4,  0, -1, -5,  4, -6,
-     -10,-12, 19,  1, -7,  9, -8, -9,-16,-11, -2, 12, 14,  4,  4, 34 },
-    { 17,  7, -6,  1,  4,-10, -5,  4,-11,  3,-18,  4, 14,-13, -3,  1,
-       0,  0,-11,  0,  7,-17, -4,  4,-11, -6, -8, 18,  0,  0,  0, 26 },
-    { -6, -7, -1, -1, 11, -8,  1,  3,  2, 11, -6, -6, 10, -3,  1, -3,
-       7,  4,-12, -8,  0, -9,  8,-22, -5,  0, -6, 22, -2, 11,-13, 24 },
-    { -3,  4,  0,  3,  9, 10, -1,  3, -9,-12,  1, -5, 18,  0, -3,  8,
-      25, 15, -8,  2,  2, -2,  4,  8,  9, -1, -5, 10, -3,  1, -1, 23 },
-    { -5,  2, -9, -1, -3,  0,  3, -1,-10, -4,  0,-13, 16,  9, -1,-14,
-       2,  6, -2, -6, -5, -2, -7,  7,  5,  3, 11, -2,-14,  0, -9, 30 },
-    {  4,  6,  6,  5, -3, -1,  4,  5, 10,  0,  5, -4,  7,-11, 14, 14,
-       7, 34, -9,  0,-10, 22, -7, -1,  7, -9,  2, -8,  0, -7, -5, 29 },
-    { -4,  3, -1, -4, -3,  5,  1, -4,  0,  2,  4,  2,  1, -1,-10,  1,
-       6, -6, -4,  1,  4, -3, -3, -5,  0,  3,  7,-12,  0, -2,-10, 55 },
-    {  5,  9, -1,  0,  4,  9,-21, -9,  4,  2,  6, -7, 11, -7,  1, -5,
-       0, -4,  2, -3,-13, -8,  0, -9, -4,  2, 16, -2,-15, -7,-11, 31 },
-    {  8,  2, -1,  0,  3, -5, -5,  5,  1, -1, -9,  1,  0, -6, -2, -1,
-       5,  2,  0,  0, 12, 20,-19,  1,  8,-12,-11,  0,  6, -5,  2, 31 },
-    { -1, -1, -2,  1, -1,  3, -9, -5,  8, -2,  5, -1,  0, -2,  4, -2,
-      -3,-12,  0, -2,  3,  0,  9,  4, -1, 21, -8,  3, -4,  9, -6, 30 },
-    { -4,  0, -7, 17, 10,-12, -2,-10,-12, -3, 10,  0, 11, -4,-13, -3,
-       5,  6, 10,  7, -8,  0, -7,-13,  1,  0, -2,  7,-12,  4, -3, 24 },
-    {-13,  9,  4, -2,  2, -4,-14, -1, -3, -5,-10,  4, 13, -2,  5, 13,
-       8,  3, -2,  1,  5, -6,  7,-18,-10,  1, -1,  5,  4,  1,  0, 25 },
-    { -5, -1, 18, 12,  8,  8,-16, -1,  1,  1,  1, -4, -5,  3,  3,  4,
-       4,-11,-12,-16, -6,  2, 12,-13,  0,  9,  7,  9, -9,  0,-10, 24 },
-    { -4,  1, -3,  0,  2, -4,  4,  1,  5,  0, -3,  2, -3, -2,  2, -1,
-       1,  4, -1, -2, -2,  1, -1, -1, -4, -1, -4, -2, -6,  6, 12, 69 },
-    {  8,  5, 11,  0,-15, -4, 13,  6,  0, -4,  9,  1, -5, -3, 15,  0,
-       1,  6, -5,  0,  1,  6,  5,  8,  0,  7,  1, -1, -4,-11, -9, 41 },
-    { -4, -9, 32, -6,  0,  7, -4,  6, -6,  1, -6, -2,  4, -8, -5, -3,
-     -16, -1, -2, -6,  1, 15,  0, 21,  3, -3, -4,  3,-12, 16,  2, 27 },
-    { -6, -5,  1, -9, -5,  3,  7, -3,  5,  5, 14, 13, 20, -7, -1, 12,
-      -1, 10,-11,-11, -7, -4,-14,  7,-14, 13, 22, 18, -1,  0, 14, 28 },
-    { -8,  3, -2,  0,  5,  6, -1, -4,  1,  3, -7,  3,  1,-15,  4, -9,
-      22,-10, -9, -4,  1,  8, -4,  9,-15,  2, -6, -4,-16, 12,-10, 23 },
-    {  0,  0,  2,  0, -1,  3, -3, -1,  3, -5,  7,  1,  5, -5, -8,  1,
-      13,-15, -5, -7, 12, -6, -2,  3, 10, -5, -8, 17, -5,-11,-14, 23 },
-    { -7, -4,  6, -4,  5, -6, -5,  2, -4, 11,  9, -4,  2, -2, -4,  6,
-      15,  3, -3, 18,-15, -2, -6,  3,  3,-20, 17, 11, -4,  2,  3, 29 },
-    {  6,  1, -6,  2,  3,  0,  0, -3,  3,  3, -1,  3, -4, -6, -6, -7,
-      -3, -2, -7, -2, -4,  5,  3, -5,-20,-13, -4, 10,-14,-29, 14, 37 },
-    {  3,  4,  3, -6, -4,  5,  0,  3,  2,  3,  0, -2,  4,  0, -3, -5,
-      -4,  4, -4,  4,  4,  3,  1, -4, -4, -9,-14, 20,-30,  3,-18, 33 },
-    {  0,  2,  5, -2, -4, -2, -1,  2, -6, -3, -2, -2,  2, -5, -1,  4,
-       3,  2, -3,  0, -1, -1,-10, -7,  2, -4,-18,  2,-37, -1, 12, 40 },
-    { -7,  2, -1,  0, -2,  4, -8,  1, -4, 12,  7,  4, 15, -7,  1, -9,
-      18,  0, 12,-17, -3, -1,  0,  0,  0,  2, -6,  0, -4, -3, -1, 26 },
-    { -6,  4,  8, -5, -6, -2,  2, -1,  1, -1,-15,  8,  7, -1,-17, -4,
-       1,  5,  6,-11, -6, 14, 17, -5,-15, 11,  8,  0, -3,-15, -6, 28 },
-    { -1,  0,  0,  0,  1,  0, -1,  0,  1,  3,  2, -2,  3, -1, -1,  2,
-       2, -1, -1, -7,  1,  2, -9,  0, -1, -4,-18,  7,-10, 49,-13, 32 },
-    { -1, -3,  4,  1,  2, -5,  1, -7, -1,  5, -9,  4,  4, 25,  1, -1,
-       2, -5,  2, -7, 17, -2, 10, -5,  0,  2,-15,  3, -9,  7, -9, 30 },
-    { -5, -1,  0,  2,  1, -1,  2,  5,-33,  3, -5, 14, 11,  7,  5, -3,
-       2, -8, -4, -2, -7, -6,  4, -8, -1, -8,  2, -2, -8, -1, -4, 27 },
-    { -1,  0, -1, -2,  1, -1, -2, -1,  2,  0,  1,  2,  2,  4,  1,  3,
-       4,  2,  1, -7, -4,  1, -3, -4,-35,-25, 17, 10, -3,-26, -7, 32 },
-    { -5,  1,  6, -2,  6,  6, -9,  3, -1, -4,  5, -4, -2, -2, -9,  2,
-      -5,  2,  2,  4,  3,  5, -5,-16,-31,-12,-11,  2,-19, 20, -2, 21 },
-    { -5,  2,  7, -7, -7,  5, -7,  2,  0,  0, -4,  3, -1,  0, -1, -2,
-       0, -3,  5,-11, -8, -3, -7, -7, 28,-11, -7,  0,-16,-11, -4, 29 },
-    {  2,  1, -3, -2, -1,  3,  4,  0,  1,  0, -1, -5,  4, -5,-12,  2,
-      -2, -5,-22, -2, -1, 11,  8, -7,-12,  0,-34,  6, -5, 11, -8, 19 },
-    { -1, -3,  5, 11, 18, -2, -2, -5, -2,  4, -1,  8,  5, -6,  1, -1,
-       2,  8,  4, -5, -8, -2,  5,-18,  7, 12,  7, 19,-18,  2, -6,-13 },
-    {  9,  0,  0,  5,  4,  3, -6,  4,  1, -4,  5, -1, -4,  8,  8,  6,
-      -8, -6,  0,  6, -3,  3,  5, -3, 17, 31, 16, 10,-13,  0, -9,-19 },
-    { 12,-10,  2, -2, -2, -1, -3,  6,-12, -5, -2, 14,-16,  4, 12, 12,
-      17,  4,  7,-16,  7, -6, 11,  7,  7,  2,-25, 23,-24,  5, -7, -9 },
-    { 10,  4, 13, 10, 10,  3, -6,  3,  3,  2, -1, -6,  8,  4, 10,  0,
-       1,  2, -4,  2, -3, -8,  0, -1,  9,  9,-10, -3,-29,  1, -1,-27 },
-    {  2,  2,  0,  7,  9, -2,-10, -1, -1,  1, -9, -5,  8,  4,  1,  2,
-     -10,  1, 13, 12, -3, 15, -9,  2, -7,  1,-10, 23,-20,-18, -9,-15 },
-    { -3, -5, -1,  8,  0, -5, -1,  4,  7, -1, -7,  2, -8, -5, 11,  7,
-      -6,  3, -3, -9,  7,  9,-22,  1,  6, -4, 14, 27,-25,-14,  3, -5 },
-    {  1,  3,  8,  4,  7,  6, 12,-17,-15,  1, -8,-10,  7,-14, -8,  6,
-      -2, -2,-11,-11, -7, 13, -2, -2,  4,  5, -5, 13,-23, -6,-17, -8 },
-    { -5,  4,-14, -5, -4, -5,  6,  5, -8, -5, -2,-11, -7,-12,  3,-11,
-       2, -6,  4,-10, -5, -7, 14,  5, 23, 11,  7, 12,-16, -6, -4,-16 },
-    {  5,  6,  2,  5, -2, -5, -5, -6, -5,-19,-13, -1, -3,-13,  5,  0,
-       6, -2, -2, -6, -7, -7, -1, -9,  4, 14, 17,-12,-27,  3,  0, -1 },
-    {  7, -1,  9,-10,  8,  2, -7, -2,  5,  2, -3, -7,  3,  0,  6,  4,
-      12,  5, 11, 14,-13, -1,  8,  1, 13,  9, 12, 12,-18,-14,-11,-16 },
-    { -7, -5, -6, -5,  0, -1, -3,  2,  2,  1,  4,  9,  2,  3,  5, -2,
-       2,  1,  8,  0,  3,  0, -2,  2,  1,  7, 29,  0,-36, -5, -9,-21 },
-    { 14, -6, -9,  0, -1, -8, -8,-11,  2,  2, -9,-12, 12, -4,  5,  3,
-      -5, -9, 11, -1, -3, 12,-21, -3, 12,  5,  3, 11,-18,-15,  1, -2 },
-    { -1,  3, -9, -3,  7, -7,-18,  2,  4, 12,-10,  2,  8, -3,-14, 13,
-      17, -5,  5, -9, 13, -3, -7,-18, 17, -2,  5,  7,-20, -3, -6,-11 },
-    { -3,  3,  3, -1,  1, -6, -5,  1,  5, -3,-14, -6, -5, -8, 14, -6,
-       7, -1,  5,  1, 15, -1, -7, -4,  6,-11,  9, -2,-37, 16, -7, -3 },
-    { -1,  0,  6,  1, -3, -9,  0, 11, -8,  2, -2,  0,  5,  2, 12,-10,
-      10, 13,  2,  7, -6,  2,-10,-10, 21, -5,  5,  5,-12,-23,  3,-14 },
-    {  6,  0, -2,  1,  0,  1,  0, -4,  1,  1,  8, -2,  2, -5, -2,  1,
-       8, -4, -1, -1,  4, -1,  2,  6, 32,  1, -5,-20,-40, -4,-18,-14 },
-    {  2,  2, -7, -2,  4,  4, -1,  2,  0, -2, -4, -7,  3,  5,  0, -5,
-       1,  2, -6,  4, -1, -2, -1,-15,  8,  3,  9, 46, -7,-18,  6,-11 },
-    {  5,  5, 16, 21,  3,-11, -4, 11,-12,  2,  4,-12, -1, 11,  8,  1,
-      -4, 11,-11,-21,  1,  1,-11,  3, 13,  1,  5, 12,-25,  1, -3, -2 },
-    {  1,  6, -7,  4,  2,  3,  1, -5,  8,  9,-15,  3, -3,-14, 17,  4,
-      -8, 14, -2, -8, -4,  5,  8, -7,  8,  9,  7,  6,-29,-17,  8,  4 },
-    { -7, -7,  4,  0, 13,  1,  0,  4,  4,-16,-10, -7,  5,  9,-15,-10,
-     -10,  8, -4, -1,-11, -1,-10,-15,  3,  3, 14, 10,-19,  2,-18,-12 },
-    { -4,  0,  2,  0,  5, -2, -9,  0,  4, -4,  2, -1, -2,  2, -4,  9,
-       2, -6, -4, -2, -1, -3, -3, -1,  2,  5, -1, 11,-24,-44, -9,-15 },
-    { -1,-10,  6, 21, 11, 15, -7, 10,-14, -9, -8, -8,  4,  6, 19,  1,
-      -6,  1, -5,-17, -8,-10,  9,  5, 11, 18, -1, 10,-16, -7, -9, -8 },
-    {  3, -5,  0,  0, -2, -2, -6,  4, -4,  1, -1,  0,  7, -3,  4, -4,
-      -7,  7, 17,-20,  6,  4,  1, -6,-12, 31, 13, 19,-14,-10, -7, -2 },
-    { -2,  6,-10,  3,  9,  6,-14, 15,  2, -5,  2,-11,  9, -8,  4,  6,
-      20,-15, -3, -3, -1, 32,-21,  6,  1,  9, 11, 17,-19,  6, -1, -3 },
-    {  8, 10, -2,  0, -8,-16,  7,  7,  6, 10,  4,-14,  7, -6, 21, -7,
-      10,  5,  5,  0, -7,  2, -6,  0, -7, 11, -9, 15,-20, -7,-11,  2 },
-    {  0, -7,  5,  2,  0, -3, -6, -4, -2, -1, -4, -5,-13, -1, 27, -9,
-      -6,-11, -7,  1, 11, -4, -4,-14, -2, 11,  6, 10,-19, -6,-15,  2 },
-    {  0,  7, -1,  2, -7,-15, -2, -3, 13, -5, -5, 12,  3,  0,  5, -5,
-     -22,  2,  7, 22, 13,  0, -1,  2,  3,  2, -7,  7,-27, -4, -4,-12 },
-    { 11,  1,-16,  6,-15,  1,  3,  2,  0,  2, -3,  2,  5, -2, -5,  9,
-       5, -3,  3, -2,-11,  3,  9,  6,  9,  3, -1, 12,-41,  8, -6,  9 },
-    {  3, -7,  3,  2,  5,  5,  0, -1,  1,  3, -5, -2,-13,  7, -1, -2,
-      -2, -6,  4, -6,  0,  2, -2,  2,  4,  1, -4,  1,-47,-21,  7, -6 },
-    {  3, 16, -7, 13, -4, -2, 10, -3, -1, 18,-13,  7,-13, -4,  8,  4,
-       8,  9, -5, 13,  8, -5,  3, -6,  7, 18, -8, 10,-25, -3,-12,-12 },
-    {  1, -1, -1,  0,  2,  5, -5, -3,  0, -5, -1,  0, -4, -8, -2,  3,
-       2, -2,-17, -6, -4,  1, 33, -6,-20, -6,  8, 31,-26, -8, -1, -4 },
-    {  3, -3, -3,  5, -3, -2,  1,  7,  0,  3,  6,  3,  6, -2,  9, 15,
-     -10, -3,-15, -5, -3, -4, -6,-30, 17, -8, -2,  2,-20,  0, -8, -2 },
-    { -2, -1, -1, -1,  3, -5, -2, -3,  4, -2,  0,  5,  8, -3,  1, -4,
-       1,  1, -3,  4,  4,-14,  3, 11, -5,  3, -3,  7, -3, 13, 23,-16 },
-    {  2, -6,  1, -3,  5,  0, -6,-11, -7, -4, -1,  2, -7, -1, -1,  7,
-       1, -2,  6, 12, -6,  8,-13, 17, 25,-23,-19, -7,-12,  9, 16,-17 },
-    {  9,  4,  4,  4, -3, -1,  6, -2, -3,  0, 13, -4, -7, 14,  1, -7,
-       0, -5,  3,-19, -3,  5,  3,  9, -1,  9,-13, 13,-17,  4, 21,-26 },
-    {  0, -5,  0,  0, -4, -5,  2, -6, -4,  5, -7, 10,  0,  2,  0, -2,
-      -2,  0,  4, -6,  7, -2,  6,  5, -5,  2,-12,  1,-29, 29, 27, 12 },
-    {  9,-10,-22,  6, -1, -1,  9,-14,-12, -2,  1, -1, 10,-11,-16,  0,
-       3, 11, 13,-14, -9, -2, -1,  6,  4,-14,  0,-10, -2, 16, 17,-11 },
-    {  2,  0, -1, -2,  4,  3, -6, -2,  1, -1,  1,  3, -4,  1,  3, -4,
-      -1, -1,  4, -1,  1,  0,  1,  6, -5, -7,  2,  1,-47, -3, 50,-17 },
-    {  8, -4,-11, -7, 11, 11, 14, -7, 12, -7,  6,  2, 13, -6, -3, -2,
-     -14,  6,  6,  6,  0,  2, -1,  5,-20,  2, -1,  4, -5,  6, 21,-11 },
-    { -2, -9,  3,  0, -6,  7,  8, -8,  1, -3,  4,  1,  5, -2, -3, -7,
-       4,  7,-12, -9, -2, 10, -6, 13,  6,  5, 20,  2,-15,  9, 28, -7 },
-    {  0, -5, -6, -6, -6,  1, -6,  6, -2,  4,  8, -3, 12, -1, -4, -2,
-       6, 16,-14,  9,-14, -2, -8,-27, -3, 18, -1, -7, -3,  8, 23,-23 },
-    {  1,  4, -9, -1, -5, 10, -2,  1,-11,  1, -9,  4,  7, 14, -9, -2,
-      -3,  2, -5, -1, -6,-10, -7, 11, 20,  2,  3,-19,  3, 15, 30, -9 },
-    {  7,  2,-14, -4,  0, -2,  5,  2,  5, -2,  8, -3, -7,  6,  6,-11,
-     -14,  1, 10, -1, -7, -8,  1, 10,  3, -6,-15,-12,-17,  4, 30, -6 },
-    {  4,  2,  1, -2,  3,  0,  1,  0,  2,  0,  1,  6, -7,  0,  3,  4,
-       4, -4, -2, -5, -2,  2, -1, -2,  0, -2,-11, -7, -3, 42, 24,-14 },
-    {  4,  1,  3,  2,  0, -2, -3, -2,  2, -1,  4, 11, -2,  2,  3, -4,
-      -5,  9,  2, -4, -9,  5,  8, -1, -7,  1, 24,-13,-28, 20, 15,-22 },
-    { -3,  7,  6,  3, -2, -5,-10, -2, -2, -1, -6, -6, -2,-14,-16, -6,
-      -5,  0, 18,  0,  9,  1,  7,-13, -5, -6, -9, 11,-15,  9, 22,-11 },
-    {  9, -2,  6,  5,  2,  9,-10,  1,  1,  5, -4, 12,  2,  2,-10, -7,
-      -4, -6,  7,  9,  6, 15,  6,  6,-10, 10,  5,-13, -5,  6, 24,-12 },
-    {  1,  3, -3, -3,  8,  1, -6,  2, -5, -3,  7,  2, 14,  6,  9, -6,
-      -5, -4, 27,  7, -3,  8, -6,  3, -8,  8, 22, -5, -6, -2, 22,-17 },
-    { -2, -2,  3, 10,  9,  9, 12,-15, -1,-11,-13,  3, -2,  1, -3,-11,
-       7,  9, 16, -3,-10, -5, -5,  1,  8, -3,  9,  9, -5,  3, 31,-12 },
-    {  7, -5, 10, -4, -8,  2, 16, -2, 10, 10, -3, -2,  3, -8, -3,  3,
-     -13, -6, 15, 20, -9, -3,-12,  1, -2,-16,  8,  8, -1, 16, 22, -5 },
-    {  5, -3,-15, -2, 12, -8,  8, -5,  2, -8, 20,-18, 14, -4,  3,  3,
-       7,-13,-16,  1,-10,  7, 16,  7,  4,-14, -4, -5, -9,  8, 23, -6 },
-    {  5, -4, -5, -4,  1,  8,  4, -7, -5,  8, 10,  6, -6,-10, -2,  6,
-       9,-17,-14, 11, 12, -3,-13, -7,  2, 18,  3,-25,-16, 18, 22, -5 },
-    {  5,  6, -7,-20, -4,  2,  8,  4,-24, -4,  1,  4, -5, -2,  1,-10,
-      -2,  9,  3, -4, -3, -4, -4, -4, 10, 10,  3,  0, -6, 25, 21,-11 },
-    {  0,  7, -1, 14, -6, -4,-10,  5,  4,  4,  4, -5,  3,  4, -1, -7,
-       8,-19,  0,  6,  2,  3,-18, -3, -6,  2,  8, 14,-26, 22, 27,-13 },
-    { -2, -6,  7, -5, 12, -7,  8, -1,  3, -2,  4,  1,  8, -2,  0, 14,
-       6, -5,  6, -4, -7,  7,-21,  8,  1,  8, -9, -4, -3, 11, 25,-13 },
-    {  4,  4, -1, -6,  4,  9, -8,  1, -3,-10, -2,  0, 15, -9,-16, 11,
-       1,  1,  6,  3, -9, -5, 16, 26,  1,-14,  1, -3,-14,  7, 15, -9 },
-    {-12, -2, -9,-13,  2,  6, 14,  0,  1,  0, -1,-13,  0, 10, -1,  6,
-       9, -7,  8,  8, 19,  6, -1,  9, 10, -4,  1, -7,-22, -2, 29, -7 },
-    {  2,  4, 13,-12, -8, -4, -5, 13, 12, -5, -3, -3, -4,  1, -1, 10,
-      15, -6, -1,-11,-30,  4, 15, -1,  9, -7,  0, -2, -7, 10, 25,-16 },
-    {  7,-15, -7, -7, -1, -5, -5,-11,-20, 10,  3,-10, -3,  5, 20, -4,
-       0, -2, -2, 17,  2,  0, -3,  3,  6,  5, -1,-12, -3, 15, 22,-16 },
-    {  4, -1,  3,  4, -5,  0, -1, -5,-24,-29,  4, -9,  1, -3,  0,  0,
-       0, -4,  7, -4, -4, -4,  3,  1, -6,  5, -3, -5,-10,  3, 25,-10 },
-    { -2, -1, -1,  4,  4, -1,  2,  0, -4, -4,  2, -1, -3, -1, -2, -2,
-       1, -3, -5, -1,  2, -3, -4, -4, -3,  5, -9,  1,-11,  7, 46,-46 },
-    {  0, -9,  3,  4,  4,  3, -5, -6,  5, -4,  4, -2,  1,  7, -4,-10,
-      13,  1,  3, -6,  4, -4,  7,  2,-19,-25, -3,-16,-12, 16, 20, -1 },
-    { 18,  6,  4,-12,  0,-14,  9, -6, -1, -4, -5,  2,  1, 12,  4,  2,
-       7,  0,  2,  5,-11, -5, -2,  2, -4, 10,  0, -9, -7,  9, 25, -8 },
-    {  5,  0, -6,  5,  6,  3,  3,-10, -5,  1, -1,  4,  3,-11, -8,  5,
-       4, -5,  5, -5, -7, -5, 11,  5, 20, -8,-16, 21, -4, 27, 23, -5 }
-};
+extern const int32_t ff_dca_sampling_freqs[16];
 
-/* FIR filter coefficients, they can be cut on half and maybe use float instead of double */
+extern const int8_t ff_dca_lfe_index[16];
 
-DECLARE_ALIGNED(16, static const float, fir_32bands_perfect)[] = {
-    +1.135985195E-010,
-    +7.018770981E-011,
-    -1.608403011E-008,
-    -5.083275667E-008,
-    -1.543309907E-007,
-    -3.961981463E-007,
-    -7.342250683E-007,
-    -3.970030775E-007,
-    -4.741137047E-007,
-    -6.022448247E-007,
-    -6.628192182E-007,
-    -6.982898526E-007,
-    -7.020648809E-007,
-    -6.767839409E-007,
-    -6.262345096E-007,
-    -5.564140224E-007,
-    +7.003467317E-007,
-    +8.419976893E-007,
-    +9.742954035E-007,
-    +1.085227950E-006,
-    +1.162929266E-006,
-    +1.194632091E-006,
-    +1.179182050E-006,
-    +1.033426656E-006,
-    +9.451737242E-007,
-    +1.975324267E-006,
-    +1.190443072E-006,
-    +5.234479659E-007,
-    +2.014677420E-007,
-    +7.834767501E-008,
-    -6.702406963E-010,
-    -1.613285505E-009,
-    -2.682709610E-009,
-    -3.399493131E-009,
-    +1.314406006E-008,
-    +7.506701927E-009,
-    +2.788728892E-008,
-    +1.444918922E-007,
-    +3.132386439E-007,
-    +1.399798180E-006,
-    +2.032118118E-006,
-    +2.715013807E-006,
-    +3.453840463E-006,
-    +4.195037945E-006,
-    +4.896494374E-006,
-    +5.516381407E-006,
-    +6.015239251E-006,
-    +6.361419310E-006,
-    +8.006985809E-006,
-    +8.087732567E-006,
-    +7.941360309E-006,
-    +7.568834008E-006,
-    +6.986399967E-006,
-    +6.225028756E-006,
-    +5.315936960E-006,
-    +4.429412002E-006,
-    +3.332600045E-006,
-    +8.427224429E-007,
-    +4.341498823E-007,
-    +9.458596395E-008,
-    +2.975164826E-008,
-    +6.402664354E-008,
-    -3.246264413E-008,
-    -3.809887872E-008,
-    +8.434094667E-008,
-    +6.437721822E-008,
-    +1.189317118E-006,
-    +2.497214155E-006,
-    +3.617151151E-006,
-    +3.157242645E-006,
-    +2.319611212E-006,
-    +7.869333785E-006,
-    +9.826449968E-006,
-    +1.177108606E-005,
-    +1.379448349E-005,
-    +1.571428584E-005,
-    +1.743183020E-005,
-    +1.884208177E-005,
-    +1.987093310E-005,
-    +2.042970118E-005,
-    -3.144468428E-005,
-    -3.334947178E-005,
-    -3.460439257E-005,
-    -3.515914432E-005,
-    -3.495384954E-005,
-    -3.397853652E-005,
-    -3.225446198E-005,
-    -2.978993689E-005,
-    -2.677291741E-005,
-    -1.806914770E-005,
-    -1.776598037E-005,
-    -1.661818715E-005,
-    -1.207003334E-005,
-    -6.993315310E-006,
-    -5.633860383E-007,
-    -9.984935332E-007,
-    -1.470520488E-006,
-    -1.853591357E-006,
-    +7.198007665E-007,
-    +3.086857760E-006,
-    +6.084746474E-006,
-    +9.561075785E-006,
-    +1.309637537E-005,
-    +2.263354872E-005,
-    +2.847247197E-005,
-    +3.415624451E-005,
-    +3.946387005E-005,
-    +4.425736552E-005,
-    +4.839275425E-005,
-    +5.176846025E-005,
-    +5.429694284E-005,
-    +5.595519906E-005,
-    +4.916387297E-006,
-    +9.299508747E-006,
-    +1.356193479E-005,
-    +1.751866148E-005,
-    +2.093936746E-005,
-    +2.362549276E-005,
-    +2.537086584E-005,
-    +2.618136386E-005,
-    +2.554462844E-005,
-    +3.018750249E-005,
-    +2.570833203E-005,
-    +1.985177369E-005,
-    +1.191342653E-005,
-    +2.525620175E-006,
-    -1.521241393E-005,
-    -1.617751332E-005,
-    +1.992636317E-005,
-    +1.774702469E-005,
-    +4.624524081E-005,
-    +5.610509834E-005,
-    +6.568001118E-005,
-    +7.513730816E-005,
-    +8.413690375E-005,
-    +8.757545584E-005,
-    +9.517164290E-005,
-    +1.020687996E-004,
-    +1.084438481E-004,
-    +1.140582463E-004,
-    +1.187910311E-004,
-    +1.224978914E-004,
-    +1.250260248E-004,
-    +1.262027217E-004,
-    +1.226499153E-004,
-    +1.213575742E-004,
-    +1.180980107E-004,
-    +1.126275165E-004,
-    +1.047207043E-004,
-    +9.417100227E-005,
-    +8.078388782E-005,
-    +6.447290798E-005,
-    +4.491530854E-005,
-    +2.470704203E-005,
-    -1.714242217E-006,
-    -3.193307566E-005,
-    -6.541742187E-005,
-    -1.024175072E-004,
-    -1.312203676E-004,
-    -1.774113771E-004,
-    -2.233728592E-004,
-    -2.682086197E-004,
-    -3.347633174E-004,
-    -3.906481725E-004,
-    -4.490280990E-004,
-    -5.099929986E-004,
-    -5.729619297E-004,
-    -6.358824321E-004,
-    -7.021900383E-004,
-    -7.698345580E-004,
-    -8.385353722E-004,
-    -9.078957955E-004,
-    -9.775133803E-004,
-    -1.046945457E-003,
-    -1.115717343E-003,
-    -1.183370827E-003,
-    -1.252829796E-003,
-    -1.316190348E-003,
-    -1.376571832E-003,
-    -1.433344092E-003,
-    -1.485876855E-003,
-    -1.533520175E-003,
-    -1.575609902E-003,
-    -1.611457788E-003,
-    -1.640390139E-003,
-    -1.661288203E-003,
-    -1.674512983E-003,
-    -1.678415807E-003,
-    -1.672798418E-003,
-    -1.656501088E-003,
-    -1.633993932E-003,
-    -1.593449386E-003,
-    +1.542080659E-003,
-    +1.479332102E-003,
-    +1.395521569E-003,
-    +1.303116791E-003,
-    +1.196175464E-003,
-    +1.073757303E-003,
-    +9.358961834E-004,
-    +7.817269652E-004,
-    +6.114174030E-004,
-    +4.244441516E-004,
-    +2.206075296E-004,
-    -2.719412748E-007,
-    -2.382978710E-004,
-    -4.935106263E-004,
-    -7.658848190E-004,
-    -1.055365428E-003,
-    -1.361547387E-003,
-    -1.684492454E-003,
-    -2.023874084E-003,
-    -2.379294252E-003,
-    -2.750317100E-003,
-    -3.136433195E-003,
-    -3.537061159E-003,
-    -3.951539751E-003,
-    -4.379155114E-003,
-    -4.819062538E-003,
-    -5.270531867E-003,
-    -5.732392892E-003,
-    -6.203945260E-003,
-    -6.683901884E-003,
-    -7.170005701E-003,
-    -7.664063945E-003,
-    -8.162760176E-003,
-    -8.665001951E-003,
-    -9.170533158E-003,
-    -9.676489048E-003,
-    -1.018219907E-002,
-    -1.068630442E-002,
-    -1.118756086E-002,
-    -1.168460958E-002,
-    -1.217562053E-002,
-    -1.265939046E-002,
-    -1.313448418E-002,
-    -1.359948888E-002,
-    -1.405300573E-002,
-    -1.449365262E-002,
-    -1.492007636E-002,
-    -1.533095632E-002,
-    -1.572482102E-002,
-    -1.610082202E-002,
-    -1.645756140E-002,
-    -1.679391414E-002,
-    -1.710879989E-002,
-    -1.740120351E-002,
-    -1.767017506E-002,
-    -1.791484281E-002,
-    -1.813439466E-002,
-    -1.832821220E-002,
-    -1.849545911E-002,
-    -1.863567345E-002,
-    -1.874836907E-002,
-    -1.883326657E-002,
-    -1.889026538E-002,
-    -1.891860925E-002,
-    +1.891860925E-002,
-    +1.889026538E-002,
-    +1.883326657E-002,
-    +1.874836907E-002,
-    +1.863567345E-002,
-    +1.849545911E-002,
-    +1.832821220E-002,
-    +1.813439466E-002,
-    +1.791484281E-002,
-    +1.767017506E-002,
-    +1.740120351E-002,
-    +1.710879989E-002,
-    +1.679391414E-002,
-    +1.645756140E-002,
-    +1.610082202E-002,
-    +1.572482102E-002,
-    +1.533095632E-002,
-    +1.492007636E-002,
-    +1.449365262E-002,
-    +1.405300573E-002,
-    +1.359948888E-002,
-    +1.313448418E-002,
-    +1.265939046E-002,
-    +1.217562053E-002,
-    +1.168460958E-002,
-    +1.118756086E-002,
-    +1.068630442E-002,
-    +1.018219907E-002,
-    +9.676489048E-003,
-    +9.170533158E-003,
-    +8.665001951E-003,
-    +8.162760176E-003,
-    +7.664063945E-003,
-    +7.170005701E-003,
-    +6.683901884E-003,
-    +6.203945260E-003,
-    +5.732392892E-003,
-    +5.270531867E-003,
-    +4.819062538E-003,
-    +4.379155114E-003,
-    +3.951539751E-003,
-    +3.537061159E-003,
-    +3.136433195E-003,
-    +2.750317100E-003,
-    +2.379294252E-003,
-    +2.023874084E-003,
-    +1.684492454E-003,
-    +1.361547387E-003,
-    +1.055365428E-003,
-    +7.658848190E-004,
-    +4.935106263E-004,
-    +2.382978710E-004,
-    +2.719412748E-007,
-    -2.206075296E-004,
-    -4.244441516E-004,
-    -6.114174030E-004,
-    -7.817269652E-004,
-    -9.358961834E-004,
-    -1.073757303E-003,
-    -1.196175464E-003,
-    -1.303116791E-003,
-    -1.395521569E-003,
-    -1.479332102E-003,
-    -1.542080659E-003,
-    +1.593449386E-003,
-    +1.633993932E-003,
-    +1.656501088E-003,
-    +1.672798418E-003,
-    +1.678415807E-003,
-    +1.674512983E-003,
-    +1.661288203E-003,
-    +1.640390139E-003,
-    +1.611457788E-003,
-    +1.575609902E-003,
-    +1.533520175E-003,
-    +1.485876855E-003,
-    +1.433344092E-003,
-    +1.376571832E-003,
-    +1.316190348E-003,
-    +1.252829796E-003,
-    +1.183370827E-003,
-    +1.115717343E-003,
-    +1.046945457E-003,
-    +9.775133803E-004,
-    +9.078957955E-004,
-    +8.385353722E-004,
-    +7.698345580E-004,
-    +7.021900383E-004,
-    +6.358824321E-004,
-    +5.729619297E-004,
-    +5.099929986E-004,
-    +4.490280990E-004,
-    +3.906481725E-004,
-    +3.347633174E-004,
-    +2.682086197E-004,
-    +2.233728592E-004,
-    +1.774113771E-004,
-    +1.312203676E-004,
-    +1.024175072E-004,
-    +6.541742187E-005,
-    +3.193307566E-005,
-    +1.714242217E-006,
-    -2.470704203E-005,
-    -4.491530854E-005,
-    -6.447290798E-005,
-    -8.078388782E-005,
-    -9.417100227E-005,
-    -1.047207043E-004,
-    -1.126275165E-004,
-    -1.180980107E-004,
-    -1.213575742E-004,
-    -1.226499153E-004,
-    -1.262027217E-004,
-    -1.250260248E-004,
-    -1.224978914E-004,
-    -1.187910311E-004,
-    -1.140582463E-004,
-    -1.084438481E-004,
-    -1.020687996E-004,
-    -9.517164290E-005,
-    -8.757545584E-005,
-    -8.413690375E-005,
-    -7.513730816E-005,
-    -6.568001118E-005,
-    -5.610509834E-005,
-    -4.624524081E-005,
-    -1.774702469E-005,
-    -1.992636317E-005,
-    +1.617751332E-005,
-    +1.521241393E-005,
-    -2.525620175E-006,
-    -1.191342653E-005,
-    -1.985177369E-005,
-    -2.570833203E-005,
-    -3.018750249E-005,
-    -2.554462844E-005,
-    -2.618136386E-005,
-    -2.537086584E-005,
-    -2.362549276E-005,
-    -2.093936746E-005,
-    -1.751866148E-005,
-    -1.356193479E-005,
-    -9.299508747E-006,
-    -4.916387297E-006,
-    -5.595519906E-005,
-    -5.429694284E-005,
-    -5.176846025E-005,
-    -4.839275425E-005,
-    -4.425736552E-005,
-    -3.946387005E-005,
-    -3.415624451E-005,
-    -2.847247197E-005,
-    -2.263354872E-005,
-    -1.309637537E-005,
-    -9.561075785E-006,
-    -6.084746474E-006,
-    -3.086857760E-006,
-    -7.198007665E-007,
-    +1.853591357E-006,
-    +1.470520488E-006,
-    +9.984935332E-007,
-    +5.633860383E-007,
-    +6.993315310E-006,
-    +1.207003334E-005,
-    +1.661818715E-005,
-    +1.776598037E-005,
-    +1.806914770E-005,
-    +2.677291741E-005,
-    +2.978993689E-005,
-    +3.225446198E-005,
-    +3.397853652E-005,
-    +3.495384954E-005,
-    +3.515914432E-005,
-    +3.460439257E-005,
-    +3.334947178E-005,
-    +3.144468428E-005,
-    -2.042970118E-005,
-    -1.987093310E-005,
-    -1.884208177E-005,
-    -1.743183020E-005,
-    -1.571428584E-005,
-    -1.379448349E-005,
-    -1.177108606E-005,
-    -9.826449968E-006,
-    -7.869333785E-006,
-    -2.319611212E-006,
-    -3.157242645E-006,
-    -3.617151151E-006,
-    -2.497214155E-006,
-    -1.189317118E-006,
-    -6.437721822E-008,
-    -8.434094667E-008,
-    +3.809887872E-008,
-    +3.246264413E-008,
-    -6.402664354E-008,
-    -2.975164826E-008,
-    -9.458596395E-008,
-    -4.341498823E-007,
-    -8.427224429E-007,
-    -3.332600045E-006,
-    -4.429412002E-006,
-    -5.315936960E-006,
-    -6.225028756E-006,
-    -6.986399967E-006,
-    -7.568834008E-006,
-    -7.941360309E-006,
-    -8.087732567E-006,
-    -8.006985809E-006,
-    -6.361419310E-006,
-    -6.015239251E-006,
-    -5.516381407E-006,
-    -4.896494374E-006,
-    -4.195037945E-006,
-    -3.453840463E-006,
-    -2.715013807E-006,
-    -2.032118118E-006,
-    -1.399798180E-006,
-    -3.132386439E-007,
-    -1.444918922E-007,
-    -2.788728892E-008,
-    -7.506701927E-009,
-    -1.314406006E-008,
-    +3.399493131E-009,
-    +2.682709610E-009,
-    +1.613285505E-009,
-    +6.702406963E-010,
-    -7.834767501E-008,
-    -2.014677420E-007,
-    -5.234479659E-007,
-    -1.190443072E-006,
-    -1.975324267E-006,
-    -9.451737242E-007,
-    -1.033426656E-006,
-    -1.179182050E-006,
-    -1.194632091E-006,
-    -1.162929266E-006,
-    -1.085227950E-006,
-    -9.742954035E-007,
-    -8.419976893E-007,
-    -7.003467317E-007,
-    +5.564140224E-007,
-    +6.262345096E-007,
-    +6.767839409E-007,
-    +7.020648809E-007,
-    +6.982898526E-007,
-    +6.628192182E-007,
-    +6.022448247E-007,
-    +4.741137047E-007,
-    +3.970030775E-007,
-    +7.342250683E-007,
-    +3.961981463E-007,
-    +1.543309907E-007,
-    +5.083275667E-008,
-    +1.608403011E-008,
-    -7.018770981E-011,
-    -1.135985195E-010
-};
+extern const int8_t ff_dca_channel_reorder_lfe[16][9];
+extern const int8_t ff_dca_channel_reorder_lfe_xch[16][9];
+extern const int8_t ff_dca_channel_reorder_nolfe[16][9];
+extern const int8_t ff_dca_channel_reorder_nolfe_xch[16][9];
 
-DECLARE_ALIGNED(16, static const float, fir_32bands_nonperfect)[] = {
-    -1.390191784E-007,
-    -1.693738625E-007,
-    -2.030677564E-007,
-    -2.404238444E-007,
-    -2.818143514E-007,
-    -3.276689142E-007,
-    -3.784752209E-007,
-    -4.347855338E-007,
-    -4.972276315E-007,
-    -5.665120852E-007,
-    -6.434325428E-007,
-    -7.288739425E-007,
-    -8.238164355E-007,
-    -9.293416952E-007,
-    -1.046637067E-006,
-    -1.176999604E-006,
-    -1.321840614E-006,
-    -1.482681114E-006,
-    -1.661159786E-006,
-    -1.859034001E-006,
-    -2.078171747E-006,
-    -2.320550948E-006,
-    -2.588257530E-006,
-    -2.883470643E-006,
-    -3.208459020E-006,
-    -3.565570978E-006,
-    -3.957220997E-006,
-    -4.385879038E-006,
-    -4.854050530E-006,
-    -5.364252502E-006,
-    -5.918994248E-006,
-    -6.520755960E-006,
-    -7.171964626E-006,
-    -7.874960829E-006,
-    -8.631964192E-006,
-    -9.445050637E-006,
-    -1.031611009E-005,
-    -1.124680875E-005,
-    -1.223855270E-005,
-    -1.329243969E-005,
-    -1.440921824E-005,
-    -1.558924305E-005,
-    -1.683242772E-005,
-    -1.813820381E-005,
-    -1.950545993E-005,
-    -2.093250441E-005,
-    -2.241701623E-005,
-    -2.395598858E-005,
-    -2.554569073E-005,
-    -2.718161704E-005,
-    -2.885844333E-005,
-    -3.056998685E-005,
-    -3.230916263E-005,
-    -3.406793985E-005,
-    -3.583733633E-005,
-    -3.760734762E-005,
-    -3.936696885E-005,
-    -4.110412556E-005,
-    -4.280570283E-005,
-    -4.445751256E-005,
-    -4.604430433E-005,
-    -4.754976908E-005,
-    -4.895655002E-005,
-    -5.024627535E-005,
-    +5.139957648E-005,
-    +5.239612074E-005,
-    +5.321469871E-005,
-    +5.383323878E-005,
-    +5.422891263E-005,
-    +5.437819709E-005,
-    +5.425697600E-005,
-    +5.384063843E-005,
-    +5.310418419E-005,
-    +5.202236207E-005,
-    +5.056979353E-005,
-    +4.872112549E-005,
-    +4.645117951E-005,
-    +4.373511547E-005,
-    +4.054862075E-005,
-    +3.686808850E-005,
-    +3.267079956E-005,
-    +2.793515523E-005,
-    +2.264085742E-005,
-    +1.676913780E-005,
-    +1.030297699E-005,
-    +3.227306706E-006,
-    -4.470633485E-006,
-    -1.280130618E-005,
-    -2.177240640E-005,
-    -3.138873581E-005,
-    -4.165195787E-005,
-    -5.256036457E-005,
-    -6.410864444E-005,
-    -7.628766616E-005,
-    -8.908427117E-005,
-    -1.024810626E-004,
-    -1.164562127E-004,
-    -1.309833024E-004,
-    -1.460311323E-004,
-    -1.615635992E-004,
-    -1.775395358E-004,
-    -1.939126523E-004,
-    -2.106313768E-004,
-    -2.276388550E-004,
-    -2.448728774E-004,
-    -2.622658503E-004,
-    -2.797449124E-004,
-    -2.972317743E-004,
-    -3.146430245E-004,
-    -3.318900708E-004,
-    -3.488793736E-004,
-    -3.655125911E-004,
-    -3.816867538E-004,
-    -3.972945851E-004,
-    -4.122247046E-004,
-    -4.263620067E-004,
-    -4.395879805E-004,
-    -4.517810594E-004,
-    -4.628172028E-004,
-    -4.725702747E-004,
-    -4.809123348E-004,
-    -4.877146275E-004,
-    -4.928477574E-004,
-    -4.961824161E-004,
-    -4.975944757E-004,
-    -4.969481961E-004,
-    -4.941228544E-004,
-    -4.889960401E-004,
-    +4.814492422E-004,
-    +4.713678791E-004,
-    +4.586426076E-004,
-    +4.431701091E-004,
-    +4.248536134E-004,
-    +4.036037717E-004,
-    +3.793396754E-004,
-    +3.519894381E-004,
-    +3.214911267E-004,
-    +2.877934603E-004,
-    +2.508567995E-004,
-    +2.106537577E-004,
-    +1.671699720E-004,
-    +1.204049113E-004,
-    +7.037253090E-005,
-    +1.710198012E-005,
-    -3.936182839E-005,
-    -9.895755647E-005,
-    -1.616069785E-004,
-    -2.272142592E-004,
-    -2.956659591E-004,
-    -3.668301215E-004,
-    -4.405563814E-004,
-    -5.166754709E-004,
-    -5.949990009E-004,
-    -6.753197522E-004,
-    -7.574109477E-004,
-    -8.410271257E-004,
-    -9.259034996E-004,
-    -1.011756598E-003,
-    -1.098284614E-003,
-    -1.185167348E-003,
-    -1.272067428E-003,
-    -1.358630019E-003,
-    -1.444484224E-003,
-    -1.529243193E-003,
-    -1.612505526E-003,
-    -1.693855622E-003,
-    -1.772865304E-003,
-    -1.849094522E-003,
-    -1.922092517E-003,
-    -1.991399564E-003,
-    -2.056547208E-003,
-    -2.117061289E-003,
-    -2.172462177E-003,
-    -2.222266514E-003,
-    -2.265989315E-003,
-    -2.303145360E-003,
-    -2.333251061E-003,
-    -2.355825622E-003,
-    -2.370394068E-003,
-    -2.376487479E-003,
-    -2.373647178E-003,
-    -2.361423569E-003,
-    -2.339380793E-003,
-    -2.307097195E-003,
-    -2.264167881E-003,
-    -2.210205887E-003,
-    -2.144844970E-003,
-    -2.067740774E-003,
-    -1.978572691E-003,
-    -1.877046190E-003,
-    -1.762894331E-003,
-    -1.635878929E-003,
-    +1.495792647E-003,
-    +1.342460280E-003,
-    +1.175740734E-003,
-    +9.955273708E-004,
-    +8.017504588E-004,
-    +5.943773431E-004,
-    +3.734139318E-004,
-    +1.389056415E-004,
-    -1.090620208E-004,
-    -3.703625989E-004,
-    -6.448282511E-004,
-    -9.322494152E-004,
-    -1.232374110E-003,
-    -1.544908970E-003,
-    -1.869517611E-003,
-    -2.205822384E-003,
-    -2.553403843E-003,
-    -2.911801683E-003,
-    -3.280514618E-003,
-    -3.659002949E-003,
-    -4.046686925E-003,
-    -4.442950245E-003,
-    -4.847140983E-003,
-    -5.258570891E-003,
-    -5.676518660E-003,
-    -6.100233644E-003,
-    -6.528933067E-003,
-    -6.961807609E-003,
-    -7.398022339E-003,
-    -7.836719044E-003,
-    -8.277016692E-003,
-    -8.718019351E-003,
-    -9.158811532E-003,
-    -9.598465636E-003,
-    -1.003604382E-002,
-    -1.047059800E-002,
-    -1.090117730E-002,
-    -1.132682897E-002,
-    -1.174659748E-002,
-    -1.215953380E-002,
-    -1.256469358E-002,
-    -1.296114177E-002,
-    -1.334795821E-002,
-    -1.372423489E-002,
-    -1.408908330E-002,
-    -1.444163360E-002,
-    -1.478104480E-002,
-    -1.510649733E-002,
-    -1.541720331E-002,
-    -1.571240649E-002,
-    -1.599138230E-002,
-    -1.625344716E-002,
-    -1.649795473E-002,
-    -1.672429405E-002,
-    -1.693190821E-002,
-    -1.712027565E-002,
-    -1.728892699E-002,
-    -1.743743755E-002,
-    -1.756543480E-002,
-    -1.767260395E-002,
-    -1.775865816E-002,
-    -1.782339066E-002,
-    -1.786663756E-002,
-    -1.788828894E-002,
-    +1.788828894E-002,
-    +1.786663756E-002,
-    +1.782339066E-002,
-    +1.775865816E-002,
-    +1.767260395E-002,
-    +1.756543480E-002,
-    +1.743743755E-002,
-    +1.728892699E-002,
-    +1.712027565E-002,
-    +1.693190821E-002,
-    +1.672429405E-002,
-    +1.649795473E-002,
-    +1.625344716E-002,
-    +1.599138230E-002,
-    +1.571240649E-002,
-    +1.541720331E-002,
-    +1.510649733E-002,
-    +1.478104480E-002,
-    +1.444163360E-002,
-    +1.408908330E-002,
-    +1.372423489E-002,
-    +1.334795821E-002,
-    +1.296114177E-002,
-    +1.256469358E-002,
-    +1.215953380E-002,
-    +1.174659748E-002,
-    +1.132682897E-002,
-    +1.090117730E-002,
-    +1.047059800E-002,
-    +1.003604382E-002,
-    +9.598465636E-003,
-    +9.158811532E-003,
-    +8.718019351E-003,
-    +8.277016692E-003,
-    +7.836719044E-003,
-    +7.398022339E-003,
-    +6.961807609E-003,
-    +6.528933067E-003,
-    +6.100233644E-003,
-    +5.676518660E-003,
-    +5.258570891E-003,
-    +4.847140983E-003,
-    +4.442950245E-003,
-    +4.046686925E-003,
-    +3.659002949E-003,
-    +3.280514618E-003,
-    +2.911801683E-003,
-    +2.553403843E-003,
-    +2.205822384E-003,
-    +1.869517611E-003,
-    +1.544908970E-003,
-    +1.232374110E-003,
-    +9.322494152E-004,
-    +6.448282511E-004,
-    +3.703625989E-004,
-    +1.090620208E-004,
-    -1.389056415E-004,
-    -3.734139318E-004,
-    -5.943773431E-004,
-    -8.017504588E-004,
-    -9.955273708E-004,
-    -1.175740734E-003,
-    -1.342460280E-003,
-    -1.495792647E-003,
-    +1.635878929E-003,
-    +1.762894331E-003,
-    +1.877046190E-003,
-    +1.978572691E-003,
-    +2.067740774E-003,
-    +2.144844970E-003,
-    +2.210205887E-003,
-    +2.264167881E-003,
-    +2.307097195E-003,
-    +2.339380793E-003,
-    +2.361423569E-003,
-    +2.373647178E-003,
-    +2.376487479E-003,
-    +2.370394068E-003,
-    +2.355825622E-003,
-    +2.333251061E-003,
-    +2.303145360E-003,
-    +2.265989315E-003,
-    +2.222266514E-003,
-    +2.172462177E-003,
-    +2.117061289E-003,
-    +2.056547208E-003,
-    +1.991399564E-003,
-    +1.922092517E-003,
-    +1.849094522E-003,
-    +1.772865304E-003,
-    +1.693855622E-003,
-    +1.612505526E-003,
-    +1.529243193E-003,
-    +1.444484224E-003,
-    +1.358630019E-003,
-    +1.272067428E-003,
-    +1.185167348E-003,
-    +1.098284614E-003,
-    +1.011756598E-003,
-    +9.259034996E-004,
-    +8.410271257E-004,
-    +7.574109477E-004,
-    +6.753197522E-004,
-    +5.949990009E-004,
-    +5.166754709E-004,
-    +4.405563814E-004,
-    +3.668301215E-004,
-    +2.956659591E-004,
-    +2.272142592E-004,
-    +1.616069785E-004,
-    +9.895755647E-005,
-    +3.936182839E-005,
-    -1.710198012E-005,
-    -7.037253090E-005,
-    -1.204049113E-004,
-    -1.671699720E-004,
-    -2.106537577E-004,
-    -2.508567995E-004,
-    -2.877934603E-004,
-    -3.214911267E-004,
-    -3.519894381E-004,
-    -3.793396754E-004,
-    -4.036037717E-004,
-    -4.248536134E-004,
-    -4.431701091E-004,
-    -4.586426076E-004,
-    -4.713678791E-004,
-    -4.814492422E-004,
-    +4.889960401E-004,
-    +4.941228544E-004,
-    +4.969481961E-004,
-    +4.975944757E-004,
-    +4.961824161E-004,
-    +4.928477574E-004,
-    +4.877146275E-004,
-    +4.809123348E-004,
-    +4.725702747E-004,
-    +4.628172028E-004,
-    +4.517810594E-004,
-    +4.395879805E-004,
-    +4.263620067E-004,
-    +4.122247046E-004,
-    +3.972945851E-004,
-    +3.816867538E-004,
-    +3.655125911E-004,
-    +3.488793736E-004,
-    +3.318900708E-004,
-    +3.146430245E-004,
-    +2.972317743E-004,
-    +2.797449124E-004,
-    +2.622658503E-004,
-    +2.448728774E-004,
-    +2.276388550E-004,
-    +2.106313768E-004,
-    +1.939126523E-004,
-    +1.775395358E-004,
-    +1.615635992E-004,
-    +1.460311323E-004,
-    +1.309833024E-004,
-    +1.164562127E-004,
-    +1.024810626E-004,
-    +8.908427117E-005,
-    +7.628766616E-005,
-    +6.410864444E-005,
-    +5.256036457E-005,
-    +4.165195787E-005,
-    +3.138873581E-005,
-    +2.177240640E-005,
-    +1.280130618E-005,
-    +4.470633485E-006,
-    -3.227306706E-006,
-    -1.030297699E-005,
-    -1.676913780E-005,
-    -2.264085742E-005,
-    -2.793515523E-005,
-    -3.267079956E-005,
-    -3.686808850E-005,
-    -4.054862075E-005,
-    -4.373511547E-005,
-    -4.645117951E-005,
-    -4.872112549E-005,
-    -5.056979353E-005,
-    -5.202236207E-005,
-    -5.310418419E-005,
-    -5.384063843E-005,
-    -5.425697600E-005,
-    -5.437819709E-005,
-    -5.422891263E-005,
-    -5.383323878E-005,
-    -5.321469871E-005,
-    -5.239612074E-005,
-    -5.139957648E-005,
-    +5.024627535E-005,
-    +4.895655002E-005,
-    +4.754976908E-005,
-    +4.604430433E-005,
-    +4.445751256E-005,
-    +4.280570283E-005,
-    +4.110412556E-005,
-    +3.936696885E-005,
-    +3.760734762E-005,
-    +3.583733633E-005,
-    +3.406793985E-005,
-    +3.230916263E-005,
-    +3.056998685E-005,
-    +2.885844333E-005,
-    +2.718161704E-005,
-    +2.554569073E-005,
-    +2.395598858E-005,
-    +2.241701623E-005,
-    +2.093250441E-005,
-    +1.950545993E-005,
-    +1.813820381E-005,
-    +1.683242772E-005,
-    +1.558924305E-005,
-    +1.440921824E-005,
-    +1.329243969E-005,
-    +1.223855270E-005,
-    +1.124680875E-005,
-    +1.031611009E-005,
-    +9.445050637E-006,
-    +8.631964192E-006,
-    +7.874960829E-006,
-    +7.171964626E-006,
-    +6.520755960E-006,
-    +5.918994248E-006,
-    +5.364252502E-006,
-    +4.854050530E-006,
-    +4.385879038E-006,
-    +3.957220997E-006,
-    +3.565570978E-006,
-    +3.208459020E-006,
-    +2.883470643E-006,
-    +2.588257530E-006,
-    +2.320550948E-006,
-    +2.078171747E-006,
-    +1.859034001E-006,
-    +1.661159786E-006,
-    +1.482681114E-006,
-    +1.321840614E-006,
-    +1.176999604E-006,
-    +1.046637067E-006,
-    +9.293416952E-007,
-    +8.238164355E-007,
-    +7.288739425E-007,
-    +6.434325428E-007,
-    +5.665120852E-007,
-    +4.972276315E-007,
-    +4.347855338E-007,
-    +3.784752209E-007,
-    +3.276689142E-007,
-    +2.818143514E-007,
-    +2.404238444E-007,
-    +2.030677564E-007,
-    +1.693738625E-007,
-    +1.390191784E-007
-};
-
-/* pre-scale lfe fir coefficients */
-#define SCALE(c) ((c) / (256.0f * 32768.0f))
-DECLARE_ALIGNED(16, static const float, lfe_fir_64)[] = {
-    SCALE(2.658434386830777e-4), SCALE(9.029330685734748e-3),
-    SCALE(7.939263433218002e-2), SCALE(2.425158768892288e-1),
-    SCALE(3.430179357528686e-1), SCALE(2.398228943347931e-1),
-    SCALE(7.746443897485733e-2), SCALE(8.622321300208569e-3),
-    SCALE(8.179365249816328e-5), SCALE(9.450953453779220e-3),
-    SCALE(8.134882897138596e-2), SCALE(2.451938837766648e-1),
-    SCALE(3.429597318172455e-1), SCALE(2.371159791946411e-1),
-    SCALE(7.556436210870743e-2), SCALE(8.229630999267101e-3),
-    SCALE(9.439323912374676e-5), SCALE(9.887560270726680e-3),
-    SCALE(8.333285897970200e-2), SCALE(2.478559017181396e-1),
-    SCALE(3.428434133529663e-1), SCALE(2.343961596488952e-1),
-    SCALE(7.369252294301987e-2), SCALE(7.850865833461285e-3),
-    SCALE(1.082170274457894e-4), SCALE(1.033949479460716e-2),
-    SCALE(8.534456789493561e-2), SCALE(2.505008876323700e-1),
-    SCALE(3.426689505577088e-1), SCALE(2.316644787788391e-1),
-    SCALE(7.184901088476181e-2), SCALE(7.485736627131701e-3),
-    SCALE(1.233371440321207e-4), SCALE(1.080708485096693e-2),
-    SCALE(8.738376945257187e-2), SCALE(2.531278133392334e-1),
-    SCALE(3.424364924430847e-1), SCALE(2.289219647645950e-1),
-    SCALE(7.003392279148102e-2), SCALE(7.133882027119398e-3),
-    SCALE(1.397485757479444e-4), SCALE(1.129068247973919e-2),
-    SCALE(8.945026248693466e-2), SCALE(2.557355761528015e-1),
-    SCALE(3.421461284160614e-1), SCALE(2.261696159839630e-1),
-    SCALE(6.824731826782227e-2), SCALE(6.794991903007030e-3),
-    SCALE(1.575958012836054e-4), SCALE(1.179065089672804e-2),
-    SCALE(9.154383838176728e-2), SCALE(2.583232223987580e-1),
-    SCALE(3.417979776859284e-1), SCALE(2.234084606170654e-1),
-    SCALE(6.648923456668854e-2), SCALE(6.468691397458315e-3),
-    SCALE(1.769922382663936e-4), SCALE(1.230732165277004e-2),
-    SCALE(9.366425126791000e-2), SCALE(2.608896791934967e-1),
-    SCALE(3.413922190666198e-1), SCALE(2.206395119428635e-1),
-    SCALE(6.475970894098282e-2), SCALE(6.154712289571762e-3),
-    SCALE(1.981738605536520e-4), SCALE(1.284105982631445e-2),
-    SCALE(9.581124037504196e-2), SCALE(2.634339034557342e-1),
-    SCALE(3.409290313720703e-1), SCALE(2.178637981414795e-1),
-    SCALE(6.305878609418869e-2), SCALE(5.852684378623962e-3),
-    SCALE(2.211847313446924e-4), SCALE(1.339218579232693e-2),
-    SCALE(9.798453748226166e-2), SCALE(2.659549415111542e-1),
-    SCALE(3.404086530208588e-1), SCALE(2.150822728872299e-1),
-    SCALE(6.138643622398376e-2), SCALE(5.562345497310162e-3),
-    SCALE(2.460231189616024e-4), SCALE(1.396108977496624e-2),
-    SCALE(1.001838669180870e-1), SCALE(2.684516608715058e-1),
-    SCALE(3.398312926292420e-1), SCALE(2.122959494590759e-1),
-    SCALE(5.974265560507774e-2), SCALE(5.283284001052380e-3),
-    SCALE(2.726115926634520e-4), SCALE(1.454808749258518e-2),
-    SCALE(1.024089083075523e-1), SCALE(2.709231376647949e-1),
-    SCALE(3.391972482204438e-1), SCALE(2.095058411359787e-1),
-    SCALE(5.812742188572884e-2), SCALE(5.015311297029257e-3),
-    SCALE(3.013863170053810e-4), SCALE(1.515355054289102e-2),
-    SCALE(1.046593263745308e-1), SCALE(2.733682692050934e-1),
-    SCALE(3.385068178176880e-1), SCALE(2.067128717899322e-1),
-    SCALE(5.654069408774376e-2), SCALE(4.758012015372515e-3),
-    SCALE(3.328395541757345e-4), SCALE(1.577781140804291e-2),
-    SCALE(1.069347932934761e-1), SCALE(2.757860720157624e-1),
-    SCALE(3.377602994441986e-1), SCALE(2.039180546998978e-1),
-    SCALE(5.498242005705833e-2), SCALE(4.511159844696522e-3),
-    SCALE(3.658991190604866e-4), SCALE(1.642123050987720e-2),
-    SCALE(1.092349365353584e-1), SCALE(2.781755328178406e-1),
-    SCALE(3.369580209255218e-1), SCALE(2.011223286390304e-1),
-    SCALE(5.345252528786659e-2), SCALE(4.274417180567980e-3),
-    SCALE(4.018281470052898e-4), SCALE(1.708412915468216e-2),
-    SCALE(1.115593686699867e-1), SCALE(2.805356979370117e-1),
-    SCALE(3.361004292964936e-1), SCALE(1.983266174793244e-1),
-    SCALE(5.195093154907227e-2), SCALE(4.047499038279056e-3),
-    SCALE(4.401875485200435e-4), SCALE(1.776690222322941e-2),
-    SCALE(1.139076948165894e-1), SCALE(2.828655838966370e-1),
-    SCALE(3.351879119873047e-1), SCALE(1.955319195985794e-1),
-    SCALE(5.047753453254700e-2), SCALE(3.830091329291463e-3),
-    SCALE(4.812776169274002e-4), SCALE(1.846982724964619e-2),
-    SCALE(1.162794977426529e-1), SCALE(2.851640880107880e-1),
-    SCALE(3.342207968235016e-1), SCALE(1.927391141653061e-1),
-    SCALE(4.903224110603333e-2), SCALE(3.621967276558280e-3),
-    SCALE(5.252459668554366e-4), SCALE(1.919330470263958e-2),
-    SCALE(1.186743453145027e-1), SCALE(2.874303460121155e-1),
-    SCALE(3.331996202468872e-1), SCALE(1.899491697549820e-1),
-    SCALE(4.761491715908051e-2), SCALE(3.422776935622096e-3),
-    SCALE(5.721592460758984e-4), SCALE(1.993762329220772e-2),
-    SCALE(1.210917681455612e-1), SCALE(2.896633744239807e-1),
-    SCALE(3.321248590946198e-1), SCALE(1.871629506349564e-1),
-    SCALE(4.622544348239899e-2), SCALE(3.232272574678064e-3),
-    SCALE(6.222130032256246e-4), SCALE(2.070316113531590e-2),
-    SCALE(1.235313042998314e-1), SCALE(2.918621897697448e-1),
-    SCALE(3.309969604015350e-1), SCALE(1.843813359737396e-1),
-    SCALE(4.486365616321564e-2), SCALE(3.050152910873294e-3),
-    SCALE(6.755515350960195e-4), SCALE(2.149021252989769e-2),
-    SCALE(1.259924471378326e-1), SCALE(2.940258979797364e-1),
-    SCALE(3.298164308071136e-1), SCALE(1.816052496433258e-1),
-    SCALE(4.352942481637001e-2), SCALE(2.876190468668938e-3),
-    SCALE(7.324148900806904e-4), SCALE(2.229913882911205e-2),
-    SCALE(1.284746825695038e-1), SCALE(2.961534857749939e-1),
-    SCALE(3.285838961601258e-1), SCALE(1.788355410099030e-1),
-    SCALE(4.222255200147629e-2), SCALE(2.710093278437853e-3),
-    SCALE(7.928516715764999e-4), SCALE(2.313023805618286e-2),
-    SCALE(1.309774816036224e-1), SCALE(2.982441186904907e-1),
-    SCALE(3.272998929023742e-1), SCALE(1.760730892419815e-1),
-    SCALE(4.094288870692253e-2), SCALE(2.551567042246461e-3),
-    SCALE(8.570110658183694e-4), SCALE(2.398385666310787e-2),
-    SCALE(1.335003077983856e-1), SCALE(3.002967536449432e-1),
-    SCALE(3.259649574756622e-1), SCALE(1.733186990022659e-1),
-    SCALE(3.969023004174232e-2), SCALE(2.400433411821723e-3),
-    SCALE(9.251192095689476e-4), SCALE(2.486028522253036e-2),
-    SCALE(1.360425949096680e-1), SCALE(3.023106753826142e-1),
-    SCALE(3.245797157287598e-1), SCALE(1.705732345581055e-1),
-    SCALE(3.846437484025955e-2), SCALE(2.256359672173858e-3),
-    SCALE(9.974770946428180e-4), SCALE(2.575986087322235e-2),
-    SCALE(1.386037617921829e-1), SCALE(3.042849004268646e-1),
-    SCALE(3.231448531150818e-1), SCALE(1.678375005722046e-1),
-    SCALE(3.726511076092720e-2), SCALE(2.119151875376701e-3),
-    SCALE(1.073930296115577e-3), SCALE(2.668286114931106e-2),
-    SCALE(1.411831974983215e-1), SCALE(3.062185347080230e-1),
-    SCALE(3.216609656810760e-1), SCALE(1.651122719049454e-1),
-    SCALE(3.609224036335945e-2), SCALE(1.988604199141264e-3),
-    SCALE(1.155023579485714e-3), SCALE(2.762960828840732e-2),
-    SCALE(1.437802612781525e-1), SCALE(3.081108033657074e-1),
-    SCALE(3.201287388801574e-1), SCALE(1.623983532190323e-1),
-    SCALE(3.494550660252571e-2), SCALE(1.864377525635064e-3),
-    SCALE(1.240676851011813e-3), SCALE(2.860039286315441e-2),
-    SCALE(1.463943719863892e-1), SCALE(3.099608123302460e-1),
-    SCALE(3.185488879680634e-1), SCALE(1.596965193748474e-1),
-    SCALE(3.382468968629837e-2), SCALE(1.746327499859035e-3),
-    SCALE(1.331258914433420e-3), SCALE(2.959549613296986e-2),
-    SCALE(1.490248143672943e-1), SCALE(3.117676973342896e-1),
-    SCALE(3.169221282005310e-1), SCALE(1.570075154304504e-1),
-    SCALE(3.272953629493714e-2), SCALE(1.634211512282491e-3),
-    SCALE(1.426893868483603e-3), SCALE(3.061520494520664e-2),
-    SCALE(1.516709625720978e-1), SCALE(3.135308027267456e-1),
-    SCALE(3.152491748332978e-1), SCALE(1.543320864439010e-1),
-    SCALE(3.165979683399200e-2), SCALE(1.527829794213176e-3),
-};
-
-DECLARE_ALIGNED(16, static const float, lfe_fir_128)[] = {
-    SCALE(0.00053168571), SCALE(0.15878495574), SCALE(0.68603444099), SCALE(0.15492856503),
-    SCALE(0.00016358691), SCALE(0.16269733012), SCALE(0.68591803312), SCALE(0.15112841129),
-    SCALE(0.00018878609), SCALE(0.16666537523), SCALE(0.68568539619), SCALE(0.14738474786),
-    SCALE(0.00021643363), SCALE(0.17068879306), SCALE(0.68533653021), SCALE(0.14369773865),
-    SCALE(0.00024667382), SCALE(0.17476719618), SCALE(0.68487155437), SCALE(0.14006754756),
-    SCALE(0.00027949660), SCALE(0.17890018225), SCALE(0.68429082632), SCALE(0.13649433851),
-    SCALE(0.00031519096), SCALE(0.18308731914), SCALE(0.68359452486), SCALE(0.13297818601),
-    SCALE(0.00035398375), SCALE(0.18732811511), SCALE(0.68278300762), SCALE(0.12951917946),
-    SCALE(0.00039634691), SCALE(0.19162209332), SCALE(0.68185669184), SCALE(0.12611730397),
-    SCALE(0.00044236859), SCALE(0.19596865773), SCALE(0.68081587553), SCALE(0.12277261168),
-    SCALE(0.00049204525), SCALE(0.20036731660), SCALE(0.67966115475), SCALE(0.11948505789),
-    SCALE(0.00054522208), SCALE(0.20481738448), SCALE(0.67839306593), SCALE(0.11625462025),
-    SCALE(0.00060277141), SCALE(0.20931822062), SCALE(0.67701220512), SCALE(0.11308115721),
-    SCALE(0.00066567765), SCALE(0.21386915445), SCALE(0.67551922798), SCALE(0.10996460915),
-    SCALE(0.00073179678), SCALE(0.21846942604), SCALE(0.67391467094), SCALE(0.10690483451),
-    SCALE(0.00080365466), SCALE(0.22311829031), SCALE(0.67219948769), SCALE(0.10390164703),
-    SCALE(0.00088037323), SCALE(0.22781492770), SCALE(0.67037439346), SCALE(0.10095486045),
-    SCALE(0.00096255314), SCALE(0.23255851865), SCALE(0.66844022274), SCALE(0.09806428105),
-    SCALE(0.00105048984), SCALE(0.23734821379), SCALE(0.66639786959), SCALE(0.09522963315),
-    SCALE(0.00114431616), SCALE(0.24218304455), SCALE(0.66424828768), SCALE(0.09245070815),
-    SCALE(0.00124442333), SCALE(0.24706205726), SCALE(0.66199249029), SCALE(0.08972713351),
-    SCALE(0.00135110028), SCALE(0.25198432803), SCALE(0.65963155031), SCALE(0.08705867827),
-    SCALE(0.00146482687), SCALE(0.25694879889), SCALE(0.65716648102), SCALE(0.08444493264),
-    SCALE(0.00158570008), SCALE(0.26195442677), SCALE(0.65459835529), SCALE(0.08188561350),
-    SCALE(0.00171401864), SCALE(0.26700007915), SCALE(0.65192854404), SCALE(0.07938029617),
-    SCALE(0.00185023469), SCALE(0.27208462358), SCALE(0.64915806055), SCALE(0.07692859322),
-    SCALE(0.00199495023), SCALE(0.27720692754), SCALE(0.64628833532), SCALE(0.07453006506),
-    SCALE(0.00214785640), SCALE(0.28236576915), SCALE(0.64332056046), SCALE(0.07218432426),
-    SCALE(0.00231004250), SCALE(0.28755992651), SCALE(0.64025616646), SCALE(0.06989086419),
-    SCALE(0.00248134881), SCALE(0.29278811812), SCALE(0.63709646463), SCALE(0.06764923781),
-    SCALE(0.00266251224), SCALE(0.29804900289), SCALE(0.63384294510), SCALE(0.06545893103),
-    SCALE(0.00285378192), SCALE(0.30334126949), SCALE(0.63049703836), SCALE(0.06331945211),
-    SCALE(0.00305565330), SCALE(0.30866351724), SCALE(0.62706029415), SCALE(0.06123027951),
-    SCALE(0.00326841651), SCALE(0.31401440501), SCALE(0.62353414297), SCALE(0.05919086933),
-    SCALE(0.00349264755), SCALE(0.31939238310), SCALE(0.61992025375), SCALE(0.05720067024),
-    SCALE(0.00372874714), SCALE(0.32479602098), SCALE(0.61622029543), SCALE(0.05525910854),
-    SCALE(0.00397720048), SCALE(0.33022382855), SCALE(0.61243581772), SCALE(0.05336561054),
-    SCALE(0.00423829490), SCALE(0.33567428589), SCALE(0.60856848955), SCALE(0.05151961371),
-    SCALE(0.00451271003), SCALE(0.34114575386), SCALE(0.60462015867), SCALE(0.04972046614),
-    SCALE(0.00480085658), SCALE(0.34663668275), SCALE(0.60059231520), SCALE(0.04796761274),
-    SCALE(0.00510312291), SCALE(0.35214546323), SCALE(0.59648692608), SCALE(0.04626038298),
-    SCALE(0.00542017492), SCALE(0.35767036676), SCALE(0.59230577946), SCALE(0.04459818453),
-    SCALE(0.00575236930), SCALE(0.36320972443), SCALE(0.58805054426), SCALE(0.04298033938),
-    SCALE(0.00610029325), SCALE(0.36876192689), SCALE(0.58372318745), SCALE(0.04140623659),
-    SCALE(0.00646453211), SCALE(0.37432509661), SCALE(0.57932555676), SCALE(0.03987516090),
-    SCALE(0.00684553990), SCALE(0.37989753485), SCALE(0.57485944033), SCALE(0.03838652745),
-    SCALE(0.00724391919), SCALE(0.38547745347), SCALE(0.57032698393), SCALE(0.03693958372),
-    SCALE(0.00766016589), SCALE(0.39106300473), SCALE(0.56572991610), SCALE(0.03553372994),
-    SCALE(0.00809498038), SCALE(0.39665243030), SCALE(0.56107026339), SCALE(0.03416819125),
-    SCALE(0.00854881573), SCALE(0.40224379301), SCALE(0.55634999275), SCALE(0.03284239396),
-    SCALE(0.00902230106), SCALE(0.40783521533), SCALE(0.55157101154), SCALE(0.03155555204),
-    SCALE(0.00951600447), SCALE(0.41342487931), SCALE(0.54673534632), SCALE(0.03030703776),
-    SCALE(0.01003060210), SCALE(0.41901078820), SCALE(0.54184508324), SCALE(0.02909611352),
-    SCALE(0.01056654565), SCALE(0.42459106445), SCALE(0.53690224886), SCALE(0.02792212367),
-    SCALE(0.01112466771), SCALE(0.43016362190), SCALE(0.53190881014), SCALE(0.02678431384),
-    SCALE(0.01170534454), SCALE(0.43572667241), SCALE(0.52686679363), SCALE(0.02568206564),
-    SCALE(0.01230939943), SCALE(0.44127810001), SCALE(0.52177828550), SCALE(0.02461459488),
-    SCALE(0.01293735672), SCALE(0.44681602716), SCALE(0.51664537191), SCALE(0.02358125709),
-    SCALE(0.01358995494), SCALE(0.45233830810), SCALE(0.51147013903), SCALE(0.02258131653),
-    SCALE(0.01426773332), SCALE(0.45784294605), SCALE(0.50625455379), SCALE(0.02161412500),
-    SCALE(0.01497144438), SCALE(0.46332800388), SCALE(0.50100076199), SCALE(0.02067894675),
-    SCALE(0.01570170000), SCALE(0.46879136562), SCALE(0.49571081996), SCALE(0.01977507770),
-    SCALE(0.01645922661), SCALE(0.47423094511), SCALE(0.49038675427), SCALE(0.01890186779),
-    SCALE(0.01724460535), SCALE(0.47964480519), SCALE(0.48503074050), SCALE(0.01805862412),
-};
-#undef SCALE
-
-/*
- * D.11 Look-up Table for Downmix Scale Factors
- *
- * Note that the range of the entries in DmixTable[] is between -60 dB and 0 dB
- * with addition of -inf (|DMixCoeff| = 0), which is coded with a DmixCode = 0.
- * Furthermore, the range [-60 to 0] is subdivided into 3 regions, each with a
- * different grid resolution:
- *
- * 1) [-60.000 to -30] with resolution of 0.500 dB
- * 2) [-29.750 to -15] with resolution of 0.250 dB
- * 3) [-14.875 to   0] with resolution of 0.125 dB
- */
-static const uint16_t dca_dmixtable[242] = {
-        0,    33,    35,    37,    39,    41,    44,    46,
-       49,    52,    55,    58,    62,    65,    69,    73,
-       78,    82,    87,    92,    98,   104,   110,   116,
-      123,   130,   138,   146,   155,   164,   174,   184,
-      195,   207,   219,   232,   246,   260,   276,   292,
-      309,   328,   347,   368,   389,   413,   437,   463,
-      490,   519,   550,   583,   617,   654,   693,   734,
-      777,   823,   872,   924,   978,  1036,  1066,  1098,
-     1130,  1163,  1197,  1232,  1268,  1305,  1343,  1382,
-     1422,  1464,  1506,  1550,  1596,  1642,  1690,  1740,
-     1790,  1843,  1896,  1952,  2009,  2068,  2128,  2190,
-     2254,  2320,  2388,  2457,  2529,  2603,  2679,  2757,
-     2838,  2920,  3006,  3093,  3184,  3277,  3372,  3471,
-     3572,  3677,  3784,  3894,  4008,  4125,  4246,  4370,
-     4497,  4629,  4764,  4903,  5046,  5193,  5345,  5501,
-     5662,  5827,  5912,  5997,  6084,  6172,  6262,  6353,
-     6445,  6538,  6633,  6729,  6827,  6925,  7026,  7128,
-     7231,  7336,  7442,  7550,  7659,  7771,  7883,  7997,
-     8113,  8231,  8350,  8471,  8594,  8719,  8845,  8973,
-     9103,  9235,  9369,  9505,  9643,  9783,  9924, 10068,
-    10214, 10362, 10512, 10665, 10819, 10976, 11135, 11297,
-    11460, 11627, 11795, 11966, 12139, 12315, 12494, 12675,
-    12859, 13045, 13234, 13426, 13621, 13818, 14018, 14222,
-    14428, 14637, 14849, 15064, 15283, 15504, 15729, 15957,
-    16188, 16423, 16661, 16902, 17147, 17396, 17648, 17904,
-    18164, 18427, 18694, 18965, 19240, 19519, 19802, 20089,
-    20380, 20675, 20975, 21279, 21587, 21900, 22218, 22540,
-    22867, 23170, 23534, 23875, 24221, 24573, 24929, 25290,
-    25657, 26029, 26406, 26789, 27177, 27571, 27970, 28376,
-    28787, 29205, 29628, 30057, 30493, 30935, 31383, 31838,
-    32300, 32768,
-};
-
-static const float dca_default_coeffs[10][6][2] = {
-    { { 0.707107, 0.707107 }, { 0.000000, 0.000000 },                                                                                                 }, // A [LFE]
-    { { 1.000000, 0.000000 }, { 0.000000, 1.000000 }, { 0.000000, 0.000000 },                                                                         }, // A + B (dual mono) [LFE]
-    { { 1.000000, 0.000000 }, { 0.000000, 1.000000 }, { 0.000000, 0.000000 },                                                                         }, // L + R (stereo) [LFE]
-    { { 1.000000, 0.000000 }, { 0.000000, 1.000000 }, { 0.000000, 0.000000 },                                                                         }, // (L+R) + (L-R) (sum-difference) [LFE]
-    { { 1.000000, 0.000000 }, { 0.000000, 1.000000 }, { 0.000000, 0.000000 },                                                                         }, // LT + RT (left and right total) [LFE]
-    { { 0.501187, 0.501187 }, { 0.707107, 0.000000 }, { 0.000000, 0.707107 }, { 0.000000, 0.000000 },                                                 }, // C + L + R [LFE]
-    { { 0.707107, 0.000000 }, { 0.000000, 0.707107 }, { 0.501187, 0.501187 }, { 0.000000, 0.000000 },                                                 }, // L + R + S [LFE]
-    { { 0.501187, 0.501187 }, { 0.707107, 0.000000 }, { 0.000000, 0.707107 }, { 0.501187, 0.501187 }, { 0.000000, 0.000000 },                         }, // C + L + R + S [LFE]
-    { { 0.707107, 0.000000 }, { 0.000000, 0.707107 }, { 0.501187, 0.000000 }, { 0.000000, 0.501187 }, { 0.000000, 0.000000 },                         }, // L + R + SL + SR [LFE]
-    { { 0.501187, 0.501187 }, { 0.707107, 0.000000 }, { 0.000000, 0.707107 }, { 0.501187, 0.000000 }, { 0.000000, 0.501187 }, { 0.000000, 0.000000 }, }, // C + L + R + SL + SR [LFE]
-};
-
-/* downmix coeffs
- *
- * TABLE 9
- * ______________________________________
- * Down-mix coefficients for 8-channel source
- * audio (5 + 3 format)
- * lt
- * cen- rt lt ctr rt
- * lt ter ctr center
- * rt srd srd srd
- * ______________________________________
- * 1 0.71 0.74 1.0 0.71 0.71 0.58 0.58 0.58
- * 2 left 1.0 0.89 0.71 0.46 0.71 0.50
- * rt 0.45 0.71 0.89 1.0 0.50 0.71
- * 3 lt 1.0 0.89 0.71 0.45
- * rt 0.45 0.71 0.89 1.0
- * srd 0.71 0.71 0.71
- * 4 lt 1.0 0.89 0.71 0.45
- * rt 0.45 0.71 0.89 1.0
- * lt srd 1.0 0.71
- * rt srd 0.71 0.71
- * 4 lt 1.0 0.5
- * ctr 0.87 1.0 0.87
- * rt 0.5 1.0
- * srd 0.71 0.71 0.71
- * 5 lt 1.0 0.5
- * ctr 0.87 1.0 0.87
- * rt 0.5 1.0
- * lt srd 1.0 0.71
- * rt srd 0.71 1.0
- * 6 lt 1.0 0.5
- * lt ctr 0.87 0.71
- * rt ctr 0.71 0.87
- * rt 0.5 1.0
- * lt srd 1.0 0.71
- * rt srd 0.71 1.0
- * 6 lt 1.0 0.5
- * ctr 0.86 1.0 0.86
- * rt 0.5 1.0
- * lt srd 1.0
- * ctr srd 1.0
- * rt srd 1.0
- * 7 lt 1.0
- * lt ctr 1.0
- * ctr 1.0
- * rt ctr 1.0
- * rt 1.0
- * lt srd 1.0 0.71
- * rt srd 0.71 1.0
- * 7 lt 1.0 0.5
- * lt ctr 0.87 0.71
- * rt ctr 0.71 0.87
- * rt 0.5 1.0
- * lt srd 1.0
- * ctr srd 1.0
- * rt srd 1.0
- * 8 lt 1.0 0.5
- * lt ctr 0.87 0.71
- * rt ctr 0.71 0.87
- * rt 0.5 1.0
- * lt 1 srd 0.87 0.35
- * lt 2 srd 0.5 0.61
- * rt 2 srd 0.61 0.50
- * rt 2 srd 0.35 0.87
- *
- * Generation of Lt Rt
- *
- * In the case when the playback system has analog or digital surround
- * multi-channel capability, a down matrix from 5, 4, or 3 channel to
- * Lt Rt may be desirable. In the case when the number of decoded audio
- * channels exceeds 5, 4 or 3 respectively a first stage down mix to 5,
- * 4 or 3 chs should be used as described above.
- *
- * The down matrixing equations for 5-channel source audio to a
- * two-channel Lt Rt playback system are given by:
- *
- * Left  = left  + 0.7 * center - 0.7 * (lt surround + rt surround)
- *
- * Right = right + 0.7 * center + 0.7 * (lt surround + rt surround)
- *
- * Embedded mixing to 2-channel
- *
- * One concern arising from the proliferation of multi-channel audio
- * systems is that most home systems presently have only two channel
- * playback capability. To accommodate this a fixed 2-channel down
- * matrix processes is commonly used following the multi-channel
- * decoding stage. However, for music only applications the image
- * quality etc. of the down matrixed signal may not match that of an
- * equivalent stereo recording found on CD.
- *
- * The concept of embedded mixing is to allow the producer to
- * dynamically specify the matrixing coefficients within the audio
- * frame itself. In this way the stereo down mix at the decoder may be
- * better matched to a 2-channel playback environment.
- *
- * CHS*2, 7-bit down mix indexes (MCOEFFS) are transmitted along with
- * the multi-channel audio once in every frame. The indexes are
- * converted to attenuation factors using a 7 bit LUT. The 2-ch down
- * mix equations are as follows,
- *
- * Left Ch  = sum (MCOEFF[n]       * Ch[n]) for n=1, CHS
- *
- * Right Ch = sum (MCOEFF[n + CHS] * Ch[n]) for n=1, CHS
- *
- * where Ch(n) represents the subband samples in the (n)th audio channel.
- */
+extern const uint16_t ff_dca_vlc_offs[63];
 
 #endif /* AVCODEC_DCADATA_H */
diff --git a/libavcodec/dcadec.c b/libavcodec/dcadec.c
index 40d8e9e..0339eef 100644
--- a/libavcodec/dcadec.c
+++ b/libavcodec/dcadec.c
@@ -4,6 +4,8 @@
  * Copyright (C) 2004 Benjamin Zores
  * Copyright (C) 2006 Benjamin Larsson
  * Copyright (C) 2007 Konstantin Shishkov
+ * Copyright (C) 2012 Paul B Mahol
+ * Copyright (C) 2014 Niels Möller
  *
  * This file is part of FFmpeg.
  *
@@ -26,6 +28,7 @@
 #include <stddef.h>
 #include <stdio.h>
 
+#include "libavutil/attributes.h"
 #include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
 #include "libavutil/float_dsp.h"
@@ -37,6 +40,7 @@
 
 #include "avcodec.h"
 #include "dca.h"
+#include "dca_syncwords.h"
 #include "dcadata.h"
 #include "dcadsp.h"
 #include "dcahuff.h"
@@ -51,17 +55,6 @@
 #   include "arm/dca.h"
 #endif
 
-//#define TRACE
-
-#define DCA_PRIM_CHANNELS_MAX  (7)
-#define DCA_ABITS_MAX         (32)      /* Should be 28 */
-#define DCA_SUBSUBFRAMES_MAX   (4)
-#define DCA_SUBFRAMES_MAX     (16)
-#define DCA_BLOCKS_MAX        (16)
-#define DCA_LFE_MAX            (3)
-#define DCA_CHSETS_MAX         (4)
-#define DCA_CHSET_CHANS_MAX    (8)
-
 enum DCAMode {
     DCA_MONO = 0,
     DCA_CHANNEL,
@@ -76,25 +69,6 @@
     DCA_4F2R
 };
 
-/* these are unconfirmed but should be mostly correct */
-enum DCAExSSSpeakerMask {
-    DCA_EXSS_FRONT_CENTER          = 0x0001,
-    DCA_EXSS_FRONT_LEFT_RIGHT      = 0x0002,
-    DCA_EXSS_SIDE_REAR_LEFT_RIGHT  = 0x0004,
-    DCA_EXSS_LFE                   = 0x0008,
-    DCA_EXSS_REAR_CENTER           = 0x0010,
-    DCA_EXSS_FRONT_HIGH_LEFT_RIGHT = 0x0020,
-    DCA_EXSS_REAR_LEFT_RIGHT       = 0x0040,
-    DCA_EXSS_FRONT_HIGH_CENTER     = 0x0080,
-    DCA_EXSS_OVERHEAD              = 0x0100,
-    DCA_EXSS_CENTER_LEFT_RIGHT     = 0x0200,
-    DCA_EXSS_WIDE_LEFT_RIGHT       = 0x0400,
-    DCA_EXSS_SIDE_LEFT_RIGHT       = 0x0800,
-    DCA_EXSS_LFE2                  = 0x1000,
-    DCA_EXSS_SIDE_HIGH_LEFT_RIGHT  = 0x2000,
-    DCA_EXSS_REAR_HIGH_CENTER      = 0x4000,
-    DCA_EXSS_REAR_HIGH_LEFT_RIGHT  = 0x8000,
-};
 
 enum DCAXxchSpeakerMask {
     DCA_XXCH_FRONT_CENTER          = 0x0000001,
@@ -127,191 +101,6 @@
     DCA_XXCH_REAR_LOW_RIGHT        = 0x8000000,
 };
 
-static const uint32_t map_xxch_to_native[28] = {
-    AV_CH_FRONT_CENTER,
-    AV_CH_FRONT_LEFT,
-    AV_CH_FRONT_RIGHT,
-    AV_CH_SIDE_LEFT,
-    AV_CH_SIDE_RIGHT,
-    AV_CH_LOW_FREQUENCY,
-    AV_CH_BACK_CENTER,
-    AV_CH_BACK_LEFT,
-    AV_CH_BACK_RIGHT,
-    AV_CH_SIDE_LEFT,           /* side surround left -- dup sur side L */
-    AV_CH_SIDE_RIGHT,          /* side surround right -- dup sur side R */
-    AV_CH_FRONT_LEFT_OF_CENTER,
-    AV_CH_FRONT_RIGHT_OF_CENTER,
-    AV_CH_TOP_FRONT_LEFT,
-    AV_CH_TOP_FRONT_CENTER,
-    AV_CH_TOP_FRONT_RIGHT,
-    AV_CH_LOW_FREQUENCY,        /* lfe2 -- duplicate lfe1 position */
-    AV_CH_FRONT_LEFT_OF_CENTER, /* side front left -- dup front cntr L */
-    AV_CH_FRONT_RIGHT_OF_CENTER,/* side front right -- dup front cntr R */
-    AV_CH_TOP_CENTER,           /* overhead */
-    AV_CH_TOP_FRONT_LEFT,       /* side high left -- dup */
-    AV_CH_TOP_FRONT_RIGHT,      /* side high right -- dup */
-    AV_CH_TOP_BACK_CENTER,
-    AV_CH_TOP_BACK_LEFT,
-    AV_CH_TOP_BACK_RIGHT,
-    AV_CH_BACK_CENTER,          /* rear low center -- dup */
-    AV_CH_BACK_LEFT,            /* rear low left -- dup */
-    AV_CH_BACK_RIGHT            /* read low right -- dup  */
-};
-
-enum DCAExtensionMask {
-    DCA_EXT_CORE       = 0x001, ///< core in core substream
-    DCA_EXT_XXCH       = 0x002, ///< XXCh channels extension in core substream
-    DCA_EXT_X96        = 0x004, ///< 96/24 extension in core substream
-    DCA_EXT_XCH        = 0x008, ///< XCh channel extension in core substream
-    DCA_EXT_EXSS_CORE  = 0x010, ///< core in ExSS (extension substream)
-    DCA_EXT_EXSS_XBR   = 0x020, ///< extended bitrate extension in ExSS
-    DCA_EXT_EXSS_XXCH  = 0x040, ///< XXCh channels extension in ExSS
-    DCA_EXT_EXSS_X96   = 0x080, ///< 96/24 extension in ExSS
-    DCA_EXT_EXSS_LBR   = 0x100, ///< low bitrate component in ExSS
-    DCA_EXT_EXSS_XLL   = 0x200, ///< lossless extension in ExSS
-};
-
-/* -1 are reserved or unknown */
-static const int dca_ext_audio_descr_mask[] = {
-    DCA_EXT_XCH,
-    -1,
-    DCA_EXT_X96,
-    DCA_EXT_XCH | DCA_EXT_X96,
-    -1,
-    -1,
-    DCA_EXT_XXCH,
-    -1,
-};
-
-/* extensions that reside in core substream */
-#define DCA_CORE_EXTS (DCA_EXT_XCH | DCA_EXT_XXCH | DCA_EXT_X96)
-
-/* Tables for mapping dts channel configurations to libavcodec multichannel api.
- * Some compromises have been made for special configurations. Most configurations
- * are never used so complete accuracy is not needed.
- *
- * L = left, R = right, C = center, S = surround, F = front, R = rear, T = total, OV = overhead.
- * S  -> side, when both rear and back are configured move one of them to the side channel
- * OV -> center back
- * All 2 channel configurations -> AV_CH_LAYOUT_STEREO
- */
-static const uint64_t dca_core_channel_layout[] = {
-    AV_CH_FRONT_CENTER,                                                     ///< 1, A
-    AV_CH_LAYOUT_STEREO,                                                    ///< 2, A + B (dual mono)
-    AV_CH_LAYOUT_STEREO,                                                    ///< 2, L + R (stereo)
-    AV_CH_LAYOUT_STEREO,                                                    ///< 2, (L + R) + (L - R) (sum-difference)
-    AV_CH_LAYOUT_STEREO,                                                    ///< 2, LT + RT (left and right total)
-    AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER,                               ///< 3, C + L + R
-    AV_CH_LAYOUT_STEREO | AV_CH_BACK_CENTER,                                ///< 3, L + R + S
-    AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER | AV_CH_BACK_CENTER,           ///< 4, C + L + R + S
-    AV_CH_LAYOUT_STEREO | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT,               ///< 4, L + R + SL + SR
-
-    AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER | AV_CH_SIDE_LEFT |
-    AV_CH_SIDE_RIGHT,                                                       ///< 5, C + L + R + SL + SR
-
-    AV_CH_LAYOUT_STEREO | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT |
-    AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER,               ///< 6, CL + CR + L + R + SL + SR
-
-    AV_CH_LAYOUT_STEREO | AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT |
-    AV_CH_FRONT_CENTER  | AV_CH_BACK_CENTER,                                ///< 6, C + L + R + LR + RR + OV
-
-    AV_CH_FRONT_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER |
-    AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_BACK_CENTER   |
-    AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT,                                     ///< 6, CF + CR + LF + RF + LR + RR
-
-    AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_CENTER   |
-    AV_CH_FRONT_RIGHT_OF_CENTER | AV_CH_LAYOUT_STEREO |
-    AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT,                                     ///< 7, CL + C + CR + L + R + SL + SR
-
-    AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER |
-    AV_CH_LAYOUT_STEREO | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT |
-    AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT,                                     ///< 8, CL + CR + L + R + SL1 + SL2 + SR1 + SR2
-
-    AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_CENTER   |
-    AV_CH_FRONT_RIGHT_OF_CENTER | AV_CH_LAYOUT_STEREO |
-    AV_CH_SIDE_LEFT | AV_CH_BACK_CENTER | AV_CH_SIDE_RIGHT,                 ///< 8, CL + C + CR + L + R + SL + S + SR
-};
-
-static const int8_t dca_lfe_index[] = {
-    1, 2, 2, 2, 2, 3, 2, 3, 2, 3, 2, 3, 1, 3, 2, 3
-};
-
-static const int8_t dca_channel_reorder_lfe[][9] = {
-    { 0, -1, -1, -1, -1, -1, -1, -1, -1 },
-    { 0,  1, -1, -1, -1, -1, -1, -1, -1 },
-    { 0,  1, -1, -1, -1, -1, -1, -1, -1 },
-    { 0,  1, -1, -1, -1, -1, -1, -1, -1 },
-    { 0,  1, -1, -1, -1, -1, -1, -1, -1 },
-    { 2,  0,  1, -1, -1, -1, -1, -1, -1 },
-    { 0,  1,  3, -1, -1, -1, -1, -1, -1 },
-    { 2,  0,  1,  4, -1, -1, -1, -1, -1 },
-    { 0,  1,  3,  4, -1, -1, -1, -1, -1 },
-    { 2,  0,  1,  4,  5, -1, -1, -1, -1 },
-    { 3,  4,  0,  1,  5,  6, -1, -1, -1 },
-    { 2,  0,  1,  4,  5,  6, -1, -1, -1 },
-    { 0,  6,  4,  5,  2,  3, -1, -1, -1 },
-    { 4,  2,  5,  0,  1,  6,  7, -1, -1 },
-    { 5,  6,  0,  1,  7,  3,  8,  4, -1 },
-    { 4,  2,  5,  0,  1,  6,  8,  7, -1 },
-};
-
-static const int8_t dca_channel_reorder_lfe_xch[][9] = {
-    { 0,  2, -1, -1, -1, -1, -1, -1, -1 },
-    { 0,  1,  3, -1, -1, -1, -1, -1, -1 },
-    { 0,  1,  3, -1, -1, -1, -1, -1, -1 },
-    { 0,  1,  3, -1, -1, -1, -1, -1, -1 },
-    { 0,  1,  3, -1, -1, -1, -1, -1, -1 },
-    { 2,  0,  1,  4, -1, -1, -1, -1, -1 },
-    { 0,  1,  3,  4, -1, -1, -1, -1, -1 },
-    { 2,  0,  1,  4,  5, -1, -1, -1, -1 },
-    { 0,  1,  4,  5,  3, -1, -1, -1, -1 },
-    { 2,  0,  1,  5,  6,  4, -1, -1, -1 },
-    { 3,  4,  0,  1,  6,  7,  5, -1, -1 },
-    { 2,  0,  1,  4,  5,  6,  7, -1, -1 },
-    { 0,  6,  4,  5,  2,  3,  7, -1, -1 },
-    { 4,  2,  5,  0,  1,  7,  8,  6, -1 },
-    { 5,  6,  0,  1,  8,  3,  9,  4,  7 },
-    { 4,  2,  5,  0,  1,  6,  9,  8,  7 },
-};
-
-static const int8_t dca_channel_reorder_nolfe[][9] = {
-    { 0, -1, -1, -1, -1, -1, -1, -1, -1 },
-    { 0,  1, -1, -1, -1, -1, -1, -1, -1 },
-    { 0,  1, -1, -1, -1, -1, -1, -1, -1 },
-    { 0,  1, -1, -1, -1, -1, -1, -1, -1 },
-    { 0,  1, -1, -1, -1, -1, -1, -1, -1 },
-    { 2,  0,  1, -1, -1, -1, -1, -1, -1 },
-    { 0,  1,  2, -1, -1, -1, -1, -1, -1 },
-    { 2,  0,  1,  3, -1, -1, -1, -1, -1 },
-    { 0,  1,  2,  3, -1, -1, -1, -1, -1 },
-    { 2,  0,  1,  3,  4, -1, -1, -1, -1 },
-    { 2,  3,  0,  1,  4,  5, -1, -1, -1 },
-    { 2,  0,  1,  3,  4,  5, -1, -1, -1 },
-    { 0,  5,  3,  4,  1,  2, -1, -1, -1 },
-    { 3,  2,  4,  0,  1,  5,  6, -1, -1 },
-    { 4,  5,  0,  1,  6,  2,  7,  3, -1 },
-    { 3,  2,  4,  0,  1,  5,  7,  6, -1 },
-};
-
-static const int8_t dca_channel_reorder_nolfe_xch[][9] = {
-    { 0,  1, -1, -1, -1, -1, -1, -1, -1 },
-    { 0,  1,  2, -1, -1, -1, -1, -1, -1 },
-    { 0,  1,  2, -1, -1, -1, -1, -1, -1 },
-    { 0,  1,  2, -1, -1, -1, -1, -1, -1 },
-    { 0,  1,  2, -1, -1, -1, -1, -1, -1 },
-    { 2,  0,  1,  3, -1, -1, -1, -1, -1 },
-    { 0,  1,  2,  3, -1, -1, -1, -1, -1 },
-    { 2,  0,  1,  3,  4, -1, -1, -1, -1 },
-    { 0,  1,  3,  4,  2, -1, -1, -1, -1 },
-    { 2,  0,  1,  4,  5,  3, -1, -1, -1 },
-    { 2,  3,  0,  1,  5,  6,  4, -1, -1 },
-    { 2,  0,  1,  3,  4,  5,  6, -1, -1 },
-    { 0,  5,  3,  4,  1,  2,  6, -1, -1 },
-    { 3,  2,  4,  0,  1,  6,  7,  5, -1 },
-    { 4,  5,  0,  1,  7,  2,  8,  3,  6 },
-    { 3,  2,  4,  0,  1,  5,  8,  7,  6 },
-};
-
 #define DCA_DOLBY                  101           /* FIXME */
 
 #define DCA_CHANNEL_BITS             6
@@ -321,15 +110,11 @@
 
 #define HEADER_SIZE                 14
 
-#define DCA_MAX_FRAME_SIZE       16384
-#define DCA_MAX_EXSS_HEADER_SIZE  4096
-
-#define DCA_BUFFER_PADDING_SIZE   1024
-
 #define DCA_NSYNCAUX        0x9A1105A0
 
+
 /** Bit allocation */
-typedef struct {
+typedef struct BitAlloc {
     int offset;                 ///< code values offset
     int maxbits[8];             ///< max bits in VLC
     int wrap;                   ///< wrap for get_vlc2()
@@ -348,148 +133,8 @@
            ba->offset;
 }
 
-typedef struct {
-    const AVClass *class;       ///< class for AVOptions
-    AVCodecContext *avctx;
-    /* Frame header */
-    int frame_type;             ///< type of the current frame
-    int samples_deficit;        ///< deficit sample count
-    int crc_present;            ///< crc is present in the bitstream
-    int sample_blocks;          ///< number of PCM sample blocks
-    int frame_size;             ///< primary frame byte size
-    int amode;                  ///< audio channels arrangement
-    int sample_rate;            ///< audio sampling rate
-    int bit_rate;               ///< transmission bit rate
-    int bit_rate_index;         ///< transmission bit rate index
-
-    int dynrange;               ///< embedded dynamic range flag
-    int timestamp;              ///< embedded time stamp flag
-    int aux_data;               ///< auxiliary data flag
-    int hdcd;                   ///< source material is mastered in HDCD
-    int ext_descr;              ///< extension audio descriptor flag
-    int ext_coding;             ///< extended coding flag
-    int aspf;                   ///< audio sync word insertion flag
-    int lfe;                    ///< low frequency effects flag
-    int predictor_history;      ///< predictor history flag
-    int header_crc;             ///< header crc check bytes
-    int multirate_inter;        ///< multirate interpolator switch
-    int version;                ///< encoder software revision
-    int copy_history;           ///< copy history
-    int source_pcm_res;         ///< source pcm resolution
-    int front_sum;              ///< front sum/difference flag
-    int surround_sum;           ///< surround sum/difference flag
-    int dialog_norm;            ///< dialog normalisation parameter
-
-    /* Primary audio coding header */
-    int subframes;              ///< number of subframes
-    int total_channels;         ///< number of channels including extensions
-    int prim_channels;          ///< number of primary audio channels
-    int subband_activity[DCA_PRIM_CHANNELS_MAX];    ///< subband activity count
-    int vq_start_subband[DCA_PRIM_CHANNELS_MAX];    ///< high frequency vq start subband
-    int joint_intensity[DCA_PRIM_CHANNELS_MAX];     ///< joint intensity coding index
-    int transient_huffman[DCA_PRIM_CHANNELS_MAX];   ///< transient mode code book
-    int scalefactor_huffman[DCA_PRIM_CHANNELS_MAX]; ///< scale factor code book
-    int bitalloc_huffman[DCA_PRIM_CHANNELS_MAX];    ///< bit allocation quantizer select
-    int quant_index_huffman[DCA_PRIM_CHANNELS_MAX][DCA_ABITS_MAX]; ///< quantization index codebook select
-    float scalefactor_adj[DCA_PRIM_CHANNELS_MAX][DCA_ABITS_MAX];   ///< scale factor adjustment
-
-    /* Primary audio coding side information */
-    int subsubframes[DCA_SUBFRAMES_MAX];                         ///< number of subsubframes
-    int partial_samples[DCA_SUBFRAMES_MAX];                      ///< partial subsubframe samples count
-    int prediction_mode[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];    ///< prediction mode (ADPCM used or not)
-    int prediction_vq[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];      ///< prediction VQ coefs
-    int bitalloc[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];           ///< bit allocation index
-    int transition_mode[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];    ///< transition mode (transients)
-    int32_t scale_factor[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][2];///< scale factors (2 if transient)
-    int joint_huff[DCA_PRIM_CHANNELS_MAX];                       ///< joint subband scale factors codebook
-    int joint_scale_factor[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS]; ///< joint subband scale factors
-    float downmix_coef[DCA_PRIM_CHANNELS_MAX + 1][2];            ///< stereo downmix coefficients
-    int dynrange_coef;                                           ///< dynamic range coefficient
-
-    /* Core substream's embedded downmix coefficients (cf. ETSI TS 102 114 V1.4.1)
-     * Input:  primary audio channels (incl. LFE if present)
-     * Output: downmix audio channels (up to 4, no LFE) */
-    uint8_t  core_downmix;                                       ///< embedded downmix coefficients available
-    uint8_t  core_downmix_amode;                                 ///< audio channel arrangement of embedded downmix
-    uint16_t core_downmix_codes[DCA_PRIM_CHANNELS_MAX + 1][4];   ///< embedded downmix coefficients (9-bit codes)
-
-    int32_t  high_freq_vq[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];  ///< VQ encoded high frequency subbands
-
-    float lfe_data[2 * DCA_LFE_MAX * (DCA_BLOCKS_MAX + 4)];      ///< Low frequency effect data
-    int lfe_scale_factor;
-
-    /* Subband samples history (for ADPCM) */
-    DECLARE_ALIGNED(16, float, subband_samples_hist)[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][4];
-    DECLARE_ALIGNED(32, float, subband_fir_hist)[DCA_PRIM_CHANNELS_MAX][512];
-    DECLARE_ALIGNED(32, float, subband_fir_noidea)[DCA_PRIM_CHANNELS_MAX][32];
-    int hist_index[DCA_PRIM_CHANNELS_MAX];
-    DECLARE_ALIGNED(32, float, raXin)[32];
-
-    int output;                 ///< type of output
-
-    DECLARE_ALIGNED(32, float, subband_samples)[DCA_BLOCKS_MAX][DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][8];
-    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
-
-    const int8_t *channel_order_tab;  ///< channel reordering table, lfe and non lfe
-    GetBitContext gb;
-    /* Current position in DCA frame */
-    int current_subframe;
-    int current_subsubframe;
-
-    int core_ext_mask;          ///< present extensions in the core substream
-
-    /* XCh extension information */
-    int xch_present;            ///< XCh extension present and valid
-    int xch_base_channel;       ///< index of first (only) channel containing XCH data
-    int xch_disable;            ///< whether the XCh extension should be decoded or not
-
-    /* XXCH extension information */
-    int xxch_chset;
-    int xxch_nbits_spk_mask;
-    uint32_t xxch_core_spkmask;
-    uint32_t xxch_spk_masks[4]; /* speaker masks, last element is core mask */
-    int xxch_chset_nch[4];
-    float xxch_dmix_sf[DCA_CHSETS_MAX];
-
-    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 */
-
-    int8_t xxch_order_tab[32];
-    int8_t lfe_index;
-
-    /* ExSS header parser */
-    int static_fields;          ///< static fields present
-    int mix_metadata;           ///< mixing metadata present
-    int num_mix_configs;        ///< number of mix out configurations
-    int mix_config_num_ch[4];   ///< number of channels in each mix out configuration
-
-    int profile;
-
-    int debug_flag;             ///< used for suppressing repeated error messages output
-    AVFloatDSPContext *fdsp;
-    FFTContext imdct;
-    SynthFilterContext synth;
-    DCADSPContext dcadsp;
-    FmtConvertContext fmt_conv;
-} DCAContext;
-
 static float dca_dmix_code(unsigned code);
 
-static const uint16_t dca_vlc_offs[] = {
-        0,   512,   640,   768,  1282,  1794,  2436,  3080,  3770,  4454,  5364,
-     5372,  5380,  5388,  5392,  5396,  5412,  5420,  5428,  5460,  5492,  5508,
-     5572,  5604,  5668,  5796,  5860,  5892,  6412,  6668,  6796,  7308,  7564,
-     7820,  8076,  8620,  9132,  9388,  9910, 10166, 10680, 11196, 11726, 12240,
-    12752, 13298, 13810, 14326, 14840, 15500, 16022, 16540, 17158, 17678, 18264,
-    18796, 19352, 19926, 20468, 21472, 22398, 23014, 23622,
-};
-
 static av_cold void dca_init_vlcs(void)
 {
     static int vlcs_initialized = 0;
@@ -502,8 +147,8 @@
     dca_bitalloc_index.offset = 1;
     dca_bitalloc_index.wrap   = 2;
     for (i = 0; i < 5; i++) {
-        dca_bitalloc_index.vlc[i].table           = &dca_table[dca_vlc_offs[i]];
-        dca_bitalloc_index.vlc[i].table_allocated = dca_vlc_offs[i + 1] - dca_vlc_offs[i];
+        dca_bitalloc_index.vlc[i].table           = &dca_table[ff_dca_vlc_offs[i]];
+        dca_bitalloc_index.vlc[i].table_allocated = ff_dca_vlc_offs[i + 1] - ff_dca_vlc_offs[i];
         init_vlc(&dca_bitalloc_index.vlc[i], bitalloc_12_vlc_bits[i], 12,
                  bitalloc_12_bits[i], 1, 1,
                  bitalloc_12_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
@@ -511,8 +156,8 @@
     dca_scalefactor.offset = -64;
     dca_scalefactor.wrap   = 2;
     for (i = 0; i < 5; i++) {
-        dca_scalefactor.vlc[i].table           = &dca_table[dca_vlc_offs[i + 5]];
-        dca_scalefactor.vlc[i].table_allocated = dca_vlc_offs[i + 6] - dca_vlc_offs[i + 5];
+        dca_scalefactor.vlc[i].table           = &dca_table[ff_dca_vlc_offs[i + 5]];
+        dca_scalefactor.vlc[i].table_allocated = ff_dca_vlc_offs[i + 6] - ff_dca_vlc_offs[i + 5];
         init_vlc(&dca_scalefactor.vlc[i], SCALES_VLC_BITS, 129,
                  scales_bits[i], 1, 1,
                  scales_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
@@ -520,8 +165,8 @@
     dca_tmode.offset = 0;
     dca_tmode.wrap   = 1;
     for (i = 0; i < 4; i++) {
-        dca_tmode.vlc[i].table           = &dca_table[dca_vlc_offs[i + 10]];
-        dca_tmode.vlc[i].table_allocated = dca_vlc_offs[i + 11] - dca_vlc_offs[i + 10];
+        dca_tmode.vlc[i].table           = &dca_table[ff_dca_vlc_offs[i + 10]];
+        dca_tmode.vlc[i].table_allocated = ff_dca_vlc_offs[i + 11] - ff_dca_vlc_offs[i + 10];
         init_vlc(&dca_tmode.vlc[i], tmode_vlc_bits[i], 4,
                  tmode_bits[i], 1, 1,
                  tmode_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
@@ -533,8 +178,8 @@
                 break;
             dca_smpl_bitalloc[i + 1].offset                 = bitalloc_offsets[i];
             dca_smpl_bitalloc[i + 1].wrap                   = 1 + (j > 4);
-            dca_smpl_bitalloc[i + 1].vlc[j].table           = &dca_table[dca_vlc_offs[c]];
-            dca_smpl_bitalloc[i + 1].vlc[j].table_allocated = dca_vlc_offs[c + 1] - dca_vlc_offs[c];
+            dca_smpl_bitalloc[i + 1].vlc[j].table           = &dca_table[ff_dca_vlc_offs[c]];
+            dca_smpl_bitalloc[i + 1].vlc[j].table_allocated = ff_dca_vlc_offs[c + 1] - ff_dca_vlc_offs[c];
 
             init_vlc(&dca_smpl_bitalloc[i + 1].vlc[j], bitalloc_maxbits[i][j],
                      bitalloc_sizes[i],
@@ -690,33 +335,6 @@
     s->current_subframe    = 0;
     s->current_subsubframe = 0;
 
-#ifdef TRACE
-    av_log(s->avctx, AV_LOG_DEBUG, "subframes: %i\n", s->subframes);
-    av_log(s->avctx, AV_LOG_DEBUG, "prim channels: %i\n", s->prim_channels);
-    for (i = base_channel; i < s->prim_channels; i++) {
-        av_log(s->avctx, AV_LOG_DEBUG, "subband activity: %i\n",
-               s->subband_activity[i]);
-        av_log(s->avctx, AV_LOG_DEBUG, "vq start subband: %i\n",
-               s->vq_start_subband[i]);
-        av_log(s->avctx, AV_LOG_DEBUG, "joint intensity: %i\n",
-               s->joint_intensity[i]);
-        av_log(s->avctx, AV_LOG_DEBUG, "transient mode codebook: %i\n",
-               s->transient_huffman[i]);
-        av_log(s->avctx, AV_LOG_DEBUG, "scale factor codebook: %i\n",
-               s->scalefactor_huffman[i]);
-        av_log(s->avctx, AV_LOG_DEBUG, "bit allocation quantizer: %i\n",
-               s->bitalloc_huffman[i]);
-        av_log(s->avctx, AV_LOG_DEBUG, "quant index huff:");
-        for (j = 0; j < 11; j++)
-            av_log(s->avctx, AV_LOG_DEBUG, " %i", s->quant_index_huffman[i][j]);
-        av_log(s->avctx, AV_LOG_DEBUG, "\n");
-        av_log(s->avctx, AV_LOG_DEBUG, "scalefac adj:");
-        for (j = 0; j < 11; j++)
-            av_log(s->avctx, AV_LOG_DEBUG, " %1.3f", s->scalefactor_adj[i][j]);
-        av_log(s->avctx, AV_LOG_DEBUG, "\n");
-    }
-#endif
-
     return 0;
 }
 
@@ -740,7 +358,7 @@
     if (!s->sample_rate)
         return AVERROR_INVALIDDATA;
     s->bit_rate_index    = get_bits(&s->gb, 5);
-    s->bit_rate          = dca_bit_rates[s->bit_rate_index];
+    s->bit_rate          = ff_dca_bit_rates[s->bit_rate_index];
     if (!s->bit_rate)
         return AVERROR_INVALIDDATA;
 
@@ -778,43 +396,6 @@
     if (s->lfe)
         s->output |= DCA_LFE;
 
-#ifdef TRACE
-    av_log(s->avctx, AV_LOG_DEBUG, "frame type: %i\n", s->frame_type);
-    av_log(s->avctx, AV_LOG_DEBUG, "samples deficit: %i\n", s->samples_deficit);
-    av_log(s->avctx, AV_LOG_DEBUG, "crc present: %i\n", s->crc_present);
-    av_log(s->avctx, AV_LOG_DEBUG, "sample blocks: %i (%i samples)\n",
-           s->sample_blocks, s->sample_blocks * 32);
-    av_log(s->avctx, AV_LOG_DEBUG, "frame size: %i bytes\n", s->frame_size);
-    av_log(s->avctx, AV_LOG_DEBUG, "amode: %i (%i channels)\n",
-           s->amode, dca_channels[s->amode]);
-    av_log(s->avctx, AV_LOG_DEBUG, "sample rate: %i Hz\n",
-           s->sample_rate);
-    av_log(s->avctx, AV_LOG_DEBUG, "bit rate: %i bits/s\n",
-           s->bit_rate);
-    av_log(s->avctx, AV_LOG_DEBUG, "dynrange: %i\n", s->dynrange);
-    av_log(s->avctx, AV_LOG_DEBUG, "timestamp: %i\n", s->timestamp);
-    av_log(s->avctx, AV_LOG_DEBUG, "aux_data: %i\n", s->aux_data);
-    av_log(s->avctx, AV_LOG_DEBUG, "hdcd: %i\n", s->hdcd);
-    av_log(s->avctx, AV_LOG_DEBUG, "ext descr: %i\n", s->ext_descr);
-    av_log(s->avctx, AV_LOG_DEBUG, "ext coding: %i\n", s->ext_coding);
-    av_log(s->avctx, AV_LOG_DEBUG, "aspf: %i\n", s->aspf);
-    av_log(s->avctx, AV_LOG_DEBUG, "lfe: %i\n", s->lfe);
-    av_log(s->avctx, AV_LOG_DEBUG, "predictor history: %i\n",
-           s->predictor_history);
-    av_log(s->avctx, AV_LOG_DEBUG, "header crc: %i\n", s->header_crc);
-    av_log(s->avctx, AV_LOG_DEBUG, "multirate inter: %i\n",
-           s->multirate_inter);
-    av_log(s->avctx, AV_LOG_DEBUG, "version number: %i\n", s->version);
-    av_log(s->avctx, AV_LOG_DEBUG, "copy history: %i\n", s->copy_history);
-    av_log(s->avctx, AV_LOG_DEBUG,
-           "source pcm resolution: %i (%i bits/sample)\n",
-           s->source_pcm_res, dca_bits_per_sample[s->source_pcm_res]);
-    av_log(s->avctx, AV_LOG_DEBUG, "front sum: %i\n", s->front_sum);
-    av_log(s->avctx, AV_LOG_DEBUG, "surround sum: %i\n", s->surround_sum);
-    av_log(s->avctx, AV_LOG_DEBUG, "dialog norm: %i\n", s->dialog_norm);
-    av_log(s->avctx, AV_LOG_DEBUG, "\n");
-#endif
-
     /* Primary audio coding header */
     s->subframes = get_bits(&s->gb, 4) + 1;
 
@@ -913,10 +494,10 @@
                s->subband_activity[j] * sizeof(s->scale_factor[0][0][0]) * 2);
 
         if (s->scalefactor_huffman[j] == 6) {
-            scale_table = scale_factor_quant7;
+            scale_table = ff_dca_scale_factor_quant7;
             log_size    = 7;
         } else {
-            scale_table = scale_factor_quant6;
+            scale_table = ff_dca_scale_factor_quant6;
             log_size    = 6;
         }
 
@@ -1010,7 +591,7 @@
             avpriv_request_sample(s->avctx, "LFEScaleIndex larger than 127");
             return AVERROR_INVALIDDATA;
         }
-        s->lfe_scale_factor = scale_factor_quant7[quant7];
+        s->lfe_scale_factor = ff_dca_scale_factor_quant7[quant7];
 
         /* Quantization step size * scale factor */
         lfe_scale = 0.035 * s->lfe_scale_factor;
@@ -1019,72 +600,6 @@
             s->lfe_data[j] *= lfe_scale;
     }
 
-#ifdef TRACE
-    av_log(s->avctx, AV_LOG_DEBUG, "subsubframes: %i\n",
-           s->subsubframes[s->current_subframe]);
-    av_log(s->avctx, AV_LOG_DEBUG, "partial samples: %i\n",
-           s->partial_samples[s->current_subframe]);
-
-    for (j = base_channel; j < s->prim_channels; j++) {
-        av_log(s->avctx, AV_LOG_DEBUG, "prediction mode:");
-        for (k = 0; k < s->subband_activity[j]; k++)
-            av_log(s->avctx, AV_LOG_DEBUG, " %i", s->prediction_mode[j][k]);
-        av_log(s->avctx, AV_LOG_DEBUG, "\n");
-    }
-    for (j = base_channel; j < s->prim_channels; j++) {
-        for (k = 0; k < s->subband_activity[j]; k++)
-            av_log(s->avctx, AV_LOG_DEBUG,
-                   "prediction coefs: %f, %f, %f, %f\n",
-                   (float) adpcm_vb[s->prediction_vq[j][k]][0] / 8192,
-                   (float) adpcm_vb[s->prediction_vq[j][k]][1] / 8192,
-                   (float) adpcm_vb[s->prediction_vq[j][k]][2] / 8192,
-                   (float) adpcm_vb[s->prediction_vq[j][k]][3] / 8192);
-    }
-    for (j = base_channel; j < s->prim_channels; j++) {
-        av_log(s->avctx, AV_LOG_DEBUG, "bitalloc index: ");
-        for (k = 0; k < s->vq_start_subband[j]; k++)
-            av_log(s->avctx, AV_LOG_DEBUG, "%2.2i ", s->bitalloc[j][k]);
-        av_log(s->avctx, AV_LOG_DEBUG, "\n");
-    }
-    for (j = base_channel; j < s->prim_channels; j++) {
-        av_log(s->avctx, AV_LOG_DEBUG, "Transition mode:");
-        for (k = 0; k < s->subband_activity[j]; k++)
-            av_log(s->avctx, AV_LOG_DEBUG, " %i", s->transition_mode[j][k]);
-        av_log(s->avctx, AV_LOG_DEBUG, "\n");
-    }
-    for (j = base_channel; j < s->prim_channels; j++) {
-        av_log(s->avctx, AV_LOG_DEBUG, "Scale factor:");
-        for (k = 0; k < s->subband_activity[j]; k++) {
-            if (k >= s->vq_start_subband[j] || s->bitalloc[j][k] > 0)
-                av_log(s->avctx, AV_LOG_DEBUG, " %i", s->scale_factor[j][k][0]);
-            if (k < s->vq_start_subband[j] && s->transition_mode[j][k])
-                av_log(s->avctx, AV_LOG_DEBUG, " %i(t)", s->scale_factor[j][k][1]);
-        }
-        av_log(s->avctx, AV_LOG_DEBUG, "\n");
-    }
-    for (j = base_channel; j < s->prim_channels; j++) {
-        if (s->joint_intensity[j] > 0) {
-            int source_channel = s->joint_intensity[j] - 1;
-            av_log(s->avctx, AV_LOG_DEBUG, "Joint scale factor index:\n");
-            for (k = s->subband_activity[j]; k < s->subband_activity[source_channel]; k++)
-                av_log(s->avctx, AV_LOG_DEBUG, " %i", s->joint_scale_factor[j][k]);
-            av_log(s->avctx, AV_LOG_DEBUG, "\n");
-        }
-    }
-    for (j = base_channel; j < s->prim_channels; j++)
-        for (k = s->vq_start_subband[j]; k < s->subband_activity[j]; k++)
-            av_log(s->avctx, AV_LOG_DEBUG, "VQ index: %i\n", s->high_freq_vq[j][k]);
-    if (!base_channel && s->lfe) {
-        int lfe_samples    = 2 * s->lfe * (4 + block_index);
-        int lfe_end_sample = 2 * s->lfe * (4 + block_index + s->subsubframes[s->current_subframe]);
-
-        av_log(s->avctx, AV_LOG_DEBUG, "LFE samples:\n");
-        for (j = lfe_samples; j < lfe_end_sample; j++)
-            av_log(s->avctx, AV_LOG_DEBUG, " %f", s->lfe_data[j]);
-        av_log(s->avctx, AV_LOG_DEBUG, "\n");
-    }
-#endif
-
     return 0;
 }
 
@@ -1100,9 +615,9 @@
 
     /* Select filter */
     if (!s->multirate_inter)    /* Non-perfect reconstruction */
-        prCoeff = fir_32bands_nonperfect;
+        prCoeff = ff_dca_fir_32bands_nonperfect;
     else                        /* Perfect reconstruction */
-        prCoeff = fir_32bands_perfect;
+        prCoeff = ff_dca_fir_32bands_perfect;
 
     s->dcadsp.qmf_32_subbands(samples_in, sb_act, &s->synth, &s->imdct,
                               s->subband_fir_hist[chans],
@@ -1111,8 +626,83 @@
                               samples_out, s->raXin, scale);
 }
 
-static void lfe_interpolation_fir(DCAContext *s, int decimation_select,
-                                  int num_deci_sample, float *samples_in,
+static QMF64_table *qmf64_precompute(void)
+{
+    unsigned i, j;
+    QMF64_table *table = av_malloc(sizeof(*table));
+    if (!table)
+        return NULL;
+
+    for (i = 0; i < 32; i++)
+        for (j = 0; j < 32; j++)
+            table->dct4_coeff[i][j] = cos((2 * i + 1) * (2 * j + 1) * M_PI / 128);
+    for (i = 0; i < 32; i++)
+        for (j = 0; j < 32; j++)
+            table->dct2_coeff[i][j] = cos((2 * i + 1) *      j      * M_PI /  64);
+
+    /* FIXME: Is the factor 0.125 = 1/8 right? */
+    for (i = 0; i < 32; i++)
+        table->rcos[i] =  0.125 / cos((2 * i + 1) * M_PI / 256);
+    for (i = 0; i < 32; i++)
+        table->rsin[i] = -0.125 / sin((2 * i + 1) * M_PI / 256);
+
+    return table;
+}
+
+/* FIXME: Totally unoptimized. Based on the reference code and
+ * http://multimedia.cx/mirror/dca-transform.pdf, with guessed tweaks
+ * for doubling the size. */
+static void qmf_64_subbands(DCAContext *s, int chans, float samples_in[64][8],
+                            float *samples_out, float scale)
+{
+    float raXin[64];
+    float A[32], B[32];
+    float *raX = s->subband_fir_hist[chans];
+    float *raZ = s->subband_fir_noidea[chans];
+    unsigned i, j, k, subindex;
+
+    for (i = s->subband_activity[chans]; i < 64; i++)
+        raXin[i] = 0.0;
+    for (subindex = 0; subindex < 8; subindex++) {
+        for (i = 0; i < s->subband_activity[chans]; i++)
+            raXin[i] = samples_in[i][subindex];
+
+        for (k = 0; k < 32; k++) {
+            A[k] = 0.0;
+            for (i = 0; i < 32; i++)
+                A[k] += (raXin[2 * i] + raXin[2 * i + 1]) * s->qmf64_table->dct4_coeff[k][i];
+        }
+        for (k = 0; k < 32; k++) {
+            B[k] = raXin[0] * s->qmf64_table->dct2_coeff[k][0];
+            for (i = 1; i < 32; i++)
+                B[k] += (raXin[2 * i] + raXin[2 * i - 1]) * s->qmf64_table->dct2_coeff[k][i];
+        }
+        for (k = 0; k < 32; k++) {
+            raX[k]      = s->qmf64_table->rcos[k] * (A[k] + B[k]);
+            raX[63 - k] = s->qmf64_table->rsin[k] * (A[k] - B[k]);
+        }
+
+        for (i = 0; i < 64; i++) {
+            float out = raZ[i];
+            for (j = 0; j < 1024; j += 128)
+                out += ff_dca_fir_64bands[j + i] * (raX[j + i] - raX[j + 63 - i]);
+            *samples_out++ = out * scale;
+        }
+
+        for (i = 0; i < 64; i++) {
+            float hist = 0.0;
+            for (j = 0; j < 1024; j += 128)
+                hist += ff_dca_fir_64bands[64 + j + i] * (-raX[i + j] - raX[j + 63 - i]);
+
+            raZ[i] = hist;
+        }
+
+        /* FIXME: Make buffer circular, to avoid this move. */
+        memmove(raX + 64, raX, (1024 - 64) * sizeof(*raX));
+    }
+}
+
+static void lfe_interpolation_fir(DCAContext *s, const float *samples_in,
                                   float *samples_out)
 {
     /* samples_in: An array holding decimated samples.
@@ -1128,15 +718,18 @@
     int deciindex;
 
     /* Select decimation filter */
-    if (decimation_select == 1) {
+    if (s->lfe == 1) {
         idx     = 1;
-        prCoeff = lfe_fir_128;
+        prCoeff = ff_dca_lfe_fir_128;
     } else {
-        idx     = 0;
-        prCoeff = lfe_fir_64;
+        idx = 0;
+        if (s->exss_ext_mask & DCA_EXT_EXSS_XLL)
+            prCoeff = ff_dca_lfe_xll_fir_64;
+        else
+            prCoeff = ff_dca_lfe_fir_64;
     }
     /* Interpolation */
-    for (deciindex = 0; deciindex < num_deci_sample; deciindex++) {
+    for (deciindex = 0; deciindex < 2 * s->lfe; deciindex++) {
         s->dcadsp.lfe_fir[idx](samples_out, samples_in, prCoeff);
         samples_in++;
         samples_out += 2 * 32 * (1 + idx);
@@ -1217,8 +810,8 @@
         break;
     }
     if (lfe_present) {
-        int lf_buf = dca_lfe_index[srcfmt];
-        int lf_idx =  dca_channels[srcfmt];
+        int lf_buf = ff_dca_lfe_index[srcfmt];
+        int lf_idx =  ff_dca_channels[srcfmt];
         for (i = 0; i < 256; i++) {
             samples[0][i] += samples[lf_buf][i] * coef[lf_idx][0];
             samples[1][i] += samples[lf_buf][i] * coef[lf_idx][1];
@@ -1270,9 +863,9 @@
 
     /* Select quantization step size table */
     if (s->bit_rate_index == 0x1f)
-        quant_step_table = lossless_quant_d;
+        quant_step_table = ff_dca_lossless_quant_d;
     else
-        quant_step_table = lossy_quant_d;
+        quant_step_table = ff_dca_lossy_quant_d;
 
     for (k = base_channel; k < s->prim_channels; k++) {
         float rscale[DCA_SUBBANDS];
@@ -1349,24 +942,24 @@
             if (s->prediction_mode[k][l]) {
                 int n;
                 if (s->predictor_history)
-                    subband_samples[k][l][0] += (adpcm_vb[s->prediction_vq[k][l]][0] *
+                    subband_samples[k][l][0] += (ff_dca_adpcm_vb[s->prediction_vq[k][l]][0] *
                                                  s->subband_samples_hist[k][l][3] +
-                                                 adpcm_vb[s->prediction_vq[k][l]][1] *
+                                                 ff_dca_adpcm_vb[s->prediction_vq[k][l]][1] *
                                                  s->subband_samples_hist[k][l][2] +
-                                                 adpcm_vb[s->prediction_vq[k][l]][2] *
+                                                 ff_dca_adpcm_vb[s->prediction_vq[k][l]][2] *
                                                  s->subband_samples_hist[k][l][1] +
-                                                 adpcm_vb[s->prediction_vq[k][l]][3] *
+                                                 ff_dca_adpcm_vb[s->prediction_vq[k][l]][3] *
                                                  s->subband_samples_hist[k][l][0]) *
                                                 (1.0f / 8192);
                 for (m = 1; m < 8; m++) {
-                    float sum = adpcm_vb[s->prediction_vq[k][l]][0] *
+                    float sum = ff_dca_adpcm_vb[s->prediction_vq[k][l]][0] *
                                 subband_samples[k][l][m - 1];
                     for (n = 2; n <= 4; n++)
                         if (m >= n)
-                            sum += adpcm_vb[s->prediction_vq[k][l]][n - 1] *
+                            sum += ff_dca_adpcm_vb[s->prediction_vq[k][l]][n - 1] *
                                    subband_samples[k][l][m - n];
                         else if (s->predictor_history)
-                            sum += adpcm_vb[s->prediction_vq[k][l]][n - 1] *
+                            sum += ff_dca_adpcm_vb[s->prediction_vq[k][l]][n - 1] *
                                    s->subband_samples_hist[k][l][m - n + 4];
                     subband_samples[k][l][m] += sum * (1.0f / 8192);
                 }
@@ -1383,7 +976,7 @@
                 s->debug_flag |= 0x01;
             }
             s->dcadsp.decode_hf(subband_samples[k], s->high_freq_vq[k],
-                                high_freq_vq, subsubframe * 8,
+                                ff_dca_high_freq_vq, subsubframe * 8,
                                 s->scale_factor[k], s->vq_start_subband[k],
                                 s->subband_activity[k]);
         }
@@ -1391,11 +984,7 @@
 
     /* Check for DSYNC after subsubframe */
     if (s->aspf || subsubframe == s->subsubframes[s->current_subframe] - 1) {
-        if (0xFFFF == get_bits(&s->gb, 16)) {   /* 0xFFFF */
-#ifdef TRACE
-            av_log(s->avctx, AV_LOG_DEBUG, "Got subframe DSYNC\n");
-#endif
-        } else {
+        if (get_bits(&s->gb, 16) != 0xFFFF) {
             av_log(s->avctx, AV_LOG_ERROR, "Didn't get subframe DSYNC\n");
             return AVERROR_INVALIDDATA;
         }
@@ -1409,27 +998,56 @@
     return 0;
 }
 
-static int dca_filter_channels(DCAContext *s, int block_index)
+static int dca_filter_channels(DCAContext *s, int block_index, int upsample)
 {
     float (*subband_samples)[DCA_SUBBANDS][8] = s->subband_samples[block_index];
     int k;
 
-    /* 32 subbands QMF */
-    for (k = 0; k < s->prim_channels; k++) {
-        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);
+    if (upsample) {
+        if (!s->qmf64_table) {
+            s->qmf64_table = qmf64_precompute();
+            if (!s->qmf64_table)
+                return AVERROR(ENOMEM);
+        }
+
+        /* 64 subbands QMF */
+        for (k = 0; k < s->prim_channels; k++) {
+            if (s->channel_order_tab[k] >= 0)
+                qmf_64_subbands(s, k, subband_samples[k],
+                                s->samples_chanptr[s->channel_order_tab[k]],
+                                /* Upsampling needs a factor 2 here. */
+                                M_SQRT2 / 32768.0);
+        }
+    } else {
+        /* 32 subbands QMF */
+        for (k = 0; k < s->prim_channels; k++) {
+            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);
+        }
     }
 
     /* Generate LFE samples for this subsubframe FIXME!!! */
     if (s->lfe) {
-        lfe_interpolation_fir(s, s->lfe, 2 * s->lfe,
+        float *samples = s->samples_chanptr[s->lfe_index];
+        lfe_interpolation_fir(s,
                               s->lfe_data + 2 * s->lfe * (block_index + 4),
-                              s->samples_chanptr[s->lfe_index]);
-        /* Outputs 20bits pcm samples */
+                              samples);
+        if (upsample) {
+            unsigned i;
+            /* Should apply the filter in Table 6-11 when upsampling. For
+             * now, just duplicate. */
+            for (i = 255; i > 0; i--) {
+                samples[2 * i]     =
+                samples[2 * i + 1] = samples[i];
+            }
+            samples[1] = samples[0];
+        }
     }
 
+    /* FIXME: This downmixing is probably broken with upsample.
+     * Probably totally broken also with XLL in general. */
     /* Downmixing to Stereo */
     if (s->prim_channels + !!s->lfe > 2 &&
         s->avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
@@ -1507,7 +1125,7 @@
                            am);
                     return AVERROR_INVALIDDATA;
                 }
-                for (out = 0; out < dca_channels[s->core_downmix_amode]; out++) {
+                for (out = 0; out < ff_dca_channels[s->core_downmix_amode]; out++) {
                     for (in = 0; in < s->prim_channels + !!s->lfe; in++) {
                         uint16_t tmp = get_bits(&s->gb, 9);
                         if ((tmp & 0xFF) > 241) {
@@ -1561,18 +1179,12 @@
     }
 
     if (!s->current_subsubframe) {
-#ifdef TRACE
-        av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subframe_header\n");
-#endif
         /* Read subframe header */
         if ((ret = dca_subframe_header(s, base_channel, block_index)))
             return ret;
     }
 
     /* Read subsubframe */
-#ifdef TRACE
-    av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subsubframe\n");
-#endif
     if ((ret = dca_subsubframe(s, base_channel, block_index)))
         return ret;
 
@@ -1583,9 +1195,6 @@
         s->current_subframe++;
     }
     if (s->current_subframe >= s->subframes) {
-#ifdef TRACE
-        av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subframe_footer\n");
-#endif
         /* Read subframe footer */
         if ((ret = dca_subframe_footer(s, base_channel)))
             return ret;
@@ -1594,197 +1203,7 @@
     return 0;
 }
 
-/**
- * Return the number of channels in an ExSS speaker mask (HD)
- */
-static int dca_exss_mask2count(int mask)
-{
-    /* count bits that mean speaker pairs twice */
-    return av_popcount(mask) +
-           av_popcount(mask & (DCA_EXSS_CENTER_LEFT_RIGHT      |
-                               DCA_EXSS_FRONT_LEFT_RIGHT       |
-                               DCA_EXSS_FRONT_HIGH_LEFT_RIGHT  |
-                               DCA_EXSS_WIDE_LEFT_RIGHT        |
-                               DCA_EXSS_SIDE_LEFT_RIGHT        |
-                               DCA_EXSS_SIDE_HIGH_LEFT_RIGHT   |
-                               DCA_EXSS_SIDE_REAR_LEFT_RIGHT   |
-                               DCA_EXSS_REAR_LEFT_RIGHT        |
-                               DCA_EXSS_REAR_HIGH_LEFT_RIGHT));
-}
-
-/**
- * Skip mixing coefficients of a single mix out configuration (HD)
- */
-static void dca_exss_skip_mix_coeffs(GetBitContext *gb, int channels, int out_ch)
-{
-    int i;
-
-    for (i = 0; i < channels; i++) {
-        int mix_map_mask = get_bits(gb, out_ch);
-        int num_coeffs = av_popcount(mix_map_mask);
-        skip_bits_long(gb, num_coeffs * 6);
-    }
-}
-
-/**
- * Parse extension substream asset header (HD)
- */
-static int dca_exss_parse_asset_header(DCAContext *s)
-{
-    int header_pos = get_bits_count(&s->gb);
-    int header_size;
-    int channels = 0;
-    int embedded_stereo = 0;
-    int embedded_6ch    = 0;
-    int drc_code_present;
-    int extensions_mask = 0;
-    int i, j;
-
-    if (get_bits_left(&s->gb) < 16)
-        return -1;
-
-    /* We will parse just enough to get to the extensions bitmask with which
-     * we can set the profile value. */
-
-    header_size = get_bits(&s->gb, 9) + 1;
-    skip_bits(&s->gb, 3); // asset index
-
-    if (s->static_fields) {
-        if (get_bits1(&s->gb))
-            skip_bits(&s->gb, 4); // asset type descriptor
-        if (get_bits1(&s->gb))
-            skip_bits_long(&s->gb, 24); // language descriptor
-
-        if (get_bits1(&s->gb)) {
-            /* How can one fit 1024 bytes of text here if the maximum value
-             * for the asset header size field above was 512 bytes? */
-            int text_length = get_bits(&s->gb, 10) + 1;
-            if (get_bits_left(&s->gb) < text_length * 8)
-                return -1;
-            skip_bits_long(&s->gb, text_length * 8); // info text
-        }
-
-        skip_bits(&s->gb, 5); // bit resolution - 1
-        skip_bits(&s->gb, 4); // max sample rate code
-        channels = get_bits(&s->gb, 8) + 1;
-
-        if (get_bits1(&s->gb)) { // 1-to-1 channels to speakers
-            int spkr_remap_sets;
-            int spkr_mask_size = 16;
-            int num_spkrs[7];
-
-            if (channels > 2)
-                embedded_stereo = get_bits1(&s->gb);
-            if (channels > 6)
-                embedded_6ch = get_bits1(&s->gb);
-
-            if (get_bits1(&s->gb)) {
-                spkr_mask_size = (get_bits(&s->gb, 2) + 1) << 2;
-                skip_bits(&s->gb, spkr_mask_size); // spkr activity mask
-            }
-
-            spkr_remap_sets = get_bits(&s->gb, 3);
-
-            for (i = 0; i < spkr_remap_sets; i++) {
-                /* std layout mask for each remap set */
-                num_spkrs[i] = dca_exss_mask2count(get_bits(&s->gb, spkr_mask_size));
-            }
-
-            for (i = 0; i < spkr_remap_sets; i++) {
-                int num_dec_ch_remaps = get_bits(&s->gb, 5) + 1;
-                if (get_bits_left(&s->gb) < 0)
-                    return -1;
-
-                for (j = 0; j < num_spkrs[i]; j++) {
-                    int remap_dec_ch_mask = get_bits_long(&s->gb, num_dec_ch_remaps);
-                    int num_dec_ch = av_popcount(remap_dec_ch_mask);
-                    skip_bits_long(&s->gb, num_dec_ch * 5); // remap codes
-                }
-            }
-        } else {
-            skip_bits(&s->gb, 3); // representation type
-        }
-    }
-
-    drc_code_present = get_bits1(&s->gb);
-    if (drc_code_present)
-        get_bits(&s->gb, 8); // drc code
-
-    if (get_bits1(&s->gb))
-        skip_bits(&s->gb, 5); // dialog normalization code
-
-    if (drc_code_present && embedded_stereo)
-        get_bits(&s->gb, 8); // drc stereo code
-
-    if (s->mix_metadata && get_bits1(&s->gb)) {
-        skip_bits(&s->gb, 1); // external mix
-        skip_bits(&s->gb, 6); // post mix gain code
-
-        if (get_bits(&s->gb, 2) != 3) // mixer drc code
-            skip_bits(&s->gb, 3); // drc limit
-        else
-            skip_bits(&s->gb, 8); // custom drc code
-
-        if (get_bits1(&s->gb)) // channel specific scaling
-            for (i = 0; i < s->num_mix_configs; i++)
-                skip_bits_long(&s->gb, s->mix_config_num_ch[i] * 6); // scale codes
-        else
-            skip_bits_long(&s->gb, s->num_mix_configs * 6); // scale codes
-
-        for (i = 0; i < s->num_mix_configs; i++) {
-            if (get_bits_left(&s->gb) < 0)
-                return -1;
-            dca_exss_skip_mix_coeffs(&s->gb, channels, s->mix_config_num_ch[i]);
-            if (embedded_6ch)
-                dca_exss_skip_mix_coeffs(&s->gb, 6, s->mix_config_num_ch[i]);
-            if (embedded_stereo)
-                dca_exss_skip_mix_coeffs(&s->gb, 2, s->mix_config_num_ch[i]);
-        }
-    }
-
-    switch (get_bits(&s->gb, 2)) {
-    case 0:
-        extensions_mask = get_bits(&s->gb, 12);
-        break;
-    case 1:
-        extensions_mask = DCA_EXT_EXSS_XLL;
-        break;
-    case 2:
-        extensions_mask = DCA_EXT_EXSS_LBR;
-        break;
-    case 3:
-        extensions_mask = 0; /* aux coding */
-        break;
-    }
-
-    /* not parsed further, we were only interested in the extensions mask */
-
-    if (get_bits_left(&s->gb) < 0)
-        return -1;
-
-    if (get_bits_count(&s->gb) - header_pos > header_size * 8) {
-        av_log(s->avctx, AV_LOG_WARNING, "Asset header size mismatch.\n");
-        return -1;
-    }
-    skip_bits_long(&s->gb, header_pos + header_size * 8 - get_bits_count(&s->gb));
-
-    if (extensions_mask & DCA_EXT_EXSS_XLL)
-        s->profile = FF_PROFILE_DTS_HD_MA;
-    else if (extensions_mask & (DCA_EXT_EXSS_XBR | DCA_EXT_EXSS_X96 |
-                                DCA_EXT_EXSS_XXCH))
-        s->profile = FF_PROFILE_DTS_HD_HRA;
-
-    if (!(extensions_mask & DCA_EXT_CORE))
-        av_log(s->avctx, AV_LOG_WARNING, "DTS core detection mismatch.\n");
-    if ((extensions_mask & DCA_CORE_EXTS) != s->core_ext_mask)
-        av_log(s->avctx, AV_LOG_WARNING,
-               "DTS extensions detection mismatch (%d, %d)\n",
-               extensions_mask & DCA_CORE_EXTS, s->core_ext_mask);
-
-    return 0;
-}
-
-static int dca_xbr_parse_frame(DCAContext *s)
+int ff_dca_xbr_parse_frame(DCAContext *s)
 {
     int scale_table_high[DCA_CHSET_CHANS_MAX][DCA_SUBBANDS][2];
     int active_bands[DCA_CHSETS_MAX][DCA_CHSET_CHANS_MAX];
@@ -1856,9 +1275,9 @@
                     int nbits;
 
                     if (s->scalefactor_huffman[chan_base+i] == 6) {
-                        scale_table = scale_factor_quant7;
+                        scale_table = ff_dca_scale_factor_quant7;
                     } else {
-                        scale_table = scale_factor_quant6;
+                        scale_table = ff_dca_scale_factor_quant6;
                     }
 
                     nbits = anctemp[i];
@@ -1881,7 +1300,7 @@
             for(i = 0; i < n_xbr_ch[chset]; i++) {
                 for(j = 0; j < active_bands[chset][i]; j++) {
                     const int xbr_abits = abits_high[i][j];
-                    const float quant_step_size = lossless_quant_d[xbr_abits];
+                    const float quant_step_size = ff_dca_lossless_quant_d[xbr_abits];
                     const int sfi = xbr_tmode && s->transition_mode[i][j] && subsubframe >= s->transition_mode[i][j];
                     const float rscale = quant_step_size * scale_table_high[i][j][sfi];
                     float *subband_samples = s->subband_samples[k][chan_base+i][j];
@@ -1944,8 +1363,9 @@
     return 0;
 }
 
+
 /* parse initial header for XXCH and dump details */
-static int dca_xxch_decode_frame(DCAContext *s)
+int ff_dca_xxch_decode_frame(DCAContext *s)
 {
     int hdr_size, spkmsk_bits, num_chsets, core_spk, hdr_pos;
     int i, chset, base_channel, chstart, fsize[8];
@@ -1998,127 +1418,11 @@
     return 0;
 }
 
-/**
- * Parse extension substream header (HD)
- */
-static void dca_exss_parse_header(DCAContext *s)
-{
-    int asset_size[8];
-    int ss_index;
-    int blownup;
-    int num_audiop = 1;
-    int num_assets = 1;
-    int active_ss_mask[8];
-    int i, j;
-    int start_posn;
-    int hdrsize;
-    uint32_t mkr;
-
-    if (get_bits_left(&s->gb) < 52)
-        return;
-
-    start_posn = get_bits_count(&s->gb) - 32;
-
-    skip_bits(&s->gb, 8); // user data
-    ss_index = get_bits(&s->gb, 2);
-
-    blownup = get_bits1(&s->gb);
-    hdrsize = get_bits(&s->gb,  8 + 4 * blownup) + 1; // header_size
-    skip_bits(&s->gb, 16 + 4 * blownup); // hd_size
-
-    s->static_fields = get_bits1(&s->gb);
-    if (s->static_fields) {
-        skip_bits(&s->gb, 2); // reference clock code
-        skip_bits(&s->gb, 3); // frame duration code
-
-        if (get_bits1(&s->gb))
-            skip_bits_long(&s->gb, 36); // timestamp
-
-        /* a single stream can contain multiple audio assets that can be
-         * combined to form multiple audio presentations */
-
-        num_audiop = get_bits(&s->gb, 3) + 1;
-        if (num_audiop > 1) {
-            avpriv_request_sample(s->avctx,
-                                  "Multiple DTS-HD audio presentations");
-            /* ignore such streams for now */
-            return;
-        }
-
-        num_assets = get_bits(&s->gb, 3) + 1;
-        if (num_assets > 1) {
-            avpriv_request_sample(s->avctx, "Multiple DTS-HD audio assets");
-            /* ignore such streams for now */
-            return;
-        }
-
-        for (i = 0; i < num_audiop; i++)
-            active_ss_mask[i] = get_bits(&s->gb, ss_index + 1);
-
-        for (i = 0; i < num_audiop; i++)
-            for (j = 0; j <= ss_index; j++)
-                if (active_ss_mask[i] & (1 << j))
-                    skip_bits(&s->gb, 8); // active asset mask
-
-        s->mix_metadata = get_bits1(&s->gb);
-        if (s->mix_metadata) {
-            int mix_out_mask_size;
-
-            skip_bits(&s->gb, 2); // adjustment level
-            mix_out_mask_size  = (get_bits(&s->gb, 2) + 1) << 2;
-            s->num_mix_configs =  get_bits(&s->gb, 2) + 1;
-
-            for (i = 0; i < s->num_mix_configs; i++) {
-                int mix_out_mask        = get_bits(&s->gb, mix_out_mask_size);
-                s->mix_config_num_ch[i] = dca_exss_mask2count(mix_out_mask);
-            }
-        }
-    }
-
-    av_assert0(num_assets > 0); // silence a warning
-
-    for (i = 0; i < num_assets; i++)
-        asset_size[i] = get_bits_long(&s->gb, 16 + 4 * blownup);
-
-    for (i = 0; i < num_assets; i++) {
-        if (dca_exss_parse_asset_header(s))
-            return;
-    }
-
-    /* not parsed further, we were only interested in the extensions mask
-     * from the asset header */
-
-        j = get_bits_count(&s->gb);
-        if (start_posn + hdrsize * 8 > j)
-            skip_bits_long(&s->gb, start_posn + hdrsize * 8 - j);
-
-        for (i = 0; i < num_assets; i++) {
-            start_posn = get_bits_count(&s->gb);
-            mkr        = get_bits_long(&s->gb, 32);
-
-            /* parse extensions that we know about */
-            if (mkr == 0x655e315e) {
-                dca_xbr_parse_frame(s);
-            } else if (mkr == 0x47004a03) {
-                dca_xxch_decode_frame(s);
-                s->core_ext_mask |= DCA_EXT_XXCH; /* xxx use for chan reordering */
-            } else {
-                av_log(s->avctx, AV_LOG_DEBUG,
-                       "DTS-ExSS: unknown marker = 0x%08x\n", mkr);
-            }
-
-            /* skip to end of block */
-            j = get_bits_count(&s->gb);
-            if (start_posn + asset_size[i] * 8 > j)
-                skip_bits_long(&s->gb, start_posn + asset_size[i] * 8 - j);
-        }
-}
-
 static float dca_dmix_code(unsigned code)
 {
     int sign = (code >> 8) - 1;
     code &= 0xff;
-    return ((dca_dmixtable[code] ^ sign) - sign) * (1.0 / (1 << 15));
+    return ((ff_dca_dmixtable[code] ^ sign) - sign) * (1.0 / (1 << 15));
 }
 
 /**
@@ -2150,8 +1454,10 @@
     int posn;
     int j, k;
     int endch;
+    int upsample = 0;
 
-    s->xch_present = 0;
+    s->exss_ext_mask = 0;
+    s->xch_present   = 0;
 
     s->dca_buffer_size = avpriv_dca_convert_bitstream(buf, buf_size, s->dca_buffer,
                                                   DCA_MAX_FRAME_SIZE + DCA_MAX_EXSS_HEADER_SIZE);
@@ -2166,7 +1472,6 @@
     }
     // set AVCodec values with parsed data
     avctx->sample_rate = s->sample_rate;
-    avctx->bit_rate    = s->bit_rate;
 
     s->profile = FF_PROFILE_DTS;
 
@@ -2197,20 +1502,20 @@
                 s->output = s->core_downmix_amode;
             } else {
                 int am = s->amode & DCA_CHANNEL_MASK;
-                if (am >= FF_ARRAY_ELEMS(dca_default_coeffs)) {
+                if (am >= FF_ARRAY_ELEMS(ff_dca_default_coeffs)) {
                     av_log(s->avctx, AV_LOG_ERROR,
                            "Invalid channel mode %d\n", am);
                     return AVERROR_INVALIDDATA;
                 }
                 if (num_core_channels + !!s->lfe >
-                    FF_ARRAY_ELEMS(dca_default_coeffs[0])) {
+                    FF_ARRAY_ELEMS(ff_dca_default_coeffs[0])) {
                     avpriv_request_sample(s->avctx, "Downmixing %d channels",
                                           s->prim_channels + !!s->lfe);
                     return AVERROR_PATCHWELCOME;
                 }
                 for (i = 0; i < num_core_channels + !!s->lfe; i++) {
-                    s->downmix_coef[i][0] = dca_default_coeffs[am][i][0];
-                    s->downmix_coef[i][1] = dca_default_coeffs[am][i][1];
+                    s->downmix_coef[i][0] = ff_dca_default_coeffs[am][i][0];
+                    s->downmix_coef[i][1] = ff_dca_default_coeffs[am][i][1];
                 }
             }
             av_dlog(s->avctx, "Stereo downmix coeffs:\n");
@@ -2224,7 +1529,7 @@
     }
 
     if (s->ext_coding)
-        s->core_ext_mask = dca_ext_audio_descr_mask[s->ext_descr];
+        s->core_ext_mask = ff_dca_ext_audio_descr_mask[s->ext_descr];
     else
         s->core_ext_mask = 0;
 
@@ -2244,7 +1549,7 @@
             uint32_t bits = get_bits_long(&s->gb, 32);
 
             switch (bits) {
-            case 0x5a5a5a5a: {
+            case DCA_SYNCWORD_XCH: {
                 int ext_amode, xch_fsize;
 
                 s->xch_base_channel = s->prim_channels;
@@ -2286,12 +1591,12 @@
                 s->xch_present = 1;
                 break;
             }
-            case 0x47004a03:
+            case DCA_SYNCWORD_XXCH:
                 /* XXCh: extended channels */
                 /* usually found either in core or HD part in DTS-HD HRA streams,
                  * but not in DTS-ES which contains XCh extensions instead */
                 s->core_ext_mask |= DCA_EXT_XXCH;
-                dca_xxch_decode_frame(s);
+                ff_dca_xxch_decode_frame(s);
                 break;
 
             case 0x1d95f262: {
@@ -2324,8 +1629,8 @@
 
     /* check for ExSS (HD part) */
     if (s->dca_buffer_size - s->frame_size > 32 &&
-        get_bits_long(&s->gb, 32) == DCA_HD_MARKER)
-        dca_exss_parse_header(s);
+        get_bits_long(&s->gb, 32) == DCA_SYNCWORD_SUBSTREAM)
+        ff_dca_exss_parse_header(s);
 
     avctx->profile = s->profile;
 
@@ -2339,7 +1644,7 @@
             < num_core_channels + !!s->lfe + s->xxch_chset_nch[0]))
     { /* xxx should also do MA extensions */
         if (s->amode < 16) {
-            avctx->channel_layout = dca_core_channel_layout[s->amode];
+            avctx->channel_layout = ff_dca_core_channel_layout[s->amode];
 
             if (s->prim_channels + !!s->lfe > 2 &&
                 avctx->request_channel_layout == AV_CH_LAYOUT_STEREO) {
@@ -2367,9 +1672,9 @@
                 avctx->channel_layout |= AV_CH_BACK_CENTER;
                 if (s->lfe) {
                     avctx->channel_layout |= AV_CH_LOW_FREQUENCY;
-                    s->channel_order_tab = dca_channel_reorder_lfe_xch[s->amode];
+                    s->channel_order_tab = ff_dca_channel_reorder_lfe_xch[s->amode];
                 } else {
-                    s->channel_order_tab = dca_channel_reorder_nolfe_xch[s->amode];
+                    s->channel_order_tab = ff_dca_channel_reorder_nolfe_xch[s->amode];
                 }
                 if (s->channel_order_tab[s->xch_base_channel] < 0)
                     return AVERROR_INVALIDDATA;
@@ -2378,9 +1683,9 @@
                 s->xch_present = 0; /* disable further xch processing */
                 if (s->lfe) {
                     avctx->channel_layout |= AV_CH_LOW_FREQUENCY;
-                    s->channel_order_tab = dca_channel_reorder_lfe[s->amode];
+                    s->channel_order_tab = ff_dca_channel_reorder_lfe[s->amode];
                 } else
-                    s->channel_order_tab = dca_channel_reorder_nolfe[s->amode];
+                    s->channel_order_tab = ff_dca_channel_reorder_nolfe[s->amode];
             }
 
             if (channels > !!s->lfe &&
@@ -2402,7 +1707,7 @@
                 static const int8_t dca_channel_order_native[9] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
                 s->channel_order_tab = dca_channel_order_native;
             }
-            s->lfe_index = dca_lfe_index[s->amode];
+            s->lfe_index = ff_dca_lfe_index[s->amode];
         } else {
             av_log(avctx, AV_LOG_ERROR,
                    "Non standard configuration %d !\n", s->amode);
@@ -2433,7 +1738,7 @@
         channel_layout = 0;
         for (i = 0; i < s->xxch_nbits_spk_mask; ++i) {
             if (channel_mask & (1 << i)) {
-                channel_layout |= map_xxch_to_native[i];
+                channel_layout |= ff_dca_map_xxch_to_native[i];
             }
         }
 
@@ -2454,7 +1759,7 @@
                                   : s->xxch_core_spkmask;
                 for (i = 0; i < s->xxch_nbits_spk_mask; i++) {
                     if (mask & ~(DCA_XXCH_LFE1 | DCA_XXCH_LFE2) & (1 << i)) {
-                        lavc = map_xxch_to_native[i];
+                        lavc = ff_dca_map_xxch_to_native[i];
                         posn = av_popcount(channel_layout & (lavc - 1));
                         s->xxch_order_tab[j++] = posn;
                     }
@@ -2473,14 +1778,51 @@
         s->channel_order_tab = s->xxch_order_tab;
     }
 
+    /* get output buffer */
+    frame->nb_samples = 256 * (s->sample_blocks / 8);
+    if (s->exss_ext_mask & DCA_EXT_EXSS_XLL) {
+        int xll_nb_samples = s->xll_segments * s->xll_smpl_in_seg;
+        /* Check for invalid/unsupported conditions first */
+        if (s->xll_residual_channels > channels) {
+            av_log(s->avctx, AV_LOG_WARNING,
+                   "DCA: too many residual channels (%d, core channels %d). Disabling XLL\n",
+                   s->xll_residual_channels, channels);
+            s->exss_ext_mask &= ~DCA_EXT_EXSS_XLL;
+        } else if (xll_nb_samples != frame->nb_samples &&
+                   2 * frame->nb_samples != xll_nb_samples) {
+            av_log(s->avctx, AV_LOG_WARNING,
+                   "DCA: unsupported upsampling (%d XLL samples, %d core samples). Disabling XLL\n",
+                   xll_nb_samples, frame->nb_samples);
+            s->exss_ext_mask &= ~DCA_EXT_EXSS_XLL;
+        } else {
+            if (2 * frame->nb_samples == xll_nb_samples) {
+                av_log(s->avctx, AV_LOG_INFO,
+                       "XLL: upsampling core channels by a factor of 2\n");
+                upsample = 1;
+
+                frame->nb_samples = xll_nb_samples;
+                // FIXME: Is it good enough to copy from the first channel set?
+                avctx->sample_rate = s->xll_chsets[0].sampling_frequency;
+            }
+            /* If downmixing to stereo, don't decode additional channels.
+             * FIXME: Using the xch_disable flag for this doesn't seem right. */
+            if (!s->xch_disable)
+                channels = s->xll_channels;
+        }
+    }
+
     if (avctx->channels != channels) {
         if (avctx->channels)
             av_log(avctx, AV_LOG_INFO, "Number of channels changed in DCA decoder (%d -> %d)\n", avctx->channels, channels);
         avctx->channels = channels;
     }
 
-    /* get output buffer */
-    frame->nb_samples = 256 * (s->sample_blocks / 8);
+    /* FIXME: This is an ugly hack, to just revert to the default
+     * layout if we have additional channels. Need to convert the XLL
+     * channel masks to ffmpeg channel_layout mask. */
+    if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels)
+        avctx->channel_layout = 0;
+
     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
         return ret;
     samples_flt = (float **) frame->extended_data;
@@ -2509,13 +1851,13 @@
     /* filter to get final output */
     for (i = 0; i < (s->sample_blocks / 8); i++) {
         int ch;
-
+        unsigned block = upsample ? 512 : 256;
         for (ch = 0; ch < channels; ch++)
-            s->samples_chanptr[ch] = samples_flt[ch] + i * 256;
+            s->samples_chanptr[ch] = samples_flt[ch] + i * block;
         for (; ch < full_channels; ch++)
-            s->samples_chanptr[ch] = s->extra_channels[ch - channels] + i * 256;
+            s->samples_chanptr[ch] = s->extra_channels[ch - channels] + i * block;
 
-        dca_filter_channels(s, i);
+        dca_filter_channels(s, i, upsample);
 
         /* If this was marked as a DTS-ES stream we need to subtract back- */
         /* channel from SL & SR to remove matrixed back-channel signal */
@@ -2580,6 +1922,11 @@
     for (i = 0; i < 2 * s->lfe * 4; i++)
         s->lfe_data[i] = s->lfe_data[i + lfe_samples];
 
+    if (s->exss_ext_mask & DCA_EXT_EXSS_XLL) {
+        ret = ff_dca_xll_decode_audio(s, frame);
+        if (ret < 0)
+            return ret;
+    }
     /* AVMatrixEncoding
      *
      * DCA_STEREO_TOTAL (Lt/Rt) is equivalent to Dolby Surround */
@@ -2589,6 +1936,9 @@
     if (ret < 0)
         return ret;
 
+    if (   avctx->profile != FF_PROFILE_DTS_HD_MA
+        && avctx->profile != FF_PROFILE_DTS_HD_HRA)
+        avctx->bit_rate = s->bit_rate;
     *got_frame_ptr = 1;
 
     return buf_size;
@@ -2638,6 +1988,8 @@
     ff_mdct_end(&s->imdct);
     av_freep(&s->extra_channels_buffer);
     av_freep(&s->fdsp);
+    av_freep(&s->xll_sample_buf);
+    av_freep(&s->qmf64_table);
     return 0;
 }
 
@@ -2652,6 +2004,7 @@
 
 static const AVOption options[] = {
     { "disable_xch", "disable decoding of the XCh extension", offsetof(DCAContext, xch_disable), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM },
+    { "disable_xll", "disable decoding of the XLL extension", offsetof(DCAContext, xll_disable), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM },
     { NULL },
 };
 
diff --git a/libavcodec/dcaenc.c b/libavcodec/dcaenc.c
index 905cdc9..d57d658 100644
--- a/libavcodec/dcaenc.c
+++ b/libavcodec/dcaenc.c
@@ -37,13 +37,13 @@
 #define DCA_HEADER_SIZE 13
 #define DCA_LFE_SAMPLES 8
 
-#define DCA_SUBBANDS 32
+#define DCAENC_SUBBANDS 32
 #define SUBFRAMES 1
 #define SUBSUBFRAMES 2
 #define SUBBAND_SAMPLES (SUBFRAMES * SUBSUBFRAMES * 8)
 #define AUBANDS 25
 
-typedef struct DCAContext {
+typedef struct DCAEncContext {
     PutBitContext pb;
     int frame_size;
     int frame_bits;
@@ -60,20 +60,20 @@
     int32_t lfe_peak_cb;
 
     int32_t history[512][MAX_CHANNELS]; /* This is a circular buffer */
-    int32_t subband[SUBBAND_SAMPLES][DCA_SUBBANDS][MAX_CHANNELS];
-    int32_t quantized[SUBBAND_SAMPLES][DCA_SUBBANDS][MAX_CHANNELS];
-    int32_t peak_cb[DCA_SUBBANDS][MAX_CHANNELS];
+    int32_t subband[SUBBAND_SAMPLES][DCAENC_SUBBANDS][MAX_CHANNELS];
+    int32_t quantized[SUBBAND_SAMPLES][DCAENC_SUBBANDS][MAX_CHANNELS];
+    int32_t peak_cb[DCAENC_SUBBANDS][MAX_CHANNELS];
     int32_t downsampled_lfe[DCA_LFE_SAMPLES];
     int32_t masking_curve_cb[SUBSUBFRAMES][256];
-    int abits[DCA_SUBBANDS][MAX_CHANNELS];
-    int scale_factor[DCA_SUBBANDS][MAX_CHANNELS];
-    softfloat quant[DCA_SUBBANDS][MAX_CHANNELS];
+    int abits[DCAENC_SUBBANDS][MAX_CHANNELS];
+    int scale_factor[DCAENC_SUBBANDS][MAX_CHANNELS];
+    softfloat quant[DCAENC_SUBBANDS][MAX_CHANNELS];
     int32_t eff_masking_curve_cb[256];
     int32_t band_masking_cb[32];
     int32_t worst_quantization_noise;
     int32_t worst_noise_ever;
     int consumed_bits;
-} DCAContext;
+} DCAEncContext;
 
 static int32_t cos_table[2048];
 static int32_t band_interpolation[2][512];
@@ -105,7 +105,7 @@
 
 static int encode_init(AVCodecContext *avctx)
 {
-    DCAContext *c = avctx->priv_data;
+    DCAEncContext *c = avctx->priv_data;
     uint64_t layout = avctx->channel_layout;
     int i, min_frame_bits;
 
@@ -148,10 +148,10 @@
         av_log(avctx, AV_LOG_ERROR, "Bit rate %i not supported.", avctx->bit_rate);
         return AVERROR(EINVAL);
     }
-    for (i = 0; dca_bit_rates[i] < avctx->bit_rate; i++)
+    for (i = 0; ff_dca_bit_rates[i] < avctx->bit_rate; i++)
         ;
     c->bitrate_index = i;
-    avctx->bit_rate = dca_bit_rates[i];
+    avctx->bit_rate = ff_dca_bit_rates[i];
     c->frame_bits = FFALIGN((avctx->bit_rate * 512 + avctx->sample_rate - 1) / avctx->sample_rate, 32);
     min_frame_bits = 132 + (493 + 28 * 32) * c->fullband_channels + c->lfe_channel * 72;
     if (c->frame_bits < min_frame_bits || c->frame_bits > (DCA_MAX_FRAME_SIZE << 3))
@@ -171,13 +171,13 @@
 
         /* FIXME: probably incorrect */
         for (i = 0; i < 256; i++) {
-            lfe_fir_64i[i] = (int32_t)(0x01ffffff * lfe_fir_64[i]);
-            lfe_fir_64i[511 - i] = (int32_t)(0x01ffffff * lfe_fir_64[i]);
+            lfe_fir_64i[i] = (int32_t)(0x01ffffff * ff_dca_lfe_fir_64[i]);
+            lfe_fir_64i[511 - i] = (int32_t)(0x01ffffff * ff_dca_lfe_fir_64[i]);
         }
 
         for (i = 0; i < 512; i++) {
-            band_interpolation[0][i] = (int32_t)(0x1000000000ULL * fir_32bands_perfect[i]);
-            band_interpolation[1][i] = (int32_t)(0x1000000000ULL * fir_32bands_nonperfect[i]);
+            band_interpolation[0][i] = (int32_t)(0x1000000000ULL * ff_dca_fir_32bands_perfect[i]);
+            band_interpolation[1][i] = (int32_t)(0x1000000000ULL * ff_dca_fir_32bands_nonperfect[i]);
         }
 
         for (i = 0; i < 9; i++) {
@@ -197,7 +197,7 @@
         for (j = 0; j < 8; j++) {
             double accum = 0;
             for (i = 0; i < 512; i++) {
-                double reconst = fir_32bands_perfect[i] * ((i & 64) ? (-1) : 1);
+                double reconst = ff_dca_fir_32bands_perfect[i] * ((i & 64) ? (-1) : 1);
                 accum += reconst * cos(2 * M_PI * (i + 0.5 - 256) * (j + 0.5) / 512);
             }
             band_spectrum[0][j] = (int32_t)(200 * log10(accum));
@@ -205,7 +205,7 @@
         for (j = 0; j < 8; j++) {
             double accum = 0;
             for (i = 0; i < 512; i++) {
-                double reconst = fir_32bands_nonperfect[i] * ((i & 64) ? (-1) : 1);
+                double reconst = ff_dca_fir_32bands_nonperfect[i] * ((i & 64) ? (-1) : 1);
                 accum += reconst * cos(2 * M_PI * (i + 0.5 - 256) * (j + 0.5) / 512);
             }
             band_spectrum[1][j] = (int32_t)(200 * log10(accum));
@@ -235,7 +235,7 @@
     return r >> 32;
 }
 
-static void subband_transform(DCAContext *c, const int32_t *input)
+static void subband_transform(DCAEncContext *c, const int32_t *input)
 {
     int ch, subs, i, k, j;
 
@@ -285,7 +285,7 @@
     }
 }
 
-static void lfe_downsample(DCAContext *c, const int32_t *input)
+static void lfe_downsample(DCAEncContext *c, const int32_t *input)
 {
     /* FIXME: make 128x LFE downsampling possible */
     int i, j, lfes;
@@ -442,11 +442,11 @@
         out_cb[j] = add_cb(out_cb[j], -out_cb_unnorm[j] - ca_cb - cs_cb);
 }
 
-typedef void (*walk_band_t)(DCAContext *c, int band1, int band2, int f,
+typedef void (*walk_band_t)(DCAEncContext *c, int band1, int band2, int f,
                             int32_t spectrum1, int32_t spectrum2, int channel,
                             int32_t * arg);
 
-static void walk_band_low(DCAContext *c, int band, int channel,
+static void walk_band_low(DCAEncContext *c, int band, int channel,
                           walk_band_t walk, int32_t *arg)
 {
     int f;
@@ -461,7 +461,7 @@
     }
 }
 
-static void walk_band_high(DCAContext *c, int band, int channel,
+static void walk_band_high(DCAEncContext *c, int band, int channel,
                            walk_band_t walk, int32_t *arg)
 {
     int f;
@@ -476,7 +476,7 @@
     }
 }
 
-static void update_band_masking(DCAContext *c, int band1, int band2,
+static void update_band_masking(DCAEncContext *c, int band1, int band2,
                                 int f, int32_t spectrum1, int32_t spectrum2,
                                 int channel, int32_t * arg)
 {
@@ -486,7 +486,7 @@
         c->band_masking_cb[band1] = value;
 }
 
-static void calc_masking(DCAContext *c, const int32_t *input)
+static void calc_masking(DCAEncContext *c, const int32_t *input)
 {
     int i, k, band, ch, ssf;
     int32_t data[512];
@@ -519,7 +519,7 @@
     }
 }
 
-static void find_peaks(DCAContext *c)
+static void find_peaks(DCAEncContext *c)
 {
     int band, ch;
 
@@ -552,7 +552,7 @@
 #define USED_NABITS 2
 #define USED_26ABITS 4
 
-static int init_quantization_noise(DCAContext *c, int noise)
+static int init_quantization_noise(DCAEncContext *c, int noise)
 {
     int ch, band, ret = 0;
 
@@ -589,7 +589,7 @@
     return ret;
 }
 
-static void assign_bits(DCAContext *c)
+static void assign_bits(DCAEncContext *c)
 {
     /* Find the bounds where the binary search should work */
     int low, high, down;
@@ -627,7 +627,7 @@
         c->worst_noise_ever = high;
 }
 
-static void shift_history(DCAContext *c, const int32_t *input)
+static void shift_history(DCAEncContext *c, const int32_t *input)
 {
     int k, ch;
 
@@ -677,7 +677,7 @@
     return our_nscale;
 }
 
-static void calc_scales(DCAContext *c)
+static void calc_scales(DCAEncContext *c)
 {
     int band, ch;
 
@@ -691,7 +691,7 @@
         c->lfe_scale_factor = calc_one_scale(c->lfe_peak_cb, 11, &c->lfe_quant);
 }
 
-static void quantize_all(DCAContext *c)
+static void quantize_all(DCAEncContext *c)
 {
     int sample, band, ch;
 
@@ -701,7 +701,7 @@
                 c->quantized[sample][band][ch] = quantize_value(c->subband[sample][band][ch], c->quant[band][ch]);
 }
 
-static void put_frame_header(DCAContext *c)
+static void put_frame_header(DCAEncContext *c)
 {
     /* SYNC */
     put_bits(&c->pb, 16, 0x7ffe);
@@ -784,7 +784,7 @@
     put_bits(&c->pb, 4, 0);
 }
 
-static void put_primary_audio_header(DCAContext *c)
+static void put_primary_audio_header(DCAEncContext *c)
 {
     static const int bitlen[11] = { 0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3 };
     static const int thr[11]    = { 0, 1, 3, 3, 3, 3, 7, 7, 7, 7, 7 };
@@ -798,11 +798,11 @@
 
     /* Subband activity count */
     for (ch = 0; ch < c->fullband_channels; ch++)
-        put_bits(&c->pb, 5, DCA_SUBBANDS - 2);
+        put_bits(&c->pb, 5, DCAENC_SUBBANDS - 2);
 
     /* High frequency VQ start subband */
     for (ch = 0; ch < c->fullband_channels; ch++)
-        put_bits(&c->pb, 5, DCA_SUBBANDS - 1);
+        put_bits(&c->pb, 5, DCAENC_SUBBANDS - 1);
 
     /* Joint intensity coding index: 0, 0 */
     for (ch = 0; ch < c->fullband_channels; ch++)
@@ -830,7 +830,7 @@
     /* Audio header CRC check word: not transmitted */
 }
 
-static void put_subframe_samples(DCAContext *c, int ss, int band, int ch)
+static void put_subframe_samples(DCAEncContext *c, int ss, int band, int ch)
 {
     if (c->abits[band][ch] <= 7) {
         int sum, i, j;
@@ -853,7 +853,7 @@
     }
 }
 
-static void put_subframe(DCAContext *c, int subframe)
+static void put_subframe(DCAEncContext *c, int subframe)
 {
     int i, band, ss, ch;
 
@@ -865,25 +865,25 @@
 
     /* Prediction mode: no ADPCM, in each channel and subband */
     for (ch = 0; ch < c->fullband_channels; ch++)
-        for (band = 0; band < DCA_SUBBANDS; band++)
+        for (band = 0; band < DCAENC_SUBBANDS; band++)
             put_bits(&c->pb, 1, 0);
 
     /* Prediction VQ address: not transmitted */
     /* Bit allocation index */
     for (ch = 0; ch < c->fullband_channels; ch++)
-        for (band = 0; band < DCA_SUBBANDS; band++)
+        for (band = 0; band < DCAENC_SUBBANDS; band++)
             put_bits(&c->pb, 5, c->abits[band][ch]);
 
     if (SUBSUBFRAMES > 1) {
         /* Transition mode: none for each channel and subband */
         for (ch = 0; ch < c->fullband_channels; ch++)
-            for (band = 0; band < DCA_SUBBANDS; band++)
+            for (band = 0; band < DCAENC_SUBBANDS; band++)
                 put_bits(&c->pb, 1, 0); /* codebook A4 */
     }
 
     /* Scale factors */
     for (ch = 0; ch < c->fullband_channels; ch++)
-        for (band = 0; band < DCA_SUBBANDS; band++)
+        for (band = 0; band < DCAENC_SUBBANDS; band++)
             put_bits(&c->pb, 7, c->scale_factor[band][ch]);
 
     /* Joint subband scale factor codebook select: not transmitted */
@@ -903,7 +903,7 @@
     /* Audio data (subsubframes) */
     for (ss = 0; ss < SUBSUBFRAMES ; ss++)
         for (ch = 0; ch < c->fullband_channels; ch++)
-            for (band = 0; band < DCA_SUBBANDS; band++)
+            for (band = 0; band < DCAENC_SUBBANDS; band++)
                     put_subframe_samples(c, ss, band, ch);
 
     /* DSYNC */
@@ -913,7 +913,7 @@
 static int encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
                         const AVFrame *frame, int *got_packet_ptr)
 {
-    DCAContext *c = avctx->priv_data;
+    DCAEncContext *c = avctx->priv_data;
     const int32_t *samples;
     int ret, i;
 
@@ -958,7 +958,7 @@
     .long_name             = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
     .type                  = AVMEDIA_TYPE_AUDIO,
     .id                    = AV_CODEC_ID_DTS,
-    .priv_data_size        = sizeof(DCAContext),
+    .priv_data_size        = sizeof(DCAEncContext),
     .init                  = encode_init,
     .encode2               = encode_frame,
     .capabilities          = CODEC_CAP_EXPERIMENTAL,
diff --git a/libavcodec/dct-test.c b/libavcodec/dct-test.c
index 30eca3e..56e1a62 100644
--- a/libavcodec/dct-test.c
+++ b/libavcodec/dct-test.c
@@ -66,7 +66,7 @@
 };
 
 static void ff_prores_idct_wrap(int16_t *dst){
-    DECLARE_ALIGNED(16, static int16_t, qmat)[64];
+    LOCAL_ALIGNED(16, int16_t, qmat, [64]);
     int i;
 
     for(i=0; i<64; i++){
diff --git a/libavcodec/diracdsp.c b/libavcodec/diracdsp.c
index 3b8c39d..6b02779 100644
--- a/libavcodec/diracdsp.c
+++ b/libavcodec/diracdsp.c
@@ -173,7 +173,7 @@
     c->PFX ## _dirac_pixels_tab[WIDTH>>4][2] = ff_ ## PFX ## _dirac_pixels ## WIDTH ## _l4_c; \
     c->PFX ## _dirac_pixels_tab[WIDTH>>4][3] = ff_ ## PFX ## _dirac_pixels ## WIDTH ## _bilinear_c
 
-void ff_diracdsp_init(DiracDSPContext *c)
+av_cold void ff_diracdsp_init(DiracDSPContext *c)
 {
     c->dirac_hpel_filter = dirac_hpel_filter;
     c->add_rect_clamped = add_rect_clamped_c;
diff --git a/libavcodec/dnxhddata.c b/libavcodec/dnxhddata.c
index 7ea9191..b648899 100644
--- a/libavcodec/dnxhddata.c
+++ b/libavcodec/dnxhddata.c
@@ -233,6 +233,28 @@
     34, 37, 39, 44, 51, 56, 61, 70,
 };
 
+static const uint8_t dnxhd_1258_luma_weight[] = {
+     0, 32, 36, 36,  40,  40, 55, 60,
+    34, 36, 37, 40,  41,  48, 57, 82,
+    35, 36, 41, 41,  46,  52, 73, 82,
+    37, 40, 42, 45,  50,  65, 80, 87,
+    39, 41, 44, 49,  62,  78, 88, 90,
+    41, 44, 49, 58,  73,  90, 95, 95,
+    43, 52, 55, 68,  90, 100, 97, 93,
+    52, 53, 71, 82, 107, 103, 99, 99,
+};
+
+static const uint8_t dnxhd_1258_chroma_weight[] = {
+     0, 32, 37,  38,  49,  53,  65,  66,
+    35, 37, 40,  49,  56,  64,  65,  82,
+    36, 42, 50,  56,  64,  67,  73,  85,
+    46, 50, 57,  63,  71,  72,  89,  87,
+    49, 58, 65,  72,  78,  88,  88,  90,
+    60, 64, 74,  81,  84,  90,  95, 134,
+    62, 74, 77,  80,  90, 114, 129, 125,
+    74, 74, 90, 100, 128, 125, 116, 116,
+};
+
 static const uint8_t dnxhd_1237_dc_codes[12] = {
     0, 12, 13, 1, 2, 3, 4, 5, 14, 30, 62, 63,
 };
@@ -956,6 +978,14 @@
     3,
 };
 
+static const uint8_t dnxhd_1258_dc_codes[14] = {
+    0, 12, 13, 1, 2, 3, 4, 5, 14, 30, 62, 63, 0, 0,
+};
+
+static const uint8_t dnxhd_1258_dc_bits[14] = {
+    3, 4, 4, 3, 3, 3, 3, 3, 4, 5, 6, 6, 0, 0,
+};
+
 const CIDEntry ff_dnxhd_cid_table[] = {
     { 1235, 1920, 1080, 0, 917504, 917504, 6, 10, 4,
       dnxhd_1235_luma_weight, dnxhd_1235_chroma_weight,
@@ -1045,6 +1075,14 @@
       dnxhd_1235_1238_1241_run_codes, dnxhd_1235_1238_1241_run_bits, dnxhd_1235_1241_run,
       { 350, 390, 440, 730, 880 },
       { { 24000, 1001 }, { 25, 1 }, { 30000, 1001 }, { 50, 1 }, { 60000, 1001 } } },
+    { 1258, 960, 720, 0, 212992, 212992, 4, 8, 5,
+      dnxhd_1258_luma_weight, dnxhd_1258_chroma_weight,
+      dnxhd_1258_dc_codes, dnxhd_1258_dc_bits,
+      dnxhd_1252_ac_codes, dnxhd_1252_ac_bits, dnxhd_1252_ac_level,
+      dnxhd_1252_ac_flags,
+      dnxhd_1251_run_codes, dnxhd_1251_run_bits, dnxhd_1251_run,
+      { 42, 60, 75, 115 } },
+
 };
 
 int ff_dnxhd_get_cid_table(int cid)
diff --git a/libavcodec/dnxhddec.c b/libavcodec/dnxhddec.c
index 790db89..cc011c4 100644
--- a/libavcodec/dnxhddec.c
+++ b/libavcodec/dnxhddec.c
@@ -136,6 +136,8 @@
         frame->top_field_first  = first_field ^ ctx->cur_field;
         av_log(ctx->avctx, AV_LOG_DEBUG,
                "interlaced %d, cur field %d\n", buf[5] & 3, ctx->cur_field);
+    } else {
+        ctx->cur_field = 0;
     }
 
     ctx->height = AV_RB16(buf + 0x18);
@@ -143,35 +145,32 @@
 
     av_dlog(ctx->avctx, "width %d, height %d\n", ctx->width, ctx->height);
 
-    ctx->is_444 = 0;
-    if (buf[0x4] == 0x2) {
-        ctx->pix_fmt = AV_PIX_FMT_YUV444P10;
-        ctx->avctx->bits_per_raw_sample = 10;
-        if (ctx->bit_depth != 10) {
-            ff_blockdsp_init(&ctx->bdsp, ctx->avctx);
-            ff_idctdsp_init(&ctx->idsp, ctx->avctx);
-            ctx->bit_depth = 10;
+    if (!ctx->bit_depth) {
+        ff_blockdsp_init(&ctx->bdsp, ctx->avctx);
+        ff_idctdsp_init(&ctx->idsp, ctx->avctx);
+    }
+    if (buf[0x21] == 0x58) { /* 10 bit */
+        ctx->bit_depth = ctx->avctx->bits_per_raw_sample = 10;
+
+        if (buf[0x4] == 0x2) {
             ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;
-        }
-        ctx->is_444 = 1;
-    } else if (buf[0x21] & 0x40) {
-        ctx->pix_fmt = AV_PIX_FMT_YUV422P10;
-        ctx->avctx->bits_per_raw_sample = 10;
-        if (ctx->bit_depth != 10) {
-            ff_blockdsp_init(&ctx->bdsp, ctx->avctx);
-            ff_idctdsp_init(&ctx->idsp, ctx->avctx);
-            ctx->bit_depth = 10;
+            ctx->pix_fmt = AV_PIX_FMT_YUV444P10;
+            ctx->is_444 = 1;
+        } else {
             ctx->decode_dct_block = dnxhd_decode_dct_block_10;
+            ctx->pix_fmt = AV_PIX_FMT_YUV422P10;
+            ctx->is_444 = 0;
         }
-    } else {
+    } else if (buf[0x21] == 0x38) { /* 8 bit */
+        ctx->bit_depth = ctx->avctx->bits_per_raw_sample = 8;
+
         ctx->pix_fmt = AV_PIX_FMT_YUV422P;
-        ctx->avctx->bits_per_raw_sample = 8;
-        if (ctx->bit_depth != 8) {
-            ff_blockdsp_init(&ctx->bdsp, ctx->avctx);
-            ff_idctdsp_init(&ctx->idsp, ctx->avctx);
-            ctx->bit_depth = 8;
-            ctx->decode_dct_block = dnxhd_decode_dct_block_8;
-        }
+        ctx->is_444 = 0;
+        ctx->decode_dct_block = dnxhd_decode_dct_block_8;
+    } else {
+        av_log(ctx->avctx, AV_LOG_ERROR, "invalid bit depth value (%d).\n",
+               buf[0x21]);
+        return AVERROR_INVALIDDATA;
     }
 
     cid = AV_RB32(buf + 0x28);
@@ -180,6 +179,15 @@
     if ((ret = dnxhd_init_vlc(ctx, cid)) < 0)
         return ret;
 
+    // make sure profile size constraints are respected
+    // DNx100 allows 1920->1440 and 1280->960 subsampling
+    if (ctx->width != ctx->cid_table->width) {
+        av_reduce(&ctx->avctx->sample_aspect_ratio.num,
+                  &ctx->avctx->sample_aspect_ratio.den,
+                  ctx->width, ctx->cid_table->width, 255);
+        ctx->width = ctx->cid_table->width;
+    }
+
     if (buf_size < ctx->cid_table->coding_unit_size) {
         av_log(ctx->avctx, AV_LOG_ERROR, "incorrect frame size (%d < %d).\n",
                buf_size, ctx->cid_table->coding_unit_size);
@@ -369,7 +377,7 @@
     dest_u = frame->data[1] + ((y * dct_linesize_chroma) << 4) + (x << (3 + shift1 + ctx->is_444));
     dest_v = frame->data[2] + ((y * dct_linesize_chroma) << 4) + (x << (3 + shift1 + ctx->is_444));
 
-    if (ctx->cur_field) {
+    if (frame->interlaced_frame && ctx->cur_field) {
         dest_y += frame->linesize[0];
         dest_u += frame->linesize[1];
         dest_v += frame->linesize[2];
diff --git a/libavcodec/dpx.c b/libavcodec/dpx.c
index 3b78486..66d8428 100644
--- a/libavcodec/dpx.c
+++ b/libavcodec/dpx.c
@@ -173,11 +173,16 @@
         break;
     case 52: // ABGR
     case 51: // RGBA
+    case 103: // UYVA4444
         elements = 4;
         break;
     case 50: // RGB
+    case 102: // UYV444
         elements = 3;
         break;
+    case 100: // UYVY422
+        elements = 2;
+        break;
     default:
         avpriv_report_missing_feature(avctx, "Descriptor %d", descriptor);
         return AVERROR_PATCHWELCOME;
@@ -280,6 +285,15 @@
     case 51160:
         avctx->pix_fmt = AV_PIX_FMT_RGBA64LE;
         break;
+    case 100081:
+        avctx->pix_fmt = AV_PIX_FMT_UYVY422;
+        break;
+    case 102081:
+        avctx->pix_fmt = AV_PIX_FMT_YUV444P;
+        break;
+    case 103081:
+        avctx->pix_fmt = AV_PIX_FMT_YUVA444P;
+        break;
     default:
         av_log(avctx, AV_LOG_ERROR, "Unsupported format\n");
         return AVERROR_PATCHWELCOME;
@@ -344,9 +358,26 @@
     case 16:
         elements *= 2;
     case 8:
+        if (   avctx->pix_fmt == AV_PIX_FMT_YUVA444P
+            || avctx->pix_fmt == AV_PIX_FMT_YUV444P) {
+            for (x = 0; x < avctx->height; x++) {
+                ptr[0] = p->data[0] + x * p->linesize[0];
+                ptr[1] = p->data[1] + x * p->linesize[1];
+                ptr[2] = p->data[2] + x * p->linesize[2];
+                ptr[3] = p->data[3] + x * p->linesize[3];
+                for (y = 0; y < avctx->width; y++) {
+                    *ptr[1]++ = *buf++;
+                    *ptr[0]++ = *buf++;
+                    *ptr[2]++ = *buf++;
+                    if (avctx->pix_fmt == AV_PIX_FMT_YUVA444P)
+                        *ptr[3]++ = *buf++;
+                }
+            }
+        } else {
         av_image_copy_plane(ptr[0], p->linesize[0],
                             buf, stride,
                             elements * avctx->width, avctx->height);
+        }
         break;
     }
 
diff --git a/libavcodec/dss_sp.c b/libavcodec/dss_sp.c
new file mode 100644
index 0000000..42ba1c4
--- /dev/null
+++ b/libavcodec/dss_sp.c
@@ -0,0 +1,787 @@
+/*
+ * Digital Speech Standard - Standard Play mode (DSS SP) audio decoder.
+ * Copyright (C) 2014 Oleksij Rempel <linux@rempel-privat.de>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/channel_layout.h"
+#include "libavutil/common.h"
+#include "libavutil/mem.h"
+#include "libavutil/opt.h"
+
+#include "avcodec.h"
+#include "get_bits.h"
+#include "internal.h"
+
+#define SUBFRAMES 4
+#define PULSE_MAX 8
+
+#define DSS_SP_FRAME_SIZE        42
+#define DSS_SP_SAMPLE_COUNT     (66 * SUBFRAMES)
+#define DSS_SP_FORMULA(a, b, c) (((((a) << 15) + (b) * (c)) + 0x4000) >> 15)
+
+typedef struct DssSpSubframe {
+    int16_t gain;
+    int32_t combined_pulse_pos;
+    int16_t pulse_pos[7];
+    int16_t pulse_val[7];
+} DssSpSubframe;
+
+typedef struct DssSpFrame {
+    int16_t filter_idx[14];
+    int16_t sf_adaptive_gain[SUBFRAMES];
+    int16_t pitch_lag[SUBFRAMES];
+    struct DssSpSubframe sf[SUBFRAMES];
+} DssSpFrame;
+
+typedef struct DssSpContext {
+    AVCodecContext *avctx;
+    int32_t excitation[288 + 6];
+    int32_t history[187];
+    DssSpFrame fparam;
+    int32_t working_buffer[SUBFRAMES][72];
+    int32_t audio_buf[15];
+    int32_t err_buf1[15];
+    int32_t lpc_filter[14];
+    int32_t filter[15];
+    int32_t vector_buf[72];
+    int noise_state;
+    int32_t err_buf2[15];
+
+    int pulse_dec_mode;
+
+    DECLARE_ALIGNED(16, uint8_t, bits)[DSS_SP_FRAME_SIZE +
+                                       FF_INPUT_BUFFER_PADDING_SIZE];
+} DssSpContext;
+
+/*
+ * Used for the coding/decoding of the pulse positions for the MP-MLQ codebook.
+ */
+static const uint32_t dss_sp_combinatorial_table[PULSE_MAX][72] = {
+    {       0,         0,         0,          0,          0,          0,
+            0,         0,         0,          0,          0,          0,
+            0,         0,         0,          0,          0,          0,
+            0,         0,         0,          0,          0,          0,
+            0,         0,         0,          0,          0,          0,
+            0,         0,         0,          0,          0,          0,
+            0,         0,         0,          0,          0,          0,
+            0,         0,         0,          0,          0,          0,
+            0,         0,         0,          0,          0,          0,
+            0,         0,         0,          0,          0,          0,
+            0,         0,         0,          0,          0,          0,
+            0,         0,         0,          0,          0,          0 },
+    {       0,         1,         2,          3,          4,          5,
+            6,         7,         8,          9,         10,         11,
+           12,        13,        14,         15,         16,         17,
+           18,        19,        20,         21,         22,         23,
+           24,        25,        26,         27,         28,         29,
+           30,        31,        32,         33,         34,         35,
+           36,        37,        38,         39,         40,         41,
+           42,        43,        44,         45,         46,         47,
+           48,        49,        50,         51,         52,         53,
+           54,        55,        56,         57,         58,         59,
+           60,        61,        62,         63,         64,         65,
+           66,        67,        68,         69,         70,         71 },
+    {       0,         0,         1,          3,          6,         10,
+           15,        21,        28,         36,         45,         55,
+           66,        78,        91,        105,        120,        136,
+          153,       171,       190,        210,        231,        253,
+          276,       300,       325,        351,        378,        406,
+          435,       465,       496,        528,        561,        595,
+          630,       666,       703,        741,        780,        820,
+          861,       903,       946,        990,       1035,       1081,
+         1128,      1176,      1225,       1275,       1326,       1378,
+         1431,      1485,      1540,       1596,       1653,       1711,
+         1770,      1830,      1891,       1953,       2016,       2080,
+         2145,      2211,      2278,       2346,       2415,       2485 },
+    {       0,         0,         0,          1,          4,         10,
+           20,        35,        56,         84,        120,        165,
+          220,       286,       364,        455,        560,        680,
+          816,       969,      1140,       1330,       1540,       1771,
+         2024,      2300,      2600,       2925,       3276,       3654,
+         4060,      4495,      4960,       5456,       5984,       6545,
+         7140,      7770,      8436,       9139,       9880,      10660,
+        11480,     12341,     13244,      14190,      15180,      16215,
+        17296,     18424,     19600,      20825,      22100,      23426,
+        24804,     26235,     27720,      29260,      30856,      32509,
+        34220,     35990,     37820,      39711,      41664,      43680,
+        45760,     47905,     50116,      52394,      54740,      57155 },
+    {       0,         0,         0,          0,          1,          5,
+           15,        35,        70,        126,        210,        330,
+          495,       715,      1001,       1365,       1820,       2380,
+         3060,      3876,      4845,       5985,       7315,       8855,
+        10626,     12650,     14950,      17550,      20475,      23751,
+        27405,     31465,     35960,      40920,      46376,      52360,
+        58905,     66045,     73815,      82251,      91390,     101270,
+       111930,    123410,    135751,     148995,     163185,     178365,
+       194580,    211876,    230300,     249900,     270725,     292825,
+       316251,    341055,    367290,     395010,     424270,     455126,
+       487635,    521855,    557845,     595665,     635376,     677040,
+       720720,    766480,    814385,     864501,     916895,     971635 },
+    {       0,         0,         0,          0,          0,          1,
+            6,        21,        56,        126,        252,        462,
+          792,      1287,      2002,       3003,       4368,       6188,
+         8568,     11628,     15504,      20349,      26334,      33649,
+        42504,     53130,     65780,      80730,      98280,     118755,
+       142506,    169911,    201376,     237336,     278256,     324632,
+       376992,    435897,    501942,     575757,     658008,     749398,
+       850668,    962598,   1086008,    1221759,    1370754,    1533939,
+      1712304,   1906884,   2118760,    2349060,    2598960,    2869685,
+      3162510,   3478761,   3819816,    4187106,    4582116,    5006386,
+      5461512,   5949147,   6471002,    7028847,    7624512,    8259888,
+      8936928,   9657648,  10424128,   11238513,   12103014,   13019909 },
+    {       0,         0,         0,          0,          0,          0,
+            1,         7,        28,         84,        210,        462,
+          924,      1716,      3003,       5005,       8008,      12376,
+        18564,     27132,     38760,      54264,      74613,     100947,
+       134596,    177100,    230230,     296010,     376740,     475020,
+       593775,    736281,    906192,    1107568,    1344904,    1623160,
+      1947792,   2324784,   2760681,    3262623,    3838380,    4496388,
+      5245786,   6096454,   7059052,    8145060,    9366819,   10737573,
+     12271512,  13983816,  15890700,   18009460,   20358520,   22957480,
+     25827165,  28989675,  32468436,   36288252,   40475358,   45057474,
+     50063860,  55525372,  61474519,   67945521,   74974368,   82598880,
+     90858768,  99795696, 109453344,  119877472,  131115985,  143218999 },
+    {       0,         0,         0,          0,          0,          0,
+            0,         1,         8,         36,        120,        330,
+          792,      1716,      3432,       6435,      11440,      19448,
+        31824,     50388,     77520,     116280,     170544,     245157,
+       346104,    480700,    657800,     888030,    1184040,    1560780,
+      2035800,   2629575,   3365856,    4272048,    5379616,    6724520,
+      8347680,  10295472,  12620256,   15380937,   18643560,   22481940,
+     26978328,  32224114,  38320568,   45379620,   53524680,   62891499,
+     73629072,  85900584,  99884400,  115775100,  133784560,  154143080,
+    177100560, 202927725, 231917400,  264385836,  300674088,  341149446,
+    386206920, 436270780, 491796152,  553270671,  621216192,  696190560,
+    778789440, 869648208, 969443904, 1078897248, 1198774720, 1329890705 },
+};
+
+static const int16_t dss_sp_filter_cb[14][32] = {
+    { -32653, -32587, -32515, -32438, -32341, -32216, -32062, -31881,
+      -31665, -31398, -31080, -30724, -30299, -29813, -29248, -28572,
+      -27674, -26439, -24666, -22466, -19433, -16133, -12218,  -7783,
+       -2834,   1819,   6544,  11260,  16050,  20220,  24774,  28120 },
+
+    { -27503, -24509, -20644, -17496, -14187, -11277,  -8420,  -5595,
+       -3013,   -624,   1711,   3880,   5844,   7774,   9739,  11592,
+       13364,  14903,  16426,  17900,  19250,  20586,  21803,  23006,
+       24142,  25249,  26275,  27300,  28359,  29249,  30118,  31183 },
+
+    { -27827, -24208, -20943, -17781, -14843, -11848,  -9066,  -6297,
+       -3660,   -910,   1918,   5025,   8223,  11649,  15086,  18423,
+           0,      0,      0,      0,      0,      0,      0,      0,
+           0,      0,      0,      0,      0,      0,      0,      0 },
+
+    { -17128, -11975,  -8270,  -5123,  -2296,    183,   2503,   4707,
+        6798,   8945,  11045,  13239,  15528,  18248,  21115,  24785,
+           0,      0,      0,      0,      0,      0,      0,      0,
+           0,      0,      0,      0,      0,      0,      0,      0 },
+
+    { -21557, -17280, -14286, -11644,  -9268,  -7087,  -4939,  -2831,
+        -691,   1407,   3536,   5721,   8125,  10677,  13721,  17731,
+           0,      0,      0,      0,      0,      0,      0,      0,
+           0,      0,      0,      0,      0,      0,      0,      0 },
+
+    { -15030, -10377,  -7034,  -4327,  -1900,    364,   2458,   4450,
+        6422,   8374,  10374,  12486,  14714,  16997,  19626,  22954,
+           0,      0,      0,      0,      0,      0,      0,      0,
+           0,      0,      0,      0,      0,      0,      0,      0 },
+
+    { -16155, -12362,  -9698,  -7460,  -5258,  -3359,  -1547,    219,
+        1916,   3599,   5299,   6994,   8963,  11226,  13716,  16982,
+           0,      0,      0,      0,      0,      0,      0,      0,
+           0,      0,      0,      0,      0,      0,      0,      0 },
+
+    { -14742,  -9848,  -6921,  -4648,  -2769,  -1065,    499,   2083,
+        3633,   5219,   6857,   8580,  10410,  12672,  15561,  20101,
+           0,      0,      0,      0,      0,      0,      0,      0,
+           0,      0,      0,      0,      0,      0,      0,      0 },
+
+    { -11099,  -7014,  -3855,  -1025,   1680,   4544,   7807,  11932,
+           0,      0,      0,      0,      0,      0,      0,      0,
+           0,      0,      0,      0,      0,      0,      0,      0,
+           0,      0,      0,      0,      0,      0,      0,      0 },
+
+    {  -9060,  -4570,  -1381,   1419,   4034,   6728,   9865,  14149,
+           0,      0,      0,      0,      0,      0,      0,      0,
+           0,      0,      0,      0,      0,      0,      0,      0,
+           0,      0,      0,      0,      0,      0,      0,      0 },
+
+    { -12450,  -7985,  -4596,  -1734,    961,   3629,   6865,  11142,
+           0,      0,      0,      0,      0,      0,      0,      0,
+           0,      0,      0,      0,      0,      0,      0,      0,
+           0,      0,      0,      0,      0,      0,      0,      0 },
+
+    { -11831,  -7404,  -4010,  -1096,   1606,   4291,   7386,  11482,
+           0,      0,      0,      0,      0,      0,      0,      0,
+           0,      0,      0,      0,      0,      0,      0,      0,
+           0,      0,      0,      0,      0,      0,      0,      0 },
+
+    { -13404,  -9250,  -5995,  -3312,   -890,   1594,   4464,   8198,
+           0,      0,      0,      0,      0,      0,      0,      0,
+           0,      0,      0,      0,      0,      0,      0,      0,
+           0,      0,      0,      0,      0,      0,      0,      0 },
+
+    { -11239,  -7220,  -4040,  -1406,    971,   3321,   6006,   9697,
+           0,      0,      0,      0,      0,      0,      0,      0,
+           0,      0,      0,      0,      0,      0,      0,      0,
+           0,      0,      0,      0,      0,      0,      0,      0 },
+};
+
+static const uint16_t  dss_sp_fixed_cb_gain[64] = {
+       0,    4,    8,   13,   17,   22,   26,   31,
+      35,   40,   44,   48,   53,   58,   63,   69,
+      76,   83,   91,   99,  109,  119,  130,  142,
+     155,  170,  185,  203,  222,  242,  265,  290,
+     317,  346,  378,  414,  452,  494,  540,  591,
+     646,  706,  771,  843,  922, 1007, 1101, 1204,
+    1316, 1438, 1572, 1719, 1879, 2053, 2244, 2453,
+    2682, 2931, 3204, 3502, 3828, 4184, 4574, 5000,
+};
+
+static const int16_t  dss_sp_pulse_val[8] = {
+    -31182, -22273, -13364, -4455, 4455, 13364, 22273, 31182
+};
+
+static const uint16_t binary_decreasing_array[] = {
+    32767, 16384, 8192, 4096, 2048, 1024, 512, 256,
+    128, 64, 32, 16, 8, 4, 2,
+};
+
+static const uint16_t dss_sp_unc_decreasing_array[] = {
+    32767, 26214, 20972, 16777, 13422, 10737, 8590, 6872,
+    5498, 4398, 3518, 2815, 2252, 1801, 1441,
+};
+
+static const uint16_t dss_sp_adaptive_gain[] = {
+     102,  231,  360,  488,  617,  746,  875, 1004,
+    1133, 1261, 1390, 1519, 1648, 1777, 1905, 2034,
+    2163, 2292, 2421, 2550, 2678, 2807, 2936, 3065,
+    3194, 3323, 3451, 3580, 3709, 3838, 3967, 4096,
+};
+
+static const int32_t dss_sp_sinc[67] = {
+      262,   293,   323,   348,   356,   336,   269,   139,
+      -67,  -358,  -733, -1178, -1668, -2162, -2607, -2940,
+    -3090, -2986, -2562, -1760,  -541,  1110,  3187,  5651,
+     8435, 11446, 14568, 17670, 20611, 23251, 25460, 27125,
+    28160, 28512, 28160,
+    27125, 25460, 23251, 20611, 17670, 14568, 11446,  8435,
+     5651,  3187,  1110,  -541, -1760, -2562, -2986, -3090,
+    -2940, -2607, -2162, -1668, -1178,  -733,  -358,   -67,
+      139,   269,   336,   356,   348,   323,   293,   262,
+};
+
+static av_cold int dss_sp_decode_init(AVCodecContext *avctx)
+{
+    DssSpContext *p = avctx->priv_data;
+    avctx->channel_layout = AV_CH_LAYOUT_MONO;
+    avctx->sample_fmt     = AV_SAMPLE_FMT_S16;
+    avctx->channels       = 1;
+    avctx->sample_rate    = 11025;
+
+    memset(p->history, 0, sizeof(p->history));
+    p->pulse_dec_mode = 1;
+    p->avctx          = avctx;
+
+    return 0;
+}
+
+static void dss_sp_unpack_coeffs(DssSpContext *p, const uint8_t *src)
+{
+    GetBitContext gb;
+    DssSpFrame *fparam = &p->fparam;
+    int i;
+    int subframe_idx;
+    uint32_t combined_pitch;
+    uint32_t tmp;
+    uint32_t pitch_lag;
+
+    for (i = 0; i < DSS_SP_FRAME_SIZE; i += 2) {
+        p->bits[i]     = src[i + 1];
+        p->bits[i + 1] = src[i];
+    }
+
+    init_get_bits(&gb, p->bits, DSS_SP_FRAME_SIZE * 8);
+
+    for (i = 0; i < 2; i++)
+        fparam->filter_idx[i] = get_bits(&gb, 5);
+    for (; i < 8; i++)
+        fparam->filter_idx[i] = get_bits(&gb, 4);
+    for (; i < 14; i++)
+        fparam->filter_idx[i] = get_bits(&gb, 3);
+
+    for (subframe_idx = 0; subframe_idx < 4; subframe_idx++) {
+        fparam->sf_adaptive_gain[subframe_idx] = get_bits(&gb, 5);
+
+        fparam->sf[subframe_idx].combined_pulse_pos = get_bits_long(&gb, 31);
+
+        fparam->sf[subframe_idx].gain = get_bits(&gb, 6);
+
+        for (i = 0; i < 7; i++)
+            fparam->sf[subframe_idx].pulse_val[i] = get_bits(&gb, 3);
+    }
+
+    for (subframe_idx = 0; subframe_idx < 4; subframe_idx++) {
+        unsigned int C72_binomials[PULSE_MAX] = {
+            72, 2556, 59640, 1028790, 13991544, 156238908, 1473109704,
+            3379081753
+        };
+        unsigned int combined_pulse_pos =
+            fparam->sf[subframe_idx].combined_pulse_pos;
+        int index = 6;
+
+        if (combined_pulse_pos < C72_binomials[PULSE_MAX - 1]) {
+            if (p->pulse_dec_mode) {
+                int pulse, pulse_idx;
+                pulse              = PULSE_MAX - 1;
+                pulse_idx          = 71;
+                combined_pulse_pos =
+                    fparam->sf[subframe_idx].combined_pulse_pos;
+
+                /* this part seems to be close to g723.1 gen_fcb_excitation()
+                 * RATE_6300 */
+
+                /* TODO: what is 7? size of subframe? */
+                for (i = 0; i < 7; i++) {
+                    for (;
+                         combined_pulse_pos <
+                         dss_sp_combinatorial_table[pulse][pulse_idx];
+                         --pulse_idx)
+                        ;
+                    combined_pulse_pos -=
+                        dss_sp_combinatorial_table[pulse][pulse_idx];
+                    pulse--;
+                    fparam->sf[subframe_idx].pulse_pos[i] = pulse_idx;
+                }
+            }
+        } else {
+            p->pulse_dec_mode = 0;
+
+            /* why do we need this? */
+            fparam->sf[subframe_idx].pulse_pos[6] = 0;
+
+            for (i = 71; i >= 0; i--) {
+                if (C72_binomials[index] <= combined_pulse_pos) {
+                    combined_pulse_pos -= C72_binomials[index];
+
+                    fparam->sf[subframe_idx].pulse_pos[6 - index] = i;
+
+                    if (!index)
+                        break;
+                    --index;
+                }
+                --C72_binomials[0];
+                if (index) {
+                    int a;
+                    for (a = 0; a < index; a++)
+                        C72_binomials[a + 1] -= C72_binomials[a];
+                }
+            }
+        }
+    }
+
+    combined_pitch = get_bits(&gb, 24);
+
+    fparam->pitch_lag[0] = (combined_pitch % 151) + 36;
+
+    combined_pitch /= 151;
+
+    for (i = 1; i < SUBFRAMES - 1; i++) {
+        fparam->pitch_lag[i] = combined_pitch % 48;
+        combined_pitch      /= 48;
+    }
+    if (combined_pitch > 47) {
+        av_log (p->avctx, AV_LOG_WARNING, "combined_pitch was too large\n");
+        combined_pitch = 0;
+    }
+    fparam->pitch_lag[i] = combined_pitch;
+
+    pitch_lag = fparam->pitch_lag[0];
+    for (i = 1; i < SUBFRAMES; i++) {
+        if (pitch_lag > 162) {
+            fparam->pitch_lag[i] += 162 - 23;
+        } else {
+            tmp = pitch_lag - 23;
+            if (tmp < 36)
+                tmp = 36;
+            fparam->pitch_lag[i] += tmp;
+        }
+        pitch_lag = fparam->pitch_lag[i];
+    }
+}
+
+static void dss_sp_unpack_filter(DssSpContext *p)
+{
+    int i;
+
+    for (i = 0; i < 14; i++)
+        p->lpc_filter[i] = dss_sp_filter_cb[i][p->fparam.filter_idx[i]];
+}
+
+static void dss_sp_convert_coeffs(int32_t *lpc_filter, int32_t *coeffs)
+{
+    int a, a_plus, i;
+
+    coeffs[0] = 0x2000;
+    for (a = 0; a < 14; a++) {
+        a_plus         = a + 1;
+        coeffs[a_plus] = lpc_filter[a] >> 2;
+        if (a_plus / 2 >= 1) {
+            for (i = 1; i <= a_plus / 2; i++) {
+                int coeff_1, coeff_2, tmp;
+
+                coeff_1 = coeffs[i];
+                coeff_2 = coeffs[a_plus - i];
+
+                tmp = DSS_SP_FORMULA(coeff_1, lpc_filter[a], coeff_2);
+                coeffs[i] = av_clip_int16(tmp);
+
+                tmp = DSS_SP_FORMULA(coeff_2, lpc_filter[a], coeff_1);
+                coeffs[a_plus - i] = av_clip_int16(tmp);
+            }
+        }
+    }
+}
+
+static void dss_sp_add_pulses(int32_t *vector_buf,
+                              const struct DssSpSubframe *sf)
+{
+    int i;
+
+    for (i = 0; i < 7; i++)
+        vector_buf[sf->pulse_pos[i]] += (dss_sp_fixed_cb_gain[sf->gain] *
+                                         dss_sp_pulse_val[sf->pulse_val[i]] +
+                                         0x4000) >> 15;
+}
+
+static void dss_sp_gen_exc(int32_t *vector, int32_t *prev_exc,
+                           int pitch_lag, int gain)
+{
+    int i;
+
+    /* do we actually need this check? we can use just [a3 - i % a3]
+     * for both cases */
+    if (pitch_lag < 72)
+        for (i = 0; i < 72; i++)
+            vector[i] = prev_exc[pitch_lag - i % pitch_lag];
+    else
+        for (i = 0; i < 72; i++)
+            vector[i] = prev_exc[pitch_lag - i];
+
+    for (i = 0; i < 72; i++) {
+        int tmp = gain * vector[i] >> 11;
+        vector[i] = av_clip_int16(tmp);
+    }
+}
+
+static void dss_sp_scale_vector(int32_t *vec, int bits, int size)
+{
+    int i;
+
+    if (bits < 0)
+        for (i = 0; i < size; i++)
+            vec[i] = vec[i] >> -bits;
+    else
+        for (i = 0; i < size; i++)
+            vec[i] = vec[i] << bits;
+}
+
+static void dss_sp_update_buf(int32_t *hist, int32_t *vector)
+{
+    int i;
+
+    for (i = 114; i > 0; i--)
+        vector[i + 72] = vector[i];
+
+    for (i = 0; i < 72; i++)
+        vector[72 - i] = hist[i];
+}
+
+static void dss_sp_shift_sq_sub(const int32_t *filter_buf,
+                                int32_t *error_buf, int32_t *dst)
+{
+    int a;
+
+    for (a = 0; a < 72; a++) {
+        int i, tmp;
+
+        tmp = dst[a] * filter_buf[0];
+
+        for (i = 14; i > 0; i--)
+            tmp -= error_buf[i] * filter_buf[i];
+
+        for (i = 14; i > 0; i--)
+            error_buf[i] = error_buf[i - 1];
+
+        tmp = (tmp + 4096) >> 13;
+
+        error_buf[1] = tmp;
+
+        dst[a] = av_clip_int16(tmp);
+    }
+}
+
+static void dss_sp_shift_sq_add(const int32_t *filter_buf, int32_t *audio_buf,
+                                int32_t *dst)
+{
+    int a;
+
+    for (a = 0; a < 72; a++) {
+        int i, tmp = 0;
+
+        audio_buf[0] = dst[a];
+
+        for (i = 14; i >= 0; i--)
+            tmp += audio_buf[i] * filter_buf[i];
+
+        for (i = 14; i > 0; i--)
+            audio_buf[i] = audio_buf[i - 1];
+
+        tmp = (tmp + 4096) >> 13;
+
+        dst[a] = av_clip_int16(tmp);
+    }
+}
+
+static void dss_sp_vec_mult(const int32_t *src, int32_t *dst,
+                            const int16_t *mult)
+{
+    int i;
+
+    dst[0] = src[0];
+
+    for (i = 1; i < 15; i++)
+        dst[i] = (src[i] * mult[i] + 0x4000) >> 15;
+}
+
+static int dss_sp_get_normalize_bits(int32_t *vector_buf, int16_t size)
+{
+    unsigned int val;
+    int max_val;
+    int i;
+
+    val = 1;
+    for (i = 0; i < size; i++)
+        val |= FFABS(vector_buf[i]);
+
+    for (max_val = 0; val <= 0x4000; ++max_val)
+        val *= 2;
+    return max_val;
+}
+
+static int dss_sp_vector_sum(DssSpContext *p, int size)
+{
+    int i, sum = 0;
+    for (i = 0; i < size; i++)
+        sum += FFABS(p->vector_buf[i]);
+    return sum;
+}
+
+static void dss_sp_sf_synthesis(DssSpContext *p, int32_t lpc_filter,
+                                int32_t *dst, int size)
+{
+    int32_t tmp_buf[15];
+    int32_t noise[72];
+    int bias, vsum_2 = 0, vsum_1 = 0, v36, normalize_bits;
+    int i, tmp;
+
+    if (size > 0) {
+        vsum_1 = dss_sp_vector_sum(p, size);
+
+        if (vsum_1 > 0xFFFFF)
+            vsum_1 = 0xFFFFF;
+    }
+
+    normalize_bits = dss_sp_get_normalize_bits(p->vector_buf, size);
+
+    dss_sp_scale_vector(p->vector_buf, normalize_bits - 3, size);
+    dss_sp_scale_vector(p->audio_buf, normalize_bits, 15);
+    dss_sp_scale_vector(p->err_buf1, normalize_bits, 15);
+
+    v36 = p->err_buf1[1];
+
+    dss_sp_vec_mult(p->filter, tmp_buf, binary_decreasing_array);
+    dss_sp_shift_sq_add(tmp_buf, p->audio_buf, p->vector_buf);
+
+    dss_sp_vec_mult(p->filter, tmp_buf, dss_sp_unc_decreasing_array);
+    dss_sp_shift_sq_sub(tmp_buf, p->err_buf1, p->vector_buf);
+
+    /* lpc_filter can be negative */
+    lpc_filter = lpc_filter >> 1;
+    if (lpc_filter >= 0)
+        lpc_filter = 0;
+
+    if (size > 1) {
+        for (i = size - 1; i > 0; i--) {
+            tmp = DSS_SP_FORMULA(p->vector_buf[i], lpc_filter,
+                                 p->vector_buf[i - 1]);
+            p->vector_buf[i] = av_clip_int16(tmp);
+        }
+    }
+
+    tmp              = DSS_SP_FORMULA(p->vector_buf[0], lpc_filter, v36);
+    p->vector_buf[0] = av_clip_int16(tmp);
+
+    dss_sp_scale_vector(p->vector_buf, -normalize_bits, size);
+    dss_sp_scale_vector(p->audio_buf, -normalize_bits, 15);
+    dss_sp_scale_vector(p->err_buf1, -normalize_bits, 15);
+
+    if (size > 0)
+        vsum_2 = dss_sp_vector_sum(p, size);
+
+    if (vsum_2 >= 0x40)
+        tmp = (vsum_1 << 11) / vsum_2;
+    else
+        tmp = 1;
+
+    bias     = 409 * tmp >> 15 << 15;
+    tmp      = (bias + 32358 * p->noise_state) >> 15;
+    noise[0] = av_clip_int16(tmp);
+
+    for (i = 1; i < size; i++) {
+        tmp      = (bias + 32358 * noise[i - 1]) >> 15;
+        noise[i] = av_clip_int16(tmp);
+    }
+
+    p->noise_state = noise[size - 1];
+    for (i = 0; i < size; i++) {
+        tmp    = (p->vector_buf[i] * noise[i]) >> 11;
+        dst[i] = av_clip_int16(tmp);
+    }
+}
+
+static void dss_sp_update_state(DssSpContext *p, int32_t *dst)
+{
+    int i, offset = 6, counter = 0, a = 0;
+
+    for (i = 0; i < 6; i++)
+        p->excitation[i] = p->excitation[288 + i];
+
+    for (i = 0; i < 72 * SUBFRAMES; i++)
+        p->excitation[6 + i] = dst[i];
+
+    do {
+        int tmp = 0;
+
+        for (i = 0; i < 6; i++)
+            tmp += p->excitation[offset--] * dss_sp_sinc[a + i * 11];
+
+        offset += 7;
+
+        tmp >>= 15;
+        dst[counter] = av_clip_int16(tmp);
+
+        counter++;
+
+        a = (a + 1) % 11;
+        if (!a)
+            offset++;
+    } while (offset < FF_ARRAY_ELEMS(p->excitation));
+}
+
+static void dss_sp_32to16bit(int16_t *dst, int32_t *src, int size)
+{
+    int i;
+
+    for (i = 0; i < size; i++)
+        dst[i] = av_clip_int16(src[i]);
+}
+
+static int dss_sp_decode_one_frame(DssSpContext *p,
+                                   int16_t *abuf_dst, const uint8_t *abuf_src)
+{
+    int i, j;
+
+    dss_sp_unpack_coeffs(p, abuf_src);
+
+    dss_sp_unpack_filter(p);
+
+    dss_sp_convert_coeffs(p->lpc_filter, p->filter);
+
+    for (j = 0; j < SUBFRAMES; j++) {
+        dss_sp_gen_exc(p->vector_buf, p->history,
+                       p->fparam.pitch_lag[j],
+                       dss_sp_adaptive_gain[p->fparam.sf_adaptive_gain[j]]);
+
+        dss_sp_add_pulses(p->vector_buf, &p->fparam.sf[j]);
+
+        dss_sp_update_buf(p->vector_buf, p->history);
+
+        for (i = 0; i < 72; i++)
+            p->vector_buf[i] = p->history[72 - i];
+
+        dss_sp_shift_sq_sub(p->filter,
+                            p->err_buf2, p->vector_buf);
+
+        dss_sp_sf_synthesis(p, p->lpc_filter[0],
+                            &p->working_buffer[j][0], 72);
+    }
+
+    dss_sp_update_state(p, &p->working_buffer[0][0]);
+
+    dss_sp_32to16bit(abuf_dst,
+                     &p->working_buffer[0][0], 264);
+    return 0;
+}
+
+static int dss_sp_decode_frame(AVCodecContext *avctx, void *data,
+                               int *got_frame_ptr, AVPacket *avpkt)
+{
+    DssSpContext *p    = avctx->priv_data;
+    AVFrame *frame     = data;
+    const uint8_t *buf = avpkt->data;
+    int buf_size       = avpkt->size;
+
+    int16_t *out;
+    int ret;
+
+    if (buf_size < DSS_SP_FRAME_SIZE) {
+        if (buf_size)
+            av_log(avctx, AV_LOG_WARNING,
+                   "Expected %d bytes, got %d - skipping packet.\n",
+                   DSS_SP_FRAME_SIZE, buf_size);
+        *got_frame_ptr = 0;
+        return AVERROR_INVALIDDATA;
+    }
+
+    frame->nb_samples = DSS_SP_SAMPLE_COUNT;
+    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
+        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed.\n");
+        return ret;
+    }
+
+    out = (int16_t *)frame->data[0];
+
+    dss_sp_decode_one_frame(p, out, buf);
+
+    *got_frame_ptr = 1;
+
+    return DSS_SP_FRAME_SIZE;
+}
+
+AVCodec ff_dss_sp_decoder = {
+    .name           = "DSS SP",
+    .long_name      = NULL_IF_CONFIG_SMALL("Digital Speech Standard - Standard Play mode (DSS SP)"),
+    .type           = AVMEDIA_TYPE_AUDIO,
+    .id             = AV_CODEC_ID_DSS_SP,
+    .priv_data_size = sizeof(DssSpContext),
+    .init           = dss_sp_decode_init,
+    .decode         = dss_sp_decode_frame,
+    .capabilities   = CODEC_CAP_DR1,
+};
diff --git a/libavcodec/dv.c b/libavcodec/dv.c
index 2bc7fc5..31d1315 100644
--- a/libavcodec/dv.c
+++ b/libavcodec/dv.c
@@ -173,15 +173,6 @@
     }
 }
 
-/* quantization quanta by QNO for DV100 */
-static const uint8_t dv100_qstep[16] = {
-    1, /* QNO = 0 and 1 both have no quantization */
-    1,
-    2, 3, 4, 5, 6, 7, 8, 16, 18, 20, 22, 24, 28, 52
-};
-
-static const uint8_t dv_quant_areas[4] = { 6, 21, 43, 64 };
-
 int ff_dv_init_dynamic_tables(DVVideoContext *ctx, const AVDVProfile *d)
 {
     int j, i, c, s, p;
diff --git a/libavcodec/dvbsub_parser.c b/libavcodec/dvbsub_parser.c
index d15c891..f9fdb6a 100644
--- a/libavcodec/dvbsub_parser.c
+++ b/libavcodec/dvbsub_parser.c
@@ -122,11 +122,11 @@
     {
         if (*p == 0x0f)
         {
-            if (p + 6 <= p_end)
+            if (6 <= p_end - p)
             {
                 len = AV_RB16(p + 4);
 
-                if (p + len + 6 <= p_end)
+                if (len + 6 <= p_end - p)
                 {
                     *poutbuf_size += len + 6;
 
@@ -136,7 +136,7 @@
             } else
                 break;
         } else if (*p == 0xff) {
-            if (p + 1 < p_end)
+            if (1 < p_end - p)
             {
                 av_dlog(avctx, "Junk at end of packet\n");
             }
diff --git a/libavcodec/dvdec.c b/libavcodec/dvdec.c
index 99fe1f4..388bbf2 100644
--- a/libavcodec/dvdec.c
+++ b/libavcodec/dvdec.c
@@ -116,7 +116,7 @@
      96,  98,  96,  88,  96,  98, 202, 196,
     196, 202, 208, 218, 208, 232, 232, 246,
 };
-const uint16_t dv_iweight_720_c[64] = {
+static const uint16_t dv_iweight_720_c[64] = {
     128,  24,  24,  26,  26,  26,  36,  36,
      36,  36,  36,  36,  38,  36,  36,  38,
      38,  38,  38,  38,  38,  84,  76,  80,
diff --git a/libavcodec/dvdsubdec.c b/libavcodec/dvdsubdec.c
index 9a49d8f..ffb2bcc 100644
--- a/libavcodec/dvdsubdec.c
+++ b/libavcodec/dvdsubdec.c
@@ -360,11 +360,16 @@
             if (w > 0 && h > 0) {
                 reset_rects(sub_header);
 
-                bitmap = av_malloc(w * h);
                 sub_header->rects = av_mallocz(sizeof(*sub_header->rects));
+                if (!sub_header->rects)
+                    goto fail;
                 sub_header->rects[0] = av_mallocz(sizeof(AVSubtitleRect));
+                if (!sub_header->rects[0])
+                    goto fail;
                 sub_header->num_rects = 1;
-                sub_header->rects[0]->pict.data[0] = bitmap;
+                bitmap = sub_header->rects[0]->pict.data[0] = av_malloc(w * h);
+                if (!bitmap)
+                    goto fail;
                 if (decode_rle(bitmap, w * 2, w, (h + 1) / 2,
                                buf, offset1, buf_size, is_8bit) < 0)
                     goto fail;
@@ -372,6 +377,8 @@
                                buf, offset2, buf_size, is_8bit) < 0)
                     goto fail;
                 sub_header->rects[0]->pict.data[1] = av_mallocz(AVPALETTE_SIZE);
+                if (!sub_header->rects[0]->pict.data[1])
+                    goto fail;
                 if (is_8bit) {
                     if (!yuv_palette)
                         goto fail;
diff --git a/libavcodec/dvenc.c b/libavcodec/dvenc.c
index 7061508..2442f2b 100644
--- a/libavcodec/dvenc.c
+++ b/libavcodec/dvenc.c
@@ -232,14 +232,14 @@
     170627, 165371, 160727, 153560, 160727, 144651, 144651, 136258,
 };
 static const int dv_weight_248[64] = {
-    131072, 242189, 257107, 237536, 229376, 200636, 242189, 223754,
-    224969, 196781, 262144, 242189, 229376, 200636, 257107, 237536,
-    211916, 185364, 235923, 217965, 229376, 211916, 206433, 180568,
-    242189, 223754, 224969, 196781, 211916, 185364, 235923, 217965,
-    200704, 175557, 222935, 205965, 200636, 185364, 195068, 170627,
-    229376, 211916, 206433, 180568, 200704, 175557, 222935, 205965,
-    175557, 153560, 188995, 174609, 165371, 144651, 200636, 185364,
-    195068, 170627, 175557, 153560, 188995, 174609, 165371, 144651,
+    131072, 262144, 257107, 257107, 242189, 242189, 242189, 242189,
+    237536, 237536, 229376, 229376, 200636, 200636, 224973, 224973,
+    223754, 223754, 235923, 235923, 229376, 229376, 217965, 217965,
+    211916, 211916, 196781, 196781, 185364, 185364, 206433, 206433,
+    211916, 211916, 222935, 222935, 200636, 200636, 205964, 205964,
+    200704, 200704, 180568, 180568, 175557, 175557, 195068, 195068,
+    185364, 185364, 188995, 188995, 174606, 174606, 175557, 175557,
+    170627, 170627, 153560, 153560, 165371, 165371, 144651, 144651,
 };
 
 static av_always_inline int dv_init_enc_block(EncBlockInfo *bi, uint8_t *data,
diff --git a/libavcodec/dxtory.c b/libavcodec/dxtory.c
index 4d8b7b2..22e7b2f 100644
--- a/libavcodec/dxtory.c
+++ b/libavcodec/dxtory.c
@@ -65,7 +65,7 @@
     uint8_t *Y1, *Y2, *Y3, *Y4, *U, *V;
     int ret;
 
-    if (src_size < avctx->width * avctx->height * 9L / 8) {
+    if (src_size < avctx->width * avctx->height * 9LL / 8) {
         av_log(avctx, AV_LOG_ERROR, "packet too small\n");
         return AVERROR_INVALIDDATA;
     }
@@ -108,7 +108,7 @@
     uint8_t *Y1, *Y2, *U, *V;
     int ret;
 
-    if (src_size < avctx->width * avctx->height * 3L / 2) {
+    if (src_size < avctx->width * avctx->height * 3LL / 2) {
         av_log(avctx, AV_LOG_ERROR, "packet too small\n");
         return AVERROR_INVALIDDATA;
     }
@@ -145,7 +145,7 @@
     uint8_t *Y, *U, *V;
     int ret;
 
-    if (src_size < avctx->width * avctx->height * 3L) {
+    if (src_size < avctx->width * avctx->height * 3LL) {
         av_log(avctx, AV_LOG_ERROR, "packet too small\n");
         return AVERROR_INVALIDDATA;
     }
@@ -285,7 +285,8 @@
                    "Slice sizes mismatch: got %"PRIu32" instead of %"PRIu32"\n",
                    AV_RL32(src + off), slice_size - 16);
         }
-        init_get_bits(&gb2, src + off + 16, (slice_size - 16) * 8);
+        if ((ret = init_get_bits8(&gb2, src + off + 16, slice_size - 16)) < 0)
+            return ret;
         dx2_decode_slice_565(&gb2, avctx->width, slice_height, dst,
                              pic->linesize[0], is_565);
 
@@ -367,7 +368,8 @@
                    "Slice sizes mismatch: got %"PRIu32" instead of %"PRIu32"\n",
                    AV_RL32(src + off), slice_size - 16);
         }
-        init_get_bits(&gb2, src + off + 16, (slice_size - 16) * 8);
+        if ((ret = init_get_bits8(&gb2, src + off + 16, slice_size - 16)) < 0)
+            return ret;
         dx2_decode_slice_rgb(&gb2, avctx->width, slice_height, dst,
                              pic->linesize[0]);
 
@@ -464,7 +466,8 @@
                    "Slice sizes mismatch: got %"PRIu32" instead of %"PRIu32"\n",
                    AV_RL32(src + off), slice_size - 16);
         }
-        init_get_bits(&gb2, src + off + 16, (slice_size - 16) * 8);
+        if ((ret = init_get_bits8(&gb2, src + off + 16, slice_size - 16)) < 0)
+            return ret;
         dx2_decode_slice_410(&gb2, avctx->width, slice_height, Y, U, V,
                              pic->linesize[0], pic->linesize[1],
                              pic->linesize[2]);
@@ -566,7 +569,8 @@
                    "Slice sizes mismatch: got %"PRIu32" instead of %"PRIu32"\n",
                    AV_RL32(src + off), slice_size - 16);
         }
-        init_get_bits(&gb2, src + off + 16, (slice_size - 16) * 8);
+        if ((ret = init_get_bits8(&gb2, src + off + 16, slice_size - 16)) < 0)
+            return ret;
         dx2_decode_slice_420(&gb2, avctx->width, slice_height, Y, U, V,
                              pic->linesize[0], pic->linesize[1],
                              pic->linesize[2]);
@@ -658,7 +662,8 @@
                    "Slice sizes mismatch: got %"PRIu32" instead of %"PRIu32"\n",
                    AV_RL32(src + off), slice_size - 16);
         }
-        init_get_bits(&gb2, src + off + 16, (slice_size - 16) * 8);
+        if ((ret = init_get_bits8(&gb2, src + off + 16, slice_size - 16)) < 0)
+            return ret;
         dx2_decode_slice_444(&gb2, avctx->width, slice_height, Y, U, V,
                              pic->linesize[0], pic->linesize[1],
                              pic->linesize[2]);
diff --git a/libavcodec/dxva2_h264.c b/libavcodec/dxva2_h264.c
index 6deccc3..62a868b 100644
--- a/libavcodec/dxva2_h264.c
+++ b/libavcodec/dxva2_h264.c
@@ -211,6 +211,7 @@
                             const DXVA_PicParams_H264 *pp, unsigned position, unsigned size)
 {
     const H264Context *h = avctx->priv_data;
+    H264SliceContext *sl = &h->slice_ctx[0];
     struct dxva_context *ctx = avctx->hwaccel_context;
     unsigned list;
 
@@ -219,27 +220,27 @@
     slice->SliceBytesInBuffer    = size;
     slice->wBadSliceChopping     = 0;
 
-    slice->first_mb_in_slice     = (h->mb_y >> FIELD_OR_MBAFF_PICTURE(h)) * h->mb_width + h->mb_x;
+    slice->first_mb_in_slice     = (sl->mb_y >> FIELD_OR_MBAFF_PICTURE(h)) * h->mb_width + sl->mb_x;
     slice->NumMbsForSlice        = 0; /* XXX it is set once we have all slices */
-    slice->BitOffsetToSliceData  = get_bits_count(&h->gb);
-    slice->slice_type            = ff_h264_get_slice_type(h);
-    if (h->slice_type_fixed)
+    slice->BitOffsetToSliceData  = get_bits_count(&sl->gb);
+    slice->slice_type            = ff_h264_get_slice_type(sl);
+    if (sl->slice_type_fixed)
         slice->slice_type += 5;
-    slice->luma_log2_weight_denom       = h->luma_log2_weight_denom;
-    slice->chroma_log2_weight_denom     = h->chroma_log2_weight_denom;
-    if (h->list_count > 0)
-        slice->num_ref_idx_l0_active_minus1 = h->ref_count[0] - 1;
-    if (h->list_count > 1)
-        slice->num_ref_idx_l1_active_minus1 = h->ref_count[1] - 1;
-    slice->slice_alpha_c0_offset_div2   = h->slice_alpha_c0_offset / 2;
-    slice->slice_beta_offset_div2       = h->slice_beta_offset     / 2;
+    slice->luma_log2_weight_denom       = sl->luma_log2_weight_denom;
+    slice->chroma_log2_weight_denom     = sl->chroma_log2_weight_denom;
+    if (sl->list_count > 0)
+        slice->num_ref_idx_l0_active_minus1 = sl->ref_count[0] - 1;
+    if (sl->list_count > 1)
+        slice->num_ref_idx_l1_active_minus1 = sl->ref_count[1] - 1;
+    slice->slice_alpha_c0_offset_div2   = sl->slice_alpha_c0_offset / 2;
+    slice->slice_beta_offset_div2       = sl->slice_beta_offset     / 2;
     slice->Reserved8Bits                = 0;
 
     for (list = 0; list < 2; list++) {
         unsigned i;
         for (i = 0; i < FF_ARRAY_ELEMS(slice->RefPicList[list]); i++) {
-            if (list < h->list_count && i < h->ref_count[list]) {
-                const H264Picture *r = &h->ref_list[list][i];
+            if (list < sl->list_count && i < sl->ref_count[list]) {
+                const H264Picture *r = sl->ref_list[list][i].parent;
                 unsigned plane;
                 unsigned index;
                 if (ctx->workaround & FF_DXVA2_WORKAROUND_INTEL_CLEARVIDEO)
@@ -250,15 +251,15 @@
                                    r->reference == PICT_BOTTOM_FIELD);
                 for (plane = 0; plane < 3; plane++) {
                     int w, o;
-                    if (plane == 0 && h->luma_weight_flag[list]) {
-                        w = h->luma_weight[i][list][0];
-                        o = h->luma_weight[i][list][1];
-                    } else if (plane >= 1 && h->chroma_weight_flag[list]) {
-                        w = h->chroma_weight[i][list][plane-1][0];
-                        o = h->chroma_weight[i][list][plane-1][1];
+                    if (plane == 0 && sl->luma_weight_flag[list]) {
+                        w = sl->luma_weight[i][list][0];
+                        o = sl->luma_weight[i][list][1];
+                    } else if (plane >= 1 && sl->chroma_weight_flag[list]) {
+                        w = sl->chroma_weight[i][list][plane-1][0];
+                        o = sl->chroma_weight[i][list][plane-1][1];
                     } else {
-                        w = 1 << (plane == 0 ? h->luma_log2_weight_denom :
-                                               h->chroma_log2_weight_denom);
+                        w = 1 << (plane == 0 ? sl->luma_log2_weight_denom :
+                                               sl->chroma_log2_weight_denom);
                         o = 0;
                     }
                     slice->Weights[list][i][plane][0] = w;
@@ -275,15 +276,15 @@
         }
     }
     slice->slice_qs_delta    = 0; /* XXX not implemented by FFmpeg */
-    slice->slice_qp_delta    = h->qscale - h->pps.init_qp;
-    slice->redundant_pic_cnt = h->redundant_pic_count;
-    if (h->slice_type == AV_PICTURE_TYPE_B)
-        slice->direct_spatial_mv_pred_flag = h->direct_spatial_mv_pred;
-    slice->cabac_init_idc = h->pps.cabac ? h->cabac_init_idc : 0;
-    if (h->deblocking_filter < 2)
-        slice->disable_deblocking_filter_idc = 1 - h->deblocking_filter;
+    slice->slice_qp_delta    = sl->qscale - h->pps.init_qp;
+    slice->redundant_pic_cnt = sl->redundant_pic_count;
+    if (sl->slice_type == AV_PICTURE_TYPE_B)
+        slice->direct_spatial_mv_pred_flag = sl->direct_spatial_mv_pred;
+    slice->cabac_init_idc = h->pps.cabac ? sl->cabac_init_idc : 0;
+    if (sl->deblocking_filter < 2)
+        slice->disable_deblocking_filter_idc = 1 - sl->deblocking_filter;
     else
-        slice->disable_deblocking_filter_idc = h->deblocking_filter;
+        slice->disable_deblocking_filter_idc = sl->deblocking_filter;
     slice->slice_id = h->current_slice - 1;
 }
 
@@ -416,6 +417,7 @@
                                    uint32_t size)
 {
     const H264Context *h = avctx->priv_data;
+    const H264SliceContext *sl = &h->slice_ctx[0];
     struct dxva_context *ctx = avctx->hwaccel_context;
     const H264Picture *current_picture = h->cur_pic_ptr;
     struct dxva2_picture_context *ctx_pic = current_picture->hwaccel_picture_private;
@@ -437,7 +439,7 @@
                         &ctx_pic->pp, position, size);
     ctx_pic->slice_count++;
 
-    if (h->slice_type != AV_PICTURE_TYPE_I && h->slice_type != AV_PICTURE_TYPE_SI)
+    if (sl->slice_type != AV_PICTURE_TYPE_I && sl->slice_type != AV_PICTURE_TYPE_SI)
         ctx_pic->pp.wBitFields &= ~(1 << 15); /* Set IntraPicFlag to 0 */
     return 0;
 }
@@ -445,6 +447,7 @@
 static int dxva2_h264_end_frame(AVCodecContext *avctx)
 {
     H264Context *h = avctx->priv_data;
+    H264SliceContext *sl = &h->slice_ctx[0];
     struct dxva2_picture_context *ctx_pic =
         h->cur_pic_ptr->hwaccel_picture_private;
     int ret;
@@ -456,7 +459,7 @@
                                     &ctx_pic->qm, sizeof(ctx_pic->qm),
                                     commit_bitstream_and_slice_buffer);
     if (!ret)
-        ff_h264_draw_horiz_band(h, 0, h->avctx->height);
+        ff_h264_draw_horiz_band(h, sl, 0, h->avctx->height);
     return ret;
 }
 
diff --git a/libavcodec/dxva2_hevc.c b/libavcodec/dxva2_hevc.c
index a9df5f4..4fba3ad 100644
--- a/libavcodec/dxva2_hevc.c
+++ b/libavcodec/dxva2_hevc.c
@@ -192,23 +192,29 @@
 
 static void fill_scaling_lists(struct dxva_context *ctx, const HEVCContext *h, DXVA_Qmatrix_HEVC *qm)
 {
-    unsigned i, j;
+    unsigned i, j, pos;
+    const ScalingList *sl = h->pps->scaling_list_data_present_flag ?
+                            &h->pps->scaling_list : &h->sps->scaling_list;
+
     memset(qm, 0, sizeof(*qm));
     for (i = 0; i < 6; i++) {
-        for (j = 0; j < 16; j++)
-            qm->ucScalingLists0[i][j] = h->pps->scaling_list.sl[0][i][j];
-
-        for (j = 0; j < 64; j++) {
-            qm->ucScalingLists1[i][j] = h->pps->scaling_list.sl[1][i][j];
-            qm->ucScalingLists2[i][j] = h->pps->scaling_list.sl[2][i][j];
-
-            if (i < 2)
-                qm->ucScalingLists3[i][j] = h->pps->scaling_list.sl[3][i][j];
+        for (j = 0; j < 16; j++) {
+            pos = 4 * ff_hevc_diag_scan4x4_y[j] + ff_hevc_diag_scan4x4_x[j];
+            qm->ucScalingLists0[i][j] = sl->sl[0][i][pos];
         }
 
-        qm->ucScalingListDCCoefSizeID2[i] = h->pps->scaling_list.sl_dc[0][i];
+        for (j = 0; j < 64; j++) {
+            pos = 8 * ff_hevc_diag_scan8x8_y[j] + ff_hevc_diag_scan8x8_x[j];
+            qm->ucScalingLists1[i][j] = sl->sl[1][i][pos];
+            qm->ucScalingLists2[i][j] = sl->sl[2][i][pos];
+
+            if (i < 2)
+                qm->ucScalingLists3[i][j] = sl->sl[3][i][pos];
+        }
+
+        qm->ucScalingListDCCoefSizeID2[i] = sl->sl_dc[0][i];
         if (i < 2)
-            qm->ucScalingListDCCoefSizeID3[i] = h->pps->scaling_list.sl_dc[1][i];
+            qm->ucScalingListDCCoefSizeID3[i] = sl->sl_dc[1][i];
     }
 }
 
diff --git a/libavcodec/eac3dec.c b/libavcodec/eac3dec.c
index 8e931fd..ef815af 100644
--- a/libavcodec/eac3dec.c
+++ b/libavcodec/eac3dec.c
@@ -63,7 +63,7 @@
 
 #define EAC3_SR_CODE_REDUCED  3
 
-void ff_eac3_apply_spectral_extension(AC3DecodeContext *s)
+static void ff_eac3_apply_spectral_extension(AC3DecodeContext *s)
 {
     int bin, bnd, ch, i;
     uint8_t wrapflag[SPX_MAX_BANDS]={1,0,}, num_copy_sections, copy_sizes[SPX_MAX_BANDS];
@@ -101,7 +101,7 @@
         for (i = 0; i < num_copy_sections; i++) {
             memcpy(&s->transform_coeffs[ch][bin],
                    &s->transform_coeffs[ch][s->spx_dst_start_freq],
-                   copy_sizes[i]*sizeof(float));
+                   copy_sizes[i]*sizeof(INTFLOAT));
             bin += copy_sizes[i];
         }
 
@@ -124,7 +124,7 @@
             bin = s->spx_src_start_freq - 2;
             for (bnd = 0; bnd < s->num_spx_bands; bnd++) {
                 if (wrapflag[bnd]) {
-                    float *coeffs = &s->transform_coeffs[ch][bin];
+                    INTFLOAT *coeffs = &s->transform_coeffs[ch][bin];
                     coeffs[0] *= atten_tab[0];
                     coeffs[1] *= atten_tab[1];
                     coeffs[2] *= atten_tab[2];
@@ -142,6 +142,11 @@
         for (bnd = 0; bnd < s->num_spx_bands; bnd++) {
             float nscale = s->spx_noise_blend[ch][bnd] * rms_energy[bnd] * (1.0f / INT32_MIN);
             float sscale = s->spx_signal_blend[ch][bnd];
+#if USE_FIXED
+            // spx_noise_blend and spx_signal_blend are both FP.23
+            nscale *= 1.0 / (1<<23);
+            sscale *= 1.0 / (1<<23);
+#endif
             for (i = 0; i < s->spx_band_sizes[bnd]; i++) {
                 float noise  = nscale * (int32_t)av_lfg_get(&s->dith_state);
                 s->transform_coeffs[ch][bin]   *= sscale;
@@ -195,7 +200,7 @@
     pre_mant[5] = even0 - odd0;
 }
 
-void ff_eac3_decode_transform_coeffs_aht_ch(AC3DecodeContext *s, int ch)
+static void ff_eac3_decode_transform_coeffs_aht_ch(AC3DecodeContext *s, int ch)
 {
     int bin, blk, gs;
     int end_bap, gaq_mode;
@@ -288,7 +293,7 @@
     }
 }
 
-int ff_eac3_parse_header(AC3DecodeContext *s)
+static int ff_eac3_parse_header(AC3DecodeContext *s)
 {
     int i, blk, ch;
     int ac3_exponent_strategy, parse_aht_info, parse_spx_atten_data;
diff --git a/libavcodec/eamad.c b/libavcodec/eamad.c
index 813a2d1..6b7134a 100644
--- a/libavcodec/eamad.c
+++ b/libavcodec/eamad.c
@@ -151,6 +151,11 @@
                 break;
             } else if (level != 0) {
                 i += run;
+                if (i > 63) {
+                    av_log(s->avctx, AV_LOG_ERROR,
+                           "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
+                    return -1;
+                }
                 j = scantable[i];
                 level = (level*quant_matrix[j]) >> 4;
                 level = (level-1)|1;
@@ -165,6 +170,11 @@
                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
 
                 i += run;
+                if (i > 63) {
+                    av_log(s->avctx, AV_LOG_ERROR,
+                           "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
+                    return -1;
+                }
                 j = scantable[i];
                 if (level < 0) {
                     level = -level;
@@ -176,10 +186,6 @@
                     level = (level-1)|1;
                 }
             }
-            if (i > 63) {
-                av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
-                return -1;
-            }
 
             block[j] = level;
         }
diff --git a/libavcodec/elbg.c b/libavcodec/elbg.c
index 851be8e..23ae948 100644
--- a/libavcodec/elbg.c
+++ b/libavcodec/elbg.c
@@ -44,7 +44,7 @@
 /**
  * ELBG internal data
  */
-typedef struct{
+typedef struct elbg_data {
     int error;
     int dim;
     int numCB;
diff --git a/libavcodec/error_resilience.c b/libavcodec/error_resilience.c
index 4fa7bc4..3366db1 100644
--- a/libavcodec/error_resilience.c
+++ b/libavcodec/error_resilience.c
@@ -1024,7 +1024,7 @@
             const int mb_xy = s->mb_index2xy[i];
             int       error = s->error_status_table[mb_xy];
 
-            if (!s->mbskip_table[mb_xy]) // FIXME partition specific
+            if (!s->mbskip_table || !s->mbskip_table[mb_xy]) // FIXME partition specific
                 distance++;
             if (error & (1 << error_type))
                 distance = 0;
@@ -1297,11 +1297,12 @@
         const int mb_xy = s->mb_index2xy[i];
         int       error = s->error_status_table[mb_xy];
 
-        if (s->cur_pic.f->pict_type != AV_PICTURE_TYPE_B &&
+        if (s->mbskip_table && s->cur_pic.f->pict_type != AV_PICTURE_TYPE_B &&
             (error & (ER_DC_ERROR | ER_MV_ERROR | ER_AC_ERROR))) {
             s->mbskip_table[mb_xy] = 0;
         }
-        s->mbintra_table[mb_xy] = 1;
+        if (s->mbintra_table)
+            s->mbintra_table[mb_xy] = 1;
     }
 
     for (i = 0; i < 2; i++) {
diff --git a/libavcodec/evrcdec.c b/libavcodec/evrcdec.c
index 20d0fe7..c605a13 100644
--- a/libavcodec/evrcdec.c
+++ b/libavcodec/evrcdec.c
@@ -760,7 +760,8 @@
                                  && !e->prev_error_flag)
         goto erasure;
 
-    init_get_bits(&e->gb, buf, 8 * buf_size);
+    if ((ret = init_get_bits8(&e->gb, buf, buf_size)) < 0)
+        return ret;
     memset(&e->frame, 0, sizeof(EVRCAFrame));
 
     unpack_frame(e);
diff --git a/libavcodec/exr.c b/libavcodec/exr.c
index f9525ec..6251fb7 100644
--- a/libavcodec/exr.c
+++ b/libavcodec/exr.c
@@ -322,7 +322,7 @@
 
     i = k - 1;
 
-    memset(lut + k, 0, (USHORT_RANGE - k) * 2);
+    memset(lut + k * 2, 0, (USHORT_RANGE - k) * 2);
 
     return i;
 }
diff --git a/libavcodec/faxcompr.c b/libavcodec/faxcompr.c
index 155f78d..eb39ae0 100644
--- a/libavcodec/faxcompr.c
+++ b/libavcodec/faxcompr.c
@@ -251,7 +251,7 @@
     PutBitContext pb;
     int run, mode = ~0, pix_left = width, run_idx = 0;
 
-    init_put_bits(&pb, dst, size * 8);
+    init_put_bits(&pb, dst, size);
     while (pix_left > 0) {
         run       = runs[run_idx++];
         mode      = ~mode;
@@ -296,7 +296,8 @@
     ref[0] = avctx->width;
     ref[1] = 0;
     ref[2] = 0;
-    init_get_bits(&gb, src, srcsize * 8);
+    if ((ret = init_get_bits8(&gb, src, srcsize)) < 0)
+        goto fail;
     has_eol = show_bits(&gb, 12) == 1 || show_bits(&gb, 16) == 1;
 
     for (j = 0; j < height; j++) {
diff --git a/libavcodec/ffv1enc.c b/libavcodec/ffv1enc.c
index 39a1501f..942bc37 100644
--- a/libavcodec/ffv1enc.c
+++ b/libavcodec/ffv1enc.c
@@ -780,6 +780,10 @@
         s->colorspace = 1;
         s->chroma_planes = 1;
         s->version = FFMAX(s->version, 1);
+        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);
@@ -924,7 +928,7 @@
                         if (a+b)
                             p = 256.0 * b / (a + b);
                         s->initial_states[i][jp][k] =
-                            best_state[av_clip(round(p), 1, 255)][av_clip((a + b) / gob_count, 0, 255)];
+                            best_state[av_clip(round(p), 1, 255)][av_clip_uint8((a + b) / gob_count)];
                         for(jp++; jp<j; jp++)
                             s->initial_states[i][jp][k] = s->initial_states[i][jp-1][k];
                         a=b=0;
@@ -935,7 +939,7 @@
                         p = 256.0 * b / (a + b);
                     }
                     s->initial_states[i][j][k] =
-                        best_state[av_clip(round(p), 1, 255)][av_clip((a + b) / gob_count, 0, 255)];
+                        best_state[av_clip(round(p), 1, 255)][av_clip_uint8((a + b) / gob_count)];
                 }
             }
         }
diff --git a/libavcodec/fic.c b/libavcodec/fic.c
index adc8a25..48e7a6e 100644
--- a/libavcodec/fic.c
+++ b/libavcodec/fic.c
@@ -266,10 +266,8 @@
     int skip_cursor = 0;
     uint8_t *sdata;
 
-    if ((ret = ff_reget_buffer(avctx, ctx->frame)) < 0) {
-        av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
+    if ((ret = ff_reget_buffer(avctx, ctx->frame)) < 0)
         return ret;
-    }
 
     /* Header + at least one slice (4) */
     if (avpkt->size < FIC_HEADER_SIZE + 4) {
diff --git a/libavcodec/flashsv2enc.c b/libavcodec/flashsv2enc.c
index f74160a..a8bcaa2 100644
--- a/libavcodec/flashsv2enc.c
+++ b/libavcodec/flashsv2enc.c
@@ -287,7 +287,7 @@
     if (buf_size < 5)
         return -1;
 
-    init_put_bits(&pb, buf, buf_size * 8);
+    init_put_bits(&pb, buf, buf_size);
 
     put_bits(&pb, 4, (s->block_width  >> 4) - 1);
     put_bits(&pb, 12, s->image_width);
diff --git a/libavcodec/flashsvenc.c b/libavcodec/flashsvenc.c
index a6d7caa..14e8ada 100644
--- a/libavcodec/flashsvenc.c
+++ b/libavcodec/flashsvenc.c
@@ -151,7 +151,7 @@
     int buf_pos, res;
     int pred_blocks = 0;
 
-    init_put_bits(&pb, buf, buf_size * 8);
+    init_put_bits(&pb, buf, buf_size);
 
     put_bits(&pb,  4, block_width / 16 - 1);
     put_bits(&pb, 12, s->image_width);
diff --git a/libavcodec/fmtconvert.c b/libavcodec/fmtconvert.c
index fb4302c..e6fc509 100644
--- a/libavcodec/fmtconvert.c
+++ b/libavcodec/fmtconvert.c
@@ -41,59 +41,10 @@
         c->int32_to_float_fmul_scalar(&dst[i], &src[i], *mul++, 8);
 }
 
-static av_always_inline int float_to_int16_one(const float *src){
-    return av_clip_int16(lrintf(*src));
-}
-
-static void float_to_int16_c(int16_t *dst, const float *src, long len)
-{
-    int i;
-    for(i=0; i<len; i++)
-        dst[i] = float_to_int16_one(src+i);
-}
-
-static void float_to_int16_interleave_c(int16_t *dst, const float **src,
-                                        long len, int channels)
-{
-    int i,j,c;
-    if(channels==2){
-        for(i=0; i<len; i++){
-            dst[2*i]   = float_to_int16_one(src[0]+i);
-            dst[2*i+1] = float_to_int16_one(src[1]+i);
-        }
-    }else{
-        for(c=0; c<channels; c++)
-            for(i=0, j=c; i<len; i++, j+=channels)
-                dst[j] = float_to_int16_one(src[c]+i);
-    }
-}
-
-void ff_float_interleave_c(float *dst, const float **src, unsigned int len,
-                           int channels)
-{
-    int j, c;
-    unsigned int i;
-    if (channels == 2) {
-        for (i = 0; i < len; i++) {
-            dst[2*i]   = src[0][i];
-            dst[2*i+1] = src[1][i];
-        }
-    } else if (channels == 1 && len < INT_MAX / sizeof(float)) {
-        memcpy(dst, src[0], len * sizeof(float));
-    } else {
-        for (c = 0; c < channels; c++)
-            for (i = 0, j = c; i < len; i++, j += channels)
-                dst[j] = src[c][i];
-    }
-}
-
 av_cold void ff_fmt_convert_init(FmtConvertContext *c, AVCodecContext *avctx)
 {
     c->int32_to_float_fmul_scalar = int32_to_float_fmul_scalar_c;
     c->int32_to_float_fmul_array8 = int32_to_float_fmul_array8_c;
-    c->float_to_int16             = float_to_int16_c;
-    c->float_to_int16_interleave  = float_to_int16_interleave_c;
-    c->float_interleave           = ff_float_interleave_c;
 
     if (ARCH_ARM) ff_fmt_convert_init_arm(c, avctx);
     if (ARCH_PPC) ff_fmt_convert_init_ppc(c, avctx);
diff --git a/libavcodec/fmtconvert.h b/libavcodec/fmtconvert.h
index 30abcc3..401ac3a 100644
--- a/libavcodec/fmtconvert.h
+++ b/libavcodec/fmtconvert.h
@@ -54,56 +54,8 @@
                                        float *dst, const int32_t *src,
                                        const float *mul, int len);
 
-    /**
-     * Convert an array of float to an array of int16_t.
-     *
-     * Convert floats from in the range [-32768.0,32767.0] to ints
-     * without rescaling
-     *
-     * @param dst destination array of int16_t.
-     *            constraints: 16-byte aligned
-     * @param src source array of float.
-     *            constraints: 16-byte aligned
-     * @param len number of elements to convert.
-     *            constraints: multiple of 8
-     */
-    void (*float_to_int16)(int16_t *dst, const float *src, long len);
-
-    /**
-     * Convert multiple arrays of float to an interleaved array of int16_t.
-     *
-     * Convert floats from in the range [-32768.0,32767.0] to ints
-     * without rescaling
-     *
-     * @param dst destination array of interleaved int16_t.
-     *            constraints: 16-byte aligned
-     * @param src source array of float arrays, one for each channel.
-     *            constraints: 16-byte aligned
-     * @param len number of elements to convert.
-     *            constraints: multiple of 8
-     * @param channels number of channels
-     */
-    void (*float_to_int16_interleave)(int16_t *dst, const float **src,
-                                      long len, int channels);
-
-    /**
-     * Convert multiple arrays of float to an array of interleaved float.
-     *
-     * @param dst destination array of interleaved float.
-     *            constraints: 16-byte aligned
-     * @param src source array of float arrays, one for each channel.
-     *            constraints: 16-byte aligned
-     * @param len number of elements to convert.
-     *            constraints: multiple of 8
-     * @param channels number of channels
-     */
-    void (*float_interleave)(float *dst, const float **src, unsigned int len,
-                             int channels);
 } FmtConvertContext;
 
-void ff_float_interleave_c(float *dst, const float **src, unsigned int len,
-                           int channels);
-
 void ff_fmt_convert_init(FmtConvertContext *c, AVCodecContext *avctx);
 
 void ff_fmt_convert_init_arm(FmtConvertContext *c, AVCodecContext *avctx);
diff --git a/libavcodec/g722.c b/libavcodec/g722.c
index 2c04c40..ee3b85f 100644
--- a/libavcodec/g722.c
+++ b/libavcodec/g722.c
@@ -71,15 +71,35 @@
      211,   170,   130,    91,    54,    17,   -54,   -17
 };
 
-/**
- * quadrature mirror filter (QMF) coefficients
- *
- * ITU-T G.722 Table 11
- */
-static const int16_t qmf_coeffs[12] = {
-    3, -11, 12, 32, -210, 951, 3876, -805, 362, -156, 53, -11,
-};
+static inline void s_zero(int cur_diff, struct G722Band *band)
+{
+    int s_zero = 0;
 
+    #define ACCUM(k, x, d) do { \
+            int tmp = x; \
+            band->zero_mem[k] = ((band->zero_mem[k] * 255) >> 8) + \
+               d*((band->diff_mem[k]^cur_diff) < 0 ? -128 : 128); \
+            band->diff_mem[k] = tmp; \
+            s_zero += (tmp * band->zero_mem[k]) >> 15; \
+        } while (0)
+    if (cur_diff) {
+        ACCUM(5, band->diff_mem[4], 1);
+        ACCUM(4, band->diff_mem[3], 1);
+        ACCUM(3, band->diff_mem[2], 1);
+        ACCUM(2, band->diff_mem[1], 1);
+        ACCUM(1, band->diff_mem[0], 1);
+        ACCUM(0, cur_diff << 1, 1);
+    } else {
+        ACCUM(5, band->diff_mem[4], 0);
+        ACCUM(4, band->diff_mem[3], 0);
+        ACCUM(3, band->diff_mem[2], 0);
+        ACCUM(2, band->diff_mem[1], 0);
+        ACCUM(1, band->diff_mem[0], 0);
+        ACCUM(0, cur_diff << 1, 0);
+    }
+    #undef ACCUM
+    band->s_zero = s_zero;
+}
 
 /**
  * adaptive predictor
@@ -89,7 +109,7 @@
  */
 static void do_adaptive_prediction(struct G722Band *band, const int cur_diff)
 {
-    int sg[2], limit, i, cur_qtzd_reconst;
+    int sg[2], limit, cur_qtzd_reconst;
 
     const int cur_part_reconst = band->s_zero + cur_diff < 0;
 
@@ -104,23 +124,7 @@
     limit = 15360 - band->pole_mem[1];
     band->pole_mem[0] = av_clip(-192 * sg[0] + (band->pole_mem[0] * 255 >> 8), -limit, limit);
 
-
-    if (cur_diff) {
-        for (i = 0; i < 6; i++)
-            band->zero_mem[i] = ((band->zero_mem[i]*255) >> 8) +
-                                ((band->diff_mem[i]^cur_diff) < 0 ? -128 : 128);
-    } else
-        for (i = 0; i < 6; i++)
-            band->zero_mem[i] = (band->zero_mem[i]*255) >> 8;
-
-    for (i = 5; i > 0; i--)
-        band->diff_mem[i] = band->diff_mem[i-1];
-    band->diff_mem[0] = av_clip_int16(cur_diff << 1);
-
-    band->s_zero = 0;
-    for (i = 5; i >= 0; i--)
-        band->s_zero += (band->zero_mem[i]*band->diff_mem[i]) >> 15;
-
+    s_zero(cur_diff, band);
 
     cur_qtzd_reconst = av_clip_int16((band->s_predictor + cur_diff) << 1);
     band->s_predictor = av_clip_int16(band->s_zero +
@@ -157,15 +161,3 @@
                                  high_log_factor_step[ihigh&1], 0, 22528);
     band->scale_factor = linear_scale_factor(band->log_factor - (10 << 11));
 }
-
-void ff_g722_apply_qmf(const int16_t *prev_samples, int *xout1, int *xout2)
-{
-    int i;
-
-    *xout1 = 0;
-    *xout2 = 0;
-    for (i = 0; i < 12; i++) {
-        MAC16(*xout2, prev_samples[2*i  ], qmf_coeffs[i   ]);
-        MAC16(*xout1, prev_samples[2*i+1], qmf_coeffs[11-i]);
-    }
-}
diff --git a/libavcodec/g722.h b/libavcodec/g722.h
index 3f89827..25676a3 100644
--- a/libavcodec/g722.h
+++ b/libavcodec/g722.h
@@ -27,6 +27,7 @@
 
 #include <stdint.h>
 #include "avcodec.h"
+#include "g722dsp.h"
 
 #define PREV_SAMPLES_BUF_SIZE 1024
 
@@ -61,6 +62,8 @@
         int value;
         int prev;
     } *paths[2];
+
+    G722DSPContext dsp;
 } G722Context;
 
 extern const int16_t ff_g722_high_inv_quant[4];
@@ -72,6 +75,4 @@
 void ff_g722_update_high_predictor(struct G722Band *band, const int dhigh,
                                    const int ihigh);
 
-void ff_g722_apply_qmf(const int16_t *prev_samples, int *xout1, int *xout2);
-
 #endif /* AVCODEC_G722_H */
diff --git a/libavcodec/g722dec.c b/libavcodec/g722dec.c
index 14bd67e..22e90a3 100644
--- a/libavcodec/g722dec.c
+++ b/libavcodec/g722dec.c
@@ -67,6 +67,8 @@
     c->band[1].scale_factor = 2;
     c->prev_samples_pos = 22;
 
+    ff_g722dsp_init(&c->dsp);
+
     return 0;
 }
 
@@ -102,28 +104,27 @@
 
     for (j = 0; j < avpkt->size; j++) {
         int ilow, ihigh, rlow, rhigh, dhigh;
-        int xout1, xout2;
+        int xout[2];
 
         ihigh = get_bits(&gb, 2);
         ilow = get_bits(&gb, 6 - skip);
         skip_bits(&gb, skip);
 
-        rlow = av_clip((c->band[0].scale_factor * quantizer_table[ilow] >> 10)
-                      + c->band[0].s_predictor, -16384, 16383);
+        rlow = av_clip_intp2((c->band[0].scale_factor * quantizer_table[ilow] >> 10)
+                      + c->band[0].s_predictor, 14);
 
         ff_g722_update_low_predictor(&c->band[0], ilow >> (2 - skip));
 
         dhigh = c->band[1].scale_factor * ff_g722_high_inv_quant[ihigh] >> 10;
-        rhigh = av_clip(dhigh + c->band[1].s_predictor, -16384, 16383);
+        rhigh = av_clip_intp2(dhigh + c->band[1].s_predictor, 14);
 
         ff_g722_update_high_predictor(&c->band[1], dhigh, ihigh);
 
         c->prev_samples[c->prev_samples_pos++] = rlow + rhigh;
         c->prev_samples[c->prev_samples_pos++] = rlow - rhigh;
-        ff_g722_apply_qmf(c->prev_samples + c->prev_samples_pos - 24,
-                          &xout1, &xout2);
-        *out_buf++ = av_clip_int16(xout1 >> 11);
-        *out_buf++ = av_clip_int16(xout2 >> 11);
+        c->dsp.apply_qmf(c->prev_samples + c->prev_samples_pos - 24, xout);
+        *out_buf++ = av_clip_int16(xout[0] >> 11);
+        *out_buf++ = av_clip_int16(xout[1] >> 11);
         if (c->prev_samples_pos >= PREV_SAMPLES_BUF_SIZE) {
             memmove(c->prev_samples, c->prev_samples + c->prev_samples_pos - 22,
                     22 * sizeof(c->prev_samples[0]));
diff --git a/libavcodec/g722dsp.c b/libavcodec/g722dsp.c
new file mode 100644
index 0000000..f148053
--- /dev/null
+++ b/libavcodec/g722dsp.c
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2015 Peter Meerwald <pmeerw@pmeerw.net>
+ *
+ * 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 "g722dsp.h"
+#include "mathops.h"
+
+/*
+ * quadrature mirror filter (QMF) coefficients (ITU-T G.722 Table 11) inlined
+ * in code below: 3, -11, 12, 32, -210, 951, 3876, -805, 362, -156, 53, -11
+ */
+
+static void g722_apply_qmf(const int16_t *prev_samples, int xout[2])
+{
+    xout[1] = MUL16(*prev_samples++, 3);
+    xout[0] = MUL16(*prev_samples++, -11);
+
+    MAC16(xout[1], *prev_samples++, -11);
+    MAC16(xout[0], *prev_samples++, 53);
+
+    MAC16(xout[1], *prev_samples++, 12);
+    MAC16(xout[0], *prev_samples++, -156);
+
+    MAC16(xout[1], *prev_samples++, 32);
+    MAC16(xout[0], *prev_samples++, 362);
+
+    MAC16(xout[1], *prev_samples++, -210);
+    MAC16(xout[0], *prev_samples++, -805);
+
+    MAC16(xout[1], *prev_samples++, 951);
+    MAC16(xout[0], *prev_samples++, 3876);
+
+    MAC16(xout[1], *prev_samples++, 3876);
+    MAC16(xout[0], *prev_samples++, 951);
+
+    MAC16(xout[1], *prev_samples++, -805);
+    MAC16(xout[0], *prev_samples++, -210);
+
+    MAC16(xout[1], *prev_samples++, 362);
+    MAC16(xout[0], *prev_samples++, 32);
+
+    MAC16(xout[1], *prev_samples++, -156);
+    MAC16(xout[0], *prev_samples++, 12);
+
+    MAC16(xout[1], *prev_samples++, 53);
+    MAC16(xout[0], *prev_samples++, -11);
+
+    MAC16(xout[1], *prev_samples++, -11);
+    MAC16(xout[0], *prev_samples++, 3);
+}
+
+av_cold void ff_g722dsp_init(G722DSPContext *c)
+{
+    c->apply_qmf = g722_apply_qmf;
+
+    if (ARCH_ARM)
+        ff_g722dsp_init_arm(c);
+    if (ARCH_X86)
+        ff_g722dsp_init_x86(c);
+}
diff --git a/libavcodec/g722dsp.h b/libavcodec/g722dsp.h
new file mode 100644
index 0000000..c956a1e
--- /dev/null
+++ b/libavcodec/g722dsp.h
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2015 Peter Meerwald <pmeerw@pmeerw.net>
+ *
+ * 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_G722DSP_H
+#define AVCODEC_G722DSP_H
+
+#include <stdint.h>
+
+typedef struct G722DSPContext {
+    void (*apply_qmf)(const int16_t *prev_samples, int xout[2]);
+} G722DSPContext;
+
+void ff_g722dsp_init(G722DSPContext *c);
+void ff_g722dsp_init_arm(G722DSPContext *c);
+void ff_g722dsp_init_x86(G722DSPContext *c);
+
+#endif /* AVCODEC_G722DSP_H */
diff --git a/libavcodec/g722enc.c b/libavcodec/g722enc.c
index 17dde9e..38432f5 100644
--- a/libavcodec/g722enc.c
+++ b/libavcodec/g722enc.c
@@ -120,6 +120,8 @@
         }
     }
 
+    ff_g722dsp_init(&c->dsp);
+
     return 0;
 error:
     g722_encode_close(avctx);
@@ -136,12 +138,12 @@
 static inline void filter_samples(G722Context *c, const int16_t *samples,
                                   int *xlow, int *xhigh)
 {
-    int xout1, xout2;
+    int xout[2];
     c->prev_samples[c->prev_samples_pos++] = samples[0];
     c->prev_samples[c->prev_samples_pos++] = samples[1];
-    ff_g722_apply_qmf(c->prev_samples + c->prev_samples_pos - 24, &xout1, &xout2);
-    *xlow  = xout1 + xout2 >> 14;
-    *xhigh = xout1 - xout2 >> 14;
+    c->dsp.apply_qmf(c->prev_samples + c->prev_samples_pos - 24, xout);
+    *xlow  = xout[0] + xout[1] >> 14;
+    *xhigh = xout[0] - xout[1] >> 14;
     if (c->prev_samples_pos >= PREV_SAMPLES_BUF_SIZE) {
         memmove(c->prev_samples,
                 c->prev_samples + c->prev_samples_pos - 22,
@@ -224,9 +226,9 @@
                 if (k < 0)
                     continue;
 
-                decoded = av_clip((cur_node->state.scale_factor *
+                decoded = av_clip_intp2((cur_node->state.scale_factor *
                                   ff_g722_low_inv_quant6[k] >> 10)
-                                + cur_node->state.s_predictor, -16384, 16383);
+                                + cur_node->state.s_predictor, 14);
                 dec_diff = xlow - decoded;
 
 #define STORE_NODE(index, UPDATE, VALUE)\
@@ -283,8 +285,7 @@
 
                 dhigh = cur_node->state.scale_factor *
                         ff_g722_high_inv_quant[ihigh] >> 10;
-                decoded = av_clip(dhigh + cur_node->state.s_predictor,
-                                  -16384, 16383);
+                decoded = av_clip_intp2(dhigh + cur_node->state.s_predictor, 14);
                 dec_diff = xhigh - decoded;
 
                 STORE_NODE(1, ff_g722_update_high_predictor(&node->state, dhigh, ihigh), ihigh);
diff --git a/libavcodec/g723_1_data.h b/libavcodec/g723_1_data.h
index 38a6c59..db7f6e4 100644
--- a/libavcodec/g723_1_data.h
+++ b/libavcodec/g723_1_data.h
@@ -78,7 +78,7 @@
 /**
  * Pitch postfilter parameters
  */
-typedef struct {
+typedef struct PPFParam {
     int     index;    ///< postfilter backward/forward lag
     int16_t opt_gain; ///< optimal gain
     int16_t sc_gain;  ///< scaling gain
@@ -87,7 +87,7 @@
 /**
  * Harmonic filter parameters
  */
-typedef struct {
+typedef struct HFParam {
     int index;
     int gain;
 } HFParam;
@@ -95,7 +95,7 @@
 /**
  * Optimized fixed codebook excitation parameters
  */
-typedef struct {
+typedef struct FCBParam {
     int min_err;
     int amp_index;
     int grid_index;
diff --git a/libavcodec/g726.c b/libavcodec/g726.c
index b0331d8..5b9986a 100644
--- a/libavcodec/g726.c
+++ b/libavcodec/g726.c
@@ -219,7 +219,7 @@
             c->b[i] = 0;
     } else {
         /* This is a bit crazy, but it really is +255 not +256 */
-        fa1 = av_clip((-c->a[0]*c->pk[0]*pk0)>>5, -256, 255);
+        fa1 = av_clip_intp2((-c->a[0]*c->pk[0]*pk0)>>5, 8);
 
         c->a[1] += 128*pk0*c->pk[1] + fa1 - (c->a[1]>>7);
         c->a[1] = av_clip(c->a[1], -12288, 12288);
diff --git a/libavcodec/gif.c b/libavcodec/gif.c
index 27d054e..cf5d438 100644
--- a/libavcodec/gif.c
+++ b/libavcodec/gif.c
@@ -39,13 +39,16 @@
 
 #include "put_bits.h"
 
-typedef struct {
+typedef struct GIFContext {
     const AVClass *class;
     LZWState *lzw;
     uint8_t *buf;
     AVFrame *last_frame;
     int flags;
     uint32_t palette[AVPALETTE_COUNT];  ///< local reference palette for !pal8
+    int palette_loaded;
+    int transparent_index;
+    uint8_t *pal_exdata;
     uint8_t *tmpl;                      ///< temporary line buffer
 } GIFContext;
 
@@ -78,11 +81,11 @@
 {
     GIFContext *s = avctx->priv_data;
     int len = 0, height = avctx->height, width = avctx->width, x, y;
-    int x_start = 0, y_start = 0, trans = -1;
+    int x_start = 0, y_start = 0, trans = s->transparent_index;
+    int honor_transparency = (s->flags & GF_TRANSDIFF) && s->last_frame;
     const uint8_t *ptr;
 
     /* Crop image */
-    // TODO support with palette change
     if ((s->flags & GF_OFFSETTING) && s->last_frame && !palette) {
         const uint8_t *ref = s->last_frame->data[0];
         const int ref_linesize = s->last_frame->linesize[0];
@@ -105,7 +108,7 @@
         /* skip common columns */
         while (x_start < x_end) {
             int same_column = 1;
-            for (y = y_start; y < y_end; y++) {
+            for (y = y_start; y <= y_end; y++) {
                 if (ref[y*ref_linesize + x_start] != buf[y*linesize + x_start]) {
                     same_column = 0;
                     break;
@@ -117,7 +120,7 @@
         }
         while (x_end > x_start) {
             int same_column = 1;
-            for (y = y_start; y < y_end; y++) {
+            for (y = y_start; y <= y_end; y++) {
                 if (ref[y*ref_linesize + x_end] != buf[y*linesize + x_end]) {
                     same_column = 0;
                     break;
@@ -151,20 +154,23 @@
         }
     }
 
-    /* TODO: support with palette change (pal8) */
-    if ((s->flags & GF_TRANSDIFF) && s->last_frame && !palette) {
+    if (honor_transparency && trans < 0) {
         trans = pick_palette_entry(buf + y_start*linesize + x_start,
                                    linesize, width, height);
         if (trans < 0) { // TODO, patch welcome
             av_log(avctx, AV_LOG_DEBUG, "No available color, can not use transparency\n");
         } else {
-            uint8_t *pal_exdata = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
+            uint8_t *pal_exdata = s->pal_exdata;
+            if (!pal_exdata)
+                pal_exdata = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
             if (!pal_exdata)
                 return AVERROR(ENOMEM);
             memcpy(pal_exdata, s->palette, AVPALETTE_SIZE);
             pal_exdata[trans*4 + 3*!HAVE_BIGENDIAN] = 0x00;
         }
     }
+    if (trans < 0)
+        honor_transparency = 0;
 
     bytestream_put_byte(bytestream, 0x08);
 
@@ -172,7 +178,7 @@
                        12, FF_LZW_GIF, put_bits);
 
     ptr = buf + y_start*linesize + x_start;
-    if (trans >= 0) {
+    if (honor_transparency) {
         const int ref_linesize = s->last_frame->linesize[0];
         const uint8_t *ref = s->last_frame->data[0] + y_start*ref_linesize + x_start;
 
@@ -223,6 +229,8 @@
     avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
     avctx->coded_frame->key_frame = 1;
 
+    s->transparent_index = -1;
+
     s->lzw = av_mallocz(ff_lzw_encode_state_size);
     s->buf = av_malloc(avctx->width*avctx->height*2);
     s->tmpl = av_malloc(avctx->width);
@@ -235,6 +243,25 @@
     return 0;
 }
 
+/* FIXME: duplicated with lavc */
+static int get_palette_transparency_index(const uint32_t *palette)
+{
+    int transparent_color_index = -1;
+    unsigned i, smallest_alpha = 0xff;
+
+    if (!palette)
+        return -1;
+
+    for (i = 0; i < AVPALETTE_COUNT; i++) {
+        const uint32_t v = palette[i];
+        if (v >> 24 < smallest_alpha) {
+            smallest_alpha = v >> 24;
+            transparent_color_index = i;
+        }
+    }
+    return smallest_alpha < 128 ? transparent_color_index : -1;
+}
+
 static int gif_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
                             const AVFrame *pict, int *got_packet)
 {
@@ -254,6 +281,20 @@
             return AVERROR(ENOMEM);
         memcpy(pal_exdata, pict->data[1], AVPALETTE_SIZE);
         palette = (uint32_t*)pict->data[1];
+
+        s->pal_exdata = pal_exdata;
+
+        /* The first palette with PAL8 will be used as generic palette by the
+         * muxer so we don't need to write it locally in the packet. We store
+         * it as a reference here in case it changes later. */
+        if (!s->palette_loaded) {
+            memcpy(s->palette, palette, AVPALETTE_SIZE);
+            s->transparent_index = get_palette_transparency_index(palette);
+            s->palette_loaded = 1;
+            palette = NULL;
+        } else if (!memcmp(s->palette, palette, AVPALETTE_SIZE)) {
+            palette = NULL;
+        }
     }
 
     gif_image_write_image(avctx, &outbuf_ptr, end, palette,
diff --git a/libavcodec/golomb.h b/libavcodec/golomb.h
index c4b1354..28ae213 100644
--- a/libavcodec/golomb.h
+++ b/libavcodec/golomb.h
@@ -195,7 +195,7 @@
 
         return ff_se_golomb_vlc_code[buf];
     } else {
-        int log = av_log2(buf);
+        int log = av_log2(buf), sign;
         LAST_SKIP_BITS(re, gb, 31 - log);
         UPDATE_CACHE(re, gb);
         buf = GET_CACHE(re, gb);
@@ -205,10 +205,8 @@
         LAST_SKIP_BITS(re, gb, 32 - log);
         CLOSE_READER(re, gb);
 
-        if (buf & 1)
-            buf = -(buf >> 1);
-        else
-            buf = (buf >> 1);
+        sign = -(buf & 1);
+        buf  = ((buf >> 1) ^ sign) - sign;
 
         return buf;
     }
@@ -217,13 +215,8 @@
 static inline int get_se_golomb_long(GetBitContext *gb)
 {
     unsigned int buf = get_ue_golomb_long(gb);
-
-    if (buf & 1)
-        buf = (buf + 1) >> 1;
-    else
-        buf = -(buf >> 1);
-
-    return buf;
+    int sign = (buf & 1) - 1;
+    return ((buf >> 1) ^ sign) + 1;
 }
 
 static inline int svq3_get_se_golomb(GetBitContext *gb)
@@ -264,13 +257,8 @@
     uint32_t ret = svq3_get_ue_golomb(gb);
 
     if (ret) {
-        uint32_t buf;
-        OPEN_READER(re, gb);
-        UPDATE_CACHE(re, gb);
-        buf = SHOW_SBITS(re, gb, 1);
-        LAST_SKIP_BITS(re, gb, 1);
-        ret = (ret ^ buf) - buf;
-        CLOSE_READER(re, gb);
+        int sign = -get_bits1(gb);
+        ret = (ret ^ sign) - sign;
     }
 
     return ret;
@@ -293,7 +281,7 @@
 
     if (log > 31 - limit) {
         buf >>= log - k;
-        buf  += (30 - log) << k;
+        buf  += (30U - log) << k;
         LAST_SKIP_BITS(re, gb, 32 + k - log);
         CLOSE_READER(re, gb);
 
@@ -329,7 +317,7 @@
     if (log - k >= 32 - MIN_CACHE_BITS + (MIN_CACHE_BITS == 32) &&
         32 - log < limit) {
         buf >>= log - k;
-        buf  += (30 - log) << k;
+        buf  += (30U - log) << k;
         LAST_SKIP_BITS(re, gb, 32 + k - log);
         CLOSE_READER(re, gb);
 
@@ -372,14 +360,7 @@
                                 int esc_len)
 {
     int v = get_ur_golomb(gb, k, limit, esc_len);
-
-    v++;
-    if (v & 1)
-        return v >> 1;
-    else
-        return -(v >> 1);
-
-//    return (v>>1) ^ -(v&1);
+    return (v >> 1) ^ -(v & 1);
 }
 
 /**
@@ -406,10 +387,7 @@
 static inline int get_sr_golomb_shorten(GetBitContext *gb, int k)
 {
     int uvar = get_ur_golomb_jpegls(gb, k + 1, INT_MAX, 0);
-    if (uvar & 1)
-        return ~(uvar >> 1);
-    else
-        return uvar >> 1;
+    return (uvar >> 1) ^ -(uvar & 1);
 }
 
 #ifdef TRACE
diff --git a/libavcodec/h261dec.c b/libavcodec/h261dec.c
index 9064f1a..e9a3a8b 100644
--- a/libavcodec/h261dec.c
+++ b/libavcodec/h261dec.c
@@ -216,6 +216,13 @@
         s->mb_skipped                  = 1;
         h->mtype                      &= ~MB_TYPE_H261_FIL;
 
+        if (s->current_picture.motion_val[0]) {
+            int b_stride = 2*s->mb_width + 1;
+            int b_xy     = 2 * s->mb_x + (2 * s->mb_y) * b_stride;
+            s->current_picture.motion_val[0][b_xy][0] = s->mv[0][0][0];
+            s->current_picture.motion_val[0][b_xy][1] = s->mv[0][0][1];
+        }
+
         ff_mpv_decode_mb(s, s->block);
     }
 
diff --git a/libavcodec/h261enc.c b/libavcodec/h261enc.c
index 75211a0..1c3f2ec 100644
--- a/libavcodec/h261enc.c
+++ b/libavcodec/h261enc.c
@@ -46,7 +46,7 @@
         return 1;
     // ERROR
     else
-        return -1;
+        return AVERROR(EINVAL);
 }
 
 void ff_h261_encode_picture_header(MpegEncContext *s, int picture_number)
@@ -61,8 +61,8 @@
 
     put_bits(&s->pb, 20, 0x10); /* PSC */
 
-    temp_ref = s->picture_number * (int64_t)30000 * s->avctx->time_base.num /
-               (1001 * (int64_t)s->avctx->time_base.den);   // FIXME maybe this should use a timestamp
+    temp_ref = s->picture_number * 30000LL * s->avctx->time_base.num /
+               (1001LL * s->avctx->time_base.den);   // FIXME maybe this should use a timestamp
     put_sbits(&s->pb, 5, temp_ref); /* TemporalReference */
 
     put_bits(&s->pb, 1, 0); /* split screen off */
@@ -250,12 +250,13 @@
         /* mvd indicates if this block is motion compensated */
         mvd = motion_x | motion_y;
 
-        if ((cbp | mvd | s->dquant) == 0) {
+        if ((cbp | mvd) == 0) {
             /* skip macroblock */
             s->skip_count++;
             s->mb_skip_run++;
             s->last_mv[0][0][0] = 0;
             s->last_mv[0][0][1] = 0;
+            s->qscale -= s->dquant;
             return;
         }
     }
@@ -274,13 +275,15 @@
             h->mtype += 3;
         if (s->loop_filter)
             h->mtype += 3;
-        if (cbp || s->dquant)
+        if (cbp)
             h->mtype++;
         av_assert1(h->mtype > 1);
     }
 
-    if (s->dquant)
+    if (s->dquant && cbp) {
         h->mtype++;
+    } else
+        s->qscale -= s->dquant;
 
     put_bits(&s->pb,
              ff_h261_mtype_bits[h->mtype],
diff --git a/libavcodec/h264.c b/libavcodec/h264.c
index 199b0fc..b30c9f5 100644
--- a/libavcodec/h264.c
+++ b/libavcodec/h264.c
@@ -49,8 +49,6 @@
 #include "thread.h"
 #include "vdpau_internal.h"
 
-#include <assert.h>
-
 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
 
 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
@@ -64,41 +62,42 @@
                               int mb_x, int mb_y, int mb_intra, int mb_skipped)
 {
     H264Context *h = opaque;
+    H264SliceContext *sl = &h->slice_ctx[0];
 
-    h->mb_x  = mb_x;
-    h->mb_y  = mb_y;
-    h->mb_xy = mb_x + mb_y * h->mb_stride;
-    memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
+    sl->mb_x = mb_x;
+    sl->mb_y = mb_y;
+    sl->mb_xy = mb_x + mb_y * h->mb_stride;
+    memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
     av_assert1(ref >= 0);
     /* FIXME: It is possible albeit uncommon that slice references
      * differ between slices. We take the easy approach and ignore
      * it for now. If this turns out to have any relevance in
      * practice then correct remapping should be added. */
-    if (ref >= h->ref_count[0])
+    if (ref >= sl->ref_count[0])
         ref = 0;
-    if (!h->ref_list[0][ref].f.data[0]) {
+    if (!sl->ref_list[0][ref].data[0]) {
         av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
         ref = 0;
     }
-    if ((h->ref_list[0][ref].reference&3) != 3) {
+    if ((sl->ref_list[0][ref].reference&3) != 3) {
         av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
         return;
     }
-    fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
+    fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
                    2, 2, 2, ref, 1);
-    fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
-    fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
+    fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
+    fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
                    pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
-    h->mb_mbaff =
-    h->mb_field_decoding_flag = 0;
-    ff_h264_hl_decode_mb(h);
+    sl->mb_mbaff =
+    sl->mb_field_decoding_flag = 0;
+    ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
 }
 
-void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
+void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
+                             int y, int height)
 {
     AVCodecContext *avctx = h->avctx;
-    AVFrame *cur  = &h->cur_pic.f;
-    AVFrame *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0].f : NULL;
+    const AVFrame   *src  = &h->cur_pic.f;
     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
     int vshift = desc->log2_chroma_h;
     const int field_pic = h->picture_structure != PICT_FRAME;
@@ -113,18 +112,9 @@
         return;
 
     if (avctx->draw_horiz_band) {
-        AVFrame *src;
         int offset[AV_NUM_DATA_POINTERS];
         int i;
 
-        if (cur->pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
-            (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
-            src = cur;
-        else if (last)
-            src = last;
-        else
-            return;
-
         offset[0] = y * src->linesize[0];
         offset[1] =
         offset[2] = (y >> vshift) * src->linesize[1];
@@ -142,7 +132,7 @@
  * Check if the top & left blocks are available if needed and
  * change the dc mode so it only uses the available blocks.
  */
-int ff_h264_check_intra4x4_pred_mode(H264Context *h)
+int ff_h264_check_intra4x4_pred_mode(const H264Context *h, H264SliceContext *sl)
 {
     static const int8_t top[12] = {
         -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
@@ -152,32 +142,32 @@
     };
     int i;
 
-    if (!(h->top_samples_available & 0x8000)) {
+    if (!(sl->top_samples_available & 0x8000)) {
         for (i = 0; i < 4; i++) {
-            int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
+            int status = top[sl->intra4x4_pred_mode_cache[scan8[0] + i]];
             if (status < 0) {
                 av_log(h->avctx, AV_LOG_ERROR,
                        "top block unavailable for requested intra4x4 mode %d at %d %d\n",
-                       status, h->mb_x, h->mb_y);
+                       status, sl->mb_x, sl->mb_y);
                 return AVERROR_INVALIDDATA;
             } else if (status) {
-                h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
+                sl->intra4x4_pred_mode_cache[scan8[0] + i] = status;
             }
         }
     }
 
-    if ((h->left_samples_available & 0x8888) != 0x8888) {
+    if ((sl->left_samples_available & 0x8888) != 0x8888) {
         static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
         for (i = 0; i < 4; i++)
-            if (!(h->left_samples_available & mask[i])) {
-                int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
+            if (!(sl->left_samples_available & mask[i])) {
+                int status = left[sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
                 if (status < 0) {
                     av_log(h->avctx, AV_LOG_ERROR,
                            "left block unavailable for requested intra4x4 mode %d at %d %d\n",
-                           status, h->mb_x, h->mb_y);
+                           status, sl->mb_x, sl->mb_y);
                     return AVERROR_INVALIDDATA;
                 } else if (status) {
-                    h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
+                    sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
                 }
             }
     }
@@ -189,7 +179,8 @@
  * Check if the top & left blocks are available if needed and
  * change the dc mode so it only uses the available blocks.
  */
-int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
+int ff_h264_check_intra_pred_mode(const H264Context *h, H264SliceContext *sl,
+                                  int mode, int is_chroma)
 {
     static const int8_t top[4]  = { LEFT_DC_PRED8x8, 1, -1, -1 };
     static const int8_t left[5] = { TOP_DC_PRED8x8, -1,  2, -1, DC_128_PRED8x8 };
@@ -197,32 +188,32 @@
     if (mode > 3U) {
         av_log(h->avctx, AV_LOG_ERROR,
                "out of range intra chroma pred mode at %d %d\n",
-               h->mb_x, h->mb_y);
+               sl->mb_x, sl->mb_y);
         return AVERROR_INVALIDDATA;
     }
 
-    if (!(h->top_samples_available & 0x8000)) {
+    if (!(sl->top_samples_available & 0x8000)) {
         mode = top[mode];
         if (mode < 0) {
             av_log(h->avctx, AV_LOG_ERROR,
                    "top block unavailable for requested intra mode at %d %d\n",
-                   h->mb_x, h->mb_y);
+                   sl->mb_x, sl->mb_y);
             return AVERROR_INVALIDDATA;
         }
     }
 
-    if ((h->left_samples_available & 0x8080) != 0x8080) {
+    if ((sl->left_samples_available & 0x8080) != 0x8080) {
         mode = left[mode];
         if (mode < 0) {
             av_log(h->avctx, AV_LOG_ERROR,
                    "left block unavailable for requested intra mode at %d %d\n",
-                   h->mb_x, h->mb_y);
+                   sl->mb_x, sl->mb_y);
             return AVERROR_INVALIDDATA;
         }
-        if (is_chroma && (h->left_samples_available & 0x8080)) {
+        if (is_chroma && (sl->left_samples_available & 0x8080)) {
             // mad cow disease mode, aka MBAFF + constrained_intra_pred
             mode = ALZHEIMER_DC_L0T_PRED8x8 +
-                   (!(h->left_samples_available & 0x8000)) +
+                   (!(sl->left_samples_available & 0x8000)) +
                    2 * (mode == DC_128_PRED8x8);
         }
     }
@@ -230,12 +221,12 @@
     return mode;
 }
 
-const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
+const uint8_t *ff_h264_decode_nal(H264Context *h, H264SliceContext *sl,
+                                  const uint8_t *src,
                                   int *dst_length, int *consumed, int length)
 {
     int i, si, di;
     uint8_t *dst;
-    int bufidx;
 
     // src[0]&0x80; // forbidden bit
     h->nal_ref_idc   = src[0] >> 5;
@@ -291,11 +282,8 @@
     }
 #endif
 
-    // use second escape buffer for inter data
-    bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
-
-    av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
-    dst = h->rbsp_buffer[bufidx];
+    av_fast_padded_malloc(&sl->rbsp_buffer, &sl->rbsp_buffer_size, length+MAX_MBPAIR_SIZE);
+    dst = sl->rbsp_buffer;
 
     if (!dst)
         return NULL;
@@ -365,7 +353,6 @@
 void ff_h264_free_tables(H264Context *h, int free_rbsp)
 {
     int i;
-    H264Context *hx;
 
     av_freep(&h->intra4x4_pred_mode);
     av_freep(&h->chroma_pred_mode_table);
@@ -398,29 +385,28 @@
 
     h->cur_pic_ptr = NULL;
 
-    for (i = 0; i < H264_MAX_THREADS; i++) {
-        hx = h->thread_context[i];
-        if (!hx)
-            continue;
-        av_freep(&hx->top_borders[1]);
-        av_freep(&hx->top_borders[0]);
-        av_freep(&hx->bipred_scratchpad);
-        av_freep(&hx->edge_emu_buffer);
-        av_freep(&hx->dc_val_base);
-        av_freep(&hx->er.mb_index2xy);
-        av_freep(&hx->er.error_status_table);
-        av_freep(&hx->er.er_temp_buffer);
-        av_freep(&hx->er.mbintra_table);
-        av_freep(&hx->er.mbskip_table);
+    for (i = 0; i < h->nb_slice_ctx; i++) {
+        H264SliceContext *sl = &h->slice_ctx[i];
+
+        av_freep(&sl->dc_val_base);
+        av_freep(&sl->er.mb_index2xy);
+        av_freep(&sl->er.error_status_table);
+        av_freep(&sl->er.er_temp_buffer);
+
+        av_freep(&sl->bipred_scratchpad);
+        av_freep(&sl->edge_emu_buffer);
+        av_freep(&sl->top_borders[0]);
+        av_freep(&sl->top_borders[1]);
+
+        sl->bipred_scratchpad_allocated = 0;
+        sl->edge_emu_buffer_allocated   = 0;
+        sl->top_borders_allocated[0]    = 0;
+        sl->top_borders_allocated[1]    = 0;
 
         if (free_rbsp) {
-            av_freep(&hx->rbsp_buffer[1]);
-            av_freep(&hx->rbsp_buffer[0]);
-            hx->rbsp_buffer_size[0] = 0;
-            hx->rbsp_buffer_size[1] = 0;
+            av_freep(&sl->rbsp_buffer);
+            sl->rbsp_buffer_size            = 0;
         }
-        if (i)
-            av_freep(&h->thread_context[i]);
     }
 }
 
@@ -432,6 +418,8 @@
 
     FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
                       row_mb_num, 8 * sizeof(uint8_t), fail)
+    h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
+
     FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
                       big_mb_num * 48 * sizeof(uint8_t), fail)
     FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
@@ -444,6 +432,9 @@
                       row_mb_num, 16 * sizeof(uint8_t), fail);
     FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[1],
                       row_mb_num, 16 * sizeof(uint8_t), fail);
+    h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
+    h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
+
     FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
                       4 * big_mb_num * sizeof(uint8_t), fail);
     FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
@@ -467,7 +458,7 @@
         }
 
     if (!h->dequant4_coeff[0])
-        h264_init_dequant_tables(h);
+        ff_h264_init_dequant_tables(h);
 
     if (!h->DPB) {
         h->DPB = av_mallocz_array(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
@@ -489,26 +480,21 @@
  * Init context
  * Allocate buffers which are not shared amongst multiple threads.
  */
-int ff_h264_context_init(H264Context *h)
+int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
 {
-    ERContext *er = &h->er;
+    ERContext *er = &sl->er;
     int mb_array_size = h->mb_height * h->mb_stride;
     int y_size  = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
     int c_size  = h->mb_stride * (h->mb_height + 1);
     int yc_size = y_size + 2   * c_size;
     int x, y, i;
 
-    FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->top_borders[0],
-                      h->mb_width, 16 * 3 * sizeof(uint8_t) * 2, fail)
-    FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->top_borders[1],
-                      h->mb_width, 16 * 3 * sizeof(uint8_t) * 2, fail)
-
-    h->ref_cache[0][scan8[5]  + 1] =
-    h->ref_cache[0][scan8[7]  + 1] =
-    h->ref_cache[0][scan8[13] + 1] =
-    h->ref_cache[1][scan8[5]  + 1] =
-    h->ref_cache[1][scan8[7]  + 1] =
-    h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
+    sl->ref_cache[0][scan8[5]  + 1] =
+    sl->ref_cache[0][scan8[7]  + 1] =
+    sl->ref_cache[0][scan8[13] + 1] =
+    sl->ref_cache[1][scan8[5]  + 1] =
+    sl->ref_cache[1][scan8[7]  + 1] =
+    sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
 
     if (CONFIG_ERROR_RESILIENCE) {
         /* init ER */
@@ -537,21 +523,16 @@
         FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
                           mb_array_size * sizeof(uint8_t), fail);
 
-        FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
-        memset(er->mbintra_table, 1, mb_array_size);
-
-        FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
-
         FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
                          h->mb_height * h->mb_stride, fail);
 
-        FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base,
+        FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
                           yc_size * sizeof(int16_t), fail);
-        er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
-        er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
+        er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
+        er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
         er->dc_val[2] = er->dc_val[1] + c_size;
         for (i = 0; i < yc_size; i++)
-            h->dc_val_base[i] = 1024;
+            sl->dc_val_base[i] = 1024;
     }
 
     return 0;
@@ -673,7 +654,16 @@
     h->pixel_shift        = 0;
     h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
 
-    h->thread_context[0] = h;
+    h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ?  H264_MAX_THREADS : 1;
+    h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
+    if (!h->slice_ctx) {
+        h->nb_slice_ctx = 0;
+        return AVERROR(ENOMEM);
+    }
+
+    for (i = 0; i < h->nb_slice_ctx; i++)
+        h->slice_ctx[i].h264 = h;
+
     h->outputed_poc      = h->next_outputed_poc = INT_MIN;
     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
         h->last_pocs[i] = INT_MIN;
@@ -716,16 +706,24 @@
 static int decode_init_thread_copy(AVCodecContext *avctx)
 {
     H264Context *h = avctx->priv_data;
+    int i;
 
     if (!avctx->internal->is_copy)
         return 0;
     memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
     memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
 
-    h->rbsp_buffer[0]      = NULL;
-    h->rbsp_buffer[1]      = NULL;
-    h->rbsp_buffer_size[0] = 0;
-    h->rbsp_buffer_size[1] = 0;
+    h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ?  H264_MAX_THREADS : 1;
+    h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
+    if (!h->slice_ctx) {
+        h->nb_slice_ctx = 0;
+        return AVERROR(ENOMEM);
+    }
+
+    for (i = 0; i < h->nb_slice_ctx; i++)
+        h->slice_ctx[i].h264 = h;
+
+    h->avctx               = avctx;
     h->context_initialized = 0;
 
     return 0;
@@ -979,75 +977,75 @@
         ff_thread_finish_setup(h->avctx);
 }
 
-int ff_pred_weight_table(H264Context *h)
+int ff_pred_weight_table(H264Context *h, H264SliceContext *sl)
 {
     int list, i;
     int luma_def, chroma_def;
 
-    h->use_weight             = 0;
-    h->use_weight_chroma      = 0;
-    h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
+    sl->use_weight             = 0;
+    sl->use_weight_chroma      = 0;
+    sl->luma_log2_weight_denom = get_ue_golomb(&sl->gb);
     if (h->sps.chroma_format_idc)
-        h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
+        sl->chroma_log2_weight_denom = get_ue_golomb(&sl->gb);
 
-    if (h->luma_log2_weight_denom > 7U) {
-        av_log(h->avctx, AV_LOG_ERROR, "luma_log2_weight_denom %d is out of range\n", h->luma_log2_weight_denom);
-        h->luma_log2_weight_denom = 0;
+    if (sl->luma_log2_weight_denom > 7U) {
+        av_log(h->avctx, AV_LOG_ERROR, "luma_log2_weight_denom %d is out of range\n", sl->luma_log2_weight_denom);
+        sl->luma_log2_weight_denom = 0;
     }
-    if (h->chroma_log2_weight_denom > 7U) {
-        av_log(h->avctx, AV_LOG_ERROR, "chroma_log2_weight_denom %d is out of range\n", h->chroma_log2_weight_denom);
-        h->chroma_log2_weight_denom = 0;
+    if (sl->chroma_log2_weight_denom > 7U) {
+        av_log(h->avctx, AV_LOG_ERROR, "chroma_log2_weight_denom %d is out of range\n", sl->chroma_log2_weight_denom);
+        sl->chroma_log2_weight_denom = 0;
     }
 
-    luma_def   = 1 << h->luma_log2_weight_denom;
-    chroma_def = 1 << h->chroma_log2_weight_denom;
+    luma_def   = 1 << sl->luma_log2_weight_denom;
+    chroma_def = 1 << sl->chroma_log2_weight_denom;
 
     for (list = 0; list < 2; list++) {
-        h->luma_weight_flag[list]   = 0;
-        h->chroma_weight_flag[list] = 0;
-        for (i = 0; i < h->ref_count[list]; i++) {
+        sl->luma_weight_flag[list]   = 0;
+        sl->chroma_weight_flag[list] = 0;
+        for (i = 0; i < sl->ref_count[list]; i++) {
             int luma_weight_flag, chroma_weight_flag;
 
-            luma_weight_flag = get_bits1(&h->gb);
+            luma_weight_flag = get_bits1(&sl->gb);
             if (luma_weight_flag) {
-                h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
-                h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
-                if (h->luma_weight[i][list][0] != luma_def ||
-                    h->luma_weight[i][list][1] != 0) {
-                    h->use_weight             = 1;
-                    h->luma_weight_flag[list] = 1;
+                sl->luma_weight[i][list][0] = get_se_golomb(&sl->gb);
+                sl->luma_weight[i][list][1] = get_se_golomb(&sl->gb);
+                if (sl->luma_weight[i][list][0] != luma_def ||
+                    sl->luma_weight[i][list][1] != 0) {
+                    sl->use_weight             = 1;
+                    sl->luma_weight_flag[list] = 1;
                 }
             } else {
-                h->luma_weight[i][list][0] = luma_def;
-                h->luma_weight[i][list][1] = 0;
+                sl->luma_weight[i][list][0] = luma_def;
+                sl->luma_weight[i][list][1] = 0;
             }
 
             if (h->sps.chroma_format_idc) {
-                chroma_weight_flag = get_bits1(&h->gb);
+                chroma_weight_flag = get_bits1(&sl->gb);
                 if (chroma_weight_flag) {
                     int j;
                     for (j = 0; j < 2; j++) {
-                        h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
-                        h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
-                        if (h->chroma_weight[i][list][j][0] != chroma_def ||
-                            h->chroma_weight[i][list][j][1] != 0) {
-                            h->use_weight_chroma        = 1;
-                            h->chroma_weight_flag[list] = 1;
+                        sl->chroma_weight[i][list][j][0] = get_se_golomb(&sl->gb);
+                        sl->chroma_weight[i][list][j][1] = get_se_golomb(&sl->gb);
+                        if (sl->chroma_weight[i][list][j][0] != chroma_def ||
+                            sl->chroma_weight[i][list][j][1] != 0) {
+                            sl->use_weight_chroma        = 1;
+                            sl->chroma_weight_flag[list] = 1;
                         }
                     }
                 } else {
                     int j;
                     for (j = 0; j < 2; j++) {
-                        h->chroma_weight[i][list][j][0] = chroma_def;
-                        h->chroma_weight[i][list][j][1] = 0;
+                        sl->chroma_weight[i][list][j][0] = chroma_def;
+                        sl->chroma_weight[i][list][j][1] = 0;
                     }
                 }
             }
         }
-        if (h->slice_type_nos != AV_PICTURE_TYPE_B)
+        if (sl->slice_type_nos != AV_PICTURE_TYPE_B)
             break;
     }
-    h->use_weight = h->use_weight || h->use_weight_chroma;
+    sl->use_weight = sl->use_weight || sl->use_weight_chroma;
     return 0;
 }
 
@@ -1083,13 +1081,16 @@
                 h->delayed_pic[j++] = h->delayed_pic[i];
         h->delayed_pic[j] = NULL;
     }
+    ff_h264_unref_picture(h, &h->last_pic_for_ec);
+
     h->first_field = 0;
     ff_h264_reset_sei(h);
     h->recovery_frame = -1;
     h->frame_recovered = 0;
-    h->list_count = 0;
     h->current_slice = 0;
     h->mmco_reset = 1;
+    for (i = 0; i < h->nb_slice_ctx; i++)
+        h->slice_ctx[i].list_count = 0;
 }
 
 /* forget old pics after a seek */
@@ -1108,7 +1109,7 @@
     h->cur_pic_ptr = NULL;
     ff_h264_unref_picture(h, &h->cur_pic);
 
-    h->mb_x = h->mb_y = 0;
+    h->mb_y = 0;
 
     ff_h264_free_tables(h, 1);
     h->context_initialized = 0;
@@ -1266,7 +1267,7 @@
     return 0;
 }
 
-int ff_set_ref_count(H264Context *h)
+int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
 {
     int ref_count[2], list_count;
     int num_ref_idx_active_override_flag;
@@ -1275,18 +1276,18 @@
     ref_count[0] = h->pps.ref_count[0];
     ref_count[1] = h->pps.ref_count[1];
 
-    if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
+    if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
         unsigned max[2];
         max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
 
-        if (h->slice_type_nos == AV_PICTURE_TYPE_B)
-            h->direct_spatial_mv_pred = get_bits1(&h->gb);
-        num_ref_idx_active_override_flag = get_bits1(&h->gb);
+        if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
+            sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
+        num_ref_idx_active_override_flag = get_bits1(&sl->gb);
 
         if (num_ref_idx_active_override_flag) {
-            ref_count[0] = get_ue_golomb(&h->gb) + 1;
-            if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
-                ref_count[1] = get_ue_golomb(&h->gb) + 1;
+            ref_count[0] = get_ue_golomb(&sl->gb) + 1;
+            if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
+                ref_count[1] = get_ue_golomb(&sl->gb) + 1;
             } else
                 // full range is spec-ok in this case, even for frames
                 ref_count[1] = 1;
@@ -1294,12 +1295,12 @@
 
         if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
             av_log(h->avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", ref_count[0]-1, max[0], ref_count[1]-1, max[1]);
-            h->ref_count[0] = h->ref_count[1] = 0;
-            h->list_count   = 0;
+            sl->ref_count[0] = sl->ref_count[1] = 0;
+            sl->list_count   = 0;
             return AVERROR_INVALIDDATA;
         }
 
-        if (h->slice_type_nos == AV_PICTURE_TYPE_B)
+        if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
             list_count = 2;
         else
             list_count = 1;
@@ -1308,12 +1309,12 @@
         ref_count[0] = ref_count[1] = 0;
     }
 
-    if (list_count != h->list_count ||
-        ref_count[0] != h->ref_count[0] ||
-        ref_count[1] != h->ref_count[1]) {
-        h->ref_count[0] = ref_count[0];
-        h->ref_count[1] = ref_count[1];
-        h->list_count   = list_count;
+    if (list_count   != sl->list_count   ||
+        ref_count[0] != sl->ref_count[0] ||
+        ref_count[1] != sl->ref_count[1]) {
+        sl->ref_count[0] = ref_count[0];
+        sl->ref_count[1] = ref_count[1];
+        sl->list_count   = list_count;
         return 1;
     }
 
@@ -1350,6 +1351,7 @@
     int first_slice = 0;
 
     while(1) {
+        GetBitContext gb;
         int nalsize = 0;
         int dst_length, bit_length, consumed;
         const uint8_t *ptr;
@@ -1367,7 +1369,7 @@
                 continue;
         }
 
-        ptr = ff_h264_decode_nal(h, buf + buf_index, &dst_length, &consumed,
+        ptr = ff_h264_decode_nal(h, &h->slice_ctx[0], buf + buf_index, &dst_length, &consumed,
                                  next_avc - buf_index);
 
         if (!ptr || dst_length < 0)
@@ -1391,8 +1393,8 @@
         case NAL_DPA:
         case NAL_IDR_SLICE:
         case NAL_SLICE:
-            init_get_bits(&h->gb, ptr, bit_length);
-            if (!get_ue_golomb(&h->gb) ||
+            init_get_bits(&gb, ptr, bit_length);
+            if (!get_ue_golomb(&gb) ||
                 !first_slice ||
                 first_slice != h->nal_unit_type)
                 nals_needed = nal_index;
@@ -1408,7 +1410,7 @@
                             int parse_extradata)
 {
     AVCodecContext *const avctx = h->avctx;
-    H264Context *hx; ///< thread context
+    H264SliceContext *sl;
     int buf_index;
     unsigned context_count;
     int next_avc;
@@ -1465,9 +1467,9 @@
                     continue;
             }
 
-            hx = h->thread_context[context_count];
+            sl = &h->slice_ctx[context_count];
 
-            ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
+            ptr = ff_h264_decode_nal(h, sl, buf + buf_index, &dst_length,
                                      &consumed, next_avc - buf_index);
             if (!ptr || dst_length < 0) {
                 ret = -1;
@@ -1480,7 +1482,7 @@
             if (h->avctx->debug & FF_DEBUG_STARTCODE)
                 av_log(h->avctx, AV_LOG_DEBUG,
                        "NAL %d/%d at %d/%d length %d\n",
-                       hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length);
+                       h->nal_unit_type, h->nal_ref_idc, buf_index, buf_size, dst_length);
 
             if (h->is_avc && (nalsize != consumed) && nalsize)
                 av_log(h->avctx, AV_LOG_DEBUG,
@@ -1496,14 +1498,14 @@
                 continue;
 
 again:
-            if (   !(avctx->active_thread_type & FF_THREAD_FRAME)
-                || nals_needed >= nal_index)
+            if (   (!(avctx->active_thread_type & FF_THREAD_FRAME) || nals_needed >= nal_index)
+                && !h->current_slice)
                 h->au_pps_id = -1;
             /* Ignore per frame NAL unit type during extradata
              * parsing. Decoding slices is not possible in codec init
              * with frame-mt */
             if (parse_extradata) {
-                switch (hx->nal_unit_type) {
+                switch (h->nal_unit_type) {
                 case NAL_IDR_SLICE:
                 case NAL_SLICE:
                 case NAL_DPA:
@@ -1511,16 +1513,16 @@
                 case NAL_DPC:
                     av_log(h->avctx, AV_LOG_WARNING,
                            "Ignoring NAL %d in global header/extradata\n",
-                           hx->nal_unit_type);
+                           h->nal_unit_type);
                     // fall through to next case
                 case NAL_AUXILIARY_SLICE:
-                    hx->nal_unit_type = NAL_FF_IGNORE;
+                    h->nal_unit_type = NAL_FF_IGNORE;
                 }
             }
 
             err = 0;
 
-            switch (hx->nal_unit_type) {
+            switch (h->nal_unit_type) {
             case NAL_IDR_SLICE:
                 if ((ptr[0] & 0xFC) == 0x98) {
                     av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
@@ -1539,15 +1541,13 @@
                 idr_cleared = 1;
                 h->has_recovery_point = 1;
             case NAL_SLICE:
-                init_get_bits(&hx->gb, ptr, bit_length);
-                hx->intra_gb_ptr      =
-                hx->inter_gb_ptr      = &hx->gb;
+                init_get_bits(&sl->gb, ptr, bit_length);
 
-                if ((err = ff_h264_decode_slice_header(hx, h)))
+                if ((err = ff_h264_decode_slice_header(h, sl)))
                     break;
 
                 if (h->sei_recovery_frame_cnt >= 0) {
-                    if (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I)
+                    if (h->frame_num != h->sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
                         h->valid_recovery_point = 1;
 
                     if (   h->recovery_frame < 0
@@ -1561,16 +1561,16 @@
                 }
 
                 h->cur_pic_ptr->f.key_frame |=
-                    (hx->nal_unit_type == NAL_IDR_SLICE);
+                    (h->nal_unit_type == NAL_IDR_SLICE);
 
-                if (hx->nal_unit_type == NAL_IDR_SLICE ||
+                if (h->nal_unit_type == NAL_IDR_SLICE ||
                     h->recovery_frame == h->frame_num) {
                     h->recovery_frame         = -1;
                     h->cur_pic_ptr->recovered = 1;
                 }
                 // If we have an IDR, all frames after it in decoded order are
                 // "recovered".
-                if (hx->nal_unit_type == NAL_IDR_SLICE)
+                if (h->nal_unit_type == NAL_IDR_SLICE)
                     h->frame_recovered |= FRAME_RECOVERED_IDR;
                 h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
                 h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
@@ -1592,7 +1592,7 @@
                         ff_vdpau_h264_picture_start(h);
                 }
 
-                if (hx->redundant_pic_count == 0) {
+                if (sl->redundant_pic_count == 0) {
                     if (avctx->hwaccel) {
                         ret = avctx->hwaccel->decode_slice(avctx,
                                                            &buf[buf_index - consumed],
@@ -1656,7 +1656,7 @@
                 break;
             default:
                 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
-                       hx->nal_unit_type, bit_length);
+                       h->nal_unit_type, bit_length);
             }
 
             if (context_count == h->max_contexts) {
@@ -1669,15 +1669,12 @@
             if (err < 0 || err == SLICE_SKIPED) {
                 if (err < 0)
                     av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
-                h->ref_count[0] = h->ref_count[1] = h->list_count = 0;
+                sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
             } else if (err == SLICE_SINGLETHREAD) {
-                /* Slice could not be decoded in parallel mode, copy down
-                 * NAL unit stuff to context 0 and restart. Note that
-                 * rbsp_buffer is not transferred, but since we no longer
+                /* Slice could not be decoded in parallel mode, restart. Note
+                 * that rbsp_buffer is not transferred, but since we no longer
                  * run in parallel mode this should not be an issue. */
-                h->nal_unit_type = hx->nal_unit_type;
-                h->nal_ref_idc   = hx->nal_ref_idc;
-                hx               = h;
+                sl               = &h->slice_ctx[0];
                 goto again;
             }
         }
@@ -1842,7 +1839,7 @@
         if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
             decode_postinit(h, 1);
 
-        ff_h264_field_end(h, 0);
+        ff_h264_field_end(h, &h->slice_ctx[0], 0);
 
         /* Wait for second field. */
         *got_frame = 0;
@@ -1879,7 +1876,7 @@
                 return ret;
             *got_frame = 1;
             if (CONFIG_MPEGVIDEO) {
-                ff_print_debug_info2(h->avctx, pict, h->er.mbskip_table,
+                ff_print_debug_info2(h->avctx, pict, NULL,
                                     h->next_output_pic->mb_type,
                                     h->next_output_pic->qscale_table,
                                     h->next_output_pic->motion_val,
@@ -1889,7 +1886,7 @@
         }
     }
 
-    assert(pict->buf[0] || !*got_frame);
+    av_assert0(pict->buf[0] || !*got_frame);
 
     ff_h264_unref_picture(h, &h->last_pic_for_ec);
 
@@ -1902,6 +1899,9 @@
 
     ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
 
+    av_freep(&h->slice_ctx);
+    h->nb_slice_ctx = 0;
+
     for (i = 0; i < MAX_SPS_COUNT; i++)
         av_freep(h->sps_buffers + i);
 
diff --git a/libavcodec/h264.h b/libavcodec/h264.h
index bf74f9c..868d285 100644
--- a/libavcodec/h264.h
+++ b/libavcodec/h264.h
@@ -333,50 +333,58 @@
     int crop_top;
 } H264Picture;
 
-/**
- * H264Context
- */
-typedef struct H264Context {
-    AVClass *av_class;
-    AVCodecContext *avctx;
-    VideoDSPContext vdsp;
-    H264DSPContext h264dsp;
-    H264ChromaContext h264chroma;
-    H264QpelContext h264qpel;
+typedef struct H264Ref {
+    uint8_t *data[3];
+    int linesize[3];
+
+    int reference;
+    int poc;
+    int pic_id;
+
+    H264Picture *parent;
+} H264Ref;
+
+typedef struct H264SliceContext {
+    struct H264Context *h264;
     GetBitContext gb;
     ERContext er;
 
-    H264Picture *DPB;
-    H264Picture *cur_pic_ptr;
-    H264Picture cur_pic;
-    H264Picture last_pic_for_ec;
-
-    int pixel_shift;    ///< 0 for 8-bit H264, 1 for high-bit-depth H264
-    int chroma_qp[2];   // QPc
-
-    int qp_thresh;      ///< QP threshold to skip loopfilter
-
-    /* coded dimensions -- 16 * mb w/h */
-    int width, height;
-    ptrdiff_t linesize, uvlinesize;
-    int chroma_x_shift, chroma_y_shift;
+    int slice_num;
+    int slice_type;
+    int slice_type_nos;         ///< S free slice type (SI/SP are remapped to I/P)
+    int slice_type_fixed;
 
     int qscale;
-    int droppable;
-    int coded_picture_number;
-    int low_delay;
+    int chroma_qp[2];   // QPc
+    int qp_thresh;      ///< QP threshold to skip loopfilter
+    int last_qscale_diff;
 
-    int context_initialized;
-    int flags;
-    int workaround_bugs;
+    // deblock
+    int deblocking_filter;          ///< disable_deblocking_filter_idc with 1 <-> 0
+    int slice_alpha_c0_offset;
+    int slice_beta_offset;
+
+    // Weighted pred stuff
+    int use_weight;
+    int use_weight_chroma;
+    int luma_log2_weight_denom;
+    int chroma_log2_weight_denom;
+    int luma_weight_flag[2];    ///< 7.4.3.2 luma_weight_lX_flag
+    int chroma_weight_flag[2];  ///< 7.4.3.2 chroma_weight_lX_flag
+    // The following 2 can be changed to int8_t but that causes 10cpu cycles speedloss
+    int luma_weight[48][2][2];
+    int chroma_weight[48][2][2][2];
+    int implicit_weight[48][48][2];
 
     int prev_mb_skipped;
     int next_mb_skipped;
 
-    // prediction stuff
     int chroma_pred_mode;
     int intra16x16_pred_mode;
 
+    int8_t intra4x4_pred_mode_cache[5 * 8];
+    int8_t(*intra4x4_pred_mode);
+
     int topleft_mb_xy;
     int top_mb_xy;
     int topright_mb_xy;
@@ -390,14 +398,64 @@
     const uint8_t *left_block;
     int topleft_partition;
 
-    int8_t intra4x4_pred_mode_cache[5 * 8];
-    int8_t(*intra4x4_pred_mode);
-    H264PredContext hpc;
     unsigned int topleft_samples_available;
     unsigned int top_samples_available;
     unsigned int topright_samples_available;
     unsigned int left_samples_available;
+
+    ptrdiff_t linesize, uvlinesize;
+    ptrdiff_t mb_linesize;  ///< may be equal to s->linesize or s->linesize * 2, for mbaff
+    ptrdiff_t mb_uvlinesize;
+
+    int mb_x, mb_y;
+    int mb_xy;
+    int resync_mb_x;
+    int resync_mb_y;
+    int mb_skip_run;
+    int is_complex;
+
+    int mb_field_decoding_flag;
+    int mb_mbaff;               ///< mb_aff_frame && mb_field_decoding_flag
+
+    int redundant_pic_count;
+
+    /**
+     * number of neighbors (top and/or left) that used 8x8 dct
+     */
+    int neighbor_transform_size;
+
+    int direct_spatial_mv_pred;
+    int col_parity;
+    int col_fieldoff;
+
+    int cbp;
+    int top_cbp;
+    int left_cbp;
+
+    int dist_scale_factor[32];
+    int dist_scale_factor_field[2][32];
+    int map_col_to_list0[2][16 + 32];
+    int map_col_to_list0_field[2][2][16 + 32];
+
+    /**
+     * num_ref_idx_l0/1_active_minus1 + 1
+     */
+    unsigned int ref_count[2];          ///< counts frames or fields, depending on current mb mode
+    unsigned int list_count;
+    H264Ref ref_list[2][48];        /**< 0..15: frame refs, 16..47: mbaff field refs.
+                                         *   Reordered version of default_ref_list
+                                         *   according to picture reordering in slice header */
+    int ref2frm[MAX_SLICES][2][64];     ///< reference to frame number lists, used in the loop filter, the first 2 are for -2,-1
+
+    const uint8_t *intra_pcm_ptr;
+    int16_t *dc_val_base;
+
+    uint8_t *bipred_scratchpad;
+    uint8_t *edge_emu_buffer;
     uint8_t (*top_borders[2])[(16 * 3) * 2];
+    int bipred_scratchpad_allocated;
+    int edge_emu_buffer_allocated;
+    int top_borders_allocated[2];
 
     /**
      * non zero coeff count cache.
@@ -405,20 +463,78 @@
      */
     DECLARE_ALIGNED(8, uint8_t, non_zero_count_cache)[15 * 8];
 
-    uint8_t (*non_zero_count)[48];
-
     /**
      * Motion vector cache.
      */
     DECLARE_ALIGNED(16, int16_t, mv_cache)[2][5 * 8][2];
-    DECLARE_ALIGNED(8, int8_t, ref_cache)[2][5 * 8];
-#define LIST_NOT_USED -1 // FIXME rename?
-#define PART_NOT_AVAILABLE -2
+    DECLARE_ALIGNED(8,  int8_t, ref_cache)[2][5 * 8];
+    DECLARE_ALIGNED(16, uint8_t, mvd_cache)[2][5 * 8][2];
+    uint8_t direct_cache[5 * 8];
+
+    DECLARE_ALIGNED(8, uint16_t, sub_mb_type)[4];
+
+    ///< as a dct coefficient is int32_t in high depth, we need to reserve twice the space.
+    DECLARE_ALIGNED(16, int16_t, mb)[16 * 48 * 2];
+    DECLARE_ALIGNED(16, int16_t, mb_luma_dc)[3][16 * 2];
+    ///< as mb is addressed by scantable[i] and scantable is uint8_t we can either
+    ///< check that i is not too large or ensure that there is some unused stuff after mb
+    int16_t mb_padding[256 * 2];
+
+    uint8_t (*mvd_table[2])[2];
 
     /**
-     * number of neighbors (top and/or left) that used 8x8 dct
+     * Cabac
      */
-    int neighbor_transform_size;
+    CABACContext cabac;
+    uint8_t cabac_state[1024];
+    int cabac_init_idc;
+
+    // rbsp buffer used for this slice
+    uint8_t *rbsp_buffer;
+    unsigned int rbsp_buffer_size;
+} H264SliceContext;
+
+/**
+ * H264Context
+ */
+typedef struct H264Context {
+    AVClass *av_class;
+    AVCodecContext *avctx;
+    VideoDSPContext vdsp;
+    H264DSPContext h264dsp;
+    H264ChromaContext h264chroma;
+    H264QpelContext h264qpel;
+    GetBitContext gb;
+
+    H264Picture *DPB;
+    H264Picture *cur_pic_ptr;
+    H264Picture cur_pic;
+    H264Picture last_pic_for_ec;
+
+    H264SliceContext *slice_ctx;
+    int            nb_slice_ctx;
+
+    int pixel_shift;    ///< 0 for 8-bit H264, 1 for high-bit-depth H264
+
+    /* coded dimensions -- 16 * mb w/h */
+    int width, height;
+    int chroma_x_shift, chroma_y_shift;
+
+    int droppable;
+    int coded_picture_number;
+    int low_delay;
+
+    int context_initialized;
+    int flags;
+    int workaround_bugs;
+
+    int8_t(*intra4x4_pred_mode);
+    H264PredContext hpc;
+
+    uint8_t (*non_zero_count)[48];
+
+#define LIST_NOT_USED -1 // FIXME rename?
+#define PART_NOT_AVAILABLE -2
 
     /**
      * block_offset[ 0..23] for frame macroblocks
@@ -430,8 +546,6 @@
     uint32_t *mb2br_xy;
     int b_stride;       // FIXME use s->b4_stride
 
-    ptrdiff_t mb_linesize;  ///< may be equal to s->linesize or s->linesize * 2, for mbaff
-    ptrdiff_t mb_uvlinesize;
 
     unsigned current_sps_id; ///< id of the current SPS
     SPS sps; ///< current sps
@@ -444,79 +558,22 @@
     uint32_t(*dequant4_coeff[6])[16];
     uint32_t(*dequant8_coeff[6])[64];
 
-    int slice_num;
     uint16_t *slice_table;      ///< slice_table_base + 2*mb_stride + 1
-    int slice_type;
-    int slice_type_nos;         ///< S free slice type (SI/SP are remapped to I/P)
-    int slice_type_fixed;
 
     // interlacing specific flags
     int mb_aff_frame;
-    int mb_field_decoding_flag;
-    int mb_mbaff;               ///< mb_aff_frame && mb_field_decoding_flag
     int picture_structure;
     int first_field;
 
-    DECLARE_ALIGNED(8, uint16_t, sub_mb_type)[4];
-
-    // Weighted pred stuff
-    int use_weight;
-    int use_weight_chroma;
-    int luma_log2_weight_denom;
-    int chroma_log2_weight_denom;
-    // The following 2 can be changed to int8_t but that causes 10cpu cycles speedloss
-    int luma_weight[48][2][2];
-    int chroma_weight[48][2][2][2];
-    int implicit_weight[48][48][2];
-
-    int direct_spatial_mv_pred;
-    int col_parity;
-    int col_fieldoff;
-    int dist_scale_factor[32];
-    int dist_scale_factor_field[2][32];
-    int map_col_to_list0[2][16 + 32];
-    int map_col_to_list0_field[2][2][16 + 32];
-
-    /**
-     * num_ref_idx_l0/1_active_minus1 + 1
-     */
-    unsigned int ref_count[2];          ///< counts frames or fields, depending on current mb mode
-    unsigned int list_count;
     uint8_t *list_counts;               ///< Array of list_count per MB specifying the slice type
-    H264Picture ref_list[2][48];        /**< 0..15: frame refs, 16..47: mbaff field refs.
-                                         *   Reordered version of default_ref_list
-                                         *   according to picture reordering in slice header */
-    int ref2frm[MAX_SLICES][2][64];     ///< reference to frame number lists, used in the loop filter, the first 2 are for -2,-1
-
-    // data partitioning
-    GetBitContext intra_gb;
-    GetBitContext inter_gb;
-    GetBitContext *intra_gb_ptr;
-    GetBitContext *inter_gb_ptr;
-
-    const uint8_t *intra_pcm_ptr;
-    DECLARE_ALIGNED(16, int16_t, mb)[16 * 48 * 2]; ///< as a dct coefficient is int32_t in high depth, we need to reserve twice the space.
-    DECLARE_ALIGNED(16, int16_t, mb_luma_dc)[3][16 * 2];
-    int16_t mb_padding[256 * 2];        ///< as mb is addressed by scantable[i] and scantable is uint8_t we can either check that i is not too large or ensure that there is some unused stuff after mb
-
-    /**
-     * Cabac
-     */
-    CABACContext cabac;
-    uint8_t cabac_state[1024];
 
     /* 0x100 -> non null luma_dc, 0x80/0x40 -> non null chroma_dc (cb/cr), 0x?0 -> chroma_cbp(0, 1, 2), 0x0? luma_cbp */
     uint16_t *cbp_table;
-    int cbp;
-    int top_cbp;
-    int left_cbp;
+
     /* chroma_pred_mode for i4x4 or i16x16, else 0 */
     uint8_t *chroma_pred_mode_table;
-    int last_qscale_diff;
     uint8_t (*mvd_table[2])[2];
-    DECLARE_ALIGNED(16, uint8_t, mvd_cache)[2][5 * 8][2];
     uint8_t *direct_table;
-    uint8_t direct_cache[5 * 8];
 
     uint8_t zigzag_scan[16];
     uint8_t zigzag_scan8x8[64];
@@ -533,29 +590,16 @@
 
     int x264_build;
 
-    int mb_x, mb_y;
-    int resync_mb_x;
-    int resync_mb_y;
-    int mb_skip_run;
+    int mb_y;
     int mb_height, mb_width;
     int mb_stride;
     int mb_num;
-    int mb_xy;
-
-    int is_complex;
-
-    // deblock
-    int deblocking_filter;          ///< disable_deblocking_filter_idc with 1 <-> 0
-    int slice_alpha_c0_offset;
-    int slice_beta_offset;
 
     // =============================================================
     // Things below are not used in the MB or more inner code
 
     int nal_ref_idc;
     int nal_unit_type;
-    uint8_t *rbsp_buffer[2];
-    unsigned int rbsp_buffer_size[2];
 
     /**
      * Used to parse AVC variant of h264
@@ -595,9 +639,7 @@
      */
     int max_pic_num;
 
-    int redundant_pic_count;
-
-    H264Picture default_ref_list[2][32]; ///< base reference list for all slices of a coded picture
+    H264Ref default_ref_list[2][32]; ///< base reference list for all slices of a coded picture
     H264Picture *short_ref[32];
     H264Picture *long_ref[32];
     H264Picture *delayed_pic[MAX_DELAYED_PIC_COUNT + 2]; // FIXME size?
@@ -616,14 +658,10 @@
     int long_ref_count;     ///< number of actual long term references
     int short_ref_count;    ///< number of actual short term references
 
-    int cabac_init_idc;
-
     /**
      * @name Members for slice based multithreading
      * @{
      */
-    struct H264Context *thread_context[H264_MAX_THREADS];
-
     /**
      * current slice number, used to initialize slice_num of each thread/context
      */
@@ -737,23 +775,17 @@
 
     int missing_fields;
 
-    int luma_weight_flag[2];    ///< 7.4.3.2 luma_weight_lX_flag
-    int chroma_weight_flag[2];  ///< 7.4.3.2 chroma_weight_lX_flag
 
     // Timestamp stuff
     int sei_buffering_period_present;   ///< Buffering period SEI flag
     int initial_cpb_removal_delay[32];  ///< Initial timestamps for CPBs
 
     int cur_chroma_format_idc;
-    uint8_t *bipred_scratchpad;
-
     int16_t slice_row[MAX_SLICES]; ///< to detect when MAX_SLICES is too low
 
     uint8_t parse_history[6];
     int parse_history_count;
     int parse_last_mb;
-    uint8_t *edge_emu_buffer;
-    int16_t *dc_val_base;
 
     AVBufferPool *qscale_table_pool;
     AVBufferPool *mb_type_pool;
@@ -796,7 +828,7 @@
  *                   or a decode rbsp tailing?
  * @return decoded bytes, might be src+1 if no escapes
  */
-const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
+const uint8_t *ff_h264_decode_nal(H264Context *h, H264SliceContext *sl, const uint8_t *src,
                                   int *dst_length, int *consumed, int length);
 
 /**
@@ -808,7 +840,7 @@
 /**
  * Reconstruct bitstream slice_type.
  */
-int ff_h264_get_slice_type(const H264Context *h);
+int ff_h264_get_slice_type(const H264SliceContext *sl);
 
 /**
  * Allocate tables.
@@ -819,10 +851,10 @@
 /**
  * Fill the default_ref_list.
  */
-int ff_h264_fill_default_ref_list(H264Context *h);
+int ff_h264_fill_default_ref_list(H264Context *h, H264SliceContext *sl);
 
-int ff_h264_decode_ref_pic_list_reordering(H264Context *h);
-void ff_h264_fill_mbaff_ref_list(H264Context *h);
+int ff_h264_decode_ref_pic_list_reordering(H264Context *h, H264SliceContext *sl);
+void ff_h264_fill_mbaff_ref_list(H264Context *h, H264SliceContext *sl);
 void ff_h264_remove_all_refs(H264Context *h);
 
 /**
@@ -839,15 +871,16 @@
  * Check if the top & left blocks are available if needed & change the
  * dc mode so it only uses the available blocks.
  */
-int ff_h264_check_intra4x4_pred_mode(H264Context *h);
+int ff_h264_check_intra4x4_pred_mode(const H264Context *h, H264SliceContext *sl);
 
 /**
  * Check if the top & left blocks are available if needed & change the
  * dc mode so it only uses the available blocks.
  */
-int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma);
+int ff_h264_check_intra_pred_mode(const H264Context *h, H264SliceContext *sl,
+                                  int mode, int is_chroma);
 
-void ff_h264_hl_decode_mb(H264Context *h);
+void ff_h264_hl_decode_mb(const H264Context *h, H264SliceContext *sl);
 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size);
 int ff_h264_decode_init(AVCodecContext *avctx);
 void ff_h264_decode_init_vlc(void);
@@ -856,26 +889,27 @@
  * Decode a macroblock
  * @return 0 if OK, ER_AC_ERROR / ER_DC_ERROR / ER_MV_ERROR on error
  */
-int ff_h264_decode_mb_cavlc(H264Context *h);
+int ff_h264_decode_mb_cavlc(const H264Context *h, H264SliceContext *sl);
 
 /**
  * Decode a CABAC coded macroblock
  * @return 0 if OK, ER_AC_ERROR / ER_DC_ERROR / ER_MV_ERROR on error
  */
-int ff_h264_decode_mb_cabac(H264Context *h);
+int ff_h264_decode_mb_cabac(const H264Context *h, H264SliceContext *sl);
 
-void ff_h264_init_cabac_states(H264Context *h);
+void ff_h264_init_cabac_states(const H264Context *h, H264SliceContext *sl);
 
-void h264_init_dequant_tables(H264Context *h);
+void ff_h264_init_dequant_tables(H264Context *h);
 
-void ff_h264_direct_dist_scale_factor(H264Context *const h);
-void ff_h264_direct_ref_list_init(H264Context *const h);
-void ff_h264_pred_direct_motion(H264Context *const h, int *mb_type);
+void ff_h264_direct_dist_scale_factor(const H264Context *const h, H264SliceContext *sl);
+void ff_h264_direct_ref_list_init(const H264Context *const h, H264SliceContext *sl);
+void ff_h264_pred_direct_motion(const H264Context *const h, H264SliceContext *sl,
+                                int *mb_type);
 
-void ff_h264_filter_mb_fast(H264Context *h, int mb_x, int mb_y,
+void ff_h264_filter_mb_fast(const H264Context *h, H264SliceContext *sl, int mb_x, int mb_y,
                             uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr,
                             unsigned int linesize, unsigned int uvlinesize);
-void ff_h264_filter_mb(H264Context *h, int mb_x, int mb_y,
+void ff_h264_filter_mb(const H264Context *h, H264SliceContext *sl, int mb_x, int mb_y,
                        uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr,
                        unsigned int linesize, unsigned int uvlinesize);
 
@@ -942,7 +976,7 @@
     0 +  0 * 8, 0 +  5 * 8, 0 + 10 * 8
 };
 
-static av_always_inline uint32_t pack16to32(int a, int b)
+static av_always_inline uint32_t pack16to32(unsigned a, unsigned b)
 {
 #if HAVE_BIGENDIAN
     return (b & 0xFFFF) + (a << 16);
@@ -951,7 +985,7 @@
 #endif
 }
 
-static av_always_inline uint16_t pack8to16(int a, int b)
+static av_always_inline uint16_t pack8to16(unsigned a, unsigned b)
 {
 #if HAVE_BIGENDIAN
     return (b & 0xFF) + (a << 8);
@@ -963,7 +997,7 @@
 /**
  * Get the chroma qp.
  */
-static av_always_inline int get_chroma_qp(H264Context *h, int t, int qscale)
+static av_always_inline int get_chroma_qp(const H264Context *h, int t, int qscale)
 {
     return h->pps.chroma_qp_table[t][qscale];
 }
@@ -971,11 +1005,12 @@
 /**
  * Get the predicted intra4x4 prediction mode.
  */
-static av_always_inline int pred_intra_mode(H264Context *h, int n)
+static av_always_inline int pred_intra_mode(const H264Context *h,
+                                            H264SliceContext *sl, int n)
 {
     const int index8 = scan8[n];
-    const int left   = h->intra4x4_pred_mode_cache[index8 - 1];
-    const int top    = h->intra4x4_pred_mode_cache[index8 - 8];
+    const int left   = sl->intra4x4_pred_mode_cache[index8 - 1];
+    const int top    = sl->intra4x4_pred_mode_cache[index8 - 8];
     const int min    = FFMIN(left, top);
 
     tprintf(h->avctx, "mode:%d %d min:%d\n", left, top, min);
@@ -986,10 +1021,11 @@
         return min;
 }
 
-static av_always_inline void write_back_intra_pred_mode(H264Context *h)
+static av_always_inline void write_back_intra_pred_mode(const H264Context *h,
+                                                        H264SliceContext *sl)
 {
-    int8_t *i4x4       = h->intra4x4_pred_mode + h->mb2br_xy[h->mb_xy];
-    int8_t *i4x4_cache = h->intra4x4_pred_mode_cache;
+    int8_t *i4x4       = sl->intra4x4_pred_mode + h->mb2br_xy[sl->mb_xy];
+    int8_t *i4x4_cache = sl->intra4x4_pred_mode_cache;
 
     AV_COPY32(i4x4, i4x4_cache + 4 + 8 * 4);
     i4x4[4] = i4x4_cache[7 + 8 * 3];
@@ -997,11 +1033,12 @@
     i4x4[6] = i4x4_cache[7 + 8 * 1];
 }
 
-static av_always_inline void write_back_non_zero_count(H264Context *h)
+static av_always_inline void write_back_non_zero_count(const H264Context *h,
+                                                       H264SliceContext *sl)
 {
-    const int mb_xy    = h->mb_xy;
+    const int mb_xy    = sl->mb_xy;
     uint8_t *nnz       = h->non_zero_count[mb_xy];
-    uint8_t *nnz_cache = h->non_zero_count_cache;
+    uint8_t *nnz_cache = sl->non_zero_count_cache;
 
     AV_COPY32(&nnz[ 0], &nnz_cache[4 + 8 * 1]);
     AV_COPY32(&nnz[ 4], &nnz_cache[4 + 8 * 2]);
@@ -1020,21 +1057,22 @@
     }
 }
 
-static av_always_inline void write_back_motion_list(H264Context *h,
+static av_always_inline void write_back_motion_list(const H264Context *h,
+                                                    H264SliceContext *sl,
                                                     int b_stride,
                                                     int b_xy, int b8_xy,
                                                     int mb_type, int list)
 {
     int16_t(*mv_dst)[2] = &h->cur_pic.motion_val[list][b_xy];
-    int16_t(*mv_src)[2] = &h->mv_cache[list][scan8[0]];
+    int16_t(*mv_src)[2] = &sl->mv_cache[list][scan8[0]];
     AV_COPY128(mv_dst + 0 * b_stride, mv_src + 8 * 0);
     AV_COPY128(mv_dst + 1 * b_stride, mv_src + 8 * 1);
     AV_COPY128(mv_dst + 2 * b_stride, mv_src + 8 * 2);
     AV_COPY128(mv_dst + 3 * b_stride, mv_src + 8 * 3);
     if (CABAC(h)) {
-        uint8_t (*mvd_dst)[2] = &h->mvd_table[list][FMO ? 8 * h->mb_xy
-                                                        : h->mb2br_xy[h->mb_xy]];
-        uint8_t(*mvd_src)[2]  = &h->mvd_cache[list][scan8[0]];
+        uint8_t (*mvd_dst)[2] = &sl->mvd_table[list][FMO ? 8 * sl->mb_xy
+                                                        : h->mb2br_xy[sl->mb_xy]];
+        uint8_t(*mvd_src)[2]  = &sl->mvd_cache[list][scan8[0]];
         if (IS_SKIP(mb_type)) {
             AV_ZERO128(mvd_dst);
         } else {
@@ -1047,7 +1085,7 @@
 
     {
         int8_t *ref_index = &h->cur_pic.ref_index[list][b8_xy];
-        int8_t *ref_cache = h->ref_cache[list];
+        int8_t *ref_cache = sl->ref_cache[list];
         ref_index[0 + 0 * 2] = ref_cache[scan8[0]];
         ref_index[1 + 0 * 2] = ref_cache[scan8[4]];
         ref_index[0 + 1 * 2] = ref_cache[scan8[8]];
@@ -1055,39 +1093,41 @@
     }
 }
 
-static av_always_inline void write_back_motion(H264Context *h, int mb_type)
+static av_always_inline void write_back_motion(const H264Context *h,
+                                               H264SliceContext *sl,
+                                               int mb_type)
 {
     const int b_stride      = h->b_stride;
-    const int b_xy  = 4 * h->mb_x + 4 * h->mb_y * h->b_stride; // try mb2b(8)_xy
-    const int b8_xy = 4 * h->mb_xy;
+    const int b_xy  = 4 * sl->mb_x + 4 * sl->mb_y * h->b_stride; // try mb2b(8)_xy
+    const int b8_xy = 4 * sl->mb_xy;
 
     if (USES_LIST(mb_type, 0)) {
-        write_back_motion_list(h, b_stride, b_xy, b8_xy, mb_type, 0);
+        write_back_motion_list(h, sl, b_stride, b_xy, b8_xy, mb_type, 0);
     } else {
         fill_rectangle(&h->cur_pic.ref_index[0][b8_xy],
                        2, 2, 2, (uint8_t)LIST_NOT_USED, 1);
     }
     if (USES_LIST(mb_type, 1))
-        write_back_motion_list(h, b_stride, b_xy, b8_xy, mb_type, 1);
+        write_back_motion_list(h, sl, b_stride, b_xy, b8_xy, mb_type, 1);
 
-    if (h->slice_type_nos == AV_PICTURE_TYPE_B && CABAC(h)) {
+    if (sl->slice_type_nos == AV_PICTURE_TYPE_B && CABAC(h)) {
         if (IS_8X8(mb_type)) {
-            uint8_t *direct_table = &h->direct_table[4 * h->mb_xy];
-            direct_table[1] = h->sub_mb_type[1] >> 1;
-            direct_table[2] = h->sub_mb_type[2] >> 1;
-            direct_table[3] = h->sub_mb_type[3] >> 1;
+            uint8_t *direct_table = &h->direct_table[4 * sl->mb_xy];
+            direct_table[1] = sl->sub_mb_type[1] >> 1;
+            direct_table[2] = sl->sub_mb_type[2] >> 1;
+            direct_table[3] = sl->sub_mb_type[3] >> 1;
         }
     }
 }
 
-static av_always_inline int get_dct8x8_allowed(H264Context *h)
+static av_always_inline int get_dct8x8_allowed(const H264Context *h, H264SliceContext *sl)
 {
     if (h->sps.direct_8x8_inference_flag)
-        return !(AV_RN64A(h->sub_mb_type) &
+        return !(AV_RN64A(sl->sub_mb_type) &
                  ((MB_TYPE_16x8 | MB_TYPE_8x16 | MB_TYPE_8x8) *
                   0x0001000100010001ULL));
     else
-        return !(AV_RN64A(h->sub_mb_type) &
+        return !(AV_RN64A(sl->sub_mb_type) &
                  ((MB_TYPE_16x8 | MB_TYPE_8x16 | MB_TYPE_8x8 | MB_TYPE_DIRECT2) *
                   0x0001000100010001ULL));
 }
@@ -1120,20 +1160,20 @@
     return nalsize;
 }
 
-int ff_h264_field_end(H264Context *h, int in_setup);
+int ff_h264_field_end(H264Context *h, H264SliceContext *sl, int in_setup);
 
 int ff_h264_ref_picture(H264Context *h, H264Picture *dst, H264Picture *src);
 void ff_h264_unref_picture(H264Context *h, H264Picture *pic);
 
-int ff_h264_context_init(H264Context *h);
+int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl);
 int ff_h264_set_parameter_from_sps(H264Context *h);
 
-void ff_h264_draw_horiz_band(H264Context *h, int y, int height);
+void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl, int y, int height);
 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc);
-int ff_pred_weight_table(H264Context *h);
-int ff_set_ref_count(H264Context *h);
+int ff_pred_weight_table(H264Context *h, H264SliceContext *sl);
+int ff_set_ref_count(H264Context *h, H264SliceContext *sl);
 
-int ff_h264_decode_slice_header(H264Context *h, H264Context *h0);
+int ff_h264_decode_slice_header(H264Context *h, H264SliceContext *sl);
 #define SLICE_SINGLETHREAD 1
 #define SLICE_SKIPED 2
 
diff --git a/libavcodec/h264_cabac.c b/libavcodec/h264_cabac.c
index bf72ec4..150be20 100644
--- a/libavcodec/h264_cabac.c
+++ b/libavcodec/h264_cabac.c
@@ -1260,13 +1260,14 @@
     }
 };
 
-void ff_h264_init_cabac_states(H264Context *h) {
+void ff_h264_init_cabac_states(const H264Context *h, H264SliceContext *sl)
+{
     int i;
     const int8_t (*tab)[2];
-    const int slice_qp = av_clip(h->qscale - 6*(h->sps.bit_depth_luma-8), 0, 51);
+    const int slice_qp = av_clip(sl->qscale - 6*(h->sps.bit_depth_luma-8), 0, 51);
 
-    if( h->slice_type_nos == AV_PICTURE_TYPE_I ) tab = cabac_context_init_I;
-    else                                 tab = cabac_context_init_PB[h->cabac_init_idc];
+    if (sl->slice_type_nos == AV_PICTURE_TYPE_I) tab = cabac_context_init_I;
+    else                                 tab = cabac_context_init_PB[sl->cabac_init_idc];
 
     /* calculate pre-state */
     for( i= 0; i < 1024; i++ ) {
@@ -1276,52 +1277,57 @@
         if(pre > 124)
             pre= 124 + (pre&1);
 
-        h->cabac_state[i] =  pre;
+        sl->cabac_state[i] =  pre;
     }
 }
 
-static int decode_cabac_field_decoding_flag(H264Context *h) {
-    const long mbb_xy = h->mb_xy - 2L*h->mb_stride;
+static int decode_cabac_field_decoding_flag(const H264Context *h, H264SliceContext *sl)
+{
+    const int mbb_xy = sl->mb_xy - 2*h->mb_stride;
 
     unsigned long ctx = 0;
 
-    ctx += h->mb_field_decoding_flag & !!h->mb_x; //for FMO:(s->current_picture.mb_type[mba_xy] >> 7) & (h->slice_table[mba_xy] == h->slice_num);
-    ctx += (h->cur_pic.mb_type[mbb_xy] >> 7) & (h->slice_table[mbb_xy] == h->slice_num);
+    ctx += sl->mb_field_decoding_flag & !!sl->mb_x; //for FMO:(s->current_picture.mb_type[mba_xy] >> 7) & (h->slice_table[mba_xy] == h->slice_num);
+    ctx += (h->cur_pic.mb_type[mbb_xy] >> 7) & (h->slice_table[mbb_xy] == sl->slice_num);
 
-    return get_cabac_noinline( &h->cabac, &(h->cabac_state+70)[ctx] );
+    return get_cabac_noinline( &sl->cabac, &(sl->cabac_state+70)[ctx] );
 }
 
-static int decode_cabac_intra_mb_type(H264Context *h, int ctx_base, int intra_slice) {
-    uint8_t *state= &h->cabac_state[ctx_base];
+static int decode_cabac_intra_mb_type(H264SliceContext *sl,
+                                      int ctx_base, int intra_slice)
+{
+    uint8_t *state= &sl->cabac_state[ctx_base];
     int mb_type;
 
     if(intra_slice){
         int ctx=0;
-        if( h->left_type[LTOP] & (MB_TYPE_INTRA16x16|MB_TYPE_INTRA_PCM))
+        if (sl->left_type[LTOP] & (MB_TYPE_INTRA16x16|MB_TYPE_INTRA_PCM))
             ctx++;
-        if( h->top_type        & (MB_TYPE_INTRA16x16|MB_TYPE_INTRA_PCM))
+        if (sl->top_type        & (MB_TYPE_INTRA16x16|MB_TYPE_INTRA_PCM))
             ctx++;
-        if( get_cabac_noinline( &h->cabac, &state[ctx] ) == 0 )
+        if( get_cabac_noinline( &sl->cabac, &state[ctx] ) == 0 )
             return 0;   /* I4x4 */
         state += 2;
     }else{
-        if( get_cabac_noinline( &h->cabac, state ) == 0 )
+        if( get_cabac_noinline( &sl->cabac, state ) == 0 )
             return 0;   /* I4x4 */
     }
 
-    if( get_cabac_terminate( &h->cabac ) )
+    if( get_cabac_terminate( &sl->cabac ) )
         return 25;  /* PCM */
 
     mb_type = 1; /* I16x16 */
-    mb_type += 12 * get_cabac_noinline( &h->cabac, &state[1] ); /* cbp_luma != 0 */
-    if( get_cabac_noinline( &h->cabac, &state[2] ) ) /* cbp_chroma */
-        mb_type += 4 + 4 * get_cabac_noinline( &h->cabac, &state[2+intra_slice] );
-    mb_type += 2 * get_cabac_noinline( &h->cabac, &state[3+intra_slice] );
-    mb_type += 1 * get_cabac_noinline( &h->cabac, &state[3+2*intra_slice] );
+    mb_type += 12 * get_cabac_noinline( &sl->cabac, &state[1] ); /* cbp_luma != 0 */
+    if( get_cabac_noinline( &sl->cabac, &state[2] ) ) /* cbp_chroma */
+        mb_type += 4 + 4 * get_cabac_noinline( &sl->cabac, &state[2+intra_slice] );
+    mb_type += 2 * get_cabac_noinline( &sl->cabac, &state[3+intra_slice] );
+    mb_type += 1 * get_cabac_noinline( &sl->cabac, &state[3+2*intra_slice] );
     return mb_type;
 }
 
-static int decode_cabac_mb_skip( H264Context *h, int mb_x, int mb_y ) {
+static int decode_cabac_mb_skip(const H264Context *h, H264SliceContext *sl,
+                                int mb_x, int mb_y)
+{
     int mba_xy, mbb_xy;
     int ctx = 0;
 
@@ -1329,141 +1335,148 @@
         int mb_xy = mb_x + (mb_y&~1)*h->mb_stride;
         mba_xy = mb_xy - 1;
         if( (mb_y&1)
-            && h->slice_table[mba_xy] == h->slice_num
-            && MB_FIELD(h) == !!IS_INTERLACED( h->cur_pic.mb_type[mba_xy] ) )
+            && h->slice_table[mba_xy] == sl->slice_num
+            && MB_FIELD(sl) == !!IS_INTERLACED( h->cur_pic.mb_type[mba_xy] ) )
             mba_xy += h->mb_stride;
-        if (MB_FIELD(h)) {
+        if (MB_FIELD(sl)) {
             mbb_xy = mb_xy - h->mb_stride;
             if( !(mb_y&1)
-                && h->slice_table[mbb_xy] == h->slice_num
+                && h->slice_table[mbb_xy] == sl->slice_num
                 && IS_INTERLACED( h->cur_pic.mb_type[mbb_xy] ) )
                 mbb_xy -= h->mb_stride;
         }else
             mbb_xy = mb_x + (mb_y-1)*h->mb_stride;
     }else{
-        int mb_xy = h->mb_xy;
+        int mb_xy = sl->mb_xy;
         mba_xy = mb_xy - 1;
         mbb_xy = mb_xy - (h->mb_stride << FIELD_PICTURE(h));
     }
 
-    if( h->slice_table[mba_xy] == h->slice_num && !IS_SKIP(h->cur_pic.mb_type[mba_xy] ))
+    if( h->slice_table[mba_xy] == sl->slice_num && !IS_SKIP(h->cur_pic.mb_type[mba_xy] ))
         ctx++;
-    if( h->slice_table[mbb_xy] == h->slice_num && !IS_SKIP(h->cur_pic.mb_type[mbb_xy] ))
+    if( h->slice_table[mbb_xy] == sl->slice_num && !IS_SKIP(h->cur_pic.mb_type[mbb_xy] ))
         ctx++;
 
-    if( h->slice_type_nos == AV_PICTURE_TYPE_B )
+    if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
         ctx += 13;
-    return get_cabac_noinline( &h->cabac, &h->cabac_state[11+ctx] );
+    return get_cabac_noinline( &sl->cabac, &sl->cabac_state[11+ctx] );
 }
 
-static int decode_cabac_mb_intra4x4_pred_mode( H264Context *h, int pred_mode ) {
+static int decode_cabac_mb_intra4x4_pred_mode(H264SliceContext *sl, int pred_mode)
+{
     int mode = 0;
 
-    if( get_cabac( &h->cabac, &h->cabac_state[68] ) )
+    if( get_cabac( &sl->cabac, &sl->cabac_state[68] ) )
         return pred_mode;
 
-    mode += 1 * get_cabac( &h->cabac, &h->cabac_state[69] );
-    mode += 2 * get_cabac( &h->cabac, &h->cabac_state[69] );
-    mode += 4 * get_cabac( &h->cabac, &h->cabac_state[69] );
+    mode += 1 * get_cabac( &sl->cabac, &sl->cabac_state[69] );
+    mode += 2 * get_cabac( &sl->cabac, &sl->cabac_state[69] );
+    mode += 4 * get_cabac( &sl->cabac, &sl->cabac_state[69] );
 
     return mode + ( mode >= pred_mode );
 }
 
-static int decode_cabac_mb_chroma_pre_mode( H264Context *h) {
-    const int mba_xy = h->left_mb_xy[0];
-    const int mbb_xy = h->top_mb_xy;
+static int decode_cabac_mb_chroma_pre_mode(const H264Context *h, H264SliceContext *sl)
+{
+    const int mba_xy = sl->left_mb_xy[0];
+    const int mbb_xy = sl->top_mb_xy;
 
     int ctx = 0;
 
     /* No need to test for IS_INTRA4x4 and IS_INTRA16x16, as we set chroma_pred_mode_table to 0 */
-    if( h->left_type[LTOP] && h->chroma_pred_mode_table[mba_xy] != 0 )
+    if (sl->left_type[LTOP] && h->chroma_pred_mode_table[mba_xy] != 0)
         ctx++;
 
-    if( h->top_type        && h->chroma_pred_mode_table[mbb_xy] != 0 )
+    if (sl->top_type        && h->chroma_pred_mode_table[mbb_xy] != 0)
         ctx++;
 
-    if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+ctx] ) == 0 )
+    if( get_cabac_noinline( &sl->cabac, &sl->cabac_state[64+ctx] ) == 0 )
         return 0;
 
-    if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+3] ) == 0 )
+    if( get_cabac_noinline( &sl->cabac, &sl->cabac_state[64+3] ) == 0 )
         return 1;
-    if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+3] ) == 0 )
+    if( get_cabac_noinline( &sl->cabac, &sl->cabac_state[64+3] ) == 0 )
         return 2;
     else
         return 3;
 }
 
-static int decode_cabac_mb_cbp_luma( H264Context *h) {
+static int decode_cabac_mb_cbp_luma(H264SliceContext *sl)
+{
     int cbp_b, cbp_a, ctx, cbp = 0;
 
-    cbp_a = h->left_cbp;
-    cbp_b = h->top_cbp;
+    cbp_a = sl->left_cbp;
+    cbp_b = sl->top_cbp;
 
     ctx = !(cbp_a & 0x02) + 2 * !(cbp_b & 0x04);
-    cbp += get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]);
+    cbp += get_cabac_noinline(&sl->cabac, &sl->cabac_state[73 + ctx]);
     ctx = !(cbp   & 0x01) + 2 * !(cbp_b & 0x08);
-    cbp += get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 1;
+    cbp += get_cabac_noinline(&sl->cabac, &sl->cabac_state[73 + ctx]) << 1;
     ctx = !(cbp_a & 0x08) + 2 * !(cbp   & 0x01);
-    cbp += get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 2;
+    cbp += get_cabac_noinline(&sl->cabac, &sl->cabac_state[73 + ctx]) << 2;
     ctx = !(cbp   & 0x04) + 2 * !(cbp   & 0x02);
-    cbp += get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 3;
+    cbp += get_cabac_noinline(&sl->cabac, &sl->cabac_state[73 + ctx]) << 3;
     return cbp;
 }
-static int decode_cabac_mb_cbp_chroma( H264Context *h) {
+static int decode_cabac_mb_cbp_chroma(H264SliceContext *sl)
+{
     int ctx;
     int cbp_a, cbp_b;
 
-    cbp_a = (h->left_cbp>>4)&0x03;
-    cbp_b = (h-> top_cbp>>4)&0x03;
+    cbp_a = (sl->left_cbp>>4)&0x03;
+    cbp_b = (sl-> top_cbp>>4)&0x03;
 
     ctx = 0;
     if( cbp_a > 0 ) ctx++;
     if( cbp_b > 0 ) ctx += 2;
-    if( get_cabac_noinline( &h->cabac, &h->cabac_state[77 + ctx] ) == 0 )
+    if( get_cabac_noinline( &sl->cabac, &sl->cabac_state[77 + ctx] ) == 0 )
         return 0;
 
     ctx = 4;
     if( cbp_a == 2 ) ctx++;
     if( cbp_b == 2 ) ctx += 2;
-    return 1 + get_cabac_noinline( &h->cabac, &h->cabac_state[77 + ctx] );
+    return 1 + get_cabac_noinline( &sl->cabac, &sl->cabac_state[77 + ctx] );
 }
 
-static int decode_cabac_p_mb_sub_type( H264Context *h ) {
-    if( get_cabac( &h->cabac, &h->cabac_state[21] ) )
+static int decode_cabac_p_mb_sub_type(H264SliceContext *sl)
+{
+    if( get_cabac( &sl->cabac, &sl->cabac_state[21] ) )
         return 0;   /* 8x8 */
-    if( !get_cabac( &h->cabac, &h->cabac_state[22] ) )
+    if( !get_cabac( &sl->cabac, &sl->cabac_state[22] ) )
         return 1;   /* 8x4 */
-    if( get_cabac( &h->cabac, &h->cabac_state[23] ) )
+    if( get_cabac( &sl->cabac, &sl->cabac_state[23] ) )
         return 2;   /* 4x8 */
     return 3;       /* 4x4 */
 }
-static int decode_cabac_b_mb_sub_type( H264Context *h ) {
+static int decode_cabac_b_mb_sub_type(H264SliceContext *sl)
+{
     int type;
-    if( !get_cabac( &h->cabac, &h->cabac_state[36] ) )
+    if( !get_cabac( &sl->cabac, &sl->cabac_state[36] ) )
         return 0;   /* B_Direct_8x8 */
-    if( !get_cabac( &h->cabac, &h->cabac_state[37] ) )
-        return 1 + get_cabac( &h->cabac, &h->cabac_state[39] ); /* B_L0_8x8, B_L1_8x8 */
+    if( !get_cabac( &sl->cabac, &sl->cabac_state[37] ) )
+        return 1 + get_cabac( &sl->cabac, &sl->cabac_state[39] ); /* B_L0_8x8, B_L1_8x8 */
     type = 3;
-    if( get_cabac( &h->cabac, &h->cabac_state[38] ) ) {
-        if( get_cabac( &h->cabac, &h->cabac_state[39] ) )
-            return 11 + get_cabac( &h->cabac, &h->cabac_state[39] ); /* B_L1_4x4, B_Bi_4x4 */
+    if( get_cabac( &sl->cabac, &sl->cabac_state[38] ) ) {
+        if( get_cabac( &sl->cabac, &sl->cabac_state[39] ) )
+            return 11 + get_cabac( &sl->cabac, &sl->cabac_state[39] ); /* B_L1_4x4, B_Bi_4x4 */
         type += 4;
     }
-    type += 2*get_cabac( &h->cabac, &h->cabac_state[39] );
-    type +=   get_cabac( &h->cabac, &h->cabac_state[39] );
+    type += 2*get_cabac( &sl->cabac, &sl->cabac_state[39] );
+    type +=   get_cabac( &sl->cabac, &sl->cabac_state[39] );
     return type;
 }
 
-static int decode_cabac_mb_ref( H264Context *h, int list, int n ) {
-    int refa = h->ref_cache[list][scan8[n] - 1];
-    int refb = h->ref_cache[list][scan8[n] - 8];
+static int decode_cabac_mb_ref(H264SliceContext *sl, int list, int n)
+{
+    int refa = sl->ref_cache[list][scan8[n] - 1];
+    int refb = sl->ref_cache[list][scan8[n] - 8];
     int ref  = 0;
     int ctx  = 0;
 
-    if( h->slice_type_nos == AV_PICTURE_TYPE_B) {
-        if( refa > 0 && !(h->direct_cache[scan8[n] - 1]&(MB_TYPE_DIRECT2>>1)) )
+    if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
+        if( refa > 0 && !(sl->direct_cache[scan8[n] - 1]&(MB_TYPE_DIRECT2>>1)) )
             ctx++;
-        if( refb > 0 && !(h->direct_cache[scan8[n] - 8]&(MB_TYPE_DIRECT2>>1)) )
+        if( refb > 0 && !(sl->direct_cache[scan8[n] - 8]&(MB_TYPE_DIRECT2>>1)) )
             ctx += 2;
     } else {
         if( refa > 0 )
@@ -1472,7 +1485,7 @@
             ctx += 2;
     }
 
-    while( get_cabac( &h->cabac, &h->cabac_state[54+ctx] ) ) {
+    while( get_cabac( &sl->cabac, &sl->cabac_state[54+ctx] ) ) {
         ref++;
         ctx = (ctx>>2)+4;
         if(ref >= 32 /*h->ref_list[list]*/){
@@ -1482,18 +1495,19 @@
     return ref;
 }
 
-static int decode_cabac_mb_mvd( H264Context *h, int ctxbase, int amvd, int *mvda) {
+static int decode_cabac_mb_mvd(H264SliceContext *sl, int ctxbase, int amvd, int *mvda)
+{
     int mvd;
 
-    if(!get_cabac(&h->cabac, &h->cabac_state[ctxbase+((amvd-3)>>(INT_BIT-1))+((amvd-33)>>(INT_BIT-1))+2])){
-//    if(!get_cabac(&h->cabac, &h->cabac_state[ctxbase+(amvd>2)+(amvd>32)])){
+    if(!get_cabac(&sl->cabac, &sl->cabac_state[ctxbase+((amvd-3)>>(INT_BIT-1))+((amvd-33)>>(INT_BIT-1))+2])){
+//    if(!get_cabac(&sl->cabac, &sl->cabac_state[ctxbase+(amvd>2)+(amvd>32)])){
         *mvda= 0;
         return 0;
     }
 
     mvd= 1;
     ctxbase+= 3;
-    while( mvd < 9 && get_cabac( &h->cabac, &h->cabac_state[ctxbase] ) ) {
+    while( mvd < 9 && get_cabac( &sl->cabac, &sl->cabac_state[ctxbase] ) ) {
         if( mvd < 4 )
             ctxbase++;
         mvd++;
@@ -1501,35 +1515,38 @@
 
     if( mvd >= 9 ) {
         int k = 3;
-        while( get_cabac_bypass( &h->cabac ) ) {
+        while( get_cabac_bypass( &sl->cabac ) ) {
             mvd += 1 << k;
             k++;
             if(k>24){
-                av_log(h->avctx, AV_LOG_ERROR, "overflow in decode_cabac_mb_mvd\n");
+                av_log(sl->h264->avctx, AV_LOG_ERROR, "overflow in decode_cabac_mb_mvd\n");
                 return INT_MIN;
             }
         }
         while( k-- ) {
-            mvd += get_cabac_bypass( &h->cabac )<<k;
+            mvd += get_cabac_bypass( &sl->cabac )<<k;
         }
         *mvda=mvd < 70 ? mvd : 70;
     }else
         *mvda=mvd;
-    return get_cabac_bypass_sign( &h->cabac, -mvd );
+    return get_cabac_bypass_sign( &sl->cabac, -mvd );
 }
 
-#define DECODE_CABAC_MB_MVD( h,  list,  n )\
+#define DECODE_CABAC_MB_MVD(sl, list,  n )\
 {\
-    int amvd0 = h->mvd_cache[list][scan8[n] - 1][0] +\
-                h->mvd_cache[list][scan8[n] - 8][0];\
-    int amvd1 = h->mvd_cache[list][scan8[n] - 1][1] +\
-                h->mvd_cache[list][scan8[n] - 8][1];\
+    int amvd0 = sl->mvd_cache[list][scan8[n] - 1][0] +\
+                sl->mvd_cache[list][scan8[n] - 8][0];\
+    int amvd1 = sl->mvd_cache[list][scan8[n] - 1][1] +\
+                sl->mvd_cache[list][scan8[n] - 8][1];\
 \
-    mx += decode_cabac_mb_mvd( h, 40, amvd0, &mpx );\
-    my += decode_cabac_mb_mvd( h, 47, amvd1, &mpy );\
+    mx += decode_cabac_mb_mvd(sl, 40, amvd0, &mpx);\
+    my += decode_cabac_mb_mvd(sl, 47, amvd1, &mpy);\
 }
 
-static av_always_inline int get_cabac_cbf_ctx( H264Context *h, int cat, int idx, int max_coeff, int is_dc ) {
+static av_always_inline int get_cabac_cbf_ctx(H264SliceContext *sl,
+                                              int cat, int idx, int max_coeff,
+                                              int is_dc)
+{
     int nza, nzb;
     int ctx = 0;
     static const uint16_t base_ctx[14] = {85,89,93,97,101,1012,460,464,468,1016,472,476,480,1020};
@@ -1537,16 +1554,16 @@
     if( is_dc ) {
         if( cat == 3 ) {
             idx -= CHROMA_DC_BLOCK_INDEX;
-            nza = (h->left_cbp>>(6+idx))&0x01;
-            nzb = (h-> top_cbp>>(6+idx))&0x01;
+            nza = (sl->left_cbp>>(6+idx))&0x01;
+            nzb = (sl-> top_cbp>>(6+idx))&0x01;
         } else {
             idx -= LUMA_DC_BLOCK_INDEX;
-            nza = h->left_cbp&(0x100<<idx);
-            nzb = h-> top_cbp&(0x100<<idx);
+            nza = sl->left_cbp&(0x100<<idx);
+            nzb = sl-> top_cbp&(0x100<<idx);
         }
     } else {
-        nza = h->non_zero_count_cache[scan8[idx] - 1];
-        nzb = h->non_zero_count_cache[scan8[idx] - 8];
+        nza = sl->non_zero_count_cache[scan8[idx] - 1];
+        nzb = sl->non_zero_count_cache[scan8[idx] - 8];
     }
 
     if( nza > 0 )
@@ -1559,7 +1576,8 @@
 }
 
 static av_always_inline void
-decode_cabac_residual_internal(H264Context *h, int16_t *block,
+decode_cabac_residual_internal(const H264Context *h, H264SliceContext *sl,
+                               int16_t *block,
                                int cat, int n, const uint8_t *scantable,
                                const uint32_t *qmul, int max_coeff,
                                int is_dc, int chroma422)
@@ -1618,21 +1636,21 @@
 #ifdef CABAC_ON_STACK
 #define CC &cc
     CABACContext cc;
-    cc.range     = h->cabac.range;
-    cc.low       = h->cabac.low;
-    cc.bytestream= h->cabac.bytestream;
+    cc.range     = sl->cabac.range;
+    cc.low       = sl->cabac.low;
+    cc.bytestream= sl->cabac.bytestream;
 #if !UNCHECKED_BITSTREAM_READER || ARCH_AARCH64
-    cc.bytestream_end = h->cabac.bytestream_end;
+    cc.bytestream_end = sl->cabac.bytestream_end;
 #endif
 #else
-#define CC &h->cabac
+#define CC &sl->cabac
 #endif
 
-    significant_coeff_ctx_base = h->cabac_state
-        + significant_coeff_flag_offset[MB_FIELD(h)][cat];
-    last_coeff_ctx_base = h->cabac_state
-        + last_coeff_flag_offset[MB_FIELD(h)][cat];
-    abs_level_m1_ctx_base = h->cabac_state
+    significant_coeff_ctx_base = sl->cabac_state
+        + significant_coeff_flag_offset[MB_FIELD(sl)][cat];
+    last_coeff_ctx_base = sl->cabac_state
+        + last_coeff_flag_offset[MB_FIELD(sl)][cat];
+    abs_level_m1_ctx_base = sl->cabac_state
         + coeff_abs_level_m1_offset[cat];
 
     if( !is_dc && max_coeff == 64 ) {
@@ -1651,7 +1669,7 @@
         if( last == max_coeff -1 ) {\
             index[coeff_count++] = last;\
         }
-        const uint8_t *sig_off = significant_coeff_flag_offset_8x8[MB_FIELD(h)];
+        const uint8_t *sig_off = significant_coeff_flag_offset_8x8[MB_FIELD(sl)];
 #ifdef decode_significance
         coeff_count = decode_significance_8x8(CC, significant_coeff_ctx_base, index,
                                                  last_coeff_ctx_base, sig_off);
@@ -1676,16 +1694,16 @@
 
     if( is_dc ) {
         if( cat == 3 )
-            h->cbp_table[h->mb_xy] |= 0x40 << (n - CHROMA_DC_BLOCK_INDEX);
+            h->cbp_table[sl->mb_xy] |= 0x40 << (n - CHROMA_DC_BLOCK_INDEX);
         else
-            h->cbp_table[h->mb_xy] |= 0x100 << (n - LUMA_DC_BLOCK_INDEX);
-        h->non_zero_count_cache[scan8[n]] = coeff_count;
+            h->cbp_table[sl->mb_xy] |= 0x100 << (n - LUMA_DC_BLOCK_INDEX);
+        sl->non_zero_count_cache[scan8[n]] = coeff_count;
     } else {
         if( max_coeff == 64 )
-            fill_rectangle(&h->non_zero_count_cache[scan8[n]], 2, 2, 8, coeff_count, 1);
+            fill_rectangle(&sl->non_zero_count_cache[scan8[n]], 2, 2, 8, coeff_count, 1);
         else {
             av_assert2( cat == 1 || cat ==  2 || cat ==  4 || cat == 7 || cat == 8 || cat == 11 || cat == 12 );
-            h->non_zero_count_cache[scan8[n]] = coeff_count;
+            sl->non_zero_count_cache[scan8[n]] = coeff_count;
         }
     }
 
@@ -1738,39 +1756,42 @@
         STORE_BLOCK(int16_t)
     }
 #ifdef CABAC_ON_STACK
-            h->cabac.range     = cc.range     ;
-            h->cabac.low       = cc.low       ;
-            h->cabac.bytestream= cc.bytestream;
+            sl->cabac.range     = cc.range     ;
+            sl->cabac.low       = cc.low       ;
+            sl->cabac.bytestream= cc.bytestream;
 #endif
 
 }
 
-static av_noinline void decode_cabac_residual_dc_internal(H264Context *h,
+static av_noinline void decode_cabac_residual_dc_internal(const H264Context *h,
+                                                          H264SliceContext *sl,
                                                           int16_t *block,
                                                           int cat, int n,
                                                           const uint8_t *scantable,
                                                           int max_coeff)
 {
-    decode_cabac_residual_internal(h, block, cat, n, scantable, NULL, max_coeff, 1, 0);
+    decode_cabac_residual_internal(h, sl, block, cat, n, scantable, NULL, max_coeff, 1, 0);
 }
 
-static av_noinline void decode_cabac_residual_dc_internal_422(H264Context *h,
+static av_noinline void decode_cabac_residual_dc_internal_422(const H264Context *h,
+                                                              H264SliceContext *sl,
                                                               int16_t *block,
                                                               int cat, int n,
                                                               const uint8_t *scantable,
                                                               int max_coeff)
 {
-    decode_cabac_residual_internal(h, block, cat, n, scantable, NULL, max_coeff, 1, 1);
+    decode_cabac_residual_internal(h, sl, block, cat, n, scantable, NULL, max_coeff, 1, 1);
 }
 
-static av_noinline void decode_cabac_residual_nondc_internal(H264Context *h,
+static av_noinline void decode_cabac_residual_nondc_internal(const H264Context *h,
+                                                             H264SliceContext *sl,
                                                              int16_t *block,
                                                              int cat, int n,
                                                              const uint8_t *scantable,
                                                              const uint32_t *qmul,
                                                              int max_coeff)
 {
-    decode_cabac_residual_internal(h, block, cat, n, scantable, qmul, max_coeff, 0, 0);
+    decode_cabac_residual_internal(h, sl, block, cat, n, scantable, qmul, max_coeff, 0, 0);
 }
 
 /* cat: 0-> DC 16x16  n = 0
@@ -1785,34 +1806,37 @@
  * because it allows improved constant propagation into get_cabac_cbf_ctx,
  * as well as because most blocks have zero CBFs. */
 
-static av_always_inline void decode_cabac_residual_dc(H264Context *h,
+static av_always_inline void decode_cabac_residual_dc(const H264Context *h,
+                                                      H264SliceContext *sl,
                                                       int16_t *block,
                                                       int cat, int n,
                                                       const uint8_t *scantable,
                                                       int max_coeff)
 {
     /* read coded block flag */
-    if( get_cabac( &h->cabac, &h->cabac_state[get_cabac_cbf_ctx( h, cat, n, max_coeff, 1 ) ] ) == 0 ) {
-        h->non_zero_count_cache[scan8[n]] = 0;
+    if( get_cabac( &sl->cabac, &sl->cabac_state[get_cabac_cbf_ctx(sl, cat, n, max_coeff, 1)]) == 0 ) {
+        sl->non_zero_count_cache[scan8[n]] = 0;
         return;
     }
-    decode_cabac_residual_dc_internal( h, block, cat, n, scantable, max_coeff );
+    decode_cabac_residual_dc_internal(h, sl, block, cat, n, scantable, max_coeff);
 }
 
 static av_always_inline void
-decode_cabac_residual_dc_422(H264Context *h, int16_t *block,
+decode_cabac_residual_dc_422(const H264Context *h, H264SliceContext *sl,
+                             int16_t *block,
                              int cat, int n, const uint8_t *scantable,
                              int max_coeff)
 {
     /* read coded block flag */
-    if (get_cabac(&h->cabac, &h->cabac_state[get_cabac_cbf_ctx(h, cat, n, max_coeff, 1)]) == 0) {
-        h->non_zero_count_cache[scan8[n]] = 0;
+    if (get_cabac(&sl->cabac, &sl->cabac_state[get_cabac_cbf_ctx(sl, cat, n, max_coeff, 1)]) == 0) {
+        sl->non_zero_count_cache[scan8[n]] = 0;
         return;
     }
-    decode_cabac_residual_dc_internal_422(h, block, cat, n, scantable, max_coeff);
+    decode_cabac_residual_dc_internal_422(h, sl, block, cat, n, scantable, max_coeff);
 }
 
-static av_always_inline void decode_cabac_residual_nondc(H264Context *h,
+static av_always_inline void decode_cabac_residual_nondc(const H264Context *h,
+                                                         H264SliceContext *sl,
                                                          int16_t *block,
                                                          int cat, int n,
                                                          const uint8_t *scantable,
@@ -1820,38 +1844,40 @@
                                                          int max_coeff)
 {
     /* read coded block flag */
-    if( (cat != 5 || CHROMA444(h)) && get_cabac( &h->cabac, &h->cabac_state[get_cabac_cbf_ctx( h, cat, n, max_coeff, 0 ) ] ) == 0 ) {
+    if( (cat != 5 || CHROMA444(h)) && get_cabac( &sl->cabac, &sl->cabac_state[get_cabac_cbf_ctx(sl, cat, n, max_coeff, 0)]) == 0) {
         if( max_coeff == 64 ) {
-            fill_rectangle(&h->non_zero_count_cache[scan8[n]], 2, 2, 8, 0, 1);
+            fill_rectangle(&sl->non_zero_count_cache[scan8[n]], 2, 2, 8, 0, 1);
         } else {
-            h->non_zero_count_cache[scan8[n]] = 0;
+            sl->non_zero_count_cache[scan8[n]] = 0;
         }
         return;
     }
-    decode_cabac_residual_nondc_internal( h, block, cat, n, scantable, qmul, max_coeff );
+    decode_cabac_residual_nondc_internal(h, sl, block, cat, n, scantable, qmul, max_coeff);
 }
 
-static av_always_inline void decode_cabac_luma_residual( H264Context *h, const uint8_t *scan, const uint8_t *scan8x8, int pixel_shift, int mb_type, int cbp, int p )
+static av_always_inline void decode_cabac_luma_residual(const H264Context *h, H264SliceContext *sl,
+                                                        const uint8_t *scan, const uint8_t *scan8x8,
+                                                        int pixel_shift, int mb_type, int cbp, int p)
 {
     static const uint8_t ctx_cat[4][3] = {{0,6,10},{1,7,11},{2,8,12},{5,9,13}};
     const uint32_t *qmul;
     int i8x8, i4x4;
-    int qscale = p == 0 ? h->qscale : h->chroma_qp[p-1];
+    int qscale = p == 0 ? sl->qscale : sl->chroma_qp[p - 1];
     if( IS_INTRA16x16( mb_type ) ) {
-        AV_ZERO128(h->mb_luma_dc[p]+0);
-        AV_ZERO128(h->mb_luma_dc[p]+8);
-        AV_ZERO128(h->mb_luma_dc[p]+16);
-        AV_ZERO128(h->mb_luma_dc[p]+24);
-        decode_cabac_residual_dc(h, h->mb_luma_dc[p], ctx_cat[0][p], LUMA_DC_BLOCK_INDEX+p, scan, 16);
+        AV_ZERO128(sl->mb_luma_dc[p]+0);
+        AV_ZERO128(sl->mb_luma_dc[p]+8);
+        AV_ZERO128(sl->mb_luma_dc[p]+16);
+        AV_ZERO128(sl->mb_luma_dc[p]+24);
+        decode_cabac_residual_dc(h, sl, sl->mb_luma_dc[p], ctx_cat[0][p], LUMA_DC_BLOCK_INDEX+p, scan, 16);
 
         if( cbp&15 ) {
             qmul = h->dequant4_coeff[p][qscale];
             for( i4x4 = 0; i4x4 < 16; i4x4++ ) {
                 const int index = 16*p + i4x4;
-                decode_cabac_residual_nondc(h, h->mb + (16*index << pixel_shift), ctx_cat[1][p], index, scan + 1, qmul, 15);
+                decode_cabac_residual_nondc(h, sl, sl->mb + (16*index << pixel_shift), ctx_cat[1][p], index, scan + 1, qmul, 15);
             }
         } else {
-            fill_rectangle(&h->non_zero_count_cache[scan8[16*p]], 4, 4, 8, 0, 1);
+            fill_rectangle(&sl->non_zero_count_cache[scan8[16*p]], 4, 4, 8, 0, 1);
         }
     } else {
         int cqm = (IS_INTRA( mb_type ) ? 0:3) + p;
@@ -1859,19 +1885,19 @@
             if( cbp & (1<<i8x8) ) {
                 if( IS_8x8DCT(mb_type) ) {
                     const int index = 16*p + 4*i8x8;
-                    decode_cabac_residual_nondc(h, h->mb + (16*index << pixel_shift), ctx_cat[3][p], index,
+                    decode_cabac_residual_nondc(h, sl, sl->mb + (16*index << pixel_shift), ctx_cat[3][p], index,
                                                 scan8x8, h->dequant8_coeff[cqm][qscale], 64);
                 } else {
                     qmul = h->dequant4_coeff[cqm][qscale];
                     for( i4x4 = 0; i4x4 < 4; i4x4++ ) {
                         const int index = 16*p + 4*i8x8 + i4x4;
 //START_TIMER
-                        decode_cabac_residual_nondc(h, h->mb + (16*index << pixel_shift), ctx_cat[2][p], index, scan, qmul, 16);
+                        decode_cabac_residual_nondc(h, sl, sl->mb + (16*index << pixel_shift), ctx_cat[2][p], index, scan, qmul, 16);
 //STOP_TIMER("decode_residual")
                     }
                 }
             } else {
-                fill_rectangle(&h->non_zero_count_cache[scan8[4*i8x8+16*p]], 2, 2, 8, 0, 1);
+                fill_rectangle(&sl->non_zero_count_cache[scan8[4*i8x8+16*p]], 2, 2, 8, 0, 1);
             }
         }
     }
@@ -1881,119 +1907,119 @@
  * Decode a macroblock.
  * @return 0 if OK, ER_AC_ERROR / ER_DC_ERROR / ER_MV_ERROR if an error is noticed
  */
-int ff_h264_decode_mb_cabac(H264Context *h) {
+int ff_h264_decode_mb_cabac(const H264Context *h, H264SliceContext *sl)
+{
     int mb_xy;
     int mb_type, partition_count, cbp = 0;
     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 = h->mb_x + h->mb_y*h->mb_stride;
+    mb_xy = sl->mb_xy = sl->mb_x + sl->mb_y*h->mb_stride;
 
-    tprintf(h->avctx, "pic:%d mb:%d/%d\n", h->frame_num, h->mb_x, h->mb_y);
-    if( h->slice_type_nos != AV_PICTURE_TYPE_I ) {
+    tprintf(h->avctx, "pic:%d mb:%d/%d\n", h->frame_num, sl->mb_x, sl->mb_y);
+    if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
         int skip;
         /* a skipped mb needs the aff flag from the following mb */
-        if (FRAME_MBAFF(h) && (h->mb_y & 1) == 1 && h->prev_mb_skipped)
-            skip = h->next_mb_skipped;
+        if (FRAME_MBAFF(h) && (sl->mb_y & 1) == 1 && sl->prev_mb_skipped)
+            skip = sl->next_mb_skipped;
         else
-            skip = decode_cabac_mb_skip( h, h->mb_x, h->mb_y );
+            skip = decode_cabac_mb_skip(h, sl, sl->mb_x, sl->mb_y );
         /* read skip flags */
         if( skip ) {
-            if (FRAME_MBAFF(h) && (h->mb_y & 1) == 0) {
+            if (FRAME_MBAFF(h) && (sl->mb_y & 1) == 0) {
                 h->cur_pic.mb_type[mb_xy] = MB_TYPE_SKIP;
-                h->next_mb_skipped = decode_cabac_mb_skip( h, h->mb_x, h->mb_y+1 );
-                if(!h->next_mb_skipped)
-                    h->mb_mbaff = h->mb_field_decoding_flag = decode_cabac_field_decoding_flag(h);
+                sl->next_mb_skipped = decode_cabac_mb_skip(h, sl, sl->mb_x, sl->mb_y+1 );
+                if(!sl->next_mb_skipped)
+                    sl->mb_mbaff = sl->mb_field_decoding_flag = decode_cabac_field_decoding_flag(h, sl);
             }
 
-            decode_mb_skip(h);
+            decode_mb_skip(h, sl);
 
             h->cbp_table[mb_xy] = 0;
             h->chroma_pred_mode_table[mb_xy] = 0;
-            h->last_qscale_diff = 0;
+            sl->last_qscale_diff = 0;
 
             return 0;
 
         }
     }
     if (FRAME_MBAFF(h)) {
-        if( (h->mb_y&1) == 0 )
-            h->mb_mbaff =
-            h->mb_field_decoding_flag = decode_cabac_field_decoding_flag(h);
+        if ((sl->mb_y & 1) == 0)
+            sl->mb_mbaff =
+            sl->mb_field_decoding_flag = decode_cabac_field_decoding_flag(h, sl);
     }
 
-    h->prev_mb_skipped = 0;
+    sl->prev_mb_skipped = 0;
 
-    fill_decode_neighbors(h, -(MB_FIELD(h)));
+    fill_decode_neighbors(h, sl, -(MB_FIELD(sl)));
 
-    if( h->slice_type_nos == AV_PICTURE_TYPE_B ) {
+    if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
         int ctx = 0;
-        av_assert2(h->slice_type_nos == AV_PICTURE_TYPE_B);
+        av_assert2(sl->slice_type_nos == AV_PICTURE_TYPE_B);
 
-        if( !IS_DIRECT( h->left_type[LTOP]-1 ) )
+        if (!IS_DIRECT(sl->left_type[LTOP] - 1))
             ctx++;
-        if( !IS_DIRECT( h->top_type-1 ) )
+        if (!IS_DIRECT(sl->top_type - 1))
             ctx++;
 
-        if( !get_cabac_noinline( &h->cabac, &h->cabac_state[27+ctx] ) ){
+        if( !get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+ctx] ) ){
             mb_type= 0; /* B_Direct_16x16 */
-        }else if( !get_cabac_noinline( &h->cabac, &h->cabac_state[27+3] ) ) {
-            mb_type= 1 + get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ); /* B_L[01]_16x16 */
+        }else if( !get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+3] ) ) {
+            mb_type= 1 + get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+5] ); /* B_L[01]_16x16 */
         }else{
             int bits;
-            bits = get_cabac_noinline( &h->cabac, &h->cabac_state[27+4] ) << 3;
-            bits+= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ) << 2;
-            bits+= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ) << 1;
-            bits+= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] );
+            bits = get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+4] ) << 3;
+            bits+= get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+5] ) << 2;
+            bits+= get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+5] ) << 1;
+            bits+= get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+5] );
             if( bits < 8 ){
                 mb_type= bits + 3; /* B_Bi_16x16 through B_L1_L0_16x8 */
             }else if( bits == 13 ){
-                mb_type= decode_cabac_intra_mb_type(h, 32, 0);
+                mb_type = decode_cabac_intra_mb_type(sl, 32, 0);
                 goto decode_intra_mb;
             }else if( bits == 14 ){
                 mb_type= 11; /* B_L1_L0_8x16 */
             }else if( bits == 15 ){
                 mb_type= 22; /* B_8x8 */
             }else{
-                bits= ( bits<<1 ) + get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] );
+                bits= ( bits<<1 ) + get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+5] );
                 mb_type= bits - 4; /* B_L0_Bi_* through B_Bi_Bi_* */
             }
         }
             partition_count= b_mb_type_info[mb_type].partition_count;
             mb_type=         b_mb_type_info[mb_type].type;
-    } else if( h->slice_type_nos == AV_PICTURE_TYPE_P ) {
-        if( get_cabac_noinline( &h->cabac, &h->cabac_state[14] ) == 0 ) {
+    } else if (sl->slice_type_nos == AV_PICTURE_TYPE_P) {
+        if( get_cabac_noinline( &sl->cabac, &sl->cabac_state[14] ) == 0 ) {
             /* P-type */
-            if( get_cabac_noinline( &h->cabac, &h->cabac_state[15] ) == 0 ) {
+            if( get_cabac_noinline( &sl->cabac, &sl->cabac_state[15] ) == 0 ) {
                 /* P_L0_D16x16, P_8x8 */
-                mb_type= 3 * get_cabac_noinline( &h->cabac, &h->cabac_state[16] );
+                mb_type= 3 * get_cabac_noinline( &sl->cabac, &sl->cabac_state[16] );
             } else {
                 /* P_L0_D8x16, P_L0_D16x8 */
-                mb_type= 2 - get_cabac_noinline( &h->cabac, &h->cabac_state[17] );
+                mb_type= 2 - get_cabac_noinline( &sl->cabac, &sl->cabac_state[17] );
             }
             partition_count= p_mb_type_info[mb_type].partition_count;
             mb_type=         p_mb_type_info[mb_type].type;
         } else {
-            mb_type= decode_cabac_intra_mb_type(h, 17, 0);
+            mb_type = decode_cabac_intra_mb_type(sl, 17, 0);
             goto decode_intra_mb;
         }
     } else {
-        mb_type= decode_cabac_intra_mb_type(h, 3, 1);
-        if(h->slice_type == AV_PICTURE_TYPE_SI && mb_type)
+        mb_type = decode_cabac_intra_mb_type(sl, 3, 1);
+        if (sl->slice_type == AV_PICTURE_TYPE_SI && mb_type)
             mb_type--;
-        av_assert2(h->slice_type_nos == AV_PICTURE_TYPE_I);
+        av_assert2(sl->slice_type_nos == AV_PICTURE_TYPE_I);
 decode_intra_mb:
         partition_count = 0;
         cbp= i_mb_type_info[mb_type].cbp;
-        h->intra16x16_pred_mode= i_mb_type_info[mb_type].pred_mode;
+        sl->intra16x16_pred_mode = i_mb_type_info[mb_type].pred_mode;
         mb_type= i_mb_type_info[mb_type].type;
     }
-    if(MB_FIELD(h))
+    if (MB_FIELD(sl))
         mb_type |= MB_TYPE_INTERLACED;
 
-    h->slice_table[ mb_xy ]= h->slice_num;
+    h->slice_table[mb_xy] = sl->slice_num;
 
     if(IS_INTRA_PCM(mb_type)) {
         const int mb_size = ff_h264_mb_sizes[h->sps.chroma_format_idc] *
@@ -2003,19 +2029,19 @@
         // We assume these blocks are very rare so we do not optimize it.
         // FIXME The two following lines get the bitstream position in the cabac
         // decode, I think it should be done by a function in cabac.h (or cabac.c).
-        ptr= h->cabac.bytestream;
-        if(h->cabac.low&0x1) ptr--;
+        ptr= sl->cabac.bytestream;
+        if(sl->cabac.low&0x1) ptr--;
         if(CABAC_BITS==16){
-            if(h->cabac.low&0x1FF) ptr--;
+            if(sl->cabac.low&0x1FF) ptr--;
         }
 
         // The pixels are stored in the same order as levels in h->mb array.
-        if ((int) (h->cabac.bytestream_end - ptr) < mb_size)
+        if ((int) (sl->cabac.bytestream_end - ptr) < mb_size)
             return -1;
-        h->intra_pcm_ptr = ptr;
+        sl->intra_pcm_ptr = ptr;
         ptr += mb_size;
 
-        ff_init_cabac_decoder(&h->cabac, ptr, h->cabac.bytestream_end - ptr);
+        ff_init_cabac_decoder(&sl->cabac, ptr, sl->cabac.bytestream_end - ptr);
 
         // All blocks are present
         h->cbp_table[mb_xy] = 0xf7ef;
@@ -2025,85 +2051,83 @@
         // All coeffs are present
         memset(h->non_zero_count[mb_xy], 16, 48);
         h->cur_pic.mb_type[mb_xy] = mb_type;
-        h->last_qscale_diff = 0;
+        sl->last_qscale_diff = 0;
         return 0;
     }
 
-    local_ref_count[0] = h->ref_count[0] << MB_MBAFF(h);
-    local_ref_count[1] = h->ref_count[1] << MB_MBAFF(h);
-
-    fill_decode_caches(h, mb_type);
+    fill_decode_caches(h, sl, mb_type);
 
     if( IS_INTRA( mb_type ) ) {
         int i, pred_mode;
         if( IS_INTRA4x4( mb_type ) ) {
-            if( dct8x8_allowed && get_cabac_noinline( &h->cabac, &h->cabac_state[399 + h->neighbor_transform_size] ) ) {
+            if (dct8x8_allowed && get_cabac_noinline(&sl->cabac, &sl->cabac_state[399 + sl->neighbor_transform_size])) {
                 mb_type |= MB_TYPE_8x8DCT;
                 for( i = 0; i < 16; i+=4 ) {
-                    int pred = pred_intra_mode( h, i );
-                    int mode = decode_cabac_mb_intra4x4_pred_mode( h, pred );
-                    fill_rectangle( &h->intra4x4_pred_mode_cache[ scan8[i] ], 2, 2, 8, mode, 1 );
+                    int pred = pred_intra_mode(h, sl, i);
+                    int mode = decode_cabac_mb_intra4x4_pred_mode(sl, pred);
+                    fill_rectangle(&sl->intra4x4_pred_mode_cache[scan8[i]], 2, 2, 8, mode, 1);
                 }
             } else {
                 for( i = 0; i < 16; i++ ) {
-                    int pred = pred_intra_mode( h, i );
-                    h->intra4x4_pred_mode_cache[ scan8[i] ] = decode_cabac_mb_intra4x4_pred_mode( h, pred );
+                    int pred = pred_intra_mode(h, sl, i);
+                    sl->intra4x4_pred_mode_cache[scan8[i]] = decode_cabac_mb_intra4x4_pred_mode(sl, pred);
 
                     av_dlog(h->avctx, "i4x4 pred=%d mode=%d\n", pred,
-                            h->intra4x4_pred_mode_cache[scan8[i]]);
+                            sl->intra4x4_pred_mode_cache[scan8[i]]);
                 }
             }
-            write_back_intra_pred_mode(h);
-            if( ff_h264_check_intra4x4_pred_mode(h) < 0 ) return -1;
+            write_back_intra_pred_mode(h, sl);
+            if (ff_h264_check_intra4x4_pred_mode(h, sl) < 0 ) return -1;
         } else {
-            h->intra16x16_pred_mode= ff_h264_check_intra_pred_mode( h, h->intra16x16_pred_mode, 0 );
-            if( h->intra16x16_pred_mode < 0 ) return -1;
+            sl->intra16x16_pred_mode = ff_h264_check_intra_pred_mode(h, sl, sl->intra16x16_pred_mode, 0);
+            if (sl->intra16x16_pred_mode < 0) return -1;
         }
         if(decode_chroma){
             h->chroma_pred_mode_table[mb_xy] =
-            pred_mode                        = decode_cabac_mb_chroma_pre_mode( h );
+            pred_mode                        = decode_cabac_mb_chroma_pre_mode(h, sl);
 
-            pred_mode= ff_h264_check_intra_pred_mode( h, pred_mode, 1 );
+            pred_mode= ff_h264_check_intra_pred_mode(h, sl, pred_mode, 1 );
             if( pred_mode < 0 ) return -1;
-            h->chroma_pred_mode= pred_mode;
+            sl->chroma_pred_mode = pred_mode;
         } else {
-            h->chroma_pred_mode= DC_128_PRED8x8;
+            sl->chroma_pred_mode = DC_128_PRED8x8;
         }
     } else if( partition_count == 4 ) {
         int i, j, sub_partition_count[4], list, ref[2][4];
 
-        if( h->slice_type_nos == AV_PICTURE_TYPE_B ) {
+        if (sl->slice_type_nos == AV_PICTURE_TYPE_B ) {
             for( i = 0; i < 4; i++ ) {
-                h->sub_mb_type[i] = decode_cabac_b_mb_sub_type( h );
-                sub_partition_count[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
-                h->sub_mb_type[i]=      b_sub_mb_type_info[ h->sub_mb_type[i] ].type;
+                sl->sub_mb_type[i] = decode_cabac_b_mb_sub_type(sl);
+                sub_partition_count[i] = b_sub_mb_type_info[sl->sub_mb_type[i]].partition_count;
+                sl->sub_mb_type[i]     = b_sub_mb_type_info[sl->sub_mb_type[i]].type;
             }
-            if( IS_DIRECT(h->sub_mb_type[0] | h->sub_mb_type[1] |
-                          h->sub_mb_type[2] | h->sub_mb_type[3]) ) {
-                ff_h264_pred_direct_motion(h, &mb_type);
-                h->ref_cache[0][scan8[4]] =
-                h->ref_cache[1][scan8[4]] =
-                h->ref_cache[0][scan8[12]] =
-                h->ref_cache[1][scan8[12]] = PART_NOT_AVAILABLE;
+            if (IS_DIRECT(sl->sub_mb_type[0] | sl->sub_mb_type[1] |
+                          sl->sub_mb_type[2] | sl->sub_mb_type[3])) {
+                ff_h264_pred_direct_motion(h, sl, &mb_type);
+                sl->ref_cache[0][scan8[4]] =
+                sl->ref_cache[1][scan8[4]] =
+                sl->ref_cache[0][scan8[12]] =
+                sl->ref_cache[1][scan8[12]] = PART_NOT_AVAILABLE;
                     for( i = 0; i < 4; i++ )
-                        fill_rectangle( &h->direct_cache[scan8[4*i]], 2, 2, 8, (h->sub_mb_type[i]>>1)&0xFF, 1 );
+                        fill_rectangle(&sl->direct_cache[scan8[4*i]], 2, 2, 8, (sl->sub_mb_type[i] >> 1) & 0xFF, 1);
             }
         } else {
             for( i = 0; i < 4; i++ ) {
-                h->sub_mb_type[i] = decode_cabac_p_mb_sub_type( h );
-                sub_partition_count[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
-                h->sub_mb_type[i]=      p_sub_mb_type_info[ h->sub_mb_type[i] ].type;
+                sl->sub_mb_type[i] = decode_cabac_p_mb_sub_type(sl);
+                sub_partition_count[i] = p_sub_mb_type_info[sl->sub_mb_type[i]].partition_count;
+                sl->sub_mb_type[i]     = p_sub_mb_type_info[sl->sub_mb_type[i]].type;
             }
         }
 
-        for( list = 0; list < h->list_count; list++ ) {
+        for( list = 0; list < sl->list_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)){
-                        if (local_ref_count[list] > 1) {
-                            ref[list][i] = decode_cabac_mb_ref( h, list, 4*i );
-                            if (ref[list][i] >= (unsigned)local_ref_count[list]) {
-                                av_log(h->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref[list][i], local_ref_count[list]);
+                    if(IS_DIRECT(sl->sub_mb_type[i])) continue;
+                    if(IS_DIR(sl->sub_mb_type[i], 0, list)){
+                        unsigned rc = sl->ref_count[list] << MB_MBAFF(sl);
+                        if (rc > 1) {
+                            ref[list][i] = decode_cabac_mb_ref(sl, list, 4 * i);
+                            if (ref[list][i] >= rc) {
+                                av_log(h->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref[list][i], rc);
                                 return -1;
                             }
                         }else
@@ -2111,33 +2135,33 @@
                     } else {
                         ref[list][i] = -1;
                     }
-                                                       h->ref_cache[list][ scan8[4*i]+1 ]=
-                    h->ref_cache[list][ scan8[4*i]+8 ]=h->ref_cache[list][ scan8[4*i]+9 ]= ref[list][i];
+                    sl->ref_cache[list][scan8[4 * i] + 1] =
+                    sl->ref_cache[list][scan8[4 * i] + 8] = sl->ref_cache[list][scan8[4 * i] + 9] = ref[list][i];
                 }
         }
 
         if(dct8x8_allowed)
-            dct8x8_allowed = get_dct8x8_allowed(h);
+            dct8x8_allowed = get_dct8x8_allowed(h, sl);
 
-        for(list=0; list<h->list_count; list++){
+        for (list = 0; list < sl->list_count; list++) {
             for(i=0; i<4; i++){
-                h->ref_cache[list][ scan8[4*i]   ]=h->ref_cache[list][ scan8[4*i]+1 ];
-                if(IS_DIRECT(h->sub_mb_type[i])){
-                    fill_rectangle(h->mvd_cache[list][scan8[4*i]], 2, 2, 8, 0, 2);
+                sl->ref_cache[list][scan8[4 * i]] = sl->ref_cache[list][scan8[4 * i] + 1];
+                if(IS_DIRECT(sl->sub_mb_type[i])){
+                    fill_rectangle(sl->mvd_cache[list][scan8[4*i]], 2, 2, 8, 0, 2);
                     continue;
                 }
 
-                if(IS_DIR(h->sub_mb_type[i], 0, list) && !IS_DIRECT(h->sub_mb_type[i])){
-                    const int sub_mb_type= h->sub_mb_type[i];
+                if(IS_DIR(sl->sub_mb_type[i], 0, list) && !IS_DIRECT(sl->sub_mb_type[i])){
+                    const int sub_mb_type= sl->sub_mb_type[i];
                     const int block_width= (sub_mb_type & (MB_TYPE_16x16|MB_TYPE_16x8)) ? 2 : 1;
                     for(j=0; j<sub_partition_count[i]; j++){
                         int mpx, mpy;
                         int mx, my;
                         const int index= 4*i + block_width*j;
-                        int16_t (* mv_cache)[2]= &h->mv_cache[list][ scan8[index] ];
-                        uint8_t (* mvd_cache)[2]= &h->mvd_cache[list][ scan8[index] ];
-                        pred_motion(h, index, block_width, list, h->ref_cache[list][ scan8[index] ], &mx, &my);
-                        DECODE_CABAC_MB_MVD( h, list, index)
+                        int16_t (* mv_cache)[2] = &sl->mv_cache[list][ scan8[index] ];
+                        uint8_t (* mvd_cache)[2]= &sl->mvd_cache[list][ scan8[index] ];
+                        pred_motion(h, sl, index, block_width, list, sl->ref_cache[list][ scan8[index] ], &mx, &my);
+                        DECODE_CABAC_MB_MVD(sl, list, index)
                         tprintf(h->avctx, "final mv:%d %d\n", mx, my);
 
                         if(IS_SUB_8X8(sub_mb_type)){
@@ -2170,111 +2194,114 @@
                         mvd_cache[ 0 ][1]= mpy;
                     }
                 }else{
-                    fill_rectangle(h->mv_cache [list][ scan8[4*i] ], 2, 2, 8, 0, 4);
-                    fill_rectangle(h->mvd_cache[list][ scan8[4*i] ], 2, 2, 8, 0, 2);
+                    fill_rectangle(sl->mv_cache [list][ scan8[4*i] ], 2, 2, 8, 0, 4);
+                    fill_rectangle(sl->mvd_cache[list][ scan8[4*i] ], 2, 2, 8, 0, 2);
                 }
             }
         }
     } else if( IS_DIRECT(mb_type) ) {
-        ff_h264_pred_direct_motion(h, &mb_type);
-        fill_rectangle(h->mvd_cache[0][scan8[0]], 4, 4, 8, 0, 2);
-        fill_rectangle(h->mvd_cache[1][scan8[0]], 4, 4, 8, 0, 2);
+        ff_h264_pred_direct_motion(h, sl, &mb_type);
+        fill_rectangle(sl->mvd_cache[0][scan8[0]], 4, 4, 8, 0, 2);
+        fill_rectangle(sl->mvd_cache[1][scan8[0]], 4, 4, 8, 0, 2);
         dct8x8_allowed &= h->sps.direct_8x8_inference_flag;
     } else {
         int list, i;
         if(IS_16X16(mb_type)){
-            for(list=0; list<h->list_count; list++){
+            for (list = 0; list < sl->list_count; list++) {
                 if(IS_DIR(mb_type, 0, list)){
                     int ref;
-                    if (local_ref_count[list] > 1) {
-                        ref= decode_cabac_mb_ref(h, list, 0);
-                        if (ref >= (unsigned)local_ref_count[list]) {
-                            av_log(h->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref, local_ref_count[list]);
+                    unsigned rc = sl->ref_count[list] << MB_MBAFF(sl);
+                    if (rc > 1) {
+                        ref= decode_cabac_mb_ref(sl, list, 0);
+                        if (ref >= rc) {
+                            av_log(h->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref, rc);
                             return -1;
                         }
                     }else
                         ref=0;
-                    fill_rectangle(&h->ref_cache[list][ scan8[0] ], 4, 4, 8, ref, 1);
+                    fill_rectangle(&sl->ref_cache[list][ scan8[0] ], 4, 4, 8, ref, 1);
                 }
             }
-            for(list=0; list<h->list_count; list++){
+            for (list = 0; list < sl->list_count; list++) {
                 if(IS_DIR(mb_type, 0, list)){
                     int mx,my,mpx,mpy;
-                    pred_motion(h, 0, 4, list, h->ref_cache[list][ scan8[0] ], &mx, &my);
-                    DECODE_CABAC_MB_MVD( h, list, 0)
+                    pred_motion(h, sl, 0, 4, list, sl->ref_cache[list][ scan8[0] ], &mx, &my);
+                    DECODE_CABAC_MB_MVD(sl, list, 0)
                     tprintf(h->avctx, "final mv:%d %d\n", mx, my);
 
-                    fill_rectangle(h->mvd_cache[list][ scan8[0] ], 4, 4, 8, pack8to16(mpx,mpy), 2);
-                    fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, pack16to32(mx,my), 4);
+                    fill_rectangle(sl->mvd_cache[list][ scan8[0] ], 4, 4, 8, pack8to16(mpx,mpy), 2);
+                    fill_rectangle(sl->mv_cache[list][ scan8[0] ], 4, 4, 8, pack16to32(mx,my), 4);
                 }
             }
         }
         else if(IS_16X8(mb_type)){
-            for(list=0; list<h->list_count; list++){
+            for (list = 0; list < sl->list_count; list++) {
                     for(i=0; i<2; i++){
                         if(IS_DIR(mb_type, i, list)){
                             int ref;
-                            if (local_ref_count[list] > 1) {
-                                ref= decode_cabac_mb_ref( h, list, 8*i );
-                                if (ref >= (unsigned)local_ref_count[list]) {
-                                    av_log(h->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref, local_ref_count[list]);
+                            unsigned rc = sl->ref_count[list] << MB_MBAFF(sl);
+                            if (rc > 1) {
+                                ref= decode_cabac_mb_ref(sl, list, 8 * i);
+                                if (ref >= rc) {
+                                    av_log(h->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref, rc);
                                     return -1;
                                 }
                             }else
                                 ref=0;
-                            fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, ref, 1);
+                            fill_rectangle(&sl->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, ref, 1);
                         }else
-                            fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, (LIST_NOT_USED&0xFF), 1);
+                            fill_rectangle(&sl->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, (LIST_NOT_USED&0xFF), 1);
                     }
             }
-            for(list=0; list<h->list_count; list++){
+            for (list = 0; list < sl->list_count; list++) {
                 for(i=0; i<2; i++){
                     if(IS_DIR(mb_type, i, list)){
                         int mx,my,mpx,mpy;
-                        pred_16x8_motion(h, 8*i, list, h->ref_cache[list][scan8[0] + 16*i], &mx, &my);
-                        DECODE_CABAC_MB_MVD( h, list, 8*i)
+                        pred_16x8_motion(h, sl, 8*i, list, sl->ref_cache[list][scan8[0] + 16*i], &mx, &my);
+                        DECODE_CABAC_MB_MVD(sl, list, 8*i)
                         tprintf(h->avctx, "final mv:%d %d\n", mx, my);
 
-                        fill_rectangle(h->mvd_cache[list][ scan8[0] + 16*i ], 4, 2, 8, pack8to16(mpx,mpy), 2);
-                        fill_rectangle(h->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, pack16to32(mx,my), 4);
+                        fill_rectangle(sl->mvd_cache[list][ scan8[0] + 16*i ], 4, 2, 8, pack8to16(mpx,mpy), 2);
+                        fill_rectangle(sl->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, pack16to32(mx,my), 4);
                     }else{
-                        fill_rectangle(h->mvd_cache[list][ scan8[0] + 16*i ], 4, 2, 8, 0, 2);
-                        fill_rectangle(h-> mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, 0, 4);
+                        fill_rectangle(sl->mvd_cache[list][ scan8[0] + 16*i ], 4, 2, 8, 0, 2);
+                        fill_rectangle(sl->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, 0, 4);
                     }
                 }
             }
         }else{
             av_assert2(IS_8X16(mb_type));
-            for(list=0; list<h->list_count; list++){
+            for (list = 0; list < sl->list_count; list++) {
                     for(i=0; i<2; i++){
                         if(IS_DIR(mb_type, i, list)){ //FIXME optimize
                             int ref;
-                            if (local_ref_count[list] > 1) {
-                                ref= decode_cabac_mb_ref( h, list, 4*i );
-                                if (ref >= (unsigned)local_ref_count[list]) {
-                                    av_log(h->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref, local_ref_count[list]);
+                            unsigned rc = sl->ref_count[list] << MB_MBAFF(sl);
+                            if (rc > 1) {
+                                ref = decode_cabac_mb_ref(sl, list, 4 * i);
+                                if (ref >= rc) {
+                                    av_log(h->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref, rc);
                                     return -1;
                                 }
                             }else
                                 ref=0;
-                            fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, ref, 1);
+                            fill_rectangle(&sl->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, ref, 1);
                         }else
-                            fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, (LIST_NOT_USED&0xFF), 1);
+                            fill_rectangle(&sl->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, (LIST_NOT_USED&0xFF), 1);
                     }
             }
-            for(list=0; list<h->list_count; list++){
+            for (list = 0; list < sl->list_count; list++) {
                 for(i=0; i<2; i++){
                     if(IS_DIR(mb_type, i, list)){
                         int mx,my,mpx,mpy;
-                        pred_8x16_motion(h, i*4, list, h->ref_cache[list][ scan8[0] + 2*i ], &mx, &my);
-                        DECODE_CABAC_MB_MVD( h, list, 4*i)
+                        pred_8x16_motion(h, sl, i*4, list, sl->ref_cache[list][ scan8[0] + 2*i ], &mx, &my);
+                        DECODE_CABAC_MB_MVD(sl, list, 4*i)
 
                         tprintf(h->avctx, "final mv:%d %d\n", mx, my);
-                        fill_rectangle(h->mvd_cache[list][ scan8[0] + 2*i ], 2, 4, 8, pack8to16(mpx,mpy), 2);
-                        fill_rectangle(h->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, pack16to32(mx,my), 4);
+                        fill_rectangle(sl->mvd_cache[list][ scan8[0] + 2*i ], 2, 4, 8, pack8to16(mpx,mpy), 2);
+                        fill_rectangle(sl->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, pack16to32(mx,my), 4);
                     }else{
-                        fill_rectangle(h->mvd_cache[list][ scan8[0] + 2*i ], 2, 4, 8, 0, 2);
-                        fill_rectangle(h-> mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, 0, 4);
+                        fill_rectangle(sl->mvd_cache[list][ scan8[0] + 2*i ], 2, 4, 8, 0, 2);
+                        fill_rectangle(sl->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, 0, 4);
                     }
                 }
             }
@@ -2283,13 +2310,13 @@
 
    if( IS_INTER( mb_type ) ) {
         h->chroma_pred_mode_table[mb_xy] = 0;
-        write_back_motion( h, mb_type );
+        write_back_motion(h, sl, mb_type);
    }
 
     if( !IS_INTRA16x16( mb_type ) ) {
-        cbp  = decode_cabac_mb_cbp_luma( h );
+        cbp  = decode_cabac_mb_cbp_luma(sl);
         if(decode_chroma)
-            cbp |= decode_cabac_mb_cbp_chroma( h ) << 4;
+            cbp |= decode_cabac_mb_cbp_chroma(sl) << 4;
     } else {
         if (!decode_chroma && cbp>15) {
             av_log(h->avctx, AV_LOG_ERROR, "gray chroma\n");
@@ -2297,19 +2324,19 @@
         }
     }
 
-    h->cbp_table[mb_xy] = h->cbp = cbp;
+    h->cbp_table[mb_xy] = sl->cbp = cbp;
 
     if( dct8x8_allowed && (cbp&15) && !IS_INTRA( mb_type ) ) {
-        mb_type |= MB_TYPE_8x8DCT * get_cabac_noinline( &h->cabac, &h->cabac_state[399 + h->neighbor_transform_size] );
+        mb_type |= MB_TYPE_8x8DCT * get_cabac_noinline(&sl->cabac, &sl->cabac_state[399 + sl->neighbor_transform_size]);
     }
 
     /* It would be better to do this in fill_decode_caches, but we don't know
      * the transform mode of the current macroblock there. */
     if (CHROMA444(h) && IS_8x8DCT(mb_type)){
         int i;
-        uint8_t *nnz_cache = h->non_zero_count_cache;
+        uint8_t *nnz_cache = sl->non_zero_count_cache;
         for (i = 0; i < 2; i++){
-            if (h->left_type[LEFT(i)] && !IS_8x8DCT(h->left_type[LEFT(i)])){
+            if (sl->left_type[LEFT(i)] && !IS_8x8DCT(sl->left_type[LEFT(i)])) {
                 nnz_cache[3+8* 1 + 2*8*i]=
                 nnz_cache[3+8* 2 + 2*8*i]=
                 nnz_cache[3+8* 6 + 2*8*i]=
@@ -2318,7 +2345,7 @@
                 nnz_cache[3+8*12 + 2*8*i]= IS_INTRA(mb_type) ? 64 : 0;
             }
         }
-        if (h->top_type && !IS_8x8DCT(h->top_type)){
+        if (sl->top_type && !IS_8x8DCT(sl->top_type)){
             uint32_t top_empty = CABAC(h) && !IS_INTRA(mb_type) ? 0 : 0x40404040;
             AV_WN32A(&nnz_cache[4+8* 0], top_empty);
             AV_WN32A(&nnz_cache[4+8* 5], top_empty);
@@ -2332,24 +2359,24 @@
         const uint32_t *qmul;
 
         if(IS_INTERLACED(mb_type)){
-            scan8x8= h->qscale ? h->field_scan8x8 : h->field_scan8x8_q0;
-            scan= h->qscale ? h->field_scan : h->field_scan_q0;
+            scan8x8 = sl->qscale ? h->field_scan8x8 : h->field_scan8x8_q0;
+            scan    = sl->qscale ? h->field_scan : h->field_scan_q0;
         }else{
-            scan8x8= h->qscale ? h->zigzag_scan8x8 : h->zigzag_scan8x8_q0;
-            scan= h->qscale ? h->zigzag_scan : h->zigzag_scan_q0;
+            scan8x8 = sl->qscale ? h->zigzag_scan8x8 : h->zigzag_scan8x8_q0;
+            scan    = sl->qscale ? h->zigzag_scan : h->zigzag_scan_q0;
         }
 
         // decode_cabac_mb_dqp
-        if(get_cabac_noinline( &h->cabac, &h->cabac_state[60 + (h->last_qscale_diff != 0)])){
+        if(get_cabac_noinline( &sl->cabac, &sl->cabac_state[60 + (sl->last_qscale_diff != 0)])){
             int val = 1;
             int ctx= 2;
             const int max_qp = 51 + 6*(h->sps.bit_depth_luma-8);
 
-            while( get_cabac_noinline( &h->cabac, &h->cabac_state[60 + ctx] ) ) {
+            while( get_cabac_noinline( &sl->cabac, &sl->cabac_state[60 + ctx] ) ) {
                 ctx= 3;
                 val++;
                 if(val > 2*max_qp){ //prevent infinite loop
-                    av_log(h->avctx, AV_LOG_ERROR, "cabac decode of qscale diff failed at %d %d\n", h->mb_x, h->mb_y);
+                    av_log(h->avctx, AV_LOG_ERROR, "cabac decode of qscale diff failed at %d %d\n", sl->mb_x, sl->mb_y);
                     return -1;
                 }
             }
@@ -2358,26 +2385,26 @@
                 val=   (val + 1)>>1 ;
             else
                 val= -((val + 1)>>1);
-            h->last_qscale_diff = val;
-            h->qscale += val;
-            if(((unsigned)h->qscale) > max_qp){
-                if(h->qscale<0) h->qscale+= max_qp+1;
-                else            h->qscale-= max_qp+1;
+            sl->last_qscale_diff = val;
+            sl->qscale += val;
+            if (((unsigned)sl->qscale) > max_qp){
+                if (sl->qscale < 0) sl->qscale += max_qp + 1;
+                else                sl->qscale -= max_qp + 1;
             }
-            h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
-            h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
+            sl->chroma_qp[0] = get_chroma_qp(h, 0, sl->qscale);
+            sl->chroma_qp[1] = get_chroma_qp(h, 1, sl->qscale);
         }else
-            h->last_qscale_diff=0;
+            sl->last_qscale_diff=0;
 
-        decode_cabac_luma_residual(h, scan, scan8x8, pixel_shift, mb_type, cbp, 0);
+        decode_cabac_luma_residual(h, sl, scan, scan8x8, pixel_shift, mb_type, cbp, 0);
         if (CHROMA444(h)) {
-            decode_cabac_luma_residual(h, scan, scan8x8, pixel_shift, mb_type, cbp, 1);
-            decode_cabac_luma_residual(h, scan, scan8x8, pixel_shift, mb_type, cbp, 2);
+            decode_cabac_luma_residual(h, sl, scan, scan8x8, pixel_shift, mb_type, cbp, 1);
+            decode_cabac_luma_residual(h, sl, scan, scan8x8, pixel_shift, mb_type, cbp, 2);
         } else if (CHROMA422(h)) {
             if( cbp&0x30 ){
                 int c;
                 for (c = 0; c < 2; c++)
-                    decode_cabac_residual_dc_422(h, h->mb + ((256 + 16*16*c) << pixel_shift), 3,
+                    decode_cabac_residual_dc_422(h, sl, sl->mb + ((256 + 16*16*c) << pixel_shift), 3,
                                                  CHROMA_DC_BLOCK_INDEX + c,
                                                  chroma422_dc_scan, 8);
             }
@@ -2385,50 +2412,50 @@
             if( cbp&0x20 ) {
                 int c, i, i8x8;
                 for( c = 0; c < 2; c++ ) {
-                    int16_t *mb = h->mb + (16*(16 + 16*c) << pixel_shift);
-                    qmul = h->dequant4_coeff[c+1+(IS_INTRA( mb_type ) ? 0:3)][h->chroma_qp[c]];
+                    int16_t *mb = sl->mb + (16*(16 + 16*c) << pixel_shift);
+                    qmul = h->dequant4_coeff[c+1+(IS_INTRA( mb_type ) ? 0:3)][sl->chroma_qp[c]];
                     for (i8x8 = 0; i8x8 < 2; i8x8++) {
                         for (i = 0; i < 4; i++) {
                             const int index = 16 + 16 * c + 8*i8x8 + i;
-                            decode_cabac_residual_nondc(h, mb, 4, index, scan + 1, qmul, 15);
+                            decode_cabac_residual_nondc(h, sl, mb, 4, index, scan + 1, qmul, 15);
                             mb += 16<<pixel_shift;
                         }
                     }
                 }
             } else {
-                fill_rectangle(&h->non_zero_count_cache[scan8[16]], 4, 4, 8, 0, 1);
-                fill_rectangle(&h->non_zero_count_cache[scan8[32]], 4, 4, 8, 0, 1);
+                fill_rectangle(&sl->non_zero_count_cache[scan8[16]], 4, 4, 8, 0, 1);
+                fill_rectangle(&sl->non_zero_count_cache[scan8[32]], 4, 4, 8, 0, 1);
             }
         } else /* yuv420 */ {
             if( cbp&0x30 ){
                 int c;
                 for (c = 0; c < 2; c++)
-                    decode_cabac_residual_dc(h, h->mb + ((256 + 16*16*c) << pixel_shift), 3, CHROMA_DC_BLOCK_INDEX+c, chroma_dc_scan, 4);
+                    decode_cabac_residual_dc(h, sl, sl->mb + ((256 + 16*16*c) << pixel_shift), 3, CHROMA_DC_BLOCK_INDEX+c, chroma_dc_scan, 4);
             }
 
             if( cbp&0x20 ) {
                 int c, i;
                 for( c = 0; c < 2; c++ ) {
-                    qmul = h->dequant4_coeff[c+1+(IS_INTRA( mb_type ) ? 0:3)][h->chroma_qp[c]];
+                    qmul = h->dequant4_coeff[c+1+(IS_INTRA( mb_type ) ? 0:3)][sl->chroma_qp[c]];
                     for( i = 0; i < 4; i++ ) {
                         const int index = 16 + 16 * c + i;
-                        decode_cabac_residual_nondc(h, h->mb + (16*index << pixel_shift), 4, index, scan + 1, qmul, 15);
+                        decode_cabac_residual_nondc(h, sl, sl->mb + (16*index << pixel_shift), 4, index, scan + 1, qmul, 15);
                     }
                 }
             } else {
-                fill_rectangle(&h->non_zero_count_cache[scan8[16]], 4, 4, 8, 0, 1);
-                fill_rectangle(&h->non_zero_count_cache[scan8[32]], 4, 4, 8, 0, 1);
+                fill_rectangle(&sl->non_zero_count_cache[scan8[16]], 4, 4, 8, 0, 1);
+                fill_rectangle(&sl->non_zero_count_cache[scan8[32]], 4, 4, 8, 0, 1);
             }
         }
     } else {
-        fill_rectangle(&h->non_zero_count_cache[scan8[ 0]], 4, 4, 8, 0, 1);
-        fill_rectangle(&h->non_zero_count_cache[scan8[16]], 4, 4, 8, 0, 1);
-        fill_rectangle(&h->non_zero_count_cache[scan8[32]], 4, 4, 8, 0, 1);
-        h->last_qscale_diff = 0;
+        fill_rectangle(&sl->non_zero_count_cache[scan8[ 0]], 4, 4, 8, 0, 1);
+        fill_rectangle(&sl->non_zero_count_cache[scan8[16]], 4, 4, 8, 0, 1);
+        fill_rectangle(&sl->non_zero_count_cache[scan8[32]], 4, 4, 8, 0, 1);
+        sl->last_qscale_diff = 0;
     }
 
-    h->cur_pic.qscale_table[mb_xy] = h->qscale;
-    write_back_non_zero_count(h);
+    h->cur_pic.qscale_table[mb_xy] = sl->qscale;
+    write_back_non_zero_count(h, sl);
 
     return 0;
 }
diff --git a/libavcodec/h264_cavlc.c b/libavcodec/h264_cavlc.c
index bc50248..c2b86c1 100644
--- a/libavcodec/h264_cavlc.c
+++ b/libavcodec/h264_cavlc.c
@@ -283,10 +283,11 @@
  * Get the predicted number of non-zero coefficients.
  * @param n block index
  */
-static inline int pred_non_zero_count(H264Context *h, int n){
+static inline int pred_non_zero_count(const H264Context *h, H264SliceContext *sl, int n)
+{
     const int index8= scan8[n];
-    const int left= h->non_zero_count_cache[index8 - 1];
-    const int top = h->non_zero_count_cache[index8 - 8];
+    const int left = sl->non_zero_count_cache[index8 - 1];
+    const int top  = sl->non_zero_count_cache[index8 - 8];
     int i= left + top;
 
     if(i<64) i= (i+1)>>1;
@@ -441,7 +442,11 @@
  * @param max_coeff number of coefficients in the block
  * @return <0 if an error occurred
  */
-static int decode_residual(H264Context *h, GetBitContext *gb, int16_t *block, int n, const uint8_t *scantable, const uint32_t *qmul, int max_coeff){
+static int decode_residual(const H264Context *h, H264SliceContext *sl,
+                           GetBitContext *gb, int16_t *block, int n,
+                           const uint8_t *scantable, const uint32_t *qmul,
+                           int max_coeff)
+{
     static const int coeff_token_table_index[17]= {0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3};
     int level[16];
     int zeros_left, coeff_token, total_coeff, i, trailing_ones, run_before;
@@ -456,23 +461,23 @@
         total_coeff= coeff_token>>2;
     }else{
         if(n >= LUMA_DC_BLOCK_INDEX){
-            total_coeff= pred_non_zero_count(h, (n - LUMA_DC_BLOCK_INDEX)*16);
+            total_coeff= pred_non_zero_count(h, sl, (n - LUMA_DC_BLOCK_INDEX)*16);
             coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
             total_coeff= coeff_token>>2;
         }else{
-            total_coeff= pred_non_zero_count(h, n);
+            total_coeff= pred_non_zero_count(h, sl, n);
             coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
             total_coeff= coeff_token>>2;
         }
     }
-    h->non_zero_count_cache[ scan8[n] ]= total_coeff;
+    sl->non_zero_count_cache[scan8[n]] = total_coeff;
 
     //FIXME set last_non_zero?
 
     if(total_coeff==0)
         return 0;
     if(total_coeff > (unsigned)max_coeff) {
-        av_log(h->avctx, AV_LOG_ERROR, "corrupted macroblock %d %d (total_coeff=%d)\n", h->mb_x, h->mb_y, total_coeff);
+        av_log(h->avctx, AV_LOG_ERROR, "corrupted macroblock %d %d (total_coeff=%d)\n", sl->mb_x, sl->mb_y, total_coeff);
         return -1;
     }
 
@@ -622,22 +627,27 @@
     }
 
     if(zeros_left<0){
-        av_log(h->avctx, AV_LOG_ERROR, "negative number of zero coeffs at %d %d\n", h->mb_x, h->mb_y);
+        av_log(h->avctx, AV_LOG_ERROR, "negative number of zero coeffs at %d %d\n", sl->mb_x, sl->mb_y);
         return -1;
     }
 
     return 0;
 }
 
-static av_always_inline int decode_luma_residual(H264Context *h, GetBitContext *gb, const uint8_t *scan, const uint8_t *scan8x8, int pixel_shift, int mb_type, int cbp, int p){
+static av_always_inline
+int decode_luma_residual(const H264Context *h, H264SliceContext *sl,
+                         GetBitContext *gb, const uint8_t *scan,
+                         const uint8_t *scan8x8, int pixel_shift,
+                         int mb_type, int cbp, int p)
+{
     int i4x4, i8x8;
-    int qscale = p == 0 ? h->qscale : h->chroma_qp[p-1];
+    int qscale = p == 0 ? sl->qscale : sl->chroma_qp[p - 1];
     if(IS_INTRA16x16(mb_type)){
-        AV_ZERO128(h->mb_luma_dc[p]+0);
-        AV_ZERO128(h->mb_luma_dc[p]+8);
-        AV_ZERO128(h->mb_luma_dc[p]+16);
-        AV_ZERO128(h->mb_luma_dc[p]+24);
-        if( decode_residual(h, h->intra_gb_ptr, h->mb_luma_dc[p], LUMA_DC_BLOCK_INDEX+p, scan, NULL, 16) < 0){
+        AV_ZERO128(sl->mb_luma_dc[p]+0);
+        AV_ZERO128(sl->mb_luma_dc[p]+8);
+        AV_ZERO128(sl->mb_luma_dc[p]+16);
+        AV_ZERO128(sl->mb_luma_dc[p]+24);
+        if (decode_residual(h, sl, gb, sl->mb_luma_dc[p], LUMA_DC_BLOCK_INDEX + p, scan, NULL, 16) < 0) {
             return -1; //FIXME continue if partitioned and other return -1 too
         }
 
@@ -647,7 +657,7 @@
             for(i8x8=0; i8x8<4; i8x8++){
                 for(i4x4=0; i4x4<4; i4x4++){
                     const int index= i4x4 + 4*i8x8 + p*16;
-                    if( decode_residual(h, h->intra_gb_ptr, h->mb + (16*index << pixel_shift),
+                    if( decode_residual(h, sl, gb, sl->mb + (16*index << pixel_shift),
                         index, scan + 1, h->dequant4_coeff[p][qscale], 15) < 0 ){
                         return -1;
                     }
@@ -655,7 +665,7 @@
             }
             return 0xf;
         }else{
-            fill_rectangle(&h->non_zero_count_cache[scan8[p*16]], 4, 4, 8, 0, 1);
+            fill_rectangle(&sl->non_zero_count_cache[scan8[p*16]], 4, 4, 8, 0, 1);
             return 0;
         }
     }else{
@@ -665,29 +675,29 @@
         for(i8x8=0; i8x8<4; i8x8++){
             if(cbp & (1<<i8x8)){
                 if(IS_8x8DCT(mb_type)){
-                    int16_t *buf = &h->mb[64*i8x8+256*p << pixel_shift];
+                    int16_t *buf = &sl->mb[64*i8x8+256*p << pixel_shift];
                     uint8_t *nnz;
                     for(i4x4=0; i4x4<4; i4x4++){
                         const int index= i4x4 + 4*i8x8 + p*16;
-                        if( decode_residual(h, gb, buf, index, scan8x8+16*i4x4,
+                        if( decode_residual(h, sl, gb, buf, index, scan8x8+16*i4x4,
                                             h->dequant8_coeff[cqm][qscale], 16) < 0 )
                             return -1;
                     }
-                    nnz= &h->non_zero_count_cache[ scan8[4*i8x8+p*16] ];
+                    nnz = &sl->non_zero_count_cache[scan8[4 * i8x8 + p * 16]];
                     nnz[0] += nnz[1] + nnz[8] + nnz[9];
                     new_cbp |= !!nnz[0] << i8x8;
                 }else{
                     for(i4x4=0; i4x4<4; i4x4++){
                         const int index= i4x4 + 4*i8x8 + p*16;
-                        if( decode_residual(h, gb, h->mb + (16*index << pixel_shift), index,
+                        if( decode_residual(h, sl, gb, sl->mb + (16*index << pixel_shift), index,
                                             scan, h->dequant4_coeff[cqm][qscale], 16) < 0 ){
                             return -1;
                         }
-                        new_cbp |= h->non_zero_count_cache[ scan8[index] ] << i8x8;
+                        new_cbp |= sl->non_zero_count_cache[scan8[index]] << i8x8;
                     }
                 }
             }else{
-                uint8_t * const nnz= &h->non_zero_count_cache[ scan8[4*i8x8+p*16] ];
+                uint8_t * const nnz = &sl->non_zero_count_cache[scan8[4 * i8x8 + p * 16]];
                 nnz[0] = nnz[1] = nnz[8] = nnz[9] = 0;
             }
         }
@@ -695,42 +705,42 @@
     }
 }
 
-int ff_h264_decode_mb_cavlc(H264Context *h){
+int ff_h264_decode_mb_cavlc(const H264Context *h, H264SliceContext *sl)
+{
     int mb_xy;
     int partition_count;
     unsigned int mb_type, cbp;
     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 = h->mb_x + h->mb_y*h->mb_stride;
+    mb_xy = sl->mb_xy = sl->mb_x + sl->mb_y*h->mb_stride;
 
-    tprintf(h->avctx, "pic:%d mb:%d/%d\n", h->frame_num, h->mb_x, h->mb_y);
+    tprintf(h->avctx, "pic:%d mb:%d/%d\n", h->frame_num, sl->mb_x, sl->mb_y);
     cbp = 0; /* avoid warning. FIXME: find a solution without slowing
                 down the code */
-    if(h->slice_type_nos != AV_PICTURE_TYPE_I){
-        if(h->mb_skip_run==-1)
-            h->mb_skip_run= get_ue_golomb_long(&h->gb);
+    if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
+        if (sl->mb_skip_run == -1)
+            sl->mb_skip_run = get_ue_golomb_long(&sl->gb);
 
-        if (h->mb_skip_run--) {
-            if(FRAME_MBAFF(h) && (h->mb_y&1) == 0){
-                if(h->mb_skip_run==0)
-                    h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&h->gb);
+        if (sl->mb_skip_run--) {
+            if (FRAME_MBAFF(h) && (sl->mb_y & 1) == 0) {
+                if (sl->mb_skip_run == 0)
+                    sl->mb_mbaff = sl->mb_field_decoding_flag = get_bits1(&sl->gb);
             }
-            decode_mb_skip(h);
+            decode_mb_skip(h, sl);
             return 0;
         }
     }
     if (FRAME_MBAFF(h)) {
-        if( (h->mb_y&1) == 0 )
-            h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&h->gb);
+        if ((sl->mb_y & 1) == 0)
+            sl->mb_mbaff = sl->mb_field_decoding_flag = get_bits1(&sl->gb);
     }
 
-    h->prev_mb_skipped= 0;
+    sl->prev_mb_skipped = 0;
 
-    mb_type= get_ue_golomb(&h->gb);
-    if(h->slice_type_nos == AV_PICTURE_TYPE_B){
+    mb_type= get_ue_golomb(&sl->gb);
+    if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
         if(mb_type < 23){
             partition_count= b_mb_type_info[mb_type].partition_count;
             mb_type=         b_mb_type_info[mb_type].type;
@@ -738,7 +748,7 @@
             mb_type -= 23;
             goto decode_intra_mb;
         }
-    }else if(h->slice_type_nos == AV_PICTURE_TYPE_P){
+    } else if (sl->slice_type_nos == AV_PICTURE_TYPE_P) {
         if(mb_type < 5){
             partition_count= p_mb_type_info[mb_type].partition_count;
             mb_type=         p_mb_type_info[mb_type].type;
@@ -747,36 +757,36 @@
             goto decode_intra_mb;
         }
     }else{
-       av_assert2(h->slice_type_nos == AV_PICTURE_TYPE_I);
-        if(h->slice_type == AV_PICTURE_TYPE_SI && mb_type)
+       av_assert2(sl->slice_type_nos == AV_PICTURE_TYPE_I);
+        if (sl->slice_type == AV_PICTURE_TYPE_SI && mb_type)
             mb_type--;
 decode_intra_mb:
         if(mb_type > 25){
-            av_log(h->avctx, AV_LOG_ERROR, "mb_type %d in %c slice too large at %d %d\n", mb_type, av_get_picture_type_char(h->slice_type), h->mb_x, h->mb_y);
+            av_log(h->avctx, AV_LOG_ERROR, "mb_type %d in %c slice too large at %d %d\n", mb_type, av_get_picture_type_char(sl->slice_type), sl->mb_x, sl->mb_y);
             return -1;
         }
         partition_count=0;
         cbp= i_mb_type_info[mb_type].cbp;
-        h->intra16x16_pred_mode= i_mb_type_info[mb_type].pred_mode;
+        sl->intra16x16_pred_mode = i_mb_type_info[mb_type].pred_mode;
         mb_type= i_mb_type_info[mb_type].type;
     }
 
-    if(MB_FIELD(h))
+    if (MB_FIELD(sl))
         mb_type |= MB_TYPE_INTERLACED;
 
-    h->slice_table[ mb_xy ]= h->slice_num;
+    h->slice_table[mb_xy] = sl->slice_num;
 
     if(IS_INTRA_PCM(mb_type)){
         const int mb_size = ff_h264_mb_sizes[h->sps.chroma_format_idc] *
                             h->sps.bit_depth_luma;
 
         // We assume these blocks are very rare so we do not optimize it.
-        h->intra_pcm_ptr = align_get_bits(&h->gb);
-        if (get_bits_left(&h->gb) < mb_size) {
+        sl->intra_pcm_ptr = align_get_bits(&sl->gb);
+        if (get_bits_left(&sl->gb) < mb_size) {
             av_log(h->avctx, AV_LOG_ERROR, "Not enough data for an intra PCM block.\n");
             return AVERROR_INVALIDDATA;
         }
-        skip_bits_long(&h->gb, mb_size);
+        skip_bits_long(&sl->gb, mb_size);
 
         // In deblocking, the quantizer is 0
         h->cur_pic.qscale_table[mb_xy] = 0;
@@ -787,11 +797,8 @@
         return 0;
     }
 
-    local_ref_count[0] = h->ref_count[0] << MB_MBAFF(h);
-    local_ref_count[1] = h->ref_count[1] << MB_MBAFF(h);
-
-    fill_decode_neighbors(h, mb_type);
-    fill_decode_caches(h, mb_type);
+    fill_decode_neighbors(h, sl, mb_type);
+    fill_decode_caches(h, sl, mb_type);
 
     //mb_pred
     if(IS_INTRA(mb_type)){
@@ -800,86 +807,86 @@
         if(IS_INTRA4x4(mb_type)){
             int i;
             int di = 1;
-            if(dct8x8_allowed && get_bits1(&h->gb)){
+            if(dct8x8_allowed && get_bits1(&sl->gb)){
                 mb_type |= MB_TYPE_8x8DCT;
                 di = 4;
             }
 
 //                fill_intra4x4_pred_table(h);
             for(i=0; i<16; i+=di){
-                int mode= pred_intra_mode(h, i);
+                int mode = pred_intra_mode(h, sl, i);
 
-                if(!get_bits1(&h->gb)){
-                    const int rem_mode= get_bits(&h->gb, 3);
+                if(!get_bits1(&sl->gb)){
+                    const int rem_mode= get_bits(&sl->gb, 3);
                     mode = rem_mode + (rem_mode >= mode);
                 }
 
                 if(di==4)
-                    fill_rectangle( &h->intra4x4_pred_mode_cache[ scan8[i] ], 2, 2, 8, mode, 1 );
+                    fill_rectangle(&sl->intra4x4_pred_mode_cache[ scan8[i] ], 2, 2, 8, mode, 1);
                 else
-                    h->intra4x4_pred_mode_cache[ scan8[i] ] = mode;
+                    sl->intra4x4_pred_mode_cache[scan8[i]] = mode;
             }
-            write_back_intra_pred_mode(h);
-            if( ff_h264_check_intra4x4_pred_mode(h) < 0)
+            write_back_intra_pred_mode(h, sl);
+            if (ff_h264_check_intra4x4_pred_mode(h, sl) < 0)
                 return -1;
         }else{
-            h->intra16x16_pred_mode= ff_h264_check_intra_pred_mode(h, h->intra16x16_pred_mode, 0);
-            if(h->intra16x16_pred_mode < 0)
+            sl->intra16x16_pred_mode = ff_h264_check_intra_pred_mode(h, sl, sl->intra16x16_pred_mode, 0);
+            if (sl->intra16x16_pred_mode < 0)
                 return -1;
         }
         if(decode_chroma){
-            pred_mode= ff_h264_check_intra_pred_mode(h, get_ue_golomb_31(&h->gb), 1);
+            pred_mode= ff_h264_check_intra_pred_mode(h, sl, get_ue_golomb_31(&sl->gb), 1);
             if(pred_mode < 0)
                 return -1;
-            h->chroma_pred_mode= pred_mode;
+            sl->chroma_pred_mode = pred_mode;
         } else {
-            h->chroma_pred_mode = DC_128_PRED8x8;
+            sl->chroma_pred_mode = DC_128_PRED8x8;
         }
     }else if(partition_count==4){
         int i, j, sub_partition_count[4], list, ref[2][4];
 
-        if(h->slice_type_nos == AV_PICTURE_TYPE_B){
+        if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
             for(i=0; i<4; i++){
-                h->sub_mb_type[i]= get_ue_golomb_31(&h->gb);
-                if(h->sub_mb_type[i] >=13){
-                    av_log(h->avctx, AV_LOG_ERROR, "B sub_mb_type %u out of range at %d %d\n", h->sub_mb_type[i], h->mb_x, h->mb_y);
+                sl->sub_mb_type[i]= get_ue_golomb_31(&sl->gb);
+                if(sl->sub_mb_type[i] >=13){
+                    av_log(h->avctx, AV_LOG_ERROR, "B sub_mb_type %u out of range at %d %d\n", sl->sub_mb_type[i], sl->mb_x, sl->mb_y);
                     return -1;
                 }
-                sub_partition_count[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
-                h->sub_mb_type[i]=      b_sub_mb_type_info[ h->sub_mb_type[i] ].type;
+                sub_partition_count[i]= b_sub_mb_type_info[ sl->sub_mb_type[i] ].partition_count;
+                sl->sub_mb_type[i]=      b_sub_mb_type_info[ sl->sub_mb_type[i] ].type;
             }
-            if( IS_DIRECT(h->sub_mb_type[0]|h->sub_mb_type[1]|h->sub_mb_type[2]|h->sub_mb_type[3])) {
-                ff_h264_pred_direct_motion(h, &mb_type);
-                h->ref_cache[0][scan8[4]] =
-                h->ref_cache[1][scan8[4]] =
-                h->ref_cache[0][scan8[12]] =
-                h->ref_cache[1][scan8[12]] = PART_NOT_AVAILABLE;
+            if( IS_DIRECT(sl->sub_mb_type[0]|sl->sub_mb_type[1]|sl->sub_mb_type[2]|sl->sub_mb_type[3])) {
+                ff_h264_pred_direct_motion(h, sl, &mb_type);
+                sl->ref_cache[0][scan8[4]] =
+                sl->ref_cache[1][scan8[4]] =
+                sl->ref_cache[0][scan8[12]] =
+                sl->ref_cache[1][scan8[12]] = PART_NOT_AVAILABLE;
             }
         }else{
-            av_assert2(h->slice_type_nos == AV_PICTURE_TYPE_P); //FIXME SP correct ?
+            av_assert2(sl->slice_type_nos == AV_PICTURE_TYPE_P); //FIXME SP correct ?
             for(i=0; i<4; i++){
-                h->sub_mb_type[i]= get_ue_golomb_31(&h->gb);
-                if(h->sub_mb_type[i] >=4){
-                    av_log(h->avctx, AV_LOG_ERROR, "P sub_mb_type %u out of range at %d %d\n", h->sub_mb_type[i], h->mb_x, h->mb_y);
+                sl->sub_mb_type[i]= get_ue_golomb_31(&sl->gb);
+                if(sl->sub_mb_type[i] >=4){
+                    av_log(h->avctx, AV_LOG_ERROR, "P sub_mb_type %u out of range at %d %d\n", sl->sub_mb_type[i], sl->mb_x, sl->mb_y);
                     return -1;
                 }
-                sub_partition_count[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
-                h->sub_mb_type[i]=      p_sub_mb_type_info[ h->sub_mb_type[i] ].type;
+                sub_partition_count[i]= p_sub_mb_type_info[ sl->sub_mb_type[i] ].partition_count;
+                sl->sub_mb_type[i]=      p_sub_mb_type_info[ sl->sub_mb_type[i] ].type;
             }
         }
 
-        for(list=0; list<h->list_count; list++){
-            int ref_count = IS_REF0(mb_type) ? 1 : local_ref_count[list];
+        for (list = 0; list < sl->list_count; list++) {
+            int ref_count = IS_REF0(mb_type) ? 1 : sl->ref_count[list] << MB_MBAFF(sl);
             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(IS_DIRECT(sl->sub_mb_type[i])) continue;
+                if(IS_DIR(sl->sub_mb_type[i], 0, list)){
                     unsigned int tmp;
                     if(ref_count == 1){
                         tmp= 0;
                     }else if(ref_count == 2){
-                        tmp= get_bits1(&h->gb)^1;
+                        tmp= get_bits1(&sl->gb)^1;
                     }else{
-                        tmp= get_ue_golomb_31(&h->gb);
+                        tmp= get_ue_golomb_31(&sl->gb);
                         if(tmp>=ref_count){
                             av_log(h->avctx, AV_LOG_ERROR, "ref %u overflow\n", tmp);
                             return -1;
@@ -894,27 +901,27 @@
         }
 
         if(dct8x8_allowed)
-            dct8x8_allowed = get_dct8x8_allowed(h);
+            dct8x8_allowed = get_dct8x8_allowed(h, sl);
 
-        for(list=0; list<h->list_count; list++){
+        for (list = 0; list < sl->list_count; list++) {
             for(i=0; i<4; i++){
-                if(IS_DIRECT(h->sub_mb_type[i])) {
-                    h->ref_cache[list][ scan8[4*i] ] = h->ref_cache[list][ scan8[4*i]+1 ];
+                if(IS_DIRECT(sl->sub_mb_type[i])) {
+                    sl->ref_cache[list][ scan8[4*i] ] = sl->ref_cache[list][ scan8[4*i]+1 ];
                     continue;
                 }
-                h->ref_cache[list][ scan8[4*i]   ]=h->ref_cache[list][ scan8[4*i]+1 ]=
-                h->ref_cache[list][ scan8[4*i]+8 ]=h->ref_cache[list][ scan8[4*i]+9 ]= ref[list][i];
+                sl->ref_cache[list][ scan8[4*i]   ]=sl->ref_cache[list][ scan8[4*i]+1 ]=
+                sl->ref_cache[list][ scan8[4*i]+8 ]=sl->ref_cache[list][ scan8[4*i]+9 ]= ref[list][i];
 
-                if(IS_DIR(h->sub_mb_type[i], 0, list)){
-                    const int sub_mb_type= h->sub_mb_type[i];
+                if(IS_DIR(sl->sub_mb_type[i], 0, list)){
+                    const int sub_mb_type= sl->sub_mb_type[i];
                     const int block_width= (sub_mb_type & (MB_TYPE_16x16|MB_TYPE_16x8)) ? 2 : 1;
                     for(j=0; j<sub_partition_count[i]; j++){
                         int mx, my;
                         const int index= 4*i + block_width*j;
-                        int16_t (* mv_cache)[2]= &h->mv_cache[list][ scan8[index] ];
-                        pred_motion(h, index, block_width, list, h->ref_cache[list][ scan8[index] ], &mx, &my);
-                        mx += get_se_golomb(&h->gb);
-                        my += get_se_golomb(&h->gb);
+                        int16_t (* mv_cache)[2]= &sl->mv_cache[list][ scan8[index] ];
+                        pred_motion(h, sl, index, block_width, list, sl->ref_cache[list][ scan8[index] ], &mx, &my);
+                        mx += get_se_golomb(&sl->gb);
+                        my += get_se_golomb(&sl->gb);
                         tprintf(h->avctx, "final mv:%d %d\n", mx, my);
 
                         if(IS_SUB_8X8(sub_mb_type)){
@@ -933,139 +940,142 @@
                         mv_cache[ 0 ][1]= my;
                     }
                 }else{
-                    uint32_t *p= (uint32_t *)&h->mv_cache[list][ scan8[4*i] ][0];
+                    uint32_t *p= (uint32_t *)&sl->mv_cache[list][ scan8[4*i] ][0];
                     p[0] = p[1]=
                     p[8] = p[9]= 0;
                 }
             }
         }
     }else if(IS_DIRECT(mb_type)){
-        ff_h264_pred_direct_motion(h, &mb_type);
+        ff_h264_pred_direct_motion(h, sl, &mb_type);
         dct8x8_allowed &= h->sps.direct_8x8_inference_flag;
     }else{
         int list, mx, my, i;
          //FIXME we should set ref_idx_l? to 0 if we use that later ...
         if(IS_16X16(mb_type)){
-            for(list=0; list<h->list_count; list++){
+            for (list = 0; list < sl->list_count; list++) {
                     unsigned int val;
                     if(IS_DIR(mb_type, 0, list)){
-                        if(local_ref_count[list]==1){
+                        unsigned rc = sl->ref_count[list] << MB_MBAFF(sl);
+                        if (rc == 1) {
                             val= 0;
-                        } else if(local_ref_count[list]==2){
-                            val= get_bits1(&h->gb)^1;
+                        } else if (rc == 2) {
+                            val= get_bits1(&sl->gb)^1;
                         }else{
-                            val= get_ue_golomb_31(&h->gb);
-                            if (val >= local_ref_count[list]){
+                            val= get_ue_golomb_31(&sl->gb);
+                            if (val >= rc) {
                                 av_log(h->avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
                                 return -1;
                             }
                         }
-                    fill_rectangle(&h->ref_cache[list][ scan8[0] ], 4, 4, 8, val, 1);
+                    fill_rectangle(&sl->ref_cache[list][ scan8[0] ], 4, 4, 8, val, 1);
                     }
             }
-            for(list=0; list<h->list_count; list++){
+            for (list = 0; list < sl->list_count; list++) {
                 if(IS_DIR(mb_type, 0, list)){
-                    pred_motion(h, 0, 4, list, h->ref_cache[list][ scan8[0] ], &mx, &my);
-                    mx += get_se_golomb(&h->gb);
-                    my += get_se_golomb(&h->gb);
+                    pred_motion(h, sl, 0, 4, list, sl->ref_cache[list][ scan8[0] ], &mx, &my);
+                    mx += get_se_golomb(&sl->gb);
+                    my += get_se_golomb(&sl->gb);
                     tprintf(h->avctx, "final mv:%d %d\n", mx, my);
 
-                    fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, pack16to32(mx,my), 4);
+                    fill_rectangle(sl->mv_cache[list][ scan8[0] ], 4, 4, 8, pack16to32(mx,my), 4);
                 }
             }
         }
         else if(IS_16X8(mb_type)){
-            for(list=0; list<h->list_count; list++){
+            for (list = 0; list < sl->list_count; list++) {
                     for(i=0; i<2; i++){
                         unsigned int val;
                         if(IS_DIR(mb_type, i, list)){
-                            if(local_ref_count[list] == 1) {
+                            unsigned rc = sl->ref_count[list] << MB_MBAFF(sl);
+                            if (rc == 1) {
                                 val= 0;
-                            } else if(local_ref_count[list] == 2) {
-                                val= get_bits1(&h->gb)^1;
+                            } else if (rc == 2) {
+                                val= get_bits1(&sl->gb)^1;
                             }else{
-                                val= get_ue_golomb_31(&h->gb);
-                                if (val >= local_ref_count[list]){
+                                val= get_ue_golomb_31(&sl->gb);
+                                if (val >= rc) {
                                     av_log(h->avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
                                     return -1;
                                 }
                             }
                         }else
                             val= LIST_NOT_USED&0xFF;
-                        fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 1);
+                        fill_rectangle(&sl->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 1);
                     }
             }
-            for(list=0; list<h->list_count; list++){
+            for (list = 0; list < sl->list_count; list++) {
                 for(i=0; i<2; i++){
                     unsigned int val;
                     if(IS_DIR(mb_type, i, list)){
-                        pred_16x8_motion(h, 8*i, list, h->ref_cache[list][scan8[0] + 16*i], &mx, &my);
-                        mx += get_se_golomb(&h->gb);
-                        my += get_se_golomb(&h->gb);
+                        pred_16x8_motion(h, sl, 8*i, list, sl->ref_cache[list][scan8[0] + 16*i], &mx, &my);
+                        mx += get_se_golomb(&sl->gb);
+                        my += get_se_golomb(&sl->gb);
                         tprintf(h->avctx, "final mv:%d %d\n", mx, my);
 
                         val= pack16to32(mx,my);
                     }else
                         val=0;
-                    fill_rectangle(h->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 4);
+                    fill_rectangle(sl->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 4);
                 }
             }
         }else{
             av_assert2(IS_8X16(mb_type));
-            for(list=0; list<h->list_count; list++){
+            for (list = 0; list < sl->list_count; list++) {
                     for(i=0; i<2; i++){
                         unsigned int val;
                         if(IS_DIR(mb_type, i, list)){ //FIXME optimize
-                            if(local_ref_count[list]==1){
+                            unsigned rc = sl->ref_count[list] << MB_MBAFF(sl);
+                            if (rc == 1) {
                                 val= 0;
-                            } else if(local_ref_count[list]==2){
-                                val= get_bits1(&h->gb)^1;
+                            } else if (rc == 2) {
+                                val= get_bits1(&sl->gb)^1;
                             }else{
-                                val= get_ue_golomb_31(&h->gb);
-                                if (val >= local_ref_count[list]){
+                                val= get_ue_golomb_31(&sl->gb);
+                                if (val >= rc) {
                                     av_log(h->avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
                                     return -1;
                                 }
                             }
                         }else
                             val= LIST_NOT_USED&0xFF;
-                        fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 1);
+                        fill_rectangle(&sl->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 1);
                     }
             }
-            for(list=0; list<h->list_count; list++){
+            for (list = 0; list < sl->list_count; list++) {
                 for(i=0; i<2; i++){
                     unsigned int val;
                     if(IS_DIR(mb_type, i, list)){
-                        pred_8x16_motion(h, i*4, list, h->ref_cache[list][ scan8[0] + 2*i ], &mx, &my);
-                        mx += get_se_golomb(&h->gb);
-                        my += get_se_golomb(&h->gb);
+                        pred_8x16_motion(h, sl, i*4, list, sl->ref_cache[list][ scan8[0] + 2*i ], &mx, &my);
+                        mx += get_se_golomb(&sl->gb);
+                        my += get_se_golomb(&sl->gb);
                         tprintf(h->avctx, "final mv:%d %d\n", mx, my);
 
                         val= pack16to32(mx,my);
                     }else
                         val=0;
-                    fill_rectangle(h->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 4);
+                    fill_rectangle(sl->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 4);
                 }
             }
         }
     }
 
     if(IS_INTER(mb_type))
-        write_back_motion(h, mb_type);
+        write_back_motion(h, sl, mb_type);
 
     if(!IS_INTRA16x16(mb_type)){
-        cbp= get_ue_golomb(&h->gb);
+        cbp= get_ue_golomb(&sl->gb);
 
         if(decode_chroma){
             if(cbp > 47){
-                av_log(h->avctx, AV_LOG_ERROR, "cbp too large (%u) at %d %d\n", cbp, h->mb_x, h->mb_y);
+                av_log(h->avctx, AV_LOG_ERROR, "cbp too large (%u) at %d %d\n", cbp, sl->mb_x, sl->mb_y);
                 return -1;
             }
             if(IS_INTRA4x4(mb_type)) cbp= golomb_to_intra4x4_cbp[cbp];
             else                     cbp= golomb_to_inter_cbp   [cbp];
         }else{
             if(cbp > 15){
-                av_log(h->avctx, AV_LOG_ERROR, "cbp too large (%u) at %d %d\n", cbp, h->mb_x, h->mb_y);
+                av_log(h->avctx, AV_LOG_ERROR, "cbp too large (%u) at %d %d\n", cbp, sl->mb_x, sl->mb_y);
                 return -1;
             }
             if(IS_INTRA4x4(mb_type)) cbp= golomb_to_intra4x4_cbp_gray[cbp];
@@ -1079,9 +1089,9 @@
     }
 
     if(dct8x8_allowed && (cbp&15) && !IS_INTRA(mb_type)){
-        mb_type |= MB_TYPE_8x8DCT*get_bits1(&h->gb);
+        mb_type |= MB_TYPE_8x8DCT*get_bits1(&sl->gb);
     }
-    h->cbp=
+    sl->cbp=
     h->cbp_table[mb_xy]= cbp;
     h->cur_pic.mb_type[mb_xy] = mb_type;
 
@@ -1089,43 +1099,43 @@
         int i4x4, i8x8, chroma_idx;
         int dquant;
         int ret;
-        GetBitContext *gb= IS_INTRA(mb_type) ? h->intra_gb_ptr : h->inter_gb_ptr;
+        GetBitContext *gb = &sl->gb;
         const uint8_t *scan, *scan8x8;
         const int max_qp = 51 + 6*(h->sps.bit_depth_luma-8);
 
         if(IS_INTERLACED(mb_type)){
-            scan8x8= h->qscale ? h->field_scan8x8_cavlc : h->field_scan8x8_cavlc_q0;
-            scan= h->qscale ? h->field_scan : h->field_scan_q0;
+            scan8x8 = sl->qscale ? h->field_scan8x8_cavlc : h->field_scan8x8_cavlc_q0;
+            scan    = sl->qscale ? h->field_scan : h->field_scan_q0;
         }else{
-            scan8x8= h->qscale ? h->zigzag_scan8x8_cavlc : h->zigzag_scan8x8_cavlc_q0;
-            scan= h->qscale ? h->zigzag_scan : h->zigzag_scan_q0;
+            scan8x8 = sl->qscale ? h->zigzag_scan8x8_cavlc : h->zigzag_scan8x8_cavlc_q0;
+            scan    = sl->qscale ? h->zigzag_scan : h->zigzag_scan_q0;
         }
 
-        dquant= get_se_golomb(&h->gb);
+        dquant= get_se_golomb(&sl->gb);
 
-        h->qscale += dquant;
+        sl->qscale += dquant;
 
-        if(((unsigned)h->qscale) > max_qp){
-            if(h->qscale<0) h->qscale+= max_qp+1;
-            else            h->qscale-= max_qp+1;
-            if(((unsigned)h->qscale) > max_qp){
-                av_log(h->avctx, AV_LOG_ERROR, "dquant out of range (%d) at %d %d\n", dquant, h->mb_x, h->mb_y);
+        if (((unsigned)sl->qscale) > max_qp){
+            if (sl->qscale < 0) sl->qscale += max_qp + 1;
+            else                sl->qscale -= max_qp+1;
+            if (((unsigned)sl->qscale) > max_qp){
+                av_log(h->avctx, AV_LOG_ERROR, "dquant out of range (%d) at %d %d\n", dquant, sl->mb_x, sl->mb_y);
                 return -1;
             }
         }
 
-        h->chroma_qp[0]= get_chroma_qp(h, 0, h->qscale);
-        h->chroma_qp[1]= get_chroma_qp(h, 1, h->qscale);
+        sl->chroma_qp[0] = get_chroma_qp(h, 0, sl->qscale);
+        sl->chroma_qp[1] = get_chroma_qp(h, 1, sl->qscale);
 
-        if( (ret = decode_luma_residual(h, gb, scan, scan8x8, pixel_shift, mb_type, cbp, 0)) < 0 ){
+        if ((ret = decode_luma_residual(h, sl, gb, scan, scan8x8, pixel_shift, mb_type, cbp, 0)) < 0 ) {
             return -1;
         }
         h->cbp_table[mb_xy] |= ret << 12;
         if (CHROMA444(h)) {
-            if( decode_luma_residual(h, gb, scan, scan8x8, pixel_shift, mb_type, cbp, 1) < 0 ){
+            if (decode_luma_residual(h, sl, gb, scan, scan8x8, pixel_shift, mb_type, cbp, 1) < 0 ) {
                 return -1;
             }
-            if( decode_luma_residual(h, gb, scan, scan8x8, pixel_shift, mb_type, cbp, 2) < 0 ){
+            if (decode_luma_residual(h, sl, gb, scan, scan8x8, pixel_shift, mb_type, cbp, 2) < 0 ) {
                 return -1;
             }
         } else {
@@ -1133,7 +1143,7 @@
 
             if(cbp&0x30){
                 for(chroma_idx=0; chroma_idx<2; chroma_idx++)
-                    if (decode_residual(h, gb, h->mb + ((256 + 16*16*chroma_idx) << pixel_shift),
+                    if (decode_residual(h, sl, gb, sl->mb + ((256 + 16*16*chroma_idx) << pixel_shift),
                                         CHROMA_DC_BLOCK_INDEX+chroma_idx,
                                         CHROMA422(h) ? chroma422_dc_scan : chroma_dc_scan,
                                         NULL, 4*num_c8x8) < 0) {
@@ -1143,29 +1153,29 @@
 
             if(cbp&0x20){
                 for(chroma_idx=0; chroma_idx<2; chroma_idx++){
-                    const uint32_t *qmul = h->dequant4_coeff[chroma_idx+1+(IS_INTRA( mb_type ) ? 0:3)][h->chroma_qp[chroma_idx]];
-                    int16_t *mb = h->mb + (16*(16 + 16*chroma_idx) << pixel_shift);
+                    const uint32_t *qmul = h->dequant4_coeff[chroma_idx+1+(IS_INTRA( mb_type ) ? 0:3)][sl->chroma_qp[chroma_idx]];
+                    int16_t *mb = sl->mb + (16*(16 + 16*chroma_idx) << pixel_shift);
                     for (i8x8 = 0; i8x8<num_c8x8; i8x8++) {
                         for (i4x4 = 0; i4x4 < 4; i4x4++) {
                             const int index = 16 + 16*chroma_idx + 8*i8x8 + i4x4;
-                            if (decode_residual(h, gb, mb, index, scan + 1, qmul, 15) < 0)
+                            if (decode_residual(h, sl, gb, mb, index, scan + 1, qmul, 15) < 0)
                                 return -1;
                             mb += 16 << pixel_shift;
                         }
                     }
                 }
             }else{
-                fill_rectangle(&h->non_zero_count_cache[scan8[16]], 4, 4, 8, 0, 1);
-                fill_rectangle(&h->non_zero_count_cache[scan8[32]], 4, 4, 8, 0, 1);
+                fill_rectangle(&sl->non_zero_count_cache[scan8[16]], 4, 4, 8, 0, 1);
+                fill_rectangle(&sl->non_zero_count_cache[scan8[32]], 4, 4, 8, 0, 1);
             }
         }
     }else{
-        fill_rectangle(&h->non_zero_count_cache[scan8[ 0]], 4, 4, 8, 0, 1);
-        fill_rectangle(&h->non_zero_count_cache[scan8[16]], 4, 4, 8, 0, 1);
-        fill_rectangle(&h->non_zero_count_cache[scan8[32]], 4, 4, 8, 0, 1);
+        fill_rectangle(&sl->non_zero_count_cache[scan8[ 0]], 4, 4, 8, 0, 1);
+        fill_rectangle(&sl->non_zero_count_cache[scan8[16]], 4, 4, 8, 0, 1);
+        fill_rectangle(&sl->non_zero_count_cache[scan8[32]], 4, 4, 8, 0, 1);
     }
-    h->cur_pic.qscale_table[mb_xy] = h->qscale;
-    write_back_non_zero_count(h);
+    h->cur_pic.qscale_table[mb_xy] = sl->qscale;
+    write_back_non_zero_count(h, sl);
 
     return 0;
 }
diff --git a/libavcodec/h264_direct.c b/libavcodec/h264_direct.c
index 3289fe4..5756a7b 100644
--- a/libavcodec/h264_direct.c
+++ b/libavcodec/h264_direct.c
@@ -34,46 +34,49 @@
 
 #include <assert.h>
 
-static int get_scale_factor(H264Context *const h, int poc, int poc1, int i)
+static int get_scale_factor(H264SliceContext *sl,
+                            int poc, int poc1, int i)
 {
-    int poc0 = h->ref_list[0][i].poc;
-    int td = av_clip(poc1 - poc0, -128, 127);
-    if (td == 0 || h->ref_list[0][i].long_ref) {
+    int poc0 = sl->ref_list[0][i].poc;
+    int td = av_clip_int8(poc1 - poc0);
+    if (td == 0 || sl->ref_list[0][i].parent->long_ref) {
         return 256;
     } else {
-        int tb = av_clip(poc - poc0, -128, 127);
+        int tb = av_clip_int8(poc - poc0);
         int tx = (16384 + (FFABS(td) >> 1)) / td;
-        return av_clip((tb * tx + 32) >> 6, -1024, 1023);
+        return av_clip_intp2((tb * tx + 32) >> 6, 10);
     }
 }
 
-void ff_h264_direct_dist_scale_factor(H264Context *const h)
+void ff_h264_direct_dist_scale_factor(const H264Context *const h,
+                                      H264SliceContext *sl)
 {
     const int poc  = FIELD_PICTURE(h) ? h->cur_pic_ptr->field_poc[h->picture_structure == PICT_BOTTOM_FIELD]
                                       : h->cur_pic_ptr->poc;
-    const int poc1 = h->ref_list[1][0].poc;
+    const int poc1 = sl->ref_list[1][0].poc;
     int i, field;
 
     if (FRAME_MBAFF(h))
         for (field = 0; field < 2; field++) {
             const int poc  = h->cur_pic_ptr->field_poc[field];
-            const int poc1 = h->ref_list[1][0].field_poc[field];
-            for (i = 0; i < 2 * h->ref_count[0]; i++)
-                h->dist_scale_factor_field[field][i ^ field] =
-                    get_scale_factor(h, poc, poc1, i + 16);
+            const int poc1 = sl->ref_list[1][0].parent->field_poc[field];
+            for (i = 0; i < 2 * sl->ref_count[0]; i++)
+                sl->dist_scale_factor_field[field][i ^ field] =
+                    get_scale_factor(sl, poc, poc1, i + 16);
         }
 
-    for (i = 0; i < h->ref_count[0]; i++)
-        h->dist_scale_factor[i] = get_scale_factor(h, poc, poc1, i);
+    for (i = 0; i < sl->ref_count[0]; i++)
+        sl->dist_scale_factor[i] = get_scale_factor(sl, poc, poc1, i);
 }
 
-static void fill_colmap(H264Context *h, int map[2][16 + 32], int list,
+static void fill_colmap(const H264Context *h, H264SliceContext *sl,
+                        int map[2][16 + 32], int list,
                         int field, int colfield, int mbafi)
 {
-    H264Picture *const ref1 = &h->ref_list[1][0];
+    H264Picture *const ref1 = sl->ref_list[1][0].parent;
     int j, old_ref, rfield;
     int start  = mbafi ? 16                       : 0;
-    int end    = mbafi ? 16 + 2 * h->ref_count[0] : h->ref_count[0];
+    int end    = mbafi ? 16 + 2 * sl->ref_count[0] : sl->ref_count[0];
     int interl = mbafi || h->picture_structure != PICT_FRAME;
 
     /* bogus; fills in for missing frames */
@@ -90,8 +93,8 @@
                 poc = (poc & ~3) + rfield + 1;
 
             for (j = start; j < end; j++) {
-                if (4 * h->ref_list[0][j].frame_num +
-                    (h->ref_list[0][j].reference & 3) == poc) {
+                if (4 * sl->ref_list[0][j].parent->frame_num +
+                    (sl->ref_list[0][j].reference & 3) == poc) {
                     int cur_ref = mbafi ? (j - 16) ^ field : j;
                     if (ref1->mbaff)
                         map[list][2 * old_ref + (rfield ^ field) + 16] = cur_ref;
@@ -104,19 +107,19 @@
     }
 }
 
-void ff_h264_direct_ref_list_init(H264Context *const h)
+void ff_h264_direct_ref_list_init(const H264Context *const h, H264SliceContext *sl)
 {
-    H264Picture *const ref1 = &h->ref_list[1][0];
+    H264Ref *const ref1 = &sl->ref_list[1][0];
     H264Picture *const cur = h->cur_pic_ptr;
     int list, j, field;
     int sidx     = (h->picture_structure & 1) ^ 1;
     int ref1sidx = (ref1->reference      & 1) ^ 1;
 
-    for (list = 0; list < 2; list++) {
-        cur->ref_count[sidx][list] = h->ref_count[list];
-        for (j = 0; j < h->ref_count[list]; j++)
-            cur->ref_poc[sidx][list][j] = 4 * h->ref_list[list][j].frame_num +
-                                          (h->ref_list[list][j].reference & 3);
+    for (list = 0; list < sl->list_count; list++) {
+        cur->ref_count[sidx][list] = sl->ref_count[list];
+        for (j = 0; j < sl->ref_count[list]; j++)
+            cur->ref_poc[sidx][list][j] = 4 * sl->ref_list[list][j].parent->frame_num +
+                                          (sl->ref_list[list][j].reference & 3);
     }
 
     if (h->picture_structure == PICT_FRAME) {
@@ -126,37 +129,41 @@
 
     cur->mbaff = FRAME_MBAFF(h);
 
-    h->col_fieldoff = 0;
+    sl->col_fieldoff = 0;
+
+    if (sl->list_count != 2 || !sl->ref_count[1])
+        return;
+
     if (h->picture_structure == PICT_FRAME) {
         int cur_poc  = h->cur_pic_ptr->poc;
-        int *col_poc = h->ref_list[1]->field_poc;
-        h->col_parity = (FFABS(col_poc[0] - cur_poc) >=
-                         FFABS(col_poc[1] - cur_poc));
+        int *col_poc = sl->ref_list[1][0].parent->field_poc;
+        sl->col_parity = (FFABS(col_poc[0] - cur_poc) >=
+                          FFABS(col_poc[1] - cur_poc));
         ref1sidx =
-        sidx     = h->col_parity;
+        sidx     = sl->col_parity;
     // FL -> FL & differ parity
-    } else if (!(h->picture_structure & h->ref_list[1][0].reference) &&
-               !h->ref_list[1][0].mbaff) {
-        h->col_fieldoff = 2 * h->ref_list[1][0].reference - 3;
+    } else if (!(h->picture_structure & sl->ref_list[1][0].reference) &&
+               !sl->ref_list[1][0].parent->mbaff) {
+        sl->col_fieldoff = 2 * sl->ref_list[1][0].reference - 3;
     }
 
-    if (h->slice_type_nos != AV_PICTURE_TYPE_B || h->direct_spatial_mv_pred)
+    if (sl->slice_type_nos != AV_PICTURE_TYPE_B || sl->direct_spatial_mv_pred)
         return;
 
     for (list = 0; list < 2; list++) {
-        fill_colmap(h, h->map_col_to_list0, list, sidx, ref1sidx, 0);
+        fill_colmap(h, sl, sl->map_col_to_list0, list, sidx, ref1sidx, 0);
         if (FRAME_MBAFF(h))
             for (field = 0; field < 2; field++)
-                fill_colmap(h, h->map_col_to_list0_field[field], list, field,
+                fill_colmap(h, sl, sl->map_col_to_list0_field[field], list, field,
                             field, 1);
     }
 }
 
-static void await_reference_mb_row(H264Context *const h, H264Picture *ref,
+static void await_reference_mb_row(const H264Context *const h, H264Ref *ref,
                                    int mb_y)
 {
     int ref_field         = ref->reference - 1;
-    int ref_field_picture = ref->field_picture;
+    int ref_field_picture = ref->parent->field_picture;
     int ref_height        = 16 * h->mb_height >> ref_field_picture;
 
     if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_FRAME))
@@ -165,17 +172,18 @@
     /* FIXME: It can be safe to access mb stuff
      * even if pixels aren't deblocked yet. */
 
-    ff_thread_await_progress(&ref->tf,
+    ff_thread_await_progress(&ref->parent->tf,
                              FFMIN(16 * mb_y >> ref_field_picture,
                                    ref_height - 1),
                              ref_field_picture && ref_field);
 }
 
-static void pred_spatial_direct_motion(H264Context *const h, int *mb_type)
+static void pred_spatial_direct_motion(const H264Context *const h, H264SliceContext *sl,
+                                       int *mb_type)
 {
     int b8_stride = 2;
     int b4_stride = h->b_stride;
-    int mb_xy = h->mb_xy, mb_y = h->mb_y;
+    int mb_xy = sl->mb_xy, mb_y = sl->mb_y;
     int mb_type_col[2];
     const int16_t (*l1mv0)[2], (*l1mv1)[2];
     const int8_t *l1ref0, *l1ref1;
@@ -186,23 +194,23 @@
     int mv[2];
     int list;
 
-    assert(h->ref_list[1][0].reference & 3);
+    assert(sl->ref_list[1][0].reference & 3);
 
-    await_reference_mb_row(h, &h->ref_list[1][0],
-                           h->mb_y + !!IS_INTERLACED(*mb_type));
+    await_reference_mb_row(h, &sl->ref_list[1][0],
+                           sl->mb_y + !!IS_INTERLACED(*mb_type));
 
 #define MB_TYPE_16x16_OR_INTRA (MB_TYPE_16x16 | MB_TYPE_INTRA4x4 | \
                                 MB_TYPE_INTRA16x16 | MB_TYPE_INTRA_PCM)
 
     /* ref = min(neighbors) */
     for (list = 0; list < 2; list++) {
-        int left_ref     = h->ref_cache[list][scan8[0] - 1];
-        int top_ref      = h->ref_cache[list][scan8[0] - 8];
-        int refc         = h->ref_cache[list][scan8[0] - 8 + 4];
-        const int16_t *C = h->mv_cache[list][scan8[0]  - 8 + 4];
+        int left_ref     = sl->ref_cache[list][scan8[0] - 1];
+        int top_ref      = sl->ref_cache[list][scan8[0] - 8];
+        int refc         = sl->ref_cache[list][scan8[0] - 8 + 4];
+        const int16_t *C = sl->mv_cache[list][scan8[0]  - 8 + 4];
         if (refc == PART_NOT_AVAILABLE) {
-            refc = h->ref_cache[list][scan8[0] - 8 - 1];
-            C    = h->mv_cache[list][scan8[0]  - 8 - 1];
+            refc = sl->ref_cache[list][scan8[0] - 8 - 1];
+            C    = sl->mv_cache[list][scan8[0]  - 8 - 1];
         }
         ref[list] = FFMIN3((unsigned)left_ref,
                            (unsigned)top_ref,
@@ -210,8 +218,8 @@
         if (ref[list] >= 0) {
             /* This is just pred_motion() but with the cases removed that
              * cannot happen for direct blocks. */
-            const int16_t *const A = h->mv_cache[list][scan8[0] - 1];
-            const int16_t *const B = h->mv_cache[list][scan8[0] - 8];
+            const int16_t *const A = sl->mv_cache[list][scan8[0] - 1];
+            const int16_t *const B = sl->mv_cache[list][scan8[0] - 8];
 
             int match_count = (left_ref == ref[list]) +
                               (top_ref  == ref[list]) +
@@ -229,7 +237,7 @@
                 else
                     mv[list] = AV_RN32A(C);
             }
-            av_assert2(ref[list] < (h->ref_count[list] << !!FRAME_MBAFF(h)));
+            av_assert2(ref[list] < (sl->ref_count[list] << !!FRAME_MBAFF(h)));
         } else {
             int mask = ~(MB_TYPE_L0 << (2 * list));
             mv[list]  = 0;
@@ -247,33 +255,33 @@
     }
 
     if (!(is_b8x8 | mv[0] | mv[1])) {
-        fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, (uint8_t)ref[0], 1);
-        fill_rectangle(&h->ref_cache[1][scan8[0]], 4, 4, 8, (uint8_t)ref[1], 1);
-        fill_rectangle(&h->mv_cache[0][scan8[0]], 4, 4, 8, 0, 4);
-        fill_rectangle(&h->mv_cache[1][scan8[0]], 4, 4, 8, 0, 4);
+        fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, (uint8_t)ref[0], 1);
+        fill_rectangle(&sl->ref_cache[1][scan8[0]], 4, 4, 8, (uint8_t)ref[1], 1);
+        fill_rectangle(&sl->mv_cache[0][scan8[0]], 4, 4, 8, 0, 4);
+        fill_rectangle(&sl->mv_cache[1][scan8[0]], 4, 4, 8, 0, 4);
         *mb_type = (*mb_type & ~(MB_TYPE_8x8 | MB_TYPE_16x8 | MB_TYPE_8x16 |
                                  MB_TYPE_P1L0 | MB_TYPE_P1L1)) |
                    MB_TYPE_16x16 | MB_TYPE_DIRECT2;
         return;
     }
 
-    if (IS_INTERLACED(h->ref_list[1][0].mb_type[mb_xy])) { // AFL/AFR/FR/FL -> AFL/FL
+    if (IS_INTERLACED(sl->ref_list[1][0].parent->mb_type[mb_xy])) { // AFL/AFR/FR/FL -> AFL/FL
         if (!IS_INTERLACED(*mb_type)) {                    //     AFR/FR    -> AFL/FL
-            mb_y  = (h->mb_y & ~1) + h->col_parity;
-            mb_xy = h->mb_x +
-                    ((h->mb_y & ~1) + h->col_parity) * h->mb_stride;
+            mb_y  = (sl->mb_y & ~1) + sl->col_parity;
+            mb_xy = sl->mb_x +
+                    ((sl->mb_y & ~1) + sl->col_parity) * h->mb_stride;
             b8_stride = 0;
         } else {
-            mb_y  += h->col_fieldoff;
-            mb_xy += h->mb_stride * h->col_fieldoff; // non-zero for FL -> FL & differ parity
+            mb_y  += sl->col_fieldoff;
+            mb_xy += h->mb_stride * sl->col_fieldoff; // non-zero for FL -> FL & differ parity
         }
         goto single_col;
     } else {                                             // AFL/AFR/FR/FL -> AFR/FR
         if (IS_INTERLACED(*mb_type)) {                   // AFL       /FL -> AFR/FR
-            mb_y           =  h->mb_y & ~1;
-            mb_xy          = (h->mb_y & ~1) * h->mb_stride + h->mb_x;
-            mb_type_col[0] = h->ref_list[1][0].mb_type[mb_xy];
-            mb_type_col[1] = h->ref_list[1][0].mb_type[mb_xy + h->mb_stride];
+            mb_y           =  sl->mb_y & ~1;
+            mb_xy          = (sl->mb_y & ~1) * h->mb_stride + sl->mb_x;
+            mb_type_col[0] = sl->ref_list[1][0].parent->mb_type[mb_xy];
+            mb_type_col[1] = sl->ref_list[1][0].parent->mb_type[mb_xy + h->mb_stride];
             b8_stride      = 2 + 4 * h->mb_stride;
             b4_stride     *= 6;
             if (IS_INTERLACED(mb_type_col[0]) !=
@@ -293,7 +301,7 @@
         } else {                                         //     AFR/FR    -> AFR/FR
 single_col:
             mb_type_col[0] =
-            mb_type_col[1] = h->ref_list[1][0].mb_type[mb_xy];
+            mb_type_col[1] = sl->ref_list[1][0].parent->mb_type[mb_xy];
 
             sub_mb_type |= MB_TYPE_16x16 | MB_TYPE_DIRECT2; /* B_SUB_8x8 */
             if (!is_b8x8 && (mb_type_col[0] & MB_TYPE_16x16_OR_INTRA)) {
@@ -313,14 +321,14 @@
         }
     }
 
-    await_reference_mb_row(h, &h->ref_list[1][0], mb_y);
+    await_reference_mb_row(h, &sl->ref_list[1][0], mb_y);
 
-    l1mv0  = (void*)&h->ref_list[1][0].motion_val[0][h->mb2b_xy[mb_xy]];
-    l1mv1  = (void*)&h->ref_list[1][0].motion_val[1][h->mb2b_xy[mb_xy]];
-    l1ref0 = &h->ref_list[1][0].ref_index[0][4 * mb_xy];
-    l1ref1 = &h->ref_list[1][0].ref_index[1][4 * mb_xy];
+    l1mv0  = (void*)&sl->ref_list[1][0].parent->motion_val[0][h->mb2b_xy[mb_xy]];
+    l1mv1  = (void*)&sl->ref_list[1][0].parent->motion_val[1][h->mb2b_xy[mb_xy]];
+    l1ref0 = &sl->ref_list[1][0].parent->ref_index[0][4 * mb_xy];
+    l1ref1 = &sl->ref_list[1][0].parent->ref_index[1][4 * mb_xy];
     if (!b8_stride) {
-        if (h->mb_y & 1) {
+        if (sl->mb_y & 1) {
             l1ref0 += 2;
             l1ref1 += 2;
             l1mv0  += 2 * b4_stride;
@@ -337,15 +345,15 @@
             int xy4 = x8 * 3 + y8 * b4_stride;
             int a, b;
 
-            if (is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
+            if (is_b8x8 && !IS_DIRECT(sl->sub_mb_type[i8]))
                 continue;
-            h->sub_mb_type[i8] = sub_mb_type;
+            sl->sub_mb_type[i8] = sub_mb_type;
 
-            fill_rectangle(&h->ref_cache[0][scan8[i8 * 4]], 2, 2, 8,
+            fill_rectangle(&sl->ref_cache[0][scan8[i8 * 4]], 2, 2, 8,
                            (uint8_t)ref[0], 1);
-            fill_rectangle(&h->ref_cache[1][scan8[i8 * 4]], 2, 2, 8,
+            fill_rectangle(&sl->ref_cache[1][scan8[i8 * 4]], 2, 2, 8,
                            (uint8_t)ref[1], 1);
-            if (!IS_INTRA(mb_type_col[y8]) && !h->ref_list[1][0].long_ref &&
+            if (!IS_INTRA(mb_type_col[y8]) && !sl->ref_list[1][0].parent->long_ref &&
                 ((l1ref0[xy8] == 0 &&
                   FFABS(l1mv0[xy4][0]) <= 1 &&
                   FFABS(l1mv0[xy4][1]) <= 1) ||
@@ -364,8 +372,8 @@
                 a = mv[0];
                 b = mv[1];
             }
-            fill_rectangle(&h->mv_cache[0][scan8[i8 * 4]], 2, 2, 8, a, 4);
-            fill_rectangle(&h->mv_cache[1][scan8[i8 * 4]], 2, 2, 8, b, 4);
+            fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2, 8, a, 4);
+            fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2, 8, b, 4);
         }
         if (!is_b8x8 && !(n & 3))
             *mb_type = (*mb_type & ~(MB_TYPE_8x8 | MB_TYPE_16x8 | MB_TYPE_8x16 |
@@ -374,9 +382,9 @@
     } else if (IS_16X16(*mb_type)) {
         int a, b;
 
-        fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, (uint8_t)ref[0], 1);
-        fill_rectangle(&h->ref_cache[1][scan8[0]], 4, 4, 8, (uint8_t)ref[1], 1);
-        if (!IS_INTRA(mb_type_col[0]) && !h->ref_list[1][0].long_ref &&
+        fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, (uint8_t)ref[0], 1);
+        fill_rectangle(&sl->ref_cache[1][scan8[0]], 4, 4, 8, (uint8_t)ref[1], 1);
+        if (!IS_INTRA(mb_type_col[0]) && !sl->ref_list[1][0].parent->long_ref &&
             ((l1ref0[0] == 0 &&
               FFABS(l1mv0[0][0]) <= 1 &&
               FFABS(l1mv0[0][1]) <= 1) ||
@@ -393,28 +401,28 @@
             a = mv[0];
             b = mv[1];
         }
-        fill_rectangle(&h->mv_cache[0][scan8[0]], 4, 4, 8, a, 4);
-        fill_rectangle(&h->mv_cache[1][scan8[0]], 4, 4, 8, b, 4);
+        fill_rectangle(&sl->mv_cache[0][scan8[0]], 4, 4, 8, a, 4);
+        fill_rectangle(&sl->mv_cache[1][scan8[0]], 4, 4, 8, b, 4);
     } else {
         int n = 0;
         for (i8 = 0; i8 < 4; i8++) {
             const int x8 = i8 & 1;
             const int y8 = i8 >> 1;
 
-            if (is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
+            if (is_b8x8 && !IS_DIRECT(sl->sub_mb_type[i8]))
                 continue;
-            h->sub_mb_type[i8] = sub_mb_type;
+            sl->sub_mb_type[i8] = sub_mb_type;
 
-            fill_rectangle(&h->mv_cache[0][scan8[i8 * 4]], 2, 2, 8, mv[0], 4);
-            fill_rectangle(&h->mv_cache[1][scan8[i8 * 4]], 2, 2, 8, mv[1], 4);
-            fill_rectangle(&h->ref_cache[0][scan8[i8 * 4]], 2, 2, 8,
+            fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2, 8, mv[0], 4);
+            fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2, 8, mv[1], 4);
+            fill_rectangle(&sl->ref_cache[0][scan8[i8 * 4]], 2, 2, 8,
                            (uint8_t)ref[0], 1);
-            fill_rectangle(&h->ref_cache[1][scan8[i8 * 4]], 2, 2, 8,
+            fill_rectangle(&sl->ref_cache[1][scan8[i8 * 4]], 2, 2, 8,
                            (uint8_t)ref[1], 1);
 
             assert(b8_stride == 2);
             /* col_zero_flag */
-            if (!IS_INTRA(mb_type_col[0]) && !h->ref_list[1][0].long_ref &&
+            if (!IS_INTRA(mb_type_col[0]) && !sl->ref_list[1][0].parent->long_ref &&
                 (l1ref0[i8] == 0 ||
                  (l1ref0[i8] < 0 &&
                   l1ref1[i8] == 0 &&
@@ -424,10 +432,10 @@
                     const int16_t *mv_col = l1mv[x8 * 3 + y8 * 3 * b4_stride];
                     if (FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1) {
                         if (ref[0] == 0)
-                            fill_rectangle(&h->mv_cache[0][scan8[i8 * 4]], 2, 2,
+                            fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2,
                                            8, 0, 4);
                         if (ref[1] == 0)
-                            fill_rectangle(&h->mv_cache[1][scan8[i8 * 4]], 2, 2,
+                            fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2,
                                            8, 0, 4);
                         n += 4;
                     }
@@ -438,14 +446,14 @@
                                                      (y8 * 2 + (i4 >> 1)) * b4_stride];
                         if (FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1) {
                             if (ref[0] == 0)
-                                AV_ZERO32(h->mv_cache[0][scan8[i8 * 4 + i4]]);
+                                AV_ZERO32(sl->mv_cache[0][scan8[i8 * 4 + i4]]);
                             if (ref[1] == 0)
-                                AV_ZERO32(h->mv_cache[1][scan8[i8 * 4 + i4]]);
+                                AV_ZERO32(sl->mv_cache[1][scan8[i8 * 4 + i4]]);
                             m++;
                         }
                     }
                     if (!(m & 3))
-                        h->sub_mb_type[i8] += MB_TYPE_16x16 - MB_TYPE_8x8;
+                        sl->sub_mb_type[i8] += MB_TYPE_16x16 - MB_TYPE_8x8;
                     n += m;
                 }
             }
@@ -457,11 +465,12 @@
     }
 }
 
-static void pred_temp_direct_motion(H264Context *const h, int *mb_type)
+static void pred_temp_direct_motion(const H264Context *const h, H264SliceContext *sl,
+                                    int *mb_type)
 {
     int b8_stride = 2;
     int b4_stride = h->b_stride;
-    int mb_xy = h->mb_xy, mb_y = h->mb_y;
+    int mb_xy = sl->mb_xy, mb_y = sl->mb_y;
     int mb_type_col[2];
     const int16_t (*l1mv0)[2], (*l1mv1)[2];
     const int8_t *l1ref0, *l1ref1;
@@ -469,28 +478,28 @@
     unsigned int sub_mb_type;
     int i8, i4;
 
-    assert(h->ref_list[1][0].reference & 3);
+    assert(sl->ref_list[1][0].reference & 3);
 
-    await_reference_mb_row(h, &h->ref_list[1][0],
-                           h->mb_y + !!IS_INTERLACED(*mb_type));
+    await_reference_mb_row(h, &sl->ref_list[1][0],
+                           sl->mb_y + !!IS_INTERLACED(*mb_type));
 
-    if (IS_INTERLACED(h->ref_list[1][0].mb_type[mb_xy])) { // AFL/AFR/FR/FL -> AFL/FL
+    if (IS_INTERLACED(sl->ref_list[1][0].parent->mb_type[mb_xy])) { // AFL/AFR/FR/FL -> AFL/FL
         if (!IS_INTERLACED(*mb_type)) {                    //     AFR/FR    -> AFL/FL
-            mb_y  = (h->mb_y & ~1) + h->col_parity;
-            mb_xy = h->mb_x +
-                    ((h->mb_y & ~1) + h->col_parity) * h->mb_stride;
+            mb_y  = (sl->mb_y & ~1) + sl->col_parity;
+            mb_xy = sl->mb_x +
+                    ((sl->mb_y & ~1) + sl->col_parity) * h->mb_stride;
             b8_stride = 0;
         } else {
-            mb_y  += h->col_fieldoff;
-            mb_xy += h->mb_stride * h->col_fieldoff; // non-zero for FL -> FL & differ parity
+            mb_y  += sl->col_fieldoff;
+            mb_xy += h->mb_stride * sl->col_fieldoff; // non-zero for FL -> FL & differ parity
         }
         goto single_col;
     } else {                                        // AFL/AFR/FR/FL -> AFR/FR
         if (IS_INTERLACED(*mb_type)) {              // AFL       /FL -> AFR/FR
-            mb_y           = h->mb_y & ~1;
-            mb_xy          = h->mb_x + (h->mb_y & ~1) * h->mb_stride;
-            mb_type_col[0] = h->ref_list[1][0].mb_type[mb_xy];
-            mb_type_col[1] = h->ref_list[1][0].mb_type[mb_xy + h->mb_stride];
+            mb_y           = sl->mb_y & ~1;
+            mb_xy          = sl->mb_x + (sl->mb_y & ~1) * h->mb_stride;
+            mb_type_col[0] = sl->ref_list[1][0].parent->mb_type[mb_xy];
+            mb_type_col[1] = sl->ref_list[1][0].parent->mb_type[mb_xy + h->mb_stride];
             b8_stride      = 2 + 4 * h->mb_stride;
             b4_stride     *= 6;
             if (IS_INTERLACED(mb_type_col[0]) !=
@@ -513,7 +522,7 @@
         } else {                                    //     AFR/FR    -> AFR/FR
 single_col:
             mb_type_col[0]     =
-                mb_type_col[1] = h->ref_list[1][0].mb_type[mb_xy];
+                mb_type_col[1] = sl->ref_list[1][0].parent->mb_type[mb_xy];
 
             sub_mb_type = MB_TYPE_16x16 | MB_TYPE_P0L0 | MB_TYPE_P0L1 |
                           MB_TYPE_DIRECT2;                  /* B_SUB_8x8 */
@@ -536,14 +545,14 @@
         }
     }
 
-    await_reference_mb_row(h, &h->ref_list[1][0], mb_y);
+    await_reference_mb_row(h, &sl->ref_list[1][0], mb_y);
 
-    l1mv0  = (void*)&h->ref_list[1][0].motion_val[0][h->mb2b_xy[mb_xy]];
-    l1mv1  = (void*)&h->ref_list[1][0].motion_val[1][h->mb2b_xy[mb_xy]];
-    l1ref0 = &h->ref_list[1][0].ref_index[0][4 * mb_xy];
-    l1ref1 = &h->ref_list[1][0].ref_index[1][4 * mb_xy];
+    l1mv0  = (void*)&sl->ref_list[1][0].parent->motion_val[0][h->mb2b_xy[mb_xy]];
+    l1mv1  = (void*)&sl->ref_list[1][0].parent->motion_val[1][h->mb2b_xy[mb_xy]];
+    l1ref0 = &sl->ref_list[1][0].parent->ref_index[0][4 * mb_xy];
+    l1ref1 = &sl->ref_list[1][0].parent->ref_index[1][4 * mb_xy];
     if (!b8_stride) {
-        if (h->mb_y & 1) {
+        if (sl->mb_y & 1) {
             l1ref0 += 2;
             l1ref1 += 2;
             l1mv0  += 2 * b4_stride;
@@ -552,17 +561,17 @@
     }
 
     {
-        const int *map_col_to_list0[2] = { h->map_col_to_list0[0],
-                                           h->map_col_to_list0[1] };
-        const int *dist_scale_factor = h->dist_scale_factor;
+        const int *map_col_to_list0[2] = { sl->map_col_to_list0[0],
+                                           sl->map_col_to_list0[1] };
+        const int *dist_scale_factor = sl->dist_scale_factor;
         int ref_offset;
 
         if (FRAME_MBAFF(h) && IS_INTERLACED(*mb_type)) {
-            map_col_to_list0[0] = h->map_col_to_list0_field[h->mb_y & 1][0];
-            map_col_to_list0[1] = h->map_col_to_list0_field[h->mb_y & 1][1];
-            dist_scale_factor   = h->dist_scale_factor_field[h->mb_y & 1];
+            map_col_to_list0[0] = sl->map_col_to_list0_field[sl->mb_y & 1][0];
+            map_col_to_list0[1] = sl->map_col_to_list0_field[sl->mb_y & 1][1];
+            dist_scale_factor   = sl->dist_scale_factor_field[sl->mb_y & 1];
         }
-        ref_offset = (h->ref_list[1][0].mbaff << 4) & (mb_type_col[0] >> 3);
+        ref_offset = (sl->ref_list[1][0].parent->mbaff << 4) & (mb_type_col[0] >> 3);
 
         if (IS_INTERLACED(*mb_type) != IS_INTERLACED(mb_type_col[0])) {
             int y_shift = 2 * !IS_INTERLACED(*mb_type);
@@ -574,15 +583,15 @@
                 int ref0, scale;
                 const int16_t (*l1mv)[2] = l1mv0;
 
-                if (is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
+                if (is_b8x8 && !IS_DIRECT(sl->sub_mb_type[i8]))
                     continue;
-                h->sub_mb_type[i8] = sub_mb_type;
+                sl->sub_mb_type[i8] = sub_mb_type;
 
-                fill_rectangle(&h->ref_cache[1][scan8[i8 * 4]], 2, 2, 8, 0, 1);
+                fill_rectangle(&sl->ref_cache[1][scan8[i8 * 4]], 2, 2, 8, 0, 1);
                 if (IS_INTRA(mb_type_col[y8])) {
-                    fill_rectangle(&h->ref_cache[0][scan8[i8 * 4]], 2, 2, 8, 0, 1);
-                    fill_rectangle(&h->mv_cache[0][scan8[i8 * 4]], 2, 2, 8, 0, 4);
-                    fill_rectangle(&h->mv_cache[1][scan8[i8 * 4]], 2, 2, 8, 0, 4);
+                    fill_rectangle(&sl->ref_cache[0][scan8[i8 * 4]], 2, 2, 8, 0, 1);
+                    fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2, 8, 0, 4);
+                    fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2, 8, 0, 4);
                     continue;
                 }
 
@@ -595,7 +604,7 @@
                     l1mv = l1mv1;
                 }
                 scale = dist_scale_factor[ref0];
-                fill_rectangle(&h->ref_cache[0][scan8[i8 * 4]], 2, 2, 8,
+                fill_rectangle(&sl->ref_cache[0][scan8[i8 * 4]], 2, 2, 8,
                                ref0, 1);
 
                 {
@@ -603,9 +612,9 @@
                     int my_col            = (mv_col[1] << y_shift) / 2;
                     int mx                = (scale * mv_col[0] + 128) >> 8;
                     int my                = (scale * my_col    + 128) >> 8;
-                    fill_rectangle(&h->mv_cache[0][scan8[i8 * 4]], 2, 2, 8,
+                    fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2, 8,
                                    pack16to32(mx, my), 4);
-                    fill_rectangle(&h->mv_cache[1][scan8[i8 * 4]], 2, 2, 8,
+                    fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2, 8,
                                    pack16to32(mx - mv_col[0], my - my_col), 4);
                 }
             }
@@ -617,7 +626,7 @@
         if (IS_16X16(*mb_type)) {
             int ref, mv0, mv1;
 
-            fill_rectangle(&h->ref_cache[1][scan8[0]], 4, 4, 8, 0, 1);
+            fill_rectangle(&sl->ref_cache[1][scan8[0]], 4, 4, 8, 0, 1);
             if (IS_INTRA(mb_type_col[0])) {
                 ref = mv0 = mv1 = 0;
             } else {
@@ -632,9 +641,9 @@
                 mv0      = pack16to32(mv_l0[0], mv_l0[1]);
                 mv1      = pack16to32(mv_l0[0] - mv_col[0], mv_l0[1] - mv_col[1]);
             }
-            fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
-            fill_rectangle(&h->mv_cache[0][scan8[0]], 4, 4, 8, mv0, 4);
-            fill_rectangle(&h->mv_cache[1][scan8[0]], 4, 4, 8, mv1, 4);
+            fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
+            fill_rectangle(&sl->mv_cache[0][scan8[0]], 4, 4, 8, mv0, 4);
+            fill_rectangle(&sl->mv_cache[1][scan8[0]], 4, 4, 8, mv1, 4);
         } else {
             for (i8 = 0; i8 < 4; i8++) {
                 const int x8 = i8 & 1;
@@ -642,14 +651,14 @@
                 int ref0, scale;
                 const int16_t (*l1mv)[2] = l1mv0;
 
-                if (is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
+                if (is_b8x8 && !IS_DIRECT(sl->sub_mb_type[i8]))
                     continue;
-                h->sub_mb_type[i8] = sub_mb_type;
-                fill_rectangle(&h->ref_cache[1][scan8[i8 * 4]], 2, 2, 8, 0, 1);
+                sl->sub_mb_type[i8] = sub_mb_type;
+                fill_rectangle(&sl->ref_cache[1][scan8[i8 * 4]], 2, 2, 8, 0, 1);
                 if (IS_INTRA(mb_type_col[0])) {
-                    fill_rectangle(&h->ref_cache[0][scan8[i8 * 4]], 2, 2, 8, 0, 1);
-                    fill_rectangle(&h->mv_cache[0][scan8[i8 * 4]], 2, 2, 8, 0, 4);
-                    fill_rectangle(&h->mv_cache[1][scan8[i8 * 4]], 2, 2, 8, 0, 4);
+                    fill_rectangle(&sl->ref_cache[0][scan8[i8 * 4]], 2, 2, 8, 0, 1);
+                    fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2, 8, 0, 4);
+                    fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2, 8, 0, 4);
                     continue;
                 }
 
@@ -663,24 +672,24 @@
                 }
                 scale = dist_scale_factor[ref0];
 
-                fill_rectangle(&h->ref_cache[0][scan8[i8 * 4]], 2, 2, 8,
+                fill_rectangle(&sl->ref_cache[0][scan8[i8 * 4]], 2, 2, 8,
                                ref0, 1);
                 if (IS_SUB_8X8(sub_mb_type)) {
                     const int16_t *mv_col = l1mv[x8 * 3 + y8 * 3 * b4_stride];
                     int mx                = (scale * mv_col[0] + 128) >> 8;
                     int my                = (scale * mv_col[1] + 128) >> 8;
-                    fill_rectangle(&h->mv_cache[0][scan8[i8 * 4]], 2, 2, 8,
+                    fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2, 8,
                                    pack16to32(mx, my), 4);
-                    fill_rectangle(&h->mv_cache[1][scan8[i8 * 4]], 2, 2, 8,
+                    fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2, 8,
                                    pack16to32(mx - mv_col[0], my - mv_col[1]), 4);
                 } else {
                     for (i4 = 0; i4 < 4; i4++) {
                         const int16_t *mv_col = l1mv[x8 * 2 + (i4 & 1) +
                                                      (y8 * 2 + (i4 >> 1)) * b4_stride];
-                        int16_t *mv_l0 = h->mv_cache[0][scan8[i8 * 4 + i4]];
+                        int16_t *mv_l0 = sl->mv_cache[0][scan8[i8 * 4 + i4]];
                         mv_l0[0] = (scale * mv_col[0] + 128) >> 8;
                         mv_l0[1] = (scale * mv_col[1] + 128) >> 8;
-                        AV_WN32A(h->mv_cache[1][scan8[i8 * 4 + i4]],
+                        AV_WN32A(sl->mv_cache[1][scan8[i8 * 4 + i4]],
                                  pack16to32(mv_l0[0] - mv_col[0],
                                             mv_l0[1] - mv_col[1]));
                     }
@@ -690,10 +699,11 @@
     }
 }
 
-void ff_h264_pred_direct_motion(H264Context *const h, int *mb_type)
+void ff_h264_pred_direct_motion(const H264Context *const h, H264SliceContext *sl,
+                                int *mb_type)
 {
-    if (h->direct_spatial_mv_pred)
-        pred_spatial_direct_motion(h, mb_type);
+    if (sl->direct_spatial_mv_pred)
+        pred_spatial_direct_motion(h, sl, mb_type);
     else
-        pred_temp_direct_motion(h, mb_type);
+        pred_temp_direct_motion(h, sl, mb_type);
 }
diff --git a/libavcodec/h264_loopfilter.c b/libavcodec/h264_loopfilter.c
index a7b6878..aed14fd 100644
--- a/libavcodec/h264_loopfilter.c
+++ b/libavcodec/h264_loopfilter.c
@@ -101,7 +101,7 @@
 static av_always_inline void filter_mb_edgev(uint8_t *pix, int stride,
                                              const int16_t bS[4],
                                              unsigned int qp, int a, int b,
-                                             H264Context *h, int intra)
+                                             const H264Context *h, int intra)
 {
     const unsigned int index_a = qp + a;
     const int alpha = alpha_table[index_a];
@@ -123,7 +123,7 @@
 static av_always_inline void filter_mb_edgecv(uint8_t *pix, int stride,
                                               const int16_t bS[4],
                                               unsigned int qp, int a, int b,
-                                              H264Context *h, int intra)
+                                              const H264Context *h, int intra)
 {
     const unsigned int index_a = qp + a;
     const int alpha = alpha_table[index_a];
@@ -142,7 +142,7 @@
     }
 }
 
-static av_always_inline void filter_mb_mbaff_edgev(H264Context *h, uint8_t *pix,
+static av_always_inline void filter_mb_mbaff_edgev(const H264Context *h, uint8_t *pix,
                                                    int stride,
                                                    const int16_t bS[7], int bsi,
                                                    int qp, int a, int b,
@@ -165,7 +165,7 @@
     }
 }
 
-static av_always_inline void filter_mb_mbaff_edgecv(H264Context *h,
+static av_always_inline void filter_mb_mbaff_edgecv(const H264Context *h,
                                                     uint8_t *pix, int stride,
                                                     const int16_t bS[7],
                                                     int bsi, int qp, int a,
@@ -191,7 +191,7 @@
 static av_always_inline void filter_mb_edgeh(uint8_t *pix, int stride,
                                              const int16_t bS[4],
                                              unsigned int qp, int a, int b,
-                                             H264Context *h, int intra)
+                                             const H264Context *h, int intra)
 {
     const unsigned int index_a = qp + a;
     const int alpha = alpha_table[index_a];
@@ -213,7 +213,7 @@
 static av_always_inline void filter_mb_edgech(uint8_t *pix, int stride,
                                               const int16_t bS[4],
                                               unsigned int qp, int a, int b,
-                                              H264Context *h, int intra)
+                                              const H264Context *h, int intra)
 {
     const unsigned int index_a = qp + a;
     const int alpha = alpha_table[index_a];
@@ -232,7 +232,8 @@
     }
 }
 
-static av_always_inline void h264_filter_mb_fast_internal(H264Context *h,
+static av_always_inline void h264_filter_mb_fast_internal(const H264Context *h,
+                                                          H264SliceContext *sl,
                                                           int mb_x, int mb_y,
                                                           uint8_t *img_y,
                                                           uint8_t *img_cb,
@@ -245,18 +246,18 @@
     int chroma444 = CHROMA444(h);
     int chroma422 = CHROMA422(h);
 
-    int mb_xy = h->mb_xy;
-    int left_type= h->left_type[LTOP];
-    int top_type= h->top_type;
+    int mb_xy = sl->mb_xy;
+    int left_type = sl->left_type[LTOP];
+    int top_type  = sl->top_type;
 
     int qp_bd_offset = 6 * (h->sps.bit_depth_luma - 8);
-    int a = 52 + h->slice_alpha_c0_offset - qp_bd_offset;
-    int b = 52 + h->slice_beta_offset - qp_bd_offset;
+    int a = 52 + sl->slice_alpha_c0_offset - qp_bd_offset;
+    int b = 52 + sl->slice_beta_offset - qp_bd_offset;
 
     int mb_type = h->cur_pic.mb_type[mb_xy];
     int qp      = h->cur_pic.qscale_table[mb_xy];
     int qp0     = h->cur_pic.qscale_table[mb_xy - 1];
-    int qp1     = h->cur_pic.qscale_table[h->top_mb_xy];
+    int qp1     = h->cur_pic.qscale_table[sl->top_mb_xy];
     int qpc = get_chroma_qp( h, 0, qp );
     int qpc0 = get_chroma_qp( h, 0, qp0 );
     int qpc1 = get_chroma_qp( h, 0, qp1 );
@@ -355,9 +356,9 @@
         }
         return;
     } else {
-        LOCAL_ALIGNED_8(int16_t, bS, [2], [4][4]);
+        LOCAL_ALIGNED(8, int16_t, bS, [2], [4][4]);
         int edges;
-        if( IS_8x8DCT(mb_type) && (h->cbp&7) == 7 && !chroma444 ) {
+        if( IS_8x8DCT(mb_type) && (sl->cbp&7) == 7 && !chroma444 ) {
             edges = 4;
             AV_WN64A(bS[0][0], 0x0002000200020002ULL);
             AV_WN64A(bS[0][2], 0x0002000200020002ULL);
@@ -367,9 +368,9 @@
             int mask_edge1 = (3*(((5*mb_type)>>5)&1)) | (mb_type>>4); //(mb_type & (MB_TYPE_16x16 | MB_TYPE_8x16)) ? 3 : (mb_type & MB_TYPE_16x8) ? 1 : 0;
             int mask_edge0 = 3*((mask_edge1>>1) & ((5*left_type)>>5)&1); // (mb_type & (MB_TYPE_16x16 | MB_TYPE_8x16)) && (h->left_type[LTOP] & (MB_TYPE_16x16 | MB_TYPE_8x16)) ? 3 : 0;
             int step =  1+(mb_type>>24); //IS_8x8DCT(mb_type) ? 2 : 1;
-            edges = 4 - 3*((mb_type>>3) & !(h->cbp & 15)); //(mb_type & MB_TYPE_16x16) && !(h->cbp & 15) ? 1 : 4;
-            h->h264dsp.h264_loop_filter_strength( bS, h->non_zero_count_cache, h->ref_cache, h->mv_cache,
-                                              h->list_count==2, edges, step, mask_edge0, mask_edge1, FIELD_PICTURE(h));
+            edges = 4 - 3*((mb_type>>3) & !(sl->cbp & 15)); //(mb_type & MB_TYPE_16x16) && !(h->cbp & 15) ? 1 : 4;
+            h->h264dsp.h264_loop_filter_strength(bS, sl->non_zero_count_cache, sl->ref_cache, sl->mv_cache,
+                                                 sl->list_count==2, edges, step, mask_edge0, mask_edge1, FIELD_PICTURE(h));
         }
         if( IS_INTRA(left_type) )
             AV_WN64A(bS[0][0], 0x0004000400040004ULL);
@@ -413,66 +414,78 @@
     }
 }
 
-void ff_h264_filter_mb_fast( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize) {
+void ff_h264_filter_mb_fast(const H264Context *h, H264SliceContext *sl,
+                            int mb_x, int mb_y, uint8_t *img_y,
+                            uint8_t *img_cb, uint8_t *img_cr,
+                            unsigned int linesize, unsigned int uvlinesize)
+{
     av_assert2(!FRAME_MBAFF(h));
     if(!h->h264dsp.h264_loop_filter_strength || h->pps.chroma_qp_diff) {
-        ff_h264_filter_mb(h, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize);
+        ff_h264_filter_mb(h, sl, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize);
         return;
     }
 
 #if CONFIG_SMALL
-    h264_filter_mb_fast_internal(h, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize, h->pixel_shift);
+    h264_filter_mb_fast_internal(h, sl, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize, h->pixel_shift);
 #else
     if(h->pixel_shift){
-        h264_filter_mb_fast_internal(h, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize, 1);
+        h264_filter_mb_fast_internal(h, sl, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize, 1);
     }else{
-        h264_filter_mb_fast_internal(h, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize, 0);
+        h264_filter_mb_fast_internal(h, sl, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize, 0);
     }
 #endif
 }
 
-static int check_mv(H264Context *h, long b_idx, long bn_idx, int mvy_limit){
+static int check_mv(H264SliceContext *sl, long b_idx, long bn_idx, int mvy_limit)
+{
     int v;
 
-    v= h->ref_cache[0][b_idx] != h->ref_cache[0][bn_idx];
-    if(!v && h->ref_cache[0][b_idx]!=-1)
-        v= h->mv_cache[0][b_idx][0] - h->mv_cache[0][bn_idx][0] + 3 >= 7U |
-           FFABS( h->mv_cache[0][b_idx][1] - h->mv_cache[0][bn_idx][1] ) >= mvy_limit;
+    v = sl->ref_cache[0][b_idx] != sl->ref_cache[0][bn_idx];
+    if (!v && sl->ref_cache[0][b_idx] != -1)
+        v = sl->mv_cache[0][b_idx][0] - sl->mv_cache[0][bn_idx][0] + 3 >= 7U |
+           FFABS(sl->mv_cache[0][b_idx][1] - sl->mv_cache[0][bn_idx][1]) >= mvy_limit;
 
-    if(h->list_count==2){
+    if (sl->list_count == 2) {
         if(!v)
-            v = h->ref_cache[1][b_idx] != h->ref_cache[1][bn_idx] |
-                h->mv_cache[1][b_idx][0] - h->mv_cache[1][bn_idx][0] + 3 >= 7U |
-                FFABS( h->mv_cache[1][b_idx][1] - h->mv_cache[1][bn_idx][1] ) >= mvy_limit;
+            v = sl->ref_cache[1][b_idx] != sl->ref_cache[1][bn_idx] |
+                sl->mv_cache[1][b_idx][0] - sl->mv_cache[1][bn_idx][0] + 3 >= 7U |
+                FFABS(sl->mv_cache[1][b_idx][1] - sl->mv_cache[1][bn_idx][1]) >= mvy_limit;
 
         if(v){
-            if(h->ref_cache[0][b_idx] != h->ref_cache[1][bn_idx] |
-               h->ref_cache[1][b_idx] != h->ref_cache[0][bn_idx])
+            if (sl->ref_cache[0][b_idx] != sl->ref_cache[1][bn_idx] |
+                sl->ref_cache[1][b_idx] != sl->ref_cache[0][bn_idx])
                 return 1;
             return
-                h->mv_cache[0][b_idx][0] - h->mv_cache[1][bn_idx][0] + 3 >= 7U |
-                FFABS( h->mv_cache[0][b_idx][1] - h->mv_cache[1][bn_idx][1] ) >= mvy_limit |
-                h->mv_cache[1][b_idx][0] - h->mv_cache[0][bn_idx][0] + 3 >= 7U |
-                FFABS( h->mv_cache[1][b_idx][1] - h->mv_cache[0][bn_idx][1] ) >= mvy_limit;
+                sl->mv_cache[0][b_idx][0] - sl->mv_cache[1][bn_idx][0] + 3 >= 7U |
+                FFABS(sl->mv_cache[0][b_idx][1] - sl->mv_cache[1][bn_idx][1]) >= mvy_limit |
+                sl->mv_cache[1][b_idx][0] - sl->mv_cache[0][bn_idx][0] + 3 >= 7U |
+                FFABS(sl->mv_cache[1][b_idx][1] - sl->mv_cache[0][bn_idx][1]) >= mvy_limit;
         }
     }
 
     return v;
 }
 
-static av_always_inline void filter_mb_dir(H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize, int mb_xy, int mb_type, int mvy_limit, int first_vertical_edge_done, int a, int b, int chroma, int dir) {
+static av_always_inline void filter_mb_dir(const H264Context *h, H264SliceContext *sl,
+                                           int mb_x, int mb_y,
+                                           uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr,
+                                           unsigned int linesize, unsigned int uvlinesize,
+                                           int mb_xy, int mb_type, int mvy_limit,
+                                           int first_vertical_edge_done, int a, int b,
+                                           int chroma, int dir)
+{
     int edge;
     int chroma_qp_avg[2];
     int chroma444 = CHROMA444(h);
     int chroma422 = CHROMA422(h);
-    const int mbm_xy = dir == 0 ? mb_xy -1 : h->top_mb_xy;
-    const int mbm_type = dir == 0 ? h->left_type[LTOP] : h->top_type;
+    const int mbm_xy = dir == 0 ? mb_xy -1 : sl->top_mb_xy;
+    const int mbm_type = dir == 0 ? sl->left_type[LTOP] : sl->top_type;
 
     // how often to recheck mv-based bS when iterating between edges
     static const uint8_t mask_edge_tab[2][8]={{0,3,3,3,1,1,1,1},
                                               {0,3,1,1,3,3,3,3}};
     const int mask_edge = mask_edge_tab[dir][(mb_type>>3)&7];
-    const int edges = mask_edge== 3 && !(h->cbp&15) ? 1 : 4;
+    const int edges = mask_edge== 3 && !(sl->cbp&15) ? 1 : 4;
 
     // how often to recheck mv-based bS when iterating along each edge
     const int mask_par0 = mb_type & (MB_TYPE_16x16 | (MB_TYPE_8x16 >> dir));
@@ -492,21 +505,21 @@
             int j;
 
             for(j=0; j<2; j++, mbn_xy += h->mb_stride){
-                DECLARE_ALIGNED(8, int16_t, bS)[4];
+                LOCAL_ALIGNED(8, int16_t, bS, [4]);
                 int qp;
                 if (IS_INTRA(mb_type | h->cur_pic.mb_type[mbn_xy])) {
                     AV_WN64A(bS, 0x0003000300030003ULL);
                 } else {
                     if (!CABAC(h) && IS_8x8DCT(h->cur_pic.mb_type[mbn_xy])) {
-                        bS[0]= 1+((h->cbp_table[mbn_xy] & 0x4000)||h->non_zero_count_cache[scan8[0]+0]);
-                        bS[1]= 1+((h->cbp_table[mbn_xy] & 0x4000)||h->non_zero_count_cache[scan8[0]+1]);
-                        bS[2]= 1+((h->cbp_table[mbn_xy] & 0x8000)||h->non_zero_count_cache[scan8[0]+2]);
-                        bS[3]= 1+((h->cbp_table[mbn_xy] & 0x8000)||h->non_zero_count_cache[scan8[0]+3]);
+                        bS[0]= 1+((h->cbp_table[mbn_xy] & 0x4000) || sl->non_zero_count_cache[scan8[0]+0]);
+                        bS[1]= 1+((h->cbp_table[mbn_xy] & 0x4000) || sl->non_zero_count_cache[scan8[0]+1]);
+                        bS[2]= 1+((h->cbp_table[mbn_xy] & 0x8000) || sl->non_zero_count_cache[scan8[0]+2]);
+                        bS[3]= 1+((h->cbp_table[mbn_xy] & 0x8000) || sl->non_zero_count_cache[scan8[0]+3]);
                     }else{
                     const uint8_t *mbn_nnz = h->non_zero_count[mbn_xy] + 3*4;
                     int i;
                     for( i = 0; i < 4; i++ ) {
-                        bS[i] = 1 + !!(h->non_zero_count_cache[scan8[0]+i] | mbn_nnz[i]);
+                        bS[i] = 1 + !!(sl->non_zero_count_cache[scan8[0]+i] | mbn_nnz[i]);
                     }
                     }
                 }
@@ -516,8 +529,8 @@
                 tprintf(h->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d ls:%d uvls:%d", mb_x, mb_y, dir, edge, qp, tmp_linesize, tmp_uvlinesize);
                 { int i; for (i = 0; i < 4; i++) tprintf(h->avctx, " bS[%d]:%d", i, bS[i]); tprintf(h->avctx, "\n"); }
                 filter_mb_edgeh( &img_y[j*linesize], tmp_linesize, bS, qp, a, b, h, 0 );
-                chroma_qp_avg[0] = (h->chroma_qp[0] + get_chroma_qp(h, 0, h->cur_pic.qscale_table[mbn_xy]) + 1) >> 1;
-                chroma_qp_avg[1] = (h->chroma_qp[1] + get_chroma_qp(h, 1, h->cur_pic.qscale_table[mbn_xy]) + 1) >> 1;
+                chroma_qp_avg[0] = (sl->chroma_qp[0] + get_chroma_qp(h, 0, h->cur_pic.qscale_table[mbn_xy]) + 1) >> 1;
+                chroma_qp_avg[1] = (sl->chroma_qp[1] + get_chroma_qp(h, 1, h->cur_pic.qscale_table[mbn_xy]) + 1) >> 1;
                 if (chroma) {
                     if (chroma444) {
                         filter_mb_edgeh (&img_cb[j*uvlinesize], tmp_uvlinesize, bS, chroma_qp_avg[0], a, b, h, 0);
@@ -529,7 +542,7 @@
                 }
             }
         }else{
-            DECLARE_ALIGNED(8, int16_t, bS)[4];
+            LOCAL_ALIGNED(8, int16_t, bS, [4]);
             int qp;
 
             if( IS_INTRA(mb_type|mbm_type)) {
@@ -550,7 +563,7 @@
                     int b_idx= 8 + 4;
                     int bn_idx= b_idx - (dir ? 8:1);
 
-                    bS[0] = bS[1] = bS[2] = bS[3] = check_mv(h, 8 + 4, bn_idx, mvy_limit);
+                    bS[0] = bS[1] = bS[2] = bS[3] = check_mv(sl, 8 + 4, bn_idx, mvy_limit);
                     mv_done = 1;
                 }
                 else
@@ -562,13 +575,13 @@
                     int b_idx= 8 + 4 + x + 8*y;
                     int bn_idx= b_idx - (dir ? 8:1);
 
-                    if( h->non_zero_count_cache[b_idx] |
-                        h->non_zero_count_cache[bn_idx] ) {
+                    if (sl->non_zero_count_cache[b_idx] |
+                        sl->non_zero_count_cache[bn_idx]) {
                         bS[i] = 2;
                     }
                     else if(!mv_done)
                     {
-                        bS[i] = check_mv(h, b_idx, bn_idx, mvy_limit);
+                        bS[i] = check_mv(sl, b_idx, bn_idx, mvy_limit);
                     }
                 }
             }
@@ -581,8 +594,8 @@
                 //tprintf(h->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d, QPc:%d, QPcn:%d\n", mb_x, mb_y, dir, edge, qp, h->chroma_qp[0], h->cur_pic.qscale_table[mbn_xy]);
                 tprintf(h->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d ls:%d uvls:%d", mb_x, mb_y, dir, edge, qp, linesize, uvlinesize);
                 //{ int i; for (i = 0; i < 4; i++) tprintf(h->avctx, " bS[%d]:%d", i, bS[i]); tprintf(h->avctx, "\n"); }
-                chroma_qp_avg[0] = (h->chroma_qp[0] + get_chroma_qp(h, 0, h->cur_pic.qscale_table[mbm_xy]) + 1) >> 1;
-                chroma_qp_avg[1] = (h->chroma_qp[1] + get_chroma_qp(h, 1, h->cur_pic.qscale_table[mbm_xy]) + 1) >> 1;
+                chroma_qp_avg[0] = (sl->chroma_qp[0] + get_chroma_qp(h, 0, h->cur_pic.qscale_table[mbm_xy]) + 1) >> 1;
+                chroma_qp_avg[1] = (sl->chroma_qp[1] + get_chroma_qp(h, 1, h->cur_pic.qscale_table[mbm_xy]) + 1) >> 1;
                 if( dir == 0 ) {
                     filter_mb_edgev( &img_y[0], linesize, bS, qp, a, b, h, 1 );
                     if (chroma) {
@@ -612,7 +625,7 @@
 
     /* Calculate bS */
     for( edge = 1; edge < edges; edge++ ) {
-        DECLARE_ALIGNED(8, int16_t, bS)[4];
+        LOCAL_ALIGNED(8, int16_t, bS, [4]);
         int qp;
         const int deblock_edge = !IS_8x8DCT(mb_type & (edge<<24)); // (edge&1) && IS_8x8DCT(mb_type)
 
@@ -633,7 +646,7 @@
                 int b_idx= 8 + 4 + edge * (dir ? 8:1);
                 int bn_idx= b_idx - (dir ? 8:1);
 
-                bS[0] = bS[1] = bS[2] = bS[3] = check_mv(h, b_idx, bn_idx, mvy_limit);
+                bS[0] = bS[1] = bS[2] = bS[3] = check_mv(sl, b_idx, bn_idx, mvy_limit);
                 mv_done = 1;
             }
             else
@@ -645,13 +658,13 @@
                 int b_idx= 8 + 4 + x + 8*y;
                 int bn_idx= b_idx - (dir ? 8:1);
 
-                if( h->non_zero_count_cache[b_idx] |
-                    h->non_zero_count_cache[bn_idx] ) {
+                if (sl->non_zero_count_cache[b_idx] |
+                    sl->non_zero_count_cache[bn_idx]) {
                     bS[i] = 2;
                 }
                 else if(!mv_done)
                 {
-                    bS[i] = check_mv(h, b_idx, bn_idx, mvy_limit);
+                    bS[i] = check_mv(sl, b_idx, bn_idx, mvy_limit);
                 }
             }
 
@@ -670,11 +683,11 @@
             filter_mb_edgev( &img_y[4*edge << h->pixel_shift], linesize, bS, qp, a, b, h, 0 );
             if (chroma) {
                 if (chroma444) {
-                    filter_mb_edgev ( &img_cb[4*edge << h->pixel_shift], uvlinesize, bS, h->chroma_qp[0], a, b, h, 0);
-                    filter_mb_edgev ( &img_cr[4*edge << h->pixel_shift], uvlinesize, bS, h->chroma_qp[1], a, b, h, 0);
+                    filter_mb_edgev ( &img_cb[4*edge << h->pixel_shift], uvlinesize, bS, sl->chroma_qp[0], a, b, h, 0);
+                    filter_mb_edgev ( &img_cr[4*edge << h->pixel_shift], uvlinesize, bS, sl->chroma_qp[1], a, b, h, 0);
                 } else if( (edge&1) == 0 ) {
-                    filter_mb_edgecv( &img_cb[2*edge << h->pixel_shift], uvlinesize, bS, h->chroma_qp[0], a, b, h, 0);
-                    filter_mb_edgecv( &img_cr[2*edge << h->pixel_shift], uvlinesize, bS, h->chroma_qp[1], a, b, h, 0);
+                    filter_mb_edgecv( &img_cb[2*edge << h->pixel_shift], uvlinesize, bS, sl->chroma_qp[0], a, b, h, 0);
+                    filter_mb_edgecv( &img_cr[2*edge << h->pixel_shift], uvlinesize, bS, sl->chroma_qp[1], a, b, h, 0);
                 }
             }
         } else {
@@ -682,18 +695,18 @@
                 if (deblock_edge)
                     filter_mb_edgeh(&img_y[4*edge*linesize], linesize, bS, qp, a, b, h, 0);
                 if (chroma) {
-                    filter_mb_edgech(&img_cb[4*edge*uvlinesize], uvlinesize, bS, h->chroma_qp[0], a, b, h, 0);
-                    filter_mb_edgech(&img_cr[4*edge*uvlinesize], uvlinesize, bS, h->chroma_qp[1], a, b, h, 0);
+                    filter_mb_edgech(&img_cb[4*edge*uvlinesize], uvlinesize, bS, sl->chroma_qp[0], a, b, h, 0);
+                    filter_mb_edgech(&img_cr[4*edge*uvlinesize], uvlinesize, bS, sl->chroma_qp[1], a, b, h, 0);
                 }
             } else {
                 filter_mb_edgeh(&img_y[4*edge*linesize], linesize, bS, qp, a, b, h, 0);
                 if (chroma) {
                     if (chroma444) {
-                        filter_mb_edgeh (&img_cb[4*edge*uvlinesize], uvlinesize, bS, h->chroma_qp[0], a, b, h, 0);
-                        filter_mb_edgeh (&img_cr[4*edge*uvlinesize], uvlinesize, bS, h->chroma_qp[1], a, b, h, 0);
+                        filter_mb_edgeh (&img_cb[4*edge*uvlinesize], uvlinesize, bS, sl->chroma_qp[0], a, b, h, 0);
+                        filter_mb_edgeh (&img_cr[4*edge*uvlinesize], uvlinesize, bS, sl->chroma_qp[1], a, b, h, 0);
                     } else if ((edge&1) == 0) {
-                        filter_mb_edgech(&img_cb[2*edge*uvlinesize], uvlinesize, bS, h->chroma_qp[0], a, b, h, 0);
-                        filter_mb_edgech(&img_cr[2*edge*uvlinesize], uvlinesize, bS, h->chroma_qp[1], a, b, h, 0);
+                        filter_mb_edgech(&img_cb[2*edge*uvlinesize], uvlinesize, bS, sl->chroma_qp[0], a, b, h, 0);
+                        filter_mb_edgech(&img_cr[2*edge*uvlinesize], uvlinesize, bS, sl->chroma_qp[1], a, b, h, 0);
                     }
                 }
             }
@@ -701,25 +714,29 @@
     }
 }
 
-void ff_h264_filter_mb( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize) {
+void ff_h264_filter_mb(const H264Context *h, H264SliceContext *sl,
+                       int mb_x, int mb_y,
+                       uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr,
+                       unsigned int linesize, unsigned int uvlinesize)
+{
     const int mb_xy= mb_x + mb_y*h->mb_stride;
     const int mb_type = h->cur_pic.mb_type[mb_xy];
     const int mvy_limit = IS_INTERLACED(mb_type) ? 2 : 4;
     int first_vertical_edge_done = 0;
     int chroma = CHROMA(h) && !(CONFIG_GRAY && (h->flags&CODEC_FLAG_GRAY));
     int qp_bd_offset = 6 * (h->sps.bit_depth_luma - 8);
-    int a = 52 + h->slice_alpha_c0_offset - qp_bd_offset;
-    int b = 52 + h->slice_beta_offset - qp_bd_offset;
+    int a = 52 + sl->slice_alpha_c0_offset - qp_bd_offset;
+    int b = 52 + sl->slice_beta_offset - qp_bd_offset;
 
     if (FRAME_MBAFF(h)
             // and current and left pair do not have the same interlaced type
-            && IS_INTERLACED(mb_type^h->left_type[LTOP])
+            && IS_INTERLACED(mb_type ^ sl->left_type[LTOP])
             // and left mb is in available to us
-            && h->left_type[LTOP]) {
+            && sl->left_type[LTOP]) {
         /* First vertical edge is different in MBAFF frames
          * There are 8 different bS to compute and 2 different Qp
          */
-        DECLARE_ALIGNED(8, int16_t, bS)[8];
+        LOCAL_ALIGNED(8, int16_t, bS, [8]);
         int qp[2];
         int bqp[2];
         int rqp[2];
@@ -740,18 +757,18 @@
                     {3+4*0, 3+4*1, 3+4*2, 3+4*3, 3+4*0, 3+4*1, 3+4*2, 3+4*3},
                 }
             };
-            const uint8_t *off= offset[MB_FIELD(h)][mb_y&1];
+            const uint8_t *off= offset[MB_FIELD(sl)][mb_y&1];
             for( i = 0; i < 8; i++ ) {
-                int j= MB_FIELD(h) ? i>>2 : i&1;
-                int mbn_xy = h->left_mb_xy[LEFT(j)];
-                int mbn_type= h->left_type[LEFT(j)];
+                int j= MB_FIELD(sl) ? i>>2 : i&1;
+                int mbn_xy = sl->left_mb_xy[LEFT(j)];
+                int mbn_type = sl->left_type[LEFT(j)];
 
                 if( IS_INTRA( mbn_type ) )
                     bS[i] = 4;
                 else{
-                    bS[i] = 1 + !!(h->non_zero_count_cache[12+8*(i>>1)] |
+                    bS[i] = 1 + !!(sl->non_zero_count_cache[12+8*(i>>1)] |
                          ((!h->pps.cabac && IS_8x8DCT(mbn_type)) ?
-                            (h->cbp_table[mbn_xy] & (((MB_FIELD(h) ? (i&2) : (mb_y&1)) ? 8 : 2) << 12))
+                            (h->cbp_table[mbn_xy] & (((MB_FIELD(sl) ? (i&2) : (mb_y&1)) ? 8 : 2) << 12))
                                                                        :
                             h->non_zero_count[mbn_xy][ off[i] ]));
                 }
@@ -759,8 +776,8 @@
         }
 
         mb_qp   = h->cur_pic.qscale_table[mb_xy];
-        mbn0_qp = h->cur_pic.qscale_table[h->left_mb_xy[0]];
-        mbn1_qp = h->cur_pic.qscale_table[h->left_mb_xy[1]];
+        mbn0_qp = h->cur_pic.qscale_table[sl->left_mb_xy[0]];
+        mbn1_qp = h->cur_pic.qscale_table[sl->left_mb_xy[1]];
         qp[0] = ( mb_qp + mbn0_qp + 1 ) >> 1;
         bqp[0] = ( get_chroma_qp( h, 0, mb_qp ) +
                    get_chroma_qp( h, 0, mbn0_qp ) + 1 ) >> 1;
@@ -775,7 +792,7 @@
         /* Filter edge */
         tprintf(h->avctx, "filter mb:%d/%d MBAFF, QPy:%d/%d, QPb:%d/%d QPr:%d/%d ls:%d uvls:%d", mb_x, mb_y, qp[0], qp[1], bqp[0], bqp[1], rqp[0], rqp[1], linesize, uvlinesize);
         { int i; for (i = 0; i < 8; i++) tprintf(h->avctx, " bS[%d]:%d", i, bS[i]); tprintf(h->avctx, "\n"); }
-        if (MB_FIELD(h)) {
+        if (MB_FIELD(sl)) {
             filter_mb_mbaff_edgev ( h, img_y                ,   linesize, bS  , 1, qp [0], a, b, 1 );
             filter_mb_mbaff_edgev ( h, img_y  + 8*  linesize,   linesize, bS+4, 1, qp [1], a, b, 1 );
             if (chroma){
@@ -819,13 +836,13 @@
     {
         int dir;
         for (dir = 0; dir < 2; dir++)
-            filter_mb_dir(h, mb_x, mb_y, img_y, img_cb, img_cr, linesize,
+            filter_mb_dir(h, sl, mb_x, mb_y, img_y, img_cb, img_cr, linesize,
                           uvlinesize, mb_xy, mb_type, mvy_limit,
                           dir ? 0 : first_vertical_edge_done, a, b,
                           chroma, dir);
     }
 #else
-    filter_mb_dir(h, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize, mb_xy, mb_type, mvy_limit, first_vertical_edge_done, a, b, chroma, 0);
-    filter_mb_dir(h, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize, mb_xy, mb_type, mvy_limit, 0,                        a, b, chroma, 1);
+    filter_mb_dir(h, sl, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize, mb_xy, mb_type, mvy_limit, first_vertical_edge_done, a, b, chroma, 0);
+    filter_mb_dir(h, sl, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize, mb_xy, mb_type, mvy_limit, 0,                        a, b, chroma, 1);
 #endif
 }
diff --git a/libavcodec/h264_mb.c b/libavcodec/h264_mb.c
index dd406c7..9036919 100644
--- a/libavcodec/h264_mb.c
+++ b/libavcodec/h264_mb.c
@@ -36,10 +36,10 @@
 #include "svq3.h"
 #include "thread.h"
 
-static inline int get_lowest_part_list_y(H264Context *h, H264Picture *pic, int n,
-                                         int height, int y_offset, int list)
+static inline int get_lowest_part_list_y(H264SliceContext *sl,
+                                         int n, int height, int y_offset, int list)
 {
-    int raw_my             = h->mv_cache[list][scan8[n]][1];
+    int raw_my             = sl->mv_cache[list][scan8[n]][1];
     int filter_height_down = (raw_my & 3) ? 3 : 0;
     int full_my            = (raw_my >> 2) + y_offset;
     int bottom             = full_my + filter_height_down + height;
@@ -49,24 +49,25 @@
     return FFMAX(0, bottom);
 }
 
-static inline void get_lowest_part_y(H264Context *h, int16_t refs[2][48], int n,
+static inline void get_lowest_part_y(const H264Context *h, H264SliceContext *sl,
+                                     int16_t refs[2][48], int n,
                                      int height, int y_offset, int list0,
                                      int list1, int *nrefs)
 {
     int my;
 
-    y_offset += 16 * (h->mb_y >> MB_FIELD(h));
+    y_offset += 16 * (sl->mb_y >> MB_FIELD(sl));
 
     if (list0) {
-        int ref_n = h->ref_cache[0][scan8[n]];
-        H264Picture *ref = &h->ref_list[0][ref_n];
+        int ref_n = sl->ref_cache[0][scan8[n]];
+        H264Ref *ref = &sl->ref_list[0][ref_n];
 
         // Error resilience puts the current picture in the ref list.
         // Don't try to wait on these as it will cause a deadlock.
         // Fields can wait on each other, though.
-        if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
+        if (ref->parent->tf.progress->data != h->cur_pic.tf.progress->data ||
             (ref->reference & 3) != h->picture_structure) {
-            my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
+            my = get_lowest_part_list_y(sl, n, height, y_offset, 0);
             if (refs[0][ref_n] < 0)
                 nrefs[0] += 1;
             refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
@@ -74,12 +75,12 @@
     }
 
     if (list1) {
-        int ref_n    = h->ref_cache[1][scan8[n]];
-        H264Picture *ref = &h->ref_list[1][ref_n];
+        int ref_n    = sl->ref_cache[1][scan8[n]];
+        H264Ref *ref = &sl->ref_list[1][ref_n];
 
-        if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
+        if (ref->parent->tf.progress->data != h->cur_pic.tf.progress->data ||
             (ref->reference & 3) != h->picture_structure) {
-            my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
+            my = get_lowest_part_list_y(sl, n, height, y_offset, 1);
             if (refs[1][ref_n] < 0)
                 nrefs[1] += 1;
             refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
@@ -92,9 +93,9 @@
  *
  * @param h the H264 context
  */
-static void await_references(H264Context *h)
+static void await_references(const H264Context *h, H264SliceContext *sl)
 {
-    const int mb_xy   = h->mb_xy;
+    const int mb_xy   = sl->mb_xy;
     const int mb_type = h->cur_pic.mb_type[mb_xy];
     int16_t refs[2][48];
     int nrefs[2] = { 0 };
@@ -103,17 +104,17 @@
     memset(refs, -1, sizeof(refs));
 
     if (IS_16X16(mb_type)) {
-        get_lowest_part_y(h, refs, 0, 16, 0,
+        get_lowest_part_y(h, sl, refs, 0, 16, 0,
                           IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
     } else if (IS_16X8(mb_type)) {
-        get_lowest_part_y(h, refs, 0, 8, 0,
+        get_lowest_part_y(h, sl, refs, 0, 8, 0,
                           IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
-        get_lowest_part_y(h, refs, 8, 8, 8,
+        get_lowest_part_y(h, sl, refs, 8, 8, 8,
                           IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
     } else if (IS_8X16(mb_type)) {
-        get_lowest_part_y(h, refs, 0, 16, 0,
+        get_lowest_part_y(h, sl, refs, 0, 16, 0,
                           IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
-        get_lowest_part_y(h, refs, 4, 16, 0,
+        get_lowest_part_y(h, sl, refs, 4, 16, 0,
                           IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
     } else {
         int i;
@@ -121,30 +122,30 @@
         av_assert2(IS_8X8(mb_type));
 
         for (i = 0; i < 4; i++) {
-            const int sub_mb_type = h->sub_mb_type[i];
+            const int sub_mb_type = sl->sub_mb_type[i];
             const int n           = 4 * i;
             int y_offset          = (i & 2) << 2;
 
             if (IS_SUB_8X8(sub_mb_type)) {
-                get_lowest_part_y(h, refs, n, 8, y_offset,
+                get_lowest_part_y(h, sl, refs, n, 8, y_offset,
                                   IS_DIR(sub_mb_type, 0, 0),
                                   IS_DIR(sub_mb_type, 0, 1),
                                   nrefs);
             } else if (IS_SUB_8X4(sub_mb_type)) {
-                get_lowest_part_y(h, refs, n, 4, y_offset,
+                get_lowest_part_y(h, sl, refs, n, 4, y_offset,
                                   IS_DIR(sub_mb_type, 0, 0),
                                   IS_DIR(sub_mb_type, 0, 1),
                                   nrefs);
-                get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
+                get_lowest_part_y(h, sl, refs, n + 2, 4, y_offset + 4,
                                   IS_DIR(sub_mb_type, 0, 0),
                                   IS_DIR(sub_mb_type, 0, 1),
                                   nrefs);
             } else if (IS_SUB_4X8(sub_mb_type)) {
-                get_lowest_part_y(h, refs, n, 8, y_offset,
+                get_lowest_part_y(h, sl, refs, n, 8, y_offset,
                                   IS_DIR(sub_mb_type, 0, 0),
                                   IS_DIR(sub_mb_type, 0, 1),
                                   nrefs);
-                get_lowest_part_y(h, refs, n + 1, 8, y_offset,
+                get_lowest_part_y(h, sl, refs, n + 1, 8, y_offset,
                                   IS_DIR(sub_mb_type, 0, 0),
                                   IS_DIR(sub_mb_type, 0, 1),
                                   nrefs);
@@ -153,7 +154,7 @@
                 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,
+                    get_lowest_part_y(h, sl, refs, n + j, 4, sub_y_offset,
                                       IS_DIR(sub_mb_type, 0, 0),
                                       IS_DIR(sub_mb_type, 0, 1),
                                       nrefs);
@@ -162,37 +163,37 @@
         }
     }
 
-    for (list = h->list_count - 1; list >= 0; list--)
+    for (list = sl->list_count - 1; list >= 0; list--)
         for (ref = 0; ref < 48 && nrefs[list]; ref++) {
             int row = refs[list][ref];
             if (row >= 0) {
-                H264Picture *ref_pic  = &h->ref_list[list][ref];
+                H264Ref *ref_pic  = &sl->ref_list[list][ref];
                 int ref_field         = ref_pic->reference - 1;
-                int ref_field_picture = ref_pic->field_picture;
+                int ref_field_picture = ref_pic->parent->field_picture;
                 int pic_height        = 16 * h->mb_height >> ref_field_picture;
 
-                row <<= MB_MBAFF(h);
+                row <<= MB_MBAFF(sl);
                 nrefs[list]--;
 
                 if (!FIELD_PICTURE(h) && ref_field_picture) { // frame referencing two fields
-                    ff_thread_await_progress(&ref_pic->tf,
+                    ff_thread_await_progress(&ref_pic->parent->tf,
                                              FFMIN((row >> 1) - !(row & 1),
                                                    pic_height - 1),
                                              1);
-                    ff_thread_await_progress(&ref_pic->tf,
+                    ff_thread_await_progress(&ref_pic->parent->tf,
                                              FFMIN((row >> 1), pic_height - 1),
                                              0);
                 } else if (FIELD_PICTURE(h) && !ref_field_picture) { // field referencing one field of a frame
-                    ff_thread_await_progress(&ref_pic->tf,
+                    ff_thread_await_progress(&ref_pic->parent->tf,
                                              FFMIN(row * 2 + ref_field,
                                                    pic_height - 1),
                                              0);
                 } else if (FIELD_PICTURE(h)) {
-                    ff_thread_await_progress(&ref_pic->tf,
+                    ff_thread_await_progress(&ref_pic->parent->tf,
                                              FFMIN(row, pic_height - 1),
                                              ref_field);
                 } else {
-                    ff_thread_await_progress(&ref_pic->tf,
+                    ff_thread_await_progress(&ref_pic->parent->tf,
                                              FFMIN(row, pic_height - 1),
                                              0);
                 }
@@ -200,21 +201,22 @@
         }
 }
 
-static av_always_inline void mc_dir_part(H264Context *h, H264Picture *pic,
+static av_always_inline void mc_dir_part(const H264Context *h, H264SliceContext *sl,
+                                         H264Ref *pic,
                                          int n, int square, int height,
                                          int delta, int list,
                                          uint8_t *dest_y, uint8_t *dest_cb,
                                          uint8_t *dest_cr,
                                          int src_x_offset, int src_y_offset,
-                                         qpel_mc_func *qpix_op,
+                                         const qpel_mc_func *qpix_op,
                                          h264_chroma_mc_func chroma_op,
                                          int pixel_shift, int chroma_idc)
 {
-    const int mx      = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
-    int my            = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
+    const int mx      = sl->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
+    int my            = sl->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
     const int luma_xy = (mx & 3) + ((my & 3) << 2);
-    ptrdiff_t offset  = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
-    uint8_t *src_y    = pic->f.data[0] + offset;
+    ptrdiff_t offset  = (mx >> 2) * (1 << pixel_shift) + (my >> 2) * sl->mb_linesize;
+    uint8_t *src_y    = pic->data[0] + offset;
     uint8_t *src_cb, *src_cr;
     int extra_width  = 0;
     int extra_height = 0;
@@ -222,7 +224,7 @@
     const int full_mx    = mx >> 2;
     const int full_my    = my >> 2;
     const int pic_width  = 16 * h->mb_width;
-    const int pic_height = 16 * h->mb_height >> MB_FIELD(h);
+    const int pic_height = 16 * h->mb_height >> MB_FIELD(sl);
     int ysh;
 
     if (mx & 7)
@@ -234,119 +236,120 @@
         full_my                <          0 - extra_height ||
         full_mx + 16 /*FIXME*/ > pic_width  + extra_width  ||
         full_my + 16 /*FIXME*/ > pic_height + extra_height) {
-        h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
-                                 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
-                                 h->mb_linesize, h->mb_linesize,
+        h->vdsp.emulated_edge_mc(sl->edge_emu_buffer,
+                                 src_y - (2 << pixel_shift) - 2 * sl->mb_linesize,
+                                 sl->mb_linesize, sl->mb_linesize,
                                  16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
                                  full_my - 2, pic_width, pic_height);
-        src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
+        src_y = sl->edge_emu_buffer + (2 << pixel_shift) + 2 * sl->mb_linesize;
         emu   = 1;
     }
 
-    qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
+    qpix_op[luma_xy](dest_y, src_y, sl->mb_linesize); // FIXME try variable height perhaps?
     if (!square)
-        qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
+        qpix_op[luma_xy](dest_y + delta, src_y + delta, sl->mb_linesize);
 
     if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
         return;
 
     if (chroma_idc == 3 /* yuv444 */) {
-        src_cb = pic->f.data[1] + offset;
+        src_cb = pic->data[1] + offset;
         if (emu) {
-            h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
-                                     src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
-                                     h->mb_linesize, h->mb_linesize,
+            h->vdsp.emulated_edge_mc(sl->edge_emu_buffer,
+                                     src_cb - (2 << pixel_shift) - 2 * sl->mb_linesize,
+                                     sl->mb_linesize, sl->mb_linesize,
                                      16 + 5, 16 + 5 /*FIXME*/,
                                      full_mx - 2, full_my - 2,
                                      pic_width, pic_height);
-            src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
+            src_cb = sl->edge_emu_buffer + (2 << pixel_shift) + 2 * sl->mb_linesize;
         }
-        qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
+        qpix_op[luma_xy](dest_cb, src_cb, sl->mb_linesize); // FIXME try variable height perhaps?
         if (!square)
-            qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
+            qpix_op[luma_xy](dest_cb + delta, src_cb + delta, sl->mb_linesize);
 
-        src_cr = pic->f.data[2] + offset;
+        src_cr = pic->data[2] + offset;
         if (emu) {
-            h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
-                                     src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
-                                     h->mb_linesize, h->mb_linesize,
+            h->vdsp.emulated_edge_mc(sl->edge_emu_buffer,
+                                     src_cr - (2 << pixel_shift) - 2 * sl->mb_linesize,
+                                     sl->mb_linesize, sl->mb_linesize,
                                      16 + 5, 16 + 5 /*FIXME*/,
                                      full_mx - 2, full_my - 2,
                                      pic_width, pic_height);
-            src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
+            src_cr = sl->edge_emu_buffer + (2 << pixel_shift) + 2 * sl->mb_linesize;
         }
-        qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
+        qpix_op[luma_xy](dest_cr, src_cr, sl->mb_linesize); // FIXME try variable height perhaps?
         if (!square)
-            qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
+            qpix_op[luma_xy](dest_cr + delta, src_cr + delta, sl->mb_linesize);
         return;
     }
 
     ysh = 3 - (chroma_idc == 2 /* yuv422 */);
-    if (chroma_idc == 1 /* yuv420 */ && MB_FIELD(h)) {
+    if (chroma_idc == 1 /* yuv420 */ && MB_FIELD(sl)) {
         // chroma offset when predicting from a field of opposite parity
-        my  += 2 * ((h->mb_y & 1) - (pic->reference - 1));
+        my  += 2 * ((sl->mb_y & 1) - (pic->reference - 1));
         emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
     }
 
-    src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
-             (my >> ysh) * h->mb_uvlinesize;
-    src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
-             (my >> ysh) * h->mb_uvlinesize;
+    src_cb = pic->data[1] + ((mx >> 3) * (1 << pixel_shift)) +
+             (my >> ysh) * sl->mb_uvlinesize;
+    src_cr = pic->data[2] + ((mx >> 3) * (1 << pixel_shift)) +
+             (my >> ysh) * sl->mb_uvlinesize;
 
     if (emu) {
-        h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cb,
-                                 h->mb_uvlinesize, h->mb_uvlinesize,
+        h->vdsp.emulated_edge_mc(sl->edge_emu_buffer, src_cb,
+                                 sl->mb_uvlinesize, sl->mb_uvlinesize,
                                  9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
                                  pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
-        src_cb = h->edge_emu_buffer;
+        src_cb = sl->edge_emu_buffer;
     }
-    chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
+    chroma_op(dest_cb, src_cb, sl->mb_uvlinesize,
               height >> (chroma_idc == 1 /* yuv420 */),
-              mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
+              mx & 7, ((unsigned)my << (chroma_idc == 2 /* yuv422 */)) & 7);
 
     if (emu) {
-        h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cr,
-                                 h->mb_uvlinesize, h->mb_uvlinesize,
+        h->vdsp.emulated_edge_mc(sl->edge_emu_buffer, src_cr,
+                                 sl->mb_uvlinesize, sl->mb_uvlinesize,
                                  9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
                                  pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
-        src_cr = h->edge_emu_buffer;
+        src_cr = sl->edge_emu_buffer;
     }
-    chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
-              mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
+    chroma_op(dest_cr, src_cr, sl->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
+              mx & 7, ((unsigned)my << (chroma_idc == 2 /* yuv422 */)) & 7);
 }
 
-static av_always_inline void mc_part_std(H264Context *h, int n, int square,
+static av_always_inline void mc_part_std(const H264Context *h, H264SliceContext *sl,
+                                         int n, int square,
                                          int height, int delta,
                                          uint8_t *dest_y, uint8_t *dest_cb,
                                          uint8_t *dest_cr,
                                          int x_offset, int y_offset,
-                                         qpel_mc_func *qpix_put,
+                                         const qpel_mc_func *qpix_put,
                                          h264_chroma_mc_func chroma_put,
-                                         qpel_mc_func *qpix_avg,
+                                         const qpel_mc_func *qpix_avg,
                                          h264_chroma_mc_func chroma_avg,
                                          int list0, int list1,
                                          int pixel_shift, int chroma_idc)
 {
-    qpel_mc_func *qpix_op         = qpix_put;
+    const qpel_mc_func *qpix_op   = qpix_put;
     h264_chroma_mc_func chroma_op = chroma_put;
 
-    dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
+    dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * sl->mb_linesize;
     if (chroma_idc == 3 /* yuv444 */) {
-        dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
-        dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
+        dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * sl->mb_linesize;
+        dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * sl->mb_linesize;
     } else if (chroma_idc == 2 /* yuv422 */) {
-        dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
-        dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
+        dest_cb += (x_offset << pixel_shift) + 2 * y_offset * sl->mb_uvlinesize;
+        dest_cr += (x_offset << pixel_shift) + 2 * y_offset * sl->mb_uvlinesize;
     } else { /* yuv420 */
-        dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
-        dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
+        dest_cb += (x_offset << pixel_shift) + y_offset * sl->mb_uvlinesize;
+        dest_cr += (x_offset << pixel_shift) + y_offset * sl->mb_uvlinesize;
     }
-    x_offset += 8 * h->mb_x;
-    y_offset += 8 * (h->mb_y >> MB_FIELD(h));
+    x_offset += 8 * sl->mb_x;
+    y_offset += 8 * (sl->mb_y >> MB_FIELD(sl));
 
     if (list0) {
-        H264Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
-        mc_dir_part(h, ref, n, square, height, delta, 0,
+        H264Ref *ref = &sl->ref_list[0][sl->ref_cache[0][scan8[n]]];
+        mc_dir_part(h, sl, ref, n, square, height, delta, 0,
                     dest_y, dest_cb, dest_cr, x_offset, y_offset,
                     qpix_op, chroma_op, pixel_shift, chroma_idc);
 
@@ -355,19 +358,20 @@
     }
 
     if (list1) {
-        H264Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
-        mc_dir_part(h, ref, n, square, height, delta, 1,
+        H264Ref *ref = &sl->ref_list[1][sl->ref_cache[1][scan8[n]]];
+        mc_dir_part(h, sl, ref, n, square, height, delta, 1,
                     dest_y, dest_cb, dest_cr, x_offset, y_offset,
                     qpix_op, chroma_op, pixel_shift, chroma_idc);
     }
 }
 
-static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
+static av_always_inline void mc_part_weighted(const H264Context *h, H264SliceContext *sl,
+                                              int n, int square,
                                               int height, int delta,
                                               uint8_t *dest_y, uint8_t *dest_cb,
                                               uint8_t *dest_cr,
                                               int x_offset, int y_offset,
-                                              qpel_mc_func *qpix_put,
+                                              const qpel_mc_func *qpix_put,
                                               h264_chroma_mc_func chroma_put,
                                               h264_weight_func luma_weight_op,
                                               h264_weight_func chroma_weight_op,
@@ -378,128 +382,130 @@
 {
     int chroma_height;
 
-    dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
+    dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * sl->mb_linesize;
     if (chroma_idc == 3 /* yuv444 */) {
         chroma_height     = height;
         chroma_weight_avg = luma_weight_avg;
         chroma_weight_op  = luma_weight_op;
-        dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
-        dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
+        dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * sl->mb_linesize;
+        dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * sl->mb_linesize;
     } else if (chroma_idc == 2 /* yuv422 */) {
         chroma_height = height;
-        dest_cb      += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
-        dest_cr      += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
+        dest_cb      += (x_offset << pixel_shift) + 2 * y_offset * sl->mb_uvlinesize;
+        dest_cr      += (x_offset << pixel_shift) + 2 * y_offset * sl->mb_uvlinesize;
     } else { /* yuv420 */
         chroma_height = height >> 1;
-        dest_cb      += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
-        dest_cr      += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
+        dest_cb      += (x_offset << pixel_shift) + y_offset * sl->mb_uvlinesize;
+        dest_cr      += (x_offset << pixel_shift) + y_offset * sl->mb_uvlinesize;
     }
-    x_offset += 8 * h->mb_x;
-    y_offset += 8 * (h->mb_y >> MB_FIELD(h));
+    x_offset += 8 * sl->mb_x;
+    y_offset += 8 * (sl->mb_y >> MB_FIELD(sl));
 
     if (list0 && list1) {
         /* don't optimize for luma-only case, since B-frames usually
          * use implicit weights => chroma too. */
-        uint8_t *tmp_cb = h->bipred_scratchpad;
-        uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
-        uint8_t *tmp_y  = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
-        int refn0       = h->ref_cache[0][scan8[n]];
-        int refn1       = h->ref_cache[1][scan8[n]];
+        uint8_t *tmp_cb = sl->bipred_scratchpad;
+        uint8_t *tmp_cr = sl->bipred_scratchpad + (16 << pixel_shift);
+        uint8_t *tmp_y  = sl->bipred_scratchpad + 16 * sl->mb_uvlinesize;
+        int refn0       = sl->ref_cache[0][scan8[n]];
+        int refn1       = sl->ref_cache[1][scan8[n]];
 
-        mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
+        mc_dir_part(h, sl, &sl->ref_list[0][refn0], n, square, height, delta, 0,
                     dest_y, dest_cb, dest_cr,
                     x_offset, y_offset, qpix_put, chroma_put,
                     pixel_shift, chroma_idc);
-        mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
+        mc_dir_part(h, sl, &sl->ref_list[1][refn1], n, square, height, delta, 1,
                     tmp_y, tmp_cb, tmp_cr,
                     x_offset, y_offset, qpix_put, chroma_put,
                     pixel_shift, chroma_idc);
 
-        if (h->use_weight == 2) {
-            int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
+        if (sl->use_weight == 2) {
+            int weight0 = sl->implicit_weight[refn0][refn1][sl->mb_y & 1];
             int weight1 = 64 - weight0;
-            luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
+            luma_weight_avg(dest_y, tmp_y, sl->mb_linesize,
                             height, 5, weight0, weight1, 0);
             if (!CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
-                chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
+                chroma_weight_avg(dest_cb, tmp_cb, sl->mb_uvlinesize,
                                   chroma_height, 5, weight0, weight1, 0);
-                chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
+                chroma_weight_avg(dest_cr, tmp_cr, sl->mb_uvlinesize,
                                   chroma_height, 5, weight0, weight1, 0);
             }
         } else {
-            luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
-                            h->luma_log2_weight_denom,
-                            h->luma_weight[refn0][0][0],
-                            h->luma_weight[refn1][1][0],
-                            h->luma_weight[refn0][0][1] +
-                            h->luma_weight[refn1][1][1]);
+            luma_weight_avg(dest_y, tmp_y, sl->mb_linesize, height,
+                            sl->luma_log2_weight_denom,
+                            sl->luma_weight[refn0][0][0],
+                            sl->luma_weight[refn1][1][0],
+                            sl->luma_weight[refn0][0][1] +
+                            sl->luma_weight[refn1][1][1]);
             if (!CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
-                chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
-                                  h->chroma_log2_weight_denom,
-                                  h->chroma_weight[refn0][0][0][0],
-                                  h->chroma_weight[refn1][1][0][0],
-                                  h->chroma_weight[refn0][0][0][1] +
-                                  h->chroma_weight[refn1][1][0][1]);
-                chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
-                                  h->chroma_log2_weight_denom,
-                                  h->chroma_weight[refn0][0][1][0],
-                                  h->chroma_weight[refn1][1][1][0],
-                                  h->chroma_weight[refn0][0][1][1] +
-                                  h->chroma_weight[refn1][1][1][1]);
+                chroma_weight_avg(dest_cb, tmp_cb, sl->mb_uvlinesize, chroma_height,
+                                  sl->chroma_log2_weight_denom,
+                                  sl->chroma_weight[refn0][0][0][0],
+                                  sl->chroma_weight[refn1][1][0][0],
+                                  sl->chroma_weight[refn0][0][0][1] +
+                                  sl->chroma_weight[refn1][1][0][1]);
+                chroma_weight_avg(dest_cr, tmp_cr, sl->mb_uvlinesize, chroma_height,
+                                  sl->chroma_log2_weight_denom,
+                                  sl->chroma_weight[refn0][0][1][0],
+                                  sl->chroma_weight[refn1][1][1][0],
+                                  sl->chroma_weight[refn0][0][1][1] +
+                                  sl->chroma_weight[refn1][1][1][1]);
             }
         }
     } else {
         int list     = list1 ? 1 : 0;
-        int refn     = h->ref_cache[list][scan8[n]];
-        H264Picture *ref = &h->ref_list[list][refn];
-        mc_dir_part(h, ref, n, square, height, delta, list,
+        int refn     = sl->ref_cache[list][scan8[n]];
+        H264Ref *ref = &sl->ref_list[list][refn];
+        mc_dir_part(h, sl, ref, n, square, height, delta, list,
                     dest_y, dest_cb, dest_cr, x_offset, y_offset,
                     qpix_put, chroma_put, pixel_shift, chroma_idc);
 
-        luma_weight_op(dest_y, h->mb_linesize, height,
-                       h->luma_log2_weight_denom,
-                       h->luma_weight[refn][list][0],
-                       h->luma_weight[refn][list][1]);
+        luma_weight_op(dest_y, sl->mb_linesize, height,
+                       sl->luma_log2_weight_denom,
+                       sl->luma_weight[refn][list][0],
+                       sl->luma_weight[refn][list][1]);
         if (!CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
-            if (h->use_weight_chroma) {
-                chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
-                                 h->chroma_log2_weight_denom,
-                                 h->chroma_weight[refn][list][0][0],
-                                 h->chroma_weight[refn][list][0][1]);
-                chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
-                                 h->chroma_log2_weight_denom,
-                                 h->chroma_weight[refn][list][1][0],
-                                 h->chroma_weight[refn][list][1][1]);
+            if (sl->use_weight_chroma) {
+                chroma_weight_op(dest_cb, sl->mb_uvlinesize, chroma_height,
+                                 sl->chroma_log2_weight_denom,
+                                 sl->chroma_weight[refn][list][0][0],
+                                 sl->chroma_weight[refn][list][0][1]);
+                chroma_weight_op(dest_cr, sl->mb_uvlinesize, chroma_height,
+                                 sl->chroma_log2_weight_denom,
+                                 sl->chroma_weight[refn][list][1][0],
+                                 sl->chroma_weight[refn][list][1][1]);
             }
         }
     }
 }
 
-static av_always_inline void prefetch_motion(H264Context *h, int list,
-                                             int pixel_shift, int chroma_idc)
+static av_always_inline void prefetch_motion(const H264Context *h, H264SliceContext *sl,
+                                             int list, int pixel_shift,
+                                             int chroma_idc)
 {
     /* fetch pixels for estimated mv 4 macroblocks ahead
      * optimized for 64byte cache lines */
-    const int refn = h->ref_cache[list][scan8[0]];
+    const int refn = sl->ref_cache[list][scan8[0]];
     if (refn >= 0) {
-        const int mx  = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
-        const int my  = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
-        uint8_t **src = h->ref_list[list][refn].f.data;
-        int off       = (mx << pixel_shift) +
-                        (my + (h->mb_x & 3) * 4) * h->mb_linesize +
+        const int mx  = (sl->mv_cache[list][scan8[0]][0] >> 2) + 16 * sl->mb_x + 8;
+        const int my  = (sl->mv_cache[list][scan8[0]][1] >> 2) + 16 * sl->mb_y;
+        uint8_t **src = sl->ref_list[list][refn].data;
+        int off       =  mx * (1<< pixel_shift) +
+                        (my + (sl->mb_x & 3) * 4) * sl->mb_linesize +
                         (64 << pixel_shift);
-        h->vdsp.prefetch(src[0] + off, h->linesize, 4);
+        h->vdsp.prefetch(src[0] + off, sl->linesize, 4);
         if (chroma_idc == 3 /* yuv444 */) {
-            h->vdsp.prefetch(src[1] + off, h->linesize, 4);
-            h->vdsp.prefetch(src[2] + off, h->linesize, 4);
+            h->vdsp.prefetch(src[1] + off, sl->linesize, 4);
+            h->vdsp.prefetch(src[2] + off, sl->linesize, 4);
         } else {
-            off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (h->mb_x&7))*h->uvlinesize;
+            off= ((mx>>1)+64) * (1<<pixel_shift) + ((my>>1) + (sl->mb_x&7))*sl->uvlinesize;
             h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
         }
     }
 }
 
-static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
+static av_always_inline void xchg_mb_border(const H264Context *h, H264SliceContext *sl,
+                                            uint8_t *src_y,
                                             uint8_t *src_cb, uint8_t *src_cr,
                                             int linesize, int uvlinesize,
                                             int xchg, int chroma444,
@@ -512,28 +518,28 @@
     uint8_t *top_border;
 
     if (!simple && FRAME_MBAFF(h)) {
-        if (h->mb_y & 1) {
-            if (!MB_MBAFF(h))
+        if (sl->mb_y & 1) {
+            if (!MB_MBAFF(sl))
                 return;
         } else {
-            top_idx = MB_MBAFF(h) ? 0 : 1;
+            top_idx = MB_MBAFF(sl) ? 0 : 1;
         }
     }
 
-    if (h->deblocking_filter == 2) {
-        deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
-        deblock_top     = h->top_type;
+    if (sl->deblocking_filter == 2) {
+        deblock_topleft = h->slice_table[sl->mb_xy - 1 - h->mb_stride] == sl->slice_num;
+        deblock_top     = sl->top_type;
     } else {
-        deblock_topleft = (h->mb_x > 0);
-        deblock_top     = (h->mb_y > !!MB_FIELD(h));
+        deblock_topleft = (sl->mb_x > 0);
+        deblock_top     = (sl->mb_y > !!MB_FIELD(sl));
     }
 
     src_y  -= linesize   + 1 + pixel_shift;
     src_cb -= uvlinesize + 1 + pixel_shift;
     src_cr -= uvlinesize + 1 + pixel_shift;
 
-    top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
-    top_border    = h->top_borders[top_idx][h->mb_x];
+    top_border_m1 = sl->top_borders[top_idx][sl->mb_x - 1];
+    top_border    = sl->top_borders[top_idx][sl->mb_x];
 
 #define XCHG(a, b, xchg)                        \
     if (pixel_shift) {                          \
@@ -555,8 +561,8 @@
         }
         XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
         XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
-        if (h->mb_x + 1 < h->mb_width) {
-            XCHG(h->top_borders[top_idx][h->mb_x + 1],
+        if (sl->mb_x + 1 < h->mb_width) {
+            XCHG(sl->top_borders[top_idx][sl->mb_x + 1],
                  src_y + (17 << pixel_shift), 1);
         }
         if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
@@ -569,9 +575,9 @@
                 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
                 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
                 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
-                if (h->mb_x + 1 < h->mb_width) {
-                    XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
-                    XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
+                if (sl->mb_x + 1 < h->mb_width) {
+                    XCHG(sl->top_borders[top_idx][sl->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
+                    XCHG(sl->top_borders[top_idx][sl->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
                 }
             } else {
                 if (deblock_topleft) {
@@ -603,19 +609,20 @@
         AV_WN16A(mb + index, value);
 }
 
-static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
+static av_always_inline void hl_decode_mb_predict_luma(const H264Context *h,
+                                                       H264SliceContext *sl,
                                                        int mb_type, int is_h264,
                                                        int simple,
                                                        int transform_bypass,
                                                        int pixel_shift,
-                                                       int *block_offset,
+                                                       const int *block_offset,
                                                        int linesize,
                                                        uint8_t *dest_y, int p)
 {
     void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
     void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
     int i;
-    int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
+    int qscale = p == 0 ? sl->qscale : sl->chroma_qp[p - 1];
     block_offset += 16 * p;
     if (IS_INTRA4x4(mb_type)) {
         if (IS_8x8DCT(mb_type)) {
@@ -628,23 +635,23 @@
             }
             for (i = 0; i < 16; i += 4) {
                 uint8_t *const ptr = dest_y + block_offset[i];
-                const int dir      = h->intra4x4_pred_mode_cache[scan8[i]];
+                const int dir      = sl->intra4x4_pred_mode_cache[scan8[i]];
                 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
                     if (h->x264_build != -1) {
-                        h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
+                        h->hpc.pred8x8l_add[dir](ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), linesize);
                     } else
-                        h->hpc.pred8x8l_filter_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift),
-                                                        (h-> topleft_samples_available << i) & 0x8000,
-                                                        (h->topright_samples_available << i) & 0x4000, linesize);
+                        h->hpc.pred8x8l_filter_add[dir](ptr, sl->mb + (i * 16 + p * 256 << pixel_shift),
+                                                        (sl-> topleft_samples_available << i) & 0x8000,
+                                                        (sl->topright_samples_available << i) & 0x4000, linesize);
                 } else {
-                    const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
-                    h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
-                                         (h->topright_samples_available << i) & 0x4000, linesize);
+                    const int nnz = sl->non_zero_count_cache[scan8[i + p * 16]];
+                    h->hpc.pred8x8l[dir](ptr, (sl->topleft_samples_available << i) & 0x8000,
+                                         (sl->topright_samples_available << i) & 0x4000, linesize);
                     if (nnz) {
-                        if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
-                            idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
+                        if (nnz == 1 && dctcoef_get(sl->mb, pixel_shift, i * 16 + p * 256))
+                            idct_dc_add(ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), linesize);
                         else
-                            idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
+                            idct_add(ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), linesize);
                     }
                 }
             }
@@ -658,17 +665,17 @@
             }
             for (i = 0; i < 16; i++) {
                 uint8_t *const ptr = dest_y + block_offset[i];
-                const int dir      = h->intra4x4_pred_mode_cache[scan8[i]];
+                const int dir      = sl->intra4x4_pred_mode_cache[scan8[i]];
 
                 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
-                    h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
+                    h->hpc.pred4x4_add[dir](ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), linesize);
                 } else {
                     uint8_t *topright;
                     int nnz, tr;
                     uint64_t tr_high;
                     if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
-                        const int topright_avail = (h->topright_samples_available << i) & 0x8000;
-                        av_assert2(h->mb_y || linesize <= block_offset[i]);
+                        const int topright_avail = (sl->topright_samples_available << i) & 0x8000;
+                        av_assert2(sl->mb_y || linesize <= block_offset[i]);
                         if (!topright_avail) {
                             if (pixel_shift) {
                                 tr_high  = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
@@ -683,26 +690,26 @@
                         topright = NULL;
 
                     h->hpc.pred4x4[dir](ptr, topright, linesize);
-                    nnz = h->non_zero_count_cache[scan8[i + p * 16]];
+                    nnz = sl->non_zero_count_cache[scan8[i + p * 16]];
                     if (nnz) {
                         if (is_h264) {
-                            if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
-                                idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
+                            if (nnz == 1 && dctcoef_get(sl->mb, pixel_shift, i * 16 + p * 256))
+                                idct_dc_add(ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), linesize);
                             else
-                                idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
+                                idct_add(ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), linesize);
                         } else if (CONFIG_SVQ3_DECODER)
-                            ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
+                            ff_svq3_add_idct_c(ptr, sl->mb + i * 16 + p * 256, linesize, qscale, 0);
                     }
                 }
             }
         }
     } else {
-        h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
+        h->hpc.pred16x16[sl->intra16x16_pred_mode](dest_y, linesize);
         if (is_h264) {
-            if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
+            if (sl->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
                 if (!transform_bypass)
-                    h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
-                                                         h->mb_luma_dc[p],
+                    h->h264dsp.h264_luma_dc_dequant_idct(sl->mb + (p * 256 << pixel_shift),
+                                                         sl->mb_luma_dc[p],
                                                          h->dequant4_coeff[p][qscale][0]);
                 else {
                     static const uint8_t dc_mapping[16] = {
@@ -712,23 +719,24 @@
                         10 * 16, 11 * 16, 14 * 16, 15 * 16
                     };
                     for (i = 0; i < 16; i++)
-                        dctcoef_set(h->mb + (p * 256 << pixel_shift),
+                        dctcoef_set(sl->mb + (p * 256 << pixel_shift),
                                     pixel_shift, dc_mapping[i],
-                                    dctcoef_get(h->mb_luma_dc[p],
+                                    dctcoef_get(sl->mb_luma_dc[p],
                                                 pixel_shift, i));
                 }
             }
         } else if (CONFIG_SVQ3_DECODER)
-            ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
-                                           h->mb_luma_dc[p], qscale);
+            ff_svq3_luma_dc_dequant_idct_c(sl->mb + p * 256,
+                                           sl->mb_luma_dc[p], qscale);
     }
 }
 
-static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
+static av_always_inline void hl_decode_mb_idct_luma(const H264Context *h, H264SliceContext *sl,
+                                                    int mb_type,
                                                     int is_h264, int simple,
                                                     int transform_bypass,
                                                     int pixel_shift,
-                                                    int *block_offset,
+                                                    const int *block_offset,
                                                     int linesize,
                                                     uint8_t *dest_y, int p)
 {
@@ -740,55 +748,55 @@
             if (IS_INTRA16x16(mb_type)) {
                 if (transform_bypass) {
                     if (h->sps.profile_idc == 244 &&
-                        (h->intra16x16_pred_mode == VERT_PRED8x8 ||
-                         h->intra16x16_pred_mode == HOR_PRED8x8)) {
-                        h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
-                                                                      h->mb + (p * 256 << pixel_shift),
+                        (sl->intra16x16_pred_mode == VERT_PRED8x8 ||
+                         sl->intra16x16_pred_mode == HOR_PRED8x8)) {
+                        h->hpc.pred16x16_add[sl->intra16x16_pred_mode](dest_y, block_offset,
+                                                                      sl->mb + (p * 256 << pixel_shift),
                                                                       linesize);
                     } else {
                         for (i = 0; i < 16; i++)
-                            if (h->non_zero_count_cache[scan8[i + p * 16]] ||
-                                dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
+                            if (sl->non_zero_count_cache[scan8[i + p * 16]] ||
+                                dctcoef_get(sl->mb, pixel_shift, i * 16 + p * 256))
                                 h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
-                                                                  h->mb + (i * 16 + p * 256 << pixel_shift),
+                                                                  sl->mb + (i * 16 + p * 256 << pixel_shift),
                                                                   linesize);
                     }
                 } else {
                     h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
-                                                    h->mb + (p * 256 << pixel_shift),
+                                                    sl->mb + (p * 256 << pixel_shift),
                                                     linesize,
-                                                    h->non_zero_count_cache + p * 5 * 8);
+                                                    sl->non_zero_count_cache + p * 5 * 8);
                 }
-            } else if (h->cbp & 15) {
+            } else if (sl->cbp & 15) {
                 if (transform_bypass) {
                     const int di = IS_8x8DCT(mb_type) ? 4 : 1;
                     idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear
                                                   : h->h264dsp.h264_add_pixels4_clear;
                     for (i = 0; i < 16; i += di)
-                        if (h->non_zero_count_cache[scan8[i + p * 16]])
+                        if (sl->non_zero_count_cache[scan8[i + p * 16]])
                             idct_add(dest_y + block_offset[i],
-                                     h->mb + (i * 16 + p * 256 << pixel_shift),
+                                     sl->mb + (i * 16 + p * 256 << pixel_shift),
                                      linesize);
                 } else {
                     if (IS_8x8DCT(mb_type))
                         h->h264dsp.h264_idct8_add4(dest_y, block_offset,
-                                                   h->mb + (p * 256 << pixel_shift),
+                                                   sl->mb + (p * 256 << pixel_shift),
                                                    linesize,
-                                                   h->non_zero_count_cache + p * 5 * 8);
+                                                   sl->non_zero_count_cache + p * 5 * 8);
                     else
                         h->h264dsp.h264_idct_add16(dest_y, block_offset,
-                                                   h->mb + (p * 256 << pixel_shift),
+                                                   sl->mb + (p * 256 << pixel_shift),
                                                    linesize,
-                                                   h->non_zero_count_cache + p * 5 * 8);
+                                                   sl->non_zero_count_cache + p * 5 * 8);
                 }
             }
         } else if (CONFIG_SVQ3_DECODER) {
             for (i = 0; i < 16; i++)
-                if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
+                if (sl->non_zero_count_cache[scan8[i + p * 16]] || sl->mb[i * 16 + p * 256]) {
                     // FIXME benchmark weird rule, & below
                     uint8_t *const ptr = dest_y + block_offset[i];
-                    ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
-                                       h->qscale, IS_INTRA(mb_type) ? 1 : 0);
+                    ff_svq3_add_idct_c(ptr, sl->mb + i * 16 + p * 256, linesize,
+                                       sl->qscale, IS_INTRA(mb_type) ? 1 : 0);
                 }
         }
     }
@@ -806,22 +814,22 @@
 #define SIMPLE 0
 #include "h264_mb_template.c"
 
-void ff_h264_hl_decode_mb(H264Context *h)
+void ff_h264_hl_decode_mb(const H264Context *h, H264SliceContext *sl)
 {
-    const int mb_xy   = h->mb_xy;
+    const int mb_xy   = sl->mb_xy;
     const int mb_type = h->cur_pic.mb_type[mb_xy];
-    int is_complex    = CONFIG_SMALL || h->is_complex ||
-                        IS_INTRA_PCM(mb_type) || h->qscale == 0;
+    int is_complex    = CONFIG_SMALL || sl->is_complex ||
+                        IS_INTRA_PCM(mb_type) || sl->qscale == 0;
 
     if (CHROMA444(h)) {
         if (is_complex || h->pixel_shift)
-            hl_decode_mb_444_complex(h);
+            hl_decode_mb_444_complex(h, sl);
         else
-            hl_decode_mb_444_simple_8(h);
+            hl_decode_mb_444_simple_8(h, sl);
     } else if (is_complex) {
-        hl_decode_mb_complex(h);
+        hl_decode_mb_complex(h, sl);
     } else if (h->pixel_shift) {
-        hl_decode_mb_simple_16(h);
+        hl_decode_mb_simple_16(h, sl);
     } else
-        hl_decode_mb_simple_8(h);
+        hl_decode_mb_simple_8(h, sl);
 }
diff --git a/libavcodec/h264_mb_template.c b/libavcodec/h264_mb_template.c
index 7c9d72b..685535f 100644
--- a/libavcodec/h264_mb_template.c
+++ b/libavcodec/h264_mb_template.c
@@ -40,62 +40,62 @@
 #define CHROMA_IDC 2
 #include "h264_mc_template.c"
 
-static av_noinline void FUNC(hl_decode_mb)(H264Context *h)
+static av_noinline void FUNC(hl_decode_mb)(const H264Context *h, H264SliceContext *sl)
 {
-    const int mb_x    = h->mb_x;
-    const int mb_y    = h->mb_y;
-    const int mb_xy   = h->mb_xy;
+    const int mb_x    = sl->mb_x;
+    const int mb_y    = sl->mb_y;
+    const int mb_xy   = sl->mb_xy;
     const int mb_type = h->cur_pic.mb_type[mb_xy];
     uint8_t *dest_y, *dest_cb, *dest_cr;
     int linesize, uvlinesize /*dct_offset*/;
     int i, j;
-    int *block_offset = &h->block_offset[0];
-    const int transform_bypass = !SIMPLE && (h->qscale == 0 && h->sps.transform_bypass);
+    const int *block_offset = &h->block_offset[0];
+    const int transform_bypass = !SIMPLE && (sl->qscale == 0 && h->sps.transform_bypass);
     /* is_h264 should always be true if SVQ3 is disabled. */
     const int is_h264 = !CONFIG_SVQ3_DECODER || SIMPLE || h->avctx->codec_id == AV_CODEC_ID_H264;
     void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
     const int block_h   = 16 >> h->chroma_y_shift;
     const int chroma422 = CHROMA422(h);
 
-    dest_y  = h->cur_pic.f.data[0] + ((mb_x << PIXEL_SHIFT)     + mb_y * h->linesize)  * 16;
-    dest_cb = h->cur_pic.f.data[1] +  (mb_x << PIXEL_SHIFT) * 8 + mb_y * h->uvlinesize * block_h;
-    dest_cr = h->cur_pic.f.data[2] +  (mb_x << PIXEL_SHIFT) * 8 + mb_y * h->uvlinesize * block_h;
+    dest_y  = h->cur_pic.f.data[0] + ((mb_x << PIXEL_SHIFT)     + mb_y * sl->linesize)  * 16;
+    dest_cb = h->cur_pic.f.data[1] +  (mb_x << PIXEL_SHIFT) * 8 + mb_y * sl->uvlinesize * block_h;
+    dest_cr = h->cur_pic.f.data[2] +  (mb_x << PIXEL_SHIFT) * 8 + mb_y * sl->uvlinesize * block_h;
 
-    h->vdsp.prefetch(dest_y  + (h->mb_x & 3) * 4 * h->linesize   + (64 << PIXEL_SHIFT), h->linesize,       4);
-    h->vdsp.prefetch(dest_cb + (h->mb_x & 7)     * h->uvlinesize + (64 << PIXEL_SHIFT), dest_cr - dest_cb, 2);
+    h->vdsp.prefetch(dest_y  + (sl->mb_x & 3) * 4 * sl->linesize   + (64 << PIXEL_SHIFT), sl->linesize,       4);
+    h->vdsp.prefetch(dest_cb + (sl->mb_x & 7)     * sl->uvlinesize + (64 << PIXEL_SHIFT), dest_cr - dest_cb, 2);
 
-    h->list_counts[mb_xy] = h->list_count;
+    h->list_counts[mb_xy] = sl->list_count;
 
-    if (!SIMPLE && MB_FIELD(h)) {
-        linesize     = h->mb_linesize = h->linesize * 2;
-        uvlinesize   = h->mb_uvlinesize = h->uvlinesize * 2;
+    if (!SIMPLE && MB_FIELD(sl)) {
+        linesize     = sl->mb_linesize = sl->linesize * 2;
+        uvlinesize   = sl->mb_uvlinesize = sl->uvlinesize * 2;
         block_offset = &h->block_offset[48];
         if (mb_y & 1) { // FIXME move out of this function?
-            dest_y  -= h->linesize * 15;
-            dest_cb -= h->uvlinesize * (block_h - 1);
-            dest_cr -= h->uvlinesize * (block_h - 1);
+            dest_y  -= sl->linesize * 15;
+            dest_cb -= sl->uvlinesize * (block_h - 1);
+            dest_cr -= sl->uvlinesize * (block_h - 1);
         }
         if (FRAME_MBAFF(h)) {
             int list;
-            for (list = 0; list < h->list_count; list++) {
+            for (list = 0; list < sl->list_count; list++) {
                 if (!USES_LIST(mb_type, list))
                     continue;
                 if (IS_16X16(mb_type)) {
-                    int8_t *ref = &h->ref_cache[list][scan8[0]];
-                    fill_rectangle(ref, 4, 4, 8, (16 + *ref) ^ (h->mb_y & 1), 1);
+                    int8_t *ref = &sl->ref_cache[list][scan8[0]];
+                    fill_rectangle(ref, 4, 4, 8, (16 + *ref) ^ (sl->mb_y & 1), 1);
                 } else {
                     for (i = 0; i < 16; i += 4) {
-                        int ref = h->ref_cache[list][scan8[i]];
+                        int ref = sl->ref_cache[list][scan8[i]];
                         if (ref >= 0)
-                            fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2,
-                                           8, (16 + ref) ^ (h->mb_y & 1), 1);
+                            fill_rectangle(&sl->ref_cache[list][scan8[i]], 2, 2,
+                                           8, (16 + ref) ^ (sl->mb_y & 1), 1);
                     }
                 }
             }
         }
     } else {
-        linesize   = h->mb_linesize   = h->linesize;
-        uvlinesize = h->mb_uvlinesize = h->uvlinesize;
+        linesize   = sl->mb_linesize   = sl->linesize;
+        uvlinesize = sl->mb_uvlinesize = sl->uvlinesize;
         // dct_offset = s->linesize * 16;
     }
 
@@ -104,7 +104,7 @@
         if (PIXEL_SHIFT) {
             int j;
             GetBitContext gb;
-            init_get_bits(&gb, h->intra_pcm_ptr,
+            init_get_bits(&gb, sl->intra_pcm_ptr,
                           ff_h264_mb_sizes[h->sps.chroma_format_idc] * bit_depth);
 
             for (i = 0; i < 16; i++) {
@@ -136,7 +136,7 @@
             }
         } else {
             for (i = 0; i < 16; i++)
-                memcpy(dest_y + i * linesize, h->intra_pcm_ptr + i * 16, 16);
+                memcpy(dest_y + i * linesize, sl->intra_pcm_ptr + i * 16, 16);
             if (SIMPLE || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
                 if (!h->sps.chroma_format_idc) {
                     for (i = 0; i < 8; i++) {
@@ -144,8 +144,8 @@
                         memset(dest_cr + i * uvlinesize, 1 << (bit_depth - 1), 8);
                     }
                 } else {
-                    const uint8_t *src_cb = h->intra_pcm_ptr + 256;
-                    const uint8_t *src_cr = h->intra_pcm_ptr + 256 + block_h * 8;
+                    const uint8_t *src_cb = sl->intra_pcm_ptr + 256;
+                    const uint8_t *src_cr = sl->intra_pcm_ptr + 256 + block_h * 8;
                     for (i = 0; i < block_h; i++) {
                         memcpy(dest_cb + i * uvlinesize, src_cb + i * 8, 8);
                         memcpy(dest_cr + i * uvlinesize, src_cr + i * 8, 8);
@@ -155,31 +155,31 @@
         }
     } else {
         if (IS_INTRA(mb_type)) {
-            if (h->deblocking_filter)
-                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
+            if (sl->deblocking_filter)
+                xchg_mb_border(h, sl, dest_y, dest_cb, dest_cr, linesize,
                                uvlinesize, 1, 0, SIMPLE, PIXEL_SHIFT);
 
             if (SIMPLE || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
-                h->hpc.pred8x8[h->chroma_pred_mode](dest_cb, uvlinesize);
-                h->hpc.pred8x8[h->chroma_pred_mode](dest_cr, uvlinesize);
+                h->hpc.pred8x8[sl->chroma_pred_mode](dest_cb, uvlinesize);
+                h->hpc.pred8x8[sl->chroma_pred_mode](dest_cr, uvlinesize);
             }
 
-            hl_decode_mb_predict_luma(h, mb_type, is_h264, SIMPLE,
+            hl_decode_mb_predict_luma(h, sl, mb_type, is_h264, SIMPLE,
                                       transform_bypass, PIXEL_SHIFT,
                                       block_offset, linesize, dest_y, 0);
 
-            if (h->deblocking_filter)
-                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
+            if (sl->deblocking_filter)
+                xchg_mb_border(h, sl, dest_y, dest_cb, dest_cr, linesize,
                                uvlinesize, 0, 0, SIMPLE, PIXEL_SHIFT);
         } else if (is_h264) {
             if (chroma422) {
-                FUNC(hl_motion_422)(h, dest_y, dest_cb, dest_cr,
+                FUNC(hl_motion_422)(h, sl, dest_y, dest_cb, dest_cr,
                               h->qpel_put, h->h264chroma.put_h264_chroma_pixels_tab,
                               h->qpel_avg, h->h264chroma.avg_h264_chroma_pixels_tab,
                               h->h264dsp.weight_h264_pixels_tab,
                               h->h264dsp.biweight_h264_pixels_tab);
             } else {
-                FUNC(hl_motion_420)(h, dest_y, dest_cb, dest_cr,
+                FUNC(hl_motion_420)(h, sl, dest_y, dest_cb, dest_cr,
                               h->qpel_put, h->h264chroma.put_h264_chroma_pixels_tab,
                               h->qpel_avg, h->h264chroma.avg_h264_chroma_pixels_tab,
                               h->h264dsp.weight_h264_pixels_tab,
@@ -187,39 +187,39 @@
             }
         }
 
-        hl_decode_mb_idct_luma(h, mb_type, is_h264, SIMPLE, transform_bypass,
+        hl_decode_mb_idct_luma(h, sl, mb_type, is_h264, SIMPLE, transform_bypass,
                                PIXEL_SHIFT, block_offset, linesize, dest_y, 0);
 
         if ((SIMPLE || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) &&
-            (h->cbp & 0x30)) {
+            (sl->cbp & 0x30)) {
             uint8_t *dest[2] = { dest_cb, dest_cr };
             if (transform_bypass) {
                 if (IS_INTRA(mb_type) && h->sps.profile_idc == 244 &&
-                    (h->chroma_pred_mode == VERT_PRED8x8 ||
-                     h->chroma_pred_mode == HOR_PRED8x8)) {
-                    h->hpc.pred8x8_add[h->chroma_pred_mode](dest[0],
+                    (sl->chroma_pred_mode == VERT_PRED8x8 ||
+                     sl->chroma_pred_mode == HOR_PRED8x8)) {
+                    h->hpc.pred8x8_add[sl->chroma_pred_mode](dest[0],
                                                             block_offset + 16,
-                                                            h->mb + (16 * 16 * 1 << PIXEL_SHIFT),
+                                                            sl->mb + (16 * 16 * 1 << PIXEL_SHIFT),
                                                             uvlinesize);
-                    h->hpc.pred8x8_add[h->chroma_pred_mode](dest[1],
+                    h->hpc.pred8x8_add[sl->chroma_pred_mode](dest[1],
                                                             block_offset + 32,
-                                                            h->mb + (16 * 16 * 2 << PIXEL_SHIFT),
+                                                            sl->mb + (16 * 16 * 2 << PIXEL_SHIFT),
                                                             uvlinesize);
                 } else {
                     idct_add = h->h264dsp.h264_add_pixels4_clear;
                     for (j = 1; j < 3; j++) {
                         for (i = j * 16; i < j * 16 + 4; i++)
-                            if (h->non_zero_count_cache[scan8[i]] ||
-                                dctcoef_get(h->mb, PIXEL_SHIFT, i * 16))
+                            if (sl->non_zero_count_cache[scan8[i]] ||
+                                dctcoef_get(sl->mb, PIXEL_SHIFT, i * 16))
                                 idct_add(dest[j - 1] + block_offset[i],
-                                         h->mb + (i * 16 << PIXEL_SHIFT),
+                                         sl->mb + (i * 16 << PIXEL_SHIFT),
                                          uvlinesize);
                         if (chroma422) {
                             for (i = j * 16 + 4; i < j * 16 + 8; i++)
-                                if (h->non_zero_count_cache[scan8[i + 4]] ||
-                                    dctcoef_get(h->mb, PIXEL_SHIFT, i * 16))
+                                if (sl->non_zero_count_cache[scan8[i + 4]] ||
+                                    dctcoef_get(sl->mb, PIXEL_SHIFT, i * 16))
                                     idct_add(dest[j - 1] + block_offset[i + 4],
-                                             h->mb + (i * 16 << PIXEL_SHIFT),
+                                             sl->mb + (i * 16 << PIXEL_SHIFT),
                                              uvlinesize);
                         }
                     }
@@ -228,33 +228,33 @@
                 if (is_h264) {
                     int qp[2];
                     if (chroma422) {
-                        qp[0] = h->chroma_qp[0] + 3;
-                        qp[1] = h->chroma_qp[1] + 3;
+                        qp[0] = sl->chroma_qp[0] + 3;
+                        qp[1] = sl->chroma_qp[1] + 3;
                     } else {
-                        qp[0] = h->chroma_qp[0];
-                        qp[1] = h->chroma_qp[1];
+                        qp[0] = sl->chroma_qp[0];
+                        qp[1] = sl->chroma_qp[1];
                     }
-                    if (h->non_zero_count_cache[scan8[CHROMA_DC_BLOCK_INDEX + 0]])
-                        h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + (16 * 16 * 1 << PIXEL_SHIFT),
+                    if (sl->non_zero_count_cache[scan8[CHROMA_DC_BLOCK_INDEX + 0]])
+                        h->h264dsp.h264_chroma_dc_dequant_idct(sl->mb + (16 * 16 * 1 << PIXEL_SHIFT),
                                                                h->dequant4_coeff[IS_INTRA(mb_type) ? 1 : 4][qp[0]][0]);
-                    if (h->non_zero_count_cache[scan8[CHROMA_DC_BLOCK_INDEX + 1]])
-                        h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + (16 * 16 * 2 << PIXEL_SHIFT),
+                    if (sl->non_zero_count_cache[scan8[CHROMA_DC_BLOCK_INDEX + 1]])
+                        h->h264dsp.h264_chroma_dc_dequant_idct(sl->mb + (16 * 16 * 2 << PIXEL_SHIFT),
                                                                h->dequant4_coeff[IS_INTRA(mb_type) ? 2 : 5][qp[1]][0]);
                     h->h264dsp.h264_idct_add8(dest, block_offset,
-                                              h->mb, uvlinesize,
-                                              h->non_zero_count_cache);
+                                              sl->mb, uvlinesize,
+                                              sl->non_zero_count_cache);
                 } else if (CONFIG_SVQ3_DECODER) {
-                    h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16 * 16 * 1,
-                                                           h->dequant4_coeff[IS_INTRA(mb_type) ? 1 : 4][h->chroma_qp[0]][0]);
-                    h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16 * 16 * 2,
-                                                           h->dequant4_coeff[IS_INTRA(mb_type) ? 2 : 5][h->chroma_qp[1]][0]);
+                    h->h264dsp.h264_chroma_dc_dequant_idct(sl->mb + 16 * 16 * 1,
+                                                           h->dequant4_coeff[IS_INTRA(mb_type) ? 1 : 4][sl->chroma_qp[0]][0]);
+                    h->h264dsp.h264_chroma_dc_dequant_idct(sl->mb + 16 * 16 * 2,
+                                                           h->dequant4_coeff[IS_INTRA(mb_type) ? 2 : 5][sl->chroma_qp[1]][0]);
                     for (j = 1; j < 3; j++) {
                         for (i = j * 16; i < j * 16 + 4; i++)
-                            if (h->non_zero_count_cache[scan8[i]] || h->mb[i * 16]) {
+                            if (sl->non_zero_count_cache[scan8[i]] || sl->mb[i * 16]) {
                                 uint8_t *const ptr = dest[j - 1] + block_offset[i];
-                                ff_svq3_add_idct_c(ptr, h->mb + i * 16,
+                                ff_svq3_add_idct_c(ptr, sl->mb + i * 16,
                                                    uvlinesize,
-                                                   ff_h264_chroma_qp[0][h->qscale + 12] - 12, 2);
+                                                   ff_h264_chroma_qp[0][sl->qscale + 12] - 12, 2);
                             }
                     }
                 }
@@ -269,61 +269,61 @@
 #define CHROMA_IDC 3
 #include "h264_mc_template.c"
 
-static av_noinline void FUNC(hl_decode_mb_444)(H264Context *h)
+static av_noinline void FUNC(hl_decode_mb_444)(const H264Context *h, H264SliceContext *sl)
 {
-    const int mb_x    = h->mb_x;
-    const int mb_y    = h->mb_y;
-    const int mb_xy   = h->mb_xy;
+    const int mb_x    = sl->mb_x;
+    const int mb_y    = sl->mb_y;
+    const int mb_xy   = sl->mb_xy;
     const int mb_type = h->cur_pic.mb_type[mb_xy];
     uint8_t *dest[3];
     int linesize;
     int i, j, p;
-    int *block_offset = &h->block_offset[0];
-    const int transform_bypass = !SIMPLE && (h->qscale == 0 && h->sps.transform_bypass);
+    const int *block_offset = &h->block_offset[0];
+    const int transform_bypass = !SIMPLE && (sl->qscale == 0 && h->sps.transform_bypass);
     const int plane_count      = (SIMPLE || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) ? 3 : 1;
 
     for (p = 0; p < plane_count; p++) {
         dest[p] = h->cur_pic.f.data[p] +
-                  ((mb_x << PIXEL_SHIFT) + mb_y * h->linesize) * 16;
-        h->vdsp.prefetch(dest[p] + (h->mb_x & 3) * 4 * h->linesize + (64 << PIXEL_SHIFT),
-                         h->linesize, 4);
+                  ((mb_x << PIXEL_SHIFT) + mb_y * sl->linesize) * 16;
+        h->vdsp.prefetch(dest[p] + (sl->mb_x & 3) * 4 * sl->linesize + (64 << PIXEL_SHIFT),
+                         sl->linesize, 4);
     }
 
-    h->list_counts[mb_xy] = h->list_count;
+    h->list_counts[mb_xy] = sl->list_count;
 
-    if (!SIMPLE && MB_FIELD(h)) {
-        linesize     = h->mb_linesize = h->mb_uvlinesize = h->linesize * 2;
+    if (!SIMPLE && MB_FIELD(sl)) {
+        linesize     = sl->mb_linesize = sl->mb_uvlinesize = sl->linesize * 2;
         block_offset = &h->block_offset[48];
         if (mb_y & 1) // FIXME move out of this function?
             for (p = 0; p < 3; p++)
-                dest[p] -= h->linesize * 15;
+                dest[p] -= sl->linesize * 15;
         if (FRAME_MBAFF(h)) {
             int list;
-            for (list = 0; list < h->list_count; list++) {
+            for (list = 0; list < sl->list_count; list++) {
                 if (!USES_LIST(mb_type, list))
                     continue;
                 if (IS_16X16(mb_type)) {
-                    int8_t *ref = &h->ref_cache[list][scan8[0]];
-                    fill_rectangle(ref, 4, 4, 8, (16 + *ref) ^ (h->mb_y & 1), 1);
+                    int8_t *ref = &sl->ref_cache[list][scan8[0]];
+                    fill_rectangle(ref, 4, 4, 8, (16 + *ref) ^ (sl->mb_y & 1), 1);
                 } else {
                     for (i = 0; i < 16; i += 4) {
-                        int ref = h->ref_cache[list][scan8[i]];
+                        int ref = sl->ref_cache[list][scan8[i]];
                         if (ref >= 0)
-                            fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2,
-                                           8, (16 + ref) ^ (h->mb_y & 1), 1);
+                            fill_rectangle(&sl->ref_cache[list][scan8[i]], 2, 2,
+                                           8, (16 + ref) ^ (sl->mb_y & 1), 1);
                     }
                 }
             }
         }
     } else {
-        linesize = h->mb_linesize = h->mb_uvlinesize = h->linesize;
+        linesize = sl->mb_linesize = sl->mb_uvlinesize = sl->linesize;
     }
 
     if (!SIMPLE && IS_INTRA_PCM(mb_type)) {
         if (PIXEL_SHIFT) {
             const int bit_depth = h->sps.bit_depth_luma;
             GetBitContext gb;
-            init_get_bits(&gb, h->intra_pcm_ptr, 768 * bit_depth);
+            init_get_bits(&gb, sl->intra_pcm_ptr, 768 * bit_depth);
 
             for (p = 0; p < plane_count; p++)
                 for (i = 0; i < 16; i++) {
@@ -335,24 +335,24 @@
             for (p = 0; p < plane_count; p++)
                 for (i = 0; i < 16; i++)
                     memcpy(dest[p] + i * linesize,
-                           h->intra_pcm_ptr + p * 256 + i * 16, 16);
+                           sl->intra_pcm_ptr + p * 256 + i * 16, 16);
         }
     } else {
         if (IS_INTRA(mb_type)) {
-            if (h->deblocking_filter)
-                xchg_mb_border(h, dest[0], dest[1], dest[2], linesize,
+            if (sl->deblocking_filter)
+                xchg_mb_border(h, sl, dest[0], dest[1], dest[2], linesize,
                                linesize, 1, 1, SIMPLE, PIXEL_SHIFT);
 
             for (p = 0; p < plane_count; p++)
-                hl_decode_mb_predict_luma(h, mb_type, 1, SIMPLE,
+                hl_decode_mb_predict_luma(h, sl, mb_type, 1, SIMPLE,
                                           transform_bypass, PIXEL_SHIFT,
                                           block_offset, linesize, dest[p], p);
 
-            if (h->deblocking_filter)
-                xchg_mb_border(h, dest[0], dest[1], dest[2], linesize,
+            if (sl->deblocking_filter)
+                xchg_mb_border(h, sl, dest[0], dest[1], dest[2], linesize,
                                linesize, 0, 1, SIMPLE, PIXEL_SHIFT);
         } else {
-            FUNC(hl_motion_444)(h, dest[0], dest[1], dest[2],
+            FUNC(hl_motion_444)(h, sl, dest[0], dest[1], dest[2],
                       h->qpel_put, h->h264chroma.put_h264_chroma_pixels_tab,
                       h->qpel_avg, h->h264chroma.avg_h264_chroma_pixels_tab,
                       h->h264dsp.weight_h264_pixels_tab,
@@ -360,7 +360,7 @@
         }
 
         for (p = 0; p < plane_count; p++)
-            hl_decode_mb_idct_luma(h, mb_type, 1, SIMPLE, transform_bypass,
+            hl_decode_mb_idct_luma(h, sl, mb_type, 1, SIMPLE, transform_bypass,
                                    PIXEL_SHIFT, block_offset, linesize,
                                    dest[p], p);
     }
diff --git a/libavcodec/h264_mc_template.c b/libavcodec/h264_mc_template.c
index 0e4e477..eaead35 100644
--- a/libavcodec/h264_mc_template.c
+++ b/libavcodec/h264_mc_template.c
@@ -34,70 +34,72 @@
 #undef  mc_part
 #define mc_part MCFUNC(mc_part)
 
-static void mc_part(H264Context *h, int n, int square,
+static void mc_part(const H264Context *h, H264SliceContext *sl,
+                    int n, int square,
                     int height, int delta,
                     uint8_t *dest_y, uint8_t *dest_cb,
                     uint8_t *dest_cr,
                     int x_offset, int y_offset,
-                    qpel_mc_func *qpix_put,
+                    const qpel_mc_func *qpix_put,
                     h264_chroma_mc_func chroma_put,
-                    qpel_mc_func *qpix_avg,
+                    const qpel_mc_func *qpix_avg,
                     h264_chroma_mc_func chroma_avg,
-                    h264_weight_func *weight_op,
-                    h264_biweight_func *weight_avg,
+                    const h264_weight_func *weight_op,
+                    const h264_biweight_func *weight_avg,
                     int list0, int list1)
 {
-    if ((h->use_weight == 2 && list0 && list1 &&
-         (h->implicit_weight[h->ref_cache[0][scan8[n]]][h->ref_cache[1][scan8[n]]][h->mb_y & 1] != 32)) ||
-        h->use_weight == 1)
-        mc_part_weighted(h, n, square, height, delta, dest_y, dest_cb, dest_cr,
+    if ((sl->use_weight == 2 && list0 && list1 &&
+         (sl->implicit_weight[sl->ref_cache[0][scan8[n]]][sl->ref_cache[1][scan8[n]]][sl->mb_y & 1] != 32)) ||
+        sl->use_weight == 1)
+        mc_part_weighted(h, sl, n, square, height, delta, dest_y, dest_cb, dest_cr,
                          x_offset, y_offset, qpix_put, chroma_put,
                          weight_op[0], weight_op[1], weight_avg[0],
                          weight_avg[1], list0, list1, PIXEL_SHIFT, CHROMA_IDC);
     else
-        mc_part_std(h, n, square, height, delta, dest_y, dest_cb, dest_cr,
+        mc_part_std(h, sl, n, square, height, delta, dest_y, dest_cb, dest_cr,
                     x_offset, y_offset, qpix_put, chroma_put, qpix_avg,
                     chroma_avg, list0, list1, PIXEL_SHIFT, CHROMA_IDC);
 }
 
-static void MCFUNC(hl_motion)(H264Context *h, uint8_t *dest_y,
+static void MCFUNC(hl_motion)(const H264Context *h, H264SliceContext *sl,
+                              uint8_t *dest_y,
                               uint8_t *dest_cb, uint8_t *dest_cr,
                               qpel_mc_func(*qpix_put)[16],
-                              h264_chroma_mc_func(*chroma_put),
+                              const h264_chroma_mc_func(*chroma_put),
                               qpel_mc_func(*qpix_avg)[16],
-                              h264_chroma_mc_func(*chroma_avg),
-                              h264_weight_func *weight_op,
-                              h264_biweight_func *weight_avg)
+                              const h264_chroma_mc_func(*chroma_avg),
+                              const h264_weight_func *weight_op,
+                              const h264_biweight_func *weight_avg)
 {
-    const int mb_xy   = h->mb_xy;
+    const int mb_xy   = sl->mb_xy;
     const int mb_type = h->cur_pic.mb_type[mb_xy];
 
     av_assert2(IS_INTER(mb_type));
 
     if (HAVE_THREADS && (h->avctx->active_thread_type & FF_THREAD_FRAME))
-        await_references(h);
-    prefetch_motion(h, 0, PIXEL_SHIFT, CHROMA_IDC);
+        await_references(h, sl);
+    prefetch_motion(h, sl, 0, PIXEL_SHIFT, CHROMA_IDC);
 
     if (IS_16X16(mb_type)) {
-        mc_part(h, 0, 1, 16, 0, dest_y, dest_cb, dest_cr, 0, 0,
+        mc_part(h, sl, 0, 1, 16, 0, dest_y, dest_cb, dest_cr, 0, 0,
                 qpix_put[0], chroma_put[0], qpix_avg[0], chroma_avg[0],
                 weight_op, weight_avg,
                 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
     } else if (IS_16X8(mb_type)) {
-        mc_part(h, 0, 0, 8, 8 << PIXEL_SHIFT, dest_y, dest_cb, dest_cr, 0, 0,
+        mc_part(h, sl, 0, 0, 8, 8 << PIXEL_SHIFT, dest_y, dest_cb, dest_cr, 0, 0,
                 qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
                 weight_op, weight_avg,
                 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
-        mc_part(h, 8, 0, 8, 8 << PIXEL_SHIFT, dest_y, dest_cb, dest_cr, 0, 4,
+        mc_part(h, sl, 8, 0, 8, 8 << PIXEL_SHIFT, dest_y, dest_cb, dest_cr, 0, 4,
                 qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
                 weight_op, weight_avg,
                 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
     } else if (IS_8X16(mb_type)) {
-        mc_part(h, 0, 0, 16, 8 * h->mb_linesize, dest_y, dest_cb, dest_cr, 0, 0,
+        mc_part(h, sl, 0, 0, 16, 8 * sl->mb_linesize, dest_y, dest_cb, dest_cr, 0, 0,
                 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
                 &weight_op[1], &weight_avg[1],
                 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
-        mc_part(h, 4, 0, 16, 8 * h->mb_linesize, dest_y, dest_cb, dest_cr, 4, 0,
+        mc_part(h, sl, 4, 0, 16, 8 * sl->mb_linesize, dest_y, dest_cb, dest_cr, 4, 0,
                 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
                 &weight_op[1], &weight_avg[1],
                 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
@@ -107,35 +109,35 @@
         av_assert2(IS_8X8(mb_type));
 
         for (i = 0; i < 4; i++) {
-            const int sub_mb_type = h->sub_mb_type[i];
+            const int sub_mb_type = sl->sub_mb_type[i];
             const int n  = 4 * i;
             int x_offset = (i & 1) << 2;
             int y_offset = (i & 2) << 1;
 
             if (IS_SUB_8X8(sub_mb_type)) {
-                mc_part(h, n, 1, 8, 0, dest_y, dest_cb, dest_cr,
+                mc_part(h, sl, n, 1, 8, 0, dest_y, dest_cb, dest_cr,
                         x_offset, y_offset,
                         qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
                         &weight_op[1], &weight_avg[1],
                         IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
             } else if (IS_SUB_8X4(sub_mb_type)) {
-                mc_part(h, n, 0, 4, 4 << PIXEL_SHIFT, dest_y, dest_cb, dest_cr,
+                mc_part(h, sl, n, 0, 4, 4 << PIXEL_SHIFT, dest_y, dest_cb, dest_cr,
                         x_offset, y_offset,
                         qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
                         &weight_op[1], &weight_avg[1],
                         IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
-                mc_part(h, n + 2, 0, 4, 4 << PIXEL_SHIFT,
+                mc_part(h, sl, n + 2, 0, 4, 4 << PIXEL_SHIFT,
                         dest_y, dest_cb, dest_cr, x_offset, y_offset + 2,
                         qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
                         &weight_op[1], &weight_avg[1],
                         IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
             } else if (IS_SUB_4X8(sub_mb_type)) {
-                mc_part(h, n, 0, 8, 4 * h->mb_linesize,
+                mc_part(h, sl, n, 0, 8, 4 * sl->mb_linesize,
                         dest_y, dest_cb, dest_cr, x_offset, y_offset,
                         qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
                         &weight_op[2], &weight_avg[2],
                         IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
-                mc_part(h, n + 1, 0, 8, 4 * h->mb_linesize,
+                mc_part(h, sl, n + 1, 0, 8, 4 * sl->mb_linesize,
                         dest_y, dest_cb, dest_cr, x_offset + 2, y_offset,
                         qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
                         &weight_op[2], &weight_avg[2],
@@ -146,7 +148,7 @@
                 for (j = 0; j < 4; j++) {
                     int sub_x_offset = x_offset + 2 * (j & 1);
                     int sub_y_offset = y_offset + (j & 2);
-                    mc_part(h, n + j, 1, 4, 0,
+                    mc_part(h, sl, n + j, 1, 4, 0,
                             dest_y, dest_cb, dest_cr, sub_x_offset, sub_y_offset,
                             qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
                             &weight_op[2], &weight_avg[2],
@@ -156,6 +158,6 @@
         }
     }
 
-    prefetch_motion(h, 1, PIXEL_SHIFT, CHROMA_IDC);
+    prefetch_motion(h, sl, 1, PIXEL_SHIFT, CHROMA_IDC);
 }
 
diff --git a/libavcodec/h264_mvpred.h b/libavcodec/h264_mvpred.h
index 5f1e9a1..e7db550 100644
--- a/libavcodec/h264_mvpred.h
+++ b/libavcodec/h264_mvpred.h
@@ -35,10 +35,11 @@
 #include "libavutil/avassert.h"
 
 
-static av_always_inline int fetch_diagonal_mv(H264Context *h, const int16_t **C,
+static av_always_inline int fetch_diagonal_mv(const H264Context *h, H264SliceContext *sl,
+                                              const int16_t **C,
                                               int i, int list, int part_width)
 {
-    const int topright_ref = h->ref_cache[list][i - 8 + part_width];
+    const int topright_ref = sl->ref_cache[list][i - 8 + part_width];
 
     /* there is no consistent mapping of mvs to neighboring locations that will
      * make mbaff happy, so we can't move all this logic to fill_caches */
@@ -49,38 +50,38 @@
         if (!USES_LIST(mb_type, list))                                  \
             return LIST_NOT_USED;                                       \
         mv = h->cur_pic_ptr->motion_val[list][h->mb2b_xy[xy] + 3 + y4 * h->b_stride]; \
-        h->mv_cache[list][scan8[0] - 2][0] = mv[0];                     \
-        h->mv_cache[list][scan8[0] - 2][1] = mv[1] MV_OP;               \
+        sl->mv_cache[list][scan8[0] - 2][0] = mv[0];                     \
+        sl->mv_cache[list][scan8[0] - 2][1] = mv[1] MV_OP;               \
         return h->cur_pic_ptr->ref_index[list][4 * xy + 1 + (y4 & ~1)] REF_OP;
 
         if (topright_ref == PART_NOT_AVAILABLE
             && i >= scan8[0] + 8 && (i & 7) == 4
-            && h->ref_cache[list][scan8[0] - 1] != PART_NOT_AVAILABLE) {
+            && sl->ref_cache[list][scan8[0] - 1] != PART_NOT_AVAILABLE) {
             const uint32_t *mb_types = h->cur_pic_ptr->mb_type;
             const int16_t *mv;
-            AV_ZERO32(h->mv_cache[list][scan8[0] - 2]);
-            *C = h->mv_cache[list][scan8[0] - 2];
+            AV_ZERO32(sl->mv_cache[list][scan8[0] - 2]);
+            *C = sl->mv_cache[list][scan8[0] - 2];
 
-            if (!MB_FIELD(h) && IS_INTERLACED(h->left_type[0])) {
-                SET_DIAG_MV(* 2, >> 1, h->left_mb_xy[0] + h->mb_stride,
-                            (h->mb_y & 1) * 2 + (i >> 5));
+            if (!MB_FIELD(sl) && IS_INTERLACED(sl->left_type[0])) {
+                SET_DIAG_MV(* 2, >> 1, sl->left_mb_xy[0] + h->mb_stride,
+                            (sl->mb_y & 1) * 2 + (i >> 5));
             }
-            if (MB_FIELD(h) && !IS_INTERLACED(h->left_type[0])) {
+            if (MB_FIELD(sl) && !IS_INTERLACED(sl->left_type[0])) {
                 // left shift will turn LIST_NOT_USED into PART_NOT_AVAILABLE, but that's OK.
-                SET_DIAG_MV(/ 2, << 1, h->left_mb_xy[i >= 36], ((i >> 2)) & 3);
+                SET_DIAG_MV(/ 2, << 1, sl->left_mb_xy[i >= 36], ((i >> 2)) & 3);
             }
         }
 #undef SET_DIAG_MV
     }
 
     if (topright_ref != PART_NOT_AVAILABLE) {
-        *C = h->mv_cache[list][i - 8 + part_width];
+        *C = sl->mv_cache[list][i - 8 + part_width];
         return topright_ref;
     } else {
         tprintf(h->avctx, "topright MV not available\n");
 
-        *C = h->mv_cache[list][i - 8 - 1];
-        return h->ref_cache[list][i - 8 - 1];
+        *C = sl->mv_cache[list][i - 8 - 1];
+        return sl->ref_cache[list][i - 8 - 1];
     }
 }
 
@@ -91,15 +92,17 @@
  * @param mx the x component of the predicted motion vector
  * @param my the y component of the predicted motion vector
  */
-static av_always_inline void pred_motion(H264Context *const h, int n,
+static av_always_inline void pred_motion(const H264Context *const h,
+                                         H264SliceContext *sl,
+                                         int n,
                                          int part_width, int list, int ref,
                                          int *const mx, int *const my)
 {
     const int index8       = scan8[n];
-    const int top_ref      = h->ref_cache[list][index8 - 8];
-    const int left_ref     = h->ref_cache[list][index8 - 1];
-    const int16_t *const A = h->mv_cache[list][index8 - 1];
-    const int16_t *const B = h->mv_cache[list][index8 - 8];
+    const int top_ref      = sl->ref_cache[list][index8 - 8];
+    const int left_ref     = sl->ref_cache[list][index8 - 1];
+    const int16_t *const A = sl->mv_cache[list][index8 - 1];
+    const int16_t *const B = sl->mv_cache[list][index8 - 8];
     const int16_t *C;
     int diagonal_ref, match_count;
 
@@ -113,7 +116,7 @@
  * . . . L . . . .
  */
 
-    diagonal_ref = fetch_diagonal_mv(h, &C, index8, list, part_width);
+    diagonal_ref = fetch_diagonal_mv(h, sl, &C, index8, list, part_width);
     match_count  = (diagonal_ref == ref) + (top_ref == ref) + (left_ref == ref);
     tprintf(h->avctx, "pred_motion match_count=%d\n", match_count);
     if (match_count > 1) { //most common
@@ -145,7 +148,7 @@
     tprintf(h->avctx,
             "pred_motion (%2d %2d %2d) (%2d %2d %2d) (%2d %2d %2d) -> (%2d %2d %2d) at %2d %2d %d list %d\n",
             top_ref, B[0], B[1], diagonal_ref, C[0], C[1], left_ref,
-            A[0], A[1], ref, *mx, *my, h->mb_x, h->mb_y, n, list);
+            A[0], A[1], ref, *mx, *my, sl->mb_x, sl->mb_y, n, list);
 }
 
 /**
@@ -154,16 +157,17 @@
  * @param mx the x component of the predicted motion vector
  * @param my the y component of the predicted motion vector
  */
-static av_always_inline void pred_16x8_motion(H264Context *const h,
+static av_always_inline void pred_16x8_motion(const H264Context *const h,
+                                              H264SliceContext *sl,
                                               int n, int list, int ref,
                                               int *const mx, int *const my)
 {
     if (n == 0) {
-        const int top_ref      = h->ref_cache[list][scan8[0] - 8];
-        const int16_t *const B = h->mv_cache[list][scan8[0] - 8];
+        const int top_ref      = sl->ref_cache[list][scan8[0] - 8];
+        const int16_t *const B = sl->mv_cache[list][scan8[0] - 8];
 
         tprintf(h->avctx, "pred_16x8: (%2d %2d %2d) at %2d %2d %d list %d\n",
-                top_ref, B[0], B[1], h->mb_x, h->mb_y, n, list);
+                top_ref, B[0], B[1], sl->mb_x, sl->mb_y, n, list);
 
         if (top_ref == ref) {
             *mx = B[0];
@@ -171,11 +175,11 @@
             return;
         }
     } else {
-        const int left_ref     = h->ref_cache[list][scan8[8] - 1];
-        const int16_t *const A = h->mv_cache[list][scan8[8] - 1];
+        const int left_ref     = sl->ref_cache[list][scan8[8] - 1];
+        const int16_t *const A = sl->mv_cache[list][scan8[8] - 1];
 
         tprintf(h->avctx, "pred_16x8: (%2d %2d %2d) at %2d %2d %d list %d\n",
-                left_ref, A[0], A[1], h->mb_x, h->mb_y, n, list);
+                left_ref, A[0], A[1], sl->mb_x, sl->mb_y, n, list);
 
         if (left_ref == ref) {
             *mx = A[0];
@@ -185,7 +189,7 @@
     }
 
     //RARE
-    pred_motion(h, n, 4, list, ref, mx, my);
+    pred_motion(h, sl, n, 4, list, ref, mx, my);
 }
 
 /**
@@ -194,16 +198,17 @@
  * @param mx the x component of the predicted motion vector
  * @param my the y component of the predicted motion vector
  */
-static av_always_inline void pred_8x16_motion(H264Context *const h,
+static av_always_inline void pred_8x16_motion(const H264Context *const h,
+                                              H264SliceContext *sl,
                                               int n, int list, int ref,
                                               int *const mx, int *const my)
 {
     if (n == 0) {
-        const int left_ref     = h->ref_cache[list][scan8[0] - 1];
-        const int16_t *const A = h->mv_cache[list][scan8[0] - 1];
+        const int left_ref     = sl->ref_cache[list][scan8[0] - 1];
+        const int16_t *const A = sl->mv_cache[list][scan8[0] - 1];
 
         tprintf(h->avctx, "pred_8x16: (%2d %2d %2d) at %2d %2d %d list %d\n",
-                left_ref, A[0], A[1], h->mb_x, h->mb_y, n, list);
+                left_ref, A[0], A[1], sl->mb_x, sl->mb_y, n, list);
 
         if (left_ref == ref) {
             *mx = A[0];
@@ -214,10 +219,10 @@
         const int16_t *C;
         int diagonal_ref;
 
-        diagonal_ref = fetch_diagonal_mv(h, &C, scan8[4], list, 2);
+        diagonal_ref = fetch_diagonal_mv(h, sl, &C, scan8[4], list, 2);
 
         tprintf(h->avctx, "pred_8x16: (%2d %2d %2d) at %2d %2d %d list %d\n",
-                diagonal_ref, C[0], C[1], h->mb_x, h->mb_y, n, list);
+                diagonal_ref, C[0], C[1], sl->mb_x, sl->mb_y, n, list);
 
         if (diagonal_ref == ref) {
             *mx = C[0];
@@ -227,12 +232,12 @@
     }
 
     //RARE
-    pred_motion(h, n, 2, list, ref, mx, my);
+    pred_motion(h, sl, n, 2, list, ref, mx, my);
 }
 
 #define FIX_MV_MBAFF(type, refn, mvn, idx)      \
     if (FRAME_MBAFF(h)) {                       \
-        if (MB_FIELD(h)) {                      \
+        if (MB_FIELD(sl)) {                     \
             if (!IS_INTERLACED(type)) {         \
                 refn <<= 1;                     \
                 AV_COPY32(mvbuf[idx], mvn);     \
@@ -249,7 +254,8 @@
         }                                       \
     }
 
-static av_always_inline void pred_pskip_motion(H264Context *const h)
+static av_always_inline void pred_pskip_motion(const H264Context *const h,
+                                               H264SliceContext *sl)
 {
     DECLARE_ALIGNED(4, static const int16_t, zeromv)[2] = { 0 };
     DECLARE_ALIGNED(4, int16_t, mvbuf)[3][2];
@@ -259,33 +265,33 @@
     const int16_t *A, *B, *C;
     int b_stride = h->b_stride;
 
-    fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, 0, 1);
+    fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, 0, 1);
 
     /* To avoid doing an entire fill_decode_caches, we inline the relevant
      * parts here.
      * FIXME: this is a partial duplicate of the logic in fill_decode_caches,
      * but it's faster this way.  Is there a way to avoid this duplication?
      */
-    if (USES_LIST(h->left_type[LTOP], 0)) {
-        left_ref = ref[4 * h->left_mb_xy[LTOP] + 1 + (h->left_block[0] & ~1)];
-        A = mv[h->mb2b_xy[h->left_mb_xy[LTOP]] + 3 + b_stride * h->left_block[0]];
-        FIX_MV_MBAFF(h->left_type[LTOP], left_ref, A, 0);
+    if (USES_LIST(sl->left_type[LTOP], 0)) {
+        left_ref = ref[4 * sl->left_mb_xy[LTOP] + 1 + (sl->left_block[0] & ~1)];
+        A = mv[h->mb2b_xy[sl->left_mb_xy[LTOP]] + 3 + b_stride * sl->left_block[0]];
+        FIX_MV_MBAFF(sl->left_type[LTOP], left_ref, A, 0);
         if (!(left_ref | AV_RN32A(A)))
             goto zeromv;
-    } else if (h->left_type[LTOP]) {
+    } else if (sl->left_type[LTOP]) {
         left_ref = LIST_NOT_USED;
         A        = zeromv;
     } else {
         goto zeromv;
     }
 
-    if (USES_LIST(h->top_type, 0)) {
-        top_ref = ref[4 * h->top_mb_xy + 2];
-        B       = mv[h->mb2b_xy[h->top_mb_xy] + 3 * b_stride];
-        FIX_MV_MBAFF(h->top_type, top_ref, B, 1);
+    if (USES_LIST(sl->top_type, 0)) {
+        top_ref = ref[4 * sl->top_mb_xy + 2];
+        B       = mv[h->mb2b_xy[sl->top_mb_xy] + 3 * b_stride];
+        FIX_MV_MBAFF(sl->top_type, top_ref, B, 1);
         if (!(top_ref | AV_RN32A(B)))
             goto zeromv;
-    } else if (h->top_type) {
+    } else if (sl->top_type) {
         top_ref = LIST_NOT_USED;
         B       = zeromv;
     } else {
@@ -293,23 +299,23 @@
     }
 
     tprintf(h->avctx, "pred_pskip: (%d) (%d) at %2d %2d\n",
-            top_ref, left_ref, h->mb_x, h->mb_y);
+            top_ref, left_ref, sl->mb_x, sl->mb_y);
 
-    if (USES_LIST(h->topright_type, 0)) {
-        diagonal_ref = ref[4 * h->topright_mb_xy + 2];
-        C = mv[h->mb2b_xy[h->topright_mb_xy] + 3 * b_stride];
-        FIX_MV_MBAFF(h->topright_type, diagonal_ref, C, 2);
-    } else if (h->topright_type) {
+    if (USES_LIST(sl->topright_type, 0)) {
+        diagonal_ref = ref[4 * sl->topright_mb_xy + 2];
+        C = mv[h->mb2b_xy[sl->topright_mb_xy] + 3 * b_stride];
+        FIX_MV_MBAFF(sl->topright_type, diagonal_ref, C, 2);
+    } else if (sl->topright_type) {
         diagonal_ref = LIST_NOT_USED;
         C = zeromv;
     } else {
-        if (USES_LIST(h->topleft_type, 0)) {
-            diagonal_ref = ref[4 * h->topleft_mb_xy + 1 +
-                               (h->topleft_partition & 2)];
-            C = mv[h->mb2b_xy[h->topleft_mb_xy] + 3 + b_stride +
-                   (h->topleft_partition & 2 * b_stride)];
-            FIX_MV_MBAFF(h->topleft_type, diagonal_ref, C, 2);
-        } else if (h->topleft_type) {
+        if (USES_LIST(sl->topleft_type, 0)) {
+            diagonal_ref = ref[4 * sl->topleft_mb_xy + 1 +
+                               (sl->topleft_partition & 2)];
+            C = mv[h->mb2b_xy[sl->topleft_mb_xy] + 3 + b_stride +
+                   (sl->topleft_partition & 2 * b_stride)];
+            FIX_MV_MBAFF(sl->topleft_type, diagonal_ref, C, 2);
+        } else if (sl->topleft_type) {
             diagonal_ref = LIST_NOT_USED;
             C            = zeromv;
         } else {
@@ -339,17 +345,17 @@
         my = mid_pred(A[1], B[1], C[1]);
     }
 
-    fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8, pack16to32(mx, my), 4);
+    fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8, pack16to32(mx, my), 4);
     return;
 
 zeromv:
-    fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8, 0, 4);
+    fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8, 0, 4);
     return;
 }
 
-static void fill_decode_neighbors(H264Context *h, int mb_type)
+static void fill_decode_neighbors(const H264Context *h, H264SliceContext *sl, int mb_type)
 {
-    const int mb_xy = h->mb_xy;
+    const int mb_xy = sl->mb_xy;
     int topleft_xy, top_xy, topright_xy, left_xy[LEFT_MBS];
     static const uint8_t left_block_options[4][32] = {
         { 0, 1, 2, 3, 7, 10, 8, 11, 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4, 1 + 4 * 4, 1 + 8 * 4, 1 + 5 * 4, 1 + 9 * 4 },
@@ -358,9 +364,9 @@
         { 0, 2, 0, 2, 7, 10, 7, 10, 3 + 0 * 4, 3 + 2 * 4, 3 + 0 * 4, 3 + 2 * 4, 1 + 4 * 4, 1 + 8 * 4, 1 + 4 * 4, 1 + 8 * 4 }
     };
 
-    h->topleft_partition = -1;
+    sl->topleft_partition = -1;
 
-    top_xy = mb_xy - (h->mb_stride << MB_FIELD(h));
+    top_xy = mb_xy - (h->mb_stride << MB_FIELD(sl));
 
     /* Wow, what a mess, why didn't they simplify the interlacing & intra
      * stuff, I can't imagine that these complex rules are worth it. */
@@ -368,22 +374,22 @@
     topleft_xy    = top_xy - 1;
     topright_xy   = top_xy + 1;
     left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
-    h->left_block = left_block_options[0];
+    sl->left_block = left_block_options[0];
     if (FRAME_MBAFF(h)) {
         const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
         const int curr_mb_field_flag = IS_INTERLACED(mb_type);
-        if (h->mb_y & 1) {
+        if (sl->mb_y & 1) {
             if (left_mb_field_flag != curr_mb_field_flag) {
                 left_xy[LBOT] = left_xy[LTOP] = mb_xy - h->mb_stride - 1;
                 if (curr_mb_field_flag) {
                     left_xy[LBOT] += h->mb_stride;
-                    h->left_block  = left_block_options[3];
+                    sl->left_block  = left_block_options[3];
                 } else {
                     topleft_xy += h->mb_stride;
                     /* take top left mv from the middle of the mb, as opposed
                      * to all other modes which use the bottom right partition */
-                    h->topleft_partition = 0;
-                    h->left_block        = left_block_options[1];
+                    sl->topleft_partition = 0;
+                    sl->left_block        = left_block_options[1];
                 }
             }
         } else {
@@ -395,129 +401,129 @@
             if (left_mb_field_flag != curr_mb_field_flag) {
                 if (curr_mb_field_flag) {
                     left_xy[LBOT] += h->mb_stride;
-                    h->left_block  = left_block_options[3];
+                    sl->left_block  = left_block_options[3];
                 } else {
-                    h->left_block = left_block_options[2];
+                    sl->left_block = left_block_options[2];
                 }
             }
         }
     }
 
-    h->topleft_mb_xy    = topleft_xy;
-    h->top_mb_xy        = top_xy;
-    h->topright_mb_xy   = topright_xy;
-    h->left_mb_xy[LTOP] = left_xy[LTOP];
-    h->left_mb_xy[LBOT] = left_xy[LBOT];
+    sl->topleft_mb_xy    = topleft_xy;
+    sl->top_mb_xy        = top_xy;
+    sl->topright_mb_xy   = topright_xy;
+    sl->left_mb_xy[LTOP] = left_xy[LTOP];
+    sl->left_mb_xy[LBOT] = left_xy[LBOT];
     //FIXME do we need all in the context?
 
-    h->topleft_type    = h->cur_pic.mb_type[topleft_xy];
-    h->top_type        = h->cur_pic.mb_type[top_xy];
-    h->topright_type   = h->cur_pic.mb_type[topright_xy];
-    h->left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
-    h->left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
+    sl->topleft_type    = h->cur_pic.mb_type[topleft_xy];
+    sl->top_type        = h->cur_pic.mb_type[top_xy];
+    sl->topright_type   = h->cur_pic.mb_type[topright_xy];
+    sl->left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
+    sl->left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
 
     if (FMO) {
-        if (h->slice_table[topleft_xy] != h->slice_num)
-            h->topleft_type = 0;
-        if (h->slice_table[top_xy] != h->slice_num)
-            h->top_type = 0;
-        if (h->slice_table[left_xy[LTOP]] != h->slice_num)
-            h->left_type[LTOP] = h->left_type[LBOT] = 0;
+        if (h->slice_table[topleft_xy] != sl->slice_num)
+            sl->topleft_type = 0;
+        if (h->slice_table[top_xy] != sl->slice_num)
+            sl->top_type = 0;
+        if (h->slice_table[left_xy[LTOP]] != sl->slice_num)
+            sl->left_type[LTOP] = sl->left_type[LBOT] = 0;
     } else {
-        if (h->slice_table[topleft_xy] != h->slice_num) {
-            h->topleft_type = 0;
-            if (h->slice_table[top_xy] != h->slice_num)
-                h->top_type = 0;
-            if (h->slice_table[left_xy[LTOP]] != h->slice_num)
-                h->left_type[LTOP] = h->left_type[LBOT] = 0;
+        if (h->slice_table[topleft_xy] != sl->slice_num) {
+            sl->topleft_type = 0;
+            if (h->slice_table[top_xy] != sl->slice_num)
+                sl->top_type = 0;
+            if (h->slice_table[left_xy[LTOP]] != sl->slice_num)
+                sl->left_type[LTOP] = sl->left_type[LBOT] = 0;
         }
     }
-    if (h->slice_table[topright_xy] != h->slice_num)
-        h->topright_type = 0;
+    if (h->slice_table[topright_xy] != sl->slice_num)
+        sl->topright_type = 0;
 }
 
-static void fill_decode_caches(H264Context *h, int mb_type)
+static void fill_decode_caches(const H264Context *h, H264SliceContext *sl, int mb_type)
 {
     int topleft_xy, top_xy, topright_xy, left_xy[LEFT_MBS];
     int topleft_type, top_type, topright_type, left_type[LEFT_MBS];
-    const uint8_t *left_block = h->left_block;
+    const uint8_t *left_block = sl->left_block;
     int i;
     uint8_t *nnz;
     uint8_t *nnz_cache;
 
-    topleft_xy      = h->topleft_mb_xy;
-    top_xy          = h->top_mb_xy;
-    topright_xy     = h->topright_mb_xy;
-    left_xy[LTOP]   = h->left_mb_xy[LTOP];
-    left_xy[LBOT]   = h->left_mb_xy[LBOT];
-    topleft_type    = h->topleft_type;
-    top_type        = h->top_type;
-    topright_type   = h->topright_type;
-    left_type[LTOP] = h->left_type[LTOP];
-    left_type[LBOT] = h->left_type[LBOT];
+    topleft_xy      = sl->topleft_mb_xy;
+    top_xy          = sl->top_mb_xy;
+    topright_xy     = sl->topright_mb_xy;
+    left_xy[LTOP]   = sl->left_mb_xy[LTOP];
+    left_xy[LBOT]   = sl->left_mb_xy[LBOT];
+    topleft_type    = sl->topleft_type;
+    top_type        = sl->top_type;
+    topright_type   = sl->topright_type;
+    left_type[LTOP] = sl->left_type[LTOP];
+    left_type[LBOT] = sl->left_type[LBOT];
 
     if (!IS_SKIP(mb_type)) {
         if (IS_INTRA(mb_type)) {
             int type_mask = h->pps.constrained_intra_pred ? IS_INTRA(-1) : -1;
-            h->topleft_samples_available      =
-                h->top_samples_available      =
-                    h->left_samples_available = 0xFFFF;
-            h->topright_samples_available     = 0xEEEA;
+            sl->topleft_samples_available     =
+                sl->top_samples_available     =
+                    sl->left_samples_available = 0xFFFF;
+            sl->topright_samples_available     = 0xEEEA;
 
             if (!(top_type & type_mask)) {
-                h->topleft_samples_available  = 0xB3FF;
-                h->top_samples_available      = 0x33FF;
-                h->topright_samples_available = 0x26EA;
+                sl->topleft_samples_available  = 0xB3FF;
+                sl->top_samples_available      = 0x33FF;
+                sl->topright_samples_available = 0x26EA;
             }
             if (IS_INTERLACED(mb_type) != IS_INTERLACED(left_type[LTOP])) {
                 if (IS_INTERLACED(mb_type)) {
                     if (!(left_type[LTOP] & type_mask)) {
-                        h->topleft_samples_available &= 0xDFFF;
-                        h->left_samples_available    &= 0x5FFF;
+                        sl->topleft_samples_available &= 0xDFFF;
+                        sl->left_samples_available    &= 0x5FFF;
                     }
                     if (!(left_type[LBOT] & type_mask)) {
-                        h->topleft_samples_available &= 0xFF5F;
-                        h->left_samples_available    &= 0xFF5F;
+                        sl->topleft_samples_available &= 0xFF5F;
+                        sl->left_samples_available    &= 0xFF5F;
                     }
                 } else {
                     int left_typei = h->cur_pic.mb_type[left_xy[LTOP] + h->mb_stride];
 
                     av_assert2(left_xy[LTOP] == left_xy[LBOT]);
                     if (!((left_typei & type_mask) && (left_type[LTOP] & type_mask))) {
-                        h->topleft_samples_available &= 0xDF5F;
-                        h->left_samples_available    &= 0x5F5F;
+                        sl->topleft_samples_available &= 0xDF5F;
+                        sl->left_samples_available    &= 0x5F5F;
                     }
                 }
             } else {
                 if (!(left_type[LTOP] & type_mask)) {
-                    h->topleft_samples_available &= 0xDF5F;
-                    h->left_samples_available    &= 0x5F5F;
+                    sl->topleft_samples_available &= 0xDF5F;
+                    sl->left_samples_available    &= 0x5F5F;
                 }
             }
 
             if (!(topleft_type & type_mask))
-                h->topleft_samples_available &= 0x7FFF;
+                sl->topleft_samples_available &= 0x7FFF;
 
             if (!(topright_type & type_mask))
-                h->topright_samples_available &= 0xFBFF;
+                sl->topright_samples_available &= 0xFBFF;
 
             if (IS_INTRA4x4(mb_type)) {
                 if (IS_INTRA4x4(top_type)) {
-                    AV_COPY32(h->intra4x4_pred_mode_cache + 4 + 8 * 0, h->intra4x4_pred_mode + h->mb2br_xy[top_xy]);
+                    AV_COPY32(sl->intra4x4_pred_mode_cache + 4 + 8 * 0, sl->intra4x4_pred_mode + h->mb2br_xy[top_xy]);
                 } else {
-                    h->intra4x4_pred_mode_cache[4 + 8 * 0] =
-                    h->intra4x4_pred_mode_cache[5 + 8 * 0] =
-                    h->intra4x4_pred_mode_cache[6 + 8 * 0] =
-                    h->intra4x4_pred_mode_cache[7 + 8 * 0] = 2 - 3 * !(top_type & type_mask);
+                    sl->intra4x4_pred_mode_cache[4 + 8 * 0] =
+                    sl->intra4x4_pred_mode_cache[5 + 8 * 0] =
+                    sl->intra4x4_pred_mode_cache[6 + 8 * 0] =
+                    sl->intra4x4_pred_mode_cache[7 + 8 * 0] = 2 - 3 * !(top_type & type_mask);
                 }
                 for (i = 0; i < 2; i++) {
                     if (IS_INTRA4x4(left_type[LEFT(i)])) {
-                        int8_t *mode = h->intra4x4_pred_mode + h->mb2br_xy[left_xy[LEFT(i)]];
-                        h->intra4x4_pred_mode_cache[3 + 8 * 1 + 2 * 8 * i] = mode[6 - left_block[0 + 2 * i]];
-                        h->intra4x4_pred_mode_cache[3 + 8 * 2 + 2 * 8 * i] = mode[6 - left_block[1 + 2 * i]];
+                        int8_t *mode = sl->intra4x4_pred_mode + h->mb2br_xy[left_xy[LEFT(i)]];
+                        sl->intra4x4_pred_mode_cache[3 + 8 * 1 + 2 * 8 * i] = mode[6 - left_block[0 + 2 * i]];
+                        sl->intra4x4_pred_mode_cache[3 + 8 * 2 + 2 * 8 * i] = mode[6 - left_block[1 + 2 * i]];
                     } else {
-                        h->intra4x4_pred_mode_cache[3 + 8 * 1 + 2 * 8 * i] =
-                        h->intra4x4_pred_mode_cache[3 + 8 * 2 + 2 * 8 * i] = 2 - 3 * !(left_type[LEFT(i)] & type_mask);
+                        sl->intra4x4_pred_mode_cache[3 + 8 * 1 + 2 * 8 * i] =
+                        sl->intra4x4_pred_mode_cache[3 + 8 * 2 + 2 * 8 * i] = 2 - 3 * !(left_type[LEFT(i)] & type_mask);
                     }
                 }
             }
@@ -533,7 +539,7 @@
          */
         /* FIXME: constraint_intra_pred & partitioning & nnz
          * (let us hope this is just a typo in the spec) */
-        nnz_cache = h->non_zero_count_cache;
+        nnz_cache = sl->non_zero_count_cache;
         if (top_type) {
             nnz = h->non_zero_count[top_xy];
             AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[4 * 3]);
@@ -583,31 +589,31 @@
         if (CABAC(h)) {
             // top_cbp
             if (top_type)
-                h->top_cbp = h->cbp_table[top_xy];
+                sl->top_cbp = h->cbp_table[top_xy];
             else
-                h->top_cbp = IS_INTRA(mb_type) ? 0x7CF : 0x00F;
+                sl->top_cbp = IS_INTRA(mb_type) ? 0x7CF : 0x00F;
             // left_cbp
             if (left_type[LTOP]) {
-                h->left_cbp =   (h->cbp_table[left_xy[LTOP]] & 0x7F0) |
+                sl->left_cbp =   (h->cbp_table[left_xy[LTOP]] & 0x7F0) |
                                ((h->cbp_table[left_xy[LTOP]] >> (left_block[0] & (~1))) & 2) |
                               (((h->cbp_table[left_xy[LBOT]] >> (left_block[2] & (~1))) & 2) << 2);
             } else {
-                h->left_cbp = IS_INTRA(mb_type) ? 0x7CF : 0x00F;
+                sl->left_cbp = IS_INTRA(mb_type) ? 0x7CF : 0x00F;
             }
         }
     }
 
-    if (IS_INTER(mb_type) || (IS_DIRECT(mb_type) && h->direct_spatial_mv_pred)) {
+    if (IS_INTER(mb_type) || (IS_DIRECT(mb_type) && sl->direct_spatial_mv_pred)) {
         int list;
         int b_stride = h->b_stride;
-        for (list = 0; list < h->list_count; list++) {
-            int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
+        for (list = 0; list < sl->list_count; list++) {
+            int8_t *ref_cache = &sl->ref_cache[list][scan8[0]];
             int8_t *ref       = h->cur_pic.ref_index[list];
-            int16_t(*mv_cache)[2] = &h->mv_cache[list][scan8[0]];
+            int16_t(*mv_cache)[2] = &sl->mv_cache[list][scan8[0]];
             int16_t(*mv)[2]       = h->cur_pic.motion_val[list];
             if (!USES_LIST(mb_type, list))
                 continue;
-            av_assert2(!(IS_DIRECT(mb_type) && !h->direct_spatial_mv_pred));
+            av_assert2(!(IS_DIRECT(mb_type) && !sl->direct_spatial_mv_pred));
 
             if (USES_LIST(top_type, list)) {
                 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
@@ -667,8 +673,8 @@
             if(ref_cache[2 - 1*8] < 0 || ref_cache[4 - 1 * 8] < 0) {
                 if (USES_LIST(topleft_type, list)) {
                     const int b_xy  = h->mb2b_xy[topleft_xy] + 3 + b_stride +
-                                      (h->topleft_partition & 2 * b_stride);
-                    const int b8_xy = 4 * topleft_xy + 1 + (h->topleft_partition & 2);
+                                      (sl->topleft_partition & 2 * b_stride);
+                    const int b8_xy = 4 * topleft_xy + 1 + (sl->topleft_partition & 2);
                     AV_COPY32(mv_cache[-1 - 1 * 8], mv[b_xy]);
                     ref_cache[-1 - 1 * 8] = ref[b8_xy];
                 } else {
@@ -682,8 +688,8 @@
                 continue;
 
             if (!(mb_type & (MB_TYPE_SKIP | MB_TYPE_DIRECT2))) {
-                uint8_t(*mvd_cache)[2]   = &h->mvd_cache[list][scan8[0]];
-                uint8_t(*mvd)[2]         = h->mvd_table[list];
+                uint8_t(*mvd_cache)[2]   = &sl->mvd_cache[list][scan8[0]];
+                uint8_t(*mvd)[2]         = sl->mvd_table[list];
                 ref_cache[2 + 8 * 0] =
                 ref_cache[2 + 8 * 2] = PART_NOT_AVAILABLE;
                 AV_ZERO32(mv_cache[2 + 8 * 0]);
@@ -714,8 +720,8 @@
                     }
                     AV_ZERO16(mvd_cache[2 + 8 * 0]);
                     AV_ZERO16(mvd_cache[2 + 8 * 2]);
-                    if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
-                        uint8_t *direct_cache = &h->direct_cache[scan8[0]];
+                    if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
+                        uint8_t *direct_cache = &sl->direct_cache[scan8[0]];
                         uint8_t *direct_table = h->direct_table;
                         fill_rectangle(direct_cache, 4, 4, 8, MB_TYPE_16x16 >> 1, 1);
 
@@ -761,13 +767,13 @@
     MAP_F2F(scan8[0] - 1 + 3 * 8, left_type[LBOT])
 
             if (FRAME_MBAFF(h)) {
-                if (MB_FIELD(h)) {
+                if (MB_FIELD(sl)) {
 
 #define MAP_F2F(idx, mb_type)                                           \
-    if (!IS_INTERLACED(mb_type) && h->ref_cache[list][idx] >= 0) {      \
-        h->ref_cache[list][idx]    <<= 1;                               \
-        h->mv_cache[list][idx][1]   /= 2;                               \
-        h->mvd_cache[list][idx][1] >>= 1;                               \
+    if (!IS_INTERLACED(mb_type) && sl->ref_cache[list][idx] >= 0) {     \
+        sl->ref_cache[list][idx]    <<= 1;                              \
+        sl->mv_cache[list][idx][1]   /= 2;                              \
+        sl->mvd_cache[list][idx][1] >>= 1;                              \
     }
 
                     MAP_MVS
@@ -775,10 +781,10 @@
 
 #undef MAP_F2F
 #define MAP_F2F(idx, mb_type)                                           \
-    if (IS_INTERLACED(mb_type) && h->ref_cache[list][idx] >= 0) {       \
-        h->ref_cache[list][idx]    >>= 1;                               \
-        h->mv_cache[list][idx][1]  <<= 1;                               \
-        h->mvd_cache[list][idx][1] <<= 1;                               \
+    if (IS_INTERLACED(mb_type) && sl->ref_cache[list][idx] >= 0) {      \
+        sl->ref_cache[list][idx]    >>= 1;                              \
+        sl->mv_cache[list][idx][1]  <<= 1;                              \
+        sl->mvd_cache[list][idx][1] <<= 1;                              \
     }
 
                     MAP_MVS
@@ -788,43 +794,43 @@
         }
     }
 
-    h->neighbor_transform_size = !!IS_8x8DCT(top_type) + !!IS_8x8DCT(left_type[LTOP]);
+    sl->neighbor_transform_size = !!IS_8x8DCT(top_type) + !!IS_8x8DCT(left_type[LTOP]);
 }
 
 /**
  * decodes a P_SKIP or B_SKIP macroblock
  */
-static void av_unused decode_mb_skip(H264Context *h)
+static void av_unused decode_mb_skip(const H264Context *h, H264SliceContext *sl)
 {
-    const int mb_xy = h->mb_xy;
+    const int mb_xy = sl->mb_xy;
     int mb_type     = 0;
 
     memset(h->non_zero_count[mb_xy], 0, 48);
 
-    if (MB_FIELD(h))
+    if (MB_FIELD(sl))
         mb_type |= MB_TYPE_INTERLACED;
 
-    if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
+    if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
         // just for fill_caches. pred_direct_motion will set the real mb_type
         mb_type |= MB_TYPE_L0L1 | MB_TYPE_DIRECT2 | MB_TYPE_SKIP;
-        if (h->direct_spatial_mv_pred) {
-            fill_decode_neighbors(h, mb_type);
-            fill_decode_caches(h, mb_type); //FIXME check what is needed and what not ...
+        if (sl->direct_spatial_mv_pred) {
+            fill_decode_neighbors(h, sl, mb_type);
+            fill_decode_caches(h, sl, mb_type); //FIXME check what is needed and what not ...
         }
-        ff_h264_pred_direct_motion(h, &mb_type);
+        ff_h264_pred_direct_motion(h, sl, &mb_type);
         mb_type |= MB_TYPE_SKIP;
     } else {
         mb_type |= MB_TYPE_16x16 | MB_TYPE_P0L0 | MB_TYPE_P1L0 | MB_TYPE_SKIP;
 
-        fill_decode_neighbors(h, mb_type);
-        pred_pskip_motion(h);
+        fill_decode_neighbors(h, sl, mb_type);
+        pred_pskip_motion(h, sl);
     }
 
-    write_back_motion(h, mb_type);
+    write_back_motion(h, sl, mb_type);
     h->cur_pic.mb_type[mb_xy]      = mb_type;
-    h->cur_pic.qscale_table[mb_xy] = h->qscale;
-    h->slice_table[mb_xy]            = h->slice_num;
-    h->prev_mb_skipped               = 1;
+    h->cur_pic.qscale_table[mb_xy] = sl->qscale;
+    h->slice_table[mb_xy]          = sl->slice_num;
+    sl->prev_mb_skipped            = 1;
 }
 
 #endif /* AVCODEC_H264_MVPRED_H */
diff --git a/libavcodec/h264_parser.c b/libavcodec/h264_parser.c
index 3ec5151..6b47e0e 100644
--- a/libavcodec/h264_parser.c
+++ b/libavcodec/h264_parser.c
@@ -131,25 +131,26 @@
 {
     H264ParseContext *p = s->priv_data;
     H264Context      *h = &p->h;
+    H264SliceContext *sl = &h->slice_ctx[0];
 
-    h->slice_type_nos = s->pict_type & 3;
+    sl->slice_type_nos = s->pict_type & 3;
 
     if (h->pps.redundant_pic_cnt_present)
-        get_ue_golomb(&h->gb); // redundant_pic_count
+        get_ue_golomb(&sl->gb); // redundant_pic_count
 
-    if (ff_set_ref_count(h) < 0)
+    if (ff_set_ref_count(h, sl) < 0)
         return AVERROR_INVALIDDATA;
 
-    if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
+    if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
         int list;
-        for (list = 0; list < h->list_count; list++) {
-            if (get_bits1(&h->gb)) {
+        for (list = 0; list < sl->list_count; list++) {
+            if (get_bits1(&sl->gb)) {
                 int index;
                 for (index = 0; ; index++) {
-                    unsigned int reordering_of_pic_nums_idc = get_ue_golomb_31(&h->gb);
+                    unsigned int reordering_of_pic_nums_idc = get_ue_golomb_31(&sl->gb);
 
                     if (reordering_of_pic_nums_idc < 3)
-                        get_ue_golomb(&h->gb);
+                        get_ue_golomb(&sl->gb);
                     else if (reordering_of_pic_nums_idc > 3) {
                         av_log(h->avctx, AV_LOG_ERROR,
                                "illegal reordering_of_pic_nums_idc %d\n",
@@ -158,7 +159,7 @@
                     } else
                         break;
 
-                    if (index >= h->ref_count[list]) {
+                    if (index >= sl->ref_count[list]) {
                         av_log(h->avctx, AV_LOG_ERROR,
                                "reference count %d overflow\n", index);
                         return AVERROR_INVALIDDATA;
@@ -168,14 +169,14 @@
         }
     }
 
-    if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
-        (h->pps.weighted_bipred_idc == 1 && h->slice_type_nos == AV_PICTURE_TYPE_B))
-        ff_pred_weight_table(h);
+    if ((h->pps.weighted_pred && sl->slice_type_nos == AV_PICTURE_TYPE_P) ||
+        (h->pps.weighted_bipred_idc == 1 && sl->slice_type_nos == AV_PICTURE_TYPE_B))
+        ff_pred_weight_table(h, sl);
 
-    if (get_bits1(&h->gb)) { // adaptive_ref_pic_marking_mode_flag
+    if (get_bits1(&sl->gb)) { // adaptive_ref_pic_marking_mode_flag
         int i;
         for (i = 0; i < MAX_MMCO_COUNT; i++) {
-            MMCOOpcode opcode = get_ue_golomb_31(&h->gb);
+            MMCOOpcode opcode = get_ue_golomb_31(&sl->gb);
             if (opcode > (unsigned) MMCO_LONG) {
                 av_log(h->avctx, AV_LOG_ERROR,
                        "illegal memory management control operation %d\n",
@@ -188,10 +189,10 @@
                 return 1;
 
             if (opcode == MMCO_SHORT2UNUSED || opcode == MMCO_SHORT2LONG)
-                get_ue_golomb(&h->gb);
+                get_ue_golomb(&sl->gb);
             if (opcode == MMCO_SHORT2LONG || opcode == MMCO_LONG2UNUSED ||
                 opcode == MMCO_LONG || opcode == MMCO_SET_MAX_LONG)
-                get_ue_golomb_31(&h->gb);
+                get_ue_golomb_31(&sl->gb);
         }
     }
 
@@ -212,6 +213,7 @@
 {
     H264ParseContext *p = s->priv_data;
     H264Context      *h = &p->h;
+    H264SliceContext *sl = &h->slice_ctx[0];
     int buf_index, next_avc;
     unsigned int pps_id;
     unsigned int slice_type;
@@ -268,7 +270,7 @@
             }
             break;
         }
-        ptr = ff_h264_decode_nal(h, buf + buf_index, &dst_length,
+        ptr = ff_h264_decode_nal(h, sl, buf + buf_index, &dst_length,
                                  &consumed, src_length);
         if (!ptr || dst_length < 0)
             break;
@@ -295,14 +297,15 @@
             h->prev_poc_lsb          = 0;
         /* fall through */
         case NAL_SLICE:
-            get_ue_golomb_long(&h->gb);  // skip first_mb_in_slice
-            slice_type   = get_ue_golomb_31(&h->gb);
+            init_get_bits(&sl->gb, ptr, 8 * dst_length);
+            get_ue_golomb_long(&sl->gb);  // skip first_mb_in_slice
+            slice_type   = get_ue_golomb_31(&sl->gb);
             s->pict_type = golomb_to_pict_type[slice_type % 5];
             if (h->sei_recovery_frame_cnt >= 0) {
                 /* key frame, since recovery_frame_cnt is set */
                 s->key_frame = 1;
             }
-            pps_id = get_ue_golomb(&h->gb);
+            pps_id = get_ue_golomb(&sl->gb);
             if (pps_id >= MAX_PPS_COUNT) {
                 av_log(h->avctx, AV_LOG_ERROR,
                        "pps_id %u out of range\n", pps_id);
@@ -320,41 +323,70 @@
                 return -1;
             }
             h->sps       = *h->sps_buffers[h->pps.sps_id];
-            h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
+            h->frame_num = get_bits(&sl->gb, h->sps.log2_max_frame_num);
 
             if(h->sps.ref_frame_count <= 1 && h->pps.ref_count[0] <= 1 && s->pict_type == AV_PICTURE_TYPE_I)
                 s->key_frame = 1;
 
+            s->coded_width  = 16 * h->sps.mb_width;
+            s->coded_height = 16 * h->sps.mb_height;
+            s->width        = s->coded_width  - (h->sps.crop_right + h->sps.crop_left);
+            s->height       = s->coded_height - (h->sps.crop_top   + h->sps.crop_bottom);
+            if (s->width <= 0 || s->height <= 0) {
+                s->width  = s->coded_width;
+                s->height = s->coded_height;
+            }
+
+            switch (h->sps.bit_depth_luma) {
+            case 9:
+                if (CHROMA444(h))      s->format = AV_PIX_FMT_YUV444P9;
+                else if (CHROMA422(h)) s->format = AV_PIX_FMT_YUV422P9;
+                else                   s->format = AV_PIX_FMT_YUV420P9;
+                break;
+            case 10:
+                if (CHROMA444(h))      s->format = AV_PIX_FMT_YUV444P10;
+                else if (CHROMA422(h)) s->format = AV_PIX_FMT_YUV422P10;
+                else                   s->format = AV_PIX_FMT_YUV420P10;
+                break;
+            case 8:
+                if (CHROMA444(h))      s->format = AV_PIX_FMT_YUV444P;
+                else if (CHROMA422(h)) s->format = AV_PIX_FMT_YUV422P;
+                else                   s->format = AV_PIX_FMT_YUV420P;
+                break;
+            default:
+                s->format = AV_PIX_FMT_NONE;
+            }
+
             avctx->profile = ff_h264_get_profile(&h->sps);
             avctx->level   = h->sps.level_idc;
 
             if (h->sps.frame_mbs_only_flag) {
                 h->picture_structure = PICT_FRAME;
             } else {
-                if (get_bits1(&h->gb)) { // field_pic_flag
-                    h->picture_structure = PICT_TOP_FIELD + get_bits1(&h->gb); // bottom_field_flag
+                if (get_bits1(&sl->gb)) { // field_pic_flag
+                    h->picture_structure = PICT_TOP_FIELD + get_bits1(&sl->gb); // bottom_field_flag
                 } else {
                     h->picture_structure = PICT_FRAME;
                 }
             }
 
             if (h->nal_unit_type == NAL_IDR_SLICE)
-                get_ue_golomb(&h->gb); /* idr_pic_id */
+                get_ue_golomb(&sl->gb); /* idr_pic_id */
             if (h->sps.poc_type == 0) {
-                h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
+                h->poc_lsb = get_bits(&sl->gb, h->sps.log2_max_poc_lsb);
 
                 if (h->pps.pic_order_present == 1 &&
                     h->picture_structure == PICT_FRAME)
-                    h->delta_poc_bottom = get_se_golomb(&h->gb);
+                    h->delta_poc_bottom = get_se_golomb(&sl->gb);
             }
 
             if (h->sps.poc_type == 1 &&
                 !h->sps.delta_pic_order_always_zero_flag) {
-                h->delta_poc[0] = get_se_golomb(&h->gb);
+                h->delta_poc[0] = get_se_golomb(&sl->gb);
 
                 if (h->pps.pic_order_present == 1 &&
                     h->picture_structure == PICT_FRAME)
-                    h->delta_poc[1] = get_se_golomb(&h->gb);
+                    h->delta_poc[1] = get_se_golomb(&sl->gb);
             }
 
             /* Decode POC of this picture.
@@ -524,34 +556,37 @@
 static int h264_split(AVCodecContext *avctx,
                       const uint8_t *buf, int buf_size)
 {
-    int i;
     uint32_t state = -1;
     int has_sps    = 0;
     int has_pps    = 0;
+    const uint8_t *ptr = buf, *end = buf + buf_size;
+    int nalu_type;
 
-    for (i = 0; i <= buf_size; i++) {
-        if ((state & 0xFFFFFF1F) == 0x107)
+    while (ptr < end) {
+        ptr = avpriv_find_start_code(ptr, end, &state);
+        if ((state & 0xFFFFFF00) != 0x100)
+            break;
+        nalu_type = state & 0x1F;
+        if (nalu_type == NAL_SPS) {
             has_sps = 1;
-        if ((state & 0xFFFFFF1F) == 0x108)
+        } else if (nalu_type == NAL_PPS)
             has_pps = 1;
-        /*  if ((state&0xFFFFFF1F) == 0x101 ||
-         *     (state&0xFFFFFF1F) == 0x102 ||
-         *     (state&0xFFFFFF1F) == 0x105) {
+        /* else if (nalu_type == 0x01 ||
+         *     nalu_type == 0x02 ||
+         *     nalu_type == 0x05) {
          *  }
          */
-        if ((state & 0xFFFFFF00) == 0x100 && ((state & 0xFFFFFF1F) != 0x106 || has_pps) &&
-            (state & 0xFFFFFF1F) != 0x107 && (state & 0xFFFFFF1F) != 0x108 &&
-            (state & 0xFFFFFF1F) != 0x109 && (state & 0xFFFFFF1F) != 0x10d &&
-            (state & 0xFFFFFF1F) != 0x10f) {
+        else if ((nalu_type != NAL_SEI || has_pps) &&
+                  nalu_type != NAL_AUD && nalu_type != NAL_SPS_EXT &&
+                  nalu_type != 0x0f) {
             if (has_sps) {
-                while (i > 4 && buf[i - 5] == 0)
-                    i--;
-                return i - 4;
+                while (ptr - 4 > buf && ptr[-5] == 0)
+                    ptr--;
+                return ptr - 4 - buf;
             }
         }
-        if (i < buf_size)
-            state = (state << 8) | buf[i];
     }
+
     return 0;
 }
 
@@ -569,7 +604,12 @@
 {
     H264ParseContext *p = s->priv_data;
     H264Context      *h = &p->h;
-    h->thread_context[0]   = h;
+
+    h->slice_ctx = av_mallocz(sizeof(*h->slice_ctx));
+    if (!h->slice_ctx)
+        return 0;
+    h->nb_slice_ctx = 1;
+
     h->slice_context_count = 1;
     ff_h264dsp_init(&h->h264dsp, 8, 1);
     return 0;
diff --git a/libavcodec/h264_picture.c b/libavcodec/h264_picture.c
index b6bdae4..127bc45 100644
--- a/libavcodec/h264_picture.c
+++ b/libavcodec/h264_picture.c
@@ -152,7 +152,7 @@
 #endif /* CONFIG_ERROR_RESILIENCE */
 }
 
-int ff_h264_field_end(H264Context *h, int in_setup)
+int ff_h264_field_end(H264Context *h, H264SliceContext *sl, int in_setup)
 {
     AVCodecContext *const avctx = h->avctx;
     int err = 0;
@@ -197,8 +197,29 @@
      * causes problems for the first MB line, too.
      */
     if (!FIELD_PICTURE(h) && h->current_slice && !h->sps.new) {
-        ff_h264_set_erpic(&h->er.cur_pic, h->cur_pic_ptr);
-        ff_er_frame_end(&h->er);
+        int use_last_pic = h->last_pic_for_ec.f.buf[0] && !sl->ref_count[0];
+
+        ff_h264_set_erpic(&sl->er.cur_pic, h->cur_pic_ptr);
+
+        if (use_last_pic) {
+            ff_h264_set_erpic(&sl->er.last_pic, &h->last_pic_for_ec);
+            sl->ref_list[0][0].parent = &h->last_pic_for_ec;
+            memcpy(sl->ref_list[0][0].data, h->last_pic_for_ec.f.data, sizeof(sl->ref_list[0][0].data));
+            memcpy(sl->ref_list[0][0].linesize, h->last_pic_for_ec.f.linesize, sizeof(sl->ref_list[0][0].linesize));
+            sl->ref_list[0][0].reference = h->last_pic_for_ec.reference;
+        } else if (sl->ref_count[0]) {
+            ff_h264_set_erpic(&sl->er.last_pic, sl->ref_list[0][0].parent);
+        } else
+            ff_h264_set_erpic(&sl->er.last_pic, NULL);
+
+        if (sl->ref_count[1])
+            ff_h264_set_erpic(&sl->er.next_pic, sl->ref_list[1][0].parent);
+
+        sl->er.ref_count = sl->ref_count[0];
+
+        ff_er_frame_end(&sl->er);
+        if (use_last_pic)
+            memset(&sl->ref_list[0][0], 0, sizeof(sl->ref_list[0][0]));
     }
 #endif /* CONFIG_ERROR_RESILIENCE */
 
diff --git a/libavcodec/h264_ps.c b/libavcodec/h264_ps.c
index 4070490..7174d5b 100644
--- a/libavcodec/h264_ps.c
+++ b/libavcodec/h264_ps.c
@@ -371,7 +371,8 @@
                                   "Different chroma and luma bit depth");
             goto fail;
         }
-        if (sps->bit_depth_luma > 14U || sps->bit_depth_chroma > 14U) {
+        if (sps->bit_depth_luma   < 8 || sps->bit_depth_luma   > 14 ||
+            sps->bit_depth_chroma < 8 || sps->bit_depth_chroma > 14) {
             av_log(h->avctx, AV_LOG_ERROR, "illegal bit depth value (%d, %d)\n",
                    sps->bit_depth_luma, sps->bit_depth_chroma);
             goto fail;
@@ -459,10 +460,10 @@
 #endif
     sps->crop = get_bits1(&h->gb);
     if (sps->crop) {
-        int crop_left   = get_ue_golomb(&h->gb);
-        int crop_right  = get_ue_golomb(&h->gb);
-        int crop_top    = get_ue_golomb(&h->gb);
-        int crop_bottom = get_ue_golomb(&h->gb);
+        unsigned int crop_left   = get_ue_golomb(&h->gb);
+        unsigned int crop_right  = get_ue_golomb(&h->gb);
+        unsigned int crop_top    = get_ue_golomb(&h->gb);
+        unsigned int crop_bottom = get_ue_golomb(&h->gb);
         int width  = 16 * sps->mb_width;
         int height = 16 * sps->mb_height * (2 - sps->frame_mbs_only_flag);
 
diff --git a/libavcodec/h264_refs.c b/libavcodec/h264_refs.c
index 78c283c..6d72d2a 100644
--- a/libavcodec/h264_refs.c
+++ b/libavcodec/h264_refs.c
@@ -36,31 +36,34 @@
 
 #include <assert.h>
 
-#define COPY_PICTURE(dst, src) \
-do {\
-    *(dst) = *(src);\
-    (dst)->f.extended_data = (dst)->f.data;\
-    (dst)->tf.f = &(dst)->f;\
-} while (0)
-
-
-static void pic_as_field(H264Picture *pic, const int parity){
+static void pic_as_field(H264Ref *pic, const int parity)
+{
     int i;
-    for (i = 0; i < 4; ++i) {
+    for (i = 0; i < FF_ARRAY_ELEMS(pic->data); ++i) {
         if (parity == PICT_BOTTOM_FIELD)
-            pic->f.data[i] += pic->f.linesize[i];
+            pic->data[i]   += pic->linesize[i];
         pic->reference      = parity;
-        pic->f.linesize[i] *= 2;
+        pic->linesize[i] *= 2;
     }
-    pic->poc= pic->field_poc[parity == PICT_BOTTOM_FIELD];
+    pic->poc = pic->parent->field_poc[parity == PICT_BOTTOM_FIELD];
 }
 
-static int split_field_copy(H264Picture *dest, H264Picture *src, int parity, int id_add)
+static void ref_from_h264pic(H264Ref *dst, H264Picture *src)
+{
+    memcpy(dst->data,     src->f.data,     sizeof(dst->data));
+    memcpy(dst->linesize, src->f.linesize, sizeof(dst->linesize));
+    dst->reference = src->reference;
+    dst->poc       = src->poc;
+    dst->pic_id    = src->pic_id;
+    dst->parent = src;
+}
+
+static int split_field_copy(H264Ref *dest, H264Picture *src, int parity, int id_add)
 {
     int match = !!(src->reference & parity);
 
     if (match) {
-        COPY_PICTURE(dest, src);
+        ref_from_h264pic(dest, src);
         if (parity != PICT_FRAME) {
             pic_as_field(dest, parity);
             dest->pic_id *= 2;
@@ -71,7 +74,7 @@
     return match;
 }
 
-static int build_def_list(H264Picture *def, int def_len,
+static int build_def_list(H264Ref *def, int def_len,
                           H264Picture **in, int len, int is_long, int sel)
 {
     int  i[2] = { 0 };
@@ -119,11 +122,11 @@
     return out_i;
 }
 
-int ff_h264_fill_default_ref_list(H264Context *h)
+int ff_h264_fill_default_ref_list(H264Context *h, H264SliceContext *sl)
 {
     int i, len;
 
-    if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
+    if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
         H264Picture *sorted[32];
         int cur_poc, list;
         int lens[2];
@@ -145,20 +148,17 @@
                                   h->long_ref, 16, 1, h->picture_structure);
             av_assert0(len <= 32);
 
-            if (len < h->ref_count[list])
-                memset(&h->default_ref_list[list][len], 0, sizeof(H264Picture) * (h->ref_count[list] - len));
+            if (len < sl->ref_count[list])
+                memset(&h->default_ref_list[list][len], 0, sizeof(H264Ref) * (sl->ref_count[list] - len));
             lens[list] = len;
         }
 
         if (lens[0] == lens[1] && lens[1] > 1) {
             for (i = 0; i < lens[0] &&
-                        h->default_ref_list[0][i].f.buf[0]->buffer ==
-                        h->default_ref_list[1][i].f.buf[0]->buffer; i++);
+                        h->default_ref_list[0][i].parent->f.buf[0]->buffer ==
+                        h->default_ref_list[1][i].parent->f.buf[0]->buffer; i++);
             if (i == lens[0]) {
-                H264Picture tmp;
-                COPY_PICTURE(&tmp, &h->default_ref_list[1][0]);
-                COPY_PICTURE(&h->default_ref_list[1][0], &h->default_ref_list[1][1]);
-                COPY_PICTURE(&h->default_ref_list[1][1], &tmp);
+                FFSWAP(H264Ref, h->default_ref_list[1][0], h->default_ref_list[1][1]);
             }
         }
     } else {
@@ -169,18 +169,18 @@
                               h-> long_ref, 16, 1, h->picture_structure);
         av_assert0(len <= 32);
 
-        if (len < h->ref_count[0])
-            memset(&h->default_ref_list[0][len], 0, sizeof(H264Picture) * (h->ref_count[0] - len));
+        if (len < sl->ref_count[0])
+            memset(&h->default_ref_list[0][len], 0, sizeof(H264Ref) * (sl->ref_count[0] - len));
     }
 #ifdef TRACE
-    for (i = 0; i < h->ref_count[0]; i++) {
+    for (i = 0; i < sl->ref_count[0]; i++) {
         tprintf(h->avctx, "List0: %s fn:%d 0x%p\n",
                 (h->default_ref_list[0][i].long_ref ? "LT" : "ST"),
                 h->default_ref_list[0][i].pic_id,
                 h->default_ref_list[0][i].f.data[0]);
     }
-    if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
-        for (i = 0; i < h->ref_count[1]; i++) {
+    if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
+        for (i = 0; i < sl->ref_count[1]; i++) {
             tprintf(h->avctx, "List1: %s fn:%d 0x%p\n",
                     (h->default_ref_list[1][i].long_ref ? "LT" : "ST"),
                     h->default_ref_list[1][i].pic_id,
@@ -217,22 +217,21 @@
     return pic_num;
 }
 
-int ff_h264_decode_ref_pic_list_reordering(H264Context *h)
+int ff_h264_decode_ref_pic_list_reordering(H264Context *h, H264SliceContext *sl)
 {
-    int list, index, pic_structure, i;
+    int list, index, pic_structure;
 
     print_short_term(h);
     print_long_term(h);
 
-    for (list = 0; list < h->list_count; list++) {
-        for (i = 0; i < h->ref_count[list]; i++)
-            COPY_PICTURE(&h->ref_list[list][i], &h->default_ref_list[list][i]);
+    for (list = 0; list < sl->list_count; list++) {
+        memcpy(sl->ref_list[list], h->default_ref_list[list], sl->ref_count[list] * sizeof(sl->ref_list[0][0]));
 
-        if (get_bits1(&h->gb)) {    // ref_pic_list_modification_flag_l[01]
+        if (get_bits1(&sl->gb)) {    // ref_pic_list_modification_flag_l[01]
             int pred = h->curr_pic_num;
 
             for (index = 0; ; index++) {
-                unsigned int modification_of_pic_nums_idc = get_ue_golomb_31(&h->gb);
+                unsigned int modification_of_pic_nums_idc = get_ue_golomb_31(&sl->gb);
                 unsigned int pic_id;
                 int i;
                 H264Picture *ref = NULL;
@@ -240,7 +239,7 @@
                 if (modification_of_pic_nums_idc == 3)
                     break;
 
-                if (index >= h->ref_count[list]) {
+                if (index >= sl->ref_count[list]) {
                     av_log(h->avctx, AV_LOG_ERROR, "reference count overflow\n");
                     return -1;
                 }
@@ -248,7 +247,7 @@
                 switch (modification_of_pic_nums_idc) {
                 case 0:
                 case 1: {
-                    const unsigned int abs_diff_pic_num = get_ue_golomb(&h->gb) + 1;
+                    const unsigned int abs_diff_pic_num = get_ue_golomb(&sl->gb) + 1;
                     int frame_num;
 
                     if (abs_diff_pic_num > h->max_pic_num) {
@@ -279,7 +278,7 @@
                 }
                 case 2: {
                     int long_idx;
-                    pic_id = get_ue_golomb(&h->gb); // long_term_pic_idx
+                    pic_id = get_ue_golomb(&sl->gb); // long_term_pic_idx
 
                     long_idx = pic_num_extract(h, pic_id, &pic_structure);
 
@@ -309,68 +308,73 @@
                 if (i < 0) {
                     av_log(h->avctx, AV_LOG_ERROR,
                            "reference picture missing during reorder\n");
-                    memset(&h->ref_list[list][index], 0, sizeof(H264Picture)); // FIXME
+                    memset(&sl->ref_list[list][index], 0, sizeof(sl->ref_list[0][0])); // FIXME
                 } else {
-                    for (i = index; i + 1 < h->ref_count[list]; i++) {
-                        if (ref->long_ref == h->ref_list[list][i].long_ref &&
-                            ref->pic_id   == h->ref_list[list][i].pic_id)
+                    for (i = index; i + 1 < sl->ref_count[list]; i++) {
+                        if (sl->ref_list[list][i].parent &&
+                            ref->long_ref == sl->ref_list[list][i].parent->long_ref &&
+                            ref->pic_id   == sl->ref_list[list][i].pic_id)
                             break;
                     }
                     for (; i > index; i--) {
-                        COPY_PICTURE(&h->ref_list[list][i], &h->ref_list[list][i - 1]);
+                        sl->ref_list[list][i] = sl->ref_list[list][i - 1];
                     }
-                    COPY_PICTURE(&h->ref_list[list][index], ref);
+                    ref_from_h264pic(&sl->ref_list[list][index], ref);
                     if (FIELD_PICTURE(h)) {
-                        pic_as_field(&h->ref_list[list][index], pic_structure);
+                        pic_as_field(&sl->ref_list[list][index], pic_structure);
                     }
                 }
             }
         }
     }
-    for (list = 0; list < h->list_count; list++) {
-        for (index = 0; index < h->ref_count[list]; index++) {
-            if (   !h->ref_list[list][index].f.buf[0]
-                || (!FIELD_PICTURE(h) && (h->ref_list[list][index].reference&3) != 3)) {
+    for (list = 0; list < sl->list_count; list++) {
+        for (index = 0; index < sl->ref_count[list]; index++) {
+            if (   !sl->ref_list[list][index].parent
+                || (!FIELD_PICTURE(h) && (sl->ref_list[list][index].reference&3) != 3)) {
                 int i;
                 av_log(h->avctx, AV_LOG_ERROR, "Missing reference picture, default is %d\n", h->default_ref_list[list][0].poc);
                 for (i = 0; i < FF_ARRAY_ELEMS(h->last_pocs); i++)
                     h->last_pocs[i] = INT_MIN;
-                if (h->default_ref_list[list][0].f.buf[0]
+                if (h->default_ref_list[list][0].parent
                     && !(!FIELD_PICTURE(h) && (h->default_ref_list[list][0].reference&3) != 3))
-                    COPY_PICTURE(&h->ref_list[list][index], &h->default_ref_list[list][0]);
+                    sl->ref_list[list][index] = h->default_ref_list[list][0];
                 else
                     return -1;
             }
-            av_assert0(av_buffer_get_ref_count(h->ref_list[list][index].f.buf[0]) > 0);
+            av_assert0(av_buffer_get_ref_count(sl->ref_list[list][index].parent->f.buf[0]) > 0);
         }
     }
 
     return 0;
 }
 
-void ff_h264_fill_mbaff_ref_list(H264Context *h)
+void ff_h264_fill_mbaff_ref_list(H264Context *h, H264SliceContext *sl)
 {
     int list, i, j;
-    for (list = 0; list < h->list_count; list++) {
-        for (i = 0; i < h->ref_count[list]; i++) {
-            H264Picture *frame = &h->ref_list[list][i];
-            H264Picture *field = &h->ref_list[list][16 + 2 * i];
-            COPY_PICTURE(field, frame);
-            for (j = 0; j < 3; j++)
-                field[0].f.linesize[j] <<= 1;
-            field[0].reference = PICT_TOP_FIELD;
-            field[0].poc       = field[0].field_poc[0];
-            COPY_PICTURE(field + 1, field);
-            for (j = 0; j < 3; j++)
-                field[1].f.data[j] += frame->f.linesize[j];
-            field[1].reference = PICT_BOTTOM_FIELD;
-            field[1].poc       = field[1].field_poc[1];
+    for (list = 0; list < sl->list_count; list++) {
+        for (i = 0; i < sl->ref_count[list]; i++) {
+            H264Ref *frame = &sl->ref_list[list][i];
+            H264Ref *field = &sl->ref_list[list][16 + 2 * i];
 
-            h->luma_weight[16 + 2 * i][list][0] = h->luma_weight[16 + 2 * i + 1][list][0] = h->luma_weight[i][list][0];
-            h->luma_weight[16 + 2 * i][list][1] = h->luma_weight[16 + 2 * i + 1][list][1] = h->luma_weight[i][list][1];
+            field[0] = *frame;
+
+            for (j = 0; j < 3; j++)
+                field[0].linesize[j] <<= 1;
+            field[0].reference = PICT_TOP_FIELD;
+            field[0].poc       = field[0].parent->field_poc[0];
+
+            field[1] = field[0];
+
+            for (j = 0; j < 3; j++)
+                field[1].data[j] += frame->parent->f.linesize[j];
+            field[1].reference = PICT_BOTTOM_FIELD;
+            field[1].poc       = field[1].parent->field_poc[1];
+
+            sl->luma_weight[16 + 2 * i][list][0] = sl->luma_weight[16 + 2 * i + 1][list][0] = sl->luma_weight[i][list][0];
+            sl->luma_weight[16 + 2 * i][list][1] = sl->luma_weight[16 + 2 * i + 1][list][1] = sl->luma_weight[i][list][1];
             for (j = 0; j < 2; j++) {
-                h->chroma_weight[16 + 2 * i][list][j][0] = h->chroma_weight[16 + 2 * i + 1][list][j][0] = h->chroma_weight[i][list][j][0];
-                h->chroma_weight[16 + 2 * i][list][j][1] = h->chroma_weight[16 + 2 * i + 1][list][j][1] = h->chroma_weight[i][list][j][1];
+                sl->chroma_weight[16 + 2 * i][list][j][0] = sl->chroma_weight[16 + 2 * i + 1][list][j][0] = sl->chroma_weight[i][list][j][0];
+                sl->chroma_weight[16 + 2 * i][list][j][1] = sl->chroma_weight[16 + 2 * i + 1][list][j][1] = sl->chroma_weight[i][list][j][1];
             }
         }
     }
@@ -493,9 +497,10 @@
     }
     assert(h->long_ref_count == 0);
 
-    ff_h264_unref_picture(h, &h->last_pic_for_ec);
-    if (h->short_ref_count)
+    if (h->short_ref_count && !h->last_pic_for_ec.f.data[0]) {
+        ff_h264_unref_picture(h, &h->last_pic_for_ec);
         ff_h264_ref_picture(h, &h->last_pic_for_ec, h->short_ref[0]);
+    }
 
     for (i = 0; i < h->short_ref_count; i++) {
         unreference_pic(h, h->short_ref[i], 0);
@@ -504,7 +509,8 @@
     h->short_ref_count = 0;
 
     memset(h->default_ref_list, 0, sizeof(h->default_ref_list));
-    memset(h->ref_list, 0, sizeof(h->ref_list));
+    for (i = 0; i < h->nb_slice_ctx; i++)
+        memset(h->slice_ctx[i].ref_list, 0, sizeof(h->slice_ctx[i].ref_list));
 }
 
 /**
diff --git a/libavcodec/h264_slice.c b/libavcodec/h264_slice.c
index 1215d17..44000c7 100644
--- a/libavcodec/h264_slice.c
+++ b/libavcodec/h264_slice.c
@@ -161,21 +161,32 @@
     }
 }
 
-static int alloc_scratch_buffers(H264Context *h, int linesize)
+static int alloc_scratch_buffers(H264SliceContext *sl, int linesize)
 {
+    const H264Context *h = sl->h264;
     int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
 
-    if (h->bipred_scratchpad)
-        return 0;
-
-    h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
+    av_fast_malloc(&sl->bipred_scratchpad, &sl->bipred_scratchpad_allocated, 16 * 6 * alloc_size);
     // edge emu needs blocksize + filter length - 1
     // (= 21x21 for  h264)
-    h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
+    av_fast_malloc(&sl->edge_emu_buffer, &sl->edge_emu_buffer_allocated, alloc_size * 2 * 21);
 
-    if (!h->bipred_scratchpad || !h->edge_emu_buffer) {
-        av_freep(&h->bipred_scratchpad);
-        av_freep(&h->edge_emu_buffer);
+    av_fast_malloc(&sl->top_borders[0], &sl->top_borders_allocated[0],
+                   h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);
+    av_fast_malloc(&sl->top_borders[1], &sl->top_borders_allocated[1],
+                   h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);
+
+    if (!sl->bipred_scratchpad || !sl->edge_emu_buffer ||
+        !sl->top_borders[0]    || !sl->top_borders[1]) {
+        av_freep(&sl->bipred_scratchpad);
+        av_freep(&sl->edge_emu_buffer);
+        av_freep(&sl->top_borders[0]);
+        av_freep(&sl->top_borders[1]);
+
+        sl->bipred_scratchpad_allocated = 0;
+        sl->edge_emu_buffer_allocated   = 0;
+        sl->top_borders_allocated[0]    = 0;
+        sl->top_borders_allocated[1]    = 0;
         return AVERROR(ENOMEM);
     }
 
@@ -221,8 +232,6 @@
     if (ret < 0)
         goto fail;
 
-    h->linesize   = pic->f.linesize[0];
-    h->uvlinesize = pic->f.linesize[1];
     pic->crop     = h->sps.crop;
     pic->crop_top = h->sps.crop_top;
     pic->crop_left= h->sps.crop_left;
@@ -362,7 +371,7 @@
     }
 }
 
-void h264_init_dequant_tables(H264Context *h)
+void ff_h264_init_dequant_tables(H264Context *h)
 {
     int i, x;
     init_dequant4_coeff_table(h);
@@ -381,31 +390,6 @@
     }
 }
 
-/**
- * Mimic alloc_tables(), but for every context thread.
- */
-static void clone_tables(H264Context *dst, H264Context *src, int i)
-{
-    dst->intra4x4_pred_mode     = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
-    dst->non_zero_count         = src->non_zero_count;
-    dst->slice_table            = src->slice_table;
-    dst->cbp_table              = src->cbp_table;
-    dst->mb2b_xy                = src->mb2b_xy;
-    dst->mb2br_xy               = src->mb2br_xy;
-    dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
-    dst->mvd_table[0]           = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
-    dst->mvd_table[1]           = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
-    dst->direct_table           = src->direct_table;
-    dst->list_counts            = src->list_counts;
-    dst->DPB                    = src->DPB;
-    dst->cur_pic_ptr            = src->cur_pic_ptr;
-    dst->cur_pic                = src->cur_pic;
-    dst->bipred_scratchpad      = NULL;
-    dst->edge_emu_buffer        = NULL;
-    ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
-                      src->sps.chroma_format_idc);
-}
-
 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
 
 #define REBASE_PICTURE(pic, new_ctx, old_ctx)             \
@@ -479,8 +463,6 @@
          * the current value */
         h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
 
-        av_freep(&h->bipred_scratchpad);
-
         h->width     = h1->width;
         h->height    = h1->height;
         h->mb_height = h1->mb_height;
@@ -512,39 +494,35 @@
         h->cur_chroma_format_idc = h1->cur_chroma_format_idc;
 #endif
     }
-    /* update linesize on resize for h264. The h264 decoder doesn't
-     * necessarily call ff_mpv_frame_start in the new thread */
-    h->linesize   = h1->linesize;
-    h->uvlinesize = h1->uvlinesize;
 
     /* copy block_offset since frame_start may not be called */
     memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
 
     if (!inited) {
+        H264SliceContext *orig_slice_ctx = h->slice_ctx;
+
         for (i = 0; i < MAX_SPS_COUNT; i++)
             av_freep(h->sps_buffers + i);
 
         for (i = 0; i < MAX_PPS_COUNT; i++)
             av_freep(h->pps_buffers + i);
 
-        av_freep(&h->rbsp_buffer[0]);
-        av_freep(&h->rbsp_buffer[1]);
         ff_h264_unref_picture(h, &h->last_pic_for_ec);
-        memcpy(h, h1, offsetof(H264Context, intra_pcm_ptr));
-        memcpy(&h->cabac, &h1->cabac,
-               sizeof(H264Context) - offsetof(H264Context, cabac));
-        av_assert0((void*)&h->cabac == &h->mb_padding + 1);
+        memcpy(h, h1, sizeof(H264Context));
 
         memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
         memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
 
-        memset(&h->er, 0, sizeof(h->er));
-        memset(&h->mb, 0, sizeof(h->mb));
-        memset(&h->mb_luma_dc, 0, sizeof(h->mb_luma_dc));
-        memset(&h->mb_padding, 0, sizeof(h->mb_padding));
         memset(&h->cur_pic, 0, sizeof(h->cur_pic));
         memset(&h->last_pic_for_ec, 0, sizeof(h->last_pic_for_ec));
 
+        h->slice_ctx = orig_slice_ctx;
+
+        memset(&h->slice_ctx[0].er,         0, sizeof(h->slice_ctx[0].er));
+        memset(&h->slice_ctx[0].mb,         0, sizeof(h->slice_ctx[0].mb));
+        memset(&h->slice_ctx[0].mb_luma_dc, 0, sizeof(h->slice_ctx[0].mb_luma_dc));
+        memset(&h->slice_ctx[0].mb_padding, 0, sizeof(h->slice_ctx[0].mb_padding));
+
         h->avctx             = dst;
         h->DPB               = NULL;
         h->qscale_table_pool = NULL;
@@ -562,10 +540,6 @@
         h->list_counts       = NULL;
         h->mb2b_xy           = NULL;
         h->mb2br_xy          = NULL;
-        for (i = 0; i < 2; i++) {
-            h->rbsp_buffer[i] = NULL;
-            h->rbsp_buffer_size[i] = 0;
-        }
 
         if (h1->context_initialized) {
         h->context_initialized = 0;
@@ -579,17 +553,13 @@
             av_log(dst, AV_LOG_ERROR, "Could not allocate memory\n");
             return ret;
         }
-        ret = ff_h264_context_init(h);
+        ret = ff_h264_slice_context_init(h, &h->slice_ctx[0]);
         if (ret < 0) {
             av_log(dst, AV_LOG_ERROR, "context_init() failed.\n");
             return ret;
         }
         }
 
-        h->bipred_scratchpad = NULL;
-        h->edge_emu_buffer   = NULL;
-
-        h->thread_context[0] = h;
         h->context_initialized = h1->context_initialized;
     }
 
@@ -600,7 +570,6 @@
     h->coded_picture_number = h1->coded_picture_number;
     h->first_field          = h1->first_field;
     h->picture_structure    = h1->picture_structure;
-    h->qscale               = h1->qscale;
     h->droppable            = h1->droppable;
     h->low_delay            = h1->low_delay;
 
@@ -613,8 +582,11 @@
 
     h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
     ff_h264_unref_picture(h, &h->cur_pic);
-    if (h1->cur_pic.f.buf[0] && (ret = ff_h264_ref_picture(h, &h->cur_pic, &h1->cur_pic)) < 0)
-        return ret;
+    if (h1->cur_pic.f.buf[0]) {
+        ret = ff_h264_ref_picture(h, &h->cur_pic, &h1->cur_pic);
+        if (ret < 0)
+            return ret;
+    }
 
     h->workaround_bugs = h1->workaround_bugs;
     h->low_delay       = h1->low_delay;
@@ -650,10 +622,10 @@
     h->dequant_coeff_pps = h1->dequant_coeff_pps;
 
     // POC timing
-    copy_fields(h, h1, poc_lsb, redundant_pic_count);
+    copy_fields(h, h1, poc_lsb, default_ref_list);
 
     // reference lists
-    copy_fields(h, h1, short_ref, cabac_init_idc);
+    copy_fields(h, h1, short_ref, current_slice);
 
     copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
     copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
@@ -733,29 +705,32 @@
     h->cur_pic_ptr = pic;
     ff_h264_unref_picture(h, &h->cur_pic);
     if (CONFIG_ERROR_RESILIENCE) {
-        ff_h264_set_erpic(&h->er.cur_pic, NULL);
+        ff_h264_set_erpic(&h->slice_ctx[0].er.cur_pic, NULL);
     }
 
     if ((ret = ff_h264_ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
         return ret;
 
-    if (CONFIG_ERROR_RESILIENCE) {
-        ff_er_frame_start(&h->er);
-        ff_h264_set_erpic(&h->er.last_pic, NULL);
-        ff_h264_set_erpic(&h->er.next_pic, NULL);
+    for (i = 0; i < h->nb_slice_ctx; i++) {
+        h->slice_ctx[i].linesize   = h->cur_pic_ptr->f.linesize[0];
+        h->slice_ctx[i].uvlinesize = h->cur_pic_ptr->f.linesize[1];
     }
 
-    assert(h->linesize && h->uvlinesize);
+    if (CONFIG_ERROR_RESILIENCE) {
+        ff_er_frame_start(&h->slice_ctx[0].er);
+        ff_h264_set_erpic(&h->slice_ctx[0].er.last_pic, NULL);
+        ff_h264_set_erpic(&h->slice_ctx[0].er.next_pic, NULL);
+    }
 
     for (i = 0; i < 16; i++) {
-        h->block_offset[i]           = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
-        h->block_offset[48 + i]      = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
+        h->block_offset[i]           = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * pic->f.linesize[0] * ((scan8[i] - scan8[0]) >> 3);
+        h->block_offset[48 + i]      = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * pic->f.linesize[0] * ((scan8[i] - scan8[0]) >> 3);
     }
     for (i = 0; i < 16; i++) {
         h->block_offset[16 + i]      =
-        h->block_offset[32 + i]      = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
+        h->block_offset[32 + i]      = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * pic->f.linesize[1] * ((scan8[i] - scan8[0]) >> 3);
         h->block_offset[48 + 16 + i] =
-        h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
+        h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * pic->f.linesize[1] * ((scan8[i] - scan8[0]) >> 3);
     }
 
     /* We mark the current picture as non-reference after allocating it, so
@@ -773,7 +748,8 @@
     return 0;
 }
 
-static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
+static av_always_inline void backup_mb_border(const H264Context *h, H264SliceContext *sl,
+                                              uint8_t *src_y,
                                               uint8_t *src_cb, uint8_t *src_cr,
                                               int linesize, int uvlinesize,
                                               int simple)
@@ -789,9 +765,9 @@
     src_cr -= uvlinesize;
 
     if (!simple && FRAME_MBAFF(h)) {
-        if (h->mb_y & 1) {
-            if (!MB_MBAFF(h)) {
-                top_border = h->top_borders[0][h->mb_x];
+        if (sl->mb_y & 1) {
+            if (!MB_MBAFF(sl)) {
+                top_border = sl->top_borders[0][sl->mb_x];
                 AV_COPY128(top_border, src_y + 15 * linesize);
                 if (pixel_shift)
                     AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
@@ -825,13 +801,13 @@
                     }
                 }
             }
-        } else if (MB_MBAFF(h)) {
+        } else if (MB_MBAFF(sl)) {
             top_idx = 0;
         } else
             return;
     }
 
-    top_border = h->top_borders[top_idx][h->mb_x];
+    top_border = sl->top_borders[top_idx][sl->mb_x];
     /* There are two lines saved, the line above the top macroblock
      * of a pair, and the line above the bottom macroblock. */
     AV_COPY128(top_border, src_y + 16 * linesize);
@@ -874,13 +850,13 @@
  * @param field  0/1 initialize the weight for interlaced MBAFF
  *                -1 initializes the rest
  */
-static void implicit_weight_table(H264Context *h, int field)
+static void implicit_weight_table(const H264Context *h, H264SliceContext *sl, int field)
 {
     int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
 
     for (i = 0; i < 2; i++) {
-        h->luma_weight_flag[i]   = 0;
-        h->chroma_weight_flag[i] = 0;
+        sl->luma_weight_flag[i]   = 0;
+        sl->chroma_weight_flag[i] = 0;
     }
 
     if (field < 0) {
@@ -889,36 +865,36 @@
         } else {
             cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
         }
-        if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
-            h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
-            h->use_weight        = 0;
-            h->use_weight_chroma = 0;
+        if (sl->ref_count[0] == 1 && sl->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
+            sl->ref_list[0][0].poc + sl->ref_list[1][0].poc == 2 * cur_poc) {
+            sl->use_weight        = 0;
+            sl->use_weight_chroma = 0;
             return;
         }
         ref_start  = 0;
-        ref_count0 = h->ref_count[0];
-        ref_count1 = h->ref_count[1];
+        ref_count0 = sl->ref_count[0];
+        ref_count1 = sl->ref_count[1];
     } else {
         cur_poc    = h->cur_pic_ptr->field_poc[field];
         ref_start  = 16;
-        ref_count0 = 16 + 2 * h->ref_count[0];
-        ref_count1 = 16 + 2 * h->ref_count[1];
+        ref_count0 = 16 + 2 * sl->ref_count[0];
+        ref_count1 = 16 + 2 * sl->ref_count[1];
     }
 
-    h->use_weight               = 2;
-    h->use_weight_chroma        = 2;
-    h->luma_log2_weight_denom   = 5;
-    h->chroma_log2_weight_denom = 5;
+    sl->use_weight               = 2;
+    sl->use_weight_chroma        = 2;
+    sl->luma_log2_weight_denom   = 5;
+    sl->chroma_log2_weight_denom = 5;
 
     for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
-        int poc0 = h->ref_list[0][ref0].poc;
+        int poc0 = sl->ref_list[0][ref0].poc;
         for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
             int w = 32;
-            if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
-                int poc1 = h->ref_list[1][ref1].poc;
-                int td   = av_clip(poc1 - poc0, -128, 127);
+            if (!sl->ref_list[0][ref0].parent->long_ref && !sl->ref_list[1][ref1].parent->long_ref) {
+                int poc1 = sl->ref_list[1][ref1].poc;
+                int td   = av_clip_int8(poc1 - poc0);
                 if (td) {
-                    int tb = av_clip(cur_poc - poc0, -128, 127);
+                    int tb = av_clip_int8(cur_poc - poc0);
                     int tx = (16384 + (FFABS(td) >> 1)) / td;
                     int dist_scale_factor = (tb * tx + 32) >> 8;
                     if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
@@ -926,10 +902,10 @@
                 }
             }
             if (field < 0) {
-                h->implicit_weight[ref0][ref1][0] =
-                h->implicit_weight[ref0][ref1][1] = w;
+                sl->implicit_weight[ref0][ref1][0] =
+                sl->implicit_weight[ref0][ref1][1] = w;
             } else {
-                h->implicit_weight[ref0][ref1][field] = w;
+                sl->implicit_weight[ref0][ref1][field] = w;
             }
         }
     }
@@ -972,34 +948,6 @@
     }
 }
 
-/**
- * Replicate H264 "master" context to thread contexts.
- */
-static int clone_slice(H264Context *dst, H264Context *src)
-{
-    memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
-    dst->cur_pic_ptr = src->cur_pic_ptr;
-    dst->cur_pic     = src->cur_pic;
-    dst->linesize    = src->linesize;
-    dst->uvlinesize  = src->uvlinesize;
-    dst->first_field = src->first_field;
-
-    dst->prev_poc_msb          = src->prev_poc_msb;
-    dst->prev_poc_lsb          = src->prev_poc_lsb;
-    dst->prev_frame_num_offset = src->prev_frame_num_offset;
-    dst->prev_frame_num        = src->prev_frame_num;
-    dst->short_ref_count       = src->short_ref_count;
-
-    memcpy(dst->short_ref,        src->short_ref,        sizeof(dst->short_ref));
-    memcpy(dst->long_ref,         src->long_ref,         sizeof(dst->long_ref));
-    memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
-
-    memcpy(dst->dequant4_coeff,   src->dequant4_coeff,   sizeof(src->dequant4_coeff));
-    memcpy(dst->dequant8_coeff,   src->dequant8_coeff,   sizeof(src->dequant8_coeff));
-
-    return 0;
-}
-
 static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
 {
 #define HWACCEL_MAX (CONFIG_H264_DXVA2_HWACCEL + \
@@ -1193,55 +1141,25 @@
     h->slice_context_count = nb_slices;
 
     if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
-        ret = ff_h264_context_init(h);
+        ret = ff_h264_slice_context_init(h, &h->slice_ctx[0]);
         if (ret < 0) {
             av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
             goto fail;
         }
     } else {
-        for (i = 1; i < h->slice_context_count; i++) {
-            H264Context *c;
-            c                    = h->thread_context[i] = av_mallocz(sizeof(H264Context));
-            if (!c) {
-                ret = AVERROR(ENOMEM);
-                goto fail;
-            }
-            c->avctx             = h->avctx;
-            c->vdsp              = h->vdsp;
-            c->h264dsp           = h->h264dsp;
-            c->h264qpel          = h->h264qpel;
-            c->h264chroma        = h->h264chroma;
-            c->sps               = h->sps;
-            c->pps               = h->pps;
-            c->pixel_shift       = h->pixel_shift;
-            c->cur_chroma_format_idc = h->cur_chroma_format_idc;
-            c->width             = h->width;
-            c->height            = h->height;
-            c->linesize          = h->linesize;
-            c->uvlinesize        = h->uvlinesize;
-            c->chroma_x_shift    = h->chroma_x_shift;
-            c->chroma_y_shift    = h->chroma_y_shift;
-            c->qscale            = h->qscale;
-            c->droppable         = h->droppable;
-            c->low_delay         = h->low_delay;
-            c->mb_width          = h->mb_width;
-            c->mb_height         = h->mb_height;
-            c->mb_stride         = h->mb_stride;
-            c->mb_num            = h->mb_num;
-            c->flags             = h->flags;
-            c->workaround_bugs   = h->workaround_bugs;
-            c->pict_type         = h->pict_type;
+        for (i = 0; i < h->slice_context_count; i++) {
+            H264SliceContext *sl = &h->slice_ctx[i];
 
-            init_scan_tables(c);
-            clone_tables(c, h, i);
-            c->context_initialized = 1;
-        }
+            sl->h264               = h;
+            sl->intra4x4_pred_mode = h->intra4x4_pred_mode + i * 8 * 2 * h->mb_stride;
+            sl->mvd_table[0]       = h->mvd_table[0]       + i * 8 * 2 * h->mb_stride;
+            sl->mvd_table[1]       = h->mvd_table[1]       + i * 8 * 2 * h->mb_stride;
 
-        for (i = 0; i < h->slice_context_count; i++)
-            if ((ret = ff_h264_context_init(h->thread_context[i])) < 0) {
+            if ((ret = ff_h264_slice_context_init(h, sl)) < 0) {
                 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
                 goto fail;
             }
+        }
     }
 
     h->context_initialized = 1;
@@ -1269,12 +1187,10 @@
  * This will (re)intialize the decoder and call h264_frame_start() as needed.
  *
  * @param h h264context
- * @param h0 h264 master context (differs from 'h' when doing sliced based
- *           parallel decoding)
  *
  * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
  */
-int ff_h264_decode_slice_header(H264Context *h, H264Context *h0)
+int ff_h264_decode_slice_header(H264Context *h, H264SliceContext *sl)
 {
     unsigned int first_mb_in_slice;
     unsigned int pps_id;
@@ -1284,22 +1200,22 @@
     int must_reinit;
     int needs_reinit = 0;
     int field_pic_flag, bottom_field_flag;
-    int first_slice = h == h0 && !h0->current_slice;
+    int first_slice = sl == h->slice_ctx && !h->current_slice;
     int frame_num, picture_structure, droppable;
     PPS *pps;
 
     h->qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
     h->qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
 
-    first_mb_in_slice = get_ue_golomb_long(&h->gb);
+    first_mb_in_slice = get_ue_golomb_long(&sl->gb);
 
     if (first_mb_in_slice == 0) { // FIXME better field boundary detection
-        if (h0->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {
-            ff_h264_field_end(h, 1);
+        if (h->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {
+            ff_h264_field_end(h, sl, 1);
         }
 
-        h0->current_slice = 0;
-        if (!h0->first_field) {
+        h->current_slice = 0;
+        if (!h->first_field) {
             if (h->cur_pic_ptr && !h->droppable) {
                 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
                                           h->picture_structure == PICT_BOTTOM_FIELD);
@@ -1308,72 +1224,82 @@
         }
     }
 
-    slice_type = get_ue_golomb_31(&h->gb);
+    slice_type = get_ue_golomb_31(&sl->gb);
     if (slice_type > 9) {
         av_log(h->avctx, AV_LOG_ERROR,
-               "slice type %d too large at %d %d\n",
-               slice_type, h->mb_x, h->mb_y);
+               "slice type %d too large at %d\n",
+               slice_type, first_mb_in_slice);
         return AVERROR_INVALIDDATA;
     }
     if (slice_type > 4) {
         slice_type -= 5;
-        h->slice_type_fixed = 1;
+        sl->slice_type_fixed = 1;
     } else
-        h->slice_type_fixed = 0;
+        sl->slice_type_fixed = 0;
 
     slice_type = golomb_to_pict_type[slice_type];
-    h->slice_type     = slice_type;
-    h->slice_type_nos = slice_type & 3;
+
+    sl->slice_type     = slice_type;
+    sl->slice_type_nos = slice_type & 3;
 
     if (h->nal_unit_type  == NAL_IDR_SLICE &&
-        h->slice_type_nos != AV_PICTURE_TYPE_I) {
+        sl->slice_type_nos != AV_PICTURE_TYPE_I) {
         av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
         return AVERROR_INVALIDDATA;
     }
 
     if (
         (h->avctx->skip_frame >= AVDISCARD_NONREF && !h->nal_ref_idc) ||
-        (h->avctx->skip_frame >= AVDISCARD_BIDIR  && h->slice_type_nos == AV_PICTURE_TYPE_B) ||
-        (h->avctx->skip_frame >= AVDISCARD_NONINTRA && h->slice_type_nos != AV_PICTURE_TYPE_I) ||
+        (h->avctx->skip_frame >= AVDISCARD_BIDIR  && sl->slice_type_nos == AV_PICTURE_TYPE_B) ||
+        (h->avctx->skip_frame >= AVDISCARD_NONINTRA && sl->slice_type_nos != AV_PICTURE_TYPE_I) ||
         (h->avctx->skip_frame >= AVDISCARD_NONKEY && h->nal_unit_type != NAL_IDR_SLICE) ||
          h->avctx->skip_frame >= AVDISCARD_ALL) {
          return SLICE_SKIPED;
      }
 
     // to make a few old functions happy, it's wrong though
-    h->pict_type = h->slice_type;
+    h->pict_type = sl->slice_type;
 
-    pps_id = get_ue_golomb(&h->gb);
+    pps_id = get_ue_golomb(&sl->gb);
     if (pps_id >= MAX_PPS_COUNT) {
         av_log(h->avctx, AV_LOG_ERROR, "pps_id %u out of range\n", pps_id);
         return AVERROR_INVALIDDATA;
     }
-    if (!h0->pps_buffers[pps_id]) {
+    if (!h->pps_buffers[pps_id]) {
         av_log(h->avctx, AV_LOG_ERROR,
                "non-existing PPS %u referenced\n",
                pps_id);
         return AVERROR_INVALIDDATA;
     }
-    if (h0->au_pps_id >= 0 && pps_id != h0->au_pps_id) {
+    if (h->au_pps_id >= 0 && pps_id != h->au_pps_id) {
         av_log(h->avctx, AV_LOG_ERROR,
                "PPS change from %d to %d forbidden\n",
-               h0->au_pps_id, pps_id);
+               h->au_pps_id, pps_id);
         return AVERROR_INVALIDDATA;
     }
-    h->pps = *h0->pps_buffers[pps_id];
 
-    if (!h0->sps_buffers[h->pps.sps_id]) {
+    pps = h->pps_buffers[pps_id];
+
+    if (!h->sps_buffers[pps->sps_id]) {
         av_log(h->avctx, AV_LOG_ERROR,
                "non-existing SPS %u referenced\n",
                h->pps.sps_id);
         return AVERROR_INVALIDDATA;
     }
+    if (first_slice)
+        h->pps = *h->pps_buffers[pps_id];
 
-    if (h->pps.sps_id != h->sps.sps_id ||
-        h->pps.sps_id != h->current_sps_id ||
-        h0->sps_buffers[h->pps.sps_id]->new) {
+    if (pps->sps_id != h->sps.sps_id ||
+        pps->sps_id != h->current_sps_id ||
+        h->sps_buffers[pps->sps_id]->new) {
 
-        h->sps = *h0->sps_buffers[h->pps.sps_id];
+        if (!first_slice) {
+            av_log(h->avctx, AV_LOG_ERROR,
+               "SPS changed in the middle of the frame\n");
+            return AVERROR_INVALIDDATA;
+        }
+
+        h->sps = *h->sps_buffers[h->pps.sps_id];
 
         if (h->mb_width  != h->sps.mb_width ||
             h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||
@@ -1404,7 +1330,7 @@
                      || h->mb_width  != h->sps.mb_width
                      || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag)
                     ));
-    if (non_j_pixfmt(h0->avctx->pix_fmt) != non_j_pixfmt(get_pixel_format(h0, 0)))
+    if (non_j_pixfmt(h->avctx->pix_fmt) != non_j_pixfmt(get_pixel_format(h, 0)))
         must_reinit = 1;
 
     if (first_slice && av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio))
@@ -1440,13 +1366,13 @@
 
     if (h->context_initialized &&
         (must_reinit || needs_reinit)) {
-        if (h != h0) {
+        if (sl != h->slice_ctx) {
             av_log(h->avctx, AV_LOG_ERROR,
                    "changing width %d -> %d / height %d -> %d on "
                    "slice %d\n",
                    h->width, h->avctx->coded_width,
                    h->height, h->avctx->coded_height,
-                   h0->current_slice + 1);
+                   h->current_slice + 1);
             return AVERROR_INVALIDDATA;
         }
 
@@ -1468,7 +1394,7 @@
         }
     }
     if (!h->context_initialized) {
-        if (h != h0) {
+        if (sl != h->slice_ctx) {
             av_log(h->avctx, AV_LOG_ERROR,
                    "Cannot (re-)initialize context during parallel decoding.\n");
             return AVERROR_PATCHWELCOME;
@@ -1485,24 +1411,24 @@
         }
     }
 
-    if (h == h0 && h->dequant_coeff_pps != pps_id) {
+    if (first_slice && h->dequant_coeff_pps != pps_id) {
         h->dequant_coeff_pps = pps_id;
-        h264_init_dequant_tables(h);
+        ff_h264_init_dequant_tables(h);
     }
 
-    frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
+    frame_num = get_bits(&sl->gb, h->sps.log2_max_frame_num);
     if (!first_slice) {
-        if (h0->frame_num != frame_num) {
+        if (h->frame_num != frame_num) {
             av_log(h->avctx, AV_LOG_ERROR, "Frame num change from %d to %d\n",
-                   h0->frame_num, frame_num);
+                   h->frame_num, frame_num);
             return AVERROR_INVALIDDATA;
         }
     }
 
-    h->mb_mbaff        = 0;
+    sl->mb_mbaff       = 0;
     h->mb_aff_frame    = 0;
-    last_pic_structure = h0->picture_structure;
-    last_pic_droppable = h0->droppable;
+    last_pic_structure = h->picture_structure;
+    last_pic_droppable = h->droppable;
     droppable          = h->nal_ref_idc == 0;
     if (h->sps.frame_mbs_only_flag) {
         picture_structure = PICT_FRAME;
@@ -1511,27 +1437,27 @@
             av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
             return -1;
         }
-        field_pic_flag = get_bits1(&h->gb);
+        field_pic_flag = get_bits1(&sl->gb);
 
         if (field_pic_flag) {
-            bottom_field_flag = get_bits1(&h->gb);
+            bottom_field_flag = get_bits1(&sl->gb);
             picture_structure = PICT_TOP_FIELD + bottom_field_flag;
         } else {
             picture_structure = PICT_FRAME;
             h->mb_aff_frame      = h->sps.mb_aff;
         }
     }
-    if (h0->current_slice) {
+    if (h->current_slice) {
         if (last_pic_structure != picture_structure ||
             last_pic_droppable != droppable) {
             av_log(h->avctx, AV_LOG_ERROR,
                    "Changing field mode (%d -> %d) between slices is not allowed\n",
                    last_pic_structure, h->picture_structure);
             return AVERROR_INVALIDDATA;
-        } else if (!h0->cur_pic_ptr) {
+        } else if (!h->cur_pic_ptr) {
             av_log(h->avctx, AV_LOG_ERROR,
                    "unset cur_pic_ptr on slice %d\n",
-                   h0->current_slice + 1);
+                   h->current_slice + 1);
             return AVERROR_INVALIDDATA;
         }
     }
@@ -1539,9 +1465,9 @@
     h->picture_structure = picture_structure;
     h->droppable         = droppable;
     h->frame_num         = frame_num;
-    h->mb_field_decoding_flag = picture_structure != PICT_FRAME;
+    sl->mb_field_decoding_flag = picture_structure != PICT_FRAME;
 
-    if (h0->current_slice == 0) {
+    if (h->current_slice == 0) {
         /* Shorten frame num gaps so we don't have to allocate reference
          * frames just to throw them away */
         if (h->frame_num != h->prev_frame_num) {
@@ -1565,14 +1491,14 @@
          * decode frames as "finished".
          * We have to do that before the "dummy" in-between frame allocation,
          * since that can modify h->cur_pic_ptr. */
-        if (h0->first_field) {
-            assert(h0->cur_pic_ptr);
-            assert(h0->cur_pic_ptr->f.buf[0]);
-            assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
+        if (h->first_field) {
+            assert(h->cur_pic_ptr);
+            assert(h->cur_pic_ptr->f.buf[0]);
+            assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
 
             /* Mark old field/frame as completed */
-            if (h0->cur_pic_ptr->tf.owner == h0->avctx) {
-                ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
+            if (h->cur_pic_ptr->tf.owner == h->avctx) {
+                ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
                                           last_pic_structure == PICT_BOTTOM_FIELD);
             }
 
@@ -1581,17 +1507,17 @@
                 /* Previous field is unmatched. Don't display it, but let it
                  * remain for reference if marked as such. */
                 if (last_pic_structure != PICT_FRAME) {
-                    ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
+                    ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
                                               last_pic_structure == PICT_TOP_FIELD);
                 }
             } else {
-                if (h0->cur_pic_ptr->frame_num != h->frame_num) {
+                if (h->cur_pic_ptr->frame_num != h->frame_num) {
                     /* This and previous field were reference, but had
                      * different frame_nums. Consider this field first in
                      * pair. Throw away previous field except for reference
                      * purposes. */
                     if (last_pic_structure != PICT_FRAME) {
-                        ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
+                        ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
                                                   last_pic_structure == PICT_TOP_FIELD);
                     }
                 } else {
@@ -1617,7 +1543,7 @@
             }
         }
 
-        while (h->frame_num != h->prev_frame_num && !h0->first_field &&
+        while (h->frame_num != h->prev_frame_num && !h->first_field &&
                h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
             H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
             av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
@@ -1627,7 +1553,7 @@
                     h->last_pocs[i] = INT_MIN;
             ret = h264_frame_start(h);
             if (ret < 0) {
-                h0->first_field = 0;
+                h->first_field = 0;
                 return ret;
             }
 
@@ -1668,41 +1594,41 @@
         /* See if we have a decoded first field looking for a pair...
          * We're using that to see whether to continue decoding in that
          * frame, or to allocate a new one. */
-        if (h0->first_field) {
-            assert(h0->cur_pic_ptr);
-            assert(h0->cur_pic_ptr->f.buf[0]);
-            assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
+        if (h->first_field) {
+            assert(h->cur_pic_ptr);
+            assert(h->cur_pic_ptr->f.buf[0]);
+            assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
 
             /* figure out if we have a complementary field pair */
             if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
                 /* Previous field is unmatched. Don't display it, but let it
                  * remain for reference if marked as such. */
-                h0->missing_fields ++;
-                h0->cur_pic_ptr = NULL;
-                h0->first_field = FIELD_PICTURE(h);
+                h->missing_fields ++;
+                h->cur_pic_ptr = NULL;
+                h->first_field = FIELD_PICTURE(h);
             } else {
-                h0->missing_fields = 0;
-                if (h0->cur_pic_ptr->frame_num != h->frame_num) {
-                    ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
-                                              h0->picture_structure==PICT_BOTTOM_FIELD);
+                h->missing_fields = 0;
+                if (h->cur_pic_ptr->frame_num != h->frame_num) {
+                    ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
+                                              h->picture_structure==PICT_BOTTOM_FIELD);
                     /* This and the previous field had different frame_nums.
                      * Consider this field first in pair. Throw away previous
                      * one except for reference purposes. */
-                    h0->first_field = 1;
-                    h0->cur_pic_ptr = NULL;
+                    h->first_field = 1;
+                    h->cur_pic_ptr = NULL;
                 } else {
                     /* Second field in complementary pair */
-                    h0->first_field = 0;
+                    h->first_field = 0;
                 }
             }
         } else {
             /* Frame or first field in a potentially complementary pair */
-            h0->first_field = FIELD_PICTURE(h);
+            h->first_field = FIELD_PICTURE(h);
         }
 
-        if (!FIELD_PICTURE(h) || h0->first_field) {
+        if (!FIELD_PICTURE(h) || h->first_field) {
             if (h264_frame_start(h) < 0) {
-                h0->first_field = 0;
+                h->first_field = 0;
                 return AVERROR_INVALIDDATA;
             }
         } else {
@@ -1717,19 +1643,9 @@
             memset(h->slice_table, -1,
                 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
         }
-        h0->last_slice_type = -1;
+        h->last_slice_type = -1;
     }
-    if (h != h0 && (ret = clone_slice(h, h0)) < 0)
-        return ret;
 
-    /* can't be in alloc_tables because linesize isn't known there.
-     * FIXME: redo bipred weight to not require extra buffer? */
-    for (i = 0; i < h->slice_context_count; i++)
-        if (h->thread_context[i]) {
-            ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
-            if (ret < 0)
-                return ret;
-        }
 
     h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
 
@@ -1739,12 +1655,12 @@
         av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
         return AVERROR_INVALIDDATA;
     }
-    h->resync_mb_x = h->mb_x =  first_mb_in_slice % h->mb_width;
-    h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<
-                               FIELD_OR_MBAFF_PICTURE(h);
+    sl->resync_mb_x = sl->mb_x =  first_mb_in_slice % h->mb_width;
+    sl->resync_mb_y = sl->mb_y = (first_mb_in_slice / h->mb_width) <<
+                                 FIELD_OR_MBAFF_PICTURE(h);
     if (h->picture_structure == PICT_BOTTOM_FIELD)
-        h->resync_mb_y = h->mb_y = h->mb_y + 1;
-    av_assert1(h->mb_y < h->mb_height);
+        sl->resync_mb_y = sl->mb_y = sl->mb_y + 1;
+    av_assert1(sl->mb_y < h->mb_height);
 
     if (h->picture_structure == PICT_FRAME) {
         h->curr_pic_num = h->frame_num;
@@ -1755,59 +1671,59 @@
     }
 
     if (h->nal_unit_type == NAL_IDR_SLICE)
-        get_ue_golomb(&h->gb); /* idr_pic_id */
+        get_ue_golomb(&sl->gb); /* idr_pic_id */
 
     if (h->sps.poc_type == 0) {
-        h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
+        h->poc_lsb = get_bits(&sl->gb, h->sps.log2_max_poc_lsb);
 
         if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
-            h->delta_poc_bottom = get_se_golomb(&h->gb);
+            h->delta_poc_bottom = get_se_golomb(&sl->gb);
     }
 
     if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
-        h->delta_poc[0] = get_se_golomb(&h->gb);
+        h->delta_poc[0] = get_se_golomb(&sl->gb);
 
         if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
-            h->delta_poc[1] = get_se_golomb(&h->gb);
+            h->delta_poc[1] = get_se_golomb(&sl->gb);
     }
 
     ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);
 
     if (h->pps.redundant_pic_cnt_present)
-        h->redundant_pic_count = get_ue_golomb(&h->gb);
+        sl->redundant_pic_count = get_ue_golomb(&sl->gb);
 
-    ret = ff_set_ref_count(h);
+    ret = ff_set_ref_count(h, sl);
     if (ret < 0)
         return ret;
 
     if (slice_type != AV_PICTURE_TYPE_I &&
-        (h0->current_slice == 0 ||
-         slice_type != h0->last_slice_type ||
-         memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) {
+        (h->current_slice == 0 ||
+         slice_type != h->last_slice_type ||
+         memcmp(h->last_ref_count, sl->ref_count, sizeof(sl->ref_count)))) {
 
-        ff_h264_fill_default_ref_list(h);
+        ff_h264_fill_default_ref_list(h, sl);
     }
 
-    if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
-       ret = ff_h264_decode_ref_pic_list_reordering(h);
+    if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
+       ret = ff_h264_decode_ref_pic_list_reordering(h, sl);
        if (ret < 0) {
-           h->ref_count[1] = h->ref_count[0] = 0;
+           sl->ref_count[1] = sl->ref_count[0] = 0;
            return ret;
        }
     }
 
-    if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
+    if ((h->pps.weighted_pred && sl->slice_type_nos == AV_PICTURE_TYPE_P) ||
         (h->pps.weighted_bipred_idc == 1 &&
-         h->slice_type_nos == AV_PICTURE_TYPE_B))
-        ff_pred_weight_table(h);
+         sl->slice_type_nos == AV_PICTURE_TYPE_B))
+        ff_pred_weight_table(h, sl);
     else if (h->pps.weighted_bipred_idc == 2 &&
-             h->slice_type_nos == AV_PICTURE_TYPE_B) {
-        implicit_weight_table(h, -1);
+             sl->slice_type_nos == AV_PICTURE_TYPE_B) {
+        implicit_weight_table(h, sl, -1);
     } else {
-        h->use_weight = 0;
+        sl->use_weight = 0;
         for (i = 0; i < 2; i++) {
-            h->luma_weight_flag[i]   = 0;
-            h->chroma_weight_flag[i] = 0;
+            sl->luma_weight_flag[i]   = 0;
+            sl->chroma_weight_flag[i] = 0;
         }
     }
 
@@ -1817,75 +1733,75 @@
     // further down the line. This may break decoding if the first slice is
     // corrupt, thus we only do this if frame-mt is enabled.
     if (h->nal_ref_idc) {
-        ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,
+        ret = ff_h264_decode_ref_pic_marking(h, &sl->gb,
                                              !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
-                                             h0->current_slice == 0);
+                                             h->current_slice == 0);
         if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
             return AVERROR_INVALIDDATA;
     }
 
     if (FRAME_MBAFF(h)) {
-        ff_h264_fill_mbaff_ref_list(h);
+        ff_h264_fill_mbaff_ref_list(h, sl);
 
-        if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
-            implicit_weight_table(h, 0);
-            implicit_weight_table(h, 1);
+        if (h->pps.weighted_bipred_idc == 2 && sl->slice_type_nos == AV_PICTURE_TYPE_B) {
+            implicit_weight_table(h, sl, 0);
+            implicit_weight_table(h, sl, 1);
         }
     }
 
-    if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
-        ff_h264_direct_dist_scale_factor(h);
-    ff_h264_direct_ref_list_init(h);
+    if (sl->slice_type_nos == AV_PICTURE_TYPE_B && !sl->direct_spatial_mv_pred)
+        ff_h264_direct_dist_scale_factor(h, sl);
+    ff_h264_direct_ref_list_init(h, sl);
 
-    if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
-        tmp = get_ue_golomb_31(&h->gb);
+    if (sl->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
+        tmp = get_ue_golomb_31(&sl->gb);
         if (tmp > 2) {
             av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);
             return AVERROR_INVALIDDATA;
         }
-        h->cabac_init_idc = tmp;
+        sl->cabac_init_idc = tmp;
     }
 
-    h->last_qscale_diff = 0;
-    tmp = h->pps.init_qp + get_se_golomb(&h->gb);
+    sl->last_qscale_diff = 0;
+    tmp = h->pps.init_qp + get_se_golomb(&sl->gb);
     if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
         av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
         return AVERROR_INVALIDDATA;
     }
-    h->qscale       = tmp;
-    h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
-    h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
+    sl->qscale       = tmp;
+    sl->chroma_qp[0] = get_chroma_qp(h, 0, sl->qscale);
+    sl->chroma_qp[1] = get_chroma_qp(h, 1, sl->qscale);
     // FIXME qscale / qp ... stuff
-    if (h->slice_type == AV_PICTURE_TYPE_SP)
-        get_bits1(&h->gb); /* sp_for_switch_flag */
-    if (h->slice_type == AV_PICTURE_TYPE_SP ||
-        h->slice_type == AV_PICTURE_TYPE_SI)
-        get_se_golomb(&h->gb); /* slice_qs_delta */
+    if (sl->slice_type == AV_PICTURE_TYPE_SP)
+        get_bits1(&sl->gb); /* sp_for_switch_flag */
+    if (sl->slice_type == AV_PICTURE_TYPE_SP ||
+        sl->slice_type == AV_PICTURE_TYPE_SI)
+        get_se_golomb(&sl->gb); /* slice_qs_delta */
 
-    h->deblocking_filter     = 1;
-    h->slice_alpha_c0_offset = 0;
-    h->slice_beta_offset     = 0;
+    sl->deblocking_filter     = 1;
+    sl->slice_alpha_c0_offset = 0;
+    sl->slice_beta_offset     = 0;
     if (h->pps.deblocking_filter_parameters_present) {
-        tmp = get_ue_golomb_31(&h->gb);
+        tmp = get_ue_golomb_31(&sl->gb);
         if (tmp > 2) {
             av_log(h->avctx, AV_LOG_ERROR,
                    "deblocking_filter_idc %u out of range\n", tmp);
             return AVERROR_INVALIDDATA;
         }
-        h->deblocking_filter = tmp;
-        if (h->deblocking_filter < 2)
-            h->deblocking_filter ^= 1;  // 1<->0
+        sl->deblocking_filter = tmp;
+        if (sl->deblocking_filter < 2)
+            sl->deblocking_filter ^= 1;  // 1<->0
 
-        if (h->deblocking_filter) {
-            h->slice_alpha_c0_offset = get_se_golomb(&h->gb) * 2;
-            h->slice_beta_offset     = get_se_golomb(&h->gb) * 2;
-            if (h->slice_alpha_c0_offset >  12 ||
-                h->slice_alpha_c0_offset < -12 ||
-                h->slice_beta_offset >  12     ||
-                h->slice_beta_offset < -12) {
+        if (sl->deblocking_filter) {
+            sl->slice_alpha_c0_offset = get_se_golomb(&sl->gb) * 2;
+            sl->slice_beta_offset     = get_se_golomb(&sl->gb) * 2;
+            if (sl->slice_alpha_c0_offset >  12 ||
+                sl->slice_alpha_c0_offset < -12 ||
+                sl->slice_beta_offset >  12     ||
+                sl->slice_beta_offset < -12) {
                 av_log(h->avctx, AV_LOG_ERROR,
                        "deblocking filter parameters %d %d out of range\n",
-                       h->slice_alpha_c0_offset, h->slice_beta_offset);
+                       sl->slice_alpha_c0_offset, sl->slice_beta_offset);
                 return AVERROR_INVALIDDATA;
             }
         }
@@ -1895,64 +1811,64 @@
         (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
          h->nal_unit_type != NAL_IDR_SLICE) ||
         (h->avctx->skip_loop_filter >= AVDISCARD_NONINTRA &&
-         h->slice_type_nos != AV_PICTURE_TYPE_I) ||
+         sl->slice_type_nos != AV_PICTURE_TYPE_I) ||
         (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR  &&
-         h->slice_type_nos == AV_PICTURE_TYPE_B) ||
+         sl->slice_type_nos == AV_PICTURE_TYPE_B) ||
         (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
          h->nal_ref_idc == 0))
-        h->deblocking_filter = 0;
+        sl->deblocking_filter = 0;
 
-    if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
+    if (sl->deblocking_filter == 1 && h->max_contexts > 1) {
         if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
             /* Cheat slightly for speed:
              * Do not bother to deblock across slices. */
-            h->deblocking_filter = 2;
+            sl->deblocking_filter = 2;
         } else {
-            h0->max_contexts = 1;
-            if (!h0->single_decode_warning) {
+            h->max_contexts = 1;
+            if (!h->single_decode_warning) {
                 av_log(h->avctx, AV_LOG_INFO,
                        "Cannot parallelize slice decoding with deblocking filter type 1, decoding such frames in sequential order\n"
                        "To parallelize slice decoding you need video encoded with disable_deblocking_filter_idc set to 2 (deblock only edges that do not cross slices).\n"
                        "Setting the flags2 libavcodec option to +fast (-flags2 +fast) will disable deblocking across slices and enable parallel slice decoding "
                        "but will generate non-standard-compliant output.\n");
-                h0->single_decode_warning = 1;
+                h->single_decode_warning = 1;
             }
-            if (h != h0) {
+            if (sl != h->slice_ctx) {
                 av_log(h->avctx, AV_LOG_ERROR,
                        "Deblocking switched inside frame.\n");
                 return SLICE_SINGLETHREAD;
             }
         }
     }
-    h->qp_thresh = 15 -
-                   FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
+    sl->qp_thresh = 15 -
+                   FFMIN(sl->slice_alpha_c0_offset, sl->slice_beta_offset) -
                    FFMAX3(0,
                           h->pps.chroma_qp_index_offset[0],
                           h->pps.chroma_qp_index_offset[1]) +
                    6 * (h->sps.bit_depth_luma - 8);
 
-    h0->last_slice_type = slice_type;
-    memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count));
-    h->slice_num        = ++h0->current_slice;
+    h->last_slice_type = slice_type;
+    memcpy(h->last_ref_count, sl->ref_count, sizeof(h->last_ref_count));
+    sl->slice_num       = ++h->current_slice;
 
-    if (h->slice_num)
-        h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y;
-    if (   h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y
-        && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y
-        && h->slice_num >= MAX_SLICES) {
+    if (sl->slice_num)
+        h->slice_row[(sl->slice_num-1)&(MAX_SLICES-1)]= sl->resync_mb_y;
+    if (   h->slice_row[sl->slice_num&(MAX_SLICES-1)] + 3 >= sl->resync_mb_y
+        && h->slice_row[sl->slice_num&(MAX_SLICES-1)] <= sl->resync_mb_y
+        && sl->slice_num >= MAX_SLICES) {
         //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
-        av_log(h->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", h->slice_num, MAX_SLICES);
+        av_log(h->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", sl->slice_num, MAX_SLICES);
     }
 
     for (j = 0; j < 2; j++) {
         int id_list[16];
-        int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
+        int *ref2frm = sl->ref2frm[sl->slice_num & (MAX_SLICES - 1)][j];
         for (i = 0; i < 16; i++) {
             id_list[i] = 60;
-            if (j < h->list_count && i < h->ref_count[j] &&
-                h->ref_list[j][i].f.buf[0]) {
+            if (j < sl->list_count && i < sl->ref_count[j] &&
+                sl->ref_list[j][i].parent->f.buf[0]) {
                 int k;
-                AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer;
+                AVBuffer *buf = sl->ref_list[j][i].parent->f.buf[0]->buffer;
                 for (k = 0; k < h->short_ref_count; k++)
                     if (h->short_ref[k]->f.buf[0]->buffer == buf) {
                         id_list[i] = k;
@@ -1969,57 +1885,46 @@
         ref2frm[0] =
         ref2frm[1] = -1;
         for (i = 0; i < 16; i++)
-            ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3);
+            ref2frm[i + 2] = 4 * id_list[i] + (sl->ref_list[j][i].reference & 3);
         ref2frm[18 + 0] =
         ref2frm[18 + 1] = -1;
         for (i = 16; i < 48; i++)
             ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
-                             (h->ref_list[j][i].reference & 3);
+                             (sl->ref_list[j][i].reference & 3);
     }
 
-#if CONFIG_ERROR_RESILIENCE
-    if (h->ref_count[0]) {
-        ff_h264_set_erpic(&h->er.last_pic, &h->ref_list[0][0]);
-    } else if (h->last_pic_for_ec.f.buf[0]) {
-        ff_h264_set_erpic(&h->er.last_pic, &h->last_pic_for_ec);
-    }
-
-    if (h->ref_count[1]) ff_h264_set_erpic(&h->er.next_pic, &h->ref_list[1][0]);
-#endif
-
-    h->er.ref_count = h->ref_count[0];
-    h0->au_pps_id = pps_id;
+    h->au_pps_id = pps_id;
     h->sps.new =
-    h0->sps_buffers[h->pps.sps_id]->new = 0;
+    h->sps_buffers[h->pps.sps_id]->new = 0;
     h->current_sps_id = h->pps.sps_id;
 
     if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
         av_log(h->avctx, AV_LOG_DEBUG,
                "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
-               h->slice_num,
+               sl->slice_num,
                (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
                first_mb_in_slice,
-               av_get_picture_type_char(h->slice_type),
-               h->slice_type_fixed ? " fix" : "",
+               av_get_picture_type_char(sl->slice_type),
+               sl->slice_type_fixed ? " fix" : "",
                h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
                pps_id, h->frame_num,
                h->cur_pic_ptr->field_poc[0],
                h->cur_pic_ptr->field_poc[1],
-               h->ref_count[0], h->ref_count[1],
-               h->qscale,
-               h->deblocking_filter,
-               h->slice_alpha_c0_offset, h->slice_beta_offset,
-               h->use_weight,
-               h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
-               h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
+               sl->ref_count[0], sl->ref_count[1],
+               sl->qscale,
+               sl->deblocking_filter,
+               sl->slice_alpha_c0_offset, sl->slice_beta_offset,
+               sl->use_weight,
+               sl->use_weight == 1 && sl->use_weight_chroma ? "c" : "",
+               sl->slice_type == AV_PICTURE_TYPE_B ? (sl->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
     }
 
     return 0;
 }
 
-int ff_h264_get_slice_type(const H264Context *h)
+int ff_h264_get_slice_type(const H264SliceContext *sl)
 {
-    switch (h->slice_type) {
+    switch (sl->slice_type) {
     case AV_PICTURE_TYPE_P:
         return 0;
     case AV_PICTURE_TYPE_B:
@@ -2035,7 +1940,8 @@
     }
 }
 
-static av_always_inline void fill_filter_caches_inter(H264Context *h,
+static av_always_inline void fill_filter_caches_inter(const H264Context *h,
+                                                      H264SliceContext *sl,
                                                       int mb_type, int top_xy,
                                                       int left_xy[LEFT_MBS],
                                                       int top_type,
@@ -2043,13 +1949,13 @@
                                                       int mb_xy, int list)
 {
     int b_stride = h->b_stride;
-    int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
-    int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
+    int16_t(*mv_dst)[2] = &sl->mv_cache[list][scan8[0]];
+    int8_t *ref_cache   = &sl->ref_cache[list][scan8[0]];
     if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
         if (USES_LIST(top_type, list)) {
             const int b_xy  = h->mb2b_xy[top_xy] + 3 * b_stride;
             const int b8_xy = 4 * top_xy + 2;
-            int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
+            int (*ref2frm)[64] = (void*)(sl->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(sl) ? 20 : 2));
             AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
             ref_cache[0 - 1 * 8] =
             ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]];
@@ -2064,7 +1970,7 @@
             if (USES_LIST(left_type[LTOP], list)) {
                 const int b_xy  = h->mb2b_xy[left_xy[LTOP]] + 3;
                 const int b8_xy = 4 * left_xy[LTOP] + 1;
-                int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
+                int (*ref2frm)[64] =(void*)( sl->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(sl) ? 20 : 2));
                 AV_COPY32(mv_dst - 1 +  0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
                 AV_COPY32(mv_dst - 1 +  8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
                 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
@@ -2097,7 +2003,7 @@
 
     {
         int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
-        int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
+        int (*ref2frm)[64] = (void*)(sl->ref2frm[sl->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(sl) ? 20 : 2));
         uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
         uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
         AV_WN32A(&ref_cache[0 * 8], ref01);
@@ -2107,7 +2013,7 @@
     }
 
     {
-        int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
+        int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * sl->mb_x + 4 * sl->mb_y * b_stride];
         AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
         AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
         AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
@@ -2119,15 +2025,15 @@
  *
  * @return non zero if the loop filter can be skipped
  */
-static int fill_filter_caches(H264Context *h, int mb_type)
+static int fill_filter_caches(const H264Context *h, H264SliceContext *sl, int mb_type)
 {
-    const int mb_xy = h->mb_xy;
+    const int mb_xy = sl->mb_xy;
     int top_xy, left_xy[LEFT_MBS];
     int top_type, left_type[LEFT_MBS];
     uint8_t *nnz;
     uint8_t *nnz_cache;
 
-    top_xy = mb_xy - (h->mb_stride << MB_FIELD(h));
+    top_xy = mb_xy - (h->mb_stride << MB_FIELD(sl));
 
     /* Wow, what a mess, why didn't they simplify the interlacing & intra
      * stuff, I can't imagine that these complex rules are worth it. */
@@ -2136,7 +2042,7 @@
     if (FRAME_MBAFF(h)) {
         const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
         const int curr_mb_field_flag = IS_INTERLACED(mb_type);
-        if (h->mb_y & 1) {
+        if (sl->mb_y & 1) {
             if (left_mb_field_flag != curr_mb_field_flag)
                 left_xy[LTOP] -= h->mb_stride;
         } else {
@@ -2148,14 +2054,14 @@
         }
     }
 
-    h->top_mb_xy        = top_xy;
-    h->left_mb_xy[LTOP] = left_xy[LTOP];
-    h->left_mb_xy[LBOT] = left_xy[LBOT];
+    sl->top_mb_xy        = top_xy;
+    sl->left_mb_xy[LTOP] = left_xy[LTOP];
+    sl->left_mb_xy[LBOT] = left_xy[LBOT];
     {
         /* For sufficiently low qp, filtering wouldn't do anything.
          * This is a conservative estimate: could also check beta_offset
          * and more accurate chroma_qp. */
-        int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
+        int qp_thresh = sl->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
         int qp        = h->cur_pic.qscale_table[mb_xy];
         if (qp <= qp_thresh &&
             (left_xy[LTOP] < 0 ||
@@ -2175,10 +2081,10 @@
     top_type        = h->cur_pic.mb_type[top_xy];
     left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
     left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
-    if (h->deblocking_filter == 2) {
-        if (h->slice_table[top_xy] != h->slice_num)
+    if (sl->deblocking_filter == 2) {
+        if (h->slice_table[top_xy] != sl->slice_num)
             top_type = 0;
-        if (h->slice_table[left_xy[LBOT]] != h->slice_num)
+        if (h->slice_table[left_xy[LBOT]] != sl->slice_num)
             left_type[LTOP] = left_type[LBOT] = 0;
     } else {
         if (h->slice_table[top_xy] == 0xFFFF)
@@ -2186,26 +2092,26 @@
         if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
             left_type[LTOP] = left_type[LBOT] = 0;
     }
-    h->top_type        = top_type;
-    h->left_type[LTOP] = left_type[LTOP];
-    h->left_type[LBOT] = left_type[LBOT];
+    sl->top_type        = top_type;
+    sl->left_type[LTOP] = left_type[LTOP];
+    sl->left_type[LBOT] = left_type[LBOT];
 
     if (IS_INTRA(mb_type))
         return 0;
 
-    fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
+    fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
                              top_type, left_type, mb_xy, 0);
-    if (h->list_count == 2)
-        fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
+    if (sl->list_count == 2)
+        fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
                                  top_type, left_type, mb_xy, 1);
 
     nnz       = h->non_zero_count[mb_xy];
-    nnz_cache = h->non_zero_count_cache;
+    nnz_cache = sl->non_zero_count_cache;
     AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
     AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
     AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
     AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
-    h->cbp = h->cbp_table[mb_xy];
+    sl->cbp = h->cbp_table[mb_xy];
 
     if (top_type) {
         nnz = h->non_zero_count[top_xy];
@@ -2242,118 +2148,118 @@
             nnz_cache[scan8[0]] =
             nnz_cache[scan8[1]] =
             nnz_cache[scan8[2]] =
-            nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
+            nnz_cache[scan8[3]] = (sl->cbp & 0x1000) >> 12;
 
             nnz_cache[scan8[0 + 4]] =
             nnz_cache[scan8[1 + 4]] =
             nnz_cache[scan8[2 + 4]] =
-            nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
+            nnz_cache[scan8[3 + 4]] = (sl->cbp & 0x2000) >> 12;
 
             nnz_cache[scan8[0 + 8]] =
             nnz_cache[scan8[1 + 8]] =
             nnz_cache[scan8[2 + 8]] =
-            nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
+            nnz_cache[scan8[3 + 8]] = (sl->cbp & 0x4000) >> 12;
 
             nnz_cache[scan8[0 + 12]] =
             nnz_cache[scan8[1 + 12]] =
             nnz_cache[scan8[2 + 12]] =
-            nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
+            nnz_cache[scan8[3 + 12]] = (sl->cbp & 0x8000) >> 12;
         }
     }
 
     return 0;
 }
 
-static void loop_filter(H264Context *h, int start_x, int end_x)
+static void loop_filter(const H264Context *h, H264SliceContext *sl, int start_x, int end_x)
 {
     uint8_t *dest_y, *dest_cb, *dest_cr;
     int linesize, uvlinesize, mb_x, mb_y;
-    const int end_mb_y       = h->mb_y + FRAME_MBAFF(h);
-    const int old_slice_type = h->slice_type;
+    const int end_mb_y       = sl->mb_y + FRAME_MBAFF(h);
+    const int old_slice_type = sl->slice_type;
     const int pixel_shift    = h->pixel_shift;
     const int block_h        = 16 >> h->chroma_y_shift;
 
-    if (h->deblocking_filter) {
+    if (sl->deblocking_filter) {
         for (mb_x = start_x; mb_x < end_x; mb_x++)
             for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
                 int mb_xy, mb_type;
-                mb_xy         = h->mb_xy = mb_x + mb_y * h->mb_stride;
-                h->slice_num  = h->slice_table[mb_xy];
+                mb_xy         = sl->mb_xy = mb_x + mb_y * h->mb_stride;
+                sl->slice_num = h->slice_table[mb_xy];
                 mb_type       = h->cur_pic.mb_type[mb_xy];
-                h->list_count = h->list_counts[mb_xy];
+                sl->list_count = h->list_counts[mb_xy];
 
                 if (FRAME_MBAFF(h))
-                    h->mb_mbaff               =
-                    h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
+                    sl->mb_mbaff               =
+                    sl->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
 
-                h->mb_x = mb_x;
-                h->mb_y = mb_y;
+                sl->mb_x = mb_x;
+                sl->mb_y = mb_y;
                 dest_y  = h->cur_pic.f.data[0] +
-                          ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
+                          ((mb_x << pixel_shift) + mb_y * sl->linesize) * 16;
                 dest_cb = h->cur_pic.f.data[1] +
                           (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
-                          mb_y * h->uvlinesize * block_h;
+                          mb_y * sl->uvlinesize * block_h;
                 dest_cr = h->cur_pic.f.data[2] +
                           (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
-                          mb_y * h->uvlinesize * block_h;
+                          mb_y * sl->uvlinesize * block_h;
                 // FIXME simplify above
 
-                if (MB_FIELD(h)) {
-                    linesize   = h->mb_linesize   = h->linesize   * 2;
-                    uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
+                if (MB_FIELD(sl)) {
+                    linesize   = sl->mb_linesize   = sl->linesize   * 2;
+                    uvlinesize = sl->mb_uvlinesize = sl->uvlinesize * 2;
                     if (mb_y & 1) { // FIXME move out of this function?
-                        dest_y  -= h->linesize   * 15;
-                        dest_cb -= h->uvlinesize * (block_h - 1);
-                        dest_cr -= h->uvlinesize * (block_h - 1);
+                        dest_y  -= sl->linesize   * 15;
+                        dest_cb -= sl->uvlinesize * (block_h - 1);
+                        dest_cr -= sl->uvlinesize * (block_h - 1);
                     }
                 } else {
-                    linesize   = h->mb_linesize   = h->linesize;
-                    uvlinesize = h->mb_uvlinesize = h->uvlinesize;
+                    linesize   = sl->mb_linesize   = sl->linesize;
+                    uvlinesize = sl->mb_uvlinesize = sl->uvlinesize;
                 }
-                backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
+                backup_mb_border(h, sl, dest_y, dest_cb, dest_cr, linesize,
                                  uvlinesize, 0);
-                if (fill_filter_caches(h, mb_type))
+                if (fill_filter_caches(h, sl, mb_type))
                     continue;
-                h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.qscale_table[mb_xy]);
-                h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.qscale_table[mb_xy]);
+                sl->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.qscale_table[mb_xy]);
+                sl->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.qscale_table[mb_xy]);
 
                 if (FRAME_MBAFF(h)) {
-                    ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
+                    ff_h264_filter_mb(h, sl, mb_x, mb_y, dest_y, dest_cb, dest_cr,
                                       linesize, uvlinesize);
                 } else {
-                    ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
+                    ff_h264_filter_mb_fast(h, sl, mb_x, mb_y, dest_y, dest_cb,
                                            dest_cr, linesize, uvlinesize);
                 }
             }
     }
-    h->slice_type   = old_slice_type;
-    h->mb_x         = end_x;
-    h->mb_y         = end_mb_y - FRAME_MBAFF(h);
-    h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
-    h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
+    sl->slice_type  = old_slice_type;
+    sl->mb_x         = end_x;
+    sl->mb_y         = end_mb_y - FRAME_MBAFF(h);
+    sl->chroma_qp[0] = get_chroma_qp(h, 0, sl->qscale);
+    sl->chroma_qp[1] = get_chroma_qp(h, 1, sl->qscale);
 }
 
-static void predict_field_decoding_flag(H264Context *h)
+static void predict_field_decoding_flag(const H264Context *h, H264SliceContext *sl)
 {
-    const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
-    int mb_type     = (h->slice_table[mb_xy - 1] == h->slice_num) ?
+    const int mb_xy = sl->mb_x + sl->mb_y * h->mb_stride;
+    int mb_type     = (h->slice_table[mb_xy - 1] == sl->slice_num) ?
                       h->cur_pic.mb_type[mb_xy - 1] :
-                      (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
+                      (h->slice_table[mb_xy - h->mb_stride] == sl->slice_num) ?
                       h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
-    h->mb_mbaff     = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
+    sl->mb_mbaff    = sl->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
 }
 
 /**
  * Draw edges and report progress for the last MB row.
  */
-static void decode_finish_row(H264Context *h)
+static void decode_finish_row(const H264Context *h, H264SliceContext *sl)
 {
-    int top            = 16 * (h->mb_y      >> FIELD_PICTURE(h));
+    int top            = 16 * (sl->mb_y      >> FIELD_PICTURE(h));
     int pic_height     = 16 *  h->mb_height >> FIELD_PICTURE(h);
     int height         =  16      << FRAME_MBAFF(h);
     int deblock_border = (16 + 4) << FRAME_MBAFF(h);
 
-    if (h->deblocking_filter) {
+    if (sl->deblocking_filter) {
         if ((top + height) >= pic_height)
             height += deblock_border;
         top -= deblock_border;
@@ -2368,20 +2274,21 @@
         top    = 0;
     }
 
-    ff_h264_draw_horiz_band(h, top, height);
+    ff_h264_draw_horiz_band(h, sl, top, height);
 
-    if (h->droppable || h->er.error_occurred)
+    if (h->droppable || sl->er.error_occurred)
         return;
 
     ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
                               h->picture_structure == PICT_BOTTOM_FIELD);
 }
 
-static void er_add_slice(H264Context *h, int startx, int starty,
+static void er_add_slice(H264SliceContext *sl,
+                         int startx, int starty,
                          int endx, int endy, int status)
 {
     if (CONFIG_ERROR_RESILIENCE) {
-        ERContext *er = &h->er;
+        ERContext *er = &sl->er;
 
         ff_er_add_slice(er, startx, starty, endx, endy, status);
     }
@@ -2389,169 +2296,178 @@
 
 static int decode_slice(struct AVCodecContext *avctx, void *arg)
 {
-    H264Context *h = *(void **)arg;
-    int lf_x_start = h->mb_x;
+    H264SliceContext *sl = arg;
+    const H264Context *h = sl->h264;
+    int lf_x_start = sl->mb_x;
+    int ret;
 
-    h->mb_skip_run = -1;
+    sl->linesize   = h->cur_pic_ptr->f.linesize[0];
+    sl->uvlinesize = h->cur_pic_ptr->f.linesize[1];
 
-    av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * h->linesize * ((scan8[15] - scan8[0]) >> 3));
+    ret = alloc_scratch_buffers(sl, sl->linesize);
+    if (ret < 0)
+        return ret;
 
-    h->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
-                    avctx->codec_id != AV_CODEC_ID_H264 ||
-                    (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
+    sl->mb_skip_run = -1;
 
-    if (!(h->avctx->active_thread_type & FF_THREAD_SLICE) && h->picture_structure == PICT_FRAME && h->er.error_status_table) {
-        const int start_i  = av_clip(h->resync_mb_x + h->resync_mb_y * h->mb_width, 0, h->mb_num - 1);
+    av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * sl->linesize * ((scan8[15] - scan8[0]) >> 3));
+
+    sl->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
+                     avctx->codec_id != AV_CODEC_ID_H264 ||
+                     (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
+
+    if (!(h->avctx->active_thread_type & FF_THREAD_SLICE) && h->picture_structure == PICT_FRAME && sl->er.error_status_table) {
+        const int start_i  = av_clip(sl->resync_mb_x + sl->resync_mb_y * h->mb_width, 0, h->mb_num - 1);
         if (start_i) {
-            int prev_status = h->er.error_status_table[h->er.mb_index2xy[start_i - 1]];
+            int prev_status = sl->er.error_status_table[sl->er.mb_index2xy[start_i - 1]];
             prev_status &= ~ VP_START;
             if (prev_status != (ER_MV_END | ER_DC_END | ER_AC_END))
-                h->er.error_occurred = 1;
+                sl->er.error_occurred = 1;
         }
     }
 
     if (h->pps.cabac) {
         /* realign */
-        align_get_bits(&h->gb);
+        align_get_bits(&sl->gb);
 
         /* init cabac */
-        ff_init_cabac_decoder(&h->cabac,
-                              h->gb.buffer + get_bits_count(&h->gb) / 8,
-                              (get_bits_left(&h->gb) + 7) / 8);
+        ff_init_cabac_decoder(&sl->cabac,
+                              sl->gb.buffer + get_bits_count(&sl->gb) / 8,
+                              (get_bits_left(&sl->gb) + 7) / 8);
 
-        ff_h264_init_cabac_states(h);
+        ff_h264_init_cabac_states(h, sl);
 
         for (;;) {
             // START_TIMER
-            int ret = ff_h264_decode_mb_cabac(h);
+            int ret = ff_h264_decode_mb_cabac(h, sl);
             int eos;
             // STOP_TIMER("decode_mb_cabac")
 
             if (ret >= 0)
-                ff_h264_hl_decode_mb(h);
+                ff_h264_hl_decode_mb(h, sl);
 
             // FIXME optimal? or let mb_decode decode 16x32 ?
             if (ret >= 0 && FRAME_MBAFF(h)) {
-                h->mb_y++;
+                sl->mb_y++;
 
-                ret = ff_h264_decode_mb_cabac(h);
+                ret = ff_h264_decode_mb_cabac(h, sl);
 
                 if (ret >= 0)
-                    ff_h264_hl_decode_mb(h);
-                h->mb_y--;
+                    ff_h264_hl_decode_mb(h, sl);
+                sl->mb_y--;
             }
-            eos = get_cabac_terminate(&h->cabac);
+            eos = get_cabac_terminate(&sl->cabac);
 
             if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
-                h->cabac.bytestream > h->cabac.bytestream_end + 2) {
-                er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
-                             h->mb_y, ER_MB_END);
-                if (h->mb_x >= lf_x_start)
-                    loop_filter(h, lf_x_start, h->mb_x + 1);
+                sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
+                er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
+                             sl->mb_y, ER_MB_END);
+                if (sl->mb_x >= lf_x_start)
+                    loop_filter(h, sl, lf_x_start, sl->mb_x + 1);
                 return 0;
             }
-            if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
-                av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %"PTRDIFF_SPECIFIER"\n", h->cabac.bytestream_end - h->cabac.bytestream);
-            if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
+            if (sl->cabac.bytestream > sl->cabac.bytestream_end + 2 )
+                av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %"PTRDIFF_SPECIFIER"\n", sl->cabac.bytestream_end - sl->cabac.bytestream);
+            if (ret < 0 || sl->cabac.bytestream > sl->cabac.bytestream_end + 4) {
                 av_log(h->avctx, AV_LOG_ERROR,
                        "error while decoding MB %d %d, bytestream %"PTRDIFF_SPECIFIER"\n",
-                       h->mb_x, h->mb_y,
-                       h->cabac.bytestream_end - h->cabac.bytestream);
-                er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
-                             h->mb_y, ER_MB_ERROR);
+                       sl->mb_x, sl->mb_y,
+                       sl->cabac.bytestream_end - sl->cabac.bytestream);
+                er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
+                             sl->mb_y, ER_MB_ERROR);
                 return AVERROR_INVALIDDATA;
             }
 
-            if (++h->mb_x >= h->mb_width) {
-                loop_filter(h, lf_x_start, h->mb_x);
-                h->mb_x = lf_x_start = 0;
-                decode_finish_row(h);
-                ++h->mb_y;
+            if (++sl->mb_x >= h->mb_width) {
+                loop_filter(h, sl, lf_x_start, sl->mb_x);
+                sl->mb_x = lf_x_start = 0;
+                decode_finish_row(h, sl);
+                ++sl->mb_y;
                 if (FIELD_OR_MBAFF_PICTURE(h)) {
-                    ++h->mb_y;
-                    if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
-                        predict_field_decoding_flag(h);
+                    ++sl->mb_y;
+                    if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
+                        predict_field_decoding_flag(h, sl);
                 }
             }
 
-            if (eos || h->mb_y >= h->mb_height) {
+            if (eos || sl->mb_y >= h->mb_height) {
                 tprintf(h->avctx, "slice end %d %d\n",
-                        get_bits_count(&h->gb), h->gb.size_in_bits);
-                er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
-                             h->mb_y, ER_MB_END);
-                if (h->mb_x > lf_x_start)
-                    loop_filter(h, lf_x_start, h->mb_x);
+                        get_bits_count(&sl->gb), sl->gb.size_in_bits);
+                er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
+                             sl->mb_y, ER_MB_END);
+                if (sl->mb_x > lf_x_start)
+                    loop_filter(h, sl, lf_x_start, sl->mb_x);
                 return 0;
             }
         }
     } else {
         for (;;) {
-            int ret = ff_h264_decode_mb_cavlc(h);
+            int ret = ff_h264_decode_mb_cavlc(h, sl);
 
             if (ret >= 0)
-                ff_h264_hl_decode_mb(h);
+                ff_h264_hl_decode_mb(h, sl);
 
             // FIXME optimal? or let mb_decode decode 16x32 ?
             if (ret >= 0 && FRAME_MBAFF(h)) {
-                h->mb_y++;
-                ret = ff_h264_decode_mb_cavlc(h);
+                sl->mb_y++;
+                ret = ff_h264_decode_mb_cavlc(h, sl);
 
                 if (ret >= 0)
-                    ff_h264_hl_decode_mb(h);
-                h->mb_y--;
+                    ff_h264_hl_decode_mb(h, sl);
+                sl->mb_y--;
             }
 
             if (ret < 0) {
                 av_log(h->avctx, AV_LOG_ERROR,
-                       "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
-                er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
-                             h->mb_y, ER_MB_ERROR);
+                       "error while decoding MB %d %d\n", sl->mb_x, sl->mb_y);
+                er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
+                             sl->mb_y, ER_MB_ERROR);
                 return ret;
             }
 
-            if (++h->mb_x >= h->mb_width) {
-                loop_filter(h, lf_x_start, h->mb_x);
-                h->mb_x = lf_x_start = 0;
-                decode_finish_row(h);
-                ++h->mb_y;
+            if (++sl->mb_x >= h->mb_width) {
+                loop_filter(h, sl, lf_x_start, sl->mb_x);
+                sl->mb_x = lf_x_start = 0;
+                decode_finish_row(h, sl);
+                ++sl->mb_y;
                 if (FIELD_OR_MBAFF_PICTURE(h)) {
-                    ++h->mb_y;
-                    if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
-                        predict_field_decoding_flag(h);
+                    ++sl->mb_y;
+                    if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
+                        predict_field_decoding_flag(h, sl);
                 }
-                if (h->mb_y >= h->mb_height) {
+                if (sl->mb_y >= h->mb_height) {
                     tprintf(h->avctx, "slice end %d %d\n",
-                            get_bits_count(&h->gb), h->gb.size_in_bits);
+                            get_bits_count(&sl->gb), sl->gb.size_in_bits);
 
-                    if (   get_bits_left(&h->gb) == 0
-                        || get_bits_left(&h->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
-                        er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
-                                     h->mb_x - 1, h->mb_y, ER_MB_END);
+                    if (   get_bits_left(&sl->gb) == 0
+                        || get_bits_left(&sl->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
+                        er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
+                                     sl->mb_x - 1, sl->mb_y, ER_MB_END);
 
                         return 0;
                     } else {
-                        er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
-                                     h->mb_x, h->mb_y, ER_MB_END);
+                        er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
+                                     sl->mb_x, sl->mb_y, ER_MB_END);
 
                         return AVERROR_INVALIDDATA;
                     }
                 }
             }
 
-            if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
+            if (get_bits_left(&sl->gb) <= 0 && sl->mb_skip_run <= 0) {
                 tprintf(h->avctx, "slice end %d %d\n",
-                        get_bits_count(&h->gb), h->gb.size_in_bits);
+                        get_bits_count(&sl->gb), sl->gb.size_in_bits);
 
-                if (get_bits_left(&h->gb) == 0) {
-                    er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
-                                 h->mb_x - 1, h->mb_y, ER_MB_END);
-                    if (h->mb_x > lf_x_start)
-                        loop_filter(h, lf_x_start, h->mb_x);
+                if (get_bits_left(&sl->gb) == 0) {
+                    er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
+                                 sl->mb_x - 1, sl->mb_y, ER_MB_END);
+                    if (sl->mb_x > lf_x_start)
+                        loop_filter(h, sl, lf_x_start, sl->mb_x);
 
                     return 0;
                 } else {
-                    er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
-                                 h->mb_y, ER_MB_ERROR);
+                    er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
+                                 sl->mb_y, ER_MB_ERROR);
 
                     return AVERROR_INVALIDDATA;
                 }
@@ -2569,38 +2485,36 @@
 int ff_h264_execute_decode_slices(H264Context *h, unsigned context_count)
 {
     AVCodecContext *const avctx = h->avctx;
-    H264Context *hx;
+    H264SliceContext *sl;
     int i;
 
-    av_assert0(h->mb_y < h->mb_height);
+    av_assert0(context_count && h->slice_ctx[context_count - 1].mb_y < h->mb_height);
 
     if (h->avctx->hwaccel ||
         h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
         return 0;
     if (context_count == 1) {
-        return decode_slice(avctx, &h);
+        int ret = decode_slice(avctx, &h->slice_ctx[0]);
+        h->mb_y = h->slice_ctx[0].mb_y;
+        return ret;
     } else {
         av_assert0(context_count > 0);
         for (i = 1; i < context_count; i++) {
-            hx                 = h->thread_context[i];
+            sl                 = &h->slice_ctx[i];
             if (CONFIG_ERROR_RESILIENCE) {
-                hx->er.error_count = 0;
+                sl->er.error_count = 0;
             }
-            hx->x264_build     = h->x264_build;
         }
 
-        avctx->execute(avctx, decode_slice, h->thread_context,
-                       NULL, context_count, sizeof(void *));
+        avctx->execute(avctx, decode_slice, h->slice_ctx,
+                       NULL, context_count, sizeof(h->slice_ctx[0]));
 
         /* pull back stuff from slices to master context */
-        hx                   = h->thread_context[context_count - 1];
-        h->mb_x              = hx->mb_x;
-        h->mb_y              = hx->mb_y;
-        h->droppable         = hx->droppable;
-        h->picture_structure = hx->picture_structure;
+        sl                   = &h->slice_ctx[context_count - 1];
+        h->mb_y              = sl->mb_y;
         if (CONFIG_ERROR_RESILIENCE) {
             for (i = 1; i < context_count; i++)
-                h->er.error_count += h->thread_context[i]->er.error_count;
+                h->slice_ctx[0].er.error_count += h->slice_ctx[i].er.error_count;
         }
     }
 
diff --git a/libavcodec/h264dsp_template.c b/libavcodec/h264dsp_template.c
index 4d5faf0..fa11019 100644
--- a/libavcodec/h264dsp_template.c
+++ b/libavcodec/h264dsp_template.c
@@ -36,7 +36,7 @@
     int y; \
     pixel *block = (pixel*)_block; \
     stride >>= sizeof(pixel)-1; \
-    offset <<= (log2_denom + (BIT_DEPTH-8)); \
+    offset = (unsigned)offset << (log2_denom + (BIT_DEPTH-8)); \
     if(log2_denom) offset += 1<<(log2_denom-1); \
     for (y = 0; y < height; y++, block += stride) { \
         op_scale1(0); \
@@ -67,8 +67,8 @@
     pixel *dst = (pixel*)_dst; \
     pixel *src = (pixel*)_src; \
     stride >>= sizeof(pixel)-1; \
-    offset <<= (BIT_DEPTH-8); \
-    offset = ((offset + 1) | 1) << log2_denom; \
+    offset = (unsigned)offset << (BIT_DEPTH-8); \
+    offset = (unsigned)((offset + 1) | 1) << log2_denom; \
     for (y = 0; y < height; y++, dst += stride, src += stride) { \
         op_scale2(0); \
         op_scale2(1); \
@@ -237,7 +237,7 @@
     xstride >>= sizeof(pixel)-1;
     ystride >>= sizeof(pixel)-1;
     for( i = 0; i < 4; i++ ) {
-        const int tc = ((tc0[i] - 1) << (BIT_DEPTH - 8)) + 1;
+        const int tc = ((tc0[i] - 1U) << (BIT_DEPTH - 8)) + 1;
         if( tc <= 0 ) {
             pix += inner_iters*ystride;
             continue;
@@ -252,7 +252,7 @@
                 FFABS( p1 - p0 ) < beta &&
                 FFABS( q1 - q0 ) < beta ) {
 
-                int delta = av_clip( (((q0 - p0 ) << 2) + (p1 - q1) + 4) >> 3, -tc, tc );
+                int delta = av_clip( ((q0 - p0) * 4 + (p1 - q1) + 4) >> 3, -tc, tc );
 
                 pix[-xstride] = av_clip_pixel( p0 + delta );    /* p0' */
                 pix[0]        = av_clip_pixel( q0 - delta );    /* q0' */
diff --git a/libavcodec/hevc.c b/libavcodec/hevc.c
index 641f4c1..f0d57ae 100644
--- a/libavcodec/hevc.c
+++ b/libavcodec/hevc.c
@@ -97,14 +97,14 @@
     if (!s->sao || !s->deblock)
         goto fail;
 
-    s->skip_flag    = av_malloc(sps->min_cb_height * sps->min_cb_width);
+    s->skip_flag    = av_malloc_array(sps->min_cb_height, sps->min_cb_width);
     s->tab_ct_depth = av_malloc_array(sps->min_cb_height, sps->min_cb_width);
     if (!s->skip_flag || !s->tab_ct_depth)
         goto fail;
 
     s->cbf_luma = av_malloc_array(sps->min_tb_width, sps->min_tb_height);
     s->tab_ipm  = av_mallocz(min_pu_size);
-    s->is_pcm   = av_malloc((sps->min_pu_width + 1) * (sps->min_pu_height + 1));
+    s->is_pcm   = av_malloc_array(sps->min_pu_width + 1, sps->min_pu_height + 1);
     if (!s->tab_ipm || !s->cbf_luma || !s->is_pcm)
         goto fail;
 
@@ -148,10 +148,10 @@
     luma_log2_weight_denom = get_ue_golomb_long(gb);
     if (luma_log2_weight_denom < 0 || luma_log2_weight_denom > 7)
         av_log(s->avctx, AV_LOG_ERROR, "luma_log2_weight_denom %d is invalid\n", luma_log2_weight_denom);
-    s->sh.luma_log2_weight_denom = av_clip_c(luma_log2_weight_denom, 0, 7);
+    s->sh.luma_log2_weight_denom = av_clip_uintp2(luma_log2_weight_denom, 3);
     if (s->sps->chroma_format_idc != 0) {
         int delta = get_se_golomb(gb);
-        s->sh.chroma_log2_weight_denom = av_clip(s->sh.luma_log2_weight_denom + delta, 0, 7);
+        s->sh.chroma_log2_weight_denom = av_clip_uintp2(s->sh.luma_log2_weight_denom + delta, 3);
     }
 
     for (i = 0; i < s->sh.nb_refs[L0]; i++) {
@@ -280,29 +280,11 @@
     return 0;
 }
 
-static int get_buffer_sao(HEVCContext *s, AVFrame *frame, const HEVCSPS *sps)
-{
-    int ret, i;
-
-    frame->width  = s->avctx->coded_width  + 2;
-    frame->height = s->avctx->coded_height + 2;
-    if ((ret = ff_get_buffer(s->avctx, frame, AV_GET_BUFFER_FLAG_REF)) < 0)
-        return ret;
-    for (i = 0; frame->data[i]; i++) {
-        int offset = frame->linesize[i] + (1 << sps->pixel_shift);
-        frame->data[i] += offset;
-    }
-    frame->width  = s->avctx->coded_width;
-    frame->height = s->avctx->coded_height;
-
-    return 0;
-}
-
-static int set_sps(HEVCContext *s, const HEVCSPS *sps)
+static int set_sps(HEVCContext *s, const HEVCSPS *sps, enum AVPixelFormat pix_fmt)
 {
     #define HWACCEL_MAX (CONFIG_HEVC_DXVA2_HWACCEL)
     enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmt = pix_fmts;
-    int ret;
+    int ret, i;
     unsigned int num = 0, den = 0;
 
     pic_arrays_free(s);
@@ -322,13 +304,18 @@
 #endif
     }
 
-    *fmt++ = sps->pix_fmt;
-    *fmt = AV_PIX_FMT_NONE;
+    if (pix_fmt == AV_PIX_FMT_NONE) {
+        *fmt++ = sps->pix_fmt;
+        *fmt = AV_PIX_FMT_NONE;
 
-    ret = ff_thread_get_format(s->avctx, pix_fmts);
-    if (ret < 0)
-        goto fail;
-    s->avctx->pix_fmt = ret;
+        ret = ff_thread_get_format(s->avctx, pix_fmts);
+        if (ret < 0)
+            goto fail;
+        s->avctx->pix_fmt = ret;
+    }
+    else {
+        s->avctx->pix_fmt = pix_fmt;
+    }
 
     ff_set_sar(s->avctx, sps->vui.sar);
 
@@ -352,10 +339,25 @@
     ff_hevc_dsp_init (&s->hevcdsp, sps->bit_depth);
     ff_videodsp_init (&s->vdsp,    sps->bit_depth);
 
+    for (i = 0; i < 3; i++) {
+        av_freep(&s->sao_pixel_buffer_h[i]);
+        av_freep(&s->sao_pixel_buffer_v[i]);
+    }
+
     if (sps->sao_enabled && !s->avctx->hwaccel) {
-        av_frame_unref(s->tmp_frame);
-        ret = get_buffer_sao(s, s->tmp_frame, sps);
-        s->sao_frame = s->tmp_frame;
+        int c_count = (sps->chroma_format_idc != 0) ? 3 : 1;
+        int c_idx;
+
+        for(c_idx = 0; c_idx < c_count; c_idx++) {
+            int w = sps->width >> sps->hshift[c_idx];
+            int h = sps->height >> sps->vshift[c_idx];
+            s->sao_pixel_buffer_h[c_idx] =
+                av_malloc((w * 2 * sps->ctb_height) <<
+                          sps->pixel_shift);
+            s->sao_pixel_buffer_v[c_idx] =
+                av_malloc((h * 2 * sps->ctb_width) <<
+                          sps->pixel_shift);
+        }
     }
 
     s->sps = sps;
@@ -423,7 +425,7 @@
                 sh->no_output_of_prior_pics_flag = 0;
         }
         ff_hevc_clear_refs(s);
-        ret = set_sps(s, s->sps);
+        ret = set_sps(s, s->sps, AV_PIX_FMT_NONE);
         if (ret < 0)
             return ret;
 
@@ -553,8 +555,10 @@
 
         if (s->sps->sao_enabled) {
             sh->slice_sample_adaptive_offset_flag[0] = get_bits1(gb);
-            sh->slice_sample_adaptive_offset_flag[1] =
-            sh->slice_sample_adaptive_offset_flag[2] = get_bits1(gb);
+            if (s->sps->chroma_format_idc) {
+                sh->slice_sample_adaptive_offset_flag[1] =
+                sh->slice_sample_adaptive_offset_flag[2] = get_bits1(gb);
+            }
         } else {
             sh->slice_sample_adaptive_offset_flag[0] = 0;
             sh->slice_sample_adaptive_offset_flag[1] = 0;
@@ -813,7 +817,7 @@
         }
     }
 
-    for (c_idx = 0; c_idx < 3; c_idx++) {
+    for (c_idx = 0; c_idx < (s->sps->chroma_format_idc ? 3 : 1); c_idx++) {
         int log2_sao_offset_scale = c_idx == 0 ? s->pps->log2_sao_offset_scale_luma :
                                                  s->pps->log2_sao_offset_scale_chroma;
 
@@ -859,7 +863,7 @@
             } else if (sao->offset_sign[c_idx][i]) {
                 sao->offset_val[c_idx][i + 1] = -sao->offset_val[c_idx][i + 1];
             }
-            sao->offset_val[c_idx][i + 1] <<= log2_sao_offset_scale;
+            sao->offset_val[c_idx][i + 1] *= 1 << log2_sao_offset_scale;
         }
     }
 }
@@ -969,7 +973,7 @@
 
         if (cbf_luma)
             ff_hevc_hls_residual_coding(s, x0, y0, log2_trafo_size, scan_idx, 0);
-        if (log2_trafo_size > 2 || s->sps->chroma_format_idc == 3) {
+        if (s->sps->chroma_format_idc && (log2_trafo_size > 2 || s->sps->chroma_format_idc == 3)) {
             int trafo_size_h = 1 << (log2_trafo_size_c + s->sps->hshift[1]);
             int trafo_size_v = 1 << (log2_trafo_size_c + s->sps->vshift[1]);
             lc->tu.cross_pf  = (s->pps->cross_component_prediction_enabled_flag && cbf_luma &&
@@ -1033,7 +1037,7 @@
                         s->hevcdsp.transform_add[log2_trafo_size_c-2](dst, coeffs, stride);
                     }
             }
-        } else if (blk_idx == 3) {
+        } else if (s->sps->chroma_format_idc && blk_idx == 3) {
             int trafo_size_h = 1 << (log2_trafo_size + 1);
             int trafo_size_v = 1 << (log2_trafo_size + s->sps->vshift[1]);
             for (i = 0; i < (s->sps->chroma_format_idc == 2 ? 2 : 1); i++) {
@@ -1057,7 +1061,7 @@
                                                 log2_trafo_size, scan_idx_c, 2);
             }
         }
-    } else if (lc->cu.pred_mode == MODE_INTRA) {
+    } else if (s->sps->chroma_format_idc && lc->cu.pred_mode == MODE_INTRA) {
         if (log2_trafo_size > 2 || s->sps->chroma_format_idc == 3) {
             int trafo_size_h = 1 << (log2_trafo_size_c + s->sps->hshift[1]);
             int trafo_size_v = 1 << (log2_trafo_size_c + s->sps->vshift[1]);
@@ -1154,7 +1158,7 @@
                                inter_split;
     }
 
-    if (log2_trafo_size > 2 || s->sps->chroma_format_idc == 3) {
+    if (s->sps->chroma_format_idc && (log2_trafo_size > 2 || s->sps->chroma_format_idc == 3)) {
         if (trafo_depth == 0 || cbf_cb[0]) {
             cbf_cb[0] = ff_hevc_cbf_cb_cr_decode(s, trafo_depth);
             if (s->sps->chroma_format_idc == 2 && (!split_transform_flag || log2_trafo_size == 3)) {
@@ -1254,14 +1258,17 @@
         return ret;
 
     s->hevcdsp.put_pcm(dst0, stride0, cb_size, cb_size,     &gb, s->sps->pcm.bit_depth);
-    s->hevcdsp.put_pcm(dst1, stride1,
-                       cb_size >> s->sps->hshift[1],
-                       cb_size >> s->sps->vshift[1],
-                       &gb, s->sps->pcm.bit_depth_chroma);
-    s->hevcdsp.put_pcm(dst2, stride2,
-                       cb_size >> s->sps->hshift[2],
-                       cb_size >> s->sps->vshift[2],
-                       &gb, s->sps->pcm.bit_depth_chroma);
+    if (s->sps->chroma_format_idc) {
+        s->hevcdsp.put_pcm(dst1, stride1,
+                           cb_size >> s->sps->hshift[1],
+                           cb_size >> s->sps->vshift[1],
+                           &gb, s->sps->pcm.bit_depth_chroma);
+        s->hevcdsp.put_pcm(dst2, stride2,
+                           cb_size >> s->sps->hshift[2],
+                           cb_size >> s->sps->vshift[2],
+                           &gb, s->sps->pcm.bit_depth_chroma);
+    }
+
     return 0;
 }
 
@@ -1298,7 +1305,7 @@
 
     x_off += mv->x >> 2;
     y_off += mv->y >> 2;
-    src   += y_off * srcstride + (x_off << s->sps->pixel_shift);
+    src   += y_off * srcstride + x_off * (1 << s->sps->pixel_shift);
 
     if (x_off < QPEL_EXTRA_BEFORE || y_off < QPEL_EXTRA_AFTER ||
         x_off >= pic_width - block_w - QPEL_EXTRA_AFTER ||
@@ -1453,7 +1460,7 @@
 
     x_off += mv->x >> (2 + hshift);
     y_off += mv->y >> (2 + vshift);
-    src0  += y_off * srcstride + (x_off << s->sps->pixel_shift);
+    src0  += y_off * srcstride + x_off * (1 << s->sps->pixel_shift);
 
     if (x_off < EPEL_EXTRA_BEFORE || y_off < EPEL_EXTRA_AFTER ||
         x_off >= pic_width - block_w - EPEL_EXTRA_AFTER ||
@@ -1717,12 +1724,14 @@
                     s->sh.luma_weight_l0[current_mv.ref_idx[0]],
                     s->sh.luma_offset_l0[current_mv.ref_idx[0]]);
 
-        chroma_mc_uni(s, dst1, s->frame->linesize[1], ref0->frame->data[1], ref0->frame->linesize[1],
-                      0, x0_c, y0_c, nPbW_c, nPbH_c, &current_mv,
-                      s->sh.chroma_weight_l0[current_mv.ref_idx[0]][0], s->sh.chroma_offset_l0[current_mv.ref_idx[0]][0]);
-        chroma_mc_uni(s, dst2, s->frame->linesize[2], ref0->frame->data[2], ref0->frame->linesize[2],
-                      0, x0_c, y0_c, nPbW_c, nPbH_c, &current_mv,
-                      s->sh.chroma_weight_l0[current_mv.ref_idx[0]][1], s->sh.chroma_offset_l0[current_mv.ref_idx[0]][1]);
+        if (s->sps->chroma_format_idc) {
+            chroma_mc_uni(s, dst1, s->frame->linesize[1], ref0->frame->data[1], ref0->frame->linesize[1],
+                          0, x0_c, y0_c, nPbW_c, nPbH_c, &current_mv,
+                          s->sh.chroma_weight_l0[current_mv.ref_idx[0]][0], s->sh.chroma_offset_l0[current_mv.ref_idx[0]][0]);
+            chroma_mc_uni(s, dst2, s->frame->linesize[2], ref0->frame->data[2], ref0->frame->linesize[2],
+                          0, x0_c, y0_c, nPbW_c, nPbH_c, &current_mv,
+                          s->sh.chroma_weight_l0[current_mv.ref_idx[0]][1], s->sh.chroma_offset_l0[current_mv.ref_idx[0]][1]);
+        }
     } else if (current_mv.pred_flag == PF_L1) {
         int x0_c = x0 >> s->sps->hshift[1];
         int y0_c = y0 >> s->sps->vshift[1];
@@ -1734,13 +1743,15 @@
                     s->sh.luma_weight_l1[current_mv.ref_idx[1]],
                     s->sh.luma_offset_l1[current_mv.ref_idx[1]]);
 
-        chroma_mc_uni(s, dst1, s->frame->linesize[1], ref1->frame->data[1], ref1->frame->linesize[1],
-                      1, x0_c, y0_c, nPbW_c, nPbH_c, &current_mv,
-                      s->sh.chroma_weight_l1[current_mv.ref_idx[1]][0], s->sh.chroma_offset_l1[current_mv.ref_idx[1]][0]);
+        if (s->sps->chroma_format_idc) {
+            chroma_mc_uni(s, dst1, s->frame->linesize[1], ref1->frame->data[1], ref1->frame->linesize[1],
+                          1, x0_c, y0_c, nPbW_c, nPbH_c, &current_mv,
+                          s->sh.chroma_weight_l1[current_mv.ref_idx[1]][0], s->sh.chroma_offset_l1[current_mv.ref_idx[1]][0]);
 
-        chroma_mc_uni(s, dst2, s->frame->linesize[2], ref1->frame->data[2], ref1->frame->linesize[2],
-                      1, x0_c, y0_c, nPbW_c, nPbH_c, &current_mv,
-                      s->sh.chroma_weight_l1[current_mv.ref_idx[1]][1], s->sh.chroma_offset_l1[current_mv.ref_idx[1]][1]);
+            chroma_mc_uni(s, dst2, s->frame->linesize[2], ref1->frame->data[2], ref1->frame->linesize[2],
+                          1, x0_c, y0_c, nPbW_c, nPbH_c, &current_mv,
+                          s->sh.chroma_weight_l1[current_mv.ref_idx[1]][1], s->sh.chroma_offset_l1[current_mv.ref_idx[1]][1]);
+        }
     } else if (current_mv.pred_flag == PF_BI) {
         int x0_c = x0 >> s->sps->hshift[1];
         int y0_c = y0 >> s->sps->vshift[1];
@@ -1751,11 +1762,13 @@
                    &current_mv.mv[0], x0, y0, nPbW, nPbH,
                    ref1->frame, &current_mv.mv[1], &current_mv);
 
-        chroma_mc_bi(s, dst1, s->frame->linesize[1], ref0->frame, ref1->frame,
-                     x0_c, y0_c, nPbW_c, nPbH_c, &current_mv, 0);
+        if (s->sps->chroma_format_idc) {
+            chroma_mc_bi(s, dst1, s->frame->linesize[1], ref0->frame, ref1->frame,
+                         x0_c, y0_c, nPbW_c, nPbH_c, &current_mv, 0);
 
-        chroma_mc_bi(s, dst2, s->frame->linesize[2], ref0->frame, ref1->frame,
-                     x0_c, y0_c, nPbW_c, nPbH_c, &current_mv, 1);
+            chroma_mc_bi(s, dst2, s->frame->linesize[2], ref0->frame, ref1->frame,
+                         x0_c, y0_c, nPbW_c, nPbH_c, &current_mv, 1);
+        }
     }
 }
 
@@ -2398,6 +2411,12 @@
     int startheader, cmpt = 0;
     int i, j, res = 0;
 
+    if (!ret || !arg) {
+        av_free(ret);
+        av_free(arg);
+        return AVERROR(ENOMEM);
+    }
+
 
     if (!s->sList[1]) {
         ff_alloc_entries(s->avctx, s->sh.num_entry_point_offsets + 1);
@@ -2586,7 +2605,8 @@
     if (ret < 0)
         goto fail;
 
-    ff_thread_finish_setup(s->avctx);
+    if (!s->avctx->hwaccel)
+        ff_thread_finish_setup(s->avctx);
 
     return 0;
 
@@ -2933,6 +2953,8 @@
 
             s->skipped_bytes_pos_size_nal[s->nals_allocated] = 1024; // initial buffer size
             s->skipped_bytes_pos_nal[s->nals_allocated] = av_malloc_array(s->skipped_bytes_pos_size_nal[s->nals_allocated], sizeof(*s->skipped_bytes_pos));
+            if (!s->skipped_bytes_pos_nal[s->nals_allocated])
+                goto fail;
             s->nals_allocated = new_size;
         }
         s->skipped_bytes_pos_size = s->skipped_bytes_pos_size_nal[s->nb_nals];
@@ -3167,7 +3189,10 @@
 
     av_freep(&s->cabac_state);
 
-    av_frame_free(&s->tmp_frame);
+    for (i = 0; i < 3; i++) {
+        av_freep(&s->sao_pixel_buffer_h[i]);
+        av_freep(&s->sao_pixel_buffer_v[i]);
+    }
     av_frame_free(&s->output_frame);
 
     for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++) {
@@ -3227,10 +3252,6 @@
     if (!s->cabac_state)
         goto fail;
 
-    s->tmp_frame = av_frame_alloc();
-    if (!s->tmp_frame)
-        goto fail;
-
     s->output_frame = av_frame_alloc();
     if (!s->output_frame)
         goto fail;
@@ -3319,7 +3340,7 @@
     }
 
     if (s->sps != s0->sps)
-        if ((ret = set_sps(s, s0->sps)) < 0)
+        if ((ret = set_sps(s, s0->sps, src->pix_fmt)) < 0)
             return ret;
 
     s->seq_decode = s0->seq_decode;
diff --git a/libavcodec/hevc.h b/libavcodec/hevc.h
index 1727b60..a4f7594 100644
--- a/libavcodec/hevc.h
+++ b/libavcodec/hevc.h
@@ -298,10 +298,10 @@
 } RefPicListTab;
 
 typedef struct HEVCWindow {
-    int left_offset;
-    int right_offset;
-    int top_offset;
-    int bottom_offset;
+    unsigned int left_offset;
+    unsigned int right_offset;
+    unsigned int top_offset;
+    unsigned int bottom_offset;
 } HEVCWindow;
 
 typedef struct VUI {
@@ -769,8 +769,9 @@
     int     end_of_tiles_y;
     /* +7 is for subpixel interpolation, *2 for high bit depths */
     DECLARE_ALIGNED(32, uint8_t, edge_emu_buffer)[(MAX_PB_SIZE + 7) * EDGE_EMU_BUFFER_STRIDE * 2];
+    /* The extended size between the new edge emu buffer is abused by SAO */
     DECLARE_ALIGNED(32, uint8_t, edge_emu_buffer2)[(MAX_PB_SIZE + 7) * EDGE_EMU_BUFFER_STRIDE * 2];
-    DECLARE_ALIGNED(16, int16_t, tmp [MAX_PB_SIZE * MAX_PB_SIZE]);
+    DECLARE_ALIGNED(32, int16_t, tmp [MAX_PB_SIZE * MAX_PB_SIZE]);
 
     int ct_depth;
     CodingUnit cu;
@@ -807,9 +808,9 @@
     uint8_t slice_initialized;
 
     AVFrame *frame;
-    AVFrame *sao_frame;
-    AVFrame *tmp_frame;
     AVFrame *output_frame;
+    uint8_t *sao_pixel_buffer_h[3];
+    uint8_t *sao_pixel_buffer_v[3];
 
     const HEVCVPS *vps;
     const HEVCSPS *sps;
diff --git a/libavcodec/hevc_filter.c b/libavcodec/hevc_filter.c
index 3aaf3e5..f50a640 100644
--- a/libavcodec/hevc_filter.c
+++ b/libavcodec/hevc_filter.c
@@ -139,25 +139,84 @@
     return s->qp_y_tab[x + y * s->sps->min_cb_width];
 }
 
-static void copy_CTB(uint8_t *dst, uint8_t *src,
-                     int width, int height, int stride_dst, int stride_src)
+static void copy_CTB(uint8_t *dst, const uint8_t *src, int width, int height,
+                     intptr_t stride_dst, intptr_t stride_src)
 {
-    int i;
+int i, j;
 
-    for (i = 0; i < height; i++) {
-        memcpy(dst, src, width);
-        dst += stride_dst;
-        src += stride_src;
+    if (((intptr_t)dst | (intptr_t)src | stride_dst | stride_src) & 15) {
+        for (i = 0; i < height; i++) {
+            for (j = 0; j < width; j+=8)
+                AV_COPY64U(dst+j, src+j);
+            dst += stride_dst;
+            src += stride_src;
+        }
+    } else {
+        for (i = 0; i < height; i++) {
+            for (j = 0; j < width; j+=16)
+                AV_COPY128(dst+j, src+j);
+            dst += stride_dst;
+            src += stride_src;
+        }
     }
 }
 
-static void restore_tqb_pixels(HEVCContext *s, int x0, int y0, int width, int height, int c_idx)
+static void copy_pixel(uint8_t *dst, const uint8_t *src, int pixel_shift)
+{
+    if (pixel_shift)
+        *(uint16_t *)dst = *(uint16_t *)src;
+    else
+        *dst = *src;
+}
+
+static void copy_vert(uint8_t *dst, const uint8_t *src,
+                      int pixel_shift, int height,
+                      int stride_dst, int stride_src)
+{
+    int i;
+    if (pixel_shift == 0) {
+        for (i = 0; i < height; i++) {
+            *dst = *src;
+            dst += stride_dst;
+            src += stride_src;
+        }
+    } else {
+        for (i = 0; i < height; i++) {
+            *(uint16_t *)dst = *(uint16_t *)src;
+            dst += stride_dst;
+            src += stride_src;
+        }
+    }
+}
+
+static void copy_CTB_to_hv(HEVCContext *s, const uint8_t *src,
+                           int stride_src, int x, int y, int width, int height,
+                           int c_idx, int x_ctb, int y_ctb)
+{
+    int sh = s->sps->pixel_shift;
+    int w = s->sps->width >> s->sps->hshift[c_idx];
+    int h = s->sps->height >> s->sps->vshift[c_idx];
+
+    /* copy horizontal edges */
+    memcpy(s->sao_pixel_buffer_h[c_idx] + (((2 * y_ctb) * w + x) << sh),
+        src, width << sh);
+    memcpy(s->sao_pixel_buffer_h[c_idx] + (((2 * y_ctb + 1) * w + x) << sh),
+        src + stride_src * (height - 1), width << sh);
+
+    /* copy vertical edges */
+    copy_vert(s->sao_pixel_buffer_v[c_idx] + (((2 * x_ctb) * h + y) << sh), src, sh, height, 1 << sh, stride_src);
+
+    copy_vert(s->sao_pixel_buffer_v[c_idx] + (((2 * x_ctb + 1) * h + y) << sh), src + ((width - 1) << sh), sh, height, 1 << sh, stride_src);
+}
+
+static void restore_tqb_pixels(HEVCContext *s,
+                               uint8_t *src1, const uint8_t *dst1,
+                               ptrdiff_t stride_src, ptrdiff_t stride_dst,
+                               int x0, int y0, int width, int height, int c_idx)
 {
     if ( s->pps->transquant_bypass_enable_flag ||
             (s->sps->pcm.loop_filter_disable_flag && s->sps->pcm_enabled_flag)) {
         int x, y;
-        ptrdiff_t stride_dst = s->sao_frame->linesize[c_idx];
-        ptrdiff_t stride_src = s->frame->linesize[c_idx];
         int min_pu_size  = 1 << s->sps->log2_min_pu_size;
         int hshift       = s->sps->hshift[c_idx];
         int vshift       = s->sps->vshift[c_idx];
@@ -165,13 +224,13 @@
         int y_min        = ((y0         ) >> s->sps->log2_min_pu_size);
         int x_max        = ((x0 + width ) >> s->sps->log2_min_pu_size);
         int y_max        = ((y0 + height) >> s->sps->log2_min_pu_size);
-        int len          = min_pu_size >> hshift;
+        int len          = (min_pu_size >> hshift) << s->sps->pixel_shift;
         for (y = y_min; y < y_max; y++) {
             for (x = x_min; x < x_max; x++) {
                 if (s->is_pcm[y * s->sps->min_pu_width + x]) {
                     int n;
-                    uint8_t *src = &s->frame->data[c_idx][    ((y << s->sps->log2_min_pu_size) >> vshift) * stride_src + (((x << s->sps->log2_min_pu_size) >> hshift) << s->sps->pixel_shift)];
-                    uint8_t *dst = &s->sao_frame->data[c_idx][((y << s->sps->log2_min_pu_size) >> vshift) * stride_dst + (((x << s->sps->log2_min_pu_size) >> hshift) << s->sps->pixel_shift)];
+                    uint8_t *src = src1 + (((y << s->sps->log2_min_pu_size) - y0) >> vshift) * stride_src + ((((x << s->sps->log2_min_pu_size) - x0) >> hshift) << s->sps->pixel_shift);
+                    const uint8_t *dst = dst1 + (((y << s->sps->log2_min_pu_size) - y0) >> vshift) * stride_dst + ((((x << s->sps->log2_min_pu_size) - x0) >> hshift) << s->sps->pixel_shift);
                     for (n = 0; n < (min_pu_size >> vshift); n++) {
                         memcpy(src, dst, len);
                         src += stride_src;
@@ -187,6 +246,8 @@
 
 static void sao_filter_CTB(HEVCContext *s, int x, int y)
 {
+    static const uint8_t sao_tab[8] = { 0, 1, 2, 2, 3, 3, 4, 4 };
+    HEVCLocalContext *lc = s->HEVClc;
     int c_idx;
     int edges[4];  // 0 left 1 top 2 right 3 bottom
     int x_ctb                = x >> s->sps->log2_ctb_size;
@@ -243,60 +304,139 @@
         }
     }
 
-    for (c_idx = 0; c_idx < 3; c_idx++) {
+    for (c_idx = 0; c_idx < (s->sps->chroma_format_idc ? 3 : 1); c_idx++) {
         int x0       = x >> s->sps->hshift[c_idx];
         int y0       = y >> s->sps->vshift[c_idx];
         int stride_src = s->frame->linesize[c_idx];
-        int stride_dst = s->sao_frame->linesize[c_idx];
         int ctb_size_h = (1 << (s->sps->log2_ctb_size)) >> s->sps->hshift[c_idx];
         int ctb_size_v = (1 << (s->sps->log2_ctb_size)) >> s->sps->vshift[c_idx];
         int width    = FFMIN(ctb_size_h, (s->sps->width  >> s->sps->hshift[c_idx]) - x0);
         int height   = FFMIN(ctb_size_v, (s->sps->height >> s->sps->vshift[c_idx]) - y0);
+        int tab      = sao_tab[(FFALIGN(width, 8) >> 3) - 1];
         uint8_t *src = &s->frame->data[c_idx][y0 * stride_src + (x0 << s->sps->pixel_shift)];
-        uint8_t *dst = &s->sao_frame->data[c_idx][y0 * stride_dst + (x0 << s->sps->pixel_shift)];
+        int stride_dst;
+        uint8_t *dst;
 
         switch (sao->type_idx[c_idx]) {
         case SAO_BAND:
+            copy_CTB_to_hv(s, src, stride_src, x0, y0, width, height, c_idx,
+                           x_ctb, y_ctb);
+            if (s->pps->transquant_bypass_enable_flag ||
+                (s->sps->pcm.loop_filter_disable_flag && s->sps->pcm_enabled_flag)) {
+            dst = lc->edge_emu_buffer;
+            stride_dst = 2*MAX_PB_SIZE;
             copy_CTB(dst, src, width << s->sps->pixel_shift, height, stride_dst, stride_src);
-            s->hevcdsp.sao_band_filter(src, dst,
-                                       stride_src, stride_dst,
-                                       sao,
-                                       edges, width,
-                                       height, c_idx);
-            restore_tqb_pixels(s, x, y, width, height, c_idx);
+            s->hevcdsp.sao_band_filter[tab](src, dst, stride_src, stride_dst,
+                                            sao->offset_val[c_idx], sao->band_position[c_idx],
+                                            width, height);
+            restore_tqb_pixels(s, src, dst, stride_src, stride_dst,
+                               x, y, width, height, c_idx);
+            } else {
+            s->hevcdsp.sao_band_filter[tab](src, src, stride_src, stride_src,
+                                            sao->offset_val[c_idx], sao->band_position[c_idx],
+                                            width, height);
+            }
             sao->type_idx[c_idx] = SAO_APPLIED;
             break;
         case SAO_EDGE:
         {
-            uint8_t left_pixels = !edges[0] && (CTB(s->sao, x_ctb-1, y_ctb).type_idx[c_idx] != SAO_APPLIED);
-            if (!edges[1]) {
-                uint8_t top_left  = !edges[0] && (CTB(s->sao, x_ctb-1, y_ctb-1).type_idx[c_idx] != SAO_APPLIED);
-                uint8_t top_right = !edges[2] && (CTB(s->sao, x_ctb+1, y_ctb-1).type_idx[c_idx] != SAO_APPLIED);
-                if (CTB(s->sao, x_ctb  , y_ctb-1).type_idx[c_idx] == 0)
-                    memcpy( dst - stride_dst - (top_left << s->sps->pixel_shift),
-                            src - stride_src - (top_left << s->sps->pixel_shift),
-                            (top_left + width + top_right) << s->sps->pixel_shift);
-                else {
-                    if (top_left)
-                        memcpy( dst - stride_dst - (1 << s->sps->pixel_shift),
-                                src - stride_src - (1 << s->sps->pixel_shift),
-                                1 << s->sps->pixel_shift);
-                    if(top_right)
-                        memcpy( dst - stride_dst + (width << s->sps->pixel_shift),
-                                src - stride_src + (width << s->sps->pixel_shift),
-                                1 << s->sps->pixel_shift);
+            int w = s->sps->width >> s->sps->hshift[c_idx];
+            int h = s->sps->height >> s->sps->vshift[c_idx];
+            int left_edge = edges[0];
+            int top_edge = edges[1];
+            int right_edge = edges[2];
+            int bottom_edge = edges[3];
+            int sh = s->sps->pixel_shift;
+            int left_pixels, right_pixels;
+
+            stride_dst = 2*MAX_PB_SIZE + FF_INPUT_BUFFER_PADDING_SIZE;
+            dst = lc->edge_emu_buffer + stride_dst + FF_INPUT_BUFFER_PADDING_SIZE;
+
+            if (!top_edge) {
+                int left = 1 - left_edge;
+                int right = 1 - right_edge;
+                const uint8_t *src1[2];
+                uint8_t *dst1;
+                int src_idx, pos;
+
+                dst1 = dst - stride_dst - (left << sh);
+                src1[0] = src - stride_src - (left << sh);
+                src1[1] = s->sao_pixel_buffer_h[c_idx] + (((2 * y_ctb - 1) * w + x0 - left) << sh);
+                pos = 0;
+                if (left) {
+                    src_idx = (CTB(s->sao, x_ctb-1, y_ctb-1).type_idx[c_idx] ==
+                               SAO_APPLIED);
+                    copy_pixel(dst1, src1[src_idx], sh);
+                    pos += (1 << sh);
+                }
+                src_idx = (CTB(s->sao, x_ctb, y_ctb-1).type_idx[c_idx] ==
+                           SAO_APPLIED);
+                memcpy(dst1 + pos, src1[src_idx] + pos, width << sh);
+                if (right) {
+                    pos += width << sh;
+                    src_idx = (CTB(s->sao, x_ctb+1, y_ctb-1).type_idx[c_idx] ==
+                               SAO_APPLIED);
+                    copy_pixel(dst1 + pos, src1[src_idx] + pos, sh);
                 }
             }
-            if (!edges[3]) {                                                                // bottom and bottom right
-                uint8_t bottom_left = !edges[0] && (CTB(s->sao, x_ctb-1, y_ctb+1).type_idx[c_idx] != SAO_APPLIED);
-                memcpy( dst + height * stride_dst - (bottom_left << s->sps->pixel_shift),
-                        src + height * stride_src - (bottom_left << s->sps->pixel_shift),
-                        (width + 1 + bottom_left) << s->sps->pixel_shift);
+            if (!bottom_edge) {
+                int left = 1 - left_edge;
+                int right = 1 - right_edge;
+                const uint8_t *src1[2];
+                uint8_t *dst1;
+                int src_idx, pos;
+
+                dst1 = dst + height * stride_dst - (left << sh);
+                src1[0] = src + height * stride_src - (left << sh);
+                src1[1] = s->sao_pixel_buffer_h[c_idx] + (((2 * y_ctb + 2) * w + x0 - left) << sh);
+                pos = 0;
+                if (left) {
+                    src_idx = (CTB(s->sao, x_ctb-1, y_ctb+1).type_idx[c_idx] ==
+                               SAO_APPLIED);
+                    copy_pixel(dst1, src1[src_idx], sh);
+                    pos += (1 << sh);
+                }
+                src_idx = (CTB(s->sao, x_ctb, y_ctb+1).type_idx[c_idx] ==
+                           SAO_APPLIED);
+                memcpy(dst1 + pos, src1[src_idx] + pos, width << sh);
+                if (right) {
+                    pos += width << sh;
+                    src_idx = (CTB(s->sao, x_ctb+1, y_ctb+1).type_idx[c_idx] ==
+                               SAO_APPLIED);
+                    copy_pixel(dst1 + pos, src1[src_idx] + pos, sh);
+                }
             }
-            copy_CTB(dst - (left_pixels << s->sps->pixel_shift),
-                     src - (left_pixels << s->sps->pixel_shift),
-                     (width + 1 + left_pixels) << s->sps->pixel_shift, height, stride_dst, stride_src);
-            s->hevcdsp.sao_edge_filter[restore](src, dst,
+            left_pixels = 0;
+            if (!left_edge) {
+                if (CTB(s->sao, x_ctb-1, y_ctb).type_idx[c_idx] == SAO_APPLIED) {
+                    copy_vert(dst - (1 << sh),
+                              s->sao_pixel_buffer_v[c_idx] + (((2 * x_ctb - 1) * h + y0) << sh),
+                              sh, height, stride_dst, 1 << sh);
+                } else {
+                    left_pixels = 1;
+                }
+            }
+            right_pixels = 0;
+            if (!right_edge) {
+                if (CTB(s->sao, x_ctb+1, y_ctb).type_idx[c_idx] == SAO_APPLIED) {
+                    copy_vert(dst + (width << sh),
+                              s->sao_pixel_buffer_v[c_idx] + (((2 * x_ctb + 2) * h + y0) << sh),
+                              sh, height, stride_dst, 1 << sh);
+                } else {
+                    right_pixels = 1;
+                }
+            }
+
+            copy_CTB(dst - (left_pixels << sh),
+                     src - (left_pixels << sh),
+                     (width + left_pixels + right_pixels) << sh,
+                     height, stride_dst, stride_src);
+
+            copy_CTB_to_hv(s, src, stride_src, x0, y0, width, height, c_idx,
+                           x_ctb, y_ctb);
+            s->hevcdsp.sao_edge_filter[tab](src, dst, stride_src, sao->offset_val[c_idx],
+                                            sao->eo_class[c_idx], width, height);
+            s->hevcdsp.sao_edge_restore[restore](src, dst,
                                                 stride_src, stride_dst,
                                                 sao,
                                                 edges, width,
@@ -304,7 +444,8 @@
                                                 vert_edge,
                                                 horiz_edge,
                                                 diag_edge);
-            restore_tqb_pixels(s, x, y, width, height, c_idx);
+            restore_tqb_pixels(s, src, dst, stride_src, stride_dst,
+                               x, y, width, height, c_idx);
             sao->type_idx[c_idx] = SAO_APPLIED;
             break;
         }
@@ -437,68 +578,70 @@
         }
     }
 
-    for (chroma = 1; chroma <= 2; chroma++) {
-        int h = 1 << s->sps->hshift[chroma];
-        int v = 1 << s->sps->vshift[chroma];
+    if (s->sps->chroma_format_idc) {
+        for (chroma = 1; chroma <= 2; chroma++) {
+            int h = 1 << s->sps->hshift[chroma];
+            int v = 1 << s->sps->vshift[chroma];
 
-        // vertical filtering chroma
-        for (y = y0; y < y_end; y += (8 * v)) {
-            for (x = x0 ? x0 : 8 * h; x < x_end; x += (8 * h)) {
-                const int bs0 = s->vertical_bs[(x +  y            * s->bs_width) >> 2];
-                const int bs1 = s->vertical_bs[(x + (y + (4 * v)) * s->bs_width) >> 2];
+            // vertical filtering chroma
+            for (y = y0; y < y_end; y += (8 * v)) {
+                for (x = x0 ? x0 : 8 * h; x < x_end; x += (8 * h)) {
+                    const int bs0 = s->vertical_bs[(x +  y            * s->bs_width) >> 2];
+                    const int bs1 = s->vertical_bs[(x + (y + (4 * v)) * s->bs_width) >> 2];
 
-                if ((bs0 == 2) || (bs1 == 2)) {
-                    const int qp0 = (get_qPy(s, x - 1, y)           + get_qPy(s, x, y)           + 1) >> 1;
-                    const int qp1 = (get_qPy(s, x - 1, y + (4 * v)) + get_qPy(s, x, y + (4 * v)) + 1) >> 1;
+                    if ((bs0 == 2) || (bs1 == 2)) {
+                        const int qp0 = (get_qPy(s, x - 1, y)           + get_qPy(s, x, y)           + 1) >> 1;
+                        const int qp1 = (get_qPy(s, x - 1, y + (4 * v)) + get_qPy(s, x, y + (4 * v)) + 1) >> 1;
 
-                    c_tc[0] = (bs0 == 2) ? chroma_tc(s, qp0, chroma, tc_offset) : 0;
-                    c_tc[1] = (bs1 == 2) ? chroma_tc(s, qp1, chroma, tc_offset) : 0;
-                    src       = &s->frame->data[chroma][(y >> s->sps->vshift[chroma]) * s->frame->linesize[chroma] + ((x >> s->sps->hshift[chroma]) << s->sps->pixel_shift)];
-                    if (pcmf) {
-                        no_p[0] = get_pcm(s, x - 1, y);
-                        no_p[1] = get_pcm(s, x - 1, y + (4 * v));
-                        no_q[0] = get_pcm(s, x, y);
-                        no_q[1] = get_pcm(s, x, y + (4 * v));
-                        s->hevcdsp.hevc_v_loop_filter_chroma_c(src,
-                                                               s->frame->linesize[chroma],
-                                                               c_tc, no_p, no_q);
-                    } else
-                        s->hevcdsp.hevc_v_loop_filter_chroma(src,
-                                                             s->frame->linesize[chroma],
-                                                             c_tc, no_p, no_q);
+                        c_tc[0] = (bs0 == 2) ? chroma_tc(s, qp0, chroma, tc_offset) : 0;
+                        c_tc[1] = (bs1 == 2) ? chroma_tc(s, qp1, chroma, tc_offset) : 0;
+                        src       = &s->frame->data[chroma][(y >> s->sps->vshift[chroma]) * s->frame->linesize[chroma] + ((x >> s->sps->hshift[chroma]) << s->sps->pixel_shift)];
+                        if (pcmf) {
+                            no_p[0] = get_pcm(s, x - 1, y);
+                            no_p[1] = get_pcm(s, x - 1, y + (4 * v));
+                            no_q[0] = get_pcm(s, x, y);
+                            no_q[1] = get_pcm(s, x, y + (4 * v));
+                            s->hevcdsp.hevc_v_loop_filter_chroma_c(src,
+                                                                   s->frame->linesize[chroma],
+                                                                   c_tc, no_p, no_q);
+                        } else
+                            s->hevcdsp.hevc_v_loop_filter_chroma(src,
+                                                                 s->frame->linesize[chroma],
+                                                                 c_tc, no_p, no_q);
+                    }
                 }
-            }
 
-            if(!y)
-                 continue;
+                if(!y)
+                    continue;
 
-            // horizontal filtering chroma
-            tc_offset = x0 ? left_tc_offset : cur_tc_offset;
-            x_end2 = x_end;
-            if (x_end != s->sps->width)
-                x_end2 = x_end - 8 * h;
-            for (x = x0 ? x0 - 8 * h : 0; x < x_end2; x += (8 * h)) {
-                const int bs0 = s->horizontal_bs[( x          + y * s->bs_width) >> 2];
-                const int bs1 = s->horizontal_bs[((x + 4 * h) + y * s->bs_width) >> 2];
-                if ((bs0 == 2) || (bs1 == 2)) {
-                    const int qp0 = bs0 == 2 ? (get_qPy(s, x,           y - 1) + get_qPy(s, x,           y) + 1) >> 1 : 0;
-                    const int qp1 = bs1 == 2 ? (get_qPy(s, x + (4 * h), y - 1) + get_qPy(s, x + (4 * h), y) + 1) >> 1 : 0;
+                // horizontal filtering chroma
+                tc_offset = x0 ? left_tc_offset : cur_tc_offset;
+                x_end2 = x_end;
+                if (x_end != s->sps->width)
+                    x_end2 = x_end - 8 * h;
+                for (x = x0 ? x0 - 8 * h : 0; x < x_end2; x += (8 * h)) {
+                    const int bs0 = s->horizontal_bs[( x          + y * s->bs_width) >> 2];
+                    const int bs1 = s->horizontal_bs[((x + 4 * h) + y * s->bs_width) >> 2];
+                    if ((bs0 == 2) || (bs1 == 2)) {
+                        const int qp0 = bs0 == 2 ? (get_qPy(s, x,           y - 1) + get_qPy(s, x,           y) + 1) >> 1 : 0;
+                        const int qp1 = bs1 == 2 ? (get_qPy(s, x + (4 * h), y - 1) + get_qPy(s, x + (4 * h), y) + 1) >> 1 : 0;
 
-                    c_tc[0]   = bs0 == 2 ? chroma_tc(s, qp0, chroma, tc_offset)     : 0;
-                    c_tc[1]   = bs1 == 2 ? chroma_tc(s, qp1, chroma, cur_tc_offset) : 0;
-                    src       = &s->frame->data[chroma][(y >> s->sps->vshift[1]) * s->frame->linesize[chroma] + ((x >> s->sps->hshift[1]) << s->sps->pixel_shift)];
-                    if (pcmf) {
-                        no_p[0] = get_pcm(s, x,           y - 1);
-                        no_p[1] = get_pcm(s, x + (4 * h), y - 1);
-                        no_q[0] = get_pcm(s, x,           y);
-                        no_q[1] = get_pcm(s, x + (4 * h), y);
-                        s->hevcdsp.hevc_h_loop_filter_chroma_c(src,
-                                                               s->frame->linesize[chroma],
-                                                               c_tc, no_p, no_q);
-                    } else
-                        s->hevcdsp.hevc_h_loop_filter_chroma(src,
-                                                             s->frame->linesize[chroma],
-                                                             c_tc, no_p, no_q);
+                        c_tc[0]   = bs0 == 2 ? chroma_tc(s, qp0, chroma, tc_offset)     : 0;
+                        c_tc[1]   = bs1 == 2 ? chroma_tc(s, qp1, chroma, cur_tc_offset) : 0;
+                        src       = &s->frame->data[chroma][(y >> s->sps->vshift[1]) * s->frame->linesize[chroma] + ((x >> s->sps->hshift[1]) << s->sps->pixel_shift)];
+                        if (pcmf) {
+                            no_p[0] = get_pcm(s, x,           y - 1);
+                            no_p[1] = get_pcm(s, x + (4 * h), y - 1);
+                            no_q[0] = get_pcm(s, x,           y);
+                            no_q[1] = get_pcm(s, x + (4 * h), y);
+                            s->hevcdsp.hevc_h_loop_filter_chroma_c(src,
+                                                                   s->frame->linesize[chroma],
+                                                                   c_tc, no_p, no_q);
+                        } else
+                            s->hevcdsp.hevc_h_loop_filter_chroma(src,
+                                                                 s->frame->linesize[chroma],
+                                                                 c_tc, no_p, no_q);
+                    }
                 }
             }
         }
diff --git a/libavcodec/hevc_mvs.c b/libavcodec/hevc_mvs.c
index 318e7a2..7e34669 100644
--- a/libavcodec/hevc_mvs.c
+++ b/libavcodec/hevc_mvs.c
@@ -118,7 +118,7 @@
     td = av_clip_int8(td);
     tb = av_clip_int8(tb);
     tx = (0x4000 + abs(td / 2)) / td;
-    scale_factor = av_clip((tb * tx + 32) >> 6, -4096, 4095);
+    scale_factor = av_clip_intp2((tb * tx + 32) >> 6, 12);
     dst->x = av_clip_int16((scale_factor * src->x + 127 +
                            (scale_factor * src->x < 0)) >> 8);
     dst->y = av_clip_int16((scale_factor * src->y + 127 +
diff --git a/libavcodec/hevc_parser.c b/libavcodec/hevc_parser.c
index 834b93b..7076897 100644
--- a/libavcodec/hevc_parser.c
+++ b/libavcodec/hevc_parser.c
@@ -286,21 +286,21 @@
 // Split after the parameter sets at the beginning of the stream if they exist.
 static int hevc_split(AVCodecContext *avctx, const uint8_t *buf, int buf_size)
 {
-    int i;
+    const uint8_t *ptr = buf, *end = buf + buf_size;
     uint32_t state = -1;
-    int has_ps = 0;
+    int has_ps = 0, nut;
 
-    for (i = 0; i < buf_size; i++) {
-        state = (state << 8) | buf[i];
-        if (((state >> 8) & 0xFFFFFF) == START_CODE) {
-            int nut = (state >> 1) & 0x3F;
-            if (nut >= NAL_VPS && nut <= NAL_PPS)
-                has_ps = 1;
-            else if (has_ps)
-                return i - 3;
-            else // no parameter set at the beginning of the stream
-                return 0;
-        }
+    while (ptr < end) {
+        ptr = avpriv_find_start_code(ptr, end, &state);
+        if ((state >> 8) != START_CODE)
+            break;
+        nut = (state >> 1) & 0x3F;
+        if (nut >= NAL_VPS && nut <= NAL_PPS)
+            has_ps = 1;
+        else if (has_ps)
+            return ptr - 4 - buf;
+        else // no parameter set at the beginning of the stream
+            return 0;
     }
     return 0;
 }
@@ -309,6 +309,8 @@
 {
     HEVCContext  *h  = &((HEVCParseContext *)s->priv_data)->h;
     h->HEVClc = av_mallocz(sizeof(HEVCLocalContext));
+    if (!h->HEVClc)
+        return AVERROR(ENOMEM);
     h->skipped_bytes_pos_size = INT_MAX;
 
     return 0;
diff --git a/libavcodec/hevc_ps.c b/libavcodec/hevc_ps.c
index 464176b..075a4bd 100644
--- a/libavcodec/hevc_ps.c
+++ b/libavcodec/hevc_ps.c
@@ -755,11 +755,6 @@
     }
 
     sps->chroma_format_idc = get_ue_golomb_long(gb);
-    if (!(sps->chroma_format_idc == 1 || sps->chroma_format_idc == 2 || sps->chroma_format_idc == 3)) {
-        avpriv_report_missing_feature(s->avctx, "chroma_format_idc != {1, 2, 3}\n");
-        ret = AVERROR_PATCHWELCOME;
-        goto err;
-    }
 
     if (sps->chroma_format_idc == 3)
         sps->separate_colour_plane_flag = get_bits1(gb);
@@ -799,7 +794,7 @@
 
     sps->bit_depth   = get_ue_golomb_long(gb) + 8;
     bit_depth_chroma = get_ue_golomb_long(gb) + 8;
-    if (bit_depth_chroma != sps->bit_depth) {
+    if (sps->chroma_format_idc && bit_depth_chroma != sps->bit_depth) {
         av_log(s->avctx, AV_LOG_ERROR,
                "Luma bit depth (%d) is different from chroma bit depth (%d), "
                "this is unsupported.\n",
@@ -810,21 +805,25 @@
 
     switch (sps->bit_depth) {
     case 8:
+        if (sps->chroma_format_idc == 0) sps->pix_fmt = AV_PIX_FMT_GRAY8;
         if (sps->chroma_format_idc == 1) sps->pix_fmt = AV_PIX_FMT_YUV420P;
         if (sps->chroma_format_idc == 2) sps->pix_fmt = AV_PIX_FMT_YUV422P;
         if (sps->chroma_format_idc == 3) sps->pix_fmt = AV_PIX_FMT_YUV444P;
        break;
     case 9:
+        if (sps->chroma_format_idc == 0) sps->pix_fmt = AV_PIX_FMT_GRAY16;
         if (sps->chroma_format_idc == 1) sps->pix_fmt = AV_PIX_FMT_YUV420P9;
         if (sps->chroma_format_idc == 2) sps->pix_fmt = AV_PIX_FMT_YUV422P9;
         if (sps->chroma_format_idc == 3) sps->pix_fmt = AV_PIX_FMT_YUV444P9;
         break;
     case 10:
+        if (sps->chroma_format_idc == 0) sps->pix_fmt = AV_PIX_FMT_GRAY16;
         if (sps->chroma_format_idc == 1) sps->pix_fmt = AV_PIX_FMT_YUV420P10;
         if (sps->chroma_format_idc == 2) sps->pix_fmt = AV_PIX_FMT_YUV422P10;
         if (sps->chroma_format_idc == 3) sps->pix_fmt = AV_PIX_FMT_YUV444P10;
         break;
     case 12:
+        if (sps->chroma_format_idc == 0) sps->pix_fmt = AV_PIX_FMT_GRAY16;
         if (sps->chroma_format_idc == 1) sps->pix_fmt = AV_PIX_FMT_YUV420P12;
         if (sps->chroma_format_idc == 2) sps->pix_fmt = AV_PIX_FMT_YUV422P12;
         if (sps->chroma_format_idc == 3) sps->pix_fmt = AV_PIX_FMT_YUV444P12;
@@ -895,11 +894,30 @@
     sps->log2_max_trafo_size                 = log2_diff_max_min_transform_block_size +
                                                sps->log2_min_tb_size;
 
-    if (sps->log2_min_tb_size >= sps->log2_min_cb_size) {
+    if (sps->log2_min_cb_size < 3 || sps->log2_min_cb_size > 30) {
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid value %d for log2_min_cb_size", sps->log2_min_cb_size);
+        ret = AVERROR_INVALIDDATA;
+        goto err;
+    }
+
+    if (sps->log2_diff_max_min_coding_block_size > 30) {
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid value %d for log2_diff_max_min_coding_block_size", sps->log2_diff_max_min_coding_block_size);
+        ret = AVERROR_INVALIDDATA;
+        goto err;
+    }
+
+    if (sps->log2_min_tb_size >= sps->log2_min_cb_size || sps->log2_min_tb_size < 2) {
         av_log(s->avctx, AV_LOG_ERROR, "Invalid value for log2_min_tb_size");
         ret = AVERROR_INVALIDDATA;
         goto err;
     }
+
+    if (log2_diff_max_min_transform_block_size < 0 || log2_diff_max_min_transform_block_size > 30) {
+        av_log(s->avctx, AV_LOG_ERROR, "Invalid value %d for log2_diff_max_min_transform_block_size", log2_diff_max_min_transform_block_size);
+        ret = AVERROR_INVALIDDATA;
+        goto err;
+    }
+
     sps->max_transform_hierarchy_depth_inter = get_ue_golomb_long(gb);
     sps->max_transform_hierarchy_depth_intra = get_ue_golomb_long(gb);
 
@@ -1021,7 +1039,8 @@
                          (sps->output_window.left_offset + sps->output_window.right_offset);
     sps->output_height = sps->height -
                          (sps->output_window.top_offset + sps->output_window.bottom_offset);
-    if (sps->output_width <= 0 || sps->output_height <= 0) {
+    if (sps->width  <= sps->output_window.left_offset + (int64_t)sps->output_window.right_offset  ||
+        sps->height <= sps->output_window.top_offset  + (int64_t)sps->output_window.bottom_offset) {
         av_log(s->avctx, AV_LOG_WARNING, "Invalid visible frame dimensions: %dx%d.\n",
                sps->output_width, sps->output_height);
         if (s->avctx->err_recognition & AV_EF_EXPLODE) {
@@ -1065,6 +1084,14 @@
         av_log(s->avctx, AV_LOG_ERROR, "CTB size out of range: 2^%d\n", sps->log2_ctb_size);
         goto err;
     }
+    if (sps->log2_ctb_size < 4) {
+        av_log(s->avctx,
+               AV_LOG_ERROR,
+               "log2_ctb_size %d differs from the bounds of any known profile\n",
+               sps->log2_ctb_size);
+        avpriv_request_sample(s->avctx, "log2_ctb_size %d", sps->log2_ctb_size);
+        goto err;
+    }
     if (sps->max_transform_hierarchy_depth_inter > sps->log2_ctb_size - sps->log2_min_tb_size) {
         av_log(s->avctx, AV_LOG_ERROR, "max_transform_hierarchy_depth_inter out of range: %d\n",
                sps->max_transform_hierarchy_depth_inter);
diff --git a/libavcodec/hevc_refs.c b/libavcodec/hevc_refs.c
index f6596e8..fea3d12 100644
--- a/libavcodec/hevc_refs.c
+++ b/libavcodec/hevc_refs.c
@@ -386,8 +386,9 @@
         }
     }
 
-    av_log(s->avctx, AV_LOG_ERROR,
-           "Could not find ref with POC %d\n", poc);
+    if (s->nal_unit_type != NAL_CRA_NUT && !IS_BLA(s))
+        av_log(s->avctx, AV_LOG_ERROR,
+               "Could not find ref with POC %d\n", poc);
     return NULL;
 }
 
diff --git a/libavcodec/hevcdsp.c b/libavcodec/hevcdsp.c
index 3eae541..04af178 100644
--- a/libavcodec/hevcdsp.c
+++ b/libavcodec/hevcdsp.c
@@ -212,9 +212,18 @@
     hevcdsp->idct_dc[2]             = FUNC(idct_16x16_dc, depth);           \
     hevcdsp->idct_dc[3]             = FUNC(idct_32x32_dc, depth);           \
                                                                             \
-    hevcdsp->sao_band_filter    = FUNC(sao_band_filter_0, depth);              \
-    hevcdsp->sao_edge_filter[0] = FUNC(sao_edge_filter_0, depth);              \
-    hevcdsp->sao_edge_filter[1] = FUNC(sao_edge_filter_1, depth);              \
+    hevcdsp->sao_band_filter[0] =                                              \
+    hevcdsp->sao_band_filter[1] =                                              \
+    hevcdsp->sao_band_filter[2] =                                              \
+    hevcdsp->sao_band_filter[3] =                                              \
+    hevcdsp->sao_band_filter[4] = FUNC(sao_band_filter_0, depth);              \
+    hevcdsp->sao_edge_filter[0] =                                              \
+    hevcdsp->sao_edge_filter[1] =                                              \
+    hevcdsp->sao_edge_filter[2] =                                              \
+    hevcdsp->sao_edge_filter[3] =                                              \
+    hevcdsp->sao_edge_filter[4] = FUNC(sao_edge_filter, depth);                \
+    hevcdsp->sao_edge_restore[0] = FUNC(sao_edge_restore_0, depth);            \
+    hevcdsp->sao_edge_restore[1] = FUNC(sao_edge_restore_1, depth);            \
                                                                                \
     QPEL_FUNCS(depth);                                                         \
     QPEL_UNI_FUNCS(depth);                                                     \
@@ -250,4 +259,6 @@
 
     if (ARCH_X86)
         ff_hevc_dsp_init_x86(hevcdsp, bit_depth);
+    if (ARCH_ARM)
+        ff_hevcdsp_init_arm(hevcdsp, bit_depth);
 }
diff --git a/libavcodec/hevcdsp.h b/libavcodec/hevcdsp.h
index ced3b99..a891ea7 100644
--- a/libavcodec/hevcdsp.h
+++ b/libavcodec/hevcdsp.h
@@ -58,14 +58,16 @@
 
     void (*idct_dc[4])(int16_t *coeffs);
 
-    void (*sao_band_filter)(uint8_t *_dst, uint8_t *_src, ptrdiff_t _stride_dst, ptrdiff_t _stride_src,
-                            struct SAOParams *sao, int *borders,
-                            int width, int height, int c_idx);
+    void (*sao_band_filter[5])(uint8_t *_dst, uint8_t *_src, ptrdiff_t _stride_dst, ptrdiff_t _stride_src,
+                               int16_t *sao_offset_val, int sao_left_class, int width, int height);
 
-    void (*sao_edge_filter[2])(uint8_t *_dst, uint8_t *_src, ptrdiff_t _stride_dst, ptrdiff_t _stride_src,
-                               struct SAOParams *sao, int *borders, int _width,
-                               int _height, int c_idx, uint8_t *vert_edge,
-                               uint8_t *horiz_edge, uint8_t *diag_edge);
+    /* implicit stride_src parameter has value of 2 * MAX_PB_SIZE + FF_INPUT_BUFFER_PADDING_SIZE */
+    void (*sao_edge_filter[5])(uint8_t *_dst /* align 16 */, uint8_t *_src /* align 32 */, ptrdiff_t stride_dst,
+                               int16_t *sao_offset_val, int sao_eo_class, int width, int height);
+
+    void (*sao_edge_restore[2])(uint8_t *_dst, uint8_t *_src, ptrdiff_t _stride_dst, ptrdiff_t _stride_src,
+                                struct SAOParams *sao, int *borders, int _width, int _height, int c_idx,
+                                uint8_t *vert_edge, uint8_t *horiz_edge, uint8_t *diag_edge);
 
     void (*put_hevc_qpel[10][2][2])(int16_t *dst, uint8_t *src, ptrdiff_t srcstride,
                                     int height, intptr_t mx, intptr_t my, int width);
@@ -126,5 +128,5 @@
 extern const int8_t ff_hevc_qpel_filters[3][16];
 
 void ff_hevc_dsp_init_x86(HEVCDSPContext *c, const int bit_depth);
-
+void ff_hevcdsp_init_arm(HEVCDSPContext *c, const int bit_depth);
 #endif /* AVCODEC_HEVCDSP_H */
diff --git a/libavcodec/hevcdsp_template.c b/libavcodec/hevcdsp_template.c
index 360a509..cec28e4 100644
--- a/libavcodec/hevcdsp_template.c
+++ b/libavcodec/hevcdsp_template.c
@@ -302,17 +302,15 @@
 #undef ADD_AND_SCALE
 
 static void FUNC(sao_band_filter_0)(uint8_t *_dst, uint8_t *_src,
-                                  ptrdiff_t stride_dst, ptrdiff_t stride_src, SAOParams *sao,
-                                  int *borders, int width, int height,
-                                  int c_idx)
+                                    ptrdiff_t stride_dst, ptrdiff_t stride_src,
+                                    int16_t *sao_offset_val, int sao_left_class,
+                                    int width, int height)
 {
     pixel *dst = (pixel *)_dst;
     pixel *src = (pixel *)_src;
     int offset_table[32] = { 0 };
     int k, y, x;
     int shift  = BIT_DEPTH - 5;
-    int16_t *sao_offset_val = sao->offset_val[c_idx];
-    int sao_left_class  = sao->band_position[c_idx];
 
     stride_dst /= sizeof(pixel);
     stride_src /= sizeof(pixel);
@@ -327,12 +325,10 @@
     }
 }
 
-#define CMP(a, b) ((a) > (b) ? 1 : ((a) == (b) ? 0 : -1))
+#define CMP(a, b) (((a) > (b)) - ((a) < (b)))
 
-static void FUNC(sao_edge_filter)(uint8_t *_dst, uint8_t *_src,
-                                  ptrdiff_t stride_dst, ptrdiff_t stride_src, SAOParams *sao,
-                                  int width, int height,
-                                  int c_idx, int init_x, int init_y) {
+static void FUNC(sao_edge_filter)(uint8_t *_dst, uint8_t *_src, ptrdiff_t stride_dst, int16_t *sao_offset_val,
+                                  int eo, int width, int height) {
 
     static const uint8_t edge_idx[] = { 1, 2, 0, 3, 4 };
     static const int8_t pos[4][2][2] = {
@@ -341,36 +337,78 @@
         { { -1, -1 }, {  1, 1 } }, // 45 degree
         { {  1, -1 }, { -1, 1 } }, // 135 degree
     };
-    int16_t *sao_offset_val = sao->offset_val[c_idx];
-    int sao_eo_class    = sao->eo_class[c_idx];
     pixel *dst = (pixel *)_dst;
     pixel *src = (pixel *)_src;
-
-    int y_stride_src = init_y * stride_src;
-    int y_stride_dst = init_y * stride_dst;
-    int pos_0_0  = pos[sao_eo_class][0][0];
-    int pos_0_1  = pos[sao_eo_class][0][1];
-    int pos_1_0  = pos[sao_eo_class][1][0];
-    int pos_1_1  = pos[sao_eo_class][1][1];
+    int a_stride, b_stride;
     int x, y;
+    ptrdiff_t stride_src = (2*MAX_PB_SIZE + FF_INPUT_BUFFER_PADDING_SIZE) / sizeof(pixel);
+    stride_dst /= sizeof(pixel);
 
-    int y_stride_0_1 = (init_y + pos_0_1) * stride_src;
-    int y_stride_1_1 = (init_y + pos_1_1) * stride_src;
-    for (y = init_y; y < height; y++) {
-        for (x = init_x; x < width; x++) {
-            int diff0             = CMP(src[x + y_stride_src], src[x + pos_0_0 + y_stride_0_1]);
-            int diff1             = CMP(src[x + y_stride_src], src[x + pos_1_0 + y_stride_1_1]);
+    a_stride = pos[eo][0][0] + pos[eo][0][1] * stride_src;
+    b_stride = pos[eo][1][0] + pos[eo][1][1] * stride_src;
+    for (y = 0; y < height; y++) {
+        for (x = 0; x < width; x++) {
+            int diff0 = CMP(src[x], src[x + a_stride]);
+            int diff1 = CMP(src[x], src[x + b_stride]);
             int offset_val        = edge_idx[2 + diff0 + diff1];
-            dst[x + y_stride_dst] = av_clip_pixel(src[x + y_stride_src] + sao_offset_val[offset_val]);
+            dst[x] = av_clip_pixel(src[x] + sao_offset_val[offset_val]);
         }
-        y_stride_src += stride_src;
-        y_stride_dst += stride_dst;
-        y_stride_0_1 += stride_src;
-        y_stride_1_1 += stride_src;
+        src += stride_src;
+        dst += stride_dst;
     }
 }
 
-static void FUNC(sao_edge_filter_0)(uint8_t *_dst, uint8_t *_src,
+static void FUNC(sao_edge_restore_0)(uint8_t *_dst, uint8_t *_src,
+                                    ptrdiff_t stride_dst, ptrdiff_t stride_src, SAOParams *sao,
+                                    int *borders, int _width, int _height,
+                                    int c_idx, uint8_t *vert_edge,
+                                    uint8_t *horiz_edge, uint8_t *diag_edge)
+{
+    int x, y;
+    pixel *dst = (pixel *)_dst;
+    pixel *src = (pixel *)_src;
+    int16_t *sao_offset_val = sao->offset_val[c_idx];
+    int sao_eo_class    = sao->eo_class[c_idx];
+    int init_x = 0, width = _width, height = _height;
+
+    stride_dst /= sizeof(pixel);
+    stride_src /= sizeof(pixel);
+
+    if (sao_eo_class != SAO_EO_VERT) {
+        if (borders[0]) {
+            int offset_val = sao_offset_val[0];
+            for (y = 0; y < height; y++) {
+                dst[y * stride_dst] = av_clip_pixel(src[y * stride_src] + offset_val);
+            }
+            init_x = 1;
+        }
+        if (borders[2]) {
+            int offset_val = sao_offset_val[0];
+            int offset     = width - 1;
+            for (x = 0; x < height; x++) {
+                dst[x * stride_dst + offset] = av_clip_pixel(src[x * stride_src + offset] + offset_val);
+            }
+            width--;
+        }
+    }
+    if (sao_eo_class != SAO_EO_HORIZ) {
+        if (borders[1]) {
+            int offset_val = sao_offset_val[0];
+            for (x = init_x; x < width; x++)
+                dst[x] = av_clip_pixel(src[x] + offset_val);
+        }
+        if (borders[3]) {
+            int offset_val   = sao_offset_val[0];
+            int y_stride_dst = stride_dst * (height - 1);
+            int y_stride_src = stride_src * (height - 1);
+            for (x = init_x; x < width; x++)
+                dst[x + y_stride_dst] = av_clip_pixel(src[x + y_stride_src] + offset_val);
+            height--;
+        }
+    }
+}
+
+static void FUNC(sao_edge_restore_1)(uint8_t *_dst, uint8_t *_src,
                                     ptrdiff_t stride_dst, ptrdiff_t stride_src, SAOParams *sao,
                                     int *borders, int _width, int _height,
                                     int c_idx, uint8_t *vert_edge,
@@ -420,61 +458,6 @@
         }
     }
 
-    FUNC(sao_edge_filter)((uint8_t *)dst, (uint8_t *)src, stride_dst, stride_src, sao, width, height, c_idx, init_x, init_y);
-}
-
-static void FUNC(sao_edge_filter_1)(uint8_t *_dst, uint8_t *_src,
-                                    ptrdiff_t stride_dst, ptrdiff_t stride_src, SAOParams *sao,
-                                    int *borders, int _width, int _height,
-                                    int c_idx, uint8_t *vert_edge,
-                                    uint8_t *horiz_edge, uint8_t *diag_edge)
-{
-    int x, y;
-    pixel *dst = (pixel *)_dst;
-    pixel *src = (pixel *)_src;
-    int16_t *sao_offset_val = sao->offset_val[c_idx];
-    int sao_eo_class    = sao->eo_class[c_idx];
-    int init_x = 0, init_y = 0, width = _width, height = _height;
-
-    stride_dst /= sizeof(pixel);
-    stride_src /= sizeof(pixel);
-
-    if (sao_eo_class != SAO_EO_VERT) {
-        if (borders[0]) {
-            int offset_val = sao_offset_val[0];
-            for (y = 0; y < height; y++) {
-                dst[y * stride_dst] = av_clip_pixel(src[y * stride_src] + offset_val);
-            }
-            init_x = 1;
-        }
-        if (borders[2]) {
-            int offset_val = sao_offset_val[0];
-            int offset     = width - 1;
-            for (x = 0; x < height; x++) {
-                dst[x * stride_dst + offset] = av_clip_pixel(src[x * stride_src + offset] + offset_val);
-            }
-            width--;
-        }
-    }
-    if (sao_eo_class != SAO_EO_HORIZ) {
-        if (borders[1]) {
-            int offset_val = sao_offset_val[0];
-            for (x = init_x; x < width; x++)
-                dst[x] = av_clip_pixel(src[x] + offset_val);
-            init_y = 1;
-        }
-        if (borders[3]) {
-            int offset_val   = sao_offset_val[0];
-            int y_stride_dst = stride_dst * (height - 1);
-            int y_stride_src = stride_src * (height - 1);
-            for (x = init_x; x < width; x++)
-                dst[x + y_stride_dst] = av_clip_pixel(src[x + y_stride_src] + offset_val);
-            height--;
-        }
-    }
-
-    FUNC(sao_edge_filter)((uint8_t *)dst, (uint8_t *)src, stride_dst, stride_src, sao, width, height, c_idx, init_x, init_y);
-
     {
         int save_upper_left  = !diag_edge[0] && sao_eo_class == SAO_EO_135D && !borders[0] && !borders[1];
         int save_upper_right = !diag_edge[1] && sao_eo_class == SAO_EO_45D  && !borders[1] && !borders[2];
diff --git a/libavcodec/hqx.c b/libavcodec/hqx.c
new file mode 100644
index 0000000..d7e605f
--- /dev/null
+++ b/libavcodec/hqx.c
@@ -0,0 +1,643 @@
+/*
+ * Canopus HQX decoder
+ *
+ * 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 <inttypes.h>
+
+#include "libavutil/imgutils.h"
+#include "libavutil/intreadwrite.h"
+
+#include "avcodec.h"
+#include "get_bits.h"
+#include "internal.h"
+
+#include "hqx.h"
+
+/* HQX has four modes - 422, 444, 422alpha and 444alpha - all 12-bit */
+enum HQXFormat {
+    HQX_422 = 0,
+    HQX_444,
+    HQX_422A,
+    HQX_444A,
+};
+
+#define HQX_HEADER_SIZE 59
+
+typedef int (*mb_decode_func)(HQXContext *ctx, AVFrame *pic,
+                              GetBitContext *gb, int x, int y);
+
+/* macroblock selects a group of 4 possible quants and
+ * a block can use any of those four quantisers
+ * one column is powers of 2, the other one is powers of 2 * 3,
+ * then there is the special one, powers of 2 * 5 */
+static const int hqx_quants[16][4] = {
+    {  0x1,   0x2,   0x4,   0x8 }, {  0x1,  0x3,   0x6,   0xC },
+    {  0x2,   0x4,   0x8,  0x10 }, {  0x3,  0x6,   0xC,  0x18 },
+    {  0x4,   0x8,  0x10,  0x20 }, {  0x6,  0xC,  0x18,  0x30 },
+    {  0x8,  0x10,  0x20,  0x40 },
+                      { 0xA, 0x14, 0x28, 0x50 },
+                                   {  0xC, 0x18,  0x30,  0x60 },
+    { 0x10,  0x20,  0x40,  0x80 }, { 0x18, 0x30,  0x60,  0xC0 },
+    { 0x20,  0x40,  0x80, 0x100 }, { 0x30, 0x60,  0xC0, 0x180 },
+    { 0x40,  0x80, 0x100, 0x200 }, { 0x60, 0xC0, 0x180, 0x300 },
+    { 0x80, 0x100, 0x200, 0x400 }
+};
+
+static const uint8_t hqx_quant_luma[64] = {
+    16,  16,  16,  19,  19,  19,  42,  44,
+    16,  16,  19,  19,  19,  38,  43,  45,
+    16,  19,  19,  19,  40,  41,  45,  48,
+    19,  19,  19,  40,  41,  42,  46,  49,
+    19,  19,  40,  41,  42,  43,  48, 101,
+    19,  38,  41,  42,  43,  44,  98, 104,
+    42,  43,  45,  46,  48,  98, 109, 116,
+    44,  45,  48,  49, 101, 104, 116, 123,
+};
+
+static const uint8_t hqx_quant_chroma[64] = {
+    16,  16,  19,  25,  26,  26,  42,  44,
+    16,  19,  25,  25,  26,  38,  43,  91,
+    19,  25,  26,  27,  40,  41,  91,  96,
+    25,  25,  27,  40,  41,  84,  93, 197,
+    26,  26,  40,  41,  84,  86, 191, 203,
+    26,  38,  41,  84,  86, 177, 197, 209,
+    42,  43,  91,  93, 191, 197, 219, 232,
+    44,  91,  96, 197, 203, 209, 232, 246,
+};
+
+static inline void idct_col(int16_t *blk, const uint8_t *quant)
+{
+    int t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, tA, tB, tC, tD, tE, tF;
+    int t10, t11, t12, t13;
+    int s0, s1, s2, s3, s4, s5, s6, s7;
+
+    s0 = (int) blk[0 * 8] * quant[0 * 8];
+    s1 = (int) blk[1 * 8] * quant[1 * 8];
+    s2 = (int) blk[2 * 8] * quant[2 * 8];
+    s3 = (int) blk[3 * 8] * quant[3 * 8];
+    s4 = (int) blk[4 * 8] * quant[4 * 8];
+    s5 = (int) blk[5 * 8] * quant[5 * 8];
+    s6 = (int) blk[6 * 8] * quant[6 * 8];
+    s7 = (int) blk[7 * 8] * quant[7 * 8];
+
+    t0  =  (s3 * 19266 + s5 * 12873) >> 15;
+    t1  =  (s5 * 19266 - s3 * 12873) >> 15;
+    t2  = ((s7 * 4520  + s1 * 22725) >> 15) - t0;
+    t3  = ((s1 * 4520  - s7 * 22725) >> 15) - t1;
+    t4  = t0 * 2 + t2;
+    t5  = t1 * 2 + t3;
+    t6  = t2 - t3;
+    t7  = t3 * 2 + t6;
+    t8  = (t6 * 11585) >> 14;
+    t9  = (t7 * 11585) >> 14;
+    tA  = (s2 * 8867 - s6 * 21407) >> 14;
+    tB  = (s6 * 8867 + s2 * 21407) >> 14;
+    tC  = (s0 >> 1) - (s4 >> 1);
+    tD  = (s4 >> 1) * 2 + tC;
+    tE  = tC - (tA >> 1);
+    tF  = tD - (tB >> 1);
+    t10 = tF - t5;
+    t11 = tE - t8;
+    t12 = tE + (tA >> 1) * 2 - t9;
+    t13 = tF + (tB >> 1) * 2 - t4;
+
+    blk[0 * 8] = t13 + t4 * 2;
+    blk[1 * 8] = t12 + t9 * 2;
+    blk[2 * 8] = t11 + t8 * 2;
+    blk[3 * 8] = t10 + t5 * 2;
+    blk[4 * 8] = t10;
+    blk[5 * 8] = t11;
+    blk[6 * 8] = t12;
+    blk[7 * 8] = t13;
+}
+
+static inline void idct_row(int16_t *blk)
+{
+    int t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, tA, tB, tC, tD, tE, tF;
+    int t10, t11, t12, t13;
+
+    t0  =  (blk[3] * 19266 + blk[5] * 12873) >> 14;
+    t1  =  (blk[5] * 19266 - blk[3] * 12873) >> 14;
+    t2  = ((blk[7] * 4520  + blk[1] * 22725) >> 14) - t0;
+    t3  = ((blk[1] * 4520  - blk[7] * 22725) >> 14) - t1;
+    t4  = t0 * 2 + t2;
+    t5  = t1 * 2 + t3;
+    t6  = t2 - t3;
+    t7  = t3 * 2 + t6;
+    t8  = (t6 * 11585) >> 14;
+    t9  = (t7 * 11585) >> 14;
+    tA  = (blk[2] * 8867 - blk[6] * 21407) >> 14;
+    tB  = (blk[6] * 8867 + blk[2] * 21407) >> 14;
+    tC  = blk[0] - blk[4];
+    tD  = blk[4] * 2 + tC;
+    tE  = tC - tA;
+    tF  = tD - tB;
+    t10 = tF - t5;
+    t11 = tE - t8;
+    t12 = tE + tA * 2 - t9;
+    t13 = tF + tB * 2 - t4;
+
+    blk[0] = (t13 + t4 * 2 + 4) >> 3;
+    blk[1] = (t12 + t9 * 2 + 4) >> 3;
+    blk[2] = (t11 + t8 * 2 + 4) >> 3;
+    blk[3] = (t10 + t5 * 2 + 4) >> 3;
+    blk[4] = (t10          + 4) >> 3;
+    blk[5] = (t11          + 4) >> 3;
+    blk[6] = (t12          + 4) >> 3;
+    blk[7] = (t13          + 4) >> 3;
+}
+
+static void hqx_idct(int16_t *block, const uint8_t *quant)
+{
+    int i;
+
+    for (i = 0; i < 8; i++)
+        idct_col(block + i, quant + i);
+    for (i = 0; i < 8; i++)
+        idct_row(block + i * 8);
+}
+
+static void hqx_idct_put(uint16_t *dst, ptrdiff_t stride,
+                         int16_t *block, const uint8_t *quant)
+{
+    int i, j;
+
+    hqx_idct(block, quant);
+
+    for (i = 0; i < 8; i++) {
+        for (j = 0; j < 8; j++) {
+            int v = av_clip(block[j + i * 8] + 0x800, 0, 0x1000);
+            dst[j] = (v << 4) | (v >> 8);
+        }
+        dst += stride >> 1;
+    }
+}
+
+static inline void put_blocks(AVFrame *pic, int plane,
+                              int x, int y, int ilace,
+                              int16_t *block0, int16_t *block1,
+                              const uint8_t *quant)
+{
+    int fields = ilace ? 2 : 1;
+    int lsize = pic->linesize[plane];
+    uint8_t *p = pic->data[plane] + x * 2;
+
+    hqx_idct_put((uint16_t *)(p + y * lsize), lsize * fields, block0, quant);
+    hqx_idct_put((uint16_t *)(p + (y + (ilace ? 1 : 8)) * lsize),
+                 lsize * fields, block1, quant);
+}
+
+static inline void hqx_get_ac(GetBitContext *gb, const HQXAC *ac,
+                              int *run, int *lev)
+{
+    int val;
+
+    val = show_bits(gb, ac->lut_bits);
+    if (ac->lut[val].bits == -1) {
+        GetBitContext gb2 = *gb;
+        skip_bits(&gb2, ac->lut_bits);
+        val = ac->lut[val].lev + show_bits(&gb2, ac->extra_bits);
+    }
+    *run = ac->lut[val].run;
+    *lev = ac->lut[val].lev;
+    skip_bits(gb, ac->lut[val].bits);
+}
+
+static int decode_block(GetBitContext *gb, VLC *vlc,
+                        const int *quants, int dcb,
+                        int16_t block[64], int *last_dc)
+{
+    int q, dc;
+    int ac_idx;
+    int run, lev, pos = 1;
+
+    memset(block, 0, 64 * sizeof(*block));
+    dc = get_vlc2(gb, vlc->table, HQX_DC_VLC_BITS, 2);
+    if (dc < 0)
+        return AVERROR_INVALIDDATA;
+    *last_dc += dc;
+
+    block[0] = sign_extend(*last_dc << (12 - dcb), 12);
+
+    q = quants[get_bits(gb, 2)];
+    if (q >= 128)
+        ac_idx = HQX_AC_Q128;
+    else if (q >= 64)
+        ac_idx = HQX_AC_Q64;
+    else if (q >= 32)
+        ac_idx = HQX_AC_Q32;
+    else if (q >= 16)
+        ac_idx = HQX_AC_Q16;
+    else if (q >= 8)
+        ac_idx = HQX_AC_Q8;
+    else
+        ac_idx = HQX_AC_Q0;
+
+    do {
+        hqx_get_ac(gb, &ff_hqx_ac[ac_idx], &run, &lev);
+        pos += run;
+        if (pos >= 64)
+            break;
+        block[ff_zigzag_direct[pos++]] = lev * q;
+    } while (pos < 64);
+
+    return 0;
+}
+
+static int hqx_decode_422(HQXContext *ctx, AVFrame *pic,
+                          GetBitContext *gb, int x, int y)
+{
+    const int *quants;
+    int flag;
+    int last_dc;
+    int i, ret;
+
+    if (ctx->interlaced)
+        flag = get_bits1(gb);
+    else
+        flag = 0;
+
+    quants = hqx_quants[get_bits(gb, 4)];
+
+    for (i = 0; i < 8; i++) {
+        int vlc_index = ctx->dcb - 9;
+        if (i == 0 || i == 4 || i == 6)
+            last_dc = 0;
+        ret = decode_block(gb, &ctx->dc_vlc[vlc_index], quants,
+                           ctx->dcb, ctx->block[i], &last_dc);
+        if (ret < 0)
+            return ret;
+    }
+
+    put_blocks(pic, 0, x,      y, flag, ctx->block[0], ctx->block[2], hqx_quant_luma);
+    put_blocks(pic, 0, x + 8,  y, flag, ctx->block[1], ctx->block[3], hqx_quant_luma);
+    put_blocks(pic, 2, x >> 1, y, flag, ctx->block[4], ctx->block[5], hqx_quant_chroma);
+    put_blocks(pic, 1, x >> 1, y, flag, ctx->block[6], ctx->block[7], hqx_quant_chroma);
+
+    return 0;
+}
+
+static int hqx_decode_422a(HQXContext *ctx, AVFrame *pic,
+                           GetBitContext *gb, int x, int y)
+{
+    const int *quants;
+    int flag = 0;
+    int last_dc;
+    int i, ret;
+    int cbp;
+
+    cbp = get_vlc2(gb, ctx->cbp_vlc.table, ctx->cbp_vlc.bits, 1);
+
+    for (i = 0; i < 12; i++)
+        memset(ctx->block[i], 0, sizeof(**ctx->block) * 64);
+    for (i = 0; i < 12; i++)
+        ctx->block[i][0] = -0x800;
+    if (cbp) {
+        if (ctx->interlaced)
+            flag = get_bits1(gb);
+
+        quants = hqx_quants[get_bits(gb, 4)];
+
+        cbp |= cbp << 4; // alpha CBP
+        if (cbp & 0x3)   // chroma CBP - top
+            cbp |= 0x500;
+        if (cbp & 0xC)   // chroma CBP - bottom
+            cbp |= 0xA00;
+        for (i = 0; i < 12; i++) {
+            if (i == 0 || i == 4 || i == 8 || i == 10)
+                last_dc = 0;
+            if (cbp & (1 << i)) {
+                int vlc_index = ctx->dcb - 9;
+                ret = decode_block(gb, &ctx->dc_vlc[vlc_index], quants,
+                                   ctx->dcb, ctx->block[i], &last_dc);
+                if (ret < 0)
+                    return ret;
+            }
+        }
+    }
+
+    put_blocks(pic, 3, x,      y, flag, ctx->block[ 0], ctx->block[ 2], hqx_quant_luma);
+    put_blocks(pic, 3, x + 8,  y, flag, ctx->block[ 1], ctx->block[ 3], hqx_quant_luma);
+    put_blocks(pic, 0, x,      y, flag, ctx->block[ 4], ctx->block[ 6], hqx_quant_luma);
+    put_blocks(pic, 0, x + 8,  y, flag, ctx->block[ 5], ctx->block[ 7], hqx_quant_luma);
+    put_blocks(pic, 2, x >> 1, y, flag, ctx->block[ 8], ctx->block[ 9], hqx_quant_chroma);
+    put_blocks(pic, 1, x >> 1, y, flag, ctx->block[10], ctx->block[11], hqx_quant_chroma);
+
+    return 0;
+}
+
+static int hqx_decode_444(HQXContext *ctx, AVFrame *pic,
+                          GetBitContext *gb, int x, int y)
+{
+    const int *quants;
+    int flag;
+    int last_dc;
+    int i, ret;
+
+    if (ctx->interlaced)
+        flag = get_bits1(gb);
+    else
+        flag = 0;
+
+    quants = hqx_quants[get_bits(gb, 4)];
+
+    for (i = 0; i < 12; i++) {
+        int vlc_index = ctx->dcb - 9;
+        if (i == 0 || i == 4 || i == 8)
+            last_dc = 0;
+        ret = decode_block(gb, &ctx->dc_vlc[vlc_index], quants,
+                           ctx->dcb, ctx->block[i], &last_dc);
+        if (ret < 0)
+            return ret;
+    }
+
+    put_blocks(pic, 0, x,     y, flag, ctx->block[0], ctx->block[ 2], hqx_quant_luma);
+    put_blocks(pic, 0, x + 8, y, flag, ctx->block[1], ctx->block[ 3], hqx_quant_luma);
+    put_blocks(pic, 2, x,     y, flag, ctx->block[4], ctx->block[ 6], hqx_quant_chroma);
+    put_blocks(pic, 2, x + 8, y, flag, ctx->block[5], ctx->block[ 7], hqx_quant_chroma);
+    put_blocks(pic, 1, x,     y, flag, ctx->block[8], ctx->block[10], hqx_quant_chroma);
+    put_blocks(pic, 1, x + 8, y, flag, ctx->block[9], ctx->block[11], hqx_quant_chroma);
+
+    return 0;
+}
+
+static int hqx_decode_444a(HQXContext *ctx, AVFrame *pic,
+                           GetBitContext *gb, int x, int y)
+{
+    const int *quants;
+    int flag = 0;
+    int last_dc;
+    int i, ret;
+    int cbp;
+
+    cbp = get_vlc2(gb, ctx->cbp_vlc.table, ctx->cbp_vlc.bits, 1);
+
+    for (i = 0; i < 16; i++)
+        memset(ctx->block[i], 0, sizeof(**ctx->block) * 64);
+    for (i = 0; i < 16; i++)
+        ctx->block[i][0] = -0x800;
+    if (cbp) {
+        if (ctx->interlaced)
+            flag = get_bits1(gb);
+
+        quants = hqx_quants[get_bits(gb, 4)];
+
+        cbp |= cbp << 4; // alpha CBP
+        cbp |= cbp << 8; // chroma CBP
+        for (i = 0; i < 16; i++) {
+            if (i == 0 || i == 4 || i == 8 || i == 12)
+                last_dc = 0;
+            if (cbp & (1 << i)) {
+                int vlc_index = ctx->dcb - 9;
+                ret = decode_block(gb, &ctx->dc_vlc[vlc_index], quants,
+                                   ctx->dcb, ctx->block[i], &last_dc);
+                if (ret < 0)
+                    return ret;
+            }
+        }
+    }
+
+    put_blocks(pic, 3, x,     y, flag, ctx->block[ 0], ctx->block[ 2], hqx_quant_luma);
+    put_blocks(pic, 3, x + 8, y, flag, ctx->block[ 1], ctx->block[ 3], hqx_quant_luma);
+    put_blocks(pic, 0, x,     y, flag, ctx->block[ 4], ctx->block[ 6], hqx_quant_luma);
+    put_blocks(pic, 0, x + 8, y, flag, ctx->block[ 5], ctx->block[ 7], hqx_quant_luma);
+    put_blocks(pic, 2, x,     y, flag, ctx->block[ 8], ctx->block[10], hqx_quant_chroma);
+    put_blocks(pic, 2, x + 8, y, flag, ctx->block[ 9], ctx->block[11], hqx_quant_chroma);
+    put_blocks(pic, 1, x,     y, flag, ctx->block[12], ctx->block[14], hqx_quant_chroma);
+    put_blocks(pic, 1, x + 8, y, flag, ctx->block[13], ctx->block[15], hqx_quant_chroma);
+
+    return 0;
+}
+
+static const int shuffle_16[16] = {
+    0, 5, 11, 14, 2, 7, 9, 13, 1, 4, 10, 15, 3, 6, 8, 12
+};
+
+static int decode_slice(HQXContext *ctx, AVFrame *pic, GetBitContext *gb,
+                        int slice_no, mb_decode_func decode_func)
+{
+    int mb_w = (ctx->width  + 15) >> 4;
+    int mb_h = (ctx->height + 15) >> 4;
+    int grp_w = (mb_w + 4) / 5;
+    int grp_h = (mb_h + 4) / 5;
+    int grp_h_edge = grp_w * (mb_w / grp_w);
+    int grp_v_edge = grp_h * (mb_h / grp_h);
+    int grp_v_rest = mb_w - grp_h_edge;
+    int grp_h_rest = mb_h - grp_v_edge;
+    int num_mbs = mb_w * mb_h;
+    int num_tiles = (num_mbs + 479) / 480;
+    int std_tile_blocks = num_mbs / (16 * num_tiles);
+    int g_tile = slice_no * num_tiles;
+    int blk_addr, loc_addr, mb_x, mb_y, pos, loc_row, i;
+    int tile_blocks, tile_limit, tile_no;
+
+    for (tile_no = 0; tile_no < num_tiles; tile_no++, g_tile++) {
+        tile_blocks = std_tile_blocks;
+        tile_limit = -1;
+        if (g_tile < num_mbs - std_tile_blocks * 16 * num_tiles) {
+            tile_limit = num_mbs / (16 * num_tiles);
+            tile_blocks++;
+        }
+        for (i = 0; i < tile_blocks; i++) {
+            if (i == tile_limit)
+                blk_addr = g_tile + 16 * num_tiles * i;
+            else
+                blk_addr = tile_no + 16 * num_tiles * i +
+                           num_tiles * shuffle_16[(i + slice_no) & 0xF];
+            loc_row  = grp_h * (blk_addr / (grp_h * mb_w));
+            loc_addr =          blk_addr % (grp_h * mb_w);
+            if (loc_row >= grp_v_edge) {
+                mb_x = grp_w * (loc_addr / (grp_h_rest * grp_w));
+                pos  =          loc_addr % (grp_h_rest * grp_w);
+            } else {
+                mb_x = grp_w * (loc_addr / (grp_h * grp_w));
+                pos  =          loc_addr % (grp_h * grp_w);
+            }
+            if (mb_x >= grp_h_edge) {
+                mb_x +=            pos % grp_v_rest;
+                mb_y  = loc_row + (pos / grp_v_rest);
+            } else {
+                mb_x +=            pos % grp_w;
+                mb_y  = loc_row + (pos / grp_w);
+            }
+            decode_func(ctx, pic, gb, mb_x * 16, mb_y * 16);
+        }
+    }
+
+    return 0;
+}
+
+static int hqx_decode_frame(AVCodecContext *avctx, void *data,
+                            int *got_picture_ptr, AVPacket *avpkt)
+{
+    HQXContext *ctx = avctx->priv_data;
+    AVFrame *pic = data;
+    uint8_t *src = avpkt->data;
+    uint32_t info_tag, info_offset;
+    int data_start;
+    unsigned data_size;
+    GetBitContext gb;
+    int i, ret;
+    int slice;
+    uint32_t slice_off[17];
+    mb_decode_func decode_func = 0;
+
+    if (avpkt->size < 8)
+        return AVERROR_INVALIDDATA;
+
+    /* Skip the INFO header if present */
+    info_offset = 0;
+    info_tag    = AV_RL32(src);
+    if (info_tag == MKTAG('I', 'N', 'F', 'O')) {
+        info_offset = AV_RL32(src + 4);
+        if (info_offset > UINT32_MAX - 8 || info_offset + 8 > avpkt->size) {
+            av_log(avctx, AV_LOG_ERROR,
+                   "Invalid INFO header offset: 0x%08"PRIX32" is too large.\n",
+                   info_offset);
+            return AVERROR_INVALIDDATA;
+        }
+
+        info_offset += 8;
+        src         += info_offset;
+
+        av_log(avctx, AV_LOG_DEBUG, "Skipping INFO chunk.\n");
+    }
+
+    data_start = src - avpkt->data;
+    data_size  = avpkt->size - data_start;
+
+    if (data_size < HQX_HEADER_SIZE) {
+        av_log(avctx, AV_LOG_ERROR, "Frame too small.\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    if (src[0] != 'H' || src[1] != 'Q') {
+        av_log(avctx, AV_LOG_ERROR, "Not an HQX frame.\n");
+        return AVERROR_INVALIDDATA;
+    }
+    ctx->interlaced = !(src[2] & 0x80);
+    ctx->format     = src[2] & 7;
+    ctx->dcb        = (src[3] & 3) + 8;
+    ctx->width      = AV_RB16(src + 4);
+    ctx->height     = AV_RB16(src + 6);
+    for (i = 0; i < 17; i++)
+        slice_off[i] = AV_RB24(src + 8 + i * 3);
+
+    if (ctx->dcb == 8) {
+        av_log(avctx, AV_LOG_ERROR, "Invalid DC precision %d.\n", ctx->dcb);
+        return AVERROR_INVALIDDATA;
+    }
+    ret = av_image_check_size(ctx->width, ctx->height, 0, avctx);
+    if (ret < 0) {
+        av_log(avctx, AV_LOG_ERROR, "Invalid stored dimensions %dx%d.\n",
+               ctx->width, ctx->height);
+        return AVERROR_INVALIDDATA;
+    }
+
+    avctx->coded_width         = FFALIGN(ctx->width,  16);
+    avctx->coded_height        = FFALIGN(ctx->height, 16);
+    avctx->width               = ctx->width;
+    avctx->height              = ctx->height;
+    avctx->bits_per_raw_sample = 10;
+
+    switch (ctx->format) {
+    case HQX_422:
+        avctx->pix_fmt = AV_PIX_FMT_YUV422P16;
+        decode_func = hqx_decode_422;
+        break;
+    case HQX_444:
+        avctx->pix_fmt = AV_PIX_FMT_YUV444P16;
+        decode_func = hqx_decode_444;
+        break;
+    case HQX_422A:
+        avctx->pix_fmt = AV_PIX_FMT_YUVA422P16;
+        decode_func = hqx_decode_422a;
+        break;
+    case HQX_444A:
+        avctx->pix_fmt = AV_PIX_FMT_YUVA444P16;
+        decode_func = hqx_decode_444a;
+        break;
+    }
+    if (!decode_func) {
+        av_log(avctx, AV_LOG_ERROR, "Invalid format: %d.\n", ctx->format);
+        return AVERROR_INVALIDDATA;
+    }
+
+    ret = ff_get_buffer(avctx, pic, 0);
+    if (ret < 0)
+        return ret;
+
+    for (slice = 0; slice < 16; slice++) {
+        if (slice_off[slice] < HQX_HEADER_SIZE ||
+            slice_off[slice] >= slice_off[slice + 1] ||
+            slice_off[slice + 1] > data_size) {
+            av_log(avctx, AV_LOG_ERROR, "Invalid slice size.\n");
+            break;
+        }
+        ret = init_get_bits8(&gb, src + slice_off[slice],
+                             slice_off[slice + 1] - slice_off[slice]);
+        if (ret < 0)
+            return ret;
+        ret = decode_slice(ctx, pic, &gb, slice, decode_func);
+        if (ret < 0) {
+            av_log(avctx, AV_LOG_ERROR, "Error decoding slice %d.\n", slice);
+        }
+    }
+
+    pic->key_frame = 1;
+    pic->pict_type = AV_PICTURE_TYPE_I;
+
+    *got_picture_ptr = 1;
+
+    return avpkt->size;
+}
+
+static av_cold int hqx_decode_close(AVCodecContext *avctx)
+{
+    int i;
+    HQXContext *ctx = avctx->priv_data;
+
+    ff_free_vlc(&ctx->cbp_vlc);
+    for (i = 0; i < 3; i++) {
+        ff_free_vlc(&ctx->dc_vlc[i]);
+    }
+
+    return 0;
+}
+
+static av_cold int hqx_decode_init(AVCodecContext *avctx)
+{
+    HQXContext *ctx = avctx->priv_data;
+    int ret = ff_hqx_init_vlcs(ctx);
+    if (ret < 0)
+        hqx_decode_close(avctx);
+    return ret;
+}
+
+AVCodec ff_hqx_decoder = {
+    .name           = "hqx",
+    .long_name      = NULL_IF_CONFIG_SMALL("Canopus HQX"),
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = AV_CODEC_ID_HQX,
+    .priv_data_size = sizeof(HQXContext),
+    .init           = hqx_decode_init,
+    .decode         = hqx_decode_frame,
+    .close          = hqx_decode_close,
+    .capabilities   = CODEC_CAP_DR1,
+};
diff --git a/libavcodec/hqx.h b/libavcodec/hqx.h
new file mode 100644
index 0000000..c4c2220
--- /dev/null
+++ b/libavcodec/hqx.h
@@ -0,0 +1,65 @@
+/*
+ * Canopus HQX decoder
+ *
+ * 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_HQX_H
+#define AVCODEC_HQX_H
+
+#include <stdint.h>
+#include "libavutil/mem.h"
+#include "get_bits.h"
+
+enum HQXACMode {
+    HQX_AC_Q0 = 0,
+    HQX_AC_Q8,
+    HQX_AC_Q16,
+    HQX_AC_Q32,
+    HQX_AC_Q64,
+    HQX_AC_Q128,
+    NUM_HQX_AC
+};
+
+typedef struct HQXLUT {
+    int16_t lev;
+    uint8_t run;
+    int8_t  bits;
+} HQXLUT;
+
+typedef struct HQXAC {
+    int lut_bits, extra_bits;
+    const HQXLUT *lut;
+} HQXAC;
+
+typedef struct HQXContext {
+    int format, dcb, width, height;
+    int interlaced;
+
+    DECLARE_ALIGNED(16, int16_t, block)[16][64];
+
+    VLC cbp_vlc;
+    VLC dc_vlc[3];
+} HQXContext;
+
+#define HQX_DC_VLC_BITS 9
+
+extern const HQXAC ff_hqx_ac[NUM_HQX_AC];
+
+int ff_hqx_init_vlcs(HQXContext *ctx);
+
+#endif /* AVCODEC_HQX_H */
diff --git a/libavcodec/hqxvlc.c b/libavcodec/hqxvlc.c
new file mode 100644
index 0000000..06a8073
--- /dev/null
+++ b/libavcodec/hqxvlc.c
@@ -0,0 +1,2163 @@
+/*
+ * Canopus HQX decoder
+ *
+ * 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 "hqx.h"
+
+static const uint8_t cbp_vlc_bits[16] = {
+    0x04, 0x1C, 0x1D, 0x09, 0x1E, 0x0B, 0x1B, 0x08,
+    0x1F, 0x1A, 0x0C, 0x07, 0x0A, 0x06, 0x05, 0x00,
+};
+
+static const uint8_t cbp_vlc_lens[16] = {
+    4, 5, 5, 4, 5, 4, 5, 4, 5, 5, 4, 4, 4, 4, 4, 2,
+};
+
+static const uint16_t dc9_vlc_bits[512] = {
+    0x0010, 0x0008, 0x0022, 0x0024, 0x0026, 0x0028, 0x002A, 0x002C,
+    0x002E, 0x0030, 0x0032, 0x0034, 0x0074, 0x0076, 0x0078, 0x007A,
+    0x007C, 0x0000, 0x0002, 0x0004, 0x0006, 0x0008, 0x000A, 0x000C,
+    0x000E, 0x0050, 0x0052, 0x0054, 0x0056, 0x0058, 0x005A, 0x005C,
+    0x005E, 0x0020, 0x0022, 0x0024, 0x0026, 0x0028, 0x002A, 0x002C,
+    0x002E, 0x0030, 0x0032, 0x0034, 0x0036, 0x0038, 0x003A, 0x003C,
+    0x003E, 0x00C0, 0x00C2, 0x00C4, 0x00C6, 0x00C8, 0x00CA, 0x00CC,
+    0x00CE, 0x00D0, 0x00D2, 0x00D4, 0x00D6, 0x00D8, 0x00DA, 0x00DC,
+    0x00DE, 0x01C0, 0x01C2, 0x01C4, 0x01C6, 0x01C8, 0x01CA, 0x01CC,
+    0x01CE, 0x01D0, 0x01D2, 0x01D4, 0x01D6, 0x01D8, 0x01DA, 0x01DC,
+    0x01DE, 0x01E0, 0x01E2, 0x01E4, 0x01E6, 0x01E8, 0x01EA, 0x01EC,
+    0x01EE, 0x01F0, 0x01F2, 0x01F4, 0x01F6, 0x01F8, 0x01FA, 0x01FC,
+    0x01FE, 0x06C0, 0x06C2, 0x06C4, 0x06C6, 0x06C8, 0x06CA, 0x06CC,
+    0x06CE, 0x06D0, 0x06D2, 0x06D4, 0x06D6, 0x06D8, 0x06DA, 0x06DC,
+    0x06DE, 0x06E0, 0x06E2, 0x06E4, 0x06E6, 0x06E8, 0x06EA, 0x06EC,
+    0x06EE, 0x06F0, 0x06F2, 0x06F4, 0x06F6, 0x06F8, 0x06FA, 0x06FC,
+    0x06FE, 0x0E00, 0x0E02, 0x0E04, 0x0E06, 0x0E08, 0x0E0A, 0x0E0C,
+    0x0E0E, 0x0E10, 0x0E12, 0x0E14, 0x0E16, 0x0E18, 0x0E1A, 0x0E1C,
+    0x0E1E, 0x0E20, 0x0E22, 0x0E24, 0x0E26, 0x0E28, 0x0E2A, 0x0E2C,
+    0x0E2E, 0x0E30, 0x0E32, 0x0E34, 0x0E36, 0x0E38, 0x0E3A, 0x0E3C,
+    0x0E3E, 0x0E40, 0x0E42, 0x0E44, 0x0E46, 0x0E48, 0x0E4A, 0x0E4C,
+    0x0E4E, 0x0E50, 0x0E52, 0x0E54, 0x0E56, 0x0E58, 0x0E5A, 0x0E5C,
+    0x0E5E, 0x0E60, 0x0E62, 0x0E64, 0x0E66, 0x0E68, 0x0E6A, 0x0E6C,
+    0x0E6E, 0x0E70, 0x0E72, 0x0E74, 0x0E76, 0x0E78, 0x0E7A, 0x0E7C,
+    0x0E7E, 0x1F80, 0x1F82, 0x1F84, 0x1F86, 0x1F88, 0x1F8A, 0x1F8C,
+    0x1F8E, 0x1F90, 0x1F92, 0x1F94, 0x1F96, 0x1F98, 0x1F9A, 0x1F9C,
+    0x1F9E, 0x1FA0, 0x1FA2, 0x1FA4, 0x1FA6, 0x1FA8, 0x1FAA, 0x1FAC,
+    0x1FAE, 0x1FB0, 0x1FB2, 0x1FB4, 0x1FB6, 0x1FB8, 0x1FBA, 0x1FBC,
+    0x1FBE, 0x1FC0, 0x1FC2, 0x1FC4, 0x1FC6, 0x1FC8, 0x1FCA, 0x1FCC,
+    0x1FCE, 0x1FD0, 0x1FD2, 0x1FD4, 0x1FD6, 0x1FD8, 0x1FDA, 0x1FDC,
+    0x1FDE, 0x1FE0, 0x1FE2, 0x1FE4, 0x1FE6, 0x1FE8, 0x1FEA, 0x1FEC,
+    0x1FEE, 0x1FF0, 0x1FF2, 0x1FF4, 0x1FF6, 0x1FF8, 0x1FFA, 0x1FFC,
+    0x0FFF, 0x1FFD, 0x1FFB, 0x1FF9, 0x1FF7, 0x1FF5, 0x1FF3, 0x1FF1,
+    0x1FEF, 0x1FED, 0x1FEB, 0x1FE9, 0x1FE7, 0x1FE5, 0x1FE3, 0x1FE1,
+    0x1FDF, 0x1FDD, 0x1FDB, 0x1FD9, 0x1FD7, 0x1FD5, 0x1FD3, 0x1FD1,
+    0x1FCF, 0x1FCD, 0x1FCB, 0x1FC9, 0x1FC7, 0x1FC5, 0x1FC3, 0x1FC1,
+    0x1FBF, 0x1FBD, 0x1FBB, 0x1FB9, 0x1FB7, 0x1FB5, 0x1FB3, 0x1FB1,
+    0x1FAF, 0x1FAD, 0x1FAB, 0x1FA9, 0x1FA7, 0x1FA5, 0x1FA3, 0x1FA1,
+    0x1F9F, 0x1F9D, 0x1F9B, 0x1F99, 0x1F97, 0x1F95, 0x1F93, 0x1F91,
+    0x1F8F, 0x1F8D, 0x1F8B, 0x1F89, 0x1F87, 0x1F85, 0x1F83, 0x1F81,
+    0x0E7F, 0x0E7D, 0x0E7B, 0x0E79, 0x0E77, 0x0E75, 0x0E73, 0x0E71,
+    0x0E6F, 0x0E6D, 0x0E6B, 0x0E69, 0x0E67, 0x0E65, 0x0E63, 0x0E61,
+    0x0E5F, 0x0E5D, 0x0E5B, 0x0E59, 0x0E57, 0x0E55, 0x0E53, 0x0E51,
+    0x0E4F, 0x0E4D, 0x0E4B, 0x0E49, 0x0E47, 0x0E45, 0x0E43, 0x0E41,
+    0x0E3F, 0x0E3D, 0x0E3B, 0x0E39, 0x0E37, 0x0E35, 0x0E33, 0x0E31,
+    0x0E2F, 0x0E2D, 0x0E2B, 0x0E29, 0x0E27, 0x0E25, 0x0E23, 0x0E21,
+    0x0E1F, 0x0E1D, 0x0E1B, 0x0E19, 0x0E17, 0x0E15, 0x0E13, 0x0E11,
+    0x0E0F, 0x0E0D, 0x0E0B, 0x0E09, 0x0E07, 0x0E05, 0x0E03, 0x0E01,
+    0x06FF, 0x06FD, 0x06FB, 0x06F9, 0x06F7, 0x06F5, 0x06F3, 0x06F1,
+    0x06EF, 0x06ED, 0x06EB, 0x06E9, 0x06E7, 0x06E5, 0x06E3, 0x06E1,
+    0x06DF, 0x06DD, 0x06DB, 0x06D9, 0x06D7, 0x06D5, 0x06D3, 0x06D1,
+    0x06CF, 0x06CD, 0x06CB, 0x06C9, 0x06C7, 0x06C5, 0x06C3, 0x06C1,
+    0x01FF, 0x01FD, 0x01FB, 0x01F9, 0x01F7, 0x01F5, 0x01F3, 0x01F1,
+    0x01EF, 0x01ED, 0x01EB, 0x01E9, 0x01E7, 0x01E5, 0x01E3, 0x01E1,
+    0x01DF, 0x01DD, 0x01DB, 0x01D9, 0x01D7, 0x01D5, 0x01D3, 0x01D1,
+    0x01CF, 0x01CD, 0x01CB, 0x01C9, 0x01C7, 0x01C5, 0x01C3, 0x01C1,
+    0x00DF, 0x00DD, 0x00DB, 0x00D9, 0x00D7, 0x00D5, 0x00D3, 0x00D1,
+    0x00CF, 0x00CD, 0x00CB, 0x00C9, 0x00C7, 0x00C5, 0x00C3, 0x00C1,
+    0x003F, 0x003D, 0x003B, 0x0039, 0x0037, 0x0035, 0x0033, 0x0031,
+    0x002F, 0x002D, 0x002B, 0x0029, 0x0027, 0x0025, 0x0023, 0x0021,
+    0x005F, 0x005D, 0x005B, 0x0059, 0x0057, 0x0055, 0x0053, 0x0051,
+    0x000F, 0x000D, 0x000B, 0x0009, 0x0007, 0x0005, 0x0003, 0x0001,
+    0x007D, 0x007B, 0x0079, 0x0077, 0x0075, 0x0035, 0x0033, 0x0031,
+    0x002F, 0x002D, 0x002B, 0x0029, 0x0027, 0x0025, 0x0023, 0x0009,
+};
+
+static const uint8_t dc9_vlc_lens[512] = {
+     5,  5,  6,  6,  6,  6,  6,  6,  6,  6,  6,  6,  7,  7,  7,  7,
+     7,  7,  7,  7,  7,  7,  7,  7,  7,  8,  8,  8,  8,  8,  8,  8,
+     8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,
+     8,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,
+     9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+    10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+    10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+    10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+     9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,
+     8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,
+     8,  8,  8,  8,  8,  8,  8,  8,  7,  7,  7,  7,  7,  7,  7,  7,
+     7,  7,  7,  7,  7,  6,  6,  6,  6,  6,  6,  6,  6,  6,  6,  5,
+};
+
+static const uint16_t dc10_vlc_bits[1024] = {
+    0x0014, 0x002A, 0x002C, 0x002E, 0x0064, 0x0066, 0x0068, 0x006A,
+    0x006C, 0x006E, 0x0070, 0x0072, 0x0074, 0x0076, 0x0078, 0x007A,
+    0x007C, 0x0040, 0x0042, 0x0044, 0x0046, 0x0048, 0x004A, 0x004C,
+    0x004E, 0x0050, 0x0052, 0x0054, 0x0056, 0x0058, 0x005A, 0x005C,
+    0x005E, 0x0000, 0x0002, 0x0004, 0x0006, 0x0008, 0x000A, 0x000C,
+    0x000E, 0x0010, 0x0012, 0x0014, 0x0016, 0x0018, 0x001A, 0x001C,
+    0x001E, 0x00C0, 0x00C2, 0x00C4, 0x00C6, 0x00C8, 0x00CA, 0x00CC,
+    0x00CE, 0x00D0, 0x00D2, 0x00D4, 0x00D6, 0x00D8, 0x00DA, 0x00DC,
+    0x00DE, 0x0040, 0x0042, 0x0044, 0x0046, 0x0048, 0x004A, 0x004C,
+    0x004E, 0x0050, 0x0052, 0x0054, 0x0056, 0x0058, 0x005A, 0x005C,
+    0x005E, 0x0060, 0x0062, 0x0064, 0x0066, 0x0068, 0x006A, 0x006C,
+    0x006E, 0x0070, 0x0072, 0x0074, 0x0076, 0x0078, 0x007A, 0x007C,
+    0x007E, 0x01C0, 0x01C2, 0x01C4, 0x01C6, 0x01C8, 0x01CA, 0x01CC,
+    0x01CE, 0x01D0, 0x01D2, 0x01D4, 0x01D6, 0x01D8, 0x01DA, 0x01DC,
+    0x01DE, 0x01E0, 0x01E2, 0x01E4, 0x01E6, 0x01E8, 0x01EA, 0x01EC,
+    0x01EE, 0x01F0, 0x01F2, 0x01F4, 0x01F6, 0x01F8, 0x01FA, 0x01FC,
+    0x01FE, 0x0400, 0x0402, 0x0404, 0x0406, 0x0408, 0x040A, 0x040C,
+    0x040E, 0x0410, 0x0412, 0x0414, 0x0416, 0x0418, 0x041A, 0x041C,
+    0x041E, 0x0420, 0x0422, 0x0424, 0x0426, 0x0428, 0x042A, 0x042C,
+    0x042E, 0x0430, 0x0432, 0x0434, 0x0436, 0x0438, 0x043A, 0x043C,
+    0x043E, 0x0440, 0x0442, 0x0444, 0x0446, 0x0448, 0x044A, 0x044C,
+    0x044E, 0x0450, 0x0452, 0x0454, 0x0456, 0x0458, 0x045A, 0x045C,
+    0x045E, 0x0460, 0x0462, 0x0464, 0x0466, 0x0468, 0x046A, 0x046C,
+    0x046E, 0x0470, 0x0472, 0x0474, 0x0476, 0x0478, 0x047A, 0x047C,
+    0x047E, 0x0C00, 0x0C02, 0x0C04, 0x0C06, 0x0C08, 0x0C0A, 0x0C0C,
+    0x0C0E, 0x0C10, 0x0C12, 0x0C14, 0x0C16, 0x0C18, 0x0C1A, 0x0C1C,
+    0x0C1E, 0x0C20, 0x0C22, 0x0C24, 0x0C26, 0x0C28, 0x0C2A, 0x0C2C,
+    0x0C2E, 0x0C30, 0x0C32, 0x0C34, 0x0C36, 0x0C38, 0x0C3A, 0x0C3C,
+    0x0C3E, 0x0C40, 0x0C42, 0x0C44, 0x0C46, 0x0C48, 0x0C4A, 0x0C4C,
+    0x0C4E, 0x0C50, 0x0C52, 0x0C54, 0x0C56, 0x0C58, 0x0C5A, 0x0C5C,
+    0x0C5E, 0x0C60, 0x0C62, 0x0C64, 0x0C66, 0x0C68, 0x0C6A, 0x0C6C,
+    0x0C6E, 0x0C70, 0x0C72, 0x0C74, 0x0C76, 0x0C78, 0x0C7A, 0x0C7C,
+    0x0C7E, 0x0900, 0x0902, 0x0904, 0x0906, 0x0908, 0x090A, 0x090C,
+    0x090E, 0x0910, 0x0912, 0x0914, 0x0916, 0x0918, 0x091A, 0x091C,
+    0x091E, 0x0920, 0x0922, 0x0924, 0x0926, 0x0928, 0x092A, 0x092C,
+    0x092E, 0x0930, 0x0932, 0x0934, 0x0936, 0x0938, 0x093A, 0x093C,
+    0x093E, 0x0940, 0x0942, 0x0944, 0x0946, 0x0948, 0x094A, 0x094C,
+    0x094E, 0x0950, 0x0952, 0x0954, 0x0956, 0x0958, 0x095A, 0x095C,
+    0x095E, 0x0960, 0x0962, 0x0964, 0x0966, 0x0968, 0x096A, 0x096C,
+    0x096E, 0x0970, 0x0972, 0x0974, 0x0976, 0x0978, 0x097A, 0x097C,
+    0x097E, 0x0980, 0x0982, 0x0984, 0x0986, 0x0988, 0x098A, 0x098C,
+    0x098E, 0x0990, 0x0992, 0x0994, 0x0996, 0x0998, 0x099A, 0x099C,
+    0x099E, 0x09A0, 0x09A2, 0x09A4, 0x09A6, 0x09A8, 0x09AA, 0x09AC,
+    0x09AE, 0x09B0, 0x09B2, 0x09B4, 0x09B6, 0x09B8, 0x09BA, 0x09BC,
+    0x09BE, 0x09C0, 0x09C2, 0x09C4, 0x09C6, 0x09C8, 0x09CA, 0x09CC,
+    0x09CE, 0x09D0, 0x09D2, 0x09D4, 0x09D6, 0x09D8, 0x09DA, 0x09DC,
+    0x09DE, 0x09E0, 0x09E2, 0x09E4, 0x09E6, 0x09E8, 0x09EA, 0x09EC,
+    0x09EE, 0x09F0, 0x09F2, 0x09F4, 0x09F6, 0x09F8, 0x09FA, 0x09FC,
+    0x09FE, 0x3F00, 0x3F02, 0x3F04, 0x3F06, 0x3F08, 0x3F0A, 0x3F0C,
+    0x3F0E, 0x3F10, 0x3F12, 0x3F14, 0x3F16, 0x3F18, 0x3F1A, 0x3F1C,
+    0x3F1E, 0x3F20, 0x3F22, 0x3F24, 0x3F26, 0x3F28, 0x3F2A, 0x3F2C,
+    0x3F2E, 0x3F30, 0x3F32, 0x3F34, 0x3F36, 0x3F38, 0x3F3A, 0x3F3C,
+    0x3F3E, 0x3F40, 0x3F42, 0x3F44, 0x3F46, 0x3F48, 0x3F4A, 0x3F4C,
+    0x3F4E, 0x3F50, 0x3F52, 0x3F54, 0x3F56, 0x3F58, 0x3F5A, 0x3F5C,
+    0x3F5E, 0x3F60, 0x3F62, 0x3F64, 0x3F66, 0x3F68, 0x3F6A, 0x3F6C,
+    0x3F6E, 0x3F70, 0x3F72, 0x3F74, 0x3F76, 0x3F78, 0x3F7A, 0x3F7C,
+    0x3F7E, 0x3F80, 0x3F82, 0x3F84, 0x3F86, 0x3F88, 0x3F8A, 0x3F8C,
+    0x3F8E, 0x3F90, 0x3F92, 0x3F94, 0x3F96, 0x3F98, 0x3F9A, 0x3F9C,
+    0x3F9E, 0x3FA0, 0x3FA2, 0x3FA4, 0x3FA6, 0x3FA8, 0x3FAA, 0x3FAC,
+    0x3FAE, 0x3FB0, 0x3FB2, 0x3FB4, 0x3FB6, 0x3FB8, 0x3FBA, 0x3FBC,
+    0x3FBE, 0x3FC0, 0x3FC2, 0x3FC4, 0x3FC6, 0x3FC8, 0x3FCA, 0x3FCC,
+    0x3FCE, 0x3FD0, 0x3FD2, 0x3FD4, 0x3FD6, 0x3FD8, 0x3FDA, 0x3FDC,
+    0x3FDE, 0x3FE0, 0x3FE2, 0x3FE4, 0x3FE6, 0x3FE8, 0x3FEA, 0x3FEC,
+    0x3FEE, 0x3FF0, 0x3FF2, 0x3FF4, 0x3FF6, 0x3FF8, 0x3FFA, 0x3FFC,
+    0x1FFF, 0x3FFD, 0x3FFB, 0x3FF9, 0x3FF7, 0x3FF5, 0x3FF3, 0x3FF1,
+    0x3FEF, 0x3FED, 0x3FEB, 0x3FE9, 0x3FE7, 0x3FE5, 0x3FE3, 0x3FE1,
+    0x3FDF, 0x3FDD, 0x3FDB, 0x3FD9, 0x3FD7, 0x3FD5, 0x3FD3, 0x3FD1,
+    0x3FCF, 0x3FCD, 0x3FCB, 0x3FC9, 0x3FC7, 0x3FC5, 0x3FC3, 0x3FC1,
+    0x3FBF, 0x3FBD, 0x3FBB, 0x3FB9, 0x3FB7, 0x3FB5, 0x3FB3, 0x3FB1,
+    0x3FAF, 0x3FAD, 0x3FAB, 0x3FA9, 0x3FA7, 0x3FA5, 0x3FA3, 0x3FA1,
+    0x3F9F, 0x3F9D, 0x3F9B, 0x3F99, 0x3F97, 0x3F95, 0x3F93, 0x3F91,
+    0x3F8F, 0x3F8D, 0x3F8B, 0x3F89, 0x3F87, 0x3F85, 0x3F83, 0x3F81,
+    0x3F7F, 0x3F7D, 0x3F7B, 0x3F79, 0x3F77, 0x3F75, 0x3F73, 0x3F71,
+    0x3F6F, 0x3F6D, 0x3F6B, 0x3F69, 0x3F67, 0x3F65, 0x3F63, 0x3F61,
+    0x3F5F, 0x3F5D, 0x3F5B, 0x3F59, 0x3F57, 0x3F55, 0x3F53, 0x3F51,
+    0x3F4F, 0x3F4D, 0x3F4B, 0x3F49, 0x3F47, 0x3F45, 0x3F43, 0x3F41,
+    0x3F3F, 0x3F3D, 0x3F3B, 0x3F39, 0x3F37, 0x3F35, 0x3F33, 0x3F31,
+    0x3F2F, 0x3F2D, 0x3F2B, 0x3F29, 0x3F27, 0x3F25, 0x3F23, 0x3F21,
+    0x3F1F, 0x3F1D, 0x3F1B, 0x3F19, 0x3F17, 0x3F15, 0x3F13, 0x3F11,
+    0x3F0F, 0x3F0D, 0x3F0B, 0x3F09, 0x3F07, 0x3F05, 0x3F03, 0x3F01,
+    0x09FF, 0x09FD, 0x09FB, 0x09F9, 0x09F7, 0x09F5, 0x09F3, 0x09F1,
+    0x09EF, 0x09ED, 0x09EB, 0x09E9, 0x09E7, 0x09E5, 0x09E3, 0x09E1,
+    0x09DF, 0x09DD, 0x09DB, 0x09D9, 0x09D7, 0x09D5, 0x09D3, 0x09D1,
+    0x09CF, 0x09CD, 0x09CB, 0x09C9, 0x09C7, 0x09C5, 0x09C3, 0x09C1,
+    0x09BF, 0x09BD, 0x09BB, 0x09B9, 0x09B7, 0x09B5, 0x09B3, 0x09B1,
+    0x09AF, 0x09AD, 0x09AB, 0x09A9, 0x09A7, 0x09A5, 0x09A3, 0x09A1,
+    0x099F, 0x099D, 0x099B, 0x0999, 0x0997, 0x0995, 0x0993, 0x0991,
+    0x098F, 0x098D, 0x098B, 0x0989, 0x0987, 0x0985, 0x0983, 0x0981,
+    0x097F, 0x097D, 0x097B, 0x0979, 0x0977, 0x0975, 0x0973, 0x0971,
+    0x096F, 0x096D, 0x096B, 0x0969, 0x0967, 0x0965, 0x0963, 0x0961,
+    0x095F, 0x095D, 0x095B, 0x0959, 0x0957, 0x0955, 0x0953, 0x0951,
+    0x094F, 0x094D, 0x094B, 0x0949, 0x0947, 0x0945, 0x0943, 0x0941,
+    0x093F, 0x093D, 0x093B, 0x0939, 0x0937, 0x0935, 0x0933, 0x0931,
+    0x092F, 0x092D, 0x092B, 0x0929, 0x0927, 0x0925, 0x0923, 0x0921,
+    0x091F, 0x091D, 0x091B, 0x0919, 0x0917, 0x0915, 0x0913, 0x0911,
+    0x090F, 0x090D, 0x090B, 0x0909, 0x0907, 0x0905, 0x0903, 0x0901,
+    0x0C7F, 0x0C7D, 0x0C7B, 0x0C79, 0x0C77, 0x0C75, 0x0C73, 0x0C71,
+    0x0C6F, 0x0C6D, 0x0C6B, 0x0C69, 0x0C67, 0x0C65, 0x0C63, 0x0C61,
+    0x0C5F, 0x0C5D, 0x0C5B, 0x0C59, 0x0C57, 0x0C55, 0x0C53, 0x0C51,
+    0x0C4F, 0x0C4D, 0x0C4B, 0x0C49, 0x0C47, 0x0C45, 0x0C43, 0x0C41,
+    0x0C3F, 0x0C3D, 0x0C3B, 0x0C39, 0x0C37, 0x0C35, 0x0C33, 0x0C31,
+    0x0C2F, 0x0C2D, 0x0C2B, 0x0C29, 0x0C27, 0x0C25, 0x0C23, 0x0C21,
+    0x0C1F, 0x0C1D, 0x0C1B, 0x0C19, 0x0C17, 0x0C15, 0x0C13, 0x0C11,
+    0x0C0F, 0x0C0D, 0x0C0B, 0x0C09, 0x0C07, 0x0C05, 0x0C03, 0x0C01,
+    0x047F, 0x047D, 0x047B, 0x0479, 0x0477, 0x0475, 0x0473, 0x0471,
+    0x046F, 0x046D, 0x046B, 0x0469, 0x0467, 0x0465, 0x0463, 0x0461,
+    0x045F, 0x045D, 0x045B, 0x0459, 0x0457, 0x0455, 0x0453, 0x0451,
+    0x044F, 0x044D, 0x044B, 0x0449, 0x0447, 0x0445, 0x0443, 0x0441,
+    0x043F, 0x043D, 0x043B, 0x0439, 0x0437, 0x0435, 0x0433, 0x0431,
+    0x042F, 0x042D, 0x042B, 0x0429, 0x0427, 0x0425, 0x0423, 0x0421,
+    0x041F, 0x041D, 0x041B, 0x0419, 0x0417, 0x0415, 0x0413, 0x0411,
+    0x040F, 0x040D, 0x040B, 0x0409, 0x0407, 0x0405, 0x0403, 0x0401,
+    0x01FF, 0x01FD, 0x01FB, 0x01F9, 0x01F7, 0x01F5, 0x01F3, 0x01F1,
+    0x01EF, 0x01ED, 0x01EB, 0x01E9, 0x01E7, 0x01E5, 0x01E3, 0x01E1,
+    0x01DF, 0x01DD, 0x01DB, 0x01D9, 0x01D7, 0x01D5, 0x01D3, 0x01D1,
+    0x01CF, 0x01CD, 0x01CB, 0x01C9, 0x01C7, 0x01C5, 0x01C3, 0x01C1,
+    0x007F, 0x007D, 0x007B, 0x0079, 0x0077, 0x0075, 0x0073, 0x0071,
+    0x006F, 0x006D, 0x006B, 0x0069, 0x0067, 0x0065, 0x0063, 0x0061,
+    0x005F, 0x005D, 0x005B, 0x0059, 0x0057, 0x0055, 0x0053, 0x0051,
+    0x004F, 0x004D, 0x004B, 0x0049, 0x0047, 0x0045, 0x0043, 0x0041,
+    0x00DF, 0x00DD, 0x00DB, 0x00D9, 0x00D7, 0x00D5, 0x00D3, 0x00D1,
+    0x00CF, 0x00CD, 0x00CB, 0x00C9, 0x00C7, 0x00C5, 0x00C3, 0x00C1,
+    0x001F, 0x001D, 0x001B, 0x0019, 0x0017, 0x0015, 0x0013, 0x0011,
+    0x000F, 0x000D, 0x000B, 0x0009, 0x0007, 0x0005, 0x0003, 0x0001,
+    0x005F, 0x005D, 0x005B, 0x0059, 0x0057, 0x0055, 0x0053, 0x0051,
+    0x004F, 0x004D, 0x004B, 0x0049, 0x0047, 0x0045, 0x0043, 0x0041,
+    0x007D, 0x007B, 0x0079, 0x0077, 0x0075, 0x0073, 0x0071, 0x006F,
+    0x006D, 0x006B, 0x0069, 0x0067, 0x0065, 0x002F, 0x002D, 0x002B,
+};
+
+static const uint8_t dc10_vlc_lens[1024] = {
+     5,  6,  6,  6,  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,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,
+     8,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,
+     9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,
+     9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,
+     9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+    10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+    10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+    10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+     9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,
+     9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,
+     9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,
+     8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,
+     8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,
+     7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  6,  6,  6,
+};
+
+static const uint16_t dc11_vlc_bits[2048] = {
+    0x0032, 0x0066, 0x0068, 0x006A, 0x006C, 0x006E, 0x0070, 0x0072,
+    0x0074, 0x00F0, 0x00F2, 0x00F4, 0x00F6, 0x00F8, 0x00FA, 0x00FC,
+    0x00FE, 0x0040, 0x0042, 0x0044, 0x0046, 0x0048, 0x004A, 0x004C,
+    0x004E, 0x0050, 0x0052, 0x0054, 0x0056, 0x0058, 0x005A, 0x005C,
+    0x005E, 0x00C0, 0x00C2, 0x00C4, 0x00C6, 0x00C8, 0x00CA, 0x00CC,
+    0x00CE, 0x00D0, 0x00D2, 0x00D4, 0x00D6, 0x00D8, 0x00DA, 0x00DC,
+    0x00DE, 0x00E0, 0x00E2, 0x00E4, 0x00E6, 0x00E8, 0x00EA, 0x00EC,
+    0x00EE, 0x00F0, 0x00F2, 0x00F4, 0x00F6, 0x00F8, 0x00FA, 0x00FC,
+    0x00FE, 0x0000, 0x0002, 0x0004, 0x0006, 0x0008, 0x000A, 0x000C,
+    0x000E, 0x0010, 0x0012, 0x0014, 0x0016, 0x0018, 0x001A, 0x001C,
+    0x001E, 0x0020, 0x0022, 0x0024, 0x0026, 0x0028, 0x002A, 0x002C,
+    0x002E, 0x0030, 0x0032, 0x0034, 0x0036, 0x0038, 0x003A, 0x003C,
+    0x003E, 0x0200, 0x0202, 0x0204, 0x0206, 0x0208, 0x020A, 0x020C,
+    0x020E, 0x0210, 0x0212, 0x0214, 0x0216, 0x0218, 0x021A, 0x021C,
+    0x021E, 0x0220, 0x0222, 0x0224, 0x0226, 0x0228, 0x022A, 0x022C,
+    0x022E, 0x0230, 0x0232, 0x0234, 0x0236, 0x0238, 0x023A, 0x023C,
+    0x023E, 0x0080, 0x0082, 0x0084, 0x0086, 0x0088, 0x008A, 0x008C,
+    0x008E, 0x0090, 0x0092, 0x0094, 0x0096, 0x0098, 0x009A, 0x009C,
+    0x009E, 0x00A0, 0x00A2, 0x00A4, 0x00A6, 0x00A8, 0x00AA, 0x00AC,
+    0x00AE, 0x00B0, 0x00B2, 0x00B4, 0x00B6, 0x00B8, 0x00BA, 0x00BC,
+    0x00BE, 0x00C0, 0x00C2, 0x00C4, 0x00C6, 0x00C8, 0x00CA, 0x00CC,
+    0x00CE, 0x00D0, 0x00D2, 0x00D4, 0x00D6, 0x00D8, 0x00DA, 0x00DC,
+    0x00DE, 0x00E0, 0x00E2, 0x00E4, 0x00E6, 0x00E8, 0x00EA, 0x00EC,
+    0x00EE, 0x00F0, 0x00F2, 0x00F4, 0x00F6, 0x00F8, 0x00FA, 0x00FC,
+    0x00FE, 0x0480, 0x0482, 0x0484, 0x0486, 0x0488, 0x048A, 0x048C,
+    0x048E, 0x0490, 0x0492, 0x0494, 0x0496, 0x0498, 0x049A, 0x049C,
+    0x049E, 0x04A0, 0x04A2, 0x04A4, 0x04A6, 0x04A8, 0x04AA, 0x04AC,
+    0x04AE, 0x04B0, 0x04B2, 0x04B4, 0x04B6, 0x04B8, 0x04BA, 0x04BC,
+    0x04BE, 0x04C0, 0x04C2, 0x04C4, 0x04C6, 0x04C8, 0x04CA, 0x04CC,
+    0x04CE, 0x04D0, 0x04D2, 0x04D4, 0x04D6, 0x04D8, 0x04DA, 0x04DC,
+    0x04DE, 0x04E0, 0x04E2, 0x04E4, 0x04E6, 0x04E8, 0x04EA, 0x04EC,
+    0x04EE, 0x04F0, 0x04F2, 0x04F4, 0x04F6, 0x04F8, 0x04FA, 0x04FC,
+    0x04FE, 0x0A00, 0x0A02, 0x0A04, 0x0A06, 0x0A08, 0x0A0A, 0x0A0C,
+    0x0A0E, 0x0A10, 0x0A12, 0x0A14, 0x0A16, 0x0A18, 0x0A1A, 0x0A1C,
+    0x0A1E, 0x0A20, 0x0A22, 0x0A24, 0x0A26, 0x0A28, 0x0A2A, 0x0A2C,
+    0x0A2E, 0x0A30, 0x0A32, 0x0A34, 0x0A36, 0x0A38, 0x0A3A, 0x0A3C,
+    0x0A3E, 0x0A40, 0x0A42, 0x0A44, 0x0A46, 0x0A48, 0x0A4A, 0x0A4C,
+    0x0A4E, 0x0A50, 0x0A52, 0x0A54, 0x0A56, 0x0A58, 0x0A5A, 0x0A5C,
+    0x0A5E, 0x0A60, 0x0A62, 0x0A64, 0x0A66, 0x0A68, 0x0A6A, 0x0A6C,
+    0x0A6E, 0x0A70, 0x0A72, 0x0A74, 0x0A76, 0x0A78, 0x0A7A, 0x0A7C,
+    0x0A7E, 0x0A80, 0x0A82, 0x0A84, 0x0A86, 0x0A88, 0x0A8A, 0x0A8C,
+    0x0A8E, 0x0A90, 0x0A92, 0x0A94, 0x0A96, 0x0A98, 0x0A9A, 0x0A9C,
+    0x0A9E, 0x0AA0, 0x0AA2, 0x0AA4, 0x0AA6, 0x0AA8, 0x0AAA, 0x0AAC,
+    0x0AAE, 0x0AB0, 0x0AB2, 0x0AB4, 0x0AB6, 0x0AB8, 0x0ABA, 0x0ABC,
+    0x0ABE, 0x0AC0, 0x0AC2, 0x0AC4, 0x0AC6, 0x0AC8, 0x0ACA, 0x0ACC,
+    0x0ACE, 0x0AD0, 0x0AD2, 0x0AD4, 0x0AD6, 0x0AD8, 0x0ADA, 0x0ADC,
+    0x0ADE, 0x0AE0, 0x0AE2, 0x0AE4, 0x0AE6, 0x0AE8, 0x0AEA, 0x0AEC,
+    0x0AEE, 0x0AF0, 0x0AF2, 0x0AF4, 0x0AF6, 0x0AF8, 0x0AFA, 0x0AFC,
+    0x0AFE, 0x1800, 0x1802, 0x1804, 0x1806, 0x1808, 0x180A, 0x180C,
+    0x180E, 0x1810, 0x1812, 0x1814, 0x1816, 0x1818, 0x181A, 0x181C,
+    0x181E, 0x1820, 0x1822, 0x1824, 0x1826, 0x1828, 0x182A, 0x182C,
+    0x182E, 0x1830, 0x1832, 0x1834, 0x1836, 0x1838, 0x183A, 0x183C,
+    0x183E, 0x1840, 0x1842, 0x1844, 0x1846, 0x1848, 0x184A, 0x184C,
+    0x184E, 0x1850, 0x1852, 0x1854, 0x1856, 0x1858, 0x185A, 0x185C,
+    0x185E, 0x1860, 0x1862, 0x1864, 0x1866, 0x1868, 0x186A, 0x186C,
+    0x186E, 0x1870, 0x1872, 0x1874, 0x1876, 0x1878, 0x187A, 0x187C,
+    0x187E, 0x1880, 0x1882, 0x1884, 0x1886, 0x1888, 0x188A, 0x188C,
+    0x188E, 0x1890, 0x1892, 0x1894, 0x1896, 0x1898, 0x189A, 0x189C,
+    0x189E, 0x18A0, 0x18A2, 0x18A4, 0x18A6, 0x18A8, 0x18AA, 0x18AC,
+    0x18AE, 0x18B0, 0x18B2, 0x18B4, 0x18B6, 0x18B8, 0x18BA, 0x18BC,
+    0x18BE, 0x18C0, 0x18C2, 0x18C4, 0x18C6, 0x18C8, 0x18CA, 0x18CC,
+    0x18CE, 0x18D0, 0x18D2, 0x18D4, 0x18D6, 0x18D8, 0x18DA, 0x18DC,
+    0x18DE, 0x18E0, 0x18E2, 0x18E4, 0x18E6, 0x18E8, 0x18EA, 0x18EC,
+    0x18EE, 0x18F0, 0x18F2, 0x18F4, 0x18F6, 0x18F8, 0x18FA, 0x18FC,
+    0x18FE, 0x1600, 0x1602, 0x1604, 0x1606, 0x1608, 0x160A, 0x160C,
+    0x160E, 0x1610, 0x1612, 0x1614, 0x1616, 0x1618, 0x161A, 0x161C,
+    0x161E, 0x1620, 0x1622, 0x1624, 0x1626, 0x1628, 0x162A, 0x162C,
+    0x162E, 0x1630, 0x1632, 0x1634, 0x1636, 0x1638, 0x163A, 0x163C,
+    0x163E, 0x1640, 0x1642, 0x1644, 0x1646, 0x1648, 0x164A, 0x164C,
+    0x164E, 0x1650, 0x1652, 0x1654, 0x1656, 0x1658, 0x165A, 0x165C,
+    0x165E, 0x1660, 0x1662, 0x1664, 0x1666, 0x1668, 0x166A, 0x166C,
+    0x166E, 0x1670, 0x1672, 0x1674, 0x1676, 0x1678, 0x167A, 0x167C,
+    0x167E, 0x1680, 0x1682, 0x1684, 0x1686, 0x1688, 0x168A, 0x168C,
+    0x168E, 0x1690, 0x1692, 0x1694, 0x1696, 0x1698, 0x169A, 0x169C,
+    0x169E, 0x16A0, 0x16A2, 0x16A4, 0x16A6, 0x16A8, 0x16AA, 0x16AC,
+    0x16AE, 0x16B0, 0x16B2, 0x16B4, 0x16B6, 0x16B8, 0x16BA, 0x16BC,
+    0x16BE, 0x16C0, 0x16C2, 0x16C4, 0x16C6, 0x16C8, 0x16CA, 0x16CC,
+    0x16CE, 0x16D0, 0x16D2, 0x16D4, 0x16D6, 0x16D8, 0x16DA, 0x16DC,
+    0x16DE, 0x16E0, 0x16E2, 0x16E4, 0x16E6, 0x16E8, 0x16EA, 0x16EC,
+    0x16EE, 0x16F0, 0x16F2, 0x16F4, 0x16F6, 0x16F8, 0x16FA, 0x16FC,
+    0x16FE, 0x1700, 0x1702, 0x1704, 0x1706, 0x1708, 0x170A, 0x170C,
+    0x170E, 0x1710, 0x1712, 0x1714, 0x1716, 0x1718, 0x171A, 0x171C,
+    0x171E, 0x1720, 0x1722, 0x1724, 0x1726, 0x1728, 0x172A, 0x172C,
+    0x172E, 0x1730, 0x1732, 0x1734, 0x1736, 0x1738, 0x173A, 0x173C,
+    0x173E, 0x1740, 0x1742, 0x1744, 0x1746, 0x1748, 0x174A, 0x174C,
+    0x174E, 0x1750, 0x1752, 0x1754, 0x1756, 0x1758, 0x175A, 0x175C,
+    0x175E, 0x1760, 0x1762, 0x1764, 0x1766, 0x1768, 0x176A, 0x176C,
+    0x176E, 0x1770, 0x1772, 0x1774, 0x1776, 0x1778, 0x177A, 0x177C,
+    0x177E, 0x1780, 0x1782, 0x1784, 0x1786, 0x1788, 0x178A, 0x178C,
+    0x178E, 0x1790, 0x1792, 0x1794, 0x1796, 0x1798, 0x179A, 0x179C,
+    0x179E, 0x17A0, 0x17A2, 0x17A4, 0x17A6, 0x17A8, 0x17AA, 0x17AC,
+    0x17AE, 0x17B0, 0x17B2, 0x17B4, 0x17B6, 0x17B8, 0x17BA, 0x17BC,
+    0x17BE, 0x17C0, 0x17C2, 0x17C4, 0x17C6, 0x17C8, 0x17CA, 0x17CC,
+    0x17CE, 0x17D0, 0x17D2, 0x17D4, 0x17D6, 0x17D8, 0x17DA, 0x17DC,
+    0x17DE, 0x17E0, 0x17E2, 0x17E4, 0x17E6, 0x17E8, 0x17EA, 0x17EC,
+    0x17EE, 0x17F0, 0x17F2, 0x17F4, 0x17F6, 0x17F8, 0x17FA, 0x17FC,
+    0x17FE, 0x7600, 0x7602, 0x7604, 0x7606, 0x7608, 0x760A, 0x760C,
+    0x760E, 0x7610, 0x7612, 0x7614, 0x7616, 0x7618, 0x761A, 0x761C,
+    0x761E, 0x7620, 0x7622, 0x7624, 0x7626, 0x7628, 0x762A, 0x762C,
+    0x762E, 0x7630, 0x7632, 0x7634, 0x7636, 0x7638, 0x763A, 0x763C,
+    0x763E, 0x7640, 0x7642, 0x7644, 0x7646, 0x7648, 0x764A, 0x764C,
+    0x764E, 0x7650, 0x7652, 0x7654, 0x7656, 0x7658, 0x765A, 0x765C,
+    0x765E, 0x7660, 0x7662, 0x7664, 0x7666, 0x7668, 0x766A, 0x766C,
+    0x766E, 0x7670, 0x7672, 0x7674, 0x7676, 0x7678, 0x767A, 0x767C,
+    0x767E, 0x7680, 0x7682, 0x7684, 0x7686, 0x7688, 0x768A, 0x768C,
+    0x768E, 0x7690, 0x7692, 0x7694, 0x7696, 0x7698, 0x769A, 0x769C,
+    0x769E, 0x76A0, 0x76A2, 0x76A4, 0x76A6, 0x76A8, 0x76AA, 0x76AC,
+    0x76AE, 0x76B0, 0x76B2, 0x76B4, 0x76B6, 0x76B8, 0x76BA, 0x76BC,
+    0x76BE, 0x76C0, 0x76C2, 0x76C4, 0x76C6, 0x76C8, 0x76CA, 0x76CC,
+    0x76CE, 0x76D0, 0x76D2, 0x76D4, 0x76D6, 0x76D8, 0x76DA, 0x76DC,
+    0x76DE, 0x76E0, 0x76E2, 0x76E4, 0x76E6, 0x76E8, 0x76EA, 0x76EC,
+    0x76EE, 0x76F0, 0x76F2, 0x76F4, 0x76F6, 0x76F8, 0x76FA, 0x76FC,
+    0x76FE, 0x7700, 0x7702, 0x7704, 0x7706, 0x7708, 0x770A, 0x770C,
+    0x770E, 0x7710, 0x7712, 0x7714, 0x7716, 0x7718, 0x771A, 0x771C,
+    0x771E, 0x7720, 0x7722, 0x7724, 0x7726, 0x7728, 0x772A, 0x772C,
+    0x772E, 0x7730, 0x7732, 0x7734, 0x7736, 0x7738, 0x773A, 0x773C,
+    0x773E, 0x7740, 0x7742, 0x7744, 0x7746, 0x7748, 0x774A, 0x774C,
+    0x774E, 0x7750, 0x7752, 0x7754, 0x7756, 0x7758, 0x775A, 0x775C,
+    0x775E, 0x7760, 0x7762, 0x7764, 0x7766, 0x7768, 0x776A, 0x776C,
+    0x776E, 0x7770, 0x7772, 0x7774, 0x7776, 0x7778, 0x777A, 0x777C,
+    0x777E, 0x7780, 0x7782, 0x7784, 0x7786, 0x7788, 0x778A, 0x778C,
+    0x778E, 0x7790, 0x7792, 0x7794, 0x7796, 0x7798, 0x779A, 0x779C,
+    0x779E, 0x77A0, 0x77A2, 0x77A4, 0x77A6, 0x77A8, 0x77AA, 0x77AC,
+    0x77AE, 0x77B0, 0x77B2, 0x77B4, 0x77B6, 0x77B8, 0x77BA, 0x77BC,
+    0x77BE, 0x77C0, 0x77C2, 0x77C4, 0x77C6, 0x77C8, 0x77CA, 0x77CC,
+    0x77CE, 0x77D0, 0x77D2, 0x77D4, 0x77D6, 0x77D8, 0x77DA, 0x77DC,
+    0x77DE, 0x77E0, 0x77E2, 0x77E4, 0x77E6, 0x77E8, 0x77EA, 0x77EC,
+    0x77EE, 0x77F0, 0x77F2, 0x77F4, 0x77F6, 0x77F8, 0x77FA, 0x77FC,
+    0x3BFF, 0x77FD, 0x77FB, 0x77F9, 0x77F7, 0x77F5, 0x77F3, 0x77F1,
+    0x77EF, 0x77ED, 0x77EB, 0x77E9, 0x77E7, 0x77E5, 0x77E3, 0x77E1,
+    0x77DF, 0x77DD, 0x77DB, 0x77D9, 0x77D7, 0x77D5, 0x77D3, 0x77D1,
+    0x77CF, 0x77CD, 0x77CB, 0x77C9, 0x77C7, 0x77C5, 0x77C3, 0x77C1,
+    0x77BF, 0x77BD, 0x77BB, 0x77B9, 0x77B7, 0x77B5, 0x77B3, 0x77B1,
+    0x77AF, 0x77AD, 0x77AB, 0x77A9, 0x77A7, 0x77A5, 0x77A3, 0x77A1,
+    0x779F, 0x779D, 0x779B, 0x7799, 0x7797, 0x7795, 0x7793, 0x7791,
+    0x778F, 0x778D, 0x778B, 0x7789, 0x7787, 0x7785, 0x7783, 0x7781,
+    0x777F, 0x777D, 0x777B, 0x7779, 0x7777, 0x7775, 0x7773, 0x7771,
+    0x776F, 0x776D, 0x776B, 0x7769, 0x7767, 0x7765, 0x7763, 0x7761,
+    0x775F, 0x775D, 0x775B, 0x7759, 0x7757, 0x7755, 0x7753, 0x7751,
+    0x774F, 0x774D, 0x774B, 0x7749, 0x7747, 0x7745, 0x7743, 0x7741,
+    0x773F, 0x773D, 0x773B, 0x7739, 0x7737, 0x7735, 0x7733, 0x7731,
+    0x772F, 0x772D, 0x772B, 0x7729, 0x7727, 0x7725, 0x7723, 0x7721,
+    0x771F, 0x771D, 0x771B, 0x7719, 0x7717, 0x7715, 0x7713, 0x7711,
+    0x770F, 0x770D, 0x770B, 0x7709, 0x7707, 0x7705, 0x7703, 0x7701,
+    0x76FF, 0x76FD, 0x76FB, 0x76F9, 0x76F7, 0x76F5, 0x76F3, 0x76F1,
+    0x76EF, 0x76ED, 0x76EB, 0x76E9, 0x76E7, 0x76E5, 0x76E3, 0x76E1,
+    0x76DF, 0x76DD, 0x76DB, 0x76D9, 0x76D7, 0x76D5, 0x76D3, 0x76D1,
+    0x76CF, 0x76CD, 0x76CB, 0x76C9, 0x76C7, 0x76C5, 0x76C3, 0x76C1,
+    0x76BF, 0x76BD, 0x76BB, 0x76B9, 0x76B7, 0x76B5, 0x76B3, 0x76B1,
+    0x76AF, 0x76AD, 0x76AB, 0x76A9, 0x76A7, 0x76A5, 0x76A3, 0x76A1,
+    0x769F, 0x769D, 0x769B, 0x7699, 0x7697, 0x7695, 0x7693, 0x7691,
+    0x768F, 0x768D, 0x768B, 0x7689, 0x7687, 0x7685, 0x7683, 0x7681,
+    0x767F, 0x767D, 0x767B, 0x7679, 0x7677, 0x7675, 0x7673, 0x7671,
+    0x766F, 0x766D, 0x766B, 0x7669, 0x7667, 0x7665, 0x7663, 0x7661,
+    0x765F, 0x765D, 0x765B, 0x7659, 0x7657, 0x7655, 0x7653, 0x7651,
+    0x764F, 0x764D, 0x764B, 0x7649, 0x7647, 0x7645, 0x7643, 0x7641,
+    0x763F, 0x763D, 0x763B, 0x7639, 0x7637, 0x7635, 0x7633, 0x7631,
+    0x762F, 0x762D, 0x762B, 0x7629, 0x7627, 0x7625, 0x7623, 0x7621,
+    0x761F, 0x761D, 0x761B, 0x7619, 0x7617, 0x7615, 0x7613, 0x7611,
+    0x760F, 0x760D, 0x760B, 0x7609, 0x7607, 0x7605, 0x7603, 0x7601,
+    0x17FF, 0x17FD, 0x17FB, 0x17F9, 0x17F7, 0x17F5, 0x17F3, 0x17F1,
+    0x17EF, 0x17ED, 0x17EB, 0x17E9, 0x17E7, 0x17E5, 0x17E3, 0x17E1,
+    0x17DF, 0x17DD, 0x17DB, 0x17D9, 0x17D7, 0x17D5, 0x17D3, 0x17D1,
+    0x17CF, 0x17CD, 0x17CB, 0x17C9, 0x17C7, 0x17C5, 0x17C3, 0x17C1,
+    0x17BF, 0x17BD, 0x17BB, 0x17B9, 0x17B7, 0x17B5, 0x17B3, 0x17B1,
+    0x17AF, 0x17AD, 0x17AB, 0x17A9, 0x17A7, 0x17A5, 0x17A3, 0x17A1,
+    0x179F, 0x179D, 0x179B, 0x1799, 0x1797, 0x1795, 0x1793, 0x1791,
+    0x178F, 0x178D, 0x178B, 0x1789, 0x1787, 0x1785, 0x1783, 0x1781,
+    0x177F, 0x177D, 0x177B, 0x1779, 0x1777, 0x1775, 0x1773, 0x1771,
+    0x176F, 0x176D, 0x176B, 0x1769, 0x1767, 0x1765, 0x1763, 0x1761,
+    0x175F, 0x175D, 0x175B, 0x1759, 0x1757, 0x1755, 0x1753, 0x1751,
+    0x174F, 0x174D, 0x174B, 0x1749, 0x1747, 0x1745, 0x1743, 0x1741,
+    0x173F, 0x173D, 0x173B, 0x1739, 0x1737, 0x1735, 0x1733, 0x1731,
+    0x172F, 0x172D, 0x172B, 0x1729, 0x1727, 0x1725, 0x1723, 0x1721,
+    0x171F, 0x171D, 0x171B, 0x1719, 0x1717, 0x1715, 0x1713, 0x1711,
+    0x170F, 0x170D, 0x170B, 0x1709, 0x1707, 0x1705, 0x1703, 0x1701,
+    0x16FF, 0x16FD, 0x16FB, 0x16F9, 0x16F7, 0x16F5, 0x16F3, 0x16F1,
+    0x16EF, 0x16ED, 0x16EB, 0x16E9, 0x16E7, 0x16E5, 0x16E3, 0x16E1,
+    0x16DF, 0x16DD, 0x16DB, 0x16D9, 0x16D7, 0x16D5, 0x16D3, 0x16D1,
+    0x16CF, 0x16CD, 0x16CB, 0x16C9, 0x16C7, 0x16C5, 0x16C3, 0x16C1,
+    0x16BF, 0x16BD, 0x16BB, 0x16B9, 0x16B7, 0x16B5, 0x16B3, 0x16B1,
+    0x16AF, 0x16AD, 0x16AB, 0x16A9, 0x16A7, 0x16A5, 0x16A3, 0x16A1,
+    0x169F, 0x169D, 0x169B, 0x1699, 0x1697, 0x1695, 0x1693, 0x1691,
+    0x168F, 0x168D, 0x168B, 0x1689, 0x1687, 0x1685, 0x1683, 0x1681,
+    0x167F, 0x167D, 0x167B, 0x1679, 0x1677, 0x1675, 0x1673, 0x1671,
+    0x166F, 0x166D, 0x166B, 0x1669, 0x1667, 0x1665, 0x1663, 0x1661,
+    0x165F, 0x165D, 0x165B, 0x1659, 0x1657, 0x1655, 0x1653, 0x1651,
+    0x164F, 0x164D, 0x164B, 0x1649, 0x1647, 0x1645, 0x1643, 0x1641,
+    0x163F, 0x163D, 0x163B, 0x1639, 0x1637, 0x1635, 0x1633, 0x1631,
+    0x162F, 0x162D, 0x162B, 0x1629, 0x1627, 0x1625, 0x1623, 0x1621,
+    0x161F, 0x161D, 0x161B, 0x1619, 0x1617, 0x1615, 0x1613, 0x1611,
+    0x160F, 0x160D, 0x160B, 0x1609, 0x1607, 0x1605, 0x1603, 0x1601,
+    0x18FF, 0x18FD, 0x18FB, 0x18F9, 0x18F7, 0x18F5, 0x18F3, 0x18F1,
+    0x18EF, 0x18ED, 0x18EB, 0x18E9, 0x18E7, 0x18E5, 0x18E3, 0x18E1,
+    0x18DF, 0x18DD, 0x18DB, 0x18D9, 0x18D7, 0x18D5, 0x18D3, 0x18D1,
+    0x18CF, 0x18CD, 0x18CB, 0x18C9, 0x18C7, 0x18C5, 0x18C3, 0x18C1,
+    0x18BF, 0x18BD, 0x18BB, 0x18B9, 0x18B7, 0x18B5, 0x18B3, 0x18B1,
+    0x18AF, 0x18AD, 0x18AB, 0x18A9, 0x18A7, 0x18A5, 0x18A3, 0x18A1,
+    0x189F, 0x189D, 0x189B, 0x1899, 0x1897, 0x1895, 0x1893, 0x1891,
+    0x188F, 0x188D, 0x188B, 0x1889, 0x1887, 0x1885, 0x1883, 0x1881,
+    0x187F, 0x187D, 0x187B, 0x1879, 0x1877, 0x1875, 0x1873, 0x1871,
+    0x186F, 0x186D, 0x186B, 0x1869, 0x1867, 0x1865, 0x1863, 0x1861,
+    0x185F, 0x185D, 0x185B, 0x1859, 0x1857, 0x1855, 0x1853, 0x1851,
+    0x184F, 0x184D, 0x184B, 0x1849, 0x1847, 0x1845, 0x1843, 0x1841,
+    0x183F, 0x183D, 0x183B, 0x1839, 0x1837, 0x1835, 0x1833, 0x1831,
+    0x182F, 0x182D, 0x182B, 0x1829, 0x1827, 0x1825, 0x1823, 0x1821,
+    0x181F, 0x181D, 0x181B, 0x1819, 0x1817, 0x1815, 0x1813, 0x1811,
+    0x180F, 0x180D, 0x180B, 0x1809, 0x1807, 0x1805, 0x1803, 0x1801,
+    0x0AFF, 0x0AFD, 0x0AFB, 0x0AF9, 0x0AF7, 0x0AF5, 0x0AF3, 0x0AF1,
+    0x0AEF, 0x0AED, 0x0AEB, 0x0AE9, 0x0AE7, 0x0AE5, 0x0AE3, 0x0AE1,
+    0x0ADF, 0x0ADD, 0x0ADB, 0x0AD9, 0x0AD7, 0x0AD5, 0x0AD3, 0x0AD1,
+    0x0ACF, 0x0ACD, 0x0ACB, 0x0AC9, 0x0AC7, 0x0AC5, 0x0AC3, 0x0AC1,
+    0x0ABF, 0x0ABD, 0x0ABB, 0x0AB9, 0x0AB7, 0x0AB5, 0x0AB3, 0x0AB1,
+    0x0AAF, 0x0AAD, 0x0AAB, 0x0AA9, 0x0AA7, 0x0AA5, 0x0AA3, 0x0AA1,
+    0x0A9F, 0x0A9D, 0x0A9B, 0x0A99, 0x0A97, 0x0A95, 0x0A93, 0x0A91,
+    0x0A8F, 0x0A8D, 0x0A8B, 0x0A89, 0x0A87, 0x0A85, 0x0A83, 0x0A81,
+    0x0A7F, 0x0A7D, 0x0A7B, 0x0A79, 0x0A77, 0x0A75, 0x0A73, 0x0A71,
+    0x0A6F, 0x0A6D, 0x0A6B, 0x0A69, 0x0A67, 0x0A65, 0x0A63, 0x0A61,
+    0x0A5F, 0x0A5D, 0x0A5B, 0x0A59, 0x0A57, 0x0A55, 0x0A53, 0x0A51,
+    0x0A4F, 0x0A4D, 0x0A4B, 0x0A49, 0x0A47, 0x0A45, 0x0A43, 0x0A41,
+    0x0A3F, 0x0A3D, 0x0A3B, 0x0A39, 0x0A37, 0x0A35, 0x0A33, 0x0A31,
+    0x0A2F, 0x0A2D, 0x0A2B, 0x0A29, 0x0A27, 0x0A25, 0x0A23, 0x0A21,
+    0x0A1F, 0x0A1D, 0x0A1B, 0x0A19, 0x0A17, 0x0A15, 0x0A13, 0x0A11,
+    0x0A0F, 0x0A0D, 0x0A0B, 0x0A09, 0x0A07, 0x0A05, 0x0A03, 0x0A01,
+    0x04FF, 0x04FD, 0x04FB, 0x04F9, 0x04F7, 0x04F5, 0x04F3, 0x04F1,
+    0x04EF, 0x04ED, 0x04EB, 0x04E9, 0x04E7, 0x04E5, 0x04E3, 0x04E1,
+    0x04DF, 0x04DD, 0x04DB, 0x04D9, 0x04D7, 0x04D5, 0x04D3, 0x04D1,
+    0x04CF, 0x04CD, 0x04CB, 0x04C9, 0x04C7, 0x04C5, 0x04C3, 0x04C1,
+    0x04BF, 0x04BD, 0x04BB, 0x04B9, 0x04B7, 0x04B5, 0x04B3, 0x04B1,
+    0x04AF, 0x04AD, 0x04AB, 0x04A9, 0x04A7, 0x04A5, 0x04A3, 0x04A1,
+    0x049F, 0x049D, 0x049B, 0x0499, 0x0497, 0x0495, 0x0493, 0x0491,
+    0x048F, 0x048D, 0x048B, 0x0489, 0x0487, 0x0485, 0x0483, 0x0481,
+    0x00FF, 0x00FD, 0x00FB, 0x00F9, 0x00F7, 0x00F5, 0x00F3, 0x00F1,
+    0x00EF, 0x00ED, 0x00EB, 0x00E9, 0x00E7, 0x00E5, 0x00E3, 0x00E1,
+    0x00DF, 0x00DD, 0x00DB, 0x00D9, 0x00D7, 0x00D5, 0x00D3, 0x00D1,
+    0x00CF, 0x00CD, 0x00CB, 0x00C9, 0x00C7, 0x00C5, 0x00C3, 0x00C1,
+    0x00BF, 0x00BD, 0x00BB, 0x00B9, 0x00B7, 0x00B5, 0x00B3, 0x00B1,
+    0x00AF, 0x00AD, 0x00AB, 0x00A9, 0x00A7, 0x00A5, 0x00A3, 0x00A1,
+    0x009F, 0x009D, 0x009B, 0x0099, 0x0097, 0x0095, 0x0093, 0x0091,
+    0x008F, 0x008D, 0x008B, 0x0089, 0x0087, 0x0085, 0x0083, 0x0081,
+    0x023F, 0x023D, 0x023B, 0x0239, 0x0237, 0x0235, 0x0233, 0x0231,
+    0x022F, 0x022D, 0x022B, 0x0229, 0x0227, 0x0225, 0x0223, 0x0221,
+    0x021F, 0x021D, 0x021B, 0x0219, 0x0217, 0x0215, 0x0213, 0x0211,
+    0x020F, 0x020D, 0x020B, 0x0209, 0x0207, 0x0205, 0x0203, 0x0201,
+    0x003F, 0x003D, 0x003B, 0x0039, 0x0037, 0x0035, 0x0033, 0x0031,
+    0x002F, 0x002D, 0x002B, 0x0029, 0x0027, 0x0025, 0x0023, 0x0021,
+    0x001F, 0x001D, 0x001B, 0x0019, 0x0017, 0x0015, 0x0013, 0x0011,
+    0x000F, 0x000D, 0x000B, 0x0009, 0x0007, 0x0005, 0x0003, 0x0001,
+    0x00FF, 0x00FD, 0x00FB, 0x00F9, 0x00F7, 0x00F5, 0x00F3, 0x00F1,
+    0x00EF, 0x00ED, 0x00EB, 0x00E9, 0x00E7, 0x00E5, 0x00E3, 0x00E1,
+    0x00DF, 0x00DD, 0x00DB, 0x00D9, 0x00D7, 0x00D5, 0x00D3, 0x00D1,
+    0x00CF, 0x00CD, 0x00CB, 0x00C9, 0x00C7, 0x00C5, 0x00C3, 0x00C1,
+    0x005F, 0x005D, 0x005B, 0x0059, 0x0057, 0x0055, 0x0053, 0x0051,
+    0x004F, 0x004D, 0x004B, 0x0049, 0x0047, 0x0045, 0x0043, 0x0041,
+    0x00FF, 0x00FD, 0x00FB, 0x00F9, 0x00F7, 0x00F5, 0x00F3, 0x00F1,
+    0x0075, 0x0073, 0x0071, 0x006F, 0x006D, 0x006B, 0x0069, 0x0067,
+};
+
+static const uint8_t dc11_vlc_lens[2048] = {
+     6,  7,  7,  7,  7,  7,  7,  7,  7,  8,  8,  8,  8,  8,  8,  8,
+     8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,
+     8,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,
+     9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,
+     9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,
+     9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,
+     9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+    10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+    10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+    10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+    10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+    10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+    10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+    11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+    10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+    10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+    10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+    10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+    10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+    10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+     9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,
+     9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,
+     9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,
+     9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,
+     8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,
+     8,  8,  8,  8,  8,  8,  8,  8,  7,  7,  7,  7,  7,  7,  7,  7,
+};
+
+#define RPT_2(a, b, c)    { a, b, c }, { a, b, c }
+#define RPT_4(a, b, c)    RPT_2(  a, b, c), RPT_2(  a, b, c)
+#define RPT_8(a, b, c)    RPT_4(  a, b, c), RPT_4(  a, b, c)
+#define RPT_16(a, b, c)   RPT_8(  a, b, c), RPT_8(  a, b, c)
+#define RPT_32(a, b, c)   RPT_16( a, b, c), RPT_16( a, b, c)
+#define RPT_64(a, b, c)   RPT_32( a, b, c), RPT_32( a, b, c)
+#define RPT_128(a, b, c)  RPT_64( a, b, c), RPT_64( a, b, c)
+#define RPT_256(a, b, c)  RPT_128(a, b, c), RPT_128(a, b, c)
+#define RPT_512(a, b, c)  RPT_256(a, b, c), RPT_256(a, b, c)
+#define RPT_1024(a, b, c) RPT_512(a, b, c), RPT_512(a, b, c)
+
+static const HQXLUT ac0_lut[] = {
+    RPT_64  (   1,  0,  4 ), RPT_64  (  -1,  0,  4 ),
+    RPT_64  (   2,  0,  4 ), RPT_64  (  -2,  0,  4 ),
+    RPT_32  (   3,  0,  5 ), RPT_32  (  -3,  0,  5 ),
+    RPT_32  (   4,  0,  5 ), RPT_32  (  -4,  0,  5 ),
+    RPT_32  (   1,  1,  5 ), RPT_32  (  -1,  1,  5 ),
+    RPT_16  (   5,  0,  6 ), RPT_16  (  -5,  0,  6 ),
+    RPT_16  (   6,  0,  6 ), RPT_16  (  -6,  0,  6 ),
+    RPT_16  (   7,  0,  6 ), RPT_16  (  -7,  0,  6 ),
+    RPT_16  (   8,  0,  6 ), RPT_16  (  -8,  0,  6 ),
+    { 1024,  0, -1 }, { 1056,  0, -1 }, { 1088,  0, -1 }, { 1120,  0, -1 },
+    { 1152,  0, -1 }, { 1184,  0, -1 }, { 1216,  0, -1 }, { 1248,  0, -1 },
+    { 1280,  0, -1 }, { 1312,  0, -1 }, { 1344,  0, -1 }, { 1376,  0, -1 },
+    { 1408,  0, -1 }, { 1440,  0, -1 }, { 1472,  0, -1 }, { 1504,  0, -1 },
+    { 1536,  0, -1 }, { 1568,  0, -1 }, { 1600,  0, -1 }, { 1632,  0, -1 },
+    { 1664,  0, -1 }, { 1696,  0, -1 }, { 1728,  0, -1 }, { 1760,  0, -1 },
+    { 1792,  0, -1 }, { 1824,  0, -1 }, { 1856,  0, -1 }, { 1888,  0, -1 },
+    { 1920,  0, -1 }, { 1952,  0, -1 }, { 1984,  0, -1 }, { 2016,  0, -1 },
+    RPT_32  (   0, 64,  5 ), RPT_8   (   9,  0,  7 ),
+    RPT_8   (  -9,  0,  7 ), RPT_8   (  10,  0,  7 ),
+    RPT_8   ( -10,  0,  7 ), RPT_8   (  11,  0,  7 ),
+    RPT_8   ( -11,  0,  7 ), RPT_8   (  12,  0,  7 ),
+    RPT_8   ( -12,  0,  7 ), RPT_8   (  13,  0,  7 ),
+    RPT_8   ( -13,  0,  7 ), RPT_8   (  14,  0,  7 ),
+    RPT_8   ( -14,  0,  7 ), RPT_8   (   2,  1,  7 ),
+    RPT_8   (  -2,  1,  7 ), RPT_8   (   1,  2,  7 ),
+    RPT_8   (  -1,  2,  7 ), RPT_4   (  15,  0,  8 ),
+    RPT_4   ( -15,  0,  8 ), RPT_4   (  16,  0,  8 ),
+    RPT_4   ( -16,  0,  8 ), RPT_4   (  17,  0,  8 ),
+    RPT_4   ( -17,  0,  8 ), RPT_4   (  18,  0,  8 ),
+    RPT_4   ( -18,  0,  8 ), RPT_4   (  19,  0,  8 ),
+    RPT_4   ( -19,  0,  8 ), RPT_4   (  20,  0,  8 ),
+    RPT_4   ( -20,  0,  8 ), RPT_4   (  21,  0,  8 ),
+    RPT_4   ( -21,  0,  8 ), RPT_4   (   3,  1,  8 ),
+    RPT_4   (  -3,  1,  8 ), RPT_4   (   4,  1,  8 ),
+    RPT_4   (  -4,  1,  8 ), RPT_4   (   1,  3,  8 ),
+    RPT_4   (  -1,  3,  8 ), RPT_4   (   1,  4,  8 ),
+    RPT_4   (  -1,  4,  8 ), RPT_4   (   0,  0,  8 ),
+    RPT_2   (  22,  0,  9 ), RPT_2   ( -22,  0,  9 ),
+    RPT_2   (  23,  0,  9 ), RPT_2   ( -23,  0,  9 ),
+    RPT_2   (  24,  0,  9 ), RPT_2   ( -24,  0,  9 ),
+    RPT_2   (  25,  0,  9 ), RPT_2   ( -25,  0,  9 ),
+    RPT_2   (  26,  0,  9 ), RPT_2   ( -26,  0,  9 ),
+    RPT_2   (  27,  0,  9 ), RPT_2   ( -27,  0,  9 ),
+    RPT_2   (  28,  0,  9 ), RPT_2   ( -28,  0,  9 ),
+    RPT_2   (  29,  0,  9 ), RPT_2   ( -29,  0,  9 ),
+    RPT_2   (  30,  0,  9 ), RPT_2   ( -30,  0,  9 ),
+    RPT_2   (  31,  0,  9 ), RPT_2   ( -31,  0,  9 ),
+    RPT_2   (  32,  0,  9 ), RPT_2   ( -32,  0,  9 ),
+    RPT_2   (  33,  0,  9 ), RPT_2   ( -33,  0,  9 ),
+    RPT_2   (   5,  1,  9 ), RPT_2   (  -5,  1,  9 ),
+    RPT_2   (   6,  1,  9 ), RPT_2   (  -6,  1,  9 ),
+    RPT_2   (   2,  2,  9 ), RPT_2   (  -2,  2,  9 ),
+    RPT_2   (   1,  5,  9 ), RPT_2   (  -1,  5,  9 ),
+    RPT_2   (   1,  6,  9 ), RPT_2   (  -1,  6,  9 ),
+    {   34,  0, 10 }, {  -34,  0, 10 }, {   35,  0, 10 }, {  -35,  0, 10 },
+    {   36,  0, 10 }, {  -36,  0, 10 }, {   37,  0, 10 }, {  -37,  0, 10 },
+    {   38,  0, 10 }, {  -38,  0, 10 }, {   39,  0, 10 }, {  -39,  0, 10 },
+    {   40,  0, 10 }, {  -40,  0, 10 }, {   41,  0, 10 }, {  -41,  0, 10 },
+    {   42,  0, 10 }, {  -42,  0, 10 }, {   43,  0, 10 }, {  -43,  0, 10 },
+    {   44,  0, 10 }, {  -44,  0, 10 }, {   45,  0, 10 }, {  -45,  0, 10 },
+    {   46,  0, 10 }, {  -46,  0, 10 }, {   47,  0, 10 }, {  -47,  0, 10 },
+    {   48,  0, 10 }, {  -48,  0, 10 }, {   49,  0, 10 }, {  -49,  0, 10 },
+    {   50,  0, 10 }, {  -50,  0, 10 }, RPT_2   (   0,  1,  9 ),
+    {    7,  1, 10 }, {   -7,  1, 10 }, {    8,  1, 10 }, {   -8,  1, 10 },
+    {    9,  1, 10 }, {   -9,  1, 10 }, {   10,  1, 10 }, {  -10,  1, 10 },
+    RPT_2   (   0,  2,  9 ), {    3,  2, 10 }, {   -3,  2, 10 },
+    RPT_2   (   0,  3,  9 ), {    2,  3, 10 }, {   -2,  3, 10 },
+    {    1,  7, 10 }, {   -1,  7, 10 }, {    1,  8, 10 }, {   -1,  8, 10 },
+    { 2048,  0, -1 }, { 2080,  0, -1 }, { 2112,  0, -1 }, { 2144,  0, -1 },
+    { 2176,  0, -1 }, { 2208,  0, -1 }, { 2240,  0, -1 }, { 2272,  0, -1 },
+    { 2304,  0, -1 }, { 2336,  0, -1 }, { 2368,  0, -1 }, { 2400,  0, -1 },
+    { 2432,  0, -1 }, { 2464,  0, -1 }, { 2496,  0, -1 }, { 2528,  0, -1 },
+    { 2560,  0, -1 }, { 2592,  0, -1 }, { 2624,  0, -1 }, { 2656,  0, -1 },
+    { 2688,  0, -1 }, { 2720,  0, -1 }, { 2752,  0, -1 }, {    0,  4, 10 },
+    { 2784,  0, -1 }, {    0,  5, 10 }, {    0,  6, 10 }, { 2816,  0, -1 },
+    { 2848,  0, -1 }, { 2880,  0, -1 }, { 2912,  0, -1 }, { 2944,  0, -1 },
+    { 2976,  0, -1 }, { 3008,  0, -1 }, { 3040,  0, -1 }, { 3072,  0, -1 },
+    { 3104,  0, -1 }, { 3136,  0, -1 }, { 3168,  0, -1 }, { 3200,  0, -1 },
+    RPT_4   (   0,  0, 13 ), RPT_2   (   1,  0, 14 ),
+    RPT_2   (  -1,  0, 14 ), RPT_2   (   2,  0, 14 ),
+    RPT_2   (  -2,  0, 14 ), RPT_2   (   3,  0, 14 ),
+    RPT_2   (  -3,  0, 14 ), RPT_2   (   4,  0, 14 ),
+    RPT_2   (  -4,  0, 14 ), RPT_2   (   5,  0, 14 ),
+    RPT_2   (  -5,  0, 14 ), RPT_2   (   6,  0, 14 ),
+    RPT_2   (  -6,  0, 14 ), RPT_2   (   7,  0, 14 ),
+    RPT_2   (  -7,  0, 14 ), RPT_2   (   8,  0, 14 ),
+    RPT_2   (  -8,  0, 14 ), RPT_2   (   9,  0, 14 ),
+    RPT_2   (  -9,  0, 14 ), RPT_2   (  10,  0, 14 ),
+    RPT_2   ( -10,  0, 14 ), RPT_2   (  11,  0, 14 ),
+    RPT_2   ( -11,  0, 14 ), RPT_2   (  12,  0, 14 ),
+    RPT_2   ( -12,  0, 14 ), RPT_2   (  13,  0, 14 ),
+    RPT_2   ( -13,  0, 14 ), RPT_2   (  14,  0, 14 ),
+    RPT_2   ( -14,  0, 14 ), RPT_2   (  15,  0, 14 ),
+    RPT_2   ( -15,  0, 14 ), RPT_2   (  16,  0, 14 ),
+    RPT_2   ( -16,  0, 14 ), RPT_2   (  17,  0, 14 ),
+    RPT_2   ( -17,  0, 14 ), RPT_2   (  18,  0, 14 ),
+    RPT_2   ( -18,  0, 14 ), RPT_2   (  19,  0, 14 ),
+    RPT_2   ( -19,  0, 14 ), RPT_2   (  20,  0, 14 ),
+    RPT_2   ( -20,  0, 14 ), RPT_2   (  21,  0, 14 ),
+    RPT_2   ( -21,  0, 14 ), RPT_2   (  22,  0, 14 ),
+    RPT_2   ( -22,  0, 14 ), RPT_2   (  23,  0, 14 ),
+    RPT_2   ( -23,  0, 14 ), RPT_2   (  24,  0, 14 ),
+    RPT_2   ( -24,  0, 14 ), RPT_2   (  25,  0, 14 ),
+    RPT_2   ( -25,  0, 14 ), RPT_2   (  26,  0, 14 ),
+    RPT_2   ( -26,  0, 14 ), RPT_2   (  27,  0, 14 ),
+    RPT_2   ( -27,  0, 14 ), RPT_2   (  28,  0, 14 ),
+    RPT_2   ( -28,  0, 14 ), RPT_2   (  29,  0, 14 ),
+    RPT_2   ( -29,  0, 14 ), RPT_2   (  30,  0, 14 ),
+    RPT_2   ( -30,  0, 14 ), RPT_2   (  31,  0, 14 ),
+    RPT_2   ( -31,  0, 14 ), RPT_2   (  32,  0, 14 ),
+    RPT_2   ( -32,  0, 14 ), RPT_2   (  33,  0, 14 ),
+    RPT_2   ( -33,  0, 14 ), RPT_2   (  34,  0, 14 ),
+    RPT_2   ( -34,  0, 14 ), RPT_2   (  35,  0, 14 ),
+    RPT_2   ( -35,  0, 14 ), RPT_2   (  36,  0, 14 ),
+    RPT_2   ( -36,  0, 14 ), RPT_2   (  37,  0, 14 ),
+    RPT_2   ( -37,  0, 14 ), RPT_2   (  38,  0, 14 ),
+    RPT_2   ( -38,  0, 14 ), RPT_2   (  39,  0, 14 ),
+    RPT_2   ( -39,  0, 14 ), RPT_2   (  40,  0, 14 ),
+    RPT_2   ( -40,  0, 14 ), RPT_2   (  41,  0, 14 ),
+    RPT_2   ( -41,  0, 14 ), RPT_2   (  42,  0, 14 ),
+    RPT_2   ( -42,  0, 14 ), RPT_2   (  43,  0, 14 ),
+    RPT_2   ( -43,  0, 14 ), RPT_2   (  44,  0, 14 ),
+    RPT_2   ( -44,  0, 14 ), RPT_2   (  45,  0, 14 ),
+    RPT_2   ( -45,  0, 14 ), RPT_2   (  46,  0, 14 ),
+    RPT_2   ( -46,  0, 14 ), RPT_2   (  47,  0, 14 ),
+    RPT_2   ( -47,  0, 14 ), RPT_2   (  48,  0, 14 ),
+    RPT_2   ( -48,  0, 14 ), RPT_2   (  49,  0, 14 ),
+    RPT_2   ( -49,  0, 14 ), RPT_2   (  50,  0, 14 ),
+    RPT_2   ( -50,  0, 14 ), RPT_2   (  51,  0, 14 ),
+    RPT_2   ( -51,  0, 14 ), RPT_2   (  52,  0, 14 ),
+    RPT_2   ( -52,  0, 14 ), RPT_2   (  53,  0, 14 ),
+    RPT_2   ( -53,  0, 14 ), RPT_2   (  54,  0, 14 ),
+    RPT_2   ( -54,  0, 14 ), RPT_2   (  55,  0, 14 ),
+    RPT_2   ( -55,  0, 14 ), RPT_2   (  56,  0, 14 ),
+    RPT_2   ( -56,  0, 14 ), RPT_2   (  57,  0, 14 ),
+    RPT_2   ( -57,  0, 14 ), RPT_2   (  58,  0, 14 ),
+    RPT_2   ( -58,  0, 14 ), RPT_2   (  59,  0, 14 ),
+    RPT_2   ( -59,  0, 14 ), RPT_2   (  60,  0, 14 ),
+    RPT_2   ( -60,  0, 14 ), RPT_2   (  61,  0, 14 ),
+    RPT_2   ( -61,  0, 14 ), RPT_2   (  62,  0, 14 ),
+    RPT_2   ( -62,  0, 14 ), RPT_2   (  63,  0, 14 ),
+    RPT_2   ( -63,  0, 14 ), RPT_2   (  64,  0, 14 ),
+    RPT_2   ( -64,  0, 14 ), RPT_2   (  65,  0, 14 ),
+    RPT_2   ( -65,  0, 14 ), RPT_2   (  66,  0, 14 ),
+    RPT_2   ( -66,  0, 14 ), RPT_2   (  67,  0, 14 ),
+    RPT_2   ( -67,  0, 14 ), RPT_2   (  68,  0, 14 ),
+    RPT_2   ( -68,  0, 14 ), RPT_2   (  69,  0, 14 ),
+    RPT_2   ( -69,  0, 14 ), RPT_2   (  70,  0, 14 ),
+    RPT_2   ( -70,  0, 14 ), RPT_2   (  71,  0, 14 ),
+    RPT_2   ( -71,  0, 14 ), RPT_2   (  72,  0, 14 ),
+    RPT_2   ( -72,  0, 14 ), RPT_2   (  73,  0, 14 ),
+    RPT_2   ( -73,  0, 14 ), RPT_2   (  74,  0, 14 ),
+    RPT_2   ( -74,  0, 14 ), RPT_2   (  75,  0, 14 ),
+    RPT_2   ( -75,  0, 14 ), RPT_2   (  76,  0, 14 ),
+    RPT_2   ( -76,  0, 14 ), RPT_2   (  77,  0, 14 ),
+    RPT_2   ( -77,  0, 14 ), RPT_2   (  78,  0, 14 ),
+    RPT_2   ( -78,  0, 14 ), RPT_2   (  79,  0, 14 ),
+    RPT_2   ( -79,  0, 14 ), RPT_2   (  80,  0, 14 ),
+    RPT_2   ( -80,  0, 14 ), RPT_2   (  81,  0, 14 ),
+    RPT_2   ( -81,  0, 14 ), RPT_2   (  82,  0, 14 ),
+    RPT_2   ( -82,  0, 14 ), RPT_2   (  83,  0, 14 ),
+    RPT_2   ( -83,  0, 14 ), RPT_2   (  84,  0, 14 ),
+    RPT_2   ( -84,  0, 14 ), RPT_2   (  85,  0, 14 ),
+    RPT_2   ( -85,  0, 14 ), RPT_2   (  86,  0, 14 ),
+    RPT_2   ( -86,  0, 14 ), RPT_2   (  87,  0, 14 ),
+    RPT_2   ( -87,  0, 14 ), RPT_2   (  88,  0, 14 ),
+    RPT_2   ( -88,  0, 14 ), RPT_2   (  89,  0, 14 ),
+    RPT_2   ( -89,  0, 14 ), RPT_2   (  90,  0, 14 ),
+    RPT_2   ( -90,  0, 14 ), RPT_2   (  91,  0, 14 ),
+    RPT_2   ( -91,  0, 14 ), RPT_2   (  92,  0, 14 ),
+    RPT_2   ( -92,  0, 14 ), RPT_2   (  93,  0, 14 ),
+    RPT_2   ( -93,  0, 14 ), RPT_2   (  94,  0, 14 ),
+    RPT_2   ( -94,  0, 14 ), RPT_2   (  95,  0, 14 ),
+    RPT_2   ( -95,  0, 14 ), RPT_2   (  96,  0, 14 ),
+    RPT_2   ( -96,  0, 14 ), RPT_2   (  97,  0, 14 ),
+    RPT_2   ( -97,  0, 14 ), RPT_2   (  98,  0, 14 ),
+    RPT_2   ( -98,  0, 14 ), RPT_2   (  99,  0, 14 ),
+    RPT_2   ( -99,  0, 14 ), RPT_2   ( 100,  0, 14 ),
+    RPT_2   (-100,  0, 14 ), RPT_2   ( 101,  0, 14 ),
+    RPT_2   (-101,  0, 14 ), RPT_2   ( 102,  0, 14 ),
+    RPT_2   (-102,  0, 14 ), RPT_2   ( 103,  0, 14 ),
+    RPT_2   (-103,  0, 14 ), RPT_2   ( 104,  0, 14 ),
+    RPT_2   (-104,  0, 14 ), RPT_2   ( 105,  0, 14 ),
+    RPT_2   (-105,  0, 14 ), RPT_2   ( 106,  0, 14 ),
+    RPT_2   (-106,  0, 14 ), RPT_2   ( 107,  0, 14 ),
+    RPT_2   (-107,  0, 14 ), RPT_2   ( 108,  0, 14 ),
+    RPT_2   (-108,  0, 14 ), RPT_2   ( 109,  0, 14 ),
+    RPT_2   (-109,  0, 14 ), RPT_2   ( 110,  0, 14 ),
+    RPT_2   (-110,  0, 14 ), RPT_2   ( 111,  0, 14 ),
+    RPT_2   (-111,  0, 14 ), RPT_2   ( 112,  0, 14 ),
+    RPT_2   (-112,  0, 14 ), RPT_2   ( 113,  0, 14 ),
+    RPT_2   (-113,  0, 14 ), RPT_2   ( 114,  0, 14 ),
+    RPT_2   (-114,  0, 14 ), RPT_2   ( 115,  0, 14 ),
+    RPT_2   (-115,  0, 14 ), RPT_2   ( 116,  0, 14 ),
+    RPT_2   (-116,  0, 14 ), RPT_2   ( 117,  0, 14 ),
+    RPT_2   (-117,  0, 14 ), RPT_2   ( 118,  0, 14 ),
+    RPT_2   (-118,  0, 14 ), RPT_2   ( 119,  0, 14 ),
+    RPT_2   (-119,  0, 14 ), RPT_2   ( 120,  0, 14 ),
+    RPT_2   (-120,  0, 14 ), RPT_2   ( 121,  0, 14 ),
+    RPT_2   (-121,  0, 14 ), RPT_2   ( 122,  0, 14 ),
+    RPT_2   (-122,  0, 14 ), RPT_2   ( 123,  0, 14 ),
+    RPT_2   (-123,  0, 14 ), RPT_2   ( 124,  0, 14 ),
+    RPT_2   (-124,  0, 14 ), RPT_2   ( 125,  0, 14 ),
+    RPT_2   (-125,  0, 14 ), RPT_2   ( 126,  0, 14 ),
+    RPT_2   (-126,  0, 14 ), RPT_2   ( 127,  0, 14 ),
+    RPT_2   (-127,  0, 14 ), RPT_2   ( 128,  0, 14 ),
+    RPT_2   (-128,  0, 14 ), RPT_2   ( 129,  0, 14 ),
+    RPT_2   (-129,  0, 14 ), RPT_2   ( 130,  0, 14 ),
+    RPT_2   (-130,  0, 14 ), RPT_2   ( 131,  0, 14 ),
+    RPT_2   (-131,  0, 14 ), RPT_2   ( 132,  0, 14 ),
+    RPT_2   (-132,  0, 14 ), RPT_2   ( 133,  0, 14 ),
+    RPT_2   (-133,  0, 14 ), RPT_2   ( 134,  0, 14 ),
+    RPT_2   (-134,  0, 14 ), RPT_2   ( 135,  0, 14 ),
+    RPT_2   (-135,  0, 14 ), RPT_2   ( 136,  0, 14 ),
+    RPT_2   (-136,  0, 14 ), RPT_2   ( 137,  0, 14 ),
+    RPT_2   (-137,  0, 14 ), RPT_2   ( 138,  0, 14 ),
+    RPT_2   (-138,  0, 14 ), RPT_2   ( 139,  0, 14 ),
+    RPT_2   (-139,  0, 14 ), RPT_2   ( 140,  0, 14 ),
+    RPT_2   (-140,  0, 14 ), RPT_2   ( 141,  0, 14 ),
+    RPT_2   (-141,  0, 14 ), RPT_2   ( 142,  0, 14 ),
+    RPT_2   (-142,  0, 14 ), RPT_2   ( 143,  0, 14 ),
+    RPT_2   (-143,  0, 14 ), RPT_2   ( 144,  0, 14 ),
+    RPT_2   (-144,  0, 14 ), RPT_2   ( 145,  0, 14 ),
+    RPT_2   (-145,  0, 14 ), RPT_2   ( 146,  0, 14 ),
+    RPT_2   (-146,  0, 14 ), RPT_2   ( 147,  0, 14 ),
+    RPT_2   (-147,  0, 14 ), RPT_2   ( 148,  0, 14 ),
+    RPT_2   (-148,  0, 14 ), RPT_2   ( 149,  0, 14 ),
+    RPT_2   (-149,  0, 14 ), RPT_2   ( 150,  0, 14 ),
+    RPT_2   (-150,  0, 14 ), RPT_2   ( 151,  0, 14 ),
+    RPT_2   (-151,  0, 14 ), RPT_2   ( 152,  0, 14 ),
+    RPT_2   (-152,  0, 14 ), RPT_2   ( 153,  0, 14 ),
+    RPT_2   (-153,  0, 14 ), RPT_2   ( 154,  0, 14 ),
+    RPT_2   (-154,  0, 14 ), RPT_2   ( 155,  0, 14 ),
+    RPT_2   (-155,  0, 14 ), RPT_2   ( 156,  0, 14 ),
+    RPT_2   (-156,  0, 14 ), RPT_2   ( 157,  0, 14 ),
+    RPT_2   (-157,  0, 14 ), RPT_2   ( 158,  0, 14 ),
+    RPT_2   (-158,  0, 14 ), RPT_2   ( 159,  0, 14 ),
+    RPT_2   (-159,  0, 14 ), RPT_2   ( 160,  0, 14 ),
+    RPT_2   (-160,  0, 14 ), RPT_2   ( 161,  0, 14 ),
+    RPT_2   (-161,  0, 14 ), RPT_2   ( 162,  0, 14 ),
+    RPT_2   (-162,  0, 14 ), RPT_2   ( 163,  0, 14 ),
+    RPT_2   (-163,  0, 14 ), RPT_2   ( 164,  0, 14 ),
+    RPT_2   (-164,  0, 14 ), RPT_2   ( 165,  0, 14 ),
+    RPT_2   (-165,  0, 14 ), RPT_2   ( 166,  0, 14 ),
+    RPT_2   (-166,  0, 14 ), RPT_2   ( 167,  0, 14 ),
+    RPT_2   (-167,  0, 14 ), RPT_2   ( 168,  0, 14 ),
+    RPT_2   (-168,  0, 14 ), RPT_2   ( 169,  0, 14 ),
+    RPT_2   (-169,  0, 14 ), RPT_2   ( 170,  0, 14 ),
+    RPT_2   (-170,  0, 14 ), RPT_2   ( 171,  0, 14 ),
+    RPT_2   (-171,  0, 14 ), RPT_2   ( 172,  0, 14 ),
+    RPT_2   (-172,  0, 14 ), RPT_2   ( 173,  0, 14 ),
+    RPT_2   (-173,  0, 14 ), RPT_2   ( 174,  0, 14 ),
+    RPT_2   (-174,  0, 14 ), RPT_2   ( 175,  0, 14 ),
+    RPT_2   (-175,  0, 14 ), RPT_2   ( 176,  0, 14 ),
+    RPT_2   (-176,  0, 14 ), RPT_2   ( 177,  0, 14 ),
+    RPT_2   (-177,  0, 14 ), RPT_2   ( 178,  0, 14 ),
+    RPT_2   (-178,  0, 14 ), RPT_2   ( 179,  0, 14 ),
+    RPT_2   (-179,  0, 14 ), RPT_2   ( 180,  0, 14 ),
+    RPT_2   (-180,  0, 14 ), RPT_2   ( 181,  0, 14 ),
+    RPT_2   (-181,  0, 14 ), RPT_2   ( 182,  0, 14 ),
+    RPT_2   (-182,  0, 14 ), RPT_2   ( 183,  0, 14 ),
+    RPT_2   (-183,  0, 14 ), RPT_2   ( 184,  0, 14 ),
+    RPT_2   (-184,  0, 14 ), RPT_2   ( 185,  0, 14 ),
+    RPT_2   (-185,  0, 14 ), RPT_2   ( 186,  0, 14 ),
+    RPT_2   (-186,  0, 14 ), RPT_2   ( 187,  0, 14 ),
+    RPT_2   (-187,  0, 14 ), RPT_2   ( 188,  0, 14 ),
+    RPT_2   (-188,  0, 14 ), RPT_2   ( 189,  0, 14 ),
+    RPT_2   (-189,  0, 14 ), RPT_2   ( 190,  0, 14 ),
+    RPT_2   (-190,  0, 14 ), RPT_2   ( 191,  0, 14 ),
+    RPT_2   (-191,  0, 14 ), RPT_2   ( 192,  0, 14 ),
+    RPT_2   (-192,  0, 14 ), RPT_2   ( 193,  0, 14 ),
+    RPT_2   (-193,  0, 14 ), RPT_2   ( 194,  0, 14 ),
+    RPT_2   (-194,  0, 14 ), RPT_2   ( 195,  0, 14 ),
+    RPT_2   (-195,  0, 14 ), RPT_2   ( 196,  0, 14 ),
+    RPT_2   (-196,  0, 14 ), RPT_2   ( 197,  0, 14 ),
+    RPT_2   (-197,  0, 14 ), RPT_2   ( 198,  0, 14 ),
+    RPT_2   (-198,  0, 14 ), RPT_2   ( 199,  0, 14 ),
+    RPT_2   (-199,  0, 14 ), RPT_2   ( 200,  0, 14 ),
+    RPT_2   (-200,  0, 14 ), RPT_2   ( 201,  0, 14 ),
+    RPT_2   (-201,  0, 14 ), RPT_2   ( 202,  0, 14 ),
+    RPT_2   (-202,  0, 14 ), RPT_2   ( 203,  0, 14 ),
+    RPT_2   (-203,  0, 14 ), RPT_2   ( 204,  0, 14 ),
+    RPT_2   (-204,  0, 14 ), RPT_2   ( 205,  0, 14 ),
+    RPT_2   (-205,  0, 14 ), RPT_2   ( 206,  0, 14 ),
+    RPT_2   (-206,  0, 14 ), RPT_2   ( 207,  0, 14 ),
+    RPT_2   (-207,  0, 14 ), RPT_2   ( 208,  0, 14 ),
+    RPT_2   (-208,  0, 14 ), RPT_2   ( 209,  0, 14 ),
+    RPT_2   (-209,  0, 14 ), RPT_2   ( 210,  0, 14 ),
+    RPT_2   (-210,  0, 14 ), RPT_2   ( 211,  0, 14 ),
+    RPT_2   (-211,  0, 14 ), RPT_2   ( 212,  0, 14 ),
+    RPT_2   (-212,  0, 14 ), RPT_2   ( 213,  0, 14 ),
+    RPT_2   (-213,  0, 14 ), RPT_2   ( 214,  0, 14 ),
+    RPT_2   (-214,  0, 14 ), RPT_2   ( 215,  0, 14 ),
+    RPT_2   (-215,  0, 14 ), RPT_2   ( 216,  0, 14 ),
+    RPT_2   (-216,  0, 14 ), RPT_2   ( 217,  0, 14 ),
+    RPT_2   (-217,  0, 14 ), RPT_2   ( 218,  0, 14 ),
+    RPT_2   (-218,  0, 14 ), RPT_2   ( 219,  0, 14 ),
+    RPT_2   (-219,  0, 14 ), RPT_2   ( 220,  0, 14 ),
+    RPT_2   (-220,  0, 14 ), RPT_2   ( 221,  0, 14 ),
+    RPT_2   (-221,  0, 14 ), RPT_2   ( 222,  0, 14 ),
+    RPT_2   (-222,  0, 14 ), RPT_2   ( 223,  0, 14 ),
+    RPT_2   (-223,  0, 14 ), RPT_2   ( 224,  0, 14 ),
+    RPT_2   (-224,  0, 14 ), RPT_2   ( 225,  0, 14 ),
+    RPT_2   (-225,  0, 14 ), RPT_2   ( 226,  0, 14 ),
+    RPT_2   (-226,  0, 14 ), RPT_2   ( 227,  0, 14 ),
+    RPT_2   (-227,  0, 14 ), RPT_2   ( 228,  0, 14 ),
+    RPT_2   (-228,  0, 14 ), RPT_2   ( 229,  0, 14 ),
+    RPT_2   (-229,  0, 14 ), RPT_2   ( 230,  0, 14 ),
+    RPT_2   (-230,  0, 14 ), RPT_2   ( 231,  0, 14 ),
+    RPT_2   (-231,  0, 14 ), RPT_2   ( 232,  0, 14 ),
+    RPT_2   (-232,  0, 14 ), RPT_2   ( 233,  0, 14 ),
+    RPT_2   (-233,  0, 14 ), RPT_2   ( 234,  0, 14 ),
+    RPT_2   (-234,  0, 14 ), RPT_2   ( 235,  0, 14 ),
+    RPT_2   (-235,  0, 14 ), RPT_2   ( 236,  0, 14 ),
+    RPT_2   (-236,  0, 14 ), RPT_2   ( 237,  0, 14 ),
+    RPT_2   (-237,  0, 14 ), RPT_2   ( 238,  0, 14 ),
+    RPT_2   (-238,  0, 14 ), RPT_2   ( 239,  0, 14 ),
+    RPT_2   (-239,  0, 14 ), RPT_2   ( 240,  0, 14 ),
+    RPT_2   (-240,  0, 14 ), RPT_2   ( 241,  0, 14 ),
+    RPT_2   (-241,  0, 14 ), RPT_2   ( 242,  0, 14 ),
+    RPT_2   (-242,  0, 14 ), RPT_2   ( 243,  0, 14 ),
+    RPT_2   (-243,  0, 14 ), RPT_2   ( 244,  0, 14 ),
+    RPT_2   (-244,  0, 14 ), RPT_2   ( 245,  0, 14 ),
+    RPT_2   (-245,  0, 14 ), RPT_2   ( 246,  0, 14 ),
+    RPT_2   (-246,  0, 14 ), RPT_2   ( 247,  0, 14 ),
+    RPT_2   (-247,  0, 14 ), RPT_2   ( 248,  0, 14 ),
+    RPT_2   (-248,  0, 14 ), RPT_2   ( 249,  0, 14 ),
+    RPT_2   (-249,  0, 14 ), RPT_2   ( 250,  0, 14 ),
+    RPT_2   (-250,  0, 14 ), RPT_2   ( 251,  0, 14 ),
+    RPT_2   (-251,  0, 14 ), RPT_2   ( 252,  0, 14 ),
+    RPT_2   (-252,  0, 14 ), RPT_2   ( 253,  0, 14 ),
+    RPT_2   (-253,  0, 14 ), RPT_2   ( 254,  0, 14 ),
+    RPT_2   (-254,  0, 14 ), RPT_2   ( 255,  0, 14 ),
+    RPT_2   (-255,  0, 14 ), {    0,  0, 15 }, {    0,  1, 15 },
+    {    0,  2, 15 }, {    0,  3, 15 }, {    0,  4, 15 }, {    0,  5, 15 },
+    {    0,  6, 15 }, {    0,  7, 15 }, {    0,  8, 15 }, {    0,  9, 15 },
+    {    0, 10, 15 }, {    0, 11, 15 }, {    0, 12, 15 }, {    0, 13, 15 },
+    {    0, 14, 15 }, {    0, 15, 15 }, {    0, 16, 15 }, {    0, 17, 15 },
+    {    0, 18, 15 }, {    0, 19, 15 }, {    0, 20, 15 }, {    0, 21, 15 },
+    {    0, 22, 15 }, {    0, 23, 15 }, {    0, 24, 15 }, {    0, 25, 15 },
+    {    0, 26, 15 }, {    0, 27, 15 }, {    0, 28, 15 }, {    0, 29, 15 },
+    {    0, 30, 15 }, {    0, 31, 15 }, {    0, 32, 15 }, {    0, 33, 15 },
+    {    0, 34, 15 }, {    0, 35, 15 }, {    0, 36, 15 }, {    0, 37, 15 },
+    {    0, 38, 15 }, {    0, 39, 15 }, {    0, 40, 15 }, {    0, 41, 15 },
+    {    0, 42, 15 }, {    0, 43, 15 }, {    0, 44, 15 }, {    0, 45, 15 },
+    {    0, 46, 15 }, {    0, 47, 15 }, {    0, 48, 15 }, {    0, 49, 15 },
+    {    0, 50, 15 }, {    0, 51, 15 }, {    0, 52, 15 }, {    0, 53, 15 },
+    {    0, 54, 15 }, {    0, 55, 15 }, {    0, 56, 15 }, {    0, 57, 15 },
+    {    0, 58, 15 }, {    0, 59, 15 }, {    0, 60, 15 }, {    0, 61, 15 },
+    {    0, 62, 15 }, {    0, 63, 15 }, RPT_16  (  51,  0, 11 ),
+    RPT_16  ( -51,  0, 11 ), RPT_16  (  52,  0, 11 ),
+    RPT_16  ( -52,  0, 11 ), RPT_16  (  53,  0, 11 ),
+    RPT_16  ( -53,  0, 11 ), RPT_16  (  54,  0, 11 ),
+    RPT_16  ( -54,  0, 11 ), RPT_16  (  55,  0, 11 ),
+    RPT_16  ( -55,  0, 11 ), RPT_16  (  56,  0, 11 ),
+    RPT_16  ( -56,  0, 11 ), RPT_16  (  57,  0, 11 ),
+    RPT_16  ( -57,  0, 11 ), RPT_16  (  58,  0, 11 ),
+    RPT_16  ( -58,  0, 11 ), RPT_16  (  59,  0, 11 ),
+    RPT_16  ( -59,  0, 11 ), RPT_16  (  60,  0, 11 ),
+    RPT_16  ( -60,  0, 11 ), RPT_16  (  61,  0, 11 ),
+    RPT_16  ( -61,  0, 11 ), RPT_16  (  62,  0, 11 ),
+    RPT_16  ( -62,  0, 11 ), RPT_16  (  63,  0, 11 ),
+    RPT_16  ( -63,  0, 11 ), RPT_16  (  11,  1, 11 ),
+    RPT_16  ( -11,  1, 11 ), RPT_16  (  12,  1, 11 ),
+    RPT_16  ( -12,  1, 11 ), RPT_16  (  13,  1, 11 ),
+    RPT_16  ( -13,  1, 11 ), RPT_16  (  14,  1, 11 ),
+    RPT_16  ( -14,  1, 11 ), RPT_16  (   4,  2, 11 ),
+    RPT_16  (  -4,  2, 11 ), RPT_16  (   5,  2, 11 ),
+    RPT_16  (  -5,  2, 11 ), RPT_16  (   6,  2, 11 ),
+    RPT_16  (  -6,  2, 11 ), RPT_16  (   3,  3, 11 ),
+    RPT_16  (  -3,  3, 11 ), RPT_16  (   2,  4, 11 ),
+    RPT_16  (  -2,  4, 11 ), RPT_16  (   1,  9, 11 ),
+    RPT_16  (  -1,  9, 11 ), RPT_16  (   1, 10, 11 ),
+    RPT_16  (  -1, 10, 11 ), RPT_8   (  15,  1, 12 ),
+    RPT_8   ( -15,  1, 12 ), RPT_8   (  16,  1, 12 ),
+    RPT_8   ( -16,  1, 12 ), RPT_8   (  17,  1, 12 ),
+    RPT_8   ( -17,  1, 12 ), RPT_8   (  18,  1, 12 ),
+    RPT_8   ( -18,  1, 12 ), RPT_8   (   7,  2, 12 ),
+    RPT_8   (  -7,  2, 12 ), RPT_8   (   8,  2, 12 ),
+    RPT_8   (  -8,  2, 12 ), RPT_8   (   9,  2, 12 ),
+    RPT_8   (  -9,  2, 12 ), RPT_8   (  10,  2, 12 ),
+    RPT_8   ( -10,  2, 12 ), RPT_8   (   4,  3, 12 ),
+    RPT_8   (  -4,  3, 12 ), RPT_8   (   5,  3, 12 ),
+    RPT_8   (  -5,  3, 12 ), RPT_8   (   6,  3, 12 ),
+    RPT_8   (  -6,  3, 12 ), RPT_8   (   2,  5, 12 ),
+    RPT_8   (  -2,  5, 12 ), RPT_16  (   0,  7, 11 ),
+    RPT_16  (   0,  8, 11 ), RPT_16  (   0,  9, 11 ),
+    RPT_16  (   0, 10, 11 ), RPT_8   (   1, 11, 12 ),
+    RPT_8   (  -1, 11, 12 ), RPT_8   (   1, 12, 12 ),
+    RPT_8   (  -1, 12, 12 ), RPT_8   (   1, 13, 12 ),
+    RPT_8   (  -1, 13, 12 ), RPT_8   (   1, 14, 12 ),
+    RPT_8   (  -1, 14, 12 ), RPT_4   (  19,  1, 13 ),
+    RPT_4   ( -19,  1, 13 ), RPT_4   (  20,  1, 13 ),
+    RPT_4   ( -20,  1, 13 ), RPT_4   (   3,  4, 13 ),
+    RPT_4   (  -3,  4, 13 ), RPT_4   (   2,  6, 13 ),
+    RPT_4   (  -2,  6, 13 ),
+};
+
+static const HQXLUT ac8_lut[] = {
+    RPT_128 (   1,  0,  4 ), RPT_128 (  -1,  0,  4 ),
+    RPT_128 (   2,  0,  4 ), RPT_128 (  -2,  0,  4 ),
+    RPT_64  (   3,  0,  5 ), RPT_64  (  -3,  0,  5 ),
+    RPT_64  (   4,  0,  5 ), RPT_64  (  -4,  0,  5 ),
+    RPT_128 (   0, 64,  4 ), RPT_32  (   5,  0,  6 ),
+    RPT_32  (  -5,  0,  6 ), RPT_32  (   6,  0,  6 ),
+    RPT_32  (  -6,  0,  6 ), RPT_32  (   7,  0,  6 ),
+    RPT_32  (  -7,  0,  6 ), RPT_32  (   8,  0,  6 ),
+    RPT_32  (  -8,  0,  6 ), RPT_32  (   1,  1,  6 ),
+    RPT_32  (  -1,  1,  6 ), RPT_32  (   2,  1,  6 ),
+    RPT_32  (  -2,  1,  6 ), RPT_16  (   9,  0,  7 ),
+    RPT_16  (  -9,  0,  7 ), RPT_16  (  10,  0,  7 ),
+    RPT_16  ( -10,  0,  7 ), RPT_16  (  11,  0,  7 ),
+    RPT_16  ( -11,  0,  7 ), RPT_16  (  12,  0,  7 ),
+    RPT_16  ( -12,  0,  7 ), RPT_16  (   3,  1,  7 ),
+    RPT_16  (  -3,  1,  7 ), RPT_16  (   4,  1,  7 ),
+    RPT_16  (  -4,  1,  7 ), RPT_16  (   1,  2,  7 ),
+    RPT_16  (  -1,  2,  7 ), { 2048,  0, -1 }, { 2112,  0, -1 },
+    { 2176,  0, -1 }, { 2240,  0, -1 }, { 2304,  0, -1 }, { 2368,  0, -1 },
+    { 2432,  0, -1 }, { 2496,  0, -1 }, { 2560,  0, -1 }, { 2624,  0, -1 },
+    { 2688,  0, -1 }, { 2752,  0, -1 }, { 2816,  0, -1 }, { 2880,  0, -1 },
+    { 2944,  0, -1 }, { 3008,  0, -1 }, { 3072,  0, -1 }, { 3136,  0, -1 },
+    { 3200,  0, -1 }, { 3264,  0, -1 }, { 3328,  0, -1 }, { 3392,  0, -1 },
+    { 3456,  0, -1 }, { 3520,  0, -1 }, { 3584,  0, -1 }, { 3648,  0, -1 },
+    { 3712,  0, -1 }, { 3776,  0, -1 }, { 3840,  0, -1 }, { 3904,  0, -1 },
+    { 3968,  0, -1 }, { 4032,  0, -1 }, RPT_8   (  13,  0,  8 ),
+    RPT_8   ( -13,  0,  8 ), RPT_8   (  14,  0,  8 ),
+    RPT_8   ( -14,  0,  8 ), RPT_8   (  15,  0,  8 ),
+    RPT_8   ( -15,  0,  8 ), RPT_8   (  16,  0,  8 ),
+    RPT_8   ( -16,  0,  8 ), RPT_8   (  17,  0,  8 ),
+    RPT_8   ( -17,  0,  8 ), RPT_8   (  18,  0,  8 ),
+    RPT_8   ( -18,  0,  8 ), RPT_8   (   5,  1,  8 ),
+    RPT_8   (  -5,  1,  8 ), RPT_8   (   6,  1,  8 ),
+    RPT_8   (  -6,  1,  8 ), RPT_8   (   2,  2,  8 ),
+    RPT_8   (  -2,  2,  8 ), RPT_8   (   1,  3,  8 ),
+    RPT_8   (  -1,  3,  8 ), RPT_8   (   0,  0,  8 ),
+    RPT_4   (  19,  0,  9 ), RPT_4   ( -19,  0,  9 ),
+    RPT_4   (  20,  0,  9 ), RPT_4   ( -20,  0,  9 ),
+    RPT_4   (  21,  0,  9 ), RPT_4   ( -21,  0,  9 ),
+    RPT_4   (  22,  0,  9 ), RPT_4   ( -22,  0,  9 ),
+    RPT_4   (  23,  0,  9 ), RPT_4   ( -23,  0,  9 ),
+    RPT_4   (  24,  0,  9 ), RPT_4   ( -24,  0,  9 ),
+    RPT_4   (  25,  0,  9 ), RPT_4   ( -25,  0,  9 ),
+    RPT_4   (   7,  1,  9 ), RPT_4   (  -7,  1,  9 ),
+    RPT_4   (   8,  1,  9 ), RPT_4   (  -8,  1,  9 ),
+    RPT_4   (   3,  2,  9 ), RPT_4   (  -3,  2,  9 ),
+    RPT_4   (   2,  3,  9 ), RPT_4   (  -2,  3,  9 ),
+    RPT_4   (   1,  4,  9 ), RPT_4   (  -1,  4,  9 ),
+    RPT_4   (   1,  5,  9 ), RPT_4   (  -1,  5,  9 ),
+    RPT_2   (  26,  0, 10 ), RPT_2   ( -26,  0, 10 ),
+    RPT_2   (  27,  0, 10 ), RPT_2   ( -27,  0, 10 ),
+    RPT_2   (  28,  0, 10 ), RPT_2   ( -28,  0, 10 ),
+    RPT_2   (  29,  0, 10 ), RPT_2   ( -29,  0, 10 ),
+    RPT_2   (  30,  0, 10 ), RPT_2   ( -30,  0, 10 ),
+    RPT_2   (  31,  0, 10 ), RPT_2   ( -31,  0, 10 ),
+    RPT_2   (  32,  0, 10 ), RPT_2   ( -32,  0, 10 ),
+    RPT_2   (  33,  0, 10 ), RPT_2   ( -33,  0, 10 ),
+    RPT_2   (  34,  0, 10 ), RPT_2   ( -34,  0, 10 ),
+    RPT_2   (  35,  0, 10 ), RPT_2   ( -35,  0, 10 ),
+    RPT_2   (  36,  0, 10 ), RPT_2   ( -36,  0, 10 ),
+    RPT_4   (   0,  1,  9 ), RPT_2   (   9,  1, 10 ),
+    RPT_2   (  -9,  1, 10 ), RPT_2   (  10,  1, 10 ),
+    RPT_2   ( -10,  1, 10 ), RPT_2   (  11,  1, 10 ),
+    RPT_2   ( -11,  1, 10 ), RPT_2   (  12,  1, 10 ),
+    RPT_2   ( -12,  1, 10 ), RPT_4   (   0,  2,  9 ),
+    RPT_2   (   4,  2, 10 ), RPT_2   (  -4,  2, 10 ),
+    RPT_2   (   5,  2, 10 ), RPT_2   (  -5,  2, 10 ),
+    RPT_2   (   6,  2, 10 ), RPT_2   (  -6,  2, 10 ),
+    RPT_4   (   0,  3,  9 ), RPT_2   (   3,  3, 10 ),
+    RPT_2   (  -3,  3, 10 ), RPT_2   (   4,  3, 10 ),
+    RPT_2   (  -4,  3, 10 ), RPT_4   (   0,  4,  9 ),
+    RPT_2   (   2,  4, 10 ), RPT_2   (  -2,  4, 10 ),
+    RPT_4   (   0,  5,  9 ), RPT_2   (   1,  6, 10 ),
+    RPT_2   (  -1,  6, 10 ), RPT_2   (   1,  7, 10 ),
+    RPT_2   (  -1,  7, 10 ), RPT_2   (   1,  8, 10 ),
+    RPT_2   (  -1,  8, 10 ), {   37,  0, 11 }, {  -37,  0, 11 },
+    {   38,  0, 11 }, {  -38,  0, 11 }, {   39,  0, 11 }, {  -39,  0, 11 },
+    {   40,  0, 11 }, {  -40,  0, 11 }, {   41,  0, 11 }, {  -41,  0, 11 },
+    {   42,  0, 11 }, {  -42,  0, 11 }, {   43,  0, 11 }, {  -43,  0, 11 },
+    {   44,  0, 11 }, {  -44,  0, 11 }, {   45,  0, 11 }, {  -45,  0, 11 },
+    {   46,  0, 11 }, {  -46,  0, 11 }, {   47,  0, 11 }, {  -47,  0, 11 },
+    {   48,  0, 11 }, {  -48,  0, 11 }, {   13,  1, 11 }, {  -13,  1, 11 },
+    {   14,  1, 11 }, {  -14,  1, 11 }, {   15,  1, 11 }, {  -15,  1, 11 },
+    {   16,  1, 11 }, {  -16,  1, 11 }, {    7,  2, 11 }, {   -7,  2, 11 },
+    {    8,  2, 11 }, {   -8,  2, 11 }, {    5,  3, 11 }, {   -5,  3, 11 },
+    {    6,  3, 11 }, {   -6,  3, 11 }, {    3,  4, 11 }, {   -3,  4, 11 },
+    {    4,  4, 11 }, {   -4,  4, 11 }, {    2,  5, 11 }, {   -2,  5, 11 },
+    RPT_2   (   0,  6, 10 ), {    2,  6, 11 }, {   -2,  6, 11 },
+    RPT_2   (   0,  7, 10 ), RPT_2   (   0,  8, 10 ),
+    RPT_2   (   0,  9, 10 ), {    1,  9, 11 }, {   -1,  9, 11 },
+    {    1, 10, 11 }, {   -1, 10, 11 }, {    1, 11, 11 }, {   -1, 11, 11 },
+    {    1, 12, 11 }, {   -1, 12, 11 }, { 4096,  0, -1 }, { 4160,  0, -1 },
+    { 4224,  0, -1 }, { 4288,  0, -1 }, { 4352,  0, -1 }, { 4416,  0, -1 },
+    { 4480,  0, -1 }, { 4544,  0, -1 }, { 4608,  0, -1 }, { 4672,  0, -1 },
+    { 4736,  0, -1 }, { 4800,  0, -1 }, { 4864,  0, -1 }, { 4928,  0, -1 },
+    { 4992,  0, -1 }, { 5056,  0, -1 }, { 5120,  0, -1 }, { 5184,  0, -1 },
+    { 5248,  0, -1 }, { 5312,  0, -1 }, { 5376,  0, -1 }, { 5440,  0, -1 },
+    { 5504,  0, -1 }, { 5568,  0, -1 }, { 5632,  0, -1 }, { 5696,  0, -1 },
+    { 5760,  0, -1 }, { 5824,  0, -1 }, { 5888,  0, -1 }, { 5952,  0, -1 },
+    { 6016,  0, -1 }, { 6080,  0, -1 }, { 6144,  0, -1 }, { 6208,  0, -1 },
+    { 6272,  0, -1 }, { 6336,  0, -1 }, { 6400,  0, -1 }, { 6464,  0, -1 },
+    { 6528,  0, -1 }, { 6592,  0, -1 }, {    0, 10, 11 }, { 6656,  0, -1 },
+    {    0, 11, 11 }, {    0, 12, 11 }, {    0, 13, 11 }, { 6720,  0, -1 },
+    { 6784,  0, -1 }, { 6848,  0, -1 }, { 6912,  0, -1 }, { 6976,  0, -1 },
+    { 7040,  0, -1 }, { 7104,  0, -1 }, { 7168,  0, -1 }, { 7232,  0, -1 },
+    { 7296,  0, -1 }, { 7360,  0, -1 }, { 7424,  0, -1 }, { 7488,  0, -1 },
+    { 7552,  0, -1 }, { 7616,  0, -1 }, RPT_8   (   0,  0, 14 ),
+    RPT_4   (   1,  0, 15 ), RPT_4   (  -1,  0, 15 ),
+    RPT_4   (   2,  0, 15 ), RPT_4   (  -2,  0, 15 ),
+    RPT_4   (   3,  0, 15 ), RPT_4   (  -3,  0, 15 ),
+    RPT_4   (   4,  0, 15 ), RPT_4   (  -4,  0, 15 ),
+    RPT_4   (   5,  0, 15 ), RPT_4   (  -5,  0, 15 ),
+    RPT_4   (   6,  0, 15 ), RPT_4   (  -6,  0, 15 ),
+    RPT_4   (   7,  0, 15 ), RPT_4   (  -7,  0, 15 ),
+    RPT_4   (   8,  0, 15 ), RPT_4   (  -8,  0, 15 ),
+    RPT_4   (   9,  0, 15 ), RPT_4   (  -9,  0, 15 ),
+    RPT_4   (  10,  0, 15 ), RPT_4   ( -10,  0, 15 ),
+    RPT_4   (  11,  0, 15 ), RPT_4   ( -11,  0, 15 ),
+    RPT_4   (  12,  0, 15 ), RPT_4   ( -12,  0, 15 ),
+    RPT_4   (  13,  0, 15 ), RPT_4   ( -13,  0, 15 ),
+    RPT_4   (  14,  0, 15 ), RPT_4   ( -14,  0, 15 ),
+    RPT_4   (  15,  0, 15 ), RPT_4   ( -15,  0, 15 ),
+    RPT_4   (  16,  0, 15 ), RPT_4   ( -16,  0, 15 ),
+    RPT_4   (  17,  0, 15 ), RPT_4   ( -17,  0, 15 ),
+    RPT_4   (  18,  0, 15 ), RPT_4   ( -18,  0, 15 ),
+    RPT_4   (  19,  0, 15 ), RPT_4   ( -19,  0, 15 ),
+    RPT_4   (  20,  0, 15 ), RPT_4   ( -20,  0, 15 ),
+    RPT_4   (  21,  0, 15 ), RPT_4   ( -21,  0, 15 ),
+    RPT_4   (  22,  0, 15 ), RPT_4   ( -22,  0, 15 ),
+    RPT_4   (  23,  0, 15 ), RPT_4   ( -23,  0, 15 ),
+    RPT_4   (  24,  0, 15 ), RPT_4   ( -24,  0, 15 ),
+    RPT_4   (  25,  0, 15 ), RPT_4   ( -25,  0, 15 ),
+    RPT_4   (  26,  0, 15 ), RPT_4   ( -26,  0, 15 ),
+    RPT_4   (  27,  0, 15 ), RPT_4   ( -27,  0, 15 ),
+    RPT_4   (  28,  0, 15 ), RPT_4   ( -28,  0, 15 ),
+    RPT_4   (  29,  0, 15 ), RPT_4   ( -29,  0, 15 ),
+    RPT_4   (  30,  0, 15 ), RPT_4   ( -30,  0, 15 ),
+    RPT_4   (  31,  0, 15 ), RPT_4   ( -31,  0, 15 ),
+    RPT_4   (  32,  0, 15 ), RPT_4   ( -32,  0, 15 ),
+    RPT_4   (  33,  0, 15 ), RPT_4   ( -33,  0, 15 ),
+    RPT_4   (  34,  0, 15 ), RPT_4   ( -34,  0, 15 ),
+    RPT_4   (  35,  0, 15 ), RPT_4   ( -35,  0, 15 ),
+    RPT_4   (  36,  0, 15 ), RPT_4   ( -36,  0, 15 ),
+    RPT_4   (  37,  0, 15 ), RPT_4   ( -37,  0, 15 ),
+    RPT_4   (  38,  0, 15 ), RPT_4   ( -38,  0, 15 ),
+    RPT_4   (  39,  0, 15 ), RPT_4   ( -39,  0, 15 ),
+    RPT_4   (  40,  0, 15 ), RPT_4   ( -40,  0, 15 ),
+    RPT_4   (  41,  0, 15 ), RPT_4   ( -41,  0, 15 ),
+    RPT_4   (  42,  0, 15 ), RPT_4   ( -42,  0, 15 ),
+    RPT_4   (  43,  0, 15 ), RPT_4   ( -43,  0, 15 ),
+    RPT_4   (  44,  0, 15 ), RPT_4   ( -44,  0, 15 ),
+    RPT_4   (  45,  0, 15 ), RPT_4   ( -45,  0, 15 ),
+    RPT_4   (  46,  0, 15 ), RPT_4   ( -46,  0, 15 ),
+    RPT_4   (  47,  0, 15 ), RPT_4   ( -47,  0, 15 ),
+    RPT_4   (  48,  0, 15 ), RPT_4   ( -48,  0, 15 ),
+    RPT_4   (  49,  0, 15 ), RPT_4   ( -49,  0, 15 ),
+    RPT_4   (  50,  0, 15 ), RPT_4   ( -50,  0, 15 ),
+    RPT_4   (  51,  0, 15 ), RPT_4   ( -51,  0, 15 ),
+    RPT_4   (  52,  0, 15 ), RPT_4   ( -52,  0, 15 ),
+    RPT_4   (  53,  0, 15 ), RPT_4   ( -53,  0, 15 ),
+    RPT_4   (  54,  0, 15 ), RPT_4   ( -54,  0, 15 ),
+    RPT_4   (  55,  0, 15 ), RPT_4   ( -55,  0, 15 ),
+    RPT_4   (  56,  0, 15 ), RPT_4   ( -56,  0, 15 ),
+    RPT_4   (  57,  0, 15 ), RPT_4   ( -57,  0, 15 ),
+    RPT_4   (  58,  0, 15 ), RPT_4   ( -58,  0, 15 ),
+    RPT_4   (  59,  0, 15 ), RPT_4   ( -59,  0, 15 ),
+    RPT_4   (  60,  0, 15 ), RPT_4   ( -60,  0, 15 ),
+    RPT_4   (  61,  0, 15 ), RPT_4   ( -61,  0, 15 ),
+    RPT_4   (  62,  0, 15 ), RPT_4   ( -62,  0, 15 ),
+    RPT_4   (  63,  0, 15 ), RPT_4   ( -63,  0, 15 ),
+    RPT_4   (  64,  0, 15 ), RPT_4   ( -64,  0, 15 ),
+    RPT_4   (  65,  0, 15 ), RPT_4   ( -65,  0, 15 ),
+    RPT_4   (  66,  0, 15 ), RPT_4   ( -66,  0, 15 ),
+    RPT_4   (  67,  0, 15 ), RPT_4   ( -67,  0, 15 ),
+    RPT_4   (  68,  0, 15 ), RPT_4   ( -68,  0, 15 ),
+    RPT_4   (  69,  0, 15 ), RPT_4   ( -69,  0, 15 ),
+    RPT_4   (  70,  0, 15 ), RPT_4   ( -70,  0, 15 ),
+    RPT_4   (  71,  0, 15 ), RPT_4   ( -71,  0, 15 ),
+    RPT_4   (  72,  0, 15 ), RPT_4   ( -72,  0, 15 ),
+    RPT_4   (  73,  0, 15 ), RPT_4   ( -73,  0, 15 ),
+    RPT_4   (  74,  0, 15 ), RPT_4   ( -74,  0, 15 ),
+    RPT_4   (  75,  0, 15 ), RPT_4   ( -75,  0, 15 ),
+    RPT_4   (  76,  0, 15 ), RPT_4   ( -76,  0, 15 ),
+    RPT_4   (  77,  0, 15 ), RPT_4   ( -77,  0, 15 ),
+    RPT_4   (  78,  0, 15 ), RPT_4   ( -78,  0, 15 ),
+    RPT_4   (  79,  0, 15 ), RPT_4   ( -79,  0, 15 ),
+    RPT_4   (  80,  0, 15 ), RPT_4   ( -80,  0, 15 ),
+    RPT_4   (  81,  0, 15 ), RPT_4   ( -81,  0, 15 ),
+    RPT_4   (  82,  0, 15 ), RPT_4   ( -82,  0, 15 ),
+    RPT_4   (  83,  0, 15 ), RPT_4   ( -83,  0, 15 ),
+    RPT_4   (  84,  0, 15 ), RPT_4   ( -84,  0, 15 ),
+    RPT_4   (  85,  0, 15 ), RPT_4   ( -85,  0, 15 ),
+    RPT_4   (  86,  0, 15 ), RPT_4   ( -86,  0, 15 ),
+    RPT_4   (  87,  0, 15 ), RPT_4   ( -87,  0, 15 ),
+    RPT_4   (  88,  0, 15 ), RPT_4   ( -88,  0, 15 ),
+    RPT_4   (  89,  0, 15 ), RPT_4   ( -89,  0, 15 ),
+    RPT_4   (  90,  0, 15 ), RPT_4   ( -90,  0, 15 ),
+    RPT_4   (  91,  0, 15 ), RPT_4   ( -91,  0, 15 ),
+    RPT_4   (  92,  0, 15 ), RPT_4   ( -92,  0, 15 ),
+    RPT_4   (  93,  0, 15 ), RPT_4   ( -93,  0, 15 ),
+    RPT_4   (  94,  0, 15 ), RPT_4   ( -94,  0, 15 ),
+    RPT_4   (  95,  0, 15 ), RPT_4   ( -95,  0, 15 ),
+    RPT_4   (  96,  0, 15 ), RPT_4   ( -96,  0, 15 ),
+    RPT_4   (  97,  0, 15 ), RPT_4   ( -97,  0, 15 ),
+    RPT_4   (  98,  0, 15 ), RPT_4   ( -98,  0, 15 ),
+    RPT_4   (  99,  0, 15 ), RPT_4   ( -99,  0, 15 ),
+    RPT_4   ( 100,  0, 15 ), RPT_4   (-100,  0, 15 ),
+    RPT_4   ( 101,  0, 15 ), RPT_4   (-101,  0, 15 ),
+    RPT_4   ( 102,  0, 15 ), RPT_4   (-102,  0, 15 ),
+    RPT_4   ( 103,  0, 15 ), RPT_4   (-103,  0, 15 ),
+    RPT_4   ( 104,  0, 15 ), RPT_4   (-104,  0, 15 ),
+    RPT_4   ( 105,  0, 15 ), RPT_4   (-105,  0, 15 ),
+    RPT_4   ( 106,  0, 15 ), RPT_4   (-106,  0, 15 ),
+    RPT_4   ( 107,  0, 15 ), RPT_4   (-107,  0, 15 ),
+    RPT_4   ( 108,  0, 15 ), RPT_4   (-108,  0, 15 ),
+    RPT_4   ( 109,  0, 15 ), RPT_4   (-109,  0, 15 ),
+    RPT_4   ( 110,  0, 15 ), RPT_4   (-110,  0, 15 ),
+    RPT_4   ( 111,  0, 15 ), RPT_4   (-111,  0, 15 ),
+    RPT_4   ( 112,  0, 15 ), RPT_4   (-112,  0, 15 ),
+    RPT_4   ( 113,  0, 15 ), RPT_4   (-113,  0, 15 ),
+    RPT_4   ( 114,  0, 15 ), RPT_4   (-114,  0, 15 ),
+    RPT_4   ( 115,  0, 15 ), RPT_4   (-115,  0, 15 ),
+    RPT_4   ( 116,  0, 15 ), RPT_4   (-116,  0, 15 ),
+    RPT_4   ( 117,  0, 15 ), RPT_4   (-117,  0, 15 ),
+    RPT_4   ( 118,  0, 15 ), RPT_4   (-118,  0, 15 ),
+    RPT_4   ( 119,  0, 15 ), RPT_4   (-119,  0, 15 ),
+    RPT_4   ( 120,  0, 15 ), RPT_4   (-120,  0, 15 ),
+    RPT_4   ( 121,  0, 15 ), RPT_4   (-121,  0, 15 ),
+    RPT_4   ( 122,  0, 15 ), RPT_4   (-122,  0, 15 ),
+    RPT_4   ( 123,  0, 15 ), RPT_4   (-123,  0, 15 ),
+    RPT_4   ( 124,  0, 15 ), RPT_4   (-124,  0, 15 ),
+    RPT_4   ( 125,  0, 15 ), RPT_4   (-125,  0, 15 ),
+    RPT_4   ( 126,  0, 15 ), RPT_4   (-126,  0, 15 ),
+    RPT_4   ( 127,  0, 15 ), RPT_4   (-127,  0, 15 ),
+    RPT_4   ( 128,  0, 15 ), RPT_4   (-128,  0, 15 ),
+    RPT_4   ( 129,  0, 15 ), RPT_4   (-129,  0, 15 ),
+    RPT_4   ( 130,  0, 15 ), RPT_4   (-130,  0, 15 ),
+    RPT_4   ( 131,  0, 15 ), RPT_4   (-131,  0, 15 ),
+    RPT_4   ( 132,  0, 15 ), RPT_4   (-132,  0, 15 ),
+    RPT_4   ( 133,  0, 15 ), RPT_4   (-133,  0, 15 ),
+    RPT_4   ( 134,  0, 15 ), RPT_4   (-134,  0, 15 ),
+    RPT_4   ( 135,  0, 15 ), RPT_4   (-135,  0, 15 ),
+    RPT_4   ( 136,  0, 15 ), RPT_4   (-136,  0, 15 ),
+    RPT_4   ( 137,  0, 15 ), RPT_4   (-137,  0, 15 ),
+    RPT_4   ( 138,  0, 15 ), RPT_4   (-138,  0, 15 ),
+    RPT_4   ( 139,  0, 15 ), RPT_4   (-139,  0, 15 ),
+    RPT_4   ( 140,  0, 15 ), RPT_4   (-140,  0, 15 ),
+    RPT_4   ( 141,  0, 15 ), RPT_4   (-141,  0, 15 ),
+    RPT_4   ( 142,  0, 15 ), RPT_4   (-142,  0, 15 ),
+    RPT_4   ( 143,  0, 15 ), RPT_4   (-143,  0, 15 ),
+    RPT_4   ( 144,  0, 15 ), RPT_4   (-144,  0, 15 ),
+    RPT_4   ( 145,  0, 15 ), RPT_4   (-145,  0, 15 ),
+    RPT_4   ( 146,  0, 15 ), RPT_4   (-146,  0, 15 ),
+    RPT_4   ( 147,  0, 15 ), RPT_4   (-147,  0, 15 ),
+    RPT_4   ( 148,  0, 15 ), RPT_4   (-148,  0, 15 ),
+    RPT_4   ( 149,  0, 15 ), RPT_4   (-149,  0, 15 ),
+    RPT_4   ( 150,  0, 15 ), RPT_4   (-150,  0, 15 ),
+    RPT_4   ( 151,  0, 15 ), RPT_4   (-151,  0, 15 ),
+    RPT_4   ( 152,  0, 15 ), RPT_4   (-152,  0, 15 ),
+    RPT_4   ( 153,  0, 15 ), RPT_4   (-153,  0, 15 ),
+    RPT_4   ( 154,  0, 15 ), RPT_4   (-154,  0, 15 ),
+    RPT_4   ( 155,  0, 15 ), RPT_4   (-155,  0, 15 ),
+    RPT_4   ( 156,  0, 15 ), RPT_4   (-156,  0, 15 ),
+    RPT_4   ( 157,  0, 15 ), RPT_4   (-157,  0, 15 ),
+    RPT_4   ( 158,  0, 15 ), RPT_4   (-158,  0, 15 ),
+    RPT_4   ( 159,  0, 15 ), RPT_4   (-159,  0, 15 ),
+    RPT_4   ( 160,  0, 15 ), RPT_4   (-160,  0, 15 ),
+    RPT_4   ( 161,  0, 15 ), RPT_4   (-161,  0, 15 ),
+    RPT_4   ( 162,  0, 15 ), RPT_4   (-162,  0, 15 ),
+    RPT_4   ( 163,  0, 15 ), RPT_4   (-163,  0, 15 ),
+    RPT_4   ( 164,  0, 15 ), RPT_4   (-164,  0, 15 ),
+    RPT_4   ( 165,  0, 15 ), RPT_4   (-165,  0, 15 ),
+    RPT_4   ( 166,  0, 15 ), RPT_4   (-166,  0, 15 ),
+    RPT_4   ( 167,  0, 15 ), RPT_4   (-167,  0, 15 ),
+    RPT_4   ( 168,  0, 15 ), RPT_4   (-168,  0, 15 ),
+    RPT_4   ( 169,  0, 15 ), RPT_4   (-169,  0, 15 ),
+    RPT_4   ( 170,  0, 15 ), RPT_4   (-170,  0, 15 ),
+    RPT_4   ( 171,  0, 15 ), RPT_4   (-171,  0, 15 ),
+    RPT_4   ( 172,  0, 15 ), RPT_4   (-172,  0, 15 ),
+    RPT_4   ( 173,  0, 15 ), RPT_4   (-173,  0, 15 ),
+    RPT_4   ( 174,  0, 15 ), RPT_4   (-174,  0, 15 ),
+    RPT_4   ( 175,  0, 15 ), RPT_4   (-175,  0, 15 ),
+    RPT_4   ( 176,  0, 15 ), RPT_4   (-176,  0, 15 ),
+    RPT_4   ( 177,  0, 15 ), RPT_4   (-177,  0, 15 ),
+    RPT_4   ( 178,  0, 15 ), RPT_4   (-178,  0, 15 ),
+    RPT_4   ( 179,  0, 15 ), RPT_4   (-179,  0, 15 ),
+    RPT_4   ( 180,  0, 15 ), RPT_4   (-180,  0, 15 ),
+    RPT_4   ( 181,  0, 15 ), RPT_4   (-181,  0, 15 ),
+    RPT_4   ( 182,  0, 15 ), RPT_4   (-182,  0, 15 ),
+    RPT_4   ( 183,  0, 15 ), RPT_4   (-183,  0, 15 ),
+    RPT_4   ( 184,  0, 15 ), RPT_4   (-184,  0, 15 ),
+    RPT_4   ( 185,  0, 15 ), RPT_4   (-185,  0, 15 ),
+    RPT_4   ( 186,  0, 15 ), RPT_4   (-186,  0, 15 ),
+    RPT_4   ( 187,  0, 15 ), RPT_4   (-187,  0, 15 ),
+    RPT_4   ( 188,  0, 15 ), RPT_4   (-188,  0, 15 ),
+    RPT_4   ( 189,  0, 15 ), RPT_4   (-189,  0, 15 ),
+    RPT_4   ( 190,  0, 15 ), RPT_4   (-190,  0, 15 ),
+    RPT_4   ( 191,  0, 15 ), RPT_4   (-191,  0, 15 ),
+    RPT_4   ( 192,  0, 15 ), RPT_4   (-192,  0, 15 ),
+    RPT_4   ( 193,  0, 15 ), RPT_4   (-193,  0, 15 ),
+    RPT_4   ( 194,  0, 15 ), RPT_4   (-194,  0, 15 ),
+    RPT_4   ( 195,  0, 15 ), RPT_4   (-195,  0, 15 ),
+    RPT_4   ( 196,  0, 15 ), RPT_4   (-196,  0, 15 ),
+    RPT_4   ( 197,  0, 15 ), RPT_4   (-197,  0, 15 ),
+    RPT_4   ( 198,  0, 15 ), RPT_4   (-198,  0, 15 ),
+    RPT_4   ( 199,  0, 15 ), RPT_4   (-199,  0, 15 ),
+    RPT_4   ( 200,  0, 15 ), RPT_4   (-200,  0, 15 ),
+    RPT_4   ( 201,  0, 15 ), RPT_4   (-201,  0, 15 ),
+    RPT_4   ( 202,  0, 15 ), RPT_4   (-202,  0, 15 ),
+    RPT_4   ( 203,  0, 15 ), RPT_4   (-203,  0, 15 ),
+    RPT_4   ( 204,  0, 15 ), RPT_4   (-204,  0, 15 ),
+    RPT_4   ( 205,  0, 15 ), RPT_4   (-205,  0, 15 ),
+    RPT_4   ( 206,  0, 15 ), RPT_4   (-206,  0, 15 ),
+    RPT_4   ( 207,  0, 15 ), RPT_4   (-207,  0, 15 ),
+    RPT_4   ( 208,  0, 15 ), RPT_4   (-208,  0, 15 ),
+    RPT_4   ( 209,  0, 15 ), RPT_4   (-209,  0, 15 ),
+    RPT_4   ( 210,  0, 15 ), RPT_4   (-210,  0, 15 ),
+    RPT_4   ( 211,  0, 15 ), RPT_4   (-211,  0, 15 ),
+    RPT_4   ( 212,  0, 15 ), RPT_4   (-212,  0, 15 ),
+    RPT_4   ( 213,  0, 15 ), RPT_4   (-213,  0, 15 ),
+    RPT_4   ( 214,  0, 15 ), RPT_4   (-214,  0, 15 ),
+    RPT_4   ( 215,  0, 15 ), RPT_4   (-215,  0, 15 ),
+    RPT_4   ( 216,  0, 15 ), RPT_4   (-216,  0, 15 ),
+    RPT_4   ( 217,  0, 15 ), RPT_4   (-217,  0, 15 ),
+    RPT_4   ( 218,  0, 15 ), RPT_4   (-218,  0, 15 ),
+    RPT_4   ( 219,  0, 15 ), RPT_4   (-219,  0, 15 ),
+    RPT_4   ( 220,  0, 15 ), RPT_4   (-220,  0, 15 ),
+    RPT_4   ( 221,  0, 15 ), RPT_4   (-221,  0, 15 ),
+    RPT_4   ( 222,  0, 15 ), RPT_4   (-222,  0, 15 ),
+    RPT_4   ( 223,  0, 15 ), RPT_4   (-223,  0, 15 ),
+    RPT_4   ( 224,  0, 15 ), RPT_4   (-224,  0, 15 ),
+    RPT_4   ( 225,  0, 15 ), RPT_4   (-225,  0, 15 ),
+    RPT_4   ( 226,  0, 15 ), RPT_4   (-226,  0, 15 ),
+    RPT_4   ( 227,  0, 15 ), RPT_4   (-227,  0, 15 ),
+    RPT_4   ( 228,  0, 15 ), RPT_4   (-228,  0, 15 ),
+    RPT_4   ( 229,  0, 15 ), RPT_4   (-229,  0, 15 ),
+    RPT_4   ( 230,  0, 15 ), RPT_4   (-230,  0, 15 ),
+    RPT_4   ( 231,  0, 15 ), RPT_4   (-231,  0, 15 ),
+    RPT_4   ( 232,  0, 15 ), RPT_4   (-232,  0, 15 ),
+    RPT_4   ( 233,  0, 15 ), RPT_4   (-233,  0, 15 ),
+    RPT_4   ( 234,  0, 15 ), RPT_4   (-234,  0, 15 ),
+    RPT_4   ( 235,  0, 15 ), RPT_4   (-235,  0, 15 ),
+    RPT_4   ( 236,  0, 15 ), RPT_4   (-236,  0, 15 ),
+    RPT_4   ( 237,  0, 15 ), RPT_4   (-237,  0, 15 ),
+    RPT_4   ( 238,  0, 15 ), RPT_4   (-238,  0, 15 ),
+    RPT_4   ( 239,  0, 15 ), RPT_4   (-239,  0, 15 ),
+    RPT_4   ( 240,  0, 15 ), RPT_4   (-240,  0, 15 ),
+    RPT_4   ( 241,  0, 15 ), RPT_4   (-241,  0, 15 ),
+    RPT_4   ( 242,  0, 15 ), RPT_4   (-242,  0, 15 ),
+    RPT_4   ( 243,  0, 15 ), RPT_4   (-243,  0, 15 ),
+    RPT_4   ( 244,  0, 15 ), RPT_4   (-244,  0, 15 ),
+    RPT_4   ( 245,  0, 15 ), RPT_4   (-245,  0, 15 ),
+    RPT_4   ( 246,  0, 15 ), RPT_4   (-246,  0, 15 ),
+    RPT_4   ( 247,  0, 15 ), RPT_4   (-247,  0, 15 ),
+    RPT_4   ( 248,  0, 15 ), RPT_4   (-248,  0, 15 ),
+    RPT_4   ( 249,  0, 15 ), RPT_4   (-249,  0, 15 ),
+    RPT_4   ( 250,  0, 15 ), RPT_4   (-250,  0, 15 ),
+    RPT_4   ( 251,  0, 15 ), RPT_4   (-251,  0, 15 ),
+    RPT_4   ( 252,  0, 15 ), RPT_4   (-252,  0, 15 ),
+    RPT_4   ( 253,  0, 15 ), RPT_4   (-253,  0, 15 ),
+    RPT_4   ( 254,  0, 15 ), RPT_4   (-254,  0, 15 ),
+    RPT_4   ( 255,  0, 15 ), RPT_4   (-255,  0, 15 ),
+    RPT_32  (  49,  0, 12 ), RPT_32  ( -49,  0, 12 ),
+    RPT_32  (  50,  0, 12 ), RPT_32  ( -50,  0, 12 ),
+    RPT_32  (  51,  0, 12 ), RPT_32  ( -51,  0, 12 ),
+    RPT_32  (  52,  0, 12 ), RPT_32  ( -52,  0, 12 ),
+    RPT_32  (  53,  0, 12 ), RPT_32  ( -53,  0, 12 ),
+    RPT_32  (  54,  0, 12 ), RPT_32  ( -54,  0, 12 ),
+    RPT_32  (  55,  0, 12 ), RPT_32  ( -55,  0, 12 ),
+    RPT_32  (  56,  0, 12 ), RPT_32  ( -56,  0, 12 ),
+    RPT_32  (  57,  0, 12 ), RPT_32  ( -57,  0, 12 ),
+    RPT_32  (  58,  0, 12 ), RPT_32  ( -58,  0, 12 ),
+    RPT_32  (  59,  0, 12 ), RPT_32  ( -59,  0, 12 ),
+    RPT_32  (  60,  0, 12 ), RPT_32  ( -60,  0, 12 ),
+    RPT_32  (  61,  0, 12 ), RPT_32  ( -61,  0, 12 ),
+    RPT_32  (  62,  0, 12 ), RPT_32  ( -62,  0, 12 ),
+    RPT_32  (  63,  0, 12 ), RPT_32  ( -63,  0, 12 ),
+    RPT_32  (  17,  1, 12 ), RPT_32  ( -17,  1, 12 ),
+    RPT_32  (  18,  1, 12 ), RPT_32  ( -18,  1, 12 ),
+    RPT_32  (  19,  1, 12 ), RPT_32  ( -19,  1, 12 ),
+    RPT_32  (  20,  1, 12 ), RPT_32  ( -20,  1, 12 ),
+    RPT_32  (  21,  1, 12 ), RPT_32  ( -21,  1, 12 ),
+    RPT_32  (  22,  1, 12 ), RPT_32  ( -22,  1, 12 ),
+    RPT_32  (  23,  1, 12 ), RPT_32  ( -23,  1, 12 ),
+    RPT_32  (  24,  1, 12 ), RPT_32  ( -24,  1, 12 ),
+    RPT_32  (   9,  2, 12 ), RPT_32  (  -9,  2, 12 ),
+    RPT_32  (  10,  2, 12 ), RPT_32  ( -10,  2, 12 ),
+    RPT_32  (  11,  2, 12 ), RPT_32  ( -11,  2, 12 ),
+    RPT_32  (  12,  2, 12 ), RPT_32  ( -12,  2, 12 ),
+    RPT_32  (   7,  3, 12 ), RPT_32  (  -7,  3, 12 ),
+    RPT_32  (   8,  3, 12 ), RPT_32  (  -8,  3, 12 ),
+    RPT_32  (   5,  4, 12 ), RPT_32  (  -5,  4, 12 ),
+    RPT_32  (   6,  4, 12 ), RPT_32  (  -6,  4, 12 ),
+    RPT_32  (   3,  5, 12 ), RPT_32  (  -3,  5, 12 ),
+    RPT_32  (   4,  5, 12 ), RPT_32  (  -4,  5, 12 ),
+    RPT_32  (   5,  5, 12 ), RPT_32  (  -5,  5, 12 ),
+    RPT_32  (   6,  5, 12 ), RPT_32  (  -6,  5, 12 ),
+    RPT_32  (   3,  6, 12 ), RPT_32  (  -3,  6, 12 ),
+    RPT_32  (   4,  6, 12 ), RPT_32  (  -4,  6, 12 ),
+    RPT_32  (   2,  7, 12 ), RPT_32  (  -2,  7, 12 ),
+    RPT_32  (   2,  8, 12 ), RPT_32  (  -2,  8, 12 ),
+    RPT_32  (   2,  9, 12 ), RPT_32  (  -2,  9, 12 ),
+    RPT_32  (   2, 10, 12 ), RPT_32  (  -2, 10, 12 ),
+    RPT_32  (   1, 13, 12 ), RPT_32  (  -1, 13, 12 ),
+    RPT_32  (   1, 14, 12 ), RPT_32  (  -1, 14, 12 ),
+    {    0,  0, 17 }, {    0,  1, 17 }, {    0,  2, 17 }, {    0,  3, 17 },
+    {    0,  4, 17 }, {    0,  5, 17 }, {    0,  6, 17 }, {    0,  7, 17 },
+    {    0,  8, 17 }, {    0,  9, 17 }, {    0, 10, 17 }, {    0, 11, 17 },
+    {    0, 12, 17 }, {    0, 13, 17 }, {    0, 14, 17 }, {    0, 15, 17 },
+    {    0, 16, 17 }, {    0, 17, 17 }, {    0, 18, 17 }, {    0, 19, 17 },
+    {    0, 20, 17 }, {    0, 21, 17 }, {    0, 22, 17 }, {    0, 23, 17 },
+    {    0, 24, 17 }, {    0, 25, 17 }, {    0, 26, 17 }, {    0, 27, 17 },
+    {    0, 28, 17 }, {    0, 29, 17 }, {    0, 30, 17 }, {    0, 31, 17 },
+    {    0, 32, 17 }, {    0, 33, 17 }, {    0, 34, 17 }, {    0, 35, 17 },
+    {    0, 36, 17 }, {    0, 37, 17 }, {    0, 38, 17 }, {    0, 39, 17 },
+    {    0, 40, 17 }, {    0, 41, 17 }, {    0, 42, 17 }, {    0, 43, 17 },
+    {    0, 44, 17 }, {    0, 45, 17 }, {    0, 46, 17 }, {    0, 47, 17 },
+    {    0, 48, 17 }, {    0, 49, 17 }, {    0, 50, 17 }, {    0, 51, 17 },
+    {    0, 52, 17 }, {    0, 53, 17 }, {    0, 54, 17 }, {    0, 55, 17 },
+    {    0, 56, 17 }, {    0, 57, 17 }, {    0, 58, 17 }, {    0, 59, 17 },
+    {    0, 60, 17 }, {    0, 61, 17 }, {    0, 62, 17 }, {    0, 63, 17 },
+    RPT_16  (  25,  1, 13 ), RPT_16  ( -25,  1, 13 ),
+    RPT_16  (  26,  1, 13 ), RPT_16  ( -26,  1, 13 ),
+    RPT_16  (  27,  1, 13 ), RPT_16  ( -27,  1, 13 ),
+    RPT_16  (  28,  1, 13 ), RPT_16  ( -28,  1, 13 ),
+    RPT_16  (  29,  1, 13 ), RPT_16  ( -29,  1, 13 ),
+    RPT_16  (  30,  1, 13 ), RPT_16  ( -30,  1, 13 ),
+    RPT_16  (  31,  1, 13 ), RPT_16  ( -31,  1, 13 ),
+    RPT_16  (  32,  1, 13 ), RPT_16  ( -32,  1, 13 ),
+    RPT_16  (  13,  2, 13 ), RPT_16  ( -13,  2, 13 ),
+    RPT_16  (  14,  2, 13 ), RPT_16  ( -14,  2, 13 ),
+    RPT_16  (  15,  2, 13 ), RPT_16  ( -15,  2, 13 ),
+    RPT_16  (  16,  2, 13 ), RPT_16  ( -16,  2, 13 ),
+    RPT_16  (   9,  3, 13 ), RPT_16  (  -9,  3, 13 ),
+    RPT_16  (  10,  3, 13 ), RPT_16  ( -10,  3, 13 ),
+    RPT_16  (  11,  3, 13 ), RPT_16  ( -11,  3, 13 ),
+    RPT_16  (   7,  4, 13 ), RPT_16  (  -7,  4, 13 ),
+    RPT_16  (   3,  7, 13 ), RPT_16  (  -3,  7, 13 ),
+    RPT_16  (   4,  7, 13 ), RPT_16  (  -4,  7, 13 ),
+    RPT_16  (   3,  8, 13 ), RPT_16  (  -3,  8, 13 ),
+    RPT_16  (   4,  8, 13 ), RPT_16  (  -4,  8, 13 ),
+    RPT_16  (   3,  9, 13 ), RPT_16  (  -3,  9, 13 ),
+    RPT_16  (   2, 11, 13 ), RPT_16  (  -2, 11, 13 ),
+    RPT_16  (   2, 12, 13 ), RPT_16  (  -2, 12, 13 ),
+    RPT_32  (   0, 14, 12 ),
+};
+
+static const HQXLUT ac16_lut[] = {
+    RPT_256 (   1,  0,  3 ), RPT_256 (  -1,  0,  3 ),
+    RPT_128 (   2,  0,  4 ), RPT_128 (  -2,  0,  4 ),
+    RPT_64  (   3,  0,  5 ), RPT_64  (  -3,  0,  5 ),
+    RPT_64  (   4,  0,  5 ), RPT_64  (  -4,  0,  5 ),
+    RPT_64  (   1,  1,  5 ), RPT_64  (  -1,  1,  5 ),
+    RPT_128 (   0, 64,  4 ), RPT_32  (   5,  0,  6 ),
+    RPT_32  (  -5,  0,  6 ), RPT_32  (   6,  0,  6 ),
+    RPT_32  (  -6,  0,  6 ), RPT_32  (   2,  1,  6 ),
+    RPT_32  (  -2,  1,  6 ), RPT_32  (   1,  2,  6 ),
+    RPT_32  (  -1,  2,  6 ), RPT_16  (   7,  0,  7 ),
+    RPT_16  (  -7,  0,  7 ), RPT_16  (   8,  0,  7 ),
+    RPT_16  (  -8,  0,  7 ), RPT_16  (   9,  0,  7 ),
+    RPT_16  (  -9,  0,  7 ), RPT_16  (   3,  1,  7 ),
+    RPT_16  (  -3,  1,  7 ), RPT_16  (   1,  3,  7 ),
+    RPT_16  (  -1,  3,  7 ), RPT_16  (   1,  4,  7 ),
+    RPT_16  (  -1,  4,  7 ), RPT_8   (  10,  0,  8 ),
+    RPT_8   ( -10,  0,  8 ), RPT_8   (  11,  0,  8 ),
+    RPT_8   ( -11,  0,  8 ), RPT_8   (  12,  0,  8 ),
+    RPT_8   ( -12,  0,  8 ), RPT_8   (   4,  1,  8 ),
+    RPT_8   (  -4,  1,  8 ), RPT_8   (   2,  2,  8 ),
+    RPT_8   (  -2,  2,  8 ), RPT_8   (   1,  5,  8 ),
+    RPT_8   (  -1,  5,  8 ), RPT_8   (   1,  6,  8 ),
+    RPT_8   (  -1,  6,  8 ), RPT_4   (  13,  0,  9 ),
+    RPT_4   ( -13,  0,  9 ), RPT_4   (  14,  0,  9 ),
+    RPT_4   ( -14,  0,  9 ), RPT_4   (  15,  0,  9 ),
+    RPT_4   ( -15,  0,  9 ), RPT_4   (  16,  0,  9 ),
+    RPT_4   ( -16,  0,  9 ), RPT_4   (  17,  0,  9 ),
+    RPT_4   ( -17,  0,  9 ), RPT_4   (   5,  1,  9 ),
+    RPT_4   (  -5,  1,  9 ), RPT_4   (   2,  3,  9 ),
+    RPT_4   (  -2,  3,  9 ), RPT_4   (   1,  7,  9 ),
+    RPT_4   (  -1,  7,  9 ), RPT_4   (   1,  8,  9 ),
+    RPT_4   (  -1,  8,  9 ), RPT_4   (   1,  9,  9 ),
+    RPT_4   (  -1,  9,  9 ), RPT_4   (   1, 10,  9 ),
+    RPT_4   (  -1, 10,  9 ), RPT_4   (   0,  0,  9 ),
+    RPT_2   (  18,  0, 10 ), RPT_2   ( -18,  0, 10 ),
+    RPT_2   (  19,  0, 10 ), RPT_2   ( -19,  0, 10 ),
+    RPT_2   (  20,  0, 10 ), RPT_2   ( -20,  0, 10 ),
+    RPT_2   (  21,  0, 10 ), RPT_2   ( -21,  0, 10 ),
+    RPT_2   (  22,  0, 10 ), RPT_2   ( -22,  0, 10 ),
+    RPT_2   (   6,  1, 10 ), RPT_2   (  -6,  1, 10 ),
+    RPT_2   (   7,  1, 10 ), RPT_2   (  -7,  1, 10 ),
+    RPT_2   (   3,  2, 10 ), RPT_2   (  -3,  2, 10 ),
+    RPT_2   (   2,  4, 10 ), RPT_2   (  -2,  4, 10 ),
+    RPT_2   (   2,  5, 10 ), RPT_2   (  -2,  5, 10 ),
+    RPT_2   (   1, 11, 10 ), RPT_2   (  -1, 11, 10 ),
+    RPT_2   (   1, 12, 10 ), RPT_2   (  -1, 12, 10 ),
+    RPT_2   (   1, 13, 10 ), RPT_2   (  -1, 13, 10 ),
+    { 2048,  0, -1 }, { 2112,  0, -1 }, { 2176,  0, -1 }, { 2240,  0, -1 },
+    { 2304,  0, -1 }, { 2368,  0, -1 }, { 2432,  0, -1 }, { 2496,  0, -1 },
+    {   23,  0, 11 }, {  -23,  0, 11 }, {   24,  0, 11 }, {  -24,  0, 11 },
+    {   25,  0, 11 }, {  -25,  0, 11 }, {   26,  0, 11 }, {  -26,  0, 11 },
+    {   27,  0, 11 }, {  -27,  0, 11 }, {   28,  0, 11 }, {  -28,  0, 11 },
+    {    8,  1, 11 }, {   -8,  1, 11 }, {    9,  1, 11 }, {   -9,  1, 11 },
+    {    4,  2, 11 }, {   -4,  2, 11 }, {    3,  3, 11 }, {   -3,  3, 11 },
+    {    3,  4, 11 }, {   -3,  4, 11 }, {    2,  6, 11 }, {   -2,  6, 11 },
+    {    2,  7, 11 }, {   -2,  7, 11 }, { 2560,  0, -1 }, { 2624,  0, -1 },
+    { 2688,  0, -1 }, { 2752,  0, -1 }, { 2816,  0, -1 }, { 2880,  0, -1 },
+    { 2944,  0, -1 }, {    0,  1, 11 }, { 3008,  0, -1 }, { 3072,  0, -1 },
+    { 3136,  0, -1 }, {    0,  2, 11 }, { 3200,  0, -1 }, {    0,  3, 11 },
+    { 3264,  0, -1 }, { 3328,  0, -1 }, { 3392,  0, -1 }, { 3456,  0, -1 },
+    { 3520,  0, -1 }, { 3584,  0, -1 }, { 3648,  0, -1 }, { 3712,  0, -1 },
+    { 3776,  0, -1 }, { 3840,  0, -1 }, { 3904,  0, -1 }, { 3968,  0, -1 },
+    { 4032,  0, -1 }, { 4096,  0, -1 }, { 4160,  0, -1 }, { 4224,  0, -1 },
+    RPT_4   (   0,  0, 15 ), RPT_4   (   0,  1, 15 ),
+    RPT_4   (   0,  2, 15 ), RPT_4   (   0,  3, 15 ),
+    RPT_4   (   0,  4, 15 ), RPT_4   (   0,  5, 15 ),
+    RPT_4   (   0,  6, 15 ), RPT_4   (   0,  7, 15 ),
+    RPT_4   (   0,  8, 15 ), RPT_4   (   0,  9, 15 ),
+    RPT_4   (   0, 10, 15 ), RPT_4   (   0, 11, 15 ),
+    RPT_4   (   0, 12, 15 ), RPT_4   (   0, 13, 15 ),
+    RPT_4   (   0, 14, 15 ), RPT_4   (   0, 15, 15 ),
+    RPT_4   (   0, 16, 15 ), RPT_4   (   0, 17, 15 ),
+    RPT_4   (   0, 18, 15 ), RPT_4   (   0, 19, 15 ),
+    RPT_4   (   0, 20, 15 ), RPT_4   (   0, 21, 15 ),
+    RPT_4   (   0, 22, 15 ), RPT_4   (   0, 23, 15 ),
+    RPT_4   (   0, 24, 15 ), RPT_4   (   0, 25, 15 ),
+    RPT_4   (   0, 26, 15 ), RPT_4   (   0, 27, 15 ),
+    RPT_4   (   0, 28, 15 ), RPT_4   (   0, 29, 15 ),
+    RPT_4   (   0, 30, 15 ), RPT_4   (   0, 31, 15 ),
+    RPT_4   (   0, 32, 15 ), RPT_4   (   0, 33, 15 ),
+    RPT_4   (   0, 34, 15 ), RPT_4   (   0, 35, 15 ),
+    RPT_4   (   0, 36, 15 ), RPT_4   (   0, 37, 15 ),
+    RPT_4   (   0, 38, 15 ), RPT_4   (   0, 39, 15 ),
+    RPT_4   (   0, 40, 15 ), RPT_4   (   0, 41, 15 ),
+    RPT_4   (   0, 42, 15 ), RPT_4   (   0, 43, 15 ),
+    RPT_4   (   0, 44, 15 ), RPT_4   (   0, 45, 15 ),
+    RPT_4   (   0, 46, 15 ), RPT_4   (   0, 47, 15 ),
+    RPT_4   (   0, 48, 15 ), RPT_4   (   0, 49, 15 ),
+    RPT_4   (   0, 50, 15 ), RPT_4   (   0, 51, 15 ),
+    RPT_4   (   0, 52, 15 ), RPT_4   (   0, 53, 15 ),
+    RPT_4   (   0, 54, 15 ), RPT_4   (   0, 55, 15 ),
+    RPT_4   (   0, 56, 15 ), RPT_4   (   0, 57, 15 ),
+    RPT_4   (   0, 58, 15 ), RPT_4   (   0, 59, 15 ),
+    RPT_4   (   0, 60, 15 ), RPT_4   (   0, 61, 15 ),
+    RPT_4   (   0, 62, 15 ), RPT_4   (   0, 63, 15 ),
+    RPT_2   (   0,  0, 16 ), {    1,  0, 17 }, {   -1,  0, 17 },
+    {    2,  0, 17 }, {   -2,  0, 17 }, {    3,  0, 17 }, {   -3,  0, 17 },
+    {    4,  0, 17 }, {   -4,  0, 17 }, {    5,  0, 17 }, {   -5,  0, 17 },
+    {    6,  0, 17 }, {   -6,  0, 17 }, {    7,  0, 17 }, {   -7,  0, 17 },
+    {    8,  0, 17 }, {   -8,  0, 17 }, {    9,  0, 17 }, {   -9,  0, 17 },
+    {   10,  0, 17 }, {  -10,  0, 17 }, {   11,  0, 17 }, {  -11,  0, 17 },
+    {   12,  0, 17 }, {  -12,  0, 17 }, {   13,  0, 17 }, {  -13,  0, 17 },
+    {   14,  0, 17 }, {  -14,  0, 17 }, {   15,  0, 17 }, {  -15,  0, 17 },
+    {   16,  0, 17 }, {  -16,  0, 17 }, {   17,  0, 17 }, {  -17,  0, 17 },
+    {   18,  0, 17 }, {  -18,  0, 17 }, {   19,  0, 17 }, {  -19,  0, 17 },
+    {   20,  0, 17 }, {  -20,  0, 17 }, {   21,  0, 17 }, {  -21,  0, 17 },
+    {   22,  0, 17 }, {  -22,  0, 17 }, {   23,  0, 17 }, {  -23,  0, 17 },
+    {   24,  0, 17 }, {  -24,  0, 17 }, {   25,  0, 17 }, {  -25,  0, 17 },
+    {   26,  0, 17 }, {  -26,  0, 17 }, {   27,  0, 17 }, {  -27,  0, 17 },
+    {   28,  0, 17 }, {  -28,  0, 17 }, {   29,  0, 17 }, {  -29,  0, 17 },
+    {   30,  0, 17 }, {  -30,  0, 17 }, {   31,  0, 17 }, {  -31,  0, 17 },
+    {   32,  0, 17 }, {  -32,  0, 17 }, {   33,  0, 17 }, {  -33,  0, 17 },
+    {   34,  0, 17 }, {  -34,  0, 17 }, {   35,  0, 17 }, {  -35,  0, 17 },
+    {   36,  0, 17 }, {  -36,  0, 17 }, {   37,  0, 17 }, {  -37,  0, 17 },
+    {   38,  0, 17 }, {  -38,  0, 17 }, {   39,  0, 17 }, {  -39,  0, 17 },
+    {   40,  0, 17 }, {  -40,  0, 17 }, {   41,  0, 17 }, {  -41,  0, 17 },
+    {   42,  0, 17 }, {  -42,  0, 17 }, {   43,  0, 17 }, {  -43,  0, 17 },
+    {   44,  0, 17 }, {  -44,  0, 17 }, {   45,  0, 17 }, {  -45,  0, 17 },
+    {   46,  0, 17 }, {  -46,  0, 17 }, {   47,  0, 17 }, {  -47,  0, 17 },
+    {   48,  0, 17 }, {  -48,  0, 17 }, {   49,  0, 17 }, {  -49,  0, 17 },
+    {   50,  0, 17 }, {  -50,  0, 17 }, {   51,  0, 17 }, {  -51,  0, 17 },
+    {   52,  0, 17 }, {  -52,  0, 17 }, {   53,  0, 17 }, {  -53,  0, 17 },
+    {   54,  0, 17 }, {  -54,  0, 17 }, {   55,  0, 17 }, {  -55,  0, 17 },
+    {   56,  0, 17 }, {  -56,  0, 17 }, {   57,  0, 17 }, {  -57,  0, 17 },
+    {   58,  0, 17 }, {  -58,  0, 17 }, {   59,  0, 17 }, {  -59,  0, 17 },
+    {   60,  0, 17 }, {  -60,  0, 17 }, {   61,  0, 17 }, {  -61,  0, 17 },
+    {   62,  0, 17 }, {  -62,  0, 17 }, {   63,  0, 17 }, {  -63,  0, 17 },
+    {   64,  0, 17 }, {  -64,  0, 17 }, {   65,  0, 17 }, {  -65,  0, 17 },
+    {   66,  0, 17 }, {  -66,  0, 17 }, {   67,  0, 17 }, {  -67,  0, 17 },
+    {   68,  0, 17 }, {  -68,  0, 17 }, {   69,  0, 17 }, {  -69,  0, 17 },
+    {   70,  0, 17 }, {  -70,  0, 17 }, {   71,  0, 17 }, {  -71,  0, 17 },
+    {   72,  0, 17 }, {  -72,  0, 17 }, {   73,  0, 17 }, {  -73,  0, 17 },
+    {   74,  0, 17 }, {  -74,  0, 17 }, {   75,  0, 17 }, {  -75,  0, 17 },
+    {   76,  0, 17 }, {  -76,  0, 17 }, {   77,  0, 17 }, {  -77,  0, 17 },
+    {   78,  0, 17 }, {  -78,  0, 17 }, {   79,  0, 17 }, {  -79,  0, 17 },
+    {   80,  0, 17 }, {  -80,  0, 17 }, {   81,  0, 17 }, {  -81,  0, 17 },
+    {   82,  0, 17 }, {  -82,  0, 17 }, {   83,  0, 17 }, {  -83,  0, 17 },
+    {   84,  0, 17 }, {  -84,  0, 17 }, {   85,  0, 17 }, {  -85,  0, 17 },
+    {   86,  0, 17 }, {  -86,  0, 17 }, {   87,  0, 17 }, {  -87,  0, 17 },
+    {   88,  0, 17 }, {  -88,  0, 17 }, {   89,  0, 17 }, {  -89,  0, 17 },
+    {   90,  0, 17 }, {  -90,  0, 17 }, {   91,  0, 17 }, {  -91,  0, 17 },
+    {   92,  0, 17 }, {  -92,  0, 17 }, {   93,  0, 17 }, {  -93,  0, 17 },
+    {   94,  0, 17 }, {  -94,  0, 17 }, {   95,  0, 17 }, {  -95,  0, 17 },
+    {   96,  0, 17 }, {  -96,  0, 17 }, {   97,  0, 17 }, {  -97,  0, 17 },
+    {   98,  0, 17 }, {  -98,  0, 17 }, {   99,  0, 17 }, {  -99,  0, 17 },
+    {  100,  0, 17 }, { -100,  0, 17 }, {  101,  0, 17 }, { -101,  0, 17 },
+    {  102,  0, 17 }, { -102,  0, 17 }, {  103,  0, 17 }, { -103,  0, 17 },
+    {  104,  0, 17 }, { -104,  0, 17 }, {  105,  0, 17 }, { -105,  0, 17 },
+    {  106,  0, 17 }, { -106,  0, 17 }, {  107,  0, 17 }, { -107,  0, 17 },
+    {  108,  0, 17 }, { -108,  0, 17 }, {  109,  0, 17 }, { -109,  0, 17 },
+    {  110,  0, 17 }, { -110,  0, 17 }, {  111,  0, 17 }, { -111,  0, 17 },
+    {  112,  0, 17 }, { -112,  0, 17 }, {  113,  0, 17 }, { -113,  0, 17 },
+    {  114,  0, 17 }, { -114,  0, 17 }, {  115,  0, 17 }, { -115,  0, 17 },
+    {  116,  0, 17 }, { -116,  0, 17 }, {  117,  0, 17 }, { -117,  0, 17 },
+    {  118,  0, 17 }, { -118,  0, 17 }, {  119,  0, 17 }, { -119,  0, 17 },
+    {  120,  0, 17 }, { -120,  0, 17 }, {  121,  0, 17 }, { -121,  0, 17 },
+    {  122,  0, 17 }, { -122,  0, 17 }, {  123,  0, 17 }, { -123,  0, 17 },
+    {  124,  0, 17 }, { -124,  0, 17 }, {  125,  0, 17 }, { -125,  0, 17 },
+    {  126,  0, 17 }, { -126,  0, 17 }, {  127,  0, 17 }, { -127,  0, 17 },
+    RPT_32  (  29,  0, 12 ), RPT_32  ( -29,  0, 12 ),
+    RPT_32  (  30,  0, 12 ), RPT_32  ( -30,  0, 12 ),
+    RPT_32  (  31,  0, 12 ), RPT_32  ( -31,  0, 12 ),
+    RPT_32  (  32,  0, 12 ), RPT_32  ( -32,  0, 12 ),
+    RPT_32  (  33,  0, 12 ), RPT_32  ( -33,  0, 12 ),
+    RPT_32  (  34,  0, 12 ), RPT_32  ( -34,  0, 12 ),
+    RPT_32  (  35,  0, 12 ), RPT_32  ( -35,  0, 12 ),
+    RPT_32  (  10,  1, 12 ), RPT_32  ( -10,  1, 12 ),
+    RPT_32  (  11,  1, 12 ), RPT_32  ( -11,  1, 12 ),
+    RPT_32  (  12,  1, 12 ), RPT_32  ( -12,  1, 12 ),
+    RPT_32  (   5,  2, 12 ), RPT_32  (  -5,  2, 12 ),
+    RPT_32  (   4,  3, 12 ), RPT_32  (  -4,  3, 12 ),
+    RPT_32  (   3,  5, 12 ), RPT_32  (  -3,  5, 12 ),
+    RPT_32  (   2,  8, 12 ), RPT_32  (  -2,  8, 12 ),
+    RPT_32  (   2,  9, 12 ), RPT_32  (  -2,  9, 12 ),
+    RPT_32  (   1, 14, 12 ), RPT_32  (  -1, 14, 12 ),
+    RPT_32  (   1, 15, 12 ), RPT_32  (  -1, 15, 12 ),
+    RPT_16  (  36,  0, 13 ), RPT_16  ( -36,  0, 13 ),
+    RPT_16  (  37,  0, 13 ), RPT_16  ( -37,  0, 13 ),
+    RPT_16  (  38,  0, 13 ), RPT_16  ( -38,  0, 13 ),
+    RPT_16  (  39,  0, 13 ), RPT_16  ( -39,  0, 13 ),
+    RPT_16  (  40,  0, 13 ), RPT_16  ( -40,  0, 13 ),
+    RPT_16  (  13,  1, 13 ), RPT_16  ( -13,  1, 13 ),
+    RPT_16  (  14,  1, 13 ), RPT_16  ( -14,  1, 13 ),
+    RPT_16  (  15,  1, 13 ), RPT_16  ( -15,  1, 13 ),
+    RPT_16  (   6,  2, 13 ), RPT_16  (  -6,  2, 13 ),
+    RPT_16  (   7,  2, 13 ), RPT_16  (  -7,  2, 13 ),
+    RPT_16  (   5,  3, 13 ), RPT_16  (  -5,  3, 13 ),
+    RPT_32  (   0,  4, 12 ), RPT_16  (   4,  4, 13 ),
+    RPT_16  (  -4,  4, 13 ), RPT_32  (   0,  5, 12 ),
+    RPT_32  (   0,  6, 12 ), RPT_16  (   3,  6, 13 ),
+    RPT_16  (  -3,  6, 13 ), RPT_32  (   0,  7, 12 ),
+    RPT_16  (   3,  7, 13 ), RPT_16  (  -3,  7, 13 ),
+    RPT_16  (   2, 10, 13 ), RPT_16  (  -2, 10, 13 ),
+    RPT_16  (   1, 16, 13 ), RPT_16  (  -1, 16, 13 ),
+};
+
+static const HQXLUT ac32_lut[] = {
+    RPT_256 (   1,  0,  3 ), RPT_256 (  -1,  0,  3 ),
+    RPT_128 (   2,  0,  4 ), RPT_128 (  -2,  0,  4 ),
+    RPT_256 (   0, 64,  3 ), RPT_64  (   3,  0,  5 ),
+    RPT_64  (  -3,  0,  5 ), RPT_64  (   1,  1,  5 ),
+    RPT_64  (  -1,  1,  5 ), RPT_32  (   4,  0,  6 ),
+    RPT_32  (  -4,  0,  6 ), RPT_32  (   5,  0,  6 ),
+    RPT_32  (  -5,  0,  6 ), RPT_32  (   2,  1,  6 ),
+    RPT_32  (  -2,  1,  6 ), RPT_32  (   1,  2,  6 ),
+    RPT_32  (  -1,  2,  6 ), RPT_32  (   1,  3,  6 ),
+    RPT_32  (  -1,  3,  6 ), RPT_16  (   6,  0,  7 ),
+    RPT_16  (  -6,  0,  7 ), RPT_16  (   7,  0,  7 ),
+    RPT_16  (  -7,  0,  7 ), RPT_16  (   3,  1,  7 ),
+    RPT_16  (  -3,  1,  7 ), RPT_16  (   1,  4,  7 ),
+    RPT_16  (  -1,  4,  7 ), RPT_16  (   1,  5,  7 ),
+    RPT_16  (  -1,  5,  7 ), RPT_8   (   8,  0,  8 ),
+    RPT_8   (  -8,  0,  8 ), RPT_8   (   9,  0,  8 ),
+    RPT_8   (  -9,  0,  8 ), RPT_8   (  10,  0,  8 ),
+    RPT_8   ( -10,  0,  8 ), RPT_8   (   4,  1,  8 ),
+    RPT_8   (  -4,  1,  8 ), RPT_8   (   2,  2,  8 ),
+    RPT_8   (  -2,  2,  8 ), RPT_8   (   1,  6,  8 ),
+    RPT_8   (  -1,  6,  8 ), RPT_8   (   1,  7,  8 ),
+    RPT_8   (  -1,  7,  8 ), RPT_8   (   1,  8,  8 ),
+    RPT_8   (  -1,  8,  8 ), RPT_4   (  11,  0,  9 ),
+    RPT_4   ( -11,  0,  9 ), RPT_4   (  12,  0,  9 ),
+    RPT_4   ( -12,  0,  9 ), RPT_4   (  13,  0,  9 ),
+    RPT_4   ( -13,  0,  9 ), RPT_4   (   5,  1,  9 ),
+    RPT_4   (  -5,  1,  9 ), RPT_4   (   2,  3,  9 ),
+    RPT_4   (  -2,  3,  9 ), RPT_4   (   1,  9,  9 ),
+    RPT_4   (  -1,  9,  9 ), RPT_4   (   1, 10,  9 ),
+    RPT_4   (  -1, 10,  9 ), RPT_2   (  14,  0, 10 ),
+    RPT_2   ( -14,  0, 10 ), RPT_2   (  15,  0, 10 ),
+    RPT_2   ( -15,  0, 10 ), RPT_2   (  16,  0, 10 ),
+    RPT_2   ( -16,  0, 10 ), RPT_2   (   6,  1, 10 ),
+    RPT_2   (  -6,  1, 10 ), RPT_2   (   7,  1, 10 ),
+    RPT_2   (  -7,  1, 10 ), RPT_2   (   3,  2, 10 ),
+    RPT_2   (  -3,  2, 10 ), RPT_2   (   3,  3, 10 ),
+    RPT_2   (  -3,  3, 10 ), RPT_2   (   2,  4, 10 ),
+    RPT_2   (  -2,  4, 10 ), RPT_2   (   2,  5, 10 ),
+    RPT_2   (  -2,  5, 10 ), RPT_2   (   1, 11, 10 ),
+    RPT_2   (  -1, 11, 10 ), RPT_2   (   1, 12, 10 ),
+    RPT_2   (  -1, 12, 10 ), RPT_2   (   1, 13, 10 ),
+    RPT_2   (  -1, 13, 10 ), { 2048,  0, -1 }, { 2112,  0, -1 },
+    { 2176,  0, -1 }, { 2240,  0, -1 }, RPT_2   (   0,  0, 10 ),
+    {   17,  0, 11 }, {  -17,  0, 11 }, {   18,  0, 11 }, {  -18,  0, 11 },
+    {   19,  0, 11 }, {  -19,  0, 11 }, {   20,  0, 11 }, {  -20,  0, 11 },
+    {    8,  1, 11 }, {   -8,  1, 11 }, {    9,  1, 11 }, {   -9,  1, 11 },
+    {    4,  2, 11 }, {   -4,  2, 11 }, {    3,  4, 11 }, {   -3,  4, 11 },
+    {    2,  6, 11 }, {   -2,  6, 11 }, {    2,  7, 11 }, {   -2,  7, 11 },
+    {    2,  8, 11 }, {   -2,  8, 11 }, {    1, 14, 11 }, {   -1, 14, 11 },
+    { 2304,  0, -1 }, { 2368,  0, -1 }, { 2432,  0, -1 }, { 2496,  0, -1 },
+    { 2560,  0, -1 }, {    0,  1, 11 }, { 2624,  0, -1 }, { 2688,  0, -1 },
+    {    0,  2, 11 }, { 2752,  0, -1 }, { 2816,  0, -1 }, {    0,  3, 11 },
+    { 2880,  0, -1 }, {    0,  4, 11 }, { 2944,  0, -1 }, { 3008,  0, -1 },
+    { 3072,  0, -1 }, { 3136,  0, -1 }, { 3200,  0, -1 }, { 3264,  0, -1 },
+    { 3328,  0, -1 }, { 3392,  0, -1 }, { 3456,  0, -1 }, { 3520,  0, -1 },
+    { 3584,  0, -1 }, { 3648,  0, -1 }, RPT_4   (   0,  0, 15 ),
+    RPT_4   (   0,  1, 15 ), RPT_4   (   0,  2, 15 ),
+    RPT_4   (   0,  3, 15 ), RPT_4   (   0,  4, 15 ),
+    RPT_4   (   0,  5, 15 ), RPT_4   (   0,  6, 15 ),
+    RPT_4   (   0,  7, 15 ), RPT_4   (   0,  8, 15 ),
+    RPT_4   (   0,  9, 15 ), RPT_4   (   0, 10, 15 ),
+    RPT_4   (   0, 11, 15 ), RPT_4   (   0, 12, 15 ),
+    RPT_4   (   0, 13, 15 ), RPT_4   (   0, 14, 15 ),
+    RPT_4   (   0, 15, 15 ), RPT_4   (   0, 16, 15 ),
+    RPT_4   (   0, 17, 15 ), RPT_4   (   0, 18, 15 ),
+    RPT_4   (   0, 19, 15 ), RPT_4   (   0, 20, 15 ),
+    RPT_4   (   0, 21, 15 ), RPT_4   (   0, 22, 15 ),
+    RPT_4   (   0, 23, 15 ), RPT_4   (   0, 24, 15 ),
+    RPT_4   (   0, 25, 15 ), RPT_4   (   0, 26, 15 ),
+    RPT_4   (   0, 27, 15 ), RPT_4   (   0, 28, 15 ),
+    RPT_4   (   0, 29, 15 ), RPT_4   (   0, 30, 15 ),
+    RPT_4   (   0, 31, 15 ), RPT_4   (   0, 32, 15 ),
+    RPT_4   (   0, 33, 15 ), RPT_4   (   0, 34, 15 ),
+    RPT_4   (   0, 35, 15 ), RPT_4   (   0, 36, 15 ),
+    RPT_4   (   0, 37, 15 ), RPT_4   (   0, 38, 15 ),
+    RPT_4   (   0, 39, 15 ), RPT_4   (   0, 40, 15 ),
+    RPT_4   (   0, 41, 15 ), RPT_4   (   0, 42, 15 ),
+    RPT_4   (   0, 43, 15 ), RPT_4   (   0, 44, 15 ),
+    RPT_4   (   0, 45, 15 ), RPT_4   (   0, 46, 15 ),
+    RPT_4   (   0, 47, 15 ), RPT_4   (   0, 48, 15 ),
+    RPT_4   (   0, 49, 15 ), RPT_4   (   0, 50, 15 ),
+    RPT_4   (   0, 51, 15 ), RPT_4   (   0, 52, 15 ),
+    RPT_4   (   0, 53, 15 ), RPT_4   (   0, 54, 15 ),
+    RPT_4   (   0, 55, 15 ), RPT_4   (   0, 56, 15 ),
+    RPT_4   (   0, 57, 15 ), RPT_4   (   0, 58, 15 ),
+    RPT_4   (   0, 59, 15 ), RPT_4   (   0, 60, 15 ),
+    RPT_4   (   0, 61, 15 ), RPT_4   (   0, 62, 15 ),
+    RPT_4   (   0, 63, 15 ), RPT_2   (   0,  0, 16 ),
+    {    1,  0, 17 }, {   -1,  0, 17 }, {    2,  0, 17 }, {   -2,  0, 17 },
+    {    3,  0, 17 }, {   -3,  0, 17 }, {    4,  0, 17 }, {   -4,  0, 17 },
+    {    5,  0, 17 }, {   -5,  0, 17 }, {    6,  0, 17 }, {   -6,  0, 17 },
+    {    7,  0, 17 }, {   -7,  0, 17 }, {    8,  0, 17 }, {   -8,  0, 17 },
+    {    9,  0, 17 }, {   -9,  0, 17 }, {   10,  0, 17 }, {  -10,  0, 17 },
+    {   11,  0, 17 }, {  -11,  0, 17 }, {   12,  0, 17 }, {  -12,  0, 17 },
+    {   13,  0, 17 }, {  -13,  0, 17 }, {   14,  0, 17 }, {  -14,  0, 17 },
+    {   15,  0, 17 }, {  -15,  0, 17 }, {   16,  0, 17 }, {  -16,  0, 17 },
+    {   17,  0, 17 }, {  -17,  0, 17 }, {   18,  0, 17 }, {  -18,  0, 17 },
+    {   19,  0, 17 }, {  -19,  0, 17 }, {   20,  0, 17 }, {  -20,  0, 17 },
+    {   21,  0, 17 }, {  -21,  0, 17 }, {   22,  0, 17 }, {  -22,  0, 17 },
+    {   23,  0, 17 }, {  -23,  0, 17 }, {   24,  0, 17 }, {  -24,  0, 17 },
+    {   25,  0, 17 }, {  -25,  0, 17 }, {   26,  0, 17 }, {  -26,  0, 17 },
+    {   27,  0, 17 }, {  -27,  0, 17 }, {   28,  0, 17 }, {  -28,  0, 17 },
+    {   29,  0, 17 }, {  -29,  0, 17 }, {   30,  0, 17 }, {  -30,  0, 17 },
+    {   31,  0, 17 }, {  -31,  0, 17 }, {   32,  0, 17 }, {  -32,  0, 17 },
+    {   33,  0, 17 }, {  -33,  0, 17 }, {   34,  0, 17 }, {  -34,  0, 17 },
+    {   35,  0, 17 }, {  -35,  0, 17 }, {   36,  0, 17 }, {  -36,  0, 17 },
+    {   37,  0, 17 }, {  -37,  0, 17 }, {   38,  0, 17 }, {  -38,  0, 17 },
+    {   39,  0, 17 }, {  -39,  0, 17 }, {   40,  0, 17 }, {  -40,  0, 17 },
+    {   41,  0, 17 }, {  -41,  0, 17 }, {   42,  0, 17 }, {  -42,  0, 17 },
+    {   43,  0, 17 }, {  -43,  0, 17 }, {   44,  0, 17 }, {  -44,  0, 17 },
+    {   45,  0, 17 }, {  -45,  0, 17 }, {   46,  0, 17 }, {  -46,  0, 17 },
+    {   47,  0, 17 }, {  -47,  0, 17 }, {   48,  0, 17 }, {  -48,  0, 17 },
+    {   49,  0, 17 }, {  -49,  0, 17 }, {   50,  0, 17 }, {  -50,  0, 17 },
+    {   51,  0, 17 }, {  -51,  0, 17 }, {   52,  0, 17 }, {  -52,  0, 17 },
+    {   53,  0, 17 }, {  -53,  0, 17 }, {   54,  0, 17 }, {  -54,  0, 17 },
+    {   55,  0, 17 }, {  -55,  0, 17 }, {   56,  0, 17 }, {  -56,  0, 17 },
+    {   57,  0, 17 }, {  -57,  0, 17 }, {   58,  0, 17 }, {  -58,  0, 17 },
+    {   59,  0, 17 }, {  -59,  0, 17 }, {   60,  0, 17 }, {  -60,  0, 17 },
+    {   61,  0, 17 }, {  -61,  0, 17 }, {   62,  0, 17 }, {  -62,  0, 17 },
+    {   63,  0, 17 }, {  -63,  0, 17 }, RPT_32  (  21,  0, 12 ),
+    RPT_32  ( -21,  0, 12 ), RPT_32  (  22,  0, 12 ),
+    RPT_32  ( -22,  0, 12 ), RPT_32  (  23,  0, 12 ),
+    RPT_32  ( -23,  0, 12 ), RPT_32  (  10,  1, 12 ),
+    RPT_32  ( -10,  1, 12 ), RPT_32  (  11,  1, 12 ),
+    RPT_32  ( -11,  1, 12 ), RPT_32  (   5,  2, 12 ),
+    RPT_32  (  -5,  2, 12 ), RPT_32  (   6,  2, 12 ),
+    RPT_32  (  -6,  2, 12 ), RPT_32  (   4,  3, 12 ),
+    RPT_32  (  -4,  3, 12 ), RPT_32  (   3,  5, 12 ),
+    RPT_32  (  -3,  5, 12 ), RPT_32  (   3,  6, 12 ),
+    RPT_32  (  -3,  6, 12 ), RPT_32  (   2,  9, 12 ),
+    RPT_32  (  -2,  9, 12 ), RPT_32  (   1, 15, 12 ),
+    RPT_32  (  -1, 15, 12 ), RPT_16  (  24,  0, 13 ),
+    RPT_16  ( -24,  0, 13 ), RPT_16  (  25,  0, 13 ),
+    RPT_16  ( -25,  0, 13 ), RPT_16  (  26,  0, 13 ),
+    RPT_16  ( -26,  0, 13 ), RPT_16  (  12,  1, 13 ),
+    RPT_16  ( -12,  1, 13 ), RPT_16  (  13,  1, 13 ),
+    RPT_16  ( -13,  1, 13 ), RPT_16  (   5,  3, 13 ),
+    RPT_16  (  -5,  3, 13 ), RPT_16  (   4,  4, 13 ),
+    RPT_16  (  -4,  4, 13 ), RPT_32  (   0,  5, 12 ),
+    RPT_16  (   4,  5, 13 ), RPT_16  (  -4,  5, 13 ),
+    RPT_32  (   0,  6, 12 ), RPT_32  (   0,  7, 12 ),
+    RPT_16  (   3,  7, 13 ), RPT_16  (  -3,  7, 13 ),
+    RPT_32  (   0,  8, 12 ), RPT_16  (   3,  8, 13 ),
+    RPT_16  (  -3,  8, 13 ), RPT_32  (   0,  9, 12 ),
+    RPT_16  (   1, 16, 13 ), RPT_16  (  -1, 16, 13 ),
+};
+
+static const HQXLUT ac64_lut[] = {
+    RPT_512 (   1,  0,  3 ), RPT_512 (  -1,  0,  3 ),
+    RPT_1024(   0, 64,  2 ), RPT_256 (   2,  0,  4 ),
+    RPT_256 (  -2,  0,  4 ), RPT_128 (   3,  0,  5 ),
+    RPT_128 (  -3,  0,  5 ), RPT_128 (   1,  1,  5 ),
+    RPT_128 (  -1,  1,  5 ), RPT_64  (   4,  0,  6 ),
+    RPT_64  (  -4,  0,  6 ), RPT_64  (   2,  1,  6 ),
+    RPT_64  (  -2,  1,  6 ), RPT_64  (   1,  2,  6 ),
+    RPT_64  (  -1,  2,  6 ), RPT_32  (   5,  0,  7 ),
+    RPT_32  (  -5,  0,  7 ), RPT_32  (   1,  3,  7 ),
+    RPT_32  (  -1,  3,  7 ), RPT_32  (   1,  4,  7 ),
+    RPT_32  (  -1,  4,  7 ), RPT_16  (   6,  0,  8 ),
+    RPT_16  (  -6,  0,  8 ), RPT_16  (   3,  1,  8 ),
+    RPT_16  (  -3,  1,  8 ), RPT_16  (   2,  2,  8 ),
+    RPT_16  (  -2,  2,  8 ), RPT_16  (   1,  5,  8 ),
+    RPT_16  (  -1,  5,  8 ), RPT_16  (   1,  6,  8 ),
+    RPT_16  (  -1,  6,  8 ), RPT_16  (   1,  7,  8 ),
+    RPT_16  (  -1,  7,  8 ), RPT_8   (   7,  0,  9 ),
+    RPT_8   (  -7,  0,  9 ), RPT_8   (   8,  0,  9 ),
+    RPT_8   (  -8,  0,  9 ), RPT_8   (   4,  1,  9 ),
+    RPT_8   (  -4,  1,  9 ), RPT_8   (   2,  3,  9 ),
+    RPT_8   (  -2,  3,  9 ), RPT_8   (   1,  8,  9 ),
+    RPT_8   (  -1,  8,  9 ), RPT_8   (   1,  9,  9 ),
+    RPT_8   (  -1,  9,  9 ), RPT_4   (   9,  0, 10 ),
+    RPT_4   (  -9,  0, 10 ), RPT_4   (  10,  0, 10 ),
+    RPT_4   ( -10,  0, 10 ), RPT_4   (   5,  1, 10 ),
+    RPT_4   (  -5,  1, 10 ), RPT_4   (   3,  2, 10 ),
+    RPT_4   (  -3,  2, 10 ), RPT_4   (   2,  4, 10 ),
+    RPT_4   (  -2,  4, 10 ), RPT_4   (   2,  5, 10 ),
+    RPT_4   (  -2,  5, 10 ), RPT_4   (   1, 10, 10 ),
+    RPT_4   (  -1, 10, 10 ), RPT_4   (   1, 11, 10 ),
+    RPT_4   (  -1, 11, 10 ), { 4096,  0, -1 }, { 4128,  0, -1 },
+    { 4160,  0, -1 }, { 4192,  0, -1 }, { 4224,  0, -1 }, { 4256,  0, -1 },
+    { 4288,  0, -1 }, { 4320,  0, -1 }, RPT_4   (   0,  0, 10 ),
+    RPT_2   (  11,  0, 11 ), RPT_2   ( -11,  0, 11 ),
+    RPT_2   (  12,  0, 11 ), RPT_2   ( -12,  0, 11 ),
+    RPT_2   (   6,  1, 11 ), RPT_2   (  -6,  1, 11 ),
+    RPT_2   (   7,  1, 11 ), RPT_2   (  -7,  1, 11 ),
+    RPT_2   (   3,  3, 11 ), RPT_2   (  -3,  3, 11 ),
+    RPT_2   (   3,  4, 11 ), RPT_2   (  -3,  4, 11 ),
+    RPT_2   (   3,  5, 11 ), RPT_2   (  -3,  5, 11 ),
+    RPT_2   (   2,  6, 11 ), RPT_2   (  -2,  6, 11 ),
+    RPT_2   (   2,  7, 11 ), RPT_2   (  -2,  7, 11 ),
+    RPT_2   (   1, 12, 11 ), RPT_2   (  -1, 12, 11 ),
+    RPT_2   (   1, 13, 11 ), RPT_2   (  -1, 13, 11 ),
+    RPT_2   (   1, 14, 11 ), RPT_2   (  -1, 14, 11 ),
+    {   13,  0, 12 }, {  -13,  0, 12 }, {   14,  0, 12 }, {  -14,  0, 12 },
+    RPT_2   (   0,  1, 11 ), {    8,  1, 12 }, {   -8,  1, 12 },
+    {    4,  2, 12 }, {   -4,  2, 12 }, {    4,  3, 12 }, {   -4,  3, 12 },
+    {    2,  8, 12 }, {   -2,  8, 12 }, {    2,  9, 12 }, {   -2,  9, 12 },
+    {    1, 15, 12 }, {   -1, 15, 12 }, { 4352,  0, -1 }, { 4384,  0, -1 },
+    { 4416,  0, -1 }, { 4448,  0, -1 }, { 4480,  0, -1 }, {    0,  2, 12 },
+    { 4512,  0, -1 }, {    0,  3, 12 }, { 4544,  0, -1 }, {    0,  4, 12 },
+    { 4576,  0, -1 }, {    0,  5, 12 }, { 4608,  0, -1 }, {    0,  6, 12 },
+    { 4640,  0, -1 }, { 4672,  0, -1 }, { 4704,  0, -1 }, { 4736,  0, -1 },
+    RPT_4   (   0,  0, 15 ), RPT_4   (   0,  1, 15 ),
+    RPT_4   (   0,  2, 15 ), RPT_4   (   0,  3, 15 ),
+    RPT_4   (   0,  4, 15 ), RPT_4   (   0,  5, 15 ),
+    RPT_4   (   0,  6, 15 ), RPT_4   (   0,  7, 15 ),
+    RPT_4   (   0,  8, 15 ), RPT_4   (   0,  9, 15 ),
+    RPT_4   (   0, 10, 15 ), RPT_4   (   0, 11, 15 ),
+    RPT_4   (   0, 12, 15 ), RPT_4   (   0, 13, 15 ),
+    RPT_4   (   0, 14, 15 ), RPT_4   (   0, 15, 15 ),
+    RPT_4   (   0, 16, 15 ), RPT_4   (   0, 17, 15 ),
+    RPT_4   (   0, 18, 15 ), RPT_4   (   0, 19, 15 ),
+    RPT_4   (   0, 20, 15 ), RPT_4   (   0, 21, 15 ),
+    RPT_4   (   0, 22, 15 ), RPT_4   (   0, 23, 15 ),
+    RPT_4   (   0, 24, 15 ), RPT_4   (   0, 25, 15 ),
+    RPT_4   (   0, 26, 15 ), RPT_4   (   0, 27, 15 ),
+    RPT_4   (   0, 28, 15 ), RPT_4   (   0, 29, 15 ),
+    RPT_4   (   0, 30, 15 ), RPT_4   (   0, 31, 15 ),
+    RPT_4   (   0, 32, 15 ), RPT_4   (   0, 33, 15 ),
+    RPT_4   (   0, 34, 15 ), RPT_4   (   0, 35, 15 ),
+    RPT_4   (   0, 36, 15 ), RPT_4   (   0, 37, 15 ),
+    RPT_4   (   0, 38, 15 ), RPT_4   (   0, 39, 15 ),
+    RPT_4   (   0, 40, 15 ), RPT_4   (   0, 41, 15 ),
+    RPT_4   (   0, 42, 15 ), RPT_4   (   0, 43, 15 ),
+    RPT_4   (   0, 44, 15 ), RPT_4   (   0, 45, 15 ),
+    RPT_4   (   0, 46, 15 ), RPT_4   (   0, 47, 15 ),
+    RPT_4   (   0, 48, 15 ), RPT_4   (   0, 49, 15 ),
+    RPT_4   (   0, 50, 15 ), RPT_4   (   0, 51, 15 ),
+    RPT_4   (   0, 52, 15 ), RPT_4   (   0, 53, 15 ),
+    RPT_4   (   0, 54, 15 ), RPT_4   (   0, 55, 15 ),
+    RPT_4   (   0, 56, 15 ), RPT_4   (   0, 57, 15 ),
+    RPT_4   (   0, 58, 15 ), RPT_4   (   0, 59, 15 ),
+    RPT_4   (   0, 60, 15 ), RPT_4   (   0, 61, 15 ),
+    RPT_4   (   0, 62, 15 ), RPT_4   (   0, 63, 15 ),
+    RPT_2   (   0,  0, 16 ), {    1,  0, 17 }, {   -1,  0, 17 },
+    {    2,  0, 17 }, {   -2,  0, 17 }, {    3,  0, 17 }, {   -3,  0, 17 },
+    {    4,  0, 17 }, {   -4,  0, 17 }, {    5,  0, 17 }, {   -5,  0, 17 },
+    {    6,  0, 17 }, {   -6,  0, 17 }, {    7,  0, 17 }, {   -7,  0, 17 },
+    {    8,  0, 17 }, {   -8,  0, 17 }, {    9,  0, 17 }, {   -9,  0, 17 },
+    {   10,  0, 17 }, {  -10,  0, 17 }, {   11,  0, 17 }, {  -11,  0, 17 },
+    {   12,  0, 17 }, {  -12,  0, 17 }, {   13,  0, 17 }, {  -13,  0, 17 },
+    {   14,  0, 17 }, {  -14,  0, 17 }, {   15,  0, 17 }, {  -15,  0, 17 },
+    {   16,  0, 17 }, {  -16,  0, 17 }, {   17,  0, 17 }, {  -17,  0, 17 },
+    {   18,  0, 17 }, {  -18,  0, 17 }, {   19,  0, 17 }, {  -19,  0, 17 },
+    {   20,  0, 17 }, {  -20,  0, 17 }, {   21,  0, 17 }, {  -21,  0, 17 },
+    {   22,  0, 17 }, {  -22,  0, 17 }, {   23,  0, 17 }, {  -23,  0, 17 },
+    {   24,  0, 17 }, {  -24,  0, 17 }, {   25,  0, 17 }, {  -25,  0, 17 },
+    {   26,  0, 17 }, {  -26,  0, 17 }, {   27,  0, 17 }, {  -27,  0, 17 },
+    {   28,  0, 17 }, {  -28,  0, 17 }, {   29,  0, 17 }, {  -29,  0, 17 },
+    {   30,  0, 17 }, {  -30,  0, 17 }, {   31,  0, 17 }, {  -31,  0, 17 },
+    RPT_16  (  15,  0, 13 ), RPT_16  ( -15,  0, 13 ),
+    RPT_16  (   9,  1, 13 ), RPT_16  (  -9,  1, 13 ),
+    RPT_16  (  10,  1, 13 ), RPT_16  ( -10,  1, 13 ),
+    RPT_16  (   5,  2, 13 ), RPT_16  (  -5,  2, 13 ),
+    RPT_16  (   5,  3, 13 ), RPT_16  (  -5,  3, 13 ),
+    RPT_16  (   4,  4, 13 ), RPT_16  (  -4,  4, 13 ),
+    RPT_16  (   4,  5, 13 ), RPT_16  (  -4,  5, 13 ),
+    RPT_16  (   3,  6, 13 ), RPT_16  (  -3,  6, 13 ),
+    RPT_16  (   3,  7, 13 ), RPT_16  (  -3,  7, 13 ),
+    RPT_16  (   1, 16, 13 ), RPT_16  (  -1, 16, 13 ),
+    RPT_16  (   1, 17, 13 ), RPT_16  (  -1, 17, 13 ),
+};
+
+static const HQXLUT ac128_lut[] = {
+    RPT_256 (   1,  0,  3 ), RPT_256 (  -1,  0,  3 ),
+    RPT_512 (   0, 64,  2 ), RPT_128 (   1,  1,  4 ),
+    RPT_128 (  -1,  1,  4 ), RPT_64  (   2,  0,  5 ),
+    RPT_64  (  -2,  0,  5 ), RPT_32  (   3,  0,  6 ),
+    RPT_32  (  -3,  0,  6 ), RPT_32  (   2,  1,  6 ),
+    RPT_32  (  -2,  1,  6 ), RPT_32  (   1,  2,  6 ),
+    RPT_32  (  -1,  2,  6 ), RPT_32  (   1,  3,  6 ),
+    RPT_32  (  -1,  3,  6 ), RPT_32  (   1,  4,  6 ),
+    RPT_32  (  -1,  4,  6 ), RPT_16  (   4,  0,  7 ),
+    RPT_16  (  -4,  0,  7 ), RPT_16  (   1,  5,  7 ),
+    RPT_16  (  -1,  5,  7 ), RPT_16  (   1,  6,  7 ),
+    RPT_16  (  -1,  6,  7 ), RPT_16  (   1,  7,  7 ),
+    RPT_16  (  -1,  7,  7 ), RPT_8   (   5,  0,  8 ),
+    RPT_8   (  -5,  0,  8 ), RPT_8   (   3,  1,  8 ),
+    RPT_8   (  -3,  1,  8 ), RPT_8   (   2,  2,  8 ),
+    RPT_8   (  -2,  2,  8 ), RPT_8   (   2,  3,  8 ),
+    RPT_8   (  -2,  3,  8 ), RPT_8   (   1,  8,  8 ),
+    RPT_8   (  -1,  8,  8 ), RPT_8   (   1,  9,  8 ),
+    RPT_8   (  -1,  9,  8 ), RPT_4   (   6,  0,  9 ),
+    RPT_4   (  -6,  0,  9 ), RPT_4   (   4,  1,  9 ),
+    RPT_4   (  -4,  1,  9 ), RPT_4   (   2,  4,  9 ),
+    RPT_4   (  -2,  4,  9 ), RPT_4   (   2,  5,  9 ),
+    RPT_4   (  -2,  5,  9 ), RPT_4   (   1, 10,  9 ),
+    RPT_4   (  -1, 10,  9 ), RPT_2   (   7,  0, 10 ),
+    RPT_2   (  -7,  0, 10 ), RPT_2   (   5,  1, 10 ),
+    RPT_2   (  -5,  1, 10 ), RPT_2   (   3,  2, 10 ),
+    RPT_2   (  -3,  2, 10 ), RPT_2   (   3,  3, 10 ),
+    RPT_2   (  -3,  3, 10 ), RPT_2   (   2,  6, 10 ),
+    RPT_2   (  -2,  6, 10 ), { 2048,  0, -1 }, { 2112,  0, -1 },
+    { 2176,  0, -1 }, { 2240,  0, -1 }, {    6,  1, 11 }, {   -6,  1, 11 },
+    {    7,  1, 11 }, {   -7,  1, 11 }, {    3,  4, 11 }, {   -3,  4, 11 },
+    {    3,  5, 11 }, {   -3,  5, 11 }, {    2,  7, 11 }, {   -2,  7, 11 },
+    {    2,  8, 11 }, {   -2,  8, 11 }, {    2,  9, 11 }, {   -2,  9, 11 },
+    {    1, 11, 11 }, {   -1, 11, 11 }, {    1, 12, 11 }, {   -1, 12, 11 },
+    {    1, 13, 11 }, {   -1, 13, 11 }, {    0,  0, 11 }, { 2304,  0, -1 },
+    { 2368,  0, -1 }, { 2432,  0, -1 }, { 2496,  0, -1 }, { 2560,  0, -1 },
+    { 2624,  0, -1 }, { 2688,  0, -1 }, { 2752,  0, -1 }, { 2816,  0, -1 },
+    { 2880,  0, -1 }, { 2944,  0, -1 }, RPT_4   (   0,  0, 15 ),
+    RPT_4   (   0,  1, 15 ), RPT_4   (   0,  2, 15 ),
+    RPT_4   (   0,  3, 15 ), RPT_4   (   0,  4, 15 ),
+    RPT_4   (   0,  5, 15 ), RPT_4   (   0,  6, 15 ),
+    RPT_4   (   0,  7, 15 ), RPT_4   (   0,  8, 15 ),
+    RPT_4   (   0,  9, 15 ), RPT_4   (   0, 10, 15 ),
+    RPT_4   (   0, 11, 15 ), RPT_4   (   0, 12, 15 ),
+    RPT_4   (   0, 13, 15 ), RPT_4   (   0, 14, 15 ),
+    RPT_4   (   0, 15, 15 ), RPT_4   (   0, 16, 15 ),
+    RPT_4   (   0, 17, 15 ), RPT_4   (   0, 18, 15 ),
+    RPT_4   (   0, 19, 15 ), RPT_4   (   0, 20, 15 ),
+    RPT_4   (   0, 21, 15 ), RPT_4   (   0, 22, 15 ),
+    RPT_4   (   0, 23, 15 ), RPT_4   (   0, 24, 15 ),
+    RPT_4   (   0, 25, 15 ), RPT_4   (   0, 26, 15 ),
+    RPT_4   (   0, 27, 15 ), RPT_4   (   0, 28, 15 ),
+    RPT_4   (   0, 29, 15 ), RPT_4   (   0, 30, 15 ),
+    RPT_4   (   0, 31, 15 ), RPT_4   (   0, 32, 15 ),
+    RPT_4   (   0, 33, 15 ), RPT_4   (   0, 34, 15 ),
+    RPT_4   (   0, 35, 15 ), RPT_4   (   0, 36, 15 ),
+    RPT_4   (   0, 37, 15 ), RPT_4   (   0, 38, 15 ),
+    RPT_4   (   0, 39, 15 ), RPT_4   (   0, 40, 15 ),
+    RPT_4   (   0, 41, 15 ), RPT_4   (   0, 42, 15 ),
+    RPT_4   (   0, 43, 15 ), RPT_4   (   0, 44, 15 ),
+    RPT_4   (   0, 45, 15 ), RPT_4   (   0, 46, 15 ),
+    RPT_4   (   0, 47, 15 ), RPT_4   (   0, 48, 15 ),
+    RPT_4   (   0, 49, 15 ), RPT_4   (   0, 50, 15 ),
+    RPT_4   (   0, 51, 15 ), RPT_4   (   0, 52, 15 ),
+    RPT_4   (   0, 53, 15 ), RPT_4   (   0, 54, 15 ),
+    RPT_4   (   0, 55, 15 ), RPT_4   (   0, 56, 15 ),
+    RPT_4   (   0, 57, 15 ), RPT_4   (   0, 58, 15 ),
+    RPT_4   (   0, 59, 15 ), RPT_4   (   0, 60, 15 ),
+    RPT_4   (   0, 61, 15 ), RPT_4   (   0, 62, 15 ),
+    RPT_4   (   0, 63, 15 ), RPT_32  (   8,  0, 12 ),
+    RPT_32  (  -8,  0, 12 ), RPT_32  (   9,  0, 12 ),
+    RPT_32  (  -9,  0, 12 ), RPT_32  (   8,  1, 12 ),
+    RPT_32  (  -8,  1, 12 ), RPT_32  (   4,  2, 12 ),
+    RPT_32  (  -4,  2, 12 ), RPT_32  (   4,  3, 12 ),
+    RPT_32  (  -4,  3, 12 ), RPT_32  (   3,  6, 12 ),
+    RPT_32  (  -3,  6, 12 ), RPT_32  (   1, 14, 12 ),
+    RPT_32  (  -1, 14, 12 ), RPT_32  (   1, 15, 12 ),
+    RPT_32  (  -1, 15, 12 ), RPT_32  (   1, 16, 12 ),
+    RPT_32  (  -1, 16, 12 ), RPT_32  (   0,  1, 12 ),
+    RPT_32  (   0,  2, 12 ), RPT_32  (   0,  3, 12 ),
+    RPT_2   (   0,  0, 16 ), {    1,  0, 17 }, {   -1,  0, 17 },
+    {    2,  0, 17 }, {   -2,  0, 17 }, {    3,  0, 17 }, {   -3,  0, 17 },
+    {    4,  0, 17 }, {   -4,  0, 17 }, {    5,  0, 17 }, {   -5,  0, 17 },
+    {    6,  0, 17 }, {   -6,  0, 17 }, {    7,  0, 17 }, {   -7,  0, 17 },
+    {    8,  0, 17 }, {   -8,  0, 17 }, {    9,  0, 17 }, {   -9,  0, 17 },
+    {   10,  0, 17 }, {  -10,  0, 17 }, {   11,  0, 17 }, {  -11,  0, 17 },
+    {   12,  0, 17 }, {  -12,  0, 17 }, {   13,  0, 17 }, {  -13,  0, 17 },
+    {   14,  0, 17 }, {  -14,  0, 17 }, {   15,  0, 17 }, {  -15,  0, 17 },
+};
+
+const HQXAC ff_hqx_ac[NUM_HQX_AC] = {
+    { 10, 5, ac0_lut   },
+    { 11, 6, ac8_lut   },
+    { 11, 6, ac16_lut  },
+    { 11, 6, ac32_lut  },
+    { 12, 5, ac64_lut  },
+    { 11, 6, ac128_lut },
+};
+
+#define INIT_DC_TABLE(idx, name)                                              \
+    do {                                                                      \
+        ret = init_vlc(&ctx->dc_vlc[idx], HQX_DC_VLC_BITS,                    \
+                       FF_ARRAY_ELEMS(name ## _vlc_lens),                     \
+                       name ## _vlc_lens, 1, 1,                               \
+                       name ## _vlc_bits, 2, 2, 0);                           \
+        if (ret < 0)                                                          \
+            return ret;                                                       \
+    } while (0)
+
+av_cold int ff_hqx_init_vlcs(HQXContext *ctx)
+{
+    int ret = init_vlc(&ctx->cbp_vlc, 5, FF_ARRAY_ELEMS(cbp_vlc_lens),
+                       cbp_vlc_lens, 1, 1, cbp_vlc_bits, 1, 1, 0);
+    if (ret < 0)
+        return ret;
+
+    INIT_DC_TABLE(0, dc9);
+    INIT_DC_TABLE(1, dc10);
+    INIT_DC_TABLE(2, dc11);
+
+    return 0;
+}
diff --git a/libavcodec/huffman.c b/libavcodec/huffman.c
index 2866eef..c771bcf 100644
--- a/libavcodec/huffman.c
+++ b/libavcodec/huffman.c
@@ -33,7 +33,7 @@
 /* symbol for Huffman tree node */
 #define HNODE -1
 
-typedef struct {
+typedef struct HeapElem {
     uint64_t val;
     int name;
 } HeapElem;
@@ -62,7 +62,7 @@
     int size = 0;
     int ret = 0;
 
-    if (!h || !up || !len) {
+    if (!h || !up || !len || !map) {
         ret = AVERROR(ENOMEM);
         goto end;
     }
diff --git a/libavcodec/idcinvideo.c b/libavcodec/idcinvideo.c
index 7765376..55319e5 100644
--- a/libavcodec/idcinvideo.c
+++ b/libavcodec/idcinvideo.c
@@ -56,8 +56,7 @@
 #define HUF_TOKENS 256
 #define PALETTE_COUNT 256
 
-typedef struct
-{
+typedef struct hnode {
   int count;
   unsigned char used;
   int children[2];
diff --git a/libavcodec/iff.c b/libavcodec/iff.c
index ce06b36..03bb3f5 100644
--- a/libavcodec/iff.c
+++ b/libavcodec/iff.c
@@ -41,7 +41,7 @@
     MASK_LASSO
 } mask_type;
 
-typedef struct {
+typedef struct IffContext {
     AVFrame *frame;
     int planesize;
     uint8_t * planebuf;
diff --git a/libavcodec/imc.c b/libavcodec/imc.c
index a3254f1..2fa910a 100644
--- a/libavcodec/imc.c
+++ b/libavcodec/imc.c
@@ -80,7 +80,7 @@
     int decoder_reset;
 } IMCChannel;
 
-typedef struct {
+typedef struct IMCContext {
     IMCChannel chctx[2];
 
     /** MDCT tables */
diff --git a/libavcodec/opus_imdct.c b/libavcodec/imdct15.c
similarity index 90%
rename from libavcodec/opus_imdct.c
rename to libavcodec/imdct15.c
index 126e882..e91aa11 100644
--- a/libavcodec/opus_imdct.c
+++ b/libavcodec/imdct15.c
@@ -33,8 +33,8 @@
 #include "libavutil/common.h"
 
 #include "avfft.h"
+#include "imdct15.h"
 #include "opus.h"
-#include "opus_imdct.h"
 
 // minimal iMDCT size to make SIMD opts easier
 #define CELT_MIN_IMDCT_SIZE 120
@@ -66,9 +66,9 @@
     (d).im = -ri + ir;                               \
 } while (0)
 
-av_cold void ff_celt_imdct_uninit(CeltIMDCTContext **ps)
+av_cold void ff_imdct15_uninit(IMDCT15Context **ps)
 {
-    CeltIMDCTContext *s = *ps;
+    IMDCT15Context *s = *ps;
     int i;
 
     if (!s)
@@ -84,12 +84,12 @@
     av_freep(ps);
 }
 
-static void celt_imdct_half(CeltIMDCTContext *s, float *dst, const float *src,
-                            ptrdiff_t stride, float scale);
+static void imdct15_half(IMDCT15Context *s, float *dst, const float *src,
+                         ptrdiff_t stride, float scale);
 
-av_cold int ff_celt_imdct_init(CeltIMDCTContext **ps, int N)
+av_cold int ff_imdct15_init(IMDCT15Context **ps, int N)
 {
-    CeltIMDCTContext *s;
+    IMDCT15Context *s;
     int len2 = 15 * (1 << N);
     int len  = 2 * len2;
     int i, j;
@@ -134,16 +134,17 @@
     for (j = 15; j < 19; j++)
         s->exptab[0][j] = s->exptab[0][j - 15];
 
-    s->imdct_half = celt_imdct_half;
+    s->imdct_half = imdct15_half;
 
     if (ARCH_AARCH64)
-        ff_celt_imdct_init_aarch64(s);
+        ff_imdct15_init_aarch64(s);
 
     *ps = s;
 
     return 0;
+
 fail:
-    ff_celt_imdct_uninit(&s);
+    ff_imdct15_uninit(&s);
     return AVERROR(ENOMEM);
 }
 
@@ -180,7 +181,8 @@
     out[4].im = in[0].im + z[0][3].im + z[1][2].im + z[2][1].im + z[3][0].im;
 }
 
-static void fft15(CeltIMDCTContext *s, FFTComplex *out, const FFTComplex *in, ptrdiff_t stride)
+static void fft15(IMDCT15Context *s, FFTComplex *out, const FFTComplex *in,
+                  ptrdiff_t stride)
 {
     const FFTComplex *exptab = s->exptab[0];
     FFTComplex tmp[5];
@@ -215,7 +217,7 @@
 /*
  * FFT of the length 15 * (2^N)
  */
-static void fft_calc(CeltIMDCTContext *s, FFTComplex *out, const FFTComplex *in,
+static void fft_calc(IMDCT15Context *s, FFTComplex *out, const FFTComplex *in,
                      int N, ptrdiff_t stride)
 {
     if (N) {
@@ -241,8 +243,8 @@
         fft15(s, out, in, stride);
 }
 
-static void celt_imdct_half(CeltIMDCTContext *s, float *dst, const float *src,
-                            ptrdiff_t stride, float scale)
+static void imdct15_half(IMDCT15Context *s, float *dst, const float *src,
+                         ptrdiff_t stride, float scale)
 {
     FFTComplex *z = (FFTComplex *)dst;
     const int len8 = s->len4 / 2;
diff --git a/libavcodec/opus_imdct.h b/libavcodec/imdct15.h
similarity index 74%
rename from libavcodec/opus_imdct.h
rename to libavcodec/imdct15.h
index 0ca4d97..1979aa7 100644
--- a/libavcodec/opus_imdct.h
+++ b/libavcodec/imdct15.h
@@ -16,14 +16,14 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#ifndef AVCODEC_OPUS_IMDCT_H
-#define AVCODEC_OPUS_IMDCT_H
+#ifndef AVCODEC_IMDCT15_H
+#define AVCODEC_IMDCT15_H
 
 #include <stddef.h>
 
 #include "avfft.h"
 
-typedef struct CeltIMDCTContext {
+typedef struct IMDCT15Context {
     int fft_n;
     int len2;
     int len4;
@@ -37,21 +37,21 @@
     /**
      * Calculate the middle half of the iMDCT
      */
-    void (*imdct_half)(struct CeltIMDCTContext *s, float *dst, const float *src,
+    void (*imdct_half)(struct IMDCT15Context *s, float *dst, const float *src,
                        ptrdiff_t src_stride, float scale);
-} CeltIMDCTContext;
+} IMDCT15Context;
 
 /**
  * Init an iMDCT of the length 2 * 15 * (2^N)
  */
-int ff_celt_imdct_init(CeltIMDCTContext **s, int N);
+int ff_imdct15_init(IMDCT15Context **s, int N);
 
 /**
  * Free an iMDCT.
  */
-void ff_celt_imdct_uninit(CeltIMDCTContext **s);
+void ff_imdct15_uninit(IMDCT15Context **s);
 
 
-void ff_celt_imdct_init_aarch64(CeltIMDCTContext *s);
+void ff_imdct15_init_aarch64(IMDCT15Context *s);
 
-#endif /* AVCODEC_OPUS_IMDCT_H */
+#endif /* AVCODEC_IMDCT15_H */
diff --git a/libavcodec/internal.h b/libavcodec/internal.h
index f4e12e8..3bf35df 100644
--- a/libavcodec/internal.h
+++ b/libavcodec/internal.h
@@ -33,6 +33,16 @@
 #include "avcodec.h"
 #include "config.h"
 
+/**
+ * Codec is thread safe.
+ */
+#define FF_CODEC_CAP_INIT_THREADSAFE        (1 << 0)
+/**
+ * Codec cleans up memory on init failure.
+ */
+#define FF_CODEC_CAP_INIT_CLEANUP           (1 << 1)
+
+
 #define FF_SANE_NB_CHANNELS 63U
 
 #define FF_SIGNBIT(x) ((x) >> CHAR_BIT * sizeof(x) - 1)
@@ -157,7 +167,7 @@
 void avpriv_color_frame(AVFrame *frame, const int color[4]);
 
 extern volatile int ff_avcodec_locked;
-int ff_lock_avcodec(AVCodecContext *log_ctx);
+int ff_lock_avcodec(AVCodecContext *log_ctx, const AVCodec *codec);
 int ff_unlock_avcodec(void);
 
 int avpriv_lock_avformat(void);
diff --git a/libavcodec/ituh263dec.c b/libavcodec/ituh263dec.c
index 1b89922..bac544e 100644
--- a/libavcodec/ituh263dec.c
+++ b/libavcodec/ituh263dec.c
@@ -434,8 +434,7 @@
         }
     } else if (s->mb_intra) {
         /* DC coef */
-        if(s->codec_id == AV_CODEC_ID_RV10){
-#if CONFIG_RV10_DECODER
+        if (CONFIG_RV10_DECODER && s->codec_id == AV_CODEC_ID_RV10) {
           if (s->rv10_version == 3 && s->pict_type == AV_PICTURE_TYPE_I) {
             int component, diff;
             component = (n <= 3 ? 0 : n - 4 + 1);
@@ -455,7 +454,6 @@
                 if (level == 255)
                     level = 128;
           }
-#endif
         }else{
             level = get_bits(&s->gb, 8);
             if((level&0x7F) == 0){
diff --git a/libavcodec/ivi_common.c b/libavcodec/ivi_common.c
index 3795081..d27eff2 100644
--- a/libavcodec/ivi_common.c
+++ b/libavcodec/ivi_common.c
@@ -646,7 +646,7 @@
 
         quant = band->glob_quant + mb->q_delta;
         if (avctx->codec_id == AV_CODEC_ID_INDEO4)
-            quant = av_clip(quant, 0, 31);
+            quant = av_clip_uintp2(quant, 5);
         else
             quant = av_clip(quant, 0, 23);
 
diff --git a/libavcodec/jpeg2000dec.c b/libavcodec/jpeg2000dec.c
index 17ee541..ecb6393 100644
--- a/libavcodec/jpeg2000dec.c
+++ b/libavcodec/jpeg2000dec.c
@@ -201,7 +201,7 @@
 // pix_fmts with lower bpp have to be listed before
 // similar pix_fmts with higher bpp.
 #define RGB_PIXEL_FORMATS   AV_PIX_FMT_PAL8,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 GRAY_PIXEL_FORMATS  AV_PIX_FMT_GRAY8,AV_PIX_FMT_GRAY8A,AV_PIX_FMT_GRAY16,AV_PIX_FMT_YA16
 #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, \
diff --git a/libavcodec/jpeglsdec.c b/libavcodec/jpeglsdec.c
index bb8c264..e6fa01f 100644
--- a/libavcodec/jpeglsdec.c
+++ b/libavcodec/jpeglsdec.c
@@ -28,6 +28,7 @@
 #include "avcodec.h"
 #include "get_bits.h"
 #include "golomb.h"
+#include "internal.h"
 #include "mathops.h"
 #include "mjpeg.h"
 #include "mjpegdec.h"
@@ -110,12 +111,20 @@
         if ((s->avctx->pix_fmt == AV_PIX_FMT_GRAY8 || s->avctx->pix_fmt == AV_PIX_FMT_PAL8) &&
             (s->picture_ptr->format == AV_PIX_FMT_GRAY8 || s->picture_ptr->format == AV_PIX_FMT_PAL8)) {
             uint32_t *pal = (uint32_t *)s->picture_ptr->data[1];
+            int shift = 0;
+
+            if (s->avctx->bits_per_raw_sample > 0 && s->avctx->bits_per_raw_sample < 8) {
+                maxtab = FFMIN(maxtab, (1<<s->avctx->bits_per_raw_sample)-1);
+                shift = 8 - s->avctx->bits_per_raw_sample;
+            }
+
             s->picture_ptr->format =
             s->avctx->pix_fmt = AV_PIX_FMT_PAL8;
             for (i=s->palette_index; i<=maxtab; i++) {
-                pal[i] = 0;
+                uint8_t k = i << shift;
+                pal[k] = 0;
                 for (j=0; j<wt; j++) {
-                    pal[i] |= get_bits(&s->gb, 8) << (8*(wt-j-1));
+                    pal[k] |= get_bits(&s->gb, 8) << (8*(wt-j-1));
                 }
             }
             s->palette_index = i;
@@ -508,4 +517,5 @@
     .close          = ff_mjpeg_decode_end,
     .decode         = ff_mjpeg_decode_frame,
     .capabilities   = CODEC_CAP_DR1,
+    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE,
 };
diff --git a/libavcodec/jpeglsenc.c b/libavcodec/jpeglsenc.c
index 2f02332..4273aa7 100644
--- a/libavcodec/jpeglsenc.c
+++ b/libavcodec/jpeglsenc.c
@@ -253,8 +253,9 @@
     const int near         = avctx->prediction_method;
     PutBitContext pb, pb2;
     GetBitContext gb;
-    uint8_t *buf2, *zero, *cur, *last;
-    JLSState *state;
+    uint8_t *buf2 = NULL;
+    uint8_t *zero, *cur, *last;
+    JLSState *state = NULL;
     int i, size, ret;
     int comps;
 
@@ -269,6 +270,8 @@
         return ret;
 
     buf2 = av_malloc(pkt->size);
+    if (!buf2)
+        goto fail;
 
     init_put_bits(&pb, pkt->data, pkt->size);
     init_put_bits(&pb2, buf2, pkt->size);
@@ -299,6 +302,8 @@
     put_bits(&pb, 8, 0);  // point transform: none
 
     state = av_mallocz(sizeof(JLSState));
+    if (!state)
+        goto fail;
     /* initialize JPEG-LS state from JPEG parameters */
     state->near = near;
     state->bpp  = (avctx->pix_fmt == AV_PIX_FMT_GRAY16) ? 16 : 8;
@@ -308,10 +313,9 @@
     ls_store_lse(state, &pb);
 
     zero = av_mallocz(FFABS(p->linesize[0]));
-    if (!zero) {
-        av_free(state);
-        return AVERROR(ENOMEM);
-    }
+    if (!zero)
+        goto fail;
+
     last = zero;
     cur  = p->data[0];
     if (avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
@@ -384,7 +388,7 @@
         }
     }
     avpriv_align_put_bits(&pb);
-    av_free(buf2);
+    av_freep(&buf2);
 
     /* End of image */
     put_marker(&pb, EOI);
@@ -396,6 +400,11 @@
     pkt->flags |= AV_PKT_FLAG_KEY;
     *got_packet = 1;
     return 0;
+fail:
+    av_freep(&buf2);
+    av_freep(&state);
+
+    return AVERROR(ENOMEM);
 }
 
 static av_cold int encode_close(AVCodecContext *avctx)
diff --git a/libavcodec/kgv1dec.c b/libavcodec/kgv1dec.c
index b81ba75..4f9329f 100644
--- a/libavcodec/kgv1dec.c
+++ b/libavcodec/kgv1dec.c
@@ -30,7 +30,7 @@
 #include "avcodec.h"
 #include "internal.h"
 
-typedef struct {
+typedef struct KgvContext {
     uint16_t *frame_buffer;
     uint16_t *last_frame_buffer;
 } KgvContext;
diff --git a/libavcodec/libaacplus.c b/libavcodec/libaacplus.c
index 545e240..9087d00 100644
--- a/libavcodec/libaacplus.c
+++ b/libavcodec/libaacplus.c
@@ -82,6 +82,10 @@
         if (aacplusEncGetDecoderSpecificInfo(s->aacplus_handle, &buffer,
                                            &decoder_specific_info_size) == 1) {
             avctx->extradata = av_malloc(decoder_specific_info_size + FF_INPUT_BUFFER_PADDING_SIZE);
+            if (!avctx->extradata) {
+                free(buffer);
+                return AVERROR(ENOMEM);
+            }
             avctx->extradata_size = decoder_specific_info_size;
             memcpy(avctx->extradata, buffer, avctx->extradata_size);
         }
diff --git a/libavcodec/libdcadec.c b/libavcodec/libdcadec.c
new file mode 100644
index 0000000..a28b983
--- /dev/null
+++ b/libavcodec/libdcadec.c
@@ -0,0 +1,197 @@
+/*
+ * libdcadec decoder wrapper
+ * Copyright (C) 2015 Hendrik Leppkes
+ *
+ * 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 <libdcadec/dca_context.h>
+
+#include "libavutil/avassert.h"
+#include "libavutil/channel_layout.h"
+#include "libavutil/common.h"
+#include "libavutil/opt.h"
+#include "avcodec.h"
+#include "dca.h"
+#include "dca_syncwords.h"
+#include "internal.h"
+
+typedef struct DCADecContext {
+    struct dcadec_context *ctx;
+    uint8_t *buffer;
+    int buffer_size;
+} DCADecContext;
+
+static int dcadec_decode_frame(AVCodecContext *avctx, void *data,
+                               int *got_frame_ptr, AVPacket *avpkt)
+{
+    DCADecContext *s = avctx->priv_data;
+    AVFrame *frame = data;
+    int ret, i, k;
+    int **samples, nsamples, channel_mask, sample_rate, bits_per_sample, profile;
+    uint32_t mrk;
+    uint8_t *input = avpkt->data;
+    int input_size = avpkt->size;
+
+    /* convert bytestream syntax to RAW BE format if required */
+    mrk = AV_RB32(input);
+    if (mrk != DCA_SYNCWORD_CORE_BE && mrk != DCA_SYNCWORD_SUBSTREAM) {
+        s->buffer = av_fast_realloc(s->buffer, &s->buffer_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
+        if (!s->buffer)
+            return AVERROR(ENOMEM);
+
+        if ((ret = avpriv_dca_convert_bitstream(avpkt->data, avpkt->size, s->buffer, s->buffer_size)) < 0)
+            return ret;
+
+        input      = s->buffer;
+        input_size = ret;
+    }
+
+    if ((ret = dcadec_context_parse(s->ctx, input, input_size)) < 0) {
+        av_log(avctx, AV_LOG_ERROR, "dcadec_context_parse() failed: %d (%s)\n", -ret, dcadec_strerror(ret));
+        return AVERROR_EXTERNAL;
+    }
+    if ((ret = dcadec_context_filter(s->ctx, &samples, &nsamples, &channel_mask,
+                                     &sample_rate, &bits_per_sample, &profile)) < 0) {
+        av_log(avctx, AV_LOG_ERROR, "dcadec_context_filter() failed: %d (%s)\n", -ret, dcadec_strerror(ret));
+        return AVERROR_EXTERNAL;
+    }
+
+    avctx->channels       = av_get_channel_layout_nb_channels(channel_mask);
+    avctx->channel_layout = channel_mask;
+    avctx->sample_rate    = sample_rate;
+
+    av_assert0(bits_per_sample >= 16 && bits_per_sample <= 24);
+    if (bits_per_sample == 16)
+        avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
+    else
+        avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
+
+    avctx->bits_per_raw_sample = bits_per_sample;
+
+    switch (profile) {
+    case DCADEC_PROFILE_DS:
+        avctx->profile = FF_PROFILE_DTS;
+        break;
+    case DCADEC_PROFILE_DS_96_24:
+        avctx->profile = FF_PROFILE_DTS_96_24;
+        break;
+    case DCADEC_PROFILE_DS_ES:
+        avctx->profile = FF_PROFILE_DTS_ES;
+        break;
+    case DCADEC_PROFILE_HD_HRA:
+        avctx->profile = FF_PROFILE_DTS_HD_HRA;
+        break;
+    case DCADEC_PROFILE_HD_MA:
+        avctx->profile = FF_PROFILE_DTS_HD_MA;
+        break;
+    case DCADEC_PROFILE_EXPRESS:
+        avctx->profile = FF_PROFILE_DTS_EXPRESS;
+        break;
+    case DCADEC_PROFILE_UNKNOWN:
+    default:
+        avctx->profile = FF_PROFILE_UNKNOWN;
+        break;
+    }
+
+    /* bitrate is only meaningful if there are no HD extensions, as they distort the bitrate */
+    if (profile == DCADEC_PROFILE_DS || profile == DCADEC_PROFILE_DS_96_24 || profile == DCADEC_PROFILE_DS_ES) {
+        struct dcadec_core_info *info = dcadec_context_get_core_info(s->ctx);
+        avctx->bit_rate = info->bit_rate;
+        dcadec_context_free_core_info(info);
+    } else
+        avctx->bit_rate = 0;
+
+    frame->nb_samples = nsamples;
+    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
+        return ret;
+
+    for (i = 0; i < avctx->channels; i++) {
+        if (frame->format == AV_SAMPLE_FMT_S16P) {
+            int16_t *plane = (int16_t *)frame->extended_data[i];
+            for (k = 0; k < nsamples; k++)
+                plane[k] = samples[i][k];
+        } else {
+            int32_t *plane = (int32_t *)frame->extended_data[i];
+            int shift = 32 - bits_per_sample;
+            for (k = 0; k < nsamples; k++)
+                plane[k] = samples[i][k] << shift;
+        }
+    }
+
+    *got_frame_ptr = 1;
+
+    return avpkt->size;
+}
+
+static av_cold void dcadec_flush(AVCodecContext *avctx)
+{
+    DCADecContext *s = avctx->priv_data;
+    dcadec_context_clear(s->ctx);
+}
+
+static av_cold int dcadec_close(AVCodecContext *avctx)
+{
+    DCADecContext *s = avctx->priv_data;
+
+    dcadec_context_destroy(s->ctx);
+    s->ctx = NULL;
+
+    av_freep(&s->buffer);
+
+    return 0;
+}
+
+static av_cold int dcadec_init(AVCodecContext *avctx)
+{
+    DCADecContext *s = avctx->priv_data;
+
+    s->ctx = dcadec_context_create(0);
+    if (!s->ctx)
+        return AVERROR(ENOMEM);
+
+    avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
+    avctx->bits_per_raw_sample = 24;
+
+    return 0;
+}
+
+static const AVProfile profiles[] = {
+    { FF_PROFILE_DTS,         "DTS"         },
+    { FF_PROFILE_DTS_ES,      "DTS-ES"      },
+    { FF_PROFILE_DTS_96_24,   "DTS 96/24"   },
+    { FF_PROFILE_DTS_HD_HRA,  "DTS-HD HRA"  },
+    { FF_PROFILE_DTS_HD_MA,   "DTS-HD MA"   },
+    { FF_PROFILE_DTS_EXPRESS, "DTS Express" },
+    { FF_PROFILE_UNKNOWN },
+};
+
+AVCodec ff_libdcadec_decoder = {
+    .name           = "libdcadec",
+    .long_name      = NULL_IF_CONFIG_SMALL("dcadec DCA decoder"),
+    .type           = AVMEDIA_TYPE_AUDIO,
+    .id             = AV_CODEC_ID_DTS,
+    .priv_data_size = sizeof(DCADecContext),
+    .init           = dcadec_init,
+    .decode         = dcadec_decode_frame,
+    .close          = dcadec_close,
+    .flush          = dcadec_flush,
+    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_CHANNEL_CONF,
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S32P, AV_SAMPLE_FMT_S16P,
+                                                      AV_SAMPLE_FMT_NONE },
+    .profiles       = NULL_IF_CONFIG_SMALL(profiles),
+};
diff --git a/libavcodec/libfdk-aacdec.c b/libavcodec/libfdk-aacdec.c
index a8ed104..f7fc811 100644
--- a/libavcodec/libfdk-aacdec.c
+++ b/libavcodec/libfdk-aacdec.c
@@ -44,7 +44,7 @@
     int initialized;
     uint8_t *decoder_buffer;
     uint8_t *anc_buffer;
-    enum ConcealMethod conceal_method;
+    int conceal_method;
     int drc_level;
     int drc_boost;
     int drc_heavy;
diff --git a/libavcodec/libopenh264enc.c b/libavcodec/libopenh264enc.c
index 9be3a97..2b7bad3 100644
--- a/libavcodec/libopenh264enc.c
+++ b/libavcodec/libopenh264enc.c
@@ -39,6 +39,10 @@
     char *profile;
 } SVCContext;
 
+#define OPENH264_VER_AT_LEAST(maj, min) \
+    ((OPENH264_MAJOR  > (maj)) || \
+     (OPENH264_MAJOR == (maj) && OPENH264_MINOR >= (min)))
+
 #define OFFSET(x) offsetof(SVCContext, x)
 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
 static const AVOption options[] = {
@@ -103,7 +107,11 @@
     param.bEnableLongTermReference   = 0;
     param.iLtrMarkPeriod             = 30;
     param.uiIntraPeriod              = avctx->gop_size;
+#if OPENH264_VER_AT_LEAST(1, 4)
+    param.eSpsPpsIdStrategy          = CONSTANT_ID;
+#else
     param.bEnableSpsPpsIdAddition    = 0;
+#endif
     param.bPrefixNalAddingCtrl       = 0;
     param.iLoopFilterDisableIdc      = !s->loopfilter;
     param.iEntropyCodingModeFlag     = 0;
@@ -220,7 +228,7 @@
     .encode2        = svc_encode_frame,
     .close          = svc_encode_close,
     .capabilities   = CODEC_CAP_AUTO_THREADS,
-    .pix_fmts       = (const enum PixelFormat[]){ AV_PIX_FMT_YUV420P,
-                                                  AV_PIX_FMT_NONE },
+    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P,
+                                                    AV_PIX_FMT_NONE },
     .priv_class     = &class,
 };
diff --git a/libavcodec/libopenjpegdec.c b/libavcodec/libopenjpegdec.c
index 0cf46e6..1cd1b9b 100644
--- a/libavcodec/libopenjpegdec.c
+++ b/libavcodec/libopenjpegdec.c
@@ -51,7 +51,7 @@
                            AV_PIX_FMT_RGB48, AV_PIX_FMT_RGBA64
 
 #define GRAY_PIXEL_FORMATS AV_PIX_FMT_GRAY8, AV_PIX_FMT_YA8,                  \
-                           AV_PIX_FMT_GRAY16
+                           AV_PIX_FMT_GRAY16, AV_PIX_FMT_YA16
 
 #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, \
@@ -80,7 +80,7 @@
     RGB_PIXEL_FORMATS, GRAY_PIXEL_FORMATS, YUV_PIXEL_FORMATS, XYZ_PIXEL_FORMATS
 };
 
-typedef struct {
+typedef struct LibOpenJPEGContext {
     AVClass *class;
     opj_dparameters_t dec_params;
     int lowqual;
@@ -184,10 +184,11 @@
 
 static inline void libopenjpeg_copy_to_packed16(AVFrame *picture, opj_image_t *image) {
     uint16_t *img_ptr;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(picture->format);
     int index, x, y, c;
     int adjust[4];
     for (x = 0; x < image->numcomps; x++)
-        adjust[x] = FFMAX(FFMIN(av_pix_fmt_desc_get(picture->format)->comp[x].depth_minus1 + 1 - image->comps[x].prec, 8), 0);
+        adjust[x] = FFMAX(FFMIN(desc->comp[x].depth_minus1 + 1 - image->comps[x].prec, 8), 0) + desc->comp[x].shift;
 
     for (y = 0; y < picture->height; y++) {
         index   = y * picture->width;
@@ -220,10 +221,11 @@
 static inline void libopenjpeg_copyto16(AVFrame *picture, opj_image_t *image) {
     int *comp_data;
     uint16_t *img_ptr;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(picture->format);
     int index, x, y;
     int adjust[4];
     for (x = 0; x < image->numcomps; x++)
-        adjust[x] = FFMAX(FFMIN(av_pix_fmt_desc_get(picture->format)->comp[x].depth_minus1 + 1 - image->comps[x].prec, 8), 0);
+        adjust[x] = FFMAX(FFMIN(desc->comp[x].depth_minus1 + 1 - image->comps[x].prec, 8), 0) + desc->comp[x].shift;
 
     for (index = 0; index < image->numcomps; index++) {
         comp_data = image->comps[index].data;
diff --git a/libavcodec/libopenjpegenc.c b/libavcodec/libopenjpegenc.c
index 4039663..95b0987 100644
--- a/libavcodec/libopenjpegenc.c
+++ b/libavcodec/libopenjpegenc.c
@@ -40,12 +40,10 @@
 # include <openjpeg.h>
 #endif
 
-typedef struct {
+typedef struct LibOpenJPEGContext {
     AVClass *avclass;
     opj_image_t *image;
-    opj_cio_t *stream;
     opj_cparameters_t enc_params;
-    opj_cinfo_t *compress;
     opj_event_mgr_t event_mgr;
     int format;
     int profile;
@@ -73,6 +71,43 @@
     av_log(data, AV_LOG_DEBUG, "%s\n", msg);
 }
 
+static void cinema_parameters(opj_cparameters_t *p)
+{
+    p->tile_size_on = 0;
+    p->cp_tdx = 1;
+    p->cp_tdy = 1;
+
+    /* Tile part */
+    p->tp_flag = 'C';
+    p->tp_on = 1;
+
+    /* Tile and Image shall be at (0, 0) */
+    p->cp_tx0 = 0;
+    p->cp_ty0 = 0;
+    p->image_offset_x0 = 0;
+    p->image_offset_y0 = 0;
+
+    /* Codeblock size= 32 * 32 */
+    p->cblockw_init = 32;
+    p->cblockh_init = 32;
+    p->csty |= 0x01;
+
+    /* The progression order shall be CPRL */
+    p->prog_order = CPRL;
+
+    /* No ROI */
+    p->roi_compno = -1;
+
+    /* No subsampling */
+    p->subsampling_dx = 1;
+    p->subsampling_dy = 1;
+
+    /* 9-7 transform */
+    p->irreversible = 1;
+
+    p->tcp_mct = 1;
+}
+
 static opj_image_t *mj2_create_image(AVCodecContext *avctx, opj_cparameters_t *parameters)
 {
     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
@@ -95,6 +130,7 @@
     case AV_PIX_FMT_GRAY8:
     case AV_PIX_FMT_YA8:
     case AV_PIX_FMT_GRAY16:
+    case AV_PIX_FMT_YA16:
         color_space = CLRSPC_GRAY;
         break;
     case AV_PIX_FMT_RGB24:
@@ -193,38 +229,7 @@
     ctx->enc_params.tcp_rates[0] = FFMAX(avctx->compression_level, 0) * 2;
 
     if (ctx->cinema_mode > 0) {
-        ctx->enc_params.irreversible = 1;
-        ctx->enc_params.tcp_mct = 1;
-        ctx->enc_params.tile_size_on = 0;
-        /* no subsampling */
-        ctx->enc_params.cp_tdx=1;
-        ctx->enc_params.cp_tdy=1;
-        ctx->enc_params.subsampling_dx = 1;
-        ctx->enc_params.subsampling_dy = 1;
-        /* Tile and Image shall be at (0,0) */
-        ctx->enc_params.cp_tx0 = 0;
-        ctx->enc_params.cp_ty0 = 0;
-        ctx->enc_params.image_offset_x0 = 0;
-        ctx->enc_params.image_offset_y0 = 0;
-        /* Codeblock size= 32*32 */
-        ctx->enc_params.cblockw_init = 32;
-        ctx->enc_params.cblockh_init = 32;
-        ctx->enc_params.csty |= 0x01;
-        /* No ROI */
-        ctx->enc_params.roi_compno = -1;
-
-        if (ctx->enc_params.prog_order != CPRL) {
-            av_log(avctx, AV_LOG_ERROR, "prog_order forced to CPRL\n");
-            ctx->enc_params.prog_order = CPRL;
-        }
-        ctx->enc_params.tp_flag = 'C';
-        ctx->enc_params.tp_on = 1;
-    }
-
-    ctx->compress = opj_create_compress(ctx->format);
-    if (!ctx->compress) {
-        av_log(avctx, AV_LOG_ERROR, "Error creating the compressor\n");
-        return AVERROR(ENOMEM);
+        cinema_parameters(&ctx->enc_params);
     }
 
     ctx->image = mj2_create_image(avctx, &ctx->enc_params);
@@ -240,20 +245,12 @@
         goto fail;
     }
 
-    memset(&ctx->event_mgr, 0, sizeof(opj_event_mgr_t));
-    ctx->event_mgr.info_handler    = info_callback;
-    ctx->event_mgr.error_handler = error_callback;
-    ctx->event_mgr.warning_handler = warning_callback;
-    opj_set_event_mgr((opj_common_ptr) ctx->compress, &ctx->event_mgr, avctx);
-
     return 0;
 
 fail:
-    opj_destroy_compress(ctx->compress);
-    ctx->compress = NULL;
     opj_image_destroy(ctx->image);
     ctx->image = NULL;
-    av_freep(&avctx->coded_frame);
+    av_frame_free(&avctx->coded_frame);
     return err;
 }
 
@@ -464,9 +461,9 @@
                                     const AVFrame *frame, int *got_packet)
 {
     LibOpenJPEGContext *ctx = avctx->priv_data;
-    opj_cinfo_t *compress   = ctx->compress;
     opj_image_t *image      = ctx->image;
-    opj_cio_t *stream       = ctx->stream;
+    opj_cinfo_t *compress   = NULL;
+    opj_cio_t *stream       = NULL;
     int cpyresult = 0;
     int ret, len;
     AVFrame *gbrframe;
@@ -482,6 +479,7 @@
         break;
     case AV_PIX_FMT_RGB48:
     case AV_PIX_FMT_RGBA64:
+    case AV_PIX_FMT_YA16:
         cpyresult = libopenjpeg_copy_packed16(avctx, frame, image);
         break;
     case AV_PIX_FMT_GBR24P:
@@ -559,6 +557,12 @@
         return -1;
     }
 
+    compress = opj_create_compress(ctx->format);
+    if (!compress) {
+        av_log(avctx, AV_LOG_ERROR, "Error creating the compressor\n");
+        return AVERROR(ENOMEM);
+    }
+
     opj_setup_encoder(compress, &ctx->enc_params, image);
 
     stream = opj_cio_open((opj_common_ptr) compress, NULL, 0);
@@ -567,6 +571,12 @@
         return AVERROR(ENOMEM);
     }
 
+    memset(&ctx->event_mgr, 0, sizeof(opj_event_mgr_t));
+    ctx->event_mgr.info_handler    = info_callback;
+    ctx->event_mgr.error_handler   = error_callback;
+    ctx->event_mgr.warning_handler = warning_callback;
+    opj_set_event_mgr((opj_common_ptr) compress, &ctx->event_mgr, avctx);
+
     if (!opj_encode(compress, stream, image, NULL)) {
         av_log(avctx, AV_LOG_ERROR, "Error during the opj encode\n");
         return -1;
@@ -580,6 +590,12 @@
     memcpy(pkt->data, stream->buffer, len);
     pkt->flags |= AV_PKT_FLAG_KEY;
     *got_packet = 1;
+
+    opj_cio_close(stream);
+    stream = NULL;
+    opj_destroy_compress(compress);
+    compress = NULL;
+
     return 0;
 }
 
@@ -587,13 +603,9 @@
 {
     LibOpenJPEGContext *ctx = avctx->priv_data;
 
-    opj_cio_close(ctx->stream);
-    ctx->stream = NULL;
-    opj_destroy_compress(ctx->compress);
-    ctx->compress = NULL;
     opj_image_destroy(ctx->image);
     ctx->image = NULL;
-    av_freep(&avctx->coded_frame);
+    av_frame_free(&avctx->coded_frame);
     return 0;
 }
 
@@ -647,7 +659,7 @@
         AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA, AV_PIX_FMT_RGB48,
         AV_PIX_FMT_RGBA64, AV_PIX_FMT_GBR24P,
         AV_PIX_FMT_GBRP9, AV_PIX_FMT_GBRP10, AV_PIX_FMT_GBRP12, AV_PIX_FMT_GBRP14, AV_PIX_FMT_GBRP16,
-        AV_PIX_FMT_GRAY8, AV_PIX_FMT_YA8, AV_PIX_FMT_GRAY16,
+        AV_PIX_FMT_GRAY8, AV_PIX_FMT_YA8, AV_PIX_FMT_GRAY16, AV_PIX_FMT_YA16,
         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,
diff --git a/libavcodec/libschroedingerdec.c b/libavcodec/libschroedingerdec.c
index dca3379..8778869 100644
--- a/libavcodec/libschroedingerdec.c
+++ b/libavcodec/libschroedingerdec.c
@@ -267,6 +267,8 @@
                 /* Decoder needs a frame - create one and push it in. */
                 frame = ff_create_schro_frame(avctx,
                                               p_schro_params->frame_format);
+                if (!frame)
+                    return AVERROR(ENOMEM);
                 schro_decoder_add_output_picture(decoder, frame);
                 break;
 
diff --git a/libavcodec/libschroedingerenc.c b/libavcodec/libschroedingerenc.c
index 294fb06..f7a3235 100644
--- a/libavcodec/libschroedingerenc.c
+++ b/libavcodec/libschroedingerenc.c
@@ -284,6 +284,8 @@
     } else {
         /* Allocate frame data to schro input buffer. */
         SchroFrame *in_frame = libschroedinger_frame_from_data(avctx, frame);
+        if (!in_frame)
+            return AVERROR(ENOMEM);
         /* Load next frame. */
         schro_encoder_push_frame(encoder, in_frame);
     }
@@ -332,6 +334,8 @@
 
             /* Create output frame. */
             p_frame_output = av_mallocz(sizeof(FFSchroEncodedFrame));
+            if (!p_frame_output)
+                return AVERROR(ENOMEM);
             /* Set output data. */
             p_frame_output->size     = p_schro_params->enc_buf_size;
             p_frame_output->p_encbuf = p_schro_params->enc_buf;
diff --git a/libavcodec/libspeexdec.c b/libavcodec/libspeexdec.c
index a5f52d1..6ca592a 100644
--- a/libavcodec/libspeexdec.c
+++ b/libavcodec/libspeexdec.c
@@ -28,7 +28,7 @@
 #include "avcodec.h"
 #include "internal.h"
 
-typedef struct {
+typedef struct LibSpeexContext {
     SpeexBits bits;
     SpeexStereoState stereo;
     void *dec_state;
diff --git a/libavcodec/libspeexenc.c b/libavcodec/libspeexenc.c
index 21238aa..22d0d6e 100644
--- a/libavcodec/libspeexenc.c
+++ b/libavcodec/libspeexenc.c
@@ -93,7 +93,7 @@
 #include "audio_frame_queue.h"
 
 /* TODO: Think about converting abr, vad, dtx and such flags to a bit field */
-typedef struct {
+typedef struct LibSpeexEncContext {
     AVClass *class;             ///< AVClass for private options
     SpeexBits bits;             ///< libspeex bitwriter context
     SpeexHeader header;         ///< libspeex header struct
diff --git a/libavcodec/libtheoraenc.c b/libavcodec/libtheoraenc.c
index 4c90822..9366a95 100644
--- a/libavcodec/libtheoraenc.c
+++ b/libavcodec/libtheoraenc.c
@@ -99,8 +99,11 @@
         return AVERROR_EXTERNAL;
     }
     if (!eos) {
-        h->stats = av_fast_realloc(h->stats, &h->stats_size,
+        void *tmp = av_fast_realloc(h->stats, &h->stats_size,
                                    h->stats_offset + bytes);
+        if (!tmp)
+            return AVERROR(ENOMEM);
+        h->stats = tmp;
         memcpy(h->stats + h->stats_offset, buf, bytes);
         h->stats_offset += bytes;
     } else {
@@ -131,6 +134,10 @@
         }
         h->stats_size = strlen(avctx->stats_in) * 3/4;
         h->stats      = av_malloc(h->stats_size);
+        if (!h->stats) {
+            h->stats_size = 0;
+            return AVERROR(ENOMEM);
+        }
         h->stats_size = av_base64_decode(h->stats, avctx->stats_in, h->stats_size);
     }
     while (h->stats_size - h->stats_offset > 0) {
@@ -260,6 +267,8 @@
 
     /* Set up the output AVFrame */
     avc_context->coded_frame = av_frame_alloc();
+    if (!avc_context->coded_frame)
+        return AVERROR(ENOMEM);
 
     return 0;
 }
@@ -352,7 +361,7 @@
 
     th_encode_free(h->t_state);
     av_freep(&h->stats);
-    av_freep(&avc_context->coded_frame);
+    av_frame_free(&avc_context->coded_frame);
     av_freep(&avc_context->stats_out);
     av_freep(&avc_context->extradata);
     avc_context->extradata_size = 0;
diff --git a/libavcodec/libutvideoenc.cpp b/libavcodec/libutvideoenc.cpp
index b430a44..3b88fff 100644
--- a/libavcodec/libutvideoenc.cpp
+++ b/libavcodec/libutvideoenc.cpp
@@ -209,7 +209,7 @@
 {
     UtVideoContext *utv = (UtVideoContext *)avctx->priv_data;
 
-    av_freep(&avctx->coded_frame);
+    av_frame_free(&avctx->coded_frame);
     av_freep(&avctx->extradata);
     av_freep(&utv->buffer);
 
diff --git a/libavcodec/libvpxenc.c b/libavcodec/libvpxenc.c
index 4cb0e21..176c6b6 100644
--- a/libavcodec/libvpxenc.c
+++ b/libavcodec/libvpxenc.c
@@ -253,7 +253,7 @@
     if (ctx->is_alpha)
         vpx_codec_destroy(&ctx->encoder_alpha);
     av_freep(&ctx->twopass_stats.buf);
-    av_freep(&avctx->coded_frame);
+    av_frame_free(&avctx->coded_frame);
     av_freep(&avctx->stats_out);
     free_frame_list(ctx->coded_frame_list);
     return 0;
@@ -330,10 +330,15 @@
         }
     }
 
-    if (avctx->qmin >= 0)
-        enccfg.rc_min_quantizer = avctx->qmin;
-    if (avctx->qmax >= 0)
-        enccfg.rc_max_quantizer = avctx->qmax;
+    if (avctx->codec_id == AV_CODEC_ID_VP9 && ctx->lossless == 1) {
+        enccfg.rc_min_quantizer =
+        enccfg.rc_max_quantizer = 0;
+    } else {
+        if (avctx->qmin >= 0)
+            enccfg.rc_min_quantizer = avctx->qmin;
+        if (avctx->qmax >= 0)
+            enccfg.rc_max_quantizer = avctx->qmax;
+    }
 
     if (enccfg.rc_end_usage == VPX_CQ
 #if CONFIG_LIBVPX_VP9_ENCODER
@@ -377,7 +382,7 @@
     if (enccfg.g_pass == VPX_RC_FIRST_PASS)
         enccfg.g_lag_in_frames = 0;
     else if (enccfg.g_pass == VPX_RC_LAST_PASS) {
-        int decode_size;
+        int decode_size, ret;
 
         if (!avctx->stats_in) {
             av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
@@ -385,12 +390,13 @@
         }
 
         ctx->twopass_stats.sz  = strlen(avctx->stats_in) * 3 / 4;
-        ctx->twopass_stats.buf = av_malloc(ctx->twopass_stats.sz);
-        if (!ctx->twopass_stats.buf) {
+        ret = av_reallocp(&ctx->twopass_stats.buf, ctx->twopass_stats.sz);
+        if (ret < 0) {
             av_log(avctx, AV_LOG_ERROR,
                    "Stat buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
                    ctx->twopass_stats.sz);
-            return AVERROR(ENOMEM);
+            ctx->twopass_stats.sz = 0;
+            return ret;
         }
         decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
                                        ctx->twopass_stats.sz);
@@ -717,9 +723,14 @@
             rawimg_alpha = &ctx->rawimg_alpha;
             rawimg_alpha->planes[VPX_PLANE_Y] = frame->data[3];
             u_plane = av_malloc(frame->linesize[1] * frame->height);
+            v_plane = av_malloc(frame->linesize[2] * frame->height);
+            if (!u_plane || !v_plane) {
+                av_free(u_plane);
+                av_free(v_plane);
+                return AVERROR(ENOMEM);
+            }
             memset(u_plane, 0x80, frame->linesize[1] * frame->height);
             rawimg_alpha->planes[VPX_PLANE_U] = u_plane;
-            v_plane = av_malloc(frame->linesize[2] * frame->height);
             memset(v_plane, 0x80, frame->linesize[2] * frame->height);
             rawimg_alpha->planes[VPX_PLANE_V] = v_plane;
             rawimg_alpha->stride[VPX_PLANE_Y] = frame->linesize[0];
diff --git a/libavcodec/libx264.c b/libavcodec/libx264.c
index 4da0ee0..72a0716 100644
--- a/libavcodec/libx264.c
+++ b/libavcodec/libx264.c
@@ -268,11 +268,11 @@
     }
     do {
         if (x264_encoder_encode(x4->enc, &nal, &nnal, frame? &x4->pic: NULL, &pic_out) < 0)
-            return -1;
+            return AVERROR_EXTERNAL;
 
         ret = encode_nals(ctx, pkt, nal, nnal);
         if (ret < 0)
-            return -1;
+            return ret;
     } while (!ret && !frame && x264_encoder_delayed_frames(x4->enc));
 
     pkt->pts = pic_out.i_pts;
@@ -687,7 +687,7 @@
 
     x4->enc = x264_encoder_open(&x4->params);
     if (!x4->enc)
-        return -1;
+        return AVERROR_EXTERNAL;
 
     avctx->coded_frame = av_frame_alloc();
     if (!avctx->coded_frame)
@@ -700,6 +700,8 @@
 
         s = x264_encoder_headers(x4->enc, &nal, &nnal);
         avctx->extradata = p = av_malloc(s);
+        if (!p)
+            goto nomem;
 
         for (i = 0; i < nnal; i++) {
             /* Don't put the SEI in extradata. */
@@ -707,6 +709,8 @@
                 av_log(avctx, AV_LOG_INFO, "%s\n", nal[i].p_payload+25);
                 x4->sei_size = nal[i].i_payload;
                 x4->sei      = av_malloc(x4->sei_size);
+                if (!x4->sei)
+                    goto nomem;
                 memcpy(x4->sei, nal[i].p_payload, nal[i].i_payload);
                 continue;
             }
@@ -717,6 +721,9 @@
     }
 
     return 0;
+nomem:
+    X264_close(avctx);
+    return AVERROR(ENOMEM);
 }
 
 static const enum AVPixelFormat pix_fmts_8bit[] = {
@@ -777,7 +784,10 @@
     { "aq-mode",       "AQ method",                                       OFFSET(aq_mode),       AV_OPT_TYPE_INT,    { .i64 = -1 }, -1, INT_MAX, VE, "aq_mode"},
     { "none",          NULL,                              0, AV_OPT_TYPE_CONST, {.i64 = X264_AQ_NONE},         INT_MIN, INT_MAX, VE, "aq_mode" },
     { "variance",      "Variance AQ (complexity mask)",   0, AV_OPT_TYPE_CONST, {.i64 = X264_AQ_VARIANCE},     INT_MIN, INT_MAX, VE, "aq_mode" },
-    { "autovariance",  "Auto-variance AQ (experimental)", 0, AV_OPT_TYPE_CONST, {.i64 = X264_AQ_AUTOVARIANCE}, INT_MIN, INT_MAX, VE, "aq_mode" },
+    { "autovariance",  "Auto-variance AQ",                0, AV_OPT_TYPE_CONST, {.i64 = X264_AQ_AUTOVARIANCE}, INT_MIN, INT_MAX, VE, "aq_mode" },
+#if X264_BUILD >= 144
+    { "autovariance-biased", "Auto-variance AQ with bias to dark scenes", 0, AV_OPT_TYPE_CONST, {.i64 = X264_AQ_AUTOVARIANCE_BIASED}, INT_MIN, INT_MAX, VE, "aq_mode" },
+#endif
     { "aq-strength",   "AQ strength. Reduces blocking and blurring in flat and textured areas.", OFFSET(aq_strength), AV_OPT_TYPE_FLOAT, {.dbl = -1}, -1, FLT_MAX, VE},
     { "psy",           "Use psychovisual optimizations.",                 OFFSET(psy),           AV_OPT_TYPE_INT,    { .i64 = -1 }, -1, 1, VE },
     { "psy-rd",        "Strength of psychovisual optimization, in <psy-rd>:<psy-trellis> format.", OFFSET(psy_rd), AV_OPT_TYPE_STRING,  {0 }, 0, 0, VE},
diff --git a/libavcodec/libx265.c b/libavcodec/libx265.c
index aee7ae2..5a26ca9 100644
--- a/libavcodec/libx265.c
+++ b/libavcodec/libx265.c
@@ -25,6 +25,7 @@
 #endif
 
 #include <x265.h>
+#include <float.h>
 
 #include "libavutil/internal.h"
 #include "libavutil/common.h"
@@ -39,6 +40,7 @@
     x265_encoder *encoder;
     x265_param   *params;
 
+    float crf;
     char *preset;
     char *tune;
     char *x265_opts;
@@ -76,10 +78,6 @@
 static av_cold int libx265_encode_init(AVCodecContext *avctx)
 {
     libx265Context *ctx = avctx->priv_data;
-    x265_nal *nal;
-    char sar[12];
-    int sar_num, sar_den;
-    int nnal;
 
     if (avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL &&
         !av_pix_fmt_desc_get(avctx->pix_fmt)->log2_chroma_w) {
@@ -114,6 +112,9 @@
     ctx->params->bEnablePsnr     = !!(avctx->flags & CODEC_FLAG_PSNR);
 
     if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
+        char sar[12];
+        int sar_num, sar_den;
+
         av_reduce(&sar_num, &sar_den,
                   avctx->sample_aspect_ratio.num,
                   avctx->sample_aspect_ratio.den, 65535);
@@ -139,7 +140,15 @@
         break;
     }
 
-    if (avctx->bit_rate > 0) {
+    if (ctx->crf >= 0) {
+        char crf[6];
+
+        snprintf(crf, sizeof(crf), "%2.2f", ctx->crf);
+        if (x265_param_parse(ctx->params, "crf", crf) == X265_PARAM_BAD_VALUE) {
+            av_log(avctx, AV_LOG_ERROR, "Invalid crf: %2.2f.\n", ctx->crf);
+            return AVERROR(EINVAL);
+        }
+    } else if (avctx->bit_rate > 0) {
         ctx->params->rc.bitrate         = avctx->bit_rate / 1000;
         ctx->params->rc.rateControlMode = X265_RC_ABR;
     }
@@ -180,6 +189,9 @@
     }
 
     if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) {
+        x265_nal *nal;
+        int nnal;
+
         avctx->extradata_size = x265_encoder_headers(ctx->encoder, &nal, &nnal);
         if (avctx->extradata_size <= 0) {
             av_log(avctx, AV_LOG_ERROR, "Cannot encode headers.\n");
@@ -292,6 +304,7 @@
 #define OFFSET(x) offsetof(libx265Context, x)
 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
 static const AVOption options[] = {
+    { "crf",         "set the x265 crf",                                                            OFFSET(crf),       AV_OPT_TYPE_FLOAT,  { .dbl = -1 }, -1, FLT_MAX, VE },
     { "preset",      "set the x265 preset",                                                         OFFSET(preset),    AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
     { "tune",        "set the x265 tune parameter",                                                 OFFSET(tune),      AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
     { "x265-params", "set the x265 configuration using a :-separated list of key=value parameters", OFFSET(x265_opts), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
diff --git a/libavcodec/libxvid_rc.c b/libavcodec/libxvid_rc.c
index ac154aa..0fd030c 100644
--- a/libavcodec/libxvid_rc.c
+++ b/libavcodec/libxvid_rc.c
@@ -47,9 +47,9 @@
     xvid_plugin_2pass2_t xvid_2pass2  = { 0 };
 
     fd = av_tempfile("xvidrc.", &tmp_name, 0, s->avctx);
-    if (fd == -1) {
+    if (fd < 0) {
         av_log(NULL, AV_LOG_ERROR, "Can't create temporary pass2 file.\n");
-        return -1;
+        return fd;
     }
 
     for (i = 0; i < s->rc_context.num_entries; i++) {
diff --git a/libavcodec/lossless_audiodsp.h b/libavcodec/lossless_audiodsp.h
index c3ee2be..9ce2e63 100644
--- a/libavcodec/lossless_audiodsp.h
+++ b/libavcodec/lossless_audiodsp.h
@@ -29,7 +29,8 @@
     /**
      * Calculate scalar product of v1 and v2,
      * and v1[i] += v3[i] * mul
-     * @param len length of vectors, should be multiple of 8
+     * @param len length of vectors, should be multiple of 16,
+     *            or padd v3 and v1 or v2 with zeros.
      */
     int32_t (*scalarproduct_and_madd_int16)(int16_t *v1 /* align 16 */,
                                             const int16_t *v2,
diff --git a/libavcodec/mathops.h b/libavcodec/mathops.h
index 87fca0c..87d110b 100644
--- a/libavcodec/mathops.h
+++ b/libavcodec/mathops.h
@@ -121,6 +121,20 @@
 }
 #endif
 
+#ifndef median4
+#define median4 median4
+static inline av_const int median4(int a, int b, int c, int d)
+{
+    if (a < b) {
+        if (c < d) return (FFMIN(b, d) + FFMAX(a, c)) / 2;
+        else       return (FFMIN(b, c) + FFMAX(a, d)) / 2;
+    } else {
+        if (c < d) return (FFMIN(a, d) + FFMAX(b, c)) / 2;
+        else       return (FFMIN(a, c) + FFMAX(b, d)) / 2;
+    }
+}
+#endif
+
 #ifndef sign_extend
 static inline av_const int sign_extend(int val, unsigned bits)
 {
diff --git a/libavcodec/mdec.c b/libavcodec/mdec.c
index 051adae..5fd06f4 100644
--- a/libavcodec/mdec.c
+++ b/libavcodec/mdec.c
@@ -88,7 +88,12 @@
             if (level == 127) {
                 break;
             } else if (level != 0) {
-                i    += run;
+                i += run;
+                if (i > 63) {
+                    av_log(a->avctx, AV_LOG_ERROR,
+                           "ac-tex damaged at %d %d\n", a->mb_x, a->mb_y);
+                    return AVERROR_INVALIDDATA;
+                }
                 j     = scantable[i];
                 level = (level * qscale * quant_matrix[j]) >> 3;
                 level = (level ^ SHOW_SBITS(re, &a->gb, 1)) - SHOW_SBITS(re, &a->gb, 1);
@@ -98,8 +103,13 @@
                 run = SHOW_UBITS(re, &a->gb, 6)+1; LAST_SKIP_BITS(re, &a->gb, 6);
                 UPDATE_CACHE(re, &a->gb);
                 level = SHOW_SBITS(re, &a->gb, 10); SKIP_BITS(re, &a->gb, 10);
-                i    += run;
-                j     = scantable[i];
+                i += run;
+                if (i > 63) {
+                    av_log(a->avctx, AV_LOG_ERROR,
+                           "ac-tex damaged at %d %d\n", a->mb_x, a->mb_y);
+                    return AVERROR_INVALIDDATA;
+                }
+                j = scantable[i];
                 if (level < 0) {
                     level = -level;
                     level = (level * qscale * quant_matrix[j]) >> 3;
@@ -110,10 +120,6 @@
                     level = (level - 1) | 1;
                 }
             }
-            if (i > 63) {
-                av_log(a->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", a->mb_x, a->mb_y);
-                return AVERROR_INVALIDDATA;
-            }
 
             block[j] = level;
         }
diff --git a/libavcodec/me_cmp.c b/libavcodec/me_cmp.c
index cfd14ab..d4213d2 100644
--- a/libavcodec/me_cmp.c
+++ b/libavcodec/me_cmp.c
@@ -108,8 +108,8 @@
     return sum;
 }
 
-#define avg2(a, b) ((a + b + 1) >> 1)
-#define avg4(a, b, c, d) ((a + b + c + d + 2) >> 2)
+#define avg2(a, b) (((a) + (b) + 1) >> 1)
+#define avg4(a, b, c, d) (((a) + (b) + (c) + (d) + 2) >> 2)
 
 static inline int pix_abs16_c(MpegEncContext *v, uint8_t *pix1, uint8_t *pix2,
                               ptrdiff_t stride, int h)
diff --git a/libavcodec/metasound_data.c b/libavcodec/metasound_data.c
index ed23cdf..e439b3d 100644
--- a/libavcodec/metasound_data.c
+++ b/libavcodec/metasound_data.c
@@ -12747,185 +12747,6 @@
     -0.0429, -0.0615, -0.0893, -0.0618, -0.0384, -0.0134, -0.0232, -0.0238,
 };
 
-static const float lsp16s[] = {
-     0.1813,  0.3911,  0.6301,  0.8012,  1.0057,  1.2041,  1.4271,  1.6943,
-     1.9402,  2.1733,  2.3521,  2.4989,  2.5839,  2.6846,  2.7634,  2.8950,
-     0.1311,  0.3183,  0.4659,  0.5601,  0.6658,  0.7828,  1.0065,  1.2717,
-     1.5185,  1.7339,  1.9530,  2.2189,  2.3739,  2.4991,  2.6984,  2.9256,
-     0.1627,  0.4519,  0.6323,  0.7012,  0.7848,  0.9801,  1.1810,  1.3222,
-     1.5413,  1.8129,  1.9338,  2.0809,  2.3180,  2.5189,  2.7066,  2.9514,
-     0.1475,  0.2447,  0.4240,  0.5669,  0.7872,  0.9838,  1.1823,  1.3814,
-     1.5358,  1.6820,  1.8794,  2.1419,  2.4132,  2.6112,  2.7911,  2.9511,
-     0.1224,  0.2876,  0.5013,  0.6985,  0.8902,  1.0901,  1.2835,  1.4768,
-     1.6596,  1.8538,  2.0467,  2.2304,  2.4124,  2.5942,  2.7729,  2.9531,
-     0.1741,  0.3034,  0.4677,  0.5879,  0.7258,  0.9648,  1.1417,  1.3220,
-     1.5081,  1.7151,  1.9212,  2.1286,  2.3208,  2.4938,  2.6765,  2.8891,
-     0.1657,  0.3174,  0.4907,  0.6559,  0.8295,  1.0254,  1.2071,  1.3880,
-     1.5737,  1.7845,  1.9027,  2.1139,  2.3323,  2.5157,  2.7323,  2.9015,
-     0.1592,  0.2758,  0.4417,  0.6315,  0.8257,  0.9873,  1.1277,  1.2830,
-     1.4337,  1.6315,  1.8899,  2.1356,  2.3572,  2.5632,  2.7468,  2.9420,
-     0.1524,  0.4325,  0.5931,  0.7036,  0.7696,  0.8923,  1.1739,  1.4773,
-     1.6609,  1.7911,  1.9666,  2.1972,  2.3754,  2.5045,  2.6613,  2.8882,
-     0.2130,  0.3013,  0.3721,  0.4257,  0.5079,  0.7015,  0.9815,  1.2554,
-     1.4648,  1.6966,  1.9138,  2.1075,  2.3318,  2.5292,  2.7453,  2.9347,
-     0.1142,  0.3748,  0.6205,  0.7642,  0.8121,  0.9022,  0.9843,  1.1558,
-     1.4467,  1.7422,  1.9574,  2.1302,  2.3812,  2.5898,  2.7720,  2.9583,
-     0.1255,  0.2339,  0.3570,  0.5323,  0.7458,  1.0003,  1.1729,  1.3567,
-     1.5217,  1.6977,  1.8924,  2.0942,  2.3145,  2.5408,  2.7553,  2.9337,
-     0.1316,  0.2289,  0.4327,  0.6663,  0.8509,  0.9994,  1.1697,  1.3804,
-     1.5609,  1.6903,  1.8572,  2.1019,  2.3687,  2.5789,  2.7715,  2.9472,
-     0.1502,  0.2546,  0.3883,  0.5333,  0.6976,  0.9163,  1.1071,  1.3364,
-     1.5420,  1.7525,  1.8948,  2.0839,  2.2819,  2.4651,  2.6875,  2.8987,
-     0.1593,  0.3014,  0.4573,  0.6354,  0.8157,  0.9805,  1.1783,  1.3747,
-     1.5678,  1.7326,  1.9286,  2.1340,  2.3253,  2.5280,  2.7180,  2.9298,
-     0.1811,  0.3167,  0.4655,  0.6507,  0.8198,  1.0075,  1.1892,  1.3743,
-     1.5227,  1.7090,  1.8849,  2.0743,  2.2750,  2.4830,  2.6896,  2.8953,
-     0.1846,  0.3577,  0.5315,  0.7290,  0.9176,  1.1016,  1.2654,  1.4525,
-     1.6315,  1.8268,  2.0238,  2.1934,  2.3868,  2.5753,  2.7682,  2.9469,
-     0.0876,  0.1439,  0.2048,  0.3654,  0.6281,  0.8853,  1.0907,  1.2992,
-     1.5227,  1.7373,  1.9395,  2.1419,  2.3488,  2.5486,  2.7466,  2.9348,
-     0.1391,  0.4170,  0.6561,  0.7953,  0.8734,  0.9986,  1.1870,  1.4520,
-     1.6042,  1.7910,  2.0135,  2.1870,  2.3358,  2.5066,  2.7409,  2.9955,
-     0.0804,  0.1355,  0.2599,  0.4998,  0.7408,  0.9474,  1.1276,  1.3428,
-     1.5556,  1.7712,  1.9699,  2.1535,  2.3605,  2.5548,  2.7489,  2.9325,
-     0.1304,  0.3087,  0.4979,  0.6584,  0.8414,  1.0329,  1.2244,  1.4189,
-     1.6118,  1.8200,  1.9985,  2.1893,  2.3915,  2.5794,  2.7647,  2.9344,
-     0.1895,  0.2849,  0.3705,  0.4126,  0.6265,  0.9207,  1.1774,  1.3762,
-     1.5757,  1.7728,  1.9568,  2.1662,  2.3615,  2.5575,  2.7561,  2.9416,
-     0.1800,  0.3078,  0.4805,  0.6796,  0.8503,  1.0046,  1.1703,  1.3269,
-     1.4862,  1.6502,  1.8454,  2.0873,  2.3175,  2.5356,  2.7516,  2.9469,
-     0.1950,  0.3233,  0.4568,  0.5940,  0.7589,  0.9978,  1.1701,  1.3383,
-     1.5017,  1.6565,  1.8243,  2.0605,  2.2938,  2.5147,  2.7419,  2.9396,
-     0.2531,  0.4391,  0.5790,  0.7170,  0.8998,  1.1430,  1.3577,  1.5326,
-     1.6328,  1.7627,  1.9726,  2.1762,  2.3563,  2.5478,  2.7385,  2.9067,
-     0.1805,  0.2788,  0.3591,  0.3881,  0.5441,  0.8055,  1.0766,  1.3165,
-     1.5316,  1.7508,  1.9477,  2.1374,  2.3438,  2.5484,  2.7501,  2.9410,
-     0.2044,  0.3671,  0.5396,  0.7042,  0.8582,  0.9831,  1.1261,  1.3194,
-     1.4769,  1.6979,  1.8717,  2.0463,  2.2620,  2.4739,  2.7054,  2.9208,
-     0.1048,  0.2175,  0.4206,  0.5923,  0.7483,  0.9400,  1.1356,  1.3799,
-     1.5958,  1.7320,  1.8984,  2.1296,  2.3594,  2.5492,  2.7387,  2.9305,
-     0.0842,  0.1729,  0.3951,  0.6447,  0.8688,  1.0605,  1.2472,  1.4330,
-     1.6232,  1.8144,  2.0216,  2.1915,  2.3878,  2.5763,  2.7685,  2.9464,
-     0.1461,  0.2593,  0.4105,  0.5677,  0.7328,  0.8919,  1.0484,  1.2302,
-     1.4386,  1.6635,  1.8873,  2.1024,  2.3116,  2.5268,  2.7273,  2.9269,
-     0.1503,  0.3108,  0.4756,  0.6731,  0.8600,  1.0233,  1.2115,  1.3971,
-     1.5915,  1.7892,  1.9517,  2.1603,  2.3487,  2.5460,  2.7308,  2.8998,
-     0.2163,  0.3669,  0.5125,  0.6709,  0.8143,  0.9930,  1.2095,  1.4205,
-     1.6176,  1.7112,  1.8398,  2.0896,  2.3513,  2.5290,  2.6667,  2.8960,
-     0.2133,  0.4382,  0.6287,  0.8702,  1.1088,  1.3749,  1.6062,  1.7446,
-     1.8333,  1.9122,  1.9614,  2.0669,  2.1789,  2.3449,  2.6038,  2.8849,
-     0.1598,  0.2719,  0.3877,  0.4815,  0.5926,  0.7795,  1.0449,  1.3045,
-     1.5210,  1.7391,  1.9462,  2.1397,  2.3553,  2.5458,  2.7540,  2.9392,
-     0.2918,  0.5607,  0.6801,  0.7404,  0.8285,  0.9431,  1.1579,  1.4080,
-     1.6332,  1.8472,  1.9738,  2.0771,  2.2890,  2.5178,  2.7445,  2.9830,
-     0.1664,  0.2842,  0.3965,  0.5463,  0.8162,  1.0346,  1.1849,  1.3446,
-     1.5122,  1.7563,  1.9960,  2.2002,  2.3796,  2.5689,  2.7712,  2.9550,
-     0.0911,  0.2397,  0.5052,  0.7868,  1.0299,  1.1311,  1.2244,  1.3333,
-     1.4395,  1.6790,  1.9369,  2.1717,  2.3689,  2.5538,  2.7340,  2.9326,
-     0.1647,  0.2931,  0.3836,  0.4978,  0.6255,  0.9243,  1.1339,  1.3001,
-     1.5269,  1.8010,  1.9715,  2.1419,  2.3784,  2.5503,  2.6719,  2.8745,
-     0.2440,  0.3802,  0.4756,  0.6613,  0.8627,  1.0292,  1.2291,  1.4060,
-     1.5198,  1.7354,  1.9044,  2.1010,  2.3147,  2.4996,  2.7171,  2.9041,
-     0.1590,  0.2876,  0.4572,  0.5996,  0.7713,  0.9490,  1.1205,  1.2815,
-     1.4516,  1.6385,  1.8179,  2.0457,  2.2759,  2.4785,  2.6861,  2.9080,
-     0.2297,  0.4309,  0.5712,  0.6717,  0.8138,  1.0463,  1.2492,  1.4560,
-     1.6796,  1.8458,  1.9642,  2.1452,  2.3636,  2.5395,  2.7456,  2.9495,
-     0.2975,  0.4678,  0.4996,  0.5809,  0.6279,  0.6884,  0.8606,  1.1386,
-     1.4412,  1.6876,  1.8760,  2.0932,  2.3178,  2.5166,  2.7345,  2.9280,
-     0.1278,  0.3737,  0.6004,  0.7069,  0.8147,  1.0180,  1.2581,  1.3812,
-     1.4855,  1.7268,  1.9970,  2.1258,  2.2936,  2.5702,  2.7563,  2.8983,
-     0.1314,  0.2508,  0.3999,  0.5680,  0.7424,  0.9367,  1.1286,  1.3175,
-     1.5336,  1.7404,  1.9317,  2.1404,  2.3514,  2.5562,  2.7510,  2.9402,
-     0.1043,  0.2367,  0.4293,  0.6376,  0.8160,  0.9836,  1.1779,  1.3850,
-     1.5835,  1.7875,  1.9765,  2.1593,  2.3654,  2.5577,  2.7465,  2.9398,
-     0.1529,  0.2515,  0.3454,  0.4374,  0.7011,  0.9015,  1.0744,  1.3532,
-     1.5699,  1.7545,  2.0021,  2.1259,  2.2278,  2.4546,  2.7264,  2.9425,
-     0.1429,  0.2808,  0.4395,  0.6334,  0.8069,  0.9705,  1.1520,  1.3250,
-     1.5109,  1.7285,  1.9356,  2.1469,  2.3479,  2.5554,  2.7512,  2.9348,
-     0.1625,  0.3022,  0.4756,  0.6315,  0.8032,  0.9924,  1.1596,  1.3204,
-     1.4994,  1.6929,  1.8955,  2.1090,  2.3025,  2.5018,  2.6908,  2.8980,
-     0.1692,  0.3427,  0.5228,  0.7756,  0.9688,  1.0950,  1.3056,  1.4360,
-     1.5675,  1.8049,  1.9376,  2.1151,  2.3407,  2.5012,  2.7192,  2.9258,
-     0.0474,  0.1251,  0.1939,  0.3841,  0.6501,  0.9231,  1.1153,  1.3240,
-     1.5478,  1.7599,  1.9651,  2.1510,  2.3645,  2.5552,  2.7542,  2.9393,
-     0.2196,  0.4656,  0.7492,  0.9922,  1.1678,  1.2489,  1.3112,  1.3657,
-     1.4223,  1.5302,  1.7212,  1.9996,  2.2523,  2.4844,  2.7036,  2.9145,
-     0.1128,  0.2368,  0.3704,  0.5476,  0.7723,  0.9968,  1.1930,  1.3992,
-     1.6013,  1.7957,  1.9888,  2.1857,  2.3825,  2.5705,  2.7616,  2.9434,
-     0.1341,  0.2768,  0.4510,  0.6359,  0.8332,  1.0335,  1.2004,  1.3952,
-     1.5762,  1.7681,  1.9815,  2.1735,  2.3657,  2.5552,  2.7514,  2.9498,
-     0.1247,  0.2559,  0.3516,  0.4726,  0.6861,  0.9483,  1.1852,  1.3858,
-     1.5851,  1.7815,  1.9778,  2.1737,  2.3729,  2.5664,  2.7620,  2.9429,
-     0.1988,  0.3320,  0.4777,  0.6737,  0.8425,  1.0265,  1.1694,  1.3655,
-     1.5463,  1.7135,  1.9385,  2.1650,  2.3529,  2.5367,  2.7545,  2.9585,
-     0.1376,  0.2620,  0.4273,  0.6169,  0.7755,  0.9441,  1.1169,  1.3157,
-     1.5179,  1.7020,  1.8931,  2.1059,  2.3112,  2.5136,  2.7169,  2.9198,
-     0.2112,  0.4385,  0.6091,  0.7618,  0.9553,  1.1543,  1.3445,  1.5396,
-     1.7153,  1.9192,  2.1263,  2.3593,  2.5958,  2.8171,  2.9394,  3.0409,
-     0.1347,  0.2099,  0.2646,  0.3453,  0.5266,  0.7869,  1.0513,  1.2795,
-     1.4880,  1.7181,  1.9294,  2.1332,  2.3362,  2.5442,  2.7433,  2.9362,
-     0.3141,  0.5935,  0.7517,  0.8313,  0.8568,  0.9570,  1.0250,  1.1275,
-     1.3422,  1.6303,  1.8577,  2.0705,  2.2957,  2.5095,  2.7244,  2.9262,
-     0.0962,  0.2116,  0.3961,  0.5641,  0.7122,  0.8883,  1.1023,  1.3481,
-     1.5623,  1.7554,  1.9618,  2.1675,  2.3706,  2.5556,  2.7430,  2.9337,
-     0.0898,  0.1510,  0.3060,  0.5820,  0.8221,  1.0388,  1.2261,  1.4289,
-     1.6054,  1.8103,  1.9941,  2.1844,  2.3742,  2.5711,  2.7632,  2.9474,
-     0.1326,  0.2316,  0.3761,  0.5177,  0.6782,  0.8761,  1.0952,  1.3175,
-     1.5078,  1.7034,  1.9051,  2.1245,  2.3424,  2.5484,  2.7444,  2.9389,
-     0.1740,  0.3293,  0.5174,  0.6824,  0.8394,  1.0372,  1.2046,  1.3723,
-     1.5656,  1.7444,  1.9442,  2.1386,  2.3139,  2.4960,  2.7071,  2.9297,
-     0.2304,  0.3775,  0.4865,  0.6182,  0.7842,  0.9208,  1.1151,  1.2843,
-     1.4641,  1.6988,  1.9209,  2.1260,  2.3099,  2.5229,  2.7414,  2.9276,
-     0.0094,  0.0261, -0.0037,  0.0041, -0.0092, -0.0044, -0.0232, -0.0073,
-    -0.0047, -0.0021,  0.0250, -0.0580, -0.0140, -0.0342, -0.0586,  0.0020,
-     0.0449,  0.0155, -0.0523, -0.0279,  0.0299, -0.0183, -0.0736, -0.0639,
-    -0.0017,  0.0336,  0.0209,  0.0046,  0.0077, -0.0148, -0.0114, -0.0120,
-     0.0115, -0.0050,  0.0445,  0.0048,  0.0188, -0.0137, -0.0080,  0.0239,
-    -0.0184, -0.0524, -0.0195, -0.0126,  0.0284,  0.0632,  0.0141, -0.0093,
-    -0.0096,  0.0196,  0.0230,  0.0379,  0.0308,  0.0237, -0.0224, -0.0600,
-    -0.0755, -0.1074, -0.0988, -0.0606, -0.1038, -0.1552, -0.1480, -0.0672,
-     0.0504,  0.0676,  0.0336, -0.0042,  0.0729,  0.1013,  0.0868,  0.0846,
-     0.0954,  0.0515, -0.0066, -0.0851, -0.0485,  0.0294,  0.0395,  0.0087,
-     0.0078,  0.0446,  0.0881,  0.0672, -0.0384, -0.0025,  0.0415,  0.0353,
-     0.0080,  0.0052,  0.0190,  0.0182,  0.0069,  0.0168,  0.0374,  0.0037,
-    -0.0292, -0.0429,  0.0302,  0.0681, -0.0233, -0.0238, -0.0003, -0.0043,
-     0.0054, -0.0029, -0.0149,  0.0642,  0.0622,  0.0341, -0.0232, -0.0461,
-    -0.0082, -0.0469, -0.0618, -0.0326, -0.0452, -0.0649, -0.0597, -0.0398,
-    -0.0318, -0.0116,  0.0011,  0.0009, -0.0384, -0.0384, -0.0156, -0.0260,
-    -0.0007,  0.0473,  0.0111, -0.0358, -0.0484, -0.0204, -0.0029, -0.0090,
-    -0.0285, -0.0495, -0.0376,  0.0917,  0.1192,  0.1026,  0.0745,  0.0397,
-     0.0463,  0.0253,  0.0025,  0.0465,  0.0100,  0.0488,  0.0416,  0.0223,
-     0.0263,  0.0072, -0.0053,  0.0595,  0.0060, -0.0518, -0.0316, -0.0043,
-    -0.0133, -0.0233, -0.0075, -0.0251,  0.0277, -0.0067, -0.0136, -0.0004,
-     0.0235,  0.0112, -0.0182, -0.0324, -0.0210, -0.0035, -0.0395, -0.0384,
-     0.0005, -0.0150, -0.0356,  0.0127, -0.0033, -0.0034,  0.0205,  0.0747,
-     0.1138,  0.1015,  0.0995, -0.0161, -0.0045,  0.0129,  0.0472,  0.0575,
-     0.0222,  0.0091,  0.0037, -0.0471,  0.0371,  0.0132,  0.0208,  0.0247,
-     0.0117,  0.0164,  0.0225,  0.0124, -0.0023,  0.0088, -0.0046,  0.0047,
-    -0.0393,  0.0018,  0.0148,  0.0020,  0.0044,  0.0165,  0.0229, -0.0208,
-    -0.0477, -0.0310, -0.0164, -0.0390, -0.0764, -0.0525, -0.0094,  0.0075,
-    -0.0102, -0.0045, -0.0504, -0.0709,  0.0822,  0.0710,  0.0426,  0.0014,
-    -0.0371, -0.0400, -0.0157, -0.0155, -0.0173, -0.0138, -0.0015,  0.0134,
-    -0.0418, -0.0682, -0.0256,  0.0050,  0.0360,  0.0354,  0.0074, -0.0396,
-    -0.0235,  0.0284,  0.0494,  0.0153,  0.0448,  0.0025, -0.0061,  0.0252,
-     0.1000,  0.2260,  0.2158,  0.2116,  0.2198,  0.2055,  0.2110,  0.1873,
-     0.1907,  0.2071,  0.2164,  0.2009,  0.2059,  0.2124,  0.2141,  0.2093,
-     0.0875,  0.0981,  0.1177,  0.1071,  0.1033,  0.1248,  0.1048,  0.1238,
-     0.1166,  0.1008,  0.1062,  0.0992,  0.0994,  0.1067,  0.0999,  0.1187,
-     0.0750,  0.0794,  0.0828,  0.0854,  0.0859,  0.0801,  0.0891,  0.0933,
-     0.0969,  0.0920,  0.0915,  0.0862,  0.0868,  0.0891,  0.0842,  0.0824,
-     0.0625,  0.0930,  0.0815,  0.0853,  0.0898,  0.0828,  0.0822,  0.0910,
-     0.0873,  0.0906,  0.0856,  0.0840,  0.0774,  0.0785,  0.0684,  0.0711,
-     0.3319,  0.4219,  0.4588,  0.4090,  0.4092,  0.4014,  0.3548,  0.3353,
-     0.3708,  0.3352,  0.3720,  0.3538,  0.4084,  0.4289,  0.4060,  0.4210,
-     0.0588,  0.0209, -0.0082, -0.0115, -0.0343, -0.0621, -0.0541, -0.0346,
-    -0.0346, -0.0366, -0.0220, -0.0265, -0.0102,  0.0374,  0.0306,  0.0404,
-     0.0306,  0.0090, -0.0054,  0.0333,  0.0047,  0.0238,  0.0141,  0.0165,
-     0.0306,  0.0420,  0.0159,  0.0124,  0.0414,  0.0158, -0.0237,  0.0141,
-     0.0765,  0.0057, -0.0260, -0.0426, -0.0395, -0.0126, -0.0579, -0.0417,
-    -0.0429, -0.0615, -0.0893, -0.0618, -0.0384, -0.0134, -0.0232, -0.0238,
-};
-
 static const float lsp22[] = {
      0.0664,  0.1875,  0.4300,  0.6730,  0.8793,  1.0640,  1.2563,  1.4433,
      1.6394,  1.8176,  2.0029,  2.1921,  2.3796,  2.5671,  2.7595,  2.9536,
diff --git a/libavcodec/mimic.c b/libavcodec/mimic.c
index 24724fa..73f2a13 100644
--- a/libavcodec/mimic.c
+++ b/libavcodec/mimic.c
@@ -35,7 +35,7 @@
 
 #define MIMIC_HEADER_SIZE   20
 
-typedef struct {
+typedef struct MimicContext {
     AVCodecContext *avctx;
 
     int             num_vblocks[3];
diff --git a/libavcodec/mips/Makefile b/libavcodec/mips/Makefile
index 6537b43..8e2459f 100644
--- a/libavcodec/mips/Makefile
+++ b/libavcodec/mips/Makefile
@@ -10,7 +10,7 @@
 MIPSFPU-OBJS-$(CONFIG_MPEGAUDIODSP)       += mips/mpegaudiodsp_mips_float.o
 MIPSDSPR1-OBJS-$(CONFIG_MPEGAUDIODSP)     += mips/mpegaudiodsp_mips_fixed.o
 MIPSFPU-OBJS-$(CONFIG_FFT)                += mips/fft_mips.o
-MIPSFPU-OBJS                              += mips/fmtconvert_mips.o
+MIPSFPU-OBJS-$(CONFIG_FMTCONVERT)         += mips/fmtconvert_mips.o
 OBJS-$(CONFIG_AC3DSP)                     += mips/ac3dsp_mips.o
 OBJS-$(CONFIG_AAC_DECODER)                += mips/aacdec_mips.o            \
                                              mips/aacsbr_mips.o            \
diff --git a/libavcodec/mips/aaccoder_mips.c b/libavcodec/mips/aaccoder_mips.c
index 8595913..ea0bf31 100644
--- a/libavcodec/mips/aaccoder_mips.c
+++ b/libavcodec/mips/aaccoder_mips.c
@@ -221,6 +221,7 @@
     for (i = 0; i < size; i += 4) {
         int curidx;
         int *in_int = (int *)&in[i];
+        int t0, t1, t2, t3, t4, t5, t6, t7;
 
         qc1 = scaled[i  ] * Q34 + 0.4054f;
         qc2 = scaled[i+1] * Q34 + 0.4054f;
@@ -235,31 +236,31 @@
             "slt    %[qc2], $zero,  %[qc2]  \n\t"
             "slt    %[qc3], $zero,  %[qc3]  \n\t"
             "slt    %[qc4], $zero,  %[qc4]  \n\t"
-            "lw     $t0,    0(%[in_int])    \n\t"
-            "lw     $t1,    4(%[in_int])    \n\t"
-            "lw     $t2,    8(%[in_int])    \n\t"
-            "lw     $t3,    12(%[in_int])   \n\t"
-            "srl    $t0,    $t0,    31      \n\t"
-            "srl    $t1,    $t1,    31      \n\t"
-            "srl    $t2,    $t2,    31      \n\t"
-            "srl    $t3,    $t3,    31      \n\t"
-            "subu   $t4,    $zero,  %[qc1]  \n\t"
-            "subu   $t5,    $zero,  %[qc2]  \n\t"
-            "subu   $t6,    $zero,  %[qc3]  \n\t"
-            "subu   $t7,    $zero,  %[qc4]  \n\t"
-            "movn   %[qc1], $t4,    $t0     \n\t"
-            "movn   %[qc2], $t5,    $t1     \n\t"
-            "movn   %[qc3], $t6,    $t2     \n\t"
-            "movn   %[qc4], $t7,    $t3     \n\t"
+            "lw     %[t0],  0(%[in_int])    \n\t"
+            "lw     %[t1],  4(%[in_int])    \n\t"
+            "lw     %[t2],  8(%[in_int])    \n\t"
+            "lw     %[t3],  12(%[in_int])   \n\t"
+            "srl    %[t0],  %[t0],  31      \n\t"
+            "srl    %[t1],  %[t1],  31      \n\t"
+            "srl    %[t2],  %[t2],  31      \n\t"
+            "srl    %[t3],  %[t3],  31      \n\t"
+            "subu   %[t4],  $zero,  %[qc1]  \n\t"
+            "subu   %[t5],  $zero,  %[qc2]  \n\t"
+            "subu   %[t6],  $zero,  %[qc3]  \n\t"
+            "subu   %[t7],  $zero,  %[qc4]  \n\t"
+            "movn   %[qc1], %[t4],  %[t0]   \n\t"
+            "movn   %[qc2], %[t5],  %[t1]   \n\t"
+            "movn   %[qc3], %[t6],  %[t2]   \n\t"
+            "movn   %[qc4], %[t7],  %[t3]   \n\t"
 
             ".set pop                       \n\t"
 
             : [qc1]"+r"(qc1), [qc2]"+r"(qc2),
-              [qc3]"+r"(qc3), [qc4]"+r"(qc4)
+              [qc3]"+r"(qc3), [qc4]"+r"(qc4),
+              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),
+              [t4]"=&r"(t4), [t5]"=&r"(t5), [t6]"=&r"(t6), [t7]"=&r"(t7)
             : [in_int]"r"(in_int)
-            : "t0", "t1", "t2", "t3",
-              "t4", "t5", "t6", "t7",
-              "memory"
+            : "memory"
         );
 
         curidx = qc1;
@@ -295,6 +296,7 @@
         int *in_int = (int *)&in[i];
         uint8_t v_bits;
         unsigned int v_codes;
+        int t0, t1, t2, t3, t4;
 
         qc1 = scaled[i  ] * Q34 + 0.4054f;
         qc2 = scaled[i+1] * Q34 + 0.4054f;
@@ -305,50 +307,51 @@
             ".set push                              \n\t"
             ".set noreorder                         \n\t"
 
-            "ori    $t4,        $zero,      2       \n\t"
+            "ori    %[t4],      $zero,      2       \n\t"
             "ori    %[sign],    $zero,      0       \n\t"
-            "slt    $t0,        $t4,        %[qc1]  \n\t"
-            "slt    $t1,        $t4,        %[qc2]  \n\t"
-            "slt    $t2,        $t4,        %[qc3]  \n\t"
-            "slt    $t3,        $t4,        %[qc4]  \n\t"
-            "movn   %[qc1],     $t4,        $t0     \n\t"
-            "movn   %[qc2],     $t4,        $t1     \n\t"
-            "movn   %[qc3],     $t4,        $t2     \n\t"
-            "movn   %[qc4],     $t4,        $t3     \n\t"
-            "lw     $t0,        0(%[in_int])        \n\t"
-            "lw     $t1,        4(%[in_int])        \n\t"
-            "lw     $t2,        8(%[in_int])        \n\t"
-            "lw     $t3,        12(%[in_int])       \n\t"
-            "slt    $t0,        $t0,        $zero   \n\t"
-            "movn   %[sign],    $t0,        %[qc1]  \n\t"
-            "slt    $t1,        $t1,        $zero   \n\t"
-            "slt    $t2,        $t2,        $zero   \n\t"
-            "slt    $t3,        $t3,        $zero   \n\t"
-            "sll    $t0,        %[sign],    1       \n\t"
-            "or     $t0,        $t0,        $t1     \n\t"
-            "movn   %[sign],    $t0,        %[qc2]  \n\t"
-            "slt    $t4,        $zero,      %[qc1]  \n\t"
-            "slt    $t1,        $zero,      %[qc2]  \n\t"
+            "slt    %[t0],      %[t4],      %[qc1]  \n\t"
+            "slt    %[t1],      %[t4],      %[qc2]  \n\t"
+            "slt    %[t2],      %[t4],      %[qc3]  \n\t"
+            "slt    %[t3],      %[t4],      %[qc4]  \n\t"
+            "movn   %[qc1],     %[t4],      %[t0]   \n\t"
+            "movn   %[qc2],     %[t4],      %[t1]   \n\t"
+            "movn   %[qc3],     %[t4],      %[t2]   \n\t"
+            "movn   %[qc4],     %[t4],      %[t3]   \n\t"
+            "lw     %[t0],      0(%[in_int])        \n\t"
+            "lw     %[t1],      4(%[in_int])        \n\t"
+            "lw     %[t2],      8(%[in_int])        \n\t"
+            "lw     %[t3],      12(%[in_int])       \n\t"
+            "slt    %[t0],      %[t0],      $zero   \n\t"
+            "movn   %[sign],    %[t0],      %[qc1]  \n\t"
+            "slt    %[t1],      %[t1],      $zero   \n\t"
+            "slt    %[t2],      %[t2],      $zero   \n\t"
+            "slt    %[t3],      %[t3],      $zero   \n\t"
+            "sll    %[t0],      %[sign],    1       \n\t"
+            "or     %[t0],      %[t0],      %[t1]   \n\t"
+            "movn   %[sign],    %[t0],      %[qc2]  \n\t"
+            "slt    %[t4],      $zero,      %[qc1]  \n\t"
+            "slt    %[t1],      $zero,      %[qc2]  \n\t"
             "slt    %[count],   $zero,      %[qc3]  \n\t"
-            "sll    $t0,        %[sign],    1       \n\t"
-            "or     $t0,        $t0,        $t2     \n\t"
-            "movn   %[sign],    $t0,        %[qc3]  \n\t"
-            "slt    $t2,        $zero,      %[qc4]  \n\t"
-            "addu   %[count],   %[count],   $t4     \n\t"
-            "addu   %[count],   %[count],   $t1     \n\t"
-            "sll    $t0,        %[sign],    1       \n\t"
-            "or     $t0,        $t0,        $t3     \n\t"
-            "movn   %[sign],    $t0,        %[qc4]  \n\t"
-            "addu   %[count],   %[count],   $t2     \n\t"
+            "sll    %[t0],      %[sign],    1       \n\t"
+            "or     %[t0],      %[t0],      %[t2]   \n\t"
+            "movn   %[sign],    %[t0],      %[qc3]  \n\t"
+            "slt    %[t2],      $zero,      %[qc4]  \n\t"
+            "addu   %[count],   %[count],   %[t4]   \n\t"
+            "addu   %[count],   %[count],   %[t1]   \n\t"
+            "sll    %[t0],      %[sign],    1       \n\t"
+            "or     %[t0],      %[t0],      %[t3]   \n\t"
+            "movn   %[sign],    %[t0],      %[qc4]  \n\t"
+            "addu   %[count],   %[count],   %[t2]   \n\t"
 
             ".set pop                               \n\t"
 
             : [qc1]"+r"(qc1), [qc2]"+r"(qc2),
               [qc3]"+r"(qc3), [qc4]"+r"(qc4),
-              [sign]"=&r"(sign), [count]"=&r"(count)
+              [sign]"=&r"(sign), [count]"=&r"(count),
+              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),
+              [t4]"=&r"(t4)
             : [in_int]"r"(in_int)
-            : "t0", "t1", "t2", "t3", "t4",
-              "memory"
+            : "memory"
         );
 
         curidx = qc1;
@@ -385,6 +388,7 @@
         int *in_int = (int *)&in[i];
         uint8_t v_bits;
         unsigned int v_codes;
+        int t0, t1, t2, t3, t4, t5, t6, t7;
 
         qc1 = scaled[i  ] * Q34 + 0.4054f;
         qc2 = scaled[i+1] * Q34 + 0.4054f;
@@ -395,40 +399,40 @@
             ".set push                      \n\t"
             ".set noreorder                 \n\t"
 
-            "ori    $t4,    $zero,  4       \n\t"
-            "slt    $t0,    $t4,    %[qc1]  \n\t"
-            "slt    $t1,    $t4,    %[qc2]  \n\t"
-            "slt    $t2,    $t4,    %[qc3]  \n\t"
-            "slt    $t3,    $t4,    %[qc4]  \n\t"
-            "movn   %[qc1], $t4,    $t0     \n\t"
-            "movn   %[qc2], $t4,    $t1     \n\t"
-            "movn   %[qc3], $t4,    $t2     \n\t"
-            "movn   %[qc4], $t4,    $t3     \n\t"
-            "lw     $t0,    0(%[in_int])    \n\t"
-            "lw     $t1,    4(%[in_int])    \n\t"
-            "lw     $t2,    8(%[in_int])    \n\t"
-            "lw     $t3,    12(%[in_int])   \n\t"
-            "srl    $t0,    $t0,    31      \n\t"
-            "srl    $t1,    $t1,    31      \n\t"
-            "srl    $t2,    $t2,    31      \n\t"
-            "srl    $t3,    $t3,    31      \n\t"
-            "subu   $t4,    $zero,  %[qc1]  \n\t"
-            "subu   $t5,    $zero,  %[qc2]  \n\t"
-            "subu   $t6,    $zero,  %[qc3]  \n\t"
-            "subu   $t7,    $zero,  %[qc4]  \n\t"
-            "movn   %[qc1], $t4,    $t0     \n\t"
-            "movn   %[qc2], $t5,    $t1     \n\t"
-            "movn   %[qc3], $t6,    $t2     \n\t"
-            "movn   %[qc4], $t7,    $t3     \n\t"
+            "ori    %[t4],  $zero,  4       \n\t"
+            "slt    %[t0],  %[t4],  %[qc1]  \n\t"
+            "slt    %[t1],  %[t4],  %[qc2]  \n\t"
+            "slt    %[t2],  %[t4],  %[qc3]  \n\t"
+            "slt    %[t3],  %[t4],  %[qc4]  \n\t"
+            "movn   %[qc1], %[t4],  %[t0]   \n\t"
+            "movn   %[qc2], %[t4],  %[t1]   \n\t"
+            "movn   %[qc3], %[t4],  %[t2]   \n\t"
+            "movn   %[qc4], %[t4],  %[t3]   \n\t"
+            "lw     %[t0],  0(%[in_int])    \n\t"
+            "lw     %[t1],  4(%[in_int])    \n\t"
+            "lw     %[t2],  8(%[in_int])    \n\t"
+            "lw     %[t3],  12(%[in_int])   \n\t"
+            "srl    %[t0],  %[t0],  31      \n\t"
+            "srl    %[t1],  %[t1],  31      \n\t"
+            "srl    %[t2],  %[t2],  31      \n\t"
+            "srl    %[t3],  %[t3],  31      \n\t"
+            "subu   %[t4],  $zero,  %[qc1]  \n\t"
+            "subu   %[t5],  $zero,  %[qc2]  \n\t"
+            "subu   %[t6],  $zero,  %[qc3]  \n\t"
+            "subu   %[t7],  $zero,  %[qc4]  \n\t"
+            "movn   %[qc1], %[t4],  %[t0]   \n\t"
+            "movn   %[qc2], %[t5],  %[t1]   \n\t"
+            "movn   %[qc3], %[t6],  %[t2]   \n\t"
+            "movn   %[qc4], %[t7],  %[t3]   \n\t"
 
             ".set pop                       \n\t"
 
             : [qc1]"+r"(qc1), [qc2]"+r"(qc2),
-              [qc3]"+r"(qc3), [qc4]"+r"(qc4)
+              [qc3]"+r"(qc3), [qc4]"+r"(qc4),
+              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),
+              [t4]"=&r"(t4), [t5]"=&r"(t5), [t6]"=&r"(t6), [t7]"=&r"(t7)
             : [in_int]"r"(in_int)
-            : "t0", "t1", "t2", "t3",
-              "t4", "t5", "t6", "t7",
-              "memory"
+            : "memory"
         );
 
         curidx = 9 * qc1;
@@ -463,6 +467,7 @@
         int *in_int = (int *)&in[i];
         uint8_t v_bits;
         unsigned int v_codes;
+        int t0, t1, t2, t3, t4;
 
         qc1 = scaled[i  ] * Q34 + 0.4054f;
         qc2 = scaled[i+1] * Q34 + 0.4054f;
@@ -473,46 +478,48 @@
             ".set push                              \n\t"
             ".set noreorder                         \n\t"
 
-            "ori    $t4,        $zero,      7       \n\t"
+            "ori    %[t4],      $zero,      7       \n\t"
             "ori    %[sign1],   $zero,      0       \n\t"
             "ori    %[sign2],   $zero,      0       \n\t"
-            "slt    $t0,        $t4,        %[qc1]  \n\t"
-            "slt    $t1,        $t4,        %[qc2]  \n\t"
-            "slt    $t2,        $t4,        %[qc3]  \n\t"
-            "slt    $t3,        $t4,        %[qc4]  \n\t"
-            "movn   %[qc1],     $t4,        $t0     \n\t"
-            "movn   %[qc2],     $t4,        $t1     \n\t"
-            "movn   %[qc3],     $t4,        $t2     \n\t"
-            "movn   %[qc4],     $t4,        $t3     \n\t"
-            "lw     $t0,        0(%[in_int])        \n\t"
-            "lw     $t1,        4(%[in_int])        \n\t"
-            "lw     $t2,        8(%[in_int])        \n\t"
-            "lw     $t3,        12(%[in_int])       \n\t"
-            "slt    $t0,        $t0,        $zero   \n\t"
-            "movn   %[sign1],   $t0,        %[qc1]  \n\t"
-            "slt    $t2,        $t2,        $zero   \n\t"
-            "movn   %[sign2],   $t2,        %[qc3]  \n\t"
-            "slt    $t1,        $t1,        $zero   \n\t"
-            "sll    $t0,        %[sign1],   1       \n\t"
-            "or     $t0,        $t0,        $t1     \n\t"
-            "movn   %[sign1],   $t0,        %[qc2]  \n\t"
-            "slt    $t3,        $t3,        $zero   \n\t"
-            "sll    $t0,        %[sign2],   1       \n\t"
-            "or     $t0,        $t0,        $t3     \n\t"
-            "movn   %[sign2],   $t0,        %[qc4]  \n\t"
+            "slt    %[t0],      %[t4],      %[qc1]  \n\t"
+            "slt    %[t1],      %[t4],      %[qc2]  \n\t"
+            "slt    %[t2],      %[t4],      %[qc3]  \n\t"
+            "slt    %[t3],      %[t4],      %[qc4]  \n\t"
+            "movn   %[qc1],     %[t4],      %[t0]   \n\t"
+            "movn   %[qc2],     %[t4],      %[t1]   \n\t"
+            "movn   %[qc3],     %[t4],      %[t2]   \n\t"
+            "movn   %[qc4],     %[t4],      %[t3]   \n\t"
+            "lw     %[t0],      0(%[in_int])        \n\t"
+            "lw     %[t1],      4(%[in_int])        \n\t"
+            "lw     %[t2],      8(%[in_int])        \n\t"
+            "lw     %[t3],      12(%[in_int])       \n\t"
+            "slt    %[t0],      %[t0],      $zero   \n\t"
+            "movn   %[sign1],   %[t0],      %[qc1]  \n\t"
+            "slt    %[t2],      %[t2],      $zero   \n\t"
+            "movn   %[sign2],   %[t2],      %[qc3]  \n\t"
+            "slt    %[t1],      %[t1],      $zero   \n\t"
+            "sll    %[t0],      %[sign1],   1       \n\t"
+            "or     %[t0],      %[t0],      %[t1]   \n\t"
+            "movn   %[sign1],   %[t0],      %[qc2]  \n\t"
+            "slt    %[t3],      %[t3],      $zero   \n\t"
+            "sll    %[t0],      %[sign2],   1       \n\t"
+            "or     %[t0],      %[t0],      %[t3]   \n\t"
+            "movn   %[sign2],   %[t0],      %[qc4]  \n\t"
             "slt    %[count1],  $zero,      %[qc1]  \n\t"
-            "slt    $t1,        $zero,      %[qc2]  \n\t"
+            "slt    %[t1],      $zero,      %[qc2]  \n\t"
             "slt    %[count2],  $zero,      %[qc3]  \n\t"
-            "slt    $t2,        $zero,      %[qc4]  \n\t"
-            "addu   %[count1],  %[count1],  $t1     \n\t"
-            "addu   %[count2],  %[count2],  $t2     \n\t"
+            "slt    %[t2],      $zero,      %[qc4]  \n\t"
+            "addu   %[count1],  %[count1],  %[t1]   \n\t"
+            "addu   %[count2],  %[count2],  %[t2]   \n\t"
 
             ".set pop                               \n\t"
 
             : [qc1]"+r"(qc1), [qc2]"+r"(qc2),
               [qc3]"+r"(qc3), [qc4]"+r"(qc4),
               [sign1]"=&r"(sign1), [count1]"=&r"(count1),
-              [sign2]"=&r"(sign2), [count2]"=&r"(count2)
+              [sign2]"=&r"(sign2), [count2]"=&r"(count2),
+              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),
+              [t4]"=&r"(t4)
             : [in_int]"r"(in_int)
             : "t0", "t1", "t2", "t3", "t4",
               "memory"
@@ -554,6 +561,7 @@
         int *in_int = (int *)&in[i];
         uint8_t v_bits;
         unsigned int v_codes;
+        int t0, t1, t2, t3, t4;
 
         qc1 = scaled[i  ] * Q34 + 0.4054f;
         qc2 = scaled[i+1] * Q34 + 0.4054f;
@@ -564,49 +572,50 @@
             ".set push                              \n\t"
             ".set noreorder                         \n\t"
 
-            "ori    $t4,        $zero,      12      \n\t"
+            "ori    %[t4],      $zero,      12      \n\t"
             "ori    %[sign1],   $zero,      0       \n\t"
             "ori    %[sign2],   $zero,      0       \n\t"
-            "slt    $t0,        $t4,        %[qc1]  \n\t"
-            "slt    $t1,        $t4,        %[qc2]  \n\t"
-            "slt    $t2,        $t4,        %[qc3]  \n\t"
-            "slt    $t3,        $t4,        %[qc4]  \n\t"
-            "movn   %[qc1],     $t4,        $t0     \n\t"
-            "movn   %[qc2],     $t4,        $t1     \n\t"
-            "movn   %[qc3],     $t4,        $t2     \n\t"
-            "movn   %[qc4],     $t4,        $t3     \n\t"
-            "lw     $t0,        0(%[in_int])        \n\t"
-            "lw     $t1,        4(%[in_int])        \n\t"
-            "lw     $t2,        8(%[in_int])        \n\t"
-            "lw     $t3,        12(%[in_int])       \n\t"
-            "slt    $t0,        $t0,        $zero   \n\t"
-            "movn   %[sign1],   $t0,        %[qc1]  \n\t"
-            "slt    $t2,        $t2,        $zero   \n\t"
-            "movn   %[sign2],   $t2,        %[qc3]  \n\t"
-            "slt    $t1,        $t1,        $zero   \n\t"
-            "sll    $t0,        %[sign1],   1       \n\t"
-            "or     $t0,        $t0,        $t1     \n\t"
-            "movn   %[sign1],   $t0,        %[qc2]  \n\t"
-            "slt    $t3,        $t3,        $zero   \n\t"
-            "sll    $t0,        %[sign2],   1       \n\t"
-            "or     $t0,        $t0,        $t3     \n\t"
-            "movn   %[sign2],   $t0,        %[qc4]  \n\t"
+            "slt    %[t0],      %[t4],      %[qc1]  \n\t"
+            "slt    %[t1],      %[t4],      %[qc2]  \n\t"
+            "slt    %[t2],      %[t4],      %[qc3]  \n\t"
+            "slt    %[t3],      %[t4],      %[qc4]  \n\t"
+            "movn   %[qc1],     %[t4],      %[t0]   \n\t"
+            "movn   %[qc2],     %[t4],      %[t1]   \n\t"
+            "movn   %[qc3],     %[t4],      %[t2]   \n\t"
+            "movn   %[qc4],     %[t4],      %[t3]   \n\t"
+            "lw     %[t0],      0(%[in_int])        \n\t"
+            "lw     %[t1],      4(%[in_int])        \n\t"
+            "lw     %[t2],      8(%[in_int])        \n\t"
+            "lw     %[t3],      12(%[in_int])       \n\t"
+            "slt    %[t0],      %[t0],      $zero   \n\t"
+            "movn   %[sign1],   %[t0],      %[qc1]  \n\t"
+            "slt    %[t2],      %[t2],      $zero   \n\t"
+            "movn   %[sign2],   %[t2],      %[qc3]  \n\t"
+            "slt    %[t1],      %[t1],      $zero   \n\t"
+            "sll    %[t0],      %[sign1],   1       \n\t"
+            "or     %[t0],      %[t0],      %[t1]   \n\t"
+            "movn   %[sign1],   %[t0],      %[qc2]  \n\t"
+            "slt    %[t3],      %[t3],      $zero   \n\t"
+            "sll    %[t0],      %[sign2],   1       \n\t"
+            "or     %[t0],      %[t0],      %[t3]   \n\t"
+            "movn   %[sign2],   %[t0],      %[qc4]  \n\t"
             "slt    %[count1],  $zero,      %[qc1]  \n\t"
-            "slt    $t1,        $zero,      %[qc2]  \n\t"
+            "slt    %[t1],      $zero,      %[qc2]  \n\t"
             "slt    %[count2],  $zero,      %[qc3]  \n\t"
-            "slt    $t2,        $zero,      %[qc4]  \n\t"
-            "addu   %[count1],  %[count1],  $t1     \n\t"
-            "addu   %[count2],  %[count2],  $t2     \n\t"
+            "slt    %[t2],      $zero,      %[qc4]  \n\t"
+            "addu   %[count1],  %[count1],  %[t1]   \n\t"
+            "addu   %[count2],  %[count2],  %[t2]   \n\t"
 
             ".set pop                               \n\t"
 
             : [qc1]"+r"(qc1), [qc2]"+r"(qc2),
               [qc3]"+r"(qc3), [qc4]"+r"(qc4),
               [sign1]"=&r"(sign1), [count1]"=&r"(count1),
-              [sign2]"=&r"(sign2), [count2]"=&r"(count2)
+              [sign2]"=&r"(sign2), [count2]"=&r"(count2),
+              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),
+              [t4]"=&r"(t4)
             : [in_int]"r"(in_int)
-            : "t0", "t1", "t2", "t3", "t4",
-              "memory"
+            : "memory"
         );
 
         curidx  = 13 * qc1;
@@ -648,6 +657,7 @@
             int *in_int = (int *)&in[i];
             uint8_t v_bits;
             unsigned int v_codes;
+            int t0, t1, t2, t3, t4;
 
             qc1 = scaled[i  ] * Q34 + 0.4054f;
             qc2 = scaled[i+1] * Q34 + 0.4054f;
@@ -658,49 +668,50 @@
                 ".set push                                  \n\t"
                 ".set noreorder                             \n\t"
 
-                "ori        $t4,        $zero,      16      \n\t"
+                "ori        %[t4],      $zero,      16      \n\t"
                 "ori        %[sign1],   $zero,      0       \n\t"
                 "ori        %[sign2],   $zero,      0       \n\t"
-                "slt        $t0,        $t4,        %[qc1]  \n\t"
-                "slt        $t1,        $t4,        %[qc2]  \n\t"
-                "slt        $t2,        $t4,        %[qc3]  \n\t"
-                "slt        $t3,        $t4,        %[qc4]  \n\t"
-                "movn       %[qc1],     $t4,        $t0     \n\t"
-                "movn       %[qc2],     $t4,        $t1     \n\t"
-                "movn       %[qc3],     $t4,        $t2     \n\t"
-                "movn       %[qc4],     $t4,        $t3     \n\t"
-                "lw         $t0,        0(%[in_int])        \n\t"
-                "lw         $t1,        4(%[in_int])        \n\t"
-                "lw         $t2,        8(%[in_int])        \n\t"
-                "lw         $t3,        12(%[in_int])       \n\t"
-                "slt        $t0,        $t0,        $zero   \n\t"
-                "movn       %[sign1],   $t0,        %[qc1]  \n\t"
-                "slt        $t2,        $t2,        $zero   \n\t"
-                "movn       %[sign2],   $t2,        %[qc3]  \n\t"
-                "slt        $t1,        $t1,        $zero   \n\t"
-                "sll        $t0,        %[sign1],   1       \n\t"
-                "or         $t0,        $t0,        $t1     \n\t"
-                "movn       %[sign1],   $t0,        %[qc2]  \n\t"
-                "slt        $t3,        $t3,        $zero   \n\t"
-                "sll        $t0,        %[sign2],   1       \n\t"
-                "or         $t0,        $t0,        $t3     \n\t"
-                "movn       %[sign2],   $t0,        %[qc4]  \n\t"
+                "slt        %[t0],      %[t4],      %[qc1]  \n\t"
+                "slt        %[t1],      %[t4],      %[qc2]  \n\t"
+                "slt        %[t2],      %[t4],      %[qc3]  \n\t"
+                "slt        %[t3],      %[t4],      %[qc4]  \n\t"
+                "movn       %[qc1],     %[t4],      %[t0]   \n\t"
+                "movn       %[qc2],     %[t4],      %[t1]   \n\t"
+                "movn       %[qc3],     %[t4],      %[t2]   \n\t"
+                "movn       %[qc4],     %[t4],      %[t3]   \n\t"
+                "lw         %[t0],      0(%[in_int])        \n\t"
+                "lw         %[t1],      4(%[in_int])        \n\t"
+                "lw         %[t2],      8(%[in_int])        \n\t"
+                "lw         %[t3],      12(%[in_int])       \n\t"
+                "slt        %[t0],      %[t0],      $zero   \n\t"
+                "movn       %[sign1],   %[t0],      %[qc1]  \n\t"
+                "slt        %[t2],      %[t2],      $zero   \n\t"
+                "movn       %[sign2],   %[t2],      %[qc3]  \n\t"
+                "slt        %[t1],      %[t1],      $zero   \n\t"
+                "sll        %[t0],      %[sign1],   1       \n\t"
+                "or         %[t0],      %[t0],      %[t1]   \n\t"
+                "movn       %[sign1],   %[t0],      %[qc2]  \n\t"
+                "slt        %[t3],      %[t3],      $zero   \n\t"
+                "sll        %[t0],      %[sign2],   1       \n\t"
+                "or         %[t0],      %[t0],      %[t3]   \n\t"
+                "movn       %[sign2],   %[t0],      %[qc4]  \n\t"
                 "slt        %[count1],  $zero,      %[qc1]  \n\t"
-                "slt        $t1,        $zero,      %[qc2]  \n\t"
+                "slt        %[t1],      $zero,      %[qc2]  \n\t"
                 "slt        %[count2],  $zero,      %[qc3]  \n\t"
-                "slt        $t2,        $zero,      %[qc4]  \n\t"
-                "addu       %[count1],  %[count1],  $t1     \n\t"
-                "addu       %[count2],  %[count2],  $t2     \n\t"
+                "slt        %[t2],      $zero,      %[qc4]  \n\t"
+                "addu       %[count1],  %[count1],  %[t1]   \n\t"
+                "addu       %[count2],  %[count2],  %[t2]   \n\t"
 
                 ".set pop                                   \n\t"
 
                 : [qc1]"+r"(qc1), [qc2]"+r"(qc2),
                   [qc3]"+r"(qc3), [qc4]"+r"(qc4),
                   [sign1]"=&r"(sign1), [count1]"=&r"(count1),
-                  [sign2]"=&r"(sign2), [count2]"=&r"(count2)
+                  [sign2]"=&r"(sign2), [count2]"=&r"(count2),
+                  [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),
+                  [t4]"=&r"(t4)
                 : [in_int]"r"(in_int)
-                : "t0", "t1", "t2", "t3", "t4",
-                  "memory"
+                : "memory"
             );
 
             curidx = 17 * qc1;
@@ -723,6 +734,7 @@
             uint8_t v_bits;
             unsigned int v_codes;
             int c1, c2, c3, c4;
+            int t0, t1, t2, t3, t4;
 
             qc1 = scaled[i  ] * Q34 + 0.4054f;
             qc2 = scaled[i+1] * Q34 + 0.4054f;
@@ -733,7 +745,7 @@
                 ".set push                                  \n\t"
                 ".set noreorder                             \n\t"
 
-                "ori        $t4,        $zero,      16      \n\t"
+                "ori        %[t4],      $zero,      16      \n\t"
                 "ori        %[sign1],   $zero,      0       \n\t"
                 "ori        %[sign2],   $zero,      0       \n\t"
                 "shll_s.w   %[c1],      %[qc1],     18      \n\t"
@@ -744,36 +756,36 @@
                 "srl        %[c2],      %[c2],      18      \n\t"
                 "srl        %[c3],      %[c3],      18      \n\t"
                 "srl        %[c4],      %[c4],      18      \n\t"
-                "slt        $t0,        $t4,        %[qc1]  \n\t"
-                "slt        $t1,        $t4,        %[qc2]  \n\t"
-                "slt        $t2,        $t4,        %[qc3]  \n\t"
-                "slt        $t3,        $t4,        %[qc4]  \n\t"
-                "movn       %[qc1],     $t4,        $t0     \n\t"
-                "movn       %[qc2],     $t4,        $t1     \n\t"
-                "movn       %[qc3],     $t4,        $t2     \n\t"
-                "movn       %[qc4],     $t4,        $t3     \n\t"
-                "lw         $t0,        0(%[in_int])        \n\t"
-                "lw         $t1,        4(%[in_int])        \n\t"
-                "lw         $t2,        8(%[in_int])        \n\t"
-                "lw         $t3,        12(%[in_int])       \n\t"
-                "slt        $t0,        $t0,        $zero   \n\t"
-                "movn       %[sign1],   $t0,        %[qc1]  \n\t"
-                "slt        $t2,        $t2,        $zero   \n\t"
-                "movn       %[sign2],   $t2,        %[qc3]  \n\t"
-                "slt        $t1,        $t1,        $zero   \n\t"
-                "sll        $t0,        %[sign1],   1       \n\t"
-                "or         $t0,        $t0,        $t1     \n\t"
-                "movn       %[sign1],   $t0,        %[qc2]  \n\t"
-                "slt        $t3,        $t3,        $zero   \n\t"
-                "sll        $t0,        %[sign2],   1       \n\t"
-                "or         $t0,        $t0,        $t3     \n\t"
-                "movn       %[sign2],   $t0,        %[qc4]  \n\t"
+                "slt        %[t0],      %[t4],      %[qc1]  \n\t"
+                "slt        %[t1],      %[t4],      %[qc2]  \n\t"
+                "slt        %[t2],      %[t4],      %[qc3]  \n\t"
+                "slt        %[t3],      %[t4],      %[qc4]  \n\t"
+                "movn       %[qc1],     %[t4],      %[t0]   \n\t"
+                "movn       %[qc2],     %[t4],      %[t1]   \n\t"
+                "movn       %[qc3],     %[t4],      %[t2]   \n\t"
+                "movn       %[qc4],     %[t4],      %[t3]   \n\t"
+                "lw         %[t0],      0(%[in_int])        \n\t"
+                "lw         %[t1],      4(%[in_int])        \n\t"
+                "lw         %[t2],      8(%[in_int])        \n\t"
+                "lw         %[t3],      12(%[in_int])       \n\t"
+                "slt        %[t0],      %[t0],      $zero   \n\t"
+                "movn       %[sign1],   %[t0],      %[qc1]  \n\t"
+                "slt        %[t2],      %[t2],      $zero   \n\t"
+                "movn       %[sign2],   %[t2],      %[qc3]  \n\t"
+                "slt        %[t1],      %[t1],      $zero   \n\t"
+                "sll        %[t0],      %[sign1],   1       \n\t"
+                "or         %[t0],      %[t0],      %[t1]   \n\t"
+                "movn       %[sign1],   %[t0],      %[qc2]  \n\t"
+                "slt        %[t3],      %[t3],      $zero   \n\t"
+                "sll        %[t0],      %[sign2],   1       \n\t"
+                "or         %[t0],      %[t0],      %[t3]   \n\t"
+                "movn       %[sign2],   %[t0],      %[qc4]  \n\t"
                 "slt        %[count1],  $zero,      %[qc1]  \n\t"
-                "slt        $t1,        $zero,      %[qc2]  \n\t"
+                "slt        %[t1],      $zero,      %[qc2]  \n\t"
                 "slt        %[count2],  $zero,      %[qc3]  \n\t"
-                "slt        $t2,        $zero,      %[qc4]  \n\t"
-                "addu       %[count1],  %[count1],  $t1     \n\t"
-                "addu       %[count2],  %[count2],  $t2     \n\t"
+                "slt        %[t2],      $zero,      %[qc4]  \n\t"
+                "addu       %[count1],  %[count1],  %[t1]   \n\t"
+                "addu       %[count2],  %[count2],  %[t2]   \n\t"
 
                 ".set pop                                   \n\t"
 
@@ -782,10 +794,11 @@
                   [sign1]"=&r"(sign1), [count1]"=&r"(count1),
                   [sign2]"=&r"(sign2), [count2]"=&r"(count2),
                   [c1]"=&r"(c1), [c2]"=&r"(c2),
-                  [c3]"=&r"(c3), [c4]"=&r"(c4)
+                  [c3]"=&r"(c3), [c4]"=&r"(c4),
+                  [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),
+                  [t4]"=&r"(t4)
                 : [in_int]"r"(in_int)
-                : "t0", "t1", "t2", "t3", "t4",
-                  "memory"
+                : "memory"
             );
 
             curidx = 17 * qc1;
@@ -889,6 +902,7 @@
     for (i = 0; i < size; i += 4) {
         int curidx;
         int *in_int = (int *)&in[i];
+        int t0, t1, t2, t3, t4, t5, t6, t7;
 
         qc1 = scaled[i  ] * Q34 + 0.4054f;
         qc2 = scaled[i+1] * Q34 + 0.4054f;
@@ -903,31 +917,31 @@
             "slt    %[qc2], $zero,  %[qc2]  \n\t"
             "slt    %[qc3], $zero,  %[qc3]  \n\t"
             "slt    %[qc4], $zero,  %[qc4]  \n\t"
-            "lw     $t0,    0(%[in_int])    \n\t"
-            "lw     $t1,    4(%[in_int])    \n\t"
-            "lw     $t2,    8(%[in_int])    \n\t"
-            "lw     $t3,    12(%[in_int])   \n\t"
-            "srl    $t0,    $t0,    31      \n\t"
-            "srl    $t1,    $t1,    31      \n\t"
-            "srl    $t2,    $t2,    31      \n\t"
-            "srl    $t3,    $t3,    31      \n\t"
-            "subu   $t4,    $zero,  %[qc1]  \n\t"
-            "subu   $t5,    $zero,  %[qc2]  \n\t"
-            "subu   $t6,    $zero,  %[qc3]  \n\t"
-            "subu   $t7,    $zero,  %[qc4]  \n\t"
-            "movn   %[qc1], $t4,    $t0     \n\t"
-            "movn   %[qc2], $t5,    $t1     \n\t"
-            "movn   %[qc3], $t6,    $t2     \n\t"
-            "movn   %[qc4], $t7,    $t3     \n\t"
+            "lw     %[t0],  0(%[in_int])    \n\t"
+            "lw     %[t1],  4(%[in_int])    \n\t"
+            "lw     %[t2],  8(%[in_int])    \n\t"
+            "lw     %[t3],  12(%[in_int])   \n\t"
+            "srl    %[t0],  %[t0],  31      \n\t"
+            "srl    %[t1],  %[t1],  31      \n\t"
+            "srl    %[t2],  %[t2],  31      \n\t"
+            "srl    %[t3],  %[t3],  31      \n\t"
+            "subu   %[t4],  $zero,  %[qc1]  \n\t"
+            "subu   %[t5],  $zero,  %[qc2]  \n\t"
+            "subu   %[t6],  $zero,  %[qc3]  \n\t"
+            "subu   %[t7],  $zero,  %[qc4]  \n\t"
+            "movn   %[qc1], %[t4],  %[t0]   \n\t"
+            "movn   %[qc2], %[t5],  %[t1]   \n\t"
+            "movn   %[qc3], %[t6],  %[t2]   \n\t"
+            "movn   %[qc4], %[t7],  %[t3]   \n\t"
 
             ".set pop                       \n\t"
 
             : [qc1]"+r"(qc1), [qc2]"+r"(qc2),
-              [qc3]"+r"(qc3), [qc4]"+r"(qc4)
+              [qc3]"+r"(qc3), [qc4]"+r"(qc4),
+              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),
+              [t4]"=&r"(t4), [t5]"=&r"(t5), [t6]"=&r"(t6), [t7]"=&r"(t7)
             : [in_int]"r"(in_int)
-            : "t0", "t1", "t2", "t3",
-              "t4", "t5", "t6", "t7",
-              "memory"
+            : "memory"
         );
 
         curidx = qc1;
@@ -959,6 +973,7 @@
 
     for (i = 0; i < size; i += 4) {
         int curidx;
+        int t0, t1, t2, t3, t4;
 
         qc1 = scaled[i  ] * Q34 + 0.4054f;
         qc2 = scaled[i+1] * Q34 + 0.4054f;
@@ -969,22 +984,22 @@
             ".set push                      \n\t"
             ".set noreorder                 \n\t"
 
-            "ori    $t4,    $zero,  2       \n\t"
-            "slt    $t0,    $t4,    %[qc1]  \n\t"
-            "slt    $t1,    $t4,    %[qc2]  \n\t"
-            "slt    $t2,    $t4,    %[qc3]  \n\t"
-            "slt    $t3,    $t4,    %[qc4]  \n\t"
-            "movn   %[qc1], $t4,    $t0     \n\t"
-            "movn   %[qc2], $t4,    $t1     \n\t"
-            "movn   %[qc3], $t4,    $t2     \n\t"
-            "movn   %[qc4], $t4,    $t3     \n\t"
+            "ori    %[t4],  $zero,  2       \n\t"
+            "slt    %[t0],  %[t4],  %[qc1]  \n\t"
+            "slt    %[t1],  %[t4],  %[qc2]  \n\t"
+            "slt    %[t2],  %[t4],  %[qc3]  \n\t"
+            "slt    %[t3],  %[t4],  %[qc4]  \n\t"
+            "movn   %[qc1], %[t4],  %[t0]   \n\t"
+            "movn   %[qc2], %[t4],  %[t1]   \n\t"
+            "movn   %[qc3], %[t4],  %[t2]   \n\t"
+            "movn   %[qc4], %[t4],  %[t3]   \n\t"
 
             ".set pop                       \n\t"
 
             : [qc1]"+r"(qc1), [qc2]"+r"(qc2),
-              [qc3]"+r"(qc3), [qc4]"+r"(qc4)
-            :
-            : "t0", "t1", "t2", "t3", "t4"
+              [qc3]"+r"(qc3), [qc4]"+r"(qc4),
+              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),
+              [t4]"=&r"(t4)
         );
 
         curidx = qc1;
@@ -1017,6 +1032,7 @@
     for (i = 0; i < size; i += 4) {
         int curidx, curidx2;
         int *in_int = (int *)&in[i];
+        int t0, t1, t2, t3, t4, t5, t6, t7;
 
         qc1 = scaled[i  ] * Q34 + 0.4054f;
         qc2 = scaled[i+1] * Q34 + 0.4054f;
@@ -1027,40 +1043,40 @@
             ".set push                      \n\t"
             ".set noreorder                 \n\t"
 
-            "ori    $t4,    $zero,  4       \n\t"
-            "slt    $t0,    $t4,    %[qc1]  \n\t"
-            "slt    $t1,    $t4,    %[qc2]  \n\t"
-            "slt    $t2,    $t4,    %[qc3]  \n\t"
-            "slt    $t3,    $t4,    %[qc4]  \n\t"
-            "movn   %[qc1], $t4,    $t0     \n\t"
-            "movn   %[qc2], $t4,    $t1     \n\t"
-            "movn   %[qc3], $t4,    $t2     \n\t"
-            "movn   %[qc4], $t4,    $t3     \n\t"
-            "lw     $t0,    0(%[in_int])    \n\t"
-            "lw     $t1,    4(%[in_int])    \n\t"
-            "lw     $t2,    8(%[in_int])    \n\t"
-            "lw     $t3,    12(%[in_int])   \n\t"
-            "srl    $t0,    $t0,    31      \n\t"
-            "srl    $t1,    $t1,    31      \n\t"
-            "srl    $t2,    $t2,    31      \n\t"
-            "srl    $t3,    $t3,    31      \n\t"
-            "subu   $t4,    $zero,  %[qc1]  \n\t"
-            "subu   $t5,    $zero,  %[qc2]  \n\t"
-            "subu   $t6,    $zero,  %[qc3]  \n\t"
-            "subu   $t7,    $zero,  %[qc4]  \n\t"
-            "movn   %[qc1], $t4,    $t0     \n\t"
-            "movn   %[qc2], $t5,    $t1     \n\t"
-            "movn   %[qc3], $t6,    $t2     \n\t"
-            "movn   %[qc4], $t7,    $t3     \n\t"
+            "ori    %[t4],  $zero,  4       \n\t"
+            "slt    %[t0],  %[t4],  %[qc1]  \n\t"
+            "slt    %[t1],  %[t4],  %[qc2]  \n\t"
+            "slt    %[t2],  %[t4],  %[qc3]  \n\t"
+            "slt    %[t3],  %[t4],  %[qc4]  \n\t"
+            "movn   %[qc1], %[t4],  %[t0]   \n\t"
+            "movn   %[qc2], %[t4],  %[t1]   \n\t"
+            "movn   %[qc3], %[t4],  %[t2]   \n\t"
+            "movn   %[qc4], %[t4],  %[t3]   \n\t"
+            "lw     %[t0],  0(%[in_int])    \n\t"
+            "lw     %[t1],  4(%[in_int])    \n\t"
+            "lw     %[t2],  8(%[in_int])    \n\t"
+            "lw     %[t3],  12(%[in_int])   \n\t"
+            "srl    %[t0],  %[t0],  31      \n\t"
+            "srl    %[t1],  %[t1],  31      \n\t"
+            "srl    %[t2],  %[t2],  31      \n\t"
+            "srl    %[t3],  %[t3],  31      \n\t"
+            "subu   %[t4],  $zero,  %[qc1]  \n\t"
+            "subu   %[t5],  $zero,  %[qc2]  \n\t"
+            "subu   %[t6],  $zero,  %[qc3]  \n\t"
+            "subu   %[t7],  $zero,  %[qc4]  \n\t"
+            "movn   %[qc1], %[t4],  %[t0]   \n\t"
+            "movn   %[qc2], %[t5],  %[t1]   \n\t"
+            "movn   %[qc3], %[t6],  %[t2]   \n\t"
+            "movn   %[qc4], %[t7],  %[t3]   \n\t"
 
             ".set pop                       \n\t"
 
             : [qc1]"+r"(qc1), [qc2]"+r"(qc2),
-              [qc3]"+r"(qc3), [qc4]"+r"(qc4)
+              [qc3]"+r"(qc3), [qc4]"+r"(qc4),
+              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),
+              [t4]"=&r"(t4), [t5]"=&r"(t5), [t6]"=&r"(t6), [t7]"=&r"(t7)
             : [in_int]"r"(in_int)
-            : "t0", "t1", "t2", "t3",
-              "t4", "t5", "t6", "t7",
-              "memory"
+            : "memory"
         );
 
         curidx  = 9 * qc1;
@@ -1089,6 +1105,7 @@
 
     for (i = 0; i < size; i += 4) {
         int curidx, curidx2;
+        int t0, t1, t2, t3, t4;
 
         qc1 = scaled[i  ] * Q34 + 0.4054f;
         qc2 = scaled[i+1] * Q34 + 0.4054f;
@@ -1099,22 +1116,22 @@
             ".set push                      \n\t"
             ".set noreorder                 \n\t"
 
-            "ori    $t4,    $zero,  7       \n\t"
-            "slt    $t0,    $t4,    %[qc1]  \n\t"
-            "slt    $t1,    $t4,    %[qc2]  \n\t"
-            "slt    $t2,    $t4,    %[qc3]  \n\t"
-            "slt    $t3,    $t4,    %[qc4]  \n\t"
-            "movn   %[qc1], $t4,    $t0     \n\t"
-            "movn   %[qc2], $t4,    $t1     \n\t"
-            "movn   %[qc3], $t4,    $t2     \n\t"
-            "movn   %[qc4], $t4,    $t3     \n\t"
+            "ori    %[t4],  $zero,  7       \n\t"
+            "slt    %[t0],  %[t4],  %[qc1]  \n\t"
+            "slt    %[t1],  %[t4],  %[qc2]  \n\t"
+            "slt    %[t2],  %[t4],  %[qc3]  \n\t"
+            "slt    %[t3],  %[t4],  %[qc4]  \n\t"
+            "movn   %[qc1], %[t4],  %[t0]   \n\t"
+            "movn   %[qc2], %[t4],  %[t1]   \n\t"
+            "movn   %[qc3], %[t4],  %[t2]   \n\t"
+            "movn   %[qc4], %[t4],  %[t3]   \n\t"
 
             ".set pop                       \n\t"
 
             : [qc1]"+r"(qc1), [qc2]"+r"(qc2),
-              [qc3]"+r"(qc3), [qc4]"+r"(qc4)
-            :
-            : "t0", "t1", "t2", "t3", "t4"
+              [qc3]"+r"(qc3), [qc4]"+r"(qc4),
+              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),
+              [t4]"=&r"(t4)
         );
 
         curidx  = 8 * qc1;
@@ -1146,6 +1163,7 @@
 
     for (i = 0; i < size; i += 4) {
         int curidx, curidx2;
+        int t0, t1, t2, t3, t4;
 
         qc1 = scaled[i  ] * Q34 + 0.4054f;
         qc2 = scaled[i+1] * Q34 + 0.4054f;
@@ -1156,22 +1174,22 @@
             ".set push                      \n\t"
             ".set noreorder                 \n\t"
 
-            "ori    $t4,    $zero,  12      \n\t"
-            "slt    $t0,    $t4,    %[qc1]  \n\t"
-            "slt    $t1,    $t4,    %[qc2]  \n\t"
-            "slt    $t2,    $t4,    %[qc3]  \n\t"
-            "slt    $t3,    $t4,    %[qc4]  \n\t"
-            "movn   %[qc1], $t4,    $t0     \n\t"
-            "movn   %[qc2], $t4,    $t1     \n\t"
-            "movn   %[qc3], $t4,    $t2     \n\t"
-            "movn   %[qc4], $t4,    $t3     \n\t"
+            "ori    %[t4],  $zero,  12      \n\t"
+            "slt    %[t0],  %[t4],  %[qc1]  \n\t"
+            "slt    %[t1],  %[t4],  %[qc2]  \n\t"
+            "slt    %[t2],  %[t4],  %[qc3]  \n\t"
+            "slt    %[t3],  %[t4],  %[qc4]  \n\t"
+            "movn   %[qc1], %[t4],  %[t0]   \n\t"
+            "movn   %[qc2], %[t4],  %[t1]   \n\t"
+            "movn   %[qc3], %[t4],  %[t2]   \n\t"
+            "movn   %[qc4], %[t4],  %[t3]   \n\t"
 
             ".set pop                       \n\t"
 
             : [qc1]"+r"(qc1), [qc2]"+r"(qc2),
-              [qc3]"+r"(qc3), [qc4]"+r"(qc4)
-            :
-            : "t0", "t1", "t2", "t3", "t4"
+              [qc3]"+r"(qc3), [qc4]"+r"(qc4),
+              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),
+              [t4]"=&r"(t4)
         );
 
         curidx  = 13 * qc1;
@@ -1205,6 +1223,7 @@
         int curidx, curidx2;
         int cond0, cond1, cond2, cond3;
         int c1, c2, c3, c4;
+        int t4, t5;
 
         qc1 = scaled[i  ] * Q34 + 0.4054f;
         qc2 = scaled[i+1] * Q34 + 0.4054f;
@@ -1215,8 +1234,8 @@
             ".set push                                  \n\t"
             ".set noreorder                             \n\t"
 
-            "ori        $t4,        $zero,  15          \n\t"
-            "ori        $t5,        $zero,  16          \n\t"
+            "ori        %[t4],      $zero,  15          \n\t"
+            "ori        %[t5],      $zero,  16          \n\t"
             "shll_s.w   %[c1],      %[qc1], 18          \n\t"
             "shll_s.w   %[c2],      %[qc2], 18          \n\t"
             "shll_s.w   %[c3],      %[qc3], 18          \n\t"
@@ -1225,23 +1244,23 @@
             "srl        %[c2],      %[c2],  18          \n\t"
             "srl        %[c3],      %[c3],  18          \n\t"
             "srl        %[c4],      %[c4],  18          \n\t"
-            "slt        %[cond0],   $t4,    %[qc1]      \n\t"
-            "slt        %[cond1],   $t4,    %[qc2]      \n\t"
-            "slt        %[cond2],   $t4,    %[qc3]      \n\t"
-            "slt        %[cond3],   $t4,    %[qc4]      \n\t"
-            "movn       %[qc1],     $t5,    %[cond0]    \n\t"
-            "movn       %[qc2],     $t5,    %[cond1]    \n\t"
-            "movn       %[qc3],     $t5,    %[cond2]    \n\t"
-            "movn       %[qc4],     $t5,    %[cond3]    \n\t"
-            "ori        $t5,        $zero,  31          \n\t"
+            "slt        %[cond0],   %[t4],  %[qc1]      \n\t"
+            "slt        %[cond1],   %[t4],  %[qc2]      \n\t"
+            "slt        %[cond2],   %[t4],  %[qc3]      \n\t"
+            "slt        %[cond3],   %[t4],  %[qc4]      \n\t"
+            "movn       %[qc1],     %[t5],  %[cond0]    \n\t"
+            "movn       %[qc2],     %[t5],  %[cond1]    \n\t"
+            "movn       %[qc3],     %[t5],  %[cond2]    \n\t"
+            "movn       %[qc4],     %[t5],  %[cond3]    \n\t"
+            "ori        %[t5],      $zero,  31          \n\t"
             "clz        %[c1],      %[c1]               \n\t"
             "clz        %[c2],      %[c2]               \n\t"
             "clz        %[c3],      %[c3]               \n\t"
             "clz        %[c4],      %[c4]               \n\t"
-            "subu       %[c1],      $t5,    %[c1]       \n\t"
-            "subu       %[c2],      $t5,    %[c2]       \n\t"
-            "subu       %[c3],      $t5,    %[c3]       \n\t"
-            "subu       %[c4],      $t5,    %[c4]       \n\t"
+            "subu       %[c1],      %[t5],  %[c1]       \n\t"
+            "subu       %[c2],      %[t5],  %[c2]       \n\t"
+            "subu       %[c3],      %[t5],  %[c3]       \n\t"
+            "subu       %[c4],      %[t5],  %[c4]       \n\t"
             "sll        %[c1],      %[c1],  1           \n\t"
             "sll        %[c2],      %[c2],  1           \n\t"
             "sll        %[c3],      %[c3],  1           \n\t"
@@ -1266,9 +1285,8 @@
               [cond0]"=&r"(cond0), [cond1]"=&r"(cond1),
               [cond2]"=&r"(cond2), [cond3]"=&r"(cond3),
               [c1]"=&r"(c1), [c2]"=&r"(c2),
-              [c3]"=&r"(c3), [c4]"=&r"(c4)
-            :
-            : "t4", "t5"
+              [c3]"=&r"(c3), [c4]"=&r"(c4),
+              [t4]"=&r"(t4), [t5]"=&r"(t5)
         );
 
         curidx = 17 * qc1;
@@ -1370,6 +1388,7 @@
         int   *in_int = (int   *)&in[i];
         float *in_pos = (float *)&in[i];
         float di0, di1, di2, di3;
+        int t0, t1, t2, t3, t4, t5, t6, t7;
 
         qc1 = scaled[i  ] * Q34 + 0.4054f;
         qc2 = scaled[i+1] * Q34 + 0.4054f;
@@ -1384,31 +1403,31 @@
             "slt        %[qc2], $zero,  %[qc2]          \n\t"
             "slt        %[qc3], $zero,  %[qc3]          \n\t"
             "slt        %[qc4], $zero,  %[qc4]          \n\t"
-            "lw         $t0,    0(%[in_int])            \n\t"
-            "lw         $t1,    4(%[in_int])            \n\t"
-            "lw         $t2,    8(%[in_int])            \n\t"
-            "lw         $t3,    12(%[in_int])           \n\t"
-            "srl        $t0,    $t0,    31              \n\t"
-            "srl        $t1,    $t1,    31              \n\t"
-            "srl        $t2,    $t2,    31              \n\t"
-            "srl        $t3,    $t3,    31              \n\t"
-            "subu       $t4,    $zero,  %[qc1]          \n\t"
-            "subu       $t5,    $zero,  %[qc2]          \n\t"
-            "subu       $t6,    $zero,  %[qc3]          \n\t"
-            "subu       $t7,    $zero,  %[qc4]          \n\t"
-            "movn       %[qc1], $t4,    $t0             \n\t"
-            "movn       %[qc2], $t5,    $t1             \n\t"
-            "movn       %[qc3], $t6,    $t2             \n\t"
-            "movn       %[qc4], $t7,    $t3             \n\t"
+            "lw         %[t0],  0(%[in_int])            \n\t"
+            "lw         %[t1],  4(%[in_int])            \n\t"
+            "lw         %[t2],  8(%[in_int])            \n\t"
+            "lw         %[t3],  12(%[in_int])           \n\t"
+            "srl        %[t0],  %[t0],  31              \n\t"
+            "srl        %[t1],  %[t1],  31              \n\t"
+            "srl        %[t2],  %[t2],  31              \n\t"
+            "srl        %[t3],  %[t3],  31              \n\t"
+            "subu       %[t4],  $zero,  %[qc1]          \n\t"
+            "subu       %[t5],  $zero,  %[qc2]          \n\t"
+            "subu       %[t6],  $zero,  %[qc3]          \n\t"
+            "subu       %[t7],  $zero,  %[qc4]          \n\t"
+            "movn       %[qc1], %[t4],  %[t0]           \n\t"
+            "movn       %[qc2], %[t5],  %[t1]           \n\t"
+            "movn       %[qc3], %[t6],  %[t2]           \n\t"
+            "movn       %[qc4], %[t7],  %[t3]           \n\t"
 
             ".set pop                                   \n\t"
 
             : [qc1]"+r"(qc1), [qc2]"+r"(qc2),
-              [qc3]"+r"(qc3), [qc4]"+r"(qc4)
+              [qc3]"+r"(qc3), [qc4]"+r"(qc4),
+              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),
+              [t4]"=&r"(t4), [t5]"=&r"(t5), [t6]"=&r"(t6), [t7]"=&r"(t7)
             : [in_int]"r"(in_int)
-            : "t0", "t1", "t2", "t3",
-              "t4", "t5", "t6", "t7",
-              "memory"
+            : "memory"
         );
 
         curidx = qc1;
@@ -1481,6 +1500,7 @@
         int curidx;
         float *in_pos = (float *)&in[i];
         float di0, di1, di2, di3;
+        int t0, t1, t2, t3, t4;
 
         qc1 = scaled[i  ] * Q34 + 0.4054f;
         qc2 = scaled[i+1] * Q34 + 0.4054f;
@@ -1491,22 +1511,22 @@
             ".set push                                  \n\t"
             ".set noreorder                             \n\t"
 
-            "ori        $t4,    $zero,  2               \n\t"
-            "slt        $t0,    $t4,    %[qc1]          \n\t"
-            "slt        $t1,    $t4,    %[qc2]          \n\t"
-            "slt        $t2,    $t4,    %[qc3]          \n\t"
-            "slt        $t3,    $t4,    %[qc4]          \n\t"
-            "movn       %[qc1], $t4,    $t0             \n\t"
-            "movn       %[qc2], $t4,    $t1             \n\t"
-            "movn       %[qc3], $t4,    $t2             \n\t"
-            "movn       %[qc4], $t4,    $t3             \n\t"
+            "ori        %[t4],  $zero,  2               \n\t"
+            "slt        %[t0],  %[t4],  %[qc1]          \n\t"
+            "slt        %[t1],  %[t4],  %[qc2]          \n\t"
+            "slt        %[t2],  %[t4],  %[qc3]          \n\t"
+            "slt        %[t3],  %[t4],  %[qc4]          \n\t"
+            "movn       %[qc1], %[t4],  %[t0]           \n\t"
+            "movn       %[qc2], %[t4],  %[t1]           \n\t"
+            "movn       %[qc3], %[t4],  %[t2]           \n\t"
+            "movn       %[qc4], %[t4],  %[t3]           \n\t"
 
             ".set pop                                   \n\t"
 
             : [qc1]"+r"(qc1), [qc2]"+r"(qc2),
-              [qc3]"+r"(qc3), [qc4]"+r"(qc4)
-            :
-            : "t0", "t1", "t2", "t3", "t4"
+              [qc3]"+r"(qc3), [qc4]"+r"(qc4),
+              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),
+              [t4]"=&r"(t4)
         );
 
         curidx = qc1;
@@ -1583,6 +1603,7 @@
         int   *in_int = (int   *)&in[i];
         float *in_pos = (float *)&in[i];
         float di0, di1, di2, di3;
+        int t0, t1, t2, t3, t4, t5, t6, t7;
 
         qc1 = scaled[i  ] * Q34 + 0.4054f;
         qc2 = scaled[i+1] * Q34 + 0.4054f;
@@ -1593,40 +1614,40 @@
             ".set push                                  \n\t"
             ".set noreorder                             \n\t"
 
-            "ori        $t4,    $zero,  4               \n\t"
-            "slt        $t0,    $t4,    %[qc1]          \n\t"
-            "slt        $t1,    $t4,    %[qc2]          \n\t"
-            "slt        $t2,    $t4,    %[qc3]          \n\t"
-            "slt        $t3,    $t4,    %[qc4]          \n\t"
-            "movn       %[qc1], $t4,    $t0             \n\t"
-            "movn       %[qc2], $t4,    $t1             \n\t"
-            "movn       %[qc3], $t4,    $t2             \n\t"
-            "movn       %[qc4], $t4,    $t3             \n\t"
-            "lw         $t0,    0(%[in_int])            \n\t"
-            "lw         $t1,    4(%[in_int])            \n\t"
-            "lw         $t2,    8(%[in_int])            \n\t"
-            "lw         $t3,    12(%[in_int])           \n\t"
-            "srl        $t0,    $t0,    31              \n\t"
-            "srl        $t1,    $t1,    31              \n\t"
-            "srl        $t2,    $t2,    31              \n\t"
-            "srl        $t3,    $t3,    31              \n\t"
-            "subu       $t4,    $zero,  %[qc1]          \n\t"
-            "subu       $t5,    $zero,  %[qc2]          \n\t"
-            "subu       $t6,    $zero,  %[qc3]          \n\t"
-            "subu       $t7,    $zero,  %[qc4]          \n\t"
-            "movn       %[qc1], $t4,    $t0             \n\t"
-            "movn       %[qc2], $t5,    $t1             \n\t"
-            "movn       %[qc3], $t6,    $t2             \n\t"
-            "movn       %[qc4], $t7,    $t3             \n\t"
+            "ori        %[t4],  $zero,  4               \n\t"
+            "slt        %[t0],  %[t4],  %[qc1]          \n\t"
+            "slt        %[t1],  %[t4],  %[qc2]          \n\t"
+            "slt        %[t2],  %[t4],  %[qc3]          \n\t"
+            "slt        %[t3],  %[t4],  %[qc4]          \n\t"
+            "movn       %[qc1], %[t4],  %[t0]           \n\t"
+            "movn       %[qc2], %[t4],  %[t1]           \n\t"
+            "movn       %[qc3], %[t4],  %[t2]           \n\t"
+            "movn       %[qc4], %[t4],  %[t3]           \n\t"
+            "lw         %[t0],  0(%[in_int])            \n\t"
+            "lw         %[t1],  4(%[in_int])            \n\t"
+            "lw         %[t2],  8(%[in_int])            \n\t"
+            "lw         %[t3],  12(%[in_int])           \n\t"
+            "srl        %[t0],  %[t0],  31              \n\t"
+            "srl        %[t1],  %[t1],  31              \n\t"
+            "srl        %[t2],  %[t2],  31              \n\t"
+            "srl        %[t3],  %[t3],  31              \n\t"
+            "subu       %[t4],  $zero,  %[qc1]          \n\t"
+            "subu       %[t5],  $zero,  %[qc2]          \n\t"
+            "subu       %[t6],  $zero,  %[qc3]          \n\t"
+            "subu       %[t7],  $zero,  %[qc4]          \n\t"
+            "movn       %[qc1], %[t4],  %[t0]           \n\t"
+            "movn       %[qc2], %[t5],  %[t1]           \n\t"
+            "movn       %[qc3], %[t6],  %[t2]           \n\t"
+            "movn       %[qc4], %[t7],  %[t3]           \n\t"
 
             ".set pop                                   \n\t"
 
             : [qc1]"+r"(qc1), [qc2]"+r"(qc2),
-              [qc3]"+r"(qc3), [qc4]"+r"(qc4)
+              [qc3]"+r"(qc3), [qc4]"+r"(qc4),
+              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),
+              [t4]"=&r"(t4), [t5]"=&r"(t5), [t6]"=&r"(t6), [t7]"=&r"(t7)
             : [in_int]"r"(in_int)
-            : "t0", "t1", "t2", "t3",
-              "t4", "t5", "t6", "t7",
-              "memory"
+            : "memory"
         );
 
         curidx = 9 * qc1;
@@ -1700,6 +1721,7 @@
         int   *in_int = (int   *)&in[i];
         float *in_pos = (float *)&in[i];
         float di0, di1, di2, di3;
+        int t0, t1, t2, t3, t4;
 
         qc1 = scaled[i  ] * Q34 + 0.4054f;
         qc2 = scaled[i+1] * Q34 + 0.4054f;
@@ -1710,49 +1732,50 @@
             ".set push                                          \n\t"
             ".set noreorder                                     \n\t"
 
-            "ori        $t4,        $zero,      7               \n\t"
+            "ori        %[t4],      $zero,      7               \n\t"
             "ori        %[sign1],   $zero,      0               \n\t"
             "ori        %[sign2],   $zero,      0               \n\t"
-            "slt        $t0,        $t4,        %[qc1]          \n\t"
-            "slt        $t1,        $t4,        %[qc2]          \n\t"
-            "slt        $t2,        $t4,        %[qc3]          \n\t"
-            "slt        $t3,        $t4,        %[qc4]          \n\t"
-            "movn       %[qc1],     $t4,        $t0             \n\t"
-            "movn       %[qc2],     $t4,        $t1             \n\t"
-            "movn       %[qc3],     $t4,        $t2             \n\t"
-            "movn       %[qc4],     $t4,        $t3             \n\t"
-            "lw         $t0,        0(%[in_int])                \n\t"
-            "lw         $t1,        4(%[in_int])                \n\t"
-            "lw         $t2,        8(%[in_int])                \n\t"
-            "lw         $t3,        12(%[in_int])               \n\t"
-            "slt        $t0,        $t0,        $zero           \n\t"
-            "movn       %[sign1],   $t0,        %[qc1]          \n\t"
-            "slt        $t2,        $t2,        $zero           \n\t"
-            "movn       %[sign2],   $t2,        %[qc3]          \n\t"
-            "slt        $t1,        $t1,        $zero           \n\t"
-            "sll        $t0,        %[sign1],   1               \n\t"
-            "or         $t0,        $t0,        $t1             \n\t"
-            "movn       %[sign1],   $t0,        %[qc2]          \n\t"
-            "slt        $t3,        $t3,        $zero           \n\t"
-            "sll        $t0,        %[sign2],   1               \n\t"
-            "or         $t0,        $t0,        $t3             \n\t"
-            "movn       %[sign2],   $t0,        %[qc4]          \n\t"
+            "slt        %[t0],      %[t4],      %[qc1]          \n\t"
+            "slt        %[t1],      %[t4],      %[qc2]          \n\t"
+            "slt        %[t2],      %[t4],      %[qc3]          \n\t"
+            "slt        %[t3],      %[t4],      %[qc4]          \n\t"
+            "movn       %[qc1],     %[t4],      %[t0]           \n\t"
+            "movn       %[qc2],     %[t4],      %[t1]           \n\t"
+            "movn       %[qc3],     %[t4],      %[t2]           \n\t"
+            "movn       %[qc4],     %[t4],      %[t3]           \n\t"
+            "lw         %[t0],      0(%[in_int])                \n\t"
+            "lw         %[t1],      4(%[in_int])                \n\t"
+            "lw         %[t2],      8(%[in_int])                \n\t"
+            "lw         %[t3],      12(%[in_int])               \n\t"
+            "slt        %[t0],      %[t0],      $zero           \n\t"
+            "movn       %[sign1],   %[t0],      %[qc1]          \n\t"
+            "slt        %[t2],      %[t2],      $zero           \n\t"
+            "movn       %[sign2],   %[t2],      %[qc3]          \n\t"
+            "slt        %[t1],      %[t1],      $zero           \n\t"
+            "sll        %[t0],      %[sign1],   1               \n\t"
+            "or         %[t0],      %[t0],      %[t1]           \n\t"
+            "movn       %[sign1],   %[t0],      %[qc2]          \n\t"
+            "slt        %[t3],      %[t3],      $zero           \n\t"
+            "sll        %[t0],      %[sign2],   1               \n\t"
+            "or         %[t0],      %[t0],      %[t3]           \n\t"
+            "movn       %[sign2],   %[t0],      %[qc4]          \n\t"
             "slt        %[count1],  $zero,      %[qc1]          \n\t"
-            "slt        $t1,        $zero,      %[qc2]          \n\t"
+            "slt        %[t1],      $zero,      %[qc2]          \n\t"
             "slt        %[count2],  $zero,      %[qc3]          \n\t"
-            "slt        $t2,        $zero,      %[qc4]          \n\t"
-            "addu       %[count1],  %[count1],  $t1             \n\t"
-            "addu       %[count2],  %[count2],  $t2             \n\t"
+            "slt        %[t2],      $zero,      %[qc4]          \n\t"
+            "addu       %[count1],  %[count1],  %[t1]           \n\t"
+            "addu       %[count2],  %[count2],  %[t2]           \n\t"
 
             ".set pop                                           \n\t"
 
             : [qc1]"+r"(qc1), [qc2]"+r"(qc2),
               [qc3]"+r"(qc3), [qc4]"+r"(qc4),
               [sign1]"=&r"(sign1), [count1]"=&r"(count1),
-              [sign2]"=&r"(sign2), [count2]"=&r"(count2)
+              [sign2]"=&r"(sign2), [count2]"=&r"(count2),
+              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),
+              [t4]"=&r"(t4)
             : [in_int]"r"(in_int)
-            : "t0", "t1", "t2", "t3", "t4",
-              "memory"
+            : "memory"
         );
 
         curidx = 8 * qc1;
@@ -1832,6 +1855,7 @@
         int   *in_int = (int   *)&in[i];
         float *in_pos = (float *)&in[i];
         float di0, di1, di2, di3;
+        int t0, t1, t2, t3, t4;
 
         qc1 = scaled[i  ] * Q34 + 0.4054f;
         qc2 = scaled[i+1] * Q34 + 0.4054f;
@@ -1842,49 +1866,50 @@
             ".set push                                          \n\t"
             ".set noreorder                                     \n\t"
 
-            "ori        $t4,        $zero,      12              \n\t"
+            "ori        %[t4],      $zero,      12              \n\t"
             "ori        %[sign1],   $zero,      0               \n\t"
             "ori        %[sign2],   $zero,      0               \n\t"
-            "slt        $t0,        $t4,        %[qc1]          \n\t"
-            "slt        $t1,        $t4,        %[qc2]          \n\t"
-            "slt        $t2,        $t4,        %[qc3]          \n\t"
-            "slt        $t3,        $t4,        %[qc4]          \n\t"
-            "movn       %[qc1],     $t4,        $t0             \n\t"
-            "movn       %[qc2],     $t4,        $t1             \n\t"
-            "movn       %[qc3],     $t4,        $t2             \n\t"
-            "movn       %[qc4],     $t4,        $t3             \n\t"
-            "lw         $t0,        0(%[in_int])                \n\t"
-            "lw         $t1,        4(%[in_int])                \n\t"
-            "lw         $t2,        8(%[in_int])                \n\t"
-            "lw         $t3,        12(%[in_int])               \n\t"
-            "slt        $t0,        $t0,        $zero           \n\t"
-            "movn       %[sign1],   $t0,        %[qc1]          \n\t"
-            "slt        $t2,        $t2,        $zero           \n\t"
-            "movn       %[sign2],   $t2,        %[qc3]          \n\t"
-            "slt        $t1,        $t1,        $zero           \n\t"
-            "sll        $t0,        %[sign1],   1               \n\t"
-            "or         $t0,        $t0,        $t1             \n\t"
-            "movn       %[sign1],   $t0,        %[qc2]          \n\t"
-            "slt        $t3,        $t3,        $zero           \n\t"
-            "sll        $t0,        %[sign2],   1               \n\t"
-            "or         $t0,        $t0,        $t3             \n\t"
-            "movn       %[sign2],   $t0,        %[qc4]          \n\t"
+            "slt        %[t0],      %[t4],      %[qc1]          \n\t"
+            "slt        %[t1],      %[t4],      %[qc2]          \n\t"
+            "slt        %[t2],      %[t4],      %[qc3]          \n\t"
+            "slt        %[t3],      %[t4],      %[qc4]          \n\t"
+            "movn       %[qc1],     %[t4],      %[t0]           \n\t"
+            "movn       %[qc2],     %[t4],      %[t1]           \n\t"
+            "movn       %[qc3],     %[t4],      %[t2]           \n\t"
+            "movn       %[qc4],     %[t4],      %[t3]           \n\t"
+            "lw         %[t0],      0(%[in_int])                \n\t"
+            "lw         %[t1],      4(%[in_int])                \n\t"
+            "lw         %[t2],      8(%[in_int])                \n\t"
+            "lw         %[t3],      12(%[in_int])               \n\t"
+            "slt        %[t0],      %[t0],      $zero           \n\t"
+            "movn       %[sign1],   %[t0],      %[qc1]          \n\t"
+            "slt        %[t2],      %[t2],      $zero           \n\t"
+            "movn       %[sign2],   %[t2],      %[qc3]          \n\t"
+            "slt        %[t1],      %[t1],      $zero           \n\t"
+            "sll        %[t0],      %[sign1],   1               \n\t"
+            "or         %[t0],      %[t0],      %[t1]           \n\t"
+            "movn       %[sign1],   %[t0],      %[qc2]          \n\t"
+            "slt        %[t3],      %[t3],      $zero           \n\t"
+            "sll        %[t0],      %[sign2],   1               \n\t"
+            "or         %[t0],      %[t0],      %[t3]           \n\t"
+            "movn       %[sign2],   %[t0],      %[qc4]          \n\t"
             "slt        %[count1],  $zero,      %[qc1]          \n\t"
-            "slt        $t1,        $zero,      %[qc2]          \n\t"
+            "slt        %[t1],      $zero,      %[qc2]          \n\t"
             "slt        %[count2],  $zero,      %[qc3]          \n\t"
-            "slt        $t2,        $zero,      %[qc4]          \n\t"
-            "addu       %[count1],  %[count1],  $t1             \n\t"
-            "addu       %[count2],  %[count2],  $t2             \n\t"
+            "slt        %[t2],      $zero,      %[qc4]          \n\t"
+            "addu       %[count1],  %[count1],  %[t1]           \n\t"
+            "addu       %[count2],  %[count2],  %[t2]           \n\t"
 
             ".set pop                                           \n\t"
 
             : [qc1]"+r"(qc1), [qc2]"+r"(qc2),
               [qc3]"+r"(qc3), [qc4]"+r"(qc4),
               [sign1]"=&r"(sign1), [count1]"=&r"(count1),
-              [sign2]"=&r"(sign2), [count2]"=&r"(count2)
+              [sign2]"=&r"(sign2), [count2]"=&r"(count2),
+              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),
+              [t4]"=&r"(t4)
             : [in_int]"r"(in_int)
-            : "t0", "t1", "t2", "t3", "t4",
-              "memory"
+            : "memory"
         );
 
         curidx = 13 * qc1;
@@ -1964,6 +1989,7 @@
         float di1, di2, di3, di4;
         int cond0, cond1, cond2, cond3;
         int c1, c2, c3, c4;
+        int t6, t7;
 
         qc1 = scaled[i  ] * Q34 + 0.4054f;
         qc2 = scaled[i+1] * Q34 + 0.4054f;
@@ -1974,8 +2000,8 @@
             ".set push                                  \n\t"
             ".set noreorder                             \n\t"
 
-            "ori        $t4,        $zero,  15          \n\t"
-            "ori        $t5,        $zero,  16          \n\t"
+            "ori        %[t6],      $zero,  15          \n\t"
+            "ori        %[t7],      $zero,  16          \n\t"
             "shll_s.w   %[c1],      %[qc1], 18          \n\t"
             "shll_s.w   %[c2],      %[qc2], 18          \n\t"
             "shll_s.w   %[c3],      %[qc3], 18          \n\t"
@@ -1984,14 +2010,14 @@
             "srl        %[c2],      %[c2],  18          \n\t"
             "srl        %[c3],      %[c3],  18          \n\t"
             "srl        %[c4],      %[c4],  18          \n\t"
-            "slt        %[cond0],   $t4,    %[qc1]      \n\t"
-            "slt        %[cond1],   $t4,    %[qc2]      \n\t"
-            "slt        %[cond2],   $t4,    %[qc3]      \n\t"
-            "slt        %[cond3],   $t4,    %[qc4]      \n\t"
-            "movn       %[qc1],     $t5,    %[cond0]    \n\t"
-            "movn       %[qc2],     $t5,    %[cond1]    \n\t"
-            "movn       %[qc3],     $t5,    %[cond2]    \n\t"
-            "movn       %[qc4],     $t5,    %[cond3]    \n\t"
+            "slt        %[cond0],   %[t6],  %[qc1]      \n\t"
+            "slt        %[cond1],   %[t6],  %[qc2]      \n\t"
+            "slt        %[cond2],   %[t6],  %[qc3]      \n\t"
+            "slt        %[cond3],   %[t6],  %[qc4]      \n\t"
+            "movn       %[qc1],     %[t7],  %[cond0]    \n\t"
+            "movn       %[qc2],     %[t7],  %[cond1]    \n\t"
+            "movn       %[qc3],     %[t7],  %[cond2]    \n\t"
+            "movn       %[qc4],     %[t7],  %[cond3]    \n\t"
 
             ".set pop                                   \n\t"
 
@@ -2000,9 +2026,8 @@
               [cond0]"=&r"(cond0), [cond1]"=&r"(cond1),
               [cond2]"=&r"(cond2), [cond3]"=&r"(cond3),
               [c1]"=&r"(c1), [c2]"=&r"(c2),
-              [c3]"=&r"(c3), [c4]"=&r"(c4)
-            :
-            : "t4", "t5"
+              [c3]"=&r"(c3), [c4]"=&r"(c4),
+              [t6]"=&r"(t6), [t7]"=&r"(t7)
         );
 
         curidx = 17 * qc1;
diff --git a/libavcodec/mips/aacdec_mips.c b/libavcodec/mips/aacdec_mips.c
index 5db10f9..253cdeb 100644
--- a/libavcodec/mips/aacdec_mips.c
+++ b/libavcodec/mips/aacdec_mips.c
@@ -56,8 +56,54 @@
 #include "aacdec_mips.h"
 #include "libavcodec/aactab.h"
 #include "libavcodec/sinewin.h"
+#include "libavutil/mips/asmdefs.h"
 
 #if HAVE_INLINE_ASM
+static av_always_inline void float_copy(float *dst, const float *src, int count)
+{
+    // Copy 'count' floats from src to dst
+    const float *loop_end = src + count;
+    int temp[8];
+
+    // count must be a multiple of 8
+    av_assert2(count % 8 == 0);
+
+    // loop unrolled 8 times
+    __asm__ volatile (
+        ".set push                               \n\t"
+        ".set noreorder                          \n\t"
+    "1:                                          \n\t"
+        "lw      %[temp0],    0(%[src])          \n\t"
+        "lw      %[temp1],    4(%[src])          \n\t"
+        "lw      %[temp2],    8(%[src])          \n\t"
+        "lw      %[temp3],    12(%[src])         \n\t"
+        "lw      %[temp4],    16(%[src])         \n\t"
+        "lw      %[temp5],    20(%[src])         \n\t"
+        "lw      %[temp6],    24(%[src])         \n\t"
+        "lw      %[temp7],    28(%[src])         \n\t"
+        PTR_ADDIU "%[src],    %[src],      32    \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"
+        "bne     %[src],      %[loop_end], 1b    \n\t"
+        PTR_ADDIU "%[dst],    %[dst],      32    \n\t"
+        ".set pop                                \n\t"
+
+        : [temp0]"=&r"(temp[0]), [temp1]"=&r"(temp[1]),
+          [temp2]"=&r"(temp[2]), [temp3]"=&r"(temp[3]),
+          [temp4]"=&r"(temp[4]), [temp5]"=&r"(temp[5]),
+          [temp6]"=&r"(temp[6]), [temp7]"=&r"(temp[7]),
+          [src]"+r"(src), [dst]"+r"(dst)
+        : [loop_end]"r"(loop_end)
+        : "memory"
+    );
+}
+
 static av_always_inline int lcg_random(unsigned previous_val)
 {
     union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
@@ -92,49 +138,7 @@
             (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
         ac->fdsp->vector_fmul_window(    out,               saved,            buf,         lwindow_prev, 512);
     } else {
-        {
-            float *buf1 = saved;
-            float *buf2 = out;
-            int temp0, temp1, temp2, temp3, temp4, temp5, temp6, temp7;
-            int loop_end;
-
-            /* loop unrolled 8 times */
-            __asm__ volatile (
-                ".set push                               \n\t"
-                ".set noreorder                          \n\t"
-                "addiu   %[loop_end], %[src],      1792  \n\t"
-            "1:                                          \n\t"
-                "lw      %[temp0],    0(%[src])          \n\t"
-                "lw      %[temp1],    4(%[src])          \n\t"
-                "lw      %[temp2],    8(%[src])          \n\t"
-                "lw      %[temp3],    12(%[src])         \n\t"
-                "lw      %[temp4],    16(%[src])         \n\t"
-                "lw      %[temp5],    20(%[src])         \n\t"
-                "lw      %[temp6],    24(%[src])         \n\t"
-                "lw      %[temp7],    28(%[src])         \n\t"
-                "addiu   %[src],      %[src],      32    \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"
-                "bne     %[src],      %[loop_end], 1b    \n\t"
-                " addiu  %[dst],      %[dst],      32    \n\t"
-                ".set pop                                \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),
-                  [loop_end]"=&r"(loop_end), [src]"+r"(buf1),
-                  [dst]"+r"(buf2)
-                :
-                : "memory"
-            );
-        }
+        float_copy(out, saved, 448);
 
         if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
             {
@@ -200,49 +204,7 @@
             }
         } else {
             ac->fdsp->vector_fmul_window(out + 448,         saved + 448,      buf,         swindow_prev, 64);
-            {
-                float *buf1 = buf + 64;
-                float *buf2 = out + 576;
-                int temp0, temp1, temp2, temp3, temp4, temp5, temp6, temp7;
-                int loop_end;
-
-                /* loop unrolled 8 times */
-                __asm__ volatile (
-                    ".set push                               \n\t"
-                    ".set noreorder                          \n\t"
-                    "addiu   %[loop_end], %[src],      1792  \n\t"
-                "1:                                          \n\t"
-                    "lw      %[temp0],    0(%[src])          \n\t"
-                    "lw      %[temp1],    4(%[src])          \n\t"
-                    "lw      %[temp2],    8(%[src])          \n\t"
-                    "lw      %[temp3],    12(%[src])         \n\t"
-                    "lw      %[temp4],    16(%[src])         \n\t"
-                    "lw      %[temp5],    20(%[src])         \n\t"
-                    "lw      %[temp6],    24(%[src])         \n\t"
-                    "lw      %[temp7],    28(%[src])         \n\t"
-                    "addiu   %[src],      %[src],      32    \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"
-                    "bne     %[src],      %[loop_end], 1b    \n\t"
-                    " addiu  %[dst],      %[dst],      32    \n\t"
-                    ".set pop                                \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),
-                      [loop_end]"=&r"(loop_end), [src]"+r"(buf1),
-                      [dst]"+r"(buf2)
-                    :
-                    : "memory"
-                );
-            }
+            float_copy(out + 576, buf + 64, 448);
         }
     }
 
@@ -251,176 +213,12 @@
         ac->fdsp->vector_fmul_window(saved + 64,  buf + 4*128 + 64, buf + 5*128, swindow, 64);
         ac->fdsp->vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
         ac->fdsp->vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
-        {
-            float *buf1 = buf + 7*128 + 64;
-            float *buf2 = saved + 448;
-            int temp0, temp1, temp2, temp3, temp4, temp5, temp6, temp7;
-            int loop_end;
-
-            /* loop unrolled 8 times */
-            __asm__ volatile (
-                ".set push                                \n\t"
-                ".set noreorder                           \n\t"
-                "addiu   %[loop_end], %[src],       256   \n\t"
-            "1:                                           \n\t"
-                "lw      %[temp0],    0(%[src])           \n\t"
-                "lw      %[temp1],    4(%[src])           \n\t"
-                "lw      %[temp2],    8(%[src])           \n\t"
-                "lw      %[temp3],    12(%[src])          \n\t"
-                "lw      %[temp4],    16(%[src])          \n\t"
-                "lw      %[temp5],    20(%[src])          \n\t"
-                "lw      %[temp6],    24(%[src])          \n\t"
-                "lw      %[temp7],    28(%[src])          \n\t"
-                "addiu   %[src],      %[src],       32    \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"
-                "bne     %[src],      %[loop_end],  1b    \n\t"
-                " addiu  %[dst],      %[dst],       32    \n\t"
-                ".set pop                                 \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),
-                  [loop_end]"=&r"(loop_end), [src]"+r"(buf1),
-                  [dst]"+r"(buf2)
-                :
-                : "memory"
-            );
-        }
+        float_copy(saved + 448, buf + 7*128 + 64, 64);
     } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
-        float *buf1 = buf + 512;
-        float *buf2 = saved;
-        int temp0, temp1, temp2, temp3, temp4, temp5, temp6, temp7;
-        int loop_end;
-
-        /* loop unrolled 8 times */
-        __asm__ volatile (
-            ".set push                                \n\t"
-            ".set noreorder                           \n\t"
-            "addiu   %[loop_end], %[src],       1792  \n\t"
-        "1:                                           \n\t"
-            "lw      %[temp0],    0(%[src])           \n\t"
-            "lw      %[temp1],    4(%[src])           \n\t"
-            "lw      %[temp2],    8(%[src])           \n\t"
-            "lw      %[temp3],    12(%[src])          \n\t"
-            "lw      %[temp4],    16(%[src])          \n\t"
-            "lw      %[temp5],    20(%[src])          \n\t"
-            "lw      %[temp6],    24(%[src])          \n\t"
-            "lw      %[temp7],    28(%[src])          \n\t"
-            "addiu   %[src],      %[src],       32    \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"
-            "bne     %[src],      %[loop_end],  1b    \n\t"
-            " addiu  %[dst],      %[dst],       32    \n\t"
-            ".set pop                                 \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),
-              [loop_end]"=&r"(loop_end), [src]"+r"(buf1),
-              [dst]"+r"(buf2)
-            :
-            : "memory"
-        );
-        {
-            float *buf1 = buf + 7*128 + 64;
-            float *buf2 = saved + 448;
-            int temp0, temp1, temp2, temp3, temp4, temp5, temp6, temp7;
-            int loop_end;
-
-            /* loop unrolled 8 times */
-            __asm__ volatile (
-                ".set push                                 \n\t"
-                ".set noreorder                            \n\t"
-                "addiu   %[loop_end], %[src],        256   \n\t"
-            "1:                                            \n\t"
-                "lw      %[temp0],    0(%[src])            \n\t"
-                "lw      %[temp1],    4(%[src])            \n\t"
-                "lw      %[temp2],    8(%[src])            \n\t"
-                "lw      %[temp3],    12(%[src])           \n\t"
-                "lw      %[temp4],    16(%[src])           \n\t"
-                "lw      %[temp5],    20(%[src])           \n\t"
-                "lw      %[temp6],    24(%[src])           \n\t"
-                "lw      %[temp7],    28(%[src])           \n\t"
-                "addiu   %[src],      %[src],        32    \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"
-                "bne     %[src],      %[loop_end],   1b    \n\t"
-                " addiu  %[dst],      %[dst],        32    \n\t"
-                ".set pop                                  \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),
-                  [loop_end]"=&r"(loop_end), [src]"+r"(buf1),
-                  [dst]"+r"(buf2)
-                :
-                : "memory"
-            );
-        }
+        float_copy(saved, buf + 512, 448);
+        float_copy(saved + 448, buf + 7*128 + 64, 64);
     } else { // LONG_STOP or ONLY_LONG
-        float *buf1 = buf + 512;
-        float *buf2 = saved;
-        int temp0, temp1, temp2, temp3, temp4, temp5, temp6, temp7;
-        int loop_end;
-
-        /* loop unrolled 8 times */
-        __asm__ volatile (
-            ".set push                                 \n\t"
-            ".set noreorder                            \n\t"
-            "addiu   %[loop_end], %[src],        2048  \n\t"
-        "1:                                            \n\t"
-            "lw      %[temp0],    0(%[src])            \n\t"
-            "lw      %[temp1],    4(%[src])            \n\t"
-            "lw      %[temp2],    8(%[src])            \n\t"
-            "lw      %[temp3],    12(%[src])           \n\t"
-            "lw      %[temp4],    16(%[src])           \n\t"
-            "lw      %[temp5],    20(%[src])           \n\t"
-            "lw      %[temp6],    24(%[src])           \n\t"
-            "lw      %[temp7],    28(%[src])           \n\t"
-            "addiu   %[src],      %[src],        32    \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"
-            "bne     %[src],      %[loop_end],   1b    \n\t"
-            " addiu  %[dst],      %[dst],        32    \n\t"
-            ".set pop                                  \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),
-              [loop_end]"=&r"(loop_end), [src]"+r"(buf1),
-              [dst]"+r"(buf2)
-            :
-            : "memory"
-        );
+        float_copy(saved, buf + 512, 512);
     }
 }
 
@@ -453,7 +251,7 @@
                 "sw      $0,              4(%[p_predTime])        \n\t"
                 "sw      $0,              8(%[p_predTime])        \n\t"
                 "sw      $0,              12(%[p_predTime])       \n\t"
-                "addiu   %[p_predTime],   %[p_predTime],     16   \n\t"
+                PTR_ADDIU "%[p_predTime], %[p_predTime],     16   \n\t"
 
                 : [p_predTime]"+r"(p_predTime)
                 :
@@ -464,7 +262,7 @@
 
             __asm__ volatile (
                 "sw      $0,              0(%[p_predTime])        \n\t"
-                "addiu   %[p_predTime],   %[p_predTime],     4    \n\t"
+                PTR_ADDIU "%[p_predTime], %[p_predTime],     4    \n\t"
 
                 : [p_predTime]"+r"(p_predTime)
                 :
@@ -485,6 +283,56 @@
 }
 
 #if HAVE_MIPSFPU
+static av_always_inline void fmul_and_reverse(float *dst, const float *src0, const float *src1, int count)
+{
+    /* Multiply 'count' floats in src0 by src1 and store the results in dst in reverse */
+    /* This should be equivalent to a normal fmul, followed by reversing dst */
+
+    // count must be a multiple of 4
+    av_assert2(count % 4 == 0);
+
+    // move src0 and src1 to the last element of their arrays
+    src0 += count - 1;
+    src1 += count - 1;
+
+    for (; count > 0; count -= 4){
+        float temp[12];
+
+        /* loop unrolled 4 times */
+        __asm__ volatile (
+            "lwc1    %[temp0],    0(%[ptr2])                \n\t"
+            "lwc1    %[temp1],    -4(%[ptr2])               \n\t"
+            "lwc1    %[temp2],    -8(%[ptr2])               \n\t"
+            "lwc1    %[temp3],    -12(%[ptr2])              \n\t"
+            "lwc1    %[temp4],    0(%[ptr3])                \n\t"
+            "lwc1    %[temp5],    -4(%[ptr3])               \n\t"
+            "lwc1    %[temp6],    -8(%[ptr3])               \n\t"
+            "lwc1    %[temp7],    -12(%[ptr3])              \n\t"
+            "mul.s   %[temp8],    %[temp0],     %[temp4]    \n\t"
+            "mul.s   %[temp9],    %[temp1],     %[temp5]    \n\t"
+            "mul.s   %[temp10],   %[temp2],     %[temp6]    \n\t"
+            "mul.s   %[temp11],   %[temp3],     %[temp7]    \n\t"
+            "swc1    %[temp8],    0(%[ptr1])                \n\t"
+            "swc1    %[temp9],    4(%[ptr1])                \n\t"
+            "swc1    %[temp10],   8(%[ptr1])                \n\t"
+            "swc1    %[temp11],   12(%[ptr1])               \n\t"
+            PTR_ADDIU "%[ptr1],   %[ptr1],      16          \n\t"
+            PTR_ADDIU "%[ptr2],   %[ptr2],      -16         \n\t"
+            PTR_ADDIU "%[ptr3],   %[ptr3],      -16         \n\t"
+
+            : [temp0]"=&f"(temp[0]), [temp1]"=&f"(temp[1]),
+              [temp2]"=&f"(temp[2]), [temp3]"=&f"(temp[3]),
+              [temp4]"=&f"(temp[4]), [temp5]"=&f"(temp[5]),
+              [temp6]"=&f"(temp[6]), [temp7]"=&f"(temp[7]),
+              [temp8]"=&f"(temp[8]), [temp9]"=&f"(temp[9]),
+              [temp10]"=&f"(temp[10]), [temp11]"=&f"(temp[11]),
+              [ptr1]"+r"(dst), [ptr2]"+r"(src0), [ptr3]"+r"(src1)
+            :
+            : "memory"
+        );
+    }
+}
+
 static void update_ltp_mips(AACContext *ac, SingleChannelElement *sce)
 {
     IndividualChannelStream *ics = &sce->ics;
@@ -492,55 +340,13 @@
     float *saved_ltp = sce->coeffs;
     const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
     const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
-    int i;
-    int loop_end, loop_end1, loop_end2;
-    float temp0, temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9, temp10, temp11;
+    float temp0, temp1, temp2, temp3, temp4, temp5, temp6, temp7;
 
     if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
-        float *buf = saved;
-        float *buf0 = saved_ltp;
         float *p_saved_ltp = saved_ltp + 576;
-        float *ptr1 = &saved_ltp[512];
-        float *ptr2 = &ac->buf_mdct[1023];
-        float *ptr3 = (float*)&swindow[63];
-        loop_end1 = (int)(p_saved_ltp + 448);
+        float *loop_end1 = p_saved_ltp + 448;
 
-        /* loop unrolled 8 times */
-        __asm__ volatile (
-            ".set push                                     \n\t"
-            ".set noreorder                                \n\t"
-            "addiu   %[loop_end],   %[src],         2048   \n\t"
-        "1:                                                \n\t"
-            "lw      %[temp0],      0(%[src])              \n\t"
-            "lw      %[temp1],      4(%[src])              \n\t"
-            "lw      %[temp2],      8(%[src])              \n\t"
-            "lw      %[temp3],      12(%[src])             \n\t"
-            "lw      %[temp4],      16(%[src])             \n\t"
-            "lw      %[temp5],      20(%[src])             \n\t"
-            "lw      %[temp6],      24(%[src])             \n\t"
-            "lw      %[temp7],      28(%[src])             \n\t"
-            "addiu   %[src],        %[src],         32     \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"
-            "bne     %[src],        %[loop_end],    1b     \n\t"
-            " addiu  %[dst],        %[dst],         32     \n\t"
-            ".set pop                                      \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),
-              [loop_end]"=&r"(loop_end), [src]"+r"(buf),
-              [dst]"+r"(buf0)
-            :
-            : "memory"
-        );
+        float_copy(saved_ltp, saved, 512);
 
         /* loop unrolled 8 times */
         __asm__ volatile (
@@ -553,7 +359,7 @@
             "sw     $0,              20(%[p_saved_ltp])       \n\t"
             "sw     $0,              24(%[p_saved_ltp])       \n\t"
             "sw     $0,              28(%[p_saved_ltp])       \n\t"
-            "addiu  %[p_saved_ltp],  %[p_saved_ltp],     32   \n\t"
+            PTR_ADDIU "%[p_saved_ltp],%[p_saved_ltp],    32   \n\t"
             "bne    %[p_saved_ltp],  %[loop_end1],       1b   \n\t"
 
             : [p_saved_ltp]"+r"(p_saved_ltp)
@@ -562,47 +368,11 @@
         );
 
         ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
-        for (i = 0; i < 16; i++){
-            /* loop unrolled 4 times */
-            __asm__ volatile (
-                "lwc1    %[temp0],    0(%[ptr2])                \n\t"
-                "lwc1    %[temp1],    -4(%[ptr2])               \n\t"
-                "lwc1    %[temp2],    -8(%[ptr2])               \n\t"
-                "lwc1    %[temp3],    -12(%[ptr2])              \n\t"
-                "lwc1    %[temp4],    0(%[ptr3])                \n\t"
-                "lwc1    %[temp5],    -4(%[ptr3])               \n\t"
-                "lwc1    %[temp6],    -8(%[ptr3])               \n\t"
-                "lwc1    %[temp7],    -12(%[ptr3])              \n\t"
-                "mul.s   %[temp8],    %[temp0],     %[temp4]    \n\t"
-                "mul.s   %[temp9],    %[temp1],     %[temp5]    \n\t"
-                "mul.s   %[temp10],   %[temp2],     %[temp6]    \n\t"
-                "mul.s   %[temp11],   %[temp3],     %[temp7]    \n\t"
-                "swc1    %[temp8],    0(%[ptr1])                \n\t"
-                "swc1    %[temp9],    4(%[ptr1])                \n\t"
-                "swc1    %[temp10],   8(%[ptr1])                \n\t"
-                "swc1    %[temp11],   12(%[ptr1])               \n\t"
-                "addiu   %[ptr1],     %[ptr1],      16          \n\t"
-                "addiu   %[ptr2],     %[ptr2],      -16         \n\t"
-                "addiu   %[ptr3],     %[ptr3],      -16         \n\t"
-
-                : [temp0]"=&f"(temp0), [temp1]"=&f"(temp1),
-                  [temp2]"=&f"(temp2), [temp3]"=&f"(temp3),
-                  [temp4]"=&f"(temp4), [temp5]"=&f"(temp5),
-                  [temp6]"=&f"(temp6), [temp7]"=&f"(temp7),
-                  [temp8]"=&f"(temp8), [temp9]"=&f"(temp9),
-                  [temp10]"=&f"(temp10), [temp11]"=&f"(temp11),
-                  [ptr1]"+r"(ptr1), [ptr2]"+r"(ptr2), [ptr3]"+r"(ptr3)
-                :
-                : "memory"
-            );
-        }
+        fmul_and_reverse(saved_ltp + 512, ac->buf_mdct + 960, swindow, 64);
     } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
         float *buff0 = saved;
         float *buff1 = saved_ltp;
-        float *ptr1 = &saved_ltp[512];
-        float *ptr2 = &ac->buf_mdct[1023];
-        float *ptr3 = (float*)&swindow[63];
-        loop_end = (int)(saved + 448);
+        float *loop_end = saved + 448;
 
         /* loop unrolled 8 times */
         __asm__ volatile (
@@ -617,7 +387,7 @@
             "lw      %[temp5],    20(%[src])            \n\t"
             "lw      %[temp6],    24(%[src])            \n\t"
             "lw      %[temp7],    28(%[src])            \n\t"
-            "addiu   %[src],      %[src],         32    \n\t"
+            PTR_ADDIU "%[src],    %[src],         32    \n\t"
             "sw      %[temp0],    0(%[dst])             \n\t"
             "sw      %[temp1],    4(%[dst])             \n\t"
             "sw      %[temp2],    8(%[dst])             \n\t"
@@ -635,7 +405,7 @@
             "sw      $0,          2328(%[dst])          \n\t"
             "sw      $0,          2332(%[dst])          \n\t"
             "bne     %[src],      %[loop_end],    1b    \n\t"
-            " addiu  %[dst],      %[dst],         32    \n\t"
+            PTR_ADDIU "%[dst],    %[dst],         32    \n\t"
             ".set pop                                   \n\t"
 
             : [temp0]"=&r"(temp0), [temp1]"=&r"(temp1),
@@ -647,174 +417,15 @@
             : "memory"
         );
         ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960,     &swindow[64],      64);
-        for (i = 0; i < 16; i++){
-            /* loop unrolled 8 times */
-            __asm__ volatile (
-                "lwc1    %[temp0],    0(%[ptr2])                \n\t"
-                "lwc1    %[temp1],    -4(%[ptr2])               \n\t"
-                "lwc1    %[temp2],    -8(%[ptr2])               \n\t"
-                "lwc1    %[temp3],    -12(%[ptr2])              \n\t"
-                "lwc1    %[temp4],    0(%[ptr3])                \n\t"
-                "lwc1    %[temp5],    -4(%[ptr3])               \n\t"
-                "lwc1    %[temp6],    -8(%[ptr3])               \n\t"
-                "lwc1    %[temp7],    -12(%[ptr3])              \n\t"
-                "mul.s   %[temp8],    %[temp0],     %[temp4]    \n\t"
-                "mul.s   %[temp9],    %[temp1],     %[temp5]    \n\t"
-                "mul.s   %[temp10],   %[temp2],     %[temp6]    \n\t"
-                "mul.s   %[temp11],   %[temp3],     %[temp7]    \n\t"
-                "swc1    %[temp8],    0(%[ptr1])                \n\t"
-                "swc1    %[temp9],    4(%[ptr1])                \n\t"
-                "swc1    %[temp10],   8(%[ptr1])                \n\t"
-                "swc1    %[temp11],   12(%[ptr1])               \n\t"
-                "addiu   %[ptr1],     %[ptr1],      16          \n\t"
-                "addiu   %[ptr2],     %[ptr2],      -16         \n\t"
-                "addiu   %[ptr3],     %[ptr3],      -16         \n\t"
-
-                : [temp0]"=&f"(temp0), [temp1]"=&f"(temp1),
-                  [temp2]"=&f"(temp2), [temp3]"=&f"(temp3),
-                  [temp4]"=&f"(temp4), [temp5]"=&f"(temp5),
-                  [temp6]"=&f"(temp6), [temp7]"=&f"(temp7),
-                  [temp8]"=&f"(temp8), [temp9]"=&f"(temp9),
-                  [temp10]"=&f"(temp10), [temp11]"=&f"(temp11),
-                  [ptr1]"+r"(ptr1), [ptr2]"+r"(ptr2), [ptr3]"+r"(ptr3)
-                :
-                : "memory"
-            );
-        }
+        fmul_and_reverse(saved_ltp + 512, ac->buf_mdct + 960, swindow, 64);
     } else { // LONG_STOP or ONLY_LONG
-        float *ptr1, *ptr2, *ptr3;
         ac->fdsp->vector_fmul_reverse(saved_ltp,       ac->buf_mdct + 512,     &lwindow[512],     512);
-
-        ptr1 = &saved_ltp[512];
-        ptr2 = &ac->buf_mdct[1023];
-        ptr3 = (float*)&lwindow[511];
-
-        for (i = 0; i < 512; i+=4){
-            /* loop unrolled 4 times */
-            __asm__ volatile (
-                "lwc1    %[temp0],    0(%[ptr2])                \n\t"
-                "lwc1    %[temp1],    -4(%[ptr2])               \n\t"
-                "lwc1    %[temp2],    -8(%[ptr2])               \n\t"
-                "lwc1    %[temp3],    -12(%[ptr2])              \n\t"
-                "lwc1    %[temp4],    0(%[ptr3])                \n\t"
-                "lwc1    %[temp5],    -4(%[ptr3])               \n\t"
-                "lwc1    %[temp6],    -8(%[ptr3])               \n\t"
-                "lwc1    %[temp7],    -12(%[ptr3])              \n\t"
-                "mul.s   %[temp8],    %[temp0],     %[temp4]    \n\t"
-                "mul.s   %[temp9],    %[temp1],     %[temp5]    \n\t"
-                "mul.s   %[temp10],   %[temp2],     %[temp6]    \n\t"
-                "mul.s   %[temp11],   %[temp3],     %[temp7]    \n\t"
-                "swc1    %[temp8],    0(%[ptr1])                \n\t"
-                "swc1    %[temp9],    4(%[ptr1])                \n\t"
-                "swc1    %[temp10],   8(%[ptr1])                \n\t"
-                "swc1    %[temp11],   12(%[ptr1])               \n\t"
-                "addiu   %[ptr1],     %[ptr1],      16          \n\t"
-                "addiu   %[ptr2],     %[ptr2],      -16         \n\t"
-                "addiu   %[ptr3],     %[ptr3],      -16         \n\t"
-
-                : [temp0]"=&f"(temp0), [temp1]"=&f"(temp1),
-                  [temp2]"=&f"(temp2), [temp3]"=&f"(temp3),
-                  [temp4]"=&f"(temp4), [temp5]"=&f"(temp5),
-                  [temp6]"=&f"(temp6), [temp7]"=&f"(temp7),
-                  [temp8]"=&f"(temp8), [temp9]"=&f"(temp9),
-                  [temp10]"=&f"(temp10), [temp11]"=&f"(temp11),
-                  [ptr1]"+r"(ptr1), [ptr2]"+r"(ptr2),
-                  [ptr3]"+r"(ptr3)
-                :
-                : "memory"
-            );
-        }
+        fmul_and_reverse(saved_ltp + 512, ac->buf_mdct + 512, lwindow, 512);
     }
 
-    {
-        float *buf1 = sce->ltp_state+1024;
-        float *buf2 = sce->ltp_state;
-        float *buf3 = sce->ret;
-        float *buf4 = sce->ltp_state+1024;
-        float *buf5 = saved_ltp;
-        float *buf6 = sce->ltp_state+2048;
-
-        /* loops unrolled 8 times */
-        __asm__ volatile (
-            ".set push                                    \n\t"
-            ".set noreorder                               \n\t"
-            "addiu   %[loop_end],   %[src],         4096  \n\t"
-            "addiu   %[loop_end1],  %[src1],        4096  \n\t"
-            "addiu   %[loop_end2],  %[src2],        4096  \n\t"
-        "1:                                               \n\t"
-            "lw      %[temp0],      0(%[src])             \n\t"
-            "lw      %[temp1],      4(%[src])             \n\t"
-            "lw      %[temp2],      8(%[src])             \n\t"
-            "lw      %[temp3],      12(%[src])            \n\t"
-            "lw      %[temp4],      16(%[src])            \n\t"
-            "lw      %[temp5],      20(%[src])            \n\t"
-            "lw      %[temp6],      24(%[src])            \n\t"
-            "lw      %[temp7],      28(%[src])            \n\t"
-            "addiu   %[src],        %[src],         32    \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"
-            "bne     %[src],        %[loop_end],    1b    \n\t"
-            " addiu  %[dst],        %[dst],         32    \n\t"
-        "2:                                               \n\t"
-            "lw      %[temp0],      0(%[src1])            \n\t"
-            "lw      %[temp1],      4(%[src1])            \n\t"
-            "lw      %[temp2],      8(%[src1])            \n\t"
-            "lw      %[temp3],      12(%[src1])           \n\t"
-            "lw      %[temp4],      16(%[src1])           \n\t"
-            "lw      %[temp5],      20(%[src1])           \n\t"
-            "lw      %[temp6],      24(%[src1])           \n\t"
-            "lw      %[temp7],      28(%[src1])           \n\t"
-            "addiu   %[src1],       %[src1],        32    \n\t"
-            "sw      %[temp0],      0(%[dst1])            \n\t"
-            "sw      %[temp1],      4(%[dst1])            \n\t"
-            "sw      %[temp2],      8(%[dst1])            \n\t"
-            "sw      %[temp3],      12(%[dst1])           \n\t"
-            "sw      %[temp4],      16(%[dst1])           \n\t"
-            "sw      %[temp5],      20(%[dst1])           \n\t"
-            "sw      %[temp6],      24(%[dst1])           \n\t"
-            "sw      %[temp7],      28(%[dst1])           \n\t"
-            "bne     %[src1],       %[loop_end1],   2b    \n\t"
-            " addiu  %[dst1],       %[dst1],        32    \n\t"
-        "3:                                               \n\t"
-            "lw      %[temp0],      0(%[src2])            \n\t"
-            "lw      %[temp1],      4(%[src2])            \n\t"
-            "lw      %[temp2],      8(%[src2])            \n\t"
-            "lw      %[temp3],      12(%[src2])           \n\t"
-            "lw      %[temp4],      16(%[src2])           \n\t"
-            "lw      %[temp5],      20(%[src2])           \n\t"
-            "lw      %[temp6],      24(%[src2])           \n\t"
-            "lw      %[temp7],      28(%[src2])           \n\t"
-            "addiu   %[src2],       %[src2],        32    \n\t"
-            "sw      %[temp0],      0(%[dst2])            \n\t"
-            "sw      %[temp1],      4(%[dst2])            \n\t"
-            "sw      %[temp2],      8(%[dst2])            \n\t"
-            "sw      %[temp3],      12(%[dst2])           \n\t"
-            "sw      %[temp4],      16(%[dst2])           \n\t"
-            "sw      %[temp5],      20(%[dst2])           \n\t"
-            "sw      %[temp6],      24(%[dst2])           \n\t"
-            "sw      %[temp7],      28(%[dst2])           \n\t"
-            "bne     %[src2],       %[loop_end2],   3b    \n\t"
-            " addiu  %[dst2],       %[dst2],        32    \n\t"
-            ".set pop                                     \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),
-              [loop_end]"=&r"(loop_end), [loop_end1]"=&r"(loop_end1),
-              [loop_end2]"=&r"(loop_end2), [src]"+r"(buf1),
-              [dst]"+r"(buf2), [src1]"+r"(buf3), [dst1]"+r"(buf4),
-              [src2]"+r"(buf5), [dst2]"+r"(buf6)
-            :
-            : "memory"
-        );
-    }
+    float_copy(sce->ltp_state, sce->ltp_state + 1024, 1024);
+    float_copy(sce->ltp_state + 1024, sce->ret, 1024);
+    float_copy(sce->ltp_state + 2048, saved_ltp, 1024);
 }
 #endif /* HAVE_MIPSFPU */
 #endif /* HAVE_INLINE_ASM */
diff --git a/libavcodec/mips/aacdec_mips.h b/libavcodec/mips/aacdec_mips.h
index 9ba3079..054a9fb 100644
--- a/libavcodec/mips/aacdec_mips.h
+++ b/libavcodec/mips/aacdec_mips.h
@@ -58,6 +58,7 @@
 #define AVCODEC_MIPS_AACDEC_FLOAT_H
 
 #include "libavcodec/aac.h"
+#include "libavutil/mips/asmdefs.h"
 
 #if HAVE_INLINE_ASM && HAVE_MIPSFPU
 static inline float *VMUL2_mips(float *dst, const float *v, unsigned idx,
@@ -68,16 +69,16 @@
     float *ret;
 
     __asm__ volatile(
-        "andi    %[temp3],  %[idx],       15           \n\t"
-        "ext     %[temp4],  %[idx],       4,      4    \n\t"
+        "andi    %[temp3],  %[idx],       0x0F         \n\t"
+        "andi    %[temp4],  %[idx],       0xF0         \n\t"
         "sll     %[temp3],  %[temp3],     2            \n\t"
-        "sll     %[temp4],  %[temp4],     2            \n\t"
+        "srl     %[temp4],  %[temp4],     2            \n\t"
         "lwc1    %[temp2],  0(%[scale])                \n\t"
         "lwxc1   %[temp0],  %[temp3](%[v])             \n\t"
         "lwxc1   %[temp1],  %[temp4](%[v])             \n\t"
         "mul.s   %[temp0],  %[temp0],     %[temp2]     \n\t"
         "mul.s   %[temp1],  %[temp1],     %[temp2]     \n\t"
-        "addiu   %[ret],    %[dst],       8            \n\t"
+        PTR_ADDIU "%[ret],  %[dst],       8            \n\t"
         "swc1    %[temp0],  0(%[dst])                  \n\t"
         "swc1    %[temp1],  4(%[dst])                  \n\t"
 
@@ -99,14 +100,13 @@
     float *ret;
 
     __asm__ volatile(
-        "andi    %[temp0],  %[idx],       3           \n\t"
-        "ext     %[temp1],  %[idx],       2,      2   \n\t"
-        "ext     %[temp2],  %[idx],       4,      2   \n\t"
-        "ext     %[temp3],  %[idx],       6,      2   \n\t"
+        "andi    %[temp0],  %[idx],       0x03        \n\t"
+        "andi    %[temp1],  %[idx],       0x0C        \n\t"
+        "andi    %[temp2],  %[idx],       0x30        \n\t"
+        "andi    %[temp3],  %[idx],       0xC0        \n\t"
         "sll     %[temp0],  %[temp0],     2           \n\t"
-        "sll     %[temp1],  %[temp1],     2           \n\t"
-        "sll     %[temp2],  %[temp2],     2           \n\t"
-        "sll     %[temp3],  %[temp3],     2           \n\t"
+        "srl     %[temp2],  %[temp2],     2           \n\t"
+        "srl     %[temp3],  %[temp3],     4           \n\t"
         "lwc1    %[temp4],  0(%[scale])               \n\t"
         "lwxc1   %[temp5],  %[temp0](%[v])            \n\t"
         "lwxc1   %[temp6],  %[temp1](%[v])            \n\t"
@@ -116,7 +116,7 @@
         "mul.s   %[temp6],  %[temp6],     %[temp4]    \n\t"
         "mul.s   %[temp7],  %[temp7],     %[temp4]    \n\t"
         "mul.s   %[temp8],  %[temp8],     %[temp4]    \n\t"
-        "addiu   %[ret],    %[dst],       16          \n\t"
+        PTR_ADDIU "%[ret],  %[dst],       16          \n\t"
         "swc1    %[temp5],  0(%[dst])                 \n\t"
         "swc1    %[temp6],  4(%[dst])                 \n\t"
         "swc1    %[temp7],  8(%[dst])                 \n\t"
@@ -142,14 +142,14 @@
     float *ret;
 
     __asm__ volatile(
-        "andi    %[temp0],  %[idx],       15         \n\t"
-        "ext     %[temp1],  %[idx],       4,     4   \n\t"
+        "andi    %[temp0],  %[idx],       0x0F       \n\t"
+        "andi    %[temp1],  %[idx],       0xF0       \n\t"
         "lw      %[temp4],  0(%[scale])              \n\t"
         "srl     %[temp2],  %[sign],      1          \n\t"
         "sll     %[temp3],  %[sign],      31         \n\t"
         "sll     %[temp2],  %[temp2],     31         \n\t"
         "sll     %[temp0],  %[temp0],     2          \n\t"
-        "sll     %[temp1],  %[temp1],     2          \n\t"
+        "srl     %[temp1],  %[temp1],     2          \n\t"
         "lwxc1   %[temp8],  %[temp0](%[v])           \n\t"
         "lwxc1   %[temp9],  %[temp1](%[v])           \n\t"
         "xor     %[temp5],  %[temp4],     %[temp2]   \n\t"
@@ -158,7 +158,7 @@
         "mtc1    %[temp4],  %[temp7]                 \n\t"
         "mul.s   %[temp8],  %[temp8],     %[temp6]   \n\t"
         "mul.s   %[temp9],  %[temp9],     %[temp7]   \n\t"
-        "addiu   %[ret],    %[dst],       8          \n\t"
+        PTR_ADDIU "%[ret],  %[dst],       8          \n\t"
         "swc1    %[temp8],  0(%[dst])                \n\t"
         "swc1    %[temp9],  4(%[dst])                \n\t"
 
@@ -185,22 +185,24 @@
 
     __asm__ volatile(
         "lw      %[temp0],   0(%[scale])               \n\t"
-        "and     %[temp1],   %[idx],       3           \n\t"
-        "ext     %[temp2],   %[idx],       2,      2   \n\t"
-        "ext     %[temp3],   %[idx],       4,      2   \n\t"
-        "ext     %[temp4],   %[idx],       6,      2   \n\t"
-        "sll     %[temp1],   %[temp1],     2           \n\t"
-        "sll     %[temp2],   %[temp2],     2           \n\t"
-        "sll     %[temp3],   %[temp3],     2           \n\t"
-        "sll     %[temp4],   %[temp4],     2           \n\t"
+        "andi    %[temp1],  %[idx],       0x03         \n\t"
+        "andi    %[temp2],  %[idx],       0x0C         \n\t"
+        "andi    %[temp3],  %[idx],       0x30         \n\t"
+        "andi    %[temp4],  %[idx],       0xC0         \n\t"
+        "sll     %[temp1],  %[temp1],     2            \n\t"
+        "srl     %[temp3],  %[temp3],     2            \n\t"
+        "srl     %[temp4],  %[temp4],     4            \n\t"
         "lwxc1   %[temp10],  %[temp1](%[v])            \n\t"
         "lwxc1   %[temp11],  %[temp2](%[v])            \n\t"
         "lwxc1   %[temp12],  %[temp3](%[v])            \n\t"
         "lwxc1   %[temp13],  %[temp4](%[v])            \n\t"
         "and     %[temp1],   %[sign],      %[mask]     \n\t"
-        "ext     %[temp2],   %[idx],       12,     1   \n\t"
-        "ext     %[temp3],   %[idx],       13,     1   \n\t"
-        "ext     %[temp4],   %[idx],       14,     1   \n\t"
+        "srl     %[temp2],   %[idx],       12          \n\t"
+        "srl     %[temp3],   %[idx],       13          \n\t"
+        "srl     %[temp4],   %[idx],       14          \n\t"
+        "andi    %[temp2],   %[temp2],     1           \n\t"
+        "andi    %[temp3],   %[temp3],     1           \n\t"
+        "andi    %[temp4],   %[temp4],     1           \n\t"
         "sllv    %[sign],    %[sign],      %[temp2]    \n\t"
         "xor     %[temp1],   %[temp0],     %[temp1]    \n\t"
         "and     %[temp2],   %[sign],      %[mask]     \n\t"
@@ -219,7 +221,7 @@
         "mul.s   %[temp11],  %[temp11],    %[temp15]   \n\t"
         "mul.s   %[temp12],  %[temp12],    %[temp16]   \n\t"
         "mul.s   %[temp13],  %[temp13],    %[temp17]   \n\t"
-        "addiu   %[ret],     %[dst],       16          \n\t"
+        PTR_ADDIU "%[ret],   %[dst],       16          \n\t"
         "swc1    %[temp10],  0(%[dst])                 \n\t"
         "swc1    %[temp11],  4(%[dst])                 \n\t"
         "swc1    %[temp12],  8(%[dst])                 \n\t"
diff --git a/libavcodec/mips/aacpsdsp_mips.c b/libavcodec/mips/aacpsdsp_mips.c
index 4730a7f..695f9ef 100644
--- a/libavcodec/mips/aacpsdsp_mips.c
+++ b/libavcodec/mips/aacpsdsp_mips.c
@@ -54,6 +54,7 @@
 
 #include "config.h"
 #include "libavcodec/aacpsdsp.h"
+#include "libavutil/mips/asmdefs.h"
 
 #if HAVE_INLINE_ASM
 static void ps_hybrid_analysis_ileave_mips(float (*out)[32][2], float L[2][38][64],
@@ -86,8 +87,8 @@
             "sw      %[temp5],   20(%[out1])         \n\t"
             "sw      %[temp6],   24(%[out1])         \n\t"
             "sw      %[temp7],   28(%[out1])         \n\t"
-            "addiu   %[out1],    %[out1],      32    \n\t"
-            "addiu   %[L1],      %[L1],        1024  \n\t"
+            PTR_ADDIU "%[out1],  %[out1],      32    \n\t"
+            PTR_ADDIU "%[L1],    %[L1],        1024  \n\t"
             "bne     %[out1],    %[j],         1b    \n\t"
 
             : [out1]"+r"(out1), [L1]"+r"(L1), [j]"+r"(j),
@@ -128,10 +129,10 @@
                  "lw      %[temp5],   16(%[in2])              \n\t"
                  "lw      %[temp6],   24(%[in1])              \n\t"
                  "lw      %[temp7],   24(%[in2])              \n\t"
-                 "addiu   %[out1],    %[out1],         1024   \n\t"
-                 "addiu   %[out2],    %[out2],         1024   \n\t"
-                 "addiu   %[in1],     %[in1],          32     \n\t"
-                 "addiu   %[in2],     %[in2],          32     \n\t"
+                 PTR_ADDIU "%[out1],  %[out1],         1024   \n\t"
+                 PTR_ADDIU "%[out2],  %[out2],         1024   \n\t"
+                 PTR_ADDIU "%[in1],   %[in1],          32     \n\t"
+                 PTR_ADDIU "%[in2],   %[in2],          32     \n\t"
                  "sw      %[temp0],   -1024(%[out1])          \n\t"
                  "sw      %[temp1],   -1024(%[out2])          \n\t"
                  "sw      %[temp2],   -768(%[out1])           \n\t"
@@ -161,10 +162,10 @@
             "lw      %[temp5],   16(%[in2])              \n\t"
             "lw      %[temp6],   24(%[in1])              \n\t"
             "lw      %[temp7],   24(%[in2])              \n\t"
-            "addiu   %[out1],    %[out1],        -7164   \n\t"
-            "addiu   %[out2],    %[out2],        -7164   \n\t"
-            "addiu   %[in1],     %[in1],         32      \n\t"
-            "addiu   %[in2],     %[in2],         32      \n\t"
+            PTR_ADDIU "%[out1],  %[out1],        -7164   \n\t"
+            PTR_ADDIU "%[out2],  %[out2],        -7164   \n\t"
+            PTR_ADDIU "%[in1],   %[in1],         32      \n\t"
+            PTR_ADDIU "%[in2],   %[in2],         32      \n\t"
             "sw      %[temp0],   7164(%[out1])           \n\t"
             "sw      %[temp1],   7164(%[out2])           \n\t"
             "sw      %[temp2],   7420(%[out1])           \n\t"
@@ -226,8 +227,8 @@
             "swc1     %[temp2],    4(%[dst0])                          \n\t"
             "swc1     %[temp4],    8(%[dst0])                          \n\t"
             "swc1     %[temp6],    12(%[dst0])                         \n\t"
-            "addiu    %[dst0],     %[dst0],     16                     \n\t"
-            "addiu    %[src0],     %[src0],     32                     \n\t"
+            PTR_ADDIU "%[dst0],    %[dst0],     16                     \n\t"
+            PTR_ADDIU "%[src0],    %[src0],     32                     \n\t"
 
             : [temp0]"=&f"(temp0), [temp1]"=&f"(temp1), [temp2]"=&f"(temp2),
               [temp3]"=&f"(temp3), [temp4]"=&f"(temp4), [temp5]"=&f"(temp5),
@@ -257,14 +258,14 @@
         "lwc1     %[temp2],   0(%[p_s1])                \n\t"
         "lwc1     %[temp0],   0(%[p_s0])                \n\t"
         "lwc1     %[temp1],   4(%[p_s0])                \n\t"
-        "addiu    %[p_d],     %[p_d],       8           \n\t"
+        PTR_ADDIU "%[p_d],    %[p_d],       8           \n\t"
         "mul.s    %[temp0],   %[temp0],     %[temp2]    \n\t"
         "mul.s    %[temp1],   %[temp1],     %[temp2]    \n\t"
-        "addiu    %[p_s0],    %[p_s0],      8           \n\t"
+        PTR_ADDIU "%[p_s0],   %[p_s0],      8           \n\t"
         "swc1     %[temp0],   -8(%[p_d])                \n\t"
         "swc1     %[temp1],   -4(%[p_d])                \n\t"
         "bne      %[p_s1],    %[end],       1b          \n\t"
-        " addiu   %[p_s1],    %[p_s1],      4           \n\t"
+        PTR_ADDIU "%[p_s1],   %[p_s1],      4           \n\t"
         ".set pop                                       \n\t"
 
         : [temp0]"=&f"(temp0), [temp1]"=&f"(temp1),
@@ -277,7 +278,7 @@
 
 static void ps_decorrelate_mips(float (*out)[2], float (*delay)[2],
                              float (*ap_delay)[PS_QMF_TIME_SLOTS + PS_MAX_AP_DELAY][2],
-                             const float phi_fract[2], float (*Q_fract)[2],
+                             const float phi_fract[2], const float (*Q_fract)[2],
                              const float *transient_gain,
                              float g_decay_slope,
                              int len)
@@ -285,14 +286,14 @@
     float *p_delay = &delay[0][0];
     float *p_out = &out[0][0];
     float *p_ap_delay = &ap_delay[0][0][0];
-    float *p_t_gain = (float*)transient_gain;
-    float *p_Q_fract = &Q_fract[0][0];
+    const float *p_t_gain = transient_gain;
+    const float *p_Q_fract = &Q_fract[0][0];
     float ag0, ag1, ag2;
     float phi_fract0 = phi_fract[0];
     float phi_fract1 = phi_fract[1];
     float temp0, temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9;
 
-    len = (int)((int*)p_delay + (len << 1));
+    float *p_delay_end = (p_delay + (len << 1));
 
     /* merged 2 loops */
     __asm__ volatile(
@@ -355,20 +356,20 @@
         "mul.s   %[temp1],      %[ag2],        %[temp3]                  \n\t"
         "lwc1    %[temp4],      0(%[p_t_gain])                           \n\t"
         "sub.s   %[temp0],      %[temp8],      %[temp0]                  \n\t"
-        "addiu   %[p_ap_delay], %[p_ap_delay], 8                         \n\t"
+        PTR_ADDIU "%[p_ap_delay], %[p_ap_delay], 8                       \n\t"
         "sub.s   %[temp1],      %[temp9],      %[temp1]                  \n\t"
-        "addiu   %[p_t_gain],   %[p_t_gain],   4                         \n\t"
+        PTR_ADDIU "%[p_t_gain], %[p_t_gain],   4                         \n\t"
         "madd.s  %[temp2],      %[temp2],      %[ag2],   %[temp0]        \n\t"
-        "addiu   %[p_delay],    %[p_delay],    8                         \n\t"
+        PTR_ADDIU "%[p_delay],  %[p_delay],    8                         \n\t"
         "madd.s  %[temp3],      %[temp3],      %[ag2],   %[temp1]        \n\t"
-        "addiu   %[p_out],      %[p_out],      8                         \n\t"
+        PTR_ADDIU "%[p_out],    %[p_out],      8                         \n\t"
         "mul.s   %[temp5],      %[temp4],      %[temp0]                  \n\t"
         "mul.s   %[temp6],      %[temp4],      %[temp1]                  \n\t"
         "swc1    %[temp2],      624(%[p_ap_delay])                       \n\t"
         "swc1    %[temp3],      628(%[p_ap_delay])                       \n\t"
         "swc1    %[temp5],      -8(%[p_out])                             \n\t"
         "swc1    %[temp6],      -4(%[p_out])                             \n\t"
-        "bne     %[p_delay],    %[len],        1b                        \n\t"
+        "bne     %[p_delay],    %[p_delay_end],1b                        \n\t"
         " swc1   %[temp6],      -4(%[p_out])                             \n\t"
         ".set    pop                                                     \n\t"
 
@@ -379,7 +380,7 @@
           [p_Q_fract]"+r"(p_Q_fract), [p_t_gain]"+r"(p_t_gain), [p_out]"+r"(p_out),
           [ag0]"=&f"(ag0), [ag1]"=&f"(ag1), [ag2]"=&f"(ag2)
         : [phi_fract0]"f"(phi_fract0), [phi_fract1]"f"(phi_fract1),
-          [len]"r"(len), [g_decay_slope]"f"(g_decay_slope)
+          [p_delay_end]"r"(p_delay_end), [g_decay_slope]"f"(g_decay_slope)
         : "memory"
     );
 }
@@ -399,7 +400,7 @@
     float temp0, temp1, temp2, temp3;
     float l_re, l_im, r_re, r_im;
 
-    len = (int)((int*)l + (len << 1));
+    float *l_end = ((float *)l + (len << 1));
 
     __asm__ volatile(
         ".set    push                                     \n\t"
@@ -414,9 +415,9 @@
         "add.s   %[h3],     %[h3],     %[hs3]             \n\t"
         "lwc1    %[r_im],   4(%[r])                       \n\t"
         "mul.s   %[temp0],  %[h0],     %[l_re]            \n\t"
-        "addiu   %[l],      %[l],      8                  \n\t"
+        PTR_ADDIU "%[l],    %[l],      8                  \n\t"
         "mul.s   %[temp2],  %[h1],     %[l_re]            \n\t"
-        "addiu   %[r],      %[r],      8                  \n\t"
+        PTR_ADDIU "%[r],    %[r],      8                  \n\t"
         "madd.s  %[temp0],  %[temp0],  %[h2],   %[r_re]   \n\t"
         "madd.s  %[temp2],  %[temp2],  %[h3],   %[r_re]   \n\t"
         "mul.s   %[temp1],  %[h0],     %[l_im]            \n\t"
@@ -426,7 +427,7 @@
         "swc1    %[temp0],  -8(%[l])                      \n\t"
         "swc1    %[temp2],  -8(%[r])                      \n\t"
         "swc1    %[temp1],  -4(%[l])                      \n\t"
-        "bne     %[l],      %[len],    1b                 \n\t"
+        "bne     %[l],      %[l_end],  1b                 \n\t"
         " swc1   %[temp3],  -4(%[r])                      \n\t"
         ".set    pop                                      \n\t"
 
@@ -437,7 +438,7 @@
           [l_re]"=&f"(l_re), [l_im]"=&f"(l_im),
           [r_re]"=&f"(r_re), [r_im]"=&f"(r_im)
         : [hs0]"f"(hs0), [hs1]"f"(hs1), [hs2]"f"(hs2),
-          [hs3]"f"(hs3), [len]"r"(len)
+          [hs3]"f"(hs3), [l_end]"r"(l_end)
         : "memory"
     );
 }
diff --git a/libavcodec/mips/aacpsy_mips.h b/libavcodec/mips/aacpsy_mips.h
index d1353c4..596dcad 100644
--- a/libavcodec/mips/aacpsy_mips.h
+++ b/libavcodec/mips/aacpsy_mips.h
@@ -56,6 +56,8 @@
 #ifndef AVCODEC_MIPS_AACPSY_MIPS_H
 #define AVCODEC_MIPS_AACPSY_MIPS_H
 
+#include "libavutil/mips/asmdefs.h"
+
 #if HAVE_INLINE_ASM && HAVE_MIPSFPU && ( PSY_LAME_FIR_LEN == 21 )
 static void calc_thr_3gpp_mips(const FFPsyWindowInfo *wi, const int num_bands,
                                AacPsyChannel *pch, const uint8_t *band_sizes,
@@ -185,7 +187,7 @@
         "madd.s %[sum1],    %[sum1],    $f8,    %[coeff3]   \n\t"
         "madd.s %[sum2],    %[sum2],    $f11,   %[coeff3]   \n\t"
         "lwc1   $f1,        36(%[fb])                       \n\t"
-        "addiu  %[fb],      %[fb],      16                  \n\t"
+        PTR_ADDIU "%[fb],   %[fb],      16                  \n\t"
         "madd.s %[sum4],    %[sum4],    $f0,    %[coeff3]   \n\t"
         "madd.s %[sum3],    %[sum3],    $f1,    %[coeff3]   \n\t"
         "madd.s %[sum1],    %[sum1],    $f1,    %[coeff4]   \n\t"
@@ -207,7 +209,7 @@
         "swc1   %[sum4],    12(%[hp])                       \n\t"
         "swc1   %[sum3],    8(%[hp])                        \n\t"
         "bne    %[fb],      %[fb_end],  1b                  \n\t"
-        " addiu %[hp],      %[hp],      16                  \n\t"
+        PTR_ADDIU "%[hp],   %[hp],      16                  \n\t"
 
         ".set pop                                           \n\t"
 
diff --git a/libavcodec/mips/aacsbr_mips.c b/libavcodec/mips/aacsbr_mips.c
index 53a5fd0..e478290 100644
--- a/libavcodec/mips/aacsbr_mips.c
+++ b/libavcodec/mips/aacsbr_mips.c
@@ -53,6 +53,7 @@
 
 #include "libavcodec/aac.h"
 #include "libavcodec/aacsbr.h"
+#include "libavutil/mips/asmdefs.h"
 
 #define ENVELOPE_ADJUSTMENT_OFFSET 2
 
@@ -81,9 +82,9 @@
         "sw     $0,            20(%[p_x1_low])          \n\t"
         "sw     $0,            24(%[p_x1_low])          \n\t"
         "sw     $0,            28(%[p_x1_low])          \n\t"
-        "addiu  %[p_x1_low],   %[p_x1_low],      32     \n\t"
+        PTR_ADDIU "%[p_x1_low],%[p_x1_low],      32     \n\t"
         "bne    %[p_x1_low],   %[loop_end],      1b     \n\t"
-        "addiu  %[p_x1_low],   %[p_x1_low],      -10240 \n\t"
+        PTR_ADDIU "%[p_x1_low],%[p_x1_low],      -10240 \n\t"
 
         : [p_x1_low]"+r"(p_x1_low)
         : [loop_end]"r"(loop_end)
@@ -110,8 +111,8 @@
                 "sw     %[temp5],   20(%[p_x_low])          \n\t"
                 "sw     %[temp6],   24(%[p_x_low])          \n\t"
                 "sw     %[temp7],   28(%[p_x_low])          \n\t"
-                "addiu  %[p_x_low], %[p_x_low],     32      \n\t"
-                "addiu  %[p_w],     %[p_w],         1024    \n\t"
+                PTR_ADDIU "%[p_x_low], %[p_x_low],  32      \n\t"
+                PTR_ADDIU "%[p_w],     %[p_w],      1024    \n\t"
 
                 : [temp0]"=&r"(temp0), [temp1]"=&r"(temp1),
                   [temp2]"=&r"(temp2), [temp3]"=&r"(temp3),
@@ -147,8 +148,8 @@
                 "sw     %[temp5],    20(%[p_x1_low])        \n\t"
                 "sw     %[temp6],    24(%[p_x1_low])        \n\t"
                 "sw     %[temp7],    28(%[p_x1_low])        \n\t"
-                "addiu  %[p_x1_low], %[p_x1_low],   32      \n\t"
-                "addiu  %[p_w1],     %[p_w1],       1024    \n\t"
+                PTR_ADDIU "%[p_x1_low], %[p_x1_low], 32     \n\t"
+                PTR_ADDIU "%[p_w1],     %[p_w1],     1024   \n\t"
 
                 : [temp0]"=&r"(temp0), [temp1]"=&r"(temp1),
                   [temp2]"=&r"(temp2), [temp3]"=&r"(temp3),
@@ -188,9 +189,9 @@
         "sw     $0,      20(%[x1])            \n\t"
         "sw     $0,      24(%[x1])            \n\t"
         "sw     $0,      28(%[x1])            \n\t"
-        "addiu  %[x1],   %[x1],      32       \n\t"
+        PTR_ADDIU "%[x1],%[x1],      32       \n\t"
         "bne    %[x1],   %[j],       1b       \n\t"
-        "addiu  %[x1],   %[x1],      -19456   \n\t"
+        PTR_ADDIU "%[x1],%[x1],      -19456   \n\t"
 
         : [x1]"+r"(x1)
         : [j]"r"(j)
@@ -210,8 +211,8 @@
                 "lw      %[temp1],    4(%[X_low1])           \n\t"
                 "sw      %[temp0],    0(%[x1])               \n\t"
                 "sw      %[temp1],    9728(%[x1])            \n\t"
-                "addiu   %[x1],       %[x1],         256     \n\t"
-                "addiu   %[X_low1],   %[X_low1],     8       \n\t"
+                PTR_ADDIU "%[x1],     %[x1],         256     \n\t"
+                PTR_ADDIU "%[X_low1], %[X_low1],     8       \n\t"
                 "addiu   %[i],        %[i],          1       \n\t"
                 "bne     %[i],        %[i_Temp],     2b      \n\t"
 
@@ -235,8 +236,8 @@
                 "lw      %[temp1],   4(%[Y01])           \n\t"
                 "sw      %[temp0],   0(%[x1])            \n\t"
                 "sw      %[temp1],   9728(%[x1])         \n\t"
-                "addiu   %[x1],      %[x1],      256     \n\t"
-                "addiu   %[Y01],     %[Y01],     512     \n\t"
+                PTR_ADDIU "%[x1],    %[x1],      256     \n\t"
+                PTR_ADDIU "%[Y01],   %[Y01],     512     \n\t"
                 "addiu   %[i],       %[i],       1       \n\t"
                 "bne     %[i],       %[i_Temp],  3b      \n\t"
 
@@ -263,8 +264,8 @@
             "lw      %[temp1],   4(%[X_low1])           \n\t"
             "sw      %[temp0],   0(%[x1])               \n\t"
             "sw      %[temp1],   9728(%[x1])            \n\t"
-            "addiu   %[x1],      %[x1],         256     \n\t"
-            "addiu   %[X_low1],  %[X_low1],     8       \n\t"
+            PTR_ADDIU "%[x1],    %[x1],         256     \n\t"
+            PTR_ADDIU "%[X_low1],%[X_low1],     8       \n\t"
             "addiu   %[i],       %[i],          1       \n\t"
             "bne     %[i],       %[temp3],      4b      \n\t"
 
@@ -291,8 +292,8 @@
            "lw      %[temp1],   4(%[Y11])               \n\t"
            "sw      %[temp0],   0(%[x1])                \n\t"
            "sw      %[temp1],   9728(%[x1])             \n\t"
-           "addiu   %[x1],      %[x1],          256     \n\t"
-           "addiu   %[Y11],     %[Y11],         512     \n\t"
+           PTR_ADDIU "%[x1],    %[x1],          256     \n\t"
+           PTR_ADDIU "%[Y11],   %[Y11],         512     \n\t"
            "addiu   %[i],       %[i],           1       \n\t"
            "bne     %[i],       %[temp2],       5b      \n\t"
 
@@ -370,10 +371,10 @@
                     "sw      %[temp2],   4(%[q_temp1])           \n\t"
                     "sw      %[temp3],   8(%[q_temp1])           \n\t"
                     "sw      %[temp4],   12(%[q_temp1])          \n\t"
-                    "addiu   %[pok],     %[pok],           16    \n\t"
-                    "addiu   %[g_temp1], %[g_temp1],       16    \n\t"
-                    "addiu   %[pok1],    %[pok1],          16    \n\t"
-                    "addiu   %[q_temp1], %[q_temp1],       16    \n\t"
+                    PTR_ADDIU "%[pok],     %[pok],         16    \n\t"
+                    PTR_ADDIU "%[g_temp1], %[g_temp1],     16    \n\t"
+                    PTR_ADDIU "%[pok1],    %[pok1],        16    \n\t"
+                    PTR_ADDIU "%[q_temp1], %[q_temp1],     16    \n\t"
 
                     : [temp1]"=&r"(temp1), [temp2]"=&r"(temp2),
                       [temp3]"=&r"(temp3), [temp4]"=&r"(temp4),
@@ -390,10 +391,10 @@
                     "lw      %[temp2],   0(%[pok1])             \n\t"
                     "sw      %[temp1],   0(%[g_temp1])          \n\t"
                     "sw      %[temp2],   0(%[q_temp1])          \n\t"
-                    "addiu   %[pok],     %[pok],          4     \n\t"
-                    "addiu   %[g_temp1], %[g_temp1],      4     \n\t"
-                    "addiu   %[pok1],    %[pok1],         4     \n\t"
-                    "addiu   %[q_temp1], %[q_temp1],      4     \n\t"
+                    PTR_ADDIU "%[pok],     %[pok],        4     \n\t"
+                    PTR_ADDIU "%[g_temp1], %[g_temp1],    4     \n\t"
+                    PTR_ADDIU "%[pok1],    %[pok1],       4     \n\t"
+                    PTR_ADDIU "%[q_temp1], %[q_temp1],    4     \n\t"
 
                     : [temp1]"=&r"(temp1), [temp2]"=&r"(temp2),
                       [temp3]"=&r"(temp3), [temp4]"=&r"(temp4),
@@ -460,8 +461,8 @@
                         "madd.s  %[temp5],  %[temp3],  %[temp1], %[B_f]  \n\t"
                         "swc1    %[temp4],  0(%[out])                    \n\t"
                         "swc1    %[temp5],  8(%[out])                    \n\t"
-                        "addiu   %[in],     %[in],     8                 \n\t"
-                        "addiu   %[out],    %[out],    16                \n\t"
+                        PTR_ADDIU "%[in],   %[in],     8                 \n\t"
+                        PTR_ADDIU "%[out],  %[out],    16                \n\t"
 
                         : [temp0]"=&f" (temp0), [temp1]"=&f"(temp1),
                           [temp4]"=&f" (temp4), [temp5]"=&f"(temp5),
diff --git a/libavcodec/mips/aacsbr_mips.h b/libavcodec/mips/aacsbr_mips.h
index 8e6ad7d..da8389f 100644
--- a/libavcodec/mips/aacsbr_mips.h
+++ b/libavcodec/mips/aacsbr_mips.h
@@ -56,6 +56,7 @@
 
 #include "libavcodec/aac.h"
 #include "libavcodec/sbr.h"
+#include "libavutil/mips/asmdefs.h"
 
 #if HAVE_INLINE_ASM
 static void sbr_qmf_analysis_mips(AVFloatDSPContext *fdsp, FFTContext *mdct,
@@ -89,8 +90,8 @@
             "sw      %[temp5],   20(%[w0])        \n\t"
             "sw      %[temp6],   24(%[w0])        \n\t"
             "sw      %[temp7],   28(%[w0])        \n\t"
-            "addiu   %[w0],      %[w0],     32    \n\t"
-            "addiu   %[w1],      %[w1],     32    \n\t"
+            PTR_ADDIU " %[w0],      %[w0],     32 \n\t"
+            PTR_ADDIU " %[w1],      %[w1],     32 \n\t"
 
             : [w0]"+r"(w0), [w1]"+r"(w1),
               [temp0]"=&r"(temp0), [temp1]"=&r"(temp1),
@@ -124,8 +125,8 @@
             "sw       %[temp5],    20(%[w0])       \n\t"
             "sw       %[temp6],    24(%[w0])       \n\t"
             "sw       %[temp7],    28(%[w0])       \n\t"
-            "addiu    %[w0],       %[w0],     32   \n\t"
-            "addiu    %[w1],       %[w1],     32   \n\t"
+            PTR_ADDIU "  %[w0],       %[w0],    32 \n\t"
+            PTR_ADDIU "  %[w1],       %[w1],    32 \n\t"
 
             : [w0]"+r"(w0), [w1]"+r"(w1),
               [temp0]"=&r"(temp0), [temp1]"=&r"(temp1),
@@ -298,13 +299,13 @@
                 "lwc1    %[temp7],   2052(%[s0])                        \n\t"
                 "madd.s  %[temp0],   %[temp0],   %[temp12],  %[temp13]  \n\t"
                 "lwc1    %[temp8],   4104(%[v0])                        \n\t"
-                "addiu   %[dst],     %[dst],     16                     \n\t"
+                PTR_ADDIU "%[dst],     %[dst],      16                  \n\t"
                 "madd.s  %[temp1],   %[temp1],   %[temp14],  %[temp15]  \n\t"
                 "lwc1    %[temp9],   2056(%[s0])                        \n\t"
-                "addiu   %[s0],      %[s0],      16                     \n\t"
+                PTR_ADDIU " %[s0],      %[s0],      16                  \n\t"
                 "madd.s  %[temp2],   %[temp2],   %[temp16],  %[temp17]  \n\t"
                 "lwc1    %[temp10],  4108(%[v0])                        \n\t"
-                "addiu   %[v0],      %[v0],      16                     \n\t"
+                PTR_ADDIU " %[v0],      %[v0],      16                  \n\t"
                 "madd.s  %[temp3],   %[temp3],   %[temp18],  %[temp19]  \n\t"
                 "lwc1    %[temp11],  2044(%[s0])                        \n\t"
                 "lwc1    %[temp12],  4848(%[v0])                        \n\t"
@@ -445,7 +446,7 @@
                 "madd.s  %[temp3],   %[temp3],   %[temp10],  %[temp11]  \n\t"
                 "lwc1    %[temp19],  2316(%[s0])                        \n\t"
                 "madd.s  %[temp0],   %[temp0],   %[temp12],  %[temp13]  \n\t"
-                "addiu   %[dst],     %[dst],     16                     \n\t"
+                PTR_ADDIU "%[dst],     %[dst],     16                   \n\t"
                 "madd.s  %[temp1],   %[temp1],   %[temp14],  %[temp15]  \n\t"
                 "madd.s  %[temp2],   %[temp2],   %[temp16],  %[temp17]  \n\t"
                 "madd.s  %[temp3],   %[temp3],   %[temp18],  %[temp19]  \n\t"
diff --git a/libavcodec/mips/ac3dsp_mips.c b/libavcodec/mips/ac3dsp_mips.c
index f33c6f1..01c7de5 100644
--- a/libavcodec/mips/ac3dsp_mips.c
+++ b/libavcodec/mips/ac3dsp_mips.c
@@ -56,7 +56,7 @@
 #include "config.h"
 #include "libavcodec/ac3dsp.h"
 #include "libavcodec/ac3.h"
-
+#include "libavutil/mips/asmdefs.h"
 
 #if HAVE_INLINE_ASM
 #if HAVE_MIPSDSPR1
@@ -91,7 +91,7 @@
             "2:                                                     \n\t"
             "lh         %[address1],    0(%[psd1])                  \n\t"
             "lh         %[address2],    2(%[psd1])                  \n\t"
-            "addiu      %[psd1],        %[psd1],        4           \n\t"
+            PTR_ADDIU " %[psd1],        %[psd1],        4           \n\t"
             "subu       %[address1],    %[address1],    %[m]        \n\t"
             "sra        %[address1],    %[address1],    5           \n\t"
             "addiu      %[address1],    %[address1],    -32         \n\t"
@@ -109,14 +109,14 @@
             "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"
+            PTR_ADDIU " %[bap1],        %[bap1],        2           \n\t"
             "bnez       %[cond],        2b                          \n\t"
-            "addiu      %[psd_end],     %[psd_end],     2           \n\t"
+            PTR_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"
+            PTR_ADDIU " %[psd1],        %[psd1],        2           \n\t"
             "subu       %[address1],    %[address1],    %[m]        \n\t"
             "sra        %[address1],    %[address1],    5           \n\t"
             "addiu      %[address1],    %[address1],    -32         \n\t"
@@ -125,7 +125,7 @@
             "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"
+            PTR_ADDIU " %[bap1],        %[bap1],        1           \n\t"
             "3:                                                     \n\t"
 
             : [address1]"=&r"(address1), [address2]"=&r"(address2),
@@ -140,34 +140,35 @@
 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;
+    void *temp0, *temp2, *temp4, *temp5, *temp6, *temp7;
+    int temp1, temp3;
 
     __asm__ volatile (
         "andi   %[temp3],   %[len],         3               \n\t"
-        "addu   %[temp2],   %[bap],         %[len]          \n\t"
-        "addu   %[temp4],   %[bap],         %[temp3]        \n\t"
+        PTR_ADDU "%[temp2], %[bap],         %[len]          \n\t"
+        PTR_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"
+        PTR_ADDU "%[temp0], %[mant_cnt],    %[temp0]        \n\t"
         "sll    %[temp5],   %[temp5],       1               \n\t"
-        "addu   %[temp5],   %[mant_cnt],    %[temp5]        \n\t"
+        PTR_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"
+        PTR_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"
+        PTR_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"
+        PTR_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"
@@ -179,9 +180,9 @@
         "3:                                                 \n\t"
         "addiu  %[temp3],   %[temp3],       -1              \n\t"
         "lbu    %[temp0],   -1(%[temp2])                    \n\t"
-        "addiu  %[temp2],   %[temp2],       -1              \n\t"
+        PTR_ADDIU "%[temp2],%[temp2],       -1              \n\t"
         "sll    %[temp0],   %[temp0],       1               \n\t"
-        "addu   %[temp0],   %[mant_cnt],    %[temp0]        \n\t"
+        PTR_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"
@@ -199,7 +200,7 @@
 }
 #endif
 
-#if HAVE_MIPSFPU && HAVE_MIPS32R2
+#if HAVE_MIPSFPU
 static void float_to_fixed24_mips(int32_t *dst, const float *src, unsigned int len)
 {
     const float scale = 1 << 24;
@@ -274,7 +275,7 @@
     float v0, v1, v2, v3;
     float v4, v5, v6, v7;
     float samples0, samples1, samples2, samples3, matrix_j, matrix_j2;
-    float *samples_p,*matrix_p, **samples_x, **samples_end, **samples_sw;
+    float *samples_p, *samples_sw, *matrix_p, **samples_x, **samples_end;
 
     __asm__ volatile(
         ".set   push                                                \n\t"
@@ -283,7 +284,7 @@
         "li     %[i1],          2                                   \n\t"
         "sll    %[len],         2                                   \n\t"
         "move   %[i],           $zero                               \n\t"
-        "sll    %[j],           %[in_ch],               2           \n\t"
+        "sll    %[j],           %[in_ch],             " PTRLOG "    \n\t"
 
         "bne    %[out_ch],      %[i1],                  3f          \n\t"   // if (out_ch == 2)
         " li    %[i2],          1                                   \n\t"
@@ -301,9 +302,9 @@
         "mtc1   $zero,          %[v7]                               \n\t"
         "addiu  %[i1],          %[i],                  4            \n\t"
         "addiu  %[i2],          %[i],                  8            \n\t"
-        "lw     %[samples_p],   0(%[samples_x])                     \n\t"
+        PTR_L " %[samples_p],   0(%[samples_x])                     \n\t"
         "addiu  %[i3],          %[i],                  12           \n\t"
-        "addu   %[samples_end], %[samples_x],          %[j]         \n\t"
+        PTR_ADDU "%[samples_end],%[samples_x],         %[j]         \n\t"
         "move   %[samples_sw],  %[samples_p]                        \n\t"
 
         "1:                                                         \n\t"   // start of the inner for loop (for (j = 0; j < in_ch; j++))
@@ -313,8 +314,8 @@
         "lwxc1  %[samples1],    %[i1](%[samples_p])                 \n\t"
         "lwxc1  %[samples2],    %[i2](%[samples_p])                 \n\t"
         "lwxc1  %[samples3],    %[i3](%[samples_p])                 \n\t"
-        "addiu  %[matrix_p],    8                                   \n\t"
-        "addiu  %[samples_x],   4                                   \n\t"
+        PTR_ADDIU "%[matrix_p], 8                                   \n\t"
+        PTR_ADDIU "%[samples_x]," PTRSIZE "                         \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"
@@ -324,9 +325,9 @@
         "madd.s %[v6],          %[v6],  %[samples2],    %[matrix_j2]\n\t"
         "madd.s %[v7],          %[v7],  %[samples3],    %[matrix_j2]\n\t"
         "bne    %[samples_x],   %[samples_end],         1b          \n\t"
-        " lw    %[samples_p],   0(%[samples_x])                     \n\t"
+        PTR_L " %[samples_p],   0(%[samples_x])                     \n\t"
 
-        "lw     %[samples_p],   4(%[samples])                       \n\t"
+        PTR_L " %[samples_p],  " PTRSIZE "(%[samples])              \n\t"
         "swxc1  %[v0],          %[i](%[samples_sw])                 \n\t"
         "swxc1  %[v1],          %[i1](%[samples_sw])                \n\t"
         "swxc1  %[v2],          %[i2](%[samples_sw])                \n\t"
@@ -351,9 +352,9 @@
         "mtc1   $zero,          %[v3]                               \n\t"
         "addiu  %[i1],          %[i],                  4            \n\t"
         "addiu  %[i2],          %[i],                  8            \n\t"
-        "lw     %[samples_p],   0(%[samples_x])                     \n\t"
+        PTR_L " %[samples_p],   0(%[samples_x])                     \n\t"
         "addiu  %[i3],          %[i],                  12           \n\t"
-        "addu   %[samples_end], %[samples_x],          %[j]         \n\t"
+        PTR_ADDU "%[samples_end],%[samples_x],         %[j]         \n\t"
         "move   %[samples_sw],  %[samples_p]                        \n\t"
 
         "4:                                                         \n\t"   // start of the inner for loop (for (j = 0; j < in_ch; j++))
@@ -362,14 +363,14 @@
         "lwxc1  %[samples1],    %[i1](%[samples_p])                 \n\t"
         "lwxc1  %[samples2],    %[i2](%[samples_p])                 \n\t"
         "lwxc1  %[samples3],    %[i3](%[samples_p])                 \n\t"
-        "addiu  %[matrix_p],    8                                   \n\t"
-        "addiu  %[samples_x],   4                                   \n\t"
+        PTR_ADDIU "%[matrix_p], 8                                   \n\t"
+        PTR_ADDIU "%[samples_x]," PTRSIZE "                         \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"
         "bne    %[samples_x],   %[samples_end],         4b          \n\t"
-        " lw    %[samples_p],   0(%[samples_x])                     \n\t"
+        PTR_L " %[samples_p],   0(%[samples_x])                     \n\t"
 
         "swxc1  %[v0],          %[i](%[samples_sw])                 \n\t"
         "addiu  %[i],           16                                  \n\t"
@@ -403,7 +404,7 @@
     c->bit_alloc_calc_bap = ac3_bit_alloc_calc_bap_mips;
     c->update_bap_counts  = ac3_update_bap_counts_mips;
 #endif
-#if HAVE_MIPSFPU && HAVE_MIPS32R2
+#if HAVE_MIPSFPU
     c->float_to_fixed24 = float_to_fixed24_mips;
     c->downmix          = ac3_downmix_mips;
 #endif
diff --git a/libavcodec/mips/acelp_filters_mips.c b/libavcodec/mips/acelp_filters_mips.c
index c8d980a..ba789ab 100644
--- a/libavcodec/mips/acelp_filters_mips.c
+++ b/libavcodec/mips/acelp_filters_mips.c
@@ -54,6 +54,7 @@
 #include "config.h"
 #include "libavutil/attributes.h"
 #include "libavcodec/acelp_filters.h"
+#include "libavutil/mips/asmdefs.h"
 
 #if HAVE_INLINE_ASM
 static void ff_acelp_interpolatef_mips(float *out, const float *in,
@@ -82,14 +83,14 @@
                 "lwc1   %[fc_val_p],           0(%[p_filter_coeffs_p])         \n\t"
                 "lwc1   %[in_val_m],           0(%[p_in_m])                    \n\t"
                 "lwc1   %[fc_val_m],           0(%[p_filter_coeffs_m])         \n\t"
-                "addiu  %[p_in_p],             %[p_in_p],              4       \n\t"
+                PTR_ADDIU "%[p_in_p],          %[p_in_p],              4       \n\t"
                 "madd.s %[v],%[v],             %[in_val_p],%[fc_val_p]         \n\t"
-                "addiu  %[p_in_m],             %[p_in_m],              -4      \n\t"
-                "addu   %[p_filter_coeffs_p],  %[p_filter_coeffs_p],   %[prec] \n\t"
-                "addu   %[p_filter_coeffs_m],  %[p_filter_coeffs_m],   %[prec] \n\t"
+                PTR_ADDIU "%[p_in_m],          %[p_in_m],              -4      \n\t"
+                PTR_ADDU "%[p_filter_coeffs_p],%[p_filter_coeffs_p],   %[prec] \n\t"
+                PTR_ADDU "%[p_filter_coeffs_m],%[p_filter_coeffs_m],   %[prec] \n\t"
                 "madd.s %[v],%[v],%[in_val_m], %[fc_val_m]                     \n\t"
 
-                : [v] "=&f" (v),[p_in_p] "+r" (p_in_p), [p_in_m] "+r" (p_in_m),
+                : [v] "+&f" (v),[p_in_p] "+r" (p_in_p), [p_in_m] "+r" (p_in_m),
                   [p_filter_coeffs_p] "+r" (p_filter_coeffs_p),
                   [in_val_p] "=&f" (in_val_p), [in_val_m] "=&f" (in_val_m),
                   [fc_val_p] "=&f" (fc_val_p), [fc_val_m] "=&f" (fc_val_m),
@@ -185,8 +186,8 @@
         "madd.s $f14,   $f0,      $f4,     $f1                                 \n\t"
         "madd.s $f14,   $f14,     $f5,     $f13                                \n\t"
         "swc1   $f8,    24(%[out])                                             \n\t"
-        "addiu  %[out], 32                                                     \n\t"
-        "addiu  %[in],  32                                                     \n\t"
+        PTR_ADDIU "%[out], 32                                                  \n\t"
+        PTR_ADDIU "%[in],  32                                                  \n\t"
         "addiu  %[n],   -8                                                     \n\t"
         "swc1   $f14,   -4(%[out])                                             \n\t"
         "bnez   %[n],   ff_acelp_apply_order_2_transfer_function_madd%=        \n\t"
diff --git a/libavcodec/mips/acelp_vectors_mips.c b/libavcodec/mips/acelp_vectors_mips.c
index 8770df8..ad94348 100644
--- a/libavcodec/mips/acelp_vectors_mips.c
+++ b/libavcodec/mips/acelp_vectors_mips.c
@@ -54,6 +54,7 @@
  */
 #include "config.h"
 #include "libavcodec/acelp_vectors.h"
+#include "libavutil/mips/asmdefs.h"
 
 #if HAVE_INLINE_ASM
 static void ff_weighted_vector_sumf_mips(
@@ -75,11 +76,11 @@
         "mul.s  $f5,       %[weight_coeff_a], $f3                            \n\t"
         "madd.s $f2,       $f2,               %[weight_coeff_b], $f1         \n\t"
         "madd.s $f5,       $f5,               %[weight_coeff_b], $f4         \n\t"
-        "addiu  %[in_a],   8                                                 \n\t"
-        "addiu  %[in_b],   8                                                 \n\t"
+        PTR_ADDIU "%[in_a],8                                                 \n\t"
+        PTR_ADDIU "%[in_b],8                                                 \n\t"
         "swc1   $f2,       0(%[out])                                         \n\t"
         "swc1   $f5,       4(%[out])                                         \n\t"
-        "addiu  %[out],    8                                                 \n\t"
+        PTR_ADDIU "%[out], 8                                                 \n\t"
         "bne   %[in_a],    %[a_end],          ff_weighted_vector_sumf_madd%= \n\t"
 
         "ff_weighted_vector_sumf_end%=:                                      \n\t"
diff --git a/libavcodec/mips/celp_filters_mips.c b/libavcodec/mips/celp_filters_mips.c
index ef5b07b..88ac458 100644
--- a/libavcodec/mips/celp_filters_mips.c
+++ b/libavcodec/mips/celp_filters_mips.c
@@ -55,6 +55,7 @@
 #include "libavutil/attributes.h"
 #include "libavutil/common.h"
 #include "libavcodec/celp_filters.h"
+#include "libavutil/mips/asmdefs.h"
 
 #if HAVE_INLINE_ASM
 static void ff_celp_lp_synthesis_filterf_mips(float *out,
@@ -118,8 +119,8 @@
             __asm__ volatile(
                 "lwc1    %[old_out3], -20(%[p_out])                         \n\t"
                 "lwc1    $f5,         16(%[p_filter_coeffs])                \n\t"
-                "addiu   %[p_out],    -8                                    \n\t"
-                "addiu   %[p_filter_coeffs], 8                              \n\t"
+                PTR_ADDIU "%[p_out],  -8                                    \n\t"
+                PTR_ADDIU "%[p_filter_coeffs], 8                            \n\t"
                 "nmsub.s %[out1],     %[out1],      $f5, %[old_out0]        \n\t"
                 "nmsub.s %[out3],     %[out3],      $f5, %[old_out2]        \n\t"
                 "lwc1    $f4,         12(%[p_filter_coeffs])                \n\t"
@@ -181,8 +182,8 @@
             __asm__ volatile(
                 "lwc1    %[fc_val],          0(%[p_filter_coeffs])                        \n\t"
                 "lwc1    %[out_val_i],       -4(%[p_out])                                 \n\t"
-                "addiu   %[p_filter_coeffs], 4                                            \n\t"
-                "addiu   %[p_out],           -4                                           \n\t"
+                PTR_ADDIU "%[p_filter_coeffs], 4                                          \n\t"
+                PTR_ADDIU "%[p_out],         -4                                           \n\t"
                 "nmsub.s %[out_val],         %[out_val],          %[fc_val], %[out_val_i] \n\t"
 
                 : [fc_val]"=&f"(fc_val), [out_val]"+f"(out_val),
@@ -245,8 +246,8 @@
             "madd.s %[sum_out1], %[sum_out1],          %[fc_val], $f0       \n\t"
             "lwc1   %[fc_val],   4(%[p_filter_coeffs])                      \n\t"
             "lwc1   $f7,         -8(%[p_in])                                \n\t"
-            "addiu  %[p_filter_coeffs], 8                                   \n\t"
-            "addiu  %[p_in],     -8                                         \n\t"
+            PTR_ADDIU "%[p_filter_coeffs], 8                                \n\t"
+            PTR_ADDIU "%[p_in],  -8                                         \n\t"
             "madd.s %[sum_out8], %[sum_out8],          %[fc_val], $f6       \n\t"
             "madd.s %[sum_out7], %[sum_out7],          %[fc_val], $f5       \n\t"
             "madd.s %[sum_out6], %[sum_out6],          %[fc_val], $f4       \n\t"
diff --git a/libavcodec/mips/celp_math_mips.c b/libavcodec/mips/celp_math_mips.c
index d7ccc23..008dd80 100644
--- a/libavcodec/mips/celp_math_mips.c
+++ b/libavcodec/mips/celp_math_mips.c
@@ -53,6 +53,7 @@
  */
 #include "config.h"
 #include "libavcodec/celp_math.h"
+#include "libavutil/mips/asmdefs.h"
 
 #if HAVE_INLINE_ASM
 static float ff_dot_productf_mips(const float* a, const float* b,
@@ -67,8 +68,8 @@
         "ff_dot_productf_madd%=:                                \n\t"
         "lwc1   $f2,        0(%[a])                             \n\t"
         "lwc1   $f1,        0(%[b])                             \n\t"
-        "addiu  %[a],       %[a],      4                        \n\t"
-        "addiu  %[b],       %[b],      4                        \n\t"
+        PTR_ADDIU "%[a],    %[a],      4                        \n\t"
+        PTR_ADDIU "%[b],    %[b],      4                        \n\t"
         "madd.s %[sum],     %[sum],    $f1, $f2                 \n\t"
         "bne   %[a],        %[a_end],  ff_dot_productf_madd%=   \n\t"
         "ff_dot_productf_end%=:                                 \n\t"
diff --git a/libavcodec/mips/compute_antialias_float.h b/libavcodec/mips/compute_antialias_float.h
index e84abda..f6cf465 100644
--- a/libavcodec/mips/compute_antialias_float.h
+++ b/libavcodec/mips/compute_antialias_float.h
@@ -55,6 +55,8 @@
 #ifndef AVCODEC_MIPS_COMPUTE_ANTIALIAS_FLOAT_H
 #define AVCODEC_MIPS_COMPUTE_ANTIALIAS_FLOAT_H
 
+#include "libavutil/mips/asmdefs.h"
+
 #if HAVE_INLINE_ASM
 static void compute_antialias_mips_float(MPADecodeContext *s,
                                         GranuleDef *g)
@@ -158,7 +160,7 @@
         "mul.s   %[out4], %[in5],  %[in7]                               \t\n"
         "swc1    %[out1], -7*4(%[ptr])                                  \t\n"
         "swc1    %[out2], 6*4(%[ptr])                                   \t\n"
-        "addiu   %[ptr],  %[ptr],  72                                   \t\n"
+        PTR_ADDIU "%[ptr],%[ptr],  72                                   \t\n"
         "nmsub.s %[out3], %[out3], %[in7], %[in8]                       \t\n"
         "madd.s  %[out4], %[out4], %[in6], %[in8]                       \t\n"
         "swc1    %[out3], -26*4(%[ptr])                                 \t\n"
diff --git a/libavcodec/mips/fft_mips.c b/libavcodec/mips/fft_mips.c
index 691f2db..cf008c6 100644
--- a/libavcodec/mips/fft_mips.c
+++ b/libavcodec/mips/fft_mips.c
@@ -50,6 +50,7 @@
 #include "config.h"
 #include "libavcodec/fft.h"
 #include "libavcodec/fft_table.h"
+#include "libavutil/mips/asmdefs.h"
 
 /**
  * FFT transform
@@ -65,26 +66,12 @@
     float w_re, w_im;
     float *w_re_ptr, *w_im_ptr;
     const int fft_size = (1 << s->nbits);
-    int s_n = s->nbits;
-    int tem1, tem2;
     float pom,  pom1,  pom2,  pom3;
     float temp, temp1, temp3, temp4;
     FFTComplex * tmpz_n2, * tmpz_n34, * tmpz_n4;
     FFTComplex * tmpz_n2_i, * tmpz_n34_i, * tmpz_n4_i, * tmpz_i;
 
-    /**
-    *num_transforms = (0x2aab >> (16 - s->nbits)) | 1;
-    */
-    __asm__ volatile (
-        "li   %[tem1], 16                                      \n\t"
-        "sub  %[s_n],  %[tem1], %[s_n]                         \n\t"
-        "li   %[tem2], 10923                                   \n\t"
-        "srav %[tem2], %[tem2], %[s_n]                         \n\t"
-        "ori  %[num_t],%[tem2], 1                              \n\t"
-        : [num_t]"=r"(num_transforms), [s_n]"+r"(s_n),
-          [tem1]"=&r"(tem1), [tem2]"=&r"(tem2)
-    );
-
+    num_transforms = (0x2aab >> (16 - s->nbits)) | 1;
 
     for (n=0; n<num_transforms; n++) {
         offset = ff_fft_offsets_lut[n] << 2;
@@ -214,15 +201,7 @@
     n4 = 4;
 
     for (nbits=4; nbits<=s->nbits; nbits++) {
-        /*
-        * num_transforms = (num_transforms >> 1) | 1;
-        */
-        __asm__ volatile (
-            "sra %[num_t], %[num_t], 1               \n\t"
-            "ori %[num_t], %[num_t], 1               \n\t"
-
-            : [num_t] "+r" (num_transforms)
-        );
+        num_transforms = (num_transforms >> 1) | 1;
         n2  = 2 * n4;
         n34 = 3 * n4;
 
@@ -390,14 +369,14 @@
             "mul.s          %[temp11],      %[temp5],   %[temp6]                \t\n"
             "mul.s          %[temp12],      %[temp5],   %[temp7]                \t\n"
             "lwc1           %[temp8],       0(%[in3])                           \t\n"
-            "addiu          %[tcos1],       %[tcos1],   8                       \t\n"
-            "addiu          %[tsin1],       %[tsin1],   8                       \t\n"
-            "addiu          %[in1],         %[in1],     16                      \t\n"
+            PTR_ADDIU "     %[tcos1],       %[tcos1],   8                       \t\n"
+            PTR_ADDIU "     %[tsin1],       %[tsin1],   8                       \t\n"
+            PTR_ADDIU "     %[in1],         %[in1],     16                      \t\n"
             "nmsub.s        %[temp11],      %[temp11],  %[temp8],   %[temp7]    \t\n"
             "madd.s         %[temp12],      %[temp12],  %[temp8],   %[temp6]    \t\n"
-            "addiu          %[in2],         %[in2],     -16                     \t\n"
-            "addiu          %[in3],         %[in3],     16                      \t\n"
-            "addiu          %[in4],         %[in4],     -16                     \t\n"
+            PTR_ADDIU "     %[in2],         %[in2],     -16                     \t\n"
+            PTR_ADDIU "     %[in3],         %[in3],     16                      \t\n"
+            PTR_ADDIU "     %[in4],         %[in4],     -16                     \t\n"
 
             : [temp1]"=&f"(temp1), [temp2]"=&f"(temp2),
               [temp3]"=&f"(temp3), [temp4]"=&f"(temp4),
diff --git a/libavcodec/mips/fmtconvert_mips.c b/libavcodec/mips/fmtconvert_mips.c
index 8a0265f..9909584 100644
--- a/libavcodec/mips/fmtconvert_mips.c
+++ b/libavcodec/mips/fmtconvert_mips.c
@@ -50,206 +50,9 @@
 #include "config.h"
 #include "libavcodec/avcodec.h"
 #include "libavcodec/fmtconvert.h"
+#include "libavutil/mips/asmdefs.h"
 
 #if HAVE_INLINE_ASM
-#if HAVE_MIPSDSPR1
-static void float_to_int16_mips(int16_t *dst, const float *src, long len)
-{
-    const float *src_end = src + len;
-    int ret0, ret1, ret2, ret3, ret4, ret5, ret6, ret7;
-    float src0, src1, src2, src3, src4, src5, src6, src7;
-
-    /*
-     * loop is 8 times unrolled in assembler in order to achieve better performance
-     */
-    __asm__ volatile(
-        "beq        %[len],  $zero,   fti16_end%=   \n\t"
-        "fti16_lp%=:                                \n\t"
-        "lwc1       %[src0], 0(%[src])              \n\t"
-        "lwc1       %[src1], 4(%[src])              \n\t"
-        "lwc1       %[src2], 8(%[src])              \n\t"
-        "lwc1       %[src3], 12(%[src])             \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"
-        "mfc1       %[ret0], %[src0]                \n\t"
-        "mfc1       %[ret1], %[src1]                \n\t"
-        "mfc1       %[ret2], %[src2]                \n\t"
-        "mfc1       %[ret3], %[src3]                \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"
-        "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"
-        "addiu      %[src],  32                     \n\t"
-        "shll_s.w   %[ret0], %[ret0], 16            \n\t"
-        "shll_s.w   %[ret1], %[ret1], 16            \n\t"
-        "shll_s.w   %[ret2], %[ret2], 16            \n\t"
-        "shll_s.w   %[ret3], %[ret3], 16            \n\t"
-        "srl        %[ret0], %[ret0], 16            \n\t"
-        "srl        %[ret1], %[ret1], 16            \n\t"
-        "srl        %[ret2], %[ret2], 16            \n\t"
-        "srl        %[ret3], %[ret3], 16            \n\t"
-        "sh         %[ret0], 0(%[dst])              \n\t"
-        "sh         %[ret1], 2(%[dst])              \n\t"
-        "sh         %[ret2], 4(%[dst])              \n\t"
-        "sh         %[ret3], 6(%[dst])              \n\t"
-        "mfc1       %[ret4], %[src4]                \n\t"
-        "mfc1       %[ret5], %[src5]                \n\t"
-        "mfc1       %[ret6], %[src6]                \n\t"
-        "mfc1       %[ret7], %[src7]                \n\t"
-        "shll_s.w   %[ret4], %[ret4], 16            \n\t"
-        "shll_s.w   %[ret5], %[ret5], 16            \n\t"
-        "shll_s.w   %[ret6], %[ret6], 16            \n\t"
-        "shll_s.w   %[ret7], %[ret7], 16            \n\t"
-        "srl        %[ret4], %[ret4], 16            \n\t"
-        "srl        %[ret5], %[ret5], 16            \n\t"
-        "srl        %[ret6], %[ret6], 16            \n\t"
-        "srl        %[ret7], %[ret7], 16            \n\t"
-        "sh         %[ret4], 8(%[dst])              \n\t"
-        "sh         %[ret5], 10(%[dst])             \n\t"
-        "sh         %[ret6], 12(%[dst])             \n\t"
-        "sh         %[ret7], 14(%[dst])             \n\t"
-        "addiu      %[dst],  16                     \n\t"
-        "bne        %[src],  %[src_end], fti16_lp%= \n\t"
-        "fti16_end%=:                               \n\t"
-        : [ret0]"=&r"(ret0), [ret1]"=&r"(ret1), [ret2]"=&r"(ret2), [ret3]"=&r"(ret3),
-          [ret4]"=&r"(ret4), [ret5]"=&r"(ret5), [ret6]"=&r"(ret6), [ret7]"=&r"(ret7),
-          [src0]"=&f"(src0), [src1]"=&f"(src1), [src2]"=&f"(src2), [src3]"=&f"(src3),
-          [src4]"=&f"(src4), [src5]"=&f"(src5), [src6]"=&f"(src6), [src7]"=&f"(src7),
-          [src]"+r"(src), [dst]"+r"(dst)
-        : [src_end]"r"(src_end), [len]"r"(len)
-        : "memory"
-    );
-}
-
-static void float_to_int16_interleave_mips(int16_t *dst, const float **src, long len,
-        int channels)
-{
-    int   c, ch2 = channels <<1;
-    int ret0, ret1, ret2, ret3, ret4, ret5, ret6, ret7;
-    float src0, src1, src2, src3, src4, src5, src6, src7;
-    int16_t *dst_ptr0, *dst_ptr1, *dst_ptr2, *dst_ptr3;
-    int16_t *dst_ptr4, *dst_ptr5, *dst_ptr6, *dst_ptr7;
-    const float *src_ptr, *src_ptr2, *src_end;
-
-    if (channels == 2) {
-        src_ptr = &src[0][0];
-        src_ptr2 = &src[1][0];
-        src_end = src_ptr + len;
-
-        __asm__ volatile (
-            "fti16i2_lp%=:                                   \n\t"
-            "lwc1       %[src0],    0(%[src_ptr])            \n\t"
-            "lwc1       %[src1],    0(%[src_ptr2])           \n\t"
-            "addiu      %[src_ptr], 4                        \n\t"
-            "cvt.w.s    $f9,        %[src0]                  \n\t"
-            "cvt.w.s    $f10,       %[src1]                  \n\t"
-            "mfc1       %[ret0],    $f9                      \n\t"
-            "mfc1       %[ret1],    $f10                     \n\t"
-            "shll_s.w   %[ret0],    %[ret0], 16              \n\t"
-            "shll_s.w   %[ret1],    %[ret1], 16              \n\t"
-            "addiu      %[src_ptr2], 4                       \n\t"
-            "srl        %[ret0],    %[ret0], 16              \n\t"
-            "srl        %[ret1],    %[ret1], 16              \n\t"
-            "sh         %[ret0],    0(%[dst])                \n\t"
-            "sh         %[ret1],    2(%[dst])                \n\t"
-            "addiu      %[dst],     4                        \n\t"
-            "bne        %[src_ptr], %[src_end], fti16i2_lp%= \n\t"
-            : [ret0]"=&r"(ret0), [ret1]"=&r"(ret1),
-              [src0]"=&f"(src0), [src1]"=&f"(src1),
-              [src_ptr]"+r"(src_ptr), [src_ptr2]"+r"(src_ptr2),
-              [dst]"+r"(dst)
-            : [src_end]"r"(src_end)
-            : "memory"
-        );
-    } else {
-        for (c = 0; c < channels; c++) {
-            src_ptr  = &src[c][0];
-            dst_ptr0 = &dst[c];
-            src_end = src_ptr + len;
-            /*
-             * loop is 8 times unrolled in assembler in order to achieve better performance
-             */
-            __asm__ volatile(
-                "fti16i_lp%=:                                     \n\t"
-                "lwc1       %[src0], 0(%[src_ptr])                \n\t"
-                "lwc1       %[src1], 4(%[src_ptr])                \n\t"
-                "lwc1       %[src2], 8(%[src_ptr])                \n\t"
-                "lwc1       %[src3], 12(%[src_ptr])               \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"
-                "mfc1       %[ret0], %[src0]                      \n\t"
-                "mfc1       %[ret1], %[src1]                      \n\t"
-                "mfc1       %[ret2], %[src2]                      \n\t"
-                "mfc1       %[ret3], %[src3]                      \n\t"
-                "lwc1       %[src4], 16(%[src_ptr])               \n\t"
-                "lwc1       %[src5], 20(%[src_ptr])               \n\t"
-                "lwc1       %[src6], 24(%[src_ptr])               \n\t"
-                "lwc1       %[src7], 28(%[src_ptr])               \n\t"
-                "addu       %[dst_ptr1], %[dst_ptr0], %[ch2]      \n\t"
-                "addu       %[dst_ptr2], %[dst_ptr1], %[ch2]      \n\t"
-                "addu       %[dst_ptr3], %[dst_ptr2], %[ch2]      \n\t"
-                "addu       %[dst_ptr4], %[dst_ptr3], %[ch2]      \n\t"
-                "addu       %[dst_ptr5], %[dst_ptr4], %[ch2]      \n\t"
-                "addu       %[dst_ptr6], %[dst_ptr5], %[ch2]      \n\t"
-                "addu       %[dst_ptr7], %[dst_ptr6], %[ch2]      \n\t"
-                "addiu      %[src_ptr],  32                       \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"
-                "shll_s.w   %[ret0], %[ret0], 16                  \n\t"
-                "shll_s.w   %[ret1], %[ret1], 16                  \n\t"
-                "shll_s.w   %[ret2], %[ret2], 16                  \n\t"
-                "shll_s.w   %[ret3], %[ret3], 16                  \n\t"
-                "srl        %[ret0], %[ret0], 16                  \n\t"
-                "srl        %[ret1], %[ret1], 16                  \n\t"
-                "srl        %[ret2], %[ret2], 16                  \n\t"
-                "srl        %[ret3], %[ret3], 16                  \n\t"
-                "sh         %[ret0], 0(%[dst_ptr0])               \n\t"
-                "sh         %[ret1], 0(%[dst_ptr1])               \n\t"
-                "sh         %[ret2], 0(%[dst_ptr2])               \n\t"
-                "sh         %[ret3], 0(%[dst_ptr3])               \n\t"
-                "mfc1       %[ret4], %[src4]                      \n\t"
-                "mfc1       %[ret5], %[src5]                      \n\t"
-                "mfc1       %[ret6], %[src6]                      \n\t"
-                "mfc1       %[ret7], %[src7]                      \n\t"
-                "shll_s.w   %[ret4], %[ret4], 16                  \n\t"
-                "shll_s.w   %[ret5], %[ret5], 16                  \n\t"
-                "shll_s.w   %[ret6], %[ret6], 16                  \n\t"
-                "shll_s.w   %[ret7], %[ret7], 16                  \n\t"
-                "srl        %[ret4], %[ret4], 16                  \n\t"
-                "srl        %[ret5], %[ret5], 16                  \n\t"
-                "srl        %[ret6], %[ret6], 16                  \n\t"
-                "srl        %[ret7], %[ret7], 16                  \n\t"
-                "sh         %[ret4], 0(%[dst_ptr4])               \n\t"
-                "sh         %[ret5], 0(%[dst_ptr5])               \n\t"
-                "sh         %[ret6], 0(%[dst_ptr6])               \n\t"
-                "sh         %[ret7], 0(%[dst_ptr7])               \n\t"
-                "addu       %[dst_ptr0], %[dst_ptr7], %[ch2]      \n\t"
-                "bne        %[src_ptr],  %[src_end],  fti16i_lp%= \n\t"
-                : [ret0]"=&r"(ret0), [ret1]"=&r"(ret1), [ret2]"=&r"(ret2), [ret3]"=&r"(ret3),
-                  [ret4]"=&r"(ret4), [ret5]"=&r"(ret5), [ret6]"=&r"(ret6), [ret7]"=&r"(ret7),
-                  [src0]"=&f"(src0), [src1]"=&f"(src1), [src2]"=&f"(src2), [src3]"=&f"(src3),
-                  [src4]"=&f"(src4), [src5]"=&f"(src5), [src6]"=&f"(src6), [src7]"=&f"(src7),
-                  [dst_ptr1]"=&r"(dst_ptr1), [dst_ptr2]"=&r"(dst_ptr2), [dst_ptr3]"=&r"(dst_ptr3),
-                  [dst_ptr4]"=&r"(dst_ptr4), [dst_ptr5]"=&r"(dst_ptr5), [dst_ptr6]"=&r"(dst_ptr6),
-                  [dst_ptr7]"=&r"(dst_ptr7), [dst_ptr0]"+r"(dst_ptr0), [src_ptr]"+r"(src_ptr)
-                : [ch2]"r"(ch2), [src_end]"r"(src_end)
-                : "memory"
-            );
-        }
-    }
-}
-#endif /* HAVE_MIPSDSPR1 */
-
 static void int32_to_float_fmul_scalar_mips(float *dst, const int *src,
         float mul, int len)
 {
@@ -283,7 +86,7 @@
         "mtc1     %[rpom12],     %[temp13]              \n\t"
         "mtc1     %[rpom22],     %[temp15]              \n\t"
 
-        "addiu    %[src],        32                     \n\t"
+        PTR_ADDIU "%[src],       32                     \n\t"
         "cvt.s.w  %[temp1],      %[temp1]               \n\t"
         "cvt.s.w  %[temp3],      %[temp3]               \n\t"
         "cvt.s.w  %[temp5],      %[temp5]               \n\t"
@@ -313,7 +116,7 @@
         "swc1    %[temp11],      20(%[dst])             \n\t" /*dst[i+5] = src[i+5] * mul;*/
         "swc1    %[temp13],      24(%[dst])             \n\t" /*dst[i+6] = src[i+6] * mul;*/
         "swc1    %[temp15],      28(%[dst])             \n\t" /*dst[i+7] = src[i+7] * mul;*/
-        "addiu   %[dst],        32                      \n\t"
+        PTR_ADDIU "%[dst],       32                     \n\t"
         "bne     %[src],        %[src_end], i32tf_lp%=  \n\t"
         : [temp1]"=&f"(temp1),   [temp11]"=&f"(temp11),
           [temp13]"=&f"(temp13), [temp15]"=&f"(temp15),
@@ -333,10 +136,6 @@
 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/lsp_mips.h b/libavcodec/mips/lsp_mips.h
index c55ef03..9d75218 100644
--- a/libavcodec/mips/lsp_mips.h
+++ b/libavcodec/mips/lsp_mips.h
@@ -55,6 +55,8 @@
 #define AVCODEC_LSP_MIPS_H
 
 #if HAVE_MIPSFPU && HAVE_INLINE_ASM
+#include "libavutil/mips/asmdefs.h"
+
 static av_always_inline void ff_lsp2polyf_mips(const double *lsp, double *f, int lp_half_order)
 {
     int i, j = 0;
@@ -73,7 +75,7 @@
         __asm__ volatile(
             "move   %[p_f],     %[p_fi]                         \n\t"
             "add.d  %[val],     %[val],     %[val]              \n\t"
-            "addiu  %[p_fi],    8                               \n\t"
+            PTR_ADDIU "%[p_fi], 8                               \n\t"
             "ldc1   %[f_j_1],   0(%[p_f])                       \n\t"
             "ldc1   %[f_j],     8(%[p_f])                       \n\t"
             "neg.d  %[val],     %[val]                          \n\t"
@@ -91,7 +93,7 @@
             "mov.d  %[f_j_1],   %[f_j_2]                        \n\t"
             "ldc1   %[f_j_2],   -16(%[p_f])                     \n\t"
             "sdc1   %[tmp],     8(%[p_f])                       \n\t"
-            "addiu  %[p_f],     -8                              \n\t"
+            PTR_ADDIU "%[p_f], -8                              \n\t"
             "bgtz   %[j],       ff_lsp2polyf_lp_j%=             \n\t"
             "ff_lsp2polyf_lp_j_end%=:                           \n\t"
 
diff --git a/libavcodec/mips/mathops.h b/libavcodec/mips/mathops.h
index 368290a..5673fc0 100644
--- a/libavcodec/mips/mathops.h
+++ b/libavcodec/mips/mathops.h
@@ -49,32 +49,6 @@
 }
 #define MLS64(d, a, b) ((d) = MLS64(d, a, b))
 
-#elif ARCH_MIPS64
-
-static inline av_const int64_t MAC64(int64_t d, int a, int b)
-{
-    int64_t m;
-    __asm__ ("dmult %2, %3     \n\t"
-             "mflo  %1         \n\t"
-             "daddu %0, %0, %1 \n\t"
-             : "+r"(d), "=&r"(m) : "r"(a), "r"(b)
-             : "hi", "lo");
-    return d;
-}
-#define MAC64(d, a, b) ((d) = MAC64(d, a, b))
-
-static inline av_const int64_t MLS64(int64_t d, int a, int b)
-{
-    int64_t m;
-    __asm__ ("dmult %2, %3     \n\t"
-             "mflo  %1         \n\t"
-             "dsubu %0, %0, %1 \n\t"
-             : "+r"(d), "=&r"(m) : "r"(a), "r"(b)
-             : "hi", "lo");
-    return d;
-}
-#define MLS64(d, a, b) ((d) = MLS64(d, a, b))
-
 #endif
 
 #endif /* HAVE_INLINE_ASM */
diff --git a/libavcodec/mips/mpegaudiodsp_mips_fixed.c b/libavcodec/mips/mpegaudiodsp_mips_fixed.c
index 047a833..86ea13d 100644
--- a/libavcodec/mips/mpegaudiodsp_mips_fixed.c
+++ b/libavcodec/mips/mpegaudiodsp_mips_fixed.c
@@ -54,6 +54,7 @@
 
 #include <string.h>
 
+#include "libavutil/mips/asmdefs.h"
 #include "libavcodec/mpegaudiodsp.h"
 
 static void ff_mpadsp_apply_window_mips_fixed(int32_t *synth_buf, int32_t *window,
@@ -152,7 +153,7 @@
 
          "extr.w %[sum1],   $ac0,       24                                \n\t"
          "mflo   %[temp3]                                                 \n\t"
-         "addi   %[w],      %[w],       4                                 \n\t"
+         PTR_ADDIU "%[w],   %[w],       4                                 \n\t"
          "and    %[temp1],  %[temp3],   0x00ffffff                        \n\t"
          "slt    %[temp2],  %[sum1],    %[min_asm]                        \n\t"
          "movn   %[sum1],   %[min_asm], %[temp2]                          \n\t"
@@ -180,7 +181,7 @@
              "mtlo   $0,         $ac1                                      \n\t"
              "mthi   $0                                                    \n\t"
              "mtlo   %[temp1]                                              \n\t"
-             "addi   %[p_temp1], %[p_temp1],       4                       \n\t"
+             PTR_ADDIU "%[p_temp1], %[p_temp1],    4                       \n\t"
              "lw     %[w_asm],   0(%[w])                                   \n\t"
              "lw     %[p_asm],   0(%[p_temp1])                             \n\t"
              "lw     %[w2_asm],  0(%[w2])                                  \n\t"
@@ -221,7 +222,7 @@
              "msub   $ac1,       %[w2_asm],        %[p_asm]                \n\t"
              "madd   %[w_asm1],  %[p_asm1]                                 \n\t"
              "msub   $ac1,       %[w2_asm1],       %[p_asm1]               \n\t"
-             "addi   %[p_temp2], %[p_temp2],       -4                      \n\t"
+             PTR_ADDIU "%[p_temp2], %[p_temp2],   -4                      \n\t"
              "lw     %[w_asm],   32*4(%[w])                                \n\t"
              "lw     %[p_asm],   0(%[p_temp2])                             \n\t"
              "lw     %[w2_asm],  32*4(%[w2])                               \n\t"
@@ -262,8 +263,8 @@
              "msub   %[w_asm1],  %[p_asm1]                                 \n\t"
              "msub   $ac1,       %[w2_asm],        %[p_asm]                \n\t"
              "msub   $ac1,       %[w2_asm1],       %[p_asm1]               \n\t"
-             "addi   %[w],       %[w],             4                       \n\t"
-             "addi   %[w2],      %[w2],            -4                      \n\t"
+             PTR_ADDIU "%[w],    %[w],             4                       \n\t"
+             PTR_ADDIU "%[w2],   %[w2],            -4                      \n\t"
              "mflo   %[temp2]                                              \n\t"
              "extr.w %[sum1],    $ac0,             24                      \n\t"
              "li     %[temp3],   1                                         \n\t"
diff --git a/libavcodec/mips/mpegaudiodsp_mips_float.c b/libavcodec/mips/mpegaudiodsp_mips_float.c
index beb8e78..bd36894 100644
--- a/libavcodec/mips/mpegaudiodsp_mips_float.c
+++ b/libavcodec/mips/mpegaudiodsp_mips_float.c
@@ -55,6 +55,7 @@
 
 #include <string.h>
 
+#include "libavutil/mips/asmdefs.h"
 #include "libavcodec/mpegaudiodsp.h"
 
 static void ff_mpadsp_apply_window_mips_float(float *synth_buf, float *window,
@@ -89,7 +90,7 @@
         "sw      $zero,       0(%[dither_state])                            \t\n"
         "lwc1    %[in3],      64*4(%[window])                               \t\n"
         "lwc1    %[in4],      80*4(%[synth_buf])                            \t\n"
-        "addu    %[samples2], %[samples],   %[t_sample]                     \t\n"
+        PTR_ADDU "%[samples2],%[samples],   %[t_sample]                     \t\n"
         "madd.s  %[sum],      %[sum],       %[in1], %[in2]                  \t\n"
         "lwc1    %[in5],      128*4(%[window])                              \t\n"
         "lwc1    %[in6],      144*4(%[synth_buf])                           \t\n"
@@ -131,15 +132,15 @@
         "lwc1    %[in7],      480*4(%[window])                              \t\n"
         "lwc1    %[in8],      496*4(%[synth_buf])                           \t\n"
         "nmsub.s %[sum],      %[sum],       %[in1], %[in2]                  \t\n"
-        "addu    %[w],        %[window],    4                               \t\n"
+        PTR_ADDU "%[w],       %[window],    4                               \t\n"
         "nmsub.s %[sum],      %[sum],       %[in3], %[in4]                  \t\n"
-        "addu    %[w2],       %[window],    124                             \t\n"
-        "addiu   %[p],        %[synth_buf], 68                              \t\n"
-        "addiu   %[p2],       %[synth_buf], 188                             \t\n"
+        PTR_ADDU "%[w2],      %[window],    124                             \t\n"
+        PTR_ADDIU "%[p],      %[synth_buf], 68                              \t\n"
+        PTR_ADDIU "%[p2],     %[synth_buf], 188                             \t\n"
         "nmsub.s %[sum],      %[sum],       %[in5], %[in6]                  \t\n"
         "nmsub.s %[sum],      %[sum],       %[in7], %[in8]                  \t\n"
         "swc1    %[sum],      0(%[samples])                                 \t\n"
-        "addu    %[samples],  %[samples],   %[incr1]                        \t\n"
+        PTR_ADDU "%[samples], %[samples],   %[incr1]                        \t\n"
 
         /* calculate two samples at the same time to avoid one memory
            access per two sample */
@@ -223,17 +224,17 @@
         "nmsub.s %[sum],      %[sum],       %[in1], %[in2]                  \t\n"
         "lwc1    %[in6],      480*4(%[w2])                                  \t\n"
         "nmsub.s %[sum2],     %[sum2],      %[in2], %[in3]                  \t\n"
-        "addiu   %[w],        %[w],         4                               \t\n"
+        PTR_ADDIU "%[w],      %[w],         4                               \t\n"
         "nmsub.s %[sum],      %[sum],       %[in4], %[in5]                  \t\n"
-        "addiu   %[w2],       %[w2],        -4                              \t\n"
+        PTR_ADDIU "%[w2],     %[w2],        -4                              \t\n"
         "nmsub.s %[sum2],     %[sum2],      %[in5], %[in6]                  \t\n"
         "addu    %[j],        %[j],         4                               \t\n"
-        "addiu   %[p],        4                                             \t\n"
+        PTR_ADDIU "%[p],      4                                             \t\n"
         "swc1    %[sum],      0(%[samples])                                 \t\n"
-        "addiu   %[p2],       -4                                            \t\n"
+        PTR_ADDIU "%[p2],     -4                                            \t\n"
         "swc1    %[sum2],     0(%[samples2])                                \t\n"
-        "addu    %[samples],  %[samples],   %[incr1]                        \t\n"
-        "subu    %[samples2], %[samples2],  %[incr1]                        \t\n"
+        PTR_ADDU "%[samples], %[samples],   %[incr1]                        \t\n"
+        PTR_SUBU "%[samples2],%[samples2],  %[incr1]                        \t\n"
         "bne     %[j],        64,           ff_mpadsp_apply_window_loop%=   \t\n"
 
         "lwc1    %[in1],      48*4(%[window])                               \t\n"
diff --git a/libavcodec/mips/sbrdsp_mips.c b/libavcodec/mips/sbrdsp_mips.c
index d4460ba..c203095 100644
--- a/libavcodec/mips/sbrdsp_mips.c
+++ b/libavcodec/mips/sbrdsp_mips.c
@@ -56,41 +56,9 @@
 
 #include "config.h"
 #include "libavcodec/sbrdsp.h"
+#include "libavutil/mips/asmdefs.h"
 
 #if HAVE_INLINE_ASM
-static void sbr_neg_odd_64_mips(float *x)
-{
-    int Temp1, Temp2, Temp3, Temp4, Temp5;
-    float *x1    = &x[1];
-    float *x_end = x1 + 64;
-
-    /* loop unrolled 4 times */
-    __asm__ volatile (
-        "lui    %[Temp5],   0x8000                  \n\t"
-    "1:                                             \n\t"
-        "lw     %[Temp1],   0(%[x1])                \n\t"
-        "lw     %[Temp2],   8(%[x1])                \n\t"
-        "lw     %[Temp3],   16(%[x1])               \n\t"
-        "lw     %[Temp4],   24(%[x1])               \n\t"
-        "xor    %[Temp1],   %[Temp1],   %[Temp5]    \n\t"
-        "xor    %[Temp2],   %[Temp2],   %[Temp5]    \n\t"
-        "xor    %[Temp3],   %[Temp3],   %[Temp5]    \n\t"
-        "xor    %[Temp4],   %[Temp4],   %[Temp5]    \n\t"
-        "sw     %[Temp1],   0(%[x1])                \n\t"
-        "sw     %[Temp2],   8(%[x1])                \n\t"
-        "sw     %[Temp3],   16(%[x1])               \n\t"
-        "sw     %[Temp4],   24(%[x1])               \n\t"
-        "addiu  %[x1],      %[x1],      32          \n\t"
-        "bne    %[x1],      %[x_end],   1b          \n\t"
-
-        : [Temp1]"=&r"(Temp1), [Temp2]"=&r"(Temp2),
-          [Temp3]"=&r"(Temp3), [Temp4]"=&r"(Temp4),
-          [Temp5]"=&r"(Temp5), [x1]"+r"(x1)
-        : [x_end]"r"(x_end)
-        : "memory"
-    );
-}
-
 static void sbr_qmf_pre_shuffle_mips(float *z)
 {
     int Temp1, Temp2, Temp3, Temp4, Temp5, Temp6;
@@ -113,7 +81,7 @@
         "xor    %[Temp3],   %[Temp3],   %[Temp6]    \n\t"
         "xor    %[Temp4],   %[Temp4],   %[Temp6]    \n\t"
         "xor    %[Temp5],   %[Temp5],   %[Temp6]    \n\t"
-        "addiu  %[z2],      %[z2],      -20         \n\t"
+        PTR_ADDIU "%[z2],   %[z2],      -20         \n\t"
         "sw     %[Temp1],   32(%[z1])               \n\t"
         "sw     %[Temp2],   24(%[z1])               \n\t"
         "sw     %[Temp3],   16(%[z1])               \n\t"
@@ -129,8 +97,8 @@
         "sw     %[Temp3],   20(%[z1])               \n\t"
         "sw     %[Temp4],   28(%[z1])               \n\t"
         "sw     %[Temp5],   36(%[z1])               \n\t"
-        "addiu  %[z3],      %[z3],      20          \n\t"
-        "addiu  %[z1],      %[z1],      40          \n\t"
+        PTR_ADDIU "%[z3],   %[z3],      20          \n\t"
+        PTR_ADDIU "%[z1],   %[z1],      40          \n\t"
         "bne    %[z1],      %[z4],      1b          \n\t"
         "lw     %[Temp1],   132(%[z])               \n\t"
         "lw     %[Temp2],   128(%[z])               \n\t"
@@ -171,7 +139,7 @@
         "xor    %[Temp2],   %[Temp2],   %[Temp5]    \n\t"
         "xor    %[Temp3],   %[Temp3],   %[Temp5]    \n\t"
         "xor    %[Temp4],   %[Temp4],   %[Temp5]    \n\t"
-        "addiu  %[z2],      %[z2],      -16         \n\t"
+        PTR_ADDIU "%[z2],   %[z2],      -16         \n\t"
         "sw     %[Temp1],   24(%[W_ptr])            \n\t"
         "sw     %[Temp2],   16(%[W_ptr])            \n\t"
         "sw     %[Temp3],   8(%[W_ptr])             \n\t"
@@ -184,8 +152,8 @@
         "sw     %[Temp2],   12(%[W_ptr])            \n\t"
         "sw     %[Temp3],   20(%[W_ptr])            \n\t"
         "sw     %[Temp4],   28(%[W_ptr])            \n\t"
-        "addiu  %[z1],      %[z1],      16          \n\t"
-        "addiu  %[W_ptr],   %[W_ptr],   32          \n\t"
+        PTR_ADDIU "%[z1],   %[z1],      16          \n\t"
+        PTR_ADDIU "%[W_ptr],%[W_ptr],   32          \n\t"
         "bne    %[z1],      %[z_end],   1b          \n\t"
 
         : [Temp1]"=&r"(Temp1), [Temp2]"=&r"(Temp2),
@@ -319,7 +287,7 @@
         "lwc1      %[temp2],   8(%[p_x])                            \n\t"
         "lwc1      %[temp3],   12(%[p_x])                           \n\t"
     "1:                                                             \n\t"
-        "addiu     %[p_x],     %[p_x],       16                     \n\t"
+        PTR_ADDIU "%[p_x],     %[p_x],       16                     \n\t"
         "madd.s    %[sum0],    %[sum0],      %[temp0],   %[temp0]   \n\t"
         "lwc1      %[temp0],   0(%[p_x])                            \n\t"
         "madd.s    %[sum1],    %[sum1],      %[temp1],   %[temp1]   \n\t"
@@ -454,10 +422,10 @@
             "swc1       %[temp6],   56(%[v0])              \n\t"
             "swc1       %[temp11],  -60(%[v1])             \n\t"
             "swc1       %[temp9],   60(%[v0])              \n\t"
-            "addiu      %[src0],    %[src0],    64         \n\t"
-            "addiu      %[src1],    %[src1],    -64        \n\t"
-            "addiu      %[v0],      %[v0],      64         \n\t"
-            "addiu      %[v1],      %[v1],      -64        \n\t"
+            PTR_ADDIU " %[src0],    %[src0],    64         \n\t"
+            PTR_ADDIU " %[src1],    %[src1],    -64        \n\t"
+            PTR_ADDIU " %[v0],      %[v0],      64         \n\t"
+            PTR_ADDIU " %[v1],      %[v1],      -64        \n\t"
 
             : [v0]"+r"(v0), [v1]"+r"(v1), [src0]"+r"(psrc0), [src1]"+r"(psrc1),
               [temp0]"=&f"(temp0), [temp1]"=&f"(temp1), [temp2]"=&f"(temp2),
@@ -506,7 +474,7 @@
         "add.s   %[imag_sum_1], %[imag_sum_1], %[temp_r2]           \n\t"
         "add.s   %[real_sum_2], %[real_sum_2], %[temp_r3]           \n\t"
         "add.s   %[imag_sum_2], %[imag_sum_2], %[temp_r4]           \n\t"
-        "addiu   %[p_x],        %[p_x],        8                    \n\t"
+        PTR_ADDIU "%[p_x],      %[p_x],        8                    \n\t"
 
         : [temp0]"=&f"(temp0), [temp1]"=&f"(temp1), [temp2]"=&f"(temp2),
           [temp3]"=&f"(temp3), [temp4]"=&f"(temp4), [temp5]"=&f"(temp5),
@@ -576,7 +544,7 @@
             "add.s   %[imag_sum_1], %[imag_sum_1], %[temp_r2]           \n\t"
             "add.s   %[real_sum_2], %[real_sum_2], %[temp_r3]           \n\t"
             "add.s   %[imag_sum_2], %[imag_sum_2], %[temp_r4]           \n\t"
-            "addiu   %[p_x],        %[p_x],        24                   \n\t"
+            PTR_ADDIU "%[p_x],      %[p_x],        24                   \n\t"
 
             : [temp0]"=&f"(temp0), [temp1]"=&f"(temp1), [temp2]"=&f"(temp2),
               [temp3]"=&f"(temp3), [temp4]"=&f"(temp4), [temp5]"=&f"(temp5),
@@ -667,8 +635,8 @@
             "lwc1    %[temp8],    4(%[alpha])                            \n\t"
             "lwc1    %[temp9],    8(%[alpha])                            \n\t"
             "lwc1    %[temp10],   12(%[alpha])                           \n\t"
-            "addiu   %[p_x_high], %[p_x_high],     8                     \n\t"
-            "addiu   %[p_x_low],  %[p_x_low],      8                     \n\t"
+            PTR_ADDIU "%[p_x_high], %[p_x_high],   8                     \n\t"
+            PTR_ADDIU "%[p_x_low],  %[p_x_low],    8                     \n\t"
             "mul.s   %[temp11],   %[temp1],        %[temp8]              \n\t"
             "msub.s  %[temp11],   %[temp11],       %[temp0],  %[temp7]   \n\t"
             "madd.s  %[temp11],   %[temp11],       %[temp2],  %[temp9]   \n\t"
@@ -697,14 +665,14 @@
 static void sbr_hf_g_filt_mips(float (*Y)[2], const float (*X_high)[40][2],
                             const float *g_filt, int m_max, intptr_t ixh)
 {
-    float *p_y, *p_x, *p_g;
+    const float *p_x, *p_g, *loop_end;
+    float *p_y;
     float temp0, temp1, temp2;
-    int loop_end;
 
-    p_g = (float*)&g_filt[0];
+    p_g = &g_filt[0];
     p_y = &Y[0][0];
-    p_x = (float*)&X_high[0][ixh][0];
-    loop_end = (int)((int*)p_g + m_max);
+    p_x = &X_high[0][ixh][0];
+    loop_end = p_g + m_max;
 
     __asm__ volatile(
         ".set    push                                \n\t"
@@ -715,12 +683,12 @@
         "lwc1    %[temp2],   4(%[p_x])               \n\t"
         "mul.s   %[temp1],   %[temp1],     %[temp0]  \n\t"
         "mul.s   %[temp2],   %[temp2],     %[temp0]  \n\t"
-        "addiu   %[p_g],     %[p_g],       4         \n\t"
-        "addiu   %[p_x],     %[p_x],       320       \n\t"
+        PTR_ADDIU "%[p_g],   %[p_g],       4         \n\t"
+        PTR_ADDIU "%[p_x],   %[p_x],       320       \n\t"
         "swc1    %[temp1],   0(%[p_y])               \n\t"
         "swc1    %[temp2],   4(%[p_y])               \n\t"
         "bne     %[p_g],     %[loop_end],  1b        \n\t"
-        " addiu  %[p_y],     %[p_y],       8         \n\t"
+        PTR_ADDIU "%[p_y],   %[p_y],       8         \n\t"
         ".set    pop                                 \n\t"
 
         : [temp0]"=&f"(temp0), [temp1]"=&f"(temp1),
@@ -752,7 +720,7 @@
             "addiu   %[noise],    %[noise],              1                    \n\t"
             "andi    %[noise],    %[noise],              0x1ff                \n\t"
             "sll     %[temp0],    %[noise], 3                                 \n\t"
-            "addu    %[ff_table], %[ff_sbr_noise_table], %[temp0]             \n\t"
+            PTR_ADDU "%[ff_table],%[ff_sbr_noise_table], %[temp0]             \n\t"
             "add.s   %[y0],       %[y0],                 %[temp1]             \n\t"
             "mfc1    %[temp3],    %[temp1]                                    \n\t"
             "bne     %[temp3],    $0,                    1f                   \n\t"
@@ -798,7 +766,7 @@
             "addiu  %[noise],    %[noise],               1                    \n\t"
             "andi   %[noise],    %[noise],               0x1ff                \n\t"
             "sll    %[temp0],    %[noise],               3                    \n\t"
-            "addu   %[ff_table], %[ff_sbr_noise_table], %[temp0]              \n\t"
+            PTR_ADDU "%[ff_table],%[ff_sbr_noise_table],%[temp0]              \n\t"
             "madd.s %[y1],       %[y1],                 %[temp1], %[phi_sign] \n\t"
             "bne    %[temp3],    $0,                    1f                    \n\t"
             "lwc1   %[y0],       0(%[Y1])                                     \n\t"
@@ -843,7 +811,7 @@
             "addiu  %[noise],    %[noise],              1                  \n\t"
             "andi   %[noise],    %[noise],              0x1ff              \n\t"
             "sll    %[temp0],    %[noise],              3                  \n\t"
-            "addu   %[ff_table], %[ff_sbr_noise_table], %[temp0]           \n\t"
+            PTR_ADDU "%[ff_table],%[ff_sbr_noise_table],%[temp0]           \n\t"
             "sub.s  %[y0],       %[y0],                 %[temp1]           \n\t"
             "mfc1   %[temp3],    %[temp1]                                  \n\t"
             "bne    %[temp3],    $0,                    1f                 \n\t"
@@ -889,7 +857,7 @@
             "addiu   %[noise],    %[noise],              1                     \n\t"
             "andi    %[noise],    %[noise],              0x1ff                 \n\t"
             "sll     %[temp0],    %[noise],              3                     \n\t"
-            "addu    %[ff_table], %[ff_sbr_noise_table], %[temp0]              \n\t"
+            PTR_ADDU "%[ff_table],%[ff_sbr_noise_table], %[temp0]              \n\t"
             "nmsub.s %[y1],       %[y1],                 %[temp1], %[phi_sign] \n\t"
             "mfc1    %[temp3],    %[temp1]                                     \n\t"
             "bne     %[temp3],    $0,                    1f                    \n\t"
@@ -920,7 +888,6 @@
 void ff_sbrdsp_init_mips(SBRDSPContext *s)
 {
 #if HAVE_INLINE_ASM
-    s->neg_odd_64 = sbr_neg_odd_64_mips;
     s->qmf_pre_shuffle = sbr_qmf_pre_shuffle_mips;
     s->qmf_post_shuffle = sbr_qmf_post_shuffle_mips;
 #if HAVE_MIPSFPU
diff --git a/libavcodec/mjpegbdec.c b/libavcodec/mjpegbdec.c
index f6ee705..8ac60c2 100644
--- a/libavcodec/mjpegbdec.c
+++ b/libavcodec/mjpegbdec.c
@@ -27,6 +27,7 @@
 #include <inttypes.h>
 
 #include "avcodec.h"
+#include "internal.h"
 #include "mjpeg.h"
 #include "mjpegdec.h"
 
@@ -167,4 +168,5 @@
     .decode         = mjpegb_decode_frame,
     .capabilities   = CODEC_CAP_DR1,
     .max_lowres     = 3,
+    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE,
 };
diff --git a/libavcodec/mjpegdec.c b/libavcodec/mjpegdec.c
index 054d936..4553152 100644
--- a/libavcodec/mjpegdec.c
+++ b/libavcodec/mjpegdec.c
@@ -250,7 +250,8 @@
     int v_count[MAX_COMPONENTS] = { 0 };
 
     s->cur_scan = 0;
-    s->upscale_h = s->upscale_v = 0;
+    memset(s->upscale_h, 0, sizeof(s->upscale_h));
+    memset(s->upscale_v, 0, sizeof(s->upscale_v));
 
     /* XXX: verify len field validity */
     len     = get_bits(&s->gb, 16);
@@ -404,8 +405,8 @@
             js = (pix_fmt_id >> (16 + 4*(i&1))) & 0xF;
 
         if (is == 1 && js == 2) {
-            if (i & 1) s->upscale_h |= 1 << (j/2);
-            else       s->upscale_v |= 1 << (j/2);
+            if (i & 1) s->upscale_h[j/2] = 1;
+            else       s->upscale_v[j/2] = 1;
         }
     }
 
@@ -441,12 +442,12 @@
     case 0x22111111:
         if (s->adobe_transform == 0 && s->bits <= 8) {
             s->avctx->pix_fmt = AV_PIX_FMT_GBRAP;
-            s->upscale_v |= 6;
-            s->upscale_h |= 6;
+            s->upscale_v[1] = s->upscale_v[2] = 1;
+            s->upscale_h[1] = s->upscale_h[2] = 1;
         } else if (s->adobe_transform == 2 && s->bits <= 8) {
             s->avctx->pix_fmt = AV_PIX_FMT_YUVA444P;
-            s->upscale_v |= 6;
-            s->upscale_h |= 6;
+            s->upscale_v[1] = s->upscale_v[2] = 1;
+            s->upscale_h[1] = s->upscale_h[2] = 1;
             s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
         } else {
             if (s->bits <= 8) s->avctx->pix_fmt = AV_PIX_FMT_YUVA420P;
@@ -495,10 +496,10 @@
             if (s->bits <= 8) s->avctx->pix_fmt = AV_PIX_FMT_GBRP;
             else
                 goto unk_pixfmt;
-            s->upscale_v |= 3;
+            s->upscale_v[0] = s->upscale_v[1] = 1;
         } else {
             if (pix_fmt_id == 0x14111100)
-                s->upscale_v |= 6;
+                s->upscale_v[1] = s->upscale_v[2] = 1;
             if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV440P : AV_PIX_FMT_YUVJ440P;
             else
                 goto unk_pixfmt;
@@ -510,13 +511,20 @@
             if (s->bits <= 8) s->avctx->pix_fmt = AV_PIX_FMT_GBRP;
             else
                 goto unk_pixfmt;
-            s->upscale_h |= 3;
+            s->upscale_h[0] = s->upscale_h[1] = 1;
         } else {
             if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
             else              s->avctx->pix_fmt = AV_PIX_FMT_YUV422P16;
             s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
         }
         break;
+    case 0x31111100:
+        if (s->bits > 8)
+            goto unk_pixfmt;
+        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_h[1] = s->upscale_h[2] = 2;
+        break;
     case 0x22121100:
     case 0x22111200:
         if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
@@ -533,11 +541,11 @@
         if (pix_fmt_id == 0x42111100) {
             if (s->bits > 8)
                 goto unk_pixfmt;
-            s->upscale_h = 6;
+            s->upscale_h[1] = s->upscale_h[2] = 1;
         } else if (pix_fmt_id == 0x24111100) {
             if (s->bits > 8)
                 goto unk_pixfmt;
-            s->upscale_v = 6;
+            s->upscale_v[1] = s->upscale_v[2] = 1;
         }
         break;
     case 0x41111100:
@@ -549,18 +557,23 @@
     default:
 unk_pixfmt:
         av_log(s->avctx, AV_LOG_ERROR, "Unhandled pixel format 0x%x bits:%d\n", pix_fmt_id, s->bits);
-        s->upscale_h = s->upscale_v = 0;
+        memset(s->upscale_h, 0, sizeof(s->upscale_h));
+        memset(s->upscale_v, 0, sizeof(s->upscale_v));
         return AVERROR_PATCHWELCOME;
     }
-    if ((s->upscale_h || s->upscale_v) && s->avctx->lowres) {
+    if ((AV_RB32(s->upscale_h) || AV_RB32(s->upscale_v)) && s->avctx->lowres) {
         av_log(s->avctx, AV_LOG_ERROR, "lowres not supported for weird subsampling\n");
         return AVERROR_PATCHWELCOME;
     }
     if (s->ls) {
-        s->upscale_h = s->upscale_v = 0;
-        if (s->nb_components > 1)
+        memset(s->upscale_h, 0, sizeof(s->upscale_h));
+        memset(s->upscale_v, 0, sizeof(s->upscale_v));
+        if (s->nb_components == 3) {
             s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
-        else if (s->palette_index && s->bits <= 8)
+        } else if (s->nb_components != 1) {
+            av_log(s->avctx, AV_LOG_ERROR, "Unsupported number of components %d\n", s->nb_components);
+            return AVERROR_PATCHWELCOME;
+        } else if (s->palette_index && s->bits <= 8)
             s->avctx->pix_fmt = AV_PIX_FMT_PAL8;
         else if (s->bits <= 8)
             s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
@@ -1245,13 +1258,18 @@
 
                     if (s->interlaced && s->bottom_field)
                         block_offset += linesize[c] >> 1;
-                    ptr = data[c] + block_offset;
+                    if (   8*(h * mb_x + x) < s->width
+                        && 8*(v * mb_y + y) < s->height) {
+                        ptr = data[c] + block_offset;
+                    } else
+                        ptr = NULL;
                     if (!s->progressive) {
-                        if (copy_mb)
-                            mjpeg_copy_block(s, ptr, reference_data[c] + block_offset,
-                                             linesize[c], s->avctx->lowres);
+                        if (copy_mb) {
+                            if (ptr)
+                                mjpeg_copy_block(s, ptr, reference_data[c] + block_offset,
+                                                linesize[c], s->avctx->lowres);
 
-                        else {
+                        } else {
                             s->bdsp.clear_block(s->block);
                             if (decode_block(s, s->block, i,
                                              s->dc_index[i], s->ac_index[i],
@@ -1260,9 +1278,11 @@
                                        "error y=%d x=%d\n", mb_y, mb_x);
                                 return AVERROR_INVALIDDATA;
                             }
-                            s->idsp.idct_put(ptr, linesize[c], s->block);
-                            if (s->bits & 7)
-                                shift_output(s, ptr, linesize[c]);
+                            if (ptr) {
+                                s->idsp.idct_put(ptr, linesize[c], s->block);
+                                if (s->bits & 7)
+                                    shift_output(s, ptr, linesize[c]);
+                            }
                         }
                     } else {
                         int block_idx  = s->block_stride[c] * (v * mb_y + y) +
@@ -1901,6 +1921,10 @@
             put_bits(&pb, 8, x);
             if (x == 0xFF) {
                 x = src[b++];
+                if (x & 0x80) {
+                    av_log(s->avctx, AV_LOG_WARNING, "Invalid escape sequence\n");
+                    x &= 0x7f;
+                }
                 put_bits(&pb, 7, x);
                 bit_count--;
             }
@@ -2115,7 +2139,7 @@
 
     is16bit = av_pix_fmt_desc_get(s->avctx->pix_fmt)->comp[0].step_minus1;
 
-    if (s->upscale_h) {
+    if (AV_RB32(s->upscale_h)) {
         int p;
         av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
                    avctx->pix_fmt == AV_PIX_FMT_YUV444P  ||
@@ -2135,29 +2159,42 @@
             uint8_t *line = s->picture_ptr->data[p];
             int w = s->width;
             int h = s->height;
-            if (!(s->upscale_h & (1<<p)))
+            if (!s->upscale_h[p])
                 continue;
             if (p==1 || p==2) {
                 w = FF_CEIL_RSHIFT(w, hshift);
                 h = FF_CEIL_RSHIFT(h, vshift);
             }
-            if (s->upscale_v & (1<<p))
+            if (s->upscale_v[p])
                 h = (h+1)>>1;
             av_assert0(w > 0);
             for (i = 0; i < h; i++) {
-                if (is16bit) ((uint16_t*)line)[w - 1] = ((uint16_t*)line)[(w - 1) / 2];
-                else                      line[w - 1] = line[(w - 1) / 2];
-                for (index = w - 2; index > 0; index--) {
-                    if (is16bit)
-                        ((uint16_t*)line)[index] = (((uint16_t*)line)[index / 2] + ((uint16_t*)line)[(index + 1) / 2]) >> 1;
-                    else
-                        line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;
+                if (s->upscale_h[p] == 1) {
+                    if (is16bit) ((uint16_t*)line)[w - 1] = ((uint16_t*)line)[(w - 1) / 2];
+                    else                      line[w - 1] = line[(w - 1) / 2];
+                    for (index = w - 2; index > 0; index--) {
+                        if (is16bit)
+                            ((uint16_t*)line)[index] = (((uint16_t*)line)[index / 2] + ((uint16_t*)line)[(index + 1) / 2]) >> 1;
+                        else
+                            line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;
+                    }
+                } else if (s->upscale_h[p] == 2) {
+                    if (is16bit) {
+                        ((uint16_t*)line)[w - 1] =
+                        ((uint16_t*)line)[w - 2] = ((uint16_t*)line)[(w - 1) / 3];
+                    } else {
+                        line[w - 1] =
+                        line[w - 2] = line[(w - 1) / 3];
+                    }
+                    for (index = w - 3; index > 0; index--) {
+                        line[index] = (line[index / 3] + line[(index + 1) / 3] + line[(index + 2) / 3] + 1) / 3;
+                    }
                 }
                 line += s->linesize[p];
             }
         }
     }
-    if (s->upscale_v) {
+    if (AV_RB32(s->upscale_v)) {
         int p;
         av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
                    avctx->pix_fmt == AV_PIX_FMT_YUV444P  ||
@@ -2178,7 +2215,7 @@
             uint8_t *dst;
             int w = s->width;
             int h = s->height;
-            if (!(s->upscale_v & (1<<p)))
+            if (!s->upscale_v[p])
                 continue;
             if (p==1 || p==2) {
                 w = FF_CEIL_RSHIFT(w, hshift);
@@ -2350,6 +2387,7 @@
     .capabilities   = CODEC_CAP_DR1,
     .max_lowres     = 3,
     .priv_class     = &mjpegdec_class,
+    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE,
 };
 #endif
 #if CONFIG_THP_DECODER
@@ -2365,5 +2403,6 @@
     .flush          = decode_flush,
     .capabilities   = CODEC_CAP_DR1,
     .max_lowres     = 3,
+    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE,
 };
 #endif
diff --git a/libavcodec/mjpegdec.h b/libavcodec/mjpegdec.h
index deacabe..28d3e4a 100644
--- a/libavcodec/mjpegdec.h
+++ b/libavcodec/mjpegdec.h
@@ -62,8 +62,8 @@
     int ls;
     int progressive;
     int rgb;
-    int upscale_h;
-    int upscale_v;
+    uint8_t upscale_h[4];
+    uint8_t upscale_v[4];
     int rct;            /* standard rct */
     int pegasus_rct;    /* pegasus reversible colorspace transform */
     int bits;           /* bits per component */
diff --git a/libavcodec/mjpegenc.c b/libavcodec/mjpegenc.c
index 14701e2..24f8d1d 100644
--- a/libavcodec/mjpegenc.c
+++ b/libavcodec/mjpegenc.c
@@ -38,6 +38,35 @@
 #include "mjpeg.h"
 #include "mjpegenc.h"
 
+static uint8_t uni_ac_vlc_len[64 * 64 * 2];
+static uint8_t uni_chroma_ac_vlc_len[64 * 64 * 2];
+
+static av_cold void init_uni_ac_vlc(const uint8_t huff_size_ac[256], uint8_t *uni_ac_vlc_len)
+{
+    int i;
+
+    for (i = 0; i < 128; i++) {
+        int level = i - 64;
+        int run;
+        if (!level)
+            continue;
+        for (run = 0; run < 64; run++) {
+            int len, code, nbits;
+            int alevel = FFABS(level);
+
+            len = (run >> 4) * huff_size_ac[0xf0];
+
+            nbits= av_log2_16bit(alevel) + 1;
+            code = ((15&run) << 4) | nbits;
+
+            len += huff_size_ac[code] + nbits;
+
+            uni_ac_vlc_len[UNI_AC_ENC_INDEX(run, i)] = len;
+            // We ignore EOB as its just a constant which does not change generally
+        }
+    }
+}
+
 av_cold int ff_mjpeg_encode_init(MpegEncContext *s)
 {
     MJpegContext *m;
@@ -72,11 +101,18 @@
                                  avpriv_mjpeg_bits_ac_chrominance,
                                  avpriv_mjpeg_val_ac_chrominance);
 
+    init_uni_ac_vlc(m->huff_size_ac_luminance,   uni_ac_vlc_len);
+    init_uni_ac_vlc(m->huff_size_ac_chrominance, uni_chroma_ac_vlc_len);
+    s->intra_ac_vlc_length      =
+    s->intra_ac_vlc_last_length = uni_ac_vlc_len;
+    s->intra_chroma_ac_vlc_length      =
+    s->intra_chroma_ac_vlc_last_length = uni_chroma_ac_vlc_len;
+
     s->mjpeg_ctx = m;
     return 0;
 }
 
-void ff_mjpeg_encode_close(MpegEncContext *s)
+av_cold void ff_mjpeg_encode_close(MpegEncContext *s)
 {
     av_freep(&s->mjpeg_ctx);
 }
diff --git a/libavcodec/motion_est.c b/libavcodec/motion_est.c
index 901fafd..a0a5965 100644
--- a/libavcodec/motion_est.c
+++ b/libavcodec/motion_est.c
@@ -36,9 +36,6 @@
 #include "mpegutils.h"
 #include "mpegvideo.h"
 
-#undef NDEBUG
-#include <assert.h>
-
 #define P_LEFT P[1]
 #define P_TOP P[2]
 #define P_TOPRIGHT P[3]
@@ -321,6 +318,9 @@
 
     c->avctx= s->avctx;
 
+    if(s->codec_id == AV_CODEC_ID_H261)
+        c->avctx->me_sub_cmp = c->avctx->me_cmp;
+
     if(cache_size < 2*dia_size && !c->stride){
         av_log(s->avctx, AV_LOG_INFO, "ME_MAP size may be a little small for the selected diamond size\n");
     }
diff --git a/libavcodec/motionpixels.c b/libavcodec/motionpixels.c
index 19da10a..84517f9 100644
--- a/libavcodec/motionpixels.c
+++ b/libavcodec/motionpixels.c
@@ -232,13 +232,13 @@
             p = mp_get_yuv_from_rgb(mp, x - 1, y);
         } else {
             p.y += mp_gradient(mp, 0, mp_get_vlc(mp, gb));
-            p.y = av_clip(p.y, 0, 31);
+            p.y = av_clip_uintp2(p.y, 5);
             if ((x & 3) == 0) {
                 if ((y & 3) == 0) {
                     p.v += mp_gradient(mp, 1, mp_get_vlc(mp, gb));
-                    p.v = av_clip(p.v, -32, 31);
+                    p.v = av_clip_intp2(p.v, 5);
                     p.u += mp_gradient(mp, 2, mp_get_vlc(mp, gb));
-                    p.u = av_clip(p.u, -32, 31);
+                    p.u = av_clip_intp2(p.u, 5);
                     mp->hpt[((y / 4) * mp->avctx->width + x) / 4] = p;
                 } else {
                     p.v = mp->hpt[((y / 4) * mp->avctx->width + x) / 4].v;
@@ -264,12 +264,12 @@
             p = mp_get_yuv_from_rgb(mp, 0, y);
         } else {
             p.y += mp_gradient(mp, 0, mp_get_vlc(mp, gb));
-            p.y = av_clip(p.y, 0, 31);
+            p.y = av_clip_uintp2(p.y, 5);
             if ((y & 3) == 0) {
                 p.v += mp_gradient(mp, 1, mp_get_vlc(mp, gb));
-                p.v = av_clip(p.v, -32, 31);
+                p.v = av_clip_intp2(p.v, 5);
                 p.u += mp_gradient(mp, 2, mp_get_vlc(mp, gb));
-                p.u = av_clip(p.u, -32, 31);
+                p.u = av_clip_intp2(p.u, 5);
             }
             mp->vpt[y] = p;
             mp_set_rgb_from_yuv(mp, 0, y, &p);
diff --git a/libavcodec/mpeg12dec.c b/libavcodec/mpeg12dec.c
index 846df79..e06f4c8 100644
--- a/libavcodec/mpeg12dec.c
+++ b/libavcodec/mpeg12dec.c
@@ -956,7 +956,7 @@
                                 av_dlog(s->avctx, "fmx=%d\n", val);
                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
                                                          s->last_mv[i][j][1] >> 1);
-                                s->last_mv[i][j][1] = val << 1;
+                                s->last_mv[i][j][1] = 2 * val;
                                 s->mv[i][j][1]      = val;
                                 av_dlog(s->avctx, "fmy=%d\n", val);
                             }
diff --git a/libavcodec/mpeg4audio.h b/libavcodec/mpeg4audio.h
index 0f41045..a3d3724 100644
--- a/libavcodec/mpeg4audio.h
+++ b/libavcodec/mpeg4audio.h
@@ -38,6 +38,7 @@
     int ext_chan_config;
     int channels;
     int ps;  ///< -1 implicit, 1 presence
+    int frame_length_short;
 } MPEG4AudioConfig;
 
 extern av_export const int avpriv_mpeg4audio_sample_rates[16];
diff --git a/libavcodec/mpegaudio_parser.c b/libavcodec/mpegaudio_parser.c
index 79dbf63..58098d8 100644
--- a/libavcodec/mpegaudio_parser.c
+++ b/libavcodec/mpegaudio_parser.c
@@ -64,7 +64,7 @@
         }else{
             while(i<buf_size){
                 int ret, sr, channels, bit_rate, frame_size;
-                enum AVCodecID codec_id;
+                enum AVCodecID codec_id = avctx->codec_id;
 
                 state= (state<<8) + buf[i++];
 
@@ -90,6 +90,16 @@
                             avctx->bit_rate += (bit_rate - avctx->bit_rate) / (s->header_count - header_threshold);
                         }
                     }
+
+                    if (s1->flags & PARSER_FLAG_COMPLETE_FRAMES) {
+                        s->frame_size = 0;
+                        next = buf_size;
+                    } else if (codec_id == AV_CODEC_ID_MP3ADU) {
+                        avpriv_report_missing_feature(avctx,
+                            "MP3ADU full parser");
+                        return AVERROR_PATCHWELCOME;
+                    }
+
                     break;
                 }
             }
@@ -110,7 +120,7 @@
 
 
 AVCodecParser ff_mpegaudio_parser = {
-    .codec_ids      = { AV_CODEC_ID_MP1, AV_CODEC_ID_MP2, AV_CODEC_ID_MP3 },
+    .codec_ids      = { AV_CODEC_ID_MP1, AV_CODEC_ID_MP2, AV_CODEC_ID_MP3, AV_CODEC_ID_MP3ADU },
     .priv_data_size = sizeof(MpegAudioParseContext),
     .parser_parse   = mpegaudio_parse,
     .parser_close   = ff_parse_close,
diff --git a/libavcodec/mpegaudiodecheader.c b/libavcodec/mpegaudiodecheader.c
index 5db1957..6af6e4b 100644
--- a/libavcodec/mpegaudiodecheader.c
+++ b/libavcodec/mpegaudiodecheader.c
@@ -134,7 +134,8 @@
         break;
     default:
     case 3:
-        *codec_id = AV_CODEC_ID_MP3;
+        if (*codec_id != AV_CODEC_ID_MP3ADU)
+            *codec_id = AV_CODEC_ID_MP3;
         if (s->lsf)
             *frame_size = 576;
         else
diff --git a/libavcodec/mpegvideo.c b/libavcodec/mpegvideo.c
index 837bd0e..b7e4fe1 100644
--- a/libavcodec/mpegvideo.c
+++ b/libavcodec/mpegvideo.c
@@ -2225,8 +2225,10 @@
 
             av_log(avctx, AV_LOG_DEBUG, "Adding %d MVs info to frame %d\n", mbcount, avctx->frame_number);
             sd = av_frame_new_side_data(pict, AV_FRAME_DATA_MOTION_VECTORS, mbcount * sizeof(AVMotionVector));
-            if (!sd)
+            if (!sd) {
+                av_freep(&mvs);
                 return;
+            }
             memcpy(sd->data, mvs, mbcount * sizeof(AVMotionVector));
         }
 
@@ -2247,7 +2249,7 @@
         for (y = 0; y < mb_height; y++) {
             for (x = 0; x < mb_width; x++) {
                 if (avctx->debug & FF_DEBUG_SKIP) {
-                    int count = mbskip_table[x + y * mb_stride];
+                    int count = mbskip_table ? mbskip_table[x + y * mb_stride] : 0;
                     if (count > 9)
                         count = 9;
                     av_log(avctx, AV_LOG_DEBUG, "%1d", count);
@@ -2516,7 +2518,8 @@
                         // hmm
                     }
                 }
-                mbskip_table[mb_index] = 0;
+                if (mbskip_table)
+                    mbskip_table[mb_index] = 0;
             }
         }
     }
@@ -2950,12 +2953,12 @@
     }
 
     for (i = 0; i < mvs; i++) {
-        my = s->mv[dir][i][1]<<qpel_shift;
+        my = s->mv[dir][i][1];
         my_max = FFMAX(my_max, my);
         my_min = FFMIN(my_min, my);
     }
 
-    off = (FFMAX(-my_min, my_max) + 63) >> 6;
+    off = ((FFMAX(-my_min, my_max)<<qpel_shift) + 63) >> 6;
 
     return FFMIN(FFMAX(s->mb_y + off, 0), s->mb_height-1);
 unhandled:
@@ -3311,9 +3314,9 @@
     s->block_index[5]= s->mb_stride*(s->mb_y + s->mb_height + 2) + s->b8_stride*s->mb_height*2 + s->mb_x - 1;
     //block_index is not used by mpeg2, so it is not affected by chroma_format
 
-    s->dest[0] = s->current_picture.f->data[0] + ((s->mb_x - 1) <<  mb_size);
-    s->dest[1] = s->current_picture.f->data[1] + ((s->mb_x - 1) << (mb_size - s->chroma_x_shift));
-    s->dest[2] = s->current_picture.f->data[2] + ((s->mb_x - 1) << (mb_size - s->chroma_x_shift));
+    s->dest[0] = s->current_picture.f->data[0] + (int)((s->mb_x - 1U) <<  mb_size);
+    s->dest[1] = s->current_picture.f->data[1] + (int)((s->mb_x - 1U) << (mb_size - s->chroma_x_shift));
+    s->dest[2] = s->current_picture.f->data[2] + (int)((s->mb_x - 1U) << (mb_size - s->chroma_x_shift));
 
     if(!(s->pict_type==AV_PICTURE_TYPE_B && s->avctx->draw_horiz_band && s->picture_structure==PICT_FRAME))
     {
diff --git a/libavcodec/mpegvideo.h b/libavcodec/mpegvideo.h
index 81f412b..0be2024 100644
--- a/libavcodec/mpegvideo.h
+++ b/libavcodec/mpegvideo.h
@@ -443,6 +443,8 @@
     int ac_esc_length;       ///< num of bits needed to encode the longest esc
     uint8_t *intra_ac_vlc_length;
     uint8_t *intra_ac_vlc_last_length;
+    uint8_t *intra_chroma_ac_vlc_length;
+    uint8_t *intra_chroma_ac_vlc_last_length;
     uint8_t *inter_ac_vlc_length;
     uint8_t *inter_ac_vlc_last_length;
     uint8_t *luma_dc_vlc_length;
@@ -877,7 +879,7 @@
 extern const uint8_t ff_h263_chroma_qscale_table[32];
 
 /* rv10.c */
-void ff_rv10_encode_picture_header(MpegEncContext *s, int picture_number);
+int ff_rv10_encode_picture_header(MpegEncContext *s, int picture_number);
 int ff_rv_decode_dc(MpegEncContext *s, int n);
 void ff_rv20_encode_picture_header(MpegEncContext *s, int picture_number);
 
diff --git a/libavcodec/mpegvideo_enc.c b/libavcodec/mpegvideo_enc.c
index 1ecf4aa..53f584d 100644
--- a/libavcodec/mpegvideo_enc.c
+++ b/libavcodec/mpegvideo_enc.c
@@ -395,18 +395,18 @@
         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;
+            avctx->rc_buffer_size = FFMAX(avctx->rc_max_rate, 15000000) * 112LL / 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);
+                avctx->rc_buffer_size = 320 + (avctx->rc_max_rate - 15000000LL) * (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);
+                avctx->rc_buffer_size =  80 + (avctx->rc_max_rate -  2000000LL) * (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);
+                avctx->rc_buffer_size =  40 + (avctx->rc_max_rate -   384000LL) * ( 80- 40) / ( 2000000 -   384000);
             } else
                 avctx->rc_buffer_size = 40;
             avctx->rc_buffer_size *= 16384;
@@ -907,6 +907,7 @@
             s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
         } else {
             /* mpeg1/2 */
+            s->chroma_intra_matrix[j] =
             s->intra_matrix[j] = ff_mpeg1_default_intra_matrix[i];
             s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
         }
@@ -1282,6 +1283,8 @@
     int64_t best_rd  = INT64_MAX;
     int best_b_count = -1;
 
+    if (!c)
+        return AVERROR(ENOMEM);
     av_assert0(scale >= 0 && scale <= 3);
 
     //emms_c();
@@ -2725,7 +2728,7 @@
     int mb_x, mb_y, pdif = 0;
     int chr_h= 16>>s->chroma_y_shift;
     int i, j;
-    MpegEncContext best_s, backup_s;
+    MpegEncContext best_s = { 0 }, backup_s;
     uint8_t bit_buf[2][MAX_MB_BYTES];
     uint8_t bit_buf2[2][MAX_MB_BYTES];
     uint8_t bit_buf_tex[2][MAX_MB_BYTES];
@@ -3705,8 +3708,11 @@
             ff_msmpeg4_encode_picture_header(s, picture_number);
         else if (CONFIG_MPEG4_ENCODER && s->h263_pred)
             ff_mpeg4_encode_picture_header(s, picture_number);
-        else if (CONFIG_RV10_ENCODER && s->codec_id == AV_CODEC_ID_RV10)
-            ff_rv10_encode_picture_header(s, picture_number);
+        else if (CONFIG_RV10_ENCODER && s->codec_id == AV_CODEC_ID_RV10) {
+            ret = ff_rv10_encode_picture_header(s, picture_number);
+            if (ret < 0)
+                return ret;
+        }
         else if (CONFIG_RV20_ENCODER && s->codec_id == AV_CODEC_ID_RV20)
             ff_rv20_encode_picture_header(s, picture_number);
         else if (CONFIG_FLV_ENCODER && s->codec_id == AV_CODEC_ID_FLV1)
@@ -3763,6 +3769,7 @@
                                   int16_t *block, int n,
                                   int qscale, int *overflow){
     const int *qmat;
+    const uint16_t *matrix;
     const uint8_t *scantable= s->intra_scantable.scantable;
     const uint8_t *perm_scantable= s->intra_scantable.permutated;
     int max=0;
@@ -3811,14 +3818,22 @@
         start_i = 1;
         last_non_zero = 0;
         qmat = n < 4 ? s->q_intra_matrix[qscale] : s->q_chroma_intra_matrix[qscale];
-        if(s->mpeg_quant || s->out_format == FMT_MPEG1)
+        matrix = n < 4 ? s->intra_matrix : s->chroma_intra_matrix;
+        if(s->mpeg_quant || s->out_format == FMT_MPEG1 || s->out_format == FMT_MJPEG)
             bias= 1<<(QMAT_SHIFT-1);
-        length     = s->intra_ac_vlc_length;
-        last_length= s->intra_ac_vlc_last_length;
+
+        if (n > 3 && s->intra_chroma_ac_vlc_length) {
+            length     = s->intra_chroma_ac_vlc_length;
+            last_length= s->intra_chroma_ac_vlc_last_length;
+        } else {
+            length     = s->intra_ac_vlc_length;
+            last_length= s->intra_ac_vlc_last_length;
+        }
     } else {
         start_i = 0;
         last_non_zero = -1;
         qmat = s->q_inter_matrix[qscale];
+        matrix = s->inter_matrix;
         length     = s->inter_ac_vlc_length;
         last_length= s->inter_ac_vlc_last_length;
     }
@@ -3894,13 +3909,16 @@
 
             if(s->out_format == FMT_H263 || s->out_format == FMT_H261){
                 unquant_coeff= alevel*qmul + qadd;
+            } else if(s->out_format == FMT_MJPEG) {
+                j = s->idsp.idct_permutation[scantable[i]];
+                unquant_coeff = alevel * matrix[j] * 8;
             }else{ //MPEG1
                 j = s->idsp.idct_permutation[scantable[i]]; // FIXME: optimize
                 if(s->mb_intra){
-                        unquant_coeff = (int)(  alevel  * qscale * s->intra_matrix[j]) >> 3;
+                        unquant_coeff = (int)(  alevel  * qscale * matrix[j]) >> 3;
                         unquant_coeff =   (unquant_coeff - 1) | 1;
                 }else{
-                        unquant_coeff = (((  alevel  << 1) + 1) * qscale * ((int) s->inter_matrix[j])) >> 4;
+                        unquant_coeff = (((  alevel  << 1) + 1) * qscale * ((int) matrix[j])) >> 4;
                         unquant_coeff =   (unquant_coeff - 1) | 1;
                 }
                 unquant_coeff<<= 3;
@@ -4016,7 +4034,7 @@
             if(s->out_format == FMT_H263 || s->out_format == FMT_H261){
                     unquant_coeff= (alevel*qmul + qadd)>>3;
             }else{ //MPEG1
-                    unquant_coeff = (((  alevel  << 1) + 1) * qscale * ((int) s->inter_matrix[0])) >> 4;
+                    unquant_coeff = (((  alevel  << 1) + 1) * qscale * ((int) matrix[0])) >> 4;
                     unquant_coeff =   (unquant_coeff - 1) | 1;
             }
             unquant_coeff = (unquant_coeff + 4) >> 3;
@@ -4123,8 +4141,13 @@
         start_i = 1;
 //        if(s->mpeg_quant || s->out_format == FMT_MPEG1)
 //            bias= 1<<(QMAT_SHIFT-1);
-        length     = s->intra_ac_vlc_length;
-        last_length= s->intra_ac_vlc_last_length;
+        if (n > 3 && s->intra_chroma_ac_vlc_length) {
+            length     = s->intra_chroma_ac_vlc_length;
+            last_length= s->intra_chroma_ac_vlc_last_length;
+        } else {
+            length     = s->intra_ac_vlc_length;
+            last_length= s->intra_ac_vlc_last_length;
+        }
     } else {
         dc= 0;
         start_i = 0;
diff --git a/libavcodec/mpegvideo_motion.c b/libavcodec/mpegvideo_motion.c
index e7a585d..4fea847 100644
--- a/libavcodec/mpegvideo_motion.c
+++ b/libavcodec/mpegvideo_motion.c
@@ -178,7 +178,7 @@
                 s->sprite_delta[0][0], s->sprite_delta[0][1],
                 s->sprite_delta[1][0], s->sprite_delta[1][1],
                 a + 1, (1 << (2 * a + 1)) - s->no_rounding,
-                s->h_edge_pos >> 1, s->v_edge_pos >> 1);
+                (s->h_edge_pos + 1) >> 1, (s->v_edge_pos + 1) >> 1);
 
     ptr = ref_picture[2];
     s->mdsp.gmc(dest_cr, ptr, uvlinesize, 8,
@@ -186,7 +186,7 @@
                 s->sprite_delta[0][0], s->sprite_delta[0][1],
                 s->sprite_delta[1][0], s->sprite_delta[1][1],
                 a + 1, (1 << (2 * a + 1)) - s->no_rounding,
-                s->h_edge_pos >> 1, s->v_edge_pos >> 1);
+                (s->h_edge_pos + 1) >> 1, (s->v_edge_pos + 1) >> 1);
 }
 
 static inline int hpel_motion(MpegEncContext *s,
@@ -210,8 +210,8 @@
         dxy |= (motion_y & 1) << 1;
     src += src_y * s->linesize + src_x;
 
-        if ((unsigned)src_x > FFMAX(s->h_edge_pos - (motion_x & 1) - 8, 0) ||
-            (unsigned)src_y > FFMAX(s->v_edge_pos - (motion_y & 1) - 8, 0)) {
+        if ((unsigned)src_x >= FFMAX(s->h_edge_pos - (motion_x & 1) - 7, 0) ||
+            (unsigned)src_y >= FFMAX(s->v_edge_pos - (motion_y & 1) - 7, 0)) {
             s->vdsp.emulated_edge_mc(s->edge_emu_buffer, src,
                                      s->linesize, s->linesize,
                                      9, 9,
@@ -306,8 +306,8 @@
     ptr_cb = ref_picture[1] + uvsrc_y * uvlinesize + uvsrc_x;
     ptr_cr = ref_picture[2] + uvsrc_y * uvlinesize + uvsrc_x;
 
-    if ((unsigned)src_x > FFMAX(s->h_edge_pos - (motion_x & 1) - 16, 0) ||
-        (unsigned)src_y > FFMAX(   v_edge_pos - (motion_y & 1) - h , 0)) {
+    if ((unsigned)src_x >= FFMAX(s->h_edge_pos - (motion_x & 1) - 15   , 0) ||
+        (unsigned)src_y >= FFMAX(   v_edge_pos - (motion_y & 1) - h + 1, 0)) {
         if (is_mpeg12 ||
             s->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
             s->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
@@ -316,24 +316,26 @@
                    src_y);
             return;
         }
+        src_y = (unsigned)src_y << field_based;
         s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr_y,
                                  s->linesize, s->linesize,
                                  17, 17 + field_based,
-                                 src_x, src_y << field_based,
+                                 src_x, src_y,
                                  s->h_edge_pos, s->v_edge_pos);
         ptr_y = s->edge_emu_buffer;
         if (!CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
             uint8_t *ubuf = s->edge_emu_buffer + 18 * s->linesize;
             uint8_t *vbuf = ubuf + 9 * s->uvlinesize;
+            uvsrc_y = (unsigned)uvsrc_y << field_based;
             s->vdsp.emulated_edge_mc(ubuf, ptr_cb,
                                      s->uvlinesize, s->uvlinesize,
                                      9, 9 + field_based,
-                                     uvsrc_x, uvsrc_y << field_based,
+                                     uvsrc_x, uvsrc_y,
                                      s->h_edge_pos >> 1, s->v_edge_pos >> 1);
             s->vdsp.emulated_edge_mc(vbuf, ptr_cr,
                                      s->uvlinesize, s->uvlinesize,
                                      9, 9 + field_based,
-                                     uvsrc_x, uvsrc_y << field_based,
+                                     uvsrc_x, uvsrc_y,
                                      s->h_edge_pos >> 1, s->v_edge_pos >> 1);
             ptr_cb = ubuf;
             ptr_cr = vbuf;
@@ -536,8 +538,8 @@
     ptr_cb = ref_picture[1] + uvsrc_y * uvlinesize + uvsrc_x;
     ptr_cr = ref_picture[2] + uvsrc_y * uvlinesize + uvsrc_x;
 
-    if ((unsigned)src_x > FFMAX(s->h_edge_pos - (motion_x & 3) - 16, 0) ||
-        (unsigned)src_y > FFMAX(   v_edge_pos - (motion_y & 3) - h, 0)) {
+    if ((unsigned)src_x >= FFMAX(s->h_edge_pos - (motion_x & 3) - 15   , 0) ||
+        (unsigned)src_y >= FFMAX(   v_edge_pos - (motion_y & 3) - h + 1, 0)) {
         s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr_y,
                                  s->linesize, s->linesize,
                                  17, 17 + field_based,
@@ -620,8 +622,8 @@
 
     offset = src_y * s->uvlinesize + src_x;
     ptr    = ref_picture[1] + offset;
-    if ((unsigned)src_x > FFMAX((s->h_edge_pos >> 1) - (dxy & 1) - 8, 0) ||
-        (unsigned)src_y > FFMAX((s->v_edge_pos >> 1) - (dxy >> 1) - 8, 0)) {
+    if ((unsigned)src_x >= FFMAX((s->h_edge_pos >> 1) - (dxy  & 1) - 7, 0) ||
+        (unsigned)src_y >= FFMAX((s->v_edge_pos >> 1) - (dxy >> 1) - 7, 0)) {
         s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr,
                                  s->uvlinesize, s->uvlinesize,
                                  9, 9, src_x, src_y,
@@ -778,8 +780,8 @@
                 dxy &= ~12;
 
             ptr = ref_picture[0] + (src_y * s->linesize) + (src_x);
-            if ((unsigned)src_x > FFMAX(s->h_edge_pos - (motion_x & 3) - 8, 0) ||
-                (unsigned)src_y > FFMAX(s->v_edge_pos - (motion_y & 3) - 8, 0)) {
+            if ((unsigned)src_x >= FFMAX(s->h_edge_pos - (motion_x & 3) - 7, 0) ||
+                (unsigned)src_y >= FFMAX(s->v_edge_pos - (motion_y & 3) - 7, 0)) {
                 s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr,
                                          s->linesize, s->linesize,
                                          9, 9,
diff --git a/libavcodec/msrledec.c b/libavcodec/msrledec.c
index 4d3da5b..c738198 100644
--- a/libavcodec/msrledec.c
+++ b/libavcodec/msrledec.c
@@ -37,16 +37,14 @@
     unsigned char extra_byte, odd_pixel;
     unsigned char stream_byte;
     unsigned int pixel_ptr = 0;
-    int row_dec = pic->linesize[0];
-    int row_ptr = (avctx->height - 1) * row_dec;
-    int frame_size = row_dec * avctx->height;
+    int line = avctx->height - 1;
     int i;
 
-    while (row_ptr >= 0) {
+    while (line >= 0 && pixel_ptr <= avctx->width) {
         if (bytestream2_get_bytes_left(gb) <= 0) {
             av_log(avctx, AV_LOG_ERROR,
-                   "MS RLE: bytestream overrun, %d rows left\n",
-                   row_ptr);
+                   "MS RLE: bytestream overrun, %dx%d left\n",
+                   avctx->width - pixel_ptr, line);
             return AVERROR_INVALIDDATA;
         }
         rle_code = stream_byte = bytestream2_get_byteu(gb);
@@ -55,7 +53,7 @@
             stream_byte = bytestream2_get_byte(gb);
             if (stream_byte == 0) {
                 /* line is done, goto the next one */
-                row_ptr -= row_dec;
+                line--;
                 pixel_ptr = 0;
             } else if (stream_byte == 1) {
                 /* decode is done */
@@ -65,13 +63,12 @@
                 stream_byte = bytestream2_get_byte(gb);
                 pixel_ptr += stream_byte;
                 stream_byte = bytestream2_get_byte(gb);
-                row_ptr -= stream_byte * row_dec;
             } else {
                 // copy pixels from encoded stream
                 odd_pixel =  stream_byte & 1;
                 rle_code = (stream_byte + 1) / 2;
                 extra_byte = rle_code & 0x01;
-                if (row_ptr + pixel_ptr + stream_byte > frame_size ||
+                if (pixel_ptr + 2*rle_code - odd_pixel > avctx->width ||
                     bytestream2_get_bytes_left(gb) < rle_code) {
                     av_log(avctx, AV_LOG_ERROR,
                            "MS RLE: frame/stream ptr just went out of bounds (copy)\n");
@@ -82,13 +79,13 @@
                     if (pixel_ptr >= avctx->width)
                         break;
                     stream_byte = bytestream2_get_byteu(gb);
-                    pic->data[0][row_ptr + pixel_ptr] = stream_byte >> 4;
+                    pic->data[0][line * pic->linesize[0] + pixel_ptr] = stream_byte >> 4;
                     pixel_ptr++;
                     if (i + 1 == rle_code && odd_pixel)
                         break;
                     if (pixel_ptr >= avctx->width)
                         break;
-                    pic->data[0][row_ptr + pixel_ptr] = stream_byte & 0x0F;
+                    pic->data[0][line * pic->linesize[0] + pixel_ptr] = stream_byte & 0x0F;
                     pixel_ptr++;
                 }
 
@@ -98,9 +95,9 @@
             }
         } else {
             // decode a run of data
-            if (row_ptr + pixel_ptr + stream_byte > frame_size) {
+            if (pixel_ptr + rle_code > avctx->width + 1) {
                 av_log(avctx, AV_LOG_ERROR,
-                       "MS RLE: frame ptr just went out of bounds (run)\n");
+                       "MS RLE: frame ptr just went out of bounds (run) %d %d %d\n", pixel_ptr, rle_code, avctx->width);
                 return AVERROR_INVALIDDATA;
             }
             stream_byte = bytestream2_get_byte(gb);
@@ -108,9 +105,9 @@
                 if (pixel_ptr >= avctx->width)
                     break;
                 if ((i & 1) == 0)
-                    pic->data[0][row_ptr + pixel_ptr] = stream_byte >> 4;
+                    pic->data[0][line * pic->linesize[0] + pixel_ptr] = stream_byte >> 4;
                 else
-                    pic->data[0][row_ptr + pixel_ptr] = stream_byte & 0x0F;
+                    pic->data[0][line * pic->linesize[0] + pixel_ptr] = stream_byte & 0x0F;
                 pixel_ptr++;
             }
         }
diff --git a/libavcodec/mss4.c b/libavcodec/mss4.c
index c5b8e07..00c31dd 100644
--- a/libavcodec/mss4.c
+++ b/libavcodec/mss4.c
@@ -572,7 +572,8 @@
             ff_mss34_gen_quant_mat(c->quant_mat[i], quality, !i);
     }
 
-    init_get_bits8(&gb, buf + HEADER_SIZE, (buf_size - HEADER_SIZE));
+    if ((ret = init_get_bits8(&gb, buf + HEADER_SIZE, buf_size - HEADER_SIZE)) < 0)
+        return ret;
 
     mb_width  = FFALIGN(width,  16) >> 4;
     mb_height = FFALIGN(height, 16) >> 4;
@@ -650,7 +651,7 @@
     }
     for (i = 0; i < 3; i++) {
         c->dc_stride[i] = FFALIGN(avctx->width, 16) >> (2 + !!i);
-        c->prev_dc[i]   = av_malloc(sizeof(**c->prev_dc) * c->dc_stride[i]);
+        c->prev_dc[i]   = av_malloc_array(c->dc_stride[i], sizeof(**c->prev_dc));
         if (!c->prev_dc[i]) {
             av_log(avctx, AV_LOG_ERROR, "Cannot allocate buffer\n");
             mss4_free_vlcs(c);
diff --git a/libavcodec/mxpegdec.c b/libavcodec/mxpegdec.c
index fbd4767..05c74ee 100644
--- a/libavcodec/mxpegdec.c
+++ b/libavcodec/mxpegdec.c
@@ -345,4 +345,5 @@
     .decode         = mxpeg_decode_frame,
     .capabilities   = CODEC_CAP_DR1,
     .max_lowres     = 3,
+    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE,
 };
diff --git a/libavcodec/nellymoserdec.c b/libavcodec/nellymoserdec.c
index 2d8a594..d5a69ed 100644
--- a/libavcodec/nellymoserdec.c
+++ b/libavcodec/nellymoserdec.c
@@ -37,7 +37,6 @@
 #include "libavutil/random_seed.h"
 #include "avcodec.h"
 #include "fft.h"
-#include "fmtconvert.h"
 #include "internal.h"
 #include "nellymoser.h"
 #include "sinewin.h"
diff --git a/libavcodec/nellymoserenc.c b/libavcodec/nellymoserenc.c
index 48caba2..7c77ff7 100644
--- a/libavcodec/nellymoserenc.c
+++ b/libavcodec/nellymoserenc.c
@@ -271,7 +271,7 @@
                 }
             }
         }
-        assert(c); //FIXME
+        av_assert1(c); //FIXME
     }
 
     best_val = INFINITY;
@@ -308,7 +308,7 @@
 
     apply_mdct(s);
 
-    init_put_bits(&pb, output, output_size * 8);
+    init_put_bits(&pb, output, output_size);
 
     i = 0;
     for (band = 0; band < NELLY_BANDS; band++) {
diff --git a/libavcodec/nuv.c b/libavcodec/nuv.c
index 048ad6f..e0cec52 100644
--- a/libavcodec/nuv.c
+++ b/libavcodec/nuv.c
@@ -33,7 +33,7 @@
 #include "internal.h"
 #include "rtjpeg.h"
 
-typedef struct {
+typedef struct NuvContext {
     AVFrame *pic;
     int codec_frameheader;
     int quality;
diff --git a/libavcodec/nvenc.c b/libavcodec/nvenc.c
index 2cfc06a..0dec720 100644
--- a/libavcodec/nvenc.c
+++ b/libavcodec/nvenc.c
@@ -67,10 +67,6 @@
 
 typedef NVENCSTATUS (NVENCAPI* PNVENCODEAPICREATEINSTANCE)(NV_ENCODE_API_FUNCTION_LIST *functionList);
 
-#if NVENCAPI_MAJOR_VERSION < 5
-static const GUID dummy_license = { 0x0, 0x0, 0x0, { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 } };
-#endif
-
 typedef struct NvencInputSurface
 {
     NV_ENC_INPUT_PTR input_surface;
@@ -474,10 +470,6 @@
     int res = 0;
     int dw, dh;
 
-#if NVENCAPI_MAJOR_VERSION < 5
-    GUID license = dummy_license;
-#endif
-
     NvencContext *ctx = avctx->priv_data;
     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
@@ -500,10 +492,6 @@
     encode_session_params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
     encode_session_params.apiVersion = NVENCAPI_VERSION;
 
-#if NVENCAPI_MAJOR_VERSION < 5
-    encode_session_params.clientKeyPtr = &license;
-#endif
-
     if (ctx->gpu >= dl_fn->nvenc_device_count) {
         av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->gpu, dl_fn->nvenc_device_count);
         res = AVERROR(EINVAL);
@@ -587,6 +575,18 @@
         ctx->init_encode_params.darWidth = avctx->width;
     }
 
+    // De-compensate for hardware, dubiously, trying to compensate for
+    // playback at 704 pixel width.
+    if (avctx->width == 720 &&
+        (avctx->height == 480 || avctx->height == 576)) {
+        av_reduce(&dw, &dh,
+                  ctx->init_encode_params.darWidth * 44,
+                  ctx->init_encode_params.darHeight * 45,
+                  1024 * 1204);
+        ctx->init_encode_params.darHeight = dh;
+        ctx->init_encode_params.darWidth = dw;
+    }
+
     ctx->init_encode_params.frameRateNum = avctx->time_base.den;
     ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
 
@@ -1096,10 +1096,6 @@
         pic_params.codecPicParams.h264PicParams.sliceMode = ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
         pic_params.codecPicParams.h264PicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
 
-#if NVENCAPI_MAJOR_VERSION < 5
-        memcpy(&pic_params.rcParams, &ctx->encode_config.rcParams, sizeof(NV_ENC_RC_PARAMS));
-#endif
-
         res = timestamp_queue_enqueue(&ctx->timestamp_list, frame->pts);
 
         if (res)
diff --git a/libavcodec/on2avc.c b/libavcodec/on2avc.c
index 9bf5e87..4a38da0 100644
--- a/libavcodec/on2avc.c
+++ b/libavcodec/on2avc.c
@@ -795,7 +795,9 @@
     GetBitContext gb;
     int i, ret;
 
-    init_get_bits(&gb, buf, buf_size * 8);
+    if ((ret = init_get_bits8(&gb, buf, buf_size)) < 0)
+        return ret;
+
     if (get_bits1(&gb)) {
         av_log(c->avctx, AV_LOG_ERROR, "enh bit set\n");
         return AVERROR_INVALIDDATA;
@@ -846,10 +848,8 @@
     if (c->is_av500) {
         /* get output buffer */
         frame->nb_samples = ON2AVC_SUBFRAME_SIZE;
-        if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
-            av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+        if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
             return ret;
-        }
 
         if ((ret = on2avc_decode_subframe(c, buf, buf_size, frame, 0)) < 0)
             return ret;
@@ -872,10 +872,8 @@
 
         /* get output buffer */
         frame->nb_samples = ON2AVC_SUBFRAME_SIZE * num_frames;
-        if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
-            av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+        if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
             return ret;
-        }
 
         audio_off = 0;
         bytestream2_init(&gb, buf, buf_size);
diff --git a/libavcodec/options_table.h b/libavcodec/options_table.h
index 442b212..a906864 100644
--- a/libavcodec/options_table.h
+++ b/libavcodec/options_table.h
@@ -103,7 +103,6 @@
 {"hex", "hex motion estimation", 0, AV_OPT_TYPE_CONST, {.i64 = ME_HEX }, INT_MIN, INT_MAX, V|E, "me_method" },
 {"umh", "umh motion estimation", 0, AV_OPT_TYPE_CONST, {.i64 = ME_UMH }, INT_MIN, INT_MAX, V|E, "me_method" },
 {"iter", "iter motion estimation", 0, AV_OPT_TYPE_CONST, {.i64 = ME_ITER }, INT_MIN, INT_MAX, V|E, "me_method" },
-{"extradata_size", NULL, OFFSET(extradata_size), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
 {"time_base", NULL, OFFSET(time_base), AV_OPT_TYPE_RATIONAL, {.dbl = 0}, INT_MIN, INT_MAX},
 {"g", "set the group of picture (GOP) size", OFFSET(gop_size), AV_OPT_TYPE_INT, {.i64 = 12 }, INT_MIN, INT_MAX, V|E},
 {"ar", "set audio sampling rate (in Hz)", OFFSET(sample_rate), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, 0, INT_MAX, A|D|E},
diff --git a/libavcodec/opus_celt.c b/libavcodec/opus_celt.c
index 4f3212b..e5d615e 100644
--- a/libavcodec/opus_celt.c
+++ b/libavcodec/opus_celt.c
@@ -28,8 +28,8 @@
 
 #include "libavutil/float_dsp.h"
 
+#include "imdct15.h"
 #include "opus.h"
-#include "opus_imdct.h"
 
 enum CeltSpread {
     CELT_SPREAD_NONE,
@@ -61,7 +61,7 @@
 struct CeltContext {
     // constant values that do not change during context lifetime
     AVCodecContext    *avctx;
-    CeltIMDCTContext  *imdct[4];
+    IMDCT15Context    *imdct[4];
     AVFloatDSPContext  *dsp;
     int output_channels;
 
@@ -1909,7 +1909,7 @@
         s->remaining2 = totalbits - consumed - 1;
         if (i <= s->codedbands - 1) {
             int curr_balance = s->remaining / FFMIN(3, s->codedbands-i);
-            b = av_clip(FFMIN(s->remaining2 + 1, s->pulses[i] + curr_balance), 0, 16383);
+            b = av_clip_uintp2(FFMIN(s->remaining2 + 1, s->pulses[i] + curr_balance), 14);
         } else
             b = 0;
 
@@ -1983,7 +1983,7 @@
     int silence = 0;
     int transient = 0;
     int anticollapse = 0;
-    CeltIMDCTContext *imdct;
+    IMDCT15Context *imdct;
     float imdct_scale = 1.0;
 
     if (coded_channels != 1 && coded_channels != 2) {
@@ -2179,7 +2179,7 @@
         return;
 
     for (i = 0; i < FF_ARRAY_ELEMS(s->imdct); i++)
-        ff_celt_imdct_uninit(&s->imdct[i]);
+        ff_imdct15_uninit(&s->imdct[i]);
 
     av_freep(&s->dsp);
     av_freep(ps);
@@ -2204,7 +2204,7 @@
     s->output_channels = output_channels;
 
     for (i = 0; i < FF_ARRAY_ELEMS(s->imdct); i++) {
-        ret = ff_celt_imdct_init(&s->imdct[i], i + 3);
+        ret = ff_imdct15_init(&s->imdct[i], i + 3);
         if (ret < 0)
             goto fail;
     }
diff --git a/libavcodec/opus_silk.c b/libavcodec/opus_silk.c
index 7a89479..841d1ed 100644
--- a/libavcodec/opus_silk.c
+++ b/libavcodec/opus_silk.c
@@ -1077,7 +1077,7 @@
         weight = y + ((213 * fpart * y) >> 16);
 
         value = cur * 128 + (lsf_res[i] * 16384) / weight;
-        nlsf[i] = av_clip(value, 0, 32767);
+        nlsf[i] = av_clip_uintp2(value, 15);
     }
 
     /* stabilize the NLSF coefficients */
@@ -1288,8 +1288,8 @@
         } else {
             /* gain is coded relative */
             int delta_gain = opus_rc_getsymbol(rc, silk_model_gain_delta);
-            log_gain = av_clip(FFMAX((delta_gain<<1) - 16,
-                                     frame->log_gain + delta_gain - 4), 0, 63);
+            log_gain = av_clip_uintp2(FFMAX((delta_gain<<1) - 16,
+                                     frame->log_gain + delta_gain - 4), 6);
         }
 
         frame->log_gain = log_gain;
diff --git a/libavcodec/opusdec.c b/libavcodec/opusdec.c
index 759eaa5..2ee3f2a 100644
--- a/libavcodec/opusdec.c
+++ b/libavcodec/opusdec.c
@@ -43,8 +43,6 @@
 #include "libswresample/swresample.h"
 
 #include "avcodec.h"
-#include "celp_filters.h"
-#include "fft.h"
 #include "get_bits.h"
 #include "internal.h"
 #include "mathops.h"
@@ -451,6 +449,14 @@
     int coded_samples   = 0;
     int decoded_samples = 0;
     int i, ret;
+    int delayed_samples = 0;
+
+    for (i = 0; i < c->nb_streams; i++) {
+        OpusStreamContext *s = &c->streams[i];
+        s->out[0] =
+        s->out[1] = NULL;
+        delayed_samples = FFMAX(delayed_samples, s->delayed_samples);
+    }
 
     /* decode the header of the first sub-packet to find out the sample count */
     if (buf) {
@@ -464,7 +470,7 @@
         c->streams[0].silk_samplerate = get_silk_samplerate(pkt->config);
     }
 
-    frame->nb_samples = coded_samples + c->streams[0].delayed_samples;
+    frame->nb_samples = coded_samples + delayed_samples;
 
     /* no input or buffered data => nothing to do */
     if (!frame->nb_samples) {
@@ -474,10 +480,8 @@
 
     /* setup the data buffers */
     ret = ff_get_buffer(avctx, frame, 0);
-    if (ret < 0) {
-        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+    if (ret < 0)
         return ret;
-    }
     frame->nb_samples = 0;
 
     for (i = 0; i < avctx->channels; i++) {
diff --git a/libavcodec/parser.c b/libavcodec/parser.c
index aa25481..59a3c75 100644
--- a/libavcodec/parser.c
+++ b/libavcodec/parser.c
@@ -28,6 +28,7 @@
 #include "libavutil/mem.h"
 
 #include "parser.h"
+#include "internal.h"
 
 static AVCodecParser *av_first_parser = NULL;
 
@@ -85,6 +86,8 @@
     s->dts_sync_point       = INT_MIN;
     s->dts_ref_dts_delta    = INT_MIN;
     s->pts_dts_delta        = INT_MIN;
+    s->format               = -1;
+
     return s;
 
 err_out:
@@ -308,13 +311,14 @@
 
 int ff_mpeg4video_split(AVCodecContext *avctx, const uint8_t *buf, int buf_size)
 {
-    int i;
     uint32_t state = -1;
+    const uint8_t *ptr = buf, *end = buf + buf_size;
 
-    for (i = 0; i < buf_size; i++) {
-        state = state << 8 | buf[i];
+    while (ptr < end) {
+        ptr = avpriv_find_start_code(ptr, end, &state);
         if (state == 0x1B3 || state == 0x1B6)
-            return i - 3;
+            return ptr - 4 - buf;
     }
+
     return 0;
 }
diff --git a/libavcodec/pcxenc.c b/libavcodec/pcxenc.c
index f48063b..a718428 100644
--- a/libavcodec/pcxenc.c
+++ b/libavcodec/pcxenc.c
@@ -69,7 +69,7 @@
 
     // check worst-case upper bound on dst_size
     if (dst_size < 2LL * src_plane_size * nplanes || src_plane_size <= 0)
-        return -1;
+        return AVERROR(EINVAL);
 
     for (p = 0; p < nplanes; p++) {
         int count = 1;
@@ -114,7 +114,7 @@
 
     if (avctx->width > 65535 || avctx->height > 65535) {
         av_log(avctx, AV_LOG_ERROR, "image dimensions do not fit in 16 bits\n");
-        return -1;
+        return AVERROR(EINVAL);
     }
 
     switch (avctx->pix_fmt) {
@@ -144,7 +144,7 @@
         break;
     default:
         av_log(avctx, AV_LOG_ERROR, "unsupported pixfmt\n");
-        return -1;
+        return AVERROR(EINVAL);
     }
 
     line_bytes = (avctx->width * bpp + 7) >> 3;
@@ -186,7 +186,7 @@
         if ((written = pcx_rle_encode(buf, buf_end - buf,
                                       src, line_bytes, nplanes)) < 0) {
             av_log(avctx, AV_LOG_ERROR, "buffer too small\n");
-            return -1;
+            return AVERROR_BUG;
         }
         buf += written;
         src += frame->linesize[0];
@@ -195,7 +195,7 @@
     if (nplanes == 1 && bpp == 8) {
         if (buf_end - buf < 257) {
             av_log(avctx, AV_LOG_ERROR, "buffer too small\n");
-            return -1;
+            return AVERROR_BUG;
         }
         bytestream_put_byte(&buf, 12);
         for (i = 0; i < 256; i++) {
diff --git a/libavcodec/pngenc.c b/libavcodec/pngenc.c
index ef33332..9bdefc4 100644
--- a/libavcodec/pngenc.c
+++ b/libavcodec/pngenc.c
@@ -26,7 +26,9 @@
 #include "png.h"
 
 #include "libavutil/avassert.h"
+#include "libavutil/libm.h"
 #include "libavutil/opt.h"
+#include "libavutil/color_utils.h"
 
 #include <zlib.h>
 
@@ -231,6 +233,59 @@
     return 0;
 }
 
+#define AV_WB32_PNG(buf, n) AV_WB32(buf, lrint((n) * 100000))
+static int png_get_chrm(enum AVColorPrimaries prim,  uint8_t *buf)
+{
+    double rx, ry, gx, gy, bx, by, wx = 0.3127, wy = 0.3290;
+    switch (prim) {
+        case AVCOL_PRI_BT709:
+            rx = 0.640; ry = 0.330;
+            gx = 0.300; gy = 0.600;
+            bx = 0.150; by = 0.060;
+            break;
+        case AVCOL_PRI_BT470M:
+            rx = 0.670; ry = 0.330;
+            gx = 0.210; gy = 0.710;
+            bx = 0.140; by = 0.080;
+            wx = 0.310; wy = 0.316;
+            break;
+        case AVCOL_PRI_BT470BG:
+            rx = 0.640; ry = 0.330;
+            gx = 0.290; gy = 0.600;
+            bx = 0.150; by = 0.060;
+            break;
+        case AVCOL_PRI_SMPTE170M:
+        case AVCOL_PRI_SMPTE240M:
+            rx = 0.630; ry = 0.340;
+            gx = 0.310; gy = 0.595;
+            bx = 0.155; by = 0.070;
+            break;
+        case AVCOL_PRI_BT2020:
+            rx = 0.708; ry = 0.292;
+            gx = 0.170; gy = 0.797;
+            bx = 0.131; by = 0.046;
+            break;
+        default:
+            return 0;
+    }
+
+    AV_WB32_PNG(buf     , wx); AV_WB32_PNG(buf + 4 , wy);
+    AV_WB32_PNG(buf + 8 , rx); AV_WB32_PNG(buf + 12, ry);
+    AV_WB32_PNG(buf + 16, gx); AV_WB32_PNG(buf + 20, gy);
+    AV_WB32_PNG(buf + 24, bx); AV_WB32_PNG(buf + 28, by);
+    return 1;
+}
+
+static int png_get_gama(enum AVColorTransferCharacteristic trc, uint8_t *buf)
+{
+    double gamma = avpriv_get_gamma_from_trc(trc);
+    if (gamma <= 1e-6)
+        return 0;
+
+    AV_WB32_PNG(buf, 1.0 / gamma);
+    return 1;
+}
+
 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
                         const AVFrame *pict, int *got_packet)
 {
@@ -358,6 +413,18 @@
     }
     png_write_chunk(&s->bytestream, MKTAG('p', 'H', 'Y', 's'), s->buf, 9);
 
+    /* write colorspace information */
+    if (pict->color_primaries == AVCOL_PRI_BT709 &&
+        pict->color_trc == AVCOL_TRC_IEC61966_2_1) {
+        s->buf[0] = 1; /* rendering intent, relative colorimetric by default */
+        png_write_chunk(&s->bytestream, MKTAG('s', 'R', 'G', 'B'), s->buf, 1);
+    }
+
+    if (png_get_chrm(pict->color_primaries, s->buf))
+        png_write_chunk(&s->bytestream, MKTAG('c', 'H', 'R', 'M'), s->buf, 32);
+    if (png_get_gama(pict->color_trc, s->buf))
+        png_write_chunk(&s->bytestream, MKTAG('g', 'A', 'M', 'A'), s->buf, 4);
+
     /* put the palette if needed */
     if (color_type == PNG_COLOR_TYPE_PALETTE) {
         int has_alpha, alpha, i;
diff --git a/libavcodec/ppc/Makefile b/libavcodec/ppc/Makefile
index 6f7eeb7..30d04b8 100644
--- a/libavcodec/ppc/Makefile
+++ b/libavcodec/ppc/Makefile
@@ -1,11 +1,10 @@
-OBJS                                   += ppc/fmtconvert_altivec.o      \
-
 # subsystems
 OBJS-$(CONFIG_AUDIODSP)                += ppc/audiodsp.o
 OBJS-$(CONFIG_BLOCKDSP)                += ppc/blockdsp.o
 OBJS-$(CONFIG_FFT)                     += ppc/fft_init.o                \
                                           ppc/fft_altivec.o             \
                                           ppc/fft_vsx.o
+OBJS-$(CONFIG_FMTCONVERT)              += ppc/fmtconvert_altivec.o
 OBJS-$(CONFIG_H264CHROMA)              += ppc/h264chroma_init.o
 OBJS-$(CONFIG_H264DSP)                 += ppc/h264dsp.o ppc/hpeldsp_altivec.o
 OBJS-$(CONFIG_H264QPEL)                += ppc/h264qpel.o
diff --git a/libavcodec/ppc/fdctdsp.c b/libavcodec/ppc/fdctdsp.c
index f2efc5d..40f4c6c 100644
--- a/libavcodec/ppc/fdctdsp.c
+++ b/libavcodec/ppc/fdctdsp.c
@@ -196,7 +196,7 @@
 void ff_fdct_altivec(int16_t *block)
 {
     vector signed short *bp;
-    vector float *cp = fdctconsts;
+    const vector float *cp = fdctconsts;
     vector float b00, b10, b20, b30, b40, b50, b60, b70;
     vector float b01, b11, b21, b31, b41, b51, b61, b71;
     vector float mzero, cnst, cnsts0, cnsts1, cnsts2;
diff --git a/libavcodec/ppc/fmtconvert_altivec.c b/libavcodec/ppc/fmtconvert_altivec.c
index 10a7169..7323eff 100644
--- a/libavcodec/ppc/fmtconvert_altivec.c
+++ b/libavcodec/ppc/fmtconvert_altivec.c
@@ -52,113 +52,6 @@
     }
 }
 
-
-static vector signed short float_to_int16_one_altivec(const float *src)
-{
-    vector float s0 = vec_ld(0, src);
-    vector float s1 = vec_ld(16, src);
-    vector signed int t0 = vec_cts(s0, 0);
-    vector signed int t1 = vec_cts(s1, 0);
-    return vec_packs(t0,t1);
-}
-
-static void float_to_int16_altivec(int16_t *dst, const float *src, long len)
-{
-    int i;
-    vector signed short d0, d1, d;
-    vector unsigned char align;
-    if (((long)dst) & 15) { //FIXME
-        for (i = 0; i < len - 7; i += 8) {
-            d0 = vec_ld(0, dst+i);
-            d  = float_to_int16_one_altivec(src + i);
-            d1 = vec_ld(15, dst+i);
-            d1 = vec_perm(d1, d0, vec_lvsl(0, dst + i));
-            align = vec_lvsr(0, dst + i);
-            d0 = vec_perm(d1, d, align);
-            d1 = vec_perm(d, d1, align);
-            vec_st(d0,  0, dst + i);
-            vec_st(d1, 15, dst + i);
-        }
-    } else {
-        for (i = 0; i < len - 7; i += 8) {
-            d = float_to_int16_one_altivec(src + i);
-            vec_st(d, 0, dst + i);
-        }
-    }
-}
-
-#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;
-
-    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)
-{
-    int i;
-    vector signed short d0, d1, d2, c0, c1, t0, t1;
-    vector unsigned char align;
-
-    if (channels == 1)
-        float_to_int16_altivec(dst, src[0], len);
-    else {
-        if (channels == 2) {
-            if (((long)dst) & 15) {
-                for (i = 0; i < len - 7; i += 8) {
-                    d0 = vec_ld(0,  dst + i);
-                    t0 = float_to_int16_one_altivec(src[0] + i);
-                    d1 = vec_ld(31, dst + i);
-                    t1 = float_to_int16_one_altivec(src[1] + i);
-                    c0 = vec_mergeh(t0, t1);
-                    c1 = vec_mergel(t0, t1);
-                    d2 = vec_perm(d1, d0, vec_lvsl(0, dst + i));
-                    align = vec_lvsr(0, dst + i);
-                    d0 = vec_perm(d2, c0, align);
-                    d1 = vec_perm(c0, c1, align);
-                    vec_st(d0,  0, dst + i);
-                    d0 = vec_perm(c1, d2, align);
-                    vec_st(d1, 15, dst + i);
-                    vec_st(d0, 31, dst + i);
-                    dst += 8;
-                }
-            } else {
-                for (i = 0; i < len - 7; i += 8) {
-                    t0 = float_to_int16_one_altivec(src[0] + i);
-                    t1 = float_to_int16_one_altivec(src[1] + i);
-                    d0 = vec_mergeh(t0, t1);
-                    d1 = vec_mergel(t0, t1);
-                    vec_st(d0,  0, dst + i);
-                    vec_st(d1, 16, dst + i);
-                    dst += 8;
-                }
-            }
-        } else {
-            for (i = 0; i < channels; i++)
-                float_to_int16_stride_altivec(dst + i, src[i], len, channels);
-        }
-    }
-}
-
 #endif /* HAVE_ALTIVEC */
 
 av_cold void ff_fmt_convert_init_ppc(FmtConvertContext *c,
@@ -169,9 +62,5 @@
         return;
 
     c->int32_to_float_fmul_scalar = int32_to_float_fmul_scalar_altivec;
-    if (!(avctx->flags & CODEC_FLAG_BITEXACT)) {
-        c->float_to_int16 = float_to_int16_altivec;
-        c->float_to_int16_interleave = float_to_int16_interleave_altivec;
-    }
 #endif /* HAVE_ALTIVEC */
 }
diff --git a/libavcodec/ppc/h264qpel_template.c b/libavcodec/ppc/h264qpel_template.c
index 9a34548..0e5ecbd 100644
--- a/libavcodec/ppc/h264qpel_template.c
+++ b/libavcodec/ppc/h264qpel_template.c
@@ -23,15 +23,12 @@
 #include <unistd.h>
 #endif
 
+#include "libavutil/avassert.h"
 #include "libavutil/mem.h"
 #include "libavutil/ppc/types_altivec.h"
 #include "libavutil/ppc/util_altivec.h"
 
-#ifdef DEBUG
-#define ASSERT_ALIGNED(ptr) assert(((unsigned long)ptr&0x0000000F));
-#else
-#define ASSERT_ALIGNED(ptr) ;
-#endif
+#define ASSERT_ALIGNED(ptr) av_assert2(((unsigned long)ptr&0x0000000F));
 
 #if HAVE_BIGENDIAN
 #define load_alignment(s, ali, pm2, pm1, pp0, pp1, pp2, pp3){\
diff --git a/libavcodec/ppc/idctdsp.c b/libavcodec/ppc/idctdsp.c
index 5ef514b..ea56a70 100644
--- a/libavcodec/ppc/idctdsp.c
+++ b/libavcodec/ppc/idctdsp.c
@@ -209,16 +209,26 @@
 
     IDCT;
 
+#if HAVE_BIGENDIAN
     p0    = vec_lvsl(0, dest);
     p1    = vec_lvsl(stride, dest);
     p     = vec_splat_u8(-1);
     perm0 = vec_mergeh(p, p0);
     perm1 = vec_mergeh(p, p1);
+#endif
+
+#if HAVE_BIGENDIAN
+#define GET_TMP2(dest, prm)                                 \
+    tmp  = vec_ld(0, dest);                                 \
+    tmp2 = (vec_s16) vec_perm(tmp, (vec_u8) zero, prm);
+#else
+#define GET_TMP2(dest, prm)                                 \
+    tmp  = vec_vsx_ld(0, dest);                             \
+    tmp2 = (vec_s16) vec_mergeh(tmp, (vec_u8) zero)
+#endif
 
 #define ADD(dest, src, perm)                                \
-    /* *(uint64_t *) &tmp = *(uint64_t *) dest; */          \
-    tmp  = vec_ld(0, dest);                                 \
-    tmp2 = (vec_s16) vec_perm(tmp, (vec_u8) zero, perm);    \
+    GET_TMP2(dest, perm);                                   \
     tmp3 = vec_adds(tmp2, src);                             \
     tmp  = vec_packsu(tmp3, tmp3);                          \
     vec_ste((vec_u32) tmp, 0, (unsigned int *) dest);       \
diff --git a/libavcodec/ppc/mpegvideo_altivec.c b/libavcodec/ppc/mpegvideo_altivec.c
index ce53ae4..1b6bda6 100644
--- a/libavcodec/ppc/mpegvideo_altivec.c
+++ b/libavcodec/ppc/mpegvideo_altivec.c
@@ -42,8 +42,6 @@
     int i, level, qmul, qadd;
     int nCoeffs;
 
-    assert(s->block_last_index[n]>=0);
-
     qadd = (qscale - 1) | 1;
     qmul = qscale << 1;
 
@@ -59,6 +57,7 @@
         nCoeffs= 63; //does not always use zigzag table
     } else {
         i = 0;
+        av_assert2(s->block_last_index[n]>=0);
         nCoeffs= s->intra_scantable.raster_end[ s->block_last_index[n] ];
     }
 
diff --git a/libavcodec/proresdec_lgpl.c b/libavcodec/proresdec_lgpl.c
index a2ee419..4bdf392 100644
--- a/libavcodec/proresdec_lgpl.c
+++ b/libavcodec/proresdec_lgpl.c
@@ -40,7 +40,7 @@
 #include "proresdsp.h"
 #include "get_bits.h"
 
-typedef struct {
+typedef struct ProresThreadData {
     const uint8_t *index;            ///< pointers to the data of this slice
     int slice_num;
     int x_pos, y_pos;
@@ -51,7 +51,7 @@
     DECLARE_ALIGNED(16, int16_t, qmat_chroma_scaled)[64];
 } ProresThreadData;
 
-typedef struct {
+typedef struct ProresContext {
     ProresDSPContext dsp;
     AVFrame    *frame;
     ScanTable  scantable;
@@ -366,6 +366,7 @@
     }
 }
 
+#define MAX_PADDING 16
 
 /**
  * Decode AC coefficients for all blocks in a slice.
@@ -390,7 +391,7 @@
         lev_cb_index = ff_prores_lev_to_cb_index[FFMIN(level, 9)];
 
         bits_left = get_bits_left(gb);
-        if (bits_left <= 0 || (bits_left <= 8 && !show_bits(gb, bits_left)))
+        if (bits_left <= 0 || (bits_left <= MAX_PADDING && !show_bits(gb, bits_left)))
             return 0;
 
         run = decode_vlc_codeword(gb, ff_prores_ac_codebook[run_cb_index]);
@@ -398,7 +399,7 @@
             return AVERROR_INVALIDDATA;
 
         bits_left = get_bits_left(gb);
-        if (bits_left <= 0 || (bits_left <= 8 && !show_bits(gb, bits_left)))
+        if (bits_left <= 0 || (bits_left <= MAX_PADDING && !show_bits(gb, bits_left)))
             return AVERROR_INVALIDDATA;
 
         level = decode_vlc_codeword(gb, ff_prores_ac_codebook[lev_cb_index]) + 1;
diff --git a/libavcodec/proresenc_anatoliy.c b/libavcodec/proresenc_anatoliy.c
index f471f49..bf6e671 100644
--- a/libavcodec/proresenc_anatoliy.c
+++ b/libavcodec/proresenc_anatoliy.c
@@ -286,7 +286,8 @@
 {
     ProresContext* ctx = avctx->priv_data;
     FDCTDSPContext *fdsp = &ctx->fdsp;
-    DECLARE_ALIGNED(16, int16_t, blocks)[DEFAULT_SLICE_MB_WIDTH << 8], *block;
+    LOCAL_ALIGNED(16, int16_t, blocks, [DEFAULT_SLICE_MB_WIDTH << 8]);
+    int16_t *block;
     int i, blocks_per_slice;
     PutBitContext pb;
 
@@ -304,7 +305,7 @@
     }
 
     blocks_per_slice = mb_count << (2 - chroma);
-    init_put_bits(&pb, buf, buf_size << 3);
+    init_put_bits(&pb, buf, buf_size);
 
     encode_dc_coeffs(&pb, blocks, blocks_per_slice, qmat);
     encode_ac_coeffs(avctx, &pb, blocks, blocks_per_slice, qmat);
@@ -601,7 +602,7 @@
 static av_cold int prores_encode_close(AVCodecContext *avctx)
 {
     ProresContext* ctx = avctx->priv_data;
-    av_freep(&avctx->coded_frame);
+    av_frame_free(&avctx->coded_frame);
     av_freep(&ctx->fill_y);
 
     return 0;
diff --git a/libavcodec/proresenc_kostya.c b/libavcodec/proresenc_kostya.c
index 3418b46..440cc8b 100644
--- a/libavcodec/proresenc_kostya.c
+++ b/libavcodec/proresenc_kostya.c
@@ -914,7 +914,7 @@
     for (x = mb = 0; x < ctx->mb_width; x += mbs_per_slice, mb++) {
         while (ctx->mb_width - x < mbs_per_slice)
             mbs_per_slice >>= 1;
-        q = find_slice_quant(avctx, avctx->coded_frame,
+        q = find_slice_quant(avctx, arg,
                              (mb + 1) * TRELLIS_WIDTH, x, y,
                              mbs_per_slice, td);
     }
@@ -942,10 +942,6 @@
     int max_slice_size = (ctx->frame_size_upper_bound - 200) / (ctx->pictures_per_frame * ctx->slices_per_picture + 1);
     uint8_t frame_flags;
 
-    *avctx->coded_frame           = *pic;
-    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
-    avctx->coded_frame->key_frame = 1;
-
     pkt_size = ctx->frame_size_upper_bound;
 
     if ((ret = ff_alloc_packet2(avctx, pkt, pkt_size + FF_MIN_BUFFER_SIZE)) < 0)
@@ -1006,7 +1002,7 @@
 
         // slices
         if (!ctx->force_quant) {
-            ret = avctx->execute2(avctx, find_quant_thread, NULL, NULL,
+            ret = avctx->execute2(avctx, find_quant_thread, (void*)pic, NULL,
                                   ctx->mb_height);
             if (ret)
                 return ret;
@@ -1057,7 +1053,7 @@
                     slice_hdr        = pkt->data + (slice_hdr        - start);
                     tmp              = pkt->data + (tmp              - start);
                 }
-                init_put_bits(&pb, buf, (pkt_size - (buf - orig_buf)) * 8);
+                init_put_bits(&pb, buf, (pkt_size - (buf - orig_buf)));
                 ret = encode_slice(avctx, pic, &pb, sizes, x, y, q,
                                    mbs_per_slice);
                 if (ret < 0)
@@ -1096,7 +1092,7 @@
     ProresContext *ctx = avctx->priv_data;
     int i;
 
-    av_freep(&avctx->coded_frame);
+    av_frame_free(&avctx->coded_frame);
 
     if (ctx->tdata) {
         for (i = 0; i < avctx->thread_count; i++)
@@ -1134,6 +1130,8 @@
     avctx->coded_frame = av_frame_alloc();
     if (!avctx->coded_frame)
         return AVERROR(ENOMEM);
+    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
+    avctx->coded_frame->key_frame = 1;
 
     ctx->fdct      = prores_fdct;
     ctx->scantable = interlaced ? ff_prores_interlaced_scan
diff --git a/libavcodec/pthread_slice.c b/libavcodec/pthread_slice.c
index b948e16..c8e69f0 100644
--- a/libavcodec/pthread_slice.c
+++ b/libavcodec/pthread_slice.c
@@ -112,14 +112,26 @@
     pthread_mutex_lock(&c->current_job_lock);
     c->done = 1;
     pthread_cond_broadcast(&c->current_job_cond);
+    for (i = 0; i < c->thread_count; i++)
+        pthread_cond_broadcast(&c->progress_cond[i]);
     pthread_mutex_unlock(&c->current_job_lock);
 
     for (i=0; i<avctx->thread_count; i++)
          pthread_join(c->workers[i], NULL);
 
+    for (i = 0; i < c->thread_count; i++) {
+        pthread_mutex_destroy(&c->progress_mutex[i]);
+        pthread_cond_destroy(&c->progress_cond[i]);
+    }
+
     pthread_mutex_destroy(&c->current_job_lock);
     pthread_cond_destroy(&c->current_job_cond);
     pthread_cond_destroy(&c->last_job_cond);
+
+    av_freep(&c->entries);
+    av_freep(&c->progress_mutex);
+    av_freep(&c->progress_cond);
+
     av_freep(&c->workers);
     av_freep(&avctx->internal->thread_ctx);
 }
diff --git a/libavcodec/put_bits.h b/libavcodec/put_bits.h
index 8858caa..81be6b3 100644
--- a/libavcodec/put_bits.h
+++ b/libavcodec/put_bits.h
@@ -28,7 +28,6 @@
 
 #include <stdint.h>
 #include <stddef.h>
-#include <assert.h>
 
 #include "libavutil/intreadwrite.h"
 #include "libavutil/avassert.h"
diff --git a/libavcodec/qcelpdec.c b/libavcodec/qcelpdec.c
index 6f08607..22564ed 100644
--- a/libavcodec/qcelpdec.c
+++ b/libavcodec/qcelpdec.c
@@ -50,7 +50,7 @@
     RATE_FULL
 } qcelp_packet_rate;
 
-typedef struct {
+typedef struct QCELPContext {
     GetBitContext     gb;
     qcelp_packet_rate bitrate;
     QCELPFrame        frame;    /**< unpacked data frame */
@@ -719,7 +719,8 @@
                                          qcelp_unpacking_bitmaps_lengths[q->bitrate];
         uint8_t *unpacked_data         = (uint8_t *)&q->frame;
 
-        init_get_bits(&q->gb, buf, 8 * buf_size);
+        if ((ret = init_get_bits8(&q->gb, buf, buf_size)) < 0)
+            return ret;
 
         memset(&q->frame, 0, sizeof(QCELPFrame));
 
diff --git a/libavcodec/qdm2.c b/libavcodec/qdm2.c
index 55d9e3f..a02c5e5 100644
--- a/libavcodec/qdm2.c
+++ b/libavcodec/qdm2.c
@@ -46,10 +46,6 @@
 
 #include "qdm2_tablegen.h"
 
-#undef NDEBUG
-#include <assert.h>
-
-
 #define QDM2_LIST_ADD(list, size, packet) \
 do { \
       if (size > 0) { \
@@ -82,7 +78,7 @@
 /**
  * Subpacket
  */
-typedef struct {
+typedef struct QDM2SubPacket {
     int type;            ///< subpacket type
     unsigned int size;   ///< subpacket size
     const uint8_t *data; ///< pointer to subpacket data (points to input data buffer, it's not a private copy)
@@ -96,12 +92,12 @@
     struct QDM2SubPNode *next; ///< pointer to next packet in the list, NULL if leaf node
 } QDM2SubPNode;
 
-typedef struct {
+typedef struct QDM2Complex {
     float re;
     float im;
 } QDM2Complex;
 
-typedef struct {
+typedef struct FFTTone {
     float level;
     QDM2Complex *complex;
     const float *table;
@@ -112,7 +108,7 @@
     short cutoff;
 } FFTTone;
 
-typedef struct {
+typedef struct FFTCoefficient {
     int16_t sub_packet;
     uint8_t channel;
     int16_t offset;
@@ -120,14 +116,14 @@
     uint8_t phase;
 } FFTCoefficient;
 
-typedef struct {
+typedef struct QDM2FFT {
     DECLARE_ALIGNED(32, QDM2Complex, complex)[MPA_MAX_CHANNELS][256];
 } QDM2FFT;
 
 /**
  * QDM2 decoder context
  */
-typedef struct {
+typedef struct QDM2Context {
     /// Parameters from codec header, do not change during playback
     int nb_channels;         ///< number of channels
     int channels;            ///< number of channels
@@ -1650,7 +1646,7 @@
 
     if (!avctx->extradata || (avctx->extradata_size < 48)) {
         av_log(avctx, AV_LOG_ERROR, "extradata missing or truncated\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     extradata      = avctx->extradata;
@@ -1666,18 +1662,18 @@
     if (extradata_size < 12) {
         av_log(avctx, AV_LOG_ERROR, "not enough extradata (%i)\n",
                extradata_size);
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     if (memcmp(extradata, "frmaQDM", 7)) {
         av_log(avctx, AV_LOG_ERROR, "invalid headers, QDM? not found\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     if (extradata[7] == 'C') {
 //        s->is_qdmc = 1;
-        av_log(avctx, AV_LOG_ERROR, "stream is QDMC version 1, which is not supported\n");
-        return -1;
+        avpriv_report_missing_feature(avctx, "QDMC version 1");
+        return AVERROR_PATCHWELCOME;
     }
 
     extradata += 8;
@@ -1688,14 +1684,14 @@
     if(size > extradata_size){
         av_log(avctx, AV_LOG_ERROR, "extradata size too small, %i < %i\n",
                extradata_size, size);
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     extradata += 4;
     av_log(avctx, AV_LOG_DEBUG, "size: %d\n", size);
     if (AV_RB32(extradata) != MKBETAG('Q','D','C','A')) {
         av_log(avctx, AV_LOG_ERROR, "invalid extradata, expecting QDCA\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     extradata += 8;
@@ -1764,8 +1760,8 @@
 
     // Fail on unknown fft order
     if ((s->fft_order < 7) || (s->fft_order > 9)) {
-        av_log(avctx, AV_LOG_ERROR, "Unknown FFT order (%d), contact the developers!\n", s->fft_order);
-        return -1;
+        avpriv_request_sample(avctx, "Unknown FFT order %d", s->fft_order);
+        return AVERROR_PATCHWELCOME;
     }
     if (s->fft_size != (1 << (s->fft_order - 1))) {
         av_log(avctx, AV_LOG_ERROR, "FFT size %d not power of 2.\n", s->fft_size);
@@ -1873,8 +1869,8 @@
     out = (int16_t *)frame->data[0];
 
     for (i = 0; i < 16; i++) {
-        if (qdm2_decode(s, buf, out) < 0)
-            return -1;
+        if ((ret = qdm2_decode(s, buf, out)) < 0)
+            return ret;
         out += s->channels * s->frame_size;
     }
 
diff --git a/libavcodec/qsv.c b/libavcodec/qsv.c
new file mode 100644
index 0000000..1e34c5f
--- /dev/null
+++ b/libavcodec/qsv.c
@@ -0,0 +1,369 @@
+/*
+ * Intel MediaSDK QSV codec-independent code
+ *
+ * copyright (c) 2013 Luca Barbato
+ * copyright (c) 2015 Anton Khirnov <anton@khirnov.net>
+ *
+ * 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 <string.h>
+#include <sys/types.h>
+
+#include <mfx/mfxvideo.h>
+
+#include "libavutil/common.h"
+#include "libavutil/mem.h"
+#include "libavutil/log.h"
+#include "libavutil/pixfmt.h"
+#include "libavutil/time.h"
+
+#include "avcodec.h"
+#include "internal.h"
+#include "qsv_internal.h"
+
+int ff_qsv_error(int mfx_err)
+{
+    switch (mfx_err) {
+    case MFX_ERR_NONE:
+        return 0;
+    case MFX_ERR_MEMORY_ALLOC:
+    case MFX_ERR_NOT_ENOUGH_BUFFER:
+        return AVERROR(ENOMEM);
+    case MFX_ERR_INVALID_HANDLE:
+        return AVERROR(EINVAL);
+    case MFX_ERR_DEVICE_FAILED:
+    case MFX_ERR_DEVICE_LOST:
+    case MFX_ERR_LOCK_MEMORY:
+        return AVERROR(EIO);
+    case MFX_ERR_NULL_PTR:
+    case MFX_ERR_UNDEFINED_BEHAVIOR:
+    case MFX_ERR_NOT_INITIALIZED:
+        return AVERROR_BUG;
+    case MFX_ERR_UNSUPPORTED:
+    case MFX_ERR_NOT_FOUND:
+        return AVERROR(ENOSYS);
+    case MFX_ERR_MORE_DATA:
+    case MFX_ERR_MORE_SURFACE:
+    case MFX_ERR_MORE_BITSTREAM:
+        return AVERROR(EAGAIN);
+    case MFX_ERR_INCOMPATIBLE_VIDEO_PARAM:
+    case MFX_ERR_INVALID_VIDEO_PARAM:
+        return AVERROR(EINVAL);
+    case MFX_ERR_ABORTED:
+    case MFX_ERR_UNKNOWN:
+    default:
+        return AVERROR_UNKNOWN;
+    }
+}
+
+int ff_qsv_map_pixfmt(enum AVPixelFormat format)
+{
+    switch (format) {
+    case AV_PIX_FMT_YUV420P:
+    case AV_PIX_FMT_YUVJ420P:
+        return AV_PIX_FMT_NV12;
+    default:
+        return AVERROR(ENOSYS);
+    }
+}
+
+static int codec_id_to_mfx(enum AVCodecID codec_id)
+{
+    switch (codec_id) {
+    case AV_CODEC_ID_H264:
+        return MFX_CODEC_AVC;
+    case AV_CODEC_ID_MPEG1VIDEO:
+    case AV_CODEC_ID_MPEG2VIDEO:
+        return MFX_CODEC_MPEG2;
+    case AV_CODEC_ID_VC1:
+        return MFX_CODEC_VC1;
+    default:
+        break;
+    }
+
+    return AVERROR(ENOSYS);
+}
+
+static int qsv_init_session(AVCodecContext *avctx, QSVContext *q, mfxSession session)
+{
+    if (!session) {
+        if (!q->internal_session) {
+            mfxIMPL impl   = MFX_IMPL_AUTO_ANY;
+            mfxVersion ver = { { QSV_VERSION_MINOR, QSV_VERSION_MAJOR } };
+
+            const char *desc;
+            int ret;
+
+            ret = MFXInit(impl, &ver, &q->internal_session);
+            if (ret < 0) {
+                av_log(avctx, AV_LOG_ERROR, "Error initializing an internal MFX session\n");
+                return ff_qsv_error(ret);
+            }
+
+            MFXQueryIMPL(q->internal_session, &impl);
+
+            switch (MFX_IMPL_BASETYPE(impl)) {
+            case MFX_IMPL_SOFTWARE:
+                desc = "software";
+                break;
+            case MFX_IMPL_HARDWARE:
+            case MFX_IMPL_HARDWARE2:
+            case MFX_IMPL_HARDWARE3:
+            case MFX_IMPL_HARDWARE4:
+                desc = "hardware accelerated";
+                break;
+            default:
+                desc = "unknown";
+            }
+
+            av_log(avctx, AV_LOG_VERBOSE,
+                   "Initialized an internal MFX session using %s implementation\n",
+                   desc);
+        }
+
+        q->session = q->internal_session;
+    } else {
+        q->session = session;
+    }
+
+    /* make sure the decoder is uninitialized */
+    MFXVideoDECODE_Close(q->session);
+
+    return 0;
+}
+
+int ff_qsv_init(AVCodecContext *avctx, QSVContext *q, mfxSession session)
+{
+    mfxVideoParam param = { { 0 } };
+    int ret;
+
+    ret = qsv_init_session(avctx, q, session);
+    if (ret < 0) {
+        av_log(avctx, AV_LOG_ERROR, "Error initializing an MFX session\n");
+        return ret;
+    }
+
+
+    ret = codec_id_to_mfx(avctx->codec_id);
+    if (ret < 0)
+        return ret;
+
+    param.mfx.CodecId      = ret;
+    param.mfx.CodecProfile = avctx->profile;
+    param.mfx.CodecLevel   = avctx->level;
+
+    param.mfx.FrameInfo.BitDepthLuma   = 8;
+    param.mfx.FrameInfo.BitDepthChroma = 8;
+    param.mfx.FrameInfo.Shift          = 0;
+    param.mfx.FrameInfo.FourCC         = MFX_FOURCC_NV12;
+    param.mfx.FrameInfo.Width          = avctx->coded_width;
+    param.mfx.FrameInfo.Height         = avctx->coded_height;
+    param.mfx.FrameInfo.ChromaFormat   = MFX_CHROMAFORMAT_YUV420;
+
+    param.IOPattern   = q->iopattern;
+    param.AsyncDepth  = q->async_depth;
+    param.ExtParam    = q->ext_buffers;
+    param.NumExtParam = q->nb_ext_buffers;
+
+    ret = MFXVideoDECODE_Init(q->session, &param);
+    if (ret < 0) {
+        av_log(avctx, AV_LOG_ERROR, "Error initializing the MFX video decoder\n");
+        return ff_qsv_error(ret);
+    }
+
+    return 0;
+}
+
+static int alloc_frame(AVCodecContext *avctx, QSVFrame *frame)
+{
+    int ret;
+
+    ret = ff_get_buffer(avctx, frame->frame, AV_GET_BUFFER_FLAG_REF);
+    if (ret < 0)
+        return ret;
+
+    if (frame->frame->format == AV_PIX_FMT_QSV) {
+        frame->surface = (mfxFrameSurface1*)frame->frame->data[3];
+    } else {
+        frame->surface_internal.Info.BitDepthLuma   = 8;
+        frame->surface_internal.Info.BitDepthChroma = 8;
+        frame->surface_internal.Info.FourCC         = MFX_FOURCC_NV12;
+        frame->surface_internal.Info.Width          = avctx->coded_width;
+        frame->surface_internal.Info.Height         = avctx->coded_height;
+        frame->surface_internal.Info.ChromaFormat   = MFX_CHROMAFORMAT_YUV420;
+
+        frame->surface_internal.Data.PitchLow = frame->frame->linesize[0];
+        frame->surface_internal.Data.Y        = frame->frame->data[0];
+        frame->surface_internal.Data.UV       = frame->frame->data[1];
+
+        frame->surface = &frame->surface_internal;
+    }
+
+    return 0;
+}
+
+static void qsv_clear_unused_frames(QSVContext *q)
+{
+    QSVFrame *cur = q->work_frames;
+    while (cur) {
+        if (cur->surface && !cur->surface->Data.Locked) {
+            cur->surface = NULL;
+            av_frame_unref(cur->frame);
+        }
+        cur = cur->next;
+    }
+}
+
+static int get_surface(AVCodecContext *avctx, QSVContext *q, mfxFrameSurface1 **surf)
+{
+    QSVFrame *frame, **last;
+    int ret;
+
+    qsv_clear_unused_frames(q);
+
+    frame = q->work_frames;
+    last  = &q->work_frames;
+    while (frame) {
+        if (!frame->surface) {
+            ret = alloc_frame(avctx, frame);
+            if (ret < 0)
+                return ret;
+            *surf = frame->surface;
+            return 0;
+        }
+
+        last  = &frame->next;
+        frame = frame->next;
+    }
+
+    frame = av_mallocz(sizeof(*frame));
+    if (!frame)
+        return AVERROR(ENOMEM);
+    frame->frame = av_frame_alloc();
+    if (!frame->frame) {
+        av_freep(&frame);
+        return AVERROR(ENOMEM);
+    }
+    *last = frame;
+
+    ret = alloc_frame(avctx, frame);
+    if (ret < 0)
+        return ret;
+
+    *surf = frame->surface;
+
+    return 0;
+}
+
+static AVFrame *find_frame(QSVContext *q, mfxFrameSurface1 *surf)
+{
+    QSVFrame *cur = q->work_frames;
+    while (cur) {
+        if (surf == cur->surface)
+            return cur->frame;
+        cur = cur->next;
+    }
+    return NULL;
+}
+
+int ff_qsv_decode(AVCodecContext *avctx, QSVContext *q,
+                  AVFrame *frame, int *got_frame,
+                  AVPacket *avpkt)
+{
+    mfxFrameSurface1 *insurf;
+    mfxFrameSurface1 *outsurf;
+    mfxSyncPoint sync;
+    mfxBitstream bs = { { { 0 } } };
+    int ret;
+
+    if (avpkt->size) {
+        bs.Data       = avpkt->data;
+        bs.DataLength = avpkt->size;
+        bs.MaxLength  = bs.DataLength;
+        bs.TimeStamp  = avpkt->pts;
+    }
+
+    do {
+        ret = get_surface(avctx, q, &insurf);
+        if (ret < 0)
+            return ret;
+
+        ret = MFXVideoDECODE_DecodeFrameAsync(q->session, avpkt->size ? &bs : NULL,
+                                              insurf, &outsurf, &sync);
+        if (ret == MFX_WRN_DEVICE_BUSY)
+            av_usleep(1);
+
+    } while (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_ERR_MORE_SURFACE);
+
+    if (ret != MFX_ERR_NONE &&
+        ret != MFX_ERR_MORE_DATA &&
+        ret != MFX_WRN_VIDEO_PARAM_CHANGED &&
+        ret != MFX_ERR_MORE_SURFACE) {
+        av_log(avctx, AV_LOG_ERROR, "Error during QSV decoding.\n");
+        return ff_qsv_error(ret);
+    }
+
+    if (sync) {
+        AVFrame *src_frame;
+
+        MFXVideoCORE_SyncOperation(q->session, sync, 60000);
+
+        src_frame = find_frame(q, outsurf);
+        if (!src_frame) {
+            av_log(avctx, AV_LOG_ERROR,
+                   "The returned surface does not correspond to any frame\n");
+            return AVERROR_BUG;
+        }
+
+        ret = av_frame_ref(frame, src_frame);
+        if (ret < 0)
+            return ret;
+
+        frame->pkt_pts = frame->pts = outsurf->Data.TimeStamp;
+
+        frame->repeat_pict =
+            outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_TRIPLING ? 4 :
+            outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_DOUBLING ? 2 :
+            outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_REPEATED ? 1 : 0;
+        frame->top_field_first =
+            outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_TFF;
+        frame->interlaced_frame =
+            !(outsurf->Info.PicStruct & MFX_PICSTRUCT_PROGRESSIVE);
+
+        *got_frame = 1;
+    }
+
+    return bs.DataOffset;
+}
+
+int ff_qsv_close(QSVContext *q)
+{
+    QSVFrame *cur = q->work_frames;
+
+    while (cur) {
+        q->work_frames = cur->next;
+        av_frame_free(&cur->frame);
+        av_freep(&cur);
+        cur = q->work_frames;
+    }
+
+    if (q->internal_session)
+        MFXClose(q->internal_session);
+
+    return 0;
+}
diff --git a/libavcodec/qsv.h b/libavcodec/qsv.h
new file mode 100644
index 0000000..e7487c8
--- /dev/null
+++ b/libavcodec/qsv.h
@@ -0,0 +1,41 @@
+/*
+ * Intel MediaSDK QSV public API
+ *
+ * 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_QSV_H
+#define AVCODEC_QSV_H
+
+#include <mfx/mfxvideo.h>
+
+typedef struct AVQSVContext {
+    mfxSession session;
+    int iopattern;
+
+    mfxExtBuffer **ext_buffers;
+    int         nb_ext_buffers;
+} AVQSVContext;
+
+/**
+ * Allocate a new context.
+ *
+ * It must be freed by the caller with av_free().
+ */
+AVQSVContext *av_qsv_alloc_context(void);
+
+#endif /* AVCODEC_QSV_H */
diff --git a/libavcodec/qsv_api.c b/libavcodec/qsv_api.c
new file mode 100644
index 0000000..327ff7d
--- /dev/null
+++ b/libavcodec/qsv_api.c
@@ -0,0 +1,42 @@
+/*
+ * Intel MediaSDK QSV public API functions
+ *
+ * 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"
+
+#include <stddef.h>
+
+#include "libavutil/mem.h"
+
+#if CONFIG_QSV
+#include "qsv.h"
+
+AVQSVContext *av_qsv_alloc_context(void)
+{
+    return av_mallocz(sizeof(AVQSVContext));
+}
+#else
+
+struct AVQSVContext *av_qsv_alloc_context(void);
+
+struct AVQSVContext *av_qsv_alloc_context(void)
+{
+    return NULL;
+}
+#endif
diff --git a/libavcodec/qsv_h264.c b/libavcodec/qsv_h264.c
new file mode 100644
index 0000000..eafc352
--- /dev/null
+++ b/libavcodec/qsv_h264.c
@@ -0,0 +1,313 @@
+/*
+ * Intel MediaSDK QSV based H.264 decoder
+ *
+ * copyright (c) 2013 Luca Barbato
+ * copyright (c) 2015 Anton Khirnov
+ *
+ * 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 <mfx/mfxvideo.h>
+
+#include "libavutil/common.h"
+#include "libavutil/fifo.h"
+#include "libavutil/opt.h"
+
+#include "avcodec.h"
+#include "internal.h"
+#include "qsv_internal.h"
+#include "qsv.h"
+
+typedef struct QSVH264Context {
+    AVClass *class;
+    QSVContext qsv;
+
+    // the internal parser and codec context for parsing the data
+    AVCodecParserContext *parser;
+    AVCodecContext *avctx_internal;
+    enum AVPixelFormat orig_pix_fmt;
+
+    // the filter for converting to Annex B
+    AVBitStreamFilterContext *bsf;
+
+    AVFifoBuffer *packet_fifo;
+
+    AVPacket input_ref;
+    AVPacket pkt_filtered;
+    uint8_t *filtered_data;
+} QSVH264Context;
+
+static void qsv_clear_buffers(QSVH264Context *s)
+{
+    AVPacket pkt;
+    while (av_fifo_size(s->packet_fifo) >= sizeof(pkt)) {
+        av_fifo_generic_read(s->packet_fifo, &pkt, sizeof(pkt), NULL);
+        av_packet_unref(&pkt);
+    }
+
+    if (s->filtered_data != s->input_ref.data)
+        av_freep(&s->filtered_data);
+    s->filtered_data = NULL;
+    av_packet_unref(&s->input_ref);
+}
+
+static av_cold int qsv_decode_close(AVCodecContext *avctx)
+{
+    QSVH264Context *s = avctx->priv_data;
+
+    ff_qsv_close(&s->qsv);
+
+    qsv_clear_buffers(s);
+
+    av_fifo_free(s->packet_fifo);
+
+    av_bitstream_filter_close(s->bsf);
+    av_parser_close(s->parser);
+    avcodec_free_context(&s->avctx_internal);
+
+    return 0;
+}
+
+static av_cold int qsv_decode_init(AVCodecContext *avctx)
+{
+    QSVH264Context *s = avctx->priv_data;
+    int ret;
+
+    s->orig_pix_fmt = AV_PIX_FMT_NONE;
+
+    s->packet_fifo = av_fifo_alloc(sizeof(AVPacket));
+    if (!s->packet_fifo) {
+        ret = AVERROR(ENOMEM);
+        goto fail;
+    }
+
+    s->bsf = av_bitstream_filter_init("h264_mp4toannexb");
+    if (!s->bsf) {
+        ret = AVERROR(ENOMEM);
+        goto fail;
+    }
+
+    s->avctx_internal = avcodec_alloc_context3(NULL);
+    if (!s->avctx_internal) {
+        ret = AVERROR(ENOMEM);
+        goto fail;
+    }
+
+    if (avctx->extradata) {
+        s->avctx_internal->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
+        if (!s->avctx_internal->extradata) {
+            ret = AVERROR(ENOMEM);
+            goto fail;
+        }
+        memcpy(s->avctx_internal->extradata, avctx->extradata,
+               avctx->extradata_size);
+        s->avctx_internal->extradata_size = avctx->extradata_size;
+    }
+
+    s->parser = av_parser_init(AV_CODEC_ID_H264);
+    if (!s->parser) {
+        ret = AVERROR(ENOMEM);
+        goto fail;
+    }
+    s->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
+
+    s->qsv.iopattern = MFX_IOPATTERN_OUT_SYSTEM_MEMORY;
+
+    return 0;
+fail:
+    qsv_decode_close(avctx);
+    return ret;
+}
+
+static int qsv_process_data(AVCodecContext *avctx, AVFrame *frame,
+                            int *got_frame, AVPacket *pkt)
+{
+    QSVH264Context *s = avctx->priv_data;
+    uint8_t *dummy_data;
+    int dummy_size;
+    int ret;
+
+    /* we assume the packets are already split properly and want
+     * just the codec parameters here */
+    av_parser_parse2(s->parser, s->avctx_internal,
+                     &dummy_data, &dummy_size,
+                     pkt->data, pkt->size, pkt->pts, pkt->dts,
+                     pkt->pos);
+
+    /* TODO: flush delayed frames on reinit */
+    if (s->parser->format       != s->orig_pix_fmt    ||
+        s->parser->coded_width  != avctx->coded_width ||
+        s->parser->coded_height != avctx->coded_height) {
+        mfxSession session = NULL;
+
+        enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_QSV,
+                                           AV_PIX_FMT_NONE,
+                                           AV_PIX_FMT_NONE };
+        enum AVPixelFormat qsv_format;
+
+        qsv_format = ff_qsv_map_pixfmt(s->parser->format);
+        if (qsv_format < 0) {
+            av_log(avctx, AV_LOG_ERROR,
+                   "Only 8-bit YUV420 streams are supported.\n");
+            ret = AVERROR(ENOSYS);
+            goto reinit_fail;
+        }
+
+        s->orig_pix_fmt     = s->parser->format;
+        avctx->pix_fmt      = pix_fmts[1] = qsv_format;
+        avctx->width        = s->parser->width;
+        avctx->height       = s->parser->height;
+        avctx->coded_width  = s->parser->coded_width;
+        avctx->coded_height = s->parser->coded_height;
+        avctx->level        = s->avctx_internal->level;
+        avctx->profile      = s->avctx_internal->profile;
+
+        ret = ff_get_format(avctx, pix_fmts);
+        if (ret < 0)
+            goto reinit_fail;
+
+        avctx->pix_fmt = ret;
+
+        if (avctx->hwaccel_context) {
+            AVQSVContext *user_ctx = avctx->hwaccel_context;
+            session               = user_ctx->session;
+            s->qsv.iopattern      = user_ctx->iopattern;
+            s->qsv.ext_buffers    = user_ctx->ext_buffers;
+            s->qsv.nb_ext_buffers = user_ctx->nb_ext_buffers;
+        }
+
+        ret = ff_qsv_init(avctx, &s->qsv, session);
+        if (ret < 0)
+            goto reinit_fail;
+    }
+
+    return ff_qsv_decode(avctx, &s->qsv, frame, got_frame, &s->pkt_filtered);
+
+reinit_fail:
+    s->orig_pix_fmt = s->parser->format = avctx->pix_fmt = AV_PIX_FMT_NONE;
+    return ret;
+}
+
+static int qsv_decode_frame(AVCodecContext *avctx, void *data,
+                            int *got_frame, AVPacket *avpkt)
+{
+    QSVH264Context *s = avctx->priv_data;
+    AVFrame *frame    = data;
+    int ret;
+
+    /* buffer the input packet */
+    if (avpkt->size) {
+        AVPacket input_ref = { 0 };
+
+        if (av_fifo_space(s->packet_fifo) < sizeof(input_ref)) {
+            ret = av_fifo_realloc2(s->packet_fifo,
+                                   av_fifo_size(s->packet_fifo) + sizeof(input_ref));
+            if (ret < 0)
+                return ret;
+        }
+
+        ret = av_packet_ref(&input_ref, avpkt);
+        if (ret < 0)
+            return ret;
+        av_fifo_generic_write(s->packet_fifo, &input_ref, sizeof(input_ref), NULL);
+    }
+
+    /* process buffered data */
+    while (!*got_frame) {
+        /* prepare the input data -- convert to Annex B if needed */
+        if (s->pkt_filtered.size <= 0) {
+            int size;
+
+            /* no more data */
+            if (av_fifo_size(s->packet_fifo) < sizeof(AVPacket))
+                return avpkt->size ? avpkt->size : ff_qsv_decode(avctx, &s->qsv, frame, got_frame, avpkt);
+
+            if (s->filtered_data != s->input_ref.data)
+                av_freep(&s->filtered_data);
+            s->filtered_data = NULL;
+            av_packet_unref(&s->input_ref);
+
+            av_fifo_generic_read(s->packet_fifo, &s->input_ref, sizeof(s->input_ref), NULL);
+            ret = av_bitstream_filter_filter(s->bsf, avctx, NULL,
+                                             &s->filtered_data, &size,
+                                             s->input_ref.data, s->input_ref.size, 0);
+            if (ret < 0) {
+                s->filtered_data = s->input_ref.data;
+                size             = s->input_ref.size;
+            }
+            s->pkt_filtered      = s->input_ref;
+            s->pkt_filtered.data = s->filtered_data;
+            s->pkt_filtered.size = size;
+        }
+
+        ret = qsv_process_data(avctx, frame, got_frame, &s->pkt_filtered);
+        if (ret < 0)
+            return ret;
+
+        s->pkt_filtered.size -= ret;
+        s->pkt_filtered.data += ret;
+    }
+
+    return avpkt->size;
+}
+
+static void qsv_decode_flush(AVCodecContext *avctx)
+{
+    QSVH264Context *s = avctx->priv_data;
+
+    qsv_clear_buffers(s);
+    s->orig_pix_fmt = AV_PIX_FMT_NONE;
+}
+
+AVHWAccel ff_h264_qsv_hwaccel = {
+    .name           = "h264_qsv",
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = AV_CODEC_ID_H264,
+    .pix_fmt        = AV_PIX_FMT_QSV,
+};
+
+#define OFFSET(x) offsetof(QSVH264Context, x)
+#define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
+static const AVOption options[] = {
+    { "async_depth", "Internal parallelization depth, the higher the value the higher the latency.", OFFSET(qsv.async_depth), AV_OPT_TYPE_INT, { .i64 = ASYNC_DEPTH_DEFAULT }, 0, INT_MAX, VD },
+    { NULL },
+};
+
+static const AVClass class = {
+    .class_name = "h264_qsv",
+    .item_name  = av_default_item_name,
+    .option     = options,
+    .version    = LIBAVUTIL_VERSION_INT,
+};
+
+AVCodec ff_h264_qsv_decoder = {
+    .name           = "h264_qsv",
+    .long_name      = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (Intel Quick Sync Video acceleration)"),
+    .priv_data_size = sizeof(QSVH264Context),
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = AV_CODEC_ID_H264,
+    .init           = qsv_decode_init,
+    .decode         = qsv_decode_frame,
+    .flush          = qsv_decode_flush,
+    .close          = qsv_decode_close,
+    .capabilities   = CODEC_CAP_DELAY,
+    .priv_class     = &class,
+};
diff --git a/libavcodec/qsv_internal.h b/libavcodec/qsv_internal.h
new file mode 100644
index 0000000..c154eaf
--- /dev/null
+++ b/libavcodec/qsv_internal.h
@@ -0,0 +1,86 @@
+/*
+ * Intel MediaSDK QSV utility functions
+ *
+ * copyright (c) 2013 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
+ */
+
+#ifndef AVCODEC_QSV_INTERNAL_H
+#define AVCODEC_QSV_INTERNAL_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <mfx/mfxvideo.h>
+
+#include "libavutil/frame.h"
+#include "libavutil/pixfmt.h"
+
+#include "avcodec.h"
+
+#define QSV_VERSION_MAJOR 1
+#define QSV_VERSION_MINOR 1
+
+#define ASYNC_DEPTH_DEFAULT 4       // internal parallelism
+
+typedef struct QSVFrame {
+    AVFrame *frame;
+    mfxFrameSurface1 *surface;
+
+    mfxFrameSurface1 surface_internal;
+
+    struct QSVFrame *next;
+} QSVFrame;
+
+typedef struct QSVContext {
+    // the session used for decoding
+    mfxSession session;
+
+    // the session we allocated internally, in case the caller did not provide
+    // one
+    mfxSession internal_session;
+
+    /**
+     * a linked list of frames currently being used by QSV
+     */
+    QSVFrame *work_frames;
+
+    // options set by the caller
+    int async_depth;
+    int iopattern;
+
+    mfxExtBuffer **ext_buffers;
+    int         nb_ext_buffers;
+} QSVContext;
+
+/**
+ * Convert a libmfx error code into a ffmpeg error code.
+ */
+int ff_qsv_error(int mfx_err);
+
+int ff_qsv_map_pixfmt(enum AVPixelFormat format);
+
+int ff_qsv_init(AVCodecContext *s, QSVContext *q, mfxSession session);
+
+int ff_qsv_decode(AVCodecContext *s, QSVContext *q,
+                  AVFrame *frame, int *got_frame,
+                  AVPacket *avpkt);
+
+int ff_qsv_close(QSVContext *q);
+
+#endif /* AVCODEC_QSV_INTERNAL_H */
diff --git a/libavcodec/r210enc.c b/libavcodec/r210enc.c
index 07dfc50..b7d5a07 100644
--- a/libavcodec/r210enc.c
+++ b/libavcodec/r210enc.c
@@ -80,7 +80,7 @@
 
 static av_cold int encode_close(AVCodecContext *avctx)
 {
-    av_freep(&avctx->coded_frame);
+    av_frame_free(&avctx->coded_frame);
 
     return 0;
 }
diff --git a/libavcodec/ra288.c b/libavcodec/ra288.c
index dbb2643..189d5c5 100644
--- a/libavcodec/ra288.c
+++ b/libavcodec/ra288.c
@@ -37,7 +37,7 @@
 #define RA288_BLOCK_SIZE        5
 #define RA288_BLOCKS_PER_FRAME 32
 
-typedef struct {
+typedef struct RA288Context {
     AVFloatDSPContext *fdsp;
     DECLARE_ALIGNED(32, float,   sp_lpc)[FFALIGN(36, 16)];   ///< LPC coefficients for speech data (spec: A)
     DECLARE_ALIGNED(32, float, gain_lpc)[FFALIGN(10, 16)];   ///< LPC coefficients for gain        (spec: GB)
diff --git a/libavcodec/ratecontrol.c b/libavcodec/ratecontrol.c
index b83af59..32a4de9 100644
--- a/libavcodec/ratecontrol.c
+++ b/libavcodec/ratecontrol.c
@@ -32,9 +32,6 @@
 #include "mpegvideo.h"
 #include "libavutil/eval.h"
 
-#undef NDEBUG // Always check asserts, the speed effect is far too small to disable them.
-#include <assert.h>
-
 #ifndef M_E
 #define M_E 2.718281828
 #endif
@@ -205,8 +202,8 @@
             }
             e = sscanf(p, " in:%d ", &picture_number);
 
-            assert(picture_number >= 0);
-            assert(picture_number < rcc->num_entries);
+            av_assert0(picture_number >= 0);
+            av_assert0(picture_number < rcc->num_entries);
             rce = &rcc->entry[picture_number];
 
             e += sscanf(p, " in:%*d out:%*d type:%d q:%f itex:%d ptex:%d mv:%d misc:%d fcode:%d bcode:%d mc-var:%"SCNd64" var:%"SCNd64" icount:%d skipcount:%d hbits:%d",
@@ -482,7 +479,7 @@
     int qmin = s->lmin;
     int qmax = s->lmax;
 
-    assert(qmin <= qmax);
+    av_assert0(qmin <= qmax);
 
     switch (pict_type) {
     case AV_PICTURE_TYPE_B:
@@ -783,7 +780,7 @@
     }
 
     if (s->flags & CODEC_FLAG_PASS2) {
-        assert(picture_number >= 0);
+        av_assert0(picture_number >= 0);
         if (picture_number >= rcc->num_entries) {
             av_log(s, AV_LOG_ERROR, "Input is longer than 2-pass log file\n");
             return -1;
@@ -818,7 +815,7 @@
     short_term_q = 0; /* avoid warning */
     if (s->flags & CODEC_FLAG_PASS2) {
         if (pict_type != AV_PICTURE_TYPE_I)
-            assert(pict_type == rce->new_pict_type);
+            av_assert0(pict_type == rce->new_pict_type);
 
         q = rce->new_qscale / br_compensation;
         av_dlog(s, "%f %f %f last:%d var:%"PRId64" type:%d//\n", q, rce->new_qscale,
@@ -857,9 +854,9 @@
         if (q < 0)
             return -1;
 
-        assert(q > 0.0);
+        av_assert0(q > 0.0);
         q = get_diff_limited_q(s, rce, q);
-        assert(q > 0.0);
+        av_assert0(q > 0.0);
 
         // FIXME type dependent blur like in 2-pass
         if (pict_type == AV_PICTURE_TYPE_P || s->intra_only) {
@@ -870,13 +867,13 @@
             rcc->short_term_qcount++;
             q = short_term_q = rcc->short_term_qsum / rcc->short_term_qcount;
         }
-        assert(q > 0.0);
+        av_assert0(q > 0.0);
 
         q = modify_qscale(s, rce, q, picture_number);
 
         rcc->pass1_wanted_bits += s->bit_rate / fps;
 
-        assert(q > 0.0);
+        av_assert0(q > 0.0);
     }
 
     if (s->avctx->debug & FF_DEBUG_RC) {
@@ -975,7 +972,7 @@
             qscale[i] = get_qscale(s, &rcc->entry[i], rate_factor, i);
             rcc->last_qscale_for[rce->pict_type] = qscale[i];
         }
-        assert(filter_size % 2 == 1);
+        av_assert0(filter_size % 2 == 1);
 
         /* fixed I/B QP relative to P mode */
         for (i = FFMAX(0, rcc->num_entries - 300); i < rcc->num_entries; i++) {
@@ -1047,7 +1044,7 @@
         qscale_sum += av_clip(rcc->entry[i].new_qscale / FF_QP2LAMBDA,
                               s->avctx->qmin, s->avctx->qmax);
     }
-    assert(toobig <= 40);
+    av_assert0(toobig <= 40);
     av_log(s->avctx, AV_LOG_DEBUG,
            "[lavc rc] requested bitrate: %d bps  expected bitrate: %d bps\n",
            s->bit_rate,
diff --git a/libavcodec/roqaudioenc.c b/libavcodec/roqaudioenc.c
index 2c59074..c373ccc 100644
--- a/libavcodec/roqaudioenc.c
+++ b/libavcodec/roqaudioenc.c
@@ -32,8 +32,7 @@
 #define MAX_DPCM (127*127)
 
 
-typedef struct
-{
+typedef struct ROQDPCMContext {
     short lastSample[2];
     int input_frames;
     int buffered_samples;
diff --git a/libavcodec/roqvideoenc.c b/libavcodec/roqvideoenc.c
index 731916f..89879e8 100644
--- a/libavcodec/roqvideoenc.c
+++ b/libavcodec/roqvideoenc.c
@@ -184,8 +184,7 @@
     return sdiff;
 }
 
-typedef struct
-{
+typedef struct SubcelEvaluation {
     int eval_dist[4];
     int best_bit_use;
     int best_coding;
@@ -195,8 +194,7 @@
     int cbEntry;
 } SubcelEvaluation;
 
-typedef struct
-{
+typedef struct CelEvaluation {
     int eval_dist[4];
     int best_coding;
 
@@ -208,8 +206,7 @@
     int sourceX, sourceY;
 } CelEvaluation;
 
-typedef struct
-{
+typedef struct RoqCodebooks {
     int numCB4;
     int numCB2;
     int usedCB2[MAX_CBS_2x2];
@@ -603,8 +600,7 @@
     return ((ax&15)<<4) | (ay&15);
 }
 
-typedef struct
-{
+typedef struct CodingSpool {
     int typeSpool;
     int typeSpoolLength;
     uint8_t argumentSpool[64];
@@ -964,7 +960,8 @@
     reconstruct_and_encode_image(enc, tempData, enc->width, enc->height,
                                  enc->width*enc->height/64);
 
-    enc->avctx->coded_frame = enc->current_frame;
+    av_frame_unref(enc->avctx->coded_frame);
+    av_frame_ref(enc->avctx->coded_frame, enc->current_frame);
 
     /* Rotate frame history */
     FFSWAP(AVFrame *, enc->current_frame, enc->last_frame);
@@ -985,6 +982,7 @@
 
     av_frame_free(&enc->current_frame);
     av_frame_free(&enc->last_frame);
+    av_frame_free(&enc->avctx->coded_frame);
 
     av_freep(&enc->tmpData);
     av_freep(&enc->this_motion4);
@@ -1001,6 +999,8 @@
 
     av_lfg_init(&enc->randctx, 1);
 
+    enc->avctx = avctx;
+
     enc->framesSinceKeyframe = 0;
     if ((avctx->width & 0xf) || (avctx->height & 0xf)) {
         av_log(avctx, AV_LOG_ERROR, "Dimensions must be divisible by 16\n");
@@ -1023,7 +1023,8 @@
 
     enc->last_frame    = av_frame_alloc();
     enc->current_frame = av_frame_alloc();
-    if (!enc->last_frame || !enc->current_frame) {
+    avctx->coded_frame = av_frame_alloc();
+    if (!enc->last_frame || !enc->current_frame || !avctx->coded_frame) {
         roq_encode_end(avctx);
         return AVERROR(ENOMEM);
     }
diff --git a/libavcodec/rv10enc.c b/libavcodec/rv10enc.c
index 2541132..45f1136 100644
--- a/libavcodec/rv10enc.c
+++ b/libavcodec/rv10enc.c
@@ -28,7 +28,7 @@
 #include "mpegvideo.h"
 #include "put_bits.h"
 
-void ff_rv10_encode_picture_header(MpegEncContext *s, int picture_number)
+int ff_rv10_encode_picture_header(MpegEncContext *s, int picture_number)
 {
     int full_frame= 0;
 
@@ -48,12 +48,18 @@
     /* if multiple packets per frame are sent, the position at which
        to display the macroblocks is coded here */
     if(!full_frame){
+        if (s->mb_width * s->mb_height >= (1U << 12)) {
+            avpriv_report_missing_feature(s->avctx, "Encoding frames with %d (>= 4096) macroblocks",
+                                          s->mb_width * s->mb_height);
+            return AVERROR(ENOSYS);
+        }
         put_bits(&s->pb, 6, 0); /* mb_x */
         put_bits(&s->pb, 6, 0); /* mb_y */
         put_bits(&s->pb, 12, s->mb_width * s->mb_height);
     }
 
     put_bits(&s->pb, 3, 0);     /* ignored */
+    return 0;
 }
 
 FF_MPV_GENERIC_CLASS(rv10)
diff --git a/libavcodec/rv34_parser.c b/libavcodec/rv34_parser.c
index 6a07a5f..765d390 100644
--- a/libavcodec/rv34_parser.c
+++ b/libavcodec/rv34_parser.c
@@ -27,7 +27,7 @@
 #include "parser.h"
 #include "libavutil/intreadwrite.h"
 
-typedef struct {
+typedef struct RV34ParseContext {
     ParseContext pc;
     int64_t key_dts;
     int key_pts;
diff --git a/libavcodec/rv40.c b/libavcodec/rv40.c
index 043fd72..e9cd110 100644
--- a/libavcodec/rv40.c
+++ b/libavcodec/rv40.c
@@ -130,22 +130,23 @@
     int mb_bits;
     int w = r->s.width, h = r->s.height;
     int mb_size;
+    int ret;
 
     memset(si, 0, sizeof(SliceInfo));
     if(get_bits1(gb))
-        return -1;
+        return AVERROR_INVALIDDATA;
     si->type = get_bits(gb, 2);
     if(si->type == 1) si->type = 0;
     si->quant = get_bits(gb, 5);
     if(get_bits(gb, 2))
-        return -1;
+        return AVERROR_INVALIDDATA;
     si->vlc_set = get_bits(gb, 2);
     skip_bits1(gb);
     si->pts = get_bits(gb, 13);
     if(!si->type || !get_bits1(gb))
         rv40_parse_picture_size(gb, &w, &h);
-    if(av_image_check_size(w, h, 0, r->s.avctx) < 0)
-        return -1;
+    if ((ret = av_image_check_size(w, h, 0, r->s.avctx)) < 0)
+        return ret;
     si->width  = w;
     si->height = h;
     mb_size = ((w + 15) >> 4) * ((h + 15) >> 4);
diff --git a/libavcodec/s302menc.c b/libavcodec/s302menc.c
index 540ac29..e738f09 100644
--- a/libavcodec/s302menc.c
+++ b/libavcodec/s302menc.c
@@ -82,7 +82,7 @@
         return ret;
 
     o = avpkt->data;
-    init_put_bits(&pb, o, buf_size * 8);
+    init_put_bits(&pb, o, buf_size);
     put_bits(&pb, 16, buf_size - AES3_HEADER_LEN);
     put_bits(&pb, 2, (avctx->channels - 2) >> 1);   // number of channels
     put_bits(&pb, 8, 0);                            // channel ID
diff --git a/libavcodec/samidec.c b/libavcodec/samidec.c
index 7705f93..47850e2 100644
--- a/libavcodec/samidec.c
+++ b/libavcodec/samidec.c
@@ -91,6 +91,7 @@
                     break;
                 if (*p == '>')
                     p++;
+                continue;
             }
             if (!av_isspace(*p))
                 av_bprint_chars(dst, *p, 1);
diff --git a/libavcodec/sgienc.c b/libavcodec/sgienc.c
index 21026af..2f45eb3 100644
--- a/libavcodec/sgienc.c
+++ b/libavcodec/sgienc.c
@@ -153,7 +153,7 @@
 
         /* Make an intermediate consecutive buffer. */
         if (!(encode_buf = av_malloc(width)))
-            return -1;
+            return AVERROR(ENOMEM);
 
         for (z = 0; z < depth; z++) {
             in_buf = p->data[0] + p->linesize[0] * (height - 1) + z;
diff --git a/libavcodec/sipr.c b/libavcodec/sipr.c
index 4cb9485..af1edf5 100644
--- a/libavcodec/sipr.c
+++ b/libavcodec/sipr.c
@@ -44,7 +44,7 @@
 #include "sipr.h"
 #include "siprdata.h"
 
-typedef struct {
+typedef struct SiprModeParam {
     const char *mode_name;
     uint16_t bits_per_frame;
     uint8_t subframe_count;
diff --git a/libavcodec/smvjpegdec.c b/libavcodec/smvjpegdec.c
index 375c9d9..5eca9bb 100644
--- a/libavcodec/smvjpegdec.c
+++ b/libavcodec/smvjpegdec.c
@@ -50,7 +50,7 @@
 
 static inline void smv_img_pnt(uint8_t *dst_data[4], 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,
                                int nlines)
 {
     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
diff --git a/libavcodec/snow.c b/libavcodec/snow.c
index c4f7004..33a2dbc 100644
--- a/libavcodec/snow.c
+++ b/libavcodec/snow.c
@@ -434,6 +434,7 @@
 
     s->avctx= avctx;
     s->max_ref_frames=1; //just make sure it's not an invalid value in case of no initial keyframe
+    s->spatial_decomposition_count = 1;
 
     ff_me_cmp_init(&s->mecc, avctx);
     ff_hpeldsp_init(&s->hdsp, avctx->flags);
@@ -534,8 +535,8 @@
         int h= s->avctx->height;
 
         if(plane_index){
-            w>>= s->chroma_h_shift;
-            h>>= s->chroma_v_shift;
+            w = FF_CEIL_RSHIFT(w, s->chroma_h_shift);
+            h = FF_CEIL_RSHIFT(h, s->chroma_v_shift);
         }
         s->plane[plane_index].width = w;
         s->plane[plane_index].height= h;
@@ -589,8 +590,8 @@
 
     for(p=0; p < s->nb_planes; p++){
         int is_chroma= !!p;
-        int w= is_chroma ? s->avctx->width >>s->chroma_h_shift : s->avctx->width;
-        int h= is_chroma ? s->avctx->height>>s->chroma_v_shift : s->avctx->height;
+        int w= is_chroma ? FF_CEIL_RSHIFT(s->avctx->width,  s->chroma_h_shift) : s->avctx->width;
+        int h= is_chroma ? FF_CEIL_RSHIFT(s->avctx->height, s->chroma_v_shift) : s->avctx->height;
         int ls= frame->linesize[p];
         uint8_t *src= frame->data[p];
 
@@ -718,8 +719,8 @@
         av_frame_free(&s->last_picture[i]);
     }
 
-    for(plane_index=0; plane_index < s->nb_planes; plane_index++){
-        for(level=s->spatial_decomposition_count-1; level>=0; level--){
+    for(plane_index=0; plane_index < MAX_PLANES; plane_index++){
+        for(level=MAX_DECOMPOSITIONS-1; level>=0; level--){
             for(orientation=level ? 1 : 0; orientation<4; orientation++){
                 SubBand *b= &s->plane[plane_index].band[level][orientation];
 
diff --git a/libavcodec/snow_dwt.c b/libavcodec/snow_dwt.c
index ecba0ea..c148cda 100644
--- a/libavcodec/snow_dwt.c
+++ b/libavcodec/snow_dwt.c
@@ -839,7 +839,7 @@
     return w_c(v, pix1, pix2, line_size, 32, h, 0);
 }
 
-void ff_dsputil_init_dwt(MECmpContext *c)
+av_cold void ff_dsputil_init_dwt(MECmpContext *c)
 {
     c->w53[0] = w53_16_c;
     c->w53[1] = w53_8_c;
@@ -847,7 +847,7 @@
     c->w97[1] = w97_8_c;
 }
 
-void ff_dwt_init(SnowDWTContext *c)
+av_cold void ff_dwt_init(SnowDWTContext *c)
 {
     c->vertical_compose97i   = ff_snow_vertical_compose97i;
     c->horizontal_compose97i = ff_snow_horizontal_compose97i;
diff --git a/libavcodec/snowdec.c b/libavcodec/snowdec.c
index 58f9ed8..81fe03c 100644
--- a/libavcodec/snowdec.c
+++ b/libavcodec/snowdec.c
@@ -90,7 +90,7 @@
 
     if(s->avmv && mb_y < mb_h && plane_index == 0)
         for(mb_x=0; mb_x<mb_w; mb_x++){
-            AVMotionVector *avmv = s->avmv + (s->avmv_index++);
+            AVMotionVector *avmv = s->avmv + s->avmv_index;
             const int b_width = s->b_width  << s->block_max_depth;
             const int b_stride= b_width;
             BlockNode *bn= &s->block[mb_x + mb_y*b_stride];
@@ -98,6 +98,8 @@
             if (bn->type)
                 continue;
 
+            s->avmv_index++;
+
             avmv->w = block_w;
             avmv->h = block_h;
             avmv->dst_x = block_w*mb_x - block_w/2;
@@ -172,7 +174,7 @@
         int l = left->color[0];
         int cb= left->color[1];
         int cr= left->color[2];
-        int ref = 0;
+        unsigned ref = 0;
         int ref_context= av_log2(2*left->ref) + av_log2(2*top->ref);
         int mx_context= av_log2(2*FFABS(left->mx - top->mx)) + 0*av_log2(2*FFABS(tr->mx - top->mx));
         int my_context= av_log2(2*FFABS(left->my - top->my)) + 0*av_log2(2*FFABS(tr->my - top->my));
diff --git a/libavcodec/snowenc.c b/libavcodec/snowenc.c
index cd8fef3..e03dc13 100644
--- a/libavcodec/snowenc.c
+++ b/libavcodec/snowenc.c
@@ -124,7 +124,8 @@
     ff_set_cmp(&s->mecc, s->mecc.me_sub_cmp, s->avctx->me_sub_cmp);
 
     s->input_picture = av_frame_alloc();
-    if (!s->input_picture)
+    avctx->coded_frame = av_frame_alloc();
+    if (!s->input_picture || !avctx->coded_frame)
         return AVERROR(ENOMEM);
 
     if ((ret = ff_snow_get_buffer(s, s->input_picture)) < 0)
@@ -547,7 +548,7 @@
     }
     *b= backup;
 
-    return av_clip( ROUNDED_DIV(ab<<LOG2_OBMC_MAX, aa), 0, 255); //FIXME we should not need clipping
+    return av_clip_uint8( ROUNDED_DIV(ab<<LOG2_OBMC_MAX, aa) ); //FIXME we should not need clipping
 }
 
 static inline int get_block_bits(SnowContext *s, int x, int y, int w){
@@ -1564,12 +1565,12 @@
     for(i=0; i < s->nb_planes; i++){
         int hshift= i ? s->chroma_h_shift : 0;
         int vshift= i ? s->chroma_v_shift : 0;
-        for(y=0; y<(height>>vshift); y++)
+        for(y=0; y<FF_CEIL_RSHIFT(height, vshift); y++)
             memcpy(&s->input_picture->data[i][y * s->input_picture->linesize[i]],
                    &pict->data[i][y * pict->linesize[i]],
-                   width>>hshift);
+                   FF_CEIL_RSHIFT(width, hshift));
         s->mpvencdsp.draw_edges(s->input_picture->data[i], s->input_picture->linesize[i],
-                                width >> hshift, height >> vshift,
+                                FF_CEIL_RSHIFT(width, hshift), FF_CEIL_RSHIFT(height, vshift),
                                 EDGE_WIDTH >> hshift, EDGE_WIDTH >> vshift,
                                 EDGE_TOP | EDGE_BOTTOM);
 
@@ -1620,7 +1621,8 @@
     }
 
     ff_snow_frame_start(s);
-    avctx->coded_frame= s->current_picture;
+    av_frame_unref(avctx->coded_frame);
+    av_frame_ref(avctx->coded_frame, s->current_picture);
 
     s->m.current_picture_ptr= &s->m.current_picture;
     s->m.current_picture.f = s->current_picture;
@@ -1862,6 +1864,7 @@
     ff_snow_common_end(s);
     ff_rate_control_uninit(&s->m);
     av_frame_free(&s->input_picture);
+    av_frame_free(&avctx->coded_frame);
     av_freep(&avctx->stats_out);
 
     return 0;
diff --git a/libavcodec/sp5xdec.c b/libavcodec/sp5xdec.c
index 7496198..3e49c59e 100644
--- a/libavcodec/sp5xdec.c
+++ b/libavcodec/sp5xdec.c
@@ -25,6 +25,7 @@
  */
 
 #include "avcodec.h"
+#include "internal.h"
 #include "mjpeg.h"
 #include "mjpegdec.h"
 #include "sp5x.h"
@@ -105,6 +106,7 @@
     .decode         = sp5x_decode_frame,
     .capabilities   = CODEC_CAP_DR1,
     .max_lowres     = 3,
+    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE,
 };
 #endif
 #if CONFIG_AMV_DECODER
@@ -118,5 +120,6 @@
     .close          = ff_mjpeg_decode_end,
     .decode         = sp5x_decode_frame,
     .max_lowres     = 3,
+    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE,
 };
 #endif
diff --git a/libavcodec/srtdec.c b/libavcodec/srtdec.c
index 6d0c9bb..a2e6227 100644
--- a/libavcodec/srtdec.c
+++ b/libavcodec/srtdec.c
@@ -42,7 +42,7 @@
     PARAM_NUMBER
 };
 
-typedef struct {
+typedef struct SrtStack {
     char tag[128];
     char param[PARAM_NUMBER][128];
 } SrtStack;
diff --git a/libavcodec/svq1dec.c b/libavcodec/svq1dec.c
index 2f9ea16..f65915c 100644
--- a/libavcodec/svq1dec.c
+++ b/libavcodec/svq1dec.c
@@ -40,9 +40,6 @@
 #include "mathops.h"
 #include "svq1.h"
 
-#undef NDEBUG
-#include <assert.h>
-
 static VLC svq1_block_type;
 static VLC svq1_motion_component;
 static VLC svq1_intra_multistage[6];
@@ -165,7 +162,8 @@
     const uint32_t *codebook;
     int entries[6];
     int i, j, m, n;
-    int mean, stages;
+    int stages;
+    unsigned mean;
     unsigned x, y, width, height, level;
     uint32_t n1, n2, n3, n4;
 
@@ -190,12 +188,13 @@
             continue;   /* skip vector */
         }
 
-        if (stages > 0 && level >= 4) {
+        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 */
         }
+        av_assert0(stages >= 0);
 
         mean = get_vlc2(bitbuf, svq1_intra_mean.table, 8, 3);
 
@@ -230,7 +229,8 @@
     const uint32_t *codebook;
     int entries[6];
     int i, j, m, n;
-    int mean, stages;
+    int stages;
+    unsigned mean;
     int x, y, width, height, level;
     uint32_t n1, n2, n3, n4;
 
@@ -252,12 +252,13 @@
         if (stages == -1)
             continue;           /* skip vector */
 
-        if ((stages > 0) && (level >= 4)) {
+        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 */
         }
+        av_assert0(stages >= 0);
 
         mean = get_vlc2(bitbuf, svq1_inter_mean.table, 9, 3) - 256;
 
diff --git a/libavcodec/svq1enc.c b/libavcodec/svq1enc.c
index 0c5971b..ec540a2 100644
--- a/libavcodec/svq1enc.c
+++ b/libavcodec/svq1enc.c
@@ -595,9 +595,9 @@
         }
     }
     if (!s->last_picture->data[0]) {
-        if ((ret = ff_get_buffer(avctx, s->last_picture, 0)) < 0) {
+        ret = ff_get_buffer(avctx, s->last_picture, 0);
+        if (ret < 0)
             return ret;
-        }
     }
     if (!s->scratchbuf) {
         s->scratchbuf = av_malloc_array(s->current_picture->linesize[0], 16 * 3);
diff --git a/libavcodec/svq3.c b/libavcodec/svq3.c
index a3354d1..a7a8f67 100644
--- a/libavcodec/svq3.c
+++ b/libavcodec/svq3.c
@@ -69,7 +69,7 @@
  * svq3 decoder.
  */
 
-typedef struct {
+typedef struct SVQ3Context {
     H264Context h;
     HpelDSPContext hdsp;
     TpelDSPContext tdsp;
@@ -303,6 +303,7 @@
                                     int thirdpel, int dir, int avg)
 {
     H264Context *h = &s->h;
+    H264SliceContext *sl = &h->slice_ctx[0];
     const H264Picture *pic = (dir == 0) ? s->last_pic : s->next_pic;
     uint8_t *src, *dest;
     int i, emu = 0;
@@ -319,23 +320,23 @@
     }
 
     /* form component predictions */
-    dest = h->cur_pic.f.data[0] + x + y * h->linesize;
-    src  = pic->f.data[0] + mx + my * h->linesize;
+    dest = h->cur_pic.f.data[0] + x + y * sl->linesize;
+    src  = pic->f.data[0] + mx + my * sl->linesize;
 
     if (emu) {
-        h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src,
-                                 h->linesize, h->linesize,
+        h->vdsp.emulated_edge_mc(sl->edge_emu_buffer, src,
+                                 sl->linesize, sl->linesize,
                                  width + 1, height + 1,
                                  mx, my, s->h_edge_pos, s->v_edge_pos);
-        src = h->edge_emu_buffer;
+        src = sl->edge_emu_buffer;
     }
     if (thirdpel)
         (avg ? s->tdsp.avg_tpel_pixels_tab
-             : s->tdsp.put_tpel_pixels_tab)[dxy](dest, src, h->linesize,
+             : s->tdsp.put_tpel_pixels_tab)[dxy](dest, src, sl->linesize,
                                                  width, height);
     else
         (avg ? s->hdsp.avg_pixels_tab
-             : s->hdsp.put_pixels_tab)[blocksize][dxy](dest, src, h->linesize,
+             : s->hdsp.put_pixels_tab)[blocksize][dxy](dest, src, sl->linesize,
                                                        height);
 
     if (!(h->flags & CODEC_FLAG_GRAY)) {
@@ -346,26 +347,26 @@
         blocksize++;
 
         for (i = 1; i < 3; i++) {
-            dest = h->cur_pic.f.data[i] + (x >> 1) + (y >> 1) * h->uvlinesize;
-            src  = pic->f.data[i] + mx + my * h->uvlinesize;
+            dest = h->cur_pic.f.data[i] + (x >> 1) + (y >> 1) * sl->uvlinesize;
+            src  = pic->f.data[i] + mx + my * sl->uvlinesize;
 
             if (emu) {
-                h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src,
-                                         h->uvlinesize, h->uvlinesize,
+                h->vdsp.emulated_edge_mc(sl->edge_emu_buffer, src,
+                                         sl->uvlinesize, sl->uvlinesize,
                                          width + 1, height + 1,
                                          mx, my, (s->h_edge_pos >> 1),
                                          s->v_edge_pos >> 1);
-                src = h->edge_emu_buffer;
+                src = sl->edge_emu_buffer;
             }
             if (thirdpel)
                 (avg ? s->tdsp.avg_tpel_pixels_tab
                      : s->tdsp.put_tpel_pixels_tab)[dxy](dest, src,
-                                                         h->uvlinesize,
+                                                         sl->uvlinesize,
                                                          width, height);
             else
                 (avg ? s->hdsp.avg_pixels_tab
                      : s->hdsp.put_pixels_tab)[blocksize][dxy](dest, src,
-                                                               h->uvlinesize,
+                                                               sl->uvlinesize,
                                                                height);
         }
     }
@@ -376,6 +377,7 @@
 {
     int i, j, k, mx, my, dx, dy, x, y;
     H264Context *h          = &s->h;
+    H264SliceContext *sl    = &h->slice_ctx[0];
     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;
@@ -384,16 +386,16 @@
 
     for (i = 0; i < 16; i += part_height)
         for (j = 0; j < 16; j += part_width) {
-            const int b_xy = (4 * h->mb_x + (j >> 2)) +
-                             (4 * h->mb_y + (i >> 2)) * h->b_stride;
+            const int b_xy = (4 * sl->mb_x + (j >> 2)) +
+                             (4 * sl->mb_y + (i >> 2)) * h->b_stride;
             int dxy;
-            x = 16 * h->mb_x + j;
-            y = 16 * h->mb_y + i;
+            x = 16 * sl->mb_x + j;
+            y = 16 * sl->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, sl, k, part_width >> 2, dir, 1, &mx, &my);
             } else {
                 mx = s->next_pic->motion_val[0][b_xy][0] << 1;
                 my = s->next_pic->motion_val[0][b_xy][1] << 1;
@@ -465,15 +467,15 @@
                 int32_t mv = pack16to32(mx, my);
 
                 if (part_height == 8 && i < 8) {
-                    AV_WN32A(h->mv_cache[dir][scan8[k] + 1 * 8], mv);
+                    AV_WN32A(sl->mv_cache[dir][scan8[k] + 1 * 8], mv);
 
                     if (part_width == 8 && j < 8)
-                        AV_WN32A(h->mv_cache[dir][scan8[k] + 1 + 1 * 8], mv);
+                        AV_WN32A(sl->mv_cache[dir][scan8[k] + 1 + 1 * 8], mv);
                 }
                 if (part_width == 8 && j < 8)
-                    AV_WN32A(h->mv_cache[dir][scan8[k] + 1], mv);
+                    AV_WN32A(sl->mv_cache[dir][scan8[k] + 1], mv);
                 if (part_width == 4 || part_height == 4)
-                    AV_WN32A(h->mv_cache[dir][scan8[k]], mv);
+                    AV_WN32A(sl->mv_cache[dir][scan8[k]], mv);
             }
 
             /* write back motion vectors */
@@ -488,25 +490,26 @@
 static int svq3_decode_mb(SVQ3Context *s, unsigned int mb_type)
 {
     H264Context *h = &s->h;
+    H264SliceContext *sl = &h->slice_ctx[0];
     int i, j, k, m, dir, mode;
     int cbp = 0;
     uint32_t vlc;
     int8_t *top, *left;
-    const int mb_xy         = h->mb_xy;
-    const int b_xy          = 4 * h->mb_x + 4 * h->mb_y * h->b_stride;
+    const int mb_xy         = sl->mb_xy;
+    const int b_xy          = 4 * sl->mb_x + 4 * sl->mb_y * h->b_stride;
 
-    h->top_samples_available      = (h->mb_y == 0) ? 0x33FF : 0xFFFF;
-    h->left_samples_available     = (h->mb_x == 0) ? 0x5F5F : 0xFFFF;
-    h->topright_samples_available = 0xFFFF;
+    sl->top_samples_available      = (sl->mb_y == 0) ? 0x33FF : 0xFFFF;
+    sl->left_samples_available     = (sl->mb_x == 0) ? 0x5F5F : 0xFFFF;
+    sl->topright_samples_available = 0xFFFF;
 
     if (mb_type == 0) {           /* SKIP */
         if (h->pict_type == AV_PICTURE_TYPE_P ||
             s->next_pic->mb_type[mb_xy] == -1) {
-            svq3_mc_dir_part(s, 16 * h->mb_x, 16 * h->mb_y, 16, 16,
+            svq3_mc_dir_part(s, 16 * sl->mb_x, 16 * sl->mb_y, 16, 16,
                              0, 0, 0, 0, 0, 0);
 
             if (h->pict_type == AV_PICTURE_TYPE_B)
-                svq3_mc_dir_part(s, 16 * h->mb_x, 16 * h->mb_y, 16, 16,
+                svq3_mc_dir_part(s, 16 * sl->mb_x, 16 * sl->mb_y, 16, 16,
                                  0, 0, 0, 0, 1, 1);
 
             mb_type = MB_TYPE_SKIP;
@@ -538,38 +541,38 @@
          */
 
         for (m = 0; m < 2; m++) {
-            if (h->mb_x > 0 && h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - 1] + 6] != -1) {
+            if (sl->mb_x > 0 && sl->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],
+                    AV_COPY32(sl->mv_cache[m][scan8[0] - 1 + i * 8],
                               h->cur_pic.motion_val[m][b_xy - 1 + i * h->b_stride]);
             } else {
                 for (i = 0; i < 4; i++)
-                    AV_ZERO32(h->mv_cache[m][scan8[0] - 1 + i * 8]);
+                    AV_ZERO32(sl->mv_cache[m][scan8[0] - 1 + i * 8]);
             }
-            if (h->mb_y > 0) {
-                memcpy(h->mv_cache[m][scan8[0] - 1 * 8],
+            if (sl->mb_y > 0) {
+                memcpy(sl->mv_cache[m][scan8[0] - 1 * 8],
                        h->cur_pic.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 - h->mb_stride]] == -1) ? PART_NOT_AVAILABLE : 1, 4);
+                memset(&sl->ref_cache[m][scan8[0] - 1 * 8],
+                       (sl->intra4x4_pred_mode[h->mb2br_xy[mb_xy - h->mb_stride]] == -1) ? PART_NOT_AVAILABLE : 1, 4);
 
-                if (h->mb_x < h->mb_width - 1) {
-                    AV_COPY32(h->mv_cache[m][scan8[0] + 4 - 1 * 8],
+                if (sl->mb_x < h->mb_width - 1) {
+                    AV_COPY32(sl->mv_cache[m][scan8[0] + 4 - 1 * 8],
                               h->cur_pic.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 - h->mb_stride + 1] + 6] == -1 ||
-                         h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - h->mb_stride]] == -1) ? PART_NOT_AVAILABLE : 1;
+                    sl->ref_cache[m][scan8[0] + 4 - 1 * 8] =
+                        (sl->intra4x4_pred_mode[h->mb2br_xy[mb_xy - h->mb_stride + 1] + 6] == -1 ||
+                         sl->intra4x4_pred_mode[h->mb2br_xy[mb_xy - h->mb_stride]] == -1) ? PART_NOT_AVAILABLE : 1;
                 } else
-                    h->ref_cache[m][scan8[0] + 4 - 1 * 8] = PART_NOT_AVAILABLE;
-                if (h->mb_x > 0) {
-                    AV_COPY32(h->mv_cache[m][scan8[0] - 1 - 1 * 8],
+                    sl->ref_cache[m][scan8[0] + 4 - 1 * 8] = PART_NOT_AVAILABLE;
+                if (sl->mb_x > 0) {
+                    AV_COPY32(sl->mv_cache[m][scan8[0] - 1 - 1 * 8],
                               h->cur_pic.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 - h->mb_stride - 1] + 3] == -1) ? PART_NOT_AVAILABLE : 1;
+                    sl->ref_cache[m][scan8[0] - 1 - 1 * 8] =
+                        (sl->intra4x4_pred_mode[h->mb2br_xy[mb_xy - h->mb_stride - 1] + 3] == -1) ? PART_NOT_AVAILABLE : 1;
                 } else
-                    h->ref_cache[m][scan8[0] - 1 - 1 * 8] = PART_NOT_AVAILABLE;
+                    sl->ref_cache[m][scan8[0] - 1 - 1 * 8] = PART_NOT_AVAILABLE;
             } else
-                memset(&h->ref_cache[m][scan8[0] - 1 * 8 - 1],
+                memset(&sl->ref_cache[m][scan8[0] - 1 * 8 - 1],
                        PART_NOT_AVAILABLE, 8);
 
             if (h->pict_type != AV_PICTURE_TYPE_B)
@@ -601,23 +604,23 @@
 
         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(sl->intra4x4_pred_mode_cache, -1, 8 * 5 * sizeof(int8_t));
 
         if (mb_type == 8) {
-            if (h->mb_x > 0) {
+            if (sl->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)
-                    h->left_samples_available = 0x5F5F;
+                    sl->intra4x4_pred_mode_cache[scan8[0] - 1 + i * 8] = sl->intra4x4_pred_mode[h->mb2br_xy[mb_xy - 1] + 6 - i];
+                if (sl->intra4x4_pred_mode_cache[scan8[0] - 1] == -1)
+                    sl->left_samples_available = 0x5F5F;
             }
-            if (h->mb_y > 0) {
-                h->intra4x4_pred_mode_cache[4 + 8 * 0] = h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - h->mb_stride] + 0];
-                h->intra4x4_pred_mode_cache[5 + 8 * 0] = h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - h->mb_stride] + 1];
-                h->intra4x4_pred_mode_cache[6 + 8 * 0] = h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - h->mb_stride] + 2];
-                h->intra4x4_pred_mode_cache[7 + 8 * 0] = h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - h->mb_stride] + 3];
+            if (sl->mb_y > 0) {
+                sl->intra4x4_pred_mode_cache[4 + 8 * 0] = sl->intra4x4_pred_mode[h->mb2br_xy[mb_xy - h->mb_stride] + 0];
+                sl->intra4x4_pred_mode_cache[5 + 8 * 0] = sl->intra4x4_pred_mode[h->mb2br_xy[mb_xy - h->mb_stride] + 1];
+                sl->intra4x4_pred_mode_cache[6 + 8 * 0] = sl->intra4x4_pred_mode[h->mb2br_xy[mb_xy - h->mb_stride] + 2];
+                sl->intra4x4_pred_mode_cache[7 + 8 * 0] = sl->intra4x4_pred_mode[h->mb2br_xy[mb_xy - h->mb_stride] + 3];
 
-                if (h->intra4x4_pred_mode_cache[4 + 8 * 0] == -1)
-                    h->top_samples_available = 0x33FF;
+                if (sl->intra4x4_pred_mode_cache[4 + 8 * 0] == -1)
+                    sl->top_samples_available = 0x33FF;
             }
 
             /* decode prediction codes for luma blocks */
@@ -630,8 +633,8 @@
                     return -1;
                 }
 
-                left = &h->intra4x4_pred_mode_cache[scan8[i] - 1];
-                top  = &h->intra4x4_pred_mode_cache[scan8[i] - 8];
+                left = &sl->intra4x4_pred_mode_cache[scan8[i] - 1];
+                top  = &sl->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]];
@@ -643,22 +646,22 @@
             }
         } 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);
+                memset(&sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i], DC_PRED, 4);
         }
 
-        write_back_intra_pred_mode(h);
+        write_back_intra_pred_mode(h, sl);
 
         if (mb_type == 8) {
-            ff_h264_check_intra4x4_pred_mode(h);
+            ff_h264_check_intra4x4_pred_mode(h, sl);
 
-            h->top_samples_available  = (h->mb_y == 0) ? 0x33FF : 0xFFFF;
-            h->left_samples_available = (h->mb_x == 0) ? 0x5F5F : 0xFFFF;
+            sl->top_samples_available  = (sl->mb_y == 0) ? 0x33FF : 0xFFFF;
+            sl->left_samples_available = (sl->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);
+                memset(&sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i], DC_128_PRED, 4);
 
-            h->top_samples_available  = 0x33FF;
-            h->left_samples_available = 0x5F5F;
+            sl->top_samples_available  = 0x33FF;
+            sl->left_samples_available = 0x5F5F;
         }
 
         mb_type = MB_TYPE_INTRA4x4;
@@ -666,9 +669,9 @@
         dir = i_mb_type_info[mb_type - 8].pred_mode;
         dir = (dir >> 1) ^ 3 * (dir & 1) ^ 1;
 
-        if ((h->intra16x16_pred_mode = ff_h264_check_intra_pred_mode(h, dir, 0)) < 0) {
+        if ((sl->intra16x16_pred_mode = ff_h264_check_intra_pred_mode(h, sl, dir, 0)) < 0) {
             av_log(h->avctx, AV_LOG_ERROR, "ff_h264_check_intra_pred_mode < 0\n");
-            return h->intra16x16_pred_mode;
+            return sl->intra16x16_pred_mode;
         }
 
         cbp     = i_mb_type_info[mb_type - 8].cbp;
@@ -686,10 +689,10 @@
         }
     }
     if (!IS_INTRA4x4(mb_type)) {
-        memset(h->intra4x4_pred_mode + h->mb2br_xy[mb_xy], DC_PRED, 8);
+        memset(sl->intra4x4_pred_mode + h->mb2br_xy[mb_xy], DC_PRED, 8);
     }
     if (!IS_SKIP(mb_type) || h->pict_type == AV_PICTURE_TYPE_B) {
-        memset(h->non_zero_count_cache + 8, 0, 14 * 8 * sizeof(uint8_t));
+        memset(sl->non_zero_count_cache + 8, 0, 14 * 8 * sizeof(uint8_t));
     }
 
     if (!IS_INTRA16x16(mb_type) &&
@@ -704,17 +707,17 @@
     }
     if (IS_INTRA16x16(mb_type) ||
         (h->pict_type != AV_PICTURE_TYPE_I && s->adaptive_quant && cbp)) {
-        h->qscale += svq3_get_se_golomb(&h->gb);
+        sl->qscale += svq3_get_se_golomb(&h->gb);
 
-        if (h->qscale > 31u) {
-            av_log(h->avctx, AV_LOG_ERROR, "qscale:%d\n", h->qscale);
+        if (sl->qscale > 31u) {
+            av_log(h->avctx, AV_LOG_ERROR, "qscale:%d\n", sl->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(&h->gb, h->mb_luma_dc[0], 0, 1)) {
+        AV_ZERO128(sl->mb_luma_dc[0] + 0);
+        AV_ZERO128(sl->mb_luma_dc[0] + 8);
+        if (svq3_decode_block(&h->gb, sl->mb_luma_dc[0], 0, 1)) {
             av_log(h->avctx, AV_LOG_ERROR,
                    "error while decoding intra luma dc\n");
             return -1;
@@ -723,7 +726,7 @@
 
     if (cbp) {
         const int index = IS_INTRA16x16(mb_type) ? 1 : 0;
-        const int type  = ((h->qscale < 24 && IS_INTRA4x4(mb_type)) ? 2 : 1);
+        const int type  = ((sl->qscale < 24 && IS_INTRA4x4(mb_type)) ? 2 : 1);
 
         for (i = 0; i < 4; i++)
             if ((cbp & (1 << i))) {
@@ -731,9 +734,9 @@
                     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;
+                    sl->non_zero_count_cache[scan8[k]] = 1;
 
-                    if (svq3_decode_block(&h->gb, &h->mb[16 * k], index, type)) {
+                    if (svq3_decode_block(&h->gb, &sl->mb[16 * k], index, type)) {
                         av_log(h->avctx, AV_LOG_ERROR,
                                "error while decoding block\n");
                         return -1;
@@ -743,7 +746,7 @@
 
         if ((cbp & 0x30)) {
             for (i = 1; i < 3; ++i)
-                if (svq3_decode_block(&h->gb, &h->mb[16 * 16 * i], 0, 3)) {
+                if (svq3_decode_block(&h->gb, &sl->mb[16 * 16 * i], 0, 3)) {
                     av_log(h->avctx, AV_LOG_ERROR,
                            "error while decoding chroma dc block\n");
                     return -1;
@@ -753,9 +756,9 @@
                 for (i = 1; i < 3; i++) {
                     for (j = 0; j < 4; j++) {
                         k                                 = 16 * i + j;
-                        h->non_zero_count_cache[scan8[k]] = 1;
+                        sl->non_zero_count_cache[scan8[k]] = 1;
 
-                        if (svq3_decode_block(&h->gb, &h->mb[16 * k], 1, 1)) {
+                        if (svq3_decode_block(&h->gb, &sl->mb[16 * k], 1, 1)) {
                             av_log(h->avctx, AV_LOG_ERROR,
                                    "error while decoding chroma ac block\n");
                             return -1;
@@ -766,11 +769,11 @@
         }
     }
 
-    h->cbp                              = cbp;
+    sl->cbp                   = cbp;
     h->cur_pic.mb_type[mb_xy] = mb_type;
 
     if (IS_INTRA(mb_type))
-        h->chroma_pred_mode = ff_h264_check_intra_pred_mode(h, DC_PRED8x8, 1);
+        sl->chroma_pred_mode = ff_h264_check_intra_pred_mode(h, sl, DC_PRED8x8, 1);
 
     return 0;
 }
@@ -779,7 +782,8 @@
 {
     SVQ3Context *s = avctx->priv_data;
     H264Context *h    = &s->h;
-    const int mb_xy   = h->mb_xy;
+    H264SliceContext *sl = &h->slice_ctx[0];
+    const int mb_xy   = sl->mb_xy;
     int i, header;
     unsigned slice_id;
 
@@ -821,19 +825,19 @@
         return -1;
     }
 
-    h->slice_type = golomb_to_pict_type[slice_id];
+    sl->slice_type = golomb_to_pict_type[slice_id];
 
     if ((header & 0x9F) == 2) {
         i              = (h->mb_num < 64) ? 6 : (1 + av_log2(h->mb_num - 1));
-        h->mb_skip_run = get_bits(&h->gb, i) -
-                         (h->mb_y * h->mb_width + h->mb_x);
+        sl->mb_skip_run = get_bits(&h->gb, i) -
+                         (sl->mb_y * h->mb_width + sl->mb_x);
     } else {
         skip_bits1(&h->gb);
-        h->mb_skip_run = 0;
+        sl->mb_skip_run = 0;
     }
 
-    h->slice_num      = get_bits(&h->gb, 8);
-    h->qscale         = get_bits(&h->gb, 5);
+    sl->slice_num     = get_bits(&h->gb, 8);
+    sl->qscale        = get_bits(&h->gb, 5);
     s->adaptive_quant = get_bits1(&h->gb);
 
     /* unknown fields */
@@ -849,18 +853,18 @@
         return AVERROR_INVALIDDATA;
 
     /* reset intra predictors and invalidate motion vector references */
-    if (h->mb_x > 0) {
-        memset(h->intra4x4_pred_mode + h->mb2br_xy[mb_xy - 1] + 3,
+    if (sl->mb_x > 0) {
+        memset(sl->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 - h->mb_x],
-               -1, 8 * sizeof(int8_t) * h->mb_x);
+        memset(sl->intra4x4_pred_mode + h->mb2br_xy[mb_xy - sl->mb_x],
+               -1, 8 * sizeof(int8_t) * sl->mb_x);
     }
-    if (h->mb_y > 0) {
-        memset(h->intra4x4_pred_mode + h->mb2br_xy[mb_xy - h->mb_stride],
-               -1, 8 * sizeof(int8_t) * (h->mb_width - h->mb_x));
+    if (sl->mb_y > 0) {
+        memset(sl->intra4x4_pred_mode + h->mb2br_xy[mb_xy - h->mb_stride],
+               -1, 8 * sizeof(int8_t) * (h->mb_width - sl->mb_x));
 
-        if (h->mb_x > 0)
-            h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - h->mb_stride - 1] + 3] = -1;
+        if (sl->mb_x > 0)
+            sl->intra4x4_pred_mode[h->mb2br_xy[mb_xy - h->mb_stride - 1] + 3] = -1;
     }
 
     return 0;
@@ -870,6 +874,7 @@
 {
     SVQ3Context *s = avctx->priv_data;
     H264Context *h = &s->h;
+    H264SliceContext *sl;
     int m;
     unsigned char *extradata;
     unsigned char *extradata_end;
@@ -891,14 +896,16 @@
     ff_hpeldsp_init(&s->hdsp, avctx->flags);
     ff_tpeldsp_init(&s->tdsp);
 
+    sl = h->slice_ctx;
+
     h->flags           = avctx->flags;
-    h->is_complex      = 1;
+    sl->is_complex     = 1;
     h->sps.chroma_format_idc = 1;
     h->picture_structure = PICT_FRAME;
     avctx->pix_fmt     = AV_PIX_FMT_YUVJ420P;
     avctx->color_range = AVCOL_RANGE_JPEG;
 
-    h->chroma_qp[0] = h->chroma_qp[1] = 4;
+    h->slice_ctx[0].chroma_qp[0] = h->slice_ctx[0].chroma_qp[1] = 4;
     h->chroma_x_shift = h->chroma_y_shift = 1;
 
     s->halfpel_flag  = 1;
@@ -1076,6 +1083,7 @@
 {
     SVQ3Context *s = avctx->priv_data;
     H264Context *h = &s->h;
+    H264SliceContext *sl = &h->slice_ctx[0];
     const int big_mb_num    = h->mb_stride * (h->mb_height + 1) + 1;
     const int mb_array_size = h->mb_stride * h->mb_height;
     const int b4_stride     = h->mb_width * 4 + 1;
@@ -1109,14 +1117,14 @@
     if (ret < 0)
         goto fail;
 
-    if (!h->edge_emu_buffer) {
-        h->edge_emu_buffer = av_mallocz_array(pic->f.linesize[0], 17);
-        if (!h->edge_emu_buffer)
+    if (!sl->edge_emu_buffer) {
+        sl->edge_emu_buffer = av_mallocz_array(pic->f.linesize[0], 17);
+        if (!sl->edge_emu_buffer)
             return AVERROR(ENOMEM);
     }
 
-    h->linesize   = pic->f.linesize[0];
-    h->uvlinesize = pic->f.linesize[1];
+    sl->linesize   = pic->f.linesize[0];
+    sl->uvlinesize = pic->f.linesize[1];
 
     return 0;
 fail:
@@ -1129,6 +1137,7 @@
 {
     SVQ3Context *s     = avctx->priv_data;
     H264Context *h     = &s->h;
+    H264SliceContext *sl = &h->slice_ctx[0];
     int buf_size       = avpkt->size;
     int left;
     uint8_t *buf;
@@ -1146,7 +1155,7 @@
         return 0;
     }
 
-    h->mb_x = h->mb_y = h->mb_xy = 0;
+    sl->mb_x = sl->mb_y = sl->mb_xy = 0;
 
     if (s->watermark_key) {
         av_fast_padded_malloc(&s->buf, &s->buf_size, buf_size);
@@ -1163,7 +1172,7 @@
     if (svq3_decode_slice_header(avctx))
         return -1;
 
-    h->pict_type = h->slice_type;
+    h->pict_type = sl->slice_type;
 
     if (h->pict_type != AV_PICTURE_TYPE_B)
         FFSWAP(H264Picture*, s->next_pic, s->last_pic);
@@ -1186,14 +1195,14 @@
         return ret;
 
     for (i = 0; i < 16; i++) {
-        h->block_offset[i]           = (4 * ((scan8[i] - scan8[0]) & 7)) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
-        h->block_offset[48 + i]      = (4 * ((scan8[i] - scan8[0]) & 7)) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
+        h->block_offset[i]           = (4 * ((scan8[i] - scan8[0]) & 7)) + 4 * sl->linesize * ((scan8[i] - scan8[0]) >> 3);
+        h->block_offset[48 + i]      = (4 * ((scan8[i] - scan8[0]) & 7)) + 8 * sl->linesize * ((scan8[i] - scan8[0]) >> 3);
     }
     for (i = 0; i < 16; i++) {
         h->block_offset[16 + i]      =
-        h->block_offset[32 + i]      = (4 * ((scan8[i] - scan8[0]) & 7)) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
+        h->block_offset[32 + i]      = (4 * ((scan8[i] - scan8[0]) & 7)) + 4 * sl->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
         h->block_offset[48 + 16 + i] =
-        h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7)) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
+        h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7)) + 8 * sl->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
     }
 
     if (h->pict_type != AV_PICTURE_TYPE_I) {
@@ -1229,7 +1238,7 @@
                "%c hpel:%d, tpel:%d aqp:%d qp:%d, slice_num:%02X\n",
                av_get_picture_type_char(h->pict_type),
                s->halfpel_flag, s->thirdpel_flag,
-               s->adaptive_quant, h->qscale, h->slice_num);
+               s->adaptive_quant, h->slice_ctx[0].qscale, sl->slice_num);
 
     if (avctx->skip_frame >= AVDISCARD_NONREF && h->pict_type == AV_PICTURE_TYPE_B ||
         avctx->skip_frame >= AVDISCARD_NONKEY && h->pict_type != AV_PICTURE_TYPE_I ||
@@ -1244,7 +1253,7 @@
     }
 
     if (h->pict_type == AV_PICTURE_TYPE_B) {
-        h->frame_num_offset = h->slice_num - h->prev_frame_num;
+        h->frame_num_offset = sl->slice_num - h->prev_frame_num;
 
         if (h->frame_num_offset < 0)
             h->frame_num_offset += 256;
@@ -1255,7 +1264,7 @@
         }
     } else {
         h->prev_frame_num        = h->frame_num;
-        h->frame_num             = h->slice_num;
+        h->frame_num             = sl->slice_num;
         h->prev_frame_num_offset = h->frame_num - h->prev_frame_num;
 
         if (h->prev_frame_num_offset < 0)
@@ -1267,16 +1276,16 @@
         for (i = 0; i < 4; i++) {
             int j;
             for (j = -1; j < 4; j++)
-                h->ref_cache[m][scan8[0] + 8 * i + j] = 1;
+                sl->ref_cache[m][scan8[0] + 8 * i + j] = 1;
             if (i < 3)
-                h->ref_cache[m][scan8[0] + 8 * i + j] = PART_NOT_AVAILABLE;
+                sl->ref_cache[m][scan8[0] + 8 * i + j] = PART_NOT_AVAILABLE;
         }
     }
 
-    for (h->mb_y = 0; h->mb_y < h->mb_height; h->mb_y++) {
-        for (h->mb_x = 0; h->mb_x < h->mb_width; h->mb_x++) {
+    for (sl->mb_y = 0; sl->mb_y < h->mb_height; sl->mb_y++) {
+        for (sl->mb_x = 0; sl->mb_x < h->mb_width; sl->mb_x++) {
             unsigned mb_type;
-            h->mb_xy = h->mb_x + h->mb_y * h->mb_stride;
+            sl->mb_xy = sl->mb_x + sl->mb_y * h->mb_stride;
 
             if ((get_bits_count(&h->gb) + 7) >= h->gb.size_in_bits &&
                 ((get_bits_count(&h->gb) & 7) == 0 ||
@@ -1298,28 +1307,28 @@
                 mb_type += 4;
             if (mb_type > 33 || svq3_decode_mb(s, mb_type)) {
                 av_log(h->avctx, AV_LOG_ERROR,
-                       "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
+                       "error while decoding MB %d %d\n", sl->mb_x, sl->mb_y);
                 return -1;
             }
 
-            if (mb_type != 0 || h->cbp)
-                ff_h264_hl_decode_mb(h);
+            if (mb_type != 0 || sl->cbp)
+                ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
 
             if (h->pict_type != AV_PICTURE_TYPE_B && !h->low_delay)
-                h->cur_pic.mb_type[h->mb_x + h->mb_y * h->mb_stride] =
+                h->cur_pic.mb_type[sl->mb_x + sl->mb_y * h->mb_stride] =
                     (h->pict_type == AV_PICTURE_TYPE_P && mb_type < 8) ? (mb_type - 1) : -1;
         }
 
         ff_draw_horiz_band(avctx, &s->cur_pic->f,
                            s->last_pic->f.data[0] ? &s->last_pic->f : NULL,
-                           16 * h->mb_y, 16, h->picture_structure, 0,
+                           16 * sl->mb_y, 16, h->picture_structure, 0,
                            h->low_delay);
     }
 
     left = buf_size*8 - get_bits_count(&h->gb);
 
-    if (h->mb_y != h->mb_height || h->mb_x != h->mb_width) {
-        av_log(avctx, AV_LOG_INFO, "frame num %d incomplete pic x %d y %d left %d\n", avctx->frame_number, h->mb_y, h->mb_x, left);
+    if (sl->mb_y != h->mb_height || sl->mb_x != h->mb_width) {
+        av_log(avctx, AV_LOG_INFO, "frame num %d incomplete pic x %d y %d left %d\n", avctx->frame_number, sl->mb_y, sl->mb_x, left);
         //av_hex_dump(stderr, buf+buf_size-8, 8);
     }
 
@@ -1366,7 +1375,6 @@
 
     av_freep(&s->buf);
     s->buf_size = 0;
-    av_freep(&h->edge_emu_buffer);
 
     return 0;
 }
diff --git a/libavcodec/tak_parser.c b/libavcodec/tak_parser.c
index 5d8460c..4f2149a 100644
--- a/libavcodec/tak_parser.c
+++ b/libavcodec/tak_parser.c
@@ -43,10 +43,12 @@
     GetBitContext gb;
     int consumed = 0;
     int needed   = buf_size ? TAK_MAX_FRAME_HEADER_BYTES : 8;
+    int ret;
 
     if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
         TAKStreamInfo ti;
-        init_get_bits(&gb, buf, buf_size);
+        if ((ret = init_get_bits8(&gb, buf, buf_size)) < 0)
+            return ret;
         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;
@@ -73,8 +75,9 @@
                 pc->buffer[ t->index + 1 ] == 0xA0) {
                 TAKStreamInfo ti;
 
-                init_get_bits(&gb, pc->buffer + t->index,
-                              8 * (pc->index - t->index));
+                if ((ret = init_get_bits8(&gb, pc->buffer + t->index,
+                                          pc->index - t->index)) < 0)
+                    return ret;
                 if (!ff_tak_decode_frame_header(avctx, &gb,
                         pc->frame_start_found ? &ti : &t->ti, 127) &&
                     !ff_tak_check_crc(pc->buffer + t->index,
diff --git a/libavcodec/takdec.c b/libavcodec/takdec.c
index 2f0155d..a453da8 100644
--- a/libavcodec/takdec.c
+++ b/libavcodec/takdec.c
@@ -476,7 +476,7 @@
                      s->residues[i + j + 1] * s->filter[j + 1] +
                      s->residues[i + j    ] * s->filter[j    ];
             }
-            v = (av_clip(v >> filter_quant, -8192, 8191) << dshift) - *decoded;
+            v = (av_clip_intp2(v >> filter_quant, 13) << dshift) - *decoded;
             *decoded++ = v;
             s->residues[filter_order + i] = v >> dshift;
         }
@@ -652,7 +652,7 @@
                          s->residues[i    ] * s->filter[0];
                 }
 
-                v = (av_clip(v >> 10, -8192, 8191) << dshift) - *p1;
+                v = (av_clip_intp2(v >> 10, 13) << dshift) - *p1;
                 *p1++ = v;
             }
 
diff --git a/libavcodec/tdsc.c b/libavcodec/tdsc.c
new file mode 100644
index 0000000..8f0ebe7
--- /dev/null
+++ b/libavcodec/tdsc.c
@@ -0,0 +1,627 @@
+/*
+ * TDSC decoder
+ * Copyright (C) 2015 Vittorio Giovara <vittorio.giovara@gmail.com>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * TDSC decoder
+ *
+ * Fourcc: TSDC
+ *
+ * TDSC is very simple. It codes picture by tiles, storing them in raw BGR24
+ * format or compressing them in JPEG. Frames can be full pictures or just
+ * updates to the previous frame. Cursor is found in its own frame or at the
+ * bottom of the picture. Every frame is then packed with zlib.
+ *
+ * Supports: BGR24
+ */
+
+#include <stdint.h>
+#include <zlib.h>
+
+#include "libavutil/imgutils.h"
+
+#include "avcodec.h"
+#include "bytestream.h"
+#include "internal.h"
+
+#define BITMAPINFOHEADER_SIZE 0x28
+#define TDSF_HEADER_SIZE      0x56
+#define TDSB_HEADER_SIZE      0x08
+
+typedef struct TDSCContext {
+    AVCodecContext *jpeg_avctx;   // wrapper context for MJPEG
+
+    int width, height;
+    GetByteContext gbc;
+
+    AVFrame *refframe;          // full decoded frame (without cursor)
+    AVFrame *jpgframe;          // decoded JPEG tile
+    uint8_t *tilebuffer;        // buffer containing tile data
+
+    /* zlib interation */
+    uint8_t *deflatebuffer;
+    uLongf deflatelen;
+
+    /* All that is cursor */
+    uint8_t    *cursor;
+    int        cursor_stride;
+    int        cursor_w, cursor_h, cursor_x, cursor_y;
+    int        cursor_hot_x, cursor_hot_y;
+} TDSCContext;
+
+/* 1 byte bits, 1 byte planes, 2 bytes format (probably) */
+enum TDSCCursorFormat {
+    CUR_FMT_MONO = 0x01010004,
+    CUR_FMT_BGRA = 0x20010004,
+    CUR_FMT_RGBA = 0x20010008,
+};
+
+static av_cold int tdsc_close(AVCodecContext *avctx)
+{
+    TDSCContext *ctx = avctx->priv_data;
+
+    av_frame_free(&ctx->refframe);
+    av_frame_free(&ctx->jpgframe);
+    av_freep(&ctx->deflatebuffer);
+    av_freep(&ctx->tilebuffer);
+    av_freep(&ctx->cursor);
+    avcodec_free_context(&ctx->jpeg_avctx);
+
+    return 0;
+}
+
+static av_cold int tdsc_init(AVCodecContext *avctx)
+{
+    TDSCContext *ctx = avctx->priv_data;
+    const AVCodec *codec;
+    int ret;
+
+    avctx->pix_fmt = AV_PIX_FMT_BGR24;
+
+    /* These needs to be set to estimate buffer and frame size */
+    if (!(avctx->width && avctx->height)) {
+        av_log(avctx, AV_LOG_ERROR, "Video size not set.\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    /* This value should be large enough for a RAW-only frame plus headers */
+    ctx->deflatelen = avctx->width * avctx->height * (3 + 1);
+    ret = av_reallocp(&ctx->deflatebuffer, ctx->deflatelen);
+    if (ret < 0)
+        return ret;
+
+    /* Allocate reference and JPEG frame */
+    ctx->refframe = av_frame_alloc();
+    ctx->jpgframe = av_frame_alloc();
+    if (!ctx->refframe || !ctx->jpgframe)
+        return AVERROR(ENOMEM);
+
+    /* Prepare everything needed for JPEG decoding */
+    codec = avcodec_find_decoder(AV_CODEC_ID_MJPEG);
+    if (!codec)
+        return AVERROR_BUG;
+    ctx->jpeg_avctx = avcodec_alloc_context3(codec);
+    if (!ctx->jpeg_avctx)
+        return AVERROR(ENOMEM);
+    ctx->jpeg_avctx->flags = avctx->flags;
+    ctx->jpeg_avctx->flags2 = avctx->flags2;
+    ctx->jpeg_avctx->dct_algo = avctx->dct_algo;
+    ctx->jpeg_avctx->idct_algo = avctx->idct_algo;
+    ret = ff_codec_open2_recursive(ctx->jpeg_avctx, codec, NULL);
+    if (ret < 0)
+        return ret;
+
+    /* Set the output pixel format on the reference frame */
+    ctx->refframe->format = avctx->pix_fmt;
+
+    return 0;
+}
+
+#define APPLY_ALPHA(src, new, alpha) \
+    src = (src * (256 - alpha) + new * alpha) >> 8
+
+/* Paint a region over a buffer, without drawing out of its bounds. */
+static void tdsc_paint_cursor(AVCodecContext *avctx, uint8_t *dst, int stride)
+{
+    TDSCContext *ctx = avctx->priv_data;
+    const uint8_t *cursor = ctx->cursor;
+    int x = ctx->cursor_x - ctx->cursor_hot_x;
+    int y = ctx->cursor_y - ctx->cursor_hot_y;
+    int w = ctx->cursor_w;
+    int h = ctx->cursor_h;
+    int i, j;
+
+    if (!ctx->cursor)
+        return;
+
+    if (x + w > ctx->width)
+        w = ctx->width - x;
+    if (y + h > ctx->height)
+        h = ctx->height - y;
+    if (x < 0) {
+        w      +=  x;
+        cursor += -x * 4;
+    } else {
+        dst    +=  x * 3;
+    }
+    if (y < 0) {
+        h      +=  y;
+        cursor += -y * ctx->cursor_stride;
+    } else {
+        dst    +=  y * stride;
+    }
+    if (w < 0 || h < 0)
+        return;
+
+    for (j = 0; j < h; j++) {
+        for (i = 0; i < w; i++) {
+            uint8_t alpha = cursor[i * 4];
+            APPLY_ALPHA(dst[i * 3 + 0], cursor[i * 4 + 1], alpha);
+            APPLY_ALPHA(dst[i * 3 + 1], cursor[i * 4 + 2], alpha);
+            APPLY_ALPHA(dst[i * 3 + 2], cursor[i * 4 + 3], alpha);
+        }
+        dst    += stride;
+        cursor += ctx->cursor_stride;
+    }
+}
+
+/* Load cursor data and store it in ABGR mode. */
+static int tdsc_load_cursor(AVCodecContext *avctx)
+{
+    TDSCContext *ctx  = avctx->priv_data;
+    int i, j, k, ret, bits, cursor_fmt;
+    uint8_t *dst;
+
+    ctx->cursor_hot_x = bytestream2_get_le16(&ctx->gbc);
+    ctx->cursor_hot_y = bytestream2_get_le16(&ctx->gbc);
+    ctx->cursor_w     = bytestream2_get_le16(&ctx->gbc);
+    ctx->cursor_h     = bytestream2_get_le16(&ctx->gbc);
+
+    ctx->cursor_stride = FFALIGN(ctx->cursor_w, 32) * 4;
+    cursor_fmt = bytestream2_get_le32(&ctx->gbc);
+
+    if (ctx->cursor_x >= avctx->width || ctx->cursor_y >= avctx->height) {
+        av_log(avctx, AV_LOG_ERROR,
+               "Invalid cursor position (%d.%d outside %dx%d).\n",
+               ctx->cursor_x, ctx->cursor_y, avctx->width, avctx->height);
+        return AVERROR_INVALIDDATA;
+    }
+    if (ctx->cursor_w < 1 || ctx->cursor_w > 256 ||
+        ctx->cursor_h < 1 || ctx->cursor_h > 256) {
+        av_log(avctx, AV_LOG_ERROR,
+               "Invalid cursor dimensions %dx%d.\n",
+               ctx->cursor_w, ctx->cursor_h);
+        return AVERROR_INVALIDDATA;
+    }
+    if (ctx->cursor_hot_x > ctx->cursor_w ||
+        ctx->cursor_hot_y > ctx->cursor_h) {
+        av_log(avctx, AV_LOG_WARNING, "Invalid hotspot position %d.%d.\n",
+               ctx->cursor_hot_x, ctx->cursor_hot_y);
+        ctx->cursor_hot_x = FFMIN(ctx->cursor_hot_x, ctx->cursor_w - 1);
+        ctx->cursor_hot_y = FFMIN(ctx->cursor_hot_y, ctx->cursor_h - 1);
+    }
+
+    ret = av_reallocp(&ctx->cursor, ctx->cursor_stride * ctx->cursor_h);
+    if (ret < 0) {
+        av_log(avctx, AV_LOG_ERROR, "Cannot allocate cursor buffer.\n");
+        return ret;
+    }
+
+    dst = ctx->cursor;
+    /* here data is packed in BE */
+    switch (cursor_fmt) {
+    case CUR_FMT_MONO:
+        for (j = 0; j < ctx->cursor_h; j++) {
+            for (i = 0; i < ctx->cursor_w; i += 32) {
+                bits = bytestream2_get_be32(&ctx->gbc);
+                for (k = 0; k < 32; k++) {
+                    dst[0] = !!(bits & 0x80000000);
+                    dst   += 4;
+                    bits <<= 1;
+                }
+            }
+            dst += ctx->cursor_stride - ctx->cursor_w * 4;
+        }
+
+        dst = ctx->cursor;
+        for (j = 0; j < ctx->cursor_h; j++) {
+            for (i = 0; i < ctx->cursor_w; i += 32) {
+                bits = bytestream2_get_be32(&ctx->gbc);
+                for (k = 0; k < 32; k++) {
+                    int mask_bit = !!(bits & 0x80000000);
+                    switch (dst[0] * 2 + mask_bit) {
+                    case 0:
+                        dst[0] = 0xFF;
+                        dst[1] = 0x00;
+                        dst[2] = 0x00;
+                        dst[3] = 0x00;
+                        break;
+                    case 1:
+                        dst[0] = 0xFF;
+                        dst[1] = 0xFF;
+                        dst[2] = 0xFF;
+                        dst[3] = 0xFF;
+                        break;
+                    default:
+                        dst[0] = 0x00;
+                        dst[1] = 0x00;
+                        dst[2] = 0x00;
+                        dst[3] = 0x00;
+                    }
+                    dst   += 4;
+                    bits <<= 1;
+                }
+            }
+            dst += ctx->cursor_stride - ctx->cursor_w * 4;
+        }
+        break;
+    case CUR_FMT_BGRA:
+    case CUR_FMT_RGBA:
+        /* Skip monochrome version of the cursor */
+        bytestream2_skip(&ctx->gbc,
+                         ctx->cursor_h * (FFALIGN(ctx->cursor_w, 32) >> 3));
+        if (cursor_fmt & 8) { // RGBA -> ABGR
+            for (j = 0; j < ctx->cursor_h; j++) {
+                for (i = 0; i < ctx->cursor_w; i++) {
+                    int val = bytestream2_get_be32(&ctx->gbc);
+                    *dst++ = val >> 24;
+                    *dst++ = val >> 16;
+                    *dst++ = val >>  8;
+                    *dst++ = val >>  0;
+                }
+                dst += ctx->cursor_stride - ctx->cursor_w * 4;
+            }
+        } else { // BGRA -> ABGR
+            for (j = 0; j < ctx->cursor_h; j++) {
+                for (i = 0; i < ctx->cursor_w; i++) {
+                    int val = bytestream2_get_be32(&ctx->gbc);
+                    *dst++ = val >>  0;
+                    *dst++ = val >> 24;
+                    *dst++ = val >> 16;
+                    *dst++ = val >>  8;
+                }
+                dst += ctx->cursor_stride - ctx->cursor_w * 4;
+            }
+        }
+        break;
+    default:
+        avpriv_request_sample(avctx, "Cursor format %08x", cursor_fmt);
+        return AVERROR_PATCHWELCOME;
+    }
+
+    return 0;
+}
+
+/* Convert a single YUV pixel to RGB. */
+static inline void tdsc_yuv2rgb(uint8_t *out, int Y, int U, int V)
+{
+    out[0] = av_clip_uint8(Y + (             91881 * V + 32768 >> 16));
+    out[1] = av_clip_uint8(Y + (-22554 * U - 46802 * V + 32768 >> 16));
+    out[2] = av_clip_uint8(Y + (116130 * U             + 32768 >> 16));
+}
+
+/* Convert a YUV420 buffer to a RGB buffer. */
+static av_always_inline void tdsc_blit(uint8_t *dst, int dst_stride,
+                                       const uint8_t *srcy, int srcy_stride,
+                                       const uint8_t *srcu, const uint8_t *srcv,
+                                       int srcuv_stride, int width, int height)
+{
+    int col, line;
+    for (line = 0; line < height; line++) {
+        for (col = 0; col < width; col++)
+            tdsc_yuv2rgb(dst + col * 3, srcy[col],
+                         srcu[col >> 1] - 128, srcv[col >> 1] - 128);
+
+        dst  +=   dst_stride;
+        srcy +=  srcy_stride;
+        srcu += srcuv_stride * (line & 1);
+        srcv += srcuv_stride * (line & 1);
+    }
+}
+
+/* Invoke the MJPEG decoder to decode the tile. */
+static int tdsc_decode_jpeg_tile(AVCodecContext *avctx, int tile_size,
+                                 int x, int y, int w, int h)
+{
+    TDSCContext *ctx = avctx->priv_data;
+    AVPacket jpkt;
+    int got_frame = 0;
+    int ret;
+
+    /* Prepare a packet and send to the MJPEG decoder */
+    av_init_packet(&jpkt);
+    jpkt.data = ctx->tilebuffer;
+    jpkt.size = tile_size;
+
+    ret = avcodec_decode_video2(ctx->jpeg_avctx, ctx->jpgframe,
+                                &got_frame, &jpkt);
+    if (ret < 0 || !got_frame || ctx->jpgframe->format != AV_PIX_FMT_YUVJ420P) {
+        av_log(avctx, AV_LOG_ERROR,
+               "JPEG decoding error (%d) for (%d) frame.\n",
+               ret, got_frame);
+
+        /* Normally skip, error if explode */
+        if (avctx->err_recognition & AV_EF_EXPLODE)
+            return AVERROR_INVALIDDATA;
+        else
+            return 0;
+    }
+
+    /* Let's paint ont the buffer */
+    tdsc_blit(ctx->refframe->data[0] + x * 3 + ctx->refframe->linesize[0] * y,
+              ctx->refframe->linesize[0],
+              ctx->jpgframe->data[0], ctx->jpgframe->linesize[0],
+              ctx->jpgframe->data[1], ctx->jpgframe->data[2],
+              ctx->jpgframe->linesize[1], w, h);
+
+    av_frame_unref(ctx->jpgframe);
+
+    return 0;
+}
+
+/* Parse frame and either copy data or decode JPEG. */
+static int tdsc_decode_tiles(AVCodecContext *avctx, int number_tiles)
+{
+    TDSCContext *ctx = avctx->priv_data;
+    int i;
+
+    /* Iterate over the number of tiles */
+    for (i = 0; i < number_tiles; i++) {
+        int tile_size;
+        int tile_mode;
+        int x, y, w, h;
+        int ret;
+
+        if (bytestream2_get_bytes_left(&ctx->gbc) < 4 ||
+            bytestream2_get_le32(&ctx->gbc) != MKTAG('T','D','S','B') ||
+            bytestream2_get_bytes_left(&ctx->gbc) < TDSB_HEADER_SIZE - 4) {
+            av_log(avctx, AV_LOG_ERROR, "TDSB tag is too small.\n");
+            return AVERROR_INVALIDDATA;
+        }
+
+        tile_size = bytestream2_get_le32(&ctx->gbc);
+        if (bytestream2_get_bytes_left(&ctx->gbc) < tile_size)
+            return AVERROR_INVALIDDATA;
+
+        tile_mode = bytestream2_get_le32(&ctx->gbc);
+        bytestream2_skip(&ctx->gbc, 4); // unknown
+        x = bytestream2_get_le32(&ctx->gbc);
+        y = bytestream2_get_le32(&ctx->gbc);
+        w = bytestream2_get_le32(&ctx->gbc) - x;
+        h = bytestream2_get_le32(&ctx->gbc) - y;
+
+        if (x >= ctx->width || y >= ctx->height) {
+            av_log(avctx, AV_LOG_ERROR,
+                   "Invalid tile position (%d.%d outside %dx%d).\n",
+                   x, y, ctx->width, ctx->height);
+            return AVERROR_INVALIDDATA;
+        }
+        if (x + w > ctx->width || y + h > ctx->height) {
+            av_log(avctx, AV_LOG_ERROR,
+                   "Invalid tile size %dx%d\n", w, h);
+            return AVERROR_INVALIDDATA;
+        }
+
+        ret = av_reallocp(&ctx->tilebuffer, tile_size);
+        if (!ctx->tilebuffer)
+            return ret;
+
+        bytestream2_get_buffer(&ctx->gbc, ctx->tilebuffer, tile_size);
+
+        if (tile_mode == MKTAG('G','E','P','J')) {
+            /* Decode JPEG tile and copy it in the reference frame */
+            ret = tdsc_decode_jpeg_tile(avctx, tile_size, x, y, w, h);
+            if (ret < 0)
+                return ret;
+        } else if (tile_mode == MKTAG(' ','W','A','R')) {
+            /* Just copy the buffer to output */
+            av_image_copy_plane(ctx->refframe->data[0] + x * 3 +
+                                ctx->refframe->linesize[0] * y,
+                                ctx->refframe->linesize[0], ctx->tilebuffer,
+                                w * 3, w * 3, h);
+        } else {
+            av_log(avctx, AV_LOG_ERROR, "Unknown tile type %08x.\n", tile_mode);
+            return AVERROR_INVALIDDATA;
+        }
+        av_log(avctx, AV_LOG_DEBUG, "Tile %d, %dx%d (%d.%d)\n", i, w, h, x, y);
+    }
+
+    return 0;
+}
+
+static int tdsc_parse_tdsf(AVCodecContext *avctx, int number_tiles)
+{
+    TDSCContext *ctx = avctx->priv_data;
+    int ret, w, h, init_refframe = !ctx->refframe->data[0];
+
+    /* BITMAPINFOHEADER
+     * http://msdn.microsoft.com/en-us/library/windows/desktop/dd183376.aspx */
+    if (bytestream2_get_le32(&ctx->gbc) != BITMAPINFOHEADER_SIZE)
+        return AVERROR_INVALIDDATA;
+
+    /* Store size, but wait for context reinit before updating avctx */
+    w =  bytestream2_get_le32(&ctx->gbc);
+    h = -bytestream2_get_le32(&ctx->gbc);
+
+    if (bytestream2_get_le16(&ctx->gbc) != 1 ||  // 1 plane
+        bytestream2_get_le16(&ctx->gbc) != 24)   // BGR24
+        return AVERROR_INVALIDDATA;
+
+    bytestream2_skip(&ctx->gbc, 24); // unused fields
+
+    /* Update sizes */
+    if (avctx->width != w || avctx->height != h) {
+        av_log(avctx, AV_LOG_DEBUG, "Size update %dx%d -> %d%d.\n",
+               avctx->width, avctx->height, ctx->width, ctx->height);
+        ret = ff_set_dimensions(avctx, w, h);
+        if (ret < 0)
+            return ret;
+        init_refframe = 1;
+    }
+    ctx->refframe->width  = ctx->width  = w;
+    ctx->refframe->height = ctx->height = h;
+
+    /* Allocate the reference frame if not already done or on size change */
+    if (init_refframe) {
+        ret = av_frame_get_buffer(ctx->refframe, 32);
+        if (ret < 0)
+            return ret;
+    }
+
+    /* Decode all tiles in a frame */
+    return tdsc_decode_tiles(avctx, number_tiles);
+}
+
+static int tdsc_parse_dtsm(AVCodecContext *avctx)
+{
+    TDSCContext *ctx = avctx->priv_data;
+    int ret;
+    int action = bytestream2_get_le32(&ctx->gbc);
+
+    bytestream2_skip(&ctx->gbc, 4); // some kind of ID or version maybe?
+
+    if (action == 2 || action == 3) {
+        /* Load cursor coordinates */
+        ctx->cursor_x = bytestream2_get_le32(&ctx->gbc);
+        ctx->cursor_y = bytestream2_get_le32(&ctx->gbc);
+
+        /* Load a full cursor sprite */
+        if (action == 3) {
+            ret = tdsc_load_cursor(avctx);
+            /* Do not consider cursor errors fatal unless in explode mode */
+            if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE))
+                return ret;
+        }
+    } else {
+        avpriv_request_sample(avctx, "Cursor action %d", action);
+    }
+
+    return 0;
+}
+
+static int tdsc_decode_frame(AVCodecContext *avctx, void *data,
+                             int *got_frame, AVPacket *avpkt)
+{
+    TDSCContext *ctx = avctx->priv_data;
+    AVFrame *frame = data;
+    int ret, tag_header, keyframe = 0;
+    uLongf dlen;
+
+    /* Resize deflate buffer on resolution change */
+    if (ctx->width != avctx->width || ctx->height != avctx->height) {
+        ctx->deflatelen = avctx->width * avctx->height * (3 + 1);
+        ret = av_reallocp(&ctx->deflatebuffer, ctx->deflatelen);
+        if (ret < 0)
+            return ret;
+    }
+    dlen = ctx->deflatelen;
+
+    /* Frames are deflated, need to inflate them first */
+    ret = uncompress(ctx->deflatebuffer, &dlen, avpkt->data, avpkt->size);
+    if (ret) {
+        av_log(avctx, AV_LOG_ERROR, "Deflate error %d.\n", ret);
+        return AVERROR_UNKNOWN;
+    }
+
+    bytestream2_init(&ctx->gbc, ctx->deflatebuffer, dlen);
+
+    /* Check for tag and for size info */
+    if (bytestream2_get_bytes_left(&ctx->gbc) < 4 + 4) {
+        av_log(avctx, AV_LOG_ERROR, "Frame is too small.\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    /* Read tag */
+    tag_header = bytestream2_get_le32(&ctx->gbc);
+
+    if (tag_header == MKTAG('T','D','S','F')) {
+        int number_tiles;
+        if (bytestream2_get_bytes_left(&ctx->gbc) < TDSF_HEADER_SIZE) {
+            av_log(avctx, AV_LOG_ERROR, "TDSF tag is too small.\n");
+            return AVERROR_INVALIDDATA;
+        }
+        /* First 4 bytes here are the number of GEPJ/WAR tiles in this frame */
+        number_tiles = bytestream2_get_le32(&ctx->gbc);
+
+        bytestream2_skip(&ctx->gbc, 4); // internal timestamp maybe?
+        keyframe = bytestream2_get_le32(&ctx->gbc) == 0x30;
+
+        ret = tdsc_parse_tdsf(avctx, number_tiles);
+        if (ret < 0)
+            return ret;
+
+        /* Check if there is anything else we are able to parse */
+        if (bytestream2_get_bytes_left(&ctx->gbc) >= 4 + 4)
+            tag_header = bytestream2_get_le32(&ctx->gbc);
+    }
+
+    /* This tag can be after a TDSF block or on its own frame */
+    if (tag_header == MKTAG('D','T','S','M')) {
+        /* First 4 bytes here are the total size in bytes for this frame */
+        int tag_size = bytestream2_get_le32(&ctx->gbc);
+
+        if (bytestream2_get_bytes_left(&ctx->gbc) < tag_size) {
+            av_log(avctx, AV_LOG_ERROR, "DTSM tag is too small.\n");
+            return AVERROR_INVALIDDATA;
+        }
+
+        ret = tdsc_parse_dtsm(avctx);
+        if (ret < 0)
+            return ret;
+    }
+
+    /* Get the output frame and copy the reference frame */
+    ret = ff_get_buffer(avctx, frame, 0);
+    if (ret < 0)
+        return ret;
+
+    ret = av_frame_copy(frame, ctx->refframe);
+    if (ret < 0)
+        return ret;
+
+    /* Paint the cursor on the output frame */
+    tdsc_paint_cursor(avctx, frame->data[0], frame->linesize[0]);
+
+    /* Frame is ready to be output */
+    if (keyframe) {
+        frame->pict_type = AV_PICTURE_TYPE_I;
+        frame->key_frame = 1;
+    } else {
+        frame->pict_type = AV_PICTURE_TYPE_P;
+    }
+    *got_frame = 1;
+
+    return 0;
+}
+
+AVCodec ff_tdsc_decoder = {
+    .name           = "tdsc",
+    .long_name      = NULL_IF_CONFIG_SMALL("TDSC"),
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = AV_CODEC_ID_TDSC,
+    .init           = tdsc_init,
+    .decode         = tdsc_decode_frame,
+    .close          = tdsc_close,
+    .priv_data_size = sizeof(TDSCContext),
+    .capabilities   = CODEC_CAP_DR1,
+    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE |
+                      FF_CODEC_CAP_INIT_CLEANUP,
+};
diff --git a/libavcodec/tiff.c b/libavcodec/tiff.c
index 8047f38..7a7f9b7 100644
--- a/libavcodec/tiff.c
+++ b/libavcodec/tiff.c
@@ -658,6 +658,14 @@
     int ret;
     int create_gray_palette = 0;
 
+    // make sure there is no aliasing in the following switch
+    if (s->bpp >= 100 || s->bppcount >= 10) {
+        av_log(s->avctx, AV_LOG_ERROR,
+               "Unsupported image parameters: bpp=%d, bppcount=%d\n",
+               s->bpp, s->bppcount);
+        return AVERROR_INVALIDDATA;
+    }
+
     switch (s->planar * 1000 + s->bpp * 10 + s->bppcount) {
     case 11:
         if (!s->palette_is_set) {
@@ -839,13 +847,6 @@
                 s->bpp = -1;
             }
         }
-        if (s->bpp > 64U) {
-            av_log(s->avctx, AV_LOG_ERROR,
-                   "This format is not supported (bpp=%d, %d components)\n",
-                   s->bpp, count);
-            s->bpp = 0;
-            return AVERROR_INVALIDDATA;
-        }
         break;
     case TIFF_SAMPLES_PER_PIXEL:
         if (count != 1) {
@@ -1158,6 +1159,13 @@
         }
     }
 end:
+    if (s->bpp > 64U) {
+        av_log(s->avctx, AV_LOG_ERROR,
+                "This format is not supported (bpp=%d, %d components)\n",
+                s->bpp, count);
+        s->bpp = 0;
+        return AVERROR_INVALIDDATA;
+    }
     bytestream2_seek(&s->gb, start, SEEK_SET);
     return 0;
 }
@@ -1293,6 +1301,8 @@
             ssize = s->width * soff;
             if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48LE ||
                 s->avctx->pix_fmt == AV_PIX_FMT_RGBA64LE ||
+                s->avctx->pix_fmt == AV_PIX_FMT_GRAY16LE ||
+                s->avctx->pix_fmt == AV_PIX_FMT_YA16LE ||
                 s->avctx->pix_fmt == AV_PIX_FMT_GBRP16LE ||
                 s->avctx->pix_fmt == AV_PIX_FMT_GBRAP16LE) {
                 for (i = 0; i < s->height; i++) {
@@ -1302,6 +1312,8 @@
                 }
             } else if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
                        s->avctx->pix_fmt == AV_PIX_FMT_RGBA64BE ||
+                       s->avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
+                       s->avctx->pix_fmt == AV_PIX_FMT_YA16BE ||
                        s->avctx->pix_fmt == AV_PIX_FMT_GBRP16BE ||
                        s->avctx->pix_fmt == AV_PIX_FMT_GBRAP16BE) {
                 for (i = 0; i < s->height; i++) {
diff --git a/libavcodec/truespeech.c b/libavcodec/truespeech.c
index b00a45f..f9e8602 100644
--- a/libavcodec/truespeech.c
+++ b/libavcodec/truespeech.c
@@ -35,7 +35,7 @@
 /**
  * TrueSpeech decoder context
  */
-typedef struct {
+typedef struct TSContext {
     BswapDSPContext bdsp;
     /* input data */
     DECLARE_ALIGNED(16, uint8_t, buffer)[32];
diff --git a/libavcodec/tscc.c b/libavcodec/tscc.c
index 628a6b3..f9b325b 100644
--- a/libavcodec/tscc.c
+++ b/libavcodec/tscc.c
@@ -133,7 +133,7 @@
     case 24:
              avctx->pix_fmt = AV_PIX_FMT_BGR24;
              break;
-    case 32: avctx->pix_fmt = AV_PIX_FMT_RGB32; break;
+    case 32: avctx->pix_fmt = AV_PIX_FMT_0RGB32; 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/twinvq.h b/libavcodec/twinvq.h
index ae0f595..206eeaa 100644
--- a/libavcodec/twinvq.h
+++ b/libavcodec/twinvq.h
@@ -197,7 +197,7 @@
 
 int ff_twinvq_decode_frame(AVCodecContext *avctx, void *data,
                            int *got_frame_ptr, AVPacket *avpkt);
-av_cold int ff_twinvq_decode_close(AVCodecContext *avctx);
-av_cold int ff_twinvq_decode_init(AVCodecContext *avctx);
+int ff_twinvq_decode_close(AVCodecContext *avctx);
+int ff_twinvq_decode_init(AVCodecContext *avctx);
 
 #endif /* AVCODEC_TWINVQ_DATA_H */
diff --git a/libavcodec/twinvqdec.c b/libavcodec/twinvqdec.c
index 67ce031..3ea4dfa 100644
--- a/libavcodec/twinvqdec.c
+++ b/libavcodec/twinvqdec.c
@@ -256,9 +256,10 @@
     int channels              = tctx->avctx->channels;
     int sub;
     GetBitContext gb;
-    int i, j, k;
+    int i, j, k, ret;
 
-    init_get_bits(&gb, buf, buf_size * 8);
+    if ((ret = init_get_bits8(&gb, buf, buf_size)) < 0)
+        return ret;
     skip_bits(&gb, get_bits(&gb, 8));
 
     bits->window_type = get_bits(&gb, TWINVQ_WINDOW_TYPE_BITS);
diff --git a/libavcodec/utils.c b/libavcodec/utils.c
index 06b6a1f..99f254b 100755
--- a/libavcodec/utils.c
+++ b/libavcodec/utils.c
@@ -246,7 +246,7 @@
     int ret = av_image_check_sar(avctx->width, avctx->height, sar);
 
     if (ret < 0) {
-        av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
+        av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %d/%d\n",
                sar.num, sar.den);
         avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
         return ret;
@@ -374,7 +374,7 @@
     case AV_PIX_FMT_YUVJ411P:
     case AV_PIX_FMT_UYYVYY411:
         w_align = 32;
-        h_align = 8;
+        h_align = 16 * 2;
         break;
     case AV_PIX_FMT_YUV410P:
         if (s->codec_id == AV_CODEC_ID_SVQ1) {
@@ -1318,7 +1318,7 @@
 
     ret = avcodec_open2(avctx, codec, options);
 
-    ff_lock_avcodec(avctx);
+    ff_lock_avcodec(avctx, codec);
     return ret;
 }
 
@@ -1348,7 +1348,7 @@
     if (options)
         av_dict_copy(&tmp, *options, 0);
 
-    ret = ff_lock_avcodec(avctx);
+    ret = ff_lock_avcodec(avctx, codec);
     if (ret < 0)
         return ret;
 
@@ -1477,7 +1477,7 @@
     if (CONFIG_FRAME_THREAD_ENCODER) {
         ff_unlock_avcodec(); //we will instanciate a few encoders thus kick the counter to prevent false detection of a problem
         ret = ff_frame_thread_encoder_init(avctx, options ? *options : NULL);
-        ff_lock_avcodec(avctx);
+        ff_lock_avcodec(avctx, codec);
         if (ret < 0)
             goto free_and_end;
     }
@@ -1704,6 +1704,10 @@
 
     return ret;
 free_and_end:
+    if (avctx->codec &&
+        (avctx->codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP))
+        avctx->codec->close(avctx);
+
     av_dict_free(&tmp);
     if (codec->priv_class && codec->priv_data_size)
         av_opt_free(avctx->priv_data);
@@ -3024,6 +3028,12 @@
 
     if (profile)
         snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", profile);
+    if (   enc->codec_type == AVMEDIA_TYPE_VIDEO
+        && av_log_get_level() >= AV_LOG_VERBOSE
+        && enc->refs)
+        snprintf(buf + strlen(buf), buf_size - strlen(buf),
+                 ", %d reference frame%s",
+                 enc->refs, enc->refs > 1 ? "s" : "");
 
     if (enc->codec_tag) {
         char tag_buf[32];
@@ -3594,15 +3604,19 @@
     return 0;
 }
 
-int ff_lock_avcodec(AVCodecContext *log_ctx)
+int ff_lock_avcodec(AVCodecContext *log_ctx, const AVCodec *codec)
 {
     if (lockmgr_cb) {
         if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
             return -1;
     }
-    entangled_thread_counter++;
-    if (entangled_thread_counter != 1) {
-        av_log(log_ctx, AV_LOG_ERROR, "Insufficient thread locking around avcodec_open/close()\n");
+
+    if (avpriv_atomic_int_add_and_fetch(&entangled_thread_counter, 1) != 1 &&
+        !(codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE)) {
+        av_log(log_ctx, AV_LOG_ERROR,
+               "Insufficient thread locking. At least %d threads are "
+               "calling avcodec_open2() at the same time right now.\n",
+               entangled_thread_counter);
         if (!lockmgr_cb)
             av_log(log_ctx, AV_LOG_ERROR, "No lock manager is set, please see av_lockmgr_register()\n");
         ff_avcodec_locked = 1;
@@ -3618,7 +3632,7 @@
 {
     av_assert0(ff_avcodec_locked);
     ff_avcodec_locked = 0;
-    entangled_thread_counter--;
+    avpriv_atomic_int_add_and_fetch(&entangled_thread_counter, -1);
     if (lockmgr_cb) {
         if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE))
             return -1;
@@ -3663,6 +3677,8 @@
     if (ret < 0)
         return ret;
 
+    av_assert0(!dst->progress);
+
     if (src->progress &&
         !(dst->progress = av_buffer_ref(src->progress))) {
         ff_thread_release_buffer(dst->owner, dst);
diff --git a/libavcodec/utvideoenc.c b/libavcodec/utvideoenc.c
index 355fdb1..99791ba 100644
--- a/libavcodec/utvideoenc.c
+++ b/libavcodec/utvideoenc.c
@@ -48,7 +48,7 @@
     UtvideoContext *c = avctx->priv_data;
     int i;
 
-    av_freep(&avctx->coded_frame);
+    av_frame_free(&avctx->coded_frame);
     av_freep(&c->slice_bits);
     for (i = 0; i < 4; i++)
         av_freep(&c->slice_buffer[i]);
diff --git a/libavcodec/v210dec.c b/libavcodec/v210dec.c
index ae03952..f1e968d 100644
--- a/libavcodec/v210dec.c
+++ b/libavcodec/v210dec.c
@@ -63,7 +63,7 @@
     s->unpack_frame            = v210_planar_unpack_c;
 
     if (HAVE_MMX)
-        v210_x86_init(s);
+        ff_v210_x86_init(s);
 
     return 0;
 }
@@ -101,7 +101,7 @@
     if (aligned_input != s->aligned_input) {
         s->aligned_input = aligned_input;
         if (HAVE_MMX)
-            v210_x86_init(s);
+            ff_v210_x86_init(s);
     }
 
     if ((ret = ff_get_buffer(avctx, pic, 0)) < 0)
diff --git a/libavcodec/v210dec.h b/libavcodec/v210dec.h
index a8db7d6..533afc4 100644
--- a/libavcodec/v210dec.h
+++ b/libavcodec/v210dec.h
@@ -31,6 +31,6 @@
     void (*unpack_frame)(const uint32_t *src, uint16_t *y, uint16_t *u, uint16_t *v, int width);
 } V210DecContext;
 
-void v210_x86_init(V210DecContext *s);
+void ff_v210_x86_init(V210DecContext *s);
 
 #endif /* AVCODEC_V210DEC_H */
diff --git a/libavcodec/v210enc.c b/libavcodec/v210enc.c
index b17bc2c..2e0fd43 100644
--- a/libavcodec/v210enc.c
+++ b/libavcodec/v210enc.c
@@ -215,7 +215,7 @@
 
 static av_cold int encode_close(AVCodecContext *avctx)
 {
-    av_freep(&avctx->coded_frame);
+    av_frame_free(&avctx->coded_frame);
 
     return 0;
 }
diff --git a/libavcodec/v210enc.h b/libavcodec/v210enc.h
index 1186e2f..c49d33f 100644
--- a/libavcodec/v210enc.h
+++ b/libavcodec/v210enc.h
@@ -23,7 +23,7 @@
 #include "libavutil/opt.h"
 #include "libavutil/pixfmt.h"
 
-typedef struct {
+typedef struct V210EncContext {
     void (*pack_line_8)(const uint8_t *y, const uint8_t *u,
                         const uint8_t *v, uint8_t *dst, ptrdiff_t width);
     void (*pack_line_10)(const uint16_t *y, const uint16_t *u,
diff --git a/libavcodec/v308enc.c b/libavcodec/v308enc.c
index c6c5ac5..408784b 100644
--- a/libavcodec/v308enc.c
+++ b/libavcodec/v308enc.c
@@ -77,7 +77,7 @@
 
 static av_cold int v308_encode_close(AVCodecContext *avctx)
 {
-    av_freep(&avctx->coded_frame);
+    av_frame_free(&avctx->coded_frame);
 
     return 0;
 }
diff --git a/libavcodec/v408enc.c b/libavcodec/v408enc.c
index 20f08c7..cdb2efa 100644
--- a/libavcodec/v408enc.c
+++ b/libavcodec/v408enc.c
@@ -82,7 +82,7 @@
 
 static av_cold int v408_encode_close(AVCodecContext *avctx)
 {
-    av_freep(&avctx->coded_frame);
+    av_frame_free(&avctx->coded_frame);
 
     return 0;
 }
diff --git a/libavcodec/v410enc.c b/libavcodec/v410enc.c
index 0e2e82a..f2f7d73 100644
--- a/libavcodec/v410enc.c
+++ b/libavcodec/v410enc.c
@@ -81,7 +81,7 @@
 
 static av_cold int v410_encode_close(AVCodecContext *avctx)
 {
-    av_freep(&avctx->coded_frame);
+    av_frame_free(&avctx->coded_frame);
 
     return 0;
 }
diff --git a/libavcodec/vaapi_h264.c b/libavcodec/vaapi_h264.c
index 8eb8a66..aef0791 100644
--- a/libavcodec/vaapi_h264.c
+++ b/libavcodec/vaapi_h264.c
@@ -156,13 +156,13 @@
  * @param[in]  ref_count   The number of reference pictures in ref_list
  */
 static void fill_vaapi_RefPicList(VAPictureH264 RefPicList[32],
-                                  H264Picture  *ref_list,
+                                  H264Ref  *ref_list,
                                   unsigned int  ref_count)
 {
     unsigned int i, n = 0;
     for (i = 0; i < ref_count; i++)
         if (ref_list[i].reference)
-            fill_vaapi_pic(&RefPicList[n++], &ref_list[i], 0);
+            fill_vaapi_pic(&RefPicList[n++], ref_list[i].parent, 0);
 
     for (; n < 32; n++)
         init_vaapi_pic(&RefPicList[n]);
@@ -192,27 +192,28 @@
                                                short          chroma_weight[32][2],
                                                short          chroma_offset[32][2])
 {
+    H264SliceContext *sl = &h->slice_ctx[0];
     unsigned int i, j;
 
-    *luma_weight_flag    = h->luma_weight_flag[list];
-    *chroma_weight_flag  = h->chroma_weight_flag[list];
+    *luma_weight_flag    = sl->luma_weight_flag[list];
+    *chroma_weight_flag  = sl->chroma_weight_flag[list];
 
-    for (i = 0; i < h->ref_count[list]; i++) {
+    for (i = 0; i < sl->ref_count[list]; i++) {
         /* VA API also wants the inferred (default) values, not
            only what is available in the bitstream (7.4.3.2). */
-        if (h->luma_weight_flag[list]) {
-            luma_weight[i] = h->luma_weight[i][list][0];
-            luma_offset[i] = h->luma_weight[i][list][1];
+        if (sl->luma_weight_flag[list]) {
+            luma_weight[i] = sl->luma_weight[i][list][0];
+            luma_offset[i] = sl->luma_weight[i][list][1];
         } else {
-            luma_weight[i] = 1 << h->luma_log2_weight_denom;
+            luma_weight[i] = 1 << sl->luma_log2_weight_denom;
             luma_offset[i] = 0;
         }
         for (j = 0; j < 2; j++) {
-            if (h->chroma_weight_flag[list]) {
-                chroma_weight[i][j] = h->chroma_weight[i][list][j][0];
-                chroma_offset[i][j] = h->chroma_weight[i][list][j][1];
+            if (sl->chroma_weight_flag[list]) {
+                chroma_weight[i][j] = sl->chroma_weight[i][list][j][0];
+                chroma_offset[i][j] = sl->chroma_weight[i][list][j][1];
             } else {
-                chroma_weight[i][j] = 1 << h->chroma_log2_weight_denom;
+                chroma_weight[i][j] = 1 << sl->chroma_log2_weight_denom;
                 chroma_offset[i][j] = 0;
             }
         }
@@ -292,6 +293,7 @@
 {
     struct vaapi_context * const vactx = avctx->hwaccel_context;
     H264Context * const h = avctx->priv_data;
+    H264SliceContext *sl = &h->slice_ctx[0];
     int ret;
 
     av_dlog(avctx, "vaapi_h264_end_frame()\n");
@@ -303,7 +305,7 @@
     if (ret < 0)
         goto finish;
 
-    ff_h264_draw_horiz_band(h, 0, h->avctx->height);
+    ff_h264_draw_horiz_band(h, sl, 0, h->avctx->height);
 
 finish:
     ff_vaapi_common_end_frame(avctx);
@@ -316,6 +318,7 @@
                                    uint32_t        size)
 {
     H264Context * const h = avctx->priv_data;
+    H264SliceContext *sl  = &h->slice_ctx[0];
     VASliceParameterBufferH264 *slice_param;
 
     av_dlog(avctx, "vaapi_h264_decode_slice(): buffer %p, size %d\n",
@@ -325,22 +328,22 @@
     slice_param = (VASliceParameterBufferH264 *)ff_vaapi_alloc_slice(avctx->hwaccel_context, buffer, size);
     if (!slice_param)
         return -1;
-    slice_param->slice_data_bit_offset          = get_bits_count(&h->gb) + 8; /* bit buffer started beyond nal_unit_type */
-    slice_param->first_mb_in_slice              = (h->mb_y >> FIELD_OR_MBAFF_PICTURE(h)) * h->mb_width + h->mb_x;
-    slice_param->slice_type                     = ff_h264_get_slice_type(h);
-    slice_param->direct_spatial_mv_pred_flag    = h->slice_type == AV_PICTURE_TYPE_B ? h->direct_spatial_mv_pred : 0;
-    slice_param->num_ref_idx_l0_active_minus1   = h->list_count > 0 ? h->ref_count[0] - 1 : 0;
-    slice_param->num_ref_idx_l1_active_minus1   = h->list_count > 1 ? h->ref_count[1] - 1 : 0;
-    slice_param->cabac_init_idc                 = h->cabac_init_idc;
-    slice_param->slice_qp_delta                 = h->qscale - h->pps.init_qp;
-    slice_param->disable_deblocking_filter_idc  = h->deblocking_filter < 2 ? !h->deblocking_filter : h->deblocking_filter;
-    slice_param->slice_alpha_c0_offset_div2     = h->slice_alpha_c0_offset / 2;
-    slice_param->slice_beta_offset_div2         = h->slice_beta_offset     / 2;
-    slice_param->luma_log2_weight_denom         = h->luma_log2_weight_denom;
-    slice_param->chroma_log2_weight_denom       = h->chroma_log2_weight_denom;
+    slice_param->slice_data_bit_offset          = get_bits_count(&sl->gb) + 8; /* bit buffer started beyond nal_unit_type */
+    slice_param->first_mb_in_slice              = (sl->mb_y >> FIELD_OR_MBAFF_PICTURE(h)) * h->mb_width + sl->mb_x;
+    slice_param->slice_type                     = ff_h264_get_slice_type(sl);
+    slice_param->direct_spatial_mv_pred_flag    = sl->slice_type == AV_PICTURE_TYPE_B ? sl->direct_spatial_mv_pred : 0;
+    slice_param->num_ref_idx_l0_active_minus1   = sl->list_count > 0 ? sl->ref_count[0] - 1 : 0;
+    slice_param->num_ref_idx_l1_active_minus1   = sl->list_count > 1 ? sl->ref_count[1] - 1 : 0;
+    slice_param->cabac_init_idc                 = sl->cabac_init_idc;
+    slice_param->slice_qp_delta                 = sl->qscale - h->pps.init_qp;
+    slice_param->disable_deblocking_filter_idc  = sl->deblocking_filter < 2 ? !sl->deblocking_filter : sl->deblocking_filter;
+    slice_param->slice_alpha_c0_offset_div2     = sl->slice_alpha_c0_offset / 2;
+    slice_param->slice_beta_offset_div2         = sl->slice_beta_offset     / 2;
+    slice_param->luma_log2_weight_denom         = sl->luma_log2_weight_denom;
+    slice_param->chroma_log2_weight_denom       = sl->chroma_log2_weight_denom;
 
-    fill_vaapi_RefPicList(slice_param->RefPicList0, h->ref_list[0], h->list_count > 0 ? h->ref_count[0] : 0);
-    fill_vaapi_RefPicList(slice_param->RefPicList1, h->ref_list[1], h->list_count > 1 ? h->ref_count[1] : 0);
+    fill_vaapi_RefPicList(slice_param->RefPicList0, sl->ref_list[0], sl->list_count > 0 ? sl->ref_count[0] : 0);
+    fill_vaapi_RefPicList(slice_param->RefPicList1, sl->ref_list[1], sl->list_count > 1 ? sl->ref_count[1] : 0);
 
     fill_vaapi_plain_pred_weight_table(h, 0,
                                        &slice_param->luma_weight_l0_flag,   slice_param->luma_weight_l0,   slice_param->luma_offset_l0,
diff --git a/libavcodec/vb.c b/libavcodec/vb.c
index 3c89a29..41ee42e 100644
--- a/libavcodec/vb.c
+++ b/libavcodec/vb.c
@@ -251,6 +251,12 @@
     c->frame      = av_mallocz(avctx->width * avctx->height);
     c->prev_frame = av_mallocz(avctx->width * avctx->height);
 
+    if (!c->frame || !c->prev_frame) {
+        av_freep(&c->frame);
+        av_freep(&c->prev_frame);
+        return AVERROR(ENOMEM);
+    }
+
     return 0;
 }
 
diff --git a/libavcodec/vble.c b/libavcodec/vble.c
index 1bf25ba..e7331b1 100644
--- a/libavcodec/vble.c
+++ b/libavcodec/vble.c
@@ -32,7 +32,7 @@
 #include "internal.h"
 #include "mathops.h"
 
-typedef struct {
+typedef struct VBLEContext {
     AVCodecContext *avctx;
     HuffYUVDSPContext hdsp;
 
diff --git a/libavcodec/vc1.c b/libavcodec/vc1.c
index b3955f2..a84522c 100644
--- a/libavcodec/vc1.c
+++ b/libavcodec/vc1.c
@@ -37,9 +37,6 @@
 #include "unary.h"
 #include "simple_idct.h"
 
-#undef NDEBUG
-#include <assert.h>
-
 /***********************************************************************/
 /**
  * @name VC-1 Bitplane decoding
@@ -237,37 +234,34 @@
     int pqdiff;
 
     //variable size
-    if (v->dquant == 2) {
-        pqdiff = get_bits(gb, 3);
-        if (pqdiff == 7)
-            v->altpq = get_bits(gb, 5);
-        else
-            v->altpq = v->pq + pqdiff + 1;
-    } else {
+    if (v->dquant != 2) {
         v->dquantfrm = get_bits1(gb);
-        if (v->dquantfrm) {
-            v->dqprofile = get_bits(gb, 2);
-            switch (v->dqprofile) {
-            case DQPROFILE_SINGLE_EDGE:
-            case DQPROFILE_DOUBLE_EDGES:
-                v->dqsbedge = get_bits(gb, 2);
-                break;
-            case DQPROFILE_ALL_MBS:
-                v->dqbilevel = get_bits1(gb);
-                if (!v->dqbilevel)
-                    v->halfpq = 0;
-            default:
-                break; //Forbidden ?
+        if (!v->dquantfrm)
+            return 0;
+
+        v->dqprofile = get_bits(gb, 2);
+        switch (v->dqprofile) {
+        case DQPROFILE_SINGLE_EDGE:
+        case DQPROFILE_DOUBLE_EDGES:
+            v->dqsbedge = get_bits(gb, 2);
+            break;
+        case DQPROFILE_ALL_MBS:
+            v->dqbilevel = get_bits1(gb);
+            if (!v->dqbilevel) {
+                v->halfpq = 0;
+                return 0;
             }
-            if (v->dqbilevel || v->dqprofile != DQPROFILE_ALL_MBS) {
-                pqdiff = get_bits(gb, 3);
-                if (pqdiff == 7)
-                    v->altpq = get_bits(gb, 5);
-                else
-                    v->altpq = v->pq + pqdiff + 1;
-            }
+        default:
+            break; //Forbidden ?
         }
     }
+
+    pqdiff = get_bits(gb, 3);
+    if (pqdiff == 7)
+        v->altpq = get_bits(gb, 5);
+    else
+        v->altpq = v->pq + pqdiff + 1;
+
     return 0;
 }
 
@@ -338,8 +332,7 @@
         return -1;
     }
     v->extended_mv     = get_bits1(gb); //common
-    if (!v->profile && v->extended_mv)
-    {
+    if (!v->profile && v->extended_mv) {
         av_log(avctx, AV_LOG_ERROR,
                "Extended MVs unavailable in Simple Profile\n");
         return -1;
@@ -348,8 +341,7 @@
     v->vstransform     = get_bits1(gb); //common
 
     v->res_transtab    = get_bits1(gb);
-    if (v->res_transtab)
-    {
+    if (v->res_transtab) {
         av_log(avctx, AV_LOG_ERROR,
                "1 for reserved RES_TRANSTAB is forbidden\n");
         return -1;
@@ -580,13 +572,13 @@
         int scale, shift, i;                                                  \
         if (!lumscale) {                                                      \
             scale = -64;                                                      \
-            shift = (255 - lumshift * 2) << 6;                                \
+            shift = (255 - lumshift * 2) * 64;                                \
             if (lumshift > 31)                                                \
                 shift += 128 << 6;                                            \
         } else {                                                              \
             scale = lumscale + 32;                                            \
             if (lumshift > 31)                                                \
-                shift = (lumshift - 64) << 6;                                 \
+                shift = (lumshift - 64) * 64;                                 \
             else                                                              \
                 shift = lumshift << 6;                                        \
         }                                                                     \
@@ -652,17 +644,14 @@
     v->rangeredfrm = 0;
     if (v->rangered)
         v->rangeredfrm = get_bits1(gb);
-    v->s.pict_type = get_bits1(gb);
-    if (v->s.avctx->max_b_frames) {
-        if (!v->s.pict_type) {
-            if (get_bits1(gb))
-                v->s.pict_type = AV_PICTURE_TYPE_I;
-            else
-                v->s.pict_type = AV_PICTURE_TYPE_B;
+    if (get_bits1(gb)) {
+        v->s.pict_type = AV_PICTURE_TYPE_P;
+    } else {
+        if (v->s.avctx->max_b_frames && !get_bits1(gb)) {
+            v->s.pict_type = AV_PICTURE_TYPE_B;
         } else
-            v->s.pict_type = AV_PICTURE_TYPE_P;
-    } else
-        v->s.pict_type = v->s.pict_type ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_I;
+            v->s.pict_type = AV_PICTURE_TYPE_I;
+    }
 
     v->bi_type = 0;
     if (v->s.pict_type == AV_PICTURE_TYPE_B) {
@@ -692,19 +681,25 @@
         v->pq = ff_vc1_pquant_table[0][pqindex];
     else
         v->pq = ff_vc1_pquant_table[1][pqindex];
-
-    v->pquantizer = 1;
-    if (v->quantizer_mode == QUANT_FRAME_IMPLICIT)
-        v->pquantizer = pqindex < 9;
-    if (v->quantizer_mode == QUANT_NON_UNIFORM)
-        v->pquantizer = 0;
     v->pqindex = pqindex;
     if (pqindex < 9)
         v->halfpq = get_bits1(gb);
     else
         v->halfpq = 0;
-    if (v->quantizer_mode == QUANT_FRAME_EXPLICIT)
+    switch (v->quantizer_mode) {
+    case QUANT_FRAME_IMPLICIT:
+        v->pquantizer = pqindex < 9;
+        break;
+    case QUANT_NON_UNIFORM:
+        v->pquantizer = 0;
+        break;
+    case QUANT_FRAME_EXPLICIT:
         v->pquantizer = get_bits1(gb);
+        break;
+    default:
+        v->pquantizer = 1;
+        break;
+    }
     v->dquantfrm = 0;
     if (v->extended_mv == 1)
         v->mvrange = get_unary(gb, 0, 3);
@@ -728,9 +723,7 @@
 
     switch (v->s.pict_type) {
     case AV_PICTURE_TYPE_P:
-        if (v->pq < 5)       v->tt_index = 0;
-        else if (v->pq < 13) v->tt_index = 1;
-        else                 v->tt_index = 2;
+        v->tt_index = (v->pq > 4) + (v->pq > 12);
 
         lowquant = (v->pq > 12) ? 0 : 1;
         v->mv_mode = ff_vc1_mv_pmode_table[lowquant][get_unary(gb, 1, 4)];
@@ -744,16 +737,15 @@
             INIT_LUT(v->lumscale, v->lumshift, v->last_luty[1], v->last_lutuv[1], 1);
         }
         v->qs_last = v->s.quarter_sample;
-        if (v->mv_mode == MV_PMODE_1MV_HPEL || v->mv_mode == MV_PMODE_1MV_HPEL_BILIN)
-            v->s.quarter_sample = 0;
-        else if (v->mv_mode == MV_PMODE_INTENSITY_COMP) {
-            if (v->mv_mode2 == MV_PMODE_1MV_HPEL || v->mv_mode2 == MV_PMODE_1MV_HPEL_BILIN)
-                v->s.quarter_sample = 0;
-            else
-                v->s.quarter_sample = 1;
-        } else
-            v->s.quarter_sample = 1;
-        v->s.mspel = !(v->mv_mode == MV_PMODE_1MV_HPEL_BILIN || (v->mv_mode == MV_PMODE_INTENSITY_COMP && v->mv_mode2 == MV_PMODE_1MV_HPEL_BILIN));
+        if (v->mv_mode == MV_PMODE_INTENSITY_COMP) {
+            v->s.quarter_sample = (v->mv_mode2 != MV_PMODE_1MV_HPEL &&
+                                   v->mv_mode2 != MV_PMODE_1MV_HPEL_BILIN);
+            v->s.mspel          = (v->mv_mode2 != MV_PMODE_1MV_HPEL_BILIN);
+        } else {
+            v->s.quarter_sample = (v->mv_mode != MV_PMODE_1MV_HPEL &&
+                                   v->mv_mode != MV_PMODE_1MV_HPEL_BILIN);
+            v->s.mspel          = (v->mv_mode != MV_PMODE_1MV_HPEL_BILIN);
+        }
 
         if ((v->mv_mode  == MV_PMODE_INTENSITY_COMP &&
              v->mv_mode2 == MV_PMODE_MIXED_MV)      ||
@@ -782,21 +774,19 @@
             vop_dquant_decoding(v);
         }
 
-        v->ttfrm = 0; //FIXME Is that so ?
         if (v->vstransform) {
             v->ttmbf = get_bits1(gb);
             if (v->ttmbf) {
                 v->ttfrm = ff_vc1_ttfrm_to_tt[get_bits(gb, 2)];
-            }
+            } else
+                v->ttfrm = 0; //FIXME Is that so ?
         } else {
             v->ttmbf = 1;
             v->ttfrm = TT_8X8;
         }
         break;
     case AV_PICTURE_TYPE_B:
-        if (v->pq < 5)       v->tt_index = 0;
-        else if (v->pq < 13) v->tt_index = 1;
-        else                 v->tt_index = 2;
+        v->tt_index = (v->pq > 4) + (v->pq > 12);
 
         v->mv_mode          = get_bits1(gb) ? MV_PMODE_1MV : MV_PMODE_1MV_HPEL_BILIN;
         v->qs_last          = v->s.quarter_sample;
@@ -822,12 +812,12 @@
             vop_dquant_decoding(v);
         }
 
-        v->ttfrm = 0;
         if (v->vstransform) {
             v->ttmbf = get_bits1(gb);
             if (v->ttmbf) {
                 v->ttfrm = ff_vc1_ttfrm_to_tt[get_bits(gb, 2)];
-            }
+            } else
+                v->ttfrm = 0;
         } else {
             v->ttmbf = 1;
             v->ttfrm = TT_8X8;
@@ -862,11 +852,12 @@
     v->numref          = 0;
     v->p_frame_skipped = 0;
     if (v->second_field) {
-        if(v->fcm!=2 || v->field_mode!=1)
+        if (v->fcm != ILACE_FIELD || v->field_mode!=1)
             return -1;
-        v->s.pict_type = (v->fptype & 1) ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_I;
         if (v->fptype & 4)
             v->s.pict_type = (v->fptype & 1) ? AV_PICTURE_TYPE_BI : AV_PICTURE_TYPE_B;
+        else
+            v->s.pict_type = (v->fptype & 1) ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_I;
         v->s.current_picture_ptr->f->pict_type = v->s.pict_type;
         if (!v->pic_header_flag)
             goto parse_common_info;
@@ -892,10 +883,10 @@
     if (v->field_mode) {
         v->s.mb_height = FFALIGN(v->s.height + 15 >> 4, 2);
         v->fptype = get_bits(gb, 3);
-        v->s.pict_type = (v->fptype & 2) ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_I;
         if (v->fptype & 4) // B-picture
             v->s.pict_type = (v->fptype & 2) ? AV_PICTURE_TYPE_BI : AV_PICTURE_TYPE_B;
-
+        else
+            v->s.pict_type = (v->fptype & 2) ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_I;
     } else {
         v->s.mb_height = v->s.height + 15 >> 4;
         switch (get_unary(gb, 0, 4)) {
@@ -977,24 +968,29 @@
     pqindex = get_bits(gb, 5);
     if (!pqindex)
         return -1;
-    v->pqindex = pqindex;
     if (v->quantizer_mode == QUANT_FRAME_IMPLICIT)
         v->pq = ff_vc1_pquant_table[0][pqindex];
     else
         v->pq = ff_vc1_pquant_table[1][pqindex];
-
-    v->pquantizer = 1;
-    if (v->quantizer_mode == QUANT_FRAME_IMPLICIT)
-        v->pquantizer = pqindex < 9;
-    if (v->quantizer_mode == QUANT_NON_UNIFORM)
-        v->pquantizer = 0;
     v->pqindex = pqindex;
     if (pqindex < 9)
         v->halfpq = get_bits1(gb);
     else
         v->halfpq = 0;
-    if (v->quantizer_mode == QUANT_FRAME_EXPLICIT)
+    switch (v->quantizer_mode) {
+    case QUANT_FRAME_IMPLICIT:
+        v->pquantizer = pqindex < 9;
+        break;
+    case QUANT_NON_UNIFORM:
+        v->pquantizer = 0;
+        break;
+    case QUANT_FRAME_EXPLICIT:
         v->pquantizer = get_bits1(gb);
+        break;
+    default:
+        v->pquantizer = 1;
+        break;
+    }
     if (v->postprocflag)
         v->postproc = get_bits(gb, 2);
 
@@ -1084,12 +1080,7 @@
         v->range_x = 1 << (v->k_x - 1);
         v->range_y = 1 << (v->k_y - 1);
 
-        if (v->pq < 5)
-            v->tt_index = 0;
-        else if (v->pq < 13)
-            v->tt_index = 1;
-        else
-            v->tt_index = 2;
+        v->tt_index = (v->pq > 4) + (v->pq > 12);
         if (v->fcm != ILACE_FRAME) {
             int mvmode;
             mvmode     = get_unary(gb, 1, 4);
@@ -1133,18 +1124,15 @@
                 v->last_use_ic = 1;
             }
             v->qs_last = v->s.quarter_sample;
-            if (v->mv_mode == MV_PMODE_1MV_HPEL || v->mv_mode == MV_PMODE_1MV_HPEL_BILIN)
-                v->s.quarter_sample = 0;
-            else if (v->mv_mode == MV_PMODE_INTENSITY_COMP) {
-                if (v->mv_mode2 == MV_PMODE_1MV_HPEL || v->mv_mode2 == MV_PMODE_1MV_HPEL_BILIN)
-                    v->s.quarter_sample = 0;
-                else
-                    v->s.quarter_sample = 1;
-            } else
-                v->s.quarter_sample = 1;
-            v->s.mspel = !(v->mv_mode == MV_PMODE_1MV_HPEL_BILIN
-                           || (v->mv_mode == MV_PMODE_INTENSITY_COMP
-                               && v->mv_mode2 == MV_PMODE_1MV_HPEL_BILIN));
+            if (v->mv_mode == MV_PMODE_INTENSITY_COMP) {
+                v->s.quarter_sample = (v->mv_mode2 != MV_PMODE_1MV_HPEL &&
+                                       v->mv_mode2 != MV_PMODE_1MV_HPEL_BILIN);
+                v->s.mspel          = (v->mv_mode2 != MV_PMODE_1MV_HPEL_BILIN);
+            } else {
+                v->s.quarter_sample = (v->mv_mode != MV_PMODE_1MV_HPEL &&
+                                       v->mv_mode != MV_PMODE_1MV_HPEL_BILIN);
+                v->s.mspel          = (v->mv_mode != MV_PMODE_1MV_HPEL_BILIN);
+            }
         }
         if (v->fcm == PROGRESSIVE) { // progressive
             if ((v->mv_mode == MV_PMODE_INTENSITY_COMP &&
@@ -1195,12 +1183,12 @@
             vop_dquant_decoding(v);
         }
 
-        v->ttfrm = 0; //FIXME Is that so ?
         if (v->vstransform) {
             v->ttmbf = get_bits1(gb);
             if (v->ttmbf) {
                 v->ttfrm = ff_vc1_ttfrm_to_tt[get_bits(gb, 2)];
-            }
+            } else
+                v->ttfrm = 0; //FIXME Is that so ?
         } else {
             v->ttmbf = 1;
             v->ttfrm = TT_8X8;
@@ -1223,12 +1211,7 @@
         v->range_x = 1 << (v->k_x - 1);
         v->range_y = 1 << (v->k_y - 1);
 
-        if (v->pq < 5)
-            v->tt_index = 0;
-        else if (v->pq < 13)
-            v->tt_index = 1;
-        else
-            v->tt_index = 2;
+        v->tt_index = (v->pq > 4) + (v->pq > 12);
 
         if (v->field_mode) {
             int mvmode;
@@ -1316,12 +1299,12 @@
             vop_dquant_decoding(v);
         }
 
-        v->ttfrm = 0;
         if (v->vstransform) {
             v->ttmbf = get_bits1(gb);
             if (v->ttmbf) {
                 v->ttfrm = ff_vc1_ttfrm_to_tt[get_bits(gb, 2)];
-            }
+            } else
+                v->ttfrm = 0;
         } else {
             v->ttmbf = 1;
             v->ttfrm = TT_8X8;
@@ -1347,11 +1330,10 @@
         vop_dquant_decoding(v);
     }
 
-    v->bi_type = 0;
-    if (v->s.pict_type == AV_PICTURE_TYPE_BI) {
+    v->bi_type = (v->s.pict_type == AV_PICTURE_TYPE_BI);
+    if (v->bi_type)
         v->s.pict_type = AV_PICTURE_TYPE_B;
-        v->bi_type = 1;
-    }
+
     return 0;
 }
 
diff --git a/libavcodec/vc1_block.c b/libavcodec/vc1_block.c
index aa62ec2..f5daa67 100644
--- a/libavcodec/vc1_block.c
+++ b/libavcodec/vc1_block.c
@@ -40,8 +40,10 @@
 #define DC_VLC_BITS 9
 
 // offset tables for interlaced picture MVDATA decoding
-static const int offset_table1[9] = {  0,  1,  2,  4,  8, 16, 32,  64, 128 };
-static const int offset_table2[9] = {  0,  1,  3,  7, 15, 31, 63, 127, 255 };
+static const uint8_t offset_table[2][9] = {
+    {  0,  1,  2,  4,  8, 16, 32,  64, 128 },
+    {  0,  1,  3,  7, 15, 31, 63, 127, 255 },
+};
 
 /***********************************************************************/
 /**
@@ -51,7 +53,7 @@
  */
 
 
-static void init_block_index(VC1Context *v)
+static inline void init_block_index(VC1Context *v)
 {
     MpegEncContext *s = &v->s;
     ff_init_block_index(s);
@@ -216,33 +218,32 @@
         s->mb_intra = 1;                                                \
     } else {                                                            \
         index1 = index % 6;                                             \
-        if (!s->quarter_sample && index1 == 5) val = 1;                 \
-        else                                   val = 0;                 \
-        if (size_table[index1] - val > 0)                               \
-            val = get_bits(gb, size_table[index1] - val);               \
-        else                                   val = 0;                 \
-        sign = 0 - (val&1);                                             \
-        _dmv_x = (sign ^ ((val>>1) + offset_table[index1])) - sign;     \
+        _dmv_x = offset_table[1][index1];                               \
+        val = size_table[index1] - (!s->quarter_sample && index1 == 5); \
+        if (val > 0) {                                                  \
+            val = get_bits(gb, val);                                    \
+            sign = 0 - (val & 1);                                       \
+            _dmv_x = (sign ^ ((val >> 1) + _dmv_x)) - sign;             \
+        }                                                               \
                                                                         \
         index1 = index / 6;                                             \
-        if (!s->quarter_sample && index1 == 5) val = 1;                 \
-        else                                   val = 0;                 \
-        if (size_table[index1] - val > 0)                               \
-            val = get_bits(gb, size_table[index1] - val);               \
-        else                                   val = 0;                 \
-        sign = 0 - (val & 1);                                           \
-        _dmv_y = (sign ^ ((val >> 1) + offset_table[index1])) - sign;   \
+        _dmv_y = offset_table[1][index1];                               \
+        val = size_table[index1] - (!s->quarter_sample && index1 == 5); \
+        if (val > 0) {                                                  \
+            val = get_bits(gb, val);                                    \
+            sign = 0 - (val & 1);                                       \
+            _dmv_y = (sign ^ ((val >> 1) + _dmv_y)) - sign;             \
+        }                                                               \
     }
 
 static av_always_inline void get_mvdata_interlaced(VC1Context *v, int *dmv_x,
                                                    int *dmv_y, int *pred_flag)
 {
     int index, index1;
-    int extend_x = 0, extend_y = 0;
+    int extend_x, extend_y;
     GetBitContext *gb = &v->s.gb;
     int bits, esc;
     int val, sign;
-    const int* offs_tab;
 
     if (v->numref) {
         bits = VC1_2REF_MVDATA_VLC_BITS;
@@ -251,52 +252,32 @@
         bits = VC1_1REF_MVDATA_VLC_BITS;
         esc  = 71;
     }
-    switch (v->dmvrange) {
-    case 1:
-        extend_x = 1;
-        break;
-    case 2:
-        extend_y = 1;
-        break;
-    case 3:
-        extend_x = extend_y = 1;
-        break;
-    }
+    extend_x = v->dmvrange & 1;
+    extend_y = (v->dmvrange >> 1) & 1;
     index = get_vlc2(gb, v->imv_vlc->table, bits, 3);
     if (index == esc) {
         *dmv_x = get_bits(gb, v->k_x);
         *dmv_y = get_bits(gb, v->k_y);
         if (v->numref) {
-            if (pred_flag) {
+            if (pred_flag)
                 *pred_flag = *dmv_y & 1;
-                *dmv_y     = (*dmv_y + *pred_flag) >> 1;
-            } else {
-                *dmv_y     = (*dmv_y + (*dmv_y & 1)) >> 1;
-            }
+            *dmv_y = (*dmv_y + (*dmv_y & 1)) >> 1;
         }
     }
     else {
         av_assert0(index < esc);
-        if (extend_x)
-            offs_tab = offset_table2;
-        else
-            offs_tab = offset_table1;
         index1 = (index + 1) % 9;
         if (index1 != 0) {
             val    = get_bits(gb, index1 + extend_x);
-            sign   = 0 -(val & 1);
-            *dmv_x = (sign ^ ((val >> 1) + offs_tab[index1])) - sign;
+            sign   = 0 - (val & 1);
+            *dmv_x = (sign ^ ((val >> 1) + offset_table[extend_x][index1])) - sign;
         } else
             *dmv_x = 0;
-        if (extend_y)
-            offs_tab = offset_table2;
-        else
-            offs_tab = offset_table1;
         index1 = (index + 1) / 9;
         if (index1 > v->numref) {
-            val    = get_bits(gb, (index1 + (extend_y << v->numref)) >> v->numref);
+            val    = get_bits(gb, (index1 >> v->numref) + extend_y);
             sign   = 0 - (val & 1);
-            *dmv_y = (sign ^ ((val >> 1) + offs_tab[index1 >> v->numref])) - sign;
+            *dmv_y = (sign ^ ((val >> 1) + offset_table[extend_y][index1 >> v->numref])) - sign;
         } else
             *dmv_y = 0;
         if (v->numref && pred_flag)
@@ -407,6 +388,12 @@
     int q1, q2 = 0;
     int dqscale_index;
 
+    /* scale predictors if needed */
+    q1 = s->current_picture.qscale_table[mb_pos];
+    dqscale_index = s->y_dc_scale_table[q1] - 1;
+    if (dqscale_index < 0)
+        return 0;
+
     wrap = s->block_wrap[n];
     dc_val = s->dc_val[0] + s->block_index[n];
 
@@ -416,11 +403,7 @@
     c = dc_val[ - 1];
     b = dc_val[ - 1 - wrap];
     a = dc_val[ - wrap];
-    /* scale predictors if needed */
-    q1 = s->current_picture.qscale_table[mb_pos];
-    dqscale_index = s->y_dc_scale_table[q1] - 1;
-    if (dqscale_index < 0)
-        return 0;
+
     if (c_avail && (n != 1 && n != 3)) {
         q2 = s->current_picture.qscale_table[mb_pos - 1];
         if (q2 && q2 != q1)
@@ -442,20 +425,12 @@
             b = (b * s->y_dc_scale_table[q2] * ff_vc1_dqscale[dqscale_index] + 0x20000) >> 18;
     }
 
-    if (a_avail && c_avail) {
-        if (abs(a - b) <= abs(b - c)) {
-            pred     = c;
-            *dir_ptr = 1; // left
-        } else {
-            pred     = a;
-            *dir_ptr = 0; // top
-        }
+    if (c_avail && (!a_avail || abs(a - b) <= abs(b - c))) {
+        pred     = c;
+        *dir_ptr = 1; // left
     } else if (a_avail) {
         pred     = a;
         *dir_ptr = 0; // top
-    } else if (c_avail) {
-        pred     = c;
-        *dir_ptr = 1; // left
     } else {
         pred     = 0;
         *dir_ptr = 1; // left
@@ -514,17 +489,16 @@
                                 int *value, int codingset)
 {
     GetBitContext *gb = &v->s.gb;
-    int index, escape, run = 0, level = 0, lst = 0;
+    int index, run, level, lst, sign;
 
     index = get_vlc2(gb, ff_vc1_ac_coeff_table[codingset].table, AC_VLC_BITS, 3);
     if (index != ff_vc1_ac_sizes[codingset] - 1) {
         run   = vc1_index_decode_table[codingset][index][0];
         level = vc1_index_decode_table[codingset][index][1];
         lst   = index >= vc1_last_decode_table[codingset] || get_bits_left(gb) < 0;
-        if (get_bits1(gb))
-            level = -level;
+        sign  = get_bits1(gb);
     } else {
-        escape = decode210(gb);
+        int escape = decode210(gb);
         if (escape != 2) {
             index = get_vlc2(gb, ff_vc1_ac_coeff_table[codingset].table, AC_VLC_BITS, 3);
             run   = vc1_index_decode_table[codingset][index][0];
@@ -541,10 +515,8 @@
                 else
                     run += vc1_delta_run_table[codingset][level] + 1;
             }
-            if (get_bits1(gb))
-                level = -level;
+            sign = get_bits1(gb);
         } else {
-            int sign;
             lst = get_bits1(gb);
             if (v->s.esc3_level_length == 0) {
                 if (v->pq < 8 || v->dquantfrm) { // table 59
@@ -559,14 +531,12 @@
             run   = get_bits(gb, v->s.esc3_run_length);
             sign  = get_bits1(gb);
             level = get_bits(gb, v->s.esc3_level_length);
-            if (sign)
-                level = -level;
         }
     }
 
     *last  = lst;
     *skip  = run;
-    *value = level;
+    *value = (level ^ -sign) + sign;
 }
 
 /** Decode intra block in intra frames - should be faster than decode_intra_block
@@ -585,7 +555,7 @@
     int i;
     int16_t *dc_val;
     int16_t *ac_val, *ac_val2;
-    int dcdiff;
+    int dcdiff, scale;
 
     /* Get DC differential */
     if (n < 4) {
@@ -598,16 +568,12 @@
         return -1;
     }
     if (dcdiff) {
+        const int m = (v->pq == 1 || v->pq == 2) ? 3 - v->pq : 0;
         if (dcdiff == 119 /* ESC index value */) {
-            /* TODO: Optimize */
-            if (v->pq == 1)      dcdiff = get_bits(gb, 10);
-            else if (v->pq == 2) dcdiff = get_bits(gb, 9);
-            else                 dcdiff = get_bits(gb, 8);
+            dcdiff = get_bits(gb, 8 + m);
         } else {
-            if (v->pq == 1)
-                dcdiff = (dcdiff << 2) + get_bits(gb, 2) - 3;
-            else if (v->pq == 2)
-                dcdiff = (dcdiff << 1) + get_bits1(gb)   - 1;
+            if (m)
+                dcdiff = (dcdiff << m) + get_bits(gb, m) - ((1 << m) - 1);
         }
         if (get_bits1(gb))
             dcdiff = -dcdiff;
@@ -618,27 +584,29 @@
     *dc_val = dcdiff;
 
     /* Store the quantized DC coeff, used for prediction */
-    if (n < 4) {
-        block[0] = dcdiff * s->y_dc_scale;
-    } else {
-        block[0] = dcdiff * s->c_dc_scale;
-    }
-    /* Skip ? */
-    if (!coded) {
-        goto not_coded;
-    }
+    if (n < 4)
+        scale = s->y_dc_scale;
+    else
+        scale = s->c_dc_scale;
+    block[0] = dcdiff * scale;
 
-    // AC Decoding
-    i = 1;
+    ac_val  = s->ac_val[0][0] + s->block_index[n] * 16;
+    ac_val2 = ac_val;
+    if (dc_pred_dir) // left
+        ac_val -= 16;
+    else // top
+        ac_val -= 16 * s->block_wrap[n];
 
-    {
+    scale = v->pq * 2 + v->halfpq;
+
+    //AC Decoding
+    i = !!coded;
+
+    if (coded) {
         int last = 0, skip, value;
         const uint8_t *zz_table;
-        int scale;
         int k;
 
-        scale = v->pq * 2 + v->halfpq;
-
         if (v->s.ac_pred) {
             if (!dc_pred_dir)
                 zz_table = v->zz_8x8[2];
@@ -647,13 +615,6 @@
         } else
             zz_table = v->zz_8x8[1];
 
-        ac_val  = s->ac_val[0][0] + s->block_index[n] * 16;
-        ac_val2 = ac_val;
-        if (dc_pred_dir) // left
-            ac_val -= 16;
-        else // top
-            ac_val -= 16 * s->block_wrap[n];
-
         while (!last) {
             vc1_decode_ac_coeff(v, &last, &skip, &value, codingset);
             i += skip;
@@ -664,13 +625,15 @@
 
         /* apply AC prediction if needed */
         if (s->ac_pred) {
+            int sh;
             if (dc_pred_dir) { // left
-                for (k = 1; k < 8; k++)
-                    block[k << v->left_blk_sh] += ac_val[k];
+                sh = v->left_blk_sh;
             } else { // top
-                for (k = 1; k < 8; k++)
-                    block[k << v->top_blk_sh] += ac_val[k + 8];
+                sh = v->top_blk_sh;
+                ac_val += 8;
             }
+            for (k = 1; k < 8; k++)
+                block[k << sh] += ac_val[k];
         }
         /* save AC coeffs for further prediction */
         for (k = 1; k < 8; k++) {
@@ -686,46 +649,30 @@
                     block[k] += (block[k] < 0) ? -v->pq : v->pq;
             }
 
-        if (s->ac_pred) i = 63;
-    }
+    } else {
+        int k;
 
-not_coded:
-    if (!coded) {
-        int k, scale;
-        ac_val  = s->ac_val[0][0] + s->block_index[n] * 16;
-        ac_val2 = ac_val;
-
-        i = 0;
-        scale = v->pq * 2 + v->halfpq;
         memset(ac_val2, 0, 16 * 2);
-        if (dc_pred_dir) { // left
-            ac_val -= 16;
-            if (s->ac_pred)
-                memcpy(ac_val2, ac_val, 8 * 2);
-        } else { // top
-            ac_val -= 16 * s->block_wrap[n];
-            if (s->ac_pred)
-                memcpy(ac_val2 + 8, ac_val + 8, 8 * 2);
-        }
 
         /* apply AC prediction if needed */
         if (s->ac_pred) {
+            int sh;
             if (dc_pred_dir) { //left
-                for (k = 1; k < 8; k++) {
-                    block[k << v->left_blk_sh] = ac_val[k] * scale;
-                    if (!v->pquantizer && block[k << v->left_blk_sh])
-                        block[k << v->left_blk_sh] += (block[k << v->left_blk_sh] < 0) ? -v->pq : v->pq;
-                }
+                sh = v->left_blk_sh;
             } else { // top
-                for (k = 1; k < 8; k++) {
-                    block[k << v->top_blk_sh] = ac_val[k + 8] * scale;
-                    if (!v->pquantizer && block[k << v->top_blk_sh])
-                        block[k << v->top_blk_sh] += (block[k << v->top_blk_sh] < 0) ? -v->pq : v->pq;
-                }
+                sh = v->top_blk_sh;
+                ac_val  += 8;
+                ac_val2 += 8;
             }
-            i = 63;
+            memcpy(ac_val2, ac_val, 8 * 2);
+            for (k = 1; k < 8; k++) {
+                block[k << sh] = ac_val[k] * scale;
+                if (!v->pquantizer && block[k << sh])
+                    block[k << sh] += (block[k << sh] < 0) ? -v->pq : v->pq;
+            }
         }
     }
+    if (s->ac_pred) i = 63;
     s->block_last_index[n] = i;
 
     return 0;
@@ -766,16 +713,12 @@
         return -1;
     }
     if (dcdiff) {
+        const int m = (mquant == 1 || mquant == 2) ? 3 - mquant : 0;
         if (dcdiff == 119 /* ESC index value */) {
-            /* TODO: Optimize */
-            if (mquant == 1)      dcdiff = get_bits(gb, 10);
-            else if (mquant == 2) dcdiff = get_bits(gb, 9);
-            else                  dcdiff = get_bits(gb, 8);
+            dcdiff = get_bits(gb, 8 + m);
         } else {
-            if (mquant == 1)
-                dcdiff = (dcdiff << 2) + get_bits(gb, 2) - 3;
-            else if (mquant == 2)
-                dcdiff = (dcdiff << 1) + get_bits1(gb)   - 1;
+            if (m)
+                dcdiff = (dcdiff << m) + get_bits(gb, m) - ((1 << m) - 1);
         }
         if (get_bits1(gb))
             dcdiff = -dcdiff;
@@ -786,39 +729,42 @@
     *dc_val = dcdiff;
 
     /* Store the quantized DC coeff, used for prediction */
-    if (n < 4) {
-        block[0] = dcdiff * s->y_dc_scale;
-    } else {
-        block[0] = dcdiff * s->c_dc_scale;
-    }
-
-    //AC Decoding
-    i = 1;
+    if (n < 4)
+        scale = s->y_dc_scale;
+    else
+        scale = s->c_dc_scale;
+    block[0] = dcdiff * scale;
 
     /* check if AC is needed at all */
     if (!a_avail && !c_avail)
         use_pred = 0;
-    ac_val  = s->ac_val[0][0] + s->block_index[n] * 16;
-    ac_val2 = ac_val;
 
     scale = mquant * 2 + ((mquant == v->pq) ? v->halfpq : 0);
 
+    ac_val  = s->ac_val[0][0] + s->block_index[n] * 16;
+    ac_val2 = ac_val;
     if (dc_pred_dir) // left
         ac_val -= 16;
     else // top
         ac_val -= 16 * s->block_wrap[n];
 
     q1 = s->current_picture.qscale_table[mb_pos];
-    if ( dc_pred_dir && c_avail && mb_pos)
-        q2 = s->current_picture.qscale_table[mb_pos - 1];
-    if (!dc_pred_dir && a_avail && mb_pos >= s->mb_stride)
-        q2 = s->current_picture.qscale_table[mb_pos - s->mb_stride];
-    if ( dc_pred_dir && n == 1)
-        q2 = q1;
-    if (!dc_pred_dir && n == 2)
-        q2 = q1;
     if (n == 3)
         q2 = q1;
+    else if (dc_pred_dir) {
+        if (n == 1)
+            q2 = q1;
+        else if (c_avail && mb_pos)
+            q2 = s->current_picture.qscale_table[mb_pos - 1];
+    } else {
+        if (n == 2)
+            q2 = q1;
+        else if (a_avail && mb_pos >= s->mb_stride)
+            q2 = s->current_picture.qscale_table[mb_pos - s->mb_stride];
+    }
+
+    //AC Decoding
+    i = 1;
 
     if (coded) {
         int last = 0, skip, value;
@@ -851,28 +797,24 @@
 
         /* apply AC prediction if needed */
         if (use_pred) {
+            int sh;
+            if (dc_pred_dir) { // left
+                sh = v->left_blk_sh;
+            } else { // top
+                sh = v->top_blk_sh;
+                ac_val += 8;
+            }
             /* scale predictors if needed*/
             if (q2 && q1 != q2) {
                 q1 = q1 * 2 + ((q1 == v->pq) ? v->halfpq : 0) - 1;
-                q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;
-
                 if (q1 < 1)
                     return AVERROR_INVALIDDATA;
-                if (dc_pred_dir) { // left
-                    for (k = 1; k < 8; k++)
-                        block[k << v->left_blk_sh] += (ac_val[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
-                } else { // top
-                    for (k = 1; k < 8; k++)
-                        block[k << v->top_blk_sh] += (ac_val[k + 8] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
-                }
+                q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;
+                for (k = 1; k < 8; k++)
+                    block[k << sh] += (ac_val[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
             } else {
-                if (dc_pred_dir) { //left
-                    for (k = 1; k < 8; k++)
-                        block[k << v->left_blk_sh] += ac_val[k];
-                } else { //top
-                    for (k = 1; k < 8; k++)
-                        block[k << v->top_blk_sh] += ac_val[k + 8];
-                }
+                for (k = 1; k < 8; k++)
+                    block[k << sh] += ac_val[k];
             }
         }
         /* save AC coeffs for further prediction */
@@ -889,55 +831,38 @@
                     block[k] += (block[k] < 0) ? -mquant : mquant;
             }
 
-        if (use_pred) i = 63;
     } else { // no AC coeffs
         int k;
 
         memset(ac_val2, 0, 16 * 2);
-        if (dc_pred_dir) { // left
-            if (use_pred) {
-                memcpy(ac_val2, ac_val, 8 * 2);
-                if (q2 && q1 != q2) {
-                    q1 = q1 * 2 + ((q1 == v->pq) ? v->halfpq : 0) - 1;
-                    q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;
-                    if (q1 < 1)
-                        return AVERROR_INVALIDDATA;
-                    for (k = 1; k < 8; k++)
-                        ac_val2[k] = (ac_val2[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
-                }
-            }
-        } else { // top
-            if (use_pred) {
-                memcpy(ac_val2 + 8, ac_val + 8, 8 * 2);
-                if (q2 && q1 != q2) {
-                    q1 = q1 * 2 + ((q1 == v->pq) ? v->halfpq : 0) - 1;
-                    q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;
-                    if (q1 < 1)
-                        return AVERROR_INVALIDDATA;
-                    for (k = 1; k < 8; k++)
-                        ac_val2[k + 8] = (ac_val2[k + 8] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
-                }
-            }
-        }
 
         /* apply AC prediction if needed */
         if (use_pred) {
+            int sh;
             if (dc_pred_dir) { // left
-                for (k = 1; k < 8; k++) {
-                    block[k << v->left_blk_sh] = ac_val2[k] * scale;
-                    if (!v->pquantizer && block[k << v->left_blk_sh])
-                        block[k << v->left_blk_sh] += (block[k << v->left_blk_sh] < 0) ? -mquant : mquant;
-                }
+                sh = v->left_blk_sh;
             } else { // top
-                for (k = 1; k < 8; k++) {
-                    block[k << v->top_blk_sh] = ac_val2[k + 8] * scale;
-                    if (!v->pquantizer && block[k << v->top_blk_sh])
-                        block[k << v->top_blk_sh] += (block[k << v->top_blk_sh] < 0) ? -mquant : mquant;
-                }
+                sh = v->top_blk_sh;
+                ac_val  += 8;
+                ac_val2 += 8;
             }
-            i = 63;
+            memcpy(ac_val2, ac_val, 8 * 2);
+            if (q2 && q1 != q2) {
+                q1 = q1 * 2 + ((q1 == v->pq) ? v->halfpq : 0) - 1;
+                q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;
+                if (q1 < 1)
+                    return AVERROR_INVALIDDATA;
+                for (k = 1; k < 8; k++)
+                    ac_val2[k] = (ac_val2[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
+            }
+            for (k = 1; k < 8; k++) {
+                block[k << sh] = ac_val2[k] * scale;
+                if (!v->pquantizer && block[k << sh])
+                    block[k << sh] += (block[k << sh] < 0) ? -mquant : mquant;
+            }
         }
     }
+    if (use_pred) i = 63;
     s->block_last_index[n] = i;
 
     return 0;
@@ -970,7 +895,7 @@
     s->bdsp.clear_block(block);
 
     /* XXX: Guard against dumb values of mquant */
-    mquant = (mquant < 1) ? 0 : ((mquant > 31) ? 31 : mquant);
+    mquant = av_clip_uintp2(mquant, 5);
 
     /* Set DC scale - y and c use the same */
     s->y_dc_scale = s->y_dc_scale_table[mquant];
@@ -987,16 +912,12 @@
         return -1;
     }
     if (dcdiff) {
+        const int m = (mquant == 1 || mquant == 2) ? 3 - mquant : 0;
         if (dcdiff == 119 /* ESC index value */) {
-            /* TODO: Optimize */
-            if (mquant == 1)      dcdiff = get_bits(gb, 10);
-            else if (mquant == 2) dcdiff = get_bits(gb, 9);
-            else                  dcdiff = get_bits(gb, 8);
+            dcdiff = get_bits(gb, 8 + m);
         } else {
-            if (mquant == 1)
-                dcdiff = (dcdiff << 2) + get_bits(gb, 2) - 3;
-            else if (mquant == 2)
-                dcdiff = (dcdiff << 1) + get_bits1(gb)   - 1;
+            if (m)
+                dcdiff = (dcdiff << m) + get_bits(gb, m) - ((1 << m) - 1);
         }
         if (get_bits1(gb))
             dcdiff = -dcdiff;
@@ -1320,8 +1241,7 @@
 
 /** @} */ // Macroblock group
 
-static const int size_table  [6] = { 0, 2, 3, 4,  5,  8 };
-static const int offset_table[6] = { 0, 1, 3, 7, 15, 31 };
+static const uint8_t size_table[6] = { 0, 2, 3, 4,  5,  8 };
 
 /** Decode one P-frame MB
  */
@@ -1697,19 +1617,14 @@
             dst_idx = 0;
             if (fourmv) {
                 mvbp = v->fourmvbp;
-                for (i = 0; i < 6; i++) {
-                    if (i < 4) {
-                        dmv_x = dmv_y = 0;
-                        val   = ((mvbp >> (3 - i)) & 1);
-                        if (val) {
-                            get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);
-                        }
-                        ff_vc1_pred_mv_intfr(v, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0], 0);
-                        ff_vc1_mc_4mv_luma(v, i, 0, 0);
-                    } else if (i == 4) {
-                        ff_vc1_mc_4mv_chroma4(v, 0, 0, 0);
-                    }
+                for (i = 0; i < 4; i++) {
+                    dmv_x = dmv_y = 0;
+                    if (mvbp & (8 >> i))
+                        get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);
+                    ff_vc1_pred_mv_intfr(v, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0], 0);
+                    ff_vc1_mc_4mv_luma(v, i, 0, 0);
                 }
+                ff_vc1_mc_4mv_chroma4(v, 0, 0, 0);
             } else if (twomv) {
                 mvbp  = v->twomvbp;
                 dmv_x = dmv_y = 0;
@@ -1845,7 +1760,8 @@
     } else {
         s->mb_intra = v->is_intra[s->mb_x] = 0;
         s->current_picture.mb_type[mb_pos + v->mb_off] = MB_TYPE_16x16;
-        for (i = 0; i < 6; i++) v->mb_type[0][s->block_index[i]] = 0;
+        for (i = 0; i < 6; i++)
+            v->mb_type[0][s->block_index[i]] = 0;
         if (idx_mbmode <= 5) { // 1-MV
             dmv_x = dmv_y = pred_flag = 0;
             if (idx_mbmode & 1) {
@@ -1856,18 +1772,14 @@
             mb_has_coeffs = !(idx_mbmode & 2);
         } else { // 4-MV
             v->fourmvbp = get_vlc2(gb, v->fourmvbp_vlc->table, VC1_4MV_BLOCK_PATTERN_VLC_BITS, 1);
-            for (i = 0; i < 6; i++) {
-                if (i < 4) {
-                    dmv_x = dmv_y = pred_flag = 0;
-                    val   = ((v->fourmvbp >> (3 - i)) & 1);
-                    if (val) {
-                        get_mvdata_interlaced(v, &dmv_x, &dmv_y, &pred_flag);
-                    }
-                    ff_vc1_pred_mv(v, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0], pred_flag, 0);
-                    ff_vc1_mc_4mv_luma(v, i, 0, 0);
-                } else if (i == 4)
-                    ff_vc1_mc_4mv_chroma(v, 0);
+            for (i = 0; i < 4; i++) {
+                dmv_x = dmv_y = pred_flag = 0;
+                if (v->fourmvbp & (8 >> i))
+                    get_mvdata_interlaced(v, &dmv_x, &dmv_y, &pred_flag);
+                ff_vc1_pred_mv(v, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0], pred_flag, 0);
+                ff_vc1_mc_4mv_luma(v, i, 0, 0);
             }
+            ff_vc1_mc_4mv_chroma(v, 0);
             mb_has_coeffs = idx_mbmode & 1;
         }
         if (mb_has_coeffs)
@@ -1892,7 +1804,8 @@
                                          (i & 4) && (s->flags & CODEC_FLAG_GRAY),
                                          &block_tt);
                 block_cbp |= pat << (i << 2);
-                if (!v->ttmbf && ttmb < 8) ttmb = -1;
+                if (!v->ttmbf && ttmb < 8)
+                    ttmb = -1;
                 first_block = 0;
             }
         }
@@ -2126,7 +2039,8 @@
     } else {
         s->mb_intra = v->is_intra[s->mb_x] = 0;
         s->current_picture.mb_type[mb_pos + v->mb_off] = MB_TYPE_16x16;
-        for (i = 0; i < 6; i++) v->mb_type[0][s->block_index[i]] = 0;
+        for (i = 0; i < 6; i++)
+            v->mb_type[0][s->block_index[i]] = 0;
         if (v->fmb_is_raw)
             fwd = v->forward_mb_plane[mb_pos] = get_bits1(gb);
         else
@@ -2174,21 +2088,18 @@
                 bmvtype = BMV_TYPE_FORWARD;
             v->bmvtype  = bmvtype;
             v->fourmvbp = get_vlc2(gb, v->fourmvbp_vlc->table, VC1_4MV_BLOCK_PATTERN_VLC_BITS, 1);
-            for (i = 0; i < 6; i++) {
-                if (i < 4) {
-                    dmv_x[0] = dmv_y[0] = pred_flag[0] = 0;
-                    dmv_x[1] = dmv_y[1] = pred_flag[1] = 0;
-                    val = ((v->fourmvbp >> (3 - i)) & 1);
-                    if (val) {
-                        get_mvdata_interlaced(v, &dmv_x[bmvtype == BMV_TYPE_BACKWARD],
-                                                 &dmv_y[bmvtype == BMV_TYPE_BACKWARD],
-                                             &pred_flag[bmvtype == BMV_TYPE_BACKWARD]);
-                    }
-                    ff_vc1_pred_b_mv_intfi(v, i, dmv_x, dmv_y, 0, pred_flag);
-                    ff_vc1_mc_4mv_luma(v, i, bmvtype == BMV_TYPE_BACKWARD, 0);
-                } else if (i == 4)
-                    ff_vc1_mc_4mv_chroma(v, bmvtype == BMV_TYPE_BACKWARD);
+            for (i = 0; i < 4; i++) {
+                dmv_x[0] = dmv_y[0] = pred_flag[0] = 0;
+                dmv_x[1] = dmv_y[1] = pred_flag[1] = 0;
+                if (v->fourmvbp & (8 >> i)) {
+                    get_mvdata_interlaced(v, &dmv_x[bmvtype == BMV_TYPE_BACKWARD],
+                                             &dmv_y[bmvtype == BMV_TYPE_BACKWARD],
+                                         &pred_flag[bmvtype == BMV_TYPE_BACKWARD]);
+                }
+                ff_vc1_pred_b_mv_intfi(v, i, dmv_x, dmv_y, 0, pred_flag);
+                ff_vc1_mc_4mv_luma(v, i, bmvtype == BMV_TYPE_BACKWARD, 0);
             }
+            ff_vc1_mc_4mv_chroma(v, bmvtype == BMV_TYPE_BACKWARD);
             mb_has_coeffs = idx_mbmode & 1;
         }
         if (mb_has_coeffs)
@@ -2835,15 +2746,14 @@
     /* raw bottom MB row */
     s->mb_x = 0;
     init_block_index(v);
-
-    for (;s->mb_x < s->mb_width; s->mb_x++) {
+    for (; s->mb_x < s->mb_width; s->mb_x++) {
         ff_update_block_index(s);
         vc1_put_signed_blocks_clamped(v);
         if (v->s.loop_filter)
             ff_vc1_loop_filter_iblk_delayed(v, v->pq);
     }
     if (v->s.loop_filter)
-        ff_mpeg_draw_horiz_band(s, (s->end_mb_y-1)*16, 16);
+        ff_mpeg_draw_horiz_band(s, (s->end_mb_y - 1) * 16, 16);
     ff_er_add_slice(&s->er, 0, s->start_mb_y << v->field_mode, s->mb_width - 1,
                     (s->end_mb_y << v->field_mode) - 1, ER_MB_END);
 }
@@ -2907,7 +2817,8 @@
         memmove(v->ttblk_base,    v->ttblk,    sizeof(v->ttblk_base[0])    * s->mb_stride);
         memmove(v->is_intra_base, v->is_intra, sizeof(v->is_intra_base[0]) * s->mb_stride);
         memmove(v->luma_mv_base,  v->luma_mv,  sizeof(v->luma_mv_base[0])  * s->mb_stride);
-        if (s->mb_y != s->start_mb_y) ff_mpeg_draw_horiz_band(s, (s->mb_y - 1) * 16, 16);
+        if (s->mb_y != s->start_mb_y)
+            ff_mpeg_draw_horiz_band(s, (s->mb_y - 1) * 16, 16);
         s->first_slice_line = 0;
     }
     if (apply_loop_filter) {
diff --git a/libavcodec/vc1_common.h b/libavcodec/vc1_common.h
index cd67b17..b46c33f 100644
--- a/libavcodec/vc1_common.h
+++ b/libavcodec/vc1_common.h
@@ -26,6 +26,7 @@
 #include <stdint.h>
 
 #include "libavutil/attributes.h"
+#include "internal.h"
 
 /** Markers used in VC-1 AP frame data */
 //@{
@@ -57,12 +58,9 @@
  */
 static av_always_inline const uint8_t* find_next_marker(const uint8_t *src, const uint8_t *end)
 {
-    uint32_t mrk = 0xFFFFFFFF;
-
-    if (end-src < 4)
-        return end;
-    while (src < end) {
-        mrk = (mrk << 8) | *src++;
+    if (end - src >= 4) {
+        uint32_t mrk = 0xFFFFFFFF;
+        src = avpriv_find_start_code(src, end, &mrk);
         if (IS_MARKER(mrk))
             return src - 4;
     }
diff --git a/libavcodec/vc1_mc.c b/libavcodec/vc1_mc.c
index 17800cb..569aad0 100644
--- a/libavcodec/vc1_mc.c
+++ b/libavcodec/vc1_mc.c
@@ -32,6 +32,140 @@
 #include "mpegvideo.h"
 #include "vc1.h"
 
+static av_always_inline void vc1_scale_luma(uint8_t *srcY,
+                                            int k, int linesize)
+{
+    int i, j;
+    for (j = 0; j < k; j++) {
+        for (i = 0; i < k; i++)
+            srcY[i] = ((srcY[i] - 128) >> 1) + 128;
+        srcY += linesize;
+    }
+}
+
+static av_always_inline void vc1_scale_chroma(uint8_t *srcU, uint8_t *srcV,
+                                              int k, int uvlinesize)
+{
+    int i, j;
+    for (j = 0; j < k; j++) {
+        for (i = 0; i < k; i++) {
+            srcU[i] = ((srcU[i] - 128) >> 1) + 128;
+            srcV[i] = ((srcV[i] - 128) >> 1) + 128;
+        }
+        srcU += uvlinesize;
+        srcV += uvlinesize;
+    }
+}
+
+static av_always_inline void vc1_lut_scale_luma(uint8_t *srcY,
+                                                uint8_t *lut1, uint8_t *lut2,
+                                                int k, int linesize)
+{
+    int i, j;
+
+    for (j = 0; j < k; j += 2) {
+        for (i = 0; i < k; i++)
+            srcY[i] = lut1[srcY[i]];
+        srcY += linesize;
+
+        if (j + 1 == k)
+            break;
+
+        for (i = 0; i < k; i++)
+            srcY[i] = lut2[srcY[i]];
+        srcY += linesize;
+    }
+}
+
+static av_always_inline void vc1_lut_scale_chroma(uint8_t *srcU, uint8_t *srcV,
+                                                  uint8_t *lut1, uint8_t *lut2,
+                                                  int k, int uvlinesize)
+{
+    int i, j;
+
+    for (j = 0; j < k; j += 2) {
+        for (i = 0; i < k; i++) {
+            srcU[i] = lut1[srcU[i]];
+            srcV[i] = lut1[srcV[i]];
+        }
+        srcU += uvlinesize;
+        srcV += uvlinesize;
+
+        if (j + 1 == k)
+            break;
+
+        for (i = 0; i < k; i++) {
+            srcU[i] = lut2[srcU[i]];
+            srcV[i] = lut2[srcV[i]];
+        }
+        srcU += uvlinesize;
+        srcV += uvlinesize;
+    }
+}
+
+static const uint8_t popcount4[16] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 };
+
+static av_always_inline int get_luma_mv(VC1Context *v, int dir, int16_t *tx, int16_t *ty)
+{
+    MpegEncContext *s = &v->s;
+    int idx = v->mv_f[dir][s->block_index[0] + v->blocks_off] |
+             (v->mv_f[dir][s->block_index[1] + v->blocks_off] << 1) |
+             (v->mv_f[dir][s->block_index[2] + v->blocks_off] << 2) |
+             (v->mv_f[dir][s->block_index[3] + v->blocks_off] << 3);
+    static const uint8_t index2[16] = { 0, 0, 0, 0x23, 0, 0x13, 0x03, 0, 0, 0x12, 0x02, 0, 0x01, 0, 0, 0 };
+    int opp_count = popcount4[idx];
+
+    switch (opp_count) {
+    case 0:
+    case 4:
+        *tx = median4(s->mv[dir][0][0], s->mv[dir][1][0], s->mv[dir][2][0], s->mv[dir][3][0]);
+        *ty = median4(s->mv[dir][0][1], s->mv[dir][1][1], s->mv[dir][2][1], s->mv[dir][3][1]);
+        break;
+    case 1:
+        *tx = mid_pred(s->mv[dir][idx < 2][0], s->mv[dir][1 + (idx < 4)][0], s->mv[dir][2 + (idx < 8)][0]);
+        *ty = mid_pred(s->mv[dir][idx < 2][1], s->mv[dir][1 + (idx < 4)][1], s->mv[dir][2 + (idx < 8)][1]);
+        break;
+    case 3:
+        *tx = mid_pred(s->mv[dir][idx > 0xd][0], s->mv[dir][1 + (idx > 0xb)][0], s->mv[dir][2 + (idx > 0x7)][0]);
+        *ty = mid_pred(s->mv[dir][idx > 0xd][1], s->mv[dir][1 + (idx > 0xb)][1], s->mv[dir][2 + (idx > 0x7)][1]);
+        break;
+    case 2:
+        *tx = (s->mv[dir][index2[idx] >> 4][0] + s->mv[dir][index2[idx] & 0xf][0]) / 2;
+        *ty = (s->mv[dir][index2[idx] >> 4][1] + s->mv[dir][index2[idx] & 0xf][1]) / 2;
+        break;
+    }
+    return opp_count;
+}
+
+static av_always_inline int get_chroma_mv(VC1Context *v, int dir, int16_t *tx, int16_t *ty)
+{
+    MpegEncContext *s = &v->s;
+    int idx = !v->mb_type[0][s->block_index[0]] |
+             (!v->mb_type[0][s->block_index[1]] << 1) |
+             (!v->mb_type[0][s->block_index[2]] << 2) |
+             (!v->mb_type[0][s->block_index[3]] << 3);
+    static const uint8_t index2[16] = { 0, 0, 0, 0x01, 0, 0x02, 0x12, 0, 0, 0x03, 0x13, 0, 0x23, 0, 0, 0 };
+    int valid_count = popcount4[idx];
+
+    switch (valid_count) {
+    case 4:
+        *tx = median4(s->mv[dir][0][0], s->mv[dir][1][0], s->mv[dir][2][0], s->mv[dir][3][0]);
+        *ty = median4(s->mv[dir][0][1], s->mv[dir][1][1], s->mv[dir][2][1], s->mv[dir][3][1]);
+        break;
+    case 3:
+        *tx = mid_pred(s->mv[dir][idx > 0xd][0], s->mv[dir][1 + (idx > 0xb)][0], s->mv[dir][2 + (idx > 0x7)][0]);
+        *ty = mid_pred(s->mv[dir][idx > 0xd][1], s->mv[dir][1 + (idx > 0xb)][1], s->mv[dir][2 + (idx > 0x7)][1]);
+        break;
+    case 2:
+        *tx = (s->mv[dir][index2[idx] >> 4][0] + s->mv[dir][index2[idx] & 0xf][0]) / 2;
+        *ty = (s->mv[dir][index2[idx] >> 4][1] + s->mv[dir][index2[idx] & 0xf][1]) / 2;
+        break;
+    default:
+        return 0;
+    }
+    return valid_count;
+}
+
 /** Do motion compensation over 1 macroblock
  * Mostly adapted hpel_motion and qpel_motion from mpegvideo.c
  */
@@ -147,11 +281,12 @@
         || (unsigned)(src_y - 1)        > v_edge_pos    - (my&3) - 16 - 3) {
         uint8_t *ubuf = s->edge_emu_buffer + 19 * s->linesize;
         uint8_t *vbuf = ubuf + 9 * s->uvlinesize;
+        const int k = 17 + s->mspel * 2;
 
         srcY -= s->mspel * (1 + s->linesize);
         s->vdsp.emulated_edge_mc(s->edge_emu_buffer, srcY,
                                  s->linesize, s->linesize,
-                                 17 + s->mspel * 2, 17 + s->mspel * 2,
+                                 k, k,
                                  src_x - s->mspel, src_y - s->mspel,
                                  s->h_edge_pos, v_edge_pos);
         srcY = s->edge_emu_buffer;
@@ -169,56 +304,26 @@
         srcV = vbuf;
         /* if we deal with range reduction we need to scale source blocks */
         if (v->rangeredfrm) {
-            int i, j;
-            uint8_t *src, *src2;
-
-            src = srcY;
-            for (j = 0; j < 17 + s->mspel * 2; j++) {
-                for (i = 0; i < 17 + s->mspel * 2; i++)
-                    src[i] = ((src[i] - 128) >> 1) + 128;
-                src += s->linesize;
-            }
-            src  = srcU;
-            src2 = srcV;
-            for (j = 0; j < 9; j++) {
-                for (i = 0; i < 9; i++) {
-                    src[i]  = ((src[i]  - 128) >> 1) + 128;
-                    src2[i] = ((src2[i] - 128) >> 1) + 128;
-                }
-                src  += s->uvlinesize;
-                src2 += s->uvlinesize;
-            }
+            vc1_scale_luma(srcY, k, s->linesize);
+            vc1_scale_chroma(srcU, srcV, 9, s->uvlinesize);
         }
         /* if we deal with intensity compensation we need to scale source blocks */
         if (use_ic) {
-            int i, j;
-            uint8_t *src, *src2;
-
-            src = srcY;
-            for (j = 0; j < 17 + s->mspel * 2; j++) {
-                int f = v->field_mode ? v->ref_field_type[dir] : ((j + src_y - s->mspel) & 1) ;
-                for (i = 0; i < 17 + s->mspel * 2; i++)
-                    src[i] = luty[f][src[i]];
-                src += s->linesize;
-            }
-            src  = srcU;
-            src2 = srcV;
-            for (j = 0; j < 9; j++) {
-                int f = v->field_mode ? v->ref_field_type[dir] : ((j + uvsrc_y) & 1);
-                for (i = 0; i < 9; i++) {
-                    src[i]  = lutuv[f][src[i]];
-                    src2[i] = lutuv[f][src2[i]];
-                }
-                src  += s->uvlinesize;
-                src2 += s->uvlinesize;
-            }
+            vc1_lut_scale_luma(srcY,
+                               luty[v->field_mode ? v->ref_field_type[dir] : ((0 + src_y - s->mspel) & 1)],
+                               luty[v->field_mode ? v->ref_field_type[dir] : ((1 + src_y - s->mspel) & 1)],
+                               k, s->linesize);
+            vc1_lut_scale_chroma(srcU, srcV,
+                                 lutuv[v->field_mode ? v->ref_field_type[dir] : ((0 + uvsrc_y) & 1)],
+                                 lutuv[v->field_mode ? v->ref_field_type[dir] : ((1 + uvsrc_y) & 1)],
+                                 9, s->uvlinesize);
         }
         srcY += s->mspel * (1 + s->linesize);
     }
 
     if (s->mspel) {
         dxy = ((my & 3) << 2) | (mx & 3);
-        v->vc1dsp.put_vc1_mspel_pixels_tab[0][dxy](s->dest[0]    , srcY    , s->linesize, v->rnd);
+        v->vc1dsp.put_vc1_mspel_pixels_tab[0][dxy](s->dest[0], srcY, s->linesize, v->rnd);
     } else { // hpel mc - always used for luma
         dxy = (my & 2) | ((mx & 2) >> 1);
         if (!v->rnd)
@@ -240,17 +345,6 @@
     }
 }
 
-static inline int median4(int a, int b, int c, int d)
-{
-    if (a < b) {
-        if (c < d) return (FFMIN(b, d) + FFMAX(a, c)) / 2;
-        else       return (FFMIN(b, c) + FFMAX(a, d)) / 2;
-    } else {
-        if (c < d) return (FFMIN(a, d) + FFMAX(b, c)) / 2;
-        else       return (FFMIN(a, c) + FFMAX(b, d)) / 2;
-    }
-}
-
 /** Do motion compensation for 4-MV macroblock - luminance block
  */
 void ff_vc1_mc_4mv_luma(VC1Context *v, int n, int dir, int avg)
@@ -299,37 +393,10 @@
     }
 
     if (s->pict_type == AV_PICTURE_TYPE_P && n == 3 && v->field_mode) {
-        int same_count = 0, opp_count = 0, k;
-        int chosen_mv[2][4][2], f;
-        int tx, ty;
-        for (k = 0; k < 4; k++) {
-            f = v->mv_f[0][s->block_index[k] + v->blocks_off];
-            chosen_mv[f][f ? opp_count : same_count][0] = s->mv[0][k][0];
-            chosen_mv[f][f ? opp_count : same_count][1] = s->mv[0][k][1];
-            opp_count  += f;
-            same_count += 1 - f;
-        }
-        f = opp_count > same_count;
-        switch (f ? opp_count : same_count) {
-        case 4:
-            tx = median4(chosen_mv[f][0][0], chosen_mv[f][1][0],
-                         chosen_mv[f][2][0], chosen_mv[f][3][0]);
-            ty = median4(chosen_mv[f][0][1], chosen_mv[f][1][1],
-                         chosen_mv[f][2][1], chosen_mv[f][3][1]);
-            break;
-        case 3:
-            tx = mid_pred(chosen_mv[f][0][0], chosen_mv[f][1][0], chosen_mv[f][2][0]);
-            ty = mid_pred(chosen_mv[f][0][1], chosen_mv[f][1][1], chosen_mv[f][2][1]);
-            break;
-        case 2:
-            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_assert0(0);
-        }
-        s->current_picture.motion_val[1][s->block_index[0] + v->blocks_off][0] = tx;
-        s->current_picture.motion_val[1][s->block_index[0] + v->blocks_off][1] = ty;
+        int opp_count = get_luma_mv(v, 0,
+                                    &s->current_picture.motion_val[1][s->block_index[0] + v->blocks_off][0],
+                                    &s->current_picture.motion_val[1][s->block_index[0] + v->blocks_off][1]);
+        int k, f = opp_count > 2;
         for (k = 0; k < 4; k++)
             v->mv_f[1][s->block_index[k] + v->blocks_off] = f;
     }
@@ -385,46 +452,36 @@
     if (v->field_mode && v->ref_field_type[dir])
         srcY += s->current_picture_ptr->f->linesize[0];
 
-    if (fieldmv && !(src_y & 1))
-        v_edge_pos--;
-    if (fieldmv && (src_y & 1) && src_y < 4)
-        src_y--;
+    if (fieldmv) {
+        if (!(src_y & 1))
+            v_edge_pos--;
+        else
+            src_y -= (src_y < 4);
+    }
     if (v->rangeredfrm || use_ic
         || s->h_edge_pos < 13 || v_edge_pos < 23
         || (unsigned)(src_x - s->mspel) > s->h_edge_pos - (mx & 3) - 8 - s->mspel * 2
         || (unsigned)(src_y - (s->mspel << fieldmv)) > v_edge_pos - (my & 3) - ((8 + s->mspel * 2) << fieldmv)) {
+        const int k = 9 + s->mspel * 2;
+
         srcY -= s->mspel * (1 + (s->linesize << fieldmv));
         /* check emulate edge stride and offset */
         s->vdsp.emulated_edge_mc(s->edge_emu_buffer, srcY,
                                  s->linesize, s->linesize,
-                                 9 + s->mspel * 2, (9 + s->mspel * 2) << fieldmv,
+                                 k, k << fieldmv,
                                  src_x - s->mspel, src_y - (s->mspel << fieldmv),
                                  s->h_edge_pos, v_edge_pos);
         srcY = s->edge_emu_buffer;
         /* if we deal with range reduction we need to scale source blocks */
         if (v->rangeredfrm) {
-            int i, j;
-            uint8_t *src;
-
-            src = srcY;
-            for (j = 0; j < 9 + s->mspel * 2; j++) {
-                for (i = 0; i < 9 + s->mspel * 2; i++)
-                    src[i] = ((src[i] - 128) >> 1) + 128;
-                src += s->linesize << fieldmv;
-            }
+            vc1_scale_luma(srcY, k, s->linesize << fieldmv);
         }
         /* if we deal with intensity compensation we need to scale source blocks */
         if (use_ic) {
-            int i, j;
-            uint8_t *src;
-
-            src = srcY;
-            for (j = 0; j < 9 + s->mspel * 2; j++) {
-                int f = v->field_mode ? v->ref_field_type[dir] : (((j<<fieldmv)+src_y - (s->mspel << fieldmv)) & 1);
-                for (i = 0; i < 9 + s->mspel * 2; i++)
-                    src[i] = luty[f][src[i]];
-                src += s->linesize << fieldmv;
-            }
+            vc1_lut_scale_luma(srcY,
+                               luty[v->field_mode ? v->ref_field_type[dir] : (((0<<fieldmv)+src_y - (s->mspel << fieldmv)) & 1)],
+                               luty[v->field_mode ? v->ref_field_type[dir] : (((1<<fieldmv)+src_y - (s->mspel << fieldmv)) & 1)],
+                               k, s->linesize << fieldmv);
         }
         srcY += s->mspel * (1 + (s->linesize << fieldmv));
     }
@@ -444,59 +501,6 @@
     }
 }
 
-static av_always_inline int get_chroma_mv(int *mvx, int *mvy, int *a, int flag, int *tx, int *ty)
-{
-    int idx, i;
-    static const int count[16] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};
-
-    idx =  ((a[3] != flag) << 3)
-         | ((a[2] != flag) << 2)
-         | ((a[1] != flag) << 1)
-         |  (a[0] != flag);
-    if (!idx) {
-        *tx = median4(mvx[0], mvx[1], mvx[2], mvx[3]);
-        *ty = median4(mvy[0], mvy[1], mvy[2], mvy[3]);
-        return 4;
-    } else if (count[idx] == 1) {
-        switch (idx) {
-        case 0x1:
-            *tx = mid_pred(mvx[1], mvx[2], mvx[3]);
-            *ty = mid_pred(mvy[1], mvy[2], mvy[3]);
-            return 3;
-        case 0x2:
-            *tx = mid_pred(mvx[0], mvx[2], mvx[3]);
-            *ty = mid_pred(mvy[0], mvy[2], mvy[3]);
-            return 3;
-        case 0x4:
-            *tx = mid_pred(mvx[0], mvx[1], mvx[3]);
-            *ty = mid_pred(mvy[0], mvy[1], mvy[3]);
-            return 3;
-        case 0x8:
-            *tx = mid_pred(mvx[0], mvx[1], mvx[2]);
-            *ty = mid_pred(mvy[0], mvy[1], mvy[2]);
-            return 3;
-        }
-    } else if (count[idx] == 2) {
-        int t1 = 0, t2 = 0;
-        for (i = 0; i < 3; i++)
-            if (!a[i]) {
-                t1 = i;
-                break;
-            }
-        for (i = t1 + 1; i < 4; i++)
-            if (!a[i]) {
-                t2 = i;
-                break;
-            }
-        *tx = (mvx[t1] + mvx[t2]) / 2;
-        *ty = (mvy[t1] + mvy[t2]) / 2;
-        return 2;
-    } else {
-        return 0;
-    }
-    return -1;
-}
-
 /** Do motion compensation for 4-MV macroblock - both chroma blocks
  */
 void ff_vc1_mc_4mv_chroma(VC1Context *v, int dir)
@@ -505,10 +509,8 @@
     H264ChromaContext *h264chroma = &v->h264chroma;
     uint8_t *srcU, *srcV;
     int uvmx, uvmy, uvsrc_x, uvsrc_y;
-    int k, tx = 0, ty = 0;
-    int mvx[4], mvy[4], intra[4], mv_f[4];
-    int valid_count;
-    int chroma_ref_type = v->cur_field_type;
+    int16_t tx, ty;
+    int chroma_ref_type;
     int v_edge_pos = s->v_edge_pos >> v->field_mode;
     uint8_t (*lutuv)[256];
     int use_ic;
@@ -518,31 +520,19 @@
     if (s->flags & CODEC_FLAG_GRAY)
         return;
 
-    for (k = 0; k < 4; k++) {
-        mvx[k] = s->mv[dir][k][0];
-        mvy[k] = s->mv[dir][k][1];
-        intra[k] = v->mb_type[0][s->block_index[k]];
-        if (v->field_mode)
-            mv_f[k] = v->mv_f[dir][s->block_index[k] + v->blocks_off];
-    }
-
     /* 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->ref_field_type[dir];
+    if (!v->field_mode || !v->numref) {
+        int valid_count = get_chroma_mv(v, dir, &tx, &ty);
         if (!valid_count) {
             s->current_picture.motion_val[1][s->block_index[0] + v->blocks_off][0] = 0;
             s->current_picture.motion_val[1][s->block_index[0] + v->blocks_off][1] = 0;
             v->luma_mv[s->mb_x][0] = v->luma_mv[s->mb_x][1] = 0;
             return; //no need to do MC for intra blocks
         }
+        chroma_ref_type = v->ref_field_type[dir];
     } else {
-        int dominant = 0;
-        if (mv_f[0] + mv_f[1] + mv_f[2] + mv_f[3] > 2)
-            dominant = 1;
-        valid_count = get_chroma_mv(mvx, mvy, mv_f, dominant, &tx, &ty);
-        if (dominant)
-            chroma_ref_type = !v->cur_field_type;
+        int opp_count = get_luma_mv(v, dir, &tx, &ty);
+        chroma_ref_type = v->cur_field_type ^ (opp_count > 2);
     }
     if (v->field_mode && chroma_ref_type == 1 && v->cur_field_type == 1 && !v->s.last_picture.f->data[0])
         return;
@@ -624,36 +614,14 @@
 
         /* if we deal with range reduction we need to scale source blocks */
         if (v->rangeredfrm) {
-            int i, j;
-            uint8_t *src, *src2;
-
-            src  = srcU;
-            src2 = srcV;
-            for (j = 0; j < 9; j++) {
-                for (i = 0; i < 9; i++) {
-                    src[i]  = ((src[i]  - 128) >> 1) + 128;
-                    src2[i] = ((src2[i] - 128) >> 1) + 128;
-                }
-                src  += s->uvlinesize;
-                src2 += s->uvlinesize;
-            }
+            vc1_scale_chroma(srcU, srcV, 9, s->uvlinesize);
         }
         /* if we deal with intensity compensation we need to scale source blocks */
         if (use_ic) {
-            int i, j;
-            uint8_t *src, *src2;
-
-            src  = srcU;
-            src2 = srcV;
-            for (j = 0; j < 9; j++) {
-                int f = v->field_mode ? chroma_ref_type : ((j + uvsrc_y) & 1);
-                for (i = 0; i < 9; i++) {
-                    src[i]  = lutuv[f][src[i]];
-                    src2[i] = lutuv[f][src2[i]];
-                }
-                src  += s->uvlinesize;
-                src2 += s->uvlinesize;
-            }
+            vc1_lut_scale_chroma(srcU, srcV,
+                                 lutuv[v->field_mode ? chroma_ref_type : ((0 + uvsrc_y) & 1)],
+                                 lutuv[v->field_mode ? chroma_ref_type : ((1 + uvsrc_y) & 1)],
+                                 9, s->uvlinesize);
         }
     }
 
@@ -680,7 +648,7 @@
     int uvmx_field[4], uvmy_field[4];
     int i, off, tx, ty;
     int fieldmv = v->blk_mv_type[s->block_index[0]];
-    static const int s_rndtblfield[16] = { 0, 0, 1, 2, 4, 4, 5, 6, 2, 2, 3, 8, 6, 6, 7, 12 };
+    static const uint8_t s_rndtblfield[16] = { 0, 0, 1, 2, 4, 4, 5, 6, 2, 2, 3, 8, 6, 6, 7, 12 };
     int v_dist = fieldmv ? 1 : 4; // vertical offset for lower sub-blocks
     int v_edge_pos = s->v_edge_pos >> 1;
     int use_ic;
@@ -725,11 +693,12 @@
         uvmx_field[i] = (uvmx_field[i] & 3) << 1;
         uvmy_field[i] = (uvmy_field[i] & 3) << 1;
 
-        if (fieldmv && !(uvsrc_y & 1))
-            v_edge_pos = (s->v_edge_pos >> 1) - 1;
-
-        if (fieldmv && (uvsrc_y & 1) && uvsrc_y < 2)
-            uvsrc_y--;
+        if (fieldmv) {
+            if (!(uvsrc_y & 1))
+                v_edge_pos = (s->v_edge_pos >> 1) - 1;
+            else
+                uvsrc_y -= (uvsrc_y < 2);
+        }
         if (use_ic
             || s->h_edge_pos < 10 || v_edge_pos < (5 << fieldmv)
             || (unsigned)uvsrc_x > (s->h_edge_pos >> 1) - 5
@@ -747,20 +716,10 @@
 
             /* if we deal with intensity compensation we need to scale source blocks */
             if (use_ic) {
-                int i, j;
-                uint8_t *src, *src2;
-
-                src  = srcU;
-                src2 = srcV;
-                for (j = 0; j < 5; j++) {
-                    int f = (uvsrc_y + (j << fieldmv)) & 1;
-                    for (i = 0; i < 5; i++) {
-                        src[i]  = lutuv[f][src[i]];
-                        src2[i] = lutuv[f][src2[i]];
-                    }
-                    src  += s->uvlinesize << fieldmv;
-                    src2 += s->uvlinesize << fieldmv;
-                }
+                vc1_lut_scale_chroma(srcU, srcV,
+                                     lutuv[(uvsrc_y + (0 << fieldmv)) & 1],
+                                     lutuv[(uvsrc_y + (1 << fieldmv)) & 1],
+                                     5, s->uvlinesize << fieldmv);
             }
         }
         if (avg) {
@@ -791,7 +750,6 @@
     H264ChromaContext *h264chroma = &v->h264chroma;
     uint8_t *srcY, *srcU, *srcV;
     int dxy, mx, my, uvmx, uvmy, src_x, src_y, uvsrc_x, uvsrc_y;
-    int off, off_uv;
     int v_edge_pos = s->v_edge_pos >> v->field_mode;
     int use_ic = v->next_use_ic;
 
@@ -852,11 +810,12 @@
         || (unsigned)(src_y - 1) > v_edge_pos    - (my & 3) - 16 - 3) {
         uint8_t *ubuf = s->edge_emu_buffer + 19 * s->linesize;
         uint8_t *vbuf = ubuf + 9 * s->uvlinesize;
+        const int k = 17 + s->mspel * 2;
 
         srcY -= s->mspel * (1 + s->linesize);
         s->vdsp.emulated_edge_mc(s->edge_emu_buffer, srcY,
                                  s->linesize, s->linesize,
-                                 17 + s->mspel * 2, 17 + s->mspel * 2,
+                                 k, k,
                                  src_x - s->mspel, src_y - s->mspel,
                                  s->h_edge_pos, v_edge_pos);
         srcY = s->edge_emu_buffer;
@@ -874,68 +833,35 @@
         srcV = vbuf;
         /* if we deal with range reduction we need to scale source blocks */
         if (v->rangeredfrm) {
-            int i, j;
-            uint8_t *src, *src2;
-
-            src = srcY;
-            for (j = 0; j < 17 + s->mspel * 2; j++) {
-                for (i = 0; i < 17 + s->mspel * 2; i++)
-                    src[i] = ((src[i] - 128) >> 1) + 128;
-                src += s->linesize;
-            }
-            src = srcU;
-            src2 = srcV;
-            for (j = 0; j < 9; j++) {
-                for (i = 0; i < 9; i++) {
-                    src[i]  = ((src[i]  - 128) >> 1) + 128;
-                    src2[i] = ((src2[i] - 128) >> 1) + 128;
-                }
-                src  += s->uvlinesize;
-                src2 += s->uvlinesize;
-            }
+            vc1_scale_luma(srcY, k, s->linesize);
+            vc1_scale_chroma(srcU, srcV, 9, s->uvlinesize);
         }
 
         if (use_ic) {
             uint8_t (*luty )[256] = v->next_luty;
             uint8_t (*lutuv)[256] = v->next_lutuv;
-            int i, j;
-            uint8_t *src, *src2;
-
-            src = srcY;
-            for (j = 0; j < 17 + s->mspel * 2; j++) {
-                int f = v->field_mode ? v->ref_field_type[1] : ((j+src_y - s->mspel) & 1);
-                for (i = 0; i < 17 + s->mspel * 2; i++)
-                    src[i] = luty[f][src[i]];
-                src += s->linesize;
-            }
-            src  = srcU;
-            src2 = srcV;
-            for (j = 0; j < 9; j++) {
-                int f = v->field_mode ? v->ref_field_type[1] : ((j+uvsrc_y) & 1);
-                for (i = 0; i < 9; i++) {
-                    src[i]  = lutuv[f][src[i]];
-                    src2[i] = lutuv[f][src2[i]];
-                }
-                src  += s->uvlinesize;
-                src2 += s->uvlinesize;
-            }
+            vc1_lut_scale_luma(srcY,
+                               luty[v->field_mode ? v->ref_field_type[1] : ((0+src_y - s->mspel) & 1)],
+                               luty[v->field_mode ? v->ref_field_type[1] : ((1+src_y - s->mspel) & 1)],
+                               k, s->linesize);
+            vc1_lut_scale_chroma(srcU, srcV,
+                                 lutuv[v->field_mode ? v->ref_field_type[1] : ((0+uvsrc_y) & 1)],
+                                 lutuv[v->field_mode ? v->ref_field_type[1] : ((1+uvsrc_y) & 1)],
+                                 9, s->uvlinesize);
         }
         srcY += s->mspel * (1 + s->linesize);
     }
 
-    off    = 0;
-    off_uv = 0;
-
     if (s->mspel) {
         dxy = ((my & 3) << 2) | (mx & 3);
-        v->vc1dsp.avg_vc1_mspel_pixels_tab[0][dxy](s->dest[0] + off    , srcY    , s->linesize, v->rnd);
+        v->vc1dsp.avg_vc1_mspel_pixels_tab[0][dxy](s->dest[0], srcY, s->linesize, v->rnd);
     } else { // hpel mc
         dxy = (my & 2) | ((mx & 2) >> 1);
 
         if (!v->rnd)
-            s->hdsp.avg_pixels_tab[0][dxy](s->dest[0] + off, srcY, s->linesize, 16);
+            s->hdsp.avg_pixels_tab[0][dxy](s->dest[0], srcY, s->linesize, 16);
         else
-            s->hdsp.avg_no_rnd_pixels_tab[dxy](s->dest[0] + off, srcY, s->linesize, 16);
+            s->hdsp.avg_no_rnd_pixels_tab[dxy](s->dest[0], srcY, s->linesize, 16);
     }
 
     if (s->flags & CODEC_FLAG_GRAY) return;
@@ -943,10 +869,10 @@
     uvmx = (uvmx & 3) << 1;
     uvmy = (uvmy & 3) << 1;
     if (!v->rnd) {
-        h264chroma->avg_h264_chroma_pixels_tab[0](s->dest[1] + off_uv, srcU, s->uvlinesize, 8, uvmx, uvmy);
-        h264chroma->avg_h264_chroma_pixels_tab[0](s->dest[2] + off_uv, srcV, s->uvlinesize, 8, uvmx, uvmy);
+        h264chroma->avg_h264_chroma_pixels_tab[0](s->dest[1], srcU, s->uvlinesize, 8, uvmx, uvmy);
+        h264chroma->avg_h264_chroma_pixels_tab[0](s->dest[2], srcV, s->uvlinesize, 8, uvmx, uvmy);
     } else {
-        v->vc1dsp.avg_no_rnd_vc1_chroma_pixels_tab[0](s->dest[1] + off_uv, srcU, s->uvlinesize, 8, uvmx, uvmy);
-        v->vc1dsp.avg_no_rnd_vc1_chroma_pixels_tab[0](s->dest[2] + off_uv, srcV, s->uvlinesize, 8, uvmx, uvmy);
+        v->vc1dsp.avg_no_rnd_vc1_chroma_pixels_tab[0](s->dest[1], srcU, s->uvlinesize, 8, uvmx, uvmy);
+        v->vc1dsp.avg_no_rnd_vc1_chroma_pixels_tab[0](s->dest[2], srcV, s->uvlinesize, 8, uvmx, uvmy);
     }
 }
diff --git a/libavcodec/vc1_parser.c b/libavcodec/vc1_parser.c
index 3a2308e..9ca6154 100644
--- a/libavcodec/vc1_parser.c
+++ b/libavcodec/vc1_parser.c
@@ -29,6 +29,7 @@
 #include "parser.h"
 #include "vc1.h"
 #include "get_bits.h"
+#include "internal.h"
 
 /** The maximum number of bytes of a sequence, entry point or
  *  frame header whose values we pay any attention to */
@@ -47,7 +48,7 @@
     ONE
 } VC1ParseSearchState;
 
-typedef struct {
+typedef struct VC1ParseContext {
     ParseContext pc;
     VC1Context v;
     uint8_t prev_start_code;
@@ -250,20 +251,18 @@
 static int vc1_split(AVCodecContext *avctx,
                            const uint8_t *buf, int buf_size)
 {
-    int i;
-    uint32_t state= -1;
-    int charged=0;
+    uint32_t state = -1;
+    int charged = 0;
+    const uint8_t *ptr = buf, *end = buf + buf_size;
 
-    for(i=0; i<buf_size; i++){
-        state= (state<<8) | buf[i];
-        if(IS_MARKER(state)){
-            if(state == VC1_CODE_SEQHDR || state == VC1_CODE_ENTRYPOINT){
-                charged=1;
-            }else if(charged){
-                return i-3;
-            }
-        }
+    while (ptr < end) {
+        ptr = avpriv_find_start_code(ptr, end, &state);
+        if (state == VC1_CODE_SEQHDR || state == VC1_CODE_ENTRYPOINT) {
+            charged = 1;
+        } else if (charged && IS_MARKER(state))
+            return ptr - 4 - buf;
     }
+
     return 0;
 }
 
diff --git a/libavcodec/vc1_pred.c b/libavcodec/vc1_pred.c
index d0908ef..13134e5 100644
--- a/libavcodec/vc1_pred.c
+++ b/libavcodec/vc1_pred.c
@@ -170,9 +170,9 @@
     n >>= hpel;
     if (v->s.pict_type != AV_PICTURE_TYPE_B || v->second_field || !dir) {
         if (dim)
-            n = scaleforsame_y(v, i, n, dir) << hpel;
+            n = scaleforsame_y(v, i, n, dir) * (1 << hpel);
         else
-            n = scaleforsame_x(v, n, dir) << hpel;
+            n = scaleforsame_x(v, n, dir) * (1 << hpel);
         return n;
     }
     brfd      = FFMIN(v->brfd, 3);
@@ -202,7 +202,7 @@
         refdist = dir ? v->brfd : v->frfd;
     scaleopp = ff_vc1_field_mvpred_scales[dir ^ v->second_field][0][refdist];
 
-    n = (n * scaleopp >> 8) << hpel;
+    n = (n * scaleopp >> 8) * (1 << hpel);
     return n;
 }
 
@@ -231,8 +231,10 @@
     else
         mixedmv_pic = 0;
     /* scale MV difference to be quad-pel */
-    dmv_x <<= 1 - s->quarter_sample;
-    dmv_y <<= 1 - s->quarter_sample;
+    if (!s->quarter_sample) {
+        dmv_x *= 2;
+        dmv_y *= 2;
+    }
 
     wrap = s->b8_stride;
     xy   = s->block_index[n];
@@ -392,17 +394,13 @@
     /* Pullback MV as specified in 8.3.5.3.4 */
     if (!v->field_mode) {
         int qx, qy, X, Y;
+        int MV = mv1 ? -60 : -28;
         qx = (s->mb_x << 6) + ((n == 1 || n == 3) ? 32 : 0);
         qy = (s->mb_y << 6) + ((n == 2 || n == 3) ? 32 : 0);
         X  = (s->mb_width  << 6) - 4;
         Y  = (s->mb_height << 6) - 4;
-        if (mv1) {
-            if (qx + px < -60) px = -60 - qx;
-            if (qy + py < -60) py = -60 - qy;
-        } else {
-            if (qx + px < -28) px = -28 - qx;
-            if (qy + py < -28) py = -28 - qy;
-        }
+        if (qx + px < MV) px = MV - qx;
+        if (qy + py < MV) py = MV - qy;
         if (qx + px > X) px = X - qx;
         if (qy + py > Y) py = Y - qy;
     }
@@ -699,10 +697,12 @@
     r_x = v->range_x;
     r_y = v->range_y;
     /* scale MV difference to be quad-pel */
-    dmv_x[0] <<= 1 - s->quarter_sample;
-    dmv_y[0] <<= 1 - s->quarter_sample;
-    dmv_x[1] <<= 1 - s->quarter_sample;
-    dmv_y[1] <<= 1 - s->quarter_sample;
+    if (!s->quarter_sample) {
+        dmv_x[0] *= 2;
+        dmv_y[0] *= 2;
+        dmv_x[1] *= 2;
+        dmv_y[1] *= 2;
+    }
 
     wrap = s->b8_stride;
     xy = s->block_index[0];
@@ -759,25 +759,16 @@
         /* Pullback MV as specified in 8.3.5.3.4 */
         {
             int qx, qy, X, Y;
-            if (v->profile < PROFILE_ADVANCED) {
-                qx = (s->mb_x << 5);
-                qy = (s->mb_y << 5);
-                X  = (s->mb_width  << 5) - 4;
-                Y  = (s->mb_height << 5) - 4;
-                if (qx + px < -28) px = -28 - qx;
-                if (qy + py < -28) py = -28 - qy;
-                if (qx + px > X) px = X - qx;
-                if (qy + py > Y) py = Y - qy;
-            } else {
-                qx = (s->mb_x << 6);
-                qy = (s->mb_y << 6);
-                X  = (s->mb_width  << 6) - 4;
-                Y  = (s->mb_height << 6) - 4;
-                if (qx + px < -60) px = -60 - qx;
-                if (qy + py < -60) py = -60 - qy;
-                if (qx + px > X) px = X - qx;
-                if (qy + py > Y) py = Y - qy;
-            }
+            int sh = v->profile < PROFILE_ADVANCED ? 5 : 6;
+            int MV = 4 - (1 << sh);
+            qx = (s->mb_x << sh);
+            qy = (s->mb_y << sh);
+            X  = (s->mb_width  << sh) - 4;
+            Y  = (s->mb_height << sh) - 4;
+            if (qx + px < MV) px = MV - qx;
+            if (qy + py < MV) py = MV - qy;
+            if (qx + px > X) px = X - qx;
+            if (qy + py > Y) py = Y - qy;
         }
         /* Calculate hybrid prediction as specified in 8.3.5.3.5 */
         if (0 && !s->first_slice_line && s->mb_x) {
@@ -838,25 +829,16 @@
         /* Pullback MV as specified in 8.3.5.3.4 */
         {
             int qx, qy, X, Y;
-            if (v->profile < PROFILE_ADVANCED) {
-                qx = (s->mb_x << 5);
-                qy = (s->mb_y << 5);
-                X  = (s->mb_width  << 5) - 4;
-                Y  = (s->mb_height << 5) - 4;
-                if (qx + px < -28) px = -28 - qx;
-                if (qy + py < -28) py = -28 - qy;
-                if (qx + px > X) px = X - qx;
-                if (qy + py > Y) py = Y - qy;
-            } else {
-                qx = (s->mb_x << 6);
-                qy = (s->mb_y << 6);
-                X  = (s->mb_width  << 6) - 4;
-                Y  = (s->mb_height << 6) - 4;
-                if (qx + px < -60) px = -60 - qx;
-                if (qy + py < -60) py = -60 - qy;
-                if (qx + px > X) px = X - qx;
-                if (qy + py > Y) py = Y - qy;
-            }
+            int sh = v->profile < PROFILE_ADVANCED ? 5 : 6;
+            int MV = 4 - (1 << sh);
+            qx = (s->mb_x << sh);
+            qy = (s->mb_y << sh);
+            X  = (s->mb_width  << sh) - 4;
+            Y  = (s->mb_height << sh) - 4;
+            if (qx + px < MV) px = MV - qx;
+            if (qy + py < MV) py = MV - qy;
+            if (qx + px > X) px = X - qx;
+            if (qy + py > Y) py = Y - qy;
         }
         /* Calculate hybrid prediction as specified in 8.3.5.3.5 */
         if (0 && !s->first_slice_line && s->mb_x) {
diff --git a/libavcodec/vc1dec.c b/libavcodec/vc1dec.c
index da6724c..7069447 100644
--- a/libavcodec/vc1dec.c
+++ b/libavcodec/vc1dec.c
@@ -41,7 +41,7 @@
 
 #if CONFIG_WMV3IMAGE_DECODER || CONFIG_VC1IMAGE_DECODER
 
-typedef struct {
+typedef struct SpriteData {
     /**
      * Transform coefficients for both sprites in 16.16 fixed point format,
      * in the order they appear in the bitstream:
@@ -188,7 +188,7 @@
         yoff[i] = av_clip(sd->coefs[i][5], 0, v->sprite_height-1 << 16);
         yadv[i] = av_clip(sd->coefs[i][4], 0, ((v->sprite_height << 16) - yoff[i]) / v->output_height);
     }
-    alpha = av_clip(sd->coefs[1][6], 0, (1<<16) - 1);
+    alpha = av_clip_uint16(sd->coefs[1][6]);
 
     for (plane = 0; plane < (s->flags&CODEC_FLAG_GRAY ? 1 : 3); plane++) {
         int width = v->output_width>>!!plane;
diff --git a/libavcodec/vc1dsp.c b/libavcodec/vc1dsp.c
index 73e1001..a16c8d5 100644
--- a/libavcodec/vc1dsp.c
+++ b/libavcodec/vc1dsp.c
@@ -723,10 +723,10 @@
     }\
 }
 
-#define op_put(a, b) a = av_clip_uint8(b)
-#define op_avg(a, b) a = (a + av_clip_uint8(b) + 1) >> 1
-#define op4_avg(a, b) a = rnd_avg32(a, b)
-#define op4_put(a, b) a = b
+#define op_put(a, b) (a) = av_clip_uint8(b)
+#define op_avg(a, b) (a) = ((a) + av_clip_uint8(b) + 1) >> 1
+#define op4_avg(a, b) (a) = rnd_avg32(a, b)
+#define op4_put(a, b) (a) = (b)
 
 VC1_MSPEL_MC(op_put, op4_put, put_)
 VC1_MSPEL_MC(op_avg, op4_avg, avg_)
diff --git a/libavcodec/vdpau.c b/libavcodec/vdpau.c
index 475a56c..1656995 100644
--- a/libavcodec/vdpau.c
+++ b/libavcodec/vdpau.c
@@ -468,7 +468,7 @@
     render = (struct vdpau_render_state *)h->cur_pic_ptr->f.data[0];
     assert(render);
 
-    render->info.h264.slice_count = h->slice_num;
+    render->info.h264.slice_count = h->current_slice;
     if (render->info.h264.slice_count < 1)
         return;
 
@@ -500,7 +500,7 @@
     memcpy(render->info.h264.scaling_lists_8x8[0], h->pps.scaling_matrix8[0], sizeof(render->info.h264.scaling_lists_8x8[0]));
     memcpy(render->info.h264.scaling_lists_8x8[1], h->pps.scaling_matrix8[3], sizeof(render->info.h264.scaling_lists_8x8[0]));
 
-    ff_h264_draw_horiz_band(h, 0, h->avctx->height);
+    ff_h264_draw_horiz_band(h, &h->slice_ctx[0], 0, h->avctx->height);
     render->bitstream_buffers_used = 0;
 }
 #endif /* CONFIG_H264_VDPAU_DECODER */
diff --git a/libavcodec/vdpau_h264.c b/libavcodec/vdpau_h264.c
index 1736bbd..a9d0c8a 100644
--- a/libavcodec/vdpau_h264.c
+++ b/libavcodec/vdpau_h264.c
@@ -198,6 +198,7 @@
 static int vdpau_h264_end_frame(AVCodecContext *avctx)
 {
     H264Context *h = avctx->priv_data;
+    H264SliceContext *sl = &h->slice_ctx[0];
     H264Picture *pic = h->cur_pic_ptr;
     struct vdpau_picture_context *pic_ctx = pic->hwaccel_picture_private;
     int val;
@@ -206,7 +207,7 @@
     if (val < 0)
         return val;
 
-    ff_h264_draw_horiz_band(h, 0, h->avctx->height);
+    ff_h264_draw_horiz_band(h, sl, 0, h->avctx->height);
     return 0;
 }
 
diff --git a/libavcodec/vdpau_internal.h b/libavcodec/vdpau_internal.h
index e5fe63d..cc49db8 100644
--- a/libavcodec/vdpau_internal.h
+++ b/libavcodec/vdpau_internal.h
@@ -31,10 +31,10 @@
 #endif
 #include "h264.h"
 
+#include "libavutil/frame.h"
+
 #include "avcodec.h"
 #include "mpeg4video.h"
-#include "mpegvideo.h"
-#include "version.h"
 
 /** Extract VdpVideoSurface from an AVFrame */
 static inline uintptr_t ff_vdpau_get_surface_id(AVFrame *pic)
diff --git a/libavcodec/vdpau_mpeg12.c b/libavcodec/vdpau_mpeg12.c
index c47e50e..3ac2cb8 100644
--- a/libavcodec/vdpau_mpeg12.c
+++ b/libavcodec/vdpau_mpeg12.c
@@ -24,6 +24,7 @@
 #include <vdpau/vdpau.h>
 
 #include "avcodec.h"
+#include "mpegvideo.h"
 #include "vdpau.h"
 #include "vdpau_internal.h"
 
diff --git a/libavcodec/version.h b/libavcodec/version.h
index 3827c38..d2950ec 100644
--- a/libavcodec/version.h
+++ b/libavcodec/version.h
@@ -29,7 +29,7 @@
 #include "libavutil/version.h"
 
 #define LIBAVCODEC_VERSION_MAJOR 56
-#define LIBAVCODEC_VERSION_MINOR  21
+#define LIBAVCODEC_VERSION_MINOR  29
 #define LIBAVCODEC_VERSION_MICRO 101
 
 #define LIBAVCODEC_VERSION_INT  AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \
@@ -48,6 +48,9 @@
  * the public API and may change, break or disappear at any time.
  */
 
+#ifndef FF_API_VIMA_DECODER
+#define FF_API_VIMA_DECODER     (LIBAVCODEC_VERSION_MAJOR < 57)
+#endif
 #ifndef FF_API_REQUEST_CHANNELS
 #define FF_API_REQUEST_CHANNELS (LIBAVCODEC_VERSION_MAJOR < 57)
 #endif
diff --git a/libavcodec/videodsp_template.c b/libavcodec/videodsp_template.c
index f4ff2ba..c569c30 100644
--- a/libavcodec/videodsp_template.c
+++ b/libavcodec/videodsp_template.c
@@ -19,8 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#include <assert.h>
-
 #include "bit_depth_template.c"
 void FUNC(ff_emulated_edge_mc)(uint8_t *buf, const uint8_t *src,
                                ptrdiff_t buf_linesize,
diff --git a/libavcodec/vima.c b/libavcodec/vima.c
index ba3f07a..74d6a9a 100644
--- a/libavcodec/vima.c
+++ b/libavcodec/vima.c
@@ -217,6 +217,7 @@
     .capabilities = CODEC_CAP_DR1,
 };
 
+#if FF_API_VIMA_DECODER
 AVCodec ff_vima_decoder = {
     .name         = "vima",
     .long_name    = NULL_IF_CONFIG_SMALL("LucasArts VIMA audio"),
@@ -226,3 +227,4 @@
     .decode       = decode_frame,
     .capabilities = CODEC_CAP_DR1,
 };
+#endif
diff --git a/libavcodec/vorbis_parser.c b/libavcodec/vorbis_parser.c
index 547fd47..8fa6d99 100644
--- a/libavcodec/vorbis_parser.c
+++ b/libavcodec/vorbis_parser.c
@@ -229,6 +229,8 @@
                 *flags |= VORBIS_FLAG_HEADER;
             else if (buf[0] == 3)
                 *flags |= VORBIS_FLAG_COMMENT;
+            else if (buf[0] == 5)
+                *flags |= VORBIS_FLAG_SETUP;
             else
                 goto bad_packet;
 
diff --git a/libavcodec/vorbis_parser.h b/libavcodec/vorbis_parser.h
index 0f73537..06e48bd 100644
--- a/libavcodec/vorbis_parser.h
+++ b/libavcodec/vorbis_parser.h
@@ -47,6 +47,7 @@
 
 #define VORBIS_FLAG_HEADER  0x00000001
 #define VORBIS_FLAG_COMMENT 0x00000002
+#define VORBIS_FLAG_SETUP   0x00000004
 
 /**
  * Get the duration for a Vorbis packet.
diff --git a/libavcodec/vorbisdec.c b/libavcodec/vorbisdec.c
index 09a863f..19bde18 100644
--- a/libavcodec/vorbisdec.c
+++ b/libavcodec/vorbisdec.c
@@ -35,7 +35,6 @@
 #include "avcodec.h"
 #include "get_bits.h"
 #include "fft.h"
-#include "fmtconvert.h"
 #include "internal.h"
 
 #include "vorbis.h"
@@ -47,7 +46,7 @@
 #define V_MAX_VLCS (1 << 16)
 #define V_MAX_PARTITIONS (1 << 20)
 
-typedef struct {
+typedef struct vorbis_codebook {
     uint8_t      dimensions;
     uint8_t      lookup_type;
     uint8_t      maxdepth;
@@ -63,7 +62,7 @@
 typedef
 int (* vorbis_floor_decode_func)
     (struct vorbis_context_s *, vorbis_floor_data *, float *);
-typedef struct {
+typedef struct vorbis_floor {
     uint8_t floor_type;
     vorbis_floor_decode_func decode;
     union vorbis_floor_u {
@@ -93,7 +92,7 @@
     } data;
 } vorbis_floor;
 
-typedef struct {
+typedef struct vorbis_residue {
     uint16_t      type;
     uint32_t      begin;
     uint32_t      end;
@@ -106,7 +105,7 @@
     uint8_t      *classifs;
 } vorbis_residue;
 
-typedef struct {
+typedef struct vorbis_mapping {
     uint8_t       submaps;
     uint16_t      coupling_steps;
     uint8_t      *magnitude;
@@ -116,7 +115,7 @@
     uint8_t       submap_residue[16];
 } vorbis_mapping;
 
-typedef struct {
+typedef struct vorbis_mode {
     uint8_t       blockflag;
     uint16_t      windowtype;
     uint16_t      transformtype;
@@ -128,7 +127,6 @@
     GetBitContext gb;
     VorbisDSPContext dsp;
     AVFloatDSPContext *fdsp;
-    FmtConvertContext fmt_conv;
 
     FFTContext mdct[2];
     uint8_t       first_frame;
@@ -379,10 +377,17 @@
             }
 
 // Weed out unused vlcs and build codevector vector
-            codebook_setup->codevectors = used_entries ? av_mallocz_array(used_entries,
-                                                                    codebook_setup->dimensions *
-                                                                    sizeof(*codebook_setup->codevectors))
-                                                       : NULL;
+            if (used_entries) {
+                codebook_setup->codevectors =
+                    av_mallocz_array(used_entries, codebook_setup->dimensions *
+                               sizeof(*codebook_setup->codevectors));
+                if (!codebook_setup->codevectors) {
+                    ret = AVERROR(ENOMEM);
+                    goto error;
+                }
+            } else
+                codebook_setup->codevectors = NULL;
+
             for (j = 0, i = 0; i < entries; ++i) {
                 unsigned dim = codebook_setup->dimensions;
 
@@ -1024,7 +1029,6 @@
 
     vc->avctx = avctx;
     ff_vorbisdsp_init(&vc->dsp);
-    ff_fmt_convert_init(&vc->fmt_conv, avctx);
 
     avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
 
@@ -1321,38 +1325,34 @@
                                            int ptns_to_read
                                           )
 {
+    vorbis_codebook *codebook = vc->codebooks + vr->classbook;
     int p, j, i;
-    unsigned c_p_c         = vc->codebooks[vr->classbook].dimensions;
+    unsigned c_p_c         = codebook->dimensions;
     unsigned inverse_class = ff_inverse[vr->classifications];
-    unsigned temp, temp2;
+    int temp, temp2;
     for (p = 0, j = 0; j < ch_used; ++j) {
         if (!do_not_decode[j]) {
-            temp = get_vlc2(&vc->gb, vc->codebooks[vr->classbook].vlc.table,
-                                     vc->codebooks[vr->classbook].nb_bits, 3);
+            temp = get_vlc2(&vc->gb, codebook->vlc.table,
+                                     codebook->nb_bits, 3);
 
             av_dlog(NULL, "Classword: %u\n", temp);
 
-            if ((int)temp < 0)
-                return temp;
+            av_assert0(temp < 65536);
+
+            if (temp < 0) {
+                av_log(vc->avctx, AV_LOG_ERROR,
+                       "Invalid vlc code decoding %d channel.", j);
+                return AVERROR_INVALIDDATA;
+            }
 
             av_assert0(vr->classifications > 1); //needed for inverse[]
 
-            if (temp <= 65536) {
-                for (i = partition_count + c_p_c - 1; i >= partition_count; i--) {
-                    temp2 = (((uint64_t)temp) * inverse_class) >> 32;
+            for (i = partition_count + c_p_c - 1; i >= partition_count; i--) {
+                temp2 = (((uint64_t)temp) * inverse_class) >> 32;
 
-                    if (i < ptns_to_read)
-                        vr->classifs[p + i] = temp - temp2 * vr->classifications;
-                    temp = temp2;
-                }
-            } else {
-                for (i = partition_count + c_p_c - 1; i >= partition_count; i--) {
-                    temp2 = temp / vr->classifications;
-
-                    if (i < ptns_to_read)
-                        vr->classifs[p + i] = temp - temp2 * vr->classifications;
-                    temp = temp2;
-                }
+                if (i < ptns_to_read)
+                    vr->classifs[p + i] = temp - temp2 * vr->classifications;
+                temp = temp2;
             }
         }
         p += ptns_to_read;
@@ -1408,8 +1408,8 @@
         voffset = vr->begin;
         for (partition_count = 0; partition_count < ptns_to_read;) {  // SPEC        error
             if (!pass) {
-                int ret;
-                if ((ret = setup_classifs(vc, vr, do_not_decode, ch_used, partition_count, ptns_to_read)) < 0)
+                int ret = setup_classifs(vc, vr, do_not_decode, ch_used, partition_count, ptns_to_read);
+                if (ret < 0)
                     return ret;
             }
             for (i = 0; (i < c_p_c) && (partition_count < ptns_to_read); ++i) {
diff --git a/libavcodec/vorbisenc.c b/libavcodec/vorbisenc.c
index c06093e..dcb2a6e 100644
--- a/libavcodec/vorbisenc.c
+++ b/libavcodec/vorbisenc.c
@@ -39,7 +39,7 @@
 #undef NDEBUG
 #include <assert.h>
 
-typedef struct {
+typedef struct vorbis_enc_codebook {
     int nentries;
     uint8_t *lens;
     uint32_t *codewords;
@@ -53,14 +53,14 @@
     float *pow2;
 } vorbis_enc_codebook;
 
-typedef struct {
+typedef struct vorbis_enc_floor_class {
     int dim;
     int subclass;
     int masterbook;
     int *books;
 } vorbis_enc_floor_class;
 
-typedef struct {
+typedef struct vorbis_enc_floor {
     int partitions;
     int *partition_to_class;
     int nclasses;
@@ -71,7 +71,7 @@
     vorbis_floor1_entry *list;
 } vorbis_enc_floor;
 
-typedef struct {
+typedef struct vorbis_enc_residue {
     int type;
     int begin;
     int end;
@@ -82,7 +82,7 @@
     float (*maxes)[2];
 } vorbis_enc_residue;
 
-typedef struct {
+typedef struct vorbis_enc_mapping {
     int submaps;
     int *mux;
     int *floor;
@@ -92,12 +92,12 @@
     int *angle;
 } vorbis_enc_mapping;
 
-typedef struct {
+typedef struct vorbis_enc_mode {
     int blockflag;
     int mapping;
 } vorbis_enc_mode;
 
-typedef struct {
+typedef struct vorbis_enc_context {
     int channels;
     int sample_rate;
     int log2_blocksize[2];
diff --git a/libavcodec/vp3.c b/libavcodec/vp3.c
index 726eda0..8a7c6b2 100644
--- a/libavcodec/vp3.c
+++ b/libavcodec/vp3.c
@@ -1998,7 +1998,8 @@
     GetBitContext gb;
     int i, ret;
 
-    init_get_bits(&gb, buf, buf_size * 8);
+    if ((ret = init_get_bits8(&gb, buf, buf_size)) < 0)
+        return ret;
 
 #if CONFIG_THEORA_DECODER
     if (s->theora && get_bits1(&gb)) {
@@ -2276,7 +2277,7 @@
     if (av_image_check_size(visible_width, visible_height, 0, avctx) < 0 ||
         visible_width  + offset_x > s->width ||
         visible_height + offset_y > s->height) {
-        av_log(s, AV_LOG_ERROR,
+        av_log(avctx, AV_LOG_ERROR,
                "Invalid frame dimensions - w:%d h:%d x:%d y:%d (%dx%d).\n",
                visible_width, visible_height, offset_x, offset_y,
                s->width, s->height);
@@ -2491,7 +2492,7 @@
     for (i = 0; i < 3; i++) {
         if (header_len[i] <= 0)
             continue;
-        init_get_bits(&gb, header_start[i], header_len[i] * 8);
+        init_get_bits8(&gb, header_start[i], header_len[i]);
 
         ptype = get_bits(&gb, 8);
 
diff --git a/libavcodec/vp56.c b/libavcodec/vp56.c
index ba39b56..6319248 100644
--- a/libavcodec/vp56.c
+++ b/libavcodec/vp56.c
@@ -473,7 +473,7 @@
     if (s->mb_width > 1000 || s->mb_height > 1000) {
         ff_set_dimensions(avctx, 0, 0);
         av_log(avctx, AV_LOG_ERROR, "picture too big\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
     }
 
     av_reallocp_array(&s->above_blocks, 4*s->mb_width+6,
@@ -509,11 +509,11 @@
 
     if (s->has_alpha) {
         if (remaining_buf_size < 3)
-            return -1;
+            return AVERROR_INVALIDDATA;
         alpha_offset = bytestream_get_be24(&buf);
         remaining_buf_size -= 3;
         if (remaining_buf_size < alpha_offset)
-            return -1;
+            return AVERROR_INVALIDDATA;
     }
 
     res = s->parse_header(s, buf, remaining_buf_size);
@@ -528,8 +528,9 @@
         }
     }
 
-    if (ff_get_buffer(avctx, p, AV_GET_BUFFER_FLAG_REF) < 0)
-        return -1;
+    ret = ff_get_buffer(avctx, p, AV_GET_BUFFER_FLAG_REF);
+    if (ret < 0)
+        return ret;
 
     if (avctx->pix_fmt == AV_PIX_FMT_YUVA420P) {
         av_frame_unref(s->alpha_context->frames[VP56_FRAME_CURRENT]);
@@ -542,7 +543,7 @@
     if (res == VP56_SIZE_CHANGE) {
         if (vp56_size_changed(s)) {
             av_frame_unref(p);
-            return -1;
+            return AVERROR_INVALIDDATA;
         }
     }
 
@@ -564,7 +565,7 @@
                 avctx->coded_height = bak_ch;
             }
             av_frame_unref(p);
-            return -1;
+            return AVERROR_INVALIDDATA;
         }
     }
 
@@ -700,7 +701,7 @@
     ff_vp3dsp_init(&s->vp3dsp, avctx->flags);
     ff_vp56dsp_init(&s->vp56dsp, avctx->codec->id);
     for (i = 0; i < 64; i++) {
-#define TRANSPOSE(x) (x >> 3) | ((x & 7) << 3)
+#define TRANSPOSE(x) (((x) >> 3) | (((x) & 7) << 3))
         s->idct_scantable[i] = TRANSPOSE(ff_zigzag_direct[i]);
 #undef TRANSPOSE
     }
diff --git a/libavcodec/vp8.c b/libavcodec/vp8.c
index 465666a..354a33e 100644
--- a/libavcodec/vp8.c
+++ b/libavcodec/vp8.c
@@ -1615,7 +1615,7 @@
             for (x = 0; x < 4; x++) {
                 int copy = 0, linesize = s->linesize;
                 uint8_t *dst = ptr + 4 * x;
-                DECLARE_ALIGNED(4, uint8_t, copy_dst)[5 * 8];
+                LOCAL_ALIGNED(4, uint8_t, copy_dst, [5 * 8]);
 
                 if ((y == 0 || x == 3) && mb_y == 0) {
                     topright = tr_top;
@@ -1721,8 +1721,8 @@
     if (AV_RN32A(mv)) {
         int src_linesize = linesize;
 
-        int mx = (mv->x << 1) & 7, mx_idx = subpel_idx[0][mx];
-        int my = (mv->y << 1) & 7, my_idx = subpel_idx[0][my];
+        int mx = (mv->x * 2) & 7, mx_idx = subpel_idx[0][mx];
+        int my = (mv->y * 2) & 7, my_idx = subpel_idx[0][my];
 
         x_off += mv->x >> 2;
         y_off += mv->y >> 2;
diff --git a/libavcodec/vp9.c b/libavcodec/vp9.c
index 2bb2432..89257fa 100644
--- a/libavcodec/vp9.c
+++ b/libavcodec/vp9.c
@@ -74,6 +74,7 @@
     AVBufferRef *extradata;
     uint8_t *segmentation_map;
     struct VP9mvrefPair *mv;
+    int uses_2pass;
 } VP9Frame;
 
 struct VP9Filter {
@@ -100,7 +101,7 @@
     VP56RangeCoder *c_b;
     unsigned c_b_size;
     VP9Block *b_base, *b;
-    int pass, uses_2pass, last_uses_2pass;
+    int pass;
     int row, row7, col, col7;
     uint8_t *dst[3];
     ptrdiff_t y_stride, uv_stride;
@@ -128,8 +129,9 @@
     uint8_t varcompref[2];
     ThreadFrame refs[8], next_refs[8];
 #define CUR_FRAME 0
-#define LAST_FRAME 1
-    VP9Frame frames[2];
+#define REF_FRAME_MVPAIR 1
+#define REF_FRAME_SEGMAP 2
+    VP9Frame frames[3];
 
     struct {
         uint8_t level;
@@ -277,12 +279,6 @@
     f->segmentation_map = f->extradata->data;
     f->mv = (struct VP9mvrefPair *) (f->extradata->data + sz);
 
-    // retain segmentation map if it doesn't update
-    if (s->segmentation.enabled && !s->segmentation.update_map &&
-        !s->intraonly && !s->keyframe && !s->errorres) {
-        memcpy(f->segmentation_map, s->frames[LAST_FRAME].segmentation_map, sz);
-    }
-
     return 0;
 }
 
@@ -305,6 +301,7 @@
 
     dst->segmentation_map = src->segmentation_map;
     dst->mv = src->mv;
+    dst->uses_2pass = src->uses_2pass;
 
     return 0;
 }
@@ -361,12 +358,12 @@
 {
     VP9Context *s = ctx->priv_data;
 
-    if (s->b_base && s->block_base && s->block_alloc_using_2pass == s->uses_2pass)
+    if (s->b_base && s->block_base && s->block_alloc_using_2pass == s->frames[CUR_FRAME].uses_2pass)
         return 0;
 
     av_free(s->b_base);
     av_free(s->block_base);
-    if (s->uses_2pass) {
+    if (s->frames[CUR_FRAME].uses_2pass) {
         int sbs = s->sb_cols * s->sb_rows;
 
         s->b_base = av_malloc_array(s->cols * s->rows, sizeof(VP9Block));
@@ -389,7 +386,7 @@
         s->uveob_base[0] = s->eob_base + 256;
         s->uveob_base[1] = s->uveob_base[0] + 64;
     }
-    s->block_alloc_using_2pass = s->uses_2pass;
+    s->block_alloc_using_2pass = s->frames[CUR_FRAME].uses_2pass;
 
     return 0;
 }
@@ -490,7 +487,6 @@
         *ref = get_bits(&s->gb, 3);
         return 0;
     }
-    s->last_uses_2pass = s->uses_2pass;
     s->last_keyframe  = s->keyframe;
     s->keyframe       = !get_bits1(&s->gb);
     last_invisible    = s->invisible;
@@ -693,10 +689,10 @@
         for (j = 1; j < 4; j++) {
             s->segmentation.feat[i].lflvl[j][0] =
                 av_clip_uintp2(lflvl + ((s->lf_delta.ref[j] +
-                                         s->lf_delta.mode[0]) << sh), 6);
+                                         s->lf_delta.mode[0]) * (1 << sh)), 6);
             s->segmentation.feat[i].lflvl[j][1] =
                 av_clip_uintp2(lflvl + ((s->lf_delta.ref[j] +
-                                         s->lf_delta.mode[1]) << sh), 6);
+                                         s->lf_delta.mode[1]) * (1 << sh)), 6);
         }
     }
 
@@ -1081,10 +1077,10 @@
 
     // MV at this position in previous frame, using same reference frame
     if (s->use_last_frame_mvs) {
-        struct VP9mvrefPair *mv = &s->frames[LAST_FRAME].mv[row * s->sb_cols * 8 + col];
+        struct VP9mvrefPair *mv = &s->frames[REF_FRAME_MVPAIR].mv[row * s->sb_cols * 8 + col];
 
-        if (!s->last_uses_2pass)
-            ff_thread_await_progress(&s->frames[LAST_FRAME].tf, row >> 3, 0);
+        if (!s->frames[REF_FRAME_MVPAIR].uses_2pass)
+            ff_thread_await_progress(&s->frames[REF_FRAME_MVPAIR].tf, row >> 3, 0);
         if (mv->ref[0] == ref) {
             RETURN_MV(mv->mv[0]);
         } else if (mv->ref[1] == ref) {
@@ -1123,7 +1119,7 @@
 
     // MV at this position in previous frame, using different reference frame
     if (s->use_last_frame_mvs) {
-        struct VP9mvrefPair *mv = &s->frames[LAST_FRAME].mv[row * s->sb_cols * 8 + col];
+        struct VP9mvrefPair *mv = &s->frames[REF_FRAME_MVPAIR].mv[row * s->sb_cols * 8 + col];
 
         // no need to await_progress, because we already did that above
         if (mv->ref[0] != ref && mv->ref[0] >= 0) {
@@ -1347,13 +1343,15 @@
                                     s->left_segpred_ctx[row7]]))) {
         if (!s->errorres) {
             int pred = 8, x;
-            uint8_t *refsegmap = s->frames[LAST_FRAME].segmentation_map;
+            uint8_t *refsegmap = s->frames[REF_FRAME_SEGMAP].segmentation_map;
 
-            if (!s->last_uses_2pass)
-                ff_thread_await_progress(&s->frames[LAST_FRAME].tf, row >> 3, 0);
-            for (y = 0; y < h4; y++)
+            if (!s->frames[REF_FRAME_SEGMAP].uses_2pass)
+                ff_thread_await_progress(&s->frames[REF_FRAME_SEGMAP].tf, row >> 3, 0);
+            for (y = 0; y < h4; y++) {
+                int idx_base = (y + row) * 8 * s->sb_cols + col;
                 for (x = 0; x < w4; x++)
-                    pred = FFMIN(pred, refsegmap[(y + row) * 8 * s->sb_cols + x + col]);
+                    pred = FFMIN(pred, refsegmap[idx_base + x]);
+            }
             av_assert1(pred < 8);
             b->seg_id = pred;
         } else {
@@ -2508,7 +2506,7 @@
             for (x = 0; x < end_x; x += uvstep1d, ptr += 4 * uvstep1d,
                                    ptr_r += 4 * uvstep1d, n += step) {
                 int mode = b->uvmode;
-                uint8_t *a = &a_buf[16];
+                uint8_t *a = &a_buf[32];
                 int eob = b->skip ? 0 : b->uvtx > TX_8X8 ? AV_RN16A(&s->uveob[p][n]) : s->uveob[p][n];
 
                 mode = check_intra_mode(s, mode, &a, ptr_r,
@@ -3719,7 +3717,7 @@
     VP9Context *s = ctx->priv_data;
     int i;
 
-    for (i = 0; i < 2; i++) {
+    for (i = 0; i < 3; i++) {
         if (s->frames[i].tf.f->data[0])
             vp9_unref_frame(ctx, &s->frames[i]);
         av_frame_free(&s->frames[i].tf.f);
@@ -3747,6 +3745,7 @@
     int size = pkt->size;
     VP9Context *s = ctx->priv_data;
     int res, tile_row, tile_col, i, ref, row, col;
+    int retain_segmap_ref = s->segmentation.enabled && !s->segmentation.update_map;
     ptrdiff_t yoff, uvoff, ls_y, ls_uv;
     AVFrame *f;
 
@@ -3760,15 +3759,22 @@
         if ((res = av_frame_ref(frame, s->refs[ref].f)) < 0)
             return res;
         *got_frame = 1;
-        return 0;
+        return pkt->size;
     }
     data += res;
     size -= res;
 
-    if (s->frames[LAST_FRAME].tf.f->data[0])
-        vp9_unref_frame(ctx, &s->frames[LAST_FRAME]);
-    if (!s->keyframe && s->frames[CUR_FRAME].tf.f->data[0] &&
-        (res = vp9_ref_frame(ctx, &s->frames[LAST_FRAME], &s->frames[CUR_FRAME])) < 0)
+    if (!retain_segmap_ref) {
+        if (s->frames[REF_FRAME_SEGMAP].tf.f->data[0])
+            vp9_unref_frame(ctx, &s->frames[REF_FRAME_SEGMAP]);
+        if (!s->keyframe && !s->intraonly && !s->errorres && s->frames[CUR_FRAME].tf.f->data[0] &&
+            (res = vp9_ref_frame(ctx, &s->frames[REF_FRAME_SEGMAP], &s->frames[CUR_FRAME])) < 0)
+            return res;
+    }
+    if (s->frames[REF_FRAME_MVPAIR].tf.f->data[0])
+        vp9_unref_frame(ctx, &s->frames[REF_FRAME_MVPAIR]);
+    if (!s->intraonly && !s->keyframe && !s->errorres && s->frames[CUR_FRAME].tf.f->data[0] &&
+        (res = vp9_ref_frame(ctx, &s->frames[REF_FRAME_MVPAIR], &s->frames[CUR_FRAME])) < 0)
         return res;
     if (s->frames[CUR_FRAME].tf.f->data[0])
         vp9_unref_frame(ctx, &s->frames[CUR_FRAME]);
@@ -3817,7 +3823,7 @@
     memset(s->above_uv_nnz_ctx[0], 0, s->sb_cols * 8);
     memset(s->above_uv_nnz_ctx[1], 0, s->sb_cols * 8);
     memset(s->above_segpred_ctx, 0, s->cols);
-    s->pass = s->uses_2pass =
+    s->pass = s->frames[CUR_FRAME].uses_2pass =
         ctx->active_thread_type == FF_THREAD_FRAME && s->refreshctx && !s->parallelmode;
     if ((res = update_block_buffers(ctx)) < 0) {
         av_log(ctx, AV_LOG_ERROR,
@@ -3984,7 +3990,7 @@
         *got_frame = 1;
     }
 
-    return 0;
+    return pkt->size;
 }
 
 static void vp9_decode_flush(AVCodecContext *ctx)
@@ -3992,7 +3998,7 @@
     VP9Context *s = ctx->priv_data;
     int i;
 
-    for (i = 0; i < 2; i++)
+    for (i = 0; i < 3; i++)
         vp9_unref_frame(ctx, &s->frames[i]);
     for (i = 0; i < 8; i++)
         ff_thread_release_buffer(ctx, &s->refs[i]);
@@ -4003,7 +4009,7 @@
     VP9Context *s = ctx->priv_data;
     int i;
 
-    for (i = 0; i < 2; i++) {
+    for (i = 0; i < 3; i++) {
         s->frames[i].tf.f = av_frame_alloc();
         if (!s->frames[i].tf.f) {
             vp9_decode_free(ctx);
@@ -4053,7 +4059,7 @@
         free_buffers(s);
     }
 
-    for (i = 0; i < 2; i++) {
+    for (i = 0; i < 3; i++) {
         if (s->frames[i].tf.f->data[0])
             vp9_unref_frame(dst, &s->frames[i]);
         if (ssrc->frames[i].tf.f->data[0]) {
@@ -4072,7 +4078,8 @@
 
     s->invisible = ssrc->invisible;
     s->keyframe = ssrc->keyframe;
-    s->uses_2pass = ssrc->uses_2pass;
+    s->segmentation.enabled = ssrc->segmentation.enabled;
+    s->segmentation.update_map = ssrc->segmentation.update_map;
     memcpy(&s->prob_ctx, &ssrc->prob_ctx, sizeof(s->prob_ctx));
     memcpy(&s->lf_delta, &ssrc->lf_delta, sizeof(s->lf_delta));
     if (ssrc->segmentation.enabled) {
diff --git a/libavcodec/vp9_parser.c b/libavcodec/vp9_parser.c
index b188785..220290f 100644
--- a/libavcodec/vp9_parser.c
+++ b/libavcodec/vp9_parser.c
@@ -24,10 +24,13 @@
 typedef struct VP9ParseContext {
     int n_frames; // 1-8
     int size[8];
+    int64_t pts;
 } VP9ParseContext;
 
 static void parse_frame(AVCodecParserContext *ctx, const uint8_t *buf, int size)
 {
+    VP9ParseContext *s = ctx->priv_data;
+
     if (buf[0] & 0x4) {
         ctx->pict_type = AV_PICTURE_TYPE_P;
         ctx->key_frame = 0;
@@ -35,6 +38,15 @@
         ctx->pict_type = AV_PICTURE_TYPE_I;
         ctx->key_frame = 1;
     }
+
+    if (buf[0] & 0x2) {
+        if (ctx->pts == AV_NOPTS_VALUE)
+            ctx->pts = s->pts;
+        s->pts = AV_NOPTS_VALUE;
+    } else {
+        s->pts = ctx->pts;
+        ctx->pts = AV_NOPTS_VALUE;
+    }
 }
 
 static int parse(AVCodecParserContext *ctx,
diff --git a/libavcodec/wavpack.h b/libavcodec/wavpack.h
index 6cb49a1..a1b46d5 100644
--- a/libavcodec/wavpack.h
+++ b/libavcodec/wavpack.h
@@ -104,15 +104,15 @@
 
 // macros for applying weight
 #define UPDATE_WEIGHT_CLIP(weight, delta, samples, in) \
-    if (samples && in) { \
-        if ((samples ^ in) < 0) { \
-            weight -= delta; \
-            if (weight < -1024) \
-                weight = -1024; \
+    if ((samples) && (in)) { \
+        if (((samples) ^ (in)) < 0) { \
+            (weight) -= (delta); \
+            if ((weight) < -1024) \
+                (weight) = -1024; \
         } else { \
-            weight += delta; \
-            if (weight > 1024) \
-                weight = 1024; \
+            (weight) += (delta); \
+            if ((weight) > 1024) \
+                (weight) = 1024; \
         } \
     }
 
diff --git a/libavcodec/wavpackenc.c b/libavcodec/wavpackenc.c
index 63971c6..c174950 100644
--- a/libavcodec/wavpackenc.c
+++ b/libavcodec/wavpackenc.c
@@ -640,9 +640,9 @@
         dbits = nbits_table[v];
         *result += (dbits << 8) + wp_log2_table[(v << (9 - dbits)) & 0xff];
     } else {
-        if (v < (1L << 16))
+        if (v < (1 << 16))
             dbits = nbits_table[v >> 8] + 8;
-        else if (v < (1L << 24))
+        else if (v < (1 << 24))
             dbits = nbits_table[v >> 16] + 16;
         else
             dbits = nbits_table[v >> 24] + 24;
@@ -1967,8 +1967,8 @@
 #define count_bits(av) ( \
  (av) < (1 << 8) ? nbits_table[av] : \
   ( \
-   (av) < (1L << 16) ? nbits_table[(av) >> 8] + 8 : \
-   ((av) < (1L << 24) ? nbits_table[(av) >> 16] + 16 : nbits_table[(av) >> 24] + 24) \
+   (av) < (1 << 16) ? nbits_table[(av) >> 8] + 8 : \
+   ((av) < (1 << 24) ? nbits_table[(av) >> 16] + 16 : nbits_table[(av) >> 24] + 24) \
   ) \
 )
 
diff --git a/libavcodec/webp.c b/libavcodec/webp.c
index 4b1c8e7..47e9e9e 100644
--- a/libavcodec/webp.c
+++ b/libavcodec/webp.c
@@ -694,6 +694,11 @@
                 length = offset + get_bits(&s->gb, extra_bits) + 1;
             }
             prefix_code = huff_reader_get_symbol(&hg[HUFF_IDX_DIST], &s->gb);
+            if (prefix_code > 39) {
+                av_log(s->avctx, AV_LOG_ERROR,
+                       "distance prefix code too large: %d\n", prefix_code);
+                return AVERROR_INVALIDDATA;
+            }
             if (prefix_code < 4) {
                 distance = prefix_code + 1;
             } else {
@@ -1099,14 +1104,14 @@
                                      unsigned int data_size, int is_alpha_chunk)
 {
     WebPContext *s = avctx->priv_data;
-    int w, h, ret, i;
+    int w, h, ret, i, used;
 
     if (!is_alpha_chunk) {
         s->lossless = 1;
         avctx->pix_fmt = AV_PIX_FMT_ARGB;
     }
 
-    ret = init_get_bits(&s->gb, data_start, data_size * 8);
+    ret = init_get_bits8(&s->gb, data_start, data_size);
     if (ret < 0)
         return ret;
 
@@ -1149,8 +1154,16 @@
     /* parse transformations */
     s->nb_transforms = 0;
     s->reduced_width = 0;
+    used = 0;
     while (get_bits1(&s->gb)) {
         enum TransformType transform = get_bits(&s->gb, 2);
+        if (used & (1 << transform)) {
+            av_log(avctx, AV_LOG_ERROR, "Transform %d used more than once\n",
+                   transform);
+            ret = AVERROR_INVALIDDATA;
+            goto free_and_return;
+        }
+        used |= (1 << transform);
         s->transforms[s->nb_transforms++] = transform;
         switch (transform) {
         case PREDICTOR_TRANSFORM:
diff --git a/libavcodec/wma.c b/libavcodec/wma.c
index fa5c887..99a87f6 100644
--- a/libavcodec/wma.c
+++ b/libavcodec/wma.c
@@ -28,9 +28,6 @@
 #include "wma_freqs.h"
 #include "wmadata.h"
 
-#undef NDEBUG
-#include <assert.h>
-
 /* XXX: use same run/length optimization as mpeg decoders */
 // FIXME maybe split decode / encode or pass flag
 static av_cold int init_coef_vlc(VLC *vlc, uint16_t **prun_table,
@@ -94,7 +91,6 @@
         avctx->bit_rate    <= 0)
         return -1;
 
-    ff_fmt_convert_init(&s->fmt_conv, avctx);
 
     if (avctx->codec->id == AV_CODEC_ID_WMAV1)
         s->version = 1;
@@ -455,7 +451,7 @@
             /** normal code */
             offset                  += run_table[code];
             sign                     = get_bits1(gb) - 1;
-            iptr[offset & coef_mask] = ilvl[code] ^ sign << 31;
+            iptr[offset & coef_mask] = ilvl[code] ^ (sign & 0x80000000);
         } else if (code == 1) {
             /** EOB */
             break;
diff --git a/libavcodec/wma.h b/libavcodec/wma.h
index 8d337df..cc9d6f9 100644
--- a/libavcodec/wma.h
+++ b/libavcodec/wma.h
@@ -24,8 +24,8 @@
 
 #include "libavutil/float_dsp.h"
 
+#include "avcodec.h"
 #include "fft.h"
-#include "fmtconvert.h"
 #include "get_bits.h"
 #include "put_bits.h"
 
@@ -131,7 +131,6 @@
     float lsp_pow_e_table[256];
     float lsp_pow_m_table1[(1 << LSP_POW_BITS)];
     float lsp_pow_m_table2[(1 << LSP_POW_BITS)];
-    FmtConvertContext fmt_conv;
     AVFloatDSPContext *fdsp;
 
 #ifdef TRACE
diff --git a/libavcodec/wmadec.c b/libavcodec/wmadec.c
index 79e7b0c..ffbf511 100644
--- a/libavcodec/wmadec.c
+++ b/libavcodec/wmadec.c
@@ -39,9 +39,6 @@
 #include "internal.h"
 #include "wma.h"
 
-#undef NDEBUG
-#include <assert.h>
-
 #define EXPVLCBITS 8
 #define EXPMAX     ((19 + EXPVLCBITS - 1) / EXPVLCBITS)
 
@@ -700,7 +697,7 @@
 
                 /* very high freqs : noise */
                 n     = s->block_len - s->coefs_end[bsize];
-                mult1 = mult * exponents[((-1 << bsize)) >> esize];
+                mult1 = mult * exponents[(-(1 << bsize)) >> esize];
                 for (i = 0; i < n; i++) {
                     *coefs++       = s->noise_table[s->noise_index] * mult1;
                     s->noise_index = (s->noise_index + 1) & (NOISE_TAB_SIZE - 1);
diff --git a/libavcodec/wmaenc.c b/libavcodec/wmaenc.c
index 08d45e9..b922acd 100644
--- a/libavcodec/wmaenc.c
+++ b/libavcodec/wmaenc.c
@@ -60,11 +60,15 @@
     flags2 = 1;
     if (avctx->codec->id == AV_CODEC_ID_WMAV1) {
         extradata             = av_malloc(4);
+        if (!extradata)
+            return AVERROR(ENOMEM);
         avctx->extradata_size = 4;
         AV_WL16(extradata, flags1);
         AV_WL16(extradata + 2, flags2);
     } else if (avctx->codec->id == AV_CODEC_ID_WMAV2) {
         extradata             = av_mallocz(10);
+        if (!extradata)
+            return AVERROR(ENOMEM);
         avctx->extradata_size = 10;
         AV_WL32(extradata, flags1);
         AV_WL16(extradata + 4, flags2);
diff --git a/libavcodec/wmalosslessdec.c b/libavcodec/wmalosslessdec.c
index e6e3476..fcadbc0 100644
--- a/libavcodec/wmalosslessdec.c
+++ b/libavcodec/wmalosslessdec.c
@@ -52,7 +52,7 @@
 /**
  * @brief frame-specific decoder context for a single channel
  */
-typedef struct {
+typedef struct WmallChannelCtx {
     int16_t     prev_block_len;                         ///< length of the previous block
     uint8_t     transmit_coefs;
     uint8_t     num_subframes;
@@ -127,7 +127,7 @@
 
     int8_t  acfilter_order;
     int8_t  acfilter_scaling;
-    int64_t acfilter_coeffs[16];
+    int16_t acfilter_coeffs[16];
     int     acfilter_prevvalues[WMALL_MAX_CHANNELS][16];
 
     int8_t  mclms_order;
@@ -147,8 +147,8 @@
         int coefsend;
         int bitsend;
         DECLARE_ALIGNED(16, int16_t, coefs)[MAX_ORDER + WMALL_COEFF_PAD_SIZE/sizeof(int16_t)];
-        DECLARE_ALIGNED(16, int16_t, lms_prevvalues)[MAX_ORDER * 2];
-        DECLARE_ALIGNED(16, int16_t, lms_updates)[MAX_ORDER * 2];
+        DECLARE_ALIGNED(16, int16_t, lms_prevvalues)[MAX_ORDER * 2 + WMALL_COEFF_PAD_SIZE/sizeof(int16_t)];
+        DECLARE_ALIGNED(16, int16_t, lms_updates)[MAX_ORDER * 2 + WMALL_COEFF_PAD_SIZE/sizeof(int16_t)];
         int recent;
     } cdlms[WMALL_MAX_CHANNELS][9];
 
@@ -175,6 +175,8 @@
     int channel_coeffs[WMALL_MAX_CHANNELS][WMALL_BLOCK_MAX_SIZE];
 } WmallDecodeCtx;
 
+/** Get sign of integer (1 for positive, -1 for negative and 0 for zero) */
+#define WMASIGN(x) (((x) > 0) - ((x) < 0))
 
 static av_cold int decode_init(AVCodecContext *avctx)
 {
@@ -551,10 +553,7 @@
         s->ave_sum[ch] = residue + s->ave_sum[ch] -
                          (s->ave_sum[ch] >> s->movave_scaling);
 
-        if (residue & 1)
-            residue = -(residue >> 1) - 1;
-        else
-            residue = residue >> 1;
+        residue = (residue >> 1) ^ -(residue & 1);
         s->channel_residues[ch][i] = residue;
     }
 
@@ -631,38 +630,22 @@
             for (i = 0; i < order * num_channels; i++)
                 s->mclms_coeffs[i + ich * order * num_channels] +=
                     s->mclms_updates[s->mclms_recent + i];
-            for (j = 0; j < ich; j++) {
-                if (s->channel_residues[j][icoef] > 0)
-                    s->mclms_coeffs_cur[ich * num_channels + j] += 1;
-                else if (s->channel_residues[j][icoef] < 0)
-                    s->mclms_coeffs_cur[ich * num_channels + j] -= 1;
-            }
+            for (j = 0; j < ich; j++)
+                s->mclms_coeffs_cur[ich * num_channels + j] += WMASIGN(s->channel_residues[j][icoef]);
         } else if (pred_error < 0) {
             for (i = 0; i < order * num_channels; i++)
                 s->mclms_coeffs[i + ich * order * num_channels] -=
                     s->mclms_updates[s->mclms_recent + i];
-            for (j = 0; j < ich; j++) {
-                if (s->channel_residues[j][icoef] > 0)
-                    s->mclms_coeffs_cur[ich * num_channels + j] -= 1;
-                else if (s->channel_residues[j][icoef] < 0)
-                    s->mclms_coeffs_cur[ich * num_channels + j] += 1;
-            }
+            for (j = 0; j < ich; j++)
+                s->mclms_coeffs_cur[ich * num_channels + j] -= WMASIGN(s->channel_residues[j][icoef]);
         }
     }
 
     for (ich = num_channels - 1; ich >= 0; ich--) {
         s->mclms_recent--;
-        s->mclms_prevvalues[s->mclms_recent] = s->channel_residues[ich][icoef];
-        if (s->channel_residues[ich][icoef] > range - 1)
-            s->mclms_prevvalues[s->mclms_recent] = range - 1;
-        else if (s->channel_residues[ich][icoef] < -range)
-            s->mclms_prevvalues[s->mclms_recent] = -range;
-
-        s->mclms_updates[s->mclms_recent] = 0;
-        if (s->channel_residues[ich][icoef] > 0)
-            s->mclms_updates[s->mclms_recent] = 1;
-        else if (s->channel_residues[ich][icoef] < 0)
-            s->mclms_updates[s->mclms_recent] = -1;
+        s->mclms_prevvalues[s->mclms_recent] = av_clip(s->channel_residues[ich][icoef],
+            -range, range - 1);
+        s->mclms_updates[s->mclms_recent] = WMASIGN(s->channel_residues[ich][icoef]);
     }
 
     if (s->mclms_recent == 0) {
@@ -711,30 +694,26 @@
 {
     int recent = s->cdlms[ich][ilms].recent;
     int range  = 1 << s->bits_per_sample - 1;
+    int order  = s->cdlms[ich][ilms].order;
 
     if (recent)
         recent--;
     else {
-        memcpy(&s->cdlms[ich][ilms].lms_prevvalues[s->cdlms[ich][ilms].order],
-               s->cdlms[ich][ilms].lms_prevvalues,
-               2 * s->cdlms[ich][ilms].order);
-        memcpy(&s->cdlms[ich][ilms].lms_updates[s->cdlms[ich][ilms].order],
-               s->cdlms[ich][ilms].lms_updates,
-               2 * s->cdlms[ich][ilms].order);
-        recent = s->cdlms[ich][ilms].order - 1;
+        memcpy(s->cdlms[ich][ilms].lms_prevvalues + order,
+               s->cdlms[ich][ilms].lms_prevvalues, sizeof(*s->cdlms[ich][ilms].lms_prevvalues) * order);
+        memcpy(s->cdlms[ich][ilms].lms_updates + order,
+               s->cdlms[ich][ilms].lms_updates, sizeof(*s->cdlms[ich][ilms].lms_updates) * order);
+        recent = order - 1;
     }
 
     s->cdlms[ich][ilms].lms_prevvalues[recent] = av_clip(input, -range, range - 1);
-    if (!input)
-        s->cdlms[ich][ilms].lms_updates[recent] = 0;
-    else if (input < 0)
-        s->cdlms[ich][ilms].lms_updates[recent] = -s->update_speed[ich];
-    else
-        s->cdlms[ich][ilms].lms_updates[recent] = s->update_speed[ich];
+    s->cdlms[ich][ilms].lms_updates[recent] = WMASIGN(input) * s->update_speed[ich];
 
-    s->cdlms[ich][ilms].lms_updates[recent + (s->cdlms[ich][ilms].order >> 4)] >>= 2;
-    s->cdlms[ich][ilms].lms_updates[recent + (s->cdlms[ich][ilms].order >> 3)] >>= 1;
+    s->cdlms[ich][ilms].lms_updates[recent + (order >> 4)] >>= 2;
+    s->cdlms[ich][ilms].lms_updates[recent + (order >> 3)] >>= 1;
     s->cdlms[ich][ilms].recent = recent;
+    memset(s->cdlms[ich][ilms].lms_updates + recent + order, 0,
+           sizeof(s->cdlms[ich][ilms].lms_updates) - 2*(recent+order));
 }
 
 static void use_high_update_speed(WmallDecodeCtx *s, int ich)
@@ -772,9 +751,6 @@
     s->update_speed[ich] = 8;
 }
 
-/** Get sign of integer (1 for positive, -1 for negative and 0 for zero) */
-#define WMASIGN(x) ((x > 0) - (x < 0))
-
 static void revert_cdlms(WmallDecodeCtx *s, int ch,
                          int coef_begin, int coef_end)
 {
@@ -790,7 +766,8 @@
                                                             + s->cdlms[ch][ilms].recent,
                                                         s->cdlms[ch][ilms].lms_updates
                                                             + s->cdlms[ch][ilms].recent,
-                                                        s->cdlms[ch][ilms].order,
+                                                        FFALIGN(s->cdlms[ch][ilms].order,
+                                                                WMALL_COEFF_PAD_SIZE),
                                                         WMASIGN(residue));
             input = residue + (pred >> s->cdlms[ch][ilms].scaling);
             lms_update(s, ch, ilms, input);
@@ -816,7 +793,7 @@
 static void revert_acfilter(WmallDecodeCtx *s, int tile_size)
 {
     int ich, pred, i, j;
-    int64_t *filter_coeffs = s->acfilter_coeffs;
+    int16_t *filter_coeffs = s->acfilter_coeffs;
     int scaling            = s->acfilter_scaling;
     int order              = s->acfilter_order;
 
@@ -1089,8 +1066,7 @@
 
     av_dlog(s->avctx, "Frame done\n");
 
-    if (s->skip_frame)
-        s->skip_frame = 0;
+    s->skip_frame = 0;
 
     if (s->len_prefix) {
         if (len != (get_bits_count(gb) - s->frame_offset) + 2) {
diff --git a/libavcodec/wmaprodec.c b/libavcodec/wmaprodec.c
index cc7ad0d..3b7a812 100644
--- a/libavcodec/wmaprodec.c
+++ b/libavcodec/wmaprodec.c
@@ -132,7 +132,7 @@
 /**
  * @brief frame specific decoder context for a single channel
  */
-typedef struct {
+typedef struct WMAProChannelCtx {
     int16_t  prev_block_len;                          ///< length of the previous block
     uint8_t  transmit_coefs;
     uint8_t  num_subframes;
@@ -157,7 +157,7 @@
 /**
  * @brief channel group for channel transformations
  */
-typedef struct {
+typedef struct WMAProChannelGrp {
     uint8_t num_channels;                                     ///< number of channels in the group
     int8_t  transform;                                        ///< transform on / off
     int8_t  transform_band[MAX_BANDS];                        ///< controls if the transform is enabled for a certain band
diff --git a/libavcodec/wmavoice.c b/libavcodec/wmavoice.c
index c2737ab..ae88d4e 100644
--- a/libavcodec/wmavoice.c
+++ b/libavcodec/wmavoice.c
@@ -129,7 +129,7 @@
 /**
  * WMA Voice decoding context.
  */
-typedef struct {
+typedef struct WMAVoiceContext {
     /**
      * @name Global values specified in the stream header / extradata or used all over.
      * @{
diff --git a/libavcodec/wmv2.h b/libavcodec/wmv2.h
index cb5b14e..4fa5e9b 100644
--- a/libavcodec/wmv2.h
+++ b/libavcodec/wmv2.h
@@ -56,4 +56,15 @@
 
 void ff_wmv2_common_init(Wmv2Context *w);
 
+static av_always_inline int wmv2_get_cbp_table_index(MpegEncContext *s, int cbp_index)
+{
+    static const uint8_t map[3][3] = {
+        { 0, 2, 1 },
+        { 1, 0, 2 },
+        { 2, 1, 0 },
+    };
+
+    return map[(s->qscale > 10) + (s->qscale > 20)][cbp_index];
+}
+
 #endif /* AVCODEC_WMV2_H */
diff --git a/libavcodec/wmv2dec.c b/libavcodec/wmv2dec.c
index d9cbfd1..bb14d56 100644
--- a/libavcodec/wmv2dec.c
+++ b/libavcodec/wmv2dec.c
@@ -86,7 +86,7 @@
     int code;
 
     if (s->avctx->extradata_size < 4)
-        return -1;
+        return AVERROR_INVALIDDATA;
 
     init_get_bits(&gb, s->avctx->extradata, 32);
 
@@ -101,7 +101,7 @@
     code                = get_bits(&gb, 3);
 
     if (code == 0)
-        return -1;
+        return AVERROR_INVALIDDATA;
 
     s->slice_height = s->mb_height / code;
 
@@ -131,7 +131,7 @@
     }
     s->chroma_qscale = s->qscale = get_bits(&s->gb, 5);
     if (s->qscale <= 0)
-        return -1;
+        return AVERROR_INVALIDDATA;
 
     return 0;
 }
@@ -173,16 +173,7 @@
 
         parse_mb_skip(w);
         cbp_index = decode012(&s->gb);
-        if (s->qscale <= 10) {
-            int map[3]         = { 0, 2, 1 };
-            w->cbp_table_index = map[cbp_index];
-        } else if (s->qscale <= 20) {
-            int map[3]         = { 1, 0, 2 };
-            w->cbp_table_index = map[cbp_index];
-        } else {
-            int map[3]         = {2,1,0};
-            w->cbp_table_index = map[cbp_index];
-        }
+        w->cbp_table_index = wmv2_get_cbp_table_index(s, cbp_index);
 
         if (w->mspel_bit)
             s->mspel = get_bits1(&s->gb);
@@ -242,7 +233,7 @@
     ret = ff_msmpeg4_decode_motion(s, mx_ptr, my_ptr);
 
     if (ret < 0)
-        return -1;
+        return ret;
 
     if ((((*mx_ptr) | (*my_ptr)) & 1) && s->mspel)
         w->hshift = get_bits1(&s->gb);
@@ -302,7 +293,7 @@
 {
     MpegEncContext *const s = &w->s;
     static const int sub_cbp_table[3] = { 2, 3, 1 };
-    int sub_cbp;
+    int sub_cbp, ret;
 
     if (!cbp) {
         s->block_last_index[n] = -1;
@@ -321,12 +312,12 @@
         sub_cbp = sub_cbp_table[decode012(&s->gb)];
 
         if (sub_cbp & 1)
-            if (ff_msmpeg4_decode_block(s, block, n, 1, scantable) < 0)
-                return -1;
+            if ((ret = ff_msmpeg4_decode_block(s, block, n, 1, scantable)) < 0)
+                return ret;
 
         if (sub_cbp & 2)
-            if (ff_msmpeg4_decode_block(s, w->abt_block2[n], n, 1, scantable) < 0)
-                return -1;
+            if ((ret = ff_msmpeg4_decode_block(s, w->abt_block2[n], n, 1, scantable)) < 0)
+                return ret;
 
         s->block_last_index[n] = 63;
 
@@ -340,7 +331,7 @@
 int ff_wmv2_decode_mb(MpegEncContext *s, int16_t block[6][64])
 {
     Wmv2Context *const w = (Wmv2Context *) s;
-    int cbp, code, i;
+    int cbp, code, i, ret;
     uint8_t *coded_val;
 
     if (w->j_type)
@@ -364,7 +355,7 @@
         code = get_vlc2(&s->gb, ff_mb_non_intra_vlc[w->cbp_table_index].table,
                         MB_NON_INTRA_VLC_BITS, 3);
         if (code < 0)
-            return -1;
+            return AVERROR_INVALIDDATA;
         s->mb_intra = (~code & 0x40) >> 6;
 
         cbp = code & 0x3f;
@@ -374,7 +365,7 @@
         if (code < 0) {
             av_log(s->avctx, AV_LOG_ERROR,
                    "II-cbp illegal at %d %d\n", s->mb_x, s->mb_y);
-            return -1;
+            return AVERROR_INVALIDDATA;
         }
         /* predict coded block pattern */
         cbp = 0;
@@ -408,8 +399,8 @@
                 w->per_block_abt = 0;
         }
 
-        if (wmv2_decode_motion(w, &mx, &my) < 0)
-            return -1;
+        if ((ret = wmv2_decode_motion(w, &mx, &my)) < 0)
+            return ret;
 
         s->mv_dir      = MV_DIR_FORWARD;
         s->mv_type     = MV_TYPE_16X16;
@@ -417,11 +408,11 @@
         s->mv[0][0][1] = my;
 
         for (i = 0; i < 6; i++) {
-            if (wmv2_decode_inter_block(w, block[i], i, (cbp >> (5 - i)) & 1) < 0) {
+            if ((ret = wmv2_decode_inter_block(w, block[i], i, (cbp >> (5 - i)) & 1)) < 0) {
                 av_log(s->avctx, AV_LOG_ERROR,
                        "\nerror while decoding inter block: %d x %d (%d)\n",
                        s->mb_x, s->mb_y, i);
-                return -1;
+                return ret;
             }
         }
     } else {
@@ -444,11 +435,11 @@
 
         s->bdsp.clear_blocks(s->block[0]);
         for (i = 0; i < 6; i++) {
-            if (ff_msmpeg4_decode_block(s, block[i], i, (cbp >> (5 - i)) & 1, NULL) < 0) {
+            if ((ret = ff_msmpeg4_decode_block(s, block[i], i, (cbp >> (5 - i)) & 1, NULL)) < 0) {
                 av_log(s->avctx, AV_LOG_ERROR,
                        "\nerror while decoding intra block: %d x %d (%d)\n",
                        s->mb_x, s->mb_y, i);
-                return -1;
+                return ret;
             }
         }
     }
@@ -459,11 +450,12 @@
 static av_cold int wmv2_decode_init(AVCodecContext *avctx)
 {
     Wmv2Context *const w = avctx->priv_data;
+    int ret;
 
     avctx->flags |= CODEC_FLAG_EMU_EDGE;
 
-    if (ff_msmpeg4_decode_init(avctx) < 0)
-        return -1;
+    if ((ret = ff_msmpeg4_decode_init(avctx)) < 0)
+        return ret;
 
     ff_wmv2_common_init(w);
 
diff --git a/libavcodec/wmv2enc.c b/libavcodec/wmv2enc.c
index 62e99c0..55ee089 100644
--- a/libavcodec/wmv2enc.c
+++ b/libavcodec/wmv2enc.c
@@ -111,16 +111,7 @@
         put_bits(&s->pb, 2, SKIP_TYPE_NONE);
 
         ff_msmpeg4_code012(&s->pb, cbp_index = 0);
-        if (s->qscale <= 10) {
-            int map[3]         = { 0, 2, 1 };
-            w->cbp_table_index = map[cbp_index];
-        } else if (s->qscale <= 20) {
-            int map[3]         = { 1, 0, 2 };
-            w->cbp_table_index = map[cbp_index];
-        } else {
-            int map[3]         = { 2, 1, 0 };
-            w->cbp_table_index = map[cbp_index];
-        }
+        w->cbp_table_index = wmv2_get_cbp_table_index(s, cbp_index);
 
         if (w->mspel_bit)
             put_bits(&s->pb, 1, s->mspel);
diff --git a/libavcodec/wnv1.c b/libavcodec/wnv1.c
index 99aee3c..fb9e9cf 100644
--- a/libavcodec/wnv1.c
+++ b/libavcodec/wnv1.c
@@ -88,7 +88,9 @@
 
     for (i = 8; i < buf_size; i++)
         rbuf[i] = ff_reverse[buf[i]];
-    init_get_bits(&l->gb, rbuf + 8, (buf_size - 8) * 8);
+
+    if ((ret = init_get_bits8(&l->gb, rbuf + 8, buf_size - 8)) < 0)
+        return ret;
 
     if (buf[2] >> 4 == 6)
         l->shift = 2;
diff --git a/libavcodec/x86/Makefile b/libavcodec/x86/Makefile
index 7c8e7aa..87985f2 100644
--- a/libavcodec/x86/Makefile
+++ b/libavcodec/x86/Makefile
@@ -1,5 +1,4 @@
 OBJS                                   += x86/constants.o               \
-                                          x86/fmtconvert_init.o         \
 
 # subsystems
 OBJS-$(CONFIG_AC3DSP)                  += x86/ac3dsp_init.o
@@ -11,6 +10,7 @@
 OBJS-$(CONFIG_FFT)                     += x86/fft_init.o
 OBJS-$(CONFIG_FLAC_DECODER)            += x86/flacdsp_init.o
 OBJS-$(CONFIG_FLAC_ENCODER)            += x86/flacdsp_init.o
+OBJS-$(CONFIG_FMTCONVERT)              += x86/fmtconvert_init.o
 OBJS-$(CONFIG_H263DSP)                 += x86/h263dsp_init.o
 OBJS-$(CONFIG_H264CHROMA)              += x86/h264chroma_init.o
 OBJS-$(CONFIG_H264DSP)                 += x86/h264dsp_init.o
@@ -37,6 +37,8 @@
 
 # decoders/encoders
 OBJS-$(CONFIG_AAC_DECODER)             += x86/sbrdsp_init.o
+OBJS-$(CONFIG_ADPCM_G722_DECODER)      += x86/g722dsp_init.o
+OBJS-$(CONFIG_ADPCM_G722_ENCODER)      += x86/g722dsp_init.o
 OBJS-$(CONFIG_APNG_DECODER)            += x86/pngdsp_init.o
 OBJS-$(CONFIG_CAVS_DECODER)            += x86/cavsdsp.o
 OBJS-$(CONFIG_DCA_DECODER)             += x86/dcadsp_init.o
@@ -71,8 +73,6 @@
 MMX-OBJS-$(CONFIG_IDCTDSP)             += x86/simple_idct.o
 
 # decoders/encoders
-MMX-OBJS-$(CONFIG_MPEG4_DECODER)       += x86/xvididct_mmx.o            \
-                                          x86/xvididct_sse2.o
 MMX-OBJS-$(CONFIG_SNOW_DECODER)        += x86/snowdsp.o
 MMX-OBJS-$(CONFIG_SNOW_ENCODER)        += x86/snowdsp.o
 MMX-OBJS-$(CONFIG_VC1_DECODER)         += x86/vc1dsp_mmx.o
@@ -80,7 +80,6 @@
 
 # YASM optimizations
 YASM-OBJS                              += x86/deinterlace.o             \
-                                          x86/fmtconvert.o              \
 
 # subsystems
 YASM-OBJS-$(CONFIG_AC3DSP)             += x86/ac3dsp.o
@@ -96,6 +95,7 @@
 ifdef CONFIG_GPL
 YASM-OBJS-$(CONFIG_FLAC_ENCODER)       += x86/flac_dsp_gpl.o
 endif
+YASM-OBJS-$(CONFIG_FMTCONVERT)         += x86/fmtconvert.o
 YASM-OBJS-$(CONFIG_H263DSP)            += x86/h263_loopfilter.o
 YASM-OBJS-$(CONFIG_H264CHROMA)         += x86/h264_chromamc.o           \
                                           x86/h264_chromamc_10bit.o
@@ -129,13 +129,17 @@
 
 # decoders/encoders
 YASM-OBJS-$(CONFIG_AAC_DECODER)        += x86/sbrdsp.o
+YASM-OBJS-$(CONFIG_ADPCM_G722_DECODER) += x86/g722dsp.o
+YASM-OBJS-$(CONFIG_ADPCM_G722_ENCODER) += x86/g722dsp.o
 YASM-OBJS-$(CONFIG_APNG_DECODER)       += x86/pngdsp.o
 YASM-OBJS-$(CONFIG_DCA_DECODER)        += x86/dcadsp.o
 YASM-OBJS-$(CONFIG_HEVC_DECODER)       += x86/hevc_mc.o                 \
                                           x86/hevc_deblock.o            \
                                           x86/hevc_idct.o               \
-                                          x86/hevc_res_add.o
+                                          x86/hevc_res_add.o            \
+                                          x86/hevc_sao.o
 YASM-OBJS-$(CONFIG_MLP_DECODER)        += x86/mlpdsp.o
+YASM-OBJS-$(CONFIG_MPEG4_DECODER)      += x86/xvididct.o
 YASM-OBJS-$(CONFIG_PNG_DECODER)        += x86/pngdsp.o
 YASM-OBJS-$(CONFIG_PRORES_DECODER)     += x86/proresdsp.o
 YASM-OBJS-$(CONFIG_PRORES_LGPL_DECODER) += x86/proresdsp.o
diff --git a/libavcodec/x86/ac3dsp.asm b/libavcodec/x86/ac3dsp.asm
index b244416..675ade3 100644
--- a/libavcodec/x86/ac3dsp.asm
+++ b/libavcodec/x86/ac3dsp.asm
@@ -32,7 +32,7 @@
 pw_bap_mul2: dw 5, 7, 0, 7, 5, 7, 0, 7
 
 ; used in ff_ac3_extract_exponents()
-pd_1:   times 4 dd 1
+cextern pd_1
 pd_151: times 4 dd 151
 
 ; used in ff_apply_window_int16()
diff --git a/libavcodec/x86/ac3dsp_init.c b/libavcodec/x86/ac3dsp_init.c
index 30a85f9..eea2736 100644
--- a/libavcodec/x86/ac3dsp_init.c
+++ b/libavcodec/x86/ac3dsp_init.c
@@ -165,7 +165,7 @@
                matrix_cmp[3][0] == matrix_cmp[4][0]) {
         MIX5(IF1, IF0);
     } else {
-        DECLARE_ALIGNED(16, float, matrix_simd)[AC3_MAX_CHANNELS][2][4];
+        LOCAL_ALIGNED(16, float, matrix_simd, [AC3_MAX_CHANNELS], [2][4]);
         float *samp[AC3_MAX_CHANNELS];
 
         for (j = 0; j < in_ch; j++)
diff --git a/libavcodec/x86/cavsdsp.c b/libavcodec/x86/cavsdsp.c
index 190f6ee..2ac3bb5 100644
--- a/libavcodec/x86/cavsdsp.c
+++ b/libavcodec/x86/cavsdsp.c
@@ -139,11 +139,9 @@
 static void cavs_idct8_add_mmx(uint8_t *dst, int16_t *block, int stride)
 {
     int i;
-    DECLARE_ALIGNED(16, int16_t, b2)[64];
+    LOCAL_ALIGNED(16, int16_t, b2, [64]);
 
     for(i=0; i<2; i++){
-        DECLARE_ALIGNED(8, uint64_t, tmp);
-
         cavs_idct8_1d(block+4*i, ff_pw_4.a);
 
         __asm__ volatile(
@@ -155,19 +153,19 @@
             "psraw     $3, %%mm2  \n\t"
             "psraw     $3, %%mm1  \n\t"
             "psraw     $3, %%mm0  \n\t"
-            "movq   %%mm7,    %0   \n\t"
+            "movq   %%mm7,   (%0) \n\t"
             TRANSPOSE4( %%mm0, %%mm2, %%mm4, %%mm6, %%mm7 )
-            "movq   %%mm0,  8(%1)  \n\t"
-            "movq   %%mm6, 24(%1)  \n\t"
-            "movq   %%mm7, 40(%1)  \n\t"
-            "movq   %%mm4, 56(%1)  \n\t"
-            "movq    %0,    %%mm7  \n\t"
+            "movq   %%mm0,  8(%0)  \n\t"
+            "movq   %%mm6, 24(%0)  \n\t"
+            "movq   %%mm7, 40(%0)  \n\t"
+            "movq   %%mm4, 56(%0)  \n\t"
+            "movq    (%0),  %%mm7  \n\t"
             TRANSPOSE4( %%mm7, %%mm5, %%mm3, %%mm1, %%mm0 )
-            "movq   %%mm7,   (%1)  \n\t"
-            "movq   %%mm1, 16(%1)  \n\t"
-            "movq   %%mm0, 32(%1)  \n\t"
-            "movq   %%mm3, 48(%1)  \n\t"
-            : "=m"(tmp)
+            "movq   %%mm7,   (%0)  \n\t"
+            "movq   %%mm1, 16(%0)  \n\t"
+            "movq   %%mm0, 32(%0)  \n\t"
+            "movq   %%mm3, 48(%0)  \n\t"
+            :
             : "r"(b2+32*i)
             : "memory"
         );
diff --git a/libavcodec/x86/constants.c b/libavcodec/x86/constants.c
index 54acc89..553dd49 100644
--- a/libavcodec/x86/constants.c
+++ b/libavcodec/x86/constants.c
@@ -22,8 +22,10 @@
 #include "libavutil/x86/asm.h" // for xmm_reg
 #include "constants.h"
 
-DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_1)    = { 0x0001000100010001ULL, 0x0001000100010001ULL };
-DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_2)    = { 0x0002000200020002ULL, 0x0002000200020002ULL };
+DECLARE_ALIGNED(32, const ymm_reg,  ff_pw_1)    = { 0x0001000100010001ULL, 0x0001000100010001ULL,
+                                                    0x0001000100010001ULL, 0x0001000100010001ULL };
+DECLARE_ALIGNED(32, const ymm_reg,  ff_pw_2)    = { 0x0002000200020002ULL, 0x0002000200020002ULL,
+                                                    0x0002000200020002ULL, 0x0002000200020002ULL };
 DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_3)    = { 0x0003000300030003ULL, 0x0003000300030003ULL };
 DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_4)    = { 0x0004000400040004ULL, 0x0004000400040004ULL };
 DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_5)    = { 0x0005000500050005ULL, 0x0005000500050005ULL };
@@ -33,29 +35,47 @@
 DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_16)   = { 0x0010001000100010ULL, 0x0010001000100010ULL };
 DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_17)   = { 0x0011001100110011ULL, 0x0011001100110011ULL };
 DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_18)   = { 0x0012001200120012ULL, 0x0012001200120012ULL };
-DECLARE_ALIGNED(8,  const uint64_t, ff_pw_20)   =   0x0014001400140014ULL;
+DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_20)   = { 0x0014001400140014ULL, 0x0014001400140014ULL };
 DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_32)   = { 0x0020002000200020ULL, 0x0020002000200020ULL };
 DECLARE_ALIGNED(8,  const uint64_t, ff_pw_42)   =   0x002A002A002A002AULL;
 DECLARE_ALIGNED(8,  const uint64_t, ff_pw_53)   =   0x0035003500350035ULL;
 DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_64)   = { 0x0040004000400040ULL, 0x0040004000400040ULL };
 DECLARE_ALIGNED(8,  const uint64_t, ff_pw_96)   =   0x0060006000600060ULL;
 DECLARE_ALIGNED(8,  const uint64_t, ff_pw_128)  =   0x0080008000800080ULL;
-DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_255)  = { 0x00ff00ff00ff00ffULL, 0x00ff00ff00ff00ffULL };
+DECLARE_ALIGNED(32, const ymm_reg,  ff_pw_255)  = { 0x00ff00ff00ff00ffULL, 0x00ff00ff00ff00ffULL,
+                                                    0x00ff00ff00ff00ffULL, 0x00ff00ff00ff00ffULL };
 DECLARE_ALIGNED(32, const ymm_reg,  ff_pw_256)  = { 0x0100010001000100ULL, 0x0100010001000100ULL,
                                                     0x0100010001000100ULL, 0x0100010001000100ULL };
-DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_512)  = { 0x0200020002000200ULL, 0x0200020002000200ULL };
+DECLARE_ALIGNED(32, const ymm_reg,  ff_pw_512)  = { 0x0200020002000200ULL, 0x0200020002000200ULL,
+                                                    0x0200020002000200ULL, 0x0200020002000200ULL };
 DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_1019) = { 0x03FB03FB03FB03FBULL, 0x03FB03FB03FB03FBULL };
-DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_1024) = { 0x0400040004000400ULL, 0x0400040004000400ULL };
-DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_2048) = { 0x0800080008000800ULL, 0x0800080008000800ULL };
-DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_8192) = { 0x2000200020002000ULL, 0x2000200020002000ULL };
-DECLARE_ALIGNED(16, const xmm_reg,  ff_pw_m1)   = { 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL };
+DECLARE_ALIGNED(32, const ymm_reg,  ff_pw_1023) = { 0x03ff03ff03ff03ffULL, 0x03ff03ff03ff03ffULL,
+                                                    0x03ff03ff03ff03ffULL, 0x03ff03ff03ff03ffULL};
+DECLARE_ALIGNED(32, const ymm_reg,  ff_pw_1024) = { 0x0400040004000400ULL, 0x0400040004000400ULL,
+                                                    0x0400040004000400ULL, 0x0400040004000400ULL};
+DECLARE_ALIGNED(32, const ymm_reg,  ff_pw_2048) = { 0x0800080008000800ULL, 0x0800080008000800ULL,
+                                                    0x0800080008000800ULL, 0x0800080008000800ULL };
+DECLARE_ALIGNED(32, const ymm_reg,  ff_pw_4096) = { 0x1000100010001000ULL, 0x1000100010001000ULL,
+                                                    0x1000100010001000ULL, 0x1000100010001000ULL };
+DECLARE_ALIGNED(32, const ymm_reg,  ff_pw_8192) = { 0x2000200020002000ULL, 0x2000200020002000ULL,
+                                                    0x2000200020002000ULL, 0x2000200020002000ULL };
+DECLARE_ALIGNED(32, const ymm_reg,  ff_pw_m1)   = { 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL,
+                                                    0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL };
 
-DECLARE_ALIGNED(16, const xmm_reg,  ff_pb_0)    = { 0x0000000000000000ULL, 0x0000000000000000ULL };
+DECLARE_ALIGNED(32, const ymm_reg,  ff_pb_0)    = { 0x0000000000000000ULL, 0x0000000000000000ULL,
+                                                    0x0000000000000000ULL, 0x0000000000000000ULL };
 DECLARE_ALIGNED(32, const ymm_reg,  ff_pb_1)    = { 0x0101010101010101ULL, 0x0101010101010101ULL,
                                                     0x0101010101010101ULL, 0x0101010101010101ULL };
+DECLARE_ALIGNED(32, const ymm_reg,  ff_pb_2)    = { 0x0202020202020202ULL, 0x0202020202020202ULL,
+                                                    0x0202020202020202ULL, 0x0202020202020202ULL };
 DECLARE_ALIGNED(32, const ymm_reg,  ff_pb_3)    = { 0x0303030303030303ULL, 0x0303030303030303ULL,
                                                     0x0303030303030303ULL, 0x0303030303030303ULL };
+DECLARE_ALIGNED(32, const xmm_reg,  ff_pb_15)   = { 0x0F0F0F0F0F0F0F0FULL, 0x0F0F0F0F0F0F0F0FULL };
 DECLARE_ALIGNED(16, const xmm_reg,  ff_pb_80)   = { 0x8080808080808080ULL, 0x8080808080808080ULL };
+DECLARE_ALIGNED(16, const xmm_reg,  ff_pb_FE)   = { 0xFEFEFEFEFEFEFEFEULL, 0xFEFEFEFEFEFEFEFEULL };
 DECLARE_ALIGNED(8,  const uint64_t, ff_pb_FC)   =   0xFCFCFCFCFCFCFCFCULL;
 
 DECLARE_ALIGNED(16, const xmm_reg,  ff_ps_neg)  = { 0x8000000080000000ULL, 0x8000000080000000ULL };
+
+DECLARE_ALIGNED(32, const ymm_reg,  ff_pd_1)    = { 0x0000000100000001ULL, 0x0000000100000001ULL,
+                                                    0x0000000100000001ULL, 0x0000000100000001ULL };
diff --git a/libavcodec/x86/constants.h b/libavcodec/x86/constants.h
index 1c24dda3..33dbb65 100644
--- a/libavcodec/x86/constants.h
+++ b/libavcodec/x86/constants.h
@@ -25,8 +25,8 @@
 
 #include "libavutil/x86/asm.h"
 
-extern const xmm_reg  ff_pw_1;
-extern const xmm_reg  ff_pw_2;
+extern const ymm_reg  ff_pw_1;
+extern const ymm_reg  ff_pw_2;
 extern const xmm_reg  ff_pw_3;
 extern const xmm_reg  ff_pw_4;
 extern const xmm_reg  ff_pw_5;
@@ -35,26 +35,32 @@
 extern const uint64_t ff_pw_15;
 extern const xmm_reg  ff_pw_16;
 extern const xmm_reg  ff_pw_18;
-extern const uint64_t ff_pw_20;
+extern const xmm_reg  ff_pw_20;
 extern const xmm_reg  ff_pw_32;
 extern const uint64_t ff_pw_42;
 extern const uint64_t ff_pw_53;
 extern const xmm_reg  ff_pw_64;
 extern const uint64_t ff_pw_96;
 extern const uint64_t ff_pw_128;
-extern const xmm_reg  ff_pw_255;
-extern const xmm_reg  ff_pw_512;
-extern const xmm_reg  ff_pw_1024;
-extern const xmm_reg  ff_pw_2048;
-extern const xmm_reg  ff_pw_8192;
-extern const xmm_reg  ff_pw_m1;
+extern const ymm_reg  ff_pw_255;
+extern const ymm_reg  ff_pw_512;
+extern const ymm_reg  ff_pw_1023;
+extern const ymm_reg  ff_pw_1024;
+extern const ymm_reg  ff_pw_2048;
+extern const ymm_reg  ff_pw_4096;
+extern const ymm_reg  ff_pw_8192;
+extern const ymm_reg  ff_pw_m1;
 
+extern const ymm_reg  ff_pb_0;
 extern const ymm_reg  ff_pb_1;
+extern const ymm_reg  ff_pb_2;
 extern const ymm_reg  ff_pb_3;
 extern const xmm_reg  ff_pb_80;
-extern const xmm_reg  ff_pb_F8;
+extern const xmm_reg  ff_pb_FE;
 extern const uint64_t ff_pb_FC;
 
 extern const xmm_reg  ff_ps_neg;
 
+extern const ymm_reg  ff_pd_1;
+
 #endif /* AVCODEC_X86_CONSTANTS_H */
diff --git a/libavcodec/x86/dct-test.c b/libavcodec/x86/dct-test.c
index 3414cb0..193a69e 100644
--- a/libavcodec/x86/dct-test.c
+++ b/libavcodec/x86/dct-test.c
@@ -22,25 +22,35 @@
 #include "xvididct.h"
 #include "simple_idct.h"
 
-#if ARCH_X86_64 && HAVE_MMX && HAVE_YASM
+#if (CONFIG_PRORES_DECODER || CONFIG_PRORES_LGPL_DECODER) && ARCH_X86_64 && HAVE_YASM
 void ff_prores_idct_put_10_sse2(uint16_t *dst, int linesize,
                                 int16_t *block, int16_t *qmat);
 
-static void ff_prores_idct_put_10_sse2_wrap(int16_t *dst){
-    DECLARE_ALIGNED(16, static int16_t, qmat)[64];
-    DECLARE_ALIGNED(16, static int16_t, tmp)[64];
-    int i;
-
-    for(i=0; i<64; i++){
-        qmat[i]=4;
-        tmp[i]= dst[i];
-    }
-    ff_prores_idct_put_10_sse2(dst, 16, tmp, qmat);
-
-    for(i=0; i<64; i++) {
-         dst[i] -= 512;
-    }
+#define PR_WRAP(INSN) \
+static void ff_prores_idct_put_10_##INSN##_wrap(int16_t *dst){ \
+    LOCAL_ALIGNED(16, int16_t, qmat, [64]); \
+    LOCAL_ALIGNED(16, int16_t, tmp, [64]); \
+    int i; \
+ \
+    for(i=0; i<64; i++){ \
+        qmat[i]=4; \
+        tmp[i]= dst[i]; \
+    } \
+    ff_prores_idct_put_10_##INSN (dst, 16, tmp, qmat); \
+ \
+    for(i=0; i<64; i++) { \
+         dst[i] -= 512; \
+    } \
 }
+
+PR_WRAP(sse2)
+
+# if HAVE_AVX_EXTERNAL
+void ff_prores_idct_put_10_avx(uint16_t *dst, int linesize,
+                               int16_t *block, int16_t *qmat);
+PR_WRAP(avx)
+# endif
+
 #endif
 
 static const struct algo fdct_tab_arch[] = {
@@ -60,20 +70,21 @@
 #if HAVE_MMX_INLINE
     { "SIMPLE-MMX",  ff_simple_idct_mmx,  FF_IDCT_PERM_SIMPLE, AV_CPU_FLAG_MMX },
 #endif
-#if CONFIG_MPEG4_DECODER
-#if HAVE_MMX_INLINE
+#if CONFIG_MPEG4_DECODER && HAVE_YASM
+#if ARCH_X86_32
     { "XVID-MMX",    ff_xvid_idct_mmx,    FF_IDCT_PERM_NONE,   AV_CPU_FLAG_MMX,    1 },
-#endif
-#if HAVE_MMXEXT_INLINE
     { "XVID-MMXEXT", ff_xvid_idct_mmxext, FF_IDCT_PERM_NONE,   AV_CPU_FLAG_MMXEXT, 1 },
 #endif
-#if HAVE_SSE2_INLINE
+#if HAVE_SSE2_EXTERNAL
     { "XVID-SSE2",   ff_xvid_idct_sse2,   FF_IDCT_PERM_SSE2,   AV_CPU_FLAG_SSE2,   1 },
-#if ARCH_X86_64 && HAVE_YASM
+#endif
+#endif /* CONFIG_MPEG4_DECODER && HAVE_YASM */
+#if (CONFIG_PRORES_DECODER || CONFIG_PRORES_LGPL_DECODER) && ARCH_X86_64 && HAVE_YASM
     { "PR-SSE2",     ff_prores_idct_put_10_sse2_wrap, FF_IDCT_PERM_TRANSPOSE, AV_CPU_FLAG_SSE2, 1 },
+# if HAVE_AVX_EXTERNAL
+    { "PR-AVX",      ff_prores_idct_put_10_avx_wrap, FF_IDCT_PERM_TRANSPOSE, AV_CPU_FLAG_AVX, 1 },
+# endif
 #endif
-#endif
-#endif /* CONFIG_MPEG4_DECODER */
     { 0 }
 };
 
diff --git a/libavcodec/x86/fmtconvert.asm b/libavcodec/x86/fmtconvert.asm
index 19595f7..f4fc0c2 100644
--- a/libavcodec/x86/fmtconvert.asm
+++ b/libavcodec/x86/fmtconvert.asm
@@ -23,14 +23,6 @@
 
 SECTION_TEXT
 
-%macro CVTPS2PI 2
-%if cpuflag(sse)
-    cvtps2pi %1, %2
-%elif cpuflag(3dnow)
-    pf2id %1, %2
-%endif
-%endmacro
-
 ;------------------------------------------------------------------------------
 ; void ff_int32_to_float_fmul_scalar(float *dst, const int32_t *src, float mul,
 ;                                    int len);
@@ -116,355 +108,3 @@
 INIT_XMM sse2
 INT32_TO_FLOAT_FMUL_ARRAY8
 
-;------------------------------------------------------------------------------
-; void ff_float_to_int16(int16_t *dst, const float *src, long 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:
-%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]
-    packssdw    m0, m1
-    packssdw    m2, m3
-    mova  [dstq+lenq  ], m0
-    mova  [dstq+lenq+8], m2
-%endif
-    add       lenq, 16
-    js .loop
-%if mmsize == 8
-    emms
-%endif
-    REP_RET
-%endmacro
-
-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 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:
-%if cpuflag(sse2)
-    cvtps2dq    m0, [srcq+2*lenq   ]
-    cvtps2dq    m1, [srcq+2*lenq+16]
-    packssdw    m0, m1
-    movd       v1d, m0
-    psrldq      m0, 4
-    movd       v2d, m0
-    psrldq      m0, 4
-    mov     [dstq], v1w
-    mov  [dstq+stepq*4], v2w
-    shr        v1d, 16
-    shr        v2d, 16
-    mov  [dstq+stepq*2], v1w
-    mov  [dstq+step3q*2], v2w
-    lea       dstq, [dstq+stepq*8]
-    movd       v1d, m0
-    psrldq      m0, 4
-    movd       v2d, m0
-    mov     [dstq], v1w
-    mov  [dstq+stepq*4], v2w
-    shr        v1d, 16
-    shr        v2d, 16
-    mov  [dstq+stepq*2], v1w
-    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]
-    packssdw    m0, m1
-    packssdw    m2, m3
-    movd       v1d, m0
-    psrlq       m0, 32
-    movd       v2d, m0
-    mov     [dstq], v1w
-    mov  [dstq+stepq*4], v2w
-    shr        v1d, 16
-    shr        v2d, 16
-    mov  [dstq+stepq*2], v1w
-    mov  [dstq+step3q*2], v2w
-    lea       dstq, [dstq+stepq*8]
-    movd       v1d, m2
-    psrlq       m2, 32
-    movd       v2d, m2
-    mov     [dstq], v1w
-    mov  [dstq+stepq*4], v2w
-    shr        v1d, 16
-    shr        v2d, 16
-    mov  [dstq+stepq*2], v1w
-    mov  [dstq+step3q*2], v2w
-    lea       dstq, [dstq+stepq*8]
-%endif
-    add       lenq, 16
-    js .loop
-%if mmsize == 8
-    emms
-%endif
-    REP_RET
-%endmacro
-
-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 0
-cglobal float_to_int16_interleave2, 3, 4, 2, dst, src0, src1, len
-    lea      lenq, [4*r2q]
-    mov     src1q, [src0q+gprsize]
-    mov     src0q, [src0q]
-    add      dstq, lenq
-    add     src0q, lenq
-    add     src1q, lenq
-    neg      lenq
-.loop:
-%if cpuflag(sse2)
-    cvtps2dq   m0, [src0q+lenq]
-    cvtps2dq   m1, [src1q+lenq]
-    packssdw   m0, m1
-    movhlps    m1, m0
-    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]
-    packssdw   m0, m1
-    packssdw   m2, m3
-    mova       m1, m0
-    punpcklwd  m0, m2
-    punpckhwd  m1, m2
-    mova  [dstq+lenq  ], m0
-    mova  [dstq+lenq+8], m1
-%endif
-    add      lenq, 16
-    js .loop
-%if mmsize == 8
-    emms
-%endif
-    REP_RET
-%endmacro
-
-INIT_MMX 3dnow
-FLOAT_TO_INT16_INTERLEAVE2
-INIT_MMX sse
-FLOAT_TO_INT16_INTERLEAVE2
-INIT_XMM sse2
-FLOAT_TO_INT16_INTERLEAVE2
-
-;-----------------------------------------------------------------------------
-; void ff_float_to_int16_interleave6(int16_t *dst, const float **src, int len)
-;-----------------------------------------------------------------------------
-%macro FLOAT_TO_INT16_INTERLEAVE6 0
-cglobal float_to_int16_interleave6, 2, 8, 0, dst, src, src1, src2, src3, src4, src5, len
-%if ARCH_X86_64
-    mov     lend, r2d
-%else
-    %define lend dword r2m
-%endif
-    mov src1q, [srcq+1*gprsize]
-    mov src2q, [srcq+2*gprsize]
-    mov src3q, [srcq+3*gprsize]
-    mov src4q, [srcq+4*gprsize]
-    mov src5q, [srcq+5*gprsize]
-    mov srcq,  [srcq]
-    sub src1q, srcq
-    sub src2q, srcq
-    sub src3q, srcq
-    sub src4q, srcq
-    sub src5q, srcq
-.loop:
-    CVTPS2PI   mm0, [srcq]
-    CVTPS2PI   mm1, [srcq+src1q]
-    CVTPS2PI   mm2, [srcq+src2q]
-    CVTPS2PI   mm3, [srcq+src3q]
-    CVTPS2PI   mm4, [srcq+src4q]
-    CVTPS2PI   mm5, [srcq+src5q]
-    packssdw   mm0, mm3
-    packssdw   mm1, mm4
-    packssdw   mm2, mm5
-    PSWAPD     mm3, mm0
-    punpcklwd  mm0, mm1
-    punpckhwd  mm1, mm2
-    punpcklwd  mm2, mm3
-    PSWAPD     mm3, mm0
-    punpckldq  mm0, mm2
-    punpckhdq  mm2, mm1
-    punpckldq  mm1, mm3
-    movq [dstq   ], mm0
-    movq [dstq+16], mm2
-    movq [dstq+ 8], mm1
-    add srcq, 8
-    add dstq, 24
-    sub lend, 2
-    jg .loop
-    emms
-    RET
-%endmacro ; FLOAT_TO_INT16_INTERLEAVE6
-
-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 1
-cglobal float_interleave6, 2, 8, %1, dst, src, src1, src2, src3, src4, src5, len
-%if ARCH_X86_64
-    mov     lend, r2d
-%else
-    %define lend dword r2m
-%endif
-    mov    src1q, [srcq+1*gprsize]
-    mov    src2q, [srcq+2*gprsize]
-    mov    src3q, [srcq+3*gprsize]
-    mov    src4q, [srcq+4*gprsize]
-    mov    src5q, [srcq+5*gprsize]
-    mov     srcq, [srcq]
-    sub    src1q, srcq
-    sub    src2q, srcq
-    sub    src3q, srcq
-    sub    src4q, srcq
-    sub    src5q, srcq
-.loop:
-%if cpuflag(sse)
-    movaps    m0, [srcq]
-    movaps    m1, [srcq+src1q]
-    movaps    m2, [srcq+src2q]
-    movaps    m3, [srcq+src3q]
-    movaps    m4, [srcq+src4q]
-    movaps    m5, [srcq+src5q]
-
-    SBUTTERFLYPS 0, 1, 6
-    SBUTTERFLYPS 2, 3, 6
-    SBUTTERFLYPS 4, 5, 6
-
-    movaps    m6, m4
-    shufps    m4, m0, 0xe4
-    movlhps   m0, m2
-    movhlps   m6, m2
-    movaps [dstq   ], m0
-    movaps [dstq+16], m4
-    movaps [dstq+32], m6
-
-    movaps    m6, m5
-    shufps    m5, m1, 0xe4
-    movlhps   m1, m3
-    movhlps   m6, m3
-    movaps [dstq+48], m1
-    movaps [dstq+64], m5
-    movaps [dstq+80], m6
-%else ; mmx
-    movq       m0, [srcq]
-    movq       m1, [srcq+src1q]
-    movq       m2, [srcq+src2q]
-    movq       m3, [srcq+src3q]
-    movq       m4, [srcq+src4q]
-    movq       m5, [srcq+src5q]
-
-    SBUTTERFLY dq, 0, 1, 6
-    SBUTTERFLY dq, 2, 3, 6
-    SBUTTERFLY dq, 4, 5, 6
-    movq [dstq   ], m0
-    movq [dstq+ 8], m2
-    movq [dstq+16], m4
-    movq [dstq+24], m1
-    movq [dstq+32], m3
-    movq [dstq+40], m5
-%endif
-    add      srcq, mmsize
-    add      dstq, mmsize*6
-    sub      lend, mmsize/4
-    jg .loop
-%if mmsize == 8
-    emms
-%endif
-    REP_RET
-%endmacro
-
-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 1
-cglobal float_interleave2, 3, 4, %1, dst, src, len, src1
-    mov     src1q, [srcq+gprsize]
-    mov      srcq, [srcq        ]
-    sub     src1q, srcq
-.loop:
-    mova       m0, [srcq             ]
-    mova       m1, [srcq+src1q       ]
-    mova       m3, [srcq      +mmsize]
-    mova       m4, [srcq+src1q+mmsize]
-
-    mova       m2, m0
-    PUNPCKLDQ  m0, m1
-    PUNPCKHDQ  m2, m1
-
-    mova       m1, m3
-    PUNPCKLDQ  m3, m4
-    PUNPCKHDQ  m1, m4
-
-    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
-%if mmsize == 8
-    emms
-%endif
-    REP_RET
-%endmacro
-
-INIT_MMX mmx
-%define PUNPCKLDQ punpckldq
-%define PUNPCKHDQ punpckhdq
-FLOAT_INTERLEAVE2 0
-INIT_XMM sse
-%define PUNPCKLDQ unpcklps
-%define PUNPCKHDQ unpckhps
-FLOAT_INTERLEAVE2 5
diff --git a/libavcodec/x86/fmtconvert_init.c b/libavcodec/x86/fmtconvert_init.c
index cbb96e2..e4cbadc 100644
--- a/libavcodec/x86/fmtconvert_init.c
+++ b/libavcodec/x86/fmtconvert_init.c
@@ -37,84 +37,6 @@
 void ff_int32_to_float_fmul_array8_sse2(FmtConvertContext *c, float *dst, const int32_t *src,
                                         const float *mul, int len);
 
-void ff_float_to_int16_3dnow(int16_t *dst, const float *src, long len);
-void ff_float_to_int16_sse  (int16_t *dst, const float *src, long len);
-void ff_float_to_int16_sse2 (int16_t *dst, const float *src, long len);
-
-void ff_float_to_int16_step_3dnow(int16_t *dst, const float *src, long len, long step);
-void ff_float_to_int16_step_sse  (int16_t *dst, const float *src, long len, long step);
-void ff_float_to_int16_step_sse2 (int16_t *dst, const float *src, long len, long step);
-
-void ff_float_to_int16_interleave2_3dnow(int16_t *dst, const float **src, long len);
-void ff_float_to_int16_interleave2_sse  (int16_t *dst, const float **src, long len);
-void ff_float_to_int16_interleave2_sse2 (int16_t *dst, const float **src, long len);
-
-void ff_float_to_int16_interleave6_sse(int16_t *dst, const float **src, int len);
-void ff_float_to_int16_interleave6_3dnow(int16_t *dst, const float **src, int len);
-void ff_float_to_int16_interleave6_3dnowext(int16_t *dst, const float **src, int len);
-
-#define ff_float_to_int16_interleave6_sse2 ff_float_to_int16_interleave6_sse
-
-#define FLOAT_TO_INT16_INTERLEAVE(cpu) \
-/* gcc pessimizes register allocation if this is in the same function as float_to_int16_interleave_sse2*/\
-static av_noinline void float_to_int16_interleave_misc_##cpu(int16_t *dst, const float **src, long len, int channels){\
-    int c;\
-    for(c=0; c<channels; c++){\
-        ff_float_to_int16_step_##cpu(dst+c, src[c], len, channels);\
-    }\
-}\
-\
-static void float_to_int16_interleave_##cpu(int16_t *dst, const float **src, long len, int channels){\
-    if(channels==1)\
-        ff_float_to_int16_##cpu(dst, src[0], len);\
-    else if(channels==2){\
-        ff_float_to_int16_interleave2_##cpu(dst, src, len);\
-    }else if(channels==6){\
-        ff_float_to_int16_interleave6_##cpu(dst, src, len);\
-    }else\
-        float_to_int16_interleave_misc_##cpu(dst, src, len, channels);\
-}
-
-FLOAT_TO_INT16_INTERLEAVE(3dnow)
-FLOAT_TO_INT16_INTERLEAVE(sse)
-FLOAT_TO_INT16_INTERLEAVE(sse2)
-
-static void float_to_int16_interleave_3dnowext(int16_t *dst, const float **src,
-                                               long len, int channels)
-{
-    if(channels==6)
-        ff_float_to_int16_interleave6_3dnowext(dst, src, len);
-    else
-        float_to_int16_interleave_3dnow(dst, src, len, channels);
-}
-
-void ff_float_interleave2_mmx(float *dst, const float **src, unsigned int len);
-void ff_float_interleave2_sse(float *dst, const float **src, unsigned int len);
-
-void ff_float_interleave6_mmx(float *dst, const float **src, unsigned int len);
-void ff_float_interleave6_sse(float *dst, const float **src, unsigned int len);
-
-static void float_interleave_mmx(float *dst, const float **src,
-                                 unsigned int len, int channels)
-{
-    if (channels == 2) {
-        ff_float_interleave2_mmx(dst, src, len);
-    } else if (channels == 6)
-        ff_float_interleave6_mmx(dst, src, len);
-    else
-        ff_float_interleave_c(dst, src, len, channels);
-}
-
-static void float_interleave_sse(float *dst, const float **src,
-                                 unsigned int len, int channels)
-{
-    if (channels == 2) {
-        ff_float_interleave2_sse(dst, src, len);
-    } else if (channels == 6)
-        ff_float_interleave6_sse(dst, src, len);
-    else
-        ff_float_interleave_c(dst, src, len, channels);
-}
 #endif /* HAVE_YASM */
 
 av_cold void ff_fmt_convert_init_x86(FmtConvertContext *c, AVCodecContext *avctx)
@@ -122,32 +44,13 @@
 #if HAVE_YASM
     int cpu_flags = av_get_cpu_flags();
 
-    if (EXTERNAL_MMX(cpu_flags)) {
-        c->float_interleave = float_interleave_mmx;
-    }
-    if (EXTERNAL_AMD3DNOW(cpu_flags)) {
-        if (!(avctx->flags & CODEC_FLAG_BITEXACT)) {
-            c->float_to_int16            = ff_float_to_int16_3dnow;
-            c->float_to_int16_interleave = float_to_int16_interleave_3dnow;
-        }
-    }
-    if (EXTERNAL_AMD3DNOWEXT(cpu_flags)) {
-        if (!(avctx->flags & CODEC_FLAG_BITEXACT)) {
-            c->float_to_int16_interleave = float_to_int16_interleave_3dnowext;
-        }
-    }
     if (EXTERNAL_SSE(cpu_flags)) {
         c->int32_to_float_fmul_scalar = ff_int32_to_float_fmul_scalar_sse;
         c->int32_to_float_fmul_array8 = ff_int32_to_float_fmul_array8_sse;
-        c->float_to_int16             = ff_float_to_int16_sse;
-        c->float_to_int16_interleave  = float_to_int16_interleave_sse;
-        c->float_interleave           = float_interleave_sse;
     }
     if (EXTERNAL_SSE2(cpu_flags)) {
         c->int32_to_float_fmul_scalar = ff_int32_to_float_fmul_scalar_sse2;
         c->int32_to_float_fmul_array8 = ff_int32_to_float_fmul_array8_sse2;
-        c->float_to_int16             = ff_float_to_int16_sse2;
-        c->float_to_int16_interleave  = float_to_int16_interleave_sse2;
     }
 #endif /* HAVE_YASM */
 }
diff --git a/libavcodec/x86/g722dsp.asm b/libavcodec/x86/g722dsp.asm
new file mode 100644
index 0000000..807a1bd
--- /dev/null
+++ b/libavcodec/x86/g722dsp.asm
@@ -0,0 +1,54 @@
+;******************************************************************************
+;* SIMD optimized DSP functions for G722 coding
+;*
+;* Copyright (c) 2014 James Almer
+;*
+;* 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
+
+pw_qmf_coeffs:  dw   3, -210,  -11, -805,  -11,  951,  53, 3876
+pw_qmf_coeffs2: dw  12, 3876, -156,  951,   32, -805, 362, -210
+pw_qmf_coeffs3: dw 362,    0 ,  32,    0, -156,    0,  12,    0
+pw_qmf_coeffs4: dw  53,    0,  -11,    0,  -11,    0,   3,    0
+
+SECTION_TEXT
+
+INIT_XMM sse2
+cglobal g722_apply_qmf, 2, 2, 5, prev, out
+    movu m0, [prevq+mmsize*0]
+    movu m1, [prevq+mmsize*1]
+    movu m2, [prevq+mmsize*2]
+    punpcklwd m3, m0, m1
+    punpckhwd m0, m1
+    punpcklwd m4, m2, m2
+    punpckhwd m2, m2
+    pmaddwd   m3, [pw_qmf_coeffs ]
+    pmaddwd   m0, [pw_qmf_coeffs2]
+    pmaddwd   m4, [pw_qmf_coeffs3]
+    pmaddwd   m2, [pw_qmf_coeffs4]
+    paddd     m0, m3
+    paddd     m2, m4
+    paddd     m0, m2
+    pshufd    m2, m0, q0032
+    paddd     m0, m2
+    pshufd    m0, m0, q0001
+    movq  [outq], m0
+    RET
diff --git a/libavcodec/x86/g722dsp_init.c b/libavcodec/x86/g722dsp_init.c
new file mode 100644
index 0000000..6146951
--- /dev/null
+++ b/libavcodec/x86/g722dsp_init.c
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2014 James Almer
+ *
+ * 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/attributes.h"
+#include "libavutil/x86/cpu.h"
+#include "libavcodec/g722dsp.h"
+
+void ff_g722_apply_qmf_sse2(const int16_t *prev_samples, int xout[2]);
+
+av_cold void ff_g722dsp_init_x86(G722DSPContext *dsp)
+{
+    int cpu_flags = av_get_cpu_flags();
+
+    if (EXTERNAL_SSE2(cpu_flags))
+        dsp->apply_qmf = ff_g722_apply_qmf_sse2;
+}
diff --git a/libavcodec/x86/h264_deblock_10bit.asm b/libavcodec/x86/h264_deblock_10bit.asm
index d8ace17..ebf8a3f 100644
--- a/libavcodec/x86/h264_deblock_10bit.asm
+++ b/libavcodec/x86/h264_deblock_10bit.asm
@@ -26,15 +26,13 @@
 
 %include "libavutil/x86/x86util.asm"
 
-SECTION_RODATA
-
-pw_pixel_max: times 8 dw ((1 << 10)-1)
-
 SECTION .text
 
 cextern pw_2
 cextern pw_3
 cextern pw_4
+cextern pw_1023
+%define pw_pixel_max pw_1023
 
 ; out: %4 = |%1-%2|-%3
 ; clobbers: %5
diff --git a/libavcodec/x86/h264_idct_10bit.asm b/libavcodec/x86/h264_idct_10bit.asm
index 5c3acb1..cc115b0 100644
--- a/libavcodec/x86/h264_idct_10bit.asm
+++ b/libavcodec/x86/h264_idct_10bit.asm
@@ -26,11 +26,13 @@
 
 SECTION_RODATA
 
-pw_pixel_max: times 8 dw ((1 << 10)-1)
 pd_32:        times 4 dd 32
 
 SECTION .text
 
+cextern pw_1023
+%define pw_pixel_max pw_1023
+
 ;-----------------------------------------------------------------------------
 ; void ff_h264_idct_add_10(pixel *dst, int16_t *block, int stride)
 ;-----------------------------------------------------------------------------
diff --git a/libavcodec/x86/h264_intrapred_10bit.asm b/libavcodec/x86/h264_intrapred_10bit.asm
index b60a210..9aeb702 100644
--- a/libavcodec/x86/h264_intrapred_10bit.asm
+++ b/libavcodec/x86/h264_intrapred_10bit.asm
@@ -26,6 +26,8 @@
 
 SECTION_RODATA
 
+cextern pw_1023
+%define pw_pixel_max pw_1023
 cextern pw_512
 cextern pw_16
 cextern pw_8
@@ -35,7 +37,6 @@
 
 pw_m32101234: dw -3, -2, -1, 0, 1, 2, 3, 4
 pw_m3:        times 8 dw -3
-pw_pixel_max: times 8 dw ((1 << 10)-1)
 pd_17:        times 4 dd 17
 pd_16:        times 4 dd 16
 
diff --git a/libavcodec/x86/h264_qpel.c b/libavcodec/x86/h264_qpel.c
index b4cb9b1..33a7fb0 100644
--- a/libavcodec/x86/h264_qpel.c
+++ b/libavcodec/x86/h264_qpel.c
@@ -282,7 +282,7 @@
 #define H264_MC_V(OPNAME, SIZE, MMX, ALIGN) \
 static void OPNAME ## h264_qpel ## SIZE ## _mc01_ ## MMX(uint8_t *dst, const uint8_t *src, ptrdiff_t stride)\
 {\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*SIZE];\
+    LOCAL_ALIGNED(ALIGN, uint8_t, temp, [SIZE*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);\
 }\
@@ -294,7 +294,7 @@
 \
 static void OPNAME ## h264_qpel ## SIZE ## _mc03_ ## MMX(uint8_t *dst, const uint8_t *src, ptrdiff_t stride)\
 {\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*SIZE];\
+    LOCAL_ALIGNED(ALIGN, uint8_t, temp, [SIZE*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);\
 }\
@@ -302,41 +302,41 @@
 #define H264_MC_HV(OPNAME, SIZE, MMX, ALIGN) \
 static void OPNAME ## h264_qpel ## SIZE ## _mc11_ ## MMX(uint8_t *dst, const uint8_t *src, ptrdiff_t stride)\
 {\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*SIZE];\
+    LOCAL_ALIGNED(ALIGN, uint8_t, temp, [SIZE*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, const uint8_t *src, ptrdiff_t stride)\
 {\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*SIZE];\
+    LOCAL_ALIGNED(ALIGN, uint8_t, temp, [SIZE*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, const uint8_t *src, ptrdiff_t stride)\
 {\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*SIZE];\
+    LOCAL_ALIGNED(ALIGN, uint8_t, temp, [SIZE*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, const uint8_t *src, ptrdiff_t stride)\
 {\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*SIZE];\
+    LOCAL_ALIGNED(ALIGN, uint8_t, temp, [SIZE*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, const uint8_t *src, ptrdiff_t stride)\
 {\
-    DECLARE_ALIGNED(ALIGN, uint16_t, temp)[SIZE*(SIZE<8?12:24)];\
+    LOCAL_ALIGNED(ALIGN, uint16_t, temp, [SIZE*(SIZE<8?12:24)]);\
     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, const uint8_t *src, ptrdiff_t stride)\
 {\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*(SIZE<8?12:24)*2 + SIZE*SIZE];\
+    LOCAL_ALIGNED(ALIGN, uint8_t, temp, [SIZE*(SIZE<8?12:24)*2 + SIZE*SIZE]);\
     uint8_t * const halfHV= temp;\
     int16_t * const halfV= (int16_t*)(temp + SIZE*SIZE);\
     av_assert2(((int)temp & 7) == 0);\
@@ -346,7 +346,7 @@
 \
 static void OPNAME ## h264_qpel ## SIZE ## _mc23_ ## MMX(uint8_t *dst, const uint8_t *src, ptrdiff_t stride)\
 {\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*(SIZE<8?12:24)*2 + SIZE*SIZE];\
+    LOCAL_ALIGNED(ALIGN, uint8_t, temp, [SIZE*(SIZE<8?12:24)*2 + SIZE*SIZE]);\
     uint8_t * const halfHV= temp;\
     int16_t * const halfV= (int16_t*)(temp + SIZE*SIZE);\
     av_assert2(((int)temp & 7) == 0);\
@@ -356,7 +356,7 @@
 \
 static void OPNAME ## h264_qpel ## SIZE ## _mc12_ ## MMX(uint8_t *dst, const uint8_t *src, ptrdiff_t stride)\
 {\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*(SIZE<8?12:24)*2 + SIZE*SIZE];\
+    LOCAL_ALIGNED(ALIGN, uint8_t, temp, [SIZE*(SIZE<8?12:24)*2 + SIZE*SIZE]);\
     uint8_t * const halfHV= temp;\
     int16_t * const halfV= (int16_t*)(temp + SIZE*SIZE);\
     av_assert2(((int)temp & 7) == 0);\
@@ -366,7 +366,7 @@
 \
 static void OPNAME ## h264_qpel ## SIZE ## _mc32_ ## MMX(uint8_t *dst, const uint8_t *src, ptrdiff_t stride)\
 {\
-    DECLARE_ALIGNED(ALIGN, uint8_t, temp)[SIZE*(SIZE<8?12:24)*2 + SIZE*SIZE];\
+    LOCAL_ALIGNED(ALIGN, uint8_t, temp, [SIZE*(SIZE<8?12:24)*2 + SIZE*SIZE]);\
     uint8_t * const halfHV= temp;\
     int16_t * const halfV= (int16_t*)(temp + SIZE*SIZE);\
     av_assert2(((int)temp & 7) == 0);\
diff --git a/libavcodec/x86/h264_qpel_10bit.asm b/libavcodec/x86/h264_qpel_10bit.asm
index d65660d..757c425 100644
--- a/libavcodec/x86/h264_qpel_10bit.asm
+++ b/libavcodec/x86/h264_qpel_10bit.asm
@@ -26,11 +26,11 @@
 
 SECTION_RODATA 32
 
+cextern pw_1023
+%define pw_pixel_max pw_1023
 cextern pw_16
 cextern pw_1
-pb_0: times 32 db 0 ; we do not use cextern here as old llvm-gcc fails to align it correctly
-
-pw_pixel_max: times 8 dw ((1 << 10)-1)
+cextern pb_0
 
 pad10: times 8 dw 10*1023
 pad20: times 8 dw 20*1023
diff --git a/libavcodec/x86/h264_weight_10bit.asm b/libavcodec/x86/h264_weight_10bit.asm
index 5d94962..f924e55 100644
--- a/libavcodec/x86/h264_weight_10bit.asm
+++ b/libavcodec/x86/h264_weight_10bit.asm
@@ -26,11 +26,12 @@
 
 SECTION_RODATA 32
 
-pw_pixel_max: times 8 dw ((1 << 10)-1)
 sq_1: dq 1
       dq 0
 
 cextern pw_1
+cextern pw_1023
+%define pw_pixel_max pw_1023
 
 SECTION .text
 
diff --git a/libavcodec/x86/hevc_deblock.asm b/libavcodec/x86/hevc_deblock.asm
index f92cb2c..48a5975 100644
--- a/libavcodec/x86/hevc_deblock.asm
+++ b/libavcodec/x86/hevc_deblock.asm
@@ -26,8 +26,9 @@
 
 SECTION_RODATA
 
+cextern pw_1023
+%define pw_pixel_max_10 pw_1023
 pw_pixel_max_12: times 8 dw ((1 << 12)-1)
-pw_pixel_max_10: times 8 dw ((1 << 10)-1)
 pw_m2:           times 8 dw -2
 pd_1 :           times 4 dd  1
 
diff --git a/libavcodec/x86/hevc_mc.asm b/libavcodec/x86/hevc_mc.asm
index 8f9f939..986493f 100644
--- a/libavcodec/x86/hevc_mc.asm
+++ b/libavcodec/x86/hevc_mc.asm
@@ -20,19 +20,27 @@
 ; */
 %include "libavutil/x86/x86util.asm"
 
-SECTION_RODATA
-pw_8:                   times 8 dw (1 << 9)
-pw_10:                  times 8 dw (1 << 11)
-pw_12:                  times 8 dw (1 << 13)
-pw_bi_8:                times 8 dw (1 << 8)
-pw_bi_10:               times 8 dw (1 << 10)
-pw_bi_12:               times 8 dw (1 << 12)
-max_pixels_10:          times 8  dw ((1 << 10)-1)
-max_pixels_12:          times 8  dw ((1 << 12)-1)
-zero:                   times 4  dd 0
-one_per_32:             times 4  dd 1
+SECTION_RODATA 32
+cextern pw_255
+cextern pw_512
+cextern pw_2048
+cextern pw_8192
+cextern pw_1023
+cextern pw_1024
+cextern pw_4096
+%define pw_8 pw_512
+%define pw_10 pw_2048
+%define pw_12 pw_8192
+%define pw_bi_10 pw_1024
+%define pw_bi_12 pw_4096
+%define max_pixels_8 pw_255
+%define max_pixels_10 pw_1023
+pw_bi_8:                times 16 dw  (1 <<  8)
+max_pixels_12:          times 16 dw ((1 << 12)-1)
+cextern pd_1
+cextern pb_0
 
-SECTION .text
+SECTION_TEXT 32
 %macro EPEL_TABLE 4
 hevc_epel_filters_%4_%1 times %2 d%3 -2, 58
                         times %2 d%3 10, -2
@@ -51,6 +59,8 @@
 %endmacro
 
 
+EPEL_TABLE  8,16, b, avx2
+EPEL_TABLE 10, 8, w, avx2
 
 EPEL_TABLE  8, 8, b, sse4
 EPEL_TABLE 10, 4, w, sse4
@@ -75,10 +85,15 @@
 QPEL_TABLE 10, 4, w, sse4
 QPEL_TABLE 12, 4, w, sse4
 
+QPEL_TABLE  8,16, b, avx2
+QPEL_TABLE 10, 8, w, avx2
+
 %define MAX_PB_SIZE  64
 
 %define hevc_qpel_filters_sse4_14 hevc_qpel_filters_sse4_10
 
+%define hevc_qpel_filters_avx2_14 hevc_qpel_filters_avx2_10
+
 %if ARCH_X86_64
 
 %macro SIMPLE_BILOAD 4   ;width, tab, r1, r2
@@ -87,11 +102,22 @@
 %elif %1 <= 8
     movdqa            %3, [%2]                                              ; load data from source2
 %elif %1 <= 12
+%if cpuflag(avx2)
+    mova              %3, [%2]
+%else
     movdqa            %3, [%2]                                              ; load data from source2
     movq              %4, [%2+16]                                           ; load data from source2
+%endif ;avx
+%elif %1 <= 16
+%if cpuflag(avx2)
+    mova              %3, [%2]
 %else
     movdqa            %3, [%2]                                              ; load data from source2
     movdqa            %4, [%2+16]                                           ; load data from source2
+%endif ; avx
+%else ; %1 = 32
+    mova              %3, [%2]
+    mova              %4, [%2+32]
 %endif
 %endmacro
 
@@ -100,79 +126,110 @@
     movd              %4, [%3]                                               ; load data from source
 %elif %1 == 4 || (%2 == 8 && %1 <= 8)
     movq              %4, [%3]                                               ; load data from source
+%elif notcpuflag(avx)
+    movu              %4, [%3]                                               ; load data from source
+%elif %1 <= 8 || (%2 == 8 && %1 <= 16)
+    movdqu           %4, [%3]
 %else
-    movdqu            %4, [%3]                                               ; load data from source
+    movu              %4, [%3]
 %endif
 %endmacro
 
-%macro SIMPLE_8LOAD 5    ;width, bitd, tab, r1, r2
-%if %1 == 2 || (%2 == 8 && %1 <= 4)
-    movq              %4, [%3]                                              ; load data from source2
-%elif %1 == 4 || (%2 == 8 && %1 <= 8)
-    movdqa            %4, [%3]                                              ; load data from source2
-%elif %1 <= 12
-    movdqa            %4, [%3]                                              ; load data from source2
-    movq              %5, [%3+16]                                           ; load data from source2
-%else
-    movdqa            %4, [%3]                                              ; load data from source2
-    movdqa            %5, [%3+16]                                           ; load data from source2
-%endif
-%endmacro
 
-%macro EPEL_FILTER 2-4                            ; bit depth, filter index
+%macro EPEL_FILTER 5 ; bit depth, filter index, xmma, xmmb, gprtmp
+%if cpuflag(avx2)
+%assign %%offset 32
 %ifdef PIC
-    lea         rfilterq, [hevc_epel_filters_sse4_%1]
+    lea              %5q, [hevc_epel_filters_avx2_%1]
+    %define FILTER %5q
 %else
-    %define rfilterq hevc_epel_filters_sse4_%1
+    %define FILTER hevc_epel_filters_avx2_%1
 %endif
+%else
+%assign %%offset 16
+%ifdef PIC
+    lea              %5q, [hevc_epel_filters_sse4_%1]
+    %define FILTER %5q
+%else
+    %define FILTER hevc_epel_filters_sse4_%1
+%endif
+%endif ;cpuflag(avx2)
     sub              %2q, 1
+%if cpuflag(avx2)
+    shl              %2q, 6                      ; multiply by 64
+  %else
     shl              %2q, 5                      ; multiply by 32
-    movdqa           %3, [rfilterq + %2q]        ; get 2 first values of filters
-    movdqa           %4, [rfilterq + %2q+16]     ; get 2 last values of filters
+%endif
+    mova           %3, [FILTER + %2q]        ; get 2 first values of filters
+    mova           %4, [FILTER + %2q+%%offset]     ; get 2 last values of filters
 %endmacro
 
 %macro EPEL_HV_FILTER 1
-%ifdef PIC
-    lea         rfilterq, [hevc_epel_filters_sse4_%1]
+%if cpuflag(avx2)
+%assign %%offset 32
+%assign %%shift  6
+%define %%table  hevc_epel_filters_avx2_%1
 %else
-    %define rfilterq hevc_epel_filters_sse4_%1
+%assign %%offset 16
+%assign %%shift  5
+%define %%table  hevc_epel_filters_sse4_%1
+%endif
+
+%ifdef PIC
+    lea           r3srcq, [%%table]
+    %define FILTER r3srcq
+%else
+    %define FILTER %%table
 %endif
     sub              mxq, 1
     sub              myq, 1
-    shl              mxq, 5                      ; multiply by 32
-    shl              myq, 5                      ; multiply by 32
-    movdqa           m14, [rfilterq + mxq]        ; get 2 first values of filters
-    movdqa           m15, [rfilterq + mxq+16]     ; get 2 last values of filters
-    lea           r3srcq, [srcstrideq*3]
+    shl              mxq, %%shift                ; multiply by 32
+    shl              myq, %%shift                ; multiply by 32
+    mova             m14, [FILTER + mxq]        ; get 2 first values of filters
+    mova             m15, [FILTER + mxq+%%offset]     ; get 2 last values of filters
 
-%ifdef PIC
-    lea         rfilterq, [hevc_epel_filters_sse4_10]
+%if cpuflag(avx2)
+%define %%table  hevc_epel_filters_avx2_10
 %else
-    %define rfilterq hevc_epel_filters_sse4_10
+%define %%table  hevc_epel_filters_sse4_10
 %endif
-    movdqa           m12, [rfilterq + myq]        ; get 2 first values of filters
-    movdqa           m13, [rfilterq + myq+16]     ; get 2 last values of filters
+%ifdef PIC
+    lea           r3srcq, [%%table]
+    %define FILTER r3srcq
+%else
+    %define FILTER %%table
+%endif
+    mova             m12, [FILTER + myq]        ; get 2 first values of filters
+    mova             m13, [FILTER + myq+%%offset]     ; get 2 last values of filters
+    lea           r3srcq, [srcstrideq*3]
 %endmacro
 
 %macro QPEL_FILTER 2
-%ifdef PIC
-    lea         rfilterq, [hevc_qpel_filters_sse4_%1]
+
+%if cpuflag(avx2)
+%assign %%offset 32
+%assign %%shift  7
+%define %%table  hevc_qpel_filters_avx2_%1
 %else
-    %define rfilterq hevc_qpel_filters_sse4_%1
+%assign %%offset 16
+%assign %%shift  6
+%define %%table  hevc_qpel_filters_sse4_%1
 %endif
-    lea              %2q, [%2q*8-8]
-    movdqa           m12, [rfilterq + %2q*8]       ; get 4 first values of filters
-    movdqa           m13, [rfilterq + %2q*8 + 16]  ; get 4 first values of filters
-    movdqa           m14, [rfilterq + %2q*8 + 32]  ; get 4 first values of filters
-    movdqa           m15, [rfilterq + %2q*8 + 48]  ; get 4 first values of filters
+
+%ifdef PIC
+    lea         rfilterq, [%%table]
+%else
+    %define rfilterq %%table
+%endif
+    sub              %2q, 1
+    shl              %2q, %%shift                        ; multiply by 32
+    mova             m12, [rfilterq + %2q]               ; get 4 first values of filters
+    mova             m13, [rfilterq + %2q +   %%offset]  ; get 4 first values of filters
+    mova             m14, [rfilterq + %2q + 2*%%offset]  ; get 4 first values of filters
+    mova             m15, [rfilterq + %2q + 3*%%offset]  ; get 4 first values of filters
 %endmacro
 
 %macro EPEL_LOAD 4
-%ifdef PIC
-    lea rfilterq, [%2]
-%else
-    %define rfilterq %2
-%endif
 %if (%1 == 8 && %4 <= 4)
 %define %%load movd
 %elif (%1 == 8 && %4 <= 8) || (%1 > 8 && %4 <= 4)
@@ -181,29 +238,28 @@
 %define %%load movdqu
 %endif
 
-    %%load            m0, [rfilterq ]
+    %%load            m0, [%2q ]
 %ifnum %3
-    %%load            m1, [rfilterq+  %3]
-    %%load            m2, [rfilterq+2*%3]
-    %%load            m3, [rfilterq+3*%3]
+    %%load            m1, [%2q+  %3]
+    %%load            m2, [%2q+2*%3]
+    %%load            m3, [%2q+3*%3]
 %else
-    %%load            m1, [rfilterq+  %3q]
-    %%load            m2, [rfilterq+2*%3q]
-    %%load            m3, [rfilterq+r3srcq]
+    %%load            m1, [%2q+  %3q]
+    %%load            m2, [%2q+2*%3q]
+    %%load            m3, [%2q+r3srcq]
 %endif
-
 %if %1 == 8
 %if %4 > 8
-    SBUTTERFLY        bw, 0, 1, 10
-    SBUTTERFLY        bw, 2, 3, 10
+    SBUTTERFLY        bw, 0, 1, 7
+    SBUTTERFLY        bw, 2, 3, 7
 %else
     punpcklbw         m0, m1
     punpcklbw         m2, m3
 %endif
 %else
 %if %4 > 4
-    SBUTTERFLY        wd, 0, 1, 10
-    SBUTTERFLY        wd, 2, 3, 10
+    SBUTTERFLY        wd, 0, 1, 7
+    SBUTTERFLY        wd, 2, 3, 7
 %else
     punpcklwd         m0, m1
     punpcklwd         m2, m3
@@ -220,7 +276,7 @@
 %elif %3 == 8
 %define %%load movq
 %else
-%define %%load movdqu
+%define %%load movu
 %endif
 %else
 %if %3 == 2
@@ -228,7 +284,7 @@
 %elif %3 == 4
 %define %%load movq
 %else
-%define %%load movdqu
+%define %%load movu
 %endif
 %endif
     %%load            m0, [%2-3*%%stride]        ;load data from source
@@ -247,10 +303,10 @@
     SBUTTERFLY        wd, 4, 5, %4
     SBUTTERFLY        wd, 6, 7, %4
 %else
-    punpcklwd         m0, m1
-    punpcklwd         m2, m3
-    punpcklwd         m4, m5
-    punpcklwd         m6, m7
+    punpcklbw         m0, m1
+    punpcklbw         m2, m3
+    punpcklbw         m4, m5
+    punpcklbw         m6, m7
 %endif
 %else
 %if %3 > 4
@@ -259,10 +315,10 @@
     SBUTTERFLY        dq, 4, 5, %4
     SBUTTERFLY        dq, 6, 7, %4
 %else
-    punpckldq         m0, m1
-    punpckldq         m2, m3
-    punpckldq         m4, m5
-    punpckldq         m6, m7
+    punpcklwd         m0, m1
+    punpcklwd         m2, m3
+    punpcklwd         m4, m5
+    punpcklwd         m6, m7
 %endif
 %endif
 %endmacro
@@ -270,14 +326,14 @@
 %macro QPEL_V_LOAD 5
     lea              %5q, [%2]
     sub              %5q, r3srcq
-    movdqu            m0, [%5q            ]      ;load x- 3*srcstride
-    movdqu            m1, [%5q+   %3q     ]      ;load x- 2*srcstride
-    movdqu            m2, [%5q+ 2*%3q     ]      ;load x-srcstride
-    movdqu            m3, [%2       ]      ;load x
-    movdqu            m4, [%2+   %3q]      ;load x+stride
-    movdqu            m5, [%2+ 2*%3q]      ;load x+2*stride
-    movdqu            m6, [%2+r3srcq]      ;load x+3*stride
-    movdqu            m7, [%2+ 4*%3q]      ;load x+4*stride
+    movu              m0, [%5q            ]      ;load x- 3*srcstride
+    movu              m1, [%5q+   %3q     ]      ;load x- 2*srcstride
+    movu              m2, [%5q+ 2*%3q     ]      ;load x-srcstride
+    movu              m3, [%2       ]      ;load x
+    movu              m4, [%2+   %3q]      ;load x+stride
+    movu              m5, [%2+ 2*%3q]      ;load x+2*stride
+    movu              m6, [%2+r3srcq]      ;load x+3*stride
+    movu              m7, [%2+ 4*%3q]      ;load x+4*stride
 %if %1 == 8
 %if %4 > 8
     SBUTTERFLY        bw, 0, 1, 8
@@ -347,8 +403,17 @@
     movq        [%1+16], %3
 %endmacro
 %macro PEL_10STORE16 3
+%if cpuflag(avx2)
+    movu            [%1], %2
+%else
     PEL_10STORE8      %1, %2, %3
     movdqa       [%1+16], %3
+%endif
+%endmacro
+
+%macro PEL_10STORE32 3
+    PEL_10STORE16     %1, %2, %3
+    movu         [%1+32], %3
 %endmacro
 
 %macro PEL_8STORE2 3
@@ -370,7 +435,14 @@
     movd          [%1+8], %2
 %endmacro
 %macro PEL_8STORE16 3
-    movdqa          [%1], %2
+%if cpuflag(avx2)
+    movdqu        [%1], %2
+%else
+    mova          [%1], %2
+%endif ; avx
+%endmacro
+%macro PEL_8STORE32 3
+    movu          [%1], %2
 %endmacro
 
 %macro LOOP_END 3
@@ -381,65 +453,107 @@
 %endmacro
 
 
-%macro MC_PIXEL_COMPUTE 2 ;width, bitdepth
+%macro MC_PIXEL_COMPUTE 2-3 ;width, bitdepth
 %if %2 == 8
+%if cpuflag(avx2) && %0 ==3
+%if %1 > 16
+    vextracti128 xm1, m0, 1
+    pmovzxbw      m1, xm1
+    psllw         m1, 14-%2
+%endif
+    pmovzxbw      m0, xm0
+%else ; not avx
 %if %1 > 8
-    punpckhbw         m1, m0, m2
-    psllw             m1, 14-%2
+    punpckhbw     m1, m0, m2
+    psllw         m1, 14-%2
 %endif
-    punpcklbw         m0, m2
+    punpcklbw     m0, m2
 %endif
-    psllw             m0, 14-%2
+%endif ;avx
+    psllw         m0, 14-%2
 %endmacro
 
-
-%macro EPEL_COMPUTE 4 ; bitdepth, width, filter1, filter2
+%macro EPEL_COMPUTE 4-8 ; bitdepth, width, filter1, filter2, HV/m0, m2, m1, m3
+%if %0 == 8
+%define %%reg0 %5
+%define %%reg2 %6
+%define %%reg1 %7
+%define %%reg3 %8
+%else
+%define %%reg0 m0
+%define %%reg2 m2
+%define %%reg1 m1
+%define %%reg3 m3
+%endif
 %if %1 == 8
-    pmaddubsw         m0, %3   ;x1*c1+x2*c2
-    pmaddubsw         m2, %4   ;x3*c3+x4*c4
-    paddw             m0, m2
+%if cpuflag(avx2) && (%0 == 5)
+%if %2 > 16
+    vperm2i128    m10, m0, m1, q0301
+%endif
+    vinserti128    m0, m0, xm1, 1
+    mova           m1, m10
+%if %2 > 16
+    vperm2i128    m10, m2, m3, q0301
+%endif
+    vinserti128    m2, m2, xm3, 1
+    mova           m3, m10
+%endif
+    pmaddubsw      %%reg0, %3   ;x1*c1+x2*c2
+    pmaddubsw      %%reg2, %4   ;x3*c3+x4*c4
+    paddw          %%reg0, %%reg2
 %if %2 > 8
-    pmaddubsw         m1, %3
-    pmaddubsw         m3, %4
-    paddw             m1, m3
+    pmaddubsw      %%reg1, %3
+    pmaddubsw      %%reg3, %4
+    paddw          %%reg1, %%reg3
 %endif
 %else
-    pmaddwd           m0, %3
-    pmaddwd           m2, %4
-    paddd             m0, m2
+    pmaddwd        %%reg0, %3
+    pmaddwd        %%reg2, %4
+    paddd          %%reg0, %%reg2
 %if %2 > 4
-    pmaddwd           m1, %3
-    pmaddwd           m3, %4
-    paddd             m1, m3
+    pmaddwd        %%reg1, %3
+    pmaddwd        %%reg3, %4
+    paddd          %%reg1, %%reg3
+%if %1 != 8
+    psrad          %%reg1, %1-8
+%endif
 %endif
 %if %1 != 8
-    psrad             m0, %1-8
-    psrad             m1, %1-8
+    psrad          %%reg0, %1-8
 %endif
-    packssdw          m0, m1
+    packssdw       %%reg0, %%reg1
 %endif
 %endmacro
 
 %macro QPEL_HV_COMPUTE 4     ; width, bitdepth, filter idx
-%ifdef PIC
-    lea         rfilterq, [hevc_qpel_filters_sse4_%2]
+
+%if cpuflag(avx2)
+%assign %%offset 32
+%define %%table  hevc_qpel_filters_avx2_%2
 %else
-    %define rfilterq hevc_qpel_filters_sse4_%2
+%assign %%offset 16
+%define %%table  hevc_qpel_filters_sse4_%2
+%endif
+
+%ifdef PIC
+    lea         rfilterq, [%%table]
+%else
+    %define rfilterq %%table
 %endif
 
 %if %2 == 8
     pmaddubsw         m0, [rfilterq + %3q*8   ]   ;x1*c1+x2*c2
-    pmaddubsw         m2, [rfilterq + %3q*8+16]   ;x3*c3+x4*c4
-    pmaddubsw         m4, [rfilterq + %3q*8+32]   ;x5*c5+x6*c6
-    pmaddubsw         m6, [rfilterq + %3q*8+48]   ;x7*c7+x8*c8
+    pmaddubsw         m2, [rfilterq + %3q*8+%%offset]   ;x3*c3+x4*c4
+    pmaddubsw         m4, [rfilterq + %3q*8+2*%%offset]   ;x5*c5+x6*c6
+    pmaddubsw         m6, [rfilterq + %3q*8+3*%%offset]   ;x7*c7+x8*c8
     paddw             m0, m2
     paddw             m4, m6
     paddw             m0, m4
 %else
     pmaddwd           m0, [rfilterq + %3q*8   ]
-    pmaddwd           m2, [rfilterq + %3q*8+16]
-    pmaddwd           m4, [rfilterq + %3q*8+32]
-    pmaddwd           m6, [rfilterq + %3q*8+48]
+    pmaddwd           m2, [rfilterq + %3q*8+%%offset]
+    pmaddwd           m4, [rfilterq + %3q*8+2*%%offset]
+    pmaddwd           m6, [rfilterq + %3q*8+3*%%offset]
     paddd             m0, m2
     paddd             m4, m6
     paddd             m0, m4
@@ -448,9 +562,9 @@
 %endif
 %if %1 > 4
     pmaddwd           m1, [rfilterq + %3q*8   ]
-    pmaddwd           m3, [rfilterq + %3q*8+16]
-    pmaddwd           m5, [rfilterq + %3q*8+32]
-    pmaddwd           m7, [rfilterq + %3q*8+48]
+    pmaddwd           m3, [rfilterq + %3q*8+%%offset]
+    pmaddwd           m5, [rfilterq + %3q*8+2*%%offset]
+    pmaddwd           m7, [rfilterq + %3q*8+3*%%offset]
     paddd             m1, m3
     paddd             m5, m7
     paddd             m1, m5
@@ -462,8 +576,28 @@
 %endif
 %endmacro
 
-%macro QPEL_COMPUTE 2     ; width, bitdepth
+%macro QPEL_COMPUTE 2-3     ; width, bitdepth
 %if %2 == 8
+%if cpuflag(avx2) && (%0 == 3)
+
+    vperm2i128 m10, m0,  m1, q0301
+    vinserti128 m0, m0, xm1, 1
+    SWAP 1, 10
+
+    vperm2i128 m10, m2,  m3, q0301
+    vinserti128 m2, m2, xm3, 1
+    SWAP 3, 10
+
+
+    vperm2i128 m10, m4,  m5, q0301
+    vinserti128 m4, m4, xm5, 1
+    SWAP 5, 10
+
+    vperm2i128 m10, m6,  m7, q0301
+    vinserti128 m6, m6, xm7, 1
+    SWAP 7, 10
+%endif
+
     pmaddubsw         m0, m12   ;x1*c1+x2*c2
     pmaddubsw         m2, m13   ;x3*c3+x4*c4
     pmaddubsw         m4, m14   ;x5*c5+x6*c6
@@ -506,12 +640,16 @@
 %endif
 %endmacro
 
-%macro BI_COMPUTE 7     ; width, bitd, src1l, src1h, scr2l, scr2h, pw
+%macro BI_COMPUTE 7-8     ; width, bitd, src1l, src1h, scr2l, scr2h, pw
     paddsw            %3, %5
 %if %1 > 8
     paddsw            %4, %6
 %endif
     UNI_COMPUTE       %1, %2, %3, %4, %7
+%if %0 == 8 && cpuflag(avx2) && (%2 == 8)
+    vpermq            %3, %3, 216
+    vpermq            %4, %4, 216
+%endif
 %endmacro
 
 %macro UNI_COMPUTE 5
@@ -522,16 +660,14 @@
 %if %2 == 8
     packuswb          %3, %4
 %else
-    pminsw            %3, [max_pixels_%2]
-    pmaxsw            %3, [zero]
-%if %1 > 8
-    pminsw            %4, [max_pixels_%2]
-    pmaxsw            %4, [zero]
+    CLIPW             %3, [pb_0], [max_pixels_%2]
+%if (%1 > 8 && notcpuflag(avx)) || %1 > 16
+    CLIPW             %4, [pb_0], [max_pixels_%2]
 %endif
 %endif
 %endmacro
 
-INIT_XMM sse4                                    ; adds ff_ and _sse4 to function name
+
 ; ******************************
 ; void put_hevc_mc_pixels(int16_t *dst, ptrdiff_t dststride,
 ;                         uint8_t *_src, ptrdiff_t _srcstride,
@@ -539,15 +675,23 @@
 ; ******************************
 
 %macro HEVC_PUT_HEVC_PEL_PIXELS 2
+HEVC_PEL_PIXELS     %1, %2
+HEVC_UNI_PEL_PIXELS %1, %2
+HEVC_BI_PEL_PIXELS  %1, %2
+%endmacro
+
+%macro HEVC_PEL_PIXELS 2
 cglobal hevc_put_hevc_pel_pixels%1_%2, 4, 4, 3, dst, src, srcstride,height
     pxor               m2, m2
 .loop
     SIMPLE_LOAD       %1, %2, srcq, m0
-    MC_PIXEL_COMPUTE  %1, %2
+    MC_PIXEL_COMPUTE  %1, %2, 1
     PEL_10STORE%1     dstq, m0, m1
     LOOP_END         dst, src, srcstride
     RET
+ %endmacro
 
+%macro HEVC_UNI_PEL_PIXELS 2
 cglobal hevc_put_hevc_uni_pel_pixels%1_%2, 5, 5, 2, dst, dststride, src, srcstride,height
 .loop
     SIMPLE_LOAD       %1, %2, srcq, m0
@@ -557,15 +701,17 @@
     dec          heightd                         ; cmp height
     jnz               .loop                      ; height loop
     RET
+%endmacro
 
+%macro HEVC_BI_PEL_PIXELS 2
 cglobal hevc_put_hevc_bi_pel_pixels%1_%2, 6, 6, 6, dst, dststride, src, srcstride, src2, height
     pxor              m2, m2
     movdqa            m5, [pw_bi_%2]
 .loop
     SIMPLE_LOAD       %1, %2, srcq, m0
     SIMPLE_BILOAD     %1, src2q, m3, m4
-    MC_PIXEL_COMPUTE  %1, %2
-    BI_COMPUTE        %1, %2, m0, m1, m3, m4, m5
+    MC_PIXEL_COMPUTE  %1, %2, 1
+    BI_COMPUTE        %1, %2, m0, m1, m3, m4, m5, 1
     PEL_%2STORE%1   dstq, m0, m1
     add             dstq, dststrideq             ; dst += dststride
     add             srcq, srcstrideq             ; src += srcstride
@@ -573,33 +719,37 @@
     dec          heightd                         ; cmp height
     jnz               .loop                      ; height loop
     RET
-
 %endmacro
 
 
 ; ******************************
 ; void put_hevc_epel_hX(int16_t *dst, ptrdiff_t dststride,
 ;                       uint8_t *_src, ptrdiff_t _srcstride,
-;                       int width, int height, int mx, int my,
-;                       int16_t* mcbuffer)
+;                       int height, int mx, int my, int width);
 ; ******************************
 
 
 %macro HEVC_PUT_HEVC_EPEL 2
-cglobal hevc_put_hevc_epel_h%1_%2, 5, 6, 11, dst, src, srcstride, height, mx, rfilter
+%if cpuflag(avx2)
+%define XMM_REGS  11
+%else
+%define XMM_REGS  8
+%endif
+
+cglobal hevc_put_hevc_epel_h%1_%2, 5, 6, XMM_REGS, dst, src, srcstride, height, mx, rfilter
 %assign %%stride ((%2 + 7)/8)
-    EPEL_FILTER       %2, mx, m4, m5
+    EPEL_FILTER       %2, mx, m4, m5, rfilter
 .loop
     EPEL_LOAD         %2, srcq-%%stride, %%stride, %1
-    EPEL_COMPUTE      %2, %1, m4, m5
+    EPEL_COMPUTE      %2, %1, m4, m5, 1
     PEL_10STORE%1      dstq, m0, m1
     LOOP_END         dst, src, srcstride
     RET
 
-cglobal hevc_put_hevc_uni_epel_h%1_%2, 6, 7, 11, dst, dststride, src, srcstride, height, mx, rfilter
+cglobal hevc_put_hevc_uni_epel_h%1_%2, 6, 7, XMM_REGS, dst, dststride, src, srcstride, height, mx, rfilter
 %assign %%stride ((%2 + 7)/8)
     movdqa            m6, [pw_%2]
-    EPEL_FILTER       %2, mx, m4, m5
+    EPEL_FILTER       %2, mx, m4, m5, rfilter
 .loop
     EPEL_LOAD         %2, srcq-%%stride, %%stride, %1
     EPEL_COMPUTE      %2, %1, m4, m5
@@ -611,14 +761,14 @@
     jnz               .loop                      ; height loop
     RET
 
-cglobal hevc_put_hevc_bi_epel_h%1_%2, 7, 8, 11, dst, dststride, src, srcstride, src2, height, mx, rfilter
+cglobal hevc_put_hevc_bi_epel_h%1_%2, 7, 8, XMM_REGS, dst, dststride, src, srcstride, src2, height, mx, rfilter
     movdqa            m6, [pw_bi_%2]
-    EPEL_FILTER       %2, mx, m4, m5
+    EPEL_FILTER       %2, mx, m4, m5, rfilter
 .loop
     EPEL_LOAD         %2, srcq-%%stride, %%stride, %1
-    EPEL_COMPUTE      %2, %1, m4, m5
+    EPEL_COMPUTE      %2, %1, m4, m5, 1
     SIMPLE_BILOAD     %1, src2q, m2, m3
-    BI_COMPUTE        %1, %2, m0, m1, m2, m3, m6
+    BI_COMPUTE        %1, %2, m0, m1, m2, m3, m6, 1
     PEL_%2STORE%1   dstq, m0, m1
     add             dstq, dststrideq             ; dst += dststride
     add             srcq, srcstrideq             ; src += srcstride
@@ -630,26 +780,27 @@
 ; ******************************
 ; void put_hevc_epel_v(int16_t *dst, ptrdiff_t dststride,
 ;                      uint8_t *_src, ptrdiff_t _srcstride,
-;                      int width, int height, int mx, int my,
-;                      int16_t* mcbuffer)
+;                      int height, int mx, int my, int width)
 ; ******************************
 
-cglobal hevc_put_hevc_epel_v%1_%2, 6, 7, 11, dst, src, srcstride, height, r3src, my, rfilter
-    lea           r3srcq, [srcstrideq*3]
+cglobal hevc_put_hevc_epel_v%1_%2, 4, 6, XMM_REGS, dst, src, srcstride, height, r3src, my
+    movifnidn        myd, mym
     sub             srcq, srcstrideq
-    EPEL_FILTER       %2, my, m4, m5
+    EPEL_FILTER       %2, my, m4, m5, r3src
+    lea           r3srcq, [srcstrideq*3]
 .loop
     EPEL_LOAD         %2, srcq, srcstride, %1
-    EPEL_COMPUTE      %2, %1, m4, m5
+    EPEL_COMPUTE      %2, %1, m4, m5, 1
     PEL_10STORE%1     dstq, m0, m1
     LOOP_END          dst, src, srcstride
     RET
 
-cglobal hevc_put_hevc_uni_epel_v%1_%2, 7, 8, 11, dst, dststride, src, srcstride, height, r3src, my, rfilter
-    lea           r3srcq, [srcstrideq*3]
+cglobal hevc_put_hevc_uni_epel_v%1_%2, 5, 7, XMM_REGS, dst, dststride, src, srcstride, height, r3src, my
+    movifnidn        myd, mym
     movdqa            m6, [pw_%2]
     sub             srcq, srcstrideq
-    EPEL_FILTER       %2, my, m4, m5
+    EPEL_FILTER       %2, my, m4, m5, r3src
+    lea           r3srcq, [srcstrideq*3]
 .loop
     EPEL_LOAD         %2, srcq, srcstride, %1
     EPEL_COMPUTE      %2, %1, m4, m5
@@ -662,16 +813,17 @@
     RET
 
 
-cglobal hevc_put_hevc_bi_epel_v%1_%2, 8, 9, 11, dst, dststride, src, srcstride, src2, height, r3src, my, rfilter
-    lea           r3srcq, [srcstrideq*3]
+cglobal hevc_put_hevc_bi_epel_v%1_%2, 6, 8, XMM_REGS, dst, dststride, src, srcstride, src2, height, r3src, my
+    movifnidn        myd, mym
     movdqa            m6, [pw_bi_%2]
     sub             srcq, srcstrideq
-    EPEL_FILTER       %2, my, m4, m5
+    EPEL_FILTER       %2, my, m4, m5, r3src
+    lea           r3srcq, [srcstrideq*3]
 .loop
     EPEL_LOAD         %2, srcq, srcstride, %1
-    EPEL_COMPUTE      %2, %1, m4, m5
+    EPEL_COMPUTE      %2, %1, m4, m5, 1
     SIMPLE_BILOAD     %1, src2q, m2, m3
-    BI_COMPUTE        %1, %2, m0, m1, m2, m3, m6
+    BI_COMPUTE        %1, %2, m0, m1, m2, m3, m6, 1
     PEL_%2STORE%1   dstq, m0, m1
     add             dstq, dststrideq             ; dst += dststride
     add             srcq, srcstrideq             ; src += srcstride
@@ -685,29 +837,41 @@
 ; ******************************
 ; void put_hevc_epel_hv(int16_t *dst, ptrdiff_t dststride,
 ;                       uint8_t *_src, ptrdiff_t _srcstride,
-;                       int width, int height, int mx, int my)
+;                       int height, int mx, int my, int width)
 ; ******************************
 
 %macro HEVC_PUT_HEVC_EPEL_HV 2
-cglobal hevc_put_hevc_epel_hv%1_%2, 6, 8, 16 , dst, src, srcstride, height, mx, my, r3src, rfilter
+cglobal hevc_put_hevc_epel_hv%1_%2, 6, 7, 16 , dst, src, srcstride, height, mx, my, r3src
 %assign %%stride ((%2 + 7)/8)
     sub             srcq, srcstrideq
     EPEL_HV_FILTER    %2
     EPEL_LOAD         %2, srcq-%%stride, %%stride, %1
     EPEL_COMPUTE      %2, %1, m14, m15
+%if (%1 > 8 && (%2 == 8))
+    SWAP              m8, m1
+%endif
     SWAP              m4, m0
     add             srcq, srcstrideq
     EPEL_LOAD         %2, srcq-%%stride, %%stride, %1
     EPEL_COMPUTE      %2, %1, m14, m15
+%if (%1 > 8 && (%2 == 8))
+    SWAP              m9, m1
+%endif
     SWAP              m5, m0
     add             srcq, srcstrideq
     EPEL_LOAD         %2, srcq-%%stride, %%stride, %1
     EPEL_COMPUTE      %2, %1, m14, m15
+%if (%1 > 8 && (%2 == 8))
+    SWAP             m10, m1
+%endif
     SWAP              m6, m0
     add             srcq, srcstrideq
 .loop
     EPEL_LOAD         %2, srcq-%%stride, %%stride, %1
     EPEL_COMPUTE      %2, %1, m14, m15
+%if (%1 > 8 && (%2 == 8))
+    SWAP             m11, m1
+%endif
     SWAP              m7, m0
     punpcklwd         m0, m4, m5
     punpcklwd         m2, m6, m7
@@ -716,33 +880,65 @@
     punpckhwd         m3, m6, m7
 %endif
     EPEL_COMPUTE      14, %1, m12, m13
+%if (%1 > 8 && (%2 == 8))
+    punpcklwd         m4, m8, m9
+    punpcklwd         m2, m10, m11
+    punpckhwd         m8, m8, m9
+    punpckhwd         m3, m10, m11
+    EPEL_COMPUTE      14, %1, m12, m13, m4, m2, m8, m3
+%if cpuflag(avx2)
+    vinserti128       m2, m0, xm4, 1
+    vperm2i128        m3, m0, m4, q0301
+    PEL_10STORE%1     dstq, m2, m3
+%else
+    PEL_10STORE%1     dstq, m0, m4
+%endif
+%else
     PEL_10STORE%1     dstq, m0, m1
+%endif
     movdqa            m4, m5
     movdqa            m5, m6
     movdqa            m6, m7
+%if (%1 > 8 && (%2 == 8))
+    mova              m8, m9
+    mova              m9, m10
+    mova             m10, m11
+%endif
     LOOP_END         dst, src, srcstride
     RET
 
-cglobal hevc_put_hevc_uni_epel_hv%1_%2, 7, 9, 16 , dst, dststride, src, srcstride, height, mx, my, r3src, rfilter
+cglobal hevc_put_hevc_uni_epel_hv%1_%2, 7, 8, 16 , dst, dststride, src, srcstride, height, mx, my, r3src
 %assign %%stride ((%2 + 7)/8)
     sub             srcq, srcstrideq
     EPEL_HV_FILTER    %2
     EPEL_LOAD         %2, srcq-%%stride, %%stride, %1
     EPEL_COMPUTE      %2, %1, m14, m15
+%if (%1 > 8 && (%2 == 8))
+    SWAP              m8, m1
+%endif
     SWAP              m4, m0
     add             srcq, srcstrideq
     EPEL_LOAD         %2, srcq-%%stride, %%stride, %1
     EPEL_COMPUTE      %2, %1, m14, m15
+%if (%1 > 8 && (%2 == 8))
+    SWAP              m9, m1
+%endif
     SWAP              m5, m0
     add             srcq, srcstrideq
     EPEL_LOAD         %2, srcq-%%stride, %%stride, %1
     EPEL_COMPUTE      %2, %1, m14, m15
+%if (%1 > 8 && (%2 == 8))
+    SWAP             m10, m1
+%endif
     SWAP              m6, m0
     add             srcq, srcstrideq
 .loop
     EPEL_LOAD         %2, srcq-%%stride, %%stride, %1
     EPEL_COMPUTE      %2, %1, m14, m15
-    SWAP              m7, m0
+%if (%1 > 8 && (%2 == 8))
+    SWAP             m11, m1
+%endif
+    mova              m7, m0
     punpcklwd         m0, m4, m5
     punpcklwd         m2, m6, m7
 %if %1 > 4
@@ -750,37 +946,62 @@
     punpckhwd         m3, m6, m7
 %endif
     EPEL_COMPUTE      14, %1, m12, m13
+%if (%1 > 8 && (%2 == 8))
+    punpcklwd         m4, m8, m9
+    punpcklwd         m2, m10, m11
+    punpckhwd         m8, m8, m9
+    punpckhwd         m3, m10, m11
+    EPEL_COMPUTE      14, %1, m12, m13, m4, m2, m8, m3
+    UNI_COMPUTE       %1, %2, m0, m4, [pw_%2]
+%else
     UNI_COMPUTE       %1, %2, m0, m1, [pw_%2]
+%endif
     PEL_%2STORE%1   dstq, m0, m1
-    movdqa            m4, m5
-    movdqa            m5, m6
-    movdqa            m6, m7
+    mova              m4, m5
+    mova              m5, m6
+    mova              m6, m7
+%if (%1 > 8 && (%2 == 8))
+    mova              m8, m9
+    mova              m9, m10
+    mova             m10, m11
+%endif
     add             dstq, dststrideq             ; dst += dststride
     add             srcq, srcstrideq             ; src += srcstride
     dec          heightd                         ; cmp height
     jnz               .loop                      ; height loop
     RET
 
-
-cglobal hevc_put_hevc_bi_epel_hv%1_%2, 8, 10, 16, dst, dststride, src, srcstride, src2, height, mx, my, r3src, rfilter
+cglobal hevc_put_hevc_bi_epel_hv%1_%2, 8, 9, 16, dst, dststride, src, srcstride, src2, height, mx, my, r3src
 %assign %%stride ((%2 + 7)/8)
     sub             srcq, srcstrideq
     EPEL_HV_FILTER    %2
     EPEL_LOAD         %2, srcq-%%stride, %%stride, %1
     EPEL_COMPUTE      %2, %1, m14, m15
+%if (%1 > 8 && (%2 == 8))
+    SWAP              m8, m1
+%endif
     SWAP              m4, m0
     add             srcq, srcstrideq
     EPEL_LOAD         %2, srcq-%%stride, %%stride, %1
     EPEL_COMPUTE      %2, %1, m14, m15
+%if (%1 > 8 && (%2 == 8))
+    SWAP              m9, m1
+%endif
     SWAP              m5, m0
     add             srcq, srcstrideq
     EPEL_LOAD         %2, srcq-%%stride, %%stride, %1
     EPEL_COMPUTE      %2, %1, m14, m15
+%if (%1 > 8 && (%2 == 8))
+    SWAP             m10, m1
+%endif
     SWAP              m6, m0
     add             srcq, srcstrideq
 .loop
     EPEL_LOAD         %2, srcq-%%stride, %%stride, %1
     EPEL_COMPUTE      %2, %1, m14, m15
+%if (%1 > 8 && (%2 == 8))
+    SWAP             m11, m1
+%endif
     SWAP              m7, m0
     punpcklwd         m0, m4, m5
     punpcklwd         m2, m6, m7
@@ -789,12 +1010,33 @@
     punpckhwd         m3, m6, m7
 %endif
     EPEL_COMPUTE      14, %1, m12, m13
+%if (%1 > 8 && (%2 == 8))
+    punpcklwd         m4, m8, m9
+    punpcklwd         m2, m10, m11
+    punpckhwd         m8, m8, m9
+    punpckhwd         m3, m10, m11
+    EPEL_COMPUTE      14, %1, m12, m13, m4, m2, m8, m3
+    SIMPLE_BILOAD     %1, src2q, m8, m3
+%if cpuflag(avx2)
+    vinserti128       m1, m8, xm3, 1
+    vperm2i128        m2, m8, m3, q0301
+    BI_COMPUTE        %1, %2, m0, m4, m1, m2, [pw_bi_%2]
+%else
+    BI_COMPUTE        %1, %2, m0, m4, m8, m3, [pw_bi_%2]
+%endif
+%else
     SIMPLE_BILOAD     %1, src2q, m8, m9
     BI_COMPUTE        %1, %2, m0, m1, m8, m9, [pw_bi_%2]
-    PEL_%2STORE%1   dstq, m0, m1
-    movdqa            m4, m5
-    movdqa            m5, m6
-    movdqa            m6, m7
+%endif
+    PEL_%2STORE%1   dstq, m0, m4
+    mova              m4, m5
+    mova              m5, m6
+    mova              m6, m7
+%if (%1 > 8 && (%2 == 8))
+    mova              m8, m9
+    mova              m9, m10
+    mova             m10, m11
+%endif
     add             dstq, dststrideq             ; dst += dststride
     add             srcq, srcstrideq             ; src += srcstride
     add            src2q, 2*MAX_PB_SIZE          ; src += srcstride
@@ -806,7 +1048,7 @@
 ; ******************************
 ; void put_hevc_qpel_hX_X_X(int16_t *dst, ptrdiff_t dststride,
 ;                       uint8_t *_src, ptrdiff_t _srcstride,
-;                       int width, int height, int mx, int my)
+;                       int height, int mx, int my, int width)
 ; ******************************
 
 %macro HEVC_PUT_HEVC_QPEL 2
@@ -814,7 +1056,7 @@
     QPEL_FILTER       %2, mx
 .loop
     QPEL_H_LOAD       %2, srcq, %1, 10
-    QPEL_COMPUTE      %1, %2
+    QPEL_COMPUTE      %1, %2, 1
 %if %2 > 8
     packssdw          m0, m1
 %endif
@@ -823,7 +1065,7 @@
     RET
 
 cglobal hevc_put_hevc_uni_qpel_h%1_%2, 6, 7, 16 , dst, dststride, src, srcstride, height, mx, rfilter
-    movdqa            m9, [pw_%2]
+    mova              m9, [pw_%2]
     QPEL_FILTER       %2, mx
 .loop
     QPEL_H_LOAD       %2, srcq, %1, 10
@@ -844,12 +1086,12 @@
     QPEL_FILTER       %2, mx
 .loop
     QPEL_H_LOAD       %2, srcq, %1, 10
-    QPEL_COMPUTE      %1, %2
+    QPEL_COMPUTE      %1, %2, 1
 %if %2 > 8
     packssdw          m0, m1
 %endif
     SIMPLE_BILOAD     %1, src2q, m10, m11
-    BI_COMPUTE        %1, %2, m0, m1, m10, m11, m9
+    BI_COMPUTE        %1, %2, m0, m1, m10, m11, m9, 1
     PEL_%2STORE%1   dstq, m0, m1
     add             dstq, dststrideq             ; dst += dststride
     add             srcq, srcstrideq             ; src += srcstride
@@ -862,15 +1104,16 @@
 ; ******************************
 ; void put_hevc_qpel_vX_X_X(int16_t *dst, ptrdiff_t dststride,
 ;                       uint8_t *_src, ptrdiff_t _srcstride,
-;                       int width, int height, int mx, int my)
+;                       int height, int mx, int my, int width)
 ; ******************************
 
-cglobal hevc_put_hevc_qpel_v%1_%2, 6, 8, 16, dst, src, srcstride, height, r3src, my, rfilter
+cglobal hevc_put_hevc_qpel_v%1_%2, 4, 8, 16, dst, src, srcstride, height, r3src, my, rfilter
+    movifnidn        myd, mym
     lea           r3srcq, [srcstrideq*3]
     QPEL_FILTER       %2, my
 .loop
     QPEL_V_LOAD       %2, srcq, srcstride, %1, r7
-    QPEL_COMPUTE      %1, %2
+    QPEL_COMPUTE      %1, %2, 1
 %if %2 > 8
     packssdw          m0, m1
 %endif
@@ -878,7 +1121,8 @@
     LOOP_END         dst, src, srcstride
     RET
 
-cglobal hevc_put_hevc_uni_qpel_v%1_%2, 7, 9, 16, dst, dststride, src, srcstride, height, r3src, my, rfilter
+cglobal hevc_put_hevc_uni_qpel_v%1_%2, 5, 9, 16, dst, dststride, src, srcstride, height, r3src, my, rfilter
+    movifnidn        myd, mym
     movdqa            m9, [pw_%2]
     lea           r3srcq, [srcstrideq*3]
     QPEL_FILTER       %2, my
@@ -896,18 +1140,19 @@
     jnz               .loop                      ; height loop
     RET
 
-cglobal hevc_put_hevc_bi_qpel_v%1_%2, 8, 10, 16, dst, dststride, src, srcstride, src2, height, r3src, my, rfilter
+cglobal hevc_put_hevc_bi_qpel_v%1_%2, 6, 10, 16, dst, dststride, src, srcstride, src2, height, r3src, my, rfilter
+    movifnidn        myd, mym
     movdqa            m9, [pw_bi_%2]
     lea           r3srcq, [srcstrideq*3]
     QPEL_FILTER       %2, my
 .loop
-    SIMPLE_BILOAD     %1, src2q, m10, m11
     QPEL_V_LOAD       %2, srcq, srcstride, %1, r9
-    QPEL_COMPUTE      %1, %2
+    QPEL_COMPUTE      %1, %2, 1
 %if %2 > 8
     packssdw          m0, m1
 %endif
-    BI_COMPUTE        %1, %2, m0, m1, m10, m11, m9
+    SIMPLE_BILOAD     %1, src2q, m10, m11
+    BI_COMPUTE        %1, %2, m0, m1, m10, m11, m9, 1
     PEL_%2STORE%1   dstq, m0, m1
     add             dstq, dststrideq             ; dst += dststride
     add             srcq, srcstrideq             ; src += srcstride
@@ -925,8 +1170,15 @@
 ; ******************************
 %macro HEVC_PUT_HEVC_QPEL_HV 2
 cglobal hevc_put_hevc_qpel_hv%1_%2, 6, 8, 16, dst, src, srcstride, height, mx, my, r3src, rfilter
-    lea              mxq, [mxq*8-8]
-    lea              myq, [myq*8-8]
+%if cpuflag(avx2)
+%assign %%shift  4
+%else
+%assign %%shift  3
+%endif
+    sub              mxq, 1
+    sub              myq, 1
+    shl              mxq, %%shift                ; multiply by 32
+    shl              myq, %%shift                ; multiply by 32
     lea           r3srcq, [srcstrideq*3]
     sub             srcq, r3srcq
     QPEL_H_LOAD       %2, srcq, %1, 15
@@ -994,8 +1246,15 @@
     RET
 
 cglobal hevc_put_hevc_uni_qpel_hv%1_%2, 7, 9, 16 , dst, dststride, src, srcstride, height, mx, my, r3src, rfilter
-    lea              mxq, [mxq*8-8]
-    lea              myq, [myq*8-8]
+%if cpuflag(avx2)
+%assign %%shift  4
+%else
+%assign %%shift  3
+%endif
+    sub              mxq, 1
+    sub              myq, 1
+    shl              mxq, %%shift                ; multiply by 32
+    shl              myq, %%shift                ; multiply by 32
     lea           r3srcq, [srcstrideq*3]
     sub             srcq, r3srcq
     QPEL_H_LOAD       %2, srcq, %1, 15
@@ -1053,13 +1312,13 @@
     movq             m13, m14
     movq             m14, m15
 %else
-    movdqa            m8, m9
-    movdqa            m9, m10
-    movdqa           m10, m11
-    movdqa           m11, m12
-    movdqa           m12, m13
-    movdqa           m13, m14
-    movdqa           m14, m15
+    mova            m8, m9
+    mova            m9, m10
+    mova           m10, m11
+    mova           m11, m12
+    mova           m12, m13
+    mova           m13, m14
+    mova           m14, m15
 %endif
     add             dstq, dststrideq             ; dst += dststride
     add             srcq, srcstrideq             ; src += srcstride
@@ -1068,8 +1327,15 @@
     RET
 
 cglobal hevc_put_hevc_bi_qpel_hv%1_%2, 8, 10, 16, dst, dststride, src, srcstride, src2, height, mx, my, r3src, rfilter
-    lea              mxq, [mxq*8-8]
-    lea              myq, [myq*8-8]
+%if cpuflag(avx2)
+%assign %%shift  4
+%else
+%assign %%shift  3
+%endif
+    sub              mxq, 1
+    sub              myq, 1
+    shl              mxq, %%shift                ; multiply by 32
+    shl              myq, %%shift                ; multiply by 32
     lea           r3srcq, [srcstrideq*3]
     sub             srcq, r3srcq
     QPEL_H_LOAD       %2, srcq, %1, 15
@@ -1146,11 +1412,11 @@
 
 %macro WEIGHTING_FUNCS 2
 %if WIN64 || ARCH_X86_32
-cglobal hevc_put_hevc_uni_w%1_%2, 4, 5, 7, dst, dststride, src, srcstride, height, denom, wx, ox
+cglobal hevc_put_hevc_uni_w%1_%2, 4, 5, 7, dst, dststride, src, height, denom, wx, ox
     mov             r4d, denomm
 %define SHIFT  r4d
 %else
-cglobal hevc_put_hevc_uni_w%1_%2, 6, 6, 7, dst, dststride, src, srcstride, height, denom, wx, ox
+cglobal hevc_put_hevc_uni_w%1_%2, 6, 6, 7, dst, dststride, src, height, denom, wx, ox
 %define SHIFT  denomd
 %endif
     lea           SHIFT, [SHIFT+14-%2]          ; shift = 14 - bitd + denom
@@ -1165,7 +1431,7 @@
     punpcklwd        m2, m2
 %endif
     dec           SHIFT
-    movdqu           m5, [one_per_32]
+    movdqu           m5, [pd_1]
     movd             m6, SHIFT
     pshufd           m2, m2, 0
     mov           SHIFT, oxm
@@ -1202,8 +1468,7 @@
 %if %2 == 8
     packuswb          m0, m0
 %else
-    pminsw            m0, [max_pixels_%2]
-    pmaxsw            m0, [zero]
+    CLIPW             m0, [pb_0], [max_pixels_%2]
 %endif
     PEL_%2STORE%1   dstq, m0, m1
     add             dstq, dststrideq             ; dst += dststride
@@ -1212,15 +1477,15 @@
     jnz               .loop                      ; height loop
     RET
 
-cglobal hevc_put_hevc_bi_w%1_%2, 5, 7, 10, dst, dststride, src, srcstride, src2, height, denom, wx0, wx1, ox0, ox1
-    mov              r6d, denomm
+cglobal hevc_put_hevc_bi_w%1_%2, 4, 6, 10, dst, dststride, src, src2, height, denom, wx0, wx1, ox0, ox1
+    movifnidn        r5d, denomm
 %if %1 <= 4
     pxor              m1, m1
 %endif
     movd              m2, wx0m         ; WX0
-    lea              r6d, [r6d+14-%2]  ; shift = 14 - bitd + denom
+    lea              r5d, [r5d+14-%2]  ; shift = 14 - bitd + denom
     movd              m3, wx1m         ; WX1
-    movd              m0, r6d          ; shift
+    movd              m0, r5d          ; shift
 %if %1 <= 4
     punpcklwd         m2, m1
     punpcklwd         m3, m1
@@ -1228,19 +1493,24 @@
     punpcklwd         m2, m2
     punpcklwd         m3, m3
 %endif
-    inc              r6d
-    movd              m5, r6d          ; shift+1
+    inc              r5d
+    movd              m5, r5d          ; shift+1
     pshufd            m2, m2, 0
-    mov              r6d, ox0m
+    mov              r5d, ox0m
     pshufd            m3, m3, 0
-    add              r6d, ox1m
+    add              r5d, ox1m
 %if %2 != 8
-    shl              r6d, %2-8         ; ox << (bitd - 8)
+    shl              r5d, %2-8         ; ox << (bitd - 8)
 %endif
-    inc              r6d
-    movd              m4, r6d          ; offset
+    inc              r5d
+    movd              m4, r5d          ; offset
     pshufd            m4, m4, 0
-    mov              r6d, heightm
+%if UNIX64
+%define h heightd
+%else
+    mov              r5d, heightm
+%define h r5d
+%endif
     pslld             m4, m0
 
 .loop
@@ -1274,18 +1544,19 @@
 %if %2 == 8
     packuswb          m0, m0
 %else
-    pminsw            m0, [max_pixels_%2]
-    pmaxsw            m0, [zero]
+     CLIPW            m0, [pb_0], [max_pixels_%2]
 %endif
     PEL_%2STORE%1   dstq, m0, m1
     add             dstq, dststrideq             ; dst += dststride
     add             srcq, 2*MAX_PB_SIZE          ; src += srcstride
     add            src2q, 2*MAX_PB_SIZE          ; src2 += srcstride
-    dec              r6d                         ; cmp height
+    dec                h                         ; cmp height
     jnz               .loop                      ; height loop
     RET
 %endmacro
 
+INIT_XMM sse4                                    ; adds ff_ and _sse4 to function name
+
 WEIGHTING_FUNCS 2, 8
 WEIGHTING_FUNCS 4, 8
 WEIGHTING_FUNCS 6, 8
@@ -1340,6 +1611,7 @@
 HEVC_PUT_HEVC_EPEL_HV 4,  8
 HEVC_PUT_HEVC_EPEL_HV 6,  8
 HEVC_PUT_HEVC_EPEL_HV 8,  8
+HEVC_PUT_HEVC_EPEL_HV 16, 8
 
 HEVC_PUT_HEVC_EPEL_HV 2, 10
 HEVC_PUT_HEVC_EPEL_HV 4, 10
@@ -1377,4 +1649,23 @@
 HEVC_PUT_HEVC_QPEL_HV 6, 12
 HEVC_PUT_HEVC_QPEL_HV 8, 12
 
+%if HAVE_AVX2_EXTERNAL
+INIT_YMM avx2  ; adds ff_ and _avx2 to function name & enables 256b registers : m0 for 256b, xm0 for 128b. cpuflag(avx2) = 1 / notcpuflag(avx) = 0
+
+HEVC_PUT_HEVC_PEL_PIXELS 32, 8
+HEVC_PUT_HEVC_PEL_PIXELS 16, 10
+
+HEVC_PUT_HEVC_EPEL 32, 8
+HEVC_PUT_HEVC_EPEL 16, 10
+
+HEVC_PUT_HEVC_EPEL_HV 16, 10
+HEVC_PUT_HEVC_EPEL_HV 32, 8
+
+HEVC_PUT_HEVC_QPEL 32, 8
+
+HEVC_PUT_HEVC_QPEL 16, 10
+
+HEVC_PUT_HEVC_QPEL_HV 16, 10
+
+%endif ;AVX2
 %endif ; ARCH_X86_64
diff --git a/libavcodec/x86/hevc_res_add.asm b/libavcodec/x86/hevc_res_add.asm
index 24b88ee..dc3e88a 100644
--- a/libavcodec/x86/hevc_res_add.asm
+++ b/libavcodec/x86/hevc_res_add.asm
@@ -20,12 +20,12 @@
 ; */
 %include "libavutil/x86/x86util.asm"
 
-SECTION_RODATA 32
-max_pixels_10:          times 16  dw ((1 << 10)-1)
-
-
 SECTION .text
 
+cextern pw_1023
+%define max_pixels_10 pw_1023
+
+
 ;the tr_add macros and functions were largely inspired by x264 project's code in the h264_idct.asm file
 %macro TR_ADD_MMX_4_8 0
     mova              m2, [r1]
diff --git a/libavcodec/x86/hevc_sao.asm b/libavcodec/x86/hevc_sao.asm
new file mode 100644
index 0000000..86ef847
--- /dev/null
+++ b/libavcodec/x86/hevc_sao.asm
@@ -0,0 +1,624 @@
+;******************************************************************************
+;* SIMD optimized SAO functions for HEVC decoding
+;*
+;* Copyright (c) 2013 Pierre-Edouard LEPERE
+;* Copyright (c) 2014 James Almer
+;*
+;* 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
+
+pw_mask10: times 16 dw 0x03FF
+pw_mask12: times 16 dw 0x0FFF
+pw_m2:     times 16 dw -2
+pb_edge_shuffle: times 2 db 1, 2, 0, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
+pb_eo:                   db -1, 0, 1, 0, 0, -1, 0, 1, -1, -1, 1, 1, 1, -1, -1, 1
+cextern pw_m1
+cextern pw_1
+cextern pw_2
+cextern pb_1
+cextern pb_2
+
+SECTION_TEXT
+
+%define MAX_PB_SIZE  64
+%define PADDING_SIZE 32 ; FF_INPUT_BUFFER_PADDING_SIZE
+
+;******************************************************************************
+;SAO Band Filter
+;******************************************************************************
+
+%macro HEVC_SAO_BAND_FILTER_INIT 1
+    and            leftq, 31
+    movd             xm0, leftd
+    add            leftq, 1
+    and            leftq, 31
+    movd             xm1, leftd
+    add            leftq, 1
+    and            leftq, 31
+    movd             xm2, leftd
+    add            leftq, 1
+    and            leftq, 31
+    movd             xm3, leftd
+
+    SPLATW            m0, xm0
+    SPLATW            m1, xm1
+    SPLATW            m2, xm2
+    SPLATW            m3, xm3
+%if mmsize > 16
+    SPLATW            m4, [offsetq + 2]
+    SPLATW            m5, [offsetq + 4]
+    SPLATW            m6, [offsetq + 6]
+    SPLATW            m7, [offsetq + 8]
+%else
+    movq              m7, [offsetq + 2]
+    SPLATW            m4, m7, 0
+    SPLATW            m5, m7, 1
+    SPLATW            m6, m7, 2
+    SPLATW            m7, m7, 3
+%endif
+
+%if ARCH_X86_64
+%if %1 > 8
+    mova             m13, [pw_mask %+ %1]
+%endif
+    pxor             m14, m14
+
+%else ; ARCH_X86_32
+    mova  [rsp+mmsize*0], m0
+    mova  [rsp+mmsize*1], m1
+    mova  [rsp+mmsize*2], m2
+    mova  [rsp+mmsize*3], m3
+    mova  [rsp+mmsize*4], m4
+    mova  [rsp+mmsize*5], m5
+    mova  [rsp+mmsize*6], m6
+    pxor              m0, m0
+%if %1 > 8
+    mova              m1, [pw_mask %+ %1]
+%endif
+    %assign MMSIZE mmsize
+    %define m14 m0
+    %define m13 m1
+    %define  m9 m2
+    %define  m8 m3
+%endif ; ARCH
+DEFINE_ARGS dst, src, dststride, srcstride, offset, height
+    mov          heightd, r7m
+%endmacro
+
+%macro HEVC_SAO_BAND_FILTER_COMPUTE 3
+    psraw             %2, %3, %1-5
+%if ARCH_X86_64
+    pcmpeqw          m10, %2, m0
+    pcmpeqw          m11, %2, m1
+    pcmpeqw          m12, %2, m2
+    pcmpeqw           %2, m3
+    pand             m10, m4
+    pand             m11, m5
+    pand             m12, m6
+    pand              %2, m7
+    por              m10, m11
+    por              m12, %2
+    por              m10, m12
+    paddw             %3, m10
+%else ; ARCH_X86_32
+    pcmpeqw           m4, %2, [rsp+MMSIZE*0]
+    pcmpeqw           m5, %2, [rsp+MMSIZE*1]
+    pcmpeqw           m6, %2, [rsp+MMSIZE*2]
+    pcmpeqw           %2, [rsp+MMSIZE*3]
+    pand              m4, [rsp+MMSIZE*4]
+    pand              m5, [rsp+MMSIZE*5]
+    pand              m6, [rsp+MMSIZE*6]
+    pand              %2, m7
+    por               m4, m5
+    por               m6, %2
+    por               m4, m6
+    paddw             %3, m4
+%endif ; ARCH
+%endmacro
+
+;void ff_hevc_sao_band_filter_<width>_8_<opt>(uint8_t *_dst, uint8_t *_src, ptrdiff_t _stride_dst, ptrdiff_t _stride_src,
+;                                             int16_t *sao_offset_val, int sao_left_class, int width, int height);
+%macro HEVC_SAO_BAND_FILTER_8 2
+cglobal hevc_sao_band_filter_%1_8, 6, 6, 15, 7*mmsize*ARCH_X86_32, dst, src, dststride, srcstride, offset, left
+    HEVC_SAO_BAND_FILTER_INIT 8
+
+align 16
+.loop
+%if %1 == 8
+    movq              m8, [srcq]
+    punpcklbw         m8, m14
+    HEVC_SAO_BAND_FILTER_COMPUTE 8, m9, m8
+    packuswb          m8, m14
+    movq          [dstq], m8
+%endif ; %1 == 8
+
+%assign i 0
+%rep %2
+    mova             m13, [srcq + i]
+    punpcklbw         m8, m13, m14
+    HEVC_SAO_BAND_FILTER_COMPUTE 8, m9,  m8
+    punpckhbw        m13, m14
+    HEVC_SAO_BAND_FILTER_COMPUTE 8, m9, m13
+    packuswb          m8, m13
+    mova      [dstq + i], m8
+%assign i i+mmsize
+%endrep
+
+%if %1 == 48
+INIT_XMM cpuname
+
+    mova             m13, [srcq + i]
+    punpcklbw         m8, m13, m14
+    HEVC_SAO_BAND_FILTER_COMPUTE 8, m9,  m8
+    punpckhbw        m13, m14
+    HEVC_SAO_BAND_FILTER_COMPUTE 8, m9, m13
+    packuswb          m8, m13
+    mova      [dstq + i], m8
+%if cpuflag(avx2)
+INIT_YMM cpuname
+%endif
+%endif ; %1 == 48
+
+    add             dstq, dststrideq             ; dst += dststride
+    add             srcq, srcstrideq             ; src += srcstride
+    dec          heightd                         ; cmp height
+    jnz               .loop                      ; height loop
+    REP_RET
+%endmacro
+
+;void ff_hevc_sao_band_filter_<width>_<depth>_<opt>(uint8_t *_dst, uint8_t *_src, ptrdiff_t _stride_dst, ptrdiff_t _stride_src,
+;                                                   int16_t *sao_offset_val, int sao_left_class, int width, int height);
+%macro HEVC_SAO_BAND_FILTER_16 3
+cglobal hevc_sao_band_filter_%2_%1, 6, 6, 15, 7*mmsize*ARCH_X86_32, dst, src, dststride, srcstride, offset, left
+    HEVC_SAO_BAND_FILTER_INIT %1
+
+align 16
+.loop
+%if %2 == 8
+    movu              m8, [srcq]
+    HEVC_SAO_BAND_FILTER_COMPUTE %1, m9, m8
+    CLIPW             m8, m14, m13
+    movu          [dstq], m8
+%endif
+
+%assign i 0
+%rep %3
+    mova              m8, [srcq + i]
+    HEVC_SAO_BAND_FILTER_COMPUTE %1, m9, m8
+    CLIPW             m8, m14, m13
+    mova      [dstq + i], m8
+
+    mova              m9, [srcq + i + mmsize]
+    HEVC_SAO_BAND_FILTER_COMPUTE %1, m8, m9
+    CLIPW             m9, m14, m13
+    mova      [dstq + i + mmsize], m9
+%assign i i+mmsize*2
+%endrep
+
+%if %2 == 48
+INIT_XMM cpuname
+    mova              m8, [srcq + i]
+    HEVC_SAO_BAND_FILTER_COMPUTE %1, m9, m8
+    CLIPW             m8, m14, m13
+    mova      [dstq + i], m8
+
+    mova              m9, [srcq + i + mmsize]
+    HEVC_SAO_BAND_FILTER_COMPUTE %1, m8, m9
+    CLIPW             m9, m14, m13
+    mova      [dstq + i + mmsize], m9
+%if cpuflag(avx2)
+INIT_YMM cpuname
+%endif
+%endif ; %1 == 48
+
+    add             dstq, dststrideq
+    add             srcq, srcstrideq
+    dec          heightd
+    jg .loop
+    REP_RET
+%endmacro
+
+%macro HEVC_SAO_BAND_FILTER_FUNCS 0
+HEVC_SAO_BAND_FILTER_8       8, 0
+HEVC_SAO_BAND_FILTER_8      16, 1
+HEVC_SAO_BAND_FILTER_8      32, 2
+HEVC_SAO_BAND_FILTER_8      48, 2
+HEVC_SAO_BAND_FILTER_8      64, 4
+
+HEVC_SAO_BAND_FILTER_16 10,  8, 0
+HEVC_SAO_BAND_FILTER_16 10, 16, 1
+HEVC_SAO_BAND_FILTER_16 10, 32, 2
+HEVC_SAO_BAND_FILTER_16 10, 48, 2
+HEVC_SAO_BAND_FILTER_16 10, 64, 4
+
+HEVC_SAO_BAND_FILTER_16 12,  8, 0
+HEVC_SAO_BAND_FILTER_16 12, 16, 1
+HEVC_SAO_BAND_FILTER_16 12, 32, 2
+HEVC_SAO_BAND_FILTER_16 12, 48, 2
+HEVC_SAO_BAND_FILTER_16 12, 64, 4
+%endmacro
+
+INIT_XMM sse2
+HEVC_SAO_BAND_FILTER_FUNCS
+INIT_XMM avx
+HEVC_SAO_BAND_FILTER_FUNCS
+
+%if HAVE_AVX2_EXTERNAL
+INIT_XMM avx2
+HEVC_SAO_BAND_FILTER_8       8, 0
+HEVC_SAO_BAND_FILTER_8      16, 1
+INIT_YMM avx2
+HEVC_SAO_BAND_FILTER_8      32, 1
+HEVC_SAO_BAND_FILTER_8      48, 1
+HEVC_SAO_BAND_FILTER_8      64, 2
+
+INIT_XMM avx2
+HEVC_SAO_BAND_FILTER_16 10,  8, 0
+HEVC_SAO_BAND_FILTER_16 10, 16, 1
+INIT_YMM avx2
+HEVC_SAO_BAND_FILTER_16 10, 32, 1
+HEVC_SAO_BAND_FILTER_16 10, 48, 1
+HEVC_SAO_BAND_FILTER_16 10, 64, 2
+
+INIT_XMM avx2
+HEVC_SAO_BAND_FILTER_16 12,  8, 0
+HEVC_SAO_BAND_FILTER_16 12, 16, 1
+INIT_YMM avx2
+HEVC_SAO_BAND_FILTER_16 12, 32, 1
+HEVC_SAO_BAND_FILTER_16 12, 48, 1
+HEVC_SAO_BAND_FILTER_16 12, 64, 2
+%endif
+
+;******************************************************************************
+;SAO Edge Filter
+;******************************************************************************
+
+%define EDGE_SRCSTRIDE 2 * MAX_PB_SIZE + PADDING_SIZE
+
+%macro HEVC_SAO_EDGE_FILTER_INIT 1
+%if WIN64
+    movsxd           eoq, dword eom
+%elif ARCH_X86_64
+    movsxd           eoq, eod
+%else
+    mov              eoq, r4m
+%endif
+    lea            tmp2q, [pb_eo]
+    movsx      a_strideq, byte [tmp2q+eoq*4+1]
+    movsx      b_strideq, byte [tmp2q+eoq*4+3]
+    imul       a_strideq, EDGE_SRCSTRIDE>>%1
+    imul       b_strideq, EDGE_SRCSTRIDE>>%1
+    movsx           tmpq, byte [tmp2q+eoq*4]
+    add        a_strideq, tmpq
+    movsx           tmpq, byte [tmp2q+eoq*4+2]
+    add        b_strideq, tmpq
+%endmacro
+
+%macro HEVC_SAO_EDGE_FILTER_COMPUTE_8 1
+    pminub            m4, m1, m2
+    pminub            m5, m1, m3
+    pcmpeqb           m2, m4
+    pcmpeqb           m3, m5
+    pcmpeqb           m4, m1
+    pcmpeqb           m5, m1
+    psubb             m4, m2
+    psubb             m5, m3
+    paddb             m4, m6
+    paddb             m4, m5
+
+    pshufb            m2, m0, m4
+%if %1 > 8
+    punpckhbw         m5, m7, m1
+    punpckhbw         m4, m2, m7
+    punpcklbw         m3, m7, m1
+    punpcklbw         m2, m7
+    pmaddubsw         m5, m4
+    pmaddubsw         m3, m2
+    packuswb          m3, m5
+%else
+    punpcklbw         m3, m7, m1
+    punpcklbw         m2, m7
+    pmaddubsw         m3, m2
+    packuswb          m3, m3
+%endif
+%endmacro
+
+;void ff_hevc_sao_edge_filter_<width>_8_<opt>(uint8_t *_dst, uint8_t *_src, ptrdiff_t stride_dst, int16_t *sao_offset_val,
+;                                             int eo, int width, int height);
+%macro HEVC_SAO_EDGE_FILTER_8 2-3
+%if ARCH_X86_64
+cglobal hevc_sao_edge_filter_%1_8, 4, 9, 8, dst, src, dststride, offset, eo, a_stride, b_stride, height, tmp
+%define tmp2q heightq
+    HEVC_SAO_EDGE_FILTER_INIT 0
+    mov          heightd, r6m
+
+%else ; ARCH_X86_32
+cglobal hevc_sao_edge_filter_%1_8, 1, 6, 8, dst, src, dststride, a_stride, b_stride, height
+%define eoq   srcq
+%define tmpq  heightq
+%define tmp2q dststrideq
+%define offsetq heightq
+    HEVC_SAO_EDGE_FILTER_INIT 0
+    mov             srcq, srcm
+    mov          offsetq, r3m
+    mov       dststrideq, dststridem
+%endif ; ARCH
+
+%if mmsize > 16
+    vbroadcasti128    m0, [offsetq]
+%else
+    movu              m0, [offsetq]
+%endif
+    mova              m1, [pb_edge_shuffle]
+    packsswb          m0, m0
+    mova              m7, [pb_1]
+    pshufb            m0, m1
+    mova              m6, [pb_2]
+%if ARCH_X86_32
+    mov          heightd, r6m
+%endif
+
+align 16
+.loop:
+
+%if %1 == 8
+    movq              m1, [srcq]
+    movq              m2, [srcq + a_strideq]
+    movq              m3, [srcq + b_strideq]
+    HEVC_SAO_EDGE_FILTER_COMPUTE_8 %1
+    movq          [dstq], m3
+%endif
+
+%assign i 0
+%rep %2
+    mova              m1, [srcq + i]
+    movu              m2, [srcq + a_strideq + i]
+    movu              m3, [srcq + b_strideq + i]
+    HEVC_SAO_EDGE_FILTER_COMPUTE_8 %1
+    mov%3     [dstq + i], m3
+%assign i i+mmsize
+%endrep
+
+%if %1 == 48
+INIT_XMM cpuname
+
+    mova              m1, [srcq + i]
+    movu              m2, [srcq + a_strideq + i]
+    movu              m3, [srcq + b_strideq + i]
+    HEVC_SAO_EDGE_FILTER_COMPUTE_8 %1
+    mova      [dstq + i], m3
+%if cpuflag(avx2)
+INIT_YMM cpuname
+%endif
+%endif
+
+    add             dstq, dststrideq
+    add             srcq, EDGE_SRCSTRIDE
+    dec          heightd
+    jg .loop
+    RET
+%endmacro
+
+%macro PMINUW 4
+%if cpuflag(sse4)
+    pminuw            %1, %2, %3
+%else
+    psubusw           %4, %2, %3
+    psubw             %1, %2, %4
+%endif
+%endmacro
+
+%macro HEVC_SAO_EDGE_FILTER_COMPUTE_10 0
+    PMINUW            m4, m1, m2, m6
+    PMINUW            m5, m1, m3, m7
+    pcmpeqw           m2, m4
+    pcmpeqw           m3, m5
+    pcmpeqw           m4, m1
+    pcmpeqw           m5, m1
+    psubw             m4, m2
+    psubw             m5, m3
+
+    paddw             m4, m5
+    pcmpeqw           m2, m4, [pw_m2]
+%if ARCH_X86_64
+    pcmpeqw           m3, m4, m13
+    pcmpeqw           m5, m4, m0
+    pcmpeqw           m6, m4, m14
+    pcmpeqw           m7, m4, m15
+    pand              m2, m8
+    pand              m3, m9
+    pand              m5, m10
+    pand              m6, m11
+    pand              m7, m12
+%else
+    pcmpeqw           m3, m4, [pw_m1]
+    pcmpeqw           m5, m4, m0
+    pcmpeqw           m6, m4, [pw_1]
+    pcmpeqw           m7, m4, [pw_2]
+    pand              m2, [rsp+MMSIZE*0]
+    pand              m3, [rsp+MMSIZE*1]
+    pand              m5, [rsp+MMSIZE*2]
+    pand              m6, [rsp+MMSIZE*3]
+    pand              m7, [rsp+MMSIZE*4]
+%endif
+    paddw             m2, m3
+    paddw             m5, m6
+    paddw             m2, m7
+    paddw             m2, m1
+    paddw             m2, m5
+%endmacro
+
+;void ff_hevc_sao_edge_filter_<width>_<depth>_<opt>(uint8_t *_dst, uint8_t *_src, ptrdiff_t stride_dst, int16_t *sao_offset_val,
+;                                                   int eo, int width, int height);
+%macro HEVC_SAO_EDGE_FILTER_16 3
+%if ARCH_X86_64
+cglobal hevc_sao_edge_filter_%2_%1, 4, 9, 16, dst, src, dststride, offset, eo, a_stride, b_stride, height, tmp
+%define tmp2q heightq
+    HEVC_SAO_EDGE_FILTER_INIT 1
+    mov          heightd, r6m
+    add        a_strideq, a_strideq
+    add        b_strideq, b_strideq
+
+%else ; ARCH_X86_32
+cglobal hevc_sao_edge_filter_%2_%1, 1, 6, 8, 5*mmsize, dst, src, dststride, a_stride, b_stride, height
+%assign MMSIZE mmsize
+%define eoq   srcq
+%define tmpq  heightq
+%define tmp2q dststrideq
+%define offsetq heightq
+%define m8 m1
+%define m9 m2
+%define m10 m3
+%define m11 m4
+%define m12 m5
+    HEVC_SAO_EDGE_FILTER_INIT 1
+    mov             srcq, srcm
+    mov          offsetq, r3m
+    mov       dststrideq, dststridem
+    add        a_strideq, a_strideq
+    add        b_strideq, b_strideq
+
+%endif ; ARCH
+
+%if cpuflag(avx2)
+    SPLATW            m8, [offsetq+2]
+    SPLATW            m9, [offsetq+4]
+    SPLATW           m10, [offsetq+0]
+    SPLATW           m11, [offsetq+6]
+    SPLATW           m12, [offsetq+8]
+%else
+    movq             m10, [offsetq+0]
+    movd             m12, [offsetq+6]
+    SPLATW            m8, xm10, 1
+    SPLATW            m9, xm10, 2
+    SPLATW           m10, xm10, 0
+    SPLATW           m11, xm12, 0
+    SPLATW           m12, xm12, 1
+%endif
+    pxor              m0, m0
+%if ARCH_X86_64
+    mova             m13, [pw_m1]
+    mova             m14, [pw_1]
+    mova             m15, [pw_2]
+%else
+    mov          heightd, r6m
+    mova  [rsp+mmsize*0], m8
+    mova  [rsp+mmsize*1], m9
+    mova  [rsp+mmsize*2], m10
+    mova  [rsp+mmsize*3], m11
+    mova  [rsp+mmsize*4], m12
+%endif
+
+align 16
+.loop
+
+%if %2 == 8
+    mova              m1, [srcq]
+    movu              m2, [srcq+a_strideq]
+    movu              m3, [srcq+b_strideq]
+
+    HEVC_SAO_EDGE_FILTER_COMPUTE_10
+    CLIPW             m2, m0, [pw_mask %+ %1]
+    movu          [dstq], m2
+%endif
+
+%assign i 0
+%rep %3
+    mova              m1, [srcq + i]
+    movu              m2, [srcq+a_strideq + i]
+    movu              m3, [srcq+b_strideq + i]
+    HEVC_SAO_EDGE_FILTER_COMPUTE_10
+    CLIPW             m2, m0, [pw_mask %+ %1]
+    mova      [dstq + i], m2
+
+    mova              m1, [srcq + i + mmsize]
+    movu              m2, [srcq+a_strideq + i + mmsize]
+    movu              m3, [srcq+b_strideq + i + mmsize]
+    HEVC_SAO_EDGE_FILTER_COMPUTE_10
+    CLIPW             m2, m0, [pw_mask %+ %1]
+    mova [dstq + i + mmsize], m2
+%assign i i+mmsize*2
+%endrep
+
+%if %2 == 48
+INIT_XMM cpuname
+    mova              m1, [srcq + i]
+    movu              m2, [srcq+a_strideq + i]
+    movu              m3, [srcq+b_strideq + i]
+    HEVC_SAO_EDGE_FILTER_COMPUTE_10
+    CLIPW             m2, m0, [pw_mask %+ %1]
+    mova              [dstq + i], m2
+
+    mova              m1, [srcq + i + mmsize]
+    movu              m2, [srcq+a_strideq + i + mmsize]
+    movu              m3, [srcq+b_strideq + i + mmsize]
+    HEVC_SAO_EDGE_FILTER_COMPUTE_10
+    CLIPW             m2, m0, [pw_mask %+ %1]
+    mova [dstq + i + mmsize], m2
+%if cpuflag(avx2)
+INIT_YMM cpuname
+%endif
+%endif
+
+    add             dstq, dststrideq
+    add             srcq, EDGE_SRCSTRIDE
+    dec          heightd
+    jg .loop
+    RET
+%endmacro
+
+INIT_XMM ssse3
+HEVC_SAO_EDGE_FILTER_8       8, 0
+HEVC_SAO_EDGE_FILTER_8      16, 1, a
+HEVC_SAO_EDGE_FILTER_8      32, 2, a
+HEVC_SAO_EDGE_FILTER_8      48, 2, a
+HEVC_SAO_EDGE_FILTER_8      64, 4, a
+
+%if HAVE_AVX2_EXTERNAL
+INIT_YMM avx2
+HEVC_SAO_EDGE_FILTER_8      32, 1, a
+HEVC_SAO_EDGE_FILTER_8      48, 1, u
+HEVC_SAO_EDGE_FILTER_8      64, 2, a
+%endif
+
+INIT_XMM sse2
+HEVC_SAO_EDGE_FILTER_16 10,  8, 0
+HEVC_SAO_EDGE_FILTER_16 10, 16, 1
+HEVC_SAO_EDGE_FILTER_16 10, 32, 2
+HEVC_SAO_EDGE_FILTER_16 10, 48, 2
+HEVC_SAO_EDGE_FILTER_16 10, 64, 4
+
+HEVC_SAO_EDGE_FILTER_16 12,  8, 0
+HEVC_SAO_EDGE_FILTER_16 12, 16, 1
+HEVC_SAO_EDGE_FILTER_16 12, 32, 2
+HEVC_SAO_EDGE_FILTER_16 12, 48, 2
+HEVC_SAO_EDGE_FILTER_16 12, 64, 4
+
+%if HAVE_AVX2_EXTERNAL
+INIT_YMM avx2
+HEVC_SAO_EDGE_FILTER_16 10, 32, 1
+HEVC_SAO_EDGE_FILTER_16 10, 48, 1
+HEVC_SAO_EDGE_FILTER_16 10, 64, 2
+
+HEVC_SAO_EDGE_FILTER_16 12, 32, 1
+HEVC_SAO_EDGE_FILTER_16 12, 48, 1
+HEVC_SAO_EDGE_FILTER_16 12, 64, 2
+%endif
diff --git a/libavcodec/x86/hevcdsp.h b/libavcodec/x86/hevcdsp.h
index 8dea142..ad8168f 100644
--- a/libavcodec/x86/hevcdsp.h
+++ b/libavcodec/x86/hevcdsp.h
@@ -74,8 +74,8 @@
         PEL_PROTOTYPE(fname##64, bitd, opt)
 
 #define WEIGHTING_PROTOTYPE(width, bitd, opt) \
-void ff_hevc_put_hevc_uni_w##width##_##bitd##_##opt(uint8_t *dst, ptrdiff_t dststride, int16_t *_src, ptrdiff_t _srcstride, int height, int denom,  int _wx, int _ox); \
-void ff_hevc_put_hevc_bi_w##width##_##bitd##_##opt(uint8_t *dst, ptrdiff_t dststride, int16_t *_src, ptrdiff_t _srcstride, int16_t *_src2, int height, int denom,  int _wx0,  int _wx1, int _ox0, int _ox1)
+void ff_hevc_put_hevc_uni_w##width##_##bitd##_##opt(uint8_t *dst, ptrdiff_t dststride, int16_t *_src, int height, int denom,  int _wx, int _ox); \
+void ff_hevc_put_hevc_bi_w##width##_##bitd##_##opt(uint8_t *dst, ptrdiff_t dststride, int16_t *_src, int16_t *_src2, int height, int denom,  int _wx0,  int _wx1, int _ox0, int _ox1)
 
 #define WEIGHTING_PROTOTYPES(bitd, opt) \
         WEIGHTING_PROTOTYPE(2, bitd, opt); \
@@ -96,6 +96,40 @@
 EPEL_PROTOTYPES(pel_pixels ,  8, sse4);
 EPEL_PROTOTYPES(pel_pixels , 10, sse4);
 EPEL_PROTOTYPES(pel_pixels , 12, sse4);
+
+void ff_hevc_put_hevc_pel_pixels16_8_avx2(int16_t *dst, uint8_t *_src, ptrdiff_t _srcstride, int height, intptr_t mx, intptr_t my,int width);
+void ff_hevc_put_hevc_pel_pixels24_8_avx2(int16_t *dst, uint8_t *_src, ptrdiff_t _srcstride, int height, intptr_t mx, intptr_t my,int width);
+void ff_hevc_put_hevc_pel_pixels32_8_avx2(int16_t *dst, uint8_t *_src, ptrdiff_t _srcstride, int height, intptr_t mx, intptr_t my,int width);
+void ff_hevc_put_hevc_pel_pixels48_8_avx2(int16_t *dst, uint8_t *_src, ptrdiff_t _srcstride, int height, intptr_t mx, intptr_t my,int width);
+void ff_hevc_put_hevc_pel_pixels64_8_avx2(int16_t *dst, uint8_t *_src, ptrdiff_t _srcstride, int height, intptr_t mx, intptr_t my,int width);
+
+void ff_hevc_put_hevc_pel_pixels16_10_avx2(int16_t *dst, uint8_t *_src, ptrdiff_t _srcstride, int height, intptr_t mx, intptr_t my,int width);
+void ff_hevc_put_hevc_pel_pixels24_10_avx2(int16_t *dst, uint8_t *_src, ptrdiff_t _srcstride, int height, intptr_t mx, intptr_t my,int width);
+void ff_hevc_put_hevc_pel_pixels32_10_avx2(int16_t *dst, uint8_t *_src, ptrdiff_t _srcstride, int height, intptr_t mx, intptr_t my,int width);
+void ff_hevc_put_hevc_pel_pixels48_10_avx2(int16_t *dst, uint8_t *_src, ptrdiff_t _srcstride, int height, intptr_t mx, intptr_t my,int width);
+void ff_hevc_put_hevc_pel_pixels64_10_avx2(int16_t *dst, uint8_t *_src, ptrdiff_t _srcstride, int height, intptr_t mx, intptr_t my,int width);
+
+
+
+void ff_hevc_put_hevc_uni_pel_pixels32_8_avx2(uint8_t *dst, ptrdiff_t dststride,uint8_t *_src, ptrdiff_t _srcstride, int height, intptr_t mx, intptr_t my,int width);
+void ff_hevc_put_hevc_uni_pel_pixels48_8_avx2(uint8_t *dst, ptrdiff_t dststride,uint8_t *_src, ptrdiff_t _srcstride, int height, intptr_t mx, intptr_t my,int width);
+void ff_hevc_put_hevc_uni_pel_pixels64_8_avx2(uint8_t *dst, ptrdiff_t dststride,uint8_t *_src, ptrdiff_t _srcstride, int height, intptr_t mx, intptr_t my,int width);
+void ff_hevc_put_hevc_uni_pel_pixels96_8_avx2(uint8_t *dst, ptrdiff_t dststride,uint8_t *_src, ptrdiff_t _srcstride, int height, intptr_t mx, intptr_t my,int width); //used for 10bit
+void ff_hevc_put_hevc_uni_pel_pixels128_8_avx2(uint8_t *dst, ptrdiff_t dststride,uint8_t *_src, ptrdiff_t _srcstride, int height, intptr_t mx, intptr_t my,int width);//used for 10bit
+
+
+void ff_hevc_put_hevc_bi_pel_pixels16_8_avx2(uint8_t *_dst, ptrdiff_t _dststride, uint8_t *_src, ptrdiff_t _srcstride, int16_t *src2, int height, intptr_t mx, intptr_t my, int width);
+void ff_hevc_put_hevc_bi_pel_pixels24_8_avx2(uint8_t *_dst, ptrdiff_t _dststride, uint8_t *_src, ptrdiff_t _srcstride, int16_t *src2, int height, intptr_t mx, intptr_t my, int width);
+void ff_hevc_put_hevc_bi_pel_pixels32_8_avx2(uint8_t *_dst, ptrdiff_t _dststride, uint8_t *_src, ptrdiff_t _srcstride, int16_t *src2, int height, intptr_t mx, intptr_t my, int width);
+void ff_hevc_put_hevc_bi_pel_pixels48_8_avx2(uint8_t *_dst, ptrdiff_t _dststride, uint8_t *_src, ptrdiff_t _srcstride, int16_t *src2, int height, intptr_t mx, intptr_t my, int width);
+void ff_hevc_put_hevc_bi_pel_pixels64_8_avx2(uint8_t *_dst, ptrdiff_t _dststride, uint8_t *_src, ptrdiff_t _srcstride, int16_t *src2, int height, intptr_t mx, intptr_t my, int width);
+
+void ff_hevc_put_hevc_bi_pel_pixels16_10_avx2(uint8_t *_dst, ptrdiff_t _dststride, uint8_t *_src, ptrdiff_t _srcstride, int16_t *src2, int height, intptr_t mx, intptr_t my, int width);
+void ff_hevc_put_hevc_bi_pel_pixels24_10_avx2(uint8_t *_dst, ptrdiff_t _dststride, uint8_t *_src, ptrdiff_t _srcstride, int16_t *src2, int height, intptr_t mx, intptr_t my, int width);
+void ff_hevc_put_hevc_bi_pel_pixels32_10_avx2(uint8_t *_dst, ptrdiff_t _dststride, uint8_t *_src, ptrdiff_t _srcstride, int16_t *src2, int height, intptr_t mx, intptr_t my, int width);
+void ff_hevc_put_hevc_bi_pel_pixels48_10_avx2(uint8_t *_dst, ptrdiff_t _dststride, uint8_t *_src, ptrdiff_t _srcstride, int16_t *src2, int height, intptr_t mx, intptr_t my, int width);
+void ff_hevc_put_hevc_bi_pel_pixels64_10_avx2(uint8_t *_dst, ptrdiff_t _dststride, uint8_t *_src, ptrdiff_t _srcstride, int16_t *src2, int height, intptr_t mx, intptr_t my, int width);
+
 ///////////////////////////////////////////////////////////////////////////////
 // EPEL
 ///////////////////////////////////////////////////////////////////////////////
@@ -111,6 +145,42 @@
 EPEL_PROTOTYPES(epel_hv , 10, sse4);
 EPEL_PROTOTYPES(epel_hv , 12, sse4);
 
+PEL_PROTOTYPE(epel_h16, 8, avx2);
+PEL_PROTOTYPE(epel_h24, 8, avx2);
+PEL_PROTOTYPE(epel_h32, 8, avx2);
+PEL_PROTOTYPE(epel_h48, 8, avx2);
+PEL_PROTOTYPE(epel_h64, 8, avx2);
+
+PEL_PROTOTYPE(epel_h16,10, avx2);
+PEL_PROTOTYPE(epel_h24,10, avx2);
+PEL_PROTOTYPE(epel_h32,10, avx2);
+PEL_PROTOTYPE(epel_h48,10, avx2);
+PEL_PROTOTYPE(epel_h64,10, avx2);
+
+PEL_PROTOTYPE(epel_v16, 8, avx2);
+PEL_PROTOTYPE(epel_v24, 8, avx2);
+PEL_PROTOTYPE(epel_v32, 8, avx2);
+PEL_PROTOTYPE(epel_v48, 8, avx2);
+PEL_PROTOTYPE(epel_v64, 8, avx2);
+
+PEL_PROTOTYPE(epel_v16,10, avx2);
+PEL_PROTOTYPE(epel_v24,10, avx2);
+PEL_PROTOTYPE(epel_v32,10, avx2);
+PEL_PROTOTYPE(epel_v48,10, avx2);
+PEL_PROTOTYPE(epel_v64,10, avx2);
+
+PEL_PROTOTYPE(epel_hv16, 8, avx2);
+PEL_PROTOTYPE(epel_hv24, 8, avx2);
+PEL_PROTOTYPE(epel_hv32, 8, avx2);
+PEL_PROTOTYPE(epel_hv48, 8, avx2);
+PEL_PROTOTYPE(epel_hv64, 8, avx2);
+
+PEL_PROTOTYPE(epel_hv16,10, avx2);
+PEL_PROTOTYPE(epel_hv24,10, avx2);
+PEL_PROTOTYPE(epel_hv32,10, avx2);
+PEL_PROTOTYPE(epel_hv48,10, avx2);
+PEL_PROTOTYPE(epel_hv64,10, avx2);
+
 ///////////////////////////////////////////////////////////////////////////////
 // QPEL
 ///////////////////////////////////////////////////////////////////////////////
@@ -126,6 +196,41 @@
 QPEL_PROTOTYPES(qpel_hv, 10, sse4);
 QPEL_PROTOTYPES(qpel_hv, 12, sse4);
 
+PEL_PROTOTYPE(qpel_h16, 8, avx2);
+PEL_PROTOTYPE(qpel_h24, 8, avx2);
+PEL_PROTOTYPE(qpel_h32, 8, avx2);
+PEL_PROTOTYPE(qpel_h48, 8, avx2);
+PEL_PROTOTYPE(qpel_h64, 8, avx2);
+
+PEL_PROTOTYPE(qpel_h16,10, avx2);
+PEL_PROTOTYPE(qpel_h24,10, avx2);
+PEL_PROTOTYPE(qpel_h32,10, avx2);
+PEL_PROTOTYPE(qpel_h48,10, avx2);
+PEL_PROTOTYPE(qpel_h64,10, avx2);
+
+PEL_PROTOTYPE(qpel_v16, 8, avx2);
+PEL_PROTOTYPE(qpel_v24, 8, avx2);
+PEL_PROTOTYPE(qpel_v32, 8, avx2);
+PEL_PROTOTYPE(qpel_v48, 8, avx2);
+PEL_PROTOTYPE(qpel_v64, 8, avx2);
+
+PEL_PROTOTYPE(qpel_v16,10, avx2);
+PEL_PROTOTYPE(qpel_v24,10, avx2);
+PEL_PROTOTYPE(qpel_v32,10, avx2);
+PEL_PROTOTYPE(qpel_v48,10, avx2);
+PEL_PROTOTYPE(qpel_v64,10, avx2);
+
+PEL_PROTOTYPE(qpel_hv16, 8, avx2);
+PEL_PROTOTYPE(qpel_hv24, 8, avx2);
+PEL_PROTOTYPE(qpel_hv32, 8, avx2);
+PEL_PROTOTYPE(qpel_hv48, 8, avx2);
+PEL_PROTOTYPE(qpel_hv64, 8, avx2);
+
+PEL_PROTOTYPE(qpel_hv16,10, avx2);
+PEL_PROTOTYPE(qpel_hv24,10, avx2);
+PEL_PROTOTYPE(qpel_hv32,10, avx2);
+PEL_PROTOTYPE(qpel_hv48,10, avx2);
+PEL_PROTOTYPE(qpel_hv64,10, avx2);
 
 WEIGHTING_PROTOTYPES(8, sse4);
 WEIGHTING_PROTOTYPES(10, sse4);
diff --git a/libavcodec/x86/hevcdsp_init.c b/libavcodec/x86/hevcdsp_init.c
index eaa97e1..ddc876d 100644
--- a/libavcodec/x86/hevcdsp_init.c
+++ b/libavcodec/x86/hevcdsp_init.c
@@ -165,6 +165,149 @@
 
 #if ARCH_X86_64 && HAVE_SSE4_EXTERNAL
 
+#define mc_rep_mix_10(name, width1, width2, width3, opt1, opt2, width4)                                       \
+void ff_hevc_put_hevc_##name##width1##_10_##opt1(int16_t *dst, uint8_t *src, ptrdiff_t _srcstride,            \
+                                                 int height, intptr_t mx, intptr_t my, int width)             \
+                                                                                                              \
+{                                                                                                             \
+    ff_hevc_put_hevc_##name##width2##_10_##opt1(dst, src, _srcstride, height, mx, my, width);                 \
+    ff_hevc_put_hevc_##name##width3##_10_##opt2(dst+ width2, src+ width4, _srcstride, height, mx, my, width); \
+}
+
+#define mc_bi_rep_mix_10(name, width1, width2, width3, opt1, opt2, width4)                                    \
+void ff_hevc_put_hevc_bi_##name##width1##_10_##opt1(uint8_t *dst, ptrdiff_t dststride, uint8_t *src,          \
+                                                    ptrdiff_t _srcstride, int16_t *src2,                      \
+                                                    int height, intptr_t mx, intptr_t my, int width)          \
+{                                                                                                             \
+    ff_hevc_put_hevc_bi_##name##width2##_10_##opt1(dst, dststride, src, _srcstride, src2,                     \
+                                                   height, mx, my, width);                                    \
+    ff_hevc_put_hevc_bi_##name##width3##_10_##opt2(dst+width4, dststride, src+width4, _srcstride, src2+width2,\
+                                                   height, mx, my, width);                                    \
+}
+
+#define mc_uni_rep_mix_10(name, width1, width2, width3, opt1, opt2, width4)                                   \
+void ff_hevc_put_hevc_uni_##name##width1##_10_##opt1(uint8_t *dst, ptrdiff_t dststride,                       \
+                                                     uint8_t *src, ptrdiff_t _srcstride, int height,          \
+                                                     intptr_t mx, intptr_t my, int width)                     \
+{                                                                                                             \
+    ff_hevc_put_hevc_uni_##name##width2##_10_##opt1(dst, dststride, src, _srcstride,                          \
+                                                      height, mx, my, width);                                 \
+    ff_hevc_put_hevc_uni_##name##width3##_10_##opt2(dst+width4, dststride, src+width4, _srcstride,            \
+                                                      height, mx, my, width);                                 \
+}
+
+#define mc_rep_mixs_10(name, width1, width2, width3, opt1, opt2, width4)    \
+mc_rep_mix_10(name, width1, width2, width3, opt1, opt2, width4);            \
+mc_bi_rep_mix_10(name, width1, width2, width3, opt1, opt2, width4);         \
+mc_uni_rep_mix_10(name, width1, width2, width3, opt1, opt2, width4)
+
+#define mc_rep_mix_8(name, width1, width2, width3, opt1, opt2)                                                \
+void ff_hevc_put_hevc_##name##width1##_8_##opt1(int16_t *dst, uint8_t *src, ptrdiff_t _srcstride,             \
+                                                int height, intptr_t mx, intptr_t my, int width)              \
+                                                                                                              \
+{                                                                                                             \
+    ff_hevc_put_hevc_##name##width2##_8_##opt1(dst, src, _srcstride, height, mx, my, width);                  \
+    ff_hevc_put_hevc_##name##width3##_8_##opt2(dst+ width2, src+ width2, _srcstride, height, mx, my, width);  \
+}
+
+#define mc_bi_rep_mix_8(name, width1, width2, width3, opt1, opt2)                                             \
+void ff_hevc_put_hevc_bi_##name##width1##_8_##opt1(uint8_t *dst, ptrdiff_t dststride, uint8_t *src,           \
+                                                   ptrdiff_t _srcstride, int16_t* src2,                       \
+                                                   int height, intptr_t mx, intptr_t my, int width)           \
+{                                                                                                             \
+    ff_hevc_put_hevc_bi_##name##width2##_8_##opt1(dst, dststride, src, _srcstride,                            \
+                                                  src2, height, mx, my, width);                               \
+    ff_hevc_put_hevc_bi_##name##width3##_8_##opt2(dst+width2, dststride, src+width2, _srcstride,              \
+                                                  src2+width2, height, mx, my, width);                        \
+}
+
+#define mc_uni_rep_mix_8(name, width1, width2, width3, opt1, opt2)                                            \
+void ff_hevc_put_hevc_uni_##name##width1##_8_##opt1(uint8_t *dst, ptrdiff_t dststride,                        \
+                                                    uint8_t *src, ptrdiff_t _srcstride, int height,           \
+                                                    intptr_t mx, intptr_t my, int width)                      \
+{                                                                                                             \
+    ff_hevc_put_hevc_uni_##name##width2##_8_##opt1(dst, dststride, src, _srcstride,                           \
+                                                   height, mx, my, width);                                    \
+    ff_hevc_put_hevc_uni_##name##width3##_8_##opt2(dst+width2, dststride, src+width2, _srcstride,             \
+                                                   height, mx, my, width);                                    \
+}
+
+#define mc_rep_mixs_8(name, width1, width2, width3, opt1, opt2)    \
+mc_rep_mix_8(name, width1, width2, width3, opt1, opt2);            \
+mc_bi_rep_mix_8(name, width1, width2, width3, opt1, opt2);         \
+mc_uni_rep_mix_8(name, width1, width2, width3, opt1, opt2)
+
+#if HAVE_AVX2_EXTERNAL
+
+mc_rep_mixs_8(pel_pixels, 48, 32, 16, avx2, sse4);
+mc_rep_mixs_8(epel_hv,    48, 32, 16, avx2, sse4);
+mc_rep_mixs_8(epel_h ,    48, 32, 16, avx2, sse4);
+mc_rep_mixs_8(epel_v ,    48, 32, 16, avx2, sse4);
+
+mc_rep_mix_10(pel_pixels, 24, 16, 8, avx2, sse4, 32);
+mc_bi_rep_mix_10(pel_pixels,24, 16, 8, avx2, sse4, 32);
+mc_rep_mixs_10(epel_hv,   24, 16, 8, avx2, sse4, 32);
+mc_rep_mixs_10(epel_h ,   24, 16, 8, avx2, sse4, 32);
+mc_rep_mixs_10(epel_v ,   24, 16, 8, avx2, sse4, 32);
+
+
+mc_rep_mixs_10(qpel_h ,   24, 16, 8, avx2, sse4, 32);
+mc_rep_mixs_10(qpel_v ,   24, 16, 8, avx2, sse4, 32);
+mc_rep_mixs_10(qpel_hv,   24, 16, 8, avx2, sse4, 32);
+
+
+mc_rep_uni_func(pel_pixels, 8, 64, 128, avx2);//used for 10bit
+mc_rep_uni_func(pel_pixels, 8, 32, 96, avx2); //used for 10bit
+
+mc_rep_funcs(pel_pixels, 8, 32, 64, avx2);
+
+mc_rep_func(pel_pixels, 10, 16, 32, avx2);
+mc_rep_func(pel_pixels, 10, 16, 48, avx2);
+mc_rep_func(pel_pixels, 10, 32, 64, avx2);
+
+mc_rep_bi_func(pel_pixels, 10, 16, 32, avx2);
+mc_rep_bi_func(pel_pixels, 10, 16, 48, avx2);
+mc_rep_bi_func(pel_pixels, 10, 32, 64, avx2);
+
+mc_rep_funcs(epel_h, 8, 32, 64, avx2);
+
+mc_rep_funcs(epel_v, 8, 32, 64, avx2);
+
+mc_rep_funcs(epel_h, 10, 16, 32, avx2);
+mc_rep_funcs(epel_h, 10, 16, 48, avx2);
+mc_rep_funcs(epel_h, 10, 32, 64, avx2);
+
+mc_rep_funcs(epel_v, 10, 16, 32, avx2);
+mc_rep_funcs(epel_v, 10, 16, 48, avx2);
+mc_rep_funcs(epel_v, 10, 32, 64, avx2);
+
+
+mc_rep_funcs(epel_hv,  8, 32, 64, avx2);
+
+mc_rep_funcs(epel_hv, 10, 16, 32, avx2);
+mc_rep_funcs(epel_hv, 10, 16, 48, avx2);
+mc_rep_funcs(epel_hv, 10, 32, 64, avx2);
+
+mc_rep_funcs(qpel_h, 8, 32, 64, avx2);
+mc_rep_mixs_8(qpel_h ,  48, 32, 16, avx2, sse4);
+
+mc_rep_funcs(qpel_v, 8, 32, 64, avx2);
+mc_rep_mixs_8(qpel_v,  48, 32, 16, avx2, sse4);
+
+mc_rep_funcs(qpel_h, 10, 16, 32, avx2);
+mc_rep_funcs(qpel_h, 10, 16, 48, avx2);
+mc_rep_funcs(qpel_h, 10, 32, 64, avx2);
+
+mc_rep_funcs(qpel_v, 10, 16, 32, avx2);
+mc_rep_funcs(qpel_v, 10, 16, 48, avx2);
+mc_rep_funcs(qpel_v, 10, 32, 64, avx2);
+
+mc_rep_funcs(qpel_hv, 10, 16, 32, avx2);
+mc_rep_funcs(qpel_hv, 10, 16, 48, avx2);
+mc_rep_funcs(qpel_hv, 10, 32, 64, avx2);
+
+#endif //AVX2
+
 mc_rep_funcs(pel_pixels, 8, 16, 64, sse4);
 mc_rep_funcs(pel_pixels, 8, 16, 48, sse4);
 mc_rep_funcs(pel_pixels, 8, 16, 32, sse4);
@@ -214,11 +357,10 @@
 mc_rep_funcs(epel_v,12,  8, 24, sse4);
 mc_rep_funcs(epel_v,12,  8, 16, sse4);
 mc_rep_funcs(epel_v,12,  4, 12, sse4);
-mc_rep_funcs(epel_hv, 8,  8, 64, sse4);
-mc_rep_funcs(epel_hv, 8,  8, 48, sse4);
-mc_rep_funcs(epel_hv, 8,  8, 32, sse4);
+mc_rep_funcs(epel_hv, 8, 16, 64, sse4);
+mc_rep_funcs(epel_hv, 8, 16, 48, sse4);
+mc_rep_funcs(epel_hv, 8, 16, 32, sse4);
 mc_rep_funcs(epel_hv, 8,  8, 24, sse4);
-mc_rep_funcs(epel_hv, 8,  8, 16, sse4);
 mc_rep_funcs2(epel_hv,8,  8,  4, 12, sse4);
 mc_rep_funcs(epel_hv,10,  8, 64, sse4);
 mc_rep_funcs(epel_hv,10,  8, 48, sse4);
@@ -285,7 +427,7 @@
 mc_rep_funcs(qpel_hv,12,  4, 12, sse4);
 
 #define mc_rep_uni_w(bitd, step, W, opt) \
-void ff_hevc_put_hevc_uni_w##W##_##bitd##_##opt(uint8_t *_dst, ptrdiff_t dststride, int16_t *_src, ptrdiff_t _srcstride,\
+void ff_hevc_put_hevc_uni_w##W##_##bitd##_##opt(uint8_t *_dst, ptrdiff_t dststride, int16_t *_src, \
                                                int height, int denom,  int _wx, int _ox)                                \
 {                                                                                                                       \
     int i;                                                                                                              \
@@ -294,7 +436,7 @@
     for (i = 0; i < W; i += step) {                                                                                     \
         src= _src + i;                                                                                                  \
         dst= _dst + (i * ((bitd + 7) / 8));                                                                             \
-        ff_hevc_put_hevc_uni_w##step##_##bitd##_##opt(dst, dststride, src, _srcstride,                                  \
+        ff_hevc_put_hevc_uni_w##step##_##bitd##_##opt(dst, dststride, src,                                   \
                                                      height, denom, _wx, _ox);                                          \
     }                                                                                                                   \
 }
@@ -321,7 +463,7 @@
 mc_rep_uni_w(12, 8, 64, sse4);
 
 #define mc_rep_bi_w(bitd, step, W, opt) \
-void ff_hevc_put_hevc_bi_w##W##_##bitd##_##opt(uint8_t *_dst, ptrdiff_t dststride, int16_t *_src, ptrdiff_t _srcstride, \
+void ff_hevc_put_hevc_bi_w##W##_##bitd##_##opt(uint8_t *_dst, ptrdiff_t dststride, int16_t *_src, \
                                               int16_t *_src2, int height,                                               \
                                               int denom,  int _wx0,  int _wx1, int _ox0, int _ox1)                      \
 {                                                                                                                       \
@@ -333,8 +475,8 @@
         src  = _src  + i;                                                                                               \
         src2 = _src2 + i;                                                                                               \
         dst  = _dst  + (i * ((bitd + 7) / 8));                                                                          \
-        ff_hevc_put_hevc_bi_w##step##_##bitd##_##opt(dst, dststride, src, _srcstride, src2,                             \
-                                                    height, denom, _wx0, _wx1, _ox0, _ox1);                             \
+        ff_hevc_put_hevc_bi_w##step##_##bitd##_##opt(dst, dststride, src, src2,                             \
+                                                     height, denom, _wx0, _wx1, _ox0, _ox1);                             \
     }                                                                                                                   \
 }
 
@@ -368,7 +510,7 @@
 {                                                                                                   \
     LOCAL_ALIGNED_16(int16_t, temp, [71 * MAX_PB_SIZE]);                                            \
     ff_hevc_put_hevc_##name##W##_##bitd##_##opt(temp, _src, _srcstride, height, mx, my, width);     \
-    ff_hevc_put_hevc_uni_w##W##_##bitd##_##opt(_dst, _dststride, temp, MAX_PB_SIZE, height, denom, _wx, _ox);\
+    ff_hevc_put_hevc_uni_w##W##_##bitd##_##opt(_dst, _dststride, temp, height, denom, _wx, _ox);\
 }
 
 #define mc_uni_w_funcs(name, bitd, opt)       \
@@ -427,8 +569,8 @@
 {                                                                                                    \
     LOCAL_ALIGNED_16(int16_t, temp, [71 * MAX_PB_SIZE]);                                             \
     ff_hevc_put_hevc_##name##W##_##bitd##_##opt(temp, _src, _srcstride, height, mx, my, width);      \
-    ff_hevc_put_hevc_bi_w##W##_##bitd##_##opt(_dst, _dststride, temp, MAX_PB_SIZE, _src2,            \
-                                             height, denom, _wx0, _wx1, _ox0, _ox1);                 \
+    ff_hevc_put_hevc_bi_w##W##_##bitd##_##opt(_dst, _dststride, temp, _src2,                         \
+                                              height, denom, _wx0, _wx1, _ox0, _ox1);                \
 }
 
 #define mc_bi_w_funcs(name, bitd, opt)       \
@@ -478,6 +620,62 @@
 mc_bi_w_funcs(qpel_hv, 12, sse4);
 #endif //ARCH_X86_64 && HAVE_SSE4_EXTERNAL
 
+#define SAO_BAND_FILTER_FUNCS(bitd, opt)                                                                                   \
+void ff_hevc_sao_band_filter_8_##bitd##_##opt(uint8_t *_dst, uint8_t *_src, ptrdiff_t _stride_dst, ptrdiff_t _stride_src,  \
+                                            int16_t *sao_offset_val, int sao_left_class, int width, int height);           \
+void ff_hevc_sao_band_filter_16_##bitd##_##opt(uint8_t *_dst, uint8_t *_src, ptrdiff_t _stride_dst, ptrdiff_t _stride_src, \
+                                            int16_t *sao_offset_val, int sao_left_class, int width, int height);           \
+void ff_hevc_sao_band_filter_32_##bitd##_##opt(uint8_t *_dst, uint8_t *_src, ptrdiff_t _stride_dst, ptrdiff_t _stride_src, \
+                                            int16_t *sao_offset_val, int sao_left_class, int width, int height);           \
+void ff_hevc_sao_band_filter_48_##bitd##_##opt(uint8_t *_dst, uint8_t *_src, ptrdiff_t _stride_dst, ptrdiff_t _stride_src, \
+                                            int16_t *sao_offset_val, int sao_left_class, int width, int height);           \
+void ff_hevc_sao_band_filter_64_##bitd##_##opt(uint8_t *_dst, uint8_t *_src, ptrdiff_t _stride_dst, ptrdiff_t _stride_src, \
+                                             int16_t *sao_offset_val, int sao_left_class, int width, int height)
+
+SAO_BAND_FILTER_FUNCS(8,  sse2);
+SAO_BAND_FILTER_FUNCS(10, sse2);
+SAO_BAND_FILTER_FUNCS(12, sse2);
+SAO_BAND_FILTER_FUNCS(8,   avx);
+SAO_BAND_FILTER_FUNCS(10,  avx);
+SAO_BAND_FILTER_FUNCS(12,  avx);
+SAO_BAND_FILTER_FUNCS(8,  avx2);
+SAO_BAND_FILTER_FUNCS(10, avx2);
+SAO_BAND_FILTER_FUNCS(12, avx2);
+
+#define SAO_BAND_INIT(bitd, opt) do {                                       \
+    c->sao_band_filter[0]      = ff_hevc_sao_band_filter_8_##bitd##_##opt;  \
+    c->sao_band_filter[1]      = ff_hevc_sao_band_filter_16_##bitd##_##opt; \
+    c->sao_band_filter[2]      = ff_hevc_sao_band_filter_32_##bitd##_##opt; \
+    c->sao_band_filter[3]      = ff_hevc_sao_band_filter_48_##bitd##_##opt; \
+    c->sao_band_filter[4]      = ff_hevc_sao_band_filter_64_##bitd##_##opt; \
+} while (0)
+
+#define SAO_EDGE_FILTER_FUNCS(bitd, opt)                                                                                    \
+void ff_hevc_sao_edge_filter_8_##bitd##_##opt(uint8_t *_dst, uint8_t *_src, ptrdiff_t stride_dst, int16_t *sao_offset_val,  \
+                                              int eo, int width, int height);                                               \
+void ff_hevc_sao_edge_filter_16_##bitd##_##opt(uint8_t *_dst, uint8_t *_src, ptrdiff_t stride_dst, int16_t *sao_offset_val, \
+                                               int eo, int width, int height);                                              \
+void ff_hevc_sao_edge_filter_32_##bitd##_##opt(uint8_t *_dst, uint8_t *_src, ptrdiff_t stride_dst, int16_t *sao_offset_val, \
+                                               int eo, int width, int height);                                              \
+void ff_hevc_sao_edge_filter_48_##bitd##_##opt(uint8_t *_dst, uint8_t *_src, ptrdiff_t stride_dst, int16_t *sao_offset_val, \
+                                               int eo, int width, int height);                                              \
+void ff_hevc_sao_edge_filter_64_##bitd##_##opt(uint8_t *_dst, uint8_t *_src, ptrdiff_t stride_dst, int16_t *sao_offset_val, \
+                                               int eo, int width, int height);                                              \
+
+SAO_EDGE_FILTER_FUNCS(8, ssse3);
+SAO_EDGE_FILTER_FUNCS(8, avx2);
+SAO_EDGE_FILTER_FUNCS(10, sse2);
+SAO_EDGE_FILTER_FUNCS(10, avx2);
+SAO_EDGE_FILTER_FUNCS(12, sse2);
+SAO_EDGE_FILTER_FUNCS(12, avx2);
+
+#define SAO_EDGE_INIT(bitd, opt) do {                                       \
+    c->sao_edge_filter[0]      = ff_hevc_sao_edge_filter_8_##bitd##_##opt;  \
+    c->sao_edge_filter[1]      = ff_hevc_sao_edge_filter_16_##bitd##_##opt; \
+    c->sao_edge_filter[2]      = ff_hevc_sao_edge_filter_32_##bitd##_##opt; \
+    c->sao_edge_filter[3]      = ff_hevc_sao_edge_filter_48_##bitd##_##opt; \
+    c->sao_edge_filter[4]      = ff_hevc_sao_edge_filter_64_##bitd##_##opt; \
+} while (0)
 
 #define EPEL_LINKS(pointer, my, mx, fname, bitd, opt )           \
         PEL_LINK(pointer, 1, my , mx , fname##4 ,  bitd, opt ); \
@@ -499,7 +697,6 @@
         PEL_LINK(pointer, 8, my , mx , fname##48,  bitd, opt ); \
         PEL_LINK(pointer, 9, my , mx , fname##64,  bitd, opt )
 
-
 void ff_hevc_dsp_init_x86(HEVCDSPContext *c, const int bit_depth)
 {
     int cpu_flags = av_get_cpu_flags();
@@ -516,7 +713,10 @@
             if (ARCH_X86_64) {
                 c->hevc_v_loop_filter_luma = ff_hevc_v_loop_filter_luma_8_sse2;
                 c->hevc_h_loop_filter_luma = ff_hevc_h_loop_filter_luma_8_sse2;
+
             }
+            SAO_BAND_INIT(8, sse2);
+
             c->idct_dc[1] = ff_hevc_idct8x8_dc_8_sse2;
             c->idct_dc[2] = ff_hevc_idct16x16_dc_8_sse2;
             c->idct_dc[3] = ff_hevc_idct32x32_dc_8_sse2;
@@ -525,9 +725,12 @@
             c->transform_add[2]    = ff_hevc_transform_add16_8_sse2;
             c->transform_add[3]    = ff_hevc_transform_add32_8_sse2;
         }
-        if (EXTERNAL_SSSE3(cpu_flags) && ARCH_X86_64) {
-            c->hevc_v_loop_filter_luma = ff_hevc_v_loop_filter_luma_8_ssse3;
-            c->hevc_h_loop_filter_luma = ff_hevc_h_loop_filter_luma_8_ssse3;
+        if (EXTERNAL_SSSE3(cpu_flags)) {
+            if(ARCH_X86_64) {
+                c->hevc_v_loop_filter_luma = ff_hevc_v_loop_filter_luma_8_ssse3;
+                c->hevc_h_loop_filter_luma = ff_hevc_h_loop_filter_luma_8_ssse3;
+            }
+            SAO_EDGE_INIT(8, ssse3);
         }
         if (EXTERNAL_SSE4(cpu_flags) && ARCH_X86_64) {
 
@@ -548,6 +751,8 @@
                 c->hevc_v_loop_filter_luma = ff_hevc_v_loop_filter_luma_8_avx;
                 c->hevc_h_loop_filter_luma = ff_hevc_h_loop_filter_luma_8_avx;
             }
+            SAO_BAND_INIT(8, avx);
+
             c->transform_add[1]    = ff_hevc_transform_add8_8_avx;
             c->transform_add[2]    = ff_hevc_transform_add16_8_avx;
             c->transform_add[3]    = ff_hevc_transform_add32_8_avx;
@@ -555,6 +760,96 @@
         if (EXTERNAL_AVX2(cpu_flags)) {
             c->idct_dc[2] = ff_hevc_idct16x16_dc_8_avx2;
             c->idct_dc[3] = ff_hevc_idct32x32_dc_8_avx2;
+            if (ARCH_X86_64) {
+                c->put_hevc_epel[7][0][0] = ff_hevc_put_hevc_pel_pixels32_8_avx2;
+                c->put_hevc_epel[8][0][0] = ff_hevc_put_hevc_pel_pixels48_8_avx2;
+                c->put_hevc_epel[9][0][0] = ff_hevc_put_hevc_pel_pixels64_8_avx2;
+
+                c->put_hevc_qpel[7][0][0] = ff_hevc_put_hevc_pel_pixels32_8_avx2;
+                c->put_hevc_qpel[8][0][0] = ff_hevc_put_hevc_pel_pixels48_8_avx2;
+                c->put_hevc_qpel[9][0][0] = ff_hevc_put_hevc_pel_pixels64_8_avx2;
+
+                c->put_hevc_epel_uni[7][0][0] = ff_hevc_put_hevc_uni_pel_pixels32_8_avx2;
+                c->put_hevc_epel_uni[8][0][0] = ff_hevc_put_hevc_uni_pel_pixels48_8_avx2;
+                c->put_hevc_epel_uni[9][0][0] = ff_hevc_put_hevc_uni_pel_pixels64_8_avx2;
+
+                c->put_hevc_qpel_uni[7][0][0] = ff_hevc_put_hevc_uni_pel_pixels32_8_avx2;
+                c->put_hevc_qpel_uni[8][0][0] = ff_hevc_put_hevc_uni_pel_pixels48_8_avx2;
+                c->put_hevc_qpel_uni[9][0][0] = ff_hevc_put_hevc_uni_pel_pixels64_8_avx2;
+
+                c->put_hevc_qpel_bi[7][0][0] = ff_hevc_put_hevc_bi_pel_pixels32_8_avx2;
+                c->put_hevc_qpel_bi[8][0][0] = ff_hevc_put_hevc_bi_pel_pixels48_8_avx2;
+                c->put_hevc_qpel_bi[9][0][0] = ff_hevc_put_hevc_bi_pel_pixels64_8_avx2;
+
+                c->put_hevc_epel_bi[7][0][0] = ff_hevc_put_hevc_bi_pel_pixels32_8_avx2;
+                c->put_hevc_epel_bi[8][0][0] = ff_hevc_put_hevc_bi_pel_pixels48_8_avx2;
+                c->put_hevc_epel_bi[9][0][0] = ff_hevc_put_hevc_bi_pel_pixels64_8_avx2;
+
+                c->put_hevc_epel[7][0][1] = ff_hevc_put_hevc_epel_h32_8_avx2;
+                c->put_hevc_epel[8][0][1] = ff_hevc_put_hevc_epel_h48_8_avx2;
+                c->put_hevc_epel[9][0][1] = ff_hevc_put_hevc_epel_h64_8_avx2;
+
+                c->put_hevc_epel_uni[7][0][1] = ff_hevc_put_hevc_uni_epel_h32_8_avx2;
+                c->put_hevc_epel_uni[8][0][1] = ff_hevc_put_hevc_uni_epel_h48_8_avx2;
+                c->put_hevc_epel_uni[9][0][1] = ff_hevc_put_hevc_uni_epel_h64_8_avx2;
+
+                c->put_hevc_epel_bi[7][0][1] = ff_hevc_put_hevc_bi_epel_h32_8_avx2;
+                c->put_hevc_epel_bi[8][0][1] = ff_hevc_put_hevc_bi_epel_h48_8_avx2;
+                c->put_hevc_epel_bi[9][0][1] = ff_hevc_put_hevc_bi_epel_h64_8_avx2;
+
+                c->put_hevc_epel[7][1][0] = ff_hevc_put_hevc_epel_v32_8_avx2;
+                c->put_hevc_epel[8][1][0] = ff_hevc_put_hevc_epel_v48_8_avx2;
+                c->put_hevc_epel[9][1][0] = ff_hevc_put_hevc_epel_v64_8_avx2;
+
+                c->put_hevc_epel_uni[7][1][0] = ff_hevc_put_hevc_uni_epel_v32_8_avx2;
+                c->put_hevc_epel_uni[8][1][0] = ff_hevc_put_hevc_uni_epel_v48_8_avx2;
+                c->put_hevc_epel_uni[9][1][0] = ff_hevc_put_hevc_uni_epel_v64_8_avx2;
+
+                c->put_hevc_epel_bi[7][1][0] = ff_hevc_put_hevc_bi_epel_v32_8_avx2;
+                c->put_hevc_epel_bi[8][1][0] = ff_hevc_put_hevc_bi_epel_v48_8_avx2;
+                c->put_hevc_epel_bi[9][1][0] = ff_hevc_put_hevc_bi_epel_v64_8_avx2;
+
+                c->put_hevc_epel[7][1][1] = ff_hevc_put_hevc_epel_hv32_8_avx2;
+                c->put_hevc_epel[8][1][1] = ff_hevc_put_hevc_epel_hv48_8_avx2;
+                c->put_hevc_epel[9][1][1] = ff_hevc_put_hevc_epel_hv64_8_avx2;
+
+                c->put_hevc_epel_uni[7][1][1] = ff_hevc_put_hevc_uni_epel_hv32_8_avx2;
+                c->put_hevc_epel_uni[8][1][1] = ff_hevc_put_hevc_uni_epel_hv48_8_avx2;
+                c->put_hevc_epel_uni[9][1][1] = ff_hevc_put_hevc_uni_epel_hv64_8_avx2;
+
+                c->put_hevc_epel_bi[7][1][1] = ff_hevc_put_hevc_bi_epel_hv32_8_avx2;
+                c->put_hevc_epel_bi[8][1][1] = ff_hevc_put_hevc_bi_epel_hv48_8_avx2;
+                c->put_hevc_epel_bi[9][1][1] = ff_hevc_put_hevc_bi_epel_hv64_8_avx2;
+
+                c->put_hevc_qpel[7][0][1] = ff_hevc_put_hevc_qpel_h32_8_avx2;
+                c->put_hevc_qpel[8][0][1] = ff_hevc_put_hevc_qpel_h48_8_avx2;
+                c->put_hevc_qpel[9][0][1] = ff_hevc_put_hevc_qpel_h64_8_avx2;
+
+                c->put_hevc_qpel[7][1][0] = ff_hevc_put_hevc_qpel_v32_8_avx2;
+                c->put_hevc_qpel[8][1][0] = ff_hevc_put_hevc_qpel_v48_8_avx2;
+                c->put_hevc_qpel[9][1][0] = ff_hevc_put_hevc_qpel_v64_8_avx2;
+
+                c->put_hevc_qpel_uni[7][0][1] = ff_hevc_put_hevc_uni_qpel_h32_8_avx2;
+                c->put_hevc_qpel_uni[8][0][1] = ff_hevc_put_hevc_uni_qpel_h48_8_avx2;
+                c->put_hevc_qpel_uni[9][0][1] = ff_hevc_put_hevc_uni_qpel_h64_8_avx2;
+
+                c->put_hevc_qpel_uni[7][1][0] = ff_hevc_put_hevc_uni_qpel_v32_8_avx2;
+                c->put_hevc_qpel_uni[8][1][0] = ff_hevc_put_hevc_uni_qpel_v48_8_avx2;
+                c->put_hevc_qpel_uni[9][1][0] = ff_hevc_put_hevc_uni_qpel_v64_8_avx2;
+
+                c->put_hevc_qpel_bi[7][0][1] = ff_hevc_put_hevc_bi_qpel_h32_8_avx2;
+                c->put_hevc_qpel_bi[8][0][1] = ff_hevc_put_hevc_bi_qpel_h48_8_avx2;
+                c->put_hevc_qpel_bi[9][0][1] = ff_hevc_put_hevc_bi_qpel_h64_8_avx2;
+
+                c->put_hevc_qpel_bi[7][1][0] = ff_hevc_put_hevc_bi_qpel_v32_8_avx2;
+                c->put_hevc_qpel_bi[8][1][0] = ff_hevc_put_hevc_bi_qpel_v48_8_avx2;
+                c->put_hevc_qpel_bi[9][1][0] = ff_hevc_put_hevc_bi_qpel_v64_8_avx2;
+            }
+            SAO_BAND_INIT(8, avx2);
+
+            c->sao_edge_filter[2] = ff_hevc_sao_edge_filter_32_8_avx2;
+            c->sao_edge_filter[3] = ff_hevc_sao_edge_filter_48_8_avx2;
+            c->sao_edge_filter[4] = ff_hevc_sao_edge_filter_64_8_avx2;
 
             c->transform_add[3]    = ff_hevc_transform_add32_8_avx2;
         }
@@ -571,6 +866,8 @@
                 c->hevc_v_loop_filter_luma = ff_hevc_v_loop_filter_luma_10_sse2;
                 c->hevc_h_loop_filter_luma = ff_hevc_h_loop_filter_luma_10_sse2;
             }
+            SAO_BAND_INIT(10, sse2);
+            SAO_EDGE_INIT(10, sse2);
 
             c->idct_dc[1] = ff_hevc_idct8x8_dc_10_sse2;
             c->idct_dc[2] = ff_hevc_idct16x16_dc_10_sse2;
@@ -602,11 +899,160 @@
                 c->hevc_v_loop_filter_luma = ff_hevc_v_loop_filter_luma_10_avx;
                 c->hevc_h_loop_filter_luma = ff_hevc_h_loop_filter_luma_10_avx;
             }
+            SAO_BAND_INIT(10, avx);
         }
         if (EXTERNAL_AVX2(cpu_flags)) {
 
             c->idct_dc[2] = ff_hevc_idct16x16_dc_10_avx2;
             c->idct_dc[3] = ff_hevc_idct32x32_dc_10_avx2;
+            if (ARCH_X86_64) {
+                c->put_hevc_epel[5][0][0] = ff_hevc_put_hevc_pel_pixels16_10_avx2;
+                c->put_hevc_epel[6][0][0] = ff_hevc_put_hevc_pel_pixels24_10_avx2;
+                c->put_hevc_epel[7][0][0] = ff_hevc_put_hevc_pel_pixels32_10_avx2;
+                c->put_hevc_epel[8][0][0] = ff_hevc_put_hevc_pel_pixels48_10_avx2;
+                c->put_hevc_epel[9][0][0] = ff_hevc_put_hevc_pel_pixels64_10_avx2;
+
+                c->put_hevc_qpel[5][0][0] = ff_hevc_put_hevc_pel_pixels16_10_avx2;
+                c->put_hevc_qpel[6][0][0] = ff_hevc_put_hevc_pel_pixels24_10_avx2;
+                c->put_hevc_qpel[7][0][0] = ff_hevc_put_hevc_pel_pixels32_10_avx2;
+                c->put_hevc_qpel[8][0][0] = ff_hevc_put_hevc_pel_pixels48_10_avx2;
+                c->put_hevc_qpel[9][0][0] = ff_hevc_put_hevc_pel_pixels64_10_avx2;
+
+                c->put_hevc_epel_uni[5][0][0] = ff_hevc_put_hevc_uni_pel_pixels32_8_avx2;
+                c->put_hevc_epel_uni[6][0][0] = ff_hevc_put_hevc_uni_pel_pixels48_8_avx2;
+                c->put_hevc_epel_uni[7][0][0] = ff_hevc_put_hevc_uni_pel_pixels64_8_avx2;
+                c->put_hevc_epel_uni[8][0][0] = ff_hevc_put_hevc_uni_pel_pixels96_8_avx2;
+                c->put_hevc_epel_uni[9][0][0] = ff_hevc_put_hevc_uni_pel_pixels128_8_avx2;
+
+                c->put_hevc_qpel_uni[5][0][0] = ff_hevc_put_hevc_uni_pel_pixels32_8_avx2;
+                c->put_hevc_qpel_uni[6][0][0] = ff_hevc_put_hevc_uni_pel_pixels48_8_avx2;
+                c->put_hevc_qpel_uni[7][0][0] = ff_hevc_put_hevc_uni_pel_pixels64_8_avx2;
+                c->put_hevc_qpel_uni[8][0][0] = ff_hevc_put_hevc_uni_pel_pixels96_8_avx2;
+                c->put_hevc_qpel_uni[9][0][0] = ff_hevc_put_hevc_uni_pel_pixels128_8_avx2;
+
+                c->put_hevc_epel_bi[5][0][0] = ff_hevc_put_hevc_bi_pel_pixels16_10_avx2;
+                c->put_hevc_epel_bi[6][0][0] = ff_hevc_put_hevc_bi_pel_pixels24_10_avx2;
+                c->put_hevc_epel_bi[7][0][0] = ff_hevc_put_hevc_bi_pel_pixels32_10_avx2;
+                c->put_hevc_epel_bi[8][0][0] = ff_hevc_put_hevc_bi_pel_pixels48_10_avx2;
+                c->put_hevc_epel_bi[9][0][0] = ff_hevc_put_hevc_bi_pel_pixels64_10_avx2;
+                c->put_hevc_qpel_bi[5][0][0] = ff_hevc_put_hevc_bi_pel_pixels16_10_avx2;
+                c->put_hevc_qpel_bi[6][0][0] = ff_hevc_put_hevc_bi_pel_pixels24_10_avx2;
+                c->put_hevc_qpel_bi[7][0][0] = ff_hevc_put_hevc_bi_pel_pixels32_10_avx2;
+                c->put_hevc_qpel_bi[8][0][0] = ff_hevc_put_hevc_bi_pel_pixels48_10_avx2;
+                c->put_hevc_qpel_bi[9][0][0] = ff_hevc_put_hevc_bi_pel_pixels64_10_avx2;
+
+                c->put_hevc_epel[5][0][1] = ff_hevc_put_hevc_epel_h16_10_avx2;
+                c->put_hevc_epel[6][0][1] = ff_hevc_put_hevc_epel_h24_10_avx2;
+                c->put_hevc_epel[7][0][1] = ff_hevc_put_hevc_epel_h32_10_avx2;
+                c->put_hevc_epel[8][0][1] = ff_hevc_put_hevc_epel_h48_10_avx2;
+                c->put_hevc_epel[9][0][1] = ff_hevc_put_hevc_epel_h64_10_avx2;
+
+                c->put_hevc_epel_uni[5][0][1] = ff_hevc_put_hevc_uni_epel_h16_10_avx2;
+                c->put_hevc_epel_uni[6][0][1] = ff_hevc_put_hevc_uni_epel_h24_10_avx2;
+                c->put_hevc_epel_uni[7][0][1] = ff_hevc_put_hevc_uni_epel_h32_10_avx2;
+                c->put_hevc_epel_uni[8][0][1] = ff_hevc_put_hevc_uni_epel_h48_10_avx2;
+                c->put_hevc_epel_uni[9][0][1] = ff_hevc_put_hevc_uni_epel_h64_10_avx2;
+
+                c->put_hevc_epel_bi[5][0][1] = ff_hevc_put_hevc_bi_epel_h16_10_avx2;
+                c->put_hevc_epel_bi[6][0][1] = ff_hevc_put_hevc_bi_epel_h24_10_avx2;
+                c->put_hevc_epel_bi[7][0][1] = ff_hevc_put_hevc_bi_epel_h32_10_avx2;
+                c->put_hevc_epel_bi[8][0][1] = ff_hevc_put_hevc_bi_epel_h48_10_avx2;
+                c->put_hevc_epel_bi[9][0][1] = ff_hevc_put_hevc_bi_epel_h64_10_avx2;
+
+                c->put_hevc_epel[5][1][0] = ff_hevc_put_hevc_epel_v16_10_avx2;
+                c->put_hevc_epel[6][1][0] = ff_hevc_put_hevc_epel_v24_10_avx2;
+                c->put_hevc_epel[7][1][0] = ff_hevc_put_hevc_epel_v32_10_avx2;
+                c->put_hevc_epel[8][1][0] = ff_hevc_put_hevc_epel_v48_10_avx2;
+                c->put_hevc_epel[9][1][0] = ff_hevc_put_hevc_epel_v64_10_avx2;
+
+                c->put_hevc_epel_uni[5][1][0] = ff_hevc_put_hevc_uni_epel_v16_10_avx2;
+                c->put_hevc_epel_uni[6][1][0] = ff_hevc_put_hevc_uni_epel_v24_10_avx2;
+                c->put_hevc_epel_uni[7][1][0] = ff_hevc_put_hevc_uni_epel_v32_10_avx2;
+                c->put_hevc_epel_uni[8][1][0] = ff_hevc_put_hevc_uni_epel_v48_10_avx2;
+                c->put_hevc_epel_uni[9][1][0] = ff_hevc_put_hevc_uni_epel_v64_10_avx2;
+
+                c->put_hevc_epel_bi[5][1][0] = ff_hevc_put_hevc_bi_epel_v16_10_avx2;
+                c->put_hevc_epel_bi[6][1][0] = ff_hevc_put_hevc_bi_epel_v24_10_avx2;
+                c->put_hevc_epel_bi[7][1][0] = ff_hevc_put_hevc_bi_epel_v32_10_avx2;
+                c->put_hevc_epel_bi[8][1][0] = ff_hevc_put_hevc_bi_epel_v48_10_avx2;
+                c->put_hevc_epel_bi[9][1][0] = ff_hevc_put_hevc_bi_epel_v64_10_avx2;
+
+                c->put_hevc_epel[5][1][1] = ff_hevc_put_hevc_epel_hv16_10_avx2;
+                c->put_hevc_epel[6][1][1] = ff_hevc_put_hevc_epel_hv24_10_avx2;
+                c->put_hevc_epel[7][1][1] = ff_hevc_put_hevc_epel_hv32_10_avx2;
+                c->put_hevc_epel[8][1][1] = ff_hevc_put_hevc_epel_hv48_10_avx2;
+                c->put_hevc_epel[9][1][1] = ff_hevc_put_hevc_epel_hv64_10_avx2;
+
+                c->put_hevc_epel_uni[5][1][1] = ff_hevc_put_hevc_uni_epel_hv16_10_avx2;
+                c->put_hevc_epel_uni[6][1][1] = ff_hevc_put_hevc_uni_epel_hv24_10_avx2;
+                c->put_hevc_epel_uni[7][1][1] = ff_hevc_put_hevc_uni_epel_hv32_10_avx2;
+                c->put_hevc_epel_uni[8][1][1] = ff_hevc_put_hevc_uni_epel_hv48_10_avx2;
+                c->put_hevc_epel_uni[9][1][1] = ff_hevc_put_hevc_uni_epel_hv64_10_avx2;
+
+                c->put_hevc_epel_bi[5][1][1] = ff_hevc_put_hevc_bi_epel_hv16_10_avx2;
+                c->put_hevc_epel_bi[6][1][1] = ff_hevc_put_hevc_bi_epel_hv24_10_avx2;
+                c->put_hevc_epel_bi[7][1][1] = ff_hevc_put_hevc_bi_epel_hv32_10_avx2;
+                c->put_hevc_epel_bi[8][1][1] = ff_hevc_put_hevc_bi_epel_hv48_10_avx2;
+                c->put_hevc_epel_bi[9][1][1] = ff_hevc_put_hevc_bi_epel_hv64_10_avx2;
+
+                c->put_hevc_qpel[5][0][1] = ff_hevc_put_hevc_qpel_h16_10_avx2;
+                c->put_hevc_qpel[6][0][1] = ff_hevc_put_hevc_qpel_h24_10_avx2;
+                c->put_hevc_qpel[7][0][1] = ff_hevc_put_hevc_qpel_h32_10_avx2;
+                c->put_hevc_qpel[8][0][1] = ff_hevc_put_hevc_qpel_h48_10_avx2;
+                c->put_hevc_qpel[9][0][1] = ff_hevc_put_hevc_qpel_h64_10_avx2;
+
+                c->put_hevc_qpel_uni[5][0][1] = ff_hevc_put_hevc_uni_qpel_h16_10_avx2;
+                c->put_hevc_qpel_uni[6][0][1] = ff_hevc_put_hevc_uni_qpel_h24_10_avx2;
+                c->put_hevc_qpel_uni[7][0][1] = ff_hevc_put_hevc_uni_qpel_h32_10_avx2;
+                c->put_hevc_qpel_uni[8][0][1] = ff_hevc_put_hevc_uni_qpel_h48_10_avx2;
+                c->put_hevc_qpel_uni[9][0][1] = ff_hevc_put_hevc_uni_qpel_h64_10_avx2;
+
+                c->put_hevc_qpel_bi[5][0][1] = ff_hevc_put_hevc_bi_qpel_h16_10_avx2;
+                c->put_hevc_qpel_bi[6][0][1] = ff_hevc_put_hevc_bi_qpel_h24_10_avx2;
+                c->put_hevc_qpel_bi[7][0][1] = ff_hevc_put_hevc_bi_qpel_h32_10_avx2;
+                c->put_hevc_qpel_bi[8][0][1] = ff_hevc_put_hevc_bi_qpel_h48_10_avx2;
+                c->put_hevc_qpel_bi[9][0][1] = ff_hevc_put_hevc_bi_qpel_h64_10_avx2;
+
+                c->put_hevc_qpel[5][1][0] = ff_hevc_put_hevc_qpel_v16_10_avx2;
+                c->put_hevc_qpel[6][1][0] = ff_hevc_put_hevc_qpel_v24_10_avx2;
+                c->put_hevc_qpel[7][1][0] = ff_hevc_put_hevc_qpel_v32_10_avx2;
+                c->put_hevc_qpel[8][1][0] = ff_hevc_put_hevc_qpel_v48_10_avx2;
+                c->put_hevc_qpel[9][1][0] = ff_hevc_put_hevc_qpel_v64_10_avx2;
+
+                c->put_hevc_qpel_uni[5][1][0] = ff_hevc_put_hevc_uni_qpel_v16_10_avx2;
+                c->put_hevc_qpel_uni[6][1][0] = ff_hevc_put_hevc_uni_qpel_v24_10_avx2;
+                c->put_hevc_qpel_uni[7][1][0] = ff_hevc_put_hevc_uni_qpel_v32_10_avx2;
+                c->put_hevc_qpel_uni[8][1][0] = ff_hevc_put_hevc_uni_qpel_v48_10_avx2;
+                c->put_hevc_qpel_uni[9][1][0] = ff_hevc_put_hevc_uni_qpel_v64_10_avx2;
+
+                c->put_hevc_qpel_bi[5][1][0] = ff_hevc_put_hevc_bi_qpel_v16_10_avx2;
+                c->put_hevc_qpel_bi[6][1][0] = ff_hevc_put_hevc_bi_qpel_v24_10_avx2;
+                c->put_hevc_qpel_bi[7][1][0] = ff_hevc_put_hevc_bi_qpel_v32_10_avx2;
+                c->put_hevc_qpel_bi[8][1][0] = ff_hevc_put_hevc_bi_qpel_v48_10_avx2;
+                c->put_hevc_qpel_bi[9][1][0] = ff_hevc_put_hevc_bi_qpel_v64_10_avx2;
+
+                c->put_hevc_qpel[5][1][1] = ff_hevc_put_hevc_qpel_hv16_10_avx2;
+                c->put_hevc_qpel[6][1][1] = ff_hevc_put_hevc_qpel_hv24_10_avx2;
+                c->put_hevc_qpel[7][1][1] = ff_hevc_put_hevc_qpel_hv32_10_avx2;
+                c->put_hevc_qpel[8][1][1] = ff_hevc_put_hevc_qpel_hv48_10_avx2;
+                c->put_hevc_qpel[9][1][1] = ff_hevc_put_hevc_qpel_hv64_10_avx2;
+
+                c->put_hevc_qpel_uni[5][1][1] = ff_hevc_put_hevc_uni_qpel_hv16_10_avx2;
+                c->put_hevc_qpel_uni[6][1][1] = ff_hevc_put_hevc_uni_qpel_hv24_10_avx2;
+                c->put_hevc_qpel_uni[7][1][1] = ff_hevc_put_hevc_uni_qpel_hv32_10_avx2;
+                c->put_hevc_qpel_uni[8][1][1] = ff_hevc_put_hevc_uni_qpel_hv48_10_avx2;
+                c->put_hevc_qpel_uni[9][1][1] = ff_hevc_put_hevc_uni_qpel_hv64_10_avx2;
+
+                c->put_hevc_qpel_bi[5][1][1] = ff_hevc_put_hevc_bi_qpel_hv16_10_avx2;
+                c->put_hevc_qpel_bi[6][1][1] = ff_hevc_put_hevc_bi_qpel_hv24_10_avx2;
+                c->put_hevc_qpel_bi[7][1][1] = ff_hevc_put_hevc_bi_qpel_hv32_10_avx2;
+                c->put_hevc_qpel_bi[8][1][1] = ff_hevc_put_hevc_bi_qpel_hv48_10_avx2;
+                c->put_hevc_qpel_bi[9][1][1] = ff_hevc_put_hevc_bi_qpel_hv64_10_avx2;
+            }
+            SAO_BAND_INIT(10, avx2);
+            c->sao_edge_filter[2] = ff_hevc_sao_edge_filter_32_10_avx2;
+            c->sao_edge_filter[3] = ff_hevc_sao_edge_filter_48_10_avx2;
+            c->sao_edge_filter[4] = ff_hevc_sao_edge_filter_64_10_avx2;
 
             c->transform_add[2] = ff_hevc_transform_add16_10_avx2;
             c->transform_add[3] = ff_hevc_transform_add32_10_avx2;
@@ -624,6 +1070,8 @@
                 c->hevc_v_loop_filter_luma = ff_hevc_v_loop_filter_luma_12_sse2;
                 c->hevc_h_loop_filter_luma = ff_hevc_h_loop_filter_luma_12_sse2;
             }
+            SAO_BAND_INIT(12, sse2);
+            SAO_EDGE_INIT(12, sse2);
 
             c->idct_dc[1] = ff_hevc_idct8x8_dc_12_sse2;
             c->idct_dc[2] = ff_hevc_idct16x16_dc_12_sse2;
@@ -651,10 +1099,16 @@
                 c->hevc_v_loop_filter_luma = ff_hevc_v_loop_filter_luma_12_avx;
                 c->hevc_h_loop_filter_luma = ff_hevc_h_loop_filter_luma_12_avx;
             }
+            SAO_BAND_INIT(12, avx);
         }
         if (EXTERNAL_AVX2(cpu_flags)) {
             c->idct_dc[2] = ff_hevc_idct16x16_dc_12_avx2;
             c->idct_dc[3] = ff_hevc_idct32x32_dc_12_avx2;
+
+            SAO_BAND_INIT(12, avx2);
+            c->sao_edge_filter[2] = ff_hevc_sao_edge_filter_32_12_avx2;
+            c->sao_edge_filter[3] = ff_hevc_sao_edge_filter_48_12_avx2;
+            c->sao_edge_filter[4] = ff_hevc_sao_edge_filter_64_12_avx2;
         }
     }
 }
diff --git a/libavcodec/x86/huffyuvdsp.asm b/libavcodec/x86/huffyuvdsp.asm
index cc48556..85ee56d 100644
--- a/libavcodec/x86/huffyuvdsp.asm
+++ b/libavcodec/x86/huffyuvdsp.asm
@@ -23,7 +23,7 @@
 %include "libavutil/x86/x86util.asm"
 
 SECTION_RODATA
-pb_f: times 16 db 15
+cextern pb_15
 pb_zzzzzzzz77777777: times 8 db -1
 pb_7: times 8 db 7
 pb_zzzz3333zzzzbbbb: db -1,-1,-1,-1,3,3,3,3,-1,-1,-1,-1,11,11,11,11
@@ -157,7 +157,7 @@
 
 INIT_XMM sse4
 cglobal add_hfyu_left_pred, 3,3,7, dst, src, w, left
-    mova    m5, [pb_f]
+    mova    m5, [pb_15]
     mova    m6, [pb_zzzzzzzz77777777]
     mova    m4, [pb_zzzz3333zzzzbbbb]
     mova    m3, [pb_zz11zz55zz99zzdd]
diff --git a/libavcodec/x86/lossless_audiodsp.asm b/libavcodec/x86/lossless_audiodsp.asm
index 39395fe..64b769f 100644
--- a/libavcodec/x86/lossless_audiodsp.asm
+++ b/libavcodec/x86/lossless_audiodsp.asm
@@ -26,12 +26,6 @@
 ; int ff_scalarproduct_and_madd_int16(int16_t *v1, int16_t *v2, int16_t *v3,
 ;                                     int order, int mul)
 cglobal scalarproduct_and_madd_int16, 4,4,8, v1, v2, v3, order, mul
-%if mmsize == 16
-    test orderq, 8
-        jnz scalarproduct_and_madd_int16_fallback
-%else
-    scalarproduct_and_madd_int16_fallback
-%endif
     shl orderq, 1
     movd    m7, mulm
 %if mmsize == 16
@@ -123,8 +117,6 @@
 ;                                     int order, int mul)
 INIT_XMM ssse3
 cglobal scalarproduct_and_madd_int16, 4,5,10, v1, v2, v3, order, mul
-    test orderq, 8
-        jnz scalarproduct_and_madd_int16_fallback
     shl orderq, 1
     movd    m7, mulm
     pshuflw m7, m7, 0
diff --git a/libavcodec/x86/lossless_audiodsp_init.c b/libavcodec/x86/lossless_audiodsp_init.c
index 4879dff..197173c 100644
--- a/libavcodec/x86/lossless_audiodsp_init.c
+++ b/libavcodec/x86/lossless_audiodsp_init.c
@@ -33,6 +33,7 @@
 
 av_cold void ff_llauddsp_init_x86(LLAudDSPContext *c)
 {
+#if HAVE_YASM
     int cpu_flags = av_get_cpu_flags();
 
     if (EXTERNAL_MMXEXT(cpu_flags))
@@ -44,4 +45,5 @@
     if (EXTERNAL_SSSE3(cpu_flags) &&
         !(cpu_flags & (AV_CPU_FLAG_SSE42 | AV_CPU_FLAG_3DNOW))) // cachesplit
         c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_ssse3;
+#endif
 }
diff --git a/libavcodec/x86/mathops.h b/libavcodec/x86/mathops.h
index 1cca05d..6298f5e 100644
--- a/libavcodec/x86/mathops.h
+++ b/libavcodec/x86/mathops.h
@@ -23,6 +23,7 @@
 #define AVCODEC_X86_MATHOPS_H
 
 #include "config.h"
+
 #include "libavutil/common.h"
 #include "libavutil/x86/asm.h"
 
@@ -100,6 +101,7 @@
     : "r" (y), "r" (b), "r" (d)\
 );
 #endif /* HAVE_6REGS */
+
 #endif /* HAVE_I686 */
 
 #define MASK_ABS(mask, level)                   \
diff --git a/libavcodec/x86/mlpdsp_init.c b/libavcodec/x86/mlpdsp_init.c
index dc0bc58..e9d9b1b 100644
--- a/libavcodec/x86/mlpdsp_init.c
+++ b/libavcodec/x86/mlpdsp_init.c
@@ -148,8 +148,8 @@
         FIRMUL   (ff_mlp_firorder_6, 0x14   )
         FIRMUL   (ff_mlp_firorder_5, 0x10   )
         FIRMUL   (ff_mlp_firorder_4, 0x0c   )
-        FIRMULREG(ff_mlp_firorder_3, 0x08,10)
-        FIRMULREG(ff_mlp_firorder_2, 0x04, 9)
+        FIRMUL   (ff_mlp_firorder_3, 0x08   )
+        FIRMUL   (ff_mlp_firorder_2, 0x04   )
         FIRMULREG(ff_mlp_firorder_1, 0x00, 8)
         LABEL_MANGLE(ff_mlp_firorder_0)":\n\t"
         "jmp  *%6                     \n\t"
@@ -178,8 +178,6 @@
         : /* 4*/"r"((x86_reg)mask), /* 5*/"r"(firjump),
           /* 6*/"r"(iirjump)      , /* 7*/"c"(filter_shift)
         , /* 8*/"r"((int64_t)coeff[0])
-        , /* 9*/"r"((int64_t)coeff[1])
-        , /*10*/"r"((int64_t)coeff[2])
         : "rax", "rdx", "rsi"
 #else /* ARCH_X86_32 */
           /* 3*/"+m"(blocksize)
diff --git a/libavcodec/x86/proresdsp.asm b/libavcodec/x86/proresdsp.asm
index 255eb24..632ece6 100644
--- a/libavcodec/x86/proresdsp.asm
+++ b/libavcodec/x86/proresdsp.asm
@@ -300,24 +300,8 @@
     RET
 %endmacro
 
-%macro SIGNEXTEND 2-3
-%if cpuflag(sse4) ; dstlow, dsthigh
-    movhlps     %2,  %1
-    pmovsxwd    %1,  %1
-    pmovsxwd    %2,  %2
-%elif cpuflag(sse2) ; dstlow, dsthigh, tmp
-    pxor        %3,  %3
-    pcmpgtw     %3,  %1
-    mova        %2,  %1
-    punpcklwd   %1,  %3
-    punpckhwd   %2,  %3
-%endif
-%endmacro
-
 INIT_XMM sse2
 idct_put_fn 16
-INIT_XMM sse4
-idct_put_fn 16
 %if HAVE_AVX_EXTERNAL
 INIT_XMM avx
 idct_put_fn 16
diff --git a/libavcodec/x86/proresdsp_init.c b/libavcodec/x86/proresdsp_init.c
index d647788..ead11ae 100644
--- a/libavcodec/x86/proresdsp_init.c
+++ b/libavcodec/x86/proresdsp_init.c
@@ -27,8 +27,6 @@
 
 void ff_prores_idct_put_10_sse2(uint16_t *dst, int linesize,
                                 int16_t *block, const int16_t *qmat);
-void ff_prores_idct_put_10_sse4(uint16_t *dst, int linesize,
-                                int16_t *block, const int16_t *qmat);
 void ff_prores_idct_put_10_avx (uint16_t *dst, int linesize,
                                 int16_t *block, const int16_t *qmat);
 
@@ -42,11 +40,6 @@
         dsp->idct_put = ff_prores_idct_put_10_sse2;
     }
 
-    if (EXTERNAL_SSE4(cpu_flags)) {
-        dsp->idct_permutation_type = FF_IDCT_PERM_TRANSPOSE;
-        dsp->idct_put = ff_prores_idct_put_10_sse4;
-    }
-
     if (EXTERNAL_AVX(cpu_flags)) {
         dsp->idct_permutation_type = FF_IDCT_PERM_TRANSPOSE;
         dsp->idct_put = ff_prores_idct_put_10_avx;
diff --git a/libavcodec/x86/rv40dsp_init.c b/libavcodec/x86/rv40dsp_init.c
index 2900e2d..bbf9c78 100644
--- a/libavcodec/x86/rv40dsp_init.c
+++ b/libavcodec/x86/rv40dsp_init.c
@@ -82,7 +82,7 @@
 {                                                                       \
     int i;                                                              \
     if (PH && PV) {                                                     \
-        DECLARE_ALIGNED(16, uint8_t, tmp)[SIZE * (SIZE + 5)];           \
+        LOCAL_ALIGNED(16, uint8_t, tmp, [SIZE * (SIZE + 5)]);           \
         uint8_t *tmpptr = tmp + SIZE * 2;                               \
         src -= stride * 2;                                              \
                                                                         \
diff --git a/libavcodec/x86/snowdsp.c b/libavcodec/x86/snowdsp.c
index 2778489..e2ad511 100644
--- a/libavcodec/x86/snowdsp.c
+++ b/libavcodec/x86/snowdsp.c
@@ -877,7 +877,7 @@
 
 #endif /* HAVE_INLINE_ASM */
 
-void ff_dwt_init_x86(SnowDWTContext *c)
+av_cold void ff_dwt_init_x86(SnowDWTContext *c)
 {
 #if HAVE_INLINE_ASM
     int mm_flags = av_get_cpu_flags();
diff --git a/libavcodec/x86/v210-init.c b/libavcodec/x86/v210-init.c
index 02c5eaa..dfdfd26 100644
--- a/libavcodec/x86/v210-init.c
+++ b/libavcodec/x86/v210-init.c
@@ -25,7 +25,7 @@
 extern void ff_v210_planar_unpack_aligned_ssse3(const uint32_t *src, uint16_t *y, uint16_t *u, uint16_t *v, int width);
 extern void ff_v210_planar_unpack_aligned_avx(const uint32_t *src, uint16_t *y, uint16_t *u, uint16_t *v, int width);
 
-av_cold void v210_x86_init(V210DecContext *s)
+av_cold void ff_v210_x86_init(V210DecContext *s)
 {
     int cpu_flags = av_get_cpu_flags();
 
diff --git a/libavcodec/x86/v210enc.asm b/libavcodec/x86/v210enc.asm
index 3245de3..751675f 100644
--- a/libavcodec/x86/v210enc.asm
+++ b/libavcodec/x86/v210enc.asm
@@ -23,7 +23,8 @@
 
 SECTION_RODATA
 
-v210_enc_min_10: times 8 dw 0x4
+cextern pw_4
+%define v210_enc_min_10 pw_4
 v210_enc_max_10: times 8 dw 0x3fb
 
 v210_enc_luma_mult_10: dw 4,1,16,4,1,16,0,0
@@ -32,8 +33,10 @@
 v210_enc_chroma_mult_10: dw 1,4,16,0,16,1,4,0
 v210_enc_chroma_shuf_10: db 0,1,8,9,-1,2,3,-1,10,11,4,5,-1,12,13,-1
 
-v210_enc_min_8: times 16 db 0x1
-v210_enc_max_8: times 16 db 0xfe
+cextern pb_1
+%define v210_enc_min_8 pb_1
+cextern pb_FE
+%define v210_enc_max_8 pb_FE
 
 v210_enc_luma_shuf_8: db 6,-1,7,-1,8,-1,9,-1,10,-1,11,-1,-1,-1,-1,-1
 v210_enc_luma_mult_8: dw 16,4,64,16,4,64,0,0
diff --git a/libavcodec/x86/vc1dsp_mmx.c b/libavcodec/x86/vc1dsp_mmx.c
index 77a8e35..f11170c 100644
--- a/libavcodec/x86/vc1dsp_mmx.c
+++ b/libavcodec/x86/vc1dsp_mmx.c
@@ -446,7 +446,7 @@
             static const int shift_value[] = { 0, 5, 1, 5 };\
             int              shift = (shift_value[hmode]+shift_value[vmode])>>1;\
             int              r;\
-            DECLARE_ALIGNED(16, int16_t, tmp)[12*8];\
+            LOCAL_ALIGNED(16, int16_t, tmp, [12*8]);\
 \
             r = (1<<(shift-1)) + rnd-1;\
             vc1_put_shift_ver_16bits[vmode](tmp, src-1, stride, r, shift);\
diff --git a/libavcodec/x86/vp3dsp.asm b/libavcodec/x86/vp3dsp.asm
index 7ad4c31..ee5a6bf 100644
--- a/libavcodec/x86/vp3dsp.asm
+++ b/libavcodec/x86/vp3dsp.asm
@@ -36,11 +36,11 @@
 pb_7:  times 8 db 0x07
 pb_1F: times 8 db 0x1f
 pb_81: times 8 db 0x81
-pb_FE: times 8 db 0xFE
 
 cextern pb_1
 cextern pb_3
 cextern pb_80
+cextern pb_FE
 
 cextern pw_8
 
diff --git a/libavcodec/x86/vp8dsp_init.c b/libavcodec/x86/vp8dsp_init.c
index 6668f91..8d5d033 100644
--- a/libavcodec/x86/vp8dsp_init.c
+++ b/libavcodec/x86/vp8dsp_init.c
@@ -169,7 +169,7 @@
     uint8_t *dst, ptrdiff_t dststride, uint8_t *src, \
     ptrdiff_t srcstride, int height, int mx, int my) \
 { \
-    DECLARE_ALIGNED(ALIGN, uint8_t, tmp)[SIZE * (MAXHEIGHT + TAPNUMY - 1)]; \
+    LOCAL_ALIGNED(ALIGN, uint8_t, tmp, [SIZE * (MAXHEIGHT + TAPNUMY - 1)]); \
     uint8_t *tmpptr = tmp + SIZE * (TAPNUMY / 2 - 1); \
     src -= srcstride * (TAPNUMY / 2 - 1); \
     ff_put_vp8_epel ## SIZE ## _h ## TAPNUMX ## _ ## OPT( \
@@ -214,7 +214,7 @@
     uint8_t *dst, ptrdiff_t dststride, uint8_t *src, \
     ptrdiff_t srcstride, int height, int mx, int my) \
 { \
-    DECLARE_ALIGNED(ALIGN, uint8_t, tmp)[SIZE * (MAXHEIGHT + 2)]; \
+    LOCAL_ALIGNED(ALIGN, uint8_t, tmp, [SIZE * (MAXHEIGHT + 2)]); \
     ff_put_vp8_bilinear ## SIZE ## _h_ ## OPT( \
         tmp, SIZE,      src, srcstride, height + 1, mx, my); \
     ff_put_vp8_bilinear ## SIZE ## _v_ ## OPT( \
diff --git a/libavcodec/x86/vp9intrapred.asm b/libavcodec/x86/vp9intrapred.asm
index 169676f..31f7d44 100644
--- a/libavcodec/x86/vp9intrapred.asm
+++ b/libavcodec/x86/vp9intrapred.asm
@@ -64,8 +64,6 @@
                   db 11, 13, 15, 0, 1, 2, 3, 4, 5, 6
 pb_02468ACE_13579BDF: db 0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15
 
-pb_2:  times 32 db 2
-pb_15: times 16 db 15
 pb_15x0_1xm1: times 15 db 0
               db -1
 pb_0to2_5x3: db 0, 1, 2
@@ -76,7 +74,9 @@
              times 2 db -1
 
 cextern pb_1
+cextern pb_2
 cextern pb_3
+cextern pb_15
 cextern pw_2
 cextern pw_4
 cextern pw_8
diff --git a/libavcodec/x86/vp9itxfm.asm b/libavcodec/x86/vp9itxfm.asm
index 64859a0..bfe427f 100644
--- a/libavcodec/x86/vp9itxfm.asm
+++ b/libavcodec/x86/vp9itxfm.asm
@@ -407,6 +407,9 @@
 %macro IADST4_FN 5
 INIT_MMX %5
 cglobal vp9_%1_%3_4x4_add, 3, 3, 6 + notcpuflag(ssse3), dst, stride, block, eob
+%if WIN64 && notcpuflag(ssse3)
+WIN64_SPILL_XMM 7
+%endif
     movdqa            xmm5, [pd_8192]
     mova                m0, [blockq+ 0]
     mova                m1, [blockq+ 8]
diff --git a/libavcodec/x86/xvididct.asm b/libavcodec/x86/xvididct.asm
new file mode 100644
index 0000000..0220885
--- /dev/null
+++ b/libavcodec/x86/xvididct.asm
@@ -0,0 +1,983 @@
+; XVID MPEG-4 VIDEO CODEC
+;
+; Conversion from gcc syntax to x264asm syntax with modifications
+; by Christophe Gisquet <christophe.gisquet@gmail.com>
+;
+; ===========     SSE2 inverse discrete cosine transform     ===========
+;
+; Copyright(C) 2003 Pascal Massimino <skal@planet-d.net>
+;
+; Conversion to gcc syntax with modifications
+; by Alexander Strange <astrange@ithinksw.com>
+;
+; Originally from dct/x86_asm/fdct_sse2_skal.asm in Xvid.
+;
+; Vertical pass is an implementation of the scheme:
+;  Loeffler C., Ligtenberg A., and Moschytz C.S.:
+;  Practical Fast 1D DCT Algorithm with Eleven Multiplications,
+;  Proc. ICASSP 1989, 988-991.
+;
+; Horizontal pass is a double 4x4 vector/matrix multiplication,
+; (see also Intel's Application Note 922:
+;  http://developer.intel.com/vtune/cbts/strmsimd/922down.htm
+;  Copyright (C) 1999 Intel Corporation)
+;
+; More details at http://skal.planet-d.net/coding/dct.html
+;
+; =======     MMX and XMM forward discrete cosine transform     =======
+;
+; Copyright(C) 2001 Peter Ross <pross@xvid.org>
+;
+; Originally provided by Intel at AP-922
+; http://developer.intel.com/vtune/cbts/strmsimd/922down.htm
+; (See more app notes at http://developer.intel.com/vtune/cbts/strmsimd/appnotes.htm)
+; but in a limited edition.
+; New macro implements a column part for precise iDCT
+; The routine precision now satisfies IEEE standard 1180-1990.
+;
+; Copyright(C) 2000-2001 Peter Gubanov <peter@elecard.net.ru>
+; Rounding trick Copyright(C) 2000 Michel Lespinasse <walken@zoy.org>
+;
+; http://www.elecard.com/peter/idct.html
+; http://www.linuxvideo.org/mpeg2dec/
+;
+; These examples contain code fragments for first stage iDCT 8x8
+; (for rows) and first stage DCT 8x8 (for columns)
+;
+; conversion to gcc syntax by 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
+
+%include "libavutil/x86/x86util.asm"
+
+SECTION_RODATA
+; Similar to tg_1_16 in MMX code
+tan1:   times 8 dw 13036
+tan2:   times 8 dw 27146
+tan3:   times 8 dw 43790
+sqrt2:  times 8 dw 23170
+
+; SSE2 tables
+iTab1:  dw 0x4000, 0x539f, 0xc000, 0xac61, 0x4000, 0xdd5d, 0x4000, 0xdd5d
+        dw 0x4000, 0x22a3, 0x4000, 0x22a3, 0xc000, 0x539f, 0x4000, 0xac61
+        dw 0x3249, 0x11a8, 0x4b42, 0xee58, 0x11a8, 0x4b42, 0x11a8, 0xcdb7
+        dw 0x58c5, 0x4b42, 0xa73b, 0xcdb7, 0x3249, 0xa73b, 0x4b42, 0xa73b
+iTab2:  dw 0x58c5, 0x73fc, 0xa73b, 0x8c04, 0x58c5, 0xcff5, 0x58c5, 0xcff5
+        dw 0x58c5, 0x300b, 0x58c5, 0x300b, 0xa73b, 0x73fc, 0x58c5, 0x8c04
+        dw 0x45bf, 0x187e, 0x6862, 0xe782, 0x187e, 0x6862, 0x187e, 0xba41
+        dw 0x7b21, 0x6862, 0x84df, 0xba41, 0x45bf, 0x84df, 0x6862, 0x84df
+iTab3:  dw 0x539f, 0x6d41, 0xac61, 0x92bf, 0x539f, 0xd2bf, 0x539f, 0xd2bf
+        dw 0x539f, 0x2d41, 0x539f, 0x2d41, 0xac61, 0x6d41, 0x539f, 0x92bf
+        dw 0x41b3, 0x1712, 0x6254, 0xe8ee, 0x1712, 0x6254, 0x1712, 0xbe4d
+        dw 0x73fc, 0x6254, 0x8c04, 0xbe4d, 0x41b3, 0x8c04, 0x6254, 0x8c04
+iTab4:  dw 0x4b42, 0x6254, 0xb4be, 0x9dac, 0x4b42, 0xd746, 0x4b42, 0xd746
+        dw 0x4b42, 0x28ba, 0x4b42, 0x28ba, 0xb4be, 0x6254, 0x4b42, 0x9dac
+        dw 0x3b21, 0x14c3, 0x587e, 0xeb3d, 0x14c3, 0x587e, 0x14c3, 0xc4df
+        dw 0x6862, 0x587e, 0x979e, 0xc4df, 0x3b21, 0x979e, 0x587e, 0x979e
+
+%if ARCH_X86_32
+; -----------------------------------------------------------------------------
+;
+; The first stage iDCT 8x8 - inverse DCTs of rows
+;
+; -----------------------------------------------------------------------------
+; The 8-point inverse DCT direct algorithm
+; -----------------------------------------------------------------------------
+;
+; static const short w[32] = {
+;     FIX(cos_4_16),  FIX(cos_2_16),  FIX(cos_4_16),  FIX(cos_6_16),
+;     FIX(cos_4_16),  FIX(cos_6_16), -FIX(cos_4_16), -FIX(cos_2_16),
+;     FIX(cos_4_16), -FIX(cos_6_16), -FIX(cos_4_16),  FIX(cos_2_16),
+;     FIX(cos_4_16), -FIX(cos_2_16),  FIX(cos_4_16), -FIX(cos_6_16),
+;     FIX(cos_1_16),  FIX(cos_3_16),  FIX(cos_5_16),  FIX(cos_7_16),
+;     FIX(cos_3_16), -FIX(cos_7_16), -FIX(cos_1_16), -FIX(cos_5_16),
+;     FIX(cos_5_16), -FIX(cos_1_16),  FIX(cos_7_16),  FIX(cos_3_16),
+;     FIX(cos_7_16), -FIX(cos_5_16),  FIX(cos_3_16), -FIX(cos_1_16) };
+;
+; #define DCT_8_INV_ROW(x, y)
+; {
+;     int a0, a1, a2, a3, b0, b1, b2, b3;
+;
+;     a0 = x[0] * w[0]  + x[2] * w[1]  + x[4] * w[2]  + x[6] * w[3];
+;     a1 = x[0] * w[4]  + x[2] * w[5]  + x[4] * w[6]  + x[6] * w[7];
+;     a2 = x[0] * w[8]  + x[2] * w[9]  + x[4] * w[10] + x[6] * w[11];
+;     a3 = x[0] * w[12] + x[2] * w[13] + x[4] * w[14] + x[6] * w[15];
+;     b0 = x[1] * w[16] + x[3] * w[17] + x[5] * w[18] + x[7] * w[19];
+;     b1 = x[1] * w[20] + x[3] * w[21] + x[5] * w[22] + x[7] * w[23];
+;     b2 = x[1] * w[24] + x[3] * w[25] + x[5] * w[26] + x[7] * w[27];
+;     b3 = x[1] * w[28] + x[3] * w[29] + x[5] * w[30] + x[7] * w[31];
+;
+;     y[0] = SHIFT_ROUND(a0 + b0);
+;     y[1] = SHIFT_ROUND(a1 + b1);
+;     y[2] = SHIFT_ROUND(a2 + b2);
+;     y[3] = SHIFT_ROUND(a3 + b3);
+;     y[4] = SHIFT_ROUND(a3 - b3);
+;     y[5] = SHIFT_ROUND(a2 - b2);
+;     y[6] = SHIFT_ROUND(a1 - b1);
+;     y[7] = SHIFT_ROUND(a0 - b0);
+; }
+;
+; -----------------------------------------------------------------------------
+;
+; In this implementation the outputs of the iDCT-1D are multiplied
+;     for rows 0,4 - by cos_4_16,
+;     for rows 1,7 - by cos_1_16,
+;     for rows 2,6 - by cos_2_16,
+;     for rows 3,5 - by cos_3_16
+; and are shifted to the left for better accuracy.
+;
+; For the constants used,
+;     FIX(float_const) = (short) (float_const * (1 << 15) + 0.5)
+;
+; -----------------------------------------------------------------------------
+
+; -----------------------------------------------------------------------------
+; Tables for mmx processors
+; -----------------------------------------------------------------------------
+
+; Table for rows 0,4 - constants are multiplied by cos_4_16
+tab_i_04_mmx: dw  16384,  16384,  16384, -16384
+              dw  21407,   8867,   8867, -21407 ; w07 w05 w03 w01
+              dw  16384, -16384,  16384,  16384 ; w14 w12 w10 w08
+              dw  -8867,  21407, -21407,  -8867 ; w15 w13 w11 w09
+              dw  22725,  12873,  19266, -22725 ; w22 w20 w18 w16
+              dw  19266,   4520,  -4520, -12873 ; w23 w21 w19 w17
+              dw  12873,   4520,   4520,  19266 ; w30 w28 w26 w24
+              dw -22725,  19266, -12873, -22725 ; w31 w29 w27 w25
+; Table for rows 1,7 - constants are multiplied by cos_1_16
+              dw  22725,  22725,  22725, -22725 ; movq-> w06 w04 w02 w00
+              dw  29692,  12299,  12299, -29692 ; w07 w05 w03 w01
+              dw  22725, -22725,  22725,  22725 ; w14 w12 w10 w08
+              dw -12299,  29692, -29692, -12299 ; w15 w13 w11 w09
+              dw  31521,  17855,  26722, -31521 ; w22 w20 w18 w16
+              dw  26722,   6270,  -6270, -17855 ; w23 w21 w19 w17
+              dw  17855,   6270,   6270,  26722 ; w30 w28 w26 w24
+              dw -31521,  26722, -17855, -31521 ; w31 w29 w27 w25
+; Table for rows 2,6 - constants are multiplied by cos_2_16
+              dw  21407,  21407,  21407, -21407 ; movq-> w06 w04 w02 w00
+              dw  27969,  11585,  11585, -27969 ; w07 w05 w03 w01
+              dw  21407, -21407,  21407,  21407 ; w14 w12 w10 w08
+              dw -11585,  27969, -27969, -11585 ; w15 w13 w11 w09
+              dw  29692,  16819,  25172, -29692 ; w22 w20 w18 w16
+              dw  25172,   5906,  -5906, -16819 ; w23 w21 w19 w17
+              dw  16819,   5906,   5906,  25172 ; w30 w28 w26 w24
+              dw -29692,  25172, -16819, -29692 ; w31 w29 w27 w25
+; Table for rows 3,5 - constants are multiplied by cos_3_16
+              dw  19266,  19266,  19266, -19266 ; movq-> w06 w04 w02 w00
+              dw  25172,  10426,  10426, -25172 ; w07 w05 w03 w01
+              dw  19266, -19266,  19266,  19266 ; w14 w12 w10 w08
+              dw -10426,  25172, -25172, -10426 ; w15 w13 w11 w09
+              dw  26722,  15137,  22654, -26722 ; w22 w20 w18 w16
+              dw  22654,   5315,  -5315, -15137 ; w23 w21 w19 w17
+              dw  15137,   5315,   5315,  22654 ; w30 w28 w26 w24
+              dw -26722,  22654, -15137, -26722 ; w31 w29 w27 w25
+
+; -----------------------------------------------------------------------------
+; Tables for xmm processors
+; -----------------------------------------------------------------------------
+
+; %3 for rows 0,4 - constants are multiplied by cos_4_16
+tab_i_04_xmm: dw  16384,  21407,  16384,   8867 ; movq-> w05 w04 w01 w00
+              dw  16384,   8867, -16384, -21407 ; w07 w06 w03 w02
+              dw  16384,  -8867,  16384, -21407 ; w13 w12 w09 w08
+              dw -16384,  21407,  16384,  -8867 ; w15 w14 w11 w10
+              dw  22725,  19266,  19266,  -4520 ; w21 w20 w17 w16
+              dw  12873,   4520, -22725, -12873 ; w23 w22 w19 w18
+              dw  12873, -22725,   4520, -12873 ; w29 w28 w25 w24
+              dw   4520,  19266,  19266, -22725 ; w31 w30 w27 w26
+; %3 for rows 1,7 - constants are multiplied by cos_1_16
+              dw  22725,  29692,  22725,  12299 ; movq-> w05 w04 w01 w00
+              dw  22725,  12299, -22725, -29692 ; w07 w06 w03 w02
+              dw  22725, -12299,  22725, -29692 ; w13 w12 w09 w08
+              dw -22725,  29692,  22725, -12299 ; w15 w14 w11 w10
+              dw  31521,  26722,  26722,  -6270 ; w21 w20 w17 w16
+              dw  17855,   6270, -31521, -17855 ; w23 w22 w19 w18
+              dw  17855, -31521,   6270, -17855 ; w29 w28 w25 w24
+              dw   6270,  26722,  26722, -31521 ; w31 w30 w27 w26
+; %3 for rows 2,6 - constants are multiplied by cos_2_16
+              dw  21407,  27969,  21407,  11585 ; movq-> w05 w04 w01 w00
+              dw  21407,  11585, -21407, -27969 ; w07 w06 w03 w02
+              dw  21407, -11585,  21407, -27969 ; w13 w12 w09 w08
+              dw -21407,  27969,  21407, -11585 ; w15 w14 w11 w10
+              dw  29692,  25172,  25172,  -5906 ; w21 w20 w17 w16
+              dw  16819,   5906, -29692, -16819 ; w23 w22 w19 w18
+              dw  16819, -29692,   5906, -16819 ; w29 w28 w25 w24
+              dw   5906,  25172,  25172, -29692 ; w31 w30 w27 w26
+; %3 for rows 3,5 - constants are multiplied by cos_3_16
+              dw  19266,  25172,  19266,  10426 ; movq-> w05 w04 w01 w00
+              dw  19266,  10426, -19266, -25172 ; w07 w06 w03 w02
+              dw  19266, -10426,  19266, -25172 ; w13 w12 w09 w08
+              dw -19266,  25172,  19266, -10426 ; w15 w14 w11 w10
+              dw  26722,  22654,  22654,  -5315 ; w21 w20 w17 w16
+              dw  15137,   5315, -26722, -15137 ; w23 w22 w19 w18
+              dw  15137, -26722,   5315, -15137 ; w29 w28 w25 w24
+              dw   5315,  22654,  22654, -26722 ; w31 w30 w27 w26
+%endif ; ~ARCH_X86_32
+
+; Similar to rounder_0 in MMX code
+; 4 first similar, then: 4*8->6*16  5*8->4*16  6/7*8->5*16
+walkenIdctRounders: times 4 dd 65536
+                    times 4 dd  3597
+                    times 4 dd  2260
+                    times 4 dd  1203
+                    times 4 dd   120
+                    times 4 dd   512
+                    times 2 dd     0
+
+pb_127: times 8 db 127
+
+SECTION .text
+
+; Temporary storage before the column pass
+%define ROW1 xmm6
+%define ROW3 xmm4
+%define ROW5 xmm5
+%define ROW7 xmm7
+
+%macro CLEAR_ODD 1
+    pxor      %1, %1
+%endmacro
+%macro PUT_ODD 1
+    pshufhw   %1, xmm2, 0x1B
+%endmacro
+
+%macro MOV32 2
+%if ARCH_X86_32
+    movdqa    %2, %1
+%endif
+%endmacro
+
+%macro CLEAR_EVEN 1
+%if ARCH_X86_64
+    CLEAR_ODD %1
+%endif
+%endmacro
+
+%macro PUT_EVEN 1
+%if ARCH_X86_64
+    PUT_ODD   %1
+%else
+    pshufhw xmm2, xmm2, 0x1B
+    movdqa    %1, xmm2
+%endif
+%endmacro
+
+%if ARCH_X86_64
+%define ROW0  xmm8
+%define REG0  ROW0
+%define ROW2  xmm9
+%define REG2  ROW2
+%define ROW4  xmm10
+%define REG4  ROW4
+%define ROW6  xmm11
+%define REG6  ROW6
+%define XMMS  xmm12
+%define SREG2 REG2
+%define TAN3  xmm13
+%define TAN1  xmm14
+%else
+%define ROW0  [BLOCK + 0*16]
+%define REG0  xmm4
+%define ROW2  [BLOCK + 2*16]
+%define REG2  xmm4
+%define ROW4  [BLOCK + 4*16]
+%define REG4  xmm6
+%define ROW6  [BLOCK + 6*16]
+%define REG6  xmm6
+%define XMMS  xmm2
+%define SREG2 xmm7
+%define TAN3  xmm0
+%define TAN1  xmm2
+%endif
+
+%macro JZ  2
+    test      %1, %1
+    jz       .%2
+%endmacro
+
+%macro JNZ  2
+    test      %1, %1
+    jnz      .%2
+%endmacro
+
+%macro TEST_ONE_ROW 4 ; src, reg, clear, arg
+    %3        %4
+    movq     mm1, [%1]
+    por      mm1, [%1 + 8]
+    paddusb  mm1, mm0
+    pmovmskb  %2, mm1
+%endmacro
+
+;row1, row2, reg1, reg2, clear1, arg1, clear2, arg2
+%macro  TEST_TWO_ROWS  8
+    %5         %6
+    %7         %8
+    movq      mm1, [%1 + 0]
+    por       mm1, [%1 + 8]
+    movq      mm2, [%2 + 0]
+    por       mm2, [%2 + 8]
+    paddusb   mm1, mm0
+    paddusb   mm2, mm0
+    pmovmskb   %3, mm1
+    pmovmskb   %4, mm2
+%endmacro
+
+; IDCT pass on rows.
+%macro iMTX_MULT   4-5 ; src, table, put, arg, rounder
+    movdqa       xmm3, [%1]
+    movdqa       xmm0, xmm3
+    pshufd       xmm1, xmm3, 0x11 ; 4602
+    punpcklqdq   xmm0, xmm0       ; 0246
+    pmaddwd      xmm0, [%2]
+    pmaddwd      xmm1, [%2+16]
+    pshufd       xmm2, xmm3, 0xBB ; 5713
+    punpckhqdq   xmm3, xmm3       ; 1357
+    pmaddwd      xmm2, [%2+32]
+    pmaddwd      xmm3, [%2+48]
+    paddd        xmm0, xmm1
+    paddd        xmm2, xmm3
+%if %0 == 5
+    paddd        xmm0, [walkenIdctRounders+%5]
+%endif
+    movdqa       xmm3, xmm2
+    paddd        xmm2, xmm0
+    psubd        xmm0, xmm3
+    psrad        xmm2, 11
+    psrad        xmm0, 11
+    packssdw     xmm2, xmm0
+    %3           %4
+%endmacro
+
+%macro iLLM_HEAD 0
+    movdqa   TAN3, [tan3]
+    movdqa   TAN1, [tan1]
+%endmacro
+
+%macro FIRST_HALF 2  ; %1=dct  %2=type(normal,add,put)
+    psraw    xmm5, 6
+    psraw    REG0, 6
+    psraw    TAN3, 6
+    psraw    xmm3, 6
+    ; dct coeffs must still be written for AC prediction
+%if %2 == 0
+    movdqa   [%1+1*16], TAN3
+    movdqa   [%1+2*16], xmm3
+    movdqa   [%1+5*16], REG0
+    movdqa   [%1+6*16], xmm5
+%else
+    ; Must now load args as gprs are no longer used for masks
+    ; DEST is set to where address of dest was loaded
+    %if ARCH_X86_32
+        %if %2 == 2 ; Not enough xmms, store
+    movdqa   [%1+1*16], TAN3
+    movdqa   [%1+2*16], xmm3
+    movdqa   [%1+5*16], REG0
+    movdqa   [%1+6*16], xmm5
+        %endif
+    %xdefine DEST r2q ; BLOCK is r0, stride r1
+    movifnidn DEST, destm
+    movifnidn strideq, stridem
+    %else
+    %xdefine DEST r0q
+    %endif
+    lea      r3q, [3*strideq]
+    %if %2 == 1
+    packuswb TAN3, xmm3
+    packuswb xmm5, REG0
+    movq     [DEST + strideq], TAN3
+    movhps   [DEST + 2*strideq], TAN3
+    ; REG0 and TAN3 are now available (and likely used in second half)
+    %endif
+%endif
+%endmacro
+
+%macro SECOND_HALF 6 ; %1=dct  %2=type(normal,add,put) 3-6: xmms
+    psraw    %3, 6
+    psraw    %4, 6
+    psraw    %5, 6
+    psraw    %6, 6
+    ; dct coeffs must still be written for AC prediction
+%if %2 == 0
+    movdqa   [%1+0*16], %3
+    movdqa   [%1+3*16], %5
+    movdqa   [%1+4*16], %6
+    movdqa   [%1+7*16], %4
+%elif %2 == 1
+    packuswb %3, %5
+    packuswb %6, %4
+    ; address of dest may have been loaded
+    movq     [DEST], %3
+    movhps   [DEST + r3q], %3
+    lea      DEST, [DEST + 4*strideq]
+    movq     [DEST], %6
+    movhps   [DEST + r3q], %6
+    ; and now write remainder of first half
+    movq     [DEST + 2*strideq], xmm5
+    movhps   [DEST + strideq], xmm5
+%elif %2 == 2
+    pxor        xmm0, xmm0
+    %if ARCH_X86_32
+    ; free: m3 REG0=m4 m5
+    ; input: m1, m7, m2, m6
+    movq        xmm3, [DEST+0*strideq]
+    movq        xmm4, [DEST+1*strideq]
+    punpcklbw   xmm3, xmm0
+    punpcklbw   xmm4, xmm0
+    paddsw      xmm3, %3
+    paddsw      xmm4, [%1 + 1*16]
+    movq          %3, [DEST+2*strideq]
+    movq        xmm5, [DEST+      r3q]
+    punpcklbw     %3, xmm0
+    punpcklbw   xmm5, xmm0
+    paddsw        %3, [%1 + 2*16]
+    paddsw      xmm5, %5
+    packuswb    xmm3, xmm4
+    packuswb      %3, xmm5
+    movq    [DEST+0*strideq], xmm3
+    movhps  [DEST+1*strideq], xmm3
+    movq    [DEST+2*strideq], %3
+    movhps  [DEST+      r3q], %3
+    lea         DEST, [DEST+4*strideq]
+    movq        xmm3, [DEST+0*strideq]
+    movq        xmm4, [DEST+1*strideq]
+    movq          %3, [DEST+2*strideq]
+    movq        xmm5, [DEST+      r3q]
+    punpcklbw   xmm3, xmm0
+    punpcklbw   xmm4, xmm0
+    punpcklbw     %3, xmm0
+    punpcklbw   xmm5, xmm0
+    paddsw      xmm3, %6
+    paddsw      xmm4, [%1 + 5*16]
+    paddsw        %3, [%1 + 6*16]
+    paddsw      xmm5, %4
+    packuswb    xmm3, xmm4
+    packuswb      %3, xmm5
+    movq    [DEST+0*strideq], xmm3
+    movhps  [DEST+1*strideq], xmm3
+    movq    [DEST+2*strideq], %3
+    movhps  [DEST+      r3q], %3
+    %else
+    ; l1:TAN3=m13  l2:m3  l5:REG0=m8 l6=m5
+    ; input: m1, m7/SREG2=m9, TAN1=m14, REG4=m10
+    movq        xmm2, [DEST+0*strideq]
+    movq        xmm4, [DEST+1*strideq]
+    movq       xmm12, [DEST+2*strideq]
+    movq       xmm11, [DEST+      r3q]
+    punpcklbw   xmm2, xmm0
+    punpcklbw   xmm4, xmm0
+    punpcklbw  xmm12, xmm0
+    punpcklbw  xmm11, xmm0
+    paddsw      xmm2, %3
+    paddsw      xmm4, TAN3
+    paddsw     xmm12, xmm3
+    paddsw     xmm11, %5
+    packuswb    xmm2, xmm4
+    packuswb   xmm12, xmm11
+    movq    [DEST+0*strideq], xmm2
+    movhps  [DEST+1*strideq], xmm2
+    movq    [DEST+2*strideq], xmm12
+    movhps  [DEST+      r3q], xmm12
+    lea         DEST, [DEST+4*strideq]
+    movq        xmm2, [DEST+0*strideq]
+    movq        xmm4, [DEST+1*strideq]
+    movq       xmm12, [DEST+2*strideq]
+    movq       xmm11, [DEST+      r3q]
+    punpcklbw   xmm2, xmm0
+    punpcklbw   xmm4, xmm0
+    punpcklbw  xmm12, xmm0
+    punpcklbw  xmm11, xmm0
+    paddsw      xmm2, %6
+    paddsw      xmm4, REG0
+    paddsw     xmm12, xmm5
+    paddsw     xmm11, %4
+    packuswb    xmm2, xmm4
+    packuswb   xmm12, xmm11
+    movq    [DEST+0*strideq], xmm2
+    movhps  [DEST+1*strideq], xmm2
+    movq    [DEST+2*strideq], xmm12
+    movhps  [DEST+      r3q], xmm12
+    %endif
+%endif
+%endmacro
+
+
+; IDCT pass on columns.
+%macro iLLM_PASS  2  ; %1=dct  %2=type(normal,add,put)
+    movdqa   xmm1, TAN3
+    movdqa   xmm3, TAN1
+    pmulhw   TAN3, xmm4
+    pmulhw   xmm1, xmm5
+    paddsw   TAN3, xmm4
+    paddsw   xmm1, xmm5
+    psubsw   TAN3, xmm5
+    paddsw   xmm1, xmm4
+    pmulhw   xmm3, xmm7
+    pmulhw   TAN1, xmm6
+    paddsw   xmm3, xmm6
+    psubsw   TAN1, xmm7
+    movdqa   xmm7, xmm3
+    movdqa   xmm6, TAN1
+    psubsw   xmm3, xmm1
+    psubsw   TAN1, TAN3
+    paddsw   xmm1, xmm7
+    paddsw   TAN3, xmm6
+    movdqa   xmm6, xmm3
+    psubsw   xmm3, TAN3
+    paddsw   TAN3, xmm6
+    movdqa   xmm4, [sqrt2]
+    pmulhw   xmm3, xmm4
+    pmulhw   TAN3, xmm4
+    paddsw   TAN3, TAN3
+    paddsw   xmm3, xmm3
+    movdqa   xmm7, [tan2]
+    MOV32    ROW2, REG2
+    MOV32    ROW6, REG6
+    movdqa   xmm5, xmm7
+    pmulhw   xmm7, REG6
+    pmulhw   xmm5, REG2
+    paddsw   xmm7, REG2
+    psubsw   xmm5, REG6
+    MOV32    ROW0, REG0
+    MOV32    ROW4, REG4
+    MOV32    TAN1, [BLOCK]
+    movdqa   XMMS, REG0
+    psubsw   REG0, REG4
+    paddsw   REG4, XMMS
+    movdqa   XMMS, REG4
+    psubsw   REG4, xmm7
+    paddsw   xmm7, XMMS
+    movdqa   XMMS, REG0
+    psubsw   REG0, xmm5
+    paddsw   xmm5, XMMS
+    movdqa   XMMS, xmm5
+    psubsw   xmm5, TAN3
+    paddsw   TAN3, XMMS
+    movdqa   XMMS, REG0
+    psubsw   REG0, xmm3
+    paddsw   xmm3, XMMS
+    MOV32    [BLOCK], TAN1
+
+    FIRST_HALF %1, %2
+
+    movdqa   xmm0, xmm7
+    movdqa   xmm4, REG4
+    psubsw   xmm7, xmm1
+    psubsw   REG4, TAN1
+    paddsw   xmm1, xmm0
+    paddsw   TAN1, xmm4
+
+    SECOND_HALF %1, %2, xmm1, xmm7, TAN1, REG4
+%endmacro
+
+; IDCT pass on columns, assuming rows 4-7 are zero
+%macro iLLM_PASS_SPARSE   2 ; %1=dct   %2=type(normal,put,add)
+    pmulhw   TAN3, xmm4
+    paddsw   TAN3, xmm4
+    movdqa   xmm3, xmm6
+    pmulhw   TAN1, xmm6
+    movdqa   xmm1, xmm4
+    psubsw   xmm3, xmm1
+    paddsw   xmm1, xmm6
+    movdqa   xmm6, TAN1
+    psubsw   TAN1, TAN3
+    paddsw   TAN3, xmm6
+    movdqa   xmm6, xmm3
+    psubsw   xmm3, TAN3
+    paddsw   TAN3, xmm6
+    movdqa   xmm4, [sqrt2]
+    pmulhw   xmm3, xmm4
+    pmulhw   TAN3, xmm4
+    paddsw   TAN3, TAN3
+    paddsw   xmm3, xmm3
+    movdqa   xmm5, [tan2]
+    MOV32    ROW2, SREG2
+    pmulhw   xmm5, SREG2
+    MOV32    ROW0, REG0
+    movdqa   xmm6, REG0
+    psubsw   xmm6, SREG2
+    paddsw  SREG2, REG0
+    MOV32    TAN1, [BLOCK]
+    movdqa   XMMS, REG0
+    psubsw   REG0, xmm5
+    paddsw   xmm5, XMMS
+    movdqa   XMMS, xmm5
+    psubsw   xmm5, TAN3
+    paddsw   TAN3, XMMS
+    movdqa   XMMS, REG0
+    psubsw   REG0, xmm3
+    paddsw   xmm3, XMMS
+    MOV32    [BLOCK], TAN1
+
+    FIRST_HALF %1, %2
+
+    movdqa   xmm0, SREG2
+    movdqa   xmm4, xmm6
+    psubsw  SREG2, xmm1
+    psubsw   xmm6, TAN1
+    paddsw   xmm1, xmm0
+    paddsw   TAN1, xmm4
+
+    SECOND_HALF %1, %2, xmm1, SREG2, TAN1, xmm6
+%endmacro
+
+%macro IDCT_SSE2 1 ; 0=normal  1=put  2=add
+%if %1 == 0 || ARCH_X86_32
+    %define GPR0  r1d
+    %define GPR1  r2d
+    %define GPR2  r3d
+    %define GPR3  r4d
+    %define NUM_GPRS 5
+%else
+    %define GPR0  r3d
+    %define GPR1  r4d
+    %define GPR2  r5d
+    %define GPR3  r6d
+    %define NUM_GPRS 7
+%endif
+%if %1 == 0
+cglobal xvid_idct, 1, NUM_GPRS, 8+7*ARCH_X86_64, block
+%xdefine BLOCK blockq
+%else
+    %if %1 == 1
+cglobal xvid_idct_put, 0, NUM_GPRS, 8+7*ARCH_X86_64, dest, stride, block
+    %else
+cglobal xvid_idct_add, 0, NUM_GPRS, 8+7*ARCH_X86_64, dest, stride, block
+    %endif
+    %if ARCH_X86_64
+    %xdefine BLOCK blockq
+    %else
+    mov    r0q, blockm
+    %xdefine BLOCK r0q
+    %endif
+%endif
+    movq           mm0, [pb_127]
+    iMTX_MULT      BLOCK + 0*16, iTab1, PUT_EVEN, ROW0, 0*16
+    iMTX_MULT      BLOCK + 1*16, iTab2, PUT_ODD, ROW1,  1*16
+    iMTX_MULT      BLOCK + 2*16, iTab3, PUT_EVEN, ROW2, 2*16
+
+    TEST_TWO_ROWS  BLOCK + 3*16, BLOCK + 4*16, GPR0, GPR1, CLEAR_ODD, ROW3, CLEAR_EVEN, ROW4 ; a, c
+    JZ   GPR0, col1
+    iMTX_MULT      BLOCK + 3*16, iTab4, PUT_ODD, ROW3,  3*16
+.col1:
+    TEST_TWO_ROWS  BLOCK + 5*16, BLOCK + 6*16, GPR0, GPR2, CLEAR_ODD, ROW5, CLEAR_EVEN, ROW6 ; a, d
+    TEST_ONE_ROW   BLOCK + 7*16, GPR3, CLEAR_ODD, ROW7 ; esi
+
+    iLLM_HEAD
+    JNZ  GPR1, 2
+    JNZ  GPR0, 3
+    JNZ  GPR2, 4
+    JNZ  GPR3, 5
+    iLLM_PASS_SPARSE BLOCK, %1
+    jmp .6
+.2:
+    iMTX_MULT     BLOCK + 4*16, iTab1, PUT_EVEN, ROW4
+.3:
+    iMTX_MULT     BLOCK + 5*16, iTab4, PUT_ODD, ROW5,  4*16
+    JZ   GPR2, col2
+.4:
+    iMTX_MULT     BLOCK + 6*16, iTab3, PUT_EVEN, ROW6, 5*16
+.col2:
+    JZ   GPR3, col3
+.5:
+    iMTX_MULT     BLOCK + 7*16, iTab2, PUT_ODD, ROW7,  5*16
+.col3:
+%if ARCH_X86_32
+    iLLM_HEAD
+%endif
+    iLLM_PASS     BLOCK, %1
+.6:
+    RET
+%endmacro
+
+INIT_XMM sse2
+IDCT_SSE2 0
+IDCT_SSE2 1
+IDCT_SSE2 2
+
+%if ARCH_X86_32
+
+; %1=offset  %2=tab_offset
+; %3=rnd_offset where 4*8->6*16  5*8->4*16  6/7*8->5*16
+%macro DCT_8_INV_ROW  3
+    movq       mm0, [r0+16*%1+0]  ; 0 ; x3 x2 x1 x0
+    movq       mm1, [r0+16*%1+8]  ; 1 ; x7 x6 x5 x4
+    movq       mm2, mm0       ; 2 ; x3 x2 x1 x0
+    movq       mm3, [%2+ 0]   ; 3 ; w06 w04 w02 w00
+%if cpuflag(mmxext)
+    pshufw     mm0, mm0, 0x88 ; x2 x0 x2 x0
+    movq       mm4, [%2+ 8]   ; 4 ; w07 w06 w03 w02
+    movq       mm5, mm1       ; 5 ; x7 x6 x5 x4
+    pmaddwd    mm3, mm0       ; x2*w05+x0*w04 x2*w01+x0*w00
+    movq       mm6, [%2+32]   ; 6 ; w21 w20 w17 w16
+    pshufw     mm1, mm1, 0x88 ; x6 x4 x6 x4
+    pmaddwd    mm4, mm1       ; x6*w07+x4*w06 x6*w03+x4*w02
+    movq       mm7, [%2+40]   ; 7; w23 w22 w19 w18
+    pshufw     mm2, mm2, 0xdd ; x3 x1 x3 x1
+    pmaddwd    mm6, mm2       ; x3*w21+x1*w20 x3*w17+x1*w16
+    pshufw     mm5, mm5, 0xdd ; x7 x5 x7 x5
+    pmaddwd    mm7, mm5       ; x7*w23+x5*w22 x7*w19+x5*w18
+    paddd      mm3, [walkenIdctRounders + %3]      ; +%3
+    pmaddwd    mm0, [%2+16]   ; x2*w13+x0*w12 x2*w09+x0*w08
+    paddd      mm3, mm4       ; 4 ; a1=sum(even1) a0=sum(even0)
+    pmaddwd    mm1, [%2+24]   ; x6*w15+x4*w14 x6*w11+x4*w10
+    movq       mm4, mm3       ; 4 ; a1 a0
+    pmaddwd    mm2, [%2+48]   ; x3*w29+x1*w28 x3*w25+x1*w24
+    paddd      mm6, mm7       ; 7 ; b1=sum(odd1) b0=sum(odd0)
+    pmaddwd    mm5, [%2+56]   ; x7*w31+x5*w30 x7*w27+x5*w26
+    paddd      mm3, mm6       ; a1+b1 a0+b0
+    paddd      mm0, [walkenIdctRounders + %3]      ; +%3
+    psrad      mm3, 11        ; y1=a1+b1 y0=a0+b0
+    paddd      mm0, mm1       ; 1 ; a3=sum(even3) a2=sum(even2)
+    psubd      mm4, mm6       ; 6 ; a1-b1 a0-b0
+    movq       mm7, mm0       ; 7 ; a3 a2
+    paddd      mm2, mm5       ; 5 ; b3=sum(odd3) b2=sum(odd2)
+    paddd      mm0, mm2       ; a3+b3 a2+b2
+    psrad      mm4, 11        ; y6=a1-b1 y7=a0-b0
+    psubd      mm7, mm2       ; 2 ; a3-b3 a2-b2
+    psrad      mm0, 11        ; y3=a3+b3 y2=a2+b2
+    psrad      mm7, 11        ; y4=a3-b3 y5=a2-b2
+    packssdw   mm3, mm0       ; 0 ; y3 y2 y1 y0
+    packssdw   mm7, mm4       ; 4 ; y6 y7 y4 y5
+    movq  [r0+16*%1+0], mm3       ; 3 ; save y3 y2 y1 y0
+    pshufw     mm7, mm7, 0xb1 ; y7 y6 y5 y4
+%else
+    punpcklwd  mm0, mm1       ; x5 x1 x4 x0
+    movq       mm5, mm0       ; 5 ; x5 x1 x4 x0
+    punpckldq  mm0, mm0       ; x4 x0 x4 x0
+    movq       mm4, [%2+ 8]   ; 4 ; w07 w05 w03 w01
+    punpckhwd  mm2, mm1       ; 1 ; x7 x3 x6 x2
+    pmaddwd    mm3, mm0       ; x4*w06+x0*w04 x4*w02+x0*w00
+    movq       mm6, mm2       ; 6 ; x7 x3 x6 x2
+    movq       mm1, [%2+32]   ; 1 ; w22 w20 w18 w16
+    punpckldq  mm2, mm2       ; x6 x2 x6 x2
+    pmaddwd    mm4, mm2       ; x6*w07+x2*w05 x6*w03+x2*w01
+    punpckhdq  mm5, mm5       ; x5 x1 x5 x1
+    pmaddwd    mm0, [%2+16]   ; x4*w14+x0*w12 x4*w10+x0*w08
+    punpckhdq  mm6, mm6       ; x7 x3 x7 x3
+    movq       mm7, [%2+40]   ; 7 ; w23 w21 w19 w17
+    pmaddwd    mm1, mm5       ; x5*w22+x1*w20 x5*w18+x1*w16
+    paddd      mm3, [walkenIdctRounders + %3]     ; +%3
+    pmaddwd    mm7, mm6       ; x7*w23+x3*w21 x7*w19+x3*w17
+    pmaddwd    mm2, [%2+24]   ; x6*w15+x2*w13 x6*w11+x2*w09
+    paddd      mm3, mm4       ; 4 ; a1=sum(even1) a0=sum(even0)
+    pmaddwd    mm5, [%2+48]   ; x5*w30+x1*w28 x5*w26+x1*w24
+    movq       mm4, mm3       ; 4 ; a1 a0
+    pmaddwd    mm6, [%2+56]   ; x7*w31+x3*w29 x7*w27+x3*w25
+    paddd      mm1, mm7       ; 7 ; b1=sum(odd1) b0=sum(odd0)
+    paddd      mm0, [walkenIdctRounders + %3]     ; +%3
+    psubd      mm3, mm1       ; a1-b1 a0-b0
+    psrad      mm3, 11        ; y6=a1-b1 y7=a0-b0
+    paddd      mm1, mm4       ; 4 ; a1+b1 a0+b0
+    paddd      mm0, mm2       ; 2 ; a3=sum(even3) a2=sum(even2)
+    psrad      mm1, 11        ; y1=a1+b1 y0=a0+b0
+    paddd      mm5, mm6       ; 6 ; b3=sum(odd3) b2=sum(odd2)
+    movq       mm4, mm0       ; 4 ; a3 a2
+    paddd      mm0, mm5       ; a3+b3 a2+b2
+    psubd      mm4, mm5       ; 5 ; a3-b3 a2-b2
+    psrad      mm0, 11        ; y3=a3+b3 y2=a2+b2
+    psrad      mm4, 11        ; y4=a3-b3 y5=a2-b2
+    packssdw   mm1, mm0       ; 0 ; y3 y2 y1 y0
+    packssdw   mm4, mm3       ; 3 ; y6 y7 y4 y5
+    movq       mm7, mm4       ; 7 ; y6 y7 y4 y5
+    psrld      mm4, 16        ; 0 y6 0 y4
+    pslld      mm7, 16        ; y7 0 y5 0
+    movq  [r0+16*%1+0], mm1   ; 1 ; save y3 y2 y1 y0
+    por        mm7, mm4       ; 4 ; y7 y6 y5 y4
+%endif
+    movq  [r0+16*%1+8], mm7   ; 7 ; save y7 y6 y5 y4
+%endmacro
+
+; -----------------------------------------------------------------------------
+;
+; The first stage DCT 8x8 - forward DCTs of columns
+;
+; The %2puts are multiplied
+; for rows 0,4 - on cos_4_16,
+; for rows 1,7 - on cos_1_16,
+; for rows 2,6 - on cos_2_16,
+; for rows 3,5 - on cos_3_16
+; and are shifted to the left for rise of accuracy
+;
+; -----------------------------------------------------------------------------
+;
+; The 8-point scaled forward DCT algorithm (26a8m)
+;
+; -----------------------------------------------------------------------------
+;
+;#define DCT_8_FRW_COL(x, y)
+; {
+;     short t0, t1, t2, t3, t4, t5, t6, t7;
+;     short tp03, tm03, tp12, tm12, tp65, tm65;
+;     short tp465, tm465, tp765, tm765;
+;
+;     t0 = LEFT_SHIFT(x[0] + x[7]);
+;     t1 = LEFT_SHIFT(x[1] + x[6]);
+;     t2 = LEFT_SHIFT(x[2] + x[5]);
+;     t3 = LEFT_SHIFT(x[3] + x[4]);
+;     t4 = LEFT_SHIFT(x[3] - x[4]);
+;     t5 = LEFT_SHIFT(x[2] - x[5]);
+;     t6 = LEFT_SHIFT(x[1] - x[6]);
+;     t7 = LEFT_SHIFT(x[0] - x[7]);
+;
+;     tp03 = t0 + t3;
+;     tm03 = t0 - t3;
+;     tp12 = t1 + t2;
+;     tm12 = t1 - t2;
+;
+;     y[0] = tp03 + tp12;
+;     y[4] = tp03 - tp12;
+;
+;     y[2] = tm03 + tm12 * tg_2_16;
+;     y[6] = tm03 * tg_2_16 - tm12;
+;
+;     tp65 = (t6 + t5) * cos_4_16;
+;     tm65 = (t6 - t5) * cos_4_16;
+;
+;     tp765 = t7 + tp65;
+;     tm765 = t7 - tp65;
+;     tp465 = t4 + tm65;
+;     tm465 = t4 - tm65;
+;
+;     y[1] = tp765 + tp465 * tg_1_16;
+;     y[7] = tp765 * tg_1_16 - tp465;
+;     y[5] = tm765 * tg_3_16 + tm465;
+;     y[3] = tm765 - tm465 * tg_3_16;
+; }
+;
+; -----------------------------------------------------------------------------
+
+; -----------------------------------------------------------------------------
+; DCT_8_INV_COL_4  INP,OUT
+; -----------------------------------------------------------------------------
+%macro DCT_8_INV_COL 1
+    movq        mm0, [tan3]
+    movq        mm3, [%1+16*3]
+    movq        mm1, mm0 ; tg_3_16
+    movq        mm5, [%1+16*5]
+    pmulhw      mm0, mm3 ; x3*(tg_3_16-1)
+    movq        mm4, [tan1]
+    pmulhw      mm1, mm5 ; x5*(tg_3_16-1)
+    movq        mm7, [%1+16*7]
+    movq        mm2, mm4 ; tg_1_16
+    movq        mm6, [%1+16*1]
+    pmulhw      mm4, mm7 ; x7*tg_1_16
+    paddsw      mm0, mm3 ; x3*tg_3_16
+    pmulhw      mm2, mm6 ; x1*tg_1_16
+    paddsw      mm1, mm3 ; x3+x5*(tg_3_16-1)
+    psubsw      mm0, mm5 ; x3*tg_3_16-x5 = tm35
+    movq        mm3, [sqrt2]
+    paddsw      mm1, mm5 ; x3+x5*tg_3_16 = tp35
+    paddsw      mm4, mm6 ; x1+tg_1_16*x7 = tp17
+    psubsw      mm2, mm7 ; x1*tg_1_16-x7 = tm17
+    movq        mm5, mm4 ; tp17
+    movq        mm6, mm2 ; tm17
+    paddsw      mm5, mm1 ; tp17+tp35 = b0
+    psubsw      mm6, mm0 ; tm17-tm35 = b3
+    psubsw      mm4, mm1 ; tp17-tp35 = t1
+    paddsw      mm2, mm0 ; tm17+tm35 = t2
+    movq        mm7, [tan2]
+    movq        mm1, mm4 ; t1
+    movq  [%1+3*16], mm5 ; save b0
+    paddsw      mm1, mm2 ; t1+t2
+    movq  [%1+5*16], mm6 ; save b3
+    psubsw      mm4, mm2 ; t1-t2
+    movq        mm5, [%1+2*16]
+    movq        mm0, mm7 ; tg_2_16
+    movq        mm6, [%1+6*16]
+    pmulhw      mm0, mm5 ; x2*tg_2_16
+    pmulhw      mm7, mm6 ; x6*tg_2_16
+    pmulhw      mm1, mm3 ; ocos_4_16*(t1+t2) = b1/2
+    movq        mm2, [%1+0*16]
+    pmulhw      mm4, mm3 ; ocos_4_16*(t1-t2) = b2/2
+    psubsw      mm0, mm6 ; t2*tg_2_16-x6 = tm26
+    movq        mm3, mm2 ; x0
+    movq        mm6, [%1+4*16]
+    paddsw      mm7, mm5 ; x2+x6*tg_2_16 = tp26
+    paddsw      mm2, mm6 ; x0+x4 = tp04
+    psubsw      mm3, mm6 ; x0-x4 = tm04
+    movq        mm5, mm2 ; tp04
+    movq        mm6, mm3 ; tm04
+    psubsw      mm2, mm7 ; tp04-tp26 = a3
+    paddsw      mm3, mm0 ; tm04+tm26 = a1
+    paddsw      mm1, mm1 ; b1
+    paddsw      mm4, mm4 ; b2
+    paddsw      mm5, mm7 ; tp04+tp26 = a0
+    psubsw      mm6, mm0 ; tm04-tm26 = a2
+    movq        mm7, mm3 ; a1
+    movq        mm0, mm6 ; a2
+    paddsw      mm3, mm1 ; a1+b1
+    paddsw      mm6, mm4 ; a2+b2
+    psraw       mm3, 6   ; dst1
+    psubsw      mm7, mm1 ; a1-b1
+    psraw       mm6, 6   ; dst2
+    psubsw      mm0, mm4 ; a2-b2
+    movq        mm1, [%1+3*16] ; load b0
+    psraw       mm7, 6   ; dst6
+    movq        mm4, mm5 ; a0
+    psraw       mm0, 6   ; dst5
+    movq  [%1+1*16], mm3
+    paddsw      mm5, mm1 ; a0+b0
+    movq  [%1+2*16], mm6
+    psubsw      mm4, mm1 ; a0-b0
+    movq        mm3, [%1+5*16] ; load b3
+    psraw       mm5, 6   ; dst0
+    movq        mm6, mm2 ; a3
+    psraw       mm4, 6   ; dst7
+    movq  [%1+5*16], mm0
+    paddsw      mm2, mm3 ; a3+b3
+    movq  [%1+6*16], mm7
+    psubsw      mm6, mm3 ; a3-b3
+    movq  [%1+0*16], mm5
+    psraw       mm2, 6   ; dst3
+    movq  [%1+7*16], mm4
+    psraw       mm6, 6   ; dst4
+    movq  [%1+3*16], mm2
+    movq  [%1+4*16], mm6
+%endmacro
+
+%macro XVID_IDCT_MMX 0
+cglobal xvid_idct, 1, 1, 0, block
+%if cpuflag(mmxext)
+%define TAB tab_i_04_xmm
+%else
+%define TAB tab_i_04_mmx
+%endif
+    ; Process each row - beware of rounder offset
+    DCT_8_INV_ROW  0, TAB + 64 * 0, 0*16
+    DCT_8_INV_ROW  1, TAB + 64 * 1, 1*16
+    DCT_8_INV_ROW  2, TAB + 64 * 2, 2*16
+    DCT_8_INV_ROW  3, TAB + 64 * 3, 3*16
+    DCT_8_INV_ROW  4, TAB + 64 * 0, 6*16
+    DCT_8_INV_ROW  5, TAB + 64 * 3, 4*16
+    DCT_8_INV_ROW  6, TAB + 64 * 2, 5*16
+    DCT_8_INV_ROW  7, TAB + 64 * 1, 5*16
+
+    ; Process the columns (4 at a time)
+    DCT_8_INV_COL  r0+0
+    DCT_8_INV_COL  r0+8
+
+    RET
+%endmacro
+
+INIT_MMX mmx
+XVID_IDCT_MMX
+INIT_MMX mmxext
+XVID_IDCT_MMX
+
+%endif ; ~ARCH_X86_32
diff --git a/libavcodec/x86/xvididct.h b/libavcodec/x86/xvididct.h
index e8586fe..573b25c 100644
--- a/libavcodec/x86/xvididct.h
+++ b/libavcodec/x86/xvididct.h
@@ -37,7 +37,7 @@
 void ff_xvid_idct_mmxext_add(uint8_t *dest, int line_size, int16_t *block);
 
 void ff_xvid_idct_sse2(short *block);
-void ff_xvid_idct_sse2_put(uint8_t *dest, int line_size, short *block);
-void ff_xvid_idct_sse2_add(uint8_t *dest, int line_size, short *block);
+void ff_xvid_idct_put_sse2(uint8_t *dest, int line_size, short *block);
+void ff_xvid_idct_add_sse2(uint8_t *dest, int line_size, short *block);
 
 #endif /* AVCODEC_X86_XVIDIDCT_H */
diff --git a/libavcodec/x86/xvididct_init.c b/libavcodec/x86/xvididct_init.c
index 8c22784..8b9d8de 100644
--- a/libavcodec/x86/xvididct_init.c
+++ b/libavcodec/x86/xvididct_init.c
@@ -26,9 +26,36 @@
 #include "idctdsp.h"
 #include "xvididct.h"
 
+#if ARCH_X86_32 && HAVE_YASM
+static void xvid_idct_mmx_put(uint8_t *dest, int line_size, short *block)
+{
+    ff_xvid_idct_mmx(block);
+    ff_put_pixels_clamped(block, dest, line_size);
+}
+
+static void xvid_idct_mmx_add(uint8_t *dest, int line_size, short *block)
+{
+    ff_xvid_idct_mmx(block);
+    ff_add_pixels_clamped(block, dest, line_size);
+}
+
+static void xvid_idct_mmxext_put(uint8_t *dest, int line_size, short *block)
+{
+    ff_xvid_idct_mmxext(block);
+    ff_put_pixels_clamped(block, dest, line_size);
+}
+
+static void xvid_idct_mmxext_add(uint8_t *dest, int line_size, short *block)
+{
+    ff_xvid_idct_mmxext(block);
+    ff_add_pixels_clamped(block, dest, line_size);
+}
+#endif
+
 av_cold void ff_xvid_idct_init_x86(IDCTDSPContext *c, AVCodecContext *avctx,
                                    unsigned high_bit_depth)
 {
+#if HAVE_YASM
     int cpu_flags = av_get_cpu_flags();
 
     if (high_bit_depth ||
@@ -36,24 +63,27 @@
           avctx->idct_algo == FF_IDCT_XVID))
         return;
 
-    if (INLINE_MMX(cpu_flags)) {
-        c->idct_put  = ff_xvid_idct_mmx_put;
-        c->idct_add  = ff_xvid_idct_mmx_add;
+#if ARCH_X86_32
+    if (EXTERNAL_MMX(cpu_flags)) {
+        c->idct_put  = xvid_idct_mmx_put;
+        c->idct_add  = xvid_idct_mmx_add;
         c->idct      = ff_xvid_idct_mmx;
         c->perm_type = FF_IDCT_PERM_NONE;
     }
 
-    if (INLINE_MMXEXT(cpu_flags)) {
-        c->idct_put  = ff_xvid_idct_mmxext_put;
-        c->idct_add  = ff_xvid_idct_mmxext_add;
+    if (EXTERNAL_MMXEXT(cpu_flags)) {
+        c->idct_put  = xvid_idct_mmxext_put;
+        c->idct_add  = xvid_idct_mmxext_add;
         c->idct      = ff_xvid_idct_mmxext;
         c->perm_type = FF_IDCT_PERM_NONE;
     }
+#endif
 
-    if (INLINE_SSE2(cpu_flags)) {
-        c->idct_put  = ff_xvid_idct_sse2_put;
-        c->idct_add  = ff_xvid_idct_sse2_add;
+    if (EXTERNAL_SSE2(cpu_flags)) {
+        c->idct_put  = ff_xvid_idct_put_sse2;
+        c->idct_add  = ff_xvid_idct_add_sse2;
         c->idct      = ff_xvid_idct_sse2;
         c->perm_type = FF_IDCT_PERM_SSE2;
     }
+#endif /* HAVE_YASM */
 }
diff --git a/libavcodec/x86/xvididct_mmx.c b/libavcodec/x86/xvididct_mmx.c
deleted file mode 100644
index 57aa8c0..0000000
--- a/libavcodec/x86/xvididct_mmx.c
+++ /dev/null
@@ -1,549 +0,0 @@
-/*
- * XVID MPEG-4 VIDEO CODEC
- * - MMX and XMM forward discrete cosine transform -
- *
- * Copyright(C) 2001 Peter Ross <pross@xvid.org>
- *
- * Originally provided by Intel at AP-922
- * http://developer.intel.com/vtune/cbts/strmsimd/922down.htm
- * (See more app notes at http://developer.intel.com/vtune/cbts/strmsimd/appnotes.htm)
- * but in a limited edition.
- * New macro implements a column part for precise iDCT
- * The routine precision now satisfies IEEE standard 1180-1990.
- *
- * Copyright(C) 2000-2001 Peter Gubanov <peter@elecard.net.ru>
- * Rounding trick Copyright(C) 2000 Michel Lespinasse <walken@zoy.org>
- *
- * http://www.elecard.com/peter/idct.html
- * http://www.linuxvideo.org/mpeg2dec/
- *
- * These examples contain code fragments for first stage iDCT 8x8
- * (for rows) and first stage DCT 8x8 (for columns)
- *
- * conversion to gcc syntax by 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
- */
-
-#include <inttypes.h>
-
-#include "config.h"
-
-#include "libavutil/mem.h"
-
-#include "libavcodec/avcodec.h"
-#include "libavcodec/idctdsp.h"
-
-#include "idctdsp.h"
-#include "xvididct.h"
-
-#if HAVE_MMX_INLINE
-
-// -----------------------------------------------------------------------------
-// Various memory constants (trigonometric values or rounding values)
-// -----------------------------------------------------------------------------
-
-DECLARE_ALIGNED(8, static const int16_t, tg_1_16)[4 * 4] = {
-     13036,  13036,  13036,  13036, // tg * (2 << 16) + 0.5
-     27146,  27146,  27146,  27146, // tg * (2 << 16) + 0.5
-    -21746, -21746, -21746, -21746, // tg * (2 << 16) + 0.5
-     23170,  23170,  23170,  23170
-};                                  // cos * (2 << 15) + 0.5
-
-DECLARE_ALIGNED(8, static const int32_t, rounder_0)[2 * 8] = {
-    65536, 65536,
-    3597,   3597,
-    2260,   2260,
-    1203,   1203,
-    0,         0,
-    120,     120,
-    512,     512,
-    512, 512
-};
-
-// -----------------------------------------------------------------------------
-//
-// The first stage iDCT 8x8 - inverse DCTs of rows
-//
-// -----------------------------------------------------------------------------
-// The 8-point inverse DCT direct algorithm
-// -----------------------------------------------------------------------------
-//
-// static const short w[32] = {
-//     FIX(cos_4_16),  FIX(cos_2_16),  FIX(cos_4_16),  FIX(cos_6_16),
-//     FIX(cos_4_16),  FIX(cos_6_16), -FIX(cos_4_16), -FIX(cos_2_16),
-//     FIX(cos_4_16), -FIX(cos_6_16), -FIX(cos_4_16),  FIX(cos_2_16),
-//     FIX(cos_4_16), -FIX(cos_2_16),  FIX(cos_4_16), -FIX(cos_6_16),
-//     FIX(cos_1_16),  FIX(cos_3_16),  FIX(cos_5_16),  FIX(cos_7_16),
-//     FIX(cos_3_16), -FIX(cos_7_16), -FIX(cos_1_16), -FIX(cos_5_16),
-//     FIX(cos_5_16), -FIX(cos_1_16),  FIX(cos_7_16),  FIX(cos_3_16),
-//     FIX(cos_7_16), -FIX(cos_5_16),  FIX(cos_3_16), -FIX(cos_1_16) };
-//
-// #define DCT_8_INV_ROW(x, y)
-// {
-//     int a0, a1, a2, a3, b0, b1, b2, b3;
-//
-//     a0 = x[0] * w[0]  + x[2] * w[1]  + x[4] * w[2]  + x[6] * w[3];
-//     a1 = x[0] * w[4]  + x[2] * w[5]  + x[4] * w[6]  + x[6] * w[7];
-//     a2 = x[0] * w[8]  + x[2] * w[9]  + x[4] * w[10] + x[6] * w[11];
-//     a3 = x[0] * w[12] + x[2] * w[13] + x[4] * w[14] + x[6] * w[15];
-//     b0 = x[1] * w[16] + x[3] * w[17] + x[5] * w[18] + x[7] * w[19];
-//     b1 = x[1] * w[20] + x[3] * w[21] + x[5] * w[22] + x[7] * w[23];
-//     b2 = x[1] * w[24] + x[3] * w[25] + x[5] * w[26] + x[7] * w[27];
-//     b3 = x[1] * w[28] + x[3] * w[29] + x[5] * w[30] + x[7] * w[31];
-//
-//     y[0] = SHIFT_ROUND(a0 + b0);
-//     y[1] = SHIFT_ROUND(a1 + b1);
-//     y[2] = SHIFT_ROUND(a2 + b2);
-//     y[3] = SHIFT_ROUND(a3 + b3);
-//     y[4] = SHIFT_ROUND(a3 - b3);
-//     y[5] = SHIFT_ROUND(a2 - b2);
-//     y[6] = SHIFT_ROUND(a1 - b1);
-//     y[7] = SHIFT_ROUND(a0 - b0);
-// }
-//
-// -----------------------------------------------------------------------------
-//
-// In this implementation the outputs of the iDCT-1D are multiplied
-//     for rows 0,4 - by cos_4_16,
-//     for rows 1,7 - by cos_1_16,
-//     for rows 2,6 - by cos_2_16,
-//     for rows 3,5 - by cos_3_16
-// and are shifted to the left for better accuracy.
-//
-// For the constants used,
-//     FIX(float_const) = (short) (float_const * (1 << 15) + 0.5)
-//
-// -----------------------------------------------------------------------------
-
-// -----------------------------------------------------------------------------
-// Tables for mmx processors
-// -----------------------------------------------------------------------------
-
-// Table for rows 0,4 - constants are multiplied by cos_4_16
-DECLARE_ALIGNED(8, static const int16_t, tab_i_04_mmx)[32 * 4] = {
-     16384,  16384,  16384, -16384, // movq-> w06 w04 w02 w00
-     21407,   8867,   8867, -21407, // w07 w05 w03 w01
-     16384, -16384,  16384,  16384, // w14 w12 w10 w08
-     -8867,  21407, -21407,  -8867, // w15 w13 w11 w09
-     22725,  12873,  19266, -22725, // w22 w20 w18 w16
-     19266,   4520,  -4520, -12873, // w23 w21 w19 w17
-     12873,   4520,   4520,  19266, // w30 w28 w26 w24
-    -22725,  19266, -12873, -22725, // w31 w29 w27 w25
-// Table for rows 1,7 - constants are multiplied by cos_1_16
-     22725,  22725,  22725, -22725, // movq-> w06 w04 w02 w00
-     29692,  12299,  12299, -29692, // w07 w05 w03 w01
-     22725, -22725,  22725,  22725, // w14 w12 w10 w08
-    -12299,  29692, -29692, -12299, // w15 w13 w11 w09
-     31521,  17855,  26722, -31521, // w22 w20 w18 w16
-     26722,   6270,  -6270, -17855, // w23 w21 w19 w17
-     17855,   6270,   6270,  26722, // w30 w28 w26 w24
-    -31521,  26722, -17855, -31521, // w31 w29 w27 w25
-// Table for rows 2,6 - constants are multiplied by cos_2_16
-     21407,  21407,  21407, -21407, // movq-> w06 w04 w02 w00
-     27969,  11585,  11585, -27969, // w07 w05 w03 w01
-     21407, -21407,  21407,  21407, // w14 w12 w10 w08
-    -11585,  27969, -27969, -11585, // w15 w13 w11 w09
-     29692,  16819,  25172, -29692, // w22 w20 w18 w16
-     25172,   5906,  -5906, -16819, // w23 w21 w19 w17
-     16819,   5906,   5906,  25172, // w30 w28 w26 w24
-    -29692,  25172, -16819, -29692, // w31 w29 w27 w25
-// Table for rows 3,5 - constants are multiplied by cos_3_16
-     19266,  19266,  19266, -19266, // movq-> w06 w04 w02 w00
-     25172,  10426,  10426, -25172, // w07 w05 w03 w01
-     19266, -19266,  19266,  19266, // w14 w12 w10 w08
-    -10426,  25172, -25172, -10426, // w15 w13 w11 w09
-     26722,  15137,  22654, -26722, // w22 w20 w18 w16
-     22654,   5315,  -5315, -15137, // w23 w21 w19 w17
-     15137,   5315,   5315,  22654, // w30 w28 w26 w24
-    -26722,  22654, -15137, -26722, // w31 w29 w27 w25
-};
-// -----------------------------------------------------------------------------
-// Tables for xmm processors
-// -----------------------------------------------------------------------------
-
-// %3 for rows 0,4 - constants are multiplied by cos_4_16
-DECLARE_ALIGNED(8, static const int16_t, tab_i_04_xmm)[32 * 4] = {
-     16384,  21407,  16384,   8867, // movq-> w05 w04 w01 w00
-     16384,   8867, -16384, -21407, // w07 w06 w03 w02
-     16384,  -8867,  16384, -21407, // w13 w12 w09 w08
-    -16384,  21407,  16384,  -8867, // w15 w14 w11 w10
-     22725,  19266,  19266,  -4520, // w21 w20 w17 w16
-     12873,   4520, -22725, -12873, // w23 w22 w19 w18
-     12873, -22725,   4520, -12873, // w29 w28 w25 w24
-      4520,  19266,  19266, -22725, // w31 w30 w27 w26
-// %3 for rows 1,7 - constants are multiplied by cos_1_16
-     22725,  29692,  22725,  12299, // movq-> w05 w04 w01 w00
-     22725,  12299, -22725, -29692, // w07 w06 w03 w02
-     22725, -12299,  22725, -29692, // w13 w12 w09 w08
-    -22725,  29692,  22725, -12299, // w15 w14 w11 w10
-     31521,  26722,  26722,  -6270, // w21 w20 w17 w16
-     17855,   6270, -31521, -17855, // w23 w22 w19 w18
-     17855, -31521,   6270, -17855, // w29 w28 w25 w24
-      6270,  26722,  26722, -31521, // w31 w30 w27 w26
-// %3 for rows 2,6 - constants are multiplied by cos_2_16
-     21407,  27969,  21407,  11585, // movq-> w05 w04 w01 w00
-     21407,  11585, -21407, -27969, // w07 w06 w03 w02
-     21407, -11585,  21407, -27969, // w13 w12 w09 w08
-    -21407,  27969,  21407, -11585, // w15 w14 w11 w10
-     29692,  25172,  25172,  -5906, // w21 w20 w17 w16
-     16819,   5906, -29692, -16819, // w23 w22 w19 w18
-     16819, -29692,   5906, -16819, // w29 w28 w25 w24
-      5906,  25172,  25172, -29692, // w31 w30 w27 w26
-// %3 for rows 3,5 - constants are multiplied by cos_3_16
-     19266,  25172,  19266,  10426, // movq-> w05 w04 w01 w00
-     19266,  10426, -19266, -25172, // w07 w06 w03 w02
-     19266, -10426,  19266, -25172, // w13 w12 w09 w08
-    -19266,  25172,  19266, -10426, // w15 w14 w11 w10
-     26722,  22654,  22654,  -5315, // w21 w20 w17 w16
-     15137,   5315, -26722, -15137, // w23 w22 w19 w18
-     15137, -26722,   5315, -15137, // w29 w28 w25 w24
-      5315,  22654,  22654, -26722, // w31 w30 w27 w26
-};
-// =============================================================================
-// Helper macros for the code
-// =============================================================================
-
-// -----------------------------------------------------------------------------
-// DCT_8_INV_ROW_MMX( INP, OUT, TABLE, ROUNDER
-// -----------------------------------------------------------------------------
-
-#define DCT_8_INV_ROW_MMX(A1, A2, A3, A4)                                       \
-    "movq       "#A1", %%mm0    \n\t" /* 0 ; x3 x2 x1 x0 */                     \
-    "movq     8+"#A1", %%mm1    \n\t" /* 1 ; x7 x6 x5 x4 */                     \
-    "movq       %%mm0, %%mm2    \n\t" /* 2 ; x3 x2 x1 x0 */                     \
-    "movq       "#A3", %%mm3    \n\t" /* 3 ; w06 w04 w02 w00 */                 \
-    "punpcklwd  %%mm1, %%mm0    \n\t" /* x5 x1 x4 x0 */                         \
-    "movq       %%mm0, %%mm5    \n\t" /* 5 ; x5 x1 x4 x0 */                     \
-    "punpckldq  %%mm0, %%mm0    \n\t" /* x4 x0 x4 x0 */                         \
-    "movq     8+"#A3", %%mm4    \n\t" /* 4 ; w07 w05 w03 w01 */                 \
-    "punpckhwd  %%mm1, %%mm2    \n\t" /* 1 ; x7 x3 x6 x2 */                     \
-    "pmaddwd    %%mm0, %%mm3    \n\t" /* x4*w06+x0*w04 x4*w02+x0*w00 */         \
-    "movq       %%mm2, %%mm6    \n\t" /* 6 ; x7 x3 x6 x2 */                     \
-    "movq    32+"#A3", %%mm1    \n\t" /* 1 ; w22 w20 w18 w16 */                 \
-    "punpckldq  %%mm2, %%mm2    \n\t" /* x6 x2 x6 x2 */                         \
-    "pmaddwd    %%mm2, %%mm4    \n\t" /* x6*w07+x2*w05 x6*w03+x2*w01 */         \
-    "punpckhdq  %%mm5, %%mm5    \n\t" /* x5 x1 x5 x1 */                         \
-    "pmaddwd 16+"#A3", %%mm0    \n\t" /* x4*w14+x0*w12 x4*w10+x0*w08 */         \
-    "punpckhdq  %%mm6, %%mm6    \n\t" /* x7 x3 x7 x3 */                         \
-    "movq 40+   "#A3", %%mm7    \n\t" /* 7 ; w23 w21 w19 w17 */                 \
-    "pmaddwd    %%mm5, %%mm1    \n\t" /* x5*w22+x1*w20 x5*w18+x1*w16 */         \
-    "paddd      "#A4", %%mm3    \n\t" /* +%4 */                                 \
-    "pmaddwd    %%mm6, %%mm7    \n\t" /* x7*w23+x3*w21 x7*w19+x3*w17 */         \
-    "pmaddwd 24+"#A3", %%mm2    \n\t" /* x6*w15+x2*w13 x6*w11+x2*w09 */         \
-    "paddd      %%mm4, %%mm3    \n\t" /* 4 ; a1=sum(even1) a0=sum(even0) */     \
-    "pmaddwd 48+"#A3", %%mm5    \n\t" /* x5*w30+x1*w28 x5*w26+x1*w24 */         \
-    "movq       %%mm3, %%mm4    \n\t" /* 4 ; a1 a0 */                           \
-    "pmaddwd 56+"#A3", %%mm6    \n\t" /* x7*w31+x3*w29 x7*w27+x3*w25 */         \
-    "paddd      %%mm7, %%mm1    \n\t" /* 7 ; b1=sum(odd1) b0=sum(odd0) */       \
-    "paddd      "#A4", %%mm0    \n\t" /* +%4 */                                 \
-    "psubd      %%mm1, %%mm3    \n\t" /* a1-b1 a0-b0 */                         \
-    "psrad        $11, %%mm3    \n\t" /* y6=a1-b1 y7=a0-b0 */                   \
-    "paddd      %%mm4, %%mm1    \n\t" /* 4 ; a1+b1 a0+b0 */                     \
-    "paddd      %%mm2, %%mm0    \n\t" /* 2 ; a3=sum(even3) a2=sum(even2) */     \
-    "psrad        $11, %%mm1    \n\t" /* y1=a1+b1 y0=a0+b0 */                   \
-    "paddd      %%mm6, %%mm5    \n\t" /* 6 ; b3=sum(odd3) b2=sum(odd2) */       \
-    "movq       %%mm0, %%mm4    \n\t" /* 4 ; a3 a2 */                           \
-    "paddd      %%mm5, %%mm0    \n\t" /* a3+b3 a2+b2 */                         \
-    "psubd      %%mm5, %%mm4    \n\t" /* 5 ; a3-b3 a2-b2 */                     \
-    "psrad        $11, %%mm0    \n\t" /* y3=a3+b3 y2=a2+b2 */                   \
-    "psrad        $11, %%mm4    \n\t" /* y4=a3-b3 y5=a2-b2 */                   \
-    "packssdw   %%mm0, %%mm1    \n\t" /* 0 ; y3 y2 y1 y0 */                     \
-    "packssdw   %%mm3, %%mm4    \n\t" /* 3 ; y6 y7 y4 y5 */                     \
-    "movq       %%mm4, %%mm7    \n\t" /* 7 ; y6 y7 y4 y5 */                     \
-    "psrld        $16, %%mm4    \n\t" /* 0 y6 0 y4 */                           \
-    "pslld        $16, %%mm7    \n\t" /* y7 0 y5 0 */                           \
-    "movq       %%mm1, "#A2"    \n\t" /* 1 ; save y3 y2 y1 y0 */                \
-    "por        %%mm4, %%mm7    \n\t" /* 4 ; y7 y6 y5 y4 */                     \
-    "movq       %%mm7, 8+"#A2"  \n\t" /* 7 ; save y7 y6 y5 y4 */                \
-
-
-// -----------------------------------------------------------------------------
-// DCT_8_INV_ROW_XMM( INP, OUT, TABLE, ROUNDER
-// -----------------------------------------------------------------------------
-
-#define DCT_8_INV_ROW_XMM(A1, A2, A3, A4)                                       \
-    "movq       "#A1", %%mm0        \n\t" /* 0 ; x3 x2 x1 x0 */                 \
-    "movq     8+"#A1", %%mm1        \n\t" /* 1 ; x7 x6 x5 x4 */                 \
-    "movq       %%mm0, %%mm2        \n\t" /* 2 ; x3 x2 x1 x0 */                 \
-    "movq       "#A3", %%mm3        \n\t" /* 3 ; w05 w04 w01 w00 */             \
-    "pshufw     $0x88, %%mm0, %%mm0 \n\t" /* x2 x0 x2 x0 */                     \
-    "movq     8+"#A3", %%mm4        \n\t" /* 4 ; w07 w06 w03 w02 */             \
-    "movq       %%mm1, %%mm5        \n\t" /* 5 ; x7 x6 x5 x4 */                 \
-    "pmaddwd    %%mm0, %%mm3        \n\t" /* x2*w05+x0*w04 x2*w01+x0*w00 */     \
-    "movq    32+"#A3", %%mm6        \n\t" /* 6 ; w21 w20 w17 w16 */             \
-    "pshufw     $0x88, %%mm1, %%mm1 \n\t" /* x6 x4 x6 x4 */                     \
-    "pmaddwd    %%mm1, %%mm4        \n\t" /* x6*w07+x4*w06 x6*w03+x4*w02 */     \
-    "movq    40+"#A3", %%mm7        \n\t" /* 7; w23 w22 w19 w18 */              \
-    "pshufw     $0xdd, %%mm2, %%mm2 \n\t" /* x3 x1 x3 x1 */                     \
-    "pmaddwd    %%mm2, %%mm6        \n\t" /* x3*w21+x1*w20 x3*w17+x1*w16 */     \
-    "pshufw     $0xdd, %%mm5, %%mm5 \n\t" /* x7 x5 x7 x5 */                     \
-    "pmaddwd    %%mm5, %%mm7        \n\t" /* x7*w23+x5*w22 x7*w19+x5*w18 */     \
-    "paddd      "#A4", %%mm3        \n\t" /* +%4 */                             \
-    "pmaddwd 16+"#A3", %%mm0        \n\t" /* x2*w13+x0*w12 x2*w09+x0*w08 */     \
-    "paddd      %%mm4, %%mm3        \n\t" /* 4 ; a1=sum(even1) a0=sum(even0) */ \
-    "pmaddwd 24+"#A3", %%mm1        \n\t" /* x6*w15+x4*w14 x6*w11+x4*w10 */     \
-    "movq       %%mm3, %%mm4        \n\t" /* 4 ; a1 a0 */                       \
-    "pmaddwd 48+"#A3", %%mm2        \n\t" /* x3*w29+x1*w28 x3*w25+x1*w24 */     \
-    "paddd      %%mm7, %%mm6        \n\t" /* 7 ; b1=sum(odd1) b0=sum(odd0) */   \
-    "pmaddwd 56+"#A3", %%mm5        \n\t" /* x7*w31+x5*w30 x7*w27+x5*w26 */     \
-    "paddd      %%mm6, %%mm3        \n\t" /* a1+b1 a0+b0 */                     \
-    "paddd      "#A4", %%mm0        \n\t" /* +%4 */                             \
-    "psrad        $11, %%mm3        \n\t" /* y1=a1+b1 y0=a0+b0 */               \
-    "paddd      %%mm1, %%mm0        \n\t" /* 1 ; a3=sum(even3) a2=sum(even2) */ \
-    "psubd      %%mm6, %%mm4        \n\t" /* 6 ; a1-b1 a0-b0 */                 \
-    "movq       %%mm0, %%mm7        \n\t" /* 7 ; a3 a2 */                       \
-    "paddd      %%mm5, %%mm2        \n\t" /* 5 ; b3=sum(odd3) b2=sum(odd2) */   \
-    "paddd      %%mm2, %%mm0        \n\t" /* a3+b3 a2+b2 */                     \
-    "psrad        $11, %%mm4        \n\t" /* y6=a1-b1 y7=a0-b0 */               \
-    "psubd      %%mm2, %%mm7        \n\t" /* 2 ; a3-b3 a2-b2 */                 \
-    "psrad        $11, %%mm0        \n\t" /* y3=a3+b3 y2=a2+b2 */               \
-    "psrad        $11, %%mm7        \n\t" /* y4=a3-b3 y5=a2-b2 */               \
-    "packssdw   %%mm0, %%mm3        \n\t" /* 0 ; y3 y2 y1 y0 */                 \
-    "packssdw   %%mm4, %%mm7        \n\t" /* 4 ; y6 y7 y4 y5 */                 \
-    "movq       %%mm3, "#A2"        \n\t" /* 3 ; save y3 y2 y1 y0 */            \
-    "pshufw     $0xb1, %%mm7, %%mm7 \n\t" /* y7 y6 y5 y4 */                     \
-    "movq       %%mm7, 8+"#A2"      \n\t" /* 7 ; save y7 y6 y5 y4 */            \
-
-
-// -----------------------------------------------------------------------------
-//
-// The first stage DCT 8x8 - forward DCTs of columns
-//
-// The %2puts are multiplied
-// for rows 0,4 - on cos_4_16,
-// for rows 1,7 - on cos_1_16,
-// for rows 2,6 - on cos_2_16,
-// for rows 3,5 - on cos_3_16
-// and are shifted to the left for rise of accuracy
-//
-// -----------------------------------------------------------------------------
-//
-// The 8-point scaled forward DCT algorithm (26a8m)
-//
-// -----------------------------------------------------------------------------
-//
-//#define DCT_8_FRW_COL(x, y)
-// {
-//     short t0, t1, t2, t3, t4, t5, t6, t7;
-//     short tp03, tm03, tp12, tm12, tp65, tm65;
-//     short tp465, tm465, tp765, tm765;
-//
-//     t0 = LEFT_SHIFT(x[0] + x[7]);
-//     t1 = LEFT_SHIFT(x[1] + x[6]);
-//     t2 = LEFT_SHIFT(x[2] + x[5]);
-//     t3 = LEFT_SHIFT(x[3] + x[4]);
-//     t4 = LEFT_SHIFT(x[3] - x[4]);
-//     t5 = LEFT_SHIFT(x[2] - x[5]);
-//     t6 = LEFT_SHIFT(x[1] - x[6]);
-//     t7 = LEFT_SHIFT(x[0] - x[7]);
-//
-//     tp03 = t0 + t3;
-//     tm03 = t0 - t3;
-//     tp12 = t1 + t2;
-//     tm12 = t1 - t2;
-//
-//     y[0] = tp03 + tp12;
-//     y[4] = tp03 - tp12;
-//
-//     y[2] = tm03 + tm12 * tg_2_16;
-//     y[6] = tm03 * tg_2_16 - tm12;
-//
-//     tp65 = (t6 + t5) * cos_4_16;
-//     tm65 = (t6 - t5) * cos_4_16;
-//
-//     tp765 = t7 + tp65;
-//     tm765 = t7 - tp65;
-//     tp465 = t4 + tm65;
-//     tm465 = t4 - tm65;
-//
-//     y[1] = tp765 + tp465 * tg_1_16;
-//     y[7] = tp765 * tg_1_16 - tp465;
-//     y[5] = tm765 * tg_3_16 + tm465;
-//     y[3] = tm765 - tm465 * tg_3_16;
-// }
-//
-// -----------------------------------------------------------------------------
-
-// -----------------------------------------------------------------------------
-// DCT_8_INV_COL_4  INP,OUT
-// -----------------------------------------------------------------------------
-
-#define DCT_8_INV_COL(A1, A2)                                                   \
-    "movq    2*8(%3), %%mm0         \n\t"                                       \
-    "movq 16*3+"#A1", %%mm3         \n\t"                                       \
-    "movq      %%mm0, %%mm1         \n\t" /* tg_3_16 */                         \
-    "movq 16*5+"#A1", %%mm5         \n\t"                                       \
-    "pmulhw    %%mm3, %%mm0         \n\t" /* x3*(tg_3_16-1) */                  \
-    "movq       (%3), %%mm4         \n\t"                                       \
-    "pmulhw    %%mm5, %%mm1         \n\t" /* x5*(tg_3_16-1) */                  \
-    "movq 16*7+"#A1", %%mm7         \n\t"                                       \
-    "movq      %%mm4, %%mm2         \n\t" /* tg_1_16 */                         \
-    "movq 16*1+"#A1", %%mm6         \n\t"                                       \
-    "pmulhw    %%mm7, %%mm4         \n\t" /* x7*tg_1_16 */                      \
-    "paddsw    %%mm3, %%mm0         \n\t" /* x3*tg_3_16 */                      \
-    "pmulhw    %%mm6, %%mm2         \n\t" /* x1*tg_1_16 */                      \
-    "paddsw    %%mm3, %%mm1         \n\t" /* x3+x5*(tg_3_16-1) */               \
-    "psubsw    %%mm5, %%mm0         \n\t" /* x3*tg_3_16-x5 = tm35 */            \
-    "movq    3*8(%3), %%mm3         \n\t"                                       \
-    "paddsw    %%mm5, %%mm1         \n\t" /* x3+x5*tg_3_16 = tp35 */            \
-    "paddsw    %%mm6, %%mm4         \n\t" /* x1+tg_1_16*x7 = tp17 */            \
-    "psubsw    %%mm7, %%mm2         \n\t" /* x1*tg_1_16-x7 = tm17 */            \
-    "movq      %%mm4, %%mm5         \n\t" /* tp17 */                            \
-    "movq      %%mm2, %%mm6         \n\t" /* tm17 */                            \
-    "paddsw    %%mm1, %%mm5         \n\t" /* tp17+tp35 = b0 */                  \
-    "psubsw    %%mm0, %%mm6         \n\t" /* tm17-tm35 = b3 */                  \
-    "psubsw    %%mm1, %%mm4         \n\t" /* tp17-tp35 = t1 */                  \
-    "paddsw    %%mm0, %%mm2         \n\t" /* tm17+tm35 = t2 */                  \
-    "movq    1*8(%3), %%mm7         \n\t"                                       \
-    "movq      %%mm4, %%mm1         \n\t" /* t1 */                              \
-    "movq      %%mm5, 3*16+"#A2"    \n\t" /* save b0 */                         \
-    "paddsw    %%mm2, %%mm1         \n\t" /* t1+t2 */                           \
-    "movq      %%mm6, 5*16+"#A2"    \n\t" /* save b3 */                         \
-    "psubsw    %%mm2, %%mm4         \n\t" /* t1-t2 */                           \
-    "movq 2*16+"#A1", %%mm5         \n\t"                                       \
-    "movq      %%mm7, %%mm0         \n\t" /* tg_2_16 */                         \
-    "movq 6*16+"#A1", %%mm6         \n\t"                                       \
-    "pmulhw    %%mm5, %%mm0         \n\t" /* x2*tg_2_16 */                      \
-    "pmulhw    %%mm6, %%mm7         \n\t" /* x6*tg_2_16 */                      \
-    "pmulhw    %%mm3, %%mm1         \n\t" /* ocos_4_16*(t1+t2) = b1/2 */        \
-    "movq 0*16+"#A1", %%mm2         \n\t"                                       \
-    "pmulhw    %%mm3, %%mm4         \n\t" /* ocos_4_16*(t1-t2) = b2/2 */        \
-    "psubsw    %%mm6, %%mm0         \n\t" /* t2*tg_2_16-x6 = tm26 */            \
-    "movq      %%mm2, %%mm3         \n\t" /* x0 */                              \
-    "movq 4*16+"#A1", %%mm6         \n\t"                                       \
-    "paddsw    %%mm5, %%mm7         \n\t" /* x2+x6*tg_2_16 = tp26 */            \
-    "paddsw    %%mm6, %%mm2         \n\t" /* x0+x4 = tp04 */                    \
-    "psubsw    %%mm6, %%mm3         \n\t" /* x0-x4 = tm04 */                    \
-    "movq      %%mm2, %%mm5         \n\t" /* tp04 */                            \
-    "movq      %%mm3, %%mm6         \n\t" /* tm04 */                            \
-    "psubsw    %%mm7, %%mm2         \n\t" /* tp04-tp26 = a3 */                  \
-    "paddsw    %%mm0, %%mm3         \n\t" /* tm04+tm26 = a1 */                  \
-    "paddsw    %%mm1, %%mm1         \n\t" /* b1 */                              \
-    "paddsw    %%mm4, %%mm4         \n\t" /* b2 */                              \
-    "paddsw    %%mm7, %%mm5         \n\t" /* tp04+tp26 = a0 */                  \
-    "psubsw    %%mm0, %%mm6         \n\t" /* tm04-tm26 = a2 */                  \
-    "movq      %%mm3, %%mm7         \n\t" /* a1 */                              \
-    "movq      %%mm6, %%mm0         \n\t" /* a2 */                              \
-    "paddsw    %%mm1, %%mm3         \n\t" /* a1+b1 */                           \
-    "paddsw    %%mm4, %%mm6         \n\t" /* a2+b2 */                           \
-    "psraw        $6, %%mm3         \n\t" /* dst1 */                            \
-    "psubsw    %%mm1, %%mm7         \n\t" /* a1-b1 */                           \
-    "psraw        $6, %%mm6         \n\t" /* dst2 */                            \
-    "psubsw    %%mm4, %%mm0         \n\t" /* a2-b2 */                           \
-    "movq 3*16+"#A2", %%mm1         \n\t" /* load b0 */                         \
-    "psraw        $6, %%mm7         \n\t" /* dst6 */                            \
-    "movq      %%mm5, %%mm4         \n\t" /* a0 */                              \
-    "psraw        $6, %%mm0         \n\t" /* dst5 */                            \
-    "movq      %%mm3, 1*16+"#A2"    \n\t"                                       \
-    "paddsw    %%mm1, %%mm5         \n\t" /* a0+b0 */                           \
-    "movq      %%mm6, 2*16+"#A2"    \n\t"                                       \
-    "psubsw    %%mm1, %%mm4         \n\t" /* a0-b0 */                           \
-    "movq 5*16+"#A2", %%mm3         \n\t" /* load b3 */                         \
-    "psraw        $6, %%mm5         \n\t" /* dst0 */                            \
-    "movq      %%mm2, %%mm6         \n\t" /* a3 */                              \
-    "psraw        $6, %%mm4         \n\t" /* dst7 */                            \
-    "movq      %%mm0, 5*16+"#A2"    \n\t"                                       \
-    "paddsw    %%mm3, %%mm2         \n\t" /* a3+b3 */                           \
-    "movq      %%mm7, 6*16+"#A2"    \n\t"                                       \
-    "psubsw    %%mm3, %%mm6         \n\t" /* a3-b3 */                           \
-    "movq      %%mm5, 0*16+"#A2"    \n\t"                                       \
-    "psraw        $6, %%mm2         \n\t" /* dst3 */                            \
-    "movq      %%mm4, 7*16+"#A2"    \n\t"                                       \
-    "psraw        $6, %%mm6         \n\t" /* dst4 */                            \
-    "movq      %%mm2, 3*16+"#A2"    \n\t"                                       \
-    "movq      %%mm6, 4*16+"#A2"    \n\t"                                       \
-
-// =============================================================================
-// Code
-// =============================================================================
-
-// -----------------------------------------------------------------------------
-// void idct_mmx(uint16_t block[64]);
-// -----------------------------------------------------------------------------
-
-void ff_xvid_idct_mmx(short *block)
-{
-    __asm__ volatile (
-        // # Process each row
-        DCT_8_INV_ROW_MMX(0 * 16(%0), 0 * 16(%0), 64 * 0(%2), 8 * 0(%1))
-        DCT_8_INV_ROW_MMX(1 * 16(%0), 1 * 16(%0), 64 * 1(%2), 8 * 1(%1))
-        DCT_8_INV_ROW_MMX(2 * 16(%0), 2 * 16(%0), 64 * 2(%2), 8 * 2(%1))
-        DCT_8_INV_ROW_MMX(3 * 16(%0), 3 * 16(%0), 64 * 3(%2), 8 * 3(%1))
-        DCT_8_INV_ROW_MMX(4 * 16(%0), 4 * 16(%0), 64 * 0(%2), 8 * 4(%1))
-        DCT_8_INV_ROW_MMX(5 * 16(%0), 5 * 16(%0), 64 * 3(%2), 8 * 5(%1))
-        DCT_8_INV_ROW_MMX(6 * 16(%0), 6 * 16(%0), 64 * 2(%2), 8 * 6(%1))
-        DCT_8_INV_ROW_MMX(7 * 16(%0), 7 * 16(%0), 64 * 1(%2), 8 * 7(%1))
-
-        // # Process the columns (4 at a time)
-        DCT_8_INV_COL(0(%0), 0(%0))
-        DCT_8_INV_COL(8(%0), 8(%0))
-        :: "r" (block), "r" (rounder_0), "r" (tab_i_04_mmx), "r" (tg_1_16));
-}
-
-void ff_xvid_idct_mmx_put(uint8_t *dest, int line_size, int16_t *block)
-{
-    ff_xvid_idct_mmx(block);
-    ff_put_pixels_clamped(block, dest, line_size);
-}
-
-void ff_xvid_idct_mmx_add(uint8_t *dest, int line_size, int16_t *block)
-{
-    ff_xvid_idct_mmx(block);
-    ff_add_pixels_clamped(block, dest, line_size);
-}
-
-#endif /* HAVE_MMX_INLINE */
-
-#if HAVE_MMXEXT_INLINE
-
-// -----------------------------------------------------------------------------
-// void idct_xmm(uint16_t block[64]);
-// -----------------------------------------------------------------------------
-
-void ff_xvid_idct_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))
-        DCT_8_INV_ROW_XMM(1 * 16(%0), 1 * 16(%0), 64 * 1(%2), 8 * 1(%1))
-        DCT_8_INV_ROW_XMM(2 * 16(%0), 2 * 16(%0), 64 * 2(%2), 8 * 2(%1))
-        DCT_8_INV_ROW_XMM(3 * 16(%0), 3 * 16(%0), 64 * 3(%2), 8 * 3(%1))
-        DCT_8_INV_ROW_XMM(4 * 16(%0), 4 * 16(%0), 64 * 0(%2), 8 * 4(%1))
-        DCT_8_INV_ROW_XMM(5 * 16(%0), 5 * 16(%0), 64 * 3(%2), 8 * 5(%1))
-        DCT_8_INV_ROW_XMM(6 * 16(%0), 6 * 16(%0), 64 * 2(%2), 8 * 6(%1))
-        DCT_8_INV_ROW_XMM(7 * 16(%0), 7 * 16(%0), 64 * 1(%2), 8 * 7(%1))
-
-        // # Process the columns (4 at a time)
-        DCT_8_INV_COL(0(%0), 0(%0))
-        DCT_8_INV_COL(8(%0), 8(%0))
-        :: "r" (block), "r" (rounder_0), "r" (tab_i_04_xmm), "r" (tg_1_16));
-}
-
-void ff_xvid_idct_mmxext_put(uint8_t *dest, int line_size, int16_t *block)
-{
-    ff_xvid_idct_mmxext(block);
-    ff_put_pixels_clamped(block, dest, line_size);
-}
-
-void ff_xvid_idct_mmxext_add(uint8_t *dest, int line_size, int16_t *block)
-{
-    ff_xvid_idct_mmxext(block);
-    ff_add_pixels_clamped(block, dest, line_size);
-}
-
-#endif /* HAVE_MMXEXT_INLINE */
diff --git a/libavcodec/x86/xvididct_sse2.c b/libavcodec/x86/xvididct_sse2.c
deleted file mode 100644
index 51a5d9d..0000000
--- a/libavcodec/x86/xvididct_sse2.c
+++ /dev/null
@@ -1,406 +0,0 @@
-/*
- * XVID MPEG-4 VIDEO CODEC
- * - SSE2 inverse discrete cosine transform -
- *
- * Copyright(C) 2003 Pascal Massimino <skal@planet-d.net>
- *
- * Conversion to gcc syntax with modifications
- * by Alexander Strange <astrange@ithinksw.com>
- *
- * Originally from dct/x86_asm/fdct_sse2_skal.asm in Xvid.
- *
- * This file is part of FFmpeg.
- *
- * Vertical pass is an implementation of the scheme:
- *  Loeffler C., Ligtenberg A., and Moschytz C.S.:
- *  Practical Fast 1D DCT Algorithm with Eleven Multiplications,
- *  Proc. ICASSP 1989, 988-991.
- *
- * Horizontal pass is a double 4x4 vector/matrix multiplication,
- * (see also Intel's Application Note 922:
- *  http://developer.intel.com/vtune/cbts/strmsimd/922down.htm
- *  Copyright (C) 1999 Intel Corporation)
- *
- * More details at http://skal.planet-d.net/coding/dct.html
- *
- * 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/mem.h"
-#include "libavutil/x86/asm.h"
-
-#include "libavcodec/idctdsp.h"
-
-#include "idctdsp.h"
-#include "xvididct.h"
-
-#if HAVE_SSE2_INLINE
-
-/**
- * @file
- * @brief SSE2 IDCT compatible with the Xvid IDCT
- */
-
-#define X8(x) x, x, x, x, x, x, x, x
-
-DECLARE_ASM_CONST(16, int16_t, tan1)[]  = { X8(13036) }; // tan( pi/16)
-DECLARE_ASM_CONST(16, int16_t, tan2)[]  = { X8(27146) }; // tan(2pi/16) = sqrt(2)-1
-DECLARE_ASM_CONST(16, int16_t, tan3)[]  = { X8(43790) }; // tan(3pi/16)-1
-DECLARE_ASM_CONST(16, int16_t, sqrt2)[] = { X8(23170) }; // 0.5/sqrt(2)
-DECLARE_ASM_CONST(8,  uint8_t, m127)[]  = { X8(127) };
-
-DECLARE_ASM_CONST(16, int16_t, iTab1)[] = {
-    0x4000, 0x539f, 0xc000, 0xac61, 0x4000, 0xdd5d, 0x4000, 0xdd5d,
-    0x4000, 0x22a3, 0x4000, 0x22a3, 0xc000, 0x539f, 0x4000, 0xac61,
-    0x3249, 0x11a8, 0x4b42, 0xee58, 0x11a8, 0x4b42, 0x11a8, 0xcdb7,
-    0x58c5, 0x4b42, 0xa73b, 0xcdb7, 0x3249, 0xa73b, 0x4b42, 0xa73b
-};
-
-DECLARE_ASM_CONST(16, int16_t, iTab2)[] = {
-    0x58c5, 0x73fc, 0xa73b, 0x8c04, 0x58c5, 0xcff5, 0x58c5, 0xcff5,
-    0x58c5, 0x300b, 0x58c5, 0x300b, 0xa73b, 0x73fc, 0x58c5, 0x8c04,
-    0x45bf, 0x187e, 0x6862, 0xe782, 0x187e, 0x6862, 0x187e, 0xba41,
-    0x7b21, 0x6862, 0x84df, 0xba41, 0x45bf, 0x84df, 0x6862, 0x84df
-};
-
-DECLARE_ASM_CONST(16, int16_t, iTab3)[] = {
-    0x539f, 0x6d41, 0xac61, 0x92bf, 0x539f, 0xd2bf, 0x539f, 0xd2bf,
-    0x539f, 0x2d41, 0x539f, 0x2d41, 0xac61, 0x6d41, 0x539f, 0x92bf,
-    0x41b3, 0x1712, 0x6254, 0xe8ee, 0x1712, 0x6254, 0x1712, 0xbe4d,
-    0x73fc, 0x6254, 0x8c04, 0xbe4d, 0x41b3, 0x8c04, 0x6254, 0x8c04
-};
-
-DECLARE_ASM_CONST(16, int16_t, iTab4)[] = {
-    0x4b42, 0x6254, 0xb4be, 0x9dac, 0x4b42, 0xd746, 0x4b42, 0xd746,
-    0x4b42, 0x28ba, 0x4b42, 0x28ba, 0xb4be, 0x6254, 0x4b42, 0x9dac,
-    0x3b21, 0x14c3, 0x587e, 0xeb3d, 0x14c3, 0x587e, 0x14c3, 0xc4df,
-    0x6862, 0x587e, 0x979e, 0xc4df, 0x3b21, 0x979e, 0x587e, 0x979e
-};
-
-DECLARE_ASM_CONST(16, int32_t, walkenIdctRounders)[] = {
-    65536, 65536, 65536, 65536,
-     3597,  3597,  3597,  3597,
-     2260,  2260,  2260,  2260,
-     1203,  1203,  1203,  1203,
-      120,   120,   120,   120,
-      512,   512,   512,   512
-};
-
-// Temporary storage before the column pass
-#define ROW1 "%%xmm6"
-#define ROW3 "%%xmm4"
-#define ROW5 "%%xmm5"
-#define ROW7 "%%xmm7"
-
-#define CLEAR_ODD(r) "pxor  "r","r" \n\t"
-#define PUT_ODD(dst) "pshufhw  $0x1B, %%xmm2, "dst"   \n\t"
-
-#if ARCH_X86_64
-
-# define ROW0 "%%xmm8"
-# define REG0 ROW0
-# define ROW2 "%%xmm9"
-# define REG2 ROW2
-# define ROW4 "%%xmm10"
-# define REG4 ROW4
-# define ROW6 "%%xmm11"
-# define REG6 ROW6
-# define CLEAR_EVEN(r) CLEAR_ODD(r)
-# define PUT_EVEN(dst) PUT_ODD(dst)
-# define XMMS "%%xmm12"
-# define MOV_32_ONLY "#"
-# define SREG2 REG2
-# define TAN3 "%%xmm13"
-# define TAN1 "%%xmm14"
-
-#else
-
-# define ROW0 "(%0)"
-# define REG0 "%%xmm4"
-# define ROW2 "2*16(%0)"
-# define REG2 "%%xmm4"
-# define ROW4 "4*16(%0)"
-# define REG4 "%%xmm6"
-# define ROW6 "6*16(%0)"
-# define REG6 "%%xmm6"
-# define CLEAR_EVEN(r)
-# define PUT_EVEN(dst) \
-    "pshufhw  $0x1B, %%xmm2, %%xmm2   \n\t" \
-    "movdqa          %%xmm2, "dst"    \n\t"
-# define XMMS "%%xmm2"
-# define MOV_32_ONLY "movdqa "
-# define SREG2 "%%xmm7"
-# define TAN3 "%%xmm0"
-# define TAN1 "%%xmm2"
-
-#endif
-
-#define ROUND(x) "paddd   "x
-
-#define JZ(reg, to)                         \
-    "testl     "reg","reg"            \n\t" \
-    "jz        "to"                   \n\t"
-
-#define JNZ(reg, to)                        \
-    "testl     "reg","reg"            \n\t" \
-    "jnz       "to"                   \n\t"
-
-#define TEST_ONE_ROW(src, reg, clear)       \
-    clear                                   \
-    "movq     "src", %%mm1            \n\t" \
-    "por    8+"src", %%mm1            \n\t" \
-    "paddusb  %%mm0, %%mm1            \n\t" \
-    "pmovmskb %%mm1, "reg"            \n\t"
-
-#define TEST_TWO_ROWS(row1, row2, reg1, reg2, clear1, clear2) \
-    clear1                                                    \
-    clear2                                                    \
-    "movq     "row1", %%mm1           \n\t"                   \
-    "por    8+"row1", %%mm1           \n\t"                   \
-    "movq     "row2", %%mm2           \n\t"                   \
-    "por    8+"row2", %%mm2           \n\t"                   \
-    "paddusb   %%mm0, %%mm1           \n\t"                   \
-    "paddusb   %%mm0, %%mm2           \n\t"                   \
-    "pmovmskb  %%mm1, "reg1"          \n\t"                   \
-    "pmovmskb  %%mm2, "reg2"          \n\t"
-
-/// IDCT pass on rows.
-#define iMTX_MULT(src, table, rounder, put)            \
-    "movdqa        "src", %%xmm3      \n\t"            \
-    "movdqa       %%xmm3, %%xmm0      \n\t"            \
-    "pshufd   $0x11, %%xmm3, %%xmm1   \n\t" /* 4602 */ \
-    "punpcklqdq   %%xmm0, %%xmm0      \n\t" /* 0246 */ \
-    "pmaddwd     "table", %%xmm0      \n\t"            \
-    "pmaddwd  16+"table", %%xmm1      \n\t"            \
-    "pshufd   $0xBB, %%xmm3, %%xmm2   \n\t" /* 5713 */ \
-    "punpckhqdq   %%xmm3, %%xmm3      \n\t" /* 1357 */ \
-    "pmaddwd  32+"table", %%xmm2      \n\t"            \
-    "pmaddwd  48+"table", %%xmm3      \n\t"            \
-    "paddd        %%xmm1, %%xmm0      \n\t"            \
-    "paddd        %%xmm3, %%xmm2      \n\t"            \
-    rounder",     %%xmm0              \n\t"            \
-    "movdqa       %%xmm2, %%xmm3      \n\t"            \
-    "paddd        %%xmm0, %%xmm2      \n\t"            \
-    "psubd        %%xmm3, %%xmm0      \n\t"            \
-    "psrad           $11, %%xmm2      \n\t"            \
-    "psrad           $11, %%xmm0      \n\t"            \
-    "packssdw     %%xmm0, %%xmm2      \n\t"            \
-    put                                                \
-    "1:                               \n\t"
-
-#define iLLM_HEAD                           \
-    "movdqa   "MANGLE(tan3)", "TAN3"  \n\t" \
-    "movdqa   "MANGLE(tan1)", "TAN1"  \n\t" \
-
-/// IDCT pass on columns.
-#define iLLM_PASS(dct)                      \
-    "movdqa   "TAN3", %%xmm1          \n\t" \
-    "movdqa   "TAN1", %%xmm3          \n\t" \
-    "pmulhw   %%xmm4, "TAN3"          \n\t" \
-    "pmulhw   %%xmm5, %%xmm1          \n\t" \
-    "paddsw   %%xmm4, "TAN3"          \n\t" \
-    "paddsw   %%xmm5, %%xmm1          \n\t" \
-    "psubsw   %%xmm5, "TAN3"          \n\t" \
-    "paddsw   %%xmm4, %%xmm1          \n\t" \
-    "pmulhw   %%xmm7, %%xmm3          \n\t" \
-    "pmulhw   %%xmm6, "TAN1"          \n\t" \
-    "paddsw   %%xmm6, %%xmm3          \n\t" \
-    "psubsw   %%xmm7, "TAN1"          \n\t" \
-    "movdqa   %%xmm3, %%xmm7          \n\t" \
-    "movdqa   "TAN1", %%xmm6          \n\t" \
-    "psubsw   %%xmm1, %%xmm3          \n\t" \
-    "psubsw   "TAN3", "TAN1"          \n\t" \
-    "paddsw   %%xmm7, %%xmm1          \n\t" \
-    "paddsw   %%xmm6, "TAN3"          \n\t" \
-    "movdqa   %%xmm3, %%xmm6          \n\t" \
-    "psubsw   "TAN3", %%xmm3          \n\t" \
-    "paddsw   %%xmm6, "TAN3"          \n\t" \
-    "movdqa   "MANGLE(sqrt2)", %%xmm4 \n\t" \
-    "pmulhw   %%xmm4, %%xmm3          \n\t" \
-    "pmulhw   %%xmm4, "TAN3"          \n\t" \
-    "paddsw   "TAN3", "TAN3"          \n\t" \
-    "paddsw   %%xmm3, %%xmm3          \n\t" \
-    "movdqa   "MANGLE(tan2)", %%xmm7  \n\t" \
-    MOV_32_ONLY ROW2", "REG2"         \n\t" \
-    MOV_32_ONLY ROW6", "REG6"         \n\t" \
-    "movdqa   %%xmm7, %%xmm5          \n\t" \
-    "pmulhw   "REG6", %%xmm7          \n\t" \
-    "pmulhw   "REG2", %%xmm5          \n\t" \
-    "paddsw   "REG2", %%xmm7          \n\t" \
-    "psubsw   "REG6", %%xmm5          \n\t" \
-    MOV_32_ONLY ROW0", "REG0"         \n\t" \
-    MOV_32_ONLY ROW4", "REG4"         \n\t" \
-    MOV_32_ONLY"  "TAN1", (%0)        \n\t" \
-    "movdqa   "REG0", "XMMS"          \n\t" \
-    "psubsw   "REG4", "REG0"          \n\t" \
-    "paddsw   "XMMS", "REG4"          \n\t" \
-    "movdqa   "REG4", "XMMS"          \n\t" \
-    "psubsw   %%xmm7, "REG4"          \n\t" \
-    "paddsw   "XMMS", %%xmm7          \n\t" \
-    "movdqa   "REG0", "XMMS"          \n\t" \
-    "psubsw   %%xmm5, "REG0"          \n\t" \
-    "paddsw   "XMMS", %%xmm5          \n\t" \
-    "movdqa   %%xmm5, "XMMS"          \n\t" \
-    "psubsw   "TAN3", %%xmm5          \n\t" \
-    "paddsw   "XMMS", "TAN3"          \n\t" \
-    "movdqa   "REG0", "XMMS"          \n\t" \
-    "psubsw   %%xmm3, "REG0"          \n\t" \
-    "paddsw   "XMMS", %%xmm3          \n\t" \
-    MOV_32_ONLY"  (%0), "TAN1"        \n\t" \
-    "psraw        $6, %%xmm5          \n\t" \
-    "psraw        $6, "REG0"          \n\t" \
-    "psraw        $6, "TAN3"          \n\t" \
-    "psraw        $6, %%xmm3          \n\t" \
-    "movdqa   "TAN3", 1*16("dct")     \n\t" \
-    "movdqa   %%xmm3, 2*16("dct")     \n\t" \
-    "movdqa   "REG0", 5*16("dct")     \n\t" \
-    "movdqa   %%xmm5, 6*16("dct")     \n\t" \
-    "movdqa   %%xmm7, %%xmm0          \n\t" \
-    "movdqa   "REG4", %%xmm4          \n\t" \
-    "psubsw   %%xmm1, %%xmm7          \n\t" \
-    "psubsw   "TAN1", "REG4"          \n\t" \
-    "paddsw   %%xmm0, %%xmm1          \n\t" \
-    "paddsw   %%xmm4, "TAN1"          \n\t" \
-    "psraw        $6, %%xmm1          \n\t" \
-    "psraw        $6, %%xmm7          \n\t" \
-    "psraw        $6, "TAN1"          \n\t" \
-    "psraw        $6, "REG4"          \n\t" \
-    "movdqa   %%xmm1, ("dct")         \n\t" \
-    "movdqa   "TAN1", 3*16("dct")     \n\t" \
-    "movdqa   "REG4", 4*16("dct")     \n\t" \
-    "movdqa   %%xmm7, 7*16("dct")     \n\t"
-
-/// IDCT pass on columns, assuming rows 4-7 are zero.
-#define iLLM_PASS_SPARSE(dct)               \
-    "pmulhw   %%xmm4, "TAN3"          \n\t" \
-    "paddsw   %%xmm4, "TAN3"          \n\t" \
-    "movdqa   %%xmm6, %%xmm3          \n\t" \
-    "pmulhw   %%xmm6, "TAN1"          \n\t" \
-    "movdqa   %%xmm4, %%xmm1          \n\t" \
-    "psubsw   %%xmm1, %%xmm3          \n\t" \
-    "paddsw   %%xmm6, %%xmm1          \n\t" \
-    "movdqa   "TAN1", %%xmm6          \n\t" \
-    "psubsw   "TAN3", "TAN1"          \n\t" \
-    "paddsw   %%xmm6, "TAN3"          \n\t" \
-    "movdqa   %%xmm3, %%xmm6          \n\t" \
-    "psubsw   "TAN3", %%xmm3          \n\t" \
-    "paddsw   %%xmm6, "TAN3"          \n\t" \
-    "movdqa   "MANGLE(sqrt2)", %%xmm4 \n\t" \
-    "pmulhw   %%xmm4, %%xmm3          \n\t" \
-    "pmulhw   %%xmm4, "TAN3"          \n\t" \
-    "paddsw   "TAN3", "TAN3"          \n\t" \
-    "paddsw   %%xmm3, %%xmm3          \n\t" \
-    "movdqa   "MANGLE(tan2)", %%xmm5  \n\t" \
-    MOV_32_ONLY ROW2", "SREG2"        \n\t" \
-    "pmulhw   "SREG2", %%xmm5         \n\t" \
-    MOV_32_ONLY ROW0", "REG0"         \n\t" \
-    "movdqa   "REG0", %%xmm6          \n\t" \
-    "psubsw   "SREG2", %%xmm6         \n\t" \
-    "paddsw   "REG0", "SREG2"         \n\t" \
-    MOV_32_ONLY"  "TAN1", (%0)        \n\t" \
-    "movdqa   "REG0", "XMMS"          \n\t" \
-    "psubsw   %%xmm5, "REG0"          \n\t" \
-    "paddsw   "XMMS", %%xmm5          \n\t" \
-    "movdqa   %%xmm5, "XMMS"          \n\t" \
-    "psubsw   "TAN3", %%xmm5          \n\t" \
-    "paddsw   "XMMS", "TAN3"          \n\t" \
-    "movdqa   "REG0", "XMMS"          \n\t" \
-    "psubsw   %%xmm3, "REG0"          \n\t" \
-    "paddsw   "XMMS", %%xmm3          \n\t" \
-    MOV_32_ONLY"  (%0), "TAN1"        \n\t" \
-    "psraw        $6, %%xmm5          \n\t" \
-    "psraw        $6, "REG0"          \n\t" \
-    "psraw        $6, "TAN3"          \n\t" \
-    "psraw        $6, %%xmm3          \n\t" \
-    "movdqa   "TAN3", 1*16("dct")     \n\t" \
-    "movdqa   %%xmm3, 2*16("dct")     \n\t" \
-    "movdqa   "REG0", 5*16("dct")     \n\t" \
-    "movdqa   %%xmm5, 6*16("dct")     \n\t" \
-    "movdqa   "SREG2", %%xmm0         \n\t" \
-    "movdqa   %%xmm6, %%xmm4          \n\t" \
-    "psubsw   %%xmm1, "SREG2"         \n\t" \
-    "psubsw   "TAN1", %%xmm6          \n\t" \
-    "paddsw   %%xmm0, %%xmm1          \n\t" \
-    "paddsw   %%xmm4, "TAN1"          \n\t" \
-    "psraw        $6, %%xmm1          \n\t" \
-    "psraw        $6, "SREG2"         \n\t" \
-    "psraw        $6, "TAN1"          \n\t" \
-    "psraw        $6, %%xmm6          \n\t" \
-    "movdqa   %%xmm1, ("dct")         \n\t" \
-    "movdqa   "TAN1", 3*16("dct")     \n\t" \
-    "movdqa   %%xmm6, 4*16("dct")     \n\t" \
-    "movdqa   "SREG2", 7*16("dct")    \n\t"
-
-av_extern_inline void ff_xvid_idct_sse2(short *block)
-{
-    __asm__ volatile (
-        "movq     "MANGLE (m127) ", %%mm0                              \n\t"
-        iMTX_MULT("(%0)",     MANGLE(iTab1), ROUND(MANGLE(walkenIdctRounders)),        PUT_EVEN(ROW0))
-        iMTX_MULT("1*16(%0)", MANGLE(iTab2), ROUND("1*16+"MANGLE(walkenIdctRounders)), PUT_ODD(ROW1))
-        iMTX_MULT("2*16(%0)", MANGLE(iTab3), ROUND("2*16+"MANGLE(walkenIdctRounders)), PUT_EVEN(ROW2))
-
-        TEST_TWO_ROWS("3*16(%0)", "4*16(%0)", "%%eax", "%%ecx", CLEAR_ODD(ROW3), CLEAR_EVEN(ROW4))
-        JZ("%%eax", "1f")
-        iMTX_MULT("3*16(%0)", MANGLE(iTab4), ROUND("3*16+"MANGLE(walkenIdctRounders)), PUT_ODD(ROW3))
-
-        TEST_TWO_ROWS("5*16(%0)", "6*16(%0)", "%%eax", "%%edx", CLEAR_ODD(ROW5), CLEAR_EVEN(ROW6))
-        TEST_ONE_ROW("7*16(%0)", "%%esi", CLEAR_ODD(ROW7))
-        iLLM_HEAD
-        ".p2align 4 \n\t"
-        JNZ("%%ecx", "2f")
-        JNZ("%%eax", "3f")
-        JNZ("%%edx", "4f")
-        JNZ("%%esi", "5f")
-        iLLM_PASS_SPARSE("%0")
-        "jmp 6f                                                      \n\t"
-        "2:                                                          \n\t"
-        iMTX_MULT("4*16(%0)", MANGLE(iTab1), "#", PUT_EVEN(ROW4))
-        "3:                                                          \n\t"
-        iMTX_MULT("5*16(%0)", MANGLE(iTab4), ROUND("4*16+"MANGLE(walkenIdctRounders)), PUT_ODD(ROW5))
-        JZ("%%edx", "1f")
-        "4:                                                          \n\t"
-        iMTX_MULT("6*16(%0)", MANGLE(iTab3), ROUND("5*16+"MANGLE(walkenIdctRounders)), PUT_EVEN(ROW6))
-        JZ("%%esi", "1f")
-        "5:                                                          \n\t"
-        iMTX_MULT("7*16(%0)", MANGLE(iTab2), ROUND("5*16+"MANGLE(walkenIdctRounders)), PUT_ODD(ROW7))
-#if ARCH_X86_32
-        iLLM_HEAD
-#endif
-        iLLM_PASS("%0")
-        "6:                                                          \n\t"
-        : "+r" (block)
-        : NAMED_CONSTRAINTS_ARRAY(m127,iTab1,walkenIdctRounders,iTab2,iTab3,iTab4,tan3,tan1,tan2,sqrt2)
-        : XMM_CLOBBERS("%xmm0", "%xmm1", "%xmm2", "%xmm3",
-                       "%xmm4", "%xmm5", "%xmm6", "%xmm7", )
-#if ARCH_X86_64
-          XMM_CLOBBERS("%xmm8", "%xmm9", "%xmm10", "%xmm11",
-                       "%xmm12", "%xmm13", "%xmm14", )
-#endif
-          "%eax", "%ecx", "%edx", "%esi", "memory");
-}
-
-void ff_xvid_idct_sse2_put(uint8_t *dest, int line_size, short *block)
-{
-    ff_xvid_idct_sse2(block);
-    ff_put_pixels_clamped(block, dest, line_size);
-}
-
-void ff_xvid_idct_sse2_add(uint8_t *dest, int line_size, short *block)
-{
-    ff_xvid_idct_sse2(block);
-    ff_add_pixels_clamped(block, dest, line_size);
-}
-
-#endif /* HAVE_SSE2_INLINE */
diff --git a/libavcodec/xfaceenc.c b/libavcodec/xfaceenc.c
index 7edef1e..fa6f227 100644
--- a/libavcodec/xfaceenc.c
+++ b/libavcodec/xfaceenc.c
@@ -223,7 +223,7 @@
 
 static av_cold int xface_encode_close(AVCodecContext *avctx)
 {
-    av_freep(&avctx->coded_frame);
+    av_frame_free(&avctx->coded_frame);
 
     return 0;
 }
@@ -237,5 +237,5 @@
     .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 },
+    .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_MONOWHITE, AV_PIX_FMT_NONE },
 };
diff --git a/libavcodec/y41penc.c b/libavcodec/y41penc.c
index 8f67944..4778618 100644
--- a/libavcodec/y41penc.c
+++ b/libavcodec/y41penc.c
@@ -84,7 +84,7 @@
 
 static av_cold int y41p_encode_close(AVCodecContext *avctx)
 {
-    av_freep(&avctx->coded_frame);
+    av_frame_free(&avctx->coded_frame);
 
     return 0;
 }
diff --git a/libavcodec/yuv4enc.c b/libavcodec/yuv4enc.c
index ed0fc77..5ce4846 100644
--- a/libavcodec/yuv4enc.c
+++ b/libavcodec/yuv4enc.c
@@ -74,7 +74,7 @@
 
 static av_cold int yuv4_encode_close(AVCodecContext *avctx)
 {
-    av_freep(&avctx->coded_frame);
+    av_frame_free(&avctx->coded_frame);
 
     return 0;
 }
diff --git a/libavcodec/zerocodec.c b/libavcodec/zerocodec.c
index 9f6c37c..12d8024 100644
--- a/libavcodec/zerocodec.c
+++ b/libavcodec/zerocodec.c
@@ -22,7 +22,7 @@
 #include "internal.h"
 #include "libavutil/common.h"
 
-typedef struct {
+typedef struct ZeroCodecContext {
     AVFrame  *previous_frame;
     z_stream zstream;
 } ZeroCodecContext;
diff --git a/libavcodec/zmbv.c b/libavcodec/zmbv.c
index c16d912..82ae169 100644
--- a/libavcodec/zmbv.c
+++ b/libavcodec/zmbv.c
@@ -410,11 +410,16 @@
     int hi_ver, lo_ver, ret;
 
     /* parse header */
+    if (len < 1)
+        return AVERROR_INVALIDDATA;
     c->flags = buf[0];
     buf++; len--;
     if (c->flags & ZMBV_KEYFRAME) {
         void *decode_intra = NULL;
         c->decode_intra= NULL;
+
+        if (len < 6)
+            return AVERROR_INVALIDDATA;
         hi_ver = buf[0];
         lo_ver = buf[1];
         c->comp = buf[2];
diff --git a/libavdevice/alsa-audio-dec.c b/libavdevice/alsa-audio-dec.c
index 7f8f8cd..efa6747 100644
--- a/libavdevice/alsa-audio-dec.c
+++ b/libavdevice/alsa-audio-dec.c
@@ -80,6 +80,7 @@
     st->codec->codec_id    = codec_id;
     st->codec->sample_rate = s->sample_rate;
     st->codec->channels    = s->channels;
+    st->codec->frame_size = s->frame_size;
     avpriv_set_pts_info(st, 64, 1, 1000000);  /* 64 bits pts in us */
     /* microseconds instead of seconds, MHz instead of Hz */
     s->timefilter = ff_timefilter_new(1000000.0 / s->sample_rate,
diff --git a/libavdevice/avfoundation.m b/libavdevice/avfoundation.m
index 1a7eb5b..e00cc3b 100644
--- a/libavdevice/avfoundation.m
+++ b/libavdevice/avfoundation.m
@@ -71,7 +71,7 @@
     { AV_PIX_FMT_YUV420P,      kCVPixelFormatType_420YpCbCr8Planar },
     { AV_PIX_FMT_NV12,         kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange },
     { AV_PIX_FMT_YUYV422,      kCVPixelFormatType_422YpCbCr8_yuvs },
-#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
+#if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
     { AV_PIX_FMT_GRAY8,        kCVPixelFormatType_OneComponent8 },
 #endif
     { AV_PIX_FMT_NONE, 0 }
@@ -268,6 +268,10 @@
     AVFContext *ctx = (AVFContext*)s->priv_data;
     NSError *error  = nil;
     AVCaptureInput* capture_input = nil;
+    struct AVFPixelFormatSpec pxl_fmt_spec;
+    NSNumber *pixel_format;
+    NSDictionary *capture_dict;
+    dispatch_queue_t queue;
 
     if (ctx->video_device_index < ctx->num_video_devices) {
         capture_input = (AVCaptureInput*) [[[AVCaptureDeviceInput alloc] initWithDevice:video_device error:&error] autorelease];
@@ -297,7 +301,6 @@
     }
 
     // select pixel format
-    struct AVFPixelFormatSpec pxl_fmt_spec;
     pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
 
     for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
@@ -352,8 +355,8 @@
     }
 
     ctx->pixel_format          = pxl_fmt_spec.ff_id;
-    NSNumber     *pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
-    NSDictionary *capture_dict = [NSDictionary dictionaryWithObject:pixel_format
+    pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
+    capture_dict = [NSDictionary dictionaryWithObject:pixel_format
                                                forKey:(id)kCVPixelBufferPixelFormatTypeKey];
 
     [ctx->video_output setVideoSettings:capture_dict];
@@ -361,7 +364,7 @@
 
     ctx->avf_delegate = [[AVFFrameReceiver alloc] initWithContext:ctx];
 
-    dispatch_queue_t queue = dispatch_queue_create("avf_queue", NULL);
+    queue = dispatch_queue_create("avf_queue", NULL);
     [ctx->video_output setSampleBufferDelegate:ctx->avf_delegate queue:queue];
     dispatch_release(queue);
 
@@ -380,6 +383,7 @@
     AVFContext *ctx = (AVFContext*)s->priv_data;
     NSError *error  = nil;
     AVCaptureDeviceInput* audio_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:audio_device error:&error] autorelease];
+    dispatch_queue_t queue;
 
     if (!audio_dev_input) {
         av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
@@ -404,7 +408,7 @@
 
     ctx->avf_audio_delegate = [[AVFAudioReceiver alloc] initWithContext:ctx];
 
-    dispatch_queue_t queue = dispatch_queue_create("avf_audio_queue", NULL);
+    queue = dispatch_queue_create("avf_audio_queue", NULL);
     [ctx->audio_output setSampleBufferDelegate:ctx->avf_audio_delegate queue:queue];
     dispatch_release(queue);
 
@@ -421,6 +425,13 @@
 static int get_video_config(AVFormatContext *s)
 {
     AVFContext *ctx = (AVFContext*)s->priv_data;
+    CVImageBufferRef image_buffer;
+    CGSize image_buffer_size;
+    AVStream* stream = avformat_new_stream(s, NULL);
+
+    if (!stream) {
+        return 1;
+    }
 
     // Take stream info from the first frame.
     while (ctx->frames_captured < 1) {
@@ -429,18 +440,12 @@
 
     lock_frames(ctx);
 
-    AVStream* stream = avformat_new_stream(s, NULL);
-
-    if (!stream) {
-        return 1;
-    }
-
     ctx->video_stream_index = stream->index;
 
     avpriv_set_pts_info(stream, 64, 1, avf_time_base);
 
-    CVImageBufferRef image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
-    CGSize image_buffer_size      = CVImageBufferGetEncodedSize(image_buffer);
+    image_buffer      = CMSampleBufferGetImageBuffer(ctx->current_frame);
+    image_buffer_size = CVImageBufferGetEncodedSize(image_buffer);
 
     stream->codec->codec_id   = AV_CODEC_ID_RAWVIDEO;
     stream->codec->codec_type = AVMEDIA_TYPE_VIDEO;
@@ -459,6 +464,12 @@
 static int get_audio_config(AVFormatContext *s)
 {
     AVFContext *ctx = (AVFContext*)s->priv_data;
+    CMFormatDescriptionRef format_desc;
+    AVStream* stream = avformat_new_stream(s, NULL);
+
+    if (!stream) {
+        return 1;
+    }
 
     // Take stream info from the first frame.
     while (ctx->audio_frames_captured < 1) {
@@ -467,17 +478,11 @@
 
     lock_frames(ctx);
 
-    AVStream* stream = avformat_new_stream(s, NULL);
-
-    if (!stream) {
-        return 1;
-    }
-
     ctx->audio_stream_index = stream->index;
 
     avpriv_set_pts_info(stream, 64, 1, avf_time_base);
 
-    CMFormatDescriptionRef format_desc = CMSampleBufferGetFormatDescription(ctx->current_audio_frame);
+    format_desc = CMSampleBufferGetFormatDescription(ctx->current_audio_frame);
     const AudioStreamBasicDescription *basic_desc = CMAudioFormatDescriptionGetStreamBasicDescription(format_desc);
 
     if (!basic_desc) {
@@ -500,8 +505,24 @@
 
     if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
         ctx->audio_float &&
+        ctx->audio_bits_per_sample == 32 &&
         ctx->audio_packed) {
         stream->codec->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
+    } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
+        ctx->audio_signed_integer &&
+        ctx->audio_bits_per_sample == 16 &&
+        ctx->audio_packed) {
+        stream->codec->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
+    } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
+        ctx->audio_signed_integer &&
+        ctx->audio_bits_per_sample == 24 &&
+        ctx->audio_packed) {
+        stream->codec->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
+    } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
+        ctx->audio_signed_integer &&
+        ctx->audio_bits_per_sample == 32 &&
+        ctx->audio_packed) {
+        stream->codec->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
     } else {
         av_log(s, AV_LOG_ERROR, "audio format is not supported\n");
         return 1;
@@ -528,30 +549,35 @@
 static int avf_read_header(AVFormatContext *s)
 {
     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+    uint32_t num_screens    = 0;
     AVFContext *ctx         = (AVFContext*)s->priv_data;
+    AVCaptureDevice *video_device = nil;
+    AVCaptureDevice *audio_device = nil;
+    // Find capture device
+    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
+    ctx->num_video_devices = [devices count];
+
     ctx->first_pts          = av_gettime();
     ctx->first_audio_pts    = av_gettime();
-    uint32_t num_screens    = 0;
 
     pthread_mutex_init(&ctx->frame_lock, NULL);
     pthread_cond_init(&ctx->frame_wait_cond, NULL);
 
-#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
+#if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
     CGGetActiveDisplayList(0, NULL, &num_screens);
 #endif
 
     // List devices if requested
     if (ctx->list_devices) {
-        av_log(ctx, AV_LOG_INFO, "AVFoundation video devices:\n");
-        NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
         int index = 0;
+        av_log(ctx, AV_LOG_INFO, "AVFoundation video devices:\n");
         for (AVCaptureDevice *device in devices) {
             const char *name = [[device localizedName] UTF8String];
             index            = [devices indexOfObject:device];
             av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
             index++;
         }
-#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
+#if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
         if (num_screens > 0) {
             CGDirectDisplayID screens[num_screens];
             CGGetActiveDisplayList(num_screens, screens, &num_screens);
@@ -571,13 +597,6 @@
          goto fail;
     }
 
-    // Find capture device
-    AVCaptureDevice *video_device = nil;
-    AVCaptureDevice *audio_device = nil;
-
-    NSArray *video_devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
-    ctx->num_video_devices = [video_devices count];
-
     // parse input filename for video and audio device
     parse_device_name(s);
 
@@ -591,9 +610,9 @@
 
     if (ctx->video_device_index >= 0) {
         if (ctx->video_device_index < ctx->num_video_devices) {
-            video_device = [video_devices objectAtIndex:ctx->video_device_index];
+            video_device = [devices objectAtIndex:ctx->video_device_index];
         } else if (ctx->video_device_index < ctx->num_video_devices + num_screens) {
-#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
+#if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
             CGDirectDisplayID screens[num_screens];
             CGGetActiveDisplayList(num_screens, screens, &num_screens);
             AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[ctx->video_device_index - ctx->num_video_devices]] autorelease];
@@ -609,14 +628,14 @@
             video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
         } else {
         // looking for video inputs
-        for (AVCaptureDevice *device in video_devices) {
+        for (AVCaptureDevice *device in devices) {
             if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
                 video_device = device;
                 break;
             }
         }
 
-#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
+#if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
         // looking for screen inputs
         if (!video_device) {
             int idx;
@@ -719,11 +738,13 @@
     AVFContext* ctx = (AVFContext*)s->priv_data;
 
     do {
+        CVImageBufferRef image_buffer;
         lock_frames(ctx);
 
-        CVImageBufferRef image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
+        image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
 
         if (ctx->current_frame != nil) {
+            void *data;
             if (av_new_packet(pkt, (int)CVPixelBufferGetDataSize(image_buffer)) < 0) {
                 return AVERROR(EIO);
             }
@@ -736,7 +757,7 @@
 
             CVPixelBufferLockBaseAddress(image_buffer, 0);
 
-            void* data = CVPixelBufferGetBaseAddress(image_buffer);
+            data = CVPixelBufferGetBaseAddress(image_buffer);
             memcpy(pkt->data, data, pkt->size);
 
             CVPixelBufferUnlockBaseAddress(image_buffer, 0);
@@ -766,14 +787,14 @@
             pkt->flags        |= AV_PKT_FLAG_KEY;
 
             if (ctx->audio_non_interleaved) {
-                int sample, c, shift;
+                int sample, c, shift, num_samples;
 
                 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, ctx->audio_buffer);
                 if (ret != kCMBlockBufferNoErr) {
                     return AVERROR(EIO);
                 }
 
-                int num_samples = pkt->size / (ctx->audio_channels * (ctx->audio_bits_per_sample >> 3));
+                num_samples = pkt->size / (ctx->audio_channels * (ctx->audio_bits_per_sample >> 3));
 
                 // transform decoded frame into output format
                 #define INTERLEAVE_OUTPUT(bps)                                         \
diff --git a/libavdevice/bktr.c b/libavdevice/bktr.c
index 6c5a834..c8a8953 100644
--- a/libavdevice/bktr.c
+++ b/libavdevice/bktr.c
@@ -104,6 +104,8 @@
     char *arg;
     int c;
     struct sigaction act = { {0} }, old;
+    int ret;
+    char errbuf[128];
 
     if (idev < 0 || idev > 4)
     {
@@ -142,8 +144,10 @@
 
     *video_fd = avpriv_open(video_device, O_RDONLY);
     if (*video_fd < 0) {
-        av_log(NULL, AV_LOG_ERROR, "%s: %s\n", video_device, strerror(errno));
-        return -1;
+        ret = AVERROR(errno);
+        av_strerror(ret, errbuf, sizeof(errbuf));
+        av_log(NULL, AV_LOG_ERROR, "%s: %s\n", video_device, errbuf);
+        return ret;
     }
 
     geo.rows = height;
@@ -165,19 +169,25 @@
         geo.oformat |= METEOR_GEO_EVEN_ONLY;
 
     if (ioctl(*video_fd, METEORSETGEO, &geo) < 0) {
-        av_log(NULL, AV_LOG_ERROR, "METEORSETGEO: %s\n", strerror(errno));
-        return -1;
+        ret = AVERROR(errno);
+        av_strerror(ret, errbuf, sizeof(errbuf));
+        av_log(NULL, AV_LOG_ERROR, "METEORSETGEO: %s\n", errbuf);
+        return ret;
     }
 
     if (ioctl(*video_fd, BT848SFMT, &c) < 0) {
-        av_log(NULL, AV_LOG_ERROR, "BT848SFMT: %s\n", strerror(errno));
-        return -1;
+        ret = AVERROR(errno);
+        av_strerror(ret, errbuf, sizeof(errbuf));
+        av_log(NULL, AV_LOG_ERROR, "BT848SFMT: %s\n", errbuf);
+        return ret;
     }
 
     c = bktr_dev[idev];
     if (ioctl(*video_fd, METEORSINPUT, &c) < 0) {
-        av_log(NULL, AV_LOG_ERROR, "METEORSINPUT: %s\n", strerror(errno));
-        return -1;
+        ret = AVERROR(errno);
+        av_strerror(ret, errbuf, sizeof(errbuf));
+        av_log(NULL, AV_LOG_ERROR, "METEORSINPUT: %s\n", errbuf);
+        return ret;
     }
 
     video_buf_size = width * height * 12 / 8;
@@ -185,8 +195,10 @@
     video_buf = (uint8_t *)mmap((caddr_t)0, video_buf_size,
         PROT_READ, MAP_SHARED, *video_fd, (off_t)0);
     if (video_buf == MAP_FAILED) {
-        av_log(NULL, AV_LOG_ERROR, "mmap: %s\n", strerror(errno));
-        return -1;
+        ret = AVERROR(errno);
+        av_strerror(ret, errbuf, sizeof(errbuf));
+        av_log(NULL, AV_LOG_ERROR, "mmap: %s\n", errbuf);
+        return ret;
     }
 
     if (frequency != 0.0) {
diff --git a/libavdevice/decklink_common.cpp b/libavdevice/decklink_common.cpp
index 07e1651..ac7964c 100644
--- a/libavdevice/decklink_common.cpp
+++ b/libavdevice/decklink_common.cpp
@@ -70,6 +70,16 @@
 #define DECKLINK_STR    OLECHAR *
 #define DECKLINK_STRDUP dup_wchar_to_utf8
 #define DECKLINK_FREE(s) SysFreeString(s)
+#elif defined(__APPLE__)
+static char *dup_cfstring_to_utf8(CFStringRef w)
+{
+    char s[256];
+    CFStringGetCString(w, s, 255, kCFStringEncodingUTF8);
+    return av_strdup(s);
+}
+#define DECKLINK_STR    const __CFString *
+#define DECKLINK_STRDUP dup_cfstring_to_utf8
+#define DECKLINK_FREE(s) free((void *) s)
 #else
 #define DECKLINK_STR    const char *
 #define DECKLINK_STRDUP av_strdup
diff --git a/libavdevice/decklink_common_c.h b/libavdevice/decklink_common_c.h
index 861a51a..fb2b788 100644
--- a/libavdevice/decklink_common_c.h
+++ b/libavdevice/decklink_common_c.h
@@ -28,5 +28,6 @@
     int list_devices;
     int list_formats;
     double preroll;
+    int v210;
 };
 
diff --git a/libavdevice/decklink_dec.cpp b/libavdevice/decklink_dec.cpp
index 77a0fe5..747f47e 100644
--- a/libavdevice/decklink_dec.cpp
+++ b/libavdevice/decklink_dec.cpp
@@ -233,6 +233,7 @@
                                   ctx->video_st->time_base.den);
 
         if (videoFrame->GetFlags() & bmdFrameHasNoInputSource) {
+            if (videoFrame->GetPixelFormat() == bmdFormat8BitYUV) {
             unsigned bars[8] = {
                 0xEA80EA80, 0xD292D210, 0xA910A9A5, 0x90229035,
                 0x6ADD6ACA, 0x51EF515A, 0x286D28EF, 0x10801080 };
@@ -244,6 +245,7 @@
                 for (int x = 0; x < width; x += 2)
                     *p++ = bars[(x * 8) / width];
             }
+            }
 
             if (!no_video) {
                 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - No input signal detected "
@@ -466,15 +468,21 @@
         goto error;
     }
     st->codec->codec_type  = AVMEDIA_TYPE_VIDEO;
-    st->codec->codec_id    = AV_CODEC_ID_RAWVIDEO;
     st->codec->width       = ctx->bmd_width;
     st->codec->height      = ctx->bmd_height;
 
-    st->codec->pix_fmt     = AV_PIX_FMT_UYVY422;
     st->codec->time_base.den      = ctx->bmd_tb_den;
     st->codec->time_base.num      = ctx->bmd_tb_num;
     st->codec->bit_rate    = avpicture_get_size(st->codec->pix_fmt, ctx->bmd_width, ctx->bmd_height) * 1/av_q2d(st->codec->time_base) * 8;
-    st->codec->codec_tag   = MKTAG('U', 'Y', 'V', 'Y');
+
+    if (cctx->v210) {
+        st->codec->codec_id    = AV_CODEC_ID_V210;
+        st->codec->codec_tag   = MKTAG('V', '2', '1', '0');
+    } else {
+        st->codec->codec_id    = AV_CODEC_ID_RAWVIDEO;
+        st->codec->pix_fmt     = AV_PIX_FMT_UYVY422;
+        st->codec->codec_tag   = MKTAG('U', 'Y', 'V', 'Y');
+    }
 
     avpriv_set_pts_info(st, 64, 1, 1000000);  /* 64 bits pts in us */
 
@@ -487,7 +495,9 @@
         goto error;
     }
 
-    result = ctx->dli->EnableVideoInput(ctx->bmd_mode, bmdFormat8BitYUV, bmdVideoInputFlagDefault);
+    result = ctx->dli->EnableVideoInput(ctx->bmd_mode,
+                                        cctx->v210 ? bmdFormat10BitYUV : bmdFormat8BitYUV,
+                                        bmdVideoInputFlagDefault);
 
     if (result != S_OK) {
         av_log(avctx, AV_LOG_ERROR, "Cannot enable video input\n");
diff --git a/libavdevice/decklink_dec_c.c b/libavdevice/decklink_dec_c.c
index 2aea277..b1a65e6 100644
--- a/libavdevice/decklink_dec_c.c
+++ b/libavdevice/decklink_dec_c.c
@@ -31,6 +31,7 @@
 static const AVOption options[] = {
     { "list_devices", "list available devices"  , OFFSET(list_devices), AV_OPT_TYPE_INT   , { .i64 = 0   }, 0, 1, DEC },
     { "list_formats", "list supported formats"  , OFFSET(list_formats), AV_OPT_TYPE_INT   , { .i64 = 0   }, 0, 1, DEC },
+    { "bm_v210",      "v210 10 bit per channel" , OFFSET(v210),         AV_OPT_TYPE_INT   , { .i64 = 0   }, 0, 1, DEC },
     { NULL },
 };
 
diff --git a/libavdevice/libcdio.c b/libavdevice/libcdio.c
index 16a4b26..9e9b0d8 100644
--- a/libavdevice/libcdio.c
+++ b/libavdevice/libcdio.c
@@ -164,11 +164,13 @@
 #define OFFSET(x) offsetof(CDIOContext, x)
 #define DEC AV_OPT_FLAG_DECODING_PARAM
 static const AVOption options[] = {
-    { "speed",              "Drive reading speed.", OFFSET(speed),         AV_OPT_TYPE_INT,   { .i64 = 0 }, 0,       INT_MAX, DEC },
-    { "paranoia_mode",      "Error recovery mode.", OFFSET(paranoia_mode), AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT_MIN, INT_MAX, DEC, "paranoia_mode" },
-        { "verify",         "Verify data integrity in overlap area", 0,    AV_OPT_TYPE_CONST, { .i64 = PARANOIA_MODE_VERIFY },    0, 0, DEC, "paranoia_mode" },
-        { "overlap",        "Perform overlapped reads.",             0,    AV_OPT_TYPE_CONST, { .i64 = PARANOIA_MODE_OVERLAP },   0, 0, DEC, "paranoia_mode" },
-        { "neverskip",      "Do not skip failed reads.",             0,    AV_OPT_TYPE_CONST, { .i64 = PARANOIA_MODE_NEVERSKIP }, 0, 0, DEC, "paranoia_mode" },
+    { "speed",              "set drive reading speed", OFFSET(speed),         AV_OPT_TYPE_INT,   { .i64 = 0 }, 0,       INT_MAX, DEC },
+    { "paranoia_mode",      "set error recovery mode", OFFSET(paranoia_mode), AV_OPT_TYPE_FLAGS, { .i64 = PARANOIA_MODE_DISABLE }, INT_MIN, INT_MAX, DEC, "paranoia_mode" },
+        { "disable",        "apply no fixups",                      0,    AV_OPT_TYPE_CONST, { .i64 = PARANOIA_MODE_DISABLE },   0, 0, DEC, "paranoia_mode" },
+        { "verify",         "verify data integrity in overlap area", 0,   AV_OPT_TYPE_CONST, { .i64 = PARANOIA_MODE_VERIFY },    0, 0, DEC, "paranoia_mode" },
+        { "overlap",        "perform overlapped reads",             0,    AV_OPT_TYPE_CONST, { .i64 = PARANOIA_MODE_OVERLAP },   0, 0, DEC, "paranoia_mode" },
+        { "neverskip",      "do not skip failed reads",             0,    AV_OPT_TYPE_CONST, { .i64 = PARANOIA_MODE_NEVERSKIP }, 0, 0, DEC, "paranoia_mode" },
+        { "full",           "apply all recovery modes",             0,    AV_OPT_TYPE_CONST, { .i64 = PARANOIA_MODE_FULL },      0, 0, DEC, "paranoia_mode" },
     { NULL },
 };
 
diff --git a/libavdevice/qtkit.m b/libavdevice/qtkit.m
index aa8fa16..22a94ca 100644
--- a/libavdevice/qtkit.m
+++ b/libavdevice/qtkit.m
@@ -25,6 +25,10 @@
  * @author Vadim Kalinsky <vadim@kalinsky.ru>
  */
 
+#if defined(__clang__)
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+#endif
+
 #import <QTKit/QTKit.h>
 #include <pthread.h>
 
diff --git a/libavdevice/v4l2.c b/libavdevice/v4l2.c
index 8337cf5..fba7764 100644
--- a/libavdevice/v4l2.c
+++ b/libavdevice/v4l2.c
@@ -285,9 +285,9 @@
                    vfd.description);
         } else if (vfd.flags & V4L2_FMT_FLAG_COMPRESSED &&
                    type & V4L_COMPFORMATS) {
-            AVCodec *codec = avcodec_find_decoder(codec_id);
-            av_log(ctx, AV_LOG_INFO, "Compressed: %9s : %20s :",
-                   codec ? codec->name : "Unsupported",
+            const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
+            av_log(ctx, AV_LOG_INFO, "Compressedll      : %9s : %20s :",
+                   desc ? desc->name : "Unsupported",
                    vfd.description);
         } else {
             continue;
@@ -747,7 +747,7 @@
             }
         } else {
             av_log(ctx, AV_LOG_WARNING,
-                   "The driver does not allow to change time per frame\n");
+                   "The driver does not permit changing the time per frame\n");
         }
     }
     if (tpf->denominator > 0 && tpf->numerator > 0) {
diff --git a/libavdevice/x11grab.c b/libavdevice/x11grab.c
index 3a833eb..be883da 100644
--- a/libavdevice/x11grab.c
+++ b/libavdevice/x11grab.c
@@ -657,6 +657,8 @@
 #define OFFSET(x) offsetof(X11GrabContext, x)
 #define DEC AV_OPT_FLAG_DECODING_PARAM
 static const AVOption options[] = {
+    { "grab_x", "Initial x coordinate.", OFFSET(x_off), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, DEC },
+    { "grab_y", "Initial y coordinate.", OFFSET(y_off), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, DEC },
     { "draw_mouse", "draw the mouse pointer", OFFSET(draw_mouse), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, DEC },
 
     { "follow_mouse", "move the grabbing region when the mouse pointer reaches within specified amount of pixels to the edge of region",
diff --git a/libavdevice/xcbgrab.c b/libavdevice/xcbgrab.c
index e26448c..17d8f9a 100644
--- a/libavdevice/xcbgrab.c
+++ b/libavdevice/xcbgrab.c
@@ -54,7 +54,6 @@
 #if CONFIG_LIBXCB_SHM
     xcb_shm_seg_t segment;
 #endif
-
     int64_t time_frame;
     AVRational time_base;
 
@@ -82,6 +81,8 @@
 static const AVOption options[] = {
     { "x", "Initial x coordinate.", OFFSET(x), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
     { "y", "Initial y coordinate.", OFFSET(y), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
+    { "grab_x", "Initial x coordinate.", OFFSET(x), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
+    { "grab_y", "Initial y coordinate.", OFFSET(y), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
     { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), AV_OPT_TYPE_STRING, {.str = "vga" }, 0, 0, D },
     { "framerate", "", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = "ntsc" }, 0, 0, D },
     { "draw_mouse", "Draw the mouse pointer.", OFFSET(draw_mouse), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, D },
@@ -614,11 +615,13 @@
 
     c->conn = xcb_connect(display_name[0] ? display_name : NULL, &screen_num);
     av_freep(&display_name);
+
     if ((ret = xcb_connection_has_error(c->conn))) {
         av_log(s, AV_LOG_ERROR, "Cannot open display %s, error %d.\n",
                s->filename[0] ? s->filename : "default", ret);
         return AVERROR(EIO);
     }
+
     setup = xcb_get_setup(c->conn);
 
     c->screen = get_screen(setup, screen_num);
@@ -629,10 +632,6 @@
         return AVERROR(EIO);
     }
 
-#if CONFIG_LIBXCB_SHM
-    c->segment = xcb_generate_id(c->conn);
-#endif
-
     ret = create_stream(s);
 
     if (ret < 0) {
@@ -641,7 +640,8 @@
     }
 
 #if CONFIG_LIBXCB_SHM
-    c->has_shm = check_shm(c->conn);
+    if ((c->has_shm = check_shm(c->conn)))
+        c->segment = xcb_generate_id(c->conn);
 #endif
 
 #if CONFIG_LIBXCB_XFIXES
diff --git a/libavfilter/Makefile b/libavfilter/Makefile
index 7e0d456..2cde029 100644
--- a/libavfilter/Makefile
+++ b/libavfilter/Makefile
@@ -65,6 +65,7 @@
 OBJS-$(CONFIG_CHANNELMAP_FILTER)             += af_channelmap.o
 OBJS-$(CONFIG_CHANNELSPLIT_FILTER)           += af_channelsplit.o
 OBJS-$(CONFIG_COMPAND_FILTER)                += af_compand.o
+OBJS-$(CONFIG_DCSHIFT_FILTER)                += af_dcshift.o
 OBJS-$(CONFIG_EARWAX_FILTER)                 += af_earwax.o
 OBJS-$(CONFIG_EBUR128_FILTER)                += f_ebur128.o
 OBJS-$(CONFIG_EQUALIZER_FILTER)              += af_biquads.o
@@ -119,6 +120,7 @@
 OBJS-$(CONFIG_EQ_FILTER)                     += vf_eq.o
 OBJS-$(CONFIG_EXTRACTPLANES_FILTER)          += vf_extractplanes.o
 OBJS-$(CONFIG_FADE_FILTER)                   += vf_fade.o
+OBJS-$(CONFIG_FFTFILT_FILTER)                += vf_fftfilt.o
 OBJS-$(CONFIG_FIELD_FILTER)                  += vf_field.o
 OBJS-$(CONFIG_FIELDMATCH_FILTER)             += vf_fieldmatch.o
 OBJS-$(CONFIG_FIELDORDER_FILTER)             += vf_fieldorder.o
@@ -149,7 +151,6 @@
 OBJS-$(CONFIG_LUTYUV_FILTER)                 += vf_lut.o
 OBJS-$(CONFIG_MCDEINT_FILTER)                += vf_mcdeint.o
 OBJS-$(CONFIG_MERGEPLANES_FILTER)            += vf_mergeplanes.o framesync.o
-OBJS-$(CONFIG_MP_FILTER)                     += vf_mp.o
 OBJS-$(CONFIG_MPDECIMATE_FILTER)             += vf_mpdecimate.o
 OBJS-$(CONFIG_NEGATE_FILTER)                 += vf_lut.o
 OBJS-$(CONFIG_NOFORMAT_FILTER)               += vf_format.o
@@ -160,6 +161,8 @@
 OBJS-$(CONFIG_OVERLAY_FILTER)                += vf_overlay.o dualinput.o framesync.o
 OBJS-$(CONFIG_OWDENOISE_FILTER)              += vf_owdenoise.o
 OBJS-$(CONFIG_PAD_FILTER)                    += vf_pad.o
+OBJS-$(CONFIG_PALETTEGEN_FILTER)             += vf_palettegen.o
+OBJS-$(CONFIG_PALETTEUSE_FILTER)             += vf_paletteuse.o dualinput.o framesync.o
 OBJS-$(CONFIG_PERMS_FILTER)                  += f_perms.o
 OBJS-$(CONFIG_PERSPECTIVE_FILTER)            += vf_perspective.o
 OBJS-$(CONFIG_PHASE_FILTER)                  += vf_phase.o
@@ -170,6 +173,7 @@
 OBJS-$(CONFIG_PULLUP_FILTER)                 += vf_pullup.o
 OBJS-$(CONFIG_QP_FILTER)                     += vf_qp.o
 OBJS-$(CONFIG_REMOVELOGO_FILTER)             += bbox.o lswsutils.o lavfutils.o vf_removelogo.o
+OBJS-$(CONFIG_REPEATFIELDS_FILTER)           += vf_repeatfields.o
 OBJS-$(CONFIG_ROTATE_FILTER)                 += vf_rotate.o
 OBJS-$(CONFIG_SEPARATEFIELDS_FILTER)         += vf_separatefields.o
 OBJS-$(CONFIG_SAB_FILTER)                    += vf_sab.o
@@ -192,7 +196,7 @@
 OBJS-$(CONFIG_SUBTITLES_FILTER)              += vf_subtitles.o
 OBJS-$(CONFIG_SUPER2XSAI_FILTER)             += vf_super2xsai.o
 OBJS-$(CONFIG_SWAPUV_FILTER)                 += vf_swapuv.o
-OBJS-$(CONFIG_TBLEND_FILTER)                 += vf_blend.o
+OBJS-$(CONFIG_TBLEND_FILTER)                 += vf_blend.o dualinput.o framesync.o
 OBJS-$(CONFIG_TELECINE_FILTER)               += vf_telecine.o
 OBJS-$(CONFIG_THUMBNAIL_FILTER)              += vf_thumbnail.o
 OBJS-$(CONFIG_TILE_FILTER)                   += vf_tile.o
@@ -226,16 +230,13 @@
 
 OBJS-$(CONFIG_NULLSINK_FILTER)               += vsink_nullsink.o
 
-OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/mp_image.o
-OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/img_format.o
-OBJS-$(CONFIG_MP_FILTER) += libmpcodecs/vf_softpulldown.o
-
 # multimedia filters
 OBJS-$(CONFIG_AVECTORSCOPE_FILTER)           += avf_avectorscope.o
 OBJS-$(CONFIG_CONCAT_FILTER)                 += avf_concat.o
 OBJS-$(CONFIG_SHOWCQT_FILTER)                += avf_showcqt.o
 OBJS-$(CONFIG_SHOWSPECTRUM_FILTER)           += avf_showspectrum.o
 OBJS-$(CONFIG_SHOWWAVES_FILTER)              += avf_showwaves.o
+OBJS-$(CONFIG_SHOWWAVESPIC_FILTER)           += avf_showwaves.o
 
 # multimedia sources
 OBJS-$(CONFIG_AMOVIE_FILTER)                 += src_movie.o
diff --git a/libavfilter/aeval.c b/libavfilter/aeval.c
index 45629a9..69de1f7 100644
--- a/libavfilter/aeval.c
+++ b/libavfilter/aeval.c
@@ -217,6 +217,7 @@
         eval->expr[i] = NULL;
     }
     av_freep(&eval->expr);
+    av_freep(&eval->channel_values);
 }
 
 static int config_props(AVFilterLink *outlink)
diff --git a/libavfilter/af_aphaser.c b/libavfilter/af_aphaser.c
index 9d8f696..708b568 100644
--- a/libavfilter/af_aphaser.c
+++ b/libavfilter/af_aphaser.c
@@ -37,7 +37,7 @@
     double decay;
     double speed;
 
-    enum WaveType type;
+    int type;
 
     int delay_buffer_length;
     double *delay_buffer;
diff --git a/libavfilter/af_astats.c b/libavfilter/af_astats.c
index 60ccd73..c20f84d 100644
--- a/libavfilter/af_astats.c
+++ b/libavfilter/af_astats.c
@@ -240,7 +240,8 @@
 {
     AudioStatsContext *s = ctx->priv;
 
-    print_stats(ctx);
+    if (s->nb_channels)
+        print_stats(ctx);
     av_freep(&s->chstats);
 }
 
diff --git a/libavfilter/af_biquads.c b/libavfilter/af_biquads.c
index 10de28d..91662c4 100644
--- a/libavfilter/af_biquads.c
+++ b/libavfilter/af_biquads.c
@@ -98,7 +98,7 @@
     const AVClass *class;
 
     enum FilterType filter_type;
-    enum WidthType width_type;
+    int width_type;
     int poles;
     int csg;
 
diff --git a/libavfilter/af_channelmap.c b/libavfilter/af_channelmap.c
index 2a43c12..cc66f04 100644
--- a/libavfilter/af_channelmap.c
+++ b/libavfilter/af_channelmap.c
@@ -88,13 +88,14 @@
 
 static int get_channel_idx(char **map, int *ch, char delim, int max_ch)
 {
-    char *next = split(*map, delim);
+    char *next;
     int len;
     int n = 0;
-    if (!next && delim == '-')
-        return AVERROR(EINVAL);
     if (!*map)
         return AVERROR(EINVAL);
+    next = split(*map, delim);
+    if (!next && delim == '-')
+        return AVERROR(EINVAL);
     len = strlen(*map);
     sscanf(*map, "%d%n", ch, &n);
     if (n != len)
diff --git a/libavfilter/af_dcshift.c b/libavfilter/af_dcshift.c
new file mode 100644
index 0000000..c1abb3c
--- /dev/null
+++ b/libavfilter/af_dcshift.c
@@ -0,0 +1,164 @@
+/*
+ * Copyright (c) 2000 Chris Ausbrooks <weed@bucket.pp.ualr.edu>
+ * Copyright (c) 2000 Fabien COELHO <fabien@coelho.net>
+ *
+ * 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/opt.h"
+#include "libavutil/samplefmt.h"
+#include "avfilter.h"
+#include "audio.h"
+#include "internal.h"
+
+typedef struct DCShiftContext {
+    const AVClass *class;
+    double dcshift;
+    double limiterthreshhold;
+    double limitergain;
+} DCShiftContext;
+
+#define OFFSET(x) offsetof(DCShiftContext, x)
+#define A AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
+
+static const AVOption dcshift_options[] = {
+    { "shift",       "set DC shift",     OFFSET(dcshift),       AV_OPT_TYPE_DOUBLE, {.dbl=0}, -1, 1, A },
+    { "limitergain", "set limiter gain", OFFSET(limitergain), AV_OPT_TYPE_DOUBLE, {.dbl=0}, 0, 1, A },
+    { NULL }
+};
+
+AVFILTER_DEFINE_CLASS(dcshift);
+
+static av_cold int init(AVFilterContext *ctx)
+{
+    DCShiftContext *s = ctx->priv;
+
+    s->limiterthreshhold = INT32_MAX * (1.0 - (fabs(s->dcshift) - s->limitergain));
+
+    return 0;
+}
+
+static int query_formats(AVFilterContext *ctx)
+{
+    AVFilterChannelLayouts *layouts;
+    AVFilterFormats *formats;
+    static const enum AVSampleFormat sample_fmts[] = {
+        AV_SAMPLE_FMT_S32P, AV_SAMPLE_FMT_NONE
+    };
+
+    layouts = ff_all_channel_layouts();
+    if (!layouts)
+        return AVERROR(ENOMEM);
+    ff_set_common_channel_layouts(ctx, layouts);
+
+    formats = ff_make_format_list(sample_fmts);
+    if (!formats)
+        return AVERROR(ENOMEM);
+    ff_set_common_formats(ctx, formats);
+
+    formats = ff_all_samplerates();
+    if (!formats)
+        return AVERROR(ENOMEM);
+    ff_set_common_samplerates(ctx, formats);
+
+    return 0;
+}
+
+static int filter_frame(AVFilterLink *inlink, AVFrame *in)
+{
+    AVFilterContext *ctx = inlink->dst;
+    AVFilterLink *outlink = ctx->outputs[0];
+    AVFrame *out = ff_get_audio_buffer(inlink, in->nb_samples);
+    DCShiftContext *s = ctx->priv;
+    int i, j;
+    double dcshift = s->dcshift;
+
+    if (!out) {
+        av_frame_free(&in);
+        return AVERROR(ENOMEM);
+    }
+    av_frame_copy_props(out, in);
+
+    if (s->limitergain > 0) {
+        for (i = 0; i < inlink->channels; i++) {
+            const int32_t *src = (int32_t *)in->extended_data[i];
+            int32_t *dst = (int32_t *)out->extended_data[i];
+
+            for (j = 0; j < in->nb_samples; j++) {
+                double d;
+
+                d = src[j];
+
+                if (d > s->limiterthreshhold && dcshift > 0) {
+                    d = (d - s->limiterthreshhold) * s->limitergain /
+                             (INT32_MAX - s->limiterthreshhold) +
+                             s->limiterthreshhold + dcshift;
+                } else if (d < -s->limiterthreshhold && dcshift < 0) {
+                    d = (d + s->limiterthreshhold) * s->limitergain /
+                             (INT32_MAX - s->limiterthreshhold) -
+                             s->limiterthreshhold + dcshift;
+                } else {
+                    d = dcshift * INT32_MAX + d;
+                }
+
+                dst[j] = av_clipl_int32(d);
+            }
+        }
+    } else {
+        for (i = 0; i < inlink->channels; i++) {
+            const int32_t *src = (int32_t *)in->extended_data[i];
+            int32_t *dst = (int32_t *)out->extended_data[i];
+
+            for (j = 0; j < in->nb_samples; j++) {
+                double d = dcshift * (INT32_MAX + 1.) + src[j];
+
+                dst[j] = av_clipl_int32(d);
+            }
+        }
+    }
+
+    av_frame_free(&in);
+    return ff_filter_frame(outlink, out);
+}
+static const AVFilterPad dcshift_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_AUDIO,
+        .filter_frame = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad dcshift_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_AUDIO,
+    },
+    { NULL }
+};
+
+AVFilter ff_af_dcshift = {
+    .name           = "dcshift",
+    .description    = NULL_IF_CONFIG_SMALL("Apply a DC shift to the audio."),
+    .query_formats  = query_formats,
+    .priv_size      = sizeof(DCShiftContext),
+    .priv_class     = &dcshift_class,
+    .init           = init,
+    .inputs         = dcshift_inputs,
+    .outputs        = dcshift_outputs,
+    .flags          = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
+};
diff --git a/libavfilter/af_volume.c b/libavfilter/af_volume.c
index 4809ae7..8d49c65 100644
--- a/libavfilter/af_volume.c
+++ b/libavfilter/af_volume.c
@@ -402,7 +402,8 @@
     }
 
     /* do volume scaling in-place if input buffer is writable */
-    if (av_frame_is_writable(buf)) {
+    if (av_frame_is_writable(buf)
+            && (vol->precision != PRECISION_FIXED || vol->volume_i > 0)) {
         out_buf = buf;
     } else {
         out_buf = ff_get_audio_buffer(inlink, nb_samples);
diff --git a/libavfilter/af_volume.h b/libavfilter/af_volume.h
index 53a328e..aff7526 100644
--- a/libavfilter/af_volume.h
+++ b/libavfilter/af_volume.h
@@ -68,13 +68,13 @@
 typedef struct VolumeContext {
     const AVClass *class;
     AVFloatDSPContext *fdsp;
-    enum PrecisionType precision;
-    enum EvalMode eval_mode;
+    int precision;
+    int eval_mode;
     const char *volume_expr;
     AVExpr *volume_pexpr;
     double var_values[VAR_VARS_NB];
 
-    enum ReplayGainType replaygain;
+    int replaygain;
     double replaygain_preamp;
     int    replaygain_noclip;
     double volume;
diff --git a/libavfilter/allfilters.c b/libavfilter/allfilters.c
index f4af8ec..0288082 100644
--- a/libavfilter/allfilters.c
+++ b/libavfilter/allfilters.c
@@ -81,6 +81,7 @@
     REGISTER_FILTER(CHANNELMAP,     channelmap,     af);
     REGISTER_FILTER(CHANNELSPLIT,   channelsplit,   af);
     REGISTER_FILTER(COMPAND,        compand,        af);
+    REGISTER_FILTER(DCSHIFT,        dcshift,        af);
     REGISTER_FILTER(EARWAX,         earwax,         af);
     REGISTER_FILTER(EBUR128,        ebur128,        af);
     REGISTER_FILTER(EQUALIZER,      equalizer,      af);
@@ -135,6 +136,7 @@
     REGISTER_FILTER(EQ,             eq,             vf);
     REGISTER_FILTER(EXTRACTPLANES,  extractplanes,  vf);
     REGISTER_FILTER(FADE,           fade,           vf);
+    REGISTER_FILTER(FFTFILT,        fftfilt,        vf);
     REGISTER_FILTER(FIELD,          field,          vf);
     REGISTER_FILTER(FIELDMATCH,     fieldmatch,     vf);
     REGISTER_FILTER(FIELDORDER,     fieldorder,     vf);
@@ -165,7 +167,6 @@
     REGISTER_FILTER(LUTYUV,         lutyuv,         vf);
     REGISTER_FILTER(MCDEINT,        mcdeint,        vf);
     REGISTER_FILTER(MERGEPLANES,    mergeplanes,    vf);
-    REGISTER_FILTER(MP,             mp,             vf);
     REGISTER_FILTER(MPDECIMATE,     mpdecimate,     vf);
     REGISTER_FILTER(NEGATE,         negate,         vf);
     REGISTER_FILTER(NOFORMAT,       noformat,       vf);
@@ -175,6 +176,8 @@
     REGISTER_FILTER(OVERLAY,        overlay,        vf);
     REGISTER_FILTER(OWDENOISE,      owdenoise,      vf);
     REGISTER_FILTER(PAD,            pad,            vf);
+    REGISTER_FILTER(PALETTEGEN,     palettegen,     vf);
+    REGISTER_FILTER(PALETTEUSE,     paletteuse,     vf);
     REGISTER_FILTER(PERMS,          perms,          vf);
     REGISTER_FILTER(PERSPECTIVE,    perspective,    vf);
     REGISTER_FILTER(PHASE,          phase,          vf);
@@ -185,6 +188,7 @@
     REGISTER_FILTER(PULLUP,         pullup,         vf);
     REGISTER_FILTER(QP,             qp,             vf);
     REGISTER_FILTER(REMOVELOGO,     removelogo,     vf);
+    REGISTER_FILTER(REPEATFIELDS,   repeatfields,   vf);
     REGISTER_FILTER(ROTATE,         rotate,         vf);
     REGISTER_FILTER(SAB,            sab,            vf);
     REGISTER_FILTER(SCALE,          scale,          vf);
@@ -247,6 +251,7 @@
     REGISTER_FILTER(SHOWCQT,        showcqt,        avf);
     REGISTER_FILTER(SHOWSPECTRUM,   showspectrum,   avf);
     REGISTER_FILTER(SHOWWAVES,      showwaves,      avf);
+    REGISTER_FILTER(SHOWWAVESPIC,   showwavespic,   avf);
 
     /* multimedia sources */
     REGISTER_FILTER(AMOVIE,         amovie,         avsrc);
diff --git a/libavfilter/avf_avectorscope.c b/libavfilter/avf_avectorscope.c
index 1b5365a..3027de3 100644
--- a/libavfilter/avf_avectorscope.c
+++ b/libavfilter/avf_avectorscope.c
@@ -44,7 +44,7 @@
     AVFrame *outpicref;
     int w, h;
     int hw, hh;
-    enum VectorScopeMode mode;
+    int mode;
     int contrast[3];
     int fade[3];
     double zoom;
diff --git a/libavfilter/avf_showspectrum.c b/libavfilter/avf_showspectrum.c
index 24116da..49491b6 100644
--- a/libavfilter/avf_showspectrum.c
+++ b/libavfilter/avf_showspectrum.c
@@ -48,16 +48,16 @@
     int nb_display_channels;
     int channel_height;
     int sliding;                ///< 1 if sliding mode, 0 otherwise
-    enum DisplayMode mode;      ///< channel display mode
-    enum ColorMode color_mode;  ///< display color scheme
-    enum DisplayScale scale;
+    int mode;                   ///< channel display mode
+    int color_mode;             ///< display color scheme
+    int scale;
     float saturation;           ///< color saturation multiplier
     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)
     FFTSample **rdft_data;      ///< bins holder for each (displayed) channels
     float *window_func_lut;     ///< Window function LUT
-    enum WindowFunc win_func;
+    int win_func;
     float *combine_buffer;      ///< color combining buffer (3 * h items)
 } ShowSpectrumContext;
 
diff --git a/libavfilter/avf_showwaves.c b/libavfilter/avf_showwaves.c
index cffa883..57a6b2e 100644
--- a/libavfilter/avf_showwaves.c
+++ b/libavfilter/avf_showwaves.c
@@ -23,6 +23,7 @@
  * audio to video multimedia filter
  */
 
+#include "libavutil/avassert.h"
 #include "libavutil/channel_layout.h"
 #include "libavutil/opt.h"
 #include "libavutil/parseutils.h"
@@ -40,6 +41,11 @@
     MODE_NB,
 };
 
+struct frame_node {
+    AVFrame *frame;
+    struct frame_node *next;
+};
+
 typedef struct {
     const AVClass *class;
     int w, h;
@@ -50,10 +56,17 @@
     int req_fullfilled;
     int n;
     int sample_count_mod;
-    enum ShowWavesMode mode;
+    int mode;                   ///< ShowWavesMode
     int split_channels;
     void (*draw_sample)(uint8_t *buf, int height, int linesize,
                         int16_t sample, int16_t *prev_y, int intensity);
+
+    /* single picture */
+    int single_pic;
+    struct frame_node *audio_frames;
+    struct frame_node *last_frame;
+    int64_t total_samples;
+    int64_t *sum; /* abs sum of the samples per channel */
 } ShowWavesContext;
 
 #define OFFSET(x) offsetof(ShowWavesContext, x)
@@ -82,6 +95,19 @@
 
     av_frame_free(&showwaves->outpicref);
     av_freep(&showwaves->buf_idy);
+
+    if (showwaves->single_pic) {
+        struct frame_node *node = showwaves->audio_frames;
+        while (node) {
+            struct frame_node *tmp = node;
+
+            node = node->next;
+            av_frame_free(&tmp->frame);
+            av_freep(&tmp);
+        }
+        av_freep(&showwaves->sum);
+        showwaves->last_frame = NULL;
+    }
 }
 
 static int query_formats(AVFilterContext *ctx)
@@ -162,6 +188,55 @@
     return ret;
 }
 
+static int push_single_pic(AVFilterLink *outlink)
+{
+    AVFilterContext *ctx = outlink->src;
+    AVFilterLink *inlink = ctx->inputs[0];
+    ShowWavesContext *showwaves = ctx->priv;
+    int64_t n = 0, max_samples = showwaves->total_samples / outlink->w;
+    AVFrame *out = showwaves->outpicref;
+    struct frame_node *node;
+    const int nb_channels = inlink->channels;
+    const int x = 255 / (showwaves->split_channels ? 1 : nb_channels);
+    const int ch_height = showwaves->split_channels ? outlink->h / nb_channels : outlink->h;
+    const int linesize = out->linesize[0];
+    int col = 0;
+    int64_t *sum = showwaves->sum;
+
+    av_log(ctx, AV_LOG_DEBUG, "Create frame averaging %"PRId64" samples per column\n", max_samples);
+
+    memset(sum, 0, nb_channels);
+
+    for (node = showwaves->audio_frames; node; node = node->next) {
+        int i;
+        const AVFrame *frame = node->frame;
+        const int16_t *p = (const int16_t *)frame->data[0];
+
+        for (i = 0; i < frame->nb_samples; i++) {
+            int ch;
+
+            for (ch = 0; ch < nb_channels; ch++)
+                sum[ch] += abs(p[ch + i*nb_channels]) << 1;
+            if (n++ == max_samples) {
+                for (ch = 0; ch < nb_channels; ch++) {
+                    int16_t sample = sum[ch] / max_samples;
+                    uint8_t *buf = out->data[0] + col;
+                    if (showwaves->split_channels)
+                        buf += ch*ch_height*linesize;
+                    av_assert0(col < outlink->w);
+                    showwaves->draw_sample(buf, ch_height, linesize, sample, &showwaves->buf_idy[ch], x);
+                    sum[ch] = 0;
+                }
+                col++;
+                n = 0;
+            }
+        }
+    }
+
+    return push_frame(outlink);
+}
+
+
 static int request_frame(AVFilterLink *outlink)
 {
     ShowWavesContext *showwaves = outlink->src->priv;
@@ -173,8 +248,13 @@
         ret = ff_request_frame(inlink);
     } while (!showwaves->req_fullfilled && ret >= 0);
 
-    if (ret == AVERROR_EOF && showwaves->outpicref)
-        push_frame(outlink);
+    if (ret == AVERROR_EOF && showwaves->outpicref) {
+        if (showwaves->single_pic)
+            push_single_pic(outlink);
+        else
+            push_frame(outlink);
+    }
+
     return ret;
 }
 
@@ -229,14 +309,56 @@
         buf[k * linesize] += intensity;
 }
 
-static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
+static int alloc_out_frame(ShowWavesContext *showwaves, const int16_t *p,
+                           const AVFilterLink *inlink, AVFilterLink *outlink,
+                           const AVFrame *in)
+{
+    if (!showwaves->outpicref) {
+        int j;
+        AVFrame *out = showwaves->outpicref =
+            ff_get_video_buffer(outlink, outlink->w, outlink->h);
+        if (!out)
+            return AVERROR(ENOMEM);
+        out->width  = outlink->w;
+        out->height = outlink->h;
+        out->pts = in->pts + av_rescale_q((p - (int16_t *)in->data[0]) / inlink->channels,
+                                          av_make_q(1, inlink->sample_rate),
+                                          outlink->time_base);
+        for (j = 0; j < outlink->h; j++)
+            memset(out->data[0] + j*out->linesize[0], 0, outlink->w);
+    }
+    return 0;
+}
+
+static av_cold int init(AVFilterContext *ctx)
+{
+    ShowWavesContext *showwaves = ctx->priv;
+
+    if (!strcmp(ctx->filter->name, "showwavespic")) {
+        showwaves->single_pic = 1;
+        showwaves->mode = MODE_CENTERED_LINE;
+    }
+
+    switch (showwaves->mode) {
+    case MODE_POINT:         showwaves->draw_sample = draw_sample_point; break;
+    case MODE_LINE:          showwaves->draw_sample = draw_sample_line;  break;
+    case MODE_P2P:           showwaves->draw_sample = draw_sample_p2p;   break;
+    case MODE_CENTERED_LINE: showwaves->draw_sample = draw_sample_cline; break;
+    default:
+        return AVERROR_BUG;
+    }
+    return 0;
+}
+
+#if CONFIG_SHOWWAVES_FILTER
+
+static int showwaves_filter_frame(AVFilterLink *inlink, AVFrame *insamples)
 {
     AVFilterContext *ctx = inlink->dst;
     AVFilterLink *outlink = ctx->outputs[0];
     ShowWavesContext *showwaves = ctx->priv;
     const int nb_samples = insamples->nb_samples;
     AVFrame *outpicref = showwaves->outpicref;
-    int linesize = outpicref ? outpicref->linesize[0] : 0;
     int16_t *p = (int16_t *)insamples->data[0];
     int nb_channels = inlink->channels;
     int i, j, ret = 0;
@@ -246,23 +368,15 @@
 
     /* draw data in the buffer */
     for (i = 0; i < nb_samples; i++) {
-        if (!showwaves->outpicref) {
-            showwaves->outpicref = outpicref =
-                ff_get_video_buffer(outlink, outlink->w, outlink->h);
-            if (!outpicref)
-                return AVERROR(ENOMEM);
-            outpicref->width  = outlink->w;
-            outpicref->height = outlink->h;
-            outpicref->pts = insamples->pts +
-                             av_rescale_q((p - (int16_t *)insamples->data[0]) / nb_channels,
-                                          (AVRational){ 1, inlink->sample_rate },
-                                          outlink->time_base);
-            linesize = outpicref->linesize[0];
-            for (j = 0; j < outlink->h; j++)
-                memset(outpicref->data[0] + j * linesize, 0, outlink->w);
-        }
+
+        ret = alloc_out_frame(showwaves, p, inlink, outlink, insamples);
+        if (ret < 0)
+            goto end;
+        outpicref = showwaves->outpicref;
+
         for (j = 0; j < nb_channels; j++) {
             uint8_t *buf = outpicref->data[0] + showwaves->buf_idx;
+            const int linesize = outpicref->linesize[0];
             if (showwaves->split_channels)
                 buf += j*ch_height*linesize;
             showwaves->draw_sample(buf, ch_height, linesize, *p++,
@@ -280,30 +394,16 @@
         outpicref = showwaves->outpicref;
     }
 
+end:
     av_frame_free(&insamples);
     return ret;
 }
 
-static av_cold int init(AVFilterContext *ctx)
-{
-    ShowWavesContext *showwaves = ctx->priv;
-
-    switch (showwaves->mode) {
-    case MODE_POINT:         showwaves->draw_sample = draw_sample_point; break;
-    case MODE_LINE:          showwaves->draw_sample = draw_sample_line;  break;
-    case MODE_P2P:           showwaves->draw_sample = draw_sample_p2p;   break;
-    case MODE_CENTERED_LINE: showwaves->draw_sample = draw_sample_cline; break;
-    default:
-        return AVERROR_BUG;
-    }
-    return 0;
-}
-
 static const AVFilterPad showwaves_inputs[] = {
     {
         .name         = "default",
         .type         = AVMEDIA_TYPE_AUDIO,
-        .filter_frame = filter_frame,
+        .filter_frame = showwaves_filter_frame,
     },
     { NULL }
 };
@@ -329,3 +429,107 @@
     .outputs       = showwaves_outputs,
     .priv_class    = &showwaves_class,
 };
+
+#endif // CONFIG_SHOWWAVES_FILTER
+
+#if CONFIG_SHOWWAVESPIC_FILTER
+
+#define OFFSET(x) offsetof(ShowWavesContext, x)
+#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
+
+static const AVOption showwavespic_options[] = {
+    { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "600x240"}, 0, 0, FLAGS },
+    { "s",    "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "600x240"}, 0, 0, FLAGS },
+    { "split_channels", "draw channels separately", OFFSET(split_channels), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, FLAGS },
+    { NULL }
+};
+
+AVFILTER_DEFINE_CLASS(showwavespic);
+
+static int showwavespic_config_input(AVFilterLink *inlink)
+{
+    AVFilterContext *ctx = inlink->dst;
+    ShowWavesContext *showwaves = ctx->priv;
+
+    if (showwaves->single_pic) {
+        showwaves->sum = av_mallocz_array(inlink->channels, sizeof(*showwaves->sum));
+        if (!showwaves->sum)
+            return AVERROR(ENOMEM);
+    }
+
+    return 0;
+}
+
+static int showwavespic_filter_frame(AVFilterLink *inlink, AVFrame *insamples)
+{
+    AVFilterContext *ctx = inlink->dst;
+    AVFilterLink *outlink = ctx->outputs[0];
+    ShowWavesContext *showwaves = ctx->priv;
+    int16_t *p = (int16_t *)insamples->data[0];
+    int ret = 0;
+
+    if (showwaves->single_pic) {
+        struct frame_node *f;
+
+        ret = alloc_out_frame(showwaves, p, inlink, outlink, insamples);
+        if (ret < 0)
+            goto end;
+
+        /* queue the audio frame */
+        f = av_malloc(sizeof(*f));
+        if (!f) {
+            ret = AVERROR(ENOMEM);
+            goto end;
+        }
+        f->frame = insamples;
+        f->next = NULL;
+        if (!showwaves->last_frame) {
+            showwaves->audio_frames =
+            showwaves->last_frame   = f;
+        } else {
+            showwaves->last_frame->next = f;
+            showwaves->last_frame = f;
+        }
+        showwaves->total_samples += insamples->nb_samples;
+
+        return 0;
+    }
+
+end:
+    av_frame_free(&insamples);
+    return ret;
+}
+
+static const AVFilterPad showwavespic_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_AUDIO,
+        .config_props = showwavespic_config_input,
+        .filter_frame = showwavespic_filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad showwavespic_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .config_props  = config_output,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
+
+AVFilter ff_avf_showwavespic = {
+    .name          = "showwavespic",
+    .description   = NULL_IF_CONFIG_SMALL("Convert input audio to a video output single picture."),
+    .init          = init,
+    .uninit        = uninit,
+    .query_formats = query_formats,
+    .priv_size     = sizeof(ShowWavesContext),
+    .inputs        = showwavespic_inputs,
+    .outputs       = showwavespic_outputs,
+    .priv_class    = &showwavespic_class,
+};
+
+#endif // CONFIG_SHOWWAVESPIC_FILTER
diff --git a/libavfilter/avfilter.c b/libavfilter/avfilter.c
index 76c60c1..bcf8d3f 100644
--- a/libavfilter/avfilter.c
+++ b/libavfilter/avfilter.c
@@ -135,7 +135,7 @@
 
     if (src->nb_outputs <= srcpad || dst->nb_inputs <= dstpad ||
         src->outputs[srcpad]      || dst->inputs[dstpad])
-        return -1;
+        return AVERROR(EINVAL);
 
     if (src->output_pads[srcpad].type != dst->input_pads[dstpad].type) {
         av_log(src, AV_LOG_ERROR,
@@ -381,7 +381,7 @@
     for (i = 0; i < link->src->nb_inputs; i++) {
         int val;
         if (!link->src->inputs[i])
-            return -1;
+            return AVERROR(EINVAL);
         val = ff_poll_frame(link->src->inputs[i]);
         min = FFMIN(min, val);
     }
@@ -965,21 +965,6 @@
                 goto fail;
 #endif
         } else {
-#if CONFIG_MP_FILTER
-            if (!strcmp(filter->filter->name, "mp")) {
-                char *escaped;
-
-                if (!strncmp(args, "filter=", 7))
-                    args += 7;
-                ret = av_escape(&escaped, args, ":=", AV_ESCAPE_MODE_BACKSLASH, 0);
-                if (ret < 0) {
-                    av_log(filter, AV_LOG_ERROR, "Unable to escape MPlayer filters arg '%s'\n", args);
-                    goto fail;
-                }
-                ret = process_options(filter, &options, escaped);
-                av_free(escaped);
-            } else
-#endif
             ret = process_options(filter, &options, args);
             if (ret < 0)
                 goto fail;
diff --git a/libavfilter/avfilter.h b/libavfilter/avfilter.h
index d296536..296f2d3 100644
--- a/libavfilter/avfilter.h
+++ b/libavfilter/avfilter.h
@@ -1245,6 +1245,8 @@
 
 /**
  * Allocate a filter graph.
+ *
+ * @return the allocated filter graph on success or NULL.
  */
 AVFilterGraph *avfilter_graph_alloc(void);
 
diff --git a/libavfilter/avfiltergraph.c b/libavfilter/avfiltergraph.c
index a859ecb..2e69cdd 100644
--- a/libavfilter/avfiltergraph.c
+++ b/libavfilter/avfiltergraph.c
@@ -1280,6 +1280,8 @@
 {
     AVFilterLink **links = graph->sink_links;
 
+    av_assert0(index >= 0);
+
     while (index) {
         int parent = (index - 1) >> 1;
         if (links[parent]->current_pts >= link->current_pts)
@@ -1297,6 +1299,8 @@
 {
     AVFilterLink **links = graph->sink_links;
 
+    av_assert0(index >= 0);
+
     while (1) {
         int child = 2 * index + 1;
         if (child >= graph->sink_links_count)
diff --git a/libavfilter/buffer.c b/libavfilter/buffer.c
index 43dc669..a5b3b1d 100644
--- a/libavfilter/buffer.c
+++ b/libavfilter/buffer.c
@@ -42,13 +42,19 @@
     av_free(ptr);
 }
 
-static void copy_video_props(AVFilterBufferRefVideoProps *dst, AVFilterBufferRefVideoProps *src) {
+static int copy_video_props(AVFilterBufferRefVideoProps *dst, AVFilterBufferRefVideoProps *src) {
     *dst = *src;
     if (src->qp_table) {
         int qsize = src->qp_table_size;
         dst->qp_table = av_malloc(qsize);
+        if (!dst->qp_table) {
+            av_log(NULL, AV_LOG_ERROR, "Failed to allocate qp_table\n");
+            dst->qp_table_size = 0;
+            return AVERROR(ENOMEM);
+        }
         memcpy(dst->qp_table, src->qp_table, qsize);
     }
+    return 0;
 }
 
 AVFilterBufferRef *avfilter_ref_buffer(AVFilterBufferRef *ref, int pmask)
diff --git a/libavfilter/f_perms.c b/libavfilter/f_perms.c
index 188ce91..abe2e4f 100644
--- a/libavfilter/f_perms.c
+++ b/libavfilter/f_perms.c
@@ -37,7 +37,7 @@
     const AVClass *class;
     AVLFG lfg;
     int64_t random_seed;
-    enum mode mode;
+    int mode;
 } PermsContext;
 
 #define OFFSET(x) offsetof(PermsContext, x)
diff --git a/libavfilter/f_select.c b/libavfilter/f_select.c
index 546a940..3e7cf78 100644
--- a/libavfilter/f_select.c
+++ b/libavfilter/f_select.c
@@ -416,11 +416,18 @@
     if (!select->do_scene_detect) {
         return ff_default_query_formats(ctx);
     } else {
+        int ret;
         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));
+        AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+
+        if (!fmts_list)
+            return AVERROR(ENOMEM);
+        ret = ff_set_common_formats(ctx, fmts_list);
+        if (ret < 0)
+            return ret;
     }
     return 0;
 }
diff --git a/libavfilter/f_sendcmd.c b/libavfilter/f_sendcmd.c
index 20d9fd1..7cb958b 100644
--- a/libavfilter/f_sendcmd.c
+++ b/libavfilter/f_sendcmd.c
@@ -318,6 +318,9 @@
     *intervals = NULL;
     *nb_intervals = 0;
 
+    if (!buf)
+        return 0;
+
     while (1) {
         Interval interval;
 
@@ -373,9 +376,9 @@
     SendCmdContext *sendcmd = ctx->priv;
     int ret, i, j;
 
-    if (sendcmd->commands_filename && sendcmd->commands_str) {
+    if ((!!sendcmd->commands_filename + !!sendcmd->commands_str) != 1) {
         av_log(ctx, AV_LOG_ERROR,
-               "Only one of the filename or commands options must be specified\n");
+               "One and only one of the filename or commands options must be specified\n");
         return AVERROR(EINVAL);
     }
 
@@ -403,6 +406,11 @@
                                sendcmd->commands_str, ctx)) < 0)
         return ret;
 
+    if (sendcmd->nb_intervals == 0) {
+        av_log(ctx, AV_LOG_ERROR, "No commands were specified\n");
+        return AVERROR(EINVAL);
+    }
+
     qsort(sendcmd->intervals, sendcmd->nb_intervals, sizeof(Interval), cmp_intervals);
 
     av_log(ctx, AV_LOG_DEBUG, "Parsed commands:\n");
diff --git a/libavfilter/formats.c b/libavfilter/formats.c
index eb3b87a..4f9773b 100644
--- a/libavfilter/formats.c
+++ b/libavfilter/formats.c
@@ -262,18 +262,6 @@
     return 0;
 }
 
-#define COPY_INT_LIST(list_copy, list, type) {                          \
-    int count = 0;                                                      \
-    if (list)                                                           \
-        for (count = 0; list[count] != -1; count++)                     \
-            ;                                                           \
-    list_copy = av_calloc(count+1, sizeof(type));                       \
-    if (list_copy) {                                                    \
-        memcpy(list_copy, list, sizeof(type) * count);                  \
-        list_copy[count] = -1;                                          \
-    }                                                                   \
-}
-
 #define MAKE_FORMAT_LIST(type, field, count_field)                      \
     type *formats;                                                      \
     int count = 0;                                                      \
@@ -281,12 +269,13 @@
         for (count = 0; fmts[count] != -1; count++)                     \
             ;                                                           \
     formats = av_mallocz(sizeof(*formats));                             \
-    if (!formats) return NULL;                                          \
+    if (!formats)                                                       \
+        return NULL;                                                    \
     formats->count_field = count;                                       \
     if (count) {                                                        \
         formats->field = av_malloc_array(count, sizeof(*formats->field));      \
         if (!formats->field) {                                          \
-            av_free(formats);                                           \
+            av_freep(&formats);                                         \
             return NULL;                                                \
         }                                                               \
     }
@@ -319,8 +308,8 @@
     if (!(*f) && !(*f = av_mallocz(sizeof(**f))))           \
         return AVERROR(ENOMEM);                             \
                                                             \
-    fmts = av_realloc((*f)->list,                           \
-                      sizeof(*(*f)->list) * ((*f)->nb + 1));\
+    fmts = av_realloc_array((*f)->list, (*f)->nb + 1,       \
+                            sizeof(*(*f)->list));           \
     if (!fmts) {                                            \
         if (!oldf)                                          \
             av_freep(f);                                    \
@@ -411,19 +400,26 @@
     return ret;
 }
 
-#define FORMATS_REF(f, ref)                                          \
-do {                                                                 \
-    *ref = f;                                                        \
-    f->refs = av_realloc(f->refs, sizeof(*f->refs) * ++f->refcount); \
-    f->refs[f->refcount-1] = ref;                                    \
-} while (0)
+#define FORMATS_REF(f, ref)                                                     \
+    void *tmp;                                                                  \
+                                                                                \
+    if (!ref)                                                                   \
+        return AVERROR_BUG;                                                     \
+                                                                                \
+    tmp = av_realloc_array(f->refs, sizeof(*f->refs), f->refcount + 1);         \
+    if (!tmp)                                                                   \
+        return AVERROR(ENOMEM);                                                 \
+    f->refs = tmp;                                                              \
+    f->refs[f->refcount++] = ref;                                               \
+    *ref = f;                                                                   \
+    return 0
 
-void ff_channel_layouts_ref(AVFilterChannelLayouts *f, AVFilterChannelLayouts **ref)
+int ff_channel_layouts_ref(AVFilterChannelLayouts *f, AVFilterChannelLayouts **ref)
 {
     FORMATS_REF(f, ref);
 }
 
-void ff_formats_ref(AVFilterFormats *f, AVFilterFormats **ref)
+int ff_formats_ref(AVFilterFormats *f, AVFilterFormats **ref)
 {
     FORMATS_REF(f, ref);
 }
@@ -494,18 +490,24 @@
 }
 
 #define SET_COMMON_FORMATS(ctx, fmts, in_fmts, out_fmts, ref, list) \
-if (fmts) {                                                         \
     int count = 0, i;                                               \
                                                                     \
+    if (!fmts)                                                      \
+        return AVERROR_BUG;                                         \
+                                                                    \
     for (i = 0; i < ctx->nb_inputs; i++) {                          \
         if (ctx->inputs[i] && !ctx->inputs[i]->out_fmts) {          \
-            ref(fmts, &ctx->inputs[i]->out_fmts);                   \
+            int ret = ref(fmts, &ctx->inputs[i]->out_fmts);         \
+            if (ret < 0)                                            \
+                return ret;                                         \
             count++;                                                \
         }                                                           \
     }                                                               \
     for (i = 0; i < ctx->nb_outputs; i++) {                         \
         if (ctx->outputs[i] && !ctx->outputs[i]->in_fmts) {         \
-            ref(fmts, &ctx->outputs[i]->in_fmts);                   \
+            int ret = ref(fmts, &ctx->outputs[i]->in_fmts);         \
+            if (ret < 0)                                            \
+                return ret;                                         \
             count++;                                                \
         }                                                           \
     }                                                               \
@@ -515,17 +517,18 @@
         av_freep(&fmts->refs);                                      \
         av_freep(&fmts);                                            \
     }                                                               \
-}
+                                                                    \
+    return 0;
 
-void ff_set_common_channel_layouts(AVFilterContext *ctx,
-                                   AVFilterChannelLayouts *layouts)
+int ff_set_common_channel_layouts(AVFilterContext *ctx,
+                                  AVFilterChannelLayouts *layouts)
 {
     SET_COMMON_FORMATS(ctx, layouts, in_channel_layouts, out_channel_layouts,
                        ff_channel_layouts_ref, channel_layouts);
 }
 
-void ff_set_common_samplerates(AVFilterContext *ctx,
-                               AVFilterFormats *samplerates)
+int ff_set_common_samplerates(AVFilterContext *ctx,
+                              AVFilterFormats *samplerates)
 {
     SET_COMMON_FORMATS(ctx, samplerates, in_samplerates, out_samplerates,
                        ff_formats_ref, formats);
@@ -536,7 +539,7 @@
  * formats. If there are no links hooked to this filter, the list of formats is
  * freed.
  */
-void ff_set_common_formats(AVFilterContext *ctx, AVFilterFormats *formats)
+int ff_set_common_formats(AVFilterContext *ctx, AVFilterFormats *formats)
 {
     SET_COMMON_FORMATS(ctx, formats, in_formats, out_formats,
                        ff_formats_ref, formats);
@@ -545,14 +548,21 @@
 static int default_query_formats_common(AVFilterContext *ctx,
                                         AVFilterChannelLayouts *(layouts)(void))
 {
+    int ret;
     enum AVMediaType type = ctx->inputs  && ctx->inputs [0] ? ctx->inputs [0]->type :
                             ctx->outputs && ctx->outputs[0] ? ctx->outputs[0]->type :
                             AVMEDIA_TYPE_VIDEO;
 
-    ff_set_common_formats(ctx, ff_all_formats(type));
+    ret = ff_set_common_formats(ctx, ff_all_formats(type));
+    if (ret < 0)
+        return ret;
     if (type == AVMEDIA_TYPE_AUDIO) {
-        ff_set_common_channel_layouts(ctx, layouts());
-        ff_set_common_samplerates(ctx, ff_all_samplerates());
+        ret = ff_set_common_channel_layouts(ctx, layouts());
+        if (ret < 0)
+            return ret;
+        ret = ff_set_common_samplerates(ctx, ff_all_samplerates());
+        if (ret < 0)
+            return ret;
     }
 
     return 0;
diff --git a/libavfilter/formats.h b/libavfilter/formats.h
index 468eac8..5a8ee5e 100644
--- a/libavfilter/formats.h
+++ b/libavfilter/formats.h
@@ -142,25 +142,25 @@
  * layouts/sample rates. If there are no links hooked to this filter, the list
  * is freed.
  */
-void ff_set_common_channel_layouts(AVFilterContext *ctx,
-                                   AVFilterChannelLayouts *layouts);
-void ff_set_common_samplerates(AVFilterContext *ctx,
-                               AVFilterFormats *samplerates);
+int ff_set_common_channel_layouts(AVFilterContext *ctx,
+                                  AVFilterChannelLayouts *layouts);
+int ff_set_common_samplerates(AVFilterContext *ctx,
+                              AVFilterFormats *samplerates);
 
 /**
  * A helper for query_formats() which sets all links to the same list of
  * formats. If there are no links hooked to this filter, the list of formats is
  * freed.
  */
-void ff_set_common_formats(AVFilterContext *ctx, AVFilterFormats *formats);
+int ff_set_common_formats(AVFilterContext *ctx, AVFilterFormats *formats);
 
 int ff_add_channel_layout(AVFilterChannelLayouts **l, uint64_t channel_layout);
 
 /**
  * Add *ref as a new reference to f.
  */
-void ff_channel_layouts_ref(AVFilterChannelLayouts *f,
-                            AVFilterChannelLayouts **ref);
+int ff_channel_layouts_ref(AVFilterChannelLayouts *f,
+                           AVFilterChannelLayouts **ref);
 
 /**
  * Remove a reference to a channel layouts list.
@@ -233,7 +233,7 @@
  *  | |____| |    | |____|
  *  |________|    |________________________
  */
-void ff_formats_ref(AVFilterFormats *formats, AVFilterFormats **ref);
+int ff_formats_ref(AVFilterFormats *formats, AVFilterFormats **ref);
 
 /**
  * If *ref is non-NULL, remove *ref as a reference to the format list
diff --git a/libavfilter/generate_wave_table.h b/libavfilter/generate_wave_table.h
index 37ea2aa..5fe297e 100644
--- a/libavfilter/generate_wave_table.h
+++ b/libavfilter/generate_wave_table.h
@@ -19,6 +19,8 @@
 #ifndef AVFILTER_GENERATE_WAVE_TABLE_H
 #define AVFILTER_GENERATE_WAVE_TABLE_H
 
+#include "libavutil/samplefmt.h"
+
 enum WaveType {
     WAVE_SIN,
     WAVE_TRI,
diff --git a/libavfilter/graphparser.c b/libavfilter/graphparser.c
index 5180bd5..dd331d1 100644
--- a/libavfilter/graphparser.c
+++ b/libavfilter/graphparser.c
@@ -62,6 +62,8 @@
     (*buf)++;
 
     name = av_get_token(buf, "]");
+    if (!name)
+        goto fail;
 
     if (!name[0]) {
         av_log(log_ctx, AV_LOG_ERROR,
diff --git a/libavfilter/lavfutils.c b/libavfilter/lavfutils.c
index 80310d2..75e68a7 100644
--- a/libavfilter/lavfutils.c
+++ b/libavfilter/lavfutils.c
@@ -96,7 +96,7 @@
     av_free_packet(&pkt);
     avcodec_close(codec_ctx);
     avformat_close_input(&format_ctx);
-    av_freep(&frame);
+    av_frame_free(&frame);
 
     if (ret < 0)
         av_log(log_ctx, AV_LOG_ERROR, "Error loading image file '%s'\n", filename);
diff --git a/libavfilter/libmpcodecs/cpudetect.h b/libavfilter/libmpcodecs/cpudetect.h
deleted file mode 100644
index 710f6e6..0000000
--- a/libavfilter/libmpcodecs/cpudetect.h
+++ /dev/null
@@ -1,60 +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.
- */
-
-#ifndef MPLAYER_CPUDETECT_H
-#define MPLAYER_CPUDETECT_H
-
-#define CPUTYPE_I386    3
-#define CPUTYPE_I486    4
-#define CPUTYPE_I586    5
-#define CPUTYPE_I686    6
-
-#include "libavutil/x86_cpu.h"
-
-typedef struct cpucaps_s {
-    int cpuType;
-    int cpuModel;
-    int cpuStepping;
-    int hasMMX;
-    int hasMMX2;
-    int has3DNow;
-    int has3DNowExt;
-    int hasSSE;
-    int hasSSE2;
-    int hasSSE3;
-    int hasSSSE3;
-    int hasSSE4;
-    int hasSSE42;
-    int hasSSE4a;
-    int hasAVX;
-    int isX86;
-    unsigned cl_size; /* size of cache line */
-    int hasAltiVec;
-    int hasTSC;
-} CpuCaps;
-
-extern CpuCaps ff_gCpuCaps;
-
-void ff_do_cpuid(unsigned int ax, unsigned int *p);
-
-void ff_GetCpuCaps(CpuCaps *caps);
-
-/* returned value is malloc()'ed so free() it after use */
-char *ff_GetCpuFriendlyName(unsigned int regs[], unsigned int regs2[]);
-
-#endif /* MPLAYER_CPUDETECT_H */
diff --git a/libavfilter/libmpcodecs/img_format.c b/libavfilter/libmpcodecs/img_format.c
deleted file mode 100644
index dd07f00..0000000
--- a/libavfilter/libmpcodecs/img_format.c
+++ /dev/null
@@ -1,244 +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 "config.h"
-#include "img_format.h"
-#include "stdio.h"
-#include "libavutil/bswap.h"
-
-const char *ff_vo_format_name(int format)
-{
-    static char unknown_format[20];
-    switch(format)
-    {
-    case IMGFMT_RGB1:    return "RGB 1-bit";
-    case IMGFMT_RGB4:    return "RGB 4-bit";
-    case IMGFMT_RG4B:    return "RGB 4-bit per byte";
-    case IMGFMT_RGB8:    return "RGB 8-bit";
-    case IMGFMT_RGB12:   return "RGB 12-bit";
-    case IMGFMT_RGB15:   return "RGB 15-bit";
-    case IMGFMT_RGB16:   return "RGB 16-bit";
-    case IMGFMT_RGB24:   return "RGB 24-bit";
-//  case IMGFMT_RGB32:   return "RGB 32-bit";
-    case IMGFMT_RGB48LE: return "RGB 48-bit LE";
-    case IMGFMT_RGB48BE: return "RGB 48-bit BE";
-    case IMGFMT_RGB64LE: return "RGB 64-bit LE";
-    case IMGFMT_RGB64BE: return "RGB 64-bit BE";
-    case IMGFMT_BGR1:    return "BGR 1-bit";
-    case IMGFMT_BGR4:    return "BGR 4-bit";
-    case IMGFMT_BG4B:    return "BGR 4-bit per byte";
-    case IMGFMT_BGR8:    return "BGR 8-bit";
-    case IMGFMT_BGR12:   return "BGR 12-bit";
-    case IMGFMT_BGR15:   return "BGR 15-bit";
-    case IMGFMT_BGR16:   return "BGR 16-bit";
-    case IMGFMT_BGR24:   return "BGR 24-bit";
-//  case IMGFMT_BGR32:   return "BGR 32-bit";
-    case IMGFMT_ABGR:    return "ABGR";
-    case IMGFMT_BGRA:    return "BGRA";
-    case IMGFMT_ARGB:    return "ARGB";
-    case IMGFMT_RGBA:    return "RGBA";
-    case IMGFMT_XYZ12LE: return "XYZ 36-bit LE";
-    case IMGFMT_XYZ12BE: return "XYZ 36-bit BE";
-    case IMGFMT_GBR24P:  return "Planar GBR 24-bit";
-    case IMGFMT_GBR12P:  return "Planar GBR 36-bit";
-    case IMGFMT_GBR14P:  return "Planar GBR 42-bit";
-    case IMGFMT_YVU9:    return "Planar YVU9";
-    case IMGFMT_IF09:    return "Planar IF09";
-    case IMGFMT_YV12:    return "Planar YV12";
-    case IMGFMT_I420:    return "Planar I420";
-    case IMGFMT_IYUV:    return "Planar IYUV";
-    case IMGFMT_CLPL:    return "Planar CLPL";
-    case IMGFMT_Y800:    return "Planar Y800";
-    case IMGFMT_Y8:      return "Planar Y8";
-    case IMGFMT_Y8A:     return "Planar Y8 with alpha";
-    case IMGFMT_Y16_LE:  return "Planar Y16 little-endian";
-    case IMGFMT_Y16_BE:  return "Planar Y16 big-endian";
-    case IMGFMT_420P16_LE: return "Planar 420P 16-bit little-endian";
-    case IMGFMT_420P16_BE: return "Planar 420P 16-bit big-endian";
-    case IMGFMT_420P14_LE: return "Planar 420P 14-bit little-endian";
-    case IMGFMT_420P14_BE: return "Planar 420P 14-bit big-endian";
-    case IMGFMT_420P12_LE: return "Planar 420P 12-bit little-endian";
-    case IMGFMT_420P12_BE: return "Planar 420P 12-bit big-endian";
-    case IMGFMT_420P10_LE: return "Planar 420P 10-bit little-endian";
-    case IMGFMT_420P10_BE: return "Planar 420P 10-bit big-endian";
-    case IMGFMT_420P9_LE:  return "Planar 420P 9-bit little-endian";
-    case IMGFMT_420P9_BE:  return "Planar 420P 9-bit big-endian";
-    case IMGFMT_422P16_LE: return "Planar 422P 16-bit little-endian";
-    case IMGFMT_422P16_BE: return "Planar 422P 16-bit big-endian";
-    case IMGFMT_422P14_LE: return "Planar 422P 14-bit little-endian";
-    case IMGFMT_422P14_BE: return "Planar 422P 14-bit big-endian";
-    case IMGFMT_422P12_LE: return "Planar 422P 12-bit little-endian";
-    case IMGFMT_422P12_BE: return "Planar 422P 12-bit big-endian";
-    case IMGFMT_422P10_LE: return "Planar 422P 10-bit little-endian";
-    case IMGFMT_422P10_BE: return "Planar 422P 10-bit big-endian";
-    case IMGFMT_422P9_LE:  return "Planar 422P 9-bit little-endian";
-    case IMGFMT_422P9_BE:  return "Planar 422P 9-bit big-endian";
-    case IMGFMT_444P16_LE: return "Planar 444P 16-bit little-endian";
-    case IMGFMT_444P16_BE: return "Planar 444P 16-bit big-endian";
-    case IMGFMT_444P14_LE: return "Planar 444P 14-bit little-endian";
-    case IMGFMT_444P14_BE: return "Planar 444P 14-bit big-endian";
-    case IMGFMT_444P12_LE: return "Planar 444P 12-bit little-endian";
-    case IMGFMT_444P12_BE: return "Planar 444P 12-bit big-endian";
-    case IMGFMT_444P10_LE: return "Planar 444P 10-bit little-endian";
-    case IMGFMT_444P10_BE: return "Planar 444P 10-bit big-endian";
-    case IMGFMT_444P9_LE:  return "Planar 444P 9-bit little-endian";
-    case IMGFMT_444P9_BE:  return "Planar 444P 9-bit big-endian";
-    case IMGFMT_420A: return "Planar 420P with alpha";
-    case IMGFMT_444P: return "Planar 444P";
-    case IMGFMT_444A: return "Planar 444P with alpha";
-    case IMGFMT_422P: return "Planar 422P";
-    case IMGFMT_422A: return "Planar 422P with alpha";
-    case IMGFMT_411P: return "Planar 411P";
-    case IMGFMT_440P: return "Planar 440P";
-    case IMGFMT_NV12: return "Planar NV12";
-    case IMGFMT_NV21: return "Planar NV21";
-    case IMGFMT_HM12: return "Planar NV12 Macroblock";
-    case IMGFMT_IUYV: return "Packed IUYV";
-    case IMGFMT_IY41: return "Packed IY41";
-    case IMGFMT_IYU1: return "Packed IYU1";
-    case IMGFMT_IYU2: return "Packed IYU2";
-    case IMGFMT_UYVY: return "Packed UYVY";
-    case IMGFMT_UYNV: return "Packed UYNV";
-    case IMGFMT_cyuv: return "Packed CYUV";
-    case IMGFMT_Y422: return "Packed Y422";
-    case IMGFMT_YUY2: return "Packed YUY2";
-    case IMGFMT_YUNV: return "Packed YUNV";
-    case IMGFMT_YVYU: return "Packed YVYU";
-    case IMGFMT_Y41P: return "Packed Y41P";
-    case IMGFMT_Y211: return "Packed Y211";
-    case IMGFMT_Y41T: return "Packed Y41T";
-    case IMGFMT_Y42T: return "Packed Y42T";
-    case IMGFMT_V422: return "Packed V422";
-    case IMGFMT_V655: return "Packed V655";
-    case IMGFMT_CLJR: return "Packed CLJR";
-    case IMGFMT_YUVP: return "Packed YUVP";
-    case IMGFMT_UYVP: return "Packed UYVP";
-    case IMGFMT_MPEGPES:         return "Mpeg PES";
-    case IMGFMT_ZRMJPEGNI:       return "Zoran MJPEG non-interlaced";
-    case IMGFMT_ZRMJPEGIT:       return "Zoran MJPEG top field first";
-    case IMGFMT_ZRMJPEGIB:       return "Zoran MJPEG bottom field first";
-    case IMGFMT_XVMC_MOCO_MPEG2: return "MPEG1/2 Motion Compensation";
-    case IMGFMT_XVMC_IDCT_MPEG2: return "MPEG1/2 Motion Compensation and IDCT";
-    case IMGFMT_VDPAU_MPEG1:     return "MPEG1 VDPAU acceleration";
-    case IMGFMT_VDPAU_MPEG2:     return "MPEG2 VDPAU acceleration";
-    case IMGFMT_VDPAU_H264:      return "H.264 VDPAU acceleration";
-    case IMGFMT_VDPAU_MPEG4:     return "MPEG-4 Part 2 VDPAU acceleration";
-    case IMGFMT_VDPAU_WMV3:      return "WMV3 VDPAU acceleration";
-    case IMGFMT_VDPAU_VC1:       return "VC1 VDPAU acceleration";
-    }
-    snprintf(unknown_format,20,"Unknown 0x%04x",format);
-    return unknown_format;
-}
-
-int ff_mp_get_chroma_shift(int format, int *x_shift, int *y_shift, int *component_bits)
-{
-    int xs = 0, ys = 0;
-    int bpp;
-    int err = 0;
-    int bits = 8;
-    if ((format & 0xff0000f0) == 0x34000050)
-        format = av_bswap32(format);
-    if ((format & 0xf00000ff) == 0x50000034) {
-        switch (format >> 24) {
-        case 0x50:
-            break;
-        case 0x51:
-            bits = 16;
-            break;
-        case 0x52:
-            bits = 10;
-            break;
-        case 0x53:
-            bits = 9;
-            break;
-        default:
-            err = 1;
-            break;
-        }
-        switch (format & 0x00ffffff) {
-        case 0x00343434: // 444
-            xs = 0;
-            ys = 0;
-            break;
-        case 0x00323234: // 422
-            xs = 1;
-            ys = 0;
-            break;
-        case 0x00303234: // 420
-            xs = 1;
-            ys = 1;
-            break;
-        case 0x00313134: // 411
-            xs = 2;
-            ys = 0;
-            break;
-        case 0x00303434: // 440
-            xs = 0;
-            ys = 1;
-            break;
-        default:
-            err = 1;
-            break;
-        }
-    } else switch (format) {
-    case IMGFMT_444A:
-        xs = 0;
-        ys = 0;
-        break;
-    case IMGFMT_422A:
-        xs = 1;
-        ys = 0;
-        break;
-    case IMGFMT_420A:
-    case IMGFMT_I420:
-    case IMGFMT_IYUV:
-    case IMGFMT_YV12:
-        xs = 1;
-        ys = 1;
-        break;
-    case IMGFMT_IF09:
-    case IMGFMT_YVU9:
-        xs = 2;
-        ys = 2;
-        break;
-    case IMGFMT_Y8:
-    case IMGFMT_Y800:
-        xs = 31;
-        ys = 31;
-        break;
-    case IMGFMT_NV12:
-    case IMGFMT_NV21:
-        xs = 1;
-        ys = 1;
-        // TODO: allowing this though currently breaks
-        // things all over the place.
-        err = 1;
-        break;
-    default:
-        err = 1;
-        break;
-    }
-    if (x_shift) *x_shift = xs;
-    if (y_shift) *y_shift = ys;
-    if (component_bits) *component_bits = bits;
-    bpp = 8 + ((16 >> xs) >> ys);
-    if (format == IMGFMT_420A || format == IMGFMT_422A || format == IMGFMT_444A)
-        bpp += 8;
-    bpp *= (bits + 7) >> 3;
-    return err ? 0 : bpp;
-}
diff --git a/libavfilter/libmpcodecs/img_format.h b/libavfilter/libmpcodecs/img_format.h
deleted file mode 100644
index b5c0b90..0000000
--- a/libavfilter/libmpcodecs/img_format.h
+++ /dev/null
@@ -1,309 +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.
- */
-
-#ifndef MPLAYER_IMG_FORMAT_H
-#define MPLAYER_IMG_FORMAT_H
-
-#include "config.h"
-
-/* RGB/BGR Formats */
-
-#define IMGFMT_RGB_MASK 0xFFFFFF00
-#define IMGFMT_RGB (('R'<<24)|('G'<<16)|('B'<<8))
-#define IMGFMT_RGB1  (IMGFMT_RGB|1)
-#define IMGFMT_RGB4  (IMGFMT_RGB|4)
-#define IMGFMT_RGB4_CHAR  (IMGFMT_RGB|4|128) // RGB4 with 1 pixel per byte
-#define IMGFMT_RGB8  (IMGFMT_RGB|8)
-#define IMGFMT_RGB12 (IMGFMT_RGB|12)
-#define IMGFMT_RGB15 (IMGFMT_RGB|15)
-#define IMGFMT_RGB16 (IMGFMT_RGB|16)
-#define IMGFMT_RGB24 (IMGFMT_RGB|24)
-#define IMGFMT_RGB32 (IMGFMT_RGB|32)
-#define IMGFMT_RGB48LE (IMGFMT_RGB|48)
-#define IMGFMT_RGB48BE (IMGFMT_RGB|48|128)
-#define IMGFMT_RGB64LE (IMGFMT_RGB|64)
-#define IMGFMT_RGB64BE (IMGFMT_RGB|64|128)
-
-#define IMGFMT_BGR_MASK 0xFFFFFF00
-#define IMGFMT_BGR (('B'<<24)|('G'<<16)|('R'<<8))
-#define IMGFMT_BGR1  (IMGFMT_BGR|1)
-#define IMGFMT_BGR4  (IMGFMT_BGR|4)
-#define IMGFMT_BGR4_CHAR (IMGFMT_BGR|4|128) // BGR4 with 1 pixel per byte
-#define IMGFMT_BGR8  (IMGFMT_BGR|8)
-#define IMGFMT_BGR12 (IMGFMT_BGR|12)
-#define IMGFMT_BGR15 (IMGFMT_BGR|15)
-#define IMGFMT_BGR16 (IMGFMT_BGR|16)
-#define IMGFMT_BGR24 (IMGFMT_BGR|24)
-#define IMGFMT_BGR32 (IMGFMT_BGR|32)
-
-#define IMGFMT_XYZ_MASK 0xFFFFFF00
-#define IMGFMT_XYZ (('X'<<24)|('Y'<<16)|('Z'<<8))
-#define IMGFMT_XYZ12LE (IMGFMT_XYZ|12)
-#define IMGFMT_XYZ12BE (IMGFMT_XYZ|12|128)
-
-#define IMGFMT_GBR24P (('G'<<24)|('B'<<16)|('R'<<8)|24)
-#define IMGFMT_GBR12PLE (('G'<<24)|('B'<<16)|('R'<<8)|36)
-#define IMGFMT_GBR12PBE (('G'<<24)|('B'<<16)|('R'<<8)|36|128)
-#define IMGFMT_GBR14PLE (('G'<<24)|('B'<<16)|('R'<<8)|42)
-#define IMGFMT_GBR14PBE (('G'<<24)|('B'<<16)|('R'<<8)|42|128)
-
-#if HAVE_BIGENDIAN
-#define IMGFMT_ABGR    IMGFMT_RGB32
-#define IMGFMT_BGRA    (IMGFMT_RGB32|128)
-#define IMGFMT_ARGB    IMGFMT_BGR32
-#define IMGFMT_RGBA    (IMGFMT_BGR32|128)
-#define IMGFMT_RGB64NE IMGFMT_RGB64BE
-#define IMGFMT_RGB48NE IMGFMT_RGB48BE
-#define IMGFMT_RGB12BE IMGFMT_RGB12
-#define IMGFMT_RGB12LE (IMGFMT_RGB12|128)
-#define IMGFMT_RGB15BE IMGFMT_RGB15
-#define IMGFMT_RGB15LE (IMGFMT_RGB15|128)
-#define IMGFMT_RGB16BE IMGFMT_RGB16
-#define IMGFMT_RGB16LE (IMGFMT_RGB16|128)
-#define IMGFMT_BGR12BE IMGFMT_BGR12
-#define IMGFMT_BGR12LE (IMGFMT_BGR12|128)
-#define IMGFMT_BGR15BE IMGFMT_BGR15
-#define IMGFMT_BGR15LE (IMGFMT_BGR15|128)
-#define IMGFMT_BGR16BE IMGFMT_BGR16
-#define IMGFMT_BGR16LE (IMGFMT_BGR16|128)
-#define IMGFMT_XYZ12  IMGFMT_XYZ12BE
-#define IMGFMT_GBR12P IMGFMT_GBR12PBE
-#define IMGFMT_GBR14P IMGFMT_GBR14PBE
-#else
-#define IMGFMT_ABGR (IMGFMT_BGR32|128)
-#define IMGFMT_BGRA IMGFMT_BGR32
-#define IMGFMT_ARGB (IMGFMT_RGB32|128)
-#define IMGFMT_RGBA IMGFMT_RGB32
-#define IMGFMT_RGB64NE IMGFMT_RGB64LE
-#define IMGFMT_RGB48NE IMGFMT_RGB48LE
-#define IMGFMT_RGB12BE (IMGFMT_RGB12|128)
-#define IMGFMT_RGB12LE IMGFMT_RGB12
-#define IMGFMT_RGB15BE (IMGFMT_RGB15|128)
-#define IMGFMT_RGB15LE IMGFMT_RGB15
-#define IMGFMT_RGB16BE (IMGFMT_RGB16|128)
-#define IMGFMT_RGB16LE IMGFMT_RGB16
-#define IMGFMT_BGR12BE (IMGFMT_BGR12|128)
-#define IMGFMT_BGR12LE IMGFMT_BGR12
-#define IMGFMT_BGR15BE (IMGFMT_BGR15|128)
-#define IMGFMT_BGR15LE IMGFMT_BGR15
-#define IMGFMT_BGR16BE (IMGFMT_BGR16|128)
-#define IMGFMT_BGR16LE IMGFMT_BGR16
-#define IMGFMT_XYZ12  IMGFMT_XYZ12LE
-#define IMGFMT_GBR12P IMGFMT_GBR12PLE
-#define IMGFMT_GBR14P IMGFMT_GBR14PLE
-#endif
-
-/* old names for compatibility */
-#define IMGFMT_RG4B  IMGFMT_RGB4_CHAR
-#define IMGFMT_BG4B  IMGFMT_BGR4_CHAR
-
-#define IMGFMT_IS_RGB(fmt) (((fmt)&IMGFMT_RGB_MASK)==IMGFMT_RGB)
-#define IMGFMT_IS_BGR(fmt) (((fmt)&IMGFMT_BGR_MASK)==IMGFMT_BGR)
-#define IMGFMT_IS_XYZ(fmt) (((fmt)&IMGFMT_XYZ_MASK)==IMGFMT_XYZ)
-
-#define IMGFMT_RGB_DEPTH(fmt) ((fmt)&0x7F)
-#define IMGFMT_BGR_DEPTH(fmt) ((fmt)&0x7F)
-#define IMGFMT_XYZ_DEPTH(fmt) ((fmt)&0x7F)
-
-
-/* Planar YUV Formats */
-
-#define IMGFMT_YVU9 0x39555659
-#define IMGFMT_IF09 0x39304649
-#define IMGFMT_YV12 0x32315659
-#define IMGFMT_I420 0x30323449
-#define IMGFMT_IYUV 0x56555949
-#define IMGFMT_CLPL 0x4C504C43
-#define IMGFMT_Y800 0x30303859
-#define IMGFMT_Y8   0x20203859
-#define IMGFMT_NV12 0x3231564E
-#define IMGFMT_NV21 0x3132564E
-#define IMGFMT_Y16_LE 0x20363159
-
-/* unofficial Planar Formats, FIXME if official 4CC exists */
-#define IMGFMT_444P 0x50343434
-#define IMGFMT_422P 0x50323234
-#define IMGFMT_411P 0x50313134
-#define IMGFMT_440P 0x50303434
-#define IMGFMT_HM12 0x32314D48
-#define IMGFMT_Y16_BE 0x59313620
-
-// Gray with alpha
-#define IMGFMT_Y8A 0x59320008
-// 4:2:0 planar with alpha
-#define IMGFMT_420A 0x41303234
-// 4:2:2 planar with alpha
-#define IMGFMT_422A 0x41323234
-// 4:4:4 planar with alpha
-#define IMGFMT_444A 0x41343434
-
-#define IMGFMT_444P16_LE 0x51343434
-#define IMGFMT_444P16_BE 0x34343451
-#define IMGFMT_444P14_LE 0x54343434
-#define IMGFMT_444P14_BE 0x34343454
-#define IMGFMT_444P12_LE 0x55343434
-#define IMGFMT_444P12_BE 0x34343455
-#define IMGFMT_444P10_LE 0x52343434
-#define IMGFMT_444P10_BE 0x34343452
-#define IMGFMT_444P9_LE  0x53343434
-#define IMGFMT_444P9_BE  0x34343453
-#define IMGFMT_422P16_LE 0x51323234
-#define IMGFMT_422P16_BE 0x34323251
-#define IMGFMT_422P14_LE 0x54323234
-#define IMGFMT_422P14_BE 0x34323254
-#define IMGFMT_422P12_LE 0x55323234
-#define IMGFMT_422P12_BE 0x34323255
-#define IMGFMT_422P10_LE 0x52323234
-#define IMGFMT_422P10_BE 0x34323252
-#define IMGFMT_422P9_LE  0x53323234
-#define IMGFMT_422P9_BE  0x34323253
-#define IMGFMT_420P16_LE 0x51303234
-#define IMGFMT_420P16_BE 0x34323051
-#define IMGFMT_420P14_LE 0x54303234
-#define IMGFMT_420P14_BE 0x34323054
-#define IMGFMT_420P12_LE 0x55303234
-#define IMGFMT_420P12_BE 0x34323055
-#define IMGFMT_420P10_LE 0x52303234
-#define IMGFMT_420P10_BE 0x34323052
-#define IMGFMT_420P9_LE  0x53303234
-#define IMGFMT_420P9_BE  0x34323053
-#if HAVE_BIGENDIAN
-#define IMGFMT_444P16 IMGFMT_444P16_BE
-#define IMGFMT_444P14 IMGFMT_444P14_BE
-#define IMGFMT_444P12 IMGFMT_444P12_BE
-#define IMGFMT_444P10 IMGFMT_444P10_BE
-#define IMGFMT_444P9  IMGFMT_444P9_BE
-#define IMGFMT_422P16 IMGFMT_422P16_BE
-#define IMGFMT_422P14 IMGFMT_422P14_BE
-#define IMGFMT_422P12 IMGFMT_422P12_BE
-#define IMGFMT_422P10 IMGFMT_422P10_BE
-#define IMGFMT_422P9  IMGFMT_422P9_BE
-#define IMGFMT_420P16 IMGFMT_420P16_BE
-#define IMGFMT_420P14 IMGFMT_420P14_BE
-#define IMGFMT_420P12 IMGFMT_420P12_BE
-#define IMGFMT_420P10 IMGFMT_420P10_BE
-#define IMGFMT_420P9  IMGFMT_420P9_BE
-#define IMGFMT_Y16    IMGFMT_Y16_BE
-#define IMGFMT_IS_YUVP16_NE(fmt) IMGFMT_IS_YUVP16_BE(fmt)
-#else
-#define IMGFMT_444P16 IMGFMT_444P16_LE
-#define IMGFMT_444P14 IMGFMT_444P14_LE
-#define IMGFMT_444P12 IMGFMT_444P12_LE
-#define IMGFMT_444P10 IMGFMT_444P10_LE
-#define IMGFMT_444P9  IMGFMT_444P9_LE
-#define IMGFMT_422P16 IMGFMT_422P16_LE
-#define IMGFMT_422P14 IMGFMT_422P14_LE
-#define IMGFMT_422P12 IMGFMT_422P12_LE
-#define IMGFMT_422P10 IMGFMT_422P10_LE
-#define IMGFMT_422P9  IMGFMT_422P9_LE
-#define IMGFMT_420P16 IMGFMT_420P16_LE
-#define IMGFMT_420P14 IMGFMT_420P14_LE
-#define IMGFMT_420P12 IMGFMT_420P12_LE
-#define IMGFMT_420P10 IMGFMT_420P10_LE
-#define IMGFMT_420P9  IMGFMT_420P9_LE
-#define IMGFMT_Y16    IMGFMT_Y16_LE
-#define IMGFMT_IS_YUVP16_NE(fmt) IMGFMT_IS_YUVP16_LE(fmt)
-#endif
-
-#define IMGFMT_IS_YUVP16_LE(fmt) (((fmt - 0x51000034) & 0xfc0000ff) == 0)
-#define IMGFMT_IS_YUVP16_BE(fmt) (((fmt - 0x34000051) & 0xff0000fc) == 0)
-#define IMGFMT_IS_YUVP16(fmt)    (IMGFMT_IS_YUVP16_LE(fmt) || IMGFMT_IS_YUVP16_BE(fmt))
-
-/**
- * \brief Find the corresponding full 16 bit format, i.e. IMGFMT_420P10_LE -> IMGFMT_420P16_LE
- * \return normalized format ID or 0 if none exists.
- */
-static inline int normalize_yuvp16(int fmt) {
-    if (IMGFMT_IS_YUVP16_LE(fmt))
-        return (fmt & 0x00ffffff) | 0x51000000;
-    if (IMGFMT_IS_YUVP16_BE(fmt))
-        return (fmt & 0xffffff00) | 0x00000051;
-    return 0;
-}
-
-/* Packed YUV Formats */
-
-#define IMGFMT_IUYV 0x56595549 // Interlaced UYVY
-#define IMGFMT_IY41 0x31435949 // Interlaced Y41P
-#define IMGFMT_IYU1 0x31555949
-#define IMGFMT_IYU2 0x32555949
-#define IMGFMT_UYVY 0x59565955
-#define IMGFMT_UYNV 0x564E5955 // Exactly same as UYVY
-#define IMGFMT_cyuv 0x76757963 // upside-down UYVY
-#define IMGFMT_Y422 0x32323459 // Exactly same as UYVY
-#define IMGFMT_YUY2 0x32595559
-#define IMGFMT_YUNV 0x564E5559 // Exactly same as YUY2
-#define IMGFMT_YVYU 0x55595659
-#define IMGFMT_Y41P 0x50313459
-#define IMGFMT_Y211 0x31313259
-#define IMGFMT_Y41T 0x54313459 // Y41P, Y lsb = transparency
-#define IMGFMT_Y42T 0x54323459 // UYVY, Y lsb = transparency
-#define IMGFMT_V422 0x32323456 // upside-down UYVY?
-#define IMGFMT_V655 0x35353656
-#define IMGFMT_CLJR 0x524A4C43
-#define IMGFMT_YUVP 0x50565559 // 10-bit YUYV
-#define IMGFMT_UYVP 0x50565955 // 10-bit UYVY
-
-/* Compressed Formats */
-#define IMGFMT_MPEGPES (('M'<<24)|('P'<<16)|('E'<<8)|('S'))
-#define IMGFMT_MJPEG (('M')|('J'<<8)|('P'<<16)|('G'<<24))
-/* Formats that are understood by zoran chips, we include
- * non-interlaced, interlaced top-first, interlaced bottom-first */
-#define IMGFMT_ZRMJPEGNI  (('Z'<<24)|('R'<<16)|('N'<<8)|('I'))
-#define IMGFMT_ZRMJPEGIT (('Z'<<24)|('R'<<16)|('I'<<8)|('T'))
-#define IMGFMT_ZRMJPEGIB (('Z'<<24)|('R'<<16)|('I'<<8)|('B'))
-
-// I think that this code could not be used by any other codec/format
-#define IMGFMT_XVMC 0x1DC70000
-#define IMGFMT_XVMC_MASK 0xFFFF0000
-#define IMGFMT_IS_XVMC(fmt) (((fmt)&IMGFMT_XVMC_MASK)==IMGFMT_XVMC)
-//these are chroma420
-#define IMGFMT_XVMC_MOCO_MPEG2 (IMGFMT_XVMC|0x02)
-#define IMGFMT_XVMC_IDCT_MPEG2 (IMGFMT_XVMC|0x82)
-
-// VDPAU specific format.
-#define IMGFMT_VDPAU               0x1DC80000
-#define IMGFMT_VDPAU_MASK          0xFFFF0000
-#define IMGFMT_IS_VDPAU(fmt)       (((fmt)&IMGFMT_VDPAU_MASK)==IMGFMT_VDPAU)
-#define IMGFMT_VDPAU_MPEG1         (IMGFMT_VDPAU|0x01)
-#define IMGFMT_VDPAU_MPEG2         (IMGFMT_VDPAU|0x02)
-#define IMGFMT_VDPAU_H264          (IMGFMT_VDPAU|0x03)
-#define IMGFMT_VDPAU_WMV3          (IMGFMT_VDPAU|0x04)
-#define IMGFMT_VDPAU_VC1           (IMGFMT_VDPAU|0x05)
-#define IMGFMT_VDPAU_MPEG4         (IMGFMT_VDPAU|0x06)
-
-#define IMGFMT_IS_HWACCEL(fmt) (IMGFMT_IS_VDPAU(fmt) || IMGFMT_IS_XVMC(fmt))
-
-typedef struct {
-    void* data;
-    int size;
-    int id;        // stream id. usually 0x1E0
-    int timestamp; // pts, 90000 Hz counter based
-} vo_mpegpes_t;
-
-const char *ff_vo_format_name(int format);
-
-/**
- * Calculates the scale shifts for the chroma planes for planar YUV
- *
- * \param component_bits bits per component
- * \return bits-per-pixel for format if successful (i.e. format is 3 or 4-planes planar YUV), 0 otherwise
- */
-int ff_mp_get_chroma_shift(int format, int *x_shift, int *y_shift, int *component_bits);
-
-#endif /* MPLAYER_IMG_FORMAT_H */
diff --git a/libavfilter/libmpcodecs/libvo/fastmemcpy.h b/libavfilter/libmpcodecs/libvo/fastmemcpy.h
deleted file mode 100644
index 5a17d01..0000000
--- a/libavfilter/libmpcodecs/libvo/fastmemcpy.h
+++ /dev/null
@@ -1,99 +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 Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser 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
- */
-
-#ifndef MPLAYER_FASTMEMCPY_H
-#define MPLAYER_FASTMEMCPY_H
-
-#include <inttypes.h>
-#include <string.h>
-#include <stddef.h>
-
-void * fast_memcpy(void * to, const void * from, size_t len);
-void * mem2agpcpy(void * to, const void * from, size_t len);
-
-#if ! defined(CONFIG_FASTMEMCPY) || ! (HAVE_MMX || HAVE_MMX2 || HAVE_AMD3DNOW /* || HAVE_SSE || HAVE_SSE2 */)
-#define mem2agpcpy(a,b,c) memcpy(a,b,c)
-#define fast_memcpy(a,b,c) memcpy(a,b,c)
-#endif
-
-static inline void * mem2agpcpy_pic(void * dst, const void * src, int bytesPerLine, int height, int dstStride, int srcStride)
-{
-    int i;
-    void *retval=dst;
-
-    if(dstStride == srcStride)
-    {
-        if (srcStride < 0) {
-                src = (const uint8_t*)src + (height-1)*srcStride;
-                dst = (uint8_t*)dst + (height-1)*dstStride;
-                srcStride = -srcStride;
-        }
-
-        mem2agpcpy(dst, src, srcStride*height);
-    }
-    else
-    {
-        for(i=0; i<height; i++)
-        {
-            mem2agpcpy(dst, src, bytesPerLine);
-            src = (const uint8_t*)src + srcStride;
-            dst = (uint8_t*)dst + dstStride;
-        }
-    }
-
-    return retval;
-}
-
-#define memcpy_pic(d, s, b, h, ds, ss) memcpy_pic2(d, s, b, h, ds, ss, 0)
-#define my_memcpy_pic(d, s, b, h, ds, ss) memcpy_pic2(d, s, b, h, ds, ss, 1)
-
-/**
- * \param limit2width always skip data between end of line and start of next
- *                    instead of copying the full block when strides are the same
- */
-static inline void * memcpy_pic2(void * dst, const void * src,
-                                 int bytesPerLine, int height,
-                                 int dstStride, int srcStride, int limit2width)
-{
-    int i;
-    void *retval=dst;
-
-    if(!limit2width && dstStride == srcStride)
-    {
-        if (srcStride < 0) {
-                src = (const uint8_t*)src + (height-1)*srcStride;
-                dst = (uint8_t*)dst + (height-1)*dstStride;
-                srcStride = -srcStride;
-        }
-
-        fast_memcpy(dst, src, srcStride*height);
-    }
-    else
-    {
-        for(i=0; i<height; i++)
-        {
-            fast_memcpy(dst, src, bytesPerLine);
-            src = (const uint8_t*)src + srcStride;
-            dst = (uint8_t*)dst + dstStride;
-        }
-    }
-
-    return retval;
-}
-
-#endif /* MPLAYER_FASTMEMCPY_H */
diff --git a/libavfilter/libmpcodecs/mp_image.c b/libavfilter/libmpcodecs/mp_image.c
deleted file mode 100644
index 0e4d6d7..0000000
--- a/libavfilter/libmpcodecs/mp_image.c
+++ /dev/null
@@ -1,257 +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 "config.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#if HAVE_MALLOC_H
-#include <malloc.h>
-#endif
-
-#include "img_format.h"
-#include "mp_image.h"
-
-#include "libvo/fastmemcpy.h"
-//#include "libavutil/mem.h"
-#include "libavutil/imgutils.h"
-
-void ff_mp_image_alloc_planes(mp_image_t *mpi) {
-    uint32_t temp[256];
-    if (avpriv_set_systematic_pal2(temp, ff_mp2ff_pix_fmt(mpi->imgfmt)) >= 0)
-        mpi->flags |= MP_IMGFLAG_RGB_PALETTE;
-
-  // IF09 - allocate space for 4. plane delta info - unused
-  if (mpi->imgfmt == IMGFMT_IF09) {
-    mpi->planes[0]=av_malloc(mpi->bpp*mpi->width*(mpi->height+2)/8+
-                            mpi->chroma_width*mpi->chroma_height);
-  } else
-    mpi->planes[0]=av_malloc(mpi->bpp*mpi->width*(mpi->height+2)/8);
-  if (mpi->flags&MP_IMGFLAG_PLANAR) {
-    int bpp = IMGFMT_IS_YUVP16(mpi->imgfmt)? 2 : 1;
-    // YV12/I420/YVU9/IF09. feel free to add other planar formats here...
-    mpi->stride[0]=mpi->stride[3]=bpp*mpi->width;
-    if(mpi->num_planes > 2){
-      mpi->stride[1]=mpi->stride[2]=bpp*mpi->chroma_width;
-      if(mpi->flags&MP_IMGFLAG_SWAPPED){
-        // I420/IYUV  (Y,U,V)
-        mpi->planes[1]=mpi->planes[0]+mpi->stride[0]*mpi->height;
-        mpi->planes[2]=mpi->planes[1]+mpi->stride[1]*mpi->chroma_height;
-        if (mpi->num_planes > 3)
-            mpi->planes[3]=mpi->planes[2]+mpi->stride[2]*mpi->chroma_height;
-      } else {
-        // YV12,YVU9,IF09  (Y,V,U)
-        mpi->planes[2]=mpi->planes[0]+mpi->stride[0]*mpi->height;
-        mpi->planes[1]=mpi->planes[2]+mpi->stride[1]*mpi->chroma_height;
-        if (mpi->num_planes > 3)
-            mpi->planes[3]=mpi->planes[1]+mpi->stride[1]*mpi->chroma_height;
-      }
-    } else {
-      // NV12/NV21
-      mpi->stride[1]=mpi->chroma_width;
-      mpi->planes[1]=mpi->planes[0]+mpi->stride[0]*mpi->height;
-    }
-  } else {
-    mpi->stride[0]=mpi->width*mpi->bpp/8;
-    if (mpi->flags & MP_IMGFLAG_RGB_PALETTE) {
-      mpi->planes[1] = av_malloc(1024);
-      memcpy(mpi->planes[1], temp, 1024);
-    }
-  }
-  mpi->flags|=MP_IMGFLAG_ALLOCATED;
-}
-
-mp_image_t* ff_alloc_mpi(int w, int h, unsigned long int fmt) {
-  mp_image_t* mpi = ff_new_mp_image(w,h);
-
-  ff_mp_image_setfmt(mpi,fmt);
-  ff_mp_image_alloc_planes(mpi);
-
-  return mpi;
-}
-
-void ff_copy_mpi(mp_image_t *dmpi, mp_image_t *mpi) {
-  if(mpi->flags&MP_IMGFLAG_PLANAR){
-    memcpy_pic(dmpi->planes[0],mpi->planes[0], mpi->w, mpi->h,
-               dmpi->stride[0],mpi->stride[0]);
-    memcpy_pic(dmpi->planes[1],mpi->planes[1], mpi->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,
-               dmpi->stride[2],mpi->stride[2]);
-  } else {
-    memcpy_pic(dmpi->planes[0],mpi->planes[0],
-               mpi->w*(dmpi->bpp/8), mpi->h,
-               dmpi->stride[0],mpi->stride[0]);
-  }
-}
-
-void ff_mp_image_setfmt(mp_image_t* mpi,unsigned int out_fmt){
-    mpi->flags&=~(MP_IMGFLAG_PLANAR|MP_IMGFLAG_YUV|MP_IMGFLAG_SWAPPED);
-    mpi->imgfmt=out_fmt;
-    // compressed formats
-    if(out_fmt == IMGFMT_MPEGPES ||
-       out_fmt == IMGFMT_ZRMJPEGNI || out_fmt == IMGFMT_ZRMJPEGIT || out_fmt == IMGFMT_ZRMJPEGIB ||
-       IMGFMT_IS_HWACCEL(out_fmt)){
-        mpi->bpp=0;
-        return;
-    }
-    mpi->num_planes=1;
-    if (IMGFMT_IS_RGB(out_fmt)) {
-        if (IMGFMT_RGB_DEPTH(out_fmt) < 8 && !(out_fmt&128))
-            mpi->bpp = IMGFMT_RGB_DEPTH(out_fmt);
-        else
-            mpi->bpp=(IMGFMT_RGB_DEPTH(out_fmt)+7)&(~7);
-        return;
-    }
-    if (IMGFMT_IS_BGR(out_fmt)) {
-        if (IMGFMT_BGR_DEPTH(out_fmt) < 8 && !(out_fmt&128))
-            mpi->bpp = IMGFMT_BGR_DEPTH(out_fmt);
-        else
-            mpi->bpp=(IMGFMT_BGR_DEPTH(out_fmt)+7)&(~7);
-        mpi->flags|=MP_IMGFLAG_SWAPPED;
-        return;
-    }
-    if (IMGFMT_IS_XYZ(out_fmt)) {
-        mpi->bpp=3*((IMGFMT_XYZ_DEPTH(out_fmt) + 7) & ~7);
-        return;
-    }
-    mpi->num_planes=3;
-    if (out_fmt == IMGFMT_GBR24P) {
-        mpi->bpp=24;
-        mpi->flags|=MP_IMGFLAG_PLANAR;
-        return;
-    } else if (out_fmt == IMGFMT_GBR12P) {
-        mpi->bpp=36;
-        mpi->flags|=MP_IMGFLAG_PLANAR;
-        return;
-    } else if (out_fmt == IMGFMT_GBR14P) {
-        mpi->bpp=42;
-        mpi->flags|=MP_IMGFLAG_PLANAR;
-        return;
-    }
-    mpi->flags|=MP_IMGFLAG_YUV;
-    if (ff_mp_get_chroma_shift(out_fmt, NULL, NULL, NULL)) {
-        mpi->flags|=MP_IMGFLAG_PLANAR;
-        mpi->bpp = ff_mp_get_chroma_shift(out_fmt, &mpi->chroma_x_shift, &mpi->chroma_y_shift, NULL);
-        mpi->chroma_width  = mpi->width  >> mpi->chroma_x_shift;
-        mpi->chroma_height = mpi->height >> mpi->chroma_y_shift;
-    }
-    switch(out_fmt){
-    case IMGFMT_I420:
-    case IMGFMT_IYUV:
-        mpi->flags|=MP_IMGFLAG_SWAPPED;
-    case IMGFMT_YV12:
-        return;
-    case IMGFMT_420A:
-    case IMGFMT_422A:
-    case IMGFMT_444A:
-    case IMGFMT_IF09:
-        mpi->num_planes=4;
-    case IMGFMT_YVU9:
-    case IMGFMT_444P:
-    case IMGFMT_422P:
-    case IMGFMT_411P:
-    case IMGFMT_440P:
-    case IMGFMT_444P16_LE:
-    case IMGFMT_444P16_BE:
-    case IMGFMT_444P14_LE:
-    case IMGFMT_444P14_BE:
-    case IMGFMT_444P12_LE:
-    case IMGFMT_444P12_BE:
-    case IMGFMT_444P10_LE:
-    case IMGFMT_444P10_BE:
-    case IMGFMT_444P9_LE:
-    case IMGFMT_444P9_BE:
-    case IMGFMT_422P16_LE:
-    case IMGFMT_422P16_BE:
-    case IMGFMT_422P14_LE:
-    case IMGFMT_422P14_BE:
-    case IMGFMT_422P12_LE:
-    case IMGFMT_422P12_BE:
-    case IMGFMT_422P10_LE:
-    case IMGFMT_422P10_BE:
-    case IMGFMT_422P9_LE:
-    case IMGFMT_422P9_BE:
-    case IMGFMT_420P16_LE:
-    case IMGFMT_420P16_BE:
-    case IMGFMT_420P14_LE:
-    case IMGFMT_420P14_BE:
-    case IMGFMT_420P12_LE:
-    case IMGFMT_420P12_BE:
-    case IMGFMT_420P10_LE:
-    case IMGFMT_420P10_BE:
-    case IMGFMT_420P9_LE:
-    case IMGFMT_420P9_BE:
-        return;
-    case IMGFMT_Y16_LE:
-    case IMGFMT_Y16_BE:
-        mpi->bpp=16;
-    case IMGFMT_Y800:
-    case IMGFMT_Y8:
-        /* they're planar ones, but for easier handling use them as packed */
-        mpi->flags&=~MP_IMGFLAG_PLANAR;
-        mpi->num_planes=1;
-        return;
-    case IMGFMT_Y8A:
-        mpi->num_planes=2;
-        return;
-    case IMGFMT_UYVY:
-        mpi->flags|=MP_IMGFLAG_SWAPPED;
-    case IMGFMT_YUY2:
-        mpi->chroma_x_shift = 1;
-        mpi->bpp=16;
-        mpi->num_planes=1;
-        return;
-    case IMGFMT_NV12:
-        mpi->flags|=MP_IMGFLAG_SWAPPED;
-    case IMGFMT_NV21:
-        mpi->flags|=MP_IMGFLAG_PLANAR;
-        mpi->bpp=12;
-        mpi->num_planes=2;
-        mpi->chroma_width=(mpi->width>>0);
-        mpi->chroma_height=(mpi->height>>1);
-        mpi->chroma_x_shift=0;
-        mpi->chroma_y_shift=1;
-        return;
-    }
-    ff_mp_msg(MSGT_DECVIDEO,MSGL_WARN,"mp_image: unknown out_fmt: 0x%X\n",out_fmt);
-    mpi->bpp=0;
-}
-
-mp_image_t* ff_new_mp_image(int w,int h){
-    mp_image_t* mpi = malloc(sizeof(mp_image_t));
-    if(!mpi) return NULL; // error!
-    memset(mpi,0,sizeof(mp_image_t));
-    mpi->width=mpi->w=w;
-    mpi->height=mpi->h=h;
-    return mpi;
-}
-
-void ff_free_mp_image(mp_image_t* mpi){
-    if(!mpi) return;
-    if(mpi->flags&MP_IMGFLAG_ALLOCATED){
-        /* because we allocate the whole image at once */
-        av_free(mpi->planes[0]);
-        if (mpi->flags & MP_IMGFLAG_RGB_PALETTE)
-            av_free(mpi->planes[1]);
-    }
-    free(mpi);
-}
-
diff --git a/libavfilter/libmpcodecs/mp_image.h b/libavfilter/libmpcodecs/mp_image.h
deleted file mode 100644
index aedf451..0000000
--- a/libavfilter/libmpcodecs/mp_image.h
+++ /dev/null
@@ -1,159 +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.
- */
-
-#ifndef MPLAYER_MP_IMAGE_H
-#define MPLAYER_MP_IMAGE_H
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#undef printf //FIXME
-#undef fprintf //FIXME
-#include "mp_msg.h"
-#include "libavutil/avutil.h"
-#include "libavutil/avassert.h"
-#undef realloc
-#undef malloc
-#undef free
-#undef rand
-#undef srand
-#undef printf
-#undef strncpy
-#define ASMALIGN(ZEROBITS) ".p2align " #ZEROBITS "\n\t"
-#define CODEC_FLAG2_MEMC_ONLY     0x00001000 ///< Only do ME/MC (I frames -> ref, P frame -> ME+MC).
-
-enum AVPixelFormat ff_mp2ff_pix_fmt(int mp);
-
-//--------- codec's requirements (filled by the codec/vf) ---------
-
-//--- buffer content restrictions:
-// set if buffer content shouldn't be modified:
-#define MP_IMGFLAG_PRESERVE 0x01
-// set if buffer content will be READ.
-// This can be e.g. for next frame's MC: (I/P mpeg frames) -
-// then in combination with MP_IMGFLAG_PRESERVE - or it
-// can be because a video filter or codec will read a significant
-// amount of data while processing that frame (e.g. blending something
-// onto the frame, MV based intra prediction).
-// A frame marked like this should not be placed in to uncachable
-// video RAM for example.
-#define MP_IMGFLAG_READABLE 0x02
-
-//--- buffer width/stride/plane restrictions: (used for direct rendering)
-// stride _have_to_ be aligned to MB boundary:  [for DR restrictions]
-#define MP_IMGFLAG_ACCEPT_ALIGNED_STRIDE 0x4
-// stride should be aligned to MB boundary:     [for buffer allocation]
-#define MP_IMGFLAG_PREFER_ALIGNED_STRIDE 0x8
-// codec accept any stride (>=width):
-#define MP_IMGFLAG_ACCEPT_STRIDE 0x10
-// codec accept any width (width*bpp=stride -> stride%bpp==0) (>=width):
-#define MP_IMGFLAG_ACCEPT_WIDTH 0x20
-//--- for planar formats only:
-// uses only stride[0], and stride[1]=stride[2]=stride[0]>>mpi->chroma_x_shift
-#define MP_IMGFLAG_COMMON_STRIDE 0x40
-// uses only planes[0], and calculates planes[1,2] from width,height,imgfmt
-#define MP_IMGFLAG_COMMON_PLANE 0x80
-
-#define MP_IMGFLAGMASK_RESTRICTIONS 0xFF
-
-//--------- color info (filled by ff_mp_image_setfmt() ) -----------
-// set if number of planes > 1
-#define MP_IMGFLAG_PLANAR 0x100
-// set if it's YUV colorspace
-#define MP_IMGFLAG_YUV 0x200
-// set if it's swapped (BGR or YVU) plane/byteorder
-#define MP_IMGFLAG_SWAPPED 0x400
-// set if you want memory for palette allocated and managed by ff_vf_get_image etc.
-#define MP_IMGFLAG_RGB_PALETTE 0x800
-
-#define MP_IMGFLAGMASK_COLORS 0xF00
-
-// codec uses drawing/rendering callbacks (draw_slice()-like thing, DR method 2)
-// [the codec will set this flag if it supports callbacks, and the vo _may_
-//  clear it in get_image() if draw_slice() not implemented]
-#define MP_IMGFLAG_DRAW_CALLBACK 0x1000
-// set if it's in video buffer/memory: [set by vo/vf's get_image() !!!]
-#define MP_IMGFLAG_DIRECT 0x2000
-// set if buffer is allocated (used in destination images):
-#define MP_IMGFLAG_ALLOCATED 0x4000
-
-// buffer type was printed (do NOT set this flag - it's for INTERNAL USE!!!)
-#define MP_IMGFLAG_TYPE_DISPLAYED 0x8000
-
-// codec doesn't support any form of direct rendering - it has own buffer
-// allocation. so we just export its buffer pointers:
-#define MP_IMGTYPE_EXPORT 0
-// codec requires a static WO buffer, but it does only partial updates later:
-#define MP_IMGTYPE_STATIC 1
-// codec just needs some WO memory, where it writes/copies the whole frame to:
-#define MP_IMGTYPE_TEMP 2
-// I+P type, requires 2+ independent static R/W buffers
-#define MP_IMGTYPE_IP 3
-// I+P+B type, requires 2+ independent static R/W and 1+ temp WO buffers
-#define MP_IMGTYPE_IPB 4
-// Upper 16 bits give desired buffer number, -1 means get next available
-#define MP_IMGTYPE_NUMBERED 5
-// Doesn't need any buffer, incomplete image (probably a first field only)
-// we need this type to be able to differentiate between half frames and
-// all other cases
-#define MP_IMGTYPE_INCOMPLETE 6
-
-#define MP_MAX_PLANES 4
-
-#define MP_IMGFIELD_ORDERED 0x01
-#define MP_IMGFIELD_TOP_FIRST 0x02
-#define MP_IMGFIELD_REPEAT_FIRST 0x04
-#define MP_IMGFIELD_TOP 0x08
-#define MP_IMGFIELD_BOTTOM 0x10
-#define MP_IMGFIELD_INTERLACED 0x20
-
-typedef struct mp_image {
-    unsigned int flags;
-    unsigned char type;
-    int number;
-    unsigned char bpp;  // bits/pixel. NOT depth! for RGB it will be n*8
-    unsigned int imgfmt;
-    int width,height;  // stored dimensions
-    int x,y,w,h;  // visible dimensions
-    unsigned char* planes[MP_MAX_PLANES];
-    int stride[MP_MAX_PLANES];
-    char * qscale;
-    int qstride;
-    int pict_type; // 0->unknown, 1->I, 2->P, 3->B
-    int fields;
-    int qscale_type; // 0->mpeg1/4/h263, 1->mpeg2
-    int num_planes;
-    /* these are only used by planar formats Y,U(Cb),V(Cr) */
-    int chroma_width;
-    int chroma_height;
-    int chroma_x_shift; // horizontal
-    int chroma_y_shift; // vertical
-    int usage_count;
-    /* for private use by filter or vo driver (to store buffer id or dmpi) */
-    void* priv;
-} mp_image_t;
-
-void ff_mp_image_setfmt(mp_image_t* mpi,unsigned int out_fmt);
-mp_image_t* ff_new_mp_image(int w,int h);
-void ff_free_mp_image(mp_image_t* mpi);
-
-mp_image_t* ff_alloc_mpi(int w, int h, unsigned long int fmt);
-void ff_mp_image_alloc_planes(mp_image_t *mpi);
-void ff_copy_mpi(mp_image_t *dmpi, mp_image_t *mpi);
-
-#endif /* MPLAYER_MP_IMAGE_H */
diff --git a/libavfilter/libmpcodecs/mp_msg.h b/libavfilter/libmpcodecs/mp_msg.h
deleted file mode 100644
index 51cdff3..0000000
--- a/libavfilter/libmpcodecs/mp_msg.h
+++ /dev/null
@@ -1,166 +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.
- */
-
-#ifndef MPLAYER_MP_MSG_H
-#define MPLAYER_MP_MSG_H
-
-#include <stdarg.h>
-
-// defined in mplayer.c and mencoder.c
-extern int verbose;
-
-// verbosity elevel:
-
-/* Only messages level MSGL_FATAL-MSGL_STATUS should be translated,
- * messages level MSGL_V and above should not be translated. */
-
-#define MSGL_FATAL 0  // will exit/abort
-#define MSGL_ERR 1    // continues
-#define MSGL_WARN 2   // only warning
-#define MSGL_HINT 3   // short help message
-#define MSGL_INFO 4   // -quiet
-#define MSGL_STATUS 5 // v=0
-#define MSGL_V 6      // v=1
-#define MSGL_DBG2 7   // v=2
-#define MSGL_DBG3 8   // v=3
-#define MSGL_DBG4 9   // v=4
-#define MSGL_DBG5 10  // v=5
-
-#define MSGL_FIXME 1  // for conversions from printf where the appropriate MSGL is not known; set equal to ERR for obtrusiveness
-#define MSGT_FIXME 0  // for conversions from printf where the appropriate MSGT is not known; set equal to GLOBAL for obtrusiveness
-
-// code/module:
-
-#define MSGT_GLOBAL 0        // common player stuff errors
-#define MSGT_CPLAYER 1       // console player (mplayer.c)
-#define MSGT_GPLAYER 2       // gui player
-
-#define MSGT_VO 3       // libvo
-#define MSGT_AO 4       // libao
-
-#define MSGT_DEMUXER 5    // demuxer.c (general stuff)
-#define MSGT_DS 6         // demux stream (add/read packet etc)
-#define MSGT_DEMUX 7      // fileformat-specific stuff (demux_*.c)
-#define MSGT_HEADER 8     // fileformat-specific header (*header.c)
-
-#define MSGT_AVSYNC 9     // mplayer.c timer stuff
-#define MSGT_AUTOQ 10     // mplayer.c auto-quality stuff
-
-#define MSGT_CFGPARSER 11 // cfgparser.c
-
-#define MSGT_DECAUDIO 12  // av decoder
-#define MSGT_DECVIDEO 13
-
-#define MSGT_SEEK 14    // seeking code
-#define MSGT_WIN32 15   // win32 dll stuff
-#define MSGT_OPEN 16    // open.c (stream opening)
-#define MSGT_DVD 17     // open.c (DVD init/read/seek)
-
-#define MSGT_PARSEES 18 // parse_es.c (mpeg stream parser)
-#define MSGT_LIRC 19    // lirc_mp.c and input lirc driver
-
-#define MSGT_STREAM 20  // stream.c
-#define MSGT_CACHE 21   // cache2.c
-
-#define MSGT_MENCODER 22
-
-#define MSGT_XACODEC 23 // XAnim codecs
-
-#define MSGT_TV 24      // TV input subsystem
-
-#define MSGT_OSDEP 25  // OS-dependent parts
-
-#define MSGT_SPUDEC 26 // spudec.c
-
-#define MSGT_PLAYTREE 27    // Playtree handeling (playtree.c, playtreeparser.c)
-
-#define MSGT_INPUT 28
-
-#define MSGT_VFILTER 29
-
-#define MSGT_OSD 30
-
-#define MSGT_NETWORK 31
-
-#define MSGT_CPUDETECT 32
-
-#define MSGT_CODECCFG 33
-
-#define MSGT_SWS 34
-
-#define MSGT_VOBSUB 35
-#define MSGT_SUBREADER 36
-
-#define MSGT_AFILTER 37  // Audio filter messages
-
-#define MSGT_NETST 38 // Netstream
-
-#define MSGT_MUXER 39 // muxer layer
-
-#define MSGT_OSD_MENU 40
-
-#define MSGT_IDENTIFY 41  // -identify output
-
-#define MSGT_RADIO 42
-
-#define MSGT_ASS 43 // libass messages
-
-#define MSGT_LOADER 44 // dll loader messages
-
-#define MSGT_STATUSLINE 45 // playback/encoding status line
-
-#define MSGT_TELETEXT 46       // Teletext decoder
-
-#define MSGT_MAX 64
-
-
-extern char *ff_mp_msg_charset;
-extern int ff_mp_msg_color;
-extern int ff_mp_msg_module;
-
-extern int ff_mp_msg_levels[MSGT_MAX];
-extern int ff_mp_msg_level_all;
-
-
-void ff_mp_msg_init(void);
-int ff_mp_msg_test(int mod, int lev);
-
-#include "config.h"
-
-void ff_mp_msg_va(int mod, int lev, const char *format, va_list va);
-#ifdef __GNUC__
-void ff_mp_msg(int mod, int lev, const char *format, ... ) __attribute__ ((format (printf, 3, 4)));
-#   ifdef MP_DEBUG
-#      define mp_dbg(mod,lev, args... ) ff_mp_msg(mod, lev, ## args )
-#   else
-       // only useful for developers, disable but check syntax
-#      define mp_dbg(mod,lev, args... ) do { if (0) ff_mp_msg(mod, lev, ## args ); } while (0)
-#   endif
-#else // not GNU C
-void ff_mp_msg(int mod, int lev, const char *format, ... );
-#   ifdef MP_DEBUG
-#      define mp_dbg(mod,lev, ... ) ff_mp_msg(mod, lev, __VA_ARGS__)
-#   else
-       // only useful for developers, disable but check syntax
-#      define mp_dbg(mod,lev, ... ) do { if (0) ff_mp_msg(mod, lev, __VA_ARGS__); } while (0)
-#   endif
-#endif /* __GNUC__ */
-
-const char* ff_filename_recode(const char* filename);
-
-#endif /* MPLAYER_MP_MSG_H */
diff --git a/libavfilter/libmpcodecs/vf.h b/libavfilter/libmpcodecs/vf.h
deleted file mode 100644
index 7cda60b..0000000
--- a/libavfilter/libmpcodecs/vf.h
+++ /dev/null
@@ -1,167 +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.
- */
-
-#ifndef MPLAYER_VF_H
-#define MPLAYER_VF_H
-
-//#include "m_option.h"
-#include "mp_image.h"
-
-//extern m_obj_settings_t* vf_settings;
-//extern const m_obj_list_t vf_obj_list;
-
-struct vf_instance;
-struct vf_priv_s;
-
-typedef struct vf_info_s {
-    const char *info;
-    const char *name;
-    const char *author;
-    const char *comment;
-    int (*vf_open)(struct vf_instance *vf,char* args);
-    // Ptr to a struct dscribing the options
-    const void* opts;
-} vf_info_t;
-
-#define NUM_NUMBERED_MPI 50
-
-typedef struct vf_image_context_s {
-    mp_image_t* static_images[2];
-    mp_image_t* temp_images[1];
-    mp_image_t* export_images[1];
-    mp_image_t* numbered_images[NUM_NUMBERED_MPI];
-    int static_idx;
-} vf_image_context_t;
-
-typedef struct vf_format_context_t {
-    int have_configured;
-    int orig_width, orig_height, orig_fmt;
-} vf_format_context_t;
-
-typedef struct vf_instance {
-    const vf_info_t* info;
-    // funcs:
-    int (*config)(struct vf_instance *vf,
-        int width, int height, int d_width, int d_height,
-        unsigned int flags, unsigned int outfmt);
-    int (*control)(struct vf_instance *vf,
-        int request, void* data);
-    int (*query_format)(struct vf_instance *vf,
-        unsigned int fmt);
-    void (*get_image)(struct vf_instance *vf,
-        mp_image_t *mpi);
-    int (*put_image)(struct vf_instance *vf,
-        mp_image_t *mpi, double pts);
-    void (*start_slice)(struct vf_instance *vf,
-        mp_image_t *mpi);
-    void (*draw_slice)(struct vf_instance *vf,
-        unsigned char** src, int* stride, int w,int h, int x, int y);
-    void (*uninit)(struct vf_instance *vf);
-
-    int (*continue_buffered_image)(struct vf_instance *vf);
-    // caps:
-    unsigned int default_caps; // used by default query_format()
-    unsigned int default_reqs; // used by default config()
-    // data:
-    int w, h;
-    vf_image_context_t imgctx;
-    vf_format_context_t fmt;
-    struct vf_instance *next;
-    mp_image_t *dmpi;
-    struct vf_priv_s* priv;
-} vf_instance_t;
-
-// control codes:
-typedef struct vf_seteq_s
-{
-    const char *item;
-    int value;
-} vf_equalizer_t;
-
-#define VFCTRL_QUERY_MAX_PP_LEVEL 4 /* test for postprocessing support (max level) */
-#define VFCTRL_SET_PP_LEVEL 5 /* set postprocessing level */
-#define VFCTRL_SET_EQUALIZER 6 /* set color options (brightness,contrast etc) */
-#define VFCTRL_GET_EQUALIZER 8 /* gset color options (brightness,contrast etc) */
-#define VFCTRL_DRAW_OSD 7
-#define VFCTRL_CHANGE_RECTANGLE 9 /* Change the rectangle boundaries */
-#define VFCTRL_FLIP_PAGE 10 /* Tell the vo to flip pages */
-#define VFCTRL_DUPLICATE_FRAME 11 /* For encoding - encode zero-change frame */
-#define VFCTRL_SKIP_NEXT_FRAME 12 /* For encoding - drop the next frame that passes through */
-#define VFCTRL_FLUSH_FRAMES    13 /* For encoding - flush delayed frames */
-#define VFCTRL_SCREENSHOT      14 /* Make a screenshot */
-#define VFCTRL_INIT_EOSD       15 /* Select EOSD renderer */
-#define VFCTRL_DRAW_EOSD       16 /* Render EOSD */
-#define VFCTRL_GET_PTS         17 /* Return last pts value that reached vf_vo*/
-#define VFCTRL_SET_DEINTERLACE 18 /* Set deinterlacing status */
-#define VFCTRL_GET_DEINTERLACE 19 /* Get deinterlacing status */
-
-#include "vfcap.h"
-
-//FIXME this should be in a common header, but i dunno which
-#define MP_NOPTS_VALUE (-1LL<<63) //both int64_t and double should be able to represent this exactly
-
-
-// functions:
-void ff_vf_mpi_clear(mp_image_t* mpi,int x0,int y0,int w,int h);
-mp_image_t* ff_vf_get_image(vf_instance_t* vf, unsigned int outfmt, int mp_imgtype, int mp_imgflag, int w, int h);
-
-vf_instance_t* vf_open_plugin(const vf_info_t* const* filter_list, vf_instance_t* next, const char *name, char **args);
-vf_instance_t* vf_open_filter(vf_instance_t* next, const char *name, char **args);
-vf_instance_t* ff_vf_add_before_vo(vf_instance_t **vf, char *name, char **args);
-vf_instance_t* vf_open_encoder(vf_instance_t* next, const char *name, char *args);
-
-unsigned int ff_vf_match_csp(vf_instance_t** vfp,const unsigned int* list,unsigned int preferred);
-void ff_vf_clone_mpi_attributes(mp_image_t* dst, mp_image_t* src);
-void ff_vf_queue_frame(vf_instance_t *vf, int (*)(vf_instance_t *));
-int ff_vf_output_queued_frame(vf_instance_t *vf);
-
-// default wrappers:
-int ff_vf_next_config(struct vf_instance *vf,
-        int width, int height, int d_width, int d_height,
-        unsigned int flags, unsigned int outfmt);
-int ff_vf_next_control(struct vf_instance *vf, int request, void* data);
-void ff_vf_extra_flip(struct vf_instance *vf);
-int ff_vf_next_query_format(struct vf_instance *vf, unsigned int fmt);
-int ff_vf_next_put_image(struct vf_instance *vf,mp_image_t *mpi, double pts);
-void ff_vf_next_draw_slice (struct vf_instance *vf, unsigned char** src, int* stride, int w,int h, int x, int y);
-
-vf_instance_t* ff_append_filters(vf_instance_t* last);
-
-void ff_vf_uninit_filter(vf_instance_t* vf);
-void ff_vf_uninit_filter_chain(vf_instance_t* vf);
-
-int ff_vf_config_wrapper(struct vf_instance *vf,
-                      int width, int height, int d_width, int d_height,
-                      unsigned int flags, unsigned int outfmt);
-
-static inline int norm_qscale(int qscale, int type)
-{
-    switch (type) {
-    case 0: // MPEG-1
-        return qscale;
-    case 1: // MPEG-2
-        return qscale >> 1;
-    case 2: // H264
-        return qscale >> 2;
-    case 3: // VP56
-        return (63 - qscale + 2) >> 2;
-    }
-    return qscale;
-}
-
-#endif /* MPLAYER_VF_H */
diff --git a/libavfilter/libmpcodecs/vf_softpulldown.c b/libavfilter/libmpcodecs/vf_softpulldown.c
deleted file mode 100644
index 556374e..0000000
--- a/libavfilter/libmpcodecs/vf_softpulldown.c
+++ /dev/null
@@ -1,163 +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 "img_format.h"
-#include "mp_image.h"
-#include "vf.h"
-
-#include "libvo/fastmemcpy.h"
-
-struct vf_priv_s {
-    int state;
-    long long in;
-    long long out;
-};
-
-static int put_image(struct vf_instance *vf, mp_image_t *mpi, double pts)
-{
-    mp_image_t *dmpi;
-    int ret = 0;
-    int flags = mpi->fields;
-    int state = vf->priv->state;
-
-    dmpi = ff_vf_get_image(vf->next, mpi->imgfmt,
-                        MP_IMGTYPE_STATIC, MP_IMGFLAG_ACCEPT_STRIDE |
-                        MP_IMGFLAG_PRESERVE, mpi->width, mpi->height);
-
-    vf->priv->in++;
-
-    if ((state == 0 &&
-         !(flags & MP_IMGFIELD_TOP_FIRST)) ||
-        (state == 1 &&
-         flags & MP_IMGFIELD_TOP_FIRST)) {
-        ff_mp_msg(MSGT_VFILTER, MSGL_WARN,
-               "softpulldown: Unexpected field flags: state=%d top_field_first=%d repeat_first_field=%d\n",
-               state,
-               (flags & MP_IMGFIELD_TOP_FIRST) != 0,
-               (flags & MP_IMGFIELD_REPEAT_FIRST) != 0);
-        state ^= 1;
-    }
-
-    if (state == 0) {
-        ret = ff_vf_next_put_image(vf, mpi, MP_NOPTS_VALUE);
-        vf->priv->out++;
-        if (flags & MP_IMGFIELD_REPEAT_FIRST) {
-            my_memcpy_pic(dmpi->planes[0],
-                       mpi->planes[0], mpi->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,
-                              dmpi->stride[1]*2,
-                              mpi->stride[1]*2);
-                my_memcpy_pic(dmpi->planes[2],
-                              mpi->planes[2],
-                              mpi->chroma_width,
-                              mpi->chroma_height/2,
-                              dmpi->stride[2]*2,
-                              mpi->stride[2]*2);
-            }
-            state=1;
-        }
-    } else {
-        my_memcpy_pic(dmpi->planes[0]+dmpi->stride[0],
-                      mpi->planes[0]+mpi->stride[0], mpi->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,
-                          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,
-                          dmpi->stride[2]*2, mpi->stride[2]*2);
-        }
-        ret = ff_vf_next_put_image(vf, dmpi, MP_NOPTS_VALUE);
-        vf->priv->out++;
-        if (flags & MP_IMGFIELD_REPEAT_FIRST) {
-            ret |= ff_vf_next_put_image(vf, mpi, MP_NOPTS_VALUE);
-            vf->priv->out++;
-            state=0;
-        } else {
-            my_memcpy_pic(dmpi->planes[0],
-                          mpi->planes[0], mpi->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,
-                              dmpi->stride[1]*2,
-                              mpi->stride[1]*2);
-                my_memcpy_pic(dmpi->planes[2],
-                              mpi->planes[2],
-                              mpi->chroma_width,
-                              mpi->chroma_height/2,
-                              dmpi->stride[2]*2,
-                              mpi->stride[2]*2);
-            }
-        }
-    }
-
-    vf->priv->state = state;
-
-    return ret;
-}
-
-static int config(struct vf_instance *vf,
-    int width, int height, int d_width, int d_height,
-    unsigned int flags, unsigned int outfmt)
-{
-    return ff_vf_next_config(vf,width,height,d_width,d_height,flags,outfmt);
-}
-
-static void uninit(struct vf_instance *vf)
-{
-    ff_mp_msg(MSGT_VFILTER, MSGL_INFO, "softpulldown: %lld frames in, %lld frames out\n", vf->priv->in, vf->priv->out);
-    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));
-    vf->priv->state = 0;
-    return 1;
-}
-
-const vf_info_t ff_vf_info_softpulldown = {
-    "mpeg2 soft 3:2 pulldown",
-    "softpulldown",
-    "Tobias Diedrich <ranma+mplayer@tdiedrich.de>",
-    "",
-    vf_open,
-    NULL
-};
diff --git a/libavfilter/libmpcodecs/vfcap.h b/libavfilter/libmpcodecs/vfcap.h
deleted file mode 100644
index 611d642..0000000
--- a/libavfilter/libmpcodecs/vfcap.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/* VFCAP_* values: they are flags, returned by query_format():
- *
- * 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.
- */
-
-#ifndef MPLAYER_VFCAP_H
-#define MPLAYER_VFCAP_H
-
-// set, if the given colorspace is supported (with or without conversion)
-#define VFCAP_CSP_SUPPORTED 0x1
-// set, if the given colorspace is supported _without_ conversion
-#define VFCAP_CSP_SUPPORTED_BY_HW 0x2
-// set if the driver/filter can draw OSD
-#define VFCAP_OSD 0x4
-// set if the driver/filter can handle compressed SPU stream
-#define VFCAP_SPU 0x8
-// scaling up/down by hardware, or software:
-#define VFCAP_HWSCALE_UP 0x10
-#define VFCAP_HWSCALE_DOWN 0x20
-#define VFCAP_SWSCALE 0x40
-// driver/filter can do vertical flip (upside-down)
-#define VFCAP_FLIP 0x80
-
-// driver/hardware handles timing (blocking)
-#define VFCAP_TIMER 0x100
-// driver _always_ flip image upside-down (for ve_vfw)
-#define VFCAP_FLIPPED 0x200
-// vf filter: accepts stride (put_image)
-// vo driver: has draw_slice() support for the given csp
-#define VFCAP_ACCEPT_STRIDE 0x400
-// filter does postprocessing (so you shouldn't scale/filter image before it)
-#define VFCAP_POSTPROC 0x800
-// filter cannot be reconfigured to different size & format
-#define VFCAP_CONSTANT 0x1000
-// filter can draw EOSD
-#define VFCAP_EOSD 0x2000
-// filter will draw EOSD at screen resolution (without scaling)
-#define VFCAP_EOSD_UNSCALED 0x4000
-// used by libvo and vf_vo, indicates the VO does not support draw_slice for this format
-#define VOCAP_NOSLICES 0x8000
-
-#endif /* MPLAYER_VFCAP_H */
diff --git a/libavfilter/unsharp.h b/libavfilter/unsharp.h
index c2aed64..fc651c0 100644
--- a/libavfilter/unsharp.h
+++ b/libavfilter/unsharp.h
@@ -41,6 +41,10 @@
     cl_kernel kernel_chroma;
     cl_mem cl_luma_mask;
     cl_mem cl_chroma_mask;
+    cl_mem cl_luma_mask_x;
+    cl_mem cl_chroma_mask_x;
+    cl_mem cl_luma_mask_y;
+    cl_mem cl_chroma_mask_y;
     int in_plane_size[8];
     int out_plane_size[8];
     int plane_num;
diff --git a/libavfilter/unsharp_opencl.c b/libavfilter/unsharp_opencl.c
index 5c6b5ef..2cc0704 100644
--- a/libavfilter/unsharp_opencl.c
+++ b/libavfilter/unsharp_opencl.c
@@ -87,11 +87,12 @@
     return ret;
 }
 
-static int compute_mask_matrix(cl_mem cl_mask_matrix, int step_x, int step_y)
+static int copy_separable_masks(cl_mem cl_mask_x, cl_mem cl_mask_y, int step_x, int step_y)
 {
-    int i, j, ret = 0;
-    uint32_t *mask_matrix, *mask_x, *mask_y;
-    size_t size_matrix = sizeof(uint32_t) * (2 * step_x + 1) * (2 * step_y + 1);
+    int ret = 0;
+    uint32_t *mask_x, *mask_y;
+    size_t size_mask_x = sizeof(uint32_t) * (2 * step_x + 1);
+    size_t size_mask_y = sizeof(uint32_t) * (2 * step_y + 1);
     mask_x = av_mallocz_array(2 * step_x + 1, sizeof(uint32_t));
     if (!mask_x) {
         ret = AVERROR(ENOMEM);
@@ -102,37 +103,36 @@
         ret = AVERROR(ENOMEM);
         goto end;
     }
-    mask_matrix = av_mallocz(size_matrix);
-    if (!mask_matrix) {
-        ret = AVERROR(ENOMEM);
-        goto end;
-    }
+
     ret = compute_mask(step_x, mask_x);
     if (ret < 0)
         goto end;
     ret = compute_mask(step_y, mask_y);
     if (ret < 0)
         goto end;
-    for (j = 0; j < 2 * step_y + 1; j++) {
-        for (i = 0; i < 2 * step_x + 1; i++) {
-            mask_matrix[i + j * (2 * step_x + 1)] = mask_y[j] * mask_x[i];
-        }
-    }
-    ret = av_opencl_buffer_write(cl_mask_matrix, (uint8_t *)mask_matrix, size_matrix);
+
+    ret = av_opencl_buffer_write(cl_mask_x, (uint8_t *)mask_x, size_mask_x);
+    ret = av_opencl_buffer_write(cl_mask_y, (uint8_t *)mask_y, size_mask_y);
 end:
     av_freep(&mask_x);
     av_freep(&mask_y);
-    av_freep(&mask_matrix);
+
     return ret;
 }
 
 static int generate_mask(AVFilterContext *ctx)
 {
-    UnsharpContext *unsharp = ctx->priv;
-    int i, ret = 0, step_x[2], step_y[2];
+    cl_mem masks[4];
     cl_mem mask_matrix[2];
+    int i, ret = 0, step_x[2], step_y[2];
+
+    UnsharpContext *unsharp = ctx->priv;
     mask_matrix[0] = unsharp->opencl_ctx.cl_luma_mask;
     mask_matrix[1] = unsharp->opencl_ctx.cl_chroma_mask;
+    masks[0] = unsharp->opencl_ctx.cl_luma_mask_x;
+    masks[1] = unsharp->opencl_ctx.cl_luma_mask_y;
+    masks[2] = unsharp->opencl_ctx.cl_chroma_mask_x;
+    masks[3] = unsharp->opencl_ctx.cl_chroma_mask_y;
     step_x[0] = unsharp->luma.steps_x;
     step_x[1] = unsharp->chroma.steps_x;
     step_y[0] = unsharp->luma.steps_y;
@@ -144,12 +144,16 @@
     else
         unsharp->opencl_ctx.use_fast_kernels = 1;
 
+    if (!masks[0] || !masks[1] || !masks[2] || !masks[3]) {
+        av_log(ctx, AV_LOG_ERROR, "Luma mask and chroma mask should not be NULL\n");
+        return AVERROR(EINVAL);
+    }
     if (!mask_matrix[0] || !mask_matrix[1]) {
         av_log(ctx, AV_LOG_ERROR, "Luma mask and chroma mask should not be NULL\n");
         return AVERROR(EINVAL);
     }
     for (i = 0; i < 2; i++) {
-        ret = compute_mask_matrix(mask_matrix[i], step_x[i], step_y[i]);
+        ret = copy_separable_masks(masks[2*i], masks[2*i+1], step_x[i], step_y[i]);
         if (ret < 0)
             return ret;
     }
@@ -184,7 +188,8 @@
         ret = avpriv_opencl_set_parameter(&kernel1,
                                       FF_OPENCL_PARAM_INFO(unsharp->opencl_ctx.cl_inbuf),
                                       FF_OPENCL_PARAM_INFO(unsharp->opencl_ctx.cl_outbuf),
-                                      FF_OPENCL_PARAM_INFO(unsharp->opencl_ctx.cl_luma_mask),
+                                      FF_OPENCL_PARAM_INFO(unsharp->opencl_ctx.cl_luma_mask_x),
+                                      FF_OPENCL_PARAM_INFO(unsharp->opencl_ctx.cl_luma_mask_y),
                                       FF_OPENCL_PARAM_INFO(unsharp->luma.amount),
                                       FF_OPENCL_PARAM_INFO(unsharp->luma.scalebits),
                                       FF_OPENCL_PARAM_INFO(unsharp->luma.halfscale),
@@ -201,7 +206,8 @@
         ret = avpriv_opencl_set_parameter(&kernel2,
                                       FF_OPENCL_PARAM_INFO(unsharp->opencl_ctx.cl_inbuf),
                                       FF_OPENCL_PARAM_INFO(unsharp->opencl_ctx.cl_outbuf),
-                                      FF_OPENCL_PARAM_INFO(unsharp->opencl_ctx.cl_chroma_mask),
+                                      FF_OPENCL_PARAM_INFO(unsharp->opencl_ctx.cl_chroma_mask_x),
+                                      FF_OPENCL_PARAM_INFO(unsharp->opencl_ctx.cl_chroma_mask_y),
                                       FF_OPENCL_PARAM_INFO(unsharp->chroma.amount),
                                       FF_OPENCL_PARAM_INFO(unsharp->chroma.scalebits),
                                       FF_OPENCL_PARAM_INFO(unsharp->chroma.halfscale),
@@ -264,7 +270,9 @@
             return AVERROR_EXTERNAL;
         }
     }
-    clFinish(unsharp->opencl_ctx.command_queue);
+    //blocking map is suffficient, no need for clFinish
+    //clFinish(unsharp->opencl_ctx.command_queue);
+
     return av_opencl_buffer_read_image(out->data, unsharp->opencl_ctx.out_plane_size,
                                        unsharp->opencl_ctx.plane_num, unsharp->opencl_ctx.cl_outbuf,
                                        unsharp->opencl_ctx.cl_outbuf_size);
@@ -286,6 +294,27 @@
     ret = av_opencl_buffer_create(&unsharp->opencl_ctx.cl_chroma_mask,
                                   sizeof(uint32_t) * (2 * unsharp->chroma.steps_x + 1) * (2 * unsharp->chroma.steps_y + 1),
                                   CL_MEM_READ_ONLY, NULL);
+    // separable filters
+    if (ret < 0)
+        return ret;
+    ret = av_opencl_buffer_create(&unsharp->opencl_ctx.cl_luma_mask_x,
+                                  sizeof(uint32_t) * (2 * unsharp->luma.steps_x + 1),
+                                  CL_MEM_READ_ONLY, NULL);
+    if (ret < 0)
+        return ret;
+    ret = av_opencl_buffer_create(&unsharp->opencl_ctx.cl_luma_mask_y,
+                                  sizeof(uint32_t) * (2 * unsharp->luma.steps_y + 1),
+                                  CL_MEM_READ_ONLY, NULL);
+    if (ret < 0)
+        return ret;
+    ret = av_opencl_buffer_create(&unsharp->opencl_ctx.cl_chroma_mask_x,
+                                  sizeof(uint32_t) * (2 * unsharp->chroma.steps_x + 1),
+                                  CL_MEM_READ_ONLY, NULL);
+    if (ret < 0)
+        return ret;
+    ret = av_opencl_buffer_create(&unsharp->opencl_ctx.cl_chroma_mask_y,
+                                  sizeof(uint32_t) * (2 * unsharp->chroma.steps_y + 1),
+                                  CL_MEM_READ_ONLY, NULL);
     if (ret < 0)
         return ret;
     ret = generate_mask(ctx);
@@ -339,6 +368,10 @@
     av_opencl_buffer_release(&unsharp->opencl_ctx.cl_outbuf);
     av_opencl_buffer_release(&unsharp->opencl_ctx.cl_luma_mask);
     av_opencl_buffer_release(&unsharp->opencl_ctx.cl_chroma_mask);
+    av_opencl_buffer_release(&unsharp->opencl_ctx.cl_luma_mask_x);
+    av_opencl_buffer_release(&unsharp->opencl_ctx.cl_chroma_mask_x);
+    av_opencl_buffer_release(&unsharp->opencl_ctx.cl_luma_mask_y);
+    av_opencl_buffer_release(&unsharp->opencl_ctx.cl_chroma_mask_y);
     clReleaseKernel(unsharp->opencl_ctx.kernel_default);
     clReleaseKernel(unsharp->opencl_ctx.kernel_luma);
     clReleaseKernel(unsharp->opencl_ctx.kernel_chroma);
diff --git a/libavfilter/unsharp_opencl_kernel.h b/libavfilter/unsharp_opencl_kernel.h
index 9c4fd65..307d0f1 100644
--- a/libavfilter/unsharp_opencl_kernel.h
+++ b/libavfilter/unsharp_opencl_kernel.h
@@ -36,7 +36,8 @@
 kernel void unsharp_luma(
                     global unsigned char *src,
                     global unsigned char *dst,
-                    global int *mask,
+                    global int *mask_x,
+                    global int *mask_y,
                     int amount,
                     int scalebits,
                     int halfscale,
@@ -59,10 +60,12 @@
         return;
     }
 
-    local uchar l[32][32];
-    local int lc[LU_RADIUS_X*LU_RADIUS_Y];
+    local unsigned int l[32][32];
+    local unsigned int lcx[LU_RADIUS_X];
+    local unsigned int lcy[LU_RADIUS_Y];
     int indexIx, indexIy, i, j;
 
+    //load up tile: actual workspace + halo of 8 points in x and y \n
     for(i = 0; i <= 1; i++) {
         indexIy = -8 + (blockIdx.y + i) * 16 + threadIdx.y;
         indexIy = indexIy < 0 ? 0 : indexIy;
@@ -76,27 +79,54 @@
     }
 
     int indexL = threadIdx.y*16 + threadIdx.x;
-    if (indexL < LU_RADIUS_X*LU_RADIUS_Y)
-        lc[indexL] = mask[indexL];
+    if (indexL < LU_RADIUS_X)
+        lcx[indexL] = mask_x[indexL];
+    if (indexL < LU_RADIUS_Y)
+        lcy[indexL] = mask_y[indexL];
     barrier(CLK_LOCAL_MEM_FENCE);
 
-    int idx, idy, maskIndex;
-    int sum = 0;
-    int steps_x = LU_RADIUS_X/2;
-    int steps_y = LU_RADIUS_Y/2;
+    //needed for unsharp mask application in the end \n
+    int orig_value = (int)l[threadIdx.y + 8][threadIdx.x + 8];
 
-    \n#pragma unroll\n
-    for (i = -steps_y; i <= steps_y; i++) {
-        idy = 8 + i + threadIdx.y;
-        \n#pragma unroll\n
-        for (j = -steps_x; j <= steps_x; j++) {
-            idx = 8 + j + threadIdx.x;
-            maskIndex = (i + steps_y)*LU_RADIUS_X + j + steps_x;
-            sum += (int)l[idy][idx] * lc[maskIndex];
+    int idx, idy, maskIndex;
+    int temp[2] = {0};
+    int steps_x = (LU_RADIUS_X-1)/2;
+    int steps_y = (LU_RADIUS_Y-1)/2;
+
+    // compute the actual workspace + left&right halos \n
+      \n#pragma unroll\n
+    for (j = 0; j <=1; j++) {
+      //extra work to cover left and right halos \n
+      idx = 16*j + threadIdx.x;
+      \n#pragma unroll\n
+        for (i = -steps_y; i <= steps_y; i++) {
+          idy = 8 + i + threadIdx.y;
+          maskIndex = (i + steps_y);
+          temp[j] += (int)l[idy][idx] * lcy[maskIndex];
         }
     }
-    int temp = (int)l[threadIdx.y + 8][threadIdx.x + 8];
-    int res = temp + (((temp - (int)((sum + halfscale) >> scalebits)) * amount) >> 16);
+    barrier(CLK_LOCAL_MEM_FENCE);
+    //save results from the vertical filter in local memory \n
+    idy = 8 + threadIdx.y;
+      \n#pragma unroll\n
+    for (j = 0; j <=1; j++) {
+      idx = 16*j + threadIdx.x;
+      l[idy][idx] = temp[j];
+    }
+    barrier(CLK_LOCAL_MEM_FENCE);
+
+    //compute results with the horizontal filter \n
+    int sum = 0;
+    idy = 8 + threadIdx.y;
+    \n#pragma unroll\n
+      for (j = -steps_x; j <= steps_x; j++) {
+        idx = 8 + j + threadIdx.x;
+        maskIndex = j + steps_x;
+        sum += (int)l[idy][idx] * lcx[maskIndex];
+      }
+
+    int res = orig_value + (((orig_value - (int)((sum + halfscale) >> scalebits)) * amount) >> 16);
+
     if (globalIdx.x < width && globalIdx.y < height)
         dst[globalIdx.x + globalIdx.y*dst_stride] = clip_uint8(res);
 }
@@ -104,7 +134,8 @@
 kernel void unsharp_chroma(
                     global unsigned char *src_y,
                     global unsigned char *dst_y,
-                    global int *mask,
+                    global int *mask_x,
+                    global int *mask_y,
                     int amount,
                     int scalebits,
                     int halfscale,
@@ -141,8 +172,9 @@
         return;
     }
 
-    local uchar l[32][32];
-    local int lc[CH_RADIUS_X*CH_RADIUS_Y];
+    local unsigned int l[32][32];
+    local unsigned int lcx[CH_RADIUS_X];
+    local unsigned int lcy[CH_RADIUS_Y];
     int indexIx, indexIy, i, j;
     for(i = 0; i <= 1; i++) {
         indexIy = -8 + (blockIdx.y + i) * 16 + threadIdx.y;
@@ -157,27 +189,51 @@
     }
 
     int indexL = threadIdx.y*16 + threadIdx.x;
-    if (indexL < CH_RADIUS_X*CH_RADIUS_Y)
-        lc[indexL] = mask[indexL];
+    if (indexL < CH_RADIUS_X)
+        lcx[indexL] = mask_x[indexL];
+    if (indexL < CH_RADIUS_Y)
+        lcy[indexL] = mask_y[indexL];
     barrier(CLK_LOCAL_MEM_FENCE);
 
+    int orig_value = (int)l[threadIdx.y + 8][threadIdx.x + 8];
+
     int idx, idy, maskIndex;
-    int sum = 0;
     int steps_x = CH_RADIUS_X/2;
     int steps_y = CH_RADIUS_Y/2;
+    int temp[2] = {0,0};
 
     \n#pragma unroll\n
-    for (i = -steps_y; i <= steps_y; i++) {
-        idy = 8 + i + threadIdx.y;
+      for (j = 0; j <= 1; j++) {
+        idx = 16*j + threadIdx.x;
         \n#pragma unroll\n
-        for (j = -steps_x; j <= steps_x; j++) {
-            idx = 8 + j + threadIdx.x;
-            maskIndex = (i + steps_y)*CH_RADIUS_X + j + steps_x;
-            sum += (int)l[idy][idx] * lc[maskIndex];
-        }
+          for (i = -steps_y; i <= steps_y; i++) {
+            idy = 8 + i + threadIdx.y;
+            maskIndex = i + steps_y;
+            temp[j] += (int)l[idy][idx] * lcy[maskIndex];
+          }
+      }
+
+    barrier(CLK_LOCAL_MEM_FENCE);
+    idy = 8 + threadIdx.y;
+    \n#pragma unroll\n
+    for (j = 0; j <= 1; j++) {
+      idx = 16*j + threadIdx.x;
+      l[idy][idx] = temp[j];
     }
-    int temp = (int)l[threadIdx.y + 8][threadIdx.x + 8];
-    int res = temp + (((temp - (int)((sum + halfscale) >> scalebits)) * amount) >> 16);
+    barrier(CLK_LOCAL_MEM_FENCE);
+
+    //compute results with the horizontal filter \n
+    int sum = 0;
+    idy = 8 + threadIdx.y;
+    \n#pragma unroll\n
+      for (j = -steps_x; j <= steps_x; j++) {
+        idx = 8 + j + threadIdx.x;
+        maskIndex = j + steps_x;
+        sum += (int)l[idy][idx] * lcx[maskIndex];
+      }
+
+    int res = orig_value + (((orig_value - (int)((sum + halfscale) >> scalebits)) * amount) >> 16);
+
     if (globalIdx.x < cw && globalIdx.y < ch)
         dst[globalIdx.x + globalIdx.y*dst_stride_ch] = clip_uint8(res);
 }
diff --git a/libavfilter/version.h b/libavfilter/version.h
index ce22f7b..43b7ab9 100644
--- a/libavfilter/version.h
+++ b/libavfilter/version.h
@@ -30,7 +30,7 @@
 #include "libavutil/version.h"
 
 #define LIBAVFILTER_VERSION_MAJOR  5
-#define LIBAVFILTER_VERSION_MINOR  9
+#define LIBAVFILTER_VERSION_MINOR  13
 #define LIBAVFILTER_VERSION_MICRO 101
 
 #define LIBAVFILTER_VERSION_INT AV_VERSION_INT(LIBAVFILTER_VERSION_MAJOR, \
diff --git a/libavfilter/vf_blend.c b/libavfilter/vf_blend.c
index a29cabc..d232457 100644
--- a/libavfilter/vf_blend.c
+++ b/libavfilter/vf_blend.c
@@ -379,7 +379,7 @@
     int i;
 
     ff_dualinput_uninit(&b->dinput);
-    av_freep(&b->prev_frame);
+    av_frame_free(&b->prev_frame);
 
     for (i = 0; i < FF_ARRAY_ELEMS(b->params); i++)
         av_expr_free(b->params[i].e);
diff --git a/libavfilter/vf_boxblur.c b/libavfilter/vf_boxblur.c
index 3ccf268..bcf0ca5 100644
--- a/libavfilter/vf_boxblur.c
+++ b/libavfilter/vf_boxblur.c
@@ -124,7 +124,7 @@
         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(fmt);
         if (!(desc->flags & (AV_PIX_FMT_FLAG_HWACCEL | AV_PIX_FMT_FLAG_BITSTREAM | AV_PIX_FMT_FLAG_PAL)) &&
             (desc->flags & AV_PIX_FMT_FLAG_PLANAR || desc->nb_components == 1) &&
-            (!(desc->flags & AV_PIX_FMT_FLAG_BE) == !HAVE_BIGENDIAN) || desc->comp[0].depth_minus1 == 7)
+            (!(desc->flags & AV_PIX_FMT_FLAG_BE) == !HAVE_BIGENDIAN || desc->comp[0].depth_minus1 == 7))
             ff_add_format(&formats, fmt);
     }
 
diff --git a/libavfilter/vf_codecview.c b/libavfilter/vf_codecview.c
index d777f97..27fac3f 100644
--- a/libavfilter/vf_codecview.c
+++ b/libavfilter/vf_codecview.c
@@ -62,8 +62,10 @@
     // TODO: we can probably add way more pixel formats without any other
     // changes; anything with 8-bit luma in first plane should be working
     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));
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static int clip_line(int *sx, int *sy, int *ex, int *ey, int maxx)
diff --git a/libavfilter/vf_colorbalance.c b/libavfilter/vf_colorbalance.c
index c8f2747..e37f199 100644
--- a/libavfilter/vf_colorbalance.c
+++ b/libavfilter/vf_colorbalance.c
@@ -76,9 +76,10 @@
         AV_PIX_FMT_RGB0,  AV_PIX_FMT_BGR0,
         AV_PIX_FMT_NONE
     };
-
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static int config_output(AVFilterLink *outlink)
diff --git a/libavfilter/vf_colormatrix.c b/libavfilter/vf_colormatrix.c
index df78391..fde4b89 100644
--- a/libavfilter/vf_colormatrix.c
+++ b/libavfilter/vf_colormatrix.c
@@ -68,11 +68,22 @@
     const AVClass *class;
     int yuv_convert[16][3][3];
     int interlaced;
-    enum ColorMode source, dest;
+    int source, dest;        ///< ColorMode
     int mode;
     int hsub, vsub;
 } ColorMatrixContext;
 
+typedef struct ThreadData {
+    AVFrame *dst;
+    const AVFrame *src;
+    int c2;
+    int c3;
+    int c4;
+    int c5;
+    int c6;
+    int c7;
+} ThreadData;
+
 #define OFFSET(x) offsetof(ColorMatrixContext, x)
 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
 
@@ -82,6 +93,8 @@
     { "bt709",     "set BT.709 colorspace",      0, AV_OPT_TYPE_CONST, {.i64=COLOR_MODE_BT709},       .flags=FLAGS, .unit="color_mode" },
     { "fcc",       "set FCC colorspace   ",      0, AV_OPT_TYPE_CONST, {.i64=COLOR_MODE_FCC},         .flags=FLAGS, .unit="color_mode" },
     { "bt601",     "set BT.601 colorspace",      0, AV_OPT_TYPE_CONST, {.i64=COLOR_MODE_BT601},       .flags=FLAGS, .unit="color_mode" },
+    { "bt470",     "set BT.470 colorspace",      0, AV_OPT_TYPE_CONST, {.i64=COLOR_MODE_BT601},       .flags=FLAGS, .unit="color_mode" },
+    { "smpte170m", "set SMTPE-170M colorspace",  0, AV_OPT_TYPE_CONST, {.i64=COLOR_MODE_BT601},       .flags=FLAGS, .unit="color_mode" },
     { "smpte240m", "set SMPTE-240M colorspace",  0, AV_OPT_TYPE_CONST, {.i64=COLOR_MODE_SMPTE240M},   .flags=FLAGS, .unit="color_mode" },
     { NULL }
 };
@@ -177,24 +190,28 @@
     return 0;
 }
 
-static void process_frame_uyvy422(ColorMatrixContext *color,
-                                  AVFrame *dst, AVFrame *src)
+static int process_slice_uyvy422(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
 {
-    const unsigned char *srcp = src->data[0];
-    const int src_pitch = src->linesize[0];
+    const ThreadData *td = arg;
+    const AVFrame *src = td->src;
+    AVFrame *dst = td->dst;
     const int height = src->height;
     const int width = src->width*2;
-    unsigned char *dstp = dst->data[0];
+    const int src_pitch = src->linesize[0];
     const int dst_pitch = dst->linesize[0];
-    const int c2 = color->yuv_convert[color->mode][0][1];
-    const int c3 = color->yuv_convert[color->mode][0][2];
-    const int c4 = color->yuv_convert[color->mode][1][1];
-    const int c5 = color->yuv_convert[color->mode][1][2];
-    const int c6 = color->yuv_convert[color->mode][2][1];
-    const int c7 = color->yuv_convert[color->mode][2][2];
+    const int slice_start = (height *  jobnr   ) / nb_jobs;
+    const int slice_end   = (height * (jobnr+1)) / nb_jobs;
+    const unsigned char *srcp = src->data[0] + slice_start * src_pitch;
+    unsigned char *dstp = dst->data[0] + slice_start * dst_pitch;
+    const int c2 = td->c2;
+    const int c3 = td->c3;
+    const int c4 = td->c4;
+    const int c5 = td->c5;
+    const int c6 = td->c6;
+    const int c7 = td->c7;
     int x, y;
 
-    for (y = 0; y < height; y++) {
+    for (y = slice_start; y < slice_end; y++) {
         for (x = 0; x < width; x += 4) {
             const int u = srcp[x + 0] - 128;
             const int v = srcp[x + 2] - 128;
@@ -207,32 +224,38 @@
         srcp += src_pitch;
         dstp += dst_pitch;
     }
+
+    return 0;
 }
 
-static void process_frame_yuv422p(ColorMatrixContext *color,
-                                  AVFrame *dst, AVFrame *src)
+static int process_slice_yuv422p(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
 {
-    const unsigned char *srcpU = src->data[1];
-    const unsigned char *srcpV = src->data[2];
-    const unsigned char *srcpY = src->data[0];
-    const int src_pitchY  = src->linesize[0];
-    const int src_pitchUV = src->linesize[1];
+    const ThreadData *td = arg;
+    const AVFrame *src = td->src;
+    AVFrame *dst = td->dst;
     const int height = src->height;
     const int width = src->width;
-    unsigned char *dstpU = dst->data[1];
-    unsigned char *dstpV = dst->data[2];
-    unsigned char *dstpY = dst->data[0];
+    const int slice_start = (height *  jobnr   ) / nb_jobs;
+    const int slice_end   = (height * (jobnr+1)) / nb_jobs;
+    const int src_pitchY  = src->linesize[0];
+    const int src_pitchUV = src->linesize[1];
+    const unsigned char *srcpU = src->data[1] + slice_start * src_pitchUV;
+    const unsigned char *srcpV = src->data[2] + slice_start * src_pitchUV;
+    const unsigned char *srcpY = src->data[0] + slice_start * src_pitchY;
     const int dst_pitchY  = dst->linesize[0];
     const int dst_pitchUV = dst->linesize[1];
-    const int c2 = color->yuv_convert[color->mode][0][1];
-    const int c3 = color->yuv_convert[color->mode][0][2];
-    const int c4 = color->yuv_convert[color->mode][1][1];
-    const int c5 = color->yuv_convert[color->mode][1][2];
-    const int c6 = color->yuv_convert[color->mode][2][1];
-    const int c7 = color->yuv_convert[color->mode][2][2];
+    unsigned char *dstpU = dst->data[1] + slice_start * dst_pitchUV;
+    unsigned char *dstpV = dst->data[2] + slice_start * dst_pitchUV;
+    unsigned char *dstpY = dst->data[0] + slice_start * dst_pitchY;
+    const int c2 = td->c2;
+    const int c3 = td->c3;
+    const int c4 = td->c4;
+    const int c5 = td->c5;
+    const int c6 = td->c6;
+    const int c7 = td->c7;
     int x, y;
 
-    for (y = 0; y < height; y++) {
+    for (y = slice_start; y < slice_end; y++) {
         for (x = 0; x < width; x += 2) {
             const int u = srcpU[x >> 1] - 128;
             const int v = srcpV[x >> 1] - 128;
@@ -249,34 +272,40 @@
         dstpU += dst_pitchUV;
         dstpV += dst_pitchUV;
     }
+
+    return 0;
 }
 
-static void process_frame_yuv420p(ColorMatrixContext *color,
-                                  AVFrame *dst, AVFrame *src)
+static int process_slice_yuv420p(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
 {
-    const unsigned char *srcpU = src->data[1];
-    const unsigned char *srcpV = src->data[2];
-    const unsigned char *srcpY = src->data[0];
-    const unsigned char *srcpN = src->data[0] + src->linesize[0];
+    const ThreadData *td = arg;
+    const AVFrame *src = td->src;
+    AVFrame *dst = td->dst;
+    const int height = FFALIGN(src->height, 2) >> 1;
+    const int width = src->width;
+    const int slice_start = ((height *  jobnr   ) / nb_jobs) << 1;
+    const int slice_end   = ((height * (jobnr+1)) / nb_jobs) << 1;
     const int src_pitchY  = src->linesize[0];
     const int src_pitchUV = src->linesize[1];
-    const int height = src->height;
-    const int width = src->width;
-    unsigned char *dstpU = dst->data[1];
-    unsigned char *dstpV = dst->data[2];
-    unsigned char *dstpY = dst->data[0];
-    unsigned char *dstpN = dst->data[0] + dst->linesize[0];
     const int dst_pitchY  = dst->linesize[0];
     const int dst_pitchUV = dst->linesize[1];
-    const int c2 = color->yuv_convert[color->mode][0][1];
-    const int c3 = color->yuv_convert[color->mode][0][2];
-    const int c4 = color->yuv_convert[color->mode][1][1];
-    const int c5 = color->yuv_convert[color->mode][1][2];
-    const int c6 = color->yuv_convert[color->mode][2][1];
-    const int c7 = color->yuv_convert[color->mode][2][2];
+    const unsigned char *srcpY = src->data[0] + src_pitchY * slice_start;
+    const unsigned char *srcpU = src->data[1] + src_pitchUV * (slice_start >> 1);
+    const unsigned char *srcpV = src->data[2] + src_pitchUV * (slice_start >> 1);
+    const unsigned char *srcpN = src->data[0] + src_pitchY * (slice_start + 1);
+    unsigned char *dstpU = dst->data[1] + dst_pitchUV * (slice_start >> 1);
+    unsigned char *dstpV = dst->data[2] + dst_pitchUV * (slice_start >> 1);
+    unsigned char *dstpY = dst->data[0] + dst_pitchY * slice_start;
+    unsigned char *dstpN = dst->data[0] + dst_pitchY * (slice_start + 1);
+    const int c2 = td->c2;
+    const int c3 = td->c3;
+    const int c4 = td->c4;
+    const int c5 = td->c5;
+    const int c6 = td->c6;
+    const int c7 = td->c7;
     int x, y;
 
-    for (y = 0; y < height; y += 2) {
+    for (y = slice_start; y < slice_end; y += 2) {
         for (x = 0; x < width; x += 2) {
             const int u = srcpU[x >> 1] - 128;
             const int v = srcpV[x >> 1] - 128;
@@ -297,6 +326,8 @@
         dstpU += dst_pitchUV;
         dstpV += dst_pitchUV;
     }
+
+    return 0;
 }
 
 static int config_input(AVFilterLink *inlink)
@@ -322,10 +353,10 @@
         AV_PIX_FMT_UYVY422,
         AV_PIX_FMT_NONE
     };
-
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static int filter_frame(AVFilterLink *link, AVFrame *in)
@@ -334,6 +365,7 @@
     ColorMatrixContext *color = ctx->priv;
     AVFilterLink *outlink = ctx->outputs[0];
     AVFrame *out;
+    ThreadData td = {0};
 
     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
     if (!out) {
@@ -351,6 +383,7 @@
         case AVCOL_SPC_FCC       : source = COLOR_MODE_FCC       ; break;
         case AVCOL_SPC_SMPTE240M : source = COLOR_MODE_SMPTE240M ; break;
         case AVCOL_SPC_BT470BG   : source = COLOR_MODE_BT601     ; break;
+        case AVCOL_SPC_SMPTE170M : source = COLOR_MODE_BT601     ; break;
         default :
             av_log(ctx, AV_LOG_ERROR, "Input frame does not specify a supported colorspace, and none has been specified as source either\n");
             av_frame_free(&out);
@@ -369,12 +402,24 @@
 
     calc_coefficients(ctx);
 
+    td.src = in;
+    td.dst = out;
+    td.c2 = color->yuv_convert[color->mode][0][1];
+    td.c3 = color->yuv_convert[color->mode][0][2];
+    td.c4 = color->yuv_convert[color->mode][1][1];
+    td.c5 = color->yuv_convert[color->mode][1][2];
+    td.c6 = color->yuv_convert[color->mode][2][1];
+    td.c7 = color->yuv_convert[color->mode][2][2];
+
     if (in->format == AV_PIX_FMT_YUV422P)
-        process_frame_yuv422p(color, out, in);
+        ctx->internal->execute(ctx, process_slice_yuv422p, &td, NULL,
+                               FFMIN(in->height, ctx->graph->nb_threads));
     else if (in->format == AV_PIX_FMT_YUV420P)
-        process_frame_yuv420p(color, out, in);
+        ctx->internal->execute(ctx, process_slice_yuv420p, &td, NULL,
+                               FFMIN(in->height / 2, ctx->graph->nb_threads));
     else
-        process_frame_uyvy422(color, out, in);
+        ctx->internal->execute(ctx, process_slice_uyvy422, &td, NULL,
+                               FFMIN(in->height, ctx->graph->nb_threads));
 
     av_frame_free(&in);
     return ff_filter_frame(outlink, out);
@@ -407,5 +452,5 @@
     .inputs        = colormatrix_inputs,
     .outputs       = colormatrix_outputs,
     .priv_class    = &colormatrix_class,
-    .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
+    .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SLICE_THREADS,
 };
diff --git a/libavfilter/vf_curves.c b/libavfilter/vf_curves.c
index b17c391..1c51c1b 100644
--- a/libavfilter/vf_curves.c
+++ b/libavfilter/vf_curves.c
@@ -60,7 +60,7 @@
 
 typedef struct {
     const AVClass *class;
-    enum preset preset;
+    int preset;
     char *comp_points_str[NB_COMP + 1];
     char *comp_points_str_all;
     uint8_t graph[NB_COMP + 1][256];
@@ -464,8 +464,10 @@
         AV_PIX_FMT_RGB0,   AV_PIX_FMT_BGR0,
         AV_PIX_FMT_NONE
     };
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static int config_input(AVFilterLink *inlink)
diff --git a/libavfilter/vf_dctdnoiz.c b/libavfilter/vf_dctdnoiz.c
index 5cce9cb..37306bb 100644
--- a/libavfilter/vf_dctdnoiz.c
+++ b/libavfilter/vf_dctdnoiz.c
@@ -513,9 +513,9 @@
 
     s->p_linesize = linesize = FFALIGN(s->pr_width, 32);
     for (i = 0; i < 2; i++) {
-        s->cbuf[i][0] = av_malloc(linesize * s->pr_height * sizeof(*s->cbuf[i][0]));
-        s->cbuf[i][1] = av_malloc(linesize * s->pr_height * sizeof(*s->cbuf[i][1]));
-        s->cbuf[i][2] = av_malloc(linesize * s->pr_height * sizeof(*s->cbuf[i][2]));
+        s->cbuf[i][0] = av_malloc_array(linesize * s->pr_height, sizeof(*s->cbuf[i][0]));
+        s->cbuf[i][1] = av_malloc_array(linesize * s->pr_height, sizeof(*s->cbuf[i][1]));
+        s->cbuf[i][2] = av_malloc_array(linesize * s->pr_height, sizeof(*s->cbuf[i][2]));
         if (!s->cbuf[i][0] || !s->cbuf[i][1] || !s->cbuf[i][2])
             return AVERROR(ENOMEM);
     }
@@ -534,7 +534,7 @@
     /* each slice will need to (pre & re)process the top and bottom block of
      * the previous one in in addition to its processing area. This is because
      * each pixel is averaged by all the surrounding blocks */
-    slice_h = (int)ceilf(s->pr_height / s->nb_threads) + (s->bsize - 1) * 2;
+    slice_h = (int)ceilf(s->pr_height / (float)s->nb_threads) + (s->bsize - 1) * 2;
     for (i = 0; i < s->nb_threads; i++) {
         s->slices[i] = av_malloc_array(linesize, slice_h * sizeof(*s->slices[i]));
         if (!s->slices[i])
@@ -600,8 +600,10 @@
         AV_PIX_FMT_BGR24, AV_PIX_FMT_RGB24,
         AV_PIX_FMT_NONE
     };
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 typedef struct ThreadData {
diff --git a/libavfilter/vf_decimate.c b/libavfilter/vf_decimate.c
index ffb9320..70357ea 100644
--- a/libavfilter/vf_decimate.c
+++ b/libavfilter/vf_decimate.c
@@ -350,8 +350,10 @@
         AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY16,
         AV_PIX_FMT_NONE
     };
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static int config_output(AVFilterLink *outlink)
diff --git a/libavfilter/vf_delogo.c b/libavfilter/vf_delogo.c
index 6ccdfb2..50a548b 100644
--- a/libavfilter/vf_delogo.c
+++ b/libavfilter/vf_delogo.c
@@ -177,9 +177,10 @@
         AV_PIX_FMT_YUVA420P, AV_PIX_FMT_GRAY8,
         AV_PIX_FMT_NONE
     };
-
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static av_cold int init(AVFilterContext *ctx)
diff --git a/libavfilter/vf_deshake.c b/libavfilter/vf_deshake.c
index b5d5457..cd06ee7 100644
--- a/libavfilter/vf_deshake.c
+++ b/libavfilter/vf_deshake.c
@@ -396,10 +396,10 @@
         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));
-
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static int config_props(AVFilterLink *link)
diff --git a/libavfilter/vf_drawbox.c b/libavfilter/vf_drawbox.c
index 115df88..35a08e8 100644
--- a/libavfilter/vf_drawbox.c
+++ b/libavfilter/vf_drawbox.c
@@ -47,6 +47,7 @@
     "h",              ///< height of the rendered box
     "w",              ///< width  of the rendered box
     "t",
+    "max",
     NULL
 };
 
@@ -63,6 +64,7 @@
     VAR_H,
     VAR_W,
     VAR_T,
+    VAR_MAX,
     VARS_NB
 };
 
@@ -110,9 +112,10 @@
         AV_PIX_FMT_YUV440P,  AV_PIX_FMT_YUVJ440P,
         AV_PIX_FMT_NONE
     };
-
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static int config_input(AVFilterLink *inlink)
@@ -142,30 +145,35 @@
 
     for (i = 0; i <= NUM_EXPR_EVALS; i++) {
         /* evaluate expressions, fail on last iteration */
+        var_values[VAR_MAX] = inlink->w;
         if ((ret = av_expr_parse_and_eval(&res, (expr = s->x_expr),
                                           var_names, var_values,
                                           NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0 && i == NUM_EXPR_EVALS)
             goto fail;
         s->x = var_values[VAR_X] = res;
 
+        var_values[VAR_MAX] = inlink->h;
         if ((ret = av_expr_parse_and_eval(&res, (expr = s->y_expr),
                                           var_names, var_values,
                                           NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0 && i == NUM_EXPR_EVALS)
             goto fail;
         s->y = var_values[VAR_Y] = res;
 
+        var_values[VAR_MAX] = inlink->w - s->x;
         if ((ret = av_expr_parse_and_eval(&res, (expr = s->w_expr),
                                           var_names, var_values,
                                           NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0 && i == NUM_EXPR_EVALS)
             goto fail;
         s->w = var_values[VAR_W] = res;
 
+        var_values[VAR_MAX] = inlink->h - s->y;
         if ((ret = av_expr_parse_and_eval(&res, (expr = s->h_expr),
                                           var_names, var_values,
                                           NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0 && i == NUM_EXPR_EVALS)
             goto fail;
         s->h = var_values[VAR_H] = res;
 
+        var_values[VAR_MAX] = INT_MAX;
         if ((ret = av_expr_parse_and_eval(&res, (expr = s->t_expr),
                                           var_names, var_values,
                                           NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0 && i == NUM_EXPR_EVALS)
diff --git a/libavfilter/vf_drawtext.c b/libavfilter/vf_drawtext.c
index d20f805..cf24d96 100644
--- a/libavfilter/vf_drawtext.c
+++ b/libavfilter/vf_drawtext.c
@@ -136,7 +136,7 @@
 
 typedef struct DrawTextContext {
     const AVClass *class;
-    enum expansion_mode exp_mode;   ///< expansion mode to use for the text
+    int exp_mode;                   ///< expansion mode to use for the text
     int reinit;                     ///< tells if the filter is being reinited
 #if CONFIG_LIBFONTCONFIG
     uint8_t *font;              ///< font to be used
diff --git a/libavfilter/vf_edgedetect.c b/libavfilter/vf_edgedetect.c
index a4e8d18..ac88e02 100644
--- a/libavfilter/vf_edgedetect.c
+++ b/libavfilter/vf_edgedetect.c
@@ -50,7 +50,7 @@
     int nb_planes;
     double   low, high;
     uint8_t  low_u8, high_u8;
-    enum FilterMode mode;
+    int mode;
 } EdgeDetectContext;
 
 #define OFFSET(x) offsetof(EdgeDetectContext, x)
@@ -78,17 +78,22 @@
 static int query_formats(AVFilterContext *ctx)
 {
     const EdgeDetectContext *edgedetect = ctx->priv;
+    static const enum AVPixelFormat wires_pix_fmts[] = {AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE};
+    static const enum AVPixelFormat colormix_pix_fmts[] = {AV_PIX_FMT_GBRP, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE};
+    AVFilterFormats *fmts_list;
+    const enum AVPixelFormat *pix_fmts = NULL;
 
     if (edgedetect->mode == MODE_WIRES) {
-        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));
+        pix_fmts = wires_pix_fmts;
     } else if (edgedetect->mode == MODE_COLORMIX) {
-        static const enum AVPixelFormat pix_fmts[] = {AV_PIX_FMT_GBRP, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE};
-        ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
+        pix_fmts = colormix_pix_fmts;
     } else {
         av_assert0(0);
     }
-    return 0;
+    fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static int config_props(AVFilterLink *inlink)
diff --git a/libavfilter/vf_elbg.c b/libavfilter/vf_elbg.c
index be0885d..8656070 100644
--- a/libavfilter/vf_elbg.c
+++ b/libavfilter/vf_elbg.c
@@ -75,15 +75,15 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
+    static const 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_NONE
     };
-
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 #define NB_COMPONENTS 3
diff --git a/libavfilter/vf_eq.c b/libavfilter/vf_eq.c
index ad2a37e..f8b8160 100644
--- a/libavfilter/vf_eq.c
+++ b/libavfilter/vf_eq.c
@@ -27,11 +27,6 @@
  * very simple video equalizer
  */
 
-/**
- * TODO:
- * - Add support to process_command
- */
-
 #include "libavfilter/internal.h"
 #include "libavutil/common.h"
 #include "libavutil/imgutils.h"
@@ -111,6 +106,7 @@
 
 static void set_contrast(EQContext *eq)
 {
+    eq->contrast = av_clipf(av_expr_eval(eq->contrast_pexpr, eq->var_values, eq), -2.0, 2.0);
     eq->param[0].contrast = eq->contrast;
     eq->param[0].lut_clean = 0;
     check_values(&eq->param[0], eq);
@@ -118,6 +114,7 @@
 
 static void set_brightness(EQContext *eq)
 {
+    eq->brightness = av_clipf(av_expr_eval(eq->brightness_pexpr, eq->var_values, eq), -1.0, 1.0);
     eq->param[0].brightness = eq->brightness;
     eq->param[0].lut_clean = 0;
     check_values(&eq->param[0], eq);
@@ -126,6 +123,13 @@
 static void set_gamma(EQContext *eq)
 {
     int i;
+
+    eq->gamma        = av_clipf(av_expr_eval(eq->gamma_pexpr,        eq->var_values, eq), 0.1, 10.0);
+    eq->gamma_r      = av_clipf(av_expr_eval(eq->gamma_r_pexpr,      eq->var_values, eq), 0.1, 10.0);
+    eq->gamma_g      = av_clipf(av_expr_eval(eq->gamma_g_pexpr,      eq->var_values, eq), 0.1, 10.0);
+    eq->gamma_b      = av_clipf(av_expr_eval(eq->gamma_b_pexpr,      eq->var_values, eq), 0.1, 10.0);
+    eq->gamma_weight = av_clipf(av_expr_eval(eq->gamma_weight_pexpr, eq->var_values, eq), 0.0,  1.0);
+
     eq->param[0].gamma = eq->gamma * eq->gamma_g;
     eq->param[1].gamma = sqrt(eq->gamma_b / eq->gamma_g);
     eq->param[2].gamma = sqrt(eq->gamma_r / eq->gamma_g);
@@ -140,6 +144,9 @@
 static void set_saturation(EQContext *eq)
 {
     int i;
+
+    eq->saturation = av_clipf(av_expr_eval(eq->saturation_pexpr, eq->var_values, eq), 0.0, 3.0);
+
     for (i = 1; i < 3; i++) {
         eq->param[i].contrast = eq->saturation;
         eq->param[i].lut_clean = 0;
@@ -147,19 +154,77 @@
     }
 }
 
+static int set_expr(AVExpr **pexpr, const char *expr, const char *option, void *log_ctx)
+{
+    int ret;
+    AVExpr *old = NULL;
+
+    if (*pexpr)
+        old = *pexpr;
+    ret = av_expr_parse(pexpr, expr, var_names, NULL, NULL, NULL, NULL, 0, log_ctx);
+    if (ret < 0) {
+        av_log(log_ctx, AV_LOG_ERROR,
+               "Error when parsing the expression '%s' for %s\n",
+               expr, option);
+        *pexpr = old;
+        return ret;
+    }
+
+    av_expr_free(old);
+    return 0;
+}
+
 static int initialize(AVFilterContext *ctx)
 {
     EQContext *eq = ctx->priv;
+    int ret;
 
     eq->process = process_c;
 
+    if ((ret = set_expr(&eq->contrast_pexpr,     eq->contrast_expr,     "contrast",     ctx)) < 0 ||
+        (ret = set_expr(&eq->brightness_pexpr,   eq->brightness_expr,   "brightness",   ctx)) < 0 ||
+        (ret = set_expr(&eq->saturation_pexpr,   eq->saturation_expr,   "saturation",   ctx)) < 0 ||
+        (ret = set_expr(&eq->gamma_pexpr,        eq->gamma_expr,        "gamma",        ctx)) < 0 ||
+        (ret = set_expr(&eq->gamma_r_pexpr,      eq->gamma_r_expr,      "gamma_r",      ctx)) < 0 ||
+        (ret = set_expr(&eq->gamma_g_pexpr,      eq->gamma_g_expr,      "gamma_g",      ctx)) < 0 ||
+        (ret = set_expr(&eq->gamma_b_pexpr,      eq->gamma_b_expr,      "gamma_b",      ctx)) < 0 ||
+        (ret = set_expr(&eq->gamma_weight_pexpr, eq->gamma_weight_expr, "gamma_weight", ctx)) < 0 )
+        return ret;
+
     if (ARCH_X86)
         ff_eq_init_x86(eq);
 
-    set_gamma(eq);
-    set_contrast(eq);
-    set_brightness(eq);
-    set_saturation(eq);
+    if (eq->eval_mode == EVAL_MODE_INIT) {
+        set_gamma(eq);
+        set_contrast(eq);
+        set_brightness(eq);
+        set_saturation(eq);
+    }
+
+    return 0;
+}
+
+static void uninit(AVFilterContext *ctx)
+{
+    EQContext *eq = ctx->priv;
+
+    av_expr_free(eq->contrast_pexpr);     eq->contrast_pexpr     = NULL;
+    av_expr_free(eq->brightness_pexpr);   eq->brightness_pexpr   = NULL;
+    av_expr_free(eq->saturation_pexpr);   eq->saturation_pexpr   = NULL;
+    av_expr_free(eq->gamma_pexpr);        eq->gamma_pexpr        = NULL;
+    av_expr_free(eq->gamma_weight_pexpr); eq->gamma_weight_pexpr = NULL;
+    av_expr_free(eq->gamma_r_pexpr);      eq->gamma_r_pexpr      = NULL;
+    av_expr_free(eq->gamma_g_pexpr);      eq->gamma_g_pexpr      = NULL;
+    av_expr_free(eq->gamma_b_pexpr);      eq->gamma_b_pexpr      = NULL;
+}
+
+static int config_props(AVFilterLink *inlink)
+{
+    EQContext *eq = inlink->dst->priv;
+
+    eq->var_values[VAR_N] = 0;
+    eq->var_values[VAR_R] = inlink->frame_rate.num == 0 || inlink->frame_rate.den == 0 ?
+        NAN : av_q2d(inlink->frame_rate);
 
     return 0;
 }
@@ -175,18 +240,21 @@
         AV_PIX_FMT_YUV444P,
         AV_PIX_FMT_NONE
     };
-
-    ff_set_common_formats(ctx, ff_make_format_list(pixel_fmts_eq));
-
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pixel_fmts_eq);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
+#define TS2T(ts, tb) ((ts) == AV_NOPTS_VALUE ? NAN : (double)(ts) * av_q2d(tb))
+
 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
 {
     AVFilterContext *ctx = inlink->dst;
     AVFilterLink *outlink = inlink->dst->outputs[0];
     EQContext *eq = ctx->priv;
     AVFrame *out;
+    int64_t pos = av_frame_get_pkt_pos(in);
     const AVPixFmtDescriptor *desc;
     int i;
 
@@ -197,6 +265,17 @@
     av_frame_copy_props(out, in);
     desc = av_pix_fmt_desc_get(inlink->format);
 
+    eq->var_values[VAR_N]   = inlink->frame_count;
+    eq->var_values[VAR_POS] = pos == -1 ? NAN : pos;
+    eq->var_values[VAR_T]   = TS2T(in->pts, inlink->time_base);
+
+    if (eq->eval_mode == EVAL_MODE_FRAME) {
+        set_gamma(eq);
+        set_contrast(eq);
+        set_brightness(eq);
+        set_saturation(eq);
+    }
+
     for (i = 0; i < desc->nb_components; i++) {
         int w = inlink->w;
         int h = inlink->h;
@@ -217,11 +296,44 @@
     av_frame_free(&in);
     return ff_filter_frame(outlink, out);
 }
+
+static inline int set_param(AVExpr **pexpr, const char *args, const char *cmd,
+                            void (*set_fn)(EQContext *eq), AVFilterContext *ctx)
+{
+    EQContext *eq = ctx->priv;
+    int ret;
+    if ((ret = set_expr(pexpr, args, cmd, ctx)) < 0)
+        return ret;
+    if (eq->eval_mode == EVAL_MODE_INIT)
+        set_fn(eq);
+    return 0;
+}
+
+static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
+                           char *res, int res_len, int flags)
+{
+    EQContext *eq = ctx->priv;
+
+#define SET_PARAM(param_name, set_fn_name)                              \
+    if (!strcmp(cmd, #param_name)) return set_param(&eq->param_name##_pexpr, args, cmd, set_##set_fn_name, ctx);
+
+         SET_PARAM(contrast, contrast)
+    else SET_PARAM(brightness, brightness)
+    else SET_PARAM(saturation, saturation)
+    else SET_PARAM(gamma, gamma)
+    else SET_PARAM(gamma_r, gamma)
+    else SET_PARAM(gamma_g, gamma)
+    else SET_PARAM(gamma_b, gamma)
+    else SET_PARAM(gamma_weight, gamma)
+    else return AVERROR(ENOSYS);
+}
+
 static const AVFilterPad eq_inputs[] = {
     {
         .name = "default",
         .type = AVMEDIA_TYPE_VIDEO,
         .filter_frame = filter_frame,
+        .config_props = config_props,
     },
     { NULL }
 };
@@ -239,33 +351,38 @@
 
 static const AVOption eq_options[] = {
     { "contrast",     "set the contrast adjustment, negative values give a negative image",
-        OFFSET(contrast),     AV_OPT_TYPE_DOUBLE, {.dbl = 1.0}, -2.0, 2.0, FLAGS },
+        OFFSET(contrast_expr),     AV_OPT_TYPE_STRING, {.str = "1.0"}, CHAR_MIN, CHAR_MAX, FLAGS },
     { "brightness",   "set the brightness adjustment",
-        OFFSET(brightness),   AV_OPT_TYPE_DOUBLE, {.dbl = 0.0}, -1.0, 1.0, FLAGS },
+        OFFSET(brightness_expr),   AV_OPT_TYPE_STRING, {.str = "0.0"}, CHAR_MIN, CHAR_MAX, FLAGS },
     { "saturation",   "set the saturation adjustment",
-        OFFSET(saturation),   AV_OPT_TYPE_DOUBLE, {.dbl = 1.0},  0.0, 3.0, FLAGS },
+        OFFSET(saturation_expr),   AV_OPT_TYPE_STRING, {.str = "1.0"}, CHAR_MIN, CHAR_MAX, FLAGS },
     { "gamma",        "set the initial gamma value",
-        OFFSET(gamma),        AV_OPT_TYPE_DOUBLE, {.dbl = 1.0},  0.1, 10.0, FLAGS },
+        OFFSET(gamma_expr),        AV_OPT_TYPE_STRING, {.str = "1.0"}, CHAR_MIN, CHAR_MAX, FLAGS },
     { "gamma_r",      "gamma value for red",
-        OFFSET(gamma_r),      AV_OPT_TYPE_DOUBLE, {.dbl = 1.0},  0.1, 10.0, FLAGS },
+        OFFSET(gamma_r_expr),      AV_OPT_TYPE_STRING, {.str = "1.0"}, CHAR_MIN, CHAR_MAX, FLAGS },
     { "gamma_g",      "gamma value for green",
-        OFFSET(gamma_g),      AV_OPT_TYPE_DOUBLE, {.dbl = 1.0},  0.1, 10.0, FLAGS },
+        OFFSET(gamma_g_expr),      AV_OPT_TYPE_STRING, {.str = "1.0"}, CHAR_MIN, CHAR_MAX, FLAGS },
     { "gamma_b",      "gamma value for blue",
-        OFFSET(gamma_b),      AV_OPT_TYPE_DOUBLE, {.dbl = 1.0},  0.1, 10.0, FLAGS },
+        OFFSET(gamma_b_expr),      AV_OPT_TYPE_STRING, {.str = "1.0"}, CHAR_MIN, CHAR_MAX, FLAGS },
     { "gamma_weight", "set the gamma weight which reduces the effect of gamma on bright areas",
-        OFFSET(gamma_weight), AV_OPT_TYPE_DOUBLE, {.dbl = 1.0},  0.0, 1.0, FLAGS },
+        OFFSET(gamma_weight_expr), AV_OPT_TYPE_STRING, {.str = "1.0"}, CHAR_MIN, CHAR_MAX, FLAGS },
+    { "eval", "specify when to evaluate expressions", OFFSET(eval_mode), AV_OPT_TYPE_INT, {.i64 = EVAL_MODE_INIT}, 0, EVAL_MODE_NB-1, FLAGS, "eval" },
+         { "init",  "eval expressions once during initialization", 0, AV_OPT_TYPE_CONST, {.i64=EVAL_MODE_INIT},  .flags = FLAGS, .unit = "eval" },
+         { "frame", "eval expressions per-frame",                  0, AV_OPT_TYPE_CONST, {.i64=EVAL_MODE_FRAME}, .flags = FLAGS, .unit = "eval" },
     { NULL }
 };
 
 AVFILTER_DEFINE_CLASS(eq);
 
 AVFilter ff_vf_eq = {
-    .name          = "eq",
-    .description   = NULL_IF_CONFIG_SMALL("Adjust brightness, contrast, gamma, and saturation."),
-    .priv_size     = sizeof(EQContext),
-    .priv_class    = &eq_class,
-    .inputs        = eq_inputs,
-    .outputs       = eq_outputs,
-    .query_formats = query_formats,
-    .init          = initialize,
+    .name            = "eq",
+    .description     = NULL_IF_CONFIG_SMALL("Adjust brightness, contrast, gamma, and saturation."),
+    .priv_size       = sizeof(EQContext),
+    .priv_class      = &eq_class,
+    .inputs          = eq_inputs,
+    .outputs         = eq_outputs,
+    .process_command = process_command,
+    .query_formats   = query_formats,
+    .init            = initialize,
+    .uninit          = uninit,
 };
diff --git a/libavfilter/vf_eq.h b/libavfilter/vf_eq.h
index 7e7c054..8525048 100644
--- a/libavfilter/vf_eq.h
+++ b/libavfilter/vf_eq.h
@@ -26,6 +26,23 @@
 #define AVFILTER_EQ_H
 
 #include "avfilter.h"
+#include "libavutil/eval.h"
+
+static const char *const var_names[] = {
+    "n",   // frame count
+    "pos", // frame position
+    "r",   // frame rate
+    "t",   // timestamp expressed in seconds
+    NULL
+};
+
+enum var_name {
+    VAR_N,
+    VAR_POS,
+    VAR_R,
+    VAR_T,
+    VAR_NB
+};
 
 typedef struct EQParameters {
     void (*adjust)(struct EQParameters *eq, uint8_t *dst, int dst_stride,
@@ -35,6 +52,7 @@
 
     double brightness, contrast, gamma, gamma_weight;
     int lut_clean;
+
 } EQParameters;
 
 typedef struct {
@@ -42,17 +60,44 @@
 
     EQParameters param[3];
 
-    double contrast;
-    double brightness;
-    double saturation;
+    char   *contrast_expr;
+    AVExpr *contrast_pexpr;
+    double  contrast;
 
-    double gamma;
-    double gamma_weight;
-    double gamma_r, gamma_g, gamma_b;
+    char   *brightness_expr;
+    AVExpr *brightness_pexpr;
+    double  brightness;
+
+    char   *saturation_expr;
+    AVExpr *saturation_pexpr;
+    double  saturation;
+
+    char   *gamma_expr;
+    AVExpr *gamma_pexpr;
+    double  gamma;
+
+    char   *gamma_weight_expr;
+    AVExpr *gamma_weight_pexpr;
+    double  gamma_weight;
+
+    char   *gamma_r_expr;
+    AVExpr *gamma_r_pexpr;
+    double  gamma_r;
+
+    char   *gamma_g_expr;
+    AVExpr *gamma_g_pexpr;
+    double  gamma_g;
+
+    char   *gamma_b_expr;
+    AVExpr *gamma_b_pexpr;
+    double  gamma_b;
+
+    double var_values[VAR_NB];
 
     void (*process)(struct EQParameters *par, uint8_t *dst, int dst_stride,
                     const uint8_t *src, int src_stride, int w, int h);
 
+    enum EvalMode { EVAL_MODE_INIT, EVAL_MODE_FRAME, EVAL_MODE_NB } eval_mode;
 } EQContext;
 
 void ff_eq_init_x86(EQContext *eq);
diff --git a/libavfilter/vf_fade.c b/libavfilter/vf_fade.c
index 80ce75d..a7597cd 100644
--- a/libavfilter/vf_fade.c
+++ b/libavfilter/vf_fade.c
@@ -138,7 +138,9 @@
     s->hsub = pixdesc->log2_chroma_w;
     s->vsub = pixdesc->log2_chroma_h;
 
-    s->bpp = av_get_bits_per_pixel(pixdesc) >> 3;
+    s->bpp = pixdesc->flags & AV_PIX_FMT_FLAG_PLANAR ?
+             1 :
+             av_get_bits_per_pixel(pixdesc) >> 3;
     s->alpha &= !!(pixdesc->flags & AV_PIX_FMT_FLAG_ALPHA);
     s->is_packed_rgb = ff_fill_rgba_map(s->rgba_map, inlink->format) >= 0;
 
diff --git a/libavfilter/vf_fftfilt.c b/libavfilter/vf_fftfilt.c
new file mode 100644
index 0000000..dff279c
--- /dev/null
+++ b/libavfilter/vf_fftfilt.c
@@ -0,0 +1,343 @@
+/*
+ * Copyright (c) 2015 Arwa Arif <arwaarif1994@gmail.com>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as published
+ * by the Free Software Foundation; either version 2.1 of the License,
+ * or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * FFT domain filtering.
+ */
+
+#include "libavfilter/internal.h"
+#include "libavutil/common.h"
+#include "libavutil/imgutils.h"
+#include "libavutil/opt.h"
+#include "libavutil/pixdesc.h"
+#include "libavcodec/avfft.h"
+#include "libavutil/eval.h"
+
+typedef struct {
+    const AVClass *class;
+
+    RDFTContext *rdft;
+    int rdft_hbits[3];
+    int rdft_vbits[3];
+    size_t rdft_hlen[3];
+    size_t rdft_vlen[3];
+    FFTSample *rdft_hdata[3];
+    FFTSample *rdft_vdata[3];
+
+    int dc[3];
+    char *weight_str[3];
+    AVExpr *weight_expr[3];
+    double *weight[3];
+
+} FFTFILTContext;
+
+static const char *const var_names[] = {   "X",   "Y",   "W",   "H",     NULL    };
+enum                                   { VAR_X, VAR_Y, VAR_W, VAR_H, VAR_VARS_NB };
+
+enum { Y = 0, U, V };
+
+#define OFFSET(x) offsetof(FFTFILTContext, x)
+#define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
+
+static const AVOption fftfilt_options[] = {
+    { "dc_Y",  "adjust gain in Y plane",              OFFSET(dc[Y]),      AV_OPT_TYPE_INT,    {.i64 = 0},      0,     1000,     FLAGS },
+    { "dc_U",  "adjust gain in U plane",              OFFSET(dc[U]),      AV_OPT_TYPE_INT,    {.i64 = 0},      0,     1000,     FLAGS },
+    { "dc_V",  "adjust gain in V plane",              OFFSET(dc[V]),      AV_OPT_TYPE_INT,    {.i64 = 0},      0,     1000,     FLAGS },
+    { "weight_Y", "set luminance expression in Y plane",   OFFSET(weight_str[Y]), AV_OPT_TYPE_STRING, {.str = "1"}, CHAR_MIN, CHAR_MAX, FLAGS },
+    { "weight_U", "set chrominance expression in U plane", OFFSET(weight_str[U]), AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX, FLAGS },
+    { "weight_V", "set chrominance expression in V plane", OFFSET(weight_str[V]), AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX, FLAGS },
+    {NULL},
+};
+
+AVFILTER_DEFINE_CLASS(fftfilt);
+
+static inline double lum(void *priv, double x, double y, int plane)
+{
+    FFTFILTContext *fftfilt = priv;
+    return fftfilt->rdft_vdata[plane][(int)x * fftfilt->rdft_vlen[plane] + (int)y];
+}
+
+static double weight_Y(void *priv, double x, double y) { return lum(priv, x, y, Y); }
+static double weight_U(void *priv, double x, double y) { return lum(priv, x, y, U); }
+static double weight_V(void *priv, double x, double y) { return lum(priv, x, y, V); }
+
+static void copy_rev (FFTSample *dest, int w, int w2)
+{
+    int i;
+
+    for (i = w; i < w + (w2-w)/2; i++)
+        dest[i] = dest[2*w - i - 1];
+
+    for (; i < w2; i++)
+        dest[i] = dest[w2 - i];
+}
+
+/*Horizontal pass - RDFT*/
+static void rdft_horizontal(FFTFILTContext *fftfilt, AVFrame *in, int w, int h, int plane)
+{
+    int i, j;
+    fftfilt->rdft = av_rdft_init(fftfilt->rdft_hbits[plane], DFT_R2C);
+
+    for (i = 0; i < h; i++) {
+        for (j = 0; j < w; j++)
+            fftfilt->rdft_hdata[plane][i * fftfilt->rdft_hlen[plane] + j] = *(in->data[plane] + in->linesize[plane] * i + j);
+
+        copy_rev(fftfilt->rdft_hdata[plane] + i * fftfilt->rdft_hlen[plane], w, fftfilt->rdft_hlen[plane]);
+    }
+
+    for (i = 0; i < h; i++)
+        av_rdft_calc(fftfilt->rdft, fftfilt->rdft_hdata[plane] + i * fftfilt->rdft_hlen[plane]);
+
+    av_rdft_end(fftfilt->rdft);
+}
+
+/*Vertical pass - RDFT*/
+static void rdft_vertical(FFTFILTContext *fftfilt, int h, int plane)
+{
+    int i, j;
+    fftfilt->rdft = av_rdft_init(fftfilt->rdft_vbits[plane], DFT_R2C);
+
+    for (i = 0; i < fftfilt->rdft_hlen[plane]; i++) {
+        for (j = 0; j < h; j++)
+            fftfilt->rdft_vdata[plane][i * fftfilt->rdft_vlen[plane] + j] =
+            fftfilt->rdft_hdata[plane][j * fftfilt->rdft_hlen[plane] + i];
+        copy_rev(fftfilt->rdft_vdata[plane] + i * fftfilt->rdft_vlen[plane], h, fftfilt->rdft_vlen[plane]);
+    }
+
+    for (i = 0; i < fftfilt->rdft_hlen[plane]; i++)
+        av_rdft_calc(fftfilt->rdft, fftfilt->rdft_vdata[plane] + i * fftfilt->rdft_vlen[plane]);
+
+    av_rdft_end(fftfilt->rdft);
+}
+/*Vertical pass - IRDFT*/
+static void irdft_vertical(FFTFILTContext *fftfilt, int h, int plane)
+{
+    int i, j;
+    fftfilt->rdft = av_rdft_init(fftfilt->rdft_vbits[plane], IDFT_C2R);
+    for (i = 0; i < fftfilt->rdft_hlen[plane]; i++)
+        av_rdft_calc(fftfilt->rdft, fftfilt->rdft_vdata[plane] + i * fftfilt->rdft_vlen[plane]);
+
+    for (i = 0; i < fftfilt->rdft_hlen[plane]; i++)
+        for (j = 0; j < h; j++)
+            fftfilt->rdft_hdata[plane][j * fftfilt->rdft_hlen[plane] + i] =
+            fftfilt->rdft_vdata[plane][i * fftfilt->rdft_vlen[plane] + j];
+
+    av_rdft_end(fftfilt->rdft);
+}
+
+/*Horizontal pass - IRDFT*/
+static void irdft_horizontal(FFTFILTContext *fftfilt, AVFrame *out, int w, int h, int plane)
+{
+    int i, j;
+    fftfilt->rdft = av_rdft_init(fftfilt->rdft_hbits[plane], IDFT_C2R);
+    for (i = 0; i < h; i++)
+        av_rdft_calc(fftfilt->rdft, fftfilt->rdft_hdata[plane] + i * fftfilt->rdft_hlen[plane]);
+
+    for (i = 0; i < h; i++)
+        for (j = 0; j < w; j++)
+            *(out->data[plane] + out->linesize[plane] * i + j) = av_clip(fftfilt->rdft_hdata[plane][i
+                                                                         *fftfilt->rdft_hlen[plane] + j] * 4 /
+                                                                         (fftfilt->rdft_hlen[plane] *
+                                                                          fftfilt->rdft_vlen[plane]), 0, 255);
+
+    av_rdft_end(fftfilt->rdft);
+}
+
+static av_cold int initialize(AVFilterContext *ctx)
+{
+    FFTFILTContext *fftfilt = ctx->priv;
+    int ret = 0, plane;
+
+    if (!fftfilt->dc[U] && !fftfilt->dc[V]) {
+        fftfilt->dc[U] = fftfilt->dc[Y];
+        fftfilt->dc[V] = fftfilt->dc[Y];
+    } else {
+        if (!fftfilt->dc[U]) fftfilt->dc[U] = fftfilt->dc[V];
+        if (!fftfilt->dc[V]) fftfilt->dc[V] = fftfilt->dc[U];
+    }
+
+    if (!fftfilt->weight_str[U] && !fftfilt->weight_str[V]) {
+        fftfilt->weight_str[U] = av_strdup(fftfilt->weight_str[Y]);
+        fftfilt->weight_str[V] = av_strdup(fftfilt->weight_str[Y]);
+    } else {
+        if (!fftfilt->weight_str[U]) fftfilt->weight_str[U] = av_strdup(fftfilt->weight_str[V]);
+        if (!fftfilt->weight_str[V]) fftfilt->weight_str[V] = av_strdup(fftfilt->weight_str[U]);
+    }
+
+    for (plane = 0; plane < 3; plane++) {
+        static double (*p[])(void *, double, double) = { weight_Y, weight_U, weight_V };
+        const char *const func2_names[] = {"weight_Y", "weight_U", "weight_V", NULL };
+        double (*func2[])(void *, double, double) = { weight_Y, weight_U, weight_V, p[plane], NULL };
+
+        ret = av_expr_parse(&fftfilt->weight_expr[plane], fftfilt->weight_str[plane], var_names,
+                            NULL, NULL, func2_names, func2, 0, ctx);
+        if (ret < 0)
+            break;
+    }
+    return ret;
+}
+
+static int config_props(AVFilterLink *inlink)
+{
+    FFTFILTContext *fftfilt = inlink->dst->priv;
+    const AVPixFmtDescriptor *desc;
+    int rdft_hbits, rdft_vbits, i, j, plane;
+    double values[VAR_VARS_NB];
+
+    desc = av_pix_fmt_desc_get(inlink->format);
+    for (i = 0; i < desc->nb_components; i++) {
+        int w = inlink->w;
+        int h = inlink->h;
+
+        /* RDFT - Array initialization for Horizontal pass*/
+        for (rdft_hbits = 1; 1 << rdft_hbits < w*10/9; rdft_hbits++);
+        fftfilt->rdft_hbits[i] = rdft_hbits;
+        fftfilt->rdft_hlen[i] = 1 << rdft_hbits;
+        if (!(fftfilt->rdft_hdata[i] = av_malloc_array(h, fftfilt->rdft_hlen[i] * sizeof(FFTSample))))
+            return AVERROR(ENOMEM);
+
+        /* RDFT - Array initialization for Vertical pass*/
+        for (rdft_vbits = 1; 1 << rdft_vbits < h*10/9; rdft_vbits++);
+        fftfilt->rdft_vbits[i] = rdft_vbits;
+        fftfilt->rdft_vlen[i] = 1 << rdft_vbits;
+        if (!(fftfilt->rdft_vdata[i] = av_malloc_array(fftfilt->rdft_hlen[i], fftfilt->rdft_vlen[i] * sizeof(FFTSample))))
+            return AVERROR(ENOMEM);
+    }
+
+    /*Luminance value - Array initialization*/
+    values[VAR_W] = inlink->w;
+    values[VAR_H] = inlink->h;
+    for (plane = 0; plane < 3; plane++)
+    {
+        if(!(fftfilt->weight[plane] = av_malloc_array(fftfilt->rdft_hlen[plane], fftfilt->rdft_vlen[plane] * sizeof(double))))
+            return AVERROR(ENOMEM);
+        for (i = 0; i < fftfilt->rdft_hlen[plane]; i++)
+        {
+            values[VAR_X] = i;
+            for (j = 0; j < fftfilt->rdft_vlen[plane]; j++)
+            {
+                values[VAR_Y] = j;
+                fftfilt->weight[plane][i * fftfilt->rdft_vlen[plane] + j] =
+                av_expr_eval(fftfilt->weight_expr[plane], values, fftfilt);
+            }
+        }
+    }
+    return 0;
+}
+
+static int filter_frame(AVFilterLink *inlink, AVFrame *in)
+{
+    AVFilterContext *ctx = inlink->dst;
+    AVFilterLink *outlink = inlink->dst->outputs[0];
+    const AVPixFmtDescriptor *desc;
+    FFTFILTContext *fftfilt = ctx->priv;
+    AVFrame *out;
+    int i, j, plane;
+
+    out = ff_get_video_buffer(outlink, inlink->w, inlink->h);
+    if (!out)
+        return AVERROR(ENOMEM);
+
+    av_frame_copy_props(out, in);
+
+    desc = av_pix_fmt_desc_get(inlink->format);
+    for (plane = 0; plane < desc->nb_components; plane++) {
+        int w = inlink->w;
+        int h = inlink->h;
+
+        if (plane == 1 || plane == 2) {
+            w = FF_CEIL_RSHIFT(w, desc->log2_chroma_w);
+            h = FF_CEIL_RSHIFT(h, desc->log2_chroma_h);
+        }
+
+        rdft_horizontal(fftfilt, in, w, h, plane);
+        rdft_vertical(fftfilt, h, plane);
+
+        /*Change user defined parameters*/
+        for (i = 0; i < fftfilt->rdft_hlen[plane]; i++)
+            for (j = 0; j < fftfilt->rdft_vlen[plane]; j++)
+                fftfilt->rdft_vdata[plane][i * fftfilt->rdft_vlen[plane] + j] *=
+                  fftfilt->weight[plane][i * fftfilt->rdft_vlen[plane] + j];
+
+        fftfilt->rdft_vdata[plane][0] += fftfilt->rdft_hlen[plane] * fftfilt->rdft_vlen[plane] * fftfilt->dc[plane];
+
+        irdft_vertical(fftfilt, h, plane);
+        irdft_horizontal(fftfilt, out, w, h, plane);
+    }
+
+    av_frame_free(&in);
+    return ff_filter_frame(outlink, out);
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    FFTFILTContext *fftfilt = ctx->priv;
+    int i;
+    for (i = 0; i < 3; i++) {
+        av_free(fftfilt->rdft_hdata[i]);
+        av_free(fftfilt->rdft_vdata[i]);
+        av_expr_free(fftfilt->weight_expr[i]);
+        av_free(fftfilt->weight[i]);
+    }
+}
+
+static int query_formats(AVFilterContext *ctx)
+{
+    static const enum AVPixelFormat pixel_fmts_fftfilt[] = {
+        AV_PIX_FMT_GRAY8,
+        AV_PIX_FMT_YUV444P,
+        AV_PIX_FMT_NONE
+    };
+
+    ff_set_common_formats(ctx, ff_make_format_list(pixel_fmts_fftfilt));
+
+    return 0;
+}
+
+static const AVFilterPad fftfilt_inputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+        .config_props = config_props,
+        .filter_frame = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad fftfilt_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
+AVFilter ff_vf_fftfilt = {
+    .name            = "fftfilt",
+    .description     = NULL_IF_CONFIG_SMALL("Apply arbitrary expressions to samples in frequency domain"),
+    .priv_size       = sizeof(FFTFILTContext),
+    .priv_class      = &fftfilt_class,
+    .inputs          = fftfilt_inputs,
+    .outputs         = fftfilt_outputs,
+    .query_formats   = query_formats,
+    .init            = initialize,
+    .uninit          = uninit,
+};
diff --git a/libavfilter/vf_field.c b/libavfilter/vf_field.c
index ed12379..72cabdb 100644
--- a/libavfilter/vf_field.c
+++ b/libavfilter/vf_field.c
@@ -33,7 +33,7 @@
 
 typedef struct {
     const AVClass *class;
-    enum FieldType type;
+    int type;                   ///< FieldType
     int nb_planes;              ///< number of planes of the current format
 } FieldContext;
 
diff --git a/libavfilter/vf_fieldmatch.c b/libavfilter/vf_fieldmatch.c
index 358bd9e..c01af66 100644
--- a/libavfilter/vf_fieldmatch.c
+++ b/libavfilter/vf_fieldmatch.c
@@ -86,13 +86,13 @@
     /* options */
     int order;
     int ppsrc;
-    enum matching_mode mode;
+    int mode;                       ///< matching_mode
     int field;
     int mchroma;
     int y0, y1;
     int64_t scthresh;
     double scthresh_flt;
-    enum comb_matching_mode combmatch;
+    int combmatch;                  ///< comb_matching_mode
     int combdbg;
     int cthresh;
     int chroma;
@@ -285,9 +285,9 @@
             cmkpV  += cmk_linesizeUV;
             cmkpU  += cmk_linesizeUV;
             for (x = 1; x < width - 1; x++) {
-#define HAS_FF_AROUND(p, lz) (p[x-1 - lz] == 0xff || p[x - lz] == 0xff || p[x+1 - lz] == 0xff || \
-                              p[x-1     ] == 0xff ||                      p[x+1     ] == 0xff || \
-                              p[x-1 + lz] == 0xff || p[x + lz] == 0xff || p[x+1 + lz] == 0xff)
+#define HAS_FF_AROUND(p, lz) (p[(x)-1 - (lz)] == 0xff || p[(x) - (lz)] == 0xff || p[(x)+1 - (lz)] == 0xff || \
+                              p[(x)-1       ] == 0xff ||                          p[(x)+1       ] == 0xff || \
+                              p[(x)-1 + (lz)] == 0xff || p[(x) + (lz)] == 0xff || p[(x)+1 + (lz)] == 0xff)
                 if ((cmkpV[x] == 0xff && HAS_FF_AROUND(cmkpV, cmk_linesizeUV)) ||
                     (cmkpU[x] == 0xff && HAS_FF_AROUND(cmkpU, cmk_linesizeUV))) {
                     ((uint16_t*)cmkp)[x]  = 0xffff;
@@ -855,8 +855,10 @@
         AV_PIX_FMT_YUV411P,  AV_PIX_FMT_YUV410P,
         AV_PIX_FMT_NONE
     };
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static int config_input(AVFilterLink *inlink)
diff --git a/libavfilter/vf_fps.c b/libavfilter/vf_fps.c
index a38633d..6154f6d 100644
--- a/libavfilter/vf_fps.c
+++ b/libavfilter/vf_fps.c
@@ -213,18 +213,15 @@
                              outlink->time_base, s->rounding) - s->frames_out ;
 
     if (delta < 1) {
-        /* drop the frame and everything buffered except the first */
-        AVFrame *tmp;
+        /* drop everything buffered except the last */
         int drop = av_fifo_size(s->fifo)/sizeof(AVFrame*);
 
         av_log(ctx, AV_LOG_DEBUG, "Dropping %d frame(s).\n", drop);
         s->drop += drop;
 
-        av_fifo_generic_read(s->fifo, &tmp, sizeof(tmp), NULL);
         flush_fifo(s->fifo);
-        ret = write_to_fifo(s->fifo, tmp);
+        ret = write_to_fifo(s->fifo, buf);
 
-        av_frame_free(&buf);
         return ret;
     }
 
diff --git a/libavfilter/vf_fspp.c b/libavfilter/vf_fspp.c
index e4de0f5..5283ef8 100644
--- a/libavfilter/vf_fspp.c
+++ b/libavfilter/vf_fspp.c
@@ -492,7 +492,7 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
+    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,
diff --git a/libavfilter/vf_geq.c b/libavfilter/vf_geq.c
index 49a3e62..b0f53a6 100644
--- a/libavfilter/vf_geq.c
+++ b/libavfilter/vf_geq.c
@@ -165,14 +165,14 @@
 static int geq_query_formats(AVFilterContext *ctx)
 {
     GEQContext *geq = ctx->priv;
-    static const enum PixelFormat yuv_pix_fmts[] = {
+    static const enum AVPixelFormat yuv_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_YUVA444P, AV_PIX_FMT_YUVA422P, AV_PIX_FMT_YUVA420P,
         AV_PIX_FMT_GRAY8,
         AV_PIX_FMT_NONE
     };
-    static const enum PixelFormat rgb_pix_fmts[] = {
+    static const enum AVPixelFormat rgb_pix_fmts[] = {
         AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRAP,
         AV_PIX_FMT_NONE
     };
diff --git a/libavfilter/vf_gradfun.c b/libavfilter/vf_gradfun.c
index 0da9e0b..8c11bda 100644
--- a/libavfilter/vf_gradfun.c
+++ b/libavfilter/vf_gradfun.c
@@ -155,10 +155,10 @@
         AV_PIX_FMT_GBRP,
         AV_PIX_FMT_NONE
     };
-
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static int config_input(AVFilterLink *inlink)
diff --git a/libavfilter/vf_histeq.c b/libavfilter/vf_histeq.c
index 6fdb7be..ce28afd 100644
--- a/libavfilter/vf_histeq.c
+++ b/libavfilter/vf_histeq.c
@@ -57,7 +57,7 @@
     const AVClass *class;
     float strength;
     float intensity;
-    enum HisteqAntibanding antibanding;
+    int antibanding;               ///< HisteqAntibanding
     int in_histogram [256];        ///< input histogram
     int out_histogram[256];        ///< output histogram
     int LUT[256];                  ///< lookup table derived from histogram[]
@@ -94,14 +94,15 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
+    static const 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_NONE
     };
-
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static int config_input(AVFilterLink *inlink)
diff --git a/libavfilter/vf_histogram.c b/libavfilter/vf_histogram.c
index 34656b5..40ec400 100644
--- a/libavfilter/vf_histogram.c
+++ b/libavfilter/vf_histogram.c
@@ -37,7 +37,7 @@
 
 typedef struct HistogramContext {
     const AVClass *class;               ///< AVClass context for log and options purpose
-    enum HistogramMode mode;
+    int mode;                           ///< HistogramMode
     unsigned       histogram[256];
     int            ncomp;
     const uint8_t  *bg_color;
diff --git a/libavfilter/vf_hqdn3d.c b/libavfilter/vf_hqdn3d.c
index 0448c0d..f862014 100644
--- a/libavfilter/vf_hqdn3d.c
+++ b/libavfilter/vf_hqdn3d.c
@@ -121,11 +121,11 @@
 }
 
 av_always_inline
-static void denoise_depth(HQDN3DContext *s,
-                          uint8_t *src, uint8_t *dst,
-                          uint16_t *line_ant, uint16_t **frame_ant_ptr,
-                          int w, int h, int sstride, int dstride,
-                          int16_t *spatial, int16_t *temporal, int depth)
+static int denoise_depth(HQDN3DContext *s,
+                         uint8_t *src, uint8_t *dst,
+                         uint16_t *line_ant, uint16_t **frame_ant_ptr,
+                         int w, int h, int sstride, int dstride,
+                         int16_t *spatial, int16_t *temporal, int depth)
 {
     // FIXME: For 16bit depth, frame_ant could be a pointer to the previous
     // filtered frame rather than a separate buffer.
@@ -134,6 +134,8 @@
     if (!frame_ant) {
         uint8_t *frame_src = src;
         *frame_ant_ptr = frame_ant = av_malloc_array(w, h*sizeof(uint16_t));
+        if (!frame_ant)
+            return AVERROR(ENOMEM);
         for (y = 0; y < h; y++, src += sstride, frame_ant += w)
             for (x = 0; x < w; x++)
                 frame_ant[x] = LOAD(x);
@@ -148,15 +150,25 @@
         denoise_temporal(src, dst, frame_ant,
                          w, h, sstride, dstride, temporal, depth);
     emms_c();
+    return 0;
 }
 
-#define denoise(...) \
-    switch (s->depth) {\
-        case  8: denoise_depth(__VA_ARGS__,  8); break;\
-        case  9: denoise_depth(__VA_ARGS__,  9); break;\
-        case 10: denoise_depth(__VA_ARGS__, 10); break;\
-        case 16: denoise_depth(__VA_ARGS__, 16); break;\
-    }
+#define denoise(...)                                                          \
+    do {                                                                      \
+        int ret = AVERROR_BUG;                                                \
+        switch (s->depth) {                                                   \
+            case  8: ret = denoise_depth(__VA_ARGS__,  8); break;             \
+            case  9: ret = denoise_depth(__VA_ARGS__,  9); break;             \
+            case 10: ret = denoise_depth(__VA_ARGS__, 10); break;             \
+            case 16: ret = denoise_depth(__VA_ARGS__, 16); break;             \
+        }                                                                     \
+        if (ret < 0) {                                                        \
+            av_frame_free(&out);                                              \
+            if (!direct)                                                      \
+                av_frame_free(&in);                                           \
+            return ret;                                                       \
+        }                                                                     \
+    } while (0)
 
 static int16_t *precalc_coefs(double dist25, int depth)
 {
@@ -241,10 +253,10 @@
         AV_PIX_FMT_YUV444P16,
         AV_PIX_FMT_NONE
     };
-
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static int config_input(AVFilterLink *inlink)
@@ -282,13 +294,11 @@
     AVFilterLink *outlink = ctx->outputs[0];
 
     AVFrame *out;
-    int direct, c;
+    int c, direct = av_frame_is_writable(in) && !ctx->is_disabled;
 
-    if (av_frame_is_writable(in) && !ctx->is_disabled) {
-        direct = 1;
+    if (direct) {
         out = in;
     } else {
-        direct = 0;
         out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
         if (!out) {
             av_frame_free(&in);
diff --git a/libavfilter/vf_hqx.c b/libavfilter/vf_hqx.c
index 4783381..fa15d9c 100644
--- a/libavfilter/vf_hqx.c
+++ b/libavfilter/vf_hqx.c
@@ -462,8 +462,10 @@
 static int query_formats(AVFilterContext *ctx)
 {
     static const enum AVPixelFormat pix_fmts[] = {AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE};
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static int config_output(AVFilterLink *outlink)
diff --git a/libavfilter/vf_hue.c b/libavfilter/vf_hue.c
index 7843673..2c1b34e 100644
--- a/libavfilter/vf_hue.c
+++ b/libavfilter/vf_hue.c
@@ -233,10 +233,10 @@
         AV_PIX_FMT_YUVA420P,
         AV_PIX_FMT_NONE
     };
-
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static int config_props(AVFilterLink *inlink)
diff --git a/libavfilter/vf_idet.c b/libavfilter/vf_idet.c
index 5430aba..eb1303a 100644
--- a/libavfilter/vf_idet.c
+++ b/libavfilter/vf_idet.c
@@ -399,10 +399,10 @@
         AV_PIX_FMT_YUVA420P,
         AV_PIX_FMT_NONE
     };
-
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static int config_output(AVFilterLink *outlink)
diff --git a/libavfilter/vf_il.c b/libavfilter/vf_il.c
index 550fde1..2501ef8 100644
--- a/libavfilter/vf_il.c
+++ b/libavfilter/vf_il.c
@@ -38,7 +38,7 @@
 
 typedef struct {
     const AVClass *class;
-    enum FilterMode luma_mode, chroma_mode, alpha_mode;
+    int luma_mode, chroma_mode, alpha_mode; ///<FilterMode
     int luma_swap, chroma_swap, alpha_swap;
     int nb_planes;
     int linesize[4], chroma_height;
diff --git a/libavfilter/vf_kerndeint.c b/libavfilter/vf_kerndeint.c
index ccb8fbd..1158fdb 100644
--- a/libavfilter/vf_kerndeint.c
+++ b/libavfilter/vf_kerndeint.c
@@ -68,7 +68,7 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
+    static const enum AVPixelFormat pix_fmts[] = {
         AV_PIX_FMT_YUV420P,
         AV_PIX_FMT_YUYV422,
         AV_PIX_FMT_ARGB, AV_PIX_FMT_0RGB,
diff --git a/libavfilter/vf_lenscorrection.c b/libavfilter/vf_lenscorrection.c
index 82ddb29..9db483d 100644
--- a/libavfilter/vf_lenscorrection.c
+++ b/libavfilter/vf_lenscorrection.c
@@ -107,9 +107,10 @@
         AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRAP,
         AV_PIX_FMT_NONE
     };
-
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static av_cold void uninit(AVFilterContext *ctx)
diff --git a/libavfilter/vf_libopencv.c b/libavfilter/vf_libopencv.c
index 1db9aa5..ec15f98 100644
--- a/libavfilter/vf_libopencv.c
+++ b/libavfilter/vf_libopencv.c
@@ -63,9 +63,10 @@
     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;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 typedef struct OCVContext {
@@ -261,19 +262,24 @@
     OCVContext *s = ctx->priv;
     DilateContext *dilate = s->priv;
     char default_kernel_str[] = "3x3+0x0/rect";
-    char *kernel_str;
+    char *kernel_str = NULL;
     const char *buf = args;
     int ret;
 
-    if (args)
+    if (args) {
         kernel_str = av_get_token(&buf, "|");
-    else
-        kernel_str = av_strdup(default_kernel_str);
-    if (!kernel_str)
-        return AVERROR(ENOMEM);
-    if ((ret = parse_iplconvkernel(&dilate->kernel, kernel_str, ctx)) < 0)
-        return ret;
+
+        if (!kernel_str)
+            return AVERROR(ENOMEM);
+    }
+
+    ret = parse_iplconvkernel(&dilate->kernel,
+                              (!kernel_str || !*kernel_str) ? default_kernel_str
+                                                            : kernel_str,
+                              ctx);
     av_free(kernel_str);
+    if (ret < 0)
+        return ret;
 
     if (!buf || sscanf(buf, "|%d", &dilate->nb_iterations) != 1)
         dilate->nb_iterations = 1;
diff --git a/libavfilter/vf_lut.c b/libavfilter/vf_lut.c
index 935bb08..93b18a8 100644
--- a/libavfilter/vf_lut.c
+++ b/libavfilter/vf_lut.c
@@ -130,9 +130,10 @@
     const enum AVPixelFormat *pix_fmts = s->is_rgb ? rgb_pix_fmts :
                                                      s->is_yuv ? yuv_pix_fmts :
                                                                  all_pix_fmts;
-
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 /**
diff --git a/libavfilter/vf_lut3d.c b/libavfilter/vf_lut3d.c
index 862ddde..3ef31ce 100644
--- a/libavfilter/vf_lut3d.c
+++ b/libavfilter/vf_lut3d.c
@@ -58,7 +58,7 @@
 
 typedef struct LUT3DContext {
     const AVClass *class;
-    enum interp_mode interpolation;
+    int interpolation;          ///<interp_mode
     char *file;
     uint8_t rgba_map[4];
     int step;
@@ -471,8 +471,10 @@
         AV_PIX_FMT_RGBA64, AV_PIX_FMT_BGRA64,
         AV_PIX_FMT_NONE
     };
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static int config_input(AVFilterLink *inlink)
diff --git a/libavfilter/vf_mcdeint.c b/libavfilter/vf_mcdeint.c
index 9f1b3f5..b0070d8 100644
--- a/libavfilter/vf_mcdeint.c
+++ b/libavfilter/vf_mcdeint.c
@@ -69,8 +69,8 @@
 
 typedef struct {
     const AVClass *class;
-    enum MCDeintMode mode;
-    enum MCDeintParity parity;
+    int mode;           ///< MCDeintMode
+    int parity;         ///< MCDeintParity
     int qp;
     AVCodecContext *enc_ctx;
 } MCDeintContext;
@@ -160,13 +160,13 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
+    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));
-
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static int filter_frame(AVFilterLink *inlink, AVFrame *inpic)
diff --git a/libavfilter/vf_mp.c b/libavfilter/vf_mp.c
deleted file mode 100644
index 63fdedd..0000000
--- a/libavfilter/vf_mp.c
+++ /dev/null
@@ -1,772 +0,0 @@
-/*
- * Copyright (c) 2011 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 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
- *
- * Parts of this file have been stolen from mplayer
- */
-
-/**
- * @file
- */
-
-#include "avfilter.h"
-#include "video.h"
-#include "formats.h"
-#include "internal.h"
-#include "libavutil/avassert.h"
-#include "libavutil/pixdesc.h"
-#include "libavutil/intreadwrite.h"
-#include "libavutil/imgutils.h"
-#include "libavutil/opt.h"
-
-#include "libmpcodecs/vf.h"
-#include "libmpcodecs/img_format.h"
-#include "libmpcodecs/cpudetect.h"
-#include "libmpcodecs/libvo/fastmemcpy.h"
-
-#include "libswscale/swscale.h"
-
-
-//FIXME maybe link the orig in
-//XXX: identical pix_fmt must be following with each others
-static const struct {
-    int fmt;
-    enum AVPixelFormat pix_fmt;
-} conversion_map[] = {
-    {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,  AV_PIX_FMT_YUVA420P},
-
-    {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,  AV_PIX_FMT_YUVJ420P},
-    {IMGFMT_422P,  AV_PIX_FMT_YUVJ422P},
-    {IMGFMT_444P,  AV_PIX_FMT_YUVJ444P},
-    {IMGFMT_440P,  AV_PIX_FMT_YUVJ440P},
-
-#if FF_API_XVMC
-    {IMGFMT_XVMC_MOCO_MPEG2, AV_PIX_FMT_XVMC_MPEG2_MC},
-    {IMGFMT_XVMC_IDCT_MPEG2, AV_PIX_FMT_XVMC_MPEG2_IDCT},
-#endif /* FF_API_XVMC */
-
-    {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}
-};
-
-extern const vf_info_t ff_vf_info_softpulldown;
-
-static const vf_info_t* const filters[]={
-    &ff_vf_info_softpulldown,
-    NULL
-};
-
-/*
-Unsupported filters
-1bpp
-ass
-bmovl
-crop
-dvbscale
-flip
-expand
-format
-halfpack
-lavc
-lavcdeint
-noformat
-pp
-scale
-tfields
-vo
-yadif
-zrmjpeg
-*/
-
-CpuCaps ff_gCpuCaps; //FIXME initialize this so optims work
-
-enum AVPixelFormat ff_mp2ff_pix_fmt(int mp){
-    int i;
-    for(i=0; conversion_map[i].fmt && mp != conversion_map[i].fmt; i++)
-        ;
-    return mp == conversion_map[i].fmt ? conversion_map[i].pix_fmt : AV_PIX_FMT_NONE;
-}
-
-typedef struct {
-    const AVClass *class;
-    vf_instance_t vf;
-    vf_instance_t next_vf;
-    AVFilterContext *avfctx;
-    int frame_returned;
-    char *filter;
-    enum AVPixelFormat in_pix_fmt;
-} MPContext;
-
-#define OFFSET(x) offsetof(MPContext, x)
-#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
-static const AVOption mp_options[] = {
-    { "filter", "set MPlayer filter name and parameters", OFFSET(filter), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
-    { NULL }
-};
-
-AVFILTER_DEFINE_CLASS(mp);
-
-void ff_mp_msg(int mod, int lev, const char *format, ... ){
-    va_list va;
-    va_start(va, format);
-    //FIXME convert lev/mod
-    av_vlog(NULL, AV_LOG_DEBUG, format, va);
-    va_end(va);
-}
-
-int ff_mp_msg_test(int mod, int lev){
-    return 123;
-}
-
-//Exact copy of vf.c
-void ff_vf_clone_mpi_attributes(mp_image_t* dst, mp_image_t* src){
-    dst->pict_type= src->pict_type;
-    dst->fields = src->fields;
-    dst->qscale_type= src->qscale_type;
-    if(dst->width == src->width && dst->height == src->height){
-        dst->qstride= src->qstride;
-        dst->qscale= src->qscale;
-    }
-}
-
-//Exact copy of vf.c
-void ff_vf_next_draw_slice(struct vf_instance *vf,unsigned char** src, int * stride,int w, int h, int x, int y){
-    if (vf->next->draw_slice) {
-        vf->next->draw_slice(vf->next,src,stride,w,h,x,y);
-        return;
-    }
-    if (!vf->dmpi) {
-        ff_mp_msg(MSGT_VFILTER,MSGL_ERR,"draw_slice: dmpi not stored by vf_%s\n", vf->info->name);
-        return;
-    }
-    if (!(vf->dmpi->flags & MP_IMGFLAG_PLANAR)) {
-        memcpy_pic(vf->dmpi->planes[0]+y*vf->dmpi->stride[0]+vf->dmpi->bpp/8*x,
-            src[0], vf->dmpi->bpp/8*w, h, vf->dmpi->stride[0], stride[0]);
-        return;
-    }
-    memcpy_pic(vf->dmpi->planes[0]+y*vf->dmpi->stride[0]+x, src[0],
-        w, h, vf->dmpi->stride[0], stride[0]);
-    memcpy_pic(vf->dmpi->planes[1]+(y>>vf->dmpi->chroma_y_shift)*vf->dmpi->stride[1]+(x>>vf->dmpi->chroma_x_shift),
-        src[1], w>>vf->dmpi->chroma_x_shift, h>>vf->dmpi->chroma_y_shift, vf->dmpi->stride[1], stride[1]);
-    memcpy_pic(vf->dmpi->planes[2]+(y>>vf->dmpi->chroma_y_shift)*vf->dmpi->stride[2]+(x>>vf->dmpi->chroma_x_shift),
-        src[2], w>>vf->dmpi->chroma_x_shift, h>>vf->dmpi->chroma_y_shift, vf->dmpi->stride[2], stride[2]);
-}
-
-//Exact copy of vf.c
-void ff_vf_mpi_clear(mp_image_t* mpi,int x0,int y0,int w,int h){
-    int y;
-    if(mpi->flags&MP_IMGFLAG_PLANAR){
-        y0&=~1;h+=h&1;
-        if(x0==0 && w==mpi->width){
-            // full width clear:
-            memset(mpi->planes[0]+mpi->stride[0]*y0,0,mpi->stride[0]*h);
-            memset(mpi->planes[1]+mpi->stride[1]*(y0>>mpi->chroma_y_shift),128,mpi->stride[1]*(h>>mpi->chroma_y_shift));
-            memset(mpi->planes[2]+mpi->stride[2]*(y0>>mpi->chroma_y_shift),128,mpi->stride[2]*(h>>mpi->chroma_y_shift));
-        } else
-        for(y=y0;y<y0+h;y+=2){
-            memset(mpi->planes[0]+x0+mpi->stride[0]*y,0,w);
-            memset(mpi->planes[0]+x0+mpi->stride[0]*(y+1),0,w);
-            memset(mpi->planes[1]+(x0>>mpi->chroma_x_shift)+mpi->stride[1]*(y>>mpi->chroma_y_shift),128,(w>>mpi->chroma_x_shift));
-            memset(mpi->planes[2]+(x0>>mpi->chroma_x_shift)+mpi->stride[2]*(y>>mpi->chroma_y_shift),128,(w>>mpi->chroma_x_shift));
-        }
-        return;
-    }
-    // packed:
-    for(y=y0;y<y0+h;y++){
-        unsigned char* dst=mpi->planes[0]+mpi->stride[0]*y+(mpi->bpp>>3)*x0;
-        if(mpi->flags&MP_IMGFLAG_YUV){
-            unsigned int* p=(unsigned int*) dst;
-            int size=(mpi->bpp>>3)*w/4;
-            int i;
-#if HAVE_BIGENDIAN
-#define CLEAR_PACKEDYUV_PATTERN 0x00800080
-#define CLEAR_PACKEDYUV_PATTERN_SWAPPED 0x80008000
-#else
-#define CLEAR_PACKEDYUV_PATTERN 0x80008000
-#define CLEAR_PACKEDYUV_PATTERN_SWAPPED 0x00800080
-#endif
-            if(mpi->flags&MP_IMGFLAG_SWAPPED){
-                for(i=0;i<size-3;i+=4) p[i]=p[i+1]=p[i+2]=p[i+3]=CLEAR_PACKEDYUV_PATTERN_SWAPPED;
-                for(;i<size;i++) p[i]=CLEAR_PACKEDYUV_PATTERN_SWAPPED;
-            } else {
-                for(i=0;i<size-3;i+=4) p[i]=p[i+1]=p[i+2]=p[i+3]=CLEAR_PACKEDYUV_PATTERN;
-                for(;i<size;i++) p[i]=CLEAR_PACKEDYUV_PATTERN;
-            }
-        } else
-            memset(dst,0,(mpi->bpp>>3)*w);
-    }
-}
-
-int ff_vf_next_query_format(struct vf_instance *vf, unsigned int fmt){
-    return 1;
-}
-
-//used by delogo
-unsigned int ff_vf_match_csp(vf_instance_t** vfp,const unsigned int* list,unsigned int preferred){
-    return preferred;
-}
-
-mp_image_t* ff_vf_get_image(vf_instance_t* vf, unsigned int outfmt, int mp_imgtype, int mp_imgflag, int w, int h){
-    MPContext *m= (MPContext*)(((uint8_t*)vf) - offsetof(MPContext, next_vf));
-  mp_image_t* mpi=NULL;
-  int w2;
-  int number = mp_imgtype >> 16;
-
-  av_assert0(vf->next == NULL); // all existing filters call this just on next
-
-  //vf_dint needs these as it calls ff_vf_get_image() before configuring the output
-  if(vf->w==0 && w>0) vf->w=w;
-  if(vf->h==0 && h>0) vf->h=h;
-
-  av_assert0(w == -1 || w >= vf->w);
-  av_assert0(h == -1 || h >= vf->h);
-  av_assert0(vf->w > 0);
-  av_assert0(vf->h > 0);
-
-  av_log(m->avfctx, AV_LOG_DEBUG, "get_image: %d:%d, vf: %d:%d\n", w,h,vf->w,vf->h);
-
-  if (w == -1) w = vf->w;
-  if (h == -1) h = vf->h;
-
-  w2=(mp_imgflag&MP_IMGFLAG_ACCEPT_ALIGNED_STRIDE)?((w+15)&(~15)):w;
-
-  // Note: we should call libvo first to check if it supports direct rendering
-  // and if not, then fallback to software buffers:
-  switch(mp_imgtype & 0xff){
-  case MP_IMGTYPE_EXPORT:
-    if(!vf->imgctx.export_images[0]) vf->imgctx.export_images[0]=ff_new_mp_image(w2,h);
-    mpi=vf->imgctx.export_images[0];
-    break;
-  case MP_IMGTYPE_STATIC:
-    if(!vf->imgctx.static_images[0]) vf->imgctx.static_images[0]=ff_new_mp_image(w2,h);
-    mpi=vf->imgctx.static_images[0];
-    break;
-  case MP_IMGTYPE_TEMP:
-    if(!vf->imgctx.temp_images[0]) vf->imgctx.temp_images[0]=ff_new_mp_image(w2,h);
-    mpi=vf->imgctx.temp_images[0];
-    break;
-  case MP_IMGTYPE_IPB:
-    if(!(mp_imgflag&MP_IMGFLAG_READABLE)){ // B frame:
-      if(!vf->imgctx.temp_images[0]) vf->imgctx.temp_images[0]=ff_new_mp_image(w2,h);
-      mpi=vf->imgctx.temp_images[0];
-      break;
-    }
-  case MP_IMGTYPE_IP:
-    if(!vf->imgctx.static_images[vf->imgctx.static_idx]) vf->imgctx.static_images[vf->imgctx.static_idx]=ff_new_mp_image(w2,h);
-    mpi=vf->imgctx.static_images[vf->imgctx.static_idx];
-    vf->imgctx.static_idx^=1;
-    break;
-  case MP_IMGTYPE_NUMBERED:
-    if (number == -1) {
-      int i;
-      for (i = 0; i < NUM_NUMBERED_MPI; i++)
-        if (!vf->imgctx.numbered_images[i] || !vf->imgctx.numbered_images[i]->usage_count)
-          break;
-      number = i;
-    }
-    if (number < 0 || number >= NUM_NUMBERED_MPI) return NULL;
-    if (!vf->imgctx.numbered_images[number]) vf->imgctx.numbered_images[number] = ff_new_mp_image(w2,h);
-    mpi = vf->imgctx.numbered_images[number];
-    mpi->number = number;
-    break;
-  }
-  if(mpi){
-    mpi->type=mp_imgtype;
-    mpi->w=vf->w; mpi->h=vf->h;
-    // keep buffer allocation status & color flags only:
-//    mpi->flags&=~(MP_IMGFLAG_PRESERVE|MP_IMGFLAG_READABLE|MP_IMGFLAG_DIRECT);
-    mpi->flags&=MP_IMGFLAG_ALLOCATED|MP_IMGFLAG_TYPE_DISPLAYED|MP_IMGFLAGMASK_COLORS;
-    // accept restrictions, draw_slice and palette flags only:
-    mpi->flags|=mp_imgflag&(MP_IMGFLAGMASK_RESTRICTIONS|MP_IMGFLAG_DRAW_CALLBACK|MP_IMGFLAG_RGB_PALETTE);
-    if(!vf->draw_slice) mpi->flags&=~MP_IMGFLAG_DRAW_CALLBACK;
-    if(mpi->width!=w2 || mpi->height!=h){
-//      printf("vf.c: MPI parameters changed!  %dx%d -> %dx%d   \n", mpi->width,mpi->height,w2,h);
-        if(mpi->flags&MP_IMGFLAG_ALLOCATED){
-            if(mpi->width<w2 || mpi->height<h){
-                // need to re-allocate buffer memory:
-                av_free(mpi->planes[0]);
-                mpi->flags&=~MP_IMGFLAG_ALLOCATED;
-                ff_mp_msg(MSGT_VFILTER,MSGL_V,"vf.c: have to REALLOCATE buffer memory :(\n");
-            }
-//      } else {
-        } {
-            mpi->width=w2; mpi->chroma_width=(w2 + (1<<mpi->chroma_x_shift) - 1)>>mpi->chroma_x_shift;
-            mpi->height=h; mpi->chroma_height=(h + (1<<mpi->chroma_y_shift) - 1)>>mpi->chroma_y_shift;
-        }
-    }
-    if(!mpi->bpp) ff_mp_image_setfmt(mpi,outfmt);
-    if(!(mpi->flags&MP_IMGFLAG_ALLOCATED) && mpi->type>MP_IMGTYPE_EXPORT){
-
-        av_assert0(!vf->get_image);
-        // check libvo first!
-        if(vf->get_image) vf->get_image(vf,mpi);
-
-        if(!(mpi->flags&MP_IMGFLAG_DIRECT)){
-          // non-direct and not yet allocated image. allocate it!
-          if (!mpi->bpp) { // no way we can allocate this
-              ff_mp_msg(MSGT_DECVIDEO, MSGL_FATAL,
-                     "ff_vf_get_image: Tried to allocate a format that can not be allocated!\n");
-              return NULL;
-          }
-
-          // check if codec prefer aligned stride:
-          if(mp_imgflag&MP_IMGFLAG_PREFER_ALIGNED_STRIDE){
-              int align=(mpi->flags&MP_IMGFLAG_PLANAR &&
-                         mpi->flags&MP_IMGFLAG_YUV) ?
-                         (8<<mpi->chroma_x_shift)-1 : 15; // -- maybe FIXME
-              w2=((w+align)&(~align));
-              if(mpi->width!=w2){
-#if 0
-                  // we have to change width... check if we CAN co it:
-                  int flags=vf->query_format(vf,outfmt); // should not fail
-                  if(!(flags&3)) ff_mp_msg(MSGT_DECVIDEO,MSGL_WARN,"??? ff_vf_get_image{vf->query_format(outfmt)} failed!\n");
-//                printf("query -> 0x%X    \n",flags);
-                  if(flags&VFCAP_ACCEPT_STRIDE){
-#endif
-                      mpi->width=w2;
-                      mpi->chroma_width=(w2 + (1<<mpi->chroma_x_shift) - 1)>>mpi->chroma_x_shift;
-//                  }
-              }
-          }
-
-          ff_mp_image_alloc_planes(mpi);
-//        printf("clearing img!\n");
-          ff_vf_mpi_clear(mpi,0,0,mpi->width,mpi->height);
-        }
-    }
-    av_assert0(!vf->start_slice);
-    if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK)
-        if(vf->start_slice) vf->start_slice(vf,mpi);
-    if(!(mpi->flags&MP_IMGFLAG_TYPE_DISPLAYED)){
-            ff_mp_msg(MSGT_DECVIDEO,MSGL_V,"*** [%s] %s%s mp_image_t, %dx%dx%dbpp %s %s, %d bytes\n",
-                  "NULL"/*vf->info->name*/,
-                  (mpi->type==MP_IMGTYPE_EXPORT)?"Exporting":
-                  ((mpi->flags&MP_IMGFLAG_DIRECT)?"Direct Rendering":"Allocating"),
-                  (mpi->flags&MP_IMGFLAG_DRAW_CALLBACK)?" (slices)":"",
-                  mpi->width,mpi->height,mpi->bpp,
-                  (mpi->flags&MP_IMGFLAG_YUV)?"YUV":((mpi->flags&MP_IMGFLAG_SWAPPED)?"BGR":"RGB"),
-                  (mpi->flags&MP_IMGFLAG_PLANAR)?"planar":"packed",
-                  mpi->bpp*mpi->width*mpi->height/8);
-            ff_mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"(imgfmt: %x, planes: %p,%p,%p strides: %d,%d,%d, chroma: %dx%d, shift: h:%d,v:%d)\n",
-                mpi->imgfmt, mpi->planes[0], mpi->planes[1], mpi->planes[2],
-                mpi->stride[0], mpi->stride[1], mpi->stride[2],
-                mpi->chroma_width, mpi->chroma_height, mpi->chroma_x_shift, mpi->chroma_y_shift);
-            mpi->flags|=MP_IMGFLAG_TYPE_DISPLAYED;
-    }
-
-  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]);
-  return mpi;
-}
-
-int ff_vf_next_put_image(struct vf_instance *vf,mp_image_t *mpi, double pts){
-    MPContext *m= (MPContext*)(((uint8_t*)vf) - offsetof(MPContext, vf));
-    AVFilterLink *outlink     = m->avfctx->outputs[0];
-    AVFrame *picref = av_frame_alloc();
-    int i;
-
-    av_assert0(vf->next);
-
-    av_log(m->avfctx, AV_LOG_DEBUG, "ff_vf_next_put_image\n");
-
-    if (!picref)
-        goto fail;
-
-    picref->width  = mpi->w;
-    picref->height = mpi->h;
-
-    for(i=0; conversion_map[i].fmt && mpi->imgfmt != conversion_map[i].fmt; i++);
-    picref->format = conversion_map[i].pix_fmt;
-
-    for(i=0; conversion_map[i].fmt && m->in_pix_fmt != conversion_map[i].pix_fmt; i++);
-    if (mpi->imgfmt == conversion_map[i].fmt)
-        picref->format = conversion_map[i].pix_fmt;
-
-    memcpy(picref->linesize, mpi->stride, FFMIN(sizeof(picref->linesize), sizeof(mpi->stride)));
-
-    for(i=0; i<4 && mpi->stride[i]; i++){
-        picref->data[i] = mpi->planes[i];
-    }
-
-    if(pts != MP_NOPTS_VALUE)
-        picref->pts= pts * av_q2d(outlink->time_base);
-
-    if(1) { // mp buffers are currently unsupported in libavfilter, we thus must copy
-        AVFrame *tofree = picref;
-        picref = av_frame_clone(picref);
-        av_frame_free(&tofree);
-    }
-
-    ff_filter_frame(outlink, picref);
-    m->frame_returned++;
-
-    return 1;
-fail:
-    av_frame_free(&picref);
-    return 0;
-}
-
-int ff_vf_next_config(struct vf_instance *vf,
-        int width, int height, int d_width, int d_height,
-        unsigned int voflags, unsigned int outfmt){
-
-    av_assert0(width>0 && height>0);
-    vf->next->w = width; vf->next->h = height;
-
-    return 1;
-#if 0
-    int flags=vf->next->query_format(vf->next,outfmt);
-    if(!flags){
-        // hmm. colorspace mismatch!!!
-        //this is fatal for us ATM
-        return 0;
-    }
-    ff_mp_msg(MSGT_VFILTER,MSGL_V,"REQ: flags=0x%X  req=0x%X  \n",flags,vf->default_reqs);
-    miss=vf->default_reqs - (flags&vf->default_reqs);
-    if(miss&VFCAP_ACCEPT_STRIDE){
-        // vf requires stride support but vf->next doesn't support it!
-        // let's insert the 'expand' filter, it does the job for us:
-        vf_instance_t* vf2=vf_open_filter(vf->next,"expand",NULL);
-        if(!vf2) return 0; // shouldn't happen!
-        vf->next=vf2;
-    }
-    vf->next->w = width; vf->next->h = height;
-    return 1;
-#endif
-}
-
-int ff_vf_next_control(struct vf_instance *vf, int request, void* data){
-    MPContext *m= (MPContext*)(((uint8_t*)vf) - offsetof(MPContext, vf));
-    av_log(m->avfctx, AV_LOG_DEBUG, "Received control %d\n", request);
-    return 0;
-}
-
-static int vf_default_query_format(struct vf_instance *vf, unsigned int fmt){
-    MPContext *m= (MPContext*)(((uint8_t*)vf) - offsetof(MPContext, vf));
-    int i;
-    av_log(m->avfctx, AV_LOG_DEBUG, "query %X\n", fmt);
-
-    for(i=0; conversion_map[i].fmt; i++){
-        if(fmt==conversion_map[i].fmt)
-            return 1; //we suport all
-    }
-    return 0;
-}
-
-
-static av_cold int init(AVFilterContext *ctx)
-{
-    MPContext *m = ctx->priv;
-    int cpu_flags = av_get_cpu_flags();
-    char name[256];
-    const char *args;
-    int i;
-
-    ff_gCpuCaps.hasMMX      = cpu_flags & AV_CPU_FLAG_MMX;
-    ff_gCpuCaps.hasMMX2     = cpu_flags & AV_CPU_FLAG_MMX2;
-    ff_gCpuCaps.hasSSE      = cpu_flags & AV_CPU_FLAG_SSE;
-    ff_gCpuCaps.hasSSE2     = cpu_flags & AV_CPU_FLAG_SSE2;
-    ff_gCpuCaps.hasSSE3     = cpu_flags & AV_CPU_FLAG_SSE3;
-    ff_gCpuCaps.hasSSSE3    = cpu_flags & AV_CPU_FLAG_SSSE3;
-    ff_gCpuCaps.hasSSE4     = cpu_flags & AV_CPU_FLAG_SSE4;
-    ff_gCpuCaps.hasSSE42    = cpu_flags & AV_CPU_FLAG_SSE42;
-    ff_gCpuCaps.hasAVX      = cpu_flags & AV_CPU_FLAG_AVX;
-    ff_gCpuCaps.has3DNow    = cpu_flags & AV_CPU_FLAG_3DNOW;
-    ff_gCpuCaps.has3DNowExt = cpu_flags & AV_CPU_FLAG_3DNOWEXT;
-
-    m->avfctx= ctx;
-
-    args = m->filter;
-    if(!args || 1!=sscanf(args, "%255[^:=]", name)){
-        av_log(ctx, AV_LOG_ERROR, "Invalid parameter.\n");
-        return AVERROR(EINVAL);
-    }
-    args += strlen(name);
-    if (args[0] == '=')
-        args++;
-
-    for(i=0; ;i++){
-        if(!filters[i] || !strcmp(name, filters[i]->name))
-            break;
-    }
-
-    if(!filters[i]){
-        av_log(ctx, AV_LOG_ERROR, "Unknown filter %s\n", name);
-        return AVERROR(EINVAL);
-    }
-
-    av_log(ctx, AV_LOG_WARNING,
-           "'%s' is a wrapped MPlayer filter (libmpcodecs). This filter may be removed\n"
-           "once it has been ported to a native libavfilter.\n", name);
-
-    memset(&m->vf,0,sizeof(m->vf));
-    m->vf.info= filters[i];
-
-    m->vf.next        = &m->next_vf;
-    m->vf.put_image   = ff_vf_next_put_image;
-    m->vf.config      = ff_vf_next_config;
-    m->vf.query_format= vf_default_query_format;
-    m->vf.control     = ff_vf_next_control;
-    m->vf.default_caps=VFCAP_ACCEPT_STRIDE;
-    m->vf.default_reqs=0;
-    if(m->vf.info->opts)
-        av_log(ctx, AV_LOG_ERROR, "opts / m_struct_set is unsupported\n");
-#if 0
-    if(vf->info->opts) { // vf_vo get some special argument
-      const m_struct_t* st = vf->info->opts;
-      void* vf_priv = m_struct_alloc(st);
-      int n;
-      for(n = 0 ; args && args[2*n] ; n++)
-        m_struct_set(st,vf_priv,args[2*n],args[2*n+1]);
-      vf->priv = vf_priv;
-      args = NULL;
-    } else // Otherwise we should have the '_oldargs_'
-      if(args && !strcmp(args[0],"_oldargs_"))
-        args = (char**)args[1];
-      else
-        args = NULL;
-#endif
-    if(m->vf.info->vf_open(&m->vf, (char*)args)<=0){
-        av_log(ctx, AV_LOG_ERROR, "vf_open() of %s with arg=%s failed\n", name, args);
-        return -1;
-    }
-
-    return 0;
-}
-
-static av_cold void uninit(AVFilterContext *ctx)
-{
-    MPContext *m = ctx->priv;
-    vf_instance_t *vf = &m->vf;
-
-    while(vf){
-        vf_instance_t *next = vf->next;
-        if(vf->uninit)
-            vf->uninit(vf);
-        ff_free_mp_image(vf->imgctx.static_images[0]);
-        ff_free_mp_image(vf->imgctx.static_images[1]);
-        ff_free_mp_image(vf->imgctx.temp_images[0]);
-        ff_free_mp_image(vf->imgctx.export_images[0]);
-        vf = next;
-    }
-}
-
-static int query_formats(AVFilterContext *ctx)
-{
-    AVFilterFormats *avfmts=NULL;
-    MPContext *m = ctx->priv;
-    enum AVPixelFormat lastpixfmt = AV_PIX_FMT_NONE;
-    int i;
-
-    for(i=0; conversion_map[i].fmt; i++){
-        av_log(ctx, AV_LOG_DEBUG, "query: %X\n", conversion_map[i].fmt);
-        if(m->vf.query_format(&m->vf, conversion_map[i].fmt)){
-            av_log(ctx, AV_LOG_DEBUG, "supported,adding\n");
-            if (conversion_map[i].pix_fmt != lastpixfmt) {
-                ff_add_format(&avfmts, conversion_map[i].pix_fmt);
-                lastpixfmt = conversion_map[i].pix_fmt;
-            }
-        }
-    }
-
-    if (!avfmts)
-        return -1;
-
-    //We assume all allowed input formats are also allowed output formats
-    ff_set_common_formats(ctx, avfmts);
-    return 0;
-}
-
-static int config_inprops(AVFilterLink *inlink)
-{
-    MPContext *m = inlink->dst->priv;
-    int i;
-    for(i=0; conversion_map[i].fmt && conversion_map[i].pix_fmt != inlink->format; i++);
-
-    av_assert0(conversion_map[i].fmt && inlink->w && inlink->h);
-
-    m->vf.fmt.have_configured = 1;
-    m->vf.fmt.orig_height     = inlink->h;
-    m->vf.fmt.orig_width      = inlink->w;
-    m->vf.fmt.orig_fmt        = conversion_map[i].fmt;
-
-    if(m->vf.config(&m->vf, inlink->w, inlink->h, inlink->w, inlink->h, 0, conversion_map[i].fmt)<=0)
-        return -1;
-
-    return 0;
-}
-
-static int config_outprops(AVFilterLink *outlink)
-{
-    MPContext *m = outlink->src->priv;
-
-    outlink->w = m->next_vf.w;
-    outlink->h = m->next_vf.h;
-
-    return 0;
-}
-
-static int request_frame(AVFilterLink *outlink)
-{
-    MPContext *m = outlink->src->priv;
-    int ret;
-
-    av_log(m->avfctx, AV_LOG_DEBUG, "mp request_frame\n");
-
-    for(m->frame_returned=0; !m->frame_returned;){
-        ret=ff_request_frame(outlink->src->inputs[0]);
-        if(ret<0)
-            break;
-    }
-
-    av_log(m->avfctx, AV_LOG_DEBUG, "mp request_frame ret=%d\n", ret);
-    return ret;
-}
-
-static int filter_frame(AVFilterLink *inlink, AVFrame *inpic)
-{
-    MPContext *m = inlink->dst->priv;
-    int i;
-    double pts= MP_NOPTS_VALUE;
-    mp_image_t* mpi = ff_new_mp_image(inpic->width, inpic->height);
-
-    if(inpic->pts != AV_NOPTS_VALUE)
-        pts= inpic->pts / av_q2d(inlink->time_base);
-
-    for(i=0; conversion_map[i].fmt && conversion_map[i].pix_fmt != inlink->format; i++);
-    ff_mp_image_setfmt(mpi,conversion_map[i].fmt);
-    m->in_pix_fmt = inlink->format;
-
-    memcpy(mpi->planes, inpic->data,     FFMIN(sizeof(inpic->data)    , sizeof(mpi->planes)));
-    memcpy(mpi->stride, inpic->linesize, FFMIN(sizeof(inpic->linesize), sizeof(mpi->stride)));
-
-    if (inpic->interlaced_frame)
-        mpi->fields |= MP_IMGFIELD_INTERLACED;
-    if (inpic->top_field_first)
-        mpi->fields |= MP_IMGFIELD_TOP_FIRST;
-    if (inpic->repeat_pict)
-        mpi->fields |= MP_IMGFIELD_REPEAT_FIRST;
-
-    // mpi->flags|=MP_IMGFLAG_ALLOCATED; ?
-    mpi->flags |= MP_IMGFLAG_READABLE;
-    if(!av_frame_is_writable(inpic))
-        mpi->flags |= MP_IMGFLAG_PRESERVE;
-    if(m->vf.put_image(&m->vf, mpi, pts) == 0){
-        av_log(m->avfctx, AV_LOG_DEBUG, "put_image() says skip\n");
-    }else{
-        av_frame_free(&inpic);
-    }
-    ff_free_mp_image(mpi);
-    return 0;
-}
-
-static const AVFilterPad mp_inputs[] = {
-    {
-        .name         = "default",
-        .type         = AVMEDIA_TYPE_VIDEO,
-        .filter_frame = filter_frame,
-        .config_props = config_inprops,
-    },
-    { NULL }
-};
-
-static const AVFilterPad mp_outputs[] = {
-    {
-        .name          = "default",
-        .type          = AVMEDIA_TYPE_VIDEO,
-        .request_frame = request_frame,
-        .config_props  = config_outprops,
-    },
-    { NULL }
-};
-
-AVFilter ff_vf_mp = {
-    .name          = "mp",
-    .description   = NULL_IF_CONFIG_SMALL("Apply a libmpcodecs filter to the input video."),
-    .init          = init,
-    .uninit        = uninit,
-    .priv_size     = sizeof(MPContext),
-    .query_formats = query_formats,
-    .inputs        = mp_inputs,
-    .outputs       = mp_outputs,
-    .priv_class    = &mp_class,
-};
diff --git a/libavfilter/vf_mpdecimate.c b/libavfilter/vf_mpdecimate.c
index 3ed9602..d86b5d8 100644
--- a/libavfilter/vf_mpdecimate.c
+++ b/libavfilter/vf_mpdecimate.c
@@ -158,10 +158,10 @@
         AV_PIX_FMT_YUVA420P,
         AV_PIX_FMT_NONE
     };
-
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static int config_input(AVFilterLink *inlink)
diff --git a/libavfilter/vf_overlay.c b/libavfilter/vf_overlay.c
index 80d99bd..788c1d9 100644
--- a/libavfilter/vf_overlay.c
+++ b/libavfilter/vf_overlay.c
@@ -92,6 +92,20 @@
 #define U 1
 #define V 2
 
+enum EvalMode {
+    EVAL_MODE_INIT,
+    EVAL_MODE_FRAME,
+    EVAL_MODE_NB
+};
+
+enum OverlayFormat {
+    OVERLAY_FORMAT_YUV420,
+    OVERLAY_FORMAT_YUV422,
+    OVERLAY_FORMAT_YUV444,
+    OVERLAY_FORMAT_RGB,
+    OVERLAY_FORMAT_NB
+};
+
 typedef struct OverlayContext {
     const AVClass *class;
     int x, y;                   ///< position of overlayed picture
@@ -103,8 +117,8 @@
     uint8_t overlay_is_packed_rgb;
     uint8_t overlay_rgba_map[4];
     uint8_t overlay_has_alpha;
-    enum OverlayFormat { OVERLAY_FORMAT_YUV420, OVERLAY_FORMAT_YUV422, OVERLAY_FORMAT_YUV444, OVERLAY_FORMAT_RGB, OVERLAY_FORMAT_NB} format;
-    enum EvalMode { EVAL_MODE_INIT, EVAL_MODE_FRAME, EVAL_MODE_NB } eval_mode;
+    int format;                 ///< OverlayFormat
+    int eval_mode;              ///< EvalMode
 
     FFDualInputContext dinput;
 
@@ -115,7 +129,7 @@
     double var_values[VAR_VARS_NB];
     char *x_expr, *y_expr;
 
-    enum EOFAction eof_action;  ///< action to take on EOF from source
+    int eof_action;             ///< action to take on EOF from source
 
     AVExpr *x_pexpr, *y_pexpr;
 } OverlayContext;
diff --git a/libavfilter/vf_owdenoise.c b/libavfilter/vf_owdenoise.c
index 29322b1..f91bbe5 100644
--- a/libavfilter/vf_owdenoise.c
+++ b/libavfilter/vf_owdenoise.c
@@ -267,8 +267,10 @@
         AV_PIX_FMT_YUVA420P,
         AV_PIX_FMT_NONE
     };
-    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
-    return 0;
+    AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
+    if (!fmts_list)
+        return AVERROR(ENOMEM);
+    return ff_set_common_formats(ctx, fmts_list);
 }
 
 static int config_input(AVFilterLink *inlink)
diff --git a/libavfilter/vf_palettegen.c b/libavfilter/vf_palettegen.c
new file mode 100644
index 0000000..4b49058
--- /dev/null
+++ b/libavfilter/vf_palettegen.c
@@ -0,0 +1,565 @@
+/*
+ * Copyright (c) 2015 Stupeflix
+ *
+ * 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
+ * Generate one palette for a whole video stream.
+ */
+
+#include "libavutil/avassert.h"
+#include "libavutil/opt.h"
+#include "libavutil/qsort.h"
+#include "avfilter.h"
+#include "internal.h"
+
+/* Reference a color and how much it's used */
+struct color_ref {
+    uint32_t color;
+    uint64_t count;
+};
+
+/* Store a range of colors */
+struct range_box {
+    uint32_t color;     // average color
+    int64_t variance;   // overall variance of the box (how much the colors are spread)
+    int start;          // index in PaletteGenContext->refs
+    int len;            // number of referenced colors
+    int sorted_by;      // whether range of colors is sorted by red (0), green (1) or blue (2)
+};
+
+struct hist_node {
+    struct color_ref *entries;
+    int nb_entries;
+};
+
+enum {
+    STATS_MODE_ALL_FRAMES,
+    STATS_MODE_DIFF_FRAMES,
+    NB_STATS_MODE
+};
+
+#define NBITS 5
+#define HIST_SIZE (1<<(3*NBITS))
+
+typedef struct {
+    const AVClass *class;
+
+    int max_colors;
+    int reserve_transparent;
+    int stats_mode;
+
+    AVFrame *prev_frame;                    // previous frame used for the diff stats_mode
+    struct hist_node histogram[HIST_SIZE];  // histogram/hashtable of the colors
+    struct color_ref **refs;                // references of all the colors used in the stream
+    int nb_refs;                            // number of color references (or number of different colors)
+    struct range_box boxes[256];            // define the segmentation of the colorspace (the final palette)
+    int nb_boxes;                           // number of boxes (increase will segmenting them)
+    int palette_pushed;                     // if the palette frame is pushed into the outlink or not
+} PaletteGenContext;
+
+#define OFFSET(x) offsetof(PaletteGenContext, x)
+#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
+static const AVOption palettegen_options[] = {
+    { "max_colors", "set the maximum number of colors to use in the palette", OFFSET(max_colors), AV_OPT_TYPE_INT, {.i64=256}, 4, 256, FLAGS },
+    { "reserve_transparent", "reserve a palette entry for transparency", OFFSET(reserve_transparent), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS },
+    { "stats_mode", "set statistics mode", OFFSET(stats_mode), AV_OPT_TYPE_INT, {.i64=STATS_MODE_ALL_FRAMES}, 0, NB_STATS_MODE, FLAGS, "mode" },
+        { "full", "compute full frame histograms", 0, AV_OPT_TYPE_CONST, {.i64=STATS_MODE_ALL_FRAMES}, INT_MIN, INT_MAX, FLAGS, "mode" },
+        { "diff", "compute histograms only for the part that differs from previous frame", 0, AV_OPT_TYPE_CONST, {.i64=STATS_MODE_DIFF_FRAMES}, INT_MIN, INT_MAX, FLAGS, "mode" },
+    { NULL }
+};
+
+AVFILTER_DEFINE_CLASS(palettegen);
+
+static int query_formats(AVFilterContext *ctx)
+{
+    static const enum AVPixelFormat in_fmts[]  = {AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE};
+    static const enum AVPixelFormat out_fmts[] = {AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE};
+    AVFilterFormats *in  = ff_make_format_list(in_fmts);
+    AVFilterFormats *out = ff_make_format_list(out_fmts);
+    if (!in || !out) {
+        av_freep(&in);
+        av_freep(&out);
+        return AVERROR(ENOMEM);
+    }
+    ff_formats_ref(in,  &ctx->inputs[0]->out_formats);
+    ff_formats_ref(out, &ctx->outputs[0]->in_formats);
+    return 0;
+}
+
+typedef int (*cmp_func)(const void *, const void *);
+
+#define DECLARE_CMP_FUNC(name, pos)                     \
+static int cmp_##name(const void *pa, const void *pb)   \
+{                                                       \
+    const struct color_ref * const *a = pa;             \
+    const struct color_ref * const *b = pb;             \
+    return   ((*a)->color >> (8 * (2 - (pos))) & 0xff)  \
+           - ((*b)->color >> (8 * (2 - (pos))) & 0xff); \
+}
+
+DECLARE_CMP_FUNC(r, 0)
+DECLARE_CMP_FUNC(g, 1)
+DECLARE_CMP_FUNC(b, 2)
+
+static const cmp_func cmp_funcs[] = {cmp_r, cmp_g, cmp_b};
+
+/**
+ * Simple color comparison for sorting the final palette
+ */
+static int cmp_color(const void *a, const void *b)
+{
+    const struct range_box *box1 = a;
+    const struct range_box *box2 = b;
+    return box1->color - box2->color;
+}
+
+static av_always_inline int diff(const uint32_t a, const uint32_t b)
+{
+    const uint8_t c1[] = {a >> 16 & 0xff, a >> 8 & 0xff, a & 0xff};
+    const uint8_t c2[] = {b >> 16 & 0xff, b >> 8 & 0xff, b & 0xff};
+    const int dr = c1[0] - c2[0];
+    const int dg = c1[1] - c2[1];
+    const int db = c1[2] - c2[2];
+    return dr*dr + dg*dg + db*db;
+}
+
+/**
+ * Find the next box to split: pick the one with the highest variance
+ */
+static int get_next_box_id_to_split(PaletteGenContext *s)
+{
+    int box_id, i, best_box_id = -1;
+    int64_t max_variance = -1;
+
+    if (s->nb_boxes == s->max_colors - s->reserve_transparent)
+        return -1;
+
+    for (box_id = 0; box_id < s->nb_boxes; box_id++) {
+        struct range_box *box = &s->boxes[box_id];
+
+        if (s->boxes[box_id].len >= 2) {
+
+            if (box->variance == -1) {
+                int64_t variance = 0;
+
+                for (i = 0; i < box->len; i++) {
+                    const struct color_ref *ref = s->refs[box->start + i];
+                    variance += diff(ref->color, box->color) * ref->count;
+                }
+                box->variance = variance;
+            }
+            if (box->variance > max_variance) {
+                best_box_id = box_id;
+                max_variance = box->variance;
+            }
+        } else {
+            box->variance = -1;
+        }
+    }
+    return best_box_id;
+}
+
+/**
+ * Get the 32-bit average color for the range of RGB colors enclosed in the
+ * specified box. Takes into account the weight of each color.
+ */
+static uint32_t get_avg_color(struct color_ref * const *refs,
+                              const struct range_box *box)
+{
+    int i;
+    const int n = box->len;
+    uint64_t r = 0, g = 0, b = 0, div = 0;
+
+    for (i = 0; i < n; i++) {
+        const struct color_ref *ref = refs[box->start + i];
+        r += (ref->color >> 16 & 0xff) * ref->count;
+        g += (ref->color >>  8 & 0xff) * ref->count;
+        b += (ref->color       & 0xff) * ref->count;
+        div += ref->count;
+    }
+
+    r = r / div;
+    g = g / div;
+    b = b / div;
+
+    return 0xffU<<24 | r<<16 | g<<8 | b;
+}
+
+/**
+ * Split given box in two at position n. The original box becomes the left part
+ * of the split, and the new index box is the right part.
+ */
+static void split_box(PaletteGenContext *s, struct range_box *box, int n)
+{
+    struct range_box *new_box = &s->boxes[s->nb_boxes++];
+    new_box->start     = n + 1;
+    new_box->len       = box->start + box->len - new_box->start;
+    new_box->sorted_by = box->sorted_by;
+    box->len -= new_box->len;
+
+    av_assert0(box->len     >= 1);
+    av_assert0(new_box->len >= 1);
+
+    box->color     = get_avg_color(s->refs, box);
+    new_box->color = get_avg_color(s->refs, new_box);
+    box->variance     = -1;
+    new_box->variance = -1;
+}
+
+/**
+ * Write the palette into the output frame.
+ */
+static void write_palette(AVFilterContext *ctx, AVFrame *out)
+{
+    const PaletteGenContext *s = ctx->priv;
+    int x, y, box_id = 0;
+    uint32_t *pal = (uint32_t *)out->data[0];
+    const int pal_linesize = out->linesize[0] >> 2;
+    uint32_t last_color = 0;
+
+    for (y = 0; y < out->height; y++) {
+        for (x = 0; x < out->width; x++) {
+            if (box_id < s->nb_boxes) {
+                pal[x] = s->boxes[box_id++].color;
+                if ((x || y) && pal[x] == last_color)
+                    av_log(ctx, AV_LOG_WARNING, "Dupped color: %08X\n", pal[x]);
+                last_color = pal[x];
+            } else {
+                pal[x] = 0xff000000; // pad with black
+            }
+        }
+        pal += pal_linesize;
+    }
+
+    if (s->reserve_transparent) {
+        av_assert0(s->nb_boxes < 256);
+        pal[out->width - pal_linesize - 1] = 0x0000ff00; // add a green transparent color
+    }
+}
+
+/**
+ * Crawl the histogram to get all the defined colors, and create a linear list
+ * of them (each color reference entry is a pointer to the value in the
+ * histogram/hash table).
+ */
+static struct color_ref **load_color_refs(const struct hist_node *hist, int nb_refs)
+{
+    int i, j, k = 0;
+    struct color_ref **refs = av_malloc_array(nb_refs, sizeof(*refs));
+
+    if (!refs)
+        return NULL;
+
+    for (j = 0; j < HIST_SIZE; j++) {
+        const struct hist_node *node = &hist[j];
+
+        for (i = 0; i < node->nb_entries; i++)
+            refs[k++] = &node->entries[i];
+    }
+
+    return refs;
+}
+
+static double set_colorquant_ratio_meta(AVFrame *out, int nb_out, int nb_in)
+{
+    char buf[32];
+    const double ratio = (double)nb_out / nb_in;
+    snprintf(buf, sizeof(buf), "%f", ratio);
+    av_dict_set(&out->metadata, "lavfi.color_quant_ratio", buf, 0);
+    return ratio;
+}
+
+/**
+ * Main function implementing the Median Cut Algorithm defined by Paul Heckbert
+ * in Color Image Quantization for Frame Buffer Display (1982)
+ */
+static AVFrame *get_palette_frame(AVFilterContext *ctx)
+{
+    AVFrame *out;
+    PaletteGenContext *s = ctx->priv;
+    AVFilterLink *outlink = ctx->outputs[0];
+    double ratio;
+    int box_id = 0;
+    struct range_box *box;
+
+    /* reference only the used colors from histogram */
+    s->refs = load_color_refs(s->histogram, s->nb_refs);
+    if (!s->refs) {
+        av_log(ctx, AV_LOG_ERROR, "Unable to allocate references for %d different colors\n", s->nb_refs);
+        return NULL;
+    }
+
+    /* create the palette frame */
+    out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
+    if (!out)
+        return NULL;
+    out->pts = 0;
+
+    /* set first box for 0..nb_refs */
+    box = &s->boxes[box_id];
+    box->len = s->nb_refs;
+    box->sorted_by = -1;
+    box->color = get_avg_color(s->refs, box);
+    box->variance = -1;
+    s->nb_boxes = 1;
+
+    while (box && box->len > 1) {
+        int i, rr, gr, br, longest;
+        uint64_t median, box_weight = 0;
+
+        /* compute the box weight (sum all the weights of the colors in the
+         * range) and its boundings */
+        uint8_t min[3] = {0xff, 0xff, 0xff};
+        uint8_t max[3] = {0x00, 0x00, 0x00};
+        for (i = box->start; i < box->start + box->len; i++) {
+            const struct color_ref *ref = s->refs[i];
+            const uint32_t rgb = ref->color;
+            const uint8_t r = rgb >> 16 & 0xff, g = rgb >> 8 & 0xff, b = rgb & 0xff;
+            min[0] = FFMIN(r, min[0]), max[0] = FFMAX(r, max[0]);
+            min[1] = FFMIN(g, min[1]), max[1] = FFMAX(g, max[1]);
+            min[2] = FFMIN(b, min[2]), max[2] = FFMAX(b, max[2]);
+            box_weight += ref->count;
+        }
+
+        /* define the axis to sort by according to the widest range of colors */
+        rr = max[0] - min[0];
+        gr = max[1] - min[1];
+        br = max[2] - min[2];
+        longest = 1; // pick green by default (the color the eye is the most sensitive to)
+        if (br >= rr && br >= gr) longest = 2;
+        if (rr >= gr && rr >= br) longest = 0;
+        if (gr >= rr && gr >= br) longest = 1; // prefer green again
+
+        av_dlog(ctx, "box #%02X [%6d..%-6d] (%6d) w:%-6"PRIu64" ranges:[%2x %2x %2x] sort by %c (already sorted:%c) ",
+                box_id, box->start, box->start + box->len - 1, box->len, box_weight,
+                rr, gr, br, "rgb"[longest], box->sorted_by == longest ? 'y':'n');
+
+        /* sort the range by its longest axis if it's not already sorted */
+        if (box->sorted_by != longest) {
+            cmp_func cmpf = cmp_funcs[longest];
+            AV_QSORT(&s->refs[box->start], box->len, const struct color_ref *, cmpf);
+            box->sorted_by = longest;
+        }
+
+        /* locate the median where to split */
+        median = (box_weight + 1) >> 1;
+        box_weight = 0;
+        /* if you have 2 boxes, the maximum is actually #0: you must have at
+         * least 1 color on each side of the split, hence the -2 */
+        for (i = box->start; i < box->start + box->len - 2; i++) {
+            box_weight += s->refs[i]->count;
+            if (box_weight > median)
+                break;
+        }
+        av_dlog(ctx, "split @ i=%-6d with w=%-6"PRIu64" (target=%6"PRIu64")\n", i, box_weight, median);
+        split_box(s, box, i);
+
+        box_id = get_next_box_id_to_split(s);
+        box = box_id >= 0 ? &s->boxes[box_id] : NULL;
+    }
+
+    ratio = set_colorquant_ratio_meta(out, s->nb_boxes, s->nb_refs);
+    av_log(ctx, AV_LOG_INFO, "%d%s colors generated out of %d colors; ratio=%f\n",
+           s->nb_boxes, s->reserve_transparent ? "(+1)" : "", s->nb_refs, ratio);
+
+    qsort(s->boxes, s->nb_boxes, sizeof(*s->boxes), cmp_color);
+
+    write_palette(ctx, out);
+
+    return out;
+}
+
+/**
+ * Hashing function for the color.
+ * It keeps the NBITS least significant bit of each component to make it
+ * "random" even if the scene doesn't have much different colors.
+ */
+static inline unsigned color_hash(uint32_t color)
+{
+    const uint8_t r = color >> 16 & ((1<<NBITS)-1);
+    const uint8_t g = color >>  8 & ((1<<NBITS)-1);
+    const uint8_t b = color       & ((1<<NBITS)-1);
+    return r<<(NBITS*2) | g<<NBITS | b;
+}
+
+/**
+ * Locate the color in the hash table and increment its counter.
+ */
+static int color_inc(struct hist_node *hist, uint32_t color)
+{
+    int i;
+    const unsigned hash = color_hash(color);
+    struct hist_node *node = &hist[hash];
+    struct color_ref *e;
+
+    for (i = 0; i < node->nb_entries; i++) {
+        e = &node->entries[i];
+        if (e->color == color) {
+            e->count++;
+            return 0;
+        }
+    }
+
+    e = av_dynarray2_add((void**)&node->entries, &node->nb_entries,
+                         sizeof(*node->entries), NULL);
+    if (!e)
+        return AVERROR(ENOMEM);
+    e->color = color;
+    e->count = 1;
+    return 1;
+}
+
+/**
+ * Update histogram when pixels differ from previous frame.
+ */
+static int update_histogram_diff(struct hist_node *hist,
+                                 const AVFrame *f1, const AVFrame *f2)
+{
+    int x, y, ret, nb_diff_colors = 0;
+
+    for (y = 0; y < f1->height; y++) {
+        const uint32_t *p = (const uint32_t *)(f1->data[0] + y*f1->linesize[0]);
+        const uint32_t *q = (const uint32_t *)(f2->data[0] + y*f2->linesize[0]);
+
+        for (x = 0; x < f1->width; x++) {
+            if (p[x] == q[x])
+                continue;
+            ret = color_inc(hist, p[x]);
+            if (ret < 0)
+                return ret;
+            nb_diff_colors += ret;
+        }
+    }
+    return nb_diff_colors;
+}
+
+/**
+ * Simple histogram of the frame.
+ */
+static int update_histogram_frame(struct hist_node *hist, const AVFrame *f)
+{
+    int x, y, ret, nb_diff_colors = 0;
+
+    for (y = 0; y < f->height; y++) {
+        const uint32_t *p = (const uint32_t *)(f->data[0] + y*f->linesize[0]);
+
+        for (x = 0; x < f->width; x++) {
+            ret = color_inc(hist, p[x]);
+            if (ret < 0)
+                return ret;
+            nb_diff_colors += ret;
+        }
+    }
+    return nb_diff_colors;
+}
+
+/**
+ * Update the histogram for each passing frame. No frame will be pushed here.
+ */
+static int filter_frame(AVFilterLink *inlink, AVFrame *in)
+{
+    AVFilterContext *ctx = inlink->dst;
+    PaletteGenContext *s = ctx->priv;
+    const int ret = s->prev_frame ? update_histogram_diff(s->histogram, s->prev_frame, in)
+                                  : update_histogram_frame(s->histogram, in);
+
+    if (ret > 0)
+        s->nb_refs += ret;
+
+    if (s->stats_mode == STATS_MODE_DIFF_FRAMES) {
+        av_frame_free(&s->prev_frame);
+        s->prev_frame = in;
+    } else {
+        av_frame_free(&in);
+    }
+
+    return ret;
+}
+
+/**
+ * Returns only one frame at the end containing the full palette.
+ */
+static int request_frame(AVFilterLink *outlink)
+{
+    AVFilterContext *ctx = outlink->src;
+    AVFilterLink *inlink = ctx->inputs[0];
+    PaletteGenContext *s = ctx->priv;
+    int r;
+
+    r = ff_request_frame(inlink);
+    if (r == AVERROR_EOF && !s->palette_pushed && s->nb_refs) {
+        r = ff_filter_frame(outlink, get_palette_frame(ctx));
+        s->palette_pushed = 1;
+        return r;
+    }
+    return r;
+}
+
+/**
+ * The output is one simple 16x16 squared-pixels palette.
+ */
+static int config_output(AVFilterLink *outlink)
+{
+    outlink->w = outlink->h = 16;
+    outlink->sample_aspect_ratio = av_make_q(1, 1);
+    outlink->flags |= FF_LINK_FLAG_REQUEST_LOOP;
+    return 0;
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    int i;
+    PaletteGenContext *s = ctx->priv;
+
+    for (i = 0; i < HIST_SIZE; i++)
+        av_freep(&s->histogram[i].entries);
+    av_freep(&s->refs);
+    av_frame_free(&s->prev_frame);
+}
+
+static const AVFilterPad palettegen_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .filter_frame = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad palettegen_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .config_props  = config_output,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
+
+AVFilter ff_vf_palettegen = {
+    .name          = "palettegen",
+    .description   = NULL_IF_CONFIG_SMALL("Find the optimal palette for a given stream."),
+    .priv_size     = sizeof(PaletteGenContext),
+    .uninit        = uninit,
+    .query_formats = query_formats,
+    .inputs        = palettegen_inputs,
+    .outputs       = palettegen_outputs,
+    .priv_class    = &palettegen_class,
+};
diff --git a/libavfilter/vf_paletteuse.c b/libavfilter/vf_paletteuse.c
new file mode 100644
index 0000000..8835d8b
--- /dev/null
+++ b/libavfilter/vf_paletteuse.c
@@ -0,0 +1,1071 @@
+/*
+ * Copyright (c) 2015 Stupeflix
+ *
+ * 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
+ * Use a palette to downsample an input video stream.
+ */
+
+#include "libavutil/bprint.h"
+#include "libavutil/opt.h"
+#include "libavutil/qsort.h"
+#include "dualinput.h"
+#include "avfilter.h"
+
+enum dithering_mode {
+    DITHERING_NONE,
+    DITHERING_BAYER,
+    DITHERING_HECKBERT,
+    DITHERING_FLOYD_STEINBERG,
+    DITHERING_SIERRA2,
+    DITHERING_SIERRA2_4A,
+    NB_DITHERING
+};
+
+enum color_search_method {
+    COLOR_SEARCH_NNS_ITERATIVE,
+    COLOR_SEARCH_NNS_RECURSIVE,
+    COLOR_SEARCH_BRUTEFORCE,
+    NB_COLOR_SEARCHES
+};
+
+enum diff_mode {
+    DIFF_MODE_NONE,
+    DIFF_MODE_RECTANGLE,
+    NB_DIFF_MODE
+};
+
+struct color_node {
+    uint8_t val[3];
+    uint8_t palette_id;
+    int split;
+    int left_id, right_id;
+};
+
+#define NBITS 5
+#define CACHE_SIZE (1<<(3*NBITS))
+
+struct cached_color {
+    uint32_t color;
+    uint8_t pal_entry;
+};
+
+struct cache_node {
+    struct cached_color *entries;
+    int nb_entries;
+};
+
+struct PaletteUseContext;
+
+typedef int (*set_frame_func)(struct PaletteUseContext *s, AVFrame *out, AVFrame *in,
+                              int x_start, int y_start, int width, int height);
+
+typedef struct PaletteUseContext {
+    const AVClass *class;
+    FFDualInputContext dinput;
+    struct cache_node cache[CACHE_SIZE];    /* lookup cache */
+    struct color_node map[AVPALETTE_COUNT]; /* 3D-Tree (KD-Tree with K=3) for reverse colormap */
+    uint32_t palette[AVPALETTE_COUNT];
+    int palette_loaded;
+    int dither;
+    set_frame_func set_frame;
+    int bayer_scale;
+    int ordered_dither[8*8];
+    int diff_mode;
+    AVFrame *last_in;
+    AVFrame *last_out;
+
+    /* debug options */
+    char *dot_filename;
+    int color_search_method;
+    int calc_mean_err;
+    uint64_t total_mean_err;
+    int debug_accuracy;
+} PaletteUseContext;
+
+#define OFFSET(x) offsetof(PaletteUseContext, x)
+#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
+static const AVOption paletteuse_options[] = {
+    { "dither", "select dithering mode", OFFSET(dither), AV_OPT_TYPE_INT, {.i64=DITHERING_SIERRA2_4A}, 0, NB_DITHERING-1, FLAGS, "dithering_mode" },
+        { "bayer",           "ordered 8x8 bayer dithering (deterministic)",                            0, AV_OPT_TYPE_CONST, {.i64=DITHERING_BAYER},           INT_MIN, INT_MAX, FLAGS, "dithering_mode" },
+        { "heckbert",        "dithering as defined by Paul Heckbert in 1982 (simple error diffusion)", 0, AV_OPT_TYPE_CONST, {.i64=DITHERING_HECKBERT},        INT_MIN, INT_MAX, FLAGS, "dithering_mode" },
+        { "floyd_steinberg", "Floyd and Steingberg dithering (error diffusion)",                       0, AV_OPT_TYPE_CONST, {.i64=DITHERING_FLOYD_STEINBERG}, INT_MIN, INT_MAX, FLAGS, "dithering_mode" },
+        { "sierra2",         "Frankie Sierra dithering v2 (error diffusion)",                          0, AV_OPT_TYPE_CONST, {.i64=DITHERING_SIERRA2},         INT_MIN, INT_MAX, FLAGS, "dithering_mode" },
+        { "sierra2_4a",      "Frankie Sierra dithering v2 \"Lite\" (error diffusion)",                 0, AV_OPT_TYPE_CONST, {.i64=DITHERING_SIERRA2_4A},      INT_MIN, INT_MAX, FLAGS, "dithering_mode" },
+    { "bayer_scale", "set scale for bayer dithering", OFFSET(bayer_scale), AV_OPT_TYPE_INT, {.i64=2}, 0, 5, FLAGS },
+    { "diff_mode",   "set frame difference mode",     OFFSET(diff_mode),   AV_OPT_TYPE_INT, {.i64=DIFF_MODE_NONE}, 0, NB_DIFF_MODE-1, FLAGS, "diff_mode" },
+        { "rectangle", "process smallest different rectangle", 0, AV_OPT_TYPE_CONST, {.i64=DIFF_MODE_RECTANGLE}, INT_MIN, INT_MAX, FLAGS, "diff_mode" },
+
+    /* following are the debug options, not part of the official API */
+    { "debug_kdtree", "save Graphviz graph of the kdtree in specified file", OFFSET(dot_filename), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS },
+    { "color_search", "set reverse colormap color search method", OFFSET(color_search_method), AV_OPT_TYPE_INT, {.i64=COLOR_SEARCH_NNS_ITERATIVE}, 0, NB_COLOR_SEARCHES-1, FLAGS, "search" },
+        { "nns_iterative", "iterative search",             0, AV_OPT_TYPE_CONST, {.i64=COLOR_SEARCH_NNS_ITERATIVE}, INT_MIN, INT_MAX, FLAGS, "search" },
+        { "nns_recursive", "recursive search",             0, AV_OPT_TYPE_CONST, {.i64=COLOR_SEARCH_NNS_RECURSIVE}, INT_MIN, INT_MAX, FLAGS, "search" },
+        { "bruteforce",    "brute-force into the palette", 0, AV_OPT_TYPE_CONST, {.i64=COLOR_SEARCH_BRUTEFORCE},    INT_MIN, INT_MAX, FLAGS, "search" },
+    { "mean_err", "compute and print mean error", OFFSET(calc_mean_err), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS },
+    { "debug_accuracy", "test color search accuracy", OFFSET(debug_accuracy), AV_OPT_TYPE_FLAGS, {.i64=0}, 0, 1, FLAGS },
+    { NULL }
+};
+
+AVFILTER_DEFINE_CLASS(paletteuse);
+
+static int query_formats(AVFilterContext *ctx)
+{
+    static const enum AVPixelFormat in_fmts[]    = {AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE};
+    static const enum AVPixelFormat inpal_fmts[] = {AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE};
+    static const enum AVPixelFormat out_fmts[]   = {AV_PIX_FMT_PAL8,  AV_PIX_FMT_NONE};
+    AVFilterFormats *in    = ff_make_format_list(in_fmts);
+    AVFilterFormats *inpal = ff_make_format_list(inpal_fmts);
+    AVFilterFormats *out   = ff_make_format_list(out_fmts);
+    if (!in || !inpal || !out) {
+        av_freep(&in);
+        av_freep(&inpal);
+        av_freep(&out);
+        return AVERROR(ENOMEM);
+    }
+    ff_formats_ref(in,    &ctx->inputs[0]->out_formats);
+    ff_formats_ref(inpal, &ctx->inputs[1]->out_formats);
+    ff_formats_ref(out,   &ctx->outputs[0]->in_formats);
+    return 0;
+}
+
+static av_always_inline int dither_color(uint32_t px, int er, int eg, int eb, int scale, int shift)
+{
+    return av_clip_uint8((px >> 16 & 0xff) + ((er * scale) / (1<<shift))) << 16
+         | av_clip_uint8((px >>  8 & 0xff) + ((eg * scale) / (1<<shift))) <<  8
+         | av_clip_uint8((px       & 0xff) + ((eb * scale) / (1<<shift)));
+}
+
+static av_always_inline int diff(const uint8_t *c1, const uint8_t *c2)
+{
+    // XXX: try L*a*b with CIE76 (dL*dL + da*da + db*db)
+    const int dr = c1[0] - c2[0];
+    const int dg = c1[1] - c2[1];
+    const int db = c1[2] - c2[2];
+    return dr*dr + dg*dg + db*db;
+}
+
+static av_always_inline uint8_t colormap_nearest_bruteforce(const uint32_t *palette, const uint8_t *rgb)
+{
+    int i, pal_id = -1, min_dist = INT_MAX;
+
+    for (i = 0; i < AVPALETTE_COUNT; i++) {
+        const uint32_t c = palette[i];
+
+        if ((c & 0xff000000) == 0xff000000) { // ignore transparent entry
+            const uint8_t palrgb[] = {
+                palette[i]>>16 & 0xff,
+                palette[i]>> 8 & 0xff,
+                palette[i]     & 0xff,
+            };
+            const int d = diff(palrgb, rgb);
+            if (d < min_dist) {
+                pal_id = i;
+                min_dist = d;
+            }
+        }
+    }
+    return pal_id;
+}
+
+/* Recursive form, simpler but a bit slower. Kept for reference. */
+struct nearest_color {
+    int node_pos;
+    int dist_sqd;
+};
+
+static void colormap_nearest_node(const struct color_node *map,
+                                  const int node_pos,
+                                  const uint8_t *target,
+                                  struct nearest_color *nearest)
+{
+    const struct color_node *kd = map + node_pos;
+    const int s = kd->split;
+    int dx, nearer_kd_id, further_kd_id;
+    const uint8_t *current = kd->val;
+    const int current_to_target = diff(target, current);
+
+    if (current_to_target < nearest->dist_sqd) {
+        nearest->node_pos = node_pos;
+        nearest->dist_sqd = current_to_target;
+    }
+
+    if (kd->left_id != -1 || kd->right_id != -1) {
+        dx = target[s] - current[s];
+
+        if (dx <= 0) nearer_kd_id = kd->left_id,  further_kd_id = kd->right_id;
+        else         nearer_kd_id = kd->right_id, further_kd_id = kd->left_id;
+
+        if (nearer_kd_id != -1)
+            colormap_nearest_node(map, nearer_kd_id, target, nearest);
+
+        if (further_kd_id != -1 && dx*dx < nearest->dist_sqd)
+            colormap_nearest_node(map, further_kd_id, target, nearest);
+    }
+}
+
+static av_always_inline uint8_t colormap_nearest_recursive(const struct color_node *node, const uint8_t *rgb)
+{
+    struct nearest_color res = {.dist_sqd = INT_MAX, .node_pos = -1};
+    colormap_nearest_node(node, 0, rgb, &res);
+    return node[res.node_pos].palette_id;
+}
+
+struct stack_node {
+    int color_id;
+    int dx2;
+};
+
+static av_always_inline uint8_t colormap_nearest_iterative(const struct color_node *root, const uint8_t *target)
+{
+    int pos = 0, best_node_id = -1, best_dist = INT_MAX, cur_color_id = 0;
+    struct stack_node nodes[16];
+    struct stack_node *node = &nodes[0];
+
+    for (;;) {
+
+        const struct color_node *kd = &root[cur_color_id];
+        const uint8_t *current = kd->val;
+        const int current_to_target = diff(target, current);
+
+        /* Compare current color node to the target and update our best node if
+         * it's actually better. */
+        if (current_to_target < best_dist) {
+            best_node_id = cur_color_id;
+            if (!current_to_target)
+                goto end; // exact match, we can return immediately
+            best_dist = current_to_target;
+        }
+
+        /* Check if it's not a leaf */
+        if (kd->left_id != -1 || kd->right_id != -1) {
+            const int split = kd->split;
+            const int dx = target[split] - current[split];
+            int nearer_kd_id, further_kd_id;
+
+            /* Define which side is the most interesting. */
+            if (dx <= 0) nearer_kd_id = kd->left_id,  further_kd_id = kd->right_id;
+            else         nearer_kd_id = kd->right_id, further_kd_id = kd->left_id;
+
+            if (nearer_kd_id != -1) {
+                if (further_kd_id != -1) {
+                    /* Here, both paths are defined, so we push a state for
+                     * when we are going back. */
+                    node->color_id = further_kd_id;
+                    node->dx2 = dx*dx;
+                    pos++;
+                    node++;
+                }
+                /* We can now update current color with the most probable path
+                 * (no need to create a state since there is nothing to save
+                 * anymore). */
+                cur_color_id = nearer_kd_id;
+                continue;
+            } else if (dx*dx < best_dist) {
+                /* The nearest path isn't available, so there is only one path
+                 * possible and it's the least probable. We enter it only if the
+                 * distance from the current point to the hyper rectangle is
+                 * less than our best distance. */
+                cur_color_id = further_kd_id;
+                continue;
+            }
+        }
+
+        /* Unstack as much as we can, typically as long as the least probable
+         * branch aren't actually probable. */
+        do {
+            if (--pos < 0)
+                goto end;
+            node--;
+        } while (node->dx2 >= best_dist);
+
+        /* We got a node where the least probable branch might actually contain
+         * a relevant color. */
+        cur_color_id = node->color_id;
+    }
+
+end:
+    return root[best_node_id].palette_id;
+}
+
+#define COLORMAP_NEAREST(search, palette, root, target)                                    \
+    search == COLOR_SEARCH_NNS_ITERATIVE ? colormap_nearest_iterative(root, target) :      \
+    search == COLOR_SEARCH_NNS_RECURSIVE ? colormap_nearest_recursive(root, target) :      \
+                                           colormap_nearest_bruteforce(palette, target)
+
+/**
+ * Check if the requested color is in the cache already. If not, find it in the
+ * color tree and cache it.
+ * Note: r, g, and b are the component of c but are passed as well to avoid
+ * recomputing them (they are generally computed by the caller for other uses).
+ */
+static av_always_inline int color_get(struct cache_node *cache, uint32_t color,
+                                      uint8_t r, uint8_t g, uint8_t b,
+                                      const struct color_node *map,
+                                      const uint32_t *palette,
+                                      const enum color_search_method search_method)
+{
+    int i;
+    const uint8_t rgb[] = {r, g, b};
+    const uint8_t rhash = r & ((1<<NBITS)-1);
+    const uint8_t ghash = g & ((1<<NBITS)-1);
+    const uint8_t bhash = b & ((1<<NBITS)-1);
+    const unsigned hash = rhash<<(NBITS*2) | ghash<<NBITS | bhash;
+    struct cache_node *node = &cache[hash];
+    struct cached_color *e;
+
+    for (i = 0; i < node->nb_entries; i++) {
+        e = &node->entries[i];
+        if (e->color == color)
+            return e->pal_entry;
+    }
+
+    e = av_dynarray2_add((void**)&node->entries, &node->nb_entries,
+                         sizeof(*node->entries), NULL);
+    if (!e)
+        return AVERROR(ENOMEM);
+    e->color = color;
+    e->pal_entry = COLORMAP_NEAREST(search_method, palette, map, rgb);
+    return e->pal_entry;
+}
+
+static av_always_inline int get_dst_color_err(struct cache_node *cache,
+                                              uint32_t c, const struct color_node *map,
+                                              const uint32_t *palette,
+                                              int *er, int *eg, int *eb,
+                                              const enum color_search_method search_method)
+{
+    const uint8_t r = c >> 16 & 0xff;
+    const uint8_t g = c >>  8 & 0xff;
+    const uint8_t b = c       & 0xff;
+    const int dstx = color_get(cache, c, r, g, b, map, palette, search_method);
+    const uint32_t dstc = palette[dstx];
+    *er = r - (dstc >> 16 & 0xff);
+    *eg = g - (dstc >>  8 & 0xff);
+    *eb = b - (dstc       & 0xff);
+    return dstx;
+}
+
+static av_always_inline int set_frame(PaletteUseContext *s, AVFrame *out, AVFrame *in,
+                                      int x_start, int y_start, int w, int h,
+                                      enum dithering_mode dither,
+                                      const enum color_search_method search_method)
+{
+    int x, y;
+    const struct color_node *map = s->map;
+    struct cache_node *cache = s->cache;
+    const uint32_t *palette = s->palette;
+    const int src_linesize = in ->linesize[0] >> 2;
+    const int dst_linesize = out->linesize[0];
+    uint32_t *src = ((uint32_t *)in ->data[0]) + y_start*src_linesize;
+    uint8_t  *dst =              out->data[0]  + y_start*dst_linesize;
+
+    w += x_start;
+    h += y_start;
+
+    for (y = y_start; y < h; y++) {
+        for (x = x_start; x < w; x++) {
+            int er, eg, eb;
+
+            if (dither == DITHERING_BAYER) {
+                const int d = s->ordered_dither[(y & 7)<<3 | (x & 7)];
+                const uint8_t r8 = src[x] >> 16 & 0xff;
+                const uint8_t g8 = src[x] >>  8 & 0xff;
+                const uint8_t b8 = src[x]       & 0xff;
+                const uint8_t r = av_clip_uint8(r8 + d);
+                const uint8_t g = av_clip_uint8(g8 + d);
+                const uint8_t b = av_clip_uint8(b8 + d);
+                const uint32_t c = r<<16 | g<<8 | b;
+                const int color = color_get(cache, c, r, g, b, map, palette, search_method);
+
+                if (color < 0)
+                    return color;
+                dst[x] = color;
+
+            } else if (dither == DITHERING_HECKBERT) {
+                const int right = x < w - 1, down = y < h - 1;
+                const int color = get_dst_color_err(cache, src[x], map, palette, &er, &eg, &eb, search_method);
+
+                if (color < 0)
+                    return color;
+                dst[x] = color;
+
+                if (right)         src[               x + 1] = dither_color(src[               x + 1], er, eg, eb, 3, 3);
+                if (         down) src[src_linesize + x    ] = dither_color(src[src_linesize + x    ], er, eg, eb, 3, 3);
+                if (right && down) src[src_linesize + x + 1] = dither_color(src[src_linesize + x + 1], er, eg, eb, 2, 3);
+
+            } else if (dither == DITHERING_FLOYD_STEINBERG) {
+                const int right = x < w - 1, down = y < h - 1, left = x > x_start;
+                const int color = get_dst_color_err(cache, src[x], map, palette, &er, &eg, &eb, search_method);
+
+                if (color < 0)
+                    return color;
+                dst[x] = color;
+
+                if (right)         src[               x + 1] = dither_color(src[               x + 1], er, eg, eb, 7, 4);
+                if (left  && down) src[src_linesize + x - 1] = dither_color(src[src_linesize + x - 1], er, eg, eb, 3, 4);
+                if (         down) src[src_linesize + x    ] = dither_color(src[src_linesize + x    ], er, eg, eb, 5, 4);
+                if (right && down) src[src_linesize + x + 1] = dither_color(src[src_linesize + x + 1], er, eg, eb, 1, 4);
+
+            } else if (dither == DITHERING_SIERRA2) {
+                const int right  = x < w - 1, down  = y < h - 1, left  = x > x_start;
+                const int right2 = x < w - 2,                    left2 = x > x_start + 1;
+                const int color = get_dst_color_err(cache, src[x], map, palette, &er, &eg, &eb, search_method);
+
+                if (color < 0)
+                    return color;
+                dst[x] = color;
+
+                if (right)          src[                 x + 1] = dither_color(src[                 x + 1], er, eg, eb, 4, 4);
+                if (right2)         src[                 x + 2] = dither_color(src[                 x + 2], er, eg, eb, 3, 4);
+
+                if (down) {
+                    if (left2)      src[  src_linesize + x - 2] = dither_color(src[  src_linesize + x - 2], er, eg, eb, 1, 4);
+                    if (left)       src[  src_linesize + x - 1] = dither_color(src[  src_linesize + x - 1], er, eg, eb, 2, 4);
+                                    src[  src_linesize + x    ] = dither_color(src[  src_linesize + x    ], er, eg, eb, 3, 4);
+                    if (right)      src[  src_linesize + x + 1] = dither_color(src[  src_linesize + x + 1], er, eg, eb, 2, 4);
+                    if (right2)     src[  src_linesize + x + 2] = dither_color(src[  src_linesize + x + 2], er, eg, eb, 1, 4);
+                }
+
+            } else if (dither == DITHERING_SIERRA2_4A) {
+                const int right = x < w - 1, down = y < h - 1, left = x > x_start;
+                const int color = get_dst_color_err(cache, src[x], map, palette, &er, &eg, &eb, search_method);
+
+                if (color < 0)
+                    return color;
+                dst[x] = color;
+
+                if (right)         src[               x + 1] = dither_color(src[               x + 1], er, eg, eb, 2, 2);
+                if (left  && down) src[src_linesize + x - 1] = dither_color(src[src_linesize + x - 1], er, eg, eb, 1, 2);
+                if (         down) src[src_linesize + x    ] = dither_color(src[src_linesize + x    ], er, eg, eb, 1, 2);
+
+            } else {
+                const uint8_t r = src[x] >> 16 & 0xff;
+                const uint8_t g = src[x] >>  8 & 0xff;
+                const uint8_t b = src[x]       & 0xff;
+                const int color = color_get(cache, src[x] & 0xffffff, r, g, b, map, palette, search_method);
+
+                if (color < 0)
+                    return color;
+                dst[x] = color;
+            }
+        }
+        src += src_linesize;
+        dst += dst_linesize;
+    }
+    return 0;
+}
+
+#define INDENT 4
+static void disp_node(AVBPrint *buf,
+                      const struct color_node *map,
+                      int parent_id, int node_id,
+                      int depth)
+{
+    const struct color_node *node = &map[node_id];
+    const uint32_t fontcolor = node->val[0] > 0x50 &&
+                               node->val[1] > 0x50 &&
+                               node->val[2] > 0x50 ? 0 : 0xffffff;
+    av_bprintf(buf, "%*cnode%d ["
+               "label=\"%c%02X%c%02X%c%02X%c\" "
+               "fillcolor=\"#%02x%02x%02x\" "
+               "fontcolor=\"#%06X\"]\n",
+               depth*INDENT, ' ', node->palette_id,
+               "[  "[node->split], node->val[0],
+               "][ "[node->split], node->val[1],
+               " ]["[node->split], node->val[2],
+               "  ]"[node->split],
+               node->val[0], node->val[1], node->val[2],
+               fontcolor);
+    if (parent_id != -1)
+        av_bprintf(buf, "%*cnode%d -> node%d\n", depth*INDENT, ' ',
+                   map[parent_id].palette_id, node->palette_id);
+    if (node->left_id  != -1) disp_node(buf, map, node_id, node->left_id,  depth + 1);
+    if (node->right_id != -1) disp_node(buf, map, node_id, node->right_id, depth + 1);
+}
+
+// debug_kdtree=kdtree.dot -> dot -Tpng kdtree.dot > kdtree.png
+static int disp_tree(const struct color_node *node, const char *fname)
+{
+    AVBPrint buf;
+    FILE *f = av_fopen_utf8(fname, "w");
+
+    if (!f) {
+        int ret = AVERROR(errno);
+        av_log(NULL, AV_LOG_ERROR, "Cannot open file '%s' for writing: %s\n",
+               fname, av_err2str(ret));
+        return ret;
+    }
+
+    av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
+
+    av_bprintf(&buf, "digraph {\n");
+    av_bprintf(&buf, "    node [style=filled fontsize=10 shape=box]\n");
+    disp_node(&buf, node, -1, 0, 0);
+    av_bprintf(&buf, "}\n");
+
+    fwrite(buf.str, 1, buf.len, f);
+    fclose(f);
+    av_bprint_finalize(&buf, NULL);
+    return 0;
+}
+
+static int debug_accuracy(const struct color_node *node, const uint32_t *palette,
+                          const enum color_search_method search_method)
+{
+    int r, g, b, ret = 0;
+
+    for (r = 0; r < 256; r++) {
+        for (g = 0; g < 256; g++) {
+            for (b = 0; b < 256; b++) {
+                const uint8_t rgb[] = {r, g, b};
+                const int r1 = COLORMAP_NEAREST(search_method, palette, node, rgb);
+                const int r2 = colormap_nearest_bruteforce(palette, rgb);
+                if (r1 != r2) {
+                    const uint32_t c1 = palette[r1];
+                    const uint32_t c2 = palette[r2];
+                    const uint8_t palrgb1[] = { c1>>16 & 0xff, c1>> 8 & 0xff, c1 & 0xff };
+                    const uint8_t palrgb2[] = { c2>>16 & 0xff, c2>> 8 & 0xff, c2 & 0xff };
+                    const int d1 = diff(palrgb1, rgb);
+                    const int d2 = diff(palrgb2, rgb);
+                    if (d1 != d2) {
+                        av_log(NULL, AV_LOG_ERROR,
+                               "/!\\ %02X%02X%02X: %d ! %d (%06X ! %06X) / dist: %d ! %d\n",
+                               r, g, b, r1, r2, c1 & 0xffffff, c2 & 0xffffff, d1, d2);
+                        ret = 1;
+                    }
+                }
+            }
+        }
+    }
+    return ret;
+}
+
+struct color {
+    uint32_t value;
+    uint8_t pal_id;
+};
+
+struct color_rect {
+    uint8_t min[3];
+    uint8_t max[3];
+};
+
+typedef int (*cmp_func)(const void *, const void *);
+
+#define DECLARE_CMP_FUNC(name, pos)                     \
+static int cmp_##name(const void *pa, const void *pb)   \
+{                                                       \
+    const struct color *a = pa;                         \
+    const struct color *b = pb;                         \
+    return   (a->value >> (8 * (2 - (pos))) & 0xff)     \
+           - (b->value >> (8 * (2 - (pos))) & 0xff);    \
+}
+
+DECLARE_CMP_FUNC(r, 0)
+DECLARE_CMP_FUNC(g, 1)
+DECLARE_CMP_FUNC(b, 2)
+
+static const cmp_func cmp_funcs[] = {cmp_r, cmp_g, cmp_b};
+
+static int get_next_color(const uint8_t *color_used, const uint32_t *palette,
+                          int *component, const struct color_rect *box)
+{
+    int wr, wg, wb;
+    int i, longest = 0;
+    unsigned nb_color = 0;
+    struct color_rect ranges;
+    struct color tmp_pal[256];
+    cmp_func cmpf;
+
+    ranges.min[0] = ranges.min[1] = ranges.min[2] = 0xff;
+    ranges.max[0] = ranges.max[1] = ranges.max[2] = 0x00;
+
+    for (i = 0; i < AVPALETTE_COUNT; i++) {
+        const uint32_t c = palette[i];
+        const uint8_t r = c >> 16 & 0xff;
+        const uint8_t g = c >>  8 & 0xff;
+        const uint8_t b = c       & 0xff;
+
+        if (color_used[i] ||
+            r < box->min[0] || g < box->min[1] || b < box->min[2] ||
+            r > box->max[0] || g > box->max[1] || b > box->max[2])
+            continue;
+
+        if (r < ranges.min[0]) ranges.min[0] = r;
+        if (g < ranges.min[1]) ranges.min[1] = g;
+        if (b < ranges.min[2]) ranges.min[2] = b;
+
+        if (r > ranges.max[0]) ranges.max[0] = r;
+        if (g > ranges.max[1]) ranges.max[1] = g;
+        if (b > ranges.max[2]) ranges.max[2] = b;
+
+        tmp_pal[nb_color].value  = c;
+        tmp_pal[nb_color].pal_id = i;
+
+        nb_color++;
+    }
+
+    if (!nb_color)
+        return -1;
+
+    /* define longest axis that will be the split component */
+    wr = ranges.max[0] - ranges.min[0];
+    wg = ranges.max[1] - ranges.min[1];
+    wb = ranges.max[2] - ranges.min[2];
+    if (wr >= wg && wr >= wb) longest = 0;
+    if (wg >= wr && wg >= wb) longest = 1;
+    if (wb >= wr && wb >= wg) longest = 2;
+    cmpf = cmp_funcs[longest];
+    *component = longest;
+
+    /* sort along this axis to get median */
+    AV_QSORT(tmp_pal, nb_color, struct color, cmpf);
+
+    return tmp_pal[nb_color >> 1].pal_id;
+}
+
+static int colormap_insert(struct color_node *map,
+                           uint8_t *color_used,
+                           int *nb_used,
+                           const uint32_t *palette,
+                           const struct color_rect *box)
+{
+    uint32_t c;
+    int component, cur_id;
+    int node_left_id = -1, node_right_id = -1;
+    struct color_node *node;
+    struct color_rect box1, box2;
+    const int pal_id = get_next_color(color_used, palette, &component, box);
+
+    if (pal_id < 0)
+        return -1;
+
+    /* create new node with that color */
+    cur_id = (*nb_used)++;
+    c = palette[pal_id];
+    node = &map[cur_id];
+    node->split = component;
+    node->palette_id = pal_id;
+    node->val[0] = c>>16 & 0xff;
+    node->val[1] = c>> 8 & 0xff;
+    node->val[2] = c     & 0xff;
+
+    color_used[pal_id] = 1;
+
+    /* get the two boxes this node creates */
+    box1 = box2 = *box;
+    box1.max[component] = node->val[component];
+    box2.min[component] = node->val[component] + 1;
+
+    node_left_id = colormap_insert(map, color_used, nb_used, palette, &box1);
+
+    if (box2.min[component] <= box2.max[component])
+        node_right_id = colormap_insert(map, color_used, nb_used, palette, &box2);
+
+    node->left_id  = node_left_id;
+    node->right_id = node_right_id;
+
+    return cur_id;
+}
+
+static int cmp_pal_entry(const void *a, const void *b)
+{
+    const int c1 = *(const uint32_t *)a & 0xffffff;
+    const int c2 = *(const uint32_t *)b & 0xffffff;
+    return c1 - c2;
+}
+
+static void load_colormap(PaletteUseContext *s)
+{
+    int i, nb_used = 0;
+    uint8_t color_used[AVPALETTE_COUNT] = {0};
+    uint32_t last_color = 0;
+    struct color_rect box;
+
+    /* disable transparent colors and dups */
+    qsort(s->palette, AVPALETTE_COUNT, sizeof(*s->palette), cmp_pal_entry);
+    for (i = 0; i < AVPALETTE_COUNT; i++) {
+        const uint32_t c = s->palette[i];
+        if (i != 0 && c == last_color) {
+            color_used[i] = 1;
+            continue;
+        }
+        last_color = c;
+        if ((c & 0xff000000) != 0xff000000) {
+            color_used[i] = 1; // ignore transparent color(s)
+            continue;
+        }
+    }
+
+    box.min[0] = box.min[1] = box.min[2] = 0x00;
+    box.max[0] = box.max[1] = box.max[2] = 0xff;
+
+    colormap_insert(s->map, color_used, &nb_used, s->palette, &box);
+
+    if (s->dot_filename)
+        disp_tree(s->map, s->dot_filename);
+
+    if (s->debug_accuracy) {
+        if (!debug_accuracy(s->map, s->palette, s->color_search_method))
+            av_log(NULL, AV_LOG_INFO, "Accuracy check passed\n");
+    }
+}
+
+static void debug_mean_error(PaletteUseContext *s, const AVFrame *in1,
+                             const AVFrame *in2, int frame_count)
+{
+    int x, y;
+    const uint32_t *palette = s->palette;
+    uint32_t *src1 = (uint32_t *)in1->data[0];
+    uint8_t  *src2 =             in2->data[0];
+    const int src1_linesize = in1->linesize[0] >> 2;
+    const int src2_linesize = in2->linesize[0];
+    const float div = in1->width * in1->height * 3;
+    unsigned mean_err = 0;
+
+    for (y = 0; y < in1->height; y++) {
+        for (x = 0; x < in1->width; x++) {
+            const uint32_t c1 = src1[x];
+            const uint32_t c2 = palette[src2[x]];
+            const uint8_t rgb1[] = {c1 >> 16 & 0xff, c1 >> 8 & 0xff, c1 & 0xff};
+            const uint8_t rgb2[] = {c2 >> 16 & 0xff, c2 >> 8 & 0xff, c2 & 0xff};
+            mean_err += diff(rgb1, rgb2);
+        }
+        src1 += src1_linesize;
+        src2 += src2_linesize;
+    }
+
+    s->total_mean_err += mean_err;
+
+    av_log(NULL, AV_LOG_INFO, "MEP:%.3f TotalMEP:%.3f\n",
+           mean_err / div, s->total_mean_err / (div * frame_count));
+}
+
+static void set_processing_window(enum diff_mode diff_mode,
+                                  const AVFrame *prv_src, const AVFrame *cur_src,
+                                  const AVFrame *prv_dst,       AVFrame *cur_dst,
+                                  int *xp, int *yp, int *wp, int *hp)
+{
+    int x_start = 0, y_start = 0;
+    int width  = cur_src->width;
+    int height = cur_src->height;
+
+    if (prv_src && diff_mode == DIFF_MODE_RECTANGLE) {
+        int y;
+        int x_end = cur_src->width  - 1,
+            y_end = cur_src->height - 1;
+        const uint32_t *prv_srcp = (const uint32_t *)prv_src->data[0];
+        const uint32_t *cur_srcp = (const uint32_t *)cur_src->data[0];
+        const uint8_t  *prv_dstp = prv_dst->data[0];
+        uint8_t        *cur_dstp = cur_dst->data[0];
+
+        const int prv_src_linesize = prv_src->linesize[0] >> 2;
+        const int cur_src_linesize = cur_src->linesize[0] >> 2;
+        const int prv_dst_linesize = prv_dst->linesize[0];
+        const int cur_dst_linesize = cur_dst->linesize[0];
+
+        /* skip common lines */
+        while (y_start < y_end && !memcmp(prv_srcp + y_start*prv_src_linesize,
+                                          cur_srcp + y_start*cur_src_linesize,
+                                          cur_src->width * 4)) {
+            memcpy(cur_dstp + y_start*cur_dst_linesize,
+                   prv_dstp + y_start*prv_dst_linesize,
+                   cur_dst->width);
+            y_start++;
+        }
+        while (y_end > y_start && !memcmp(prv_srcp + y_end*prv_src_linesize,
+                                          cur_srcp + y_end*cur_src_linesize,
+                                          cur_src->width * 4)) {
+            memcpy(cur_dstp + y_end*cur_dst_linesize,
+                   prv_dstp + y_end*prv_dst_linesize,
+                   cur_dst->width);
+            y_end--;
+        }
+
+        height = y_end + 1 - y_start;
+
+        /* skip common columns */
+        while (x_start < x_end) {
+            int same_column = 1;
+            for (y = y_start; y <= y_end; y++) {
+                if (prv_srcp[y*prv_src_linesize + x_start] != cur_srcp[y*cur_src_linesize + x_start]) {
+                    same_column = 0;
+                    break;
+                }
+            }
+            if (!same_column)
+                break;
+            x_start++;
+        }
+        while (x_end > x_start) {
+            int same_column = 1;
+            for (y = y_start; y <= y_end; y++) {
+                if (prv_srcp[y*prv_src_linesize + x_end] != cur_srcp[y*cur_src_linesize + x_end]) {
+                    same_column = 0;
+                    break;
+                }
+            }
+            if (!same_column)
+                break;
+            x_end--;
+        }
+        width = x_end + 1 - x_start;
+
+        if (x_start) {
+            for (y = y_start; y <= y_end; y++)
+                memcpy(cur_dstp + y*cur_dst_linesize,
+                       prv_dstp + y*prv_dst_linesize, x_start);
+        }
+        if (x_end != cur_src->width - 1) {
+            const int copy_len = cur_src->width - 1 - x_end;
+            for (y = y_start; y <= y_end; y++)
+                memcpy(cur_dstp + y*cur_dst_linesize + x_end + 1,
+                       prv_dstp + y*prv_dst_linesize + x_end + 1,
+                       copy_len);
+        }
+    }
+    *xp = x_start;
+    *yp = y_start;
+    *wp = width;
+    *hp = height;
+}
+
+static AVFrame *apply_palette(AVFilterLink *inlink, AVFrame *in)
+{
+    int x, y, w, h;
+    AVFilterContext *ctx = inlink->dst;
+    PaletteUseContext *s = ctx->priv;
+    AVFilterLink *outlink = inlink->dst->outputs[0];
+
+    AVFrame *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
+    if (!out) {
+        av_frame_free(&in);
+        return NULL;
+    }
+    av_frame_copy_props(out, in);
+
+    set_processing_window(s->diff_mode, s->last_in, in,
+                          s->last_out, out, &x, &y, &w, &h);
+    av_frame_free(&s->last_in);
+    av_frame_free(&s->last_out);
+    s->last_in  = av_frame_clone(in);
+    s->last_out = av_frame_clone(out);
+    if (!s->last_in || !s->last_out ||
+        av_frame_make_writable(s->last_in) < 0) {
+        av_frame_free(&in);
+        av_frame_free(&out);
+        return NULL;
+    }
+
+    av_dlog(ctx, "%dx%d rect: (%d;%d) -> (%d,%d) [area:%dx%d]\n",
+            w, h, x, y, x+w, y+h, in->width, in->height);
+
+    if (s->set_frame(s, out, in, x, y, w, h) < 0) {
+        av_frame_free(&out);
+        return NULL;
+    }
+    memcpy(out->data[1], s->palette, AVPALETTE_SIZE);
+    if (s->calc_mean_err)
+        debug_mean_error(s, in, out, inlink->frame_count);
+    av_frame_free(&in);
+    return out;
+}
+
+static int config_output(AVFilterLink *outlink)
+{
+    int ret;
+    AVFilterContext *ctx = outlink->src;
+    PaletteUseContext *s = ctx->priv;
+
+    outlink->w = ctx->inputs[0]->w;
+    outlink->h = ctx->inputs[0]->h;
+
+    outlink->time_base = ctx->inputs[0]->time_base;
+    if ((ret = ff_dualinput_init(ctx, &s->dinput)) < 0)
+        return ret;
+    return 0;
+}
+
+static int config_input_palette(AVFilterLink *inlink)
+{
+    AVFilterContext *ctx = inlink->dst;
+
+    if (inlink->w * inlink->h != AVPALETTE_COUNT) {
+        av_log(ctx, AV_LOG_ERROR,
+               "Palette input must contain exactly %d pixels. "
+               "Specified input has %dx%d=%d pixels\n",
+               AVPALETTE_COUNT, inlink->w, inlink->h,
+               inlink->w * inlink->h);
+        return AVERROR(EINVAL);
+    }
+    return 0;
+}
+
+static void load_palette(PaletteUseContext *s, const AVFrame *palette_frame)
+{
+    int i, x, y;
+    const uint32_t *p = (const uint32_t *)palette_frame->data[0];
+    const int p_linesize = palette_frame->linesize[0] >> 2;
+
+    i = 0;
+    for (y = 0; y < palette_frame->height; y++) {
+        for (x = 0; x < palette_frame->width; x++)
+            s->palette[i++] = p[x];
+        p += p_linesize;
+    }
+
+    load_colormap(s);
+
+    s->palette_loaded = 1;
+}
+
+static AVFrame *load_apply_palette(AVFilterContext *ctx, AVFrame *main,
+                                   const AVFrame *second)
+{
+    AVFilterLink *inlink = ctx->inputs[0];
+    PaletteUseContext *s = ctx->priv;
+    if (!s->palette_loaded) {
+        load_palette(s, second);
+    }
+    return apply_palette(inlink, main);
+}
+
+static int filter_frame(AVFilterLink *inlink, AVFrame *in)
+{
+    PaletteUseContext *s = inlink->dst->priv;
+    return ff_dualinput_filter_frame(&s->dinput, inlink, in);
+}
+
+#define DEFINE_SET_FRAME(color_search, name, value)                             \
+static int set_frame_##name(PaletteUseContext *s, AVFrame *out, AVFrame *in,    \
+                            int x_start, int y_start, int w, int h)             \
+{                                                                               \
+    return set_frame(s, out, in, x_start, y_start, w, h, value, color_search);  \
+}
+
+#define DEFINE_SET_FRAME_COLOR_SEARCH(color_search, color_search_macro)                                 \
+    DEFINE_SET_FRAME(color_search_macro, color_search##_##none,            DITHERING_NONE)              \
+    DEFINE_SET_FRAME(color_search_macro, color_search##_##bayer,           DITHERING_BAYER)             \
+    DEFINE_SET_FRAME(color_search_macro, color_search##_##heckbert,        DITHERING_HECKBERT)          \
+    DEFINE_SET_FRAME(color_search_macro, color_search##_##floyd_steinberg, DITHERING_FLOYD_STEINBERG)   \
+    DEFINE_SET_FRAME(color_search_macro, color_search##_##sierra2,         DITHERING_SIERRA2)           \
+    DEFINE_SET_FRAME(color_search_macro, color_search##_##sierra2_4a,      DITHERING_SIERRA2_4A)        \
+
+DEFINE_SET_FRAME_COLOR_SEARCH(nns_iterative, COLOR_SEARCH_NNS_ITERATIVE)
+DEFINE_SET_FRAME_COLOR_SEARCH(nns_recursive, COLOR_SEARCH_NNS_RECURSIVE)
+DEFINE_SET_FRAME_COLOR_SEARCH(bruteforce,    COLOR_SEARCH_BRUTEFORCE)
+
+#define DITHERING_ENTRIES(color_search) {       \
+    set_frame_##color_search##_none,            \
+    set_frame_##color_search##_bayer,           \
+    set_frame_##color_search##_heckbert,        \
+    set_frame_##color_search##_floyd_steinberg, \
+    set_frame_##color_search##_sierra2,         \
+    set_frame_##color_search##_sierra2_4a,      \
+}
+
+static const set_frame_func set_frame_lut[NB_COLOR_SEARCHES][NB_DITHERING] = {
+    DITHERING_ENTRIES(nns_iterative),
+    DITHERING_ENTRIES(nns_recursive),
+    DITHERING_ENTRIES(bruteforce),
+};
+
+static int dither_value(int p)
+{
+    const int q = p ^ (p >> 3);
+    return   (p & 4) >> 2 | (q & 4) >> 1 \
+           | (p & 2) << 1 | (q & 2) << 2 \
+           | (p & 1) << 4 | (q & 1) << 5;
+}
+
+static av_cold int init(AVFilterContext *ctx)
+{
+    PaletteUseContext *s = ctx->priv;
+    s->dinput.repeatlast = 1; // only 1 frame in the palette
+    s->dinput.process    = load_apply_palette;
+
+    s->set_frame = set_frame_lut[s->color_search_method][s->dither];
+
+    if (s->dither == DITHERING_BAYER) {
+        int i;
+        const int delta = 1 << (5 - s->bayer_scale); // to avoid too much luma
+
+        for (i = 0; i < FF_ARRAY_ELEMS(s->ordered_dither); i++)
+            s->ordered_dither[i] = (dither_value(i) >> s->bayer_scale) - delta;
+    }
+
+    return 0;
+}
+
+static int request_frame(AVFilterLink *outlink)
+{
+    PaletteUseContext *s = outlink->src->priv;
+    return ff_dualinput_request_frame(&s->dinput, outlink);
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    int i;
+    PaletteUseContext *s = ctx->priv;
+
+    ff_dualinput_uninit(&s->dinput);
+    for (i = 0; i < CACHE_SIZE; i++)
+        av_freep(&s->cache[i].entries);
+    av_frame_free(&s->last_in);
+    av_frame_free(&s->last_out);
+}
+
+static const AVFilterPad paletteuse_inputs[] = {
+    {
+        .name           = "default",
+        .type           = AVMEDIA_TYPE_VIDEO,
+        .filter_frame   = filter_frame,
+        .needs_writable = 1, // for error diffusal dithering
+    },{
+        .name           = "palette",
+        .type           = AVMEDIA_TYPE_VIDEO,
+        .config_props   = config_input_palette,
+        .filter_frame   = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad paletteuse_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .config_props  = config_output,
+        .request_frame = request_frame,
+    },
+    { NULL }
+};
+
+AVFilter ff_vf_paletteuse = {
+    .name          = "paletteuse",
+    .description   = NULL_IF_CONFIG_SMALL("Use a palette to downsample an input video stream."),
+    .priv_size     = sizeof(PaletteUseContext),
+    .query_formats = query_formats,
+    .init          = init,
+    .uninit        = uninit,
+    .inputs        = paletteuse_inputs,
+    .outputs       = paletteuse_outputs,
+    .priv_class    = &paletteuse_class,
+};
diff --git a/libavfilter/vf_perspective.c b/libavfilter/vf_perspective.c
index bebe37f..2f2032e 100644
--- a/libavfilter/vf_perspective.c
+++ b/libavfilter/vf_perspective.c
@@ -320,7 +320,7 @@
             }
 
             sum = (sum + (1<<(COEFF_BITS * 2 - 1))) >> (COEFF_BITS * 2);
-            sum = av_clip(sum, 0, 255);
+            sum = av_clip_uint8(sum);
             dst[x + y * dst_linesize] = sum;
         }
     }
@@ -395,7 +395,7 @@
                 }
             }
 
-            sum = av_clip(sum, 0, 255);
+            sum = av_clip_uint8(sum);
             dst[x + y * dst_linesize] = sum;
         }
     }
diff --git a/libavfilter/vf_phase.c b/libavfilter/vf_phase.c
index 82dc603..1818355 100644
--- a/libavfilter/vf_phase.c
+++ b/libavfilter/vf_phase.c
@@ -41,7 +41,7 @@
 
 typedef struct PhaseContext {
     const AVClass *class;
-    enum PhaseMode mode;
+    int mode;                   ///<PhaseMode
     AVFrame *frame; /* previous frame */
     int nb_planes;
     int planeheight[4];
@@ -106,7 +106,7 @@
  *
  * (The result is actually multiplied by 25)
  */
-#define DIFF(a, as, b, bs) (t = ((*a - b[bs]) << 2) + a[as << 1] - b[-bs], t * t)
+#define DIFF(a, as, b, bs) ((t) = ((*(a) - (b)[bs]) << 2) + (a)[(as) << 1] - (b)[-(bs)], (t) * (t))
 
 /*
  * Find which field combination has the smallest average squared difference
diff --git a/libavfilter/vf_pp.c b/libavfilter/vf_pp.c
index e33ac48..ff60e61 100644
--- a/libavfilter/vf_pp.c
+++ b/libavfilter/vf_pp.c
@@ -75,7 +75,7 @@
 
 static int pp_query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
+    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_YUV411P,
diff --git a/libavfilter/vf_pp7.c b/libavfilter/vf_pp7.c
index 0a70902..4761728 100644
--- a/libavfilter/vf_pp7.c
+++ b/libavfilter/vf_pp7.c
@@ -79,13 +79,6 @@
     N / (N2 * N0), N / (N2 * N1), N / (N2 * N0), N / (N2 * N2),
 };
 
-static const int thres[16] = {
-    N / (SN0 * SN0), N / (SN0 * SN2), N / (SN0 * SN0), N / (SN0 * SN2),
-    N / (SN2 * SN0), N / (SN2 * SN2), N / (SN2 * SN0), N / (SN2 * SN2),
-    N / (SN0 * SN0), N / (SN0 * SN2), N / (SN0 * SN0), N / (SN0 * SN2),
-    N / (SN2 * SN0), N / (SN2 * SN2), N / (SN2 * SN0), N / (SN2 * SN2),
-};
-
 static void init_thres2(PP7Context *p)
 {
     int qp, i;
@@ -272,7 +265,7 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
+    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,
diff --git a/libavfilter/vf_psnr.c b/libavfilter/vf_psnr.c
index 082612a..a76a9f9 100644
--- a/libavfilter/vf_psnr.c
+++ b/libavfilter/vf_psnr.c
@@ -217,7 +217,7 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
+    static const enum AVPixelFormat pix_fmts[] = {
         AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY16,
 #define PF_NOALPHA(suf) AV_PIX_FMT_YUV420##suf,  AV_PIX_FMT_YUV422##suf,  AV_PIX_FMT_YUV444##suf
 #define PF_ALPHA(suf)   AV_PIX_FMT_YUVA420##suf, AV_PIX_FMT_YUVA422##suf, AV_PIX_FMT_YUVA444##suf
diff --git a/libavfilter/vf_qp.c b/libavfilter/vf_qp.c
index 9c0679a..d976634 100644
--- a/libavfilter/vf_qp.c
+++ b/libavfilter/vf_qp.c
@@ -95,6 +95,7 @@
 
     out = av_frame_clone(in);
     if (!out) {
+        av_buffer_unref(&out_qp_table_buf);
         ret = AVERROR(ENOMEM);
         goto fail;
     }
diff --git a/libavfilter/vf_removelogo.c b/libavfilter/vf_removelogo.c
index 555517f..dd7629f 100644
--- a/libavfilter/vf_removelogo.c
+++ b/libavfilter/vf_removelogo.c
@@ -114,7 +114,7 @@
  * opinion. This will calculate only at init-time, so you can put a
  * long expression here without effecting performance.
  */
-#define apply_mask_fudge_factor(x) (((x) >> 2) + x)
+#define apply_mask_fudge_factor(x) (((x) >> 2) + (x))
 
 /**
  * Pre-process an image to give distance information.
diff --git a/libavfilter/vf_repeatfields.c b/libavfilter/vf_repeatfields.c
new file mode 100644
index 0000000..5dbfd52
--- /dev/null
+++ b/libavfilter/vf_repeatfields.c
@@ -0,0 +1,191 @@
+/*
+ * Copyright (c) 2003 Tobias Diedrich
+ *
+ * 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.
+ */
+
+#include "libavutil/imgutils.h"
+#include "avfilter.h"
+#include "internal.h"
+
+typedef struct RepeatFieldsContext {
+    const AVClass *class;
+    int state;
+    int nb_planes;
+    int linesize[4];
+    int planeheight[4];
+    AVFrame *frame;
+} RepeatFieldsContext;
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    RepeatFieldsContext *s = ctx->priv;
+
+    av_frame_free(&s->frame);
+}
+
+static int query_formats(AVFilterContext *ctx)
+{
+    static const enum AVPixelFormat pixel_fmts_eq[] = {
+        AV_PIX_FMT_GRAY8,
+        AV_PIX_FMT_YUV410P,
+        AV_PIX_FMT_YUV411P,
+        AV_PIX_FMT_YUV420P,
+        AV_PIX_FMT_YUV422P,
+        AV_PIX_FMT_YUV444P,
+        AV_PIX_FMT_NONE
+    };
+
+    ff_set_common_formats(ctx, ff_make_format_list(pixel_fmts_eq));
+
+    return 0;
+}
+
+static int config_input(AVFilterLink *inlink)
+{
+    RepeatFieldsContext *s = inlink->dst->priv;
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
+    int ret;
+
+    if ((ret = av_image_fill_linesizes(s->linesize, inlink->format, inlink->w)) < 0)
+        return ret;
+
+    s->planeheight[1] = s->planeheight[2] = FF_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
+    s->planeheight[0] = s->planeheight[3] = inlink->h;
+
+    s->nb_planes = av_pix_fmt_count_planes(inlink->format);
+
+    return 0;
+}
+
+static void update_pts(AVFilterLink *link, AVFrame *f, int64_t pts, int fields)
+{
+    if (av_cmp_q(link->frame_rate, (AVRational){30000, 1001}) == 0 &&
+         av_cmp_q(link->time_base, (AVRational){1001, 60000}) <= 0
+    ) {
+        f->pts = pts + av_rescale_q(fields, (AVRational){1001, 60000}, link->time_base);
+    } else
+        f->pts = AV_NOPTS_VALUE;
+}
+
+static int filter_frame(AVFilterLink *inlink, AVFrame *in) {
+    AVFilterContext *ctx = inlink->dst;
+    AVFilterLink *outlink = inlink->dst->outputs[0];
+    RepeatFieldsContext *s = ctx->priv;
+    AVFrame *out;
+    int ret, i;
+    int state = s->state;
+
+    if (!s->frame) {
+        s->frame = av_frame_clone(in);
+        if (!s->frame)
+            return AVERROR(ENOMEM);
+        s->frame->pts = AV_NOPTS_VALUE;
+    }
+
+    out = s->frame;
+
+    if ((state == 0 && !in->top_field_first) ||
+        (state == 1 &&  in->top_field_first)) {
+        av_log(ctx, AV_LOG_WARNING, "Unexpected field flags: "
+                                    "state=%d top_field_first=%d repeat_first_field=%d\n",
+                                    state, in->top_field_first, in->repeat_pict);
+        state ^= 1;
+    }
+
+    if (state == 0) {
+        AVFrame *new;
+
+        new = av_frame_clone(in);
+        if (!new)
+            return AVERROR(ENOMEM);
+
+        ret = ff_filter_frame(outlink, new);
+
+        if (in->repeat_pict) {
+            av_frame_make_writable(out);
+            update_pts(outlink, out, in->pts, 2);
+            for (i = 0; i < s->nb_planes; i++) {
+                av_image_copy_plane(out->data[i], out->linesize[i] * 2,
+                                    in->data[i], in->linesize[i] * 2,
+                                    s->linesize[i], s->planeheight[i] / 2);
+            }
+            state = 1;
+        }
+    } else {
+        for (i = 0; i < s->nb_planes; i++) {
+            av_frame_make_writable(out);
+            av_image_copy_plane(out->data[i] + out->linesize[i], out->linesize[i] * 2,
+                                in->data[i] + in->linesize[i], in->linesize[i] * 2,
+                                s->linesize[i], s->planeheight[i] / 2);
+        }
+
+        ret = ff_filter_frame(outlink, av_frame_clone(out));
+
+        if (in->repeat_pict) {
+            AVFrame *new;
+
+            new = av_frame_clone(in);
+            if (!new)
+                return AVERROR(ENOMEM);
+
+            ret = ff_filter_frame(outlink, new);
+            state = 0;
+        } else {
+            av_frame_make_writable(out);
+            update_pts(outlink, out, in->pts, 1);
+            for (i = 0; i < s->nb_planes; i++) {
+                av_image_copy_plane(out->data[i], out->linesize[i] * 2,
+                                    in->data[i], in->linesize[i] * 2,
+                                    s->linesize[i], s->planeheight[i] / 2);
+            }
+        }
+    }
+
+    s->state = state;
+
+    av_frame_free(&in);
+    return ret;
+}
+
+static const AVFilterPad repeatfields_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .filter_frame = filter_frame,
+        .config_props = config_input,
+    },
+    { NULL }
+};
+
+static const AVFilterPad repeatfields_outputs[] = {
+    {
+        .name = "default",
+        .type = AVMEDIA_TYPE_VIDEO,
+    },
+    { NULL }
+};
+
+AVFilter ff_vf_repeatfields = {
+    .name          = "repeatfields",
+    .description   = NULL_IF_CONFIG_SMALL("Hard repeat fields based on MPEG repeat field flag."),
+    .priv_size     = sizeof(RepeatFieldsContext),
+    .uninit        = uninit,
+    .inputs        = repeatfields_inputs,
+    .outputs       = repeatfields_outputs,
+    .query_formats = query_formats,
+};
diff --git a/libavfilter/vf_rotate.c b/libavfilter/vf_rotate.c
index 8dec742..e5eff6b 100644
--- a/libavfilter/vf_rotate.c
+++ b/libavfilter/vf_rotate.c
@@ -130,7 +130,7 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
+    static const enum AVPixelFormat pix_fmts[] = {
         AV_PIX_FMT_GBRP,   AV_PIX_FMT_GBRAP,
         AV_PIX_FMT_ARGB,   AV_PIX_FMT_RGBA,
         AV_PIX_FMT_ABGR,   AV_PIX_FMT_BGRA,
diff --git a/libavfilter/vf_setfield.c b/libavfilter/vf_setfield.c
index eb4df74..96e9d18 100644
--- a/libavfilter/vf_setfield.c
+++ b/libavfilter/vf_setfield.c
@@ -37,7 +37,7 @@
 
 typedef struct {
     const AVClass *class;
-    enum SetFieldMode mode;
+    int mode;                   ///< SetFieldMode
 } SetFieldContext;
 
 #define OFFSET(x) offsetof(SetFieldContext, x)
diff --git a/libavfilter/vf_showinfo.c b/libavfilter/vf_showinfo.c
index 78ba4a0..5125944 100644
--- a/libavfilter/vf_showinfo.c
+++ b/libavfilter/vf_showinfo.c
@@ -104,7 +104,7 @@
     }
 
     av_log(ctx, AV_LOG_INFO,
-           "n:%"PRId64" pts:%s pts_time:%s pos:%"PRId64" "
+           "n:%4"PRId64" pts:%7s pts_time:%-7s pos:%9"PRId64" "
            "fmt:%s sar:%d/%d s:%dx%d i:%c iskey:%d type:%c "
            "checksum:%08"PRIX32" plane_checksum:[%08"PRIX32,
            inlink->frame_count,
diff --git a/libavfilter/vf_showpalette.c b/libavfilter/vf_showpalette.c
index adcfeb4..e4d59b6 100644
--- a/libavfilter/vf_showpalette.c
+++ b/libavfilter/vf_showpalette.c
@@ -48,8 +48,11 @@
     static const enum AVPixelFormat out_fmts[] = {AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE};
     AVFilterFormats *in  = ff_make_format_list(in_fmts);
     AVFilterFormats *out = ff_make_format_list(out_fmts);
-    if (!in || !out)
+    if (!in || !out) {
+        av_freep(&in);
+        av_freep(&out);
         return AVERROR(ENOMEM);
+    }
     ff_formats_ref(in,  &ctx->inputs[0]->out_formats);
     ff_formats_ref(out, &ctx->outputs[0]->in_formats);
     return 0;
diff --git a/libavfilter/vf_signalstats.c b/libavfilter/vf_signalstats.c
index 8632761..e89bd79 100644
--- a/libavfilter/vf_signalstats.c
+++ b/libavfilter/vf_signalstats.c
@@ -40,7 +40,7 @@
     int vsub;       // vertical subsampling
     int fs;         // pixel count per frame
     int cfs;        // pixel count per frame of chroma planes
-    enum FilterMode outfilter;
+    int outfilter;  // FilterMode
     int filters;
     AVFrame *frame_prev;
     uint8_t rgba_color[4];
diff --git a/libavfilter/vf_spp.c b/libavfilter/vf_spp.c
index 4235544..19c2c72 100644
--- a/libavfilter/vf_spp.c
+++ b/libavfilter/vf_spp.c
@@ -303,7 +303,7 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
+    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,
diff --git a/libavfilter/vf_stereo3d.c b/libavfilter/vf_stereo3d.c
index 2140120..d86a7f2 100644
--- a/libavfilter/vf_stereo3d.c
+++ b/libavfilter/vf_stereo3d.c
@@ -63,7 +63,7 @@
 };
 
 typedef struct StereoComponent {
-    enum StereoCode format;
+    int format;                 ///< StereoCode
     int width, height;
     int off_left, off_right;
     int off_lstep, off_rstep;
diff --git a/libavfilter/vf_subtitles.c b/libavfilter/vf_subtitles.c
index be4c6a5..90416b5 100644
--- a/libavfilter/vf_subtitles.c
+++ b/libavfilter/vf_subtitles.c
@@ -51,6 +51,7 @@
     ASS_Track    *track;
     char *filename;
     char *charenc;
+    char *force_style;
     int stream_index;
     uint8_t rgba_map[4];
     int     pix_step[4];       ///< steps per pixel for each plane of the main output
@@ -152,7 +153,7 @@
 #define AR(c)  ( (c)>>24)
 #define AG(c)  (((c)>>16)&0xFF)
 #define AB(c)  (((c)>>8) &0xFF)
-#define AA(c)  ((0xFF-c) &0xFF)
+#define AA(c)  ((0xFF-(c)) &0xFF)
 
 static void overlay_ass_image(AssContext *ass, AVFrame *picref,
                               const ASS_Image *image)
@@ -260,6 +261,7 @@
     {"charenc",      "set input character encoding", OFFSET(charenc),      AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
     {"stream_index", "set stream index",             OFFSET(stream_index), AV_OPT_TYPE_INT,    { .i64 = -1 }, -1,       INT_MAX,  FLAGS},
     {"si",           "set stream index",             OFFSET(stream_index), AV_OPT_TYPE_INT,    { .i64 = -1 }, -1,       INT_MAX,  FLAGS},
+    {"force_style",  "force subtitle style",         OFFSET(force_style),  AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
     {NULL},
 };
 
@@ -392,6 +394,27 @@
     if (ret < 0)
         goto end;
 
+    if (ass->force_style) {
+        char **list = NULL;
+        char *temp = NULL;
+        char *ptr = av_strtok(ass->force_style, ",", &temp);
+        int i = 0;
+        while (ptr) {
+            av_dynarray_add(&list, &i, ptr);
+            if (!list) {
+                ret = AVERROR(ENOMEM);
+                goto end;
+            }
+            ptr = av_strtok(NULL, ",", &temp);
+        }
+        av_dynarray_add(&list, &i, NULL);
+        if (!list) {
+            ret = AVERROR(ENOMEM);
+            goto end;
+        }
+        ass_set_style_overrides(ass->library, list);
+        av_free(list);
+    }
     /* Decode subtitles and push them into the renderer (libass) */
     if (dec_ctx->subtitle_header)
         ass_process_codec_private(ass->track,
diff --git a/libavfilter/vf_uspp.c b/libavfilter/vf_uspp.c
index a60e513..6ce3e59 100644
--- a/libavfilter/vf_uspp.c
+++ b/libavfilter/vf_uspp.c
@@ -284,7 +284,7 @@
 
 static int query_formats(AVFilterContext *ctx)
 {
-    static const enum PixelFormat pix_fmts[] = {
+    static const enum AVPixelFormat pix_fmts[] = {
         AV_PIX_FMT_YUV444P,
         AV_PIX_FMT_YUV420P,
         AV_PIX_FMT_YUV410P,
diff --git a/libavfilter/vsrc_mandelbrot.c b/libavfilter/vsrc_mandelbrot.c
index 255f2db..05072e1 100644
--- a/libavfilter/vsrc_mandelbrot.c
+++ b/libavfilter/vsrc_mandelbrot.c
@@ -354,14 +354,14 @@
             }
             if(!c){
                 if(mb->inner==PERIOD){
-                int j;
-                for(j=i-1; j; j--)
-                    if(SQR(mb->zyklus[j][0]-zr) + SQR(mb->zyklus[j][1]-zi) < epsilon*epsilon*10)
-                        break;
-                if(j){
-                    c= i-j;
-                    c= ((c<<5)&0xE0) + ((c<<10)&0xE000) + ((c<<15)&0xE00000);
-                }
+                    int j;
+                    for(j=i-1; j; j--)
+                        if(SQR(mb->zyklus[j][0]-zr) + SQR(mb->zyklus[j][1]-zi) < epsilon*epsilon*10)
+                            break;
+                    if(j){
+                        c= i-j;
+                        c= ((c<<5)&0xE0) + ((c<<10)&0xE000) + ((c<<15)&0xE00000);
+                    }
                 }else if(mb->inner==CONVTIME){
                     c= floor(i*255.0/mb->maxiter+dv)*0x010101;
                 } else if(mb->inner==MINCOL){
diff --git a/libavfilter/vsrc_mptestsrc.c b/libavfilter/vsrc_mptestsrc.c
index d045704..0b80e47 100644
--- a/libavfilter/vsrc_mptestsrc.c
+++ b/libavfilter/vsrc_mptestsrc.c
@@ -121,7 +121,7 @@
             for (k = 0; k < 8; k++)
                 sum += c[k*8+i]*tmp[8*k+j];
 
-            dst[dst_linesize*i + j] = av_clip((int)floor(sum+0.5), 0, 255);
+            dst[dst_linesize*i + j] = av_clip_uint8((int)floor(sum+0.5));
         }
     }
 }
diff --git a/libavformat/Makefile b/libavformat/Makefile
index 5eb834e..2118ff2 100644
--- a/libavformat/Makefile
+++ b/libavformat/Makefile
@@ -20,7 +20,6 @@
        os_support.o         \
        riff.o               \
        sdp.o                \
-       seek.o               \
        url.o                \
        utils.o              \
 
@@ -30,8 +29,10 @@
 OBJS-$(CONFIG_RTPDEC)                    += rdt.o                       \
                                             rtp.o                       \
                                             rtpdec.o                    \
+                                            rtpdec_ac3.o                \
                                             rtpdec_amr.o                \
                                             rtpdec_asf.o                \
+                                            rtpdec_dv.o                 \
                                             rtpdec_g726.o               \
                                             rtpdec_h261.o               \
                                             rtpdec_h263.o               \
@@ -41,6 +42,7 @@
                                             rtpdec_ilbc.o               \
                                             rtpdec_jpeg.o               \
                                             rtpdec_latm.o               \
+                                            rtpdec_mpa_robust.o         \
                                             rtpdec_mpeg12.o             \
                                             rtpdec_mpeg4.o              \
                                             rtpdec_mpegts.o             \
@@ -49,6 +51,7 @@
                                             rtpdec_qt.o                 \
                                             rtpdec_svq3.o               \
                                             rtpdec_vp8.o                \
+                                            rtpdec_vp9.o                \
                                             rtpdec_xiph.o               \
                                             srtp.o
 OBJS-$(CONFIG_RTPENC_CHAIN)              += rtpenc_chain.o rtp.o
@@ -87,7 +90,7 @@
 OBJS-$(CONFIG_AST_MUXER)                 += ast.o astenc.o
 OBJS-$(CONFIG_AU_DEMUXER)                += au.o pcm.o
 OBJS-$(CONFIG_AU_MUXER)                  += au.o rawenc.o
-OBJS-$(CONFIG_AVI_DEMUXER)               += avidec.o
+OBJS-$(CONFIG_AVI_DEMUXER)               += avidec.o isom.o
 OBJS-$(CONFIG_AVI_MUXER)                 += avienc.o mpegtsenc.o avlanguage.o
 OBJS-$(CONFIG_AVISYNTH)                  += avisynth.o
 OBJS-$(CONFIG_AVM2_MUXER)                += swfenc.o swf.o
@@ -125,6 +128,7 @@
 OBJS-$(CONFIG_DNXHD_MUXER)               += rawenc.o
 OBJS-$(CONFIG_DSF_DEMUXER)               += dsfdec.o
 OBJS-$(CONFIG_DSICIN_DEMUXER)            += dsicin.o
+OBJS-$(CONFIG_DSS_DEMUXER)               += dss.o
 OBJS-$(CONFIG_DTSHD_DEMUXER)             += dtshddec.o
 OBJS-$(CONFIG_DTS_DEMUXER)               += dtsdec.o rawdec.o
 OBJS-$(CONFIG_DTS_MUXER)                 += rawenc.o
@@ -279,7 +283,7 @@
 OBJS-$(CONFIG_NISTSPHERE_DEMUXER)        += nistspheredec.o pcm.o
 OBJS-$(CONFIG_NSV_DEMUXER)               += nsvdec.o
 OBJS-$(CONFIG_NULL_MUXER)                += nullenc.o
-OBJS-$(CONFIG_NUT_DEMUXER)               += nutdec.o nut.o
+OBJS-$(CONFIG_NUT_DEMUXER)               += nutdec.o nut.o isom.o
 OBJS-$(CONFIG_NUT_MUXER)                 += nutenc.o nut.o
 OBJS-$(CONFIG_NUV_DEMUXER)               += nuv.o
 OBJS-$(CONFIG_OGG_DEMUXER)               += oggdec.o         \
@@ -372,11 +376,10 @@
                                             rtpenc_h261.o    \
                                             rtpenc_h263.o    \
                                             rtpenc_h263_rfc2190.o \
-                                            rtpenc_hevc.o    \
+                                            rtpenc_h264_hevc.o    \
                                             rtpenc_jpeg.o \
                                             rtpenc_mpv.o     \
                                             rtpenc.o      \
-                                            rtpenc_h264.o \
                                             rtpenc_vp8.o  \
                                             rtpenc_xiph.o \
                                             avc.o hevc.o
@@ -517,6 +520,7 @@
 OBJS-$(CONFIG_TCP_PROTOCOL)              += tcp.o
 OBJS-$(CONFIG_TLS_PROTOCOL)              += tls.o
 OBJS-$(CONFIG_UDP_PROTOCOL)              += udp.o
+OBJS-$(CONFIG_UDPLITE_PROTOCOL)          += udp.o
 OBJS-$(CONFIG_UNIX_PROTOCOL)             += unix.o
 
 OBJS-$(HAVE_LIBC_MSVCRT)                 += file_open.o
diff --git a/libavformat/adtsenc.c b/libavformat/adtsenc.c
index 89c8869..7448ec7 100644
--- a/libavformat/adtsenc.c
+++ b/libavformat/adtsenc.c
@@ -31,7 +31,7 @@
 
 #define ADTS_HEADER_SIZE 7
 
-typedef struct {
+typedef struct ADTSContext {
     AVClass *class;
     int write_adts;
     int objecttype;
diff --git a/libavformat/adxdec.c b/libavformat/adxdec.c
index ddaa201..e7107ac 100644
--- a/libavformat/adxdec.c
+++ b/libavformat/adxdec.c
@@ -40,6 +40,11 @@
     AVCodecContext *avctx = s->streams[0]->codec;
     int ret, size;
 
+    if (avctx->channels <= 0) {
+        av_log(s, AV_LOG_ERROR, "invalid number of channels %d\n", avctx->channels);
+        return AVERROR_INVALIDDATA;
+    }
+
     size = BLOCK_SIZE * avctx->channels;
 
     pkt->pos = avio_tell(s->pb);
@@ -83,8 +88,14 @@
         av_log(s, AV_LOG_ERROR, "Invalid extradata size.\n");
         return AVERROR_INVALIDDATA;
     }
+    avctx->channels    = AV_RB8(avctx->extradata + 7);
     avctx->sample_rate = AV_RB32(avctx->extradata + 8);
 
+    if (avctx->channels <= 0) {
+        av_log(s, AV_LOG_ERROR, "invalid number of channels %d\n", avctx->channels);
+        return AVERROR_INVALIDDATA;
+    }
+
     st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
     st->codec->codec_id    = s->iformat->raw_codec_id;
 
diff --git a/libavformat/aiffdec.c b/libavformat/aiffdec.c
index 301d90f..ff04c2b 100644
--- a/libavformat/aiffdec.c
+++ b/libavformat/aiffdec.c
@@ -33,7 +33,7 @@
 #define AIFF                    0
 #define AIFF_C_VERSION1         0xA2805140
 
-typedef struct {
+typedef struct AIFFInputContext {
     int64_t data_end;
     int block_duration;
 } AIFFInputContext;
@@ -223,6 +223,11 @@
     while (filesize > 0) {
         /* parse different chunks */
         size = get_tag(pb, &tag);
+
+        if (size == AVERROR_EOF && offset > 0 && st->codec->block_align) {
+            av_log(s, AV_LOG_WARNING, "header parser hit EOF\n");
+            goto got_sound;
+        }
         if (size < 0)
             return size;
 
@@ -306,6 +311,9 @@
             if(ff_mov_read_chan(s, pb, st, size) < 0)
                 return AVERROR_INVALIDDATA;
             break;
+        case 0:
+            if (offset > 0 && st->codec->block_align) // COMM && SSND
+                goto got_sound;
         default: /* Jump */
             if (size & 1)   /* Always even aligned */
                 size++;
diff --git a/libavformat/aiffenc.c b/libavformat/aiffenc.c
index 90fc433..e2828e7 100644
--- a/libavformat/aiffenc.c
+++ b/libavformat/aiffenc.c
@@ -30,7 +30,7 @@
 #include "isom.h"
 #include "id3v2.h"
 
-typedef struct {
+typedef struct AIFFOutputContext {
     const AVClass *class;
     int64_t form;
     int64_t frames;
diff --git a/libavformat/allformats.c b/libavformat/allformats.c
index bc033ef..26ccc27 100644
--- a/libavformat/allformats.c
+++ b/libavformat/allformats.c
@@ -110,6 +110,7 @@
     REGISTER_MUXDEMUX(DNXHD,            dnxhd);
     REGISTER_DEMUXER (DSF,              dsf);
     REGISTER_DEMUXER (DSICIN,           dsicin);
+    REGISTER_DEMUXER (DSS,              dss);
     REGISTER_MUXDEMUX(DTS,              dts);
     REGISTER_DEMUXER (DTSHD,            dtshd);
     REGISTER_MUXDEMUX(DV,               dv);
@@ -206,6 +207,7 @@
     REGISTER_DEMUXER (MVI,              mvi);
     REGISTER_MUXDEMUX(MXF,              mxf);
     REGISTER_MUXER   (MXF_D10,          mxf_d10);
+    REGISTER_MUXER   (MXF_OPATOM,       mxf_opatom);
     REGISTER_DEMUXER (MXG,              mxg);
     REGISTER_DEMUXER (NC,               nc);
     REGISTER_DEMUXER (NISTSPHERE,       nistsphere);
diff --git a/libavformat/anm.c b/libavformat/anm.c
index 5196cb8..f718797 100644
--- a/libavformat/anm.c
+++ b/libavformat/anm.c
@@ -28,13 +28,13 @@
 #include "avformat.h"
 #include "internal.h"
 
-typedef struct {
+typedef struct Page {
     int base_record;
     unsigned int nb_records;
     int size;
 } Page;
 
-typedef struct {
+typedef struct AnmDemuxContext {
     unsigned int nb_pages;    /**< total pages in file */
     unsigned int nb_records;  /**< total records in file */
     int page_table_offset;
diff --git a/libavformat/ape.c b/libavformat/ape.c
index fafc1df..28f73d3 100644
--- a/libavformat/ape.c
+++ b/libavformat/ape.c
@@ -40,7 +40,7 @@
 
 #define APE_EXTRADATA_SIZE 6
 
-typedef struct {
+typedef struct APEFrame {
     int64_t pos;
     int nblocks;
     int size;
@@ -48,7 +48,7 @@
     int64_t pts;
 } APEFrame;
 
-typedef struct {
+typedef struct APEContext {
     /* Derived fields */
     uint32_t junklength;
     uint32_t firstframe;
diff --git a/libavformat/apetag.c b/libavformat/apetag.c
index 258bdaa..2635920 100644
--- a/libavformat/apetag.c
+++ b/libavformat/apetag.c
@@ -38,7 +38,7 @@
 {
     AVIOContext *pb = s->pb;
     uint8_t key[1024], *value;
-    uint32_t size, flags;
+    int64_t size, flags;
     int i, c;
 
     size = avio_rl32(pb);  /* field size */
diff --git a/libavformat/apngdec.c b/libavformat/apngdec.c
index 5e7a4a1..6deff3b 100644
--- a/libavformat/apngdec.c
+++ b/libavformat/apngdec.c
@@ -150,7 +150,8 @@
     AVIOContext *pb = s->pb;
     uint32_t len, tag;
     AVStream *st;
-    int ret = AVERROR_INVALIDDATA, acTL_found = 0;
+    int acTL_found = 0;
+    int64_t ret = AVERROR_INVALIDDATA;
 
     /* verify PNGSIG */
     if (avio_rb64(pb) != PNGSIG)
@@ -321,7 +322,7 @@
 static int apng_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     APNGDemuxContext *ctx = s->priv_data;
-    int ret;
+    int64_t ret;
     int64_t size;
     AVIOContext *pb = s->pb;
     uint32_t len, tag;
diff --git a/libavformat/asfdec.c b/libavformat/asfdec.c
index c7d03f0..0a2e77e 100644
--- a/libavformat/asfdec.c
+++ b/libavformat/asfdec.c
@@ -39,7 +39,7 @@
 #include "asf.h"
 #include "asfcrypt.h"
 
-typedef struct {
+typedef struct ASFContext {
     const AVClass *class;
     int asfid2avid[128];                 ///< conversion table from asf ID 2 AVStream ID
     ASFStream streams[128];              ///< it's max number and it's not that big
@@ -80,10 +80,12 @@
     ASFStream *asf_st;                   ///< currently decoded stream
 
     int no_resync_search;
+    int export_xmp;
 } ASFContext;
 
 static const AVOption options[] = {
     { "no_resync_search", "Don't try to resynchronize by looking for a certain optional start code", offsetof(ASFContext, no_resync_search), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
+    { "export_xmp", "Export full XMP metadata", offsetof(ASFContext, export_xmp), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
     { NULL },
 };
 
@@ -277,13 +279,17 @@
 
 static void get_tag(AVFormatContext *s, const char *key, int type, int len, int type2_size)
 {
-    char *value;
+    ASFContext *asf = s->priv_data;
+    char *value = NULL;
     int64_t off = avio_tell(s->pb);
 #define LEN 22
 
     if ((unsigned)len >= (UINT_MAX - LEN) / 2)
         return;
 
+    if (!asf->export_xmp && !strncmp(key, "xmp", 3))
+        goto finish;
+
     value = av_malloc(2 * len + LEN);
     if (!value)
         goto finish;
@@ -909,7 +915,7 @@
     if (asf->no_resync_search)
         off = 3;
     else if (s->packet_size > 0)
-        off = (avio_tell(pb) - s->data_offset) % s->packet_size + 3;
+        off = (avio_tell(pb) - s->internal->data_offset) % s->packet_size + 3;
 
     c = d = e = -1;
     while (off-- > 0) {
@@ -1445,9 +1451,9 @@
         start_pos[i] = pos;
 
     if (s->packet_size > 0)
-        pos = (pos + s->packet_size - 1 - s->data_offset) /
+        pos = (pos + s->packet_size - 1 - s->internal->data_offset) /
               s->packet_size * s->packet_size +
-              s->data_offset;
+              s->internal->data_offset;
     *ppos = pos;
     if (avio_seek(s->pb, pos, SEEK_SET) < 0)
         return AV_NOPTS_VALUE;
@@ -1489,7 +1495,7 @@
     ff_asf_guid g;
     ASFContext *asf     = s->priv_data;
     int64_t current_pos = avio_tell(s->pb);
-    int ret = 0;
+    int64_t ret;
 
     if((ret = avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET)) < 0) {
         return ret;
@@ -1526,7 +1532,7 @@
         for (i = 0; i < ict; i++) {
             int pktnum        = avio_rl32(s->pb);
             int pktct         = avio_rl16(s->pb);
-            int64_t pos       = s->data_offset + s->packet_size * (int64_t)pktnum;
+            int64_t pos       = s->internal->data_offset + s->packet_size * (int64_t)pktnum;
             int64_t index_pts = FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0);
 
             if (pos != last_pos) {
@@ -1559,7 +1565,7 @@
 
     /* Try using the protocol's read_seek if available */
     if (s->pb) {
-        int ret = avio_seek_time(s->pb, stream_index, pts, flags);
+        int64_t ret = avio_seek_time(s->pb, stream_index, pts, flags);
         if (ret >= 0)
             asf_reset_header(s);
         if (ret != AVERROR(ENOSYS))
@@ -1569,7 +1575,7 @@
     /* explicitly handle the case of seeking to 0 */
     if (!pts) {
         asf_reset_header(s);
-        avio_seek(s->pb, s->data_offset, SEEK_SET);
+        avio_seek(s->pb, s->internal->data_offset, SEEK_SET);
         return 0;
     }
 
diff --git a/libavformat/asfenc.c b/libavformat/asfenc.c
index 3dc58f3..5e0f7b0 100644
--- a/libavformat/asfenc.c
+++ b/libavformat/asfenc.c
@@ -28,10 +28,6 @@
 #include "riff.h"
 #include "asf.h"
 
-#undef NDEBUG
-#include <assert.h>
-
-
 #define ASF_INDEXED_INTERVAL    10000000
 #define ASF_INDEX_BLOCK         (1<<9)
 #define ASF_PAYLOADS_PER_PACKET 63
@@ -187,7 +183,7 @@
 
 #define DATA_HEADER_SIZE 50
 
-typedef struct {
+typedef struct ASFContext {
     uint32_t seqno;
     int is_streamed;
     ASFStream streams[128];              ///< it's max number and it's not that big
@@ -664,6 +660,7 @@
      * It is needed to use asf as a streamable format. */
     if (asf_write_header1(s, 0, DATA_HEADER_SIZE) < 0) {
         //av_free(asf);
+        av_freep(&asf->index_ptr);
         return -1;
     }
 
diff --git a/libavformat/avc.c b/libavformat/avc.c
index c927b47..9d843e0 100644
--- a/libavformat/avc.c
+++ b/libavformat/avc.c
@@ -180,7 +180,7 @@
     if (11 + sps_size + pps_size > *size)
         return AVERROR_INVALIDDATA;
     out_size = 8 + sps_size + pps_size;
-    out = av_mallocz(out_size);
+    out = av_mallocz(out_size + FF_INPUT_BUFFER_PADDING_SIZE);
     if (!out)
         return AVERROR(ENOMEM);
     AV_WB32(&out[0], 0x00000001);
diff --git a/libavformat/avformat.h b/libavformat/avformat.h
index db72c18..4211a95 100644
--- a/libavformat/avformat.h
+++ b/libavformat/avformat.h
@@ -198,6 +198,10 @@
  *   be set to the timebase that the caller desires to use for this stream (note
  *   that the timebase actually used by the muxer can be different, as will be
  *   described later).
+ * - It is advised to manually initialize only the relevant fields in
+ *   AVCodecContext, rather than using @ref avcodec_copy_context() during
+ *   remuxing: there is no guarantee that the codec context values remain valid
+ *   for both input and output format contexts.
  * - The caller may fill in additional information, such as @ref
  *   AVFormatContext.metadata "global" or @ref AVStream.metadata "per-stream"
  *   metadata, @ref AVFormatContext.chapters "chapters", @ref
@@ -1503,7 +1507,6 @@
 #define AVFMT_AVOID_NEG_TS_MAKE_NON_NEGATIVE 1 ///< Shift timestamps so they are non negative
 #define AVFMT_AVOID_NEG_TS_MAKE_ZERO         2 ///< Shift timestamps so that they start at 0
 
-
     /**
      * Transport stream id.
      * This will be moved into demuxer private options. Thus no API/ABI compatibility
@@ -1617,56 +1620,6 @@
      */
     char *format_whitelist;
 
-    /*****************************************************************
-     * 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.
-     *****************************************************************
-     */
-
-    /**
-     * This buffer is only needed when packets were already buffered but
-     * not decoded, for example to get the codec parameters in MPEG
-     * streams.
-     */
-    struct AVPacketList *packet_buffer;
-    struct AVPacketList *packet_buffer_end;
-
-    /* av_seek_frame() support */
-    int64_t data_offset; /**< offset of the first packet */
-
-    /**
-     * Raw packets from the demuxer, prior to parsing and decoding.
-     * This buffer is used for buffering packets until the codec can
-     * be identified, as parsing cannot be done without knowing the
-     * codec.
-     */
-    struct AVPacketList *raw_packet_buffer;
-    struct AVPacketList *raw_packet_buffer_end;
-    /**
-     * Packets split by the parser get queued here.
-     */
-    struct AVPacketList *parse_queue;
-    struct AVPacketList *parse_queue_end;
-    /**
-     * Remaining size available for raw_packet_buffer, in bytes.
-     */
-#define RAW_PACKET_BUFFER_SIZE 2500000
-    int raw_packet_buffer_remaining_size;
-
-    /**
-     * Offset to remap timestamps to be non-negative.
-     * Expressed in timebase units.
-     * @see AVStream.mux_ts_offset
-     */
-    int64_t offset;
-
-    /**
-     * Timebase for the timestamp offset.
-     */
-    AVRational offset_timebase;
-
     /**
      * An opaque field for libavformat internal usage.
      * Must not be accessed in any way by callers.
@@ -2184,6 +2137,24 @@
 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags);
 
 /**
+ * Discard all internally buffered data. This can be useful when dealing with
+ * discontinuities in the byte stream. Generally works only with formats that
+ * can resync. This includes headerless formats like MPEG-TS/TS but should also
+ * work with NUT, Ogg and in a limited way AVI for example.
+ *
+ * The set of streams, the detected duration, stream parameters and codecs do
+ * not change when calling this function. If you want a complete reset, it's
+ * better to open a new AVFormatContext.
+ *
+ * This does not flush the AVIOContext (s->pb). If necessary, call
+ * avio_flush(s->pb) before calling this function.
+ *
+ * @param s media file handle
+ * @return >=0 on success, error code otherwise
+ */
+int avformat_flush(AVFormatContext *s);
+
+/**
  * Start playing a network-based stream (e.g. RTSP stream) at the
  * current position.
  */
diff --git a/libavformat/avidec.c b/libavformat/avidec.c
index 963af34..6bd8b11 100644
--- a/libavformat/avidec.c
+++ b/libavformat/avidec.c
@@ -33,9 +33,11 @@
 #include "avi.h"
 #include "dv.h"
 #include "internal.h"
+#include "isom.h"
 #include "riff.h"
 #include "libavcodec/bytestream.h"
 #include "libavcodec/exif.h"
+#include "libavcodec/internal.h"
 
 typedef struct AVIStream {
     int64_t frame_offset;   /* current frame (video) or byte (audio) counter
@@ -64,7 +66,7 @@
     int64_t seek_pos;
 } AVIStream;
 
-typedef struct {
+typedef struct AVIContext {
     const AVClass *class;
     int64_t riff_end;
     int64_t movi_end;
@@ -136,7 +138,7 @@
 static int get_riff(AVFormatContext *s, AVIOContext *pb)
 {
     AVIContext *avi = s->priv_data;
-    char header[8];
+    char header[8] = {0};
     int i;
 
     /* check RIFF header */
@@ -178,12 +180,13 @@
 
     av_dlog(s,
             "longs_pre_entry:%d index_type:%d entries_in_use:%d "
-            "chunk_id:%X base:%16"PRIX64"\n",
+            "chunk_id:%X base:%16"PRIX64" frame_num:%d\n",
             longs_pre_entry,
             index_type,
             entries_in_use,
             chunk_id,
-            base);
+            base,
+            frame_num);
 
     if (stream_id >= s->nb_streams || stream_id < 0)
         return AVERROR_INVALIDDATA;
@@ -308,7 +311,8 @@
     value = av_malloc(size + 1);
     if (!value)
         return AVERROR(ENOMEM);
-    avio_read(pb, value, size);
+    if (avio_read(pb, value, size) != size)
+        return AVERROR_INVALIDDATA;
     value[size] = 0;
 
     AV_WL32(key, tag);
@@ -772,6 +776,17 @@
                     st->codec->codec_tag  = tag1;
                     st->codec->codec_id   = ff_codec_get_id(ff_codec_bmp_tags,
                                                             tag1);
+                    /* If codec is not found yet, try with the mov tags. */
+                    if (!st->codec->codec_id) {
+                        char tag_buf[32];
+                        av_get_codec_tag_string(tag_buf, sizeof(tag_buf), tag1);
+                        st->codec->codec_id =
+                            ff_codec_get_id(ff_codec_movvideo_tags, tag1);
+                        if (st->codec->codec_id)
+                           av_log(s, AV_LOG_WARNING,
+                                  "mov tag found in avi (fourcc %s)\n",
+                                  tag_buf);
+                    }
                     /* This is needed to get the pict type which is necessary
                      * for generating correct pts. */
                     st->need_parsing = AVSTREAM_PARSE_HEADERS;
@@ -1438,17 +1453,16 @@
                 if (index >= 0 && e->timestamp == ast->frame_offset) {
                     if (index == st->nb_index_entries-1) {
                         int key=1;
-                        int i;
                         uint32_t state=-1;
-                        for (i=0; i<FFMIN(size,256); i++) {
-                            if (st->codec->codec_id == AV_CODEC_ID_MPEG4) {
-                                if (state == 0x1B6) {
-                                    key= !(pkt->data[i]&0xC0);
+                        if (st->codec->codec_id == AV_CODEC_ID_MPEG4) {
+                            const uint8_t *ptr = pkt->data, *end = ptr + FFMIN(size, 256);
+                            while (ptr < end) {
+                                ptr = avpriv_find_start_code(ptr, end, &state);
+                                if (state == 0x1B6 && ptr < end) {
+                                    key = !(*ptr & 0xC0);
                                     break;
                                 }
-                            }else
-                                break;
-                            state= (state<<8) + pkt->data[i];
+                            }
                         }
                         if (!key)
                             e->flags &= ~AVINDEX_KEYFRAME;
diff --git a/libavformat/avienc.c b/libavformat/avienc.c
index 944c154..fb2cdd2 100644
--- a/libavformat/avienc.c
+++ b/libavformat/avienc.c
@@ -49,23 +49,26 @@
 
 typedef struct AVIIndex {
     int64_t     indx_start;
+    int64_t     audio_strm_offset;
     int         entry;
     int         ents_allocated;
+    int         master_odml_riff_id_base;
     AVIIentry** cluster;
 } AVIIndex;
 
-typedef struct {
+typedef struct AVIContext {
     int64_t riff_start, movi_list, odml_list;
     int64_t frames_hdr_all;
     int riff_id;
 } AVIContext;
 
-typedef struct  {
+typedef struct AVIStream {
     int64_t frames_hdr_strm;
     int64_t audio_strm_length;
     int packet_count;
     int entry;
     int max_size;
+    int sample_requested;
 
     int64_t last_dts;
 
@@ -91,6 +94,7 @@
     avi->riff_id++;
     for (i = 0; i < s->nb_streams; i++) {
         AVIStream *avist = s->streams[i]->priv_data;
+        avist->indexes.audio_strm_offset = avist->audio_strm_length;
         avist->indexes.entry = 0;
     }
 
@@ -153,6 +157,33 @@
     return 0;
 }
 
+static void write_odml_master(AVFormatContext *s, int stream_index)
+{
+    AVIOContext *pb = s->pb;
+    AVStream *st = s->streams[stream_index];
+    AVCodecContext *enc = st->codec;
+    AVIStream *avist = st->priv_data;
+    unsigned char tag[5];
+    int j;
+
+    /* Starting to lay out AVI OpenDML master index.
+        * We want to make it JUNK entry for now, since we'd
+        * like to get away without making AVI an OpenDML one
+        * for compatibility reasons. */
+    avist->indexes.indx_start = ff_start_tag(pb, "JUNK");
+    avio_wl16(pb, 4);   /* wLongsPerEntry */
+    avio_w8(pb, 0);     /* bIndexSubType (0 == frame index) */
+    avio_w8(pb, 0);     /* bIndexType (0 == AVI_INDEX_OF_INDEXES) */
+    avio_wl32(pb, 0);   /* nEntriesInUse (will fill out later on) */
+    ffio_wfourcc(pb, avi_stream2fourcc(tag, stream_index, enc->codec_type));
+                        /* dwChunkId */
+    avio_wl64(pb, 0);   /* dwReserved[3] */
+    avio_wl32(pb, 0);   /* Must be 0.    */
+    for (j = 0; j < AVI_MASTER_INDEX_SIZE * 2; j++)
+        avio_wl64(pb, 0);
+    ff_end_tag(pb, avist->indexes.indx_start);
+}
+
 static int avi_write_header(AVFormatContext *s)
 {
     AVIContext *avi = s->priv_data;
@@ -362,26 +393,7 @@
         }
 
         if (pb->seekable) {
-            unsigned char tag[5];
-            int j;
-
-            /* Starting to lay out AVI OpenDML master index.
-             * We want to make it JUNK entry for now, since we'd
-             * like to get away without making AVI an OpenDML one
-             * for compatibility reasons. */
-            avist->indexes.entry      = avist->indexes.ents_allocated = 0;
-            avist->indexes.indx_start = ff_start_tag(pb, "JUNK");
-            avio_wl16(pb, 4);   /* wLongsPerEntry */
-            avio_w8(pb, 0);     /* bIndexSubType (0 == frame index) */
-            avio_w8(pb, 0);     /* bIndexType (0 == AVI_INDEX_OF_INDEXES) */
-            avio_wl32(pb, 0);   /* nEntriesInUse (will fill out later on) */
-            ffio_wfourcc(pb, avi_stream2fourcc(tag, i, enc->codec_type));
-                                /* dwChunkId */
-            avio_wl64(pb, 0);   /* dwReserved[3] */
-            // avio_wl32(pb, 0);   /* Must be 0.    */
-            for (j = 0; j < AVI_MASTER_INDEX_SIZE * 2; j++)
-                avio_wl64(pb, 0);
-            ff_end_tag(pb, avist->indexes.indx_start);
+            write_odml_master(s, i);
         }
 
         if (enc->codec_type == AVMEDIA_TYPE_VIDEO   &&
@@ -457,6 +469,39 @@
     return 0;
 }
 
+static void update_odml_entry(AVFormatContext *s, int stream_index, int64_t ix, int size)
+{
+    AVIOContext *pb = s->pb;
+    AVIContext *avi = s->priv_data;
+    AVIStream *avist = s->streams[stream_index]->priv_data;
+    int64_t pos;
+    int au_byterate, au_ssize, au_scale;
+
+    avio_flush(pb);
+    pos = avio_tell(pb);
+
+    /* Updating one entry in the AVI OpenDML master index */
+    avio_seek(pb, avist->indexes.indx_start - 8, SEEK_SET);
+    ffio_wfourcc(pb, "indx");             /* enabling this entry */
+    avio_skip(pb, 8);
+    avio_wl32(pb, avi->riff_id - avist->indexes.master_odml_riff_id_base);          /* nEntriesInUse */
+    avio_skip(pb, 16 * (avi->riff_id - avist->indexes.master_odml_riff_id_base));
+    avio_wl64(pb, ix);                    /* qwOffset */
+    avio_wl32(pb, size);                  /* dwSize */
+    ff_parse_specific_params(s->streams[stream_index], &au_byterate, &au_ssize, &au_scale);
+    if (s->streams[stream_index]->codec->codec_type == AVMEDIA_TYPE_AUDIO && au_ssize > 0) {
+        uint32_t audio_segm_size = (avist->audio_strm_length - avist->indexes.audio_strm_offset);
+        if ((audio_segm_size % au_ssize > 0) && !avist->sample_requested) {
+            avpriv_request_sample(s, "OpenDML index duration for audio packets with partial frames");
+            avist->sample_requested = 1;
+        }
+        avio_wl32(pb, audio_segm_size / au_ssize);  /* dwDuration (sample count) */
+    } else
+        avio_wl32(pb, avist->indexes.entry);  /* dwDuration (packet count) */
+
+    avio_seek(pb, pos, SEEK_SET);
+}
+
 static int avi_write_ix(AVFormatContext *s)
 {
     AVIOContext *pb = s->pb;
@@ -467,15 +512,24 @@
 
     av_assert0(pb->seekable);
 
-    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;
+        if (avi->riff_id - avist->indexes.master_odml_riff_id_base == AVI_MASTER_INDEX_SIZE) {
+            int64_t pos;
+            int size = 8+2+1+1+4+8+4+4+16*AVI_MASTER_INDEX_SIZE;
+
+            pos = avio_tell(pb);
+            update_odml_entry(s, i, pos, size);
+            write_odml_master(s, i);
+            av_assert1(avio_tell(pb) - pos == size);
+            avist->indexes.master_odml_riff_id_base = avi->riff_id - 1;
+        }
+        av_assert0(avi->riff_id - avist->indexes.master_odml_riff_id_base < AVI_MASTER_INDEX_SIZE);
     }
 
     for (i = 0; i < s->nb_streams; i++) {
         AVIStream *avist = s->streams[i]->priv_data;
-        int64_t ix, pos;
+        int64_t ix;
 
         avi_stream2fourcc(tag, i, s->streams[i]->codec->codec_type);
         ix_tag[3] = '0' + i;
@@ -500,20 +554,8 @@
             avio_wl32(pb, ((uint32_t) ie->len & ~0x80000000) |
                           (ie->flags & 0x10 ? 0 : 0x80000000));
         }
-        avio_flush(pb);
-        pos = avio_tell(pb);
 
-        /* Updating one entry in the AVI OpenDML master index */
-        avio_seek(pb, avist->indexes.indx_start - 8, SEEK_SET);
-        ffio_wfourcc(pb, "indx");             /* enabling this entry */
-        avio_skip(pb, 8);
-        avio_wl32(pb, avi->riff_id);          /* nEntriesInUse */
-        avio_skip(pb, 16 * avi->riff_id);
-        avio_wl64(pb, ix);                    /* qwOffset */
-        avio_wl32(pb, pos - ix);              /* dwSize */
-        avio_wl32(pb, avist->indexes.entry);  /* dwDuration */
-
-        avio_seek(pb, pos, SEEK_SET);
+        update_odml_entry(s, i, ix, avio_tell(pb) - ix);
     }
     return 0;
 }
diff --git a/libavformat/avio.c b/libavformat/avio.c
index 326bb0a..4896782 100644
--- a/libavformat/avio.c
+++ b/libavformat/avio.c
@@ -349,7 +349,9 @@
     if (h->max_packet_size && size > h->max_packet_size)
         return AVERROR(EIO);
 
-    return retry_transfer_wrapper(h, (unsigned char *)buf, size, size, (void*)h->prot->url_write);
+    return retry_transfer_wrapper(h, (unsigned char *)buf, size, size,
+                                  (int (*)(struct URLContext *, uint8_t *, int))
+                                  h->prot->url_write);
 }
 
 int64_t ffurl_seek(URLContext *h, int64_t pos, int whence)
diff --git a/libavformat/avio.h b/libavformat/avio.h
index b9b4017..8fc7e27 100644
--- a/libavformat/avio.h
+++ b/libavformat/avio.h
@@ -234,6 +234,12 @@
 int avio_put_str16le(AVIOContext *s, const char *str);
 
 /**
+ * Convert an UTF-8 string to UTF-16BE and write it.
+ * @return number of bytes written.
+ */
+int avio_put_str16be(AVIOContext *s, const char *str);
+
+/**
  * Passing this as the "whence" parameter to a seek function causes it to
  * return the filesize without seeking anywhere. Supporting this is optional.
  * If it is not supported then the seek function will return <0.
diff --git a/libavformat/avio_internal.h b/libavformat/avio_internal.h
index 5864048..1ed5831 100644
--- a/libavformat/avio_internal.h
+++ b/libavformat/avio_internal.h
@@ -25,7 +25,7 @@
 
 #include "libavutil/log.h"
 
-extern const AVClass ffio_url_class;
+extern const AVClass ff_avio_class;
 
 int ffio_init_context(AVIOContext *s,
                   unsigned char *buffer,
@@ -150,4 +150,11 @@
  */
 int ffio_close_null_buf(AVIOContext *s);
 
+/**
+ * Free a dynamic buffer.
+ *
+ * @param s a pointer to an IO context opened by avio_open_dyn_buf()
+ */
+void ffio_free_dyn_buf(AVIOContext **s);
+
 #endif /* AVFORMAT_AVIO_INTERNAL_H */
diff --git a/libavformat/aviobuf.c b/libavformat/aviobuf.c
index 3d77a7f..7de59f1 100644
--- a/libavformat/aviobuf.c
+++ b/libavformat/aviobuf.c
@@ -42,28 +42,28 @@
  */
 #define SHORT_SEEK_THRESHOLD 4096
 
-static void *ffio_url_child_next(void *obj, void *prev)
+static void *ff_avio_child_next(void *obj, void *prev)
 {
     AVIOContext *s = obj;
     return prev ? NULL : s->opaque;
 }
 
-static const AVClass *ffio_url_child_class_next(const AVClass *prev)
+static const AVClass *ff_avio_child_class_next(const AVClass *prev)
 {
     return prev ? NULL : &ffurl_context_class;
 }
 
-static const AVOption ffio_url_options[] = {
+static const AVOption ff_avio_options[] = {
     { NULL },
 };
 
-const AVClass ffio_url_class = {
+const AVClass ff_avio_class = {
     .class_name = "AVIOContext",
     .item_name  = av_default_item_name,
     .version    = LIBAVUTIL_VERSION_INT,
-    .option     = ffio_url_options,
-    .child_next = ffio_url_child_next,
-    .child_class_next = ffio_url_child_class_next,
+    .option     = ff_avio_options,
+    .child_next = ff_avio_child_next,
+    .child_class_next = ff_avio_child_class_next,
 };
 
 static void fill_buffer(AVIOContext *s);
@@ -342,7 +342,7 @@
     return len;
 }
 
-int avio_put_str16le(AVIOContext *s, const char *str)
+static inline int put_str16(AVIOContext *s, const char *str, const int be)
 {
     const uint8_t *q = str;
     int ret = 0;
@@ -353,19 +353,34 @@
         uint16_t tmp;
 
         GET_UTF8(ch, *q++, goto invalid;)
-        PUT_UTF16(ch, tmp, avio_wl16(s, tmp); ret += 2;)
+        PUT_UTF16(ch, tmp, be ? avio_wb16(s, tmp) : avio_wl16(s, tmp);
+                  ret += 2;)
         continue;
 invalid:
-        av_log(s, AV_LOG_ERROR, "Invaid UTF8 sequence in avio_put_str16le\n");
+        av_log(s, AV_LOG_ERROR, "Invaid UTF8 sequence in avio_put_str16%s\n", be ? "be" : "le");
         err = AVERROR(EINVAL);
     }
-    avio_wl16(s, 0);
+    if (be)
+        avio_wb16(s, 0);
+    else
+        avio_wl16(s, 0);
     if (err)
         return err;
     ret += 2;
     return ret;
 }
 
+#define PUT_STR16(type, big_endian)                          \
+int avio_put_str16 ## type(AVIOContext *s, const char *str)  \
+{                                                            \
+return put_str16(s, str, big_endian);                        \
+}
+
+PUT_STR16(le, 0)
+PUT_STR16(be, 1)
+
+#undef PUT_STR16
+
 int ff_get_v_length(uint64_t val)
 {
     int i = 1;
@@ -763,7 +778,9 @@
         return AVERROR(ENOMEM);
 
     *s = avio_alloc_context(buffer, buffer_size, h->flags & AVIO_FLAG_WRITE, h,
-                            (void*)ffurl_read, (void*)ffurl_write, (void*)ffurl_seek);
+                            (int (*)(void *, uint8_t *, int)) ffurl_read,
+                            (int (*)(void *, uint8_t *, int)) ffurl_write,
+                            (int64_t (*)(void *, int64_t, int)) ffurl_seek);
     if (!*s) {
         av_free(buffer);
         return AVERROR(ENOMEM);
@@ -775,7 +792,7 @@
         (*s)->read_pause = (int (*)(void *, int))h->prot->url_read_pause;
         (*s)->read_seek  = (int64_t (*)(void *, int, int64_t, int))h->prot->url_read_seek;
     }
-    (*s)->av_class = &ffio_url_class;
+    (*s)->av_class = &ff_avio_class;
     return 0;
 }
 
@@ -1117,6 +1134,16 @@
     return size - padding;
 }
 
+void ffio_free_dyn_buf(AVIOContext **s)
+{
+    uint8_t *tmp;
+    if (!*s)
+        return;
+    avio_close_dyn_buf(*s, &tmp);
+    av_free(tmp);
+    *s = NULL;
+}
+
 static int null_buf_write(void *opaque, uint8_t *buf, int buf_size)
 {
     DynBuffer *d = opaque;
diff --git a/libavformat/avisynth.c b/libavformat/avisynth.c
index fbd4a8d..ac3247a 100644
--- a/libavformat/avisynth.c
+++ b/libavformat/avisynth.c
@@ -65,6 +65,17 @@
     AVSC_DECLARE_FUNC(avs_release_value);
     AVSC_DECLARE_FUNC(avs_release_video_frame);
     AVSC_DECLARE_FUNC(avs_take_clip);
+#ifdef USING_AVISYNTH
+    AVSC_DECLARE_FUNC(avs_bits_per_pixel);
+    AVSC_DECLARE_FUNC(avs_get_height_p);
+    AVSC_DECLARE_FUNC(avs_get_pitch_p);
+    AVSC_DECLARE_FUNC(avs_get_read_ptr_p);
+    AVSC_DECLARE_FUNC(avs_get_row_size_p);
+    AVSC_DECLARE_FUNC(avs_is_yv24);
+    AVSC_DECLARE_FUNC(avs_is_yv16);
+    AVSC_DECLARE_FUNC(avs_is_yv411);
+    AVSC_DECLARE_FUNC(avs_is_y8);
+#endif
 #undef AVSC_DECLARE_FUNC
 } AviSynthLibrary;
 
@@ -128,6 +139,17 @@
     LOAD_AVS_FUNC(avs_release_value, 0);
     LOAD_AVS_FUNC(avs_release_video_frame, 0);
     LOAD_AVS_FUNC(avs_take_clip, 0);
+#ifdef USING_AVISYNTH
+    LOAD_AVS_FUNC(avs_bits_per_pixel, 0);
+    LOAD_AVS_FUNC(avs_get_height_p, 0);
+    LOAD_AVS_FUNC(avs_get_pitch_p, 0);
+    LOAD_AVS_FUNC(avs_get_read_ptr_p, 0);
+    LOAD_AVS_FUNC(avs_get_row_size_p, 0);
+    LOAD_AVS_FUNC(avs_is_yv24, 0);
+    LOAD_AVS_FUNC(avs_is_yv16, 0);
+    LOAD_AVS_FUNC(avs_is_yv411, 0);
+    LOAD_AVS_FUNC(avs_is_y8, 0);
+#endif
 #undef LOAD_AVS_FUNC
 
     atexit(avisynth_atexit_handler);
@@ -438,17 +460,19 @@
      * Since AvxSynth doesn't have these functions, special-case
      * it in order to avoid implicit declaration errors. */
 
-    if (avs_is_yv24(avs->vi))
+    if (avs_library.avs_is_yv24(avs->vi))
         bits = 24;
-    else if (avs_is_yv16(avs->vi))
+    else if (avs_library.avs_is_yv16(avs->vi))
         bits = 16;
-    else if (avs_is_yv411(avs->vi))
+    else if (avs_library.avs_is_yv411(avs->vi))
         bits = 12;
-    else if (avs_is_y8(avs->vi))
+    else if (avs_library.avs_is_y8(avs->vi))
         bits = 8;
     else
+        bits = avs_library.avs_bits_per_pixel(avs->vi);
+#else
+    bits = avs_bits_per_pixel(avs->vi);
 #endif
-        bits = avs_bits_per_pixel(avs->vi);
 
     /* Without the cast to int64_t, calculation overflows at about 9k x 9k
      * resolution. */
@@ -477,18 +501,21 @@
     dst_p = pkt->data;
     for (i = 0; i < avs->n_planes; i++) {
         plane = avs->planes[i];
-        src_p = avs_get_read_ptr_p(frame, plane);
-        pitch = avs_get_pitch_p(frame, plane);
-
 #ifdef USING_AVISYNTH
+        src_p = avs_library.avs_get_read_ptr_p(frame, plane);
+        pitch = avs_library.avs_get_pitch_p(frame, plane);
+
         if (avs_library.avs_get_version(avs->clip) == 3) {
             rowsize     = avs_get_row_size_p_25(frame, plane);
             planeheight = avs_get_height_p_25(frame, plane);
         } else {
-            rowsize     = avs_get_row_size_p(frame, plane);
-            planeheight = avs_get_height_p(frame, plane);
+            rowsize     = avs_library.avs_get_row_size_p(frame, plane);
+            planeheight = avs_library.avs_get_height_p(frame, plane);
         }
 #else
+        src_p = avs_get_read_ptr_p(frame, plane);
+        pitch = avs_get_pitch_p(frame, plane);
+
         rowsize     = avs_get_row_size_p(frame, plane);
         planeheight = avs_get_height_p(frame, plane);
 #endif
diff --git a/libavformat/bink.c b/libavformat/bink.c
index 395c8d9..92ce261 100644
--- a/libavformat/bink.c
+++ b/libavformat/bink.c
@@ -46,7 +46,7 @@
 #define BINK_MAX_WIDTH          7680
 #define BINK_MAX_HEIGHT         4800
 
-typedef struct {
+typedef struct BinkDemuxContext {
     uint32_t file_size;
 
     uint32_t num_audio_tracks;
diff --git a/libavformat/bit.c b/libavformat/bit.c
index 7b807b9..138d2fe 100644
--- a/libavformat/bit.c
+++ b/libavformat/bit.c
@@ -119,8 +119,12 @@
 {
     AVCodecContext *enc = s->streams[0]->codec;
 
-    enc->codec_id = AV_CODEC_ID_G729;
-    enc->channels = 1;
+    if ((enc->codec_id != AV_CODEC_ID_G729) || enc->channels != 1) {
+        av_log(s, AV_LOG_ERROR,
+               "only codec g729 with 1 channel is supported by this format\n");
+        return AVERROR(EINVAL);
+    }
+
     enc->bits_per_coded_sample = 16;
     enc->block_align = (enc->bits_per_coded_sample * enc->channels) >> 3;
 
@@ -133,6 +137,9 @@
     GetBitContext gb;
     int i;
 
+    if (pkt->size != 10)
+        return AVERROR(EINVAL);
+
     avio_wl16(pb, SYNC_WORD);
     avio_wl16(pb, 8 * 10);
 
diff --git a/libavformat/boadec.c b/libavformat/boadec.c
index 45f6b39..be003e5 100644
--- a/libavformat/boadec.c
+++ b/libavformat/boadec.c
@@ -21,6 +21,7 @@
 
 #include "libavutil/intreadwrite.h"
 #include "avformat.h"
+#include "internal.h"
 
 static int probe(AVProbeData *p)
 {
@@ -52,11 +53,11 @@
     avio_rl32(s->pb);
     st->codec->sample_rate = avio_rl32(s->pb);
     st->codec->channels    = avio_rl32(s->pb);
-    s->data_offset         = avio_rl32(s->pb);
+    s->internal->data_offset = avio_rl32(s->pb);
     avio_r8(s->pb);
     st->codec->block_align = st->codec->channels * avio_rl32(s->pb);
 
-    avio_seek(s->pb, s->data_offset, SEEK_SET);
+    avio_seek(s->pb, s->internal->data_offset, SEEK_SET);
 
     return 0;
 }
diff --git a/libavformat/c93.c b/libavformat/c93.c
index 93a61be..d67afcf 100644
--- a/libavformat/c93.c
+++ b/libavformat/c93.c
@@ -24,13 +24,13 @@
 #include "voc.h"
 #include "libavutil/intreadwrite.h"
 
-typedef struct {
+typedef struct C93BlockRecord {
     uint16_t index;
     uint8_t length;
     uint8_t frames;
 } C93BlockRecord;
 
-typedef struct {
+typedef struct C93DemuxContext {
     VocDecContext voc;
 
     C93BlockRecord block_records[512];
diff --git a/libavformat/cache.c b/libavformat/cache.c
index 02b02bb..d3d12bb 100644
--- a/libavformat/cache.c
+++ b/libavformat/cache.c
@@ -70,7 +70,7 @@
     return (*(int64_t *) key) - ((const CacheEntry *) node)->logical_pos;
 }
 
-static int cache_open(URLContext *h, const char *arg, int flags)
+static int cache_open(URLContext *h, const char *arg, int flags, AVDictionary **options)
 {
     char *buffername;
     Context *c= h->priv_data;
@@ -86,7 +86,7 @@
     unlink(buffername);
     av_freep(&buffername);
 
-    return ffurl_open(&c->inner, arg, flags, &h->interrupt_callback, NULL);
+    return ffurl_open(&c->inner, arg, flags, &h->interrupt_callback, options);
 }
 
 static int add_entry(URLContext *h, const unsigned char *buf, int size)
@@ -145,7 +145,7 @@
 
     return 0;
 fail:
-    //we could truncate the file to pos here if pos >=0 but ftruncate isnt available in VS so
+    //we could truncate the file to pos here if pos >=0 but ftruncate isn't available in VS so
     //for simplicty we just leave the file a bit larger
     av_free(entry);
     av_free(node);
@@ -300,7 +300,7 @@
 #define D AV_OPT_FLAG_DECODING_PARAM
 
 static const AVOption options[] = {
-    { "read_ahead_limit", "Amount in bytes that may be read ahead when seeking isnt supported, -1 for unlimited", OFFSET(read_ahead_limit), AV_OPT_TYPE_INT, { .i64 = 65536 }, -1, INT_MAX, D },
+    { "read_ahead_limit", "Amount in bytes that may be read ahead when seeking isn't supported, -1 for unlimited", OFFSET(read_ahead_limit), AV_OPT_TYPE_INT, { .i64 = 65536 }, -1, INT_MAX, D },
     {NULL},
 };
 
@@ -313,7 +313,7 @@
 
 URLProtocol ff_cache_protocol = {
     .name                = "cache",
-    .url_open            = cache_open,
+    .url_open2           = cache_open,
     .url_read            = cache_read,
     .url_seek            = cache_seek,
     .url_close           = cache_close,
diff --git a/libavformat/cafdec.c b/libavformat/cafdec.c
index 7d518d7..e31c0a5 100644
--- a/libavformat/cafdec.c
+++ b/libavformat/cafdec.c
@@ -36,7 +36,7 @@
 #include "libavutil/dict.h"
 #include "caf.h"
 
-typedef struct {
+typedef struct CafContext {
     int bytes_per_packet;           ///< bytes in a packet, or 0 if variable
     int frames_per_packet;          ///< frames in a packet, or 0 if variable
     int64_t num_bytes;              ///< total number of bytes in stream
diff --git a/libavformat/cavsvideodec.c b/libavformat/cavsvideodec.c
index 880f4ab..b4da58e 100644
--- a/libavformat/cavsvideodec.c
+++ b/libavformat/cavsvideodec.c
@@ -21,6 +21,7 @@
 
 #include "avformat.h"
 #include "rawdec.h"
+#include "libavcodec/internal.h"
 
 #define CAVS_SEQ_START_CODE       0x000001b0
 #define CAVS_PIC_I_START_CODE     0x000001b3
@@ -33,10 +34,10 @@
 {
     uint32_t code= -1;
     int pic=0, seq=0, slice_pos = 0;
-    int i;
+    const uint8_t *ptr = p->buf, *end = p->buf + p->buf_size;
 
-    for(i=0; i<p->buf_size; i++){
-        code = (code<<8) + p->buf[i];
+    while (ptr < end) {
+        ptr = avpriv_find_start_code(ptr, end, &code);
         if ((code & 0xffffff00) == 0x100) {
             if(code < CAVS_SEQ_START_CODE) {
                 /* slices have to be consecutive */
@@ -49,7 +50,7 @@
             if (code == CAVS_SEQ_START_CODE) {
                 seq++;
                 /* check for the only currently supported profile */
-                if(p->buf[i+1] != CAVS_PROFILE_JIZHUN)
+                if (*ptr != CAVS_PROFILE_JIZHUN)
                     return 0;
             } else if ((code == CAVS_PIC_I_START_CODE) ||
                        (code == CAVS_PIC_PB_START_CODE)) {
diff --git a/libavformat/crypto.c b/libavformat/crypto.c
index 22529fb..f56ee4e 100644
--- a/libavformat/crypto.c
+++ b/libavformat/crypto.c
@@ -29,7 +29,7 @@
 #define MAX_BUFFER_BLOCKS 150
 #define BLOCKSIZE 16
 
-typedef struct {
+typedef struct CryptoContext {
     const AVClass *class;
     URLContext *hd;
     uint8_t inbuffer [BLOCKSIZE*MAX_BUFFER_BLOCKS],
diff --git a/libavformat/dashenc.c b/libavformat/dashenc.c
index 8b6be71..cc88676 100644
--- a/libavformat/dashenc.c
+++ b/libavformat/dashenc.c
@@ -69,6 +69,7 @@
     int nb_segments, segments_size, segment_index;
     Segment **segments;
     int64_t first_pts, start_pts, max_pts;
+    int64_t last_dts;
     int bit_rate;
     char bandwidth_str[64];
 
@@ -155,8 +156,7 @@
             if (avio_open_dyn_buf(&pb) < 0)
                 return;
             if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
-                avio_close_dyn_buf(pb, &tmpbuf);
-                av_free(tmpbuf);
+                ffio_free_dyn_buf(&pb);
                 return;
             }
             extradata_size = avio_close_dyn_buf(pb, &extradata);
@@ -499,8 +499,10 @@
         for (i = 0; i < s->nb_streams; i++) {
             AVStream *st = s->streams[i];
             OutputStream *os = &c->streams[i];
-            if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_VIDEO)
+
+            if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO)
                 continue;
+
             avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/mp4\" codecs=\"%s\"%s width=\"%d\" height=\"%d\">\n", i, os->codec_str, os->bandwidth_str, st->codec->width, st->codec->height);
             output_segment_list(&c->streams[i], out, c);
             avio_printf(out, "\t\t\t</Representation>\n");
@@ -512,8 +514,10 @@
         for (i = 0; i < s->nb_streams; i++) {
             AVStream *st = s->streams[i];
             OutputStream *os = &c->streams[i];
-            if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
+
+            if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
                 continue;
+
             avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/mp4\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n", i, os->codec_str, os->bandwidth_str, st->codec->sample_rate);
             avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n", st->codec->channels);
             output_segment_list(&c->streams[i], out, c);
@@ -648,9 +652,10 @@
         else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
             c->has_audio = 1;
 
-        set_codec_str(s, os->ctx->streams[0]->codec, os->codec_str, sizeof(os->codec_str));
+        set_codec_str(s, st->codec, os->codec_str, sizeof(os->codec_str));
         os->first_pts = AV_NOPTS_VALUE;
         os->max_pts = AV_NOPTS_VALUE;
+        os->last_dts = AV_NOPTS_VALUE;
         os->segment_index = 1;
     }
 
@@ -733,6 +738,29 @@
     *index_length = AV_RB32(&buf[0]);
 }
 
+static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
+                                   AVCodecContext *codec)
+{
+    uint8_t *extradata;
+
+    if (os->ctx->streams[0]->codec->extradata_size || !codec->extradata_size)
+        return 0;
+
+    extradata = av_malloc(codec->extradata_size);
+
+    if (!extradata)
+        return AVERROR(ENOMEM);
+
+    memcpy(extradata, codec->extradata, codec->extradata_size);
+
+    os->ctx->streams[0]->codec->extradata = extradata;
+    os->ctx->streams[0]->codec->extradata_size = codec->extradata_size;
+
+    set_codec_str(s, codec, os->codec_str, sizeof(os->codec_str));
+
+    return 0;
+}
+
 static int dash_flush(AVFormatContext *s, int final, int stream)
 {
     DASHContext *c = s->priv_data;
@@ -836,6 +864,20 @@
     int64_t seg_end_duration = (os->segment_index) * (int64_t) c->min_seg_duration;
     int ret;
 
+    ret = update_stream_extradata(s, os, st->codec);
+    if (ret < 0)
+        return ret;
+
+    // Fill in a heuristic guess of the packet duration, if none is available.
+    // The mp4 muxer will do something similar (for the last packet in a fragment)
+    // if nothing is set (setting it for the other packets doesn't hurt).
+    // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
+    // invoke its heuristic (this doesn't have to be identical to that algorithm),
+    // so that we know the exact timestamps of fragments.
+    if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
+        pkt->duration = pkt->dts - os->last_dts;
+    os->last_dts = pkt->dts;
+
     // If forcing the stream to start at 0, the mp4 muxer will set the start
     // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
     if (os->first_pts == AV_NOPTS_VALUE &&
diff --git a/libavformat/dss.c b/libavformat/dss.c
new file mode 100644
index 0000000..ead0ee0
--- /dev/null
+++ b/libavformat/dss.c
@@ -0,0 +1,397 @@
+/*
+ * Digital Speech Standard (DSS) demuxer
+ * Copyright (c) 2014 Oleksij Rempel <linux@rempel-privat.de>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/attributes.h"
+#include "libavutil/bswap.h"
+#include "libavutil/channel_layout.h"
+#include "libavutil/intreadwrite.h"
+
+#include "avformat.h"
+#include "internal.h"
+
+#define DSS_HEAD_OFFSET_AUTHOR        0xc
+#define DSS_AUTHOR_SIZE               16
+
+#define DSS_HEAD_OFFSET_START_TIME    0x26
+#define DSS_HEAD_OFFSET_END_TIME      0x32
+#define DSS_TIME_SIZE                 12
+
+#define DSS_HEAD_OFFSET_ACODEC        0x2a4
+#define DSS_ACODEC_DSS_SP             0x0    /* SP mode */
+#define DSS_ACODEC_G723_1             0x2    /* LP mode */
+
+#define DSS_HEAD_OFFSET_COMMENT       0x31e
+#define DSS_COMMENT_SIZE              64
+
+#define DSS_BLOCK_SIZE                512
+#define DSS_HEADER_SIZE              (DSS_BLOCK_SIZE * 2)
+#define DSS_AUDIO_BLOCK_HEADER_SIZE   6
+#define DSS_FRAME_SIZE                42
+
+static const uint8_t frame_size[4] = { 24, 20, 4, 1 };
+
+typedef struct DSSDemuxContext {
+    unsigned int audio_codec;
+    int counter;
+    int swap;
+    int dss_sp_swap_byte;
+    int8_t *dss_sp_buf;
+
+    int packet_size;
+} DSSDemuxContext;
+
+static int dss_probe(AVProbeData *p)
+{
+    if (AV_RL32(p->buf) != MKTAG(0x2, 'd', 's', 's'))
+        return 0;
+
+    return AVPROBE_SCORE_MAX;
+}
+
+static int dss_read_metadata_date(AVFormatContext *s, unsigned int offset,
+                                  const char *key)
+{
+    AVIOContext *pb = s->pb;
+    char datetime[64], string[DSS_TIME_SIZE + 1] = { 0 };
+    int y, month, d, h, minute, sec;
+    int ret;
+
+    avio_seek(pb, offset, SEEK_SET);
+
+    ret = avio_read(s->pb, string, DSS_TIME_SIZE);
+    if (ret < DSS_TIME_SIZE)
+        return ret < 0 ? ret : AVERROR_EOF;
+
+    if (sscanf(string, "%2d%2d%2d%2d%2d%2d", &y, &month, &d, &h, &minute, &sec) != 6)
+        return AVERROR_INVALIDDATA;
+    /* We deal with a two-digit year here, so set the default date to 2000
+     * and hope it will never be used in the next century. */
+    snprintf(datetime, sizeof(datetime), "%.4d-%.2d-%.2dT%.2d:%.2d:%.2d",
+             y + 2000, month, d, h, minute, sec);
+    return av_dict_set(&s->metadata, key, datetime, 0);
+}
+
+static int dss_read_metadata_string(AVFormatContext *s, unsigned int offset,
+                                    unsigned int size, const char *key)
+{
+    AVIOContext *pb = s->pb;
+    char *value;
+    int ret;
+
+    avio_seek(pb, offset, SEEK_SET);
+
+    value = av_mallocz(size + 1);
+    if (!value)
+        return AVERROR(ENOMEM);
+
+    ret = avio_read(s->pb, value, size);
+    if (ret < size) {
+        ret = ret < 0 ? ret : AVERROR_EOF;
+        goto exit;
+    }
+
+    ret = av_dict_set(&s->metadata, key, value, 0);
+
+exit:
+    av_free(value);
+    return ret;
+}
+
+static int dss_read_header(AVFormatContext *s)
+{
+    DSSDemuxContext *ctx = s->priv_data;
+    AVIOContext *pb = s->pb;
+    AVStream *st;
+    int ret;
+
+    st = avformat_new_stream(s, NULL);
+    if (!st)
+        return AVERROR(ENOMEM);
+
+    ret = dss_read_metadata_string(s, DSS_HEAD_OFFSET_AUTHOR,
+                                   DSS_AUTHOR_SIZE, "author");
+    if (ret)
+        return ret;
+
+    ret = dss_read_metadata_date(s, DSS_HEAD_OFFSET_END_TIME, "date");
+    if (ret)
+        return ret;
+
+    ret = dss_read_metadata_string(s, DSS_HEAD_OFFSET_COMMENT,
+                                   DSS_COMMENT_SIZE, "comment");
+    if (ret)
+        return ret;
+
+    avio_seek(pb, DSS_HEAD_OFFSET_ACODEC, SEEK_SET);
+    ctx->audio_codec = avio_r8(pb);
+
+    if (ctx->audio_codec == DSS_ACODEC_DSS_SP) {
+        st->codec->codec_id    = AV_CODEC_ID_DSS_SP;
+        st->codec->sample_rate = 11025;
+    } else if (ctx->audio_codec == DSS_ACODEC_G723_1) {
+        st->codec->codec_id    = AV_CODEC_ID_G723_1;
+        st->codec->sample_rate = 8000;
+    } else {
+        avpriv_request_sample(s, "Support for codec %x in DSS",
+                              ctx->audio_codec);
+        return AVERROR_PATCHWELCOME;
+    }
+
+    st->codec->codec_type     = AVMEDIA_TYPE_AUDIO;
+    st->codec->channel_layout = AV_CH_LAYOUT_MONO;
+    st->codec->channels       = 1;
+
+    avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
+    st->start_time = 0;
+
+    /* Jump over header */
+
+    if (avio_seek(pb, DSS_HEADER_SIZE, SEEK_SET) != DSS_HEADER_SIZE)
+        return AVERROR(EIO);
+
+    ctx->counter = 0;
+    ctx->swap    = 0;
+
+    ctx->dss_sp_buf = av_malloc(DSS_FRAME_SIZE + 1);
+    if (!ctx->dss_sp_buf)
+        return AVERROR(ENOMEM);
+
+    return 0;
+}
+
+static void dss_skip_audio_header(AVFormatContext *s, AVPacket *pkt)
+{
+    DSSDemuxContext *ctx = s->priv_data;
+    AVIOContext *pb = s->pb;
+
+    avio_skip(pb, DSS_AUDIO_BLOCK_HEADER_SIZE);
+    ctx->counter += DSS_BLOCK_SIZE - DSS_AUDIO_BLOCK_HEADER_SIZE;
+}
+
+static void dss_sp_byte_swap(DSSDemuxContext *ctx,
+                             uint8_t *dst, const uint8_t *src)
+{
+    int i;
+
+    if (ctx->swap) {
+        for (i = 3; i < DSS_FRAME_SIZE; i += 2)
+            dst[i] = src[i];
+
+        for (i = 0; i < DSS_FRAME_SIZE - 2; i += 2)
+            dst[i] = src[i + 4];
+
+        dst[1] = ctx->dss_sp_swap_byte;
+    } else {
+        memcpy(dst, src, DSS_FRAME_SIZE);
+        ctx->dss_sp_swap_byte = src[DSS_FRAME_SIZE - 2];
+    }
+
+    /* make sure byte 40 is always 0 */
+    dst[DSS_FRAME_SIZE - 2] = 0;
+    ctx->swap             ^= 1;
+}
+
+static int dss_sp_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    DSSDemuxContext *ctx = s->priv_data;
+    AVStream *st = s->streams[0];
+    int read_size, ret, offset = 0, buff_offset = 0;
+    int64_t pos = avio_tell(s->pb);
+
+    if (ctx->counter == 0)
+        dss_skip_audio_header(s, pkt);
+
+    if (ctx->swap) {
+        read_size   = DSS_FRAME_SIZE - 2;
+        buff_offset = 3;
+    } else
+        read_size = DSS_FRAME_SIZE;
+
+    ctx->counter -= read_size;
+    ctx->packet_size = DSS_FRAME_SIZE - 1;
+
+    ret = av_new_packet(pkt, DSS_FRAME_SIZE);
+    if (ret < 0)
+        return ret;
+
+    pkt->duration     = 264;
+    pkt->pos = pos;
+    pkt->stream_index = 0;
+    s->bit_rate = 8LL * ctx->packet_size * st->codec->sample_rate * 512 / (506 * pkt->duration);
+
+    if (ctx->counter < 0) {
+        int size2 = ctx->counter + read_size;
+
+        ret = avio_read(s->pb, ctx->dss_sp_buf + offset + buff_offset,
+                        size2 - offset);
+        if (ret < size2 - offset)
+            goto error_eof;
+
+        dss_skip_audio_header(s, pkt);
+        offset = size2;
+    }
+
+    ret = avio_read(s->pb, ctx->dss_sp_buf + offset + buff_offset,
+                    read_size - offset);
+    if (ret < read_size - offset)
+        goto error_eof;
+
+    dss_sp_byte_swap(ctx, pkt->data, ctx->dss_sp_buf);
+
+    if (ctx->dss_sp_swap_byte < 0) {
+        ret = AVERROR(EAGAIN);
+        goto error_eof;
+    }
+
+    if (pkt->data[0] == 0xff)
+        return AVERROR_INVALIDDATA;
+
+    return pkt->size;
+
+error_eof:
+    av_free_packet(pkt);
+    return ret < 0 ? ret : AVERROR_EOF;
+}
+
+static int dss_723_1_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    DSSDemuxContext *ctx = s->priv_data;
+    AVStream *st = s->streams[0];
+    int size, byte, ret, offset;
+    int64_t pos = avio_tell(s->pb);
+
+    if (ctx->counter == 0)
+        dss_skip_audio_header(s, pkt);
+
+    /* We make one byte-step here. Don't forget to add offset. */
+    byte = avio_r8(s->pb);
+    if (byte == 0xff)
+        return AVERROR_INVALIDDATA;
+
+    size = frame_size[byte & 3];
+
+    ctx->packet_size = size;
+    ctx->counter -= size;
+
+    ret = av_new_packet(pkt, size);
+    if (ret < 0)
+        return ret;
+    pkt->pos = pos;
+
+    pkt->data[0]  = byte;
+    offset        = 1;
+    pkt->duration = 240;
+    s->bit_rate = 8LL * size * st->codec->sample_rate * 512 / (506 * pkt->duration);
+
+    pkt->stream_index = 0;
+
+    if (ctx->counter < 0) {
+        int size2 = ctx->counter + size;
+
+        ret = avio_read(s->pb, pkt->data + offset,
+                        size2 - offset);
+        if (ret < size2 - offset) {
+            av_free_packet(pkt);
+            return ret < 0 ? ret : AVERROR_EOF;
+        }
+
+        dss_skip_audio_header(s, pkt);
+        offset = size2;
+    }
+
+    ret = avio_read(s->pb, pkt->data + offset, size - offset);
+    if (ret < size - offset) {
+        av_free_packet(pkt);
+        return ret < 0 ? ret : AVERROR_EOF;
+    }
+
+    return pkt->size;
+}
+
+static int dss_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    DSSDemuxContext *ctx = s->priv_data;
+
+    if (ctx->audio_codec == DSS_ACODEC_DSS_SP)
+        return dss_sp_read_packet(s, pkt);
+    else
+        return dss_723_1_read_packet(s, pkt);
+}
+
+static int dss_read_close(AVFormatContext *s)
+{
+    DSSDemuxContext *ctx = s->priv_data;
+
+    av_freep(&ctx->dss_sp_buf);
+
+    return 0;
+}
+
+static int dss_read_seek(AVFormatContext *s, int stream_index,
+                         int64_t timestamp, int flags)
+{
+    DSSDemuxContext *ctx = s->priv_data;
+    int64_t ret, seekto;
+    uint8_t header[DSS_AUDIO_BLOCK_HEADER_SIZE];
+    int offset;
+
+    if (ctx->audio_codec == DSS_ACODEC_DSS_SP)
+        seekto = timestamp / 264 * 41 / 506 * 512;
+    else
+        seekto = timestamp / 240 * ctx->packet_size / 506 * 512;
+
+    if (seekto < 0)
+        seekto = 0;
+
+    seekto += DSS_HEADER_SIZE;
+
+    ret = avio_seek(s->pb, seekto, SEEK_SET);
+    if (ret < 0)
+        return ret;
+
+    avio_read(s->pb, header, DSS_AUDIO_BLOCK_HEADER_SIZE);
+    ctx->swap = !!(header[0] & 0x80);
+    offset = 2*header[1] + 2*ctx->swap;
+    if (offset < DSS_AUDIO_BLOCK_HEADER_SIZE)
+        return AVERROR_INVALIDDATA;
+    if (offset == DSS_AUDIO_BLOCK_HEADER_SIZE) {
+        ctx->counter = 0;
+        offset = avio_skip(s->pb, -DSS_AUDIO_BLOCK_HEADER_SIZE);
+    } else {
+        ctx->counter = DSS_BLOCK_SIZE - offset;
+        offset = avio_skip(s->pb, offset - DSS_AUDIO_BLOCK_HEADER_SIZE);
+    }
+    ctx->dss_sp_swap_byte = -1;
+    return 0;
+}
+
+
+AVInputFormat ff_dss_demuxer = {
+    .name           = "dss",
+    .long_name      = NULL_IF_CONFIG_SMALL("Digital Speech Standard (DSS)"),
+    .priv_data_size = sizeof(DSSDemuxContext),
+    .read_probe     = dss_probe,
+    .read_header    = dss_read_header,
+    .read_packet    = dss_read_packet,
+    .read_close     = dss_read_close,
+    .read_seek      = dss_read_seek,
+    .extensions     = "dss"
+};
diff --git a/libavformat/dtsdec.c b/libavformat/dtsdec.c
index d054f43..50b14c6 100644
--- a/libavformat/dtsdec.c
+++ b/libavformat/dtsdec.c
@@ -20,16 +20,13 @@
  */
 
 #include "libavcodec/bytestream.h"
-#include "libavcodec/get_bits.h"
 #include "libavcodec/dca.h"
+#include "libavcodec/dca_syncwords.h"
+#include "libavcodec/get_bits.h"
+
 #include "avformat.h"
 #include "rawdec.h"
 
-#define DCA_MARKER_14B_BE 0x1FFFE800
-#define DCA_MARKER_14B_LE 0xFF1F00E8
-#define DCA_MARKER_RAW_BE 0x7FFE8001
-#define DCA_MARKER_RAW_LE 0xFE7F0180
-
 static int dts_probe(AVProbeData *p)
 {
     const uint8_t *buf, *bufp;
@@ -53,18 +50,18 @@
             diff += FFABS(((int16_t)AV_RL16(buf)) - (int16_t)AV_RL16(buf-4));
 
         /* regular bitstream */
-        if (state == DCA_MARKER_RAW_BE)
+        if (state == DCA_SYNCWORD_CORE_BE)
             marker = 0;
-        else if (state == DCA_MARKER_RAW_LE)
+        else if (state == DCA_SYNCWORD_CORE_LE)
             marker = 1;
 
         /* 14 bits big-endian bitstream */
-        else if (state == DCA_MARKER_14B_BE &&
+        else if (state == DCA_SYNCWORD_CORE_14B_BE &&
                  (bytestream_get_be16(&bufp) & 0xFFF0) == 0x07F0)
             marker = 2;
 
         /* 14 bits little-endian bitstream */
-        else if (state == DCA_MARKER_14B_LE &&
+        else if (state == DCA_SYNCWORD_CORE_14B_LE &&
                  (bytestream_get_be16(&bufp) & 0xF0FF) == 0xF007)
             marker = 3;
         else
diff --git a/libavformat/dv.c b/libavformat/dv.c
index 3243ca2..485a5f8 100644
--- a/libavformat/dv.c
+++ b/libavformat/dv.c
@@ -425,7 +425,7 @@
     const AVDVProfile *sys = av_dv_codec_profile2(c->vst->codec->width, c->vst->codec->height,
                                                  c->vst->codec->pix_fmt, c->vst->codec->time_base);
     int64_t offset;
-    int64_t size       = avio_size(s->pb) - s->data_offset;
+    int64_t size       = avio_size(s->pb) - s->internal->data_offset;
     int64_t max_offset = ((size - 1) / sys->frame_size) * sys->frame_size;
 
     offset = sys->frame_size * timestamp;
@@ -435,7 +435,7 @@
     else if (offset < 0)
         offset = 0;
 
-    return offset + s->data_offset;
+    return offset + s->internal->data_offset;
 }
 
 void ff_dv_offset_reset(DVDemuxContext *c, int64_t frame_offset)
diff --git a/libavformat/dvbsub.c b/libavformat/dvbsub.c
index d52bc86..3d2f704 100644
--- a/libavformat/dvbsub.c
+++ b/libavformat/dvbsub.c
@@ -37,7 +37,7 @@
             const uint8_t *ptr = p->buf + i;
             uint8_t histogram[6] = {0};
             int min = 255;
-            for(j=0; ptr + 6 < end; j++) {
+            for(j=0; 6 < end - ptr; j++) {
                 if (*ptr != 0x0f)
                     break;
                 type    = ptr[1];
@@ -49,6 +49,8 @@
                     histogram[type - 0x10] ++;
                 } else
                     break;
+                if (6 + len > end - ptr)
+                    break;
                 ptr += 6 + len;
             }
             for (k=0; k < 4; k++) {
diff --git a/libavformat/dxa.c b/libavformat/dxa.c
index 9da2ffd..4403356 100644
--- a/libavformat/dxa.c
+++ b/libavformat/dxa.c
@@ -28,7 +28,7 @@
 
 #define DXA_EXTRA_SIZE  9
 
-typedef struct{
+typedef struct DXAContext {
     int frames;
     int has_sound;
     int bpc;
diff --git a/libavformat/eacdata.c b/libavformat/eacdata.c
index 57e5145..165ff1a 100644
--- a/libavformat/eacdata.c
+++ b/libavformat/eacdata.c
@@ -31,7 +31,7 @@
 #include "avformat.h"
 #include "internal.h"
 
-typedef struct {
+typedef struct CdataDemuxContext {
   unsigned int channels;
   unsigned int audio_pts;
 } CdataDemuxContext;
diff --git a/libavformat/ffmdec.c b/libavformat/ffmdec.c
index 987f419..33bbde0 100644
--- a/libavformat/ffmdec.c
+++ b/libavformat/ffmdec.c
@@ -82,6 +82,7 @@
     FFMContext *ffm = s->priv_data;
     AVIOContext *pb = s->pb;
     int len, fill_size, size1, frame_offset, id;
+    int64_t last_pos = -1;
 
     size1 = size;
     while (size > 0) {
@@ -101,9 +102,11 @@
                 avio_seek(pb, tell, SEEK_SET);
             }
             id = avio_rb16(pb); /* PACKET_ID */
-            if (id != PACKET_ID)
+            if (id != PACKET_ID) {
                 if (ffm_resync(s, id) < 0)
                     return -1;
+                last_pos = avio_tell(pb);
+            }
             fill_size = avio_rb16(pb);
             ffm->dts = avio_rb64(pb);
             frame_offset = avio_rb16(pb);
@@ -117,7 +120,9 @@
                 if (!frame_offset) {
                     /* This packet has no frame headers in it */
                     if (avio_tell(pb) >= ffm->packet_size * 3LL) {
-                        avio_seek(pb, -ffm->packet_size * 2LL, SEEK_CUR);
+                        int64_t seekback = FFMIN(ffm->packet_size * 2LL, avio_tell(pb) - last_pos);
+                        seekback = FFMAX(seekback, 0);
+                        avio_seek(pb, -seekback, SEEK_CUR);
                         goto retry_read;
                     }
                     /* This is bad, we cannot find a valid frame header */
@@ -261,7 +266,7 @@
     AVIOContext *pb = s->pb;
     AVCodecContext *codec;
     int ret;
-    int f_main = 0, f_cprv, f_stvi, f_stau;
+    int f_main = 0, f_cprv = -1, f_stvi = -1, f_stau = -1;
     AVCodec *enc;
     char *buffer;
 
@@ -331,6 +336,12 @@
             }
             codec->time_base.num = avio_rb32(pb);
             codec->time_base.den = avio_rb32(pb);
+            if (codec->time_base.num <= 0 || codec->time_base.den <= 0) {
+                av_log(s, AV_LOG_ERROR, "Invalid time base %d/%d\n",
+                       codec->time_base.num, codec->time_base.den);
+                ret = AVERROR_INVALIDDATA;
+                goto fail;
+            }
             codec->width = avio_rb16(pb);
             codec->height = avio_rb16(pb);
             codec->gop_size = avio_rb16(pb);
@@ -434,7 +445,7 @@
     }
 
     /* get until end of block reached */
-    while ((avio_tell(pb) % ffm->packet_size) != 0)
+    while ((avio_tell(pb) % ffm->packet_size) != 0 && !pb->eof_reached)
         avio_r8(pb);
 
     /* init packet demux */
@@ -503,6 +514,11 @@
         case AVMEDIA_TYPE_VIDEO:
             codec->time_base.num = avio_rb32(pb);
             codec->time_base.den = avio_rb32(pb);
+            if (codec->time_base.num <= 0 || codec->time_base.den <= 0) {
+                av_log(s, AV_LOG_ERROR, "Invalid time base %d/%d\n",
+                       codec->time_base.num, codec->time_base.den);
+                goto fail;
+            }
             codec->width = avio_rb16(pb);
             codec->height = avio_rb16(pb);
             codec->gop_size = avio_rb16(pb);
@@ -561,7 +577,7 @@
     }
 
     /* get until end of block reached */
-    while ((avio_tell(pb) % ffm->packet_size) != 0)
+    while ((avio_tell(pb) % ffm->packet_size) != 0 && !pb->eof_reached)
         avio_r8(pb);
 
     /* init packet demux */
diff --git a/libavformat/ffmenc.c b/libavformat/ffmenc.c
index e6d1a31..3abbfdd 100644
--- a/libavformat/ffmenc.c
+++ b/libavformat/ffmenc.c
@@ -25,6 +25,7 @@
 #include "libavutil/parseutils.h"
 #include "libavutil/opt.h"
 #include "avformat.h"
+#include "avio_internal.h"
 #include "internal.h"
 #include "ffm.h"
 
@@ -94,15 +95,18 @@
     av_free(dyn_buf);
 }
 
-static int ffm_write_header_codec_private_ctx(AVIOContext *pb, AVCodecContext *ctx, int type)
+static int ffm_write_header_codec_private_ctx(AVFormatContext *s, AVCodecContext *ctx, int type)
 {
+    AVIOContext *pb = s->pb;
     AVIOContext *tmp;
     char *buf = NULL;
     int ret;
     const AVCodec *enc = ctx->codec ? ctx->codec : avcodec_find_encoder(ctx->codec_id);
 
-    if (!enc)
-        return AVERROR(EINVAL);
+    if (!enc) {
+        av_log(s, AV_LOG_WARNING, "Stream codec is not found. Codec private options are not stored.\n");
+        return 0;
+    }
     if (ctx->priv_data && enc->priv_class && enc->priv_data_size) {
         if ((ret = av_opt_serialize(ctx->priv_data, AV_OPT_FLAG_ENCODING_PARAM | type,
                                     AV_OPT_SERIALIZE_SKIP_DEFAULTS, &buf, '=', ',')) < 0)
@@ -124,7 +128,6 @@
 {
     AVIOContext *tmp;
     char *buf = NULL;
-    uint8_t *p = NULL;
     int ret, need_coma = 0;
 
 #define SKIP_DEFAULTS   AV_OPT_SERIALIZE_SKIP_DEFAULTS
@@ -137,7 +140,7 @@
         goto fail;
     if (buf && strlen(buf)) {
         avio_write(tmp, buf, strlen(buf));
-        av_free(buf);
+        av_freep(&buf);
         need_coma = 1;
     }
     if ((ret = av_opt_serialize(ctx, 0, SKIP_DEFAULTS | OPT_FLAGS_EXACT, &buf, '=', ',')) < 0)
@@ -146,15 +149,14 @@
         if (need_coma)
             avio_w8(tmp, ',');
         avio_write(tmp, buf, strlen(buf));
-        av_free(buf);
     }
+    av_freep(&buf);
     avio_w8(tmp, 0);
     write_header_chunk(pb, tmp, tag);
     return 0;
   fail:
     av_free(buf);
-    avio_close_dyn_buf(tmp, &p);
-    av_free(p);
+    ffio_free_dyn_buf(&tmp);
     return ret;
 
 #undef SKIP_DEFAULTS
@@ -281,7 +283,7 @@
                                                         st->recommended_encoder_configuration)) < 0)
                 return ret;
             } else if ((ret = ffm_write_header_codec_ctx(s->pb, codec, MKBETAG('S', '2', 'V', 'I'), AV_OPT_FLAG_VIDEO_PARAM)) < 0 ||
-                       (ret = ffm_write_header_codec_private_ctx(s->pb, codec, AV_OPT_FLAG_VIDEO_PARAM)) < 0)
+                       (ret = ffm_write_header_codec_private_ctx(s, codec, AV_OPT_FLAG_VIDEO_PARAM)) < 0)
                 return ret;
             break;
         case AVMEDIA_TYPE_AUDIO:
@@ -292,7 +294,7 @@
                                                         st->recommended_encoder_configuration)) < 0)
                 return ret;
             } else if ((ret = ffm_write_header_codec_ctx(s->pb, codec, MKBETAG('S', '2', 'A', 'U'), AV_OPT_FLAG_AUDIO_PARAM)) < 0 ||
-                     (ret = ffm_write_header_codec_private_ctx(s->pb, codec, AV_OPT_FLAG_AUDIO_PARAM)) < 0)
+                     (ret = ffm_write_header_codec_private_ctx(s, codec, AV_OPT_FLAG_AUDIO_PARAM)) < 0)
                 return ret;
             break;
         default:
diff --git a/libavformat/filmstripdec.c b/libavformat/filmstripdec.c
index b76d4b7..cdbb93b 100644
--- a/libavformat/filmstripdec.c
+++ b/libavformat/filmstripdec.c
@@ -30,7 +30,7 @@
 
 #define RAND_TAG MKBETAG('R','a','n','d')
 
-typedef struct {
+typedef struct FilmstripDemuxContext {
     int leading;
 } FilmstripDemuxContext;
 
diff --git a/libavformat/filmstripenc.c b/libavformat/filmstripenc.c
index 7c9bc6d..9e2c710 100644
--- a/libavformat/filmstripenc.c
+++ b/libavformat/filmstripenc.c
@@ -29,7 +29,7 @@
 
 #define RAND_TAG MKBETAG('R','a','n','d')
 
-typedef struct {
+typedef struct FilmstripMuxContext {
     int nb_frames;
 } FilmstripMuxContext;
 
diff --git a/libavformat/flacenc.c b/libavformat/flacenc.c
index 0eea942..4255363 100644
--- a/libavformat/flacenc.c
+++ b/libavformat/flacenc.c
@@ -95,7 +95,7 @@
         padding = 8192;
     /* The FLAC specification states that 24 bits are used to represent the
      * size of a metadata block so we must clip this value to 2^24-1. */
-    padding = av_clip(padding, 0, 16777215);
+    padding = av_clip_uintp2(padding, 24);
 
     ret = ff_flac_write_header(s->pb, codec->extradata,
                                codec->extradata_size, 0);
diff --git a/libavformat/flvdec.c b/libavformat/flvdec.c
index 572268f..b625c78 100644
--- a/libavformat/flvdec.c
+++ b/libavformat/flvdec.c
@@ -39,7 +39,7 @@
 
 #define VALIDATE_INDEX_TS_THRESH 2500
 
-typedef struct {
+typedef struct FLVContext {
     const AVClass *class; ///< Class for private options.
     int trust_metadata;   ///< configure streams according onMetaData
     int wrong_dts;        ///< wrong dts due to negative cts
@@ -92,8 +92,8 @@
         return NULL;
     st->codec->codec_type = codec_type;
     if (s->nb_streams>=3 ||(   s->nb_streams==2
-                           && s->streams[0]->codec->codec_type != AVMEDIA_TYPE_DATA
-                           && s->streams[1]->codec->codec_type != AVMEDIA_TYPE_DATA))
+                           && s->streams[0]->codec->codec_type != AVMEDIA_TYPE_SUBTITLE
+                           && s->streams[1]->codec->codec_type != AVMEDIA_TYPE_SUBTITLE))
         s->ctx_flags &= ~AVFMTCTX_NOHEADER;
 
     avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
@@ -482,7 +482,7 @@
                          0 <= (int)(num_val * 1024.0))
                     acodec->bit_rate = num_val * 1024.0;
                 else if (!strcmp(key, "datastream")) {
-                    AVStream *st = create_stream(s, AVMEDIA_TYPE_DATA);
+                    AVStream *st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
                     if (!st)
                         return AVERROR(ENOMEM);
                     st->codec->codec_id = AV_CODEC_ID_TEXT;
@@ -546,7 +546,8 @@
 }
 
 #define TYPE_ONTEXTDATA 1
-#define TYPE_UNKNOWN 2
+#define TYPE_ONCAPTION 2
+#define TYPE_UNKNOWN 9
 
 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
 {
@@ -573,6 +574,9 @@
     if (!strcmp(buffer, "onTextData"))
         return TYPE_ONTEXTDATA;
 
+    if (!strcmp(buffer, "onCaption"))
+        return TYPE_ONCAPTION;
+
     if (strcmp(buffer, "onMetaData") && strcmp(buffer, "onCuePoint"))
         return TYPE_UNKNOWN;
 
@@ -584,7 +588,7 @@
             vstream = stream;
         else if (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO)
             astream = stream;
-        else if (stream->codec->codec_type == AVMEDIA_TYPE_DATA)
+        else if (stream->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
             dstream = stream;
     }
 
@@ -717,8 +721,11 @@
     char buf[20];
     int ret = AVERROR_INVALIDDATA;
     int i, length = -1;
+    int array = 0;
 
     switch (avio_r8(pb)) {
+    case AMF_DATA_TYPE_ARRAY:
+        array = 1;
     case AMF_DATA_TYPE_MIXEDARRAY:
         avio_seek(pb, 4, SEEK_CUR);
     case AMF_DATA_TYPE_OBJECT:
@@ -727,9 +734,9 @@
         goto skip;
     }
 
-    while ((ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
+    while (array || (ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
         AMFDataType type = avio_r8(pb);
-        if (type == AMF_DATA_TYPE_STRING && !strcmp(buf, "text")) {
+        if (type == AMF_DATA_TYPE_STRING && (array || !strcmp(buf, "text"))) {
             length = avio_rb16(pb);
             ret    = av_get_packet(pb, pkt, length);
             if (ret < 0)
@@ -749,12 +756,12 @@
 
     for (i = 0; i < s->nb_streams; i++) {
         st = s->streams[i];
-        if (st->codec->codec_type == AVMEDIA_TYPE_DATA)
+        if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
             break;
     }
 
     if (i == s->nb_streams) {
-        st = create_stream(s, AVMEDIA_TYPE_DATA);
+        st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
         if (!st)
             return AVERROR(ENOMEM);
         st->codec->codec_id = AV_CODEC_ID_TEXT;
@@ -830,10 +837,17 @@
                 goto skip;
         } else if (type == FLV_TAG_TYPE_META) {
             stream_type=FLV_STREAM_TYPE_DATA;
-            if (size > 13 + 1 + 4 && dts == 0) { // Header-type metadata stuff
+            if (size > 13 + 1 + 4) { // Header-type metadata stuff
+                int type;
                 meta_pos = avio_tell(s->pb);
-                if (flv_read_metabody(s, next) <= 0) {
+                type = flv_read_metabody(s, next);
+                if (type == 0 && dts == 0 || type < 0) {
                     goto skip;
+                } else if (type == TYPE_ONTEXTDATA) {
+                    avpriv_request_sample(s, "OnTextData packet");
+                    return flv_data_packet(s, pkt, dts, next);
+                } else if (type == TYPE_ONCAPTION) {
+                    return flv_data_packet(s, pkt, dts, next);
                 }
                 avio_seek(s->pb, meta_pos, SEEK_SET);
             }
@@ -862,12 +876,12 @@
                     (s->video_codec_id || flv_same_video_codec(st->codec, flags)))
                     break;
             } else if (stream_type == FLV_STREAM_TYPE_DATA) {
-                if (st->codec->codec_type == AVMEDIA_TYPE_DATA)
+                if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
                     break;
             }
         }
         if (i == s->nb_streams) {
-            static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_DATA};
+            static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_SUBTITLE};
             av_log(s, AV_LOG_WARNING, "Stream discovered after head already parsed\n");
             st = create_stream(s, stream_types[stream_type]);
             if (!st)
@@ -950,6 +964,8 @@
         }
     } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
         size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
+    } else if (stream_type == FLV_STREAM_TYPE_DATA) {
+        st->codec->codec_id = AV_CODEC_ID_TEXT;
     }
 
     if (st->codec->codec_id == AV_CODEC_ID_AAC ||
diff --git a/libavformat/flvenc.c b/libavformat/flvenc.c
index 7d3a0ca..e4717ca 100644
--- a/libavformat/flvenc.c
+++ b/libavformat/flvenc.c
@@ -325,6 +325,17 @@
     avio_wb32(pb, data_size + 11);
 }
 
+static int unsupported_codec(AVFormatContext *s,
+                             const char* type, int codec_id)
+{
+    const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
+    av_log(s, AV_LOG_ERROR,
+           "%s codec %s not compatible with flv\n",
+            type,
+            desc ? desc->name : "unknown");
+    return AVERROR(ENOSYS);
+}
+
 static int flv_write_header(AVFormatContext *s)
 {
     int i;
@@ -347,11 +358,9 @@
                 return AVERROR(EINVAL);
             }
             flv->video_enc = enc;
-            if (enc->codec_tag == 0) {
-                av_log(s, AV_LOG_ERROR, "Video codec '%s' for stream %d is not compatible with FLV\n",
-                       avcodec_get_name(enc->codec_id), i);
-                return AVERROR(EINVAL);
-            }
+            if (!ff_codec_get_tag(flv_video_codec_ids, enc->codec_id))
+                return unsupported_codec(s, "Video", enc->codec_id);
+
             if (enc->codec_id == AV_CODEC_ID_MPEG4 ||
                 enc->codec_id == AV_CODEC_ID_H263) {
                 int error = s->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL;
@@ -376,17 +385,14 @@
             }
             flv->audio_enc = enc;
             if (get_audio_flags(s, enc) < 0)
-                return AVERROR_INVALIDDATA;
+                return unsupported_codec(s, "Audio", enc->codec_id);
             if (enc->codec_id == AV_CODEC_ID_PCM_S16BE)
                 av_log(s, AV_LOG_WARNING,
                        "16-bit big-endian audio in flv is valid but most likely unplayable (hardware dependent); use s16le\n");
             break;
         case AVMEDIA_TYPE_DATA:
-            if (enc->codec_id != AV_CODEC_ID_TEXT && enc->codec_id != AV_CODEC_ID_NONE) {
-                av_log(s, AV_LOG_ERROR, "Data codec '%s' for stream %d is not compatible with FLV\n",
-                       avcodec_get_name(enc->codec_id), i);
-                return AVERROR_INVALIDDATA;
-            }
+            if (enc->codec_id != AV_CODEC_ID_TEXT && enc->codec_id != AV_CODEC_ID_NONE)
+                return unsupported_codec(s, "Data", enc->codec_id);
             flv->data_enc = enc;
             break;
         case AVMEDIA_TYPE_SUBTITLE:
@@ -536,13 +542,7 @@
     case AVMEDIA_TYPE_VIDEO:
         avio_w8(pb, FLV_TAG_TYPE_VIDEO);
 
-        flags = enc->codec_tag;
-        if (flags == 0) {
-            av_log(s, AV_LOG_ERROR,
-                   "Video codec '%s' is not compatible with FLV\n",
-                   avcodec_get_name(enc->codec_id));
-            return AVERROR(EINVAL);
-        }
+        flags = ff_codec_get_tag(flv_video_codec_ids, enc->codec_id);
 
         flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER;
         break;
diff --git a/libavformat/gif.c b/libavformat/gif.c
index e817121..e5d558d 100644
--- a/libavformat/gif.c
+++ b/libavformat/gif.c
@@ -28,13 +28,34 @@
 #include "libavutil/log.h"
 #include "libavutil/opt.h"
 
-static int gif_image_write_header(AVFormatContext *s, int width, int height,
+/* XXX: random value that shouldn't be taken into effect if there is no
+ * transparent color in the palette (the transparency bit will be set to 0) */
+#define DEFAULT_TRANSPARENCY_INDEX 0x1f
+
+static int get_palette_transparency_index(const uint32_t *palette)
+{
+    int transparent_color_index = -1;
+    unsigned i, smallest_alpha = 0xff;
+
+    if (!palette)
+        return -1;
+
+    for (i = 0; i < AVPALETTE_COUNT; i++) {
+        const uint32_t v = palette[i];
+        if (v >> 24 < smallest_alpha) {
+            smallest_alpha = v >> 24;
+            transparent_color_index = i;
+        }
+    }
+    return smallest_alpha < 128 ? transparent_color_index : -1;
+}
+
+static int gif_image_write_header(AVIOContext *pb, const AVCodecContext *avctx,
                                   int loop_count, uint32_t *palette)
 {
-    AVIOContext *pb = s->pb;
-    AVRational sar = s->streams[0]->codec->sample_aspect_ratio;
     int i;
     int64_t aspect = 0;
+    const AVRational sar = avctx->sample_aspect_ratio;
 
     if (sar.num > 0 && sar.den > 0) {
         aspect = sar.num * 64LL / sar.den - 15;
@@ -44,12 +65,14 @@
 
     avio_write(pb, "GIF", 3);
     avio_write(pb, "89a", 3);
-    avio_wl16(pb, width);
-    avio_wl16(pb, height);
+    avio_wl16(pb, avctx->width);
+    avio_wl16(pb, avctx->height);
 
     if (palette) {
+        const int bcid = get_palette_transparency_index(palette);
+
         avio_w8(pb, 0xf7); /* flags: global clut, 256 entries */
-        avio_w8(pb, 0x1f); /* background color index */
+        avio_w8(pb, bcid < 0 ? DEFAULT_TRANSPARENCY_INDEX : bcid); /* background color index */
         avio_w8(pb, aspect);
         for (i = 0; i < 256; i++) {
             const uint32_t v = palette[i] & 0xffffff;
@@ -74,10 +97,11 @@
         avio_w8(pb, 0x00); /* Data Sub-block Terminator */
     }
 
+    avio_flush(pb);
     return 0;
 }
 
-typedef struct {
+typedef struct GIFContext {
     AVClass *class;
     int loop;
     int last_delay;
@@ -89,7 +113,6 @@
 {
     GIFContext *gif = s->priv_data;
     AVCodecContext *video_enc;
-    int width, height;
     uint32_t palette[AVPALETTE_COUNT];
 
     if (s->nb_streams != 1 ||
@@ -101,27 +124,24 @@
     }
 
     video_enc = s->streams[0]->codec;
-    width  = video_enc->width;
-    height = video_enc->height;
 
     avpriv_set_pts_info(s->streams[0], 64, 1, 100);
     if (avpriv_set_systematic_pal2(palette, video_enc->pix_fmt) < 0) {
         av_assert0(video_enc->pix_fmt == AV_PIX_FMT_PAL8);
-        gif_image_write_header(s, width, height, gif->loop, NULL);
+        /* delay header writing: we wait for the first palette to put it
+         * globally */
     } else {
-        gif_image_write_header(s, width, height, gif->loop, palette);
+        gif_image_write_header(s->pb, video_enc, gif->loop, palette);
     }
 
-    avio_flush(s->pb);
     return 0;
 }
 
 static int flush_packet(AVFormatContext *s, AVPacket *new)
 {
     GIFContext *gif = s->priv_data;
-    int size;
+    int size, bcid;
     AVIOContext *pb = s->pb;
-    uint8_t flags = 0x4, transparent_color_index = 0x1f;
     const uint32_t *palette;
     AVPacket *pkt = gif->prev_pkt;
 
@@ -135,19 +155,7 @@
         av_log(s, AV_LOG_ERROR, "Invalid palette extradata\n");
         return AVERROR_INVALIDDATA;
     }
-    if (palette) {
-        unsigned i, smallest_alpha = 0xff;
-
-        for (i = 0; i < AVPALETTE_COUNT; i++) {
-            const uint32_t v = palette[i];
-            if (v >> 24 < smallest_alpha) {
-                smallest_alpha = v >> 24;
-                transparent_color_index = i;
-            }
-        }
-        if (smallest_alpha < 128)
-            flags |= 0x1; /* Transparent Color Flag */
-    }
+    bcid = get_palette_transparency_index(palette);
 
     if (new && new->pts != AV_NOPTS_VALUE)
         gif->duration = av_clip_uint16(new->pts - gif->prev_pkt->pts);
@@ -158,9 +166,9 @@
     avio_w8(pb, 0x21);
     avio_w8(pb, 0xf9);
     avio_w8(pb, 0x04); /* block size */
-    avio_w8(pb, flags);
+    avio_w8(pb, 1<<2 | (bcid >= 0));
     avio_wl16(pb, gif->duration);
-    avio_w8(pb, transparent_color_index);
+    avio_w8(pb, bcid < 0 ? DEFAULT_TRANSPARENCY_INDEX : bcid);
     avio_w8(pb, 0x00);
 
     avio_write(pb, pkt->data, pkt->size);
@@ -175,11 +183,29 @@
 static int gif_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     GIFContext *gif = s->priv_data;
+    const AVCodecContext *video_enc = s->streams[0]->codec;
 
     if (!gif->prev_pkt) {
         gif->prev_pkt = av_malloc(sizeof(*gif->prev_pkt));
         if (!gif->prev_pkt)
             return AVERROR(ENOMEM);
+
+        /* Write the first palette as global palette */
+        if (video_enc->pix_fmt == AV_PIX_FMT_PAL8) {
+            int size;
+            void *palette = av_packet_get_side_data(pkt, AV_PKT_DATA_PALETTE, &size);
+
+            if (!palette) {
+                av_log(s, AV_LOG_ERROR, "PAL8 packet is missing palette in extradata\n");
+                return AVERROR_INVALIDDATA;
+            }
+            if (size != AVPALETTE_SIZE) {
+                av_log(s, AV_LOG_ERROR, "Invalid palette extradata\n");
+                return AVERROR_INVALIDDATA;
+            }
+            gif_image_write_header(s->pb, video_enc, gif->loop, palette);
+        }
+
         return av_copy_packet(gif->prev_pkt, pkt);
     }
     return flush_packet(s, pkt);
diff --git a/libavformat/gopher.c b/libavformat/gopher.c
index 9dc155a..a5340d2 100644
--- a/libavformat/gopher.c
+++ b/libavformat/gopher.c
@@ -28,7 +28,7 @@
 #include "network.h"
 #include "url.h"
 
-typedef struct {
+typedef struct GopherContext {
     URLContext *hd;
 } GopherContext;
 
diff --git a/libavformat/gsmdec.c b/libavformat/gsmdec.c
index dbe557b..a9865db 100644
--- a/libavformat/gsmdec.c
+++ b/libavformat/gsmdec.c
@@ -29,7 +29,7 @@
 #define GSM_BLOCK_SAMPLES 160
 #define GSM_SAMPLE_RATE   8000
 
-typedef struct {
+typedef struct GSMDemuxerContext {
     AVClass *class;
     int sample_rate;
 } GSMDemuxerContext;
diff --git a/libavformat/gxf.c b/libavformat/gxf.c
index 6c624f0..d9b629d 100644
--- a/libavformat/gxf.c
+++ b/libavformat/gxf.c
@@ -560,7 +560,7 @@
 }
 
 static int gxf_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) {
-    int res = 0;
+    int64_t res = 0;
     uint64_t pos;
     uint64_t maxlen = 100 * 1024 * 1024;
     AVStream *st = s->streams[0];
diff --git a/libavformat/hls.c b/libavformat/hls.c
index f17b826..af890bd 100644
--- a/libavformat/hls.c
+++ b/libavformat/hls.c
@@ -62,6 +62,7 @@
 enum KeyType {
     KEY_NONE,
     KEY_AES_128,
+    KEY_SAMPLE_AES
 };
 
 struct segment {
@@ -329,7 +330,7 @@
 
 struct key_info {
      char uri[MAX_URL_SIZE];
-     char method[10];
+     char method[11];
      char iv[35];
 };
 
@@ -556,6 +557,8 @@
             has_iv = 0;
             if (!strcmp(info.method, "AES-128"))
                 key_type = KEY_AES_128;
+            if (!strcmp(info.method, "SAMPLE-AES"))
+                key_type = KEY_SAMPLE_AES;
             if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
                 ff_hex_to_data(iv, info.iv + 2);
                 has_iv = 1;
@@ -900,6 +903,14 @@
         pls->is_id3_timestamped = (pls->id3_mpegts_timestamp != AV_NOPTS_VALUE);
 }
 
+static void update_options(char **dest, const char *name, void *src)
+{
+    av_freep(dest);
+    av_opt_get(src, name, 0, (uint8_t**)dest);
+    if (*dest && !strlen(*dest))
+        av_freep(dest);
+}
+
 static int open_input(HLSContext *c, struct playlist *pls)
 {
     AVDictionary *opts = NULL;
@@ -941,6 +952,8 @@
                     av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
                            seg->key);
                 }
+                update_options(&c->cookies, "cookies", uc->priv_data);
+                av_dict_set(&opts, "cookies", c->cookies, 0);
                 ffurl_close(uc);
             } else {
                 av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
@@ -967,6 +980,10 @@
             goto cleanup;
         }
         ret = 0;
+    } else if (seg->key_type == KEY_SAMPLE_AES) {
+        av_log(pls->parent, AV_LOG_ERROR,
+               "SAMPLE-AES encryption is not supported yet\n");
+        ret = AVERROR_PATCHWELCOME;
     }
     else
       ret = AVERROR(ENOSYS);
@@ -1245,22 +1262,13 @@
     // if the URL context is good, read important options we must broker later
     if (u && u->prot->priv_data_class) {
         // get the previous user agent & set back to null if string size is zero
-        av_freep(&c->user_agent);
-        av_opt_get(u->priv_data, "user-agent", 0, (uint8_t**)&(c->user_agent));
-        if (c->user_agent && !strlen(c->user_agent))
-            av_freep(&c->user_agent);
+        update_options(&c->user_agent, "user-agent", u->priv_data);
 
         // get the previous cookies & set back to null if string size is zero
-        av_freep(&c->cookies);
-        av_opt_get(u->priv_data, "cookies", 0, (uint8_t**)&(c->cookies));
-        if (c->cookies && !strlen(c->cookies))
-            av_freep(&c->cookies);
+        update_options(&c->cookies, "cookies", u->priv_data);
 
         // get the previous headers & set back to null if string size is zero
-        av_freep(&c->headers);
-        av_opt_get(u->priv_data, "headers", 0, (uint8_t**)&(c->headers));
-        if (c->headers && !strlen(c->headers))
-            av_freep(&c->headers);
+        update_options(&c->headers, "headers", u->priv_data);
     }
 
     if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
@@ -1313,14 +1321,14 @@
         struct playlist *pls = c->playlists[i];
         AVInputFormat *in_fmt = NULL;
 
-        if (pls->n_segments == 0)
-            continue;
-
         if (!(pls->ctx = avformat_alloc_context())) {
             ret = AVERROR(ENOMEM);
             goto fail;
         }
 
+        if (pls->n_segments == 0)
+            continue;
+
         pls->index  = i;
         pls->needed = 1;
         pls->parent = s;
diff --git a/libavformat/hlsenc.c b/libavformat/hlsenc.c
index 29bf30e..7885351 100644
--- a/libavformat/hlsenc.c
+++ b/libavformat/hlsenc.c
@@ -85,8 +85,6 @@
     char *baseurl;
     char *format_options_str;
     AVDictionary *format_options;
-
-    AVIOContext *pb;
 } HLSContext;
 
 static int hls_delete_old_segments(HLSContext *hls) {
@@ -243,10 +241,19 @@
     HLSSegment *en;
     int target_duration = 0;
     int ret = 0;
+    AVIOContext *out = NULL;
+    char temp_filename[1024];
     int64_t sequence = FFMAX(hls->start_sequence, hls->sequence - hls->nb_entries);
     int version = hls->flags & HLS_SINGLE_FILE ? 4 : 3;
+    const char *proto = avio_find_protocol_name(s->filename);
+    int use_rename = proto && !strcmp(proto, "file");
+    static unsigned warned_non_file;
 
-    if ((ret = avio_open2(&hls->pb, s->filename, AVIO_FLAG_WRITE,
+    if (!use_rename && !warned_non_file++)
+        av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporarly partial files\n");
+
+    snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->filename);
+    if ((ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE,
                           &s->interrupt_callback, NULL)) < 0)
         goto fail;
 
@@ -255,32 +262,34 @@
             target_duration = ceil(en->duration);
     }
 
-    avio_printf(hls->pb, "#EXTM3U\n");
-    avio_printf(hls->pb, "#EXT-X-VERSION:%d\n", version);
+    avio_printf(out, "#EXTM3U\n");
+    avio_printf(out, "#EXT-X-VERSION:%d\n", version);
     if (hls->allowcache == 0 || hls->allowcache == 1) {
-        avio_printf(hls->pb, "#EXT-X-ALLOW-CACHE:%s\n", hls->allowcache == 0 ? "NO" : "YES");
+        avio_printf(out, "#EXT-X-ALLOW-CACHE:%s\n", hls->allowcache == 0 ? "NO" : "YES");
     }
-    avio_printf(hls->pb, "#EXT-X-TARGETDURATION:%d\n", target_duration);
-    avio_printf(hls->pb, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
+    avio_printf(out, "#EXT-X-TARGETDURATION:%d\n", target_duration);
+    avio_printf(out, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
 
     av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%"PRId64"\n",
            sequence);
 
     for (en = hls->segments; en; en = en->next) {
-        avio_printf(hls->pb, "#EXTINF:%f,\n", en->duration);
+        avio_printf(out, "#EXTINF:%f,\n", en->duration);
         if (hls->flags & HLS_SINGLE_FILE)
-             avio_printf(hls->pb, "#EXT-X-BYTERANGE:%"PRIi64"@%"PRIi64"\n",
+             avio_printf(out, "#EXT-X-BYTERANGE:%"PRIi64"@%"PRIi64"\n",
                          en->size, en->pos);
         if (hls->baseurl)
-            avio_printf(hls->pb, "%s", hls->baseurl);
-        avio_printf(hls->pb, "%s\n", en->filename);
+            avio_printf(out, "%s", hls->baseurl);
+        avio_printf(out, "%s\n", en->filename);
     }
 
     if (last)
-        avio_printf(hls->pb, "#EXT-X-ENDLIST\n");
+        avio_printf(out, "#EXT-X-ENDLIST\n");
 
 fail:
-    avio_closep(&hls->pb);
+    avio_closep(&out);
+    if (ret >= 0 && use_rename)
+        ff_rename(temp_filename, s->filename, s);
     return ret;
 }
 
@@ -486,7 +495,6 @@
 
     hls_free_segments(hls->segments);
     hls_free_segments(hls->old_segments);
-    avio_closep(&hls->pb);
     return 0;
 }
 
diff --git a/libavformat/http.c b/libavformat/http.c
index b9e1870..da3c9be 100644
--- a/libavformat/http.c
+++ b/libavformat/http.c
@@ -45,7 +45,7 @@
 #define BUFFER_SIZE   MAX_URL_SIZE
 #define MAX_REDIRECTS 8
 
-typedef struct {
+typedef struct HTTPContext {
     const AVClass *class;
     URLContext *hd;
     unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
@@ -77,6 +77,8 @@
     int is_akamai;
     int is_mediagateway;
     char *cookies;          ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
+    /* A dictionary containing cookies keyed by cookie name */
+    AVDictionary *cookie_dict;
     int icy;
     /* how much data was read since the last ICY metadata packet */
     int icy_data_read;
@@ -93,6 +95,7 @@
     AVDictionary *chained_options;
     int send_expect_100;
     char *method;
+    int reconnect;
 } HTTPContext;
 
 #define OFFSET(x) offsetof(HTTPContext, x)
@@ -123,6 +126,7 @@
     { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
     { "end_offset", "try to limit the request to bytes preceding this offset", OFFSET(end_off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
     { "method", "Override the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
+    { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D },
     { NULL }
 };
 
@@ -464,6 +468,43 @@
     return 0;
 }
 
+static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
+{
+    char *eql, *name;
+
+    // duplicate the cookie name (dict will dupe the value)
+    if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
+    if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
+
+    // add the cookie to the dictionary
+    av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
+
+    return 0;
+}
+
+static int cookie_string(AVDictionary *dict, char **cookies)
+{
+    AVDictionaryEntry *e = NULL;
+    int len = 1;
+
+    // determine how much memory is needed for the cookies string
+    while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
+        len += strlen(e->key) + strlen(e->value) + 1;
+
+    // reallocate the cookies
+    e = NULL;
+    if (*cookies) av_free(*cookies);
+    *cookies = av_malloc(len);
+    if (!cookies) return AVERROR(ENOMEM);
+    *cookies[0] = '\0';
+
+    // write out the cookies
+    while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
+        av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
+
+    return 0;
+}
+
 static int process_line(URLContext *h, char *line, int line_count,
                         int *new_location)
 {
@@ -535,19 +576,8 @@
             av_free(s->mime_type);
             s->mime_type = av_strdup(p);
         } else if (!av_strcasecmp(tag, "Set-Cookie")) {
-            if (!s->cookies) {
-                if (!(s->cookies = av_strdup(p)))
-                    return AVERROR(ENOMEM);
-            } else {
-                char *tmp = s->cookies;
-                size_t str_size = strlen(tmp) + strlen(p) + 2;
-                if (!(s->cookies = av_malloc(str_size))) {
-                    s->cookies = tmp;
-                    return AVERROR(ENOMEM);
-                }
-                snprintf(s->cookies, str_size, "%s\n%s", tmp, p);
-                av_free(tmp);
-            }
+            if (parse_cookie(s, p, &s->cookie_dict))
+                av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
         } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
             s->icy_metaint = strtoll(p, NULL, 10);
         } else if (!av_strncasecmp(tag, "Icy-", 4)) {
@@ -578,12 +608,19 @@
 
     if (!set_cookies) return AVERROR(EINVAL);
 
+    // destroy any cookies in the dictionary.
+    av_dict_free(&s->cookie_dict);
+
     *cookies = NULL;
     while ((cookie = av_strtok(set_cookies, "\n", &next))) {
         int domain_offset = 0;
         char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
         set_cookies = NULL;
 
+        // store the cookie in a dict in case it is updated in the response
+        if (parse_cookie(s, cookie, &s->cookie_dict))
+            av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
+
         while ((param = av_strtok(cookie, "; ", &next_param))) {
             if (cookie) {
                 // first key-value pair is the actual cookie value
@@ -691,6 +728,10 @@
     if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
         h->is_streamed = 1; /* we can in fact _not_ seek */
 
+    // add any new cookies into the existing cookie string
+    cookie_string(s->cookie_dict, &s->cookies);
+    av_dict_free(&s->cookie_dict);
+
     return err;
 }
 
@@ -908,10 +949,12 @@
 }
 #endif /* CONFIG_ZLIB */
 
+static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
+
 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
 {
     HTTPContext *s = h->priv_data;
-    int err, new_location;
+    int err, new_location, read_ret, seek_ret;
 
     if (!s->hd)
         return AVERROR_EOF;
@@ -945,7 +988,19 @@
     if (s->compressed)
         return http_buf_read_compressed(h, buf, size);
 #endif /* CONFIG_ZLIB */
-    return http_buf_read(h, buf, size);
+    read_ret = http_buf_read(h, buf, size);
+    if (read_ret < 0 && s->reconnect && !h->is_streamed && s->filesize > 0 && s->off < s->filesize) {
+        av_log(h, AV_LOG_INFO, "Will reconnect at %"PRId64".\n", s->off);
+        seek_ret = http_seek_internal(h, s->off, SEEK_SET, 1);
+        if (seek_ret != s->off) {
+            av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRId64".\n", s->off);
+            return read_ret;
+        }
+
+        read_ret = http_buf_read(h, buf, size);
+    }
+
+    return read_ret;
 }
 
 // Like http_read_stream(), but no short reads.
@@ -1104,7 +1159,7 @@
     return ret;
 }
 
-static int64_t http_seek(URLContext *h, int64_t off, int whence)
+static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
 {
     HTTPContext *s = h->priv_data;
     URLContext *old_hd = s->hd;
@@ -1115,8 +1170,9 @@
 
     if (whence == AVSEEK_SIZE)
         return s->filesize;
-    else if ((whence == SEEK_CUR && off == 0) ||
-             (whence == SEEK_SET && off == s->off))
+    else if (!force_reconnect &&
+             ((whence == SEEK_CUR && off == 0) ||
+              (whence == SEEK_SET && off == s->off)))
         return s->off;
     else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
         return AVERROR(ENOSYS);
@@ -1151,6 +1207,11 @@
     return off;
 }
 
+static int64_t http_seek(URLContext *h, int64_t off, int whence)
+{
+    return http_seek_internal(h, off, whence, 0);
+}
+
 static int http_get_file_handle(URLContext *h)
 {
     HTTPContext *s = h->priv_data;
diff --git a/libavformat/id3v2.c b/libavformat/id3v2.c
index dae4aeb..a8273e2 100644
--- a/libavformat/id3v2.c
+++ b/libavformat/id3v2.c
@@ -265,8 +265,8 @@
     case ID3v2_ENCODING_UTF16BOM:
         if ((left -= 2) < 0) {
             av_log(s, AV_LOG_ERROR, "Cannot read BOM value, input too short\n");
-            avio_close_dyn_buf(dynbuf, dst);
-            av_freep(dst);
+            ffio_free_dyn_buf(&dynbuf);
+            *dst = NULL;
             return AVERROR_INVALIDDATA;
         }
         switch (avio_rb16(pb)) {
@@ -276,8 +276,8 @@
             break;
         default:
             av_log(s, AV_LOG_ERROR, "Incorrect BOM value\n");
-            avio_close_dyn_buf(dynbuf, dst);
-            av_freep(dst);
+            ffio_free_dyn_buf(&dynbuf);
+            *dst = NULL;
             *maxread = left;
             return AVERROR_INVALIDDATA;
         }
diff --git a/libavformat/idcin.c b/libavformat/idcin.c
index d7a46a1..4e455bf 100644
--- a/libavformat/idcin.c
+++ b/libavformat/idcin.c
@@ -359,7 +359,7 @@
     IdcinDemuxContext *idcin = s->priv_data;
 
     if (idcin->first_pkt_pos > 0) {
-        int ret = avio_seek(s->pb, idcin->first_pkt_pos, SEEK_SET);
+        int64_t ret = avio_seek(s->pb, idcin->first_pkt_pos, SEEK_SET);
         if (ret < 0)
             return ret;
         ff_update_cur_dts(s, s->streams[idcin->video_stream_index], 0);
diff --git a/libavformat/iff.c b/libavformat/iff.c
index e7c240c..7235bc1 100644
--- a/libavformat/iff.c
+++ b/libavformat/iff.c
@@ -98,7 +98,7 @@
     COMP_EXP
 } svx8_compression_type;
 
-typedef struct {
+typedef struct IffDemuxContext {
     int      is_64bit;  ///< chunk size is 64-bit
     int64_t  body_pos;
     int64_t  body_end;
diff --git a/libavformat/img2.c b/libavformat/img2.c
index d6f1244..8493a3e 100644
--- a/libavformat/img2.c
+++ b/libavformat/img2.c
@@ -23,7 +23,7 @@
 #include "libavutil/avstring.h"
 #include "internal.h"
 
-typedef struct {
+typedef struct IdStrMap {
     enum AVCodecID id;
     const char *str;
 } IdStrMap;
diff --git a/libavformat/img2.h b/libavformat/img2.h
index 58a6833..67bd7a3 100644
--- a/libavformat/img2.h
+++ b/libavformat/img2.h
@@ -30,7 +30,7 @@
 #include <glob.h>
 #endif
 
-typedef struct {
+typedef struct VideoDemuxData {
     const AVClass *class;  /**< Class for private options. */
     int img_first;
     int img_last;
diff --git a/libavformat/img2dec.c b/libavformat/img2dec.c
index 68cbefd..8c5e9d5 100644
--- a/libavformat/img2dec.c
+++ b/libavformat/img2dec.c
@@ -537,7 +537,7 @@
     { "sequence",     "select sequence 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 },
+    { "start_number", "set first number in the sequence",    OFFSET(start_number), AV_OPT_TYPE_INT,    {.i64 = 0   }, INT_MIN, 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(width),        AV_OPT_TYPE_IMAGE_SIZE, {.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 },
@@ -599,10 +599,8 @@
 
     if (!AV_RN32(b + 6)) {
         return AVPROBE_SCORE_EXTENSION + 1;
-    } else {
-        return AVPROBE_SCORE_EXTENSION / 4;
     }
-    return 0;
+    return AVPROBE_SCORE_EXTENSION / 4;
 }
 
 static int dpx_probe(AVProbeData *p)
diff --git a/libavformat/img2enc.c b/libavformat/img2enc.c
index b0bd252..f56c39e 100644
--- a/libavformat/img2enc.c
+++ b/libavformat/img2enc.c
@@ -31,7 +31,7 @@
 #include "avio_internal.h"
 #include "internal.h"
 
-typedef struct {
+typedef struct VideoMuxData {
     const AVClass *class;  /**< Class for private options. */
     int img_number;
     int is_pipe;
diff --git a/libavformat/internal.h b/libavformat/internal.h
index d56644b..76ffcc5 100644
--- a/libavformat/internal.h
+++ b/libavformat/internal.h
@@ -54,6 +54,48 @@
      */
     int nb_interleaved_streams;
 
+    /**
+     * This buffer is only needed when packets were already buffered but
+     * not decoded, for example to get the codec parameters in MPEG
+     * streams.
+     */
+    struct AVPacketList *packet_buffer;
+    struct AVPacketList *packet_buffer_end;
+
+    /* av_seek_frame() support */
+    int64_t data_offset; /**< offset of the first packet */
+
+    /**
+     * Raw packets from the demuxer, prior to parsing and decoding.
+     * This buffer is used for buffering packets until the codec can
+     * be identified, as parsing cannot be done without knowing the
+     * codec.
+     */
+    struct AVPacketList *raw_packet_buffer;
+    struct AVPacketList *raw_packet_buffer_end;
+    /**
+     * Packets split by the parser get queued here.
+     */
+    struct AVPacketList *parse_queue;
+    struct AVPacketList *parse_queue_end;
+    /**
+     * Remaining size available for raw_packet_buffer, in bytes.
+     */
+#define RAW_PACKET_BUFFER_SIZE 2500000
+    int raw_packet_buffer_remaining_size;
+
+    /**
+     * Offset to remap timestamps to be non-negative.
+     * Expressed in timebase units.
+     * @see AVStream.mux_ts_offset
+     */
+    int64_t offset;
+
+    /**
+     * Timebase for the timestamp offset.
+     */
+    AVRational offset_timebase;
+
     int inject_global_side_data;
 };
 
@@ -135,7 +177,7 @@
  * @param dst_stream the stream index within dst to write the packet to
  * @param pkt the packet to be written
  * @param src the muxer the packet originally was intended for
- * @param interleave 0->use av_write_frame, 1->av_write_interleaved_frame
+ * @param interleave 0->use av_write_frame, 1->av_interleaved_write_frame
  * @return the value av_write_frame returned
  */
 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
diff --git a/libavformat/isom.c b/libavformat/isom.c
index 68ddd32..73a221e 100644
--- a/libavformat/isom.c
+++ b/libavformat/isom.c
@@ -59,6 +59,7 @@
     { AV_CODEC_ID_AC3         , 0xA5 },
     { AV_CODEC_ID_EAC3        , 0xA6 },
     { AV_CODEC_ID_DTS         , 0xA9 }, /* mp4ra.org */
+    { AV_CODEC_ID_TSCC2       , 0xD0 }, /* non standard, camtasia uses it */
     { AV_CODEC_ID_VORBIS      , 0xDD }, /* non standard, gpac uses it */
     { AV_CODEC_ID_DVD_SUBTITLE, 0xE0 }, /* non standard, see unsupported-embedded-subs-2.mp4 */
     { AV_CODEC_ID_QCELP       , 0xE1 },
@@ -173,6 +174,7 @@
     { AV_CODEC_ID_H264, MKTAG('a', 'i', '1', '6') }, /* AVC-Intra 100M 1080i60 */
     { AV_CODEC_ID_H264, MKTAG('A', 'V', 'i', 'n') }, /* AVC-Intra with implicit SPS/PPS */
     { AV_CODEC_ID_H264, MKTAG('a', 'i', 'v', 'x') }, /* XAVC 4:2:2 10bit */
+    { AV_CODEC_ID_H264, MKTAG('r', 'v', '6', '4') }, /* X-Com Radvision */
 
     { AV_CODEC_ID_MPEG1VIDEO, MKTAG('m', '1', 'v', ' ') },
     { AV_CODEC_ID_MPEG1VIDEO, MKTAG('m', '1', 'v', '1') }, /* Apple MPEG-1 Camcorder */
diff --git a/libavformat/isom.h b/libavformat/isom.h
index d233839..5d48989 100644
--- a/libavformat/isom.h
+++ b/libavformat/isom.h
@@ -186,6 +186,7 @@
     int chapter_track;
     int use_absolute_path;
     int ignore_editlist;
+    int seek_individually;
     int64_t next_root_atom; ///< offset of the next root atom
     int export_all;
     int export_xmp;
diff --git a/libavformat/iss.c b/libavformat/iss.c
index e994531..fbde505 100644
--- a/libavformat/iss.c
+++ b/libavformat/iss.c
@@ -35,7 +35,7 @@
 #define ISS_SIG_LEN 15
 #define MAX_TOKEN_SIZE 20
 
-typedef struct {
+typedef struct IssDemuxContext {
     int packet_size;
     int sample_start_pos;
 } IssDemuxContext;
diff --git a/libavformat/jvdec.c b/libavformat/jvdec.c
index 21eb14d..64d31e0 100644
--- a/libavformat/jvdec.c
+++ b/libavformat/jvdec.c
@@ -33,14 +33,14 @@
 
 #define JV_PREAMBLE_SIZE 5
 
-typedef struct {
+typedef struct JVFrame {
     int audio_size;    /**< audio packet size (bytes) */
     int video_size;    /**< video packet size (bytes) */
     int palette_size;  /**< palette size (bytes) */
     int video_type;    /**< per-frame video compression type */
 } JVFrame;
 
-typedef struct {
+typedef struct JVDemuxContext {
     JVFrame *frames;
     enum {
         JV_AUDIO = 0,
diff --git a/libavformat/latmenc.c b/libavformat/latmenc.c
index cb79e84..17dbf33 100644
--- a/libavformat/latmenc.c
+++ b/libavformat/latmenc.c
@@ -29,7 +29,7 @@
 
 #define MAX_EXTRADATA_SIZE 1024
 
-typedef struct {
+typedef struct LATMContext {
     AVClass *av_class;
     int off;
     int channel_conf;
diff --git a/libavformat/libssh.c b/libavformat/libssh.c
index 3ec60cb..fac6114 100644
--- a/libavformat/libssh.c
+++ b/libavformat/libssh.c
@@ -55,6 +55,10 @@
         ssh_options_set(libssh->session, SSH_OPTIONS_TIMEOUT_USEC, &timeout);
     }
 
+    if (ssh_options_parse_config(libssh->session, NULL) < 0) {
+        av_log(libssh, AV_LOG_WARNING, "Could not parse the config file.\n");
+    }
+
     if (ssh_connect(libssh->session) != SSH_OK) {
         av_log(libssh, AV_LOG_ERROR, "Connection failed: %s\n", ssh_get_error(libssh->session));
         return AVERROR(EIO);
@@ -187,7 +191,7 @@
 {
     LIBSSHContext *libssh = h->priv_data;
     char proto[10], path[MAX_URL_SIZE], hostname[1024], credencials[1024];
-    int port = 22, ret;
+    int port, ret;
     const char *user = NULL, *pass = NULL;
     char *end = NULL;
 
@@ -198,8 +202,9 @@
                  path, sizeof(path),
                  url);
 
-    if (port <= 0 || port > 65535)
-        port = 22;
+    // a port of 0 will use a port from ~/.ssh/config or the default value 22
+    if (port < 0 || port > 65535)
+        port = 0;
 
     if ((ret = libssh_create_ssh_session(libssh, hostname, port)) < 0)
         goto fail;
diff --git a/libavformat/lxfdec.c b/libavformat/lxfdec.c
index fb37da7..ce5da82 100644
--- a/libavformat/lxfdec.c
+++ b/libavformat/lxfdec.c
@@ -46,7 +46,7 @@
     { AV_CODEC_ID_NONE,        0 },
 };
 
-typedef struct {
+typedef struct LXFDemuxContext {
     int channels;                       ///< number of audio channels. zero means no audio
     int frame_number;                   ///< current video frame
     uint32_t video_format, packet_type, extended_size;
diff --git a/libavformat/matroskadec.c b/libavformat/matroskadec.c
index 1fbc160..527ce5a 100644
--- a/libavformat/matroskadec.c
+++ b/libavformat/matroskadec.c
@@ -77,6 +77,7 @@
     EBML_UTF8,
     EBML_BIN,
     EBML_NEST,
+    EBML_LEVEL1,
     EBML_PASS,
     EBML_STOP,
     EBML_SINT,
@@ -96,18 +97,18 @@
     } def;
 } EbmlSyntax;
 
-typedef struct {
+typedef struct EbmlList {
     int nb_elem;
     void *elem;
 } EbmlList;
 
-typedef struct {
+typedef struct EbmlBin {
     int      size;
     uint8_t *data;
     int64_t  pos;
 } EbmlBin;
 
-typedef struct {
+typedef struct Ebml {
     uint64_t version;
     uint64_t max_size;
     uint64_t id_length;
@@ -115,24 +116,24 @@
     uint64_t doctype_version;
 } Ebml;
 
-typedef struct {
+typedef struct MatroskaTrackCompression {
     uint64_t algo;
     EbmlBin  settings;
 } MatroskaTrackCompression;
 
-typedef struct {
+typedef struct MatroskaTrackEncryption {
     uint64_t algo;
     EbmlBin  key_id;
 } MatroskaTrackEncryption;
 
-typedef struct {
+typedef struct MatroskaTrackEncoding {
     uint64_t scope;
     uint64_t type;
     MatroskaTrackCompression compression;
     MatroskaTrackEncryption encryption;
 } MatroskaTrackEncoding;
 
-typedef struct {
+typedef struct MatroskaTrackVideo {
     double   frame_rate;
     uint64_t display_width;
     uint64_t display_height;
@@ -143,7 +144,7 @@
     uint64_t alpha_mode;
 } MatroskaTrackVideo;
 
-typedef struct {
+typedef struct MatroskaTrackAudio {
     double   samplerate;
     double   out_samplerate;
     uint64_t bitdepth;
@@ -160,16 +161,16 @@
     uint8_t *buf;
 } MatroskaTrackAudio;
 
-typedef struct {
+typedef struct MatroskaTrackPlane {
     uint64_t uid;
     uint64_t type;
 } MatroskaTrackPlane;
 
-typedef struct {
+typedef struct MatroskaTrackOperation {
     EbmlList combine_planes;
 } MatroskaTrackOperation;
 
-typedef struct {
+typedef struct MatroskaTrack {
     uint64_t num;
     uint64_t uid;
     uint64_t type;
@@ -194,7 +195,7 @@
     uint64_t max_block_additional_id;
 } MatroskaTrack;
 
-typedef struct {
+typedef struct MatroskaAttachment {
     uint64_t uid;
     char *filename;
     char *mime;
@@ -203,7 +204,7 @@
     AVStream *stream;
 } MatroskaAttachment;
 
-typedef struct {
+typedef struct MatroskaChapter {
     uint64_t start;
     uint64_t end;
     uint64_t uid;
@@ -212,17 +213,17 @@
     AVChapter *chapter;
 } MatroskaChapter;
 
-typedef struct {
+typedef struct MatroskaIndexPos {
     uint64_t track;
     uint64_t pos;
 } MatroskaIndexPos;
 
-typedef struct {
+typedef struct MatroskaIndex {
     uint64_t time;
     EbmlList pos;
 } MatroskaIndex;
 
-typedef struct {
+typedef struct MatroskaTag {
     char *name;
     char *string;
     char *lang;
@@ -230,7 +231,7 @@
     EbmlList sub;
 } MatroskaTag;
 
-typedef struct {
+typedef struct MatroskaTagTarget {
     char    *type;
     uint64_t typevalue;
     uint64_t trackuid;
@@ -238,27 +239,33 @@
     uint64_t attachuid;
 } MatroskaTagTarget;
 
-typedef struct {
+typedef struct MatroskaTags {
     MatroskaTagTarget target;
     EbmlList tag;
 } MatroskaTags;
 
-typedef struct {
+typedef struct MatroskaSeekhead {
     uint64_t id;
     uint64_t pos;
 } MatroskaSeekhead;
 
-typedef struct {
+typedef struct MatroskaLevel {
     uint64_t start;
     uint64_t length;
 } MatroskaLevel;
 
-typedef struct {
+typedef struct MatroskaCluster {
     uint64_t timecode;
     EbmlList blocks;
 } MatroskaCluster;
 
-typedef struct {
+typedef struct MatroskaLevel1Element {
+    uint64_t id;
+    uint64_t pos;
+    int parsed;
+} MatroskaLevel1Element;
+
+typedef struct MatroskaDemuxContext {
     AVFormatContext *ctx;
 
     /* EBML stuff */
@@ -296,6 +303,10 @@
     /* File has a CUES element, but we defer parsing until it is needed. */
     int cues_parsing_deferred;
 
+    /* Level1 elements and whether they were read yet */
+    MatroskaLevel1Element level1_elems[64];
+    int num_level1_elems;
+
     int current_cluster_num_blocks;
     int64_t current_cluster_pos;
     MatroskaCluster current_cluster;
@@ -304,7 +315,7 @@
     int contains_ssa;
 } MatroskaDemuxContext;
 
-typedef struct {
+typedef struct MatroskaBlock {
     uint64_t duration;
     int64_t  reference;
     uint64_t non_simple;
@@ -557,13 +568,13 @@
 };
 
 static EbmlSyntax matroska_segment[] = {
-    { MATROSKA_ID_INFO,        EBML_NEST, 0, 0, { .n = matroska_info } },
-    { MATROSKA_ID_TRACKS,      EBML_NEST, 0, 0, { .n = matroska_tracks } },
-    { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, { .n = matroska_attachments } },
-    { MATROSKA_ID_CHAPTERS,    EBML_NEST, 0, 0, { .n = matroska_chapters } },
-    { MATROSKA_ID_CUES,        EBML_NEST, 0, 0, { .n = matroska_index } },
-    { MATROSKA_ID_TAGS,        EBML_NEST, 0, 0, { .n = matroska_tags } },
-    { MATROSKA_ID_SEEKHEAD,    EBML_NEST, 0, 0, { .n = matroska_seekhead } },
+    { MATROSKA_ID_INFO,        EBML_LEVEL1, 0, 0, { .n = matroska_info } },
+    { MATROSKA_ID_TRACKS,      EBML_LEVEL1, 0, 0, { .n = matroska_tracks } },
+    { MATROSKA_ID_ATTACHMENTS, EBML_LEVEL1, 0, 0, { .n = matroska_attachments } },
+    { MATROSKA_ID_CHAPTERS,    EBML_LEVEL1, 0, 0, { .n = matroska_chapters } },
+    { MATROSKA_ID_CUES,        EBML_LEVEL1, 0, 0, { .n = matroska_index } },
+    { MATROSKA_ID_TAGS,        EBML_LEVEL1, 0, 0, { .n = matroska_tags } },
+    { MATROSKA_ID_SEEKHEAD,    EBML_LEVEL1, 0, 0, { .n = matroska_seekhead } },
     { MATROSKA_ID_CLUSTER,     EBML_STOP },
     { 0 }
 };
@@ -933,9 +944,7 @@
         matroska->levels[matroska->num_levels - 1].length == 0xffffffffffffff)
         return 0;  // we reached the end of an unknown size cluster
     if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
-        av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%"PRIX32"\n", id);
-        if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
-            return AVERROR_INVALIDDATA;
+        av_log(matroska->ctx, AV_LOG_DEBUG, "Unknown entry 0x%"PRIX32"\n", id);
     }
     return ebml_parse_elem(matroska, &syntax[i], data);
 }
@@ -984,6 +993,42 @@
     return res;
 }
 
+/*
+ * Allocate and return the entry for the level1 element with the given ID. If
+ * an entry already exists, return the existing entry.
+ */
+static MatroskaLevel1Element *matroska_find_level1_elem(MatroskaDemuxContext *matroska,
+                                                        uint32_t id)
+{
+    int i;
+    MatroskaLevel1Element *elem;
+
+    // Some files link to all clusters; useless.
+    if (id == MATROSKA_ID_CLUSTER)
+        return NULL;
+
+    // There can be multiple seekheads.
+    if (id != MATROSKA_ID_SEEKHEAD) {
+        for (i = 0; i < matroska->num_level1_elems; i++) {
+            if (matroska->level1_elems[i].id == id)
+                return &matroska->level1_elems[i];
+        }
+    }
+
+    // Only a completely broken file would have more elements.
+    // It also provides a low-effort way to escape from circular seekheads
+    // (every iteration will add a level1 entry).
+    if (matroska->num_level1_elems >= FF_ARRAY_ELEMS(matroska->level1_elems)) {
+        av_log(matroska->ctx, AV_LOG_ERROR, "Too many level1 elements or circular seekheads.\n");
+        return NULL;
+    }
+
+    elem = &matroska->level1_elems[matroska->num_level1_elems++];
+    *elem = (MatroskaLevel1Element){.id = id};
+
+    return elem;
+}
+
 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
                            EbmlSyntax *syntax, void *data)
 {
@@ -1002,6 +1047,7 @@
     uint64_t length;
     int res;
     void *newelem;
+    MatroskaLevel1Element *level1_elem;
 
     data = (char *) data + syntax->data_offset;
     if (syntax->list_elem_size) {
@@ -1044,11 +1090,20 @@
     case EBML_BIN:
         res = ebml_read_binary(pb, length, data);
         break;
+    case EBML_LEVEL1:
     case EBML_NEST:
         if ((res = ebml_read_master(matroska, length)) < 0)
             return res;
         if (id == MATROSKA_ID_SEGMENT)
             matroska->segment_start = avio_tell(matroska->ctx->pb);
+        if (id == MATROSKA_ID_CUES)
+            matroska->cues_parsing_deferred = 0;
+        if (syntax->type == EBML_LEVEL1 &&
+            (level1_elem = matroska_find_level1_elem(matroska, syntax->id))) {
+            if (level1_elem->parsed)
+                av_log(matroska->ctx, AV_LOG_ERROR, "Duplicate element\n");
+            level1_elem->parsed = 1;
+        }
         return ebml_parse_nest(matroska, syntax->def.n, data);
     case EBML_PASS:
         return ebml_parse_id(matroska, syntax->def.n, id, data);
@@ -1079,6 +1134,7 @@
         case EBML_BIN:
             av_freep(&((EbmlBin *) data_off)->data);
             break;
+        case EBML_LEVEL1:
         case EBML_NEST:
             if (syntax[i].list_elem_size) {
                 EbmlList *list = data_off;
@@ -1364,24 +1420,17 @@
 }
 
 static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska,
-                                         int idx)
+                                         uint64_t pos)
 {
-    EbmlList *seekhead_list = &matroska->seekhead;
     uint32_t level_up       = matroska->level_up;
     uint32_t saved_id       = matroska->current_id;
-    MatroskaSeekhead *seekhead = seekhead_list->elem;
     int64_t before_pos = avio_tell(matroska->ctx->pb);
     MatroskaLevel level;
     int64_t offset;
     int ret = 0;
 
-    if (idx >= seekhead_list->nb_elem            ||
-        seekhead[idx].id == MATROSKA_ID_SEEKHEAD ||
-        seekhead[idx].id == MATROSKA_ID_CLUSTER)
-        return 0;
-
     /* seek */
-    offset = seekhead[idx].pos + matroska->segment_start;
+    offset = pos + matroska->segment_start;
     if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
         /* We don't want to lose our seekhead level, so we add
          * a dummy. This is a crude hack. */
@@ -1418,37 +1467,34 @@
 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
 {
     EbmlList *seekhead_list = &matroska->seekhead;
-    int64_t before_pos = avio_tell(matroska->ctx->pb);
     int i;
-    int nb_elem;
 
     // we should not do any seeking in the streaming case
-    if (!matroska->ctx->pb->seekable ||
-        (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
+    if (!matroska->ctx->pb->seekable)
         return;
 
-    // do not read entries that are added while parsing seekhead entries
-    nb_elem = seekhead_list->nb_elem;
+    for (i = 0; i < seekhead_list->nb_elem; i++) {
+        MatroskaSeekhead *seekheads = seekhead_list->elem;
+        uint32_t id  = seekheads[i].id;
+        uint64_t pos = seekheads[i].pos;
 
-    for (i = 0; i < nb_elem; i++) {
-        MatroskaSeekhead *seekhead = seekhead_list->elem;
-        if (seekhead[i].pos <= before_pos)
+        MatroskaLevel1Element *elem = matroska_find_level1_elem(matroska, id);
+        if (!elem || elem->parsed)
             continue;
 
+        elem->pos = pos;
+
         // defer cues parsing until we actually need cue data.
-        if (seekhead[i].id == MATROSKA_ID_CUES) {
-            matroska->cues_parsing_deferred = 1;
+        if (id == MATROSKA_ID_CUES)
             continue;
-        }
 
-        if (matroska_parse_seekhead_entry(matroska, i) < 0) {
+        if (matroska_parse_seekhead_entry(matroska, pos) < 0) {
             // mark index as broken
             matroska->cues_parsing_deferred = -1;
             break;
         }
-    }
-    if (nb_elem != seekhead_list->nb_elem) {
-        avpriv_request_sample(matroska->ctx, "recursive SeekHead elements");
+
+        elem->parsed = 1;
     }
 }
 
@@ -1459,6 +1505,9 @@
     int index_scale = 1;
     int i, j;
 
+    if (matroska->ctx->flags & AVFMT_FLAG_IGNIDX)
+        return;
+
     index_list = &matroska->index;
     index      = index_list->elem;
     if (index_list->nb_elem &&
@@ -1482,17 +1531,21 @@
 }
 
 static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
-    EbmlList *seekhead_list = &matroska->seekhead;
-    MatroskaSeekhead *seekhead = seekhead_list->elem;
     int i;
 
-    for (i = 0; i < seekhead_list->nb_elem; i++)
-        if (seekhead[i].id == MATROSKA_ID_CUES)
-            break;
-    av_assert1(i <= seekhead_list->nb_elem);
+    if (matroska->ctx->flags & AVFMT_FLAG_IGNIDX)
+        return;
 
-    if (matroska_parse_seekhead_entry(matroska, i) < 0)
-       matroska->cues_parsing_deferred = -1;
+    for (i = 0; i < matroska->num_level1_elems; i++) {
+        MatroskaLevel1Element *elem = &matroska->level1_elems[i];
+        if (elem->id == MATROSKA_ID_CUES && !elem->parsed) {
+            if (matroska_parse_seekhead_entry(matroska, elem->pos) < 0)
+                matroska->cues_parsing_deferred = -1;
+            elem->parsed = 1;
+            break;
+        }
+    }
+
     matroska_add_index_entries(matroska);
 }
 
@@ -1941,8 +1994,8 @@
                 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
                           1000000000, track->default_duration, 30000);
 #if FF_API_R_FRAME_RATE
-                if (   st->avg_frame_rate.num < st->avg_frame_rate.den * 1000L
-                    && st->avg_frame_rate.num > st->avg_frame_rate.den * 5L)
+                if (   st->avg_frame_rate.num < st->avg_frame_rate.den * 1000LL
+                    && st->avg_frame_rate.num > st->avg_frame_rate.den * 5LL)
                     st->r_frame_rate = st->avg_frame_rate;
 #endif
             }
@@ -2028,6 +2081,7 @@
     int i, j, res;
 
     matroska->ctx = s;
+    matroska->cues_parsing_deferred = 1;
 
     /* First read the EBML header. */
     if (ebml_parse(matroska, ebml_syntax, &ebml) ||
@@ -2611,8 +2665,11 @@
         offset = 8;
 
     pkt = av_mallocz(sizeof(AVPacket));
-    if (!pkt)
+    if (!pkt) {
+        if (pkt_data != data)
+            av_freep(&pkt_data);
         return AVERROR(ENOMEM);
+    }
     /* XXX: prevent data copy... */
     if (av_new_packet(pkt, pkt_size + offset) < 0) {
         av_free(pkt);
diff --git a/libavformat/matroskaenc.c b/libavformat/matroskaenc.c
index dabfd86..6b2e390 100644
--- a/libavformat/matroskaenc.c
+++ b/libavformat/matroskaenc.c
@@ -71,7 +71,7 @@
     int                     num_entries;
 } mkv_seekhead;
 
-typedef struct {
+typedef struct mkv_cuepoint {
     uint64_t        pts;
     int             stream_idx;
     int             tracknum;
@@ -80,13 +80,13 @@
     int64_t         duration;           ///< duration of the block according to time base
 } mkv_cuepoint;
 
-typedef struct {
+typedef struct mkv_cues {
     int64_t         segment_offset;
     mkv_cuepoint    *entries;
     int             num_entries;
 } mkv_cues;
 
-typedef struct {
+typedef struct mkv_track {
     int             write_dts;
     int             has_cue;
     int64_t         ts_offset;
@@ -123,6 +123,8 @@
 
     uint32_t chapter_id_offset;
     int wrote_chapters;
+
+    int allow_raw_vfw;
 } MatroskaMuxContext;
 
 
@@ -603,8 +605,9 @@
         return ff_isom_write_avcc(dyn_cp, codec->extradata,
                                   codec->extradata_size);
     case AV_CODEC_ID_HEVC:
-        return ff_isom_write_hvcc(dyn_cp, codec->extradata,
-                                  codec->extradata_size, 0);
+        ff_isom_write_hvcc(dyn_cp, codec->extradata,
+                           codec->extradata_size, 0);
+        return 0;
     case AV_CODEC_ID_ALAC:
         if (codec->extradata_size < 36) {
             av_log(s, AV_LOG_ERROR,
@@ -665,7 +668,7 @@
             if (!codec->codec_tag)
                 codec->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags,
                                                     codec->codec_id);
-            if (!codec->codec_tag) {
+            if (!codec->codec_tag && codec->codec_id != AV_CODEC_ID_RAWVIDEO) {
                 av_log(s, AV_LOG_ERROR, "No bmp codec tag found for codec %s\n",
                        avcodec_get_name(codec->codec_id));
                 ret = AVERROR(EINVAL);
@@ -879,6 +882,15 @@
                 break;
             }
         }
+        if (codec->codec_id == AV_CODEC_ID_RAWVIDEO && !codec->codec_tag) {
+            if (mkv->allow_raw_vfw) {
+                native_id = 0;
+            } else {
+                av_log(s, AV_LOG_ERROR, "Raw RGB is not supported Natively in Matroska, you can use AVI or NUT or\n"
+                                        "If you would like to store it anyway using VFW mode, enable allow_raw_vfw (-allow_raw_vfw 1)\n");
+                return AVERROR(EINVAL);
+            }
+        }
     }
 
     if (codec->codec_type == AVMEDIA_TYPE_AUDIO && codec->initial_padding && codec->codec_id == AV_CODEC_ID_OPUS) {
@@ -917,7 +929,7 @@
 
         if (!native_id &&
             ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id) &&
-            (!ff_codec_get_tag(ff_codec_bmp_tags,   codec->codec_id) ||
+            ((!ff_codec_get_tag(ff_codec_bmp_tags,   codec->codec_id) && codec->codec_id != AV_CODEC_ID_RAWVIDEO) ||
              codec->codec_id == AV_CODEC_ID_SVQ1 ||
              codec->codec_id == AV_CODEC_ID_SVQ3 ||
              codec->codec_id == AV_CODEC_ID_CINEPAK))
@@ -1063,14 +1075,20 @@
     for (i = 0; i < s->nb_chapters; i++) {
         ebml_master chapteratom, chapterdisplay;
         AVChapter *c     = s->chapters[i];
+        int64_t chapterstart = av_rescale_q(c->start, c->time_base, scale);
+        int64_t chapterend   = av_rescale_q(c->end,   c->time_base, scale);
         AVDictionaryEntry *t = NULL;
+        if (chapterstart < 0 || chapterstart > chapterend || chapterend < 0) {
+            av_log(s, AV_LOG_ERROR,
+                   "Invalid chapter start (%"PRId64") or end (%"PRId64").\n",
+                   chapterstart, chapterend);
+            return AVERROR_INVALIDDATA;
+        }
 
         chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
         put_ebml_uint(pb, MATROSKA_ID_CHAPTERUID, c->id + mkv->chapter_id_offset);
-        put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART,
-                      av_rescale_q(c->start, c->time_base, scale));
-        put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND,
-                      av_rescale_q(c->end,   c->time_base, scale));
+        put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART, chapterstart);
+        put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND, chapterend);
         put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
         put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
@@ -1982,6 +2000,12 @@
     { AV_CODEC_ID_NONE,      0xFFFFFFFF }
 };
 
+static const AVCodecTag additional_subtitle_tags[] = {
+    { AV_CODEC_ID_DVB_SUBTITLE,      0xFFFFFFFF },
+    { AV_CODEC_ID_HDMV_PGS_SUBTITLE, 0xFFFFFFFF },
+    { AV_CODEC_ID_NONE,              0xFFFFFFFF }
+};
+
 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
 static const AVOption options[] = {
@@ -1990,6 +2014,7 @@
     { "cluster_time_limit",  "Store at most the provided number of milliseconds in a cluster.",                               OFFSET(cluster_time_limit), AV_OPT_TYPE_INT64, { .i64 = -1 }, -1, INT64_MAX, FLAGS },
     { "dash", "Create a WebM file conforming to WebM DASH specification", OFFSET(is_dash), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
     { "dash_track_number", "Track number for the DASH stream", OFFSET(dash_track_number), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 127, FLAGS },
+    { "allow_raw_vfw", "allow RAW VFW mode", OFFSET(allow_raw_vfw), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
     { NULL },
 };
 
@@ -2018,7 +2043,7 @@
                          AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
     .codec_tag         = (const AVCodecTag* const []){
          ff_codec_bmp_tags, ff_codec_wav_tags,
-         additional_audio_tags, additional_video_tags, 0
+         additional_audio_tags, additional_video_tags, additional_subtitle_tags, 0
     },
     .subtitle_codec    = AV_CODEC_ID_ASS,
     .query_codec       = mkv_query_codec,
diff --git a/libavformat/mlvdec.c b/libavformat/mlvdec.c
index d0c51ae..9d821bb 100644
--- a/libavformat/mlvdec.c
+++ b/libavformat/mlvdec.c
@@ -242,6 +242,7 @@
     AVIOContext *pb = avctx->pb;
     AVStream *vst = NULL, *ast = NULL;
     int size, ret;
+    unsigned nb_video_frames, nb_audio_frames;
     uint64_t guid;
     char guidstr[32];
 
@@ -259,11 +260,17 @@
     avio_skip(pb, 8); //fileNum, fileCount, fileFlags
 
     mlv->class[0] = avio_rl16(pb);
-    if (mlv->class[0]) {
+    mlv->class[1] = avio_rl16(pb);
+
+    nb_video_frames = avio_rl32(pb);
+    nb_audio_frames = avio_rl32(pb);
+
+    if (nb_video_frames && mlv->class[0]) {
         vst = avformat_new_stream(avctx, NULL);
         if (!vst)
             return AVERROR(ENOMEM);
         vst->id = 0;
+        vst->nb_frames = nb_video_frames;
         if ((mlv->class[0] & (MLV_CLASS_FLAG_DELTA|MLV_CLASS_FLAG_LZMA)))
             avpriv_request_sample(avctx, "compression");
         vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
@@ -289,12 +296,12 @@
         }
     }
 
-    mlv->class[1] = avio_rl16(pb);
-    if (mlv->class[1]) {
+    if (nb_audio_frames && mlv->class[1]) {
         ast = avformat_new_stream(avctx, NULL);
         if (!ast)
             return AVERROR(ENOMEM);
         ast->id = 1;
+        ast->nb_frames = nb_audio_frames;
         if ((mlv->class[1] & MLV_CLASS_FLAG_LZMA))
             avpriv_request_sample(avctx, "compression");
         if ((mlv->class[1] & ~MLV_CLASS_FLAG_LZMA) != MLV_AUDIO_CLASS_WAV)
@@ -304,16 +311,6 @@
         avpriv_set_pts_info(ast, 33, 1, ast->codec->sample_rate);
     }
 
-    if (vst)
-       vst->nb_frames = avio_rl32(pb);
-    else
-       avio_skip(pb, 4);
-
-    if (ast)
-       ast->nb_frames = avio_rl32(pb);
-    else
-       avio_skip(pb, 4);
-
     if (vst) {
        AVRational framerate;
        framerate.num = avio_rl32(pb);
diff --git a/libavformat/mm.c b/libavformat/mm.c
index 4315802..81ae1a5 100644
--- a/libavformat/mm.c
+++ b/libavformat/mm.c
@@ -54,7 +54,7 @@
 #define MM_PALETTE_COUNT    128
 #define MM_PALETTE_SIZE     (MM_PALETTE_COUNT*3)
 
-typedef struct {
+typedef struct MmDemuxContext {
   unsigned int audio_pts, video_pts;
 } MmDemuxContext;
 
diff --git a/libavformat/mmf.c b/libavformat/mmf.c
index e963112..c2acec9 100644
--- a/libavformat/mmf.c
+++ b/libavformat/mmf.c
@@ -27,7 +27,7 @@
 #include "rawenc.h"
 #include "riff.h"
 
-typedef struct {
+typedef struct MMFContext {
     int64_t atrpos, atsqpos, awapos;
     int64_t data_end;
     int stereo;
diff --git a/libavformat/mms.c b/libavformat/mms.c
index 7e60b3b..807aade 100644
--- a/libavformat/mms.c
+++ b/libavformat/mms.c
@@ -104,6 +104,8 @@
                 mms->streams = av_fast_realloc(mms->streams,
                                    &mms->nb_streams_allocated,
                                    (mms->stream_num + 1) * sizeof(MMSStream));
+                if (!mms->streams)
+                    return AVERROR(ENOMEM);
                 mms->streams[mms->stream_num].id = stream_id;
                 mms->stream_num++;
             } else {
diff --git a/libavformat/mmsh.c b/libavformat/mmsh.c
index dac5d9f..38e6b31 100644
--- a/libavformat/mmsh.c
+++ b/libavformat/mmsh.c
@@ -54,7 +54,7 @@
     CHUNK_TYPE_STREAM_CHANGE = 0x4324,
 } ChunkType;
 
-typedef struct {
+typedef struct MMSHContext {
     MMSContext mms;
     uint8_t location[1024];
     int request_seq;  ///< request packet sequence
diff --git a/libavformat/mmst.c b/libavformat/mmst.c
index 653b403..65c4f44 100644
--- a/libavformat/mmst.c
+++ b/libavformat/mmst.c
@@ -85,7 +85,7 @@
     /*@}*/
 } MMSSCPacketType;
 
-typedef struct {
+typedef struct MMSTContext {
     MMSContext  mms;
     int outgoing_packet_seq;             ///< Outgoing packet sequence number.
     char path[256];                      ///< Path of the resource being asked for.
diff --git a/libavformat/mov.c b/libavformat/mov.c
index f7e6137..dc31e5a 100644
--- a/libavformat/mov.c
+++ b/libavformat/mov.c
@@ -55,10 +55,6 @@
 
 #include "qtpalette.h"
 
-
-#undef NDEBUG
-#include <assert.h>
-
 /* those functions parse an atom */
 /* links atom IDs to parse functions */
 typedef struct MOVParseTableEntry {
@@ -342,7 +338,7 @@
     case MKTAG(0xa9,'w','r','t'): key = "composer";  break;
     case MKTAG(0xa9,'x','y','z'): key = "location";  break;
     }
-
+retry:
     if (c->itunes_metadata && atom.size > 8) {
         int data_size = avio_rb32(pb);
         int tag = avio_rl32(pb);
@@ -362,6 +358,12 @@
         } else return 0;
     } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
         str_size = avio_rb16(pb); // string length
+        if (str_size > atom.size) {
+            raw = 1;
+            avio_seek(pb, -2, SEEK_CUR);
+            av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
+            goto retry;
+        }
         langcode = avio_rb16(pb);
         ff_mov_lang_to_iso639(langcode, language);
         atom.size -= 4;
@@ -560,7 +562,7 @@
     AVStream *st;
     uint32_t type;
     uint32_t av_unused ctype;
-    int title_size;
+    int64_t title_size;
     char *title_str;
 
     if (c->fc->nb_streams < 1) // meta before first trak
@@ -598,9 +600,10 @@
             return AVERROR(ENOMEM);
         avio_read(pb, title_str, title_size);
         title_str[title_size] = 0;
-        if (title_str[0])
-            av_dict_set(&st->metadata, "handler_name", title_str +
-                        (!c->isom && title_str[0] == title_size - 1), 0);
+        if (title_str[0]) {
+            int off = (!c->isom && title_str[0] == title_size - 1);
+            av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
+        }
         av_freep(&title_str);
     }
 
@@ -753,8 +756,8 @@
                st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
                num, den);
     } else if (den != 0) {
-        st->sample_aspect_ratio.num = num;
-        st->sample_aspect_ratio.den = den;
+        av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
+                  num, den, 32767);
     }
     return 0;
 }
@@ -998,7 +1001,7 @@
     av_dlog(c->fc, "%s: pri %d trc %d matrix %d",
             color_parameter_type, color_primaries, color_trc, color_matrix);
 
-    if (c->isom) {
+    if (strncmp(color_parameter_type, "nclx", 4) == 0) {
         uint8_t color_range = avio_r8(pb) >> 7;
         av_dlog(c->fc, " full %"PRIu8"", color_range);
         if (color_range)
@@ -1076,42 +1079,66 @@
     return 0;
 }
 
+static int mov_realloc_extradata(AVCodecContext *codec, MOVAtom atom)
+{
+    int err = 0;
+    uint64_t size = (uint64_t)codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
+    if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
+        return AVERROR_INVALIDDATA;
+    if ((err = av_reallocp(&codec->extradata, size)) < 0) {
+        codec->extradata_size = 0;
+        return err;
+    }
+    codec->extradata_size = size - FF_INPUT_BUFFER_PADDING_SIZE;
+    return 0;
+}
+
+/* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
+static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
+                                        AVCodecContext *codec, uint8_t *buf)
+{
+    int64_t result = atom.size;
+    int err;
+
+    AV_WB32(buf    , atom.size + 8);
+    AV_WL32(buf + 4, atom.type);
+    err = avio_read(pb, buf + 8, atom.size);
+    if (err < 0) {
+        codec->extradata_size -= atom.size;
+        return err;
+    } else if (err < atom.size) {
+        av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
+        codec->extradata_size -= atom.size - err;
+        result = err;
+    }
+    memset(buf + 8 + err, 0, FF_INPUT_BUFFER_PADDING_SIZE);
+    return result;
+}
+
 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
                               enum AVCodecID codec_id)
 {
     AVStream *st;
-    uint64_t size;
-    uint8_t *buf;
+    uint64_t original_size;
     int err;
 
     if (c->fc->nb_streams < 1) // will happen with jp2 files
         return 0;
-    st= c->fc->streams[c->fc->nb_streams-1];
+    st = c->fc->streams[c->fc->nb_streams-1];
 
     if (st->codec->codec_id != codec_id)
         return 0; /* unexpected codec_id - don't mess with extradata */
 
-    size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
-    if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
-        return AVERROR_INVALIDDATA;
-    if ((err = av_reallocp(&st->codec->extradata, size)) < 0) {
-        st->codec->extradata_size = 0;
+    original_size = st->codec->extradata_size;
+    err = mov_realloc_extradata(st->codec, atom);
+    if (err)
         return err;
-    }
-    buf = st->codec->extradata + st->codec->extradata_size;
-    st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
-    AV_WB32(       buf    , atom.size + 8);
-    AV_WL32(       buf + 4, atom.type);
-    err = avio_read(pb, buf + 8, atom.size);
-    if (err < 0) {
+
+    err =  mov_read_atom_into_extradata(c, pb, atom, st->codec,  st->codec->extradata + original_size);
+    if (err < 0)
         return err;
-    } else if (err < atom.size) {
-        av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
-        st->codec->extradata_size -= atom.size - err;
-    }
-    memset(buf + 8 + err, 0, FF_INPUT_BUFFER_PADDING_SIZE);
-    return 0;
+    return 0; // Note: this is the original behavior to ignore truncation.
 }
 
 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
@@ -1175,6 +1202,47 @@
     return mov_read_avid(c, pb, atom);
 }
 
+static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
+{
+    int ret = 0;
+    int length = 0;
+    uint64_t original_size;
+    if (c->fc->nb_streams >= 1) {
+        AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
+        if (atom.size == 16) {
+            original_size = codec->extradata_size;
+            ret = mov_realloc_extradata(codec, atom);
+            if (!ret) {
+                length =  mov_read_atom_into_extradata(c, pb, atom, codec, codec->extradata + original_size);
+                if (length == atom.size) {
+                    const uint8_t range_value = codec->extradata[original_size + 19];
+                    switch (range_value) {
+                    case 1:
+                        codec->color_range = AVCOL_RANGE_MPEG;
+                        break;
+                    case 2:
+                        codec->color_range = AVCOL_RANGE_JPEG;
+                        break;
+                    default:
+                        av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
+                        break;
+                    }
+                    av_dlog(c, "color_range: %"PRIu8"\n", codec->color_range);
+                } else {
+                  /* For some reason the whole atom was not added to the extradata */
+                  av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
+                }
+            } else {
+                av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
+            }
+        } else {
+            av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
+        }
+    }
+
+    return ret;
+}
+
 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
@@ -2532,7 +2600,7 @@
     /* try relative path, we do not try the absolute because it can leak information about our
        system to an attacker */
     if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
-        char filename[1024];
+        char filename[1025];
         const char *src_path;
         int i, l;
 
@@ -2558,10 +2626,15 @@
             filename[src_path - src] = 0;
 
             for (i = 1; i < ref->nlvl_from; i++)
-                av_strlcat(filename, "../", 1024);
+                av_strlcat(filename, "../", sizeof(filename));
 
-            av_strlcat(filename, ref->path + l + 1, 1024);
+            av_strlcat(filename, ref->path + l + 1, sizeof(filename));
+            if (!use_absolute_path)
+                if(strstr(ref->path + l + 1, "..") || ref->nlvl_from > 1)
+                    return AVERROR(ENOENT);
 
+            if (strlen(filename) + 1 == sizeof(filename))
+                return AVERROR(ENOENT);
             if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
                 return 0;
         }
@@ -2633,7 +2706,8 @@
     }
 
     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
-        if (!st->sample_aspect_ratio.num &&
+        if (!st->sample_aspect_ratio.num && st->codec->width && st->codec->height &&
+            sc->height && sc->width &&
             (st->codec->width != sc->width || st->codec->height != sc->height)) {
             st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
                                              ((double)st->codec->width * sc->height), INT_MAX);
@@ -2875,7 +2949,7 @@
 
         for (i = 0; i < 3; i++)
             for (j = 0; j < 3; j++)
-                sc->display_matrix[i * 3 + j] = display_matrix[j][i];
+                sc->display_matrix[i * 3 + j] = display_matrix[i][j];
 
         rotate = av_display_rotation_get(sc->display_matrix);
         if (!isnan(rotate)) {
@@ -3139,8 +3213,11 @@
                                   MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
         if (keyframe)
             distance = 0;
-        av_add_index_entry(st, offset, dts, sample_size, distance,
-                           keyframe ? AVINDEX_KEYFRAME : 0);
+        err = av_add_index_entry(st, offset, dts, sample_size, distance,
+                                 keyframe ? AVINDEX_KEYFRAME : 0);
+        if (err < 0) {
+            av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
+        }
         av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
                 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
                 offset, dts, sample_size, distance, keyframe);
@@ -3375,7 +3452,7 @@
 }
 
 static const MOVParseTableEntry mov_default_parse_table[] = {
-{ MKTAG('A','C','L','R'), mov_read_avid },
+{ MKTAG('A','C','L','R'), mov_read_aclr },
 { MKTAG('A','P','R','G'), mov_read_avid },
 { MKTAG('A','A','L','P'), mov_read_avid },
 { MKTAG('A','R','E','S'), mov_read_ares },
@@ -3587,7 +3664,9 @@
                  AV_RB64(p->buf+offset + 8) == 0)) {
                 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
             } else if (tag == MKTAG('f','t','y','p') &&
-                       AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')) {
+                       (   AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
+                        || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
+                    )) {
                 score = FFMAX(score, 5);
             } else {
                 score = AVPROBE_SCORE_MAX;
@@ -4246,8 +4325,8 @@
 
 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
 {
+    MOVContext *mc = s->priv_data;
     AVStream *st;
-    int64_t seek_timestamp, timestamp;
     int sample;
     int i;
 
@@ -4259,19 +4338,39 @@
     if (sample < 0)
         return sample;
 
-    /* adjust seek timestamp to found sample timestamp */
-    seek_timestamp = st->index_entries[sample].timestamp;
+    if (mc->seek_individually) {
+        /* adjust seek timestamp to found sample timestamp */
+        int64_t seek_timestamp = st->index_entries[sample].timestamp;
 
-    for (i = 0; i < s->nb_streams; i++) {
-        MOVStreamContext *sc = s->streams[i]->priv_data;
-        st = s->streams[i];
-        st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
+        for (i = 0; i < s->nb_streams; i++) {
+            int64_t timestamp;
+            MOVStreamContext *sc = s->streams[i]->priv_data;
+            st = s->streams[i];
+            st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
 
-        if (stream_index == i)
-            continue;
+            if (stream_index == i)
+                continue;
 
-        timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
-        mov_seek_stream(s, st, timestamp, flags);
+            timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
+            mov_seek_stream(s, st, timestamp, flags);
+        }
+    } else {
+        for (i = 0; i < s->nb_streams; i++) {
+            MOVStreamContext *sc;
+            st = s->streams[i];
+            sc = st->priv_data;
+            sc->current_sample = 0;
+        }
+        while (1) {
+            MOVStreamContext *sc;
+            AVIndexEntry *entry = mov_find_next_sample(s, &st);
+            if (!entry)
+                return AVERROR_INVALIDDATA;
+            sc = st->priv_data;
+            if (sc->ffindex == stream_index && sc->current_sample == sample)
+                break;
+            sc->current_sample++;
+        }
     }
     return 0;
 }
@@ -4283,6 +4382,10 @@
         "allow using absolute path when opening alias, this is a possible security issue",
         OFFSET(use_absolute_path), FF_OPT_TYPE_INT, {.i64 = 0},
         0, 1, FLAGS},
+    {"seek_streams_individually",
+        "Seek each stream individually to the to the closest point",
+        OFFSET(seek_individually), AV_OPT_TYPE_INT, { .i64 = 1 },
+        0, 1, FLAGS},
     {"ignore_editlist", "", OFFSET(ignore_editlist), FF_OPT_TYPE_INT, {.i64 = 0},
         0, 1, FLAGS},
     {"use_mfra_for",
diff --git a/libavformat/movenc.c b/libavformat/movenc.c
index d7ae5f0..b6821d4 100644
--- a/libavformat/movenc.c
+++ b/libavformat/movenc.c
@@ -40,17 +40,16 @@
 #include "libavutil/avstring.h"
 #include "libavutil/intfloat.h"
 #include "libavutil/mathematics.h"
+#include "libavutil/libm.h"
 #include "libavutil/opt.h"
 #include "libavutil/dict.h"
 #include "libavutil/pixdesc.h"
 #include "libavutil/timecode.h"
+#include "libavutil/color_utils.h"
 #include "hevc.h"
 #include "rtpenc.h"
 #include "mov_chan.h"
 
-#undef NDEBUG
-#include <assert.h>
-
 static const AVOption options[] = {
     { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
     { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
@@ -67,7 +66,8 @@
     { "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
     { "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
     { "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
-    { "write_colr", "Write colr atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_COLR}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
+    { "write_colr", "Write colr atom (Experimental, may be renamed or changed, do not use from scripts)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_COLR}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
+    { "write_gama", "Write deprecated gama atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_GAMA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
     FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
     { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
     { "iods_audio_profile", "iods audio profile atom.", offsetof(MOVMuxContext, iods_audio_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM},
@@ -79,7 +79,9 @@
     { "video_track_timescale", "set timescale of all video tracks", offsetof(MOVMuxContext, video_track_timescale), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
     { "brand",    "Override major brand", offsetof(MOVMuxContext, major_brand),   AV_OPT_TYPE_STRING, {.str = NULL}, .flags = 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},
-    { "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
+    { "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
+    { "mov_gamma", "gamma value for gama atom", offsetof(MOVMuxContext, gamma), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, 0.0, 10, AV_OPT_FLAG_ENCODING_PARAM},
+    { "frag_interleave", "Interleave samples within fragments (max number of consecutive samples, lower is tighter interleaving, but with more overhead)", offsetof(MOVMuxContext, frag_interleave), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
     { NULL },
 };
 
@@ -325,6 +327,7 @@
     } substream[1]; /* TODO: support 8 independent substreams */
 };
 
+#if CONFIG_AC3_PARSER
 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
 {
     GetBitContext gbc;
@@ -445,6 +448,7 @@
 
     return pkt->size;
 }
+#endif
 
 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
 {
@@ -1034,11 +1038,33 @@
 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
 {
     int i;
+    int interlaced;
+    int cid;
+
+    if (track->vos_data && track->vos_len > 0x29) {
+        if (track->vos_data[0] == 0x00 &&
+            track->vos_data[1] == 0x00 &&
+            track->vos_data[2] == 0x02 &&
+            track->vos_data[3] == 0x80 &&
+            (track->vos_data[4] == 0x01 || track->vos_data[4] == 0x02)) {
+            /* looks like a DNxHD bit stream */
+            interlaced = (track->vos_data[5] & 2);
+            cid = AV_RB32(track->vos_data + 0x28);
+        } else {
+            av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
+            return 0;
+        }
+    } else {
+        av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
+        return 0;
+    }
+
     avio_wb32(pb, 24); /* size */
     ffio_wfourcc(pb, "ACLR");
     ffio_wfourcc(pb, "ACLR");
     ffio_wfourcc(pb, "0001");
-    if (track->enc->color_range == AVCOL_RANGE_MPEG) { /* Legal range (16-235) */
+    if (track->enc->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
+        track->enc->color_range == AVCOL_RANGE_UNSPECIFIED) {
         avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
     } else { /* Full range (0-255) */
         avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
@@ -1056,10 +1082,10 @@
     ffio_wfourcc(pb, "ARES");
     ffio_wfourcc(pb, "ARES");
     ffio_wfourcc(pb, "0001");
-    avio_wb32(pb, AV_RB32(track->vos_data + 0x28)); /* dnxhd cid, some id ? */
+    avio_wb32(pb, cid); /* dnxhd cid, some id ? */
     avio_wb32(pb, track->enc->width);
     /* values below are based on samples created with quicktime and avid codecs */
-    if (track->vos_data[5] & 2) { // interlaced
+    if (interlaced) {
         avio_wb32(pb, track->enc->height / 2);
         avio_wb32(pb, 2); /* unknown */
         avio_wb32(pb, 0); /* unknown */
@@ -1077,8 +1103,6 @@
     for (i = 0; i < 10; i++)
         avio_wb64(pb, 0);
 
-    /* extra padding for stsd needed */
-    avio_wb32(pb, 0);
     return 0;
 }
 
@@ -1500,9 +1524,35 @@
     return 16;
 }
 
+static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
+{
+    uint32_t gama = 0;
+    if (gamma <= 0.0)
+    {
+        gamma = avpriv_get_gamma_from_trc(track->enc->color_trc);
+    }
+    av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
+
+    if (gamma > 1e-6) {
+        gama = (uint32_t)lrint((double)(1<<16) * gamma);
+        av_log(pb, AV_LOG_DEBUG, "writing gama value %d\n", gama);
+
+        av_assert0(track->mode == MODE_MOV);
+        avio_wb32(pb, 12);
+        ffio_wfourcc(pb, "gama");
+        avio_wb32(pb, gama);
+        return 12;
+    }
+    else {
+        av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
+    }
+    return 0;
+}
+
 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
 {
-    // Ref: https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
+    // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
+    // Ref (MP4): ISO/IEC 14496-12:2012
 
     if (track->enc->color_primaries == AVCOL_PRI_UNSPECIFIED &&
         track->enc->color_trc == AVCOL_TRC_UNSPECIFIED &&
@@ -1534,9 +1584,15 @@
         }
     }
 
-    avio_wb32(pb, 18);
+    /* We should only ever be called by MOV or MP4. */
+    av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
+
+    avio_wb32(pb, 18 + (track->mode == MODE_MP4));
     ffio_wfourcc(pb, "colr");
-    ffio_wfourcc(pb, "nclc");
+    if (track->mode == MODE_MP4)
+        ffio_wfourcc(pb, "nclx");
+    else
+        ffio_wfourcc(pb, "nclc");
     switch (track->enc->color_primaries) {
     case AVCOL_PRI_BT709:     avio_wb16(pb, 1); break;
     case AVCOL_PRI_SMPTE170M:
@@ -1557,7 +1613,13 @@
     default:                  avio_wb16(pb, 2);
     }
 
-    return 18;
+    if (track->mode == MODE_MP4) {
+        int full_range = track->enc->color_range == AVCOL_RANGE_JPEG;
+        avio_w8(pb, full_range << 7);
+        return 19;
+    } else {
+        return 18;
+    }
 }
 
 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
@@ -1592,6 +1654,7 @@
 {
     int64_t pos = avio_tell(pb);
     char compressor_name[32] = { 0 };
+    int avid = 0;
 
     avio_wb32(pb, 0); /* size */
     avio_wl32(pb, track->tag); // store it byteswapped
@@ -1640,9 +1703,10 @@
             track->enc->codec_id == AV_CODEC_ID_SVQ3) {
         mov_write_extradata_tag(pb, track);
         avio_wb32(pb, 0);
-    } else if (track->enc->codec_id == AV_CODEC_ID_DNXHD)
+    } else if (track->enc->codec_id == AV_CODEC_ID_DNXHD) {
         mov_write_avid_tag(pb, track);
-    else if (track->enc->codec_id == AV_CODEC_ID_HEVC)
+        avid = 1;
+    } else if (track->enc->codec_id == AV_CODEC_ID_HEVC)
         mov_write_hvcc_tag(pb, track);
     else if (track->enc->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
         mov_write_avcc_tag(pb, track);
@@ -1666,14 +1730,29 @@
         if (track->enc->field_order != AV_FIELD_UNKNOWN)
             mov_write_fiel_tag(pb, track);
 
-    if (mov->flags & FF_MOV_FLAG_WRITE_COLR)
-        mov_write_colr_tag(pb, track);
+    if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
+        if (track->mode == MODE_MOV)
+            mov_write_gama_tag(pb, track, mov->gamma);
+        else
+            av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
+    }
+    if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
+        if (track->mode == MODE_MOV || track->mode == MODE_MP4)
+            mov_write_colr_tag(pb, track);
+        else
+            av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
+    }
 
     if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
         track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
         mov_write_pasp_tag(pb, track);
     }
 
+    /* extra padding for avid stsd */
+    /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
+    if (avid)
+        avio_wb32(pb, 0);
+
     return update_size(pb, pos);
 }
 
@@ -1817,20 +1896,24 @@
 /* Time to sample atom */
 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
 {
-    MOVStts *stts_entries;
+    MOVStts *stts_entries = NULL;
     uint32_t entries = -1;
     uint32_t atom_size;
     int i;
 
     if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
         stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
+        if (!stts_entries)
+            return AVERROR(ENOMEM);
         stts_entries[0].count = track->sample_count;
         stts_entries[0].duration = 1;
         entries = 1;
     } else {
-        stts_entries = track->entry ?
-                       av_malloc_array(track->entry, sizeof(*stts_entries)) : /* worst case */
-                       NULL;
+        if (track->entry) {
+            stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
+            if (!stts_entries)
+                return AVERROR(ENOMEM);
+        }
         for (i = 0; i < track->entry; i++) {
             int duration = get_cluster_duration(track, i);
             if (i && duration == stts_entries[entries].duration) {
@@ -2208,12 +2291,19 @@
     int rotation = 0;
     int group   = 0;
 
+    uint32_t *display_matrix = NULL;
+    int      display_matrix_size, i;
 
     if (st) {
         if (mov->per_stream_grouping)
             group = st->index;
         else
             group = st->codec->codec_type;
+
+        display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
+                                                            &display_matrix_size);
+        if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
+            display_matrix = NULL;
     }
 
     if (track->flags & MOV_TRACK_ENABLED)
@@ -2258,7 +2348,10 @@
         AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
         rotation = (rot && rot->value) ? atoi(rot->value) : 0;
     }
-    if (rotation == 90) {
+    if (display_matrix) {
+        for (i = 0; i < 9; i++)
+            avio_wb32(pb, display_matrix[i]);
+    } else if (rotation == 90) {
         write_matrix(pb,  0,  1, -1,  0, track->enc->height, 0);
     } else if (rotation == 180) {
         write_matrix(pb, -1,  0,  0, -1, track->enc->width, track->enc->height);
@@ -2980,6 +3073,8 @@
         mov_write_string_metadata(s, pb_buf, "\251cmt", "comment",     0);
         mov_write_string_metadata(s, pb_buf, "\251gen", "genre",       0);
         mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright",   0);
+        mov_write_string_metadata(s, pb_buf, "\251mak", "make",        0);
+        mov_write_string_metadata(s, pb_buf, "\251mod", "model",       0);
         mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
     } else {
         /* iTunes meta data */
@@ -3253,6 +3348,12 @@
     return 0;
 }
 
+static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
+{
+    return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
+           (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
+}
+
 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
                               MOVTrack *track, int64_t moof_offset)
 {
@@ -3298,38 +3399,39 @@
         track->default_size = -1;
 
     if (flags & MOV_TFHD_DEFAULT_FLAGS) {
-        track->default_sample_flags =
-            track->enc->codec_type == AVMEDIA_TYPE_VIDEO ?
-            (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
-            MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
+        /* Set the default flags based on the second sample, if available.
+         * If the first sample is different, that can be signaled via a separate field. */
+        if (track->entry > 1)
+            track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
+        else
+            track->default_sample_flags =
+                track->enc->codec_type == AVMEDIA_TYPE_VIDEO ?
+                (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
+                MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
         avio_wb32(pb, track->default_sample_flags);
     }
 
     return update_size(pb, pos);
 }
 
-static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
-{
-    return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
-           (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
-}
-
 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
-                              MOVTrack *track, int moof_size)
+                              MOVTrack *track, int moof_size,
+                              int first, int end)
 {
     int64_t pos = avio_tell(pb);
     uint32_t flags = MOV_TRUN_DATA_OFFSET;
     int i;
 
-    for (i = 0; i < track->entry; i++) {
+    for (i = first; i < end; i++) {
         if (get_cluster_duration(track, i) != track->default_duration)
             flags |= MOV_TRUN_SAMPLE_DURATION;
         if (track->cluster[i].size != track->default_size)
             flags |= MOV_TRUN_SAMPLE_SIZE;
-        if (i > 0 && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
+        if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
             flags |= MOV_TRUN_SAMPLE_FLAGS;
     }
-    if (!(flags & MOV_TRUN_SAMPLE_FLAGS))
+    if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
+         get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
         flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
     if (track->flags & MOV_TRACK_CTTS)
         flags |= MOV_TRUN_SAMPLE_CTS;
@@ -3339,18 +3441,18 @@
     avio_w8(pb, 0); /* version */
     avio_wb24(pb, flags);
 
-    avio_wb32(pb, track->entry); /* sample count */
+    avio_wb32(pb, end - first); /* sample count */
     if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
         !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
         !mov->first_trun)
         avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
     else
         avio_wb32(pb, moof_size + 8 + track->data_offset +
-                      track->cluster[0].pos); /* data offset */
+                      track->cluster[first].pos); /* data offset */
     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
-        avio_wb32(pb, get_sample_flags(track, &track->cluster[0]));
+        avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
 
-    for (i = 0; i < track->entry; i++) {
+    for (i = first; i < end; i++) {
         if (flags & MOV_TRUN_SAMPLE_DURATION)
             avio_wb32(pb, get_cluster_duration(track, i));
         if (flags & MOV_TRUN_SAMPLE_SIZE)
@@ -3378,9 +3480,10 @@
     avio_write(pb, uuid, sizeof(uuid));
     avio_w8(pb, 1);
     avio_wb24(pb, 0);
-    avio_wb64(pb, track->frag_start);
-    avio_wb64(pb, track->start_dts + track->track_duration -
-                  track->cluster[0].dts);
+    avio_wb64(pb, track->start_dts + track->frag_start +
+                  track->cluster[0].cts);
+    avio_wb64(pb, track->end_pts -
+                  (track->cluster[0].dts + track->cluster[0].cts));
 
     return update_size(pb, pos);
 }
@@ -3459,13 +3562,15 @@
         // from the fields we have stored
         info->time     = track->start_dts + track->frag_start +
                          track->cluster[0].cts;
+        info->duration = track->end_pts -
+                         (track->cluster[0].dts + track->cluster[0].cts);
         // If the pts is less than zero, we will have trimmed
         // away parts of the media track using an edit list,
         // and the corresponding start presentation time is zero.
-        if (info->time < 0)
+        if (info->time < 0) {
+            info->duration += info->time;
             info->time = 0;
-        info->duration = track->start_dts + track->track_duration -
-                         track->cluster[0].dts;
+        }
         info->tfrf_offset = 0;
         mov_write_tfrf_tags(pb, mov, track);
     }
@@ -3489,13 +3594,20 @@
                               int moof_size)
 {
     int64_t pos = avio_tell(pb);
+    int i, start = 0;
     avio_wb32(pb, 0); /* size placeholder */
     ffio_wfourcc(pb, "traf");
 
     mov_write_tfhd_tag(pb, mov, track, moof_offset);
     if (mov->mode != MODE_ISM)
         mov_write_tfdt_tag(pb, track);
-    mov_write_trun_tag(pb, mov, track, moof_size);
+    for (i = 1; i < track->entry; i++) {
+        if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
+            mov_write_trun_tag(pb, mov, track, moof_size, start, i);
+            start = i;
+        }
+    }
+    mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
     if (mov->mode == MODE_ISM) {
         mov_write_tfxd_tag(pb, track);
 
@@ -3551,18 +3663,20 @@
         entries = 1;
         presentation_time = track->start_dts + track->frag_start +
                             track->cluster[0].cts;
-        duration = track->start_dts + track->track_duration -
-                   track->cluster[0].dts;
+        duration = track->end_pts -
+                   (track->cluster[0].dts + track->cluster[0].cts);
         starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
+
+        // pts<0 should be cut away using edts
+        if (presentation_time < 0) {
+            duration += presentation_time;
+            presentation_time = 0;
+        }
     } else {
         entries = track->nb_frag_info;
         presentation_time = track->frag_info[0].time;
     }
 
-    // pts<0 should be cut away using edts
-    if (presentation_time < 0)
-        presentation_time = 0;
-
     avio_wb32(pb, 0); /* size */
     ffio_wfourcc(pb, "sidx");
     avio_w8(pb, 1); /* version */
@@ -3900,7 +4014,7 @@
     return 0;
 }
 
-static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk, int fragment)
+static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
 {
     const uint8_t *start, *next, *end = pkt->data + pkt->size;
     int seq = 0, entry = 0;
@@ -3920,10 +4034,13 @@
             break;
         }
     }
-    if (!trk->entry && !fragment) {
+    if (!trk->entry && trk->vc1_info.first_packet_seen)
+        trk->vc1_info.first_frag_written = 1;
+    if (!trk->entry && !trk->vc1_info.first_frag_written) {
         /* First packet in first fragment */
         trk->vc1_info.first_packet_seq   = seq;
         trk->vc1_info.first_packet_entry = entry;
+        trk->vc1_info.first_packet_seen  = 1;
     } else if ((seq && !trk->vc1_info.packet_seq) ||
                (entry && !trk->vc1_info.packet_entry)) {
         int i;
@@ -3934,7 +4051,7 @@
             trk->vc1_info.packet_seq = 1;
         if (entry)
             trk->vc1_info.packet_entry = 1;
-        if (!fragment) {
+        if (!trk->vc1_info.first_frag_written) {
             /* First fragment */
             if ((!seq   || trk->vc1_info.first_packet_seq) &&
                 (!entry || trk->vc1_info.first_packet_entry)) {
@@ -3957,6 +4074,32 @@
     }
 }
 
+static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
+{
+    MOVMuxContext *mov = s->priv_data;
+    int ret, buf_size;
+    uint8_t *buf;
+    int i, offset;
+
+    if (!track->mdat_buf)
+        return 0;
+    if (!mov->mdat_buf) {
+        if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
+            return ret;
+    }
+    buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
+    track->mdat_buf = NULL;
+
+    offset = avio_tell(mov->mdat_buf);
+    avio_write(mov->mdat_buf, buf, buf_size);
+    av_free(buf);
+
+    for (i = track->entries_flushed; i < track->entry; i++)
+        track->cluster[i].pos += offset;
+    track->entries_flushed = track->entry;
+    return 0;
+}
+
 static int mov_flush_fragment(AVFormatContext *s)
 {
     MOVMuxContext *mov = s->priv_data;
@@ -3967,7 +4110,34 @@
     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
         return 0;
 
-    if (mov->fragments == 0) {
+    for (i = 0; i < mov->nb_streams; i++) {
+        MOVTrack *track = &mov->tracks[i];
+        if (track->entry <= 1)
+            continue;
+        // Sample durations are calculated as the diff of dts values,
+        // but for the last sample in a fragment, we don't know the dts
+        // of the first sample in the next fragment, so we have to rely
+        // on what was set as duration in the AVPacket. Not all callers
+        // set this though, so we might want to replace it with an
+        // estimate if it currently is zero.
+        if (get_cluster_duration(track, track->entry - 1) != 0)
+            continue;
+        // Use the duration (i.e. dts diff) of the second last sample for
+        // the last one. This is a wild guess (and fatal if it turns out
+        // to be too long), but probably the best we can do - having a zero
+        // duration is bad as well.
+        track->track_duration += get_cluster_duration(track, track->entry - 2);
+        track->end_pts        += get_cluster_duration(track, track->entry - 2);
+        if (!mov->missing_duration_warned) {
+            av_log(s, AV_LOG_WARNING,
+                   "Estimating the duration of the last packet in a "
+                   "fragment, consider setting the duration field in "
+                   "AVPacket instead.\n");
+            mov->missing_duration_warned = 1;
+        }
+    }
+
+    if (!mov->moov_written) {
         int64_t pos = avio_tell(s->pb);
         uint8_t *buf;
         int buf_size, moov_size;
@@ -3992,7 +4162,7 @@
             if (mov->flags & FF_MOV_FLAG_FASTSTART)
                 mov->reserved_moov_pos = avio_tell(s->pb);
             avio_flush(s->pb);
-            mov->fragments++;
+            mov->moov_written = 1;
             return 0;
         }
 
@@ -4003,7 +4173,7 @@
         avio_write(s->pb, buf, buf_size);
         av_free(buf);
 
-        mov->fragments++;
+        mov->moov_written = 1;
         mov->mdat_size = 0;
         for (i = 0; i < mov->nb_streams; i++) {
             if (mov->tracks[i].entry)
@@ -4016,15 +4186,29 @@
         return 0;
     }
 
+    if (mov->frag_interleave) {
+        for (i = 0; i < mov->nb_streams; i++) {
+            MOVTrack *track = &mov->tracks[i];
+            int ret;
+            if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
+                return ret;
+        }
+
+        if (!mov->mdat_buf)
+            return 0;
+        mdat_size = avio_tell(mov->mdat_buf);
+    }
+
     for (i = 0; i < mov->nb_streams; i++) {
         MOVTrack *track = &mov->tracks[i];
-        if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF)
+        if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
             track->data_offset = 0;
         else
             track->data_offset = mdat_size;
-        if (!track->mdat_buf)
+        if (!track->entry)
             continue;
-        mdat_size += avio_tell(track->mdat_buf);
+        if (track->mdat_buf)
+            mdat_size += avio_tell(track->mdat_buf);
         if (first_track < 0)
             first_track = i;
     }
@@ -4063,10 +4247,18 @@
         if (track->entry)
             track->frag_start += duration;
         track->entry = 0;
-        if (!track->mdat_buf)
-            continue;
-        buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
-        track->mdat_buf = NULL;
+        track->entries_flushed = 0;
+        if (!mov->frag_interleave) {
+            if (!track->mdat_buf)
+                continue;
+            buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
+            track->mdat_buf = NULL;
+        } else {
+            if (!mov->mdat_buf)
+                continue;
+            buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
+            mov->mdat_buf = NULL;
+        }
 
         avio_write(s->pb, buf, buf_size);
         av_free(buf);
@@ -4081,12 +4273,13 @@
 static int mov_auto_flush_fragment(AVFormatContext *s)
 {
     MOVMuxContext *mov = s->priv_data;
+    int had_moov = mov->moov_written;
     int ret = mov_flush_fragment(s);
     if (ret < 0)
         return ret;
     // If using delay_moov, the first flush only wrote the moov,
     // not the actual moof+mdat pair, thus flush once again.
-    if (mov->fragments == 1 && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
+    if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
         ret = mov_flush_fragment(s);
     return ret;
 }
@@ -4118,7 +4311,14 @@
     }
     if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
         int ret;
-        if (mov->fragments > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
+        if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
+            if (mov->frag_interleave && mov->fragments > 0) {
+                if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
+                    if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
+                        return ret;
+                }
+            }
+
             if (!trk->mdat_buf) {
                 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
                     return ret;
@@ -4156,9 +4356,15 @@
         samples_in_chunk = 1;
 
     /* copy extradata if it exists */
-    if (trk->vos_len == 0 && enc->extradata_size > 0 && !TAG_IS_AVCI(trk->tag)) {
+    if (trk->vos_len == 0 && enc->extradata_size > 0 &&
+        !TAG_IS_AVCI(trk->tag) &&
+        (enc->codec_id != AV_CODEC_ID_DNXHD)) {
         trk->vos_len  = enc->extradata_size;
         trk->vos_data = av_malloc(trk->vos_len);
+        if (!trk->vos_data) {
+            ret = AVERROR(ENOMEM);
+            goto err;
+        }
         memcpy(trk->vos_data, enc->extradata, trk->vos_len);
     }
 
@@ -4191,13 +4397,15 @@
         } else {
             size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
         }
-    } else if (CONFIG_AC3_PARSER && enc->codec_id == AV_CODEC_ID_EAC3) {
+#if CONFIG_AC3_PARSER
+    } else if (enc->codec_id == AV_CODEC_ID_EAC3) {
         size = handle_eac3(mov, pkt, trk);
         if (size < 0)
             return size;
         else if (!size)
             goto end;
         avio_write(pb, pkt->data, size);
+#endif
     } else {
         avio_write(pb, pkt->data, size);
     }
@@ -4238,15 +4446,18 @@
              * of this packet to be what the previous packets duration implies. */
             trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
             /* We also may have written the pts and the corresponding duration
-             * in sidx tags; make sure the sidx pts and duration match up with
+             * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
              * the next fragment. This means the cts of the first sample must
              * be the same in all fragments. */
-            pkt->pts = pkt->dts + trk->start_cts;
+            if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_FASTSTART)) ||
+                mov->mode == MODE_ISM)
+                pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
         } else {
             /* New fragment, but discontinuous from previous fragments.
              * Pretend the duration sum of the earlier fragments is
              * pkt->dts - trk->start_dts. */
             trk->frag_start = pkt->dts - trk->start_dts;
+            trk->end_pts = AV_NOPTS_VALUE;
             trk->frag_discont = 0;
         }
     }
@@ -4268,7 +4479,7 @@
             trk->frag_start   = pkt->dts;
             trk->start_dts    = 0;
             trk->frag_discont = 0;
-        } else if (pkt->dts && mov->fragments >= 1)
+        } else if (pkt->dts && mov->moov_written)
             av_log(s, AV_LOG_WARNING,
                    "Track %d starts with a nonzero dts %"PRId64", while the moov "
                    "already has been written. Set the delay_moov flag to handle "
@@ -4288,9 +4499,16 @@
     trk->cluster[trk->entry].flags = 0;
     if (trk->start_cts == AV_NOPTS_VALUE)
         trk->start_cts = pkt->pts - pkt->dts;
+    if (trk->end_pts == AV_NOPTS_VALUE)
+        trk->end_pts = trk->cluster[trk->entry].dts +
+                       trk->cluster[trk->entry].cts + pkt->duration;
+    else
+        trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
+                                           trk->cluster[trk->entry].cts +
+                                           pkt->duration);
 
     if (enc->codec_id == AV_CODEC_ID_VC1) {
-        mov_parse_vc1_frame(pkt, trk, mov->fragments);
+        mov_parse_vc1_frame(pkt, trk);
     } else if (pkt->flags & AV_PKT_FLAG_KEY) {
         if (mov->mode == MODE_MOV && enc->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
             trk->entry > 0) { // force sync sample for the first key frame
@@ -4346,8 +4564,15 @@
              (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
               enc->codec_type == AVMEDIA_TYPE_VIDEO &&
               trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
-            if (frag_duration >= mov->min_fragment_duration)
+            if (frag_duration >= mov->min_fragment_duration) {
+                // Set the duration of this track to line up with the next
+                // sample in this track. This avoids relying on AVPacket
+                // duration, but only helps for this particular track, not
+                // for the other ones that are flushed at the same time.
+                trk->track_duration = pkt->dts - trk->start_dts;
+                trk->end_pts = pkt->pts;
                 mov_auto_flush_fragment(s);
+            }
         }
 
         return ff_mov_write_packet(s, pkt);
@@ -4548,12 +4773,16 @@
 
     /* encode context: tmcd data stream */
     track->enc = avcodec_alloc_context3(NULL);
+    if (!track->enc)
+        return AVERROR(ENOMEM);
     track->enc->codec_type = AVMEDIA_TYPE_DATA;
     track->enc->codec_tag  = track->tag;
     track->enc->time_base  = av_inv_q(rate);
 
     /* the tmcd track just contains one packet with the frame number */
     pkt.data = av_malloc(pkt.size);
+    if (!pkt.data)
+        return AVERROR(ENOMEM);
     AV_WB32(pkt.data, tc.start);
     ret = ff_mov_write_packet(s, &pkt);
     av_free(pkt.data);
@@ -4770,6 +4999,21 @@
     if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
         s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
 
+    /* Clear the omit_tfhd_offset flag if default_base_moof is set;
+     * if the latter is set that's enough and omit_tfhd_offset doesn't
+     * add anything extra on top of that. */
+    if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
+        mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
+        mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
+
+    if (mov->frag_interleave &&
+        mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
+        av_log(s, AV_LOG_ERROR,
+               "Sample interleaving in fragments is mutually exclusive with "
+               "omit_tfhd_offset and separate_moof\n");
+        return AVERROR(EINVAL);
+    }
+
     /* 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 &&
@@ -4855,6 +5099,7 @@
         track->hint_track = -1;
         track->start_dts  = AV_NOPTS_VALUE;
         track->start_cts  = AV_NOPTS_VALUE;
+        track->end_pts    = AV_NOPTS_VALUE;
         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
             if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
                 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
@@ -4933,9 +5178,13 @@
         if (st->codec->extradata_size) {
             if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
                 mov_create_dvd_sub_decoder_specific_info(track, st);
-            else if (!TAG_IS_AVCI(track->tag)){
+            else if (!TAG_IS_AVCI(track->tag) && st->codec->codec_id != AV_CODEC_ID_DNXHD) {
                 track->vos_len  = st->codec->extradata_size;
                 track->vos_data = av_malloc(track->vos_len);
+                if (!track->vos_data) {
+                    ret = AVERROR(ENOMEM);
+                    goto error;
+                }
                 memcpy(track->vos_data, st->codec->extradata, track->vos_len);
             }
         }
@@ -5036,7 +5285,7 @@
         !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
         if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
             return ret;
-        mov->fragments++;
+        mov->moov_written = 1;
         if (mov->flags & FF_MOV_FLAG_FASTSTART)
             mov->reserved_moov_pos = avio_tell(pb);
     }
diff --git a/libavformat/movenc.h b/libavformat/movenc.h
index 3a72937..744d14e 100644
--- a/libavformat/movenc.h
+++ b/libavformat/movenc.h
@@ -113,6 +113,7 @@
     int         tref_id; ///< trackID of the referenced track
     int64_t     start_dts;
     int64_t     start_cts;
+    int64_t     end_pts;
 
     int         hint_track;   ///< the track that hints this track, -1 if no hint track is set
     int         src_track;    ///< the track that this hint (or tmcd) track describes
@@ -131,6 +132,7 @@
     int64_t     data_offset;
     int64_t     frag_start;
     int         frag_discont;
+    int         entries_flushed;
 
     int         nb_frag_info;
     MOVFragmentInfo *frag_info;
@@ -139,6 +141,8 @@
     struct {
         int     first_packet_seq;
         int     first_packet_entry;
+        int     first_packet_seen;
+        int     first_frag_written;
         int     packet_seq;
         int     packet_entry;
         int     slices;
@@ -166,6 +170,7 @@
     int iods_video_profile;
     int iods_audio_profile;
 
+    int moov_written;
     int fragments;
     int max_fragment_duration;
     int min_fragment_duration;
@@ -185,6 +190,10 @@
     AVFormatContext *fc;
 
     int use_editlist;
+    float gamma;
+
+    int frag_interleave;
+    int missing_duration_warned;
 } MOVMuxContext;
 
 #define FF_MOV_FLAG_RTP_HINT              (1 <<  0)
@@ -202,6 +211,7 @@
 #define FF_MOV_FLAG_FRAG_DISCONT          (1 << 12)
 #define FF_MOV_FLAG_DELAY_MOOV            (1 << 13)
 #define FF_MOV_FLAG_WRITE_COLR            (1 << 14)
+#define FF_MOV_FLAG_WRITE_GAMA            (1 << 15)
 
 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt);
 
diff --git a/libavformat/movenchint.c b/libavformat/movenchint.c
index 006aa09..9e667ed 100644
--- a/libavformat/movenchint.c
+++ b/libavformat/movenchint.c
@@ -459,7 +459,6 @@
 void ff_mov_close_hinting(MOVTrack *track)
 {
     AVFormatContext *rtp_ctx = track->rtp_ctx;
-    uint8_t *ptr;
 
     av_freep(&track->enc);
     sample_queue_free(&track->sample_queue);
@@ -467,8 +466,7 @@
         return;
     if (rtp_ctx->pb) {
         av_write_trailer(rtp_ctx);
-        avio_close_dyn_buf(rtp_ctx->pb, &ptr);
-        av_free(ptr);
+        ffio_free_dyn_buf(&rtp_ctx->pb);
     }
     avformat_free_context(rtp_ctx);
 }
diff --git a/libavformat/mp3dec.c b/libavformat/mp3dec.c
index ff42280..369f822 100644
--- a/libavformat/mp3dec.c
+++ b/libavformat/mp3dec.c
@@ -32,6 +32,7 @@
 #include "id3v1.h"
 #include "replaygain.h"
 
+#include "libavcodec/avcodec.h"
 #include "libavcodec/mpegaudiodecheader.h"
 
 #define XING_FLAG_FRAMES 0x01
@@ -61,7 +62,10 @@
     int fsize, frames;
     uint32_t header;
     const uint8_t *buf, *buf0, *buf2, *end;
-    AVCodecContext avctx;
+    AVCodecContext *avctx = avcodec_alloc_context3(NULL);
+
+    if (!avctx)
+        return AVERROR(ENOMEM);
 
     buf0 = p->buf;
     end = p->buf + p->buf_size - sizeof(uint32_t);
@@ -79,7 +83,8 @@
         for(frames = 0; buf2 < end; frames++) {
             int dummy;
             header = AV_RB32(buf2);
-            fsize = avpriv_mpa_decode_header(&avctx, header, &dummy, &dummy, &dummy, &dummy);
+            fsize = avpriv_mpa_decode_header(avctx, header,
+                                             &dummy, &dummy, &dummy, &dummy);
             if(fsize < 0)
                 break;
             buf2 += fsize;
@@ -88,6 +93,7 @@
         if(buf == buf0)
             first_frames= frames;
     }
+    avcodec_free_context(&avctx);
     // keep this in sync with ac3 probe, both need to avoid
     // issues with MPEG-files!
     if   (first_frames>=4) return AVPROBE_SCORE_EXTENSION + 1;
@@ -405,17 +411,17 @@
     int64_t best_pos;
     int best_score;
 
-    if (mp3->is_cbr && st->duration > 0 && mp3->header_filesize > s->data_offset) {
+    if (mp3->is_cbr && st->duration > 0 && mp3->header_filesize > s->internal->data_offset) {
         int64_t filesize = avio_size(s->pb);
         int64_t duration;
-        if (filesize <= s->data_offset)
+        if (filesize <= s->internal->data_offset)
             filesize = mp3->header_filesize;
-        filesize -= s->data_offset;
-        duration = av_rescale(st->duration, filesize, mp3->header_filesize - s->data_offset);
+        filesize -= s->internal->data_offset;
+        duration = av_rescale(st->duration, filesize, mp3->header_filesize - s->internal->data_offset);
         ie = &ie1;
         timestamp = av_clip64(timestamp, 0, duration);
         ie->timestamp = timestamp;
-        ie->pos       = av_rescale(timestamp, filesize, duration) + s->data_offset;
+        ie->pos       = av_rescale(timestamp, filesize, duration) + s->internal->data_offset;
     } else if (mp3->xing_toc) {
         if (ret < 0)
             return ret;
diff --git a/libavformat/mpc.c b/libavformat/mpc.c
index 8f8ac9c..a62a3f2 100644
--- a/libavformat/mpc.c
+++ b/libavformat/mpc.c
@@ -31,12 +31,12 @@
 #define DELAY_FRAMES   32
 
 static const int mpc_rate[4] = { 44100, 48000, 37800, 32000 };
-typedef struct {
+typedef struct MPCFrame {
     int64_t pos;
     int size, skip;
 }MPCFrame;
 
-typedef struct {
+typedef struct MPCContext {
     int ver;
     uint32_t curframe, lastframe;
     uint32_t fcount;
diff --git a/libavformat/mpc8.c b/libavformat/mpc8.c
index a15dc25..0cef65f 100644
--- a/libavformat/mpc8.c
+++ b/libavformat/mpc8.c
@@ -27,7 +27,7 @@
 #include "avio_internal.h"
 
 /// Two-byte MPC tag
-#define MKMPCTAG(a, b) (a | (b << 8))
+#define MKMPCTAG(a, b) ((a) | ((b) << 8))
 
 #define TAG_MPCK MKTAG('M','P','C','K')
 
@@ -47,7 +47,7 @@
 
 static const int mpc8_rate[8] = { 44100, 48000, 37800, 32000, -1, -1, -1, -1 };
 
-typedef struct {
+typedef struct MPCContext {
     int ver;
     int64_t header_pos;
     int64_t samples;
@@ -57,7 +57,7 @@
 
 static inline int64_t bs_get_v(const uint8_t **bs)
 {
-    int64_t v = 0;
+    uint64_t v = 0;
     int br = 0;
     int c;
 
@@ -91,7 +91,7 @@
         size = bs_get_v(&bs);
         if (size < 2)
             return 0;
-        if (bs + size - 2 >= bs_end)
+        if (size >= bs_end - bs + 2)
             return AVPROBE_SCORE_EXTENSION - 1; // seems to be valid MPC but no header yet
         if (header_found) {
             if (size < 11 || size > 28)
@@ -108,7 +108,7 @@
 
 static inline int64_t gb_get_v(GetBitContext *gb)
 {
-    int64_t v = 0;
+    uint64_t v = 0;
     int bits = 0;
     while(get_bits1(gb) && bits < 64-7){
         v <<= 7;
@@ -223,6 +223,10 @@
     while(!avio_feof(pb)){
         pos = avio_tell(pb);
         mpc8_get_chunk_header(pb, &tag, &size);
+        if (size < 0) {
+            av_log(s, AV_LOG_ERROR, "Invalid chunk length\n");
+            return AVERROR_INVALIDDATA;
+        }
         if(tag == TAG_STREAMHDR)
             break;
         mpc8_handle_chunk(s, tag, pos, size);
diff --git a/libavformat/mpeg.c b/libavformat/mpeg.c
index f98d850..a0b5738 100644
--- a/libavformat/mpeg.c
+++ b/libavformat/mpeg.c
@@ -28,8 +28,6 @@
 # include "libavutil/bprint.h"
 #endif
 
-#undef NDEBUG
-#include <assert.h>
 #include "libavutil/avassert.h"
 
 /*********************************************/
diff --git a/libavformat/mpegenc.c b/libavformat/mpegenc.c
index 3ef2b24..b1b59ed 100644
--- a/libavformat/mpegenc.c
+++ b/libavformat/mpegenc.c
@@ -43,7 +43,7 @@
     struct PacketDesc *next;
 } PacketDesc;
 
-typedef struct {
+typedef struct StreamInfo {
     AVFifoBuffer *fifo;
     uint8_t id;
     int max_buffer_size; /* in bytes */
@@ -59,7 +59,7 @@
     int64_t vobu_start_pts;
 } StreamInfo;
 
-typedef struct {
+typedef struct MpegMuxContext {
     const AVClass *class;
     int packet_size; /* required packet size */
     int packet_number;
@@ -960,6 +960,7 @@
     int best_i = -1;
     int best_score = INT_MIN;
     int ignore_constraints = 0;
+    int ignore_delay = 0;
     int64_t scr = s->last_scr;
     PacketDesc *timestamp_packet;
     const int64_t max_delay = av_rescale(ctx->max_delay, 90000, AV_TIME_BASE);
@@ -985,7 +986,7 @@
         if (space < s->packet_size && !ignore_constraints)
             continue;
 
-        if (next_pkt && next_pkt->dts - scr > max_delay)
+        if (next_pkt && next_pkt->dts - scr > max_delay && !ignore_delay)
             continue;
         if (   stream->predecode_packet
             && stream->predecode_packet->size > stream->buffer_index)
@@ -999,6 +1000,7 @@
 
     if (best_i < 0) {
         int64_t best_dts = INT64_MAX;
+        int has_premux = 0;
 
         for (i = 0; i < ctx->nb_streams; i++) {
             AVStream *st = ctx->streams[i];
@@ -1006,21 +1008,29 @@
             PacketDesc *pkt_desc = stream->predecode_packet;
             if (pkt_desc && pkt_desc->dts < best_dts)
                 best_dts = pkt_desc->dts;
+            has_premux |= !!stream->premux_packet;
         }
 
-        av_dlog(ctx, "bumping scr, scr:%f, dts:%f\n",
-                scr / 90000.0, best_dts / 90000.0);
-        if (best_dts == INT64_MAX)
+        if (best_dts < INT64_MAX) {
+            av_dlog(ctx, "bumping scr, scr:%f, dts:%f\n",
+                    scr / 90000.0, best_dts / 90000.0);
+
+            if (scr >= best_dts + 1 && !ignore_constraints) {
+                av_log(ctx, AV_LOG_ERROR,
+                    "packet too large, ignoring buffer limits to mux it\n");
+                ignore_constraints = 1;
+            }
+            scr = FFMAX(best_dts + 1, scr);
+            if (remove_decoded_packets(ctx, scr) < 0)
+                return -1;
+        } else if (has_premux && flush) {
+            av_log(ctx, AV_LOG_ERROR,
+                  "delay too large, ignoring ...\n");
+            ignore_delay = 1;
+            ignore_constraints = 1;
+        } else
             return 0;
 
-        if (scr >= best_dts + 1 && !ignore_constraints) {
-            av_log(ctx, AV_LOG_ERROR,
-                   "packet too large, ignoring buffer limits to mux it\n");
-            ignore_constraints = 1;
-        }
-        scr = FFMAX(best_dts + 1, scr);
-        if (remove_decoded_packets(ctx, scr) < 0)
-            return -1;
         goto retry;
     }
 
diff --git a/libavformat/mpegts.c b/libavformat/mpegts.c
index 6fb186e..a4b6d4d 100644
--- a/libavformat/mpegts.c
+++ b/libavformat/mpegts.c
@@ -34,7 +34,6 @@
 #include "mpegts.h"
 #include "internal.h"
 #include "avio_internal.h"
-#include "seek.h"
 #include "mpeg.h"
 #include "isom.h"
 
@@ -519,7 +518,8 @@
     ts->pids[pid] = NULL;
 }
 
-static int analyze(const uint8_t *buf, int size, int packet_size, int *index)
+static int analyze(const uint8_t *buf, int size, int packet_size, int *index,
+                   int probe)
 {
     int stat[TS_MAX_PACKET_SIZE];
     int stat_all = 0;
@@ -529,7 +529,8 @@
     memset(stat, 0, packet_size * sizeof(*stat));
 
     for (i = 0; i < size - 3; i++) {
-        if (buf[i] == 0x47 && !(buf[i + 1] & 0x80) && buf[i + 3] != 0x47) {
+        if (buf[i] == 0x47 &&
+            (!probe || (!(buf[i + 1] & 0x80) && buf[i + 3] != 0x47))) {
             int x = i % packet_size;
             stat[x]++;
             stat_all++;
@@ -552,9 +553,9 @@
     if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
         return AVERROR_INVALIDDATA;
 
-    score      = analyze(buf, size, TS_PACKET_SIZE, NULL);
-    dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
-    fec_score  = analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
+    score      = analyze(buf, size, TS_PACKET_SIZE,      NULL, 0);
+    dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL, 0);
+    fec_score  = analyze(buf, size, TS_FEC_PACKET_SIZE,  NULL, 0);
     av_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n",
             score, dvhs_score, fec_score);
 
@@ -595,7 +596,7 @@
     int c;
 
     p = *pp;
-    if ((p + 1) >= p_end)
+    if (1 >= p_end - p)
         return AVERROR_INVALIDDATA;
     c   = AV_RB16(p);
     p  += 2;
@@ -614,7 +615,7 @@
     len = get8(&p, p_end);
     if (len < 0)
         return NULL;
-    if ((p + len) > p_end)
+    if (len > p_end - p)
         return NULL;
     str = av_malloc(len + 1);
     if (!str)
@@ -655,7 +656,7 @@
     return 0;
 }
 
-typedef struct {
+typedef struct StreamType {
     uint32_t stream_type;
     enum AVMediaType codec_type;
     enum AVCodecID codec_id;
@@ -1214,7 +1215,7 @@
 }
 
 #define MAX_LEVEL 4
-typedef struct {
+typedef struct MP4DescrParseContext {
     AVFormatContext *s;
     AVIOContext pb;
     Mp4Descr *descr;
@@ -2180,7 +2181,7 @@
         if (is_start) {
             /* pointer field present */
             len = *p++;
-            if (p + len > p_end)
+            if (len > p_end - p)
                 return 0;
             if (len && cc_ok) {
                 /* write remaining section bytes */
@@ -2395,9 +2396,9 @@
 
     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);
+        int score      = analyze(p->buf + TS_PACKET_SIZE     *i, TS_PACKET_SIZE     *left, TS_PACKET_SIZE     , NULL, 1);
+        int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL, 1);
+        int fec_score  = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL, 1);
         score = FFMAX3(score, dvhs_score, fec_score);
         sumscore += score;
         maxscore = FFMAX(maxscore, score);
diff --git a/libavformat/mpegtsenc.c b/libavformat/mpegtsenc.c
index 8d0da0b..cc650bb 100644
--- a/libavformat/mpegtsenc.c
+++ b/libavformat/mpegtsenc.c
@@ -30,6 +30,7 @@
 #include "libavcodec/internal.h"
 
 #include "avformat.h"
+#include "avio_internal.h"
 #include "internal.h"
 #include "mpegts.h"
 
@@ -57,6 +58,16 @@
     int pcr_packet_period;
 } MpegTSService;
 
+// service_type values as defined in ETSI 300 468
+enum {
+    MPEGTS_SERVICE_TYPE_DIGITAL_TV                   = 0x01,
+    MPEGTS_SERVICE_TYPE_DIGITAL_RADIO                = 0x02,
+    MPEGTS_SERVICE_TYPE_TELETEXT                     = 0x03,
+    MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_RADIO = 0x0A,
+    MPEGTS_SERVICE_TYPE_MPEG2_DIGITAL_HDTV           = 0x11,
+    MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_SDTV  = 0x16,
+    MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_HDTV  = 0x19
+};
 typedef struct MpegTSWrite {
     const AVClass *av_class;
     MpegTSSection pat; /* MPEG2 pat table */
@@ -76,6 +87,7 @@
     int transport_stream_id;
     int original_network_id;
     int service_id;
+    int service_type;
 
     int pmt_start_pid;
     int start_pid;
@@ -521,7 +533,7 @@
         *q++         = 0x48;
         desc_len_ptr = q;
         q++;
-        *q++         = 0x01; /* digital television service */
+        *q++         = ts->service_type;
         putstr8(&q, service->provider_name);
         putstr8(&q, service->name);
         desc_len_ptr[0] = q - desc_len_ptr - 1;
@@ -1191,7 +1203,7 @@
 
 int ff_check_h264_startcode(AVFormatContext *s, const AVStream *st, const AVPacket *pkt)
 {
-    if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
+    if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001 && AV_RB24(pkt->data) != 0x000001) {
         if (!st->nb_frames) {
             av_log(s, AV_LOG_ERROR, "H.264 bitstream malformed, "
                    "no startcode found, use the video bitstream filter 'h264_mp4toannexb' to fix it "
@@ -1259,26 +1271,35 @@
     if (st->codec->codec_id == AV_CODEC_ID_H264) {
         const uint8_t *p = buf, *buf_end = p + size;
         uint32_t state = -1;
+        int extradd = (pkt->flags & AV_PKT_FLAG_KEY) ? st->codec->extradata_size : 0;
         int ret = ff_check_h264_startcode(s, st, pkt);
         if (ret < 0)
             return ret;
 
+        if (extradd && AV_RB24(st->codec->extradata) > 1)
+            extradd = 0;
+
         do {
             p = avpriv_find_start_code(p, buf_end, &state);
             av_dlog(s, "nal %d\n", state & 0x1f);
+            if ((state & 0x1f) == 7)
+                extradd = 0;
         } while (p < buf_end && (state & 0x1f) != 9 &&
                  (state & 0x1f) != 5 && (state & 0x1f) != 1);
 
+        if ((state & 0x1f) != 5)
+            extradd = 0;
         if ((state & 0x1f) != 9) { // AUD NAL
-            data = av_malloc(pkt->size + 6);
+            data = av_malloc(pkt->size + 6 + extradd);
             if (!data)
                 return AVERROR(ENOMEM);
-            memcpy(data + 6, pkt->data, pkt->size);
+            memcpy(data + 6, st->codec->extradata, extradd);
+            memcpy(data + 6 + extradd, pkt->data, pkt->size);
             AV_WB32(data, 0x00000001);
             data[4] = 0x09;
             data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
             buf     = data;
-            size    = pkt->size + 6;
+            size    = pkt->size + 6 + extradd;
         }
     } else if (st->codec->codec_id == AV_CODEC_ID_AAC) {
         if (pkt->size < 2) {
@@ -1307,9 +1328,7 @@
 
             ret = av_write_frame(ts_st->amux, &pkt2);
             if (ret < 0) {
-                avio_close_dyn_buf(ts_st->amux->pb, &data);
-                ts_st->amux->pb = NULL;
-                av_free(data);
+                ffio_free_dyn_buf(&ts_st->amux->pb);
                 return ret;
             }
             size            = avio_close_dyn_buf(ts_st->amux->pb, &data);
@@ -1434,6 +1453,30 @@
     { "mpegts_service_id", "Set service_id field.",
       offsetof(MpegTSWrite, service_id), AV_OPT_TYPE_INT,
       { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
+    { "mpegts_service_type", "Set service_type field.",
+      offsetof(MpegTSWrite, service_type), AV_OPT_TYPE_INT,
+      { .i64 = 0x01 }, 0x01, 0xff, AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
+    { "digital_tv", "Digital Television.",
+      0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_DIGITAL_TV }, 0x01, 0xff,
+      AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
+    { "digital_radio", "Digital Radio.",
+      0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_DIGITAL_RADIO }, 0x01, 0xff,
+      AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
+    { "teletext", "Teletext.",
+      0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_TELETEXT }, 0x01, 0xff,
+      AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
+    { "advanced_codec_digital_radio", "Advanced Codec Digital Radio.",
+      0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_RADIO }, 0x01, 0xff,
+      AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
+    { "mpeg2_digital_hdtv", "MPEG2 Digital HDTV.",
+      0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_MPEG2_DIGITAL_HDTV }, 0x01, 0xff,
+      AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
+    { "advanced_codec_digital_sdtv", "Advanced Codec Digital SDTV.",
+      0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_SDTV }, 0x01, 0xff,
+      AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
+    { "advanced_codec_digital_hdtv", "Advanced Codec Digital HDTV.",
+      0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_HDTV }, 0x01, 0xff,
+      AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
     { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
       offsetof(MpegTSWrite, pmt_start_pid), AV_OPT_TYPE_INT,
       { .i64 = 0x1000 }, 0x0010, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM },
diff --git a/libavformat/mpegvideodec.c b/libavformat/mpegvideodec.c
index ade76d8..aca9621 100644
--- a/libavformat/mpegvideodec.c
+++ b/libavformat/mpegvideodec.c
@@ -24,6 +24,7 @@
 #include "rawdec.h"
 
 #include "libavutil/intreadwrite.h"
+#include "libavcodec/internal.h"
 
 #define SEQ_START_CODE          0x000001b3
 #define GOP_START_CODE          0x000001b8
@@ -37,26 +38,27 @@
 {
     uint32_t code= -1;
     int pic=0, seq=0, slice=0, pspack=0, vpes=0, apes=0, res=0, sicle=0;
-    int i, j;
+    const uint8_t *ptr = p->buf, *end = ptr + p->buf_size;
     uint32_t last = 0;
+    int j;
 
-    for(i=0; i<p->buf_size; i++){
-        code = (code<<8) + p->buf[i];
+    while (ptr < end) {
+        ptr = avpriv_find_start_code(ptr, end, &code);
         if ((code & 0xffffff00) == 0x100) {
             switch(code){
             case     SEQ_START_CODE:
-                if (!(p->buf[i+1+3+1+2] & 0x20))
+                if (!(ptr[3 + 1 + 2] & 0x20))
                     break;
-                j = i;
-                if (p->buf[j+8] & 2)
+                j = -1;
+                if (ptr[j + 8] & 2)
                     j+= 64;
-                if (j >= p->buf_size)
+                if (j >= end - ptr)
                     break;
-                if (p->buf[j+8] & 1)
+                if (ptr[j + 8] & 1)
                     j+= 64;
-                if (j >= p->buf_size)
+                if (j >= end - ptr)
                     break;
-                if (AV_RB24(p->buf + j + 9) & 0xFFFFFE)
+                if (AV_RB24(ptr + j + 9) & 0xFFFFFE)
                     break;
                 seq++;
             break;
diff --git a/libavformat/mtv.c b/libavformat/mtv.c
index addad24..a91e4c8 100644
--- a/libavformat/mtv.c
+++ b/libavformat/mtv.c
@@ -200,7 +200,7 @@
     AVIOContext *pb = s->pb;
     int ret;
 
-    if((avio_tell(pb) - s->data_offset + mtv->img_segment_size) % mtv->full_segment_size)
+    if((avio_tell(pb) - s->internal->data_offset + mtv->img_segment_size) % mtv->full_segment_size)
     {
         avio_skip(pb, MTV_AUDIO_PADDING_SIZE);
 
diff --git a/libavformat/mux.c b/libavformat/mux.c
index 052f649..ee45057 100644
--- a/libavformat/mux.c
+++ b/libavformat/mux.c
@@ -44,9 +44,6 @@
 #include "network.h"
 #endif
 
-#undef NDEBUG
-#include <assert.h>
-
 /**
  * @file
  * muxing functions for use within libavformat
@@ -578,16 +575,16 @@
         AVStream *st = s->streams[pkt->stream_index];
         int64_t offset = st->mux_ts_offset;
 
-        if (s->offset == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
+        if (s->internal->offset == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
             (pkt->dts < 0 || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)) {
-            s->offset = -pkt->dts;
-            s->offset_timebase = st->time_base;
+            s->internal->offset = -pkt->dts;
+            s->internal->offset_timebase = st->time_base;
         }
 
-        if (s->offset != AV_NOPTS_VALUE && !offset) {
+        if (s->internal->offset != AV_NOPTS_VALUE && !offset) {
             offset = st->mux_ts_offset =
-                av_rescale_q_rnd(s->offset,
-                                 s->offset_timebase,
+                av_rescale_q_rnd(s->internal->offset,
+                                 s->internal->offset_timebase,
                                  st->time_base,
                                  AV_ROUND_UP);
         }
@@ -717,7 +714,7 @@
     if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
         next_point = &(st->last_in_packet_buffer->next);
     } else {
-        next_point = &s->packet_buffer;
+        next_point = &s->internal->packet_buffer;
     }
 
     if (chunked) {
@@ -741,7 +738,7 @@
         if (chunked && !(this_pktl->pkt.flags & CHUNK_START))
             goto next_non_null;
 
-        if (compare(s, &s->packet_buffer_end->pkt, pkt)) {
+        if (compare(s, &s->internal->packet_buffer_end->pkt, pkt)) {
             while (   *next_point
                    && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
                        || !compare(s, &(*next_point)->pkt, pkt)))
@@ -749,12 +746,12 @@
             if (*next_point)
                 goto next_non_null;
         } else {
-            next_point = &(s->packet_buffer_end->next);
+            next_point = &(s->internal->packet_buffer_end->next);
         }
     }
     av_assert1(!*next_point);
 
-    s->packet_buffer_end = this_pktl;
+    s->internal->packet_buffer_end = this_pktl;
 next_non_null:
 
     this_pktl->next = *next_point;
@@ -815,11 +812,11 @@
         flush = 1;
 
     if (s->max_interleave_delta > 0 &&
-        s->packet_buffer &&
+        s->internal->packet_buffer &&
         !flush &&
         s->internal->nb_interleaved_streams == stream_count+noninterleaved_count
     ) {
-        AVPacket *top_pkt = &s->packet_buffer->pkt;
+        AVPacket *top_pkt = &s->internal->packet_buffer->pkt;
         int64_t delta_dts = INT64_MIN;
         int64_t top_dts = av_rescale_q(top_pkt->dts,
                                        s->streams[top_pkt->stream_index]->time_base,
@@ -849,13 +846,13 @@
 
     if (stream_count && flush) {
         AVStream *st;
-        pktl = s->packet_buffer;
+        pktl = s->internal->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;
+        s->internal->packet_buffer = pktl->next;
+        if (!s->internal->packet_buffer)
+            s->internal->packet_buffer_end = NULL;
 
         if (st->last_in_packet_buffer == pktl)
             st->last_in_packet_buffer = NULL;
diff --git a/libavformat/mvdec.c b/libavformat/mvdec.c
index c8a5ebf..7aa6452 100644
--- a/libavformat/mvdec.c
+++ b/libavformat/mvdec.c
@@ -408,7 +408,7 @@
     AVStream *st = avctx->streams[mv->stream_index];
     const AVIndexEntry *index;
     int frame = mv->frame[mv->stream_index];
-    int ret;
+    int64_t ret;
     uint64_t pos;
 
     if (frame < st->nb_index_entries) {
diff --git a/libavformat/mxf.c b/libavformat/mxf.c
index 14d143e..61b37f8 100644
--- a/libavformat/mxf.c
+++ b/libavformat/mxf.c
@@ -50,6 +50,7 @@
     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x00,0x00 }, 14,       AV_CODEC_ID_H264 }, /* H.264/MPEG-4 AVC Intra */
     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x31,0x11,0x01 }, 14,       AV_CODEC_ID_H264 }, /* H.264/MPEG-4 AVC SPS/PPS in-band */
     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x01,0x01,0x02,0x02,0x01 }, 16,       AV_CODEC_ID_V210 }, /* V210 */
+    { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0E,0x04,0x02,0x01,0x02,0x11,0x04,0x00 }, 15,     AV_CODEC_ID_PRORES }, /* PRORES */
     /* SoundEssenceCompression */
     { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x03,0x04,0x02,0x02,0x02,0x03,0x03,0x01,0x00 }, 14,        AV_CODEC_ID_AAC }, /* MPEG2 AAC ADTS (legacy) */
     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 }, 13,  AV_CODEC_ID_PCM_S16LE }, /* Uncompressed */
diff --git a/libavformat/mxf.h b/libavformat/mxf.h
index d9e17c6..71a4084 100644
--- a/libavformat/mxf.h
+++ b/libavformat/mxf.h
@@ -47,6 +47,7 @@
     EssenceContainerData,
     TypeBottom,// add metadata type before this
     EssenceGroup,
+    TaggedValue,
 };
 
 enum MXFFrameLayout {
diff --git a/libavformat/mxfdec.c b/libavformat/mxfdec.c
index 181e9e6..b60a56d 100644
--- a/libavformat/mxfdec.c
+++ b/libavformat/mxfdec.c
@@ -75,7 +75,7 @@
     OPSONYOpt,  /* FATE sample, violates the spec in places */
 } MXFOP;
 
-typedef struct {
+typedef struct MXFPartition {
     int closed;
     int complete;
     MXFPartitionType type;
@@ -92,13 +92,13 @@
     int64_t pack_ofs;               ///< absolute offset of pack in file, including run-in
 } MXFPartition;
 
-typedef struct {
+typedef struct MXFCryptoContext {
     UID uid;
     enum MXFMetadataSetType type;
     UID source_container_ul;
 } MXFCryptoContext;
 
-typedef struct {
+typedef struct MXFStructuralComponent {
     UID uid;
     enum MXFMetadataSetType type;
     UID source_package_uid;
@@ -108,7 +108,7 @@
     int source_track_id;
 } MXFStructuralComponent;
 
-typedef struct {
+typedef struct MXFSequence {
     UID uid;
     enum MXFMetadataSetType type;
     UID data_definition_ul;
@@ -118,7 +118,7 @@
     uint8_t origin;
 } MXFSequence;
 
-typedef struct {
+typedef struct MXFTrack {
     UID uid;
     enum MXFMetadataSetType type;
     int drop_frame;
@@ -144,6 +144,13 @@
 typedef struct {
     UID uid;
     enum MXFMetadataSetType type;
+    char *name;
+    char *value;
+} MXFTaggedValue;
+
+typedef struct {
+    UID uid;
+    enum MXFMetadataSetType type;
     MXFSequence *sequence; /* mandatory, and only one */
     UID sequence_ref;
     int track_id;
@@ -154,7 +161,7 @@
     int64_t original_duration; /* st->duration in SampleRate/EditRate units */
 } MXFTrack;
 
-typedef struct {
+typedef struct MXFDescriptor {
     UID uid;
     enum MXFMetadataSetType type;
     UID essence_container_ul;
@@ -181,7 +188,7 @@
     enum AVPixelFormat pix_fmt;
 } MXFDescriptor;
 
-typedef struct {
+typedef struct MXFIndexTableSegment {
     UID uid;
     enum MXFMetadataSetType type;
     int edit_unit_byte_count;
@@ -196,7 +203,7 @@
     int nb_index_entries;
 } MXFIndexTableSegment;
 
-typedef struct {
+typedef struct MXFPackage {
     UID uid;
     enum MXFMetadataSetType type;
     UID package_uid;
@@ -206,15 +213,17 @@
     MXFDescriptor *descriptor; /* only one */
     UID descriptor_ref;
     char *name;
+    UID *comment_refs;
+    int comment_count;
 } MXFPackage;
 
-typedef struct {
+typedef struct MXFMetadataSet {
     UID uid;
     enum MXFMetadataSetType type;
 } MXFMetadataSet;
 
 /* decoded index table */
-typedef struct {
+typedef struct MXFIndexTable {
     int index_sid;
     int body_sid;
     int nb_ptses;               /* number of PTSes or total duration of index */
@@ -225,7 +234,7 @@
     AVIndexEntry *fake_index;   /* used for calling ff_index_search_timestamp() */
 } MXFIndexTable;
 
-typedef struct {
+typedef struct MXFContext {
     MXFPartition *partitions;
     unsigned partitions_count;
     MXFOP op;
@@ -259,7 +268,7 @@
 /* NOTE: klv_offset is not set (-1) for local keys */
 typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset);
 
-typedef struct {
+typedef struct MXFMetadataReadTableEntry {
     const UID key;
     MXFMetadataReadFunc *read;
     int ctx_size;
@@ -281,6 +290,9 @@
 static const uint8_t mxf_random_index_pack_key[]           = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x11,0x01,0x00 };
 static const uint8_t mxf_sony_mpeg4_extradata[]            = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 };
 static const uint8_t mxf_avid_project_name[]               = { 0xa5,0xfb,0x7b,0x25,0xf6,0x15,0x94,0xb9,0x62,0xfc,0x37,0x17,0x49,0x2d,0x42,0xbf };
+static const uint8_t mxf_jp2k_rsiz[]                       = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 };
+static const uint8_t mxf_indirect_value_utf16le[]          = { 0x4c,0x00,0x02,0x10,0x01,0x00,0x00,0x00,0x00,0x06,0x0e,0x2b,0x34,0x01,0x04,0x01,0x01 };
+static const uint8_t mxf_indirect_value_utf16be[]          = { 0x42,0x01,0x10,0x02,0x00,0x00,0x00,0x00,0x00,0x06,0x0e,0x2b,0x34,0x01,0x04,0x01,0x01 };
 
 #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
 
@@ -304,6 +316,11 @@
     case MaterialPackage:
         av_freep(&((MXFPackage *)*ctx)->tracks_refs);
         av_freep(&((MXFPackage *)*ctx)->name);
+        av_freep(&((MXFPackage *)*ctx)->comment_refs);
+        break;
+    case TaggedValue:
+        av_freep(&((MXFTaggedValue *)*ctx)->name);
+        av_freep(&((MXFTaggedValue *)*ctx)->value);
         break;
     case IndexTableSegment:
         seg = (MXFIndexTableSegment *)*ctx;
@@ -671,6 +688,19 @@
     return 0;
 }
 
+static int mxf_read_strong_ref_array(AVIOContext *pb, UID **refs, int *count)
+{
+    *count = avio_rb32(pb);
+    *refs = av_calloc(*count, sizeof(UID));
+    if (!*refs) {
+        *count = 0;
+        return AVERROR(ENOMEM);
+    }
+    avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
+    avio_read(pb, (uint8_t *)*refs, *count * sizeof(UID));
+    return 0;
+}
+
 static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
 {
     MXFContext *mxf = arg;
@@ -679,13 +709,7 @@
         if (mxf->packages_refs)
             av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple packages_refs\n");
         av_free(mxf->packages_refs);
-        mxf->packages_count = avio_rb32(pb);
-        mxf->packages_refs = av_calloc(mxf->packages_count, sizeof(UID));
-        if (!mxf->packages_refs)
-            return AVERROR(ENOMEM);
-        avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
-        avio_read(pb, (uint8_t *)mxf->packages_refs, mxf->packages_count * sizeof(UID));
-        break;
+        return mxf_read_strong_ref_array(pb, &mxf->packages_refs, &mxf->packages_count);
     }
     return 0;
 }
@@ -775,15 +799,8 @@
         sequence->origin = avio_r8(pb);
         break;
     case 0x1001:
-        sequence->structural_components_count = avio_rb32(pb);
-        sequence->structural_components_refs = av_calloc(sequence->structural_components_count, sizeof(UID));
-        if (!sequence->structural_components_refs) {
-            sequence->structural_components_count = 0;
-            return AVERROR(ENOMEM);
-        }
-        avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
-        avio_read(pb, (uint8_t *)sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));
-        break;
+        return mxf_read_strong_ref_array(pb, &sequence->structural_components_refs,
+                                             &sequence->structural_components_count);
     }
     return 0;
 }
@@ -796,20 +813,13 @@
         essence_group->duration = avio_rb64(pb);
         break;
     case 0x0501:
-        essence_group->structural_components_count = avio_rb32(pb);
-        essence_group->structural_components_refs = av_calloc(essence_group->structural_components_count, sizeof(UID));
-        if (!essence_group->structural_components_refs) {
-            essence_group->structural_components_count = 0;
-            return AVERROR(ENOMEM);
-        }
-        avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
-        avio_read(pb, (uint8_t *)essence_group->structural_components_refs, essence_group->structural_components_count * sizeof(UID));
-        break;
+        return mxf_read_strong_ref_array(pb, &essence_group->structural_components_refs,
+                                             &essence_group->structural_components_count);
     }
     return 0;
 }
 
-static int mxf_read_utf16_string(AVIOContext *pb, int size, char** str)
+static inline int mxf_read_utf16_string(AVIOContext *pb, int size, char** str, int be)
 {
     int ret;
     size_t buf_size;
@@ -822,7 +832,12 @@
     if (!*str)
         return AVERROR(ENOMEM);
 
-    if ((ret = avio_get_str16be(pb, size, *str, buf_size)) < 0) {
+    if (be)
+        ret = avio_get_str16be(pb, size, *str, buf_size);
+    else
+        ret = avio_get_str16le(pb, size, *str, buf_size);
+
+    if (ret < 0) {
         av_freep(str);
         return ret;
     }
@@ -830,18 +845,22 @@
     return ret;
 }
 
+#define READ_STR16(type, big_endian)                                               \
+static int mxf_read_utf16 ## type ##_string(AVIOContext *pb, int size, char** str) \
+{                                                                                  \
+return mxf_read_utf16_string(pb, size, str, big_endian);                           \
+}
+READ_STR16(be, 1)
+READ_STR16(le, 0)
+#undef READ_STR16
+
 static int mxf_read_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
 {
     MXFPackage *package = arg;
     switch(tag) {
     case 0x4403:
-        package->tracks_count = avio_rb32(pb);
-        package->tracks_refs = av_calloc(package->tracks_count, sizeof(UID));
-        if (!package->tracks_refs)
-            return AVERROR(ENOMEM);
-        avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
-        avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
-        break;
+        return mxf_read_strong_ref_array(pb, &package->tracks_refs,
+                                             &package->tracks_count);
     case 0x4401:
         /* UMID */
         avio_read(pb, package->package_ul, 16);
@@ -851,7 +870,10 @@
         avio_read(pb, package->descriptor_ref, 16);
         break;
     case 0x4402:
-        return mxf_read_utf16_string(pb, size, &package->name);
+        return mxf_read_utf16be_string(pb, size, &package->name);
+    case 0x4406:
+        return mxf_read_strong_ref_array(pb, &package->comment_refs,
+                                             &package->comment_count);
     }
     return 0;
 }
@@ -944,13 +966,8 @@
     MXFDescriptor *descriptor = arg;
     switch(tag) {
     case 0x3F01:
-        descriptor->sub_descriptors_count = avio_rb32(pb);
-        descriptor->sub_descriptors_refs = av_calloc(descriptor->sub_descriptors_count, sizeof(UID));
-        if (!descriptor->sub_descriptors_refs)
-            return AVERROR(ENOMEM);
-        avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
-        avio_read(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
-        break;
+        return mxf_read_strong_ref_array(pb, &descriptor->sub_descriptors_refs,
+                                             &descriptor->sub_descriptors_count);
     case 0x3002: /* ContainerDuration */
         descriptor->duration = avio_rb64(pb);
         break;
@@ -1017,11 +1034,47 @@
             descriptor->extradata_size = size;
             avio_read(pb, descriptor->extradata, size);
         }
+        if (IS_KLV_KEY(uid, mxf_jp2k_rsiz)) {
+            uint32_t rsiz = avio_rb16(pb);
+            if (rsiz == FF_PROFILE_JPEG2000_DCINEMA_2K ||
+                rsiz == FF_PROFILE_JPEG2000_DCINEMA_4K)
+                descriptor->pix_fmt = AV_PIX_FMT_XYZ12;
+        }
         break;
     }
     return 0;
 }
 
+static int mxf_read_indirect_value(void *arg, AVIOContext *pb, int size)
+{
+    MXFTaggedValue *tagged_value = arg;
+    uint8_t key[17];
+
+    if (size <= 17)
+        return 0;
+
+    avio_read(pb, key, 17);
+    /* TODO: handle other types of of indirect values */
+    if (memcmp(key, mxf_indirect_value_utf16le, 17) == 0) {
+        return mxf_read_utf16le_string(pb, size - 17, &tagged_value->value);
+    } else if (memcmp(key, mxf_indirect_value_utf16be, 17) == 0) {
+        return mxf_read_utf16be_string(pb, size - 17, &tagged_value->value);
+    }
+    return 0;
+}
+
+static int mxf_read_tagged_value(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
+{
+    MXFTaggedValue *tagged_value = arg;
+    switch (tag){
+    case 0x5001:
+        return mxf_read_utf16be_string(pb, size, &tagged_value->name);
+    case 0x5003:
+        return mxf_read_indirect_value(tagged_value, pb, size);
+    }
+    return 0;
+}
+
 /*
  * Match an uid independently of the version byte and up to len common bytes
  * Returns: boolean
@@ -1640,6 +1693,28 @@
     return NULL;
 }
 
+static int mxf_parse_package_comments(MXFContext *mxf, AVDictionary **pm, MXFPackage *package)
+{
+    MXFTaggedValue *tag;
+    int size, i;
+    char *key = NULL;
+
+    for (i = 0; i < package->comment_count; i++) {
+        tag = mxf_resolve_strong_ref(mxf, &package->comment_refs[i], TaggedValue);
+        if (!tag || !tag->name || !tag->value)
+            continue;
+
+        size = strlen(tag->name) + 8 + 1;
+        key = av_mallocz(size);
+        if (!key)
+            return AVERROR(ENOMEM);
+
+        snprintf(key, size, "comment_%s", tag->name);
+        av_dict_set(pm, key, tag->value, AV_DICT_DONT_STRDUP_KEY);
+    }
+    return 0;
+}
+
 static int mxf_parse_physical_source_package(MXFContext *mxf, MXFTrack *source_track, AVStream *st)
 {
     MXFPackage *physical_package = NULL;
@@ -1719,6 +1794,7 @@
     mxf_add_umid_metadata(&mxf->fc->metadata, "material_package_umid", material_package);
     if (material_package->name && material_package->name[0])
         av_dict_set(&mxf->fc->metadata, "material_package_name", material_package->name, 0);
+    mxf_parse_package_comments(mxf, &mxf->fc->metadata, material_package);
 
     for (i = 0; i < material_package->tracks_count; i++) {
         MXFPackage *source_package = NULL;
@@ -2051,13 +2127,13 @@
     if (!*str)
         return AVERROR(ENOMEM);
     if (!strftime(*str, 32, "%Y-%m-%d %H:%M:%S", &time))
-        str[0] = '\0';
+        (*str)[0] = '\0';
 
     return 0;
 }
 
 #define SET_STR_METADATA(pb, name, str) do { \
-    if ((ret = mxf_read_utf16_string(pb, size, &str)) < 0) \
+    if ((ret = mxf_read_utf16be_string(pb, size, &str)) < 0) \
         return ret; \
     av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \
 } while (0)
@@ -2146,6 +2222,7 @@
     { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0f,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence },
     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01,0x01,0x05,0x00 }, mxf_read_essence_group, sizeof(MXFEssenceGroup), EssenceGroup},
     { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip },
+    { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3f,0x00 }, mxf_read_tagged_value, sizeof(MXFTaggedValue), TaggedValue },
     { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor },
     { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x42,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Generic Sound */
     { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */
diff --git a/libavformat/mxfenc.c b/libavformat/mxfenc.c
index a850239..ac60357 100644
--- a/libavformat/mxfenc.c
+++ b/libavformat/mxfenc.c
@@ -52,23 +52,24 @@
 #include "config.h"
 
 extern AVOutputFormat ff_mxf_d10_muxer;
+extern AVOutputFormat ff_mxf_opatom_muxer;
 
 #define EDIT_UNITS_PER_BODY 250
 #define KAG_SIZE 512
 
-typedef struct {
+typedef struct MXFLocalTagPair {
     int local_tag;
     UID uid;
 } MXFLocalTagPair;
 
-typedef struct {
+typedef struct MXFIndexEntry {
     uint8_t flags;
     uint64_t offset;
     unsigned slice_offset; ///< offset of audio slice
     uint16_t temporal_ref;
 } MXFIndexEntry;
 
-typedef struct {
+typedef struct MXFStreamContext {
     AudioInterleaveContext aic;
     UID track_essence_element_key;
     int index;               ///< index in mxf_essence_container_uls table
@@ -83,7 +84,7 @@
     int video_bit_rate;
 } MXFStreamContext;
 
-typedef struct {
+typedef struct MXFContainerEssenceEntry {
     UID container_ul;
     UID element_ul;
     UID codec_ul;
@@ -311,6 +312,7 @@
     uint32_t instance_number;
     uint8_t umid[16];        ///< unique material identifier
     int channel_count;
+    uint32_t tagged_value_count;
 } MXFContext;
 
 static const uint8_t uuid_base[]            = { 0xAD,0xAB,0x44,0x24,0x2f,0x25,0x4d,0xc7,0x92,0xff,0x29,0xbd };
@@ -320,6 +322,7 @@
  * complete key for operation pattern, partitions, and primer pack
  */
 static const uint8_t op1a_ul[]                     = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x01,0x09,0x00 };
+static const uint8_t opatom_ul[]                   = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x02,0x01,0x10,0x03,0x00,0x00 };
 static const uint8_t footer_partition_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }; // ClosedComplete
 static const uint8_t primer_pack_key[]             = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x05,0x01,0x00 };
 static const uint8_t index_table_segment_key[]     = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 };
@@ -365,7 +368,9 @@
     { 0x4401, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x10,0x00,0x00,0x00,0x00}}, /* Package UID */
     { 0x4405, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x01,0x03,0x00,0x00}}, /* Package Creation Date */
     { 0x4404, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x05,0x00,0x00}}, /* Package Modified Date */
+    { 0x4402, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x03,0x03,0x02,0x01,0x00,0x00,0x00}}, /* Package Name */
     { 0x4403, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x05,0x00,0x00}}, /* Tracks Strong reference array */
+    { 0x4406, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x02,0x01,0x02,0x0C,0x00,0x00,0x00}}, /* User Comments */
     { 0x4701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x03,0x00,0x00}}, /* Descriptor */
     // Track
     { 0x4801, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x07,0x01,0x01,0x00,0x00,0x00,0x00}}, /* Track ID */
@@ -385,10 +390,14 @@
     { 0x1501, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x05,0x00,0x00}}, /* Start Time Code */
     { 0x1502, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x04,0x01,0x01,0x02,0x06,0x00,0x00}}, /* Rounded Time Code Base */
     { 0x1503, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x04,0x01,0x01,0x05,0x00,0x00,0x00}}, /* Drop Frame */
+    // Tagged Value
+    { 0x5001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x02,0x01,0x02,0x09,0x01,0x00,0x00}}, /* Name */
+    { 0x5003, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x02,0x01,0x02,0x0A,0x01,0x00,0x00}}, /* Value */
     // File Descriptor
     { 0x3F01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x04,0x06,0x0B,0x00,0x00}}, /* Sub Descriptors reference array */
     { 0x3006, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x06,0x01,0x01,0x03,0x05,0x00,0x00,0x00}}, /* Linked Track ID */
     { 0x3001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x00,0x00,0x00,0x00}}, /* SampleRate */
+    { 0x3002, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x06,0x01,0x02,0x00,0x00,0x00,0x00}}, /* ContainerDuration */
     { 0x3004, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x01,0x02,0x00,0x00}}, /* Essence Container */
     // Generic Picture Essence Descriptor
     { 0x320C, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x03,0x01,0x04,0x00,0x00,0x00}}, /* Frame Layout */
@@ -483,6 +492,12 @@
     avio_wb24(pb, len);
 }
 
+static void klv_encode_ber9_length(AVIOContext *pb, uint64_t len)
+{
+    avio_w8(pb, 0x80 + 8);
+    avio_wb64(pb, len);
+}
+
 /*
  * Get essence container ul index
  */
@@ -601,7 +616,10 @@
 
     // operational pattern
     mxf_write_local_tag(pb, 16, 0x3B09);
-    avio_write(pb, op1a_ul, 16);
+    if (s->oformat == &ff_mxf_opatom_muxer)
+        avio_write(pb, opatom_ul, 16);
+    else
+        avio_write(pb, op1a_ul, 16);
 
     // write essence_container_refs
     mxf_write_local_tag(pb, 8 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count), 0x3B0A);
@@ -613,14 +631,61 @@
 }
 
 /*
- * Write a local tag containing an ascii string as utf-16
+ * Returns the length of the UTF-16 string, in 16-bit characters, that would result
+ * from decoding the utf-8 string.
+ */
+static uint64_t mxf_utf16len(const char *utf8_str)
+{
+    const uint8_t *q = utf8_str;
+    uint64_t size = 0;
+    while (*q) {
+        uint32_t ch;
+        GET_UTF8(ch, *q++, goto invalid;)
+        if (ch < 0x10000)
+            size++;
+        else
+            size += 2;
+        continue;
+invalid:
+        av_log(NULL, AV_LOG_ERROR, "Invaid UTF8 sequence in mxf_utf16len\n\n");
+    }
+    size += 1;
+    return size;
+}
+
+/*
+ * Returns the calculated length a local tag containing an utf-8 string as utf-16
+ */
+static int mxf_utf16_local_tag_length(const char *utf8_str)
+{
+    uint64_t size;
+
+    if (!utf8_str)
+        return 0;
+
+    size = mxf_utf16len(utf8_str);
+    if (size >= UINT16_MAX/2) {
+        av_log(NULL, AV_LOG_ERROR, "utf16 local tag size %"PRIx64" invalid (too large), ignoring\n", size);
+        return 0;
+    }
+
+    return 4 + size * 2;
+}
+
+/*
+ * Write a local tag containing an utf-8 string as utf-16
  */
 static void mxf_write_local_tag_utf16(AVIOContext *pb, int tag, const char *value)
 {
-    int i, size = strlen(value);
+    uint64_t size = mxf_utf16len(value);
+
+    if (size >= UINT16_MAX/2) {
+        av_log(NULL, AV_LOG_ERROR, "utf16 local tag size %"PRIx64" invalid (too large), ignoring\n", size);
+        return;
+    }
+
     mxf_write_local_tag(pb, size*2, tag);
-    for (i = 0; i < size; i++)
-        avio_wb16(pb, value[i]);
+    avio_put_str16be(pb, value);
 }
 
 static void mxf_write_identification(AVFormatContext *s)
@@ -628,7 +693,7 @@
     MXFContext *mxf = s->priv_data;
     AVIOContext *pb = s->pb;
     const char *company = "FFmpeg";
-    const char *product = "OP1a Muxer";
+    const char *product = s->oformat != &ff_mxf_opatom_muxer ? "OP1a Muxer" : "OPAtom Muxer";
     const char *version;
     int length;
 
@@ -637,7 +702,9 @@
 
     version = s->flags & AVFMT_FLAG_BITEXACT ?
         "0.0.0" : AV_STRINGIFY(LIBAVFORMAT_VERSION);
-    length = 84 + (strlen(company)+strlen(product)+strlen(version))*2; // utf-16
+    length = 72 + mxf_utf16_local_tag_length(company) +
+                  mxf_utf16_local_tag_length(product) +
+                  mxf_utf16_local_tag_length(version);
     klv_encode_ber_length(pb, length);
 
     // write uid
@@ -648,7 +715,6 @@
     // write generation uid
     mxf_write_local_tag(pb, 16, 0x3C09);
     mxf_write_uuid(pb, Identification, 1);
-
     mxf_write_local_tag_utf16(pb, 0x3C01, company); // Company Name
     mxf_write_local_tag_utf16(pb, 0x3C02, product); // Product Name
     mxf_write_local_tag_utf16(pb, 0x3C04, version); // Version String
@@ -1081,20 +1147,72 @@
     mxf_write_generic_sound_common(s, st, mxf_generic_sound_descriptor_key, 0);
 }
 
-static void mxf_write_package(AVFormatContext *s, enum MXFMetadataSetType type)
+static const uint8_t mxf_indirect_value_utf16le[] = { 0x4c,0x00,0x02,0x10,0x01,0x00,0x00,0x00,0x00,0x06,0x0e,0x2b,0x34,0x01,0x04,0x01,0x01 };
+
+static int mxf_write_tagged_value(AVFormatContext *s, const char* name, const char* value)
+{
+    MXFContext *mxf = s->priv_data;
+    AVIOContext *pb = s->pb;
+    int name_size = mxf_utf16_local_tag_length(name);
+    int indirect_value_size = 13 + mxf_utf16_local_tag_length(value);
+
+    if (!name_size || indirect_value_size == 13)
+        return 1;
+
+    mxf_write_metadata_key(pb, 0x013f00);
+    klv_encode_ber_length(pb, 24 + name_size + indirect_value_size);
+
+    // write instance UID
+    mxf_write_local_tag(pb, 16, 0x3C0A);
+    mxf_write_uuid(pb, TaggedValue, mxf->tagged_value_count);
+
+    // write name
+    mxf_write_local_tag_utf16(pb, 0x5001, name); // Name
+
+    // write indirect value
+    mxf_write_local_tag(pb, indirect_value_size, 0x5003);
+    avio_write(pb, mxf_indirect_value_utf16le, 17);
+    avio_put_str16le(pb, value);
+
+    mxf->tagged_value_count++;
+    return 0;
+}
+
+static int mxf_write_user_comments(AVFormatContext *s, const AVDictionary *m)
+{
+    MXFContext *mxf = s->priv_data;
+    AVDictionaryEntry *t = NULL;
+    int count = 0;
+
+    while ((t = av_dict_get(m, "comment_", t, AV_DICT_IGNORE_SUFFIX))) {
+        if (mxf->tagged_value_count >= UINT16_MAX) {
+            av_log(s, AV_LOG_ERROR, "too many tagged values, ignoring remaining\n");
+            return count;
+        }
+
+        if (mxf_write_tagged_value(s, t->key + 8, t->value) == 0)
+            count++;
+    }
+    return count;
+}
+
+static void mxf_write_package(AVFormatContext *s, enum MXFMetadataSetType type, const char *package_name)
 {
     MXFContext *mxf = s->priv_data;
     AVIOContext *pb = s->pb;
     int i, track_count = s->nb_streams+1;
+    int name_size = mxf_utf16_local_tag_length(package_name);
+    int user_comment_count = 0;
 
     if (type == MaterialPackage) {
+        user_comment_count = mxf_write_user_comments(s, s->metadata);
         mxf_write_metadata_key(pb, 0x013600);
         PRINT_KEY(s, "Material Package key", pb->buf_ptr - 16);
-        klv_encode_ber_length(pb, 92 + 16*track_count);
+        klv_encode_ber_length(pb, 104 + name_size + (16*track_count) + (16*user_comment_count));
     } else {
         mxf_write_metadata_key(pb, 0x013700);
         PRINT_KEY(s, "Source Package key", pb->buf_ptr - 16);
-        klv_encode_ber_length(pb, 112 + 16*track_count); // 20 bytes length for descriptor reference
+        klv_encode_ber_length(pb, 124 + name_size + (16*track_count)); // 20 bytes length for descriptor reference
     }
 
     // write uid
@@ -1108,6 +1226,10 @@
     mxf_write_umid(s, type == SourcePackage);
     PRINT_KEY(s, "package umid second part", pb->buf_ptr - 16);
 
+    // package name
+    if (name_size)
+        mxf_write_local_tag_utf16(pb, 0x4402, package_name);
+
     // package creation date
     mxf_write_local_tag(pb, 8, 0x4405);
     avio_wb64(pb, mxf->timestamp);
@@ -1124,6 +1246,12 @@
     for (i = 0; i < s->nb_streams; i++)
         mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, i);
 
+    // write user comment refs
+    mxf_write_local_tag(pb, user_comment_count*16 + 8, 0x4406);
+    mxf_write_refs_count(pb, user_comment_count);
+    for (i = 0; i < user_comment_count; i++)
+         mxf_write_uuid(pb, TaggedValue, mxf->tagged_value_count - user_comment_count + i);
+
     // write multiple descriptor reference
     if (type == SourcePackage) {
         mxf_write_local_tag(pb, 16, 0x4701);
@@ -1176,11 +1304,33 @@
 
 static int mxf_write_header_metadata_sets(AVFormatContext *s)
 {
+    const char *material_package_name = NULL;
+    const char *file_package_name = NULL;
+    AVDictionaryEntry *entry = NULL;
+    AVStream *st = NULL;
+    int i;
+
+    if (entry = av_dict_get(s->metadata, "material_package_name", NULL, 0))
+       material_package_name = entry->value;
+
+    if (entry = av_dict_get(s->metadata, "file_package_name", NULL, 0)) {
+        file_package_name = entry->value;
+    } else {
+        /* check if any of the streams contain a file_package_name */
+        for (i = 0; i < s->nb_streams; i++) {
+            st = s->streams[i];
+            if (entry = av_dict_get(st->metadata, "file_package_name", NULL, 0)) {
+                file_package_name = entry->value;
+                break;
+            }
+        }
+    }
+
     mxf_write_preface(s);
     mxf_write_identification(s);
     mxf_write_content_storage(s);
-    mxf_write_package(s, MaterialPackage);
-    mxf_write_package(s, SourcePackage);
+    mxf_write_package(s, MaterialPackage, material_package_name);
+    mxf_write_package(s, SourcePackage, file_package_name);
     mxf_write_essence_container_data(s);
     return 0;
 }
@@ -1362,7 +1512,7 @@
         index_byte_count += klv_fill_size(index_byte_count);
     }
 
-    if (!memcmp(key, body_partition_key, 16)) {
+    if (key && !memcmp(key, body_partition_key, 16)) {
         if ((err = av_reallocp_array(&mxf->body_partition_offset, mxf->body_partitions_count + 1,
                                      sizeof(*mxf->body_partition_offset))) < 0) {
             mxf->body_partitions_count = 0;
@@ -1372,7 +1522,11 @@
     }
 
     // write klv
-    avio_write(pb, key, 16);
+    if (key)
+        avio_write(pb, key, 16);
+    else
+        avio_write(pb, body_partition_key, 16);
+
     klv_encode_ber_length(pb, 88 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count));
 
     // write partition value
@@ -1382,9 +1536,9 @@
 
     avio_wb64(pb, partition_offset); // ThisPartition
 
-    if (!memcmp(key, body_partition_key, 16) && mxf->body_partitions_count > 1)
+    if (key && !memcmp(key, body_partition_key, 16) && mxf->body_partitions_count > 1)
         avio_wb64(pb, mxf->body_partition_offset[mxf->body_partitions_count-2]); // PreviousPartition
-    else if (!memcmp(key, footer_partition_key, 16) && mxf->body_partitions_count)
+    else if (key && !memcmp(key, footer_partition_key, 16) && mxf->body_partitions_count)
         avio_wb64(pb, mxf->body_partition_offset[mxf->body_partitions_count-1]); // PreviousPartition
     else
         avio_wb64(pb, 0);
@@ -1400,15 +1554,18 @@
     avio_wb32(pb, index_byte_count ? indexsid : 0); // indexSID
 
     // BodyOffset
-    if (bodysid && mxf->edit_units_count && mxf->body_partitions_count) {
+    if (bodysid && mxf->edit_units_count && mxf->body_partitions_count && s->oformat != &ff_mxf_opatom_muxer)
         avio_wb64(pb, mxf->body_offset);
-    } else
+    else
         avio_wb64(pb, 0);
 
     avio_wb32(pb, bodysid); // bodySID
 
     // operational pattern
-    avio_write(pb, op1a_ul, 16);
+    if (s->oformat == &ff_mxf_opatom_muxer)
+        avio_write(pb, opatom_ul, 16);
+    else
+        avio_write(pb, op1a_ul, 16);
 
     // essence container
     mxf_write_essence_container_refs(s);
@@ -1431,7 +1588,8 @@
         avio_seek(pb, pos, SEEK_SET);
     }
 
-    avio_flush(pb);
+    if(key)
+        avio_flush(pb);
 
     return 0;
 }
@@ -1498,6 +1656,11 @@
     sc->codec_ul = &mxf_essence_container_uls[sc->index].codec_ul;
     sc->aspect_ratio = (AVRational){ 16, 9 };
 
+    if(s->oformat == &ff_mxf_opatom_muxer){
+        mxf->edit_unit_byte_count = frame_size;
+        return 1;
+    }
+
     mxf->edit_unit_byte_count = KAG_SIZE;
     for (i = 0; i < s->nb_streams; i++) {
         AVStream *st = s->streams[i];
@@ -1568,6 +1731,11 @@
     sc->index = ul_index + 16;
     sc->codec_ul =  &mxf_essence_container_uls[sc->index].codec_ul;
 
+    if(s->oformat == &ff_mxf_opatom_muxer) {
+        mxf->edit_unit_byte_count = frame_size;
+        return 1;
+    }
+
     mxf->edit_unit_byte_count = KAG_SIZE;
     for (i = 0; i < s->nb_streams; i++) {
         AVStream *st = s->streams[i];
@@ -1803,6 +1971,11 @@
     if (!s->nb_streams)
         return -1;
 
+    if (s->oformat == &ff_mxf_opatom_muxer && s->nb_streams !=1){
+        av_log(s, AV_LOG_ERROR, "there must be exactly one stream for mxf opatom\n");
+        return -1;
+    }
+
     for (i = 0; i < s->nb_streams; i++) {
         AVStream *st = s->streams[i];
         MXFStreamContext *sc = av_mallocz(sizeof(*sc));
@@ -1901,7 +2074,7 @@
         present[sc->index]++;
     }
 
-    if (s->oformat == &ff_mxf_d10_muxer) {
+    if (s->oformat == &ff_mxf_d10_muxer || s->oformat == &ff_mxf_opatom_muxer) {
         mxf->essence_container_count = 1;
     }
 
@@ -2046,6 +2219,58 @@
     }
 }
 
+static int mxf_write_opatom_body_partition(AVFormatContext *s)
+{
+    MXFContext *mxf = s->priv_data;
+    AVIOContext *pb = s->pb;
+    AVStream *st = s->streams[0];
+    MXFStreamContext *sc = st->priv_data;
+    const uint8_t *key = NULL;
+
+    int err;
+
+    if (!mxf->header_written)
+        key = body_partition_key;
+
+    if ((err = mxf_write_partition(s, 1, 0, key, 0)) < 0)
+        return err;
+    mxf_write_klv_fill(s);
+    avio_write(pb, sc->track_essence_element_key, 16);
+    klv_encode_ber9_length(pb, mxf->body_offset);
+    return 0;
+}
+
+static int mxf_write_opatom_packet(AVFormatContext *s, AVPacket *pkt, MXFIndexEntry *ie)
+{
+    MXFContext *mxf = s->priv_data;
+    AVIOContext *pb = s->pb;
+
+    int err;
+
+    if (!mxf->header_written) {
+        if ((err = mxf_write_partition(s, 0, 0, header_open_partition_key, 1)) < 0)
+            return err;
+        mxf_write_klv_fill(s);
+
+        if ((err = mxf_write_opatom_body_partition(s)) < 0)
+            return err;
+        mxf->header_written = 1;
+    }
+
+    if (!mxf->edit_unit_byte_count) {
+        mxf->index_entries[mxf->edit_units_count].offset = mxf->body_offset;
+        mxf->index_entries[mxf->edit_units_count].flags = ie->flags;
+        mxf->index_entries[mxf->edit_units_count].temporal_ref = ie->temporal_ref;
+    }
+    mxf->edit_units_count++;
+    avio_write(pb, pkt->data, pkt->size);
+    mxf->body_offset += pkt->size;
+
+    avio_flush(pb);
+
+    return 0;
+}
+
 static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     MXFContext *mxf = s->priv_data;
@@ -2086,6 +2311,9 @@
         }
     }
 
+    if (s->oformat == &ff_mxf_opatom_muxer)
+        return mxf_write_opatom_packet(s, pkt, &ie);
+
     if (!mxf->header_written) {
         if (mxf->edit_unit_byte_count) {
             if ((err = mxf_write_partition(s, 1, 2, header_open_partition_key, 1)) < 0)
@@ -2153,7 +2381,7 @@
     avio_write(pb, random_index_pack_key, 16);
     klv_encode_ber_length(pb, 28 + 12LL*mxf->body_partitions_count);
 
-    if (mxf->edit_unit_byte_count)
+    if (mxf->edit_unit_byte_count && s->oformat != &ff_mxf_opatom_muxer)
         avio_wb32(pb, 1); // BodySID of header partition
     else
         avio_wb32(pb, 0);
@@ -2174,18 +2402,25 @@
 {
     MXFContext *mxf = s->priv_data;
     AVIOContext *pb = s->pb;
-    int err;
+    int err = 0;
+
+    if (!mxf->header_written ||
+        (s->oformat == &ff_mxf_opatom_muxer && !mxf->body_partition_offset)) {
+        /* reason could be invalid options/not supported codec/out of memory */
+        err = AVERROR_UNKNOWN;
+        goto end;
+    }
 
     mxf->duration = mxf->last_indexed_edit_unit + mxf->edit_units_count;
 
     mxf_write_klv_fill(s);
     mxf->footer_partition_offset = avio_tell(pb);
-    if (mxf->edit_unit_byte_count) { // no need to repeat index
+    if (mxf->edit_unit_byte_count && s->oformat != &ff_mxf_opatom_muxer) { // no need to repeat index
         if ((err = mxf_write_partition(s, 0, 0, footer_partition_key, 0)) < 0)
-            return err;
+            goto end;
     } else {
         if ((err = mxf_write_partition(s, 0, 2, footer_partition_key, 0)) < 0)
-            return err;
+            goto end;
         mxf_write_klv_fill(s);
         mxf_write_index_table_segment(s);
     }
@@ -2194,18 +2429,26 @@
     mxf_write_random_index_pack(s);
 
     if (s->pb->seekable) {
+        if (s->oformat == &ff_mxf_opatom_muxer){
+            /* rewrite body partition to update lengths */
+            avio_seek(pb, mxf->body_partition_offset[0], SEEK_SET);
+            if ((err = mxf_write_opatom_body_partition(s)) < 0)
+                goto end;
+        }
+
         avio_seek(pb, 0, SEEK_SET);
-        if (mxf->edit_unit_byte_count) {
+        if (mxf->edit_unit_byte_count && s->oformat != &ff_mxf_opatom_muxer) {
             if ((err = mxf_write_partition(s, 1, 2, header_closed_partition_key, 1)) < 0)
-                return err;
+                goto end;
             mxf_write_klv_fill(s);
             mxf_write_index_table_segment(s);
         } else {
             if ((err = mxf_write_partition(s, 0, 0, header_closed_partition_key, 1)) < 0)
-                return err;
+                goto end;
         }
     }
 
+end:
     ff_audio_interleave_close(s);
 
     av_freep(&mxf->index_entries);
@@ -2215,7 +2458,7 @@
 
     mxf_free(s);
 
-    return 0;
+    return err < 0 ? err : 0;
 }
 
 static int mxf_interleave_get_packet(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
@@ -2226,7 +2469,7 @@
         stream_count += !!s->streams[i]->last_in_packet_buffer;
 
     if (stream_count && (s->nb_streams == stream_count || flush)) {
-        AVPacketList *pktl = s->packet_buffer;
+        AVPacketList *pktl = s->internal->packet_buffer;
         if (s->nb_streams != stream_count) {
             AVPacketList *last = NULL;
             // find last packet in edit unit
@@ -2250,20 +2493,20 @@
             if (last)
                 last->next = NULL;
             else {
-                s->packet_buffer = NULL;
-                s->packet_buffer_end= NULL;
+                s->internal->packet_buffer = NULL;
+                s->internal->packet_buffer_end= NULL;
                 goto out;
             }
-            pktl = s->packet_buffer;
+            pktl = s->internal->packet_buffer;
         }
 
         *out = pktl->pkt;
         av_dlog(s, "out st:%d dts:%"PRId64"\n", (*out).stream_index, (*out).dts);
-        s->packet_buffer = pktl->next;
+        s->internal->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;
-        if(!s->packet_buffer)
-            s->packet_buffer_end= NULL;
+        if(!s->internal->packet_buffer)
+            s->internal->packet_buffer_end= NULL;
         av_freep(&pktl);
         return 1;
     } else {
@@ -2330,3 +2573,18 @@
     .interleave_packet = mxf_interleave,
     .priv_class        = &mxf_d10_muxer_class,
 };
+
+AVOutputFormat ff_mxf_opatom_muxer = {
+    .name              = "mxf_opatom",
+    .long_name         = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format) Operational Pattern Atom"),
+    .mime_type         = "application/mxf",
+    .extensions        = "mxf",
+    .priv_data_size    = sizeof(MXFContext),
+    .audio_codec       = AV_CODEC_ID_PCM_S16LE,
+    .video_codec       = AV_CODEC_ID_DNXHD,
+    .write_header      = mxf_write_header,
+    .write_packet      = mxf_write_packet,
+    .write_trailer     = mxf_write_footer,
+    .flags             = AVFMT_NOTIMESTAMPS,
+    .interleave_packet = mxf_interleave,
+};
diff --git a/libavformat/network.c b/libavformat/network.c
index 9f02ec6..e9eab29 100644
--- a/libavformat/network.c
+++ b/libavformat/network.c
@@ -66,7 +66,7 @@
 #endif
 #endif
 
-void ff_tls_init(void)
+int ff_tls_init(void)
 {
     avpriv_lock_avformat();
 #if CONFIG_OPENSSL
@@ -77,6 +77,8 @@
         if (!CRYPTO_get_locking_callback()) {
             int i;
             openssl_mutexes = av_malloc_array(sizeof(pthread_mutex_t), CRYPTO_num_locks());
+            if (!openssl_mutexes)
+                return AVERROR(ENOMEM);
             for (i = 0; i < CRYPTO_num_locks(); i++)
                 pthread_mutex_init(&openssl_mutexes[i], NULL);
             CRYPTO_set_locking_callback(openssl_lock);
@@ -96,6 +98,8 @@
     gnutls_global_init();
 #endif
     avpriv_unlock_avformat();
+
+    return 0;
 }
 
 void ff_tls_deinit(void)
diff --git a/libavformat/network.h b/libavformat/network.h
index 0d1081a..86fb656 100644
--- a/libavformat/network.h
+++ b/libavformat/network.h
@@ -78,7 +78,7 @@
 int ff_network_init(void);
 void ff_network_close(void);
 
-void ff_tls_init(void);
+int ff_tls_init(void);
 void ff_tls_deinit(void);
 
 int ff_network_wait_fd(int fd, int write);
diff --git a/libavformat/nsvdec.c b/libavformat/nsvdec.c
index 632667c..59b7938 100644
--- a/libavformat/nsvdec.c
+++ b/libavformat/nsvdec.c
@@ -162,7 +162,7 @@
     int cum_len; /* temporary storage (used during seek) */
 } NSVStream;
 
-typedef struct {
+typedef struct NSVContext {
     int  base_offset;
     int  NSVf_end;
     uint32_t *nsvs_file_offset;
diff --git a/libavformat/nut.c b/libavformat/nut.c
index 86a0301..c6fdb0b 100644
--- a/libavformat/nut.c
+++ b/libavformat/nut.c
@@ -40,6 +40,7 @@
 };
 
 const AVCodecTag ff_nut_video_tags[] = {
+    { AV_CODEC_ID_GIF,              MKTAG('G', 'I', 'F',  0 ) },
     { AV_CODEC_ID_XFACE,            MKTAG('X', 'F', 'A', 'C') },
     { AV_CODEC_ID_VP9,              MKTAG('V', 'P', '9', '0') },
     { AV_CODEC_ID_RAWVIDEO,         MKTAG('R', 'G', 'B', 15 ) },
@@ -182,6 +183,7 @@
     { 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_WAVPACK,          MKTAG('w', 'v', 'p', 'k') },
     { AV_CODEC_ID_NONE,             0                         }
 };
 
diff --git a/libavformat/nutdec.c b/libavformat/nutdec.c
index ef29bdf..00e86bb 100644
--- a/libavformat/nutdec.c
+++ b/libavformat/nutdec.c
@@ -790,7 +790,7 @@
         decode_info_header(nut);
     }
 
-    s->data_offset = pos - 8;
+    s->internal->data_offset = pos - 8;
 
     if (bc->seekable) {
         int64_t orig_pos = avio_tell(bc);
diff --git a/libavformat/nutenc.c b/libavformat/nutenc.c
index 3146f89..b4b6dcd 100644
--- a/libavformat/nutenc.c
+++ b/libavformat/nutenc.c
@@ -168,7 +168,6 @@
         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;
-        const AVCodecDescriptor *desc = avcodec_descriptor_get(codec->codec_id);
         int is_audio          = codec->codec_type == AVMEDIA_TYPE_AUDIO;
         int intra_only        = /*codec->intra_only || */ is_audio;
         int pred_count;
@@ -420,7 +419,6 @@
 {
     NUTContext *nut       = avctx->priv_data;
     AVCodecContext *codec = st->codec;
-    const AVCodecDescriptor *desc = avcodec_descriptor_get(codec->codec_id);
 
     ff_put_v(bc, i);
     switch (codec->codec_type) {
@@ -668,11 +666,8 @@
             return ret;
         if (ret > 0)
             put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
-        else {
-            uint8_t *buf;
-            avio_close_dyn_buf(dyn_bc, &buf);
-            av_free(buf);
-        }
+        else
+            ffio_free_dyn_buf(&dyn_bc);
     }
 
     for (i = 0; i < nut->avf->nb_chapters; i++) {
@@ -681,9 +676,7 @@
             return ret;
         ret = write_chapter(nut, dyn_bc, i);
         if (ret < 0) {
-            uint8_t *buf;
-            avio_close_dyn_buf(dyn_bc, &buf);
-            av_freep(&buf);
+            ffio_free_dyn_buf(&dyn_bc);
             return ret;
         }
         put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
diff --git a/libavformat/nuv.c b/libavformat/nuv.c
index 65d2e56..001d9c8 100644
--- a/libavformat/nuv.c
+++ b/libavformat/nuv.c
@@ -33,7 +33,7 @@
     { AV_CODEC_ID_NONE,      0 },
 };
 
-typedef struct {
+typedef struct NUVContext {
     int v_id;
     int a_id;
     int rtjpg_video;
diff --git a/libavformat/oggdec.c b/libavformat/oggdec.c
index 8f146e4..28057ad 100644
--- a/libavformat/oggdec.c
+++ b/libavformat/oggdec.c
@@ -68,6 +68,10 @@
     struct ogg_state *ost =
         av_malloc(sizeof(*ost) + (ogg->nstreams - 1) * sizeof(*ogg->streams));
     int i;
+
+    if (!ost)
+        return AVERROR(ENOMEM);
+
     ost->pos      = avio_tell(s->pb);
     ost->curidx   = ogg->curidx;
     ost->next     = ogg->state;
@@ -142,7 +146,7 @@
         os->segp       = 0;
         os->incomplete = 0;
         os->got_data = 0;
-        if (start_pos <= s->data_offset) {
+        if (start_pos <= s->internal->data_offset) {
             os->lastpts = 0;
         }
         os->end_trimming = 0;
@@ -276,6 +280,9 @@
     uint8_t *nb = av_malloc(os->bufsize + FF_INPUT_BUFFER_PADDING_SIZE);
     int size = os->bufpos - os->pstart;
 
+    if (!nb)
+        return AVERROR(ENOMEM);
+
     if (os->buf) {
         memcpy(nb, os->buf + os->pstart, size);
         av_free(os->buf);
@@ -370,8 +377,11 @@
     ogg->page_pos =
     os->page_pos = avio_tell(bc) - 27;
 
-    if (os->psize > 0)
-        ogg_new_buf(ogg, idx);
+    if (os->psize > 0) {
+        ret = ogg_new_buf(ogg, idx);
+        if (ret < 0)
+            return ret;
+    }
 
     ret = avio_read(bc, os->segments, nsegs);
     if (ret < nsegs)
@@ -520,8 +530,8 @@
 
             // Update the header state for all streams and
             // compute the data_offset.
-            if (!s->data_offset)
-                s->data_offset = os->sync_pos;
+            if (!s->internal->data_offset)
+                s->internal->data_offset = os->sync_pos;
 
             for (i = 0; i < ogg->nstreams; i++) {
                 struct ogg_stream *cur_os = ogg->streams + i;
@@ -529,7 +539,7 @@
                 // if we have a partial non-header packet, its start is
                 // obviously at or after the data start
                 if (cur_os->incomplete)
-                    s->data_offset = FFMIN(s->data_offset, cur_os->sync_pos);
+                    s->internal->data_offset = FFMIN(s->internal->data_offset, cur_os->sync_pos);
             }
         } else {
             os->nb_header++;
@@ -577,6 +587,7 @@
     int i;
     int64_t size, end;
     int streams_left=0;
+    int ret;
 
     if (!s->pb->seekable)
         return 0;
@@ -590,7 +601,9 @@
         return 0;
     end = size > MAX_PAGE_SIZE ? size - MAX_PAGE_SIZE : 0;
 
-    ogg_save(s);
+    ret = ogg_save(s);
+    if (ret < 0)
+        return ret;
     avio_seek(s->pb, end, SEEK_SET);
     ogg->page_pos = -1;
 
@@ -612,8 +625,11 @@
 
     ogg_restore(s, 0);
 
-    ogg_save (s);
-    avio_seek (s->pb, s->data_offset, SEEK_SET);
+    ret = ogg_save(s);
+    if (ret < 0)
+        return ret;
+
+    avio_seek (s->pb, s->internal->data_offset, SEEK_SET);
     ogg_reset(s);
     while (streams_left > 0 && !ogg_packet(s, &i, NULL, NULL, NULL)) {
         int64_t pts;
diff --git a/libavformat/oggenc.c b/libavformat/oggenc.c
index 3929311..ca40063 100644
--- a/libavformat/oggenc.c
+++ b/libavformat/oggenc.c
@@ -35,7 +35,7 @@
 
 #define MAX_PAGE_SIZE 65025
 
-typedef struct {
+typedef struct OGGPage {
     int64_t start_granule;
     int64_t granule;
     int stream_index;
@@ -46,7 +46,7 @@
     uint16_t size;
 } OGGPage;
 
-typedef struct {
+typedef struct OGGStreamContext {
     unsigned page_counter;
     uint8_t *header[3];
     int header_len[3];
@@ -66,19 +66,22 @@
     struct OGGPageList *next;
 } OGGPageList;
 
-typedef struct {
+typedef struct OGGContext {
     const AVClass *class;
     OGGPageList *page_list;
     int pref_size; ///< preferred page size (0 => fill all segments)
     int64_t pref_duration;      ///< preferred page duration (0 => fill all segments)
+    int serial_offset;
 } OGGContext;
 
 #define OFFSET(x) offsetof(OGGContext, x)
 #define PARAM AV_OPT_FLAG_ENCODING_PARAM
 
 static const AVOption options[] = {
+    { "serial_offset", "serial number offset",
+        OFFSET(serial_offset), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, PARAM },
     { "oggpagesize", "Set preferred Ogg page size.",
-      offsetof(OGGContext, pref_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, MAX_PAGE_SIZE, AV_OPT_FLAG_ENCODING_PARAM},
+      OFFSET(pref_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, MAX_PAGE_SIZE, PARAM},
     { "pagesize", "preferred page size in bytes (deprecated)",
         OFFSET(pref_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, MAX_PAGE_SIZE, PARAM },
     { "page_duration", "preferred page duration, in microseconds",
@@ -430,7 +433,7 @@
 
     for (i = 0; i < s->nb_streams; i++) {
         AVStream *st = s->streams[i];
-        unsigned serial_num = i;
+        unsigned serial_num = i + ogg->serial_offset;
 
         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
             if (st->codec->codec_id == AV_CODEC_ID_OPUS)
diff --git a/libavformat/omadec.c b/libavformat/omadec.c
index 9f3d3aa..858ee84 100644
--- a/libavformat/omadec.c
+++ b/libavformat/omadec.c
@@ -47,6 +47,7 @@
 #include "internal.h"
 #include "libavutil/intreadwrite.h"
 #include "libavutil/des.h"
+#include "libavutil/mathematics.h"
 #include "oma.h"
 #include "pcm.h"
 #include "id3v2.h"
@@ -174,7 +175,7 @@
     taglen  = AV_RB32(&enc_header[pos + 32]);
     datalen = AV_RB32(&enc_header[pos + 36]) >> 4;
 
-    pos += 44L + taglen;
+    pos += 44LL + taglen;
 
     if (pos + (((uint64_t)datalen) << 4) > size)
         return -1;
@@ -412,9 +413,12 @@
 
 static int oma_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
-    OMAContext *oc = s->priv_data;
-    int packet_size = s->streams[0]->codec->block_align;
-    int ret = av_get_packet(s->pb, pkt, packet_size);
+    OMAContext *oc  = s->priv_data;
+    AVStream *st    = s->streams[0];
+    int packet_size = st->codec->block_align;
+    int byte_rate   = st->codec->bit_rate >> 3;
+    int64_t pos     = avio_tell(s->pb);
+    int ret         = av_get_packet(s->pb, pkt, packet_size);
 
     if (ret < packet_size)
         pkt->flags |= AV_PKT_FLAG_CORRUPT;
@@ -426,6 +430,12 @@
 
     pkt->stream_index = 0;
 
+    if (pos >= oc->content_start && byte_rate > 0) {
+        pkt->pts =
+        pkt->dts = av_rescale(pos - oc->content_start, st->time_base.den,
+                              byte_rate * (int64_t)st->time_base.num);
+    }
+
     if (oc->encrypted) {
         /* previous unencrypted block saved in IV for
          * the next packet (CBC mode) */
@@ -464,7 +474,7 @@
                          int stream_index, int64_t timestamp, int flags)
 {
     OMAContext *oc = s->priv_data;
-    int err = ff_pcm_read_seek(s, stream_index, timestamp, flags);
+    int64_t err = ff_pcm_read_seek(s, stream_index, timestamp, flags);
 
     if (!oc->encrypted)
         return err;
diff --git a/libavformat/options.c b/libavformat/options.c
index 5044043..4b08f3f 100644
--- a/libavformat/options.c
+++ b/libavformat/options.c
@@ -55,7 +55,7 @@
     AVOutputFormat *ofmt = NULL;
 
     if (!prev)
-        return &ffio_url_class;
+        return &ff_avio_class;
 
     while ((ifmt = av_iformat_next(ifmt)))
         if (ifmt->priv_class == prev)
@@ -110,13 +110,13 @@
     ic = av_malloc(sizeof(AVFormatContext));
     if (!ic) return ic;
     avformat_get_context_defaults(ic);
-    ic->offset = AV_NOPTS_VALUE;
 
     ic->internal = av_mallocz(sizeof(*ic->internal));
     if (!ic->internal) {
         avformat_free_context(ic);
         return NULL;
     }
+    ic->internal->offset = AV_NOPTS_VALUE;
 
     return ic;
 }
diff --git a/libavformat/paf.c b/libavformat/paf.c
index 618994c..4fc5006 100644
--- a/libavformat/paf.c
+++ b/libavformat/paf.c
@@ -26,7 +26,7 @@
 
 #define MAGIC "Packed Animation File V1.0\n(c) 1992-96 Amazing Studio\x0a\x1a"
 
-typedef struct {
+typedef struct PAFDemuxContext {
     uint32_t buffer_size;
     uint32_t frame_blks;
     uint32_t nb_frames;
diff --git a/libavformat/pcm.c b/libavformat/pcm.c
index a57a4b6..f62075f 100644
--- a/libavformat/pcm.c
+++ b/libavformat/pcm.c
@@ -21,6 +21,7 @@
 
 #include "libavutil/mathematics.h"
 #include "avformat.h"
+#include "internal.h"
 #include "pcm.h"
 
 #define RAW_SAMPLES     1024
@@ -68,7 +69,7 @@
 
     /* recompute exact position */
     st->cur_dts = av_rescale(pos, st->time_base.den, byte_rate * (int64_t)st->time_base.num);
-    if ((ret = avio_seek(s->pb, pos + s->data_offset, SEEK_SET)) < 0)
+    if ((ret = avio_seek(s->pb, pos + s->internal->data_offset, SEEK_SET)) < 0)
         return ret;
     return 0;
 }
diff --git a/libavformat/pva.c b/libavformat/pva.c
index 18ab1cd..900ad61 100644
--- a/libavformat/pva.c
+++ b/libavformat/pva.c
@@ -28,7 +28,7 @@
 #define PVA_AUDIO_PAYLOAD       0x02
 #define PVA_MAGIC               (('A' << 8) + 'V')
 
-typedef struct {
+typedef struct PVAContext {
     int continue_pes;
 } PVAContext;
 
diff --git a/libavformat/qcp.c b/libavformat/qcp.c
index ccfa047..9e2eedf 100644
--- a/libavformat/qcp.c
+++ b/libavformat/qcp.c
@@ -32,7 +32,7 @@
 #include "avformat.h"
 #include "riff.h"
 
-typedef struct {
+typedef struct QCPContext {
     uint32_t data_size;                     ///< size of data chunk
 
 #define QCP_MAX_MODE 4
diff --git a/libavformat/r3d.c b/libavformat/r3d.c
index 0719fb6..6dda174 100644
--- a/libavformat/r3d.c
+++ b/libavformat/r3d.c
@@ -25,13 +25,13 @@
 #include "avformat.h"
 #include "internal.h"
 
-typedef struct {
+typedef struct R3DContext {
     unsigned video_offsets_count;
     unsigned *video_offsets;
     unsigned rdvo_offset;
 } R3DContext;
 
-typedef struct {
+typedef struct Atom {
     unsigned size;
     uint32_t tag;
     uint64_t offset;
@@ -185,8 +185,8 @@
         return -1;
     }
 
-    s->data_offset = avio_tell(s->pb);
-    av_dlog(s, "data offset %#"PRIx64"\n", s->data_offset);
+    s->internal->data_offset = avio_tell(s->pb);
+    av_dlog(s, "data offset %#"PRIx64"\n", s->internal->data_offset);
     if (!s->pb->seekable)
         return 0;
     // find REOB/REOF/REOS to load index
@@ -212,7 +212,7 @@
     }
 
  out:
-    avio_seek(s->pb, s->data_offset, SEEK_SET);
+    avio_seek(s->pb, s->internal->data_offset, SEEK_SET);
     return 0;
 }
 
@@ -221,7 +221,7 @@
     AVStream *st = s->streams[0];
     int tmp;
     int av_unused tmp2;
-    uint64_t pos = avio_tell(s->pb);
+    int64_t pos = avio_tell(s->pb);
     unsigned dts;
     int ret;
 
@@ -276,7 +276,7 @@
     AVStream *st = s->streams[1];
     int av_unused tmp, tmp2;
     int samples, size;
-    uint64_t pos = avio_tell(s->pb);
+    int64_t pos = avio_tell(s->pb);
     unsigned dts;
     int ret;
 
diff --git a/libavformat/rdt.c b/libavformat/rdt.c
index 212e139..bb56a8b 100644
--- a/libavformat/rdt.c
+++ b/libavformat/rdt.c
@@ -299,12 +299,12 @@
     AVIOContext pb;
 
     if (rdt->audio_pkt_cnt == 0) {
-        int pos;
+        int pos, rmflags;
 
         ffio_init_context(&pb, (uint8_t *)buf, len, 0, NULL, NULL, NULL, NULL);
-        flags = (flags & RTP_FLAG_KEY) ? 2 : 0;
+        rmflags = (flags & RTP_FLAG_KEY) ? 2 : 0;
         res = ff_rm_parse_packet (rdt->rmctx, &pb, st, rdt->rmst[st->index], len, pkt,
-                                  &seq, flags, *timestamp);
+                                  &seq, rmflags, *timestamp);
         pos = avio_tell(&pb);
         if (res < 0)
             return res;
@@ -434,6 +434,8 @@
                     rdt->nb_rmst = count;
                 }
                 rdt->rmst[s->streams[n]->index] = ff_rm_alloc_rmstream();
+                if (!rdt->rmst[s->streams[n]->index])
+                    return AVERROR(ENOMEM);
                 rdt_load_mdpr(rdt, s->streams[n], (n - first) * 2);
            }
     }
@@ -519,24 +521,15 @@
         real_parse_asm_rulebook(s, s->streams[stream_index], p);
 }
 
-static PayloadContext *
-rdt_new_context (void)
+
+
+static av_cold int rdt_init(AVFormatContext *s, int st_index, PayloadContext *rdt)
 {
-    PayloadContext *rdt = av_mallocz(sizeof(PayloadContext));
-    if (!rdt)
-        return NULL;
+    int ret;
 
     rdt->rmctx = avformat_alloc_context();
     if (!rdt->rmctx)
-        av_freep(&rdt);
-
-    return rdt;
-}
-
-static int
-rdt_init_context (AVFormatContext *s, int st_index, PayloadContext *rdt)
-{
-    int ret;
+        return AVERROR(ENOMEM);
 
     if ((ret = ff_copy_whitelists(rdt->rmctx, s)) < 0)
         return ret;
@@ -545,7 +538,7 @@
 }
 
 static void
-rdt_free_context (PayloadContext *rdt)
+rdt_close_context (PayloadContext *rdt)
 {
     int i;
 
@@ -558,7 +551,6 @@
         avformat_close_input(&rdt->rmctx);
     av_freep(&rdt->mlti_data);
     av_freep(&rdt->rmst);
-    av_free(rdt);
 }
 
 #define RDT_HANDLER(n, s, t) \
@@ -566,10 +558,10 @@
     .enc_name         = s, \
     .codec_type       = t, \
     .codec_id         = AV_CODEC_ID_NONE, \
+    .priv_data_size   = sizeof(PayloadContext), \
+    .init             = rdt_init, \
     .parse_sdp_a_line = rdt_parse_sdp_line, \
-    .alloc            = rdt_new_context, \
-    .init             = rdt_init_context, \
-    .free             = rdt_free_context, \
+    .close            = rdt_close_context, \
     .parse_packet     = rdt_parse_packet \
 }
 
diff --git a/libavformat/riff.c b/libavformat/riff.c
index 8d7b1c2..eb58ecc 100644
--- a/libavformat/riff.c
+++ b/libavformat/riff.c
@@ -42,6 +42,7 @@
     { AV_CODEC_ID_H264,         MKTAG('V', '2', '6', '4') }, /* CCTV recordings */
     { AV_CODEC_ID_H264,         MKTAG('G', 'A', 'V', 'C') }, /* GeoVision camera */
     { AV_CODEC_ID_H264,         MKTAG('U', 'M', 'S', 'V') },
+    { AV_CODEC_ID_H264,         MKTAG('t', 's', 'h', 'd') },
     { AV_CODEC_ID_H264,         MKTAG('I', 'N', 'M', 'C') },
     { AV_CODEC_ID_H263,         MKTAG('H', '2', '6', '3') },
     { AV_CODEC_ID_H263,         MKTAG('X', '2', '6', '3') },
@@ -362,7 +363,8 @@
     { AV_CODEC_ID_G2M,          MKTAG('G', '2', 'M', '4') },
     { AV_CODEC_ID_G2M,          MKTAG('G', '2', 'M', '5') },
     { AV_CODEC_ID_FIC,          MKTAG('F', 'I', 'C', 'V') },
-    { AV_CODEC_ID_PRORES,       MKTAG('A', 'P', 'C', 'N') },
+    { AV_CODEC_ID_HQX,          MKTAG('C', 'H', 'Q', 'X') },
+    { AV_CODEC_ID_TDSC,         MKTAG('T', 'D', 'S', 'C') },
     { AV_CODEC_ID_NONE,         0 }
 };
 
diff --git a/libavformat/riff.h b/libavformat/riff.h
index 15b07a6..ae5ecef 100644
--- a/libavformat/riff.h
+++ b/libavformat/riff.h
@@ -110,7 +110,7 @@
 
 int ff_get_guid(AVIOContext *s, ff_asf_guid *g);
 void ff_put_guid(AVIOContext *s, const ff_asf_guid *g);
-const ff_asf_guid *get_codec_guid(enum AVCodecID id, const AVCodecGuid *av_guid);
+const ff_asf_guid *ff_get_codec_guid(enum AVCodecID id, const AVCodecGuid *av_guid);
 
 enum AVCodecID ff_codec_guid_get_id(const AVCodecGuid *guids, ff_asf_guid guid);
 
diff --git a/libavformat/riffenc.c b/libavformat/riffenc.c
index 5e85800..a629b8a 100644
--- a/libavformat/riffenc.c
+++ b/libavformat/riffenc.c
@@ -178,7 +178,7 @@
         avio_wl32(pb, write_channel_mask ? enc->channel_layout : 0);
         /* GUID + next 3 */
         if (enc->codec_id == AV_CODEC_ID_EAC3) {
-            ff_put_guid(pb, get_codec_guid(enc->codec_id, ff_codec_wav_guids));
+            ff_put_guid(pb, ff_get_codec_guid(enc->codec_id, ff_codec_wav_guids));
         } else {
         avio_wl32(pb, enc->codec_tag);
         avio_wl32(pb, 0x00100000);
@@ -326,7 +326,7 @@
     avio_write(s, *g, sizeof(*g));
 }
 
-const ff_asf_guid *get_codec_guid(enum AVCodecID id, const AVCodecGuid *av_guid)
+const ff_asf_guid *ff_get_codec_guid(enum AVCodecID id, const AVCodecGuid *av_guid)
 {
     int i;
     for (i = 0; av_guid[i].id != AV_CODEC_ID_NONE; i++) {
diff --git a/libavformat/rmdec.c b/libavformat/rmdec.c
index 9418848..727d065 100644
--- a/libavformat/rmdec.c
+++ b/libavformat/rmdec.c
@@ -56,7 +56,7 @@
     int32_t deint_id;  ///< deinterleaver used in audio stream
 };
 
-typedef struct {
+typedef struct RMDemuxContext {
     int nb_packets;
     int old_format;
     int current_stream;
@@ -112,6 +112,8 @@
 RMStream *ff_rm_alloc_rmstream (void)
 {
     RMStream *rms = av_mallocz(sizeof(RMStream));
+    if (!rms)
+        return NULL;
     rms->curpic_num = -1;
     return rms;
 }
@@ -493,6 +495,8 @@
     if (!st)
         return -1;
     st->priv_data = ff_rm_alloc_rmstream();
+    if (!st->priv_data)
+        return AVERROR(ENOMEM);
     return rm_read_audio_stream_info(s, s->pb, st, st->priv_data, 1);
 }
 
@@ -576,6 +580,8 @@
             get_str8(pb, mime, sizeof(mime)); /* mimetype */
             st->codec->codec_type = AVMEDIA_TYPE_DATA;
             st->priv_data = ff_rm_alloc_rmstream();
+            if (!st->priv_data)
+                return AVERROR(ENOMEM);
             if (ff_rm_read_mdpr_codecdata(s, s->pb, st, st->priv_data,
                                           avio_rb32(pb), mime) < 0)
                 goto fail;
@@ -702,7 +708,7 @@
                                    int64_t *timestamp)
 {
     int hdr;
-    int seq = 0, pic_num = 0, len2 = 0, pos = 0; //init to silcense compiler warning
+    int seq = 0, pic_num = 0, len2 = 0, pos = 0; //init to silence compiler warning
     int type;
     int ret;
 
diff --git a/libavformat/rmenc.c b/libavformat/rmenc.c
index 2e50ed3..cd32f27 100644
--- a/libavformat/rmenc.c
+++ b/libavformat/rmenc.c
@@ -23,7 +23,7 @@
 #include "rm.h"
 #include "libavutil/dict.h"
 
-typedef struct {
+typedef struct StreamInfo {
     int nb_packets;
     int packet_total_size;
     int packet_max_size;
@@ -36,7 +36,7 @@
     AVCodecContext *enc;
 } StreamInfo;
 
-typedef struct {
+typedef struct RMMuxContext {
     StreamInfo streams[2];
     StreamInfo *audio_stream, *video_stream;
     int data_pos; /* position of the data after the header */
@@ -44,6 +44,10 @@
 
 /* in ms */
 #define BUFFER_DURATION 0
+/* the header needs at most 7 + 4 + 12 B */
+#define MAX_HEADER_SIZE (7 + 4 + 12)
+/* UINT16_MAX is the maximal chunk size */
+#define MAX_PACKET_SIZE (UINT16_MAX - MAX_HEADER_SIZE)
 
 
 static void put_str(AVIOContext *s, const char *tag)
@@ -364,6 +368,8 @@
 
     /* XXX: suppress this malloc */
     buf1 = av_malloc(size * sizeof(uint8_t));
+    if (!buf1)
+        return AVERROR(ENOMEM);
 
     write_packet_header(s, stream, size, !!(flags & AV_PKT_FLAG_KEY));
 
@@ -394,6 +400,10 @@
     /* Well, I spent some time finding the meaning of these bits. I am
        not sure I understood everything, but it works !! */
 #if 1
+    if (size > MAX_PACKET_SIZE) {
+        av_log(s, AV_LOG_ERROR, "Muxing packets larger than 64 kB (%d) is not supported\n", size);
+        return AVERROR_PATCHWELCOME;
+    }
     write_packet_header(s, stream, size + 7 + (size >= 0x4000)*4, key_frame);
     /* bit 7: '1' if final packet of a frame converted in several packets */
     avio_w8(pb, 0x81);
diff --git a/libavformat/rpl.c b/libavformat/rpl.c
index c1229e8..04cb917 100644
--- a/libavformat/rpl.c
+++ b/libavformat/rpl.c
@@ -278,7 +278,7 @@
     AVIOContext *pb = s->pb;
     AVStream* stream;
     AVIndexEntry* index_entry;
-    uint32_t ret;
+    int ret;
 
     if (rpl->chunk_part == s->nb_streams) {
         rpl->chunk_number++;
@@ -308,6 +308,8 @@
             return AVERROR(EIO);
 
         ret = av_get_packet(pb, pkt, frame_size);
+        if (ret < 0)
+            return ret;
         if (ret != frame_size) {
             av_free_packet(pkt);
             return AVERROR(EIO);
@@ -323,6 +325,8 @@
         }
     } else {
         ret = av_get_packet(pb, pkt, index_entry->size);
+        if (ret < 0)
+            return ret;
         if (ret != index_entry->size) {
             av_free_packet(pkt);
             return AVERROR(EIO);
diff --git a/libavformat/rtpdec.c b/libavformat/rtpdec.c
index 28a926f..2227e23 100644
--- a/libavformat/rtpdec.c
+++ b/libavformat/rtpdec.c
@@ -56,6 +56,12 @@
     .codec_id   = AV_CODEC_ID_OPUS,
 };
 
+static RTPDynamicProtocolHandler t140_dynamic_handler = { /* RFC 4103 */
+    .enc_name   = "t140",
+    .codec_type = AVMEDIA_TYPE_SUBTITLE,
+    .codec_id   = AV_CODEC_ID_TEXT,
+};
+
 static RTPDynamicProtocolHandler *rtp_first_dynamic_payload_handler = NULL;
 
 void ff_register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler)
@@ -66,8 +72,10 @@
 
 void ff_register_rtp_dynamic_payload_handlers(void)
 {
+    ff_register_dynamic_payload_handler(&ff_ac3_dynamic_handler);
     ff_register_dynamic_payload_handler(&ff_amr_nb_dynamic_handler);
     ff_register_dynamic_payload_handler(&ff_amr_wb_dynamic_handler);
+    ff_register_dynamic_payload_handler(&ff_dv_dynamic_handler);
     ff_register_dynamic_payload_handler(&ff_g726_16_dynamic_handler);
     ff_register_dynamic_payload_handler(&ff_g726_24_dynamic_handler);
     ff_register_dynamic_payload_handler(&ff_g726_32_dynamic_handler);
@@ -83,6 +91,7 @@
     ff_register_dynamic_payload_handler(&ff_mp4a_latm_dynamic_handler);
     ff_register_dynamic_payload_handler(&ff_mp4v_es_dynamic_handler);
     ff_register_dynamic_payload_handler(&ff_mpeg_audio_dynamic_handler);
+    ff_register_dynamic_payload_handler(&ff_mpeg_audio_robust_dynamic_handler);
     ff_register_dynamic_payload_handler(&ff_mpeg_video_dynamic_handler);
     ff_register_dynamic_payload_handler(&ff_mpeg4_generic_dynamic_handler);
     ff_register_dynamic_payload_handler(&ff_mpegts_dynamic_handler);
@@ -98,10 +107,12 @@
     ff_register_dynamic_payload_handler(&ff_theora_dynamic_handler);
     ff_register_dynamic_payload_handler(&ff_vorbis_dynamic_handler);
     ff_register_dynamic_payload_handler(&ff_vp8_dynamic_handler);
+    ff_register_dynamic_payload_handler(&ff_vp9_dynamic_handler);
     ff_register_dynamic_payload_handler(&gsm_dynamic_handler);
     ff_register_dynamic_payload_handler(&opus_dynamic_handler);
     ff_register_dynamic_payload_handler(&realmedia_mp3_dynamic_handler);
     ff_register_dynamic_payload_handler(&speex_dynamic_handler);
+    ff_register_dynamic_payload_handler(&t140_dynamic_handler);
 }
 
 RTPDynamicProtocolHandler *ff_rtp_handler_find_by_name(const char *name,
@@ -110,7 +121,8 @@
     RTPDynamicProtocolHandler *handler;
     for (handler = rtp_first_dynamic_payload_handler;
          handler; handler = handler->next)
-        if (!av_strcasecmp(name, handler->enc_name) &&
+        if (handler->enc_name &&
+            !av_strcasecmp(name, handler->enc_name) &&
             codec_type == handler->codec_type)
             return handler;
     return NULL;
@@ -150,7 +162,7 @@
                 s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;
                 if (!s->base_timestamp)
                     s->base_timestamp = s->last_rtcp_timestamp;
-                s->rtcp_ts_offset = s->last_rtcp_timestamp - s->base_timestamp;
+                s->rtcp_ts_offset = (int32_t)(s->last_rtcp_timestamp - s->base_timestamp);
             }
 
             break;
@@ -840,7 +852,7 @@
                   int (*parse_fmtp)(AVFormatContext *s,
                                     AVStream *stream,
                                     PayloadContext *data,
-                                    char *attr, char *value))
+                                    const char *attr, const char *value))
 {
     char attr[256];
     char *value;
diff --git a/libavformat/rtpdec.h b/libavformat/rtpdec.h
index 7b41cc4..96cbb5e 100644
--- a/libavformat/rtpdec.h
+++ b/libavformat/rtpdec.h
@@ -113,22 +113,24 @@
                                                int len, uint16_t seq, int flags);
 
 struct RTPDynamicProtocolHandler {
-    const char enc_name[50];
+    const char *enc_name;
     enum AVMediaType codec_type;
     enum AVCodecID codec_id;
+    enum AVStreamParseType need_parsing;
     int static_payload_id; /* 0 means no payload id is set. 0 is a valid
                             * payload ID (PCMU), too, but that format doesn't
                             * require any custom depacketization code. */
+    int priv_data_size;
 
     /** Initialize dynamic protocol handler, called after the full rtpmap line is parsed, may be null */
     int (*init)(AVFormatContext *s, int st_index, PayloadContext *priv_data);
     /** Parse the a= line from the sdp field */
     int (*parse_sdp_a_line)(AVFormatContext *s, int st_index,
                             PayloadContext *priv_data, const char *line);
-    /** Allocate any data needed by the rtp parsing for this dynamic data. */
-    PayloadContext *(*alloc)(void);
-    /** Free any data needed by the rtp parsing for this dynamic data. */
-    void (*free)(PayloadContext *protocol_data);
+    /** Free any data needed by the rtp parsing for this dynamic data.
+      * Don't free the protocol_data pointer itself, that is freed by the
+      * caller. This is called even if the init method failed. */
+    void (*close)(PayloadContext *protocol_data);
     /** Parse handler for this dynamic packet */
     DynamicPayloadPacketHandlerProc parse_packet;
     int (*need_keyframe)(PayloadContext *context);
@@ -205,7 +207,7 @@
                   int (*parse_fmtp)(AVFormatContext *s,
                                     AVStream *stream,
                                     PayloadContext *data,
-                                    char *attr, char *value));
+                                    const char *attr, const char *value));
 
 void ff_register_rtp_dynamic_payload_handlers(void);
 
diff --git a/libavformat/rtpdec_ac3.c b/libavformat/rtpdec_ac3.c
new file mode 100644
index 0000000..48b2d9c
--- /dev/null
+++ b/libavformat/rtpdec_ac3.c
@@ -0,0 +1,133 @@
+/*
+ * RTP parser for AC3 payload format (RFC 4184)
+ * Copyright (c) 2015 Gilles Chanteperdrix <gch@xenomai.org>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "avio_internal.h"
+#include "rtpdec_formats.h"
+
+#define RTP_AC3_PAYLOAD_HEADER_SIZE 2
+
+struct PayloadContext {
+    unsigned nr_frames;
+    unsigned last_frame;
+    uint32_t timestamp;
+    AVIOContext *fragment;
+};
+
+static void ac3_close_context(PayloadContext *data)
+{
+    ffio_free_dyn_buf(&data->fragment);
+}
+
+static int ac3_handle_packet(AVFormatContext *ctx, PayloadContext *data,
+                             AVStream *st, AVPacket *pkt, uint32_t *timestamp,
+                             const uint8_t *buf, int len, uint16_t seq,
+                             int flags)
+{
+    unsigned frame_type;
+    unsigned nr_frames;
+    int err;
+
+    if (len < RTP_AC3_PAYLOAD_HEADER_SIZE + 1) {
+        av_log(ctx, AV_LOG_ERROR, "Invalid %d bytes packet\n", len);
+        return AVERROR_INVALIDDATA;
+    }
+
+    frame_type = buf[0] & 0x3;
+    nr_frames = buf[1];
+    buf += RTP_AC3_PAYLOAD_HEADER_SIZE;
+    len -= RTP_AC3_PAYLOAD_HEADER_SIZE;
+
+    switch (frame_type) {
+    case 0: /* One or more complete frames */
+        if (!nr_frames) {
+            av_log(ctx, AV_LOG_ERROR, "Invalid AC3 packet data\n");
+            return AVERROR_INVALIDDATA;
+        }
+        if (av_new_packet(pkt, len)) {
+            av_log(ctx, AV_LOG_ERROR, "Out of memory.\n");
+            return AVERROR(ENOMEM);
+        }
+
+        pkt->stream_index = st->index;
+        memcpy(pkt->data, buf, len);
+        return 0;
+
+    case 1:
+    case 2: /* First fragment */
+        ffio_free_dyn_buf(&data->fragment);
+
+        data->last_frame = 1;
+        data->nr_frames = nr_frames;
+        err = avio_open_dyn_buf(&data->fragment);
+        if (err < 0)
+            return err;
+
+        avio_write(data->fragment, buf, len);
+        data->timestamp = *timestamp;
+        return AVERROR(EAGAIN);
+
+    case 3: /* Fragment other than first */
+        if (!data->fragment) {
+            av_log(ctx, AV_LOG_WARNING,
+                   "Received packet without a start fragment; dropping.\n");
+            return AVERROR(EAGAIN);
+        }
+        if (nr_frames != data->nr_frames ||
+            data->timestamp != *timestamp) {
+            ffio_free_dyn_buf(&data->fragment);
+            av_log(ctx, AV_LOG_ERROR, "Invalid packet received\n");
+            return AVERROR_INVALIDDATA;
+        }
+
+        avio_write(data->fragment, buf, len);
+        data->last_frame++;
+    }
+
+    if (!(flags & RTP_FLAG_MARKER))
+        return AVERROR(EAGAIN);
+
+    if (data->last_frame != data->nr_frames) {
+        ffio_free_dyn_buf(&data->fragment);
+        av_log(ctx, AV_LOG_ERROR, "Missed %d packets\n",
+               data->nr_frames - data->last_frame);
+        return AVERROR_INVALIDDATA;
+    }
+
+    err = ff_rtp_finalize_packet(pkt, &data->fragment, st->index);
+    if (err < 0) {
+        av_log(ctx, AV_LOG_ERROR,
+               "Error occurred when getting fragment buffer.\n");
+        return err;
+    }
+
+    return 0;
+}
+
+RTPDynamicProtocolHandler ff_ac3_dynamic_handler = {
+    .enc_name           = "ac3",
+    .codec_type         = AVMEDIA_TYPE_AUDIO,
+    .codec_id           = AV_CODEC_ID_AC3,
+    .need_parsing       = AVSTREAM_PARSE_FULL,
+    .priv_data_size     = sizeof(PayloadContext),
+    .close              = ac3_close_context,
+    .parse_packet       = ac3_handle_packet,
+};
diff --git a/libavformat/rtpdec_amr.c b/libavformat/rtpdec_amr.c
index 31acfe7..848db9d 100644
--- a/libavformat/rtpdec_amr.c
+++ b/libavformat/rtpdec_amr.c
@@ -38,17 +38,10 @@
     int channels;
 };
 
-static PayloadContext *amr_new_context(void)
+static av_cold int amr_init(AVFormatContext *s, int st_index, PayloadContext *data)
 {
-    PayloadContext *data = av_mallocz(sizeof(PayloadContext));
-    if(!data) return data;
     data->channels = 1;
-    return data;
-}
-
-static void amr_free_context(PayloadContext *data)
-{
-    av_free(data);
+    return 0;
 }
 
 static int amr_handle_packet(AVFormatContext *ctx, PayloadContext *data,
@@ -141,7 +134,7 @@
 
 static int amr_parse_fmtp(AVFormatContext *s,
                           AVStream *stream, PayloadContext *data,
-                          char *attr, char *value)
+                          const char *attr, const char *value)
 {
     /* Some AMR SDP configurations contain "octet-align", without
      * the trailing =1. Therefore, if the value is empty,
@@ -150,7 +143,7 @@
     if (!strcmp(value, "")) {
         av_log(s, AV_LOG_WARNING, "AMR fmtp attribute %s had "
                                   "nonstandard empty value\n", attr);
-        strcpy(value, "1");
+        value = "1";
     }
     if (!strcmp(attr, "octet-align"))
         data->octet_align = atoi(value);
@@ -193,9 +186,9 @@
     .enc_name         = "AMR",
     .codec_type       = AVMEDIA_TYPE_AUDIO,
     .codec_id         = AV_CODEC_ID_AMR_NB,
+    .priv_data_size   = sizeof(PayloadContext),
+    .init             = amr_init,
     .parse_sdp_a_line = amr_parse_sdp_line,
-    .alloc            = amr_new_context,
-    .free             = amr_free_context,
     .parse_packet     = amr_handle_packet,
 };
 
@@ -203,8 +196,8 @@
     .enc_name         = "AMR-WB",
     .codec_type       = AVMEDIA_TYPE_AUDIO,
     .codec_id         = AV_CODEC_ID_AMR_WB,
+    .priv_data_size   = sizeof(PayloadContext),
+    .init             = amr_init,
     .parse_sdp_a_line = amr_parse_sdp_line,
-    .alloc            = amr_new_context,
-    .free             = amr_free_context,
     .parse_packet     = amr_handle_packet,
 };
diff --git a/libavformat/rtpdec_asf.c b/libavformat/rtpdec_asf.c
index 44c0a24..e8377b9 100644
--- a/libavformat/rtpdec_asf.c
+++ b/libavformat/rtpdec_asf.c
@@ -205,8 +205,6 @@
             int start_off = avio_tell(pb);
 
             mflags = avio_r8(pb);
-            if (mflags & 0x80)
-                flags |= RTP_FLAG_KEY;
             len_off = avio_rb24(pb);
             if (mflags & 0x20)   /**< relative timestamp */
                 avio_skip(pb, 4);
@@ -224,10 +222,7 @@
                  * multiple RTP packets.
                  */
                 if (asf->pktbuf && len_off != avio_tell(asf->pktbuf)) {
-                    uint8_t *p;
-                    avio_close_dyn_buf(asf->pktbuf, &p);
-                    asf->pktbuf = NULL;
-                    av_free(p);
+                    ffio_free_dyn_buf(&asf->pktbuf);
                 }
                 if (!len_off && !asf->pktbuf &&
                     (res = avio_open_dyn_buf(&asf->pktbuf)) < 0)
@@ -288,21 +283,10 @@
     return res == 1 ? -1 : res;
 }
 
-static PayloadContext *asfrtp_new_context(void)
+static void asfrtp_close_context(PayloadContext *asf)
 {
-    return av_mallocz(sizeof(PayloadContext));
-}
-
-static void asfrtp_free_context(PayloadContext *asf)
-{
-    if (asf->pktbuf) {
-        uint8_t *p = NULL;
-        avio_close_dyn_buf(asf->pktbuf, &p);
-        asf->pktbuf = NULL;
-        av_free(p);
-    }
+    ffio_free_dyn_buf(&asf->pktbuf);
     av_freep(&asf->buf);
-    av_free(asf);
 }
 
 #define RTP_ASF_HANDLER(n, s, t) \
@@ -310,9 +294,9 @@
     .enc_name         = s, \
     .codec_type       = t, \
     .codec_id         = AV_CODEC_ID_NONE, \
+    .priv_data_size   = sizeof(PayloadContext), \
     .parse_sdp_a_line = asfrtp_parse_sdp_line, \
-    .alloc            = asfrtp_new_context, \
-    .free             = asfrtp_free_context, \
+    .close            = asfrtp_close_context, \
     .parse_packet     = asfrtp_parse_packet,   \
 }
 
diff --git a/libavformat/rtpdec_dv.c b/libavformat/rtpdec_dv.c
new file mode 100644
index 0000000..de99d27
--- /dev/null
+++ b/libavformat/rtpdec_dv.c
@@ -0,0 +1,143 @@
+/*
+ * RTP parser for DV payload format (RFC 6469)
+ * Copyright (c) 2015 Thomas Volkert <thomas@homer-conferencing.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/avstring.h"
+
+#include "libavcodec/bytestream.h"
+
+#include "avio_internal.h"
+#include "rtpdec_formats.h"
+
+struct PayloadContext {
+    AVIOContext *buf;
+    uint32_t    timestamp;
+    int         bundled_audio;
+};
+
+static av_cold void dv_close_context(PayloadContext *data)
+{
+    ffio_free_dyn_buf(&data->buf);
+}
+
+static av_cold int dv_sdp_parse_fmtp_config(AVFormatContext *s,
+                                            AVStream *stream,
+                                            PayloadContext *dv_data,
+                                            const char *attr, const char *value)
+{
+    /* does the DV stream include audio? */
+    if (!strcmp(attr, "audio") && !strcmp(value, "bundled"))
+        dv_data->bundled_audio = 1;
+
+    /* extract the DV profile */
+    if (!strcmp(attr, "encode")) {
+        /* SD-VCR/525-60 */
+        /* SD-VCR/625-50 */
+        /* HD-VCR/1125-60 */
+        /* HD-VCR/1250-50 */
+        /* SDL-VCR/525-60 */
+        /* SDL-VCR/625-50 */
+        /* 314M-25/525-60 */
+        /* 314M-25/625-50 */
+        /* 314M-50/525-60 */
+        /* 314M-50/625-50 */
+        /* 370M/1080-60i */
+        /* 370M/1080-50i */
+        /* 370M/720-60p */
+        /* 370M/720-50p */
+        /* 306M/525-60 (for backward compatibility) */
+        /* 306M/625-50 (for backward compatibility) */
+    }
+
+    return 0;
+}
+
+static av_cold int dv_parse_sdp_line(AVFormatContext *ctx, int st_index,
+                                     PayloadContext *dv_data, const char *line)
+{
+    AVStream *current_stream;
+    const char *sdp_line_ptr = line;
+
+    if (st_index < 0)
+        return 0;
+
+    current_stream = ctx->streams[st_index];
+
+    if (av_strstart(sdp_line_ptr, "fmtp:", &sdp_line_ptr)) {
+        return ff_parse_fmtp(ctx, current_stream, dv_data, sdp_line_ptr,
+                             dv_sdp_parse_fmtp_config);
+    }
+
+    return 0;
+}
+
+static int dv_handle_packet(AVFormatContext *ctx, PayloadContext *rtp_dv_ctx,
+                            AVStream *st, AVPacket *pkt, uint32_t *timestamp,
+                            const uint8_t *buf, int len, uint16_t seq,
+                            int flags)
+{
+    int res = 0;
+
+    /* drop data of previous packets in case of non-continuous (lossy) packet stream */
+    if (rtp_dv_ctx->buf && rtp_dv_ctx->timestamp != *timestamp) {
+        ffio_free_dyn_buf(&rtp_dv_ctx->buf);
+    }
+
+    /* sanity check for size of input packet: 1 byte payload at least */
+    if (len < 1) {
+        av_log(ctx, AV_LOG_ERROR, "Too short RTP/DV packet, got %d bytes\n", len);
+        return AVERROR_INVALIDDATA;
+    }
+
+    /* start frame buffering with new dynamic buffer */
+    if (!rtp_dv_ctx->buf) {
+        res = avio_open_dyn_buf(&rtp_dv_ctx->buf);
+        if (res < 0)
+            return res;
+        /* update the timestamp in the frame packet with the one from the RTP packet */
+        rtp_dv_ctx->timestamp = *timestamp;
+    }
+
+    /* write the fragment to the dyn. buffer */
+    avio_write(rtp_dv_ctx->buf, buf, len);
+
+    /* RTP marker bit means: last fragment of current frame was received;
+       otherwise, an additional fragment is needed for the current frame */
+    if (!(flags & RTP_FLAG_MARKER))
+        return AVERROR(EAGAIN);
+
+    /* close frame buffering and create resulting A/V packet */
+    res = ff_rtp_finalize_packet(pkt, &rtp_dv_ctx->buf, st->index);
+    if (res < 0)
+        return res;
+
+    return 0;
+}
+
+RTPDynamicProtocolHandler ff_dv_dynamic_handler = {
+    .enc_name         = "DV",
+    .codec_type       = AVMEDIA_TYPE_VIDEO,
+    .codec_id         = AV_CODEC_ID_DVVIDEO,
+    .need_parsing     = AVSTREAM_PARSE_FULL,
+    .parse_sdp_a_line = dv_parse_sdp_line,
+    .priv_data_size   = sizeof(PayloadContext),
+    .close             = dv_close_context,
+    .parse_packet     = dv_handle_packet,
+};
diff --git a/libavformat/rtpdec_formats.h b/libavformat/rtpdec_formats.h
index 87e316f..50a2f4c 100644
--- a/libavformat/rtpdec_formats.h
+++ b/libavformat/rtpdec_formats.h
@@ -35,8 +35,22 @@
                           AVStream *st, AVPacket *pkt, uint32_t *timestamp,
                           const uint8_t *buf, int len, uint16_t seq, int flags);
 
+int ff_h264_parse_sprop_parameter_sets(AVFormatContext *s,
+                                       uint8_t **data_ptr, int *size_ptr,
+                                       const char *value);
+int ff_h264_handle_aggregated_packet(AVFormatContext *ctx, PayloadContext *data, AVPacket *pkt,
+                                     const uint8_t *buf, int len,
+                                     int start_skip, int *nal_counters,
+                                     int nal_mask);
+int ff_h264_handle_frag_packet(AVPacket *pkt, const uint8_t *buf, int len,
+                               int start_bit, const uint8_t *nal_header,
+                               int nal_header_len);
+void ff_h264_parse_framesize(AVCodecContext *codec, const char *p);
+
+extern RTPDynamicProtocolHandler ff_ac3_dynamic_handler;
 extern RTPDynamicProtocolHandler ff_amr_nb_dynamic_handler;
 extern RTPDynamicProtocolHandler ff_amr_wb_dynamic_handler;
+extern RTPDynamicProtocolHandler ff_dv_dynamic_handler;
 extern RTPDynamicProtocolHandler ff_g726_16_dynamic_handler;
 extern RTPDynamicProtocolHandler ff_g726_24_dynamic_handler;
 extern RTPDynamicProtocolHandler ff_g726_32_dynamic_handler;
@@ -52,6 +66,7 @@
 extern RTPDynamicProtocolHandler ff_mp4a_latm_dynamic_handler;
 extern RTPDynamicProtocolHandler ff_mp4v_es_dynamic_handler;
 extern RTPDynamicProtocolHandler ff_mpeg_audio_dynamic_handler;
+extern RTPDynamicProtocolHandler ff_mpeg_audio_robust_dynamic_handler;
 extern RTPDynamicProtocolHandler ff_mpeg_video_dynamic_handler;
 extern RTPDynamicProtocolHandler ff_mpeg4_generic_dynamic_handler;
 extern RTPDynamicProtocolHandler ff_mpegts_dynamic_handler;
@@ -67,5 +82,6 @@
 extern RTPDynamicProtocolHandler ff_theora_dynamic_handler;
 extern RTPDynamicProtocolHandler ff_vorbis_dynamic_handler;
 extern RTPDynamicProtocolHandler ff_vp8_dynamic_handler;
+extern RTPDynamicProtocolHandler ff_vp9_dynamic_handler;
 
 #endif /* AVFORMAT_RTPDEC_FORMATS_H */
diff --git a/libavformat/rtpdec_h261.c b/libavformat/rtpdec_h261.c
index 9f34889..9729f21 100644
--- a/libavformat/rtpdec_h261.c
+++ b/libavformat/rtpdec_h261.c
@@ -21,6 +21,7 @@
 
 #include "libavcodec/get_bits.h"
 #include "avformat.h"
+#include "avio_internal.h"
 #include "rtpdec_formats.h"
 
 #define RTP_H261_PAYLOAD_HEADER_SIZE 4
@@ -32,43 +33,14 @@
     uint32_t     timestamp;
 };
 
-static av_cold PayloadContext *h261_new_context(void)
-{
-    return av_mallocz(sizeof(PayloadContext));
-}
-
-static void h261_free_dyn_buffer(AVIOContext **dyn_buf)
-{
-    uint8_t *ptr_dyn_buffer;
-    avio_close_dyn_buf(*dyn_buf, &ptr_dyn_buffer);
-    av_free(ptr_dyn_buffer);
-    *dyn_buf = NULL;
-}
-
-static av_cold void h261_free_context(PayloadContext *pl_ctx)
+static av_cold void h261_close_context(PayloadContext *pl_ctx)
 {
     /* return if context is invalid */
     if (!pl_ctx)
         return;
 
     /* free buffer if it is valid */
-    if (pl_ctx->buf) {
-        h261_free_dyn_buffer(&pl_ctx->buf);
-    }
-
-    /* free context */
-    av_free(pl_ctx);
-}
-
-static av_cold int h261_init(AVFormatContext *ctx, int st_index,
-                             PayloadContext *data)
-{
-    if (st_index < 0)
-        return 0;
-
-    ctx->streams[st_index]->need_parsing = AVSTREAM_PARSE_FULL;
-
-    return 0;
+    ffio_free_dyn_buf(&pl_ctx->buf);
 }
 
 static int h261_handle_packet(AVFormatContext *ctx, PayloadContext *rtp_h261_ctx,
@@ -81,7 +53,7 @@
 
     /* drop data of previous packets in case of non-continuous (lossy) packet stream */
     if (rtp_h261_ctx->buf && rtp_h261_ctx->timestamp != *timestamp) {
-        h261_free_dyn_buffer(&rtp_h261_ctx->buf);
+        ffio_free_dyn_buf(&rtp_h261_ctx->buf);
         rtp_h261_ctx->endbyte_bits = 0;
     }
 
@@ -194,9 +166,9 @@
     .enc_name          = "H261",
     .codec_type        = AVMEDIA_TYPE_VIDEO,
     .codec_id          = AV_CODEC_ID_H261,
-    .init              = h261_init,
-    .alloc             = h261_new_context,
-    .free              = h261_free_context,
+    .need_parsing      = AVSTREAM_PARSE_FULL,
+    .priv_data_size    = sizeof(PayloadContext),
+    .close             = h261_close_context,
     .parse_packet      = h261_handle_packet,
     .static_payload_id = 31,
 };
diff --git a/libavformat/rtpdec_h263.c b/libavformat/rtpdec_h263.c
index ae4cc27..97aa4ad 100644
--- a/libavformat/rtpdec_h263.c
+++ b/libavformat/rtpdec_h263.c
@@ -24,15 +24,6 @@
 #include "libavutil/attributes.h"
 #include "libavutil/intreadwrite.h"
 
-static av_cold int h263_init(AVFormatContext *ctx, int st_index,
-                             PayloadContext *data)
-{
-    if (st_index < 0)
-        return 0;
-    ctx->streams[st_index]->need_parsing = AVSTREAM_PARSE_FULL;
-    return 0;
-}
-
 int ff_h263_handle_packet(AVFormatContext *ctx, PayloadContext *data,
                           AVStream *st, AVPacket *pkt, uint32_t *timestamp,
                           const uint8_t *buf, int len, uint16_t seq, int flags)
@@ -102,7 +93,7 @@
     .enc_name         = "H263-1998",
     .codec_type       = AVMEDIA_TYPE_VIDEO,
     .codec_id         = AV_CODEC_ID_H263,
-    .init             = h263_init,
+    .need_parsing     = AVSTREAM_PARSE_FULL,
     .parse_packet     = ff_h263_handle_packet,
 };
 
@@ -110,6 +101,6 @@
     .enc_name         = "H263-2000",
     .codec_type       = AVMEDIA_TYPE_VIDEO,
     .codec_id         = AV_CODEC_ID_H263,
-    .init             = h263_init,
+    .need_parsing     = AVSTREAM_PARSE_FULL,
     .parse_packet     = ff_h263_handle_packet,
 };
diff --git a/libavformat/rtpdec_h263_rfc2190.c b/libavformat/rtpdec_h263_rfc2190.c
index 8a36e53..33712e7 100644
--- a/libavformat/rtpdec_h263_rfc2190.c
+++ b/libavformat/rtpdec_h263_rfc2190.c
@@ -26,6 +26,7 @@
  */
 
 #include "avformat.h"
+#include "avio_internal.h"
 #include "rtpdec_formats.h"
 #include "libavutil/attributes.h"
 #include "libavutil/intreadwrite.h"
@@ -39,29 +40,9 @@
     int          newformat;
 };
 
-static PayloadContext *h263_new_context(void)
+static void h263_close_context(PayloadContext *data)
 {
-    return av_mallocz(sizeof(PayloadContext));
-}
-
-static void h263_free_context(PayloadContext *data)
-{
-    if (!data)
-        return;
-    if (data->buf) {
-        uint8_t *p;
-        avio_close_dyn_buf(data->buf, &p);
-        av_free(p);
-    }
-    av_free(data);
-}
-
-static av_cold int h263_init(AVFormatContext *ctx, int st_index, PayloadContext *data)
-{
-    if (st_index < 0)
-        return 0;
-    ctx->streams[st_index]->need_parsing = AVSTREAM_PARSE_FULL;
-    return 0;
+    ffio_free_dyn_buf(&data->buf);
 }
 
 static int h263_handle_packet(AVFormatContext *ctx, PayloadContext *data,
@@ -79,10 +60,7 @@
 
     if (data->buf && data->timestamp != *timestamp) {
         /* Dropping old buffered, unfinished data */
-        uint8_t *p;
-        avio_close_dyn_buf(data->buf, &p);
-        av_free(p);
-        data->buf = NULL;
+        ffio_free_dyn_buf(&data->buf);
         data->endbyte_bits = 0;
     }
 
@@ -208,9 +186,9 @@
 RTPDynamicProtocolHandler ff_h263_rfc2190_dynamic_handler = {
     .codec_type        = AVMEDIA_TYPE_VIDEO,
     .codec_id          = AV_CODEC_ID_H263,
-    .init              = h263_init,
+    .need_parsing      = AVSTREAM_PARSE_FULL,
     .parse_packet      = h263_handle_packet,
-    .alloc             = h263_new_context,
-    .free              = h263_free_context,
+    .priv_data_size    = sizeof(PayloadContext),
+    .close             = h263_close_context,
     .static_payload_id = 34,
 };
diff --git a/libavformat/rtpdec_h264.c b/libavformat/rtpdec_h264.c
index 4dbbae7..2ac79db 100644
--- a/libavformat/rtpdec_h264.c
+++ b/libavformat/rtpdec_h264.c
@@ -35,13 +35,10 @@
 
 #include "libavutil/attributes.h"
 #include "libavutil/base64.h"
+#include "libavutil/intreadwrite.h"
 #include "libavutil/avstring.h"
-#include "libavcodec/get_bits.h"
 #include "avformat.h"
 
-#include "network.h"
-#include <assert.h>
-
 #include "rtpdec.h"
 #include "rtpdec_formats.h"
 
@@ -58,20 +55,98 @@
 
 #ifdef DEBUG
 #define COUNT_NAL_TYPE(data, nal) data->packet_types_received[(nal) & 0x1f]++
+#define NAL_COUNTERS data->packet_types_received
 #else
 #define COUNT_NAL_TYPE(data, nal) do { } while (0)
+#define NAL_COUNTERS NULL
 #endif
+#define NAL_MASK 0x1f
 
 static const uint8_t start_sequence[] = { 0, 0, 0, 1 };
 
+static void parse_profile_level_id(AVFormatContext *s,
+                                   PayloadContext *h264_data,
+                                   const char *value)
+{
+    char buffer[3];
+    // 6 characters=3 bytes, in hex.
+    uint8_t profile_idc;
+    uint8_t profile_iop;
+    uint8_t level_idc;
+
+    buffer[0]   = value[0];
+    buffer[1]   = value[1];
+    buffer[2]   = '\0';
+    profile_idc = strtol(buffer, NULL, 16);
+    buffer[0]   = value[2];
+    buffer[1]   = value[3];
+    profile_iop = strtol(buffer, NULL, 16);
+    buffer[0]   = value[4];
+    buffer[1]   = value[5];
+    level_idc   = strtol(buffer, NULL, 16);
+
+    av_log(s, AV_LOG_DEBUG,
+           "RTP Profile IDC: %x Profile IOP: %x Level: %x\n",
+           profile_idc, profile_iop, level_idc);
+    h264_data->profile_idc = profile_idc;
+    h264_data->profile_iop = profile_iop;
+    h264_data->level_idc   = level_idc;
+}
+
+int ff_h264_parse_sprop_parameter_sets(AVFormatContext *s,
+                                       uint8_t **data_ptr, int *size_ptr,
+                                       const char *value)
+{
+    char base64packet[1024];
+    uint8_t decoded_packet[1024];
+    int packet_size;
+
+    while (*value) {
+        char *dst = base64packet;
+
+        while (*value && *value != ','
+               && (dst - base64packet) < sizeof(base64packet) - 1) {
+            *dst++ = *value++;
+        }
+        *dst++ = '\0';
+
+        if (*value == ',')
+            value++;
+
+        packet_size = av_base64_decode(decoded_packet, base64packet,
+                                       sizeof(decoded_packet));
+        if (packet_size > 0) {
+            uint8_t *dest = av_realloc(*data_ptr,
+                                       packet_size + sizeof(start_sequence) +
+                                       *size_ptr +
+                                       FF_INPUT_BUFFER_PADDING_SIZE);
+            if (!dest) {
+                av_log(s, AV_LOG_ERROR,
+                       "Unable to allocate memory for extradata!\n");
+                return AVERROR(ENOMEM);
+            }
+            *data_ptr = dest;
+
+            memcpy(dest + *size_ptr, start_sequence,
+                   sizeof(start_sequence));
+            memcpy(dest + *size_ptr + sizeof(start_sequence),
+                   decoded_packet, packet_size);
+            memset(dest + *size_ptr + sizeof(start_sequence) +
+                   packet_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
+
+            *size_ptr += sizeof(start_sequence) + packet_size;
+        }
+    }
+
+    return 0;
+}
+
 static int sdp_parse_fmtp_config_h264(AVFormatContext *s,
                                       AVStream *stream,
                                       PayloadContext *h264_data,
-                                      char *attr, char *value)
+                                      const char *attr, const char *value)
 {
     AVCodecContext *codec = stream->codec;
-    assert(codec->codec_id == AV_CODEC_ID_H264);
-    assert(h264_data);
 
     if (!strcmp(attr, "packetization-mode")) {
         av_log(s, AV_LOG_DEBUG, "RTP Packetization Mode: %d\n", atoi(value));
@@ -87,83 +162,148 @@
             av_log(s, AV_LOG_ERROR,
                    "Interleaved RTP mode is not supported yet.\n");
     } else if (!strcmp(attr, "profile-level-id")) {
-        if (strlen(value) == 6) {
-            char buffer[3];
-            // 6 characters=3 bytes, in hex.
-            uint8_t profile_idc;
-            uint8_t profile_iop;
-            uint8_t level_idc;
-
-            buffer[0]   = value[0];
-            buffer[1]   = value[1];
-            buffer[2]   = '\0';
-            profile_idc = strtol(buffer, NULL, 16);
-            buffer[0]   = value[2];
-            buffer[1]   = value[3];
-            profile_iop = strtol(buffer, NULL, 16);
-            buffer[0]   = value[4];
-            buffer[1]   = value[5];
-            level_idc   = strtol(buffer, NULL, 16);
-
-            av_log(s, AV_LOG_DEBUG,
-                   "RTP Profile IDC: %x Profile IOP: %x Level: %x\n",
-                   profile_idc, profile_iop, level_idc);
-            h264_data->profile_idc = profile_idc;
-            h264_data->profile_iop = profile_iop;
-            h264_data->level_idc   = level_idc;
-        }
+        if (strlen(value) == 6)
+            parse_profile_level_id(s, h264_data, value);
     } else if (!strcmp(attr, "sprop-parameter-sets")) {
+        int ret;
         codec->extradata_size = 0;
         av_freep(&codec->extradata);
-
-        while (*value) {
-            char base64packet[1024];
-            uint8_t decoded_packet[1024];
-            int packet_size;
-            char *dst = base64packet;
-
-            while (*value && *value != ','
-                   && (dst - base64packet) < sizeof(base64packet) - 1) {
-                *dst++ = *value++;
-            }
-            *dst++ = '\0';
-
-            if (*value == ',')
-                value++;
-
-            packet_size = av_base64_decode(decoded_packet, base64packet,
-                                           sizeof(decoded_packet));
-            if (packet_size > 0) {
-                uint8_t *dest = av_malloc(packet_size + sizeof(start_sequence) +
-                                          codec->extradata_size +
-                                          FF_INPUT_BUFFER_PADDING_SIZE);
-                if (!dest) {
-                    av_log(s, AV_LOG_ERROR,
-                           "Unable to allocate memory for extradata!\n");
-                    return AVERROR(ENOMEM);
-                }
-                if (codec->extradata_size) {
-                    memcpy(dest, codec->extradata, codec->extradata_size);
-                    av_free(codec->extradata);
-                }
-
-                memcpy(dest + codec->extradata_size, start_sequence,
-                       sizeof(start_sequence));
-                memcpy(dest + codec->extradata_size + sizeof(start_sequence),
-                       decoded_packet, packet_size);
-                memset(dest + codec->extradata_size + sizeof(start_sequence) +
-                       packet_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
-
-                codec->extradata       = dest;
-                codec->extradata_size += sizeof(start_sequence) + packet_size;
-            }
-        }
-        av_log(s, AV_LOG_DEBUG, "Extradata set to %p (size: %d)!\n",
+        ret = ff_h264_parse_sprop_parameter_sets(s, &codec->extradata,
+                                                 &codec->extradata_size, value);
+        av_log(s, AV_LOG_DEBUG, "Extradata set to %p (size: %d)\n",
                codec->extradata, codec->extradata_size);
+        return ret;
     }
     return 0;
 }
 
+void ff_h264_parse_framesize(AVCodecContext *codec, const char *p)
+{
+    char buf1[50];
+    char *dst = buf1;
+
+    // remove the protocol identifier
+    while (*p && *p == ' ')
+        p++;                     // strip spaces.
+    while (*p && *p != ' ')
+        p++;                     // eat protocol identifier
+    while (*p && *p == ' ')
+        p++;                     // strip trailing spaces.
+    while (*p && *p != '-' && (dst - buf1) < sizeof(buf1) - 1)
+        *dst++ = *p++;
+    *dst = '\0';
+
+    // a='framesize:96 320-240'
+    // set our parameters
+    codec->width   = atoi(buf1);
+    codec->height  = atoi(p + 1); // skip the -
+}
+
+int ff_h264_handle_aggregated_packet(AVFormatContext *ctx, PayloadContext *data, AVPacket *pkt,
+                                     const uint8_t *buf, int len,
+                                     int skip_between, int *nal_counters,
+                                     int nal_mask)
+{
+    int pass         = 0;
+    int total_length = 0;
+    uint8_t *dst     = NULL;
+    int ret;
+
+    // first we are going to figure out the total size
+    for (pass = 0; pass < 2; pass++) {
+        const uint8_t *src = buf;
+        int src_len        = len;
+
+        while (src_len > 2) {
+            uint16_t nal_size = AV_RB16(src);
+
+            // consume the length of the aggregate
+            src     += 2;
+            src_len -= 2;
+
+            if (nal_size <= src_len) {
+                if (pass == 0) {
+                    // counting
+                    total_length += sizeof(start_sequence) + nal_size;
+                } else {
+                    // copying
+                    memcpy(dst, start_sequence, sizeof(start_sequence));
+                    dst += sizeof(start_sequence);
+                    memcpy(dst, src, nal_size);
+                    if (nal_counters)
+                        nal_counters[(*src) & nal_mask]++;
+                    dst += nal_size;
+                }
+            } else {
+                av_log(ctx, AV_LOG_ERROR,
+                       "nal size exceeds length: %d %d\n", nal_size, src_len);
+                return AVERROR_INVALIDDATA;
+            }
+
+            // eat what we handled
+            src     += nal_size + skip_between;
+            src_len -= nal_size + skip_between;
+        }
+
+        if (pass == 0) {
+            /* now we know the total size of the packet (with the
+             * start sequences added) */
+            if ((ret = av_new_packet(pkt, total_length)) < 0)
+                return ret;
+            dst = pkt->data;
+        }
+    }
+
+    return 0;
+}
+
+int ff_h264_handle_frag_packet(AVPacket *pkt, const uint8_t *buf, int len,
+                               int start_bit, const uint8_t *nal_header,
+                               int nal_header_len)
+{
+    int ret;
+    int tot_len = len;
+    int pos = 0;
+    if (start_bit)
+        tot_len += sizeof(start_sequence) + nal_header_len;
+    if ((ret = av_new_packet(pkt, tot_len)) < 0)
+        return ret;
+    if (start_bit) {
+        memcpy(pkt->data + pos, start_sequence, sizeof(start_sequence));
+        pos += sizeof(start_sequence);
+        memcpy(pkt->data + pos, nal_header, nal_header_len);
+        pos += nal_header_len;
+    }
+    memcpy(pkt->data + pos, buf, len);
+    return 0;
+}
+
+static int h264_handle_packet_fu_a(AVFormatContext *ctx, PayloadContext *data, AVPacket *pkt,
+                                   const uint8_t *buf, int len,
+                                   int *nal_counters, int nal_mask)
+{
+    uint8_t fu_indicator, fu_header, start_bit, nal_type, nal;
+
+    if (len < 3) {
+        av_log(ctx, AV_LOG_ERROR, "Too short data for FU-A H264 RTP packet\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    fu_indicator = buf[0];
+    fu_header    = buf[1];
+    start_bit    = fu_header >> 7;
+    nal_type     = fu_header & 0x1f;
+    nal          = fu_indicator & 0xe0 | nal_type;
+
+    // skip the fu_indicator and fu_header
+    buf += 2;
+    len -= 2;
+
+    if (start_bit && nal_counters)
+        nal_counters[nal_type & nal_mask]++;
+    return ff_h264_handle_frag_packet(pkt, buf, len, start_bit, &nal, 1);
+}
+
 // return 0 on packet, no more left, 1 on packet, 1 on partial packet
 static int h264_handle_packet(AVFormatContext *ctx, PayloadContext *data,
                               AVStream *st, AVPacket *pkt, uint32_t *timestamp,
@@ -181,9 +321,6 @@
     nal  = buf[0];
     type = nal & 0x1f;
 
-    assert(data);
-    assert(buf);
-
     /* Simplify the case (these are all the nal types used internally by
      * the h264 codec). */
     if (type >= 1 && type <= 23)
@@ -202,61 +339,8 @@
         // consume the STAP-A NAL
         buf++;
         len--;
-        // first we are going to figure out the total size
-        {
-            int pass         = 0;
-            int total_length = 0;
-            uint8_t *dst     = NULL;
-
-            for (pass = 0; pass < 2; pass++) {
-                const uint8_t *src = buf;
-                int src_len        = len;
-
-                while (src_len > 2) {
-                    uint16_t nal_size = AV_RB16(src);
-
-                    // consume the length of the aggregate
-                    src     += 2;
-                    src_len -= 2;
-
-                    if (nal_size <= src_len) {
-                        if (pass == 0) {
-                            // counting
-                            total_length += sizeof(start_sequence) + nal_size;
-                        } else {
-                            // copying
-                            assert(dst);
-                            memcpy(dst, start_sequence, sizeof(start_sequence));
-                            dst += sizeof(start_sequence);
-                            memcpy(dst, src, nal_size);
-                            COUNT_NAL_TYPE(data, *src);
-                            dst += nal_size;
-                        }
-                    } else {
-                        av_log(ctx, AV_LOG_ERROR,
-                               "nal size exceeds length: %d %d\n", nal_size, src_len);
-                    }
-
-                    // eat what we handled
-                    src     += nal_size;
-                    src_len -= nal_size;
-
-                    if (src_len < 0)
-                        av_log(ctx, AV_LOG_ERROR,
-                               "Consumed more bytes than we got! (%d)\n", src_len);
-                }
-
-                if (pass == 0) {
-                    /* now we know the total size of the packet (with the
-                     * start sequences added) */
-                    if ((result = av_new_packet(pkt, total_length)) < 0)
-                        return result;
-                    dst = pkt->data;
-                } else {
-                    assert(dst - pkt->data == total_length);
-                }
-            }
-        }
+        result = ff_h264_handle_aggregated_packet(ctx, data, pkt, buf, len, 0,
+                                                  NAL_COUNTERS, NAL_MASK);
         break;
 
     case 25:                   // STAP-B
@@ -264,51 +348,14 @@
     case 27:                   // MTAP-24
     case 29:                   // FU-B
         av_log(ctx, AV_LOG_ERROR,
-               "Unhandled type (%d) (See RFC for implementation details\n",
+               "Unhandled type (%d) (See RFC for implementation details)\n",
                type);
         result = AVERROR(ENOSYS);
         break;
 
     case 28:                   // FU-A (fragmented nal)
-        buf++;
-        len--;                 // skip the fu_indicator
-        if (len > 1) {
-            // these are the same as above, we just redo them here for clarity
-            uint8_t fu_indicator      = nal;
-            uint8_t fu_header         = *buf;
-            uint8_t start_bit         = fu_header >> 7;
-            uint8_t av_unused end_bit = (fu_header & 0x40) >> 6;
-            uint8_t nal_type          = fu_header & 0x1f;
-            uint8_t reconstructed_nal;
-
-            // Reconstruct this packet's true nal; only the data follows.
-            /* The original nal forbidden bit and NRI are stored in this
-             * packet's nal. */
-            reconstructed_nal  = fu_indicator & 0xe0;
-            reconstructed_nal |= nal_type;
-
-            // skip the fu_header
-            buf++;
-            len--;
-
-            if (start_bit)
-                COUNT_NAL_TYPE(data, nal_type);
-            if (start_bit) {
-                /* copy in the start sequence, and the reconstructed nal */
-                if ((result = av_new_packet(pkt, sizeof(start_sequence) + sizeof(nal) + len)) < 0)
-                    return result;
-                memcpy(pkt->data, start_sequence, sizeof(start_sequence));
-                pkt->data[sizeof(start_sequence)] = reconstructed_nal;
-                memcpy(pkt->data + sizeof(start_sequence) + sizeof(nal), buf, len);
-            } else {
-                if ((result = av_new_packet(pkt, len)) < 0)
-                    return result;
-                memcpy(pkt->data, buf, len);
-            }
-        } else {
-            av_log(ctx, AV_LOG_ERROR, "Too short data for FU-A H264 RTP packet\n");
-            result = AVERROR_INVALIDDATA;
-        }
+        result = h264_handle_packet_fu_a(ctx, data, pkt, buf, len,
+                                         NAL_COUNTERS, NAL_MASK);
         break;
 
     case 30:                   // undefined
@@ -324,12 +371,7 @@
     return result;
 }
 
-static PayloadContext *h264_new_context(void)
-{
-    return av_mallocz(sizeof(PayloadContext) + FF_INPUT_BUFFER_PADDING_SIZE);
-}
-
-static void h264_free_context(PayloadContext *data)
+static void h264_close_context(PayloadContext *data)
 {
 #ifdef DEBUG
     int ii;
@@ -340,51 +382,21 @@
                    data->packet_types_received[ii], ii);
     }
 #endif
-
-    av_free(data);
-}
-
-static av_cold int h264_init(AVFormatContext *s, int st_index,
-                             PayloadContext *data)
-{
-    if (st_index < 0)
-        return 0;
-    s->streams[st_index]->need_parsing = AVSTREAM_PARSE_FULL;
-    return 0;
 }
 
 static int parse_h264_sdp_line(AVFormatContext *s, int st_index,
                                PayloadContext *h264_data, const char *line)
 {
     AVStream *stream;
-    AVCodecContext *codec;
     const char *p = line;
 
     if (st_index < 0)
         return 0;
 
     stream = s->streams[st_index];
-    codec  = stream->codec;
 
     if (av_strstart(p, "framesize:", &p)) {
-        char buf1[50];
-        char *dst = buf1;
-
-        // remove the protocol identifier
-        while (*p && *p == ' ')
-            p++;                     // strip spaces.
-        while (*p && *p != ' ')
-            p++;                     // eat protocol identifier
-        while (*p && *p == ' ')
-            p++;                     // strip trailing spaces.
-        while (*p && *p != '-' && (dst - buf1) < sizeof(buf1) - 1)
-            *dst++ = *p++;
-        *dst = '\0';
-
-        // a='framesize:96 320-240'
-        // set our parameters
-        codec->width   = atoi(buf1);
-        codec->height  = atoi(p + 1); // skip the -
+        ff_h264_parse_framesize(stream->codec, p);
     } else if (av_strstart(p, "fmtp:", &p)) {
         return ff_parse_fmtp(s, stream, h264_data, p, sdp_parse_fmtp_config_h264);
     } else if (av_strstart(p, "cliprect:", &p)) {
@@ -398,9 +410,9 @@
     .enc_name         = "H264",
     .codec_type       = AVMEDIA_TYPE_VIDEO,
     .codec_id         = AV_CODEC_ID_H264,
-    .init             = h264_init,
+    .need_parsing     = AVSTREAM_PARSE_FULL,
+    .priv_data_size   = sizeof(PayloadContext),
     .parse_sdp_a_line = parse_h264_sdp_line,
-    .alloc            = h264_new_context,
-    .free             = h264_free_context,
-    .parse_packet     = h264_handle_packet
+    .close            = h264_close_context,
+    .parse_packet     = h264_handle_packet,
 };
diff --git a/libavformat/rtpdec_hevc.c b/libavformat/rtpdec_hevc.c
index 3926614..6ceae44 100644
--- a/libavformat/rtpdec_hevc.c
+++ b/libavformat/rtpdec_hevc.c
@@ -23,14 +23,18 @@
 #include "libavutil/avassert.h"
 #include "libavutil/avstring.h"
 #include "libavutil/base64.h"
+#include "libavcodec/get_bits.h"
 
 #include "avformat.h"
 #include "rtpdec.h"
+#include "rtpdec_formats.h"
 
-#define RTP_HEVC_PAYLOAD_HEADER_SIZE  2
-#define RTP_HEVC_FU_HEADER_SIZE       1
-#define RTP_HEVC_DONL_FIELD_SIZE      2
-#define HEVC_SPECIFIED_NAL_UNIT_TYPES 48
+#define RTP_HEVC_PAYLOAD_HEADER_SIZE       2
+#define RTP_HEVC_FU_HEADER_SIZE            1
+#define RTP_HEVC_DONL_FIELD_SIZE           2
+#define RTP_HEVC_DOND_FIELD_SIZE           1
+#define RTP_HEVC_AP_NALU_LENGTH_FIELD_SIZE 2
+#define HEVC_SPECIFIED_NAL_UNIT_TYPES      48
 
 /* SDP out-of-band signaling data */
 struct PayloadContext {
@@ -42,33 +46,10 @@
 
 static const uint8_t start_sequence[] = { 0x00, 0x00, 0x00, 0x01 };
 
-static av_cold PayloadContext *hevc_new_context(void)
-{
-    return av_mallocz(sizeof(PayloadContext));
-}
-
-static av_cold void hevc_free_context(PayloadContext *data)
-{
-    av_free(data);
-}
-
-static av_cold int hevc_init(AVFormatContext *ctx, int st_index,
-                             PayloadContext *data)
-{
-    av_dlog(ctx, "hevc_init() for stream %d\n", st_index);
-
-    if (st_index < 0)
-        return 0;
-
-    ctx->streams[st_index]->need_parsing = AVSTREAM_PARSE_FULL;
-
-    return 0;
-}
-
 static av_cold int hevc_sdp_parse_fmtp_config(AVFormatContext *s,
                                               AVStream *stream,
                                               PayloadContext *hevc_data,
-                                              char *attr, char *value)
+                                              const char *attr, const char *value)
 {
     /* profile-space: 0-3 */
     /* profile-id: 0-31 */
@@ -91,8 +72,8 @@
     /* sprop-sei: [base64] */
     if (!strcmp(attr, "sprop-vps") || !strcmp(attr, "sprop-sps") ||
         !strcmp(attr, "sprop-pps") || !strcmp(attr, "sprop-sei")) {
-        uint8_t **data_ptr;
-        int *size_ptr;
+        uint8_t **data_ptr = NULL;
+        int *size_ptr = NULL;
         if (!strcmp(attr, "sprop-vps")) {
             data_ptr = &hevc_data->vps;
             size_ptr = &hevc_data->vps_size;
@@ -108,41 +89,8 @@
         } else
             av_assert0(0);
 
-        while (*value) {
-            char base64packet[1024];
-            uint8_t decoded_packet[1024];
-            int decoded_packet_size;
-            char *dst = base64packet;
-
-            while (*value && *value != ',' &&
-                   (dst - base64packet) < sizeof(base64packet) - 1) {
-                *dst++ = *value++;
-            }
-            *dst++ = '\0';
-
-            if (*value == ',')
-                value++;
-
-            decoded_packet_size = av_base64_decode(decoded_packet, base64packet,
-                                                   sizeof(decoded_packet));
-            if (decoded_packet_size > 0) {
-                uint8_t *tmp = av_realloc(*data_ptr, decoded_packet_size +
-                                          sizeof(start_sequence) + *size_ptr);
-                if (!tmp) {
-                    av_log(s, AV_LOG_ERROR,
-                           "Unable to allocate memory for extradata!\n");
-                    return AVERROR(ENOMEM);
-                }
-                *data_ptr = tmp;
-
-                memcpy(*data_ptr + *size_ptr, start_sequence,
-                       sizeof(start_sequence));
-                memcpy(*data_ptr + *size_ptr + sizeof(start_sequence),
-                       decoded_packet, decoded_packet_size);
-
-                *size_ptr += sizeof(start_sequence) + decoded_packet_size;
-            }
-        }
+        ff_h264_parse_sprop_parameter_sets(s, data_ptr,
+                                           size_ptr, value);
     }
 
     /* max-lsr, max-lps, max-cpb, max-dpb, max-br, max-tr, max-tc */
@@ -194,33 +142,7 @@
     codec  = current_stream->codec;
 
     if (av_strstart(sdp_line_ptr, "framesize:", &sdp_line_ptr)) {
-        char str_video_width[50];
-        char *str_video_width_ptr = str_video_width;
-
-        /*
-         * parse "a=framesize:96 320-240"
-         */
-
-        /* ignore spaces */
-        while (*sdp_line_ptr && *sdp_line_ptr == ' ')
-            sdp_line_ptr++;
-        /* ignore RTP payload ID */
-        while (*sdp_line_ptr && *sdp_line_ptr != ' ')
-            sdp_line_ptr++;
-        /* ignore spaces */
-        while (*sdp_line_ptr && *sdp_line_ptr == ' ')
-            sdp_line_ptr++;
-        /* extract the actual video resolution description */
-        while (*sdp_line_ptr && *sdp_line_ptr != '-' &&
-               (str_video_width_ptr - str_video_width) < sizeof(str_video_width) - 1)
-            *str_video_width_ptr++ = *sdp_line_ptr++;
-        /* add trailing zero byte */
-        *str_video_width_ptr = '\0';
-
-        /* determine the width value */
-        codec->width   = atoi(str_video_width);
-        /* jump beyond the "-" and determine the height value */
-        codec->height  = atoi(sdp_line_ptr + 1);
+        ff_h264_parse_framesize(codec, sdp_line_ptr);
     } else if (av_strstart(sdp_line_ptr, "fmtp:", &sdp_line_ptr)) {
         int ret = ff_parse_fmtp(ctx, current_stream, hevc_data, sdp_line_ptr,
                                 hevc_sdp_parse_fmtp_config);
@@ -280,19 +202,19 @@
     }
 
     /*
-      decode the HEVC payload header according to section 4 of draft version 6:
-
-         0                   1
-         0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
-        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-        |F|   Type    |  LayerId  | TID |
-        +-------------+-----------------+
-
-           Forbidden zero (F): 1 bit
-           NAL unit type (Type): 6 bits
-           NUH layer ID (LayerId): 6 bits
-           NUH temporal ID plus 1 (TID): 3 bits
-    */
+     * decode the HEVC payload header according to section 4 of draft version 6:
+     *
+     *    0                   1
+     *    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
+     *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+     *   |F|   Type    |  LayerId  | TID |
+     *   +-------------+-----------------+
+     *
+     *      Forbidden zero (F): 1 bit
+     *      NAL unit type (Type): 6 bits
+     *      NUH layer ID (LayerId): 6 bits
+     *      NUH temporal ID plus 1 (TID): 3 bits
+     */
     nal_type =  (buf[0] >> 1) & 0x3f;
     lid  = ((buf[0] << 5) & 0x20) | ((buf[1] >> 3) & 0x1f);
     tid  =   buf[1] & 0x07;
@@ -317,7 +239,26 @@
     }
 
     switch (nal_type) {
-    /* aggregated packets (AP) */
+    /* video parameter set (VPS) */
+    case 32:
+    /* sequence parameter set (SPS) */
+    case 33:
+    /* picture parameter set (PPS) */
+    case 34:
+    /*  supplemental enhancement information (SEI) */
+    case 39:
+    /* single NAL unit packet */
+    default:
+        /* create A/V packet */
+        if ((res = av_new_packet(pkt, sizeof(start_sequence) + len)) < 0)
+            return res;
+        /* A/V packet: copy start sequence */
+        memcpy(pkt->data, start_sequence, sizeof(start_sequence));
+        /* A/V packet: copy NAL unit data */
+        memcpy(pkt->data + sizeof(start_sequence), buf, len);
+
+        break;
+    /* aggregated packet (AP) - with two or more NAL units */
     case 48:
         /* pass the HEVC payload header */
         buf += RTP_HEVC_PAYLOAD_HEADER_SIZE;
@@ -329,33 +270,12 @@
             len -= RTP_HEVC_DONL_FIELD_SIZE;
         }
 
-        /* fall-through */
-    /* video parameter set (VPS) */
-    case 32:
-    /* sequence parameter set (SPS) */
-    case 33:
-    /* picture parameter set (PPS) */
-    case 34:
-    /*  supplemental enhancement information (SEI) */
-    case 39:
-    /* single NAL unit packet */
-    default:
-        /* sanity check for size of input packet: 1 byte payload at least */
-        if (len < 1) {
-            av_log(ctx, AV_LOG_ERROR,
-                   "Too short RTP/HEVC packet, got %d bytes of NAL unit type %d\n",
-                   len, nal_type);
-            return AVERROR_INVALIDDATA;
-        }
-
-        /* create A/V packet */
-        if ((res = av_new_packet(pkt, sizeof(start_sequence) + len)) < 0)
+        res = ff_h264_handle_aggregated_packet(ctx, rtp_hevc_ctx, pkt, buf, len,
+                                               rtp_hevc_ctx->using_donl_field ?
+                                               RTP_HEVC_DOND_FIELD_SIZE : 0,
+                                               NULL, 0);
+        if (res < 0)
             return res;
-        /* A/V packet: copy start sequence */
-        memcpy(pkt->data, start_sequence, sizeof(start_sequence));
-        /* A/V packet: copy NAL unit data */
-        memcpy(pkt->data + sizeof(start_sequence), buf, len);
-
         break;
     /* fragmentation unit (FU) */
     case 49:
@@ -364,17 +284,17 @@
         len -= RTP_HEVC_PAYLOAD_HEADER_SIZE;
 
         /*
-             decode the FU header
-
-              0 1 2 3 4 5 6 7
-             +-+-+-+-+-+-+-+-+
-             |S|E|  FuType   |
-             +---------------+
-
-                Start fragment (S): 1 bit
-                End fragment (E): 1 bit
-                FuType: 6 bits
-        */
+         *    decode the FU header
+         *
+         *     0 1 2 3 4 5 6 7
+         *    +-+-+-+-+-+-+-+-+
+         *    |S|E|  FuType   |
+         *    +---------------+
+         *
+         *       Start fragment (S): 1 bit
+         *       End fragment (E): 1 bit
+         *       FuType: 6 bits
+         */
         first_fragment = buf[0] & 0x80;
         last_fragment  = buf[0] & 0x40;
         fu_type        = buf[0] & 0x3f;
@@ -392,44 +312,28 @@
         av_dlog(ctx, " FU type %d with %d bytes\n", fu_type, len);
 
         /* sanity check for size of input packet: 1 byte payload at least */
-        if (len > 0) {
-            new_nal_header[0] = (rtp_pl[0] & 0x81) | (fu_type << 1);
-            new_nal_header[1] = rtp_pl[1];
-
-            /* start fragment vs. subsequent fragments */
-            if (first_fragment) {
-                if (!last_fragment) {
-                    /* create A/V packet which is big enough */
-                    if ((res = av_new_packet(pkt, sizeof(start_sequence) + sizeof(new_nal_header) + len)) < 0)
-                        return res;
-                    /* A/V packet: copy start sequence */
-                    memcpy(pkt->data, start_sequence, sizeof(start_sequence));
-                    /* A/V packet: copy new NAL header */
-                    memcpy(pkt->data + sizeof(start_sequence), new_nal_header, sizeof(new_nal_header));
-                    /* A/V packet: copy NAL unit data */
-                    memcpy(pkt->data + sizeof(start_sequence) + sizeof(new_nal_header), buf, len);
-                } else {
-                    av_log(ctx, AV_LOG_ERROR, "Illegal combination of S and E bit in RTP/HEVC packet\n");
-                    res = AVERROR_INVALIDDATA;
-                }
-            } else {
-                /* create A/V packet */
-                if ((res = av_new_packet(pkt, len)) < 0)
-                    return res;
-                /* A/V packet: copy NAL unit data */
-                memcpy(pkt->data, buf, len);
-            }
-        } else {
+        if (len <= 0) {
             if (len < 0) {
                 av_log(ctx, AV_LOG_ERROR,
                        "Too short RTP/HEVC packet, got %d bytes of NAL unit type %d\n",
                        len, nal_type);
-                res = AVERROR_INVALIDDATA;
+                return AVERROR_INVALIDDATA;
             } else {
-                res = AVERROR(EAGAIN);
+                return AVERROR(EAGAIN);
             }
         }
 
+        if (first_fragment && last_fragment) {
+            av_log(ctx, AV_LOG_ERROR, "Illegal combination of S and E bit in RTP/HEVC packet\n");
+            return AVERROR_INVALIDDATA;
+        }
+
+        new_nal_header[0] = (rtp_pl[0] & 0x81) | (fu_type << 1);
+        new_nal_header[1] = rtp_pl[1];
+
+        res = ff_h264_handle_frag_packet(pkt, buf, len, first_fragment,
+                                         new_nal_header, sizeof(new_nal_header));
+
         break;
     /* PACI packet */
     case 50:
@@ -448,9 +352,8 @@
     .enc_name         = "H265",
     .codec_type       = AVMEDIA_TYPE_VIDEO,
     .codec_id         = AV_CODEC_ID_HEVC,
-    .init             = hevc_init,
+    .need_parsing     = AVSTREAM_PARSE_FULL,
+    .priv_data_size   = sizeof(PayloadContext),
     .parse_sdp_a_line = hevc_parse_sdp_line,
-    .alloc            = hevc_new_context,
-    .free             = hevc_free_context,
-    .parse_packet     = hevc_handle_packet
+    .parse_packet     = hevc_handle_packet,
 };
diff --git a/libavformat/rtpdec_ilbc.c b/libavformat/rtpdec_ilbc.c
index aa1579f..82109e1 100644
--- a/libavformat/rtpdec_ilbc.c
+++ b/libavformat/rtpdec_ilbc.c
@@ -25,7 +25,7 @@
 
 static int ilbc_parse_fmtp(AVFormatContext *s,
                            AVStream *stream, PayloadContext *data,
-                           char *attr, char *value)
+                           const char *attr, const char *value)
 {
     if (!strcmp(attr, "mode")) {
         int mode = atoi(value);
diff --git a/libavformat/rtpdec_jpeg.c b/libavformat/rtpdec_jpeg.c
index ccd80ad..2028053 100644
--- a/libavformat/rtpdec_jpeg.c
+++ b/libavformat/rtpdec_jpeg.c
@@ -20,6 +20,7 @@
  */
 
 #include "avformat.h"
+#include "avio_internal.h"
 #include "rtpdec.h"
 #include "rtpdec_formats.h"
 #include "libavutil/intreadwrite.h"
@@ -59,25 +60,9 @@
     99,  99,  99,  99,  99,  99,  99,  99
 };
 
-static PayloadContext *jpeg_new_context(void)
+static void jpeg_close_context(PayloadContext *jpeg)
 {
-    return av_mallocz(sizeof(PayloadContext));
-}
-
-static inline void free_frame_if_needed(PayloadContext *jpeg)
-{
-    if (jpeg->frame) {
-        uint8_t *p;
-        avio_close_dyn_buf(jpeg->frame, &p);
-        av_free(p);
-        jpeg->frame = NULL;
-    }
-}
-
-static void jpeg_free_context(PayloadContext *jpeg)
-{
-    free_frame_if_needed(jpeg);
-    av_free(jpeg);
+    ffio_free_dyn_buf(&jpeg->frame);
 }
 
 static int jpeg_create_huffman_table(PutByteContext *p, int table_class,
@@ -338,7 +323,7 @@
 
         /* Skip the current frame in case of the end packet
          * has been lost somewhere. */
-        free_frame_if_needed(jpeg);
+        ffio_free_dyn_buf(&jpeg->frame);
 
         if ((ret = avio_open_dyn_buf(&jpeg->frame)) < 0)
             return ret;
@@ -364,7 +349,7 @@
     if (jpeg->timestamp != *timestamp) {
         /* Skip the current frame if timestamp is incorrect.
          * A start packet has been lost somewhere. */
-        free_frame_if_needed(jpeg);
+        ffio_free_dyn_buf(&jpeg->frame);
         av_log(ctx, AV_LOG_ERROR, "RTP timestamps don't match.\n");
         return AVERROR_INVALIDDATA;
     }
@@ -402,8 +387,8 @@
     .enc_name          = "JPEG",
     .codec_type        = AVMEDIA_TYPE_VIDEO,
     .codec_id          = AV_CODEC_ID_MJPEG,
-    .alloc             = jpeg_new_context,
-    .free              = jpeg_free_context,
+    .priv_data_size    = sizeof(PayloadContext),
+    .close             = jpeg_close_context,
     .parse_packet      = jpeg_parse_packet,
     .static_payload_id = 26,
 };
diff --git a/libavformat/rtpdec_latm.c b/libavformat/rtpdec_latm.c
index c3cb2f2..7db92f6 100644
--- a/libavformat/rtpdec_latm.c
+++ b/libavformat/rtpdec_latm.c
@@ -19,6 +19,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "avio_internal.h"
 #include "rtpdec_formats.h"
 #include "internal.h"
 #include "libavutil/avstring.h"
@@ -31,22 +32,10 @@
     uint32_t timestamp;
 };
 
-static PayloadContext *latm_new_context(void)
+static void latm_close_context(PayloadContext *data)
 {
-    return av_mallocz(sizeof(PayloadContext));
-}
-
-static void latm_free_context(PayloadContext *data)
-{
-    if (!data)
-        return;
-    if (data->dyn_buf) {
-        uint8_t *p;
-        avio_close_dyn_buf(data->dyn_buf, &p);
-        av_free(p);
-    }
+    ffio_free_dyn_buf(&data->dyn_buf);
     av_freep(&data->buf);
-    av_free(data);
 }
 
 static int latm_parse_packet(AVFormatContext *ctx, PayloadContext *data,
@@ -59,10 +48,7 @@
     if (buf) {
         if (!data->dyn_buf || data->timestamp != *timestamp) {
             av_freep(&data->buf);
-            if (data->dyn_buf)
-                avio_close_dyn_buf(data->dyn_buf, &data->buf);
-            data->dyn_buf = NULL;
-            av_freep(&data->buf);
+            ffio_free_dyn_buf(&data->dyn_buf);
 
             data->timestamp = *timestamp;
             if ((ret = avio_open_dyn_buf(&data->dyn_buf)) < 0)
@@ -103,7 +89,7 @@
     return data->pos < data->len;
 }
 
-static int parse_fmtp_config(AVStream *st, char *value)
+static int parse_fmtp_config(AVStream *st, const char *value)
 {
     int len = ff_hex_to_data(NULL, value), i, ret = 0;
     GetBitContext gb;
@@ -144,7 +130,7 @@
 
 static int parse_fmtp(AVFormatContext *s,
                       AVStream *stream, PayloadContext *data,
-                      char *attr, char *value)
+                      const char *attr, const char *value)
 {
     int res;
 
@@ -180,8 +166,8 @@
     .enc_name           = "MP4A-LATM",
     .codec_type         = AVMEDIA_TYPE_AUDIO,
     .codec_id           = AV_CODEC_ID_AAC,
+    .priv_data_size     = sizeof(PayloadContext),
     .parse_sdp_a_line   = latm_parse_sdp_line,
-    .alloc              = latm_new_context,
-    .free               = latm_free_context,
-    .parse_packet       = latm_parse_packet
+    .close              = latm_close_context,
+    .parse_packet       = latm_parse_packet,
 };
diff --git a/libavformat/rtpdec_mpa_robust.c b/libavformat/rtpdec_mpa_robust.c
new file mode 100644
index 0000000..07057fe
--- /dev/null
+++ b/libavformat/rtpdec_mpa_robust.c
@@ -0,0 +1,200 @@
+/*
+ * RTP parser for loss tolerant payload format for MP3 audio (RFC 5219)
+ * Copyright (c) 2015 Gilles Chanteperdrix <gch@xenomai.org>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/attributes.h"
+#include "libavutil/intreadwrite.h"
+
+#include "avio_internal.h"
+#include "rtpdec_formats.h"
+
+struct PayloadContext {
+    unsigned adu_size;
+    unsigned cur_size;
+    uint32_t timestamp;
+    uint8_t *split_buf;
+    int split_pos, split_buf_size, split_pkts;
+    AVIOContext *fragment;
+};
+
+static void mpa_robust_close_context(PayloadContext *data)
+{
+    ffio_free_dyn_buf(&data->fragment);
+    av_free(data->split_buf);
+}
+
+static int mpa_robust_parse_rtp_header(AVFormatContext *ctx,
+                                       const uint8_t *buf, int len,
+                                       unsigned *adu_size, unsigned *cont)
+{
+    unsigned header_size;
+
+    if (len < 2) {
+        av_log(ctx, AV_LOG_ERROR, "Invalid %d bytes packet\n", len);
+        return AVERROR_INVALIDDATA;
+    }
+
+    *cont = !!(buf[0] & 0x80);
+    if (!(buf[0] & 0x40)) {
+        header_size = 1;
+        *adu_size = buf[0] & ~0xc0;
+    } else {
+        header_size = 2;
+        *adu_size = AV_RB16(buf) & ~0xc000;
+    }
+
+    return header_size;
+}
+
+static int mpa_robust_parse_packet(AVFormatContext *ctx, PayloadContext *data,
+                                   AVStream *st, AVPacket *pkt,
+                                   uint32_t *timestamp, const uint8_t *buf,
+                                   int len, uint16_t seq, int flags)
+{
+    unsigned adu_size, continuation;
+    int err, header_size;
+
+    if (!buf) {
+        buf = &data->split_buf[data->split_pos];
+        len = data->split_buf_size - data->split_pos;
+
+        header_size = mpa_robust_parse_rtp_header(ctx, buf, len, &adu_size,
+                                                  &continuation);
+        if (header_size < 0) {
+            av_freep(&data->split_buf);
+            return header_size;
+        }
+        buf += header_size;
+        len -= header_size;
+
+        if (continuation || adu_size > len) {
+            av_freep(&data->split_buf);
+            av_log(ctx, AV_LOG_ERROR, "Invalid frame\n");
+            return AVERROR_INVALIDDATA;
+        }
+
+        if (av_new_packet(pkt, adu_size)) {
+            av_log(ctx, AV_LOG_ERROR, "Out of memory.\n");
+            return AVERROR(ENOMEM);
+        }
+
+        pkt->stream_index = st->index;
+        memcpy(pkt->data, buf, adu_size);
+
+        data->split_pos += header_size + adu_size;
+
+        if (data->split_pos == data->split_buf_size) {
+            av_freep(&data->split_buf);
+            return 0;
+        }
+
+        return 1;
+    }
+
+
+    header_size = mpa_robust_parse_rtp_header(ctx, buf, len, &adu_size,
+                                              &continuation);
+    if (header_size < 0)
+        return header_size;
+
+    buf += header_size;
+    len -= header_size;
+
+    if (!continuation && adu_size <= len) {
+        /* One or more complete frames */
+
+        if (av_new_packet(pkt, adu_size)) {
+            av_log(ctx, AV_LOG_ERROR, "Out of memory.\n");
+            return AVERROR(ENOMEM);
+        }
+
+        pkt->stream_index = st->index;
+        memcpy(pkt->data, buf, adu_size);
+
+        buf += adu_size;
+        len -= adu_size;
+        if (len) {
+            data->split_buf_size = len;
+            data->split_buf = av_malloc(data->split_buf_size);
+            data->split_pos = 0;
+            if (!data->split_buf) {
+                av_log(ctx, AV_LOG_ERROR, "Out of memory.\n");
+                av_free_packet(pkt);
+                return AVERROR(ENOMEM);
+            }
+            memcpy(data->split_buf, buf, data->split_buf_size);
+            return 1;
+        }
+        return 0;
+    } else if (!continuation) { /* && adu_size > len */
+        /* First fragment */
+        ffio_free_dyn_buf(&data->fragment);
+
+        data->adu_size = adu_size;
+        data->cur_size = len;
+        data->timestamp = *timestamp;
+
+        err = avio_open_dyn_buf(&data->fragment);
+        if (err < 0)
+            return err;
+
+        avio_write(data->fragment, buf, len);
+        return AVERROR(EAGAIN);
+    }
+    /* else continuation == 1 */
+
+    /* Fragment other than first */
+    if (!data->fragment) {
+        av_log(ctx, AV_LOG_WARNING,
+            "Received packet without a start fragment; dropping.\n");
+        return AVERROR(EAGAIN);
+    }
+    if (adu_size = data->adu_size ||
+        data->timestamp != *timestamp) {
+        ffio_free_dyn_buf(&data->fragment);
+        av_log(ctx, AV_LOG_ERROR, "Invalid packet received\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    avio_write(data->fragment, buf, len);
+    data->cur_size += len;
+
+    if (data->cur_size < data->adu_size)
+        return AVERROR(EAGAIN);
+
+    err = ff_rtp_finalize_packet(pkt, &data->fragment, st->index);
+    if (err < 0) {
+        av_log(ctx, AV_LOG_ERROR,
+               "Error occurred when getting fragment buffer.\n");
+        return err;
+    }
+
+    return 0;
+}
+
+RTPDynamicProtocolHandler ff_mpeg_audio_robust_dynamic_handler = {
+    .enc_name          = "mpa-robust",
+    .codec_type        = AVMEDIA_TYPE_AUDIO,
+    .codec_id          = AV_CODEC_ID_MP3ADU,
+    .need_parsing      = AVSTREAM_PARSE_HEADERS,
+    .priv_data_size    = sizeof(PayloadContext),
+    .close             = mpa_robust_close_context,
+    .parse_packet      = mpa_robust_parse_packet,
+};
diff --git a/libavformat/rtpdec_mpeg12.c b/libavformat/rtpdec_mpeg12.c
index d73ff1e..e6185ea 100644
--- a/libavformat/rtpdec_mpeg12.c
+++ b/libavformat/rtpdec_mpeg12.c
@@ -23,14 +23,6 @@
 #include "libavutil/intreadwrite.h"
 #include "rtpdec_formats.h"
 
-static av_cold int mpeg_init(AVFormatContext *ctx, int st_index, PayloadContext *data)
-{
-    if (st_index < 0)
-        return 0;
-    ctx->streams[st_index]->need_parsing = AVSTREAM_PARSE_FULL;
-    return 0;
-}
-
 static int mpeg_parse_packet(AVFormatContext *ctx, PayloadContext *data,
                              AVStream *st, AVPacket *pkt, uint32_t *timestamp,
                              const uint8_t *buf, int len, uint16_t seq,
@@ -59,7 +51,7 @@
 RTPDynamicProtocolHandler ff_mpeg_audio_dynamic_handler = {
     .codec_type        = AVMEDIA_TYPE_AUDIO,
     .codec_id          = AV_CODEC_ID_MP3,
-    .init              = mpeg_init,
+    .need_parsing      = AVSTREAM_PARSE_FULL,
     .parse_packet      = mpeg_parse_packet,
     .static_payload_id = 14,
 };
@@ -67,7 +59,7 @@
 RTPDynamicProtocolHandler ff_mpeg_video_dynamic_handler = {
     .codec_type        = AVMEDIA_TYPE_VIDEO,
     .codec_id          = AV_CODEC_ID_MPEG2VIDEO,
-    .init              = mpeg_init,
+    .need_parsing      = AVSTREAM_PARSE_FULL,
     .parse_packet      = mpeg_parse_packet,
     .static_payload_id = 32,
 };
diff --git a/libavformat/rtpdec_mpeg4.c b/libavformat/rtpdec_mpeg4.c
index 9655d30..70e51f8 100644
--- a/libavformat/rtpdec_mpeg4.c
+++ b/libavformat/rtpdec_mpeg4.c
@@ -33,6 +33,8 @@
 #include "libavutil/avstring.h"
 #include "libavcodec/get_bits.h"
 
+#define MAX_AAC_HBR_FRAME_SIZE 8191
+
 /** Structure listing useful vars to parse RTP packet payload */
 struct PayloadContext {
     int sizelength;
@@ -59,11 +61,12 @@
     int au_headers_length_bytes;
     int cur_au_index;
 
-    uint8_t buf[RTP_MAX_PACKET_LENGTH];
+    uint8_t buf[FFMAX(RTP_MAX_PACKET_LENGTH, MAX_AAC_HBR_FRAME_SIZE)];
     int buf_pos, buf_size;
+    uint32_t timestamp;
 };
 
-typedef struct {
+typedef struct AttrNameMap {
     const char *str;
     uint16_t    type;
     uint32_t    offset;
@@ -88,19 +91,13 @@
     { NULL, -1, -1 },
 };
 
-static PayloadContext *new_context(void)
-{
-    return av_mallocz(sizeof(PayloadContext));
-}
-
-static void free_context(PayloadContext *data)
+static void close_context(PayloadContext *data)
 {
     av_freep(&data->au_headers);
     av_freep(&data->mode);
-    av_freep(&data);
 }
 
-static int parse_fmtp_config(AVCodecContext *codec, char *value)
+static int parse_fmtp_config(AVCodecContext *codec, const char *value)
 {
     /* decode the hexa encoded parameter */
     int len = ff_hex_to_data(NULL, value);
@@ -168,30 +165,95 @@
 {
     int ret;
 
+
     if (!buf) {
-        if (data->cur_au_index > data->nb_au_headers)
+        if (data->cur_au_index > data->nb_au_headers) {
+            av_log(ctx, AV_LOG_ERROR, "Invalid parser state\n");
             return AVERROR_INVALIDDATA;
-        if (data->buf_size - data->buf_pos < data->au_headers[data->cur_au_index].size)
+        }
+        if (data->buf_size - data->buf_pos < data->au_headers[data->cur_au_index].size) {
+            av_log(ctx, AV_LOG_ERROR, "Invalid AU size\n");
             return AVERROR_INVALIDDATA;
-        if ((ret = av_new_packet(pkt, data->au_headers[data->cur_au_index].size)) < 0)
+        }
+        if ((ret = av_new_packet(pkt, data->au_headers[data->cur_au_index].size)) < 0) {
+            av_log(ctx, AV_LOG_ERROR, "Out of memory\n");
             return ret;
+        }
         memcpy(pkt->data, &data->buf[data->buf_pos], data->au_headers[data->cur_au_index].size);
         data->buf_pos += data->au_headers[data->cur_au_index].size;
         pkt->stream_index = st->index;
         data->cur_au_index++;
-        return data->cur_au_index < data->nb_au_headers;
+
+        if (data->cur_au_index == data->nb_au_headers) {
+            data->buf_pos = 0;
+            return 0;
+        }
+
+        return 1;
     }
 
-    if (rtp_parse_mp4_au(data, buf, len))
+    if (rtp_parse_mp4_au(data, buf, len)) {
+        av_log(ctx, AV_LOG_ERROR, "Error parsing AU headers\n");
         return -1;
+    }
 
     buf += data->au_headers_length_bytes + 2;
     len -= data->au_headers_length_bytes + 2;
+    if (data->nb_au_headers == 1 && len < data->au_headers[0].size) {
+        /* Packet is fragmented */
 
-    if (len < data->au_headers[0].size)
+        if (!data->buf_pos) {
+            if (data->au_headers[0].size > MAX_AAC_HBR_FRAME_SIZE) {
+                av_log(ctx, AV_LOG_ERROR, "Invalid AU size\n");
+                return AVERROR_INVALIDDATA;
+            }
+
+            data->buf_size = data->au_headers[0].size;
+            data->timestamp = *timestamp;
+        }
+
+        if (data->timestamp != *timestamp ||
+            data->au_headers[0].size != data->buf_size ||
+            data->buf_pos + len > MAX_AAC_HBR_FRAME_SIZE) {
+            data->buf_pos = 0;
+            data->buf_size = 0;
+            av_log(ctx, AV_LOG_ERROR, "Invalid packet received\n");
+            return AVERROR_INVALIDDATA;
+        }
+
+        memcpy(&data->buf[data->buf_pos], buf, len);
+        data->buf_pos += len;
+
+        if (!(flags & RTP_FLAG_MARKER))
+            return AVERROR(EAGAIN);
+
+        if (data->buf_pos != data->buf_size) {
+            data->buf_pos = 0;
+            av_log(ctx, AV_LOG_ERROR, "Missed some packets, discarding frame\n");
+            return AVERROR_INVALIDDATA;
+        }
+
+        data->buf_pos = 0;
+        ret = av_new_packet(pkt, data->buf_size);
+        if (ret < 0) {
+            av_log(ctx, AV_LOG_ERROR, "Out of memory\n");
+            return ret;
+        }
+        pkt->stream_index = st->index;
+
+        memcpy(pkt->data, data->buf, data->buf_size);
+
+        return 0;
+    }
+
+    if (len < data->au_headers[0].size) {
+        av_log(ctx, AV_LOG_ERROR, "First AU larger than packet size\n");
         return AVERROR_INVALIDDATA;
-    if ((ret = av_new_packet(pkt, data->au_headers[0].size)) < 0)
+    }
+    if ((ret = av_new_packet(pkt, data->au_headers[0].size)) < 0) {
+        av_log(ctx, AV_LOG_ERROR, "Out of memory\n");
         return ret;
+    }
     memcpy(pkt->data, buf, data->au_headers[0].size);
     len -= data->au_headers[0].size;
     buf += data->au_headers[0].size;
@@ -210,7 +272,7 @@
 
 static int parse_fmtp(AVFormatContext *s,
                       AVStream *stream, PayloadContext *data,
-                      char *attr, char *value)
+                      const char *attr, const char *value)
 {
     AVCodecContext *codec = stream->codec;
     int res, i;
@@ -252,20 +314,12 @@
     return 0;
 }
 
-static av_cold int init_video(AVFormatContext *s, int st_index,
-                              PayloadContext *data)
-{
-    if (st_index < 0)
-        return 0;
-    s->streams[st_index]->need_parsing = AVSTREAM_PARSE_FULL;
-    return 0;
-}
-
 RTPDynamicProtocolHandler ff_mp4v_es_dynamic_handler = {
     .enc_name           = "MP4V-ES",
     .codec_type         = AVMEDIA_TYPE_VIDEO,
     .codec_id           = AV_CODEC_ID_MPEG4,
-    .init               = init_video,
+    .need_parsing       = AVSTREAM_PARSE_FULL,
+    .priv_data_size     = sizeof(PayloadContext),
     .parse_sdp_a_line   = parse_sdp_line,
 };
 
@@ -273,8 +327,8 @@
     .enc_name           = "mpeg4-generic",
     .codec_type         = AVMEDIA_TYPE_AUDIO,
     .codec_id           = AV_CODEC_ID_AAC,
+    .priv_data_size     = sizeof(PayloadContext),
     .parse_sdp_a_line   = parse_sdp_line,
-    .alloc              = new_context,
-    .free               = free_context,
-    .parse_packet       = aac_parse_packet
+    .close              = close_context,
+    .parse_packet       = aac_parse_packet,
 };
diff --git a/libavformat/rtpdec_mpegts.c b/libavformat/rtpdec_mpegts.c
index 0c2b717..5bf0f18 100644
--- a/libavformat/rtpdec_mpegts.c
+++ b/libavformat/rtpdec_mpegts.c
@@ -30,18 +30,12 @@
     uint8_t buf[RTP_MAX_PACKET_LENGTH];
 };
 
-static PayloadContext *mpegts_new_context(void)
-{
-    return av_mallocz(sizeof(PayloadContext));
-}
-
-static void mpegts_free_context(PayloadContext *data)
+static void mpegts_close_context(PayloadContext *data)
 {
     if (!data)
         return;
     if (data->ts)
         avpriv_mpegts_parse_close(data->ts);
-    av_free(data);
 }
 
 static av_cold int mpegts_init(AVFormatContext *ctx, int st_index,
@@ -66,9 +60,6 @@
     // different ranges.
     *timestamp = RTP_NOTS_VALUE;
 
-    if (!data->ts)
-        return AVERROR(EINVAL);
-
     if (!buf) {
         if (data->read_buf_index >= data->read_buf_size)
             return AVERROR(EAGAIN);
@@ -100,9 +91,9 @@
 
 RTPDynamicProtocolHandler ff_mpegts_dynamic_handler = {
     .codec_type        = AVMEDIA_TYPE_DATA,
+    .priv_data_size    = sizeof(PayloadContext),
     .parse_packet      = mpegts_handle_packet,
-    .alloc             = mpegts_new_context,
     .init              = mpegts_init,
-    .free              = mpegts_free_context,
+    .close             = mpegts_close_context,
     .static_payload_id = 33,
 };
diff --git a/libavformat/rtpdec_qcelp.c b/libavformat/rtpdec_qcelp.c
index eebcdd0..41cc826 100644
--- a/libavformat/rtpdec_qcelp.c
+++ b/libavformat/rtpdec_qcelp.c
@@ -25,7 +25,7 @@
     1, 4, 8, 17, 35
 };
 
-typedef struct {
+typedef struct InterleavePacket {
     int pos;
     int size;
     /* The largest frame is 35 bytes, only 10 frames are allowed per
@@ -47,16 +47,6 @@
     uint32_t next_timestamp;
 };
 
-static PayloadContext *qcelp_new_context(void)
-{
-    return av_mallocz(sizeof(PayloadContext));
-}
-
-static void qcelp_free_context(PayloadContext *data)
-{
-    av_free(data);
-}
-
 static int return_stored_frame(AVFormatContext *ctx, PayloadContext *data,
                                AVStream *st, AVPacket *pkt, uint32_t *timestamp,
                                const uint8_t *buf, int len);
@@ -223,8 +213,7 @@
     .enc_name           = "x-Purevoice",
     .codec_type         = AVMEDIA_TYPE_AUDIO,
     .codec_id           = AV_CODEC_ID_QCELP,
+    .priv_data_size     = sizeof(PayloadContext),
     .static_payload_id  = 12,
-    .alloc              = qcelp_new_context,
-    .free               = qcelp_free_context,
-    .parse_packet       = qcelp_parse_packet
+    .parse_packet       = qcelp_parse_packet,
 };
diff --git a/libavformat/rtpdec_qdm2.c b/libavformat/rtpdec_qdm2.c
index e1dd62f..22b419e 100644
--- a/libavformat/rtpdec_qdm2.c
+++ b/libavformat/rtpdec_qdm2.c
@@ -189,7 +189,7 @@
     uint8_t *p, *csum_pos = NULL;
 
     /* create packet to hold subpkts into a superblock */
-    assert(qdm->cache > 0);
+    av_assert0(qdm->cache > 0);
     for (n = 0; n < 0x80; n++)
         if (qdm->len[n] > 0)
             break;
@@ -298,21 +298,10 @@
     return (qdm->cache > 0) ? 1 : 0;
 }
 
-static PayloadContext *qdm2_extradata_new(void)
-{
-    return av_mallocz(sizeof(PayloadContext));
-}
-
-static void qdm2_extradata_free(PayloadContext *qdm)
-{
-    av_free(qdm);
-}
-
 RTPDynamicProtocolHandler ff_qdm2_dynamic_handler = {
     .enc_name         = "X-QDM",
     .codec_type       = AVMEDIA_TYPE_AUDIO,
     .codec_id         = AV_CODEC_ID_NONE,
-    .alloc            = qdm2_extradata_new,
-    .free             = qdm2_extradata_free,
+    .priv_data_size   = sizeof(PayloadContext),
     .parse_packet     = qdm2_parse_packet,
 };
diff --git a/libavformat/rtpdec_qt.c b/libavformat/rtpdec_qt.c
index 58253b6..ba701dc 100644
--- a/libavformat/rtpdec_qt.c
+++ b/libavformat/rtpdec_qt.c
@@ -47,7 +47,8 @@
     AVIOContext pb;
     GetBitContext gb;
     int packing_scheme, has_payload_desc, has_packet_info, alen,
-        has_marker_bit = flags & RTP_FLAG_MARKER;
+        has_marker_bit = flags & RTP_FLAG_MARKER,
+        keyframe;
 
     if (qt->remaining) {
         int num = qt->pkt.size / qt->bytes_per_frame;
@@ -79,8 +80,7 @@
     skip_bits(&gb, 4); // version
     if ((packing_scheme = get_bits(&gb, 2)) == 0)
         return AVERROR_INVALIDDATA;
-    if (get_bits1(&gb))
-        flags          |= RTP_FLAG_KEY;
+    keyframe            = get_bits1(&gb);
     has_payload_desc    = get_bits1(&gb);
     has_packet_info     = get_bits1(&gb);
     skip_bits(&gb, 23); // reserved:7, cache payload info:1, payload ID:15
@@ -196,7 +196,7 @@
 
             qt->pkt.size = 0;
             qt->pkt.data = NULL;
-            pkt->flags        = flags & RTP_FLAG_KEY ? AV_PKT_FLAG_KEY : 0;
+            pkt->flags        = keyframe ? AV_PKT_FLAG_KEY : 0;
             pkt->stream_index = st->index;
             memset(pkt->data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
             return 0;
@@ -211,7 +211,7 @@
         if (av_new_packet(pkt, qt->bytes_per_frame))
             return AVERROR(ENOMEM);
         memcpy(pkt->data, buf + avio_tell(&pb), qt->bytes_per_frame);
-        pkt->flags = flags & RTP_FLAG_KEY ? AV_PKT_FLAG_KEY : 0;
+        pkt->flags = keyframe ? AV_PKT_FLAG_KEY : 0;
         pkt->stream_index = st->index;
         if (qt->remaining > 0) {
             av_freep(&qt->pkt.data);
@@ -235,15 +235,9 @@
     }
 }
 
-static PayloadContext *qt_rtp_new(void)
-{
-    return av_mallocz(sizeof(PayloadContext));
-}
-
-static void qt_rtp_free(PayloadContext *qt)
+static void qt_rtp_close(PayloadContext *qt)
 {
     av_freep(&qt->pkt.data);
-    av_free(qt);
 }
 
 #define RTP_QT_HANDLER(m, n, s, t) \
@@ -251,8 +245,8 @@
     .enc_name         = s, \
     .codec_type       = t, \
     .codec_id         = AV_CODEC_ID_NONE, \
-    .alloc            = qt_rtp_new,    \
-    .free             = qt_rtp_free,   \
+    .priv_data_size   = sizeof(PayloadContext), \
+    .close            = qt_rtp_close,   \
     .parse_packet     = qt_rtp_parse_packet, \
 }
 
diff --git a/libavformat/rtpdec_svq3.c b/libavformat/rtpdec_svq3.c
index 98e8b58..bad199f 100644
--- a/libavformat/rtpdec_svq3.c
+++ b/libavformat/rtpdec_svq3.c
@@ -28,6 +28,7 @@
 
 #include <string.h>
 #include "libavutil/intreadwrite.h"
+#include "avio_internal.h"
 #include "internal.h"
 #include "rtp.h"
 #include "rtpdec.h"
@@ -81,11 +82,7 @@
     if (start_packet) {
         int res;
 
-        if (sv->pktbuf) {
-            uint8_t *tmp;
-            avio_close_dyn_buf(sv->pktbuf, &tmp);
-            av_free(tmp);
-        }
+        ffio_free_dyn_buf(&sv->pktbuf);
         if ((res = avio_open_dyn_buf(&sv->pktbuf)) < 0)
             return res;
         sv->timestamp   = *timestamp;
@@ -108,26 +105,16 @@
     return AVERROR(EAGAIN);
 }
 
-static PayloadContext *svq3_extradata_new(void)
+static void svq3_close_context(PayloadContext *sv)
 {
-    return av_mallocz(sizeof(PayloadContext));
-}
-
-static void svq3_extradata_free(PayloadContext *sv)
-{
-    if (sv->pktbuf) {
-        uint8_t *buf;
-        avio_close_dyn_buf(sv->pktbuf, &buf);
-        av_free(buf);
-    }
-    av_free(sv);
+    ffio_free_dyn_buf(&sv->pktbuf);
 }
 
 RTPDynamicProtocolHandler ff_svq3_dynamic_handler = {
     .enc_name         = "X-SV3V-ES",
     .codec_type       = AVMEDIA_TYPE_VIDEO,
     .codec_id         = AV_CODEC_ID_NONE,      // see if (config_packet) above
-    .alloc            = svq3_extradata_new,
-    .free             = svq3_extradata_free,
+    .priv_data_size   = sizeof(PayloadContext),
+    .close            = svq3_close_context,
     .parse_packet     = svq3_parse_packet,
 };
diff --git a/libavformat/rtpdec_vp8.c b/libavformat/rtpdec_vp8.c
index b4b4f22..d1e355d 100644
--- a/libavformat/rtpdec_vp8.c
+++ b/libavformat/rtpdec_vp8.c
@@ -29,6 +29,7 @@
 
 #include "libavcodec/bytestream.h"
 
+#include "avio_internal.h"
 #include "rtpdec_formats.h"
 
 struct PayloadContext {
@@ -52,22 +53,12 @@
     int          got_keyframe;
 };
 
-static void vp8_free_buffer(PayloadContext *vp8)
-{
-    uint8_t *tmp;
-    if (!vp8->data)
-        return;
-    avio_close_dyn_buf(vp8->data, &tmp);
-    av_free(tmp);
-    vp8->data = NULL;
-}
-
 static int vp8_broken_sequence(AVFormatContext *ctx, PayloadContext *vp8,
                                const char *msg)
 {
     vp8->sequence_ok = 0;
     av_log(ctx, AV_LOG_WARNING, "%s", msg);
-    vp8_free_buffer(vp8);
+    ffio_free_dyn_buf(&vp8->data);
     return AVERROR(EAGAIN);
 }
 
@@ -150,7 +141,7 @@
         int res;
         int non_key = buf[0] & 0x01;
         if (!non_key) {
-            vp8_free_buffer(vp8);
+            ffio_free_dyn_buf(&vp8->data);
             // Keyframe, decoding ok again
             vp8->sequence_ok = 1;
             vp8->sequence_dirty = 0;
@@ -205,7 +196,7 @@
                     old_timestamp = vp8->timestamp;
                 } else {
                     // Shouldn't happen
-                    vp8_free_buffer(vp8);
+                    ffio_free_dyn_buf(&vp8->data);
                 }
             }
         }
@@ -261,25 +252,23 @@
             return ret;
         if (vp8->sequence_dirty)
             pkt->flags |= AV_PKT_FLAG_CORRUPT;
+        if (vp8->is_keyframe)
+            pkt->flags |= AV_PKT_FLAG_KEY;
         return 0;
     }
 
     return AVERROR(EAGAIN);
 }
 
-static PayloadContext *vp8_new_context(void)
+static av_cold int vp8_init(AVFormatContext *s, int st_index, PayloadContext *vp8)
 {
-    PayloadContext *vp8 = av_mallocz(sizeof(PayloadContext));
-    if (!vp8)
-        return NULL;
     vp8->sequence_ok = 1;
-    return vp8;
+    return 0;
 }
 
-static void vp8_free_context(PayloadContext *vp8)
+static void vp8_close_context(PayloadContext *vp8)
 {
-    vp8_free_buffer(vp8);
-    av_free(vp8);
+    ffio_free_dyn_buf(&vp8->data);
 }
 
 static int vp8_need_keyframe(PayloadContext *vp8)
@@ -291,8 +280,9 @@
     .enc_name       = "VP8",
     .codec_type     = AVMEDIA_TYPE_VIDEO,
     .codec_id       = AV_CODEC_ID_VP8,
-    .alloc          = vp8_new_context,
-    .free           = vp8_free_context,
+    .priv_data_size = sizeof(PayloadContext),
+    .init           = vp8_init,
+    .close          = vp8_close_context,
     .parse_packet   = vp8_handle_packet,
     .need_keyframe  = vp8_need_keyframe,
 };
diff --git a/libavformat/rtpdec_vp9.c b/libavformat/rtpdec_vp9.c
new file mode 100644
index 0000000..e50bede
--- /dev/null
+++ b/libavformat/rtpdec_vp9.c
@@ -0,0 +1,289 @@
+/*
+ * RTP parser for VP9 payload format (draft version 0) - experimental
+ * Copyright (c) 2015 Thomas Volkert <thomas@homer-conferencing.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/intreadwrite.h"
+
+#include "avio_internal.h"
+#include "rtpdec_formats.h"
+
+#define RTP_VP9_DESC_REQUIRED_SIZE 1
+
+struct PayloadContext {
+    AVIOContext *buf;
+    uint32_t     timestamp;
+};
+
+static av_cold int vp9_init(AVFormatContext *ctx, int st_index,
+                            PayloadContext *data)
+{
+    av_log(ctx, AV_LOG_WARNING,
+           "RTP/VP9 support is still experimental\n");
+
+    return 0;
+}
+
+static int vp9_handle_packet(AVFormatContext *ctx, PayloadContext *rtp_vp9_ctx,
+                             AVStream *st, AVPacket *pkt, uint32_t *timestamp,
+                             const uint8_t *buf, int len, uint16_t seq,
+                             int flags)
+{
+    int has_pic_id, has_layer_idc, has_ref_idc, has_ss_data, has_su_data;
+    av_unused int pic_id = 0, non_key_frame = 0;
+    av_unused int layer_temporal = -1, layer_spatial = -1, layer_quality = -1;
+    int ref_fields = 0, has_ref_field_ext_pic_id = 0;
+    int first_fragment, last_fragment;
+    int rtp_m;
+    int res = 0;
+
+    /* drop data of previous packets in case of non-continuous (lossy) packet stream */
+    if (rtp_vp9_ctx->buf && rtp_vp9_ctx->timestamp != *timestamp)
+        ffio_free_dyn_buf(&rtp_vp9_ctx->buf);
+
+    /* sanity check for size of input packet: 1 byte payload at least */
+    if (len < RTP_VP9_DESC_REQUIRED_SIZE + 1) {
+        av_log(ctx, AV_LOG_ERROR, "Too short RTP/VP9 packet, got %d bytes\n", len);
+        return AVERROR_INVALIDDATA;
+    }
+
+    /*
+     *     decode the required VP9 payload descriptor according to section 4.2 of the spec.:
+     *
+     *      0 1 2 3 4 5 6 7
+     *     +-+-+-+-+-+-+-+-+
+     *     |I|L|F|B|E|V|U|-| (REQUIRED)
+     *     +-+-+-+-+-+-+-+-+
+     *
+     *     I: PictureID present
+     *     L: Layer indices present
+     *     F: Reference indices present
+     *     B: Start of VP9 frame
+     *     E: End of picture
+     *     V: Scalability Structure (SS) present
+     *     U: Scalability Structure Update (SU) present
+     */
+    has_pic_id     = !!(buf[0] & 0x80);
+    has_layer_idc  = !!(buf[0] & 0x40);
+    has_ref_idc    = !!(buf[0] & 0x20);
+    first_fragment = !!(buf[0] & 0x10);
+    last_fragment  = !!(buf[0] & 0x08);
+    has_ss_data    = !!(buf[0] & 0x04);
+    has_su_data    = !!(buf[0] & 0x02);
+
+    rtp_m = !!(flags & RTP_FLAG_MARKER);
+
+    /* sanity check for markers: B should always be equal to the RTP M marker */
+    if (last_fragment != rtp_m) {
+        av_log(ctx, AV_LOG_ERROR, "Invalid combination of B and M marker (%d != %d)\n", last_fragment, rtp_m);
+        return AVERROR_INVALIDDATA;
+    }
+
+    /* pass the extensions field */
+    buf += RTP_VP9_DESC_REQUIRED_SIZE;
+    len -= RTP_VP9_DESC_REQUIRED_SIZE;
+
+    /*
+     *         decode the 1-byte/2-byte picture ID:
+     *
+     *          0 1 2 3 4 5 6 7
+     *         +-+-+-+-+-+-+-+-+
+     *   I:    |M|PICTURE ID   | (RECOMMENDED)
+     *         +-+-+-+-+-+-+-+-+
+     *   M:    | EXTENDED PID  | (RECOMMENDED)
+     *         +-+-+-+-+-+-+-+-+
+     *
+     *   M: The most significant bit of the first octet is an extension flag.
+     *   PictureID:  8 or 16 bits including the M bit.
+     */
+    if (has_pic_id) {
+        /* check for 1-byte or 2-byte picture index */
+        if (buf[0] & 0x80) {
+            if (len < 2) {
+                av_log(ctx, AV_LOG_ERROR, "Too short RTP/VP9 packet\n");
+                return AVERROR_INVALIDDATA;
+            }
+            pic_id = AV_RB16(buf) & 0x7fff;
+            buf += 2;
+            len -= 2;
+        } else {
+            pic_id = buf[0] & 0x7f;
+            buf++;
+            len--;
+        }
+    }
+
+    /*
+     *         decode layer indices
+     *
+     *          0 1 2 3 4 5 6 7
+     *         +-+-+-+-+-+-+-+-+
+     *   L:    | T | S | Q | R | (CONDITIONALLY RECOMMENDED)
+     *         +-+-+-+-+-+-+-+-+
+     *
+     *   T, S and Q are 2-bit indices for temporal, spatial, and quality layers.
+     *   If "F" is set in the initial octet, R is 2 bits representing the number
+     *   of reference fields this frame refers to.
+     */
+    if (has_layer_idc) {
+        if (len < 1) {
+            av_log(ctx, AV_LOG_ERROR, "Too short RTP/VP9 packet\n");
+            return AVERROR_INVALIDDATA;
+        }
+        layer_temporal = buf[0] & 0xC0;
+        layer_spatial  = buf[0] & 0x30;
+        layer_quality  = buf[0] & 0x0C;
+        if (has_ref_idc) {
+            ref_fields = buf[0] & 0x03;
+            if (ref_fields)
+                non_key_frame = 1;
+        }
+        buf++;
+        len--;
+    }
+
+    /*
+     *         decode the reference fields
+     *
+     *          0 1 2 3 4 5 6 7
+     *         +-+-+-+-+-+-+-+-+              -\
+     *   F:    | PID |X| RS| RQ| (OPTIONAL)    .
+     *         +-+-+-+-+-+-+-+-+               . - R times
+     *   X:    | EXTENDED PID  | (OPTIONAL)    .
+     *         +-+-+-+-+-+-+-+-+              -/
+     *
+     *   PID:  The relative Picture ID referred to by this frame.
+     *   RS and RQ:  The spatial and quality layer IDs.
+     *   X: 1 if this layer index has an extended relative Picture ID.
+     */
+    if (has_ref_idc) {
+        while (ref_fields) {
+            if (len < 1) {
+                av_log(ctx, AV_LOG_ERROR, "Too short RTP/VP9 packet\n");
+                return AVERROR_INVALIDDATA;
+            }
+
+            has_ref_field_ext_pic_id = buf[0] & 0x10;
+
+            /* pass ref. field */
+            if (has_ref_field_ext_pic_id) {
+                if (len < 2) {
+                    av_log(ctx, AV_LOG_ERROR, "Too short RTP/VP9 packet\n");
+                    return AVERROR_INVALIDDATA;
+                }
+
+                /* ignore ref. data */
+
+                buf += 2;
+                len -= 2;
+            } else {
+
+                /* ignore ref. data */
+
+                buf++;
+                len--;
+            }
+            ref_fields--;
+        }
+    }
+
+    /*
+     *         decode the scalability structure (SS)
+     *
+     *          0 1 2 3 4 5 6 7
+     *         +-+-+-+-+-+-+-+-+
+     *   V:    | PATTERN LENGTH|
+     *         +-+-+-+-+-+-+-+-+                           -\
+     *         | T | S | Q | R | (OPTIONAL)                 .
+     *         +-+-+-+-+-+-+-+-+              -\            .
+     *         | PID |X| RS| RQ| (OPTIONAL)    .            . - PAT. LEN. times
+     *         +-+-+-+-+-+-+-+-+               . - R times  .
+     *   X:    | EXTENDED PID  | (OPTIONAL)    .            .
+     *         +-+-+-+-+-+-+-+-+              -/           -/
+     *
+     *   PID:  The relative Picture ID referred to by this frame.
+     *   RS and RQ:  The spatial and quality layer IDs.
+     *   X: 1 if this layer index has an extended relative Picture ID.
+     */
+    if (has_ss_data) {
+        avpriv_report_missing_feature(ctx, "VP9 scalability structure data");
+        return AVERROR(ENOSYS);
+    }
+
+    /*
+     * decode the scalability update structure (SU)
+     *
+     *  spec. is tbd
+     */
+    if (has_su_data) {
+        avpriv_report_missing_feature(ctx, "VP9 scalability update structure data");
+        return AVERROR(ENOSYS);
+    }
+
+    /*
+     * decode the VP9 payload header
+     *
+     *  spec. is tbd
+     */
+    //XXX: implement when specified
+
+    /* sanity check: 1 byte payload as minimum */
+    if (len < 1) {
+        av_log(ctx, AV_LOG_ERROR, "Too short RTP/VP9 packet\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    /* start frame buffering with new dynamic buffer */
+    if (!rtp_vp9_ctx->buf) {
+        /* sanity check: a new frame should have started */
+        if (first_fragment) {
+            res = avio_open_dyn_buf(&rtp_vp9_ctx->buf);
+            if (res < 0)
+                return res;
+            /* update the timestamp in the frame packet with the one from the RTP packet */
+            rtp_vp9_ctx->timestamp = *timestamp;
+        } else {
+            /* frame not started yet, need more packets */
+            return AVERROR(EAGAIN);
+        }
+    }
+
+    /* write the fragment to the dyn. buffer */
+    avio_write(rtp_vp9_ctx->buf, buf, len);
+
+    /* do we need more fragments? */
+    if (!last_fragment)
+        return AVERROR(EAGAIN);
+
+    /* close frame buffering and create resulting A/V packet */
+    res = ff_rtp_finalize_packet(pkt, &rtp_vp9_ctx->buf, st->index);
+    if (res < 0)
+        return res;
+
+    return 0;
+}
+
+RTPDynamicProtocolHandler ff_vp9_dynamic_handler = {
+    .enc_name         = "VP9",
+    .codec_type       = AVMEDIA_TYPE_VIDEO,
+    .codec_id         = AV_CODEC_ID_VP9,
+    .priv_data_size   = sizeof(PayloadContext),
+    .init             = vp9_init,
+    .parse_packet     = vp9_handle_packet
+};
diff --git a/libavformat/rtpdec_xiph.c b/libavformat/rtpdec_xiph.c
index 53b4975..a09653f 100644
--- a/libavformat/rtpdec_xiph.c
+++ b/libavformat/rtpdec_xiph.c
@@ -33,6 +33,7 @@
 #include "libavutil/base64.h"
 #include "libavcodec/bytestream.h"
 
+#include "avio_internal.h"
 #include "internal.h"
 #include "rtpdec.h"
 #include "rtpdec_formats.h"
@@ -49,35 +50,10 @@
     int split_pkts;
 };
 
-static PayloadContext *xiph_new_context(void)
+static void xiph_close_context(PayloadContext * data)
 {
-    return av_mallocz(sizeof(PayloadContext));
-}
-
-static inline void free_fragment_if_needed(PayloadContext * data)
-{
-    if (data->fragment) {
-        uint8_t* p;
-        avio_close_dyn_buf(data->fragment, &p);
-        av_free(p);
-        data->fragment = NULL;
-    }
-}
-
-static void xiph_free_context(PayloadContext * data)
-{
-    free_fragment_if_needed(data);
+    ffio_free_dyn_buf(&data->fragment);
     av_freep(&data->split_buf);
-    av_freep(&data);
-}
-
-static av_cold int xiph_vorbis_init(AVFormatContext *ctx, int st_index,
-                                    PayloadContext *data)
-{
-    if (st_index < 0)
-        return 0;
-    ctx->streams[st_index]->need_parsing = AVSTREAM_PARSE_HEADERS;
-    return 0;
 }
 
 
@@ -183,7 +159,7 @@
         int res;
 
         // end packet has been lost somewhere, so drop buffered data
-        free_fragment_if_needed(data);
+        ffio_free_dyn_buf(&data->fragment);
 
         if((res = avio_open_dyn_buf(&data->fragment)) < 0)
             return res;
@@ -196,7 +172,7 @@
         if (data->timestamp != *timestamp) {
             // skip if fragmented timestamp is incorrect;
             // a start packet has been lost somewhere
-            free_fragment_if_needed(data);
+            ffio_free_dyn_buf(&data->fragment);
             av_log(ctx, AV_LOG_ERROR, "RTP timestamps don't match!\n");
             return AVERROR_INVALIDDATA;
         }
@@ -309,7 +285,7 @@
 static int xiph_parse_fmtp_pair(AVFormatContext *s,
                                 AVStream* stream,
                                 PayloadContext *xiph_data,
-                                char *attr, char *value)
+                                const char *attr, const char *value)
 {
     AVCodecContext *codec = stream->codec;
     int result = 0;
@@ -394,19 +370,19 @@
     .enc_name         = "theora",
     .codec_type       = AVMEDIA_TYPE_VIDEO,
     .codec_id         = AV_CODEC_ID_THEORA,
+    .priv_data_size   = sizeof(PayloadContext),
     .parse_sdp_a_line = xiph_parse_sdp_line,
-    .alloc            = xiph_new_context,
-    .free             = xiph_free_context,
-    .parse_packet     = xiph_handle_packet
+    .close            = xiph_close_context,
+    .parse_packet     = xiph_handle_packet,
 };
 
 RTPDynamicProtocolHandler ff_vorbis_dynamic_handler = {
     .enc_name         = "vorbis",
     .codec_type       = AVMEDIA_TYPE_AUDIO,
     .codec_id         = AV_CODEC_ID_VORBIS,
-    .init             = xiph_vorbis_init,
+    .need_parsing     = AVSTREAM_PARSE_HEADERS,
+    .priv_data_size   = sizeof(PayloadContext),
     .parse_sdp_a_line = xiph_parse_sdp_line,
-    .alloc            = xiph_new_context,
-    .free             = xiph_free_context,
-    .parse_packet     = xiph_handle_packet
+    .close            = xiph_close_context,
+    .parse_packet     = xiph_handle_packet,
 };
diff --git a/libavformat/rtpenc.c b/libavformat/rtpenc.c
index c4c4d3e..1eb0191 100644
--- a/libavformat/rtpenc.c
+++ b/libavformat/rtpenc.c
@@ -152,38 +152,17 @@
     }
     s->max_payload_size = s1->packet_size - 12;
 
-    s->max_frames_per_packet = 0;
-    if (s1->max_delay > 0) {
-        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
-            int frame_size = av_get_audio_frame_duration(st->codec, 0);
-            if (!frame_size)
-                frame_size = st->codec->frame_size;
-            if (frame_size == 0) {
-                av_log(s1, AV_LOG_ERROR, "Cannot respect max delay: frame size = 0\n");
-            } else {
-                s->max_frames_per_packet =
-                        av_rescale_q_rnd(s1->max_delay,
-                                         AV_TIME_BASE_Q,
-                                         (AVRational){ frame_size, st->codec->sample_rate },
-                                         AV_ROUND_DOWN);
-            }
-        }
-        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
-            /* FIXME: We should round down here... */
-            if (st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0) {
-                s->max_frames_per_packet = av_rescale_q(s1->max_delay,
-                                                        (AVRational){1, 1000000},
-                                                        av_inv_q(st->avg_frame_rate));
-            } else
-                s->max_frames_per_packet = 1;
-        }
+    if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
+        avpriv_set_pts_info(st, 32, 1, st->codec->sample_rate);
+    } else {
+        avpriv_set_pts_info(st, 32, 1, 90000);
     }
-
-    avpriv_set_pts_info(st, 32, 1, 90000);
+    s->buf_ptr = s->buf;
     switch(st->codec->codec_id) {
     case AV_CODEC_ID_MP2:
     case AV_CODEC_ID_MP3:
         s->buf_ptr = s->buf + 4;
+        avpriv_set_pts_info(st, 32, 1, 90000);
         break;
     case AV_CODEC_ID_MPEG1VIDEO:
     case AV_CODEC_ID_MPEG2VIDEO:
@@ -193,7 +172,6 @@
         if (n < 1)
             n = 1;
         s->max_payload_size = n * TS_PACKET_SIZE;
-        s->buf_ptr = s->buf;
         break;
     case AV_CODEC_ID_H261:
         if (s1->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
@@ -223,11 +201,8 @@
         break;
     case AV_CODEC_ID_VORBIS:
     case AV_CODEC_ID_THEORA:
-        if (!s->max_frames_per_packet) s->max_frames_per_packet = 15;
-        s->max_frames_per_packet = av_clip(s->max_frames_per_packet, 1, 15);
-        s->max_payload_size -= 6; // ident+frag+tdt/vdt+pkt_num+pkt_length
-        s->num_frames = 0;
-        goto defaultcase;
+        s->max_frames_per_packet = 15;
+        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. */
@@ -248,15 +223,11 @@
             av_log(s1, AV_LOG_ERROR, "Incorrect iLBC block size specified\n");
             goto fail;
         }
-        if (!s->max_frames_per_packet)
-            s->max_frames_per_packet = 1;
-        s->max_frames_per_packet = FFMIN(s->max_frames_per_packet,
-                                         s->max_payload_size / st->codec->block_align);
-        goto defaultcase;
+        s->max_frames_per_packet = s->max_payload_size / st->codec->block_align;
+        break;
     case AV_CODEC_ID_AMR_NB:
     case AV_CODEC_ID_AMR_WB:
-        if (!s->max_frames_per_packet)
-            s->max_frames_per_packet = 12;
+        s->max_frames_per_packet = 50;
         if (st->codec->codec_id == AV_CODEC_ID_AMR_NB)
             n = 31;
         else
@@ -270,17 +241,11 @@
             av_log(s1, AV_LOG_ERROR, "Only mono is supported\n");
             goto fail;
         }
-        s->num_frames = 0;
-        goto defaultcase;
+        break;
     case AV_CODEC_ID_AAC:
-        s->num_frames = 0;
-        goto defaultcase;
+        s->max_frames_per_packet = 50;
+        break;
     default:
-defaultcase:
-        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
-            avpriv_set_pts_info(st, 32, 1, st->codec->sample_rate);
-        }
-        s->buf_ptr = s->buf;
         break;
     }
 
@@ -497,18 +462,23 @@
     int frames = size / frame_size;
 
     while (frames > 0) {
-        int n = FFMIN(s->max_frames_per_packet - s->num_frames, frames);
+        if (s->num_frames > 0 &&
+            av_compare_ts(s->cur_timestamp - s->timestamp, st->time_base,
+                          s1->max_delay, AV_TIME_BASE_Q) >= 0) {
+            ff_rtp_send_data(s1, s->buf, s->buf_ptr - s->buf, 1);
+            s->num_frames = 0;
+        }
 
         if (!s->num_frames) {
             s->buf_ptr = s->buf;
             s->timestamp = s->cur_timestamp;
         }
-        memcpy(s->buf_ptr, buf, n * frame_size);
-        frames           -= n;
-        s->num_frames    += n;
-        s->buf_ptr       += n * frame_size;
-        buf              += n * frame_size;
-        s->cur_timestamp += n * frame_duration;
+        memcpy(s->buf_ptr, buf, frame_size);
+        frames--;
+        s->num_frames++;
+        s->buf_ptr       += frame_size;
+        buf              += frame_size;
+        s->cur_timestamp += frame_duration;
 
         if (s->num_frames == s->max_frames_per_packet) {
             ff_rtp_send_data(s1, s->buf, s->buf_ptr - s->buf, 1);
@@ -580,7 +550,7 @@
         rtp_send_mpegts_raw(s1, pkt->data, size);
         break;
     case AV_CODEC_ID_H264:
-        ff_rtp_send_h264(s1, pkt->data, size);
+        ff_rtp_send_h264_hevc(s1, pkt->data, size);
         break;
     case AV_CODEC_ID_H261:
         ff_rtp_send_h261(s1, pkt->data, size);
@@ -603,7 +573,7 @@
         ff_rtp_send_h263(s1, pkt->data, size);
         break;
     case AV_CODEC_ID_HEVC:
-        ff_rtp_send_hevc(s1, pkt->data, size);
+        ff_rtp_send_h264_hevc(s1, pkt->data, size);
         break;
     case AV_CODEC_ID_VORBIS:
     case AV_CODEC_ID_THEORA:
diff --git a/libavformat/rtpenc.h b/libavformat/rtpenc.h
index 4eb98d8..d34153f 100644
--- a/libavformat/rtpenc.h
+++ b/libavformat/rtpenc.h
@@ -56,6 +56,7 @@
      * (1, 2 or 4)
      */
     int nal_length_size;
+    int buffered_nals;
 
     int flags;
 
@@ -80,12 +81,11 @@
 
 void ff_rtp_send_data(AVFormatContext *s1, const uint8_t *buf1, int len, int m);
 
-void ff_rtp_send_h264(AVFormatContext *s1, const uint8_t *buf1, int size);
+void ff_rtp_send_h264_hevc(AVFormatContext *s1, const uint8_t *buf1, int size);
 void ff_rtp_send_h261(AVFormatContext *s1, const uint8_t *buf1, int size);
 void ff_rtp_send_h263(AVFormatContext *s1, const uint8_t *buf1, int size);
 void ff_rtp_send_h263_rfc2190(AVFormatContext *s1, const uint8_t *buf1, int size,
                               const uint8_t *mb_info, int mb_info_size);
-void ff_rtp_send_hevc(AVFormatContext *s1, const uint8_t *buf1, int size);
 void ff_rtp_send_aac(AVFormatContext *s1, const uint8_t *buff, int size);
 void ff_rtp_send_latm(AVFormatContext *s1, const uint8_t *buff, int size);
 void ff_rtp_send_amr(AVFormatContext *s1, const uint8_t *buff, int size);
diff --git a/libavformat/rtpenc_aac.c b/libavformat/rtpenc_aac.c
index be8f43a..f835183 100644
--- a/libavformat/rtpenc_aac.c
+++ b/libavformat/rtpenc_aac.c
@@ -18,6 +18,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include "libavutil/intreadwrite.h"
+
 #include "avformat.h"
 #include "rtpenc.h"
 
@@ -25,21 +27,24 @@
 void ff_rtp_send_aac(AVFormatContext *s1, const uint8_t *buff, int size)
 {
     RTPMuxContext *s = s1->priv_data;
-    int len, max_packet_size;
+    AVStream *st = s1->streams[0];
+    const int max_au_headers_size = 2 + 2 * s->max_frames_per_packet;
+    int len, max_packet_size = s->max_payload_size - max_au_headers_size;
     uint8_t *p;
-    const int max_frames_per_packet = s->max_frames_per_packet ? s->max_frames_per_packet : 5;
-    const int max_au_headers_size = 2 + 2 * max_frames_per_packet;
 
     /* skip ADTS header, if present */
     if ((s1->streams[0]->codec->extradata_size) == 0) {
         size -= 7;
         buff += 7;
     }
-    max_packet_size = s->max_payload_size - max_au_headers_size;
 
     /* test if the packet must be sent */
     len = (s->buf_ptr - s->buf);
-    if ((s->num_frames == max_frames_per_packet) || (len && (len + size) > s->max_payload_size)) {
+    if (s->num_frames &&
+        (s->num_frames == s->max_frames_per_packet ||
+         (len + size) > s->max_payload_size ||
+         av_compare_ts(s->cur_timestamp - s->timestamp, st->time_base,
+                       s1->max_delay, AV_TIME_BASE_Q) >= 0)) {
         int au_size = s->num_frames * 2;
 
         p = s->buf + max_au_headers_size - au_size - 2;
@@ -47,8 +52,7 @@
             memmove(p + 2, s->buf + 2, au_size);
         }
         /* Write the AU header size */
-        p[0] =  au_size >> 5;
-        p[1] = (au_size & 0x1F) << 3;
+        AV_WB16(p, au_size * 8);
 
         ff_rtp_send_data(s1, p, s->buf_ptr - p, 1);
 
@@ -61,8 +65,7 @@
 
     if (size <= max_packet_size) {
         p = s->buf + s->num_frames++ * 2 + 2;
-        *p++ = size >> 5;
-        *p = (size & 0x1F) << 3;
+        AV_WB16(p, size * 8);
         memcpy(s->buf_ptr, buff, size);
         s->buf_ptr += size;
     } else {
@@ -70,12 +73,10 @@
 
         max_packet_size = s->max_payload_size - 4;
         p = s->buf;
-        p[0] = 0;
-        p[1] = 16;
+        AV_WB16(p, 2 * 8);
         while (size > 0) {
             len = FFMIN(size, max_packet_size);
-            p[2] = au_size >> 5;
-            p[3] = (au_size & 0x1F) << 3;
+            AV_WB16(&p[2], au_size * 8);
             memcpy(p + 4, buff, len);
             ff_rtp_send_data(s1, p, len + 4, len == size);
             size -= len;
diff --git a/libavformat/rtpenc_amr.c b/libavformat/rtpenc_amr.c
index bd1c197..8df5a3c 100644
--- a/libavformat/rtpenc_amr.c
+++ b/libavformat/rtpenc_amr.c
@@ -30,13 +30,18 @@
 void ff_rtp_send_amr(AVFormatContext *s1, const uint8_t *buff, int size)
 {
     RTPMuxContext *s          = s1->priv_data;
+    AVStream *st              = s1->streams[0];
     int max_header_toc_size   = 1 + s->max_frames_per_packet;
     uint8_t *p;
     int len;
 
     /* Test if the packet must be sent. */
     len = s->buf_ptr - s->buf;
-    if (s->num_frames == s->max_frames_per_packet || (len && len + size - 1 > s->max_payload_size)) {
+    if (s->num_frames &&
+        (s->num_frames == s->max_frames_per_packet ||
+         len + size - 1 > s->max_payload_size ||
+         av_compare_ts(s->cur_timestamp - s->timestamp, st->time_base,
+                       s1->max_delay, AV_TIME_BASE_Q) >= 0)) {
         int header_size = s->num_frames + 1;
         p = s->buf + max_header_toc_size - header_size;
         if (p != s->buf)
diff --git a/libavformat/rtpenc_chain.c b/libavformat/rtpenc_chain.c
index 302c14c..74f306e 100644
--- a/libavformat/rtpenc_chain.c
+++ b/libavformat/rtpenc_chain.c
@@ -91,9 +91,7 @@
         if (handle && rtpctx->pb) {
             avio_closep(&rtpctx->pb);
         } else if (rtpctx->pb) {
-            uint8_t *ptr;
-            avio_close_dyn_buf(rtpctx->pb, &ptr);
-            av_free(ptr);
+            ffio_free_dyn_buf(&rtpctx->pb);
         }
         avformat_free_context(rtpctx);
         return ret;
diff --git a/libavformat/rtpenc_h264.c b/libavformat/rtpenc_h264.c
deleted file mode 100644
index d2b2ed8..0000000
--- a/libavformat/rtpenc_h264.c
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * RTP packetization for H.264 (RFC3984)
- * Copyright (c) 2008 Luca Abeni
- *
- * 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 H.264 packetization
- * @author Luca Abeni <lucabe72@email.it>
- */
-
-#include "avformat.h"
-#include "avc.h"
-#include "rtpenc.h"
-
-static void nal_send(AVFormatContext *s1, const uint8_t *buf, int size, int last)
-{
-    RTPMuxContext *s = s1->priv_data;
-
-    av_log(s1, AV_LOG_DEBUG, "Sending NAL %x of len %d M=%d\n", buf[0] & 0x1F, size, last);
-    if (size <= s->max_payload_size) {
-        ff_rtp_send_data(s1, buf, size, last);
-    } else {
-        uint8_t type = buf[0] & 0x1F;
-        uint8_t nri = buf[0] & 0x60;
-
-        if (s->flags & FF_RTP_FLAG_H264_MODE0) {
-            av_log(s1, AV_LOG_ERROR,
-                   "NAL size %d > %d, try -slice-max-size %d\n", size,
-                   s->max_payload_size, s->max_payload_size);
-            return;
-        }
-        av_log(s1, AV_LOG_DEBUG, "NAL size %d > %d\n", size, s->max_payload_size);
-        s->buf[0] = 28;        /* FU Indicator; Type = 28 ---> FU-A */
-        s->buf[0] |= nri;
-        s->buf[1] = type;
-        s->buf[1] |= 1 << 7;
-        buf += 1;
-        size -= 1;
-        while (size + 2 > s->max_payload_size) {
-            memcpy(&s->buf[2], buf, s->max_payload_size - 2);
-            ff_rtp_send_data(s1, s->buf, s->max_payload_size, 0);
-            buf += s->max_payload_size - 2;
-            size -= s->max_payload_size - 2;
-            s->buf[1] &= ~(1 << 7);
-        }
-        s->buf[1] |= 1 << 6;
-        memcpy(&s->buf[2], buf, size);
-        ff_rtp_send_data(s1, s->buf, size + 2, last);
-    }
-}
-
-void ff_rtp_send_h264(AVFormatContext *s1, const uint8_t *buf1, int size)
-{
-    const uint8_t *r, *end = buf1 + size;
-    RTPMuxContext *s = s1->priv_data;
-
-    s->timestamp = s->cur_timestamp;
-    if (s->nal_length_size)
-        r = ff_avc_mp4_find_startcode(buf1, end, s->nal_length_size) ? buf1 : end;
-    else
-        r = ff_avc_find_startcode(buf1, end);
-    while (r < end) {
-        const uint8_t *r1;
-
-        if (s->nal_length_size) {
-            r1 = ff_avc_mp4_find_startcode(r, end, s->nal_length_size);
-            if (!r1)
-                r1 = end;
-            r += s->nal_length_size;
-        } else {
-            while (!*(r++));
-            r1 = ff_avc_find_startcode(r, end);
-        }
-        nal_send(s1, r, r1 - r, r1 == end);
-        r = r1;
-    }
-}
diff --git a/libavformat/rtpenc_h264_hevc.c b/libavformat/rtpenc_h264_hevc.c
new file mode 100644
index 0000000..7234c7e
--- /dev/null
+++ b/libavformat/rtpenc_h264_hevc.c
@@ -0,0 +1,207 @@
+/*
+ * RTP packetization for H.264 (RFC3984)
+ * RTP packetizer for HEVC/H.265 payload format (draft version 6)
+ * Copyright (c) 2008 Luca Abeni
+ * Copyright (c) 2014 Thomas Volkert <thomas@homer-conferencing.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
+ * @brief H.264/HEVC packetization
+ * @author Luca Abeni <lucabe72@email.it>
+ */
+
+#include "libavutil/intreadwrite.h"
+
+#include "avformat.h"
+#include "avc.h"
+#include "rtpenc.h"
+
+static void flush_buffered(AVFormatContext *s1, int last)
+{
+    RTPMuxContext *s = s1->priv_data;
+    if (s->buf_ptr != s->buf) {
+        // If we're only sending one single NAL unit, send it as such, skip
+        // the STAP-A/AP framing
+        if (s->buffered_nals == 1) {
+            enum AVCodecID codec = s1->streams[0]->codec->codec_id;
+            if (codec == AV_CODEC_ID_H264)
+                ff_rtp_send_data(s1, s->buf + 3, s->buf_ptr - s->buf - 3, last);
+            else
+                ff_rtp_send_data(s1, s->buf + 4, s->buf_ptr - s->buf - 4, last);
+        } else
+            ff_rtp_send_data(s1, s->buf, s->buf_ptr - s->buf, last);
+    }
+    s->buf_ptr = s->buf;
+    s->buffered_nals = 0;
+}
+
+static void nal_send(AVFormatContext *s1, const uint8_t *buf, int size, int last)
+{
+    RTPMuxContext *s = s1->priv_data;
+    enum AVCodecID codec = s1->streams[0]->codec->codec_id;
+
+    av_log(s1, AV_LOG_DEBUG, "Sending NAL %x of len %d M=%d\n", buf[0] & 0x1F, size, last);
+    if (size <= s->max_payload_size) {
+        int buffered_size = s->buf_ptr - s->buf;
+        int header_size;
+        int skip_aggregate = 0;
+
+        if (codec == AV_CODEC_ID_H264) {
+            header_size = 1;
+            skip_aggregate = s->flags & FF_RTP_FLAG_H264_MODE0;
+        } else {
+            header_size = 2;
+        }
+
+        // Flush buffered NAL units if the current unit doesn't fit
+        if (buffered_size + 2 + size > s->max_payload_size) {
+            flush_buffered(s1, 0);
+            buffered_size = 0;
+        }
+        // If we aren't using mode 0, and the NAL unit fits including the
+        // framing (2 bytes length, plus 1/2 bytes for the STAP-A/AP marker),
+        // write the unit to the buffer as a STAP-A/AP packet, otherwise flush
+        // and send as single NAL.
+        if (buffered_size + 2 + header_size + size <= s->max_payload_size &&
+            !skip_aggregate) {
+            if (buffered_size == 0) {
+                if (codec == AV_CODEC_ID_H264) {
+                    *s->buf_ptr++ = 24;
+                } else {
+                    *s->buf_ptr++ = 48 << 1;
+                    *s->buf_ptr++ = 1;
+                }
+            }
+            AV_WB16(s->buf_ptr, size);
+            s->buf_ptr += 2;
+            memcpy(s->buf_ptr, buf, size);
+            s->buf_ptr += size;
+            s->buffered_nals++;
+        } else {
+            flush_buffered(s1, 0);
+            ff_rtp_send_data(s1, buf, size, last);
+        }
+    } else {
+        int flag_byte, header_size;
+        flush_buffered(s1, 0);
+        if (codec == AV_CODEC_ID_H264 && (s->flags & FF_RTP_FLAG_H264_MODE0)) {
+            av_log(s1, AV_LOG_ERROR,
+                   "NAL size %d > %d, try -slice-max-size %d\n", size,
+                   s->max_payload_size, s->max_payload_size);
+            return;
+        }
+        av_log(s1, AV_LOG_DEBUG, "NAL size %d > %d\n", size, s->max_payload_size);
+        if (codec == AV_CODEC_ID_H264) {
+            uint8_t type = buf[0] & 0x1F;
+            uint8_t nri = buf[0] & 0x60;
+
+            s->buf[0] = 28;        /* FU Indicator; Type = 28 ---> FU-A */
+            s->buf[0] |= nri;
+            s->buf[1] = type;
+            s->buf[1] |= 1 << 7;
+            buf  += 1;
+            size -= 1;
+
+            flag_byte   = 1;
+            header_size = 2;
+        } else {
+            uint8_t nal_type = (buf[0] >> 1) & 0x3F;
+            /*
+             * create the HEVC payload header and transmit the buffer as fragmentation units (FU)
+             *
+             *    0                   1
+             *    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
+             *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+             *   |F|   Type    |  LayerId  | TID |
+             *   +-------------+-----------------+
+             *
+             *      F       = 0
+             *      Type    = 49 (fragmentation unit (FU))
+             *      LayerId = 0
+             *      TID     = 1
+             */
+            s->buf[0] = 49 << 1;
+            s->buf[1] = 1;
+
+            /*
+             *     create the FU header
+             *
+             *     0 1 2 3 4 5 6 7
+             *    +-+-+-+-+-+-+-+-+
+             *    |S|E|  FuType   |
+             *    +---------------+
+             *
+             *       S       = variable
+             *       E       = variable
+             *       FuType  = NAL unit type
+             */
+            s->buf[2]  = nal_type;
+            /* set the S bit: mark as start fragment */
+            s->buf[2] |= 1 << 7;
+
+            /* pass the original NAL header */
+            buf  += 2;
+            size -= 2;
+
+            flag_byte   = 2;
+            header_size = 3;
+        }
+
+        while (size + header_size > s->max_payload_size) {
+            memcpy(&s->buf[header_size], buf, s->max_payload_size - header_size);
+            ff_rtp_send_data(s1, s->buf, s->max_payload_size, 0);
+            buf  += s->max_payload_size - header_size;
+            size -= s->max_payload_size - header_size;
+            s->buf[flag_byte] &= ~(1 << 7);
+        }
+        s->buf[flag_byte] |= 1 << 6;
+        memcpy(&s->buf[header_size], buf, size);
+        ff_rtp_send_data(s1, s->buf, size + header_size, last);
+    }
+}
+
+void ff_rtp_send_h264_hevc(AVFormatContext *s1, const uint8_t *buf1, int size)
+{
+    const uint8_t *r, *end = buf1 + size;
+    RTPMuxContext *s = s1->priv_data;
+
+    s->timestamp = s->cur_timestamp;
+    s->buf_ptr   = s->buf;
+    if (s->nal_length_size)
+        r = ff_avc_mp4_find_startcode(buf1, end, s->nal_length_size) ? buf1 : end;
+    else
+        r = ff_avc_find_startcode(buf1, end);
+    while (r < end) {
+        const uint8_t *r1;
+
+        if (s->nal_length_size) {
+            r1 = ff_avc_mp4_find_startcode(r, end, s->nal_length_size);
+            if (!r1)
+                r1 = end;
+            r += s->nal_length_size;
+        } else {
+            while (!*(r++));
+            r1 = ff_avc_find_startcode(r, end);
+        }
+        nal_send(s1, r, r1 - r, r1 == end);
+        r = r1;
+    }
+    flush_buffered(s1, 1);
+}
diff --git a/libavformat/rtpenc_hevc.c b/libavformat/rtpenc_hevc.c
deleted file mode 100644
index ce661fa..0000000
--- a/libavformat/rtpenc_hevc.c
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * RTP packetizer for HEVC/H.265 payload format (draft version 6)
- * Copyright (c) 2014 Thomas Volkert <thomas@homer-conferencing.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 "avc.h"
-#include "avformat.h"
-#include "rtpenc.h"
-
-#define RTP_HEVC_HEADERS_SIZE 3
-
-static void nal_send(AVFormatContext *ctx, const uint8_t *buf, int len, int last_packet_of_frame)
-{
-    RTPMuxContext *rtp_ctx = ctx->priv_data;
-    int rtp_payload_size   = rtp_ctx->max_payload_size - RTP_HEVC_HEADERS_SIZE;
-    int nal_type           = (buf[0] >> 1) & 0x3F;
-
-    /* send it as one single NAL unit? */
-    if (len <= rtp_ctx->max_payload_size) {
-        /* use the original NAL unit buffer and transmit it as RTP payload */
-        ff_rtp_send_data(ctx, buf, len, last_packet_of_frame);
-    } else {
-        /*
-          create the HEVC payload header and transmit the buffer as fragmentation units (FU)
-
-             0                   1
-             0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
-            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-            |F|   Type    |  LayerId  | TID |
-            +-------------+-----------------+
-
-               F       = 0
-               Type    = 49 (fragmentation unit (FU))
-               LayerId = 0
-               TID     = 1
-         */
-        rtp_ctx->buf[0] = 49 << 1;
-        rtp_ctx->buf[1] = 1;
-
-        /*
-              create the FU header
-
-              0 1 2 3 4 5 6 7
-             +-+-+-+-+-+-+-+-+
-             |S|E|  FuType   |
-             +---------------+
-
-                S       = variable
-                E       = variable
-                FuType  = NAL unit type
-         */
-        rtp_ctx->buf[2]  = nal_type;
-        /* set the S bit: mark as start fragment */
-        rtp_ctx->buf[2] |= 1 << 7;
-
-        /* pass the original NAL header */
-        buf += 2;
-        len -= 2;
-
-        while (len > rtp_payload_size) {
-            /* complete and send current RTP packet */
-            memcpy(&rtp_ctx->buf[RTP_HEVC_HEADERS_SIZE], buf, rtp_payload_size);
-            ff_rtp_send_data(ctx, rtp_ctx->buf, rtp_ctx->max_payload_size, 0);
-
-            buf += rtp_payload_size;
-            len -= rtp_payload_size;
-
-            /* reset the S bit */
-            rtp_ctx->buf[2] &= ~(1 << 7);
-        }
-
-        /* set the E bit: mark as last fragment */
-        rtp_ctx->buf[2] |= 1 << 6;
-
-        /* complete and send last RTP packet */
-        memcpy(&rtp_ctx->buf[RTP_HEVC_HEADERS_SIZE], buf, len);
-        ff_rtp_send_data(ctx, rtp_ctx->buf, len + 2, last_packet_of_frame);
-    }
-}
-
-void ff_rtp_send_hevc(AVFormatContext *ctx, const uint8_t *frame_buf, int frame_size)
-{
-    const uint8_t *next_NAL_unit;
-    const uint8_t *buf_ptr, *buf_end = frame_buf + frame_size;
-    RTPMuxContext *rtp_ctx = ctx->priv_data;
-
-    /* use the default 90 KHz time stamp */
-    rtp_ctx->timestamp = rtp_ctx->cur_timestamp;
-
-    if (rtp_ctx->nal_length_size)
-        buf_ptr = ff_avc_mp4_find_startcode(frame_buf, buf_end, rtp_ctx->nal_length_size) ? frame_buf : buf_end;
-    else
-        buf_ptr = ff_avc_find_startcode(frame_buf, buf_end);
-
-    /* find all NAL units and send them as separate packets */
-    while (buf_ptr < buf_end) {
-        if (rtp_ctx->nal_length_size) {
-            next_NAL_unit = ff_avc_mp4_find_startcode(buf_ptr, buf_end, rtp_ctx->nal_length_size);
-            if (!next_NAL_unit)
-                next_NAL_unit = buf_end;
-
-            buf_ptr += rtp_ctx->nal_length_size;
-        } else {
-            while (!*(buf_ptr++))
-                ;
-            next_NAL_unit = ff_avc_find_startcode(buf_ptr, buf_end);
-        }
-        /* send the next NAL unit */
-        nal_send(ctx, buf_ptr, next_NAL_unit - buf_ptr, next_NAL_unit == buf_end);
-
-        /* jump to the next NAL unit */
-        buf_ptr = next_NAL_unit;
-    }
-}
diff --git a/libavformat/rtpenc_mpegts.c b/libavformat/rtpenc_mpegts.c
index e0339bd..db1680e 100644
--- a/libavformat/rtpenc_mpegts.c
+++ b/libavformat/rtpenc_mpegts.c
@@ -21,6 +21,7 @@
 
 #include "libavutil/mathematics.h"
 #include "avformat.h"
+#include "avio_internal.h"
 
 struct MuxChain {
     AVFormatContext *mpegts_ctx;
@@ -33,11 +34,7 @@
 
     if (chain->mpegts_ctx) {
         av_write_trailer(chain->mpegts_ctx);
-        if (chain->mpegts_ctx->pb) {
-            uint8_t *buf;
-            avio_close_dyn_buf(chain->mpegts_ctx->pb, &buf);
-            av_free(buf);
-        }
+        ffio_free_dyn_buf(&chain->mpegts_ctx->pb);
         avformat_free_context(chain->mpegts_ctx);
     }
     if (chain->rtp_ctx) {
@@ -91,21 +88,16 @@
     st->time_base.num   = 1;
     st->time_base.den   = 90000;
     st->codec->codec_id = AV_CODEC_ID_MPEG2TS;
-    chain->rtp_ctx = rtp_ctx;
     rtp_ctx->pb = s->pb;
     if ((ret = avformat_write_header(rtp_ctx, NULL)) < 0)
         goto fail;
-    rtp_ctx = NULL;
+    chain->rtp_ctx = rtp_ctx;
 
     return 0;
 
 fail:
     if (mpegts_ctx) {
-        if (mpegts_ctx->pb) {
-            uint8_t *buf;
-            avio_close_dyn_buf(mpegts_ctx->pb, &buf);
-            av_free(buf);
-        }
+        ffio_free_dyn_buf(&mpegts_ctx->pb);
         avformat_free_context(mpegts_ctx);
     }
     if (rtp_ctx)
diff --git a/libavformat/rtpenc_xiph.c b/libavformat/rtpenc_xiph.c
index bc40cf8..b4d950b 100644
--- a/libavformat/rtpenc_xiph.c
+++ b/libavformat/rtpenc_xiph.c
@@ -20,6 +20,8 @@
  */
 
 #include "libavutil/avassert.h"
+#include "libavutil/intreadwrite.h"
+
 #include "avformat.h"
 #include "rtpenc.h"
 
@@ -31,10 +33,11 @@
 void ff_rtp_send_xiph(AVFormatContext *s1, const uint8_t *buff, int size)
 {
     RTPMuxContext *s = s1->priv_data;
+    AVStream *st = s1->streams[0];
     int max_pkt_size, xdt, frag;
     uint8_t *q;
 
-    max_pkt_size = s->max_payload_size;
+    max_pkt_size = s->max_payload_size - 6; // ident+frag+tdt/vdt+pkt_num+pkt_length
 
     // set xiph data type
     switch (*buff) {
@@ -74,24 +77,29 @@
         int remaining    = end_ptr - ptr;
 
         av_assert1(s->num_frames <= s->max_frames_per_packet);
-        if ((s->num_frames > 0 && remaining < 0) ||
-            s->num_frames == s->max_frames_per_packet) {
-            // send previous packets now; no room for new data
+        if (s->num_frames > 0 &&
+            (remaining < 0 ||
+             s->num_frames == s->max_frames_per_packet ||
+             av_compare_ts(s->cur_timestamp - s->timestamp, st->time_base,
+                           s1->max_delay, AV_TIME_BASE_Q) >= 0)) {
+            // send previous packets now; no room for new data, or too much delay
             ff_rtp_send_data(s1, s->buf, s->buf_ptr - s->buf, 0);
             s->num_frames = 0;
         }
 
         // buffer current frame to send later
-        if (0 == s->num_frames) s->timestamp = s->cur_timestamp;
+        if (0 == s->num_frames)
+            s->timestamp = s->cur_timestamp;
         s->num_frames++;
 
         // Set packet header. Normally, this is OR'd with frag and xdt,
         // but those are zero, so omitted here
         *q++ = s->num_frames;
 
-        if (s->num_frames > 1) q = s->buf_ptr; // jump ahead if needed
-        *q++ = (size >> 8) & 0xff;
-        *q++ = size & 0xff;
+        if (s->num_frames > 1)
+            q = s->buf_ptr; // jump ahead if needed
+        AV_WB16(q, size);
+        q += 2;
         memcpy(q, buff, size);
         q += size;
         s->buf_ptr = q;
@@ -112,8 +120,8 @@
 
         // set packet headers
         *q++ = (frag << 6) | (xdt << 4); // num_frames = 0
-        *q++ = (len >> 8) & 0xff;
-        *q++ = len & 0xff;
+        AV_WB16(q, len);
+        q += 2;
         // set packet body
         memcpy(q, buff, len);
         q += len;
diff --git a/libavformat/rtsp.c b/libavformat/rtsp.c
index c9ffba4..14ac510 100644
--- a/libavformat/rtsp.c
+++ b/libavformat/rtsp.c
@@ -68,10 +68,11 @@
     { "filter_src", "only receive packets from the negotiated peer IP", 0, AV_OPT_TYPE_CONST, {.i64 = RTSP_FLAG_FILTER_SRC}, 0, 0, DEC, "rtsp_flags" }
 
 #define RTSP_MEDIATYPE_OPTS(name, longname) \
-    { name, longname, OFFSET(media_type_mask), AV_OPT_TYPE_FLAGS, { .i64 = (1 << (AVMEDIA_TYPE_DATA+1)) - 1 }, INT_MIN, INT_MAX, DEC, "allowed_media_types" }, \
+    { name, longname, OFFSET(media_type_mask), AV_OPT_TYPE_FLAGS, { .i64 = (1 << (AVMEDIA_TYPE_SUBTITLE+1)) - 1 }, INT_MIN, INT_MAX, DEC, "allowed_media_types" }, \
     { "video", "Video", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_VIDEO}, 0, 0, DEC, "allowed_media_types" }, \
     { "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" }
+    { "data", "Data", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_DATA}, 0, 0, DEC, "allowed_media_types" }, \
+    { "subtitle", "Subtitle", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_SUBTITLE}, 0, 0, DEC, "allowed_media_types" }
 
 #define RTSP_REORDERING_OPTS() \
     { "reorder_queue_size", "set number of packets to buffer for handling of reordered packets", OFFSET(reordering_queue_size), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, DEC }
@@ -180,20 +181,42 @@
 
 #if CONFIG_RTPDEC
 static void init_rtp_handler(RTPDynamicProtocolHandler *handler,
-                             RTSPStream *rtsp_st, AVCodecContext *codec)
+                             RTSPStream *rtsp_st, AVStream *st)
 {
+    AVCodecContext *codec = st ? st->codec : NULL;
     if (!handler)
         return;
     if (codec)
         codec->codec_id          = handler->codec_id;
     rtsp_st->dynamic_handler = handler;
-    if (handler->alloc) {
-        rtsp_st->dynamic_protocol_context = handler->alloc();
+    if (st)
+        st->need_parsing = handler->need_parsing;
+    if (handler->priv_data_size) {
+        rtsp_st->dynamic_protocol_context = av_mallocz(handler->priv_data_size);
         if (!rtsp_st->dynamic_protocol_context)
             rtsp_st->dynamic_handler = NULL;
     }
 }
 
+static void finalize_rtp_handler_init(AVFormatContext *s, RTSPStream *rtsp_st,
+                                      AVStream *st)
+{
+    if (rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->init) {
+        int ret = rtsp_st->dynamic_handler->init(s, st ? st->index : -1,
+                                                 rtsp_st->dynamic_protocol_context);
+        if (ret < 0) {
+            if (rtsp_st->dynamic_protocol_context) {
+                if (rtsp_st->dynamic_handler->close)
+                    rtsp_st->dynamic_handler->close(
+                        rtsp_st->dynamic_protocol_context);
+                av_free(rtsp_st->dynamic_protocol_context);
+            }
+            rtsp_st->dynamic_protocol_context = NULL;
+            rtsp_st->dynamic_handler = NULL;
+        }
+    }
+}
+
 /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
 static int sdp_parse_rtpmap(AVFormatContext *s,
                             AVStream *st, RTSPStream *rtsp_st,
@@ -219,7 +242,7 @@
     if (codec->codec_id == AV_CODEC_ID_NONE) {
         RTPDynamicProtocolHandler *handler =
             ff_rtp_handler_find_by_name(buf, codec->codec_type);
-        init_rtp_handler(handler, rtsp_st, codec);
+        init_rtp_handler(handler, rtsp_st, st);
         /* If no dynamic handler was found, check with the list of standard
          * allocated types, if such a stream for some reason happens to
          * use a private payload type. This isn't handled in rtpdec.c, since
@@ -262,9 +285,7 @@
     default:
         break;
     }
-    if (rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->init)
-        rtsp_st->dynamic_handler->init(s, st->index,
-                                       rtsp_st->dynamic_protocol_context);
+    finalize_rtp_handler_init(s, rtsp_st, st);
     return 0;
 }
 
@@ -327,7 +348,7 @@
             rtsp_st->dynamic_handler &&
             rtsp_st->dynamic_handler->parse_sdp_a_line) {
             rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
-            rtsp_st->dynamic_protocol_context, line);
+                rtsp_st->dynamic_protocol_context, line);
         }
     }
 }
@@ -399,6 +420,8 @@
             codec_type = AVMEDIA_TYPE_VIDEO;
         } else if (!strcmp(st_type, "application")) {
             codec_type = AVMEDIA_TYPE_DATA;
+        } else if (!strcmp(st_type, "text")) {
+            codec_type = AVMEDIA_TYPE_SUBTITLE;
         }
         if (codec_type == AVMEDIA_TYPE_UNKNOWN || !(rt->media_type_mask & (1 << codec_type))) {
             s1->skip_media = 1;
@@ -445,8 +468,7 @@
                 handler = ff_rtp_handler_find_by_id(
                               rtsp_st->sdp_payload_type, AVMEDIA_TYPE_DATA);
                 init_rtp_handler(handler, rtsp_st, NULL);
-                if (handler && handler->init)
-                    handler->init(s, -1, rtsp_st->dynamic_protocol_context);
+                finalize_rtp_handler_init(s, rtsp_st, NULL);
             }
         } else if (rt->server_type == RTSP_SERVER_WMS &&
                    codec_type == AVMEDIA_TYPE_DATA) {
@@ -469,11 +491,11 @@
                 /* Even static payload types may need a custom depacketizer */
                 handler = ff_rtp_handler_find_by_id(
                               rtsp_st->sdp_payload_type, st->codec->codec_type);
-                init_rtp_handler(handler, rtsp_st, st->codec);
-                if (handler && handler->init)
-                    handler->init(s, st->index,
-                                  rtsp_st->dynamic_protocol_context);
+                init_rtp_handler(handler, rtsp_st, st);
+                finalize_rtp_handler_init(s, rtsp_st, st);
             }
+            if (rt->default_lang[0])
+                av_dict_set(&st->metadata, "language", rt->default_lang, 0);
         }
         /* put a default control url */
         av_strlcpy(rtsp_st->control_url, rt->control_uri,
@@ -537,6 +559,16 @@
             /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
             s->duration   = (end == AV_NOPTS_VALUE) ?
                             AV_NOPTS_VALUE : end - start;
+        } else if (av_strstart(p, "lang:", &p)) {
+            if (s->nb_streams > 0) {
+                get_word(buf1, sizeof(buf1), &p);
+                rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
+                if (rtsp_st->stream_index >= 0) {
+                    st = s->streams[rtsp_st->stream_index];
+                    av_dict_set(&st->metadata, "language", buf1, 0);
+                }
+            } else
+                get_word(rt->default_lang, sizeof(rt->default_lang), &p);
         } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
             if (atoi(p) == 1)
                 rt->transport = RTSP_TRANSPORT_RDT;
@@ -678,11 +710,9 @@
                 AVFormatContext *rtpctx = rtsp_st->transport_priv;
                 av_write_trailer(rtpctx);
                 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
-                    uint8_t *ptr;
                     if (CONFIG_RTSP_MUXER && rtpctx->pb && send_packets)
                         ff_rtsp_tcp_write_packet(s, rtsp_st);
-                    avio_close_dyn_buf(rtpctx->pb, &ptr);
-                    av_free(ptr);
+                    ffio_free_dyn_buf(&rtpctx->pb);
                 } else {
                     avio_closep(&rtpctx->pb);
                 }
@@ -710,9 +740,12 @@
     for (i = 0; i < rt->nb_rtsp_streams; i++) {
         rtsp_st = rt->rtsp_streams[i];
         if (rtsp_st) {
-            if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
-                rtsp_st->dynamic_handler->free(
-                    rtsp_st->dynamic_protocol_context);
+            if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context) {
+                if (rtsp_st->dynamic_handler->close)
+                    rtsp_st->dynamic_handler->close(
+                        rtsp_st->dynamic_protocol_context);
+                av_free(rtsp_st->dynamic_protocol_context);
+            }
             for (j = 0; j < rtsp_st->nb_include_source_addrs; j++)
                 av_freep(&rtsp_st->include_source_addrs[j]);
             av_freep(&rtsp_st->include_source_addrs);
@@ -1524,13 +1557,6 @@
                 err = AVERROR_INVALIDDATA;
                 goto fail;
             }
-            /* Try to initialize the connection state in a
-             * potential NAT router by sending dummy packets.
-             * RTP/RTCP dummy packets are used for RDT, too.
-             */
-            if (CONFIG_RTPDEC &&
-                !(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat)
-                ff_rtp_send_punch_packets(rtsp_st->rtp_handle);
             break;
         }
         case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
@@ -2170,7 +2196,7 @@
 
     /* we look for a line beginning "c=IN IP" */
     while (p < p_end && *p != '\0') {
-        if (p + sizeof("c=IN IP") - 1 < p_end &&
+        if (sizeof("c=IN IP") - 1 < p_end - p &&
             av_strstart(p, "c=IN IP", NULL))
             return AVPROBE_SCORE_EXTENSION;
 
@@ -2372,7 +2398,7 @@
     /* sdp_read_header initializes this again */
     ff_network_close();
 
-    rt->media_type_mask = (1 << (AVMEDIA_TYPE_DATA+1)) - 1;
+    rt->media_type_mask = (1 << (AVMEDIA_TYPE_SUBTITLE+1)) - 1;
 
     ret = sdp_read_header(s);
     s->pb = NULL;
diff --git a/libavformat/rtsp.h b/libavformat/rtsp.h
index a9f2f1e..3cfcfb6 100644
--- a/libavformat/rtsp.h
+++ b/libavformat/rtsp.h
@@ -405,6 +405,8 @@
      * User-Agent string
      */
     char *user_agent;
+
+    char default_lang[4];
 } RTSPState;
 
 #define RTSP_FLAG_FILTER_SRC  0x1    /**< Filter incoming UDP packets -
diff --git a/libavformat/rtspdec.c b/libavformat/rtspdec.c
index c899498..12aa122 100644
--- a/libavformat/rtspdec.c
+++ b/libavformat/rtspdec.c
@@ -506,6 +506,18 @@
     av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
     rt->nb_byes = 0;
 
+    if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
+        for (i = 0; i < rt->nb_rtsp_streams; i++) {
+            RTSPStream *rtsp_st = rt->rtsp_streams[i];
+            /* Try to initialize the connection state in a
+             * potential NAT router by sending dummy packets.
+             * RTP/RTCP dummy packets are used for RDT, too.
+             */
+            if (rtsp_st->rtp_handle &&
+                !(rt->server_type == RTSP_SERVER_WMS && i > 1))
+                ff_rtp_send_punch_packets(rtsp_st->rtp_handle);
+        }
+    }
     if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
         if (rt->transport == RTSP_TRANSPORT_RTP) {
             for (i = 0; i < rt->nb_rtsp_streams; i++) {
@@ -542,6 +554,7 @@
                 AVStream *st = NULL;
                 if (!rtpctx || rtsp_st->stream_index < 0)
                     continue;
+
                 st = s->streams[rtsp_st->stream_index];
                 rtpctx->range_start_offset =
                     av_rescale_q(reply->range_start, AV_TIME_BASE_Q,
diff --git a/libavformat/sctp.c b/libavformat/sctp.c
index d733895..3dae13e 100644
--- a/libavformat/sctp.c
+++ b/libavformat/sctp.c
@@ -48,6 +48,7 @@
 
 #include "libavutil/intreadwrite.h"
 #include "libavutil/parseutils.h"
+#include "libavutil/opt.h"
 #include "avformat.h"
 #include "internal.h"
 #include "network.h"
@@ -147,12 +148,33 @@
 }
 
 typedef struct SCTPContext {
+    const AVClass *class;
     int fd;
+    int listen;
+    int timeout;
+    int listen_timeout;
     int max_streams;
     struct sockaddr_storage dest_addr;
-    socklen_t dest_addr_len;
 } SCTPContext;
 
+#define OFFSET(x) offsetof(SCTPContext, x)
+#define D AV_OPT_FLAG_DECODING_PARAM
+#define E AV_OPT_FLAG_ENCODING_PARAM
+static const AVOption options[] = {
+    { "listen",          "Listen for incoming connections",  OFFSET(listen),         AV_OPT_TYPE_INT, { .i64 = 0 },     0,       1,         .flags = D|E },
+    { "timeout",         "Connection timeout (in milliseconds)", OFFSET(timeout),    AV_OPT_TYPE_INT, { .i64 = 10000 }, INT_MIN, INT_MAX,   .flags = D|E },
+    { "listen_timeout",  "Bind timeout (in milliseconds)",   OFFSET(listen_timeout), AV_OPT_TYPE_INT, { .i64 = -1 },    INT_MIN, INT_MAX,   .flags = D|E },
+    { "max_streams",     "Max stream to allocate",           OFFSET(max_streams), AV_OPT_TYPE_INT, { .i64 = 0 },              0, INT16_MAX, .flags = D|E },
+    { NULL }
+};
+
+static const AVClass sctp_class = {
+    .class_name = "sctp",
+    .item_name  = av_default_item_name,
+    .option     = options,
+    .version    = LIBAVUTIL_VERSION_INT,
+};
+
 static int sctp_open(URLContext *h, const char *uri, int flags)
 {
     struct addrinfo *ai, *cur_ai;
@@ -164,7 +186,7 @@
     SCTPContext *s = h->priv_data;
     const char *p;
     char buf[256];
-    int ret, listen_socket = 0;
+    int ret;
     char hostname[1024], proto[1024], path[1024];
     char portstr[10];
 
@@ -177,11 +199,10 @@
         return AVERROR(EINVAL);
     }
 
-    s->max_streams = 0;
     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), "max_streams", p))
             s->max_streams = strtol(buf, NULL, 10);
     }
@@ -198,23 +219,29 @@
 
     cur_ai = ai;
 
+restart:
     fd = ff_socket(cur_ai->ai_family, SOCK_STREAM, IPPROTO_SCTP);
-    if (fd < 0)
+    if (fd < 0) {
+        ret = ff_neterrno();
         goto fail;
+    }
 
-    s->dest_addr_len = sizeof(s->dest_addr);
+    if (s->listen) {
+        if ((fd = ff_listen_bind(fd, cur_ai->ai_addr, cur_ai->ai_addrlen,
+                                 s->listen_timeout, h)) < 0) {
+            ret = fd;
+            goto fail1;
+        }
+    } else {
+        if ((ret = ff_listen_connect(fd, cur_ai->ai_addr, cur_ai->ai_addrlen,
+                                     s->timeout, h, !!cur_ai->ai_next)) < 0) {
 
-    if (listen_socket) {
-        int fd1;
-        ret = bind(fd, cur_ai->ai_addr, cur_ai->ai_addrlen);
-        listen(fd, 100);
-        fd1 = accept(fd, NULL, NULL);
-        closesocket(fd);
-        fd  = fd1;
-    } else
-        ret = connect(fd, cur_ai->ai_addr, cur_ai->ai_addrlen);
-
-    ff_socket_nonblock(fd, 1);
+            if (ret == AVERROR_EXIT)
+                goto fail1;
+            else
+                goto fail;
+        }
+    }
 
     event.sctp_data_io_event = 1;
     /* TODO: Subscribe to more event types and handle them */
@@ -223,17 +250,20 @@
                    sizeof(event)) != 0) {
         av_log(h, AV_LOG_ERROR,
                "SCTP ERROR: Unable to subscribe to events\n");
-        goto fail;
+        goto fail1;
     }
 
     if (s->max_streams) {
         initparams.sinit_max_instreams = s->max_streams;
         initparams.sinit_num_ostreams  = s->max_streams;
         if (setsockopt(fd, IPPROTO_SCTP, SCTP_INITMSG, &initparams,
-                       sizeof(initparams)) < 0)
+                       sizeof(initparams)) < 0) {
             av_log(h, AV_LOG_ERROR,
                    "SCTP ERROR: Unable to initialize socket max streams %d\n",
                    s->max_streams);
+            ret = ff_neterrno();
+            goto fail1;
+        }
     }
 
     h->priv_data   = s;
@@ -243,6 +273,15 @@
     return 0;
 
 fail:
+    if (cur_ai->ai_next) {
+        /* Retry with the next sockaddr */
+        cur_ai = cur_ai->ai_next;
+        if (fd >= 0)
+            closesocket(fd);
+        ret = 0;
+        goto restart;
+    }
+fail1:
     ret = AVERROR(EIO);
     freeaddrinfo(ai);
     return ret;
@@ -329,4 +368,5 @@
     .url_get_file_handle = sctp_get_file_handle,
     .priv_data_size      = sizeof(SCTPContext),
     .flags               = URL_PROTOCOL_FLAG_NETWORK,
+    .priv_data_class     = &sctp_class,
 };
diff --git a/libavformat/seek.c b/libavformat/seek.c
deleted file mode 100644
index 967f282..0000000
--- a/libavformat/seek.c
+++ /dev/null
@@ -1,507 +0,0 @@
-/*
- * seek utility functions for use within format handlers
- *
- * Copyright (c) 2009 Ivan Schreter
- *
- * 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 "seek.h"
-#include "libavutil/mathematics.h"
-#include "libavutil/mem.h"
-#include "internal.h"
-
-// NOTE: implementation should be moved here in another patch, to keep patches
-// separated.
-
-/**
- * helper structure describing keyframe search state of one stream
- */
-typedef struct {
-    int64_t     pos_lo;      ///< position of the frame with low timestamp in file or INT64_MAX if not found (yet)
-    int64_t     ts_lo;       ///< frame presentation timestamp or same as pos_lo for byte seeking
-
-    int64_t     pos_hi;      ///< position of the frame with high timestamp in file or INT64_MAX if not found (yet)
-    int64_t     ts_hi;       ///< frame presentation timestamp or same as pos_hi for byte seeking
-
-    int64_t     last_pos;    ///< last known position of a frame, for multi-frame packets
-
-    int64_t     term_ts;     ///< termination timestamp (which TS we already read)
-    AVRational  term_ts_tb;  ///< timebase for term_ts
-    int64_t     first_ts;    ///< first packet timestamp in this iteration (to fill term_ts later)
-    AVRational  first_ts_tb; ///< timebase for first_ts
-
-    int         terminated;  ///< termination flag for the current iteration
-} AVSyncPoint;
-
-/**
- * Compute a distance between timestamps.
- *
- * Distances are only comparable, if same time bases are used for computing
- * distances.
- *
- * @param ts_hi high timestamp
- * @param tb_hi high timestamp time base
- * @param ts_lo low timestamp
- * @param tb_lo low timestamp time base
- * @return representation of distance between high and low timestamps
- */
-static int64_t ts_distance(int64_t ts_hi,
-                           AVRational tb_hi,
-                           int64_t ts_lo,
-                           AVRational tb_lo)
-{
-    int64_t hi, lo;
-
-    hi = ts_hi * tb_hi.num * tb_lo.den;
-    lo = ts_lo * tb_lo.num * tb_hi.den;
-
-    return hi - lo;
-}
-
-/**
- * Partial search for keyframes in multiple streams.
- *
- * This routine searches in each stream for the next lower and the next higher
- * timestamp compared to the given target timestamp. The search starts at the current
- * file position and ends at the file position, where all streams have already been
- * examined (or when all higher key frames are found in the first iteration).
- *
- * This routine is called iteratively with an exponential backoff to find the lower
- * timestamp.
- *
- * @param s                 format context
- * @param timestamp         target timestamp (or position, if AVSEEK_FLAG_BYTE)
- * @param timebase          time base for timestamps
- * @param flags             seeking flags
- * @param sync              array with information per stream
- * @param keyframes_to_find count of keyframes to find in total
- * @param found_lo          ptr to the count of already found low timestamp keyframes
- * @param found_hi          ptr to the count of already found high timestamp keyframes
- * @param first_iter        flag for first iteration
- */
-static void search_hi_lo_keyframes(AVFormatContext *s,
-                                   int64_t timestamp,
-                                   AVRational timebase,
-                                   int flags,
-                                   AVSyncPoint *sync,
-                                   int keyframes_to_find,
-                                   int *found_lo,
-                                   int *found_hi,
-                                   int first_iter)
-{
-    AVPacket pkt;
-    AVSyncPoint *sp;
-    AVStream *st;
-    int idx;
-    int flg;
-    int terminated_count = 0;
-    int64_t pos;
-    int64_t pts, dts;   // PTS/DTS from stream
-    int64_t ts;         // PTS in stream-local time base or position for byte seeking
-    AVRational ts_tb;   // Time base of the stream or 1:1 for byte seeking
-
-    for (;;) {
-        if (av_read_frame(s, &pkt) < 0) {
-            // EOF or error, make sure high flags are set
-            for (idx = 0; idx < s->nb_streams; ++idx) {
-                if (s->streams[idx]->discard < AVDISCARD_ALL) {
-                    sp = &sync[idx];
-                    if (sp->pos_hi == INT64_MAX) {
-                        // no high frame exists for this stream
-                        (*found_hi)++;
-                        sp->ts_hi  = INT64_MAX;
-                        sp->pos_hi = INT64_MAX - 1;
-                    }
-                }
-            }
-            break;
-        }
-
-        idx = pkt.stream_index;
-        st = s->streams[idx];
-        if (st->discard >= AVDISCARD_ALL)
-            // this stream is not active, skip packet
-            continue;
-
-        sp = &sync[idx];
-
-        flg = pkt.flags;
-        pos = pkt.pos;
-        pts = pkt.pts;
-        dts = pkt.dts;
-        if (pts == AV_NOPTS_VALUE)
-            // some formats don't provide PTS, only DTS
-            pts = dts;
-
-        av_free_packet(&pkt);
-
-        // Multi-frame packets only return position for the very first frame.
-        // Other frames are read with position == -1. Therefore, we note down
-        // last known position of a frame and use it if a frame without
-        // position arrives. In this way, it's possible to seek to proper
-        // position. Additionally, for parsers not providing position at all,
-        // an approximation will be used (starting position of this iteration).
-        if (pos < 0)
-            pos = sp->last_pos;
-        else
-            sp->last_pos = pos;
-
-        // Evaluate key frames with known TS (or any frames, if AVSEEK_FLAG_ANY set).
-        if (pts != AV_NOPTS_VALUE &&
-            ((flg & AV_PKT_FLAG_KEY) || (flags & AVSEEK_FLAG_ANY))) {
-            if (flags & AVSEEK_FLAG_BYTE) {
-                // for byte seeking, use position as timestamp
-                ts        = pos;
-                ts_tb.num = 1;
-                ts_tb.den = 1;
-            } else {
-                // otherwise, get stream time_base
-                ts    = pts;
-                ts_tb = st->time_base;
-            }
-
-            if (sp->first_ts == AV_NOPTS_VALUE) {
-                // Note down termination timestamp for the next iteration - when
-                // we encounter a packet with the same timestamp, we will ignore
-                // any further packets for this stream in next iteration (as they
-                // are already evaluated).
-                sp->first_ts    = ts;
-                sp->first_ts_tb = ts_tb;
-            }
-
-            if (sp->term_ts != AV_NOPTS_VALUE &&
-                av_compare_ts(ts, ts_tb, sp->term_ts, sp->term_ts_tb) > 0) {
-                // past the end position from last iteration, ignore packet
-                if (!sp->terminated) {
-                    sp->terminated = 1;
-                    ++terminated_count;
-                    if (sp->pos_hi == INT64_MAX) {
-                        // no high frame exists for this stream
-                        (*found_hi)++;
-                        sp->ts_hi  = INT64_MAX;
-                        sp->pos_hi = INT64_MAX - 1;
-                    }
-                    if (terminated_count == keyframes_to_find)
-                        break;  // all terminated, iteration done
-                }
-                continue;
-            }
-
-            if (av_compare_ts(ts, ts_tb, timestamp, timebase) <= 0) {
-                // keyframe found before target timestamp
-                if (sp->pos_lo == INT64_MAX) {
-                    // found first keyframe lower than target timestamp
-                    (*found_lo)++;
-                    sp->ts_lo  = ts;
-                    sp->pos_lo = pos;
-                } else if (sp->ts_lo < ts) {
-                    // found a better match (closer to target timestamp)
-                    sp->ts_lo  = ts;
-                    sp->pos_lo = pos;
-                }
-            }
-            if (av_compare_ts(ts, ts_tb, timestamp, timebase) >= 0) {
-                // keyframe found after target timestamp
-                if (sp->pos_hi == INT64_MAX) {
-                    // found first keyframe higher than target timestamp
-                    (*found_hi)++;
-                    sp->ts_hi  = ts;
-                    sp->pos_hi = pos;
-                    if (*found_hi >= keyframes_to_find && first_iter) {
-                        // We found high frame for all. They may get updated
-                        // to TS closer to target TS in later iterations (which
-                        // will stop at start position of previous iteration).
-                        break;
-                    }
-                } else if (sp->ts_hi > ts) {
-                    // found a better match (actually, shouldn't happen)
-                    sp->ts_hi  = ts;
-                    sp->pos_hi = pos;
-                }
-            }
-        }
-    }
-
-    // Clean up the parser.
-    ff_read_frame_flush(s);
-}
-
-int64_t ff_gen_syncpoint_search(AVFormatContext *s,
-                                int stream_index,
-                                int64_t pos,
-                                int64_t ts_min,
-                                int64_t ts,
-                                int64_t ts_max,
-                                int flags)
-{
-    AVSyncPoint *sync, *sp;
-    AVStream *st;
-    int i;
-    int keyframes_to_find = 0;
-    int64_t curpos;
-    int64_t step;
-    int found_lo = 0, found_hi = 0;
-    int64_t min_distance, distance;
-    int64_t min_pos = 0;
-    int first_iter = 1;
-    AVRational time_base;
-
-    if (flags & AVSEEK_FLAG_BYTE) {
-        // for byte seeking, we have exact 1:1 "timestamps" - positions
-        time_base.num = 1;
-        time_base.den = 1;
-    } else {
-        if (stream_index >= 0) {
-            // we have a reference stream, which time base we use
-            st = s->streams[stream_index];
-            time_base = st->time_base;
-        } else {
-            // no reference stream, use AV_TIME_BASE as reference time base
-            time_base.num = 1;
-            time_base.den = AV_TIME_BASE;
-        }
-    }
-
-    // Initialize syncpoint structures for each stream.
-    sync = av_malloc_array(s->nb_streams, sizeof(AVSyncPoint));
-    if (!sync)
-        // cannot allocate helper structure
-        return -1;
-
-    for (i = 0; i < s->nb_streams; ++i) {
-        st = s->streams[i];
-        sp = &sync[i];
-
-        sp->pos_lo     = INT64_MAX;
-        sp->ts_lo      = INT64_MAX;
-        sp->pos_hi     = INT64_MAX;
-        sp->ts_hi      = INT64_MAX;
-        sp->terminated = 0;
-        sp->first_ts   = AV_NOPTS_VALUE;
-        sp->term_ts    = ts_max;
-        sp->term_ts_tb = time_base;
-        sp->last_pos   = pos;
-
-        st->cur_dts    = AV_NOPTS_VALUE;
-
-        if (st->discard < AVDISCARD_ALL)
-            ++keyframes_to_find;
-    }
-
-    if (!keyframes_to_find) {
-        // no stream active, error
-        av_free(sync);
-        return -1;
-    }
-
-    // Find keyframes in all active streams with timestamp/position just before
-    // and just after requested timestamp/position.
-    step = s->pb->buffer_size;
-    curpos = FFMAX(pos - step / 2, 0);
-    for (;;) {
-        avio_seek(s->pb, curpos, SEEK_SET);
-        search_hi_lo_keyframes(s,
-                               ts, time_base,
-                               flags,
-                               sync,
-                               keyframes_to_find,
-                               &found_lo, &found_hi,
-                               first_iter);
-        if (found_lo == keyframes_to_find && found_hi == keyframes_to_find)
-            break;  // have all keyframes we wanted
-        if (!curpos)
-            break;  // cannot go back anymore
-
-        curpos = pos - step;
-        if (curpos < 0)
-            curpos = 0;
-        step *= 2;
-
-        // switch termination positions
-        for (i = 0; i < s->nb_streams; ++i) {
-            st = s->streams[i];
-            st->cur_dts = AV_NOPTS_VALUE;
-
-            sp = &sync[i];
-            if (sp->first_ts != AV_NOPTS_VALUE) {
-                sp->term_ts    = sp->first_ts;
-                sp->term_ts_tb = sp->first_ts_tb;
-                sp->first_ts   = AV_NOPTS_VALUE;
-            }
-            sp->terminated = 0;
-            sp->last_pos = curpos;
-        }
-        first_iter = 0;
-    }
-
-    // Find actual position to start decoding so that decoder synchronizes
-    // closest to ts and between ts_min and ts_max.
-    pos = INT64_MAX;
-
-    for (i = 0; i < s->nb_streams; ++i) {
-        st = s->streams[i];
-        if (st->discard < AVDISCARD_ALL) {
-            sp = &sync[i];
-            min_distance = INT64_MAX;
-            // Find timestamp closest to requested timestamp within min/max limits.
-            if (sp->pos_lo != INT64_MAX
-                && av_compare_ts(ts_min, time_base, sp->ts_lo, st->time_base) <= 0
-                && av_compare_ts(sp->ts_lo, st->time_base, ts_max, time_base) <= 0) {
-                // low timestamp is in range
-                min_distance = ts_distance(ts, time_base, sp->ts_lo, st->time_base);
-                min_pos = sp->pos_lo;
-            }
-            if (sp->pos_hi != INT64_MAX
-                && av_compare_ts(ts_min, time_base, sp->ts_hi, st->time_base) <= 0
-                && av_compare_ts(sp->ts_hi, st->time_base, ts_max, time_base) <= 0) {
-                // high timestamp is in range, check distance
-                distance = ts_distance(sp->ts_hi, st->time_base, ts, time_base);
-                if (distance < min_distance) {
-                    min_distance = distance;
-                    min_pos = sp->pos_hi;
-                }
-            }
-            if (min_distance == INT64_MAX) {
-                // no timestamp is in range, cannot seek
-                av_free(sync);
-                return -1;
-            }
-            if (min_pos < pos)
-                pos = min_pos;
-        }
-    }
-
-    avio_seek(s->pb, pos, SEEK_SET);
-    av_free(sync);
-    return pos;
-}
-
-AVParserState *ff_store_parser_state(AVFormatContext *s)
-{
-    int i;
-    AVStream *st;
-    AVParserStreamState *ss;
-    AVParserState *state = av_malloc(sizeof(AVParserState));
-    if (!state)
-        return NULL;
-
-    state->stream_states = av_malloc_array(s->nb_streams, sizeof(AVParserStreamState));
-    if (!state->stream_states) {
-        av_free(state);
-        return NULL;
-    }
-
-    state->fpos = avio_tell(s->pb);
-
-    // copy context structures
-    state->packet_buffer                    = s->packet_buffer;
-    state->parse_queue                      = s->parse_queue;
-    state->raw_packet_buffer                = s->raw_packet_buffer;
-    state->raw_packet_buffer_remaining_size = s->raw_packet_buffer_remaining_size;
-
-    s->packet_buffer                        = NULL;
-    s->parse_queue                          = NULL;
-    s->raw_packet_buffer                    = NULL;
-    s->raw_packet_buffer_remaining_size     = RAW_PACKET_BUFFER_SIZE;
-
-    // copy stream structures
-    state->nb_streams = s->nb_streams;
-    for (i = 0; i < s->nb_streams; i++) {
-        st = s->streams[i];
-        ss = &state->stream_states[i];
-
-        ss->parser        = st->parser;
-        ss->last_IP_pts   = st->last_IP_pts;
-        ss->cur_dts       = st->cur_dts;
-        ss->probe_packets = st->probe_packets;
-
-        st->parser        = NULL;
-        st->last_IP_pts   = AV_NOPTS_VALUE;
-        st->cur_dts       = AV_NOPTS_VALUE;
-        st->probe_packets = MAX_PROBE_PACKETS;
-    }
-
-    return state;
-}
-
-void ff_restore_parser_state(AVFormatContext *s, AVParserState *state)
-{
-    int i;
-    AVStream *st;
-    AVParserStreamState *ss;
-    ff_read_frame_flush(s);
-
-    if (!state)
-        return;
-
-    avio_seek(s->pb, state->fpos, SEEK_SET);
-
-    // copy context structures
-    s->packet_buffer                    = state->packet_buffer;
-    s->parse_queue                      = state->parse_queue;
-    s->raw_packet_buffer                = state->raw_packet_buffer;
-    s->raw_packet_buffer_remaining_size = state->raw_packet_buffer_remaining_size;
-
-    // copy stream structures
-    for (i = 0; i < state->nb_streams; i++) {
-        st = s->streams[i];
-        ss = &state->stream_states[i];
-
-        st->parser        = ss->parser;
-        st->last_IP_pts   = ss->last_IP_pts;
-        st->cur_dts       = ss->cur_dts;
-        st->probe_packets = ss->probe_packets;
-    }
-
-    av_freep(&state->stream_states);
-    av_freep(&state);
-}
-
-static void free_packet_list(AVPacketList *pktl)
-{
-    while (pktl) {
-        AVPacketList *cur = pktl;
-        pktl = cur->next;
-        av_free_packet(&cur->pkt);
-        av_free(cur);
-    }
-}
-
-void ff_free_parser_state(AVFormatContext *s, AVParserState *state)
-{
-    int i;
-    AVParserStreamState *ss;
-
-    if (!state)
-        return;
-
-    for (i = 0; i < state->nb_streams; i++) {
-        ss = &state->stream_states[i];
-        if (ss->parser)
-            av_parser_close(ss->parser);
-    }
-
-    free_packet_list(state->packet_buffer);
-    free_packet_list(state->parse_queue);
-    free_packet_list(state->raw_packet_buffer);
-
-    av_freep(&state->stream_states);
-    av_freep(&state);
-}
diff --git a/libavformat/seek.h b/libavformat/seek.h
deleted file mode 100644
index 3fa7ae3..0000000
--- a/libavformat/seek.h
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * seek utility functions for use within format handlers
- *
- * Copyright (c) 2009 Ivan Schreter
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVFORMAT_SEEK_H
-#define AVFORMAT_SEEK_H
-
-#include "avformat.h"
-
-/**
- * structure to store parser state of one AVStream
- */
-typedef struct AVParserStreamState {
-    // saved members of AVStream
-    AVCodecParserContext   *parser;
-    int64_t                 last_IP_pts;
-    int64_t                 cur_dts;
-    int                     probe_packets;
-} AVParserStreamState;
-
-/**
- * structure to store parser state of AVFormat
- */
-typedef struct AVParserState {
-    int64_t         fpos;                   ///< file position at the time of call
-
-    // saved members of AVFormatContext
-    AVPacketList   *packet_buffer;          ///< packet buffer of original state
-    AVPacketList   *parse_queue;            ///< parse queue of original state
-    AVPacketList   *raw_packet_buffer;      ///< raw packet buffer of original state
-    int raw_packet_buffer_remaining_size;   ///< remaining space in raw_packet_buffer
-
-    // saved info for streams
-    int                  nb_streams;        ///< number of streams with stored state
-    AVParserStreamState *stream_states;     ///< states of individual streams (array)
-} AVParserState;
-
-/**
- * Search for the sync point of all active streams.
- *
- * This routine is not supposed to be called directly by a user application,
- * but by demuxers.
- *
- * A sync point is defined as a point in stream, such that, when decoding start
- * from this point, the decoded output of all streams synchronizes closest
- * to the given timestamp ts. This routine also takes timestamp limits into account.
- * Thus, the output will synchronize no sooner than ts_min and no later than ts_max.
- *
- * @param stream_index stream index for time base reference of timestamps
- * @param pos          approximate position where to start searching for key frames
- * @param min_ts       minimum allowed timestamp (position, if AVSEEK_FLAG_BYTE set)
- * @param ts           target timestamp (or position, if AVSEEK_FLAG_BYTE set in flags)
- * @param max_ts       maximum allowed timestamp (position, if AVSEEK_FLAG_BYTE set)
- * @param flags        if AVSEEK_FLAG_ANY is set, seek to any frame, otherwise only
- *                     to a keyframe. If AVSEEK_FLAG_BYTE is set, search by
- *                     position, not by timestamp.
- * @return -1 if no such sync point could be found, otherwise stream position
- *                     (stream is repositioned to this position)
- */
-int64_t ff_gen_syncpoint_search(AVFormatContext *s,
-                                int stream_index,
-                                int64_t pos,
-                                int64_t min_ts,
-                                int64_t ts,
-                                int64_t max_ts,
-                                int flags);
-
-/**
- * Store current parser state and file position.
- *
- * This function can be used by demuxers before a destructive seeking algorithm
- * to store the parser state. Depending on the outcome of the seek, either the original
- * state can be restored or the new state kept and the original state freed.
- *
- * @note As a side effect, the original parser state is reset, since structures
- *       are relinked to the stored state instead of being deeply-copied (for
- *       performance reasons and to keep the code simple).
- *
- * @param s context from which to save state
- * @return parser state object or NULL if memory could not be allocated
- */
-AVParserState *ff_store_parser_state(AVFormatContext *s);
-
-/**
- * Restore previously saved parser state and file position.
- *
- * Saved state will be invalidated and freed by this call, since internal
- * structures will be relinked back to the stored state instead of being
- * deeply-copied.
- *
- * @param s     context to which to restore state (same as used for storing state)
- * @param state state to restore
- */
-void ff_restore_parser_state(AVFormatContext *s, AVParserState *state);
-
-/**
- * Free previously saved parser state.
- *
- * @param s     context to which the state belongs (same as used for storing state)
- * @param state state to free
- */
-void ff_free_parser_state(AVFormatContext *s, AVParserState *state);
-
-#endif /* AVFORMAT_SEEK_H */
diff --git a/libavformat/segafilm.c b/libavformat/segafilm.c
index b0f0c4e..f8b3eee 100644
--- a/libavformat/segafilm.c
+++ b/libavformat/segafilm.c
@@ -38,7 +38,7 @@
 #define CVID_TAG MKBETAG('c', 'v', 'i', 'd')
 #define RAW_TAG  MKBETAG('r', 'a', 'w', ' ')
 
-typedef struct {
+typedef struct film_sample {
   int stream;
   int64_t sample_offset;
   unsigned int sample_size;
diff --git a/libavformat/segment.c b/libavformat/segment.c
index 0ee65bb..b65a2eb 100644
--- a/libavformat/segment.c
+++ b/libavformat/segment.c
@@ -65,7 +65,7 @@
 #define SEGMENT_LIST_FLAG_CACHE 1
 #define SEGMENT_LIST_FLAG_LIVE  2
 
-typedef struct {
+typedef struct SegmentContext {
     const AVClass *class;  /**< Class for private options. */
     int segment_idx;       ///< index of the segment file to write, starting from 0
     int segment_idx_wrap;  ///< number after which the index wraps
diff --git a/libavformat/sierravmd.c b/libavformat/sierravmd.c
index 2046f91..8bdd973 100644
--- a/libavformat/sierravmd.c
+++ b/libavformat/sierravmd.c
@@ -36,7 +36,7 @@
 #define VMD_HEADER_SIZE 0x0330
 #define BYTES_PER_FRAME_RECORD 16
 
-typedef struct {
+typedef struct vmd_frame {
   int stream_index;
   int64_t frame_offset;
   unsigned int frame_size;
diff --git a/libavformat/siff.c b/libavformat/siff.c
index 8da6c2f..b6ea390 100644
--- a/libavformat/siff.c
+++ b/libavformat/siff.c
@@ -21,11 +21,12 @@
 
 #include "libavutil/channel_layout.h"
 #include "libavutil/intreadwrite.h"
+
 #include "avformat.h"
 #include "internal.h"
 #include "avio_internal.h"
 
-enum SIFFTags{
+enum SIFFTags {
     TAG_SIFF = MKTAG('S', 'I', 'F', 'F'),
     TAG_BODY = MKTAG('B', 'O', 'D', 'Y'),
     TAG_VBHD = MKTAG('V', 'B', 'H', 'D'),
@@ -34,7 +35,7 @@
     TAG_SOUN = MKTAG('S', 'O', 'U', 'N'),
 };
 
-enum VBFlags{
+enum VBFlags {
     VB_HAS_GMC     = 0x01,
     VB_HAS_AUDIO   = 0x04,
     VB_HAS_VIDEO   = 0x08,
@@ -42,7 +43,7 @@
     VB_HAS_LENGTH  = 0x20
 };
 
-typedef struct SIFFContext{
+typedef struct SIFFContext {
     int frames;
     int cur_frame;
     int rate;
@@ -53,13 +54,13 @@
     int has_audio;
 
     int curstrm;
-    int pktsize;
+    unsigned int pktsize;
     int gmcsize;
-    int sndsize;
+    unsigned int sndsize;
 
-    int flags;
+    unsigned int flags;
     uint8_t gmc[4];
-}SIFFContext;
+} SIFFContext;
 
 static int siff_probe(AVProbeData *p)
 {
@@ -77,14 +78,14 @@
     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_U8;
-    ast->codec->channels        = 1;
-    ast->codec->channel_layout  = AV_CH_LAYOUT_MONO;
+    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;
+    ast->codec->sample_rate           = c->rate;
     avpriv_set_pts_info(ast, 16, 1, c->rate);
-    ast->start_time = 0;
+    ast->start_time                   = 0;
     return 0;
 }
 
@@ -93,31 +94,31 @@
     AVStream *st;
     int width, height;
 
-    if (avio_rl32(pb) != TAG_VBHD){
+    if (avio_rl32(pb) != TAG_VBHD) {
         av_log(s, AV_LOG_ERROR, "Header chunk is missing\n");
         return AVERROR_INVALIDDATA;
     }
-    if(avio_rb32(pb) != 32){
+    if (avio_rb32(pb) != 32) {
         av_log(s, AV_LOG_ERROR, "Header chunk size is incorrect\n");
         return AVERROR_INVALIDDATA;
     }
-    if(avio_rl16(pb) != 1){
+    if (avio_rl16(pb) != 1) {
         av_log(s, AV_LOG_ERROR, "Incorrect header version\n");
         return AVERROR_INVALIDDATA;
     }
-    width = avio_rl16(pb);
+    width  = avio_rl16(pb);
     height = avio_rl16(pb);
     avio_skip(pb, 4);
     c->frames = avio_rl16(pb);
-    if(!c->frames){
+    if (!c->frames) {
         av_log(s, AV_LOG_ERROR, "File contains no frames ???\n");
         return AVERROR_INVALIDDATA;
     }
-    c->bits = avio_rl16(pb);
-    c->rate = avio_rl16(pb);
+    c->bits        = avio_rl16(pb);
+    c->rate        = avio_rl16(pb);
     c->block_align = c->rate * (c->bits >> 3);
 
-    avio_skip(pb, 16); //zeroes
+    avio_skip(pb, 16); // zeroes
 
     st = avformat_new_stream(s, NULL);
     if (!st)
@@ -135,25 +136,25 @@
     c->cur_frame = 0;
     c->has_video = 1;
     c->has_audio = !!c->rate;
-    c->curstrm = -1;
-    if (c->has_audio && create_audio_stream(s, c) < 0)
-        return AVERROR(ENOMEM);
+    c->curstrm   = -1;
+    if (c->has_audio)
+        return create_audio_stream(s, c);
     return 0;
 }
 
 static int siff_parse_soun(AVFormatContext *s, SIFFContext *c, AVIOContext *pb)
 {
-    if (avio_rl32(pb) != TAG_SHDR){
+    if (avio_rl32(pb) != TAG_SHDR) {
         av_log(s, AV_LOG_ERROR, "Header chunk is missing\n");
         return AVERROR_INVALIDDATA;
     }
-    if(avio_rb32(pb) != 8){
+    if (avio_rb32(pb) != 8) {
         av_log(s, AV_LOG_ERROR, "Header chunk size is incorrect\n");
         return AVERROR_INVALIDDATA;
     }
-    avio_skip(pb, 4); //unknown value
-    c->rate = avio_rl16(pb);
-    c->bits = avio_rl16(pb);
+    avio_skip(pb, 4); // unknown value
+    c->rate        = avio_rl16(pb);
+    c->bits        = avio_rl16(pb);
     c->block_align = c->rate * (c->bits >> 3);
     return create_audio_stream(s, c);
 }
@@ -161,16 +162,16 @@
 static int siff_read_header(AVFormatContext *s)
 {
     AVIOContext *pb = s->pb;
-    SIFFContext *c = s->priv_data;
+    SIFFContext *c  = s->priv_data;
     uint32_t tag;
     int ret;
 
     if (avio_rl32(pb) != TAG_SIFF)
         return AVERROR_INVALIDDATA;
-    avio_skip(pb, 4); //ignore size
+    avio_skip(pb, 4); // ignore size
     tag = avio_rl32(pb);
 
-    if (tag != TAG_VBV1 && tag != TAG_SOUN){
+    if (tag != TAG_VBV1 && tag != TAG_SOUN) {
         av_log(s, AV_LOG_ERROR, "Not a VBV file\n");
         return AVERROR_INVALIDDATA;
     }
@@ -179,11 +180,11 @@
         return ret;
     if (tag == TAG_SOUN && (ret = siff_parse_soun(s, c, pb)) < 0)
         return ret;
-    if (avio_rl32(pb) != MKTAG('B', 'O', 'D', 'Y')){
+    if (avio_rl32(pb) != MKTAG('B', 'O', 'D', 'Y')) {
         av_log(s, AV_LOG_ERROR, "'BODY' chunk is missing\n");
         return AVERROR_INVALIDDATA;
     }
-    avio_skip(pb, 4); //ignore size
+    avio_skip(pb, 4); // ignore size
 
     return 0;
 }
@@ -191,26 +192,27 @@
 static int siff_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     SIFFContext *c = s->priv_data;
-    int size;
 
-    if (c->has_video){
+    if (c->has_video) {
+        unsigned int size;
         if (c->cur_frame >= c->frames)
             return AVERROR_EOF;
-        if (c->curstrm == -1){
+        if (c->curstrm == -1) {
             c->pktsize = avio_rl32(s->pb) - 4;
-            c->flags = avio_rl16(s->pb);
+            c->flags   = avio_rl16(s->pb);
             c->gmcsize = (c->flags & VB_HAS_GMC) ? 4 : 0;
             if (c->gmcsize)
                 avio_read(s->pb, c->gmc, c->gmcsize);
-            c->sndsize = (c->flags & VB_HAS_AUDIO) ? avio_rl32(s->pb): 0;
+            c->sndsize = (c->flags & VB_HAS_AUDIO) ? avio_rl32(s->pb) : 0;
             c->curstrm = !!(c->flags & VB_HAS_AUDIO);
         }
 
-        if (!c->curstrm){
+        if (!c->curstrm) {
+            if (c->pktsize < 2LL + c->sndsize + c->gmcsize)
+                return AVERROR_INVALIDDATA;
+
             size = c->pktsize - c->sndsize - c->gmcsize - 2;
             size = ffio_limit(s->pb, size);
-            if(size < 0 || c->pktsize < c->sndsize)
-                return AVERROR_INVALIDDATA;
             if (av_new_packet(pkt, size + c->gmcsize + 2) < 0)
                 return AVERROR(ENOMEM);
             AV_WL16(pkt->data, c->flags);
@@ -221,25 +223,26 @@
                 return AVERROR_INVALIDDATA;
             }
             pkt->stream_index = 0;
-            c->curstrm = -1;
-        }else{
-            if ((size = av_get_packet(s->pb, pkt, c->sndsize - 4)) < 0)
+            c->curstrm        = -1;
+        } else {
+            int pktsize = av_get_packet(s->pb, pkt, c->sndsize - 4);
+            if (pktsize < 0)
                 return AVERROR(EIO);
             pkt->stream_index = 1;
-            pkt->duration     = size;
-            c->curstrm = 0;
+            pkt->duration     = pktsize;
+            c->curstrm        = 0;
         }
-        if(!c->cur_frame || c->curstrm)
+        if (!c->cur_frame || c->curstrm)
             pkt->flags |= AV_PKT_FLAG_KEY;
         if (c->curstrm == -1)
             c->cur_frame++;
-    }else{
-        size = av_get_packet(s->pb, pkt, c->block_align);
-        if(!size)
+    } else {
+        int pktsize = av_get_packet(s->pb, pkt, c->block_align);
+        if (!pktsize)
             return AVERROR_EOF;
-        if(size < 0)
+        if (pktsize <= 0)
             return AVERROR(EIO);
-        pkt->duration = size;
+        pkt->duration = pktsize;
     }
     return pkt->size;
 }
diff --git a/libavformat/smacker.c b/libavformat/smacker.c
index 284cdc1..5dcf4ad 100644
--- a/libavformat/smacker.c
+++ b/libavformat/smacker.c
@@ -321,7 +321,7 @@
                 int err;
 
                 size = avio_rl32(s->pb) - 4;
-                if (!size || size + 4L > frame_size) {
+                if (!size || size + 4LL > frame_size) {
                     av_log(s, AV_LOG_ERROR, "Invalid audio part size\n");
                     return AVERROR_INVALIDDATA;
                 }
diff --git a/libavformat/smoothstreamingenc.c b/libavformat/smoothstreamingenc.c
index 075b303..07173a9 100644
--- a/libavformat/smoothstreamingenc.c
+++ b/libavformat/smoothstreamingenc.c
@@ -38,7 +38,7 @@
 #include "libavutil/mathematics.h"
 #include "libavutil/intreadwrite.h"
 
-typedef struct {
+typedef struct Fragment {
     char file[1024];
     char infofile[1024];
     int64_t start_time, duration;
@@ -46,7 +46,7 @@
     int64_t start_pos, size;
 } Fragment;
 
-typedef struct {
+typedef struct OutputStream {
     AVFormatContext *ctx;
     int ctx_inited;
     char dirname[1024];
@@ -66,7 +66,7 @@
     int audio_tag;
 } OutputStream;
 
-typedef struct {
+typedef struct SmoothStreamingContext {
     const AVClass *class;  /* Class for private options. */
     int window_size;
     int extra_window_size;
diff --git a/libavformat/soxenc.c b/libavformat/soxenc.c
index 95af10c..bfa9002 100644
--- a/libavformat/soxenc.c
+++ b/libavformat/soxenc.c
@@ -37,7 +37,7 @@
 #include "rawenc.h"
 #include "sox.h"
 
-typedef struct {
+typedef struct SoXContext {
     int64_t header_size;
 } SoXContext;
 
diff --git a/libavformat/spdifenc.c b/libavformat/spdifenc.c
index 18afd42..cdcff24 100644
--- a/libavformat/spdifenc.c
+++ b/libavformat/spdifenc.c
@@ -51,6 +51,7 @@
 #include "spdif.h"
 #include "libavcodec/ac3.h"
 #include "libavcodec/dca.h"
+#include "libavcodec/dca_syncwords.h"
 #include "libavcodec/aacadtsdec.h"
 #include "libavutil/opt.h"
 
@@ -251,25 +252,25 @@
         return AVERROR_INVALIDDATA;
 
     switch (syncword_dts) {
-    case DCA_MARKER_RAW_BE:
+    case DCA_SYNCWORD_CORE_BE:
         blocks = (AV_RB16(pkt->data + 4) >> 2) & 0x7f;
         core_size = ((AV_RB24(pkt->data + 5) >> 4) & 0x3fff) + 1;
         sample_rate = avpriv_dca_sample_rates[(pkt->data[8] >> 2) & 0x0f];
         break;
-    case DCA_MARKER_RAW_LE:
+    case DCA_SYNCWORD_CORE_LE:
         blocks = (AV_RL16(pkt->data + 4) >> 2) & 0x7f;
         ctx->extra_bswap = 1;
         break;
-    case DCA_MARKER_14B_BE:
+    case DCA_SYNCWORD_CORE_14B_BE:
         blocks =
             (((pkt->data[5] & 0x07) << 4) | ((pkt->data[6] & 0x3f) >> 2));
         break;
-    case DCA_MARKER_14B_LE:
+    case DCA_SYNCWORD_CORE_14B_LE:
         blocks =
             (((pkt->data[4] & 0x07) << 4) | ((pkt->data[7] & 0x3f) >> 2));
         ctx->extra_bswap = 1;
         break;
-    case DCA_HD_MARKER:
+    case DCA_SYNCWORD_SUBSTREAM:
         /* We only handle HD frames that are paired with core. However,
            sometimes DTS-HD streams with core have a stray HD frame without
            core in the beginning of the stream. */
diff --git a/libavformat/tcp.c b/libavformat/tcp.c
index 0aabc9d..4016c0e 100644
--- a/libavformat/tcp.c
+++ b/libavformat/tcp.c
@@ -46,7 +46,7 @@
 static const AVOption options[] = {
     { "listen",          "Listen for incoming connections",  OFFSET(listen),         AV_OPT_TYPE_INT, { .i64 = 0 },     0,       1,       .flags = D|E },
     { "timeout",     "set timeout (in microseconds) of socket I/O operations", OFFSET(rw_timeout),     AV_OPT_TYPE_INT, { .i64 = -1 },         -1, INT_MAX, .flags = D|E },
-    { "listen_timeout",  "Connection awaiting timeout",      OFFSET(listen_timeout), AV_OPT_TYPE_INT, { .i64 = -1 },         -1, INT_MAX, .flags = D|E },
+    { "listen_timeout",  "Connection awaiting timeout (in milliseconds)",      OFFSET(listen_timeout), AV_OPT_TYPE_INT, { .i64 = -1 },         -1, INT_MAX, .flags = D|E },
     { NULL }
 };
 
diff --git a/libavformat/tedcaptionsdec.c b/libavformat/tedcaptionsdec.c
index 68063fa..fb578eb 100644
--- a/libavformat/tedcaptionsdec.c
+++ b/libavformat/tedcaptionsdec.c
@@ -51,7 +51,7 @@
 
 #define HEX_DIGIT_TEST(c) (BETWEEN(c, '0', '9') || BETWEEN((c) | 32, 'a', 'z'))
 #define HEX_DIGIT_VAL(c) ((c) <= '9' ? (c) - '0' : ((c) | 32) - 'a' + 10)
-#define ERR_CODE(c) (c < 0 ? c : AVERROR_INVALIDDATA)
+#define ERR_CODE(c) ((c) < 0 ? (c) : AVERROR_INVALIDDATA)
 
 static void av_bprint_utf8(AVBPrint *bp, unsigned c)
 {
diff --git a/libavformat/thp.c b/libavformat/thp.c
index 714cec6..727fb50 100644
--- a/libavformat/thp.c
+++ b/libavformat/thp.c
@@ -176,6 +176,8 @@
             thp->frame++;
 
         ret = av_get_packet(pb, pkt, size);
+        if (ret < 0)
+            return ret;
         if (ret != size) {
             av_free_packet(pkt);
             return AVERROR(EIO);
@@ -184,6 +186,8 @@
         pkt->stream_index = thp->video_stream_index;
     } else {
         ret = av_get_packet(pb, pkt, thp->audiosize);
+        if (ret < 0)
+            return ret;
         if (ret != thp->audiosize) {
             av_free_packet(pkt);
             return AVERROR(EIO);
diff --git a/libavformat/tls.c b/libavformat/tls.c
index d6a6be3..2a415c9 100644
--- a/libavformat/tls.c
+++ b/libavformat/tls.c
@@ -30,34 +30,34 @@
 #if CONFIG_GNUTLS
 #include <gnutls/gnutls.h>
 #include <gnutls/x509.h>
-#define TLS_read(c, buf, size)  gnutls_record_recv(c->session, buf, size)
-#define TLS_write(c, buf, size) gnutls_record_send(c->session, buf, size)
-#define TLS_shutdown(c)         gnutls_bye(c->session, GNUTLS_SHUT_RDWR)
+#define TLS_read(c, buf, size)  gnutls_record_recv((c)->session, (buf), (size))
+#define TLS_write(c, buf, size) gnutls_record_send((c)->session, (buf), (size))
+#define TLS_shutdown(c)         gnutls_bye((c)->session, GNUTLS_SHUT_RDWR)
 #define TLS_free(c) do { \
-        if (c->session) \
-            gnutls_deinit(c->session); \
-        if (c->cred) \
-            gnutls_certificate_free_credentials(c->cred); \
+        if ((c)->session) \
+            gnutls_deinit((c)->session); \
+        if ((c)->cred) \
+            gnutls_certificate_free_credentials((c)->cred); \
     } while (0)
 #elif CONFIG_OPENSSL
 #include <openssl/bio.h>
 #include <openssl/ssl.h>
 #include <openssl/err.h>
-#define TLS_read(c, buf, size)  SSL_read(c->ssl,  buf, size)
-#define TLS_write(c, buf, size) SSL_write(c->ssl, buf, size)
-#define TLS_shutdown(c)         SSL_shutdown(c->ssl)
+#define TLS_read(c, buf, size)  SSL_read((c)->ssl,  (buf), (size))
+#define TLS_write(c, buf, size) SSL_write((c)->ssl, (buf), (size))
+#define TLS_shutdown(c)         SSL_shutdown((c)->ssl)
 #define TLS_free(c) do { \
-        if (c->ssl) \
-            SSL_free(c->ssl); \
-        if (c->ctx) \
-            SSL_CTX_free(c->ctx); \
+        if ((c)->ssl) \
+            SSL_free((c)->ssl); \
+        if ((c)->ctx) \
+            SSL_CTX_free((c)->ctx); \
     } while (0)
 #endif
 #if HAVE_POLL_H
 #include <poll.h>
 #endif
 
-typedef struct {
+typedef struct TLSContext {
     const AVClass *class;
     URLContext *tcp;
 #if CONFIG_GNUTLS
@@ -163,7 +163,7 @@
         c->key_file = av_strdup(buf);
 }
 
-static int tls_open(URLContext *h, const char *uri, int flags)
+static int tls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
 {
     TLSContext *c = h->priv_data;
     int ret;
@@ -175,7 +175,8 @@
     const char *proxy_path;
     int use_proxy;
 
-    ff_tls_init();
+    if ((ret = ff_tls_init()) < 0)
+        return ret;
 
     if (c->listen)
         snprintf(opts, sizeof(opts), "?listen=1");
@@ -215,7 +216,7 @@
     }
 
     ret = ffurl_open(&c->tcp, buf, AVIO_FLAG_READ_WRITE,
-                     &h->interrupt_callback, NULL);
+                     &h->interrupt_callback, options);
     if (ret)
         goto fail;
     c->fd = ffurl_get_file_handle(c->tcp);
@@ -394,7 +395,7 @@
 
 URLProtocol ff_tls_protocol = {
     .name           = "tls",
-    .url_open       = tls_open,
+    .url_open2      = tls_open,
     .url_read       = tls_read,
     .url_write      = tls_write,
     .url_close      = tls_close,
diff --git a/libavformat/tta.c b/libavformat/tta.c
index 7174fd5..7566939 100644
--- a/libavformat/tta.c
+++ b/libavformat/tta.c
@@ -28,7 +28,7 @@
 #include "libavutil/crc.h"
 #include "libavutil/dict.h"
 
-typedef struct {
+typedef struct TTAContext {
     int totalframes, currentframe;
     int frame_size;
     int last_frame_size;
@@ -56,12 +56,14 @@
     TTAContext *c = s->priv_data;
     AVStream *st;
     int i, channels, bps, samplerate;
-    uint64_t framepos, start_offset;
+    int64_t framepos, start_offset;
     uint32_t nb_samples, crc;
 
     ff_id3v1_read(s);
 
     start_offset = avio_tell(s->pb);
+    if (start_offset < 0)
+        return start_offset;
     ffio_init_checksum(s->pb, tta_check_crc, UINT32_MAX);
     if (avio_rl32(s->pb) != AV_RL32("TTA1"))
         return AVERROR_INVALIDDATA;
@@ -82,7 +84,7 @@
     }
 
     crc = ffio_get_checksum(s->pb) ^ UINT32_MAX;
-    if (crc != avio_rl32(s->pb)) {
+    if (crc != avio_rl32(s->pb) && s->error_recognition & AV_EF_CRCCHECK) {
         av_log(s, AV_LOG_ERROR, "Header CRC error\n");
         return AVERROR_INVALIDDATA;
     }
@@ -107,7 +109,10 @@
     st->start_time = 0;
     st->duration = nb_samples;
 
-    framepos = avio_tell(s->pb) + 4*c->totalframes + 4;
+    framepos = avio_tell(s->pb);
+    if (framepos < 0)
+        return framepos;
+    framepos += 4 * c->totalframes + 4;
 
     if (ff_alloc_extradata(st->codec, avio_tell(s->pb) - start_offset))
         return AVERROR(ENOMEM);
@@ -118,12 +123,14 @@
     ffio_init_checksum(s->pb, tta_check_crc, UINT32_MAX);
     for (i = 0; i < c->totalframes; i++) {
         uint32_t size = avio_rl32(s->pb);
-        av_add_index_entry(st, framepos, i * c->frame_size, size, 0,
-                           AVINDEX_KEYFRAME);
+        int r;
+        if ((r = av_add_index_entry(st, framepos, i * c->frame_size, size, 0,
+                                    AVINDEX_KEYFRAME)) < 0)
+            return r;
         framepos += size;
     }
     crc = ffio_get_checksum(s->pb) ^ UINT32_MAX;
-    if (crc != avio_rl32(s->pb)) {
+    if (crc != avio_rl32(s->pb) && s->error_recognition & AV_EF_CRCCHECK) {
         av_log(s, AV_LOG_ERROR, "Seek table CRC error\n");
         return AVERROR_INVALIDDATA;
     }
@@ -153,6 +160,11 @@
     if (c->currentframe >= c->totalframes)
         return AVERROR_EOF;
 
+    if (st->nb_index_entries < c->totalframes) {
+        av_log(s, AV_LOG_ERROR, "Index entry disappeared\n");
+        return AVERROR_INVALIDDATA;
+    }
+
     size = st->index_entries[c->currentframe].size;
 
     ret = av_get_packet(s->pb, pkt, size);
diff --git a/libavformat/tty.c b/libavformat/tty.c
index 909b550..9022e91 100644
--- a/libavformat/tty.c
+++ b/libavformat/tty.c
@@ -34,7 +34,7 @@
 #include "internal.h"
 #include "sauce.h"
 
-typedef struct {
+typedef struct TtyDemuxContext {
     AVClass *class;
     int chars_per_frame;
     uint64_t fsize;  /**< file size less metadata buffer */
diff --git a/libavformat/udp.c b/libavformat/udp.c
index 91c7910..b6a4724 100644
--- a/libavformat/udp.c
+++ b/libavformat/udp.c
@@ -71,12 +71,13 @@
 #define UDP_MAX_PKT_SIZE 65536
 #define UDP_HEADER_SIZE 8
 
-typedef struct {
+typedef struct UDPContext {
     const AVClass *class;
     int udp_fd;
     int ttl;
     int udplite_coverage;
     int buffer_size;
+    int pkt_size;
     int is_multicast;
     int is_broadcast;
     int local_port;
@@ -98,37 +99,42 @@
 #endif
     uint8_t tmp[UDP_MAX_PKT_SIZE+4];
     int remaining_in_dg;
-    char *local_addr;
-    int packet_size;
+    char *localaddr;
     int timeout;
     struct sockaddr_storage local_addr_storage;
+    char *sources;
+    char *block;
 } UDPContext;
 
 #define OFFSET(x) offsetof(UDPContext, x)
 #define D AV_OPT_FLAG_DECODING_PARAM
 #define E AV_OPT_FLAG_ENCODING_PARAM
 static const AVOption options[] = {
-{"buffer_size", "set packet buffer size in bytes", OFFSET(buffer_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, D|E },
-{"localport", "set local port to bind to", OFFSET(local_port), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, D|E },
-{"localaddr", "choose local IP address", OFFSET(local_addr), AV_OPT_TYPE_STRING, {.str = ""}, 0, 0, D|E },
-{"udplite_coverage", "choose UDPLite head size which should be validated by checksum", OFFSET(udplite_coverage), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, D|E },
-{"pkt_size", "set size of UDP packets", OFFSET(packet_size), AV_OPT_TYPE_INT, {.i64 = 1472}, 0, INT_MAX, D|E },
-{"reuse", "explicitly allow or disallow reusing UDP sockets", OFFSET(reuse_socket), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
-{"broadcast", "explicitly allow or disallow broadcast destination", OFFSET(is_broadcast), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
-{"ttl", "set the time to live value (for multicast only)", OFFSET(ttl), AV_OPT_TYPE_INT, {.i64 = 16}, 0, INT_MAX, E },
-{"connect", "set if connect() should be called on socket", OFFSET(is_connected), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
-/* TODO 'sources', 'block' option */
-{"fifo_size", "set the UDP receiving circular buffer size, expressed as a number of packets with size of 188 bytes", OFFSET(circular_buffer_size), AV_OPT_TYPE_INT, {.i64 = 7*4096}, 0, INT_MAX, D },
-{"overrun_nonfatal", "survive in case of UDP receiving circular buffer overrun", OFFSET(overrun_nonfatal), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D },
-{"timeout", "set raise error timeout (only in read mode)", OFFSET(timeout), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, D },
-{NULL}
+    { "buffer_size",    "System data size (in bytes)",                     OFFSET(buffer_size),    AV_OPT_TYPE_INT,    { .i64 = -1 },    -1, INT_MAX, .flags = D|E },
+    { "localport",      "Local port",                                      OFFSET(local_port),     AV_OPT_TYPE_INT,    { .i64 = -1 },    -1, INT_MAX, D|E },
+    { "local_port",     "Local port",                                      OFFSET(local_port),     AV_OPT_TYPE_INT,    { .i64 = -1 },    -1, INT_MAX, .flags = D|E },
+    { "localaddr",      "Local address",                                   OFFSET(localaddr),      AV_OPT_TYPE_STRING, { .str = NULL },               .flags = D|E },
+    { "udplite_coverage", "choose UDPLite head size which should be validated by checksum", OFFSET(udplite_coverage), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, D|E },
+    { "pkt_size",       "set size of UDP packets",                         OFFSET(pkt_size),       AV_OPT_TYPE_INT,    { .i64 = 1472 },  -1, INT_MAX, D|E },
+    { "pkt_size",       "Maximum UDP packet size",                         OFFSET(pkt_size),       AV_OPT_TYPE_INT,    { .i64 = 1472 },  -1, INT_MAX, .flags = D|E },
+    { "reuse",          "explicitly allow reusing UDP sockets",            OFFSET(reuse_socket),   AV_OPT_TYPE_INT,    { .i64 = -1 },    -1, 1,       D|E },
+    { "reuse_socket",   "explicitly allow reusing UDP sockets",            OFFSET(reuse_socket),   AV_OPT_TYPE_INT,    { .i64 = -1 },    -1, 1,       .flags = D|E },
+    { "broadcast", "explicitly allow or disallow broadcast destination",   OFFSET(is_broadcast),   AV_OPT_TYPE_INT,    { .i64 = 0  },     0, 1,       E },
+    { "ttl",            "Time to live (multicast only)",                   OFFSET(ttl),            AV_OPT_TYPE_INT,    { .i64 = 16 },     0, INT_MAX, E },
+    { "connect",        "set if connect() should be called on socket",     OFFSET(is_connected),   AV_OPT_TYPE_INT,    { .i64 =  0 },     0, 1,       .flags = D|E },
+    { "fifo_size",      "set the UDP receiving circular buffer size, expressed as a number of packets with size of 188 bytes", OFFSET(circular_buffer_size), AV_OPT_TYPE_INT, {.i64 = 7*4096}, 0, INT_MAX, D },
+    { "overrun_nonfatal", "survive in case of UDP receiving circular buffer overrun", OFFSET(overrun_nonfatal), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1,    D },
+    { "timeout",        "set raise error timeout (only in read mode)",     OFFSET(timeout),        AV_OPT_TYPE_INT,    { .i64 = 0 },      0, INT_MAX, D },
+    { "sources",        "Source list",                                     OFFSET(sources),        AV_OPT_TYPE_STRING, { .str = NULL },               .flags = D|E },
+    { "block",          "Block list",                                      OFFSET(block),          AV_OPT_TYPE_STRING, { .str = NULL },               .flags = D|E },
+    { NULL }
 };
 
-static const AVClass udp_context_class = {
-    .class_name     = "udp",
-    .item_name      = av_default_item_name,
-    .option         = options,
-    .version        = LIBAVUTIL_VERSION_INT,
+static const AVClass udp_class = {
+    .class_name = "udp",
+    .item_name  = av_default_item_name,
+    .option     = options,
+    .version    = LIBAVUTIL_VERSION_INT,
 };
 
 static const AVClass udplite_context_class = {
@@ -354,7 +360,7 @@
 
     if (((struct sockaddr *) &s->dest_addr)->sa_family)
         family = ((struct sockaddr *) &s->dest_addr)->sa_family;
-    res0 = udp_resolve_host(localaddr[0] ? localaddr : NULL, s->local_port,
+    res0 = udp_resolve_host((localaddr && localaddr[0]) ? localaddr : NULL, s->local_port,
                             SOCK_DGRAM, family, AI_PASSIVE);
     if (!res0)
         goto fail;
@@ -563,16 +569,31 @@
     char buf[256];
     struct sockaddr_storage my_addr;
     socklen_t len;
-    int reuse_specified = 0;
     int i, num_include_sources = 0, num_exclude_sources = 0;
     char *include_sources[32], *exclude_sources[32];
 
     h->is_streamed = 1;
 
     is_output = !(flags & AVIO_FLAG_READ);
-    if (!s->buffer_size) /* if not set explicitly */
+    if (s->buffer_size < 0)
         s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
 
+    if (s->sources) {
+        if (parse_source_list(s->sources, include_sources,
+                              &num_include_sources,
+                              FF_ARRAY_ELEMS(include_sources)))
+            goto fail;
+    }
+
+    if (s->block) {
+        if (parse_source_list(s->block, exclude_sources, &num_exclude_sources,
+                              FF_ARRAY_ELEMS(exclude_sources)))
+            goto fail;
+    }
+
+    if (s->pkt_size)
+        h->max_packet_size = s->pkt_size;
+
     p = strchr(uri, '?');
     if (p) {
         if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
@@ -581,7 +602,6 @@
             /* assume if no digits were found it is a request to enable it */
             if (buf == endptr)
                 s->reuse_socket = 1;
-            reuse_specified = 1;
         }
         if (av_find_info_tag(buf, sizeof(buf), "overrun_nonfatal", p)) {
             char *endptr = NULL;
@@ -604,7 +624,7 @@
             s->local_port = strtol(buf, NULL, 10);
         }
         if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
-            s->packet_size = strtol(buf, NULL, 10);
+            s->pkt_size = strtol(buf, NULL, 10);
         }
         if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
             s->buffer_size = strtol(buf, NULL, 10);
@@ -643,7 +663,7 @@
     /* handling needed to support options picking from both AVOption and URL */
     s->circular_buffer_size *= 188;
     if (flags & AVIO_FLAG_WRITE) {
-        h->max_packet_size = s->packet_size;
+        h->max_packet_size = s->pkt_size;
     } else {
         h->max_packet_size = UDP_MAX_PKT_SIZE;
     }
@@ -662,9 +682,13 @@
             goto fail;
     }
 
-    if ((s->is_multicast || !s->local_port) && (h->flags & AVIO_FLAG_READ))
+    if ((s->is_multicast || s->local_port <= 0) && (h->flags & AVIO_FLAG_READ))
         s->local_port = port;
-    udp_fd = udp_socket_create(s, &my_addr, &len, localaddr[0] ? localaddr : s->local_addr);
+
+    if (localaddr[0])
+        udp_fd = udp_socket_create(s, &my_addr, &len, localaddr);
+    else
+        udp_fd = udp_socket_create(s, &my_addr, &len, s->localaddr);
     if (udp_fd < 0)
         goto fail;
 
@@ -673,7 +697,7 @@
     /* Follow the requested reuse option, unless it's multicast in which
      * case enable reuse unless explicitly disabled.
      */
-    if (s->reuse_socket || (s->is_multicast && !reuse_specified)) {
+    if (s->reuse_socket > 0 || (s->is_multicast && s->reuse_socket < 0)) {
         s->reuse_socket = 1;
         if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
             goto fail;
@@ -951,7 +975,7 @@
     .url_close           = udp_close,
     .url_get_file_handle = udp_get_file_handle,
     .priv_data_size      = sizeof(UDPContext),
-    .priv_data_class     = &udp_context_class,
+    .priv_data_class     = &udp_class,
     .flags               = URL_PROTOCOL_FLAG_NETWORK,
 };
 
diff --git a/libavformat/utils.c b/libavformat/utils.c
index f6df49b..6eec7a1 100644
--- a/libavformat/utils.c
+++ b/libavformat/utils.c
@@ -19,8 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#undef NDEBUG
-#include <assert.h>
 #include <stdarg.h>
 #include <stdint.h>
 
@@ -321,8 +319,8 @@
             return err;
     }
 
-    if (ic->pb && !ic->data_offset)
-        ic->data_offset = avio_tell(ic->pb);
+    if (ic->pb && !ic->internal->data_offset)
+        ic->internal->data_offset = avio_tell(ic->pb);
 
     return 0;
 }
@@ -394,8 +392,8 @@
             if (!copy.buf)
                 return AVERROR(ENOMEM);
 
-            add_to_pktbuf(&s->raw_packet_buffer, &copy,
-                          &s->raw_packet_buffer_end);
+            add_to_pktbuf(&s->internal->raw_packet_buffer, &copy,
+                          &s->internal->raw_packet_buffer_end);
         }
     return 0;
 }
@@ -481,10 +479,10 @@
     if ((ret = avformat_queue_attached_pictures(s)) < 0)
         goto fail;
 
-    if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->pb && !s->data_offset)
-        s->data_offset = avio_tell(s->pb);
+    if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->pb && !s->internal->data_offset)
+        s->internal->data_offset = avio_tell(s->pb);
 
-    s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
+    s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
 
     if (options) {
         av_dict_free(options);
@@ -552,7 +550,7 @@
             }
         }
 
-        end=    s->raw_packet_buffer_remaining_size <= 0
+        end=    s->internal->raw_packet_buffer_remaining_size <= 0
                 || st->probe_packets<= 0;
 
         if (end || av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
@@ -645,17 +643,17 @@
     AVStream *st;
 
     for (;;) {
-        AVPacketList *pktl = s->raw_packet_buffer;
+        AVPacketList *pktl = s->internal->raw_packet_buffer;
 
         if (pktl) {
             *pkt = pktl->pkt;
             st   = s->streams[pkt->stream_index];
-            if (s->raw_packet_buffer_remaining_size <= 0)
+            if (s->internal->raw_packet_buffer_remaining_size <= 0)
                 if ((err = probe_codec(s, st, NULL)) < 0)
                     return err;
             if (st->request_probe <= 0) {
-                s->raw_packet_buffer                 = pktl->next;
-                s->raw_packet_buffer_remaining_size += pkt->size;
+                s->internal->raw_packet_buffer                 = pktl->next;
+                s->internal->raw_packet_buffer_remaining_size += pkt->size;
                 av_free(pktl);
                 return 0;
             }
@@ -716,8 +714,9 @@
         if (!pktl && st->request_probe <= 0)
             return ret;
 
-        add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
-        s->raw_packet_buffer_remaining_size -= pkt->size;
+        add_to_pktbuf(&s->internal->raw_packet_buffer, pkt,
+                      &s->internal->raw_packet_buffer_end);
+        s->internal->raw_packet_buffer_remaining_size -= pkt->size;
 
         if ((err = probe_codec(s, st, pkt)) < 0)
             return err;
@@ -829,8 +828,8 @@
 {
     if (pktl->next)
         return pktl->next;
-    if (pktl == s->packet_buffer_end)
-        return s->parse_queue;
+    if (pktl == s->internal->packet_buffer_end)
+        return s->internal->parse_queue;
     return NULL;
 }
 
@@ -880,7 +879,7 @@
                                       int64_t dts, int64_t pts, AVPacket *pkt)
 {
     AVStream *st       = s->streams[stream_index];
-    AVPacketList *pktl = s->packet_buffer ? s->packet_buffer : s->parse_queue;
+    AVPacketList *pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
     int64_t pts_buffer[MAX_REORDER_DELAY+1];
     int64_t shift;
     int i, delay;
@@ -930,7 +929,7 @@
 static void update_initial_durations(AVFormatContext *s, AVStream *st,
                                      int stream_index, int duration)
 {
-    AVPacketList *pktl = s->packet_buffer ? s->packet_buffer : s->parse_queue;
+    AVPacketList *pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
     int64_t cur_dts    = RELATIVE_TS_BASE;
 
     if (st->first_dts != AV_NOPTS_VALUE) {
@@ -956,7 +955,7 @@
             av_log(s, AV_LOG_DEBUG, "first_dts %s but no packet with dts in the queue\n", av_ts2str(st->first_dts));
             return;
         }
-        pktl          = s->packet_buffer ? s->packet_buffer : s->parse_queue;
+        pktl          = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
         st->first_dts = cur_dts;
     } else if (st->cur_dts != RELATIVE_TS_BASE)
         return;
@@ -1066,7 +1065,7 @@
         }
     }
 
-    if (pkt->duration != 0 && (s->packet_buffer || s->parse_queue))
+    if (pkt->duration != 0 && (s->internal->packet_buffer || s->internal->parse_queue))
         update_initial_durations(s, st, pkt->stream_index, pkt->duration);
 
     /* Correct timestamps with byte offset if demuxers only have timestamps
@@ -1266,7 +1265,7 @@
         if ((ret = av_dup_packet(&out_pkt)) < 0)
             goto fail;
 
-        if (!add_to_pktbuf(&s->parse_queue, &out_pkt, &s->parse_queue_end)) {
+        if (!add_to_pktbuf(&s->internal->parse_queue, &out_pkt, &s->internal->parse_queue_end)) {
             av_free_packet(&out_pkt);
             ret = AVERROR(ENOMEM);
             goto fail;
@@ -1311,7 +1310,7 @@
 
     av_init_packet(pkt);
 
-    while (!got_packet && !s->parse_queue) {
+    while (!got_packet && !s->internal->parse_queue) {
         AVStream *st;
         AVPacket cur_pkt;
 
@@ -1396,8 +1395,8 @@
         }
     }
 
-    if (!got_packet && s->parse_queue)
-        ret = read_from_packet_buffer(&s->parse_queue, &s->parse_queue_end, pkt);
+    if (!got_packet && s->internal->parse_queue)
+        ret = read_from_packet_buffer(&s->internal->parse_queue, &s->internal->parse_queue_end, pkt);
 
     if (ret >= 0) {
         AVStream *st = s->streams[pkt->stream_index];
@@ -1472,9 +1471,9 @@
     AVStream *st;
 
     if (!genpts) {
-        ret = s->packet_buffer
-              ? read_from_packet_buffer(&s->packet_buffer,
-                                        &s->packet_buffer_end, pkt)
+        ret = s->internal->packet_buffer
+              ? read_from_packet_buffer(&s->internal->packet_buffer,
+                                        &s->internal->packet_buffer_end, pkt)
               : read_frame_internal(s, pkt);
         if (ret < 0)
             return ret;
@@ -1482,7 +1481,7 @@
     }
 
     for (;;) {
-        AVPacketList *pktl = s->packet_buffer;
+        AVPacketList *pktl = s->internal->packet_buffer;
 
         if (pktl) {
             AVPacket *next_pkt = &pktl->pkt;
@@ -1514,15 +1513,15 @@
                     // 3. the packets for this stream at the end of the files had valid dts.
                     next_pkt->pts = last_dts + next_pkt->duration;
                 }
-                pktl = s->packet_buffer;
+                pktl = s->internal->packet_buffer;
             }
 
             /* read packet from packet buffer, if there is data */
             st = s->streams[next_pkt->stream_index];
             if (!(next_pkt->pts == AV_NOPTS_VALUE && st->discard < AVDISCARD_ALL &&
                   next_pkt->dts != AV_NOPTS_VALUE && !eof)) {
-                ret = read_from_packet_buffer(&s->packet_buffer,
-                                               &s->packet_buffer_end, pkt);
+                ret = read_from_packet_buffer(&s->internal->packet_buffer,
+                                               &s->internal->packet_buffer_end, pkt);
                 goto return_packet;
             }
         }
@@ -1536,8 +1535,8 @@
                 return ret;
         }
 
-        if (av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
-                                        &s->packet_buffer_end)) < 0)
+        if (av_dup_packet(add_to_pktbuf(&s->internal->packet_buffer, pkt,
+                                        &s->internal->packet_buffer_end)) < 0)
             return AVERROR(ENOMEM);
     }
 
@@ -1560,11 +1559,13 @@
 /* XXX: suppress the packet queue */
 static void flush_packet_queue(AVFormatContext *s)
 {
-    free_packet_buffer(&s->parse_queue,       &s->parse_queue_end);
-    free_packet_buffer(&s->packet_buffer,     &s->packet_buffer_end);
-    free_packet_buffer(&s->raw_packet_buffer, &s->raw_packet_buffer_end);
+    if (!s->internal)
+        return;
+    free_packet_buffer(&s->internal->parse_queue,       &s->internal->parse_queue_end);
+    free_packet_buffer(&s->internal->packet_buffer,     &s->internal->packet_buffer_end);
+    free_packet_buffer(&s->internal->raw_packet_buffer, &s->internal->raw_packet_buffer_end);
 
-    s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
+    s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
 }
 
 /*******************************************************/
@@ -1902,7 +1903,7 @@
     av_dlog(s, "gen_seek: %d %s\n", stream_index, av_ts2str(target_ts));
 
     if (ts_min == AV_NOPTS_VALUE) {
-        pos_min = s->data_offset;
+        pos_min = s->internal->data_offset;
         ts_min  = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
         if (ts_min == AV_NOPTS_VALUE)
             return -1;
@@ -1998,7 +1999,7 @@
 {
     int64_t pos_min, pos_max;
 
-    pos_min = s->data_offset;
+    pos_min = s->internal->data_offset;
     pos_max = avio_size(s->pb) - 1;
 
     if (pos < pos_min)
@@ -2040,7 +2041,7 @@
                 return ret;
             ff_update_cur_dts(s, st, ie->timestamp);
         } else {
-            if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
+            if ((ret = avio_seek(s->pb, s->internal->data_offset, SEEK_SET)) < 0)
                 return ret;
         }
         for (;;) {
@@ -2200,6 +2201,12 @@
     return -1; //unreachable
 }
 
+int avformat_flush(AVFormatContext *s)
+{
+    ff_read_frame_flush(s);
+    return 0;
+}
+
 /*******************************************************/
 
 /**
@@ -2349,8 +2356,8 @@
     if (ic->duration == AV_NOPTS_VALUE &&
         ic->bit_rate != 0) {
         filesize = ic->pb ? avio_size(ic->pb) : 0;
-        if (filesize > ic->data_offset) {
-            filesize -= ic->data_offset;
+        if (filesize > ic->internal->data_offset) {
+            filesize -= ic->internal->data_offset;
             for (i = 0; i < ic->nb_streams; i++) {
                 st      = ic->streams[i];
                 if (   st->time_base.num <= INT64_MAX / ic->bit_rate
@@ -2827,8 +2834,8 @@
  * And there are "variable" fps files this needs to detect as well. */
 static int tb_unreliable(AVCodecContext *c)
 {
-    if (c->time_base.den >= 101L * c->time_base.num ||
-        c->time_base.den <    5L * c->time_base.num ||
+    if (c->time_base.den >= 101LL * c->time_base.num ||
+        c->time_base.den <    5LL * c->time_base.num ||
         // c->codec_tag == AV_RL32("DIVX") ||
         // c->codec_tag == AV_RL32("XVID") ||
         c->codec_tag == AV_RL32("mp4v") ||
@@ -3180,10 +3187,11 @@
         }
 
         if (ic->flags & AVFMT_FLAG_NOBUFFER)
-            free_packet_buffer(&ic->packet_buffer, &ic->packet_buffer_end);
+            free_packet_buffer(&ic->internal->packet_buffer,
+                               &ic->internal->packet_buffer_end);
         {
-            pkt = add_to_pktbuf(&ic->packet_buffer, &pkt1,
-                                &ic->packet_buffer_end);
+            pkt = add_to_pktbuf(&ic->internal->packet_buffer, &pkt1,
+                                &ic->internal->packet_buffer_end);
             if (!pkt) {
                 ret = AVERROR(ENOMEM);
                 goto find_stream_info_err;
@@ -3829,6 +3837,8 @@
                 if (percentd_found)
                     goto fail;
                 percentd_found = 1;
+                if (number < 0)
+                    nd += 1;
                 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
                 len = strlen(buf1);
                 if ((q - buf + len) > buf_size - 1)
@@ -4097,7 +4107,8 @@
     ff_network_inited_globally = 1;
     if ((ret = ff_network_init()) < 0)
         return ret;
-    ff_tls_init();
+    if ((ret = ff_tls_init()) < 0)
+        return ret;
 #endif
     return 0;
 }
@@ -4189,8 +4200,8 @@
 
 
     if (st->codec->ticks_per_frame > 1) {
-        if (   codec_fr.num > 0 && codec_fr.den > 0 && av_q2d(codec_fr) < av_q2d(fr)*0.7
-            && fabs(1.0 - av_q2d(av_div_q(avg_fr, fr))) > 0.1)
+        if (   codec_fr.num > 0 && codec_fr.den > 0 &&
+            (fr.num == 0 || av_q2d(codec_fr) < av_q2d(fr)*0.7 && fabs(1.0 - av_q2d(av_div_q(avg_fr, fr))) > 0.1))
             fr = codec_fr;
     }
 
@@ -4276,6 +4287,28 @@
 
         av_freep(&key);
         return ret;
+    } else if (*spec == 'u') {
+        AVCodecContext *avctx = st->codec;
+        int val;
+        switch (avctx->codec_type) {
+        case AVMEDIA_TYPE_AUDIO:
+            val = avctx->sample_rate && avctx->channels;
+            if (avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
+                return 0;
+            break;
+        case AVMEDIA_TYPE_VIDEO:
+            val = avctx->width && avctx->height;
+            if (avctx->pix_fmt == AV_PIX_FMT_NONE)
+                return 0;
+            break;
+        case AVMEDIA_TYPE_UNKNOWN:
+            val = 0;
+            break;
+        default:
+            val = 1;
+            break;
+        }
+        return avctx->codec_id != AV_CODEC_ID_NONE && val != 0;
     } else if (!*spec) /* empty specifier, matches everything */
         return 1;
 
@@ -4312,7 +4345,7 @@
         0x11, 0x12, 0x08, 0xc6, 0x8c, 0x04, 0x41, 0x28,
         0x4c, 0x34, 0xf0, 0x1e, 0x01, 0x13, 0xf2, 0xe0,
         0x3c, 0x60, 0x20, 0x20, 0x28, 0x00, 0x00, 0x03,
-        0x00, 0x08, 0x00, 0x00, 0x03, 0x01, 0x94, 0x00,
+        0x00, 0x08, 0x00, 0x00, 0x03, 0x01, 0x94, 0x20,
         // PPS
         0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
         0xd0
diff --git a/libavformat/version.h b/libavformat/version.h
index 9a38df9..a183d7f 100644
--- a/libavformat/version.h
+++ b/libavformat/version.h
@@ -30,8 +30,8 @@
 #include "libavutil/version.h"
 
 #define LIBAVFORMAT_VERSION_MAJOR 56
-#define LIBAVFORMAT_VERSION_MINOR  19
-#define LIBAVFORMAT_VERSION_MICRO 100
+#define LIBAVFORMAT_VERSION_MINOR  26
+#define LIBAVFORMAT_VERSION_MICRO 101
 
 #define LIBAVFORMAT_VERSION_INT AV_VERSION_INT(LIBAVFORMAT_VERSION_MAJOR, \
                                                LIBAVFORMAT_VERSION_MINOR, \
diff --git a/libavformat/vqf.c b/libavformat/vqf.c
index 15e8246..29c726d 100644
--- a/libavformat/vqf.c
+++ b/libavformat/vqf.c
@@ -261,7 +261,7 @@
 {
     VqfContext *c = s->priv_data;
     AVStream *st;
-    int ret;
+    int64_t ret;
     int64_t pos;
 
     st = s->streams[stream_index];
@@ -275,7 +275,7 @@
     st->cur_dts = av_rescale(pos, st->time_base.den,
                              st->codec->bit_rate * (int64_t)st->time_base.num);
 
-    if ((ret = avio_seek(s->pb, ((pos-7) >> 3) + s->data_offset, SEEK_SET)) < 0)
+    if ((ret = avio_seek(s->pb, ((pos-7) >> 3) + s->internal->data_offset, SEEK_SET)) < 0)
         return ret;
 
     c->remaining_bits = -7 - ((pos-7)&7);
diff --git a/libavformat/wtvdec.c b/libavformat/wtvdec.c
index f200300..e226690 100644
--- a/libavformat/wtvdec.c
+++ b/libavformat/wtvdec.c
@@ -49,7 +49,7 @@
  *
  */
 
-typedef struct {
+typedef struct WtvFile {
     AVIOContext *pb_filesystem;  /**< file system (AVFormatContext->pb) */
 
     int sector_bits;     /**< sector shift bits; used to convert sector number into pb_filesystem offset */
@@ -316,11 +316,11 @@
  *
  */
 
-typedef struct {
+typedef struct WtvStream {
     int seen_data;
 } WtvStream;
 
-typedef struct {
+typedef struct WtvContext {
     AVIOContext *pb;       /**< timeline file */
     int64_t epoch;
     int64_t pts;             /**< pts for next data chunk */
@@ -767,7 +767,7 @@
     int i;
     for (i = 0; i < wtv->nb_index_entries; i++) {
         if (wtv->index_entries[i].pos > broken_pos) {
-            int ret = avio_seek(pb, wtv->index_entries[i].pos, SEEK_SET);
+            int64_t ret = avio_seek(pb, wtv->index_entries[i].pos, SEEK_SET);
             if (ret < 0)
                 return ret;
             wtv->pts = wtv->index_entries[i].timestamp;
@@ -965,7 +965,7 @@
     uint8_t root[WTV_SECTOR_SIZE];
     AVIOContext *pb;
     int64_t timeline_pos;
-    int ret;
+    int64_t ret;
 
     wtv->epoch          =
     wtv->pts            =
diff --git a/libavformat/wtvenc.c b/libavformat/wtvenc.c
index 634545d..e8a2b72 100644
--- a/libavformat/wtvenc.c
+++ b/libavformat/wtvenc.c
@@ -265,12 +265,12 @@
     int hdr_size = 0;
 
     if (st->codec->codec_type  == AVMEDIA_TYPE_VIDEO) {
-        g = get_codec_guid(st->codec->codec_id, ff_video_guids);
+        g = ff_get_codec_guid(st->codec->codec_id, ff_video_guids);
         media_type = &ff_mediatype_video;
         format_type = st->codec->codec_id == AV_CODEC_ID_MPEG2VIDEO ? &ff_format_mpeg2_video : &ff_format_videoinfo2;
         tags = ff_codec_bmp_tags;
     } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
-        g = get_codec_guid(st->codec->codec_id, ff_codec_wav_guids);
+        g = ff_get_codec_guid(st->codec->codec_id, ff_codec_wav_guids);
         media_type = &ff_mediatype_audio;
         format_type = &ff_format_waveformatex;
         tags = ff_codec_wav_tags;
diff --git a/libavformat/wvdec.c b/libavformat/wvdec.c
index 76768cd..4e58512 100644
--- a/libavformat/wvdec.c
+++ b/libavformat/wvdec.c
@@ -47,7 +47,7 @@
     32000, 44100, 48000, 64000, 88200, 96000, 192000,    -1
 };
 
-typedef struct {
+typedef struct WVContext {
     uint8_t block_header[WV_HEADER_SIZE];
     WvHeader header;
     int rate, chan, bpp;
diff --git a/libavformat/xwma.c b/libavformat/xwma.c
index b172120..075a85a 100644
--- a/libavformat/xwma.c
+++ b/libavformat/xwma.c
@@ -30,7 +30,7 @@
  * Demuxer for xWMA, a Microsoft audio container used by XAudio 2.
  */
 
-typedef struct {
+typedef struct XWMAContext {
     int64_t data_end;
 } XWMAContext;
 
diff --git a/libavformat/yop.c b/libavformat/yop.c
index 07086d5..81b3cc2 100644
--- a/libavformat/yop.c
+++ b/libavformat/yop.c
@@ -199,7 +199,7 @@
     if (!stream_index)
         return -1;
 
-    pos_min        = s->data_offset;
+    pos_min        = s->internal->data_offset;
     pos_max        = avio_size(s->pb) - yop->frame_size;
     frame_count    = (pos_max - pos_min) / yop->frame_size;
 
diff --git a/libavformat/yuv4mpegdec.c b/libavformat/yuv4mpegdec.c
index 6d94a59..7613c3c 100644
--- a/libavformat/yuv4mpegdec.c
+++ b/libavformat/yuv4mpegdec.c
@@ -38,8 +38,8 @@
         rated =  0, aspectn =  0, aspectd = 0;
     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;
     enum AVFieldOrder field_order = AV_FIELD_UNKNOWN;
+    AVStream *st;
 
     for (i = 0; i < MAX_YUV4_HEADER; i++) {
         header[i] = avio_r8(pb);
diff --git a/libavresample/aarch64/resample_init.c b/libavresample/aarch64/resample_init.c
index d3dfb12..e21c600 100644
--- a/libavresample/aarch64/resample_init.c
+++ b/libavresample/aarch64/resample_init.c
@@ -45,8 +45,8 @@
                               int dst_index, const void *src0,
                               unsigned int index, int frac);
 
-void ff_audio_resample_init_aarch64(ResampleContext *c,
-                                    enum AVSampleFormat sample_fmt)
+av_cold void ff_audio_resample_init_aarch64(ResampleContext *c,
+                                            enum AVSampleFormat sample_fmt)
 {
     int cpu_flags = av_get_cpu_flags();
 
diff --git a/libavresample/arm/Makefile b/libavresample/arm/Makefile
index 60f3f6d..affc2bf 100644
--- a/libavresample/arm/Makefile
+++ b/libavresample/arm/Makefile
@@ -1,5 +1,7 @@
-OBJS      += arm/audio_convert_init.o
+OBJS      += arm/audio_convert_init.o \
+             arm/resample_init.o
 
 OBJS-$(CONFIG_NEON_CLOBBER_TEST) += arm/neontest.o
 
-NEON-OBJS += arm/audio_convert_neon.o
+NEON-OBJS += arm/audio_convert_neon.o \
+             arm/resample_neon.o
diff --git a/libavresample/arm/asm-offsets.h b/libavresample/arm/asm-offsets.h
new file mode 100644
index 0000000..4d3d116
--- /dev/null
+++ b/libavresample/arm/asm-offsets.h
@@ -0,0 +1,29 @@
+/*
+ * 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 AVRESAMPLE_ARM_ASM_OFFSETS_H
+#define AVRESAMPLE_ARM_ASM_OFFSETS_H
+
+/* struct ResampleContext */
+#define FILTER_BANK                     0x08
+#define FILTER_LENGTH                   0x0c
+#define SRC_INCR                        0x20
+#define PHASE_SHIFT                     0x28
+#define PHASE_MASK                      (PHASE_SHIFT + 0x04)
+
+#endif /* AVRESAMPLE_ARM_ASM_OFFSETS_H */
diff --git a/libavresample/arm/resample_init.c b/libavresample/arm/resample_init.c
new file mode 100644
index 0000000..10af09c
--- /dev/null
+++ b/libavresample/arm/resample_init.c
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2014 Peter Meerwald <pmeerw@pmeerw.net>
+ *
+ * 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"
+
+#include "libavutil/cpu.h"
+#include "libavutil/arm/cpu.h"
+#include "libavutil/internal.h"
+#include "libavutil/samplefmt.h"
+
+#include "libavresample/resample.h"
+
+#include "asm-offsets.h"
+
+AV_CHECK_OFFSET(struct ResampleContext, filter_bank,   FILTER_BANK);
+AV_CHECK_OFFSET(struct ResampleContext, filter_length, FILTER_LENGTH);
+AV_CHECK_OFFSET(struct ResampleContext, src_incr,      SRC_INCR);
+AV_CHECK_OFFSET(struct ResampleContext, phase_shift,   PHASE_SHIFT);
+AV_CHECK_OFFSET(struct ResampleContext, phase_mask,    PHASE_MASK);
+
+void ff_resample_one_flt_neon(struct ResampleContext *c, void *dst0,
+                              int dst_index, const void *src0,
+                              unsigned int index, int frac);
+void ff_resample_one_s16_neon(struct ResampleContext *c, void *dst0,
+                              int dst_index, const void *src0,
+                              unsigned int index, int frac);
+void ff_resample_one_s32_neon(struct ResampleContext *c, void *dst0,
+                              int dst_index, const void *src0,
+                              unsigned int index, int frac);
+
+void ff_resample_linear_flt_neon(struct ResampleContext *c, void *dst0,
+                                 int dst_index, const void *src0,
+                                 unsigned int index, int frac);
+
+av_cold void ff_audio_resample_init_arm(ResampleContext *c,
+                                        enum AVSampleFormat sample_fmt)
+{
+    int cpu_flags = av_get_cpu_flags();
+    if (have_neon(cpu_flags)) {
+        switch (sample_fmt) {
+        case AV_SAMPLE_FMT_FLTP:
+            if (c->linear)
+                c->resample_one = ff_resample_linear_flt_neon;
+            else
+                c->resample_one = ff_resample_one_flt_neon;
+            break;
+        case AV_SAMPLE_FMT_S16P:
+            if (!c->linear)
+                c->resample_one = ff_resample_one_s16_neon;
+            break;
+        case AV_SAMPLE_FMT_S32P:
+            if (!c->linear)
+                c->resample_one = ff_resample_one_s32_neon;
+            break;
+        }
+    }
+}
diff --git a/libavresample/arm/resample_neon.S b/libavresample/arm/resample_neon.S
new file mode 100644
index 0000000..7ee8497
--- /dev/null
+++ b/libavresample/arm/resample_neon.S
@@ -0,0 +1,358 @@
+/*
+ * Copyright (c) 2014 Peter Meerwald <pmeerw@pmeerw.net>
+ *
+ * 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/arm/asm.S"
+
+#include "asm-offsets.h"
+
+.macro resample_one     fmt, es=2
+function ff_resample_one_\fmt\()_neon, export=1
+        push            {r4, r5}
+        add             r1, r1, r2, lsl #\es
+
+        ldr             r2, [r0, #PHASE_SHIFT+4] /* phase_mask */
+        ldr             ip, [sp, #8] /* index */
+        ldr             r5, [r0, #FILTER_LENGTH]
+        and             r2, ip, r2 /* (index & phase_mask) */
+        ldr             r4, [r0, #PHASE_SHIFT]
+        lsr             r4, ip, r4 /* compute sample_index */
+        mul             r2, r2, r5
+
+        ldr             ip, [r0, #FILTER_BANK]
+        add             r3, r3, r4, lsl #\es /* &src[sample_index] */
+
+        cmp             r5, #8
+        add             r0, ip, r2, lsl #\es /* filter = &filter_bank[...] */
+
+        blt             5f
+8:
+        subs            r5, r5, #8
+        LOAD4
+        MUL4
+7:
+        LOAD4
+        beq             6f
+        cmp             r5, #8
+        MLA4
+        blt             4f
+        subs            r5, r5, #8
+        LOAD4
+        MLA4
+        b               7b
+6:
+        MLA4
+        STORE
+        pop             {r4, r5}
+        bx              lr
+5:
+        INIT4
+4:      /* remaining filter_length 1 to 7 */
+        cmp             r5, #4
+        blt             2f
+        subs            r5, r5, #4
+        LOAD4
+        MLA4
+        beq             0f
+2:      /* remaining filter_length 1 to 3 */
+        cmp             r5, #2
+        blt             1f
+        subs            r5, r5, #2
+        LOAD2
+        MLA2
+        beq             0f
+1:      /* remaining filter_length 1 */
+        LOAD1
+        MLA1
+0:
+        STORE
+        pop             {r4, r5}
+        bx              lr
+endfunc
+
+.purgem LOAD1
+.purgem LOAD2
+.purgem LOAD4
+.purgem MLA1
+.purgem MLA2
+.purgem MLA4
+.purgem MUL4
+.purgem INIT4
+.purgem STORE
+.endm
+
+
+/* float32 */
+.macro  LOAD1
+        veor.32         d0, d0
+        vld1.32         {d0[0]}, [r0]! /* load filter */
+        vld1.32         {d4[0]}, [r3]! /* load src */
+.endm
+.macro  LOAD2
+        vld1.32         {d0}, [r0]! /* load filter */
+        vld1.32         {d4}, [r3]! /* load src */
+.endm
+.macro  LOAD4
+        vld1.32         {d0,d1}, [r0]! /* load filter */
+        vld1.32         {d4,d5}, [r3]! /* load src */
+.endm
+.macro  MLA1
+        vmla.f32        d16, d0, d4[0]
+.endm
+.macro  MLA2
+        vmla.f32        d16, d0, d4
+.endm
+.macro  MLA4
+        vmla.f32        d16, d0, d4
+        vmla.f32        d17, d1, d5
+.endm
+.macro  MUL4
+        vmul.f32        d16, d0, d4
+        vmul.f32        d17, d1, d5
+.endm
+.macro  INIT4
+        veor.f32        q8, q8
+.endm
+.macro  STORE
+        vpadd.f32       d16, d16, d17
+        vpadd.f32       d16, d16, d16
+        vst1.32         d16[0], [r1]
+.endm
+
+resample_one flt, 2
+
+
+/* s32 */
+.macro  LOAD1
+        veor.32         d0, d0
+        vld1.32         {d0[0]}, [r0]! /* load filter */
+        vld1.32         {d4[0]}, [r3]! /* load src */
+.endm
+.macro  LOAD2
+        vld1.32         {d0}, [r0]! /* load filter */
+        vld1.32         {d4}, [r3]! /* load src */
+.endm
+.macro  LOAD4
+        vld1.32         {d0,d1}, [r0]! /* load filter */
+        vld1.32         {d4,d5}, [r3]! /* load src */
+.endm
+.macro  MLA1
+        vmlal.s32       q8, d0, d4[0]
+.endm
+.macro  MLA2
+        vmlal.s32       q8, d0, d4
+.endm
+.macro  MLA4
+        vmlal.s32       q8, d0, d4
+        vmlal.s32       q9, d1, d5
+.endm
+.macro  MUL4
+        vmull.s32       q8, d0, d4
+        vmull.s32       q9, d1, d5
+.endm
+.macro  INIT4
+        veor.s64        q8, q8
+        veor.s64        q9, q9
+.endm
+.macro  STORE
+        vadd.s64        q8, q8, q9
+        vadd.s64        d16, d16, d17
+        vqrshrn.s64     d16, q8, #30
+        vst1.32         d16[0], [r1]
+.endm
+
+resample_one s32, 2
+
+
+/* s16 */
+.macro  LOAD1
+        veor.16         d0, d0
+        vld1.16         {d0[0]}, [r0]! /* load filter */
+        vld1.16         {d4[0]}, [r3]! /* load src */
+.endm
+.macro  LOAD2
+        veor.16         d0, d0
+        vld1.32         {d0[0]}, [r0]! /* load filter */
+        veor.16         d4, d4
+        vld1.32         {d4[0]}, [r3]! /* load src */
+.endm
+.macro  LOAD4
+        vld1.16         {d0}, [r0]! /* load filter */
+        vld1.16         {d4}, [r3]! /* load src */
+.endm
+.macro  MLA1
+        vmlal.s16       q8, d0, d4[0]
+.endm
+.macro  MLA2
+        vmlal.s16       q8, d0, d4
+.endm
+.macro  MLA4
+        vmlal.s16       q8, d0, d4
+.endm
+.macro  MUL4
+        vmull.s16       q8, d0, d4
+.endm
+.macro  INIT4
+        veor.s32        q8, q8
+.endm
+.macro  STORE
+        vpadd.s32       d16, d16, d17
+        vpadd.s32       d16, d16, d16
+        vqrshrn.s32     d16, q8, #15
+        vst1.16         d16[0], [r1]
+.endm
+
+resample_one s16, 1
+
+
+.macro resample_linear  fmt, es=2
+function ff_resample_linear_\fmt\()_neon, export=1
+        push            {r4, r5}
+        add             r1, r1, r2, lsl #\es
+
+        ldr             r2, [r0, #PHASE_SHIFT+4] /* phase_mask */
+        ldr             ip, [sp, #8] /* index */
+        ldr             r5, [r0, #FILTER_LENGTH]
+        and             r2, ip, r2 /* (index & phase_mask) */
+        ldr             r4, [r0, #PHASE_SHIFT]
+        lsr             r4, ip, r4 /* compute sample_index */
+        mul             r2, r2, r5
+
+        ldr             ip, [r0, #FILTER_BANK]
+        add             r3, r3, r4, lsl #\es /* &src[sample_index] */
+
+        cmp             r5, #8
+        ldr             r4, [r0, #SRC_INCR]
+        add             r0, ip, r2, lsl #\es /* filter = &filter_bank[...] */
+        add             r2, r0, r5, lsl #\es /* filter[... + c->filter_length] */
+
+        blt             5f
+8:
+        subs            r5, r5, #8
+        LOAD4
+        MUL4
+7:
+        LOAD4
+        beq             6f
+        cmp             r5, #8
+        MLA4
+        blt             4f
+        subs            r5, r5, #8
+        LOAD4
+        MLA4
+        b               7b
+6:
+        MLA4
+        STORE
+        pop             {r4, r5}
+        bx              lr
+5:
+        INIT4
+4:      /* remaining filter_length 1 to 7 */
+        cmp             r5, #4
+        blt             2f
+        subs            r5, r5, #4
+        LOAD4
+        MLA4
+        beq             0f
+2:      /* remaining filter_length 1 to 3 */
+        cmp             r5, #2
+        blt             1f
+        subs            r5, r5, #2
+        LOAD2
+        MLA2
+        beq             0f
+1:      /* remaining filter_length 1 */
+        LOAD1
+        MLA1
+0:
+        STORE
+        pop             {r4, r5}
+        bx              lr
+endfunc
+
+.purgem LOAD1
+.purgem LOAD2
+.purgem LOAD4
+.purgem MLA1
+.purgem MLA2
+.purgem MLA4
+.purgem MUL4
+.purgem INIT4
+.purgem STORE
+.endm
+
+
+/* float32 linear */
+.macro  LOAD1
+        veor.32         d0, d0
+        veor.32         d2, d2
+        vld1.32         {d0[0]}, [r0]! /* load filter */
+        vld1.32         {d2[0]}, [r2]! /* load filter */
+        vld1.32         {d4[0]}, [r3]! /* load src */
+.endm
+.macro  LOAD2
+        vld1.32         {d0}, [r0]! /* load filter */
+        vld1.32         {d2}, [r2]! /* load filter */
+        vld1.32         {d4}, [r3]! /* load src */
+.endm
+.macro  LOAD4
+        vld1.32         {d0,d1}, [r0]! /* load filter */
+        vld1.32         {d2,d3}, [r2]! /* load filter */
+        vld1.32         {d4,d5}, [r3]! /* load src */
+.endm
+.macro  MLA1
+        vmla.f32        d18, d0, d4[0]
+        vmla.f32        d16, d2, d4[0]
+.endm
+.macro  MLA2
+        vmla.f32        d18, d0, d4
+        vmla.f32        d16, d2, d4
+.endm
+.macro  MLA4
+        vmla.f32        q9, q0, q2
+        vmla.f32        q8, q1, q2
+.endm
+.macro  MUL4
+        vmul.f32        q9, q0, q2
+        vmul.f32        q8, q1, q2
+.endm
+.macro  INIT4
+        veor.f32        q9, q9
+        veor.f32        q8, q8
+.endm
+.macro  STORE
+        vldr            s0, [sp, #12] /* frac */
+        vmov            s1, r4
+        vcvt.f32.s32    d0, d0
+
+        vsub.f32        q8, q8, q9 /* v2 - val */
+        vpadd.f32       d18, d18, d19
+        vpadd.f32       d16, d16, d17
+        vpadd.f32       d2, d18, d18
+        vpadd.f32       d1, d16, d16
+
+        vmul.f32        s2, s2, s0 /* (v2 - val) * frac */
+        vdiv.f32        s2, s2, s1 /* / c->src_incr */
+        vadd.f32        s4, s4, s2
+
+        vstr            s4, [r1]
+.endm
+
+resample_linear flt, 2
diff --git a/libavresample/internal.h b/libavresample/internal.h
index fe6bd8f..2fc3f6d 100644
--- a/libavresample/internal.h
+++ b/libavresample/internal.h
@@ -110,4 +110,7 @@
 
 void ff_audio_resample_init_aarch64(ResampleContext *c,
                                     enum AVSampleFormat sample_fmt);
+void ff_audio_resample_init_arm(ResampleContext *c,
+                                enum AVSampleFormat sample_fmt);
+
 #endif /* AVRESAMPLE_INTERNAL_H */
diff --git a/libavresample/resample.c b/libavresample/resample.c
index bdc74a2..4ae3075 100644
--- a/libavresample/resample.c
+++ b/libavresample/resample.c
@@ -172,6 +172,8 @@
 
     if (ARCH_AARCH64)
         ff_audio_resample_init_aarch64(c, avr->internal_sample_fmt);
+    if (ARCH_ARM)
+        ff_audio_resample_init_arm(c, avr->internal_sample_fmt);
 
     felem_size = av_get_bytes_per_sample(avr->internal_sample_fmt);
     c->filter_bank = av_mallocz(c->filter_length * (phase_count + 1) * felem_size);
diff --git a/libavutil/Makefile b/libavutil/Makefile
index 6caf896..df85cd1 100644
--- a/libavutil/Makefile
+++ b/libavutil/Makefile
@@ -88,6 +88,7 @@
        cast5.o                                                          \
        camellia.o                                                       \
        channel_layout.o                                                 \
+       color_utils.o                                                    \
        cpu.o                                                            \
        crc.o                                                            \
        des.o                                                            \
diff --git a/libavutil/aes.c b/libavutil/aes.c
index 9eb2bb3..fd87060 100644
--- a/libavutil/aes.c
+++ b/libavutil/aes.c
@@ -62,9 +62,9 @@
 #endif
 
 #if HAVE_BIGENDIAN
-#   define ROT(x, s) ((x >> s) | (x << (32-s)))
+#   define ROT(x, s) (((x) >> (s)) | ((x) << (32-(s))))
 #else
-#   define ROT(x, s) ((x << s) | (x >> (32-s)))
+#   define ROT(x, s) (((x) << (s)) | ((x) >> (32-(s))))
 #endif
 
 static inline void addkey(av_aes_block *dst, const av_aes_block *src,
diff --git a/libavutil/arm/asm.S b/libavutil/arm/asm.S
index 1d0e5a9..e9b0bca 100644
--- a/libavutil/arm/asm.S
+++ b/libavutil/arm/asm.S
@@ -49,11 +49,17 @@
 #elif HAVE_ARMV5TE
         .arch           armv5te
 #endif
+#if   HAVE_AS_OBJECT_ARCH
+ELF     .object_arch    armv4
+#endif
 
 #if   HAVE_NEON
         .fpu            neon
+ELF     .eabi_attribute 10, 0           @ suppress Tag_FP_arch
+ELF     .eabi_attribute 12, 0           @ suppress Tag_Advanced_SIMD_arch
 #elif HAVE_VFP
         .fpu            vfp
+ELF     .eabi_attribute 10, 0           @ suppress Tag_FP_arch
 #endif
 
         .syntax unified
diff --git a/libavutil/arm/intmath.h b/libavutil/arm/intmath.h
index faea5ea..77bcfd1 100644
--- a/libavutil/arm/intmath.h
+++ b/libavutil/arm/intmath.h
@@ -66,6 +66,16 @@
 TODO(dalecurtis): This causes compilation to fail if the function can't be
 inlined because the 2nd operand in usat must be an immediate.  So disable since
 av_always_inline doesn't seem to really mean always...
+TODO(watk): Upstream added av_clip_intp2_arm, which uses the similar ssat, so I
+commented it out too.
+
+#define av_clip_intp2 av_clip_intp2_arm
+static av_always_inline av_const int av_clip_intp2_arm(int a, int p)
+{
+    unsigned x;
+    __asm__ ("ssat %0, %2, %1" : "=r"(x) : "r"(a), "i"(p+1));
+    return x;
+}
 
 #define av_clip_uintp2 av_clip_uintp2_arm
 static av_always_inline av_const unsigned av_clip_uintp2_arm(int a, int p)
diff --git a/libavutil/attributes.h b/libavutil/attributes.h
index 7d3f4a9..ebcdd6b 100644
--- a/libavutil/attributes.h
+++ b/libavutil/attributes.h
@@ -27,7 +27,7 @@
 #define AVUTIL_ATTRIBUTES_H
 
 #ifdef __GNUC__
-#    define AV_GCC_VERSION_AT_LEAST(x,y) (__GNUC__ > x || __GNUC__ == x && __GNUC_MINOR__ >= y)
+#    define AV_GCC_VERSION_AT_LEAST(x,y) (__GNUC__ > (x) || __GNUC__ == (x) && __GNUC_MINOR__ >= (y))
 #else
 #    define AV_GCC_VERSION_AT_LEAST(x,y) 0
 #endif
diff --git a/libavutil/buffer.c b/libavutil/buffer.c
index ca102fd..bb112c2 100644
--- a/libavutil/buffer.c
+++ b/libavutil/buffer.c
@@ -159,8 +159,8 @@
         return AVERROR(ENOMEM);
 
     memcpy(newbuf->data, buf->data, buf->size);
-    av_buffer_unref(pbuf);
-    *pbuf = newbuf;
+
+    buffer_replace(pbuf, &newbuf);
 
     return 0;
 }
@@ -201,8 +201,7 @@
 
         memcpy(new->data, buf->data, FFMIN(size, buf->size));
 
-        av_buffer_unref(pbuf);
-        *pbuf = new;
+        buffer_replace(pbuf, &new);
         return 0;
     }
 
diff --git a/libavutil/camellia.c b/libavutil/camellia.c
index 7382414..483eed2 100644
--- a/libavutil/camellia.c
+++ b/libavutil/camellia.c
@@ -37,6 +37,8 @@
 #define Sigma5  0x10E527FADE682D1D
 #define Sigma6  0xB05688C2B3E6C1FD
 
+static uint64_t SP[8][256];
+
 typedef struct AVCAMELLIA {
     uint64_t Kw[4];
     uint64_t Ke[6];
@@ -140,17 +142,9 @@
 
 static uint64_t F(uint64_t F_IN, uint64_t KE)
 {
-    uint32_t Zl, Zr;
     KE ^= F_IN;
-    Zl = KE >> 32;
-    Zr = KE & MASK32;
-    Zl = (((uint32_t)SBOX1[(Zl >> 24)] << 24) | ((uint32_t)SBOX2[(Zl >> 16) & MASK8] << 16) | ((uint32_t)SBOX3[(Zl >> 8) & MASK8] << 8) |(SBOX4[Zl & MASK8]));
-    Zr = (((uint32_t)SBOX2[(Zr >> 24)] << 24) | ((uint32_t)SBOX3[(Zr >> 16) & MASK8] << 16) | ((uint32_t)SBOX4[(Zr >> 8) & MASK8] << 8) |(SBOX1[Zr & MASK8]));
-    Zl ^= LR32(Zr, 8);
-    Zr ^= LR32(Zl, 16);
-    Zl ^= RR32(Zr, 8);
-    Zr ^= RR32(Zl, 8);
-    return ((uint64_t)Zr << 32) | (uint64_t)Zl;
+    F_IN=SP[0][KE >> 56]^SP[1][(KE >> 48) & MASK8]^SP[2][(KE >> 40) & MASK8]^SP[3][(KE >> 32) & MASK8]^SP[4][(KE >> 24) & MASK8]^SP[5][(KE >> 16) & MASK8]^SP[6][(KE >> 8) & MASK8]^SP[7][KE & MASK8];
+    return F_IN;
 }
 
 static uint64_t FL(uint64_t FL_IN, uint64_t KE)
@@ -330,6 +324,26 @@
     AV_WB64(dst + 8, D1);
 }
 
+static void computeSP(void)
+{
+    uint64_t z;
+    int i;
+    for (i = 0; i < 256; i++) {
+        z = SBOX1[i];
+        SP[0][i] = (z << 56) ^ (z << 48) ^ (z << 40) ^ (z << 24) ^ z;
+        SP[7][i] = (z << 56) ^ (z << 48) ^ (z << 40) ^ (z << 24) ^ (z << 16) ^ (z << 8);
+        z = SBOX2[i];
+        SP[1][i] = (z << 48) ^ (z << 40) ^ (z << 32) ^ (z << 24) ^ (z << 16);
+        SP[4][i] = (z << 48) ^ (z << 40) ^ (z << 32) ^ (z << 16) ^ (z << 8) ^ z;
+        z = SBOX3[i];
+        SP[2][i] = (z << 56) ^ (z << 40) ^ (z << 32) ^ (z << 16) ^ (z << 8);
+        SP[5][i] = (z << 56) ^ (z << 40) ^ (z << 32) ^ (z << 24) ^ (z << 8) ^ z;
+        z = SBOX4[i];
+        SP[3][i] = (z << 56) ^ (z << 48) ^ (z << 32) ^ (z << 8) ^ z;
+        SP[6][i] = (z << 56) ^ (z << 48) ^ (z << 32) ^ (z << 24) ^ (z << 16) ^ z;
+    }
+}
+
 struct AVCAMELLIA *av_camellia_alloc(void)
 {
     return av_mallocz(sizeof(struct AVCAMELLIA));
@@ -353,6 +367,7 @@
         Kr[0] = AV_RB64(key + 16);
         Kr[1] = AV_RB64(key + 24);
     }
+    computeSP();
     D1 = Kl[0] ^ Kr[0];
     D2 = Kl[1] ^ Kr[1];
     D2 ^= F(D1, Sigma1);
diff --git a/libavutil/color_utils.c b/libavutil/color_utils.c
new file mode 100644
index 0000000..59146be
--- /dev/null
+++ b/libavutil/color_utils.c
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2015 Kevin Wheatley <kevin.j.wheatley@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/color_utils.h"
+#include "libavutil/pixfmt.h"
+
+double avpriv_get_gamma_from_trc(enum AVColorTransferCharacteristic trc)
+{
+    double gamma;
+    switch (trc) {
+        case AVCOL_TRC_BT709:
+        case AVCOL_TRC_SMPTE170M:
+        case AVCOL_TRC_SMPTE240M:
+        case AVCOL_TRC_BT1361_ECG:
+        case AVCOL_TRC_BT2020_10:
+        case AVCOL_TRC_BT2020_12:
+            /* these share a segmented TRC, but gamma 1.961 is a close
+              approximation, and also more correct for decoding content */
+            gamma = 1.961;
+            break;
+        case AVCOL_TRC_GAMMA22:
+        case AVCOL_TRC_IEC61966_2_1:
+            gamma = 2.2;
+            break;
+        case AVCOL_TRC_GAMMA28:
+            gamma = 2.8;
+            break;
+        case AVCOL_TRC_LINEAR:
+            gamma = 1.0;
+            break;
+        default:
+            gamma = 0.0; // Unknown value representation
+    }
+    return gamma;
+}
diff --git a/libavutil/color_utils.h b/libavutil/color_utils.h
new file mode 100644
index 0000000..3600a72
--- /dev/null
+++ b/libavutil/color_utils.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2015 Kevin Wheatley <kevin.j.wheatley@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 AVUTIL_COLOR_UTILS_H
+#define AVUTIL_COLOR_UTILS_H
+
+
+#include "libavutil/pixfmt.h"
+
+/**
+ * Determine a suitable 'gamma' value to match the supplied
+ * AVColorTransferCharacteristic.
+ *
+ * See Apple Technical Note TN2257 (https://developer.apple.com/library/mac/technotes/tn2257/_index.html)
+ *
+ * @return Will return an approximation to the simple gamma function matching
+ *         the supplied Transfer Characteristic, Will return 0.0 for any
+ *         we cannot reasonably match against.
+ */
+double avpriv_get_gamma_from_trc(enum AVColorTransferCharacteristic trc);
+
+#endif
diff --git a/libavutil/common.h b/libavutil/common.h
index c82a3a6..3e62b6d 100644
--- a/libavutil/common.h
+++ b/libavutil/common.h
@@ -147,7 +147,7 @@
  */
 static av_always_inline av_const int8_t av_clip_int8_c(int a)
 {
-    if ((a+0x80) & ~0xFF) return (a>>31) ^ 0x7F;
+    if ((a+0x80U) & ~0xFF) return (a>>31) ^ 0x7F;
     else                  return a;
 }
 
@@ -169,7 +169,7 @@
  */
 static av_always_inline av_const int16_t av_clip_int16_c(int a)
 {
-    if ((a+0x8000) & ~0xFFFF) return (a>>31) ^ 0x7FFF;
+    if ((a+0x8000U) & ~0xFFFF) return (a>>31) ^ 0x7FFF;
     else                      return a;
 }
 
@@ -185,6 +185,20 @@
 }
 
 /**
+ * Clip a signed integer into the -(2^p),(2^p-1) range.
+ * @param  a value to clip
+ * @param  p bit position to clip at
+ * @return clipped value
+ */
+static av_always_inline av_const int av_clip_intp2_c(int a, int p)
+{
+    if ((a + (1 << p)) & ~((2 << p) - 1))
+        return (a >> 31) ^ ((1 << p) - 1);
+    else
+        return a;
+}
+
+/**
  * Clip a signed integer to an unsigned power of two range.
  * @param  a value to clip
  * @param  p bit position to clip at
@@ -197,6 +211,17 @@
 }
 
 /**
+ * Clear high bits from an unsigned integer starting with specific bit position
+ * @param  a value to clip
+ * @param  p bit position to clip at
+ * @return clipped value
+ */
+static av_always_inline av_const unsigned av_mod_uintp2_c(unsigned a, unsigned p)
+{
+    return a & ((1 << p) - 1);
+}
+
+/**
  * Add two signed 32-bit values with saturation.
  *
  * @param  a one value
@@ -446,9 +471,15 @@
 #ifndef av_clipl_int32
 #   define av_clipl_int32   av_clipl_int32_c
 #endif
+#ifndef av_clip_intp2
+#   define av_clip_intp2    av_clip_intp2_c
+#endif
 #ifndef av_clip_uintp2
 #   define av_clip_uintp2   av_clip_uintp2_c
 #endif
+#ifndef av_mod_uintp2
+#   define av_mod_uintp2    av_mod_uintp2_c
+#endif
 #ifndef av_sat_add32
 #   define av_sat_add32     av_sat_add32_c
 #endif
diff --git a/libavutil/display.c b/libavutil/display.c
index 53e8aa2..a0076e0 100644
--- a/libavutil/display.c
+++ b/libavutil/display.c
@@ -44,12 +44,12 @@
     rotation = atan2(CONV_FP(matrix[1]) / scale[1],
                      CONV_FP(matrix[0]) / scale[0]) * 180 / M_PI;
 
-    return rotation;
+    return -rotation;
 }
 
 void av_display_rotation_set(int32_t matrix[9], double angle)
 {
-    double radians = angle * M_PI / 180.0f;
+    double radians = -angle * M_PI / 180.0f;
     double c = cos(radians);
     double s = sin(radians);
 
diff --git a/libavutil/display.h b/libavutil/display.h
index 2cb930d..c0cfee3 100644
--- a/libavutil/display.h
+++ b/libavutil/display.h
@@ -55,9 +55,9 @@
  * Extract the rotation component of the transformation matrix.
  *
  * @param matrix the transformation matrix
- * @return the angle (in degrees) by which the transformation rotates the frame.
- *         The angle will be in range [-180.0, 180.0], or NaN if the matrix is
- *         singular.
+ * @return the angle (in degrees) by which the transformation rotates the frame
+ *         counterclockwise. The angle will be in range [-180.0, 180.0],
+ *         or NaN if the matrix is singular.
  *
  * @note floating point numbers are inherently inexact, so callers are
  *       recommended to round the return value to nearest integer before use.
@@ -65,8 +65,8 @@
 double av_display_rotation_get(const int32_t matrix[9]);
 
 /**
- * Initialize a transformation matrix describing a pure rotation by the
- * specified angle (in degrees).
+ * Initialize a transformation matrix describing a pure counterclockwise
+ * rotation by the specified angle (in degrees).
  *
  * @param matrix an allocated transformation matrix (will be fully overwritten
  *               by this function)
diff --git a/libavutil/error.c b/libavutil/error.c
index d2868ac..4425968 100644
--- a/libavutil/error.c
+++ b/libavutil/error.c
@@ -29,6 +29,7 @@
 };
 
 #define ERROR_TAG(tag) AVERROR_##tag, #tag
+#define EERROR_TAG(tag) AVERROR(tag), #tag
 #define AVERROR_INPUT_AND_OUTPUT_CHANGED (AVERROR_INPUT_CHANGED | AVERROR_OUTPUT_CHANGED)
 static const struct error_entry error_entries[] = {
     { ERROR_TAG(BSF_NOT_FOUND),      "Bitstream filter not found"                     },
@@ -59,6 +60,9 @@
     { ERROR_TAG(HTTP_NOT_FOUND),     "Server returned 404 Not Found"           },
     { ERROR_TAG(HTTP_OTHER_4XX),     "Server returned 4XX Client Error, but not one of 40{0,1,3,4}" },
     { ERROR_TAG(HTTP_SERVER_ERROR),  "Server returned 5XX Server Error reply" },
+#if !HAVE_STRERROR_R
+    { EERROR_TAG(EINVAL),            "Invalid argument" },
+#endif
 };
 
 int av_strerror(int errnum, char *errbuf, size_t errbuf_size)
diff --git a/libavutil/file.c b/libavutil/file.c
index 359d290..2a06be4 100644
--- a/libavutil/file.c
+++ b/libavutil/file.c
@@ -35,7 +35,7 @@
 #include <windows.h>
 #endif
 
-typedef struct {
+typedef struct FileLogContext {
     const AVClass *class;
     int   log_offset;
     void *log_ctx;
diff --git a/libavutil/fixed_dsp.c b/libavutil/fixed_dsp.c
index b99fea5..9f2e841 100644
--- a/libavutil/fixed_dsp.c
+++ b/libavutil/fixed_dsp.c
@@ -63,8 +63,8 @@
         s1 = src1[j];
         wi = win[i];
         wj = win[j];
-        dst[i] = av_clip_int16_c(((((int64_t)s0*wj - (int64_t)s1*wi + 0x40000000) >> 31) + round) >> bits);
-        dst[j] = av_clip_int16_c(((((int64_t)s0*wi + (int64_t)s1*wj + 0x40000000) >> 31) + round) >> bits);
+        dst[i] = av_clip_int16(((((int64_t)s0*wj - (int64_t)s1*wi + 0x40000000) >> 31) + round) >> bits);
+        dst[j] = av_clip_int16(((((int64_t)s0*wi + (int64_t)s1*wj + 0x40000000) >> 31) + round) >> bits);
     }
 }
 
@@ -91,6 +91,10 @@
 AVFixedDSPContext * avpriv_alloc_fixed_dsp(int bit_exact)
 {
     AVFixedDSPContext * fdsp = av_malloc(sizeof(AVFixedDSPContext));
+
+    if (!fdsp)
+        return NULL;
+
     fdsp->vector_fmul_window_scaled = vector_fmul_window_fixed_scaled_c;
     fdsp->vector_fmul_window = vector_fmul_window_fixed_c;
 
diff --git a/libavutil/frame.h b/libavutil/frame.h
index 1e29652..2fab79e 100644
--- a/libavutil/frame.h
+++ b/libavutil/frame.h
@@ -124,6 +124,13 @@
     AV_AFD_SP_4_3       = 15,
 };
 
+
+/**
+ * Structure to hold side data for an AVFrame.
+ *
+ * sizeof(AVFrameSideData) is not a part of the public ABI, so new fields may be added
+ * to the end with a minor bump.
+ */
 typedef struct AVFrameSideData {
     enum AVFrameSideDataType type;
     uint8_t *data;
@@ -420,7 +427,9 @@
 
     /**
      * AVBuffer references backing the data for this frame. If all elements of
-     * this array are NULL, then this frame is not reference counted.
+     * this array are NULL, then this frame is not reference counted. This array
+     * must be filled contiguously -- if buf[i] is non-NULL then buf[j] must
+     * also be non-NULL for all j < i.
      *
      * There may be at most one AVBuffer per data plane, so for video this array
      * always contains all the references. For planar audio with more than
diff --git a/libavutil/imgutils.c b/libavutil/imgutils.c
index 07b494c..a8bc18d 100644
--- a/libavutil/imgutils.c
+++ b/libavutil/imgutils.c
@@ -245,7 +245,7 @@
 {
     int64_t scaled_dim;
 
-    if (!sar.den)
+    if (sar.den <= 0 || sar.num < 0)
         return AVERROR(EINVAL);
 
     if (!sar.num || sar.num == sar.den)
diff --git a/libavutil/internal.h b/libavutil/internal.h
index c69df23..ec9c745 100644
--- a/libavutil/internal.h
+++ b/libavutil/internal.h
@@ -164,9 +164,9 @@
 
 #include "libm.h"
 
-#if defined(_MSC_VER)
-#pragma comment(linker, "/include:" EXTERN_PREFIX "avpriv_strtod")
-#pragma comment(linker, "/include:" EXTERN_PREFIX "avpriv_snprintf")
+#if defined(_MSC_VER) && _MSC_VER < 1900
+#pragma comment(linker, "/include:" EXTERN_PREFIX" avpriv_strtod")
+#pragma comment(linker, "/include:" EXTERN_PREFIX" avpriv_snprintf")
 #endif
 
 /**
@@ -273,4 +273,6 @@
 uint64_t ff_get_channel_layout(const char *name, int compat);
 #endif
 
+void ff_check_pixfmt_descriptors(void);
+
 #endif /* AVUTIL_INTERNAL_H */
diff --git a/libavutil/intmath.h b/libavutil/intmath.h
index 308c776..f5ecc77 100644
--- a/libavutil/intmath.h
+++ b/libavutil/intmath.h
@@ -29,6 +29,9 @@
 #if ARCH_ARM
 #   include "arm/intmath.h"
 #endif
+#if ARCH_X86
+#   include "x86/intmath.h"
+#endif
 
 /**
  * @addtogroup lavu_internal
@@ -45,7 +48,7 @@
 #endif /* ff_log2 */
 #elif defined( __INTEL_COMPILER )
 #ifndef ff_log2
-#   define ff_log2(x) (_bit_scan_reverse(x|1))
+#   define ff_log2(x) (_bit_scan_reverse((x)|1))
 #   ifndef ff_log2_16bit
 #      define ff_log2_16bit av_log2
 #   endif
diff --git a/libavutil/log.h b/libavutil/log.h
index e1ff09b..993a4f5 100644
--- a/libavutil/log.h
+++ b/libavutil/log.h
@@ -209,7 +209,7 @@
  * Requires 256color terminal support. Uses outside debugging is not
  * recommended.
  */
-#define AV_LOG_C(x) (x << 8)
+#define AV_LOG_C(x) ((x) << 8)
 
 /**
  * Send the specified message to the log if the level is less than or equal
diff --git a/libavutil/mem.c b/libavutil/mem.c
index 91ce2d9..95cd3c7 100644
--- a/libavutil/mem.c
+++ b/libavutil/mem.c
@@ -185,21 +185,22 @@
 
 int av_reallocp(void *ptr, size_t size)
 {
-    void **ptrptr = ptr;
-    void *ret;
+    void *val;
 
     if (!size) {
         av_freep(ptr);
         return 0;
     }
-    ret = av_realloc(*ptrptr, size);
 
-    if (!ret) {
+    memcpy(&val, ptr, sizeof(val));
+    val = av_realloc(val, size);
+
+    if (!val) {
         av_freep(ptr);
         return AVERROR(ENOMEM);
     }
 
-    *ptrptr = ret;
+    memcpy(ptr, &val, sizeof(val));
     return 0;
 }
 
@@ -212,10 +213,14 @@
 
 int av_reallocp_array(void *ptr, size_t nmemb, size_t size)
 {
-    void **ptrptr = ptr;
-    *ptrptr = av_realloc_f(*ptrptr, nmemb, size);
-    if (!*ptrptr && nmemb && size)
+    void *val;
+
+    memcpy(&val, ptr, sizeof(val));
+    val = av_realloc_f(val, nmemb, size);
+    memcpy(ptr, &val, sizeof(val));
+    if (!val && nmemb && size)
         return AVERROR(ENOMEM);
+
     return 0;
 }
 
@@ -236,9 +241,11 @@
 
 void av_freep(void *arg)
 {
-    void **ptr = (void **)arg;
-    av_free(*ptr);
-    *ptr = NULL;
+    void *val;
+
+    memcpy(&val, arg, sizeof(val));
+    memcpy(arg, &(void *){ NULL }, sizeof(val));
+    av_free(val);
 }
 
 void *av_mallocz(size_t size)
@@ -301,11 +308,12 @@
 
 int av_dynarray_add_nofree(void *tab_ptr, int *nb_ptr, void *elem)
 {
-    void **tab = *(void ***)tab_ptr;
+    void **tab;
+    memcpy(&tab, tab_ptr, sizeof(tab));
 
     AV_DYNARRAY_ADD(INT_MAX, sizeof(*tab), tab, *nb_ptr, {
         tab[*nb_ptr] = elem;
-        *(void ***)tab_ptr = tab;
+        memcpy(tab_ptr, &tab, sizeof(tab));
     }, {
         return AVERROR(ENOMEM);
     });
@@ -314,11 +322,12 @@
 
 void av_dynarray_add(void *tab_ptr, int *nb_ptr, void *elem)
 {
-    void **tab = *(void ***)tab_ptr;
+    void **tab;
+    memcpy(&tab, tab_ptr, sizeof(tab));
 
     AV_DYNARRAY_ADD(INT_MAX, sizeof(*tab), tab, *nb_ptr, {
         tab[*nb_ptr] = elem;
-        *(void ***)tab_ptr = tab;
+        memcpy(tab_ptr, &tab, sizeof(tab));
     }, {
         *nb_ptr = 0;
         av_freep(tab_ptr);
@@ -488,13 +497,15 @@
 
 static inline int ff_fast_malloc(void *ptr, unsigned int *size, size_t min_size, int zero_realloc)
 {
-    void **p = ptr;
+    void *val;
+
     if (min_size < *size)
         return 0;
     min_size = FFMAX(17 * min_size / 16 + 32, min_size);
-    av_free(*p);
-    *p = zero_realloc ? av_mallocz(min_size) : av_malloc(min_size);
-    if (!*p)
+    av_freep(ptr);
+    val = zero_realloc ? av_mallocz(min_size) : av_malloc(min_size);
+    memcpy(ptr, &val, sizeof(val));
+    if (!val)
         min_size = 0;
     *size = min_size;
     return 1;
diff --git a/libavutil/mips/asmdefs.h b/libavutil/mips/asmdefs.h
new file mode 100644
index 0000000..fdf82a0
--- /dev/null
+++ b/libavutil/mips/asmdefs.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2015 Imagination Technologies Ltd
+ *
+ * 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
+ * MIPS assembly defines from sys/asm.h but rewritten for use with C inline
+ * assembly (rather than from within .s files).
+ */
+
+#ifndef AVUTIL_MIPS_ASMDEFS_H
+#define AVUTIL_MIPS_ASMDEFS_H
+
+#if defined(_ABI64) && _MIPS_SIM == _ABI64
+# define PTRSIZE        " 8 "
+# define PTRLOG         " 3 "
+# define PTR_ADDU       "daddu "
+# define PTR_ADDIU      "daddiu "
+# define PTR_SUBU       "dsubu "
+# define PTR_L          "ld "
+#else
+# define PTRSIZE        " 4 "
+# define PTRLOG         " 2 "
+# define PTR_ADDU       "addu "
+# define PTR_ADDIU      "addiu "
+# define PTR_SUBU       "subu "
+# define PTR_L          "lw "
+#endif
+
+#endif /* AVCODEC_MIPS_ASMDEFS_H */
diff --git a/libavutil/mips/float_dsp_mips.c b/libavutil/mips/float_dsp_mips.c
index 06d52dc..b3a812ce 100644
--- a/libavutil/mips/float_dsp_mips.c
+++ b/libavutil/mips/float_dsp_mips.c
@@ -53,6 +53,7 @@
 
 #include "config.h"
 #include "libavutil/float_dsp.h"
+#include "libavutil/mips/asmdefs.h"
 
 #if HAVE_INLINE_ASM && HAVE_MIPSFPU
 static void vector_fmul_mips(float *dst, const float *src0, const float *src1,
@@ -90,9 +91,9 @@
             "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"
+            PTR_ADDIU "%[s0],   %[s0],      16          \n\t"
+            PTR_ADDIU "%[s1],   %[s1],      16          \n\t"
+            PTR_ADDIU "%[d],    %[d],       16          \n\t"
             "bne    %[d],       %[d_end],   1b          \n\t"
 
             : [src0_0]"=&f"(src0_0), [src0_1]"=&f"(src0_1),
@@ -122,12 +123,12 @@
         "lwc1    %[temp1],   4(%[src])            \n\t"
         "lwc1    %[temp2],   8(%[src])            \n\t"
         "lwc1    %[temp3],   12(%[src])           \n\t"
-        "addiu   %[dst],     %[dst],     16       \n\t"
+        PTR_ADDIU "%[dst],   %[dst],     16       \n\t"
         "mul.s   %[temp0],   %[temp0],   %[mul]   \n\t"
         "mul.s   %[temp1],   %[temp1],   %[mul]   \n\t"
         "mul.s   %[temp2],   %[temp2],   %[mul]   \n\t"
         "mul.s   %[temp3],   %[temp3],   %[mul]   \n\t"
-        "addiu   %[src],     %[src],     16       \n\t"
+        PTR_ADDIU "%[src],   %[src],     16       \n\t"
         "swc1    %[temp0],   -16(%[dst])          \n\t"
         "swc1    %[temp1],   -12(%[dst])          \n\t"
         "swc1    %[temp2],   -8(%[dst])           \n\t"
@@ -144,114 +145,82 @@
 }
 
 static void vector_fmul_window_mips(float *dst, const float *src0,
-        const float *src1, const float *win, int len)
+                                    const float *src1, const float *win, int len)
 {
-    int i, j;
-    /*
-     * variables used in inline assembler
-     */
-    float * dst_i, * dst_j, * dst_i2, * dst_j2;
-    float temp, temp1, temp2, temp3, temp4, temp5, temp6, temp7;
+    float * dst_j, *win_j, *src0_i, *src1_j, *dst_i, *win_i;
+    float temp, temp1, temp2, temp3;
+    float s0, s01, s1, s11;
+    float wi, wi1, wi2, wi3;
+    float wj, wj1, wj2, wj3;
+    const float * lp_end = win + len;
 
-    dst  += len;
-    win  += len;
-    src0 += len;
+    win_i  = (float *)win;
+    win_j  = (float *)(win + 2 * len -1);
+    src1_j = (float *)(src1 + len - 1);
+    src0_i = (float *)src0;
+    dst_i  = (float *)dst;
+    dst_j  = (float *)(dst + 2 * len -1);
 
-    for (i = -len, j = len - 1; i < 0; i += 8, j -= 8) {
-
-        dst_i = dst + i;
-        dst_j = dst + j;
-
-        dst_i2 = dst + i + 4;
-        dst_j2 = dst + j - 4;
-
-        __asm__ volatile (
-            "mul.s   %[temp],   %[s1],       %[wi]            \n\t"
-            "mul.s   %[temp1],  %[s1],       %[wj]            \n\t"
-            "mul.s   %[temp2],  %[s11],      %[wi1]           \n\t"
-            "mul.s   %[temp3],  %[s11],      %[wj1]           \n\t"
-
-            "msub.s  %[temp],   %[temp],     %[s0],  %[wj]    \n\t"
-            "madd.s  %[temp1],  %[temp1],    %[s0],  %[wi]    \n\t"
-            "msub.s  %[temp2],  %[temp2],    %[s01], %[wj1]   \n\t"
-            "madd.s  %[temp3],  %[temp3],    %[s01], %[wi1]   \n\t"
-
-            "swc1    %[temp],   0(%[dst_i])                   \n\t" /* dst[i] = s0*wj - s1*wi; */
-            "swc1    %[temp1],  0(%[dst_j])                   \n\t" /* dst[j] = s0*wi + s1*wj; */
-            "swc1    %[temp2],  4(%[dst_i])                   \n\t" /* dst[i+1] = s01*wj1 - s11*wi1; */
-            "swc1    %[temp3], -4(%[dst_j])                   \n\t" /* dst[j-1] = s01*wi1 + s11*wj1; */
-
-            "mul.s   %[temp4],  %[s12],      %[wi2]           \n\t"
-            "mul.s   %[temp5],  %[s12],      %[wj2]           \n\t"
-            "mul.s   %[temp6],  %[s13],      %[wi3]           \n\t"
-            "mul.s   %[temp7],  %[s13],      %[wj3]           \n\t"
-
-            "msub.s  %[temp4],  %[temp4],    %[s02], %[wj2]   \n\t"
-            "madd.s  %[temp5],  %[temp5],    %[s02], %[wi2]   \n\t"
-            "msub.s  %[temp6],  %[temp6],    %[s03], %[wj3]   \n\t"
-            "madd.s  %[temp7],  %[temp7],    %[s03], %[wi3]   \n\t"
-
-            "swc1    %[temp4],  8(%[dst_i])                   \n\t" /* dst[i+2] = s02*wj2 - s12*wi2; */
-            "swc1    %[temp5], -8(%[dst_j])                   \n\t" /* dst[j-2] = s02*wi2 + s12*wj2; */
-            "swc1    %[temp6],  12(%[dst_i])                  \n\t" /* dst[i+2] = s03*wj3 - s13*wi3; */
-            "swc1    %[temp7], -12(%[dst_j])                  \n\t" /* dst[j-3] = s03*wi3 + s13*wj3; */
-            : [temp]"=&f"(temp),  [temp1]"=&f"(temp1), [temp2]"=&f"(temp2),
-              [temp3]"=&f"(temp3), [temp4]"=&f"(temp4), [temp5]"=&f"(temp5),
-              [temp6]"=&f"(temp6), [temp7]"=&f"(temp7)
-            : [dst_j]"r"(dst_j),     [dst_i]"r" (dst_i),
-              [s0] "f"(src0[i]),     [wj] "f"(win[j]),     [s1] "f"(src1[j]),
-              [wi] "f"(win[i]),      [s01]"f"(src0[i + 1]),[wj1]"f"(win[j - 1]),
-              [s11]"f"(src1[j - 1]), [wi1]"f"(win[i + 1]), [s02]"f"(src0[i + 2]),
-              [wj2]"f"(win[j - 2]),  [s12]"f"(src1[j - 2]),[wi2]"f"(win[i + 2]),
-              [s03]"f"(src0[i + 3]), [wj3]"f"(win[j - 3]), [s13]"f"(src1[j - 3]),
-              [wi3]"f"(win[i + 3])
-            : "memory"
-        );
-
-        __asm__ volatile (
-            "mul.s  %[temp],   %[s1],       %[wi]            \n\t"
-            "mul.s  %[temp1],  %[s1],       %[wj]            \n\t"
-            "mul.s  %[temp2],  %[s11],      %[wi1]           \n\t"
-            "mul.s  %[temp3],  %[s11],      %[wj1]           \n\t"
-
-            "msub.s %[temp],   %[temp],     %[s0],  %[wj]    \n\t"
-            "madd.s %[temp1],  %[temp1],    %[s0],  %[wi]    \n\t"
-            "msub.s %[temp2],  %[temp2],    %[s01], %[wj1]   \n\t"
-            "madd.s %[temp3],  %[temp3],    %[s01], %[wi1]   \n\t"
-
-            "swc1   %[temp],   0(%[dst_i2])                  \n\t" /* dst[i] = s0*wj - s1*wi; */
-            "swc1   %[temp1],  0(%[dst_j2])                  \n\t" /* dst[j] = s0*wi + s1*wj; */
-            "swc1   %[temp2],  4(%[dst_i2])                  \n\t" /* dst[i+1] = s01*wj1 - s11*wi1; */
-            "swc1   %[temp3], -4(%[dst_j2])                  \n\t" /* dst[j-1] = s01*wi1 + s11*wj1; */
-
-            "mul.s  %[temp4],  %[s12],      %[wi2]           \n\t"
-            "mul.s  %[temp5],  %[s12],      %[wj2]           \n\t"
-            "mul.s  %[temp6],  %[s13],      %[wi3]           \n\t"
-            "mul.s  %[temp7],  %[s13],      %[wj3]           \n\t"
-
-            "msub.s %[temp4],  %[temp4],    %[s02], %[wj2]   \n\t"
-            "madd.s %[temp5],  %[temp5],    %[s02], %[wi2]   \n\t"
-            "msub.s %[temp6],  %[temp6],    %[s03], %[wj3]   \n\t"
-            "madd.s %[temp7],  %[temp7],    %[s03], %[wi3]   \n\t"
-
-            "swc1   %[temp4],  8(%[dst_i2])                  \n\t" /* dst[i+2] = s02*wj2 - s12*wi2; */
-            "swc1   %[temp5], -8(%[dst_j2])                  \n\t" /* dst[j-2] = s02*wi2 + s12*wj2; */
-            "swc1   %[temp6],  12(%[dst_i2])                 \n\t" /* dst[i+2] = s03*wj3 - s13*wi3; */
-            "swc1   %[temp7], -12(%[dst_j2])                 \n\t" /* dst[j-3] = s03*wi3 + s13*wj3; */
-            : [temp]"=&f"(temp),
-              [temp1]"=&f"(temp1), [temp2]"=&f"(temp2), [temp3]"=&f"(temp3),
-              [temp4]"=&f"(temp4), [temp5]"=&f"(temp5), [temp6]"=&f"(temp6),
-              [temp7]  "=&f" (temp7)
-            : [dst_j2]"r"(dst_j2),   [dst_i2]"r"(dst_i2),
-              [s0] "f"(src0[i + 4]), [wj] "f"(win[j - 4]), [s1] "f"(src1[j - 4]),
-              [wi] "f"(win[i + 4]),  [s01]"f"(src0[i + 5]),[wj1]"f"(win[j - 5]),
-              [s11]"f"(src1[j - 5]), [wi1]"f"(win[i + 5]), [s02]"f"(src0[i + 6]),
-              [wj2]"f"(win[j - 6]),  [s12]"f"(src1[j - 6]),[wi2]"f"(win[i + 6]),
-              [s03]"f"(src0[i + 7]), [wj3]"f"(win[j - 7]), [s13]"f"(src1[j - 7]),
-              [wi3]"f"(win[i + 7])
-            : "memory"
-        );
-    }
+    /* loop unrolled 4 times */
+    __asm__ volatile (
+        "1:"
+        "lwc1    %[s1],     0(%[src1_j])                \n\t"
+        "lwc1    %[wi],     0(%[win_i])                 \n\t"
+        "lwc1    %[wj],     0(%[win_j])                 \n\t"
+        "lwc1    %[s11],   -4(%[src1_j])                \n\t"
+        "lwc1    %[wi1],    4(%[win_i])                 \n\t"
+        "lwc1    %[wj1],   -4(%[win_j])                 \n\t"
+        "lwc1    %[s0],     0(%[src0_i])                \n\t"
+        "lwc1    %[s01],    4(%[src0_i])                \n\t"
+        "mul.s   %[temp],   %[s1],   %[wi]              \n\t"
+        "mul.s   %[temp1],  %[s1],   %[wj]              \n\t"
+        "mul.s   %[temp2],  %[s11],  %[wi1]             \n\t"
+        "mul.s   %[temp3],  %[s11],  %[wj1]             \n\t"
+        "lwc1    %[s1],    -8(%[src1_j])                \n\t"
+        "lwc1    %[wi2],    8(%[win_i])                 \n\t"
+        "lwc1    %[wj2],   -8(%[win_j])                 \n\t"
+        "lwc1    %[s11],   -12(%[src1_j])               \n\t"
+        "msub.s  %[temp],   %[temp],  %[s0],  %[wj]     \n\t"
+        "madd.s  %[temp1],  %[temp1], %[s0],  %[wi]     \n\t"
+        "msub.s  %[temp2],  %[temp2], %[s01], %[wj1]    \n\t"
+        "madd.s  %[temp3],  %[temp3], %[s01], %[wi1]    \n\t"
+        "lwc1    %[wi3],    12(%[win_i])                \n\t"
+        "lwc1    %[wj3],   -12(%[win_j])                \n\t"
+        "lwc1    %[s0],     8(%[src0_i])                \n\t"
+        "lwc1    %[s01],    12(%[src0_i])               \n\t"
+        PTR_ADDIU "%[src1_j],-16                        \n\t"
+        PTR_ADDIU "%[win_i],16                          \n\t"
+        PTR_ADDIU "%[win_j],-16                         \n\t"
+        PTR_ADDIU "%[src0_i],16                         \n\t"
+        "swc1    %[temp],   0(%[dst_i])                 \n\t" /* dst[i] = s0*wj - s1*wi; */
+        "swc1    %[temp1],  0(%[dst_j])                 \n\t" /* dst[j] = s0*wi + s1*wj; */
+        "swc1    %[temp2],  4(%[dst_i])                 \n\t" /* dst[i+1] = s01*wj1 - s11*wi1; */
+        "swc1    %[temp3], -4(%[dst_j])                 \n\t" /* dst[j-1] = s01*wi1 + s11*wj1; */
+        "mul.s   %[temp],   %[s1],    %[wi2]            \n\t"
+        "mul.s   %[temp1],  %[s1],    %[wj2]            \n\t"
+        "mul.s   %[temp2],  %[s11],   %[wi3]            \n\t"
+        "mul.s   %[temp3],  %[s11],   %[wj3]            \n\t"
+        "msub.s  %[temp],   %[temp],  %[s0],  %[wj2]    \n\t"
+        "madd.s  %[temp1],  %[temp1], %[s0],  %[wi2]    \n\t"
+        "msub.s  %[temp2],  %[temp2], %[s01], %[wj3]    \n\t"
+        "madd.s  %[temp3],  %[temp3], %[s01], %[wi3]    \n\t"
+        "swc1    %[temp],   8(%[dst_i])                 \n\t" /* dst[i+2] = s0*wj2 - s1*wi2; */
+        "swc1    %[temp1], -8(%[dst_j])                 \n\t" /* dst[j-2] = s0*wi2 + s1*wj2; */
+        "swc1    %[temp2],  12(%[dst_i])                \n\t" /* dst[i+2] = s01*wj3 - s11*wi3; */
+        "swc1    %[temp3], -12(%[dst_j])                \n\t" /* dst[j-3] = s01*wi3 + s11*wj3; */
+        PTR_ADDIU "%[dst_i],16                          \n\t"
+        PTR_ADDIU "%[dst_j],-16                         \n\t"
+        "bne     %[win_i], %[lp_end], 1b                \n\t"
+        : [temp]"=&f"(temp), [temp1]"=&f"(temp1), [temp2]"=&f"(temp2),
+          [temp3]"=&f"(temp3), [src0_i]"+r"(src0_i), [win_i]"+r"(win_i),
+          [src1_j]"+r"(src1_j), [win_j]"+r"(win_j), [dst_i]"+r"(dst_i),
+          [dst_j]"+r"(dst_j), [s0] "=&f"(s0), [s01]"=&f"(s01), [s1] "=&f"(s1),
+          [s11]"=&f"(s11), [wi] "=&f"(wi), [wj] "=&f"(wj), [wi2]"=&f"(wi2),
+          [wj2]"=&f"(wj2), [wi3]"=&f"(wi3), [wj3]"=&f"(wj3), [wi1]"=&f"(wi1),
+          [wj1]"=&f"(wj1)
+        : [lp_end]"r"(lp_end)
+        : "memory"
+    );
 }
 
 static void butterflies_float_mips(float *av_restrict v1, float *av_restrict v2,
@@ -283,8 +252,8 @@
         "add.s    %[temp13],   %[temp2],    %[temp6]    \n\t"
         "sub.s    %[temp14],   %[temp3],    %[temp7]    \n\t"
         "add.s    %[temp15],   %[temp3],    %[temp7]    \n\t"
-        "addiu    %[v1],       %[v1],       16          \n\t"
-        "addiu    %[v2],       %[v2],       16          \n\t"
+        PTR_ADDIU "%[v1],      %[v1],       16          \n\t"
+        PTR_ADDIU "%[v2],      %[v2],       16          \n\t"
         "addiu    %[pom],      %[pom],      -1          \n\t"
         "lwc1     %[temp0],    0(%[v1])                 \n\t"
         "lwc1     %[temp1],    4(%[v1])                 \n\t"
@@ -353,9 +322,9 @@
             "mul.s     %[temp2],     %[temp3],     %[temp2]     \n\t"
             "mul.s     %[temp4],     %[temp5],     %[temp4]     \n\t"
             "mul.s     %[temp6],     %[temp7],     %[temp6]     \n\t"
-            "addiu     %[src0],      %[src0],      16           \n\t"
-            "addiu     %[src1],      %[src1],      -16          \n\t"
-            "addiu     %[dst],       %[dst],       16           \n\t"
+            PTR_ADDIU "%[src0],      %[src0],      16           \n\t"
+            PTR_ADDIU "%[src1],      %[src1],      -16          \n\t"
+            PTR_ADDIU "%[dst],       %[dst],       16           \n\t"
             "swc1      %[temp0],     -16(%[dst])                \n\t"
             "swc1      %[temp2],     -12(%[dst])                \n\t"
             "swc1      %[temp4],     -8(%[dst])                 \n\t"
diff --git a/libavutil/murmur3.c b/libavutil/murmur3.c
index 701fa6a..c4d8dcb 100644
--- a/libavutil/murmur3.c
+++ b/libavutil/murmur3.c
@@ -49,7 +49,7 @@
 static const uint64_t c1 = UINT64_C(0x87c37b91114253d5);
 static const uint64_t c2 = UINT64_C(0x4cf5ad432745937f);
 
-#define ROT(a, b) ((a << b) | (a >> (64 - b)))
+#define ROT(a, b) (((a) << (b)) | ((a) >> (64 - (b))))
 
 static uint64_t inline get_k1(const uint8_t *src)
 {
diff --git a/libavutil/opencl.c b/libavutil/opencl.c
index 36cb6fe..2df5653 100644
--- a/libavutil/opencl.c
+++ b/libavutil/opencl.c
@@ -588,6 +588,7 @@
 
 void av_opencl_uninit(void)
 {
+    int i;
     cl_int status;
     LOCK_OPENCL;
     opencl_ctx.init_count--;
@@ -611,6 +612,9 @@
         }
         opencl_ctx.context = NULL;
     }
+    for (i = 0; i < opencl_ctx.kernel_code_count; i++) {
+        opencl_ctx.kernel_code[i].is_compiled = 0;
+    }
     free_device_list(&opencl_ctx.device_list);
 end:
     if (opencl_ctx.init_count <= 0)
diff --git a/libavutil/opt.c b/libavutil/opt.c
index c68dacc..092446b 100644
--- a/libavutil/opt.c
+++ b/libavutil/opt.c
@@ -65,8 +65,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_PIXEL_FMT: *intnum = *(enum AVPixelFormat *)dst;return 0;
+    case AV_OPT_TYPE_SAMPLE_FMT:*intnum = *(enum AVSampleFormat*)dst;return 0;
     case AV_OPT_TYPE_INT:       *intnum = *(int         *)dst;return 0;
     case AV_OPT_TYPE_CHANNEL_LAYOUT:
     case AV_OPT_TYPE_DURATION:
@@ -100,9 +100,9 @@
     }
 
     switch (o->type) {
+    case AV_OPT_TYPE_PIXEL_FMT: *(enum AVPixelFormat *)dst = llrint(num/den) * intnum; break;
+    case AV_OPT_TYPE_SAMPLE_FMT:*(enum AVSampleFormat*)dst = llrint(num/den) * intnum; break;
     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_DURATION:
     case AV_OPT_TYPE_CHANNEL_LAYOUT:
@@ -1928,28 +1928,28 @@
 #define TEST_FLAG_MU   04
 
 static const AVOption test_options[]= {
-{"num",      "set num",        OFFSET(num),      AV_OPT_TYPE_INT,      {.i64 = 0},       0,        100                 },
-{"toggle",   "set toggle",     OFFSET(toggle),   AV_OPT_TYPE_INT,      {.i64 = 1},       0,        1                   },
-{"rational", "set rational",   OFFSET(rational), AV_OPT_TYPE_RATIONAL, {.dbl = 1},       0,        10                  },
-{"string",   "set string",     OFFSET(string),   AV_OPT_TYPE_STRING,   {.str = "default"}, CHAR_MIN, CHAR_MAX          },
-{"escape",   "set escape str", OFFSET(escape),   AV_OPT_TYPE_STRING,   {.str = "\\=,"}, CHAR_MIN, CHAR_MAX             },
-{"flags",    "set flags",      OFFSET(flags),    AV_OPT_TYPE_FLAGS,    {.i64 = 1},       0,        INT_MAX, 0, "flags" },
-{"cool",     "set cool flag ", 0,                AV_OPT_TYPE_CONST,    {.i64 = TEST_FLAG_COOL}, INT_MIN,  INT_MAX, 0, "flags" },
-{"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,{.str="200x300"},             0,        0                   },
-{"pix_fmt",  "set pixfmt",     OFFSET(pix_fmt),  AV_OPT_TYPE_PIXEL_FMT, {.i64 = AV_PIX_FMT_0BGR}, -1, INT_MAX},
-{"sample_fmt", "set samplefmt", OFFSET(sample_fmt), AV_OPT_TYPE_SAMPLE_FMT, {.i64 = AV_SAMPLE_FMT_S16}, -1, INT_MAX},
-{"video_rate", "set videorate", OFFSET(video_rate), AV_OPT_TYPE_VIDEO_RATE,  {.str = "25"}, 0,     0                   },
-{"duration", "set duration",   OFFSET(duration), AV_OPT_TYPE_DURATION, {.i64 = 1000}, 0, INT64_MAX},
-{"color", "set color",   OFFSET(color), AV_OPT_TYPE_COLOR, {.str = "pink"}, 0, 0},
-{"cl", "set channel layout", OFFSET(channel_layout), AV_OPT_TYPE_CHANNEL_LAYOUT, {.i64 = AV_CH_LAYOUT_HEXAGONAL}, 0, INT64_MAX},
-{"bin", "set binary value",    OFFSET(binary),   AV_OPT_TYPE_BINARY,   {.str="62696e00"}, 0,        0 },
-{"bin1", "set binary value",   OFFSET(binary1),  AV_OPT_TYPE_BINARY,   {.str=NULL},       0,        0 },
-{"bin2", "set binary value",   OFFSET(binary2),  AV_OPT_TYPE_BINARY,   {.str=""},         0,        0 },
-{"num64",    "set num 64bit",  OFFSET(num64),    AV_OPT_TYPE_INT64,    {.i64 = 1},        0,        100 },
-{"flt",      "set float",      OFFSET(flt),      AV_OPT_TYPE_FLOAT,    {.dbl = 1.0/3},    0,        100 },
-{"dbl",      "set double",     OFFSET(dbl),      AV_OPT_TYPE_DOUBLE,   {.dbl = 1.0/3},    0,        100 },
+{"num",      "set num",        OFFSET(num),      AV_OPT_TYPE_INT,      {.i64 = 0},       0,        100, 1              },
+{"toggle",   "set toggle",     OFFSET(toggle),   AV_OPT_TYPE_INT,      {.i64 = 1},       0,        1,   1              },
+{"rational", "set rational",   OFFSET(rational), AV_OPT_TYPE_RATIONAL, {.dbl = 1},       0,        10,  1              },
+{"string",   "set string",     OFFSET(string),   AV_OPT_TYPE_STRING,   {.str = "default"}, CHAR_MIN, CHAR_MAX, 1       },
+{"escape",   "set escape str", OFFSET(escape),   AV_OPT_TYPE_STRING,   {.str = "\\=,"}, CHAR_MIN, CHAR_MAX, 1          },
+{"flags",    "set flags",      OFFSET(flags),    AV_OPT_TYPE_FLAGS,    {.i64 = 1},       0,        INT_MAX, 1, "flags" },
+{"cool",     "set cool flag",  0,                AV_OPT_TYPE_CONST,    {.i64 = TEST_FLAG_COOL}, INT_MIN,  INT_MAX, 1, "flags" },
+{"lame",     "set lame flag",  0,                AV_OPT_TYPE_CONST,    {.i64 = TEST_FLAG_LAME}, INT_MIN,  INT_MAX, 1, "flags" },
+{"mu",       "set mu flag",    0,                AV_OPT_TYPE_CONST,    {.i64 = TEST_FLAG_MU},   INT_MIN,  INT_MAX, 1, "flags" },
+{"size",     "set size",       OFFSET(w),        AV_OPT_TYPE_IMAGE_SIZE,{.str="200x300"},             0,        0, 1},
+{"pix_fmt",  "set pixfmt",     OFFSET(pix_fmt),  AV_OPT_TYPE_PIXEL_FMT, {.i64 = AV_PIX_FMT_0BGR}, -1, INT_MAX, 1},
+{"sample_fmt", "set samplefmt", OFFSET(sample_fmt), AV_OPT_TYPE_SAMPLE_FMT, {.i64 = AV_SAMPLE_FMT_S16}, -1, INT_MAX, 1},
+{"video_rate", "set videorate", OFFSET(video_rate), AV_OPT_TYPE_VIDEO_RATE,  {.str = "25"}, 0,     0                   , 1},
+{"duration", "set duration",   OFFSET(duration), AV_OPT_TYPE_DURATION, {.i64 = 1000}, 0, INT64_MAX, 1},
+{"color", "set color",   OFFSET(color), AV_OPT_TYPE_COLOR, {.str = "pink"}, 0, 0, 1},
+{"cl", "set channel layout", OFFSET(channel_layout), AV_OPT_TYPE_CHANNEL_LAYOUT, {.i64 = AV_CH_LAYOUT_HEXAGONAL}, 0, INT64_MAX, 1},
+{"bin", "set binary value",    OFFSET(binary),   AV_OPT_TYPE_BINARY,   {.str="62696e00"}, 0,        0, 1 },
+{"bin1", "set binary value",   OFFSET(binary1),  AV_OPT_TYPE_BINARY,   {.str=NULL},       0,        0, 1 },
+{"bin2", "set binary value",   OFFSET(binary2),  AV_OPT_TYPE_BINARY,   {.str=""},         0,        0, 1 },
+{"num64",    "set num 64bit",  OFFSET(num64),    AV_OPT_TYPE_INT64,    {.i64 = 1},        0,        100, 1 },
+{"flt",      "set float",      OFFSET(flt),      AV_OPT_TYPE_FLOAT,    {.dbl = 1.0/3},    0,        100, 1},
+{"dbl",      "set double",     OFFSET(dbl),      AV_OPT_TYPE_DOUBLE,   {.dbl = 1.0/3},    0,        100, 1 },
 {NULL},
 };
 
@@ -1964,10 +1964,18 @@
     test_options
 };
 
+static void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
+{
+    vfprintf(stdout, fmt, vl);
+}
+
 int main(void)
 {
     int i;
 
+    av_log_set_level(AV_LOG_DEBUG);
+    av_log_set_callback(log_callback_help);
+
     printf("Testing default values\n");
     {
         TestContext test_ctx = { 0 };
@@ -1993,6 +2001,9 @@
         printf("num64=%"PRId64"\n", test_ctx.num64);
         printf("flt=%.6f\n", test_ctx.flt);
         printf("dbl=%.6f\n", test_ctx.dbl);
+
+        av_opt_show2(&test_ctx, NULL, -1, 0);
+
         av_opt_free(&test_ctx);
     }
 
@@ -2112,11 +2123,15 @@
         av_log_set_level(AV_LOG_QUIET);
 
         for (i=0; i < FF_ARRAY_ELEMS(options); i++) {
+            int silence_log = !strcmp(options[i], "rational=-1/0"); // inf formating differs between platforms
             av_log(&test_ctx, AV_LOG_DEBUG, "Setting options string '%s'\n", options[i]);
+            if (silence_log)
+                av_log_set_callback(NULL);
             if (av_set_options_string(&test_ctx, options[i], "=", ":") < 0)
                 printf("Error '%s'\n", options[i]);
             else
                 printf("OK    '%s'\n", options[i]);
+            av_log_set_callback(log_callback_help);
         }
         av_opt_free(&test_ctx);
     }
diff --git a/libavutil/parseutils.c b/libavutil/parseutils.c
index 4708699..8cd844e 100644
--- a/libavutil/parseutils.c
+++ b/libavutil/parseutils.c
@@ -62,12 +62,12 @@
     return 0;
 }
 
-typedef struct {
+typedef struct VideoSizeAbbr {
     const char *abbr;
     int width, height;
 } VideoSizeAbbr;
 
-typedef struct {
+typedef struct VideoRateAbbr {
     const char *abbr;
     AVRational rate;
 } VideoRateAbbr;
@@ -186,7 +186,7 @@
     return 0;
 }
 
-typedef struct {
+typedef struct ColorEntry {
     const char *name;            ///< a string representing the name of the color
     uint8_t     rgb_color[3];    ///< RGB values for the color
 } ColorEntry;
diff --git a/libavutil/pixdesc.c b/libavutil/pixdesc.c
index 648d014..5316ba4 100644
--- a/libavutil/pixdesc.c
+++ b/libavutil/pixdesc.c
@@ -1721,7 +1721,8 @@
             { 1, 0, 1, 0, 7 },        /* B */
             { 3, 0, 1, 0, 7 },        /* A */
         },
-        .flags = AV_PIX_FMT_FLAG_PLANAR | AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_ALPHA,
+        .flags = AV_PIX_FMT_FLAG_PLANAR | AV_PIX_FMT_FLAG_RGB |
+                 AV_PIX_FMT_FLAG_ALPHA,
     },
     [AV_PIX_FMT_GBRAP16LE] = {
         .name = "gbrap16le",
@@ -1734,7 +1735,8 @@
             { 1, 1, 1, 0, 15 },       /* B */
             { 3, 1, 1, 0, 15 },       /* A */
         },
-        .flags = AV_PIX_FMT_FLAG_PLANAR | AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_ALPHA,
+        .flags = AV_PIX_FMT_FLAG_PLANAR | AV_PIX_FMT_FLAG_RGB |
+                 AV_PIX_FMT_FLAG_ALPHA,
     },
     [AV_PIX_FMT_GBRAP16BE] = {
         .name = "gbrap16be",
@@ -1747,7 +1749,8 @@
             { 1, 1, 1, 0, 15 },       /* B */
             { 3, 1, 1, 0, 15 },       /* A */
         },
-        .flags = AV_PIX_FMT_FLAG_BE | AV_PIX_FMT_FLAG_PLANAR | AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_ALPHA,
+        .flags = AV_PIX_FMT_FLAG_BE | AV_PIX_FMT_FLAG_PLANAR |
+                 AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_ALPHA,
     },
     [AV_PIX_FMT_VDPAU] = {
         .name = "vdpau",
@@ -1900,6 +1903,10 @@
         .name = "vda",
         .flags = AV_PIX_FMT_FLAG_HWACCEL,
     },
+    [AV_PIX_FMT_QSV] = {
+        .name = "qsv",
+        .flags = AV_PIX_FMT_FLAG_HWACCEL,
+    },
 };
 
 static const char *color_range_names[AVCOL_RANGE_NB] = {
@@ -2049,7 +2056,6 @@
 
     return desc - av_pix_fmt_descriptors;
 }
-FF_ENABLE_DEPRECATION_WARNINGS
 
 int av_pix_fmt_get_chroma_sub_sample(enum AVPixelFormat pix_fmt,
                                      int *h_shift, int *v_shift)
@@ -2118,6 +2124,7 @@
         }
     }
 }
+FF_ENABLE_DEPRECATION_WARNINGS
 
 
 enum AVPixelFormat av_pix_fmt_swap_endianness(enum AVPixelFormat pix_fmt)
diff --git a/libavutil/pixdesc.h b/libavutil/pixdesc.h
index 705377d..78f8d55 100644
--- a/libavutil/pixdesc.h
+++ b/libavutil/pixdesc.h
@@ -93,9 +93,9 @@
      * Parameters that describe how pixels are packed.
      * If the format has 2 or 4 components, then alpha is last.
      * If the format has 1 or 2 components, then luma is 0.
-     * If the format has 3 or 4 components,
-     * if the RGB flag is set then 0 is red, 1 is green and 2 is blue;
-     * otherwise 0 is luma, 1 is chroma-U and 2 is chroma-V.
+     * If the format has 3 or 4 components:
+     *   if the RGB flag is set then 0 is red, 1 is green and 2 is blue;
+     *   otherwise 0 is luma, 1 is chroma-U and 2 is chroma-V.
      */
     AVComponentDescriptor comp[4];
 
@@ -139,8 +139,19 @@
  * An example of a pseudo-paletted format is AV_PIX_FMT_GRAY8
  */
 #define AV_PIX_FMT_FLAG_PSEUDOPAL    (1 << 6)
+
 /**
- * The pixel format has an alpha channel.
+ * The pixel format has an alpha channel. This is set on all formats that
+ * support alpha in some way. The exception is AV_PIX_FMT_PAL8, which can
+ * carry alpha as part of the palette. Details are explained in the
+ * AVPixelFormat enum, and are also encoded in the corresponding
+ * AVPixFmtDescriptor.
+ *
+ * The alpha is always straight, never pre-multiplied.
+ *
+ * If a codec or a filter does not support alpha, it should set all alpha to
+ * opaque, or use the equivalent pixel formats without alpha component, e.g.
+ * AV_PIX_FMT_RGB0 (or AV_PIX_FMT_RGB24 etc.) instead of AV_PIX_FMT_RGBA.
  */
 #define AV_PIX_FMT_FLAG_ALPHA        (1 << 7)
 
@@ -299,8 +310,6 @@
  */
 int av_pix_fmt_count_planes(enum AVPixelFormat pix_fmt);
 
-void ff_check_pixfmt_descriptors(void);
-
 /**
  * Utility function to swap the endianness of a pixel format.
  *
diff --git a/libavutil/pixelutils.c b/libavutil/pixelutils.c
index 8f04024..1ec4fbb 100644
--- a/libavutil/pixelutils.c
+++ b/libavutil/pixelutils.c
@@ -19,6 +19,7 @@
 #include "config.h"
 #include "common.h"
 #include "pixelutils.h"
+#include "internal.h"
 
 #if CONFIG_PIXELUTILS
 
@@ -151,6 +152,8 @@
         goto end;
     }
 
+    ff_check_pixfmt_descriptors();
+
 #define RANDOM_INIT(buf, size) do {             \
     int k;                                      \
     for (k = 0; k < size; k++) {                \
diff --git a/libavutil/pixfmt.h b/libavutil/pixfmt.h
index ef1837f..50403d7 100644
--- a/libavutil/pixfmt.h
+++ b/libavutil/pixfmt.h
@@ -44,11 +44,11 @@
  * big-endian CPUs.
  *
  * @par
- * When the pixel format is palettized RGB (AV_PIX_FMT_PAL8), the palettized
+ * When the pixel format is palettized RGB32 (AV_PIX_FMT_PAL8), the palettized
  * image data is stored in AVFrame.data[0]. The palette is transported in
  * AVFrame.data[1], is 1024 bytes long (256 4-byte entries) and is
  * formatted the same as in AV_PIX_FMT_RGB32 described above (i.e., it is
- * also endian-specific). Note also that the individual RGB palette
+ * also endian-specific). Note also that the individual RGB32 palette
  * components stored in AVFrame.data[1] should be in the range 0..255.
  * This is important as many custom PAL8 video codecs that were designed
  * to run on the IBM VGA graphics adapter use 6-bit palette components.
@@ -76,10 +76,10 @@
     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_PAL8,      ///< 8 bit with AV_PIX_FMT_RGB32 palette
+    AV_PIX_FMT_YUVJ420P,  ///< planar YUV 4:2:0, 12bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV420P and setting color_range
+    AV_PIX_FMT_YUVJ422P,  ///< planar YUV 4:2:2, 16bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV422P and setting color_range
+    AV_PIX_FMT_YUVJ444P,  ///< planar YUV 4:4:4, 24bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV444P and setting color_range
 #if FF_API_XVMC
     AV_PIX_FMT_XVMC_MPEG2_MC,///< XVideo Motion Acceleration via common packet passing
     AV_PIX_FMT_XVMC_MPEG2_IDCT,
@@ -104,7 +104,7 @@
     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_YUVJ440P,  ///< planar YUV 4:4:0 full scale (JPEG), deprecated in favor of AV_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)
 #if FF_API_VDPAU
     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
@@ -118,13 +118,13 @@
 
     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
+    AV_PIX_FMT_RGB555BE,  ///< packed RGB 5:5:5, 16bpp, (msb)1X 5R 5G 5B(lsb), big-endian   , X=unused/undefined
+    AV_PIX_FMT_RGB555LE,  ///< packed RGB 5:5:5, 16bpp, (msb)1X 5R 5G 5B(lsb), little-endian, X=unused/undefined
 
     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
+    AV_PIX_FMT_BGR555BE,  ///< packed BGR 5:5:5, 16bpp, (msb)1X 5B 5G 5R(lsb), big-endian   , X=unused/undefined
+    AV_PIX_FMT_BGR555LE,  ///< packed BGR 5:5:5, 16bpp, (msb)1X 5B 5G 5R(lsb), little-endian, X=unused/undefined
 
     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
@@ -141,10 +141,10 @@
 #endif
     AV_PIX_FMT_DXVA2_VLD,    ///< HW decoding through DXVA2, Picture.data[3] contains a LPDIRECT3DSURFACE9 pointer
 
-    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_RGB444LE,  ///< packed RGB 4:4:4, 16bpp, (msb)4X 4R 4G 4B(lsb), little-endian, X=unused/undefined
+    AV_PIX_FMT_RGB444BE,  ///< packed RGB 4:4:4, 16bpp, (msb)4X 4R 4G 4B(lsb), big-endian,    X=unused/undefined
+    AV_PIX_FMT_BGR444LE,  ///< packed BGR 4:4:4, 16bpp, (msb)4X 4B 4G 4R(lsb), little-endian, X=unused/undefined
+    AV_PIX_FMT_BGR444BE,  ///< packed BGR 4:4:4, 16bpp, (msb)4X 4B 4G 4R(lsb), big-endian,    X=unused/undefined
     AV_PIX_FMT_YA8,       ///< 8bit gray, 8bit alpha
 
     AV_PIX_FMT_Y400A = AV_PIX_FMT_YA8, ///< alias for AV_PIX_FMT_YA8
@@ -247,7 +247,11 @@
     AV_PIX_FMT_GBRAP_LIBAV,        ///< planar GBRA 4:4:4:4 32bpp
     AV_PIX_FMT_GBRAP16BE_LIBAV,    ///< planar GBRA 4:4:4:4 64bpp, big-endian
     AV_PIX_FMT_GBRAP16LE_LIBAV,    ///< planar GBRA 4:4:4:4 64bpp, little-endian
-
+    /**
+     *  HW acceleration through QSV, data[3] contains a pointer to the
+     *  mfxFrameSurface1 structure.
+     */
+    AV_PIX_FMT_QSV,
 
 #ifndef AV_PIX_FMT_ABI_GIT_MASTER
     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
@@ -255,10 +259,10 @@
     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
-    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_0RGB=0x123+4,///< packed RGB 8:8:8, 32bpp, XRGBXRGB...   X=unused/undefined
+    AV_PIX_FMT_RGB0,        ///< packed RGB 8:8:8, 32bpp, RGBXRGBX...   X=unused/undefined
+    AV_PIX_FMT_0BGR,        ///< packed BGR 8:8:8, 32bpp, XBGRXBGR...   X=unused/undefined
+    AV_PIX_FMT_BGR0,        ///< packed BGR 8:8:8, 32bpp, BGRXBGRX...   X=unused/undefined
     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)
 
@@ -281,7 +285,7 @@
     AV_PIX_FMT_GBRAP,       ///< planar GBRA 4:4:4:4 32bpp
     AV_PIX_FMT_GBRAP16BE,   ///< planar GBRA 4:4:4:4 64bpp, big-endian
     AV_PIX_FMT_GBRAP16LE,   ///< planar GBRA 4:4:4:4 64bpp, little-endian
-    AV_PIX_FMT_YUVJ411P,    ///< planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples) full scale (JPEG), deprecated in favor of PIX_FMT_YUV411P and setting color_range
+    AV_PIX_FMT_YUVJ411P,    ///< planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples) full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV411P and setting color_range
 
     AV_PIX_FMT_BAYER_BGGR8,    ///< bayer, BGBG..(odd line), GRGR..(even line), 8-bit samples */
     AV_PIX_FMT_BAYER_RGGB8,    ///< bayer, RGRG..(odd line), GBGB..(even line), 8-bit samples */
diff --git a/libavutil/ppc/intreadwrite.h b/libavutil/ppc/intreadwrite.h
index 1ec349e..7671676 100644
--- a/libavutil/ppc/intreadwrite.h
+++ b/libavutil/ppc/intreadwrite.h
@@ -24,20 +24,6 @@
 #include <stdint.h>
 #include "config.h"
 
-/*
- * -O0 would compile the packed struct version, which is used by
- * default, in an overly verbose fashion, so we override it here.
- */
-#if HAVE_BIGENDIAN
-#define AV_RB64(p) (*(const uint64_t *)(p))
-#define AV_WB64(p, v) (*(uint64_t *)(p) = (v))
-
-#else
-#define AV_RL64(p) (*(const uint64_t *)(p))
-#define AV_WL64(p, v) (*(uint64_t *)(p) = (v))
-
-#endif
-
 #if HAVE_XFORM_ASM
 
 #if HAVE_BIGENDIAN
diff --git a/libavutil/sha.c b/libavutil/sha.c
index 0cf9424..9963043 100644
--- a/libavutil/sha.c
+++ b/libavutil/sha.c
@@ -51,13 +51,13 @@
 
 /* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */
 #define blk0(i) (block[i] = AV_RB32(buffer + 4 * (i)))
-#define blk(i)  (block[i] = rol(block[i-3] ^ block[i-8] ^ block[i-14] ^ block[i-16], 1))
+#define blk(i)  (block[i] = rol(block[(i)-3] ^ block[(i)-8] ^ block[(i)-14] ^ block[(i)-16], 1))
 
-#define R0(v,w,x,y,z,i) z += ((w&(x^y))^y)     + blk0(i) + 0x5A827999 + rol(v, 5); w = rol(w, 30);
-#define R1(v,w,x,y,z,i) z += ((w&(x^y))^y)     + blk (i) + 0x5A827999 + rol(v, 5); w = rol(w, 30);
-#define R2(v,w,x,y,z,i) z += ( w^x     ^y)     + blk (i) + 0x6ED9EBA1 + rol(v, 5); w = rol(w, 30);
-#define R3(v,w,x,y,z,i) z += (((w|x)&y)|(w&x)) + blk (i) + 0x8F1BBCDC + rol(v, 5); w = rol(w, 30);
-#define R4(v,w,x,y,z,i) z += ( w^x     ^y)     + blk (i) + 0xCA62C1D6 + rol(v, 5); w = rol(w, 30);
+#define R0(v,w,x,y,z,i) z += (((w)&((x)^(y)))^(y))       + blk0(i) + 0x5A827999 + rol(v, 5); w = rol(w, 30);
+#define R1(v,w,x,y,z,i) z += (((w)&((x)^(y)))^(y))       + blk (i) + 0x5A827999 + rol(v, 5); w = rol(w, 30);
+#define R2(v,w,x,y,z,i) z += ( (w)^(x)       ^(y))       + blk (i) + 0x6ED9EBA1 + rol(v, 5); w = rol(w, 30);
+#define R3(v,w,x,y,z,i) z += ((((w)|(x))&(y))|((w)&(x))) + blk (i) + 0x8F1BBCDC + rol(v, 5); w = rol(w, 30);
+#define R4(v,w,x,y,z,i) z += ( (w)^(x)       ^(y))       + blk (i) + 0xCA62C1D6 + rol(v, 5); w = rol(w, 30);
 
 /* Hash a single 512-bit block. This is the core of the algorithm. */
 
diff --git a/libavutil/twofish.c b/libavutil/twofish.c
index 337c099..f735a1f 100644
--- a/libavutil/twofish.c
+++ b/libavutil/twofish.c
@@ -30,6 +30,10 @@
     uint32_t K[40];
     uint32_t S[4];
     int ksize;
+    uint32_t MDS1[256];
+    uint32_t MDS2[256];
+    uint32_t MDS3[256];
+    uint32_t MDS4[256];
 } AVTWOFISH;
 
 static const uint8_t MD1[256] = {
@@ -142,10 +146,9 @@
     return AV_RL32(s);
 }
 
-static uint32_t tf_h(uint32_t X, uint32_t L[4], int k)
+static void tf_h0(uint8_t y[4], uint32_t L[4], int k)
 {
-    uint8_t y[4], l[4];
-    AV_WL32(y, X);
+    uint8_t l[4];
     if (k == 4) {
         AV_WL32(l, L[3]);
         y[0] = q1[y[0]] ^ l[0];
@@ -165,6 +168,13 @@
     y[1] = q0[q0[q1[y[1]] ^ l[1]] ^ ((L[0] >> 8) & 0xff)];
     y[2] = q1[q1[q0[y[2]] ^ l[2]] ^ ((L[0] >> 16) & 0xff)];
     y[3] = q0[q1[q1[y[3]] ^ l[3]] ^ (L[0] >> 24)];
+}
+
+static uint32_t tf_h(uint32_t X, uint32_t L[4], int k)
+{
+    uint8_t y[4], l[4];
+    AV_WL32(y, X);
+    tf_h0(y, L, k);
 
     l[0] = y[0] ^ MD2[y[1]] ^ MD1[y[2]] ^ MD1[y[3]];
     l[1] = MD1[y[0]] ^ MD2[y[1]] ^ MD2[y[2]] ^ y[3];
@@ -174,6 +184,25 @@
     return AV_RL32(l);
 }
 
+static uint32_t MDS_mul(AVTWOFISH *cs, uint32_t X)
+{
+    return cs->MDS1[(X) & 0xff] ^ cs->MDS2[((X) >> 8) & 0xff] ^ cs->MDS3[((X) >> 16) & 0xff] ^ cs->MDS4[(X) >> 24];
+}
+
+static void precomputeMDS(AVTWOFISH *cs)
+{
+    uint8_t y[4];
+    int i;
+    for (i = 0; i < 256; i++) {
+        y[0] = y[1] = y[2] = y[3] = i;
+    tf_h0(y, cs->S, cs->ksize);
+        cs->MDS1[i] = ((uint32_t)y[0]) ^ ((uint32_t)MD1[y[0]] << 8) ^ ((uint32_t)MD2[y[0]] << 16) ^ ((uint32_t)MD2[y[0]] << 24);
+        cs->MDS2[i] = ((uint32_t)MD2[y[1]]) ^ ((uint32_t)MD2[y[1]] << 8) ^ ((uint32_t)MD1[y[1]] << 16) ^ ((uint32_t)y[1] << 24);
+        cs->MDS3[i] = ((uint32_t)MD1[y[2]]) ^ ((uint32_t)MD2[y[2]] << 8) ^ ((uint32_t)y[2] << 16) ^ ((uint32_t)MD2[y[2]] << 24);
+        cs->MDS4[i] = ((uint32_t)MD1[y[3]]) ^ ((uint32_t)y[3] << 8) ^ ((uint32_t)MD2[y[3]] << 16) ^ ((uint32_t)MD1[y[3]] << 24);
+    }
+}
+
 static void twofish_encrypt(AVTWOFISH *cs, uint8_t *dst, const uint8_t *src)
 {
     uint32_t P[4], t0, t1;
@@ -183,12 +212,12 @@
     P[2] = AV_RL32(src + 8) ^ cs->K[2];
     P[3] = AV_RL32(src + 12) ^ cs->K[3];
     for (i = 0; i < 16; i += 2) {
-        t0 = tf_h(P[0], cs->S, cs->ksize);
-        t1 = tf_h(LR(P[1], 8), cs->S, cs->ksize);
+        t0 = MDS_mul(cs, P[0]);
+        t1 = MDS_mul(cs, LR(P[1], 8));
         P[2] = RR(P[2] ^ (t0 + t1 + cs->K[2 * i + 8]), 1);
         P[3] = LR(P[3], 1) ^ (t0 + 2 * t1 + cs->K[2 * i + 9]);
-        t0 = tf_h(P[2], cs->S, cs->ksize);
-        t1 = tf_h(LR(P[3], 8), cs->S, cs->ksize);
+        t0 = MDS_mul(cs, P[2]);
+        t1 = MDS_mul(cs, LR(P[3], 8));
         P[0] = RR(P[0] ^ (t0 + t1 + cs->K[2 * i + 10]), 1);
         P[1] = LR(P[1], 1) ^ (t0 + 2 * t1 + cs->K[2 * i + 11]);
     }
@@ -211,12 +240,12 @@
     P[0] = AV_RL32(src + 8) ^ cs->K[6];
     P[1] = AV_RL32(src + 12) ^ cs->K[7];
     for (i = 15; i >= 0; i -= 2) {
-        t0 = tf_h(P[2], cs->S, cs->ksize);
-        t1 = tf_h(LR(P[3], 8), cs->S, cs->ksize);
+        t0 = MDS_mul(cs, P[2]);
+        t1 = MDS_mul(cs, LR(P[3], 8));
         P[0] = LR(P[0], 1) ^ (t0 + t1 + cs->K[2 * i + 8]);
         P[1] = RR(P[1] ^ (t0 + 2 * t1 + cs->K[2 * i + 9]), 1);
-        t0 = tf_h(P[0], cs->S, cs->ksize);
-        t1 = tf_h(LR(P[1], 8), cs->S, cs->ksize);
+        t0 = MDS_mul(cs, P[0]);
+        t1 = MDS_mul(cs, LR(P[1], 8));
         P[2] = LR(P[2], 1) ^ (t0 + t1 + cs->K[2 * i + 6]);
         P[3] = RR(P[3] ^ (t0 + 2 * t1 + cs->K[2 * i + 7]), 1);
     }
@@ -265,6 +294,7 @@
         Mo[i] = Key[2 * i + 1];
         cs->S[cs->ksize - i - 1] = tf_RS(Me[i], Mo[i]);
     }
+    precomputeMDS(cs);
     for (i = 0; i < 20; i++) {
         A = tf_h((2 * i) * rho, Me, cs->ksize);
         B = tf_h((2 * i + 1) * rho, Mo, cs->ksize);
diff --git a/libavutil/utils.c b/libavutil/utils.c
index da8b5ae..0b765ed 100644
--- a/libavutil/utils.c
+++ b/libavutil/utils.c
@@ -20,7 +20,7 @@
 #include "avutil.h"
 #include "avassert.h"
 #include "samplefmt.h"
-#include "pixdesc.h"
+#include "internal.h"
 
 /**
  * @file
@@ -54,9 +54,6 @@
         av_log(NULL, AV_LOG_ERROR, "Libavutil has been linked to a broken llrint()\n");
     }
 
-#if defined(ASSERT_LEVEL) && ASSERT_LEVEL > 0
-    ff_check_pixfmt_descriptors();
-#endif
     checks_done = 1;
     return LIBAVUTIL_VERSION_INT;
 }
diff --git a/libavutil/version.h b/libavutil/version.h
index 053bd99..897384a 100644
--- a/libavutil/version.h
+++ b/libavutil/version.h
@@ -32,7 +32,7 @@
  * @{
  */
 
-#define AV_VERSION_INT(a, b, c) (a<<16 | b<<8 | c)
+#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)
 
@@ -56,8 +56,8 @@
  */
 
 #define LIBAVUTIL_VERSION_MAJOR  54
-#define LIBAVUTIL_VERSION_MINOR  18
-#define LIBAVUTIL_VERSION_MICRO 100
+#define LIBAVUTIL_VERSION_MINOR  20
+#define LIBAVUTIL_VERSION_MICRO 101
 
 #define LIBAVUTIL_VERSION_INT   AV_VERSION_INT(LIBAVUTIL_VERSION_MAJOR, \
                                                LIBAVUTIL_VERSION_MINOR, \
diff --git a/libavutil/x86/intmath.h b/libavutil/x86/intmath.h
new file mode 100644
index 0000000..c42fa83
--- /dev/null
+++ b/libavutil/x86/intmath.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2015 James Almer
+ *
+ * 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
+
+#include <stdint.h>
+#include "config.h"
+
+#if defined(__GNUC__)
+
+/* Our generic version of av_popcount is faster than GCC's built-in on
+ * CPUs that don't support the popcnt instruction.
+ */
+#if defined(__POPCNT__)
+    #define av_popcount   __builtin_popcount
+#if ARCH_X86_64
+    #define av_popcount64 __builtin_popcountll
+#endif
+
+#endif /* __POPCNT__ */
+
+#if defined(__BMI2__)
+
+#define av_mod_uintp2 av_mod_uintp2_bmi2
+static av_always_inline av_const unsigned av_mod_uintp2_bmi2(unsigned a, unsigned p)
+{
+    if (av_builtin_constant_p(p))
+        return a & ((1 << p) - 1);
+    else {
+        unsigned x;
+        __asm__ ("bzhi %2, %1, %0 \n\t" : "=r"(x) : "rm"(a), "r"(p));
+        return x;
+    }
+}
+
+#endif /* __BMI2__ */
+
+#endif /* __GNUC__ */
+
+#endif /* AVUTIL_X86_INTMATH_H */
diff --git a/libavutil/x86/pixelutils_init.c b/libavutil/x86/pixelutils_init.c
index d600510..c24a533 100644
--- a/libavutil/x86/pixelutils_init.c
+++ b/libavutil/x86/pixelutils_init.c
@@ -43,6 +43,12 @@
         sad[2] = ff_pixelutils_sad_8x8_mmx;
     }
 
+    // The best way to use SSE2 would be to do 2 SADs in parallel,
+    // but we'd have to modify the pixelutils API to return SIMD functions.
+
+    // It's probably not faster to shuffle data around
+    // to get two lines of 8 pixels into a single 16byte register,
+    // so just use the MMX 8x8 version even when SSE2 is available.
     if (EXTERNAL_MMXEXT(cpu_flags)) {
         sad[2] = ff_pixelutils_sad_8x8_mmxext;
         sad[3] = ff_pixelutils_sad_16x16_mmxext;
diff --git a/libavutil/x86/x86inc.asm b/libavutil/x86/x86inc.asm
index 8a13064..f1b4b85 100644
--- a/libavutil/x86/x86inc.asm
+++ b/libavutil/x86/x86inc.asm
@@ -856,14 +856,6 @@
     INIT_CPUFLAGS %1
 %endmacro
 
-; FIXME: INIT_AVX can be replaced by INIT_XMM avx
-%macro INIT_AVX 0
-    INIT_XMM
-    %assign avx_enabled 1
-    %define PALIGNR PALIGNR_SSSE3
-    %define RESET_MM_PERMUTATION INIT_AVX
-%endmacro
-
 %macro INIT_YMM 0-1+
     %assign avx_enabled 1
     %define RESET_MM_PERMUTATION INIT_YMM %1
@@ -879,7 +871,7 @@
     %assign %%i 0
     %rep num_mmregs
     CAT_XDEFINE m, %%i, ymm %+ %%i
-    CAT_XDEFINE nymm, %%i, %%i
+    CAT_XDEFINE nnymm, %%i, %%i
     %assign %%i %%i+1
     %endrep
     INIT_CPUFLAGS %1
@@ -1055,15 +1047,16 @@
 %endmacro
 
 ;%1 == instruction
-;%2 == 1 if float, 0 if int
-;%3 == 1 if non-destructive or 4-operand (xmm, xmm, xmm, imm), 0 otherwise
-;%4 == 1 if commutative (i.e. doesn't matter which src arg is which), 0 if not
-;%5+: operands
-%macro RUN_AVX_INSTR 5-8+
-    %ifnum sizeof%6
+;%2 == minimal instruction set
+;%3 == 1 if float, 0 if int
+;%4 == 1 if non-destructive or 4-operand (xmm, xmm, xmm, imm), 0 otherwise
+;%5 == 1 if commutative (i.e. doesn't matter which src arg is which), 0 if not
+;%6+: operands
+%macro RUN_AVX_INSTR 6-9+
+    %ifnum sizeof%7
+        %assign __sizeofreg sizeof%7
+    %elifnum sizeof%6
         %assign __sizeofreg sizeof%6
-    %elifnum sizeof%5
-        %assign __sizeofreg sizeof%5
     %else
         %assign __sizeofreg mmsize
     %endif
@@ -1072,325 +1065,335 @@
         %xdefine __instr v%1
     %else
         %xdefine __instr %1
-        %if %0 >= 7+%3
+        %if %0 >= 8+%4
             %assign __emulate_avx 1
         %endif
     %endif
+    %ifnidn %2, fnord
+        %ifdef cpuname
+            %if notcpuflag(%2)
+                %error use of ``%1'' %2 instruction in cpuname function: current_function
+            %elif cpuflags_%2 < cpuflags_sse && notcpuflag(sse2) && __sizeofreg > 8
+                %error use of ``%1'' sse2 instruction in cpuname function: current_function
+            %endif
+        %endif
+    %endif
 
     %if __emulate_avx
-        %xdefine __src1 %6
-        %xdefine __src2 %7
-        %ifnidn %5, %6
-            %if %0 >= 8
-                CHECK_AVX_INSTR_EMU {%1 %5, %6, %7, %8}, %5, %7, %8
+        %xdefine __src1 %7
+        %xdefine __src2 %8
+        %ifnidn %6, %7
+            %if %0 >= 9
+                CHECK_AVX_INSTR_EMU {%1 %6, %7, %8, %9}, %6, %8, %9
             %else
-                CHECK_AVX_INSTR_EMU {%1 %5, %6, %7}, %5, %7
+                CHECK_AVX_INSTR_EMU {%1 %6, %7, %8}, %6, %8
             %endif
-            %if %4 && %3 == 0
-                %ifnid %7
+            %if %5 && %4 == 0
+                %ifnid %8
                     ; 3-operand AVX instructions with a memory arg can only have it in src2,
                     ; whereas SSE emulation prefers to have it in src1 (i.e. the mov).
                     ; So, if the instruction is commutative with a memory arg, swap them.
-                    %xdefine __src1 %7
-                    %xdefine __src2 %6
+                    %xdefine __src1 %8
+                    %xdefine __src2 %7
                 %endif
             %endif
             %if __sizeofreg == 8
-                MOVQ %5, __src1
-            %elif %2
-                MOVAPS %5, __src1
+                MOVQ %6, __src1
+            %elif %3
+                MOVAPS %6, __src1
             %else
-                MOVDQA %5, __src1
+                MOVDQA %6, __src1
             %endif
         %endif
-        %if %0 >= 8
-            %1 %5, __src2, %8
+        %if %0 >= 9
+            %1 %6, __src2, %9
         %else
-            %1 %5, __src2
+            %1 %6, __src2
         %endif
-    %elif %0 >= 8
-        __instr %5, %6, %7, %8
+    %elif %0 >= 9
+        __instr %6, %7, %8, %9
+    %elif %0 == 8
+        __instr %6, %7, %8
     %elif %0 == 7
-        __instr %5, %6, %7
-    %elif %0 == 6
-        __instr %5, %6
+        __instr %6, %7
     %else
-        __instr %5
+        __instr %6
     %endif
 %endmacro
 
 ;%1 == instruction
-;%2 == 1 if float, 0 if int
-;%3 == 1 if non-destructive or 4-operand (xmm, xmm, xmm, imm), 0 otherwise
-;%4 == 1 if commutative (i.e. doesn't matter which src arg is which), 0 if not
-%macro AVX_INSTR 1-4 0, 1, 0
-    %macro %1 1-9 fnord, fnord, fnord, fnord, %1, %2, %3, %4
+;%2 == minimal instruction set
+;%3 == 1 if float, 0 if int
+;%4 == 1 if non-destructive or 4-operand (xmm, xmm, xmm, imm), 0 otherwise
+;%5 == 1 if commutative (i.e. doesn't matter which src arg is which), 0 if not
+%macro AVX_INSTR 1-5 fnord, 0, 1, 0
+    %macro %1 1-10 fnord, fnord, fnord, fnord, %1, %2, %3, %4, %5
         %ifidn %2, fnord
-            RUN_AVX_INSTR %6, %7, %8, %9, %1
+            RUN_AVX_INSTR %6, %7, %8, %9, %10, %1
         %elifidn %3, fnord
-            RUN_AVX_INSTR %6, %7, %8, %9, %1, %2
+            RUN_AVX_INSTR %6, %7, %8, %9, %10, %1, %2
         %elifidn %4, fnord
-            RUN_AVX_INSTR %6, %7, %8, %9, %1, %2, %3
+            RUN_AVX_INSTR %6, %7, %8, %9, %10, %1, %2, %3
         %elifidn %5, fnord
-            RUN_AVX_INSTR %6, %7, %8, %9, %1, %2, %3, %4
+            RUN_AVX_INSTR %6, %7, %8, %9, %10, %1, %2, %3, %4
         %else
-            RUN_AVX_INSTR %6, %7, %8, %9, %1, %2, %3, %4, %5
+            RUN_AVX_INSTR %6, %7, %8, %9, %10, %1, %2, %3, %4, %5
         %endif
     %endmacro
 %endmacro
 
 ; Instructions with both VEX and non-VEX encodings
 ; Non-destructive instructions are written without parameters
-AVX_INSTR addpd, 1, 0, 1
-AVX_INSTR addps, 1, 0, 1
-AVX_INSTR addsd, 1, 0, 1
-AVX_INSTR addss, 1, 0, 1
-AVX_INSTR addsubpd, 1, 0, 0
-AVX_INSTR addsubps, 1, 0, 0
-AVX_INSTR aesdec, 0, 0, 0
-AVX_INSTR aesdeclast, 0, 0, 0
-AVX_INSTR aesenc, 0, 0, 0
-AVX_INSTR aesenclast, 0, 0, 0
+AVX_INSTR addpd, sse2, 1, 0, 1
+AVX_INSTR addps, sse, 1, 0, 1
+AVX_INSTR addsd, sse2, 1, 0, 1
+AVX_INSTR addss, sse, 1, 0, 1
+AVX_INSTR addsubpd, sse3, 1, 0, 0
+AVX_INSTR addsubps, sse3, 1, 0, 0
+AVX_INSTR aesdec, fnord, 0, 0, 0
+AVX_INSTR aesdeclast, fnord, 0, 0, 0
+AVX_INSTR aesenc, fnord, 0, 0, 0
+AVX_INSTR aesenclast, fnord, 0, 0, 0
 AVX_INSTR aesimc
 AVX_INSTR aeskeygenassist
-AVX_INSTR andnpd, 1, 0, 0
-AVX_INSTR andnps, 1, 0, 0
-AVX_INSTR andpd, 1, 0, 1
-AVX_INSTR andps, 1, 0, 1
-AVX_INSTR blendpd, 1, 0, 0
-AVX_INSTR blendps, 1, 0, 0
-AVX_INSTR blendvpd, 1, 0, 0
-AVX_INSTR blendvps, 1, 0, 0
-AVX_INSTR cmppd, 1, 1, 0
-AVX_INSTR cmpps, 1, 1, 0
-AVX_INSTR cmpsd, 1, 1, 0
-AVX_INSTR cmpss, 1, 1, 0
-AVX_INSTR comisd
-AVX_INSTR comiss
-AVX_INSTR cvtdq2pd
-AVX_INSTR cvtdq2ps
-AVX_INSTR cvtpd2dq
-AVX_INSTR cvtpd2ps
-AVX_INSTR cvtps2dq
-AVX_INSTR cvtps2pd
-AVX_INSTR cvtsd2si
-AVX_INSTR cvtsd2ss
-AVX_INSTR cvtsi2sd
-AVX_INSTR cvtsi2ss
-AVX_INSTR cvtss2sd
-AVX_INSTR cvtss2si
-AVX_INSTR cvttpd2dq
-AVX_INSTR cvttps2dq
-AVX_INSTR cvttsd2si
-AVX_INSTR cvttss2si
-AVX_INSTR divpd, 1, 0, 0
-AVX_INSTR divps, 1, 0, 0
-AVX_INSTR divsd, 1, 0, 0
-AVX_INSTR divss, 1, 0, 0
-AVX_INSTR dppd, 1, 1, 0
-AVX_INSTR dpps, 1, 1, 0
-AVX_INSTR extractps
-AVX_INSTR haddpd, 1, 0, 0
-AVX_INSTR haddps, 1, 0, 0
-AVX_INSTR hsubpd, 1, 0, 0
-AVX_INSTR hsubps, 1, 0, 0
-AVX_INSTR insertps, 1, 1, 0
-AVX_INSTR lddqu
-AVX_INSTR ldmxcsr
-AVX_INSTR maskmovdqu
-AVX_INSTR maxpd, 1, 0, 1
-AVX_INSTR maxps, 1, 0, 1
-AVX_INSTR maxsd, 1, 0, 1
-AVX_INSTR maxss, 1, 0, 1
-AVX_INSTR minpd, 1, 0, 1
-AVX_INSTR minps, 1, 0, 1
-AVX_INSTR minsd, 1, 0, 1
-AVX_INSTR minss, 1, 0, 1
-AVX_INSTR movapd
-AVX_INSTR movaps
-AVX_INSTR movd
-AVX_INSTR movddup
-AVX_INSTR movdqa
-AVX_INSTR movdqu
-AVX_INSTR movhlps, 1, 0, 0
-AVX_INSTR movhpd, 1, 0, 0
-AVX_INSTR movhps, 1, 0, 0
-AVX_INSTR movlhps, 1, 0, 0
-AVX_INSTR movlpd, 1, 0, 0
-AVX_INSTR movlps, 1, 0, 0
-AVX_INSTR movmskpd
-AVX_INSTR movmskps
-AVX_INSTR movntdq
-AVX_INSTR movntdqa
-AVX_INSTR movntpd
-AVX_INSTR movntps
-AVX_INSTR movq
-AVX_INSTR movsd, 1, 0, 0
-AVX_INSTR movshdup
-AVX_INSTR movsldup
-AVX_INSTR movss, 1, 0, 0
-AVX_INSTR movupd
-AVX_INSTR movups
-AVX_INSTR mpsadbw, 0, 1, 0
-AVX_INSTR mulpd, 1, 0, 1
-AVX_INSTR mulps, 1, 0, 1
-AVX_INSTR mulsd, 1, 0, 1
-AVX_INSTR mulss, 1, 0, 1
-AVX_INSTR orpd, 1, 0, 1
-AVX_INSTR orps, 1, 0, 1
-AVX_INSTR pabsb
-AVX_INSTR pabsd
-AVX_INSTR pabsw
-AVX_INSTR packsswb, 0, 0, 0
-AVX_INSTR packssdw, 0, 0, 0
-AVX_INSTR packuswb, 0, 0, 0
-AVX_INSTR packusdw, 0, 0, 0
-AVX_INSTR paddb, 0, 0, 1
-AVX_INSTR paddw, 0, 0, 1
-AVX_INSTR paddd, 0, 0, 1
-AVX_INSTR paddq, 0, 0, 1
-AVX_INSTR paddsb, 0, 0, 1
-AVX_INSTR paddsw, 0, 0, 1
-AVX_INSTR paddusb, 0, 0, 1
-AVX_INSTR paddusw, 0, 0, 1
-AVX_INSTR palignr, 0, 1, 0
-AVX_INSTR pand, 0, 0, 1
-AVX_INSTR pandn, 0, 0, 0
-AVX_INSTR pavgb, 0, 0, 1
-AVX_INSTR pavgw, 0, 0, 1
-AVX_INSTR pblendvb, 0, 0, 0
-AVX_INSTR pblendw, 0, 1, 0
-AVX_INSTR pclmulqdq, 0, 1, 0
-AVX_INSTR pcmpestri
-AVX_INSTR pcmpestrm
-AVX_INSTR pcmpistri
-AVX_INSTR pcmpistrm
-AVX_INSTR pcmpeqb, 0, 0, 1
-AVX_INSTR pcmpeqw, 0, 0, 1
-AVX_INSTR pcmpeqd, 0, 0, 1
-AVX_INSTR pcmpeqq, 0, 0, 1
-AVX_INSTR pcmpgtb, 0, 0, 0
-AVX_INSTR pcmpgtw, 0, 0, 0
-AVX_INSTR pcmpgtd, 0, 0, 0
-AVX_INSTR pcmpgtq, 0, 0, 0
-AVX_INSTR pextrb
-AVX_INSTR pextrd
-AVX_INSTR pextrq
-AVX_INSTR pextrw
-AVX_INSTR phaddw, 0, 0, 0
-AVX_INSTR phaddd, 0, 0, 0
-AVX_INSTR phaddsw, 0, 0, 0
-AVX_INSTR phminposuw
-AVX_INSTR phsubw, 0, 0, 0
-AVX_INSTR phsubd, 0, 0, 0
-AVX_INSTR phsubsw, 0, 0, 0
-AVX_INSTR pinsrb, 0, 1, 0
-AVX_INSTR pinsrd, 0, 1, 0
-AVX_INSTR pinsrq, 0, 1, 0
-AVX_INSTR pinsrw, 0, 1, 0
-AVX_INSTR pmaddwd, 0, 0, 1
-AVX_INSTR pmaddubsw, 0, 0, 0
-AVX_INSTR pmaxsb, 0, 0, 1
-AVX_INSTR pmaxsw, 0, 0, 1
-AVX_INSTR pmaxsd, 0, 0, 1
-AVX_INSTR pmaxub, 0, 0, 1
-AVX_INSTR pmaxuw, 0, 0, 1
-AVX_INSTR pmaxud, 0, 0, 1
-AVX_INSTR pminsb, 0, 0, 1
-AVX_INSTR pminsw, 0, 0, 1
-AVX_INSTR pminsd, 0, 0, 1
-AVX_INSTR pminub, 0, 0, 1
-AVX_INSTR pminuw, 0, 0, 1
-AVX_INSTR pminud, 0, 0, 1
-AVX_INSTR pmovmskb
-AVX_INSTR pmovsxbw
-AVX_INSTR pmovsxbd
-AVX_INSTR pmovsxbq
-AVX_INSTR pmovsxwd
-AVX_INSTR pmovsxwq
-AVX_INSTR pmovsxdq
-AVX_INSTR pmovzxbw
-AVX_INSTR pmovzxbd
-AVX_INSTR pmovzxbq
-AVX_INSTR pmovzxwd
-AVX_INSTR pmovzxwq
-AVX_INSTR pmovzxdq
-AVX_INSTR pmuldq, 0, 0, 1
-AVX_INSTR pmulhrsw, 0, 0, 1
-AVX_INSTR pmulhuw, 0, 0, 1
-AVX_INSTR pmulhw, 0, 0, 1
-AVX_INSTR pmullw, 0, 0, 1
-AVX_INSTR pmulld, 0, 0, 1
-AVX_INSTR pmuludq, 0, 0, 1
-AVX_INSTR por, 0, 0, 1
-AVX_INSTR psadbw, 0, 0, 1
-AVX_INSTR pshufb, 0, 0, 0
-AVX_INSTR pshufd
-AVX_INSTR pshufhw
-AVX_INSTR pshuflw
-AVX_INSTR psignb, 0, 0, 0
-AVX_INSTR psignw, 0, 0, 0
-AVX_INSTR psignd, 0, 0, 0
-AVX_INSTR psllw, 0, 0, 0
-AVX_INSTR pslld, 0, 0, 0
-AVX_INSTR psllq, 0, 0, 0
-AVX_INSTR pslldq, 0, 0, 0
-AVX_INSTR psraw, 0, 0, 0
-AVX_INSTR psrad, 0, 0, 0
-AVX_INSTR psrlw, 0, 0, 0
-AVX_INSTR psrld, 0, 0, 0
-AVX_INSTR psrlq, 0, 0, 0
-AVX_INSTR psrldq, 0, 0, 0
-AVX_INSTR psubb, 0, 0, 0
-AVX_INSTR psubw, 0, 0, 0
-AVX_INSTR psubd, 0, 0, 0
-AVX_INSTR psubq, 0, 0, 0
-AVX_INSTR psubsb, 0, 0, 0
-AVX_INSTR psubsw, 0, 0, 0
-AVX_INSTR psubusb, 0, 0, 0
-AVX_INSTR psubusw, 0, 0, 0
-AVX_INSTR ptest
-AVX_INSTR punpckhbw, 0, 0, 0
-AVX_INSTR punpckhwd, 0, 0, 0
-AVX_INSTR punpckhdq, 0, 0, 0
-AVX_INSTR punpckhqdq, 0, 0, 0
-AVX_INSTR punpcklbw, 0, 0, 0
-AVX_INSTR punpcklwd, 0, 0, 0
-AVX_INSTR punpckldq, 0, 0, 0
-AVX_INSTR punpcklqdq, 0, 0, 0
-AVX_INSTR pxor, 0, 0, 1
-AVX_INSTR rcpps, 1, 0, 0
-AVX_INSTR rcpss, 1, 0, 0
-AVX_INSTR roundpd
-AVX_INSTR roundps
-AVX_INSTR roundsd
-AVX_INSTR roundss
-AVX_INSTR rsqrtps, 1, 0, 0
-AVX_INSTR rsqrtss, 1, 0, 0
-AVX_INSTR shufpd, 1, 1, 0
-AVX_INSTR shufps, 1, 1, 0
-AVX_INSTR sqrtpd, 1, 0, 0
-AVX_INSTR sqrtps, 1, 0, 0
-AVX_INSTR sqrtsd, 1, 0, 0
-AVX_INSTR sqrtss, 1, 0, 0
-AVX_INSTR stmxcsr
-AVX_INSTR subpd, 1, 0, 0
-AVX_INSTR subps, 1, 0, 0
-AVX_INSTR subsd, 1, 0, 0
-AVX_INSTR subss, 1, 0, 0
-AVX_INSTR ucomisd
-AVX_INSTR ucomiss
-AVX_INSTR unpckhpd, 1, 0, 0
-AVX_INSTR unpckhps, 1, 0, 0
-AVX_INSTR unpcklpd, 1, 0, 0
-AVX_INSTR unpcklps, 1, 0, 0
-AVX_INSTR xorpd, 1, 0, 1
-AVX_INSTR xorps, 1, 0, 1
+AVX_INSTR andnpd, sse2, 1, 0, 0
+AVX_INSTR andnps, sse, 1, 0, 0
+AVX_INSTR andpd, sse2, 1, 0, 1
+AVX_INSTR andps, sse, 1, 0, 1
+AVX_INSTR blendpd, sse4, 1, 0, 0
+AVX_INSTR blendps, sse4, 1, 0, 0
+AVX_INSTR blendvpd, sse4, 1, 0, 0
+AVX_INSTR blendvps, sse4, 1, 0, 0
+AVX_INSTR cmppd, sse2, 1, 1, 0
+AVX_INSTR cmpps, sse, 1, 1, 0
+AVX_INSTR cmpsd, sse2, 1, 1, 0
+AVX_INSTR cmpss, sse, 1, 1, 0
+AVX_INSTR comisd, sse2
+AVX_INSTR comiss, sse
+AVX_INSTR cvtdq2pd, sse2
+AVX_INSTR cvtdq2ps, sse2
+AVX_INSTR cvtpd2dq, sse2
+AVX_INSTR cvtpd2ps, sse2
+AVX_INSTR cvtps2dq, sse2
+AVX_INSTR cvtps2pd, sse2
+AVX_INSTR cvtsd2si, sse2
+AVX_INSTR cvtsd2ss, sse2
+AVX_INSTR cvtsi2sd, sse2
+AVX_INSTR cvtsi2ss, sse
+AVX_INSTR cvtss2sd, sse2
+AVX_INSTR cvtss2si, sse
+AVX_INSTR cvttpd2dq, sse2
+AVX_INSTR cvttps2dq, sse2
+AVX_INSTR cvttsd2si, sse2
+AVX_INSTR cvttss2si, sse
+AVX_INSTR divpd, sse2, 1, 0, 0
+AVX_INSTR divps, sse, 1, 0, 0
+AVX_INSTR divsd, sse2, 1, 0, 0
+AVX_INSTR divss, sse, 1, 0, 0
+AVX_INSTR dppd, sse4, 1, 1, 0
+AVX_INSTR dpps, sse4, 1, 1, 0
+AVX_INSTR extractps, sse4
+AVX_INSTR haddpd, sse3, 1, 0, 0
+AVX_INSTR haddps, sse3, 1, 0, 0
+AVX_INSTR hsubpd, sse3, 1, 0, 0
+AVX_INSTR hsubps, sse3, 1, 0, 0
+AVX_INSTR insertps, sse4, 1, 1, 0
+AVX_INSTR lddqu, sse3
+AVX_INSTR ldmxcsr, sse
+AVX_INSTR maskmovdqu, sse2
+AVX_INSTR maxpd, sse2, 1, 0, 1
+AVX_INSTR maxps, sse, 1, 0, 1
+AVX_INSTR maxsd, sse2, 1, 0, 1
+AVX_INSTR maxss, sse, 1, 0, 1
+AVX_INSTR minpd, sse2, 1, 0, 1
+AVX_INSTR minps, sse, 1, 0, 1
+AVX_INSTR minsd, sse2, 1, 0, 1
+AVX_INSTR minss, sse, 1, 0, 1
+AVX_INSTR movapd, sse2
+AVX_INSTR movaps, sse
+AVX_INSTR movd, mmx
+AVX_INSTR movddup, sse3
+AVX_INSTR movdqa, sse2
+AVX_INSTR movdqu, sse2
+AVX_INSTR movhlps, sse, 1, 0, 0
+AVX_INSTR movhpd, sse2, 1, 0, 0
+AVX_INSTR movhps, sse, 1, 0, 0
+AVX_INSTR movlhps, sse, 1, 0, 0
+AVX_INSTR movlpd, sse2, 1, 0, 0
+AVX_INSTR movlps, sse, 1, 0, 0
+AVX_INSTR movmskpd, sse2
+AVX_INSTR movmskps, sse
+AVX_INSTR movntdq, sse2
+AVX_INSTR movntdqa, sse4
+AVX_INSTR movntpd, sse2
+AVX_INSTR movntps, sse
+AVX_INSTR movq, mmx
+AVX_INSTR movsd, sse2, 1, 0, 0
+AVX_INSTR movshdup, sse3
+AVX_INSTR movsldup, sse3
+AVX_INSTR movss, sse, 1, 0, 0
+AVX_INSTR movupd, sse2
+AVX_INSTR movups, sse
+AVX_INSTR mpsadbw, sse4
+AVX_INSTR mulpd, sse2, 1, 0, 1
+AVX_INSTR mulps, sse, 1, 0, 1
+AVX_INSTR mulsd, sse2, 1, 0, 1
+AVX_INSTR mulss, sse, 1, 0, 1
+AVX_INSTR orpd, sse2, 1, 0, 1
+AVX_INSTR orps, sse, 1, 0, 1
+AVX_INSTR pabsb, ssse3
+AVX_INSTR pabsd, ssse3
+AVX_INSTR pabsw, ssse3
+AVX_INSTR packsswb, mmx, 0, 0, 0
+AVX_INSTR packssdw, mmx, 0, 0, 0
+AVX_INSTR packuswb, mmx, 0, 0, 0
+AVX_INSTR packusdw, sse4, 0, 0, 0
+AVX_INSTR paddb, mmx, 0, 0, 1
+AVX_INSTR paddw, mmx, 0, 0, 1
+AVX_INSTR paddd, mmx, 0, 0, 1
+AVX_INSTR paddq, sse2, 0, 0, 1
+AVX_INSTR paddsb, mmx, 0, 0, 1
+AVX_INSTR paddsw, mmx, 0, 0, 1
+AVX_INSTR paddusb, mmx, 0, 0, 1
+AVX_INSTR paddusw, mmx, 0, 0, 1
+AVX_INSTR palignr, ssse3
+AVX_INSTR pand, mmx, 0, 0, 1
+AVX_INSTR pandn, mmx, 0, 0, 0
+AVX_INSTR pavgb, mmx2, 0, 0, 1
+AVX_INSTR pavgw, mmx2, 0, 0, 1
+AVX_INSTR pblendvb, sse4, 0, 0, 0
+AVX_INSTR pblendw, sse4
+AVX_INSTR pclmulqdq
+AVX_INSTR pcmpestri, sse42
+AVX_INSTR pcmpestrm, sse42
+AVX_INSTR pcmpistri, sse42
+AVX_INSTR pcmpistrm, sse42
+AVX_INSTR pcmpeqb, mmx, 0, 0, 1
+AVX_INSTR pcmpeqw, mmx, 0, 0, 1
+AVX_INSTR pcmpeqd, mmx, 0, 0, 1
+AVX_INSTR pcmpeqq, sse4, 0, 0, 1
+AVX_INSTR pcmpgtb, mmx, 0, 0, 0
+AVX_INSTR pcmpgtw, mmx, 0, 0, 0
+AVX_INSTR pcmpgtd, mmx, 0, 0, 0
+AVX_INSTR pcmpgtq, sse42, 0, 0, 0
+AVX_INSTR pextrb, sse4
+AVX_INSTR pextrd, sse4
+AVX_INSTR pextrq, sse4
+AVX_INSTR pextrw, mmx2
+AVX_INSTR phaddw, ssse3, 0, 0, 0
+AVX_INSTR phaddd, ssse3, 0, 0, 0
+AVX_INSTR phaddsw, ssse3, 0, 0, 0
+AVX_INSTR phminposuw, sse4
+AVX_INSTR phsubw, ssse3, 0, 0, 0
+AVX_INSTR phsubd, ssse3, 0, 0, 0
+AVX_INSTR phsubsw, ssse3, 0, 0, 0
+AVX_INSTR pinsrb, sse4
+AVX_INSTR pinsrd, sse4
+AVX_INSTR pinsrq, sse4
+AVX_INSTR pinsrw, mmx2
+AVX_INSTR pmaddwd, mmx, 0, 0, 1
+AVX_INSTR pmaddubsw, ssse3, 0, 0, 0
+AVX_INSTR pmaxsb, sse4, 0, 0, 1
+AVX_INSTR pmaxsw, mmx2, 0, 0, 1
+AVX_INSTR pmaxsd, sse4, 0, 0, 1
+AVX_INSTR pmaxub, mmx2, 0, 0, 1
+AVX_INSTR pmaxuw, sse4, 0, 0, 1
+AVX_INSTR pmaxud, sse4, 0, 0, 1
+AVX_INSTR pminsb, sse4, 0, 0, 1
+AVX_INSTR pminsw, mmx2, 0, 0, 1
+AVX_INSTR pminsd, sse4, 0, 0, 1
+AVX_INSTR pminub, mmx2, 0, 0, 1
+AVX_INSTR pminuw, sse4, 0, 0, 1
+AVX_INSTR pminud, sse4, 0, 0, 1
+AVX_INSTR pmovmskb, mmx2
+AVX_INSTR pmovsxbw, sse4
+AVX_INSTR pmovsxbd, sse4
+AVX_INSTR pmovsxbq, sse4
+AVX_INSTR pmovsxwd, sse4
+AVX_INSTR pmovsxwq, sse4
+AVX_INSTR pmovsxdq, sse4
+AVX_INSTR pmovzxbw, sse4
+AVX_INSTR pmovzxbd, sse4
+AVX_INSTR pmovzxbq, sse4
+AVX_INSTR pmovzxwd, sse4
+AVX_INSTR pmovzxwq, sse4
+AVX_INSTR pmovzxdq, sse4
+AVX_INSTR pmuldq, sse4, 0, 0, 1
+AVX_INSTR pmulhrsw, ssse3, 0, 0, 1
+AVX_INSTR pmulhuw, mmx2, 0, 0, 1
+AVX_INSTR pmulhw, mmx, 0, 0, 1
+AVX_INSTR pmullw, mmx, 0, 0, 1
+AVX_INSTR pmulld, sse4, 0, 0, 1
+AVX_INSTR pmuludq, sse2, 0, 0, 1
+AVX_INSTR por, mmx, 0, 0, 1
+AVX_INSTR psadbw, mmx2, 0, 0, 1
+AVX_INSTR pshufb, ssse3, 0, 0, 0
+AVX_INSTR pshufd, sse2
+AVX_INSTR pshufhw, sse2
+AVX_INSTR pshuflw, sse2
+AVX_INSTR psignb, ssse3, 0, 0, 0
+AVX_INSTR psignw, ssse3, 0, 0, 0
+AVX_INSTR psignd, ssse3, 0, 0, 0
+AVX_INSTR psllw, mmx, 0, 0, 0
+AVX_INSTR pslld, mmx, 0, 0, 0
+AVX_INSTR psllq, mmx, 0, 0, 0
+AVX_INSTR pslldq, sse2, 0, 0, 0
+AVX_INSTR psraw, mmx, 0, 0, 0
+AVX_INSTR psrad, mmx, 0, 0, 0
+AVX_INSTR psrlw, mmx, 0, 0, 0
+AVX_INSTR psrld, mmx, 0, 0, 0
+AVX_INSTR psrlq, mmx, 0, 0, 0
+AVX_INSTR psrldq, sse2, 0, 0, 0
+AVX_INSTR psubb, mmx, 0, 0, 0
+AVX_INSTR psubw, mmx, 0, 0, 0
+AVX_INSTR psubd, mmx, 0, 0, 0
+AVX_INSTR psubq, sse2, 0, 0, 0
+AVX_INSTR psubsb, mmx, 0, 0, 0
+AVX_INSTR psubsw, mmx, 0, 0, 0
+AVX_INSTR psubusb, mmx, 0, 0, 0
+AVX_INSTR psubusw, mmx, 0, 0, 0
+AVX_INSTR ptest, sse4
+AVX_INSTR punpckhbw, mmx, 0, 0, 0
+AVX_INSTR punpckhwd, mmx, 0, 0, 0
+AVX_INSTR punpckhdq, mmx, 0, 0, 0
+AVX_INSTR punpckhqdq, sse2, 0, 0, 0
+AVX_INSTR punpcklbw, mmx, 0, 0, 0
+AVX_INSTR punpcklwd, mmx, 0, 0, 0
+AVX_INSTR punpckldq, mmx, 0, 0, 0
+AVX_INSTR punpcklqdq, sse2, 0, 0, 0
+AVX_INSTR pxor, mmx, 0, 0, 1
+AVX_INSTR rcpps, sse, 1, 0, 0
+AVX_INSTR rcpss, sse, 1, 0, 0
+AVX_INSTR roundpd, sse4
+AVX_INSTR roundps, sse4
+AVX_INSTR roundsd, sse4
+AVX_INSTR roundss, sse4
+AVX_INSTR rsqrtps, sse, 1, 0, 0
+AVX_INSTR rsqrtss, sse, 1, 0, 0
+AVX_INSTR shufpd, sse2, 1, 1, 0
+AVX_INSTR shufps, sse, 1, 1, 0
+AVX_INSTR sqrtpd, sse2, 1, 0, 0
+AVX_INSTR sqrtps, sse, 1, 0, 0
+AVX_INSTR sqrtsd, sse2, 1, 0, 0
+AVX_INSTR sqrtss, sse, 1, 0, 0
+AVX_INSTR stmxcsr, sse
+AVX_INSTR subpd, sse2, 1, 0, 0
+AVX_INSTR subps, sse, 1, 0, 0
+AVX_INSTR subsd, sse2, 1, 0, 0
+AVX_INSTR subss, sse, 1, 0, 0
+AVX_INSTR ucomisd, sse2
+AVX_INSTR ucomiss, sse
+AVX_INSTR unpckhpd, sse2, 1, 0, 0
+AVX_INSTR unpckhps, sse, 1, 0, 0
+AVX_INSTR unpcklpd, sse2, 1, 0, 0
+AVX_INSTR unpcklps, sse, 1, 0, 0
+AVX_INSTR xorpd, sse2, 1, 0, 1
+AVX_INSTR xorps, sse, 1, 0, 1
 
 ; 3DNow instructions, for sharing code between AVX, SSE and 3DN
-AVX_INSTR pfadd, 1, 0, 1
-AVX_INSTR pfsub, 1, 0, 0
-AVX_INSTR pfmul, 1, 0, 1
+AVX_INSTR pfadd, 3dnow, 1, 0, 1
+AVX_INSTR pfsub, 3dnow, 1, 0, 0
+AVX_INSTR pfmul, 3dnow, 1, 0, 1
 
 ; base-4 constants for shuffles
 %assign i 0
diff --git a/libpostproc/postprocess.c b/libpostproc/postprocess.c
index c11debc..9d89782 100644
--- a/libpostproc/postprocess.c
+++ b/libpostproc/postprocess.c
@@ -700,6 +700,8 @@
     }
 
     ppMode= av_malloc(sizeof(PPMode));
+    if (!ppMode)
+        return NULL;
 
     ppMode->lumMode= 0;
     ppMode->chromMode= 0;
@@ -912,12 +914,14 @@
 
 static const AVClass av_codec_context_class = { "Postproc", context_to_name, NULL };
 
-pp_context *pp_get_context(int width, int height, int cpuCaps){
-    PPContext *c= av_malloc(sizeof(PPContext));
+av_cold pp_context *pp_get_context(int width, int height, int cpuCaps){
+    PPContext *c= av_mallocz(sizeof(PPContext));
     int stride= FFALIGN(width, 16);  //assumed / will realloc if needed
     int qpStride= (width+15)/16 + 2; //assumed / will realloc if needed
 
-    memset(c, 0, sizeof(PPContext));
+    if (!c)
+        return NULL;
+
     c->av_class = &av_codec_context_class;
     if(cpuCaps&PP_FORMAT){
         c->hChromaSubSample= cpuCaps&0x3;
@@ -943,7 +947,7 @@
     return c;
 }
 
-void pp_free_context(void *vc){
+av_cold void pp_free_context(void *vc){
     PPContext *c = (PPContext*)vc;
     int i;
 
diff --git a/libpostproc/postprocess_template.c b/libpostproc/postprocess_template.c
index 6722f96..4016b08 100644
--- a/libpostproc/postprocess_template.c
+++ b/libpostproc/postprocess_template.c
@@ -3395,14 +3395,6 @@
                 "g" ((x86_reg)x), "g" ((x86_reg)copyAhead)
                 : "%"REG_a, "%"REG_d
             );
-
-#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);
-            prefetchw(dstBlock + (((x>>3)&3) + 5)*dstStride + 32);
-            prefetchw(dstBlock + (((x>>3)&3) + 9)*dstStride + 32);
-*/
 #endif
 
             RENAME(blockCopy)(dstBlock + dstStride*8, dstStride,
@@ -3476,35 +3468,12 @@
         // From this point on it is guaranteed that we can read and write 16 lines downward
         // finish 1 block before the next otherwise we might have a problem
         // with the L1 Cache of the P4 ... or only a few blocks at a time or something
-        for(x=0; x<width; x+=BLOCK_SIZE){
-            const int stride= dstStride;
-#if TEMPLATE_PP_MMX
-            uint8_t *tmpXchg;
-#endif
-            if(isColor){
-                QP= QPptr[x>>qpHShift];
-                c.nonBQP= nonBQPptr[x>>qpHShift];
-            }else{
-                QP= QPptr[x>>4];
-                QP= (QP* QPCorrecture + 256*128)>>16;
-                c.nonBQP= nonBQPptr[x>>4];
-                c.nonBQP= (c.nonBQP* QPCorrecture + 256*128)>>16;
-                yHistogram[ srcBlock[srcStride*12 + 4] ]++;
-            }
-            c.QP= QP;
-#if TEMPLATE_PP_MMX
-            __asm__ volatile(
-                "movd %1, %%mm7         \n\t"
-                "packuswb %%mm7, %%mm7  \n\t" // 0, 0, 0, QP, 0, 0, 0, QP
-                "packuswb %%mm7, %%mm7  \n\t" // 0,QP, 0, QP, 0,QP, 0, QP
-                "packuswb %%mm7, %%mm7  \n\t" // QP,..., QP
-                "movq %%mm7, %0         \n\t"
-                : "=m" (c.pQPb)
-                : "r" (QP)
-            );
-#endif
-
-
+        for(x=0; x<width; ){
+            int startx = x;
+            int endx = FFMIN(width, x+32);
+            uint8_t *dstBlockStart = dstBlock;
+            const uint8_t *srcBlockStart = srcBlock;
+          for(; x < endx; x+=BLOCK_SIZE){
 #if TEMPLATE_PP_MMXEXT && HAVE_6REGS
 /*
             prefetchnta(srcBlock + (((x>>2)&6) + 5)*srcStride + 32);
@@ -3531,14 +3500,6 @@
                 "g" ((x86_reg)x), "g" ((x86_reg)copyAhead)
                 : "%"REG_a, "%"REG_d
             );
-
-#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);
-            prefetchw(dstBlock + (((x>>3)&3) + 5)*dstStride + 32);
-            prefetchw(dstBlock + (((x>>3)&3) + 9)*dstStride + 32);
-*/
 #endif
 
             RENAME(blockCopy)(dstBlock + dstStride*copyAhead, dstStride,
@@ -3559,7 +3520,38 @@
 /*          else if(mode & CUBIC_BLEND_DEINT_FILTER)
                 RENAME(deInterlaceBlendCubic)(dstBlock, dstStride);
 */
+            dstBlock+=8;
+            srcBlock+=8;
+          }
 
+          dstBlock = dstBlockStart;
+          srcBlock = srcBlockStart;
+
+          for(x = startx; x < endx; x+=BLOCK_SIZE){
+            const int stride= dstStride;
+
+            if(isColor){
+                QP= QPptr[x>>qpHShift];
+                c.nonBQP= nonBQPptr[x>>qpHShift];
+            }else{
+                QP= QPptr[x>>4];
+                QP= (QP* QPCorrecture + 256*128)>>16;
+                c.nonBQP= nonBQPptr[x>>4];
+                c.nonBQP= (c.nonBQP* QPCorrecture + 256*128)>>16;
+                yHistogram[ srcBlock[srcStride*12 + 4] ]++;
+            }
+            c.QP= QP;
+#if TEMPLATE_PP_MMX
+            __asm__ volatile(
+                "movd %1, %%mm7         \n\t"
+                "packuswb %%mm7, %%mm7  \n\t" // 0, 0, 0, QP, 0, 0, 0, QP
+                "packuswb %%mm7, %%mm7  \n\t" // 0,QP, 0, QP, 0,QP, 0, QP
+                "packuswb %%mm7, %%mm7  \n\t" // QP,..., QP
+                "movq %%mm7, %0         \n\t"
+                : "=m" (c.pQPb)
+                : "r" (QP)
+            );
+#endif
             /* only deblock if we have 2 blocks */
             if(y + 8 < height){
                 if(mode & V_X1_FILTER)
@@ -3576,7 +3568,37 @@
                 }
             }
 
+            dstBlock+=8;
+            srcBlock+=8;
+          }
+
+          dstBlock = dstBlockStart;
+          srcBlock = srcBlockStart;
+
+          for(x = startx; x < endx; x+=BLOCK_SIZE){
+            const int stride= dstStride;
+            av_unused uint8_t *tmpXchg;
+
+            if(isColor){
+                QP= QPptr[x>>qpHShift];
+                c.nonBQP= nonBQPptr[x>>qpHShift];
+            }else{
+                QP= QPptr[x>>4];
+                QP= (QP* QPCorrecture + 256*128)>>16;
+                c.nonBQP= nonBQPptr[x>>4];
+                c.nonBQP= (c.nonBQP* QPCorrecture + 256*128)>>16;
+            }
+            c.QP= QP;
 #if TEMPLATE_PP_MMX
+            __asm__ volatile(
+                "movd %1, %%mm7         \n\t"
+                "packuswb %%mm7, %%mm7  \n\t" // 0, 0, 0, QP, 0, 0, 0, QP
+                "packuswb %%mm7, %%mm7  \n\t" // 0,QP, 0, QP, 0,QP, 0, QP
+                "packuswb %%mm7, %%mm7  \n\t" // QP,..., QP
+                "movq %%mm7, %0         \n\t"
+                : "=m" (c.pQPb)
+                : "r" (QP)
+            );
             RENAME(transpose1)(tempBlock1, tempBlock2, dstBlock, dstStride);
 #endif
             /* check if we have a previous block to deblock it with dstBlock */
@@ -3585,9 +3607,7 @@
                 if(mode & H_X1_FILTER)
                         RENAME(vertX1Filter)(tempBlock1, 16, &c);
                 else if(mode & H_DEBLOCK){
-//START_TIMER
                     const int t= RENAME(vertClassify)(tempBlock1, 16, &c);
-//STOP_TIMER("dc & minmax")
                     if(t==1)
                         RENAME(doVertLowPass)(tempBlock1, 16, &c);
                     else if(t==2)
@@ -3650,6 +3670,7 @@
             tempBlock1= tempBlock2;
             tempBlock2 = tmpXchg;
 #endif
+          }
         }
 
         if(mode & DERING){
@@ -3675,15 +3696,6 @@
                 }
             }
         }
-/*
-        for(x=0; x<width; x+=32){
-            volatile int i;
-            i+=   dstBlock[x + 7*dstStride] + dstBlock[x + 8*dstStride]
-                + dstBlock[x + 9*dstStride] + dstBlock[x +10*dstStride]
-                + dstBlock[x +11*dstStride] + dstBlock[x +12*dstStride];
-                + dstBlock[x +13*dstStride]
-                + dstBlock[x +14*dstStride] + dstBlock[x +15*dstStride];
-        }*/
     }
 #if   TEMPLATE_PP_3DNOW
     __asm__ volatile("femms");
diff --git a/library.mak b/library.mak
index 72e5574..e23abd2 100644
--- a/library.mak
+++ b/library.mak
@@ -22,7 +22,11 @@
 $(SUBDIR)%-test.i: $(SUBDIR)%.c
 	$(CC) $(CCFLAGS) $(CC_E) $<
 
-$(SUBDIR)x86/%.o: $(SUBDIR)x86/%.asm
+$(SUBDIR)x86/%$(DEFAULT_YASMD).asm: $(SUBDIR)x86/%.asm
+	$(DEPYASM) $(YASMFLAGS) -I $(<D)/ -M -o $@ $< > $(@:.asm=.d)
+	$(YASM) $(YASMFLAGS) -I $(<D)/ -e $< | sed '/^%/d;/^$$/d;' > $@
+
+$(SUBDIR)x86/%.o: $(SUBDIR)x86/%$(YASMD).asm
 	$(DEPYASM) $(YASMFLAGS) -I $(<D)/ -M -o $@ $< > $(@:.o=.d)
 	$(YASM) $(YASMFLAGS) -I $(<D)/ -o $@ $<
 	-$(if $(ASMSTRIPFLAGS), $(STRIP) $(ASMSTRIPFLAGS) $@)
diff --git a/libswresample/dither.c b/libswresample/dither.c
index b8b592a..ca09e67 100644
--- a/libswresample/dither.c
+++ b/libswresample/dither.c
@@ -72,7 +72,7 @@
     av_free(tmp);
 }
 
-int swri_dither_init(SwrContext *s, enum AVSampleFormat out_fmt, enum AVSampleFormat in_fmt)
+av_cold int swri_dither_init(SwrContext *s, enum AVSampleFormat out_fmt, enum AVSampleFormat in_fmt)
 {
     int i;
     double scale = 0;
@@ -84,14 +84,14 @@
     in_fmt  = av_get_packed_sample_fmt( in_fmt);
 
     if(in_fmt == AV_SAMPLE_FMT_FLT || in_fmt == AV_SAMPLE_FMT_DBL){
-        if(out_fmt == AV_SAMPLE_FMT_S32) scale = 1.0/(1L<<31);
-        if(out_fmt == AV_SAMPLE_FMT_S16) scale = 1.0/(1L<<15);
-        if(out_fmt == AV_SAMPLE_FMT_U8 ) scale = 1.0/(1L<< 7);
+        if(out_fmt == AV_SAMPLE_FMT_S32) scale = 1.0/(1LL<<31);
+        if(out_fmt == AV_SAMPLE_FMT_S16) scale = 1.0/(1LL<<15);
+        if(out_fmt == AV_SAMPLE_FMT_U8 ) scale = 1.0/(1LL<< 7);
     }
     if(in_fmt == AV_SAMPLE_FMT_S32 && out_fmt == AV_SAMPLE_FMT_S32 && (s->dither.output_sample_bits&31)) scale = 1;
-    if(in_fmt == AV_SAMPLE_FMT_S32 && out_fmt == AV_SAMPLE_FMT_S16) scale = 1L<<16;
-    if(in_fmt == AV_SAMPLE_FMT_S32 && out_fmt == AV_SAMPLE_FMT_U8 ) scale = 1L<<24;
-    if(in_fmt == AV_SAMPLE_FMT_S16 && out_fmt == AV_SAMPLE_FMT_U8 ) scale = 1L<<8;
+    if(in_fmt == AV_SAMPLE_FMT_S32 && out_fmt == AV_SAMPLE_FMT_S16) scale = 1<<16;
+    if(in_fmt == AV_SAMPLE_FMT_S32 && out_fmt == AV_SAMPLE_FMT_U8 ) scale = 1<<24;
+    if(in_fmt == AV_SAMPLE_FMT_S16 && out_fmt == AV_SAMPLE_FMT_U8 ) scale = 1<<8;
 
     scale *= s->dither.scale;
 
diff --git a/libswresample/rematrix.c b/libswresample/rematrix.c
index 6552a2f..f26ede7 100644
--- a/libswresample/rematrix.c
+++ b/libswresample/rematrix.c
@@ -415,7 +415,8 @@
         s->matrix_ch[i][0]= ch_in;
     }
 
-    if(HAVE_YASM && HAVE_MMX) swri_rematrix_init_x86(s);
+    if(HAVE_YASM && HAVE_MMX)
+        return swri_rematrix_init_x86(s);
 
     return 0;
 }
diff --git a/libswresample/resample.c b/libswresample/resample.c
index d0f6e20..d4c7d06 100644
--- a/libswresample/resample.c
+++ b/libswresample/resample.c
@@ -338,7 +338,7 @@
 static int64_t get_delay(struct SwrContext *s, int64_t base){
     ResampleContext *c = s->resample;
     int64_t num = s->in_buffer_count - (c->filter_length-1)/2;
-    num <<= c->phase_shift;
+    num *= 1 << c->phase_shift;
     num -= c->index;
     num *= c->src_incr;
     num -= c->frac;
diff --git a/libswresample/resample_template.c b/libswresample/resample_template.c
index 069b19c..7e80ef9 100644
--- a/libswresample/resample_template.c
+++ b/libswresample/resample_template.c
@@ -52,8 +52,8 @@
 #    define FELEM2 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 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)
 
@@ -65,8 +65,8 @@
 #    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 OUT(d, v) (v) = ((v) + (1<<(FILTER_SHIFT-1)))>>FILTER_SHIFT;\
+                      (d) = (unsigned)((v) + 32768) > 65535 ? ((v)>>31) ^ 32767 : (v)
 
 #endif
 
diff --git a/libswresample/soxr_resample.c b/libswresample/soxr_resample.c
index 9e87f2f..0f75bc5 100644
--- a/libswresample/soxr_resample.c
+++ b/libswresample/soxr_resample.c
@@ -97,7 +97,7 @@
     return 0;
 }
 
-struct Resampler const soxr_resampler={
+struct Resampler const swri_soxr_resampler={
     create, destroy, process, flush, NULL /* set_compensation */, get_delay,
     invert_initial_buffer,
 };
diff --git a/libswresample/swresample-test.c b/libswresample/swresample-test.c
index c0162cd..8859e94 100644
--- a/libswresample/swresample-test.c
+++ b/libswresample/swresample-test.c
@@ -153,7 +153,7 @@
     unsigned static rnd;
 
 #define PUT_SAMPLE set(data, ch, k, channels, sample_fmt, v);
-#define uint_rand(x) (x = x * 1664525 + 1013904223)
+#define uint_rand(x) ((x) = (x) * 1664525 + 1013904223)
 #define dbl_rand(x) (uint_rand(x)*2.0 / (double)UINT_MAX - 1)
     k = 0;
 
diff --git a/libswresample/swresample.c b/libswresample/swresample.c
index eb6effa..9baccd2 100644
--- a/libswresample/swresample.c
+++ b/libswresample/swresample.c
@@ -176,8 +176,7 @@
 
     switch(s->engine){
 #if CONFIG_LIBSOXR
-        extern struct Resampler const soxr_resampler;
-        case SWR_ENGINE_SOXR: s->resampler = &soxr_resampler; break;
+        case SWR_ENGINE_SOXR: s->resampler = &swri_soxr_resampler; break;
 #endif
         case SWR_ENGINE_SWR : s->resampler = &swri_resampler; break;
         default:
diff --git a/libswresample/swresample_internal.h b/libswresample/swresample_internal.h
index 6250921..77ec9bb 100644
--- a/libswresample/swresample_internal.h
+++ b/libswresample/swresample_internal.h
@@ -53,7 +53,7 @@
 } AudioData;
 
 struct DitherContext {
-    enum SwrDitherType method;
+    int method;
     int noise_pos;
     float scale;
     float noise_scale;                              ///< Noise scale
@@ -88,6 +88,7 @@
 };
 
 extern struct Resampler const swri_resampler;
+extern struct Resampler const swri_soxr_resampler;
 
 struct SwrContext {
     const AVClass *av_class;                        ///< AVClass used for AVOption and av_log()
@@ -106,10 +107,10 @@
     float lfe_mix_level;                            ///< LFE mixing level
     float rematrix_volume;                          ///< rematrixing volume coefficient
     float rematrix_maxval;                          ///< maximum value for rematrixing output
-    enum AVMatrixEncoding matrix_encoding;          /**< matrixed stereo encoding */
+    int matrix_encoding;                            /**< matrixed stereo encoding */
     const int *channel_map;                         ///< channel index (or -1 if muted channel) map
     int used_ch_count;                              ///< number of used input channels (mapped channel count if channel_map, otherwise in.ch_count)
-    enum SwrEngine engine;
+    int engine;
 
     struct DitherContext dither;
 
@@ -117,7 +118,7 @@
     int phase_shift;                                /**< log2 of the number of entries in the resampling polyphase filterbank */
     int linear_interp;                              /**< if 1 then the resampling FIR filter will be linearly interpolated */
     double cutoff;                                  /**< resampling cutoff frequency (swr: 6dB point; soxr: 0dB point). 1.0 corresponds to half the output sample rate */
-    enum SwrFilterType filter_type;                 /**< swr resampling filter type */
+    int filter_type;                                /**< swr resampling filter type */
     int kaiser_beta;                                /**< swr beta value for Kaiser window (only applicable if filter_type == AV_FILTER_TYPE_KAISER) */
     double precision;                               /**< soxr resampling precision (in bits) */
     int cheby;                                      /**< soxr: if 1 then passband rolloff will be none (Chebyshev) & irrational ratio approximation precision will be higher */
@@ -183,7 +184,7 @@
 int swri_rematrix_init(SwrContext *s);
 void swri_rematrix_free(SwrContext *s);
 int swri_rematrix(SwrContext *s, AudioData *out, AudioData *in, int len, int mustcopy);
-void swri_rematrix_init_x86(struct SwrContext *s);
+int swri_rematrix_init_x86(struct SwrContext *s);
 
 void swri_get_dither(SwrContext *s, void *dst, int len, unsigned seed, enum AVSampleFormat noise_fmt);
 int swri_dither_init(SwrContext *s, enum AVSampleFormat out_fmt, enum AVSampleFormat in_fmt);
@@ -200,4 +201,5 @@
                                  enum AVSampleFormat out_fmt,
                                  enum AVSampleFormat in_fmt,
                                  int channels);
+
 #endif
diff --git a/libswresample/x86/audio_convert.asm b/libswresample/x86/audio_convert.asm
index 1617e0b..69e4f05 100644
--- a/libswresample/x86/audio_convert.asm
+++ b/libswresample/x86/audio_convert.asm
@@ -378,26 +378,36 @@
     REP_RET
 %endmacro
 
+%define PACK_8CH_GPRS (10 * ARCH_X86_64) + ((6 + HAVE_ALIGNED_STACK) * ARCH_X86_32)
+
 %macro PACK_8CH 5-7
-cglobal pack_8ch_%2_to_%1_%3, 2,10,10, ARCH_X86_32*32, dst, src, len, src1, src2, src3, src4, src5, src6, src7
+cglobal pack_8ch_%2_to_%1_%3, 2,PACK_8CH_GPRS,10, ARCH_X86_32*48, dst, src, len, src1, src2, src3, src4, src5, src6, src7
     mov     dstq, [dstq]
 %if ARCH_X86_32
     DEFINE_ARGS dst, src, src2, src3, src4, src5, src6
     %define lend dword r2m
     %define src1q r0q
-    %define src1m r1mp
+    %define src1m dword [rsp+32]
+%if HAVE_ALIGNED_STACK == 0
+    DEFINE_ARGS dst, src, src2, src3, src5, src6
+    %define src4q r0q
+    %define src4m dword [rsp+36]
+%endif
     %define src7q r0q
-    %define src7m r3mp
+    %define src7m dword [rsp+40]
     mov     dstm, dstq
 %endif
     mov    src7q, [srcq+7*gprsize]
     mov    src6q, [srcq+6*gprsize]
+%if ARCH_X86_32
+    mov    src7m, src7q
+%endif
     mov    src5q, [srcq+5*gprsize]
     mov    src4q, [srcq+4*gprsize]
-%if ARCH_X86_32
-    mov src7m, src7q
-%endif
     mov    src3q, [srcq+3*gprsize]
+%if ARCH_X86_32 && HAVE_ALIGNED_STACK == 0
+    mov    src4m, src4q
+%endif
     mov    src2q, [srcq+2*gprsize]
     mov    src1q, [srcq+1*gprsize]
     mov     srcq, [srcq]
@@ -416,7 +426,11 @@
         jne pack_8ch_%2_to_%1_u_int %+ SUFFIX
     test src3q, mmsize-1
         jne pack_8ch_%2_to_%1_u_int %+ SUFFIX
+%if ARCH_X86_32 && HAVE_ALIGNED_STACK == 0
+    test src4m, mmsize-1
+%else
     test src4q, mmsize-1
+%endif
         jne pack_8ch_%2_to_%1_u_int %+ SUFFIX
     test src5q, mmsize-1
         jne pack_8ch_%2_to_%1_u_int %+ SUFFIX
@@ -434,7 +448,11 @@
     sub    src1q, srcq
     sub    src2q, srcq
     sub    src3q, srcq
+%if ARCH_X86_64 || HAVE_ALIGNED_STACK
     sub    src4q, srcq
+%else
+    sub    src4m, srcq
+%endif
     sub    src5q, srcq
     sub    src6q, srcq
 %if ARCH_X86_64
@@ -456,12 +474,15 @@
     mov%3     m0, [srcq      ]
     mov%3     m1, [srcq+src1q]
     mov%3     m2, [srcq+src2q]
+%if ARCH_X86_32 && HAVE_ALIGNED_STACK == 0
+    mov    src4q, src4m
+%endif
     mov%3     m3, [srcq+src3q]
+    mov%3     m4, [srcq+src4q]
+    mov%3     m5, [srcq+src5q]
 %if ARCH_X86_32
     mov    src7q, src7m
 %endif
-    mov%3     m4, [srcq+src4q]
-    mov%3     m5, [srcq+src5q]
     mov%3     m6, [srcq+src6q]
     mov%3     m7, [srcq+src7q]
 
@@ -664,7 +685,6 @@
 UNPACK_6CH int32, float, u, 2, 2, FLOAT_TO_INT32_N, FLOAT_TO_INT32_INIT
 UNPACK_6CH int32, float, a, 2, 2, FLOAT_TO_INT32_N, FLOAT_TO_INT32_INIT
 
-%if HAVE_ALIGNED_STACK
 PACK_8CH float, float, u, 2, 2, NOP_N, NOP_N
 PACK_8CH float, float, a, 2, 2, NOP_N, NOP_N
 
@@ -672,7 +692,6 @@
 PACK_8CH float, int32, a, 2, 2, INT32_TO_FLOAT_N, INT32_TO_FLOAT_INIT
 PACK_8CH int32, float, u, 2, 2, FLOAT_TO_INT32_N, FLOAT_TO_INT32_INIT
 PACK_8CH int32, float, a, 2, 2, FLOAT_TO_INT32_N, FLOAT_TO_INT32_INIT
-%endif
 
 INIT_XMM ssse3
 UNPACK_2CH int16, int16, u, 1, 1, NOP_N, NOP_N
@@ -700,7 +719,6 @@
 UNPACK_6CH int32, float, u, 2, 2, FLOAT_TO_INT32_N, FLOAT_TO_INT32_INIT
 UNPACK_6CH int32, float, a, 2, 2, FLOAT_TO_INT32_N, FLOAT_TO_INT32_INIT
 
-%if HAVE_ALIGNED_STACK
 PACK_8CH float, float, u, 2, 2, NOP_N, NOP_N
 PACK_8CH float, float, a, 2, 2, NOP_N, NOP_N
 
@@ -708,7 +726,6 @@
 PACK_8CH float, int32, a, 2, 2, INT32_TO_FLOAT_N, INT32_TO_FLOAT_INIT
 PACK_8CH int32, float, u, 2, 2, FLOAT_TO_INT32_N, FLOAT_TO_INT32_INIT
 PACK_8CH int32, float, a, 2, 2, FLOAT_TO_INT32_N, FLOAT_TO_INT32_INIT
-%endif
 
 INIT_YMM avx
 CONV float, int32, u, 2, 2, INT32_TO_FLOAT_N, INT32_TO_FLOAT_INIT
diff --git a/libswresample/x86/audio_convert_init.c b/libswresample/x86/audio_convert_init.c
index bd5f741..7f25d98 100644
--- a/libswresample/x86/audio_convert_init.c
+++ b/libswresample/x86/audio_convert_init.c
@@ -126,7 +126,7 @@
             if(   out_fmt == AV_SAMPLE_FMT_S32P  && in_fmt == AV_SAMPLE_FMT_FLT)
                 ac->simd_f =  ff_unpack_6ch_float_to_int32_a_sse2;
         }
-        if(HAVE_ALIGNED_STACK && channels == 8) {
+        if(channels == 8) {
             if(   out_fmt == AV_SAMPLE_FMT_FLT  && in_fmt == AV_SAMPLE_FMT_FLTP || out_fmt == AV_SAMPLE_FMT_S32 && in_fmt == AV_SAMPLE_FMT_S32P)
                 ac->simd_f =  ff_pack_8ch_float_to_float_a_sse2;
             if(   out_fmt == AV_SAMPLE_FMT_FLT  && in_fmt == AV_SAMPLE_FMT_S32P)
@@ -163,7 +163,7 @@
             if(   out_fmt == AV_SAMPLE_FMT_S32P  && in_fmt == AV_SAMPLE_FMT_FLT)
                 ac->simd_f =  ff_unpack_6ch_float_to_int32_a_avx;
         }
-        if(HAVE_ALIGNED_STACK && channels == 8) {
+        if(channels == 8) {
             if(   out_fmt == AV_SAMPLE_FMT_FLT  && in_fmt == AV_SAMPLE_FMT_FLTP || out_fmt == AV_SAMPLE_FMT_S32 && in_fmt == AV_SAMPLE_FMT_S32P)
                 ac->simd_f =  ff_pack_8ch_float_to_float_a_avx;
             if(   out_fmt == AV_SAMPLE_FMT_FLT  && in_fmt == AV_SAMPLE_FMT_S32P)
diff --git a/libswresample/x86/rematrix_init.c b/libswresample/x86/rematrix_init.c
index e2ee291..918479a 100644
--- a/libswresample/x86/rematrix_init.c
+++ b/libswresample/x86/rematrix_init.c
@@ -30,7 +30,7 @@
 D(int16, mmx)
 D(int16, sse2)
 
-av_cold void swri_rematrix_init_x86(struct SwrContext *s){
+av_cold int swri_rematrix_init_x86(struct SwrContext *s){
 #if HAVE_YASM
     int mm_flags = av_get_cpu_flags();
     int nb_in  = av_get_channel_layout_nb_channels(s->in_ch_layout);
@@ -50,8 +50,11 @@
             s->mix_1_1_simd = ff_mix_1_1_a_int16_sse2;
             s->mix_2_1_simd = ff_mix_2_1_a_int16_sse2;
         }
-        s->native_simd_matrix = av_mallocz(2 * num * sizeof(int16_t));
+        s->native_simd_matrix = av_mallocz_array(num,  2 * sizeof(int16_t));
         s->native_simd_one    = av_mallocz(2 * sizeof(int16_t));
+        if (!s->native_simd_matrix || !s->native_simd_one)
+            return AVERROR(ENOMEM);
+
         for(i=0; i<nb_out; i++){
             int sh = 0;
             for(j=0; j<nb_in; j++)
@@ -74,10 +77,14 @@
             s->mix_1_1_simd = ff_mix_1_1_a_float_avx;
             s->mix_2_1_simd = ff_mix_2_1_a_float_avx;
         }
-        s->native_simd_matrix = av_mallocz(num * sizeof(float));
-        memcpy(s->native_simd_matrix, s->native_matrix, num * sizeof(float));
+        s->native_simd_matrix = av_mallocz_array(num, sizeof(float));
         s->native_simd_one = av_mallocz(sizeof(float));
+        if (!s->native_simd_matrix || !s->native_simd_one)
+            return AVERROR(ENOMEM);
+        memcpy(s->native_simd_matrix, s->native_matrix, num * sizeof(float));
         memcpy(s->native_simd_one, s->native_one, sizeof(float));
     }
 #endif
+
+    return 0;
 }
diff --git a/libswresample/x86/resample_init.c b/libswresample/x86/resample_init.c
index 99f5e14..93001d6 100644
--- a/libswresample/x86/resample_init.c
+++ b/libswresample/x86/resample_init.c
@@ -43,7 +43,7 @@
 RESAMPLE_FUNCS(float,  fma4);
 RESAMPLE_FUNCS(double, sse2);
 
-void swri_resample_dsp_x86_init(ResampleContext *c)
+av_cold void swri_resample_dsp_x86_init(ResampleContext *c)
 {
     int av_unused mm_flags = av_get_cpu_flags();
 
diff --git a/libswscale/bayer_template.c b/libswscale/bayer_template.c
index 67ab2ae..1af1b60 100644
--- a/libswscale/bayer_template.c
+++ b/libswscale/bayer_template.c
@@ -36,12 +36,12 @@
 #define BAYER_SHIFT   0
 #endif
 #if defined(BAYER_16LE)
-#define BAYER_READ(x) AV_RL16(&x)
+#define BAYER_READ(x) AV_RL16(&(x))
 #define BAYER_SIZEOF  2
 #define BAYER_SHIFT   8
 #endif
 #if defined(BAYER_16BE)
-#define BAYER_READ(x) AV_RB16(&x)
+#define BAYER_READ(x) AV_RB16(&(x))
 #define BAYER_SIZEOF  2
 #define BAYER_SHIFT   8
 #endif
diff --git a/libswscale/output.c b/libswscale/output.c
index eee6b48..88fa2b5 100644
--- a/libswscale/output.c
+++ b/libswscale/output.c
@@ -1549,16 +1549,16 @@
                 r = (((R >> 19) + A_DITHER(i,y)  -96)>>8);
                 g = (((G >> 19) + A_DITHER(i + 17,y) - 96)>>8);
                 b = (((B >> 20) + A_DITHER(i + 17*2,y) -96)>>8);
-                r = av_clip(r, 0, 7);
-                g = av_clip(g, 0, 7);
-                b = av_clip(b, 0, 3);
+                r = av_clip_uintp2(r, 3);
+                g = av_clip_uintp2(g, 3);
+                b = av_clip_uintp2(b, 2);
             } else {
                 r = (((R >> 21) + A_DITHER(i,y)-256)>>8);
                 g = (((G >> 19) + A_DITHER(i + 17,y)-256)>>8);
                 b = (((B >> 21) + A_DITHER(i + 17*2,y)-256)>>8);
-                r = av_clip(r, 0, 1);
-                g = av_clip(g, 0, 3);
-                b = av_clip(b, 0, 1);
+                r = av_clip_uintp2(r, 1);
+                g = av_clip_uintp2(g, 2);
+                b = av_clip_uintp2(b, 1);
             }
             break;
         case SWS_DITHER_X_DITHER:
@@ -1568,16 +1568,16 @@
                 r = (((R >> 19) + X_DITHER(i,y) - 96)>>8);
                 g = (((G >> 19) + X_DITHER(i + 17,y) - 96)>>8);
                 b = (((B >> 20) + X_DITHER(i + 17*2,y) - 96)>>8);
-                r = av_clip(r, 0, 7);
-                g = av_clip(g, 0, 7);
-                b = av_clip(b, 0, 3);
+                r = av_clip_uintp2(r, 3);
+                g = av_clip_uintp2(g, 3);
+                b = av_clip_uintp2(b, 2);
             } else {
                 r = (((R >> 21) + X_DITHER(i,y)-256)>>8);
                 g = (((G >> 19) + X_DITHER(i + 17,y)-256)>>8);
                 b = (((B >> 21) + X_DITHER(i + 17*2,y)-256)>>8);
-                r = av_clip(r, 0, 1);
-                g = av_clip(g, 0, 3);
-                b = av_clip(b, 0, 1);
+                r = av_clip_uintp2(r, 1);
+                g = av_clip_uintp2(g, 2);
+                b = av_clip_uintp2(b, 1);
             }
 
             break;
diff --git a/libswscale/ppc/swscale_altivec.c b/libswscale/ppc/swscale_altivec.c
index a1548a7..3034c72 100644
--- a/libswscale/ppc/swscale_altivec.c
+++ b/libswscale/ppc/swscale_altivec.c
@@ -90,7 +90,7 @@
                                   const uint8_t *dither, int offset, int x)
 {
     register int i, j;
-    DECLARE_ALIGNED(16, int, val)[16];
+    LOCAL_ALIGNED(16, int, val, [16]);
     vector signed int vo1, vo2, vo3, vo4;
     vector unsigned short vs1, vs2;
     vector unsigned char vf;
@@ -215,7 +215,7 @@
                                 const int32_t *filterPos, int filterSize)
 {
     register int i;
-    DECLARE_ALIGNED(16, int, tempo)[4];
+    LOCAL_ALIGNED(16, int, tempo, [4]);
 
     if (filterSize % 4) {
         for (i = 0; i < dstW; i++) {
diff --git a/libswscale/swscale.c b/libswscale/swscale.c
index 16a31ce..dff44dd 100644
--- a/libswscale/swscale.c
+++ b/libswscale/swscale.c
@@ -522,7 +522,7 @@
             break;  // we can't output a dstY line so let's try with the next slice
 
 #if HAVE_MMX_INLINE
-        updateMMXDitherTables(c, dstY, lumBufIndex, chrBufIndex,
+        ff_updateMMXDitherTables(c, dstY, lumBufIndex, chrBufIndex,
                               lastInLumBuf, lastInChrBuf);
 #endif
         if (should_dither) {
@@ -742,7 +742,7 @@
     return swscale;
 }
 
-static void reset_ptr(const uint8_t *src[], int format)
+static void reset_ptr(const uint8_t *src[], enum AVPixelFormat format)
 {
     if (!isALPHA(format))
         src[3] = NULL;
@@ -805,9 +805,9 @@
                 c->xyz2rgb_matrix[2][2] * z >> 12;
 
             // limit values to 12-bit depth
-            r = av_clip(r, 0, 4095);
-            g = av_clip(g, 0, 4095);
-            b = av_clip(b, 0, 4095);
+            r = av_clip_uintp2(r, 12);
+            g = av_clip_uintp2(g, 12);
+            b = av_clip_uintp2(b, 12);
 
             // convert from sRGBlinear to RGB and scale from 12bit to 16bit
             if (desc->flags & AV_PIX_FMT_FLAG_BE) {
@@ -861,9 +861,9 @@
                 c->rgb2xyz_matrix[2][2] * b >> 12;
 
             // limit values to 12-bit depth
-            x = av_clip(x, 0, 4095);
-            y = av_clip(y, 0, 4095);
-            z = av_clip(z, 0, 4095);
+            x = av_clip_uintp2(x, 12);
+            y = av_clip_uintp2(y, 12);
+            z = av_clip_uintp2(z, 12);
 
             // convert from XYZlinear to X'Y'Z' and scale from 12bit to 16bit
             if (desc->flags & AV_PIX_FMT_FLAG_BE) {
diff --git a/libswscale/swscale_internal.h b/libswscale/swscale_internal.h
index 37c2b37..55f683f 100644
--- a/libswscale/swscale_internal.h
+++ b/libswscale/swscale_internal.h
@@ -613,7 +613,7 @@
 void ff_yuv2rgb_init_tables_ppc(SwsContext *c, const int inv_table[4],
                                 int brightness, int contrast, int saturation);
 
-void updateMMXDitherTables(SwsContext *c, int dstY, int lumBufIndex, int chrBufIndex,
+void ff_updateMMXDitherTables(SwsContext *c, int dstY, int lumBufIndex, int chrBufIndex,
                            int lastInLumBuf, int lastInChrBuf);
 
 av_cold void ff_sws_init_range_convert(SwsContext *c);
diff --git a/libswscale/utils.c b/libswscale/utils.c
index d2ad20e..7810719 100644
--- a/libswscale/utils.c
+++ b/libswscale/utils.c
@@ -384,7 +384,7 @@
             int j;
             (*filterPos)[i] = xx;
             for (j = 0; j < filterSize; j++) {
-                int64_t d = (FFABS(((int64_t)xx << 17) - xDstInSrc)) << 13;
+                int64_t d = (FFABS(((int64_t)xx * (1 << 17)) - xDstInSrc)) << 13;
                 double floatd;
                 int64_t coeff;
 
@@ -611,14 +611,32 @@
         }
 
         if ((*filterPos)[i] + filterSize > srcW) {
-            int shift = (*filterPos)[i] + filterSize - srcW;
-            // move filter coefficients right to compensate for filterPos
-            for (j = filterSize - 2; j >= 0; j--) {
-                int right = FFMIN(j + shift, filterSize - 1);
-                filter[i * filterSize + right] += filter[i * filterSize + j];
-                filter[i * filterSize + j]      = 0;
+            int shift = (*filterPos)[i] + FFMIN(filterSize - srcW, 0);
+            int64_t acc = 0;
+
+            for (j = filterSize - 1; j >= 0; j--) {
+                if ((*filterPos)[i] + j >= srcW) {
+                    acc += filter[i * filterSize + j];
+                    filter[i * filterSize + j] = 0;
+                }
             }
-            (*filterPos)[i]= srcW - filterSize;
+            for (j = filterSize - 1; j >= 0; j--) {
+                if (j < shift) {
+                    filter[i * filterSize + j] = 0;
+                } else {
+                    filter[i * filterSize + j] = filter[i * filterSize + j - shift];
+                }
+            }
+
+            (*filterPos)[i]-= shift;
+            filter[i * filterSize + srcW - 1 - (*filterPos)[i]] += acc;
+        }
+        av_assert0((*filterPos)[i] >= 0);
+        av_assert0((*filterPos)[i] < srcW);
+        if ((*filterPos)[i] + filterSize > srcW) {
+            for (j = 0; j < filterSize; j++) {
+                av_assert0((*filterPos)[i] + j < srcW || !filter[i * filterSize + j]);
+            }
         }
     }
 
@@ -1166,7 +1184,7 @@
     c->chrDstW = FF_CEIL_RSHIFT(dstW, c->chrDstHSubSample);
     c->chrDstH = FF_CEIL_RSHIFT(dstH, c->chrDstVSubSample);
 
-    FF_ALLOC_OR_GOTO(c, c->formatConvBuffer, FFALIGN(srcW*2+78, 16) * 2, fail);
+    FF_ALLOCZ_OR_GOTO(c, c->formatConvBuffer, FFALIGN(srcW*2+78, 16) * 2, fail);
 
     c->srcBpc = 1 + desc_src->comp[0].depth_minus1;
     if (c->srcBpc < 8)
@@ -1590,8 +1608,13 @@
         filter->chrV = sws_getIdentityVec();
     }
 
+    if (!filter->lumH || !filter->lumV || !filter->chrH || !filter->chrV)
+        goto fail;
+
     if (chromaSharpen != 0.0) {
         SwsVector *id = sws_getIdentityVec();
+        if (!id)
+            goto fail;
         sws_scaleVec(filter->chrH, -chromaSharpen);
         sws_scaleVec(filter->chrV, -chromaSharpen);
         sws_addVec(filter->chrH, id);
@@ -1601,6 +1624,8 @@
 
     if (lumaSharpen != 0.0) {
         SwsVector *id = sws_getIdentityVec();
+        if (!id)
+            goto fail;
         sws_scaleVec(filter->lumH, -lumaSharpen);
         sws_scaleVec(filter->lumV, -lumaSharpen);
         sws_addVec(filter->lumH, id);
@@ -1625,6 +1650,14 @@
         sws_printVec2(filter->lumH, NULL, AV_LOG_DEBUG);
 
     return filter;
+
+fail:
+    sws_freeVec(filter->lumH);
+    sws_freeVec(filter->lumV);
+    sws_freeVec(filter->chrH);
+    sws_freeVec(filter->chrV);
+    av_freep(&filter);
+    return NULL;
 }
 
 SwsVector *sws_allocVec(int length)
diff --git a/libswscale/x86/swscale.c b/libswscale/x86/swscale.c
index fe5c4ea..a06d1f2 100644
--- a/libswscale/x86/swscale.c
+++ b/libswscale/x86/swscale.c
@@ -80,7 +80,7 @@
 #include "swscale_template.c"
 #endif
 
-void updateMMXDitherTables(SwsContext *c, int dstY, int lumBufIndex, int chrBufIndex,
+void ff_updateMMXDitherTables(SwsContext *c, int dstY, int lumBufIndex, int chrBufIndex,
                            int lastInLumBuf, int lastInChrBuf)
 {
     const int dstH= c->dstH;
diff --git a/libswscale/yuv2rgb.c b/libswscale/yuv2rgb.c
index cadd7f8..1d682ba 100644
--- a/libswscale/yuv2rgb.c
+++ b/libswscale/yuv2rgb.c
@@ -720,7 +720,7 @@
     y_table -= elemsize * (inc >> 9);
 
     for (i = 0; i < 256 + 2*YUVRGB_TABLE_HEADROOM; i++) {
-        int64_t cb = av_clip(i-YUVRGB_TABLE_HEADROOM, 0, 255)*inc;
+        int64_t cb = av_clip_uint8(i-YUVRGB_TABLE_HEADROOM)*inc;
         table[i] = y_table + elemsize * (cb >> 16);
     }
 }
@@ -731,7 +731,7 @@
     int off    = -(inc >> 9);
 
     for (i = 0; i < 256 + 2*YUVRGB_TABLE_HEADROOM; i++) {
-        int64_t cb = av_clip(i-YUVRGB_TABLE_HEADROOM, 0, 255)*inc;
+        int64_t cb = av_clip_uint8(i-YUVRGB_TABLE_HEADROOM)*inc;
         table[i] = elemsize * (off + (cb >> 16));
     }
 }
diff --git a/tests/Makefile b/tests/Makefile
index 065be41..8505211 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -195,7 +195,7 @@
 
 $(FATE) $(FATE_TESTS-no): $(FATE_UTILS:%=tests/%$(HOSTEXESUF))
 	@echo "TEST    $(@:fate-%=%)"
-	$(Q)$(SRC_PATH)/tests/fate-run.sh $@ "$(TARGET_SAMPLES)" "$(TARGET_EXEC)" "$(TARGET_PATH)" '$(CMD)' '$(CMP)' '$(REF)' '$(FUZZ)' '$(THREADS)' '$(THREAD_TYPE)' '$(CPUFLAGS)' '$(CMP_SHIFT)' '$(CMP_TARGET)' '$(SIZE_TOLERANCE)' '$(CMP_UNIT)' '$(GEN)'
+	$(Q)$(SRC_PATH)/tests/fate-run.sh $@ "$(TARGET_SAMPLES)" "$(TARGET_EXEC)" "$(TARGET_PATH)" '$(CMD)' '$(CMP)' '$(REF)' '$(FUZZ)' '$(THREADS)' '$(THREAD_TYPE)' '$(CPUFLAGS)' '$(CMP_SHIFT)' '$(CMP_TARGET)' '$(SIZE_TOLERANCE)' '$(CMP_UNIT)' '$(GEN)' '$(HWACCEL)'
 
 fate-list:
 	@printf '%s\n' $(sort $(FATE))
diff --git a/tests/fate-run.sh b/tests/fate-run.sh
index f78e4fc..fec3c5e 100755
--- a/tests/fate-run.sh
+++ b/tests/fate-run.sh
@@ -23,6 +23,7 @@
 size_tolerance=${14:-0}
 cmp_unit=${15:-2}
 gen=${16:-no}
+hwaccel=${17:-none}
 
 outdir="tests/data/fate"
 outfile="${outdir}/${test}"
@@ -38,7 +39,7 @@
 # $1=value1, $2=value2, $3=threshold
 # prints 0 if absolute difference between value1 and value2 is <= threshold
 compare(){
-    echo "scale=2; v = $1 - $2; if (v < 0) v = -v; if (v > $3) r = 1; r" | bc
+    awk "BEGIN { v = $1 - $2; printf ((v < 0 ? -v : v) > $3) }"
 }
 
 do_tiny_psnr(){
@@ -50,6 +51,12 @@
     size_cmp=$(compare $size1 $size2 $size_tolerance)
     if [ "$val_cmp" != 0 ] || [ "$size_cmp" != 0 ]; then
         echo "$psnr"
+        if [ "$val_cmp" != 0 ]; then
+            echo "$3: |$val - $cmp_target| >= $fuzz"
+        fi
+        if [ "$size_cmp" != 0 ]; then
+            echo "size: |$size1 - $size2| >= $size_tolerance"
+        fi
         return 1
     fi
 }
@@ -85,7 +92,7 @@
 }
 
 ffmpeg(){
-    dec_opts="-threads $threads -thread_type $thread_type"
+    dec_opts="-hwaccel $hwaccel -threads $threads -thread_type $thread_type"
     ffmpeg_args="-nostats -cpuflags $cpuflags"
     for arg in $@; do
         [ x${arg} = x-i ] && ffmpeg_args="${ffmpeg_args} ${dec_opts}"
diff --git a/tests/fate.sh b/tests/fate.sh
index 5a78018..81224b6 100755
--- a/tests/fate.sh
+++ b/tests/fate.sh
@@ -51,6 +51,7 @@
         --enable-avresample                                             \
         ${arch:+--arch=$arch}                                           \
         ${cpu:+--cpu="$cpu"}                                            \
+        ${toolchain:+--toolchain="$toolchain"}                          \
         ${cross_prefix:+--cross-prefix="$cross_prefix"}                 \
         ${as:+--as="$as"}                                               \
         ${cc:+--cc="$cc"}                                               \
diff --git a/tests/fate/aac.mak b/tests/fate/aac.mak
index bc52cad..34823be 100644
--- a/tests/fate/aac.mak
+++ b/tests/fate/aac.mak
@@ -66,6 +66,10 @@
 fate-aac-er_eld2000np_48_ep0: CMD = pcm -i $(TARGET_SAMPLES)/aac/er_eld2000np_48_ep0.mp4
 fate-aac-er_eld2000np_48_ep0: REF = $(SAMPLES)/aac/er_eld2000np_48_ep0.s16
 
+FATE_AAC += fate-aac-er_eld2100np_48_ep0
+fate-aac-er_eld2100np_48_ep0: CMD = pcm -i $(TARGET_SAMPLES)/aac/er_eld2100np_48_ep0.mp4
+fate-aac-er_eld2100np_48_ep0: REF = $(SAMPLES)/aac/er_eld2100np_48.s16
+
 
 fate-aac-ct%: CMD = pcm -i $(TARGET_SAMPLES)/aac/CT_DecoderCheck/$(@:fate-aac-ct-%=%)
 fate-aac-ct%: REF = $(SAMPLES)/aac/CT_DecoderCheck/aacPlusv2.wav
@@ -87,8 +91,9 @@
 fate-aac-aref-encode: CMP = stddev
 fate-aac-aref-encode: REF = ./tests/data/asynth-44100-2.wav
 fate-aac-aref-encode: CMP_SHIFT = -4096
-fate-aac-aref-encode: CMP_TARGET = 1862
+fate-aac-aref-encode: CMP_TARGET = 434
 fate-aac-aref-encode: SIZE_TOLERANCE = 2464
+fate-aac-aref-encode: FUZZ = 5
 
 FATE_AAC_ENCODE += fate-aac-ln-encode
 fate-aac-ln-encode: CMD = enc_dec_pcm adts wav s16le $(TARGET_SAMPLES)/audio-reference/luckynight_2ch_44kHz_s16.wav -strict -2 -c:a aac -b:a 512k
diff --git a/tests/fate/acodec.mak b/tests/fate/acodec.mak
index 325bbd9..b7e510c 100644
--- a/tests/fate/acodec.mak
+++ b/tests/fate/acodec.mak
@@ -140,6 +140,16 @@
 fate-acodec-roqaudio: ENCOPTS = -ar 22050
 fate-acodec-roqaudio: DECOPTS = -ar 44100
 
+FATE_ACODEC-$(call ENCDEC, S302M, MPEGTS) += fate-acodec-s302m
+fate-acodec-s302m: FMT = mpegts
+fate-acodec-s302m: CODEC = s302m
+fate-acodec-s302m: ENCOPTS = -ar 48000 -strict -2
+fate-acodec-s302m: DECOPTS = -ar 44100
+
+FATE_ACODEC-$(call ENCDEC, WAVPACK, WV) += fate-acodec-wavpack
+fate-acodec-wavpack: FMT = wv
+fate-acodec-wavpack: CODEC = wavpack -compression_level 1
+
 FATE_ACODEC += $(FATE_ACODEC-yes)
 
 $(FATE_ACODEC): tests/data/asynth-44100-2.wav
diff --git a/tests/fate/audio.mak b/tests/fate/audio.mak
index b7e5362..7ab4038 100644
--- a/tests/fate/audio.mak
+++ b/tests/fate/audio.mak
@@ -16,13 +16,25 @@
 FATE_SAMPLES_AUDIO-$(call DEMDEC, BMV, BMV_AUDIO) += fate-bmv-audio
 fate-bmv-audio: CMD = framecrc -i $(TARGET_SAMPLES)/bmv/SURFING-partial.BMV -vn
 
+FATE_DCA-$(CONFIG_MPEGTS_DEMUXER) += fate-dca-core
+fate-dca-core: CMD = pcm -i $(TARGET_SAMPLES)/dts/dts.ts
+fate-dca-core: CMP = oneoff
+fate-dca-core: REF = $(SAMPLES)/dts/dts.pcm
+
+FATE_DCA-$(CONFIG_DTS_DEMUXER) += fate-dca-xll
+fate-dca-xll: CMD = pcm -disable_xll 0 -i $(TARGET_SAMPLES)/dts/master_audio_7.1_24bit.dts
+fate-dca-xll: CMP = oneoff
+fate-dca-xll: REF = $(SAMPLES)/dts/master_audio_7.1_24bit.pcm
+
+FATE_SAMPLES_AUDIO-$(CONFIG_DCA_DECODER) += $(FATE_DCA-yes)
+fate-dca: $(FATE_DCA-yes)
+
 FATE_SAMPLES_AUDIO-$(call DEMDEC, DSICIN, DSICINAUDIO) += fate-delphine-cin-audio
 fate-delphine-cin-audio: CMD = framecrc -i $(TARGET_SAMPLES)/delphine-cin/LOGO-partial.CIN -vn
 
-FATE_SAMPLES_AUDIO-$(call DEMDEC, MPEGTS, DCA) += fate-dts
-fate-dts: CMD = pcm -i $(TARGET_SAMPLES)/dts/dts.ts
-fate-dts: CMP = oneoff
-fate-dts: REF = $(SAMPLES)/dts/dts.pcm
+FATE_SAMPLES_AUDIO-$(call DEMDEC, DSS, DSS_SP) += fate-dss-lp fate-dss-sp
+fate-dss-lp: CMD = framecrc -i $(TARGET_SAMPLES)/dss/lp.dss -frames 30
+fate-dss-sp: CMD = framecrc -i $(TARGET_SAMPLES)/dss/sp.dss -frames 30
 
 FATE_SAMPLES_AUDIO-$(call DEMDEC, DTS, DCA) += fate-dts_es
 fate-dts_es: CMD = pcm -i $(TARGET_SAMPLES)/dts/dts_es.dts
diff --git a/tests/fate/avformat.mak b/tests/fate/avformat.mak
index 1040afa..4e7a440 100644
--- a/tests/fate/avformat.mak
+++ b/tests/fate/avformat.mak
@@ -22,6 +22,7 @@
 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, DNXHD,      PCM_S16LE, MXF_OPATOM MXF)     += mxf_opatom
 FATE_LAVF-$(call ENCDEC2, MPEG4,      MP2,       NUT)                += nut
 FATE_LAVF-$(call ENCDEC,  FLAC,                  OGG)                += ogg
 FATE_LAVF-$(call ENCDEC,  PAM,                   IMAGE2)             += pam
diff --git a/tests/fate/filter-video.mak b/tests/fate/filter-video.mak
index e50e387..330ea73 100644
--- a/tests/fate/filter-video.mak
+++ b/tests/fate/filter-video.mak
@@ -29,6 +29,27 @@
 FATE_FILTER-$(call ALLYES, SHOWPALETTE_FILTER FLIC_DEMUXER FLIC_DECODER) += fate-filter-showpalette
 fate-filter-showpalette: CMD = framecrc -i $(TARGET_SAMPLES)/fli/fli-engines.fli -vf showpalette=3 -pix_fmt bgra
 
+FATE_FILTER_PALETTEGEN += fate-filter-palettegen-1
+fate-filter-palettegen-1: CMD = framecrc -i $(TARGET_SAMPLES)/filter/anim.mkv -vf palettegen -pix_fmt bgra
+
+FATE_FILTER_PALETTEGEN += fate-filter-palettegen-2
+fate-filter-palettegen-2: CMD = framecrc -i $(TARGET_SAMPLES)/filter/anim.mkv -vf palettegen=max_colors=128:reserve_transparent=0:stats_mode=diff -pix_fmt bgra
+
+fate-filter-palettegen: $(FATE_FILTER_PALETTEGEN)
+FATE_FILTER-$(call ALLYES, PALETTEGEN_FILTER MATROSKA_DEMUXER H264_DECODER) += $(FATE_FILTER_PALETTEGEN)
+
+FATE_FILTER_PALETTEUSE += fate-filter-paletteuse-nodither
+fate-filter-paletteuse-nodither: CMD = framecrc -i $(TARGET_SAMPLES)/filter/anim.mkv -i $(TARGET_SAMPLES)/filter/anim-palette.png -lavfi paletteuse=none -pix_fmt bgra
+
+FATE_FILTER_PALETTEUSE += fate-filter-paletteuse-bayer
+fate-filter-paletteuse-bayer: CMD = framecrc -i $(TARGET_SAMPLES)/filter/anim.mkv -i $(TARGET_SAMPLES)/filter/anim-palette.png -lavfi paletteuse=bayer -pix_fmt bgra
+
+FATE_FILTER_PALETTEUSE += fate-filter-paletteuse-sierra2_4a
+fate-filter-paletteuse-sierra2_4a: CMD = framecrc -i $(TARGET_SAMPLES)/filter/anim.mkv -i $(TARGET_SAMPLES)/filter/anim-palette.png -lavfi paletteuse=sierra2_4a:diff_mode=rectangle -pix_fmt bgra
+
+fate-filter-paletteuse: $(FATE_FILTER_PALETTEUSE)
+FATE_FILTER-$(call ALLYES, PALETTEUSE_FILTER MATROSKA_DEMUXER H264_DECODER IMAGE2_DEMUXER PNG_DECODER) += $(FATE_FILTER_PALETTEUSE)
+
 FATE_SAMPLES_AVCONV += $(FATE_FILTER-yes)
 
 FATE_FILTER-$(call ALLYES, AVDEVICE LIFE_FILTER) += fate-filter-lavd-life
diff --git a/tests/fate/libavutil.mak b/tests/fate/libavutil.mak
index 92a7f05..58307ae 100644
--- a/tests/fate/libavutil.mak
+++ b/tests/fate/libavutil.mak
@@ -108,6 +108,11 @@
 fate-tree: CMD = run libavutil/tree-test
 fate-tree: REF = /dev/null
 
+FATE_LIBAVUTIL += fate-twofish
+fate-twofish: libavutil/twofish-test$(EXESUF)
+fate-twofish: CMD = run libavutil/twofish-test
+fate-twofish: REF = /dev/null
+
 FATE_LIBAVUTIL += fate-xtea
 fate-xtea: libavutil/xtea-test$(EXESUF)
 fate-xtea: CMD = run libavutil/xtea-test
diff --git a/tests/fate/qt.mak b/tests/fate/qt.mak
index 6d78822..670523e 100644
--- a/tests/fate/qt.mak
+++ b/tests/fate/qt.mak
@@ -46,6 +46,9 @@
 FATE_QT-$(call DEMDEC, MOV, SVQ1) += fate-svq1
 fate-svq1: CMD = framecrc -i $(TARGET_SAMPLES)/svq1/marymary-shackles.mov -an -t 10
 
+FATE_QT-$(call DEMDEC, MOV, SVQ1) += fate-svq1-headerswap
+fate-svq1-headerswap: CMD = framecrc -i $(TARGET_SAMPLES)/svq1/ct_ending_cut.mov -frames 4
+
 FATE_QT-$(call ALLYES, MOV_DEMUXER SVQ3_DECODER ZLIB) += fate-svq3
 fate-svq3: CMD = framecrc -i $(TARGET_SAMPLES)/svq3/Vertical400kbit.sorenson3.mov -t 6 -an
 
diff --git a/tests/fate/screen.mak b/tests/fate/screen.mak
index 72e9b4c..9142d49 100644
--- a/tests/fate/screen.mak
+++ b/tests/fate/screen.mak
@@ -29,6 +29,9 @@
 FATE_SCREEN-$(call DEMDEC, AVI, FRAPS) += $(FATE_FRAPS)
 fate-fraps: $(FATE_FRAPS)
 
+FATE_SAMPLES_AVCONV-$(call DEMDEC, ASF, TDSC) += fate-tdsc
+fate-tdsc: CMD = framecrc -idct simple -i $(TARGET_SAMPLES)/tdsc/tdsc.asf -an -pix_fmt bgr24
+
 FATE_TSCC += fate-tscc-15bit
 fate-tscc-15bit: CMD = framecrc -i $(TARGET_SAMPLES)/tscc/oneminute.avi -t 15 -pix_fmt rgb24
 
@@ -38,8 +41,14 @@
 FATE_SCREEN-$(call DEMDEC, AVI, TSCC) += $(FATE_TSCC)
 fate-tscc: $(FATE_TSCC)
 
-FATE_SAMPLES_AVCONV-$(call DEMDEC, AVI, TSCC2) += fate-tscc2
-fate-tscc2: CMD = framecrc -i $(TARGET_SAMPLES)/tscc/tsc2_16bpp.avi
+FATE_TSCC2-$(CONFIG_AVI_DEMUXER) += fate-tscc2-avi
+fate-tscc2-avi: CMD = framecrc -i $(TARGET_SAMPLES)/tscc/tsc2_16bpp.avi
+
+FATE_TSCC2-$(CONFIG_MOV_DEMUXER) += fate-tscc2-mov
+fate-tscc2-mov: CMD = framecrc -i $(TARGET_SAMPLES)/tscc/rec.trec
+
+FATE_SAMPLES_AVCONV-$(CONFIG_TSCC2_DECODER) += $(FATE_TSCC2-yes)
+fate-tscc2: $(FATE_TSCC2-yes)
 
 FATE_VMNC += fate-vmnc-16bit
 fate-vmnc-16bit: CMD = framecrc -i $(TARGET_SAMPLES)/VMnc/test.avi -pix_fmt rgb24
diff --git a/tests/fate/seek.mak b/tests/fate/seek.mak
index 105f3c7..4f4ccff 100644
--- a/tests/fate/seek.mak
+++ b/tests/fate/seek.mak
@@ -178,6 +178,7 @@
 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, DNXHD,      PCM_S16LE, MXF_OPATOM MXF) += mxf_opatom
 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
@@ -216,6 +217,7 @@
 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-mxf_opatom: SRC = lavf/lavf.mxf_opatom
 fate-seek-lavf-nut:      SRC = lavf/lavf.nut
 fate-seek-lavf-ogg:      SRC = lavf/lavf.ogg
 fate-seek-lavf-pbmpipe:  SRC = lavf/pbmpipe.pbm
diff --git a/tests/fate/vcodec.mak b/tests/fate/vcodec.mak
index 6363117..0aba87b 100644
--- a/tests/fate/vcodec.mak
+++ b/tests/fate/vcodec.mak
@@ -118,10 +118,11 @@
 FATE_VCODEC-$(call ENCDEC, LJPEG MJPEG, AVI) += ljpeg
 fate-vsynth%-ljpeg:              ENCOPTS = -strict -1
 
-FATE_VCODEC-$(call ENCDEC, MJPEG, AVI)  += mjpeg mjpeg-422 mjpeg-444
+FATE_VCODEC-$(call ENCDEC, MJPEG, AVI)  += mjpeg mjpeg-422 mjpeg-444 mjpeg-trell
 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-vsynth%-mjpeg-trell:        ENCOPTS = -qscale 9 -pix_fmt yuvj420p -trellis 1
 
 FATE_VCODEC-$(call ENCDEC, MPEG1VIDEO, MPEG1VIDEO MPEGVIDEO) += mpeg1 mpeg1b
 fate-vsynth%-mpeg1:              FMT     = mpeg1video
diff --git a/tests/fate/video.mak b/tests/fate/video.mak
index 7e5416c..08eae86 100644
--- a/tests/fate/video.mak
+++ b/tests/fate/video.mak
@@ -13,6 +13,9 @@
 FATE_VIDEO-$(call DEMDEC, MOV, AIC) += fate-aic
 fate-aic: CMD = framecrc -idct simple -i $(TARGET_SAMPLES)/aic/small_apple_intermediate_codec.mov -an -vframes 15
 
+FATE_VIDEO-$(call DEMDEC, MOV, AIC) += fate-aic-oddsize
+fate-aic-oddsize: CMD = framecrc -idct simple -i $(TARGET_SAMPLES)/aic/aic_odd_dimensions.mov
+
 FATE_VIDEO-$(call DEMDEC, MM, MMVIDEO) += fate-alg-mm
 fate-alg-mm: CMD = framecrc -i $(TARGET_SAMPLES)/alg-mm/ibmlogo.mm -an -pix_fmt rgb24
 
@@ -57,6 +60,15 @@
 FATE_VIDEO-$(call DEMDEC, BMV, BMV_VIDEO) += fate-bmv-video
 fate-bmv-video: CMD = framecrc -i $(TARGET_SAMPLES)/bmv/SURFING-partial.BMV -pix_fmt rgb24 -an
 
+FATE_CANOPUS_HQX += fate-canopus-hqx422
+fate-canopus-hqx422: CMD = framecrc -i $(TARGET_SAMPLES)/canopus/hqx422.avi -pix_fmt yuv422p16be -an
+
+FATE_CANOPUS_HQX += fate-canopus-hqx422a
+fate-canopus-hqx422a: CMD = framecrc -i $(TARGET_SAMPLES)/canopus/hqx422a.avi -pix_fmt yuv422p16be -an
+
+FATE_VIDEO-$(call DEMDEC, AVI, HQX) += $(FATE_CANOPUS_HQX)
+fate-canopus-hqx: $(FATE_CANOPUS_HQX)
+
 FATE_VIDEO-$(call DEMDEC, MPEGPS, CAVS) += fate-cavs
 fate-cavs: CMD = framecrc -i $(TARGET_SAMPLES)/cavs/cavs.mpg -an
 
diff --git a/tests/fate/vpx.mak b/tests/fate/vpx.mak
index 0ef8dcc..83cda9c 100644
--- a/tests/fate/vpx.mak
+++ b/tests/fate/vpx.mak
@@ -102,6 +102,7 @@
 $(eval $(call FATE_VP9_SUITE,segmentation-sf-akiyo,$(1),$(2)))
 $(eval $(call FATE_VP9_SUITE,tiling-pedestrian,$(1),$(2)))
 $(eval $(call FATE_VP9_SUITE,trac3849,$(1),$(2)))
+$(eval $(call FATE_VP9_SUITE,trac4359,$(1),$(2)))
 endef
 
 $(eval $(call FATE_VP9_FULL))
diff --git a/tests/lavf-regression.sh b/tests/lavf-regression.sh
index 947e0f9..c5cb597 100755
--- a/tests/lavf-regression.sh
+++ b/tests/lavf-regression.sh
@@ -90,6 +90,10 @@
 do_lavf mxf_d10 "-ar 48000 -ac 2" "-r 25 -vf scale=720:576,pad=720:608:0:32 -vcodec mpeg2video -g 0 -flags +ildct+low_delay -dc 10 -non_linear_quant 1 -intra_vlc 1 -qscale 1 -ps 1 -qmin 1 -rc_max_vbv_use 1 -rc_min_vbv_use 1 -pix_fmt yuv422p -minrate 30000k -maxrate 30000k -b 30000k -bufsize 1200000 -top 1 -rc_init_occupancy 1200000 -qmax 12 -f mxf_d10"
 fi
 
+if [ -n "$do_mxf_opatom" ]; then
+do_lavf mxf_opatom "" "-s 1920x1080 -vcodec dnxhd -pix_fmt yuv422p -vb 36M -f mxf_opatom -map 0"
+fi
+
 if [ -n "$do_ts" ] ; then
 do_lavf ts "" "-ab 64k -mpegts_transport_stream_id 42 -ar 44100 -threads 1"
 fi
diff --git a/tests/ref/acodec/s302m b/tests/ref/acodec/s302m
new file mode 100644
index 0000000..f19eebe
--- /dev/null
+++ b/tests/ref/acodec/s302m
@@ -0,0 +1,4 @@
+2d1494ad78292dca556fd079ec27f28d *tests/data/fate/acodec-s302m.mpegts
+1589164 tests/data/fate/acodec-s302m.mpegts
+f9b6528eee1aea04640ee83400c78689 *tests/data/fate/acodec-s302m.out.wav
+stddev:  986.97 PSNR: 36.44 MAXDIFF:18642 bytes:  1058400/  1056708
diff --git a/tests/ref/acodec/wavpack b/tests/ref/acodec/wavpack
new file mode 100644
index 0000000..02f09ae
--- /dev/null
+++ b/tests/ref/acodec/wavpack
@@ -0,0 +1,4 @@
+000420796cc3e526650ce6f4c6334471 *tests/data/fate/acodec-wavpack.wv
+338166 tests/data/fate/acodec-wavpack.wv
+95e54b261530a1bcf6de6fe3b21dc5f6 *tests/data/fate/acodec-wavpack.out.wav
+stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/fate/aic-oddsize b/tests/ref/fate/aic-oddsize
new file mode 100644
index 0000000..9183089
--- /dev/null
+++ b/tests/ref/fate/aic-oddsize
@@ -0,0 +1,58 @@
+#tb 0: 1000/14587
+0,          0,          0,        1,   174243, 0xa40491e1
+0,          1,          1,        1,   174243, 0xa12cbb56
+0,          2,          2,        1,   174243, 0xa12cbb56
+0,          3,          3,        1,   174243, 0xa12cbb56
+0,          4,          4,        1,   174243, 0xa12cbb56
+0,          5,          5,        1,   174243, 0xa12cbb56
+0,          6,          6,        1,   174243, 0xa12cbb56
+0,          7,          7,        1,   174243, 0xa12cbb56
+0,          8,          8,        1,   174243, 0xa12cbb56
+0,          9,          9,        1,   174243, 0x4e7b7299
+0,         10,         10,        1,   174243, 0x31573b99
+0,         11,         11,        1,   174243, 0x013397b6
+0,         12,         12,        1,   174243, 0xdd988ab8
+0,         13,         13,        1,   174243, 0xd6d96b1e
+0,         14,         14,        1,   174243, 0xd6d96b1e
+0,         15,         15,        1,   174243, 0xd6d96b1e
+0,         16,         16,        1,   174243, 0x111627d3
+0,         17,         17,        1,   174243, 0x284d9ab7
+0,         18,         18,        1,   174243, 0xa348c492
+0,         19,         19,        1,   174243, 0xa348c492
+0,         20,         20,        1,   174243, 0xa348c492
+0,         21,         21,        1,   174243, 0xa348c492
+0,         22,         22,        1,   174243, 0x2d22c3b8
+0,         23,         23,        1,   174243, 0x2d22c3b8
+0,         24,         24,        1,   174243, 0x2d22c3b8
+0,         25,         25,        1,   174243, 0x2d22c3b8
+0,         26,         26,        1,   174243, 0xa6d7c890
+0,         27,         27,        1,   174243, 0x8068bfbb
+0,         28,         28,        1,   174243, 0x420ae647
+0,         29,         29,        1,   174243, 0xc5467756
+0,         30,         30,        1,   174243, 0x238a13dd
+0,         31,         31,        1,   174243, 0x5bab75dc
+0,         32,         32,        1,   174243, 0x14d7f61f
+0,         33,         33,        1,   174243, 0x2e1d334f
+0,         34,         34,        1,   174243, 0xeade7dc0
+0,         35,         35,        1,   174243, 0xeade7dc0
+0,         36,         36,        1,   174243, 0xeade7dc0
+0,         37,         37,        1,   174243, 0xeade7dc0
+0,         38,         38,        1,   174243, 0x088c7ef9
+0,         39,         39,        1,   174243, 0x70a3554e
+0,         40,         40,        1,   174243, 0x0753d1d4
+0,         41,         41,        1,   174243, 0x8266bd6d
+0,         42,         42,        1,   174243, 0x4ce3cda9
+0,         43,         43,        1,   174243, 0x4ce3cda9
+0,         44,         44,        1,   174243, 0x4ce3cda9
+0,         45,         45,        1,   174243, 0x4ce3cda9
+0,         46,         46,        1,   174243, 0xe5f7cd98
+0,         47,         47,        1,   174243, 0xe5f7cd98
+0,         48,         48,        1,   174243, 0xe5f7cd98
+0,         49,         49,        1,   174243, 0xe5f7cd98
+0,         50,         50,        1,   174243, 0x78c5cdb7
+0,         51,         51,        1,   174243, 0x78c5cdb7
+0,         52,         52,        1,   174243, 0x78c5cdb7
+0,         53,         53,        1,   174243, 0xce7ccd92
+0,         54,         54,        1,   174243, 0xce7ccd92
+0,         55,         55,        1,   174243, 0xce7ccd92
+0,         56,         56,        1,   174243, 0xce7ccd92
diff --git a/tests/ref/fate/canopus-hqx422 b/tests/ref/fate/canopus-hqx422
new file mode 100644
index 0000000..2e1fdf1
--- /dev/null
+++ b/tests/ref/fate/canopus-hqx422
@@ -0,0 +1,2 @@
+#tb 0: 1/25
+0,          0,          0,        1,  1658880, 0x823fcbac
diff --git a/tests/ref/fate/canopus-hqx422a b/tests/ref/fate/canopus-hqx422a
new file mode 100644
index 0000000..29dc307
--- /dev/null
+++ b/tests/ref/fate/canopus-hqx422a
@@ -0,0 +1,2 @@
+#tb 0: 1/25
+0,          0,          0,        1,  8294400, 0x9b38264d
diff --git a/tests/ref/fate/dss-lp b/tests/ref/fate/dss-lp
new file mode 100644
index 0000000..b5bee18
--- /dev/null
+++ b/tests/ref/fate/dss-lp
@@ -0,0 +1,31 @@
+#tb 0: 1/8000
+0,          0,          0,      240,      480, 0xf1107658
+0,        240,        240,      240,      480, 0x50dee179
+0,        480,        480,      240,      480, 0x40090802
+0,        720,        720,      240,      480, 0x3ef9f6ff
+0,        960,        960,      240,      480, 0x5b7df231
+0,       1200,       1200,      240,      480, 0xe266efd1
+0,       1440,       1440,      240,      480, 0xfbe6e658
+0,       1680,       1680,      240,      480, 0xde84f311
+0,       1920,       1920,      240,      480, 0x5854ec2f
+0,       2160,       2160,      240,      480, 0x4901cdea
+0,       2400,       2400,      240,      480, 0x03f3e619
+0,       2640,       2640,      240,      480, 0x47abfe87
+0,       2880,       2880,      240,      480, 0x69dddf34
+0,       3120,       3120,      240,      480, 0x1cfeee2c
+0,       3360,       3360,      240,      480, 0x1860ef1c
+0,       3600,       3600,      240,      480, 0x8f86e8ed
+0,       3840,       3840,      240,      480, 0x307deaf8
+0,       4080,       4080,      240,      480, 0xeca7eca0
+0,       4320,       4320,      240,      480, 0x1835ee1c
+0,       4560,       4560,      240,      480, 0x6676ed66
+0,       4800,       4800,      240,      480, 0x49c2fd04
+0,       5040,       5040,      240,      480, 0xc463db75
+0,       5280,       5280,      240,      480, 0x1931ed7d
+0,       5520,       5520,      240,      480, 0xc99ff886
+0,       5760,       5760,      240,      480, 0xcd3ae8de
+0,       6000,       6000,      240,      480, 0x2294ecfa
+0,       6240,       6240,      240,      480, 0xcf5ef14b
+0,       6480,       6480,      240,      480, 0x6325d4fe
+0,       6720,       6720,      240,      480, 0x3790dcf2
+0,       6960,       6960,      240,      480, 0x0fbee6c0
diff --git a/tests/ref/fate/dss-sp b/tests/ref/fate/dss-sp
new file mode 100644
index 0000000..111c621
--- /dev/null
+++ b/tests/ref/fate/dss-sp
@@ -0,0 +1,31 @@
+#tb 0: 1/11025
+0,          0,          0,      264,      528, 0xa2579e96
+0,        264,        264,      264,      528, 0xf9b23172
+0,        528,        528,      264,      528, 0x5571a0fe
+0,        792,        792,      264,      528, 0x2c989245
+0,       1056,       1056,      264,      528, 0xc4d3b5b5
+0,       1320,       1320,      264,      528, 0x0becb08d
+0,       1584,       1584,      264,      528, 0x71537374
+0,       1848,       1848,      264,      528, 0xed6e4784
+0,       2112,       2112,      264,      528, 0x8dc73f7e
+0,       2376,       2376,      264,      528, 0x20804ba8
+0,       2640,       2640,      264,      528, 0xcfdd4803
+0,       2904,       2904,      264,      528, 0x6fad0da5
+0,       3168,       3168,      264,      528, 0xeaa41f45
+0,       3432,       3432,      264,      528, 0x99ef463e
+0,       3696,       3696,      264,      528, 0x5a8c256a
+0,       3960,       3960,      264,      528, 0x668c253a
+0,       4224,       4224,      264,      528, 0x29890b2e
+0,       4488,       4488,      264,      528, 0x6cd51639
+0,       4752,       4752,      264,      528, 0x6cc95342
+0,       5016,       5016,      264,      528, 0x2bdc59ea
+0,       5280,       5280,      264,      528, 0x72ff263d
+0,       5544,       5544,      264,      528, 0xb5bd3592
+0,       5808,       5808,      264,      528, 0x16de4402
+0,       6072,       6072,      264,      528, 0x80195ab4
+0,       6336,       6336,      264,      528, 0x425c594c
+0,       6600,       6600,      264,      528, 0x04b32203
+0,       6864,       6864,      264,      528, 0x688a38ec
+0,       7128,       7128,      264,      528, 0x34531167
+0,       7392,       7392,      264,      528, 0xdef83475
+0,       7656,       7656,      264,      528, 0xf5fe3fe5
diff --git a/tests/ref/fate/ffprobe_compact b/tests/ref/fate/ffprobe_compact
index 84d9667..fb0b834 100644
--- a/tests/ref/fate/ffprobe_compact
+++ b/tests/ref/fate/ffprobe_compact
@@ -27,6 +27,6 @@
 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=1024801|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|best_effort_timestamp=6144|best_effort_timestamp_time=0.120000|pkt_duration=2048|pkt_duration_time=0.040000|pkt_pos=1024801|pkt_size=30000|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
 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|channel_layout=unknown|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=N/A|duration=N/A|bit_rate=705600|max_bit_rate=N/A|bits_per_raw_sample=N/A|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²|tag:encoder=Lavc pcm_s16le
-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|color_range=N/A|color_space=unknown|color_transfer=unknown|color_primaries=unknown|chroma_location=unspecified|timecode=N/A|refs=1|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=N/A|duration=N/A|bit_rate=N/A|max_bit_rate=N/A|bits_per_raw_sample=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|tag:encoder=Lavc rawvideo
-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|color_range=N/A|color_space=unknown|color_transfer=unknown|color_primaries=unknown|chroma_location=unspecified|timecode=N/A|refs=1|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=N/A|duration=N/A|bit_rate=N/A|max_bit_rate=N/A|bits_per_raw_sample=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:encoder=Lavc rawvideo
+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|coded_width=320|coded_height=240|has_b_frames=0|sample_aspect_ratio=1:1|display_aspect_ratio=4:3|pix_fmt=rgb24|level=-99|color_range=N/A|color_space=unknown|color_transfer=unknown|color_primaries=unknown|chroma_location=unspecified|timecode=N/A|refs=1|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=N/A|duration=N/A|bit_rate=N/A|max_bit_rate=N/A|bits_per_raw_sample=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|tag:encoder=Lavc rawvideo
+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|coded_width=100|coded_height=100|has_b_frames=0|sample_aspect_ratio=1:1|display_aspect_ratio=1:1|pix_fmt=rgb24|level=-99|color_range=N/A|color_space=unknown|color_transfer=unknown|color_primaries=unknown|chroma_location=unspecified|timecode=N/A|refs=1|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=N/A|duration=N/A|bit_rate=N/A|max_bit_rate=N/A|bits_per_raw_sample=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:encoder=Lavc rawvideo
 format|filename=tests/data/ffprobe-test.nut|nb_streams=3|nb_programs=0|format_name=nut|start_time=0.000000|duration=0.120000|size=1054882|bit_rate=70325466|probe_score=100|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 c428d4f..496477f 100644
--- a/tests/ref/fate/ffprobe_csv
+++ b/tests/ref/fate/ffprobe_csv
@@ -27,6 +27,6 @@
 packet,video,2,6144,0.120000,6144,0.120000,2048,0.040000,N/A,N/A,30000,1024801,K
 frame,video,1,6144,0.120000,6144,0.120000,6144,0.120000,2048,0.040000,1024801,30000,100,100,rgb24,1:1,I,0,0,0,0,0
 stream,0,pcm_s16le,unknown,audio,1/44100,PSD[16],0x10445350,s16,44100,1,unknown,16,N/A,0/0,0/0,1/44100,0,0.000000,N/A,N/A,705600,N/A,N/A,N/A,6,6,0,0,0,0,0,0,0,0,0,0,0,mc²,Lavc pcm_s16le
-stream,1,rawvideo,unknown,video,1/51200,RGB[24],0x18424752,320,240,0,1:1,4:3,rgb24,-99,N/A,unknown,unknown,unknown,unspecified,N/A,1,N/A,25/1,25/1,1/51200,0,0.000000,N/A,N/A,N/A,N/A,N/A,N/A,4,4,0,0,0,0,0,0,0,0,0,0,0,foobar,field-and-tags-conflict-attempt,Lavc rawvideo
-stream,2,rawvideo,unknown,video,1/51200,RGB[24],0x18424752,100,100,0,1:1,1:1,rgb24,-99,N/A,unknown,unknown,unknown,unspecified,N/A,1,N/A,25/1,25/1,1/51200,0,0.000000,N/A,N/A,N/A,N/A,N/A,N/A,4,4,0,0,0,0,0,0,0,0,0,0,0,Lavc rawvideo
+stream,1,rawvideo,unknown,video,1/51200,RGB[24],0x18424752,320,240,320,240,0,1:1,4:3,rgb24,-99,N/A,unknown,unknown,unknown,unspecified,N/A,1,N/A,25/1,25/1,1/51200,0,0.000000,N/A,N/A,N/A,N/A,N/A,N/A,4,4,0,0,0,0,0,0,0,0,0,0,0,foobar,field-and-tags-conflict-attempt,Lavc rawvideo
+stream,2,rawvideo,unknown,video,1/51200,RGB[24],0x18424752,100,100,100,100,0,1:1,1:1,rgb24,-99,N/A,unknown,unknown,unknown,unspecified,N/A,1,N/A,25/1,25/1,1/51200,0,0.000000,N/A,N/A,N/A,N/A,N/A,N/A,4,4,0,0,0,0,0,0,0,0,0,0,0,Lavc rawvideo
 format,tests/data/ffprobe-test.nut,3,0,nut,0.000000,0.120000,1054882,70325466,100,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 41e95a4..123208a 100644
--- a/tests/ref/fate/ffprobe_default
+++ b/tests/ref/fate/ffprobe_default
@@ -559,6 +559,8 @@
 codec_tag=0x18424752
 width=320
 height=240
+coded_width=320
+coded_height=240
 has_b_frames=0
 sample_aspect_ratio=1:1
 display_aspect_ratio=4:3
@@ -610,6 +612,8 @@
 codec_tag=0x18424752
 width=100
 height=100
+coded_width=100
+coded_height=100
 has_b_frames=0
 sample_aspect_ratio=1:1
 display_aspect_ratio=1:1
diff --git a/tests/ref/fate/ffprobe_flat b/tests/ref/fate/ffprobe_flat
index e395cf5..5c02a21 100644
--- a/tests/ref/fate/ffprobe_flat
+++ b/tests/ref/fate/ffprobe_flat
@@ -500,6 +500,8 @@
 streams.stream.1.codec_tag="0x18424752"
 streams.stream.1.width=320
 streams.stream.1.height=240
+streams.stream.1.coded_width=320
+streams.stream.1.coded_height=240
 streams.stream.1.has_b_frames=0
 streams.stream.1.sample_aspect_ratio="1:1"
 streams.stream.1.display_aspect_ratio="4:3"
@@ -549,6 +551,8 @@
 streams.stream.2.codec_tag="0x18424752"
 streams.stream.2.width=100
 streams.stream.2.height=100
+streams.stream.2.coded_width=100
+streams.stream.2.coded_height=100
 streams.stream.2.has_b_frames=0
 streams.stream.2.sample_aspect_ratio="1:1"
 streams.stream.2.display_aspect_ratio="1:1"
diff --git a/tests/ref/fate/ffprobe_ini b/tests/ref/fate/ffprobe_ini
index c779ace..e30c2fe 100644
--- a/tests/ref/fate/ffprobe_ini
+++ b/tests/ref/fate/ffprobe_ini
@@ -565,6 +565,8 @@
 codec_tag=0x18424752
 width=320
 height=240
+coded_width=320
+coded_height=240
 has_b_frames=0
 sample_aspect_ratio=1\:1
 display_aspect_ratio=4\:3
@@ -620,6 +622,8 @@
 codec_tag=0x18424752
 width=100
 height=100
+coded_width=100
+coded_height=100
 has_b_frames=0
 sample_aspect_ratio=1\:1
 display_aspect_ratio=1\:1
diff --git a/tests/ref/fate/ffprobe_json b/tests/ref/fate/ffprobe_json
index a0aecbd..ee2f8e6 100644
--- a/tests/ref/fate/ffprobe_json
+++ b/tests/ref/fate/ffprobe_json
@@ -552,6 +552,8 @@
             "codec_tag": "0x18424752",
             "width": 320,
             "height": 240,
+            "coded_width": 320,
+            "coded_height": 240,
             "has_b_frames": 0,
             "sample_aspect_ratio": "1:1",
             "display_aspect_ratio": "4:3",
@@ -593,6 +595,8 @@
             "codec_tag": "0x18424752",
             "width": 100,
             "height": 100,
+            "coded_width": 100,
+            "coded_height": 100,
             "has_b_frames": 0,
             "sample_aspect_ratio": "1:1",
             "display_aspect_ratio": "1:1",
diff --git a/tests/ref/fate/ffprobe_xml b/tests/ref/fate/ffprobe_xml
index 2dcdc97..5dad3e7 100644
--- a/tests/ref/fate/ffprobe_xml
+++ b/tests/ref/fate/ffprobe_xml
@@ -37,13 +37,13 @@
             <tag key="E" value="mc²"/>
             <tag key="encoder" value="Lavc pcm_s16le"/>
         </stream>
-        <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" refs="1" r_frame_rate="25/1" avg_frame_rate="25/1" time_base="1/51200" start_pts="0" start_time="0.000000" 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" coded_width="320" coded_height="240" has_b_frames="0" sample_aspect_ratio="1:1" display_aspect_ratio="4:3" pix_fmt="rgb24" level="-99" refs="1" r_frame_rate="25/1" avg_frame_rate="25/1" time_base="1/51200" start_pts="0" start_time="0.000000" 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"/>
             <tag key="encoder" value="Lavc rawvideo"/>
         </stream>
-        <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" refs="1" r_frame_rate="25/1" avg_frame_rate="25/1" time_base="1/51200" start_pts="0" start_time="0.000000" 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" coded_width="100" coded_height="100" has_b_frames="0" sample_aspect_ratio="1:1" display_aspect_ratio="1:1" pix_fmt="rgb24" level="-99" refs="1" r_frame_rate="25/1" avg_frame_rate="25/1" time_base="1/51200" start_pts="0" start_time="0.000000" 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="encoder" value="Lavc rawvideo"/>
         </stream>
diff --git a/tests/ref/fate/filter-palettegen-1 b/tests/ref/fate/filter-palettegen-1
new file mode 100644
index 0000000..98b7159
--- /dev/null
+++ b/tests/ref/fate/filter-palettegen-1
@@ -0,0 +1,2 @@
+#tb 0: 1001/24000
+0,          0,          0,        1,     1024, 0x3395ef5a
diff --git a/tests/ref/fate/filter-palettegen-2 b/tests/ref/fate/filter-palettegen-2
new file mode 100644
index 0000000..2f58b64
--- /dev/null
+++ b/tests/ref/fate/filter-palettegen-2
@@ -0,0 +1,2 @@
+#tb 0: 1001/24000
+0,          0,          0,        1,     1024, 0x906ff5aa
diff --git a/tests/ref/fate/filter-paletteuse-bayer b/tests/ref/fate/filter-paletteuse-bayer
new file mode 100644
index 0000000..4b44939
--- /dev/null
+++ b/tests/ref/fate/filter-paletteuse-bayer
@@ -0,0 +1,72 @@
+#tb 0: 1001/24000
+0,          0,          0,        1,   230400, 0x7b259d08
+0,          1,          1,        1,   230400, 0xf04095e0
+0,          2,          2,        1,   230400, 0x84d49cd5
+0,          3,          3,        1,   230400, 0xd7a29aaf
+0,          4,          4,        1,   230400, 0x9047947c
+0,          5,          5,        1,   230400, 0xfeb990e7
+0,          6,          6,        1,   230400, 0x51ee9295
+0,          7,          7,        1,   230400, 0x66fd4833
+0,          8,          8,        1,   230400, 0x4c0948f0
+0,          9,          9,        1,   230400, 0x632b4776
+0,         10,         10,        1,   230400, 0x7a3c87e2
+0,         11,         11,        1,   230400, 0x4a9286ba
+0,         12,         12,        1,   230400, 0x54dc8649
+0,         13,         13,        1,   230400, 0x92628944
+0,         14,         14,        1,   230400, 0x80f9899f
+0,         15,         15,        1,   230400, 0x5cd78bd8
+0,         16,         16,        1,   230400, 0x4b4ca390
+0,         17,         17,        1,   230400, 0x82cca153
+0,         18,         18,        1,   230400, 0x65f1a2d0
+0,         19,         19,        1,   230400, 0x7df6ae4c
+0,         20,         20,        1,   230400, 0x909baccc
+0,         21,         21,        1,   230400, 0x1892ac65
+0,         22,         22,        1,   230400, 0x3247bb32
+0,         23,         23,        1,   230400, 0x592fbbe5
+0,         24,         24,        1,   230400, 0x189db9d5
+0,         25,         25,        1,   230400, 0x1a38b8da
+0,         26,         26,        1,   230400, 0xccd6bd07
+0,         27,         27,        1,   230400, 0xd4a2bc53
+0,         28,         28,        1,   230400, 0x9ce3bb4e
+0,         29,         29,        1,   230400, 0x5ffdc4db
+0,         30,         30,        1,   230400, 0xc885c7c9
+0,         31,         31,        1,   230400, 0xe27b9d33
+0,         32,         32,        1,   230400, 0xac03a256
+0,         33,         33,        1,   230400, 0xa2c73929
+0,         34,         34,        1,   230400, 0x33793b73
+0,         35,         35,        1,   230400, 0x1e400add
+0,         36,         36,        1,   230400, 0x98e50c6e
+0,         37,         37,        1,   230400, 0x68ed226d
+0,         38,         38,        1,   230400, 0x569e23cb
+0,         39,         39,        1,   230400, 0x82bf3fc0
+0,         40,         40,        1,   230400, 0x2b202e86
+0,         41,         41,        1,   230400, 0x7acd2dee
+0,         42,         42,        1,   230400, 0xfe872e42
+0,         43,         43,        1,   230400, 0x026c12e5
+0,         44,         44,        1,   230400, 0x81561399
+0,         45,         45,        1,   230400, 0xa08c13b6
+0,         46,         46,        1,   230400, 0x89e712f5
+0,         47,         47,        1,   230400, 0x569011ac
+0,         48,         48,        1,   230400, 0xd4691112
+0,         49,         49,        1,   230400, 0x2e50165a
+0,         50,         50,        1,   230400, 0x0a1215b6
+0,         51,         51,        1,   230400, 0x3c5316e3
+0,         52,         52,        1,   230400, 0x079c1393
+0,         53,         53,        1,   230400, 0x39ca1c48
+0,         54,         54,        1,   230400, 0xe27f199c
+0,         55,         55,        1,   230400, 0x10ab1bab
+0,         56,         56,        1,   230400, 0xeab017c3
+0,         57,         57,        1,   230400, 0x5f701f77
+0,         58,         58,        1,   230400, 0x01371d7d
+0,         59,         59,        1,   230400, 0x22751e99
+0,         60,         60,        1,   230400, 0xaee91a97
+0,         61,         61,        1,   230400, 0x27b41f32
+0,         62,         62,        1,   230400, 0x4ff32bb1
+0,         63,         63,        1,   230400, 0x86e02864
+0,         64,         64,        1,   230400, 0x5eb52b3e
+0,         65,         65,        1,   230400, 0xd9252ba8
+0,         66,         66,        1,   230400, 0x72232d9b
+0,         67,         67,        1,   230400, 0x599a206f
+0,         68,         68,        1,   230400, 0x4d2c1ca5
+0,         69,         69,        1,   230400, 0x9166293b
+0,         70,         70,        1,   230400, 0x00992453
diff --git a/tests/ref/fate/filter-paletteuse-nodither b/tests/ref/fate/filter-paletteuse-nodither
new file mode 100644
index 0000000..8171ffa
--- /dev/null
+++ b/tests/ref/fate/filter-paletteuse-nodither
@@ -0,0 +1,72 @@
+#tb 0: 1001/24000
+0,          0,          0,        1,   230400, 0x690560cb
+0,          1,          1,        1,   230400, 0x197a5a54
+0,          2,          2,        1,   230400, 0x665961db
+0,          3,          3,        1,   230400, 0xce0b5fa8
+0,          4,          4,        1,   230400, 0xa40e5cb0
+0,          5,          5,        1,   230400, 0xa5aa58da
+0,          6,          6,        1,   230400, 0x8e0259bb
+0,          7,          7,        1,   230400, 0x476d0dba
+0,          8,          8,        1,   230400, 0xfb1b0e8c
+0,          9,          9,        1,   230400, 0x50f60d3b
+0,         10,         10,        1,   230400, 0x12cd4bab
+0,         11,         11,        1,   230400, 0x4c274b13
+0,         12,         12,        1,   230400, 0xea494b0a
+0,         13,         13,        1,   230400, 0x118c4cc1
+0,         14,         14,        1,   230400, 0xd4224db7
+0,         15,         15,        1,   230400, 0xc3014f88
+0,         16,         16,        1,   230400, 0xe07a6838
+0,         17,         17,        1,   230400, 0x1b97659a
+0,         18,         18,        1,   230400, 0xf104670c
+0,         19,         19,        1,   230400, 0x7b63733d
+0,         20,         20,        1,   230400, 0x2c237200
+0,         21,         21,        1,   230400, 0x775d7248
+0,         22,         22,        1,   230400, 0xcaee7f9e
+0,         23,         23,        1,   230400, 0x4e4680a1
+0,         24,         24,        1,   230400, 0x21fb7e53
+0,         25,         25,        1,   230400, 0xf0297db6
+0,         26,         26,        1,   230400, 0x79a9829d
+0,         27,         27,        1,   230400, 0x8ccb80f7
+0,         28,         28,        1,   230400, 0xf4dd807f
+0,         29,         29,        1,   230400, 0xb6cc8696
+0,         30,         30,        1,   230400, 0x6c8a8917
+0,         31,         31,        1,   230400, 0x9e08615a
+0,         32,         32,        1,   230400, 0xc098685b
+0,         33,         33,        1,   230400, 0x5c09e710
+0,         34,         34,        1,   230400, 0xe4c4e9be
+0,         35,         35,        1,   230400, 0xac59c150
+0,         36,         36,        1,   230400, 0x6045c272
+0,         37,         37,        1,   230400, 0xf71ee6dc
+0,         38,         38,        1,   230400, 0xc82ce6f6
+0,         39,         39,        1,   230400, 0xb7ed039a
+0,         40,         40,        1,   230400, 0xda93f241
+0,         41,         41,        1,   230400, 0x194bf23b
+0,         42,         42,        1,   230400, 0xe7e6f2e2
+0,         43,         43,        1,   230400, 0xe479d834
+0,         44,         44,        1,   230400, 0xefdfd87e
+0,         45,         45,        1,   230400, 0xec66d8c0
+0,         46,         46,        1,   230400, 0x3a6bd81b
+0,         47,         47,        1,   230400, 0xb5d1d700
+0,         48,         48,        1,   230400, 0x3bc69e8b
+0,         49,         49,        1,   230400, 0x723fa455
+0,         50,         50,        1,   230400, 0x7c49a392
+0,         51,         51,        1,   230400, 0x272ea4b7
+0,         52,         52,        1,   230400, 0xebdda081
+0,         53,         53,        1,   230400, 0xfd26ab99
+0,         54,         54,        1,   230400, 0xfa02a891
+0,         55,         55,        1,   230400, 0xda2caa7f
+0,         56,         56,        1,   230400, 0x2360a611
+0,         57,         57,        1,   230400, 0xaa3baefd
+0,         58,         58,        1,   230400, 0x0961ad5c
+0,         59,         59,        1,   230400, 0x48d2ae47
+0,         60,         60,        1,   230400, 0x20eda81b
+0,         61,         61,        1,   230400, 0x8821adbb
+0,         62,         62,        1,   230400, 0x1150b810
+0,         63,         63,        1,   230400, 0x08dab596
+0,         64,         64,        1,   230400, 0x4731b7a5
+0,         65,         65,        1,   230400, 0xf382b87e
+0,         66,         66,        1,   230400, 0xdba7bac2
+0,         67,         67,        1,   230400, 0xf569acf9
+0,         68,         68,        1,   230400, 0x22d8a95d
+0,         69,         69,        1,   230400, 0xed0bb4fb
+0,         70,         70,        1,   230400, 0x2dccb218
diff --git a/tests/ref/fate/filter-paletteuse-sierra2_4a b/tests/ref/fate/filter-paletteuse-sierra2_4a
new file mode 100644
index 0000000..95d7636
--- /dev/null
+++ b/tests/ref/fate/filter-paletteuse-sierra2_4a
@@ -0,0 +1,72 @@
+#tb 0: 1001/24000
+0,          0,          0,        1,   230400, 0xa4f85758
+0,          1,          1,        1,   230400, 0xbe83505c
+0,          2,          2,        1,   230400, 0x0a09584e
+0,          3,          3,        1,   230400, 0xd2065629
+0,          4,          4,        1,   230400, 0x11eb5319
+0,          5,          5,        1,   230400, 0x61024f4c
+0,          6,          6,        1,   230400, 0xd5384faa
+0,          7,          7,        1,   230400, 0xdeae0343
+0,          8,          8,        1,   230400, 0xcb640541
+0,          9,          9,        1,   230400, 0xea2602c3
+0,         10,         10,        1,   230400, 0xa7974293
+0,         11,         11,        1,   230400, 0x67cd4287
+0,         12,         12,        1,   230400, 0x83fa437a
+0,         13,         13,        1,   230400, 0x852b42bf
+0,         14,         14,        1,   230400, 0x6d2d434c
+0,         15,         15,        1,   230400, 0x20c44629
+0,         16,         16,        1,   230400, 0xf2a35f57
+0,         17,         17,        1,   230400, 0x232959ec
+0,         18,         18,        1,   230400, 0x1f8e5c48
+0,         19,         19,        1,   230400, 0x88dc69bd
+0,         20,         20,        1,   230400, 0x4b6866f3
+0,         21,         21,        1,   230400, 0xe8f966dc
+0,         22,         22,        1,   230400, 0xe0877466
+0,         23,         23,        1,   230400, 0x8799748c
+0,         24,         24,        1,   230400, 0xcab871bc
+0,         25,         25,        1,   230400, 0x2e0372b4
+0,         26,         26,        1,   230400, 0x15fb77d5
+0,         27,         27,        1,   230400, 0xbadf75fc
+0,         28,         28,        1,   230400, 0xa4977626
+0,         29,         29,        1,   230400, 0x5b987943
+0,         30,         30,        1,   230400, 0x9ed57c09
+0,         31,         31,        1,   230400, 0x565d5105
+0,         32,         32,        1,   230400, 0x901b5a07
+0,         33,         33,        1,   230400, 0x8dc4e9a8
+0,         34,         34,        1,   230400, 0x0b9cee1c
+0,         35,         35,        1,   230400, 0x2bcdbe37
+0,         36,         36,        1,   230400, 0xf3e2bf71
+0,         37,         37,        1,   230400, 0xb718da67
+0,         38,         38,        1,   230400, 0x8f59da64
+0,         39,         39,        1,   230400, 0x8812f9aa
+0,         40,         40,        1,   230400, 0xe0dae6a3
+0,         41,         41,        1,   230400, 0xd2c7e5b7
+0,         42,         42,        1,   230400, 0xea2ae5d2
+0,         43,         43,        1,   230400, 0x2d66ca25
+0,         44,         44,        1,   230400, 0xf0d3cac6
+0,         45,         45,        1,   230400, 0xb9acccac
+0,         46,         46,        1,   230400, 0x8523ca4a
+0,         47,         47,        1,   230400, 0x92b9c9ef
+0,         48,         48,        1,   230400, 0x0a88946e
+0,         49,         49,        1,   230400, 0xe33699b8
+0,         50,         50,        1,   230400, 0x5e7b9917
+0,         51,         51,        1,   230400, 0xdac99998
+0,         52,         52,        1,   230400, 0xb5c995fc
+0,         53,         53,        1,   230400, 0x908b9f50
+0,         54,         54,        1,   230400, 0x60d59ced
+0,         55,         55,        1,   230400, 0x212e9f55
+0,         56,         56,        1,   230400, 0x95e69b2a
+0,         57,         57,        1,   230400, 0x6c38a34a
+0,         58,         58,        1,   230400, 0xeb32a103
+0,         59,         59,        1,   230400, 0x0131a1b7
+0,         60,         60,        1,   230400, 0xd59b9c4e
+0,         61,         61,        1,   230400, 0x2fc0a13f
+0,         62,         62,        1,   230400, 0x7a40adf9
+0,         63,         63,        1,   230400, 0x5cdbab2f
+0,         64,         64,        1,   230400, 0xcdc0ada8
+0,         65,         65,        1,   230400, 0x2f5faf32
+0,         66,         66,        1,   230400, 0xd463b224
+0,         67,         67,        1,   230400, 0xe337a2d5
+0,         68,         68,        1,   230400, 0xe775a0c1
+0,         69,         69,        1,   230400, 0x726aab49
+0,         70,         70,        1,   230400, 0x74dda81e
diff --git a/tests/ref/fate/force_key_frames b/tests/ref/fate/force_key_frames
index 863e746..0a41378 100644
--- a/tests/ref/fate/force_key_frames
+++ b/tests/ref/fate/force_key_frames
@@ -1,4 +1,4 @@
-74daf0c27174418b74191fd855a631e8 *tests/data/fate/force_key_frames.avi
-113308 tests/data/fate/force_key_frames.avi
+07567b9528b8de523faaf49e4e1e0fc6 *tests/data/fate/force_key_frames.avi
+113312 tests/data/fate/force_key_frames.avi
 8f68ad2e602ecd87a3e0c097ba99d773 *tests/data/fate/force_key_frames.out.framecrc
 stddev:34363.01 PSNR:  5.61 MAXDIFF:56305 bytes:  7603200/      186
diff --git a/tests/ref/fate/gifenc-bgr8 b/tests/ref/fate/gifenc-bgr8
index 9f4a593..f3b7772 100644
--- a/tests/ref/fate/gifenc-bgr8
+++ b/tests/ref/fate/gifenc-bgr8
@@ -35,15 +35,15 @@
 0,         33,         33,        1,     4295, 0xf71b0b38, S=1,     1024, 0xf351799f
 0,         34,         34,        1,     2044, 0x5adcb93b, S=1,     1024, 0xf351799f
 0,         35,         35,        1,     3212, 0xcf79eeed, S=1,     1024, 0xf351799f
-0,         36,         36,        1,     2281, 0x68464d30, S=1,     1024, 0xf351799f
+0,         36,         36,        1,     2292, 0xb4386334, S=1,     1024, 0xf351799f
 0,         37,         37,        1,     3633, 0x0010992f, S=1,     1024, 0xf351799f
 0,         38,         38,        1,     3552, 0x23697490, S=1,     1024, 0xf351799f
 0,         39,         39,        1,     3690, 0x62afdbb8, S=1,     1024, 0xf351799f
-0,         40,         40,        1,     1558, 0x7a13e53b, S=1,     1024, 0xf351799f
-0,         41,         41,        1,      940, 0xb1b6cba2, S=1,     1024, 0xf351799f
+0,         40,         40,        1,     1559, 0x5baef54a, S=1,     1024, 0xf351799f
+0,         41,         41,        1,      954, 0xca75ca79, S=1,     1024, 0xf351799f
 0,         42,         42,        1,      273, 0x3687799b, S=1,     1024, 0xf351799f
 0,         43,         43,        1,      930, 0x29f3b0c4, S=1,     1024, 0xf351799f
-0,         44,         44,        1,      271, 0xe7af807c, S=1,     1024, 0xf351799f
+0,         44,         44,        1,      271, 0x305e8094, S=1,     1024, 0xf351799f
 0,         45,         45,        1,      196, 0xf5ab51ee, S=1,     1024, 0xf351799f
 0,         46,         46,        1,     4299, 0x67ec0d55, S=1,     1024, 0xf351799f
 0,         47,         47,        1,     4895, 0xb394406c, S=1,     1024, 0xf351799f
@@ -56,7 +56,7 @@
 0,         54,         54,        1,     5179, 0x860fc6a1, S=1,     1024, 0xf351799f
 0,         55,         55,        1,     5046, 0xce9183d3, S=1,     1024, 0xf351799f
 0,         56,         56,        1,     5140, 0xa6d7b9af, S=1,     1024, 0xf351799f
-0,         57,         57,        1,     4289, 0xb415f717, S=1,     1024, 0xf351799f
+0,         57,         57,        1,     4301, 0x03b6ef3f, S=1,     1024, 0xf351799f
 0,         58,         58,        1,     5079, 0xa8d59e01, S=1,     1024, 0xf351799f
 0,         59,         59,        1,     5284, 0xea34e3b3, S=1,     1024, 0xf351799f
 0,         60,         60,        1,     5426, 0x556a15cd, S=1,     1024, 0xf351799f
diff --git a/tests/ref/fate/gifenc-pal8 b/tests/ref/fate/gifenc-pal8
index 203a154..a84efa0 100644
--- a/tests/ref/fate/gifenc-pal8
+++ b/tests/ref/fate/gifenc-pal8
@@ -1,174 +1,174 @@
 #tb 0: 1/10
-0,          0,          0,        1,     1320, 0x95d1a9e9, S=1,     1024, 0xec907a9e
-0,          1,          1,        1,     1463, 0xa697fe95, S=1,     1024, 0xec907a9e
-0,          2,          2,        1,     1638, 0x7ea154fa, S=1,     1024, 0xec907a9e
-0,          3,          3,        1,     1755, 0x7e0b9c4d, S=1,     1024, 0xec907a9e
-0,          4,          4,        1,     1896, 0x4aacc768, S=1,     1024, 0xec907a9e
-0,          5,          5,        1,     2038, 0x209d1490, S=1,     1024, 0xec907a9e
-0,          6,          6,        1,     2168, 0x0c405606, S=1,     1024, 0xec907a9e
-0,          7,          7,        1,     2258, 0xc2fa9229, S=1,     1024, 0xec907a9e
-0,          8,          8,        1,     2442, 0x0d4bec48, S=1,     1024, 0xec907a9e
-0,          9,          9,        1,     2565, 0x15742730, S=1,     1024, 0xec907a9e
-0,         10,         10,        1,     2733, 0x2eb57d95, S=1,     1024, 0xec907a9e
-0,         11,         11,        1,     2849, 0x9f16ad46, S=1,     1024, 0xec907a9e
-0,         12,         12,        1,     2981, 0xf139f908, S=1,     1024, 0xec907a9e
-0,         13,         13,        1,     3082, 0x57144aec, S=1,     1024, 0xec907a9e
-0,         14,         14,        1,     3200, 0x35227f42, S=1,     1024, 0xec907a9e
-0,         15,         15,        1,     3316, 0xf6d7c002, S=1,     1024, 0xec907a9e
-0,         16,         16,        1,     3462, 0x27a20d23, S=1,     1024, 0xec907a9e
-0,         17,         17,        1,     3600, 0xaecb2b02, S=1,     1024, 0xec907a9e
-0,         18,         18,        1,     3712, 0x947d49d1, S=1,     1024, 0xec907a9e
-0,         19,         19,        1,     3838, 0xf87eb223, S=1,     1024, 0xec907a9e
-0,         20,         20,        1,     3949, 0x4152eedf, S=1,     1024, 0xec907a9e
-0,         21,         21,        1,     4084, 0x512c1e34, S=1,     1024, 0xec907a9e
-0,         22,         22,        1,     4187, 0xc5715a14, S=1,     1024, 0xec907a9e
-0,         23,         23,        1,     4323, 0x6326a0f5, S=1,     1024, 0xec907a9e
-0,         24,         24,        1,     4426, 0x5f6bd655, S=1,     1024, 0xec907a9e
-0,         25,         25,        1,     4564, 0xc62005fd, S=1,     1024, 0xec907a9e
-0,         26,         26,        1,     4664, 0x43e97006, S=1,     1024, 0xec907a9e
-0,         27,         27,        1,     4808, 0xf6e08d4f, S=1,     1024, 0xec907a9e
-0,         28,         28,        1,     4932, 0x2d51e0b5, S=1,     1024, 0xec907a9e
-0,         29,         29,        1,     5072, 0x577430c8, S=1,     1024, 0xec907a9e
-0,         30,         30,        1,     5247, 0xd9fe945d, S=1,     1024, 0xec907a9e
-0,         31,         31,        1,     5353, 0x27eec140, S=1,     1024, 0xec907a9e
-0,         32,         32,        1,     5536, 0xde59038d, S=1,     1024, 0xec907a9e
-0,         33,         33,        1,     5691, 0x358970e4, S=1,     1024, 0xec907a9e
-0,         34,         34,        1,     5835, 0xd89201d8, S=1,     1024, 0xec907a9e
-0,         35,         35,        1,     5967, 0x1c2e1fee, S=1,     1024, 0xec907a9e
-0,         36,         36,        1,     6082, 0xd4b88e90, S=1,     1024, 0xec907a9e
-0,         37,         37,        1,     6277, 0x020fe685, S=1,     1024, 0xec907a9e
-0,         38,         38,        1,     6382, 0xc1db2297, S=1,     1024, 0xec907a9e
-0,         39,         39,        1,     6509, 0xc65473a6, S=1,     1024, 0xec907a9e
-0,         40,         40,        1,     6621, 0xca917a35, S=1,     1024, 0xec907a9e
-0,         41,         41,        1,     6714, 0x70f29b1d, S=1,     1024, 0xec907a9e
-0,         42,         42,        1,     6822, 0x6f02e7ec, S=1,     1024, 0xec907a9e
-0,         43,         43,        1,     6880, 0x95440d97, S=1,     1024, 0xec907a9e
-0,         44,         44,        1,     6983, 0xab7a43fb, S=1,     1024, 0xec907a9e
-0,         45,         45,        1,     7085, 0xc3427580, S=1,     1024, 0xec907a9e
-0,         46,         46,        1,     7242, 0x3d00c5f0, S=1,     1024, 0xec907a9e
-0,         47,         47,        1,     7349, 0x453fad59, S=1,     1024, 0xec907a9e
-0,         48,         48,        1,     7514, 0xbd862667, S=1,     1024, 0xec907a9e
-0,         49,         49,        1,     7575, 0xf8cb3c77, S=1,     1024, 0xec907a9e
-0,         50,         50,        1,     7759, 0x1fe6ab40, S=1,     1024, 0xec907a9e
-0,         51,         51,        1,     7846, 0x3853fd0f, S=1,     1024, 0xec907a9e
-0,         52,         52,        1,     7975, 0x88d02c47, S=1,     1024, 0xec907a9e
-0,         53,         53,        1,     8092, 0xe28a3368, S=1,     1024, 0xec907a9e
-0,         54,         54,        1,     8188, 0x159a5d3b, S=1,     1024, 0xec907a9e
-0,         55,         55,        1,     8307, 0x598cae50, S=1,     1024, 0xec907a9e
-0,         56,         56,        1,     8436, 0xd104ee50, S=1,     1024, 0xec907a9e
-0,         57,         57,        1,     8498, 0x0b1527ed, S=1,     1024, 0xec907a9e
-0,         58,         58,        1,     8559, 0x0f722288, S=1,     1024, 0xec907a9e
-0,         59,         59,        1,     8661, 0x3efb2500, S=1,     1024, 0xec907a9e
-0,         60,         60,        1,     8774, 0x1e188a8b, S=1,     1024, 0xec907a9e
-0,         61,         61,        1,     8848, 0x5b438dbb, S=1,     1024, 0xec907a9e
-0,         62,         62,        1,     8968, 0x4b47ecb3, S=1,     1024, 0xec907a9e
-0,         63,         63,        1,     9036, 0x7a8e0791, S=1,     1024, 0xec907a9e
-0,         64,         64,        1,     9114, 0x7379131a, S=1,     1024, 0xec907a9e
-0,         65,         65,        1,     9258, 0x06099246, S=1,     1024, 0xec907a9e
-0,         66,         66,        1,     9423, 0x721ac9ab, S=1,     1024, 0xec907a9e
-0,         67,         67,        1,     9529, 0xbb1c0d18, S=1,     1024, 0xec907a9e
-0,         68,         68,        1,     9608, 0xc29a05f0, S=1,     1024, 0xec907a9e
-0,         69,         69,        1,     9668, 0xf35221ff, S=1,     1024, 0xec907a9e
-0,         70,         70,        1,     9709, 0x8c6d33f0, S=1,     1024, 0xec907a9e
-0,         71,         71,        1,     9810, 0x2d5b59f4, S=1,     1024, 0xec907a9e
-0,         72,         72,        1,     9879, 0x110ea6e5, S=1,     1024, 0xec907a9e
-0,         73,         73,        1,    10038, 0x5945f5f4, S=1,     1024, 0xec907a9e
-0,         74,         74,        1,    10120, 0xab24f519, S=1,     1024, 0xec907a9e
-0,         75,         75,        1,    10218, 0x090d305a, S=1,     1024, 0xec907a9e
-0,         76,         76,        1,    10231, 0xa77e6a66, S=1,     1024, 0xec907a9e
-0,         77,         77,        1,    10313, 0x192254b7, S=1,     1024, 0xec907a9e
-0,         78,         78,        1,    10444, 0x36609934, S=1,     1024, 0xec907a9e
-0,         79,         79,        1,    10670, 0xfa971206, S=1,     1024, 0xec907a9e
-0,         80,         80,        1,    10902, 0x01b59fd5, S=1,     1024, 0xec907a9e
-0,         81,         81,        1,    10992, 0x1f2ab0bc, S=1,     1024, 0xec907a9e
-0,         82,         82,        1,    11044, 0x7f5b1dc2, S=1,     1024, 0xec907a9e
-0,         83,         83,        1,    11170, 0x0beaee49, S=1,     1024, 0xec907a9e
-0,         84,         84,        1,    11267, 0xb1ae3808, S=1,     1024, 0xec907a9e
-0,         85,         85,        1,    11427, 0x2cc9aa3f, S=1,     1024, 0xec907a9e
-0,         86,         86,        1,    11529, 0x654de4f3, S=1,     1024, 0xec907a9e
-0,         87,         87,        1,    11632, 0xf4972bdf, S=1,     1024, 0xec907a9e
-0,         88,         88,        1,    11825, 0x0cd2548c, S=1,     1024, 0xec907a9e
-0,         89,         89,        1,    11864, 0x80758637, S=1,     1024, 0xec907a9e
-0,         90,         90,        1,    11950, 0xf8246fba, S=1,     1024, 0xec907a9e
-0,         91,         91,        1,    12088, 0x1b99c82b, S=1,     1024, 0xec907a9e
-0,         92,         92,        1,    12161, 0x682cf4ad, S=1,     1024, 0xec907a9e
-0,         93,         93,        1,    12305, 0x9f62069a, S=1,     1024, 0xec907a9e
-0,         94,         94,        1,    12296, 0xe08dd96c, S=1,     1024, 0xec907a9e
-0,         95,         95,        1,    12497, 0x9a20b2d0, S=1,     1024, 0xec907a9e
-0,         96,         96,        1,    12660, 0x4d1d05ea, S=1,     1024, 0xec907a9e
-0,         97,         97,        1,    12763, 0x12542531, S=1,     1024, 0xec907a9e
-0,         98,         98,        1,    12917, 0x7d0944dc, S=1,     1024, 0xec907a9e
-0,         99,         99,        1,    13021, 0xa1c89f22, S=1,     1024, 0xec907a9e
-0,        100,        100,        1,    13184, 0xe13ad0be, S=1,     1024, 0xec907a9e
-0,        101,        101,        1,    13315, 0x11b93a5d, S=1,     1024, 0xec907a9e
-0,        102,        102,        1,    13337, 0x677e54ef, S=1,     1024, 0xec907a9e
-0,        103,        103,        1,    13536, 0x48b7b5de, S=1,     1024, 0xec907a9e
-0,        104,        104,        1,    13728, 0x03f4d302, S=1,     1024, 0xec907a9e
-0,        105,        105,        1,    13822, 0x973b97ec, S=1,     1024, 0xec907a9e
-0,        106,        106,        1,    14002, 0x0de77dfc, S=1,     1024, 0xec907a9e
-0,        107,        107,        1,    14156, 0xf1b1d4e1, S=1,     1024, 0xec907a9e
-0,        108,        108,        1,    14256, 0x355320cc, S=1,     1024, 0xec907a9e
-0,        109,        109,        1,    14451, 0x306cb131, S=1,     1024, 0xec907a9e
-0,        110,        110,        1,    14508, 0xca729c8e, S=1,     1024, 0xec907a9e
-0,        111,        111,        1,    14683, 0x7abec197, S=1,     1024, 0xec907a9e
-0,        112,        112,        1,    14852, 0xa5b90496, S=1,     1024, 0xec907a9e
-0,        113,        113,        1,    15090, 0xcd29839d, S=1,     1024, 0xec907a9e
-0,        114,        114,        1,    15225, 0xfd85f899, S=1,     1024, 0xec907a9e
-0,        115,        115,        1,    15340, 0x07411310, S=1,     1024, 0xec907a9e
-0,        116,        116,        1,    15473, 0xe90086c1, S=1,     1024, 0xec907a9e
-0,        117,        117,        1,    15583, 0x524da1f3, S=1,     1024, 0xec907a9e
-0,        118,        118,        1,    15683, 0x404cbd62, S=1,     1024, 0xec907a9e
-0,        119,        119,        1,    15779, 0x3ec01717, S=1,     1024, 0xec907a9e
-0,        120,        120,        1,    15934, 0xac8b4c03, S=1,     1024, 0xec907a9e
-0,        121,        121,        1,    16116, 0xb4fa83c9, S=1,     1024, 0xec907a9e
-0,        122,        122,        1,    16153, 0x18f669c1, S=1,     1024, 0xec907a9e
-0,        123,        123,        1,    16303, 0x765b10e4, S=1,     1024, 0xec907a9e
-0,        124,        124,        1,    16460, 0xc4a8149a, S=1,     1024, 0xec907a9e
-0,        125,        125,        1,    16475, 0x48664e2d, S=1,     1024, 0xec907a9e
-0,        126,        126,        1,    16710, 0x8a599742, S=1,     1024, 0xec907a9e
-0,        127,        127,        1,    16848, 0x8634a3d5, S=1,     1024, 0xec907a9e
-0,        128,        128,        1,    16955, 0x01f1ebda, S=1,     1024, 0xec907a9e
-0,        129,        129,        1,    17044, 0xd57b47df, S=1,     1024, 0xec907a9e
-0,        130,        130,        1,    17153, 0xc5cf7bc7, S=1,     1024, 0xec907a9e
-0,        131,        131,        1,    17375, 0xbbeea767, S=1,     1024, 0xec907a9e
-0,        132,        132,        1,    17476, 0xd7a25686, S=1,     1024, 0xec907a9e
-0,        133,        133,        1,    17602, 0x1c99b228, S=1,     1024, 0xec907a9e
-0,        134,        134,        1,    17676, 0xd860d1d2, S=1,     1024, 0xec907a9e
-0,        135,        135,        1,    17799, 0xe4ccb3ae, S=1,     1024, 0xec907a9e
-0,        136,        136,        1,    17930, 0xf322e416, S=1,     1024, 0xec907a9e
-0,        137,        137,        1,    18201, 0xc6f1cfa7, S=1,     1024, 0xec907a9e
-0,        138,        138,        1,    18409, 0x7cdfe609, S=1,     1024, 0xec907a9e
-0,        139,        139,        1,    18686, 0xf65e5519, S=1,     1024, 0xec907a9e
-0,        140,        140,        1,    18790, 0x6d5c8a90, S=1,     1024, 0xec907a9e
-0,        141,        141,        1,    18891, 0x4702a6cf, S=1,     1024, 0xec907a9e
-0,        142,        142,        1,    18995, 0x69e5e02d, S=1,     1024, 0xec907a9e
-0,        143,        143,        1,    19058, 0xc56f0272, S=1,     1024, 0xec907a9e
-0,        144,        144,        1,    19223, 0xe89733f6, S=1,     1024, 0xec907a9e
-0,        145,        145,        1,    19501, 0xdb80f9e9, S=1,     1024, 0xec907a9e
-0,        146,        146,        1,    19566, 0xa3952da8, S=1,     1024, 0xec907a9e
-0,        147,        147,        1,    19692, 0x65925150, S=1,     1024, 0xec907a9e
-0,        148,        148,        1,    19730, 0x1352599a, S=1,     1024, 0xec907a9e
-0,        149,        149,        1,    19916, 0xd246bf9b, S=1,     1024, 0xec907a9e
-0,        150,        150,        1,    20136, 0x1c462eea, S=1,     1024, 0xec907a9e
-0,        151,        151,        1,    20210, 0xdec93f63, S=1,     1024, 0xec907a9e
-0,        152,        152,        1,    20311, 0xdff7836e, S=1,     1024, 0xec907a9e
-0,        153,        153,        1,    20377, 0x753d813f, S=1,     1024, 0xec907a9e
-0,        154,        154,        1,    20478, 0x7592b1a8, S=1,     1024, 0xec907a9e
-0,        155,        155,        1,    20597, 0x58313994, S=1,     1024, 0xec907a9e
-0,        156,        156,        1,    20717, 0xcdd9c665, S=1,     1024, 0xec907a9e
-0,        157,        157,        1,    20816, 0x803b4b03, S=1,     1024, 0xec907a9e
-0,        158,        158,        1,    20912, 0xce36ce22, S=1,     1024, 0xec907a9e
-0,        159,        159,        1,    20975, 0x1d08e543, S=1,     1024, 0xec907a9e
-0,        160,        160,        1,    21130, 0xc966e24c, S=1,     1024, 0xec907a9e
-0,        161,        161,        1,    21343, 0x735e614e, S=1,     1024, 0xec907a9e
-0,        162,        162,        1,    21455, 0x78d7afd1, S=1,     1024, 0xec907a9e
-0,        163,        163,        1,    21533, 0x62a10f46, S=1,     1024, 0xec907a9e
-0,        164,        164,        1,    21645, 0x8e53a12f, S=1,     1024, 0xec907a9e
-0,        165,        165,        1,    21931, 0x3b2f7226, S=1,     1024, 0xec907a9e
-0,        166,        166,        1,    22009, 0xf06bc58a, S=1,     1024, 0xec907a9e
-0,        167,        167,        1,    22115, 0xeeb1c5d7, S=1,     1024, 0xec907a9e
-0,        168,        168,        1,    22211, 0xcbab1084, S=1,     1024, 0xec907a9e
-0,        169,        169,        1,    22380, 0xf07d5cb7, S=1,     1024, 0xec907a9e
-0,        170,        170,        1,    22443, 0xcb79441c, S=1,     1024, 0xec907a9e
-0,        171,        171,        1,    22588, 0xcad49814, S=1,     1024, 0xec907a9e
-0,        172,        172,        1,    22706, 0x34924e43, S=1,     1024, 0xec907a9e
+0,          0,          0,        1,      552, 0x271a2dd3, S=1,     1024, 0xec907a9e
+0,          1,          1,        1,      297, 0x90168a95, S=1,     1024, 0xf351799f
+0,          2,          2,        1,      438, 0x91efce1b, S=1,     1024, 0xf351799f
+0,          3,          3,        1,      450, 0x7c2dcfad, S=1,     1024, 0xf351799f
+0,          4,          4,        1,      547, 0xc131fd3b, S=1,     1024, 0xf351799f
+0,          5,          5,        1,      614, 0x68182006, S=1,     1024, 0xf351799f
+0,          6,          6,        1,      642, 0x78bb1f5f, S=1,     1024, 0xf351799f
+0,          7,          7,        1,      660, 0x35c033a2, S=1,     1024, 0xf351799f
+0,          8,          8,        1,      821, 0xaf30790b, S=1,     1024, 0xf351799f
+0,          9,          9,        1,     1157, 0x741c2da1, S=1,     1024, 0xf351799f
+0,         10,         10,        1,      179, 0x3a27517c, S=1,     1024, 0xf351799f
+0,         11,         11,        1,     1333, 0x5ee76f3c, S=1,     1024, 0xf351799f
+0,         12,         12,        1,     1638, 0x5f640e86, S=1,     1024, 0xf351799f
+0,         13,         13,        1,     1531, 0xccb8e437, S=1,     1024, 0xf351799f
+0,         14,         14,        1,     1720, 0xc95d45ec, S=1,     1024, 0xf351799f
+0,         15,         15,        1,     1910, 0x56cc831e, S=1,     1024, 0xf351799f
+0,         16,         16,        1,     2124, 0x9cc8e130, S=1,     1024, 0xf351799f
+0,         17,         17,        1,     2248, 0x05a325b1, S=1,     1024, 0xf351799f
+0,         18,         18,        1,     2311, 0xdc633703, S=1,     1024, 0xf351799f
+0,         19,         19,        1,     2408, 0x91c26f3e, S=1,     1024, 0xf351799f
+0,         20,         20,        1,     2601, 0x8cf3c157, S=1,     1024, 0xf351799f
+0,         21,         21,        1,     2687, 0x8f6400e6, S=1,     1024, 0xf351799f
+0,         22,         22,        1,     2784, 0xaa880e55, S=1,     1024, 0xf351799f
+0,         23,         23,        1,     2884, 0x46f546f6, S=1,     1024, 0xf351799f
+0,         24,         24,        1,     2982, 0x807c7ad5, S=1,     1024, 0xf351799f
+0,         25,         25,        1,     3101, 0xbcc89bec, S=1,     1024, 0xf351799f
+0,         26,         26,        1,     3253, 0xd032f3fa, S=1,     1024, 0xf351799f
+0,         27,         27,        1,     3329, 0xe4d42430, S=1,     1024, 0xf351799f
+0,         28,         28,        1,     3572, 0xf8058aa0, S=1,     1024, 0xf351799f
+0,         29,         29,        1,     3807, 0x3d2af9f3, S=1,     1024, 0xf351799f
+0,         30,         30,        1,     2750, 0x814d1c33, S=1,     1024, 0xf351799f
+0,         31,         31,        1,     4031, 0x3b077006, S=1,     1024, 0xf351799f
+0,         32,         32,        1,     3025, 0x86729c1c, S=1,     1024, 0xf351799f
+0,         33,         33,        1,     4295, 0xf71b0b38, S=1,     1024, 0xf351799f
+0,         34,         34,        1,     2044, 0x5adcb93b, S=1,     1024, 0xf351799f
+0,         35,         35,        1,     3212, 0xcf79eeed, S=1,     1024, 0xf351799f
+0,         36,         36,        1,     2292, 0xb4386334, S=1,     1024, 0xf351799f
+0,         37,         37,        1,     3633, 0x0010992f, S=1,     1024, 0xf351799f
+0,         38,         38,        1,     3552, 0x23697490, S=1,     1024, 0xf351799f
+0,         39,         39,        1,     3690, 0x62afdbb8, S=1,     1024, 0xf351799f
+0,         40,         40,        1,     1559, 0x5baef54a, S=1,     1024, 0xf351799f
+0,         41,         41,        1,      954, 0xca75ca79, S=1,     1024, 0xf351799f
+0,         42,         42,        1,      273, 0x3687799b, S=1,     1024, 0xf351799f
+0,         43,         43,        1,      930, 0x29f3b0c4, S=1,     1024, 0xf351799f
+0,         44,         44,        1,      271, 0x305e8094, S=1,     1024, 0xf351799f
+0,         45,         45,        1,      196, 0xf5ab51ee, S=1,     1024, 0xf351799f
+0,         46,         46,        1,     4299, 0x67ec0d55, S=1,     1024, 0xf351799f
+0,         47,         47,        1,     4895, 0xb394406c, S=1,     1024, 0xf351799f
+0,         48,         48,        1,     4928, 0x233919d7, S=1,     1024, 0xf351799f
+0,         49,         49,        1,     4941, 0x58a357da, S=1,     1024, 0xf351799f
+0,         50,         50,        1,     4154, 0x21f2ac33, S=1,     1024, 0xf351799f
+0,         51,         51,        1,     4678, 0xab3cc050, S=1,     1024, 0xf351799f
+0,         52,         52,        1,     4741, 0x1974b581, S=1,     1024, 0xf351799f
+0,         53,         53,        1,     4982, 0x891456d5, S=1,     1024, 0xf351799f
+0,         54,         54,        1,     5179, 0x860fc6a1, S=1,     1024, 0xf351799f
+0,         55,         55,        1,     5046, 0xce9183d3, S=1,     1024, 0xf351799f
+0,         56,         56,        1,     5140, 0xa6d7b9af, S=1,     1024, 0xf351799f
+0,         57,         57,        1,     4301, 0x03b6ef3f, S=1,     1024, 0xf351799f
+0,         58,         58,        1,     5079, 0xa8d59e01, S=1,     1024, 0xf351799f
+0,         59,         59,        1,     5284, 0xea34e3b3, S=1,     1024, 0xf351799f
+0,         60,         60,        1,     5426, 0x556a15cd, S=1,     1024, 0xf351799f
+0,         61,         61,        1,     4645, 0x061e8936, S=1,     1024, 0xf351799f
+0,         62,         62,        1,     5263, 0x7536cf7d, S=1,     1024, 0xf351799f
+0,         63,         63,        1,     5221, 0x9fbac3ca, S=1,     1024, 0xf351799f
+0,         64,         64,        1,     5217, 0x02269bd2, S=1,     1024, 0xf351799f
+0,         65,         65,        1,     5395, 0x120fff66, S=1,     1024, 0xf351799f
+0,         66,         66,        1,     5220, 0x77cedcc5, S=1,     1024, 0xf351799f
+0,         67,         67,        1,     5704, 0xba42dd96, S=1,     1024, 0xf351799f
+0,         68,         68,        1,     5636, 0xcb91a25b, S=1,     1024, 0xf351799f
+0,         69,         69,        1,     5818, 0x8dc0df92, S=1,     1024, 0xf351799f
+0,         70,         70,        1,     5763, 0x51d5d5f0, S=1,     1024, 0xf351799f
+0,         71,         71,        1,     6116, 0x09558b48, S=1,     1024, 0xf351799f
+0,         72,         72,        1,     6069, 0x41926817, S=1,     1024, 0xf351799f
+0,         73,         73,        1,     5796, 0x7fbeda44, S=1,     1024, 0xf351799f
+0,         74,         74,        1,     5999, 0xe07d3770, S=1,     1024, 0xf351799f
+0,         75,         75,        1,     6220, 0x6607b06f, S=1,     1024, 0xf351799f
+0,         76,         76,        1,     6374, 0x7628e533, S=1,     1024, 0xf351799f
+0,         77,         77,        1,     6465, 0xfe956b15, S=1,     1024, 0xf351799f
+0,         78,         78,        1,     7019, 0x6c9a1aef, S=1,     1024, 0xf351799f
+0,         79,         79,        1,     7255, 0x5fa5c1bf, S=1,     1024, 0xf351799f
+0,         80,         80,        1,     8197, 0xf11d6ef2, S=1,     1024, 0xf351799f
+0,         81,         81,        1,     8358, 0x027279e8, S=1,     1024, 0xf351799f
+0,         82,         82,        1,     7708, 0x607f8e8b, S=1,     1024, 0xf351799f
+0,         83,         83,        1,     7412, 0x6bb2105f, S=1,     1024, 0xf351799f
+0,         84,         84,        1,     7541, 0xfdc02154, S=1,     1024, 0xf351799f
+0,         85,         85,        1,     7948, 0x916ecd8b, S=1,     1024, 0xf351799f
+0,         86,         86,        1,     8408, 0x1f97d414, S=1,     1024, 0xf351799f
+0,         87,         87,        1,     8056, 0x9cbf159c, S=1,     1024, 0xf351799f
+0,         88,         88,        1,     7401, 0x2625addb, S=1,     1024, 0xf351799f
+0,         89,         89,        1,     7494, 0x2877eacb, S=1,     1024, 0xf351799f
+0,         90,         90,        1,     7806, 0xe32574a3, S=1,     1024, 0xf351799f
+0,         91,         91,        1,     7768, 0x25ed7ee7, S=1,     1024, 0xf351799f
+0,         92,         92,        1,     7749, 0x6d8e978e, S=1,     1024, 0xf351799f
+0,         93,         93,        1,     8047, 0xec4b150c, S=1,     1024, 0xf351799f
+0,         94,         94,        1,     7618, 0x88cf30d5, S=1,     1024, 0xf351799f
+0,         95,         95,        1,     7979, 0x0eb1cf2a, S=1,     1024, 0xf351799f
+0,         96,         96,        1,    12062, 0xb49d9125, S=1,     1024, 0xf351799f
+0,         97,         97,        1,    12317, 0x2d8fd6e9, S=1,     1024, 0xf351799f
+0,         98,         98,        1,    12217, 0x9b3be549, S=1,     1024, 0xf351799f
+0,         99,         99,        1,    11227, 0x067e9118, S=1,     1024, 0xf351799f
+0,        100,        100,        1,    11108, 0x5e5b0afd, S=1,     1024, 0xf351799f
+0,        101,        101,        1,    11366, 0xb38e8d15, S=1,     1024, 0xf351799f
+0,        102,        102,        1,    11896, 0xeb3e35ca, S=1,     1024, 0xf351799f
+0,        103,        103,        1,    11479, 0xbf7581e9, S=1,     1024, 0xf351799f
+0,        104,        104,        1,    13395, 0x415b38d8, S=1,     1024, 0xf351799f
+0,        105,        105,        1,    12913, 0x61544631, S=1,     1024, 0xf351799f
+0,        106,        106,        1,    13864, 0xd39fe768, S=1,     1024, 0xf351799f
+0,        107,        107,        1,    13551, 0x76c167d1, S=1,     1024, 0xf351799f
+0,        108,        108,        1,    14041, 0x2f206888, S=1,     1024, 0xf351799f
+0,        109,        109,        1,    14144, 0x9ec030d3, S=1,     1024, 0xf351799f
+0,        110,        110,        1,    14277, 0xa84b3a9b, S=1,     1024, 0xf351799f
+0,        111,        111,        1,    14424, 0xf5f1e06e, S=1,     1024, 0xf351799f
+0,        112,        112,        1,    14689, 0xbca0adb5, S=1,     1024, 0xf351799f
+0,        113,        113,        1,    14598, 0xc1d45745, S=1,     1024, 0xf351799f
+0,        114,        114,        1,    15213, 0x8f3080fc, S=1,     1024, 0xf351799f
+0,        115,        115,        1,    15425, 0xb0aa8f59, S=1,     1024, 0xf351799f
+0,        116,        116,        1,    15595, 0x1406e5d5, S=1,     1024, 0xf351799f
+0,        117,        117,        1,    15598, 0x48ec7d08, S=1,     1024, 0xf351799f
+0,        118,        118,        1,    15863, 0x5381db7b, S=1,     1024, 0xf351799f
+0,        119,        119,        1,    15717, 0xb87a1b87, S=1,     1024, 0xf351799f
+0,        120,        120,        1,    16078, 0x5bab2453, S=1,     1024, 0xf351799f
+0,        121,        121,        1,    16225, 0xa1f88113, S=1,     1024, 0xf351799f
+0,        122,        122,        1,    16135, 0x6af2f4e1, S=1,     1024, 0xf351799f
+0,        123,        123,        1,    16661, 0xf02a3343, S=1,     1024, 0xf351799f
+0,        124,        124,        1,    16619, 0xc71935a4, S=1,     1024, 0xf351799f
+0,        125,        125,        1,    16829, 0x29849844, S=1,     1024, 0xf351799f
+0,        126,        126,        1,    16944, 0x3423ae77, S=1,     1024, 0xf351799f
+0,        127,        127,        1,    17119, 0x609b4409, S=1,     1024, 0xf351799f
+0,        128,        128,        1,    17150, 0xf85dfd31, S=1,     1024, 0xf351799f
+0,        129,        129,        1,    17321, 0x38eccb10, S=1,     1024, 0xf351799f
+0,        130,        130,        1,    17395, 0x0ba08b85, S=1,     1024, 0xf351799f
+0,        131,        131,        1,    17666, 0x6fbc0264, S=1,     1024, 0xf351799f
+0,        132,        132,        1,    17730, 0x3dcc64a6, S=1,     1024, 0xf351799f
+0,        133,        133,        1,    17934, 0xb539974b, S=1,     1024, 0xf351799f
+0,        134,        134,        1,    17944, 0x2214ec94, S=1,     1024, 0xf351799f
+0,        135,        135,        1,    18238, 0x70f9ff1d, S=1,     1024, 0xf351799f
+0,        136,        136,        1,    18391, 0x4b149209, S=1,     1024, 0xf351799f
+0,        137,        137,        1,    18543, 0x45a1c02f, S=1,     1024, 0xf351799f
+0,        138,        138,        1,    18939, 0x2789a88c, S=1,     1024, 0xf351799f
+0,        139,        139,        1,    19145, 0x5daafd7a, S=1,     1024, 0xf351799f
+0,        140,        140,        1,    19120, 0x565f80e6, S=1,     1024, 0xf351799f
+0,        141,        141,        1,    19130, 0xff70cc21, S=1,     1024, 0xf351799f
+0,        142,        142,        1,    19494, 0xbfa284db, S=1,     1024, 0xf351799f
+0,        143,        143,        1,    19534, 0x3d40743b, S=1,     1024, 0xf351799f
+0,        144,        144,        1,    19747, 0x33c9b108, S=1,     1024, 0xf351799f
+0,        145,        145,        1,    20114, 0x9d223e36, S=1,     1024, 0xf351799f
+0,        146,        146,        1,    20257, 0xe7bdaf43, S=1,     1024, 0xf351799f
+0,        147,        147,        1,    20370, 0x0c5f1970, S=1,     1024, 0xf351799f
+0,        148,        148,        1,    20292, 0x6986d20e, S=1,     1024, 0xf351799f
+0,        149,        149,        1,    20491, 0xd88e4c08, S=1,     1024, 0xf351799f
+0,        150,        150,        1,    20647, 0x1aefaffc, S=1,     1024, 0xf351799f
+0,        151,        151,        1,    20666, 0x43e4aaaa, S=1,     1024, 0xf351799f
+0,        152,        152,        1,    21007, 0xa7ca3ef0, S=1,     1024, 0xf351799f
+0,        153,        153,        1,    21058, 0x06814351, S=1,     1024, 0xf351799f
+0,        154,        154,        1,    21153, 0x3c852b10, S=1,     1024, 0xf351799f
+0,        155,        155,        1,    21078, 0x8df15855, S=1,     1024, 0xf351799f
+0,        156,        156,        1,    21458, 0xd3a531d6, S=1,     1024, 0xf351799f
+0,        157,        157,        1,    21669, 0x88baca53, S=1,     1024, 0xf351799f
+0,        158,        158,        1,    21581, 0xd692fa1f, S=1,     1024, 0xf351799f
+0,        159,        159,        1,    21654, 0x30fb9061, S=1,     1024, 0xf351799f
+0,        160,        160,        1,    21987, 0xe7646d8b, S=1,     1024, 0xf351799f
+0,        161,        161,        1,    22205, 0x0fc55b6a, S=1,     1024, 0xf351799f
+0,        162,        162,        1,    22475, 0x4bc4c032, S=1,     1024, 0xf351799f
+0,        163,        163,        1,    22490, 0x58ca23f6, S=1,     1024, 0xf351799f
+0,        164,        164,        1,    22460, 0xf9ceb0ac, S=1,     1024, 0xf351799f
+0,        165,        165,        1,    22861, 0xb05f0f84, S=1,     1024, 0xf351799f
+0,        166,        166,        1,    22746, 0x0df23a5c, S=1,     1024, 0xf351799f
+0,        167,        167,        1,    23165, 0xbd7147ad, S=1,     1024, 0xf351799f
+0,        168,        168,        1,    23273, 0x9781a34f, S=1,     1024, 0xf351799f
+0,        169,        169,        1,    23211, 0x69c7606b, S=1,     1024, 0xf351799f
+0,        170,        170,        1,    23648, 0xdafde037, S=1,     1024, 0xf351799f
+0,        171,        171,        1,    23675, 0x2a2147ed, S=1,     1024, 0xf351799f
+0,        172,        172,        1,    23874, 0x12c184b6, S=1,     1024, 0xf351799f
diff --git a/tests/ref/fate/gifenc-rgb8 b/tests/ref/fate/gifenc-rgb8
index a894173..d1a990d 100644
--- a/tests/ref/fate/gifenc-rgb8
+++ b/tests/ref/fate/gifenc-rgb8
@@ -35,15 +35,15 @@
 0,         33,         33,        1,     4295, 0xc1850a80, S=1,     1024, 0xcfc8799f
 0,         34,         34,        1,     2044, 0x0440c072, S=1,     1024, 0xcfc8799f
 0,         35,         35,        1,     3212, 0xe91af08f, S=1,     1024, 0xcfc8799f
-0,         36,         36,        1,     2281, 0x6a414aa1, S=1,     1024, 0xcfc8799f
+0,         36,         36,        1,     2292, 0x6765633e, S=1,     1024, 0xcfc8799f
 0,         37,         37,        1,     3633, 0xac779aa3, S=1,     1024, 0xcfc8799f
 0,         38,         38,        1,     3552, 0xed2c75b2, S=1,     1024, 0xcfc8799f
 0,         39,         39,        1,     3690, 0x2020dd0d, S=1,     1024, 0xcfc8799f
-0,         40,         40,        1,     1558, 0x2c14e4b2, S=1,     1024, 0xcfc8799f
-0,         41,         41,        1,      940, 0x4927cd90, S=1,     1024, 0xcfc8799f
+0,         40,         40,        1,     1559, 0x596ef330, S=1,     1024, 0xcfc8799f
+0,         41,         41,        1,      954, 0xac12c9c5, S=1,     1024, 0xcfc8799f
 0,         42,         42,        1,      273, 0x138c7831, S=1,     1024, 0xcfc8799f
 0,         43,         43,        1,      930, 0xf1c3ae3f, S=1,     1024, 0xcfc8799f
-0,         44,         44,        1,      271, 0x6d338044, S=1,     1024, 0xcfc8799f
+0,         44,         44,        1,      271, 0x921a80af, S=1,     1024, 0xcfc8799f
 0,         45,         45,        1,      196, 0xa5de5322, S=1,     1024, 0xcfc8799f
 0,         46,         46,        1,     4299, 0x5bac0d86, S=1,     1024, 0xcfc8799f
 0,         47,         47,        1,     4895, 0xc43639a6, S=1,     1024, 0xcfc8799f
@@ -56,7 +56,7 @@
 0,         54,         54,        1,     5179, 0x97aac3a1, S=1,     1024, 0xcfc8799f
 0,         55,         55,        1,     5046, 0x836a80cd, S=1,     1024, 0xcfc8799f
 0,         56,         56,        1,     5140, 0xa725c1e7, S=1,     1024, 0xcfc8799f
-0,         57,         57,        1,     4289, 0x7b3afbc0, S=1,     1024, 0xcfc8799f
+0,         57,         57,        1,     4301, 0x0203f239, S=1,     1024, 0xcfc8799f
 0,         58,         58,        1,     5079, 0xb2e7a2de, S=1,     1024, 0xcfc8799f
 0,         59,         59,        1,     5284, 0xb757dfe1, S=1,     1024, 0xcfc8799f
 0,         60,         60,        1,     5426, 0xf9f11e57, S=1,     1024, 0xcfc8799f
diff --git a/tests/ref/fate/opt b/tests/ref/fate/opt
index 084a222..3aa7423 100644
--- a/tests/ref/fate/opt
+++ b/tests/ref/fate/opt
@@ -17,6 +17,29 @@
 num64=1
 flt=0.333333
 dbl=0.333333
+TestContext AVOptions:
+  -num               <int>        E....... set num (from 0 to 100) (default 0)
+  -toggle            <int>        E....... set toggle (from 0 to 1) (default 1)
+  -rational          <rational>   E....... set rational (from 0 to 10) (default 1/1)
+  -string            <string>     E....... set string (default "default")
+  -escape            <string>     E....... set escape str (default "\=,")
+  -flags             <flags>      E....... set flags (default 1)
+     cool                         E....... set cool flag
+     lame                         E....... set lame flag
+     mu                           E....... set mu flag
+  -size              <image_size> E....... set size (default "200x300")
+  -pix_fmt           <pix_fmt>    E....... set pixfmt (default 0bgr)
+  -sample_fmt        <sample_fmt> E....... set samplefmt (default s16)
+  -video_rate        <video_rate> E....... set videorate (default "25")
+  -duration          <duration>   E....... set duration (default 1000)
+  -color             <color>      E....... set color (default "pink")
+  -cl                <channel_layout> E....... set channel layout (default 0x137)
+  -bin               <binary>     E....... set binary value
+  -bin1              <binary>     E....... set binary value
+  -bin2              <binary>     E....... set binary value
+  -num64             <int64>      E....... set num 64bit (from 0 to 100) (default 1)
+  -flt               <float>      E....... set float (from 0 to 100) (default 0.333333)
+  -dbl               <double>     E....... set double (from 0 to 100) (default 0.333333)
 
 Testing av_opt_is_set_to_default()
 name:       num default:1 error:
@@ -66,76 +89,276 @@
 
 Test av_opt_serialize()
 num=0,toggle=1,rational=1/1,string=default,escape=\\\=\,,flags=0x00000001,size=200x300,pix_fmt=0bgr,sample_fmt=s16,video_rate=25/1,duration=0:00:00.001000,color=0xffc0cbff,cl=0x137,bin=62696E00,bin1=,bin2=,num64=1,flt=0.333333,dbl=0.333333
+Setting entry with key 'num' to value '0'
+Setting entry with key 'toggle' to value '1'
+Setting entry with key 'rational' to value '1/1'
+Setting entry with key 'string' to value 'default'
+Setting entry with key 'escape' to value '\=,'
+Setting entry with key 'flags' to value '0x00000001'
+Setting entry with key 'size' to value '200x300'
+Setting entry with key 'pix_fmt' to value '0bgr'
+Setting entry with key 'sample_fmt' to value 's16'
+Setting entry with key 'video_rate' to value '25/1'
+Setting entry with key 'duration' to value '0:00:00.001000'
+Setting entry with key 'color' to value '0xffc0cbff'
+Setting entry with key 'cl' to value '0x137'
+Setting entry with key 'bin' to value '62696E00'
+Setting entry with key 'bin1' to value ''
+Setting entry with key 'bin2' to value ''
+Setting entry with key 'num64' to value '1'
+Setting entry with key 'flt' to value '0.333333'
+Setting entry with key 'dbl' to value '0.333333'
 num=0,toggle=1,rational=1/1,string=default,escape=\\\=\,,flags=0x00000001,size=200x300,pix_fmt=0bgr,sample_fmt=s16,video_rate=25/1,duration=0:00:00.001000,color=0xffc0cbff,cl=0x137,bin=62696E00,bin1=,bin2=,num64=1,flt=0.333333,dbl=0.333333
 
 Testing av_set_options_string()
+Setting options string ''
 OK    ''
+Setting options string ':'
+Missing key or no key/value separator found after key ':'
 Error ':'
+Setting options string '='
+Missing key or no key/value separator found after key ''
 Error '='
+Setting options string 'foo=:'
+Setting entry with key 'foo' to value ''
+Key 'foo' not found.
 Error 'foo=:'
+Setting options string ':=foo'
+Setting entry with key ':' to value 'foo'
+Key ':' not found.
 Error ':=foo'
+Setting options string '=foo'
+Missing key or no key/value separator found after key ''
 Error '=foo'
+Setting options string 'foo='
+Setting entry with key 'foo' to value ''
+Key 'foo' not found.
 Error 'foo='
+Setting options string 'foo'
+Missing key or no key/value separator found after key 'foo'
 Error 'foo'
+Setting options string 'foo=val'
+Setting entry with key 'foo' to value 'val'
+Key 'foo' not found.
 Error 'foo=val'
+Setting options string 'foo==val'
+Setting entry with key 'foo' to value '=val'
+Key 'foo' not found.
 Error 'foo==val'
+Setting options string 'toggle=:'
+Setting entry with key 'toggle' to value ''
+Undefined constant or missing '(' in ''
+Unable to parse option value ""
 Error 'toggle=:'
+Setting options string 'string=:'
+Setting entry with key 'string' to value ''
 OK    'string=:'
+Setting options string 'toggle=1 : foo'
+Setting entry with key 'toggle' to value '1'
+Missing key or no key/value separator found after key 'foo'
 Error 'toggle=1 : foo'
+Setting options string 'toggle=100'
+Setting entry with key 'toggle' to value '100'
+Value 100.000000 for parameter 'toggle' out of range [0 - 1]
 Error 'toggle=100'
+Setting options string 'toggle==1'
+Setting entry with key 'toggle' to value '=1'
+Undefined constant or missing '(' in '=1'
+Unable to parse option value "=1"
 Error 'toggle==1'
+Setting options string 'flags=+mu-lame : num=42: toggle=0'
+Setting entry with key 'flags' to value '+mu-lame'
+Setting entry with key 'num' to value '42'
+Setting entry with key 'toggle' to value '0'
 OK    'flags=+mu-lame : num=42: toggle=0'
+Setting options string 'num=42 : string=blahblah'
+Setting entry with key 'num' to value '42'
+Setting entry with key 'string' to value 'blahblah'
 OK    'num=42 : string=blahblah'
+Setting options string 'rational=0 : rational=1/2 : rational=1/-1'
+Setting entry with key 'rational' to value '0'
+Setting entry with key 'rational' to value '1/2'
+Setting entry with key 'rational' to value '1/-1'
+Value -1.000000 for parameter 'rational' out of range [0 - 10]
+Value -1.000000 for parameter 'rational' out of range [0 - 10]
 Error 'rational=0 : rational=1/2 : rational=1/-1'
+Setting options string 'rational=-1/0'
 Error 'rational=-1/0'
+Setting options string 'size=1024x768'
+Setting entry with key 'size' to value '1024x768'
 OK    'size=1024x768'
+Setting options string 'size=pal'
+Setting entry with key 'size' to value 'pal'
 OK    'size=pal'
+Setting options string 'size=bogus'
+Setting entry with key 'size' to value 'bogus'
+Unable to parse option value "bogus" as image size
 Error 'size=bogus'
+Setting options string 'pix_fmt=yuv420p'
+Setting entry with key 'pix_fmt' to value 'yuv420p'
 OK    'pix_fmt=yuv420p'
+Setting options string 'pix_fmt=2'
+Setting entry with key 'pix_fmt' to value '2'
 OK    'pix_fmt=2'
+Setting options string 'pix_fmt=bogus'
+Setting entry with key 'pix_fmt' to value 'bogus'
+Unable to parse option value "bogus" as pixel format
 Error 'pix_fmt=bogus'
+Setting options string 'sample_fmt=s16'
+Setting entry with key 'sample_fmt' to value 's16'
 OK    'sample_fmt=s16'
+Setting options string 'sample_fmt=2'
+Setting entry with key 'sample_fmt' to value '2'
 OK    'sample_fmt=2'
+Setting options string 'sample_fmt=bogus'
+Setting entry with key 'sample_fmt' to value 'bogus'
+Unable to parse option value "bogus" as sample format
 Error 'sample_fmt=bogus'
+Setting options string 'video_rate=pal'
+Setting entry with key 'video_rate' to value 'pal'
 OK    'video_rate=pal'
+Setting options string 'video_rate=25'
+Setting entry with key 'video_rate' to value '25'
 OK    'video_rate=25'
+Setting options string 'video_rate=30000/1001'
+Setting entry with key 'video_rate' to value '30000/1001'
 OK    'video_rate=30000/1001'
+Setting options string 'video_rate=30/1.001'
+Setting entry with key 'video_rate' to value '30/1.001'
 OK    'video_rate=30/1.001'
+Setting options string 'video_rate=bogus'
+Setting entry with key 'video_rate' to value 'bogus'
+Undefined constant or missing '(' in 'bogus'
+Unable to parse option value "bogus" as video rate
 Error 'video_rate=bogus'
+Setting options string 'duration=bogus'
+Setting entry with key 'duration' to value 'bogus'
+Unable to parse option value "bogus" as duration
 Error 'duration=bogus'
+Setting options string 'duration=123.45'
+Setting entry with key 'duration' to value '123.45'
 OK    'duration=123.45'
+Setting options string 'duration=1\:23\:45.67'
+Setting entry with key 'duration' to value '1:23:45.67'
 OK    'duration=1\:23\:45.67'
+Setting options string 'color=blue'
+Setting entry with key 'color' to value 'blue'
 OK    'color=blue'
+Setting options string 'color=0x223300'
+Setting entry with key 'color' to value '0x223300'
 OK    'color=0x223300'
+Setting options string 'color=0x42FF07AA'
+Setting entry with key 'color' to value '0x42FF07AA'
 OK    'color=0x42FF07AA'
+Setting options string 'cl=stereo+downmix'
+Setting entry with key 'cl' to value 'stereo+downmix'
 OK    'cl=stereo+downmix'
+Setting options string 'cl=foo'
+Setting entry with key 'cl' to value 'foo'
+Unable to parse option value "foo" as channel layout
 Error 'cl=foo'
+Setting options string 'bin=boguss'
+Setting entry with key 'bin' to value 'boguss'
 Error 'bin=boguss'
+Setting options string 'bin=111'
+Setting entry with key 'bin' to value '111'
 Error 'bin=111'
+Setting options string 'bin=ffff'
+Setting entry with key 'bin' to value 'ffff'
 OK    'bin=ffff'
+Setting options string 'num64=bogus'
+Setting entry with key 'num64' to value 'bogus'
+Undefined constant or missing '(' in 'bogus'
+Unable to parse option value "bogus"
 Error 'num64=bogus'
+Setting options string 'num64=44'
+Setting entry with key 'num64' to value '44'
 OK    'num64=44'
+Setting options string 'num64=44.4'
+Setting entry with key 'num64' to value '44.4'
 OK    'num64=44.4'
+Setting options string 'num64=-1'
+Setting entry with key 'num64' to value '-1'
+Value -1.000000 for parameter 'num64' out of range [0 - 100]
 Error 'num64=-1'
+Setting options string 'num64=101'
+Setting entry with key 'num64' to value '101'
+Value 101.000000 for parameter 'num64' out of range [0 - 100]
 Error 'num64=101'
+Setting options string 'flt=bogus'
+Setting entry with key 'flt' to value 'bogus'
+Undefined constant or missing '(' in 'bogus'
+Unable to parse option value "bogus"
 Error 'flt=bogus'
+Setting options string 'flt=2'
+Setting entry with key 'flt' to value '2'
 OK    'flt=2'
+Setting options string 'flt=2.2'
+Setting entry with key 'flt' to value '2.2'
 OK    'flt=2.2'
+Setting options string 'flt=-1'
+Setting entry with key 'flt' to value '-1'
+Value -1.000000 for parameter 'flt' out of range [0 - 100]
 Error 'flt=-1'
+Setting options string 'flt=101'
+Setting entry with key 'flt' to value '101'
+Value 101.000000 for parameter 'flt' out of range [0 - 100]
 Error 'flt=101'
+Setting options string 'dbl=bogus'
+Setting entry with key 'dbl' to value 'bogus'
+Undefined constant or missing '(' in 'bogus'
+Unable to parse option value "bogus"
 Error 'dbl=bogus'
+Setting options string 'dbl=2'
+Setting entry with key 'dbl' to value '2'
 OK    'dbl=2'
+Setting options string 'dbl=2.2'
+Setting entry with key 'dbl' to value '2.2'
 OK    'dbl=2.2'
+Setting options string 'dbl=-1'
+Setting entry with key 'dbl' to value '-1'
+Value -1.000000 for parameter 'dbl' out of range [0 - 100]
 Error 'dbl=-1'
+Setting options string 'dbl=101'
+Setting entry with key 'dbl' to value '101'
+Value 101.000000 for parameter 'dbl' out of range [0 - 100]
 Error 'dbl=101'
 
 Testing av_opt_set_from_string()
+Setting options string ''
 OK    ''
+Setting options string '5'
+Setting 'num' to value '5'
 OK    '5'
+Setting options string '5:hello'
+Setting 'num' to value '5'
+Setting 'string' to value 'hello'
 OK    '5:hello'
+Setting options string '5:hello:size=pal'
+Setting 'num' to value '5'
+Setting 'string' to value 'hello'
+Setting 'size' to value 'pal'
 OK    '5:hello:size=pal'
+Setting options string '5:size=pal:hello'
+Setting 'num' to value '5'
+Setting 'size' to value 'pal'
+No option name near 'hello'
 Error '5:size=pal:hello'
+Setting options string ':'
+Setting 'num' to value ''
+Undefined constant or missing '(' in ''
+Unable to parse option value ""
 Error ':'
+Setting options string '='
+Setting '' to value ''
+Option '' not found
 Error '='
+Setting options string ' 5 : hello : size = pal '
+Setting 'num' to value '5'
+Setting 'string' to value 'hello'
+Setting 'size' to value 'pal'
 OK    ' 5 : hello : size = pal '
+Setting options string 'a_very_long_option_name_that_will_need_to_be_ellipsized_around_here=42'
+Setting 'a_very_long_option_name_that_will_need_to_be_ellipsized_around_here' to value '42'
+Option 'a_very_long_option_name_that_will_need_to_be_ellipsized_around_here' not found
 Error 'a_very_long_option_name_that_will_need_to_be_ellipsized_around_here=42'
diff --git a/tests/ref/fate/sub-movtextenc b/tests/ref/fate/sub-movtextenc
index e74b8f2..6efe2c0 100644
--- a/tests/ref/fate/sub-movtextenc
+++ b/tests/ref/fate/sub-movtextenc
@@ -1 +1 @@
-bb762c178bd8c437a9101c748c1ccb4d
+ef264064c522389d0cf267c4d6235561
diff --git a/tests/ref/fate/svq1-headerswap b/tests/ref/fate/svq1-headerswap
new file mode 100644
index 0000000..d9f9597
--- /dev/null
+++ b/tests/ref/fate/svq1-headerswap
@@ -0,0 +1,5 @@
+#tb 0: 1/10
+0,          0,          0,        1,    58814, 0x5caad04b
+0,          1,          1,        1,    58814, 0x98d8ceb8
+0,          2,          2,        1,    58814, 0x8925cdb0
+0,          3,          3,        1,    58814, 0x6ffc02c3
diff --git a/tests/ref/fate/tdsc b/tests/ref/fate/tdsc
new file mode 100644
index 0000000..d6925e9
--- /dev/null
+++ b/tests/ref/fate/tdsc
@@ -0,0 +1,42 @@
+#tb 0: 1/30
+0,          0,          0,        1,  3888000, 0x9c498657
+0,          7,          7,        1,  3888000, 0x72a2ae22
+0,          8,          8,        1,  3888000, 0x72a2ae22
+0,         10,         10,        1,  3888000, 0x72a2ae22
+0,         16,         16,        1,  3888000, 0x72a2ae22
+0,         17,         17,        1,  3888000, 0x72a2ae22
+0,         20,         20,        1,  3888000, 0x550e417b
+0,         29,         29,        1,  3888000, 0x550e417b
+0,         30,         30,        1,  3888000, 0x550e417b
+0,         31,         31,        1,  3888000, 0x550e417b
+0,         32,         32,        1,  3888000, 0x550e417b
+0,         34,         34,        1,  3888000, 0x550e417b
+0,         35,         35,        1,  3888000, 0x38dcde13
+0,         47,         47,        1,  3888000, 0x2b7c0edd
+0,         48,         48,        1,  3888000, 0xaaaf3c7b
+0,         49,         49,        1,  3888000, 0x26d1710f
+0,         50,         50,        1,  3888000, 0xa6609f3f
+0,         51,         51,        1,  3888000, 0xaa41c6f3
+0,         52,         52,        1,  3888000, 0xc0ffd4d5
+0,         53,         53,        1,  3888000, 0x44d4f383
+0,         55,         55,        1,  3888000, 0x517047eb
+0,         56,         56,        1,  3888000, 0x1d5a4d5b
+0,         57,         57,        1,  3888000, 0x7d2da2f6
+0,         58,         58,        1,  3888000, 0x27f7a2f6
+0,         59,         59,        1,  3888000, 0x9de49edb
+0,         60,         60,        1,  3888000, 0x5ccb9f38
+0,         61,         61,        1,  3888000, 0x88069fb2
+0,         62,         62,        1,  3888000, 0x1d059fd3
+0,         63,         63,        1,  3888000, 0xe16d9fd3
+0,         64,         64,        1,  3888000, 0xb6a69fd3
+0,         65,         65,        1,  3888000, 0xb6a69fd3
+0,         66,         66,        1,  3888000, 0x61709fd3
+0,         67,         67,        1,  3888000, 0xb6f59fd3
+0,         68,         68,        1,  3888000, 0x5c7b9fd3
+0,         69,         69,        1,  3888000, 0x57869fd3
+0,         70,         70,        1,  3888000, 0x9d3f9fd3
+0,         73,         73,        1,  3888000, 0x5e6082a5
+0,         74,         74,        1,  3888000, 0x5e6082a5
+0,         75,         75,        1,  3888000, 0x5e6082a5
+0,         76,         76,        1,  3888000, 0x48ce82f3
+0,         77,         77,        1,  3888000, 0x4c5ebeaf
diff --git a/tests/ref/fate/tscc2 b/tests/ref/fate/tscc2-avi
similarity index 100%
rename from tests/ref/fate/tscc2
rename to tests/ref/fate/tscc2-avi
diff --git a/tests/ref/fate/tscc2-mov b/tests/ref/fate/tscc2-mov
new file mode 100644
index 0000000..d73ff3f
--- /dev/null
+++ b/tests/ref/fate/tscc2-mov
@@ -0,0 +1,16 @@
+#tb 0: 1/5
+0,          0,          0,        1,  1180116, 0x01d01336
+0,          1,          1,        1,  1180116, 0x01d01336
+0,          2,          2,        1,  1180116, 0x01d01336
+0,          3,          3,        1,  1180116, 0x01d01336
+0,          4,          4,        1,  1180116, 0x01d01336
+0,          5,          5,        1,  1180116, 0x01d01336
+0,          6,          6,        1,  1180116, 0x01d01336
+0,          7,          7,        1,  1180116, 0x01d01336
+0,          8,          8,        1,  1180116, 0x01d01336
+0,          9,          9,        1,  1180116, 0x01d01336
+0,         10,         10,        1,  1180116, 0x056fdadd
+0,         11,         11,        1,  1180116, 0x6f73e080
+0,         12,         12,        1,  1180116, 0x5244d9e5
+0,         13,         13,        1,  1180116, 0x629bf10f
+0,         14,         14,        1,  1180116, 0x97c726cb
diff --git a/tests/ref/fate/vp9-trac4359 b/tests/ref/fate/vp9-trac4359
new file mode 100644
index 0000000..cd271a7
--- /dev/null
+++ b/tests/ref/fate/vp9-trac4359
@@ -0,0 +1,9 @@
+#format: frame checksums
+#version: 1
+#hash: MD5
+#tb 0: 1/25
+#stream#, dts,        pts, duration,     size, hash
+0,          0,          0,        1,  1382400, 2929e5318edee6cd6b24ede0c1015137
+0,          1,          1,        1,  1382400, ca0d83b04297da33a1aa17129a9fe9c9
+0,          2,          2,        1,  1382400, dfdb277e615307e501f416669a208ff4
+0,          3,          3,        1,  1382400, 9c17c58ea4fc5ff1c3398acbf5cc6c69
diff --git a/tests/ref/lavf/avi b/tests/ref/lavf/avi
index 4068fad..8b14370 100644
--- a/tests/ref/lavf/avi
+++ b/tests/ref/lavf/avi
@@ -1,3 +1,3 @@
-cec38e42ff83343f6a5c300aa3009e7f *./tests/data/lavf/lavf.avi
-330806 ./tests/data/lavf/lavf.avi
+07a29d329e7f07a4fd682145c3771995 *./tests/data/lavf/lavf.avi
+330814 ./tests/data/lavf/lavf.avi
 ./tests/data/lavf/lavf.avi CRC=0xec6c3c68
diff --git a/tests/ref/lavf/mxf b/tests/ref/lavf/mxf
index 236661c..8ead434 100644
--- a/tests/ref/lavf/mxf
+++ b/tests/ref/lavf/mxf
@@ -1,9 +1,9 @@
-dbc4ced82ef1c2fa4df3571b4f994a22 *./tests/data/lavf/lavf.mxf
+306708cc2ad2414def89fa2f3c0bfc5c *./tests/data/lavf/lavf.mxf
 525369 ./tests/data/lavf/lavf.mxf
 ./tests/data/lavf/lavf.mxf CRC=0xdbfff6f1
-fe4294023cd990938f042c7855405f63 *./tests/data/lavf/lavf.mxf
+f465084f0c365926a81aab56fb6b945c *./tests/data/lavf/lavf.mxf
 560697 ./tests/data/lavf/lavf.mxf
 ./tests/data/lavf/lavf.mxf CRC=0x11a6178e
-ef0c741e17bf7963fc51adcb6bab8ec8 *./tests/data/lavf/lavf.mxf
+52fc707e1177c97232e2537168c232e6 *./tests/data/lavf/lavf.mxf
 525369 ./tests/data/lavf/lavf.mxf
 ./tests/data/lavf/lavf.mxf CRC=0xdbfff6f1
diff --git a/tests/ref/lavf/mxf_d10 b/tests/ref/lavf/mxf_d10
index ff7d876..71707ca 100644
--- a/tests/ref/lavf/mxf_d10
+++ b/tests/ref/lavf/mxf_d10
@@ -1,3 +1,3 @@
-87e0903ef7ea55b1a032b9d878588683 *./tests/data/lavf/lavf.mxf_d10
+8f601d5b55a0665cc105a115dc8b3af0 *./tests/data/lavf/lavf.mxf_d10
 5330989 ./tests/data/lavf/lavf.mxf_d10
 ./tests/data/lavf/lavf.mxf_d10 CRC=0x6c74d488
diff --git a/tests/ref/lavf/mxf_opatom b/tests/ref/lavf/mxf_opatom
new file mode 100644
index 0000000..5529e5b
--- /dev/null
+++ b/tests/ref/lavf/mxf_opatom
@@ -0,0 +1,3 @@
+0f753a141424e2a1b44e6390f70172eb *./tests/data/lavf/lavf.mxf_opatom
+4717113 ./tests/data/lavf/lavf.mxf_opatom
+./tests/data/lavf/lavf.mxf_opatom CRC=0xbdd696b9
diff --git a/tests/ref/seek/lavf-avi b/tests/ref/seek/lavf-avi
index 7725134..4f308d6 100644
--- a/tests/ref/seek/lavf-avi
+++ b/tests/ref/seek/lavf-avi
@@ -1,44 +1,44 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9926 size: 27867
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9934 size: 27867
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9926 size: 27867
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9934 size: 27867
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301474 size: 27864
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301482 size: 27864
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301474 size: 27864
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301482 size: 27864
 ret:-1         st: 0 flags:1  ts:-0.320000
 ret:-1         st: 1 flags:0  ts: 2.586122
 ret: 0         st: 1 flags:1  ts: 1.462857
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301474 size: 27864
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301482 size: 27864
 ret: 0         st:-1 flags:0  ts: 0.365002
-ret: 0         st: 1 flags:1 dts: 0.470204 pts: 0.470204 pos: 155956 size:   209
+ret: 0         st: 1 flags:1 dts: 0.470204 pts: 0.470204 pos: 155964 size:   209
 ret:-1         st:-1 flags:1  ts:-0.740831
 ret:-1         st: 0 flags:0  ts: 2.160000
 ret: 0         st: 0 flags:1  ts: 1.040000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301474 size: 27864
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301482 size: 27864
 ret: 0         st: 1 flags:0  ts:-0.052245
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9926 size: 27867
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9934 size: 27867
 ret: 0         st: 1 flags:1  ts: 2.847347
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301474 size: 27864
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301482 size: 27864
 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.470204 pts: 0.470204 pos: 155956 size:   209
+ret: 0         st: 1 flags:1 dts: 0.470204 pts: 0.470204 pos: 155964 size:   209
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9926 size: 27867
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9934 size: 27867
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301474 size: 27864
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301482 size: 27864
 ret:-1         st: 1 flags:0  ts: 1.306122
 ret: 0         st: 1 flags:1  ts: 0.208980
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9926 size: 27867
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9934 size: 27867
 ret: 0         st:-1 flags:0  ts:-0.904994
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9926 size: 27867
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   9934 size: 27867
 ret: 0         st:-1 flags:1  ts: 1.989173
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301474 size: 27864
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301482 size: 27864
 ret: 0         st: 0 flags:0  ts: 0.880000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301474 size: 27864
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301482 size: 27864
 ret:-1         st: 0 flags:1  ts:-0.240000
 ret:-1         st: 1 flags:0  ts: 2.664490
 ret: 0         st: 1 flags:1  ts: 1.567347
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301474 size: 27864
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 301482 size: 27864
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 1 flags:1 dts: 0.470204 pts: 0.470204 pos: 155956 size:   209
+ret: 0         st: 1 flags:1 dts: 0.470204 pts: 0.470204 pos: 155964 size:   209
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/lavf-mxf_opatom b/tests/ref/seek/lavf-mxf_opatom
new file mode 100644
index 0000000..ca17ba7
--- /dev/null
+++ b/tests/ref/seek/lavf-mxf_opatom
@@ -0,0 +1,53 @@
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5145 size:188416
+ret: 0         st:-1 flags:0  ts:-1.000000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5145 size:188416
+ret: 0         st:-1 flags:1  ts: 1.894167
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:4527129 size:188416
+ret: 0         st: 0 flags:0  ts: 0.800000
+ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:3773465 size:188416
+ret: 0         st: 0 flags:1  ts:-0.320000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5145 size:188416
+ret: 0         st:-1 flags:0  ts: 2.576668
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:4527129 size:188416
+ret: 0         st:-1 flags:1  ts: 1.470835
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:4527129 size:188416
+ret: 0         st: 0 flags:0  ts: 0.360000
+ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos:1700889 size:188416
+ret: 0         st: 0 flags:1  ts:-0.760000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5145 size:188416
+ret: 0         st:-1 flags:0  ts: 2.153336
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:4527129 size:188416
+ret: 0         st:-1 flags:1  ts: 1.047503
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:4527129 size:188416
+ret: 0         st: 0 flags:0  ts:-0.040000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5145 size:188416
+ret: 0         st: 0 flags:1  ts: 2.840000
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:4527129 size:188416
+ret: 0         st:-1 flags:0  ts: 1.730004
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:4527129 size:188416
+ret: 0         st:-1 flags:1  ts: 0.624171
+ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:3019801 size:188416
+ret: 0         st: 0 flags:0  ts:-0.480000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5145 size:188416
+ret: 0         st: 0 flags:1  ts: 2.400000
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:4527129 size:188416
+ret: 0         st:-1 flags:0  ts: 1.306672
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:4527129 size:188416
+ret: 0         st:-1 flags:1  ts: 0.200839
+ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos: 947225 size:188416
+ret: 0         st: 0 flags:0  ts:-0.920000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5145 size:188416
+ret: 0         st: 0 flags:1  ts: 2.000000
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:4527129 size:188416
+ret: 0         st:-1 flags:0  ts: 0.883340
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:4150297 size:188416
+ret: 0         st:-1 flags:1  ts:-0.222493
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5145 size:188416
+ret: 0         st: 0 flags:0  ts: 2.680000
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:4527129 size:188416
+ret: 0         st: 0 flags:1  ts: 1.560000
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:4527129 size:188416
+ret: 0         st:-1 flags:0  ts: 0.460008
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:2266137 size:188416
+ret: 0         st:-1 flags:1  ts:-0.645825
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5145 size:188416
diff --git a/tests/ref/seek/vsynth_lena-asv1 b/tests/ref/seek/vsynth_lena-asv1
index e2556a7..0957d84 100644
--- a/tests/ref/seek/vsynth_lena-asv1
+++ b/tests/ref/seek/vsynth_lena-asv1
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 12152
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 12152
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 12152
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 12152
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos: 643344 size: 15064
+ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos: 643348 size: 15064
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos: 255232 size: 13312
+ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos: 255236 size: 13312
 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: 493584 size: 14796
+ret: 0         st: 0 flags:1 dts: 1.480000 pts: 1.480000 pos: 493588 size: 14796
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos: 114852 size: 12356
+ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos: 114856 size: 12356
 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: 336180 size: 13824
+ret: 0         st: 0 flags:1 dts: 1.040000 pts: 1.040000 pos: 336184 size: 13824
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 12152
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 12152
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 673504 size: 15104
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 673508 size: 15104
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos: 583312 size: 14956
+ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos: 583316 size: 14956
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos: 202872 size: 12944
+ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos: 202876 size: 12944
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 12152
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 12152
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 673504 size: 15104
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 673508 size: 15104
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos: 435128 size: 14488
+ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos: 435132 size: 14488
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos:  65864 size: 12144
+ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos:  65868 size: 12144
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 12152
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 12152
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 673504 size: 15104
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 673508 size: 15104
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos: 281884 size: 13412
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos: 281888 size: 13412
 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: 523324 size: 14972
+ret: 0         st: 0 flags:1 dts: 1.560000 pts: 1.560000 pos: 523328 size: 14972
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 152056 size: 12540
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 152060 size: 12540
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-asv2 b/tests/ref/seek/vsynth_lena-asv2
index cd99c45..1a3c93f 100644
--- a/tests/ref/seek/vsynth_lena-asv2
+++ b/tests/ref/seek/vsynth_lena-asv2
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 12072
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 12072
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 12072
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 12072
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos: 630028 size: 14892
+ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos: 630032 size: 14892
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos: 248836 size: 13024
+ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos: 248840 size: 13024
 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: 482700 size: 14532
+ret: 0         st: 0 flags:1 dts: 1.480000 pts: 1.480000 pos: 482704 size: 14532
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos: 111600 size: 12016
+ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos: 111604 size: 12016
 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: 328252 size: 13532
+ret: 0         st: 0 flags:1 dts: 1.040000 pts: 1.040000 pos: 328256 size: 13532
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 12072
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 12072
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 659848 size: 14928
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 659852 size: 14928
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos: 570784 size: 14712
+ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos: 570788 size: 14712
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos: 197536 size: 12724
+ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos: 197540 size: 12724
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 12072
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 12072
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 659848 size: 14928
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 659852 size: 14928
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos: 425316 size: 14116
+ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos: 425320 size: 14116
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos:  64104 size: 11780
+ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos:  64108 size: 11780
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size: 12072
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5660 size: 12072
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 659848 size: 14928
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 659852 size: 14928
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos: 274964 size: 13176
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos: 274968 size: 13176
 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: 511944 size: 14668
+ret: 0         st: 0 flags:1 dts: 1.560000 pts: 1.560000 pos: 511948 size: 14668
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 147820 size: 12240
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 147824 size: 12240
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-ffv1 b/tests/ref/seek/vsynth_lena-ffv1
index 84e7436..5758368 100644
--- a/tests/ref/seek/vsynth_lena-ffv1
+++ b/tests/ref/seek/vsynth_lena-ffv1
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5690 size: 71707
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5694 size: 71707
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5690 size: 71707
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5694 size: 71707
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:2499438 size: 75965
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:2499442 size: 75965
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1631570 size: 72710
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1631574 size: 72710
 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:2499438 size: 75965
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:2499442 size: 75965
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 801634 size: 69485
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 801638 size: 69485
 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:1631570 size: 72710
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1631574 size: 72710
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5690 size: 71707
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5694 size: 71707
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:3393890 size: 77489
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:3393894 size: 77489
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:3393890 size: 77489
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:3393894 size: 77489
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 801634 size: 69485
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 801638 size: 69485
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5690 size: 71707
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5694 size: 71707
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:3393890 size: 77489
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:3393894 size: 77489
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:2499438 size: 75965
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:2499442 size: 75965
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5690 size: 71707
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5694 size: 71707
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5690 size: 71707
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5694 size: 71707
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:3393890 size: 77489
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:3393894 size: 77489
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1631570 size: 72710
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1631574 size: 72710
 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:2499438 size: 75965
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:2499442 size: 75965
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 801634 size: 69485
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 801638 size: 69485
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-h261 b/tests/ref/seek/vsynth_lena-h261
index 48ee00f..dabf6a3 100644
--- a/tests/ref/seek/vsynth_lena-h261
+++ b/tests/ref/seek/vsynth_lena-h261
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9645
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  9645
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9645
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  9645
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 126494 size: 11377
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 126498 size: 11377
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  82052 size: 10322
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  82056 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: 126494 size: 11377
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 126498 size: 11377
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  44664 size:  9404
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  44668 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:  82052 size: 10322
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  82056 size: 10322
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9645
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  9645
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 175856 size: 11707
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 175860 size: 11707
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 175856 size: 11707
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 175860 size: 11707
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  44664 size:  9404
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  44668 size:  9404
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9645
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  9645
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 175856 size: 11707
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 175860 size: 11707
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 126494 size: 11377
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 126498 size: 11377
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9645
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  9645
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9645
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  9645
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 175856 size: 11707
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 175860 size: 11707
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  82052 size: 10322
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  82056 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: 126494 size: 11377
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 126498 size: 11377
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  44664 size:  9404
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  44668 size:  9404
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-h263 b/tests/ref/seek/vsynth_lena-h263
index 6b7df48..5e50ca3 100644
--- a/tests/ref/seek/vsynth_lena-h263
+++ b/tests/ref/seek/vsynth_lena-h263
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10381
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 10381
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10381
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 10381
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 103702 size: 12296
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 103706 size: 12296
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  66792 size: 11128
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  66796 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: 103702 size: 12296
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 103706 size: 12296
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  36438 size: 10090
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  36442 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:  66792 size: 11128
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  66796 size: 11128
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10381
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 10381
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 144552 size: 12731
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 144556 size: 12731
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 144552 size: 12731
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 144556 size: 12731
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  36438 size: 10090
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  36442 size: 10090
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10381
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 10381
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 144552 size: 12731
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 144556 size: 12731
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 103702 size: 12296
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 103706 size: 12296
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10381
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 10381
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10381
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 10381
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 144552 size: 12731
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 144556 size: 12731
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  66792 size: 11128
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  66796 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: 103702 size: 12296
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 103706 size: 12296
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  36438 size: 10090
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  36442 size: 10090
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-h263p b/tests/ref/seek/vsynth_lena-h263p
index 7dd4852..c87a906 100644
--- a/tests/ref/seek/vsynth_lena-h263p
+++ b/tests/ref/seek/vsynth_lena-h263p
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 36208
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 36208
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 36208
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 36208
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 569918 size: 45151
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 569922 size: 45151
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 355968 size: 40907
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 355972 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: 569918 size: 45151
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 569922 size: 45151
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 171042 size: 36514
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 171046 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: 355968 size: 40907
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 355972 size: 40907
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 36208
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 36208
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 804358 size: 46411
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 804362 size: 46411
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 804358 size: 46411
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 804362 size: 46411
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 171042 size: 36514
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 171046 size: 36514
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 36208
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 36208
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 804358 size: 46411
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 804362 size: 46411
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 569918 size: 45151
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 569922 size: 45151
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 36208
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 36208
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 36208
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 36208
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 804358 size: 46411
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 804362 size: 46411
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 355968 size: 40907
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos: 355972 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: 569918 size: 45151
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 569922 size: 45151
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 171042 size: 36514
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 171046 size: 36514
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-huffyuv b/tests/ref/seek/vsynth_lena-huffyuv
index ad01899..79e29a0 100644
--- a/tests/ref/seek/vsynth_lena-huffyuv
+++ b/tests/ref/seek/vsynth_lena-huffyuv
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5754 size:123508
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5758 size:123508
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5754 size:123508
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5758 size:123508
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos:5744998 size:121152
+ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos:5745002 size:121152
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:2437994 size:122516
+ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:2437998 size:122516
 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:4523454 size:122784
+ret: 0         st: 0 flags:1 dts: 1.480000 pts: 1.480000 pos:4523458 size:122784
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos:1093870 size:121320
+ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos:1093874 size:121320
 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:3173590 size:122784
+ret: 0         st: 0 flags:1 dts: 1.040000 pts: 1.040000 pos:3173594 size:122784
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5754 size:123508
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5758 size:123508
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:5987030 size:120672
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:5987034 size:120672
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:5258650 size:121992
+ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:5258654 size:121992
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:1947350 size:122568
+ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:1947354 size:122568
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5754 size:123508
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5758 size:123508
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:5987030 size:120672
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:5987034 size:120672
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:4032694 size:122544
+ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:4032698 size:122544
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos: 609906 size:120724
+ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos: 609910 size:120724
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5754 size:123508
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5758 size:123508
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:5987030 size:120672
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:5987034 size:120672
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:2683062 size:122588
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:2683066 size:122588
 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:4768978 size:122556
+ret: 0         st: 0 flags:1 dts: 1.560000 pts: 1.560000 pos:4768982 size:122556
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:1458406 size:121888
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:1458410 size:121888
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-jpegls b/tests/ref/seek/vsynth_lena-jpegls
index 3c0da21..c773313 100644
--- a/tests/ref/seek/vsynth_lena-jpegls
+++ b/tests/ref/seek/vsynth_lena-jpegls
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:164074
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:164074
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:164074
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:164074
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos:7804118 size:176295
+ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos:7804122 size:176295
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:3172780 size:164643
+ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:3172784 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:6052974 size:174097
+ret: 0         st: 0 flags:1 dts: 1.480000 pts: 1.480000 pos:6052978 size:174097
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos:1402344 size:157283
+ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos:1402348 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:4170248 size:168401
+ret: 0         st: 0 flags:1 dts: 1.040000 pts: 1.040000 pos:4170252 size:168401
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:164074
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:164074
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:8157016 size:176793
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:8157020 size:176793
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:7101754 size:175326
+ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:7101758 size:175326
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:2519260 size:162522
+ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:2519264 size:162522
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:164074
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:164074
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:8157016 size:176793
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:8157020 size:176793
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:5360818 size:172183
+ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:5360822 size:172183
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos: 779834 size:154579
+ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos: 779838 size:154579
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:164074
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:164074
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:8157016 size:176793
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:8157020 size:176793
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:3502828 size:166017
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:3502832 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:6401452 size:174815
+ret: 0         st: 0 flags:1 dts: 1.560000 pts: 1.560000 pos:6401456 size:174815
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:1876416 size:159659
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:1876420 size:159659
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-ljpeg b/tests/ref/seek/vsynth_lena-ljpeg
index 1ca1441..bb58fd9 100644
--- a/tests/ref/seek/vsynth_lena-ljpeg
+++ b/tests/ref/seek/vsynth_lena-ljpeg
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 96000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 96000
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 96000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 96000
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos:4478624 size: 94801
+ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos:4478628 size: 94801
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:1900940 size: 95396
+ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:1900944 size: 95396
 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:3525172 size: 95655
+ret: 0         st: 0 flags:1 dts: 1.480000 pts: 1.480000 pos:3525176 size: 95655
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos: 854322 size: 94566
+ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos: 854326 size: 94566
 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:2473776 size: 95580
+ret: 0         st: 0 flags:1 dts: 1.040000 pts: 1.040000 pos:2473780 size: 95580
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 96000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 96000
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:4668120 size: 94526
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:4668124 size: 94526
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:4098374 size: 95284
+ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:4098378 size: 95284
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:1519182 size: 95341
+ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:1519186 size: 95341
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 96000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 96000
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:4668120 size: 94526
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:4668124 size: 94526
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:3142838 size: 95518
+ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:3142842 size: 95518
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos: 476880 size: 94192
+ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos: 476884 size: 94192
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 96000
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 96000
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:4668120 size: 94526
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:4668124 size: 94526
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:2091786 size: 95459
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:2091790 size: 95459
 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:3716438 size: 95546
+ret: 0         st: 0 flags:1 dts: 1.560000 pts: 1.560000 pos:3716442 size: 95546
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:1138408 size: 94963
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:1138412 size: 94963
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-mjpeg b/tests/ref/seek/vsynth_lena-mjpeg
index c1395a9..08cbd88 100644
--- a/tests/ref/seek/vsynth_lena-mjpeg
+++ b/tests/ref/seek/vsynth_lena-mjpeg
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 12096
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 12096
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 12096
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 12096
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos: 627814 size: 14806
+ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos: 627818 size: 14806
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos: 247498 size: 12959
+ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos: 247502 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: 480736 size: 14519
+ret: 0         st: 0 flags:1 dts: 1.480000 pts: 1.480000 pos: 480740 size: 14519
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos: 110996 size: 11924
+ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos: 111000 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: 326680 size: 13491
+ret: 0         st: 0 flags:1 dts: 1.040000 pts: 1.040000 pos: 326684 size: 13491
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 12096
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 12096
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 657468 size: 14897
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 657472 size: 14897
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos: 568606 size: 14751
+ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos: 568610 size: 14751
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos: 196420 size: 12720
+ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos: 196424 size: 12720
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 12096
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 12096
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 657468 size: 14897
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 657472 size: 14897
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos: 423470 size: 14114
+ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos: 423474 size: 14114
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos:  63862 size: 11715
+ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos:  63866 size: 11715
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 12096
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 12096
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 657468 size: 14897
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos: 657472 size: 14897
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos: 273512 size: 13122
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos: 273516 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: 509892 size: 14594
+ret: 0         st: 0 flags:1 dts: 1.560000 pts: 1.560000 pos: 509896 size: 14594
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146950 size: 12173
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 146954 size: 12173
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-mpeg4-adap b/tests/ref/seek/vsynth_lena-mpeg4-adap
index cb6beee..0611ee4 100644
--- a/tests/ref/seek/vsynth_lena-mpeg4-adap
+++ b/tests/ref/seek/vsynth_lena-mpeg4-adap
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size:  6855
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size:  6855
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size:  6855
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size:  6855
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174442 size: 16883
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174446 size: 16883
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  98216 size: 17063
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  98220 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: 135578 size: 17525
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 135582 size: 17525
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  59442 size: 17261
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  59446 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:  98216 size: 17063
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  98220 size: 17063
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size:  6855
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size:  6855
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174442 size: 16883
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174446 size: 16883
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174442 size: 16883
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174446 size: 16883
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  59442 size: 17261
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  59446 size: 17261
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size:  6855
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size:  6855
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174442 size: 16883
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174446 size: 16883
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 135578 size: 17525
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 135582 size: 17525
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size:  6855
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size:  6855
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size:  6855
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size:  6855
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174442 size: 16883
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 174446 size: 16883
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  98216 size: 17063
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  98220 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: 135578 size: 17525
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 135582 size: 17525
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  98216 size: 17063
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  98220 size: 17063
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-mpeg4-adv b/tests/ref/seek/vsynth_lena-mpeg4-adv
index 6765864..9a51eae 100644
--- a/tests/ref/seek/vsynth_lena-mpeg4-adv
+++ b/tests/ref/seek/vsynth_lena-mpeg4-adv
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8653
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8653
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8653
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8653
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  91718 size: 11013
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  91722 size: 11013
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  59492 size:  9815
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  59496 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:  91718 size: 11013
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  91722 size: 11013
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  31932 size:  8753
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  31936 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:  59492 size:  9815
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  59496 size:  9815
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8653
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8653
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 127612 size: 11279
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 127616 size: 11279
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 127612 size: 11279
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 127616 size: 11279
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  31932 size:  8753
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  31936 size:  8753
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8653
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8653
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 127612 size: 11279
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 127616 size: 11279
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  91718 size: 11013
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  91722 size: 11013
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8653
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8653
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8653
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8653
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 127612 size: 11279
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 127616 size: 11279
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  59492 size:  9815
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  59496 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:  91718 size: 11013
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  91722 size: 11013
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  31932 size:  8753
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  31936 size:  8753
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-mpeg4-error b/tests/ref/seek/vsynth_lena-mpeg4-error
index e31df5d..9608a7b 100644
--- a/tests/ref/seek/vsynth_lena-mpeg4-error
+++ b/tests/ref/seek/vsynth_lena-mpeg4-error
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9729
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  9729
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9729
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  9729
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 113182 size: 15063
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 113186 size: 15063
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  73142 size: 10235
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  73146 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: 113182 size: 15063
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 113186 size: 15063
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  38228 size: 10303
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  38232 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:  73142 size: 10235
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  73146 size: 10235
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9729
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  9729
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 163064 size: 13980
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 163068 size: 13980
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 163064 size: 13980
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 163068 size: 13980
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  38228 size: 10303
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  38232 size: 10303
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9729
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  9729
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 163064 size: 13980
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 163068 size: 13980
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 113182 size: 15063
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 113186 size: 15063
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9729
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  9729
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9729
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  9729
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 163064 size: 13980
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 163068 size: 13980
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  73142 size: 10235
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  73146 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: 113182 size: 15063
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 113186 size: 15063
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  38228 size: 10303
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  38232 size: 10303
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-mpeg4-nr b/tests/ref/seek/vsynth_lena-mpeg4-nr
index 3d6b5ce..6de31b7 100644
--- a/tests/ref/seek/vsynth_lena-mpeg4-nr
+++ b/tests/ref/seek/vsynth_lena-mpeg4-nr
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10673
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 10673
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10673
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 10673
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 100652 size: 12464
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 100656 size: 12464
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  65488 size: 11180
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  65492 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: 100652 size: 12464
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 100656 size: 12464
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  35310 size:  9987
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  35314 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:  65488 size: 11180
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  65492 size: 11180
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10673
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 10673
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139372 size: 12911
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139376 size: 12911
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139372 size: 12911
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139376 size: 12911
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  35310 size:  9987
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  35314 size:  9987
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10673
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 10673
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139372 size: 12911
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139376 size: 12911
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 100652 size: 12464
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 100656 size: 12464
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10673
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 10673
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 10673
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 10673
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139372 size: 12911
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 139376 size: 12911
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  65488 size: 11180
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  65492 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: 100652 size: 12464
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 100656 size: 12464
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  35310 size:  9987
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  35314 size:  9987
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-mpeg4-nsse b/tests/ref/seek/vsynth_lena-mpeg4-nsse
index 8e2a95f..e73ce60 100644
--- a/tests/ref/seek/vsynth_lena-mpeg4-nsse
+++ b/tests/ref/seek/vsynth_lena-mpeg4-nsse
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 11937
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 11937
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 11937
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 11937
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 127872 size: 15054
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 127876 size: 15054
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  81652 size: 13376
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  81656 size: 13376
 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: 127872 size: 15054
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 127876 size: 15054
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  42638 size: 11805
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  42642 size: 11805
 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:  81652 size: 13376
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  81656 size: 13376
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 11937
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 11937
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 179512 size: 15553
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 179516 size: 15553
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 179512 size: 15553
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 179516 size: 15553
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  42638 size: 11805
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  42642 size: 11805
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 11937
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 11937
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 179512 size: 15553
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 179516 size: 15553
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 127872 size: 15054
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 127876 size: 15054
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 11937
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 11937
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 11937
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 11937
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 179512 size: 15553
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 179516 size: 15553
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  81652 size: 13376
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  81656 size: 13376
 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: 127872 size: 15054
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos: 127876 size: 15054
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  42638 size: 11805
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  42642 size: 11805
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-mpeg4-qpel b/tests/ref/seek/vsynth_lena-mpeg4-qpel
index cd6eaf0..cf5da07 100644
--- a/tests/ref/seek/vsynth_lena-mpeg4-qpel
+++ b/tests/ref/seek/vsynth_lena-mpeg4-qpel
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 11938
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 11938
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 11938
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 11938
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141526 size: 15554
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141530 size: 15554
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  64110 size: 13377
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  64114 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: 100336 size: 15055
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 100340 size: 15055
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  32836 size: 11806
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  32840 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:  64110 size: 13377
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  64114 size: 13377
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 11938
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 11938
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141526 size: 15554
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141530 size: 15554
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141526 size: 15554
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141530 size: 15554
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  32836 size: 11806
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  32840 size: 11806
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 11938
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 11938
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141526 size: 15554
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141530 size: 15554
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 100336 size: 15055
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 100340 size: 15055
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 11938
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 11938
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 11938
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 11938
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141526 size: 15554
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 141530 size: 15554
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  64110 size: 13377
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  64114 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: 100336 size: 15055
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 100340 size: 15055
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  64110 size: 13377
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos:  64114 size: 13377
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-mpeg4-qprd b/tests/ref/seek/vsynth_lena-mpeg4-qprd
index 74aee79..b92e3d2 100644
--- a/tests/ref/seek/vsynth_lena-mpeg4-qprd
+++ b/tests/ref/seek/vsynth_lena-mpeg4-qprd
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14873
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 14873
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14873
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 14873
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211030 size: 14638
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211034 size: 14638
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 150654 size: 14502
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 150658 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: 180778 size: 14371
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 180782 size: 14371
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  93024 size: 29366
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  93028 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: 150654 size: 14502
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 150658 size: 14502
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14873
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 14873
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211030 size: 14638
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211034 size: 14638
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211030 size: 14638
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211034 size: 14638
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  93024 size: 29366
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  93028 size: 29366
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14873
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 14873
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211030 size: 14638
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211034 size: 14638
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 180778 size: 14371
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 180782 size: 14371
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14873
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 14873
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14873
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 14873
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211030 size: 14638
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 211034 size: 14638
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 150654 size: 14502
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 150658 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: 180778 size: 14371
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 180782 size: 14371
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 150654 size: 14502
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 150658 size: 14502
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-mpeg4-rc b/tests/ref/seek/vsynth_lena-mpeg4-rc
index 6bcfd48..e1994af 100644
--- a/tests/ref/seek/vsynth_lena-mpeg4-rc
+++ b/tests/ref/seek/vsynth_lena-mpeg4-rc
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 15766
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 15766
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 15766
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 15766
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207950 size: 13826
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207954 size: 13826
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 153784 size: 13377
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 153788 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: 180946 size: 13326
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 180950 size: 13326
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  94574 size: 32807
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  94578 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: 153784 size: 13377
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 153788 size: 13377
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 15766
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 15766
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207950 size: 13826
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207954 size: 13826
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207950 size: 13826
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207954 size: 13826
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  94574 size: 32807
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  94578 size: 32807
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 15766
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 15766
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207950 size: 13826
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207954 size: 13826
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 180946 size: 13326
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 180950 size: 13326
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 15766
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 15766
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 15766
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 15766
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207950 size: 13826
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 207954 size: 13826
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 153784 size: 13377
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 153788 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: 180946 size: 13326
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 180950 size: 13326
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 153784 size: 13377
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 153788 size: 13377
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-mpeg4-thread b/tests/ref/seek/vsynth_lena-mpeg4-thread
index ca849f3..287b96d 100644
--- a/tests/ref/seek/vsynth_lena-mpeg4-thread
+++ b/tests/ref/seek/vsynth_lena-mpeg4-thread
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14874
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 14874
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14874
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 14874
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228186 size: 16323
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228190 size: 16323
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 162156 size: 16462
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 162160 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: 195330 size: 16153
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 195334 size: 16153
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  97832 size: 33332
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  97836 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: 162156 size: 16462
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 162160 size: 16462
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14874
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 14874
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228186 size: 16323
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228190 size: 16323
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228186 size: 16323
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228190 size: 16323
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  97832 size: 33332
+ret: 0         st: 0 flags:1 dts: 0.400000 pts: NOPTS    pos:  97836 size: 33332
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14874
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 14874
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228186 size: 16323
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228190 size: 16323
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 195330 size: 16153
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 195334 size: 16153
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14874
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 14874
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5648 size: 14874
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: NOPTS    pos:   5652 size: 14874
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228186 size: 16323
+ret: 0         st: 0 flags:1 dts: 1.840000 pts: NOPTS    pos: 228190 size: 16323
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 162156 size: 16462
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 162160 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: 195330 size: 16153
+ret: 0         st: 0 flags:1 dts: 1.360000 pts: NOPTS    pos: 195334 size: 16153
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 162156 size: 16462
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: NOPTS    pos: 162160 size: 16462
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-msmpeg4 b/tests/ref/seek/vsynth_lena-msmpeg4
index e096f76..0bb9f75 100644
--- a/tests/ref/seek/vsynth_lena-msmpeg4
+++ b/tests/ref/seek/vsynth_lena-msmpeg4
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8637
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8637
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  82508 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  82512 size: 10783
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  53846 size:  9624
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  53850 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:  82508 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  82512 size: 10783
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29388 size:  8502
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29392 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:  53846 size:  9624
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  53850 size:  9624
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8637
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114256 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114260 size: 11180
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114256 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114260 size: 11180
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29388 size:  8502
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29392 size:  8502
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8637
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114256 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114260 size: 11180
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  82508 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  82512 size: 10783
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8637
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8637
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8637
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114256 size: 11180
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 114260 size: 11180
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  53846 size:  9624
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  53850 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:  82508 size: 10783
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  82512 size: 10783
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29388 size:  8502
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29392 size:  8502
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-msmpeg4v2 b/tests/ref/seek/vsynth_lena-msmpeg4v2
index 00a175d..27ed0ed 100644
--- a/tests/ref/seek/vsynth_lena-msmpeg4v2
+++ b/tests/ref/seek/vsynth_lena-msmpeg4v2
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9003
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  9003
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9003
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  9003
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83870 size: 11165
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83874 size: 11165
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54778 size: 10010
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54782 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:  83870 size: 11165
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83874 size: 11165
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29770 size:  8869
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29774 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:  54778 size: 10010
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54782 size: 10010
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9003
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  9003
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116112 size: 11578
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116116 size: 11578
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116112 size: 11578
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116116 size: 11578
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29770 size:  8869
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29774 size:  8869
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9003
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  9003
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116112 size: 11578
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116116 size: 11578
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83870 size: 11165
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83874 size: 11165
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9003
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  9003
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  9003
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  9003
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116112 size: 11578
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116116 size: 11578
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54778 size: 10010
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54782 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:  83870 size: 11165
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83874 size: 11165
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29770 size:  8869
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29774 size:  8869
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-rgb b/tests/ref/seek/vsynth_lena-rgb
index 91f7260..8173ca9 100644
--- a/tests/ref/seek/vsynth_lena-rgb
+++ b/tests/ref/seek/vsynth_lena-rgb
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:304128
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:304128
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:304128
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:304128
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos:14300040 size:304128
+ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos:14300044 size:304128
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:6088368 size:304128
+ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:6088372 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:11258680 size:304128
+ret: 0         st: 0 flags:1 dts: 1.480000 pts: 1.480000 pos:11258684 size:304128
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos:2742872 size:304128
+ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos:2742876 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:7913184 size:304128
+ret: 0         st: 0 flags:1 dts: 1.040000 pts: 1.040000 pos:7913188 size:304128
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:304128
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:304128
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:14908312 size:304128
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:14908316 size:304128
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:13083496 size:304128
+ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:13083500 size:304128
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:4871824 size:304128
+ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:4871828 size:304128
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:304128
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:304128
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:14908312 size:304128
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:14908316 size:304128
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:10042136 size:304128
+ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:10042140 size:304128
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos:1526328 size:304128
+ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos:1526332 size:304128
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:304128
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:304128
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:14908312 size:304128
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:14908316 size:304128
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:6696640 size:304128
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:6696644 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:11866952 size:304128
+ret: 0         st: 0 flags:1 dts: 1.560000 pts: 1.560000 pos:11866956 size:304128
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:3655280 size:304128
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:3655284 size:304128
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-snow b/tests/ref/seek/vsynth_lena-snow
index d8f5aae..9d4ada6 100644
--- a/tests/ref/seek/vsynth_lena-snow
+++ b/tests/ref/seek/vsynth_lena-snow
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  3035
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  3035
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  3035
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  3035
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  39714 size:  3640
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  39718 size:  3640
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  27434 size:  3494
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  27438 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:  39714 size:  3640
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  39718 size:  3640
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  16124 size:  3244
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  16128 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:  27434 size:  3494
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  27438 size:  3494
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  3035
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  3035
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:  52604 size:  3582
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:  52608 size:  3582
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:  52604 size:  3582
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:  52608 size:  3582
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  16124 size:  3244
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  16128 size:  3244
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  3035
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  3035
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:  52604 size:  3582
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:  52608 size:  3582
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  39714 size:  3640
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  39718 size:  3640
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  3035
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  3035
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  3035
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  3035
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:  52604 size:  3582
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:  52608 size:  3582
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  27434 size:  3494
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  27438 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:  39714 size:  3640
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  39718 size:  3640
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  16124 size:  3244
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  16128 size:  3244
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-snow-ll b/tests/ref/seek/vsynth_lena-snow-ll
index 95a4a79..039db70 100644
--- a/tests/ref/seek/vsynth_lena-snow-ll
+++ b/tests/ref/seek/vsynth_lena-snow-ll
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 72476
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 72476
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 72476
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 72476
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:1902788 size: 78837
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:1902792 size: 78837
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1239090 size: 74994
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1239094 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:1902788 size: 78837
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:1902792 size: 78837
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 605628 size: 71059
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 605632 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:1239090 size: 74994
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1239094 size: 74994
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 72476
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 72476
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:2585614 size: 79731
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:2585618 size: 79731
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:2585614 size: 79731
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:2585618 size: 79731
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 605628 size: 71059
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 605632 size: 71059
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 72476
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 72476
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:2585614 size: 79731
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:2585618 size: 79731
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:1902788 size: 78837
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:1902792 size: 78837
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 72476
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 72476
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size: 72476
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size: 72476
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:2585614 size: 79731
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos:2585618 size: 79731
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1239090 size: 74994
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:1239094 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:1902788 size: 78837
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:1902792 size: 78837
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 605628 size: 71059
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos: 605632 size: 71059
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-wmv1 b/tests/ref/seek/vsynth_lena-wmv1
index 0f073b2..125e6cd 100644
--- a/tests/ref/seek/vsynth_lena-wmv1
+++ b/tests/ref/seek/vsynth_lena-wmv1
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8990
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8990
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8990
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8990
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83742 size: 11099
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83746 size: 11099
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54758 size:  9931
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54762 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:  83742 size: 11099
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83746 size: 11099
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29794 size:  8796
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29798 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:  54758 size:  9931
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54762 size:  9931
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8990
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8990
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 115806 size: 11486
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 115810 size: 11486
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 115806 size: 11486
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 115810 size: 11486
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29794 size:  8796
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29798 size:  8796
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8990
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8990
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 115806 size: 11486
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 115810 size: 11486
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83742 size: 11099
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83746 size: 11099
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8990
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8990
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:  8990
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8990
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 115806 size: 11486
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 115810 size: 11486
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54758 size:  9931
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54762 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:  83742 size: 11099
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83746 size: 11099
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29794 size:  8796
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29798 size:  8796
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-wmv2 b/tests/ref/seek/vsynth_lena-wmv2
index a29f0d4..ffa5762 100644
--- a/tests/ref/seek/vsynth_lena-wmv2
+++ b/tests/ref/seek/vsynth_lena-wmv2
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8917
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size:  8917
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8917
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size:  8917
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83764 size: 11169
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83768 size: 11169
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54534 size:  9989
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54538 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:  83764 size: 11169
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83768 size: 11169
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29588 size:  8839
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29592 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:  54534 size:  9989
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54538 size:  9989
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8917
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size:  8917
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116066 size: 11554
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116070 size: 11554
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116066 size: 11554
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116070 size: 11554
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29588 size:  8839
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29592 size:  8839
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8917
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size:  8917
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116066 size: 11554
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116070 size: 11554
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83764 size: 11169
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83768 size: 11169
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8917
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size:  8917
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:  8917
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5656 size:  8917
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116066 size: 11554
+ret: 0         st: 0 flags:1 dts: 1.920000 pts: 1.920000 pos: 116070 size: 11554
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54534 size:  9989
+ret: 0         st: 0 flags:1 dts: 0.960000 pts: 0.960000 pos:  54538 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:  83764 size: 11169
+ret: 0         st: 0 flags:1 dts: 1.440000 pts: 1.440000 pos:  83768 size: 11169
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29588 size:  8839
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:  29592 size:  8839
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/seek/vsynth_lena-yuv b/tests/ref/seek/vsynth_lena-yuv
index d440761..f899d7f 100644
--- a/tests/ref/seek/vsynth_lena-yuv
+++ b/tests/ref/seek/vsynth_lena-yuv
@@ -1,46 +1,46 @@
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:152064
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:152064
 ret: 0         st:-1 flags:0  ts:-1.000000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:152064
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:152064
 ret: 0         st:-1 flags:1  ts: 1.894167
-ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos:7153032 size:152064
+ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.880000 pos:7153036 size:152064
 ret: 0         st: 0 flags:0  ts: 0.800000
-ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:3047088 size:152064
+ret: 0         st: 0 flags:1 dts: 0.800000 pts: 0.800000 pos:3047092 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:5632312 size:152064
+ret: 0         st: 0 flags:1 dts: 1.480000 pts: 1.480000 pos:5632316 size:152064
 ret: 0         st: 0 flags:0  ts: 0.360000
-ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos:1374296 size:152064
+ret: 0         st: 0 flags:1 dts: 0.360000 pts: 0.360000 pos:1374300 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:3959520 size:152064
+ret: 0         st: 0 flags:1 dts: 1.040000 pts: 1.040000 pos:3959524 size:152064
 ret: 0         st: 0 flags:0  ts:-0.040000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:152064
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:152064
 ret: 0         st: 0 flags:1  ts: 2.840000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:7457176 size:152064
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:7457180 size:152064
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:6544744 size:152064
+ret: 0         st: 0 flags:1 dts: 1.720000 pts: 1.720000 pos:6544748 size:152064
 ret: 0         st:-1 flags:1  ts: 0.624171
-ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:2438800 size:152064
+ret: 0         st: 0 flags:1 dts: 0.640000 pts: 0.640000 pos:2438804 size:152064
 ret: 0         st: 0 flags:0  ts:-0.480000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:152064
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:152064
 ret: 0         st: 0 flags:1  ts: 2.400000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:7457176 size:152064
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:7457180 size:152064
 ret: 0         st:-1 flags:0  ts: 1.306672
-ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:5024024 size:152064
+ret: 0         st: 0 flags:1 dts: 1.320000 pts: 1.320000 pos:5024028 size:152064
 ret: 0         st:-1 flags:1  ts: 0.200839
-ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos: 766008 size:152064
+ret: 0         st: 0 flags:1 dts: 0.200000 pts: 0.200000 pos: 766012 size:152064
 ret: 0         st: 0 flags:0  ts:-0.920000
-ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5648 size:152064
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   5652 size:152064
 ret: 0         st: 0 flags:1  ts: 2.000000
-ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:7457176 size:152064
+ret: 0         st: 0 flags:1 dts: 1.960000 pts: 1.960000 pos:7457180 size:152064
 ret: 0         st:-1 flags:0  ts: 0.883340
-ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:3351232 size:152064
+ret: 0         st: 0 flags:1 dts: 0.880000 pts: 0.880000 pos:3351236 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:5936456 size:152064
+ret: 0         st: 0 flags:1 dts: 1.560000 pts: 1.560000 pos:5936460 size:152064
 ret: 0         st:-1 flags:0  ts: 0.460008
-ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:1830512 size:152064
+ret: 0         st: 0 flags:1 dts: 0.480000 pts: 0.480000 pos:1830516 size:152064
 ret:-1         st:-1 flags:1  ts:-0.645825
diff --git a/tests/ref/vsynth/vsynth1-amv b/tests/ref/vsynth/vsynth1-amv
index 38a34b2..e4652c5 100644
--- a/tests/ref/vsynth/vsynth1-amv
+++ b/tests/ref/vsynth/vsynth1-amv
@@ -1,4 +1,4 @@
-e3e6dcf69be5c598b4eae901034a80e2 *tests/data/fate/vsynth1-amv.avi
-1365496 tests/data/fate/vsynth1-amv.avi
+9e155fcedb3b853876e9ea4233971803 *tests/data/fate/vsynth1-amv.avi
+1365500 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
index 445197a..99ce220 100644
--- a/tests/ref/vsynth/vsynth1-asv1
+++ b/tests/ref/vsynth/vsynth1-asv1
@@ -1,4 +1,4 @@
-f446db5dfd6bcc14378bca9406e39adb *tests/data/fate/vsynth1-asv1.avi
-1298616 tests/data/fate/vsynth1-asv1.avi
+8f1ab10246da351b6be88dd74319f76e *tests/data/fate/vsynth1-asv1.avi
+1298620 tests/data/fate/vsynth1-asv1.avi
 a4f95c58e8b9258da52b9d09153b1078 *tests/data/fate/vsynth1-asv1.out.rawvideo
 stddev:   11.89 PSNR: 26.62 MAXDIFF:  132 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-asv2 b/tests/ref/vsynth/vsynth1-asv2
index 225712e..2932147 100644
--- a/tests/ref/vsynth/vsynth1-asv2
+++ b/tests/ref/vsynth/vsynth1-asv2
@@ -1,4 +1,4 @@
-06b7b65686a1eb03d43f25e179c03872 *tests/data/fate/vsynth1-asv2.avi
-1434408 tests/data/fate/vsynth1-asv2.avi
+ea142aefed8e72a2e39cdef350c315ed *tests/data/fate/vsynth1-asv2.avi
+1434412 tests/data/fate/vsynth1-asv2.avi
 cb1f5560005800e889bfbb36cdc9fc40 *tests/data/fate/vsynth1-asv2.out.rawvideo
 stddev:    8.36 PSNR: 29.68 MAXDIFF:   58 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-cljr b/tests/ref/vsynth/vsynth1-cljr
index 58191a6..4260d9e 100644
--- a/tests/ref/vsynth/vsynth1-cljr
+++ b/tests/ref/vsynth/vsynth1-cljr
@@ -1,4 +1,4 @@
-d04d90410c1936ec545e049cb7f0d1e9 *tests/data/fate/vsynth1-cljr.avi
-5075648 tests/data/fate/vsynth1-cljr.avi
+085c6c83b0ef1ff6b3abd598f296e01e *tests/data/fate/vsynth1-cljr.avi
+5075652 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/vsynth/vsynth1-dnxhd-1080i b/tests/ref/vsynth/vsynth1-dnxhd-1080i
index f9b7e0e..28d55b6 100644
--- a/tests/ref/vsynth/vsynth1-dnxhd-1080i
+++ b/tests/ref/vsynth/vsynth1-dnxhd-1080i
@@ -1,4 +1,4 @@
-14f1ea20bbd3024ccbfd84c681888d07 *tests/data/fate/vsynth1-dnxhd-1080i.mov
+a0234e0a8516d958f423b119aa9e35c4 *tests/data/fate/vsynth1-dnxhd-1080i.mov
 3031911 tests/data/fate/vsynth1-dnxhd-1080i.mov
 a09132c6db44f415e831dcaa630a351b *tests/data/fate/vsynth1-dnxhd-1080i.out.rawvideo
 stddev:    6.29 PSNR: 32.15 MAXDIFF:   64 bytes:  7603200/   760320
diff --git a/tests/ref/vsynth/vsynth1-dnxhd-1080i-colr b/tests/ref/vsynth/vsynth1-dnxhd-1080i-colr
index 5971f33..16d8953 100644
--- a/tests/ref/vsynth/vsynth1-dnxhd-1080i-colr
+++ b/tests/ref/vsynth/vsynth1-dnxhd-1080i-colr
@@ -1,4 +1,4 @@
-b6fbfdfe7027fde6853930abad87eaab *tests/data/fate/vsynth1-dnxhd-1080i-colr.mov
+5fccdb16c0f14dea1b6b603bac90b97e *tests/data/fate/vsynth1-dnxhd-1080i-colr.mov
 3031929 tests/data/fate/vsynth1-dnxhd-1080i-colr.mov
 5835dff88cb84e83bbe70b5ed5edd5ab *tests/data/fate/vsynth1-dnxhd-1080i-colr.out.rawvideo
 stddev:    5.79 PSNR: 32.87 MAXDIFF:   56 bytes:  7603200/   760320
diff --git a/tests/ref/vsynth/vsynth1-ffv1 b/tests/ref/vsynth/vsynth1-ffv1
index dd11996..71fb045 100644
--- a/tests/ref/vsynth/vsynth1-ffv1
+++ b/tests/ref/vsynth/vsynth1-ffv1
@@ -1,4 +1,4 @@
-7563e82e673db8ca60e79e7e725e174f *tests/data/fate/vsynth1-ffv1.avi
-2691264 tests/data/fate/vsynth1-ffv1.avi
+85c421168aab0ca8e24f71da504701af *tests/data/fate/vsynth1-ffv1.avi
+2691268 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-ffv1.0 b/tests/ref/vsynth/vsynth1-ffv1.0
index 346bde8..0905303 100644
--- a/tests/ref/vsynth/vsynth1-ffv1.0
+++ b/tests/ref/vsynth/vsynth1-ffv1.0
@@ -1,4 +1,4 @@
-b9ce2f9781613d3380f7036d619af87b *tests/data/fate/vsynth1-ffv1.0.avi
-2655364 tests/data/fate/vsynth1-ffv1.0.avi
+36011c9a2b288fb04bf6c520371646d4 *tests/data/fate/vsynth1-ffv1.0.avi
+2655368 tests/data/fate/vsynth1-ffv1.0.avi
 c5ccac874dbf808e9088bc3107860042 *tests/data/fate/vsynth1-ffv1.0.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
index a8b9e41..c982fb9 100644
--- a/tests/ref/vsynth/vsynth1-ffvhuff
+++ b/tests/ref/vsynth/vsynth1-ffvhuff
@@ -1,4 +1,4 @@
-936c7cb29dc7b12a5db8a0217b3486b9 *tests/data/fate/vsynth1-ffvhuff.avi
-6809210 tests/data/fate/vsynth1-ffvhuff.avi
+be797b3c97bea941c5df720b44b779d4 *tests/data/fate/vsynth1-ffvhuff.avi
+6809214 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/vsynth/vsynth1-ffvhuff420p12 b/tests/ref/vsynth/vsynth1-ffvhuff420p12
index 334c846..0d80bd6 100644
--- a/tests/ref/vsynth/vsynth1-ffvhuff420p12
+++ b/tests/ref/vsynth/vsynth1-ffvhuff420p12
@@ -1,4 +1,4 @@
-571a999f4f0e5895be97d9240e036695 *tests/data/fate/vsynth1-ffvhuff420p12.avi
-14205352 tests/data/fate/vsynth1-ffvhuff420p12.avi
+866485c954242232878e40f0389790dd *tests/data/fate/vsynth1-ffvhuff420p12.avi
+14205356 tests/data/fate/vsynth1-ffvhuff420p12.avi
 b48f32c140712e8c7bf81cfdd66ae312 *tests/data/fate/vsynth1-ffvhuff420p12.out.rawvideo
 stddev:    0.68 PSNR: 51.47 MAXDIFF:    1 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-ffvhuff422p10left b/tests/ref/vsynth/vsynth1-ffvhuff422p10left
index 0d88cdd..25c2ded 100644
--- a/tests/ref/vsynth/vsynth1-ffvhuff422p10left
+++ b/tests/ref/vsynth/vsynth1-ffvhuff422p10left
@@ -1,4 +1,4 @@
-43705266ad32d9b98feb54d59c05b83e *tests/data/fate/vsynth1-ffvhuff422p10left.avi
-13860680 tests/data/fate/vsynth1-ffvhuff422p10left.avi
+d29edc22816fd865d3075ad6c1eaaffa *tests/data/fate/vsynth1-ffvhuff422p10left.avi
+13860684 tests/data/fate/vsynth1-ffvhuff422p10left.avi
 c31e6caada921ffa3daad3432ef3b754 *tests/data/fate/vsynth1-ffvhuff422p10left.out.rawvideo
 stddev:    1.85 PSNR: 42.78 MAXDIFF:   29 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-ffvhuff444 b/tests/ref/vsynth/vsynth1-ffvhuff444
index 7c518f4..978a0af 100644
--- a/tests/ref/vsynth/vsynth1-ffvhuff444
+++ b/tests/ref/vsynth/vsynth1-ffvhuff444
@@ -1,4 +1,4 @@
-962b03019d92658356eb7cdfad857d08 *tests/data/fate/vsynth1-ffvhuff444.avi
-11712338 tests/data/fate/vsynth1-ffvhuff444.avi
+b013f0933ef27f7e23a62a13226e0510 *tests/data/fate/vsynth1-ffvhuff444.avi
+11712342 tests/data/fate/vsynth1-ffvhuff444.avi
 10fb42f1abf40a289c3edafc0390482c *tests/data/fate/vsynth1-ffvhuff444.out.rawvideo
 stddev:    2.67 PSNR: 39.60 MAXDIFF:   43 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-ffvhuff444p16 b/tests/ref/vsynth/vsynth1-ffvhuff444p16
index 76acffd..f3a6d7d 100644
--- a/tests/ref/vsynth/vsynth1-ffvhuff444p16
+++ b/tests/ref/vsynth/vsynth1-ffvhuff444p16
@@ -1,4 +1,4 @@
-9d7ab6d77fb4004512246c2f93f93c29 *tests/data/fate/vsynth1-ffvhuff444p16.avi
-24706272 tests/data/fate/vsynth1-ffvhuff444p16.avi
+2f780c186d2549aa257511a951918617 *tests/data/fate/vsynth1-ffvhuff444p16.avi
+24706276 tests/data/fate/vsynth1-ffvhuff444p16.avi
 ee8379fa217dfd023de3aa6974a14d1e *tests/data/fate/vsynth1-ffvhuff444p16.out.rawvideo
 stddev:    2.66 PSNR: 39.62 MAXDIFF:   44 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-h261 b/tests/ref/vsynth/vsynth1-h261
index 52372d8..4ba2a44 100644
--- a/tests/ref/vsynth/vsynth1-h261
+++ b/tests/ref/vsynth/vsynth1-h261
@@ -1,4 +1,4 @@
-364cc6703e90df30631dad52d1d9c909 *tests/data/fate/vsynth1-h261.avi
-707546 tests/data/fate/vsynth1-h261.avi
+be41f18a8c3120b730270a9ec45545aa *tests/data/fate/vsynth1-h261.avi
+707550 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-h261-trellis b/tests/ref/vsynth/vsynth1-h261-trellis
index 23fa231..bf74a24 100644
--- a/tests/ref/vsynth/vsynth1-h261-trellis
+++ b/tests/ref/vsynth/vsynth1-h261-trellis
@@ -1,4 +1,4 @@
-a61e040bbbfc6875e6842ac066a5285b *tests/data/fate/vsynth1-h261-trellis.avi
-655412 tests/data/fate/vsynth1-h261-trellis.avi
+707aac692b7478d2312a87b09228e437 *tests/data/fate/vsynth1-h261-trellis.avi
+655416 tests/data/fate/vsynth1-h261-trellis.avi
 70ceba944548ba680b1101c91707ea25 *tests/data/fate/vsynth1-h261-trellis.out.rawvideo
 stddev:    8.75 PSNR: 29.28 MAXDIFF:   90 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-h263 b/tests/ref/vsynth/vsynth1-h263
index a07c597..53885bf 100644
--- a/tests/ref/vsynth/vsynth1-h263
+++ b/tests/ref/vsynth/vsynth1-h263
@@ -1,4 +1,4 @@
-3975fd5e232267fab6a5f8a5e095e3f9 *tests/data/fate/vsynth1-h263.avi
-659674 tests/data/fate/vsynth1-h263.avi
+0d94f4a01b959b21de8d351b092d3fd8 *tests/data/fate/vsynth1-h263.avi
+659678 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
index ecb7a9a..b7a267a 100644
--- a/tests/ref/vsynth/vsynth1-h263-obmc
+++ b/tests/ref/vsynth/vsynth1-h263-obmc
@@ -1,4 +1,4 @@
-d66bfd3b2cd4bc59d8ec218391294266 *tests/data/fate/vsynth1-h263-obmc.avi
-657316 tests/data/fate/vsynth1-h263-obmc.avi
+7dec64380f375e5118b66f3baaaa1e24 *tests/data/fate/vsynth1-h263-obmc.avi
+657320 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
index b96913d..ac3a660 100644
--- a/tests/ref/vsynth/vsynth1-h263p
+++ b/tests/ref/vsynth/vsynth1-h263p
@@ -1,4 +1,4 @@
-15a47620dcf88daaa71d4c679f620b47 *tests/data/fate/vsynth1-h263p.avi
-2328362 tests/data/fate/vsynth1-h263p.avi
+7fbb9a42f7047643fa4e1d533bc61f57 *tests/data/fate/vsynth1-h263p.avi
+2328366 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
index f747d9d..6bf7944 100644
--- a/tests/ref/vsynth/vsynth1-huffyuv
+++ b/tests/ref/vsynth/vsynth1-huffyuv
@@ -1,4 +1,4 @@
-b48b81b3bdd4e24834f9ada6f567b94e *tests/data/fate/vsynth1-huffyuv.avi
-8876470 tests/data/fate/vsynth1-huffyuv.avi
+9a89f73cb2e305c15dda99c99c39b9d1 *tests/data/fate/vsynth1-huffyuv.avi
+8876474 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-huffyuvbgr24 b/tests/ref/vsynth/vsynth1-huffyuvbgr24
index c40ad0f..e4e7723 100644
--- a/tests/ref/vsynth/vsynth1-huffyuvbgr24
+++ b/tests/ref/vsynth/vsynth1-huffyuvbgr24
@@ -1,4 +1,4 @@
-62748f420e76a0b26886f432074f89a1 *tests/data/fate/vsynth1-huffyuvbgr24.avi
-13196986 tests/data/fate/vsynth1-huffyuvbgr24.avi
+54032b56a1727c1ad940d8c66d65169e *tests/data/fate/vsynth1-huffyuvbgr24.avi
+13196990 tests/data/fate/vsynth1-huffyuvbgr24.avi
 49c03ab1b73b7cd3cabc3c77a9479c9e *tests/data/fate/vsynth1-huffyuvbgr24.out.rawvideo
 stddev:    3.16 PSNR: 38.12 MAXDIFF:   50 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-huffyuvbgra b/tests/ref/vsynth/vsynth1-huffyuvbgra
index 8578b81..f4ea59b 100644
--- a/tests/ref/vsynth/vsynth1-huffyuvbgra
+++ b/tests/ref/vsynth/vsynth1-huffyuvbgra
@@ -1,4 +1,4 @@
-0a441061598152cd44ddc308076671c3 *tests/data/fate/vsynth1-huffyuvbgra.avi
-14464166 tests/data/fate/vsynth1-huffyuvbgra.avi
+98e1f0bd1734cfb0eb0b442259a7de32 *tests/data/fate/vsynth1-huffyuvbgra.avi
+14464170 tests/data/fate/vsynth1-huffyuvbgra.avi
 49c03ab1b73b7cd3cabc3c77a9479c9e *tests/data/fate/vsynth1-huffyuvbgra.out.rawvideo
 stddev:    3.16 PSNR: 38.12 MAXDIFF:   50 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-jpeg2000 b/tests/ref/vsynth/vsynth1-jpeg2000
index a6a3e10..d169cf6 100644
--- a/tests/ref/vsynth/vsynth1-jpeg2000
+++ b/tests/ref/vsynth/vsynth1-jpeg2000
@@ -1,4 +1,4 @@
-b526a22fcc4f710da181617ad06ec523 *tests/data/fate/vsynth1-jpeg2000.avi
-2306902 tests/data/fate/vsynth1-jpeg2000.avi
+ed9c45dc090a03c2eb9c35cf76e4d914 *tests/data/fate/vsynth1-jpeg2000.avi
+2306906 tests/data/fate/vsynth1-jpeg2000.avi
 1774b621bd92a53a24712cb77e9f0b28 *tests/data/fate/vsynth1-jpeg2000.out.rawvideo
 stddev:    5.37 PSNR: 33.52 MAXDIFF:   63 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-jpeg2000-97 b/tests/ref/vsynth/vsynth1-jpeg2000-97
index cd56149..a8e9bf8 100644
--- a/tests/ref/vsynth/vsynth1-jpeg2000-97
+++ b/tests/ref/vsynth/vsynth1-jpeg2000-97
@@ -1,4 +1,4 @@
-397690bc9f6202c77ce3810640762ca3 *tests/data/fate/vsynth1-jpeg2000-97.avi
-2243132 tests/data/fate/vsynth1-jpeg2000-97.avi
+dfb35e733795195c6519ecc37e953931 *tests/data/fate/vsynth1-jpeg2000-97.avi
+2243136 tests/data/fate/vsynth1-jpeg2000-97.avi
 e1a095b40d7f6440f6c46f2995c4759c *tests/data/fate/vsynth1-jpeg2000-97.out.rawvideo
 stddev:    6.23 PSNR: 32.23 MAXDIFF:   75 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-jpegls b/tests/ref/vsynth/vsynth1-jpegls
index 2e44308..8737249 100644
--- a/tests/ref/vsynth/vsynth1-jpegls
+++ b/tests/ref/vsynth/vsynth1-jpegls
@@ -1,4 +1,4 @@
-424107c7919713b422b8e982ae3e4319 *tests/data/fate/vsynth1-jpegls.avi
-9089800 tests/data/fate/vsynth1-jpegls.avi
+29cea344136c89ef4e9da29888f7bf34 *tests/data/fate/vsynth1-jpegls.avi
+9089804 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
index 99bfade..4e38aee 100644
--- a/tests/ref/vsynth/vsynth1-ljpeg
+++ b/tests/ref/vsynth/vsynth1-ljpeg
@@ -1,4 +1,4 @@
-24d72a5b4c0d3a49a30098369d56b1cc *tests/data/fate/vsynth1-ljpeg.avi
-6309478 tests/data/fate/vsynth1-ljpeg.avi
+a9c92718692c7eb3fdce5041a6a21eb6 *tests/data/fate/vsynth1-ljpeg.avi
+6309482 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
index 63ad240..11de020 100644
--- a/tests/ref/vsynth/vsynth1-mjpeg
+++ b/tests/ref/vsynth/vsynth1-mjpeg
@@ -1,4 +1,4 @@
-c14acfb3472919caa50ed90125ab33a9 *tests/data/fate/vsynth1-mjpeg.avi
-1515902 tests/data/fate/vsynth1-mjpeg.avi
+9ff18b19d12bb9bb2ed434a79f212888 *tests/data/fate/vsynth1-mjpeg.avi
+1515906 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
index 3356dd3..bd760a1 100644
--- a/tests/ref/vsynth/vsynth1-mjpeg-422
+++ b/tests/ref/vsynth/vsynth1-mjpeg-422
@@ -1,4 +1,4 @@
-bcd2370d76f32b9eed7842685a04f29f *tests/data/fate/vsynth1-mjpeg-422.avi
-1756300 tests/data/fate/vsynth1-mjpeg-422.avi
+3b19da06ffe23cb804bca7a9a86eb3d5 *tests/data/fate/vsynth1-mjpeg-422.avi
+1756304 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
index 5ebf895..42a9be3 100644
--- a/tests/ref/vsynth/vsynth1-mjpeg-444
+++ b/tests/ref/vsynth/vsynth1-mjpeg-444
@@ -1,4 +1,4 @@
-f611f316df9b6890d6dcd3379691c36e *tests/data/fate/vsynth1-mjpeg-444.avi
-1989780 tests/data/fate/vsynth1-mjpeg-444.avi
+9591b754ca151f3802738840fa5c26c0 *tests/data/fate/vsynth1-mjpeg-444.avi
+1989784 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/vsynth/vsynth1-mjpeg-trell b/tests/ref/vsynth/vsynth1-mjpeg-trell
new file mode 100644
index 0000000..b97efcb
--- /dev/null
+++ b/tests/ref/vsynth/vsynth1-mjpeg-trell
@@ -0,0 +1,4 @@
+03d14b3db6232f46c0d931477801a7a6 *tests/data/fate/vsynth1-mjpeg-trell.avi
+1454308 tests/data/fate/vsynth1-mjpeg-trell.avi
+218d4dc8086fdef15d5382e6ba97df0b *tests/data/fate/vsynth1-mjpeg-trell.out.rawvideo
+stddev:    7.71 PSNR: 30.39 MAXDIFF:   62 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-mpeg4-adap b/tests/ref/vsynth/vsynth1-mpeg4-adap
index a9d11b7..e6bd6a5 100644
--- a/tests/ref/vsynth/vsynth1-mpeg4-adap
+++ b/tests/ref/vsynth/vsynth1-mpeg4-adap
@@ -1,4 +1,4 @@
-82726c84fc7a0b464818bf6e83e0d2db *tests/data/fate/vsynth1-mpeg4-adap.avi
-403432 tests/data/fate/vsynth1-mpeg4-adap.avi
+f120f0bf976bb510c5b5305fe7d8159a *tests/data/fate/vsynth1-mpeg4-adap.avi
+403436 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
index d1d921f..f450779 100644
--- a/tests/ref/vsynth/vsynth1-mpeg4-adv
+++ b/tests/ref/vsynth/vsynth1-mpeg4-adv
@@ -1,4 +1,4 @@
-8f6e6b9a8242a2342edab58c00900841 *tests/data/fate/vsynth1-mpeg4-adv.avi
-589704 tests/data/fate/vsynth1-mpeg4-adv.avi
+0700d773f269babdaea4c6c71a3d7876 *tests/data/fate/vsynth1-mpeg4-adv.avi
+589708 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
index 3aafd4e..b3b8d66 100644
--- a/tests/ref/vsynth/vsynth1-mpeg4-error
+++ b/tests/ref/vsynth/vsynth1-mpeg4-error
@@ -1,4 +1,4 @@
-6ea634d8b179098a3ec7f05af1e4a98d *tests/data/fate/vsynth1-mpeg4-error.avi
-752346 tests/data/fate/vsynth1-mpeg4-error.avi
+d23ad508e15bf6af8de8799c59acd6dc *tests/data/fate/vsynth1-mpeg4-error.avi
+752350 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
index a18eabc..94b5b4f 100644
--- a/tests/ref/vsynth/vsynth1-mpeg4-nr
+++ b/tests/ref/vsynth/vsynth1-mpeg4-nr
@@ -1,4 +1,4 @@
-953407e0e1fd1c99e4b320065f69ad81 *tests/data/fate/vsynth1-mpeg4-nr.avi
-675452 tests/data/fate/vsynth1-mpeg4-nr.avi
+793b77835fe8073bba19a22e9039d6e1 *tests/data/fate/vsynth1-mpeg4-nr.avi
+675456 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-nsse b/tests/ref/vsynth/vsynth1-mpeg4-nsse
index a6065f9..48cc851 100644
--- a/tests/ref/vsynth/vsynth1-mpeg4-nsse
+++ b/tests/ref/vsynth/vsynth1-mpeg4-nsse
@@ -1,4 +1,4 @@
-10fa4b9d835349220908b5ebde9a0e70 *tests/data/fate/vsynth1-mpeg4-nsse.avi
-886842 tests/data/fate/vsynth1-mpeg4-nsse.avi
+1c2eac81a7768afe8dba1df85e977aec *tests/data/fate/vsynth1-mpeg4-nsse.avi
+886846 tests/data/fate/vsynth1-mpeg4-nsse.avi
 a987cb2e49284ea83174e3a2c6527173 *tests/data/fate/vsynth1-mpeg4-nsse.out.rawvideo
 stddev:    6.00 PSNR: 32.57 MAXDIFF:   73 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-mpeg4-qpel b/tests/ref/vsynth/vsynth1-mpeg4-qpel
index ed53fed..f845542 100644
--- a/tests/ref/vsynth/vsynth1-mpeg4-qpel
+++ b/tests/ref/vsynth/vsynth1-mpeg4-qpel
@@ -1,4 +1,4 @@
-b49ff3a036fdb479404f80f1490c6330 *tests/data/fate/vsynth1-mpeg4-qpel.avi
-858680 tests/data/fate/vsynth1-mpeg4-qpel.avi
+cb55178feaf790db7bca758708f989dd *tests/data/fate/vsynth1-mpeg4-qpel.avi
+858684 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
index 307ff32..d5c75ab 100644
--- a/tests/ref/vsynth/vsynth1-mpeg4-qprd
+++ b/tests/ref/vsynth/vsynth1-mpeg4-qprd
@@ -1,4 +1,4 @@
-1bcc031a67149a9650d7efb56952c5fa *tests/data/fate/vsynth1-mpeg4-qprd.avi
-710672 tests/data/fate/vsynth1-mpeg4-qprd.avi
+14612d85cd7f77de7b5e6345240535ba *tests/data/fate/vsynth1-mpeg4-qprd.avi
+710676 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
index f41b458..5b1d7ff 100644
--- a/tests/ref/vsynth/vsynth1-mpeg4-rc
+++ b/tests/ref/vsynth/vsynth1-mpeg4-rc
@@ -1,4 +1,4 @@
-e9ff13628bd5bd138a44f4d4815d8d09 *tests/data/fate/vsynth1-mpeg4-rc.avi
-830494 tests/data/fate/vsynth1-mpeg4-rc.avi
+91c127f2acc04f51e0e62bcf0752e064 *tests/data/fate/vsynth1-mpeg4-rc.avi
+830498 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
index 581897c..6b69fb4 100644
--- a/tests/ref/vsynth/vsynth1-mpeg4-thread
+++ b/tests/ref/vsynth/vsynth1-mpeg4-thread
@@ -1,4 +1,4 @@
-fa47e87b4fac7ee7da58cf677d816567 *tests/data/fate/vsynth1-mpeg4-thread.avi
-774750 tests/data/fate/vsynth1-mpeg4-thread.avi
+369ace2f9613261af869efd9fbb3c149 *tests/data/fate/vsynth1-mpeg4-thread.avi
+774754 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
index 7c6b872..9b394d7 100644
--- a/tests/ref/vsynth/vsynth1-mpng
+++ b/tests/ref/vsynth/vsynth1-mpng
@@ -1,4 +1,4 @@
-a32e70b1079dff3af0fe1fc339fafce2 *tests/data/fate/vsynth1-mpng.avi
-12158276 tests/data/fate/vsynth1-mpng.avi
+6a27410a07ed1c5556e15b7a7c6a586d *tests/data/fate/vsynth1-mpng.avi
+12158280 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
index e0f3c2a..7ff4974 100644
--- a/tests/ref/vsynth/vsynth1-msmpeg4
+++ b/tests/ref/vsynth/vsynth1-msmpeg4
@@ -1,4 +1,4 @@
-391863936d129fef45d855dd0fcf5b8a *tests/data/fate/vsynth1-msmpeg4.avi
-624702 tests/data/fate/vsynth1-msmpeg4.avi
+3957ca57ac97f651c828ab00d8f0e088 *tests/data/fate/vsynth1-msmpeg4.avi
+624706 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
index 150bf30..514ca99 100644
--- a/tests/ref/vsynth/vsynth1-msmpeg4v2
+++ b/tests/ref/vsynth/vsynth1-msmpeg4v2
@@ -1,4 +1,4 @@
-a1f1ad51642bd8394ea9ad7646d91b85 *tests/data/fate/vsynth1-msmpeg4v2.avi
-623766 tests/data/fate/vsynth1-msmpeg4v2.avi
+d13c6aaf0d3842d3e50cc96574572f6f *tests/data/fate/vsynth1-msmpeg4v2.avi
+623770 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
index dd87a21..e7435a9 100644
--- a/tests/ref/vsynth/vsynth1-msvideo1
+++ b/tests/ref/vsynth/vsynth1-msvideo1
@@ -1,4 +1,4 @@
-e017b7844d81f70cdd6aaad479d9462b *tests/data/fate/vsynth1-msvideo1.avi
-2051892 tests/data/fate/vsynth1-msvideo1.avi
+41c8ec9813bb32831c4cf279677e631b *tests/data/fate/vsynth1-msvideo1.avi
+2051896 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-r210 b/tests/ref/vsynth/vsynth1-r210
index 477f1a5..e25b1de 100644
--- a/tests/ref/vsynth/vsynth1-r210
+++ b/tests/ref/vsynth/vsynth1-r210
@@ -1,4 +1,4 @@
-7b674ea381bacc9abe3e3579f9df0e98 *tests/data/fate/vsynth1-r210.avi
-22125248 tests/data/fate/vsynth1-r210.avi
+fd2bb8b3d3e47f5ea7769443324ee0ae *tests/data/fate/vsynth1-r210.avi
+22125252 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
index 5f43618..0a3947c 100644
--- a/tests/ref/vsynth/vsynth1-rgb
+++ b/tests/ref/vsynth/vsynth1-rgb
@@ -1,4 +1,4 @@
-a955310c1ad92f967fc4e3d38dc0ef91 *tests/data/fate/vsynth1-rgb.avi
-15213248 tests/data/fate/vsynth1-rgb.avi
+c8a4b8648436e73ced7fe32f6f65a1b3 *tests/data/fate/vsynth1-rgb.avi
+15213252 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/vsynth/vsynth1-snow b/tests/ref/vsynth/vsynth1-snow
index a3d7028..2f0f582 100644
--- a/tests/ref/vsynth/vsynth1-snow
+++ b/tests/ref/vsynth/vsynth1-snow
@@ -1,4 +1,4 @@
-40c38c87f15a76745fcc1e1c59f80054 *tests/data/fate/vsynth1-snow.avi
-136076 tests/data/fate/vsynth1-snow.avi
+e4de85f539ef50b08d2a1dc7e57c7f49 *tests/data/fate/vsynth1-snow.avi
+136080 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
index 5ef7de0..2d3401c 100644
--- a/tests/ref/vsynth/vsynth1-snow-hpel
+++ b/tests/ref/vsynth/vsynth1-snow-hpel
@@ -1,4 +1,4 @@
-6a91c3b8d05cbcc664e357539bd13269 *tests/data/fate/vsynth1-snow-hpel.avi
-138700 tests/data/fate/vsynth1-snow-hpel.avi
+a9e99877f757a99816fd82461d047812 *tests/data/fate/vsynth1-snow-hpel.avi
+138704 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
index 7cb8643..ca5007f 100644
--- a/tests/ref/vsynth/vsynth1-snow-ll
+++ b/tests/ref/vsynth/vsynth1-snow-ll
@@ -1,4 +1,4 @@
-ef9af2fa50b412301aeeaa1aeca09526 *tests/data/fate/vsynth1-snow-ll.avi
-3419968 tests/data/fate/vsynth1-snow-ll.avi
+47690bd6f32d8f5ce11b9f6e7f090be2 *tests/data/fate/vsynth1-snow-ll.avi
+3419972 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-v210 b/tests/ref/vsynth/vsynth1-v210
index 0d12afa..388e8b6 100644
--- a/tests/ref/vsynth/vsynth1-v210
+++ b/tests/ref/vsynth/vsynth1-v210
@@ -1,4 +1,4 @@
-b066679e08cd90c342da21c88bec2a20 *tests/data/fate/vsynth1-v210.avi
-14752448 tests/data/fate/vsynth1-v210.avi
+0712d60b3a00cf2d5a7e39aa21e2547a *tests/data/fate/vsynth1-v210.avi
+14752452 tests/data/fate/vsynth1-v210.avi
 2ba7f4ca302f3c4147860b9dfb12b6e4 *tests/data/fate/vsynth1-v210.out.rawvideo
 stddev:    1.84 PSNR: 42.81 MAXDIFF:   29 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-v308 b/tests/ref/vsynth/vsynth1-v308
index 45b20ed..9eb2911 100644
--- a/tests/ref/vsynth/vsynth1-v308
+++ b/tests/ref/vsynth/vsynth1-v308
@@ -1,4 +1,4 @@
-b1d7f4300e69fc8995188f73b7680481 *tests/data/fate/vsynth1-v308.avi
-15213248 tests/data/fate/vsynth1-v308.avi
+58ea26d3060f9d47cf95056ed9361c90 *tests/data/fate/vsynth1-v308.avi
+15213252 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
index e5970e1..bf16cbd 100644
--- a/tests/ref/vsynth/vsynth1-v408
+++ b/tests/ref/vsynth/vsynth1-v408
@@ -1,4 +1,4 @@
-c14aa9857a0ff73130a9fb11cf738c73 *tests/data/fate/vsynth1-v408.avi
-20282048 tests/data/fate/vsynth1-v408.avi
+4ac68e91ac25bc422abb3febe86a4acd *tests/data/fate/vsynth1-v408.avi
+20282052 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
index 1759ec1..8603ba2 100644
--- a/tests/ref/vsynth/vsynth1-wmv1
+++ b/tests/ref/vsynth/vsynth1-wmv1
@@ -1,4 +1,4 @@
-76024303a316ffe69b4357b220eafc4a *tests/data/fate/vsynth1-wmv1.avi
-626870 tests/data/fate/vsynth1-wmv1.avi
+871a92dc2fe36ca94211830160f9f406 *tests/data/fate/vsynth1-wmv1.avi
+626874 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
index 75d3e22..4039d86 100644
--- a/tests/ref/vsynth/vsynth1-wmv2
+++ b/tests/ref/vsynth/vsynth1-wmv2
@@ -1,4 +1,4 @@
-818ade4e037d5db8c10f6bce727faec6 *tests/data/fate/vsynth1-wmv2.avi
-659138 tests/data/fate/vsynth1-wmv2.avi
+be5c5985d7f4d5b7797aeb0c825bf4f8 *tests/data/fate/vsynth1-wmv2.avi
+659142 tests/data/fate/vsynth1-wmv2.avi
 8a6061ef825e79d887705db656d51247 *tests/data/fate/vsynth1-wmv2.out.rawvideo
 stddev:    7.97 PSNR: 30.09 MAXDIFF:  105 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth1-y41p b/tests/ref/vsynth/vsynth1-y41p
index 6b5b08c..cb4c001 100644
--- a/tests/ref/vsynth/vsynth1-y41p
+++ b/tests/ref/vsynth/vsynth1-y41p
@@ -1,4 +1,4 @@
-1441e4ca15d9fb1d6b2901cac7938e7f *tests/data/fate/vsynth1-y41p.avi
-7610048 tests/data/fate/vsynth1-y41p.avi
+862ffddd90c82163d2505031e5bbcd9a *tests/data/fate/vsynth1-y41p.avi
+7610052 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
index 3648e69..8498d68 100644
--- a/tests/ref/vsynth/vsynth1-yuv
+++ b/tests/ref/vsynth/vsynth1-yuv
@@ -1,4 +1,4 @@
-79738c86c951f7b2f061b3cb238989b0 *tests/data/fate/vsynth1-yuv.avi
-7610048 tests/data/fate/vsynth1-yuv.avi
+2b930d809c19e8d50eb4c92474085c27 *tests/data/fate/vsynth1-yuv.avi
+7610052 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
index dc79810..22ba3b0 100644
--- a/tests/ref/vsynth/vsynth1-yuv4
+++ b/tests/ref/vsynth/vsynth1-yuv4
@@ -1,4 +1,4 @@
-7fe85091535c7f7db31f9aaa00388d9a *tests/data/fate/vsynth1-yuv4.avi
-7610048 tests/data/fate/vsynth1-yuv4.avi
+71d07cf8dd5631f8669294aa86db363e *tests/data/fate/vsynth1-yuv4.avi
+7610052 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
index 9ed0aed..419c6a6 100644
--- a/tests/ref/vsynth/vsynth1-zlib
+++ b/tests/ref/vsynth/vsynth1-zlib
@@ -1,4 +1,4 @@
-18a22e378a1a5961663fe76925fee271 *tests/data/fate/vsynth1-zlib.avi
-12108632 tests/data/fate/vsynth1-zlib.avi
+fd44e7bf6322f4be46f4f0dada728849 *tests/data/fate/vsynth1-zlib.avi
+12108636 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/vsynth/vsynth2-amv b/tests/ref/vsynth/vsynth2-amv
index a9b4a0f..088b5ce 100644
--- a/tests/ref/vsynth/vsynth2-amv
+++ b/tests/ref/vsynth/vsynth2-amv
@@ -1,4 +1,4 @@
-4aecb14ef9fc1a0b54d1ae39808a488e *tests/data/fate/vsynth2-amv.avi
-912548 tests/data/fate/vsynth2-amv.avi
+a77c55410820d0e0883c76f557774bcf *tests/data/fate/vsynth2-amv.avi
+912552 tests/data/fate/vsynth2-amv.avi
 5b7fe07a366b176e35d2564ecf95ebe9 *tests/data/fate/vsynth2-amv.out.rawvideo
 stddev:    4.91 PSNR: 34.31 MAXDIFF:   71 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-asv1 b/tests/ref/vsynth/vsynth2-asv1
index 2f20a07..a466ec0 100644
--- a/tests/ref/vsynth/vsynth2-asv1
+++ b/tests/ref/vsynth/vsynth2-asv1
@@ -1,4 +1,4 @@
-c80b5ad97e55e5fa644698a53e8f0559 *tests/data/fate/vsynth2-asv1.avi
-836552 tests/data/fate/vsynth2-asv1.avi
+375a52cafcd2b2d7bd2fc2841e945bf8 *tests/data/fate/vsynth2-asv1.avi
+836556 tests/data/fate/vsynth2-asv1.avi
 da15fb1affc65904161dc37eff4cdc7a *tests/data/fate/vsynth2-asv1.out.rawvideo
 stddev:    5.78 PSNR: 32.88 MAXDIFF:   75 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-asv2 b/tests/ref/vsynth/vsynth2-asv2
index fc07630..d4bb4c8 100644
--- a/tests/ref/vsynth/vsynth2-asv2
+++ b/tests/ref/vsynth/vsynth2-asv2
@@ -1,4 +1,4 @@
-56d3455969d54fc484b13df3cca465ec *tests/data/fate/vsynth2-asv2.avi
-822228 tests/data/fate/vsynth2-asv2.avi
+ad6e4a2adf55b04ba42bea1db19d360f *tests/data/fate/vsynth2-asv2.avi
+822232 tests/data/fate/vsynth2-asv2.avi
 15329433bcccfb9ca874d949423cef47 *tests/data/fate/vsynth2-asv2.out.rawvideo
 stddev:    5.13 PSNR: 33.92 MAXDIFF:   50 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-cljr b/tests/ref/vsynth/vsynth2-cljr
index 7c44804..e3d02c9 100644
--- a/tests/ref/vsynth/vsynth2-cljr
+++ b/tests/ref/vsynth/vsynth2-cljr
@@ -1,4 +1,4 @@
-655e904953107fb0c015338bccb40873 *tests/data/fate/vsynth2-cljr.avi
-5075648 tests/data/fate/vsynth2-cljr.avi
+4ccffc9ea4a5e260b9867b03d127f85c *tests/data/fate/vsynth2-cljr.avi
+5075652 tests/data/fate/vsynth2-cljr.avi
 14e64b6e6c1d7fdefbb111920911f301 *tests/data/fate/vsynth2-cljr.out.rawvideo
 stddev:    3.34 PSNR: 37.65 MAXDIFF:   37 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-dnxhd-1080i b/tests/ref/vsynth/vsynth2-dnxhd-1080i
index 527e6a7..c3a5073 100644
--- a/tests/ref/vsynth/vsynth2-dnxhd-1080i
+++ b/tests/ref/vsynth/vsynth2-dnxhd-1080i
@@ -1,4 +1,4 @@
-d59d5d40ffb33ebb9e9e0d5025aefb88 *tests/data/fate/vsynth2-dnxhd-1080i.mov
+2b75889122f8d918e1b068d128b618ca *tests/data/fate/vsynth2-dnxhd-1080i.mov
 3031911 tests/data/fate/vsynth2-dnxhd-1080i.mov
 099001db73036eeb9545c463cf90f0ba *tests/data/fate/vsynth2-dnxhd-1080i.out.rawvideo
 stddev:    1.53 PSNR: 44.43 MAXDIFF:   31 bytes:  7603200/   760320
diff --git a/tests/ref/vsynth/vsynth2-dnxhd-1080i-colr b/tests/ref/vsynth/vsynth2-dnxhd-1080i-colr
index 0994820..ba5e6a1 100644
--- a/tests/ref/vsynth/vsynth2-dnxhd-1080i-colr
+++ b/tests/ref/vsynth/vsynth2-dnxhd-1080i-colr
@@ -1,4 +1,4 @@
-d510bc0d58c7cae875e3e67023771d6f *tests/data/fate/vsynth2-dnxhd-1080i-colr.mov
+f9827e9867b0ea4f7585d8e362a58413 *tests/data/fate/vsynth2-dnxhd-1080i-colr.mov
 3031929 tests/data/fate/vsynth2-dnxhd-1080i-colr.mov
 e4cf5528c993b5e7d57a9d0a4d2cd0c6 *tests/data/fate/vsynth2-dnxhd-1080i-colr.out.rawvideo
 stddev:    1.58 PSNR: 44.15 MAXDIFF:   33 bytes:  7603200/   760320
diff --git a/tests/ref/vsynth/vsynth2-ffv1 b/tests/ref/vsynth/vsynth2-ffv1
index eef1115..297388c 100644
--- a/tests/ref/vsynth/vsynth2-ffv1
+++ b/tests/ref/vsynth/vsynth2-ffv1
@@ -1,4 +1,4 @@
-5ebaa3df3ab8063214a3c612c8e98e04 *tests/data/fate/vsynth2-ffv1.avi
-3718022 tests/data/fate/vsynth2-ffv1.avi
+d69458b07bcbce4e7e9388d8fe6c748d *tests/data/fate/vsynth2-ffv1.avi
+3718026 tests/data/fate/vsynth2-ffv1.avi
 36d7ca943916e1743cefa609eba0205c *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-ffv1.0 b/tests/ref/vsynth/vsynth2-ffv1.0
index a4f1a81..117fe27 100644
--- a/tests/ref/vsynth/vsynth2-ffv1.0
+++ b/tests/ref/vsynth/vsynth2-ffv1.0
@@ -1,4 +1,4 @@
-f7960e9a863ce303f71b8a9feaeec1d2 *tests/data/fate/vsynth2-ffv1.0.avi
-3692538 tests/data/fate/vsynth2-ffv1.0.avi
+9647e906f0739ed84303bd03d1cb8105 *tests/data/fate/vsynth2-ffv1.0.avi
+3692542 tests/data/fate/vsynth2-ffv1.0.avi
 36d7ca943916e1743cefa609eba0205c *tests/data/fate/vsynth2-ffv1.0.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
index 4fe9f86..4a79180 100644
--- a/tests/ref/vsynth/vsynth2-ffvhuff
+++ b/tests/ref/vsynth/vsynth2-ffvhuff
@@ -1,4 +1,4 @@
-ca0fd7f4ab121383c89c1e708375ed73 *tests/data/fate/vsynth2-ffvhuff.avi
-4865618 tests/data/fate/vsynth2-ffvhuff.avi
+bf05520f43523ffde8952c23f36cc6a9 *tests/data/fate/vsynth2-ffvhuff.avi
+4865622 tests/data/fate/vsynth2-ffvhuff.avi
 36d7ca943916e1743cefa609eba0205c *tests/data/fate/vsynth2-ffvhuff.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-ffvhuff420p12 b/tests/ref/vsynth/vsynth2-ffvhuff420p12
index bde1843..82c467a 100644
--- a/tests/ref/vsynth/vsynth2-ffvhuff420p12
+++ b/tests/ref/vsynth/vsynth2-ffvhuff420p12
@@ -1,4 +1,4 @@
-954970affeb3bf759625945364b48681 *tests/data/fate/vsynth2-ffvhuff420p12.avi
-10562804 tests/data/fate/vsynth2-ffvhuff420p12.avi
+3ab9567895bf1ec31a82aadf16a5da0e *tests/data/fate/vsynth2-ffvhuff420p12.avi
+10562808 tests/data/fate/vsynth2-ffvhuff420p12.avi
 542327cb5ca7708085513ffc3d7c693c *tests/data/fate/vsynth2-ffvhuff420p12.out.rawvideo
 stddev:    0.72 PSNR: 50.87 MAXDIFF:    1 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-ffvhuff422p10left b/tests/ref/vsynth/vsynth2-ffvhuff422p10left
index fb6fb18..a4284cf 100644
--- a/tests/ref/vsynth/vsynth2-ffvhuff422p10left
+++ b/tests/ref/vsynth/vsynth2-ffvhuff422p10left
@@ -1,4 +1,4 @@
-e6aac4b4faafac27aa3ae76ef84519e5 *tests/data/fate/vsynth2-ffvhuff422p10left.avi
-9870624 tests/data/fate/vsynth2-ffvhuff422p10left.avi
+d13c20fb63b70b81dd6100be47a3f07c *tests/data/fate/vsynth2-ffvhuff422p10left.avi
+9870628 tests/data/fate/vsynth2-ffvhuff422p10left.avi
 8bb1c449e1a2a94fd0d98841c04246bb *tests/data/fate/vsynth2-ffvhuff422p10left.out.rawvideo
 stddev:    0.39 PSNR: 56.17 MAXDIFF:    9 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-ffvhuff444 b/tests/ref/vsynth/vsynth2-ffvhuff444
index 719373d..7c7242e 100644
--- a/tests/ref/vsynth/vsynth2-ffvhuff444
+++ b/tests/ref/vsynth/vsynth2-ffvhuff444
@@ -1,4 +1,4 @@
-38071294a9151e244640d32ce6bc440d *tests/data/fate/vsynth2-ffvhuff444.avi
-7635770 tests/data/fate/vsynth2-ffvhuff444.avi
+770909cb12fc8a1b2ce020e5f9b421d4 *tests/data/fate/vsynth2-ffvhuff444.avi
+7635774 tests/data/fate/vsynth2-ffvhuff444.avi
 8394327c14ef0b6fbaae3b69fcc5572a *tests/data/fate/vsynth2-ffvhuff444.out.rawvideo
 stddev:    0.50 PSNR: 54.10 MAXDIFF:   13 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-ffvhuff444p16 b/tests/ref/vsynth/vsynth2-ffvhuff444p16
index 6308761..ebc3840 100644
--- a/tests/ref/vsynth/vsynth2-ffvhuff444p16
+++ b/tests/ref/vsynth/vsynth2-ffvhuff444p16
@@ -1,4 +1,4 @@
-d66af9c3aa21371f8483a2d32af2ff59 *tests/data/fate/vsynth2-ffvhuff444p16.avi
-26612920 tests/data/fate/vsynth2-ffvhuff444p16.avi
+63ad1a32444c67d7092735fd74a7193d *tests/data/fate/vsynth2-ffvhuff444p16.avi
+26612924 tests/data/fate/vsynth2-ffvhuff444p16.avi
 410af07de7ae21936aaeae03fc90cbc9 *tests/data/fate/vsynth2-ffvhuff444p16.out.rawvideo
 stddev:    0.53 PSNR: 53.63 MAXDIFF:   13 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-h261 b/tests/ref/vsynth/vsynth2-h261
index afa57b6..999ac36 100644
--- a/tests/ref/vsynth/vsynth2-h261
+++ b/tests/ref/vsynth/vsynth2-h261
@@ -1,4 +1,4 @@
-99f46a0a9d77052818e503f17376c67b *tests/data/fate/vsynth2-h261.avi
-257934 tests/data/fate/vsynth2-h261.avi
+6334083b8899cdd8b56f80f8e1345213 *tests/data/fate/vsynth2-h261.avi
+257938 tests/data/fate/vsynth2-h261.avi
 8962b6ea3153a828e5a4df68e1d5da44 *tests/data/fate/vsynth2-h261.out.rawvideo
 stddev:    7.21 PSNR: 30.97 MAXDIFF:   96 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-h261-trellis b/tests/ref/vsynth/vsynth2-h261-trellis
index 372d7d8..7f53e30 100644
--- a/tests/ref/vsynth/vsynth2-h261-trellis
+++ b/tests/ref/vsynth/vsynth2-h261-trellis
@@ -1,4 +1,4 @@
-21e3d72b623a17d695e9a7d491d932e4 *tests/data/fate/vsynth2-h261-trellis.avi
-249852 tests/data/fate/vsynth2-h261-trellis.avi
+f5105d846793cd12f1fedffd917a240d *tests/data/fate/vsynth2-h261-trellis.avi
+249856 tests/data/fate/vsynth2-h261-trellis.avi
 15452237f6c333690d3e05f354f63196 *tests/data/fate/vsynth2-h261-trellis.out.rawvideo
 stddev:    7.10 PSNR: 31.10 MAXDIFF:   96 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-h263 b/tests/ref/vsynth/vsynth2-h263
index 6ab7dc7..057021b 100644
--- a/tests/ref/vsynth/vsynth2-h263
+++ b/tests/ref/vsynth/vsynth2-h263
@@ -1,4 +1,4 @@
-0f4436f0e58e5e26ed191647b17325f6 *tests/data/fate/vsynth2-h263.avi
-216470 tests/data/fate/vsynth2-h263.avi
+8f765ba6afa2a0a1e33d7bf9d168ae2f *tests/data/fate/vsynth2-h263.avi
+216474 tests/data/fate/vsynth2-h263.avi
 d77291a0611eeec0667bbc3aba7190b8 *tests/data/fate/vsynth2-h263.out.rawvideo
 stddev:    6.12 PSNR: 32.39 MAXDIFF:   83 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-h263-obmc b/tests/ref/vsynth/vsynth2-h263-obmc
index 997e941..2cef7f5 100644
--- a/tests/ref/vsynth/vsynth2-h263-obmc
+++ b/tests/ref/vsynth/vsynth2-h263-obmc
@@ -1,4 +1,4 @@
-7b2bd6306c6d5a5d092d45087ceb0ed8 *tests/data/fate/vsynth2-h263-obmc.avi
-208518 tests/data/fate/vsynth2-h263-obmc.avi
+2d8a58b295e03f94e6a41468b2d3909e *tests/data/fate/vsynth2-h263-obmc.avi
+208522 tests/data/fate/vsynth2-h263-obmc.avi
 4a939ef99fc759293f2e609bfcacd2a4 *tests/data/fate/vsynth2-h263-obmc.out.rawvideo
 stddev:    6.10 PSNR: 32.41 MAXDIFF:   90 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-h263p b/tests/ref/vsynth/vsynth2-h263p
index 98b1e41..487d282 100644
--- a/tests/ref/vsynth/vsynth2-h263p
+++ b/tests/ref/vsynth/vsynth2-h263p
@@ -1,4 +1,4 @@
-4026635d74704989f48a6599c1a8a076 *tests/data/fate/vsynth2-h263p.avi
-1134962 tests/data/fate/vsynth2-h263p.avi
+f18d6a61cb0b581b0c4835f4055f0905 *tests/data/fate/vsynth2-h263p.avi
+1134966 tests/data/fate/vsynth2-h263p.avi
 66e8c0bd40918f970e62b6cdd7df79a5 *tests/data/fate/vsynth2-h263p.out.rawvideo
 stddev:    2.01 PSNR: 42.04 MAXDIFF:   21 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-huffyuv b/tests/ref/vsynth/vsynth2-huffyuv
index 137ac46..a10d430 100644
--- a/tests/ref/vsynth/vsynth2-huffyuv
+++ b/tests/ref/vsynth/vsynth2-huffyuv
@@ -1,4 +1,4 @@
-e0fdf09f1265c24d2878088594f88ecf *tests/data/fate/vsynth2-huffyuv.avi
-6159094 tests/data/fate/vsynth2-huffyuv.avi
+0f56e00a2850c0156de419d979782f29 *tests/data/fate/vsynth2-huffyuv.avi
+6159098 tests/data/fate/vsynth2-huffyuv.avi
 36d7ca943916e1743cefa609eba0205c *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-huffyuvbgr24 b/tests/ref/vsynth/vsynth2-huffyuvbgr24
index eedb564..4263e0f 100644
--- a/tests/ref/vsynth/vsynth2-huffyuvbgr24
+++ b/tests/ref/vsynth/vsynth2-huffyuvbgr24
@@ -1,4 +1,4 @@
-06eb7c8bd4cc8401431b1a6ce7652b34 *tests/data/fate/vsynth2-huffyuvbgr24.avi
-8809206 tests/data/fate/vsynth2-huffyuvbgr24.avi
+f7a321d9dc6b2cdef377067eae413954 *tests/data/fate/vsynth2-huffyuvbgr24.avi
+8809210 tests/data/fate/vsynth2-huffyuvbgr24.avi
 835a86f8dff88917c3e5f2776954c5b7 *tests/data/fate/vsynth2-huffyuvbgr24.out.rawvideo
 stddev:    1.57 PSNR: 44.18 MAXDIFF:   20 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-huffyuvbgra b/tests/ref/vsynth/vsynth2-huffyuvbgra
index 1062473..1451f6b 100644
--- a/tests/ref/vsynth/vsynth2-huffyuvbgra
+++ b/tests/ref/vsynth/vsynth2-huffyuvbgra
@@ -1,4 +1,4 @@
-5f386d45bd3b2c250c5db43ab59b3439 *tests/data/fate/vsynth2-huffyuvbgra.avi
-10076386 tests/data/fate/vsynth2-huffyuvbgra.avi
+7f591295660b0a4dd93cc436e51d1a87 *tests/data/fate/vsynth2-huffyuvbgra.avi
+10076390 tests/data/fate/vsynth2-huffyuvbgra.avi
 835a86f8dff88917c3e5f2776954c5b7 *tests/data/fate/vsynth2-huffyuvbgra.out.rawvideo
 stddev:    1.57 PSNR: 44.18 MAXDIFF:   20 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-jpeg2000 b/tests/ref/vsynth/vsynth2-jpeg2000
index d1ebf4b..04c5a2a 100644
--- a/tests/ref/vsynth/vsynth2-jpeg2000
+++ b/tests/ref/vsynth/vsynth2-jpeg2000
@@ -1,4 +1,4 @@
-bd10f835a585ca63bcd6f94a5a71b1d4 *tests/data/fate/vsynth2-jpeg2000.avi
-1513140 tests/data/fate/vsynth2-jpeg2000.avi
+b918de21dec4310f87af3788ed458462 *tests/data/fate/vsynth2-jpeg2000.avi
+1513144 tests/data/fate/vsynth2-jpeg2000.avi
 1d33de510f21eaad6c3cecfcf29798ba *tests/data/fate/vsynth2-jpeg2000.out.rawvideo
 stddev:    4.99 PSNR: 34.17 MAXDIFF:   70 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-jpeg2000-97 b/tests/ref/vsynth/vsynth2-jpeg2000-97
index cfc61eb..21ab8ad 100644
--- a/tests/ref/vsynth/vsynth2-jpeg2000-97
+++ b/tests/ref/vsynth/vsynth2-jpeg2000-97
@@ -1,4 +1,4 @@
-91c0f0afa29952204ebfc2f93fb41c75 *tests/data/fate/vsynth2-jpeg2000-97.avi
-1467468 tests/data/fate/vsynth2-jpeg2000-97.avi
+f8880f48a46ad43623d00de15ecba2cd *tests/data/fate/vsynth2-jpeg2000-97.avi
+1467472 tests/data/fate/vsynth2-jpeg2000-97.avi
 e523db4385f586d73aa0ee2688a75d2e *tests/data/fate/vsynth2-jpeg2000-97.out.rawvideo
 stddev:    5.44 PSNR: 33.41 MAXDIFF:   57 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-jpegls b/tests/ref/vsynth/vsynth2-jpegls
index 47cb5a5..02cdf09 100644
--- a/tests/ref/vsynth/vsynth2-jpegls
+++ b/tests/ref/vsynth/vsynth2-jpegls
@@ -1,4 +1,4 @@
-c51763b68e2c1f37c7d588c0f1ea532f *tests/data/fate/vsynth2-jpegls.avi
-8311644 tests/data/fate/vsynth2-jpegls.avi
+b26c90f2661ccfe8a68b6cde71e9ccf0 *tests/data/fate/vsynth2-jpegls.avi
+8311648 tests/data/fate/vsynth2-jpegls.avi
 7f0fc12c02e68faddc153e69ddd6841c *tests/data/fate/vsynth2-jpegls.out.rawvideo
 stddev:    1.20 PSNR: 46.52 MAXDIFF:   20 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-ljpeg b/tests/ref/vsynth/vsynth2-ljpeg
index bd7fbd8..776cfcf 100644
--- a/tests/ref/vsynth/vsynth2-ljpeg
+++ b/tests/ref/vsynth/vsynth2-ljpeg
@@ -1,4 +1,4 @@
-bc40b0e3bf900ce18942886c9193869c *tests/data/fate/vsynth2-ljpeg.avi
-4712244 tests/data/fate/vsynth2-ljpeg.avi
+ae8b43d92240077d7a80b6d543a63d0c *tests/data/fate/vsynth2-ljpeg.avi
+4712248 tests/data/fate/vsynth2-ljpeg.avi
 36d7ca943916e1743cefa609eba0205c *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
index 5e51523..98b257e 100644
--- a/tests/ref/vsynth/vsynth2-mjpeg
+++ b/tests/ref/vsynth/vsynth2-mjpeg
@@ -1,4 +1,4 @@
-52873568b64fd315f01559d1216930b2 *tests/data/fate/vsynth2-mjpeg.avi
-830150 tests/data/fate/vsynth2-mjpeg.avi
+c76100bdc3f4c8e2580bb263accda9ec *tests/data/fate/vsynth2-mjpeg.avi
+830154 tests/data/fate/vsynth2-mjpeg.avi
 2b8c59c59e33d6ca7c85d31c5eeab7be *tests/data/fate/vsynth2-mjpeg.out.rawvideo
 stddev:    4.87 PSNR: 34.37 MAXDIFF:   55 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mjpeg-422 b/tests/ref/vsynth/vsynth2-mjpeg-422
index bc25008..ddedda6 100644
--- a/tests/ref/vsynth/vsynth2-mjpeg-422
+++ b/tests/ref/vsynth/vsynth2-mjpeg-422
@@ -1,4 +1,4 @@
-98afd6e384f6c0dad8d5e713be157cf3 *tests/data/fate/vsynth2-mjpeg-422.avi
-920360 tests/data/fate/vsynth2-mjpeg-422.avi
+1c8dd65c901ce48ef82d73b80e38c735 *tests/data/fate/vsynth2-mjpeg-422.avi
+920364 tests/data/fate/vsynth2-mjpeg-422.avi
 4a1b18eeb8b0f3dccc2c0e6a9f8c876d *tests/data/fate/vsynth2-mjpeg-422.out.rawvideo
 stddev:    4.69 PSNR: 34.69 MAXDIFF:   55 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mjpeg-444 b/tests/ref/vsynth/vsynth2-mjpeg-444
index bfc0e10..428fedc 100644
--- a/tests/ref/vsynth/vsynth2-mjpeg-444
+++ b/tests/ref/vsynth/vsynth2-mjpeg-444
@@ -1,4 +1,4 @@
-0f8f4b3b45bfd0157ac4500cf88a639b *tests/data/fate/vsynth2-mjpeg-444.avi
-1060066 tests/data/fate/vsynth2-mjpeg-444.avi
+0ac6d33ef31d07eecf65955eabf241f7 *tests/data/fate/vsynth2-mjpeg-444.avi
+1060070 tests/data/fate/vsynth2-mjpeg-444.avi
 6417f5a4be03ca7854f0a1be429a286e *tests/data/fate/vsynth2-mjpeg-444.out.rawvideo
 stddev:    4.57 PSNR: 34.93 MAXDIFF:   55 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mjpeg-trell b/tests/ref/vsynth/vsynth2-mjpeg-trell
new file mode 100644
index 0000000..ce6d917
--- /dev/null
+++ b/tests/ref/vsynth/vsynth2-mjpeg-trell
@@ -0,0 +1,4 @@
+4fdbd2327ed16fc4448eb421def22b5e *tests/data/fate/vsynth2-mjpeg-trell.avi
+765628 tests/data/fate/vsynth2-mjpeg-trell.avi
+ce145393bece26d49076b26cf1a2e52e *tests/data/fate/vsynth2-mjpeg-trell.out.rawvideo
+stddev:    5.03 PSNR: 34.09 MAXDIFF:   67 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mpeg4-adap b/tests/ref/vsynth/vsynth2-mpeg4-adap
index 67f9904..a3223f6 100644
--- a/tests/ref/vsynth/vsynth2-mpeg4-adap
+++ b/tests/ref/vsynth/vsynth2-mpeg4-adap
@@ -1,4 +1,4 @@
-36f4edf171cd1990211a44136fa1d038 *tests/data/fate/vsynth2-mpeg4-adap.avi
-213504 tests/data/fate/vsynth2-mpeg4-adap.avi
+4bff98da2342836476da817428594403 *tests/data/fate/vsynth2-mpeg4-adap.avi
+213508 tests/data/fate/vsynth2-mpeg4-adap.avi
 0c709f2b81f4593eaa29490332c2cb39 *tests/data/fate/vsynth2-mpeg4-adap.out.rawvideo
 stddev:    4.87 PSNR: 34.36 MAXDIFF:   86 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mpeg4-adv b/tests/ref/vsynth/vsynth2-mpeg4-adv
index 664d329..6132b58 100644
--- a/tests/ref/vsynth/vsynth2-mpeg4-adv
+++ b/tests/ref/vsynth/vsynth2-mpeg4-adv
@@ -1,4 +1,4 @@
-42618863ff3400b699775ed7de5a6e5f *tests/data/fate/vsynth2-mpeg4-adv.avi
-187242 tests/data/fate/vsynth2-mpeg4-adv.avi
+b2021365c46e52a93492e2a8697762e5 *tests/data/fate/vsynth2-mpeg4-adv.avi
+187246 tests/data/fate/vsynth2-mpeg4-adv.avi
 505bdffb9b051dc2123d07a4ae183faf *tests/data/fate/vsynth2-mpeg4-adv.out.rawvideo
 stddev:    5.51 PSNR: 33.30 MAXDIFF:   80 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mpeg4-error b/tests/ref/vsynth/vsynth2-mpeg4-error
index ce7119c..e1adba4 100644
--- a/tests/ref/vsynth/vsynth2-mpeg4-error
+++ b/tests/ref/vsynth/vsynth2-mpeg4-error
@@ -1,4 +1,4 @@
-aa15d3d241e2d23d1f17e30833b8ee99 *tests/data/fate/vsynth2-mpeg4-error.avi
-236056 tests/data/fate/vsynth2-mpeg4-error.avi
+0bee773ac15fd1edd56e1dd28704292f *tests/data/fate/vsynth2-mpeg4-error.avi
+236060 tests/data/fate/vsynth2-mpeg4-error.avi
 f67a99fe41cd22a2a6713965eebb990e *tests/data/fate/vsynth2-mpeg4-error.out.rawvideo
 stddev:   15.66 PSNR: 24.23 MAXDIFF:  236 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mpeg4-nr b/tests/ref/vsynth/vsynth2-mpeg4-nr
index 7d88e83..debf3ba 100644
--- a/tests/ref/vsynth/vsynth2-mpeg4-nr
+++ b/tests/ref/vsynth/vsynth2-mpeg4-nr
@@ -1,4 +1,4 @@
-402c4381982f706fac32a693de9d9001 *tests/data/fate/vsynth2-mpeg4-nr.avi
-206034 tests/data/fate/vsynth2-mpeg4-nr.avi
+83bb3f4618f8d6259d48a51bc65b3cbc *tests/data/fate/vsynth2-mpeg4-nr.avi
+206038 tests/data/fate/vsynth2-mpeg4-nr.avi
 b1b0edaec04620b5f9149dce5171939c *tests/data/fate/vsynth2-mpeg4-nr.out.rawvideo
 stddev:    5.32 PSNR: 33.61 MAXDIFF:   78 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mpeg4-nsse b/tests/ref/vsynth/vsynth2-mpeg4-nsse
index c61b603..cae5716 100644
--- a/tests/ref/vsynth/vsynth2-mpeg4-nsse
+++ b/tests/ref/vsynth/vsynth2-mpeg4-nsse
@@ -1,4 +1,4 @@
-dc007cd18a96cacbac7c8c182a397267 *tests/data/fate/vsynth2-mpeg4-nsse.avi
-266096 tests/data/fate/vsynth2-mpeg4-nsse.avi
+4fdc2aaa4761f245590a3c78c85f0ae2 *tests/data/fate/vsynth2-mpeg4-nsse.avi
+266100 tests/data/fate/vsynth2-mpeg4-nsse.avi
 9123b1641394250a6edd389d02f249e8 *tests/data/fate/vsynth2-mpeg4-nsse.out.rawvideo
 stddev:    4.83 PSNR: 34.45 MAXDIFF:   59 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mpeg4-qpel b/tests/ref/vsynth/vsynth2-mpeg4-qpel
index 4d708b1..495b9f0 100644
--- a/tests/ref/vsynth/vsynth2-mpeg4-qpel
+++ b/tests/ref/vsynth/vsynth2-mpeg4-qpel
@@ -1,4 +1,4 @@
-5213d1609a3ee3a92e9abfddc214bd1d *tests/data/fate/vsynth2-mpeg4-qpel.avi
-209866 tests/data/fate/vsynth2-mpeg4-qpel.avi
+d05dbd6c6b8a57953aea3caa6cab57b0 *tests/data/fate/vsynth2-mpeg4-qpel.avi
+209870 tests/data/fate/vsynth2-mpeg4-qpel.avi
 5313cb1ef8c520de548389d541842c51 *tests/data/fate/vsynth2-mpeg4-qpel.out.rawvideo
 stddev:    4.42 PSNR: 35.22 MAXDIFF:   56 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mpeg4-qprd b/tests/ref/vsynth/vsynth2-mpeg4-qprd
index 0acc301..0a8786b 100644
--- a/tests/ref/vsynth/vsynth2-mpeg4-qprd
+++ b/tests/ref/vsynth/vsynth2-mpeg4-qprd
@@ -1,4 +1,4 @@
-0a3dd46ad20ea8e5e07aab03f2175487 *tests/data/fate/vsynth2-mpeg4-qprd.avi
-248702 tests/data/fate/vsynth2-mpeg4-qprd.avi
+4ddd2fef35854d9b387bbcbda03dc7f0 *tests/data/fate/vsynth2-mpeg4-qprd.avi
+248706 tests/data/fate/vsynth2-mpeg4-qprd.avi
 baa8d0d57a7fb5e393642cb20efed2c2 *tests/data/fate/vsynth2-mpeg4-qprd.out.rawvideo
 stddev:    4.85 PSNR: 34.40 MAXDIFF:   85 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mpeg4-rc b/tests/ref/vsynth/vsynth2-mpeg4-rc
index 0417bad..ec7d7ba 100644
--- a/tests/ref/vsynth/vsynth2-mpeg4-rc
+++ b/tests/ref/vsynth/vsynth2-mpeg4-rc
@@ -1,4 +1,4 @@
-ba5823634562defe9a5d73e951e6849d *tests/data/fate/vsynth2-mpeg4-rc.avi
-254734 tests/data/fate/vsynth2-mpeg4-rc.avi
+0cf3a444622becc5d56e9034b226cfe2 *tests/data/fate/vsynth2-mpeg4-rc.avi
+254738 tests/data/fate/vsynth2-mpeg4-rc.avi
 53ef615a87c8ae49c379242385315f61 *tests/data/fate/vsynth2-mpeg4-rc.out.rawvideo
 stddev:    5.57 PSNR: 33.20 MAXDIFF:  116 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mpeg4-thread b/tests/ref/vsynth/vsynth2-mpeg4-thread
index 0120689..49c0ce0 100644
--- a/tests/ref/vsynth/vsynth2-mpeg4-thread
+++ b/tests/ref/vsynth/vsynth2-mpeg4-thread
@@ -1,4 +1,4 @@
-48a493804d07360c413b189eed200306 *tests/data/fate/vsynth2-mpeg4-thread.avi
-268392 tests/data/fate/vsynth2-mpeg4-thread.avi
+92128f8adc4ac70a66fdddf58e46b923 *tests/data/fate/vsynth2-mpeg4-thread.avi
+268396 tests/data/fate/vsynth2-mpeg4-thread.avi
 f432bd8d897c7c8e286e385b77cedcfa *tests/data/fate/vsynth2-mpeg4-thread.out.rawvideo
 stddev:    4.89 PSNR: 34.34 MAXDIFF:   86 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-mpng b/tests/ref/vsynth/vsynth2-mpng
index cd40fb7..e49714a 100644
--- a/tests/ref/vsynth/vsynth2-mpng
+++ b/tests/ref/vsynth/vsynth2-mpng
@@ -1,4 +1,4 @@
-77f4e52311a1b3a1abf10e0a68cad6eb *tests/data/fate/vsynth2-mpng.avi
-11816974 tests/data/fate/vsynth2-mpng.avi
+481e2d148f411bb61783aa688ec22943 *tests/data/fate/vsynth2-mpng.avi
+11816978 tests/data/fate/vsynth2-mpng.avi
 32fae3e665407bb4317b3f90fedb903c *tests/data/fate/vsynth2-mpng.out.rawvideo
 stddev:    1.54 PSNR: 44.37 MAXDIFF:   17 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-msmpeg4 b/tests/ref/vsynth/vsynth2-msmpeg4
index e192b53..375f21c 100644
--- a/tests/ref/vsynth/vsynth2-msmpeg4
+++ b/tests/ref/vsynth/vsynth2-msmpeg4
@@ -1,4 +1,4 @@
-7c95be46992866b930e24fa96deb7fe4 *tests/data/fate/vsynth2-msmpeg4.avi
-170436 tests/data/fate/vsynth2-msmpeg4.avi
+3f4e6d746b71f367ce5964fd1e421c91 *tests/data/fate/vsynth2-msmpeg4.avi
+170440 tests/data/fate/vsynth2-msmpeg4.avi
 81135454c184b78040c49a2aadca6394 *tests/data/fate/vsynth2-msmpeg4.out.rawvideo
 stddev:    6.02 PSNR: 32.53 MAXDIFF:   89 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-msmpeg4v2 b/tests/ref/vsynth/vsynth2-msmpeg4v2
index bd02100..3af9f1d 100644
--- a/tests/ref/vsynth/vsynth2-msmpeg4v2
+++ b/tests/ref/vsynth/vsynth2-msmpeg4v2
@@ -1,4 +1,4 @@
-a40774474aeee3534ae146fea8ee234a *tests/data/fate/vsynth2-msmpeg4v2.avi
-171906 tests/data/fate/vsynth2-msmpeg4v2.avi
+67358757350de1b3ba39ab074e92b5a7 *tests/data/fate/vsynth2-msmpeg4v2.avi
+171910 tests/data/fate/vsynth2-msmpeg4v2.avi
 c4ca06487e0fdfdfccdccdb671acab42 *tests/data/fate/vsynth2-msmpeg4v2.out.rawvideo
 stddev:    6.02 PSNR: 32.53 MAXDIFF:   83 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-msvideo1 b/tests/ref/vsynth/vsynth2-msvideo1
index 4ec274b..0d13c90 100644
--- a/tests/ref/vsynth/vsynth2-msvideo1
+++ b/tests/ref/vsynth/vsynth2-msvideo1
@@ -1,4 +1,4 @@
-da9992daf1e15d7815fcd6c6b6be1b18 *tests/data/fate/vsynth2-msvideo1.avi
-1301736 tests/data/fate/vsynth2-msvideo1.avi
+92708a8eb94d1dc80ae3508c4f712e54 *tests/data/fate/vsynth2-msvideo1.avi
+1301740 tests/data/fate/vsynth2-msvideo1.avi
 9b6e5905b00c64ed936293f85abbd6cf *tests/data/fate/vsynth2-msvideo1.out.rawvideo
 stddev:    9.04 PSNR: 29.01 MAXDIFF:  169 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-r210 b/tests/ref/vsynth/vsynth2-r210
index 30dc5f0..3e19ef8 100644
--- a/tests/ref/vsynth/vsynth2-r210
+++ b/tests/ref/vsynth/vsynth2-r210
@@ -1,4 +1,4 @@
-4ec1178f35bed604600da20b528b7372 *tests/data/fate/vsynth2-r210.avi
-22125248 tests/data/fate/vsynth2-r210.avi
+50e82830a941457a3cade01394e34dd0 *tests/data/fate/vsynth2-r210.avi
+22125252 tests/data/fate/vsynth2-r210.avi
 2ade5f6167d7a4a1589e168ddbbc35d0 *tests/data/fate/vsynth2-r210.out.rawvideo
 stddev:    1.17 PSNR: 46.71 MAXDIFF:   15 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-rgb b/tests/ref/vsynth/vsynth2-rgb
index 5176643..93fe634 100644
--- a/tests/ref/vsynth/vsynth2-rgb
+++ b/tests/ref/vsynth/vsynth2-rgb
@@ -1,4 +1,4 @@
-d32e51226ad1ef1ee0846841d077d4cd *tests/data/fate/vsynth2-rgb.avi
-15213248 tests/data/fate/vsynth2-rgb.avi
+707159e45a20b22d383e71d3e5960753 *tests/data/fate/vsynth2-rgb.avi
+15213252 tests/data/fate/vsynth2-rgb.avi
 32fae3e665407bb4317b3f90fedb903c *tests/data/fate/vsynth2-rgb.out.rawvideo
 stddev:    1.54 PSNR: 44.37 MAXDIFF:   17 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-snow b/tests/ref/vsynth/vsynth2-snow
index 255e0b7..bedb194 100644
--- a/tests/ref/vsynth/vsynth2-snow
+++ b/tests/ref/vsynth/vsynth2-snow
@@ -1,4 +1,4 @@
-1ff8a762f2501b1b674cffa5d98631b3 *tests/data/fate/vsynth2-snow.avi
-72802 tests/data/fate/vsynth2-snow.avi
+f80a52dad2fd125df9dd6fcb0313eba9 *tests/data/fate/vsynth2-snow.avi
+72806 tests/data/fate/vsynth2-snow.avi
 fb1944b90011ff997e4762eebe3d5ad3 *tests/data/fate/vsynth2-snow.out.rawvideo
 stddev:   13.72 PSNR: 25.38 MAXDIFF:  162 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-snow-hpel b/tests/ref/vsynth/vsynth2-snow-hpel
index 6742c51..66839fd 100644
--- a/tests/ref/vsynth/vsynth2-snow-hpel
+++ b/tests/ref/vsynth/vsynth2-snow-hpel
@@ -1,4 +1,4 @@
-be952f3c331c49cad45b01311f586fae *tests/data/fate/vsynth2-snow-hpel.avi
-79724 tests/data/fate/vsynth2-snow-hpel.avi
+9bc409e4794ee50691a26c9c836d31a7 *tests/data/fate/vsynth2-snow-hpel.avi
+79728 tests/data/fate/vsynth2-snow-hpel.avi
 2cc64d8171175a1532fd7d3ed3011fbf *tests/data/fate/vsynth2-snow-hpel.out.rawvideo
 stddev:   13.70 PSNR: 25.39 MAXDIFF:  162 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-snow-ll b/tests/ref/vsynth/vsynth2-snow-ll
index 09affc1..54b7d43 100644
--- a/tests/ref/vsynth/vsynth2-snow-ll
+++ b/tests/ref/vsynth/vsynth2-snow-ll
@@ -1,4 +1,4 @@
-615ef578a42f0d64fbf65b0c763df915 *tests/data/fate/vsynth2-snow-ll.avi
-2829414 tests/data/fate/vsynth2-snow-ll.avi
+4934defc7c2d3f3b6b74a8d3d877cd96 *tests/data/fate/vsynth2-snow-ll.avi
+2829418 tests/data/fate/vsynth2-snow-ll.avi
 36d7ca943916e1743cefa609eba0205c *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-v210 b/tests/ref/vsynth/vsynth2-v210
index 68cafc7..cc72bb2 100644
--- a/tests/ref/vsynth/vsynth2-v210
+++ b/tests/ref/vsynth/vsynth2-v210
@@ -1,4 +1,4 @@
-06dc558ed5ea170f746bd40c94990adc *tests/data/fate/vsynth2-v210.avi
-14752448 tests/data/fate/vsynth2-v210.avi
+211a901d7e6327cc7a48a80250acf4f8 *tests/data/fate/vsynth2-v210.avi
+14752452 tests/data/fate/vsynth2-v210.avi
 99e367a50da75c2c187230889bee8e2e *tests/data/fate/vsynth2-v210.out.rawvideo
 stddev:    0.40 PSNR: 56.06 MAXDIFF:    9 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-v308 b/tests/ref/vsynth/vsynth2-v308
index 703289f..f1fee2d 100644
--- a/tests/ref/vsynth/vsynth2-v308
+++ b/tests/ref/vsynth/vsynth2-v308
@@ -1,4 +1,4 @@
-62f4b2028533f889a932ed7b052abdcc *tests/data/fate/vsynth2-v308.avi
-15213248 tests/data/fate/vsynth2-v308.avi
+a07c9e12508dec90a414a4a6119c5ae4 *tests/data/fate/vsynth2-v308.avi
+15213252 tests/data/fate/vsynth2-v308.avi
 8394327c14ef0b6fbaae3b69fcc5572a *tests/data/fate/vsynth2-v308.out.rawvideo
 stddev:    0.50 PSNR: 54.10 MAXDIFF:   13 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-v408 b/tests/ref/vsynth/vsynth2-v408
index 771d579..808135f 100644
--- a/tests/ref/vsynth/vsynth2-v408
+++ b/tests/ref/vsynth/vsynth2-v408
@@ -1,4 +1,4 @@
-3efbdd666f299c23297db8e1cc137bc2 *tests/data/fate/vsynth2-v408.avi
-20282048 tests/data/fate/vsynth2-v408.avi
+01612752a44782cd99bf6399875d313c *tests/data/fate/vsynth2-v408.avi
+20282052 tests/data/fate/vsynth2-v408.avi
 36d7ca943916e1743cefa609eba0205c *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
index 0db298a..5d65d61 100644
--- a/tests/ref/vsynth/vsynth2-wmv1
+++ b/tests/ref/vsynth/vsynth2-wmv1
@@ -1,4 +1,4 @@
-ab72afaaaf155eaeea89eef5adfcf8e5 *tests/data/fate/vsynth2-wmv1.avi
-172400 tests/data/fate/vsynth2-wmv1.avi
+1e041a3ffcdbc4ebfe5e4b43c3d177e2 *tests/data/fate/vsynth2-wmv1.avi
+172404 tests/data/fate/vsynth2-wmv1.avi
 da619b78881243205024fca4c525d8cc *tests/data/fate/vsynth2-wmv1.out.rawvideo
 stddev:    6.01 PSNR: 32.54 MAXDIFF:   88 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-wmv2 b/tests/ref/vsynth/vsynth2-wmv2
index ff457e3..9608f7a 100644
--- a/tests/ref/vsynth/vsynth2-wmv2
+++ b/tests/ref/vsynth/vsynth2-wmv2
@@ -1,4 +1,4 @@
-a3f7bdaf87799839537951b40c765f9f *tests/data/fate/vsynth2-wmv2.avi
-173818 tests/data/fate/vsynth2-wmv2.avi
+a999f38b25de2ff43438802e40c1ce70 *tests/data/fate/vsynth2-wmv2.avi
+173822 tests/data/fate/vsynth2-wmv2.avi
 cfcdca2c4b183c5502cd6ec69e573127 *tests/data/fate/vsynth2-wmv2.out.rawvideo
 stddev:    6.02 PSNR: 32.54 MAXDIFF:   88 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-y41p b/tests/ref/vsynth/vsynth2-y41p
index 8afabb1..e40a0f3 100644
--- a/tests/ref/vsynth/vsynth2-y41p
+++ b/tests/ref/vsynth/vsynth2-y41p
@@ -1,4 +1,4 @@
-9abb526eb8a5cacbabf2745099c850bf *tests/data/fate/vsynth2-y41p.avi
-7610048 tests/data/fate/vsynth2-y41p.avi
+34425303a27433cfa2cf077258c21c68 *tests/data/fate/vsynth2-y41p.avi
+7610052 tests/data/fate/vsynth2-y41p.avi
 7c760febffcf1c2e43e494f38b010af1 *tests/data/fate/vsynth2-y41p.out.rawvideo
 stddev:    1.32 PSNR: 45.72 MAXDIFF:   34 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth2-yuv b/tests/ref/vsynth/vsynth2-yuv
index 0825e35..08c9593 100644
--- a/tests/ref/vsynth/vsynth2-yuv
+++ b/tests/ref/vsynth/vsynth2-yuv
@@ -1,4 +1,4 @@
-b1abb1a3febd265c9dc57eaa421fe8ff *tests/data/fate/vsynth2-yuv.avi
-7610048 tests/data/fate/vsynth2-yuv.avi
+3d7ecff63ce4863a3d299ff82d910d78 *tests/data/fate/vsynth2-yuv.avi
+7610052 tests/data/fate/vsynth2-yuv.avi
 36d7ca943916e1743cefa609eba0205c *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
index 51bd8b3..557a71a 100644
--- a/tests/ref/vsynth/vsynth2-yuv4
+++ b/tests/ref/vsynth/vsynth2-yuv4
@@ -1,4 +1,4 @@
-4074b647de926ca3a91c987bc8f49d2a *tests/data/fate/vsynth2-yuv4.avi
-7610048 tests/data/fate/vsynth2-yuv4.avi
+a62377e0d0a7eba811aada12434959f0 *tests/data/fate/vsynth2-yuv4.avi
+7610052 tests/data/fate/vsynth2-yuv4.avi
 36d7ca943916e1743cefa609eba0205c *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
index 4a29285..9dfb0d6 100644
--- a/tests/ref/vsynth/vsynth2-zlib
+++ b/tests/ref/vsynth/vsynth2-zlib
@@ -1,4 +1,4 @@
-f93b760f637c67e0945f564afc3a5f6c *tests/data/fate/vsynth2-zlib.avi
-11760516 tests/data/fate/vsynth2-zlib.avi
+8d2783483b354e7836cfc45a7241c4eb *tests/data/fate/vsynth2-zlib.avi
+11760520 tests/data/fate/vsynth2-zlib.avi
 32fae3e665407bb4317b3f90fedb903c *tests/data/fate/vsynth2-zlib.out.rawvideo
 stddev:    1.54 PSNR: 44.37 MAXDIFF:   17 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth3-amv b/tests/ref/vsynth/vsynth3-amv
index bbfba3e..d2859c7 100644
--- a/tests/ref/vsynth/vsynth3-amv
+++ b/tests/ref/vsynth/vsynth3-amv
@@ -1,4 +1,4 @@
-4d0844cd148bd9fa8155b72cc4a6e991 *tests/data/fate/vsynth3-amv.avi
-33928 tests/data/fate/vsynth3-amv.avi
+be6f013af371ab9d350e4998e86d2ea4 *tests/data/fate/vsynth3-amv.avi
+33932 tests/data/fate/vsynth3-amv.avi
 f916c620790a9cf2674391610985ae27 *tests/data/fate/vsynth3-amv.out.rawvideo
 stddev:   11.58 PSNR: 26.85 MAXDIFF:   89 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-asv1 b/tests/ref/vsynth/vsynth3-asv1
index 8486b04..0abbf78 100644
--- a/tests/ref/vsynth/vsynth3-asv1
+++ b/tests/ref/vsynth/vsynth3-asv1
@@ -1,4 +1,4 @@
-642c88813798d857d236f21bb36d8783 *tests/data/fate/vsynth3-asv1.avi
-34700 tests/data/fate/vsynth3-asv1.avi
+81eeea0d0e6219b2f381cf2100e9a12f *tests/data/fate/vsynth3-asv1.avi
+34704 tests/data/fate/vsynth3-asv1.avi
 3c8636e22a96267451684f42d7a6f608 *tests/data/fate/vsynth3-asv1.out.rawvideo
 stddev:   13.16 PSNR: 25.74 MAXDIFF:  112 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-asv2 b/tests/ref/vsynth/vsynth3-asv2
index 2a5d23b..90b8a47 100644
--- a/tests/ref/vsynth/vsynth3-asv2
+++ b/tests/ref/vsynth/vsynth3-asv2
@@ -1,4 +1,4 @@
-45f865e3d1cac1ef59ae4689f41dead5 *tests/data/fate/vsynth3-asv2.avi
-36204 tests/data/fate/vsynth3-asv2.avi
+8402fb1112fb8119c019154a472b5cd0 *tests/data/fate/vsynth3-asv2.avi
+36208 tests/data/fate/vsynth3-asv2.avi
 5469c0735b7c9279e5e8e3439fc6acab *tests/data/fate/vsynth3-asv2.out.rawvideo
 stddev:    9.07 PSNR: 28.97 MAXDIFF:   51 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-cljr b/tests/ref/vsynth/vsynth3-cljr
index 9a2daa4..53a2e38 100644
--- a/tests/ref/vsynth/vsynth3-cljr
+++ b/tests/ref/vsynth/vsynth3-cljr
@@ -1,4 +1,4 @@
-c05ee9983a4f8fe62d7270507a87655b *tests/data/fate/vsynth3-cljr.avi
-68048 tests/data/fate/vsynth3-cljr.avi
+34c26d901c5ccfcd10fd63a1494ae23a *tests/data/fate/vsynth3-cljr.avi
+68052 tests/data/fate/vsynth3-cljr.avi
 ac4c80dda332b6311beb1e8f723c13ca *tests/data/fate/vsynth3-cljr.out.rawvideo
 stddev:    7.51 PSNR: 30.61 MAXDIFF:   84 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-dnxhd-1080i-colr b/tests/ref/vsynth/vsynth3-dnxhd-1080i-colr
index 926a7b2..7cc2298 100644
--- a/tests/ref/vsynth/vsynth3-dnxhd-1080i-colr
+++ b/tests/ref/vsynth/vsynth3-dnxhd-1080i-colr
@@ -1,4 +1,4 @@
-3b06d8675f9623db77b6a42916663608 *tests/data/fate/vsynth3-dnxhd-1080i-colr.mov
+ee7a70832f37793b62642f770d988bdb *tests/data/fate/vsynth3-dnxhd-1080i-colr.mov
 3031929 tests/data/fate/vsynth3-dnxhd-1080i-colr.mov
 7dd6b261e439cda21df4f01b45336b41 *tests/data/fate/vsynth3-dnxhd-1080i-colr.out.rawvideo
 stddev:    6.92 PSNR: 31.32 MAXDIFF:   50 bytes:    86700/     8670
diff --git a/tests/ref/vsynth/vsynth3-ffv1 b/tests/ref/vsynth/vsynth3-ffv1
index cdd011a..aff0149 100644
--- a/tests/ref/vsynth/vsynth3-ffv1
+++ b/tests/ref/vsynth/vsynth3-ffv1
@@ -1,4 +1,4 @@
-b781c01d152c5a040ee71b2421b6d8e6 *tests/data/fate/vsynth3-ffv1.avi
-62190 tests/data/fate/vsynth3-ffv1.avi
+63c2cdbbdb577dfb5e43ca813f1db68b *tests/data/fate/vsynth3-ffv1.avi
+62194 tests/data/fate/vsynth3-ffv1.avi
 a038ad7c3c09f776304ef7accdea9c74 *tests/data/fate/vsynth3-ffv1.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-ffv1.0 b/tests/ref/vsynth/vsynth3-ffv1.0
index 6e2c4e0..7abc1f0 100644
--- a/tests/ref/vsynth/vsynth3-ffv1.0
+++ b/tests/ref/vsynth/vsynth3-ffv1.0
@@ -1,4 +1,4 @@
-aa9187b44d9d8ff4d0ac7b9c5301830c *tests/data/fate/vsynth3-ffv1.0.avi
-52252 tests/data/fate/vsynth3-ffv1.0.avi
+91ddf7723476e2b084253ffca69f382e *tests/data/fate/vsynth3-ffv1.0.avi
+52256 tests/data/fate/vsynth3-ffv1.0.avi
 a038ad7c3c09f776304ef7accdea9c74 *tests/data/fate/vsynth3-ffv1.0.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-ffvhuff b/tests/ref/vsynth/vsynth3-ffvhuff
index c89611f..b2772b0 100644
--- a/tests/ref/vsynth/vsynth3-ffvhuff
+++ b/tests/ref/vsynth/vsynth3-ffvhuff
@@ -1,4 +1,4 @@
-bc18700e9ce7947fe4c5ffc71457f3c1 *tests/data/fate/vsynth3-ffvhuff.avi
-90206 tests/data/fate/vsynth3-ffvhuff.avi
+9f355bfe2abe63b06e325a078151f784 *tests/data/fate/vsynth3-ffvhuff.avi
+90210 tests/data/fate/vsynth3-ffvhuff.avi
 a038ad7c3c09f776304ef7accdea9c74 *tests/data/fate/vsynth3-ffvhuff.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-ffvhuff420p12 b/tests/ref/vsynth/vsynth3-ffvhuff420p12
index 2d775d9..72d412d 100644
--- a/tests/ref/vsynth/vsynth3-ffvhuff420p12
+++ b/tests/ref/vsynth/vsynth3-ffvhuff420p12
@@ -1,4 +1,4 @@
-9b3e44ccdd28614f588804a0682db312 *tests/data/fate/vsynth3-ffvhuff420p12.avi
-175256 tests/data/fate/vsynth3-ffvhuff420p12.avi
+e5a178d75afeda6df1d4eb6f7cdfa3a0 *tests/data/fate/vsynth3-ffvhuff420p12.avi
+175260 tests/data/fate/vsynth3-ffvhuff420p12.avi
 ee95a44ccd612b5057860b43fe9775d6 *tests/data/fate/vsynth3-ffvhuff420p12.out.rawvideo
 stddev:    0.69 PSNR: 51.35 MAXDIFF:    1 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-ffvhuff422p10left b/tests/ref/vsynth/vsynth3-ffvhuff422p10left
index d62ee0f..d395829 100644
--- a/tests/ref/vsynth/vsynth3-ffvhuff422p10left
+++ b/tests/ref/vsynth/vsynth3-ffvhuff422p10left
@@ -1,4 +1,4 @@
-5afec2536440c892919a1569c7109858 *tests/data/fate/vsynth3-ffvhuff422p10left.avi
-173548 tests/data/fate/vsynth3-ffvhuff422p10left.avi
+37e15f58570aeeafc86972524756136a *tests/data/fate/vsynth3-ffvhuff422p10left.avi
+173552 tests/data/fate/vsynth3-ffvhuff422p10left.avi
 0cf7cf68724fa5146b1667e4fa08b0e1 *tests/data/fate/vsynth3-ffvhuff422p10left.out.rawvideo
 stddev:    2.12 PSNR: 41.58 MAXDIFF:   26 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-ffvhuff444 b/tests/ref/vsynth/vsynth3-ffvhuff444
index 8446a7f..37e20e1 100644
--- a/tests/ref/vsynth/vsynth3-ffvhuff444
+++ b/tests/ref/vsynth/vsynth3-ffvhuff444
@@ -1,4 +1,4 @@
-134851e6f9702e83c4c9aa6e5ff1eaa4 *tests/data/fate/vsynth3-ffvhuff444.avi
-151362 tests/data/fate/vsynth3-ffvhuff444.avi
+dc07c964dad37768d1a021afe7c3612e *tests/data/fate/vsynth3-ffvhuff444.avi
+151366 tests/data/fate/vsynth3-ffvhuff444.avi
 02a85ec07377df6b483281038f8882ee *tests/data/fate/vsynth3-ffvhuff444.out.rawvideo
 stddev:    3.06 PSNR: 38.40 MAXDIFF:   40 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-ffvhuff444p16 b/tests/ref/vsynth/vsynth3-ffvhuff444p16
index 842104f..0f4bc77 100644
--- a/tests/ref/vsynth/vsynth3-ffvhuff444p16
+++ b/tests/ref/vsynth/vsynth3-ffvhuff444p16
@@ -1,4 +1,4 @@
-1a6e53646d0988bd67ced92923439e51 *tests/data/fate/vsynth3-ffvhuff444p16.avi
-320084 tests/data/fate/vsynth3-ffvhuff444p16.avi
+93571f2ddceadebd534c6d76fe93fc93 *tests/data/fate/vsynth3-ffvhuff444p16.avi
+320088 tests/data/fate/vsynth3-ffvhuff444p16.avi
 e5933e1e6dbacddb78e6d90cd5ed2b5d *tests/data/fate/vsynth3-ffvhuff444p16.out.rawvideo
 stddev:    3.06 PSNR: 38.40 MAXDIFF:   40 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-huffyuv b/tests/ref/vsynth/vsynth3-huffyuv
index 0a16b65..2d79e56 100644
--- a/tests/ref/vsynth/vsynth3-huffyuv
+++ b/tests/ref/vsynth/vsynth3-huffyuv
@@ -1,4 +1,4 @@
-27cd1ec1151b7456117f98a8cdf281cd *tests/data/fate/vsynth3-huffyuv.avi
-116346 tests/data/fate/vsynth3-huffyuv.avi
+4468635f2c221d7744cc6f87ff9e9b48 *tests/data/fate/vsynth3-huffyuv.avi
+116350 tests/data/fate/vsynth3-huffyuv.avi
 a038ad7c3c09f776304ef7accdea9c74 *tests/data/fate/vsynth3-huffyuv.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-huffyuvbgr24 b/tests/ref/vsynth/vsynth3-huffyuvbgr24
index 95f4422..91cd51e 100644
--- a/tests/ref/vsynth/vsynth3-huffyuvbgr24
+++ b/tests/ref/vsynth/vsynth3-huffyuvbgr24
@@ -1,4 +1,4 @@
-a7bf0c82277d59d425ebe4af93f75e27 *tests/data/fate/vsynth3-huffyuvbgr24.avi
-165154 tests/data/fate/vsynth3-huffyuvbgr24.avi
+758d6b72a396743c096b003f41f54023 *tests/data/fate/vsynth3-huffyuvbgr24.avi
+165158 tests/data/fate/vsynth3-huffyuvbgr24.avi
 5d031d2e891b13593b8cd79e63d083b4 *tests/data/fate/vsynth3-huffyuvbgr24.out.rawvideo
 stddev:    3.23 PSNR: 37.92 MAXDIFF:   50 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-huffyuvbgra b/tests/ref/vsynth/vsynth3-huffyuvbgra
index 32eecd4..c155f74 100644
--- a/tests/ref/vsynth/vsynth3-huffyuvbgra
+++ b/tests/ref/vsynth/vsynth3-huffyuvbgra
@@ -1,4 +1,4 @@
-9d360ce029b5ec86f0f6c80c44edf9bd *tests/data/fate/vsynth3-huffyuvbgra.avi
-179598 tests/data/fate/vsynth3-huffyuvbgra.avi
+79a2b229d1c105b4b20de226f254f4b2 *tests/data/fate/vsynth3-huffyuvbgra.avi
+179602 tests/data/fate/vsynth3-huffyuvbgra.avi
 5d031d2e891b13593b8cd79e63d083b4 *tests/data/fate/vsynth3-huffyuvbgra.out.rawvideo
 stddev:    3.23 PSNR: 37.92 MAXDIFF:   50 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-jpeg2000 b/tests/ref/vsynth/vsynth3-jpeg2000
index 6b5f110..d4015d2 100644
--- a/tests/ref/vsynth/vsynth3-jpeg2000
+++ b/tests/ref/vsynth/vsynth3-jpeg2000
@@ -1,4 +1,4 @@
-1c49dca7b2d828b9a551bf66f3324f3d *tests/data/fate/vsynth3-jpeg2000.avi
-63768 tests/data/fate/vsynth3-jpeg2000.avi
+7ea4e3901817f06a3de59ee70836f5d9 *tests/data/fate/vsynth3-jpeg2000.avi
+63772 tests/data/fate/vsynth3-jpeg2000.avi
 11b954cc1b0091399fa4342a6bb432b2 *tests/data/fate/vsynth3-jpeg2000.out.rawvideo
 stddev:    5.50 PSNR: 33.31 MAXDIFF:   48 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-jpeg2000-97 b/tests/ref/vsynth/vsynth3-jpeg2000-97
index 1087241..d1695de 100644
--- a/tests/ref/vsynth/vsynth3-jpeg2000-97
+++ b/tests/ref/vsynth/vsynth3-jpeg2000-97
@@ -1,4 +1,4 @@
-9ce2c4690cbc85aae9e9e5227e74eb94 *tests/data/fate/vsynth3-jpeg2000-97.avi
-65360 tests/data/fate/vsynth3-jpeg2000-97.avi
+3e2f1e7d009d05e2bb9e8c3b10fab134 *tests/data/fate/vsynth3-jpeg2000-97.avi
+65364 tests/data/fate/vsynth3-jpeg2000-97.avi
 f9dad7a31175e400ca35de60aec826fd *tests/data/fate/vsynth3-jpeg2000-97.out.rawvideo
 stddev:    6.27 PSNR: 32.17 MAXDIFF:   52 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-jpegls b/tests/ref/vsynth/vsynth3-jpegls
index b035373..da005ec 100644
--- a/tests/ref/vsynth/vsynth3-jpegls
+++ b/tests/ref/vsynth/vsynth3-jpegls
@@ -1,4 +1,4 @@
-13bf416e04554609ddc2830912ff1d89 *tests/data/fate/vsynth3-jpegls.avi
-133164 tests/data/fate/vsynth3-jpegls.avi
+7651480a59692e77e346f9cc4d2fdb96 *tests/data/fate/vsynth3-jpegls.avi
+133168 tests/data/fate/vsynth3-jpegls.avi
 faa660b0ecaaab1bf9b5d7284019aa01 *tests/data/fate/vsynth3-jpegls.out.rawvideo
 stddev:    2.97 PSNR: 38.67 MAXDIFF:   49 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-ljpeg b/tests/ref/vsynth/vsynth3-ljpeg
index 47db0c1..b104c6a 100644
--- a/tests/ref/vsynth/vsynth3-ljpeg
+++ b/tests/ref/vsynth/vsynth3-ljpeg
@@ -1,4 +1,4 @@
-39cd774ffe47c804f2f58d5bbcf7b0a5 *tests/data/fate/vsynth3-ljpeg.avi
-105840 tests/data/fate/vsynth3-ljpeg.avi
+d3cd7906eecc70b882b7cae300d08646 *tests/data/fate/vsynth3-ljpeg.avi
+105844 tests/data/fate/vsynth3-ljpeg.avi
 a038ad7c3c09f776304ef7accdea9c74 *tests/data/fate/vsynth3-ljpeg.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-mjpeg b/tests/ref/vsynth/vsynth3-mjpeg
index 25036c8..c69338f 100644
--- a/tests/ref/vsynth/vsynth3-mjpeg
+++ b/tests/ref/vsynth/vsynth3-mjpeg
@@ -1,4 +1,4 @@
-cf68ecc19e6c07d2a0c211e6ad1e3d9f *tests/data/fate/vsynth3-mjpeg.avi
-64804 tests/data/fate/vsynth3-mjpeg.avi
+7d7a2fa8559a3652db52b7a70267d1a3 *tests/data/fate/vsynth3-mjpeg.avi
+64808 tests/data/fate/vsynth3-mjpeg.avi
 c4fe7a2669afbd96c640748693fc4e30 *tests/data/fate/vsynth3-mjpeg.out.rawvideo
 stddev:    8.60 PSNR: 29.43 MAXDIFF:   58 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-mjpeg-422 b/tests/ref/vsynth/vsynth3-mjpeg-422
index 23c58bb..b50e479 100644
--- a/tests/ref/vsynth/vsynth3-mjpeg-422
+++ b/tests/ref/vsynth/vsynth3-mjpeg-422
@@ -1,4 +1,4 @@
-c1f42031676078a7cfc38a7eb53c89e8 *tests/data/fate/vsynth3-mjpeg-422.avi
-69458 tests/data/fate/vsynth3-mjpeg-422.avi
+34c57632d23c4322d2e508368e7c8e36 *tests/data/fate/vsynth3-mjpeg-422.avi
+69462 tests/data/fate/vsynth3-mjpeg-422.avi
 a332893cb0603f2f505fe5d3bf105519 *tests/data/fate/vsynth3-mjpeg-422.out.rawvideo
 stddev:    8.23 PSNR: 29.82 MAXDIFF:   58 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-mjpeg-444 b/tests/ref/vsynth/vsynth3-mjpeg-444
index d17df66..d701f66 100644
--- a/tests/ref/vsynth/vsynth3-mjpeg-444
+++ b/tests/ref/vsynth/vsynth3-mjpeg-444
@@ -1,4 +1,4 @@
-893c830a9635aaf686f53372cbe5e0ed *tests/data/fate/vsynth3-mjpeg-444.avi
-70584 tests/data/fate/vsynth3-mjpeg-444.avi
+0900258953e90ab97a95ccaccb7b0d8a *tests/data/fate/vsynth3-mjpeg-444.avi
+70588 tests/data/fate/vsynth3-mjpeg-444.avi
 79a901f2ed85d82cf1c674fab3d3ef72 *tests/data/fate/vsynth3-mjpeg-444.out.rawvideo
 stddev:    8.21 PSNR: 29.84 MAXDIFF:   58 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-mjpeg-trell b/tests/ref/vsynth/vsynth3-mjpeg-trell
new file mode 100644
index 0000000..9178d02
--- /dev/null
+++ b/tests/ref/vsynth/vsynth3-mjpeg-trell
@@ -0,0 +1,4 @@
+6f815acb8fce5458561aa902703e6189 *tests/data/fate/vsynth3-mjpeg-trell.avi
+63994 tests/data/fate/vsynth3-mjpeg-trell.avi
+4fed1e12c80df7b67df292b153c3cf16 *tests/data/fate/vsynth3-mjpeg-trell.out.rawvideo
+stddev:    8.27 PSNR: 29.77 MAXDIFF:   61 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-mpeg4-adap b/tests/ref/vsynth/vsynth3-mpeg4-adap
index ec5b9e2..0942f83 100644
--- a/tests/ref/vsynth/vsynth3-mpeg4-adap
+++ b/tests/ref/vsynth/vsynth3-mpeg4-adap
@@ -1,4 +1,4 @@
-40a36d85d24df09ba8695ab4a16e0843 *tests/data/fate/vsynth3-mpeg4-adap.avi
-43702 tests/data/fate/vsynth3-mpeg4-adap.avi
+c16e5c2436ca9953517eadba562768e9 *tests/data/fate/vsynth3-mpeg4-adap.avi
+43706 tests/data/fate/vsynth3-mpeg4-adap.avi
 b42b614e19e7c4859fca1af6d4e36eae *tests/data/fate/vsynth3-mpeg4-adap.out.rawvideo
 stddev:    5.48 PSNR: 33.34 MAXDIFF:   53 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-mpeg4-adv b/tests/ref/vsynth/vsynth3-mpeg4-adv
index 7274207..7a9ecb6 100644
--- a/tests/ref/vsynth/vsynth3-mpeg4-adv
+++ b/tests/ref/vsynth/vsynth3-mpeg4-adv
@@ -1,4 +1,4 @@
-c3b4a5d4d642b6fea981b4f762a8081b *tests/data/fate/vsynth3-mpeg4-adv.avi
-32292 tests/data/fate/vsynth3-mpeg4-adv.avi
+140ecea2eb7d85cbe647adb666f09aa5 *tests/data/fate/vsynth3-mpeg4-adv.avi
+32296 tests/data/fate/vsynth3-mpeg4-adv.avi
 9f80b96af57556d53ce44008bd687f55 *tests/data/fate/vsynth3-mpeg4-adv.out.rawvideo
 stddev:    7.60 PSNR: 30.51 MAXDIFF:   63 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-mpeg4-error b/tests/ref/vsynth/vsynth3-mpeg4-error
index 4f54a60..c33dad9 100644
--- a/tests/ref/vsynth/vsynth3-mpeg4-error
+++ b/tests/ref/vsynth/vsynth3-mpeg4-error
@@ -1,4 +1,4 @@
-cee34cadd91b861d424f493acb9289ab *tests/data/fate/vsynth3-mpeg4-error.avi
-38208 tests/data/fate/vsynth3-mpeg4-error.avi
+7f1fb64c5a37be6e5606f92adb84f273 *tests/data/fate/vsynth3-mpeg4-error.avi
+38212 tests/data/fate/vsynth3-mpeg4-error.avi
 f9fd24e26f4ffb5ed597b9bbf0ea731b *tests/data/fate/vsynth3-mpeg4-error.out.rawvideo
 stddev:    6.06 PSNR: 32.47 MAXDIFF:   54 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-mpeg4-nr b/tests/ref/vsynth/vsynth3-mpeg4-nr
index 8cb1032..590e133 100644
--- a/tests/ref/vsynth/vsynth3-mpeg4-nr
+++ b/tests/ref/vsynth/vsynth3-mpeg4-nr
@@ -1,4 +1,4 @@
-b0f9c0997901e00ca2582ebe20f120e5 *tests/data/fate/vsynth3-mpeg4-nr.avi
-36496 tests/data/fate/vsynth3-mpeg4-nr.avi
+62790bdb7c2bb4da94dba992ea967fc8 *tests/data/fate/vsynth3-mpeg4-nr.avi
+36500 tests/data/fate/vsynth3-mpeg4-nr.avi
 d0ad9918a12019dd2eacfb804d1f7e78 *tests/data/fate/vsynth3-mpeg4-nr.out.rawvideo
 stddev:    8.27 PSNR: 29.78 MAXDIFF:   70 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-mpeg4-nsse b/tests/ref/vsynth/vsynth3-mpeg4-nsse
index f96b1c6..6ad377c 100644
--- a/tests/ref/vsynth/vsynth3-mpeg4-nsse
+++ b/tests/ref/vsynth/vsynth3-mpeg4-nsse
@@ -1,4 +1,4 @@
-4b2c5176f1fc2134612f3b512e8f936a *tests/data/fate/vsynth3-mpeg4-nsse.avi
-41976 tests/data/fate/vsynth3-mpeg4-nsse.avi
+88b1aa2dcea6a45c527487ba8f441feb *tests/data/fate/vsynth3-mpeg4-nsse.avi
+41980 tests/data/fate/vsynth3-mpeg4-nsse.avi
 69d86dec0d73e00608e03855a79dbdc0 *tests/data/fate/vsynth3-mpeg4-nsse.out.rawvideo
 stddev:    6.70 PSNR: 31.60 MAXDIFF:   68 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-mpeg4-qpel b/tests/ref/vsynth/vsynth3-mpeg4-qpel
index f17474f..2d91586 100644
--- a/tests/ref/vsynth/vsynth3-mpeg4-qpel
+++ b/tests/ref/vsynth/vsynth3-mpeg4-qpel
@@ -1,4 +1,4 @@
-5e4bb1c9bd845896891ca5fe418948a3 *tests/data/fate/vsynth3-mpeg4-qpel.avi
-42618 tests/data/fate/vsynth3-mpeg4-qpel.avi
+8e60ed0013bfc28f48ed4d826fd26a6a *tests/data/fate/vsynth3-mpeg4-qpel.avi
+42622 tests/data/fate/vsynth3-mpeg4-qpel.avi
 50af37a5ae05f0af34bd56dcef997c8d *tests/data/fate/vsynth3-mpeg4-qpel.out.rawvideo
 stddev:    6.59 PSNR: 31.75 MAXDIFF:   54 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-mpeg4-qprd b/tests/ref/vsynth/vsynth3-mpeg4-qprd
index 1691e1f..db6e58d 100644
--- a/tests/ref/vsynth/vsynth3-mpeg4-qprd
+++ b/tests/ref/vsynth/vsynth3-mpeg4-qprd
@@ -1,4 +1,4 @@
-af2517de1718262000b76c1da0bd100d *tests/data/fate/vsynth3-mpeg4-qprd.avi
-61826 tests/data/fate/vsynth3-mpeg4-qprd.avi
+e3b49e22e8acbd21f34a2909bb35075e *tests/data/fate/vsynth3-mpeg4-qprd.avi
+61830 tests/data/fate/vsynth3-mpeg4-qprd.avi
 c59f2bead1c81b23fabc0a740048b110 *tests/data/fate/vsynth3-mpeg4-qprd.out.rawvideo
 stddev:    2.68 PSNR: 39.55 MAXDIFF:   27 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-mpeg4-rc b/tests/ref/vsynth/vsynth3-mpeg4-rc
index 36c771c..fae0677 100644
--- a/tests/ref/vsynth/vsynth3-mpeg4-rc
+++ b/tests/ref/vsynth/vsynth3-mpeg4-rc
@@ -1,4 +1,4 @@
-ddc944ea93e7e87bfae36bb85ee36c91 *tests/data/fate/vsynth3-mpeg4-rc.avi
-81088 tests/data/fate/vsynth3-mpeg4-rc.avi
+5b51e8f91fecd621cd3aa5d687659fbc *tests/data/fate/vsynth3-mpeg4-rc.avi
+81092 tests/data/fate/vsynth3-mpeg4-rc.avi
 07ba5baf141a24561f7dba43645a3400 *tests/data/fate/vsynth3-mpeg4-rc.out.rawvideo
 stddev:    2.62 PSNR: 39.74 MAXDIFF:   23 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-mpeg4-thread b/tests/ref/vsynth/vsynth3-mpeg4-thread
index 2b59322..d618031 100644
--- a/tests/ref/vsynth/vsynth3-mpeg4-thread
+++ b/tests/ref/vsynth/vsynth3-mpeg4-thread
@@ -1,4 +1,4 @@
-601ac957b2a8cc4d9f5812824b7d1e0d *tests/data/fate/vsynth3-mpeg4-thread.avi
-74578 tests/data/fate/vsynth3-mpeg4-thread.avi
+b071631783ee76df554161fc3966f567 *tests/data/fate/vsynth3-mpeg4-thread.avi
+74582 tests/data/fate/vsynth3-mpeg4-thread.avi
 7eb4d38b01c71064406ce6705c471439 *tests/data/fate/vsynth3-mpeg4-thread.out.rawvideo
 stddev:    1.99 PSNR: 42.12 MAXDIFF:   18 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-mpng b/tests/ref/vsynth/vsynth3-mpng
index 2a112a7..e708a60 100644
--- a/tests/ref/vsynth/vsynth3-mpng
+++ b/tests/ref/vsynth/vsynth3-mpng
@@ -1,4 +1,4 @@
-f1a9b596c743645e5518a41e4fe2b043 *tests/data/fate/vsynth3-mpng.avi
-179800 tests/data/fate/vsynth3-mpng.avi
+3f64b66a1f46e31d45dd7f5514422ed0 *tests/data/fate/vsynth3-mpng.avi
+179804 tests/data/fate/vsynth3-mpng.avi
 693aff10c094f8bd31693f74cf79d2b2 *tests/data/fate/vsynth3-mpng.out.rawvideo
 stddev:    3.67 PSNR: 36.82 MAXDIFF:   43 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-msmpeg4 b/tests/ref/vsynth/vsynth3-msmpeg4
index dc653fc..a73cb2c 100644
--- a/tests/ref/vsynth/vsynth3-msmpeg4
+++ b/tests/ref/vsynth/vsynth3-msmpeg4
@@ -1,4 +1,4 @@
-68d0838cf0e66a3092acaf347061cea8 *tests/data/fate/vsynth3-msmpeg4.avi
-32440 tests/data/fate/vsynth3-msmpeg4.avi
+31c27687a8bda16ef9cafc9b43f1a016 *tests/data/fate/vsynth3-msmpeg4.avi
+32444 tests/data/fate/vsynth3-msmpeg4.avi
 216b15fb02691b662d0f0112507d5583 *tests/data/fate/vsynth3-msmpeg4.out.rawvideo
 stddev:    9.63 PSNR: 28.45 MAXDIFF:  104 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-msmpeg4v2 b/tests/ref/vsynth/vsynth3-msmpeg4v2
index 58d6e4f2..81854f1 100644
--- a/tests/ref/vsynth/vsynth3-msmpeg4v2
+++ b/tests/ref/vsynth/vsynth3-msmpeg4v2
@@ -1,4 +1,4 @@
-dfba0b605760d087cb6f5c0ce45f671a *tests/data/fate/vsynth3-msmpeg4v2.avi
-32626 tests/data/fate/vsynth3-msmpeg4v2.avi
+206b95674f0d7d77b894c17bf81b6b2d *tests/data/fate/vsynth3-msmpeg4v2.avi
+32630 tests/data/fate/vsynth3-msmpeg4v2.avi
 575bfa06fd3f3944faf92205fabf5f22 *tests/data/fate/vsynth3-msmpeg4v2.out.rawvideo
 stddev:    9.66 PSNR: 28.43 MAXDIFF:   86 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-r210 b/tests/ref/vsynth/vsynth3-r210
index 8362ee5..cdbdb28 100644
--- a/tests/ref/vsynth/vsynth3-r210
+++ b/tests/ref/vsynth/vsynth3-r210
@@ -1,4 +1,4 @@
-5f6e0ba5fc9a1b1440e80aebcb41d57a *tests/data/fate/vsynth3-r210.avi
-442048 tests/data/fate/vsynth3-r210.avi
+40b93804d521e2b7c82a3060dec81221 *tests/data/fate/vsynth3-r210.avi
+442052 tests/data/fate/vsynth3-r210.avi
 e1d882babc8754f7418aa91ce48f7ab0 *tests/data/fate/vsynth3-r210.out.rawvideo
 stddev:    3.48 PSNR: 37.28 MAXDIFF:   42 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-rgb b/tests/ref/vsynth/vsynth3-rgb
index f407523..c0a8563 100644
--- a/tests/ref/vsynth/vsynth3-rgb
+++ b/tests/ref/vsynth/vsynth3-rgb
@@ -1,4 +1,4 @@
-7b20b20734352d33b18b802513f5fc47 *tests/data/fate/vsynth3-rgb.avi
-180248 tests/data/fate/vsynth3-rgb.avi
+a2cb86007b8945e2d1399b56585b983a *tests/data/fate/vsynth3-rgb.avi
+180252 tests/data/fate/vsynth3-rgb.avi
 693aff10c094f8bd31693f74cf79d2b2 *tests/data/fate/vsynth3-rgb.out.rawvideo
 stddev:    3.67 PSNR: 36.82 MAXDIFF:   43 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-v210 b/tests/ref/vsynth/vsynth3-v210
index 0eaf041..658f90c 100644
--- a/tests/ref/vsynth/vsynth3-v210
+++ b/tests/ref/vsynth/vsynth3-v210
@@ -1,4 +1,4 @@
-6618ab86d047f4fb8fdd2d633888b20b *tests/data/fate/vsynth3-v210.avi
-224448 tests/data/fate/vsynth3-v210.avi
+df0ae6cafc1aedbf17176eb44a732e4d *tests/data/fate/vsynth3-v210.avi
+224452 tests/data/fate/vsynth3-v210.avi
 198ffb24c06927d8aaac5e59d81a0934 *tests/data/fate/vsynth3-v210.out.rawvideo
 stddev:    2.11 PSNR: 41.61 MAXDIFF:   27 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-v308 b/tests/ref/vsynth/vsynth3-v308
index c70678c..347d475 100644
--- a/tests/ref/vsynth/vsynth3-v308
+++ b/tests/ref/vsynth/vsynth3-v308
@@ -1,4 +1,4 @@
-53dacfdcf280d58b465da71583f4af26 *tests/data/fate/vsynth3-v308.avi
-180248 tests/data/fate/vsynth3-v308.avi
+073e24cc00a27436e97e0b242d4fd077 *tests/data/fate/vsynth3-v308.avi
+180252 tests/data/fate/vsynth3-v308.avi
 02a85ec07377df6b483281038f8882ee *tests/data/fate/vsynth3-v308.out.rawvideo
 stddev:    3.06 PSNR: 38.40 MAXDIFF:   40 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-v408 b/tests/ref/vsynth/vsynth3-v408
index da87e81..2da09e1 100644
--- a/tests/ref/vsynth/vsynth3-v408
+++ b/tests/ref/vsynth/vsynth3-v408
@@ -1,4 +1,4 @@
-ac8ea8d8f38b5c6b76c2fef9667a172d *tests/data/fate/vsynth3-v408.avi
-238048 tests/data/fate/vsynth3-v408.avi
+e74a1abf73b9df90f5103d901b37185f *tests/data/fate/vsynth3-v408.avi
+238052 tests/data/fate/vsynth3-v408.avi
 a038ad7c3c09f776304ef7accdea9c74 *tests/data/fate/vsynth3-v408.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-wmv1 b/tests/ref/vsynth/vsynth3-wmv1
index 568d3cf..4344acd 100644
--- a/tests/ref/vsynth/vsynth3-wmv1
+++ b/tests/ref/vsynth/vsynth3-wmv1
@@ -1,4 +1,4 @@
-b13831403f2dfdf3e5e6d33b03dbc687 *tests/data/fate/vsynth3-wmv1.avi
-32654 tests/data/fate/vsynth3-wmv1.avi
+de255d5f4838784e18af6ff86cf97e0b *tests/data/fate/vsynth3-wmv1.avi
+32658 tests/data/fate/vsynth3-wmv1.avi
 4dafe3c433c7f48c6c9e56d59ca0f7c3 *tests/data/fate/vsynth3-wmv1.out.rawvideo
 stddev:    9.65 PSNR: 28.44 MAXDIFF:   91 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-wmv2 b/tests/ref/vsynth/vsynth3-wmv2
index 9d20b7b..2276e7e 100644
--- a/tests/ref/vsynth/vsynth3-wmv2
+++ b/tests/ref/vsynth/vsynth3-wmv2
@@ -1,4 +1,4 @@
-1a8a90c91240f84d0ceca4f20ae4be27 *tests/data/fate/vsynth3-wmv2.avi
-33976 tests/data/fate/vsynth3-wmv2.avi
+d9c2a235b43d1704bb41c73f285d86a8 *tests/data/fate/vsynth3-wmv2.avi
+33980 tests/data/fate/vsynth3-wmv2.avi
 691e00ebbb56c061f74ade70088102e7 *tests/data/fate/vsynth3-wmv2.out.rawvideo
 stddev:    9.60 PSNR: 28.48 MAXDIFF:   81 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-yuv b/tests/ref/vsynth/vsynth3-yuv
index 29abb30..aa2cf2f 100644
--- a/tests/ref/vsynth/vsynth3-yuv
+++ b/tests/ref/vsynth/vsynth3-yuv
@@ -1,4 +1,4 @@
-d0a6f0188d9cc70919865ebc59cc0179 *tests/data/fate/vsynth3-yuv.avi
-93548 tests/data/fate/vsynth3-yuv.avi
+080401647f4b08df4fb44a253c914cc0 *tests/data/fate/vsynth3-yuv.avi
+93552 tests/data/fate/vsynth3-yuv.avi
 a038ad7c3c09f776304ef7accdea9c74 *tests/data/fate/vsynth3-yuv.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-yuv4 b/tests/ref/vsynth/vsynth3-yuv4
index 70f8274..7c7b54e 100644
--- a/tests/ref/vsynth/vsynth3-yuv4
+++ b/tests/ref/vsynth/vsynth3-yuv4
@@ -1,4 +1,4 @@
-4b5196292069c5301446b546d0148783 *tests/data/fate/vsynth3-yuv4.avi
-93548 tests/data/fate/vsynth3-yuv4.avi
+88bcfebb7710fc17137459c104d7de4e *tests/data/fate/vsynth3-yuv4.avi
+93552 tests/data/fate/vsynth3-yuv4.avi
 a038ad7c3c09f776304ef7accdea9c74 *tests/data/fate/vsynth3-yuv4.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth3-zlib b/tests/ref/vsynth/vsynth3-zlib
index e69e289..55d65f3 100644
--- a/tests/ref/vsynth/vsynth3-zlib
+++ b/tests/ref/vsynth/vsynth3-zlib
@@ -1,4 +1,4 @@
-278541a159accf11fec8914cad41e85c *tests/data/fate/vsynth3-zlib.avi
-174878 tests/data/fate/vsynth3-zlib.avi
+d3705acfc90b16968d0d4a3ac56b049c *tests/data/fate/vsynth3-zlib.avi
+174882 tests/data/fate/vsynth3-zlib.avi
 693aff10c094f8bd31693f74cf79d2b2 *tests/data/fate/vsynth3-zlib.out.rawvideo
 stddev:    3.67 PSNR: 36.82 MAXDIFF:   43 bytes:    86700/    86700
diff --git a/tests/ref/vsynth/vsynth_lena-amv b/tests/ref/vsynth/vsynth_lena-amv
index d2d1288..e4bf725 100644
--- a/tests/ref/vsynth/vsynth_lena-amv
+++ b/tests/ref/vsynth/vsynth_lena-amv
@@ -1,4 +1,4 @@
-e0d0da8cf786616eff2e88c45644c902 *tests/data/fate/vsynth_lena-amv.avi
-761976 tests/data/fate/vsynth_lena-amv.avi
+49552a6ac39f27568fab1a4644aa5ddd *tests/data/fate/vsynth_lena-amv.avi
+761980 tests/data/fate/vsynth_lena-amv.avi
 f256ad9feefb499c6569d06d868eb496 *tests/data/fate/vsynth_lena-amv.out.rawvideo
 stddev:    4.30 PSNR: 35.46 MAXDIFF:   65 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-asv1 b/tests/ref/vsynth/vsynth_lena-asv1
index 7859d98..d64bf49 100644
--- a/tests/ref/vsynth/vsynth_lena-asv1
+++ b/tests/ref/vsynth/vsynth_lena-asv1
@@ -1,4 +1,4 @@
-bffe7188b4b5c3ff76c75561d0bebd77 *tests/data/fate/vsynth_lena-asv1.avi
-689416 tests/data/fate/vsynth_lena-asv1.avi
+fc74737b0ea7de84609e1207d0ee9d93 *tests/data/fate/vsynth_lena-asv1.avi
+689420 tests/data/fate/vsynth_lena-asv1.avi
 a7cdefad200f48ab308c746461a8792e *tests/data/fate/vsynth_lena-asv1.out.rawvideo
 stddev:    5.07 PSNR: 34.03 MAXDIFF:   70 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-asv2 b/tests/ref/vsynth/vsynth_lena-asv2
index f9d6ac6..bebb5ac 100644
--- a/tests/ref/vsynth/vsynth_lena-asv2
+++ b/tests/ref/vsynth/vsynth_lena-asv2
@@ -1,4 +1,4 @@
-f8c3b9899bbd9545757fac0c7ecf4e34 *tests/data/fate/vsynth_lena-asv2.avi
-675584 tests/data/fate/vsynth_lena-asv2.avi
+36b7ff52186fd87027f57f880eb67fd7 *tests/data/fate/vsynth_lena-asv2.avi
+675588 tests/data/fate/vsynth_lena-asv2.avi
 5990db66c7ac0bbe2f98ec2770c1bf3b *tests/data/fate/vsynth_lena-asv2.out.rawvideo
 stddev:    4.57 PSNR: 34.93 MAXDIFF:   47 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-cljr b/tests/ref/vsynth/vsynth_lena-cljr
index e841001..6ee6150 100644
--- a/tests/ref/vsynth/vsynth_lena-cljr
+++ b/tests/ref/vsynth/vsynth_lena-cljr
@@ -1,4 +1,4 @@
-7bfd989038611212a80b5b050bb78ea7 *tests/data/fate/vsynth_lena-cljr.avi
-5075648 tests/data/fate/vsynth_lena-cljr.avi
+e3579621c868e464da096a41af0674e4 *tests/data/fate/vsynth_lena-cljr.avi
+5075652 tests/data/fate/vsynth_lena-cljr.avi
 965c4a134144b30b24d6d138b03ddb8c *tests/data/fate/vsynth_lena-cljr.out.rawvideo
 stddev:    3.29 PSNR: 37.76 MAXDIFF:   23 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-dnxhd-1080i b/tests/ref/vsynth/vsynth_lena-dnxhd-1080i
index 5211b36..3693d57 100644
--- a/tests/ref/vsynth/vsynth_lena-dnxhd-1080i
+++ b/tests/ref/vsynth/vsynth_lena-dnxhd-1080i
@@ -1,4 +1,4 @@
-d680a5eed77c5b8dc6b5ef3bcf6e87e8 *tests/data/fate/vsynth_lena-dnxhd-1080i.mov
+f7412afbcb4454692f7492f6710189e3 *tests/data/fate/vsynth_lena-dnxhd-1080i.mov
 3031911 tests/data/fate/vsynth_lena-dnxhd-1080i.mov
 744ba46da5d4c19a28562ea31061d170 *tests/data/fate/vsynth_lena-dnxhd-1080i.out.rawvideo
 stddev:    1.31 PSNR: 45.77 MAXDIFF:   23 bytes:  7603200/   760320
diff --git a/tests/ref/vsynth/vsynth_lena-dnxhd-1080i-colr b/tests/ref/vsynth/vsynth_lena-dnxhd-1080i-colr
index f9ce4cf..1889786 100644
--- a/tests/ref/vsynth/vsynth_lena-dnxhd-1080i-colr
+++ b/tests/ref/vsynth/vsynth_lena-dnxhd-1080i-colr
@@ -1,4 +1,4 @@
-4deae1b3d9a5c8fbd28075e8dca0034e *tests/data/fate/vsynth_lena-dnxhd-1080i-colr.mov
+5ba3ddb58b10e5f0069cb4f82d594695 *tests/data/fate/vsynth_lena-dnxhd-1080i-colr.mov
 3031929 tests/data/fate/vsynth_lena-dnxhd-1080i-colr.mov
 864c3d5f49d9edf66ce8f82a2a6725f6 *tests/data/fate/vsynth_lena-dnxhd-1080i-colr.out.rawvideo
 stddev:    1.36 PSNR: 45.45 MAXDIFF:   22 bytes:  7603200/   760320
diff --git a/tests/ref/vsynth/vsynth_lena-ffv1 b/tests/ref/vsynth/vsynth_lena-ffv1
index 154f455..5d63381 100644
--- a/tests/ref/vsynth/vsynth_lena-ffv1
+++ b/tests/ref/vsynth/vsynth_lena-ffv1
@@ -1,4 +1,4 @@
-9e091bee097632ef7106d3bade12b81b *tests/data/fate/vsynth_lena-ffv1.avi
-3547788 tests/data/fate/vsynth_lena-ffv1.avi
+e756081d98f11f303a06897ff6b563b5 *tests/data/fate/vsynth_lena-ffv1.avi
+3547792 tests/data/fate/vsynth_lena-ffv1.avi
 dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth_lena-ffv1.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-ffv1.0 b/tests/ref/vsynth/vsynth_lena-ffv1.0
index 059170a..58b1061 100644
--- a/tests/ref/vsynth/vsynth_lena-ffv1.0
+++ b/tests/ref/vsynth/vsynth_lena-ffv1.0
@@ -1,4 +1,4 @@
-114950628c091cd830d9e66e74f6bca2 *tests/data/fate/vsynth_lena-ffv1.0.avi
-3525792 tests/data/fate/vsynth_lena-ffv1.0.avi
+ad518c7014bdd6a72514a79a9102f64f *tests/data/fate/vsynth_lena-ffv1.0.avi
+3525796 tests/data/fate/vsynth_lena-ffv1.0.avi
 dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth_lena-ffv1.0.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-ffvhuff b/tests/ref/vsynth/vsynth_lena-ffvhuff
index 8a64606..88711a5 100644
--- a/tests/ref/vsynth/vsynth_lena-ffvhuff
+++ b/tests/ref/vsynth/vsynth_lena-ffvhuff
@@ -1,4 +1,4 @@
-7cb61df06d2cb4659ceb8d73c4822aaf *tests/data/fate/vsynth_lena-ffvhuff.avi
-4845022 tests/data/fate/vsynth_lena-ffvhuff.avi
+c8bcad0cd3babf63ce96525f6c11ae6e *tests/data/fate/vsynth_lena-ffvhuff.avi
+4845026 tests/data/fate/vsynth_lena-ffvhuff.avi
 dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth_lena-ffvhuff.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-ffvhuff420p12 b/tests/ref/vsynth/vsynth_lena-ffvhuff420p12
index 6b666f8..e8ea4bc 100644
--- a/tests/ref/vsynth/vsynth_lena-ffvhuff420p12
+++ b/tests/ref/vsynth/vsynth_lena-ffvhuff420p12
@@ -1,4 +1,4 @@
-e5873a19c7be1cdf25600eb033738b9e *tests/data/fate/vsynth_lena-ffvhuff420p12.avi
-10925576 tests/data/fate/vsynth_lena-ffvhuff420p12.avi
+b2f3d04ca30c113b79877bb5518dd6ea *tests/data/fate/vsynth_lena-ffvhuff420p12.avi
+10925580 tests/data/fate/vsynth_lena-ffvhuff420p12.avi
 08b3c6c70eba608bae926608ff253f2a *tests/data/fate/vsynth_lena-ffvhuff420p12.out.rawvideo
 stddev:    0.68 PSNR: 51.38 MAXDIFF:    1 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-ffvhuff422p10left b/tests/ref/vsynth/vsynth_lena-ffvhuff422p10left
index 519ea75..d650427 100644
--- a/tests/ref/vsynth/vsynth_lena-ffvhuff422p10left
+++ b/tests/ref/vsynth/vsynth_lena-ffvhuff422p10left
@@ -1,4 +1,4 @@
-d7d321c3b1ed3378e03b2f618f248d86 *tests/data/fate/vsynth_lena-ffvhuff422p10left.avi
-10041832 tests/data/fate/vsynth_lena-ffvhuff422p10left.avi
+f6eae87090fcccc682f84a794784b4dd *tests/data/fate/vsynth_lena-ffvhuff422p10left.avi
+10041836 tests/data/fate/vsynth_lena-ffvhuff422p10left.avi
 a627fb50c8276200fd71383977d87ca3 *tests/data/fate/vsynth_lena-ffvhuff422p10left.out.rawvideo
 stddev:    0.34 PSNR: 57.43 MAXDIFF:    6 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-ffvhuff444 b/tests/ref/vsynth/vsynth_lena-ffvhuff444
index efd281c..366498d 100644
--- a/tests/ref/vsynth/vsynth_lena-ffvhuff444
+++ b/tests/ref/vsynth/vsynth_lena-ffvhuff444
@@ -1,4 +1,4 @@
-68e78dc89bb596f93a14e7f4a7a24365 *tests/data/fate/vsynth_lena-ffvhuff444.avi
-7530714 tests/data/fate/vsynth_lena-ffvhuff444.avi
+1afdc5e87de165520f2b7e0fab18b241 *tests/data/fate/vsynth_lena-ffvhuff444.avi
+7530718 tests/data/fate/vsynth_lena-ffvhuff444.avi
 d43cb310c130c69214332d74f6ee5f9a *tests/data/fate/vsynth_lena-ffvhuff444.out.rawvideo
 stddev:    0.41 PSNR: 55.80 MAXDIFF:    7 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-ffvhuff444p16 b/tests/ref/vsynth/vsynth_lena-ffvhuff444p16
index cb28f09..3161b41 100644
--- a/tests/ref/vsynth/vsynth_lena-ffvhuff444p16
+++ b/tests/ref/vsynth/vsynth_lena-ffvhuff444p16
@@ -1,4 +1,4 @@
-db17747292df97d6c62b15b041c378da *tests/data/fate/vsynth_lena-ffvhuff444p16.avi
-26360716 tests/data/fate/vsynth_lena-ffvhuff444p16.avi
+94e2c25a08522071ca4d2314ddb2a4a1 *tests/data/fate/vsynth_lena-ffvhuff444p16.avi
+26360720 tests/data/fate/vsynth_lena-ffvhuff444p16.avi
 05ccd9a38f9726030b3099c0c99d3a13 *tests/data/fate/vsynth_lena-ffvhuff444p16.out.rawvideo
 stddev:    0.45 PSNR: 55.06 MAXDIFF:    7 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-h261 b/tests/ref/vsynth/vsynth_lena-h261
index 70b1da5..c4ea318 100644
--- a/tests/ref/vsynth/vsynth_lena-h261
+++ b/tests/ref/vsynth/vsynth_lena-h261
@@ -1,4 +1,4 @@
-6399cb1044e5433c844c21790fc17128 *tests/data/fate/vsynth_lena-h261.avi
-191060 tests/data/fate/vsynth_lena-h261.avi
+a8a6fe710cf8591d1ce5fd18f478e217 *tests/data/fate/vsynth_lena-h261.avi
+191064 tests/data/fate/vsynth_lena-h261.avi
 08f65e9aeeeaf189548c2bb417d5114f *tests/data/fate/vsynth_lena-h261.out.rawvideo
 stddev:    6.37 PSNR: 32.03 MAXDIFF:   77 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-h261-trellis b/tests/ref/vsynth/vsynth_lena-h261-trellis
index 1baab97..128f224 100644
--- a/tests/ref/vsynth/vsynth_lena-h261-trellis
+++ b/tests/ref/vsynth/vsynth_lena-h261-trellis
@@ -1,4 +1,4 @@
-616cb40cf84704d177e207ee85a24531 *tests/data/fate/vsynth_lena-h261-trellis.avi
-184582 tests/data/fate/vsynth_lena-h261-trellis.avi
+43fca6298b5366199104942e8a901d52 *tests/data/fate/vsynth_lena-h261-trellis.avi
+184586 tests/data/fate/vsynth_lena-h261-trellis.avi
 f9df8cd110a2f3d9706dd2f29a1d0a89 *tests/data/fate/vsynth_lena-h261-trellis.out.rawvideo
 stddev:    6.32 PSNR: 32.11 MAXDIFF:   89 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-h263 b/tests/ref/vsynth/vsynth_lena-h263
index 9865c48..862231b 100644
--- a/tests/ref/vsynth/vsynth_lena-h263
+++ b/tests/ref/vsynth/vsynth_lena-h263
@@ -1,4 +1,4 @@
-b5ea141b794ad88019507375ec092ad7 *tests/data/fate/vsynth_lena-h263.avi
-160102 tests/data/fate/vsynth_lena-h263.avi
+005cba8a5e8f10adc8973fd3c66ea236 *tests/data/fate/vsynth_lena-h263.avi
+160106 tests/data/fate/vsynth_lena-h263.avi
 b7d733ebedbaa04f49bf7493a907e223 *tests/data/fate/vsynth_lena-h263.out.rawvideo
 stddev:    5.43 PSNR: 33.42 MAXDIFF:   77 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-h263-obmc b/tests/ref/vsynth/vsynth_lena-h263-obmc
index 9bd1108..5b96310 100644
--- a/tests/ref/vsynth/vsynth_lena-h263-obmc
+++ b/tests/ref/vsynth/vsynth_lena-h263-obmc
@@ -1,4 +1,4 @@
-d242b7948697014abcaaff50551400ac *tests/data/fate/vsynth_lena-h263-obmc.avi
-154726 tests/data/fate/vsynth_lena-h263-obmc.avi
+3c6946f808412ac320be9e0c36051ea2 *tests/data/fate/vsynth_lena-h263-obmc.avi
+154730 tests/data/fate/vsynth_lena-h263-obmc.avi
 588d992d9d8096da8bdc5027268da914 *tests/data/fate/vsynth_lena-h263-obmc.out.rawvideo
 stddev:    5.39 PSNR: 33.49 MAXDIFF:   82 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-h263p b/tests/ref/vsynth/vsynth_lena-h263p
index b0ca89e..3aa8223 100644
--- a/tests/ref/vsynth/vsynth_lena-h263p
+++ b/tests/ref/vsynth/vsynth_lena-h263p
@@ -1,4 +1,4 @@
-000157a2e05709df95e40bd5e2185141 *tests/data/fate/vsynth_lena-h263p.avi
-867998 tests/data/fate/vsynth_lena-h263p.avi
+de3a8bca32aba3bd5138cbb40fe0099e *tests/data/fate/vsynth_lena-h263p.avi
+868002 tests/data/fate/vsynth_lena-h263p.avi
 dca18571c05c13dd691d7b0b232e43fc *tests/data/fate/vsynth_lena-h263p.out.rawvideo
 stddev:    1.91 PSNR: 42.50 MAXDIFF:   19 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-huffyuv b/tests/ref/vsynth/vsynth_lena-huffyuv
index fa9061a..25dac45 100644
--- a/tests/ref/vsynth/vsynth_lena-huffyuv
+++ b/tests/ref/vsynth/vsynth_lena-huffyuv
@@ -1,4 +1,4 @@
-c639e4044a66dc5dffb46d5d82516ef8 *tests/data/fate/vsynth_lena-huffyuv.avi
-6108510 tests/data/fate/vsynth_lena-huffyuv.avi
+e0027fb7a9ab8ac964bba02186b4a829 *tests/data/fate/vsynth_lena-huffyuv.avi
+6108514 tests/data/fate/vsynth_lena-huffyuv.avi
 dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth_lena-huffyuv.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-huffyuvbgr24 b/tests/ref/vsynth/vsynth_lena-huffyuvbgr24
index 4c23a95..6bb71fc 100644
--- a/tests/ref/vsynth/vsynth_lena-huffyuvbgr24
+++ b/tests/ref/vsynth/vsynth_lena-huffyuvbgr24
@@ -1,4 +1,4 @@
-d72d98a2847811499028f8997320a38b *tests/data/fate/vsynth_lena-huffyuvbgr24.avi
-8872410 tests/data/fate/vsynth_lena-huffyuvbgr24.avi
+baa4da184fd977f1d6040d63644cbd55 *tests/data/fate/vsynth_lena-huffyuvbgr24.avi
+8872414 tests/data/fate/vsynth_lena-huffyuvbgr24.avi
 0a8b7ddfec03622e37c869c5b552f9fc *tests/data/fate/vsynth_lena-huffyuvbgr24.out.rawvideo
 stddev:    1.24 PSNR: 46.26 MAXDIFF:   17 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-huffyuvbgra b/tests/ref/vsynth/vsynth_lena-huffyuvbgra
index ea7edb8..509275d 100644
--- a/tests/ref/vsynth/vsynth_lena-huffyuvbgra
+++ b/tests/ref/vsynth/vsynth_lena-huffyuvbgra
@@ -1,4 +1,4 @@
-e8c2dbe6ad5d273af2bdb2dc3a2a524d *tests/data/fate/vsynth_lena-huffyuvbgra.avi
-10139598 tests/data/fate/vsynth_lena-huffyuvbgra.avi
+bf52b827c5fabea0949ce4776d3d66c8 *tests/data/fate/vsynth_lena-huffyuvbgra.avi
+10139602 tests/data/fate/vsynth_lena-huffyuvbgra.avi
 0a8b7ddfec03622e37c869c5b552f9fc *tests/data/fate/vsynth_lena-huffyuvbgra.out.rawvideo
 stddev:    1.24 PSNR: 46.26 MAXDIFF:   17 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-jpeg2000 b/tests/ref/vsynth/vsynth_lena-jpeg2000
index 3efa6c5..d4d8cf3 100644
--- a/tests/ref/vsynth/vsynth_lena-jpeg2000
+++ b/tests/ref/vsynth/vsynth_lena-jpeg2000
@@ -1,4 +1,4 @@
-6cf1985f29a7febbb79edf1d5268e203 *tests/data/fate/vsynth_lena-jpeg2000.avi
-1151144 tests/data/fate/vsynth_lena-jpeg2000.avi
+9283c83bc8dc830bd48ad66f71ae42e8 *tests/data/fate/vsynth_lena-jpeg2000.avi
+1151148 tests/data/fate/vsynth_lena-jpeg2000.avi
 e7d79c9e11d0fe97f03e38be66c34e4f *tests/data/fate/vsynth_lena-jpeg2000.out.rawvideo
 stddev:    4.41 PSNR: 35.23 MAXDIFF:   63 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-jpeg2000-97 b/tests/ref/vsynth/vsynth_lena-jpeg2000-97
index 1577dd6..5945ac7 100644
--- a/tests/ref/vsynth/vsynth_lena-jpeg2000-97
+++ b/tests/ref/vsynth/vsynth_lena-jpeg2000-97
@@ -1,4 +1,4 @@
-7cdaa014398f52869704dc537983db54 *tests/data/fate/vsynth_lena-jpeg2000-97.avi
-1118952 tests/data/fate/vsynth_lena-jpeg2000-97.avi
+ba27504dcabe43d6608798c9cadc5cca *tests/data/fate/vsynth_lena-jpeg2000-97.avi
+1118956 tests/data/fate/vsynth_lena-jpeg2000-97.avi
 8ac8b9ee81fa73c873668e9f6b78764d *tests/data/fate/vsynth_lena-jpeg2000-97.out.rawvideo
 stddev:    4.95 PSNR: 34.23 MAXDIFF:   60 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-jpegls b/tests/ref/vsynth/vsynth_lena-jpegls
index 99f47d6..72a619b 100644
--- a/tests/ref/vsynth/vsynth_lena-jpegls
+++ b/tests/ref/vsynth/vsynth_lena-jpegls
@@ -1,4 +1,4 @@
-9840b70886b4fc86512de729e41de979 *tests/data/fate/vsynth_lena-jpegls.avi
-8334618 tests/data/fate/vsynth_lena-jpegls.avi
+517b3a8d84f1ec5d502ddb9ed0bb8580 *tests/data/fate/vsynth_lena-jpegls.avi
+8334622 tests/data/fate/vsynth_lena-jpegls.avi
 3a984506f1ebfc9fb73b6814cab201cc *tests/data/fate/vsynth_lena-jpegls.out.rawvideo
 stddev:    0.66 PSNR: 51.73 MAXDIFF:   14 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-ljpeg b/tests/ref/vsynth/vsynth_lena-ljpeg
index 6a25fda..81f9cdb 100644
--- a/tests/ref/vsynth/vsynth_lena-ljpeg
+++ b/tests/ref/vsynth/vsynth_lena-ljpeg
@@ -1,4 +1,4 @@
-234a0e54d00829513bdc92fc580b2598 *tests/data/fate/vsynth_lena-ljpeg.avi
-4763454 tests/data/fate/vsynth_lena-ljpeg.avi
+dc136b224f01c757a887d5672d5edfd2 *tests/data/fate/vsynth_lena-ljpeg.avi
+4763458 tests/data/fate/vsynth_lena-ljpeg.avi
 dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth_lena-ljpeg.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-mjpeg b/tests/ref/vsynth/vsynth_lena-mjpeg
index 84cbbcd..1487641 100644
--- a/tests/ref/vsynth/vsynth_lena-mjpeg
+++ b/tests/ref/vsynth/vsynth_lena-mjpeg
@@ -1,4 +1,4 @@
-a3c1f9f7887b726bab17dbafa5debdca *tests/data/fate/vsynth_lena-mjpeg.avi
-673174 tests/data/fate/vsynth_lena-mjpeg.avi
+40c5ba1b15006799773617f888c2808b *tests/data/fate/vsynth_lena-mjpeg.avi
+673178 tests/data/fate/vsynth_lena-mjpeg.avi
 9d4bd90e9abfa18192383b4adc23c8d4 *tests/data/fate/vsynth_lena-mjpeg.out.rawvideo
 stddev:    4.32 PSNR: 35.40 MAXDIFF:   49 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-mjpeg-422 b/tests/ref/vsynth/vsynth_lena-mjpeg-422
index 39978a8..23dd1a2 100644
--- a/tests/ref/vsynth/vsynth_lena-mjpeg-422
+++ b/tests/ref/vsynth/vsynth_lena-mjpeg-422
@@ -1,4 +1,4 @@
-ebf2e0f17a75119ff86b15e721d16a76 *tests/data/fate/vsynth_lena-mjpeg-422.avi
-746530 tests/data/fate/vsynth_lena-mjpeg-422.avi
+4a1f72cf4c8e562f4e805f0c7912515b *tests/data/fate/vsynth_lena-mjpeg-422.avi
+746534 tests/data/fate/vsynth_lena-mjpeg-422.avi
 451ac80989c4e14445cf951fd7f83b6d *tests/data/fate/vsynth_lena-mjpeg-422.out.rawvideo
 stddev:    4.18 PSNR: 35.70 MAXDIFF:   49 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-mjpeg-444 b/tests/ref/vsynth/vsynth_lena-mjpeg-444
index 6ba105d..1dc103c 100644
--- a/tests/ref/vsynth/vsynth_lena-mjpeg-444
+++ b/tests/ref/vsynth/vsynth_lena-mjpeg-444
@@ -1,4 +1,4 @@
-7674eb1aedaad0976c60329f556440d1 *tests/data/fate/vsynth_lena-mjpeg-444.avi
-851442 tests/data/fate/vsynth_lena-mjpeg-444.avi
+969ac14cbc77d5475f4871cefe3cc6b0 *tests/data/fate/vsynth_lena-mjpeg-444.avi
+851446 tests/data/fate/vsynth_lena-mjpeg-444.avi
 34edcb9c87ff7aac456a4fb07f43504b *tests/data/fate/vsynth_lena-mjpeg-444.out.rawvideo
 stddev:    4.05 PSNR: 35.96 MAXDIFF:   49 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-mjpeg-trell b/tests/ref/vsynth/vsynth_lena-mjpeg-trell
new file mode 100644
index 0000000..d37d5a2
--- /dev/null
+++ b/tests/ref/vsynth/vsynth_lena-mjpeg-trell
@@ -0,0 +1,4 @@
+61c12b5e0f95c352c1ff2f3b95d88274 *tests/data/fate/vsynth_lena-mjpeg-trell.avi
+613612 tests/data/fate/vsynth_lena-mjpeg-trell.avi
+ee4999fcc0913e01e69fe689b4229cbe *tests/data/fate/vsynth_lena-mjpeg-trell.out.rawvideo
+stddev:    4.51 PSNR: 35.03 MAXDIFF:   60 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-mpeg4-adap b/tests/ref/vsynth/vsynth_lena-mpeg4-adap
index 7787693..10af80b 100644
--- a/tests/ref/vsynth/vsynth_lena-mpeg4-adap
+++ b/tests/ref/vsynth/vsynth_lena-mpeg4-adap
@@ -1,4 +1,4 @@
-bbb12e077f858242c1387d23d2ccdae8 *tests/data/fate/vsynth_lena-mpeg4-adap.avi
-198496 tests/data/fate/vsynth_lena-mpeg4-adap.avi
+c6108621b1202d32dac68b1944c5b8c2 *tests/data/fate/vsynth_lena-mpeg4-adap.avi
+198500 tests/data/fate/vsynth_lena-mpeg4-adap.avi
 87b6dbe98d276137fceaae2fa672eced *tests/data/fate/vsynth_lena-mpeg4-adap.out.rawvideo
 stddev:    3.75 PSNR: 36.65 MAXDIFF:   71 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-mpeg4-adv b/tests/ref/vsynth/vsynth_lena-mpeg4-adv
index 2304417..c725264 100644
--- a/tests/ref/vsynth/vsynth_lena-mpeg4-adv
+++ b/tests/ref/vsynth/vsynth_lena-mpeg4-adv
@@ -1,4 +1,4 @@
-9fa1b5a68a6128a7160cfc8443a696e1 *tests/data/fate/vsynth_lena-mpeg4-adv.avi
-141534 tests/data/fate/vsynth_lena-mpeg4-adv.avi
+68117f01abe704a4ce6a664efffcfb40 *tests/data/fate/vsynth_lena-mpeg4-adv.avi
+141538 tests/data/fate/vsynth_lena-mpeg4-adv.avi
 3f3a21e9db85a9c0f7022f557a5374c1 *tests/data/fate/vsynth_lena-mpeg4-adv.out.rawvideo
 stddev:    4.94 PSNR: 34.25 MAXDIFF:   69 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-mpeg4-error b/tests/ref/vsynth/vsynth_lena-mpeg4-error
index f04f3c3..b5ebd5e 100644
--- a/tests/ref/vsynth/vsynth_lena-mpeg4-error
+++ b/tests/ref/vsynth/vsynth_lena-mpeg4-error
@@ -1,4 +1,4 @@
-82510449a3200b58dbcfbf0a643eb624 *tests/data/fate/vsynth_lena-mpeg4-error.avi
-180364 tests/data/fate/vsynth_lena-mpeg4-error.avi
+0126f46feb09b49144136be09ce6d26b *tests/data/fate/vsynth_lena-mpeg4-error.avi
+180368 tests/data/fate/vsynth_lena-mpeg4-error.avi
 4537ba5320f1ae0971cc6e329c366776 *tests/data/fate/vsynth_lena-mpeg4-error.out.rawvideo
 stddev:    7.65 PSNR: 30.45 MAXDIFF:  158 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-mpeg4-nr b/tests/ref/vsynth/vsynth_lena-mpeg4-nr
index 35c17ca..e6b5dc4 100644
--- a/tests/ref/vsynth/vsynth_lena-mpeg4-nr
+++ b/tests/ref/vsynth/vsynth_lena-mpeg4-nr
@@ -1,4 +1,4 @@
-cf0cde80515f8bfbd89d33aa51f1c5e1 *tests/data/fate/vsynth_lena-mpeg4-nr.avi
-154994 tests/data/fate/vsynth_lena-mpeg4-nr.avi
+c1cf10bd999899bce94be0efd15c3605 *tests/data/fate/vsynth_lena-mpeg4-nr.avi
+154998 tests/data/fate/vsynth_lena-mpeg4-nr.avi
 d89cd5d0b1707f48fa9c4747c66d2d56 *tests/data/fate/vsynth_lena-mpeg4-nr.out.rawvideo
 stddev:    4.73 PSNR: 34.63 MAXDIFF:   64 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-mpeg4-nsse b/tests/ref/vsynth/vsynth_lena-mpeg4-nsse
index 0bc51c9..31cddaa 100644
--- a/tests/ref/vsynth/vsynth_lena-mpeg4-nsse
+++ b/tests/ref/vsynth/vsynth_lena-mpeg4-nsse
@@ -1,4 +1,4 @@
-b60bb3d8b942795272f0f0d89cd6351e *tests/data/fate/vsynth_lena-mpeg4-nsse.avi
-198434 tests/data/fate/vsynth_lena-mpeg4-nsse.avi
+f09593231b2137ae2064845c315b6a0b *tests/data/fate/vsynth_lena-mpeg4-nsse.avi
+198438 tests/data/fate/vsynth_lena-mpeg4-nsse.avi
 59864a1050e641eaed8b0ee077bc780b *tests/data/fate/vsynth_lena-mpeg4-nsse.out.rawvideo
 stddev:    4.32 PSNR: 35.40 MAXDIFF:   60 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-mpeg4-qpel b/tests/ref/vsynth/vsynth_lena-mpeg4-qpel
index d5c19dc..e656130 100644
--- a/tests/ref/vsynth/vsynth_lena-mpeg4-qpel
+++ b/tests/ref/vsynth/vsynth_lena-mpeg4-qpel
@@ -1,4 +1,4 @@
-ab94d9e56635e100d95e74fc8dc845e5 *tests/data/fate/vsynth_lena-mpeg4-qpel.avi
-163662 tests/data/fate/vsynth_lena-mpeg4-qpel.avi
+04d020deb9956fb2b5970a16986d688c *tests/data/fate/vsynth_lena-mpeg4-qpel.avi
+163666 tests/data/fate/vsynth_lena-mpeg4-qpel.avi
 e2ce994dbb66da51c2e1ad26617d7c2f *tests/data/fate/vsynth_lena-mpeg4-qpel.out.rawvideo
 stddev:    3.97 PSNR: 36.14 MAXDIFF:   54 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-mpeg4-qprd b/tests/ref/vsynth/vsynth_lena-mpeg4-qprd
index a0f20fe..831300b 100644
--- a/tests/ref/vsynth/vsynth_lena-mpeg4-qprd
+++ b/tests/ref/vsynth/vsynth_lena-mpeg4-qprd
@@ -1,4 +1,4 @@
-a576ecbf48c33916f2d17cf1bf37f3fe *tests/data/fate/vsynth_lena-mpeg4-qprd.avi
-231450 tests/data/fate/vsynth_lena-mpeg4-qprd.avi
+5342abedb8fdc788e08c344d4122f2dc *tests/data/fate/vsynth_lena-mpeg4-qprd.avi
+231454 tests/data/fate/vsynth_lena-mpeg4-qprd.avi
 3071250e0864546c2455c9f9c9b8604e *tests/data/fate/vsynth_lena-mpeg4-qprd.out.rawvideo
 stddev:    3.71 PSNR: 36.72 MAXDIFF:   61 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-mpeg4-rc b/tests/ref/vsynth/vsynth_lena-mpeg4-rc
index 85af229..fd6a998 100644
--- a/tests/ref/vsynth/vsynth_lena-mpeg4-rc
+++ b/tests/ref/vsynth/vsynth_lena-mpeg4-rc
@@ -1,4 +1,4 @@
-ea96539a0bebf70c3c09de0199a53a30 *tests/data/fate/vsynth_lena-mpeg4-rc.avi
-226310 tests/data/fate/vsynth_lena-mpeg4-rc.avi
+396a76466dee56e2714dfa42cebe3d2d *tests/data/fate/vsynth_lena-mpeg4-rc.avi
+226314 tests/data/fate/vsynth_lena-mpeg4-rc.avi
 6e8b62e8c3bcbfdcc58afb69a0b1c4e3 *tests/data/fate/vsynth_lena-mpeg4-rc.out.rawvideo
 stddev:    4.23 PSNR: 35.60 MAXDIFF:   85 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-mpeg4-thread b/tests/ref/vsynth/vsynth_lena-mpeg4-thread
index 6e84c1a..c0b7978 100644
--- a/tests/ref/vsynth/vsynth_lena-mpeg4-thread
+++ b/tests/ref/vsynth/vsynth_lena-mpeg4-thread
@@ -1,4 +1,4 @@
-8d7903d55221035c67866b8c1314c499 *tests/data/fate/vsynth_lena-mpeg4-thread.avi
-250092 tests/data/fate/vsynth_lena-mpeg4-thread.avi
+af5ea0bab124371051eb104552344b2e *tests/data/fate/vsynth_lena-mpeg4-thread.avi
+250096 tests/data/fate/vsynth_lena-mpeg4-thread.avi
 045fe9f226bbcc3d41644bffaed03b31 *tests/data/fate/vsynth_lena-mpeg4-thread.out.rawvideo
 stddev:    3.69 PSNR: 36.78 MAXDIFF:   65 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-mpng b/tests/ref/vsynth/vsynth_lena-mpng
index 45cd860..2025843 100644
--- a/tests/ref/vsynth/vsynth_lena-mpng
+++ b/tests/ref/vsynth/vsynth_lena-mpng
@@ -1,4 +1,4 @@
-aaee9d1ff7dccfc045603c45f0160000 *tests/data/fate/vsynth_lena-mpng.avi
-12558330 tests/data/fate/vsynth_lena-mpng.avi
+319ca02f8465a9c53128442f4b0dd528 *tests/data/fate/vsynth_lena-mpng.avi
+12558334 tests/data/fate/vsynth_lena-mpng.avi
 98d0e2854731472c5bf13d8638502d0a *tests/data/fate/vsynth_lena-mpng.out.rawvideo
 stddev:    1.26 PSNR: 46.10 MAXDIFF:   13 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-msmpeg4 b/tests/ref/vsynth/vsynth_lena-msmpeg4
index c9eadbb..37bf791 100644
--- a/tests/ref/vsynth/vsynth_lena-msmpeg4
+++ b/tests/ref/vsynth/vsynth_lena-msmpeg4
@@ -1,4 +1,4 @@
-50b91fe78559c0f5f1e5873cdcc0e6a8 *tests/data/fate/vsynth_lena-msmpeg4.avi
-127660 tests/data/fate/vsynth_lena-msmpeg4.avi
+9f48dd3b88a931ba25963a02d33261ca *tests/data/fate/vsynth_lena-msmpeg4.avi
+127664 tests/data/fate/vsynth_lena-msmpeg4.avi
 bb14902d5850d6b0ab70fdb017855775 *tests/data/fate/vsynth_lena-msmpeg4.out.rawvideo
 stddev:    5.33 PSNR: 33.58 MAXDIFF:   78 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-msmpeg4v2 b/tests/ref/vsynth/vsynth_lena-msmpeg4v2
index a8c4740..c355eac 100644
--- a/tests/ref/vsynth/vsynth_lena-msmpeg4v2
+++ b/tests/ref/vsynth/vsynth_lena-msmpeg4v2
@@ -1,4 +1,4 @@
-4770bd848f1937a861bf1a72295c6094 *tests/data/fate/vsynth_lena-msmpeg4v2.avi
-129918 tests/data/fate/vsynth_lena-msmpeg4v2.avi
+7e3376dea39d44edd6ee3b0a59a87cbd *tests/data/fate/vsynth_lena-msmpeg4v2.avi
+129922 tests/data/fate/vsynth_lena-msmpeg4v2.avi
 537c114e1d47c54a4bccd31f4073e9bd *tests/data/fate/vsynth_lena-msmpeg4v2.out.rawvideo
 stddev:    5.33 PSNR: 33.59 MAXDIFF:   79 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-msvideo1 b/tests/ref/vsynth/vsynth_lena-msvideo1
index b49d187..4f7de40 100644
--- a/tests/ref/vsynth/vsynth_lena-msvideo1
+++ b/tests/ref/vsynth/vsynth_lena-msvideo1
@@ -1,4 +1,4 @@
-e554e31a4a635c924391228b7194d21b *tests/data/fate/vsynth_lena-msvideo1.avi
-914560 tests/data/fate/vsynth_lena-msvideo1.avi
+f2d42ddffd6546b6ca71bbb6e3b62c00 *tests/data/fate/vsynth_lena-msvideo1.avi
+914564 tests/data/fate/vsynth_lena-msvideo1.avi
 9a6ac7c0171286f009d159b59fdc1154 *tests/data/fate/vsynth_lena-msvideo1.out.rawvideo
 stddev:    7.97 PSNR: 30.10 MAXDIFF:  123 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-r210 b/tests/ref/vsynth/vsynth_lena-r210
index c6bac90..3ed30ff 100644
--- a/tests/ref/vsynth/vsynth_lena-r210
+++ b/tests/ref/vsynth/vsynth_lena-r210
@@ -1,4 +1,4 @@
-16717c6cee907554cbeaefbbc116cd66 *tests/data/fate/vsynth_lena-r210.avi
-22125248 tests/data/fate/vsynth_lena-r210.avi
+e5f96a1d0fe5c519f6cb954838e105bc *tests/data/fate/vsynth_lena-r210.avi
+22125252 tests/data/fate/vsynth_lena-r210.avi
 6ea4fcd93fc83defc8770e85b64b60bb *tests/data/fate/vsynth_lena-r210.out.rawvideo
 stddev:    0.70 PSNR: 51.12 MAXDIFF:   12 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-rgb b/tests/ref/vsynth/vsynth_lena-rgb
index 15df006..9706ffb 100644
--- a/tests/ref/vsynth/vsynth_lena-rgb
+++ b/tests/ref/vsynth/vsynth_lena-rgb
@@ -1,4 +1,4 @@
-188bce319523a1c7d24103aab1ed1bda *tests/data/fate/vsynth_lena-rgb.avi
-15213248 tests/data/fate/vsynth_lena-rgb.avi
+f083e812216195c1e9454b5fac681c92 *tests/data/fate/vsynth_lena-rgb.avi
+15213252 tests/data/fate/vsynth_lena-rgb.avi
 98d0e2854731472c5bf13d8638502d0a *tests/data/fate/vsynth_lena-rgb.out.rawvideo
 stddev:    1.26 PSNR: 46.10 MAXDIFF:   13 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-snow b/tests/ref/vsynth/vsynth_lena-snow
index 26c023f..580d5c7 100644
--- a/tests/ref/vsynth/vsynth_lena-snow
+++ b/tests/ref/vsynth/vsynth_lena-snow
@@ -1,4 +1,4 @@
-a7bc7eba6ac50f0b417cb9f829feb7a1 *tests/data/fate/vsynth_lena-snow.avi
-57688 tests/data/fate/vsynth_lena-snow.avi
+ca3ca23811d77e8d6b438116675c5550 *tests/data/fate/vsynth_lena-snow.avi
+57692 tests/data/fate/vsynth_lena-snow.avi
 8890189af71a0dd3447c4e8424c9a76b *tests/data/fate/vsynth_lena-snow.out.rawvideo
 stddev:   10.47 PSNR: 27.72 MAXDIFF:  119 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-snow-hpel b/tests/ref/vsynth/vsynth_lena-snow-hpel
index bdf2746..df073b8 100644
--- a/tests/ref/vsynth/vsynth_lena-snow-hpel
+++ b/tests/ref/vsynth/vsynth_lena-snow-hpel
@@ -1,4 +1,4 @@
-fa6986c9ebaa087b037d099acefa0ade *tests/data/fate/vsynth_lena-snow-hpel.avi
-61760 tests/data/fate/vsynth_lena-snow-hpel.avi
+189b98a51f6d9f4fe8cc6c08a77e5b46 *tests/data/fate/vsynth_lena-snow-hpel.avi
+61764 tests/data/fate/vsynth_lena-snow-hpel.avi
 8680d40905f423999d65b996c4dcb984 *tests/data/fate/vsynth_lena-snow-hpel.out.rawvideo
 stddev:   10.45 PSNR: 27.74 MAXDIFF:  123 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-snow-ll b/tests/ref/vsynth/vsynth_lena-snow-ll
index e68ba3f..aa8566f 100644
--- a/tests/ref/vsynth/vsynth_lena-snow-ll
+++ b/tests/ref/vsynth/vsynth_lena-snow-ll
@@ -1,4 +1,4 @@
-ed109f21012f92ad5ea19451844ae721 *tests/data/fate/vsynth_lena-snow-ll.avi
-2721746 tests/data/fate/vsynth_lena-snow-ll.avi
+c0b349dadc1d1714960df23b7c92961c *tests/data/fate/vsynth_lena-snow-ll.avi
+2721750 tests/data/fate/vsynth_lena-snow-ll.avi
 dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth_lena-snow-ll.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-v210 b/tests/ref/vsynth/vsynth_lena-v210
index fe0a5a7..ef5020b 100644
--- a/tests/ref/vsynth/vsynth_lena-v210
+++ b/tests/ref/vsynth/vsynth_lena-v210
@@ -1,4 +1,4 @@
-fa1c4b1b8d0e9454b4bc2269c7fe634b *tests/data/fate/vsynth_lena-v210.avi
-14752448 tests/data/fate/vsynth_lena-v210.avi
+20af8b986704b9713cd75d3e6e41efa4 *tests/data/fate/vsynth_lena-v210.avi
+14752452 tests/data/fate/vsynth_lena-v210.avi
 7ba6e411e43c6b57c95c49d6848f41e6 *tests/data/fate/vsynth_lena-v210.out.rawvideo
 stddev:    0.34 PSNR: 57.41 MAXDIFF:    6 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-v308 b/tests/ref/vsynth/vsynth_lena-v308
index d7bacf6..6de15b5 100644
--- a/tests/ref/vsynth/vsynth_lena-v308
+++ b/tests/ref/vsynth/vsynth_lena-v308
@@ -1,4 +1,4 @@
-1ea64cd6ad32dae72963b8fdf89e96d1 *tests/data/fate/vsynth_lena-v308.avi
-15213248 tests/data/fate/vsynth_lena-v308.avi
+5bff4d7763e624272835e056c9faf4c2 *tests/data/fate/vsynth_lena-v308.avi
+15213252 tests/data/fate/vsynth_lena-v308.avi
 d43cb310c130c69214332d74f6ee5f9a *tests/data/fate/vsynth_lena-v308.out.rawvideo
 stddev:    0.41 PSNR: 55.80 MAXDIFF:    7 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-v408 b/tests/ref/vsynth/vsynth_lena-v408
index 2451c01..ba19e28 100644
--- a/tests/ref/vsynth/vsynth_lena-v408
+++ b/tests/ref/vsynth/vsynth_lena-v408
@@ -1,4 +1,4 @@
-b4cdf2351f908fc308d8693d0cee69e1 *tests/data/fate/vsynth_lena-v408.avi
-20282048 tests/data/fate/vsynth_lena-v408.avi
+e2a1c097a78f1a5c8ad1bccc4077844b *tests/data/fate/vsynth_lena-v408.avi
+20282052 tests/data/fate/vsynth_lena-v408.avi
 dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth_lena-v408.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-wmv1 b/tests/ref/vsynth/vsynth_lena-wmv1
index f6e3ca9..f407d17 100644
--- a/tests/ref/vsynth/vsynth_lena-wmv1
+++ b/tests/ref/vsynth/vsynth_lena-wmv1
@@ -1,4 +1,4 @@
-3099f5514693a609180ab5761dc8d4ca *tests/data/fate/vsynth_lena-wmv1.avi
-129510 tests/data/fate/vsynth_lena-wmv1.avi
+a9f43b25c3235a6cf922a2c5abd086e8 *tests/data/fate/vsynth_lena-wmv1.avi
+129514 tests/data/fate/vsynth_lena-wmv1.avi
 dec44e3c04db4fef49a7728f164d9159 *tests/data/fate/vsynth_lena-wmv1.out.rawvideo
 stddev:    5.33 PSNR: 33.60 MAXDIFF:   77 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-wmv2 b/tests/ref/vsynth/vsynth_lena-wmv2
index c75f762..fca0199 100644
--- a/tests/ref/vsynth/vsynth_lena-wmv2
+++ b/tests/ref/vsynth/vsynth_lena-wmv2
@@ -1,4 +1,4 @@
-c8d1d1371bd09add388c32f3259ef555 *tests/data/fate/vsynth_lena-wmv2.avi
-129852 tests/data/fate/vsynth_lena-wmv2.avi
+62ef27d48181d8256ad476e02c536145 *tests/data/fate/vsynth_lena-wmv2.avi
+129856 tests/data/fate/vsynth_lena-wmv2.avi
 b4de16a0d302c52702f7a4362da989bc *tests/data/fate/vsynth_lena-wmv2.out.rawvideo
 stddev:    5.33 PSNR: 33.59 MAXDIFF:   77 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-y41p b/tests/ref/vsynth/vsynth_lena-y41p
index 91681c3..9cc0957 100644
--- a/tests/ref/vsynth/vsynth_lena-y41p
+++ b/tests/ref/vsynth/vsynth_lena-y41p
@@ -1,4 +1,4 @@
-522ebf5fbf98aeec5ee6b39de1c1afc0 *tests/data/fate/vsynth_lena-y41p.avi
-7610048 tests/data/fate/vsynth_lena-y41p.avi
+3b958734c653d265cd42e31d6a22230f *tests/data/fate/vsynth_lena-y41p.avi
+7610052 tests/data/fate/vsynth_lena-y41p.avi
 d27a84ccdac09055724d122e03fea82a *tests/data/fate/vsynth_lena-y41p.out.rawvideo
 stddev:    1.07 PSNR: 47.54 MAXDIFF:   21 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-yuv b/tests/ref/vsynth/vsynth_lena-yuv
index 3ee30de..bc27dcf 100644
--- a/tests/ref/vsynth/vsynth_lena-yuv
+++ b/tests/ref/vsynth/vsynth_lena-yuv
@@ -1,4 +1,4 @@
-f48f08c67097b3c35b1105f24ef68a0c *tests/data/fate/vsynth_lena-yuv.avi
-7610048 tests/data/fate/vsynth_lena-yuv.avi
+0d061b0b7bedcd59e5c90a99f58ceeae *tests/data/fate/vsynth_lena-yuv.avi
+7610052 tests/data/fate/vsynth_lena-yuv.avi
 dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth_lena-yuv.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-yuv4 b/tests/ref/vsynth/vsynth_lena-yuv4
index 4d173cc..97a1374 100644
--- a/tests/ref/vsynth/vsynth_lena-yuv4
+++ b/tests/ref/vsynth/vsynth_lena-yuv4
@@ -1,4 +1,4 @@
-1dcf2c21fe3ff1b57f9280a4fd550d14 *tests/data/fate/vsynth_lena-yuv4.avi
-7610048 tests/data/fate/vsynth_lena-yuv4.avi
+0686b8b4cbd3398f8b9f9d8c12922442 *tests/data/fate/vsynth_lena-yuv4.avi
+7610052 tests/data/fate/vsynth_lena-yuv4.avi
 dde5895817ad9d219f79a52d0bdfb001 *tests/data/fate/vsynth_lena-yuv4.out.rawvideo
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth/vsynth_lena-zlib b/tests/ref/vsynth/vsynth_lena-zlib
index 913d155..009bcad 100644
--- a/tests/ref/vsynth/vsynth_lena-zlib
+++ b/tests/ref/vsynth/vsynth_lena-zlib
@@ -1,4 +1,4 @@
-f2c6b3c88f07f0ed08dd25ca654854fb *tests/data/fate/vsynth_lena-zlib.avi
-12517176 tests/data/fate/vsynth_lena-zlib.avi
+abbfccc551b173a357024d8392de21dd *tests/data/fate/vsynth_lena-zlib.avi
+12517180 tests/data/fate/vsynth_lena-zlib.avi
 98d0e2854731472c5bf13d8638502d0a *tests/data/fate/vsynth_lena-zlib.out.rawvideo
 stddev:    1.26 PSNR: 46.10 MAXDIFF:   13 bytes:  7603200/  7603200
diff --git a/tests/utils.c b/tests/utils.c
index dde6e03..f244104 100644
--- a/tests/utils.c
+++ b/tests/utils.c
@@ -25,7 +25,7 @@
 
 #define SCALEBITS 8
 #define ONE_HALF  (1 << (SCALEBITS - 1))
-#define FIX(x)    ((int) ((x) * (1L << SCALEBITS) + 0.5))
+#define FIX(x)    ((int) ((x) * (1 << SCALEBITS) + 0.5))
 
 #define err_if(expr) do {                                              \
     if (expr) {                                                        \
diff --git a/tools/coverity.c b/tools/coverity.c
new file mode 100644
index 0000000..80fc1c2
--- /dev/null
+++ b/tools/coverity.c
@@ -0,0 +1,42 @@
+/* Coverity Scan model
+*
+* Copyright (C) 2014 Red Hat, Inc.
+*
+* Authors:
+* Markus Armbruster <armbru@redhat.com>
+* Paolo Bonzini <pbonzini@redhat.com>
+*
+* This work is licensed under the terms of the GNU GPL, version 2 or, at your
+* option, any later version. See the COPYING file in the top-level directory.
+*/
+/*
+* This is the source code for our Coverity user model file. The
+* purpose of user models is to increase scanning accuracy by explaining
+* code Coverity can't see (out of tree libraries) or doesn't
+* sufficiently understand. Better accuracy means both fewer false
+* positives and more true defects. Memory leaks in particular.
+*
+* - A model file can't import any header files. Some built-in primitives are
+* available but not wchar_t, NULL etc.
+* - Modeling doesn't need full structs and typedefs. Rudimentary structs
+* and similar types are sufficient.
+* - An uninitialized local variable signifies that the variable could be
+* any value.
+*
+* The model file must be uploaded by an admin in the analysis settings of
+* https://scan.coverity.com/projects/54
+*
+* above text is based on https://github.com/qemu/qemu/blob/master/scripts/coverity-model.c
+*/
+
+#define NULL (void *)0
+
+// Based on https://scan.coverity.com/models
+void *av_malloc(size_t size) {
+    int has_memory;
+    __coverity_negative_sink__(size);
+    if(has_memory)
+        return __coverity_alloc__(size);
+    else
+        return 0;
+}
diff --git a/tools/crypto_bench.c b/tools/crypto_bench.c
index 5e56d12..79629bc 100644
--- a/tools/crypto_bench.c
+++ b/tools/crypto_bench.c
@@ -77,6 +77,7 @@
 #include "libavutil/aes.h"
 #include "libavutil/camellia.h"
 #include "libavutil/cast5.h"
+#include "libavutil/twofish.h"
 
 #define IMPL_USE_lavu IMPL_USE
 
@@ -133,6 +134,15 @@
     av_cast5_crypt(cast, output, input, size >> 3, 0);
 }
 
+static void run_lavu_twofish(uint8_t *output,
+                              const uint8_t *input, unsigned size)
+{
+    static struct AVTWOFISH *twofish;
+    if (!twofish && !(twofish = av_twofish_alloc()))
+        fatal_error("out of memory");
+    av_twofish_init(twofish, hardcoded_key, 128);
+    av_twofish_crypt(twofish, output, input, size >> 4, NULL, 0);
+}
 /***************************************************************************
  * crypto: OpenSSL's libcrypto
  ***************************************************************************/
@@ -250,6 +260,16 @@
     gcry_cipher_encrypt(cast, output, size, input, size);
 }
 
+static void run_gcrypt_twofish(uint8_t *output,
+                                const uint8_t *input, unsigned size)
+{
+    static gcry_cipher_hd_t twofish;
+    if (!twofish)
+        gcry_cipher_open(&twofish, GCRY_CIPHER_TWOFISH128, GCRY_CIPHER_MODE_ECB, 0);
+    gcry_cipher_setkey(twofish, hardcoded_key, 16);
+    gcry_cipher_encrypt(twofish, output, size, input, size);
+}
+
 #define IMPL_USE_gcrypt(...) IMPL_USE(__VA_ARGS__)
 #else
 #define IMPL_USE_gcrypt(...) /* ignore */
@@ -314,6 +334,19 @@
         cast5_ecb_encrypt(input + i, output + i, &cast);
 }
 
+static void run_tomcrypt_twofish(uint8_t *output,
+                                const uint8_t *input, unsigned size)
+{
+    symmetric_key twofish;
+    unsigned i;
+
+    twofish_setup(hardcoded_key, 16, 0, &twofish);
+    size -= 15;
+    for (i = 0; i < size; i += 16)
+        twofish_ecb_encrypt(input + i, output + i, &twofish);
+}
+
+
 #define IMPL_USE_tomcrypt(...) IMPL_USE(__VA_ARGS__)
 #else
 #define IMPL_USE_tomcrypt(...) /* ignore */
@@ -398,6 +431,9 @@
     IMPL_ALL("AES-128",    aes128,    "crc:ff6bc888")
     IMPL_ALL("CAMELLIA",   camellia,  "crc:7abb59a7")
     IMPL_ALL("CAST-128",   cast128,   "crc:456aa584")
+    IMPL(lavu,     "TWOFISH", twofish, "crc:9edbd5c1")
+    IMPL(gcrypt,   "TWOFISH", twofish, "crc:9edbd5c1")
+    IMPL(tomcrypt, "TWOFISH", twofish, "crc:9edbd5c1")
 };
 
 int main(int argc, char **argv)
diff --git a/tools/graph2dot.c b/tools/graph2dot.c
index 964322d..5552b34 100644
--- a/tools/graph2dot.c
+++ b/tools/graph2dot.c
@@ -157,9 +157,17 @@
         struct line *line, *last_line, *first_line;
         char *p;
         last_line = first_line = av_malloc(sizeof(struct line));
+        if (!last_line) {
+            fprintf(stderr, "Memory allocation failure\n");
+            return 1;
+        }
 
         while (fgets(last_line->data, sizeof(last_line->data), infile)) {
             struct line *new_line = av_malloc(sizeof(struct line));
+            if (!new_line) {
+                fprintf(stderr, "Memory allocation failure\n");
+                return 1;
+            }
             count += strlen(last_line->data);
             last_line->next = new_line;
             last_line       = new_line;
@@ -167,6 +175,10 @@
         last_line->next = NULL;
 
         graph_string = av_malloc(count + 1);
+        if (!graph_string) {
+            fprintf(stderr, "Memory allocation failure\n");
+            return 1;
+        }
         p = graph_string;
         for (line = first_line; line->next; line = line->next) {
             unsigned int l = strlen(line->data);
diff --git a/tools/ismindex.c b/tools/ismindex.c
index 47a148c..8636c96 100644
--- a/tools/ismindex.c
+++ b/tools/ismindex.c
@@ -230,10 +230,12 @@
 static int64_t read_trun_duration(AVIOContext *in, int default_duration,
                                   int64_t end)
 {
-    int64_t ret = 0;
+    int64_t dts = 0;
     int64_t pos;
     int flags, i;
     int entries;
+    int64_t first_pts = 0;
+    int64_t max_pts = 0;
     avio_r8(in); /* version */
     flags = avio_rb24(in);
     if (default_duration <= 0 && !(flags & MOV_TRUN_SAMPLE_DURATION)) {
@@ -248,19 +250,23 @@
     pos = avio_tell(in);
     for (i = 0; i < entries && pos < end; i++) {
         int sample_duration = default_duration;
+        int64_t pts = dts;
         if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(in);
         if (flags & MOV_TRUN_SAMPLE_SIZE)     avio_rb32(in);
         if (flags & MOV_TRUN_SAMPLE_FLAGS)    avio_rb32(in);
-        if (flags & MOV_TRUN_SAMPLE_CTS)      avio_rb32(in);
+        if (flags & MOV_TRUN_SAMPLE_CTS)      pts += avio_rb32(in);
         if (sample_duration < 0) {
             fprintf(stderr, "Negative sample duration %d\n", sample_duration);
             return -1;
         }
-        ret += sample_duration;
+        if (i == 0)
+            first_pts = pts;
+        max_pts = FFMAX(max_pts, pts + sample_duration);
+        dts += sample_duration;
         pos = avio_tell(in);
     }
 
-    return ret;
+    return max_pts - first_pts;
 }
 
 static int64_t read_moof_duration(AVIOContext *in, int64_t offset)
diff --git a/tools/trasher.c b/tools/trasher.c
index aaa09f4..0b89cfe 100644
--- a/tools/trasher.c
+++ b/tools/trasher.c
@@ -30,6 +30,15 @@
     return state = state * 1664525 + 1013904223;
 }
 
+static void checked_seek(FILE *stream, int64_t offset, int whence)
+{
+    offset = fseek(stream, offset, whence);
+    if (offset < 0) {
+        fprintf(stderr, "seek failed\n");
+        exit(1);
+    }
+}
+
 int main(int argc, char **argv)
 {
     FILE *f;
@@ -49,17 +58,14 @@
     maxburst = atoi(argv[3]);
     state    = atoi(argv[4]);
 
-    fseek(f, 0, SEEK_END);
+    checked_seek(f, 0, SEEK_END);
     length = ftell(f);
-    fseek(f, 0, SEEK_SET);
+    checked_seek(f, 0, SEEK_SET);
 
     while (count--) {
         int burst = 1 + ran() * (uint64_t) (abs(maxburst) - 1) / UINT32_MAX;
         int pos   = ran() * (uint64_t) length / UINT32_MAX;
-        if (fseek(f, pos, SEEK_SET) < 0) {
-            fprintf(stderr, "seek failed\n");
-            return 1;
-        }
+        checked_seek(f, pos, SEEK_SET);
 
         if (maxburst < 0)
             burst = -maxburst;